@milaboratories/pl-middle-layer 1.43.17 → 1.43.19
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/js_render/index.cjs +1 -1
- package/dist/js_render/index.cjs.map +1 -1
- package/dist/js_render/index.d.ts.map +1 -1
- package/dist/js_render/index.js +1 -1
- package/dist/js_render/index.js.map +1 -1
- package/dist/middle_layer/active_cfg.cjs +6 -2
- package/dist/middle_layer/active_cfg.cjs.map +1 -1
- package/dist/middle_layer/active_cfg.d.ts.map +1 -1
- package/dist/middle_layer/active_cfg.js +7 -3
- package/dist/middle_layer/active_cfg.js.map +1 -1
- package/dist/middle_layer/project.cjs +3 -0
- package/dist/middle_layer/project.cjs.map +1 -1
- package/dist/middle_layer/project.d.ts +2 -0
- package/dist/middle_layer/project.d.ts.map +1 -1
- package/dist/middle_layer/project.js +3 -0
- package/dist/middle_layer/project.js.map +1 -1
- package/dist/middle_layer/project_overview.cjs +9 -1
- package/dist/middle_layer/project_overview.cjs.map +1 -1
- package/dist/middle_layer/project_overview.d.ts.map +1 -1
- package/dist/middle_layer/project_overview.js +10 -2
- package/dist/middle_layer/project_overview.js.map +1 -1
- package/dist/model/project_helper.cjs.map +1 -1
- package/dist/model/project_helper.js.map +1 -1
- package/dist/mutator/block-pack/block_pack.cjs +20 -10
- package/dist/mutator/block-pack/block_pack.cjs.map +1 -1
- package/dist/mutator/block-pack/block_pack.d.ts.map +1 -1
- package/dist/mutator/block-pack/block_pack.js +20 -10
- package/dist/mutator/block-pack/block_pack.js.map +1 -1
- package/package.json +14 -14
- package/src/js_render/index.ts +2 -1
- package/src/middle_layer/active_cfg.ts +7 -3
- package/src/middle_layer/project.ts +4 -0
- package/src/middle_layer/project_overview.ts +11 -2
- package/src/model/project_helper.ts +1 -1
- package/src/mutator/block-pack/block_pack.ts +26 -13
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project.js","sources":["../../src/middle_layer/project.ts"],"sourcesContent":["import type { MiddleLayerEnvironment } from './middle_layer';\nimport type {\n FieldData,\n OptionalAnyResourceId,\n ResourceId,\n} from '@milaboratories/pl-client';\nimport {\n DefaultRetryOptions,\n ensureResourceIdNotNull,\n field,\n isNotFoundError,\n isTimeoutOrCancelError,\n Pl,\n resourceIdToString,\n} from '@milaboratories/pl-client';\nimport type { ComputableStableDefined, ComputableValueOrErrors } from '@milaboratories/computable';\nimport { Computable } from '@milaboratories/computable';\nimport { projectOverview } from './project_overview';\nimport type { BlockPackSpecAny } from '../model';\nimport { randomUUID } from 'node:crypto';\nimport { withProject, withProjectAuthored } from '../mutator/project';\nimport type { ExtendedResourceData } from '@milaboratories/pl-tree';\nimport { SynchronizedTreeState, treeDumpStats } from '@milaboratories/pl-tree';\nimport { setTimeout } from 'node:timers/promises';\nimport { frontendData } from './frontend_path';\nimport type { NavigationState } from '@milaboratories/pl-model-common';\nimport { blockArgsAndUiState, blockOutputs } from './block';\nimport type { FrontendData } from '../model/frontend';\nimport type { ProjectStructure } from '../model/project_model';\nimport { projectFieldName } from '../model/project_model';\nimport { cachedDeserialize, notEmpty } from '@milaboratories/ts-helpers';\nimport type { BlockPackInfo } from '../model/block_pack';\nimport type {\n ProjectOverview,\n AuthorMarker,\n BlockStateInternal,\n BlockSettings,\n} from '@milaboratories/pl-model-middle-layer';\nimport { activeConfigs } from './active_cfg';\nimport { NavigationStates } from './navigation_states';\nimport { extractConfig } from '@platforma-sdk/model';\nimport fs from 'node:fs/promises';\nimport canonicalize from 'canonicalize';\nimport type { ProjectOverviewLight } from './project_overview_light';\nimport { projectOverviewLight } from './project_overview_light';\nimport { applyProjectMigrations } from '../mutator/migration';\n\ntype BlockStateComputables = {\n readonly fullState: Computable<BlockStateInternal>;\n};\n\nfunction stringifyForDump(object: unknown): string {\n return JSON.stringify(object, (key, value) => {\n if (typeof value === 'bigint')\n return resourceIdToString(value as OptionalAnyResourceId);\n else if (\n ArrayBuffer.isView(value)\n || value instanceof Int8Array\n || value instanceof Uint8Array\n || value instanceof Uint8ClampedArray\n || value instanceof Int16Array\n || value instanceof Uint16Array\n || value instanceof Int32Array\n || value instanceof Uint32Array\n || value instanceof Float32Array\n || value instanceof Float64Array\n || value instanceof BigInt64Array\n || value instanceof BigUint64Array\n )\n return Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString('base64');\n else if (Buffer.isBuffer(value))\n return value.toString('base64');\n\n return value;\n });\n}\n\n/** Data access object, to manipulate and read single opened (!) project data. */\nexport class Project {\n /** Underlying pl resource id */\n public readonly rid: ResourceId;\n\n /** Data for the left panel, contain basic information about block status. */\n public readonly overview: ComputableStableDefined<ProjectOverview>;\n private readonly overviewLight: Computable<ProjectOverviewLight>;\n\n private readonly navigationStates = new NavigationStates();\n // null is set for deleted blocks\n private readonly blockComputables = new Map<string, BlockStateComputables | null>();\n\n private readonly blockFrontends = new Map<string, ComputableStableDefined<FrontendData>>();\n private readonly activeConfigs: Computable<unknown[]>;\n private readonly refreshLoopResult: Promise<void>;\n\n private readonly abortController = new AbortController();\n private destroyed = false;\n\n constructor(\n private readonly env: MiddleLayerEnvironment,\n rid: ResourceId,\n private readonly projectTree: SynchronizedTreeState,\n ) {\n this.overview = projectOverview(\n projectTree.entry(),\n this.navigationStates,\n env,\n ).withPreCalculatedValueTree();\n this.overviewLight = projectOverviewLight(projectTree.entry())\n .withPreCalculatedValueTree();\n this.rid = rid;\n this.refreshLoopResult = this.refreshLoop();\n this.activeConfigs = activeConfigs(projectTree.entry(), env);\n }\n\n get projectLockId(): string {\n return 'project:' + this.rid.toString();\n }\n\n private async refreshLoop(): Promise<void> {\n while (!this.destroyed) {\n try {\n await withProject(this.env.projectHelper, this.env.pl, this.rid, (prj) => {\n prj.doRefresh(this.env.ops.stagingRenderingRate);\n }, { name: 'doRefresh', lockId: this.projectLockId });\n await this.activeConfigs.getValue();\n await setTimeout(this.env.ops.projectRefreshInterval, this.abortController.signal);\n\n // Block computables houskeeping\n const overviewLight = await this.overviewLight.getValue();\n const existingBlocks = new Set(overviewLight.listOfBlocks);\n // Doing cleanup for deleted blocks\n for (const blockId of this.blockComputables.keys()) {\n if (!existingBlocks.has(blockId)) {\n const computable = this.blockComputables.get(blockId);\n if (computable !== undefined && computable !== null) computable.fullState.resetState();\n this.blockComputables.set(blockId, null);\n }\n }\n } catch (e: unknown) {\n if (isNotFoundError(e)) {\n console.warn(\n 'project refresh routine terminated, because project was externally deleted',\n );\n break;\n } else if (!isTimeoutOrCancelError(e))\n throw new Error('Unexpected exception', { cause: e });\n }\n }\n }\n\n /**\n * Adds new block to the project.\n *\n * @param blockLabel block label / title visible to the user\n * @param blockPackSpec object describing the \"block type\", read more in the type docs\n * @param before id of the block to insert new block before\n * @param blockId internal id to be assigned for the block, this arg can be omitted\n * then, randomly generated UUID will be assigned automatically\n *\n * @return returns newly created block id\n * */\n public async addBlock(\n blockLabel: string,\n blockPackSpec: BlockPackSpecAny,\n before?: string,\n author: AuthorMarker | undefined = undefined,\n blockId: string = randomUUID(),\n ): Promise<string> {\n const preparedBp = await this.env.bpPreparer.prepare(blockPackSpec);\n const blockCfgContainer = await this.env.bpPreparer.getBlockConfigContainer(blockPackSpec);\n const blockCfg = extractConfig(blockCfgContainer); // full content of this var should never be persisted\n await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, author, (mut) => {\n return mut.addBlock(\n {\n id: blockId,\n label: blockLabel,\n renderingMode: blockCfg.renderingMode,\n },\n {\n args: canonicalize(blockCfg.initialArgs)!,\n uiState: canonicalize(blockCfg.initialUiState)!,\n blockPack: preparedBp,\n },\n before,\n );\n },\n {\n retryOptions: {\n ...DefaultRetryOptions,\n backoffMultiplier: DefaultRetryOptions.backoffMultiplier * 1.1,\n },\n name: 'addBlock',\n lockId: this.projectLockId,\n });\n\n await this.projectTree.refreshState();\n\n return blockId;\n }\n\n /**\n * Duplicates an existing block by copying all its fields and state.\n * This method works at the mutator level for efficient block copying.\n *\n * @param originalBlockId id of the block to duplicate\n * @param before id of the block to insert new block before\n * @param author author marker for the duplication operation\n * @param newBlockId internal id to be assigned for the duplicated block,\n * if omitted, a randomly generated UUID will be assigned\n *\n * @return returns newly created block id\n * */\n public async duplicateBlock(\n originalBlockId: string,\n before?: string,\n author: AuthorMarker | undefined = undefined,\n newBlockId: string = randomUUID(),\n ): Promise<string> {\n await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, author, (mut) =>\n mut.duplicateBlock(originalBlockId, newBlockId, before),\n { name: 'duplicateBlock', lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n\n return newBlockId;\n }\n\n /**\n * Update block to new block pack, optionally resetting args and ui state to\n * initial values\n * */\n public async updateBlockPack(\n blockId: string,\n blockPackSpec: BlockPackSpecAny,\n resetArgs: boolean = false,\n author?: AuthorMarker,\n ): Promise<void> {\n const preparedBp = await this.env.bpPreparer.prepare(blockPackSpec);\n const blockCfg = extractConfig(await this.env.bpPreparer.getBlockConfigContainer(blockPackSpec));\n await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, author, (mut) =>\n mut.migrateBlockPack(\n blockId,\n preparedBp,\n resetArgs ? { args: blockCfg.initialArgs, uiState: blockCfg.initialUiState } : undefined,\n ),\n { name: 'updateBlockPack', lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /** Deletes a block with all associated data. */\n public async deleteBlock(blockId: string, author?: AuthorMarker): Promise<void> {\n await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, author, (mut) => mut.deleteBlock(blockId), { name: 'deleteBlock', lockId: this.projectLockId });\n this.navigationStates.deleteBlock(blockId);\n await this.projectTree.refreshState();\n }\n\n /**\n * Updates block order according to the given array of block ids.\n *\n * Provided array must contain exactly the same set of ids current project cosists of,\n * an error will be thrown instead.\n */\n public async reorderBlocks(blocks: string[], author?: AuthorMarker): Promise<void> {\n await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, author, (mut) => {\n const currentStructure = mut.structure;\n if (currentStructure.groups.length !== 1)\n throw new Error('Unexpected project structure, non-singular block group');\n const currentGroup = currentStructure.groups[0];\n if (currentGroup.blocks.length !== blocks.length)\n throw new Error(`Length mismatch: ${currentGroup.blocks.length} !== ${blocks.length}`);\n if (new Set<string>(blocks).size !== blocks.length) throw new Error(`Repeated block ids`);\n const newStructure: ProjectStructure = {\n groups: [\n {\n id: currentGroup.id,\n label: currentGroup.label,\n blocks: blocks.map((blockId) => {\n const block = currentGroup.blocks.find((b) => b.id === blockId);\n if (block === undefined) throw new Error(`Can't find block: ${blockId}`);\n return block;\n }),\n },\n ],\n };\n mut.updateStructure(newStructure);\n }, { name: 'reorderBlocks', lockId: this.projectLockId });\n await this.projectTree.refreshState();\n }\n\n /**\n * Renders production part of the block starting all connected heavy computations.\n * Upstream blocks of the specified block will be started automatically if in\n * stale state.\n * */\n public async runBlock(blockId: string): Promise<void> {\n await withProject(this.env.projectHelper, this.env.pl, this.rid, (mut) => mut.renderProduction([blockId], true), { name: 'runBlock', lockId: this.projectLockId });\n await this.projectTree.refreshState();\n }\n\n /**\n * Stops the block if it is running by destroying its production state. All\n * its downstreams will also be destroyed or moved to limbo if already\n * calculated.\n * */\n public async stopBlock(blockId: string): Promise<void> {\n await withProject(this.env.projectHelper, this.env.pl, this.rid, (mut) => mut.stopProduction(blockId), { name: 'stopBlock', lockId: this.projectLockId });\n await this.projectTree.refreshState();\n }\n\n // /** Update block label. */\n // public async setBlockLabel(blockId: string, label: string, author?: AuthorMarker) {\n // await withProjectAuthored(this.env.pl, this.rid, author, (mut) => {\n // mut.setBlockLabel(blockId, label);\n // });\n // await this.projectTree.refreshState();\n // }\n\n /**\n * Sets block args, and changes whole project state accordingly.\n * Along with setting arguments one can specify author marker, that will be\n * transactionally associated with the block, to facilitate conflict resolution\n * in collaborative editing scenario.\n * */\n public async setBlockArgs(blockId: string, args: unknown, author?: AuthorMarker) {\n await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, author, (mut) =>\n mut.setStates([{ blockId, args }]),\n { name: 'setBlockArgs', lockId: this.projectLockId });\n await this.projectTree.refreshState();\n }\n\n /**\n * Sets ui block state associated with the block.\n * Along with setting arguments one can specify author marker, that will be\n * transactionally associated with the block, to facilitate conflict resolution\n * in collaborative editing scenario.\n * */\n public async setUiState(blockId: string, uiState: unknown, author?: AuthorMarker) {\n await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, author, (mut) =>\n mut.setStates([{ blockId, uiState }]),\n { name: 'setUiState', lockId: this.projectLockId });\n await this.projectTree.refreshState();\n }\n\n /**\n * Sets navigation state.\n * */\n // eslint-disable-next-line @typescript-eslint/require-await\n public async setNavigationState(blockId: string, state: NavigationState): Promise<void> {\n this.navigationStates.setState(blockId, state);\n }\n\n /**\n * Sets block args and ui state, and changes the whole project state accordingly.\n * Along with setting arguments one can specify author marker, that will be\n * transactionally associated with the block, to facilitate conflict resolution\n * in collaborative editing scenario.\n * */\n public async setBlockArgsAndUiState(\n blockId: string,\n args: unknown,\n uiState: unknown,\n author?: AuthorMarker,\n ) {\n await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, author, (mut) => {\n mut.setStates([{ blockId, args, uiState }]);\n }, { name: 'setBlockArgsAndUiState', lockId: this.projectLockId });\n await this.projectTree.refreshState();\n }\n\n /** Update block settings */\n public async setBlockSettings(blockId: string, newValue: BlockSettings) {\n await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, undefined, (mut) => {\n mut.setBlockSettings(blockId, newValue);\n }, { name: 'setBlockSettings' });\n await this.projectTree.refreshState();\n }\n\n /** Resets arguments and ui state of the block to initial state */\n public async resetBlockArgsAndUiState(blockId: string, author?: AuthorMarker): Promise<void> {\n await this.env.pl.withWriteTx('BlockInputsReset', async (tx) => {\n // reading default arg values from block pack\n const bpHolderRid = ensureResourceIdNotNull(\n (await tx.getField(field(this.rid, projectFieldName(blockId, 'blockPack')))).value,\n );\n const bpRid = ensureResourceIdNotNull(\n (await tx.getField(field(bpHolderRid, Pl.HolderRefField))).value,\n );\n const bpData = await tx.getResourceData(bpRid, false);\n const config = extractConfig(cachedDeserialize<BlockPackInfo>(notEmpty(bpData.data)).config);\n await withProjectAuthored(this.env.projectHelper, tx, this.rid, author, (prj) => {\n prj.setStates([{ blockId, args: config.initialArgs, uiState: config.initialUiState }]);\n }, { name: 'resetBlockArgsAndUiState', lockId: this.projectLockId });\n await tx.commit();\n });\n await this.projectTree.refreshState();\n }\n\n private getBlockComputables(blockId: string): BlockStateComputables {\n const cached = this.blockComputables.get(blockId);\n if (cached === null) throw new Error(`Block ${blockId} is deleted`);\n if (cached === undefined) {\n // state consists of inputs (args + ui state) and outputs\n const outputs = blockOutputs(this.projectTree.entry(), blockId, this.env);\n const fullState = Computable.make(\n (ctx) => {\n return {\n argsAndUiState: blockArgsAndUiState(this.projectTree.entry(), blockId, ctx),\n outputs,\n navigationState: this.navigationStates.getState(blockId),\n overview: this.overview,\n };\n },\n {\n postprocessValue: (v) => {\n const sdkVersion = v.overview?.blocks?.find((b) => b.id == blockId)?.sdkVersion;\n const toString = sdkVersion && shouldStillUseStringErrors(sdkVersion);\n const newOutputs = toString && v.outputs !== undefined\n ? convertErrorsToStrings(v.outputs)\n : v.outputs;\n\n return {\n ...v.argsAndUiState,\n outputs: newOutputs,\n navigationState: v.navigationState,\n } as BlockStateInternal;\n },\n },\n );\n\n const computables: BlockStateComputables = {\n fullState: fullState.withPreCalculatedValueTree(),\n };\n\n this.blockComputables.set(blockId, computables);\n\n return computables;\n }\n return cached;\n }\n\n /**\n * Returns a computable, that can be used to retrieve and watch full block state,\n * including outputs, arguments, ui state.\n * */\n public getBlockState(blockId: string): Computable<BlockStateInternal> {\n return this.getBlockComputables(blockId).fullState;\n }\n\n /**\n * Returns a computable, that can be used to retrieve and watch path of the\n * folder containing frontend code.\n * */\n public getBlockFrontend(blockId: string): ComputableStableDefined<FrontendData> {\n const cached = this.blockFrontends.get(blockId);\n if (cached === undefined) {\n const fd = frontendData(\n this.projectTree.entry(),\n blockId,\n this.env,\n ).withPreCalculatedValueTree();\n this.blockFrontends.set(blockId, fd);\n return fd;\n }\n return cached;\n }\n\n /** Called by middle layer on close */\n public async destroy(): Promise<void> {\n // terminating the project service loop\n this.destroyed = true;\n this.abortController.abort();\n await this.refreshLoopResult;\n\n // terminating the synchronized project tree\n await this.projectTree.terminate();\n\n // the following will deregister all external resource holders, like\n // downloaded files, running uploads and alike\n this.overview.resetState();\n this.blockFrontends.forEach((c) => c.resetState());\n this.blockComputables.forEach((c) => {\n if (c !== null) c.fullState.resetState();\n });\n this.activeConfigs.resetState();\n }\n\n /** @deprecated */\n public async destroyAndAwaitTermination(): Promise<void> {\n await this.destroy();\n }\n\n public static async init(env: MiddleLayerEnvironment, rid: ResourceId): Promise<Project> {\n // Applying migrations to the project resource, if needed\n await applyProjectMigrations(env.pl, rid);\n\n // Doing a no-op mutation to apply all migration and schema fixes\n await withProject(env.projectHelper, env.pl, rid, (_) => {}, { name: 'init' });\n\n // Loading project tree\n const projectTree = await SynchronizedTreeState.init(\n env.pl,\n rid,\n {\n ...env.ops.defaultTreeOptions,\n pruning: projectTreePruning,\n },\n env.logger,\n );\n\n if (env.ops.debugOps.dumpInitialTreeState) {\n const state = projectTree.dumpState();\n state.sort((a, b) => (b.data?.byteLength ?? 0) - (a.data?.byteLength ?? 0));\n const stats = treeDumpStats(state);\n await fs.writeFile(`${resourceIdToString(rid)}.json`, stringifyForDump(state));\n await fs.writeFile(`${resourceIdToString(rid)}.stats.json`, stringifyForDump(stats));\n }\n\n return new Project(env, rid, projectTree);\n }\n}\n\nfunction projectTreePruning(r: ExtendedResourceData): FieldData[] {\n // console.log(\n // JSON.stringify(\n // { ...r, kv: [], data: undefined } satisfies ExtendedResourceData,\n // (_, v) => {\n // if (typeof v === 'bigint') return v.toString();\n // return v;\n // }\n // )\n // );\n if (r.type.name.startsWith('StreamWorkdir/'))\n return [];\n switch (r.type.name) {\n case 'BlockPackCustom':\n return r.fields.filter((f) => f.name !== 'template');\n case 'UserProject':\n return r.fields.filter((f) => !f.name.startsWith('__serviceTemplate'));\n case 'Blob':\n return [];\n default:\n return r.fields;\n }\n}\n\n/** Returns true if sdk version of the block is old and we need to convert\n * ErrorLike errors to strings like it was.\n * We need it for keeping old blocks and new UI compatibility. */\nfunction shouldStillUseStringErrors(sdkVersion: string): boolean {\n return !isVersionGreater(sdkVersion, '1.26.0');\n}\n\n/** Checks if sdk version is greater that a target version. */\nfunction isVersionGreater(sdkVersion: string, targetVersion: string): boolean {\n const version = sdkVersion.split('.').map(Number);\n const target = targetVersion.split('.').map(Number);\n\n return (\n version[0] > target[0]\n || (version[0] === target[0] && version[1] > target[1])\n || (version[0] === target[0] && version[1] === target[1] && version[2] > target[2])\n );\n};\n\n/** Converts ErrorLike errors to strings in the outputs like it was in old ML versions. */\nfunction convertErrorsToStrings(\n outputs: Record<string, ComputableValueOrErrors<unknown>>,\n): Record<string, ComputableValueOrErrors<unknown>> {\n const result: Record<string, ComputableValueOrErrors<unknown>> = {};\n for (const [key, val] of Object.entries(outputs)) {\n if (val.ok) {\n result[key] = val;\n continue;\n }\n\n result[key] = {\n ok: false,\n errors: val.errors.map((e) => {\n if (typeof e === 'string') {\n return e;\n } else if (e.type == 'PlError' && e.fullMessage !== undefined) {\n return e.fullMessage;\n }\n return e.message;\n }),\n moreErrors: val.moreErrors,\n };\n }\n\n return result;\n}\n"],"names":["fs"],"mappings":";;;;;;;;;;;;;;;;;;;AAmDA,SAAS,gBAAgB,CAAC,MAAe,EAAA;IACvC,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,KAAK,KAAI;QAC3C,IAAI,OAAO,KAAK,KAAK,QAAQ;AAC3B,YAAA,OAAO,kBAAkB,CAAC,KAA8B,CAAC;AACtD,aAAA,IACH,WAAW,CAAC,MAAM,CAAC,KAAK;AACrB,eAAA,KAAK,YAAY;AACjB,eAAA,KAAK,YAAY;AACjB,eAAA,KAAK,YAAY;AACjB,eAAA,KAAK,YAAY;AACjB,eAAA,KAAK,YAAY;AACjB,eAAA,KAAK,YAAY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|
+
{"version":3,"file":"project.js","sources":["../../src/middle_layer/project.ts"],"sourcesContent":["import type { MiddleLayerEnvironment } from './middle_layer';\nimport type {\n FieldData,\n OptionalAnyResourceId,\n ResourceId,\n} from '@milaboratories/pl-client';\nimport {\n DefaultRetryOptions,\n ensureResourceIdNotNull,\n field,\n isNotFoundError,\n isTimeoutOrCancelError,\n Pl,\n resourceIdToString,\n} from '@milaboratories/pl-client';\nimport type { ComputableStableDefined, ComputableValueOrErrors } from '@milaboratories/computable';\nimport { Computable } from '@milaboratories/computable';\nimport { projectOverview } from './project_overview';\nimport type { BlockPackSpecAny } from '../model';\nimport { randomUUID } from 'node:crypto';\nimport { withProject, withProjectAuthored } from '../mutator/project';\nimport type { ExtendedResourceData } from '@milaboratories/pl-tree';\nimport { SynchronizedTreeState, treeDumpStats } from '@milaboratories/pl-tree';\nimport { setTimeout } from 'node:timers/promises';\nimport { frontendData } from './frontend_path';\nimport type { NavigationState } from '@milaboratories/pl-model-common';\nimport { blockArgsAndUiState, blockOutputs } from './block';\nimport type { FrontendData } from '../model/frontend';\nimport type { ProjectStructure } from '../model/project_model';\nimport { projectFieldName } from '../model/project_model';\nimport { cachedDeserialize, notEmpty } from '@milaboratories/ts-helpers';\nimport type { BlockPackInfo } from '../model/block_pack';\nimport type {\n ProjectOverview,\n AuthorMarker,\n BlockStateInternal,\n BlockSettings,\n} from '@milaboratories/pl-model-middle-layer';\nimport { activeConfigs } from './active_cfg';\nimport { NavigationStates } from './navigation_states';\nimport { extractConfig } from '@platforma-sdk/model';\nimport fs from 'node:fs/promises';\nimport canonicalize from 'canonicalize';\nimport type { ProjectOverviewLight } from './project_overview_light';\nimport { projectOverviewLight } from './project_overview_light';\nimport { applyProjectMigrations } from '../mutator/migration';\n\ntype BlockStateComputables = {\n readonly fullState: Computable<BlockStateInternal>;\n};\n\nfunction stringifyForDump(object: unknown): string {\n return JSON.stringify(object, (key, value) => {\n if (typeof value === 'bigint')\n return resourceIdToString(value as OptionalAnyResourceId);\n else if (\n ArrayBuffer.isView(value)\n || value instanceof Int8Array\n || value instanceof Uint8Array\n || value instanceof Uint8ClampedArray\n || value instanceof Int16Array\n || value instanceof Uint16Array\n || value instanceof Int32Array\n || value instanceof Uint32Array\n || value instanceof Float32Array\n || value instanceof Float64Array\n || value instanceof BigInt64Array\n || value instanceof BigUint64Array\n )\n return Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString('base64');\n else if (Buffer.isBuffer(value))\n return value.toString('base64');\n\n return value;\n });\n}\n\n/** Data access object, to manipulate and read single opened (!) project data. */\nexport class Project {\n /** Underlying pl resource id */\n public readonly rid: ResourceId;\n\n /** Data for the left panel, contain basic information about block status. */\n public readonly overview: ComputableStableDefined<ProjectOverview>;\n private readonly overviewLight: Computable<ProjectOverviewLight>;\n\n private readonly navigationStates = new NavigationStates();\n // null is set for deleted blocks\n private readonly blockComputables = new Map<string, BlockStateComputables | null>();\n\n private readonly blockFrontends = new Map<string, ComputableStableDefined<FrontendData>>();\n private readonly activeConfigs: Computable<unknown[]>;\n private readonly refreshLoopResult: Promise<void>;\n\n private readonly abortController = new AbortController();\n private destroyed = false;\n\n constructor(\n private readonly env: MiddleLayerEnvironment,\n rid: ResourceId,\n private readonly projectTree: SynchronizedTreeState,\n ) {\n this.overview = projectOverview(\n projectTree.entry(),\n this.navigationStates,\n env,\n ).withPreCalculatedValueTree();\n this.overviewLight = projectOverviewLight(projectTree.entry())\n .withPreCalculatedValueTree();\n this.rid = rid;\n this.refreshLoopResult = this.refreshLoop();\n this.activeConfigs = activeConfigs(projectTree.entry(), env);\n }\n\n get projectLockId(): string {\n return 'project:' + this.rid.toString();\n }\n\n private async refreshLoop(): Promise<void> {\n while (!this.destroyed) {\n try {\n await withProject(this.env.projectHelper, this.env.pl, this.rid, (prj) => {\n prj.doRefresh(this.env.ops.stagingRenderingRate);\n }, { name: 'doRefresh', lockId: this.projectLockId });\n await this.activeConfigs.getValue();\n await setTimeout(this.env.ops.projectRefreshInterval, this.abortController.signal);\n\n // Block computables houskeeping\n const overviewLight = await this.overviewLight.getValue();\n const existingBlocks = new Set(overviewLight.listOfBlocks);\n // Doing cleanup for deleted blocks\n for (const blockId of this.blockComputables.keys()) {\n if (!existingBlocks.has(blockId)) {\n const computable = this.blockComputables.get(blockId);\n if (computable !== undefined && computable !== null) computable.fullState.resetState();\n this.blockComputables.set(blockId, null);\n }\n }\n } catch (e: unknown) {\n if (isNotFoundError(e)) {\n console.warn(\n 'project refresh routine terminated, because project was externally deleted',\n );\n break;\n } else if (!isTimeoutOrCancelError(e))\n throw new Error('Unexpected exception', { cause: e });\n }\n }\n }\n\n /**\n * Adds new block to the project.\n *\n * @param blockLabel block label / title visible to the user\n * @param blockPackSpec object describing the \"block type\", read more in the type docs\n * @param before id of the block to insert new block before\n * @param blockId internal id to be assigned for the block, this arg can be omitted\n * then, randomly generated UUID will be assigned automatically\n *\n * @return returns newly created block id\n * */\n public async addBlock(\n blockLabel: string,\n blockPackSpec: BlockPackSpecAny,\n before?: string,\n author: AuthorMarker | undefined = undefined,\n blockId: string = randomUUID(),\n ): Promise<string> {\n const preparedBp = await this.env.bpPreparer.prepare(blockPackSpec);\n const blockCfgContainer = await this.env.bpPreparer.getBlockConfigContainer(blockPackSpec);\n const blockCfg = extractConfig(blockCfgContainer); // full content of this var should never be persisted\n await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, author, (mut) => {\n return mut.addBlock(\n {\n id: blockId,\n label: blockLabel,\n renderingMode: blockCfg.renderingMode,\n },\n {\n args: canonicalize(blockCfg.initialArgs)!,\n uiState: canonicalize(blockCfg.initialUiState)!,\n blockPack: preparedBp,\n },\n before,\n );\n },\n {\n retryOptions: {\n ...DefaultRetryOptions,\n backoffMultiplier: DefaultRetryOptions.backoffMultiplier * 1.1,\n },\n name: 'addBlock',\n lockId: this.projectLockId,\n });\n\n await this.projectTree.refreshState();\n\n return blockId;\n }\n\n /**\n * Duplicates an existing block by copying all its fields and state.\n * This method works at the mutator level for efficient block copying.\n *\n * @param originalBlockId id of the block to duplicate\n * @param before id of the block to insert new block before\n * @param author author marker for the duplication operation\n * @param newBlockId internal id to be assigned for the duplicated block,\n * if omitted, a randomly generated UUID will be assigned\n *\n * @return returns newly created block id\n * */\n public async duplicateBlock(\n originalBlockId: string,\n before?: string,\n author: AuthorMarker | undefined = undefined,\n newBlockId: string = randomUUID(),\n ): Promise<string> {\n await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, author, (mut) =>\n mut.duplicateBlock(originalBlockId, newBlockId, before),\n { name: 'duplicateBlock', lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n\n return newBlockId;\n }\n\n /**\n * Update block to new block pack, optionally resetting args and ui state to\n * initial values\n * */\n public async updateBlockPack(\n blockId: string,\n blockPackSpec: BlockPackSpecAny,\n resetArgs: boolean = false,\n author?: AuthorMarker,\n ): Promise<void> {\n const preparedBp = await this.env.bpPreparer.prepare(blockPackSpec);\n const blockCfg = extractConfig(await this.env.bpPreparer.getBlockConfigContainer(blockPackSpec));\n await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, author, (mut) =>\n mut.migrateBlockPack(\n blockId,\n preparedBp,\n resetArgs ? { args: blockCfg.initialArgs, uiState: blockCfg.initialUiState } : undefined,\n ),\n { name: 'updateBlockPack', lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /** Deletes a block with all associated data. */\n public async deleteBlock(blockId: string, author?: AuthorMarker): Promise<void> {\n await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, author, (mut) => mut.deleteBlock(blockId), { name: 'deleteBlock', lockId: this.projectLockId });\n this.navigationStates.deleteBlock(blockId);\n await this.projectTree.refreshState();\n }\n\n /**\n * Updates block order according to the given array of block ids.\n *\n * Provided array must contain exactly the same set of ids current project cosists of,\n * an error will be thrown instead.\n */\n public async reorderBlocks(blocks: string[], author?: AuthorMarker): Promise<void> {\n await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, author, (mut) => {\n const currentStructure = mut.structure;\n if (currentStructure.groups.length !== 1)\n throw new Error('Unexpected project structure, non-singular block group');\n const currentGroup = currentStructure.groups[0];\n if (currentGroup.blocks.length !== blocks.length)\n throw new Error(`Length mismatch: ${currentGroup.blocks.length} !== ${blocks.length}`);\n if (new Set<string>(blocks).size !== blocks.length) throw new Error(`Repeated block ids`);\n const newStructure: ProjectStructure = {\n groups: [\n {\n id: currentGroup.id,\n label: currentGroup.label,\n blocks: blocks.map((blockId) => {\n const block = currentGroup.blocks.find((b) => b.id === blockId);\n if (block === undefined) throw new Error(`Can't find block: ${blockId}`);\n return block;\n }),\n },\n ],\n };\n mut.updateStructure(newStructure);\n }, { name: 'reorderBlocks', lockId: this.projectLockId });\n await this.projectTree.refreshState();\n }\n\n /**\n * Renders production part of the block starting all connected heavy computations.\n * Upstream blocks of the specified block will be started automatically if in\n * stale state.\n * */\n public async runBlock(blockId: string): Promise<void> {\n await withProject(this.env.projectHelper, this.env.pl, this.rid, (mut) => mut.renderProduction([blockId], true), { name: 'runBlock', lockId: this.projectLockId });\n await this.projectTree.refreshState();\n }\n\n /**\n * Stops the block if it is running by destroying its production state. All\n * its downstreams will also be destroyed or moved to limbo if already\n * calculated.\n * */\n public async stopBlock(blockId: string): Promise<void> {\n await withProject(this.env.projectHelper, this.env.pl, this.rid, (mut) => mut.stopProduction(blockId), { name: 'stopBlock', lockId: this.projectLockId });\n await this.projectTree.refreshState();\n }\n\n // /** Update block label. */\n // public async setBlockLabel(blockId: string, label: string, author?: AuthorMarker) {\n // await withProjectAuthored(this.env.pl, this.rid, author, (mut) => {\n // mut.setBlockLabel(blockId, label);\n // });\n // await this.projectTree.refreshState();\n // }\n\n /**\n * Sets block args, and changes whole project state accordingly.\n * Along with setting arguments one can specify author marker, that will be\n * transactionally associated with the block, to facilitate conflict resolution\n * in collaborative editing scenario.\n * */\n public async setBlockArgs(blockId: string, args: unknown, author?: AuthorMarker) {\n await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, author, (mut) =>\n mut.setStates([{ blockId, args }]),\n { name: 'setBlockArgs', lockId: this.projectLockId });\n await this.projectTree.refreshState();\n }\n\n /**\n * Sets ui block state associated with the block.\n * Along with setting arguments one can specify author marker, that will be\n * transactionally associated with the block, to facilitate conflict resolution\n * in collaborative editing scenario.\n * */\n public async setUiState(blockId: string, uiState: unknown, author?: AuthorMarker) {\n await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, author, (mut) =>\n mut.setStates([{ blockId, uiState }]),\n { name: 'setUiState', lockId: this.projectLockId });\n await this.projectTree.refreshState();\n }\n\n /**\n * Sets navigation state.\n * */\n // eslint-disable-next-line @typescript-eslint/require-await\n public async setNavigationState(blockId: string, state: NavigationState): Promise<void> {\n this.navigationStates.setState(blockId, state);\n }\n\n /**\n * Sets block args and ui state, and changes the whole project state accordingly.\n * Along with setting arguments one can specify author marker, that will be\n * transactionally associated with the block, to facilitate conflict resolution\n * in collaborative editing scenario.\n * */\n public async setBlockArgsAndUiState(\n blockId: string,\n args: unknown,\n uiState: unknown,\n author?: AuthorMarker,\n ) {\n await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, author, (mut) => {\n mut.setStates([{ blockId, args, uiState }]);\n }, { name: 'setBlockArgsAndUiState', lockId: this.projectLockId });\n await this.projectTree.refreshState();\n }\n\n /** Update block settings */\n public async setBlockSettings(blockId: string, newValue: BlockSettings) {\n await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, undefined, (mut) => {\n mut.setBlockSettings(blockId, newValue);\n }, { name: 'setBlockSettings' });\n await this.projectTree.refreshState();\n }\n\n /** Resets arguments and ui state of the block to initial state */\n public async resetBlockArgsAndUiState(blockId: string, author?: AuthorMarker): Promise<void> {\n await this.env.pl.withWriteTx('BlockInputsReset', async (tx) => {\n // reading default arg values from block pack\n const bpHolderRid = ensureResourceIdNotNull(\n (await tx.getField(field(this.rid, projectFieldName(blockId, 'blockPack')))).value,\n );\n const bpRid = ensureResourceIdNotNull(\n (await tx.getField(field(bpHolderRid, Pl.HolderRefField))).value,\n );\n const bpData = await tx.getResourceData(bpRid, false);\n const config = extractConfig(cachedDeserialize<BlockPackInfo>(notEmpty(bpData.data)).config);\n await withProjectAuthored(this.env.projectHelper, tx, this.rid, author, (prj) => {\n prj.setStates([{ blockId, args: config.initialArgs, uiState: config.initialUiState }]);\n }, { name: 'resetBlockArgsAndUiState', lockId: this.projectLockId });\n await tx.commit();\n });\n await this.projectTree.refreshState();\n }\n\n private getBlockComputables(blockId: string): BlockStateComputables {\n const cached = this.blockComputables.get(blockId);\n if (cached === null) throw new Error(`Block ${blockId} is deleted`);\n if (cached === undefined) {\n // state consists of inputs (args + ui state) and outputs\n const outputs = blockOutputs(this.projectTree.entry(), blockId, this.env);\n const fullState = Computable.make(\n (ctx) => {\n return {\n argsAndUiState: blockArgsAndUiState(this.projectTree.entry(), blockId, ctx),\n outputs,\n navigationState: this.navigationStates.getState(blockId),\n overview: this.overview,\n };\n },\n {\n postprocessValue: (v) => {\n const sdkVersion = v.overview?.blocks?.find((b) => b.id == blockId)?.sdkVersion;\n const toString = sdkVersion && shouldStillUseStringErrors(sdkVersion);\n const newOutputs = toString && v.outputs !== undefined\n ? convertErrorsToStrings(v.outputs)\n : v.outputs;\n\n return {\n ...v.argsAndUiState,\n outputs: newOutputs,\n navigationState: v.navigationState,\n } as BlockStateInternal;\n },\n },\n );\n\n const computables: BlockStateComputables = {\n fullState: fullState.withPreCalculatedValueTree(),\n };\n\n this.blockComputables.set(blockId, computables);\n\n return computables;\n }\n return cached;\n }\n\n /**\n * Returns a computable, that can be used to retrieve and watch full block state,\n * including outputs, arguments, ui state.\n * */\n public getBlockState(blockId: string): Computable<BlockStateInternal> {\n return this.getBlockComputables(blockId).fullState;\n }\n\n /**\n * Returns a computable, that can be used to retrieve and watch path of the\n * folder containing frontend code.\n * */\n public getBlockFrontend(blockId: string): ComputableStableDefined<FrontendData> {\n const cached = this.blockFrontends.get(blockId);\n if (cached === undefined) {\n const fd = frontendData(\n this.projectTree.entry(),\n blockId,\n this.env,\n ).withPreCalculatedValueTree();\n this.blockFrontends.set(blockId, fd);\n return fd;\n }\n return cached;\n }\n\n /** Called by middle layer on close */\n public async destroy(): Promise<void> {\n // terminating the project service loop\n this.destroyed = true;\n this.abortController.abort();\n await this.refreshLoopResult;\n\n // terminating the synchronized project tree\n await this.projectTree.terminate();\n\n // the following will deregister all external resource holders, like\n // downloaded files, running uploads and alike\n this.overview.resetState();\n this.blockFrontends.forEach((c) => c.resetState());\n this.blockComputables.forEach((c) => {\n if (c !== null) c.fullState.resetState();\n });\n this.activeConfigs.resetState();\n }\n\n /** @deprecated */\n public async destroyAndAwaitTermination(): Promise<void> {\n await this.destroy();\n }\n\n public dumpState(): ExtendedResourceData[] {\n return this.projectTree.dumpState();\n }\n\n public static async init(env: MiddleLayerEnvironment, rid: ResourceId): Promise<Project> {\n // Applying migrations to the project resource, if needed\n await applyProjectMigrations(env.pl, rid);\n\n // Doing a no-op mutation to apply all migration and schema fixes\n await withProject(env.projectHelper, env.pl, rid, (_) => {}, { name: 'init' });\n\n // Loading project tree\n const projectTree = await SynchronizedTreeState.init(\n env.pl,\n rid,\n {\n ...env.ops.defaultTreeOptions,\n pruning: projectTreePruning,\n },\n env.logger,\n );\n\n if (env.ops.debugOps.dumpInitialTreeState) {\n const state = projectTree.dumpState();\n state.sort((a, b) => (b.data?.byteLength ?? 0) - (a.data?.byteLength ?? 0));\n const stats = treeDumpStats(state);\n await fs.writeFile(`${resourceIdToString(rid)}.json`, stringifyForDump(state));\n await fs.writeFile(`${resourceIdToString(rid)}.stats.json`, stringifyForDump(stats));\n }\n\n return new Project(env, rid, projectTree);\n }\n}\n\nfunction projectTreePruning(r: ExtendedResourceData): FieldData[] {\n // console.log(\n // JSON.stringify(\n // { ...r, kv: [], data: undefined } satisfies ExtendedResourceData,\n // (_, v) => {\n // if (typeof v === 'bigint') return v.toString();\n // return v;\n // }\n // )\n // );\n if (r.type.name.startsWith('StreamWorkdir/'))\n return [];\n switch (r.type.name) {\n case 'BlockPackCustom':\n return r.fields.filter((f) => f.name !== 'template');\n case 'UserProject':\n return r.fields.filter((f) => !f.name.startsWith('__serviceTemplate'));\n case 'Blob':\n return [];\n default:\n return r.fields;\n }\n}\n\n/** Returns true if sdk version of the block is old and we need to convert\n * ErrorLike errors to strings like it was.\n * We need it for keeping old blocks and new UI compatibility. */\nfunction shouldStillUseStringErrors(sdkVersion: string): boolean {\n return !isVersionGreater(sdkVersion, '1.26.0');\n}\n\n/** Checks if sdk version is greater that a target version. */\nfunction isVersionGreater(sdkVersion: string, targetVersion: string): boolean {\n const version = sdkVersion.split('.').map(Number);\n const target = targetVersion.split('.').map(Number);\n\n return (\n version[0] > target[0]\n || (version[0] === target[0] && version[1] > target[1])\n || (version[0] === target[0] && version[1] === target[1] && version[2] > target[2])\n );\n};\n\n/** Converts ErrorLike errors to strings in the outputs like it was in old ML versions. */\nfunction convertErrorsToStrings(\n outputs: Record<string, ComputableValueOrErrors<unknown>>,\n): Record<string, ComputableValueOrErrors<unknown>> {\n const result: Record<string, ComputableValueOrErrors<unknown>> = {};\n for (const [key, val] of Object.entries(outputs)) {\n if (val.ok) {\n result[key] = val;\n continue;\n }\n\n result[key] = {\n ok: false,\n errors: val.errors.map((e) => {\n if (typeof e === 'string') {\n return e;\n } else if (e.type == 'PlError' && e.fullMessage !== undefined) {\n return e.fullMessage;\n }\n return e.message;\n }),\n moreErrors: val.moreErrors,\n };\n }\n\n return result;\n}\n"],"names":["fs"],"mappings":";;;;;;;;;;;;;;;;;;;AAmDA,SAAS,gBAAgB,CAAC,MAAe,EAAA;IACvC,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,KAAK,KAAI;QAC3C,IAAI,OAAO,KAAK,KAAK,QAAQ;AAC3B,YAAA,OAAO,kBAAkB,CAAC,KAA8B,CAAC;AACtD,aAAA,IACH,WAAW,CAAC,MAAM,CAAC,KAAK;AACrB,eAAA,KAAK,YAAY;AACjB,eAAA,KAAK,YAA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AAO,CAAC,CAAC,WAAW;gBACtB;gBACA,OAAO,CAAC,CAAC,OAAO;AAClB,YAAA,CAAC,CAAC;YACF,UAAU,EAAE,GAAG,CAAC,UAAU;SAC3B;IACH;AAEA,IAAA,OAAO,MAAM;AACf;;;;"}
|
|
@@ -120,7 +120,15 @@ function projectOverview(prjEntry, navigationStates, env) {
|
|
|
120
120
|
};
|
|
121
121
|
}
|
|
122
122
|
const blockCtxArgsOnly = block_ctx.constructBlockContextArgsOnly(prjEntry, id);
|
|
123
|
-
const
|
|
123
|
+
const codeWithInfoOrError = model.wrapCallback(() => model.extractCodeWithInfo(cfg));
|
|
124
|
+
if (codeWithInfoOrError.error) {
|
|
125
|
+
return {
|
|
126
|
+
title: codeWithInfoOrError.error.message,
|
|
127
|
+
isIncompatibleWithRuntime: true,
|
|
128
|
+
featureFlags: cfg.featureFlags,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
const codeWithInfo = codeWithInfoOrError.value;
|
|
124
132
|
return {
|
|
125
133
|
sections: render.computableFromCfgOrRF(env, blockCtxArgsOnly, cfg.sections, codeWithInfo, bpId).wrap({
|
|
126
134
|
recover: (e) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project_overview.cjs","sources":["../../src/middle_layer/project_overview.ts"],"sourcesContent":["import type { PlTreeEntry } from '@milaboratories/pl-tree';\nimport type { ComputableStableDefined } from '@milaboratories/computable';\nimport { Computable } from '@milaboratories/computable';\nimport type {\n ProjectRenderingState,\n ProjectStructure } from '../model/project_model';\nimport {\n BlockRenderingStateKey,\n ProjectCreatedTimestamp,\n projectFieldName,\n ProjectLastModifiedTimestamp,\n ProjectMetaKey,\n ProjectStructureAuthorKey,\n ProjectStructureKey,\n} from '../model/project_model';\nimport { notEmpty } from '@milaboratories/ts-helpers';\nimport { allBlocks, productionGraph } from '../model/project_model_util';\nimport type { MiddleLayerEnvironment } from './middle_layer';\nimport type {\n AuthorMarker,\n BlockCalculationStatus,\n BlockSettings,\n ProjectMeta,\n ProjectOverview,\n} from '@milaboratories/pl-model-middle-layer';\nimport { constructBlockContextArgsOnly } from './block_ctx';\nimport { ifNotUndef } from '../cfg_render/util';\nimport { extractCodeWithInfo, type BlockSection } from '@platforma-sdk/model';\nimport { computableFromCfgOrRF } from './render';\nimport type { NavigationStates } from './navigation_states';\nimport { getBlockPackInfo } from './util';\nimport { resourceIdToString, type ResourceId } from '@milaboratories/pl-client';\nimport * as R from 'remeda';\n\ntype BlockInfo = {\n argsRid: ResourceId;\n currentArguments: unknown;\n prod?: ProdState;\n};\n\ntype _CalculationStatus = 'Running' | 'Done';\n\ntype ProdState = {\n finished: boolean;\n\n outputError: boolean;\n\n outputsError?: string;\n\n exportsError?: string;\n\n stale: boolean;\n\n /** Arguments current production was rendered with. */\n arguments: Record<string, unknown>;\n};\n\nfunction argsEquals(a: Record<string, unknown> | undefined, b: Record<string, unknown> | undefined): boolean {\n if (a === b) return true;\n if (a === undefined || b === undefined) return false;\n const clean = R.omitBy<Record<string, unknown>>((_, key) => key.startsWith('__'));\n return R.isDeepEqual(clean(a), clean(b));\n}\n\n/** Returns derived general project state form the project resource */\nexport function projectOverview(\n prjEntry: PlTreeEntry,\n navigationStates: NavigationStates,\n env: MiddleLayerEnvironment,\n): ComputableStableDefined<ProjectOverview> {\n return Computable.make(\n (ctx) => {\n const prj = ctx.accessor(prjEntry).node();\n\n const created = notEmpty(prj.getKeyValueAsJson<number>(ProjectCreatedTimestamp));\n const lastModified = notEmpty(prj.getKeyValueAsJson<number>(ProjectLastModifiedTimestamp));\n\n const meta = notEmpty(prj.getKeyValueAsJson<ProjectMeta>(ProjectMetaKey));\n const structure = notEmpty(prj.getKeyValueAsJson<ProjectStructure>(ProjectStructureKey));\n const renderingState = notEmpty(\n prj.getKeyValueAsJson<ProjectRenderingState>(BlockRenderingStateKey),\n );\n\n const infos = new Map<string, BlockInfo>();\n for (const { id } of allBlocks(structure)) {\n const cInputs = prj.traverse({\n field: projectFieldName(id, 'currentArgs'),\n assertFieldType: 'Dynamic',\n errorIfFieldNotSet: true,\n });\n const currentArguments = cInputs.getDataAsJson() as Record<string, unknown>;\n\n let prod: ProdState | undefined = undefined;\n\n const rInputs = prj.traverse({\n field: projectFieldName(id, 'prodArgs'),\n assertFieldType: 'Dynamic',\n stableIfNotFound: true,\n });\n if (rInputs !== undefined) {\n const prodArgs = rInputs.getDataAsJson() as Record<string, unknown>;\n const result = prj.getField({\n field: projectFieldName(id, 'prodOutput'),\n assertFieldType: 'Dynamic',\n errorIfFieldNotFound: true,\n });\n const ctx = prj.getField({\n field: projectFieldName(id, 'prodUiCtx'),\n assertFieldType: 'Dynamic',\n errorIfFieldNotFound: true,\n });\n prod = {\n arguments: prodArgs,\n stale: !argsEquals(currentArguments, prodArgs),\n outputError:\n result.error !== undefined\n || ctx.error !== undefined\n || result.value?.getError() !== undefined\n || ctx.value?.getError() !== undefined,\n outputsError:\n result.error?.getDataAsString() ?? result.value?.getError()?.getDataAsString(),\n exportsError: ctx.error?.getDataAsString() ?? ctx.value?.getError()?.getDataAsString(),\n finished:\n ((result.value !== undefined && result.value.getIsReadyOrError())\n || (result.error !== undefined && result.error.getIsReadyOrError()))\n && ((ctx.value !== undefined && ctx.value.getIsReadyOrError())\n || (ctx.error !== undefined && ctx.error.getIsReadyOrError())),\n };\n }\n\n infos.set(id, { currentArguments, prod, argsRid: cInputs.resourceInfo.id });\n }\n\n const currentGraph = productionGraph(structure, (id) => {\n const bpInfo = getBlockPackInfo(prj, id)!;\n const bInfo = infos.get(id)!;\n const args = bInfo.currentArguments;\n return {\n args,\n enrichmentTargets: env.projectHelper.getEnrichmentTargets(() => bpInfo.cfg, () => args, { argsRid: bInfo.argsRid, blockPackRid: bpInfo.bpResourceId }),\n };\n });\n\n const limbo = new Set(renderingState.blocksInLimbo);\n\n const blocks = [...allBlocks(structure)].map(({ id, label: defaultLabel, renderingMode }) => {\n const info = notEmpty(infos.get(id));\n const gNode = notEmpty(currentGraph.nodes.get(id));\n let calculationStatus: BlockCalculationStatus = 'NotCalculated';\n if (info.prod !== undefined) {\n if (limbo.has(id)) calculationStatus = 'Limbo';\n else calculationStatus = info.prod.finished ? 'Done' : 'Running';\n }\n\n const bp = getBlockPackInfo(prj, id);\n\n const { sections, title, inputsValid, sdkVersion, featureFlags, isIncompatibleWithRuntime }\n = ifNotUndef(bp, ({ bpId, cfg }) => {\n if (!env.runtimeCapabilities.checkCompatibility(cfg.featureFlags)) {\n return {\n isIncompatibleWithRuntime: true,\n featureFlags: cfg.featureFlags,\n };\n }\n const blockCtxArgsOnly = constructBlockContextArgsOnly(prjEntry, id);\n const codeWithInfo = extractCodeWithInfo(cfg);\n return {\n sections: computableFromCfgOrRF(\n env,\n blockCtxArgsOnly,\n cfg.sections,\n codeWithInfo,\n bpId,\n ).wrap({\n recover: (e) => {\n env.logger.error('Error in block model sections');\n env.logger.error(e);\n return [];\n },\n }) as ComputableStableDefined<BlockSection[]>,\n title: ifNotUndef(\n cfg.title,\n (title) =>\n computableFromCfgOrRF(\n env,\n blockCtxArgsOnly,\n title,\n codeWithInfo,\n bpId,\n ).wrap({\n recover: (e) => {\n env.logger.error('Error in block model title');\n env.logger.error(e);\n return 'Invalid title';\n },\n }) as ComputableStableDefined<string>,\n ),\n inputsValid: computableFromCfgOrRF(\n env,\n blockCtxArgsOnly,\n cfg.inputsValid,\n codeWithInfo,\n bpId,\n ).wrap({\n recover: (e) => {\n // I'm not sure that we should write an error here, because it just means \"Invalid args\"\n env.logger.error('Error in block model argsValid');\n env.logger.error(e);\n return false;\n },\n }) as ComputableStableDefined<boolean>,\n sdkVersion: codeWithInfo?.sdkVersion,\n featureFlags: codeWithInfo?.featureFlags ?? {},\n isIncompatibleWithRuntime: false,\n };\n }) || {};\n\n const settings = prj\n .traverse({\n field: projectFieldName(id, 'blockSettings'),\n assertFieldType: 'Dynamic',\n errorIfFieldNotSet: true,\n })\n .getDataAsJson() as BlockSettings;\n\n const updates = ifNotUndef(bp, ({ info }) =>\n env.blockUpdateWatcher.get({ currentSpec: info.source, settings }),\n );\n\n return {\n projectResourceId: resourceIdToString(prjEntry.rid),\n id,\n label: title ?? defaultLabel,\n title: title ?? defaultLabel,\n renderingMode,\n stale: info.prod?.stale !== false || calculationStatus === 'Limbo',\n missingReference: gNode.missingReferences,\n upstreams: [...currentGraph.traverseIdsExcludingRoots('upstream', id)],\n downstreams: [...currentGraph.traverseIdsExcludingRoots('downstream', id)],\n calculationStatus,\n outputErrors: info.prod?.outputError === true,\n outputsError: info.prod?.outputsError,\n exportsError: info.prod?.exportsError,\n settings,\n sections,\n inputsValid,\n updateInfo: {},\n currentBlockPack: bp?.info?.source,\n updates,\n sdkVersion,\n featureFlags,\n isIncompatibleWithRuntime,\n navigationState: navigationStates.getState(id),\n };\n });\n\n return {\n meta,\n created: new Date(created),\n lastModified: new Date(lastModified),\n authorMarker: prj.getKeyValueAsJson<AuthorMarker>(ProjectStructureAuthorKey),\n blocks,\n };\n },\n {\n postprocessValue: (value) => {\n const cantRun = new Set<string>();\n const staleBlocks = new Set<string>();\n return {\n ...value,\n blocks: value.blocks.map((b) => {\n if (!b.inputsValid) cantRun.add(b.id);\n if (b.stale) staleBlocks.add(b.id);\n const stale = b.stale || b.upstreams.findIndex((u) => staleBlocks.has(u)) !== -1;\n const canRun\n = (stale || b.outputErrors)\n && Boolean(b.inputsValid)\n && !b.missingReference\n && b.upstreams.findIndex((u) => cantRun.has(u)) === -1;\n const bb = {\n ...b,\n canRun,\n stale,\n updateSuggestions: b.updates?.suggestions ?? [],\n updatedBlockPack: b.updates?.mainSuggestion,\n };\n delete bb['updates'];\n return bb;\n }),\n };\n },\n },\n ).withStableType();\n}\n"],"names":["R","Computable","notEmpty","ProjectCreatedTimestamp","ProjectLastModifiedTimestamp","ProjectMetaKey","ProjectStructureKey","BlockRenderingStateKey","allBlocks","projectFieldName","productionGraph","getBlockPackInfo","ifNotUndef","constructBlockContextArgsOnly","extractCodeWithInfo","computableFromCfgOrRF","resourceIdToString","ProjectStruct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IAAI,CAAC,CAAC,YAAY;AACvB,2BAAA,OAAO,CAAC,CAAC,CAAC,WAAW;2BACrB,CAAC,CAAC,CAAC;2BACH,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE;AACxD,oBAAA,MAAM,EAAE,GAAG;AACT,wBAAA,GAAG,CAAC;wBACJ,MAAM;wBACN,KAAK;AACL,wBAAA,iBAAiB,EAAE,CAAC,CAAC,OAAO,EAAE,WAAW,IAAI,EAAE;AAC/C,wBAAA,gBAAgB,EAAE,CAAC,CAAC,OAAO,EAAE,cAAc;qBAC5C;AACD,oBAAA,OAAO,EAAE,CAAC,SAAS,CAAC;AACpB,oBAAA,OAAO,EAAE;AACX,gBAAA,CAAC,CAAC;aACH;QACH,CAAC;KACF,CACF,CAAC,cAAc,EAAE;AACpB;;;;"}
|
|
1
|
+
{"version":3,"file":"project_overview.cjs","sources":["../../src/middle_layer/project_overview.ts"],"sourcesContent":["import type { PlTreeEntry } from '@milaboratories/pl-tree';\nimport type { ComputableStableDefined } from '@milaboratories/computable';\nimport { Computable } from '@milaboratories/computable';\nimport type {\n ProjectRenderingState,\n ProjectStructure } from '../model/project_model';\nimport {\n BlockRenderingStateKey,\n ProjectCreatedTimestamp,\n projectFieldName,\n ProjectLastModifiedTimestamp,\n ProjectMetaKey,\n ProjectStructureAuthorKey,\n ProjectStructureKey,\n} from '../model/project_model';\nimport { notEmpty } from '@milaboratories/ts-helpers';\nimport { allBlocks, productionGraph } from '../model/project_model_util';\nimport type { MiddleLayerEnvironment } from './middle_layer';\nimport type {\n AuthorMarker,\n BlockCalculationStatus,\n BlockSettings,\n ProjectMeta,\n ProjectOverview,\n} from '@milaboratories/pl-model-middle-layer';\nimport { constructBlockContextArgsOnly } from './block_ctx';\nimport { ifNotUndef } from '../cfg_render/util';\nimport { type BlockSection } from '@platforma-sdk/model';\nimport { extractCodeWithInfo, wrapCallback } from '@platforma-sdk/model';\nimport { computableFromCfgOrRF } from './render';\nimport type { NavigationStates } from './navigation_states';\nimport { getBlockPackInfo } from './util';\nimport { resourceIdToString, type ResourceId } from '@milaboratories/pl-client';\nimport * as R from 'remeda';\n\ntype BlockInfo = {\n argsRid: ResourceId;\n currentArguments: unknown;\n prod?: ProdState;\n};\n\ntype _CalculationStatus = 'Running' | 'Done';\n\ntype ProdState = {\n finished: boolean;\n\n outputError: boolean;\n\n outputsError?: string;\n\n exportsError?: string;\n\n stale: boolean;\n\n /** Arguments current production was rendered with. */\n arguments: Record<string, unknown>;\n};\n\nfunction argsEquals(a: Record<string, unknown> | undefined, b: Record<string, unknown> | undefined): boolean {\n if (a === b) return true;\n if (a === undefined || b === undefined) return false;\n const clean = R.omitBy<Record<string, unknown>>((_, key) => key.startsWith('__'));\n return R.isDeepEqual(clean(a), clean(b));\n}\n\n/** Returns derived general project state form the project resource */\nexport function projectOverview(\n prjEntry: PlTreeEntry,\n navigationStates: NavigationStates,\n env: MiddleLayerEnvironment,\n): ComputableStableDefined<ProjectOverview> {\n return Computable.make(\n (ctx) => {\n const prj = ctx.accessor(prjEntry).node();\n\n const created = notEmpty(prj.getKeyValueAsJson<number>(ProjectCreatedTimestamp));\n const lastModified = notEmpty(prj.getKeyValueAsJson<number>(ProjectLastModifiedTimestamp));\n\n const meta = notEmpty(prj.getKeyValueAsJson<ProjectMeta>(ProjectMetaKey));\n const structure = notEmpty(prj.getKeyValueAsJson<ProjectStructure>(ProjectStructureKey));\n const renderingState = notEmpty(\n prj.getKeyValueAsJson<ProjectRenderingState>(BlockRenderingStateKey),\n );\n\n const infos = new Map<string, BlockInfo>();\n for (const { id } of allBlocks(structure)) {\n const cInputs = prj.traverse({\n field: projectFieldName(id, 'currentArgs'),\n assertFieldType: 'Dynamic',\n errorIfFieldNotSet: true,\n });\n const currentArguments = cInputs.getDataAsJson() as Record<string, unknown>;\n\n let prod: ProdState | undefined = undefined;\n\n const rInputs = prj.traverse({\n field: projectFieldName(id, 'prodArgs'),\n assertFieldType: 'Dynamic',\n stableIfNotFound: true,\n });\n if (rInputs !== undefined) {\n const prodArgs = rInputs.getDataAsJson() as Record<string, unknown>;\n const result = prj.getField({\n field: projectFieldName(id, 'prodOutput'),\n assertFieldType: 'Dynamic',\n errorIfFieldNotFound: true,\n });\n const ctx = prj.getField({\n field: projectFieldName(id, 'prodUiCtx'),\n assertFieldType: 'Dynamic',\n errorIfFieldNotFound: true,\n });\n prod = {\n arguments: prodArgs,\n stale: !argsEquals(currentArguments, prodArgs),\n outputError:\n result.error !== undefined\n || ctx.error !== undefined\n || result.value?.getError() !== undefined\n || ctx.value?.getError() !== undefined,\n outputsError:\n result.error?.getDataAsString() ?? result.value?.getError()?.getDataAsString(),\n exportsError: ctx.error?.getDataAsString() ?? ctx.value?.getError()?.getDataAsString(),\n finished:\n ((result.value !== undefined && result.value.getIsReadyOrError())\n || (result.error !== undefined && result.error.getIsReadyOrError()))\n && ((ctx.value !== undefined && ctx.value.getIsReadyOrError())\n || (ctx.error !== undefined && ctx.error.getIsReadyOrError())),\n };\n }\n\n infos.set(id, { currentArguments, prod, argsRid: cInputs.resourceInfo.id });\n }\n\n const currentGraph = productionGraph(structure, (id) => {\n const bpInfo = getBlockPackInfo(prj, id)!;\n const bInfo = infos.get(id)!;\n const args = bInfo.currentArguments;\n return {\n args,\n enrichmentTargets: env.projectHelper.getEnrichmentTargets(() => bpInfo.cfg, () => args, { argsRid: bInfo.argsRid, blockPackRid: bpInfo.bpResourceId }),\n };\n });\n\n const limbo = new Set(renderingState.blocksInLimbo);\n\n const blocks = [...allBlocks(structure)].map(({ id, label: defaultLabel, renderingMode }) => {\n const info = notEmpty(infos.get(id));\n const gNode = notEmpty(currentGraph.nodes.get(id));\n let calculationStatus: BlockCalculationStatus = 'NotCalculated';\n if (info.prod !== undefined) {\n if (limbo.has(id)) calculationStatus = 'Limbo';\n else calculationStatus = info.prod.finished ? 'Done' : 'Running';\n }\n\n const bp = getBlockPackInfo(prj, id);\n\n const { sections, title, inputsValid, sdkVersion, featureFlags, isIncompatibleWithRuntime }\n = ifNotUndef(bp, ({ bpId, cfg }) => {\n if (!env.runtimeCapabilities.checkCompatibility(cfg.featureFlags)) {\n return {\n isIncompatibleWithRuntime: true,\n featureFlags: cfg.featureFlags,\n };\n }\n const blockCtxArgsOnly = constructBlockContextArgsOnly(prjEntry, id);\n const codeWithInfoOrError = wrapCallback(() => extractCodeWithInfo(cfg));\n if (codeWithInfoOrError.error) {\n return {\n title: codeWithInfoOrError.error.message,\n isIncompatibleWithRuntime: true,\n featureFlags: cfg.featureFlags,\n };\n }\n const codeWithInfo = codeWithInfoOrError.value;\n return {\n sections: computableFromCfgOrRF(\n env,\n blockCtxArgsOnly,\n cfg.sections,\n codeWithInfo,\n bpId,\n ).wrap({\n recover: (e) => {\n env.logger.error('Error in block model sections');\n env.logger.error(e);\n return [];\n },\n }) as ComputableStableDefined<BlockSection[]>,\n title: ifNotUndef(\n cfg.title,\n (title) =>\n computableFromCfgOrRF(\n env,\n blockCtxArgsOnly,\n title,\n codeWithInfo,\n bpId,\n ).wrap({\n recover: (e) => {\n env.logger.error('Error in block model title');\n env.logger.error(e);\n return 'Invalid title';\n },\n }) as ComputableStableDefined<string>,\n ),\n inputsValid: computableFromCfgOrRF(\n env,\n blockCtxArgsOnly,\n cfg.inputsValid,\n codeWithInfo,\n bpId,\n ).wrap({\n recover: (e) => {\n // I'm not sure that we should write an error here, because it just means \"Invalid args\"\n env.logger.error('Error in block model argsValid');\n env.logger.error(e);\n return false;\n },\n }) as ComputableStableDefined<boolean>,\n sdkVersion: codeWithInfo?.sdkVersion,\n featureFlags: codeWithInfo?.featureFlags ?? {},\n isIncompatibleWithRuntime: false,\n };\n }) || {};\n\n const settings = prj\n .traverse({\n field: projectFieldName(id, 'blockSettings'),\n assertFieldType: 'Dynamic',\n errorIfFieldNotSet: true,\n })\n .getDataAsJson() as BlockSettings;\n\n const updates = ifNotUndef(bp, ({ info }) =>\n env.blockUpdateWatcher.get({ currentSpec: info.source, settings }),\n );\n\n return {\n projectResourceId: resourceIdToString(prjEntry.rid),\n id,\n label: title ?? defaultLabel,\n title: title ?? defaultLabel,\n renderingMode,\n stale: info.prod?.stale !== false || calculationStatus === 'Limbo',\n missingReference: gNode.missingReferences,\n upstreams: [...currentGraph.traverseIdsExcludingRoots('upstream', id)],\n downstreams: [...currentGraph.traverseIdsExcludingRoots('downstream', id)],\n calculationStatus,\n outputErrors: info.prod?.outputError === true,\n outputsError: info.prod?.outputsError,\n exportsError: info.prod?.exportsError,\n settings,\n sections,\n inputsValid,\n updateInfo: {},\n currentBlockPack: bp?.info?.source,\n updates,\n sdkVersion,\n featureFlags,\n isIncompatibleWithRuntime,\n navigationState: navigationStates.getState(id),\n };\n });\n\n return {\n meta,\n created: new Date(created),\n lastModified: new Date(lastModified),\n authorMarker: prj.getKeyValueAsJson<AuthorMarker>(ProjectStructureAuthorKey),\n blocks,\n };\n },\n {\n postprocessValue: (value) => {\n const cantRun = new Set<string>();\n const staleBlocks = new Set<string>();\n return {\n ...value,\n blocks: value.blocks.map((b) => {\n if (!b.inputsValid) cantRun.add(b.id);\n if (b.stale) staleBlocks.add(b.id);\n const stale = b.stale || b.upstreams.findIndex((u) => staleBlocks.has(u)) !== -1;\n const canRun\n = (stale || b.outputErrors)\n && Boolean(b.inputsValid)\n && !b.missingReference\n && b.upstreams.findIndex((u) => cantRun.has(u)) === -1;\n const bb = {\n ...b,\n canRun,\n stale,\n updateSuggestions: b.updates?.suggestions ?? [],\n updatedBlockPack: b.updates?.mainSuggestion,\n };\n delete bb['updates'];\n return bb;\n }),\n };\n },\n },\n ).withStableType();\n}\n"],"names":["R","Computable","notEmpty","ProjectCreatedTimestamp","ProjectLastModifiedTimestamp","ProjectMetaKey","ProjectStructureKey","BlockRenderingStateKey","allBlocks","projectFieldName","productionGraph","getBlockPackInfo","ifNotUndef","constructBlockContextArgsOnly","wrapCallback","extractCodeWithInfo","computableFromCfgOrRF","resourceId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E,CAAC;oBACrC,IAAI,CAAC,CAAC,KAAK;AAAE,wBAAA,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;oBAClC,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE;oBAChF,MAAM,MAAM,GACR,CAAC,KAAK,IAAI,CAAC,CAAC,YAAY;AACvB,2BAAA,OAAO,CAAC,CAAC,CAAC,WAAW;2BACrB,CAAC,CAAC,CAAC;2BACH,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE;AACxD,oBAAA,MAAM,EAAE,GAAG;AACT,wBAAA,GAAG,CAAC;wBACJ,MAAM;wBACN,KAAK;AACL,wBAAA,iBAAiB,EAAE,CAAC,CAAC,OAAO,EAAE,WAAW,IAAI,EAAE;AAC/C,wBAAA,gBAAgB,EAAE,CAAC,CAAC,OAAO,EAAE,cAAc;qBAC5C;AACD,oBAAA,OAAO,EAAE,CAAC,SAAS,CAAC;AACpB,oBAAA,OAAO,EAAE;AACX,gBAAA,CAAC,CAAC;aACH;QACH,CAAC;KACF,CACF,CAAC,cAAc,EAAE;AACpB;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project_overview.d.ts","sourceRoot":"","sources":["../../src/middle_layer/project_overview.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAgB1E,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AAC7D,OAAO,KAAK,EAKV,eAAe,EAChB,MAAM,uCAAuC,CAAC;
|
|
1
|
+
{"version":3,"file":"project_overview.d.ts","sourceRoot":"","sources":["../../src/middle_layer/project_overview.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAgB1E,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AAC7D,OAAO,KAAK,EAKV,eAAe,EAChB,MAAM,uCAAuC,CAAC;AAM/C,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAmC5D,sEAAsE;AACtE,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,WAAW,EACrB,gBAAgB,EAAE,gBAAgB,EAClC,GAAG,EAAE,sBAAsB,GAC1B,uBAAuB,CAAC,eAAe,CAAC,CAwO1C"}
|
|
@@ -4,7 +4,7 @@ import { notEmpty } from '@milaboratories/ts-helpers';
|
|
|
4
4
|
import { allBlocks, productionGraph } from '../model/project_model_util.js';
|
|
5
5
|
import { constructBlockContextArgsOnly } from './block_ctx.js';
|
|
6
6
|
import { ifNotUndef } from '../cfg_render/util.js';
|
|
7
|
-
import { extractCodeWithInfo } from '@platforma-sdk/model';
|
|
7
|
+
import { wrapCallback, extractCodeWithInfo } from '@platforma-sdk/model';
|
|
8
8
|
import { computableFromCfgOrRF } from './render.js';
|
|
9
9
|
import { getBlockPackInfo } from './util.js';
|
|
10
10
|
import { resourceIdToString } from '@milaboratories/pl-client';
|
|
@@ -99,7 +99,15 @@ function projectOverview(prjEntry, navigationStates, env) {
|
|
|
99
99
|
};
|
|
100
100
|
}
|
|
101
101
|
const blockCtxArgsOnly = constructBlockContextArgsOnly(prjEntry, id);
|
|
102
|
-
const
|
|
102
|
+
const codeWithInfoOrError = wrapCallback(() => extractCodeWithInfo(cfg));
|
|
103
|
+
if (codeWithInfoOrError.error) {
|
|
104
|
+
return {
|
|
105
|
+
title: codeWithInfoOrError.error.message,
|
|
106
|
+
isIncompatibleWithRuntime: true,
|
|
107
|
+
featureFlags: cfg.featureFlags,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
const codeWithInfo = codeWithInfoOrError.value;
|
|
103
111
|
return {
|
|
104
112
|
sections: computableFromCfgOrRF(env, blockCtxArgsOnly, cfg.sections, codeWithInfo, bpId).wrap({
|
|
105
113
|
recover: (e) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project_overview.js","sources":["../../src/middle_layer/project_overview.ts"],"sourcesContent":["import type { PlTreeEntry } from '@milaboratories/pl-tree';\nimport type { ComputableStableDefined } from '@milaboratories/computable';\nimport { Computable } from '@milaboratories/computable';\nimport type {\n ProjectRenderingState,\n ProjectStructure } from '../model/project_model';\nimport {\n BlockRenderingStateKey,\n ProjectCreatedTimestamp,\n projectFieldName,\n ProjectLastModifiedTimestamp,\n ProjectMetaKey,\n ProjectStructureAuthorKey,\n ProjectStructureKey,\n} from '../model/project_model';\nimport { notEmpty } from '@milaboratories/ts-helpers';\nimport { allBlocks, productionGraph } from '../model/project_model_util';\nimport type { MiddleLayerEnvironment } from './middle_layer';\nimport type {\n AuthorMarker,\n BlockCalculationStatus,\n BlockSettings,\n ProjectMeta,\n ProjectOverview,\n} from '@milaboratories/pl-model-middle-layer';\nimport { constructBlockContextArgsOnly } from './block_ctx';\nimport { ifNotUndef } from '../cfg_render/util';\nimport { extractCodeWithInfo, type BlockSection } from '@platforma-sdk/model';\nimport { computableFromCfgOrRF } from './render';\nimport type { NavigationStates } from './navigation_states';\nimport { getBlockPackInfo } from './util';\nimport { resourceIdToString, type ResourceId } from '@milaboratories/pl-client';\nimport * as R from 'remeda';\n\ntype BlockInfo = {\n argsRid: ResourceId;\n currentArguments: unknown;\n prod?: ProdState;\n};\n\ntype _CalculationStatus = 'Running' | 'Done';\n\ntype ProdState = {\n finished: boolean;\n\n outputError: boolean;\n\n outputsError?: string;\n\n exportsError?: string;\n\n stale: boolean;\n\n /** Arguments current production was rendered with. */\n arguments: Record<string, unknown>;\n};\n\nfunction argsEquals(a: Record<string, unknown> | undefined, b: Record<string, unknown> | undefined): boolean {\n if (a === b) return true;\n if (a === undefined || b === undefined) return false;\n const clean = R.omitBy<Record<string, unknown>>((_, key) => key.startsWith('__'));\n return R.isDeepEqual(clean(a), clean(b));\n}\n\n/** Returns derived general project state form the project resource */\nexport function projectOverview(\n prjEntry: PlTreeEntry,\n navigationStates: NavigationStates,\n env: MiddleLayerEnvironment,\n): ComputableStableDefined<ProjectOverview> {\n return Computable.make(\n (ctx) => {\n const prj = ctx.accessor(prjEntry).node();\n\n const created = notEmpty(prj.getKeyValueAsJson<number>(ProjectCreatedTimestamp));\n const lastModified = notEmpty(prj.getKeyValueAsJson<number>(ProjectLastModifiedTimestamp));\n\n const meta = notEmpty(prj.getKeyValueAsJson<ProjectMeta>(ProjectMetaKey));\n const structure = notEmpty(prj.getKeyValueAsJson<ProjectStructure>(ProjectStructureKey));\n const renderingState = notEmpty(\n prj.getKeyValueAsJson<ProjectRenderingState>(BlockRenderingStateKey),\n );\n\n const infos = new Map<string, BlockInfo>();\n for (const { id } of allBlocks(structure)) {\n const cInputs = prj.traverse({\n field: projectFieldName(id, 'currentArgs'),\n assertFieldType: 'Dynamic',\n errorIfFieldNotSet: true,\n });\n const currentArguments = cInputs.getDataAsJson() as Record<string, unknown>;\n\n let prod: ProdState | undefined = undefined;\n\n const rInputs = prj.traverse({\n field: projectFieldName(id, 'prodArgs'),\n assertFieldType: 'Dynamic',\n stableIfNotFound: true,\n });\n if (rInputs !== undefined) {\n const prodArgs = rInputs.getDataAsJson() as Record<string, unknown>;\n const result = prj.getField({\n field: projectFieldName(id, 'prodOutput'),\n assertFieldType: 'Dynamic',\n errorIfFieldNotFound: true,\n });\n const ctx = prj.getField({\n field: projectFieldName(id, 'prodUiCtx'),\n assertFieldType: 'Dynamic',\n errorIfFieldNotFound: true,\n });\n prod = {\n arguments: prodArgs,\n stale: !argsEquals(currentArguments, prodArgs),\n outputError:\n result.error !== undefined\n || ctx.error !== undefined\n || result.value?.getError() !== undefined\n || ctx.value?.getError() !== undefined,\n outputsError:\n result.error?.getDataAsString() ?? result.value?.getError()?.getDataAsString(),\n exportsError: ctx.error?.getDataAsString() ?? ctx.value?.getError()?.getDataAsString(),\n finished:\n ((result.value !== undefined && result.value.getIsReadyOrError())\n || (result.error !== undefined && result.error.getIsReadyOrError()))\n && ((ctx.value !== undefined && ctx.value.getIsReadyOrError())\n || (ctx.error !== undefined && ctx.error.getIsReadyOrError())),\n };\n }\n\n infos.set(id, { currentArguments, prod, argsRid: cInputs.resourceInfo.id });\n }\n\n const currentGraph = productionGraph(structure, (id) => {\n const bpInfo = getBlockPackInfo(prj, id)!;\n const bInfo = infos.get(id)!;\n const args = bInfo.currentArguments;\n return {\n args,\n enrichmentTargets: env.projectHelper.getEnrichmentTargets(() => bpInfo.cfg, () => args, { argsRid: bInfo.argsRid, blockPackRid: bpInfo.bpResourceId }),\n };\n });\n\n const limbo = new Set(renderingState.blocksInLimbo);\n\n const blocks = [...allBlocks(structure)].map(({ id, label: defaultLabel, renderingMode }) => {\n const info = notEmpty(infos.get(id));\n const gNode = notEmpty(currentGraph.nodes.get(id));\n let calculationStatus: BlockCalculationStatus = 'NotCalculated';\n if (info.prod !== undefined) {\n if (limbo.has(id)) calculationStatus = 'Limbo';\n else calculationStatus = info.prod.finished ? 'Done' : 'Running';\n }\n\n const bp = getBlockPackInfo(prj, id);\n\n const { sections, title, inputsValid, sdkVersion, featureFlags, isIncompatibleWithRuntime }\n = ifNotUndef(bp, ({ bpId, cfg }) => {\n if (!env.runtimeCapabilities.checkCompatibility(cfg.featureFlags)) {\n return {\n isIncompatibleWithRuntime: true,\n featureFlags: cfg.featureFlags,\n };\n }\n const blockCtxArgsOnly = constructBlockContextArgsOnly(prjEntry, id);\n const codeWithInfo = extractCodeWithInfo(cfg);\n return {\n sections: computableFromCfgOrRF(\n env,\n blockCtxArgsOnly,\n cfg.sections,\n codeWithInfo,\n bpId,\n ).wrap({\n recover: (e) => {\n env.logger.error('Error in block model sections');\n env.logger.error(e);\n return [];\n },\n }) as ComputableStableDefined<BlockSection[]>,\n title: ifNotUndef(\n cfg.title,\n (title) =>\n computableFromCfgOrRF(\n env,\n blockCtxArgsOnly,\n title,\n codeWithInfo,\n bpId,\n ).wrap({\n recover: (e) => {\n env.logger.error('Error in block model title');\n env.logger.error(e);\n return 'Invalid title';\n },\n }) as ComputableStableDefined<string>,\n ),\n inputsValid: computableFromCfgOrRF(\n env,\n blockCtxArgsOnly,\n cfg.inputsValid,\n codeWithInfo,\n bpId,\n ).wrap({\n recover: (e) => {\n // I'm not sure that we should write an error here, because it just means \"Invalid args\"\n env.logger.error('Error in block model argsValid');\n env.logger.error(e);\n return false;\n },\n }) as ComputableStableDefined<boolean>,\n sdkVersion: codeWithInfo?.sdkVersion,\n featureFlags: codeWithInfo?.featureFlags ?? {},\n isIncompatibleWithRuntime: false,\n };\n }) || {};\n\n const settings = prj\n .traverse({\n field: projectFieldName(id, 'blockSettings'),\n assertFieldType: 'Dynamic',\n errorIfFieldNotSet: true,\n })\n .getDataAsJson() as BlockSettings;\n\n const updates = ifNotUndef(bp, ({ info }) =>\n env.blockUpdateWatcher.get({ currentSpec: info.source, settings }),\n );\n\n return {\n projectResourceId: resourceIdToString(prjEntry.rid),\n id,\n label: title ?? defaultLabel,\n title: title ?? defaultLabel,\n renderingMode,\n stale: info.prod?.stale !== false || calculationStatus === 'Limbo',\n missingReference: gNode.missingReferences,\n upstreams: [...currentGraph.traverseIdsExcludingRoots('upstream', id)],\n downstreams: [...currentGraph.traverseIdsExcludingRoots('downstream', id)],\n calculationStatus,\n outputErrors: info.prod?.outputError === true,\n outputsError: info.prod?.outputsError,\n exportsError: info.prod?.exportsError,\n settings,\n sections,\n inputsValid,\n updateInfo: {},\n currentBlockPack: bp?.info?.source,\n updates,\n sdkVersion,\n featureFlags,\n isIncompatibleWithRuntime,\n navigationState: navigationStates.getState(id),\n };\n });\n\n return {\n meta,\n created: new Date(created),\n lastModified: new Date(lastModified),\n authorMarker: prj.getKeyValueAsJson<AuthorMarker>(ProjectStructureAuthorKey),\n blocks,\n };\n },\n {\n postprocessValue: (value) => {\n const cantRun = new Set<string>();\n const staleBlocks = new Set<string>();\n return {\n ...value,\n blocks: value.blocks.map((b) => {\n if (!b.inputsValid) cantRun.add(b.id);\n if (b.stale) staleBlocks.add(b.id);\n const stale = b.stale || b.upstreams.findIndex((u) => staleBlocks.has(u)) !== -1;\n const canRun\n = (stale || b.outputErrors)\n && Boolean(b.inputsValid)\n && !b.missingReference\n && b.upstreams.findIndex((u) => cantRun.has(u)) === -1;\n const bb = {\n ...b,\n canRun,\n stale,\n updateSuggestions: b.updates?.suggestions ?? [],\n updatedBlockPack: b.updates?.mainSuggestion,\n };\n delete bb['updates'];\n return bb;\n }),\n };\n },\n },\n ).withStableType();\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAyDA,SAAS,UAAU,CAAC,CAAsC,EAAE,CAAsC,EAAA;IAChG,IAAI,CAAC,KAAK,CAAC;AAAE,QAAA,OAAO,IAAI;AACxB,IAAA,IAAI,CAAC,KAAK,SAAS,IAAI,CAAC,KAAK,SAAS;AAAE,QAAA,OAAO,KAAK;IACpD,MAAM,KAAK,GAAG,CAAC,CAAC,MAAM,CAA0B,CAAC,CAAC,EAAE,GAAG,KAAK,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AACjF,IAAA,OAAO,CAAC,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;AAC1C;AAEA;SACgB,eAAe,CAC7B,QAAqB,EACrB,gBAAkC,EAClC,GAA2B,EAAA;AAE3B,IAAA,OAAO,UAAU,CAAC,IAAI,CACpB,CAAC,GAAG,KAAI;QACN,MAAM,GAAG,GAAG,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,IAAI,EAAE;QAEzC,MAAM,OAAO,GAAG,QAAQ,C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ACR,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,KAAI;oBAC7B,IAAI,CAAC,CAAC,CAAC,WAAW;AAAE,wBAAA,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;oBACrC,IAAI,CAAC,CAAC,KAAK;AAAE,wBAAA,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;oBAClC,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE;oBAChF,MAAM,MAAM,GACR,CAAC,KAAK,IAAI,CAAC,CAAC,YAAY;AACvB,2BAAA,OAAO,CAAC,CAAC,CAAC,WAAW;2BACrB,CAAC,CAAC,CAAC;2BACH,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE;AACxD,oBAAA,MAAM,EAAE,GAAG;AACT,wBAAA,GAAG,CAAC;wBACJ,MAAM;wBACN,KAAK;AACL,wBAAA,iBAAiB,EAAE,CAAC,CAAC,OAAO,EAAE,WAAW,IAAI,EAAE;AAC/C,wBAAA,gBAAgB,EAAE,CAAC,CAAC,OAAO,EAAE,cAAc;qBAC5C;AACD,oBAAA,OAAO,EAAE,CAAC,SAAS,CAAC;AACpB,oBAAA,OAAO,EAAE;AACX,gBAAA,CAAC,CAAC;aACH;QACH,CAAC;KACF,CACF,CAAC,cAAc,EAAE;AACpB;;;;"}
|
|
1
|
+
{"version":3,"file":"project_overview.js","sources":["../../src/middle_layer/project_overview.ts"],"sourcesContent":["import type { PlTreeEntry } from '@milaboratories/pl-tree';\nimport type { ComputableStableDefined } from '@milaboratories/computable';\nimport { Computable } from '@milaboratories/computable';\nimport type {\n ProjectRenderingState,\n ProjectStructure } from '../model/project_model';\nimport {\n BlockRenderingStateKey,\n ProjectCreatedTimestamp,\n projectFieldName,\n ProjectLastModifiedTimestamp,\n ProjectMetaKey,\n ProjectStructureAuthorKey,\n ProjectStructureKey,\n} from '../model/project_model';\nimport { notEmpty } from '@milaboratories/ts-helpers';\nimport { allBlocks, productionGraph } from '../model/project_model_util';\nimport type { MiddleLayerEnvironment } from './middle_layer';\nimport type {\n AuthorMarker,\n BlockCalculationStatus,\n BlockSettings,\n ProjectMeta,\n ProjectOverview,\n} from '@milaboratories/pl-model-middle-layer';\nimport { constructBlockContextArgsOnly } from './block_ctx';\nimport { ifNotUndef } from '../cfg_render/util';\nimport { type BlockSection } from '@platforma-sdk/model';\nimport { extractCodeWithInfo, wrapCallback } from '@platforma-sdk/model';\nimport { computableFromCfgOrRF } from './render';\nimport type { NavigationStates } from './navigation_states';\nimport { getBlockPackInfo } from './util';\nimport { resourceIdToString, type ResourceId } from '@milaboratories/pl-client';\nimport * as R from 'remeda';\n\ntype BlockInfo = {\n argsRid: ResourceId;\n currentArguments: unknown;\n prod?: ProdState;\n};\n\ntype _CalculationStatus = 'Running' | 'Done';\n\ntype ProdState = {\n finished: boolean;\n\n outputError: boolean;\n\n outputsError?: string;\n\n exportsError?: string;\n\n stale: boolean;\n\n /** Arguments current production was rendered with. */\n arguments: Record<string, unknown>;\n};\n\nfunction argsEquals(a: Record<string, unknown> | undefined, b: Record<string, unknown> | undefined): boolean {\n if (a === b) return true;\n if (a === undefined || b === undefined) return false;\n const clean = R.omitBy<Record<string, unknown>>((_, key) => key.startsWith('__'));\n return R.isDeepEqual(clean(a), clean(b));\n}\n\n/** Returns derived general project state form the project resource */\nexport function projectOverview(\n prjEntry: PlTreeEntry,\n navigationStates: NavigationStates,\n env: MiddleLayerEnvironment,\n): ComputableStableDefined<ProjectOverview> {\n return Computable.make(\n (ctx) => {\n const prj = ctx.accessor(prjEntry).node();\n\n const created = notEmpty(prj.getKeyValueAsJson<number>(ProjectCreatedTimestamp));\n const lastModified = notEmpty(prj.getKeyValueAsJson<number>(ProjectLastModifiedTimestamp));\n\n const meta = notEmpty(prj.getKeyValueAsJson<ProjectMeta>(ProjectMetaKey));\n const structure = notEmpty(prj.getKeyValueAsJson<ProjectStructure>(ProjectStructureKey));\n const renderingState = notEmpty(\n prj.getKeyValueAsJson<ProjectRenderingState>(BlockRenderingStateKey),\n );\n\n const infos = new Map<string, BlockInfo>();\n for (const { id } of allBlocks(structure)) {\n const cInputs = prj.traverse({\n field: projectFieldName(id, 'currentArgs'),\n assertFieldType: 'Dynamic',\n errorIfFieldNotSet: true,\n });\n const currentArguments = cInputs.getDataAsJson() as Record<string, unknown>;\n\n let prod: ProdState | undefined = undefined;\n\n const rInputs = prj.traverse({\n field: projectFieldName(id, 'prodArgs'),\n assertFieldType: 'Dynamic',\n stableIfNotFound: true,\n });\n if (rInputs !== undefined) {\n const prodArgs = rInputs.getDataAsJson() as Record<string, unknown>;\n const result = prj.getField({\n field: projectFieldName(id, 'prodOutput'),\n assertFieldType: 'Dynamic',\n errorIfFieldNotFound: true,\n });\n const ctx = prj.getField({\n field: projectFieldName(id, 'prodUiCtx'),\n assertFieldType: 'Dynamic',\n errorIfFieldNotFound: true,\n });\n prod = {\n arguments: prodArgs,\n stale: !argsEquals(currentArguments, prodArgs),\n outputError:\n result.error !== undefined\n || ctx.error !== undefined\n || result.value?.getError() !== undefined\n || ctx.value?.getError() !== undefined,\n outputsError:\n result.error?.getDataAsString() ?? result.value?.getError()?.getDataAsString(),\n exportsError: ctx.error?.getDataAsString() ?? ctx.value?.getError()?.getDataAsString(),\n finished:\n ((result.value !== undefined && result.value.getIsReadyOrError())\n || (result.error !== undefined && result.error.getIsReadyOrError()))\n && ((ctx.value !== undefined && ctx.value.getIsReadyOrError())\n || (ctx.error !== undefined && ctx.error.getIsReadyOrError())),\n };\n }\n\n infos.set(id, { currentArguments, prod, argsRid: cInputs.resourceInfo.id });\n }\n\n const currentGraph = productionGraph(structure, (id) => {\n const bpInfo = getBlockPackInfo(prj, id)!;\n const bInfo = infos.get(id)!;\n const args = bInfo.currentArguments;\n return {\n args,\n enrichmentTargets: env.projectHelper.getEnrichmentTargets(() => bpInfo.cfg, () => args, { argsRid: bInfo.argsRid, blockPackRid: bpInfo.bpResourceId }),\n };\n });\n\n const limbo = new Set(renderingState.blocksInLimbo);\n\n const blocks = [...allBlocks(structure)].map(({ id, label: defaultLabel, renderingMode }) => {\n const info = notEmpty(infos.get(id));\n const gNode = notEmpty(currentGraph.nodes.get(id));\n let calculationStatus: BlockCalculationStatus = 'NotCalculated';\n if (info.prod !== undefined) {\n if (limbo.has(id)) calculationStatus = 'Limbo';\n else calculationStatus = info.prod.finished ? 'Done' : 'Running';\n }\n\n const bp = getBlockPackInfo(prj, id);\n\n const { sections, title, inputsValid, sdkVersion, featureFlags, isIncompatibleWithRuntime }\n = ifNotUndef(bp, ({ bpId, cfg }) => {\n if (!env.runtimeCapabilities.checkCompatibility(cfg.featureFlags)) {\n return {\n isIncompatibleWithRuntime: true,\n featureFlags: cfg.featureFlags,\n };\n }\n const blockCtxArgsOnly = constructBlockContextArgsOnly(prjEntry, id);\n const codeWithInfoOrError = wrapCallback(() => extractCodeWithInfo(cfg));\n if (codeWithInfoOrError.error) {\n return {\n title: codeWithInfoOrError.error.message,\n isIncompatibleWithRuntime: true,\n featureFlags: cfg.featureFlags,\n };\n }\n const codeWithInfo = codeWithInfoOrError.value;\n return {\n sections: computableFromCfgOrRF(\n env,\n blockCtxArgsOnly,\n cfg.sections,\n codeWithInfo,\n bpId,\n ).wrap({\n recover: (e) => {\n env.logger.error('Error in block model sections');\n env.logger.error(e);\n return [];\n },\n }) as ComputableStableDefined<BlockSection[]>,\n title: ifNotUndef(\n cfg.title,\n (title) =>\n computableFromCfgOrRF(\n env,\n blockCtxArgsOnly,\n title,\n codeWithInfo,\n bpId,\n ).wrap({\n recover: (e) => {\n env.logger.error('Error in block model title');\n env.logger.error(e);\n return 'Invalid title';\n },\n }) as ComputableStableDefined<string>,\n ),\n inputsValid: computableFromCfgOrRF(\n env,\n blockCtxArgsOnly,\n cfg.inputsValid,\n codeWithInfo,\n bpId,\n ).wrap({\n recover: (e) => {\n // I'm not sure that we should write an error here, because it just means \"Invalid args\"\n env.logger.error('Error in block model argsValid');\n env.logger.error(e);\n return false;\n },\n }) as ComputableStableDefined<boolean>,\n sdkVersion: codeWithInfo?.sdkVersion,\n featureFlags: codeWithInfo?.featureFlags ?? {},\n isIncompatibleWithRuntime: false,\n };\n }) || {};\n\n const settings = prj\n .traverse({\n field: projectFieldName(id, 'blockSettings'),\n assertFieldType: 'Dynamic',\n errorIfFieldNotSet: true,\n })\n .getDataAsJson() as BlockSettings;\n\n const updates = ifNotUndef(bp, ({ info }) =>\n env.blockUpdateWatcher.get({ currentSpec: info.source, settings }),\n );\n\n return {\n projectResourceId: resourceIdToString(prjEntry.rid),\n id,\n label: title ?? defaultLabel,\n title: title ?? defaultLabel,\n renderingMode,\n stale: info.prod?.stale !== false || calculationStatus === 'Limbo',\n missingReference: gNode.missingReferences,\n upstreams: [...currentGraph.traverseIdsExcludingRoots('upstream', id)],\n downstreams: [...currentGraph.traverseIdsExcludingRoots('downstream', id)],\n calculationStatus,\n outputErrors: info.prod?.outputError === true,\n outputsError: info.prod?.outputsError,\n exportsError: info.prod?.exportsError,\n settings,\n sections,\n inputsValid,\n updateInfo: {},\n currentBlockPack: bp?.info?.source,\n updates,\n sdkVersion,\n featureFlags,\n isIncompatibleWithRuntime,\n navigationState: navigationStates.getState(id),\n };\n });\n\n return {\n meta,\n created: new Date(created),\n lastModified: new Date(lastModified),\n authorMarker: prj.getKeyValueAsJson<AuthorMarker>(ProjectStructureAuthorKey),\n blocks,\n };\n },\n {\n postprocessValue: (value) => {\n const cantRun = new Set<string>();\n const staleBlocks = new Set<string>();\n return {\n ...value,\n blocks: value.blocks.map((b) => {\n if (!b.inputsValid) cantRun.add(b.id);\n if (b.stale) staleBlocks.add(b.id);\n const stale = b.stale || b.upstreams.findIndex((u) => staleBlocks.has(u)) !== -1;\n const canRun\n = (stale || b.outputErrors)\n && Boolean(b.inputsValid)\n && !b.missingReference\n && b.upstreams.findIndex((u) => cantRun.has(u)) === -1;\n const bb = {\n ...b,\n canRun,\n stale,\n updateSuggestions: b.updates?.suggestions ?? [],\n updatedBlockPack: b.updates?.mainSuggestion,\n };\n delete bb['updates'];\n return bb;\n }),\n };\n },\n },\n ).withStableType();\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AA0DA,SAAS,UAAU,CAAC,CAAsC,EAAE,CAAsC,EAAA;IAChG,IAAI,CAAC,KAAK,CAAC;AAAE,QAAA,OAAO,IAAI;AACxB,IAAA,IAAI,CAAC,KAAK,SAAS,IAAI,CAAC,KAAK,SAAS;AAAE,QAAA,OAAO,KAAK;IACpD,MAAM,KAAK,GAAG,CAAC,CAAC,MAAM,CAA0B,CAAC,CAAC,EAAE,GAAG,KAAK,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AACjF,IAAA,OAAO,CAAC,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;AAC1C;AAEA;SACgB,eAAe,CAC7B,QAAqB,EACrB,gBAAkC,EAClC,GAA2B,EAAA;AAE3B,IAAA,OAAO,UAAU,CAAC,IAAI,CACpB,CAAC,GAAG,KAAI;QACN,MAAM,GAAG,GAAG,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,IAAI,EAAE;QAEzC,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,iBAAiB,CAAS,uBAAuB,CAAC,CAAC;QAChF,MAAM,YAAY,GAAG,QAAQ,CAAC,GAAG,CAAC,iBAAiB,CAAS,4BAA4B,CAAC,CAAC;QAE1F,MAAM,IAAI,GAAG,QAAQ,CAAC,GAAG,CAAC,iBAAiB,CAAc,cAAc,CAAC,CAAC;QACzE,MAAM,SAAS,GAAG,QAAQ,CAAC,GAAG,CAAC,iBAAiB,CAAmB,mBA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M,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,KAAI;oBAC7B,IAAI,CAAC,CAAC,CAAC,WAAW;AAAE,wBAAA,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;oBACrC,IAAI,CAAC,CAAC,KAAK;AAAE,wBAAA,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;oBAClC,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE;oBAChF,MAAM,MAAM,GACR,CAAC,KAAK,IAAI,CAAC,CAAC,YAAY;AACvB,2BAAA,OAAO,CAAC,CAAC,CAAC,WAAW;2BACrB,CAAC,CAAC,CAAC;2BACH,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE;AACxD,oBAAA,MAAM,EAAE,GAAG;AACT,wBAAA,GAAG,CAAC;wBACJ,MAAM;wBACN,KAAK;AACL,wBAAA,iBAAiB,EAAE,CAAC,CAAC,OAAO,EAAE,WAAW,IAAI,EAAE;AAC/C,wBAAA,gBAAgB,EAAE,CAAC,CAAC,OAAO,EAAE,cAAc;qBAC5C;AACD,oBAAA,OAAO,EAAE,CAAC,SAAS,CAAC;AACpB,oBAAA,OAAO,EAAE;AACX,gBAAA,CAAC,CAAC;aACH;QACH,CAAC;KACF,CACF,CAAC,cAAc,EAAE;AACpB;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project_helper.cjs","sources":["../../src/model/project_helper.ts"],"sourcesContent":["import { extractCodeWithInfo, type BlockConfig, type PlRef } from '@platforma-sdk/model';\nimport { LRUCache } from 'lru-cache';\nimport type { QuickJSWASMModule } from 'quickjs-emscripten';\nimport { executeSingleLambda } from '../js_render';\nimport type { ResourceId } from '@milaboratories/pl-client';\n\ntype EnrichmentTargetsRequest = {\n blockConfig: () => BlockConfig;\n args: () => unknown;\n};\n\ntype EnrichmentTargetsValue = {\n value: PlRef[] | undefined;\n};\n\nexport class ProjectHelper {\n private readonly enrichmentTargetsCache = new LRUCache<string, EnrichmentTargetsValue, EnrichmentTargetsRequest>({\n max: 256,\n memoMethod: (_key, _value, { context }) => {\n return { value: this.calculateEnrichmentTargets(context) };\n },\n });\n\n constructor(private readonly quickJs: QuickJSWASMModule) {}\n\n private calculateEnrichmentTargets(req: EnrichmentTargetsRequest): PlRef[] | undefined {\n const blockConfig = req.blockConfig();\n if (blockConfig.enrichmentTargets === undefined) return undefined;\n const args = req.args();\n const result = executeSingleLambda(this.quickJs, blockConfig.enrichmentTargets, extractCodeWithInfo(blockConfig)
|
|
1
|
+
{"version":3,"file":"project_helper.cjs","sources":["../../src/model/project_helper.ts"],"sourcesContent":["import { extractCodeWithInfo, type BlockConfig, type PlRef } from '@platforma-sdk/model';\nimport { LRUCache } from 'lru-cache';\nimport type { QuickJSWASMModule } from 'quickjs-emscripten';\nimport { executeSingleLambda } from '../js_render';\nimport type { ResourceId } from '@milaboratories/pl-client';\n\ntype EnrichmentTargetsRequest = {\n blockConfig: () => BlockConfig;\n args: () => unknown;\n};\n\ntype EnrichmentTargetsValue = {\n value: PlRef[] | undefined;\n};\n\nexport class ProjectHelper {\n private readonly enrichmentTargetsCache = new LRUCache<string, EnrichmentTargetsValue, EnrichmentTargetsRequest>({\n max: 256,\n memoMethod: (_key, _value, { context }) => {\n return { value: this.calculateEnrichmentTargets(context) };\n },\n });\n\n constructor(private readonly quickJs: QuickJSWASMModule) {}\n\n private calculateEnrichmentTargets(req: EnrichmentTargetsRequest): PlRef[] | undefined {\n const blockConfig = req.blockConfig();\n if (blockConfig.enrichmentTargets === undefined) return undefined;\n const args = req.args();\n const result = executeSingleLambda(this.quickJs, blockConfig.enrichmentTargets, extractCodeWithInfo(blockConfig), args) as PlRef[];\n return result;\n }\n\n public getEnrichmentTargets(blockConfig: () => BlockConfig, args: () => unknown, key?: { argsRid: ResourceId; blockPackRid: ResourceId }): PlRef[] | undefined {\n const req = { blockConfig, args };\n if (key === undefined)\n return this.calculateEnrichmentTargets(req);\n const cacheKey = `${key.argsRid}:${key.blockPackRid}`;\n return this.enrichmentTargetsCache.memo(cacheKey, { context: req }).value;\n }\n}\n"],"names":["LRUCache","executeSingleLambda","extractCodeWithInfo"],"mappings":";;;;;;MAea,aAAa,CAAA;AAQK,IAAA,OAAA;IAPZ,sBAAsB,GAAG,IAAIA,iBAAQ,CAA2D;AAC/G,QAAA,GAAG,EAAE,GAAG;QACR,UAAU,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,KAAI;YACxC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,0BAA0B,CAAC,OAAO,CAAC,EAAE;QAC5D,CAAC;AACF,KAAA,CAAC;AAEF,IAAA,WAAA,CAA6B,OAA0B,EAAA;QAA1B,IAAA,CAAA,OAAO,GAAP,OAAO;IAAsB;AAElD,IAAA,0BAA0B,CAAC,GAA6B,EAAA;AAC9D,QAAA,MAAM,WAAW,GAAG,GAAG,CAAC,WAAW,EAAE;AACrC,QAAA,IAAI,WAAW,CAAC,iBAAiB,KAAK,SAAS;AAAE,YAAA,OAAO,SAAS;AACjE,QAAA,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,EAAE;AACvB,QAAA,MAAM,MAAM,GAAGC,yBAAmB,CAAC,IAAI,CAAC,OAAO,EAAE,WAAW,CAAC,iBAAiB,EAAEC,yBAAmB,CAAC,WAAW,CAAC,EAAE,IAAI,CAAY;AAClI,QAAA,OAAO,MAAM;IACf;AAEO,IAAA,oBAAoB,CAAC,WAA8B,EAAE,IAAmB,EAAE,GAAuD,EAAA;AACtI,QAAA,MAAM,GAAG,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE;QACjC,IAAI,GAAG,KAAK,SAAS;AACnB,YAAA,OAAO,IAAI,CAAC,0BAA0B,CAAC,GAAG,CAAC;QAC7C,MAAM,QAAQ,GAAG,CAAA,EAAG,GAAG,CAAC,OAAO,CAAA,CAAA,EAAI,GAAG,CAAC,YAAY,CAAA,CAAE;AACrD,QAAA,OAAO,IAAI,CAAC,sBAAsB,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC,KAAK;IAC3E;AACD;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project_helper.js","sources":["../../src/model/project_helper.ts"],"sourcesContent":["import { extractCodeWithInfo, type BlockConfig, type PlRef } from '@platforma-sdk/model';\nimport { LRUCache } from 'lru-cache';\nimport type { QuickJSWASMModule } from 'quickjs-emscripten';\nimport { executeSingleLambda } from '../js_render';\nimport type { ResourceId } from '@milaboratories/pl-client';\n\ntype EnrichmentTargetsRequest = {\n blockConfig: () => BlockConfig;\n args: () => unknown;\n};\n\ntype EnrichmentTargetsValue = {\n value: PlRef[] | undefined;\n};\n\nexport class ProjectHelper {\n private readonly enrichmentTargetsCache = new LRUCache<string, EnrichmentTargetsValue, EnrichmentTargetsRequest>({\n max: 256,\n memoMethod: (_key, _value, { context }) => {\n return { value: this.calculateEnrichmentTargets(context) };\n },\n });\n\n constructor(private readonly quickJs: QuickJSWASMModule) {}\n\n private calculateEnrichmentTargets(req: EnrichmentTargetsRequest): PlRef[] | undefined {\n const blockConfig = req.blockConfig();\n if (blockConfig.enrichmentTargets === undefined) return undefined;\n const args = req.args();\n const result = executeSingleLambda(this.quickJs, blockConfig.enrichmentTargets, extractCodeWithInfo(blockConfig)
|
|
1
|
+
{"version":3,"file":"project_helper.js","sources":["../../src/model/project_helper.ts"],"sourcesContent":["import { extractCodeWithInfo, type BlockConfig, type PlRef } from '@platforma-sdk/model';\nimport { LRUCache } from 'lru-cache';\nimport type { QuickJSWASMModule } from 'quickjs-emscripten';\nimport { executeSingleLambda } from '../js_render';\nimport type { ResourceId } from '@milaboratories/pl-client';\n\ntype EnrichmentTargetsRequest = {\n blockConfig: () => BlockConfig;\n args: () => unknown;\n};\n\ntype EnrichmentTargetsValue = {\n value: PlRef[] | undefined;\n};\n\nexport class ProjectHelper {\n private readonly enrichmentTargetsCache = new LRUCache<string, EnrichmentTargetsValue, EnrichmentTargetsRequest>({\n max: 256,\n memoMethod: (_key, _value, { context }) => {\n return { value: this.calculateEnrichmentTargets(context) };\n },\n });\n\n constructor(private readonly quickJs: QuickJSWASMModule) {}\n\n private calculateEnrichmentTargets(req: EnrichmentTargetsRequest): PlRef[] | undefined {\n const blockConfig = req.blockConfig();\n if (blockConfig.enrichmentTargets === undefined) return undefined;\n const args = req.args();\n const result = executeSingleLambda(this.quickJs, blockConfig.enrichmentTargets, extractCodeWithInfo(blockConfig), args) as PlRef[];\n return result;\n }\n\n public getEnrichmentTargets(blockConfig: () => BlockConfig, args: () => unknown, key?: { argsRid: ResourceId; blockPackRid: ResourceId }): PlRef[] | undefined {\n const req = { blockConfig, args };\n if (key === undefined)\n return this.calculateEnrichmentTargets(req);\n const cacheKey = `${key.argsRid}:${key.blockPackRid}`;\n return this.enrichmentTargetsCache.memo(cacheKey, { context: req }).value;\n }\n}\n"],"names":[],"mappings":";;;;MAea,aAAa,CAAA;AAQK,IAAA,OAAA;IAPZ,sBAAsB,GAAG,IAAI,QAAQ,CAA2D;AAC/G,QAAA,GAAG,EAAE,GAAG;QACR,UAAU,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,KAAI;YACxC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,0BAA0B,CAAC,OAAO,CAAC,EAAE;QAC5D,CAAC;AACF,KAAA,CAAC;AAEF,IAAA,WAAA,CAA6B,OAA0B,EAAA;QAA1B,IAAA,CAAA,OAAO,GAAP,OAAO;IAAsB;AAElD,IAAA,0BAA0B,CAAC,GAA6B,EAAA;AAC9D,QAAA,MAAM,WAAW,GAAG,GAAG,CAAC,WAAW,EAAE;AACrC,QAAA,IAAI,WAAW,CAAC,iBAAiB,KAAK,SAAS;AAAE,YAAA,OAAO,SAAS;AACjE,QAAA,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,EAAE;AACvB,QAAA,MAAM,MAAM,GAAG,mBAAmB,CAAC,IAAI,CAAC,OAAO,EAAE,WAAW,CAAC,iBAAiB,EAAE,mBAAmB,CAAC,WAAW,CAAC,EAAE,IAAI,CAAY;AAClI,QAAA,OAAO,MAAM;IACf;AAEO,IAAA,oBAAoB,CAAC,WAA8B,EAAE,IAAmB,EAAE,GAAuD,EAAA;AACtI,QAAA,MAAM,GAAG,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE;QACjC,IAAI,GAAG,KAAK,SAAS;AACnB,YAAA,OAAO,IAAI,CAAC,0BAA0B,CAAC,GAAG,CAAC;QAC7C,MAAM,QAAQ,GAAG,CAAA,EAAG,GAAG,CAAC,OAAO,CAAA,CAAA,EAAI,GAAG,CAAC,YAAY,CAAA,CAAE;AACrD,QAAA,OAAO,IAAI,CAAC,sBAAsB,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC,KAAK;IAC3E;AACD;;;;"}
|
|
@@ -7,11 +7,13 @@ var tsHelpers = require('@milaboratories/ts-helpers');
|
|
|
7
7
|
var fs = require('node:fs');
|
|
8
8
|
var undici = require('undici');
|
|
9
9
|
var frontend = require('./frontend.cjs');
|
|
10
|
+
var model = require('@platforma-sdk/model');
|
|
10
11
|
var blockTools = require('@platforma-sdk/block-tools');
|
|
11
12
|
var index = require('../../dev_env/index.cjs');
|
|
12
13
|
var registry = require('../../block_registry/registry.cjs');
|
|
13
14
|
var lruCache = require('lru-cache');
|
|
14
15
|
var WorkerManager = require('../../worker/WorkerManager.cjs');
|
|
16
|
+
var zod = require('zod');
|
|
15
17
|
|
|
16
18
|
const BlockPackCustomType = { name: 'BlockPackCustom', version: '1' };
|
|
17
19
|
const BlockPackTemplateField = 'template';
|
|
@@ -23,11 +25,18 @@ function tSlash(str) {
|
|
|
23
25
|
else
|
|
24
26
|
return `${str}/`;
|
|
25
27
|
}
|
|
26
|
-
function
|
|
27
|
-
|
|
28
|
+
function parseStringConfig(configContent) {
|
|
29
|
+
const res = zod.z.record(zod.z.string(), zod.z.unknown()).safeParse(JSON.parse(configContent));
|
|
30
|
+
if (!res.success) {
|
|
31
|
+
throw new Error('Invalid config content');
|
|
32
|
+
}
|
|
33
|
+
if (!model.Code.safeParse(res.data.code).success) {
|
|
34
|
+
throw new Error('No code bundle');
|
|
35
|
+
}
|
|
36
|
+
return res.data;
|
|
28
37
|
}
|
|
29
|
-
function
|
|
30
|
-
return
|
|
38
|
+
function parseBufferConfig(buffer) {
|
|
39
|
+
return parseStringConfig(Buffer.from(buffer).toString('utf8'));
|
|
31
40
|
}
|
|
32
41
|
class BlockPackPreparer {
|
|
33
42
|
v2RegistryProvider;
|
|
@@ -55,6 +64,7 @@ class BlockPackPreparer {
|
|
|
55
64
|
return spec.config;
|
|
56
65
|
case 'dev-v1': {
|
|
57
66
|
const devPaths = await index.resolveDevPacket(spec.folder);
|
|
67
|
+
console.log('devPaths', devPaths);
|
|
58
68
|
const configContent = await fs.promises.readFile(devPaths.config, { encoding: 'utf-8' });
|
|
59
69
|
return JSON.parse(configContent);
|
|
60
70
|
}
|
|
@@ -63,18 +73,18 @@ class BlockPackPreparer {
|
|
|
63
73
|
const configContent = await fs.promises.readFile(description.components.model.file, {
|
|
64
74
|
encoding: 'utf-8',
|
|
65
75
|
});
|
|
66
|
-
return
|
|
76
|
+
return parseStringConfig(configContent);
|
|
67
77
|
}
|
|
68
78
|
case 'from-registry-v1': {
|
|
69
79
|
const urlPrefix = `${tSlash(spec.registryUrl)}${blockTools.RegistryV1.packageContentPrefix({ organization: spec.id.organization, package: spec.id.name, version: spec.id.version })}`;
|
|
70
80
|
const configResponse = await this.remoteContentCache.forceFetch(`${urlPrefix}/config.json`);
|
|
71
|
-
return
|
|
81
|
+
return JSON.parse(Buffer.from(configResponse).toString('utf8'));
|
|
72
82
|
}
|
|
73
83
|
case 'from-registry-v2': {
|
|
74
84
|
const registry = this.v2RegistryProvider.getRegistry(spec.registryUrl);
|
|
75
85
|
const components = await registry.getComponents(spec.id);
|
|
76
86
|
const configResponse = await this.remoteContentCache.forceFetch(components.model.url);
|
|
77
|
-
return
|
|
87
|
+
return parseBufferConfig(configResponse);
|
|
78
88
|
}
|
|
79
89
|
default:
|
|
80
90
|
return tsHelpers.assertNever(spec);
|
|
@@ -136,7 +146,7 @@ class BlockPackPreparer {
|
|
|
136
146
|
}
|
|
137
147
|
case 'dev-v2': {
|
|
138
148
|
const description = await blockTools.loadPackDescription(spec.folder);
|
|
139
|
-
const config =
|
|
149
|
+
const config = parseStringConfig(await fs.promises.readFile(description.components.model.file, {
|
|
140
150
|
encoding: 'utf-8',
|
|
141
151
|
}));
|
|
142
152
|
const workflowContent = await fs.promises.readFile(description.components.workflow.main.file);
|
|
@@ -168,7 +178,7 @@ class BlockPackPreparer {
|
|
|
168
178
|
const templateContent = new Uint8Array(templateResponse);
|
|
169
179
|
// config
|
|
170
180
|
const configResponse = await this.remoteContentCache.forceFetch(`${urlPrefix}/config.json`);
|
|
171
|
-
const config =
|
|
181
|
+
const config = JSON.parse(Buffer.from(configResponse).toString('utf8'));
|
|
172
182
|
return {
|
|
173
183
|
type: 'explicit',
|
|
174
184
|
template: {
|
|
@@ -186,7 +196,7 @@ class BlockPackPreparer {
|
|
|
186
196
|
case 'from-registry-v2': {
|
|
187
197
|
const registry = this.v2RegistryProvider.getRegistry(spec.registryUrl);
|
|
188
198
|
const components = await registry.getComponents(spec.id);
|
|
189
|
-
const getModel = async () =>
|
|
199
|
+
const getModel = async () => parseBufferConfig(await this.remoteContentCache.forceFetch(components.model.url));
|
|
190
200
|
const getWorkflow = async () => await this.remoteContentCache.forceFetch(components.workflow.main.url);
|
|
191
201
|
const [model, workflow] = await Promise.all([getModel(), getWorkflow()]);
|
|
192
202
|
return {
|