@platforma-sdk/model 1.86.5 → 1.88.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 (76) hide show
  1. package/dist/block_api_v3.d.ts +9 -0
  2. package/dist/block_api_v3.d.ts.map +1 -1
  3. package/dist/block_model.cjs +89 -9
  4. package/dist/block_model.cjs.map +1 -1
  5. package/dist/block_model.d.ts +81 -19
  6. package/dist/block_model.d.ts.map +1 -1
  7. package/dist/block_model.js +89 -9
  8. package/dist/block_model.js.map +1 -1
  9. package/dist/block_storage_callbacks.cjs +128 -25
  10. package/dist/block_storage_callbacks.cjs.map +1 -1
  11. package/dist/block_storage_callbacks.js +129 -26
  12. package/dist/block_storage_callbacks.js.map +1 -1
  13. package/dist/block_storage_facade.cjs.map +1 -1
  14. package/dist/block_storage_facade.d.ts +37 -4
  15. package/dist/block_storage_facade.d.ts.map +1 -1
  16. package/dist/block_storage_facade.js.map +1 -1
  17. package/dist/columns/column_providers/providers.cjs +2 -10
  18. package/dist/columns/column_providers/providers.cjs.map +1 -1
  19. package/dist/columns/column_providers/providers.d.ts.map +1 -1
  20. package/dist/columns/column_providers/providers.js +3 -11
  21. package/dist/columns/column_providers/providers.js.map +1 -1
  22. package/dist/columns/column_recipes/index.cjs +2 -2
  23. package/dist/columns/column_recipes/index.cjs.map +1 -1
  24. package/dist/columns/column_recipes/index.d.ts +2 -3
  25. package/dist/columns/column_recipes/index.d.ts.map +1 -1
  26. package/dist/columns/column_recipes/index.js +2 -2
  27. package/dist/columns/column_recipes/index.js.map +1 -1
  28. package/dist/columns/column_values.cjs +126 -0
  29. package/dist/columns/column_values.cjs.map +1 -0
  30. package/dist/columns/column_values.d.ts +65 -0
  31. package/dist/columns/column_values.d.ts.map +1 -0
  32. package/dist/columns/column_values.js +124 -0
  33. package/dist/columns/column_values.js.map +1 -0
  34. package/dist/columns/data_column.cjs +12 -42
  35. package/dist/columns/data_column.cjs.map +1 -1
  36. package/dist/columns/data_column.d.ts +10 -26
  37. package/dist/columns/data_column.d.ts.map +1 -1
  38. package/dist/columns/data_column.js +13 -42
  39. package/dist/columns/data_column.js.map +1 -1
  40. package/dist/columns/index.cjs +4 -1
  41. package/dist/columns/index.d.ts +3 -2
  42. package/dist/columns/index.js +3 -2
  43. package/dist/index.cjs +6 -1
  44. package/dist/index.d.ts +4 -2
  45. package/dist/index.js +4 -2
  46. package/dist/package.cjs +1 -1
  47. package/dist/package.js +1 -1
  48. package/dist/pframe_utils/column_value_options.cjs +85 -0
  49. package/dist/pframe_utils/column_value_options.cjs.map +1 -0
  50. package/dist/pframe_utils/column_value_options.d.ts +14 -0
  51. package/dist/pframe_utils/column_value_options.d.ts.map +1 -0
  52. package/dist/pframe_utils/column_value_options.js +85 -0
  53. package/dist/pframe_utils/column_value_options.js.map +1 -0
  54. package/dist/pframe_utils/index.cjs +2 -0
  55. package/dist/pframe_utils/index.cjs.map +1 -1
  56. package/dist/pframe_utils/index.d.ts +2 -1
  57. package/dist/pframe_utils/index.d.ts.map +1 -1
  58. package/dist/pframe_utils/index.js +2 -1
  59. package/dist/pframe_utils/index.js.map +1 -1
  60. package/package.json +7 -7
  61. package/src/args_issues.test.ts +532 -0
  62. package/src/block_api_v3.ts +10 -0
  63. package/src/block_model.ts +146 -32
  64. package/src/block_storage_callbacks.ts +174 -43
  65. package/src/block_storage_facade.ts +36 -6
  66. package/src/columns/column_providers/providers.ts +3 -15
  67. package/src/columns/column_recipes/column_recipes.test.ts +11 -15
  68. package/src/columns/column_recipes/index.ts +2 -3
  69. package/src/columns/column_values.test.ts +183 -0
  70. package/src/columns/column_values.ts +194 -0
  71. package/src/columns/data_column.test.ts +13 -14
  72. package/src/columns/data_column.ts +12 -41
  73. package/src/columns/index.ts +1 -0
  74. package/src/pframe_utils/column_value_options.test.ts +126 -0
  75. package/src/pframe_utils/column_value_options.ts +111 -0
  76. package/src/pframe_utils/index.ts +1 -0
@@ -50,7 +50,7 @@
50
50
  import type { MutateStoragePayload } from "./block_storage";
51
51
  import type { ConfigRenderLambda } from "./bconfig";
52
52
  import { createRenderLambda, tryRegisterCallback } from "./internal";
53
- import type { StringifiedJson } from "@milaboratories/pl-model-common";
53
+ import type { ArgsIssue, StringifiedJson } from "@milaboratories/pl-model-common";
54
54
 
55
55
  // =============================================================================
56
56
  // Facade Version
@@ -170,23 +170,53 @@ export interface BlockStorageFacade {
170
170
 
171
171
  /**
172
172
  * Derive args from storage.
173
- * Called to get block configuration args from storage.
173
+ * Called to get block configuration args from storage, and whether the block may run them.
174
+ *
175
+ * A middle layer that predates args issues reads only `error` and `value`, and each variant
176
+ * means the same to it as before: `value` is runnable args, `error` is no args. A block built
177
+ * with an SDK that predates args issues returns `{ error }` or `{ value }` with no `issues`.
178
+ *
174
179
  * @param storageJson - Storage as JSON string
175
- * @returns Args derivation result - either error or derived value
180
+ * @returns One of:
181
+ * - `{ error }`: `args()` threw, so there are no args;
182
+ * - `{ error, args, issues }`: args were built, but the block's `argsIssues()` found errors in
183
+ * them, so the block must not run; `error` joins the error messages, `issues` lists every
184
+ * issue;
185
+ * - `{ value, issues }`: args the block may run; `issues` holds the warnings.
176
186
  */
177
187
  [BlockStorageFacadeCallbacks.ArgsDerive]: (
178
188
  storageJson: StringifiedJson,
179
- ) => { error: string } | { error?: undefined; value: unknown };
189
+ ) =>
190
+ | { error: string }
191
+ | { error: string; args: unknown; issues: ArgsIssue[] }
192
+ | { error?: undefined; value: unknown; issues: ArgsIssue[] };
180
193
 
181
194
  /**
182
195
  * Derive prerunArgs from storage.
183
196
  * Called to get prerun args; falls back to args callback if not registered.
197
+ *
198
+ * A block with its own prerunArgs is staged with them unless its `prerunArgsIssues()` finds errors
199
+ * in them. A block without its own prerunArgs is staged with its args unless its `argsIssues()`
200
+ * finds errors in them.
201
+ *
202
+ * A middle layer that predates args issues reads only `error` and `value`: `value` is args to
203
+ * stage, `error` skips staging. A block built with an SDK that predates args issues returns
204
+ * `{ error }` or `{ value }` with no `issues`.
205
+ *
184
206
  * @param storageJson - Storage as JSON string
185
- * @returns Args derivation result - either error or derived value
207
+ * @returns One of:
208
+ * - `{ error }`: the lambda building the prerun args threw;
209
+ * - `{ error, issues }`: prerun args were built, but errors were found in them, so the block
210
+ * is not staged; `error` joins the error messages, `issues` lists every issue;
211
+ * - `{ value, issues }`: args to stage, `undefined` to skip staging; `issues` holds the
212
+ * warnings.
186
213
  */
187
214
  [BlockStorageFacadeCallbacks.PrerunArgsDerive]: (
188
215
  storageJson: StringifiedJson,
189
- ) => { error: string } | { error?: undefined; value: unknown };
216
+ ) =>
217
+ | { error: string }
218
+ | { error: string; issues: ArgsIssue[] }
219
+ | { error?: undefined; value: unknown; issues: ArgsIssue[] };
190
220
 
191
221
  /**
192
222
  * Get initial storage JSON for new blocks.
@@ -1,13 +1,12 @@
1
1
  import {
2
2
  AccessorEntriesProvider,
3
3
  ResultPoolEntriesProvider,
4
- type LeafEntry,
5
4
  type PColumn,
6
5
  type PObjectId,
7
6
  type UpstreamBlockCtx,
8
7
  } from "@milaboratories/pl-model-common";
9
8
  import { AccessorHandle, PColumnDataUniversal, TreeNodeAccessor } from "../../render";
10
- import { ColumnAbsentError, DataColumn, DataColumnRecipe } from "../data_column";
9
+ import { DataColumn, DataColumnRecipe } from "../data_column";
11
10
  import { getCfgRenderCtx } from "../../internal";
12
11
  import { isNil } from "es-toolkit";
13
12
  import { LRUCache } from "lru-cache";
@@ -130,7 +129,7 @@ export class AccessorColumnsProviderImpl
130
129
 
131
130
  getColumns(): DataColumnRecipe<PObjectId>[] {
132
131
  if (this.cachedColumns !== undefined) return this.cachedColumns;
133
- return (this.cachedColumns = Array.from(this.entries.values(), columnUnlessAbsent).filter(
132
+ return (this.cachedColumns = Array.from(this.entries.values(), DataColumn.fromAccessor).filter(
134
133
  (column) => column !== undefined,
135
134
  ));
136
135
  }
@@ -176,7 +175,7 @@ export class ResultPoolColumnsProviderImpl
176
175
  if (this.cachedColumns !== undefined) return this.cachedColumns;
177
176
  return (this.cachedColumns = Array.from(
178
177
  this.getPObjectEntries().values(),
179
- columnUnlessAbsent,
178
+ DataColumn.fromAccessor,
180
179
  ).filter((column) => column !== undefined));
181
180
  }
182
181
  }
@@ -184,17 +183,6 @@ export class ResultPoolColumnsProviderImpl
184
183
  /** Public type alias — value of the same name is the memoised factory above. */
185
184
  export type ResultPoolColumnsProvider = ResultPoolColumnsProviderImpl;
186
185
 
187
- function columnUnlessAbsent(
188
- entry: LeafEntry<TreeNodeAccessor>,
189
- ): DataColumnRecipe<PObjectId> | undefined {
190
- try {
191
- return DataColumn.fromAccessor(entry);
192
- } catch (error) {
193
- if (error instanceof ColumnAbsentError) return undefined;
194
- throw error;
195
- }
196
- }
197
-
198
186
  function hashRawPool(rawPool: ReadonlyArray<UpstreamBlockCtx<AccessorHandle>>): string {
199
187
  return rawPool
200
188
  .map(
@@ -24,7 +24,6 @@ import { ColumnDiscoveredRecipe } from "./column_discovered_recipe";
24
24
  import { ColumnOverriddenRecipe } from "./column_overrided_recipe";
25
25
  import { ColumnFilteredRecipe } from "./column_filtered_recipe";
26
26
  import { ColumnRecipe } from "./index";
27
- import { ColumnAbsentError } from "../data_column";
28
27
  import type { ColumnFieldStatus } from "./types";
29
28
  import { installStubRegistry } from "../__test_helpers__/stub_registry";
30
29
  import { throwError } from "@milaboratories/helpers";
@@ -403,11 +402,9 @@ describe("ColumnDiscoveredRecipe", () => {
403
402
  ).toThrow(/Unsupported ColumnRecipe id variant/);
404
403
  });
405
404
 
406
- test("fromKey propagates ColumnAbsentError from a referenced absent column", () => {
407
- // Default ctx mock has no providers → empty registry → leaf id is provably
408
- // absent. The leaf-level throw inside `Column(uniId, opts)` propagates
409
- // unchanged through `fromKey`.
410
- expect(() => ColumnDiscoveredRecipe.fromKey(trivialKey)).toThrow(ColumnAbsentError);
405
+ test("fromKey returns undefined when a referenced column is absent", () => {
406
+ // Default ctx mock has no providers → empty registry → leaf id is absent.
407
+ expect(ColumnDiscoveredRecipe.fromKey(trivialKey)).toBeUndefined();
411
408
  });
412
409
 
413
410
  test("id is the canonical stringify(ColumnDiscoveredKey)", () => {
@@ -611,10 +608,9 @@ describe("ColumnRecipe.getStatus (top-level dispatcher)", () => {
611
608
  });
612
609
  });
613
610
 
614
- describe("ColumnRecipe(id) throw propagation on absent leaves", () => {
615
- test("filtered id over an absent source throws ColumnAbsentError", () => {
616
- // Empty registry with isFinal=true → leaf is provably absent → throw
617
- // propagates through the Filtered dispatch branch.
611
+ describe("ColumnRecipe(id) over absent leaves", () => {
612
+ test("filtered id over an absent source returns undefined", () => {
613
+ // Empty registry with isFinal=true → leaf is absent.
618
614
  const ctx = makeCtx();
619
615
  (globalThis as { cfgRenderCtx?: unknown }).cfgRenderCtx = ctx;
620
616
  installStubRegistry(ctx, {}, { isFinal: true });
@@ -622,10 +618,10 @@ describe("ColumnRecipe(id) throw propagation on absent leaves", () => {
622
618
  source: baseLeaf,
623
619
  axisFilters: [],
624
620
  });
625
- expect(() => ColumnRecipe(id)).toThrow(ColumnAbsentError);
621
+ expect(ColumnRecipe(id)).toBeUndefined();
626
622
  });
627
623
 
628
- test("overrided id over an absent source throws ColumnAbsentError", () => {
624
+ test("overrided id over an absent source returns undefined", () => {
629
625
  const ctx = makeCtx();
630
626
  (globalThis as { cfgRenderCtx?: unknown }).cfgRenderCtx = ctx;
631
627
  installStubRegistry(ctx, {}, { isFinal: true });
@@ -633,15 +629,15 @@ describe("ColumnRecipe(id) throw propagation on absent leaves", () => {
633
629
  source: baseLeaf,
634
630
  specOverrides: overrides({}),
635
631
  });
636
- expect(() => ColumnRecipe(id)).toThrow(ColumnAbsentError);
632
+ expect(ColumnRecipe(id)).toBeUndefined();
637
633
  });
638
634
 
639
- test("discovered id over an absent hit throws ColumnAbsentError", () => {
635
+ test("discovered id over an absent hit returns undefined", () => {
640
636
  const ctx = makeCtx();
641
637
  (globalThis as { cfgRenderCtx?: unknown }).cfgRenderCtx = ctx;
642
638
  installStubRegistry(ctx, {}, { isFinal: true });
643
639
  const id = stringifyColumnDiscoveredId({ column: baseLeaf });
644
- expect(() => ColumnRecipe(id)).toThrow(ColumnAbsentError);
640
+ expect(ColumnRecipe(id)).toBeUndefined();
645
641
  });
646
642
  });
647
643
 
@@ -19,7 +19,6 @@ import type {
19
19
  } from "./types";
20
20
 
21
21
  export type { ColumnFieldStatus, ColumnRecipeId, ColumnResolutionStatus, SpecQuery } from "./types";
22
- export { ColumnAbsentError } from "../data_column";
23
22
  export { ColumnDiscoveredRecipe } from "./column_discovered_recipe";
24
23
  export { ColumnFilteredRecipe } from "./column_filtered_recipe";
25
24
  export { ColumnOverriddenRecipe } from "./column_overrided_recipe";
@@ -90,8 +89,8 @@ function ColumnRecipeBuild(
90
89
  * Resolution status counterpart to {@link ColumnRecipeBuild}. Dispatches on
91
90
  * the parsed id shape to the matching `getStatusBy*` static — never
92
91
  * constructs the recipe. Use this at boundaries (resolver, filter/sort
93
- * targets) to throw early on `absent` instead of silently producing an empty
94
- * recipe via {@link ColumnRecipeBuild}.
92
+ * targets) to tell an `absent` column from a `resolving` one: the recipe
93
+ * factory returns `undefined` for both.
95
94
  */
96
95
  function ColumnRecipeGetStatus(
97
96
  id: ColumnUniversalId,
@@ -0,0 +1,183 @@
1
+ import { afterEach, describe, expect, test, vi } from "vitest";
2
+ import {
3
+ createColumnValueId,
4
+ createGlobalPObjectId,
5
+ type PColumn,
6
+ type PColumnValues,
7
+ type PFrameHandle,
8
+ } from "@milaboratories/pl-model-common";
9
+ import type { GlobalCfgRenderCtx } from "../render/internal";
10
+ import { ColumnRecipe } from "./column_recipes";
11
+ import {
12
+ createColumnValueOptions,
13
+ deriveColumnValueOptions,
14
+ deriveLabelledColumnValueOptions,
15
+ } from "./column_values";
16
+
17
+ afterEach(() => {
18
+ vi.restoreAllMocks();
19
+ });
20
+
21
+ describe("deriveColumnValueOptions", () => {
22
+ test("offers each distinct value once, in natural order of labels", () => {
23
+ expect(deriveColumnValueOptions(COLUMN_ID, ["R10", "R2", "R10", "Library"])).toEqual([
24
+ option("Library"),
25
+ option("R2"),
26
+ option("R10"),
27
+ ]);
28
+ });
29
+
30
+ test("does not offer an empty value", () => {
31
+ expect(deriveColumnValueOptions(COLUMN_ID, ["", "R1"])).toEqual([option("R1")]);
32
+ });
33
+
34
+ test("orders digit runs as numbers and text case-insensitively", () => {
35
+ const labels = deriveColumnValueOptions(COLUMN_ID, ["r10", "R009", "b", "A"]).map(
36
+ (o) => o.label,
37
+ );
38
+ expect(labels).toEqual(["A", "b", "R009", "r10"]);
39
+ });
40
+
41
+ test("works in a runtime without Intl", async () => {
42
+ vi.resetModules();
43
+ vi.stubGlobal("Intl", undefined);
44
+ try {
45
+ const fresh = await import("./column_values");
46
+ const labels = fresh.deriveColumnValueOptions(COLUMN_ID, ["R10", "R2"]).map((o) => o.label);
47
+ expect(labels).toEqual(["R2", "R10"]);
48
+ } finally {
49
+ vi.unstubAllGlobals();
50
+ }
51
+ });
52
+ });
53
+
54
+ describe("deriveLabelledColumnValueOptions", () => {
55
+ test("labels each value by the label of its first row, in natural order of labels", () => {
56
+ const rows = [
57
+ { value: "s2", label: "Donor 10" },
58
+ { value: "s1", label: "Donor 2" },
59
+ { value: "s2", label: "Donor 11" },
60
+ ];
61
+ expect(deriveLabelledColumnValueOptions(COLUMN_ID, rows)).toEqual([
62
+ option("s1", "Donor 2"),
63
+ option("s2", "Donor 10"),
64
+ ]);
65
+ });
66
+
67
+ test("leaves a value with an empty label to label itself, and offers no empty value", () => {
68
+ const rows = [
69
+ { value: "s1", label: "" },
70
+ { value: "", label: "Nobody" },
71
+ ];
72
+ expect(deriveLabelledColumnValueOptions(COLUMN_ID, rows)).toEqual([option("s1")]);
73
+ });
74
+ });
75
+
76
+ describe("createColumnValueOptions", () => {
77
+ test("holds a frame of the value column while it is there", () => {
78
+ vi.spyOn(ColumnRecipe, "getStatus").mockReturnValue("present");
79
+ const ctx = renderCtx();
80
+
81
+ expect(createColumnValueOptions({ valueColumn: COLUMN_ID }, { ctx })).toEqual({
82
+ type: "present",
83
+ valueColumn: COLUMN_ID,
84
+ frame: FRAME,
85
+ frameColumns: { value: COLUMN_ID, label: null },
86
+ });
87
+ expect(ctx.createPFrame).toHaveBeenCalledWith([COLUMN_ID]);
88
+ });
89
+
90
+ test("puts the label column into the frame beside the value column", () => {
91
+ vi.spyOn(ColumnRecipe, "getStatus").mockReturnValue("present");
92
+ const ctx = renderCtx();
93
+
94
+ expect(
95
+ createColumnValueOptions({ valueColumn: COLUMN_ID, labelColumn: LABEL_ID }, { ctx }),
96
+ ).toEqual({
97
+ type: "present",
98
+ valueColumn: COLUMN_ID,
99
+ frame: FRAME,
100
+ frameColumns: { value: COLUMN_ID, label: LABEL_ID },
101
+ });
102
+ expect(ctx.createPFrame).toHaveBeenCalledWith([COLUMN_ID, LABEL_ID]);
103
+ });
104
+
105
+ test("takes a materialised column as it is", () => {
106
+ const ctx = renderCtx();
107
+ const column: PColumn<PColumnValues> = {
108
+ id: COLUMN_ID,
109
+ spec: {
110
+ kind: "PColumn",
111
+ name: "pl7.app/metadata",
112
+ valueType: "String",
113
+ axesSpec: [{ name: "pl7.app/sampleId", type: "String" }],
114
+ },
115
+ data: [{ key: ["s1"], val: "R1" }],
116
+ };
117
+
118
+ expect(createColumnValueOptions({ valueColumn: column }, { ctx })).toMatchObject({
119
+ type: "present",
120
+ valueColumn: COLUMN_ID,
121
+ frameColumns: { value: COLUMN_ID, label: null },
122
+ });
123
+ expect(ctx.createPFrame).toHaveBeenCalledWith([column]);
124
+ });
125
+
126
+ test("is resolving while the value column or the label column is", () => {
127
+ vi.spyOn(ColumnRecipe, "getStatus").mockReturnValue("resolving");
128
+ expect(createColumnValueOptions({ valueColumn: COLUMN_ID }, { ctx: renderCtx() })).toEqual({
129
+ type: "resolving",
130
+ valueColumn: COLUMN_ID,
131
+ });
132
+
133
+ vi.spyOn(ColumnRecipe, "getStatus").mockImplementation((id) =>
134
+ id === LABEL_ID ? "resolving" : "present",
135
+ );
136
+ const ctx = renderCtx();
137
+ expect(
138
+ createColumnValueOptions({ valueColumn: COLUMN_ID, labelColumn: LABEL_ID }, { ctx }),
139
+ ).toEqual({ type: "resolving", valueColumn: COLUMN_ID });
140
+ expect(ctx.createPFrame).not.toHaveBeenCalled();
141
+ });
142
+
143
+ test("is absent once the value column is gone", () => {
144
+ vi.spyOn(ColumnRecipe, "getStatus").mockReturnValue("absent");
145
+ const ctx = renderCtx();
146
+
147
+ expect(createColumnValueOptions({ valueColumn: COLUMN_ID }, { ctx })).toEqual({
148
+ type: "absent",
149
+ valueColumn: COLUMN_ID,
150
+ });
151
+ expect(ctx.createPFrame).not.toHaveBeenCalled();
152
+ });
153
+
154
+ test("leaves the values to label themselves once the label column is gone", () => {
155
+ vi.spyOn(ColumnRecipe, "getStatus").mockImplementation((id) =>
156
+ id === LABEL_ID ? "absent" : "present",
157
+ );
158
+ const ctx = renderCtx();
159
+
160
+ expect(
161
+ createColumnValueOptions({ valueColumn: COLUMN_ID, labelColumn: LABEL_ID }, { ctx }),
162
+ ).toMatchObject({ type: "present", frameColumns: { value: COLUMN_ID, label: null } });
163
+ expect(ctx.createPFrame).toHaveBeenCalledWith([COLUMN_ID]);
164
+ });
165
+ });
166
+
167
+ // Internals
168
+
169
+ const COLUMN_ID = createGlobalPObjectId("samples", "pf.metadata.round");
170
+
171
+ const LABEL_ID = createGlobalPObjectId("samples", "pf.metadata.roundName");
172
+
173
+ const FRAME = "frame-of-round" as PFrameHandle;
174
+
175
+ function option(value: string, label = value) {
176
+ return { value: createColumnValueId({ column: COLUMN_ID, value }), label };
177
+ }
178
+
179
+ /** A render ctx that creates {@link FRAME} for any columns; only `createPFrame` is called. */
180
+ function renderCtx() {
181
+ const createPFrame = vi.fn(() => FRAME);
182
+ return Object.assign({ createPFrame } as GlobalCfgRenderCtx, { createPFrame });
183
+ }
@@ -0,0 +1,194 @@
1
+ import {
2
+ createColumnValueId,
3
+ extractPObjectId,
4
+ isPColumn,
5
+ type ColumnUniversalId,
6
+ type ColumnValueId,
7
+ type PColumn,
8
+ type PFrameHandle,
9
+ type PObjectId,
10
+ } from "@milaboratories/pl-model-common";
11
+ import { finalizePColumnData } from "../render/api";
12
+ import type { GlobalCfgRenderCtx, PColumnDataUniversal } from "../render/internal";
13
+ import { getCfgRenderCtx } from "../internal";
14
+ import { ColumnRecipe } from "./column_recipes";
15
+ import type { ColumnResolutionStatus } from "./column_recipes/types";
16
+ import type { DataColumnRecipe } from "./data_column";
17
+
18
+ /** Drop-down option for a value of a column — column-value-id valued. */
19
+ export type ColumnValueOption = {
20
+ readonly value: ColumnValueId;
21
+ readonly label: string;
22
+ };
23
+
24
+ /** A column a value picker offers the values of, or labels them by. */
25
+ export type ColumnValueOptionsColumn =
26
+ | ColumnUniversalId
27
+ | PColumn<undefined | PColumnDataUniversal>
28
+ | DataColumnRecipe
29
+ | ColumnRecipe;
30
+
31
+ /**
32
+ * What a UI reads the options of a value picker from: a frame holding the value column, and the
33
+ * label column while there is one, as long as the value column is there. `valueColumn` is the
34
+ * column the options are values of, so the UI can tell a model that still describes an earlier
35
+ * pick. `frameColumns` names both columns as the frame holds them.
36
+ */
37
+ export type ColumnValueOptionsModel =
38
+ | { readonly type: "resolving"; readonly valueColumn: ColumnUniversalId }
39
+ | { readonly type: "absent"; readonly valueColumn: ColumnUniversalId }
40
+ | {
41
+ readonly type: "present";
42
+ readonly valueColumn: ColumnUniversalId;
43
+ readonly frame: PFrameHandle;
44
+ readonly frameColumns: {
45
+ readonly value: PObjectId;
46
+ /** `null` when the values label themselves. */
47
+ readonly label: PObjectId | null;
48
+ };
49
+ };
50
+
51
+ /**
52
+ * The model of a value picker over the values of `valueColumn`, for a model output; the UI reads
53
+ * the options through it (`usePlColumnValueOptions`, `PlColumnValueDropdown`). Each option is a
54
+ * value of `valueColumn`, labelled by the value of `labelColumn` in the same row, or by the value
55
+ * itself when no label column is given.
56
+ *
57
+ * `absent` once the value column is gone: a stored id may name a column its upstream block no
58
+ * longer produces. A label column that is gone leaves the values to label themselves; one that is
59
+ * still resolving keeps the model resolving.
60
+ */
61
+ export function createColumnValueOptions(
62
+ columns: {
63
+ readonly valueColumn: ColumnValueOptionsColumn;
64
+ readonly labelColumn?: ColumnValueOptionsColumn;
65
+ },
66
+ deps?: { readonly ctx?: GlobalCfgRenderCtx },
67
+ ): ColumnValueOptionsModel {
68
+ const ctx = deps?.ctx ?? getCfgRenderCtx();
69
+ const value = frameEntryOf(columns.valueColumn, ctx);
70
+ const valueColumn = value.id;
71
+ if (value.status !== "present") return { type: value.status, valueColumn };
72
+
73
+ const label =
74
+ columns.labelColumn === undefined ? undefined : frameEntryOf(columns.labelColumn, ctx);
75
+ if (label?.status === "resolving") return { type: "resolving", valueColumn };
76
+ const labelled =
77
+ label?.status === "present" && label.frameId !== value.frameId ? label : undefined;
78
+
79
+ const frame = ctx.createPFrame(labelled === undefined ? [value.def] : [value.def, labelled.def]);
80
+ return {
81
+ type: "present",
82
+ valueColumn,
83
+ frame,
84
+ frameColumns: { value: value.frameId, label: labelled?.frameId ?? null },
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Distinct `values` of `column` as options, each a column value id naming the column, labelled
90
+ * by the value itself and ordered naturally by label ("R2" before "R10"). Empty values are not
91
+ * offered.
92
+ */
93
+ export function deriveColumnValueOptions(
94
+ column: ColumnUniversalId,
95
+ values: readonly string[],
96
+ ): ColumnValueOption[] {
97
+ return deriveLabelledColumnValueOptions(
98
+ column,
99
+ values.map((value) => ({ value, label: value })),
100
+ );
101
+ }
102
+
103
+ /**
104
+ * Distinct values of `column` among `rows` as options, each a column value id naming the column,
105
+ * labelled by the label of the first row holding the value, and ordered naturally by label ("R2"
106
+ * before "R10"). Empty values are not offered; a value whose label is empty labels itself.
107
+ */
108
+ export function deriveLabelledColumnValueOptions(
109
+ column: ColumnUniversalId,
110
+ rows: readonly { readonly value: string; readonly label: string }[],
111
+ ): ColumnValueOption[] {
112
+ const options = new Map<string, ColumnValueOption>();
113
+ for (const { value, label } of rows) {
114
+ if (value === "" || options.has(value)) continue;
115
+ options.set(value, {
116
+ value: createColumnValueId({ column, value }),
117
+ label: label === "" ? value : label,
118
+ });
119
+ }
120
+ return [...options.values()].sort((a, b) => compareNatural(a.label, b.label));
121
+ }
122
+
123
+ // Internals
124
+
125
+ /** A column as a frame is made of it: its id, its status, and what the frame is created from. */
126
+ type FrameEntry = {
127
+ readonly id: ColumnUniversalId;
128
+ readonly status: ColumnResolutionStatus;
129
+ readonly frameId: PObjectId;
130
+ readonly def: Parameters<GlobalCfgRenderCtx["createPFrame"]>[0][number];
131
+ };
132
+
133
+ /**
134
+ * A column given by id or by a recipe goes into the frame by its id, which the frame holds as the
135
+ * bare id of its leaf; a materialised column goes in as it is.
136
+ */
137
+ function frameEntryOf(column: ColumnValueOptionsColumn, ctx: GlobalCfgRenderCtx): FrameEntry {
138
+ if (typeof column === "string") {
139
+ return {
140
+ id: column,
141
+ status: ColumnRecipe.getStatus(column, { ctx }),
142
+ frameId: extractPObjectId(column),
143
+ def: column,
144
+ };
145
+ }
146
+ if (isPColumn<undefined | PColumnDataUniversal>(column)) {
147
+ return {
148
+ id: column.id,
149
+ status: "present",
150
+ frameId: column.id,
151
+ def: finalizePColumnData(column),
152
+ };
153
+ }
154
+ return {
155
+ id: column.id,
156
+ status: column.getDataStatus(),
157
+ frameId: extractPObjectId(column.id),
158
+ def: column.id,
159
+ };
160
+ }
161
+
162
+ const CHUNKS = /\d+|\D+/g;
163
+
164
+ /**
165
+ * Natural order: runs of digits compare as numbers, other text case-insensitively, so "R2"
166
+ * comes before "R10". The model runtime has no `Intl`.
167
+ */
168
+ function compareNatural(a: string, b: string): number {
169
+ const chunksA = a.match(CHUNKS) ?? [];
170
+ const chunksB = b.match(CHUNKS) ?? [];
171
+ for (let i = 0; i < Math.min(chunksA.length, chunksB.length); i++) {
172
+ const order = compareChunks(chunksA[i], chunksB[i]);
173
+ if (order !== 0) return order;
174
+ }
175
+ return chunksA.length - chunksB.length || compareStrings(a, b);
176
+ }
177
+
178
+ function compareChunks(a: string, b: string): number {
179
+ if (isDigits(a) && isDigits(b)) {
180
+ // Compared as digit strings, so numbers of any length keep their order.
181
+ const numberA = a.replace(/^0+(?=\d)/, "");
182
+ const numberB = b.replace(/^0+(?=\d)/, "");
183
+ return numberA.length - numberB.length || compareStrings(numberA, numberB);
184
+ }
185
+ return compareStrings(a.toLowerCase(), b.toLowerCase());
186
+ }
187
+
188
+ function isDigits(chunk: string): boolean {
189
+ return chunk.charCodeAt(0) >= 48 && chunk.charCodeAt(0) <= 57;
190
+ }
191
+
192
+ function compareStrings(a: string, b: string): number {
193
+ return a < b ? -1 : a > b ? 1 : 0;
194
+ }
@@ -7,7 +7,7 @@ import {
7
7
  type PObjectId,
8
8
  type PObjectSpec,
9
9
  } from "@milaboratories/pl-model-common";
10
- import { ColumnAbsentError, DataColumnImpl } from "./data_column";
10
+ import { DataColumnImpl } from "./data_column";
11
11
  import { _ctxProvidersCache } from "./column_providers";
12
12
  import { installStubRegistry } from "./__test_helpers__/stub_registry";
13
13
 
@@ -86,10 +86,9 @@ describe("DataColumnImpl.spec — applySpecOverrides", () => {
86
86
  expect(c.getSpec()).toBe(stubSpec);
87
87
  });
88
88
 
89
- test("fromId throws ColumnAbsentError when ctx has no handles", () => {
90
- // Empty registry — `isFinal()` returns true vacuously, so the leaf is
91
- // provably absent (no provider will ever supply it).
92
- expect(() => DataColumnImpl.fromId(baseLeaf)).toThrow(ColumnAbsentError);
89
+ test("fromId returns undefined when ctx has no handles", () => {
90
+ // Empty registry — `isFinal()` returns true vacuously, so the leaf is absent.
91
+ expect(DataColumnImpl.fromId(baseLeaf)).toBeUndefined();
93
92
  });
94
93
 
95
94
  test("appends axes at indices past base.axesSpec.length", () => {
@@ -130,7 +129,7 @@ describe("DataColumnImpl.spec — applySpecOverrides", () => {
130
129
  });
131
130
  });
132
131
 
133
- // --- resolution status / absent throw --------------------------------------
132
+ // --- resolution status / absent column --------------------------------------
134
133
 
135
134
  describe("DataColumnImpl resolution: fromId / fromAccessor / getStatus", () => {
136
135
  test("fromId returns undefined when registry is unfinalized and id not found", () => {
@@ -139,10 +138,10 @@ describe("DataColumnImpl resolution: fromId / fromAccessor / getStatus", () => {
139
138
  expect(DataColumnImpl.fromId(baseLeaf)).toBeUndefined();
140
139
  });
141
140
 
142
- test("fromId throws ColumnAbsentError when leaf has no spec field on locked accessor", () => {
143
- // Leaf entry present, no spec field, accessor locked → absent forever.
141
+ test("fromId returns undefined when leaf has no spec field on locked accessor", () => {
142
+ // Leaf entry present, no spec field, accessor locked → absent.
144
143
  installStubRegistry(mockCtx, { [baseLeaf]: { accessorLocked: true } });
145
- expect(() => DataColumnImpl.fromId(baseLeaf)).toThrow(ColumnAbsentError);
144
+ expect(DataColumnImpl.fromId(baseLeaf)).toBeUndefined();
146
145
  });
147
146
 
148
147
  test("fromId returns undefined when leaf has no spec field on unlocked accessor", () => {
@@ -157,10 +156,10 @@ describe("DataColumnImpl resolution: fromId / fromAccessor / getStatus", () => {
157
156
  expect(DataColumnImpl.fromId(baseLeaf)).toBeUndefined();
158
157
  });
159
158
 
160
- test("fromAccessor throws ColumnAbsentError when accessor is locked without spec", () => {
159
+ test("fromAccessor returns undefined when accessor is locked without spec", () => {
161
160
  installStubRegistry(mockCtx, { [baseLeaf]: { accessorLocked: true } });
162
161
  const entry = pluckLeafEntry(baseLeaf);
163
- expect(() => DataColumnImpl.fromAccessor(entry)).toThrow(ColumnAbsentError);
162
+ expect(DataColumnImpl.fromAccessor(entry)).toBeUndefined();
164
163
  });
165
164
 
166
165
  test("fromAccessor returns undefined when accessor is unlocked without spec", () => {
@@ -169,10 +168,10 @@ describe("DataColumnImpl resolution: fromId / fromAccessor / getStatus", () => {
169
168
  expect(DataColumnImpl.fromAccessor(entry)).toBeUndefined();
170
169
  });
171
170
 
172
- test("an export that is not a column: fromId and fromAccessor throw, status tracks only resolution", () => {
171
+ test("an export that is not a column: fromId and fromAccessor return undefined, status tracks only resolution", () => {
173
172
  installStubRegistry(mockCtx, { [baseLeaf]: { spec: fileSpec } });
174
- expect(() => DataColumnImpl.fromId(baseLeaf)).toThrow(ColumnAbsentError);
175
- expect(() => DataColumnImpl.fromAccessor(pluckLeafEntry(baseLeaf))).toThrow(ColumnAbsentError);
173
+ expect(DataColumnImpl.fromId(baseLeaf)).toBeUndefined();
174
+ expect(DataColumnImpl.fromAccessor(pluckLeafEntry(baseLeaf))).toBeUndefined();
176
175
  expect(DataColumnImpl.getStatusById(baseLeaf)).toBe("present");
177
176
  });
178
177