@platforma-sdk/model 1.96.4 → 1.97.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_model.cjs +93 -6
- package/dist/block_model.cjs.map +1 -1
- package/dist/block_model.d.ts +64 -2
- package/dist/block_model.d.ts.map +1 -1
- package/dist/block_model.js +95 -8
- package/dist/block_model.js.map +1 -1
- package/dist/block_storage_callbacks.cjs +46 -0
- package/dist/block_storage_callbacks.cjs.map +1 -1
- package/dist/block_storage_callbacks.js +46 -1
- package/dist/block_storage_callbacks.js.map +1 -1
- package/dist/block_storage_facade.cjs +25 -5
- package/dist/block_storage_facade.cjs.map +1 -1
- package/dist/block_storage_facade.d.ts +39 -2
- package/dist/block_storage_facade.d.ts.map +1 -1
- package/dist/block_storage_facade.js +25 -6
- package/dist/block_storage_facade.js.map +1 -1
- package/dist/filters/converters/filterToQuery.cjs.map +1 -1
- package/dist/filters/converters/filterToQuery.d.ts +6 -2
- package/dist/filters/converters/filterToQuery.d.ts.map +1 -1
- package/dist/filters/converters/filterToQuery.js.map +1 -1
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/package.cjs +1 -1
- package/dist/package.js +1 -1
- package/package.json +2 -2
- package/src/apply_params.test.ts +330 -0
- package/src/block_model.ts +120 -4
- package/src/block_storage_callbacks.ts +74 -0
- package/src/block_storage_facade.ts +51 -4
- package/src/filters/converters/filterToQuery.ts +6 -3
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
|
2
|
+
import type { BlockConfigContainer, PlRef } from "@milaboratories/pl-model-common";
|
|
3
|
+
import { createPlRef, isPlRef, stringifyJson } from "@milaboratories/pl-model-common";
|
|
4
|
+
import { assertParamsObject, defineBlockKind } from "@platforma-sdk/block-kind";
|
|
5
|
+
import type { PluginName } from "./block_storage";
|
|
6
|
+
import { createBlockStorage } from "./block_storage";
|
|
7
|
+
import type { PluginHandle } from "./plugin_handle";
|
|
8
|
+
import { applyParamsToStorage } from "./block_storage_callbacks";
|
|
9
|
+
import { BlockStorageFacadeCallbacks } from "./block_storage_facade";
|
|
10
|
+
import { DataModelBuilder } from "./block_migrations";
|
|
11
|
+
import { BlockModelV3 } from "./block_model";
|
|
12
|
+
import { extractConfig } from "./bconfig/normalization";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* `BlockModelV3.applyParams(data, params)`: the block puts its kind's params onto live data
|
|
16
|
+
* itself (D-045), declared next to `templateParams`, its inverse.
|
|
17
|
+
*
|
|
18
|
+
* The block here holds a list of samples matched by `id`. Each sample also carries what the
|
|
19
|
+
* params do not describe — a file and view state — and the data holds view state of its own;
|
|
20
|
+
* `applyParams` keeps all of it, as the JSDoc example does.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
type SampleParams = { id: string; label: string; threshold?: number };
|
|
24
|
+
type Params = { samples?: SampleParams[]; sources?: PlRef[] };
|
|
25
|
+
|
|
26
|
+
function isSampleParams(value: unknown): value is SampleParams {
|
|
27
|
+
if (typeof value !== "object" || value === null) return false;
|
|
28
|
+
const { id, label, threshold } = value as Record<string, unknown>;
|
|
29
|
+
return (
|
|
30
|
+
typeof id === "string" &&
|
|
31
|
+
typeof label === "string" &&
|
|
32
|
+
(threshold === undefined || typeof threshold === "number")
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The kind's check: samples with a string id and label, references in their stored form. */
|
|
37
|
+
function parseInitializationParams(value: unknown): Params {
|
|
38
|
+
assertParamsObject(value);
|
|
39
|
+
const { samples, sources } = value;
|
|
40
|
+
if (samples !== undefined && !(Array.isArray(samples) && samples.every(isSampleParams)))
|
|
41
|
+
throw new Error("'samples' must be samples with an id and a label");
|
|
42
|
+
if (sources !== undefined && !(Array.isArray(sources) && sources.every(isPlRef)))
|
|
43
|
+
throw new Error("'sources' must be references");
|
|
44
|
+
return {
|
|
45
|
+
samples: samples?.map(({ id, label, threshold }) => ({ id, label, threshold })),
|
|
46
|
+
sources,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const kind = defineBlockKind<Params>({
|
|
51
|
+
name: "@platforma-open/milaboratories.apply-params-demo.kind",
|
|
52
|
+
version: "1.0.0",
|
|
53
|
+
parseInitializationParams,
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
type Sample = {
|
|
57
|
+
id: string;
|
|
58
|
+
label: string;
|
|
59
|
+
threshold: number;
|
|
60
|
+
/** An uploaded file: does not travel in params. */
|
|
61
|
+
file?: string;
|
|
62
|
+
/** View state: not in params. */
|
|
63
|
+
expanded: boolean;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
type BlockData = {
|
|
67
|
+
samples: Sample[];
|
|
68
|
+
sources: PlRef[];
|
|
69
|
+
view: { sort: string };
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const DEFAULT_THRESHOLD = 1;
|
|
73
|
+
|
|
74
|
+
const defaults = (): BlockData => ({ samples: [], sources: [], view: { sort: "asc" } });
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Whole params: the sample list is the params', each sample keeps its own file and view state,
|
|
78
|
+
* an absent key is the kind's "unset" and is written as the default.
|
|
79
|
+
*/
|
|
80
|
+
const applyParams = (data: BlockData, params: Params): BlockData => {
|
|
81
|
+
const current = new Map(data.samples.map((s) => [s.id, s]));
|
|
82
|
+
return {
|
|
83
|
+
...data,
|
|
84
|
+
samples: (params.samples ?? []).map((p): Sample => {
|
|
85
|
+
const kept = current.get(p.id);
|
|
86
|
+
return {
|
|
87
|
+
id: p.id,
|
|
88
|
+
label: p.label,
|
|
89
|
+
threshold: p.threshold ?? DEFAULT_THRESHOLD,
|
|
90
|
+
...(kept?.file !== undefined ? { file: kept.file } : {}),
|
|
91
|
+
expanded: kept?.expanded ?? false,
|
|
92
|
+
};
|
|
93
|
+
}),
|
|
94
|
+
sources: params.sources ?? [],
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
const templateParams = (data: BlockData): Params => ({
|
|
99
|
+
samples: data.samples.map(({ id, label, threshold }) => ({ id, label, threshold })),
|
|
100
|
+
sources: data.sources,
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
const dataModel = new DataModelBuilder({ kind }).from<BlockData>("v1").init(defaults);
|
|
104
|
+
|
|
105
|
+
/** Init seen with params: the same block, configured the way a block without applyParams is. */
|
|
106
|
+
const initWithParams = new DataModelBuilder({ kind })
|
|
107
|
+
.from<BlockData>("v1")
|
|
108
|
+
.init(({ params }) => applyParams(defaults(), params ?? {}));
|
|
109
|
+
|
|
110
|
+
const upstream = "3f1c2b7a-0000-4000-8000-000000000001";
|
|
111
|
+
|
|
112
|
+
/** Live data a user has edited: files, view state and a reordered list. */
|
|
113
|
+
const edited: BlockData = {
|
|
114
|
+
samples: [
|
|
115
|
+
{ id: "s2", label: "Second", threshold: 4, file: "upload://s2.fastq", expanded: true },
|
|
116
|
+
{ id: "s1", label: "First", threshold: 3, file: "upload://s1.fastq", expanded: false },
|
|
117
|
+
],
|
|
118
|
+
sources: [createPlRef(upstream, "reads")],
|
|
119
|
+
view: { sort: "desc" },
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
/** Storage the callback produced, parsed back. Fails the test if it errored. */
|
|
123
|
+
function storageOf(result: unknown) {
|
|
124
|
+
const r = result as { error?: string; storageJson?: string };
|
|
125
|
+
if (r.error !== undefined || r.storageJson === undefined)
|
|
126
|
+
throw new Error(`expected storage, got: ${r.error}`);
|
|
127
|
+
return JSON.parse(r.storageJson) as Record<string, unknown>;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** `__pl_storage_applyParams` hooks for the example block, as `BlockModelV3.done()` wires them. */
|
|
131
|
+
const hooks = {
|
|
132
|
+
dataVersion: "v1",
|
|
133
|
+
applyParams: (data: unknown, p: unknown) => ({
|
|
134
|
+
version: "v1",
|
|
135
|
+
data: applyParams(data as BlockData, p as Params),
|
|
136
|
+
}),
|
|
137
|
+
parseInitializationParams,
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
describe("applyParamsToStorage", () => {
|
|
141
|
+
const editedStorage = stringifyJson(createBlockStorage(edited, "v1"));
|
|
142
|
+
const apply = (storageJson: string, params: unknown) =>
|
|
143
|
+
applyParamsToStorage(storageJson, JSON.stringify(params), hooks);
|
|
144
|
+
|
|
145
|
+
test("puts the params onto live data and keeps what they do not describe", () => {
|
|
146
|
+
const storage = storageOf(apply(editedStorage, { samples: [{ id: "s2", label: "Two" }] }));
|
|
147
|
+
expect(storage.__dataVersion).toBe("v1");
|
|
148
|
+
expect(storage.__data).toEqual({
|
|
149
|
+
...edited,
|
|
150
|
+
samples: [
|
|
151
|
+
{
|
|
152
|
+
id: "s2",
|
|
153
|
+
label: "Two",
|
|
154
|
+
threshold: DEFAULT_THRESHOLD,
|
|
155
|
+
file: "upload://s2.fastq",
|
|
156
|
+
expanded: true,
|
|
157
|
+
},
|
|
158
|
+
],
|
|
159
|
+
sources: [],
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
test("keeps the plugins and the registry", () => {
|
|
164
|
+
const handle = "table" as PluginHandle;
|
|
165
|
+
const withPlugin = stringifyJson({
|
|
166
|
+
...createBlockStorage(edited, "v1"),
|
|
167
|
+
__pluginRegistry: { [handle]: "plTable" as PluginName },
|
|
168
|
+
__plugins: { [handle]: { __dataVersion: "p1", __data: { state: 1 } } },
|
|
169
|
+
});
|
|
170
|
+
const storage = storageOf(apply(withPlugin, {}));
|
|
171
|
+
expect(storage.__pluginRegistry).toEqual({ [handle]: "plTable" });
|
|
172
|
+
expect(storage.__plugins).toEqual({ [handle]: { __dataVersion: "p1", __data: { state: 1 } } });
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
test("runs the kind's check, and applyParams gets its output", () => {
|
|
176
|
+
const rejected = apply(editedStorage, { samples: [{ id: 1 }] });
|
|
177
|
+
expect(rejected.error).toContain("params do not match this block's kind");
|
|
178
|
+
expect(rejected.error).toContain("'samples' must be samples");
|
|
179
|
+
|
|
180
|
+
// The parser drops keys it does not declare; applyParams never sees them.
|
|
181
|
+
let seen: unknown;
|
|
182
|
+
const result = applyParamsToStorage(editedStorage, JSON.stringify({ samples: [], typo: 1 }), {
|
|
183
|
+
...hooks,
|
|
184
|
+
applyParams: (data, p) => {
|
|
185
|
+
seen = p;
|
|
186
|
+
return hooks.applyParams(data, p);
|
|
187
|
+
},
|
|
188
|
+
});
|
|
189
|
+
expect(result.error).toBeUndefined();
|
|
190
|
+
expect(seen).toEqual({ samples: [], sources: undefined });
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
test("expands the readable reference spelling before the check", () => {
|
|
194
|
+
const storage = storageOf(apply(editedStorage, { sources: [{ block: upstream, name: "x" }] }));
|
|
195
|
+
expect((storage.__data as BlockData).sources).toEqual([createPlRef(upstream, "x")]);
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
test("refuses data waiting for a migration", () => {
|
|
199
|
+
const old = stringifyJson(createBlockStorage(edited, "v0"));
|
|
200
|
+
expect(apply(old, {}).error).toContain("waits for a migration");
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
test("reports an applyParams that throws, and params that are not JSON", () => {
|
|
204
|
+
const throwing = applyParamsToStorage(editedStorage, "{}", {
|
|
205
|
+
...hooks,
|
|
206
|
+
applyParams: () => {
|
|
207
|
+
throw new Error("boom");
|
|
208
|
+
},
|
|
209
|
+
});
|
|
210
|
+
expect(throwing.error).toBe("applyParams() threw on the given params: boom");
|
|
211
|
+
|
|
212
|
+
const notJson = applyParamsToStorage(editedStorage, "{not json", hooks);
|
|
213
|
+
expect(notJson.error).toMatch(/params are not valid JSON/);
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
describe("BlockModelV3.applyParams", () => {
|
|
218
|
+
let callbackRegistry: Record<string, (...args: string[]) => unknown>;
|
|
219
|
+
|
|
220
|
+
beforeEach(() => {
|
|
221
|
+
callbackRegistry = {};
|
|
222
|
+
Object.assign(globalThis, { cfgRenderCtx: { callbackRegistry } });
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
afterEach(() => {
|
|
226
|
+
Reflect.deleteProperty(globalThis, "cfgRenderCtx");
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
const APPLY = BlockStorageFacadeCallbacks.StorageApplyParams;
|
|
230
|
+
const FROM_PARAMS = BlockStorageFacadeCallbacks.StorageInitialFromParams;
|
|
231
|
+
const DERIVE = BlockStorageFacadeCallbacks.InitializationParamsDerive;
|
|
232
|
+
|
|
233
|
+
const applying = (model = dataModel) =>
|
|
234
|
+
BlockModelV3.create({ dataModel: model, kind })
|
|
235
|
+
.args((data) => data)
|
|
236
|
+
.templateParams(templateParams)
|
|
237
|
+
.applyParams(applyParams)
|
|
238
|
+
.done();
|
|
239
|
+
|
|
240
|
+
const initOnly = () =>
|
|
241
|
+
BlockModelV3.create({ dataModel: initWithParams, kind })
|
|
242
|
+
.args((data) => data)
|
|
243
|
+
.templateParams(templateParams)
|
|
244
|
+
.done();
|
|
245
|
+
|
|
246
|
+
/** Data the from-params callback builds, as template apply and creation with params do. */
|
|
247
|
+
const fromParams = (params: unknown) =>
|
|
248
|
+
storageOf(callbackRegistry[FROM_PARAMS](JSON.stringify(params), "{}"));
|
|
249
|
+
|
|
250
|
+
test("registers the callback and lists its handle in the config", () => {
|
|
251
|
+
const model = applying();
|
|
252
|
+
expect(lifecycleCallbacks(model)).toContain(APPLY);
|
|
253
|
+
|
|
254
|
+
const result = callbackRegistry[APPLY](
|
|
255
|
+
stringifyJson(createBlockStorage(edited, "v1")),
|
|
256
|
+
JSON.stringify({ samples: [{ id: "s1", label: "One", threshold: 9 }] }),
|
|
257
|
+
);
|
|
258
|
+
expect(storageOf(result).__data).toEqual({
|
|
259
|
+
...edited,
|
|
260
|
+
samples: [
|
|
261
|
+
{ id: "s1", label: "One", threshold: 9, file: "upload://s1.fastq", expanded: false },
|
|
262
|
+
],
|
|
263
|
+
sources: [],
|
|
264
|
+
});
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
test("data from params is applyParams over the defaults", () => {
|
|
268
|
+
applying();
|
|
269
|
+
const params = { samples: [{ id: "s1", label: "One" }], sources: [createPlRef(upstream, "x")] };
|
|
270
|
+
const storage = fromParams(params);
|
|
271
|
+
expect(storage.__dataVersion).toBe("v1");
|
|
272
|
+
expect(storage.__data).toEqual(applyParams(defaults(), params));
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
test("the defaults are the data model's init called without params", () => {
|
|
276
|
+
const seen: unknown[] = [];
|
|
277
|
+
const spying = new DataModelBuilder({ kind }).from<BlockData>("v1").init((args) => {
|
|
278
|
+
seen.push(args);
|
|
279
|
+
return { ...defaults(), view: { sort: "custom" } };
|
|
280
|
+
});
|
|
281
|
+
applying(spying);
|
|
282
|
+
const storage = fromParams({ samples: [{ id: "s1", label: "One" }] });
|
|
283
|
+
expect(seen).toEqual([{}]);
|
|
284
|
+
expect((storage.__data as BlockData).view).toEqual({ sort: "custom" });
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
test("the first law holds through the callbacks: projected params do not depend on the data", () => {
|
|
288
|
+
applying();
|
|
289
|
+
const p = { samples: [{ id: "s1", label: "One", threshold: 2 }] };
|
|
290
|
+
const derive = (storageJson: string) =>
|
|
291
|
+
(callbackRegistry[DERIVE](storageJson) as { value: unknown }).value;
|
|
292
|
+
const onDefaults = derive(stringifyJson(fromParams(p)));
|
|
293
|
+
const applied = storageOf(
|
|
294
|
+
callbackRegistry[APPLY](stringifyJson(createBlockStorage(edited, "v1")), JSON.stringify(p)),
|
|
295
|
+
);
|
|
296
|
+
const onEdited = derive(stringifyJson(applied));
|
|
297
|
+
expect(onEdited).toEqual(onDefaults);
|
|
298
|
+
expect(onEdited).toEqual({ samples: [{ id: "s1", label: "One", threshold: 2 }], sources: [] });
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
test("a block without applyParams has neither the callback nor its handle, and inits from params", () => {
|
|
302
|
+
const model = initOnly();
|
|
303
|
+
expect(lifecycleCallbacks(model)).not.toContain(APPLY);
|
|
304
|
+
expect(callbackRegistry[APPLY]).toBeUndefined();
|
|
305
|
+
expect(lifecycleCallbacks(model)).toContain(FROM_PARAMS);
|
|
306
|
+
// The data model's init gets the params, as before.
|
|
307
|
+
const params = { samples: [{ id: "s1", label: "One" }] };
|
|
308
|
+
expect(fromParams(params).__data).toEqual(applyParams(defaults(), params));
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
test("applyParams is typed by the kind's params and the data model's data", () => {
|
|
312
|
+
const model = BlockModelV3.create({ dataModel, kind })
|
|
313
|
+
.args((data) => data)
|
|
314
|
+
.templateParams(templateParams);
|
|
315
|
+
// @ts-expect-error -- params are the kind's, which have no `other`
|
|
316
|
+
model.applyParams((data, _params: { other: string }) => data);
|
|
317
|
+
// @ts-expect-error -- the result must be the block's data
|
|
318
|
+
model.applyParams(() => ({ wrong: 1 }));
|
|
319
|
+
expect(true).toBe(true);
|
|
320
|
+
});
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
/** The callback handles the config `done()` returns outside a UI lists. */
|
|
324
|
+
function lifecycleCallbacks(model: unknown): string[] {
|
|
325
|
+
if (typeof model !== "object" || model === null || !("config" in model))
|
|
326
|
+
throw new Error("done() returned no block config");
|
|
327
|
+
const config = extractConfig(model.config as BlockConfigContainer);
|
|
328
|
+
if (config.modelAPIVersion !== 2) throw new Error("not a BlockModelV3 config");
|
|
329
|
+
return Object.keys(config.blockLifecycleCallbacks);
|
|
330
|
+
}
|
package/src/block_model.ts
CHANGED
|
@@ -33,6 +33,7 @@ import {
|
|
|
33
33
|
migrateStorage,
|
|
34
34
|
createInitialStorage,
|
|
35
35
|
createInitialStorageFromParams,
|
|
36
|
+
applyParamsToStorage,
|
|
36
37
|
validateTemplateParamsJson,
|
|
37
38
|
deriveArgsFromStorage,
|
|
38
39
|
derivePrerunArgsFromStorage,
|
|
@@ -51,6 +52,7 @@ import {
|
|
|
51
52
|
BLOCK_STORAGE_FACADE_VERSION,
|
|
52
53
|
BlockStorageFacadeCallbacks,
|
|
53
54
|
BlockStorageFacadeHandles,
|
|
55
|
+
BlockStorageFacadeOptionalHandles,
|
|
54
56
|
registerFacadeCallbacks,
|
|
55
57
|
} from "./block_storage_facade";
|
|
56
58
|
|
|
@@ -135,6 +137,8 @@ interface BlockModelV3Config<
|
|
|
135
137
|
prerunArgsIssues: ((input: { prerunArgs: unknown; data: unknown }) => ArgsIssue[]) | undefined;
|
|
136
138
|
/** Projects block data back to this kind's params for template export. */
|
|
137
139
|
deriveTemplateParams: ((data: Data) => Params) | undefined;
|
|
140
|
+
/** Puts this kind's params onto live block data; the inverse of `deriveTemplateParams`. */
|
|
141
|
+
applyParams: ((data: Data, params: Params) => Data) | undefined;
|
|
138
142
|
/**
|
|
139
143
|
* The kind's runtime check for params supplied by a template. Read off the compiled
|
|
140
144
|
* kind rather than declared per block: the params contract belongs to the kind, and
|
|
@@ -240,6 +244,7 @@ export class BlockModelV3<
|
|
|
240
244
|
derivePrerunArgs: undefined,
|
|
241
245
|
prerunArgsIssues: undefined,
|
|
242
246
|
deriveTemplateParams: undefined,
|
|
247
|
+
applyParams: undefined,
|
|
243
248
|
plugins: {},
|
|
244
249
|
});
|
|
245
250
|
}
|
|
@@ -475,8 +480,9 @@ export class BlockModelV3<
|
|
|
475
480
|
* Sets the function that projects block data back to this kind's params, for
|
|
476
481
|
* exporting the project as a template.
|
|
477
482
|
*
|
|
478
|
-
* The inverse of
|
|
479
|
-
* recovers the `params` that would rebuild the
|
|
483
|
+
* The inverse of how params become data — {@link applyParams} when the block declares it,
|
|
484
|
+
* the data model's `init` otherwise: this recovers the `params` that would rebuild the
|
|
485
|
+
* current data. Return only params
|
|
480
486
|
* — runtime and derived state is dropped, and the exporter supplies the rest of
|
|
481
487
|
* the entry (`id`, `kind`), which this lambda cannot set.
|
|
482
488
|
*
|
|
@@ -508,6 +514,75 @@ export class BlockModelV3<
|
|
|
508
514
|
});
|
|
509
515
|
}
|
|
510
516
|
|
|
517
|
+
/**
|
|
518
|
+
* Sets the function that puts this kind's params onto live block data: the data the block
|
|
519
|
+
* would have, were it configured with `params`. Together with {@link templateParams} it is a
|
|
520
|
+
* pair — `templateParams` projects data onto params, `applyParams` writes params back onto data.
|
|
521
|
+
*
|
|
522
|
+
* Everything the params describe is written from `params`; everything they do not describe
|
|
523
|
+
* (files, per-item values, view state, edits made in the UI) is kept from `data`.
|
|
524
|
+
*
|
|
525
|
+
* Declaring it makes it the one way params become data. Data built from params (template
|
|
526
|
+
* apply, creation with params) is `applyParams(defaults, params)`, `defaults` being the data
|
|
527
|
+
* model's default data (its `init` called without params); a write of params onto an existing
|
|
528
|
+
* block (the MCP `set_block_params`) is `applyParams(current, params)`. Both run after the
|
|
529
|
+
* kind's parser has accepted the params. Without it, data from params is the data model's
|
|
530
|
+
* `init` called with them, as before.
|
|
531
|
+
*
|
|
532
|
+
* Params are whole, not a patch: a key absent from `params` is the kind's "unset", and
|
|
533
|
+
* `applyParams` writes that into the data rather than leaving the old value.
|
|
534
|
+
*
|
|
535
|
+
* Laws the block keeps:
|
|
536
|
+
* - `templateParams(applyParams(d, p))` equals `templateParams(applyParams(defaults, p))` for
|
|
537
|
+
* any data `d` (the projection may leave out what does not travel, such as files);
|
|
538
|
+
* - `applyParams(d, templateParams(d))` equals `d`.
|
|
539
|
+
* The middle layer checks the first on every write of params and refuses one that breaks it.
|
|
540
|
+
*
|
|
541
|
+
* A shallow spread such as `({ ...data, ...params })` is usually wrong. It overwrites whole
|
|
542
|
+
* values the params describe only in part — a list of items replaces the items in data along
|
|
543
|
+
* with their files and view state — and it leaves in place what a key absent from `params`
|
|
544
|
+
* should unset. Write each field the params describe, and match list items by their id.
|
|
545
|
+
*
|
|
546
|
+
* The parameter types are the kind's `Params` and the data model's data, so the function is
|
|
547
|
+
* checked against the same contract as {@link templateParams}.
|
|
548
|
+
*
|
|
549
|
+
* @example
|
|
550
|
+
* // Params: { samples: { id: string; label: string; threshold?: number }[] }
|
|
551
|
+
* // Data: { samples: { id; label; threshold; file?: ImportFileHandle; expanded: boolean }[];
|
|
552
|
+
* // tab: string }
|
|
553
|
+
* BlockModelV3.create({ dataModel, kind })
|
|
554
|
+
* .args((data) => ({ samples: data.samples }))
|
|
555
|
+
* .templateParams((data) => ({
|
|
556
|
+
* samples: data.samples.map(({ id, label, threshold }) => ({ id, label, threshold })),
|
|
557
|
+
* }))
|
|
558
|
+
* .applyParams((data, params) => {
|
|
559
|
+
* const current = new Map(data.samples.map((s) => [s.id, s]));
|
|
560
|
+
* return {
|
|
561
|
+
* ...data, // `tab` and anything else the params do not describe
|
|
562
|
+
* // The list is the params': a sample absent from them is removed.
|
|
563
|
+
* samples: params.samples.map((p) => {
|
|
564
|
+
* const kept = current.get(p.id); // per-sample state the params do not describe
|
|
565
|
+
* return {
|
|
566
|
+
* id: p.id,
|
|
567
|
+
* label: p.label,
|
|
568
|
+
* threshold: p.threshold ?? DEFAULT_THRESHOLD, // absent means unset, not unchanged
|
|
569
|
+
* file: kept?.file,
|
|
570
|
+
* expanded: kept?.expanded ?? false,
|
|
571
|
+
* };
|
|
572
|
+
* }),
|
|
573
|
+
* };
|
|
574
|
+
* })
|
|
575
|
+
* .done();
|
|
576
|
+
*/
|
|
577
|
+
public applyParams(
|
|
578
|
+
fn: (data: Data, params: Params) => Data,
|
|
579
|
+
): BlockModelV3<Args, OutputsCfg, Data, Href, Plugins, Transfers, Params, PrerunArgs> {
|
|
580
|
+
return new BlockModelV3<Args, OutputsCfg, Data, Href, Plugins, Transfers, Params, PrerunArgs>({
|
|
581
|
+
...this.config,
|
|
582
|
+
applyParams: fn,
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
|
|
511
586
|
/** Sets the lambda to generate list of sections in the left block overviews panel. */
|
|
512
587
|
public sections<
|
|
513
588
|
const Ret extends SectionsExpectedType,
|
|
@@ -762,9 +837,16 @@ export class BlockModelV3<
|
|
|
762
837
|
derivePrerunArgs,
|
|
763
838
|
prerunArgsIssues,
|
|
764
839
|
deriveTemplateParams,
|
|
840
|
+
applyParams,
|
|
765
841
|
parseInitializationParams,
|
|
766
842
|
} = this.config;
|
|
767
843
|
|
|
844
|
+
// The block's `applyParams` with its types erased, as the callbacks hand it data and params
|
|
845
|
+
// that arrive as JSON. The params have passed the kind's parser by the time it runs.
|
|
846
|
+
const applyParamsErased = applyParams as
|
|
847
|
+
| ((data: unknown, params: unknown) => unknown)
|
|
848
|
+
| undefined;
|
|
849
|
+
|
|
768
850
|
function getPlugin(handle: PluginHandle): PluginRecord {
|
|
769
851
|
const plugin = plugins[handle];
|
|
770
852
|
if (!plugin) throw new Error(`Plugin model not found for '${handle}'`);
|
|
@@ -807,13 +889,36 @@ export class BlockModelV3<
|
|
|
807
889
|
),
|
|
808
890
|
[BlockStorageFacadeCallbacks.StorageInitialFromParams]: (paramsJson, blockIdsJson) =>
|
|
809
891
|
createInitialStorageFromParams(paramsJson, blockIdsJson, {
|
|
810
|
-
|
|
892
|
+
// With `applyParams` declared, data from params is `applyParams(defaults, params)`.
|
|
893
|
+
getBlockDataFromParams: (params) => {
|
|
894
|
+
if (applyParamsErased === undefined || params === undefined)
|
|
895
|
+
return dataModel.getDataFromParams(params);
|
|
896
|
+
const defaults = dataModel.getDefaultData();
|
|
897
|
+
return {
|
|
898
|
+
version: defaults.version,
|
|
899
|
+
data: applyParamsErased(defaults.data, params),
|
|
900
|
+
};
|
|
901
|
+
},
|
|
811
902
|
getPluginRegistry: () => pluginRegistry,
|
|
812
903
|
createPluginData: (handle) => getPlugin(handle).model.getDefaultData(),
|
|
813
904
|
parseInitializationParams,
|
|
814
905
|
}),
|
|
815
906
|
[BlockStorageFacadeCallbacks.InitializationParamsValidate]: (paramsJson) =>
|
|
816
907
|
validateTemplateParamsJson(paramsJson, parseInitializationParams),
|
|
908
|
+
// Only for a block that declares `applyParams`: the callback's absence is how the
|
|
909
|
+
// middle layer knows to build data from params some other way.
|
|
910
|
+
[BlockStorageFacadeCallbacks.StorageApplyParams]:
|
|
911
|
+
applyParamsErased === undefined
|
|
912
|
+
? undefined
|
|
913
|
+
: (storageJson, paramsJson) =>
|
|
914
|
+
applyParamsToStorage(storageJson, paramsJson, {
|
|
915
|
+
dataVersion: dataModel.version,
|
|
916
|
+
applyParams: (data, params) => ({
|
|
917
|
+
version: dataModel.version,
|
|
918
|
+
data: applyParamsErased(data, params),
|
|
919
|
+
}),
|
|
920
|
+
parseInitializationParams,
|
|
921
|
+
}),
|
|
817
922
|
});
|
|
818
923
|
|
|
819
924
|
// Register plugin input and output lambdas
|
|
@@ -855,7 +960,17 @@ export class BlockModelV3<
|
|
|
855
960
|
outputs: allOutputs,
|
|
856
961
|
enrichmentTargets: this.config.enrichmentTargets,
|
|
857
962
|
featureFlags: this.config.featureFlags,
|
|
858
|
-
blockLifecycleCallbacks: {
|
|
963
|
+
blockLifecycleCallbacks: {
|
|
964
|
+
...BlockStorageFacadeHandles,
|
|
965
|
+
...(applyParams !== undefined
|
|
966
|
+
? {
|
|
967
|
+
[BlockStorageFacadeCallbacks.StorageApplyParams]:
|
|
968
|
+
BlockStorageFacadeOptionalHandles[
|
|
969
|
+
BlockStorageFacadeCallbacks.StorageApplyParams
|
|
970
|
+
],
|
|
971
|
+
}
|
|
972
|
+
: {}),
|
|
973
|
+
},
|
|
859
974
|
},
|
|
860
975
|
|
|
861
976
|
// Block-kind identity, baked at the container level beside `code`
|
|
@@ -948,6 +1063,7 @@ type _ConfigTest = Expect<
|
|
|
948
1063
|
| ((input: { prerunArgs: unknown; data: unknown }) => ArgsIssue[])
|
|
949
1064
|
| undefined;
|
|
950
1065
|
deriveTemplateParams: ((data: _TestData) => unknown) | undefined;
|
|
1066
|
+
applyParams: ((data: _TestData, params: unknown) => _TestData) | undefined;
|
|
951
1067
|
parseInitializationParams: (value: unknown) => unknown;
|
|
952
1068
|
dataModel: DataModel<_TestData, unknown, {}>;
|
|
953
1069
|
kind: BlockKindReference | undefined;
|
|
@@ -500,6 +500,80 @@ export function createInitialStorageFromParams(
|
|
|
500
500
|
}
|
|
501
501
|
}
|
|
502
502
|
|
|
503
|
+
// =============================================================================
|
|
504
|
+
// Params onto Live Data
|
|
505
|
+
// =============================================================================
|
|
506
|
+
|
|
507
|
+
/** Dependencies for putting params onto a block's live data. */
|
|
508
|
+
export interface ApplyParamsHooks {
|
|
509
|
+
/** The data model's current version: the one `applyParams` takes and returns. */
|
|
510
|
+
dataVersion: string;
|
|
511
|
+
/** The block's `applyParams`, given data at {@link ApplyParamsHooks.dataVersion}. */
|
|
512
|
+
applyParams: (data: unknown, params: unknown) => DataVersioned<unknown>;
|
|
513
|
+
/** The kind's runtime params check; its output is what `applyParams` gets. */
|
|
514
|
+
parseInitializationParams: (value: unknown) => unknown;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* Puts params onto the block's live data with the block's own `applyParams`, the
|
|
519
|
+
* `__pl_storage_applyParams` callback.
|
|
520
|
+
*
|
|
521
|
+
* The params are checked as {@link createInitialStorageFromParams} checks them: the readable
|
|
522
|
+
* reference spelling is expanded, then the kind's parser runs and its output is what
|
|
523
|
+
* `applyParams` gets. They are live params, so no reference is relocated.
|
|
524
|
+
*
|
|
525
|
+
* The data is refused unless it is at the data model's current version: `applyParams` is written
|
|
526
|
+
* against that type, and migrating here would leave plugin transfers half done. Everything but the
|
|
527
|
+
* block's data — its version, plugins, registry — is kept as it is.
|
|
528
|
+
*
|
|
529
|
+
* @param storageJson - Current storage as JSON string
|
|
530
|
+
* @param paramsJson - The new params as JSON string, whole
|
|
531
|
+
* @param hooks - The block's `applyParams`, its data version, the kind's parser
|
|
532
|
+
* @returns The storage with the params applied, or why there is none
|
|
533
|
+
*/
|
|
534
|
+
export function applyParamsToStorage(
|
|
535
|
+
storageJson: string,
|
|
536
|
+
paramsJson: string,
|
|
537
|
+
hooks: ApplyParamsHooks,
|
|
538
|
+
): ParamsStorageResult {
|
|
539
|
+
let params: unknown;
|
|
540
|
+
try {
|
|
541
|
+
params = JSON.parse(paramsJson);
|
|
542
|
+
} catch (e) {
|
|
543
|
+
return { error: `params are not valid JSON: ${messageOf(e)}` };
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
const { storage, data } = normalizeStorage(storageJson);
|
|
547
|
+
if (storage.__dataVersion !== hooks.dataVersion)
|
|
548
|
+
return {
|
|
549
|
+
error:
|
|
550
|
+
`the block's data is at version ${storage.__dataVersion}, while applyParams() ` +
|
|
551
|
+
`takes version ${hooks.dataVersion}: the data waits for a migration`,
|
|
552
|
+
};
|
|
553
|
+
|
|
554
|
+
try {
|
|
555
|
+
params = expandTemplateRefs(params);
|
|
556
|
+
} catch (e) {
|
|
557
|
+
return { error: `the params' references could not be read: ${messageOf(e)}` };
|
|
558
|
+
}
|
|
559
|
+
const checked = validateTemplateParams(params, hooks.parseInitializationParams);
|
|
560
|
+
if (checked.error !== undefined) return { error: checked.error };
|
|
561
|
+
|
|
562
|
+
let applied: DataVersioned<unknown>;
|
|
563
|
+
try {
|
|
564
|
+
applied = hooks.applyParams(data, checked.value);
|
|
565
|
+
} catch (e) {
|
|
566
|
+
return { error: `applyParams() threw on the given params: ${messageOf(e)}` };
|
|
567
|
+
}
|
|
568
|
+
return {
|
|
569
|
+
storageJson: stringifyJson({
|
|
570
|
+
...storage,
|
|
571
|
+
__dataVersion: applied.version,
|
|
572
|
+
__data: applied.data,
|
|
573
|
+
}),
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
|
|
503
577
|
// =============================================================================
|
|
504
578
|
// Args Derivation from Storage
|
|
505
579
|
// =============================================================================
|