@contractspec/lib.presentation-runtime-core 3.7.5 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +60 -54
  2. package/dist/browser/index.js +473 -1
  3. package/dist/browser/table.js +21 -0
  4. package/dist/browser/visualization.echarts.js +148 -0
  5. package/dist/browser/visualization.js +307 -0
  6. package/dist/browser/visualization.model.builders.js +290 -0
  7. package/dist/browser/visualization.model.helpers.js +199 -0
  8. package/dist/browser/visualization.model.js +306 -0
  9. package/dist/browser/visualization.types.js +0 -0
  10. package/dist/browser/visualization.utils.js +65 -0
  11. package/dist/index.d.ts +5 -0
  12. package/dist/index.js +473 -1
  13. package/dist/node/index.js +473 -1
  14. package/dist/node/table.js +21 -0
  15. package/dist/node/visualization.echarts.js +148 -0
  16. package/dist/node/visualization.js +307 -0
  17. package/dist/node/visualization.model.builders.js +290 -0
  18. package/dist/node/visualization.model.helpers.js +199 -0
  19. package/dist/node/visualization.model.js +306 -0
  20. package/dist/node/visualization.types.js +0 -0
  21. package/dist/node/visualization.utils.js +65 -0
  22. package/dist/table.d.ts +99 -0
  23. package/dist/table.js +22 -0
  24. package/dist/visualization.d.ts +3 -0
  25. package/dist/visualization.echarts.d.ts +3 -0
  26. package/dist/visualization.echarts.js +149 -0
  27. package/dist/visualization.js +308 -0
  28. package/dist/visualization.model.builders.d.ts +20 -0
  29. package/dist/visualization.model.builders.js +291 -0
  30. package/dist/visualization.model.d.ts +3 -0
  31. package/dist/visualization.model.helpers.d.ts +60 -0
  32. package/dist/visualization.model.helpers.js +200 -0
  33. package/dist/visualization.model.js +307 -0
  34. package/dist/visualization.model.test.d.ts +1 -0
  35. package/dist/visualization.types.d.ts +74 -0
  36. package/dist/visualization.types.js +1 -0
  37. package/dist/visualization.utils.d.ts +5 -0
  38. package/dist/visualization.utils.js +66 -0
  39. package/package.json +121 -5
@@ -0,0 +1,149 @@
1
+ // @bun
2
+ // src/visualization.echarts.ts
3
+ function buildVisualizationEChartsOption(model) {
4
+ const thresholdLines = model.thresholds.map((threshold) => ({
5
+ yAxis: threshold.value,
6
+ name: threshold.label,
7
+ lineStyle: {
8
+ color: threshold.color ?? "#ef4444",
9
+ type: "dashed"
10
+ }
11
+ }));
12
+ const annotationLines = model.annotations.filter((annotation) => annotation.kind === "line" && annotation.y != null).map((annotation) => toMarkLine(annotation));
13
+ switch (model.kind) {
14
+ case "cartesian":
15
+ const cartesianSeries = model.series.map((series) => ({
16
+ name: series.label,
17
+ type: resolveCartesianSeriesType(series.type),
18
+ smooth: series.smooth,
19
+ stack: series.stack,
20
+ areaStyle: series.type === "area" ? {} : undefined,
21
+ itemStyle: series.color ? { color: series.color } : undefined,
22
+ lineStyle: series.color ? { color: series.color } : undefined,
23
+ data: series.points.filter((point) => point.y != null).map((point) => [point.x, point.y]),
24
+ markLine: thresholdLines.length || annotationLines.length ? { data: [...thresholdLines, ...annotationLines] } : undefined
25
+ }));
26
+ return {
27
+ color: model.palette,
28
+ tooltip: model.tooltip === false ? undefined : { trigger: "axis" },
29
+ legend: { show: model.legend ?? model.series.length > 1 },
30
+ xAxis: { type: model.xAxis?.type === "time" ? "time" : "category" },
31
+ yAxis: { type: "value", name: model.yAxis?.label },
32
+ series: cartesianSeries
33
+ };
34
+ case "pie":
35
+ const pieSeries = [
36
+ {
37
+ type: "pie",
38
+ radius: ["0%", "70%"],
39
+ data: model.series[0]?.points.filter((point) => point.value != null).map((point) => ({
40
+ name: point.name ?? "",
41
+ value: point.value
42
+ })) ?? []
43
+ }
44
+ ];
45
+ return {
46
+ color: model.palette,
47
+ tooltip: model.tooltip === false ? undefined : { trigger: "item" },
48
+ series: pieSeries
49
+ };
50
+ case "heatmap":
51
+ const heatmapSeries = [
52
+ {
53
+ type: "heatmap",
54
+ data: model.series[0]?.points.filter((point) => point.value != null && point.name != null).map((point) => [point.x, point.name, point.value]) ?? []
55
+ }
56
+ ];
57
+ return {
58
+ color: model.palette,
59
+ tooltip: model.tooltip === false ? undefined : { position: "top" },
60
+ xAxis: {
61
+ type: "category",
62
+ data: uniqueValues(model.series[0]?.points.map((point) => point.x))
63
+ },
64
+ yAxis: {
65
+ type: "category",
66
+ data: uniqueValues(model.series[0]?.points.map((point) => point.name))
67
+ },
68
+ visualMap: {
69
+ min: 0,
70
+ max: maxValue(model.series[0]?.points.map((point) => point.value)),
71
+ calculable: true,
72
+ orient: "horizontal",
73
+ left: "center",
74
+ bottom: 0
75
+ },
76
+ series: heatmapSeries
77
+ };
78
+ case "funnel":
79
+ const funnelSeries = [
80
+ {
81
+ type: "funnel",
82
+ data: model.series[0]?.points.filter((point) => point.value != null).map((point) => ({
83
+ name: point.name ?? "",
84
+ value: point.value
85
+ })) ?? []
86
+ }
87
+ ];
88
+ return {
89
+ color: model.palette,
90
+ tooltip: model.tooltip === false ? undefined : { trigger: "item" },
91
+ series: funnelSeries
92
+ };
93
+ case "geo":
94
+ if (!model.geo || model.geo.mode === "slippy-map" || !model.geo.geoJson) {
95
+ return {};
96
+ }
97
+ const geoSeries = [
98
+ {
99
+ type: model.geo.variant === "heatmap" ? "heatmap" : "scatter",
100
+ coordinateSystem: "geo",
101
+ data: model.series[0]?.points.filter((point) => point.longitude != null && point.latitude != null && point.value != null).map((point) => ({
102
+ name: point.name ?? "",
103
+ value: [
104
+ point.longitude,
105
+ point.latitude,
106
+ point.value
107
+ ]
108
+ })) ?? []
109
+ }
110
+ ];
111
+ return {
112
+ color: model.palette,
113
+ tooltip: model.tooltip === false ? undefined : { trigger: "item" },
114
+ geo: {
115
+ map: "contractspec-visualization-geo",
116
+ roam: true
117
+ },
118
+ series: geoSeries
119
+ };
120
+ default:
121
+ return {};
122
+ }
123
+ }
124
+ function uniqueValues(values) {
125
+ return Array.from(new Set((values ?? []).filter((value) => value != null).map(String)));
126
+ }
127
+ function maxValue(values) {
128
+ return Math.max(...(values ?? []).map((value) => value ?? 0), 1);
129
+ }
130
+ function toMarkLine(annotation) {
131
+ return {
132
+ yAxis: annotation.y,
133
+ name: annotation.label,
134
+ lineStyle: {
135
+ color: annotation.color ?? "#2563eb",
136
+ type: "solid"
137
+ }
138
+ };
139
+ }
140
+ function resolveCartesianSeriesType(type) {
141
+ if (type === "bar")
142
+ return "bar";
143
+ if (type === "scatter")
144
+ return "scatter";
145
+ return "line";
146
+ }
147
+ export {
148
+ buildVisualizationEChartsOption
149
+ };
@@ -0,0 +1,308 @@
1
+ // @bun
2
+ // src/visualization.utils.ts
3
+ function formatVisualizationValue(value, format) {
4
+ if (value == null)
5
+ return "\u2014";
6
+ if (format === "currency" && typeof value === "number") {
7
+ return new Intl.NumberFormat(undefined, {
8
+ style: "currency",
9
+ currency: "USD"
10
+ }).format(value);
11
+ }
12
+ if (format === "percentage" && typeof value === "number") {
13
+ return `${(value * 100).toFixed(1)}%`;
14
+ }
15
+ if ((format === "date" || format === "dateTime") && value) {
16
+ const date = value instanceof Date ? value : new Date(String(value));
17
+ return Number.isNaN(date.getTime()) ? String(value) : new Intl.DateTimeFormat(undefined, {
18
+ dateStyle: "medium",
19
+ timeStyle: format === "dateTime" ? "short" : undefined
20
+ }).format(date);
21
+ }
22
+ return String(value);
23
+ }
24
+ function resolveVisualizationRows(data, resultPath) {
25
+ const value = resultPath ? getAtPath(data, resultPath) : data;
26
+ const candidate = value ?? data;
27
+ if (Array.isArray(candidate))
28
+ return candidate.map(asRow);
29
+ if (Array.isArray(getAtPath(candidate, "items"))) {
30
+ return getAtPath(candidate, "items").map(asRow);
31
+ }
32
+ if (Array.isArray(getAtPath(candidate, "rows"))) {
33
+ return getAtPath(candidate, "rows").map(asRow);
34
+ }
35
+ if (Array.isArray(getAtPath(candidate, "data"))) {
36
+ return getAtPath(candidate, "data").map(asRow);
37
+ }
38
+ return candidate && typeof candidate === "object" ? [asRow(candidate)] : [];
39
+ }
40
+ function getAtPath(source, path) {
41
+ if (!path || source == null)
42
+ return source;
43
+ return path.replace(/\[(\d+)\]/g, ".$1").split(".").filter(Boolean).reduce((current, segment) => {
44
+ if (current == null || typeof current !== "object")
45
+ return;
46
+ return current[segment];
47
+ }, source);
48
+ }
49
+ function toNumber(value) {
50
+ if (typeof value === "number" && Number.isFinite(value))
51
+ return value;
52
+ if (typeof value === "string" && value.trim()) {
53
+ const parsed = Number(value);
54
+ return Number.isFinite(parsed) ? parsed : null;
55
+ }
56
+ return null;
57
+ }
58
+ function asRow(value) {
59
+ return value && typeof value === "object" ? value : { value };
60
+ }
61
+
62
+ // src/visualization.model.helpers.ts
63
+ function createVisualizationMaps(spec) {
64
+ return {
65
+ dimensions: new Map((spec.visualization.dimensions ?? []).map((dimension) => [
66
+ dimension.key,
67
+ dimension
68
+ ])),
69
+ measures: new Map((spec.visualization.measures ?? []).map((measure) => [
70
+ measure.key,
71
+ measure
72
+ ]))
73
+ };
74
+ }
75
+ function createVisualizationBaseModel(spec, rows, maps) {
76
+ const config = spec.visualization;
77
+ return {
78
+ kind: config.kind,
79
+ title: config.title ?? spec.meta.title,
80
+ description: config.description ?? spec.meta.description,
81
+ summary: `${spec.meta.title ?? spec.meta.key}: ${rows.length} row${rows.length === 1 ? "" : "s"}`,
82
+ warnings: rows.length === 0 ? ["No visualization rows available."] : [],
83
+ palette: config.palette,
84
+ legend: config.legend,
85
+ tooltip: config.tooltip,
86
+ drilldown: config.drilldown,
87
+ thresholds: config.thresholds ?? [],
88
+ annotations: (config.annotations ?? []).map((annotation) => resolveAnnotation(annotation, rows[0] ?? {})),
89
+ table: createTable(config.table?.caption, config, rows)
90
+ };
91
+ }
92
+ function createMeasureSeries(measureKey, measures, rows, dimension, config) {
93
+ const measure = measures.get(measureKey);
94
+ if (!measure)
95
+ return null;
96
+ return {
97
+ key: config?.key ?? measure.key,
98
+ label: config?.label ?? measure.label,
99
+ type: config?.type,
100
+ color: config?.color ?? measure.color,
101
+ stack: config?.stack,
102
+ smooth: config?.smooth,
103
+ points: rows.map((row, index) => ({
104
+ id: `${measure.key}-${index}`,
105
+ raw: row,
106
+ x: dimension ? readDimensionValue(row, dimension) : index,
107
+ y: numericValue(row, measure),
108
+ value: numericValue(row, measure)
109
+ }))
110
+ };
111
+ }
112
+ function defaultSeries(keys) {
113
+ return keys.map((key) => ({ key, label: key, measure: key }));
114
+ }
115
+ function createAxis(dimension) {
116
+ if (!dimension)
117
+ return;
118
+ return {
119
+ key: dimension.key,
120
+ label: dimension.label,
121
+ type: dimension.type === "time" ? "time" : dimension.type === "number" ? "number" : "category",
122
+ format: dimension.format
123
+ };
124
+ }
125
+ function createValueAxis(key, measures) {
126
+ const measure = key ? measures.get(key) : undefined;
127
+ if (!measure)
128
+ return;
129
+ return {
130
+ key: measure.key,
131
+ label: measure.label,
132
+ type: "number",
133
+ format: measure.format
134
+ };
135
+ }
136
+ function readValue(row, measure) {
137
+ return measure ? getAtPath(row, measure.dataPath) : undefined;
138
+ }
139
+ function readDimensionValue(row, dimension) {
140
+ return dimension ? getAtPath(row, dimension.dataPath) : undefined;
141
+ }
142
+ function numericValue(row, measure) {
143
+ return toNumber(readValue(row, measure));
144
+ }
145
+ function numericPathValue(row, dimension) {
146
+ return toNumber(readDimensionValue(row, dimension));
147
+ }
148
+ function stringValue(row, dimension) {
149
+ const value = readDimensionValue(row, dimension);
150
+ return value == null ? undefined : String(value);
151
+ }
152
+ function createTable(caption, config, rows) {
153
+ const dimensions = config.dimensions ?? [];
154
+ const measures = config.measures ?? [];
155
+ return {
156
+ caption,
157
+ columns: [
158
+ ...dimensions.map((dimension) => ({
159
+ key: dimension.key,
160
+ label: dimension.label
161
+ })),
162
+ ...measures.map((measure) => ({
163
+ key: measure.key,
164
+ label: measure.label
165
+ }))
166
+ ],
167
+ rows: rows.map((row) => ({
168
+ ...Object.fromEntries(dimensions.map((dimension) => [
169
+ dimension.key,
170
+ readDimensionValue(row, dimension)
171
+ ])),
172
+ ...Object.fromEntries(measures.map((measure) => [measure.key, readValue(row, measure)]))
173
+ }))
174
+ };
175
+ }
176
+ function resolveAnnotation(annotation, row) {
177
+ return {
178
+ key: annotation.key,
179
+ label: annotation.label,
180
+ kind: annotation.kind,
181
+ color: annotation.color,
182
+ x: annotation.xDataPath ? getAtPath(row, annotation.xDataPath) : undefined,
183
+ y: annotation.yDataPath ? toNumber(getAtPath(row, annotation.yDataPath)) : undefined,
184
+ start: annotation.startDataPath ? getAtPath(row, annotation.startDataPath) : undefined,
185
+ end: annotation.endDataPath ? getAtPath(row, annotation.endDataPath) : undefined
186
+ };
187
+ }
188
+
189
+ // src/visualization.model.builders.ts
190
+ function buildMetricModel(base, config, rows, maps) {
191
+ const measure = maps.measures.get(config.measure);
192
+ const comparison = config.comparisonMeasure ? maps.measures.get(config.comparisonMeasure) : undefined;
193
+ const currentRow = rows.at(-1) ?? {};
194
+ const sparkline = config.sparkline ? createMeasureSeries(config.sparkline.measure ?? config.measure, maps.measures, rows, maps.dimensions.get(config.sparkline.dimension)) : null;
195
+ return {
196
+ ...base,
197
+ series: sparkline ? [sparkline] : [],
198
+ metric: {
199
+ label: measure?.label ?? config.measure,
200
+ value: readValue(currentRow, measure),
201
+ comparisonValue: comparison ? readValue(currentRow, comparison) : undefined,
202
+ format: measure?.format
203
+ }
204
+ };
205
+ }
206
+ function buildCartesianModel(base, config, rows, maps) {
207
+ const series = (config.series ?? defaultSeries(config.yMeasures ?? [])).map((seriesItem) => createMeasureSeries(seriesItem.measure, maps.measures, rows, maps.dimensions.get(config.xDimension), seriesItem)).filter((item) => Boolean(item));
208
+ return {
209
+ ...base,
210
+ series,
211
+ xAxis: createAxis(maps.dimensions.get(config.xDimension)),
212
+ yAxis: createValueAxis(config.yMeasures?.[0], maps.measures)
213
+ };
214
+ }
215
+ function buildDistributionModel(base, config, rows, maps) {
216
+ const nameDimension = maps.dimensions.get(config.nameDimension);
217
+ const valueMeasure = maps.measures.get(config.valueMeasure);
218
+ return {
219
+ ...base,
220
+ series: [
221
+ {
222
+ key: valueMeasure?.key ?? config.valueMeasure,
223
+ label: valueMeasure?.label ?? config.valueMeasure,
224
+ type: config.kind,
225
+ points: rows.map((row, index) => ({
226
+ id: `${config.kind}-${index}`,
227
+ raw: row,
228
+ name: stringValue(row, nameDimension),
229
+ value: numericValue(row, valueMeasure)
230
+ }))
231
+ }
232
+ ]
233
+ };
234
+ }
235
+ function buildHeatmapModel(base, config, rows, maps) {
236
+ const xDimension = maps.dimensions.get(config.xDimension);
237
+ const yDimension = maps.dimensions.get(config.yDimension);
238
+ const valueMeasure = maps.measures.get(config.valueMeasure);
239
+ return {
240
+ ...base,
241
+ series: [
242
+ {
243
+ key: config.valueMeasure,
244
+ label: valueMeasure?.label ?? config.valueMeasure,
245
+ type: "heatmap",
246
+ points: rows.map((row, index) => ({
247
+ id: `heatmap-${index}`,
248
+ raw: row,
249
+ name: stringValue(row, yDimension),
250
+ x: readDimensionValue(row, xDimension),
251
+ y: numericValue(row, valueMeasure),
252
+ value: numericValue(row, valueMeasure)
253
+ }))
254
+ }
255
+ ],
256
+ xAxis: createAxis(xDimension),
257
+ yAxis: createAxis(yDimension)
258
+ };
259
+ }
260
+ function buildGeoModel(base, config, rows, maps) {
261
+ return {
262
+ ...base,
263
+ series: [
264
+ {
265
+ key: "geo",
266
+ label: "Geo",
267
+ type: config.variant ?? "scatter",
268
+ points: rows.map((row, index) => ({
269
+ id: `geo-${index}`,
270
+ raw: row,
271
+ name: config.nameDimension ? stringValue(row, maps.dimensions.get(config.nameDimension)) : undefined,
272
+ value: config.valueMeasure ? numericValue(row, maps.measures.get(config.valueMeasure)) : undefined,
273
+ latitude: numericPathValue(row, maps.dimensions.get(config.latitudeDimension ?? "")),
274
+ longitude: numericPathValue(row, maps.dimensions.get(config.longitudeDimension ?? ""))
275
+ }))
276
+ }
277
+ ],
278
+ geo: {
279
+ mode: config.mode ?? "chart",
280
+ variant: config.variant ?? "scatter",
281
+ geoJson: config.geoJson
282
+ }
283
+ };
284
+ }
285
+
286
+ // src/visualization.model.ts
287
+ function createVisualizationModel(spec, data) {
288
+ const rows = resolveVisualizationRows(data, spec.source.resultPath);
289
+ const maps = createVisualizationMaps(spec);
290
+ const base = createVisualizationBaseModel(spec, rows, maps);
291
+ switch (spec.visualization.kind) {
292
+ case "metric":
293
+ return buildMetricModel(base, spec.visualization, rows, maps);
294
+ case "cartesian":
295
+ return buildCartesianModel(base, spec.visualization, rows, maps);
296
+ case "pie":
297
+ case "funnel":
298
+ return buildDistributionModel(base, spec.visualization, rows, maps);
299
+ case "heatmap":
300
+ return buildHeatmapModel(base, spec.visualization, rows, maps);
301
+ case "geo":
302
+ return buildGeoModel(base, spec.visualization, rows, maps);
303
+ }
304
+ }
305
+ export {
306
+ formatVisualizationValue,
307
+ createVisualizationModel
308
+ };
@@ -0,0 +1,20 @@
1
+ import type { VisualizationSpec } from '@contractspec/lib.contracts-spec/visualizations';
2
+ import { type VisualizationModelMaps } from './visualization.model.helpers';
3
+ import type { ContractVisualizationRenderModel } from './visualization.types';
4
+ type VisualizationModelBase = Omit<ContractVisualizationRenderModel, 'series' | 'metric' | 'xAxis' | 'yAxis' | 'geo'>;
5
+ export declare function buildMetricModel(base: VisualizationModelBase, config: Extract<VisualizationSpec['visualization'], {
6
+ kind: 'metric';
7
+ }>, rows: Record<string, unknown>[], maps: VisualizationModelMaps): ContractVisualizationRenderModel;
8
+ export declare function buildCartesianModel(base: VisualizationModelBase, config: Extract<VisualizationSpec['visualization'], {
9
+ kind: 'cartesian';
10
+ }>, rows: Record<string, unknown>[], maps: VisualizationModelMaps): ContractVisualizationRenderModel;
11
+ export declare function buildDistributionModel(base: VisualizationModelBase, config: Extract<VisualizationSpec['visualization'], {
12
+ kind: 'pie' | 'funnel';
13
+ }>, rows: Record<string, unknown>[], maps: VisualizationModelMaps): ContractVisualizationRenderModel;
14
+ export declare function buildHeatmapModel(base: VisualizationModelBase, config: Extract<VisualizationSpec['visualization'], {
15
+ kind: 'heatmap';
16
+ }>, rows: Record<string, unknown>[], maps: VisualizationModelMaps): ContractVisualizationRenderModel;
17
+ export declare function buildGeoModel(base: VisualizationModelBase, config: Extract<VisualizationSpec['visualization'], {
18
+ kind: 'geo';
19
+ }>, rows: Record<string, unknown>[], maps: VisualizationModelMaps): ContractVisualizationRenderModel;
20
+ export {};