@chartpng/render 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +165 -2
- package/SECURITY.md +34 -0
- package/THIRD_PARTY_NOTICES.md +253 -0
- package/bin/chartpng-render.js +2 -0
- package/dist/packages/render/cli.d.ts +1 -0
- package/dist/packages/render/cli.js +88 -0
- package/dist/packages/render/index.d.ts +61 -0
- package/dist/packages/render/index.js +79 -0
- package/dist/src/fonts/plex.d.ts +2 -0
- package/dist/src/fonts/plex.js +9 -0
- package/dist/src/lib/errors.d.ts +4 -0
- package/dist/src/lib/errors.js +9 -0
- package/dist/src/lib/maker.d.ts +90 -0
- package/dist/src/lib/maker.js +297 -0
- package/dist/src/lib/presets.d.ts +61 -0
- package/dist/src/lib/presets.js +576 -0
- package/dist/src/lib/render.d.ts +38 -0
- package/dist/src/lib/render.js +738 -0
- package/dist/src/lib/repair.d.ts +8 -0
- package/dist/src/lib/repair.js +598 -0
- package/dist/src/lib/style.d.ts +23 -0
- package/dist/src/lib/style.js +110 -0
- package/dist/src/lib/table-chart.d.ts +133 -0
- package/dist/src/lib/table-chart.js +624 -0
- package/dist/src/lib/theme.d.ts +37 -0
- package/dist/src/lib/theme.js +288 -0
- package/package.json +51 -3
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare const FIX_CODES: readonly ['trailing_comma', 'code_fence', 'single_quotes', 'unquoted_keys', 'double_encoded', 'function_string', 'missing_type', 'v2_scales', 'v2_plugins', 'v2_datasets', 'v2_defaults'];
|
|
2
|
+
export type FixCode = (typeof FIX_CODES)[number];
|
|
3
|
+
export declare function isFunctionSource(text: string): boolean;
|
|
4
|
+
export interface Repaired {
|
|
5
|
+
config: unknown;
|
|
6
|
+
fixes: FixCode[];
|
|
7
|
+
}
|
|
8
|
+
export declare function repairConfig(c: unknown, maxDepth: number): Repaired | null;
|
|
@@ -0,0 +1,598 @@
|
|
|
1
|
+
// Repairs the near-JSON that language models write. Nothing here evaluates the
|
|
2
|
+
// config: text is scanned, then parsed by the strict JSON.parse, and function
|
|
3
|
+
// strings are dropped, never run.
|
|
4
|
+
// In the order of the X-ChartPNG-Fixes header.
|
|
5
|
+
export const FIX_CODES = [
|
|
6
|
+
'trailing_comma',
|
|
7
|
+
'code_fence',
|
|
8
|
+
'single_quotes',
|
|
9
|
+
'unquoted_keys',
|
|
10
|
+
'double_encoded',
|
|
11
|
+
'function_string',
|
|
12
|
+
'missing_type',
|
|
13
|
+
'v2_scales',
|
|
14
|
+
'v2_plugins',
|
|
15
|
+
'v2_datasets',
|
|
16
|
+
'v2_defaults',
|
|
17
|
+
];
|
|
18
|
+
// How many times a config can be a JSON string inside a JSON string.
|
|
19
|
+
const MAX_ENCODINGS = 2;
|
|
20
|
+
function tryParse(text) {
|
|
21
|
+
try {
|
|
22
|
+
return { value: JSON.parse(text) };
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
const isObject = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
29
|
+
// The text inside a ``` fence, with an optional language tag; prose around it is ignored.
|
|
30
|
+
function unfence(text, fixes) {
|
|
31
|
+
const open = text.indexOf('```');
|
|
32
|
+
if (open < 0)
|
|
33
|
+
return text;
|
|
34
|
+
fixes.add('code_fence');
|
|
35
|
+
let body = text.slice(open + 3);
|
|
36
|
+
const tagLine = /^[A-Za-z0-9_-]*[ \t]*\r?\n/.exec(body) ?? /^(?:jsonc?|json5|javascript|js)[ \t]+/i.exec(body);
|
|
37
|
+
if (tagLine)
|
|
38
|
+
body = body.slice(tagLine[0].length);
|
|
39
|
+
const close = body.indexOf('```');
|
|
40
|
+
return (close < 0 ? body : body.slice(0, close)).trim();
|
|
41
|
+
}
|
|
42
|
+
// Index just past the closing quote of the string that starts at `start`.
|
|
43
|
+
function stringEnd(text, start) {
|
|
44
|
+
const quote = text[start];
|
|
45
|
+
let i = start + 1;
|
|
46
|
+
while (i < text.length) {
|
|
47
|
+
if (text[i] === '\\')
|
|
48
|
+
i += 2;
|
|
49
|
+
else if (text[i] === quote)
|
|
50
|
+
return i + 1;
|
|
51
|
+
else
|
|
52
|
+
i++;
|
|
53
|
+
}
|
|
54
|
+
return text.length;
|
|
55
|
+
}
|
|
56
|
+
// A 'single quoted' string as a JSON string. An unterminated one stays open so JSON.parse rejects it.
|
|
57
|
+
function doubleQuoted(text, start) {
|
|
58
|
+
let body = '';
|
|
59
|
+
let i = start + 1;
|
|
60
|
+
while (i < text.length) {
|
|
61
|
+
const ch = text[i];
|
|
62
|
+
if (ch === '\\' && i + 1 < text.length) {
|
|
63
|
+
body += text[i + 1] === "'" ? "'" : ch + text[i + 1];
|
|
64
|
+
i += 2;
|
|
65
|
+
}
|
|
66
|
+
else if (ch === "'") {
|
|
67
|
+
return { json: `"${body}"`, end: i + 1 };
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
body += ch === '"' ? '\\"' : ch;
|
|
71
|
+
i++;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return { json: `"${body}`, end: text.length };
|
|
75
|
+
}
|
|
76
|
+
const WHITESPACE = /\s/;
|
|
77
|
+
const BARE_TOKEN = /[A-Za-z0-9_$.+-]/;
|
|
78
|
+
function nextNonSpace(text, from) {
|
|
79
|
+
let i = from;
|
|
80
|
+
while (i < text.length && WHITESPACE.test(text[i]))
|
|
81
|
+
i++;
|
|
82
|
+
return i;
|
|
83
|
+
}
|
|
84
|
+
// One pass that respects strings: commas, quotes and colons inside them are never touched.
|
|
85
|
+
function scan(text, fixes) {
|
|
86
|
+
let out = '';
|
|
87
|
+
let i = 0;
|
|
88
|
+
while (i < text.length) {
|
|
89
|
+
const ch = text[i];
|
|
90
|
+
if (ch === '"') {
|
|
91
|
+
const end = stringEnd(text, i);
|
|
92
|
+
out += text.slice(i, end);
|
|
93
|
+
i = end;
|
|
94
|
+
}
|
|
95
|
+
else if (ch === "'") {
|
|
96
|
+
const { json, end } = doubleQuoted(text, i);
|
|
97
|
+
fixes.add('single_quotes');
|
|
98
|
+
out += json;
|
|
99
|
+
i = end;
|
|
100
|
+
}
|
|
101
|
+
else if (ch === ',') {
|
|
102
|
+
const next = text[nextNonSpace(text, i + 1)];
|
|
103
|
+
if (next === '}' || next === ']')
|
|
104
|
+
fixes.add('trailing_comma');
|
|
105
|
+
else
|
|
106
|
+
out += ch;
|
|
107
|
+
i++;
|
|
108
|
+
}
|
|
109
|
+
else if (BARE_TOKEN.test(ch)) {
|
|
110
|
+
let end = i + 1;
|
|
111
|
+
while (end < text.length && BARE_TOKEN.test(text[end]))
|
|
112
|
+
end++;
|
|
113
|
+
const token = text.slice(i, end);
|
|
114
|
+
if (text[nextNonSpace(text, end)] === ':') {
|
|
115
|
+
fixes.add('unquoted_keys');
|
|
116
|
+
out += JSON.stringify(token);
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
out += token;
|
|
120
|
+
}
|
|
121
|
+
i = end;
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
out += ch;
|
|
125
|
+
i++;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
130
|
+
// Strict parse first; only when it fails does the text get repaired. A JSON
|
|
131
|
+
// string holding a config is decoded again, up to MAX_ENCODINGS times.
|
|
132
|
+
function parseLoose(text, fixes, level = 0) {
|
|
133
|
+
let parsed = tryParse(text);
|
|
134
|
+
if (!parsed) {
|
|
135
|
+
const found = new Set();
|
|
136
|
+
parsed = tryParse(scan(unfence(text, found), found));
|
|
137
|
+
if (!parsed)
|
|
138
|
+
return null;
|
|
139
|
+
for (const code of found)
|
|
140
|
+
fixes.add(code);
|
|
141
|
+
}
|
|
142
|
+
if (typeof parsed.value === 'string' && level < MAX_ENCODINGS) {
|
|
143
|
+
const inner = new Set();
|
|
144
|
+
const decoded = parseLoose(parsed.value, inner, level + 1);
|
|
145
|
+
if (decoded && isObject(decoded.value)) {
|
|
146
|
+
for (const code of inner)
|
|
147
|
+
fixes.add(code);
|
|
148
|
+
fixes.add('double_encoded');
|
|
149
|
+
return decoded;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return parsed;
|
|
153
|
+
}
|
|
154
|
+
// "function(v) { ... }", "async function name(a) { ... }", "(v) => v + '%'" and
|
|
155
|
+
// "v => v * 2". An arrow only counts as code when its body reads as a JS
|
|
156
|
+
// expression (using a parameter, or with operators or calls), so labels like "Plan => Plan, ok",
|
|
157
|
+
// "Precio => Precio final" or "(Antes) => Después" stay labels.
|
|
158
|
+
// No two adjacent quantifiers here can match the same character (the star, the name and the
|
|
159
|
+
// spaces are separated by literals), so a failed match is linear: 'function' + 20000 spaces + 'x'
|
|
160
|
+
// used to backtrack cubically.
|
|
161
|
+
const FUNCTION_SOURCE = /^(?:async\s+)?function\b\s*(?:\*\s*)?(?:[\w$]+\s*)?\([^)]*\)\s*\{/;
|
|
162
|
+
// Only the head of an arrow, for strings too long to read the body of.
|
|
163
|
+
const ARROW_HEAD = /^(?:async\s*)?(?:\([^()]*\)|[A-Za-z_$][\w$]*)\s*=>\s*\S/;
|
|
164
|
+
// The arrow body checks (STRING_LITERAL retries from every quote of an unterminated string, so it
|
|
165
|
+
// is quadratic) run only up to this many characters. Real callbacks are a line or two; 2048 keeps
|
|
166
|
+
// the worst case near 4 million steps, and the 16 KB config cap bounds anything above it.
|
|
167
|
+
const MAX_CODE_CHECK = 2048;
|
|
168
|
+
const ARROW = /^(?:async\s*)?(?:\(([^()]*)\)|([A-Za-z_$][\w$]*))\s*=>\s*(\S[\s\S]*)$/;
|
|
169
|
+
const PARAMS = /^[\w$\s,.{}[\]=:]*$/;
|
|
170
|
+
const STRING_LITERAL = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`/g;
|
|
171
|
+
const EXPRESSION_CHARS = /^[\w$\s.+\-*/%?:<>=!&|()[\]{},]*$/;
|
|
172
|
+
const OPERATOR_WORDS = /(?<![\w$])(?:return|typeof|new|await|void|in|instanceof|delete)(?![\w$])/g;
|
|
173
|
+
function hasWord(text, word) {
|
|
174
|
+
return new RegExp(`(?<![\\w$])${word.replace(/\$/g, '\\$')}(?![\\w$])`).test(text);
|
|
175
|
+
}
|
|
176
|
+
// Outside quotes, a body may hold identifiers, numbers and operators, but two
|
|
177
|
+
// words in a row ("Precio final") or a top-level comma make it prose.
|
|
178
|
+
function readsAsExpression(body) {
|
|
179
|
+
const bare = body.replace(STRING_LITERAL, 'S');
|
|
180
|
+
if (!EXPRESSION_CHARS.test(bare))
|
|
181
|
+
return false;
|
|
182
|
+
const spaced = bare.replace(OPERATOR_WORDS, '+');
|
|
183
|
+
if (/[\w$]\s+[\w$]/.test(spaced))
|
|
184
|
+
return false;
|
|
185
|
+
let depth = 0;
|
|
186
|
+
for (const char of spaced) {
|
|
187
|
+
if (char === '(' || char === '[' || char === '{')
|
|
188
|
+
depth++;
|
|
189
|
+
else if (char === ')' || char === ']' || char === '}')
|
|
190
|
+
depth--;
|
|
191
|
+
else if (char === ',' && depth === 0)
|
|
192
|
+
return false;
|
|
193
|
+
}
|
|
194
|
+
return true;
|
|
195
|
+
}
|
|
196
|
+
function isArrowSource(source) {
|
|
197
|
+
const arrow = ARROW.exec(source);
|
|
198
|
+
if (!arrow)
|
|
199
|
+
return false;
|
|
200
|
+
const parens = arrow[1] !== undefined;
|
|
201
|
+
if (parens && !PARAMS.test(arrow[1]))
|
|
202
|
+
return false;
|
|
203
|
+
const body = arrow[3].trim();
|
|
204
|
+
if (body.startsWith('{'))
|
|
205
|
+
return body.endsWith('}');
|
|
206
|
+
if (!readsAsExpression(body))
|
|
207
|
+
return false;
|
|
208
|
+
const names = (parens ? arrow[1] : arrow[2]).match(/[A-Za-z_$][\w$]*/g) ?? [];
|
|
209
|
+
if (names.length === 0)
|
|
210
|
+
return !/^[A-Za-z_$][\w$]*$/.test(body);
|
|
211
|
+
if (names.some((name) => hasWord(body, name)))
|
|
212
|
+
return true;
|
|
213
|
+
return /[^\w$\s]/.test(body.replace(STRING_LITERAL, 'S'));
|
|
214
|
+
}
|
|
215
|
+
export function isFunctionSource(text) {
|
|
216
|
+
const source = text.trim();
|
|
217
|
+
if (FUNCTION_SOURCE.test(source))
|
|
218
|
+
return true;
|
|
219
|
+
// Too long to judge its body: an arrow head is treated as code, which is the safe side, since
|
|
220
|
+
// code strings are dropped and a label this long is not a real case.
|
|
221
|
+
if (source.length > MAX_CODE_CHECK)
|
|
222
|
+
return ARROW_HEAD.test(source);
|
|
223
|
+
return isArrowSource(source);
|
|
224
|
+
}
|
|
225
|
+
function setOwn(target, key, value) {
|
|
226
|
+
Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true });
|
|
227
|
+
}
|
|
228
|
+
// Keys removed at any depth, whatever their value. JSON.parse makes '__proto__' an own key, which
|
|
229
|
+
// downstream merges and Chart.js would treat as a scale or option name. The other four are
|
|
230
|
+
// Chart.js resolver descriptors, read from every option scope: a _fallback string is kept for the
|
|
231
|
+
// life of the process (keyResolvers is never evicted), and two _fallback keys that point at each
|
|
232
|
+
// other send the resolver round a loop that never ends. None of them belongs in a request.
|
|
233
|
+
const DROPPED_KEYS = new Set(['__proto__', '_fallback', '_scriptable', '_indexable', '_allKeys']);
|
|
234
|
+
// Object keys whose value is a function string are removed, at any depth. The
|
|
235
|
+
// input is never changed: only the objects on a changed path are copied.
|
|
236
|
+
// Arrays are left alone: a string in an array is a label, not a callback.
|
|
237
|
+
function dropFunctionStrings(node, depth, maxDepth, found) {
|
|
238
|
+
if (!node || typeof node !== 'object' || depth > maxDepth)
|
|
239
|
+
return node;
|
|
240
|
+
if (Array.isArray(node)) {
|
|
241
|
+
let copy;
|
|
242
|
+
node.forEach((item, index) => {
|
|
243
|
+
const next = dropFunctionStrings(item, depth + 1, maxDepth, found);
|
|
244
|
+
if (next !== item)
|
|
245
|
+
(copy ??= [...node])[index] = next;
|
|
246
|
+
});
|
|
247
|
+
return copy ?? node;
|
|
248
|
+
}
|
|
249
|
+
let copy;
|
|
250
|
+
for (const [key, child] of Object.entries(node)) {
|
|
251
|
+
if (DROPPED_KEYS.has(key)) {
|
|
252
|
+
copy ??= { ...node };
|
|
253
|
+
delete copy[key];
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
if (typeof child === 'string' && isFunctionSource(child)) {
|
|
257
|
+
copy ??= { ...node };
|
|
258
|
+
delete copy[key];
|
|
259
|
+
found.any = true;
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
const next = dropFunctionStrings(child, depth + 1, maxDepth, found);
|
|
263
|
+
if (next !== child)
|
|
264
|
+
setOwn((copy ??= { ...node }), key, next);
|
|
265
|
+
}
|
|
266
|
+
return copy ?? node;
|
|
267
|
+
}
|
|
268
|
+
// Chart.js v2 options, the kind QuickChart's default version takes, renamed as
|
|
269
|
+
// the Chart.js v3 migration guide says. Nothing is translated when the v4 key
|
|
270
|
+
// is already there, and a v4 key inside an axis always wins over its v2 spelling.
|
|
271
|
+
const CARTESIAN_TYPES = new Set(['bar', 'line', 'scatter', 'bubble']);
|
|
272
|
+
// Axis types the renderer can draw; a time axis needs a date adapter it does not have.
|
|
273
|
+
const SCALE_TYPES = new Set(['category', 'linear', 'logarithmic']);
|
|
274
|
+
const V2_AXIS_KEYS = new Set(['gridLines', 'scaleLabel', 'ticks', 'id']);
|
|
275
|
+
const TICK_TO_SCALE = ['beginAtZero', 'min', 'max', 'suggestedMin', 'suggestedMax', 'reverse'];
|
|
276
|
+
const V2_AXES = [['xAxes', 'x', 'xAxisID'], ['yAxes', 'y', 'yAxisID']];
|
|
277
|
+
const V2_PLUGINS = [['legend', 'legend'], ['title', 'title'], ['tooltips', 'tooltip']];
|
|
278
|
+
// fontColor, fontFamily, fontSize, fontStyle and lineHeight of a v2 text option as
|
|
279
|
+
// color and font.{family,size,style,weight,lineHeight}, the shape Chart.js 3 and
|
|
280
|
+
// later read (https://www.chartjs.org/docs/latest/general/fonts.html). fontStyle
|
|
281
|
+
// was a CSS font shorthand ('bold', 'italic', 'bold italic'); in v4 the weight and
|
|
282
|
+
// the style are two options. A v4 key already there wins, and a v2 value of the
|
|
283
|
+
// wrong type is left where it is, as Chart.js 4 ignored it before.
|
|
284
|
+
const FONT_WEIGHT = /^(bold|bolder|lighter|[1-9]00)$/;
|
|
285
|
+
const FONT_STYLE = /^(italic|oblique)$/;
|
|
286
|
+
function translateFont(node) {
|
|
287
|
+
if (!('fontColor' in node || 'fontFamily' in node || 'fontSize' in node || 'fontStyle' in node || 'lineHeight' in node))
|
|
288
|
+
return node;
|
|
289
|
+
const out = { ...node };
|
|
290
|
+
const font = isObject(node.font) ? { ...node.font } : {};
|
|
291
|
+
const finite = (value) => typeof value === 'number' && Number.isFinite(value);
|
|
292
|
+
const setFont = (key, value) => {
|
|
293
|
+
if (!(key in font))
|
|
294
|
+
setOwn(font, key, value);
|
|
295
|
+
};
|
|
296
|
+
if (typeof node.fontColor === 'string') {
|
|
297
|
+
if (!('color' in node))
|
|
298
|
+
setOwn(out, 'color', node.fontColor);
|
|
299
|
+
delete out.fontColor;
|
|
300
|
+
}
|
|
301
|
+
if (typeof node.fontFamily === 'string') {
|
|
302
|
+
setFont('family', node.fontFamily);
|
|
303
|
+
delete out.fontFamily;
|
|
304
|
+
}
|
|
305
|
+
if (finite(node.fontSize)) {
|
|
306
|
+
setFont('size', node.fontSize);
|
|
307
|
+
delete out.fontSize;
|
|
308
|
+
}
|
|
309
|
+
if (finite(node.lineHeight) || typeof node.lineHeight === 'string') {
|
|
310
|
+
setFont('lineHeight', node.lineHeight);
|
|
311
|
+
delete out.lineHeight;
|
|
312
|
+
}
|
|
313
|
+
if (typeof node.fontStyle === 'string') {
|
|
314
|
+
const words = node.fontStyle.trim().split(/\s+/);
|
|
315
|
+
if (words.every((word) => word === 'normal' || FONT_WEIGHT.test(word) || FONT_STYLE.test(word))) {
|
|
316
|
+
for (const word of words) {
|
|
317
|
+
if (FONT_WEIGHT.test(word))
|
|
318
|
+
setFont('weight', word);
|
|
319
|
+
else if (FONT_STYLE.test(word))
|
|
320
|
+
setFont('style', word);
|
|
321
|
+
}
|
|
322
|
+
delete out.fontStyle;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
if (Object.keys(font).length)
|
|
326
|
+
setOwn(out, 'font', font);
|
|
327
|
+
return out;
|
|
328
|
+
}
|
|
329
|
+
function translateAxis(axis) {
|
|
330
|
+
const out = {};
|
|
331
|
+
for (const [key, value] of Object.entries(axis))
|
|
332
|
+
if (!V2_AXIS_KEYS.has(key))
|
|
333
|
+
setOwn(out, key, value);
|
|
334
|
+
const put = (key, value) => {
|
|
335
|
+
if (value !== undefined && !(key in axis))
|
|
336
|
+
setOwn(out, key, value);
|
|
337
|
+
};
|
|
338
|
+
// gridLines.drawBorder is border.display in Chart.js 4 (v4 migration guide).
|
|
339
|
+
if (isObject(axis.gridLines) && typeof axis.gridLines.drawBorder === 'boolean') {
|
|
340
|
+
const { drawBorder, ...grid } = axis.gridLines;
|
|
341
|
+
if (Object.keys(grid).length)
|
|
342
|
+
put('grid', grid);
|
|
343
|
+
put('border', isObject(axis.border) ? { display: drawBorder, ...axis.border } : { display: drawBorder });
|
|
344
|
+
}
|
|
345
|
+
else {
|
|
346
|
+
put('grid', axis.gridLines);
|
|
347
|
+
}
|
|
348
|
+
if (isObject(axis.scaleLabel)) {
|
|
349
|
+
const { labelString, ...title } = axis.scaleLabel;
|
|
350
|
+
put('title', translateFont(labelString === undefined ? title : { ...title, text: labelString }));
|
|
351
|
+
}
|
|
352
|
+
if (isObject(axis.ticks)) {
|
|
353
|
+
const ticks = { ...axis.ticks };
|
|
354
|
+
for (const key of TICK_TO_SCALE) {
|
|
355
|
+
put(key, ticks[key]);
|
|
356
|
+
delete ticks[key];
|
|
357
|
+
}
|
|
358
|
+
const font = translateFont(ticks);
|
|
359
|
+
if (Object.keys(font).length)
|
|
360
|
+
setOwn(out, 'ticks', font);
|
|
361
|
+
}
|
|
362
|
+
return out;
|
|
363
|
+
}
|
|
364
|
+
// Chart.js 4 ignores a v2 axis, so an axis is only translated when the v4 one
|
|
365
|
+
// draws: grid and title must be objects, a callback can only be a function
|
|
366
|
+
// (function strings are already gone), and a limit past the range guard would
|
|
367
|
+
// turn a chart that renders into a 400.
|
|
368
|
+
const LIMIT_KEYS = ['min', 'max', 'suggestedMin', 'suggestedMax'];
|
|
369
|
+
function drawsInV4(axis) {
|
|
370
|
+
if (axis.gridLines !== undefined && !isObject(axis.gridLines))
|
|
371
|
+
return false;
|
|
372
|
+
if (axis.title === null)
|
|
373
|
+
return false;
|
|
374
|
+
const ticks = isObject(axis.ticks) ? axis.ticks : {};
|
|
375
|
+
if (typeof ticks.callback === 'string')
|
|
376
|
+
return false;
|
|
377
|
+
return LIMIT_KEYS.every((key) => {
|
|
378
|
+
const value = ticks[key];
|
|
379
|
+
if (typeof value !== 'number' && typeof value !== 'string')
|
|
380
|
+
return true;
|
|
381
|
+
const number = Number(value);
|
|
382
|
+
return Number.isNaN(number) || Math.abs(number) <= 1e300;
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
// Several axes in one list, each with its own id: scales[id] for every one. Done
|
|
386
|
+
// only when nothing can be left pointing at the wrong axis: every axis has a
|
|
387
|
+
// distinct id that is free in scales, every dataset that names an axis names one
|
|
388
|
+
// of these, and a dataset that names none lands on an axis called x or y, the
|
|
389
|
+
// first one, as it did in v2. A v4 axis takes its direction from the first letter
|
|
390
|
+
// of its id, so `axis` is written when the id does not start with x or y.
|
|
391
|
+
function translateAxisList(list, id, ref, scales, datasets) {
|
|
392
|
+
const axes = list.filter(isObject);
|
|
393
|
+
if (axes.length !== list.length)
|
|
394
|
+
return null;
|
|
395
|
+
const ids = axes.map((axis) => axis.id);
|
|
396
|
+
if (!ids.every((name) => typeof name === 'string' && name !== '' && !(name in scales)))
|
|
397
|
+
return null;
|
|
398
|
+
if (new Set(ids).size !== ids.length)
|
|
399
|
+
return null;
|
|
400
|
+
if (!axes.every((axis) => (axis.type === undefined || SCALE_TYPES.has(axis.type)) && (axis.ticks === undefined || isObject(axis.ticks)) && drawsInV4(axis)))
|
|
401
|
+
return null;
|
|
402
|
+
for (const dataset of datasets) {
|
|
403
|
+
if (!isObject(dataset))
|
|
404
|
+
continue;
|
|
405
|
+
if (dataset[ref] === undefined ? ids[0] !== id : !ids.includes(dataset[ref]))
|
|
406
|
+
return null;
|
|
407
|
+
}
|
|
408
|
+
const out = { ...scales };
|
|
409
|
+
delete out[id === 'x' ? 'xAxes' : 'yAxes'];
|
|
410
|
+
for (const axis of axes) {
|
|
411
|
+
const translated = translateAxis(axis);
|
|
412
|
+
if (!axis.id.startsWith(id) && !('axis' in translated))
|
|
413
|
+
setOwn(translated, 'axis', id);
|
|
414
|
+
setOwn(out, axis.id, translated);
|
|
415
|
+
}
|
|
416
|
+
return out;
|
|
417
|
+
}
|
|
418
|
+
// An axis keyed x or y that still carries a v2 gridLines or scaleLabel: the config
|
|
419
|
+
// mixes the two spellings. Chart.js 4 ignores both keys, so they are renamed in place.
|
|
420
|
+
function translateKeyedAxes(scales) {
|
|
421
|
+
let out = null;
|
|
422
|
+
for (const id of ['x', 'y']) {
|
|
423
|
+
const axis = scales[id];
|
|
424
|
+
if (!isObject(axis) || !('gridLines' in axis || 'scaleLabel' in axis))
|
|
425
|
+
continue;
|
|
426
|
+
if (axis.ticks !== undefined && !isObject(axis.ticks))
|
|
427
|
+
continue;
|
|
428
|
+
if (!drawsInV4(axis))
|
|
429
|
+
continue;
|
|
430
|
+
out ??= { ...scales };
|
|
431
|
+
setOwn(out, id, translateAxis(axis));
|
|
432
|
+
}
|
|
433
|
+
return out;
|
|
434
|
+
}
|
|
435
|
+
// scales.xAxes[0]/yAxes[0] as scales.x/y. A list with several axes goes to
|
|
436
|
+
// translateAxisList; an axis type the renderer lacks, or a dataset that names a
|
|
437
|
+
// single axis by id, is left as it came.
|
|
438
|
+
function translateScales(scales, datasets) {
|
|
439
|
+
let out = null;
|
|
440
|
+
for (const [legacy, id, ref] of V2_AXES) {
|
|
441
|
+
const list = scales[legacy];
|
|
442
|
+
if (!Array.isArray(list) || id in scales)
|
|
443
|
+
continue;
|
|
444
|
+
if (list.length > 1) {
|
|
445
|
+
const translated = translateAxisList(list, id, ref, out ?? scales, datasets);
|
|
446
|
+
if (translated)
|
|
447
|
+
out = translated;
|
|
448
|
+
continue;
|
|
449
|
+
}
|
|
450
|
+
if (list.length !== 1 || !isObject(list[0]))
|
|
451
|
+
continue;
|
|
452
|
+
const axis = list[0];
|
|
453
|
+
if (axis.type !== undefined && !SCALE_TYPES.has(axis.type))
|
|
454
|
+
continue;
|
|
455
|
+
if (axis.ticks !== undefined && !isObject(axis.ticks))
|
|
456
|
+
continue;
|
|
457
|
+
if (!drawsInV4(axis))
|
|
458
|
+
continue;
|
|
459
|
+
if (datasets.some((dataset) => isObject(dataset) && dataset[ref] !== undefined))
|
|
460
|
+
continue;
|
|
461
|
+
out ??= { ...scales };
|
|
462
|
+
delete out[legacy];
|
|
463
|
+
setOwn(out, id, translateAxis(axis));
|
|
464
|
+
}
|
|
465
|
+
const keyed = translateKeyedAxes(out ?? scales);
|
|
466
|
+
return keyed ?? out;
|
|
467
|
+
}
|
|
468
|
+
// options.legend, title and tooltips as options.plugins.legend, title and tooltip.
|
|
469
|
+
// The text options inside move to color and font as well.
|
|
470
|
+
function translatePlugins(options) {
|
|
471
|
+
if (options.plugins !== undefined && !isObject(options.plugins))
|
|
472
|
+
return null;
|
|
473
|
+
const plugins = { ...options.plugins };
|
|
474
|
+
let out = null;
|
|
475
|
+
for (const [legacy, id] of V2_PLUGINS) {
|
|
476
|
+
const value = options[legacy];
|
|
477
|
+
if (!isObject(value) || id in plugins)
|
|
478
|
+
continue;
|
|
479
|
+
out ??= { ...options };
|
|
480
|
+
delete out[legacy];
|
|
481
|
+
let moved = value;
|
|
482
|
+
if (id === 'title')
|
|
483
|
+
moved = translateFont(moved);
|
|
484
|
+
if (id === 'legend' && isObject(moved.labels))
|
|
485
|
+
moved = { ...moved, labels: translateFont(moved.labels) };
|
|
486
|
+
setOwn(plugins, id, moved);
|
|
487
|
+
}
|
|
488
|
+
if (out)
|
|
489
|
+
out.plugins = plugins;
|
|
490
|
+
return out;
|
|
491
|
+
}
|
|
492
|
+
// The dataset option steppedLine is stepped in Chart.js 3 and later, with the same values.
|
|
493
|
+
function translateDatasets(data) {
|
|
494
|
+
if (!Array.isArray(data.datasets))
|
|
495
|
+
return null;
|
|
496
|
+
const stepped = (value) => typeof value === 'boolean' || value === 'before' || value === 'after' || value === 'middle';
|
|
497
|
+
if (!data.datasets.some((dataset) => isObject(dataset) && 'steppedLine' in dataset && !('stepped' in dataset) && stepped(dataset.steppedLine)))
|
|
498
|
+
return null;
|
|
499
|
+
const datasets = data.datasets.map((dataset) => {
|
|
500
|
+
if (!isObject(dataset) || !('steppedLine' in dataset) || 'stepped' in dataset || !stepped(dataset.steppedLine))
|
|
501
|
+
return dataset;
|
|
502
|
+
const { steppedLine, ...rest } = dataset;
|
|
503
|
+
return { ...rest, stepped: steppedLine };
|
|
504
|
+
});
|
|
505
|
+
return { ...data, datasets };
|
|
506
|
+
}
|
|
507
|
+
// Chart.js 2 filled the area under a line by default, Chart.js 3 and later do not
|
|
508
|
+
// ("elements.line.fill default changed from true to false" in the v3 guide). On a
|
|
509
|
+
// config that is v2 for certain, because another v2 option was translated, a line
|
|
510
|
+
// dataset that does not say fill gets the v2 default back through
|
|
511
|
+
// options.elements.line.fill. A fill the config sets, on a dataset or there, wins.
|
|
512
|
+
function restoreLineFill(config) {
|
|
513
|
+
const datasets = isObject(config.data) && Array.isArray(config.data.datasets) ? config.data.datasets : [];
|
|
514
|
+
const line = (dataset) => isObject(dataset) && (dataset.type ?? config.type) === 'line';
|
|
515
|
+
if (!datasets.some((dataset) => line(dataset) && !('fill' in dataset)))
|
|
516
|
+
return null;
|
|
517
|
+
const options = isObject(config.options) ? config.options : {};
|
|
518
|
+
if (options.elements !== undefined && !isObject(options.elements))
|
|
519
|
+
return null;
|
|
520
|
+
const elements = isObject(options.elements) ? options.elements : {};
|
|
521
|
+
if (elements.line !== undefined && !isObject(elements.line))
|
|
522
|
+
return null;
|
|
523
|
+
const lineElement = isObject(elements.line) ? elements.line : {};
|
|
524
|
+
if ('fill' in lineElement)
|
|
525
|
+
return null;
|
|
526
|
+
return { ...config, options: { ...options, elements: { ...elements, line: { ...lineElement, fill: true } } } };
|
|
527
|
+
}
|
|
528
|
+
// Scales are only translated for cartesian charts: Chart.js 4 ignores the v2
|
|
529
|
+
// arrays on a pie or radar, and a scales.y there would draw an axis over it.
|
|
530
|
+
function translateV2(config, fixes) {
|
|
531
|
+
let out = config;
|
|
532
|
+
if (isObject(out.data)) {
|
|
533
|
+
const data = translateDatasets(out.data);
|
|
534
|
+
if (data) {
|
|
535
|
+
out = { ...out, data };
|
|
536
|
+
fixes.add('v2_datasets');
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
// A v4 config with a stray gridLines on scales.y is not v2 for certain; the axis lists,
|
|
540
|
+
// the moved plugins and the dataset keys are, and only they restore v2's line fill.
|
|
541
|
+
let v2ForCertain = fixes.has('v2_datasets');
|
|
542
|
+
if (isObject(out.options)) {
|
|
543
|
+
let options = out.options;
|
|
544
|
+
if (CARTESIAN_TYPES.has(out.type) && isObject(options.scales)) {
|
|
545
|
+
const datasets = isObject(out.data) && Array.isArray(out.data.datasets) ? out.data.datasets : [];
|
|
546
|
+
const scales = translateScales(options.scales, datasets);
|
|
547
|
+
if (scales) {
|
|
548
|
+
if (['xAxes', 'yAxes'].some((key) => key in options.scales && !(key in scales)))
|
|
549
|
+
v2ForCertain = true;
|
|
550
|
+
options = { ...options, scales };
|
|
551
|
+
fixes.add('v2_scales');
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
const moved = translatePlugins(options);
|
|
555
|
+
if (moved) {
|
|
556
|
+
options = moved;
|
|
557
|
+
fixes.add('v2_plugins');
|
|
558
|
+
v2ForCertain = true;
|
|
559
|
+
}
|
|
560
|
+
if (options !== out.options)
|
|
561
|
+
out = { ...out, options };
|
|
562
|
+
}
|
|
563
|
+
if (v2ForCertain) {
|
|
564
|
+
const filled = restoreLineFill(out);
|
|
565
|
+
if (filled) {
|
|
566
|
+
out = filled;
|
|
567
|
+
fixes.add('v2_defaults');
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
return out;
|
|
571
|
+
}
|
|
572
|
+
// The raw `c` (a string, or an object from a POST body) as a config object plus
|
|
573
|
+
// the codes of what was fixed. Null when a string can't be turned into valid JSON.
|
|
574
|
+
// Validation (type, data, limits) stays with the caller and runs after this.
|
|
575
|
+
export function repairConfig(c, maxDepth) {
|
|
576
|
+
const fixes = new Set();
|
|
577
|
+
let config = c;
|
|
578
|
+
if (typeof c === 'string') {
|
|
579
|
+
const parsed = parseLoose(c, fixes);
|
|
580
|
+
if (!parsed)
|
|
581
|
+
return null;
|
|
582
|
+
config = parsed.value;
|
|
583
|
+
}
|
|
584
|
+
if (isObject(config)) {
|
|
585
|
+
const found = { any: false };
|
|
586
|
+
config = dropFunctionStrings(config, 0, maxDepth, found);
|
|
587
|
+
if (found.any)
|
|
588
|
+
fixes.add('function_string');
|
|
589
|
+
let object = config;
|
|
590
|
+
const data = object.data;
|
|
591
|
+
if (object.type === undefined && isObject(data) && Array.isArray(data.datasets)) {
|
|
592
|
+
object = { type: 'bar', ...object };
|
|
593
|
+
fixes.add('missing_type');
|
|
594
|
+
}
|
|
595
|
+
config = translateV2(object, fixes);
|
|
596
|
+
}
|
|
597
|
+
return { config, fixes: FIX_CODES.filter((code) => fixes.has(code)) };
|
|
598
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { OutputPresetName } from './presets.js';
|
|
2
|
+
import type { ChartConfig } from './render.js';
|
|
3
|
+
export interface StyleFields {
|
|
4
|
+
theme?: string;
|
|
5
|
+
palette?: string;
|
|
6
|
+
preset?: string;
|
|
7
|
+
}
|
|
8
|
+
export declare const OUTPUT_DEFAULTS: Record<OutputPresetName, {
|
|
9
|
+
width: number;
|
|
10
|
+
height: number;
|
|
11
|
+
dpr: 1 | 2;
|
|
12
|
+
}>;
|
|
13
|
+
export declare const OUTPUT_MIN_FONT = 11;
|
|
14
|
+
export declare function styleFields(raw: {
|
|
15
|
+
theme?: unknown;
|
|
16
|
+
palette?: unknown;
|
|
17
|
+
preset?: unknown;
|
|
18
|
+
}): StyleFields;
|
|
19
|
+
export declare function checkStyle(fields: StyleFields): void;
|
|
20
|
+
export declare function outputPreset(config: ChartConfig, fields: StyleFields): OutputPresetName | undefined;
|
|
21
|
+
export declare function withStyle(config: ChartConfig, fields: StyleFields): ChartConfig;
|
|
22
|
+
export declare function isOpaque(background: string): boolean;
|
|
23
|
+
export declare function floorFonts<T>(value: T, min?: number): T;
|