@milaboratories/pl-middle-layer 2.10.0 → 2.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/middle_layer/build_stamp.cjs +1 -1
- package/dist/middle_layer/build_stamp.js +1 -1
- package/dist/middle_layer/middle_layer.cjs +4 -3
- package/dist/middle_layer/middle_layer.cjs.map +1 -1
- package/dist/middle_layer/middle_layer.d.ts.map +1 -1
- package/dist/middle_layer/middle_layer.js +3 -2
- package/dist/middle_layer/middle_layer.js.map +1 -1
- package/dist/middle_layer/project.cjs +6 -21
- package/dist/middle_layer/project.cjs.map +1 -1
- package/dist/middle_layer/project.d.ts +1 -1
- package/dist/middle_layer/project.d.ts.map +1 -1
- package/dist/middle_layer/project.js +5 -19
- package/dist/middle_layer/project.js.map +1 -1
- package/dist/model/block_pack_spec.cjs.map +1 -1
- package/dist/model/block_pack_spec.d.ts +3 -3
- package/dist/model/block_pack_spec.d.ts.map +1 -1
- package/dist/model/block_pack_spec.js.map +1 -1
- package/dist/model/template_spec.d.ts +18 -0
- package/dist/model/template_spec.d.ts.map +1 -1
- package/dist/mutator/block-pack/block_pack.cjs +89 -2
- package/dist/mutator/block-pack/block_pack.cjs.map +1 -1
- package/dist/mutator/block-pack/block_pack.d.ts +16 -0
- package/dist/mutator/block-pack/block_pack.d.ts.map +1 -1
- package/dist/mutator/block-pack/block_pack.js +90 -4
- package/dist/mutator/block-pack/block_pack.js.map +1 -1
- package/dist/mutator/block-pack/required_capabilities.cjs +16 -0
- package/dist/mutator/block-pack/required_capabilities.cjs.map +1 -1
- package/dist/mutator/block-pack/required_capabilities.js +16 -1
- package/dist/mutator/block-pack/required_capabilities.js.map +1 -1
- package/dist/mutator/template/template_cache.cjs +8 -1
- package/dist/mutator/template/template_cache.cjs.map +1 -1
- package/dist/mutator/template/template_cache.d.ts +7 -3
- package/dist/mutator/template/template_cache.d.ts.map +1 -1
- package/dist/mutator/template/template_cache.js +8 -1
- package/dist/mutator/template/template_cache.js.map +1 -1
- package/package.json +2 -2
- package/src/middle_layer/middle_layer.ts +4 -2
- package/src/middle_layer/project.ts +7 -27
- package/src/model/block_pack_spec.ts +3 -2
- package/src/model/template_spec.ts +21 -0
- package/src/mutator/block-pack/block_pack.test.ts +10 -1
- package/src/mutator/block-pack/block_pack.ts +102 -2
- package/src/mutator/block-pack/block_pack_load.test.ts +52 -0
- package/src/mutator/block-pack/required_capabilities.ts +25 -0
- package/src/mutator/project-v3.test.ts +27 -16
- package/src/mutator/template/template_cache.ts +26 -3
- package/src/test/block_packs.ts +12 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"block_pack.cjs","names":["z","Code","LRUCache","request","resolveDevPacket","fs","loadPackDescription","fileURLToPath","loadPackDescriptionFromManifest","RegistryV1","assertNever","WorkerManager","requiredCapabilitiesFromTemplate","getDevV2PacketMtime","getFromPackV2Mtime","field","loadTemplate","createFrontend"],"sources":["../../../src/mutator/block-pack/block_pack.ts"],"sourcesContent":["import type { AnyResourceRef, PlTransaction, ResourceType } from \"@milaboratories/pl-client\";\nimport { field } from \"@milaboratories/pl-client\";\nimport { loadTemplate } from \"../template/template_loading\";\nimport type { BlockPackExplicit, BlockPackSpecAny, BlockPackSpecPrepared } from \"../../model\";\nimport type { Signer } from \"@milaboratories/ts-helpers\";\nimport { assertNever } from \"@milaboratories/ts-helpers\";\nimport type { Branded } from \"@milaboratories/pl-model-common\";\nimport fs from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Dispatcher } from \"undici\";\nimport { request } from \"undici\";\nimport { createFrontend } from \"./frontend\";\nimport { requiredCapabilitiesFromTemplate } from \"./required_capabilities\";\nimport type { BlockConfigContainer } from \"@platforma-sdk/model\";\nimport { Code } from \"@platforma-sdk/model\";\nimport {\n loadPackDescription,\n loadPackDescriptionFromManifest,\n RegistryV1,\n} from \"@platforma-sdk/block-tools\";\nimport type { BlockPackInfo } from \"../../model/block_pack\";\nimport { resolveDevPacket } from \"../../dev_env\";\nimport { getDevV2PacketMtime, getFromPackV2Mtime } from \"../../block_registry\";\nimport type { V2RegistryProvider } from \"../../block_registry/registry-v2-provider\";\nimport { LRUCache } from \"lru-cache\";\nimport canonicalize from \"canonicalize\";\nimport type { BlockPackSpec } from \"@milaboratories/pl-model-middle-layer\";\nimport { WorkerManager } from \"../../worker/WorkerManager\";\nimport { z } from \"zod\";\n\ntype PreparedCacheKey = Branded<string, \"PreparedCacheKey\">;\n\nexport const BlockPackCustomType: ResourceType = { name: \"BlockPackCustom\", version: \"1\" };\nexport const BlockPackTemplateField = \"template\";\nexport const BlockPackFrontendField = \"frontend\";\n\n/** Ensure trailing slash */\nfunction tSlash(str: string): string {\n if (str.endsWith(\"/\")) return str;\n else return `${str}/`;\n}\n\nfunction parseStringConfig(configContent: string): BlockConfigContainer {\n const res = z.record(z.string(), z.unknown()).safeParse(JSON.parse(configContent));\n\n if (!res.success) {\n throw new Error(\"Invalid config content\");\n }\n\n if (!Code.safeParse(res.data.code).success) {\n throw new Error(\"parseStringConfig:No code bundle\");\n }\n\n return res.data as BlockConfigContainer;\n}\n\nfunction parseBufferConfig(buffer: ArrayBuffer): BlockConfigContainer {\n return parseStringConfig(Buffer.from(buffer).toString(\"utf8\"));\n}\n\nexport class BlockPackPreparer {\n constructor(\n private readonly v2RegistryProvider: V2RegistryProvider,\n private readonly signer: Signer,\n private readonly http?: Dispatcher,\n ) {}\n\n private readonly remoteContentCache = new LRUCache<string, ArrayBuffer>({\n max: 500,\n maxSize: 128 * 1024 * 1024,\n fetchMethod: async (key) => {\n const httpOptions = this.http !== undefined ? { dispatcher: this.http } : {};\n return await (await request(key, httpOptions)).body.arrayBuffer();\n },\n sizeCalculation: (value) => value.byteLength,\n });\n\n /** Cache of prepared block packs for registry specs (immutable by version). */\n private readonly preparedCache = new LRUCache<PreparedCacheKey, BlockPackSpecPrepared>({\n max: 50,\n });\n\n public async getBlockConfigContainer(spec: BlockPackSpecAny): Promise<BlockConfigContainer> {\n switch (spec.type) {\n case \"explicit\":\n return spec.config;\n\n case \"prepared\":\n return spec.config;\n\n case \"dev-v1\": {\n const devPaths = await resolveDevPacket(spec.folder, false);\n const configContent = await fs.promises.readFile(devPaths.config, { encoding: \"utf-8\" });\n return JSON.parse(configContent);\n }\n\n case \"dev-v2\": {\n const description = await loadPackDescription(spec.folder);\n const configContent = await fs.promises.readFile(description.components.model.file, {\n encoding: \"utf-8\",\n });\n return parseStringConfig(configContent);\n }\n\n case \"from-pack-v2\": {\n // packUrl is a file: URL (the facade emits URLs, not paths); convert at\n // this Node boundary before touching the filesystem.\n const packDir = fileURLToPath(spec.packUrl);\n const description = await loadPackDescriptionFromManifest(packDir);\n const configContent = await fs.promises.readFile(description.components.model.file, {\n encoding: \"utf-8\",\n });\n return parseStringConfig(configContent);\n }\n\n case \"from-registry-v1\": {\n const urlPrefix = `${tSlash(spec.registryUrl)}${RegistryV1.packageContentPrefix({ organization: spec.id.organization, package: spec.id.name, version: spec.id.version })}`;\n\n const configResponse = await this.remoteContentCache.forceFetch(`${urlPrefix}/config.json`);\n return JSON.parse(Buffer.from(configResponse).toString(\"utf8\"));\n }\n\n case \"from-registry-v2\": {\n const registry = this.v2RegistryProvider.getRegistry(spec.registryUrl);\n const components = await registry.getComponents(spec.id);\n const configResponse = await this.remoteContentCache.forceFetch(components.model.url);\n return parseBufferConfig(configResponse);\n }\n\n default:\n return assertNever(spec);\n }\n }\n\n /** Returns a stable cache key for registry specs (immutable by version). Dev specs return undefined. */\n private specKey(spec: BlockPackSpecAny): PreparedCacheKey | undefined {\n switch (spec.type) {\n case \"from-registry-v1\":\n return `v1:${spec.registryUrl}:${spec.id.organization}:${spec.id.name}:${spec.id.version}` as PreparedCacheKey;\n case \"from-registry-v2\":\n return `v2:${spec.registryUrl}:${canonicalize(spec.id)}` as PreparedCacheKey;\n default:\n return undefined; // dev, explicit, prepared — not cacheable\n }\n }\n\n public async prepare(spec: BlockPackSpecAny): Promise<BlockPackSpecPrepared> {\n if (spec.type === \"prepared\") {\n return spec;\n }\n\n // Check prepare cache for registry specs\n const key = this.specKey(spec);\n if (key) {\n const cached = this.preparedCache.get(key);\n if (cached) return cached;\n }\n\n const explicit = await this.prepareWithoutUnpacking(spec);\n\n await using workerManager = new WorkerManager();\n\n const parsed = await workerManager.process(\"parseTemplate\", explicit.template.content);\n\n const result: BlockPackSpecPrepared = {\n ...explicit,\n type: \"prepared\",\n template: {\n type: \"prepared\",\n data: parsed,\n },\n requiredCapabilities: requiredCapabilitiesFromTemplate(parsed),\n };\n\n if (key) {\n this.preparedCache.set(key, result);\n }\n\n return result;\n }\n\n private async prepareWithoutUnpacking(\n spec: BlockPackExplicit | BlockPackSpec,\n ): Promise<BlockPackExplicit> {\n switch (spec.type) {\n case \"explicit\":\n return spec;\n\n case \"dev-v1\": {\n const devPaths = await resolveDevPacket(spec.folder, false);\n\n // template\n const templateContent = await fs.promises.readFile(devPaths.workflow);\n\n // config\n const config = JSON.parse(await fs.promises.readFile(devPaths.config, \"utf-8\"));\n\n // frontend\n const frontendPath = devPaths.ui;\n\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: templateContent,\n },\n config,\n frontend: {\n type: \"local\",\n path: frontendPath,\n signature: this.signer.sign(frontendPath),\n },\n source: spec,\n };\n }\n\n case \"dev-v2\": {\n const description = await loadPackDescription(spec.folder);\n const config = parseStringConfig(\n await fs.promises.readFile(description.components.model.file, {\n encoding: \"utf-8\",\n }),\n );\n const workflowContent = await fs.promises.readFile(\n description.components.workflow.main.file,\n );\n const frontendPath = description.components.ui.folder;\n const source = { ...spec };\n if (spec.mtime === undefined)\n // if absent, calculating the mtime here, so the block will correctly show whether it can be updated\n source.mtime = await getDevV2PacketMtime(description);\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: workflowContent,\n },\n config,\n frontend: {\n type: \"local\",\n path: frontendPath,\n signature: this.signer.sign(frontendPath),\n },\n source,\n };\n }\n\n case \"from-pack-v2\": {\n // packUrl is a file: URL (the facade emits URLs, not paths); convert at\n // this Node boundary before touching the filesystem.\n const packDir = fileURLToPath(spec.packUrl);\n const description = await loadPackDescriptionFromManifest(packDir);\n const config = parseStringConfig(\n await fs.promises.readFile(description.components.model.file, {\n encoding: \"utf-8\",\n }),\n );\n const workflowContent = await fs.promises.readFile(\n description.components.workflow.main.file,\n );\n // UI ships as ui.tgz inside block-pack/; its absolute path is carried\n // in the ui folder slot. The tarball is unpacked lazily at serve-time by\n // the download driver (local-tgz frontend), not eagerly here — so it\n // inherits the driver's usage-tracking and space recycling.\n const uiTgzPath = description.components.ui.folder;\n const source = { ...spec };\n let mtime = spec.mtime;\n if (mtime === undefined) {\n // No explicit mtime: derive one so the frontend cache key invalidates\n // when the block changes.\n mtime = await getFromPackV2Mtime(packDir, uiTgzPath);\n source.mtime = mtime;\n }\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: workflowContent,\n },\n config,\n frontend: {\n type: \"local-tgz\",\n path: uiTgzPath,\n mtime,\n signature: this.signer.sign(`${uiTgzPath}:${mtime}`),\n },\n source,\n };\n }\n\n case \"from-registry-v1\": {\n const urlPrefix = `${tSlash(spec.registryUrl)}${RegistryV1.packageContentPrefix({ organization: spec.id.organization, package: spec.id.name, version: spec.id.version })}`;\n\n const templateUrl = `${urlPrefix}/template.plj.gz`;\n // template\n const templateResponse = await this.remoteContentCache.forceFetch(templateUrl);\n const templateContent = new Uint8Array(templateResponse);\n\n // config\n const configResponse = await this.remoteContentCache.forceFetch(`${urlPrefix}/config.json`);\n const config = JSON.parse(\n Buffer.from(configResponse).toString(\"utf8\"),\n ) as BlockConfigContainer;\n\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: templateContent,\n },\n config,\n frontend: {\n type: \"url\",\n url: `${urlPrefix}/frontend.tgz`,\n },\n source: spec,\n };\n }\n\n case \"from-registry-v2\": {\n const registry = this.v2RegistryProvider.getRegistry(spec.registryUrl);\n const components = await registry.getComponents(spec.id);\n const getModel = async () =>\n parseBufferConfig(await this.remoteContentCache.forceFetch(components.model.url));\n const getWorkflow = async () =>\n await this.remoteContentCache.forceFetch(components.workflow.main.url);\n\n const [model, workflow] = await Promise.all([getModel(), getWorkflow()]);\n const workflowContent = Buffer.from(workflow);\n\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: workflowContent,\n },\n config: model,\n frontend: {\n type: \"url\",\n url: components.ui.url,\n },\n source: spec,\n };\n }\n\n default:\n return assertNever(spec);\n }\n }\n}\n\nfunction createCustomBlockPack(tx: PlTransaction, spec: BlockPackSpecPrepared): AnyResourceRef {\n const blockPackInfo: BlockPackInfo = { config: spec.config, source: spec.source };\n const bp = tx.createStruct(BlockPackCustomType, JSON.stringify(blockPackInfo));\n tx.createField(field(bp, BlockPackTemplateField), \"Input\", loadTemplate(tx, spec.template));\n tx.createField(field(bp, BlockPackFrontendField), \"Input\", createFrontend(tx, spec.frontend));\n tx.lock(bp);\n\n return bp;\n}\n\nexport function createBlockPack(tx: PlTransaction, spec: BlockPackSpecPrepared): AnyResourceRef {\n switch (spec.type) {\n case \"prepared\":\n return createCustomBlockPack(tx, spec);\n default:\n return assertNever(spec.type);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,sBAAoC;CAAE,MAAM;CAAmB,SAAS;AAAI;AACzF,MAAa,yBAAyB;AACtC,MAAa,yBAAyB;;AAGtC,SAAS,OAAO,KAAqB;CACnC,IAAI,IAAI,SAAS,GAAG,GAAG,OAAO;MACzB,OAAO,GAAG,IAAI;AACrB;AAEA,SAAS,kBAAkB,eAA6C;CACtE,MAAM,MAAMA,IAAAA,EAAE,OAAOA,IAAAA,EAAE,OAAO,GAAGA,IAAAA,EAAE,QAAQ,CAAC,CAAC,CAAC,UAAU,KAAK,MAAM,aAAa,CAAC;CAEjF,IAAI,CAAC,IAAI,SACP,MAAM,IAAI,MAAM,wBAAwB;C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sBAAsB,GAAG,SAASE,iBAAAA,eAAe,IAAI,KAAK,QAAQ,CAAC;CAC5F,GAAG,KAAK,EAAE;CAEV,OAAO;AACT;AAEA,SAAgB,gBAAgB,IAAmB,MAA6C;CAC9F,QAAQ,KAAK,MAAb;EACE,KAAK,YACH,OAAO,sBAAsB,IAAI,IAAI;EACvC,SACE,QAAA,GAAOP,2BAAAA,YAAAA,CAAY,KAAK,IAAI;CAChC;AACF"}
|
|
1
|
+
{"version":3,"file":"block_pack.cjs","names":["z","Code","LRUCache","request","resolveDevPacket","fs","loadPackDescription","fileURLToPath","loadPackDescriptionFromManifest","RegistryV1","assertNever","WorkerManager","requiredCapabilitiesFromTemplate","notEmpty","getDevV2PacketMtime","getFromPackV2Mtime","createHash","field","loadTemplate","createFrontend"],"sources":["../../../src/mutator/block-pack/block_pack.ts"],"sourcesContent":["import type { AnyResourceRef, PlTransaction, ResourceType } from \"@milaboratories/pl-client\";\nimport { field } from \"@milaboratories/pl-client\";\nimport { loadTemplate } from \"../template/template_loading\";\nimport type { BlockPackExplicit, BlockPackSpecAny, BlockPackSpecPrepared } from \"../../model\";\nimport type { Signer } from \"@milaboratories/ts-helpers\";\nimport { assertNever, notEmpty } from \"@milaboratories/ts-helpers\";\nimport type { Branded } from \"@milaboratories/pl-model-common\";\nimport fs from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Dispatcher } from \"undici\";\nimport { request } from \"undici\";\nimport { createFrontend } from \"./frontend\";\nimport { requiredCapabilitiesFromTemplate } from \"./required_capabilities\";\nimport type { BlockConfigContainer } from \"@platforma-sdk/model\";\nimport { Code } from \"@platforma-sdk/model\";\nimport {\n loadPackDescription,\n loadPackDescriptionFromManifest,\n RegistryV1,\n} from \"@platforma-sdk/block-tools\";\nimport type { BlockPackInfo } from \"../../model/block_pack\";\nimport type { InstallablePackTemplate, PreparedTemplate } from \"../../model/template_spec\";\nimport { resolveDevPacket } from \"../../dev_env\";\nimport { getDevV2PacketMtime, getFromPackV2Mtime } from \"../../block_registry\";\nimport type { V2RegistryProvider } from \"../../block_registry/registry-v2-provider\";\nimport { LRUCache } from \"lru-cache\";\nimport canonicalize from \"canonicalize\";\nimport type { BlockPackFromRegistryV2, BlockPackSpec } from \"@milaboratories/pl-model-middle-layer\";\nimport { WorkerManager } from \"../../worker/WorkerManager\";\nimport { z } from \"zod\";\n\ntype PreparedCacheKey = Branded<string, \"PreparedCacheKey\">;\n\nexport const BlockPackCustomType: ResourceType = { name: \"BlockPackCustom\", version: \"1\" };\nexport const BlockPackTemplateField = \"template\";\nexport const BlockPackFrontendField = \"frontend\";\n\n/** Ensure trailing slash */\nfunction tSlash(str: string): string {\n if (str.endsWith(\"/\")) return str;\n else return `${str}/`;\n}\n\nfunction parseStringConfig(configContent: string): BlockConfigContainer {\n const res = z.record(z.string(), z.unknown()).safeParse(JSON.parse(configContent));\n\n if (!res.success) {\n throw new Error(\"Invalid config content\");\n }\n\n if (!Code.safeParse(res.data.code).success) {\n throw new Error(\"parseStringConfig:No code bundle\");\n }\n\n return res.data as BlockConfigContainer;\n}\n\nfunction parseBufferConfig(buffer: ArrayBuffer): BlockConfigContainer {\n return parseStringConfig(Buffer.from(buffer).toString(\"utf8\"));\n}\n\nexport class BlockPackPreparer {\n constructor(\n private readonly v2RegistryProvider: V2RegistryProvider,\n private readonly signer: Signer,\n private readonly http?: Dispatcher,\n ) {}\n\n private readonly remoteContentCache = new LRUCache<string, ArrayBuffer>({\n max: 500,\n maxSize: 128 * 1024 * 1024,\n fetchMethod: async (key) => {\n const httpOptions = this.http !== undefined ? { dispatcher: this.http } : {};\n return await (await request(key, httpOptions)).body.arrayBuffer();\n },\n sizeCalculation: (value) => value.byteLength,\n });\n\n /** Parsed packs by sha256, so adding a block again does not parse its workflow again. */\n private readonly loadedPackCache = new LRUCache<string, LoadedPack>({ max: 50 });\n\n /** Cache of prepared block packs for registry specs (immutable by version). */\n private readonly preparedCache = new LRUCache<PreparedCacheKey, BlockPackSpecPrepared>({\n max: 50,\n });\n\n public async getBlockConfigContainer(spec: BlockPackSpecAny): Promise<BlockConfigContainer> {\n switch (spec.type) {\n case \"explicit\":\n return spec.config;\n\n case \"prepared\":\n return spec.config;\n\n case \"dev-v1\": {\n const devPaths = await resolveDevPacket(spec.folder, false);\n const configContent = await fs.promises.readFile(devPaths.config, { encoding: \"utf-8\" });\n return JSON.parse(configContent);\n }\n\n case \"dev-v2\": {\n const description = await loadPackDescription(spec.folder);\n const configContent = await fs.promises.readFile(description.components.model.file, {\n encoding: \"utf-8\",\n });\n return parseStringConfig(configContent);\n }\n\n case \"from-pack-v2\": {\n // packUrl is a file: URL (the facade emits URLs, not paths); convert at\n // this Node boundary before touching the filesystem.\n const packDir = fileURLToPath(spec.packUrl);\n const description = await loadPackDescriptionFromManifest(packDir);\n const configContent = await fs.promises.readFile(description.components.model.file, {\n encoding: \"utf-8\",\n });\n return parseStringConfig(configContent);\n }\n\n case \"from-registry-v1\": {\n const urlPrefix = `${tSlash(spec.registryUrl)}${RegistryV1.packageContentPrefix({ organization: spec.id.organization, package: spec.id.name, version: spec.id.version })}`;\n\n const configResponse = await this.remoteContentCache.forceFetch(`${urlPrefix}/config.json`);\n return JSON.parse(Buffer.from(configResponse).toString(\"utf8\"));\n }\n\n case \"from-registry-v2\": {\n const registry = this.v2RegistryProvider.getRegistry(spec.registryUrl);\n const components = await registry.getComponents(spec.id);\n const configResponse = await this.remoteContentCache.forceFetch(components.model.url);\n return parseBufferConfig(configResponse);\n }\n\n default:\n return assertNever(spec);\n }\n }\n\n /** Returns a stable cache key for registry specs (immutable by version). Dev specs return undefined. */\n private specKey(spec: BlockPackSpecAny): PreparedCacheKey | undefined {\n switch (spec.type) {\n case \"from-registry-v1\":\n return `v1:${spec.registryUrl}:${spec.id.organization}:${spec.id.name}:${spec.id.version}` as PreparedCacheKey;\n case \"from-registry-v2\":\n return `v2:${spec.registryUrl}:${canonicalize(spec.id)}` as PreparedCacheKey;\n default:\n return undefined; // dev, explicit, prepared — not cacheable\n }\n }\n\n public async prepare(spec: BlockPackSpecAny): Promise<BlockPackSpecPrepared> {\n if (spec.type === \"prepared\") {\n return spec;\n }\n\n // Check prepare cache for registry specs\n const key = this.specKey(spec);\n if (key) {\n const cached = this.preparedCache.get(key);\n if (cached) return cached;\n }\n\n const registryPack =\n spec.type === \"from-registry-v2\" ? await this.prepareRegistryPack(spec) : undefined;\n if (registryPack !== undefined) {\n if (key) this.preparedCache.set(key, registryPack);\n return registryPack;\n }\n\n const explicit = await this.prepareWithoutUnpacking(spec);\n\n // Local dev packs are parsed when installed, which also checks their required capabilities.\n const { localPath, content } = explicit.template;\n if (localPath !== undefined)\n return {\n ...explicit,\n type: \"prepared\",\n template: { type: \"local-pack\", path: localPath, sha256: packSha256(content) },\n };\n\n await using workerManager = new WorkerManager();\n\n const parsed = await workerManager.process(\"parseTemplate\", explicit.template.content);\n\n const result: BlockPackSpecPrepared = {\n ...explicit,\n type: \"prepared\",\n template: {\n type: \"prepared\",\n data: parsed,\n },\n requiredCapabilities: requiredCapabilitiesFromTemplate(parsed),\n };\n\n if (key) {\n this.preparedCache.set(key, result);\n }\n\n return result;\n }\n\n /**\n * Prepares a v2 registry block from its manifest alone, without downloading the workflow.\n * Undefined when the manifest does not list the workflow pack's sha256.\n */\n private async prepareRegistryPack(\n spec: BlockPackFromRegistryV2,\n ): Promise<BlockPackSpecPrepared | undefined> {\n const registry = this.v2RegistryProvider.getRegistry(spec.registryUrl);\n const [manifest, components] = await Promise.all([\n registry.getManifest(spec.id),\n registry.getComponents(spec.id),\n ]);\n const workflowPath = manifest.description.components.workflow.main.path;\n const workflowFile = manifest.files.find((f) => f.name === workflowPath);\n if (workflowFile === undefined) return undefined;\n\n return {\n type: \"prepared\",\n template: {\n type: \"registry-pack\",\n url: components.workflow.main.url,\n sha256: workflowFile.sha256.toLowerCase(),\n },\n config: parseBufferConfig(await this.remoteContentCache.forceFetch(components.model.url)),\n frontend: { type: \"url\", url: components.ui.url },\n source: spec,\n requiredCapabilities: manifest.description.meta.requiredCapabilities,\n };\n }\n\n /** Downloads or reads a pack, checks its sha256 and parses it. */\n public async loadPack(template: InstallablePackTemplate): Promise<LoadedPack> {\n let content: Uint8Array | undefined;\n if (template.type === \"local-pack\") {\n // A rebuild after prepare would pair this config with another build's workflow.\n content = await fs.promises.readFile(template.path);\n if (packSha256(content) !== template.sha256)\n throw new Error(\n `workflow pack ${template.path} changed after the block was prepared; add the block again`,\n );\n }\n\n const cached = this.loadedPackCache.get(template.sha256);\n if (cached !== undefined) return cached;\n\n if (content === undefined && template.type === \"registry-pack\") {\n content = new Uint8Array(await this.remoteContentCache.forceFetch(template.url));\n const sha256 = packSha256(content);\n if (sha256 !== template.sha256) {\n // Do not keep a broken download for the next attempt.\n this.remoteContentCache.delete(template.url);\n throw new Error(\n `workflow pack ${template.url} has sha256 ${sha256}, expected ${template.sha256}`,\n );\n }\n }\n\n await using workerManager = new WorkerManager();\n const parsed = await workerManager.process(\"parseTemplate\", notEmpty(content));\n const loaded: LoadedPack = {\n template: { type: \"prepared\", data: parsed },\n requiredCapabilities: requiredCapabilitiesFromTemplate(parsed),\n };\n this.loadedPackCache.set(template.sha256, loaded);\n return loaded;\n }\n\n private async prepareWithoutUnpacking(\n spec: BlockPackExplicit | BlockPackSpec,\n ): Promise<BlockPackExplicit> {\n switch (spec.type) {\n case \"explicit\":\n return spec;\n\n case \"dev-v1\": {\n const devPaths = await resolveDevPacket(spec.folder, false);\n\n // template\n const templateContent = await fs.promises.readFile(devPaths.workflow);\n\n // config\n const config = JSON.parse(await fs.promises.readFile(devPaths.config, \"utf-8\"));\n\n // frontend\n const frontendPath = devPaths.ui;\n\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: templateContent,\n },\n config,\n frontend: {\n type: \"local\",\n path: frontendPath,\n signature: this.signer.sign(frontendPath),\n },\n source: spec,\n };\n }\n\n case \"dev-v2\": {\n const description = await loadPackDescription(spec.folder);\n const config = parseStringConfig(\n await fs.promises.readFile(description.components.model.file, {\n encoding: \"utf-8\",\n }),\n );\n const workflowContent = await fs.promises.readFile(\n description.components.workflow.main.file,\n );\n const frontendPath = description.components.ui.folder;\n const source = { ...spec };\n if (spec.mtime === undefined)\n // if absent, calculating the mtime here, so the block will correctly show whether it can be updated\n source.mtime = await getDevV2PacketMtime(description);\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: workflowContent,\n localPath: description.components.workflow.main.file,\n },\n config,\n frontend: {\n type: \"local\",\n path: frontendPath,\n signature: this.signer.sign(frontendPath),\n },\n source,\n };\n }\n\n case \"from-pack-v2\": {\n // packUrl is a file: URL (the facade emits URLs, not paths); convert at\n // this Node boundary before touching the filesystem.\n const packDir = fileURLToPath(spec.packUrl);\n const description = await loadPackDescriptionFromManifest(packDir);\n const config = parseStringConfig(\n await fs.promises.readFile(description.components.model.file, {\n encoding: \"utf-8\",\n }),\n );\n const workflowContent = await fs.promises.readFile(\n description.components.workflow.main.file,\n );\n // UI ships as ui.tgz inside block-pack/; its absolute path is carried\n // in the ui folder slot. The tarball is unpacked lazily at serve-time by\n // the download driver (local-tgz frontend), not eagerly here — so it\n // inherits the driver's usage-tracking and space recycling.\n const uiTgzPath = description.components.ui.folder;\n const source = { ...spec };\n let mtime = spec.mtime;\n if (mtime === undefined) {\n // No explicit mtime: derive one so the frontend cache key invalidates\n // when the block changes.\n mtime = await getFromPackV2Mtime(packDir, uiTgzPath);\n source.mtime = mtime;\n }\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: workflowContent,\n localPath: description.components.workflow.main.file,\n },\n config,\n frontend: {\n type: \"local-tgz\",\n path: uiTgzPath,\n mtime,\n signature: this.signer.sign(`${uiTgzPath}:${mtime}`),\n },\n source,\n };\n }\n\n case \"from-registry-v1\": {\n const urlPrefix = `${tSlash(spec.registryUrl)}${RegistryV1.packageContentPrefix({ organization: spec.id.organization, package: spec.id.name, version: spec.id.version })}`;\n\n const templateUrl = `${urlPrefix}/template.plj.gz`;\n // template\n const templateResponse = await this.remoteContentCache.forceFetch(templateUrl);\n const templateContent = new Uint8Array(templateResponse);\n\n // config\n const configResponse = await this.remoteContentCache.forceFetch(`${urlPrefix}/config.json`);\n const config = JSON.parse(\n Buffer.from(configResponse).toString(\"utf8\"),\n ) as BlockConfigContainer;\n\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: templateContent,\n },\n config,\n frontend: {\n type: \"url\",\n url: `${urlPrefix}/frontend.tgz`,\n },\n source: spec,\n };\n }\n\n case \"from-registry-v2\": {\n const registry = this.v2RegistryProvider.getRegistry(spec.registryUrl);\n const components = await registry.getComponents(spec.id);\n const getModel = async () =>\n parseBufferConfig(await this.remoteContentCache.forceFetch(components.model.url));\n const getWorkflow = async () =>\n await this.remoteContentCache.forceFetch(components.workflow.main.url);\n\n const [model, workflow] = await Promise.all([getModel(), getWorkflow()]);\n const workflowContent = Buffer.from(workflow);\n\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: workflowContent,\n },\n config: model,\n frontend: {\n type: \"url\",\n url: components.ui.url,\n },\n source: spec,\n };\n }\n\n default:\n return assertNever(spec);\n }\n }\n}\n\n/** A pack parsed on the client, with the capabilities it declares. */\ntype LoadedPack = { template: PreparedTemplate; requiredCapabilities?: string[] };\n\n/** Lowercase hex sha256 of a gzipped workflow pack, the key the backend installs it by. */\nexport function packSha256(content: Uint8Array): string {\n return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\nfunction createCustomBlockPack(tx: PlTransaction, spec: BlockPackSpecPrepared): AnyResourceRef {\n if (spec.template.type === \"registry-pack\" || spec.template.type === \"local-pack\")\n throw new Error(\"BUG: a pack must be installed by cacheBlockPackTemplate first\");\n const blockPackInfo: BlockPackInfo = { config: spec.config, source: spec.source };\n const bp = tx.createStruct(BlockPackCustomType, JSON.stringify(blockPackInfo));\n tx.createField(field(bp, BlockPackTemplateField), \"Input\", loadTemplate(tx, spec.template));\n tx.createField(field(bp, BlockPackFrontendField), \"Input\", createFrontend(tx, spec.frontend));\n tx.lock(bp);\n\n return bp;\n}\n\nexport function createBlockPack(tx: PlTransaction, spec: BlockPackSpecPrepared): AnyResourceRef {\n switch (spec.type) {\n case \"prepared\":\n return createCustomBlockPack(tx, spec);\n default:\n return assertNever(spec.type);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,sBAAoC;CAAE,MAAM;CAAmB,SAAS;AAAI;AACzF,MAAa,yBAAyB;AACtC,MAAa,yBAAyB;;AAGtC,SAAS,OAAO,KAAqB;CACnC,IAAI,IAAI,SAAS,GAAG,GAAG,OAAO;MACzB,OAAO,GAAG,IAAI;AACrB;AAEA,SAAS,kBAAkB,eAA6C;CACtE,MAAM,MAAMA,IAAAA,EAAE,OAAOA,IAAAA,EAAE,OAAO,GAAGA,IAAAA,EAAE,QAAQ,CAAC,CAAC,CAAC,UAAU,KAAK,MAAM,aAAa,CAAC;CAEjF,IAAI,CAAC,IAAI,SACP,MAAM,IAAI,MAAM,wBAAwB;CAG1C,IAAI,CAACC,qBAAAA,KAAK,UAAU,IAAI,KAAK,IAAI,CAAC,CAAC,SACjC,MAAM,IAAI,MAAM,kCAAkC;CAGpD,OAAO,IAAI;AACb;AAEA,SAAS,kBAAkB,QAA2C;CACpE,OAAO,kBAAkB,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC;AAC/D;AAEA,IAAa,oBAAb,MAA+B;CAEV;CACA;CACA;CAHnB,YACE,oBACA,QACA,MACA;EAHiB,KAAA,qBAAA;EACA,KAAA,SAAA;EACA,KAAA,OAAA;CAChB;CAEH,qBAAsC,IAAIC,UAAAA,SAA8B;EACtE,KAAK;EACL,SAAS;EACT,aAAa,OAAO,QAAQ;GAC1B,MAAM,cAAc,KAAK,SAAS,KAAA,IAAY,EAAE,YAAY,KAAK,KAAK,IAAI,CAAC;GAC3E,OAAO,OAAO,OAAA,GAAMC,OAAAA,QAAAA,CAAQ,KAAK,WAAW,EAAA,CAAG,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,OAAO,KAAK;AAC1D;AAEA,SAAS,sBAAsB,IAAmB,MAA6C;CAC7F,IAAI,KAAK,SAAS,SAAS,mBAAmB,KAAK,SAAS,SAAS,cACnE,MAAM,IAAI,MAAM,+DAA+D;CACjF,MAAM,gBAA+B;EAAE,QAAQ,KAAK;EAAQ,QAAQ,KAAK;CAAO;CAChF,MAAM,KAAK,GAAG,aAAa,qBAAqB,KAAK,UAAU,aAAa,CAAC;CAC7E,GAAG,aAAA,GAAYC,0BAAAA,MAAAA,CAAM,IAAI,sBAAsB,GAAG,SAASC,yBAAAA,aAAa,IAAI,KAAK,QAAQ,CAAC;CAC1F,GAAG,aAAA,GAAYD,0BAAAA,MAAAA,CAAM,IAAI,sBAAsB,GAAG,SAASE,iBAAAA,eAAe,IAAI,KAAK,QAAQ,CAAC;CAC5F,GAAG,KAAK,EAAE;CAEV,OAAO;AACT;AAEA,SAAgB,gBAAgB,IAAmB,MAA6C;CAC9F,QAAQ,KAAK,MAAb;EACE,KAAK,YACH,OAAO,sBAAsB,IAAI,IAAI;EACvC,SACE,QAAA,GAAOT,2BAAAA,YAAAA,CAAY,KAAK,IAAI;CAChC;AACF"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { V2RegistryProvider } from "../../block_registry/registry-v2-provider.js";
|
|
2
|
+
import { InstallablePackTemplate, PreparedTemplate } from "../../model/template_spec.js";
|
|
2
3
|
import { BlockPackSpecAny, BlockPackSpecPrepared } from "../../model/block_pack_spec.js";
|
|
3
4
|
import "../../model/index.js";
|
|
4
5
|
import { BlockConfigContainer } from "@platforma-sdk/model";
|
|
@@ -11,12 +12,27 @@ export declare class BlockPackPreparer {
|
|
|
11
12
|
private readonly http?;
|
|
12
13
|
constructor(v2RegistryProvider: V2RegistryProvider, signer: Signer, http?: Dispatcher | undefined);
|
|
13
14
|
private readonly remoteContentCache;
|
|
15
|
+
/** Parsed packs by sha256, so adding a block again does not parse its workflow again. */
|
|
16
|
+
private readonly loadedPackCache;
|
|
14
17
|
/** Cache of prepared block packs for registry specs (immutable by version). */
|
|
15
18
|
private readonly preparedCache;
|
|
16
19
|
getBlockConfigContainer(spec: BlockPackSpecAny): Promise<BlockConfigContainer>;
|
|
17
20
|
/** Returns a stable cache key for registry specs (immutable by version). Dev specs return undefined. */
|
|
18
21
|
private specKey;
|
|
19
22
|
prepare(spec: BlockPackSpecAny): Promise<BlockPackSpecPrepared>;
|
|
23
|
+
/**
|
|
24
|
+
* Prepares a v2 registry block from its manifest alone, without downloading the workflow.
|
|
25
|
+
* Undefined when the manifest does not list the workflow pack's sha256.
|
|
26
|
+
*/
|
|
27
|
+
private prepareRegistryPack;
|
|
28
|
+
/** Downloads or reads a pack, checks its sha256 and parses it. */
|
|
29
|
+
loadPack(template: InstallablePackTemplate): Promise<LoadedPack>;
|
|
20
30
|
private prepareWithoutUnpacking;
|
|
21
31
|
}
|
|
32
|
+
/** A pack parsed on the client, with the capabilities it declares. */
|
|
33
|
+
type LoadedPack = {
|
|
34
|
+
template: PreparedTemplate;
|
|
35
|
+
requiredCapabilities?: string[];
|
|
36
|
+
};
|
|
37
|
+
export {};
|
|
22
38
|
//# sourceMappingURL=block_pack.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"block_pack.d.ts","names":[],"sources":["../../../src/mutator/block-pack/block_pack.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"block_pack.d.ts","names":[],"sources":["../../../src/mutator/block-pack/block_pack.ts"],"mappings":";;;;;;;;qBA8Da;mBAEQ;mBACA;mBACA;EAHnB,YACmB,oBAAoB,oBACpB,QAAQ,QACR,OAAO;mBAGT;;mBAWA;;mBAGA;EAIJ,wBAAwB,MAAM,mBAAmB,QAAQ;;UAqD9D;EAWK,QAAQ,MAAM,mBAAmB,QAAQ;;;;;UAuDxC;;EA2BD,SAAS,UAAU,0BAA0B,QAAQ;UAoCpD;;;KA6KX;EAAe,UAAU;EAAkB"}
|
|
@@ -10,10 +10,11 @@ import { Code } from "@platforma-sdk/model";
|
|
|
10
10
|
import { request } from "undici";
|
|
11
11
|
import { RegistryV1, loadPackDescription, loadPackDescriptionFromManifest } from "@platforma-sdk/block-tools";
|
|
12
12
|
import fs from "node:fs";
|
|
13
|
-
import { assertNever } from "@milaboratories/ts-helpers";
|
|
13
|
+
import { assertNever, notEmpty } from "@milaboratories/ts-helpers";
|
|
14
14
|
import { fileURLToPath } from "node:url";
|
|
15
15
|
import { field } from "@milaboratories/pl-client";
|
|
16
16
|
import { LRUCache } from "lru-cache";
|
|
17
|
+
import { createHash } from "node:crypto";
|
|
17
18
|
import canonicalize from "canonicalize";
|
|
18
19
|
import { z } from "zod";
|
|
19
20
|
// src/mutator/block-pack/block_pack.ts
|
|
@@ -55,6 +56,8 @@ var BlockPackPreparer = class {
|
|
|
55
56
|
},
|
|
56
57
|
sizeCalculation: (value) => value.byteLength
|
|
57
58
|
});
|
|
59
|
+
/** Parsed packs by sha256, so adding a block again does not parse its workflow again. */
|
|
60
|
+
loadedPackCache = new LRUCache({ max: 50 });
|
|
58
61
|
/** Cache of prepared block packs for registry specs (immutable by version). */
|
|
59
62
|
preparedCache = new LRUCache({ max: 50 });
|
|
60
63
|
async getBlockConfigContainer(spec) {
|
|
@@ -108,7 +111,22 @@ var BlockPackPreparer = class {
|
|
|
108
111
|
const cached = this.preparedCache.get(key);
|
|
109
112
|
if (cached) return cached;
|
|
110
113
|
}
|
|
114
|
+
const registryPack = spec.type === "from-registry-v2" ? await this.prepareRegistryPack(spec) : void 0;
|
|
115
|
+
if (registryPack !== void 0) {
|
|
116
|
+
if (key) this.preparedCache.set(key, registryPack);
|
|
117
|
+
return registryPack;
|
|
118
|
+
}
|
|
111
119
|
const explicit = await this.prepareWithoutUnpacking(spec);
|
|
120
|
+
const { localPath, content } = explicit.template;
|
|
121
|
+
if (localPath !== void 0) return {
|
|
122
|
+
...explicit,
|
|
123
|
+
type: "prepared",
|
|
124
|
+
template: {
|
|
125
|
+
type: "local-pack",
|
|
126
|
+
path: localPath,
|
|
127
|
+
sha256: packSha256(content)
|
|
128
|
+
}
|
|
129
|
+
};
|
|
112
130
|
const parsed = await _usingCtx$1.a(new WorkerManager()).process("parseTemplate", explicit.template.content);
|
|
113
131
|
const result = {
|
|
114
132
|
...explicit,
|
|
@@ -127,6 +145,67 @@ var BlockPackPreparer = class {
|
|
|
127
145
|
await _usingCtx$1.d();
|
|
128
146
|
}
|
|
129
147
|
}
|
|
148
|
+
/**
|
|
149
|
+
* Prepares a v2 registry block from its manifest alone, without downloading the workflow.
|
|
150
|
+
* Undefined when the manifest does not list the workflow pack's sha256.
|
|
151
|
+
*/
|
|
152
|
+
async prepareRegistryPack(spec) {
|
|
153
|
+
const registry = this.v2RegistryProvider.getRegistry(spec.registryUrl);
|
|
154
|
+
const [manifest, components] = await Promise.all([registry.getManifest(spec.id), registry.getComponents(spec.id)]);
|
|
155
|
+
const workflowPath = manifest.description.components.workflow.main.path;
|
|
156
|
+
const workflowFile = manifest.files.find((f) => f.name === workflowPath);
|
|
157
|
+
if (workflowFile === void 0) return void 0;
|
|
158
|
+
return {
|
|
159
|
+
type: "prepared",
|
|
160
|
+
template: {
|
|
161
|
+
type: "registry-pack",
|
|
162
|
+
url: components.workflow.main.url,
|
|
163
|
+
sha256: workflowFile.sha256.toLowerCase()
|
|
164
|
+
},
|
|
165
|
+
config: parseBufferConfig(await this.remoteContentCache.forceFetch(components.model.url)),
|
|
166
|
+
frontend: {
|
|
167
|
+
type: "url",
|
|
168
|
+
url: components.ui.url
|
|
169
|
+
},
|
|
170
|
+
source: spec,
|
|
171
|
+
requiredCapabilities: manifest.description.meta.requiredCapabilities
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
/** Downloads or reads a pack, checks its sha256 and parses it. */
|
|
175
|
+
async loadPack(template) {
|
|
176
|
+
try {
|
|
177
|
+
var _usingCtx3 = _usingCtx();
|
|
178
|
+
let content;
|
|
179
|
+
if (template.type === "local-pack") {
|
|
180
|
+
content = await fs.promises.readFile(template.path);
|
|
181
|
+
if (packSha256(content) !== template.sha256) throw new Error(`workflow pack ${template.path} changed after the block was prepared; add the block again`);
|
|
182
|
+
}
|
|
183
|
+
const cached = this.loadedPackCache.get(template.sha256);
|
|
184
|
+
if (cached !== void 0) return cached;
|
|
185
|
+
if (content === void 0 && template.type === "registry-pack") {
|
|
186
|
+
content = new Uint8Array(await this.remoteContentCache.forceFetch(template.url));
|
|
187
|
+
const sha256 = packSha256(content);
|
|
188
|
+
if (sha256 !== template.sha256) {
|
|
189
|
+
this.remoteContentCache.delete(template.url);
|
|
190
|
+
throw new Error(`workflow pack ${template.url} has sha256 ${sha256}, expected ${template.sha256}`);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
const parsed = await _usingCtx3.a(new WorkerManager()).process("parseTemplate", notEmpty(content));
|
|
194
|
+
const loaded = {
|
|
195
|
+
template: {
|
|
196
|
+
type: "prepared",
|
|
197
|
+
data: parsed
|
|
198
|
+
},
|
|
199
|
+
requiredCapabilities: requiredCapabilitiesFromTemplate(parsed)
|
|
200
|
+
};
|
|
201
|
+
this.loadedPackCache.set(template.sha256, loaded);
|
|
202
|
+
return loaded;
|
|
203
|
+
} catch (_) {
|
|
204
|
+
_usingCtx3.e = _;
|
|
205
|
+
} finally {
|
|
206
|
+
await _usingCtx3.d();
|
|
207
|
+
}
|
|
208
|
+
}
|
|
130
209
|
async prepareWithoutUnpacking(spec) {
|
|
131
210
|
switch (spec.type) {
|
|
132
211
|
case "explicit": return spec;
|
|
@@ -161,7 +240,8 @@ var BlockPackPreparer = class {
|
|
|
161
240
|
type: "explicit",
|
|
162
241
|
template: {
|
|
163
242
|
type: "explicit",
|
|
164
|
-
content: workflowContent
|
|
243
|
+
content: workflowContent,
|
|
244
|
+
localPath: description.components.workflow.main.file
|
|
165
245
|
},
|
|
166
246
|
config,
|
|
167
247
|
frontend: {
|
|
@@ -188,7 +268,8 @@ var BlockPackPreparer = class {
|
|
|
188
268
|
type: "explicit",
|
|
189
269
|
template: {
|
|
190
270
|
type: "explicit",
|
|
191
|
-
content: workflowContent
|
|
271
|
+
content: workflowContent,
|
|
272
|
+
localPath: description.components.workflow.main.file
|
|
192
273
|
},
|
|
193
274
|
config,
|
|
194
275
|
frontend: {
|
|
@@ -248,7 +329,12 @@ var BlockPackPreparer = class {
|
|
|
248
329
|
}
|
|
249
330
|
}
|
|
250
331
|
};
|
|
332
|
+
/** Lowercase hex sha256 of a gzipped workflow pack, the key the backend installs it by. */
|
|
333
|
+
function packSha256(content) {
|
|
334
|
+
return createHash("sha256").update(content).digest("hex");
|
|
335
|
+
}
|
|
251
336
|
function createCustomBlockPack(tx, spec) {
|
|
337
|
+
if (spec.template.type === "registry-pack" || spec.template.type === "local-pack") throw new Error("BUG: a pack must be installed by cacheBlockPackTemplate first");
|
|
252
338
|
const blockPackInfo = {
|
|
253
339
|
config: spec.config,
|
|
254
340
|
source: spec.source
|
|
@@ -265,6 +351,6 @@ function createBlockPack(tx, spec) {
|
|
|
265
351
|
default: return assertNever(spec.type);
|
|
266
352
|
}
|
|
267
353
|
}
|
|
268
|
-
export { BlockPackCustomType, BlockPackFrontendField, BlockPackPreparer, BlockPackTemplateField, createBlockPack };
|
|
354
|
+
export { BlockPackCustomType, BlockPackFrontendField, BlockPackPreparer, BlockPackTemplateField, createBlockPack, packSha256 };
|
|
269
355
|
|
|
270
356
|
//# sourceMappingURL=block_pack.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"block_pack.js","names":[],"sources":["../../../src/mutator/block-pack/block_pack.ts"],"sourcesContent":["import type { AnyResourceRef, PlTransaction, ResourceType } from \"@milaboratories/pl-client\";\nimport { field } from \"@milaboratories/pl-client\";\nimport { loadTemplate } from \"../template/template_loading\";\nimport type { BlockPackExplicit, BlockPackSpecAny, BlockPackSpecPrepared } from \"../../model\";\nimport type { Signer } from \"@milaboratories/ts-helpers\";\nimport { assertNever } from \"@milaboratories/ts-helpers\";\nimport type { Branded } from \"@milaboratories/pl-model-common\";\nimport fs from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Dispatcher } from \"undici\";\nimport { request } from \"undici\";\nimport { createFrontend } from \"./frontend\";\nimport { requiredCapabilitiesFromTemplate } from \"./required_capabilities\";\nimport type { BlockConfigContainer } from \"@platforma-sdk/model\";\nimport { Code } from \"@platforma-sdk/model\";\nimport {\n loadPackDescription,\n loadPackDescriptionFromManifest,\n RegistryV1,\n} from \"@platforma-sdk/block-tools\";\nimport type { BlockPackInfo } from \"../../model/block_pack\";\nimport { resolveDevPacket } from \"../../dev_env\";\nimport { getDevV2PacketMtime, getFromPackV2Mtime } from \"../../block_registry\";\nimport type { V2RegistryProvider } from \"../../block_registry/registry-v2-provider\";\nimport { LRUCache } from \"lru-cache\";\nimport canonicalize from \"canonicalize\";\nimport type { BlockPackSpec } from \"@milaboratories/pl-model-middle-layer\";\nimport { WorkerManager } from \"../../worker/WorkerManager\";\nimport { z } from \"zod\";\n\ntype PreparedCacheKey = Branded<string, \"PreparedCacheKey\">;\n\nexport const BlockPackCustomType: ResourceType = { name: \"BlockPackCustom\", version: \"1\" };\nexport const BlockPackTemplateField = \"template\";\nexport const BlockPackFrontendField = \"frontend\";\n\n/** Ensure trailing slash */\nfunction tSlash(str: string): string {\n if (str.endsWith(\"/\")) return str;\n else return `${str}/`;\n}\n\nfunction parseStringConfig(configContent: string): BlockConfigContainer {\n const res = z.record(z.string(), z.unknown()).safeParse(JSON.parse(configContent));\n\n if (!res.success) {\n throw new Error(\"Invalid config content\");\n }\n\n if (!Code.safeParse(res.data.code).success) {\n throw new Error(\"parseStringConfig:No code bundle\");\n }\n\n return res.data as BlockConfigContainer;\n}\n\nfunction parseBufferConfig(buffer: ArrayBuffer): BlockConfigContainer {\n return parseStringConfig(Buffer.from(buffer).toString(\"utf8\"));\n}\n\nexport class BlockPackPreparer {\n constructor(\n private readonly v2RegistryProvider: V2RegistryProvider,\n private readonly signer: Signer,\n private readonly http?: Dispatcher,\n ) {}\n\n private readonly remoteContentCache = new LRUCache<string, ArrayBuffer>({\n max: 500,\n maxSize: 128 * 1024 * 1024,\n fetchMethod: async (key) => {\n const httpOptions = this.http !== undefined ? { dispatcher: this.http } : {};\n return await (await request(key, httpOptions)).body.arrayBuffer();\n },\n sizeCalculation: (value) => value.byteLength,\n });\n\n /** Cache of prepared block packs for registry specs (immutable by version). */\n private readonly preparedCache = new LRUCache<PreparedCacheKey, BlockPackSpecPrepared>({\n max: 50,\n });\n\n public async getBlockConfigContainer(spec: BlockPackSpecAny): Promise<BlockConfigContainer> {\n switch (spec.type) {\n case \"explicit\":\n return spec.config;\n\n case \"prepared\":\n return spec.config;\n\n case \"dev-v1\": {\n const devPaths = await resolveDevPacket(spec.folder, false);\n const configContent = await fs.promises.readFile(devPaths.config, { encoding: \"utf-8\" });\n return JSON.parse(configContent);\n }\n\n case \"dev-v2\": {\n const description = await loadPackDescription(spec.folder);\n const configContent = await fs.promises.readFile(description.components.model.file, {\n encoding: \"utf-8\",\n });\n return parseStringConfig(configContent);\n }\n\n case \"from-pack-v2\": {\n // packUrl is a file: URL (the facade emits URLs, not paths); convert at\n // this Node boundary before touching the filesystem.\n const packDir = fileURLToPath(spec.packUrl);\n const description = await loadPackDescriptionFromManifest(packDir);\n const configContent = await fs.promises.readFile(description.components.model.file, {\n encoding: \"utf-8\",\n });\n return parseStringConfig(configContent);\n }\n\n case \"from-registry-v1\": {\n const urlPrefix = `${tSlash(spec.registryUrl)}${RegistryV1.packageContentPrefix({ organization: spec.id.organization, package: spec.id.name, version: spec.id.version })}`;\n\n const configResponse = await this.remoteContentCache.forceFetch(`${urlPrefix}/config.json`);\n return JSON.parse(Buffer.from(configResponse).toString(\"utf8\"));\n }\n\n case \"from-registry-v2\": {\n const registry = this.v2RegistryProvider.getRegistry(spec.registryUrl);\n const components = await registry.getComponents(spec.id);\n const configResponse = await this.remoteContentCache.forceFetch(components.model.url);\n return parseBufferConfig(configResponse);\n }\n\n default:\n return assertNever(spec);\n }\n }\n\n /** Returns a stable cache key for registry specs (immutable by version). Dev specs return undefined. */\n private specKey(spec: BlockPackSpecAny): PreparedCacheKey | undefined {\n switch (spec.type) {\n case \"from-registry-v1\":\n return `v1:${spec.registryUrl}:${spec.id.organization}:${spec.id.name}:${spec.id.version}` as PreparedCacheKey;\n case \"from-registry-v2\":\n return `v2:${spec.registryUrl}:${canonicalize(spec.id)}` as PreparedCacheKey;\n default:\n return undefined; // dev, explicit, prepared — not cacheable\n }\n }\n\n public async prepare(spec: BlockPackSpecAny): Promise<BlockPackSpecPrepared> {\n if (spec.type === \"prepared\") {\n return spec;\n }\n\n // Check prepare cache for registry specs\n const key = this.specKey(spec);\n if (key) {\n const cached = this.preparedCache.get(key);\n if (cached) return cached;\n }\n\n const explicit = await this.prepareWithoutUnpacking(spec);\n\n await using workerManager = new WorkerManager();\n\n const parsed = await workerManager.process(\"parseTemplate\", explicit.template.content);\n\n const result: BlockPackSpecPrepared = {\n ...explicit,\n type: \"prepared\",\n template: {\n type: \"prepared\",\n data: parsed,\n },\n requiredCapabilities: requiredCapabilitiesFromTemplate(parsed),\n };\n\n if (key) {\n this.preparedCache.set(key, result);\n }\n\n return result;\n }\n\n private async prepareWithoutUnpacking(\n spec: BlockPackExplicit | BlockPackSpec,\n ): Promise<BlockPackExplicit> {\n switch (spec.type) {\n case \"explicit\":\n return spec;\n\n case \"dev-v1\": {\n const devPaths = await resolveDevPacket(spec.folder, false);\n\n // template\n const templateContent = await fs.promises.readFile(devPaths.workflow);\n\n // config\n const config = JSON.parse(await fs.promises.readFile(devPaths.config, \"utf-8\"));\n\n // frontend\n const frontendPath = devPaths.ui;\n\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: templateContent,\n },\n config,\n frontend: {\n type: \"local\",\n path: frontendPath,\n signature: this.signer.sign(frontendPath),\n },\n source: spec,\n };\n }\n\n case \"dev-v2\": {\n const description = await loadPackDescription(spec.folder);\n const config = parseStringConfig(\n await fs.promises.readFile(description.components.model.file, {\n encoding: \"utf-8\",\n }),\n );\n const workflowContent = await fs.promises.readFile(\n description.components.workflow.main.file,\n );\n const frontendPath = description.components.ui.folder;\n const source = { ...spec };\n if (spec.mtime === undefined)\n // if absent, calculating the mtime here, so the block will correctly show whether it can be updated\n source.mtime = await getDevV2PacketMtime(description);\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: workflowContent,\n },\n config,\n frontend: {\n type: \"local\",\n path: frontendPath,\n signature: this.signer.sign(frontendPath),\n },\n source,\n };\n }\n\n case \"from-pack-v2\": {\n // packUrl is a file: URL (the facade emits URLs, not paths); convert at\n // this Node boundary before touching the filesystem.\n const packDir = fileURLToPath(spec.packUrl);\n const description = await loadPackDescriptionFromManifest(packDir);\n const config = parseStringConfig(\n await fs.promises.readFile(description.components.model.file, {\n encoding: \"utf-8\",\n }),\n );\n const workflowContent = await fs.promises.readFile(\n description.components.workflow.main.file,\n );\n // UI ships as ui.tgz inside block-pack/; its absolute path is carried\n // in the ui folder slot. The tarball is unpacked lazily at serve-time by\n // the download driver (local-tgz frontend), not eagerly here — so it\n // inherits the driver's usage-tracking and space recycling.\n const uiTgzPath = description.components.ui.folder;\n const source = { ...spec };\n let mtime = spec.mtime;\n if (mtime === undefined) {\n // No explicit mtime: derive one so the frontend cache key invalidates\n // when the block changes.\n mtime = await getFromPackV2Mtime(packDir, uiTgzPath);\n source.mtime = mtime;\n }\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: workflowContent,\n },\n config,\n frontend: {\n type: \"local-tgz\",\n path: uiTgzPath,\n mtime,\n signature: this.signer.sign(`${uiTgzPath}:${mtime}`),\n },\n source,\n };\n }\n\n case \"from-registry-v1\": {\n const urlPrefix = `${tSlash(spec.registryUrl)}${RegistryV1.packageContentPrefix({ organization: spec.id.organization, package: spec.id.name, version: spec.id.version })}`;\n\n const templateUrl = `${urlPrefix}/template.plj.gz`;\n // template\n const templateResponse = await this.remoteContentCache.forceFetch(templateUrl);\n const templateContent = new Uint8Array(templateResponse);\n\n // config\n const configResponse = await this.remoteContentCache.forceFetch(`${urlPrefix}/config.json`);\n const config = JSON.parse(\n Buffer.from(configResponse).toString(\"utf8\"),\n ) as BlockConfigContainer;\n\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: templateContent,\n },\n config,\n frontend: {\n type: \"url\",\n url: `${urlPrefix}/frontend.tgz`,\n },\n source: spec,\n };\n }\n\n case \"from-registry-v2\": {\n const registry = this.v2RegistryProvider.getRegistry(spec.registryUrl);\n const components = await registry.getComponents(spec.id);\n const getModel = async () =>\n parseBufferConfig(await this.remoteContentCache.forceFetch(components.model.url));\n const getWorkflow = async () =>\n await this.remoteContentCache.forceFetch(components.workflow.main.url);\n\n const [model, workflow] = await Promise.all([getModel(), getWorkflow()]);\n const workflowContent = Buffer.from(workflow);\n\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: workflowContent,\n },\n config: model,\n frontend: {\n type: \"url\",\n url: components.ui.url,\n },\n source: spec,\n };\n }\n\n default:\n return assertNever(spec);\n }\n }\n}\n\nfunction createCustomBlockPack(tx: PlTransaction, spec: BlockPackSpecPrepared): AnyResourceRef {\n const blockPackInfo: BlockPackInfo = { config: spec.config, source: spec.source };\n const bp = tx.createStruct(BlockPackCustomType, JSON.stringify(blockPackInfo));\n tx.createField(field(bp, BlockPackTemplateField), \"Input\", loadTemplate(tx, spec.template));\n tx.createField(field(bp, BlockPackFrontendField), \"Input\", createFrontend(tx, spec.frontend));\n tx.lock(bp);\n\n return bp;\n}\n\nexport function createBlockPack(tx: PlTransaction, spec: BlockPackSpecPrepared): AnyResourceRef {\n switch (spec.type) {\n case \"prepared\":\n return createCustomBlockPack(tx, spec);\n default:\n return assertNever(spec.type);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgCA,MAAa,sBAAoC;CAAE,MAAM;CAAmB,SAAS;AAAI;AACzF,MAAa,yBAAyB;AACtC,MAAa,yBAAyB;;AAGtC,SAAS,OAAO,KAAqB;CACnC,IAAI,IAAI,SAA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C,SACE,OAAO,YAAY,KAAK,IAAI;CAChC;AACF"}
|
|
1
|
+
{"version":3,"file":"block_pack.js","names":[],"sources":["../../../src/mutator/block-pack/block_pack.ts"],"sourcesContent":["import type { AnyResourceRef, PlTransaction, ResourceType } from \"@milaboratories/pl-client\";\nimport { field } from \"@milaboratories/pl-client\";\nimport { loadTemplate } from \"../template/template_loading\";\nimport type { BlockPackExplicit, BlockPackSpecAny, BlockPackSpecPrepared } from \"../../model\";\nimport type { Signer } from \"@milaboratories/ts-helpers\";\nimport { assertNever, notEmpty } from \"@milaboratories/ts-helpers\";\nimport type { Branded } from \"@milaboratories/pl-model-common\";\nimport fs from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Dispatcher } from \"undici\";\nimport { request } from \"undici\";\nimport { createFrontend } from \"./frontend\";\nimport { requiredCapabilitiesFromTemplate } from \"./required_capabilities\";\nimport type { BlockConfigContainer } from \"@platforma-sdk/model\";\nimport { Code } from \"@platforma-sdk/model\";\nimport {\n loadPackDescription,\n loadPackDescriptionFromManifest,\n RegistryV1,\n} from \"@platforma-sdk/block-tools\";\nimport type { BlockPackInfo } from \"../../model/block_pack\";\nimport type { InstallablePackTemplate, PreparedTemplate } from \"../../model/template_spec\";\nimport { resolveDevPacket } from \"../../dev_env\";\nimport { getDevV2PacketMtime, getFromPackV2Mtime } from \"../../block_registry\";\nimport type { V2RegistryProvider } from \"../../block_registry/registry-v2-provider\";\nimport { LRUCache } from \"lru-cache\";\nimport canonicalize from \"canonicalize\";\nimport type { BlockPackFromRegistryV2, BlockPackSpec } from \"@milaboratories/pl-model-middle-layer\";\nimport { WorkerManager } from \"../../worker/WorkerManager\";\nimport { z } from \"zod\";\n\ntype PreparedCacheKey = Branded<string, \"PreparedCacheKey\">;\n\nexport const BlockPackCustomType: ResourceType = { name: \"BlockPackCustom\", version: \"1\" };\nexport const BlockPackTemplateField = \"template\";\nexport const BlockPackFrontendField = \"frontend\";\n\n/** Ensure trailing slash */\nfunction tSlash(str: string): string {\n if (str.endsWith(\"/\")) return str;\n else return `${str}/`;\n}\n\nfunction parseStringConfig(configContent: string): BlockConfigContainer {\n const res = z.record(z.string(), z.unknown()).safeParse(JSON.parse(configContent));\n\n if (!res.success) {\n throw new Error(\"Invalid config content\");\n }\n\n if (!Code.safeParse(res.data.code).success) {\n throw new Error(\"parseStringConfig:No code bundle\");\n }\n\n return res.data as BlockConfigContainer;\n}\n\nfunction parseBufferConfig(buffer: ArrayBuffer): BlockConfigContainer {\n return parseStringConfig(Buffer.from(buffer).toString(\"utf8\"));\n}\n\nexport class BlockPackPreparer {\n constructor(\n private readonly v2RegistryProvider: V2RegistryProvider,\n private readonly signer: Signer,\n private readonly http?: Dispatcher,\n ) {}\n\n private readonly remoteContentCache = new LRUCache<string, ArrayBuffer>({\n max: 500,\n maxSize: 128 * 1024 * 1024,\n fetchMethod: async (key) => {\n const httpOptions = this.http !== undefined ? { dispatcher: this.http } : {};\n return await (await request(key, httpOptions)).body.arrayBuffer();\n },\n sizeCalculation: (value) => value.byteLength,\n });\n\n /** Parsed packs by sha256, so adding a block again does not parse its workflow again. */\n private readonly loadedPackCache = new LRUCache<string, LoadedPack>({ max: 50 });\n\n /** Cache of prepared block packs for registry specs (immutable by version). */\n private readonly preparedCache = new LRUCache<PreparedCacheKey, BlockPackSpecPrepared>({\n max: 50,\n });\n\n public async getBlockConfigContainer(spec: BlockPackSpecAny): Promise<BlockConfigContainer> {\n switch (spec.type) {\n case \"explicit\":\n return spec.config;\n\n case \"prepared\":\n return spec.config;\n\n case \"dev-v1\": {\n const devPaths = await resolveDevPacket(spec.folder, false);\n const configContent = await fs.promises.readFile(devPaths.config, { encoding: \"utf-8\" });\n return JSON.parse(configContent);\n }\n\n case \"dev-v2\": {\n const description = await loadPackDescription(spec.folder);\n const configContent = await fs.promises.readFile(description.components.model.file, {\n encoding: \"utf-8\",\n });\n return parseStringConfig(configContent);\n }\n\n case \"from-pack-v2\": {\n // packUrl is a file: URL (the facade emits URLs, not paths); convert at\n // this Node boundary before touching the filesystem.\n const packDir = fileURLToPath(spec.packUrl);\n const description = await loadPackDescriptionFromManifest(packDir);\n const configContent = await fs.promises.readFile(description.components.model.file, {\n encoding: \"utf-8\",\n });\n return parseStringConfig(configContent);\n }\n\n case \"from-registry-v1\": {\n const urlPrefix = `${tSlash(spec.registryUrl)}${RegistryV1.packageContentPrefix({ organization: spec.id.organization, package: spec.id.name, version: spec.id.version })}`;\n\n const configResponse = await this.remoteContentCache.forceFetch(`${urlPrefix}/config.json`);\n return JSON.parse(Buffer.from(configResponse).toString(\"utf8\"));\n }\n\n case \"from-registry-v2\": {\n const registry = this.v2RegistryProvider.getRegistry(spec.registryUrl);\n const components = await registry.getComponents(spec.id);\n const configResponse = await this.remoteContentCache.forceFetch(components.model.url);\n return parseBufferConfig(configResponse);\n }\n\n default:\n return assertNever(spec);\n }\n }\n\n /** Returns a stable cache key for registry specs (immutable by version). Dev specs return undefined. */\n private specKey(spec: BlockPackSpecAny): PreparedCacheKey | undefined {\n switch (spec.type) {\n case \"from-registry-v1\":\n return `v1:${spec.registryUrl}:${spec.id.organization}:${spec.id.name}:${spec.id.version}` as PreparedCacheKey;\n case \"from-registry-v2\":\n return `v2:${spec.registryUrl}:${canonicalize(spec.id)}` as PreparedCacheKey;\n default:\n return undefined; // dev, explicit, prepared — not cacheable\n }\n }\n\n public async prepare(spec: BlockPackSpecAny): Promise<BlockPackSpecPrepared> {\n if (spec.type === \"prepared\") {\n return spec;\n }\n\n // Check prepare cache for registry specs\n const key = this.specKey(spec);\n if (key) {\n const cached = this.preparedCache.get(key);\n if (cached) return cached;\n }\n\n const registryPack =\n spec.type === \"from-registry-v2\" ? await this.prepareRegistryPack(spec) : undefined;\n if (registryPack !== undefined) {\n if (key) this.preparedCache.set(key, registryPack);\n return registryPack;\n }\n\n const explicit = await this.prepareWithoutUnpacking(spec);\n\n // Local dev packs are parsed when installed, which also checks their required capabilities.\n const { localPath, content } = explicit.template;\n if (localPath !== undefined)\n return {\n ...explicit,\n type: \"prepared\",\n template: { type: \"local-pack\", path: localPath, sha256: packSha256(content) },\n };\n\n await using workerManager = new WorkerManager();\n\n const parsed = await workerManager.process(\"parseTemplate\", explicit.template.content);\n\n const result: BlockPackSpecPrepared = {\n ...explicit,\n type: \"prepared\",\n template: {\n type: \"prepared\",\n data: parsed,\n },\n requiredCapabilities: requiredCapabilitiesFromTemplate(parsed),\n };\n\n if (key) {\n this.preparedCache.set(key, result);\n }\n\n return result;\n }\n\n /**\n * Prepares a v2 registry block from its manifest alone, without downloading the workflow.\n * Undefined when the manifest does not list the workflow pack's sha256.\n */\n private async prepareRegistryPack(\n spec: BlockPackFromRegistryV2,\n ): Promise<BlockPackSpecPrepared | undefined> {\n const registry = this.v2RegistryProvider.getRegistry(spec.registryUrl);\n const [manifest, components] = await Promise.all([\n registry.getManifest(spec.id),\n registry.getComponents(spec.id),\n ]);\n const workflowPath = manifest.description.components.workflow.main.path;\n const workflowFile = manifest.files.find((f) => f.name === workflowPath);\n if (workflowFile === undefined) return undefined;\n\n return {\n type: \"prepared\",\n template: {\n type: \"registry-pack\",\n url: components.workflow.main.url,\n sha256: workflowFile.sha256.toLowerCase(),\n },\n config: parseBufferConfig(await this.remoteContentCache.forceFetch(components.model.url)),\n frontend: { type: \"url\", url: components.ui.url },\n source: spec,\n requiredCapabilities: manifest.description.meta.requiredCapabilities,\n };\n }\n\n /** Downloads or reads a pack, checks its sha256 and parses it. */\n public async loadPack(template: InstallablePackTemplate): Promise<LoadedPack> {\n let content: Uint8Array | undefined;\n if (template.type === \"local-pack\") {\n // A rebuild after prepare would pair this config with another build's workflow.\n content = await fs.promises.readFile(template.path);\n if (packSha256(content) !== template.sha256)\n throw new Error(\n `workflow pack ${template.path} changed after the block was prepared; add the block again`,\n );\n }\n\n const cached = this.loadedPackCache.get(template.sha256);\n if (cached !== undefined) return cached;\n\n if (content === undefined && template.type === \"registry-pack\") {\n content = new Uint8Array(await this.remoteContentCache.forceFetch(template.url));\n const sha256 = packSha256(content);\n if (sha256 !== template.sha256) {\n // Do not keep a broken download for the next attempt.\n this.remoteContentCache.delete(template.url);\n throw new Error(\n `workflow pack ${template.url} has sha256 ${sha256}, expected ${template.sha256}`,\n );\n }\n }\n\n await using workerManager = new WorkerManager();\n const parsed = await workerManager.process(\"parseTemplate\", notEmpty(content));\n const loaded: LoadedPack = {\n template: { type: \"prepared\", data: parsed },\n requiredCapabilities: requiredCapabilitiesFromTemplate(parsed),\n };\n this.loadedPackCache.set(template.sha256, loaded);\n return loaded;\n }\n\n private async prepareWithoutUnpacking(\n spec: BlockPackExplicit | BlockPackSpec,\n ): Promise<BlockPackExplicit> {\n switch (spec.type) {\n case \"explicit\":\n return spec;\n\n case \"dev-v1\": {\n const devPaths = await resolveDevPacket(spec.folder, false);\n\n // template\n const templateContent = await fs.promises.readFile(devPaths.workflow);\n\n // config\n const config = JSON.parse(await fs.promises.readFile(devPaths.config, \"utf-8\"));\n\n // frontend\n const frontendPath = devPaths.ui;\n\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: templateContent,\n },\n config,\n frontend: {\n type: \"local\",\n path: frontendPath,\n signature: this.signer.sign(frontendPath),\n },\n source: spec,\n };\n }\n\n case \"dev-v2\": {\n const description = await loadPackDescription(spec.folder);\n const config = parseStringConfig(\n await fs.promises.readFile(description.components.model.file, {\n encoding: \"utf-8\",\n }),\n );\n const workflowContent = await fs.promises.readFile(\n description.components.workflow.main.file,\n );\n const frontendPath = description.components.ui.folder;\n const source = { ...spec };\n if (spec.mtime === undefined)\n // if absent, calculating the mtime here, so the block will correctly show whether it can be updated\n source.mtime = await getDevV2PacketMtime(description);\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: workflowContent,\n localPath: description.components.workflow.main.file,\n },\n config,\n frontend: {\n type: \"local\",\n path: frontendPath,\n signature: this.signer.sign(frontendPath),\n },\n source,\n };\n }\n\n case \"from-pack-v2\": {\n // packUrl is a file: URL (the facade emits URLs, not paths); convert at\n // this Node boundary before touching the filesystem.\n const packDir = fileURLToPath(spec.packUrl);\n const description = await loadPackDescriptionFromManifest(packDir);\n const config = parseStringConfig(\n await fs.promises.readFile(description.components.model.file, {\n encoding: \"utf-8\",\n }),\n );\n const workflowContent = await fs.promises.readFile(\n description.components.workflow.main.file,\n );\n // UI ships as ui.tgz inside block-pack/; its absolute path is carried\n // in the ui folder slot. The tarball is unpacked lazily at serve-time by\n // the download driver (local-tgz frontend), not eagerly here — so it\n // inherits the driver's usage-tracking and space recycling.\n const uiTgzPath = description.components.ui.folder;\n const source = { ...spec };\n let mtime = spec.mtime;\n if (mtime === undefined) {\n // No explicit mtime: derive one so the frontend cache key invalidates\n // when the block changes.\n mtime = await getFromPackV2Mtime(packDir, uiTgzPath);\n source.mtime = mtime;\n }\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: workflowContent,\n localPath: description.components.workflow.main.file,\n },\n config,\n frontend: {\n type: \"local-tgz\",\n path: uiTgzPath,\n mtime,\n signature: this.signer.sign(`${uiTgzPath}:${mtime}`),\n },\n source,\n };\n }\n\n case \"from-registry-v1\": {\n const urlPrefix = `${tSlash(spec.registryUrl)}${RegistryV1.packageContentPrefix({ organization: spec.id.organization, package: spec.id.name, version: spec.id.version })}`;\n\n const templateUrl = `${urlPrefix}/template.plj.gz`;\n // template\n const templateResponse = await this.remoteContentCache.forceFetch(templateUrl);\n const templateContent = new Uint8Array(templateResponse);\n\n // config\n const configResponse = await this.remoteContentCache.forceFetch(`${urlPrefix}/config.json`);\n const config = JSON.parse(\n Buffer.from(configResponse).toString(\"utf8\"),\n ) as BlockConfigContainer;\n\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: templateContent,\n },\n config,\n frontend: {\n type: \"url\",\n url: `${urlPrefix}/frontend.tgz`,\n },\n source: spec,\n };\n }\n\n case \"from-registry-v2\": {\n const registry = this.v2RegistryProvider.getRegistry(spec.registryUrl);\n const components = await registry.getComponents(spec.id);\n const getModel = async () =>\n parseBufferConfig(await this.remoteContentCache.forceFetch(components.model.url));\n const getWorkflow = async () =>\n await this.remoteContentCache.forceFetch(components.workflow.main.url);\n\n const [model, workflow] = await Promise.all([getModel(), getWorkflow()]);\n const workflowContent = Buffer.from(workflow);\n\n return {\n type: \"explicit\",\n template: {\n type: \"explicit\",\n content: workflowContent,\n },\n config: model,\n frontend: {\n type: \"url\",\n url: components.ui.url,\n },\n source: spec,\n };\n }\n\n default:\n return assertNever(spec);\n }\n }\n}\n\n/** A pack parsed on the client, with the capabilities it declares. */\ntype LoadedPack = { template: PreparedTemplate; requiredCapabilities?: string[] };\n\n/** Lowercase hex sha256 of a gzipped workflow pack, the key the backend installs it by. */\nexport function packSha256(content: Uint8Array): string {\n return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\nfunction createCustomBlockPack(tx: PlTransaction, spec: BlockPackSpecPrepared): AnyResourceRef {\n if (spec.template.type === \"registry-pack\" || spec.template.type === \"local-pack\")\n throw new Error(\"BUG: a pack must be installed by cacheBlockPackTemplate first\");\n const blockPackInfo: BlockPackInfo = { config: spec.config, source: spec.source };\n const bp = tx.createStruct(BlockPackCustomType, JSON.stringify(blockPackInfo));\n tx.createField(field(bp, BlockPackTemplateField), \"Input\", loadTemplate(tx, spec.template));\n tx.createField(field(bp, BlockPackFrontendField), \"Input\", createFrontend(tx, spec.frontend));\n tx.lock(bp);\n\n return bp;\n}\n\nexport function createBlockPack(tx: PlTransaction, spec: BlockPackSpecPrepared): AnyResourceRef {\n switch (spec.type) {\n case \"prepared\":\n return createCustomBlockPack(tx, spec);\n default:\n return assertNever(spec.type);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,sBAAoC;CAAE,MAAM;CAAmB,SAAS;AAAI;AACzF,MAAa,yBAAyB;AACtC,MAAa,yBAAyB;;AAGtC,SAAS,OAAO,KAAqB;CACnC,IAAI,IAAI,SAAS,GAAG,GAAG,OAAO;MACzB,OAAO,GAAG,IAAI;AAC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S,GAAG,YAAY,CAAC,CAAC;IAGvE,OAAO;KACL,MAAM;KACN,UAAU;MACR,MAAM;MACN,SANoB,OAAO,KAAK,QAMT;KACzB;KACA,QAAQ;KACR,UAAU;MACR,MAAM;MACN,KAAK,WAAW,GAAG;KACrB;KACA,QAAQ;IACV;GACF;GAEA,SACE,OAAO,YAAY,IAAI;EAC3B;CACF;AACF;;AAMA,SAAgB,WAAW,SAA6B;CACtD,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,OAAO,KAAK;AAC1D;AAEA,SAAS,sBAAsB,IAAmB,MAA6C;CAC7F,IAAI,KAAK,SAAS,SAAS,mBAAmB,KAAK,SAAS,SAAS,cACnE,MAAM,IAAI,MAAM,+DAA+D;CACjF,MAAM,gBAA+B;EAAE,QAAQ,KAAK;EAAQ,QAAQ,KAAK;CAAO;CAChF,MAAM,KAAK,GAAG,aAAa,qBAAqB,KAAK,UAAU,aAAa,CAAC;CAC7E,GAAG,YAAY,MAAM,IAAI,sBAAsB,GAAG,SAAS,aAAa,IAAI,KAAK,QAAQ,CAAC;CAC1F,GAAG,YAAY,MAAM,IAAI,sBAAsB,GAAG,SAAS,eAAe,IAAI,KAAK,QAAQ,CAAC;CAC5F,GAAG,KAAK,EAAE;CAEV,OAAO;AACT;AAEA,SAAgB,gBAAgB,IAAmB,MAA6C;CAC9F,QAAQ,KAAK,MAAb;EACE,KAAK,YACH,OAAO,sBAAsB,IAAI,IAAI;EACvC,SACE,OAAO,YAAY,KAAK,IAAI;CAChC;AACF"}
|
|
@@ -36,7 +36,23 @@ function deriveRequiredCapabilities(workflowContent) {
|
|
|
36
36
|
}
|
|
37
37
|
return requiredCapabilitiesFromTemplate(parsed);
|
|
38
38
|
}
|
|
39
|
+
/** Throws when the connected backend doesn't advertise every capability the
|
|
40
|
+
* block-pack requires (as declared in `meta.requiredCapabilities`).
|
|
41
|
+
*
|
|
42
|
+
* The matching set is the desktop's install gate moved server-side so both
|
|
43
|
+
* the UI (`AddBlockModal`) and direct middle-layer callers (the MCP server's
|
|
44
|
+
* `add_block` tool, programmatic block installs, tests) reject incompatible
|
|
45
|
+
* blocks consistently. */
|
|
46
|
+
function throwIfMissingServerCapabilities(pl, requiredCapabilities) {
|
|
47
|
+
if (!requiredCapabilities || requiredCapabilities.length === 0) return;
|
|
48
|
+
const advertised = pl.serverInfo.capabilities ?? [];
|
|
49
|
+
const filterFn = (c) => !advertised.includes(c);
|
|
50
|
+
if (!requiredCapabilities.some(filterFn)) return;
|
|
51
|
+
const missing = requiredCapabilities.filter(filterFn);
|
|
52
|
+
throw new Error(`Block cannot be added: connected backend does not advertise capabilities ${JSON.stringify(missing)}. Backend advertises ${JSON.stringify(advertised)}. Upgrade the backend or remove the requirement from the block manifest.`);
|
|
53
|
+
}
|
|
39
54
|
exports.deriveRequiredCapabilities = deriveRequiredCapabilities;
|
|
40
55
|
exports.requiredCapabilitiesFromTemplate = requiredCapabilitiesFromTemplate;
|
|
56
|
+
exports.throwIfMissingServerCapabilities = throwIfMissingServerCapabilities;
|
|
41
57
|
|
|
42
58
|
//# sourceMappingURL=required_capabilities.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"required_capabilities.cjs","names":["gunzipSync"],"sources":["../../../src/mutator/block-pack/required_capabilities.ts"],"sourcesContent":["import { gunzipSync } from \"node:zlib\";\nimport type { CompiledTemplateV3, TemplateData } from \"@milaboratories/pl-model-backend\";\n\n/**\n * Reads the capability tokens a template declares it requires via\n * `TemplateDataV3.requiredCapabilities` (populated by `tengo-builder` at\n * compile time).\n *\n * Use this on the install path: `BlockPackPreparer.prepare` parses the\n * workflow off-thread via the worker, and the parsed result feeds\n * straight into this function — no second gunzip+JSON.parse on the main\n * thread, no recursive walk to re-derive what the compiler already wrote\n * down.\n *\n * Returns `undefined` for v2 templates (no compile-time capability\n * field) and for v3 templates that declare no requirements; otherwise\n * the array as the compiler wrote it.\n */\nexport function requiredCapabilitiesFromTemplate(\n parsed: TemplateData | CompiledTemplateV3,\n): string[] | undefined {\n if (parsed.type !== \"pl.tengo-template.v3\") return undefined;\n return parsed.template.requiredCapabilities;\n}\n\n/**\n * Same lookup, starting from raw `main.plj.gz` bytes. Used only at\n * catalog-listing time for local-dev blocks where the worker pipeline\n * isn't in play (`block_registry/registry.ts`). Install paths go through\n * `requiredCapabilitiesFromTemplate` instead to avoid parsing the\n * workflow twice.\n */\nexport function deriveRequiredCapabilities(\n workflowContent: Uint8Array | Buffer,\n): string[] | undefined {\n let parsed: unknown;\n try {\n const json = gunzipSync(workflowContent).toString(\"utf-8\");\n parsed = JSON.parse(json);\n } catch {\n return undefined;\n }\n return requiredCapabilitiesFromTemplate(parsed as TemplateData | CompiledTemplateV3);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"required_capabilities.cjs","names":["gunzipSync"],"sources":["../../../src/mutator/block-pack/required_capabilities.ts"],"sourcesContent":["import { gunzipSync } from \"node:zlib\";\nimport type { CompiledTemplateV3, TemplateData } from \"@milaboratories/pl-model-backend\";\nimport type { PlClient } from \"@milaboratories/pl-client\";\n\n/**\n * Reads the capability tokens a template declares it requires via\n * `TemplateDataV3.requiredCapabilities` (populated by `tengo-builder` at\n * compile time).\n *\n * Use this on the install path: `BlockPackPreparer.prepare` parses the\n * workflow off-thread via the worker, and the parsed result feeds\n * straight into this function — no second gunzip+JSON.parse on the main\n * thread, no recursive walk to re-derive what the compiler already wrote\n * down.\n *\n * Returns `undefined` for v2 templates (no compile-time capability\n * field) and for v3 templates that declare no requirements; otherwise\n * the array as the compiler wrote it.\n */\nexport function requiredCapabilitiesFromTemplate(\n parsed: TemplateData | CompiledTemplateV3,\n): string[] | undefined {\n if (parsed.type !== \"pl.tengo-template.v3\") return undefined;\n return parsed.template.requiredCapabilities;\n}\n\n/**\n * Same lookup, starting from raw `main.plj.gz` bytes. Used only at\n * catalog-listing time for local-dev blocks where the worker pipeline\n * isn't in play (`block_registry/registry.ts`). Install paths go through\n * `requiredCapabilitiesFromTemplate` instead to avoid parsing the\n * workflow twice.\n */\nexport function deriveRequiredCapabilities(\n workflowContent: Uint8Array | Buffer,\n): string[] | undefined {\n let parsed: unknown;\n try {\n const json = gunzipSync(workflowContent).toString(\"utf-8\");\n parsed = JSON.parse(json);\n } catch {\n return undefined;\n }\n return requiredCapabilitiesFromTemplate(parsed as TemplateData | CompiledTemplateV3);\n}\n\n/** Throws when the connected backend doesn't advertise every capability the\n * block-pack requires (as declared in `meta.requiredCapabilities`).\n *\n * The matching set is the desktop's install gate moved server-side so both\n * the UI (`AddBlockModal`) and direct middle-layer callers (the MCP server's\n * `add_block` tool, programmatic block installs, tests) reject incompatible\n * blocks consistently. */\nexport function throwIfMissingServerCapabilities(\n pl: PlClient,\n requiredCapabilities: readonly string[] | undefined,\n): void {\n if (!requiredCapabilities || requiredCapabilities.length === 0) return;\n const advertised = (pl.serverInfo.capabilities ?? []) as readonly string[];\n const filterFn = (c: string) => !advertised.includes(c);\n if (!requiredCapabilities.some(filterFn)) return;\n const missing = requiredCapabilities.filter(filterFn);\n throw new Error(\n `Block cannot be added: connected backend does not advertise capabilities ` +\n `${JSON.stringify(missing)}. ` +\n `Backend advertises ${JSON.stringify(advertised)}. ` +\n `Upgrade the backend or remove the requirement from the block manifest.`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmBA,SAAgB,iCACd,QACsB;CACtB,IAAI,OAAO,SAAS,wBAAwB,OAAO,KAAA;CACnD,OAAO,OAAO,SAAS;AACzB;;;;;;;;AASA,SAAgB,2BACd,iBACsB;CACtB,IAAI;CACJ,IAAI;EACF,MAAM,QAAA,GAAOA,UAAAA,WAAAA,CAAW,eAAe,CAAC,CAAC,SAAS,OAAO;EACzD,SAAS,KAAK,MAAM,IAAI;CAC1B,QAAQ;EACN;CACF;CACA,OAAO,iCAAiC,MAA2C;AACrF;;;;;;;;AASA,SAAgB,iCACd,IACA,sBACM;CACN,IAAI,CAAC,wBAAwB,qBAAqB,WAAW,GAAG;CAChE,MAAM,aAAc,GAAG,WAAW,gBAAgB,CAAC;CACnD,MAAM,YAAY,MAAc,CAAC,WAAW,SAAS,CAAC;CACtD,IAAI,CAAC,qBAAqB,KAAK,QAAQ,GAAG;CAC1C,MAAM,UAAU,qBAAqB,OAAO,QAAQ;CACpD,MAAM,IAAI,MACR,4EACK,KAAK,UAAU,OAAO,EAAE,uBACL,KAAK,UAAU,UAAU,EAAE,yEAErD;AACF"}
|
|
@@ -36,6 +36,21 @@ function deriveRequiredCapabilities(workflowContent) {
|
|
|
36
36
|
}
|
|
37
37
|
return requiredCapabilitiesFromTemplate(parsed);
|
|
38
38
|
}
|
|
39
|
-
|
|
39
|
+
/** Throws when the connected backend doesn't advertise every capability the
|
|
40
|
+
* block-pack requires (as declared in `meta.requiredCapabilities`).
|
|
41
|
+
*
|
|
42
|
+
* The matching set is the desktop's install gate moved server-side so both
|
|
43
|
+
* the UI (`AddBlockModal`) and direct middle-layer callers (the MCP server's
|
|
44
|
+
* `add_block` tool, programmatic block installs, tests) reject incompatible
|
|
45
|
+
* blocks consistently. */
|
|
46
|
+
function throwIfMissingServerCapabilities(pl, requiredCapabilities) {
|
|
47
|
+
if (!requiredCapabilities || requiredCapabilities.length === 0) return;
|
|
48
|
+
const advertised = pl.serverInfo.capabilities ?? [];
|
|
49
|
+
const filterFn = (c) => !advertised.includes(c);
|
|
50
|
+
if (!requiredCapabilities.some(filterFn)) return;
|
|
51
|
+
const missing = requiredCapabilities.filter(filterFn);
|
|
52
|
+
throw new Error(`Block cannot be added: connected backend does not advertise capabilities ${JSON.stringify(missing)}. Backend advertises ${JSON.stringify(advertised)}. Upgrade the backend or remove the requirement from the block manifest.`);
|
|
53
|
+
}
|
|
54
|
+
export { deriveRequiredCapabilities, requiredCapabilitiesFromTemplate, throwIfMissingServerCapabilities };
|
|
40
55
|
|
|
41
56
|
//# sourceMappingURL=required_capabilities.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"required_capabilities.js","names":[],"sources":["../../../src/mutator/block-pack/required_capabilities.ts"],"sourcesContent":["import { gunzipSync } from \"node:zlib\";\nimport type { CompiledTemplateV3, TemplateData } from \"@milaboratories/pl-model-backend\";\n\n/**\n * Reads the capability tokens a template declares it requires via\n * `TemplateDataV3.requiredCapabilities` (populated by `tengo-builder` at\n * compile time).\n *\n * Use this on the install path: `BlockPackPreparer.prepare` parses the\n * workflow off-thread via the worker, and the parsed result feeds\n * straight into this function — no second gunzip+JSON.parse on the main\n * thread, no recursive walk to re-derive what the compiler already wrote\n * down.\n *\n * Returns `undefined` for v2 templates (no compile-time capability\n * field) and for v3 templates that declare no requirements; otherwise\n * the array as the compiler wrote it.\n */\nexport function requiredCapabilitiesFromTemplate(\n parsed: TemplateData | CompiledTemplateV3,\n): string[] | undefined {\n if (parsed.type !== \"pl.tengo-template.v3\") return undefined;\n return parsed.template.requiredCapabilities;\n}\n\n/**\n * Same lookup, starting from raw `main.plj.gz` bytes. Used only at\n * catalog-listing time for local-dev blocks where the worker pipeline\n * isn't in play (`block_registry/registry.ts`). Install paths go through\n * `requiredCapabilitiesFromTemplate` instead to avoid parsing the\n * workflow twice.\n */\nexport function deriveRequiredCapabilities(\n workflowContent: Uint8Array | Buffer,\n): string[] | undefined {\n let parsed: unknown;\n try {\n const json = gunzipSync(workflowContent).toString(\"utf-8\");\n parsed = JSON.parse(json);\n } catch {\n return undefined;\n }\n return requiredCapabilitiesFromTemplate(parsed as TemplateData | CompiledTemplateV3);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"required_capabilities.js","names":[],"sources":["../../../src/mutator/block-pack/required_capabilities.ts"],"sourcesContent":["import { gunzipSync } from \"node:zlib\";\nimport type { CompiledTemplateV3, TemplateData } from \"@milaboratories/pl-model-backend\";\nimport type { PlClient } from \"@milaboratories/pl-client\";\n\n/**\n * Reads the capability tokens a template declares it requires via\n * `TemplateDataV3.requiredCapabilities` (populated by `tengo-builder` at\n * compile time).\n *\n * Use this on the install path: `BlockPackPreparer.prepare` parses the\n * workflow off-thread via the worker, and the parsed result feeds\n * straight into this function — no second gunzip+JSON.parse on the main\n * thread, no recursive walk to re-derive what the compiler already wrote\n * down.\n *\n * Returns `undefined` for v2 templates (no compile-time capability\n * field) and for v3 templates that declare no requirements; otherwise\n * the array as the compiler wrote it.\n */\nexport function requiredCapabilitiesFromTemplate(\n parsed: TemplateData | CompiledTemplateV3,\n): string[] | undefined {\n if (parsed.type !== \"pl.tengo-template.v3\") return undefined;\n return parsed.template.requiredCapabilities;\n}\n\n/**\n * Same lookup, starting from raw `main.plj.gz` bytes. Used only at\n * catalog-listing time for local-dev blocks where the worker pipeline\n * isn't in play (`block_registry/registry.ts`). Install paths go through\n * `requiredCapabilitiesFromTemplate` instead to avoid parsing the\n * workflow twice.\n */\nexport function deriveRequiredCapabilities(\n workflowContent: Uint8Array | Buffer,\n): string[] | undefined {\n let parsed: unknown;\n try {\n const json = gunzipSync(workflowContent).toString(\"utf-8\");\n parsed = JSON.parse(json);\n } catch {\n return undefined;\n }\n return requiredCapabilitiesFromTemplate(parsed as TemplateData | CompiledTemplateV3);\n}\n\n/** Throws when the connected backend doesn't advertise every capability the\n * block-pack requires (as declared in `meta.requiredCapabilities`).\n *\n * The matching set is the desktop's install gate moved server-side so both\n * the UI (`AddBlockModal`) and direct middle-layer callers (the MCP server's\n * `add_block` tool, programmatic block installs, tests) reject incompatible\n * blocks consistently. */\nexport function throwIfMissingServerCapabilities(\n pl: PlClient,\n requiredCapabilities: readonly string[] | undefined,\n): void {\n if (!requiredCapabilities || requiredCapabilities.length === 0) return;\n const advertised = (pl.serverInfo.capabilities ?? []) as readonly string[];\n const filterFn = (c: string) => !advertised.includes(c);\n if (!requiredCapabilities.some(filterFn)) return;\n const missing = requiredCapabilities.filter(filterFn);\n throw new Error(\n `Block cannot be added: connected backend does not advertise capabilities ` +\n `${JSON.stringify(missing)}. ` +\n `Backend advertises ${JSON.stringify(advertised)}. ` +\n `Upgrade the backend or remove the requirement from the block manifest.`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmBA,SAAgB,iCACd,QACsB;CACtB,IAAI,OAAO,SAAS,wBAAwB,OAAO,KAAA;CACnD,OAAO,OAAO,SAAS;AACzB;;;;;;;;AASA,SAAgB,2BACd,iBACsB;CACtB,IAAI;CACJ,IAAI;EACF,MAAM,OAAO,WAAW,eAAe,CAAC,CAAC,SAAS,OAAO;EACzD,SAAS,KAAK,MAAM,IAAI;CAC1B,QAAQ;EACN;CACF;CACA,OAAO,iCAAiC,MAA2C;AACrF;;;;;;;;AASA,SAAgB,iCACd,IACA,sBACM;CACN,IAAI,CAAC,wBAAwB,qBAAqB,WAAW,GAAG;CAChE,MAAM,aAAc,GAAG,WAAW,gBAAgB,CAAC;CACnD,MAAM,YAAY,MAAc,CAAC,WAAW,SAAS,CAAC;CACtD,IAAI,CAAC,qBAAqB,KAAK,QAAQ,GAAG;CAC1C,MAAM,UAAU,qBAAqB,OAAO,QAAQ;CACpD,MAAM,IAAI,MACR,4EACK,KAAK,UAAU,OAAO,EAAE,uBACL,KAAK,UAAU,UAAU,EAAE,yEAErD;AACF"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
const require_required_capabilities = require("../block-pack/required_capabilities.cjs");
|
|
1
2
|
const require_index = require("../../debug/index.cjs");
|
|
2
3
|
let _milaboratories_ts_helpers = require("@milaboratories/ts-helpers");
|
|
3
4
|
let _milaboratories_pl_client = require("@milaboratories/pl-client");
|
|
@@ -512,7 +513,7 @@ async function loadTemplateCached(pl, spec, options) {
|
|
|
512
513
|
*/
|
|
513
514
|
async function cacheBlockPackTemplate(pl, spec, options) {
|
|
514
515
|
if (spec.template.type === "cached") return spec;
|
|
515
|
-
const resourceId = await loadTemplateCached(pl, spec.template, options);
|
|
516
|
+
const resourceId = spec.template.type === "registry-pack" || spec.template.type === "local-pack" ? await installPackOnClient(pl, spec.template, options) : await loadTemplateCached(pl, spec.template, options);
|
|
516
517
|
return {
|
|
517
518
|
...spec,
|
|
518
519
|
template: {
|
|
@@ -521,6 +522,12 @@ async function cacheBlockPackTemplate(pl, spec, options) {
|
|
|
521
522
|
}
|
|
522
523
|
};
|
|
523
524
|
}
|
|
525
|
+
async function installPackOnClient(pl, template, options) {
|
|
526
|
+
if (options?.preparer === void 0) throw new Error("BUG: a pack needs a preparer to load it");
|
|
527
|
+
const loaded = await options.preparer.loadPack(template);
|
|
528
|
+
require_required_capabilities.throwIfMissingServerCapabilities(pl, loaded.requiredCapabilities);
|
|
529
|
+
return await loadTemplateCached(pl, loaded.template, options);
|
|
530
|
+
}
|
|
524
531
|
exports.ACCESS_COUNT_KEY = ACCESS_COUNT_KEY;
|
|
525
532
|
exports.ACCESS_KEY_PREFIX = ACCESS_KEY_PREFIX;
|
|
526
533
|
exports.GC_ACCESS_THRESHOLD = GC_ACCESS_THRESHOLD;
|