@milaboratories/pl-middle-layer 2.10.0 → 2.11.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.
Files changed (181) hide show
  1. package/dist/block_registry/registry-v2-provider.cjs +8 -1
  2. package/dist/block_registry/registry-v2-provider.cjs.map +1 -1
  3. package/dist/block_registry/registry-v2-provider.d.ts.map +1 -1
  4. package/dist/block_registry/registry-v2-provider.js +8 -1
  5. package/dist/block_registry/registry-v2-provider.js.map +1 -1
  6. package/dist/index.cjs +25 -1
  7. package/dist/index.d.ts +12 -5
  8. package/dist/index.js +5 -3
  9. package/dist/js_render/bundle_bytecode_cache.cjs +6 -1
  10. package/dist/js_render/bundle_bytecode_cache.cjs.map +1 -1
  11. package/dist/js_render/bundle_bytecode_cache.js +6 -1
  12. package/dist/js_render/bundle_bytecode_cache.js.map +1 -1
  13. package/dist/js_render/column_registry.cjs +17 -0
  14. package/dist/js_render/column_registry.cjs.map +1 -1
  15. package/dist/js_render/column_registry.js +16 -1
  16. package/dist/js_render/column_registry.js.map +1 -1
  17. package/dist/js_render/computable_context.cjs +1 -1
  18. package/dist/js_render/computable_context.js +1 -1
  19. package/dist/js_render/context.cjs +3 -2
  20. package/dist/js_render/context.cjs.map +1 -1
  21. package/dist/js_render/context.js +3 -2
  22. package/dist/js_render/context.js.map +1 -1
  23. package/dist/js_render/index.cjs +1 -1
  24. package/dist/js_render/index.cjs.map +1 -1
  25. package/dist/js_render/index.js +1 -1
  26. package/dist/js_render/index.js.map +1 -1
  27. package/dist/js_render/service_injectors.cjs +2 -9
  28. package/dist/js_render/service_injectors.cjs.map +1 -1
  29. package/dist/js_render/service_injectors.js +2 -9
  30. package/dist/js_render/service_injectors.js.map +1 -1
  31. package/dist/middle_layer/block.cjs +48 -0
  32. package/dist/middle_layer/block.cjs.map +1 -1
  33. package/dist/middle_layer/block.js +51 -4
  34. package/dist/middle_layer/block.js.map +1 -1
  35. package/dist/middle_layer/block_pack_description.cjs +80 -0
  36. package/dist/middle_layer/block_pack_description.cjs.map +1 -0
  37. package/dist/middle_layer/block_pack_description.d.ts +36 -0
  38. package/dist/middle_layer/block_pack_description.d.ts.map +1 -0
  39. package/dist/middle_layer/block_pack_description.js +78 -0
  40. package/dist/middle_layer/block_pack_description.js.map +1 -0
  41. package/dist/middle_layer/build_stamp.cjs +1 -1
  42. package/dist/middle_layer/build_stamp.js +1 -1
  43. package/dist/middle_layer/index.cjs +11 -0
  44. package/dist/middle_layer/index.d.ts +8 -2
  45. package/dist/middle_layer/index.js +3 -1
  46. package/dist/middle_layer/legacy_project_holds.cjs +61 -0
  47. package/dist/middle_layer/legacy_project_holds.cjs.map +1 -0
  48. package/dist/middle_layer/legacy_project_holds.js +61 -0
  49. package/dist/middle_layer/legacy_project_holds.js.map +1 -0
  50. package/dist/middle_layer/middle_layer.cjs +22 -24
  51. package/dist/middle_layer/middle_layer.cjs.map +1 -1
  52. package/dist/middle_layer/middle_layer.d.ts +13 -3
  53. package/dist/middle_layer/middle_layer.d.ts.map +1 -1
  54. package/dist/middle_layer/middle_layer.js +21 -23
  55. package/dist/middle_layer/middle_layer.js.map +1 -1
  56. package/dist/middle_layer/pool_columns.cjs +160 -0
  57. package/dist/middle_layer/pool_columns.cjs.map +1 -0
  58. package/dist/middle_layer/pool_columns.d.ts +59 -0
  59. package/dist/middle_layer/pool_columns.d.ts.map +1 -0
  60. package/dist/middle_layer/pool_columns.js +157 -0
  61. package/dist/middle_layer/pool_columns.js.map +1 -0
  62. package/dist/middle_layer/pool_frame.cjs +82 -0
  63. package/dist/middle_layer/pool_frame.cjs.map +1 -0
  64. package/dist/middle_layer/pool_frame.d.ts +37 -0
  65. package/dist/middle_layer/pool_frame.d.ts.map +1 -0
  66. package/dist/middle_layer/pool_frame.js +81 -0
  67. package/dist/middle_layer/pool_frame.js.map +1 -0
  68. package/dist/middle_layer/pool_table.cjs +66 -0
  69. package/dist/middle_layer/pool_table.cjs.map +1 -0
  70. package/dist/middle_layer/pool_table.d.ts +27 -0
  71. package/dist/middle_layer/pool_table.d.ts.map +1 -0
  72. package/dist/middle_layer/pool_table.js +66 -0
  73. package/dist/middle_layer/pool_table.js.map +1 -0
  74. package/dist/middle_layer/project.cjs +89 -23
  75. package/dist/middle_layer/project.cjs.map +1 -1
  76. package/dist/middle_layer/project.d.ts +70 -4
  77. package/dist/middle_layer/project.d.ts.map +1 -1
  78. package/dist/middle_layer/project.js +89 -22
  79. package/dist/middle_layer/project.js.map +1 -1
  80. package/dist/middle_layer/rich_column_query.cjs +180 -0
  81. package/dist/middle_layer/rich_column_query.cjs.map +1 -0
  82. package/dist/middle_layer/rich_column_query.d.ts +34 -0
  83. package/dist/middle_layer/rich_column_query.d.ts.map +1 -0
  84. package/dist/middle_layer/rich_column_query.js +176 -0
  85. package/dist/middle_layer/rich_column_query.js.map +1 -0
  86. package/dist/model/args.cjs +23 -0
  87. package/dist/model/args.cjs.map +1 -1
  88. package/dist/model/args.js +24 -2
  89. package/dist/model/args.js.map +1 -1
  90. package/dist/model/args_derivation.cjs +60 -2
  91. package/dist/model/args_derivation.cjs.map +1 -1
  92. package/dist/model/args_derivation.d.ts +73 -3
  93. package/dist/model/args_derivation.d.ts.map +1 -1
  94. package/dist/model/args_derivation.js +60 -3
  95. package/dist/model/args_derivation.js.map +1 -1
  96. package/dist/model/block_pack_spec.cjs.map +1 -1
  97. package/dist/model/block_pack_spec.d.ts +3 -3
  98. package/dist/model/block_pack_spec.d.ts.map +1 -1
  99. package/dist/model/block_pack_spec.js.map +1 -1
  100. package/dist/model/block_params_model.cjs +42 -0
  101. package/dist/model/block_params_model.cjs.map +1 -0
  102. package/dist/model/block_params_model.d.ts +45 -0
  103. package/dist/model/block_params_model.d.ts.map +1 -0
  104. package/dist/model/block_params_model.js +42 -0
  105. package/dist/model/block_params_model.js.map +1 -0
  106. package/dist/model/index.d.ts +3 -1
  107. package/dist/model/project_helper.cjs +50 -6
  108. package/dist/model/project_helper.cjs.map +1 -1
  109. package/dist/model/project_helper.d.ts +25 -1
  110. package/dist/model/project_helper.d.ts.map +1 -1
  111. package/dist/model/project_helper.js +51 -7
  112. package/dist/model/project_helper.js.map +1 -1
  113. package/dist/model/template_spec.d.ts +18 -0
  114. package/dist/model/template_spec.d.ts.map +1 -1
  115. package/dist/mutator/block-pack/block_pack.cjs +90 -3
  116. package/dist/mutator/block-pack/block_pack.cjs.map +1 -1
  117. package/dist/mutator/block-pack/block_pack.d.ts +16 -0
  118. package/dist/mutator/block-pack/block_pack.d.ts.map +1 -1
  119. package/dist/mutator/block-pack/block_pack.js +91 -5
  120. package/dist/mutator/block-pack/block_pack.js.map +1 -1
  121. package/dist/mutator/block-pack/required_capabilities.cjs +16 -0
  122. package/dist/mutator/block-pack/required_capabilities.cjs.map +1 -1
  123. package/dist/mutator/block-pack/required_capabilities.js +16 -1
  124. package/dist/mutator/block-pack/required_capabilities.js.map +1 -1
  125. package/dist/mutator/project.cjs +4 -0
  126. package/dist/mutator/project.cjs.map +1 -1
  127. package/dist/mutator/project.d.ts +1 -1
  128. package/dist/mutator/project.d.ts.map +1 -1
  129. package/dist/mutator/project.js +4 -0
  130. package/dist/mutator/project.js.map +1 -1
  131. package/dist/mutator/template/template_cache.cjs +8 -1
  132. package/dist/mutator/template/template_cache.cjs.map +1 -1
  133. package/dist/mutator/template/template_cache.d.ts +7 -3
  134. package/dist/mutator/template/template_cache.d.ts.map +1 -1
  135. package/dist/mutator/template/template_cache.js +8 -1
  136. package/dist/mutator/template/template_cache.js.map +1 -1
  137. package/package.json +9 -9
  138. package/src/block_registry/registry-v2-provider.test.ts +23 -0
  139. package/src/block_registry/registry-v2-provider.ts +11 -1
  140. package/src/index.ts +2 -0
  141. package/src/js_render/bundle_bytecode_cache.ts +15 -4
  142. package/src/js_render/column_registry.ts +24 -3
  143. package/src/js_render/context.ts +4 -3
  144. package/src/js_render/index.ts +3 -2
  145. package/src/js_render/service_injectors.ts +2 -11
  146. package/src/middle_layer/block.ts +61 -2
  147. package/src/middle_layer/block_pack_description.test.ts +235 -0
  148. package/src/middle_layer/block_pack_description.ts +143 -0
  149. package/src/middle_layer/index.ts +9 -1
  150. package/src/middle_layer/legacy_project_holds.test.ts +133 -0
  151. package/src/middle_layer/legacy_project_holds.ts +73 -0
  152. package/src/middle_layer/middle_layer.ts +27 -28
  153. package/src/middle_layer/pool_columns.test.ts +217 -0
  154. package/src/middle_layer/pool_columns.ts +250 -0
  155. package/src/middle_layer/pool_frame.test.ts +144 -0
  156. package/src/middle_layer/pool_frame.ts +127 -0
  157. package/src/middle_layer/pool_table.test.ts +182 -0
  158. package/src/middle_layer/pool_table.ts +98 -0
  159. package/src/middle_layer/project.ts +135 -32
  160. package/src/middle_layer/rich_column_query.test.ts +311 -0
  161. package/src/middle_layer/rich_column_query.ts +214 -0
  162. package/src/model/args.test.ts +23 -1
  163. package/src/model/args.ts +29 -1
  164. package/src/model/args_derivation.test.ts +129 -12
  165. package/src/model/args_derivation.ts +112 -8
  166. package/src/model/block_pack_spec.ts +3 -2
  167. package/src/model/block_params_model.test.ts +194 -0
  168. package/src/model/block_params_model.ts +117 -0
  169. package/src/model/index.ts +6 -0
  170. package/src/model/project_helper.ts +101 -20
  171. package/src/model/template_spec.ts +21 -0
  172. package/src/mutator/block-pack/block_pack.test.ts +10 -1
  173. package/src/mutator/block-pack/block_pack.ts +102 -2
  174. package/src/mutator/block-pack/block_pack_load.test.ts +52 -0
  175. package/src/mutator/block-pack/required_capabilities.ts +25 -0
  176. package/src/mutator/project-v3.test.ts +27 -16
  177. package/src/mutator/project.ts +5 -0
  178. package/src/mutator/template/template_cache.ts +26 -3
  179. package/src/pool/result_pool_markers.test.ts +47 -0
  180. package/src/test/block_packs.ts +12 -0
  181. package/src/test/fake_project.ts +33 -6
@@ -1,21 +1,27 @@
1
+ import { throwIfMissingServerCapabilities } from "../mutator/block-pack/required_capabilities.js";
1
2
  import { ProjectStatusFieldPattern, projectFieldName, projectStatusFieldRegex } from "../model/project_model.js";
2
3
  import { withProject, withProjectAuthored } from "../mutator/project.js";
4
+ import { cacheBlockPackTemplate } from "../mutator/template/template_cache.js";
3
5
  import { finalityStopRules } from "./finality_stop_rules.js";
4
6
  import { getBlockPackInfo } from "./util.js";
5
7
  import { projectOverview } from "./project_overview.js";
6
8
  import { blockDependencies, blockDependents, labelBlockColumnLinks } from "./column_links.js";
7
9
  import { frontendData } from "./frontend_path.js";
8
- import { blockOutputs, getBlockParameters } from "./block.js";
10
+ import { blockOutputs, blockReadiness, getBlockParameters } from "./block.js";
9
11
  import { readBlockActionContextTree } from "./block_action_context.js";
10
12
  import { BlockStatusWatch } from "./block_status_tree.js";
11
13
  import { activeConfigs } from "./active_cfg.js";
14
+ import { poolColumns, poolColumnsById } from "./pool_columns.js";
15
+ import { poolFrame } from "./pool_frame.js";
16
+ import { poolTable } from "./pool_table.js";
12
17
  import { NavigationStates } from "./navigation_states.js";
13
18
  import { projectOverviewLight } from "./project_overview_light.js";
14
19
  import { applyProjectMigrations } from "../mutator/migration.js";
15
- import { cacheBlockPackTemplate } from "../mutator/template/template_cache.js";
20
+ import { blockParamsModel } from "../model/block_params_model.js";
16
21
  import { BLOCK_STORAGE_FACADE_VERSION, BlockStorageFacadeCallbacks, checkBlockFlag, extractConfig } from "@platforma-sdk/model";
17
22
  import { cachedDeserialize, createInfiniteRetryState, nextInfiniteRetryState, notEmpty } from "@milaboratories/ts-helpers";
18
23
  import fsp from "node:fs/promises";
24
+ import { asBlockId } from "@milaboratories/pl-model-common";
19
25
  import { Computable } from "@milaboratories/computable";
20
26
  import { setTimeout } from "node:timers/promises";
21
27
  import { DefaultRetryOptions, Pl, TreeFinality, ensureSignedResourceIdNotNull, field, isNotFoundError, isPermissionDenied, isTimeoutOrCancelError, isUnauthenticated, parseSignedResourceId, resourceIdToString, treeFilter } from "@milaboratories/pl-client";
@@ -35,6 +41,7 @@ function stringifyForDump(object) {
35
41
  /** Releases what the computables of a block hold. */
36
42
  function resetBlockState(computables) {
37
43
  computables.fullState.resetState();
44
+ computables.readiness.resetState();
38
45
  computables.dependencies.resetState();
39
46
  computables.dependents.resetState();
40
47
  }
@@ -263,7 +270,7 @@ var Project = class Project {
263
270
  if (storage.error !== void 0) throw new BlockInitParamsRejectedError(storage.error.message);
264
271
  initialStorage = storage.value;
265
272
  }
266
- const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp);
273
+ const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp, { preparer: this.env.bpPreparer });
267
274
  const newBlockSpec = blockCfg.modelAPIVersion === BLOCK_STORAGE_FACADE_VERSION ? {
268
275
  storageMode: "fromModel",
269
276
  blockPack: cachedBp,
@@ -316,13 +323,17 @@ var Project = class Project {
316
323
  /**
317
324
  * Update block to new block pack, optionally resetting args and ui state to
318
325
  * initial values
326
+ *
327
+ * @throws ModelAPIVersionMismatchError when `ops.requireModelAPIVersion` differs from the
328
+ * model API version of the new block pack; nothing is changed
319
329
  * */
320
- async updateBlockPack(blockId, blockPackSpec, resetArgs = false, author) {
330
+ async updateBlockPack(blockId, blockPackSpec, resetArgs = false, author, ops = {}) {
321
331
  const preparedBp = await this.env.bpPreparer.prepare(blockPackSpec);
322
332
  const blockCfg = extractConfig(preparedBp.config);
333
+ if (ops.requireModelAPIVersion !== void 0 && blockCfg.modelAPIVersion !== ops.requireModelAPIVersion) throw new ModelAPIVersionMismatchError(blockId, ops.requireModelAPIVersion, blockCfg.modelAPIVersion);
323
334
  this.env.runtimeCapabilities.throwIfIncompatible(blockCfg.featureFlags);
324
335
  throwIfMissingServerCapabilities(this.env.pl, preparedBp.requiredCapabilities);
325
- const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp);
336
+ const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp, { preparer: this.env.bpPreparer });
326
337
  const resetState = resetArgs ? { state: blockCfg.modelAPIVersion === 1 ? {
327
338
  args: blockCfg.initialArgs,
328
339
  uiState: blockCfg.initialUiState
@@ -375,13 +386,17 @@ var Project = class Project {
375
386
  * Renders production part of the block starting all connected heavy computations.
376
387
  * Upstream blocks of the specified block will be started automatically if in
377
388
  * stale state.
389
+ *
390
+ * @returns the ids of the blocks whose production was started, in project order; empty when
391
+ * the block and the blocks above it were up to date and nothing was started
378
392
  * */
379
393
  async runBlock(blockId) {
380
- await withProject(this.env.projectHelper, this.env.pl, this.rid, (mut) => mut.renderProduction([blockId], true), {
394
+ const started = await withProject(this.env.projectHelper, this.env.pl, this.rid, (mut) => [...mut.renderProduction([blockId], true)].map(asBlockId), {
381
395
  name: "runBlock",
382
396
  lockId: this.projectLockId
383
397
  });
384
398
  await this.refreshAfterWrite();
399
+ return started;
385
400
  }
386
401
  /**
387
402
  * Stops the block if it is running by destroying its production state. All
@@ -504,6 +519,23 @@ var Project = class Project {
504
519
  lockId: this.projectLockId
505
520
  });
506
521
  }
522
+ /**
523
+ * The block's model as functions between its kind's params and its data: `init(params)` and
524
+ * `templateParams(data)` of the model of the block's current pack (see {@link BlockParamsModel}).
525
+ * One read transaction finds the model; each call of the result then runs it in the VM on its
526
+ * own, with no block created and nothing written. A caller writes what it computed with
527
+ * {@link mutateBlockStorage}.
528
+ *
529
+ * @throws when the project has no such block
530
+ * @throws {ModelAPIVersionMismatchError} when the block is not on BlockModelV3
531
+ */
532
+ async getBlockParamsModel(blockId) {
533
+ const config = await withProject(this.env.projectHelper, this.env.pl, this.rid, (prj) => prj.getBlockConfig(blockId), {
534
+ name: "getBlockParamsModel",
535
+ lockId: this.projectLockId
536
+ });
537
+ return blockParamsModel(this.env.projectHelper, blockId, config);
538
+ }
507
539
  /** Update block settings */
508
540
  async setBlockSettings(blockId, newValue) {
509
541
  await withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, void 0, (mut) => {
@@ -583,6 +615,7 @@ var Project = class Project {
583
615
  }, v.overview?.blocks ?? [])
584
616
  };
585
617
  } }).withPreCalculatedValueTree(),
618
+ readiness: blockReadiness(this.projectTree.entry(), asBlockId(blockId), this.env),
586
619
  dependencies,
587
620
  dependents
588
621
  };
@@ -688,6 +721,55 @@ var Project = class Project {
688
721
  return this.getBlockComputables(blockId).fullState;
689
722
  }
690
723
  /**
724
+ * Returns a computable of what keeps the block from running or from being staged: the issues
725
+ * its model finds in its current data and the references to blocks it cannot read from (see
726
+ * {@link BlockReadiness}). The block's model runs when the value is asked for, not before, and
727
+ * again only after the project changed. `undefined` for a block not on model API version 2.
728
+ */
729
+ getBlockReadiness(blockId) {
730
+ return this.getBlockComputables(blockId).readiness;
731
+ }
732
+ /**
733
+ * Returns a computable of the project's result-pool columns, specs and refs with no data: as the
734
+ * block `query.viewAs` sees them (the block and the blocks above it), or as the last block sees
735
+ * them, which is every block's, and filtered by the selectors a block model passes to
736
+ * `ColumnsCollection.filter`. Nothing is computed before the value is asked for, and the
737
+ * computable is not kept by the project: each call makes a new one.
738
+ */
739
+ getPoolColumns(query = {}) {
740
+ return poolColumns(this.projectTree.entry(), query, this.env);
741
+ }
742
+ /**
743
+ * Returns a computable of the result-pool columns `ids` stand for, in their order, as the block
744
+ * `viewAs` sees the pool (default: every block's); `undefined` for an id that is no column of
745
+ * it. Each id is looked up directly, so it finds a column {@link getPoolColumns} leaves out for
746
+ * having the same spec as another (see {@link poolColumnsById}). Not kept by the project.
747
+ */
748
+ getPoolColumnsById(ids, viewAs) {
749
+ return poolColumnsById(this.projectTree.entry(), ids, viewAs);
750
+ }
751
+ /**
752
+ * Returns a computable of a PFrame over result-pool columns of the project, by their ids (see
753
+ * {@link poolFrame}): what the values of a pool column are read from. A column that is unknown,
754
+ * not ready, without data or failed, or whose id filters an axis, is refused, and nothing is
755
+ * built. The frame is built when the value is asked for and released by the computable's
756
+ * `resetState()`; the computable is not kept by the project, so its owner must reset it.
757
+ */
758
+ createPoolFrame(ids) {
759
+ return poolFrame(this.projectTree.entry(), ids, this.env);
760
+ }
761
+ /**
762
+ * Returns a computable of a table over result-pool columns of the project, built by the PFrame
763
+ * driver from `def`, whose columns are the ids {@link getPoolColumns} lists, discovered ones
764
+ * included (see {@link poolTable}): the query of a rich id is built on the host. An unknown
765
+ * column, or one whose data is missing or not ready, is refused, and nothing is built. The table is built when the value is asked for and released by the
766
+ * computable's `resetState()`; the computable is not kept by the project, so its owner must
767
+ * reset it.
768
+ */
769
+ createPoolTable(def) {
770
+ return poolTable(this.projectTree.entry(), def, this.env);
771
+ }
772
+ /**
691
773
  * Returns a computable, that can be used to retrieve and watch path of the
692
774
  * folder containing frontend code.
693
775
  * */
@@ -869,21 +951,6 @@ function convertErrorsToStrings(outputs) {
869
951
  }
870
952
  return result;
871
953
  }
872
- /** Throws when the connected backend doesn't advertise every capability the
873
- * block-pack requires (as declared in `meta.requiredCapabilities`).
874
- *
875
- * The matching set is the desktop's install gate moved server-side so both
876
- * the UI (`AddBlockModal`) and direct middle-layer callers (the MCP server's
877
- * `add_block` tool, programmatic block installs, tests) reject incompatible
878
- * blocks consistently. */
879
- function throwIfMissingServerCapabilities(pl, requiredCapabilities) {
880
- if (!requiredCapabilities || requiredCapabilities.length === 0) return;
881
- const advertised = pl.serverInfo.capabilities ?? [];
882
- const filterFn = (c) => !advertised.includes(c);
883
- if (!requiredCapabilities.some(filterFn)) return;
884
- const missing = requiredCapabilities.filter(filterFn);
885
- throw new Error(`Block cannot be added: connected backend does not advertise capabilities ${JSON.stringify(missing)}. Backend advertises ${JSON.stringify(advertised)}. Upgrade the backend or remove the requirement from the block manifest.`);
886
- }
887
- export { Project, isSnapshotFailsafeError, projectTreeFieldFilter, projectTreePruning, projectTreeTraverseStopRules, throwIfMissingServerCapabilities };
954
+ export { Project, isSnapshotFailsafeError, projectTreeFieldFilter, projectTreePruning, projectTreeTraverseStopRules };
888
955
 
889
956
  //# sourceMappingURL=project.js.map
@@ -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 { 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 /** Called once, from the maintenance loop, when the loop finds the project was deleted\n * elsewhere. The loop has stopped by then; the owner is expected to destroy the project. */\n private readonly onGone?: (project: Project) => void,\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 /**\n * Brings the project tree up to a write that has just committed.\n *\n * The write is already on the backend when this runs, so a project destroyed meanwhile (closed\n * by its last holder, or deleted) must not turn it into a failure: a caller told it failed would\n * retry it and apply it twice. `destroy` marks the project destroyed before it terminates the\n * tree, so a refresh failing on a terminated tree always finds the mark set.\n */\n private async refreshAfterWrite(): Promise<void> {\n if (this.destroyed) return;\n try {\n await this.projectTree.refreshState();\n } catch (e: unknown) {\n if (this.destroyed) return;\n throw e;\n }\n }\n\n private async refreshLoop(): Promise<void> {\n let retryState: InfiniteRetryState | undefined;\n let gone = false;\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 gone = true;\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 if (gone) this.onGone?.(this);\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.refreshAfterWrite();\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.refreshAfterWrite();\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.refreshAfterWrite();\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.refreshAfterWrite();\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.refreshAfterWrite();\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.refreshAfterWrite();\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.refreshAfterWrite();\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.refreshAfterWrite();\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.refreshAfterWrite();\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.refreshAfterWrite();\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.refreshAfterWrite();\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.refreshAfterWrite();\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.refreshAfterWrite();\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.refreshAfterWrite();\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 onGone?: (project: Project) => void,\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, onGone);\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;CA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CACnD,MAAM,YAAY,MAAc,CAAC,WAAW,SAAS,CAAC;CACtD,IAAI,CAAC,qBAAqB,KAAK,QAAQ,GAAG;CAC1C,MAAM,UAAU,qBAAqB,OAAO,QAAQ;CACpD,MAAM,IAAI,MACR,4EACK,KAAK,UAAU,OAAO,EAAE,uBACL,KAAK,UAAU,UAAU,EAAE,yEAErD;AACF"}
1
+ {"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 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, blockReadiness } from \"./block\";\nimport type { BlockReadiness } from \"../model/args_derivation\";\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 {\n asBlockId,\n type BlockId,\n type ColumnLink,\n type ColumnUniversalId,\n type PTableDefV2,\n} from \"@milaboratories/pl-model-common\";\nimport { activeConfigs } from \"./active_cfg\";\nimport {\n poolColumns,\n poolColumnsById,\n type PoolColumn,\n type PoolColumns,\n type PoolColumnsQuery,\n} from \"./pool_columns\";\nimport { poolFrame, type PoolFrame } from \"./pool_frame\";\nimport { poolTable, type PoolTable } from \"./pool_table\";\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 { blockParamsModel, type BlockParamsModel } from \"../model/block_params_model\";\nimport { cacheBlockPackTemplate } from \"../mutator/template/template_cache\";\nimport { throwIfMissingServerCapabilities } from \"../mutator/block-pack/required_capabilities\";\n\ntype BlockStateComputables = {\n readonly fullState: Computable<BlockStateInternalV3>;\n /** Lazy: the block's model runs only when the readiness is asked for. Not in the full state. */\n readonly readiness: Computable<BlockReadiness | undefined>;\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.readiness.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/** Options of {@link Project.updateBlockPack}. */\nexport type UpdateBlockPackOps = {\n /** Refuse a block pack 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 /** Called once, from the maintenance loop, when the loop finds the project was deleted\n * elsewhere. The loop has stopped by then; the owner is expected to destroy the project. */\n private readonly onGone?: (project: Project) => void,\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 /**\n * Brings the project tree up to a write that has just committed.\n *\n * The write is already on the backend when this runs, so a project destroyed meanwhile (closed\n * by its last holder, or deleted) must not turn it into a failure: a caller told it failed would\n * retry it and apply it twice. `destroy` marks the project destroyed before it terminates the\n * tree, so a refresh failing on a terminated tree always finds the mark set.\n */\n private async refreshAfterWrite(): Promise<void> {\n if (this.destroyed) return;\n try {\n await this.projectTree.refreshState();\n } catch (e: unknown) {\n if (this.destroyed) return;\n throw e;\n }\n }\n\n private async refreshLoop(): Promise<void> {\n let retryState: InfiniteRetryState | undefined;\n let gone = false;\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 gone = true;\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 if (gone) this.onGone?.(this);\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 preparer: this.env.bpPreparer,\n });\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.refreshAfterWrite();\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.refreshAfterWrite();\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 * @throws ModelAPIVersionMismatchError when `ops.requireModelAPIVersion` differs from the\n * model API version of the new block pack; nothing is changed\n * */\n public async updateBlockPack(\n blockId: string,\n blockPackSpec: BlockPackSpecAny,\n resetArgs: boolean = false,\n author?: AuthorMarker,\n ops: UpdateBlockPackOps = {},\n ): Promise<void> {\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 // Pre-materialize template via cache (separate transaction(s))\n const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp, {\n preparer: this.env.bpPreparer,\n });\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.refreshAfterWrite();\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.refreshAfterWrite();\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.refreshAfterWrite();\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 * @returns the ids of the blocks whose production was started, in project order; empty when\n * the block and the blocks above it were up to date and nothing was started\n * */\n public async runBlock(blockId: string): Promise<BlockId[]> {\n const started = await withProject(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n (mut) => [...mut.renderProduction([blockId], true)].map(asBlockId),\n { name: \"runBlock\", lockId: this.projectLockId },\n );\n await this.refreshAfterWrite();\n return started;\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.refreshAfterWrite();\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.refreshAfterWrite();\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.refreshAfterWrite();\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.refreshAfterWrite();\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.refreshAfterWrite();\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 /**\n * The block's model as functions between its kind's params and its data: `init(params)` and\n * `templateParams(data)` of the model of the block's current pack (see {@link BlockParamsModel}).\n * One read transaction finds the model; each call of the result then runs it in the VM on its\n * own, with no block created and nothing written. A caller writes what it computed with\n * {@link mutateBlockStorage}.\n *\n * @throws when the project has no such block\n * @throws {ModelAPIVersionMismatchError} when the block is not on BlockModelV3\n */\n public async getBlockParamsModel(blockId: BlockId): Promise<BlockParamsModel> {\n const config = await withProject(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n (prj) => prj.getBlockConfig(blockId),\n { name: \"getBlockParamsModel\", lockId: this.projectLockId },\n );\n return blockParamsModel(this.env.projectHelper, blockId, config);\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.refreshAfterWrite();\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.refreshAfterWrite();\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.refreshAfterWrite();\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 readiness: blockReadiness(this.projectTree.entry(), asBlockId(blockId), this.env),\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 of what keeps the block from running or from being staged: the issues\n * its model finds in its current data and the references to blocks it cannot read from (see\n * {@link BlockReadiness}). The block's model runs when the value is asked for, not before, and\n * again only after the project changed. `undefined` for a block not on model API version 2.\n */\n public getBlockReadiness(blockId: BlockId): Computable<BlockReadiness | undefined> {\n return this.getBlockComputables(blockId).readiness;\n }\n\n /**\n * Returns a computable of the project's result-pool columns, specs and refs with no data: as the\n * block `query.viewAs` sees them (the block and the blocks above it), or as the last block sees\n * them, which is every block's, and filtered by the selectors a block model passes to\n * `ColumnsCollection.filter`. Nothing is computed before the value is asked for, and the\n * computable is not kept by the project: each call makes a new one.\n */\n public getPoolColumns(query: PoolColumnsQuery = {}): Computable<PoolColumns> {\n return poolColumns(this.projectTree.entry(), query, this.env);\n }\n\n /**\n * Returns a computable of the result-pool columns `ids` stand for, in their order, as the block\n * `viewAs` sees the pool (default: every block's); `undefined` for an id that is no column of\n * it. Each id is looked up directly, so it finds a column {@link getPoolColumns} leaves out for\n * having the same spec as another (see {@link poolColumnsById}). Not kept by the project.\n */\n public getPoolColumnsById(\n ids: readonly ColumnUniversalId[],\n viewAs?: BlockId,\n ): Computable<(PoolColumn | undefined)[]> {\n return poolColumnsById(this.projectTree.entry(), ids, viewAs);\n }\n\n /**\n * Returns a computable of a PFrame over result-pool columns of the project, by their ids (see\n * {@link poolFrame}): what the values of a pool column are read from. A column that is unknown,\n * not ready, without data or failed, or whose id filters an axis, is refused, and nothing is\n * built. The frame is built when the value is asked for and released by the computable's\n * `resetState()`; the computable is not kept by the project, so its owner must reset it.\n */\n public createPoolFrame(ids: readonly ColumnUniversalId[]): Computable<PoolFrame> {\n return poolFrame(this.projectTree.entry(), ids, this.env);\n }\n\n /**\n * Returns a computable of a table over result-pool columns of the project, built by the PFrame\n * driver from `def`, whose columns are the ids {@link getPoolColumns} lists, discovered ones\n * included (see {@link poolTable}): the query of a rich id is built on the host. An unknown\n * column, or one whose data is missing or not ready, is refused, and nothing is built. The table is built when the value is asked for and released by the\n * computable's `resetState()`; the computable is not kept by the project, so its owner must\n * reset it.\n */\n public createPoolTable(def: PTableDefV2<ColumnUniversalId>): Computable<PoolTable> {\n return poolTable(this.projectTree.entry(), def, this.env);\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 onGone?: (project: Project) => void,\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, onGone);\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuHA,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;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