@outsidedata/dolex 0.1.13 → 0.2.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 (160) hide show
  1. package/dist/src/analysis/rules.d.ts.map +1 -1
  2. package/dist/src/analysis/rules.js +8 -2
  3. package/dist/src/analysis/rules.js.map +1 -1
  4. package/dist/src/connectors/csv.d.ts.map +1 -1
  5. package/dist/src/connectors/csv.js +31 -1
  6. package/dist/src/connectors/csv.js.map +1 -1
  7. package/dist/src/connectors/dsl-compiler.d.ts +4 -0
  8. package/dist/src/connectors/dsl-compiler.d.ts.map +1 -1
  9. package/dist/src/connectors/dsl-compiler.js +51 -18
  10. package/dist/src/connectors/dsl-compiler.js.map +1 -1
  11. package/dist/src/connectors/dsl-validator.js +6 -1
  12. package/dist/src/connectors/dsl-validator.js.map +1 -1
  13. package/dist/src/connectors/js-aggregation.d.ts.map +1 -1
  14. package/dist/src/connectors/js-aggregation.js +18 -12
  15. package/dist/src/connectors/js-aggregation.js.map +1 -1
  16. package/dist/src/mcp/index.js +62 -28
  17. package/dist/src/mcp/index.js.map +1 -1
  18. package/dist/src/mcp/spec-store.d.ts +2 -1
  19. package/dist/src/mcp/spec-store.d.ts.map +1 -1
  20. package/dist/src/mcp/spec-store.js +4 -2
  21. package/dist/src/mcp/spec-store.js.map +1 -1
  22. package/dist/src/mcp/tools/dsl-schemas.d.ts +52 -51
  23. package/dist/src/mcp/tools/dsl-schemas.d.ts.map +1 -1
  24. package/dist/src/mcp/tools/dsl-schemas.js +1 -1
  25. package/dist/src/mcp/tools/dsl-schemas.js.map +1 -1
  26. package/dist/src/mcp/tools/list-patterns.js +2 -2
  27. package/dist/src/mcp/tools/list-patterns.js.map +1 -1
  28. package/dist/src/mcp/tools/query-source.d.ts +16 -16
  29. package/dist/src/mcp/tools/refine.d.ts +124 -15
  30. package/dist/src/mcp/tools/refine.d.ts.map +1 -1
  31. package/dist/src/mcp/tools/refine.js +335 -253
  32. package/dist/src/mcp/tools/refine.js.map +1 -1
  33. package/dist/src/mcp/tools/shared.d.ts +15 -2
  34. package/dist/src/mcp/tools/shared.d.ts.map +1 -1
  35. package/dist/src/mcp/tools/shared.js +64 -6
  36. package/dist/src/mcp/tools/shared.js.map +1 -1
  37. package/dist/src/mcp/tools/visualize-from-source.d.ts +52 -76
  38. package/dist/src/mcp/tools/visualize-from-source.d.ts.map +1 -1
  39. package/dist/src/mcp/tools/visualize-from-source.js +20 -5
  40. package/dist/src/mcp/tools/visualize-from-source.js.map +1 -1
  41. package/dist/src/mcp/tools/visualize.d.ts +45 -100
  42. package/dist/src/mcp/tools/visualize.d.ts.map +1 -1
  43. package/dist/src/mcp/tools/visualize.js +19 -19
  44. package/dist/src/mcp/tools/visualize.js.map +1 -1
  45. package/dist/src/patterns/definitions/comparison/grouped-bar.js +5 -5
  46. package/dist/src/patterns/definitions/comparison/grouped-bar.js.map +1 -1
  47. package/dist/src/patterns/definitions/composition/waffle.d.ts.map +1 -1
  48. package/dist/src/patterns/definitions/composition/waffle.js +17 -3
  49. package/dist/src/patterns/definitions/composition/waffle.js.map +1 -1
  50. package/dist/src/patterns/definitions/distribution/strip-plot.d.ts.map +1 -1
  51. package/dist/src/patterns/definitions/distribution/strip-plot.js +12 -3
  52. package/dist/src/patterns/definitions/distribution/strip-plot.js.map +1 -1
  53. package/dist/src/patterns/definitions/time/sparkline-grid.js +2 -2
  54. package/dist/src/patterns/definitions/time/sparkline-grid.js.map +1 -1
  55. package/dist/src/patterns/selector.d.ts.map +1 -1
  56. package/dist/src/patterns/selector.js +46 -1
  57. package/dist/src/patterns/selector.js.map +1 -1
  58. package/dist/src/renderers/d3/comparison/bar.d.ts.map +1 -1
  59. package/dist/src/renderers/d3/comparison/bar.js +24 -1
  60. package/dist/src/renderers/d3/comparison/bar.js.map +1 -1
  61. package/dist/src/renderers/d3/comparison/grouped-bar.d.ts.map +1 -1
  62. package/dist/src/renderers/d3/comparison/grouped-bar.js +9 -4
  63. package/dist/src/renderers/d3/comparison/grouped-bar.js.map +1 -1
  64. package/dist/src/renderers/d3/composition/donut.d.ts.map +1 -1
  65. package/dist/src/renderers/d3/composition/donut.js +12 -0
  66. package/dist/src/renderers/d3/composition/donut.js.map +1 -1
  67. package/dist/src/renderers/d3/composition/stacked-bar.d.ts.map +1 -1
  68. package/dist/src/renderers/d3/composition/stacked-bar.js +4 -0
  69. package/dist/src/renderers/d3/composition/stacked-bar.js.map +1 -1
  70. package/dist/src/renderers/d3/composition/treemap.js +2 -1
  71. package/dist/src/renderers/d3/composition/treemap.js.map +1 -1
  72. package/dist/src/renderers/d3/distribution/beeswarm.d.ts.map +1 -1
  73. package/dist/src/renderers/d3/distribution/beeswarm.js +8 -0
  74. package/dist/src/renderers/d3/distribution/beeswarm.js.map +1 -1
  75. package/dist/src/renderers/d3/distribution/histogram.js +36 -2
  76. package/dist/src/renderers/d3/distribution/histogram.js.map +1 -1
  77. package/dist/src/renderers/d3/flow/funnel.d.ts.map +1 -1
  78. package/dist/src/renderers/d3/flow/funnel.js +4 -0
  79. package/dist/src/renderers/d3/flow/funnel.js.map +1 -1
  80. package/dist/src/renderers/d3/flow/sankey-layout.js +20 -3
  81. package/dist/src/renderers/d3/flow/sankey-layout.js.map +1 -1
  82. package/dist/src/renderers/d3/heatmap.d.ts.map +1 -1
  83. package/dist/src/renderers/d3/heatmap.js +18 -3
  84. package/dist/src/renderers/d3/heatmap.js.map +1 -1
  85. package/dist/src/renderers/d3/radar.d.ts.map +1 -1
  86. package/dist/src/renderers/d3/radar.js +3 -1
  87. package/dist/src/renderers/d3/radar.js.map +1 -1
  88. package/dist/src/renderers/d3/relationship.d.ts.map +1 -1
  89. package/dist/src/renderers/d3/relationship.js +29 -7
  90. package/dist/src/renderers/d3/relationship.js.map +1 -1
  91. package/dist/src/renderers/d3/shared.js +7 -7
  92. package/dist/src/renderers/d3/shared.js.map +1 -1
  93. package/dist/src/renderers/d3/time/area.js +21 -7
  94. package/dist/src/renderers/d3/time/area.js.map +1 -1
  95. package/dist/src/renderers/d3/time/calendar-heatmap.js +6 -0
  96. package/dist/src/renderers/d3/time/calendar-heatmap.js.map +1 -1
  97. package/dist/src/renderers/d3/time/horizon-chart.d.ts.map +1 -1
  98. package/dist/src/renderers/d3/time/horizon-chart.js +10 -0
  99. package/dist/src/renderers/d3/time/horizon-chart.js.map +1 -1
  100. package/dist/src/renderers/d3/time/line.d.ts.map +1 -1
  101. package/dist/src/renderers/d3/time/line.js +27 -7
  102. package/dist/src/renderers/d3/time/line.js.map +1 -1
  103. package/dist/src/renderers/d3/time/small-multiples.js +8 -0
  104. package/dist/src/renderers/d3/time/small-multiples.js.map +1 -1
  105. package/dist/src/renderers/d3/time/sparkline-grid.d.ts.map +1 -1
  106. package/dist/src/renderers/d3/time/sparkline-grid.js +5 -2
  107. package/dist/src/renderers/d3/time/sparkline-grid.js.map +1 -1
  108. package/dist/src/renderers/d3/time/stream-graph.js +6 -0
  109. package/dist/src/renderers/d3/time/stream-graph.js.map +1 -1
  110. package/dist/src/renderers/html/_generated/bundles.d.ts +39 -39
  111. package/dist/src/renderers/html/_generated/bundles.d.ts.map +1 -1
  112. package/dist/src/renderers/html/_generated/bundles.js +39 -39
  113. package/dist/src/renderers/html/_generated/bundles.js.map +1 -1
  114. package/dist/src/renderers/html/template.js +2 -2
  115. package/dist/src/renderers/html/template.js.map +1 -1
  116. package/dist/src/types.d.ts +30 -2
  117. package/dist/src/types.d.ts.map +1 -1
  118. package/dist/src/types.js.map +1 -1
  119. package/package.json +2 -1
  120. package/src/analysis/rules.ts +10 -2
  121. package/src/connectors/csv.ts +31 -1
  122. package/src/connectors/dsl-compiler.ts +56 -20
  123. package/src/connectors/dsl-validator.ts +6 -1
  124. package/src/connectors/js-aggregation.ts +16 -11
  125. package/src/mcp/index.ts +62 -28
  126. package/src/mcp/spec-store.ts +5 -1
  127. package/src/mcp/tools/dsl-schemas.ts +1 -1
  128. package/src/mcp/tools/list-patterns.ts +2 -2
  129. package/src/mcp/tools/refine.ts +333 -258
  130. package/src/mcp/tools/shared.ts +70 -7
  131. package/src/mcp/tools/visualize-from-source.ts +20 -5
  132. package/src/mcp/tools/visualize.ts +22 -22
  133. package/src/patterns/definitions/comparison/grouped-bar.ts +5 -5
  134. package/src/patterns/definitions/composition/waffle.ts +17 -3
  135. package/src/patterns/definitions/distribution/strip-plot.ts +12 -3
  136. package/src/patterns/definitions/time/sparkline-grid.ts +2 -2
  137. package/src/patterns/selector.ts +47 -1
  138. package/src/renderers/d3/comparison/bar.ts +24 -1
  139. package/src/renderers/d3/comparison/grouped-bar.ts +9 -4
  140. package/src/renderers/d3/composition/donut.ts +14 -0
  141. package/src/renderers/d3/composition/stacked-bar.ts +5 -0
  142. package/src/renderers/d3/composition/treemap.ts +2 -1
  143. package/src/renderers/d3/distribution/beeswarm.ts +12 -0
  144. package/src/renderers/d3/distribution/histogram.ts +44 -2
  145. package/src/renderers/d3/flow/funnel.ts +8 -0
  146. package/src/renderers/d3/flow/sankey-layout.ts +23 -3
  147. package/src/renderers/d3/heatmap.ts +20 -2
  148. package/src/renderers/d3/radar.ts +4 -1
  149. package/src/renderers/d3/relationship.ts +31 -6
  150. package/src/renderers/d3/shared.ts +7 -7
  151. package/src/renderers/d3/time/area.ts +22 -7
  152. package/src/renderers/d3/time/calendar-heatmap.ts +5 -0
  153. package/src/renderers/d3/time/horizon-chart.ts +11 -0
  154. package/src/renderers/d3/time/line.ts +24 -9
  155. package/src/renderers/d3/time/small-multiples.ts +6 -0
  156. package/src/renderers/d3/time/sparkline-grid.ts +5 -2
  157. package/src/renderers/d3/time/stream-graph.ts +5 -0
  158. package/src/renderers/html/_generated/bundles.ts +39 -39
  159. package/src/renderers/html/template.ts +2 -2
  160. package/src/types.ts +18 -2
@@ -1,328 +1,376 @@
1
- /**
2
- * MCP Tool: refine_visualization
3
- * Takes a current visualization spec and a refinement request,
4
- * returns an updated spec.
5
- *
6
- * Supports both atomic VisualizationSpec and CompoundVisualizationSpec.
7
- * Accepts specId from a previous visualize/refine call.
8
- */
9
-
10
1
  import { z } from 'zod';
11
2
  import type {
12
3
  VisualizationSpec,
13
4
  CompoundVisualizationSpec,
14
5
  RefineOutput,
15
- ColorPaletteName,
6
+ DataColumn,
16
7
  } from '../../types.js';
17
8
  import { isCompoundSpec } from '../../types.js';
18
9
  import { buildChartHtml, isHtmlPatternSupported } from '../../renderers/html/index.js';
19
10
  import { buildCompoundHtml } from '../../renderers/html/builders/compound.js';
20
11
  import { specStore } from '../spec-store.js';
21
- import { errorResponse, jsonResponse, htmlResponse } from './shared.js';
12
+ import type { StoredSpec } from '../spec-store.js';
13
+ import { errorResponse, htmlResponse } from './shared.js';
22
14
  import { logOperation } from './operation-log.js';
15
+ import { selectPattern } from '../../patterns/selector.js';
16
+ import { ALL_PALETTE_NAMES } from './dsl-schemas.js';
17
+
18
+ const FLIPPABLE_PATTERNS = new Set([
19
+ 'bar', 'grouped-bar', 'stacked-bar', 'lollipop', 'bullet',
20
+ 'line', 'area', 'histogram', 'scatter', 'connected-scatter',
21
+ ]);
22
+
23
+ const FLOW_PATTERNS = new Set(['sankey', 'alluvial', 'chord', 'funnel']);
24
+
25
+ const FORMAT_MAP: Record<string, string> = {
26
+ 'percent': '.1%',
27
+ 'dollar': '$,.0f',
28
+ 'integer': ',.0f',
29
+ 'decimal': ',.2f',
30
+ 'compact': '.2s',
31
+ };
23
32
 
24
33
  export const refineInputSchema = z.object({
25
34
  specId: z.string().describe('Spec ID from a previous visualize or refine call'),
26
- refinement: z.string().describe('What to change — e.g., "sort by value descending", "use warm palette", "highlight Engineering and Science", "mute to 30% opacity"'),
27
- selectAlternative: z.string().optional().describe('Switch to an alternative pattern by ID (e.g., "line"). Uses alternatives stored from the original visualize call.'),
28
- });
29
35
 
30
- // ─── PALETTE LOOKUP ─────────────────────────────────────────────────────────
31
-
32
- /** Map natural language color terms to valid ColorPaletteName values */
33
- const PALETTE_LOOKUP: [RegExp, ColorPaletteName, string][] = [
34
- [/\bblue\s*red\b|\bblue[-_]?red\b/, 'blueRed', 'blueRed diverging palette'],
35
- [/\bgreen\s*purple\b|\bgreen[-_]?purple\b/, 'greenPurple', 'greenPurple diverging palette'],
36
- [/\bteal\s*orange\b|\bteal[-_]?orange\b/, 'tealOrange', 'tealOrange diverging palette'],
37
- [/\bred\s*green\b|\bred[-_]?green\b/, 'redGreen', 'redGreen diverging palette'],
38
- [/\btraffic\s*light\b|\bstoplight\b/, 'traffic-light', 'traffic-light palette'],
39
- [/\bprofit[-\s]*loss\b/, 'profit-loss', 'profit-loss palette'],
40
- [/\btemperature\b/, 'temperature', 'temperature palette'],
41
- [/\bwarm\b|\borange\b/, 'warm', 'warm palette'],
42
- [/\bpurple\b|\bviolet\b/, 'purple', 'purple palette'],
43
- [/\bgreen\b/, 'green', 'green palette'],
44
- [/\bblue\b|\bsequential\b|\bcool\b/, 'blue', 'blue palette'],
45
- [/\bdiverging\b/, 'blueRed', 'blueRed diverging palette'],
46
- [/\bcategorical\b|\bdistinct\b|\bqualitative\b/, 'categorical', 'categorical palette'],
47
- ];
48
-
49
- function matchPalette(text: string): [ColorPaletteName, string] | null {
50
- const lower = text.toLowerCase();
51
- for (const [regex, palette, label] of PALETTE_LOOKUP) {
52
- if (regex.test(lower)) return [palette, label];
53
- }
54
- return null;
55
- }
36
+ sort: z.object({
37
+ field: z.string().optional().describe('Column to sort by. If omitted, sorts by primary measure axis.'),
38
+ direction: z.enum(['asc', 'desc']),
39
+ }).nullable().optional(),
56
40
 
57
- // ─── HIGHLIGHT PARSING ──────────────────────────────────────────────────────
58
-
59
- /** Parse highlight values from a refinement string */
60
- function parseHighlight(refinement: string, lower: string): {
61
- values: string[];
62
- color?: string;
63
- mutedOpacity?: number;
64
- } | null {
65
- // "highlight X and Y" or "highlight X, Y, Z"
66
- const highlightMatch = lower.match(
67
- /highlight\s+(.+?)(?:\s+in\s+(#[0-9a-f]{3,8}|\w+))?$/
68
- );
69
- if (!highlightMatch) return null;
70
-
71
- const rawValues = highlightMatch[1]
72
- // Remove trailing "in <color>" that may have been greedily captured
73
- .replace(/\s+in\s+#[0-9a-f]{3,8}$/i, '')
74
- .replace(/\s+in\s+\w+$/i, '');
75
-
76
- // Split on " and ", commas, or " & "
77
- const values = rawValues
78
- .split(/\s*(?:,\s*|\s+and\s+|\s*&\s*)\s*/)
79
- .map(v => v.trim())
80
- .filter(Boolean)
81
- // Restore original casing from the refinement string
82
- .map(v => {
83
- const idx = refinement.toLowerCase().indexOf(v);
84
- return idx >= 0 ? refinement.slice(idx, idx + v.length) : v;
85
- });
41
+ limit: z.number().optional().describe('Top N rows'),
86
42
 
87
- if (values.length === 0) return null;
43
+ filter: z.array(z.object({
44
+ field: z.string(),
45
+ op: z.enum(['in', 'not_in', 'gt', 'gte', 'lt', 'lte', '=', '!='])
46
+ .default('in')
47
+ .transform(op => op === '=' ? 'in' as const : op === '!=' ? 'not_in' as const : op),
48
+ values: z.array(z.union([z.string(), z.number()])),
49
+ })).optional().describe('Data filters. Pass empty array [] to clear filters.'),
88
50
 
89
- const result: { values: string[]; color?: string; mutedOpacity?: number } = { values };
90
- if (highlightMatch[2]) result.color = highlightMatch[2];
51
+ flip: z.boolean().optional().describe('Swap x/y axes (Cartesian charts only)'),
91
52
 
92
- return result;
93
- }
53
+ title: z.string().optional(),
54
+ subtitle: z.string().optional(),
55
+ xLabel: z.string().optional().describe('X-axis label'),
56
+ yLabel: z.string().optional().describe('Y-axis label'),
94
57
 
95
- /** Parse muted opacity from refinement */
96
- function parseMutedOpacity(lower: string): number | null {
97
- const match = lower.match(/mute\w*\s+(?:to\s+)?(\d+)%\s*opacity/);
98
- if (match) return parseInt(match[1], 10) / 100;
99
- const match2 = lower.match(/opacity\s+(\d+)%/);
100
- if (match2) return parseInt(match2[1], 10) / 100;
101
- const match3 = lower.match(/mute\w*\s+(?:to\s+)?(?:0?\.\d+)/);
102
- if (match3) {
103
- const val = parseFloat(match3[0].match(/\d+\.\d+/)![0]);
104
- return val > 0 && val <= 1 ? val : null;
105
- }
106
- return null;
107
- }
58
+ palette: z.enum(ALL_PALETTE_NAMES).optional()
59
+ .describe('Named palette: categorical, blue, green, purple, warm, blueRed, etc.'),
60
+
61
+ highlight: z.object({
62
+ values: z.array(z.union([z.string(), z.number()])).describe('Values to emphasize'),
63
+ color: z.union([z.string(), z.array(z.string())]).optional(),
64
+ mutedColor: z.string().optional(),
65
+ mutedOpacity: z.number().optional(),
66
+ }).nullable().optional()
67
+ .transform(v => v && v.values?.length === 0 ? null : v)
68
+ .describe('Highlight specific values. Pass null to clear.'),
69
+
70
+ colorField: z.string().optional().describe('Which data field drives color'),
71
+
72
+ flowColorBy: z.enum(['source', 'target']).optional()
73
+ .describe('Color flow charts by source or target node'),
74
+
75
+ format: z.enum(['percent', 'dollar', 'integer', 'decimal', 'compact']).optional()
76
+ .describe('Value axis number format'),
77
+
78
+ switchPattern: z.string().optional()
79
+ .describe('Switch to a different chart type by pattern ID'),
80
+
81
+ removeTable: z.boolean().optional().describe('Remove the data table from a compound chart'),
82
+ layout: z.enum(['rows', 'columns']).optional().describe('Compound layout'),
83
+ hideColumns: z.array(z.string()).optional().describe('Hide columns from the data table'),
84
+ });
108
85
 
109
- // ─── APPLY REFINEMENT ───────────────────────────────────────────────────────
86
+ type RefineArgs = z.infer<typeof refineInputSchema>;
110
87
 
111
- /** Apply refinements to an atomic visualization spec */
112
- function applyRefinement(spec: VisualizationSpec, refinement: string): RefineOutput {
88
+ function applyAtomicParams(
89
+ spec: VisualizationSpec,
90
+ args: RefineArgs,
91
+ stored: StoredSpec,
92
+ ): RefineOutput {
113
93
  const changes: string[] = [];
114
- const updated = JSON.parse(JSON.stringify(spec)) as VisualizationSpec;
115
- const lower = refinement.toLowerCase();
116
-
117
- // Sort refinements
118
- if (lower.includes('sort') && lower.includes('desc')) {
119
- if (updated.encoding.x) updated.encoding.x.sort = 'descending';
120
- if (updated.encoding.y) updated.encoding.y.sort = 'descending';
121
- changes.push('Applied descending sort');
122
- } else if (lower.includes('sort') && lower.includes('asc')) {
123
- if (updated.encoding.x) updated.encoding.x.sort = 'ascending';
124
- if (updated.encoding.y) updated.encoding.y.sort = 'ascending';
125
- changes.push('Applied ascending sort');
126
- }
94
+ const notes: string[] = [];
127
95
 
128
- // Limit refinements
129
- const limitMatch = lower.match(/(?:top|limit|first)\s*(\d+)/);
130
- if (limitMatch) {
131
- const limit = parseInt(limitMatch[1], 10);
132
- updated.data = updated.data.slice(0, limit);
133
- changes.push(`Limited data to top ${limit} rows`);
96
+ if (args.filter !== undefined) {
97
+ if (args.filter.length === 0) {
98
+ if (stored.originalData) {
99
+ spec.data = [...stored.originalData];
100
+ changes.push('Cleared all filters');
101
+ }
102
+ } else {
103
+ for (const f of args.filter) {
104
+ const before = spec.data.length;
105
+ const normalizeStr = (v: any) => String(v).toLowerCase();
106
+ if (f.op === 'in') {
107
+ const valSet = new Set(f.values.map(normalizeStr));
108
+ spec.data = spec.data.filter(d => valSet.has(normalizeStr(d[f.field])));
109
+ } else if (f.op === 'not_in') {
110
+ const valSet = new Set(f.values.map(normalizeStr));
111
+ spec.data = spec.data.filter(d => !valSet.has(normalizeStr(d[f.field])));
112
+ } else {
113
+ const threshold = Number(f.values[0]);
114
+ spec.data = spec.data.filter(d => {
115
+ const v = Number(d[f.field]);
116
+ if (f.op === 'gt') return v > threshold;
117
+ if (f.op === 'gte') return v >= threshold;
118
+ if (f.op === 'lt') return v < threshold;
119
+ if (f.op === 'lte') return v <= threshold;
120
+ return true;
121
+ });
122
+ }
123
+ if (spec.data.length === 0) {
124
+ spec.data = stored.originalData ? [...stored.originalData] : spec.data;
125
+ notes.push(`Filter on '${f.field}' removed all rows — filter was not applied.`);
126
+ } else {
127
+ changes.push(`Filtered ${f.field}: ${before} → ${spec.data.length} rows`);
128
+ }
129
+ }
130
+ }
134
131
  }
135
132
 
136
- // Orientation refinements
137
- if (lower.includes('horizontal') || lower.includes('flip')) {
138
- const { x, y } = updated.encoding;
139
- if (x && y) {
140
- updated.encoding.x = y;
141
- updated.encoding.y = x;
142
- changes.push('Flipped axes for horizontal layout');
133
+ if (args.sort !== undefined) {
134
+ if (args.sort === null) {
135
+ delete spec.config.sortBy;
136
+ delete spec.config.sortOrder;
137
+ changes.push('Cleared sort');
138
+ } else {
139
+ const dir = args.sort.direction;
140
+ const sortOrder = dir === 'desc' ? 'descending' : 'ascending';
141
+ if (args.sort.field) {
142
+ const field = args.sort.field;
143
+ if (spec.encoding.y && field === spec.encoding.y.field) {
144
+ spec.config.sortBy = 'value';
145
+ } else if (spec.encoding.x && field === spec.encoding.x.field) {
146
+ spec.config.sortBy = 'category';
147
+ } else {
148
+ const keys = spec.data.length > 0 ? Object.keys(spec.data[0]) : [];
149
+ if (keys.includes(field)) {
150
+ spec.data.sort((a, b) => {
151
+ const av = a[field], bv = b[field];
152
+ if (av == null) return 1;
153
+ if (bv == null) return -1;
154
+ return dir === 'desc'
155
+ ? (typeof av === 'number' ? bv - av : String(bv).localeCompare(String(av)))
156
+ : (typeof av === 'number' ? av - bv : String(av).localeCompare(String(bv)));
157
+ });
158
+ } else {
159
+ notes.push(`Sort field '${field}' not found. Available: ${keys.join(', ')}`);
160
+ }
161
+ }
162
+ spec.config.sortOrder = sortOrder;
163
+ changes.push(`Sorted by ${field} ${dir}`);
164
+ } else {
165
+ spec.config.sortBy = 'value';
166
+ spec.config.sortOrder = sortOrder;
167
+ changes.push(`Sorted by value ${dir}`);
168
+ }
143
169
  }
144
170
  }
145
171
 
146
- // Title refinements
147
- const titleMatch = refinement.match(/title[:\s]+"?([^"]+)"?/i);
148
- if (titleMatch) {
149
- updated.title = titleMatch[1].trim();
150
- changes.push(`Changed title to "${updated.title}"`);
172
+ if (args.limit !== undefined) {
173
+ spec.data = spec.data.slice(0, args.limit);
174
+ changes.push(`Limited to top ${args.limit} rows`);
151
175
  }
152
176
 
153
- // ── Palette refinements (replaces broken colorScheme block) ──
154
- if (lower.includes('color') || lower.includes('palette') || lower.includes('scheme') ||
155
- lower.includes('warm') || lower.includes('diverging') || lower.includes('sequential') ||
156
- lower.includes('categorical')) {
157
- const paletteResult = matchPalette(lower);
158
- if (paletteResult) {
159
- if (!updated.encoding.color) updated.encoding.color = {};
160
- updated.encoding.color.palette = paletteResult[0];
161
- changes.push(`Applied ${paletteResult[1]}`);
162
- }
177
+ if (args.colorField !== undefined) {
178
+ if (!spec.encoding.color) spec.encoding.color = {};
179
+ spec.encoding.color.field = args.colorField;
180
+ if (!spec.encoding.color.type) spec.encoding.color.type = 'nominal';
181
+ changes.push(`Set color field to '${args.colorField}'`);
182
+ }
183
+
184
+ if (args.palette !== undefined) {
185
+ if (!spec.encoding.color) spec.encoding.color = {};
186
+ spec.encoding.color.palette = args.palette;
187
+ changes.push(`Applied ${args.palette} palette`);
163
188
  }
164
189
 
165
- // ── Highlight refinements ──
166
- if (lower.includes('highlight')) {
167
- const highlight = parseHighlight(refinement, lower);
168
- if (highlight && highlight.values.length > 0) {
169
- // Validate highlight values against actual data values in the color field
170
- const colorField = updated.encoding.color?.field;
171
- if (colorField) {
172
- const dataValues = new Set(updated.data.map(d => String(d[colorField]).toLowerCase()));
173
- const validValues = highlight.values.filter(v => dataValues.has(v.toLowerCase()));
174
- if (validValues.length > 0) {
175
- if (!updated.encoding.color) updated.encoding.color = {};
176
- updated.encoding.color.highlight = {
177
- values: validValues,
178
- ...(highlight.color ? { color: highlight.color } : {}),
190
+ if (args.highlight !== undefined) {
191
+ if (args.highlight === null) {
192
+ if (spec.encoding.color) {
193
+ delete spec.encoding.color.highlight;
194
+ }
195
+ changes.push('Cleared highlight');
196
+ } else {
197
+ if (!spec.encoding.color) spec.encoding.color = {};
198
+ const colorField = spec.encoding.color.field;
199
+ if (colorField && spec.data.length > 0) {
200
+ const normalize = (v: any) => String(v).trim().toLowerCase();
201
+ const dataVals = new Map<string, string>();
202
+ for (const d of spec.data) {
203
+ const raw = String(d[colorField]);
204
+ dataVals.set(normalize(raw), raw);
205
+ }
206
+ const matched: (string | number)[] = [];
207
+ const unmatched: (string | number)[] = [];
208
+ for (const v of args.highlight.values) {
209
+ const found = dataVals.get(normalize(v));
210
+ if (found !== undefined) {
211
+ matched.push(found);
212
+ } else {
213
+ unmatched.push(v);
214
+ }
215
+ }
216
+ if (unmatched.length > 0) {
217
+ notes.push(`Highlight: ${unmatched.map(v => `'${v}'`).join(', ')} not found in '${colorField}'.`);
218
+ }
219
+ if (matched.length > 0) {
220
+ spec.encoding.color.highlight = {
221
+ values: matched,
222
+ ...(args.highlight.color != null ? { color: args.highlight.color } : {}),
223
+ ...(args.highlight.mutedColor != null ? { mutedColor: args.highlight.mutedColor } : {}),
224
+ ...(args.highlight.mutedOpacity != null ? { mutedOpacity: args.highlight.mutedOpacity } : {}),
179
225
  };
180
- changes.push(`Highlighted values: ${validValues.join(', ')}`);
226
+ changes.push(`Highlighted: ${matched.join(', ')}`);
181
227
  }
182
- // If no values match data, skip highlight (it's likely descriptive text like "highlight differences")
183
228
  } else {
184
- // No color field — apply highlight as-is (may be used for x/y field matching)
185
- if (!updated.encoding.color) updated.encoding.color = {};
186
- updated.encoding.color.highlight = {
187
- values: highlight.values,
188
- ...(highlight.color ? { color: highlight.color } : {}),
229
+ spec.encoding.color.highlight = {
230
+ values: args.highlight.values,
231
+ ...(args.highlight.color != null ? { color: args.highlight.color } : {}),
232
+ ...(args.highlight.mutedColor != null ? { mutedColor: args.highlight.mutedColor } : {}),
233
+ ...(args.highlight.mutedOpacity != null ? { mutedOpacity: args.highlight.mutedOpacity } : {}),
189
234
  };
190
- changes.push(`Highlighted values: ${highlight.values.join(', ')}`);
235
+ changes.push(`Highlighted: ${args.highlight.values.join(', ')}`);
191
236
  }
192
237
  }
193
238
  }
194
239
 
195
- // ── Muted opacity refinements ──
196
- if (lower.includes('mute') || lower.includes('opacity')) {
197
- const opacity = parseMutedOpacity(lower);
198
- if (opacity !== null) {
199
- if (!updated.encoding.color) updated.encoding.color = {};
200
- if (!updated.encoding.color.highlight) {
201
- // Set opacity on existing highlight or create a placeholder
202
- updated.encoding.color.highlight = { values: [], mutedOpacity: opacity };
203
- } else {
204
- updated.encoding.color.highlight.mutedOpacity = opacity;
240
+ if (args.flip === true) {
241
+ if (FLIPPABLE_PATTERNS.has(spec.pattern)) {
242
+ const { x, y } = spec.encoding;
243
+ if (x && y) {
244
+ spec.encoding.x = y;
245
+ spec.encoding.y = x;
246
+ changes.push('Flipped axes');
205
247
  }
206
- changes.push(`Set muted opacity to ${opacity}`);
248
+ } else {
249
+ notes.push(`Flip ignored — ${spec.pattern} charts don't have swappable axes.`);
207
250
  }
208
251
  }
209
252
 
210
- // ── colorBy refinements (for alluvial, sankey, chord) ──
211
- const colorByMatch = lower.match(/color\s*by\s+(\w+)/);
212
- if (colorByMatch) {
213
- updated.config.colorBy = colorByMatch[1];
214
- changes.push(`Set colorBy to "${colorByMatch[1]}"`);
253
+ if (args.title !== undefined) {
254
+ spec.title = args.title;
255
+ changes.push(`Title: "${args.title}"`);
256
+ }
257
+ if (args.subtitle !== undefined) {
258
+ spec.config.subtitle = args.subtitle;
259
+ changes.push(`Subtitle: "${args.subtitle}"`);
260
+ }
261
+ if (args.xLabel !== undefined) {
262
+ if (spec.encoding.x) spec.encoding.x.title = args.xLabel;
263
+ changes.push(`X-axis label: "${args.xLabel}"`);
264
+ }
265
+ if (args.yLabel !== undefined) {
266
+ if (spec.encoding.y) spec.encoding.y.title = args.yLabel;
267
+ changes.push(`Y-axis label: "${args.yLabel}"`);
215
268
  }
216
269
 
217
- // Percentage format
218
- if (lower.includes('percent') || lower.includes('%')) {
219
- if (updated.encoding.y) {
220
- updated.encoding.y.format = '.1%';
221
- changes.push('Applied percentage format to y-axis');
270
+ if (args.format !== undefined) {
271
+ const fmt = FORMAT_MAP[args.format];
272
+ if (fmt) {
273
+ if (spec.pattern === 'heatmap') {
274
+ if (!spec.encoding.color) spec.encoding.color = {};
275
+ (spec.encoding.color as any).format = fmt;
276
+ } else if (spec.encoding.y) {
277
+ spec.encoding.y.format = fmt;
278
+ }
279
+ changes.push(`Applied ${args.format} format`);
222
280
  }
223
281
  }
224
282
 
225
- if (changes.length === 0) {
226
- changes.push(`Refinement noted: "${refinement}" — manual adjustment may be needed`);
227
- updated.config._pendingRefinement = refinement;
283
+ if (args.flowColorBy !== undefined) {
284
+ if (FLOW_PATTERNS.has(spec.pattern)) {
285
+ spec.config.colorBy = args.flowColorBy;
286
+ changes.push(`Set flow colorBy to '${args.flowColorBy}'`);
287
+ } else {
288
+ notes.push(`flowColorBy ignored — only applies to flow patterns (sankey, alluvial, chord, funnel).`);
289
+ }
228
290
  }
229
291
 
230
- return { spec: updated, changes };
292
+ return { spec, changes, notes };
231
293
  }
232
294
 
233
- /** Apply refinements to a compound visualization spec */
234
- function applyCompoundRefinement(
295
+ function applyCompoundParams(
235
296
  spec: CompoundVisualizationSpec,
236
- refinement: string
297
+ args: RefineArgs,
298
+ stored: StoredSpec,
237
299
  ): RefineOutput {
238
300
  const changes: string[] = [];
239
- const updated = JSON.parse(JSON.stringify(spec)) as CompoundVisualizationSpec;
240
- const lower = refinement.toLowerCase();
301
+ const notes: string[] = [];
241
302
 
242
- // ── Remove table ──
243
- if (lower.includes('remove') && lower.includes('table')) {
244
- const chartView = updated.views.find(v => v.type === 'chart');
303
+ if (args.removeTable === true) {
304
+ const chartView = spec.views.find(v => v.type === 'chart');
245
305
  if (chartView?.chart) {
246
- // Unwrap compound to atomic spec
247
306
  const atomicSpec: VisualizationSpec = {
248
307
  ...chartView.chart,
249
- data: updated.data,
308
+ data: spec.data,
250
309
  } as VisualizationSpec;
251
- return { spec: atomicSpec, changes: ['Removed table, returned atomic chart spec'] };
310
+ const subResult = applyAtomicParams(atomicSpec, { ...args, removeTable: undefined }, stored);
311
+ return {
312
+ spec: subResult.spec,
313
+ changes: ['Removed table, returned atomic chart', ...subResult.changes],
314
+ notes: subResult.notes,
315
+ };
252
316
  }
253
317
  }
254
318
 
255
- // ── Layout changes ──
256
- if (lower.includes('side by side') || lower.includes('columns') || lower.includes('right') || lower.includes('left')) {
257
- updated.layout.type = 'columns';
258
- changes.push('Changed layout to side-by-side columns');
259
- } else if (lower.includes('stack') || lower.includes('rows') || lower.includes('below') || lower.includes('above')) {
260
- updated.layout.type = 'rows';
261
- changes.push('Changed layout to stacked rows');
319
+ if (args.layout !== undefined) {
320
+ spec.layout.type = args.layout;
321
+ changes.push(`Layout: ${args.layout}`);
262
322
  }
263
323
 
264
- // ── Change interaction field ──
265
- const highlightFieldMatch = lower.match(/highlight\s+(?:by|on)\s+(\w+)/);
266
- if (highlightFieldMatch) {
267
- const field = highlightFieldMatch[1];
268
- updated.interactions = [{ type: 'highlight', field }];
269
- changes.push(`Changed highlight interaction field to "${field}"`);
270
- }
271
-
272
- // ── Table column visibility ──
273
- const hideMatch = lower.match(/hide\s+(?:the\s+)?(\w+)\s+column/);
274
- if (hideMatch) {
275
- const colName = hideMatch[1].toLowerCase();
276
- const tableView = updated.views.find(v => v.type === 'table');
324
+ if (args.hideColumns !== undefined && args.hideColumns.length > 0) {
325
+ const tableView = spec.views.find(v => v.type === 'table');
277
326
  if (tableView?.table?.columns) {
327
+ const hideSet = new Set(args.hideColumns.map(c => c.toLowerCase()));
278
328
  tableView.table.columns = tableView.table.columns.filter(
279
- c => c.field.toLowerCase() !== colName && (c.title || '').toLowerCase() !== colName
329
+ c => !hideSet.has(c.field.toLowerCase()) && !hideSet.has((c.title || '').toLowerCase())
280
330
  );
281
- changes.push(`Hidden "${colName}" column from table`);
331
+ changes.push(`Hidden columns: ${args.hideColumns.join(', ')}`);
282
332
  }
283
333
  }
284
334
 
285
- // ── Title change ──
286
- const titleMatch = refinement.match(/title[:\s]+"?([^"]+)"?/i);
287
- if (titleMatch) {
288
- updated.title = titleMatch[1].trim();
289
- // Also update chart view title
290
- const chartView = updated.views.find(v => v.type === 'chart');
291
- if (chartView?.chart) chartView.chart.title = updated.title;
292
- changes.push(`Changed title to "${updated.title}"`);
335
+ if (args.title !== undefined) {
336
+ spec.title = args.title;
337
+ const chartView = spec.views.find(v => v.type === 'chart');
338
+ if (chartView?.chart) chartView.chart.title = args.title;
339
+ changes.push(`Title: "${args.title}"`);
293
340
  }
294
341
 
295
- // ── Delegate chart-specific refinements to the chart view ──
296
- if (changes.length === 0) {
297
- const chartView = updated.views.find(v => v.type === 'chart');
298
- if (chartView?.chart) {
299
- const chartSpec: VisualizationSpec = {
300
- ...chartView.chart,
301
- data: updated.data,
302
- } as VisualizationSpec;
303
- const chartResult = applyRefinement(chartSpec, refinement);
304
- // Write chart changes back to compound spec
305
- const refinedChart = chartResult.spec as VisualizationSpec;
342
+ const chartView = spec.views.find(v => v.type === 'chart');
343
+ if (chartView?.chart) {
344
+ const chartSpec: VisualizationSpec = {
345
+ ...chartView.chart,
346
+ data: spec.data,
347
+ } as VisualizationSpec;
348
+ const atomicArgs = { ...args, removeTable: undefined, layout: undefined, hideColumns: undefined, title: undefined };
349
+ const hasAtomicArgs = atomicArgs.sort !== undefined || atomicArgs.limit !== undefined ||
350
+ atomicArgs.filter !== undefined || atomicArgs.flip !== undefined ||
351
+ atomicArgs.palette !== undefined || atomicArgs.highlight !== undefined ||
352
+ atomicArgs.colorField !== undefined || atomicArgs.format !== undefined ||
353
+ atomicArgs.flowColorBy !== undefined || atomicArgs.subtitle !== undefined ||
354
+ atomicArgs.xLabel !== undefined || atomicArgs.yLabel !== undefined;
355
+
356
+ if (hasAtomicArgs) {
357
+ const subResult = applyAtomicParams(chartSpec, atomicArgs, stored);
358
+ const refinedChart = subResult.spec as VisualizationSpec;
306
359
  chartView.chart = {
307
360
  pattern: refinedChart.pattern,
308
361
  title: refinedChart.title,
309
362
  encoding: refinedChart.encoding,
310
363
  config: refinedChart.config,
311
364
  };
312
- updated.data = refinedChart.data;
313
- changes.push(...chartResult.changes);
365
+ spec.data = refinedChart.data;
366
+ changes.push(...subResult.changes);
367
+ notes.push(...subResult.notes);
314
368
  }
315
369
  }
316
370
 
317
- if (changes.length === 0) {
318
- changes.push(`Refinement noted: "${refinement}" — manual adjustment may be needed`);
319
- }
320
-
321
- return { spec: updated, changes };
371
+ return { spec, changes, notes };
322
372
  }
323
373
 
324
- // ─── BUILD HTML FOR OUTPUT ──────────────────────────────────────────────────
325
-
326
374
  function buildOutputHtml(spec: VisualizationSpec | CompoundVisualizationSpec): string | undefined {
327
375
  if (isCompoundSpec(spec)) {
328
376
  return buildCompoundHtml(spec);
@@ -333,34 +381,61 @@ function buildOutputHtml(spec: VisualizationSpec | CompoundVisualizationSpec): s
333
381
  return undefined;
334
382
  }
335
383
 
336
- // ─── HANDLER ────────────────────────────────────────────────────────────────
337
-
338
384
  export function handleRefine() {
339
- return async (args: z.infer<typeof refineInputSchema>) => {
385
+ return async (args: RefineArgs) => {
340
386
  const start = Date.now();
341
- let spec: VisualizationSpec | CompoundVisualizationSpec;
387
+ const switchNotes: string[] = [];
388
+
389
+ const stored = specStore.get(args.specId);
390
+ if (!stored) {
391
+ return errorResponse(`Spec "${args.specId}" not found. It may have expired. Re-run visualize to get a new specId.`);
392
+ }
393
+
394
+ let spec = JSON.parse(JSON.stringify(stored.spec)) as VisualizationSpec | CompoundVisualizationSpec;
342
395
 
343
- if (args.selectAlternative) {
344
- const altSpec = specStore.getAlternative(args.specId, args.selectAlternative);
345
- if (!altSpec) {
346
- return errorResponse(`Alternative pattern "${args.selectAlternative}" not found for specId "${args.specId}". Check the alternatives list from the original visualize call.`);
396
+ if (args.switchPattern) {
397
+ const altSpec = stored.alternatives.get(args.switchPattern);
398
+ if (altSpec) {
399
+ spec = JSON.parse(JSON.stringify(altSpec)) as VisualizationSpec;
400
+ } else {
401
+ try {
402
+ const data = isCompoundSpec(spec)
403
+ ? (spec as CompoundVisualizationSpec).data
404
+ : (spec as VisualizationSpec).data;
405
+ const result = selectPattern(data, stored.columns, '', { forcePattern: args.switchPattern });
406
+ spec = result.recommended.spec;
407
+ for (const alt of result.alternatives) {
408
+ stored.alternatives.set(alt.pattern.id, alt.spec);
409
+ }
410
+ } catch {
411
+ switchNotes.push(`Pattern '${args.switchPattern}' cannot render this data shape. Available: ${[...stored.alternatives.keys()].join(', ')}`);
412
+ }
347
413
  }
348
- spec = altSpec;
414
+ }
415
+
416
+ let result: RefineOutput;
417
+ if (isCompoundSpec(spec)) {
418
+ result = applyCompoundParams(spec as CompoundVisualizationSpec, args, stored);
349
419
  } else {
350
- const stored = specStore.get(args.specId);
351
- if (!stored) {
352
- return errorResponse(`Spec "${args.specId}" not found. It may have expired. Re-run visualize to get a new specId.`);
353
- }
354
- spec = stored.spec;
420
+ result = applyAtomicParams(spec as VisualizationSpec, args, stored);
355
421
  }
356
422
 
357
- const result = isCompoundSpec(spec)
358
- ? applyCompoundRefinement(spec as CompoundVisualizationSpec, args.refinement)
359
- : applyRefinement(spec as VisualizationSpec, args.refinement);
423
+ if (args.switchPattern && !switchNotes.length) {
424
+ result.changes.unshift(`Switched to ${args.switchPattern}`);
425
+ }
426
+ result.notes.push(...switchNotes);
360
427
 
361
428
  const outputHtml = buildOutputHtml(result.spec);
362
429
  const newSpecId = specStore.updateSpec(args.specId, result.spec);
363
- const body = { specId: newSpecId, changes: result.changes };
430
+
431
+ const body: Record<string, any> = {
432
+ specId: newSpecId,
433
+ changes: result.changes,
434
+ alternatives: [...stored.alternatives.keys()],
435
+ };
436
+ if (result.notes.length > 0) {
437
+ body.notes = result.notes;
438
+ }
364
439
 
365
440
  const pattern = isCompoundSpec(result.spec)
366
441
  ? (result.spec as any).views?.find((v: any) => v.type === 'chart')?.chart?.pattern
@@ -380,6 +455,6 @@ export function handleRefine() {
380
455
  if (outputHtml) {
381
456
  return htmlResponse(body, outputHtml);
382
457
  }
383
- return jsonResponse(body);
458
+ return { content: [{ type: 'text' as const, text: JSON.stringify(body, null, 2) }] };
384
459
  };
385
460
  }