@milaboratories/pl-middle-layer 2.10.1 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/dist/block_registry/registry-v2-provider.cjs +8 -1
  2. package/dist/block_registry/registry-v2-provider.cjs.map +1 -1
  3. package/dist/block_registry/registry-v2-provider.d.ts.map +1 -1
  4. package/dist/block_registry/registry-v2-provider.js +8 -1
  5. package/dist/block_registry/registry-v2-provider.js.map +1 -1
  6. package/dist/index.cjs +24 -0
  7. package/dist/index.d.ts +11 -4
  8. package/dist/index.js +4 -2
  9. package/dist/js_render/bundle_bytecode_cache.cjs +6 -1
  10. package/dist/js_render/bundle_bytecode_cache.cjs.map +1 -1
  11. package/dist/js_render/bundle_bytecode_cache.js +6 -1
  12. package/dist/js_render/bundle_bytecode_cache.js.map +1 -1
  13. package/dist/js_render/column_registry.cjs +17 -0
  14. package/dist/js_render/column_registry.cjs.map +1 -1
  15. package/dist/js_render/column_registry.js +16 -1
  16. package/dist/js_render/column_registry.js.map +1 -1
  17. package/dist/js_render/computable_context.cjs +1 -1
  18. package/dist/js_render/computable_context.js +1 -1
  19. package/dist/js_render/context.cjs +3 -2
  20. package/dist/js_render/context.cjs.map +1 -1
  21. package/dist/js_render/context.js +3 -2
  22. package/dist/js_render/context.js.map +1 -1
  23. package/dist/js_render/index.cjs +1 -1
  24. package/dist/js_render/index.cjs.map +1 -1
  25. package/dist/js_render/index.js +1 -1
  26. package/dist/js_render/index.js.map +1 -1
  27. package/dist/js_render/service_injectors.cjs +2 -9
  28. package/dist/js_render/service_injectors.cjs.map +1 -1
  29. package/dist/js_render/service_injectors.js +2 -9
  30. package/dist/js_render/service_injectors.js.map +1 -1
  31. package/dist/middle_layer/block.cjs +48 -0
  32. package/dist/middle_layer/block.cjs.map +1 -1
  33. package/dist/middle_layer/block.js +51 -4
  34. package/dist/middle_layer/block.js.map +1 -1
  35. package/dist/middle_layer/block_pack_description.cjs +80 -0
  36. package/dist/middle_layer/block_pack_description.cjs.map +1 -0
  37. package/dist/middle_layer/block_pack_description.d.ts +36 -0
  38. package/dist/middle_layer/block_pack_description.d.ts.map +1 -0
  39. package/dist/middle_layer/block_pack_description.js +78 -0
  40. package/dist/middle_layer/block_pack_description.js.map +1 -0
  41. package/dist/middle_layer/build_stamp.cjs +1 -1
  42. package/dist/middle_layer/build_stamp.js +1 -1
  43. package/dist/middle_layer/index.cjs +11 -0
  44. package/dist/middle_layer/index.d.ts +8 -2
  45. package/dist/middle_layer/index.js +3 -1
  46. package/dist/middle_layer/legacy_project_holds.cjs +61 -0
  47. package/dist/middle_layer/legacy_project_holds.cjs.map +1 -0
  48. package/dist/middle_layer/legacy_project_holds.js +61 -0
  49. package/dist/middle_layer/legacy_project_holds.js.map +1 -0
  50. package/dist/middle_layer/middle_layer.cjs +18 -21
  51. package/dist/middle_layer/middle_layer.cjs.map +1 -1
  52. package/dist/middle_layer/middle_layer.d.ts +13 -3
  53. package/dist/middle_layer/middle_layer.d.ts.map +1 -1
  54. package/dist/middle_layer/middle_layer.js +18 -21
  55. package/dist/middle_layer/middle_layer.js.map +1 -1
  56. package/dist/middle_layer/pool_columns.cjs +160 -0
  57. package/dist/middle_layer/pool_columns.cjs.map +1 -0
  58. package/dist/middle_layer/pool_columns.d.ts +59 -0
  59. package/dist/middle_layer/pool_columns.d.ts.map +1 -0
  60. package/dist/middle_layer/pool_columns.js +157 -0
  61. package/dist/middle_layer/pool_columns.js.map +1 -0
  62. package/dist/middle_layer/pool_frame.cjs +82 -0
  63. package/dist/middle_layer/pool_frame.cjs.map +1 -0
  64. package/dist/middle_layer/pool_frame.d.ts +37 -0
  65. package/dist/middle_layer/pool_frame.d.ts.map +1 -0
  66. package/dist/middle_layer/pool_frame.js +81 -0
  67. package/dist/middle_layer/pool_frame.js.map +1 -0
  68. package/dist/middle_layer/pool_table.cjs +66 -0
  69. package/dist/middle_layer/pool_table.cjs.map +1 -0
  70. package/dist/middle_layer/pool_table.d.ts +27 -0
  71. package/dist/middle_layer/pool_table.d.ts.map +1 -0
  72. package/dist/middle_layer/pool_table.js +66 -0
  73. package/dist/middle_layer/pool_table.js.map +1 -0
  74. package/dist/middle_layer/project.cjs +83 -2
  75. package/dist/middle_layer/project.cjs.map +1 -1
  76. package/dist/middle_layer/project.d.ts +69 -3
  77. package/dist/middle_layer/project.d.ts.map +1 -1
  78. package/dist/middle_layer/project.js +84 -3
  79. package/dist/middle_layer/project.js.map +1 -1
  80. package/dist/middle_layer/rich_column_query.cjs +180 -0
  81. package/dist/middle_layer/rich_column_query.cjs.map +1 -0
  82. package/dist/middle_layer/rich_column_query.d.ts +34 -0
  83. package/dist/middle_layer/rich_column_query.d.ts.map +1 -0
  84. package/dist/middle_layer/rich_column_query.js +176 -0
  85. package/dist/middle_layer/rich_column_query.js.map +1 -0
  86. package/dist/model/args.cjs +23 -0
  87. package/dist/model/args.cjs.map +1 -1
  88. package/dist/model/args.js +24 -2
  89. package/dist/model/args.js.map +1 -1
  90. package/dist/model/args_derivation.cjs +60 -2
  91. package/dist/model/args_derivation.cjs.map +1 -1
  92. package/dist/model/args_derivation.d.ts +73 -3
  93. package/dist/model/args_derivation.d.ts.map +1 -1
  94. package/dist/model/args_derivation.js +60 -3
  95. package/dist/model/args_derivation.js.map +1 -1
  96. package/dist/model/block_params_model.cjs +42 -0
  97. package/dist/model/block_params_model.cjs.map +1 -0
  98. package/dist/model/block_params_model.d.ts +45 -0
  99. package/dist/model/block_params_model.d.ts.map +1 -0
  100. package/dist/model/block_params_model.js +42 -0
  101. package/dist/model/block_params_model.js.map +1 -0
  102. package/dist/model/index.d.ts +3 -1
  103. package/dist/model/project_helper.cjs +50 -6
  104. package/dist/model/project_helper.cjs.map +1 -1
  105. package/dist/model/project_helper.d.ts +25 -1
  106. package/dist/model/project_helper.d.ts.map +1 -1
  107. package/dist/model/project_helper.js +51 -7
  108. package/dist/model/project_helper.js.map +1 -1
  109. package/dist/mutator/block-pack/block_pack.cjs +1 -1
  110. package/dist/mutator/block-pack/block_pack.js +1 -1
  111. package/dist/mutator/project.cjs +4 -0
  112. package/dist/mutator/project.cjs.map +1 -1
  113. package/dist/mutator/project.d.ts +1 -1
  114. package/dist/mutator/project.d.ts.map +1 -1
  115. package/dist/mutator/project.js +4 -0
  116. package/dist/mutator/project.js.map +1 -1
  117. package/package.json +9 -9
  118. package/src/block_registry/registry-v2-provider.test.ts +23 -0
  119. package/src/block_registry/registry-v2-provider.ts +11 -1
  120. package/src/index.ts +2 -0
  121. package/src/js_render/bundle_bytecode_cache.ts +15 -4
  122. package/src/js_render/column_registry.ts +24 -3
  123. package/src/js_render/context.ts +4 -3
  124. package/src/js_render/index.ts +3 -2
  125. package/src/js_render/service_injectors.ts +2 -11
  126. package/src/middle_layer/block.ts +61 -2
  127. package/src/middle_layer/block_pack_description.test.ts +235 -0
  128. package/src/middle_layer/block_pack_description.ts +143 -0
  129. package/src/middle_layer/index.ts +9 -1
  130. package/src/middle_layer/legacy_project_holds.test.ts +133 -0
  131. package/src/middle_layer/legacy_project_holds.ts +73 -0
  132. package/src/middle_layer/middle_layer.ts +23 -26
  133. package/src/middle_layer/pool_columns.test.ts +217 -0
  134. package/src/middle_layer/pool_columns.ts +250 -0
  135. package/src/middle_layer/pool_frame.test.ts +144 -0
  136. package/src/middle_layer/pool_frame.ts +127 -0
  137. package/src/middle_layer/pool_table.test.ts +182 -0
  138. package/src/middle_layer/pool_table.ts +98 -0
  139. package/src/middle_layer/project.ts +128 -5
  140. package/src/middle_layer/rich_column_query.test.ts +311 -0
  141. package/src/middle_layer/rich_column_query.ts +214 -0
  142. package/src/model/args.test.ts +23 -1
  143. package/src/model/args.ts +29 -1
  144. package/src/model/args_derivation.test.ts +129 -12
  145. package/src/model/args_derivation.ts +112 -8
  146. package/src/model/block_params_model.test.ts +194 -0
  147. package/src/model/block_params_model.ts +117 -0
  148. package/src/model/index.ts +6 -0
  149. package/src/model/project_helper.ts +101 -20
  150. package/src/mutator/project.ts +5 -0
  151. package/src/pool/result_pool_markers.test.ts +47 -0
  152. package/src/test/fake_project.ts +33 -6
@@ -8,6 +8,7 @@ import {
8
8
  argsFingerprint,
9
9
  derivedArgsValue,
10
10
  parseArgsDeriveResult,
11
+ parsePrerunArgsDeriveResult,
11
12
  readArgsErrorsField,
12
13
  argsErrorsFieldChange,
13
14
  argsErrorsOfBlock,
@@ -30,6 +31,7 @@ describe("parseArgsDeriveResult", () => {
30
31
  expect(parseArgsDeriveResult({ value: { n: 1 } })).toEqual({
31
32
  type: "runnable",
32
33
  args: { n: 1 },
34
+ issues: [],
33
35
  });
34
36
  expect(parseArgsDeriveResult({ error: "args() threw: no input" })).toEqual({
35
37
  type: "absent",
@@ -45,21 +47,32 @@ describe("parseArgsDeriveResult", () => {
45
47
  ).toMatchObject({ type: "absent" });
46
48
  });
47
49
 
48
- test("warnings leave the args runnable", () => {
50
+ test("warnings leave the args runnable, and are kept as issues", () => {
49
51
  expect(parseArgsDeriveResult({ value: { n: 1 }, issues: [fewSamples] })).toEqual({
50
52
  type: "runnable",
51
53
  args: { n: 1 },
54
+ issues: [fewSamples],
55
+ });
56
+ expect(parseArgsDeriveResult({ value: { n: 1 }, issues: "not a list" })).toEqual({
57
+ type: "runnable",
58
+ args: { n: 1 },
59
+ issues: [],
52
60
  });
53
61
  });
54
62
 
55
- test("errors of argsIssues block the args, warnings are left out", () => {
63
+ test("errors of argsIssues block the args; warnings are left out of the errors, not the issues", () => {
56
64
  expect(
57
65
  parseArgsDeriveResult({
58
66
  error: "Set a threshold",
59
67
  args: { n: 1 },
60
68
  issues: [fewSamples, missingThreshold],
61
69
  }),
62
- ).toEqual({ type: "blocked", args: { n: 1 }, errors: [missingThreshold] });
70
+ ).toEqual({
71
+ type: "blocked",
72
+ args: { n: 1 },
73
+ errors: [missingThreshold],
74
+ issues: [fewSamples, missingThreshold],
75
+ });
63
76
  });
64
77
 
65
78
  test("a severity other than warning is an error", () => {
@@ -69,22 +82,28 @@ describe("parseArgsDeriveResult", () => {
69
82
  args: {},
70
83
  issues: [{ severity: "fatal", message: "Set a threshold" }],
71
84
  }),
72
- ).toEqual({ type: "blocked", args: {}, errors: [missingThreshold] });
85
+ ).toEqual({
86
+ type: "blocked",
87
+ args: {},
88
+ errors: [missingThreshold],
89
+ issues: [missingThreshold],
90
+ });
73
91
  });
74
92
 
75
93
  test("issues that cannot be read, or hold no error, give way to the reported error", () => {
76
94
  const reported: ArgsIssue = { severity: "error", message: "Set a threshold; Pick a column" };
77
95
  expect(
78
96
  parseArgsDeriveResult({ error: reported.message, args: {}, issues: "not a list" }),
79
- ).toEqual({ type: "blocked", args: {}, errors: [reported] });
97
+ ).toEqual({ type: "blocked", args: {}, errors: [reported], issues: [reported] });
80
98
  expect(parseArgsDeriveResult({ error: reported.message, args: {} })).toEqual({
81
99
  type: "blocked",
82
100
  args: {},
83
101
  errors: [reported],
102
+ issues: [reported],
84
103
  });
85
104
  expect(
86
105
  parseArgsDeriveResult({ error: reported.message, args: {}, issues: [fewSamples] }),
87
- ).toEqual({ type: "blocked", args: {}, errors: [reported] });
106
+ ).toEqual({ type: "blocked", args: {}, errors: [reported], issues: [reported, fewSamples] });
88
107
  });
89
108
 
90
109
  test("refuses a result that is not an object, or whose error is not a string", () => {
@@ -255,7 +274,7 @@ describe("ProjectHelper.deriveArgsFromStorage", () => {
255
274
  test("a model without args issues whose args() succeeds has runnable args", () => {
256
275
  const derived = helper.deriveArgsFromStorage(configWith("() => ({ value: { n: 1 } })"), "{}");
257
276
 
258
- expect(derived).toEqual({ type: "runnable", args: { n: 1 } });
277
+ expect(derived).toEqual({ type: "runnable", args: { n: 1 }, issues: [] });
259
278
  expect(argsErrorsFieldChange(undefined, derived)).toEqual({
260
279
  type: "write",
261
280
  data: recordBytes({ n: 1 }, []),
@@ -272,7 +291,12 @@ describe("ProjectHelper.deriveArgsFromStorage", () => {
272
291
  JSON.stringify({ n: 5 }),
273
292
  );
274
293
 
275
- expect(derived).toEqual({ type: "blocked", args: { n: 5 }, errors: [missingThreshold] });
294
+ expect(derived).toEqual({
295
+ type: "blocked",
296
+ args: { n: 5 },
297
+ errors: [missingThreshold],
298
+ issues: [fewSamples, missingThreshold],
299
+ });
276
300
  });
277
301
 
278
302
  test("a model that fails, or returns something unreadable, gives no args", () => {
@@ -285,14 +309,105 @@ describe("ProjectHelper.deriveArgsFromStorage", () => {
285
309
  });
286
310
  });
287
311
 
312
+ describe("parsePrerunArgsDeriveResult", () => {
313
+ test("reads the results of a model without args issues as before", () => {
314
+ expect(parsePrerunArgsDeriveResult({ value: { n: 1 } })).toEqual({
315
+ type: "staged",
316
+ args: { n: 1 },
317
+ issues: [],
318
+ });
319
+ expect(parsePrerunArgsDeriveResult({ error: "prerunArgs() threw: no input" })).toEqual({
320
+ type: "failed",
321
+ error: "prerunArgs() threw: no input",
322
+ });
323
+ });
324
+
325
+ test("prerun args that are undefined skip staging", () => {
326
+ expect(parsePrerunArgsDeriveResult({ value: undefined, issues: [] })).toEqual({
327
+ type: "skipped",
328
+ issues: [],
329
+ });
330
+ expect(parsePrerunArgsDeriveResult({})).toEqual({ type: "skipped", issues: [] });
331
+ });
332
+
333
+ test("errors among the issues block staging; warnings stage with the args", () => {
334
+ expect(
335
+ parsePrerunArgsDeriveResult({
336
+ error: "argsIssues() found errors (fallback): Set a threshold",
337
+ issues: [fewSamples, missingThreshold],
338
+ }),
339
+ ).toEqual({
340
+ type: "blocked",
341
+ error: "argsIssues() found errors (fallback): Set a threshold",
342
+ issues: [fewSamples, missingThreshold],
343
+ });
344
+ expect(parsePrerunArgsDeriveResult({ value: { n: 1 }, issues: [fewSamples] })).toEqual({
345
+ type: "staged",
346
+ args: { n: 1 },
347
+ issues: [fewSamples],
348
+ });
349
+ });
350
+
351
+ test("refuses a result that is not an object, or whose error is not a string", () => {
352
+ expect(() => parsePrerunArgsDeriveResult(null)).toThrow();
353
+ expect(() => parsePrerunArgsDeriveResult({ error: 1 })).toThrow();
354
+ });
355
+ });
356
+
357
+ describe("ProjectHelper.derivePrerunArgsDetailedFromStorage", () => {
358
+ const prerun = (body: string) => configWith(body, BlockStorageFacadeCallbacks.PrerunArgsDerive);
359
+
360
+ test("gives the prerun args to stage, and the plain helper gives the same args", () => {
361
+ const config = prerun("(storageJson) => ({ value: JSON.parse(storageJson), issues: [] })");
362
+ expect(helper.derivePrerunArgsDetailedFromStorage(config, '{"n":2}')).toEqual({
363
+ type: "staged",
364
+ args: { n: 2 },
365
+ issues: [],
366
+ });
367
+ expect(helper.derivePrerunArgsFromStorage(config, '{"n":2}')).toEqual({ n: 2 });
368
+ });
369
+
370
+ test("says why there is nothing to stage; the plain helper gives undefined", () => {
371
+ const cases = [
372
+ [
373
+ prerun("() => ({ error: 'prerunArgs() threw: Select a dataset' })"),
374
+ { type: "failed", error: "prerunArgs() threw: Select a dataset" },
375
+ ],
376
+ [
377
+ prerun(
378
+ "() => ({ error: 'Set a threshold', issues: [{ severity: 'error', message: 'Set a threshold' }] })",
379
+ ),
380
+ { type: "blocked", error: "Set a threshold", issues: [missingThreshold] },
381
+ ],
382
+ [prerun("() => ({ value: undefined, issues: [] })"), { type: "skipped", issues: [] }],
383
+ ] as const;
384
+ for (const [config, expected] of cases) {
385
+ expect(helper.derivePrerunArgsDetailedFromStorage(config, "{}")).toEqual(expected);
386
+ expect(helper.derivePrerunArgsFromStorage(config, "{}")).toBeUndefined();
387
+ }
388
+ });
389
+
390
+ test("a model that fails, or returns something unreadable, is a failed derivation", () => {
391
+ expect(
392
+ helper.derivePrerunArgsDetailedFromStorage(
393
+ prerun("() => { throw new Error('boom'); }"),
394
+ "{}",
395
+ ),
396
+ ).toMatchObject({ type: "failed", error: expect.stringContaining("boom") });
397
+ expect(helper.derivePrerunArgsDetailedFromStorage(prerun("() => 42"), "{}")).toMatchObject({
398
+ type: "failed",
399
+ });
400
+ });
401
+ });
402
+
288
403
  // Internals
289
404
 
290
405
  function runnable(args: unknown): DerivedArgs {
291
- return { type: "runnable", args };
406
+ return { type: "runnable", args, issues: [] };
292
407
  }
293
408
 
294
409
  function blocked(args: unknown, errors: ArgsIssue[]): DerivedArgs {
295
- return { type: "blocked", args, errors };
410
+ return { type: "blocked", args, errors, issues: errors };
296
411
  }
297
412
 
298
413
  function recordBytes(args: unknown, errors: ArgsIssue[]): Uint8Array {
@@ -308,8 +423,10 @@ function absent(): DerivedArgs {
308
423
  * A block config whose model code registers `body` as its __pl_args_derive callback, the way the
309
424
  * SDK registers callbacks inside a real bundle.
310
425
  */
311
- function configWith(body: string): BlockConfig {
312
- const handle = BlockStorageFacadeCallbacks.ArgsDerive;
426
+ function configWith(
427
+ body: string,
428
+ handle: string = BlockStorageFacadeCallbacks.ArgsDerive,
429
+ ): BlockConfig {
313
430
  return {
314
431
  configVersion: 4,
315
432
  modelAPIVersion: 2,
@@ -1,4 +1,4 @@
1
- import { parseArgsIssues, type ArgsIssue } from "@milaboratories/pl-model-common";
1
+ import { parseArgsIssues, type ArgsIssue, type BlockId } from "@milaboratories/pl-model-common";
2
2
  import { cachedDeserialize, canonicalJsonBytes } from "@milaboratories/ts-helpers";
3
3
  import { isString } from "es-toolkit";
4
4
  import { createHash } from "node:crypto";
@@ -7,16 +7,72 @@ import { BLOCK_STORAGE_FACADE_VERSION } from "@platforma-sdk/model";
7
7
  /**
8
8
  * What the args derivation of a block with model API version 2 made of the block's storage.
9
9
  *
10
- * - `runnable`: the block has args and may run with them.
10
+ * - `runnable`: the block has args and may run with them. `issues` holds the warnings its
11
+ * `argsIssues()` found, if any.
11
12
  * - `blocked`: the block has args, but its `argsIssues()` found errors in them, so it must not run.
12
- * `errors` is never empty.
13
+ * `errors` is never empty; `issues` holds every issue found, warnings included.
13
14
  * - `absent`: the block has no args, because `args()` threw or returned nothing.
14
15
  */
15
16
  export type DerivedArgs =
16
- | { readonly type: "runnable"; readonly args: unknown }
17
- | { readonly type: "blocked"; readonly args: unknown; readonly errors: readonly ArgsIssue[] }
17
+ | { readonly type: "runnable"; readonly args: unknown; readonly issues: readonly ArgsIssue[] }
18
+ | {
19
+ readonly type: "blocked";
20
+ readonly args: unknown;
21
+ readonly errors: readonly ArgsIssue[];
22
+ readonly issues: readonly ArgsIssue[];
23
+ }
18
24
  | { readonly type: "absent"; readonly error: Error };
19
25
 
26
+ /**
27
+ * What the prerun args derivation of a block with model API version 2 made of the block's storage.
28
+ *
29
+ * - `staged`: the block has prerun args and is staged with them. `issues` holds the warnings.
30
+ * - `skipped`: its `prerunArgs()` returned nothing, so the block is not staged.
31
+ * - `blocked`: the issues found in the prerun args (or, for a block without its own
32
+ * `prerunArgs()`, in its args) include errors, so the block is not staged. `error` joins the
33
+ * error messages; `issues` holds every issue found.
34
+ * - `failed`: the lambda that builds the prerun args threw, or the derivation itself failed.
35
+ *
36
+ * Whenever the block is not staged, its staging keeps what an earlier derivation rendered.
37
+ */
38
+ export type DerivedPrerunArgs =
39
+ | { readonly type: "staged"; readonly args: unknown; readonly issues: readonly ArgsIssue[] }
40
+ | { readonly type: "skipped"; readonly issues: readonly ArgsIssue[] }
41
+ | { readonly type: "blocked"; readonly error: string; readonly issues: readonly ArgsIssue[] }
42
+ | { readonly type: "failed"; readonly error: string };
43
+
44
+ /** A reference in a block's args to a block it cannot read from. */
45
+ export type MissingBlockReference = {
46
+ /** The block the reference names. */
47
+ readonly blockId: BlockId;
48
+ /**
49
+ * `unknown-block`: the project has no such block; `not-above`: the block is the referring block
50
+ * itself or below it.
51
+ */
52
+ readonly reason: "unknown-block" | "not-above";
53
+ };
54
+
55
+ /**
56
+ * What keeps a block with model API version 2 from running or from being staged, found by running
57
+ * its args and prerun args derivations on its current storage. Nothing is written.
58
+ */
59
+ export type BlockReadiness = {
60
+ /** What `args()` and `argsIssues()` make of the current storage. */
61
+ readonly args:
62
+ | { readonly type: "runnable" | "blocked"; readonly issues: readonly ArgsIssue[] }
63
+ | { readonly type: "absent"; readonly error: string };
64
+ /** What the block's prerun args derivation makes of the current storage. */
65
+ readonly prerun: DerivedPrerunArgsSummary;
66
+ /** References in the derived args to blocks the block cannot read from. */
67
+ readonly missingReferences: readonly MissingBlockReference[];
68
+ };
69
+
70
+ /** {@link DerivedPrerunArgs} without the args. */
71
+ export type DerivedPrerunArgsSummary =
72
+ | { readonly type: "staged" | "skipped"; readonly issues: readonly ArgsIssue[] }
73
+ | { readonly type: "blocked"; readonly error: string; readonly issues: readonly ArgsIssue[] }
74
+ | { readonly type: "failed"; readonly error: string };
75
+
20
76
  /**
21
77
  * What a block's `inputsValid` field holds: the errors found in the block's current args, and the
22
78
  * fingerprint of the args they were found in. Every args derivation that produces args writes
@@ -55,17 +111,46 @@ export function parseArgsDeriveResult(value: unknown): DerivedArgs {
55
111
  }
56
112
 
57
113
  const error = "error" in value ? value.error : undefined;
114
+ const issues = "issues" in value ? value.issues : undefined;
58
115
  if (error !== undefined) {
59
116
  if (!isString(error)) throw new Error(`Args derivation error is ${typeof error}, not a string`);
60
117
  const args = "args" in value ? value.args : undefined;
61
118
  if (args === undefined) return { type: "absent", error: new Error(error) };
62
- const issues = "issues" in value ? value.issues : undefined;
63
- return { type: "blocked", args, errors: argsErrorsOf(issues, error) };
119
+ const errors = argsErrorsOf(issues, error);
120
+ return { type: "blocked", args, errors, issues: issuesWithErrors(issues, errors) };
64
121
  }
65
122
 
66
123
  const args = "value" in value ? value.value : undefined;
67
124
  if (args === undefined) return { type: "absent", error: new Error("args() returned no args") };
68
- return { type: "runnable", args };
125
+ return { type: "runnable", args, issues: readableIssues(issues) };
126
+ }
127
+
128
+ /**
129
+ * Reads the result of the model's `__pl_prerunArgs_derive` callback.
130
+ *
131
+ * A model built before args issues returns `{ value }` for prerun args and `{ error }` for none.
132
+ * A newer model adds the issues, and returns `{ error, issues }` when they include errors. An
133
+ * `{ error }` without issues is a lambda that threw.
134
+ *
135
+ * @throws when `value` is not an object, or carries an `error` that is not a string
136
+ */
137
+ export function parsePrerunArgsDeriveResult(value: unknown): DerivedPrerunArgs {
138
+ if (typeof value !== "object" || value === null) {
139
+ throw new Error(`Prerun args derivation returned ${value === null ? "null" : typeof value}`);
140
+ }
141
+
142
+ const error = "error" in value ? value.error : undefined;
143
+ const issues = "issues" in value ? value.issues : undefined;
144
+ if (error !== undefined) {
145
+ if (!isString(error))
146
+ throw new Error(`Prerun args derivation error is ${typeof error}, not a string`);
147
+ if (issues === undefined) return { type: "failed", error };
148
+ return { type: "blocked", error, issues: readableIssues(issues) };
149
+ }
150
+
151
+ const args = "value" in value ? value.value : undefined;
152
+ if (args === undefined) return { type: "skipped", issues: readableIssues(issues) };
153
+ return { type: "staged", args, issues: readableIssues(issues) };
69
154
  }
70
155
 
71
156
  /** The args an args derivation produced; `undefined` when it produced none. */
@@ -192,3 +277,22 @@ function parseArgsErrorsRecord(value: unknown): ArgsErrorsRecord {
192
277
  function isError(issue: ArgsIssue): boolean {
193
278
  return issue.severity === "error";
194
279
  }
280
+
281
+ /** The issues of a derivation result; none when they cannot be read. */
282
+ function readableIssues(issues: unknown): readonly ArgsIssue[] {
283
+ if (issues === undefined) return [];
284
+ try {
285
+ return parseArgsIssues(issues);
286
+ } catch {
287
+ return [];
288
+ }
289
+ }
290
+
291
+ /**
292
+ * Every issue of a derivation whose `argsIssues()` found errors: the readable issues when they
293
+ * hold the errors, otherwise the errors that stood in for them.
294
+ */
295
+ function issuesWithErrors(issues: unknown, errors: readonly ArgsIssue[]): readonly ArgsIssue[] {
296
+ const readable = readableIssues(issues);
297
+ return readable.some(isError) ? readable : [...errors, ...readable];
298
+ }
@@ -0,0 +1,194 @@
1
+ import { beforeAll, describe, expect, test } from "vitest";
2
+ import { getQuickJS } from "quickjs-emscripten";
3
+ import { asBlockId } from "@milaboratories/pl-model-common";
4
+ import { ModelAPIVersionMismatchError } from "@milaboratories/pl-errors";
5
+ import type { BlockConfig } from "@platforma-sdk/model";
6
+ import { BlockStorageFacadeCallbacks } from "@platforma-sdk/model";
7
+ import { ProjectHelper } from "./project_helper";
8
+ import { blockParamsModel } from "./block_params_model";
9
+
10
+ /**
11
+ * `blockParamsModel` — `init(params)` and `templateParams(data)` of a block's model, run in the
12
+ * VM. The model is hand-written, as in `project_helper_params_init.test.ts`: what is driven here
13
+ * is what crosses the boundary (the versioned data out of the storage `init` builds, the data
14
+ * wrapped into a storage for `templateParams`), not the SDK behind the callbacks.
15
+ */
16
+
17
+ const DERIVE = BlockStorageFacadeCallbacks.InitializationParamsDerive;
18
+ const INIT = BlockStorageFacadeCallbacks.StorageInitialFromParams;
19
+ const APPLY = BlockStorageFacadeCallbacks.StorageApplyParams;
20
+
21
+ /** `templateParams`: the threshold, nothing of the view state. */
22
+ const deriveBody = `(storageJson) => {
23
+ const storage = JSON.parse(storageJson);
24
+ return { value: { threshold: storage.__data.threshold, version: storage.__dataVersion } };
25
+ }`;
26
+
27
+ /** `init`: the kind accepts a numeric threshold only; the data also holds view state. */
28
+ const initBody = `(paramsJson) => {
29
+ const params = JSON.parse(paramsJson);
30
+ if (typeof params.threshold !== "number") return { error: "threshold must be a number" };
31
+ return {
32
+ storageJson: JSON.stringify({
33
+ __pl_a7f3e2b9__: "v1",
34
+ __dataVersion: "v3",
35
+ __data: { threshold: params.threshold, view: { sort: "asc" } },
36
+ __pluginRegistry: {},
37
+ __plugins: {},
38
+ }),
39
+ };
40
+ }`;
41
+
42
+ /**
43
+ * `applyParams`: the threshold onto the data, the rest kept; the kind's check as in `init`; data
44
+ * at another version than v3 refused.
45
+ */
46
+ const applyBody = `(storageJson, paramsJson) => {
47
+ const storage = JSON.parse(storageJson);
48
+ const params = JSON.parse(paramsJson);
49
+ if (storage.__dataVersion !== "v3") return { error: "the data waits for a migration" };
50
+ if (typeof params.threshold !== "number") return { error: "threshold must be a number" };
51
+ return {
52
+ storageJson: JSON.stringify({
53
+ ...storage,
54
+ __data: { ...storage.__data, threshold: params.threshold },
55
+ }),
56
+ };
57
+ }`;
58
+
59
+ function configWith(callbacks: Record<string, string>): BlockConfig {
60
+ const code = Object.entries(callbacks)
61
+ .map(([h, body]) => `globalThis.cfgRenderCtx.callbackRegistry[${JSON.stringify(h)}] = ${body};`)
62
+ .join("\n");
63
+ return {
64
+ configVersion: 4,
65
+ modelAPIVersion: 2,
66
+ sdkVersion: "1.0.0",
67
+ renderingMode: "Heavy",
68
+ sections: { __renderLambda: true, handle: "sections" },
69
+ outputs: {},
70
+ code: { type: "plain", content: code },
71
+ blockLifecycleCallbacks: Object.fromEntries(
72
+ Object.keys(callbacks).map((handle) => [handle, { __renderLambda: true, handle }]),
73
+ ),
74
+ };
75
+ }
76
+
77
+ /** A model of block API 1: no storage facade, no callbacks. */
78
+ const V1_CONFIG: BlockConfig = {
79
+ configVersion: 3,
80
+ modelAPIVersion: 1,
81
+ sdkVersion: "1.0.0",
82
+ renderingMode: "Heavy",
83
+ initialArgs: {},
84
+ initialUiState: {},
85
+ inputsValid: { __renderLambda: true, handle: "inputsValid" },
86
+ sections: { __renderLambda: true, handle: "sections" },
87
+ outputs: {},
88
+ };
89
+
90
+ const blockId = asBlockId("b1");
91
+ let helper: ProjectHelper;
92
+
93
+ beforeAll(async () => {
94
+ helper = new ProjectHelper(await getQuickJS());
95
+ });
96
+
97
+ describe("blockParamsModel", () => {
98
+ test("init gives the data and its version, without the storage around it", () => {
99
+ const model = blockParamsModel(
100
+ helper,
101
+ blockId,
102
+ configWith({ [DERIVE]: deriveBody, [INIT]: initBody }),
103
+ );
104
+ expect(model.givesParams).toBe(true);
105
+ expect(model.dataOf({ threshold: 2 })).toEqual({
106
+ value: { dataVersion: "v3", data: { threshold: 2, view: { sort: "asc" } } },
107
+ });
108
+ });
109
+
110
+ test("templateParams sees the given data at the given version", () => {
111
+ const model = blockParamsModel(
112
+ helper,
113
+ blockId,
114
+ configWith({ [DERIVE]: deriveBody, [INIT]: initBody }),
115
+ );
116
+ expect(
117
+ model.paramsOf({ dataVersion: "v3", data: { threshold: 5, view: { sort: "desc" } } }),
118
+ ).toEqual({ value: { threshold: 5, version: "v3" } });
119
+ });
120
+
121
+ test("params the kind rejects come back as an error in the block's words", () => {
122
+ const model = blockParamsModel(
123
+ helper,
124
+ blockId,
125
+ configWith({ [DERIVE]: deriveBody, [INIT]: initBody }),
126
+ );
127
+ const result = model.dataOf({ threshold: "high" });
128
+ expect(result.error?.message).toContain("threshold must be a number");
129
+ });
130
+
131
+ test("a model without the callbacks gives no params", () => {
132
+ const model = blockParamsModel(helper, blockId, configWith({}));
133
+ expect(model.givesParams).toBe(false);
134
+ expect(model.paramsOf({ dataVersion: "v1", data: {} }).error?.message).toContain(
135
+ "cannot be written to a template",
136
+ );
137
+ expect(model.dataOf({}).error).toBeDefined();
138
+ });
139
+
140
+ test("a model with only one of the two callbacks gives no params either", () => {
141
+ expect(
142
+ blockParamsModel(helper, blockId, configWith({ [DERIVE]: deriveBody })).givesParams,
143
+ ).toBe(false);
144
+ });
145
+
146
+ test("applyParams puts the params onto the given data and keeps the rest", () => {
147
+ const model = blockParamsModel(
148
+ helper,
149
+ blockId,
150
+ configWith({ [DERIVE]: deriveBody, [INIT]: initBody, [APPLY]: applyBody }),
151
+ );
152
+ expect(model.appliesParams).toBe(true);
153
+ expect(
154
+ model.applyParams(
155
+ { dataVersion: "v3", data: { threshold: 5, view: { sort: "desc" } } },
156
+ { threshold: 2 },
157
+ ),
158
+ ).toEqual({ value: { dataVersion: "v3", data: { threshold: 2, view: { sort: "desc" } } } });
159
+ });
160
+
161
+ test("applyParams answers the block's refusals as errors", () => {
162
+ const model = blockParamsModel(
163
+ helper,
164
+ blockId,
165
+ configWith({ [DERIVE]: deriveBody, [INIT]: initBody, [APPLY]: applyBody }),
166
+ );
167
+ const data = { dataVersion: "v3", data: { threshold: 5 } };
168
+ expect(model.applyParams(data, { threshold: "high" }).error?.message).toContain(
169
+ "threshold must be a number",
170
+ );
171
+ expect(
172
+ model.applyParams({ ...data, dataVersion: "v2" }, { threshold: 1 }).error?.message,
173
+ ).toContain("waits for a migration");
174
+ });
175
+
176
+ test("a model without the applyParams callback does not apply params", () => {
177
+ const model = blockParamsModel(
178
+ helper,
179
+ blockId,
180
+ configWith({ [DERIVE]: deriveBody, [INIT]: initBody }),
181
+ );
182
+ expect(model.givesParams).toBe(true);
183
+ expect(model.appliesParams).toBe(false);
184
+ expect(
185
+ model.applyParams({ dataVersion: "v3", data: {} }, { threshold: 1 }).error?.message,
186
+ ).toContain("does not put params onto its data itself");
187
+ });
188
+
189
+ test("a block on block API 1 is refused", () => {
190
+ expect(() => blockParamsModel(helper, blockId, V1_CONFIG)).toThrow(
191
+ ModelAPIVersionMismatchError,
192
+ );
193
+ });
194
+ });
@@ -0,0 +1,117 @@
1
+ import type { BlockId } from "@milaboratories/pl-model-common";
2
+ import { ModelAPIVersionMismatchError } from "@milaboratories/pl-errors";
3
+ import type { BlockConfig, ResultOrError } from "@platforma-sdk/model";
4
+ import {
5
+ BLOCK_STORAGE_FACADE_VERSION,
6
+ BlockStorageFacadeCallbacks,
7
+ createBlockStorage,
8
+ isBlockStorage,
9
+ } from "@platforma-sdk/model";
10
+ import type { ProjectHelper } from "./project_helper";
11
+
12
+ /** A block's data with the version of the block's data model it is written in. */
13
+ export type VersionedBlockData = {
14
+ dataVersion: string;
15
+ data: unknown;
16
+ };
17
+
18
+ /**
19
+ * A block's model as functions between its kind's initialization params and its data: the data
20
+ * model's `init(params)`, its inverse `templateParams(data)` and, when the block declares it,
21
+ * `applyParams(data, params)`. Each runs the block's own model code in the VM, each call on its
22
+ * own; no block is created and nothing is read from or written to the project.
23
+ */
24
+ export interface BlockParamsModel {
25
+ /**
26
+ * Whether the model has both functions. A model built before blocks gave params has neither
27
+ * callback; its calls answer with an error.
28
+ */
29
+ readonly givesParams: boolean;
30
+
31
+ /**
32
+ * `templateParams(data)`: the params the block's model derives from `data`. The data is not
33
+ * migrated first (the SDK does not), so it should be in the version {@link dataOf} produces.
34
+ */
35
+ paramsOf(data: VersionedBlockData): ResultOrError<unknown>;
36
+
37
+ /**
38
+ * `init(params)`: the data the block's model builds from `params`, after the kind's parser has
39
+ * accepted them, with the version of the data model it is in. References in `params` are taken
40
+ * as they are: they name blocks of this project.
41
+ */
42
+ dataOf(params: unknown): ResultOrError<VersionedBlockData>;
43
+
44
+ /**
45
+ * Whether the block declares `applyParams`, putting its params onto live data
46
+ * itself. For such a block {@link dataOf} is `applyParams(defaults, params)`.
47
+ */
48
+ readonly appliesParams: boolean;
49
+
50
+ /**
51
+ * `applyParams(data, params)`: `data` with `params` put onto it by the block's own model, after
52
+ * the kind's parser has accepted them, with the version of the data model it is in. The model
53
+ * refuses data at another version than its current one, the version {@link dataOf} produces.
54
+ * A model that does not apply params ({@link appliesParams} false) answers with an error.
55
+ */
56
+ applyParams(data: VersionedBlockData, params: unknown): ResultOrError<VersionedBlockData>;
57
+ }
58
+
59
+ /** No template entries: live params already name the blocks of the project. */
60
+ const NO_BLOCK_IDS: ReadonlyMap<string, string> = new Map();
61
+
62
+ /**
63
+ * The {@link BlockParamsModel} of block `blockId` with model `config`.
64
+ *
65
+ * @throws {ModelAPIVersionMismatchError} when the block is not on BlockModelV3: such a model has
66
+ * no storage facade and no params
67
+ */
68
+ export function blockParamsModel(
69
+ helper: ProjectHelper,
70
+ blockId: BlockId,
71
+ config: BlockConfig,
72
+ ): BlockParamsModel {
73
+ if (config.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION)
74
+ throw new ModelAPIVersionMismatchError(
75
+ blockId,
76
+ BLOCK_STORAGE_FACADE_VERSION,
77
+ config.modelAPIVersion,
78
+ );
79
+ const callbacks = config.blockLifecycleCallbacks;
80
+ return {
81
+ givesParams:
82
+ callbacks[BlockStorageFacadeCallbacks.InitializationParamsDerive] !== undefined &&
83
+ callbacks[BlockStorageFacadeCallbacks.StorageInitialFromParams] !== undefined,
84
+
85
+ paramsOf: ({ dataVersion, data }) =>
86
+ helper.deriveTemplateParamsFromStorage(
87
+ config,
88
+ JSON.stringify(createBlockStorage(data, dataVersion)),
89
+ ),
90
+
91
+ dataOf: (params) => {
92
+ const storage = helper.getInitialStorageFromParamsInVM(config, params, NO_BLOCK_IDS);
93
+ if (storage.error !== undefined) return storage;
94
+ return parseVersionedData(storage.value);
95
+ },
96
+
97
+ appliesParams: callbacks[BlockStorageFacadeCallbacks.StorageApplyParams] !== undefined,
98
+
99
+ applyParams: ({ dataVersion, data }, params) => {
100
+ const storage = helper.applyParamsInVM(
101
+ config,
102
+ JSON.stringify(createBlockStorage(data, dataVersion)),
103
+ params,
104
+ );
105
+ if (storage.error !== undefined) return storage;
106
+ return parseVersionedData(storage.value);
107
+ },
108
+ };
109
+ }
110
+
111
+ /** The data and its version out of a block storage the model built, as JSON text. */
112
+ function parseVersionedData(storageJson: string): ResultOrError<VersionedBlockData> {
113
+ const storage: unknown = JSON.parse(storageJson);
114
+ if (!isBlockStorage(storage) || typeof storage.__dataVersion !== "string")
115
+ return { error: new Error("The block's model built its data in an unknown storage format") };
116
+ return { value: { dataVersion: storage.__dataVersion, data: storage.__data } };
117
+ }