@action-state-group/capsule-viewer 0.3.0 → 0.5.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 (60) hide show
  1. package/README.md +3 -2
  2. package/dist/browser.d.ts +1 -1
  3. package/dist/browser.js +5 -3
  4. package/dist/browser.js.map +1 -1
  5. package/dist/chart-dataset.d.ts +23 -0
  6. package/dist/chart-dataset.js +195 -0
  7. package/dist/chart-dataset.js.map +1 -0
  8. package/dist/chart-spec.d.ts +141 -0
  9. package/dist/chart-spec.js +646 -0
  10. package/dist/chart-spec.js.map +1 -0
  11. package/dist/chart-view.d.ts +34 -0
  12. package/dist/chart-view.js +389 -0
  13. package/dist/chart-view.js.map +1 -0
  14. package/dist/compliance-styles.js +0 -1
  15. package/dist/compliance-styles.js.map +1 -1
  16. package/dist/compliance-view.js +53 -17
  17. package/dist/compliance-view.js.map +1 -1
  18. package/dist/contract-report-wording.js +51 -2
  19. package/dist/contract-report-wording.js.map +1 -1
  20. package/dist/core-strip.d.ts +38 -0
  21. package/dist/core-strip.js +183 -0
  22. package/dist/core-strip.js.map +1 -0
  23. package/dist/emitter-shell.html +10 -1
  24. package/dist/emitter.js +13 -3
  25. package/dist/emitter.js.map +1 -1
  26. package/dist/evidence-graph-view.d.ts +6 -0
  27. package/dist/evidence-graph-view.js +244 -91
  28. package/dist/evidence-graph-view.js.map +1 -1
  29. package/dist/evidence-graph.iife.js +6351 -1633
  30. package/dist/outcome-report-view.js +49 -25
  31. package/dist/outcome-report-view.js.map +1 -1
  32. package/dist/presentation-builder.d.ts +15 -0
  33. package/dist/presentation-builder.js +36 -2
  34. package/dist/presentation-builder.js.map +1 -1
  35. package/dist/presentation-mount.d.ts +2 -0
  36. package/dist/presentation-mount.js +1 -0
  37. package/dist/presentation-mount.js.map +1 -1
  38. package/dist/report-front-styles.d.ts +2 -2
  39. package/dist/report-front-styles.js +3 -15
  40. package/dist/report-front-styles.js.map +1 -1
  41. package/dist/report-front.d.ts +2 -24
  42. package/dist/report-front.js +11 -145
  43. package/dist/report-front.js.map +1 -1
  44. package/dist/report-levels.d.ts +33 -1
  45. package/dist/report-levels.js +135 -0
  46. package/dist/report-levels.js.map +1 -1
  47. package/dist/report-provenance.d.ts +28 -0
  48. package/dist/report-provenance.js +60 -11
  49. package/dist/report-provenance.js.map +1 -1
  50. package/dist/report-view-render.d.ts +13 -0
  51. package/dist/report-view-render.js +280 -0
  52. package/dist/report-view-render.js.map +1 -0
  53. package/dist/report-view.d.ts +29 -0
  54. package/dist/report-view.js +170 -0
  55. package/dist/report-view.js.map +1 -0
  56. package/dist/viewer-build.js +3 -3
  57. package/dist/viewer-build.js.map +1 -1
  58. package/dist/wording/contract-report-eu-ai-act.en.json +36 -0
  59. package/dist/wording/contract-report-outcomes.en.json +36 -0
  60. package/package.json +5 -3
@@ -0,0 +1,646 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ import { isCalendarDate, utcDateOf, } from "@action-state-group/agent-action-capsule";
3
+ const isObj = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
4
+ /** A refused chart: its reason, the JSON pointer it names (if any) and why. */
5
+ export class ChartRefusal extends Error {
6
+ reason;
7
+ pointer;
8
+ constructor(reason, message, pointer) {
9
+ super(`${reason}: ${message}`);
10
+ this.name = "ChartRefusal";
11
+ this.reason = reason;
12
+ this.pointer = pointer;
13
+ }
14
+ }
15
+ const refuse = (reason, message, pointer) => {
16
+ throw new ChartRefusal(reason, message, pointer);
17
+ };
18
+ const SCHEMA = "https://vega.github.io/schema/vega-lite/v5.json";
19
+ const MARKS = ["bar", "line", "point", "rect"];
20
+ const TYPES = [
21
+ "quantitative",
22
+ "ordinal",
23
+ "nominal",
24
+ "temporal",
25
+ ];
26
+ const UNITS = ["utcyearmonthdate", "utcyearmonth"];
27
+ const CHANNELS = ["x", "y", "color"];
28
+ // The same grammar as agent-action-capsule's dataset plan field paths (§5.1).
29
+ const FIELD_PATH = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/u;
30
+ const pointerOf = (base, key) => `${base}/${String(key).replaceAll("~", "~0").replaceAll("/", "~1")}`;
31
+ function onlyKeys(value, allowed, at) {
32
+ for (const key of Object.keys(value))
33
+ if (!allowed.includes(key))
34
+ refuse("chart-unsupported-member", `${pointerOf(at, key) || "/"} is not in the accepted subset`, pointerOf(at, key));
35
+ }
36
+ function need(ok, value, at, what) {
37
+ if (!ok)
38
+ refuse("chart-unsupported-member", `${at || "/"} must be ${what}`, at);
39
+ return value;
40
+ }
41
+ const isScalar = (value) => typeof value === "string" ||
42
+ typeof value === "boolean" ||
43
+ (typeof value === "number" && Number.isFinite(value));
44
+ function readField(value, at) {
45
+ return need(typeof value === "string" && FIELD_PATH.test(value), value, at, "a field path (name, dot-separated)");
46
+ }
47
+ /** A Vega-Lite DateTime `{year, month, date, utc: true}` naming a real day, as `YYYY-MM-DD`. */
48
+ function readDay(value, at) {
49
+ if (isObj(value)) {
50
+ onlyKeys(value, ["year", "month", "date", "utc"], at);
51
+ const { year, month, date, utc } = value;
52
+ if (utc === true &&
53
+ Number.isInteger(year) &&
54
+ Number.isInteger(month) &&
55
+ Number.isInteger(date)) {
56
+ const day = `${String(year).padStart(4, "0")}-${String(month).padStart(2, "0")}-${String(date).padStart(2, "0")}`;
57
+ if (year >= 1 &&
58
+ year <= 9999 &&
59
+ isCalendarDate(day))
60
+ return day;
61
+ }
62
+ }
63
+ return refuse("chart-unsupported-member", `${at} must be a UTC DateTime {year, month, date, utc: true} naming a real day`, at);
64
+ }
65
+ export function readPredicate(value, at) {
66
+ need(isObj(value), undefined, at, "a predicate object");
67
+ const p = value;
68
+ for (const kind of ["and", "or"])
69
+ if (Object.hasOwn(p, kind)) {
70
+ onlyKeys(p, [kind], at);
71
+ const items = p[kind];
72
+ need(Array.isArray(items) && items.length > 0, undefined, pointerOf(at, kind), "a non-empty list of predicates");
73
+ return {
74
+ kind,
75
+ items: items.map((item, i) => readPredicate(item, pointerOf(pointerOf(at, kind), i))),
76
+ };
77
+ }
78
+ if (Object.hasOwn(p, "not")) {
79
+ onlyKeys(p, ["not"], at);
80
+ return { kind: "not", item: readPredicate(p.not, pointerOf(at, "not")) };
81
+ }
82
+ if (Object.hasOwn(p, "equal")) {
83
+ onlyKeys(p, ["field", "equal"], at);
84
+ const field = readField(p.field, pointerOf(at, "field"));
85
+ return {
86
+ kind: "equal",
87
+ field,
88
+ value: need(isScalar(p.equal), p.equal, pointerOf(at, "equal"), "a string, number or boolean"),
89
+ };
90
+ }
91
+ if (Object.hasOwn(p, "oneOf")) {
92
+ onlyKeys(p, ["field", "oneOf"], at);
93
+ const field = readField(p.field, pointerOf(at, "field"));
94
+ const values = p.oneOf;
95
+ need(Array.isArray(values) && values.length > 0 && values.every(isScalar), undefined, pointerOf(at, "oneOf"), "a non-empty list of strings, numbers or booleans");
96
+ return { kind: "oneOf", field, values: values };
97
+ }
98
+ if (Object.hasOwn(p, "range")) {
99
+ onlyKeys(p, ["field", "range", "timeUnit"], at);
100
+ const field = readField(p.field, pointerOf(at, "field"));
101
+ need(p.timeUnit === "utcyearmonthdate", undefined, pointerOf(at, "timeUnit"), '"utcyearmonthdate"');
102
+ const range = p.range;
103
+ need(Array.isArray(range) && range.length === 2, undefined, pointerOf(at, "range"), "a list of two days");
104
+ const [lo, hi] = range;
105
+ const from = readDay(lo, pointerOf(pointerOf(at, "range"), 0));
106
+ const to = readDay(hi, pointerOf(pointerOf(at, "range"), 1));
107
+ if (from > to)
108
+ refuse("chart-unsupported-member", `${at}: the range ends before it starts`, pointerOf(at, "range"));
109
+ return { kind: "range", field, from, to };
110
+ }
111
+ return refuse("chart-unsupported-member", `${at} is not an accepted predicate (equal, oneOf, range, and, or, not)`, at);
112
+ }
113
+ // ---------------------------------------------------------------------------
114
+ // Rows and fields
115
+ // ---------------------------------------------------------------------------
116
+ const MISSING = Symbol("missing");
117
+ /** A field path resolved on a record header: each name an own member of the object before it. */
118
+ export function resolveField(header, path) {
119
+ let at = header;
120
+ for (const name of path.split(".")) {
121
+ if (!isObj(at) || !Object.hasOwn(at, name))
122
+ return MISSING;
123
+ at = at[name];
124
+ }
125
+ return at;
126
+ }
127
+ const rowName = (row) => `row seq ${row.seq} (${row.recordType})`;
128
+ function headerOf(row) {
129
+ // Withheld rows are refused before any field is read.
130
+ return row.header;
131
+ }
132
+ function evaluate(p, row) {
133
+ switch (p.kind) {
134
+ case "and":
135
+ return p.items.every((item) => evaluate(item, row));
136
+ case "or":
137
+ return p.items.some((item) => evaluate(item, row));
138
+ case "not":
139
+ return !evaluate(p.item, row);
140
+ default: {
141
+ // A predicate is false on a row that lacks its field, as in
142
+ // Vega-Lite: that is how a filter selects one record type.
143
+ const value = resolveField(headerOf(row), p.field);
144
+ if (value === MISSING)
145
+ return false;
146
+ if (p.kind === "range") {
147
+ const day = utcDateOf(value);
148
+ if (day === undefined)
149
+ refuse("chart-field-type", `${rowName(row)}: ${p.field} is not an RFC 3339 date-time with an offset`);
150
+ return day >= p.from && day <= p.to;
151
+ }
152
+ if (!isScalar(value))
153
+ refuse("chart-field-type", `${rowName(row)}: ${p.field} is not a string, number or boolean`);
154
+ return p.kind === "equal"
155
+ ? value === p.value
156
+ : p.values.some((v) => v === value);
157
+ }
158
+ }
159
+ }
160
+ function readChannel(value, at) {
161
+ need(isObj(value), undefined, at, "an encoding object");
162
+ const c = value;
163
+ onlyKeys(c, ["field", "type", "aggregate", "timeUnit", "title"], at);
164
+ const type = need(TYPES.includes(c.type), c.type, pointerOf(at, "type"), "quantitative, ordinal, nominal or temporal");
165
+ const out = { type };
166
+ if (Object.hasOwn(c, "aggregate"))
167
+ out.aggregate = need(c.aggregate === "count" || c.aggregate === "sum", c.aggregate, pointerOf(at, "aggregate"), "count or sum");
168
+ if (Object.hasOwn(c, "field")) {
169
+ if (out.aggregate === "count")
170
+ refuse("chart-unsupported-member", `${at}: a count names no field`, pointerOf(at, "field"));
171
+ out.field = readField(c.field, pointerOf(at, "field"));
172
+ }
173
+ else if (out.aggregate !== "count")
174
+ refuse("chart-unsupported-member", `${at} must name a field`, pointerOf(at, "field"));
175
+ if (out.aggregate !== undefined && type !== "quantitative")
176
+ refuse("chart-unsupported-member", `${at}: an aggregate is quantitative`, pointerOf(at, "type"));
177
+ if (Object.hasOwn(c, "timeUnit")) {
178
+ out.timeUnit = need(type === "temporal" && UNITS.includes(c.timeUnit), c.timeUnit, pointerOf(at, "timeUnit"), "utcyearmonthdate or utcyearmonth, on a temporal field");
179
+ }
180
+ else if (type === "temporal")
181
+ refuse("chart-unsupported-member", `${at}: a temporal field needs a timeUnit (utcyearmonthdate or utcyearmonth)`, pointerOf(at, "timeUnit"));
182
+ return out;
183
+ }
184
+ function readWindow(value, at) {
185
+ need(isObj(value), undefined, at, "{field, from, to}");
186
+ const w = value;
187
+ onlyKeys(w, ["field", "from", "to"], at);
188
+ const field = readField(w.field, pointerOf(at, "field"));
189
+ const from = need(isCalendarDate(w.from), w.from, pointerOf(at, "from"), "a calendar day YYYY-MM-DD");
190
+ const to = need(isCalendarDate(w.to), w.to, pointerOf(at, "to"), "a calendar day YYYY-MM-DD");
191
+ if (from > to)
192
+ refuse("chart-unsupported-member", `${at}: the window ends before it starts`, at);
193
+ return { field, from, to };
194
+ }
195
+ function readStatement(value, at) {
196
+ need(isObj(value), undefined, at, "an object");
197
+ const s = value;
198
+ onlyKeys(s, ["population", "window", "runs", "values"], at);
199
+ const pop = s.population;
200
+ need(isObj(pop), undefined, pointerOf(at, "population"), "{count}");
201
+ onlyKeys(pop, ["count"], pointerOf(at, "population"));
202
+ const count = pop.count;
203
+ need(Number.isInteger(count) && count >= 0, undefined, pointerOf(pointerOf(at, "population"), "count"), "a non-negative integer");
204
+ const out = { population: count, values: [] };
205
+ if (Object.hasOwn(s, "window"))
206
+ out.window = readWindow(s.window, pointerOf(at, "window"));
207
+ if (Object.hasOwn(s, "runs")) {
208
+ const r = s.runs;
209
+ const rat = pointerOf(at, "runs");
210
+ need(isObj(r), undefined, rat, "{filter, field}");
211
+ onlyKeys(r, ["filter", "field"], rat);
212
+ out.runs = {
213
+ filter: readPredicate(r.filter, pointerOf(rat, "filter")),
214
+ field: readField(r.field, pointerOf(rat, "field")),
215
+ };
216
+ }
217
+ const values = s.values;
218
+ need(Array.isArray(values), undefined, pointerOf(at, "values"), "a list of groups");
219
+ values.forEach((v, i) => {
220
+ const vat = pointerOf(pointerOf(at, "values"), i);
221
+ need(isObj(v), undefined, vat, "a group object");
222
+ onlyKeys(v, [...CHANNELS, "not_run"], vat);
223
+ if (Object.hasOwn(v, "not_run"))
224
+ need(v.not_run === true, undefined, pointerOf(vat, "not_run"), "true");
225
+ out.values.push(v);
226
+ });
227
+ return out;
228
+ }
229
+ /**
230
+ * The first number in a spec that is not a safe integer, by its pointer. A
231
+ * spec is hashed (JCS) for the page and carried in its render options, and
232
+ * JCS here has no form for a fraction or an unsafe integer; a record header
233
+ * holds none either, so no such number can match the data.
234
+ */
235
+ function inexactNumber(value, at) {
236
+ if (typeof value === "number")
237
+ return Number.isSafeInteger(value) ? undefined : at || "/";
238
+ if (Array.isArray(value)) {
239
+ for (let i = 0; i < value.length; i++) {
240
+ const found = inexactNumber(value[i], pointerOf(at, i));
241
+ if (found !== undefined)
242
+ return found;
243
+ }
244
+ return undefined;
245
+ }
246
+ if (isObj(value))
247
+ for (const [k, v] of Object.entries(value)) {
248
+ const found = inexactNumber(v, pointerOf(at, k));
249
+ if (found !== undefined)
250
+ return found;
251
+ }
252
+ return undefined;
253
+ }
254
+ /** Read a spec in the closed subset, or refuse it (structure only; no data is read). */
255
+ export function readChartSpec(value) {
256
+ need(isObj(value), undefined, "", "a Vega-Lite object");
257
+ const inexact = inexactNumber(value, "");
258
+ if (inexact !== undefined)
259
+ refuse("chart-unsupported-member", `${inexact} is a fraction or an integer beyond 2^53; a spec holds integers only`, inexact);
260
+ const spec = value;
261
+ onlyKeys(spec, [
262
+ "$schema",
263
+ "data",
264
+ "mark",
265
+ "transform",
266
+ "encoding",
267
+ "usermeta",
268
+ "title",
269
+ "description",
270
+ ], "");
271
+ need(spec.$schema === SCHEMA, undefined, "/$schema", SCHEMA);
272
+ const data = spec.data;
273
+ need(isObj(data), undefined, "/data", '{"name": "dataset"}');
274
+ onlyKeys(data, ["name"], "/data");
275
+ need(data.name === "dataset", undefined, "/data/name", '"dataset"');
276
+ let mark;
277
+ if (isObj(spec.mark)) {
278
+ onlyKeys(spec.mark, ["type"], "/mark");
279
+ mark = need(MARKS.includes(spec.mark.type), spec.mark.type, "/mark/type", "bar, line, point or rect");
280
+ }
281
+ else
282
+ mark = need(MARKS.includes(spec.mark), spec.mark, "/mark", "bar, line, point or rect");
283
+ const transform = [];
284
+ if (Object.hasOwn(spec, "transform")) {
285
+ need(Array.isArray(spec.transform), undefined, "/transform", "a list of filters");
286
+ spec.transform.forEach((t, i) => {
287
+ const at = pointerOf("/transform", i);
288
+ need(isObj(t), undefined, at, "{filter: predicate}");
289
+ onlyKeys(t, ["filter"], at);
290
+ need(Object.hasOwn(t, "filter"), undefined, at, "{filter: predicate}");
291
+ transform.push(readPredicate(t.filter, pointerOf(at, "filter")));
292
+ });
293
+ }
294
+ const encoding = spec.encoding;
295
+ need(isObj(encoding), undefined, "/encoding", "an object");
296
+ onlyKeys(encoding, CHANNELS, "/encoding");
297
+ const channels = {};
298
+ for (const name of CHANNELS)
299
+ if (Object.hasOwn(encoding, name))
300
+ channels[name] = readChannel(encoding[name], pointerOf("/encoding", name));
301
+ const usermeta = spec.usermeta;
302
+ need(isObj(usermeta), undefined, "/usermeta", "{capsule: statement}");
303
+ onlyKeys(usermeta, ["capsule"], "/usermeta");
304
+ const statement = readStatement(usermeta.capsule, "/usermeta/capsule");
305
+ // Exactly one channel aggregates: y for bar, line and point; color for rect.
306
+ const aggregating = CHANNELS.filter((c) => channels[c]?.aggregate);
307
+ const want = mark === "rect" ? "color" : "y";
308
+ const required = mark === "rect" ? ["x", "y", "color"] : ["x", "y"];
309
+ if (aggregating.length !== 1 ||
310
+ aggregating[0] !== want ||
311
+ required.some((c) => channels[c] === undefined))
312
+ refuse("chart-aggregate-shape", mark === "rect"
313
+ ? "a rect chart encodes x and y and aggregates color, and nothing else aggregates"
314
+ : `a ${mark} chart encodes x and aggregates y, and nothing else aggregates`, "/encoding");
315
+ const keys = CHANNELS.filter((c) => channels[c] !== undefined && c !== want);
316
+ const temporals = keys.filter((c) => channels[c].type === "temporal");
317
+ // A key is a category or a time unit: the renderer places keys in bands,
318
+ // so a quantitative key would draw its distances wrong.
319
+ for (const c of keys)
320
+ if (channels[c].type === "quantitative")
321
+ refuse("chart-unsupported-member", `${c} is a key, so it is nominal, ordinal or temporal; only the aggregate is quantitative`, pointerOf(pointerOf("/encoding", c), "type"));
322
+ // The time axis is x: "not run" is drawn as a column of x.
323
+ for (const c of temporals)
324
+ if (c !== "x")
325
+ refuse("chart-unsupported-member", "only x can be temporal", pointerOf(pointerOf("/encoding", c), "type"));
326
+ return {
327
+ mark,
328
+ transform,
329
+ channels,
330
+ aggregate: want,
331
+ keys,
332
+ ...(temporals[0] === undefined ? {} : { temporal: temporals[0] }),
333
+ statement,
334
+ };
335
+ }
336
+ // ---------------------------------------------------------------------------
337
+ // Time units
338
+ // ---------------------------------------------------------------------------
339
+ // Days in a month of the proleptic Gregorian calendar, by arithmetic: Date.UTC
340
+ // maps years 0-99 to 1900-1999.
341
+ const MONTH_DAYS = (year, month) => month === 2
342
+ ? (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0
343
+ ? 29
344
+ : 28
345
+ : [4, 6, 9, 11].includes(month)
346
+ ? 30
347
+ : 31;
348
+ /** The unit a UTC day falls in, named by its first day. */
349
+ function unitOf(day, unit) {
350
+ return unit === "utcyearmonth" ? `${day.slice(0, 8)}01` : day;
351
+ }
352
+ function nextDay(day) {
353
+ const [y, m, d] = day.split("-").map(Number);
354
+ const last = d === MONTH_DAYS(y, m);
355
+ const ny = last && m === 12 ? y + 1 : y;
356
+ const nm = last ? (m % 12) + 1 : m;
357
+ const nd = last ? 1 : d + 1;
358
+ return `${String(ny).padStart(4, "0")}-${String(nm).padStart(2, "0")}-${String(nd).padStart(2, "0")}`;
359
+ }
360
+ /** Every unit of the window, in order; refuses a window the units don't tile. */
361
+ function unitsOf(window, unit) {
362
+ if (unit === "utcyearmonth") {
363
+ const [ty, tm, td] = window.to.split("-").map(Number);
364
+ if (!window.from.endsWith("-01") || td !== MONTH_DAYS(ty, tm))
365
+ refuse("chart-window-mismatch", `a utcyearmonth chart's window runs from a month's first day to a month's last day; ${window.from} to ${window.to} does not`, "/usermeta/capsule/window");
366
+ }
367
+ const out = [];
368
+ // Stops at `to` itself: the day after 9999-12-31 has five year digits and
369
+ // would sort before it.
370
+ for (let day = window.from;; day = nextDay(day)) {
371
+ const u = unitOf(day, unit);
372
+ if (out[out.length - 1] !== u)
373
+ out.push(u);
374
+ if (day === window.to)
375
+ break;
376
+ }
377
+ return out;
378
+ }
379
+ // ---------------------------------------------------------------------------
380
+ // The check
381
+ // ---------------------------------------------------------------------------
382
+ /** The plan's `traditional.window` nodes' params: the sealed windows. */
383
+ function sealedWindows(plan) {
384
+ const nodes = plan.nodes;
385
+ if (!Array.isArray(nodes))
386
+ refuse("chart-dataset-invalid", "the dataset plan has no nodes");
387
+ const out = [];
388
+ for (const node of nodes) {
389
+ if (!isObj(node) || node.operator !== "traditional.window")
390
+ continue;
391
+ const p = node.params;
392
+ if (!isObj(p) ||
393
+ typeof p.field !== "string" ||
394
+ !isCalendarDate(p.from) ||
395
+ !isCalendarDate(p.to))
396
+ refuse("chart-dataset-invalid", "a window node of the dataset plan has no {field, from, to}");
397
+ const w = p;
398
+ out.push({
399
+ field: w.field,
400
+ from: w.from,
401
+ to: w.to,
402
+ });
403
+ }
404
+ return out;
405
+ }
406
+ const sameWindow = (a, b) => a.field === b.field && a.from === b.from && a.to === b.to;
407
+ const describe = (w) => `${w.field} ${w.from} to ${w.to}`;
408
+ /** Compare two key values: false before true, numbers by value, strings by code point. */
409
+ export function compareScalar(a, b) {
410
+ if (typeof a === "number" && typeof b === "number")
411
+ return a - b;
412
+ if (typeof a === "boolean" && typeof b === "boolean")
413
+ return Number(a) - Number(b);
414
+ const x = [...String(a)].map((c) => c.codePointAt(0));
415
+ const y = [...String(b)].map((c) => c.codePointAt(0));
416
+ for (let i = 0; i < Math.min(x.length, y.length); i++)
417
+ if (x[i] !== y[i])
418
+ return x[i] - y[i];
419
+ return x.length - y.length;
420
+ }
421
+ const keyText = (keys, key) => JSON.stringify(keys.map((k) => [typeof key[k], key[k]]));
422
+ /**
423
+ * Check one spec against the dataset and return what the page draws. The
424
+ * checks run in the design note's order (section 3), and each refuses with
425
+ * its own reason: the subset; the dataset; withheld rows; fields; window;
426
+ * runs; population; values.
427
+ */
428
+ export function checkChart(value, dataset) {
429
+ const spec = readChartSpec(value);
430
+ if (dataset === undefined)
431
+ refuse("chart-no-dataset", "the report's Result names no dataset (dataset_ref), or the bundle does not disclose it");
432
+ const { plan, rows } = dataset;
433
+ for (const row of rows)
434
+ if (row.header === undefined)
435
+ refuse("chart-row-withheld", `${rowName(row)}: the bundle does not disclose its record to this audience, so the population can't be counted`);
436
+ const { statement, channels, keys, temporal } = spec;
437
+ const aggregate = channels[spec.aggregate];
438
+ // 1. Fields exist and have a type, on the rows they apply to.
439
+ const selected = rows.filter((row) => spec.transform.every((p) => evaluate(p, row)));
440
+ const timestamp = (row, field) => {
441
+ const v = resolveField(headerOf(row), field);
442
+ if (v === MISSING)
443
+ refuse("chart-field-missing", `${rowName(row)} has no ${field}`);
444
+ const day = utcDateOf(v);
445
+ if (day === undefined)
446
+ refuse("chart-field-type", `${rowName(row)}: ${field} is not an RFC 3339 date-time with an offset`);
447
+ return day;
448
+ };
449
+ const keyOf = new Map();
450
+ const amountOf = new Map();
451
+ for (const row of selected) {
452
+ const key = {};
453
+ for (const name of keys) {
454
+ const c = channels[name];
455
+ if (c.type === "temporal") {
456
+ key[name] = unitOf(timestamp(row, c.field), c.timeUnit);
457
+ continue;
458
+ }
459
+ const v = resolveField(headerOf(row), c.field);
460
+ if (v === MISSING)
461
+ refuse("chart-field-missing", `${rowName(row)} has no ${c.field}`);
462
+ if (c.type === "quantitative" ? typeof v !== "number" : !isScalar(v))
463
+ refuse("chart-field-type", `${rowName(row)}: ${c.field} is not ${c.type === "quantitative" ? "a number" : "a string, number or boolean"}`);
464
+ key[name] = v;
465
+ }
466
+ keyOf.set(row, key);
467
+ if (aggregate.aggregate === "sum") {
468
+ const v = resolveField(headerOf(row), aggregate.field);
469
+ if (v === MISSING)
470
+ refuse("chart-field-missing", `${rowName(row)} has no ${aggregate.field}`);
471
+ if (typeof v !== "number" || !Number.isFinite(v))
472
+ refuse("chart-field-type", `${rowName(row)}: ${aggregate.field} is not a number, so it can't be summed`);
473
+ amountOf.set(row, v);
474
+ }
475
+ if (statement.window !== undefined)
476
+ timestamp(row, statement.window.field);
477
+ }
478
+ for (const name of keys) {
479
+ const types = new Set(selected.map((row) => typeof keyOf.get(row)[name]));
480
+ if (types.size > 1)
481
+ refuse("chart-field-type", `${channels[name].field} holds values of more than one type`);
482
+ }
483
+ // 2. Window: the statement, the transform's range filter and the seal agree.
484
+ const windows = sealedWindows(plan);
485
+ const window = statement.window;
486
+ if (temporal !== undefined && window === undefined)
487
+ refuse("chart-window-mismatch", "a temporal chart states its window (usermeta.capsule.window)", "/usermeta/capsule");
488
+ if (window !== undefined) {
489
+ const restated = spec.transform.some((p) => p.kind === "range" &&
490
+ p.field === window.field &&
491
+ p.from === window.from &&
492
+ p.to === window.to);
493
+ if (!restated)
494
+ refuse("chart-window-mismatch", `the transform has no range filter over ${describe(window)} with timeUnit utcyearmonthdate`, "/transform");
495
+ if (temporal !== undefined && channels[temporal].field !== window.field)
496
+ refuse("chart-window-mismatch", `the time axis reads ${channels[temporal].field}, the window ${window.field}`, pointerOf(pointerOf("/encoding", temporal), "field"));
497
+ if (windows.length === 1 && !sameWindow(window, windows[0]))
498
+ refuse("chart-window-mismatch", `the chart's window is ${describe(window)}, the sealed window ${describe(windows[0])}`, "/usermeta/capsule/window");
499
+ for (const sealed of windows)
500
+ if (sealed.field === window.field &&
501
+ (window.from < sealed.from || window.to > sealed.to))
502
+ refuse("chart-window-mismatch", `the chart's window ${describe(window)} is not inside the sealed window ${describe(sealed)}`, "/usermeta/capsule/window");
503
+ }
504
+ const units = temporal === undefined
505
+ ? undefined
506
+ : unitsOf(window, channels[temporal].timeUnit);
507
+ // Runs: only a plan with exactly one window node can tell "not run" from
508
+ // zero (spec/evidence-plan-ir-v0.md §5.1), by that node's own field.
509
+ const runs = statement.runs;
510
+ if (windows.length !== 1) {
511
+ if (runs !== undefined)
512
+ refuse("chart-runs-unsealed", `the dataset plan has ${windows.length} window nodes, so no day can read "not run"; this chart states runs`, "/usermeta/capsule/runs");
513
+ }
514
+ else if (temporal !== undefined) {
515
+ if (runs === undefined)
516
+ refuse("chart-runs-missing", "a temporal chart over a windowed plan names its run records (usermeta.capsule.runs)", "/usermeta/capsule");
517
+ }
518
+ if (runs !== undefined && windows.length === 1) {
519
+ if (runs.field !== windows[0].field)
520
+ refuse("chart-runs-field-mismatch", `runs are dated by ${runs.field}; the sealed window field is ${windows[0].field}`, "/usermeta/capsule/runs/field");
521
+ if (temporal === undefined)
522
+ refuse("chart-runs-unsealed", "only a temporal chart can say a unit was not run; this chart has no time axis", "/usermeta/capsule/runs");
523
+ }
524
+ const runRowsOf = new Map();
525
+ const drawsRuns = runs !== undefined && windows.length === 1 && temporal !== undefined;
526
+ if (drawsRuns) {
527
+ const unit = channels[temporal].timeUnit;
528
+ for (const row of rows) {
529
+ if (!evaluate(runs.filter, row))
530
+ continue;
531
+ const day = timestamp(row, runs.field);
532
+ if (day < window.from || day > window.to)
533
+ continue;
534
+ const u = unitOf(day, unit);
535
+ const list = runRowsOf.get(u);
536
+ if (list === undefined)
537
+ runRowsOf.set(u, [row]);
538
+ else
539
+ list.push(row);
540
+ }
541
+ }
542
+ // 3. Population.
543
+ if (selected.length !== statement.population)
544
+ refuse("chart-population-mismatch", `${selected.length} rows pass the transform; the chart states ${statement.population}`, "/usermeta/capsule/population/count");
545
+ // 4. Values: every group of the domain, recomputed.
546
+ const domains = keys.map((name) => name === temporal
547
+ ? units
548
+ : [...new Set(selected.map((row) => keyOf.get(row)[name]))].sort(compareScalar));
549
+ // The stated values list every group, so a domain of another size
550
+ // refuses before it is enumerated: a spec can't make the check build a
551
+ // domain far larger than itself.
552
+ const size = domains.reduce((n, d) => n * d.length, 1);
553
+ if (size !== statement.values.length)
554
+ refuse("chart-aggregate-mismatch", `the chart's domain has ${size} groups; the statement lists ${statement.values.length}`, "/usermeta/capsule/values");
555
+ const rowsByKey = new Map();
556
+ for (const row of selected) {
557
+ const text = keyText(keys, keyOf.get(row));
558
+ const list = rowsByKey.get(text);
559
+ if (list === undefined)
560
+ rowsByKey.set(text, [row]);
561
+ else
562
+ list.push(row);
563
+ }
564
+ const groups = [];
565
+ const product = (i, key) => {
566
+ if (i === keys.length) {
567
+ const counted = rowsByKey.get(keyText(keys, key)) ?? [];
568
+ const unit = temporal === undefined ? undefined : key[temporal];
569
+ const runRows = unit === undefined ? [] : (runRowsOf.get(unit) ?? []);
570
+ const notRun = drawsRuns && runRows.length === 0;
571
+ const value = aggregate.aggregate === "count"
572
+ ? counted.length
573
+ : counted.reduce((sum, row) => sum + amountOf.get(row), 0);
574
+ groups.push({
575
+ key: { ...key },
576
+ ...(notRun ? {} : { value }),
577
+ notRun,
578
+ rows: counted,
579
+ runRows,
580
+ });
581
+ return;
582
+ }
583
+ for (const v of domains[i])
584
+ product(i + 1, { ...key, [keys[i]]: v });
585
+ };
586
+ // A unit with rows but no run record is still not run (§5.1: "a day
587
+ // without a run row was not run"); its rows stay in the population.
588
+ product(0, {});
589
+ const stated = new Map();
590
+ statement.values.forEach((v, i) => {
591
+ const key = {};
592
+ for (const name of keys)
593
+ if (Object.hasOwn(v, name))
594
+ key[name] = v[name];
595
+ const text = keyText(keys, key);
596
+ if (stated.has(text))
597
+ refuse("chart-aggregate-mismatch", `the group ${text} is listed twice`, pointerOf("/usermeta/capsule/values", i));
598
+ stated.set(text, v);
599
+ });
600
+ const want = new Map(groups.map((g) => [keyText(keys, g.key), g]));
601
+ for (const [text, v] of stated) {
602
+ const g = want.get(text);
603
+ const extra = Object.keys(v).filter((k) => k !== "not_run" &&
604
+ k !== spec.aggregate &&
605
+ !keys.includes(k));
606
+ const ok = g !== undefined &&
607
+ extra.length === 0 &&
608
+ (g.notRun
609
+ ? v.not_run === true && !Object.hasOwn(v, spec.aggregate)
610
+ : !Object.hasOwn(v, "not_run") && v[spec.aggregate] === g.value);
611
+ if (!ok)
612
+ refuse("chart-aggregate-mismatch", g === undefined
613
+ ? `the stated group ${text} is not in the chart's domain`
614
+ : `the stated group ${text} does not match the data (${g.notRun ? "not run" : String(g.value)})`, "/usermeta/capsule/values");
615
+ }
616
+ for (const [text, g] of want)
617
+ if (!stated.has(text))
618
+ refuse("chart-aggregate-mismatch", `the group ${text} (${g.notRun ? "not run" : String(g.value)}) is missing from the stated values`, "/usermeta/capsule/values");
619
+ return {
620
+ mark: spec.mark,
621
+ channels,
622
+ aggregate: spec.aggregate,
623
+ keys,
624
+ ...(temporal === undefined ? {} : { temporal }),
625
+ population: selected.length,
626
+ ...(window === undefined ? {} : { window }),
627
+ runs: drawsRuns,
628
+ ...(temporal === undefined
629
+ ? {}
630
+ : {
631
+ units: units.map((unit) => ({
632
+ unit,
633
+ notRun: drawsRuns && (runRowsOf.get(unit) ?? []).length === 0,
634
+ })),
635
+ }),
636
+ groups,
637
+ };
638
+ }
639
+ /** A checked chart's groups in the statement's `values` form, for vectors. */
640
+ export function groupsAsValues(chart) {
641
+ return chart.groups.map((g) => ({
642
+ ...g.key,
643
+ ...(g.notRun ? { not_run: true } : { [chart.aggregate]: g.value }),
644
+ }));
645
+ }
646
+ //# sourceMappingURL=chart-spec.js.map