@milaboratories/pl-middle-layer 2.10.1 → 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 (152) 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 +24 -0
  7. package/dist/index.d.ts +11 -4
  8. package/dist/index.js +4 -2
  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 +18 -21
  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 +18 -21
  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 +83 -2
  75. package/dist/middle_layer/project.cjs.map +1 -1
  76. package/dist/middle_layer/project.d.ts +69 -3
  77. package/dist/middle_layer/project.d.ts.map +1 -1
  78. package/dist/middle_layer/project.js +84 -3
  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_params_model.cjs +42 -0
  97. package/dist/model/block_params_model.cjs.map +1 -0
  98. package/dist/model/block_params_model.d.ts +45 -0
  99. package/dist/model/block_params_model.d.ts.map +1 -0
  100. package/dist/model/block_params_model.js +42 -0
  101. package/dist/model/block_params_model.js.map +1 -0
  102. package/dist/model/index.d.ts +3 -1
  103. package/dist/model/project_helper.cjs +50 -6
  104. package/dist/model/project_helper.cjs.map +1 -1
  105. package/dist/model/project_helper.d.ts +25 -1
  106. package/dist/model/project_helper.d.ts.map +1 -1
  107. package/dist/model/project_helper.js +51 -7
  108. package/dist/model/project_helper.js.map +1 -1
  109. package/dist/mutator/block-pack/block_pack.cjs +1 -1
  110. package/dist/mutator/block-pack/block_pack.js +1 -1
  111. package/dist/mutator/project.cjs +4 -0
  112. package/dist/mutator/project.cjs.map +1 -1
  113. package/dist/mutator/project.d.ts +1 -1
  114. package/dist/mutator/project.d.ts.map +1 -1
  115. package/dist/mutator/project.js +4 -0
  116. package/dist/mutator/project.js.map +1 -1
  117. package/package.json +9 -9
  118. package/src/block_registry/registry-v2-provider.test.ts +23 -0
  119. package/src/block_registry/registry-v2-provider.ts +11 -1
  120. package/src/index.ts +2 -0
  121. package/src/js_render/bundle_bytecode_cache.ts +15 -4
  122. package/src/js_render/column_registry.ts +24 -3
  123. package/src/js_render/context.ts +4 -3
  124. package/src/js_render/index.ts +3 -2
  125. package/src/js_render/service_injectors.ts +2 -11
  126. package/src/middle_layer/block.ts +61 -2
  127. package/src/middle_layer/block_pack_description.test.ts +235 -0
  128. package/src/middle_layer/block_pack_description.ts +143 -0
  129. package/src/middle_layer/index.ts +9 -1
  130. package/src/middle_layer/legacy_project_holds.test.ts +133 -0
  131. package/src/middle_layer/legacy_project_holds.ts +73 -0
  132. package/src/middle_layer/middle_layer.ts +23 -26
  133. package/src/middle_layer/pool_columns.test.ts +217 -0
  134. package/src/middle_layer/pool_columns.ts +250 -0
  135. package/src/middle_layer/pool_frame.test.ts +144 -0
  136. package/src/middle_layer/pool_frame.ts +127 -0
  137. package/src/middle_layer/pool_table.test.ts +182 -0
  138. package/src/middle_layer/pool_table.ts +98 -0
  139. package/src/middle_layer/project.ts +128 -5
  140. package/src/middle_layer/rich_column_query.test.ts +311 -0
  141. package/src/middle_layer/rich_column_query.ts +214 -0
  142. package/src/model/args.test.ts +23 -1
  143. package/src/model/args.ts +29 -1
  144. package/src/model/args_derivation.test.ts +129 -12
  145. package/src/model/args_derivation.ts +112 -8
  146. package/src/model/block_params_model.test.ts +194 -0
  147. package/src/model/block_params_model.ts +117 -0
  148. package/src/model/index.ts +6 -0
  149. package/src/model/project_helper.ts +101 -20
  150. package/src/mutator/project.ts +5 -0
  151. package/src/pool/result_pool_markers.test.ts +47 -0
  152. package/src/test/fake_project.ts +33 -6
@@ -3,8 +3,8 @@ const require_index = require("../debug/index.cjs");
3
3
  const require_index$1 = require("../js_render/index.cjs");
4
4
  let _platforma_sdk_model = require("@platforma-sdk/model");
5
5
  let _milaboratories_ts_helpers = require("@milaboratories/ts-helpers");
6
- let _milaboratories_pl_model_common = require("@milaboratories/pl-model-common");
7
6
  let lru_cache = require("lru-cache");
7
+ let _milaboratories_pl_model_common = require("@milaboratories/pl-model-common");
8
8
  // src/model/project_helper.ts
9
9
  var ProjectHelper = class {
10
10
  quickJs;
@@ -59,12 +59,29 @@ var ProjectHelper = class {
59
59
  */
60
60
  derivePrerunArgsFromStorage(blockConfig, storageJson) {
61
61
  if (blockConfig.modelAPIVersion !== _platforma_sdk_model.BLOCK_STORAGE_FACADE_VERSION) throw new Error("derivePrerunArgsFromStorage is only supported for model API version 2");
62
+ const derived = this.derivePrerunArgsDetailedFromStorage(blockConfig, storageJson);
63
+ return derived.type === "staged" ? derived.args : void 0;
64
+ }
65
+ /**
66
+ * {@link derivePrerunArgsFromStorage} with the reason when there are no prerun args to stage:
67
+ * the issues found in them, the error of a lambda that threw, or a `prerunArgs()` that returned
68
+ * nothing. Never throws; a failure of the derivation itself is `failed`.
69
+ *
70
+ * @param blockConfig The block configuration (provides the model code)
71
+ * @param storageJson Storage as JSON string
72
+ */
73
+ derivePrerunArgsDetailedFromStorage(blockConfig, storageJson) {
74
+ if (blockConfig.modelAPIVersion !== _platforma_sdk_model.BLOCK_STORAGE_FACADE_VERSION) return {
75
+ type: "failed",
76
+ error: "Prerun args derivation from storage is only supported for model API version 2"
77
+ };
62
78
  try {
63
- const result = require_index$1.executeSingleLambda(this.quickJs, blockConfig.blockLifecycleCallbacks[_platforma_sdk_model.BlockStorageFacadeCallbacks.PrerunArgsDerive], (0, _platforma_sdk_model.extractCodeWithInfo)(blockConfig), storageJson);
64
- if (result.error !== void 0) return;
65
- return result.value;
66
- } catch {
67
- return;
79
+ return require_args_derivation.parsePrerunArgsDeriveResult(require_index$1.executeSingleLambda(this.quickJs, blockConfig.blockLifecycleCallbacks[_platforma_sdk_model.BlockStorageFacadeCallbacks.PrerunArgsDerive], (0, _platforma_sdk_model.extractCodeWithInfo)(blockConfig), storageJson));
80
+ } catch (e) {
81
+ return {
82
+ type: "failed",
83
+ error: `Prerun args derivation from storage failed: ${(0, _platforma_sdk_model.ensureError)(e).message}`
84
+ };
68
85
  }
69
86
  }
70
87
  /**
@@ -228,6 +245,33 @@ var ProjectHelper = class {
228
245
  }
229
246
  }
230
247
  /**
248
+ * Puts params onto a block's live data with the block's own `applyParams`, through the VM
249
+ * callback `__pl_storage_applyParams`. Nothing is written: the storage comes back as JSON.
250
+ *
251
+ * The callback runs the kind's params check first, as
252
+ * {@link getInitialStorageFromParamsInVM} does, and refuses data that is not at the data
253
+ * model's current version. Params are live: their references name blocks of this project and
254
+ * are not relocated.
255
+ *
256
+ * @param blockConfig The block configuration (provides the model code)
257
+ * @param storageJson The block's current storage as JSON string
258
+ * @param params The new params, whole
259
+ * @returns The storage with the params applied as JSON string, or why there is none
260
+ */
261
+ applyParamsInVM(blockConfig, storageJson, params) {
262
+ if (blockConfig.modelAPIVersion !== _platforma_sdk_model.BLOCK_STORAGE_FACADE_VERSION) return { error: /* @__PURE__ */ new Error("applyParamsInVM is only supported for model API version 2") };
263
+ const callback = blockConfig.blockLifecycleCallbacks[_platforma_sdk_model.BlockStorageFacadeCallbacks.StorageApplyParams];
264
+ if (callback === void 0) return { error: /* @__PURE__ */ new Error("This version of the block does not put params onto its data itself.") };
265
+ try {
266
+ const result = require_index$1.executeSingleLambda(this.quickJs, callback, (0, _platforma_sdk_model.extractCodeWithInfo)(blockConfig), storageJson, JSON.stringify(params ?? {}));
267
+ if (result.error !== void 0) return { error: new Error(result.error) };
268
+ return { value: result.storageJson };
269
+ } catch (e) {
270
+ const cause = (0, _platforma_sdk_model.ensureError)(e);
271
+ return { error: new Error(`Applying params to the block's data failed: ${cause.message}`, { cause }) };
272
+ }
273
+ }
274
+ /**
231
275
  * Applies a state update using VM-based transformation.
232
276
  * This calls the model's `__pl_storage_applyUpdate` callback which:
233
277
  * - Normalizes current storage
@@ -1 +1 @@
1
- {"version":3,"file":"project_helper.cjs","names":["LRUCache","ConsoleLoggerAdapter","BLOCK_STORAGE_FACADE_VERSION","parseArgsDeriveResult","executeSingleLambda","BlockStorageFacadeCallbacks","extractCodeWithInfo","ensureError","collectColumnReferences","getDebugFlags"],"sources":["../../src/model/project_helper.ts"],"sourcesContent":["import type { ResultOrError, BlockConfig, BlockStorage, PlRef } from \"@platforma-sdk/model\";\nimport type { ColumnReference, StringifiedJson } from \"@milaboratories/pl-model-common\";\nimport { collectColumnReferences } from \"@milaboratories/pl-model-common\";\nimport {\n extractCodeWithInfo,\n ensureError,\n BlockStorageFacadeCallbacks,\n BLOCK_STORAGE_FACADE_VERSION,\n} from \"@platforma-sdk/model\";\nimport { LRUCache } from \"lru-cache\";\nimport type { QuickJSWASMModule } from \"quickjs-emscripten\";\nimport { executeSingleLambda } from \"../js_render\";\nimport type { SignedResourceId } from \"@milaboratories/pl-client\";\nimport { ConsoleLoggerAdapter, type MiLogger } from \"@milaboratories/ts-helpers\";\nimport { getDebugFlags } from \"../debug\";\nimport { parseArgsDeriveResult, type DerivedArgs } from \"./args_derivation\";\n\ntype EnrichmentTargetsRequest = {\n blockConfig: () => BlockConfig;\n args: () => unknown;\n};\n\ntype EnrichmentTargetsValue = {\n value: PlRef[] | undefined;\n};\n\n/**\n * Result of VM-based storage migration.\n * Returned by migrateStorageInVM().\n *\n * - Error result: { error: string } - serious failure (no context, etc.)\n * - Success result: { newStorageJson: StringifiedJson<BlockStorage>, info: string } - migration succeeded\n */\nexport type MigrationResult =\n | { error: string }\n | { error?: undefined; newStorageJson: StringifiedJson<BlockStorage>; info: string };\n\n/**\n * Result of a derivation from storage that either produced a value or failed.\n * Returned by the __pl_prerunArgs_derive and __pl_initializationParams_derive VM callbacks; a\n * newer model adds the issues found in the prerun args, which are not read here.\n */\ntype DeriveResult = { error: string } | { error?: undefined; value: unknown };\n\n/**\n * Result of building initial storage from params.\n * Returned by the __pl_storage_initialFromParams VM callback.\n */\ntype ParamsStorageResult =\n | { error: string }\n | { error?: undefined; storageJson: StringifiedJson<BlockStorage> };\n\n/**\n * Result of checking params against their kind.\n * Returned by the __pl_initializationParams_validate VM callback.\n */\ntype InitializationParamsValidateResult = { error: string } | { error?: undefined };\n\nexport class ProjectHelper {\n private readonly enrichmentTargetsCache = new LRUCache<\n string,\n EnrichmentTargetsValue,\n EnrichmentTargetsRequest\n >({\n max: 256,\n memoMethod: (_key, _value, { context }) => {\n return { value: this.calculateEnrichmentTargets(context) };\n },\n });\n\n // An args resource never changes, so its id alone identifies the columns found in it.\n private readonly columnReferencesCache = new LRUCache<\n SignedResourceId,\n readonly ColumnReference[]\n >({ max: 1024 });\n\n constructor(\n private readonly quickJs: QuickJSWASMModule,\n public readonly logger: MiLogger = new ConsoleLoggerAdapter(),\n ) {}\n\n // =============================================================================\n // Args Derivation from Storage (V3+)\n // =============================================================================\n\n /**\n * Derives args directly from storage JSON using VM callback.\n * The VM extracts data from storage, calls the block's args() function and then its argsIssues().\n *\n * This allows the middle layer to work only with storage JSON,\n * without needing to know the underlying data structure.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson Storage as JSON string\n * @returns The derived args and whether the block may run with them, or why there are none\n */\n public deriveArgsFromStorage(blockConfig: BlockConfig, storageJson: string): DerivedArgs {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n type: \"absent\",\n error: new Error(\"deriveArgsFromStorage is only supported for model API version 2\"),\n };\n }\n\n try {\n return parseArgsDeriveResult(\n executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.ArgsDerive],\n extractCodeWithInfo(blockConfig),\n storageJson,\n ),\n );\n } catch (e) {\n return {\n type: \"absent\",\n error: new Error(\"Args derivation from storage failed\", { cause: ensureError(e) }),\n };\n }\n }\n\n /**\n * Derives prerunArgs directly from storage JSON using VM callback.\n * Falls back to args() if prerunArgs is not defined in the block model.\n *\n * Errors the block's `prerunArgsIssues()` finds in its prerun args, or for a block without its\n * own prerunArgs, the errors its `argsIssues()` finds in its args, come back as an `error` and\n * skip staging the same way.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson Storage as JSON string\n * @returns The derived prerunArgs, or undefined if derivation fails or found errors\n */\n public derivePrerunArgsFromStorage(blockConfig: BlockConfig, storageJson: string): unknown {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"derivePrerunArgsFromStorage is only supported for model API version 2\");\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.PrerunArgsDerive],\n extractCodeWithInfo(blockConfig),\n storageJson,\n ) as DeriveResult;\n\n if (result.error !== undefined) {\n // Return undefined if derivation fails (skip block in staging)\n return undefined;\n }\n return result.value;\n } catch {\n // Return undefined if derivation fails (skip block in staging)\n return undefined;\n }\n }\n\n /**\n * Derives this block's template-export params from storage JSON using the VM\n * callback (`__pl_initializationParams_derive`).\n *\n * The template-export counterpart of {@link deriveArgsFromStorage}: instead of\n * the args a workflow runs on, it returns the params that would recreate the\n * block — the inverse of the data model's `init`. Params come back exactly as the block\n * projected them, references included: nothing marks or rewrites them on the way out, so\n * nothing here has to know a kind's params shape or how a reference is spelled.\n *\n * A `{ value: undefined }` result means the block declares no `templateParams`, which only\n * a block built against an older SDK can do. It does not reach a document: the export walk\n * requires a mapping and reports anything else as that block's problem, so an entry always\n * carries params.\n *\n * Unlike {@link derivePrerunArgsFromStorage}, a failure here is surfaced rather\n * than swallowed — a prerun that cannot derive args just skips a block in\n * staging, whereas an export that silently drops a block produces a template\n * that does not describe the project.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson Storage as JSON string\n * @returns The derived params with identifiers wrapped, `undefined` if the block declares\n * no lambda, or an error if derivation failed\n */\n public deriveTemplateParamsFromStorage(\n blockConfig: BlockConfig,\n storageJson: string,\n ): ResultOrError<unknown> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\n \"deriveTemplateParamsFromStorage is only supported for model API version 2\",\n ),\n };\n }\n\n const callback =\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.InitializationParamsDerive];\n\n // A model built before this callback existed simply has no entry for it. That is\n // NOT the same as a block declaring no `templateParams`: the block may well have\n // params, we just have no way to ask for them. Reporting it as `undefined` params\n // would export the block stripped of its configuration and quietly rebuild a\n // differently-configured project, so it has to be an error.\n // The message names the one action available to whoever pressed Export. It\n // deliberately says nothing about SDKs or callbacks: the person reading it did\n // not build this block and cannot change how it was built.\n if (callback === undefined) {\n return {\n error: new Error(\n \"This version of the block cannot be written to a template. Update the block \" +\n \"to a newer version and export again.\",\n ),\n };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n callback,\n extractCodeWithInfo(blockConfig),\n storageJson,\n ) as DeriveResult;\n\n if (result.error !== undefined) {\n return { error: new Error(result.error) };\n }\n return { value: result.value };\n } catch (e) {\n const cause = ensureError(e);\n // The reason goes in the message, not only in `cause`: this error is rendered\n // into a per-block export problem and shown to whoever triggered the export,\n // and every layer between here and there carries only `message`.\n return {\n error: new Error(`Template params derivation from storage failed: ${cause.message}`, {\n cause,\n }),\n };\n }\n }\n\n private calculateEnrichmentTargets(req: EnrichmentTargetsRequest): PlRef[] | undefined {\n const blockConfig = req.blockConfig();\n if (blockConfig.enrichmentTargets === undefined) return undefined;\n const args = req.args();\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.enrichmentTargets,\n extractCodeWithInfo(blockConfig),\n args,\n ) as PlRef[];\n return result;\n }\n\n public getEnrichmentTargets(\n blockConfig: () => BlockConfig,\n args: () => unknown,\n key?: { argsRid: SignedResourceId; blockPackRid: SignedResourceId },\n ): PlRef[] | undefined {\n const req = { blockConfig, args };\n if (key === undefined) return this.calculateEnrichmentTargets(req);\n const cacheKey = `${key.argsRid}:${key.blockPackRid}`;\n return this.enrichmentTargetsCache.memo(cacheKey, { context: req }).value;\n }\n\n /**\n * Columns referenced by a block's args, with the values of them the args picked, read from the\n * args resource `argsRid`. `undefined` while the resource data is not loaded yet: `args`\n * returns `undefined` then, and nothing is remembered for such a read, so the references are\n * found once the data arrives.\n */\n public getColumnReferences(\n argsRid: SignedResourceId,\n args: () => unknown,\n ): undefined | readonly ColumnReference[] {\n const cached = this.columnReferencesCache.get(argsRid);\n if (cached !== undefined) return cached;\n const data = args();\n if (data === undefined) return undefined;\n const references = collectColumnReferences(data);\n this.columnReferencesCache.set(argsRid, references);\n return references;\n }\n\n // =============================================================================\n // VM-based Storage Operations\n // =============================================================================\n\n /**\n * Creates initial BlockStorage for a new block using VM-based transformation.\n * This calls the '__pl_storage_initial' callback registered by DataModel which:\n * - Gets initial data from DataModel.getDefaultData()\n * - Creates BlockStorage with correct version\n *\n * @param blockConfig The block configuration (provides the model code)\n * @returns Initial storage as JSON string\n * @throws Error if storage creation fails\n */\n public getInitialStorageInVM(blockConfig: BlockConfig): string {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"getInitialStorageInVM is only supported for model API version 2\");\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageInitial],\n extractCodeWithInfo(blockConfig),\n ) as string;\n return result;\n } catch (e) {\n this.logger.error(\n new Error(\"[ProjectHelper.getInitialStorageInVM] Initial storage creation failed\", {\n cause: e,\n }),\n );\n throw new Error(`Block initial storage creation failed: ${e}`);\n }\n }\n\n /**\n * Checks a template entry's params against the block's kind, creating nothing.\n *\n * The pre-flight half of {@link getInitialStorageFromParamsInVM}: run once per entry\n * before a template is applied, so params a kind rejects are reported against the\n * entry that carries them while there is still no project. Skipping it is safe —\n * initialization runs the same check — but then the report arrives after earlier\n * entries have already been created.\n *\n * Every kind declares a parser, so a pass here means the params were checked against\n * the contract — not merely that they were JSON.\n *\n * A block whose model predates the callback passes unchecked rather than failing.\n * Unlike initialization, this method creates nothing, so there is nothing to get wrong\n * by proceeding, and such a block is refused outright at the point it is applied.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param params The entry's params. Reference ids may be placeholders: what is being\n * checked is the shape of the params, not what they point at\n * @returns Nothing, or why the params were rejected\n */\n public validateTemplateParamsInVM(\n blockConfig: BlockConfig,\n params: unknown,\n ): ResultOrError<undefined> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\"validateTemplateParamsInVM is only supported for model API version 2\"),\n };\n }\n\n const callback =\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.InitializationParamsValidate];\n if (callback === undefined) return { value: undefined };\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n callback,\n extractCodeWithInfo(blockConfig),\n JSON.stringify(params ?? {}),\n ) as InitializationParamsValidateResult;\n\n if (result.error !== undefined) return { error: new Error(result.error) };\n return { value: undefined };\n } catch (e) {\n const cause = ensureError(e);\n return { error: new Error(`Params check failed to run: ${cause.message}`, { cause }) };\n }\n }\n\n /**\n * Creates initial BlockStorage for a block being created from template params.\n *\n * The inverse of {@link deriveTemplateParamsFromStorage}, and the reason a block\n * can be created by anything other than the UI: it hands the params to the\n * block's own init factory inside the model VM, so the resulting storage is\n * whatever that block considers a correctly-initialized state.\n *\n * **Pointing the entry's references at this project happens in the same call**, before the\n * factory sees them — inside the block's bundle, because recognizing a reference means\n * knowing the reference system and a template engine deliberately does not. Params reach\n * here exactly as the file held them.\n *\n * One call and not two: every VM call builds a fresh runtime and re-evaluates the whole\n * model bundle, so asking the block to relocate and then asking it to initialize would parse\n * it twice per entry, for an intermediate value nothing else reads.\n *\n * `blockIds` holds the entries created so far, so an id it does not name is left as it is —\n * a reference to an entry further down the file keeps pointing at nothing, and the applied\n * block reports itself as missing references rather than being wired to a block below it.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param params The entry's params, as the document held them\n * @param blockIds template-local entry id → the block id that entry was given\n * @returns The initial storage as JSON string, or why the params yield none\n */\n public getInitialStorageFromParamsInVM(\n blockConfig: BlockConfig,\n params: unknown,\n blockIds: ReadonlyMap<string, string>,\n ): ResultOrError<string> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\n \"getInitialStorageFromParamsInVM is only supported for model API version 2\",\n ),\n };\n }\n\n const callback =\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageInitialFromParams];\n\n // A model built before this callback existed has no entry for it. Falling back to the\n // params-less initializer is not an option: it would produce a default-configured block\n // that looks like a successful apply, so the block the user gets would silently differ\n // from the one the template describes. Nor could its params be used as written — they name\n // the blocks of the project the template came from, and only this callback knows which of\n // the values in there are references at all.\n //\n // The message offers the two actions available to whoever applied the file. The\n // second one is the reason this branch is reachable at all: kind resolution only\n // ever returns a block that declares a kind, and such a block is new enough to\n // support this — but an entry may pin an exact block version instead, bypassing\n // resolution, and that pin can name anything ever published.\n if (callback === undefined) {\n return {\n error: new Error(\n \"This version of the block cannot be created from a template. Use a newer \" +\n \"version of the block, or remove the pinned block version from the template \" +\n \"entry so a supported one is chosen automatically.\",\n ),\n };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n callback,\n extractCodeWithInfo(blockConfig),\n // Params cross the VM boundary as text, like storage does. `undefined` would\n // stringify to nothing at all, and an entry with no params must go through\n // the params-less initializer rather than reaching this method.\n JSON.stringify(params ?? {}),\n JSON.stringify(Object.fromEntries(blockIds)),\n ) as ParamsStorageResult;\n\n if (result.error !== undefined) return { error: new Error(result.error) };\n return { value: result.storageJson };\n } catch (e) {\n const cause = ensureError(e);\n // The reason goes in the message, not only in `cause`: this error becomes a\n // per-entry apply problem shown to whoever triggered the import, and every\n // layer in between carries only `message`.\n return {\n error: new Error(`Initial storage creation from params failed: ${cause.message}`, {\n cause,\n }),\n };\n }\n }\n\n /**\n * Applies a state update using VM-based transformation.\n * This calls the model's `__pl_storage_applyUpdate` callback which:\n * - Normalizes current storage\n * - Updates state while preserving other fields (version, plugins)\n * - Returns the updated storage as JSON string\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param currentStorageJson Current storage as JSON string (must be defined)\n * @param newState New state from developer\n * @returns Updated storage as JSON string\n * @throws Error if storage update fails\n */\n public applyStorageUpdateInVM(\n blockConfig: BlockConfig,\n currentStorageJson: string,\n payload: { operation: string; value: unknown },\n ): string {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"applyStorageUpdateInVM is only supported for model API version 2\");\n }\n\n if (getDebugFlags().logJsExecStat) {\n this.logger.info(\n `[ProjectHelper.applyStorageUpdateInVM] currentStorageJson=${currentStorageJson.length}B, payload=${JSON.stringify(payload).length}B, operation=${payload.operation}`,\n );\n }\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageApplyUpdate],\n extractCodeWithInfo(blockConfig),\n currentStorageJson,\n payload,\n ) as string;\n return result;\n } catch (e) {\n const payloadJson = JSON.stringify(payload);\n this.logger.error(\n new Error(\n `[ProjectHelper.applyStorageUpdateInVM] Storage update failed (currentStorageJson=${currentStorageJson.length}B, payload=${payloadJson.length}B, operation=${payload.operation})`,\n { cause: e },\n ),\n );\n throw new Error(`Block storage update failed: ${e}`);\n }\n }\n\n // =============================================================================\n // Block State Migrations\n // =============================================================================\n\n /**\n * Runs block state migrations via VM-based transformation.\n * This calls the model's `__pl_storage_migrate` callback which:\n * - Normalizes current storage to get state and version\n * - Applies DataModel upgrade to reach target version key\n * - Runs all necessary migrations sequentially\n * - Returns new storage with updated state and version\n *\n * The middle layer doesn't need to know about dataVersion or storage internals.\n * All migration logic is encapsulated in the model.\n *\n * @param blockConfig The NEW block configuration (provides the model code with migrations)\n * @param currentStorageJson Current storage as JSON string (or undefined)\n * @returns MigrationResult with new storage or skip/error info\n */\n public migrateStorageInVM(\n blockConfig: BlockConfig,\n currentStorageJson: string | undefined,\n ): MigrationResult {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return { error: \"migrateStorageInVM is only supported for model API version 2\" };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageMigrate],\n extractCodeWithInfo(blockConfig),\n currentStorageJson,\n ) as MigrationResult;\n return result;\n } catch (e) {\n this.logger.error(\n new Error(\"[ProjectHelper.migrateStorageInVM] Migration failed\", { cause: e }),\n );\n return { error: `VM execution failed: ${e}` };\n }\n }\n}\n"],"mappings":";;;;;;;;AA0DA,IAAa,gBAAb,MAA2B;CAmBN;CACD;CAnBlB,yBAA0C,IAAIA,UAAAA,SAI5C;EACA,KAAK;EACL,aAAa,MAAM,QAAQ,EAAE,cAAc;GACzC,OAAO,EAAE,OAAO,KAAK,2BAA2B,OAAO,EAAE;EAC3D;CACF,CAAC;CAGD,wBAAyC,IAAIA,UAAAA,SAG3C,EAAE,KAAK,KAAK,CAAC;CAEf,YACE,SACA,SAAmC,IAAIC,2BAAAA,qBAAqB,GAC5D;EAFiB,KAAA,UAAA;EACD,KAAA,SAAA;CACf;;;;;;;;;;;;CAiBH,sBAA6B,aAA0B,aAAkC;EACvF,IAAI,YAAY,oBAAoBC,qBAAAA,8BAClC,OAAO;GACL,MAAM;GACN,uBAAO,IAAI,MAAM,iEAAiE;EACpF;EAGF,IAAI;GACF,OAAOC,wBAAAA,sBACLC,gBAAAA,oBACE,KAAK,SACL,YAAY,wBAAwBC,qBAAAA,4BAA4B,cAAA,GAChEC,qBAAAA,oBAAAA,CAAoB,WAAW,GAC/B,WACF,CACF;EACF,SAAS,GAAG;GACV,OAAO;IACL,MAAM;IACN,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ACR,IAAI,YAAY,oBAAoBL,qBAAAA,8BAClC,MAAM,IAAI,MAAM,kEAAkE;EAGpF,IAAIO,cAAAA,cAAc,CAAC,CAAC,eAClB,KAAK,OAAO,KACV,6DAA6D,mBAAmB,OAAO,aAAa,KAAK,UAAU,OAAO,CAAC,CAAC,OAAO,eAAe,QAAQ,WAC5J;EAEF,IAAI;GAQF,OAPeL,gBAAAA,oBACb,KAAK,SACL,YAAY,wBAAwBC,qBAAAA,4BAA4B,sBAAA,GAChEC,qBAAAA,oBAAAA,CAAoB,WAAW,GAC/B,oBACA,OAEU;EACd,SAAS,GAAG;GACV,MAAM,cAAc,KAAK,UAAU,OAAO;GAC1C,KAAK,OAAO,MACV,IAAI,MACF,oFAAoF,mBAAmB,OAAO,aAAa,YAAY,OAAO,eAAe,QAAQ,UAAU,IAC/K,EAAE,OAAO,EAAE,CACb,CACF;GACA,MAAM,IAAI,MAAM,gCAAgC,GAAG;EACrD;CACF;;;;;;;;;;;;;;;;CAqBA,mBACE,aACA,oBACiB;EACjB,IAAI,YAAY,oBAAoBJ,qBAAAA,8BAClC,OAAO,EAAE,OAAO,+DAA+D;EAGjF,IAAI;GAOF,OANeE,gBAAAA,oBACb,KAAK,SACL,YAAY,wBAAwBC,qBAAAA,4BAA4B,kBAAA,GAChEC,qBAAAA,oBAAAA,CAAoB,WAAW,GAC/B,kBAEU;EACd,SAAS,GAAG;GACV,KAAK,OAAO,MACV,IAAI,MAAM,uDAAuD,EAAE,OAAO,EAAE,CAAC,CAC/E;GACA,OAAO,EAAE,OAAO,wBAAwB,IAAI;EAC9C;CACF;AACF"}
1
+ {"version":3,"file":"project_helper.cjs","names":["LRUCache","ConsoleLoggerAdapter","BLOCK_STORAGE_FACADE_VERSION","parseArgsDeriveResult","executeSingleLambda","BlockStorageFacadeCallbacks","extractCodeWithInfo","ensureError","parsePrerunArgsDeriveResult","collectColumnReferences","getDebugFlags"],"sources":["../../src/model/project_helper.ts"],"sourcesContent":["import type { ResultOrError, BlockConfig, BlockStorage, PlRef } from \"@platforma-sdk/model\";\nimport type { ColumnReference, StringifiedJson } from \"@milaboratories/pl-model-common\";\nimport { collectColumnReferences } from \"@milaboratories/pl-model-common\";\nimport {\n extractCodeWithInfo,\n ensureError,\n BlockStorageFacadeCallbacks,\n BLOCK_STORAGE_FACADE_VERSION,\n} from \"@platforma-sdk/model\";\nimport { LRUCache } from \"lru-cache\";\nimport type { QuickJSWASMModule } from \"quickjs-emscripten\";\nimport { executeSingleLambda } from \"../js_render\";\nimport type { SignedResourceId } from \"@milaboratories/pl-client\";\nimport { ConsoleLoggerAdapter, type MiLogger } from \"@milaboratories/ts-helpers\";\nimport { getDebugFlags } from \"../debug\";\nimport {\n parseArgsDeriveResult,\n parsePrerunArgsDeriveResult,\n type DerivedArgs,\n type DerivedPrerunArgs,\n} from \"./args_derivation\";\n\ntype EnrichmentTargetsRequest = {\n blockConfig: () => BlockConfig;\n args: () => unknown;\n};\n\ntype EnrichmentTargetsValue = {\n value: PlRef[] | undefined;\n};\n\n/**\n * Result of VM-based storage migration.\n * Returned by migrateStorageInVM().\n *\n * - Error result: { error: string } - serious failure (no context, etc.)\n * - Success result: { newStorageJson: StringifiedJson<BlockStorage>, info: string } - migration succeeded\n */\nexport type MigrationResult =\n | { error: string }\n | { error?: undefined; newStorageJson: StringifiedJson<BlockStorage>; info: string };\n\n/**\n * Result of a derivation from storage that either produced a value or failed.\n * Returned by the __pl_initializationParams_derive VM callback.\n */\ntype DeriveResult = { error: string } | { error?: undefined; value: unknown };\n\n/**\n * Result of building storage from params.\n * Returned by the __pl_storage_initialFromParams and __pl_storage_applyParams VM callbacks.\n */\ntype ParamsStorageResult =\n | { error: string }\n | { error?: undefined; storageJson: StringifiedJson<BlockStorage> };\n\n/**\n * Result of checking params against their kind.\n * Returned by the __pl_initializationParams_validate VM callback.\n */\ntype InitializationParamsValidateResult = { error: string } | { error?: undefined };\n\nexport class ProjectHelper {\n private readonly enrichmentTargetsCache = new LRUCache<\n string,\n EnrichmentTargetsValue,\n EnrichmentTargetsRequest\n >({\n max: 256,\n memoMethod: (_key, _value, { context }) => {\n return { value: this.calculateEnrichmentTargets(context) };\n },\n });\n\n // An args resource never changes, so its id alone identifies the columns found in it.\n private readonly columnReferencesCache = new LRUCache<\n SignedResourceId,\n readonly ColumnReference[]\n >({ max: 1024 });\n\n constructor(\n private readonly quickJs: QuickJSWASMModule,\n public readonly logger: MiLogger = new ConsoleLoggerAdapter(),\n ) {}\n\n // =============================================================================\n // Args Derivation from Storage (V3+)\n // =============================================================================\n\n /**\n * Derives args directly from storage JSON using VM callback.\n * The VM extracts data from storage, calls the block's args() function and then its argsIssues().\n *\n * This allows the middle layer to work only with storage JSON,\n * without needing to know the underlying data structure.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson Storage as JSON string\n * @returns The derived args and whether the block may run with them, or why there are none\n */\n public deriveArgsFromStorage(blockConfig: BlockConfig, storageJson: string): DerivedArgs {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n type: \"absent\",\n error: new Error(\"deriveArgsFromStorage is only supported for model API version 2\"),\n };\n }\n\n try {\n return parseArgsDeriveResult(\n executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.ArgsDerive],\n extractCodeWithInfo(blockConfig),\n storageJson,\n ),\n );\n } catch (e) {\n return {\n type: \"absent\",\n error: new Error(\"Args derivation from storage failed\", { cause: ensureError(e) }),\n };\n }\n }\n\n /**\n * Derives prerunArgs directly from storage JSON using VM callback.\n * Falls back to args() if prerunArgs is not defined in the block model.\n *\n * Errors the block's `prerunArgsIssues()` finds in its prerun args, or for a block without its\n * own prerunArgs, the errors its `argsIssues()` finds in its args, come back as an `error` and\n * skip staging the same way.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson Storage as JSON string\n * @returns The derived prerunArgs, or undefined if derivation fails or found errors\n */\n public derivePrerunArgsFromStorage(blockConfig: BlockConfig, storageJson: string): unknown {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"derivePrerunArgsFromStorage is only supported for model API version 2\");\n }\n const derived = this.derivePrerunArgsDetailedFromStorage(blockConfig, storageJson);\n // Anything but staged args skips the block in staging.\n return derived.type === \"staged\" ? derived.args : undefined;\n }\n\n /**\n * {@link derivePrerunArgsFromStorage} with the reason when there are no prerun args to stage:\n * the issues found in them, the error of a lambda that threw, or a `prerunArgs()` that returned\n * nothing. Never throws; a failure of the derivation itself is `failed`.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson Storage as JSON string\n */\n public derivePrerunArgsDetailedFromStorage(\n blockConfig: BlockConfig,\n storageJson: string,\n ): DerivedPrerunArgs {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n type: \"failed\",\n error: \"Prerun args derivation from storage is only supported for model API version 2\",\n };\n }\n\n try {\n return parsePrerunArgsDeriveResult(\n executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.PrerunArgsDerive],\n extractCodeWithInfo(blockConfig),\n storageJson,\n ),\n );\n } catch (e) {\n return {\n type: \"failed\",\n error: `Prerun args derivation from storage failed: ${ensureError(e).message}`,\n };\n }\n }\n\n /**\n * Derives this block's template-export params from storage JSON using the VM\n * callback (`__pl_initializationParams_derive`).\n *\n * The template-export counterpart of {@link deriveArgsFromStorage}: instead of\n * the args a workflow runs on, it returns the params that would recreate the\n * block — the inverse of the data model's `init`. Params come back exactly as the block\n * projected them, references included: nothing marks or rewrites them on the way out, so\n * nothing here has to know a kind's params shape or how a reference is spelled.\n *\n * A `{ value: undefined }` result means the block declares no `templateParams`, which only\n * a block built against an older SDK can do. It does not reach a document: the export walk\n * requires a mapping and reports anything else as that block's problem, so an entry always\n * carries params.\n *\n * Unlike {@link derivePrerunArgsFromStorage}, a failure here is surfaced rather\n * than swallowed — a prerun that cannot derive args just skips a block in\n * staging, whereas an export that silently drops a block produces a template\n * that does not describe the project.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson Storage as JSON string\n * @returns The derived params with identifiers wrapped, `undefined` if the block declares\n * no lambda, or an error if derivation failed\n */\n public deriveTemplateParamsFromStorage(\n blockConfig: BlockConfig,\n storageJson: string,\n ): ResultOrError<unknown> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\n \"deriveTemplateParamsFromStorage is only supported for model API version 2\",\n ),\n };\n }\n\n const callback =\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.InitializationParamsDerive];\n\n // A model built before this callback existed simply has no entry for it. That is\n // NOT the same as a block declaring no `templateParams`: the block may well have\n // params, we just have no way to ask for them. Reporting it as `undefined` params\n // would export the block stripped of its configuration and quietly rebuild a\n // differently-configured project, so it has to be an error.\n // The message names the one action available to whoever pressed Export. It\n // deliberately says nothing about SDKs or callbacks: the person reading it did\n // not build this block and cannot change how it was built.\n if (callback === undefined) {\n return {\n error: new Error(\n \"This version of the block cannot be written to a template. Update the block \" +\n \"to a newer version and export again.\",\n ),\n };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n callback,\n extractCodeWithInfo(blockConfig),\n storageJson,\n ) as DeriveResult;\n\n if (result.error !== undefined) {\n return { error: new Error(result.error) };\n }\n return { value: result.value };\n } catch (e) {\n const cause = ensureError(e);\n // The reason goes in the message, not only in `cause`: this error is rendered\n // into a per-block export problem and shown to whoever triggered the export,\n // and every layer between here and there carries only `message`.\n return {\n error: new Error(`Template params derivation from storage failed: ${cause.message}`, {\n cause,\n }),\n };\n }\n }\n\n private calculateEnrichmentTargets(req: EnrichmentTargetsRequest): PlRef[] | undefined {\n const blockConfig = req.blockConfig();\n if (blockConfig.enrichmentTargets === undefined) return undefined;\n const args = req.args();\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.enrichmentTargets,\n extractCodeWithInfo(blockConfig),\n args,\n ) as PlRef[];\n return result;\n }\n\n public getEnrichmentTargets(\n blockConfig: () => BlockConfig,\n args: () => unknown,\n key?: { argsRid: SignedResourceId; blockPackRid: SignedResourceId },\n ): PlRef[] | undefined {\n const req = { blockConfig, args };\n if (key === undefined) return this.calculateEnrichmentTargets(req);\n const cacheKey = `${key.argsRid}:${key.blockPackRid}`;\n return this.enrichmentTargetsCache.memo(cacheKey, { context: req }).value;\n }\n\n /**\n * Columns referenced by a block's args, with the values of them the args picked, read from the\n * args resource `argsRid`. `undefined` while the resource data is not loaded yet: `args`\n * returns `undefined` then, and nothing is remembered for such a read, so the references are\n * found once the data arrives.\n */\n public getColumnReferences(\n argsRid: SignedResourceId,\n args: () => unknown,\n ): undefined | readonly ColumnReference[] {\n const cached = this.columnReferencesCache.get(argsRid);\n if (cached !== undefined) return cached;\n const data = args();\n if (data === undefined) return undefined;\n const references = collectColumnReferences(data);\n this.columnReferencesCache.set(argsRid, references);\n return references;\n }\n\n // =============================================================================\n // VM-based Storage Operations\n // =============================================================================\n\n /**\n * Creates initial BlockStorage for a new block using VM-based transformation.\n * This calls the '__pl_storage_initial' callback registered by DataModel which:\n * - Gets initial data from DataModel.getDefaultData()\n * - Creates BlockStorage with correct version\n *\n * @param blockConfig The block configuration (provides the model code)\n * @returns Initial storage as JSON string\n * @throws Error if storage creation fails\n */\n public getInitialStorageInVM(blockConfig: BlockConfig): string {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"getInitialStorageInVM is only supported for model API version 2\");\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageInitial],\n extractCodeWithInfo(blockConfig),\n ) as string;\n return result;\n } catch (e) {\n this.logger.error(\n new Error(\"[ProjectHelper.getInitialStorageInVM] Initial storage creation failed\", {\n cause: e,\n }),\n );\n throw new Error(`Block initial storage creation failed: ${e}`);\n }\n }\n\n /**\n * Checks a template entry's params against the block's kind, creating nothing.\n *\n * The pre-flight half of {@link getInitialStorageFromParamsInVM}: run once per entry\n * before a template is applied, so params a kind rejects are reported against the\n * entry that carries them while there is still no project. Skipping it is safe —\n * initialization runs the same check — but then the report arrives after earlier\n * entries have already been created.\n *\n * Every kind declares a parser, so a pass here means the params were checked against\n * the contract — not merely that they were JSON.\n *\n * A block whose model predates the callback passes unchecked rather than failing.\n * Unlike initialization, this method creates nothing, so there is nothing to get wrong\n * by proceeding, and such a block is refused outright at the point it is applied.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param params The entry's params. Reference ids may be placeholders: what is being\n * checked is the shape of the params, not what they point at\n * @returns Nothing, or why the params were rejected\n */\n public validateTemplateParamsInVM(\n blockConfig: BlockConfig,\n params: unknown,\n ): ResultOrError<undefined> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\"validateTemplateParamsInVM is only supported for model API version 2\"),\n };\n }\n\n const callback =\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.InitializationParamsValidate];\n if (callback === undefined) return { value: undefined };\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n callback,\n extractCodeWithInfo(blockConfig),\n JSON.stringify(params ?? {}),\n ) as InitializationParamsValidateResult;\n\n if (result.error !== undefined) return { error: new Error(result.error) };\n return { value: undefined };\n } catch (e) {\n const cause = ensureError(e);\n return { error: new Error(`Params check failed to run: ${cause.message}`, { cause }) };\n }\n }\n\n /**\n * Creates initial BlockStorage for a block being created from template params.\n *\n * The inverse of {@link deriveTemplateParamsFromStorage}, and the reason a block\n * can be created by anything other than the UI: it hands the params to the\n * block's own init factory inside the model VM, so the resulting storage is\n * whatever that block considers a correctly-initialized state.\n *\n * **Pointing the entry's references at this project happens in the same call**, before the\n * factory sees them — inside the block's bundle, because recognizing a reference means\n * knowing the reference system and a template engine deliberately does not. Params reach\n * here exactly as the file held them.\n *\n * One call and not two: every VM call builds a fresh runtime and re-evaluates the whole\n * model bundle, so asking the block to relocate and then asking it to initialize would parse\n * it twice per entry, for an intermediate value nothing else reads.\n *\n * `blockIds` holds the entries created so far, so an id it does not name is left as it is —\n * a reference to an entry further down the file keeps pointing at nothing, and the applied\n * block reports itself as missing references rather than being wired to a block below it.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param params The entry's params, as the document held them\n * @param blockIds template-local entry id → the block id that entry was given\n * @returns The initial storage as JSON string, or why the params yield none\n */\n public getInitialStorageFromParamsInVM(\n blockConfig: BlockConfig,\n params: unknown,\n blockIds: ReadonlyMap<string, string>,\n ): ResultOrError<string> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\n \"getInitialStorageFromParamsInVM is only supported for model API version 2\",\n ),\n };\n }\n\n const callback =\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageInitialFromParams];\n\n // A model built before this callback existed has no entry for it. Falling back to the\n // params-less initializer is not an option: it would produce a default-configured block\n // that looks like a successful apply, so the block the user gets would silently differ\n // from the one the template describes. Nor could its params be used as written — they name\n // the blocks of the project the template came from, and only this callback knows which of\n // the values in there are references at all.\n //\n // The message offers the two actions available to whoever applied the file. The\n // second one is the reason this branch is reachable at all: kind resolution only\n // ever returns a block that declares a kind, and such a block is new enough to\n // support this — but an entry may pin an exact block version instead, bypassing\n // resolution, and that pin can name anything ever published.\n if (callback === undefined) {\n return {\n error: new Error(\n \"This version of the block cannot be created from a template. Use a newer \" +\n \"version of the block, or remove the pinned block version from the template \" +\n \"entry so a supported one is chosen automatically.\",\n ),\n };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n callback,\n extractCodeWithInfo(blockConfig),\n // Params cross the VM boundary as text, like storage does. `undefined` would\n // stringify to nothing at all, and an entry with no params must go through\n // the params-less initializer rather than reaching this method.\n JSON.stringify(params ?? {}),\n JSON.stringify(Object.fromEntries(blockIds)),\n ) as ParamsStorageResult;\n\n if (result.error !== undefined) return { error: new Error(result.error) };\n return { value: result.storageJson };\n } catch (e) {\n const cause = ensureError(e);\n // The reason goes in the message, not only in `cause`: this error becomes a\n // per-entry apply problem shown to whoever triggered the import, and every\n // layer in between carries only `message`.\n return {\n error: new Error(`Initial storage creation from params failed: ${cause.message}`, {\n cause,\n }),\n };\n }\n }\n\n /**\n * Puts params onto a block's live data with the block's own `applyParams`, through the VM\n * callback `__pl_storage_applyParams`. Nothing is written: the storage comes back as JSON.\n *\n * The callback runs the kind's params check first, as\n * {@link getInitialStorageFromParamsInVM} does, and refuses data that is not at the data\n * model's current version. Params are live: their references name blocks of this project and\n * are not relocated.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson The block's current storage as JSON string\n * @param params The new params, whole\n * @returns The storage with the params applied as JSON string, or why there is none\n */\n public applyParamsInVM(\n blockConfig: BlockConfig,\n storageJson: string,\n params: unknown,\n ): ResultOrError<string> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\"applyParamsInVM is only supported for model API version 2\"),\n };\n }\n\n // Registered only by a block that declares `applyParams`; anything else builds data\n // from params with `init` instead, which is the caller's call to make.\n const callback =\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageApplyParams];\n if (callback === undefined) {\n return {\n error: new Error(\"This version of the block does not put params onto its data itself.\"),\n };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n callback,\n extractCodeWithInfo(blockConfig),\n storageJson,\n JSON.stringify(params ?? {}),\n ) as ParamsStorageResult;\n\n if (result.error !== undefined) return { error: new Error(result.error) };\n return { value: result.storageJson };\n } catch (e) {\n const cause = ensureError(e);\n return {\n error: new Error(`Applying params to the block's data failed: ${cause.message}`, {\n cause,\n }),\n };\n }\n }\n\n /**\n * Applies a state update using VM-based transformation.\n * This calls the model's `__pl_storage_applyUpdate` callback which:\n * - Normalizes current storage\n * - Updates state while preserving other fields (version, plugins)\n * - Returns the updated storage as JSON string\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param currentStorageJson Current storage as JSON string (must be defined)\n * @param newState New state from developer\n * @returns Updated storage as JSON string\n * @throws Error if storage update fails\n */\n public applyStorageUpdateInVM(\n blockConfig: BlockConfig,\n currentStorageJson: string,\n payload: { operation: string; value: unknown },\n ): string {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"applyStorageUpdateInVM is only supported for model API version 2\");\n }\n\n if (getDebugFlags().logJsExecStat) {\n this.logger.info(\n `[ProjectHelper.applyStorageUpdateInVM] currentStorageJson=${currentStorageJson.length}B, payload=${JSON.stringify(payload).length}B, operation=${payload.operation}`,\n );\n }\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageApplyUpdate],\n extractCodeWithInfo(blockConfig),\n currentStorageJson,\n payload,\n ) as string;\n return result;\n } catch (e) {\n const payloadJson = JSON.stringify(payload);\n this.logger.error(\n new Error(\n `[ProjectHelper.applyStorageUpdateInVM] Storage update failed (currentStorageJson=${currentStorageJson.length}B, payload=${payloadJson.length}B, operation=${payload.operation})`,\n { cause: e },\n ),\n );\n throw new Error(`Block storage update failed: ${e}`);\n }\n }\n\n // =============================================================================\n // Block State Migrations\n // =============================================================================\n\n /**\n * Runs block state migrations via VM-based transformation.\n * This calls the model's `__pl_storage_migrate` callback which:\n * - Normalizes current storage to get state and version\n * - Applies DataModel upgrade to reach target version key\n * - Runs all necessary migrations sequentially\n * - Returns new storage with updated state and version\n *\n * The middle layer doesn't need to know about dataVersion or storage internals.\n * All migration logic is encapsulated in the model.\n *\n * @param blockConfig The NEW block configuration (provides the model code with migrations)\n * @param currentStorageJson Current storage as JSON string (or undefined)\n * @returns MigrationResult with new storage or skip/error info\n */\n public migrateStorageInVM(\n blockConfig: BlockConfig,\n currentStorageJson: string | undefined,\n ): MigrationResult {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return { error: \"migrateStorageInVM is only supported for model API version 2\" };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageMigrate],\n extractCodeWithInfo(blockConfig),\n currentStorageJson,\n ) as MigrationResult;\n return result;\n } catch (e) {\n this.logger.error(\n new Error(\"[ProjectHelper.migrateStorageInVM] Migration failed\", { cause: e }),\n );\n return { error: `VM execution failed: ${e}` };\n }\n }\n}\n"],"mappings":";;;;;;;;AA8DA,IAAa,gBAAb,MAA2B;CAmBN;CACD;CAnBlB,yBAA0C,IAAIA,UAAAA,SAI5C;EACA,KAAK;EACL,aAAa,MAAM,QAAQ,EAAE,cAAc;GACzC,OAAO,EAAE,OAAO,KAAK,2BAA2B,OAAO,EAAE;EAC3D;CACF,CAAC;CAGD,wBAAyC,IAAIA,UAAAA,SAG3C,EAAE,KAAK,KAAK,CAAC;CAEf,YACE,SACA,SAAmC,IAAIC,2BAAAA,qBAAqB,GAC5D;EAFiB,KAAA,UAAA;EACD,KAAA,SAAA;CACf;;;;;;;;;;;;CAiBH,sBAA6B,aAA0B,aAAkC;EACvF,IAAI,YAAY,oBAAoBC,qBAAAA,8BAClC,OAAO;GACL,MAAM;GACN,uBAAO,IAAI,MAAM,iEAAiE;EACpF;EAGF,IAAI;GACF,OAAOC,wBAAAA,sBACLC,gBAAAA,oBACE,KAAK,SACL,YAAY,wBAAwBC,qBAAAA,4BAA4B,cAAA,GAChEC,qBAAAA,oBAAAA,CAAoB,WAAW,GAC/B,WACF,CACF;EACF,SAAS,GAAG;GACV,OAAO;IACL,MAAM;IACN,OAAO,IAAI,MAAM,uCAAuC,EAAE,QAAA,GAAOC,qBAAAA,YAAAA,CAAY,CAAC,EAAE,CAAC;GACnF;EACF;CACF;;;;;;;;;;;;;CAcA,4BAAmC,aAA0B,aAA8B;EACzF,IAAI,YAAY,oBAAoBL,qBAAAA,8BAClC,MAAM,IAAI,MAAM,uEAAuE;EAEzF,MAAM,UAAU,KAAK,oCAAoC,aAA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b,CACF;GACA,MAAM,IAAI,MAAM,gCAAgC,GAAG;EACrD;CACF;;;;;;;;;;;;;;;;CAqBA,mBACE,aACA,oBACiB;EACjB,IAAI,YAAY,oBAAoBJ,qBAAAA,8BAClC,OAAO,EAAE,OAAO,+DAA+D;EAGjF,IAAI;GAOF,OANeE,gBAAAA,oBACb,KAAK,SACL,YAAY,wBAAwBC,qBAAAA,4BAA4B,kBAAA,GAChEC,qBAAAA,oBAAAA,CAAoB,WAAW,GAC/B,kBAEU;EACd,SAAS,GAAG;GACV,KAAK,OAAO,MACV,IAAI,MAAM,uDAAuD,EAAE,OAAO,EAAE,CAAC,CAC/E;GACA,OAAO,EAAE,OAAO,wBAAwB,IAAI;EAC9C;CACF;AACF"}
@@ -1,4 +1,4 @@
1
- import { DerivedArgs } from "./args_derivation.js";
1
+ import { DerivedArgs, DerivedPrerunArgs } from "./args_derivation.js";
2
2
  import { BlockConfig, BlockStorage, PlRef, ResultOrError } from "@platforma-sdk/model";
3
3
  import { MiLogger } from "@milaboratories/ts-helpers";
4
4
  import { ColumnReference, StringifiedJson } from "@milaboratories/pl-model-common";
@@ -49,6 +49,15 @@ export declare class ProjectHelper {
49
49
  * @returns The derived prerunArgs, or undefined if derivation fails or found errors
50
50
  */
51
51
  derivePrerunArgsFromStorage(blockConfig: BlockConfig, storageJson: string): unknown;
52
+ /**
53
+ * {@link derivePrerunArgsFromStorage} with the reason when there are no prerun args to stage:
54
+ * the issues found in them, the error of a lambda that threw, or a `prerunArgs()` that returned
55
+ * nothing. Never throws; a failure of the derivation itself is `failed`.
56
+ *
57
+ * @param blockConfig The block configuration (provides the model code)
58
+ * @param storageJson Storage as JSON string
59
+ */
60
+ derivePrerunArgsDetailedFromStorage(blockConfig: BlockConfig, storageJson: string): DerivedPrerunArgs;
52
61
  /**
53
62
  * Derives this block's template-export params from storage JSON using the VM
54
63
  * callback (`__pl_initializationParams_derive`).
@@ -147,6 +156,21 @@ export declare class ProjectHelper {
147
156
  * @returns The initial storage as JSON string, or why the params yield none
148
157
  */
149
158
  getInitialStorageFromParamsInVM(blockConfig: BlockConfig, params: unknown, blockIds: ReadonlyMap<string, string>): ResultOrError<string>;
159
+ /**
160
+ * Puts params onto a block's live data with the block's own `applyParams`, through the VM
161
+ * callback `__pl_storage_applyParams`. Nothing is written: the storage comes back as JSON.
162
+ *
163
+ * The callback runs the kind's params check first, as
164
+ * {@link getInitialStorageFromParamsInVM} does, and refuses data that is not at the data
165
+ * model's current version. Params are live: their references name blocks of this project and
166
+ * are not relocated.
167
+ *
168
+ * @param blockConfig The block configuration (provides the model code)
169
+ * @param storageJson The block's current storage as JSON string
170
+ * @param params The new params, whole
171
+ * @returns The storage with the params applied as JSON string, or why there is none
172
+ */
173
+ applyParamsInVM(blockConfig: BlockConfig, storageJson: string, params: unknown): ResultOrError<string>;
150
174
  /**
151
175
  * Applies a state update using VM-based transformation.
152
176
  * This calls the model's `__pl_storage_applyUpdate` callback which:
@@ -1 +1 @@
1
- {"version":3,"file":"project_helper.d.ts","names":[],"sources":["../../src/model/project_helper.ts"],"mappings":";;;;;;;;;;;;;YAiCY;EACN;;EACA;EAAmB,gBAAgB,gBAAgB;EAAe;;qBAuB3D;mBAmBQ;WACD,QAAQ;mBAnBT;mBAYA;EAKjB,YACmB,SAAS,mBACV,SAAQ;;;;;;;;;;;;EAkBnB,sBAAsB,aAAa,aAAa,sBAAsB;;;;;;;;;;;;;EAqCtE,4BAA4B,aAAa,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;EAiDtD,gCACL,aAAa,aACb,sBACC;UAsDK;EAaD,qBACL,mBAAmB,aACnB,qBACA;IAAQ,SAAS;IAAkB,cAAc;MAChD;;;;;;;EAaI,oBACL,SAAS,kBACT,2CACsB;;;;;;;;;;;EAwBjB,sBAAsB,aAAa;;;;;;;;;;;;;;;;;;;;;;EA2CnC,2BACL,aAAa,aACb,kBACC;;;;;;;;;;;;;;;;;;;;;;;;;;;EAqDI,gCACL,aAAa,aACb,iBACA,UAAU,8BACT;;;;;;;;;;;;;;EA0EI,uBACL,aAAa,aACb,4BACA;IAAW;IAAmB;;;;;;;;;;;;;;;;;EAmDzB,mBACL,aAAa,aACb,yCACC"}
1
+ {"version":3,"file":"project_helper.d.ts","names":[],"sources":["../../src/model/project_helper.ts"],"mappings":";;;;;;;;;;;;;YAsCY;EACN;;EACA;EAAmB,gBAAgB,gBAAgB;EAAe;;qBAsB3D;mBAmBQ;WACD,QAAQ;mBAnBT;mBAYA;EAKjB,YACmB,SAAS,mBACV,SAAQ;;;;;;;;;;;;EAkBnB,sBAAsB,aAAa,aAAa,sBAAsB;;;;;;;;;;;;;EAqCtE,4BAA4B,aAAa,aAAa;;;;;;;;;EAiBtD,oCACL,aAAa,aACb,sBACC;;;;;;;;;;;;;;;;;;;;;;;;;;EAkDI,gCACL,aAAa,aACb,sBACC;UAsDK;EAaD,qBACL,mBAAmB,aACnB,qBACA;IAAQ,SAAS;IAAkB,cAAc;MAChD;;;;;;;EAaI,oBACL,SAAS,kBACT,2CACsB;;;;;;;;;;;EAwBjB,sBAAsB,aAAa;;;;;;;;;;;;;;;;;;;;;;EA2CnC,2BACL,aAAa,aACb,kBACC;;;;;;;;;;;;;;;;;;;;;;;;;;;EAqDI,gCACL,aAAa,aACb,iBACA,UAAU,8BACT;;;;;;;;;;;;;;;EA2EI,gBACL,aAAa,aACb,qBACA,kBACC;;;;;;;;;;;;;;EAmDI,uBACL,aAAa,aACb,4BACA;IAAW;IAAmB;;;;;;;;;;;;;;;;;EAmDzB,mBACL,aAAa,aACb,yCACC"}
@@ -1,10 +1,10 @@
1
- import { parseArgsDeriveResult } from "./args_derivation.js";
1
+ import { parseArgsDeriveResult, parsePrerunArgsDeriveResult } from "./args_derivation.js";
2
2
  import { getDebugFlags } from "../debug/index.js";
3
3
  import { executeSingleLambda } from "../js_render/index.js";
4
4
  import { BLOCK_STORAGE_FACADE_VERSION, BlockStorageFacadeCallbacks, ensureError, extractCodeWithInfo } from "@platforma-sdk/model";
5
5
  import { ConsoleLoggerAdapter } from "@milaboratories/ts-helpers";
6
- import { collectColumnReferences } from "@milaboratories/pl-model-common";
7
6
  import { LRUCache } from "lru-cache";
7
+ import { collectColumnReferences } from "@milaboratories/pl-model-common";
8
8
  // src/model/project_helper.ts
9
9
  var ProjectHelper = class {
10
10
  quickJs;
@@ -59,12 +59,29 @@ var ProjectHelper = class {
59
59
  */
60
60
  derivePrerunArgsFromStorage(blockConfig, storageJson) {
61
61
  if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) throw new Error("derivePrerunArgsFromStorage is only supported for model API version 2");
62
+ const derived = this.derivePrerunArgsDetailedFromStorage(blockConfig, storageJson);
63
+ return derived.type === "staged" ? derived.args : void 0;
64
+ }
65
+ /**
66
+ * {@link derivePrerunArgsFromStorage} with the reason when there are no prerun args to stage:
67
+ * the issues found in them, the error of a lambda that threw, or a `prerunArgs()` that returned
68
+ * nothing. Never throws; a failure of the derivation itself is `failed`.
69
+ *
70
+ * @param blockConfig The block configuration (provides the model code)
71
+ * @param storageJson Storage as JSON string
72
+ */
73
+ derivePrerunArgsDetailedFromStorage(blockConfig, storageJson) {
74
+ if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) return {
75
+ type: "failed",
76
+ error: "Prerun args derivation from storage is only supported for model API version 2"
77
+ };
62
78
  try {
63
- const result = executeSingleLambda(this.quickJs, blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.PrerunArgsDerive], extractCodeWithInfo(blockConfig), storageJson);
64
- if (result.error !== void 0) return;
65
- return result.value;
66
- } catch {
67
- return;
79
+ return parsePrerunArgsDeriveResult(executeSingleLambda(this.quickJs, blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.PrerunArgsDerive], extractCodeWithInfo(blockConfig), storageJson));
80
+ } catch (e) {
81
+ return {
82
+ type: "failed",
83
+ error: `Prerun args derivation from storage failed: ${ensureError(e).message}`
84
+ };
68
85
  }
69
86
  }
70
87
  /**
@@ -228,6 +245,33 @@ var ProjectHelper = class {
228
245
  }
229
246
  }
230
247
  /**
248
+ * Puts params onto a block's live data with the block's own `applyParams`, through the VM
249
+ * callback `__pl_storage_applyParams`. Nothing is written: the storage comes back as JSON.
250
+ *
251
+ * The callback runs the kind's params check first, as
252
+ * {@link getInitialStorageFromParamsInVM} does, and refuses data that is not at the data
253
+ * model's current version. Params are live: their references name blocks of this project and
254
+ * are not relocated.
255
+ *
256
+ * @param blockConfig The block configuration (provides the model code)
257
+ * @param storageJson The block's current storage as JSON string
258
+ * @param params The new params, whole
259
+ * @returns The storage with the params applied as JSON string, or why there is none
260
+ */
261
+ applyParamsInVM(blockConfig, storageJson, params) {
262
+ if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) return { error: /* @__PURE__ */ new Error("applyParamsInVM is only supported for model API version 2") };
263
+ const callback = blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageApplyParams];
264
+ if (callback === void 0) return { error: /* @__PURE__ */ new Error("This version of the block does not put params onto its data itself.") };
265
+ try {
266
+ const result = executeSingleLambda(this.quickJs, callback, extractCodeWithInfo(blockConfig), storageJson, JSON.stringify(params ?? {}));
267
+ if (result.error !== void 0) return { error: new Error(result.error) };
268
+ return { value: result.storageJson };
269
+ } catch (e) {
270
+ const cause = ensureError(e);
271
+ return { error: new Error(`Applying params to the block's data failed: ${cause.message}`, { cause }) };
272
+ }
273
+ }
274
+ /**
231
275
  * Applies a state update using VM-based transformation.
232
276
  * This calls the model's `__pl_storage_applyUpdate` callback which:
233
277
  * - Normalizes current storage
@@ -1 +1 @@
1
- {"version":3,"file":"project_helper.js","names":[],"sources":["../../src/model/project_helper.ts"],"sourcesContent":["import type { ResultOrError, BlockConfig, BlockStorage, PlRef } from \"@platforma-sdk/model\";\nimport type { ColumnReference, StringifiedJson } from \"@milaboratories/pl-model-common\";\nimport { collectColumnReferences } from \"@milaboratories/pl-model-common\";\nimport {\n extractCodeWithInfo,\n ensureError,\n BlockStorageFacadeCallbacks,\n BLOCK_STORAGE_FACADE_VERSION,\n} from \"@platforma-sdk/model\";\nimport { LRUCache } from \"lru-cache\";\nimport type { QuickJSWASMModule } from \"quickjs-emscripten\";\nimport { executeSingleLambda } from \"../js_render\";\nimport type { SignedResourceId } from \"@milaboratories/pl-client\";\nimport { ConsoleLoggerAdapter, type MiLogger } from \"@milaboratories/ts-helpers\";\nimport { getDebugFlags } from \"../debug\";\nimport { parseArgsDeriveResult, type DerivedArgs } from \"./args_derivation\";\n\ntype EnrichmentTargetsRequest = {\n blockConfig: () => BlockConfig;\n args: () => unknown;\n};\n\ntype EnrichmentTargetsValue = {\n value: PlRef[] | undefined;\n};\n\n/**\n * Result of VM-based storage migration.\n * Returned by migrateStorageInVM().\n *\n * - Error result: { error: string } - serious failure (no context, etc.)\n * - Success result: { newStorageJson: StringifiedJson<BlockStorage>, info: string } - migration succeeded\n */\nexport type MigrationResult =\n | { error: string }\n | { error?: undefined; newStorageJson: StringifiedJson<BlockStorage>; info: string };\n\n/**\n * Result of a derivation from storage that either produced a value or failed.\n * Returned by the __pl_prerunArgs_derive and __pl_initializationParams_derive VM callbacks; a\n * newer model adds the issues found in the prerun args, which are not read here.\n */\ntype DeriveResult = { error: string } | { error?: undefined; value: unknown };\n\n/**\n * Result of building initial storage from params.\n * Returned by the __pl_storage_initialFromParams VM callback.\n */\ntype ParamsStorageResult =\n | { error: string }\n | { error?: undefined; storageJson: StringifiedJson<BlockStorage> };\n\n/**\n * Result of checking params against their kind.\n * Returned by the __pl_initializationParams_validate VM callback.\n */\ntype InitializationParamsValidateResult = { error: string } | { error?: undefined };\n\nexport class ProjectHelper {\n private readonly enrichmentTargetsCache = new LRUCache<\n string,\n EnrichmentTargetsValue,\n EnrichmentTargetsRequest\n >({\n max: 256,\n memoMethod: (_key, _value, { context }) => {\n return { value: this.calculateEnrichmentTargets(context) };\n },\n });\n\n // An args resource never changes, so its id alone identifies the columns found in it.\n private readonly columnReferencesCache = new LRUCache<\n SignedResourceId,\n readonly ColumnReference[]\n >({ max: 1024 });\n\n constructor(\n private readonly quickJs: QuickJSWASMModule,\n public readonly logger: MiLogger = new ConsoleLoggerAdapter(),\n ) {}\n\n // =============================================================================\n // Args Derivation from Storage (V3+)\n // =============================================================================\n\n /**\n * Derives args directly from storage JSON using VM callback.\n * The VM extracts data from storage, calls the block's args() function and then its argsIssues().\n *\n * This allows the middle layer to work only with storage JSON,\n * without needing to know the underlying data structure.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson Storage as JSON string\n * @returns The derived args and whether the block may run with them, or why there are none\n */\n public deriveArgsFromStorage(blockConfig: BlockConfig, storageJson: string): DerivedArgs {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n type: \"absent\",\n error: new Error(\"deriveArgsFromStorage is only supported for model API version 2\"),\n };\n }\n\n try {\n return parseArgsDeriveResult(\n executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.ArgsDerive],\n extractCodeWithInfo(blockConfig),\n storageJson,\n ),\n );\n } catch (e) {\n return {\n type: \"absent\",\n error: new Error(\"Args derivation from storage failed\", { cause: ensureError(e) }),\n };\n }\n }\n\n /**\n * Derives prerunArgs directly from storage JSON using VM callback.\n * Falls back to args() if prerunArgs is not defined in the block model.\n *\n * Errors the block's `prerunArgsIssues()` finds in its prerun args, or for a block without its\n * own prerunArgs, the errors its `argsIssues()` finds in its args, come back as an `error` and\n * skip staging the same way.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson Storage as JSON string\n * @returns The derived prerunArgs, or undefined if derivation fails or found errors\n */\n public derivePrerunArgsFromStorage(blockConfig: BlockConfig, storageJson: string): unknown {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"derivePrerunArgsFromStorage is only supported for model API version 2\");\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.PrerunArgsDerive],\n extractCodeWithInfo(blockConfig),\n storageJson,\n ) as DeriveResult;\n\n if (result.error !== undefined) {\n // Return undefined if derivation fails (skip block in staging)\n return undefined;\n }\n return result.value;\n } catch {\n // Return undefined if derivation fails (skip block in staging)\n return undefined;\n }\n }\n\n /**\n * Derives this block's template-export params from storage JSON using the VM\n * callback (`__pl_initializationParams_derive`).\n *\n * The template-export counterpart of {@link deriveArgsFromStorage}: instead of\n * the args a workflow runs on, it returns the params that would recreate the\n * block — the inverse of the data model's `init`. Params come back exactly as the block\n * projected them, references included: nothing marks or rewrites them on the way out, so\n * nothing here has to know a kind's params shape or how a reference is spelled.\n *\n * A `{ value: undefined }` result means the block declares no `templateParams`, which only\n * a block built against an older SDK can do. It does not reach a document: the export walk\n * requires a mapping and reports anything else as that block's problem, so an entry always\n * carries params.\n *\n * Unlike {@link derivePrerunArgsFromStorage}, a failure here is surfaced rather\n * than swallowed — a prerun that cannot derive args just skips a block in\n * staging, whereas an export that silently drops a block produces a template\n * that does not describe the project.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson Storage as JSON string\n * @returns The derived params with identifiers wrapped, `undefined` if the block declares\n * no lambda, or an error if derivation failed\n */\n public deriveTemplateParamsFromStorage(\n blockConfig: BlockConfig,\n storageJson: string,\n ): ResultOrError<unknown> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\n \"deriveTemplateParamsFromStorage is only supported for model API version 2\",\n ),\n };\n }\n\n const callback =\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.InitializationParamsDerive];\n\n // A model built before this callback existed simply has no entry for it. That is\n // NOT the same as a block declaring no `templateParams`: the block may well have\n // params, we just have no way to ask for them. Reporting it as `undefined` params\n // would export the block stripped of its configuration and quietly rebuild a\n // differently-configured project, so it has to be an error.\n // The message names the one action available to whoever pressed Export. It\n // deliberately says nothing about SDKs or callbacks: the person reading it did\n // not build this block and cannot change how it was built.\n if (callback === undefined) {\n return {\n error: new Error(\n \"This version of the block cannot be written to a template. Update the block \" +\n \"to a newer version and export again.\",\n ),\n };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n callback,\n extractCodeWithInfo(blockConfig),\n storageJson,\n ) as DeriveResult;\n\n if (result.error !== undefined) {\n return { error: new Error(result.error) };\n }\n return { value: result.value };\n } catch (e) {\n const cause = ensureError(e);\n // The reason goes in the message, not only in `cause`: this error is rendered\n // into a per-block export problem and shown to whoever triggered the export,\n // and every layer between here and there carries only `message`.\n return {\n error: new Error(`Template params derivation from storage failed: ${cause.message}`, {\n cause,\n }),\n };\n }\n }\n\n private calculateEnrichmentTargets(req: EnrichmentTargetsRequest): PlRef[] | undefined {\n const blockConfig = req.blockConfig();\n if (blockConfig.enrichmentTargets === undefined) return undefined;\n const args = req.args();\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.enrichmentTargets,\n extractCodeWithInfo(blockConfig),\n args,\n ) as PlRef[];\n return result;\n }\n\n public getEnrichmentTargets(\n blockConfig: () => BlockConfig,\n args: () => unknown,\n key?: { argsRid: SignedResourceId; blockPackRid: SignedResourceId },\n ): PlRef[] | undefined {\n const req = { blockConfig, args };\n if (key === undefined) return this.calculateEnrichmentTargets(req);\n const cacheKey = `${key.argsRid}:${key.blockPackRid}`;\n return this.enrichmentTargetsCache.memo(cacheKey, { context: req }).value;\n }\n\n /**\n * Columns referenced by a block's args, with the values of them the args picked, read from the\n * args resource `argsRid`. `undefined` while the resource data is not loaded yet: `args`\n * returns `undefined` then, and nothing is remembered for such a read, so the references are\n * found once the data arrives.\n */\n public getColumnReferences(\n argsRid: SignedResourceId,\n args: () => unknown,\n ): undefined | readonly ColumnReference[] {\n const cached = this.columnReferencesCache.get(argsRid);\n if (cached !== undefined) return cached;\n const data = args();\n if (data === undefined) return undefined;\n const references = collectColumnReferences(data);\n this.columnReferencesCache.set(argsRid, references);\n return references;\n }\n\n // =============================================================================\n // VM-based Storage Operations\n // =============================================================================\n\n /**\n * Creates initial BlockStorage for a new block using VM-based transformation.\n * This calls the '__pl_storage_initial' callback registered by DataModel which:\n * - Gets initial data from DataModel.getDefaultData()\n * - Creates BlockStorage with correct version\n *\n * @param blockConfig The block configuration (provides the model code)\n * @returns Initial storage as JSON string\n * @throws Error if storage creation fails\n */\n public getInitialStorageInVM(blockConfig: BlockConfig): string {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"getInitialStorageInVM is only supported for model API version 2\");\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageInitial],\n extractCodeWithInfo(blockConfig),\n ) as string;\n return result;\n } catch (e) {\n this.logger.error(\n new Error(\"[ProjectHelper.getInitialStorageInVM] Initial storage creation failed\", {\n cause: e,\n }),\n );\n throw new Error(`Block initial storage creation failed: ${e}`);\n }\n }\n\n /**\n * Checks a template entry's params against the block's kind, creating nothing.\n *\n * The pre-flight half of {@link getInitialStorageFromParamsInVM}: run once per entry\n * before a template is applied, so params a kind rejects are reported against the\n * entry that carries them while there is still no project. Skipping it is safe —\n * initialization runs the same check — but then the report arrives after earlier\n * entries have already been created.\n *\n * Every kind declares a parser, so a pass here means the params were checked against\n * the contract — not merely that they were JSON.\n *\n * A block whose model predates the callback passes unchecked rather than failing.\n * Unlike initialization, this method creates nothing, so there is nothing to get wrong\n * by proceeding, and such a block is refused outright at the point it is applied.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param params The entry's params. Reference ids may be placeholders: what is being\n * checked is the shape of the params, not what they point at\n * @returns Nothing, or why the params were rejected\n */\n public validateTemplateParamsInVM(\n blockConfig: BlockConfig,\n params: unknown,\n ): ResultOrError<undefined> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\"validateTemplateParamsInVM is only supported for model API version 2\"),\n };\n }\n\n const callback =\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.InitializationParamsValidate];\n if (callback === undefined) return { value: undefined };\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n callback,\n extractCodeWithInfo(blockConfig),\n JSON.stringify(params ?? {}),\n ) as InitializationParamsValidateResult;\n\n if (result.error !== undefined) return { error: new Error(result.error) };\n return { value: undefined };\n } catch (e) {\n const cause = ensureError(e);\n return { error: new Error(`Params check failed to run: ${cause.message}`, { cause }) };\n }\n }\n\n /**\n * Creates initial BlockStorage for a block being created from template params.\n *\n * The inverse of {@link deriveTemplateParamsFromStorage}, and the reason a block\n * can be created by anything other than the UI: it hands the params to the\n * block's own init factory inside the model VM, so the resulting storage is\n * whatever that block considers a correctly-initialized state.\n *\n * **Pointing the entry's references at this project happens in the same call**, before the\n * factory sees them — inside the block's bundle, because recognizing a reference means\n * knowing the reference system and a template engine deliberately does not. Params reach\n * here exactly as the file held them.\n *\n * One call and not two: every VM call builds a fresh runtime and re-evaluates the whole\n * model bundle, so asking the block to relocate and then asking it to initialize would parse\n * it twice per entry, for an intermediate value nothing else reads.\n *\n * `blockIds` holds the entries created so far, so an id it does not name is left as it is —\n * a reference to an entry further down the file keeps pointing at nothing, and the applied\n * block reports itself as missing references rather than being wired to a block below it.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param params The entry's params, as the document held them\n * @param blockIds template-local entry id → the block id that entry was given\n * @returns The initial storage as JSON string, or why the params yield none\n */\n public getInitialStorageFromParamsInVM(\n blockConfig: BlockConfig,\n params: unknown,\n blockIds: ReadonlyMap<string, string>,\n ): ResultOrError<string> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\n \"getInitialStorageFromParamsInVM is only supported for model API version 2\",\n ),\n };\n }\n\n const callback =\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageInitialFromParams];\n\n // A model built before this callback existed has no entry for it. Falling back to the\n // params-less initializer is not an option: it would produce a default-configured block\n // that looks like a successful apply, so the block the user gets would silently differ\n // from the one the template describes. Nor could its params be used as written — they name\n // the blocks of the project the template came from, and only this callback knows which of\n // the values in there are references at all.\n //\n // The message offers the two actions available to whoever applied the file. The\n // second one is the reason this branch is reachable at all: kind resolution only\n // ever returns a block that declares a kind, and such a block is new enough to\n // support this — but an entry may pin an exact block version instead, bypassing\n // resolution, and that pin can name anything ever published.\n if (callback === undefined) {\n return {\n error: new Error(\n \"This version of the block cannot be created from a template. Use a newer \" +\n \"version of the block, or remove the pinned block version from the template \" +\n \"entry so a supported one is chosen automatically.\",\n ),\n };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n callback,\n extractCodeWithInfo(blockConfig),\n // Params cross the VM boundary as text, like storage does. `undefined` would\n // stringify to nothing at all, and an entry with no params must go through\n // the params-less initializer rather than reaching this method.\n JSON.stringify(params ?? {}),\n JSON.stringify(Object.fromEntries(blockIds)),\n ) as ParamsStorageResult;\n\n if (result.error !== undefined) return { error: new Error(result.error) };\n return { value: result.storageJson };\n } catch (e) {\n const cause = ensureError(e);\n // The reason goes in the message, not only in `cause`: this error becomes a\n // per-entry apply problem shown to whoever triggered the import, and every\n // layer in between carries only `message`.\n return {\n error: new Error(`Initial storage creation from params failed: ${cause.message}`, {\n cause,\n }),\n };\n }\n }\n\n /**\n * Applies a state update using VM-based transformation.\n * This calls the model's `__pl_storage_applyUpdate` callback which:\n * - Normalizes current storage\n * - Updates state while preserving other fields (version, plugins)\n * - Returns the updated storage as JSON string\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param currentStorageJson Current storage as JSON string (must be defined)\n * @param newState New state from developer\n * @returns Updated storage as JSON string\n * @throws Error if storage update fails\n */\n public applyStorageUpdateInVM(\n blockConfig: BlockConfig,\n currentStorageJson: string,\n payload: { operation: string; value: unknown },\n ): string {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"applyStorageUpdateInVM is only supported for model API version 2\");\n }\n\n if (getDebugFlags().logJsExecStat) {\n this.logger.info(\n `[ProjectHelper.applyStorageUpdateInVM] currentStorageJson=${currentStorageJson.length}B, payload=${JSON.stringify(payload).length}B, operation=${payload.operation}`,\n );\n }\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageApplyUpdate],\n extractCodeWithInfo(blockConfig),\n currentStorageJson,\n payload,\n ) as string;\n return result;\n } catch (e) {\n const payloadJson = JSON.stringify(payload);\n this.logger.error(\n new Error(\n `[ProjectHelper.applyStorageUpdateInVM] Storage update failed (currentStorageJson=${currentStorageJson.length}B, payload=${payloadJson.length}B, operation=${payload.operation})`,\n { cause: e },\n ),\n );\n throw new Error(`Block storage update failed: ${e}`);\n }\n }\n\n // =============================================================================\n // Block State Migrations\n // =============================================================================\n\n /**\n * Runs block state migrations via VM-based transformation.\n * This calls the model's `__pl_storage_migrate` callback which:\n * - Normalizes current storage to get state and version\n * - Applies DataModel upgrade to reach target version key\n * - Runs all necessary migrations sequentially\n * - Returns new storage with updated state and version\n *\n * The middle layer doesn't need to know about dataVersion or storage internals.\n * All migration logic is encapsulated in the model.\n *\n * @param blockConfig The NEW block configuration (provides the model code with migrations)\n * @param currentStorageJson Current storage as JSON string (or undefined)\n * @returns MigrationResult with new storage or skip/error info\n */\n public migrateStorageInVM(\n blockConfig: BlockConfig,\n currentStorageJson: string | undefined,\n ): MigrationResult {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return { error: \"migrateStorageInVM is only supported for model API version 2\" };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageMigrate],\n extractCodeWithInfo(blockConfig),\n currentStorageJson,\n ) as MigrationResult;\n return result;\n } catch (e) {\n this.logger.error(\n new Error(\"[ProjectHelper.migrateStorageInVM] Migration failed\", { cause: e }),\n );\n return { error: `VM execution failed: ${e}` };\n }\n }\n}\n"],"mappings":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xE,OAAO,EAAE,OAAO,OAAO,YAAY;EACrC,SAAS,GAAG;GACV,MAAM,QAAQ,YAAY,CAAC;GAI3B,OAAO,EACL,OAAO,IAAI,MAAM,gDAAgD,MAAM,WAAW,EAChF,MACF,CAAC,EACH;EACF;CACF;;;;;;;;;;;;;;CAeA,uBACE,aACA,oBACA,SACQ;EACR,IAAI,YAAY,oBAAoB,8BAClC,MAAM,IAAI,MAAM,kEAAkE;EAGpF,IAAI,cAAc,CAAC,CAAC,eAClB,KAAK,OAAO,KACV,6DAA6D,mBAAmB,OAAO,aAAa,KAAK,UAAU,OAAO,CAAC,CAAC,OAAO,eAAe,QAAQ,WAC5J;EAEF,IAAI;GAQF,OAPe,oBACb,KAAK,SACL,YAAY,wBAAwB,4BAA4B,qBAChE,oBAAoB,WAAW,GAC/B,oBACA,OAEU;EACd,SAAS,GAAG;GACV,MAAM,cAAc,KAAK,UAAU,OAAO;GAC1C,KAAK,OAAO,MACV,IAAI,MACF,oFAAoF,mBAAmB,OAAO,aAAa,YAAY,OAAO,eAAe,QAAQ,UAAU,IAC/K,EAAE,OAAO,EAAE,CACb,CACF;GACA,MAAM,IAAI,MAAM,gCAAgC,GAAG;EACrD;CACF;;;;;;;;;;;;;;;;CAqBA,mBACE,aACA,oBACiB;EACjB,IAAI,YAAY,oBAAoB,8BAClC,OAAO,EAAE,OAAO,+DAA+D;EAGjF,IAAI;GAOF,OANe,oBACb,KAAK,SACL,YAAY,wBAAwB,4BAA4B,iBAChE,oBAAoB,WAAW,GAC/B,kBAEU;EACd,SAAS,GAAG;GACV,KAAK,OAAO,MACV,IAAI,MAAM,uDAAuD,EAAE,OAAO,EAAE,CAAC,CAC/E;GACA,OAAO,EAAE,OAAO,wBAAwB,IAAI;EAC9C;CACF;AACF"}
1
+ {"version":3,"file":"project_helper.js","names":[],"sources":["../../src/model/project_helper.ts"],"sourcesContent":["import type { ResultOrError, BlockConfig, BlockStorage, PlRef } from \"@platforma-sdk/model\";\nimport type { ColumnReference, StringifiedJson } from \"@milaboratories/pl-model-common\";\nimport { collectColumnReferences } from \"@milaboratories/pl-model-common\";\nimport {\n extractCodeWithInfo,\n ensureError,\n BlockStorageFacadeCallbacks,\n BLOCK_STORAGE_FACADE_VERSION,\n} from \"@platforma-sdk/model\";\nimport { LRUCache } from \"lru-cache\";\nimport type { QuickJSWASMModule } from \"quickjs-emscripten\";\nimport { executeSingleLambda } from \"../js_render\";\nimport type { SignedResourceId } from \"@milaboratories/pl-client\";\nimport { ConsoleLoggerAdapter, type MiLogger } from \"@milaboratories/ts-helpers\";\nimport { getDebugFlags } from \"../debug\";\nimport {\n parseArgsDeriveResult,\n parsePrerunArgsDeriveResult,\n type DerivedArgs,\n type DerivedPrerunArgs,\n} from \"./args_derivation\";\n\ntype EnrichmentTargetsRequest = {\n blockConfig: () => BlockConfig;\n args: () => unknown;\n};\n\ntype EnrichmentTargetsValue = {\n value: PlRef[] | undefined;\n};\n\n/**\n * Result of VM-based storage migration.\n * Returned by migrateStorageInVM().\n *\n * - Error result: { error: string } - serious failure (no context, etc.)\n * - Success result: { newStorageJson: StringifiedJson<BlockStorage>, info: string } - migration succeeded\n */\nexport type MigrationResult =\n | { error: string }\n | { error?: undefined; newStorageJson: StringifiedJson<BlockStorage>; info: string };\n\n/**\n * Result of a derivation from storage that either produced a value or failed.\n * Returned by the __pl_initializationParams_derive VM callback.\n */\ntype DeriveResult = { error: string } | { error?: undefined; value: unknown };\n\n/**\n * Result of building storage from params.\n * Returned by the __pl_storage_initialFromParams and __pl_storage_applyParams VM callbacks.\n */\ntype ParamsStorageResult =\n | { error: string }\n | { error?: undefined; storageJson: StringifiedJson<BlockStorage> };\n\n/**\n * Result of checking params against their kind.\n * Returned by the __pl_initializationParams_validate VM callback.\n */\ntype InitializationParamsValidateResult = { error: string } | { error?: undefined };\n\nexport class ProjectHelper {\n private readonly enrichmentTargetsCache = new LRUCache<\n string,\n EnrichmentTargetsValue,\n EnrichmentTargetsRequest\n >({\n max: 256,\n memoMethod: (_key, _value, { context }) => {\n return { value: this.calculateEnrichmentTargets(context) };\n },\n });\n\n // An args resource never changes, so its id alone identifies the columns found in it.\n private readonly columnReferencesCache = new LRUCache<\n SignedResourceId,\n readonly ColumnReference[]\n >({ max: 1024 });\n\n constructor(\n private readonly quickJs: QuickJSWASMModule,\n public readonly logger: MiLogger = new ConsoleLoggerAdapter(),\n ) {}\n\n // =============================================================================\n // Args Derivation from Storage (V3+)\n // =============================================================================\n\n /**\n * Derives args directly from storage JSON using VM callback.\n * The VM extracts data from storage, calls the block's args() function and then its argsIssues().\n *\n * This allows the middle layer to work only with storage JSON,\n * without needing to know the underlying data structure.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson Storage as JSON string\n * @returns The derived args and whether the block may run with them, or why there are none\n */\n public deriveArgsFromStorage(blockConfig: BlockConfig, storageJson: string): DerivedArgs {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n type: \"absent\",\n error: new Error(\"deriveArgsFromStorage is only supported for model API version 2\"),\n };\n }\n\n try {\n return parseArgsDeriveResult(\n executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.ArgsDerive],\n extractCodeWithInfo(blockConfig),\n storageJson,\n ),\n );\n } catch (e) {\n return {\n type: \"absent\",\n error: new Error(\"Args derivation from storage failed\", { cause: ensureError(e) }),\n };\n }\n }\n\n /**\n * Derives prerunArgs directly from storage JSON using VM callback.\n * Falls back to args() if prerunArgs is not defined in the block model.\n *\n * Errors the block's `prerunArgsIssues()` finds in its prerun args, or for a block without its\n * own prerunArgs, the errors its `argsIssues()` finds in its args, come back as an `error` and\n * skip staging the same way.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson Storage as JSON string\n * @returns The derived prerunArgs, or undefined if derivation fails or found errors\n */\n public derivePrerunArgsFromStorage(blockConfig: BlockConfig, storageJson: string): unknown {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"derivePrerunArgsFromStorage is only supported for model API version 2\");\n }\n const derived = this.derivePrerunArgsDetailedFromStorage(blockConfig, storageJson);\n // Anything but staged args skips the block in staging.\n return derived.type === \"staged\" ? derived.args : undefined;\n }\n\n /**\n * {@link derivePrerunArgsFromStorage} with the reason when there are no prerun args to stage:\n * the issues found in them, the error of a lambda that threw, or a `prerunArgs()` that returned\n * nothing. Never throws; a failure of the derivation itself is `failed`.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson Storage as JSON string\n */\n public derivePrerunArgsDetailedFromStorage(\n blockConfig: BlockConfig,\n storageJson: string,\n ): DerivedPrerunArgs {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n type: \"failed\",\n error: \"Prerun args derivation from storage is only supported for model API version 2\",\n };\n }\n\n try {\n return parsePrerunArgsDeriveResult(\n executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.PrerunArgsDerive],\n extractCodeWithInfo(blockConfig),\n storageJson,\n ),\n );\n } catch (e) {\n return {\n type: \"failed\",\n error: `Prerun args derivation from storage failed: ${ensureError(e).message}`,\n };\n }\n }\n\n /**\n * Derives this block's template-export params from storage JSON using the VM\n * callback (`__pl_initializationParams_derive`).\n *\n * The template-export counterpart of {@link deriveArgsFromStorage}: instead of\n * the args a workflow runs on, it returns the params that would recreate the\n * block — the inverse of the data model's `init`. Params come back exactly as the block\n * projected them, references included: nothing marks or rewrites them on the way out, so\n * nothing here has to know a kind's params shape or how a reference is spelled.\n *\n * A `{ value: undefined }` result means the block declares no `templateParams`, which only\n * a block built against an older SDK can do. It does not reach a document: the export walk\n * requires a mapping and reports anything else as that block's problem, so an entry always\n * carries params.\n *\n * Unlike {@link derivePrerunArgsFromStorage}, a failure here is surfaced rather\n * than swallowed — a prerun that cannot derive args just skips a block in\n * staging, whereas an export that silently drops a block produces a template\n * that does not describe the project.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson Storage as JSON string\n * @returns The derived params with identifiers wrapped, `undefined` if the block declares\n * no lambda, or an error if derivation failed\n */\n public deriveTemplateParamsFromStorage(\n blockConfig: BlockConfig,\n storageJson: string,\n ): ResultOrError<unknown> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\n \"deriveTemplateParamsFromStorage is only supported for model API version 2\",\n ),\n };\n }\n\n const callback =\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.InitializationParamsDerive];\n\n // A model built before this callback existed simply has no entry for it. That is\n // NOT the same as a block declaring no `templateParams`: the block may well have\n // params, we just have no way to ask for them. Reporting it as `undefined` params\n // would export the block stripped of its configuration and quietly rebuild a\n // differently-configured project, so it has to be an error.\n // The message names the one action available to whoever pressed Export. It\n // deliberately says nothing about SDKs or callbacks: the person reading it did\n // not build this block and cannot change how it was built.\n if (callback === undefined) {\n return {\n error: new Error(\n \"This version of the block cannot be written to a template. Update the block \" +\n \"to a newer version and export again.\",\n ),\n };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n callback,\n extractCodeWithInfo(blockConfig),\n storageJson,\n ) as DeriveResult;\n\n if (result.error !== undefined) {\n return { error: new Error(result.error) };\n }\n return { value: result.value };\n } catch (e) {\n const cause = ensureError(e);\n // The reason goes in the message, not only in `cause`: this error is rendered\n // into a per-block export problem and shown to whoever triggered the export,\n // and every layer between here and there carries only `message`.\n return {\n error: new Error(`Template params derivation from storage failed: ${cause.message}`, {\n cause,\n }),\n };\n }\n }\n\n private calculateEnrichmentTargets(req: EnrichmentTargetsRequest): PlRef[] | undefined {\n const blockConfig = req.blockConfig();\n if (blockConfig.enrichmentTargets === undefined) return undefined;\n const args = req.args();\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.enrichmentTargets,\n extractCodeWithInfo(blockConfig),\n args,\n ) as PlRef[];\n return result;\n }\n\n public getEnrichmentTargets(\n blockConfig: () => BlockConfig,\n args: () => unknown,\n key?: { argsRid: SignedResourceId; blockPackRid: SignedResourceId },\n ): PlRef[] | undefined {\n const req = { blockConfig, args };\n if (key === undefined) return this.calculateEnrichmentTargets(req);\n const cacheKey = `${key.argsRid}:${key.blockPackRid}`;\n return this.enrichmentTargetsCache.memo(cacheKey, { context: req }).value;\n }\n\n /**\n * Columns referenced by a block's args, with the values of them the args picked, read from the\n * args resource `argsRid`. `undefined` while the resource data is not loaded yet: `args`\n * returns `undefined` then, and nothing is remembered for such a read, so the references are\n * found once the data arrives.\n */\n public getColumnReferences(\n argsRid: SignedResourceId,\n args: () => unknown,\n ): undefined | readonly ColumnReference[] {\n const cached = this.columnReferencesCache.get(argsRid);\n if (cached !== undefined) return cached;\n const data = args();\n if (data === undefined) return undefined;\n const references = collectColumnReferences(data);\n this.columnReferencesCache.set(argsRid, references);\n return references;\n }\n\n // =============================================================================\n // VM-based Storage Operations\n // =============================================================================\n\n /**\n * Creates initial BlockStorage for a new block using VM-based transformation.\n * This calls the '__pl_storage_initial' callback registered by DataModel which:\n * - Gets initial data from DataModel.getDefaultData()\n * - Creates BlockStorage with correct version\n *\n * @param blockConfig The block configuration (provides the model code)\n * @returns Initial storage as JSON string\n * @throws Error if storage creation fails\n */\n public getInitialStorageInVM(blockConfig: BlockConfig): string {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"getInitialStorageInVM is only supported for model API version 2\");\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageInitial],\n extractCodeWithInfo(blockConfig),\n ) as string;\n return result;\n } catch (e) {\n this.logger.error(\n new Error(\"[ProjectHelper.getInitialStorageInVM] Initial storage creation failed\", {\n cause: e,\n }),\n );\n throw new Error(`Block initial storage creation failed: ${e}`);\n }\n }\n\n /**\n * Checks a template entry's params against the block's kind, creating nothing.\n *\n * The pre-flight half of {@link getInitialStorageFromParamsInVM}: run once per entry\n * before a template is applied, so params a kind rejects are reported against the\n * entry that carries them while there is still no project. Skipping it is safe —\n * initialization runs the same check — but then the report arrives after earlier\n * entries have already been created.\n *\n * Every kind declares a parser, so a pass here means the params were checked against\n * the contract — not merely that they were JSON.\n *\n * A block whose model predates the callback passes unchecked rather than failing.\n * Unlike initialization, this method creates nothing, so there is nothing to get wrong\n * by proceeding, and such a block is refused outright at the point it is applied.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param params The entry's params. Reference ids may be placeholders: what is being\n * checked is the shape of the params, not what they point at\n * @returns Nothing, or why the params were rejected\n */\n public validateTemplateParamsInVM(\n blockConfig: BlockConfig,\n params: unknown,\n ): ResultOrError<undefined> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\"validateTemplateParamsInVM is only supported for model API version 2\"),\n };\n }\n\n const callback =\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.InitializationParamsValidate];\n if (callback === undefined) return { value: undefined };\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n callback,\n extractCodeWithInfo(blockConfig),\n JSON.stringify(params ?? {}),\n ) as InitializationParamsValidateResult;\n\n if (result.error !== undefined) return { error: new Error(result.error) };\n return { value: undefined };\n } catch (e) {\n const cause = ensureError(e);\n return { error: new Error(`Params check failed to run: ${cause.message}`, { cause }) };\n }\n }\n\n /**\n * Creates initial BlockStorage for a block being created from template params.\n *\n * The inverse of {@link deriveTemplateParamsFromStorage}, and the reason a block\n * can be created by anything other than the UI: it hands the params to the\n * block's own init factory inside the model VM, so the resulting storage is\n * whatever that block considers a correctly-initialized state.\n *\n * **Pointing the entry's references at this project happens in the same call**, before the\n * factory sees them — inside the block's bundle, because recognizing a reference means\n * knowing the reference system and a template engine deliberately does not. Params reach\n * here exactly as the file held them.\n *\n * One call and not two: every VM call builds a fresh runtime and re-evaluates the whole\n * model bundle, so asking the block to relocate and then asking it to initialize would parse\n * it twice per entry, for an intermediate value nothing else reads.\n *\n * `blockIds` holds the entries created so far, so an id it does not name is left as it is —\n * a reference to an entry further down the file keeps pointing at nothing, and the applied\n * block reports itself as missing references rather than being wired to a block below it.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param params The entry's params, as the document held them\n * @param blockIds template-local entry id → the block id that entry was given\n * @returns The initial storage as JSON string, or why the params yield none\n */\n public getInitialStorageFromParamsInVM(\n blockConfig: BlockConfig,\n params: unknown,\n blockIds: ReadonlyMap<string, string>,\n ): ResultOrError<string> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\n \"getInitialStorageFromParamsInVM is only supported for model API version 2\",\n ),\n };\n }\n\n const callback =\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageInitialFromParams];\n\n // A model built before this callback existed has no entry for it. Falling back to the\n // params-less initializer is not an option: it would produce a default-configured block\n // that looks like a successful apply, so the block the user gets would silently differ\n // from the one the template describes. Nor could its params be used as written — they name\n // the blocks of the project the template came from, and only this callback knows which of\n // the values in there are references at all.\n //\n // The message offers the two actions available to whoever applied the file. The\n // second one is the reason this branch is reachable at all: kind resolution only\n // ever returns a block that declares a kind, and such a block is new enough to\n // support this — but an entry may pin an exact block version instead, bypassing\n // resolution, and that pin can name anything ever published.\n if (callback === undefined) {\n return {\n error: new Error(\n \"This version of the block cannot be created from a template. Use a newer \" +\n \"version of the block, or remove the pinned block version from the template \" +\n \"entry so a supported one is chosen automatically.\",\n ),\n };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n callback,\n extractCodeWithInfo(blockConfig),\n // Params cross the VM boundary as text, like storage does. `undefined` would\n // stringify to nothing at all, and an entry with no params must go through\n // the params-less initializer rather than reaching this method.\n JSON.stringify(params ?? {}),\n JSON.stringify(Object.fromEntries(blockIds)),\n ) as ParamsStorageResult;\n\n if (result.error !== undefined) return { error: new Error(result.error) };\n return { value: result.storageJson };\n } catch (e) {\n const cause = ensureError(e);\n // The reason goes in the message, not only in `cause`: this error becomes a\n // per-entry apply problem shown to whoever triggered the import, and every\n // layer in between carries only `message`.\n return {\n error: new Error(`Initial storage creation from params failed: ${cause.message}`, {\n cause,\n }),\n };\n }\n }\n\n /**\n * Puts params onto a block's live data with the block's own `applyParams`, through the VM\n * callback `__pl_storage_applyParams`. Nothing is written: the storage comes back as JSON.\n *\n * The callback runs the kind's params check first, as\n * {@link getInitialStorageFromParamsInVM} does, and refuses data that is not at the data\n * model's current version. Params are live: their references name blocks of this project and\n * are not relocated.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson The block's current storage as JSON string\n * @param params The new params, whole\n * @returns The storage with the params applied as JSON string, or why there is none\n */\n public applyParamsInVM(\n blockConfig: BlockConfig,\n storageJson: string,\n params: unknown,\n ): ResultOrError<string> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\"applyParamsInVM is only supported for model API version 2\"),\n };\n }\n\n // Registered only by a block that declares `applyParams`; anything else builds data\n // from params with `init` instead, which is the caller's call to make.\n const callback =\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageApplyParams];\n if (callback === undefined) {\n return {\n error: new Error(\"This version of the block does not put params onto its data itself.\"),\n };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n callback,\n extractCodeWithInfo(blockConfig),\n storageJson,\n JSON.stringify(params ?? {}),\n ) as ParamsStorageResult;\n\n if (result.error !== undefined) return { error: new Error(result.error) };\n return { value: result.storageJson };\n } catch (e) {\n const cause = ensureError(e);\n return {\n error: new Error(`Applying params to the block's data failed: ${cause.message}`, {\n cause,\n }),\n };\n }\n }\n\n /**\n * Applies a state update using VM-based transformation.\n * This calls the model's `__pl_storage_applyUpdate` callback which:\n * - Normalizes current storage\n * - Updates state while preserving other fields (version, plugins)\n * - Returns the updated storage as JSON string\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param currentStorageJson Current storage as JSON string (must be defined)\n * @param newState New state from developer\n * @returns Updated storage as JSON string\n * @throws Error if storage update fails\n */\n public applyStorageUpdateInVM(\n blockConfig: BlockConfig,\n currentStorageJson: string,\n payload: { operation: string; value: unknown },\n ): string {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"applyStorageUpdateInVM is only supported for model API version 2\");\n }\n\n if (getDebugFlags().logJsExecStat) {\n this.logger.info(\n `[ProjectHelper.applyStorageUpdateInVM] currentStorageJson=${currentStorageJson.length}B, payload=${JSON.stringify(payload).length}B, operation=${payload.operation}`,\n );\n }\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageApplyUpdate],\n extractCodeWithInfo(blockConfig),\n currentStorageJson,\n payload,\n ) as string;\n return result;\n } catch (e) {\n const payloadJson = JSON.stringify(payload);\n this.logger.error(\n new Error(\n `[ProjectHelper.applyStorageUpdateInVM] Storage update failed (currentStorageJson=${currentStorageJson.length}B, payload=${payloadJson.length}B, operation=${payload.operation})`,\n { cause: e },\n ),\n );\n throw new Error(`Block storage update failed: ${e}`);\n }\n }\n\n // =============================================================================\n // Block State Migrations\n // =============================================================================\n\n /**\n * Runs block state migrations via VM-based transformation.\n * This calls the model's `__pl_storage_migrate` callback which:\n * - Normalizes current storage to get state and version\n * - Applies DataModel upgrade to reach target version key\n * - Runs all necessary migrations sequentially\n * - Returns new storage with updated state and version\n *\n * The middle layer doesn't need to know about dataVersion or storage internals.\n * All migration logic is encapsulated in the model.\n *\n * @param blockConfig The NEW block configuration (provides the model code with migrations)\n * @param currentStorageJson Current storage as JSON string (or undefined)\n * @returns MigrationResult with new storage or skip/error info\n */\n public migrateStorageInVM(\n blockConfig: BlockConfig,\n currentStorageJson: string | undefined,\n ): MigrationResult {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return { error: \"migrateStorageInVM is only supported for model API version 2\" };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageMigrate],\n extractCodeWithInfo(blockConfig),\n currentStorageJson,\n ) as MigrationResult;\n return result;\n } catch (e) {\n this.logger.error(\n new Error(\"[ProjectHelper.migrateStorageInVM] Migration failed\", { cause: e }),\n );\n return { error: `VM execution failed: ${e}` };\n }\n }\n}\n"],"mappings":";;;;;;;;AA8DA,IAAa,gBAAb,MAA2B;CAmBN;CACD;CAnBlB,yBAA0C,IAAI,SAI5C;EACA,KAAK;EACL,aAAa,MAAM,QAAQ,EAAE,cAAc;GACzC,OAAO,EAAE,OAAO,KAAK,2BAA2B,OAAO,EAAE;EAC3D;CACF,CAAC;CAGD,wBAAyC,IAAI,SAG3C,EAAE,KAAK,KAAK,CAAC;CAEf,YACE,SACA,SAAmC,IAAI,qBAAqB,GAC5D;EAFiB,KAAA,UAAA;EACD,KAAA,SAAA;CACf;;;;;;;;;;;;CAiBH,sBAA6B,aAA0B,aAAkC;EACvF,IAAI,YAAY,oBAAoB,8BAClC,OAAO;GACL,MAAM;GACN,uBAAO,IAAI,MAAM,iEAAiE;EACpF;EAGF,IAAI;GACF,OAAO,sBACL,oBACE,KAAK,SACL,YAAY,wBAAwB,4BAA4B,aAChE,oBAAoB,WAAW,GAC/B,WACF,CACF;EACF,SAAS,GAAG;GACV,OAAO;IACL,MAAM;IACN,OAAO,IAAI,MAAM,uCAAuC,EAAE,OAAO,YAAY,CAAC,EAAE,CAAC;GACnF;EACF;CACF;;;;;;;;;;;;;CAcA,4BAAmC,aAA0B,aAA8B;EACzF,IAAI,YAAY,oBAAoB,8BAClC,MAAM,IAAI,MAAM,uEAAuE;EAEzF,MAAM,UAAU,KAAK,oCAAoC,aAAa,WAAW;EAEjF,OAAO,QAAQ,SAAS,WAAW,QAAQ,OAAO,KAAA;CACpD;;;;;;;;;CAUA,oCACE,aACA,aACmB;EACnB,IAAI,YAAY,oBAAoB,8BAClC,OAAO;GACL,MAAM;GACN,OAAO;EACT;EAGF,IAA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;;;;;;;CAeA,uBACE,aACA,oBACA,SACQ;EACR,IAAI,YAAY,oBAAoB,8BAClC,MAAM,IAAI,MAAM,kEAAkE;EAGpF,IAAI,cAAc,CAAC,CAAC,eAClB,KAAK,OAAO,KACV,6DAA6D,mBAAmB,OAAO,aAAa,KAAK,UAAU,OAAO,CAAC,CAAC,OAAO,eAAe,QAAQ,WAC5J;EAEF,IAAI;GAQF,OAPe,oBACb,KAAK,SACL,YAAY,wBAAwB,4BAA4B,qBAChE,oBAAoB,WAAW,GAC/B,oBACA,OAEU;EACd,SAAS,GAAG;GACV,MAAM,cAAc,KAAK,UAAU,OAAO;GAC1C,KAAK,OAAO,MACV,IAAI,MACF,oFAAoF,mBAAmB,OAAO,aAAa,YAAY,OAAO,eAAe,QAAQ,UAAU,IAC/K,EAAE,OAAO,EAAE,CACb,CACF;GACA,MAAM,IAAI,MAAM,gCAAgC,GAAG;EACrD;CACF;;;;;;;;;;;;;;;;CAqBA,mBACE,aACA,oBACiB;EACjB,IAAI,YAAY,oBAAoB,8BAClC,OAAO,EAAE,OAAO,+DAA+D;EAGjF,IAAI;GAOF,OANe,oBACb,KAAK,SACL,YAAY,wBAAwB,4BAA4B,iBAChE,oBAAoB,WAAW,GAC/B,kBAEU;EACd,SAAS,GAAG;GACV,KAAK,OAAO,MACV,IAAI,MAAM,uDAAuD,EAAE,OAAO,EAAE,CAAC,CAC/E;GACA,OAAO,EAAE,OAAO,wBAAwB,IAAI;EAC9C;CACF;AACF"}
@@ -13,9 +13,9 @@ let _platforma_sdk_block_tools = require("@platforma-sdk/block-tools");
13
13
  let node_fs = require("node:fs");
14
14
  node_fs = require_runtime.__toESM(node_fs, 1);
15
15
  let _milaboratories_ts_helpers = require("@milaboratories/ts-helpers");
16
+ let lru_cache = require("lru-cache");
16
17
  let node_url = require("node:url");
17
18
  let _milaboratories_pl_client = require("@milaboratories/pl-client");
18
- let lru_cache = require("lru-cache");
19
19
  let node_crypto = require("node:crypto");
20
20
  let canonicalize = require("canonicalize");
21
21
  canonicalize = require_runtime.__toESM(canonicalize, 1);
@@ -11,9 +11,9 @@ import { request } from "undici";
11
11
  import { RegistryV1, loadPackDescription, loadPackDescriptionFromManifest } from "@platforma-sdk/block-tools";
12
12
  import fs from "node:fs";
13
13
  import { assertNever, notEmpty } from "@milaboratories/ts-helpers";
14
+ import { LRUCache } from "lru-cache";
14
15
  import { fileURLToPath } from "node:url";
15
16
  import { field } from "@milaboratories/pl-client";
16
- import { LRUCache } from "lru-cache";
17
17
  import { createHash } from "node:crypto";
18
18
  import canonicalize from "canonicalize";
19
19
  import { z } from "zod";
@@ -354,6 +354,10 @@ var ProjectMutator = class ProjectMutator {
354
354
  if (info === void 0) throw new Error(`No such block: ${blockId}`);
355
355
  return info;
356
356
  }
357
+ /** The model of the block's current pack, as this transaction sees it. */
358
+ getBlockConfig(blockId) {
359
+ return this.getBlockInfo(blockId).config;
360
+ }
357
361
  /** Create a plain JSON resource value from a JS object (no compression). */
358
362
  createJsonFieldValue(obj) {
359
363
  const value = Buffer.from(JSON.stringify(obj));