@opendata-ai/openchart-engine 8.0.0-rc.10 → 8.0.0-rc.12

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 (271) hide show
  1. package/dist/index.d.ts +7 -0
  2. package/dist/index.js +123 -54
  3. package/dist/index.js.map +1 -1
  4. package/package.json +3 -4
  5. package/src/__test-fixtures__/specs.ts +0 -182
  6. package/src/__tests__/__snapshots__/compile-snapshot.test.ts.snap +0 -2401
  7. package/src/__tests__/annotation-behavior.test.ts +0 -852
  8. package/src/__tests__/axes.test.ts +0 -1579
  9. package/src/__tests__/compile-animation.test.ts +0 -161
  10. package/src/__tests__/compile-chart.test.ts +0 -1303
  11. package/src/__tests__/compile-footnotes.test.ts +0 -277
  12. package/src/__tests__/compile-layer.test.ts +0 -969
  13. package/src/__tests__/compile-snapshot.test.ts +0 -156
  14. package/src/__tests__/compound-labels.test.ts +0 -147
  15. package/src/__tests__/dimensions.test.ts +0 -918
  16. package/src/__tests__/encoding-sugar.test.ts +0 -390
  17. package/src/__tests__/facet.test.ts +0 -359
  18. package/src/__tests__/helpers/invariants.ts +0 -299
  19. package/src/__tests__/known-bugs.test.ts +0 -566
  20. package/src/__tests__/layout-fuzz.test.ts +0 -358
  21. package/src/__tests__/layout-invariants.test.ts +0 -535
  22. package/src/__tests__/legend.test.ts +0 -721
  23. package/src/__tests__/mark-keys.test.ts +0 -294
  24. package/src/__tests__/ranking-recipes.test.ts +0 -260
  25. package/src/__tests__/rotation.test.ts +0 -83
  26. package/src/__tests__/scales.test.ts +0 -323
  27. package/src/__tests__/series-search.test.ts +0 -92
  28. package/src/__tests__/spec-sugar.test.ts +0 -801
  29. package/src/__tests__/you-draw-it.test.ts +0 -160
  30. package/src/annotations/__tests__/compute.test.ts +0 -1672
  31. package/src/annotations/__tests__/geometry.test.ts +0 -66
  32. package/src/annotations/__tests__/placement-fuzz.test.ts +0 -256
  33. package/src/annotations/__tests__/placement-invariants.test.ts +0 -345
  34. package/src/annotations/__tests__/placement.test.ts +0 -316
  35. package/src/annotations/__tests__/resolve-text.test.ts +0 -788
  36. package/src/annotations/__tests__/rich-text.test.ts +0 -91
  37. package/src/annotations/__tests__/thinning.test.ts +0 -285
  38. package/src/annotations/collisions.ts +0 -326
  39. package/src/annotations/compute.ts +0 -333
  40. package/src/annotations/constants.ts +0 -162
  41. package/src/annotations/geometry.ts +0 -376
  42. package/src/annotations/move.ts +0 -135
  43. package/src/annotations/placement.ts +0 -636
  44. package/src/annotations/position.ts +0 -131
  45. package/src/annotations/resolve-range.ts +0 -117
  46. package/src/annotations/resolve-refline.ts +0 -157
  47. package/src/annotations/resolve-text.ts +0 -545
  48. package/src/annotations/rich-text.ts +0 -65
  49. package/src/annotations/thinning.ts +0 -190
  50. package/src/barlist/__tests__/compile-barlist.test.ts +0 -200
  51. package/src/barlist/compile-barlist.ts +0 -391
  52. package/src/barlist/types.ts +0 -28
  53. package/src/charts/__tests__/post-process.test.ts +0 -237
  54. package/src/charts/__tests__/registry.test.ts +0 -116
  55. package/src/charts/__tests__/utils.test.ts +0 -195
  56. package/src/charts/_shared/__tests__/density-filter.test.ts +0 -32
  57. package/src/charts/_shared/density-filter.ts +0 -26
  58. package/src/charts/_shared/format-label-value.ts +0 -16
  59. package/src/charts/bar/__tests__/compute.test.ts +0 -934
  60. package/src/charts/bar/__tests__/gradient-orient.test.ts +0 -127
  61. package/src/charts/bar/__tests__/labels.test.ts +0 -292
  62. package/src/charts/bar/compute.ts +0 -539
  63. package/src/charts/bar/index.ts +0 -60
  64. package/src/charts/bar/labels.ts +0 -311
  65. package/src/charts/beeswarm/__tests__/compute.test.ts +0 -280
  66. package/src/charts/beeswarm/__tests__/dodge.test.ts +0 -148
  67. package/src/charts/beeswarm/compute.ts +0 -203
  68. package/src/charts/beeswarm/dodge.ts +0 -155
  69. package/src/charts/beeswarm/index.ts +0 -32
  70. package/src/charts/builtin.ts +0 -75
  71. package/src/charts/calendar/__tests__/compute.test.ts +0 -417
  72. package/src/charts/calendar/compute.ts +0 -319
  73. package/src/charts/calendar/index.ts +0 -32
  74. package/src/charts/column/__tests__/compute.test.ts +0 -540
  75. package/src/charts/column/__tests__/labels.test.ts +0 -179
  76. package/src/charts/column/compute.ts +0 -493
  77. package/src/charts/column/index.ts +0 -53
  78. package/src/charts/column/labels.ts +0 -229
  79. package/src/charts/dot/__tests__/compute.test.ts +0 -380
  80. package/src/charts/dot/__tests__/labels.test.ts +0 -98
  81. package/src/charts/dot/compute.ts +0 -285
  82. package/src/charts/dot/index.ts +0 -62
  83. package/src/charts/dot/labels.ts +0 -121
  84. package/src/charts/line/__tests__/compute.test.ts +0 -1194
  85. package/src/charts/line/__tests__/curves.test.ts +0 -51
  86. package/src/charts/line/__tests__/labels.test.ts +0 -94
  87. package/src/charts/line/__tests__/mark-options.test.ts +0 -175
  88. package/src/charts/line/area.ts +0 -484
  89. package/src/charts/line/compute.ts +0 -356
  90. package/src/charts/line/curves.ts +0 -85
  91. package/src/charts/line/index.ts +0 -176
  92. package/src/charts/line/labels.ts +0 -177
  93. package/src/charts/parliament/__tests__/compute.test.ts +0 -411
  94. package/src/charts/parliament/compute.ts +0 -313
  95. package/src/charts/parliament/index.ts +0 -32
  96. package/src/charts/pie/__tests__/compute.test.ts +0 -384
  97. package/src/charts/pie/__tests__/labels.test.ts +0 -132
  98. package/src/charts/pie/compute.ts +0 -324
  99. package/src/charts/pie/index.ts +0 -49
  100. package/src/charts/pie/labels.ts +0 -143
  101. package/src/charts/post-process.ts +0 -229
  102. package/src/charts/range/__tests__/compute.test.ts +0 -486
  103. package/src/charts/range/compute.ts +0 -273
  104. package/src/charts/range/index.ts +0 -82
  105. package/src/charts/range/labels.ts +0 -169
  106. package/src/charts/rect/__tests__/compute.test.ts +0 -120
  107. package/src/charts/rect/index.ts +0 -127
  108. package/src/charts/registry.ts +0 -72
  109. package/src/charts/rule/index.ts +0 -139
  110. package/src/charts/scatter/__tests__/compute.test.ts +0 -488
  111. package/src/charts/scatter/__tests__/trendline.test.ts +0 -191
  112. package/src/charts/scatter/compute.ts +0 -192
  113. package/src/charts/scatter/index.ts +0 -46
  114. package/src/charts/scatter/trendline.ts +0 -100
  115. package/src/charts/text/__tests__/compute.test.ts +0 -307
  116. package/src/charts/text/index.ts +0 -141
  117. package/src/charts/tick/__tests__/compute.test.ts +0 -75
  118. package/src/charts/tick/index.ts +0 -99
  119. package/src/charts/utils.ts +0 -170
  120. package/src/charts/waffle/__tests__/compute.test.ts +0 -305
  121. package/src/charts/waffle/compute.ts +0 -197
  122. package/src/charts/waffle/index.ts +0 -31
  123. package/src/compile/__tests__/color-scale-range.test.ts +0 -158
  124. package/src/compile/__tests__/color-scale-reverse.test.ts +0 -89
  125. package/src/compile/__tests__/data-clip.test.ts +0 -127
  126. package/src/compile/__tests__/fill-patterns.test.ts +0 -154
  127. package/src/compile/__tests__/size-scale.test.ts +0 -108
  128. package/src/compile/__tests__/watermark-obstacle.test.ts +0 -93
  129. package/src/compile/color-scale-range.ts +0 -101
  130. package/src/compile/data-clip.ts +0 -48
  131. package/src/compile/fill-patterns.ts +0 -74
  132. package/src/compile/layer.ts +0 -630
  133. package/src/compile/size-scale.ts +0 -141
  134. package/src/compile/spec-sugar.ts +0 -767
  135. package/src/compile/watermark-obstacle.ts +0 -54
  136. package/src/compile/you-draw-it.ts +0 -123
  137. package/src/compile.ts +0 -1548
  138. package/src/compiler/__tests__/a11y-warnings.test.ts +0 -148
  139. package/src/compiler/__tests__/animation.test.ts +0 -177
  140. package/src/compiler/__tests__/compile.test.ts +0 -87
  141. package/src/compiler/__tests__/fixtures/vl-parity/axis-null.json +0 -19
  142. package/src/compiler/__tests__/fixtures/vl-parity/color-value.json +0 -20
  143. package/src/compiler/__tests__/fixtures/vl-parity/count-aggregate.json +0 -22
  144. package/src/compiler/__tests__/fixtures/vl-parity/data-values.json +0 -19
  145. package/src/compiler/__tests__/fixtures/vl-parity/layer-axis-null.json +0 -14
  146. package/src/compiler/__tests__/fixtures/vl-parity/layer-count.json +0 -34
  147. package/src/compiler/__tests__/fixtures/vl-parity/layer-data-values.json +0 -22
  148. package/src/compiler/__tests__/fixtures/vl-parity/layer-legend-null.json +0 -41
  149. package/src/compiler/__tests__/fixtures/vl-parity/layer-scheme.json +0 -38
  150. package/src/compiler/__tests__/fixtures/vl-parity/layer-sort.json +0 -28
  151. package/src/compiler/__tests__/fixtures/vl-parity/layer-theta.json +0 -28
  152. package/src/compiler/__tests__/fixtures/vl-parity/layer-title.json +0 -30
  153. package/src/compiler/__tests__/fixtures/vl-parity/layer-value-def.json +0 -29
  154. package/src/compiler/__tests__/fixtures/vl-parity/legend-null.json +0 -32
  155. package/src/compiler/__tests__/fixtures/vl-parity/scheme.json +0 -25
  156. package/src/compiler/__tests__/fixtures/vl-parity/sort-by-value.json +0 -19
  157. package/src/compiler/__tests__/fixtures/vl-parity/theta-arc.json +0 -19
  158. package/src/compiler/__tests__/fixtures/vl-parity/title-subtitle.json +0 -21
  159. package/src/compiler/__tests__/fixtures/vl-parity/width-height.json +0 -23
  160. package/src/compiler/__tests__/keys.test.ts +0 -83
  161. package/src/compiler/__tests__/normalize-highlight.test.ts +0 -103
  162. package/src/compiler/__tests__/normalize.test.ts +0 -399
  163. package/src/compiler/__tests__/sparkline-defaults.test.ts +0 -153
  164. package/src/compiler/__tests__/validate-did-you-mean.test.ts +0 -170
  165. package/src/compiler/__tests__/validate-highlight.test.ts +0 -112
  166. package/src/compiler/__tests__/validate-near-miss.test.ts +0 -251
  167. package/src/compiler/__tests__/validate.test.ts +0 -731
  168. package/src/compiler/__tests__/vl-parity.test.ts +0 -68
  169. package/src/compiler/a11y-warnings.ts +0 -110
  170. package/src/compiler/animation.ts +0 -142
  171. package/src/compiler/index.ts +0 -47
  172. package/src/compiler/keys.ts +0 -55
  173. package/src/compiler/normalize.ts +0 -734
  174. package/src/compiler/sparkline-defaults.ts +0 -138
  175. package/src/compiler/types.ts +0 -241
  176. package/src/compiler/validate.ts +0 -2093
  177. package/src/endpoint-labels/__tests__/compute.test.ts +0 -587
  178. package/src/endpoint-labels/compute.ts +0 -621
  179. package/src/endpoint-labels/constants.ts +0 -54
  180. package/src/endpoint-labels/format.ts +0 -60
  181. package/src/endpoint-labels/predict.ts +0 -139
  182. package/src/format/__tests__/field-format.test.ts +0 -164
  183. package/src/format/field-format.ts +0 -27
  184. package/src/geo/__tests__/compile-map.test.ts +0 -1128
  185. package/src/geo/compile-map.ts +0 -1376
  186. package/src/geo/join.ts +0 -115
  187. package/src/geo/projections.ts +0 -65
  188. package/src/geo/types.ts +0 -26
  189. package/src/graphs/__tests__/community.test.ts +0 -228
  190. package/src/graphs/__tests__/compile-graph.test.ts +0 -396
  191. package/src/graphs/__tests__/encoding.test.ts +0 -415
  192. package/src/graphs/community.ts +0 -92
  193. package/src/graphs/compile-graph.ts +0 -329
  194. package/src/graphs/encoding.ts +0 -356
  195. package/src/graphs/types.ts +0 -106
  196. package/src/index.ts +0 -177
  197. package/src/layout/__tests__/metrics.test.ts +0 -97
  198. package/src/layout/__tests__/scales-highlight.test.ts +0 -192
  199. package/src/layout/axes/rotation.ts +0 -152
  200. package/src/layout/axes/thinning.ts +0 -98
  201. package/src/layout/axes/ticks.ts +0 -409
  202. package/src/layout/axes.ts +0 -757
  203. package/src/layout/dimensions.ts +0 -912
  204. package/src/layout/facet.ts +0 -91
  205. package/src/layout/gridlines.ts +0 -84
  206. package/src/layout/metrics.ts +0 -132
  207. package/src/layout/plan.ts +0 -631
  208. package/src/layout/scales.ts +0 -1053
  209. package/src/layout/shared.ts +0 -44
  210. package/src/legend/__tests__/continuous.test.ts +0 -318
  211. package/src/legend/__tests__/redundancy.test.ts +0 -108
  212. package/src/legend/__tests__/size.test.ts +0 -348
  213. package/src/legend/__tests__/suppression.test.ts +0 -382
  214. package/src/legend/compute.ts +0 -748
  215. package/src/legend/continuous.ts +0 -327
  216. package/src/legend/size.ts +0 -407
  217. package/src/legend/suppression.ts +0 -226
  218. package/src/legend/wrap.ts +0 -117
  219. package/src/sankey/__tests__/compile-sankey.test.ts +0 -458
  220. package/src/sankey/__tests__/layout.test.ts +0 -165
  221. package/src/sankey/__tests__/node-label-wrap.test.ts +0 -114
  222. package/src/sankey/__tests__/node-sort.test.ts +0 -45
  223. package/src/sankey/compile-sankey.ts +0 -706
  224. package/src/sankey/layout.ts +0 -184
  225. package/src/sankey/types.ts +0 -41
  226. package/src/tables/__tests__/bar-column.test.ts +0 -147
  227. package/src/tables/__tests__/category-colors.test.ts +0 -230
  228. package/src/tables/__tests__/compile-table.test.ts +0 -236
  229. package/src/tables/__tests__/format-cells.test.ts +0 -143
  230. package/src/tables/__tests__/heatmap.test.ts +0 -148
  231. package/src/tables/__tests__/pagination.test.ts +0 -78
  232. package/src/tables/__tests__/search.test.ts +0 -94
  233. package/src/tables/__tests__/sort.test.ts +0 -107
  234. package/src/tables/__tests__/sparkline.test.ts +0 -122
  235. package/src/tables/bar-column.ts +0 -94
  236. package/src/tables/category-colors.ts +0 -78
  237. package/src/tables/compile-table.ts +0 -427
  238. package/src/tables/format-cells.ts +0 -115
  239. package/src/tables/heatmap.ts +0 -141
  240. package/src/tables/pagination.ts +0 -46
  241. package/src/tables/search.ts +0 -66
  242. package/src/tables/sort.ts +0 -69
  243. package/src/tables/sparkline.ts +0 -113
  244. package/src/tables/utils.ts +0 -16
  245. package/src/tilemap/__tests__/compile-tilemap.test.ts +0 -576
  246. package/src/tilemap/compile-tilemap.ts +0 -755
  247. package/src/tilemap/layout.ts +0 -172
  248. package/src/tilemap/types.ts +0 -33
  249. package/src/tooltips/__tests__/compute.test.ts +0 -582
  250. package/src/tooltips/compute.ts +0 -700
  251. package/src/transforms/__tests__/aggregate.test.ts +0 -159
  252. package/src/transforms/__tests__/bin.test.ts +0 -88
  253. package/src/transforms/__tests__/calculate.test.ts +0 -146
  254. package/src/transforms/__tests__/conditional.test.ts +0 -127
  255. package/src/transforms/__tests__/filter-relative.test.ts +0 -202
  256. package/src/transforms/__tests__/filter.test.ts +0 -59
  257. package/src/transforms/__tests__/fold.test.ts +0 -79
  258. package/src/transforms/__tests__/index.test.ts +0 -93
  259. package/src/transforms/__tests__/predicates.test.ts +0 -193
  260. package/src/transforms/__tests__/timeunit.test.ts +0 -129
  261. package/src/transforms/__tests__/window.test.ts +0 -286
  262. package/src/transforms/aggregate.ts +0 -131
  263. package/src/transforms/bin.ts +0 -87
  264. package/src/transforms/calculate.ts +0 -60
  265. package/src/transforms/conditional.ts +0 -46
  266. package/src/transforms/filter.ts +0 -122
  267. package/src/transforms/fold.ts +0 -49
  268. package/src/transforms/index.ts +0 -60
  269. package/src/transforms/predicates.ts +0 -123
  270. package/src/transforms/timeunit.ts +0 -88
  271. package/src/transforms/window.ts +0 -185
@@ -1,2093 +0,0 @@
1
- /**
2
- * Runtime spec validation.
3
- *
4
- * TypeScript catches compile-time errors for specs written in code.
5
- * This module catches runtime errors for specs coming from JSON, APIs,
6
- * or Claude-generated output where the TypeScript compiler can't help.
7
- *
8
- * Every error includes a machine-readable code and an actionable suggestion
9
- * so consumers (and LLMs) can fix issues programmatically.
10
- */
11
-
12
- import {
13
- type FieldType,
14
- inferFieldType,
15
- MARK_ENCODING_RULES,
16
- MARK_TYPES,
17
- type MarkType,
18
- resolveSchemeName,
19
- SEQUENTIAL_PALETTES,
20
- SUPPORTED_SCHEME_NAMES,
21
- type VizSpec,
22
- } from '@opendata-ai/openchart-core';
23
-
24
- import type { ValidationError, ValidationResult } from './types';
25
-
26
- // ---------------------------------------------------------------------------
27
- // Helpers
28
- // ---------------------------------------------------------------------------
29
-
30
- const VALID_FIELD_TYPES = new Set<string>(['quantitative', 'temporal', 'nominal', 'ordinal']);
31
-
32
- const VALID_DARK_MODES = new Set<string>(['auto', 'force', 'off']);
33
-
34
- /** Check if a value looks like a parseable date. */
35
- function isParseableDate(value: unknown): boolean {
36
- if (value instanceof Date) return !Number.isNaN(value.getTime());
37
- if (typeof value === 'string') {
38
- const d = new Date(value);
39
- return !Number.isNaN(d.getTime());
40
- }
41
- if (typeof value === 'number') return true;
42
- return false;
43
- }
44
-
45
- /** Check if a value is numeric. */
46
- function isNumeric(value: unknown): boolean {
47
- if (typeof value === 'number') return Number.isFinite(value);
48
- if (typeof value === 'string') {
49
- const n = Number(value);
50
- return !Number.isNaN(n) && Number.isFinite(n);
51
- }
52
- return false;
53
- }
54
-
55
- /**
56
- * Levenshtein edit distance between two strings (case-insensitive). Used to
57
- * turn a misspelled field reference into a "did you mean" repair hint.
58
- */
59
- function editDistance(a: string, b: string): number {
60
- const s = a.toLowerCase();
61
- const t = b.toLowerCase();
62
- const m = s.length;
63
- const n = t.length;
64
- if (m === 0) return n;
65
- if (n === 0) return m;
66
- // Single-row DP: prev[j] holds distance for the previous source char.
67
- let prev = Array.from({ length: n + 1 }, (_, j) => j);
68
- let curr = new Array<number>(n + 1);
69
- for (let i = 1; i <= m; i++) {
70
- curr[0] = i;
71
- for (let j = 1; j <= n; j++) {
72
- const cost = s[i - 1] === t[j - 1] ? 0 : 1;
73
- curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);
74
- }
75
- [prev, curr] = [curr, prev];
76
- }
77
- return prev[n];
78
- }
79
-
80
- /**
81
- * Given a misspelled field name and the actual data columns, return the nearest
82
- * column when it is close enough to be a plausible typo, else undefined.
83
- *
84
- * The threshold scales with word length (at most ~40% of the target length, and
85
- * never more than 3 edits) so short columns don't match unrelated names.
86
- */
87
- function nearestColumn(field: string, columns: string[]): string | undefined {
88
- let best: string | undefined;
89
- let bestDistance = Number.POSITIVE_INFINITY;
90
- for (const column of columns) {
91
- const distance = editDistance(field, column);
92
- if (distance < bestDistance) {
93
- bestDistance = distance;
94
- best = column;
95
- }
96
- }
97
- if (best === undefined) return undefined;
98
- const threshold = Math.min(3, Math.max(1, Math.floor(best.length * 0.4)));
99
- return bestDistance <= threshold ? best : undefined;
100
- }
101
-
102
- /**
103
- * Build the "did you mean" clause appended to DATA_FIELD_MISSING suggestions.
104
- * Returns an empty string when no column is a plausible near-match.
105
- */
106
- function didYouMean(field: string, columns: string[]): string {
107
- const match = nearestColumn(field, columns);
108
- return match ? ` Did you mean "${match}"?` : '';
109
- }
110
-
111
- /**
112
- * Push an INVALID_VALUE error when a channel carries an unrecognized
113
- * scale.scheme name. Chart specs are the only family that consumes schemes
114
- * this way: known names (including VL aliases) resolve via the core palette
115
- * registry and are expanded to scale.range by the pre-validation sugar pass,
116
- * so `resolveSchemeName` failing means the name is unknown.
117
- */
118
- function checkSchemeName(
119
- channelObj: Record<string, unknown>,
120
- channelPath: string,
121
- errors: ValidationError[],
122
- ): void {
123
- const scale = channelObj.scale as Record<string, unknown> | undefined;
124
- if (scale && typeof scale.scheme === 'string' && !resolveSchemeName(scale.scheme)) {
125
- errors.push({
126
- message: `Spec error: ${channelPath}.scale.scheme "${scale.scheme}" is not a supported scheme name`,
127
- path: `${channelPath}.scale.scheme`,
128
- code: 'INVALID_VALUE',
129
- suggestion: `Use one of the supported scheme names: ${[...SUPPORTED_SCHEME_NAMES].join(', ')}. Or provide explicit colors via scale.range.`,
130
- });
131
- }
132
- }
133
-
134
- /**
135
- * Push an INVALID_VALUE error when any channel of an encoding block carries a
136
- * scale.scheme on a spec family whose compile path never reads it. Even a
137
- * known scheme name is dead config there — silently accepting it would leave
138
- * the author believing they chose the colors.
139
- */
140
- function checkSchemeUnused(
141
- encoding: Record<string, unknown>,
142
- errors: ValidationError[],
143
- familyNote: string,
144
- suggestion: string,
145
- ): void {
146
- for (const [channel, ch] of Object.entries(encoding)) {
147
- if (!ch || typeof ch !== 'object' || Array.isArray(ch)) continue;
148
- const scale = (ch as Record<string, unknown>).scale as Record<string, unknown> | undefined;
149
- if (scale && typeof scale.scheme === 'string') {
150
- errors.push({
151
- message: `Spec error: encoding.${channel}.scale.scheme has no effect — ${familyNote}`,
152
- path: `encoding.${channel}.scale.scheme`,
153
- code: 'INVALID_VALUE',
154
- suggestion,
155
- });
156
- }
157
- }
158
- }
159
-
160
- /** Palette names the map compile path actually supports (sequential only). */
161
- const MAP_PALETTE_NAMES = Object.keys(SEQUENTIAL_PALETTES).join(', ');
162
-
163
- /**
164
- * Map color channels resolve scale.scheme against SEQUENTIAL_PALETTES with a
165
- * silent fallback to blue — a typo'd scheme would render the default palette
166
- * with no signal. Reject names outside the map's supported set here instead.
167
- * Categorical channels never read schemes at all (colors come from
168
- * scale.domain/scale.range), so any scheme there is dead config.
169
- */
170
- function checkMapSchemeName(
171
- channelObj: Record<string, unknown>,
172
- channelPath: string,
173
- errors: ValidationError[],
174
- ): void {
175
- const scale = channelObj.scale as Record<string, unknown> | undefined;
176
- if (!scale || typeof scale.scheme !== 'string') return;
177
-
178
- if (channelObj.type === 'nominal' || channelObj.type === 'ordinal') {
179
- errors.push({
180
- message: `Spec error: ${channelPath}.scale.scheme has no effect — categorical map colors come from scale.range and scale.domain`,
181
- path: `${channelPath}.scale.scheme`,
182
- code: 'INVALID_VALUE',
183
- suggestion:
184
- 'Remove scale.scheme. To customize categorical map colors, provide explicit colors via scale.range (with scale.domain for category order).',
185
- });
186
- return;
187
- }
188
-
189
- if (!(scale.scheme in SEQUENTIAL_PALETTES)) {
190
- errors.push({
191
- message: `Spec error: ${channelPath}.scale.scheme "${scale.scheme}" is not a supported map palette`,
192
- path: `${channelPath}.scale.scheme`,
193
- code: 'INVALID_VALUE',
194
- suggestion: `Maps support the sequential palettes: ${MAP_PALETTE_NAMES}. The default is "blue".`,
195
- });
196
- }
197
- }
198
-
199
- // ---------------------------------------------------------------------------
200
- // Range mark validation
201
- // ---------------------------------------------------------------------------
202
-
203
- const VALID_RANGE_STYLES = new Set(['dumbbell', 'arrow', 'bar']);
204
-
205
- /**
206
- * Range marks need an orientation-dependent encoding pair: x + x2 when the
207
- * category axis is y (horizontal, the common editorial form), or y + y2 when
208
- * the category axis is x (vertical). The static MARK_ENCODING_RULES table
209
- * can't express "x2 required only when y is categorical", so this check
210
- * enforces it with errors naming exactly what to add.
211
- */
212
- function validateRangeSpec(spec: Record<string, unknown>, errors: ValidationError[]): void {
213
- const encoding = spec.encoding as Record<string, Record<string, unknown> | undefined>;
214
- const data = spec.data as Record<string, unknown>[];
215
- const x = encoding.x;
216
- const y = encoding.y;
217
- // Missing x/y already produced MISSING_FIELD errors from the generic loop.
218
- if (!x?.field || typeof x.field !== 'string' || !y?.field || typeof y.field !== 'string') {
219
- return;
220
- }
221
-
222
- const xType = (x.type as string | undefined) ?? inferFieldType(data, x.field);
223
- const yType = (y.type as string | undefined) ?? inferFieldType(data, y.field);
224
- const xIsCategory = xType === 'nominal' || xType === 'ordinal';
225
- const yIsCategory = yType === 'nominal' || yType === 'ordinal';
226
-
227
- if (xIsCategory && yIsCategory) {
228
- errors.push({
229
- message:
230
- 'Spec error: range chart requires a quantitative value axis, but both encoding.x and encoding.y are categorical',
231
- path: 'encoding',
232
- code: 'ENCODING_MISMATCH',
233
- suggestion:
234
- 'Map the range start to a quantitative channel: x (with x2 for the end) for horizontal ranges, or y (with y2) for vertical ranges',
235
- });
236
- return;
237
- }
238
- if (!xIsCategory && !yIsCategory) {
239
- errors.push({
240
- message:
241
- 'Spec error: range chart requires a nominal or ordinal category axis, but neither encoding.x nor encoding.y is categorical',
242
- path: 'encoding',
243
- code: 'ENCODING_MISMATCH',
244
- suggestion:
245
- 'Set encoding.y to a nominal field for horizontal ranges (the common form), or encoding.x for vertical ranges',
246
- });
247
- return;
248
- }
249
-
250
- const availableColumns = data.length > 0 ? Object.keys(data[0]).join(', ') : '';
251
- if (yIsCategory) {
252
- // Horizontal: x is the range start, x2 the end.
253
- if (!encoding.x2) {
254
- errors.push({
255
- message:
256
- 'Spec error: range chart requires encoding.x2 (the range end) when encoding.y is the category axis, but none was provided',
257
- path: 'encoding.x2',
258
- code: 'MISSING_FIELD',
259
- suggestion: `Add encoding.x2 with the field holding the range's end value, e.g. x2: { field: "endValue" }. Available columns: ${availableColumns}`,
260
- });
261
- }
262
- if (encoding.y2) {
263
- errors.push({
264
- message:
265
- 'Spec error: encoding.y2 is not used on a horizontal range chart (category axis on y); the range end belongs on x2',
266
- path: 'encoding.y2',
267
- code: 'INVALID_VALUE',
268
- suggestion:
269
- 'Remove encoding.y2, or move the category to encoding.x and the values to y/y2 for a vertical range chart',
270
- });
271
- }
272
- } else {
273
- // Vertical: y is the range start, y2 the end.
274
- if (!encoding.y2) {
275
- errors.push({
276
- message:
277
- 'Spec error: range chart requires encoding.y2 (the range end) when encoding.x is the category axis, but none was provided',
278
- path: 'encoding.y2',
279
- code: 'MISSING_FIELD',
280
- suggestion: `Add encoding.y2 with the field holding the range's end value, e.g. y2: { field: "endValue" }. Available columns: ${availableColumns}`,
281
- });
282
- }
283
- if (encoding.x2) {
284
- errors.push({
285
- message:
286
- 'Spec error: encoding.x2 is not used on a vertical range chart (category axis on x); the range end belongs on y2',
287
- path: 'encoding.x2',
288
- code: 'INVALID_VALUE',
289
- suggestion:
290
- 'Remove encoding.x2, or move the category to encoding.y and the values to x/x2 for a horizontal range chart',
291
- });
292
- }
293
- }
294
-
295
- // markDef options: style must be one of the known variants.
296
- const mark = spec.mark;
297
- if (mark && typeof mark === 'object' && !Array.isArray(mark)) {
298
- const style = (mark as Record<string, unknown>).style;
299
- if (style !== undefined && !VALID_RANGE_STYLES.has(style as string)) {
300
- errors.push({
301
- message: `Spec error: mark.style "${style}" is not valid for range marks. Must be one of: dumbbell, arrow, bar`,
302
- path: 'mark.style',
303
- code: 'INVALID_VALUE',
304
- suggestion:
305
- 'Use mark: { type: "range", style: "dumbbell" } (default), "arrow" for directional change, or "bar" for a plain floating range bar',
306
- });
307
- }
308
- }
309
- }
310
-
311
- // ---------------------------------------------------------------------------
312
- // Calendar mark validation
313
- // ---------------------------------------------------------------------------
314
-
315
- const VALID_WEEK_STARTS = new Set(['monday', 'sunday']);
316
-
317
- /**
318
- * Calendar heatmaps take daily dates on x and a quantitative value on color;
319
- * the weeks-x-weekdays geometry is computed internally, so there is no y
320
- * channel. This check enforces the parts the static MARK_ENCODING_RULES
321
- * table can't express: no y, a temporal x even when the type is inferred,
322
- * every date parseable, one row per day (daily granularity), and valid
323
- * mark-level weekStart/cellRadius options.
324
- */
325
- function validateCalendarSpec(spec: Record<string, unknown>, errors: ValidationError[]): void {
326
- const encoding = spec.encoding as Record<string, Record<string, unknown> | undefined>;
327
- const data = spec.data as Record<string, unknown>[];
328
-
329
- if (encoding.y) {
330
- errors.push({
331
- message:
332
- 'Spec error: calendar chart does not accept encoding.y (the weeks x weekdays layout is computed from the dates)',
333
- path: 'encoding.y',
334
- code: 'ENCODING_MISMATCH',
335
- suggestion:
336
- 'Remove encoding.y. A calendar needs only x (temporal, daily dates) and color (quantitative).',
337
- });
338
- }
339
-
340
- // Mark-level options (weekStart / cellRadius) on the MarkDef object form.
341
- if (spec.mark && typeof spec.mark === 'object') {
342
- const markDef = spec.mark as Record<string, unknown>;
343
- if (markDef.weekStart !== undefined && !VALID_WEEK_STARTS.has(markDef.weekStart as string)) {
344
- errors.push({
345
- message: `Spec error: mark.weekStart "${markDef.weekStart}" is not a valid week start`,
346
- path: 'mark.weekStart',
347
- code: 'INVALID_VALUE',
348
- suggestion:
349
- 'Use mark: { type: "calendar", weekStart: "monday" } (default, ISO weeks) or "sunday"',
350
- });
351
- }
352
- if (
353
- markDef.cellRadius !== undefined &&
354
- (typeof markDef.cellRadius !== 'number' ||
355
- !Number.isFinite(markDef.cellRadius) ||
356
- markDef.cellRadius < 0)
357
- ) {
358
- errors.push({
359
- message: `Spec error: mark.cellRadius must be a non-negative number, got ${JSON.stringify(markDef.cellRadius)}`,
360
- path: 'mark.cellRadius',
361
- code: 'INVALID_VALUE',
362
- suggestion:
363
- 'Use a pixel radius like cellRadius: 1 (default) or cellRadius: 0 for square corners',
364
- });
365
- }
366
- }
367
-
368
- const x = encoding.x;
369
- // Missing x already produced a MISSING_FIELD error from the generic loop.
370
- if (!x?.field || typeof x.field !== 'string') return;
371
-
372
- // The generic loop rejects a declared non-temporal type against the
373
- // encoding rules table; this catches the inferred case (type omitted).
374
- const xType = (x.type as string | undefined) ?? inferFieldType(data, x.field);
375
- if (xType !== 'temporal') {
376
- if (!x.type) {
377
- errors.push({
378
- message: `Spec error: calendar chart requires temporal encoding.x, but "${x.field}" was inferred as ${xType}`,
379
- path: 'encoding.x',
380
- code: 'ENCODING_MISMATCH',
381
- suggestion: `Provide daily dates in "${x.field}" (ISO 8601 strings like "2024-01-15" or Date objects) and declare x: { field: "${x.field}", type: "temporal" }`,
382
- });
383
- }
384
- return;
385
- }
386
-
387
- // Transforms (e.g. a timeUnit aggregation) reshape the data before the
388
- // calendar sees it, so per-row date checks only apply to untransformed specs.
389
- if (Array.isArray(spec.transform) && spec.transform.length > 0) return;
390
-
391
- // Every date must parse; report the first offender by row index.
392
- for (let i = 0; i < data.length; i++) {
393
- const value = data[i][x.field];
394
- if (value != null && !isParseableDate(value)) {
395
- errors.push({
396
- message: `Spec error: encoding.x.field "${x.field}" contains an unparseable date at data[${i}]: ${JSON.stringify(value)}`,
397
- path: `data[${i}].${x.field}`,
398
- code: 'INVALID_VALUE',
399
- suggestion: `Fix data[${i}].${x.field} to a parseable date (ISO 8601 strings like "2024-01-15" or Date objects)`,
400
- });
401
- return;
402
- }
403
- }
404
-
405
- // Daily granularity: more than one row on the same UTC day means the data
406
- // is sub-daily (or duplicated) and cells would silently overwrite.
407
- const seenDays = new Map<string, number>();
408
- for (let i = 0; i < data.length; i++) {
409
- const value = data[i][x.field];
410
- if (value == null) continue;
411
- const date = value instanceof Date ? value : new Date(value as string | number);
412
- if (Number.isNaN(date.getTime())) continue;
413
- const dayKey = `${date.getUTCFullYear()}-${date.getUTCMonth()}-${date.getUTCDate()}`;
414
- const firstIndex = seenDays.get(dayKey);
415
- if (firstIndex !== undefined) {
416
- errors.push({
417
- message: `Spec error: calendar chart requires daily granularity, but data[${firstIndex}] and data[${i}] fall on the same day (${JSON.stringify(value)})`,
418
- path: `data[${i}].${x.field}`,
419
- code: 'ENCODING_MISMATCH',
420
- suggestion: `Aggregate to one row per day first, e.g. transform: [{ timeUnit: "yearmonthdate", field: "${x.field}", as: "day" }] plus an aggregate over the value field, or pre-aggregate the data.`,
421
- });
422
- return;
423
- }
424
- seenDays.set(dayKey, i);
425
- }
426
- }
427
-
428
- // ---------------------------------------------------------------------------
429
- // Chart validation
430
- // ---------------------------------------------------------------------------
431
-
432
- function validateChartSpec(spec: Record<string, unknown>, errors: ValidationError[]): void {
433
- const markType =
434
- typeof spec.mark === 'string' ? spec.mark : (spec.mark as Record<string, unknown>)?.type;
435
-
436
- // Check data
437
- if (!Array.isArray(spec.data)) {
438
- // Near-miss: the VL `data: { url }` form. Fetching is out of scope for a
439
- // rendering library, so reject it with a pointed message. The `{ values }`
440
- // form is unwrapped by the pre-validation sugar expansion and never
441
- // reaches this check on the compile path.
442
- if (spec.data && typeof spec.data === 'object' && 'url' in (spec.data as object)) {
443
- errors.push({
444
- message: 'Spec error: data.url is not supported (openchart does not fetch remote data)',
445
- path: 'data.url',
446
- code: 'INVALID_VALUE',
447
- suggestion:
448
- 'Fetch the data in your application and provide the rows inline: data: [...] or data: { values: [...] }',
449
- });
450
- return;
451
- }
452
- errors.push({
453
- message: 'Spec error: "data" must be an array',
454
- path: 'data',
455
- code: 'INVALID_TYPE',
456
- suggestion: 'Provide data as an array of objects, e.g. data: [{ x: 1, y: 2 }]',
457
- });
458
- return; // Can't validate further without data
459
- }
460
-
461
- if (spec.data.length === 0) {
462
- errors.push({
463
- message: 'Spec error: "data" must be a non-empty array',
464
- path: 'data',
465
- code: 'EMPTY_DATA',
466
- suggestion: 'Add at least one data row, e.g. data: [{ x: 1, y: 2 }]',
467
- });
468
- return;
469
- }
470
-
471
- // Validate data entries are objects
472
- const firstRow = spec.data[0] as unknown;
473
- if (typeof firstRow !== 'object' || firstRow === null || Array.isArray(firstRow)) {
474
- errors.push({
475
- message: 'Spec error: each item in "data" must be a plain object',
476
- path: 'data[0]',
477
- code: 'INVALID_TYPE',
478
- suggestion:
479
- 'Each data item should be an object with key-value pairs, e.g. { name: "Alice", value: 10 }',
480
- });
481
- return;
482
- }
483
-
484
- // Check encoding exists
485
- if (!spec.encoding || typeof spec.encoding !== 'object') {
486
- const rules = MARK_ENCODING_RULES[markType as MarkType];
487
- const requiredChannels = Object.entries(rules)
488
- .filter(([, rule]) => rule.required)
489
- .map(([ch]) => ch);
490
- errors.push({
491
- message: `Spec error: ${markType} chart requires an "encoding" object`,
492
- path: 'encoding',
493
- code: 'MISSING_FIELD',
494
- suggestion: `Add an encoding object with required channels: ${requiredChannels.join(', ')}. Example: encoding: { ${requiredChannels.map((ch) => `${ch}: { field: "...", type: "..." }`).join(', ')} }`,
495
- });
496
- return;
497
- }
498
-
499
- const rules = MARK_ENCODING_RULES[markType as MarkType];
500
- const encoding = spec.encoding as Record<string, unknown>;
501
- const dataColumns = new Set(Object.keys(firstRow as Record<string, unknown>));
502
- const columnList = [...dataColumns];
503
- const availableColumns = columnList.join(', ');
504
-
505
- // Validate required channels. Arc's canonical channel is theta; waffle and
506
- // parliament still key on y with theta as an alias. For backward compat,
507
- // validateSpec (a public entry point that callers may invoke on un-expanded
508
- // specs) accepts y as satisfying a theta requirement and vice versa on
509
- // theta-capable marks.
510
- const THETA_MARKS = new Set(['arc', 'waffle', 'parliament']);
511
- const isThetaMark = THETA_MARKS.has(markType as string);
512
- for (const [channel, rule] of Object.entries(rules)) {
513
- if (!rule.required) continue;
514
- const satisfiedByAlias =
515
- isThetaMark && ((channel === 'theta' && encoding.y) || (channel === 'y' && encoding.theta));
516
- if (!encoding[channel] && !satisfiedByAlias) {
517
- const allowedTypes = rule.allowedTypes.join(' or ');
518
- const suggestedChannel = channel === 'y' && isThetaMark ? 'theta' : channel;
519
- errors.push({
520
- message: `Spec error: ${markType} chart requires encoding.${suggestedChannel} but none was provided`,
521
- path: `encoding.${suggestedChannel}`,
522
- code: 'MISSING_FIELD',
523
- suggestion: `Add encoding.${suggestedChannel} with a field from your data (${availableColumns}) and type (${allowedTypes}). Example: ${suggestedChannel}: { field: "${[...dataColumns][0] ?? 'myField'}", type: "${rule.allowedTypes[0]}" }`,
524
- });
525
- }
526
- }
527
-
528
- // Beeswarm axis combination: the channel rules mark both axes optional, so
529
- // enforce the shape here. Exactly one positional channel is the quantitative
530
- // value axis; the other, when present, is the nominal/ordinal lane channel.
531
- // Only declared types are checked; omitted types are inferred later.
532
- if (markType === 'beeswarm') {
533
- const xChannel = encoding.x as Record<string, unknown> | undefined;
534
- const yChannel = encoding.y as Record<string, unknown> | undefined;
535
- const xType = xChannel?.type as string | undefined;
536
- const yType = yChannel?.type as string | undefined;
537
- if (!xChannel && !yChannel) {
538
- errors.push({
539
- message:
540
- 'Spec error: beeswarm chart requires a quantitative encoding.x or encoding.y (the value axis)',
541
- path: 'encoding',
542
- code: 'MISSING_FIELD',
543
- suggestion: `Add the value axis, e.g. x: { field: "${[...dataColumns][0] ?? 'myField'}", type: "quantitative" }. Optionally add a nominal channel on the other axis for grouped swarms.`,
544
- });
545
- } else if (xType === 'quantitative' && yType === 'quantitative') {
546
- errors.push({
547
- message:
548
- 'Spec error: beeswarm chart accepts only one quantitative axis (the value axis), but both encoding.x and encoding.y are quantitative',
549
- path: 'encoding',
550
- code: 'ENCODING_MISMATCH',
551
- suggestion:
552
- 'Keep the value axis quantitative and change the other channel to nominal/ordinal (grouped swarm lanes), or remove it for a single swarm. For two quantitative axes use mark: "point".',
553
- });
554
- } else if (
555
- xType !== 'quantitative' &&
556
- yType !== 'quantitative' &&
557
- (!xChannel || !!xType) &&
558
- (!yChannel || !!yType)
559
- ) {
560
- errors.push({
561
- message:
562
- 'Spec error: beeswarm chart requires one quantitative axis (the value axis), but neither encoding.x nor encoding.y is quantitative',
563
- path: 'encoding',
564
- code: 'ENCODING_MISMATCH',
565
- suggestion:
566
- 'Set the value axis to type: "quantitative" (x for a horizontal swarm, y for a vertical one).',
567
- });
568
- }
569
- }
570
-
571
- // Range marks: orientation-dependent x2/y2 requirement + mark.style options
572
- if (markType === 'range') {
573
- validateRangeSpec(spec, errors);
574
- }
575
-
576
- // Calendar marks: temporal daily x, no y, parseable dates, mark options
577
- if (markType === 'calendar') {
578
- validateCalendarSpec(spec, errors);
579
- }
580
-
581
- // Near-miss: VL's string expression form of calculate. A restricted string
582
- // grammar is deliberately not supported (decision: structured form only);
583
- // point authors at the structured equivalent instead.
584
- if (Array.isArray(spec.transform)) {
585
- const transforms = spec.transform as Record<string, unknown>[];
586
- for (let i = 0; i < transforms.length; i++) {
587
- const t = transforms[i];
588
- if (t && typeof t === 'object' && typeof t.calculate === 'string') {
589
- errors.push({
590
- message: `Spec error: transform[${i}].calculate must be a structured expression object, not a string`,
591
- path: `transform[${i}].calculate`,
592
- code: 'INVALID_TYPE',
593
- suggestion:
594
- 'Use the structured form for single operations, e.g. calculate: { op: "/", field: "a", field2: "b" } with as: "ratio". For running or grouped computations use the window or aggregate transforms.',
595
- });
596
- }
597
- }
598
- }
599
-
600
- // Collect fields that transforms will create, so we don't reject them
601
- const transformFields = new Set<string>();
602
- if (Array.isArray(spec.transform)) {
603
- for (const t of spec.transform as Record<string, unknown>[]) {
604
- // filter/bin/calculate/timeUnit/fold write their output(s) to `as`.
605
- if (typeof t.as === 'string') transformFields.add(t.as);
606
- if (Array.isArray(t.as)) {
607
- for (const f of t.as) {
608
- if (typeof f === 'string') transformFields.add(f);
609
- }
610
- }
611
- // aggregate/window carry their output field names inside their op arrays,
612
- // and aggregate preserves its groupby fields on the output rows.
613
- const opList = (t.aggregate ?? t.window) as Record<string, unknown>[] | undefined;
614
- if (Array.isArray(opList)) {
615
- for (const op of opList) {
616
- if (op && typeof op.as === 'string') transformFields.add(op.as);
617
- }
618
- }
619
- if (Array.isArray(t.groupby)) {
620
- for (const g of t.groupby) {
621
- if (typeof g === 'string') transformFields.add(g);
622
- }
623
- }
624
- }
625
- }
626
-
627
- // Validate provided channels
628
- for (const [channel, channelSpec] of Object.entries(encoding)) {
629
- if (!channelSpec || typeof channelSpec !== 'object') continue;
630
-
631
- // Tooltip can be an array of encoding channels
632
- if (channel === 'tooltip' && Array.isArray(channelSpec)) {
633
- for (let i = 0; i < channelSpec.length; i++) {
634
- const elem = channelSpec[i] as Record<string, unknown> | null;
635
- if (!elem || typeof elem !== 'object') continue;
636
- if (!elem.field || typeof elem.field !== 'string') {
637
- errors.push({
638
- message: `Spec error: encoding.tooltip[${i}] must have a "field" string`,
639
- path: `encoding.tooltip[${i}].field`,
640
- code: 'MISSING_FIELD',
641
- suggestion: `Add a field name from your data columns: ${availableColumns}`,
642
- });
643
- continue;
644
- }
645
- if (!dataColumns.has(elem.field) && !transformFields.has(elem.field)) {
646
- errors.push({
647
- message: `Spec error: encoding.tooltip[${i}].field "${elem.field}" does not exist in data. Available columns: ${availableColumns}`,
648
- path: `encoding.tooltip[${i}].field`,
649
- code: 'DATA_FIELD_MISSING',
650
- suggestion: `Use one of the available data columns: ${availableColumns}.${didYouMean(elem.field, columnList)}`,
651
- });
652
- }
653
- if (elem.type && !VALID_FIELD_TYPES.has(elem.type as string)) {
654
- errors.push({
655
- message: `Spec error: encoding.tooltip[${i}].type "${elem.type}" is not valid. Must be one of: ${[...VALID_FIELD_TYPES].join(', ')}`,
656
- path: `encoding.tooltip[${i}].type`,
657
- code: 'INVALID_VALUE',
658
- suggestion: `Use one of: ${[...VALID_FIELD_TYPES].join(', ')}`,
659
- });
660
- }
661
- }
662
- continue;
663
- }
664
-
665
- const channelObj = channelSpec as Record<string, unknown>;
666
- const channelRule = rules[channel as keyof typeof rules];
667
-
668
- // Skip ConditionalValueDef channels (they have 'condition' instead of 'field')
669
- if ('condition' in channelObj) continue;
670
-
671
- // Check field exists
672
- if (!channelObj.field || typeof channelObj.field !== 'string') {
673
- errors.push({
674
- message: `Spec error: encoding.${channel} must have a "field" string`,
675
- path: `encoding.${channel}.field`,
676
- code: 'MISSING_FIELD',
677
- suggestion: `For constant colors, use mark.fill (e.g., mark: { type: "bar", fill: "#1b7fa3" }) instead of encoding.${channel}. Encoding channels require a data field: ${availableColumns}`,
678
- });
679
- continue;
680
- }
681
-
682
- // Check field references a column in data (or will be created by a transform)
683
- if (!dataColumns.has(channelObj.field) && !transformFields.has(channelObj.field)) {
684
- errors.push({
685
- message: `Spec error: encoding.${channel}.field "${channelObj.field}" does not exist in data. Available columns: ${availableColumns}`,
686
- path: `encoding.${channel}.field`,
687
- code: 'DATA_FIELD_MISSING',
688
- suggestion: `Use one of the available data columns: ${availableColumns}.${didYouMean(channelObj.field, columnList)}`,
689
- });
690
- }
691
-
692
- // Check field type is valid
693
- if (channelObj.type && !VALID_FIELD_TYPES.has(channelObj.type as string)) {
694
- errors.push({
695
- message: `Spec error: encoding.${channel}.type "${channelObj.type}" is not valid. Must be one of: ${[...VALID_FIELD_TYPES].join(', ')}`,
696
- path: `encoding.${channel}.type`,
697
- code: 'INVALID_VALUE',
698
- suggestion: `Use one of: ${[...VALID_FIELD_TYPES].join(', ')}`,
699
- });
700
- }
701
-
702
- // Check scale.scheme names. Known names (including VL aliases) are
703
- // resolved to palette ranges by the pre-validation sugar expansion, so a
704
- // scheme surviving to this point on the compile path is an unknown name.
705
- checkSchemeName(channelObj, `encoding.${channel}`, errors);
706
-
707
- // Check field type is allowed for this channel
708
- if (channelRule && channelObj.type && channelRule.allowedTypes.length > 0) {
709
- if (!channelRule.allowedTypes.includes(channelObj.type as FieldType)) {
710
- errors.push({
711
- message: `Spec error: encoding.${channel} for ${markType} chart does not accept type "${channelObj.type}". Allowed types: ${channelRule.allowedTypes.join(', ')}`,
712
- path: `encoding.${channel}.type`,
713
- code: 'ENCODING_MISMATCH',
714
- suggestion: `Change encoding.${channel}.type to one of: ${channelRule.allowedTypes.join(', ')}`,
715
- });
716
- }
717
- }
718
-
719
- // Check field values match declared type
720
- if (channelObj.type && channelObj.field && dataColumns.has(channelObj.field as string)) {
721
- const data = spec.data as Record<string, unknown>[];
722
- const fieldName = channelObj.field as string;
723
- const fieldType = channelObj.type as string;
724
- // Sample up to 5 values for type checking
725
- const sampleSize = Math.min(5, data.length);
726
-
727
- if (fieldType === 'temporal') {
728
- let nonDateCount = 0;
729
- for (let i = 0; i < sampleSize; i++) {
730
- const val = data[i][fieldName];
731
- if (val != null && !isParseableDate(val)) {
732
- nonDateCount++;
733
- }
734
- }
735
- if (nonDateCount > 0) {
736
- errors.push({
737
- message: `Spec error: encoding.${channel}.field "${fieldName}" is declared as temporal but contains non-date values`,
738
- path: `encoding.${channel}`,
739
- code: 'ENCODING_MISMATCH',
740
- suggestion: `Either change the type to "nominal" or ensure "${fieldName}" values are parseable dates (ISO 8601 strings like "2024-01-15" or Date objects)`,
741
- });
742
- }
743
- }
744
-
745
- if (fieldType === 'quantitative') {
746
- let nonNumericCount = 0;
747
- for (let i = 0; i < sampleSize; i++) {
748
- const val = data[i][fieldName];
749
- if (val != null && !isNumeric(val)) {
750
- nonNumericCount++;
751
- }
752
- }
753
- if (nonNumericCount > 0) {
754
- errors.push({
755
- message: `Spec error: encoding.${channel}.field "${fieldName}" is declared as quantitative but contains non-numeric values`,
756
- path: `encoding.${channel}`,
757
- code: 'ENCODING_MISMATCH',
758
- suggestion: `Either change the type to "nominal" or ensure "${fieldName}" values are numbers`,
759
- });
760
- }
761
- }
762
- }
763
- }
764
-
765
- // Validate highlight on the color channel
766
- if (encoding) {
767
- const colorCh = (encoding as Record<string, Record<string, unknown> | undefined>).color;
768
- if (colorCh && colorCh.highlight != null) {
769
- const hlVal = colorCh.highlight;
770
- const isValidType =
771
- typeof hlVal === 'string' ||
772
- (Array.isArray(hlVal) && hlVal.every((v: unknown) => typeof v === 'string'));
773
- if (!isValidType) {
774
- errors.push({
775
- message: 'Spec error: encoding.color.highlight must be a string or array of strings',
776
- path: 'encoding.color.highlight',
777
- code: 'INVALID_TYPE',
778
- suggestion: 'Provide a series name (string) or an array of series names.',
779
- });
780
- } else {
781
- const colorType =
782
- (colorCh.type as string | undefined) ??
783
- (colorCh.field && Array.isArray(spec.data) && spec.data.length > 0
784
- ? inferFieldType(spec.data as Record<string, unknown>[], colorCh.field as string)
785
- : undefined);
786
- if (colorType === 'quantitative') {
787
- errors.push({
788
- message:
789
- 'Spec error: encoding.color.highlight is not supported on quantitative color channels',
790
- path: 'encoding.color.highlight',
791
- code: 'INVALID_VALUE',
792
- suggestion:
793
- 'Highlight works with nominal/ordinal color (categorical series). Remove highlight or change encoding.color.type to nominal.',
794
- });
795
- }
796
- }
797
- }
798
- }
799
-
800
- // Validate facet channel if provided
801
- if (encoding.facet && typeof encoding.facet === 'object') {
802
- const facet = encoding.facet as Record<string, unknown>;
803
- if (!facet.field || typeof facet.field !== 'string') {
804
- errors.push({
805
- message: 'Spec error: encoding.facet.field is required and must be a non-empty string',
806
- path: 'encoding.facet.field',
807
- code: 'MISSING_FIELD',
808
- suggestion:
809
- 'Add a field property to encoding.facet (e.g. { field: "category", type: "nominal" })',
810
- });
811
- } else if (
812
- !dataColumns.has(facet.field as string) &&
813
- !transformFields.has(facet.field as string)
814
- ) {
815
- errors.push({
816
- message: `Spec error: encoding.facet.field "${facet.field}" does not exist in data. Available columns: ${availableColumns}`,
817
- path: 'encoding.facet.field',
818
- code: 'DATA_FIELD_MISSING',
819
- suggestion: `Use one of the available data columns: ${availableColumns}.${didYouMean(facet.field as string, columnList)}`,
820
- });
821
- }
822
- if (!facet.type || (facet.type !== 'nominal' && facet.type !== 'ordinal')) {
823
- errors.push({
824
- message: `Spec error: encoding.facet.type must be "nominal" or "ordinal"${facet.type ? `, got "${facet.type}"` : ''}`,
825
- path: 'encoding.facet.type',
826
- code: facet.type ? 'INVALID_VALUE' : 'MISSING_FIELD',
827
- suggestion: 'Set encoding.facet.type to "nominal" or "ordinal"',
828
- });
829
- }
830
- if (facet.columns !== undefined) {
831
- const cols = Number(facet.columns);
832
- if (!Number.isInteger(cols) || cols < 1) {
833
- errors.push({
834
- message: 'Spec error: encoding.facet.columns must be a positive integer',
835
- path: 'encoding.facet.columns',
836
- code: 'INVALID_VALUE',
837
- suggestion: 'Set columns to a positive integer (e.g. 3)',
838
- });
839
- }
840
- }
841
- }
842
-
843
- // Validate row/column facet channels
844
- for (const channel of ['row', 'column'] as const) {
845
- const ch = (encoding as Record<string, unknown>)[channel];
846
- if (ch && typeof ch === 'object') {
847
- const facetCh = ch as Record<string, unknown>;
848
- if (!facetCh.field || typeof facetCh.field !== 'string') {
849
- errors.push({
850
- message: `Spec error: encoding.${channel}.field is required and must be a non-empty string`,
851
- path: `encoding.${channel}.field`,
852
- code: 'MISSING_FIELD',
853
- suggestion: `Add a field property to encoding.${channel} (e.g. { field: "category", type: "nominal" })`,
854
- });
855
- } else if (
856
- !dataColumns.has(facetCh.field as string) &&
857
- !transformFields.has(facetCh.field as string)
858
- ) {
859
- errors.push({
860
- message: `Spec error: encoding.${channel}.field "${facetCh.field}" does not exist in data. Available columns: ${availableColumns}`,
861
- path: `encoding.${channel}.field`,
862
- code: 'DATA_FIELD_MISSING',
863
- suggestion: `Use one of the available data columns: ${availableColumns}.${didYouMean(facetCh.field as string, columnList)}`,
864
- });
865
- }
866
- if (!facetCh.type || (facetCh.type !== 'nominal' && facetCh.type !== 'ordinal')) {
867
- errors.push({
868
- message: `Spec error: encoding.${channel}.type must be "nominal" or "ordinal"${facetCh.type ? `, got "${facetCh.type}"` : ''}`,
869
- path: `encoding.${channel}.type`,
870
- code: facetCh.type ? 'INVALID_VALUE' : 'MISSING_FIELD',
871
- suggestion: `Set encoding.${channel}.type to "nominal" or "ordinal"`,
872
- });
873
- }
874
- if (encoding.facet && typeof encoding.facet === 'object') {
875
- errors.push({
876
- message: `Spec error: encoding.${channel} and encoding.facet cannot be used together`,
877
- path: `encoding.${channel}`,
878
- code: 'INVALID_VALUE',
879
- suggestion: `Use either encoding.${channel} or encoding.facet, not both`,
880
- });
881
- }
882
- const otherChannel = channel === 'row' ? 'column' : 'row';
883
- if ((encoding as Record<string, unknown>)[otherChannel]) {
884
- errors.push({
885
- message:
886
- 'Spec error: encoding.row and encoding.column cannot be used together (cross-product faceting is not yet supported)',
887
- path: `encoding.${channel}`,
888
- code: 'INVALID_VALUE',
889
- suggestion: 'Use encoding.facet with columns for grid layout, or use only row or column',
890
- });
891
- }
892
- }
893
- }
894
-
895
- // Validate darkMode if provided
896
- if (spec.darkMode !== undefined && !VALID_DARK_MODES.has(spec.darkMode as string)) {
897
- errors.push({
898
- message: `Spec error: darkMode must be "auto", "force", or "off"`,
899
- path: 'darkMode',
900
- code: 'INVALID_VALUE',
901
- suggestion:
902
- 'Use one of: "auto" (system preference), "force" (always dark), or "off" (always light)',
903
- });
904
- }
905
-
906
- // Validate youDrawIt: line marks only, single-series only, "from" required.
907
- if (spec.youDrawIt !== undefined && spec.youDrawIt !== false) {
908
- if (markType !== 'line') {
909
- errors.push({
910
- message: `Spec error: youDrawIt is only supported on line charts, but mark is "${markType}"`,
911
- path: 'youDrawIt',
912
- code: 'ENCODING_MISMATCH',
913
- suggestion: 'Remove youDrawIt or change mark to "line".',
914
- });
915
- } else {
916
- const config = spec.youDrawIt as Record<string, unknown>;
917
- if (
918
- typeof config !== 'object' ||
919
- Array.isArray(config) ||
920
- (config.from !== 0 && !config.from)
921
- ) {
922
- errors.push({
923
- message: 'Spec error: youDrawIt.from is required (the x value where drawing starts)',
924
- path: 'youDrawIt.from',
925
- code: 'MISSING_FIELD',
926
- suggestion:
927
- 'Set youDrawIt.from to an x value from your data, e.g. youDrawIt: { from: "2010" }',
928
- });
929
- } else if (typeof config.from !== 'string' && typeof config.from !== 'number') {
930
- errors.push({
931
- message: 'Spec error: youDrawIt.from must be a string or number',
932
- path: 'youDrawIt.from',
933
- code: 'INVALID_TYPE',
934
- suggestion: 'Provide the x value as a string or number matching your data.',
935
- });
936
- }
937
-
938
- const data = Array.isArray(spec.data) ? (spec.data as Record<string, unknown>[]) : [];
939
- const colorCh = encoding?.color as Record<string, unknown> | undefined;
940
- if (colorCh && typeof colorCh === 'object' && typeof colorCh.field === 'string') {
941
- const colorType =
942
- (colorCh.type as string | undefined) ?? inferFieldType(data, colorCh.field);
943
- if (colorType !== 'quantitative') {
944
- const distinct = new Set(data.map((row) => row[colorCh.field as string]));
945
- if (distinct.size > 1) {
946
- errors.push({
947
- message:
948
- 'Spec error: youDrawIt only supports single-series line charts, but encoding.color has multiple distinct values',
949
- path: 'youDrawIt',
950
- code: 'ENCODING_MISMATCH',
951
- suggestion:
952
- 'Remove encoding.color (or filter the data to one series) to use youDrawIt.',
953
- });
954
- }
955
- }
956
- }
957
- }
958
- }
959
- }
960
-
961
- // ---------------------------------------------------------------------------
962
- // Table validation
963
- // ---------------------------------------------------------------------------
964
-
965
- function validateTableSpec(spec: Record<string, unknown>, errors: ValidationError[]): void {
966
- if (!Array.isArray(spec.data)) {
967
- errors.push({
968
- message: 'Spec error: "data" must be an array',
969
- path: 'data',
970
- code: 'INVALID_TYPE',
971
- suggestion: 'Provide data as an array of objects, e.g. data: [{ name: "Alice", age: 30 }]',
972
- });
973
- return;
974
- }
975
-
976
- if (spec.data.length === 0) {
977
- errors.push({
978
- message: 'Spec error: "data" must be a non-empty array',
979
- path: 'data',
980
- code: 'EMPTY_DATA',
981
- suggestion: 'Add at least one data row to the data array',
982
- });
983
- return;
984
- }
985
-
986
- if (!Array.isArray(spec.columns)) {
987
- errors.push({
988
- message: 'Spec error: table spec requires a "columns" array',
989
- path: 'columns',
990
- code: 'MISSING_FIELD',
991
- suggestion:
992
- 'Add a columns array defining which data fields to display, e.g. columns: [{ key: "name" }, { key: "age" }]',
993
- });
994
- return;
995
- }
996
-
997
- const data = spec.data as Record<string, unknown>[];
998
- const firstRow = data[0];
999
- if (typeof firstRow !== 'object' || firstRow === null || Array.isArray(firstRow)) {
1000
- errors.push({
1001
- message: 'Spec error: each item in "data" must be a plain object',
1002
- path: 'data[0]',
1003
- code: 'INVALID_TYPE',
1004
- suggestion:
1005
- 'Each data item should be an object with key-value pairs, e.g. { name: "Alice", age: 30 }',
1006
- });
1007
- return;
1008
- }
1009
-
1010
- const dataColumns = new Set(Object.keys(firstRow as Record<string, unknown>));
1011
- const columnList = [...dataColumns];
1012
- const availableColumns = columnList.join(', ');
1013
- const columns = spec.columns as Record<string, unknown>[];
1014
-
1015
- for (let i = 0; i < columns.length; i++) {
1016
- const col = columns[i];
1017
- if (!col || typeof col !== 'object') {
1018
- errors.push({
1019
- message: `Spec error: columns[${i}] must be an object`,
1020
- path: `columns[${i}]`,
1021
- code: 'INVALID_TYPE',
1022
- suggestion: 'Each column entry should be an object, e.g. { key: "fieldName" }',
1023
- });
1024
- continue;
1025
- }
1026
-
1027
- // Check key exists
1028
- if (!col.key || typeof col.key !== 'string') {
1029
- errors.push({
1030
- message: `Spec error: columns[${i}] must have a "key" string`,
1031
- path: `columns[${i}].key`,
1032
- code: 'MISSING_FIELD',
1033
- suggestion: `Add a key referencing a data field. Available columns: ${availableColumns}`,
1034
- });
1035
- continue;
1036
- }
1037
-
1038
- // Check key references a field in data
1039
- if (!dataColumns.has(col.key as string)) {
1040
- errors.push({
1041
- message: `Spec error: columns[${i}].key "${col.key}" does not exist in data. Available columns: ${availableColumns}`,
1042
- path: `columns[${i}].key`,
1043
- code: 'DATA_FIELD_MISSING',
1044
- suggestion: `Use one of the available data columns: ${availableColumns}.${didYouMean(col.key as string, columnList)}`,
1045
- });
1046
- }
1047
-
1048
- // Check at most one visual enhancement
1049
- const visuals = ['heatmap', 'bar', 'sparkline', 'image', 'flag', 'categoryColors'].filter(
1050
- (v) => col[v] != null && col[v] !== false,
1051
- );
1052
- if (visuals.length > 1) {
1053
- errors.push({
1054
- message: `Spec error: columns[${i}] has multiple visual features (${visuals.join(', ')}). Only one is allowed per column.`,
1055
- path: `columns[${i}]`,
1056
- code: 'INVALID_VALUE',
1057
- suggestion: `Keep only one visual feature per column. Remove all but one of: ${visuals.join(', ')}`,
1058
- });
1059
- }
1060
- }
1061
- }
1062
-
1063
- // ---------------------------------------------------------------------------
1064
- // Graph validation
1065
- // ---------------------------------------------------------------------------
1066
-
1067
- function validateGraphSpec(spec: Record<string, unknown>, errors: ValidationError[]): void {
1068
- // Validate nodes array exists and is non-empty
1069
- if (!Array.isArray(spec.nodes)) {
1070
- errors.push({
1071
- message: 'Spec error: graph spec requires a "nodes" array',
1072
- path: 'nodes',
1073
- code: 'MISSING_FIELD',
1074
- suggestion:
1075
- 'Add a nodes array with objects that have an "id" field, e.g. nodes: [{ id: "a" }, { id: "b" }]',
1076
- });
1077
- return; // Can't validate further without nodes
1078
- }
1079
-
1080
- if (spec.nodes.length === 0) {
1081
- errors.push({
1082
- message: 'Spec error: "nodes" must be a non-empty array',
1083
- path: 'nodes',
1084
- code: 'EMPTY_DATA',
1085
- suggestion: 'Add at least one node, e.g. nodes: [{ id: "a" }]',
1086
- });
1087
- return;
1088
- }
1089
-
1090
- // Validate each node has a string id
1091
- const nodeIds = new Set<string>();
1092
- const nodes = spec.nodes as Record<string, unknown>[];
1093
- for (let i = 0; i < nodes.length; i++) {
1094
- const node = nodes[i];
1095
- if (!node || typeof node !== 'object') {
1096
- errors.push({
1097
- message: `Spec error: nodes[${i}] must be an object`,
1098
- path: `nodes[${i}]`,
1099
- code: 'INVALID_TYPE',
1100
- suggestion: 'Each node must be an object with at least an "id" field, e.g. { id: "a" }',
1101
- });
1102
- continue;
1103
- }
1104
- if (typeof node.id !== 'string' || node.id === '') {
1105
- errors.push({
1106
- message: `Spec error: nodes[${i}] must have a non-empty string "id" field`,
1107
- path: `nodes[${i}].id`,
1108
- code: 'MISSING_FIELD',
1109
- suggestion: 'Add a string id to the node, e.g. { id: "node1" }',
1110
- });
1111
- } else {
1112
- nodeIds.add(node.id);
1113
- }
1114
- }
1115
-
1116
- // Validate edges array exists
1117
- if (!Array.isArray(spec.edges)) {
1118
- errors.push({
1119
- message: 'Spec error: graph spec requires an "edges" array',
1120
- path: 'edges',
1121
- code: 'MISSING_FIELD',
1122
- suggestion: 'Add an edges array (can be empty), e.g. edges: [{ source: "a", target: "b" }]',
1123
- });
1124
- return;
1125
- }
1126
-
1127
- // Validate each edge has string source and target that reference existing nodes
1128
- const edges = spec.edges as Record<string, unknown>[];
1129
- for (let i = 0; i < edges.length; i++) {
1130
- const edge = edges[i];
1131
- if (!edge || typeof edge !== 'object') {
1132
- errors.push({
1133
- message: `Spec error: edges[${i}] must be an object`,
1134
- path: `edges[${i}]`,
1135
- code: 'INVALID_TYPE',
1136
- suggestion:
1137
- 'Each edge must be an object with "source" and "target" fields, e.g. { source: "a", target: "b" }',
1138
- });
1139
- continue;
1140
- }
1141
-
1142
- if (typeof edge.source !== 'string' || edge.source === '') {
1143
- errors.push({
1144
- message: `Spec error: edges[${i}] must have a non-empty string "source" field`,
1145
- path: `edges[${i}].source`,
1146
- code: 'MISSING_FIELD',
1147
- suggestion: 'Add a source node id, e.g. { source: "a", target: "b" }',
1148
- });
1149
- } else if (nodeIds.size > 0 && !nodeIds.has(edge.source)) {
1150
- errors.push({
1151
- message: `Spec error: edges[${i}].source "${edge.source}" does not reference an existing node id`,
1152
- path: `edges[${i}].source`,
1153
- code: 'DATA_FIELD_MISSING',
1154
- suggestion: `Use one of the existing node ids: ${[...nodeIds].slice(0, 5).join(', ')}${nodeIds.size > 5 ? '...' : ''}.${didYouMean(edge.source, [...nodeIds])}`,
1155
- });
1156
- }
1157
-
1158
- if (typeof edge.target !== 'string' || edge.target === '') {
1159
- errors.push({
1160
- message: `Spec error: edges[${i}] must have a non-empty string "target" field`,
1161
- path: `edges[${i}].target`,
1162
- code: 'MISSING_FIELD',
1163
- suggestion: 'Add a target node id, e.g. { source: "a", target: "b" }',
1164
- });
1165
- } else if (nodeIds.size > 0 && !nodeIds.has(edge.target)) {
1166
- errors.push({
1167
- message: `Spec error: edges[${i}].target "${edge.target}" does not reference an existing node id`,
1168
- path: `edges[${i}].target`,
1169
- code: 'DATA_FIELD_MISSING',
1170
- suggestion: `Use one of the existing node ids: ${[...nodeIds].slice(0, 5).join(', ')}${nodeIds.size > 5 ? '...' : ''}.${didYouMean(edge.target, [...nodeIds])}`,
1171
- });
1172
- }
1173
- }
1174
-
1175
- // Validate encoding fields exist on at least the first node/edge
1176
- if (spec.encoding && typeof spec.encoding === 'object') {
1177
- const encoding = spec.encoding as Record<string, unknown>;
1178
- const firstNode = nodes[0] as Record<string, unknown>;
1179
- const firstEdge = edges.length > 0 ? (edges[0] as Record<string, unknown>) : null;
1180
- const nodeFields = firstNode ? new Set(Object.keys(firstNode)) : new Set<string>();
1181
- const edgeFields = firstEdge ? new Set(Object.keys(firstEdge)) : new Set<string>();
1182
-
1183
- const nodeChannels = ['nodeColor', 'nodeSize', 'nodeLabel'] as const;
1184
- for (const channel of nodeChannels) {
1185
- const ch = encoding[channel] as Record<string, unknown> | undefined;
1186
- if (ch?.field && typeof ch.field === 'string' && !nodeFields.has(ch.field)) {
1187
- errors.push({
1188
- message: `Spec error: encoding.${channel}.field "${ch.field}" does not exist on nodes. Available fields: ${[...nodeFields].join(', ')}`,
1189
- path: `encoding.${channel}.field`,
1190
- code: 'DATA_FIELD_MISSING',
1191
- suggestion: `Use one of the node fields: ${[...nodeFields].join(', ')}.${didYouMean(ch.field, [...nodeFields])}`,
1192
- });
1193
- }
1194
- }
1195
-
1196
- const edgeChannels = ['edgeColor', 'edgeWidth'] as const;
1197
- for (const channel of edgeChannels) {
1198
- const ch = encoding[channel] as Record<string, unknown> | undefined;
1199
- if (ch?.field && typeof ch.field === 'string' && firstEdge && !edgeFields.has(ch.field)) {
1200
- errors.push({
1201
- message: `Spec error: encoding.${channel}.field "${ch.field}" does not exist on edges. Available fields: ${[...edgeFields].join(', ')}`,
1202
- path: `encoding.${channel}.field`,
1203
- code: 'DATA_FIELD_MISSING',
1204
- suggestion: `Use one of the edge fields: ${[...edgeFields].join(', ')}.${didYouMean(ch.field, [...edgeFields])}`,
1205
- });
1206
- }
1207
- }
1208
-
1209
- // Graph never reads scale.scheme: colors come from scale.range/scale.domain
1210
- checkSchemeUnused(
1211
- encoding,
1212
- errors,
1213
- 'graph colors come from scale.range and scale.domain',
1214
- 'Remove scale.scheme. To customize graph colors, provide explicit colors via scale.range.',
1215
- );
1216
- }
1217
-
1218
- // Validate layout type if specified
1219
- if (spec.layout && typeof spec.layout === 'object') {
1220
- const layout = spec.layout as Record<string, unknown>;
1221
- if (layout.type && layout.type !== 'force') {
1222
- errors.push({
1223
- message: `Spec error: layout.type "${layout.type}" is not supported. Only "force" is currently supported`,
1224
- path: 'layout.type',
1225
- code: 'INVALID_VALUE',
1226
- suggestion:
1227
- 'Use layout.type: "force" or omit the layout field to use the default force layout',
1228
- });
1229
- }
1230
- }
1231
- }
1232
-
1233
- // ---------------------------------------------------------------------------
1234
- // Sankey validation
1235
- // ---------------------------------------------------------------------------
1236
-
1237
- function validateSankeySpec(spec: Record<string, unknown>, errors: ValidationError[]): void {
1238
- // Validate data
1239
- if (!Array.isArray(spec.data)) {
1240
- errors.push({
1241
- message: 'Spec error: sankey spec requires a "data" array',
1242
- path: 'data',
1243
- code: 'INVALID_TYPE',
1244
- suggestion:
1245
- 'Provide data as an array of objects, e.g. data: [{ source: "A", target: "B", value: 10 }]',
1246
- });
1247
- return;
1248
- }
1249
-
1250
- if (spec.data.length === 0) {
1251
- errors.push({
1252
- message: 'Spec error: "data" must be a non-empty array',
1253
- path: 'data',
1254
- code: 'EMPTY_DATA',
1255
- suggestion: 'Add at least one data row, e.g. data: [{ source: "A", target: "B", value: 10 }]',
1256
- });
1257
- return;
1258
- }
1259
-
1260
- const firstRow = spec.data[0] as unknown;
1261
- if (typeof firstRow !== 'object' || firstRow === null || Array.isArray(firstRow)) {
1262
- errors.push({
1263
- message: 'Spec error: each item in "data" must be a plain object',
1264
- path: 'data[0]',
1265
- code: 'INVALID_TYPE',
1266
- suggestion:
1267
- 'Each data item should be an object, e.g. { source: "A", target: "B", value: 10 }',
1268
- });
1269
- return;
1270
- }
1271
-
1272
- // Validate encoding
1273
- if (!spec.encoding || typeof spec.encoding !== 'object') {
1274
- errors.push({
1275
- message:
1276
- 'Spec error: sankey spec requires an "encoding" object with source, target, and value channels',
1277
- path: 'encoding',
1278
- code: 'MISSING_FIELD',
1279
- suggestion:
1280
- 'Add an encoding object, e.g. encoding: { source: { field: "source", type: "nominal" }, target: { field: "target", type: "nominal" }, value: { field: "value", type: "quantitative" } }',
1281
- });
1282
- return;
1283
- }
1284
-
1285
- const encoding = spec.encoding as Record<string, unknown>;
1286
- const dataColumns = new Set(Object.keys(firstRow as Record<string, unknown>));
1287
- const columnList = [...dataColumns];
1288
- const availableColumns = columnList.join(', ');
1289
-
1290
- // Required channels
1291
- for (const channel of ['source', 'target', 'value'] as const) {
1292
- const ch = encoding[channel] as Record<string, unknown> | undefined;
1293
- if (!ch || typeof ch !== 'object') {
1294
- errors.push({
1295
- message: `Spec error: sankey encoding requires "${channel}" channel`,
1296
- path: `encoding.${channel}`,
1297
- code: 'MISSING_FIELD',
1298
- suggestion: `Add encoding.${channel} with a field from your data (${availableColumns}). Example: ${channel}: { field: "${columnList[0] ?? 'myField'}", type: "${channel === 'value' ? 'quantitative' : 'nominal'}" }`,
1299
- });
1300
- continue;
1301
- }
1302
-
1303
- if (!ch.field || typeof ch.field !== 'string') {
1304
- errors.push({
1305
- message: `Spec error: encoding.${channel} must have a "field" string`,
1306
- path: `encoding.${channel}.field`,
1307
- code: 'MISSING_FIELD',
1308
- suggestion: `Add a field name from your data columns: ${availableColumns}`,
1309
- });
1310
- continue;
1311
- }
1312
-
1313
- if (!dataColumns.has(ch.field as string)) {
1314
- errors.push({
1315
- message: `Spec error: encoding.${channel}.field "${ch.field}" does not exist in data. Available columns: ${availableColumns}`,
1316
- path: `encoding.${channel}.field`,
1317
- code: 'DATA_FIELD_MISSING',
1318
- suggestion: `Use one of the available data columns: ${availableColumns}.${didYouMean(ch.field as string, columnList)}`,
1319
- });
1320
- }
1321
- }
1322
-
1323
- // Sankey never reads scale.scheme: node colors cycle theme.colors.categorical
1324
- checkSchemeUnused(
1325
- encoding,
1326
- errors,
1327
- 'sankey node colors cycle the theme categorical palette',
1328
- 'Remove scale.scheme. To customize sankey colors, set theme.colors.categorical.',
1329
- );
1330
-
1331
- // Validate darkMode if provided
1332
- if (spec.darkMode !== undefined && !VALID_DARK_MODES.has(spec.darkMode as string)) {
1333
- errors.push({
1334
- message: 'Spec error: darkMode must be "auto", "force", or "off"',
1335
- path: 'darkMode',
1336
- code: 'INVALID_VALUE',
1337
- suggestion:
1338
- 'Use one of: "auto" (system preference), "force" (always dark), or "off" (always light)',
1339
- });
1340
- }
1341
- }
1342
-
1343
- // ---------------------------------------------------------------------------
1344
- // TileMap validation
1345
- // ---------------------------------------------------------------------------
1346
-
1347
- function validateTileMapSpec(spec: Record<string, unknown>, errors: ValidationError[]): void {
1348
- // Validate data (can be record or array)
1349
- if (!spec.data || typeof spec.data !== 'object') {
1350
- errors.push({
1351
- message: 'Spec error: tilemap spec requires a "data" field (record or array)',
1352
- path: 'data',
1353
- code: 'INVALID_TYPE',
1354
- suggestion:
1355
- 'Provide data as either a record mapping state codes to values (e.g. { "CA": 12000, "TX": 8500 }) or an array of objects with state and value fields',
1356
- });
1357
- return;
1358
- }
1359
-
1360
- // If data is an object (record), validate it has at least one entry
1361
- if (!Array.isArray(spec.data) && Object.keys(spec.data as Record<string, unknown>).length === 0) {
1362
- errors.push({
1363
- message: 'Spec error: "data" must have at least one entry',
1364
- path: 'data',
1365
- code: 'EMPTY_DATA',
1366
- suggestion: 'Add at least one state-value pair, e.g. { "CA": 12000 }',
1367
- });
1368
- return;
1369
- }
1370
-
1371
- // If data is an array, validate it's non-empty
1372
- if (Array.isArray(spec.data)) {
1373
- if (spec.data.length === 0) {
1374
- errors.push({
1375
- message: 'Spec error: "data" array must be non-empty',
1376
- path: 'data',
1377
- code: 'EMPTY_DATA',
1378
- suggestion: 'Add at least one data row',
1379
- });
1380
- return;
1381
- }
1382
-
1383
- const firstRow = spec.data[0] as unknown;
1384
- if (typeof firstRow !== 'object' || firstRow === null || Array.isArray(firstRow)) {
1385
- errors.push({
1386
- message: 'Spec error: each item in "data" must be a plain object',
1387
- path: 'data[0]',
1388
- code: 'INVALID_TYPE',
1389
- suggestion: 'Each data item should be an object, e.g. { state: "CA", value: 12000 }',
1390
- });
1391
- return;
1392
- }
1393
-
1394
- // If data is array, encoding is required
1395
- if (!spec.encoding || typeof spec.encoding !== 'object') {
1396
- errors.push({
1397
- message:
1398
- 'Spec error: tilemap spec with array data requires an "encoding" object with state and value channels',
1399
- path: 'encoding',
1400
- code: 'MISSING_FIELD',
1401
- suggestion:
1402
- 'Add an encoding object, e.g. encoding: { state: { field: "state", type: "nominal" }, value: { field: "value", type: "quantitative" } }',
1403
- });
1404
- return;
1405
- }
1406
-
1407
- const encoding = spec.encoding as Record<string, unknown>;
1408
- const dataColumns = new Set(Object.keys(firstRow as Record<string, unknown>));
1409
- const columnList = [...dataColumns];
1410
- const availableColumns = columnList.join(', ');
1411
-
1412
- // Required channels
1413
- for (const channel of ['state', 'value'] as const) {
1414
- const ch = encoding[channel] as Record<string, unknown> | undefined;
1415
- if (!ch || typeof ch !== 'object') {
1416
- errors.push({
1417
- message: `Spec error: tilemap encoding requires "${channel}" channel`,
1418
- path: `encoding.${channel}`,
1419
- code: 'MISSING_FIELD',
1420
- suggestion: `Add encoding.${channel} with a field from your data (${availableColumns}). Example: ${channel}: { field: "${columnList[0] ?? 'myField'}", type: "${channel === 'value' ? 'quantitative' : 'nominal'}" }`,
1421
- });
1422
- continue;
1423
- }
1424
-
1425
- if (!ch.field || typeof ch.field !== 'string') {
1426
- errors.push({
1427
- message: `Spec error: encoding.${channel} must have a "field" string`,
1428
- path: `encoding.${channel}.field`,
1429
- code: 'MISSING_FIELD',
1430
- suggestion: `Add a field name from your data columns: ${availableColumns}`,
1431
- });
1432
- continue;
1433
- }
1434
-
1435
- if (!dataColumns.has(ch.field as string)) {
1436
- errors.push({
1437
- message: `Spec error: encoding.${channel}.field "${ch.field}" does not exist in data. Available columns: ${availableColumns}`,
1438
- path: `encoding.${channel}.field`,
1439
- code: 'DATA_FIELD_MISSING',
1440
- suggestion: `Use one of the available data columns: ${availableColumns}.${didYouMean(ch.field as string, columnList)}`,
1441
- });
1442
- }
1443
- }
1444
- }
1445
-
1446
- // Tilemap never reads scale.scheme: fills come from the top-level palette
1447
- // prop (encoding may be present in both record-map and array-data modes)
1448
- if (spec.encoding && typeof spec.encoding === 'object') {
1449
- checkSchemeUnused(
1450
- spec.encoding as Record<string, unknown>,
1451
- errors,
1452
- 'tilemap fills come from the top-level palette property',
1453
- `Remove scale.scheme and set the top-level palette property instead, e.g. palette: "green". Supported: ${MAP_PALETTE_NAMES}.`,
1454
- );
1455
- }
1456
-
1457
- // Validate darkMode if provided
1458
- if (spec.darkMode !== undefined && !VALID_DARK_MODES.has(spec.darkMode as string)) {
1459
- errors.push({
1460
- message: 'Spec error: darkMode must be "auto", "force", or "off"',
1461
- path: 'darkMode',
1462
- code: 'INVALID_VALUE',
1463
- suggestion:
1464
- 'Use one of: "auto" (system preference), "force" (always dark), or "off" (always light)',
1465
- });
1466
- }
1467
- }
1468
-
1469
- // ---------------------------------------------------------------------------
1470
- // Map validation
1471
- // ---------------------------------------------------------------------------
1472
-
1473
- function validateMapSpec(spec: Record<string, unknown>, errors: ValidationError[]): void {
1474
- if (!spec.geo || typeof spec.geo !== 'object') {
1475
- errors.push({
1476
- message: 'Spec error: map spec requires a "geo" object with a TopoJSON "features" field',
1477
- path: 'geo',
1478
- code: 'MISSING_FIELD',
1479
- suggestion: 'Add a geo object, e.g. geo: { features: topoJsonData, projection: "identity" }',
1480
- });
1481
- return;
1482
- }
1483
-
1484
- const geo = spec.geo as Record<string, unknown>;
1485
- if (!geo.features) {
1486
- errors.push({
1487
- message: 'Spec error: geo requires a "features" field containing TopoJSON topology',
1488
- path: 'geo.features',
1489
- code: 'MISSING_FIELD',
1490
- suggestion:
1491
- 'Import a TopoJSON file and pass it as geo.features, e.g. import topo from "us-atlas/states-albers-10m.json"',
1492
- });
1493
- return;
1494
- }
1495
-
1496
- if (!spec.encoding || typeof spec.encoding !== 'object') {
1497
- errors.push({
1498
- message: 'Spec error: map spec requires an "encoding" object with key and color channels',
1499
- path: 'encoding',
1500
- code: 'MISSING_FIELD',
1501
- suggestion:
1502
- 'Add an encoding object, e.g. encoding: { key: { field: "id", type: "nominal" }, color: { field: "value", type: "quantitative" } }',
1503
- });
1504
- return;
1505
- }
1506
-
1507
- // Map color channels resolve scale.scheme against the sequential palettes
1508
- // with a silent blue fallback; reject unsupported names here instead.
1509
- const mapEncoding = spec.encoding as Record<string, unknown>;
1510
- if (mapEncoding.color && typeof mapEncoding.color === 'object') {
1511
- checkMapSchemeName(mapEncoding.color as Record<string, unknown>, 'encoding.color', errors);
1512
- }
1513
- if (spec.points && typeof spec.points === 'object') {
1514
- const pointsLayer = spec.points as Record<string, unknown>;
1515
- if (pointsLayer.color && typeof pointsLayer.color === 'object') {
1516
- checkMapSchemeName(pointsLayer.color as Record<string, unknown>, 'points.color', errors);
1517
- }
1518
- }
1519
-
1520
- // Validate geo.focus if present
1521
- if ('focus' in geo && geo.focus !== undefined && geo.focus !== null) {
1522
- const focus = geo.focus;
1523
- if (typeof focus === 'string' || typeof focus === 'number') {
1524
- // valid: single id
1525
- } else if (Array.isArray(focus)) {
1526
- for (let i = 0; i < focus.length; i++) {
1527
- if (typeof focus[i] !== 'string' && typeof focus[i] !== 'number') {
1528
- errors.push({
1529
- message: `Spec error: geo.focus array element [${i}] must be a string or number`,
1530
- path: `geo.focus[${i}]`,
1531
- code: 'INVALID_TYPE',
1532
- suggestion: 'Each element in the focus array should be a feature id (string or number)',
1533
- });
1534
- }
1535
- }
1536
- } else if (typeof focus === 'object') {
1537
- const focusObj = focus as Record<string, unknown>;
1538
- if ('points' in focusObj) {
1539
- // Points form: { points: true | { field, value }, padding? } fits the
1540
- // point layer's cluster (all points, or a matching subset).
1541
- const pts = focusObj.points;
1542
- const isSubset =
1543
- typeof pts === 'object' &&
1544
- pts !== null &&
1545
- typeof (pts as Record<string, unknown>).field === 'string' &&
1546
- 'value' in (pts as Record<string, unknown>);
1547
- if (pts !== true && !isSubset) {
1548
- errors.push({
1549
- message:
1550
- 'Spec error: geo.focus.points must be true or { field: string, value: string | number }',
1551
- path: 'geo.focus.points',
1552
- code: 'INVALID_TYPE',
1553
- suggestion:
1554
- 'Use { points: true } to fit all points, or { points: { field: "rating", value: "F" } } to fit a subset.',
1555
- });
1556
- }
1557
- if (focusObj.padding !== undefined && typeof focusObj.padding !== 'number') {
1558
- errors.push({
1559
- message: 'Spec error: geo.focus.padding must be a number',
1560
- path: 'geo.focus.padding',
1561
- code: 'INVALID_TYPE',
1562
- suggestion: 'Provide padding as a number in map-local units, e.g. padding: 16',
1563
- });
1564
- }
1565
- } else if (!('features' in focusObj) || focusObj.features == null) {
1566
- errors.push({
1567
- message: 'Spec error: geo.focus object must have a "features" or "points" property',
1568
- path: 'geo.focus.features',
1569
- code: 'MISSING_FIELD',
1570
- suggestion:
1571
- 'Provide feature id(s) to focus on, e.g. { features: "36", padding: 32 }, or { points: true } to fit the point cluster.',
1572
- });
1573
- } else {
1574
- const feats = focusObj.features;
1575
- if (typeof feats !== 'string' && typeof feats !== 'number' && !Array.isArray(feats)) {
1576
- errors.push({
1577
- message:
1578
- 'Spec error: geo.focus.features must be a string, number, or array of strings/numbers',
1579
- path: 'geo.focus.features',
1580
- code: 'INVALID_TYPE',
1581
- suggestion: 'Use a feature id or array of ids, e.g. "36" or ["36", "34"]',
1582
- });
1583
- } else if (Array.isArray(feats)) {
1584
- for (let i = 0; i < feats.length; i++) {
1585
- if (typeof feats[i] !== 'string' && typeof feats[i] !== 'number') {
1586
- errors.push({
1587
- message: `Spec error: geo.focus.features[${i}] must be a string or number`,
1588
- path: `geo.focus.features[${i}]`,
1589
- code: 'INVALID_TYPE',
1590
- suggestion: 'Each element should be a feature id (string or number)',
1591
- });
1592
- }
1593
- }
1594
- }
1595
- if (focusObj.padding !== undefined && typeof focusObj.padding !== 'number') {
1596
- errors.push({
1597
- message: 'Spec error: geo.focus.padding must be a number',
1598
- path: 'geo.focus.padding',
1599
- code: 'INVALID_TYPE',
1600
- suggestion: 'Provide padding as a number in map-local units, e.g. padding: 32',
1601
- });
1602
- }
1603
- }
1604
- } else {
1605
- errors.push({
1606
- message:
1607
- 'Spec error: geo.focus must be a string, number, array of ids, or object with { features, padding? } or { points: true, padding? }',
1608
- path: 'geo.focus',
1609
- code: 'INVALID_TYPE',
1610
- suggestion:
1611
- 'Use a feature id, array of ids, { features: "36", padding: 16 }, or { points: true }. Pass null to clear focus.',
1612
- });
1613
- }
1614
- }
1615
-
1616
- const encoding = spec.encoding as Record<string, unknown>;
1617
- const hasPoints = spec.points && typeof spec.points === 'object' && !Array.isArray(spec.points);
1618
-
1619
- // key is required unless basemap-only mode (points present + empty/no choropleth data)
1620
- const specData = spec.data as unknown[] | undefined;
1621
- const isBasemapOnly = hasPoints && (!specData || specData.length === 0);
1622
- const keyCh = encoding.key as Record<string, unknown> | undefined;
1623
- if (!isBasemapOnly) {
1624
- if (!keyCh || typeof keyCh !== 'object') {
1625
- errors.push({
1626
- message: 'Spec error: map encoding requires "key" channel',
1627
- path: 'encoding.key',
1628
- code: 'MISSING_FIELD',
1629
- suggestion: 'Add encoding.key, e.g. key: { field: "id", type: "nominal" }',
1630
- });
1631
- } else if (!keyCh.field || typeof keyCh.field !== 'string') {
1632
- errors.push({
1633
- message: 'Spec error: encoding.key must have a "field" string',
1634
- path: 'encoding.key.field',
1635
- code: 'MISSING_FIELD',
1636
- suggestion: 'Add a field name, e.g. key: { field: "id" }',
1637
- });
1638
- }
1639
- }
1640
-
1641
- // color is required UNLESS points is present (basemap-only mode)
1642
- const colorCh = encoding.color as Record<string, unknown> | undefined;
1643
- if (!hasPoints) {
1644
- if (!colorCh || typeof colorCh !== 'object') {
1645
- errors.push({
1646
- message:
1647
- 'Spec error: map encoding requires "color" channel (or add a "points" layer for basemap-only mode)',
1648
- path: 'encoding.color',
1649
- code: 'MISSING_FIELD',
1650
- suggestion: 'Add encoding.color, e.g. color: { field: "value", type: "quantitative" }',
1651
- });
1652
- } else if (!colorCh.field || typeof colorCh.field !== 'string') {
1653
- errors.push({
1654
- message: 'Spec error: encoding.color must have a "field" string',
1655
- path: 'encoding.color.field',
1656
- code: 'MISSING_FIELD',
1657
- suggestion: 'Add a field name, e.g. color: { field: "value" }',
1658
- });
1659
- }
1660
- } else if (
1661
- colorCh &&
1662
- typeof colorCh === 'object' &&
1663
- (!colorCh.field || typeof colorCh.field !== 'string')
1664
- ) {
1665
- errors.push({
1666
- message: 'Spec error: encoding.color must have a "field" string when provided',
1667
- path: 'encoding.color.field',
1668
- code: 'MISSING_FIELD',
1669
- suggestion: 'Add a field name, e.g. color: { field: "value" }',
1670
- });
1671
- }
1672
-
1673
- // Validate points layer if present
1674
- if (hasPoints) {
1675
- const points = spec.points as Record<string, unknown>;
1676
- if (!Array.isArray(points.data)) {
1677
- errors.push({
1678
- message: 'Spec error: points.data must be an array of data rows',
1679
- path: 'points.data',
1680
- code: 'INVALID_TYPE',
1681
- suggestion: 'Provide data as an array of objects with lat/lng fields',
1682
- });
1683
- }
1684
- for (const ch of ['longitude', 'latitude'] as const) {
1685
- const enc = points[ch] as Record<string, unknown> | undefined;
1686
- if (!enc || typeof enc !== 'object') {
1687
- errors.push({
1688
- message: `Spec error: points requires "${ch}" encoding channel`,
1689
- path: `points.${ch}`,
1690
- code: 'MISSING_FIELD',
1691
- suggestion: `Add points.${ch}, e.g. ${ch}: { field: "${ch === 'longitude' ? 'lon' : 'lat'}", type: "quantitative" }`,
1692
- });
1693
- } else if (!enc.field || typeof enc.field !== 'string') {
1694
- errors.push({
1695
- message: `Spec error: points.${ch} must have a "field" string`,
1696
- path: `points.${ch}.field`,
1697
- code: 'MISSING_FIELD',
1698
- suggestion: `Add a field name, e.g. ${ch}: { field: "${ch === 'longitude' ? 'lon' : 'lat'}" }`,
1699
- });
1700
- }
1701
- }
1702
- for (const ch of ['size', 'color', 'key'] as const) {
1703
- const enc = points[ch] as Record<string, unknown> | undefined;
1704
- if (enc && typeof enc === 'object' && (!enc.field || typeof enc.field !== 'string')) {
1705
- errors.push({
1706
- message: `Spec error: points.${ch} must have a "field" string when provided`,
1707
- path: `points.${ch}.field`,
1708
- code: 'MISSING_FIELD',
1709
- suggestion: `Add a field name, e.g. ${ch}: { field: "myField" }`,
1710
- });
1711
- }
1712
- }
1713
- }
1714
- }
1715
-
1716
- // ---------------------------------------------------------------------------
1717
- // BarList validation
1718
- // ---------------------------------------------------------------------------
1719
-
1720
- function validateBarListSpec(spec: Record<string, unknown>, errors: ValidationError[]): void {
1721
- if (!Array.isArray(spec.data)) {
1722
- errors.push({
1723
- message: 'Spec error: barlist spec requires a "data" array',
1724
- path: 'data',
1725
- code: 'INVALID_TYPE',
1726
- suggestion:
1727
- 'Provide data as an array of objects, e.g. data: [{ label: "Category A", value: 42 }]',
1728
- });
1729
- return;
1730
- }
1731
-
1732
- if (spec.data.length === 0) {
1733
- errors.push({
1734
- message: 'Spec error: "data" array must be non-empty',
1735
- path: 'data',
1736
- code: 'EMPTY_DATA',
1737
- suggestion: 'Add at least one data row',
1738
- });
1739
- return;
1740
- }
1741
-
1742
- const firstRow = spec.data[0] as unknown;
1743
- if (typeof firstRow !== 'object' || firstRow === null || Array.isArray(firstRow)) {
1744
- errors.push({
1745
- message: 'Spec error: each item in "data" must be a plain object',
1746
- path: 'data[0]',
1747
- code: 'INVALID_TYPE',
1748
- suggestion: 'Each data item should be an object, e.g. { label: "Category A", value: 42 }',
1749
- });
1750
- return;
1751
- }
1752
-
1753
- if (!spec.encoding || typeof spec.encoding !== 'object') {
1754
- errors.push({
1755
- message:
1756
- 'Spec error: barlist spec requires an "encoding" object with label and value channels',
1757
- path: 'encoding',
1758
- code: 'MISSING_FIELD',
1759
- suggestion:
1760
- 'Add an encoding object, e.g. encoding: { label: { field: "name", type: "nominal" }, value: { field: "count", type: "quantitative" } }',
1761
- });
1762
- return;
1763
- }
1764
-
1765
- const encoding = spec.encoding as Record<string, unknown>;
1766
- const dataColumns = new Set(Object.keys(firstRow as Record<string, unknown>));
1767
- const columnList = [...dataColumns];
1768
- const availableColumns = columnList.join(', ');
1769
-
1770
- for (const channel of ['label', 'value'] as const) {
1771
- const ch = encoding[channel] as Record<string, unknown> | undefined;
1772
- if (!ch || typeof ch !== 'object') {
1773
- errors.push({
1774
- message: `Spec error: barlist encoding requires "${channel}" channel`,
1775
- path: `encoding.${channel}`,
1776
- code: 'MISSING_FIELD',
1777
- suggestion: `Add encoding.${channel} with a field from your data (${availableColumns}). Example: ${channel}: { field: "${columnList[0] ?? 'myField'}", type: "${channel === 'value' ? 'quantitative' : 'nominal'}" }`,
1778
- });
1779
- continue;
1780
- }
1781
-
1782
- if (!ch.field || typeof ch.field !== 'string') {
1783
- errors.push({
1784
- message: `Spec error: encoding.${channel} must have a "field" string`,
1785
- path: `encoding.${channel}.field`,
1786
- code: 'MISSING_FIELD',
1787
- suggestion: `Add a field name from your data columns: ${availableColumns}`,
1788
- });
1789
- continue;
1790
- }
1791
-
1792
- if (!dataColumns.has(ch.field as string)) {
1793
- errors.push({
1794
- message: `Spec error: encoding.${channel}.field "${ch.field}" does not exist in data. Available columns: ${availableColumns}`,
1795
- path: `encoding.${channel}.field`,
1796
- code: 'DATA_FIELD_MISSING',
1797
- suggestion: `Use one of the available data columns: ${availableColumns}.${didYouMean(ch.field as string, columnList)}`,
1798
- });
1799
- }
1800
- }
1801
-
1802
- // Validate optional encoding channels
1803
- for (const channel of ['subtitle', 'color', 'tooltip'] as const) {
1804
- const ch = encoding[channel] as Record<string, unknown> | undefined;
1805
- if (!ch) continue;
1806
- const field = ch.field;
1807
- if (field && typeof field === 'string' && !dataColumns.has(field)) {
1808
- errors.push({
1809
- message: `Spec error: encoding.${channel}.field "${field}" does not exist in data. Available columns: ${availableColumns}`,
1810
- path: `encoding.${channel}.field`,
1811
- code: 'DATA_FIELD_MISSING',
1812
- suggestion: `Use one of the available data columns: ${availableColumns}.${didYouMean(field, columnList)}`,
1813
- });
1814
- }
1815
- }
1816
-
1817
- // Barlist never reads scale.scheme: bars cycle the built-in barlist palette
1818
- checkSchemeUnused(
1819
- encoding,
1820
- errors,
1821
- 'bar list colors cycle the built-in barlist palette',
1822
- 'Remove scale.scheme. Bar list colors are not configurable via encoding; they cycle the built-in palette.',
1823
- );
1824
-
1825
- if (spec.darkMode !== undefined && !VALID_DARK_MODES.has(spec.darkMode as string)) {
1826
- errors.push({
1827
- message: 'Spec error: darkMode must be "auto", "force", or "off"',
1828
- path: 'darkMode',
1829
- code: 'INVALID_VALUE',
1830
- suggestion:
1831
- 'Use one of: "auto" (system preference), "force" (always dark), or "off" (always light)',
1832
- });
1833
- }
1834
- }
1835
-
1836
- // ---------------------------------------------------------------------------
1837
- // Layer validation
1838
- // ---------------------------------------------------------------------------
1839
-
1840
- function validateLayerSpec(spec: Record<string, unknown>, errors: ValidationError[]): void {
1841
- const layer = spec.layer as unknown[];
1842
-
1843
- if (layer.length === 0) {
1844
- errors.push({
1845
- message: 'Spec error: "layer" must be a non-empty array',
1846
- path: 'layer',
1847
- code: 'EMPTY_DATA',
1848
- suggestion: 'Add at least one layer with a mark and encoding',
1849
- });
1850
- return;
1851
- }
1852
-
1853
- for (let i = 0; i < layer.length; i++) {
1854
- const child = layer[i];
1855
- if (!child || typeof child !== 'object' || Array.isArray(child)) {
1856
- errors.push({
1857
- message: `Spec error: layer[${i}] must be an object`,
1858
- path: `layer[${i}]`,
1859
- code: 'INVALID_TYPE',
1860
- suggestion:
1861
- 'Each layer must be a chart spec (with mark) or a nested layer spec (with layer)',
1862
- });
1863
- continue;
1864
- }
1865
-
1866
- const childObj = child as Record<string, unknown>;
1867
- const isNestedLayer = 'layer' in childObj && Array.isArray(childObj.layer);
1868
- const isChildChart = 'mark' in childObj;
1869
-
1870
- if (!isNestedLayer && !isChildChart) {
1871
- errors.push({
1872
- message: `Spec error: layer[${i}] must have a "mark" field or a "layer" array`,
1873
- path: `layer[${i}]`,
1874
- code: 'MISSING_FIELD',
1875
- suggestion:
1876
- 'Each layer must be a chart spec (with mark + encoding) or a nested layer spec (with layer array)',
1877
- });
1878
- continue;
1879
- }
1880
-
1881
- if (isNestedLayer) {
1882
- validateLayerSpec(childObj, errors);
1883
- } else if (isChildChart) {
1884
- // Validate mark type
1885
- const mark = childObj.mark;
1886
- let markValue: string | undefined;
1887
- if (typeof mark === 'string') {
1888
- markValue = mark;
1889
- } else if (mark && typeof mark === 'object' && !Array.isArray(mark)) {
1890
- markValue = (mark as Record<string, unknown>).type as string | undefined;
1891
- }
1892
-
1893
- if (!markValue || !MARK_TYPES.has(markValue)) {
1894
- errors.push({
1895
- message: `Spec error: layer[${i}].mark "${markValue ?? String(mark)}" is not a valid mark type`,
1896
- path: `layer[${i}].mark`,
1897
- code: 'INVALID_VALUE',
1898
- suggestion: `Change mark to one of: ${[...MARK_TYPES].join(', ')}`,
1899
- });
1900
- continue;
1901
- }
1902
-
1903
- // Child layers can inherit data and encoding from parent, so only validate
1904
- // if the child has its own data (or the parent provides shared data).
1905
- const hasOwnData = Array.isArray(childObj.data) && (childObj.data as unknown[]).length > 0;
1906
- const parentHasData = Array.isArray(spec.data) && (spec.data as unknown[]).length > 0;
1907
-
1908
- if (hasOwnData || parentHasData) {
1909
- // Build a merged spec for validation purposes
1910
- const mergedForValidation = { ...childObj };
1911
- if (!hasOwnData && parentHasData) {
1912
- mergedForValidation.data = spec.data;
1913
- }
1914
- // Merge encoding: parent fields are inherited unless child overrides
1915
- if (spec.encoding && typeof spec.encoding === 'object') {
1916
- mergedForValidation.encoding = {
1917
- ...(spec.encoding as Record<string, unknown>),
1918
- ...((childObj.encoding as Record<string, unknown>) ?? {}),
1919
- };
1920
- }
1921
- if (mergedForValidation.data && mergedForValidation.encoding) {
1922
- validateChartSpec(mergedForValidation, errors);
1923
- }
1924
- }
1925
- }
1926
- }
1927
- }
1928
-
1929
- // ---------------------------------------------------------------------------
1930
- // Public API
1931
- // ---------------------------------------------------------------------------
1932
-
1933
- /**
1934
- * Validate a spec at runtime.
1935
- *
1936
- * Checks structure, required fields, encoding rules, data shape, and
1937
- * field type compatibility. Returns structured errors with machine-readable
1938
- * codes and actionable suggestions for each problem found.
1939
- */
1940
- export function validateSpec(spec: unknown): ValidationResult {
1941
- const errors: ValidationError[] = [];
1942
-
1943
- // Basic shape check
1944
- if (!spec || typeof spec !== 'object' || Array.isArray(spec)) {
1945
- return {
1946
- valid: false,
1947
- errors: [
1948
- {
1949
- message: 'Spec error: spec must be a non-null object',
1950
- code: 'INVALID_TYPE',
1951
- suggestion:
1952
- 'Pass a spec object with at least a "mark" field for charts, e.g. { mark: "line", data: [...], encoding: {...} }',
1953
- },
1954
- ],
1955
- normalized: null,
1956
- };
1957
- }
1958
-
1959
- const obj = spec as Record<string, unknown>;
1960
-
1961
- // Determine spec type via structural discrimination:
1962
- // - Layer specs have a 'layer' array
1963
- // - Chart specs have a 'mark' field (string or object with type property)
1964
- // - Table specs have type: 'table'
1965
- // - Graph specs have type: 'graph'
1966
- // - Sankey specs have type: 'sankey'
1967
- // - TileMap specs have type: 'tilemap'
1968
- const hasLayer = 'layer' in obj && Array.isArray(obj.layer);
1969
- const hasMark = 'mark' in obj;
1970
- const isTable = obj.type === 'table';
1971
- const isGraph = obj.type === 'graph';
1972
- const isSankey = obj.type === 'sankey';
1973
- const isTileMap = obj.type === 'tilemap';
1974
- const isMap = obj.type === 'map';
1975
- const isBarList = obj.type === 'barlist';
1976
- const isLayer =
1977
- hasLayer && !isTable && !isGraph && !isSankey && !isTileMap && !isMap && !isBarList;
1978
- const isChart =
1979
- hasMark && !hasLayer && !isTable && !isGraph && !isSankey && !isTileMap && !isMap && !isBarList;
1980
-
1981
- if (
1982
- !isChart &&
1983
- !isTable &&
1984
- !isGraph &&
1985
- !isSankey &&
1986
- !isTileMap &&
1987
- !isMap &&
1988
- !isBarList &&
1989
- !isLayer
1990
- ) {
1991
- // Near-misses for VL composition operators that are unsupported by decision
1992
- if ('hconcat' in obj || 'vconcat' in obj) {
1993
- const key = 'hconcat' in obj ? 'hconcat' : 'vconcat';
1994
- return {
1995
- valid: false,
1996
- errors: [
1997
- {
1998
- message: `Spec error: "${key}" composition is not supported`,
1999
- path: key,
2000
- code: 'INVALID_VALUE',
2001
- suggestion:
2002
- 'Render each chart in its own container instead. For small multiples of the same chart, use the facet encoding channel: encoding.facet = { field, type }',
2003
- },
2004
- ],
2005
- normalized: null,
2006
- };
2007
- }
2008
- if ('facet' in obj && 'spec' in obj) {
2009
- return {
2010
- valid: false,
2011
- errors: [
2012
- {
2013
- message: 'Spec error: the top-level "facet" operator is not supported',
2014
- path: 'facet',
2015
- code: 'INVALID_VALUE',
2016
- suggestion:
2017
- 'Use the facet encoding channel on a regular chart spec instead: encoding.facet = { field: "category", type: "nominal" }',
2018
- },
2019
- ],
2020
- normalized: null,
2021
- };
2022
- }
2023
- return {
2024
- valid: false,
2025
- errors: [
2026
- {
2027
- message:
2028
- 'Spec error: spec must have a "mark" field for charts, a "layer" array for layered charts, or a "type" field for tables/graphs/sankey/tilemap/map/barlist',
2029
- path: 'mark',
2030
- code: 'MISSING_FIELD',
2031
- suggestion: `Add a "mark" field for charts (e.g. mark: "bar"), a "layer" array for layered charts, or a "type" field (type: "table", type: "graph", type: "sankey", type: "tilemap", type: "map", or type: "barlist"). Valid mark types: ${[...MARK_TYPES].join(', ')}`,
2032
- },
2033
- ],
2034
- normalized: null,
2035
- };
2036
- }
2037
-
2038
- // For layer specs, validate each child layer recursively
2039
- if (isLayer) {
2040
- validateLayerSpec(obj, errors);
2041
- }
2042
-
2043
- // For chart specs, validate the mark field
2044
- if (isChart) {
2045
- const mark = obj.mark;
2046
- let markValue: string | undefined;
2047
-
2048
- if (typeof mark === 'string') {
2049
- markValue = mark;
2050
- } else if (mark && typeof mark === 'object' && !Array.isArray(mark)) {
2051
- markValue = (mark as Record<string, unknown>).type as string | undefined;
2052
- }
2053
-
2054
- if (!markValue || !MARK_TYPES.has(markValue)) {
2055
- return {
2056
- valid: false,
2057
- errors: [
2058
- {
2059
- message: `Spec error: "${markValue ?? String(mark)}" is not a valid mark type. Valid mark types: ${[...MARK_TYPES].join(', ')}`,
2060
- path: 'mark',
2061
- code: 'INVALID_VALUE',
2062
- suggestion: `Change mark to one of: ${[...MARK_TYPES].join(', ')}`,
2063
- },
2064
- ],
2065
- normalized: null,
2066
- };
2067
- }
2068
-
2069
- validateChartSpec(obj, errors);
2070
- } else if (isTable) {
2071
- validateTableSpec(obj, errors);
2072
- } else if (isGraph) {
2073
- validateGraphSpec(obj, errors);
2074
- } else if (isSankey) {
2075
- validateSankeySpec(obj, errors);
2076
- } else if (isTileMap) {
2077
- validateTileMapSpec(obj, errors);
2078
- } else if (isMap) {
2079
- validateMapSpec(obj, errors);
2080
- } else if (isBarList) {
2081
- validateBarListSpec(obj, errors);
2082
- }
2083
-
2084
- if (errors.length > 0) {
2085
- return { valid: false, errors, normalized: null };
2086
- }
2087
-
2088
- return {
2089
- valid: true,
2090
- errors: [],
2091
- normalized: spec as VizSpec,
2092
- };
2093
- }