@milaboratories/pl-middle-layer 1.66.19 → 1.67.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/block_registry/index.cjs +3 -0
- package/dist/block_registry/index.d.ts +2 -1
- package/dist/block_registry/index.js +2 -1
- package/dist/block_registry/location_provider.cjs +117 -0
- package/dist/block_registry/location_provider.cjs.map +1 -0
- package/dist/block_registry/location_provider.js +114 -0
- package/dist/block_registry/location_provider.js.map +1 -0
- package/dist/block_registry/registry.cjs +13 -0
- package/dist/block_registry/registry.cjs.map +1 -1
- package/dist/block_registry/registry.d.ts +14 -1
- package/dist/block_registry/registry.d.ts.map +1 -1
- package/dist/block_registry/registry.js +13 -0
- package/dist/block_registry/registry.js.map +1 -1
- package/dist/block_registry/template_provider.cjs +104 -0
- package/dist/block_registry/template_provider.cjs.map +1 -0
- package/dist/block_registry/template_provider.d.ts +62 -0
- package/dist/block_registry/template_provider.d.ts.map +1 -0
- package/dist/block_registry/template_provider.js +103 -0
- package/dist/block_registry/template_provider.js.map +1 -0
- package/dist/block_registry/watcher.cjs +3 -3
- package/dist/block_registry/watcher.js +2 -2
- package/dist/dev_env/util.js +2 -2
- package/dist/dev_env/util.js.map +1 -1
- package/dist/index.cjs +10 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.js +5 -1
- package/dist/js_render/computable_context.cjs +1 -1
- package/dist/js_render/computable_context.js +1 -1
- package/dist/middle_layer/driver_kit.d.ts +1 -1
- package/dist/middle_layer/middle_layer.cjs +144 -2
- package/dist/middle_layer/middle_layer.cjs.map +1 -1
- package/dist/middle_layer/middle_layer.d.ts +67 -1
- package/dist/middle_layer/middle_layer.d.ts.map +1 -1
- package/dist/middle_layer/middle_layer.js +146 -4
- package/dist/middle_layer/middle_layer.js.map +1 -1
- package/dist/middle_layer/project.cjs +1 -0
- package/dist/middle_layer/project.cjs.map +1 -1
- package/dist/middle_layer/project.d.ts +2 -2
- package/dist/middle_layer/project.js +4 -4
- package/dist/middle_layer/project.js.map +1 -1
- package/dist/middle_layer/sharing_list.d.ts +1 -1
- package/dist/model/args.cjs +9 -28
- package/dist/model/args.cjs.map +1 -1
- package/dist/model/args.js +9 -28
- package/dist/model/args.js.map +1 -1
- package/dist/model/index.cjs +7 -0
- package/dist/model/index.d.ts +4 -1
- package/dist/model/index.js +4 -1
- package/dist/model/project_helper.cjs +111 -0
- package/dist/model/project_helper.cjs.map +1 -1
- package/dist/model/project_helper.d.ts +76 -1
- package/dist/model/project_helper.d.ts.map +1 -1
- package/dist/model/project_helper.js +111 -0
- package/dist/model/project_helper.js.map +1 -1
- package/dist/model/project_model.d.ts +1 -1
- package/dist/model/sharing_model.d.ts +1 -1
- package/dist/model/template_apply.cjs +67 -0
- package/dist/model/template_apply.cjs.map +1 -0
- package/dist/model/template_apply.d.ts +50 -0
- package/dist/model/template_apply.d.ts.map +1 -0
- package/dist/model/template_apply.js +64 -0
- package/dist/model/template_apply.js.map +1 -0
- package/dist/model/template_export.cjs +82 -0
- package/dist/model/template_export.cjs.map +1 -0
- package/dist/model/template_export.d.ts +9 -0
- package/dist/model/template_export.d.ts.map +1 -0
- package/dist/model/template_export.js +82 -0
- package/dist/model/template_export.js.map +1 -0
- package/dist/model/template_parser.cjs +74 -0
- package/dist/model/template_parser.cjs.map +1 -0
- package/dist/model/template_parser.d.ts +43 -0
- package/dist/model/template_parser.d.ts.map +1 -0
- package/dist/model/template_parser.js +72 -0
- package/dist/model/template_parser.js.map +1 -0
- package/dist/model/template_resolve.cjs +134 -0
- package/dist/model/template_resolve.cjs.map +1 -0
- package/dist/model/template_resolve.d.ts +193 -0
- package/dist/model/template_resolve.d.ts.map +1 -0
- package/dist/model/template_resolve.js +133 -0
- package/dist/model/template_resolve.js.map +1 -0
- package/dist/model/template_serializer.cjs +162 -0
- package/dist/model/template_serializer.cjs.map +1 -0
- package/dist/model/template_serializer.d.ts +17 -0
- package/dist/model/template_serializer.d.ts.map +1 -0
- package/dist/model/template_serializer.js +157 -0
- package/dist/model/template_serializer.js.map +1 -0
- package/dist/mutator/block-pack/block_pack.cjs +1 -1
- package/dist/mutator/block-pack/block_pack.js +1 -1
- package/dist/mutator/migration.cjs +1 -1
- package/dist/mutator/migration.js +1 -1
- package/dist/mutator/project.cjs +35 -5
- package/dist/mutator/project.cjs.map +1 -1
- package/dist/mutator/project.d.ts.map +1 -1
- package/dist/mutator/project.js +35 -5
- package/dist/mutator/project.js.map +1 -1
- package/dist/mutator/template_construct.cjs +77 -0
- package/dist/mutator/template_construct.cjs.map +1 -0
- package/dist/mutator/template_construct.js +77 -0
- package/dist/mutator/template_construct.js.map +1 -0
- package/dist/network_check/template.js +3 -3
- package/dist/network_check/template.js.map +1 -1
- package/package.json +18 -18
- package/src/block_registry/index.ts +1 -0
- package/src/block_registry/location_provider.test.ts +236 -0
- package/src/block_registry/location_provider.ts +124 -0
- package/src/block_registry/registry.ts +22 -0
- package/src/block_registry/template_provider.test.ts +275 -0
- package/src/block_registry/template_provider.ts +168 -0
- package/src/middle_layer/middle_layer.ts +192 -1
- package/src/middle_layer/project.ts +1 -1
- package/src/model/args.test.ts +26 -1
- package/src/model/args.ts +16 -31
- package/src/model/index.ts +21 -0
- package/src/model/project_helper.ts +238 -0
- package/src/model/project_helper_params_init.test.ts +249 -0
- package/src/model/template_apply.test.ts +65 -0
- package/src/model/template_apply.ts +128 -0
- package/src/model/template_export.test.ts +255 -0
- package/src/model/template_export.ts +136 -0
- package/src/model/template_parser.test.ts +264 -0
- package/src/model/template_parser.ts +108 -0
- package/src/model/template_resolve.test.ts +397 -0
- package/src/model/template_resolve.ts +346 -0
- package/src/model/template_serializer.test.ts +398 -0
- package/src/model/template_serializer.ts +232 -0
- package/src/model/template_serializer_fixtures.test.ts +274 -0
- package/src/mutator/project-v3.test.ts +11 -11
- package/src/mutator/project.ts +92 -5
- package/src/mutator/template_construct.test.ts +456 -0
- package/src/mutator/template_construct.ts +150 -0
|
@@ -56,6 +56,44 @@ var ProjectHelper = class {
|
|
|
56
56
|
return;
|
|
57
57
|
}
|
|
58
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* Derives this block's template-export params from storage JSON using the VM
|
|
61
|
+
* callback (`__pl_initializationParams_derive`).
|
|
62
|
+
*
|
|
63
|
+
* The template-export counterpart of {@link deriveArgsFromStorage}: instead of
|
|
64
|
+
* the args a workflow runs on, it returns the params that would recreate the
|
|
65
|
+
* block — the inverse of the data model's `init`. Params come back exactly as the block
|
|
66
|
+
* projected them, references included: nothing marks or rewrites them on the way out, so
|
|
67
|
+
* nothing here has to know a kind's params shape or how a reference is spelled.
|
|
68
|
+
*
|
|
69
|
+
* A `{ value: undefined }` result means the block declares no `templateParams`, which only
|
|
70
|
+
* a block built against an older SDK can do. It does not reach a document: the export walk
|
|
71
|
+
* requires a mapping and reports anything else as that block's problem, so an entry always
|
|
72
|
+
* carries params.
|
|
73
|
+
*
|
|
74
|
+
* Unlike {@link derivePrerunArgsFromStorage}, a failure here is surfaced rather
|
|
75
|
+
* than swallowed — a prerun that cannot derive args just skips a block in
|
|
76
|
+
* staging, whereas an export that silently drops a block produces a template
|
|
77
|
+
* that does not describe the project.
|
|
78
|
+
*
|
|
79
|
+
* @param blockConfig The block configuration (provides the model code)
|
|
80
|
+
* @param storageJson Storage as JSON string
|
|
81
|
+
* @returns The derived params with identifiers wrapped, `undefined` if the block declares
|
|
82
|
+
* no lambda, or an error if derivation failed
|
|
83
|
+
*/
|
|
84
|
+
deriveTemplateParamsFromStorage(blockConfig, storageJson) {
|
|
85
|
+
if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) return { error: /* @__PURE__ */ new Error("deriveTemplateParamsFromStorage is only supported for model API version 2") };
|
|
86
|
+
const callback = blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.InitializationParamsDerive];
|
|
87
|
+
if (callback === void 0) return { error: /* @__PURE__ */ new Error("This version of the block cannot be written to a template. Update the block to a newer version and export again.") };
|
|
88
|
+
try {
|
|
89
|
+
const result = executeSingleLambda(this.quickJs, callback, extractCodeWithInfo(blockConfig), storageJson);
|
|
90
|
+
if (result.error !== void 0) return { error: new Error(result.error) };
|
|
91
|
+
return { value: result.value };
|
|
92
|
+
} catch (e) {
|
|
93
|
+
const cause = ensureError(e);
|
|
94
|
+
return { error: new Error(`Template params derivation from storage failed: ${cause.message}`, { cause }) };
|
|
95
|
+
}
|
|
96
|
+
}
|
|
59
97
|
calculateEnrichmentTargets(req) {
|
|
60
98
|
const blockConfig = req.blockConfig();
|
|
61
99
|
if (blockConfig.enrichmentTargets === void 0) return void 0;
|
|
@@ -91,6 +129,79 @@ var ProjectHelper = class {
|
|
|
91
129
|
}
|
|
92
130
|
}
|
|
93
131
|
/**
|
|
132
|
+
* Checks a template entry's params against the block's kind, creating nothing.
|
|
133
|
+
*
|
|
134
|
+
* The pre-flight half of {@link getInitialStorageFromParamsInVM}: run once per entry
|
|
135
|
+
* before a template is applied, so params a kind rejects are reported against the
|
|
136
|
+
* entry that carries them while there is still no project. Skipping it is safe —
|
|
137
|
+
* initialization runs the same check — but then the report arrives after earlier
|
|
138
|
+
* entries have already been created.
|
|
139
|
+
*
|
|
140
|
+
* Every kind declares a parser, so a pass here means the params were checked against
|
|
141
|
+
* the contract — not merely that they were JSON.
|
|
142
|
+
*
|
|
143
|
+
* A block whose model predates the callback passes unchecked rather than failing.
|
|
144
|
+
* Unlike initialization, this method creates nothing, so there is nothing to get wrong
|
|
145
|
+
* by proceeding, and such a block is refused outright at the point it is applied.
|
|
146
|
+
*
|
|
147
|
+
* @param blockConfig The block configuration (provides the model code)
|
|
148
|
+
* @param params The entry's params. Reference ids may be placeholders: what is being
|
|
149
|
+
* checked is the shape of the params, not what they point at
|
|
150
|
+
* @returns Nothing, or why the params were rejected
|
|
151
|
+
*/
|
|
152
|
+
validateTemplateParamsInVM(blockConfig, params) {
|
|
153
|
+
if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) return { error: /* @__PURE__ */ new Error("validateTemplateParamsInVM is only supported for model API version 2") };
|
|
154
|
+
const callback = blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.InitializationParamsValidate];
|
|
155
|
+
if (callback === void 0) return { value: void 0 };
|
|
156
|
+
try {
|
|
157
|
+
const result = executeSingleLambda(this.quickJs, callback, extractCodeWithInfo(blockConfig), JSON.stringify(params ?? {}));
|
|
158
|
+
if (result.error !== void 0) return { error: new Error(result.error) };
|
|
159
|
+
return { value: void 0 };
|
|
160
|
+
} catch (e) {
|
|
161
|
+
const cause = ensureError(e);
|
|
162
|
+
return { error: new Error(`Params check failed to run: ${cause.message}`, { cause }) };
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Creates initial BlockStorage for a block being created from template params.
|
|
167
|
+
*
|
|
168
|
+
* The inverse of {@link deriveTemplateParamsFromStorage}, and the reason a block
|
|
169
|
+
* can be created by anything other than the UI: it hands the params to the
|
|
170
|
+
* block's own init factory inside the model VM, so the resulting storage is
|
|
171
|
+
* whatever that block considers a correctly-initialized state.
|
|
172
|
+
*
|
|
173
|
+
* **Pointing the entry's references at this project happens in the same call**, before the
|
|
174
|
+
* factory sees them — inside the block's bundle, because recognizing a reference means
|
|
175
|
+
* knowing the reference system and a template engine deliberately does not. Params reach
|
|
176
|
+
* here exactly as the file held them.
|
|
177
|
+
*
|
|
178
|
+
* One call and not two: every VM call builds a fresh runtime and re-evaluates the whole
|
|
179
|
+
* model bundle, so asking the block to relocate and then asking it to initialize would parse
|
|
180
|
+
* it twice per entry, for an intermediate value nothing else reads.
|
|
181
|
+
*
|
|
182
|
+
* `blockIds` holds the entries created so far, so an id it does not name is left as it is —
|
|
183
|
+
* a reference to an entry further down the file keeps pointing at nothing, and the applied
|
|
184
|
+
* block reports itself as missing references rather than being wired to a block below it.
|
|
185
|
+
*
|
|
186
|
+
* @param blockConfig The block configuration (provides the model code)
|
|
187
|
+
* @param params The entry's params, as the document held them
|
|
188
|
+
* @param blockIds template-local entry id → the block id that entry was given
|
|
189
|
+
* @returns The initial storage as JSON string, or why the params yield none
|
|
190
|
+
*/
|
|
191
|
+
getInitialStorageFromParamsInVM(blockConfig, params, blockIds) {
|
|
192
|
+
if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) return { error: /* @__PURE__ */ new Error("getInitialStorageFromParamsInVM is only supported for model API version 2") };
|
|
193
|
+
const callback = blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageInitialFromParams];
|
|
194
|
+
if (callback === void 0) return { error: /* @__PURE__ */ new Error("This version of the block cannot be created from a template. Use a newer version of the block, or remove the pinned block version from the template entry so a supported one is chosen automatically.") };
|
|
195
|
+
try {
|
|
196
|
+
const result = executeSingleLambda(this.quickJs, callback, extractCodeWithInfo(blockConfig), JSON.stringify(params ?? {}), JSON.stringify(Object.fromEntries(blockIds)));
|
|
197
|
+
if (result.error !== void 0) return { error: new Error(result.error) };
|
|
198
|
+
return { value: result.storageJson };
|
|
199
|
+
} catch (e) {
|
|
200
|
+
const cause = ensureError(e);
|
|
201
|
+
return { error: new Error(`Initial storage creation from params failed: ${cause.message}`, { cause }) };
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
94
205
|
* Applies a state update using VM-based transformation.
|
|
95
206
|
* This calls the model's `__pl_storage_applyUpdate` callback which:
|
|
96
207
|
* - 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 { StringifiedJson } 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 type { StorageDebugView } from \"@milaboratories/pl-model-middle-layer\";\nimport { getDebugFlags } from \"../debug\";\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 args derivation from storage.\n * Returned by __pl_args_derive and __pl_prerunArgs_derive VM callbacks.\n */\ntype ArgsDeriveResult = { error: string } | { error?: undefined; value: unknown };\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 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 and calls the block's args() function.\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 object, or error if derivation fails\n */\n public deriveArgsFromStorage(\n blockConfig: BlockConfig,\n storageJson: string,\n ): ResultOrError<unknown> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\"deriveArgsFromStorage is only supported for model API version 2\"),\n };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.ArgsDerive],\n extractCodeWithInfo(blockConfig),\n storageJson,\n ) as ArgsDeriveResult;\n\n if (result.error !== undefined) {\n return { error: new Error(result.error) };\n }\n return { value: result.value };\n } catch (e) {\n return { error: new Error(\"Args derivation from storage failed\", { cause: ensureError(e) }) };\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 * @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\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 ArgsDeriveResult;\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 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 // 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 * 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 * Gets storage debug view from raw storage data by calling the VM's __pl_storage_debugView callback.\n * Returns structured debug info about the storage (e.g., dataVersion).\n *\n * @param blockConfig Block configuration\n * @param rawStorageJson Raw storage as JSON string (or undefined)\n * @returns Storage debug view as JSON string (e.g., '{\"dataVersion\": \"v1\"}')\n */\n public getStorageDebugViewInVM(\n blockConfig: BlockConfig,\n rawStorageJson: string | undefined,\n ): StringifiedJson<StorageDebugView> | undefined {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"getStorageDebugViewInVM is only supported for model API version 2\");\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageDebugView],\n extractCodeWithInfo(blockConfig),\n rawStorageJson,\n ) as StringifiedJson<StorageDebugView>;\n return result;\n } catch (e) {\n this.logger.error(\n new Error(\"[ProjectHelper.getStorageDebugViewInVM] Get storage debug view failed\", {\n cause: e,\n }),\n );\n return undefined;\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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"}
|
|
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 { StringifiedJson } 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 type { StorageDebugView } from \"@milaboratories/pl-model-middle-layer\";\nimport { getDebugFlags } from \"../debug\";\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 args derivation from storage.\n * Returned by __pl_args_derive and __pl_prerunArgs_derive VM callbacks.\n */\ntype ArgsDeriveResult = { 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 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 and calls the block's args() function.\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 object, or error if derivation fails\n */\n public deriveArgsFromStorage(\n blockConfig: BlockConfig,\n storageJson: string,\n ): ResultOrError<unknown> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\"deriveArgsFromStorage is only supported for model API version 2\"),\n };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.ArgsDerive],\n extractCodeWithInfo(blockConfig),\n storageJson,\n ) as ArgsDeriveResult;\n\n if (result.error !== undefined) {\n return { error: new Error(result.error) };\n }\n return { value: result.value };\n } catch (e) {\n return { error: new Error(\"Args derivation from storage failed\", { cause: ensureError(e) }) };\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 * @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\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 ArgsDeriveResult;\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 ArgsDeriveResult;\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 // 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 * Gets storage debug view from raw storage data by calling the VM's __pl_storage_debugView callback.\n * Returns structured debug info about the storage (e.g., dataVersion).\n *\n * @param blockConfig Block configuration\n * @param rawStorageJson Raw storage as JSON string (or undefined)\n * @returns Storage debug view as JSON string (e.g., '{\"dataVersion\": \"v1\"}')\n */\n public getStorageDebugViewInVM(\n blockConfig: BlockConfig,\n rawStorageJson: string | undefined,\n ): StringifiedJson<StorageDebugView> | undefined {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"getStorageDebugViewInVM is only supported for model API version 2\");\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageDebugView],\n extractCodeWithInfo(blockConfig),\n rawStorageJson,\n ) as StringifiedJson<StorageDebugView>;\n return result;\n } catch (e) {\n this.logger.error(\n new Error(\"[ProjectHelper.getStorageDebugViewInVM] Get storage debug view failed\", {\n cause: e,\n }),\n );\n return undefined;\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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"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ProjectListEntry, ProjectMeta } from "@milaboratories/pl-model-middle-layer";
|
|
2
|
-
import { ResourceType } from "@milaboratories/pl-client";
|
|
3
2
|
import { ProjectId as ProjectId$1 } from "@milaboratories/pl-model-common";
|
|
3
|
+
import { ResourceType } from "@milaboratories/pl-client";
|
|
4
4
|
|
|
5
5
|
//#region src/model/project_model.d.ts
|
|
6
6
|
interface ProjectListEntry$1 extends Omit<ProjectListEntry, "id"> {
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
|
|
2
|
+
let _platforma_sdk_model = require("@platforma-sdk/model");
|
|
3
|
+
let _platforma_sdk_block_tools = require("@platforma-sdk/block-tools");
|
|
4
|
+
let _milaboratories_pl_model_common = require("@milaboratories/pl-model-common");
|
|
5
|
+
let semver = require("semver");
|
|
6
|
+
semver = require_runtime.__toESM(semver, 1);
|
|
7
|
+
//#region src/model/template_apply.ts
|
|
8
|
+
/**
|
|
9
|
+
* One entry the file describes in a way this project cannot honour.
|
|
10
|
+
*
|
|
11
|
+
* Thrown, not returned, and that is the whole failure policy: an apply either creates every
|
|
12
|
+
* entry or creates none. It travels out through the open transaction, which is therefore
|
|
13
|
+
* never committed, so a rejected file leaves the project exactly as it was. The caller turns
|
|
14
|
+
* it into a {@link TemplateApplyProblem}; anything else reaching that caller is an outage
|
|
15
|
+
* rather than a statement about the file, and keeps propagating.
|
|
16
|
+
*/
|
|
17
|
+
var TemplateEntryRejected = class extends Error {
|
|
18
|
+
entryId;
|
|
19
|
+
constructor(entryId, message) {
|
|
20
|
+
super(message);
|
|
21
|
+
this.entryId = entryId;
|
|
22
|
+
this.name = "TemplateEntryRejected";
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Why the block prepared for an entry cannot serve it, or `undefined` when it can.
|
|
27
|
+
*
|
|
28
|
+
* An entry's `kind` is the contract its params are written against, so the block that ends up
|
|
29
|
+
* installed has to implement it. Only one of the three routes to a block gives that for free:
|
|
30
|
+
* kind resolution, where the kind's own projection picks the block. The two overrides do not —
|
|
31
|
+
* a location's folder can change without the file changing, and a pinned version names a
|
|
32
|
+
* package with no reference to a kind at all.
|
|
33
|
+
*
|
|
34
|
+
* So this belongs here, with the apply's other per-entry checks, and not in resolution: it is
|
|
35
|
+
* asked once, of the block that was actually prepared, whichever route found it. Resolution
|
|
36
|
+
* could answer it for a location — `byLocation` reads the block's config anyway — and doing so
|
|
37
|
+
* there would have been a second place stating the same invariant, with the pinned-version
|
|
38
|
+
* route still uncovered. One caller is the point.
|
|
39
|
+
*
|
|
40
|
+
* It is also the check that makes the params check meaningful, so it is asked first: params are
|
|
41
|
+
* checked by the INSTALLED block's kind parser, which against a block of the wrong kind would
|
|
42
|
+
* hold params written for one contract against another.
|
|
43
|
+
*
|
|
44
|
+
* Version comparison goes through the same selector-to-range translation the registry resolver
|
|
45
|
+
* uses, so "this resolves locally" and "this would resolve once published" cannot disagree
|
|
46
|
+
* about the version math.
|
|
47
|
+
*
|
|
48
|
+
* Messages name no route, so a caller adds whichever locator the entry carried.
|
|
49
|
+
*/
|
|
50
|
+
function kindMismatch(asked, declared) {
|
|
51
|
+
if (declared === void 0) return "The block resolved for this entry declares no kind, so it cannot be the implementation it asks for";
|
|
52
|
+
let wanted;
|
|
53
|
+
let has;
|
|
54
|
+
try {
|
|
55
|
+
wanted = (0, _milaboratories_pl_model_common.parseKindSelectorReference)(asked);
|
|
56
|
+
has = (0, _milaboratories_pl_model_common.parseKindRef)(declared);
|
|
57
|
+
} catch (e) {
|
|
58
|
+
return `The block resolved for this entry declares an unreadable kind: ${(0, _platforma_sdk_model.ensureError)(e).message}`;
|
|
59
|
+
}
|
|
60
|
+
if (wanted.name !== has.name) return `This entry asks for kind '${wanted.name}', but the block resolved for it implements '${has.name}'`;
|
|
61
|
+
if (!semver.satisfies(has.version, (0, _platforma_sdk_block_tools.selectorToRange)(wanted.selector))) return `This entry asks for '${asked}', but the block resolved for it implements version ${has.version} of that kind`;
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
exports.TemplateEntryRejected = TemplateEntryRejected;
|
|
65
|
+
exports.kindMismatch = kindMismatch;
|
|
66
|
+
|
|
67
|
+
//# sourceMappingURL=template_apply.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"template_apply.cjs","names":[],"sources":["../../src/model/template_apply.ts"],"sourcesContent":["import type {\n BlockKindReference,\n BlockKindSelectorReference,\n} from \"@milaboratories/pl-model-common\";\nimport { parseKindRef, parseKindSelectorReference } from \"@milaboratories/pl-model-common\";\nimport { selectorToRange } from \"@platforma-sdk/block-tools\";\nimport { ensureError } from \"@platforma-sdk/model\";\nimport * as semver from \"semver\";\n\n/**\n * One entry the file describes in a way this project cannot honour.\n *\n * Thrown, not returned, and that is the whole failure policy: an apply either creates every\n * entry or creates none. It travels out through the open transaction, which is therefore\n * never committed, so a rejected file leaves the project exactly as it was. The caller turns\n * it into a {@link TemplateApplyProblem}; anything else reaching that caller is an outage\n * rather than a statement about the file, and keeps propagating.\n */\nexport class TemplateEntryRejected extends Error {\n constructor(\n readonly entryId: string,\n message: string,\n ) {\n super(message);\n this.name = \"TemplateEntryRejected\";\n }\n}\n\n/**\n * Something that stopped one entry from being applied.\n *\n * Every stage of an apply reports in this shape — resolution, validation,\n * construction — so a caller assembles one list and the reader sees which entry in\n * their file each problem belongs to. `error` is a finished sentence for the person\n * who applied the file, not a code.\n */\nexport type TemplateApplyProblem = {\n /** The template-local id of the entry the problem belongs to. */\n readonly entryId: string;\n readonly error: string;\n};\n\n/** One entry that made it into the project. */\nexport type AppliedEntry = {\n /** The entry's id in the file. */\n readonly templateLocalId: string;\n /** The project-local id the block was given. */\n readonly blockId: string;\n};\n\n/**\n * What a whole apply — reading, checking, resolving, placing — left behind.\n *\n * One shape for every stage's findings, because the reader does not care which stage\n * objected. `problems` empty means the project holds exactly what the document described;\n * otherwise `added` is empty, because no stage creates anything until every entry has passed.\n *\n * A stage that checks reports every problem it found, so a file with three mistakes takes one\n * pass to fix. Placement stops at the first one — hence at most one problem from there.\n */\nexport type TemplateApplyReport = {\n readonly added: readonly AppliedEntry[];\n readonly problems: readonly TemplateApplyProblem[];\n};\n\n/**\n * Why the block prepared for an entry cannot serve it, or `undefined` when it can.\n *\n * An entry's `kind` is the contract its params are written against, so the block that ends up\n * installed has to implement it. Only one of the three routes to a block gives that for free:\n * kind resolution, where the kind's own projection picks the block. The two overrides do not —\n * a location's folder can change without the file changing, and a pinned version names a\n * package with no reference to a kind at all.\n *\n * So this belongs here, with the apply's other per-entry checks, and not in resolution: it is\n * asked once, of the block that was actually prepared, whichever route found it. Resolution\n * could answer it for a location — `byLocation` reads the block's config anyway — and doing so\n * there would have been a second place stating the same invariant, with the pinned-version\n * route still uncovered. One caller is the point.\n *\n * It is also the check that makes the params check meaningful, so it is asked first: params are\n * checked by the INSTALLED block's kind parser, which against a block of the wrong kind would\n * hold params written for one contract against another.\n *\n * Version comparison goes through the same selector-to-range translation the registry resolver\n * uses, so \"this resolves locally\" and \"this would resolve once published\" cannot disagree\n * about the version math.\n *\n * Messages name no route, so a caller adds whichever locator the entry carried.\n */\nexport function kindMismatch(\n asked: BlockKindSelectorReference,\n declared: BlockKindReference | undefined,\n): string | undefined {\n if (declared === undefined) {\n return (\n \"The block resolved for this entry declares no kind, so it cannot be the \" +\n \"implementation it asks for\"\n );\n }\n\n let wanted: { name: string; selector: { op: \"exact\" | \"patch\" | \"minor\"; version: string } };\n let has: { name: string; version: string };\n try {\n wanted = parseKindSelectorReference(asked);\n has = parseKindRef(declared);\n } catch (e) {\n // The entry's own selector was checked when the document was parsed, so this is the\n // block's stored reference being unreadable.\n return `The block resolved for this entry declares an unreadable kind: ${ensureError(e).message}`;\n }\n\n if (wanted.name !== has.name) {\n return (\n `This entry asks for kind '${wanted.name}', but the block resolved for it ` +\n `implements '${has.name}'`\n );\n }\n\n if (!semver.satisfies(has.version, selectorToRange(wanted.selector))) {\n return (\n `This entry asks for '${asked}', but the block resolved for it implements ` +\n `version ${has.version} of that kind`\n );\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,IAAa,wBAAb,cAA2C,MAAM;CAEpC;CADX,YACE,SACA,SACA;EACA,MAAM,OAAO;EAHJ,KAAA,UAAA;EAIT,KAAK,OAAO;CACd;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,SAAgB,aACd,OACA,UACoB;CACpB,IAAI,aAAa,KAAA,GACf,OACE;CAKJ,IAAI;CACJ,IAAI;CACJ,IAAI;EACF,UAAA,GAAA,gCAAA,2BAAA,CAAoC,KAAK;EACzC,OAAA,GAAA,gCAAA,aAAA,CAAmB,QAAQ;CAC7B,SAAS,GAAG;EAGV,OAAO,mEAAA,GAAA,qBAAA,YAAA,CAA8E,CAAC,CAAC,CAAC;CAC1F;CAEA,IAAI,OAAO,SAAS,IAAI,MACtB,OACE,6BAA6B,OAAO,KAAK,+CAC1B,IAAI,KAAK;CAI5B,IAAI,CAAC,OAAO,UAAU,IAAI,UAAA,GAAA,2BAAA,gBAAA,CAAyB,OAAO,QAAQ,CAAC,GACjE,OACE,wBAAwB,MAAM,sDACnB,IAAI,QAAQ;AAK7B"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { BlockKindReference, BlockKindSelectorReference } from "@milaboratories/pl-model-common";
|
|
2
|
+
|
|
3
|
+
//#region src/model/template_apply.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* One entry the file describes in a way this project cannot honour.
|
|
6
|
+
*
|
|
7
|
+
* Thrown, not returned, and that is the whole failure policy: an apply either creates every
|
|
8
|
+
* entry or creates none. It travels out through the open transaction, which is therefore
|
|
9
|
+
* never committed, so a rejected file leaves the project exactly as it was. The caller turns
|
|
10
|
+
* it into a {@link TemplateApplyProblem}; anything else reaching that caller is an outage
|
|
11
|
+
* rather than a statement about the file, and keeps propagating.
|
|
12
|
+
*/
|
|
13
|
+
declare class TemplateEntryRejected extends Error {
|
|
14
|
+
readonly entryId: string;
|
|
15
|
+
constructor(entryId: string, message: string);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Something that stopped one entry from being applied.
|
|
19
|
+
*
|
|
20
|
+
* Every stage of an apply reports in this shape — resolution, validation,
|
|
21
|
+
* construction — so a caller assembles one list and the reader sees which entry in
|
|
22
|
+
* their file each problem belongs to. `error` is a finished sentence for the person
|
|
23
|
+
* who applied the file, not a code.
|
|
24
|
+
*/
|
|
25
|
+
type TemplateApplyProblem = {
|
|
26
|
+
/** The template-local id of the entry the problem belongs to. */readonly entryId: string;
|
|
27
|
+
readonly error: string;
|
|
28
|
+
};
|
|
29
|
+
/** One entry that made it into the project. */
|
|
30
|
+
type AppliedEntry = {
|
|
31
|
+
/** The entry's id in the file. */readonly templateLocalId: string; /** The project-local id the block was given. */
|
|
32
|
+
readonly blockId: string;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* What a whole apply — reading, checking, resolving, placing — left behind.
|
|
36
|
+
*
|
|
37
|
+
* One shape for every stage's findings, because the reader does not care which stage
|
|
38
|
+
* objected. `problems` empty means the project holds exactly what the document described;
|
|
39
|
+
* otherwise `added` is empty, because no stage creates anything until every entry has passed.
|
|
40
|
+
*
|
|
41
|
+
* A stage that checks reports every problem it found, so a file with three mistakes takes one
|
|
42
|
+
* pass to fix. Placement stops at the first one — hence at most one problem from there.
|
|
43
|
+
*/
|
|
44
|
+
type TemplateApplyReport = {
|
|
45
|
+
readonly added: readonly AppliedEntry[];
|
|
46
|
+
readonly problems: readonly TemplateApplyProblem[];
|
|
47
|
+
};
|
|
48
|
+
//#endregion
|
|
49
|
+
export { AppliedEntry, TemplateApplyProblem, TemplateApplyReport, TemplateEntryRejected };
|
|
50
|
+
//# sourceMappingURL=template_apply.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"template_apply.d.ts","names":[],"sources":["../../src/model/template_apply.ts"],"mappings":";;;;;AAkBA;;;;;;;cAAa,qBAAA,SAA8B,KAAK;EAAA,SAEnC,OAAA;cAAA,OAAA,UACT,OAAA;AAAA;AAeJ;;;;AAGgB;AAIhB;;;AAPA,KAAY,oBAAA;EAWM,0EATP,OAAA;EAAA,SACA,KAAK;AAAA;;KAIJ,YAAA;EAkBe,2CAhBhB,eAAA,UAiBmB;EAAA,SAfnB,OAAO;AAAA;;;;;;;;;;;KAaN,mBAAA;EAAA,SACD,KAAA,WAAgB,YAAA;EAAA,SAChB,QAAA,WAAmB,oBAAoB;AAAA"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { ensureError } from "@platforma-sdk/model";
|
|
2
|
+
import { selectorToRange } from "@platforma-sdk/block-tools";
|
|
3
|
+
import { parseKindRef, parseKindSelectorReference } from "@milaboratories/pl-model-common";
|
|
4
|
+
import * as semver from "semver";
|
|
5
|
+
//#region src/model/template_apply.ts
|
|
6
|
+
/**
|
|
7
|
+
* One entry the file describes in a way this project cannot honour.
|
|
8
|
+
*
|
|
9
|
+
* Thrown, not returned, and that is the whole failure policy: an apply either creates every
|
|
10
|
+
* entry or creates none. It travels out through the open transaction, which is therefore
|
|
11
|
+
* never committed, so a rejected file leaves the project exactly as it was. The caller turns
|
|
12
|
+
* it into a {@link TemplateApplyProblem}; anything else reaching that caller is an outage
|
|
13
|
+
* rather than a statement about the file, and keeps propagating.
|
|
14
|
+
*/
|
|
15
|
+
var TemplateEntryRejected = class extends Error {
|
|
16
|
+
entryId;
|
|
17
|
+
constructor(entryId, message) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.entryId = entryId;
|
|
20
|
+
this.name = "TemplateEntryRejected";
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Why the block prepared for an entry cannot serve it, or `undefined` when it can.
|
|
25
|
+
*
|
|
26
|
+
* An entry's `kind` is the contract its params are written against, so the block that ends up
|
|
27
|
+
* installed has to implement it. Only one of the three routes to a block gives that for free:
|
|
28
|
+
* kind resolution, where the kind's own projection picks the block. The two overrides do not —
|
|
29
|
+
* a location's folder can change without the file changing, and a pinned version names a
|
|
30
|
+
* package with no reference to a kind at all.
|
|
31
|
+
*
|
|
32
|
+
* So this belongs here, with the apply's other per-entry checks, and not in resolution: it is
|
|
33
|
+
* asked once, of the block that was actually prepared, whichever route found it. Resolution
|
|
34
|
+
* could answer it for a location — `byLocation` reads the block's config anyway — and doing so
|
|
35
|
+
* there would have been a second place stating the same invariant, with the pinned-version
|
|
36
|
+
* route still uncovered. One caller is the point.
|
|
37
|
+
*
|
|
38
|
+
* It is also the check that makes the params check meaningful, so it is asked first: params are
|
|
39
|
+
* checked by the INSTALLED block's kind parser, which against a block of the wrong kind would
|
|
40
|
+
* hold params written for one contract against another.
|
|
41
|
+
*
|
|
42
|
+
* Version comparison goes through the same selector-to-range translation the registry resolver
|
|
43
|
+
* uses, so "this resolves locally" and "this would resolve once published" cannot disagree
|
|
44
|
+
* about the version math.
|
|
45
|
+
*
|
|
46
|
+
* Messages name no route, so a caller adds whichever locator the entry carried.
|
|
47
|
+
*/
|
|
48
|
+
function kindMismatch(asked, declared) {
|
|
49
|
+
if (declared === void 0) return "The block resolved for this entry declares no kind, so it cannot be the implementation it asks for";
|
|
50
|
+
let wanted;
|
|
51
|
+
let has;
|
|
52
|
+
try {
|
|
53
|
+
wanted = parseKindSelectorReference(asked);
|
|
54
|
+
has = parseKindRef(declared);
|
|
55
|
+
} catch (e) {
|
|
56
|
+
return `The block resolved for this entry declares an unreadable kind: ${ensureError(e).message}`;
|
|
57
|
+
}
|
|
58
|
+
if (wanted.name !== has.name) return `This entry asks for kind '${wanted.name}', but the block resolved for it implements '${has.name}'`;
|
|
59
|
+
if (!semver.satisfies(has.version, selectorToRange(wanted.selector))) return `This entry asks for '${asked}', but the block resolved for it implements version ${has.version} of that kind`;
|
|
60
|
+
}
|
|
61
|
+
//#endregion
|
|
62
|
+
export { TemplateEntryRejected, kindMismatch };
|
|
63
|
+
|
|
64
|
+
//# sourceMappingURL=template_apply.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"template_apply.js","names":[],"sources":["../../src/model/template_apply.ts"],"sourcesContent":["import type {\n BlockKindReference,\n BlockKindSelectorReference,\n} from \"@milaboratories/pl-model-common\";\nimport { parseKindRef, parseKindSelectorReference } from \"@milaboratories/pl-model-common\";\nimport { selectorToRange } from \"@platforma-sdk/block-tools\";\nimport { ensureError } from \"@platforma-sdk/model\";\nimport * as semver from \"semver\";\n\n/**\n * One entry the file describes in a way this project cannot honour.\n *\n * Thrown, not returned, and that is the whole failure policy: an apply either creates every\n * entry or creates none. It travels out through the open transaction, which is therefore\n * never committed, so a rejected file leaves the project exactly as it was. The caller turns\n * it into a {@link TemplateApplyProblem}; anything else reaching that caller is an outage\n * rather than a statement about the file, and keeps propagating.\n */\nexport class TemplateEntryRejected extends Error {\n constructor(\n readonly entryId: string,\n message: string,\n ) {\n super(message);\n this.name = \"TemplateEntryRejected\";\n }\n}\n\n/**\n * Something that stopped one entry from being applied.\n *\n * Every stage of an apply reports in this shape — resolution, validation,\n * construction — so a caller assembles one list and the reader sees which entry in\n * their file each problem belongs to. `error` is a finished sentence for the person\n * who applied the file, not a code.\n */\nexport type TemplateApplyProblem = {\n /** The template-local id of the entry the problem belongs to. */\n readonly entryId: string;\n readonly error: string;\n};\n\n/** One entry that made it into the project. */\nexport type AppliedEntry = {\n /** The entry's id in the file. */\n readonly templateLocalId: string;\n /** The project-local id the block was given. */\n readonly blockId: string;\n};\n\n/**\n * What a whole apply — reading, checking, resolving, placing — left behind.\n *\n * One shape for every stage's findings, because the reader does not care which stage\n * objected. `problems` empty means the project holds exactly what the document described;\n * otherwise `added` is empty, because no stage creates anything until every entry has passed.\n *\n * A stage that checks reports every problem it found, so a file with three mistakes takes one\n * pass to fix. Placement stops at the first one — hence at most one problem from there.\n */\nexport type TemplateApplyReport = {\n readonly added: readonly AppliedEntry[];\n readonly problems: readonly TemplateApplyProblem[];\n};\n\n/**\n * Why the block prepared for an entry cannot serve it, or `undefined` when it can.\n *\n * An entry's `kind` is the contract its params are written against, so the block that ends up\n * installed has to implement it. Only one of the three routes to a block gives that for free:\n * kind resolution, where the kind's own projection picks the block. The two overrides do not —\n * a location's folder can change without the file changing, and a pinned version names a\n * package with no reference to a kind at all.\n *\n * So this belongs here, with the apply's other per-entry checks, and not in resolution: it is\n * asked once, of the block that was actually prepared, whichever route found it. Resolution\n * could answer it for a location — `byLocation` reads the block's config anyway — and doing so\n * there would have been a second place stating the same invariant, with the pinned-version\n * route still uncovered. One caller is the point.\n *\n * It is also the check that makes the params check meaningful, so it is asked first: params are\n * checked by the INSTALLED block's kind parser, which against a block of the wrong kind would\n * hold params written for one contract against another.\n *\n * Version comparison goes through the same selector-to-range translation the registry resolver\n * uses, so \"this resolves locally\" and \"this would resolve once published\" cannot disagree\n * about the version math.\n *\n * Messages name no route, so a caller adds whichever locator the entry carried.\n */\nexport function kindMismatch(\n asked: BlockKindSelectorReference,\n declared: BlockKindReference | undefined,\n): string | undefined {\n if (declared === undefined) {\n return (\n \"The block resolved for this entry declares no kind, so it cannot be the \" +\n \"implementation it asks for\"\n );\n }\n\n let wanted: { name: string; selector: { op: \"exact\" | \"patch\" | \"minor\"; version: string } };\n let has: { name: string; version: string };\n try {\n wanted = parseKindSelectorReference(asked);\n has = parseKindRef(declared);\n } catch (e) {\n // The entry's own selector was checked when the document was parsed, so this is the\n // block's stored reference being unreadable.\n return `The block resolved for this entry declares an unreadable kind: ${ensureError(e).message}`;\n }\n\n if (wanted.name !== has.name) {\n return (\n `This entry asks for kind '${wanted.name}', but the block resolved for it ` +\n `implements '${has.name}'`\n );\n }\n\n if (!semver.satisfies(has.version, selectorToRange(wanted.selector))) {\n return (\n `This entry asks for '${asked}', but the block resolved for it implements ` +\n `version ${has.version} of that kind`\n );\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;AAkBA,IAAa,wBAAb,cAA2C,MAAM;CAEpC;CADX,YACE,SACA,SACA;EACA,MAAM,OAAO;EAHJ,KAAA,UAAA;EAIT,KAAK,OAAO;CACd;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,SAAgB,aACd,OACA,UACoB;CACpB,IAAI,aAAa,KAAA,GACf,OACE;CAKJ,IAAI;CACJ,IAAI;CACJ,IAAI;EACF,SAAS,2BAA2B,KAAK;EACzC,MAAM,aAAa,QAAQ;CAC7B,SAAS,GAAG;EAGV,OAAO,kEAAkE,YAAY,CAAC,CAAC,CAAC;CAC1F;CAEA,IAAI,OAAO,SAAS,IAAI,MACtB,OACE,6BAA6B,OAAO,KAAK,+CAC1B,IAAI,KAAK;CAI5B,IAAI,CAAC,OAAO,UAAU,IAAI,SAAS,gBAAgB,OAAO,QAAQ,CAAC,GACjE,OACE,wBAAwB,MAAM,sDACnB,IAAI,QAAQ;AAK7B"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
const require_project_model_util = require("./project_model_util.cjs");
|
|
2
|
+
//#region src/model/template_export.ts
|
|
3
|
+
/**
|
|
4
|
+
* Walk a project's blocks in dependency order, collecting each one's
|
|
5
|
+
* template-descriptor output.
|
|
6
|
+
*
|
|
7
|
+
* **No topological sort is performed, because none is needed.** The project
|
|
8
|
+
* structure is already stored in topological order, and that is enforced rather
|
|
9
|
+
* than assumed: `productionGraph` traverses `allBlocks(structure)` and passes the
|
|
10
|
+
* set of blocks seen *so far* as the allowed set to `inferAllReferencedBlocks`, so
|
|
11
|
+
* a reference to a block that is not already above is recorded as a missing
|
|
12
|
+
* reference instead of an upstream. A block can therefore only legally reference
|
|
13
|
+
* blocks earlier in this sequence — which is exactly what a template file needs,
|
|
14
|
+
* since its block order is the instantiation order and the engine creates blocks
|
|
15
|
+
* upstream-first. Emitting entries in structure order satisfies that for free.
|
|
16
|
+
*
|
|
17
|
+
* Groups are flattened in order, so cross-group ordering is the structure's too.
|
|
18
|
+
*
|
|
19
|
+
* A structure that violates the ordering rule is reported as-is, not repaired:
|
|
20
|
+
* reordering would change which references are legal in the first place.
|
|
21
|
+
*
|
|
22
|
+
* Params are written exactly as the block projected them. The walk parses nothing, rewrites
|
|
23
|
+
* nothing and inspects nothing inside them, and neither does anything else between here and the
|
|
24
|
+
* file — which values carry block ids is knowledge of the reference system, and a template
|
|
25
|
+
* engine holds none of it. The block that receives these params on the way back in is what
|
|
26
|
+
* recognizes them; a block that projects the wrong fields produces a template that does not
|
|
27
|
+
* work, the same way one whose `templateParams` returns the wrong shape does.
|
|
28
|
+
*
|
|
29
|
+
* @param structure The project structure — the source of both membership and order
|
|
30
|
+
* @param paramsProvider Yields a block's derived template params. Return
|
|
31
|
+
* `undefined` for a block whose state cannot be read at all; such a block is
|
|
32
|
+
* recorded as a problem rather than skipped, because a template that quietly
|
|
33
|
+
* omits a block does not describe the project it was exported from, and the
|
|
34
|
+
* surviving entries may still reference the omitted one.
|
|
35
|
+
*/
|
|
36
|
+
function walkProjectForTemplateExport(structure, paramsProvider) {
|
|
37
|
+
const entries = [];
|
|
38
|
+
const problems = [];
|
|
39
|
+
for (const { id } of require_project_model_util.allBlocks(structure)) {
|
|
40
|
+
const derived = paramsProvider(id);
|
|
41
|
+
if (derived === void 0) {
|
|
42
|
+
problems.push({
|
|
43
|
+
blockId: id,
|
|
44
|
+
error: "Block state is unavailable, so its template params could not be derived"
|
|
45
|
+
});
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (derived.error !== void 0) {
|
|
49
|
+
problems.push({
|
|
50
|
+
blockId: id,
|
|
51
|
+
error: derived.error
|
|
52
|
+
});
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
const params = derived.value;
|
|
56
|
+
if (typeof params !== "object" || params === null || Array.isArray(params)) {
|
|
57
|
+
problems.push({
|
|
58
|
+
blockId: id,
|
|
59
|
+
error: `templateParams() must return an object, got ${typeName(params)}`
|
|
60
|
+
});
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
entries.push({
|
|
64
|
+
blockId: id,
|
|
65
|
+
params
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
entries,
|
|
70
|
+
problems
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/** Name the offending value's type for an error message, without printing the value. */
|
|
74
|
+
function typeName(value) {
|
|
75
|
+
if (value === null) return "null";
|
|
76
|
+
if (Array.isArray(value)) return "an array";
|
|
77
|
+
return `a ${typeof value}`;
|
|
78
|
+
}
|
|
79
|
+
//#endregion
|
|
80
|
+
exports.walkProjectForTemplateExport = walkProjectForTemplateExport;
|
|
81
|
+
|
|
82
|
+
//# sourceMappingURL=template_export.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"template_export.cjs","names":["allBlocks"],"sources":["../../src/model/template_export.ts"],"sourcesContent":["import type { ProjectStructure } from \"./project_model\";\nimport { allBlocks } from \"./project_model_util\";\n\n/**\n * One block's template-descriptor output as the walk receives it.\n *\n * Deliberately the same shape the `__pl_initializationParams_derive` facade callback\n * returns, so a provider can hand the VM's result straight through without\n * reshaping it.\n */\nexport type TemplateParamsResult =\n | { readonly error: string }\n | { readonly error?: undefined; readonly value: unknown };\n\n/** One block's contribution to the template being exported. */\nexport type TemplateExportEntry = {\n /**\n * The block's project-local id, which is also its template-local id: a template\n * has no id namespace of its own, so the id is reused verbatim and references\n * already stored in params need no translation.\n */\n readonly blockId: string;\n /**\n * The block's params exactly as it projected them.\n *\n * Always a mapping: a block that declared no `templateParams`, or whose lambda returned\n * something else, is reported as a problem rather than carried here — see the object check\n * in the walk. So nothing downstream has an absent case to decide.\n */\n readonly params: Record<string, unknown>;\n};\n\n/** Why one block could not be exported. */\nexport type TemplateExportProblem = {\n readonly blockId: string;\n readonly error: string;\n};\n\n/**\n * Outcome of the walk: the blocks that can be written, and the ones that cannot.\n *\n * Both lists are returned rather than throwing on the first failure, so the\n * caller can report every offending block at once instead of making the user fix\n * them one export at a time. Whether a non-empty `problems` aborts the export is\n * the caller's policy, not the walk's — but note that emitting `entries` while\n * ignoring `problems` can produce a file whose surviving entries reference a\n * dropped block, which is an unusable template.\n */\nexport type TemplateExportWalk = {\n readonly entries: readonly TemplateExportEntry[];\n readonly problems: readonly TemplateExportProblem[];\n};\n\n/**\n * Walk a project's blocks in dependency order, collecting each one's\n * template-descriptor output.\n *\n * **No topological sort is performed, because none is needed.** The project\n * structure is already stored in topological order, and that is enforced rather\n * than assumed: `productionGraph` traverses `allBlocks(structure)` and passes the\n * set of blocks seen *so far* as the allowed set to `inferAllReferencedBlocks`, so\n * a reference to a block that is not already above is recorded as a missing\n * reference instead of an upstream. A block can therefore only legally reference\n * blocks earlier in this sequence — which is exactly what a template file needs,\n * since its block order is the instantiation order and the engine creates blocks\n * upstream-first. Emitting entries in structure order satisfies that for free.\n *\n * Groups are flattened in order, so cross-group ordering is the structure's too.\n *\n * A structure that violates the ordering rule is reported as-is, not repaired:\n * reordering would change which references are legal in the first place.\n *\n * Params are written exactly as the block projected them. The walk parses nothing, rewrites\n * nothing and inspects nothing inside them, and neither does anything else between here and the\n * file — which values carry block ids is knowledge of the reference system, and a template\n * engine holds none of it. The block that receives these params on the way back in is what\n * recognizes them; a block that projects the wrong fields produces a template that does not\n * work, the same way one whose `templateParams` returns the wrong shape does.\n *\n * @param structure The project structure — the source of both membership and order\n * @param paramsProvider Yields a block's derived template params. Return\n * `undefined` for a block whose state cannot be read at all; such a block is\n * recorded as a problem rather than skipped, because a template that quietly\n * omits a block does not describe the project it was exported from, and the\n * surviving entries may still reference the omitted one.\n */\nexport function walkProjectForTemplateExport(\n structure: ProjectStructure,\n paramsProvider: (blockId: string) => TemplateParamsResult | undefined,\n): TemplateExportWalk {\n const entries: TemplateExportEntry[] = [];\n const problems: TemplateExportProblem[] = [];\n\n for (const { id } of allBlocks(structure)) {\n const derived = paramsProvider(id);\n\n if (derived === undefined) {\n problems.push({\n blockId: id,\n error: \"Block state is unavailable, so its template params could not be derived\",\n });\n continue;\n }\n\n if (derived.error !== undefined) {\n problems.push({ blockId: id, error: derived.error });\n continue;\n }\n\n const params = derived.value;\n\n // An entry's `params` must be a mapping. The lambda's declared return type is the\n // block kind's params type, and the kind's parser checks values coming IN, but\n // nothing checks what the lambda hands back on the way out — so a block whose\n // params type is a primitive or a tuple compiles fine and would produce an\n // unwritable entry. This is the only place that can catch it.\n if (typeof params !== \"object\" || params === null || Array.isArray(params)) {\n problems.push({\n blockId: id,\n error: `templateParams() must return an object, got ${typeName(params)}`,\n });\n continue;\n }\n\n entries.push({ blockId: id, params: params as Record<string, unknown> });\n }\n\n return { entries, problems };\n}\n\n/** Name the offending value's type for an error message, without printing the value. */\nfunction typeName(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"an array\";\n return `a ${typeof value}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsFA,SAAgB,6BACd,WACA,gBACoB;CACpB,MAAM,UAAiC,CAAC;CACxC,MAAM,WAAoC,CAAC;CAE3C,KAAK,MAAM,EAAE,QAAQA,2BAAAA,UAAU,SAAS,GAAG;EACzC,MAAM,UAAU,eAAe,EAAE;EAEjC,IAAI,YAAY,KAAA,GAAW;GACzB,SAAS,KAAK;IACZ,SAAS;IACT,OAAO;GACT,CAAC;GACD;EACF;EAEA,IAAI,QAAQ,UAAU,KAAA,GAAW;GAC/B,SAAS,KAAK;IAAE,SAAS;IAAI,OAAO,QAAQ;GAAM,CAAC;GACnD;EACF;EAEA,MAAM,SAAS,QAAQ;EAOvB,IAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,MAAM,QAAQ,MAAM,GAAG;GAC1E,SAAS,KAAK;IACZ,SAAS;IACT,OAAO,+CAA+C,SAAS,MAAM;GACvE,CAAC;GACD;EACF;EAEA,QAAQ,KAAK;GAAE,SAAS;GAAY;EAAkC,CAAC;CACzE;CAEA,OAAO;EAAE;EAAS;CAAS;AAC7B;;AAGA,SAAS,SAAS,OAAwB;CACxC,IAAI,UAAU,MAAM,OAAO;CAC3B,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO;CACjC,OAAO,KAAK,OAAO;AACrB"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
//#region src/model/template_export.d.ts
|
|
2
|
+
/** Why one block could not be exported. */
|
|
3
|
+
type TemplateExportProblem = {
|
|
4
|
+
readonly blockId: string;
|
|
5
|
+
readonly error: string;
|
|
6
|
+
};
|
|
7
|
+
//#endregion
|
|
8
|
+
export { TemplateExportProblem };
|
|
9
|
+
//# sourceMappingURL=template_export.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"template_export.d.ts","names":[],"sources":["../../src/model/template_export.ts"],"mappings":";;KAiCY,qBAAA;EAAA,SACD,OAAA;EAAA,SACA,KAAK;AAAA"}
|