@milaboratories/pl-middle-layer 2.8.10 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +2 -2
- package/dist/middle_layer/build_stamp.cjs +1 -1
- package/dist/middle_layer/build_stamp.js +1 -1
- package/dist/middle_layer/index.d.ts +2 -2
- package/dist/middle_layer/project.cjs +34 -2
- package/dist/middle_layer/project.cjs.map +1 -1
- package/dist/middle_layer/project.d.ts +42 -2
- package/dist/middle_layer/project.d.ts.map +1 -1
- package/dist/middle_layer/project.js +35 -3
- package/dist/middle_layer/project.js.map +1 -1
- package/dist/mutator/project.cjs +18 -0
- package/dist/mutator/project.cjs.map +1 -1
- package/dist/mutator/project.d.ts +2 -2
- package/dist/mutator/project.d.ts.map +1 -1
- package/dist/mutator/project.js +18 -0
- package/dist/mutator/project.js.map +1 -1
- package/package.json +4 -4
- package/src/middle_layer/index.ts +1 -0
- package/src/middle_layer/project.ts +101 -3
- package/src/mutator/project.ts +23 -1
|
@@ -13,7 +13,7 @@ import { NavigationStates } from "./navigation_states.js";
|
|
|
13
13
|
import { projectOverviewLight } from "./project_overview_light.js";
|
|
14
14
|
import { applyProjectMigrations } from "../mutator/migration.js";
|
|
15
15
|
import { cacheBlockPackTemplate } from "../mutator/template/template_cache.js";
|
|
16
|
-
import { BLOCK_STORAGE_FACADE_VERSION, checkBlockFlag, extractConfig } from "@platforma-sdk/model";
|
|
16
|
+
import { BLOCK_STORAGE_FACADE_VERSION, BlockStorageFacadeCallbacks, checkBlockFlag, extractConfig } from "@platforma-sdk/model";
|
|
17
17
|
import { cachedDeserialize, createInfiniteRetryState, nextInfiniteRetryState, notEmpty } from "@milaboratories/ts-helpers";
|
|
18
18
|
import fsp from "node:fs/promises";
|
|
19
19
|
import { Computable } from "@milaboratories/computable";
|
|
@@ -21,6 +21,7 @@ import { setTimeout } from "node:timers/promises";
|
|
|
21
21
|
import { DefaultRetryOptions, Pl, TreeFinality, ensureSignedResourceIdNotNull, field, isNotFoundError, isPermissionDenied, isTimeoutOrCancelError, isUnauthenticated, parseSignedResourceId, resourceIdToString, treeFilter } from "@milaboratories/pl-client";
|
|
22
22
|
import { SynchronizedTreeState, TreeStateUpdateError, treeDumpStats } from "@milaboratories/pl-tree";
|
|
23
23
|
import { randomUUID } from "node:crypto";
|
|
24
|
+
import { BlockInitParamsRejectedError, ModelAPIVersionMismatchError } from "@milaboratories/pl-errors";
|
|
24
25
|
import canonicalize from "canonicalize";
|
|
25
26
|
// src/middle_layer/project.ts
|
|
26
27
|
function stringifyForDump(object) {
|
|
@@ -218,18 +219,33 @@ var Project = class Project {
|
|
|
218
219
|
* @param before id of the block to insert new block before
|
|
219
220
|
* @param blockId internal id to be assigned for the block, this arg can be omitted
|
|
220
221
|
* then, randomly generated UUID will be assigned automatically
|
|
222
|
+
* @param ops see {@link AddBlockOps}
|
|
221
223
|
*
|
|
222
224
|
* @return returns newly created block id
|
|
225
|
+
* @throws ModelAPIVersionMismatchError when `ops.requireModelAPIVersion` differs from the
|
|
226
|
+
* block's model API version; nothing is created
|
|
227
|
+
* @throws BlockInitParamsRejectedError when the block does not accept `ops.init.params`;
|
|
228
|
+
* nothing is created
|
|
223
229
|
* */
|
|
224
|
-
async addBlock(blockLabel, blockPackSpec, before, author = void 0, blockId = randomUUID()) {
|
|
230
|
+
async addBlock(blockLabel, blockPackSpec, before, author = void 0, blockId = randomUUID(), ops = {}) {
|
|
225
231
|
const preparedBp = await this.env.bpPreparer.prepare(blockPackSpec);
|
|
226
232
|
const blockCfg = extractConfig(preparedBp.config);
|
|
233
|
+
if (ops.requireModelAPIVersion !== void 0 && blockCfg.modelAPIVersion !== ops.requireModelAPIVersion) throw new ModelAPIVersionMismatchError(blockId, ops.requireModelAPIVersion, blockCfg.modelAPIVersion);
|
|
227
234
|
this.env.runtimeCapabilities.throwIfIncompatible(blockCfg.featureFlags);
|
|
228
235
|
throwIfMissingServerCapabilities(this.env.pl, preparedBp.requiredCapabilities);
|
|
236
|
+
let initialStorage;
|
|
237
|
+
if (ops.init !== void 0) {
|
|
238
|
+
if (blockCfg.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) throw new ModelAPIVersionMismatchError(blockId, BLOCK_STORAGE_FACADE_VERSION, blockCfg.modelAPIVersion);
|
|
239
|
+
if (blockCfg.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageInitialFromParams] === void 0) throw new BlockInitParamsRejectedError("this version of the block was built before blocks could be created from initialization params; use a newer version of the block");
|
|
240
|
+
const storage = this.env.projectHelper.getInitialStorageFromParamsInVM(blockCfg, ops.init.params, new Map(Object.entries(ops.init.blockIds ?? {})));
|
|
241
|
+
if (storage.error !== void 0) throw new BlockInitParamsRejectedError(storage.error.message);
|
|
242
|
+
initialStorage = storage.value;
|
|
243
|
+
}
|
|
229
244
|
const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp);
|
|
230
245
|
const newBlockSpec = blockCfg.modelAPIVersion === BLOCK_STORAGE_FACADE_VERSION ? {
|
|
231
246
|
storageMode: "fromModel",
|
|
232
|
-
blockPack: cachedBp
|
|
247
|
+
blockPack: cachedBp,
|
|
248
|
+
initialStorage
|
|
233
249
|
} : {
|
|
234
250
|
storageMode: "legacy",
|
|
235
251
|
blockPack: cachedBp,
|
|
@@ -450,6 +466,22 @@ var Project = class Project {
|
|
|
450
466
|
});
|
|
451
467
|
await this.projectTree.refreshState();
|
|
452
468
|
}
|
|
469
|
+
/**
|
|
470
|
+
* Reads the block's initialization params as its own model projects them from the current
|
|
471
|
+
* storage, with the kind the block declares: the entry a template export writes for this block.
|
|
472
|
+
* Passing the result as {@link AddBlockOps.init} to {@link addBlock} with the same block pack
|
|
473
|
+
* recreates the block's configuration.
|
|
474
|
+
*
|
|
475
|
+
* @returns `kind` is undefined for a block that declares none; `params` is undefined when the
|
|
476
|
+
* block has no storage yet
|
|
477
|
+
* @throws when the project has no such block, or the block's model fails to project its params
|
|
478
|
+
*/
|
|
479
|
+
async getBlockInitializationParams(blockId) {
|
|
480
|
+
return await withProject(this.env.projectHelper, this.env.pl, this.rid, (prj) => prj.getBlockInitializationParams(blockId), {
|
|
481
|
+
name: "getBlockInitializationParams",
|
|
482
|
+
lockId: this.projectLockId
|
|
483
|
+
});
|
|
484
|
+
}
|
|
453
485
|
/** Update block settings */
|
|
454
486
|
async setBlockSettings(blockId, newValue) {
|
|
455
487
|
await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, void 0, (mut) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project.js","names":["fs"],"sources":["../../src/middle_layer/project.ts"],"sourcesContent":["import type { MiddleLayerEnvironment } from \"./middle_layer\";\nimport type {\n FieldData,\n Filter,\n OptionalAnyResourceId,\n PlClient,\n SignedResourceId,\n} from \"@milaboratories/pl-client\";\nimport {\n DefaultRetryOptions,\n ensureSignedResourceIdNotNull,\n field,\n isNotFoundError,\n isPermissionDenied,\n isTimeoutOrCancelError,\n isUnauthenticated,\n parseSignedResourceId,\n Pl,\n resourceIdToString,\n treeFilter,\n TreeFinality,\n} from \"@milaboratories/pl-client\";\nimport { finalityStopRules } from \"./finality_stop_rules\";\nimport type { ComputableStableDefined, ComputableValueOrErrors } from \"@milaboratories/computable\";\nimport { Computable } from \"@milaboratories/computable\";\nimport { projectOverview } from \"./project_overview\";\nimport { blockDependencies, blockDependents, labelBlockColumnLinks } from \"./column_links\";\nimport type { BlockPackSpecAny } from \"../model\";\nimport { randomUUID } from \"node:crypto\";\nimport { withProject, withProjectAuthored } from \"../mutator/project\";\nimport type {\n ExtendedResourceData,\n PlTreeNodeAccessor,\n PruningFunction,\n} from \"@milaboratories/pl-tree\";\nimport {\n SynchronizedTreeState,\n treeDumpStats,\n TreeStateUpdateError,\n} from \"@milaboratories/pl-tree\";\nimport type { TreeSnapshotStore } from \"./tree_snapshot_store\";\nimport { setTimeout } from \"node:timers/promises\";\nimport { frontendData } from \"./frontend_path\";\nimport type { NavigationState } from \"@milaboratories/pl-model-common\";\nimport { getBlockParameters, blockOutputs } from \"./block\";\nimport type { BlockActionContextMode, BlockActionContextNode } from \"./block_action_context\";\nimport { readBlockActionContextTree } from \"./block_action_context\";\nimport { getBlockPackInfo } from \"./util\";\nimport { BlockStatusWatch } from \"./block_status_tree\";\nimport type { BlockStatusSummary, BlockStatusTree } from \"@milaboratories/pl-model-middle-layer\";\nimport type { FrontendData } from \"../model/frontend\";\nimport type { ProjectId, ProjectStructure } from \"../model/project_model\";\nimport {\n projectFieldName,\n ProjectStatusFieldPattern,\n projectStatusFieldRegex,\n} from \"../model/project_model\";\nimport {\n cachedDeserialize,\n notEmpty,\n type MiLogger,\n createInfiniteRetryState,\n nextInfiniteRetryState,\n type InfiniteRetryState,\n} from \"@milaboratories/ts-helpers\";\nimport type { BlockPackInfo } from \"../model/block_pack\";\nimport type {\n ProjectOverview,\n AuthorMarker,\n BlockSettings,\n BlockStateInternalV3,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport type { ColumnLink } from \"@milaboratories/pl-model-common\";\nimport { activeConfigs } from \"./active_cfg\";\nimport { NavigationStates } from \"./navigation_states\";\nimport { checkBlockFlag, extractConfig, BLOCK_STORAGE_FACADE_VERSION } 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\";\nimport { cacheBlockPackTemplate } from \"../mutator/template/template_cache\";\n\ntype BlockStateComputables = {\n readonly fullState: Computable<BlockStateInternalV3>;\n /** Column links of the block, nested into its full state. */\n readonly dependencies: Computable<ColumnLink[] | undefined>;\n readonly dependents: Computable<ColumnLink[] | undefined>;\n};\n\nfunction stringifyForDump(object: unknown): string {\n return JSON.stringify(object, (key, value) => {\n if (typeof value === \"bigint\") 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)) return value.toString(\"base64\");\n\n return value;\n });\n}\n\n/** Releases what the computables of a block hold. */\nfunction resetBlockState(computables: BlockStateComputables): void {\n computables.fullState.resetState();\n computables.dependencies.resetState();\n computables.dependents.resetState();\n}\n\n/** Data access object, to manipulate and read single opened (!) project data. */\nexport class Project {\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\n /** Live status watches, keyed by {@link blockStatusKey}. One per block whose status is shown;\n * each owns a synchronized tree, so they are started and terminated explicitly. */\n private readonly blockStatusWatches = new Map<string, Promise<BlockStatusWatch>>();\n private readonly activeConfigs: Computable<unknown[]>;\n private readonly refreshLoopResult: Promise<void>;\n\n private readonly abortController = new AbortController();\n\n /** Tree change generation as of the snapshot currently on disk, or -1 when this session has\n * not written one. Compared against the tree's current generation to skip writing a mirror\n * that has not moved, which is what makes a project left open and idle go quiet. */\n private snapshotGeneration: number;\n\n /** When a snapshot was last attempted, for the periodic write's wall-clock gate.\n *\n * Zero, not the construction time, so the first write lands on the first maintenance pass\n * after the tree has settled rather than a full interval later. Sessions shorter than one\n * interval are the common case for a desktop app that is quit with a project still open, and\n * seeding this to now would leave every one of them with nothing on disk. Set on every\n * attempt, successful or not, so a persistently failing write retries at the interval rather\n * than on every pass of the loop. */\n private lastSnapshotAt = 0;\n\n private get destroyed() {\n return this.abortController.signal.aborted;\n }\n\n constructor(\n private readonly env: MiddleLayerEnvironment,\n public readonly id: ProjectId /* Project ID, exposed to outer consumers, who work with ML */,\n readonly rid: SignedResourceId /* Contains signature, not exposed outside middle layer. */,\n private readonly projectTree: SynchronizedTreeState,\n /** Whether this tree was seeded from a snapshot. When it was, the file on disk already\n * holds generation 0, so an idle warm reopen writes nothing at all. */\n restoredFromSnapshot: boolean = false,\n ) {\n this.snapshotGeneration = restoredFromSnapshot ? 0 : -1;\n this.overview = projectOverview(\n projectTree.entry(),\n this.navigationStates,\n env,\n ).withPreCalculatedValueTree();\n this.overviewLight = projectOverviewLight(projectTree.entry()).withPreCalculatedValueTree();\n this.refreshLoopResult = this.refreshLoop();\n this.refreshLoopResult.catch((err) => {\n env.logger.warn(new Error(\"Error during refresh loop\", { cause: err })); // TODO (safe voiding for now)\n });\n this.activeConfigs = activeConfigs(projectTree.entry(), env);\n }\n\n get projectLockId(): string {\n return \"project:\" + this.id.toString();\n }\n\n /**\n * Periodic snapshot write, carried on the maintenance loop rather than a timer of its own.\n *\n * Gated on the tree having changed since the last snapshot, so a project left open and idle\n * writes once and then goes quiet, and on wall clock, so a project changing continuously\n * writes at most once per interval.\n */\n private async maybeWriteSnapshot(): Promise<void> {\n const store = this.env.treeSnapshots;\n if (store === undefined) return;\n\n const generation = this.projectTree.changeGeneration;\n if (generation === this.snapshotGeneration) return;\n if (Date.now() - this.lastSnapshotAt < this.env.ops.treeSnapshotOps.writeInterval) return;\n\n await this.writeSnapshot(store, generation);\n }\n\n /**\n * Starts the close-boundary snapshot and returns without waiting for the write.\n *\n * On top of the periodic write, since closing is a natural point to persist. Change-gated but\n * not interval-gated: rewriting a mirror that has not moved is pure waste, but a mirror that\n * has moved is worth keeping however recently the last write happened.\n *\n * The **capture is synchronous and happens here**, before the caller destroys the tree,\n * because destroying it invalidates it and a later capture would be refused. Only the encode\n * and the write are deferred: they are up to ten megabytes of work, and project switching\n * should not wait for them. Deferring is safe only because a capture is a copy rather than a\n * view of the tree.\n *\n * The returned promise never rejects. The caller is expected to keep it so it can be drained\n * at shutdown, not to await it here.\n */\n public snapshotOnClose(): Promise<void> {\n const store = this.env.treeSnapshots;\n if (store === undefined) return Promise.resolve();\n\n const generation = this.projectTree.changeGeneration;\n if (generation === this.snapshotGeneration) return Promise.resolve();\n\n let snapshot;\n try {\n snapshot = this.projectTree.capture(parseSignedResourceId(this.rid).signature);\n } catch (e: unknown) {\n this.env.logger.warn(\n new Error(`failed to capture tree snapshot for project ${this.id} on close`, { cause: e }),\n );\n return Promise.resolve();\n }\n\n this.lastSnapshotAt = Date.now();\n\n // Queued behind any in-flight periodic write rather than racing it. Both would land\n // atomically, but the loser would be a wasted encode of the same mirror.\n const previous = this.snapshotInFlight ?? Promise.resolve();\n const write = previous.then(async () => {\n if (this.snapshotGeneration >= generation) return; // the in-flight write covered it\n if (await store.write(this.rid, snapshot)) this.snapshotGeneration = generation;\n });\n\n this.snapshotInFlight = write.finally(() => {\n this.snapshotInFlight = undefined;\n });\n return this.snapshotInFlight;\n }\n\n /** In-flight snapshot write, if any. Both triggers can fire close together (the close write\n * lands while the loop is mid-write), and encoding ten megabytes twice for the same mirror\n * is worth avoiding. */\n private snapshotInFlight: Promise<void> | undefined;\n\n /** Serializes writes, and skips one that the in-flight write has already made redundant. */\n private async writeSnapshot(store: TreeSnapshotStore, generation: number): Promise<void> {\n // A loop, not a single check: with three or more callers, re-checking only once would let\n // a waiter install its own promise over another's and clear the field while that write is\n // still running. Two callers is the most that can happen today, so this is a guard against\n // the next caller rather than a live fix.\n while (this.snapshotInFlight !== undefined) {\n await this.snapshotInFlight;\n if (this.snapshotGeneration >= generation) return;\n }\n\n this.snapshotInFlight = this.captureAndWrite(store, generation).finally(() => {\n this.snapshotInFlight = undefined;\n });\n await this.snapshotInFlight;\n }\n\n /** Captures and writes, never throwing: a snapshot is an optimisation and must not fail\n * whatever triggered it. */\n private async captureAndWrite(store: TreeSnapshotStore, generation: number): Promise<void> {\n // Recorded before the attempt and regardless of its outcome, so a failing disk is retried\n // once per interval instead of on every pass of the maintenance loop.\n this.lastSnapshotAt = Date.now();\n try {\n // The root's signature is the session witness a later open compares against.\n const snapshot = this.projectTree.capture(parseSignedResourceId(this.rid).signature);\n\n // Only a real write advances the change gate. Marking the generation persisted after a\n // failed write would tell both triggers the tree is already on disk, so one transient\n // I/O error would cost the rest of the session, close write included.\n if (await store.write(this.rid, snapshot)) this.snapshotGeneration = generation;\n } catch (e: unknown) {\n this.env.logger.warn(\n new Error(`failed to capture tree snapshot for project ${this.id}`, { cause: e }),\n );\n }\n }\n\n private async refreshLoop(): Promise<void> {\n let retryState: InfiniteRetryState | undefined;\n while (!this.destroyed) {\n try {\n await withProject(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n (prj) => {\n prj.doRefresh();\n },\n {\n name: \"doRefresh\",\n lockId: this.projectLockId,\n abortSignal: this.abortController.signal,\n },\n );\n await this.activeConfigs.getValue();\n await setTimeout(this.env.ops.projectRefreshInterval, undefined, {\n signal: this.abortController.signal,\n });\n\n await this.maybeWriteSnapshot();\n\n // Block computables housekeeping\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 computables = this.blockComputables.get(blockId);\n if (computables !== undefined && computables !== null) resetBlockState(computables);\n this.blockComputables.set(blockId, null);\n }\n }\n retryState = undefined;\n } catch (error: unknown) {\n // If we're destroyed, exit gracefully regardless of error type\n if (this.destroyed) break;\n\n if (isNotFoundError(error)) {\n this.env.logger.warn(\n \"project refresh routine terminated, because project was externally deleted\",\n );\n break;\n } else if (isTimeoutOrCancelError(error)) {\n // Timeout during normal operation, continue the loop\n } else {\n retryState = retryState\n ? nextInfiniteRetryState(retryState)\n : createInfiniteRetryState({\n type: \"exponentialWithMaxDelayBackoff\",\n initialDelay: 1000,\n maxDelay: 60_000,\n backoffMultiplier: 2,\n jitter: 0,\n });\n this.env.logger.error(\n new Error(`[refreshLoop] unexpected exception, retrying in ${retryState.nextDelay}ms`, {\n cause: error,\n }),\n );\n try {\n await setTimeout(retryState.nextDelay, undefined, {\n signal: this.abortController.signal,\n });\n } catch {\n // Aborted during retry delay, will exit via while condition or destroyed check\n break;\n }\n }\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 blockCfg = extractConfig(preparedBp.config);\n\n this.env.runtimeCapabilities.throwIfIncompatible(blockCfg.featureFlags);\n throwIfMissingServerCapabilities(this.env.pl, preparedBp.requiredCapabilities);\n\n // Pre-materialize template via cache (separate transaction(s))\n const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp);\n\n // Build NewBlockSpec based on model API version\n const newBlockSpec =\n blockCfg.modelAPIVersion === BLOCK_STORAGE_FACADE_VERSION\n ? { storageMode: \"fromModel\" as const, blockPack: cachedBp }\n : {\n storageMode: \"legacy\" as const,\n blockPack: cachedBp,\n legacyState: canonicalize({\n args: blockCfg.initialArgs,\n uiState: blockCfg.initialUiState,\n })!,\n };\n\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => {\n return mut.addBlock(\n {\n id: blockId,\n label: blockLabel,\n renderingMode: blockCfg.renderingMode,\n },\n newBlockSpec,\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\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(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => 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(preparedBp.config);\n\n this.env.runtimeCapabilities.throwIfIncompatible(blockCfg.featureFlags);\n throwIfMissingServerCapabilities(this.env.pl, preparedBp.requiredCapabilities);\n\n // Pre-materialize template via cache (separate transaction(s))\n const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp);\n\n // resetState signals to mutator to reset storage\n // For v2+ blocks: mutator gets initial storage directly via getInitialStorageInVM\n // For v1 blocks: we pass the legacy state format\n const resetState = resetArgs\n ? {\n state:\n blockCfg.modelAPIVersion === 1\n ? { args: blockCfg.initialArgs, uiState: blockCfg.initialUiState }\n : {},\n }\n : undefined;\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => mut.migrateBlockPack(blockId, cachedBp, resetState),\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(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => mut.deleteBlock(blockId),\n { name: \"deleteBlock\", lockId: this.projectLockId },\n );\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(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (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 },\n { name: \"reorderBlocks\", lockId: this.projectLockId },\n );\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(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n (mut) => mut.renderProduction([blockId], true),\n { name: \"runBlock\", lockId: this.projectLockId },\n );\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(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n (mut) => mut.stopProduction(blockId),\n { name: \"stopBlock\", lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /**\n * @deprecated Use mutateBlockStorage() for V3 blocks.\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(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => {\n const state = mut.mergeBlockState(blockId, { args });\n mut.setStates([{ modelAPIVersion: 1, blockId, state }]);\n },\n { name: \"setBlockArgs\", lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /**\n * @deprecated Use mutateBlockStorage() for V3 blocks.\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(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => {\n const state = mut.mergeBlockState(blockId, { uiState });\n mut.setStates([{ modelAPIVersion: 1, blockId, state }]);\n },\n { name: \"setUiState\", lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /**\n * @deprecated Use mutateBlockStorage() for V3 blocks.\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, // keep for v1/v2 compatibility\n uiState: unknown, // keep for v1/v2 compatibility\n author?: AuthorMarker,\n ) {\n // Normalize to unified state format { args, uiState } for v1/v2 blocks\n const state = { args, uiState };\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => {\n mut.setStates([{ modelAPIVersion: 1, blockId, state }]);\n },\n { name: \"setBlockArgsAndUiState\", lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /**\n * Sets navigation state.\n * */\n //\n public async setNavigationState(blockId: string, state: NavigationState): Promise<void> {\n this.navigationStates.setState(blockId, state);\n }\n\n /**\n * Mutates block storage for Model API v3 blocks.\n * Applies a storage operation (e.g., 'update-data') which triggers\n * args derivation (args(data) and prerunArgs(data)).\n * The derived args are stored atomically with the data.\n *\n * @param blockId - The block ID\n * @param payload - Storage mutation payload with operation and value\n * @param author - Optional author marker for collaborative editing\n */\n public async mutateBlockStorage(\n blockId: string,\n payload: { operation: string; value: unknown },\n author?: AuthorMarker,\n ) {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => mut.setStates([{ modelAPIVersion: 2, blockId, payload }]),\n { name: \"mutateBlockStorage\", lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /** Update block settings */\n public async setBlockSettings(blockId: string, newValue: BlockSettings) {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n undefined,\n (mut) => {\n mut.setBlockSettings(blockId, newValue);\n },\n { name: \"setBlockSettings\" },\n );\n await this.projectTree.refreshState();\n }\n\n /**\n * Sets raw block storage content directly.\n * This bypasses all normalization and VM transformations.\n *\n * @param blockId The block to set storage for\n * @param rawStorageJson Raw storage as JSON string\n */\n public async setBlockStorageRaw(blockId: string, rawStorageJson: string): Promise<void> {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n undefined,\n (mut) => {\n mut.setBlockStorageRaw(blockId, rawStorageJson);\n },\n { name: \"setBlockStorageRaw\" },\n );\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 = ensureSignedResourceIdNotNull(\n (await tx.getField(field(this.rid, projectFieldName(blockId, \"blockPack\")))).value,\n );\n const bpRid = ensureSignedResourceIdNotNull(\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\n await withProjectAuthored(\n this.env.projectHelper,\n tx,\n this.rid,\n author,\n (prj) => {\n if (config.modelAPIVersion === BLOCK_STORAGE_FACADE_VERSION) {\n // V2+: Reset to initial storage via VM\n prj.resetToInitialStorage(blockId);\n } else {\n // V1: Use legacy state format\n const initialState = { args: config.initialArgs, uiState: config.initialUiState };\n prj.setStates([{ modelAPIVersion: 1, blockId, state: initialState }]);\n }\n },\n { name: \"resetBlockArgsAndUiState\", lockId: this.projectLockId },\n );\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 dependencies = blockDependencies(this.projectTree.entry(), blockId, this.env);\n const dependents = blockDependents(this.projectTree.entry(), blockId, this.env);\n const fullState = Computable.make(\n (ctx) => {\n // Links are computed only for a block whose UI reads them.\n const linked = readsColumnLinks(ctx.accessor(this.projectTree.entry()).node(), blockId);\n return {\n parameters: getBlockParameters(this.projectTree.entry(), blockId, ctx),\n outputs,\n navigationState: this.navigationStates.getState(blockId),\n overview: this.overview,\n dependencies: linked ? dependencies : undefined,\n dependents: linked ? dependents : undefined,\n };\n },\n {\n postprocessValue: (v) => {\n const blockOverview = v.overview?.blocks?.find((b) => b.id == blockId);\n const sdkVersion = blockOverview?.sdkVersion;\n const toString = sdkVersion && shouldStillUseStringErrors(sdkVersion);\n const newOutputs =\n toString && v.outputs !== undefined ? convertErrorsToStrings(v.outputs) : v.outputs;\n\n return {\n ...v.parameters,\n outputs: newOutputs,\n navigationState: v.navigationState,\n // The block state already nests the overview, so labelling by its titles adds\n // nothing to watch.\n columnLinks: labelBlockColumnLinks({ ...v, blockId }, v.overview?.blocks ?? []),\n } as BlockStateInternalV3;\n },\n },\n );\n\n const computables: BlockStateComputables = {\n fullState: fullState.withPreCalculatedValueTree(),\n dependencies,\n dependents,\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 /**\n * Reads the block action context tree of a block render (see readBlockActionContextTree): current state, not\n * watched. Undefined when the block has no action context.\n */\n public async getBlockActionContext(\n blockId: string,\n mode: BlockActionContextMode = \"prod\",\n ): Promise<BlockActionContextNode | undefined> {\n return await readBlockActionContextTree(this.env.pl, this.rid, blockId, mode);\n }\n\n /**\n * Starts watching the live status of a block render, and returns the folded summary.\n *\n * One watch per block and mode: calling it again while a watch is open returns the same\n * computable. The watch owns a synchronized tree, so the caller must call\n * {@link unwatchBlockStatus} once it stops showing the status; {@link destroy} terminates\n * whatever is left.\n *\n * The summary survives a re-run of the block: a new render gets a new status context, and the\n * watch re-seeds itself onto it.\n */\n public async watchBlockStatus(\n blockId: string,\n mode: BlockActionContextMode = \"prod\",\n ): Promise<Computable<BlockStatusSummary>> {\n return (await this.retainBlockStatusWatch(blockId, mode)).summary;\n }\n\n /**\n * Starts watching the action-context tree of a block render, context by context. Takes the same\n * hold as {@link watchBlockStatus}, released by {@link unwatchBlockStatus}, and shares its\n * synchronized tree.\n */\n public async watchBlockStatusTree(\n blockId: string,\n mode: BlockActionContextMode = \"prod\",\n ): Promise<Computable<BlockStatusTree>> {\n return (await this.retainBlockStatusWatch(blockId, mode)).tree;\n }\n\n /**\n * Sets which contexts of {@link watchBlockStatusTree} show their children. A no-op while nobody\n * watches the block: the expansion lives with the watch.\n */\n public async setBlockStatusTreeExpanded(\n blockId: string,\n contextIds: readonly string[],\n mode: BlockActionContextMode = \"prod\",\n ): Promise<void> {\n const pending = this.blockStatusWatches.get(blockStatusKey(blockId, mode));\n if (pending === undefined) return;\n (await pending).setExpanded(contextIds);\n }\n\n private async retainBlockStatusWatch(\n blockId: string,\n mode: BlockActionContextMode,\n ): Promise<BlockStatusWatch> {\n if (this.destroyed)\n throw new Error(`cannot watch the status of ${blockId}: the project is closed`);\n\n const key = blockStatusKey(blockId, mode);\n const existing = this.blockStatusWatches.get(key);\n if (existing !== undefined) {\n const watch = await existing;\n watch.retain();\n return watch;\n }\n\n const started = BlockStatusWatch.start({\n env: this.env,\n projectRid: this.rid,\n blockId,\n mode,\n projectGeneration: () => (this.destroyed ? -1 : this.projectTree.changeGeneration),\n });\n this.blockStatusWatches.set(key, started);\n // A failed start must not leave a rejected promise in the map for every later caller. Only\n // this start's own entry is dropped: by the time a late rejection lands, the key may already\n // hold a newer, live watch.\n started.catch(() => {\n if (this.blockStatusWatches.get(key) === started) this.blockStatusWatches.delete(key);\n });\n return await started;\n }\n\n /**\n * Releases one hold taken by {@link watchBlockStatus}. The tree is terminated when the last\n * holder lets go, so two callers watching one block do not cut each other off.\n */\n public async unwatchBlockStatus(\n blockId: string,\n mode: BlockActionContextMode = \"prod\",\n ): Promise<void> {\n const key = blockStatusKey(blockId, mode);\n const pending = this.blockStatusWatches.get(key);\n if (pending === undefined) return;\n\n let watch: BlockStatusWatch;\n try {\n watch = await pending;\n } catch {\n // The start failed; its own catch handler drops the entry. Nothing to release, and a\n // caller letting go must not see that failure again.\n return;\n }\n\n if (await watch.release()) {\n if (this.blockStatusWatches.get(key) === pending) this.blockStatusWatches.delete(key);\n }\n }\n\n private async terminateBlockStatusWatches(): Promise<void> {\n const watches = [...this.blockStatusWatches.values()];\n this.blockStatusWatches.clear();\n await Promise.all(\n watches.map(async (watch) => {\n try {\n await (await watch).terminate();\n } catch (e: unknown) {\n // A watch whose start rejected has nothing to terminate; anything else is logged.\n this.env.logger.warn(new Error(\"block status watch termination failed\", { cause: e }));\n }\n }),\n );\n }\n\n public getBlockState(blockId: string): Computable<BlockStateInternalV3> {\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.abortController.abort();\n try {\n await this.refreshLoopResult;\n } catch (e: unknown) {\n // Error was already logged in the constructor's catch handler, but log again for context\n this.env.logger.warn(\n new Error(\"Refresh loop had terminated with error before destroy\", { cause: e }),\n );\n }\n\n // terminating the status trees before the project tree: they are seeded from it\n await this.terminateBlockStatusWatches();\n\n // terminating the synchronized project tree\n try {\n await this.projectTree.terminate();\n } catch (e: unknown) {\n // TODO: SynchronizedTreeState.terminate() can throw if mainLoop had an error before termination\n // Log error but continue cleanup - we must clean up remaining resources\n this.env.logger.warn(new Error(\"Project tree termination failed\", { cause: e }));\n }\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) resetBlockState(c);\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(\n env: MiddleLayerEnvironment,\n id: ProjectId,\n rid: SignedResourceId,\n ): 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, warm from a persisted mirror when one is usable\n const { tree: projectTree, restored } = await loadProjectTree(env, rid);\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, id, rid, projectTree, restored);\n }\n}\n\n/**\n * Opens the project tree, seeded from a persisted mirror when there is a usable one.\n *\n * Carries the fail-safe: if the restored tree fails its first refresh on authentication,\n * permission or an inconsistency, the snapshot is deleted and the open is retried cold. Once,\n * and only for that first refresh, so a genuinely dead session still surfaces as itself rather\n * than being masked as a slow open.\n *\n * The fail-safe is what bounds every case the cache key does not cover: a rotated master\n * secret, a revoked grant, a snapshot valid in itself but no longer matching what the backend\n * will serve. Without it, an explicit-root tree propagates the refresh failure rather than\n * healing, so the project would fail to open on every attempt until someone deleted the cache\n * directory by hand.\n */\nasync function loadProjectTree(\n env: MiddleLayerEnvironment,\n rid: SignedResourceId,\n): Promise<{ tree: SynchronizedTreeState; restored: boolean }> {\n const treeOps = {\n ...env.ops.defaultTreeOptions,\n pruning: projectTreePruning(env.logger),\n fieldFilter: projectTreeFieldFilter(),\n traverseStopRules: projectTreeTraverseStopRules(),\n };\n const cold = async () => ({\n tree: await SynchronizedTreeState.init(env.pl, rid, treeOps, env.logger),\n restored: false,\n });\n\n const store = env.treeSnapshots;\n if (store === undefined) return await cold();\n\n const snapshot = await store.read(rid);\n if (!snapshot.ok) {\n env.logger.info(`project tree opening cold, snapshot miss: ${snapshot.miss}`);\n return await cold();\n }\n\n try {\n const tree = await SynchronizedTreeState.init(\n env.pl,\n rid,\n { ...treeOps, restoreFrom: snapshot.tree },\n env.logger,\n );\n\n // Read from the tree rather than assumed: a snapshot can be handed over and still be\n // refused, in which case this open was cold and the file on disk does not describe the\n // tree we now hold.\n const restored = tree.wasRestoredFromSnapshot;\n if (restored) store.noteRestored();\n else env.logger.info(\"project tree opening cold: the snapshot was not applied\");\n\n return { tree, restored };\n } catch (e: unknown) {\n // Retry cold on ANY failure of the warm open, not only on the classified ones. A cold open\n // is exactly what this code did before snapshots existed, so the retry cannot regress\n // anything, whereas rethrowing here leaves a project that fails to open on every attempt\n // until someone deletes the cache directory by hand: the snapshot stays on disk and the\n // next open restores it and fails the same way. That is the outcome this fail-safe exists\n // to prevent, and the error classes that can reach here are not a closed set.\n env.logger.warn(\n new Error(\"restored project tree failed its first refresh, opening cold\", { cause: e }),\n );\n\n // Deleting is reserved for failures that implicate the snapshot itself. Anything else (a\n // timeout, a dropped connection) says nothing about the file, and throwing it away would\n // destroy a mirror that is still good, along with the evidence a later signature refresh\n // would repair.\n if (isSnapshotFailsafeError(e)) await store.discard(rid);\n\n return await cold();\n }\n}\n\n/** The failures that implicate the snapshot rather than the link or the session: a rotated\n * master secret, a revoked grant, or state the tree cannot reconcile. Only these delete the\n * file; every other failure still falls back to a cold open, it just keeps the file.\n *\n * The cause chain is walked because a wrapper anywhere between the tree update and here would\n * otherwise silently disarm the inconsistency arm. `isUnauthenticated` and `isPermissionDenied`\n * do their own one-level unwrapping. */\nexport function isSnapshotFailsafeError(e: unknown): boolean {\n if (isUnauthenticated(e) || isPermissionDenied(e)) return true;\n for (let cause: unknown = e, depth = 0; cause !== undefined && depth < 8; depth++) {\n if (cause instanceof TreeStateUpdateError) return true;\n cause = (cause as { cause?: unknown } | null)?.cause;\n }\n return false;\n}\n\n/** Key of a status watch in {@link Project.blockStatusWatches}. */\nfunction blockStatusKey(blockId: string, mode: BlockActionContextMode): string {\n return `${mode}:${blockId}`;\n}\n\nexport function projectTreePruning(logger: MiLogger): PruningFunction {\n return (r: ExtendedResourceData): FieldData[] => {\n if (r.fields.length > 1000)\n logger.warn(\n `resource with excessive field count: type=${r.type.name} id=${r.id} fields=${r.fields.length}` +\n ` names=[${r.fields\n .slice(0, 10)\n .map((f) => f.name)\n .join(\", \")}, ...]`,\n );\n if (r.type.name.startsWith(\"StreamWorkdir/\")) 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(\n (f) => !f.name.startsWith(\"__serviceTemplate\") && !projectStatusFieldRegex.test(f.name),\n );\n case \"Blob\":\n return [];\n default:\n return r.fields;\n }\n };\n}\n\n/** ResourceTree analogue of projectTreePruning() used by modern backend path. */\nexport function projectTreeFieldFilter(): Filter {\n return treeFilter.not(\n treeFilter.or(\n // StreamWorkdir/* — pruned entirely\n treeFilter.resourceTypeMatch(\"^StreamWorkdir/\"),\n // BlockPackCustom: drop `template`\n treeFilter.and(\n treeFilter.resourceTypeEq(\"BlockPackCustom\"),\n treeFilter.fieldNameEq(\"template\"),\n ),\n // UserProject: drop `__serviceTemplate*`\n treeFilter.and(\n treeFilter.resourceTypeEq(\"UserProject\"),\n treeFilter.fieldNameMatch(\"^__serviceTemplate\"),\n ),\n // UserProject: drop the status-context fields, see ProjectStatusFieldPattern\n treeFilter.and(\n treeFilter.resourceTypeEq(\"UserProject\"),\n treeFilter.fieldNameMatch(ProjectStatusFieldPattern),\n ),\n // Blob — pruned entirely\n treeFilter.resourceTypeEq(\"Blob\"),\n ),\n );\n}\n\n/** Stop rules for the project tree's ResourceTree walks: {@link TreeFinality}'s declared clauses,\n * which may stop before the predicate calls a resource final where an entry declares so. */\nexport function projectTreeTraverseStopRules(): Filter {\n return finalityStopRules(TreeFinality);\n}\n\n/** Whether the block's model declares that its UI reads the column links of the block state. */\nfunction readsColumnLinks(prj: PlTreeNodeAccessor, blockId: string): boolean {\n const info = getBlockPackInfo(prj, blockId);\n return info !== undefined && checkBlockFlag(info.cfg.featureFlags, \"supportsColumnLinks\");\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\n/** Throws when the connected backend doesn't advertise every capability the\n * block-pack requires (as declared in `meta.requiredCapabilities`).\n *\n * The matching set is the desktop's install gate moved server-side so both\n * the UI (`AddBlockModal`) and direct middle-layer callers (the MCP server's\n * `add_block` tool, programmatic block installs, tests) reject incompatible\n * blocks consistently. */\nexport function throwIfMissingServerCapabilities(\n pl: PlClient,\n requiredCapabilities: readonly string[] | undefined,\n): void {\n if (!requiredCapabilities || requiredCapabilities.length === 0) return;\n const advertised = (pl.serverInfo.capabilities ?? []) as readonly string[];\n const filterFn = (c: string) => !advertised.includes(c);\n if (!requiredCapabilities.some(filterFn)) return;\n const missing = requiredCapabilities.filter(filterFn);\n throw new Error(\n `Block cannot be added: connected backend does not advertise capabilities ` +\n `${JSON.stringify(missing)}. ` +\n `Backend advertises ${JSON.stringify(advertised)}. ` +\n `Upgrade the backend or remove the requirement from the block manifest.`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,SAAS,iBAAiB,QAAyB;CACjD,OAAO,KAAK,UAAU,SAAS,KAAK,UAAU;EAC5C,IAAI,OAAO,UAAU,UAAU,OAAO,mBAAmB,KAA8B;OAClF,IACH,YAAY,OAAO,KAAK,KACxB,iBAAiB,aACjB,iBAAiB,cACjB,iBAAiB,qBACjB,iBAAiB,cACjB,iBAAiB,eACjB,iBAAiB,cACjB,iBAAiB,eACjB,iBAAiB,gBACjB,iBAAiB,gBACjB,iBAAiB,iBACjB,iBAAiB,gBAEjB,OAAO,OAAO,KAAK,MAAM,QAAQ,MAAM,YAAY,MAAM,UAAU,CAAC,CAAC,SAAS,QAAQ;OACnF,IAAI,OAAO,SAAS,KAAK,GAAG,OAAO,MAAM,SAAS,QAAQ;EAE/D,OAAO;CACT,CAAC;AACH;;AAGA,SAAS,gBAAgB,aAA0C;CACjE,YAAY,UAAU,WAAW;CACjC,YAAY,aAAa,WAAW;CACpC,YAAY,WAAW,WAAW;AACpC;;AAGA,IAAa,UAAb,MAAa,QAAQ;CAuCA;CACD;CACP;CACQ;;CAxCnB;CACA;CAEA,mBAAoC,IAAI,iBAAiB;CAEzD,mCAAoC,IAAI,IAA0C;CAElF,iCAAkC,IAAI,IAAmD;;;CAIzF,qCAAsC,IAAI,IAAuC;CACjF;CACA;CAEA,kBAAmC,IAAI,gBAAgB;;;;CAKvD;;;;;;;;;CAUA,iBAAyB;CAEzB,IAAY,YAAY;EACtB,OAAO,KAAK,gBAAgB,OAAO;CACrC;CAEA,YACE,KACA,IACA,KACA,aAGA,uBAAgC,OAChC;EAPiB,KAAA,MAAA;EACD,KAAA,KAAA;EACP,KAAA,MAAA;EACQ,KAAA,cAAA;EAKjB,KAAK,qBAAqB,uBAAuB,IAAI;EACrD,KAAK,WAAW,gBACd,YAAY,MAAM,GAClB,KAAK,kBACL,GACF,C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fs"],"sources":["../../src/middle_layer/project.ts"],"sourcesContent":["import type { MiddleLayerEnvironment } from \"./middle_layer\";\nimport type {\n FieldData,\n Filter,\n OptionalAnyResourceId,\n PlClient,\n SignedResourceId,\n} from \"@milaboratories/pl-client\";\nimport {\n DefaultRetryOptions,\n ensureSignedResourceIdNotNull,\n field,\n isNotFoundError,\n isPermissionDenied,\n isTimeoutOrCancelError,\n isUnauthenticated,\n parseSignedResourceId,\n Pl,\n resourceIdToString,\n treeFilter,\n TreeFinality,\n} from \"@milaboratories/pl-client\";\nimport { finalityStopRules } from \"./finality_stop_rules\";\nimport type { ComputableStableDefined, ComputableValueOrErrors } from \"@milaboratories/computable\";\nimport { Computable } from \"@milaboratories/computable\";\nimport { projectOverview } from \"./project_overview\";\nimport { blockDependencies, blockDependents, labelBlockColumnLinks } from \"./column_links\";\nimport type { BlockPackSpecAny } from \"../model\";\nimport { randomUUID } from \"node:crypto\";\nimport { withProject, withProjectAuthored } from \"../mutator/project\";\nimport type {\n ExtendedResourceData,\n PlTreeNodeAccessor,\n PruningFunction,\n} from \"@milaboratories/pl-tree\";\nimport {\n SynchronizedTreeState,\n treeDumpStats,\n TreeStateUpdateError,\n} from \"@milaboratories/pl-tree\";\nimport type { TreeSnapshotStore } from \"./tree_snapshot_store\";\nimport { setTimeout } from \"node:timers/promises\";\nimport { frontendData } from \"./frontend_path\";\nimport type { NavigationState } from \"@milaboratories/pl-model-common\";\nimport { getBlockParameters, blockOutputs } from \"./block\";\nimport type { BlockActionContextMode, BlockActionContextNode } from \"./block_action_context\";\nimport { readBlockActionContextTree } from \"./block_action_context\";\nimport { getBlockPackInfo } from \"./util\";\nimport { BlockStatusWatch } from \"./block_status_tree\";\nimport type { BlockStatusSummary, BlockStatusTree } from \"@milaboratories/pl-model-middle-layer\";\nimport type { FrontendData } from \"../model/frontend\";\nimport type { ProjectId, ProjectStructure } from \"../model/project_model\";\nimport {\n projectFieldName,\n ProjectStatusFieldPattern,\n projectStatusFieldRegex,\n} from \"../model/project_model\";\nimport {\n cachedDeserialize,\n notEmpty,\n type MiLogger,\n createInfiniteRetryState,\n nextInfiniteRetryState,\n type InfiniteRetryState,\n} from \"@milaboratories/ts-helpers\";\nimport type { BlockPackInfo } from \"../model/block_pack\";\nimport type {\n ProjectOverview,\n AuthorMarker,\n BlockSettings,\n BlockStateInternalV3,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport type { BlockId, ColumnLink } from \"@milaboratories/pl-model-common\";\nimport { activeConfigs } from \"./active_cfg\";\nimport { NavigationStates } from \"./navigation_states\";\nimport {\n checkBlockFlag,\n extractConfig,\n BLOCK_STORAGE_FACADE_VERSION,\n BlockStorageFacadeCallbacks,\n type BlockKindReference,\n} from \"@platforma-sdk/model\";\nimport {\n BlockInitParamsRejectedError,\n ModelAPIVersionMismatchError,\n} from \"@milaboratories/pl-errors\";\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\";\nimport { cacheBlockPackTemplate } from \"../mutator/template/template_cache\";\n\ntype BlockStateComputables = {\n readonly fullState: Computable<BlockStateInternalV3>;\n /** Column links of the block, nested into its full state. */\n readonly dependencies: Computable<ColumnLink[] | undefined>;\n readonly dependents: Computable<ColumnLink[] | undefined>;\n};\n\nfunction stringifyForDump(object: unknown): string {\n return JSON.stringify(object, (key, value) => {\n if (typeof value === \"bigint\") 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)) return value.toString(\"base64\");\n\n return value;\n });\n}\n\n/** Releases what the computables of a block hold. */\nfunction resetBlockState(computables: BlockStateComputables): void {\n computables.fullState.resetState();\n computables.dependencies.resetState();\n computables.dependents.resetState();\n}\n\n/** Options of {@link Project.addBlock}. */\nexport type AddBlockOps = {\n /**\n * Start the block from initialization params instead of the model's default state. The block's\n * model checks the params against its kind and builds its initial storage from them. Only a\n * block with model API version 2 whose SDK has the params initializer can be created this way.\n */\n init?: {\n /** The kind's initialization params, as a template entry holds them. */\n params: unknown;\n /**\n * Ids used inside `params` in place of block ids, each mapped to the id of a block of this\n * project. The block's model replaces them in every reference it recognizes. An id that is\n * not listed is left as it is, so params that already hold real block ids need no map.\n */\n blockIds?: Readonly<Record<string, BlockId>>;\n };\n /** Refuse to add a block whose model API version differs from this one. */\n requireModelAPIVersion?: number;\n};\n\n/** Data access object, to manipulate and read single opened (!) project data. */\nexport class Project {\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\n /** Live status watches, keyed by {@link blockStatusKey}. One per block whose status is shown;\n * each owns a synchronized tree, so they are started and terminated explicitly. */\n private readonly blockStatusWatches = new Map<string, Promise<BlockStatusWatch>>();\n private readonly activeConfigs: Computable<unknown[]>;\n private readonly refreshLoopResult: Promise<void>;\n\n private readonly abortController = new AbortController();\n\n /** Tree change generation as of the snapshot currently on disk, or -1 when this session has\n * not written one. Compared against the tree's current generation to skip writing a mirror\n * that has not moved, which is what makes a project left open and idle go quiet. */\n private snapshotGeneration: number;\n\n /** When a snapshot was last attempted, for the periodic write's wall-clock gate.\n *\n * Zero, not the construction time, so the first write lands on the first maintenance pass\n * after the tree has settled rather than a full interval later. Sessions shorter than one\n * interval are the common case for a desktop app that is quit with a project still open, and\n * seeding this to now would leave every one of them with nothing on disk. Set on every\n * attempt, successful or not, so a persistently failing write retries at the interval rather\n * than on every pass of the loop. */\n private lastSnapshotAt = 0;\n\n private get destroyed() {\n return this.abortController.signal.aborted;\n }\n\n constructor(\n private readonly env: MiddleLayerEnvironment,\n public readonly id: ProjectId /* Project ID, exposed to outer consumers, who work with ML */,\n readonly rid: SignedResourceId /* Contains signature, not exposed outside middle layer. */,\n private readonly projectTree: SynchronizedTreeState,\n /** Whether this tree was seeded from a snapshot. When it was, the file on disk already\n * holds generation 0, so an idle warm reopen writes nothing at all. */\n restoredFromSnapshot: boolean = false,\n ) {\n this.snapshotGeneration = restoredFromSnapshot ? 0 : -1;\n this.overview = projectOverview(\n projectTree.entry(),\n this.navigationStates,\n env,\n ).withPreCalculatedValueTree();\n this.overviewLight = projectOverviewLight(projectTree.entry()).withPreCalculatedValueTree();\n this.refreshLoopResult = this.refreshLoop();\n this.refreshLoopResult.catch((err) => {\n env.logger.warn(new Error(\"Error during refresh loop\", { cause: err })); // TODO (safe voiding for now)\n });\n this.activeConfigs = activeConfigs(projectTree.entry(), env);\n }\n\n get projectLockId(): string {\n return \"project:\" + this.id.toString();\n }\n\n /**\n * Periodic snapshot write, carried on the maintenance loop rather than a timer of its own.\n *\n * Gated on the tree having changed since the last snapshot, so a project left open and idle\n * writes once and then goes quiet, and on wall clock, so a project changing continuously\n * writes at most once per interval.\n */\n private async maybeWriteSnapshot(): Promise<void> {\n const store = this.env.treeSnapshots;\n if (store === undefined) return;\n\n const generation = this.projectTree.changeGeneration;\n if (generation === this.snapshotGeneration) return;\n if (Date.now() - this.lastSnapshotAt < this.env.ops.treeSnapshotOps.writeInterval) return;\n\n await this.writeSnapshot(store, generation);\n }\n\n /**\n * Starts the close-boundary snapshot and returns without waiting for the write.\n *\n * On top of the periodic write, since closing is a natural point to persist. Change-gated but\n * not interval-gated: rewriting a mirror that has not moved is pure waste, but a mirror that\n * has moved is worth keeping however recently the last write happened.\n *\n * The **capture is synchronous and happens here**, before the caller destroys the tree,\n * because destroying it invalidates it and a later capture would be refused. Only the encode\n * and the write are deferred: they are up to ten megabytes of work, and project switching\n * should not wait for them. Deferring is safe only because a capture is a copy rather than a\n * view of the tree.\n *\n * The returned promise never rejects. The caller is expected to keep it so it can be drained\n * at shutdown, not to await it here.\n */\n public snapshotOnClose(): Promise<void> {\n const store = this.env.treeSnapshots;\n if (store === undefined) return Promise.resolve();\n\n const generation = this.projectTree.changeGeneration;\n if (generation === this.snapshotGeneration) return Promise.resolve();\n\n let snapshot;\n try {\n snapshot = this.projectTree.capture(parseSignedResourceId(this.rid).signature);\n } catch (e: unknown) {\n this.env.logger.warn(\n new Error(`failed to capture tree snapshot for project ${this.id} on close`, { cause: e }),\n );\n return Promise.resolve();\n }\n\n this.lastSnapshotAt = Date.now();\n\n // Queued behind any in-flight periodic write rather than racing it. Both would land\n // atomically, but the loser would be a wasted encode of the same mirror.\n const previous = this.snapshotInFlight ?? Promise.resolve();\n const write = previous.then(async () => {\n if (this.snapshotGeneration >= generation) return; // the in-flight write covered it\n if (await store.write(this.rid, snapshot)) this.snapshotGeneration = generation;\n });\n\n this.snapshotInFlight = write.finally(() => {\n this.snapshotInFlight = undefined;\n });\n return this.snapshotInFlight;\n }\n\n /** In-flight snapshot write, if any. Both triggers can fire close together (the close write\n * lands while the loop is mid-write), and encoding ten megabytes twice for the same mirror\n * is worth avoiding. */\n private snapshotInFlight: Promise<void> | undefined;\n\n /** Serializes writes, and skips one that the in-flight write has already made redundant. */\n private async writeSnapshot(store: TreeSnapshotStore, generation: number): Promise<void> {\n // A loop, not a single check: with three or more callers, re-checking only once would let\n // a waiter install its own promise over another's and clear the field while that write is\n // still running. Two callers is the most that can happen today, so this is a guard against\n // the next caller rather than a live fix.\n while (this.snapshotInFlight !== undefined) {\n await this.snapshotInFlight;\n if (this.snapshotGeneration >= generation) return;\n }\n\n this.snapshotInFlight = this.captureAndWrite(store, generation).finally(() => {\n this.snapshotInFlight = undefined;\n });\n await this.snapshotInFlight;\n }\n\n /** Captures and writes, never throwing: a snapshot is an optimisation and must not fail\n * whatever triggered it. */\n private async captureAndWrite(store: TreeSnapshotStore, generation: number): Promise<void> {\n // Recorded before the attempt and regardless of its outcome, so a failing disk is retried\n // once per interval instead of on every pass of the maintenance loop.\n this.lastSnapshotAt = Date.now();\n try {\n // The root's signature is the session witness a later open compares against.\n const snapshot = this.projectTree.capture(parseSignedResourceId(this.rid).signature);\n\n // Only a real write advances the change gate. Marking the generation persisted after a\n // failed write would tell both triggers the tree is already on disk, so one transient\n // I/O error would cost the rest of the session, close write included.\n if (await store.write(this.rid, snapshot)) this.snapshotGeneration = generation;\n } catch (e: unknown) {\n this.env.logger.warn(\n new Error(`failed to capture tree snapshot for project ${this.id}`, { cause: e }),\n );\n }\n }\n\n private async refreshLoop(): Promise<void> {\n let retryState: InfiniteRetryState | undefined;\n while (!this.destroyed) {\n try {\n await withProject(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n (prj) => {\n prj.doRefresh();\n },\n {\n name: \"doRefresh\",\n lockId: this.projectLockId,\n abortSignal: this.abortController.signal,\n },\n );\n await this.activeConfigs.getValue();\n await setTimeout(this.env.ops.projectRefreshInterval, undefined, {\n signal: this.abortController.signal,\n });\n\n await this.maybeWriteSnapshot();\n\n // Block computables housekeeping\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 computables = this.blockComputables.get(blockId);\n if (computables !== undefined && computables !== null) resetBlockState(computables);\n this.blockComputables.set(blockId, null);\n }\n }\n retryState = undefined;\n } catch (error: unknown) {\n // If we're destroyed, exit gracefully regardless of error type\n if (this.destroyed) break;\n\n if (isNotFoundError(error)) {\n this.env.logger.warn(\n \"project refresh routine terminated, because project was externally deleted\",\n );\n break;\n } else if (isTimeoutOrCancelError(error)) {\n // Timeout during normal operation, continue the loop\n } else {\n retryState = retryState\n ? nextInfiniteRetryState(retryState)\n : createInfiniteRetryState({\n type: \"exponentialWithMaxDelayBackoff\",\n initialDelay: 1000,\n maxDelay: 60_000,\n backoffMultiplier: 2,\n jitter: 0,\n });\n this.env.logger.error(\n new Error(`[refreshLoop] unexpected exception, retrying in ${retryState.nextDelay}ms`, {\n cause: error,\n }),\n );\n try {\n await setTimeout(retryState.nextDelay, undefined, {\n signal: this.abortController.signal,\n });\n } catch {\n // Aborted during retry delay, will exit via while condition or destroyed check\n break;\n }\n }\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 * @param ops see {@link AddBlockOps}\n *\n * @return returns newly created block id\n * @throws ModelAPIVersionMismatchError when `ops.requireModelAPIVersion` differs from the\n * block's model API version; nothing is created\n * @throws BlockInitParamsRejectedError when the block does not accept `ops.init.params`;\n * nothing is created\n * */\n public async addBlock(\n blockLabel: string,\n blockPackSpec: BlockPackSpecAny,\n before?: string,\n author: AuthorMarker | undefined = undefined,\n blockId: string = randomUUID(),\n ops: AddBlockOps = {},\n ): Promise<string> {\n const preparedBp = await this.env.bpPreparer.prepare(blockPackSpec);\n const blockCfg = extractConfig(preparedBp.config);\n\n if (\n ops.requireModelAPIVersion !== undefined &&\n blockCfg.modelAPIVersion !== ops.requireModelAPIVersion\n )\n throw new ModelAPIVersionMismatchError(\n blockId,\n ops.requireModelAPIVersion,\n blockCfg.modelAPIVersion,\n );\n\n this.env.runtimeCapabilities.throwIfIncompatible(blockCfg.featureFlags);\n throwIfMissingServerCapabilities(this.env.pl, preparedBp.requiredCapabilities);\n\n // The block's own model turns the params into its initial storage, and may decline them.\n // Asked before the template is cached and before the transaction, so a refusal changes\n // nothing on the backend.\n let initialStorage: string | undefined;\n if (ops.init !== undefined) {\n if (blockCfg.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION)\n throw new ModelAPIVersionMismatchError(\n blockId,\n BLOCK_STORAGE_FACADE_VERSION,\n blockCfg.modelAPIVersion,\n );\n if (\n blockCfg.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageInitialFromParams] ===\n undefined\n )\n throw new BlockInitParamsRejectedError(\n \"this version of the block was built before blocks could be created from \" +\n \"initialization params; use a newer version of the block\",\n );\n const storage = this.env.projectHelper.getInitialStorageFromParamsInVM(\n blockCfg,\n ops.init.params,\n new Map(Object.entries(ops.init.blockIds ?? {})),\n );\n if (storage.error !== undefined)\n throw new BlockInitParamsRejectedError(storage.error.message);\n initialStorage = storage.value;\n }\n\n // Pre-materialize template via cache (separate transaction(s))\n const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp);\n\n // Build NewBlockSpec based on model API version\n const newBlockSpec =\n blockCfg.modelAPIVersion === BLOCK_STORAGE_FACADE_VERSION\n ? { storageMode: \"fromModel\" as const, blockPack: cachedBp, initialStorage }\n : {\n storageMode: \"legacy\" as const,\n blockPack: cachedBp,\n legacyState: canonicalize({\n args: blockCfg.initialArgs,\n uiState: blockCfg.initialUiState,\n })!,\n };\n\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => {\n return mut.addBlock(\n {\n id: blockId,\n label: blockLabel,\n renderingMode: blockCfg.renderingMode,\n },\n newBlockSpec,\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\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(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => 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(preparedBp.config);\n\n this.env.runtimeCapabilities.throwIfIncompatible(blockCfg.featureFlags);\n throwIfMissingServerCapabilities(this.env.pl, preparedBp.requiredCapabilities);\n\n // Pre-materialize template via cache (separate transaction(s))\n const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp);\n\n // resetState signals to mutator to reset storage\n // For v2+ blocks: mutator gets initial storage directly via getInitialStorageInVM\n // For v1 blocks: we pass the legacy state format\n const resetState = resetArgs\n ? {\n state:\n blockCfg.modelAPIVersion === 1\n ? { args: blockCfg.initialArgs, uiState: blockCfg.initialUiState }\n : {},\n }\n : undefined;\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => mut.migrateBlockPack(blockId, cachedBp, resetState),\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(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => mut.deleteBlock(blockId),\n { name: \"deleteBlock\", lockId: this.projectLockId },\n );\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(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (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 },\n { name: \"reorderBlocks\", lockId: this.projectLockId },\n );\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(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n (mut) => mut.renderProduction([blockId], true),\n { name: \"runBlock\", lockId: this.projectLockId },\n );\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(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n (mut) => mut.stopProduction(blockId),\n { name: \"stopBlock\", lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /**\n * @deprecated Use mutateBlockStorage() for V3 blocks.\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(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => {\n const state = mut.mergeBlockState(blockId, { args });\n mut.setStates([{ modelAPIVersion: 1, blockId, state }]);\n },\n { name: \"setBlockArgs\", lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /**\n * @deprecated Use mutateBlockStorage() for V3 blocks.\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(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => {\n const state = mut.mergeBlockState(blockId, { uiState });\n mut.setStates([{ modelAPIVersion: 1, blockId, state }]);\n },\n { name: \"setUiState\", lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /**\n * @deprecated Use mutateBlockStorage() for V3 blocks.\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, // keep for v1/v2 compatibility\n uiState: unknown, // keep for v1/v2 compatibility\n author?: AuthorMarker,\n ) {\n // Normalize to unified state format { args, uiState } for v1/v2 blocks\n const state = { args, uiState };\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => {\n mut.setStates([{ modelAPIVersion: 1, blockId, state }]);\n },\n { name: \"setBlockArgsAndUiState\", lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /**\n * Sets navigation state.\n * */\n //\n public async setNavigationState(blockId: string, state: NavigationState): Promise<void> {\n this.navigationStates.setState(blockId, state);\n }\n\n /**\n * Mutates block storage for Model API v3 blocks.\n * Applies a storage operation (e.g., 'update-data') which triggers\n * args derivation (args(data) and prerunArgs(data)).\n * The derived args are stored atomically with the data.\n *\n * @param blockId - The block ID\n * @param payload - Storage mutation payload with operation and value\n * @param author - Optional author marker for collaborative editing\n */\n public async mutateBlockStorage(\n blockId: string,\n payload: { operation: string; value: unknown },\n author?: AuthorMarker,\n ) {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => mut.setStates([{ modelAPIVersion: 2, blockId, payload }]),\n { name: \"mutateBlockStorage\", lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /**\n * Reads the block's initialization params as its own model projects them from the current\n * storage, with the kind the block declares: the entry a template export writes for this block.\n * Passing the result as {@link AddBlockOps.init} to {@link addBlock} with the same block pack\n * recreates the block's configuration.\n *\n * @returns `kind` is undefined for a block that declares none; `params` is undefined when the\n * block has no storage yet\n * @throws when the project has no such block, or the block's model fails to project its params\n */\n public async getBlockInitializationParams(\n blockId: BlockId,\n ): Promise<{ kind: BlockKindReference | undefined; params: unknown }> {\n return await withProject(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n (prj) => prj.getBlockInitializationParams(blockId),\n { name: \"getBlockInitializationParams\", lockId: this.projectLockId },\n );\n }\n\n /** Update block settings */\n public async setBlockSettings(blockId: string, newValue: BlockSettings) {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n undefined,\n (mut) => {\n mut.setBlockSettings(blockId, newValue);\n },\n { name: \"setBlockSettings\" },\n );\n await this.projectTree.refreshState();\n }\n\n /**\n * Sets raw block storage content directly.\n * This bypasses all normalization and VM transformations.\n *\n * @param blockId The block to set storage for\n * @param rawStorageJson Raw storage as JSON string\n */\n public async setBlockStorageRaw(blockId: string, rawStorageJson: string): Promise<void> {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n undefined,\n (mut) => {\n mut.setBlockStorageRaw(blockId, rawStorageJson);\n },\n { name: \"setBlockStorageRaw\" },\n );\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 = ensureSignedResourceIdNotNull(\n (await tx.getField(field(this.rid, projectFieldName(blockId, \"blockPack\")))).value,\n );\n const bpRid = ensureSignedResourceIdNotNull(\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\n await withProjectAuthored(\n this.env.projectHelper,\n tx,\n this.rid,\n author,\n (prj) => {\n if (config.modelAPIVersion === BLOCK_STORAGE_FACADE_VERSION) {\n // V2+: Reset to initial storage via VM\n prj.resetToInitialStorage(blockId);\n } else {\n // V1: Use legacy state format\n const initialState = { args: config.initialArgs, uiState: config.initialUiState };\n prj.setStates([{ modelAPIVersion: 1, blockId, state: initialState }]);\n }\n },\n { name: \"resetBlockArgsAndUiState\", lockId: this.projectLockId },\n );\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 dependencies = blockDependencies(this.projectTree.entry(), blockId, this.env);\n const dependents = blockDependents(this.projectTree.entry(), blockId, this.env);\n const fullState = Computable.make(\n (ctx) => {\n // Links are computed only for a block whose UI reads them.\n const linked = readsColumnLinks(ctx.accessor(this.projectTree.entry()).node(), blockId);\n return {\n parameters: getBlockParameters(this.projectTree.entry(), blockId, ctx),\n outputs,\n navigationState: this.navigationStates.getState(blockId),\n overview: this.overview,\n dependencies: linked ? dependencies : undefined,\n dependents: linked ? dependents : undefined,\n };\n },\n {\n postprocessValue: (v) => {\n const blockOverview = v.overview?.blocks?.find((b) => b.id == blockId);\n const sdkVersion = blockOverview?.sdkVersion;\n const toString = sdkVersion && shouldStillUseStringErrors(sdkVersion);\n const newOutputs =\n toString && v.outputs !== undefined ? convertErrorsToStrings(v.outputs) : v.outputs;\n\n return {\n ...v.parameters,\n outputs: newOutputs,\n navigationState: v.navigationState,\n // The block state already nests the overview, so labelling by its titles adds\n // nothing to watch.\n columnLinks: labelBlockColumnLinks({ ...v, blockId }, v.overview?.blocks ?? []),\n } as BlockStateInternalV3;\n },\n },\n );\n\n const computables: BlockStateComputables = {\n fullState: fullState.withPreCalculatedValueTree(),\n dependencies,\n dependents,\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 /**\n * Reads the block action context tree of a block render (see readBlockActionContextTree): current state, not\n * watched. Undefined when the block has no action context.\n */\n public async getBlockActionContext(\n blockId: string,\n mode: BlockActionContextMode = \"prod\",\n ): Promise<BlockActionContextNode | undefined> {\n return await readBlockActionContextTree(this.env.pl, this.rid, blockId, mode);\n }\n\n /**\n * Starts watching the live status of a block render, and returns the folded summary.\n *\n * One watch per block and mode: calling it again while a watch is open returns the same\n * computable. The watch owns a synchronized tree, so the caller must call\n * {@link unwatchBlockStatus} once it stops showing the status; {@link destroy} terminates\n * whatever is left.\n *\n * The summary survives a re-run of the block: a new render gets a new status context, and the\n * watch re-seeds itself onto it.\n */\n public async watchBlockStatus(\n blockId: string,\n mode: BlockActionContextMode = \"prod\",\n ): Promise<Computable<BlockStatusSummary>> {\n return (await this.retainBlockStatusWatch(blockId, mode)).summary;\n }\n\n /**\n * Starts watching the action-context tree of a block render, context by context. Takes the same\n * hold as {@link watchBlockStatus}, released by {@link unwatchBlockStatus}, and shares its\n * synchronized tree.\n */\n public async watchBlockStatusTree(\n blockId: string,\n mode: BlockActionContextMode = \"prod\",\n ): Promise<Computable<BlockStatusTree>> {\n return (await this.retainBlockStatusWatch(blockId, mode)).tree;\n }\n\n /**\n * Sets which contexts of {@link watchBlockStatusTree} show their children. A no-op while nobody\n * watches the block: the expansion lives with the watch.\n */\n public async setBlockStatusTreeExpanded(\n blockId: string,\n contextIds: readonly string[],\n mode: BlockActionContextMode = \"prod\",\n ): Promise<void> {\n const pending = this.blockStatusWatches.get(blockStatusKey(blockId, mode));\n if (pending === undefined) return;\n (await pending).setExpanded(contextIds);\n }\n\n private async retainBlockStatusWatch(\n blockId: string,\n mode: BlockActionContextMode,\n ): Promise<BlockStatusWatch> {\n if (this.destroyed)\n throw new Error(`cannot watch the status of ${blockId}: the project is closed`);\n\n const key = blockStatusKey(blockId, mode);\n const existing = this.blockStatusWatches.get(key);\n if (existing !== undefined) {\n const watch = await existing;\n watch.retain();\n return watch;\n }\n\n const started = BlockStatusWatch.start({\n env: this.env,\n projectRid: this.rid,\n blockId,\n mode,\n projectGeneration: () => (this.destroyed ? -1 : this.projectTree.changeGeneration),\n });\n this.blockStatusWatches.set(key, started);\n // A failed start must not leave a rejected promise in the map for every later caller. Only\n // this start's own entry is dropped: by the time a late rejection lands, the key may already\n // hold a newer, live watch.\n started.catch(() => {\n if (this.blockStatusWatches.get(key) === started) this.blockStatusWatches.delete(key);\n });\n return await started;\n }\n\n /**\n * Releases one hold taken by {@link watchBlockStatus}. The tree is terminated when the last\n * holder lets go, so two callers watching one block do not cut each other off.\n */\n public async unwatchBlockStatus(\n blockId: string,\n mode: BlockActionContextMode = \"prod\",\n ): Promise<void> {\n const key = blockStatusKey(blockId, mode);\n const pending = this.blockStatusWatches.get(key);\n if (pending === undefined) return;\n\n let watch: BlockStatusWatch;\n try {\n watch = await pending;\n } catch {\n // The start failed; its own catch handler drops the entry. Nothing to release, and a\n // caller letting go must not see that failure again.\n return;\n }\n\n if (await watch.release()) {\n if (this.blockStatusWatches.get(key) === pending) this.blockStatusWatches.delete(key);\n }\n }\n\n private async terminateBlockStatusWatches(): Promise<void> {\n const watches = [...this.blockStatusWatches.values()];\n this.blockStatusWatches.clear();\n await Promise.all(\n watches.map(async (watch) => {\n try {\n await (await watch).terminate();\n } catch (e: unknown) {\n // A watch whose start rejected has nothing to terminate; anything else is logged.\n this.env.logger.warn(new Error(\"block status watch termination failed\", { cause: e }));\n }\n }),\n );\n }\n\n public getBlockState(blockId: string): Computable<BlockStateInternalV3> {\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.abortController.abort();\n try {\n await this.refreshLoopResult;\n } catch (e: unknown) {\n // Error was already logged in the constructor's catch handler, but log again for context\n this.env.logger.warn(\n new Error(\"Refresh loop had terminated with error before destroy\", { cause: e }),\n );\n }\n\n // terminating the status trees before the project tree: they are seeded from it\n await this.terminateBlockStatusWatches();\n\n // terminating the synchronized project tree\n try {\n await this.projectTree.terminate();\n } catch (e: unknown) {\n // TODO: SynchronizedTreeState.terminate() can throw if mainLoop had an error before termination\n // Log error but continue cleanup - we must clean up remaining resources\n this.env.logger.warn(new Error(\"Project tree termination failed\", { cause: e }));\n }\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) resetBlockState(c);\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(\n env: MiddleLayerEnvironment,\n id: ProjectId,\n rid: SignedResourceId,\n ): 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, warm from a persisted mirror when one is usable\n const { tree: projectTree, restored } = await loadProjectTree(env, rid);\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, id, rid, projectTree, restored);\n }\n}\n\n/**\n * Opens the project tree, seeded from a persisted mirror when there is a usable one.\n *\n * Carries the fail-safe: if the restored tree fails its first refresh on authentication,\n * permission or an inconsistency, the snapshot is deleted and the open is retried cold. Once,\n * and only for that first refresh, so a genuinely dead session still surfaces as itself rather\n * than being masked as a slow open.\n *\n * The fail-safe is what bounds every case the cache key does not cover: a rotated master\n * secret, a revoked grant, a snapshot valid in itself but no longer matching what the backend\n * will serve. Without it, an explicit-root tree propagates the refresh failure rather than\n * healing, so the project would fail to open on every attempt until someone deleted the cache\n * directory by hand.\n */\nasync function loadProjectTree(\n env: MiddleLayerEnvironment,\n rid: SignedResourceId,\n): Promise<{ tree: SynchronizedTreeState; restored: boolean }> {\n const treeOps = {\n ...env.ops.defaultTreeOptions,\n pruning: projectTreePruning(env.logger),\n fieldFilter: projectTreeFieldFilter(),\n traverseStopRules: projectTreeTraverseStopRules(),\n };\n const cold = async () => ({\n tree: await SynchronizedTreeState.init(env.pl, rid, treeOps, env.logger),\n restored: false,\n });\n\n const store = env.treeSnapshots;\n if (store === undefined) return await cold();\n\n const snapshot = await store.read(rid);\n if (!snapshot.ok) {\n env.logger.info(`project tree opening cold, snapshot miss: ${snapshot.miss}`);\n return await cold();\n }\n\n try {\n const tree = await SynchronizedTreeState.init(\n env.pl,\n rid,\n { ...treeOps, restoreFrom: snapshot.tree },\n env.logger,\n );\n\n // Read from the tree rather than assumed: a snapshot can be handed over and still be\n // refused, in which case this open was cold and the file on disk does not describe the\n // tree we now hold.\n const restored = tree.wasRestoredFromSnapshot;\n if (restored) store.noteRestored();\n else env.logger.info(\"project tree opening cold: the snapshot was not applied\");\n\n return { tree, restored };\n } catch (e: unknown) {\n // Retry cold on ANY failure of the warm open, not only on the classified ones. A cold open\n // is exactly what this code did before snapshots existed, so the retry cannot regress\n // anything, whereas rethrowing here leaves a project that fails to open on every attempt\n // until someone deletes the cache directory by hand: the snapshot stays on disk and the\n // next open restores it and fails the same way. That is the outcome this fail-safe exists\n // to prevent, and the error classes that can reach here are not a closed set.\n env.logger.warn(\n new Error(\"restored project tree failed its first refresh, opening cold\", { cause: e }),\n );\n\n // Deleting is reserved for failures that implicate the snapshot itself. Anything else (a\n // timeout, a dropped connection) says nothing about the file, and throwing it away would\n // destroy a mirror that is still good, along with the evidence a later signature refresh\n // would repair.\n if (isSnapshotFailsafeError(e)) await store.discard(rid);\n\n return await cold();\n }\n}\n\n/** The failures that implicate the snapshot rather than the link or the session: a rotated\n * master secret, a revoked grant, or state the tree cannot reconcile. Only these delete the\n * file; every other failure still falls back to a cold open, it just keeps the file.\n *\n * The cause chain is walked because a wrapper anywhere between the tree update and here would\n * otherwise silently disarm the inconsistency arm. `isUnauthenticated` and `isPermissionDenied`\n * do their own one-level unwrapping. */\nexport function isSnapshotFailsafeError(e: unknown): boolean {\n if (isUnauthenticated(e) || isPermissionDenied(e)) return true;\n for (let cause: unknown = e, depth = 0; cause !== undefined && depth < 8; depth++) {\n if (cause instanceof TreeStateUpdateError) return true;\n cause = (cause as { cause?: unknown } | null)?.cause;\n }\n return false;\n}\n\n/** Key of a status watch in {@link Project.blockStatusWatches}. */\nfunction blockStatusKey(blockId: string, mode: BlockActionContextMode): string {\n return `${mode}:${blockId}`;\n}\n\nexport function projectTreePruning(logger: MiLogger): PruningFunction {\n return (r: ExtendedResourceData): FieldData[] => {\n if (r.fields.length > 1000)\n logger.warn(\n `resource with excessive field count: type=${r.type.name} id=${r.id} fields=${r.fields.length}` +\n ` names=[${r.fields\n .slice(0, 10)\n .map((f) => f.name)\n .join(\", \")}, ...]`,\n );\n if (r.type.name.startsWith(\"StreamWorkdir/\")) 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(\n (f) => !f.name.startsWith(\"__serviceTemplate\") && !projectStatusFieldRegex.test(f.name),\n );\n case \"Blob\":\n return [];\n default:\n return r.fields;\n }\n };\n}\n\n/** ResourceTree analogue of projectTreePruning() used by modern backend path. */\nexport function projectTreeFieldFilter(): Filter {\n return treeFilter.not(\n treeFilter.or(\n // StreamWorkdir/* — pruned entirely\n treeFilter.resourceTypeMatch(\"^StreamWorkdir/\"),\n // BlockPackCustom: drop `template`\n treeFilter.and(\n treeFilter.resourceTypeEq(\"BlockPackCustom\"),\n treeFilter.fieldNameEq(\"template\"),\n ),\n // UserProject: drop `__serviceTemplate*`\n treeFilter.and(\n treeFilter.resourceTypeEq(\"UserProject\"),\n treeFilter.fieldNameMatch(\"^__serviceTemplate\"),\n ),\n // UserProject: drop the status-context fields, see ProjectStatusFieldPattern\n treeFilter.and(\n treeFilter.resourceTypeEq(\"UserProject\"),\n treeFilter.fieldNameMatch(ProjectStatusFieldPattern),\n ),\n // Blob — pruned entirely\n treeFilter.resourceTypeEq(\"Blob\"),\n ),\n );\n}\n\n/** Stop rules for the project tree's ResourceTree walks: {@link TreeFinality}'s declared clauses,\n * which may stop before the predicate calls a resource final where an entry declares so. */\nexport function projectTreeTraverseStopRules(): Filter {\n return finalityStopRules(TreeFinality);\n}\n\n/** Whether the block's model declares that its UI reads the column links of the block state. */\nfunction readsColumnLinks(prj: PlTreeNodeAccessor, blockId: string): boolean {\n const info = getBlockPackInfo(prj, blockId);\n return info !== undefined && checkBlockFlag(info.cfg.featureFlags, \"supportsColumnLinks\");\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\n/** Throws when the connected backend doesn't advertise every capability the\n * block-pack requires (as declared in `meta.requiredCapabilities`).\n *\n * The matching set is the desktop's install gate moved server-side so both\n * the UI (`AddBlockModal`) and direct middle-layer callers (the MCP server's\n * `add_block` tool, programmatic block installs, tests) reject incompatible\n * blocks consistently. */\nexport function throwIfMissingServerCapabilities(\n pl: PlClient,\n requiredCapabilities: readonly string[] | undefined,\n): void {\n if (!requiredCapabilities || requiredCapabilities.length === 0) return;\n const advertised = (pl.serverInfo.capabilities ?? []) as readonly string[];\n const filterFn = (c: string) => !advertised.includes(c);\n if (!requiredCapabilities.some(filterFn)) return;\n const missing = requiredCapabilities.filter(filterFn);\n throw new Error(\n `Block cannot be added: connected backend does not advertise capabilities ` +\n `${JSON.stringify(missing)}. ` +\n `Backend advertises ${JSON.stringify(advertised)}. ` +\n `Upgrade the backend or remove the requirement from the block manifest.`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAoGA,SAAS,iBAAiB,QAAyB;CACjD,OAAO,KAAK,UAAU,SAAS,KAAK,UAAU;EAC5C,IAAI,OAAO,UAAU,UAAU,OAAO,mBAAmB,KAA8B;OAClF,IACH,YAAY,OAAO,KAAK,KACxB,iBAAiB,aACjB,iBAAiB,cACjB,iBAAiB,qBACjB,iBAAiB,cACjB,iBAAiB,eACjB,iBAAiB,cACjB,iBAAiB,eACjB,iBAAiB,gBACjB,iBAAiB,gBACjB,iBAAiB,iBACjB,iBAAiB,gBAEjB,OAAO,OAAO,KAAK,MAAM,QAAQ,MAAM,YAAY,MAAM,UAAU,CAAC,CAAC,SAAS,QAAQ;OACnF,IAAI,OAAO,SAAS,KAAK,GAAG,OAAO,MAAM,SAAS,QAAQ;EAE/D,OAAO;CACT,CAAC;AACH;;AAGA,SAAS,gBAAgB,aAA0C;CACjE,YAAY,UAAU,WAAW;CACjC,YAAY,aAAa,WAAW;CACpC,YAAY,WAAW,WAAW;AACpC;;AAwBA,IAAa,UAAb,MAAa,QAAQ;CAuCA;CACD;CACP;CACQ;;CAxCnB;CACA;CAEA,mBAAoC,IAAI,iBAAiB;CAEzD,mCAAoC,IAAI,IAA0C;CAElF,iCAAkC,IAAI,IAAmD;;;CAIzF,qCAAsC,IAAI,IAAuC;CACjF;CACA;CAEA,kBAAmC,IAAI,gBAAgB;;;;CAKvD;;;;;;;;;CAUA,iBAAyB;CAEzB,IAAY,YAAY;EACtB,OAAO,KAAK,gBAAgB,OAAO;CACrC;CAEA,YACE,KACA,IACA,KACA,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D,OACE,QAAQ,KAAK,OAAO,MACnB,QAAQ,OAAO,OAAO,MAAM,QAAQ,KAAK,OAAO,MAChD,QAAQ,OAAO,OAAO,MAAM,QAAQ,OAAO,OAAO,MAAM,QAAQ,KAAK,OAAO;AAEjF;;AAGA,SAAS,uBACP,SACkD;CAClD,MAAM,SAA2D,CAAC;CAClE,KAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,OAAO,GAAG;EAChD,IAAI,IAAI,IAAI;GACV,OAAO,OAAO;GACd;EACF;EAEA,OAAO,OAAO;GACZ,IAAI;GACJ,QAAQ,IAAI,OAAO,KAAK,MAAM;IAC5B,IAAI,OAAO,MAAM,UACf,OAAO;SACF,IAAI,EAAE,QAAQ,aAAa,EAAE,gBAAgB,KAAA,GAClD,OAAO,EAAE;IAEX,OAAO,EAAE;GACX,CAAC;GACD,YAAY,IAAI;EAClB;CACF;CAEA,OAAO;AACT;;;;;;;;AASA,SAAgB,iCACd,IACA,sBACM;CACN,IAAI,CAAC,wBAAwB,qBAAqB,WAAW,GAAG;CAChE,MAAM,aAAc,GAAG,WAAW,gBAAgB,CAAC;CACnD,MAAM,YAAY,MAAc,CAAC,WAAW,SAAS,CAAC;CACtD,IAAI,CAAC,qBAAqB,KAAK,QAAQ,GAAG;CAC1C,MAAM,UAAU,qBAAqB,OAAO,QAAQ;CACpD,MAAM,IAAI,MACR,4EACK,KAAK,UAAU,OAAO,EAAE,uBACL,KAAK,UAAU,UAAU,EAAE,yEAErD;AACF"}
|
package/dist/mutator/project.cjs
CHANGED
|
@@ -288,6 +288,24 @@ var ProjectMutator = class ProjectMutator {
|
|
|
288
288
|
exportAsTemplateV1() {
|
|
289
289
|
return require_template_serializer.exportProjectAsTemplateV1(this.struct, (blockId) => this.deriveTemplateParams(blockId), (blockId) => this.blockInfos.get(blockId)?.kind, (blockId) => this.blockInfos.get(blockId)?.source);
|
|
290
290
|
}
|
|
291
|
+
/**
|
|
292
|
+
* The block's initialization params as its own model projects them from the current storage,
|
|
293
|
+
* with the kind the block declares: what a template export writes for this block.
|
|
294
|
+
*
|
|
295
|
+
* Read-only, like {@link exportAsTemplateV1}.
|
|
296
|
+
*
|
|
297
|
+
* @returns `params` is undefined when the block has no storage yet
|
|
298
|
+
* @throws when the project has no such block, or the block's model fails to project its params
|
|
299
|
+
*/
|
|
300
|
+
getBlockInitializationParams(blockId) {
|
|
301
|
+
const info = this.getBlockInfo(blockId);
|
|
302
|
+
const derived = this.deriveTemplateParams(blockId);
|
|
303
|
+
if (derived?.error !== void 0) throw new Error(`Block ${blockId} failed to derive its initialization params: ${derived.error}`);
|
|
304
|
+
return {
|
|
305
|
+
kind: info.kind,
|
|
306
|
+
params: derived?.value
|
|
307
|
+
};
|
|
308
|
+
}
|
|
291
309
|
deriveTemplateParams(blockId) {
|
|
292
310
|
const info = this.blockInfos.get(blockId);
|
|
293
311
|
if (info === void 0) return void 0;
|