← Files DataARCHIVED FILE
output_formats/html/src/charting/shared/core/chart-spec-validation.js
10.6 KB · Nov 28, 2026 · 18:12 UTC
// Generated by scripts/sync-chart-semantics.mjs from skills/visualize-data/src/core/chart-spec-validation.js.
// Edit the canonical source and regenerate; do not edit this distribution copy.
import { boxPlotSpecError } from "./chart-transforms.js";
import {
standardFeatureError,
normalizeStandardChartSpec,
} from "./chart-standard-features.js";
import { chartTypes } from "./chart-capabilities.js";
import { valueFormatError } from "./chart-value-format.js";
import { isTemporalCategory } from "./chart-data-shape.js";
import { histogramSpecError } from "../families/histogram/bins.js";
import { sankeyEdgeError } from "../families/sankey/edges.js";
const fieldName = (value) =>
typeof value === "string" && value.trim().length > 0;
const trendTypes = ["line", "sparkline", "area", "stackedArea"];
/** Do not silently replace continuous coordinates with equally spaced labels. */
function trendAxisError(spec, rows) {
if (!trendTypes.includes(spec.type) || !rows?.length) return null;
const values = rows.map((row) => row[spec.x]);
if (values.some((value) => !Number.isFinite(value) && !fieldName(value)))
return "trend X coordinates must be finite numbers or nonblank text; missing X coordinates cannot be plotted.";
if (spec.xScale === "category") return null;
const numeric = values.every(Number.isFinite);
if (spec.xScale === "linear" && !numeric)
return 'linear xScale requires finite numeric X coordinates; supply JSON numbers, or explicitly choose xScale: "category" for equally spaced labels.';
if (numeric || values.every(isTemporalCategory)) return null;
if (
values.some(
(value) =>
Number.isFinite(value) ||
isTemporalCategory(value) ||
(typeof value === "string" && !Number.isNaN(Number(value))),
)
)
return 'ambiguous trend X coordinates would use equally spaced categories. Supply JSON numbers for numeric X, consistent dates for time, or explicitly choose xScale: "category" for categorical labels.';
return null;
}
function scatterAxisError(spec, rows) {
if (spec.type !== "scatter" || !rows?.length) return null;
for (const field of [spec.x, spec.y]) {
const values = rows.map((row) => row[field]);
const categorical =
field === spec.x &&
spec.xScale == null &&
values.every(
(value) => fieldName(value) && !Number.isFinite(Number(value)),
);
if (categorical) {
if (new Set(values).size !== values.length)
return "Categorical scatter x labels must be unique.";
} else if (!values.every(Number.isFinite)) {
return "Scatter coordinates must be finite numbers on every row; return missing observations to the data owner.";
}
}
return null;
}
const wideMeasureTypes = [
"line",
"sparkline",
"area",
"stackedArea",
"bar",
"horizontalBar",
"horizontal-bar",
"stackedBar",
"stackedBar100",
"horizontalStackedBar",
"horizontalStackedBar100",
];
/** Validate raw bindings before projection can silently discard malformed values. */
export function getChartSpecError(spec, { id, partial = false, rows } = {}) {
spec = normalizeStandardChartSpec(spec);
const invalid = (message) =>
`Invalid chart${id ? ` ${JSON.stringify(id)}` : ""}: ${message}`;
if (spec === null || typeof spec !== "object" || Array.isArray(spec)) {
return invalid("chart must be a configuration object.");
}
// Legacy presentation records may omit the chart type. Validate supplied
// options against the supported union without synthesizing a discriminator.
// This accepts partial records for storage; rendering still needs a full spec.
if (partial && spec.type === undefined) {
const errors = chartTypes.map((type) =>
getChartSpecError({ ...spec, type }, { id, partial, rows }),
);
return errors.includes(null) ? null : errors[0];
}
if (
(!partial || Object.hasOwn(spec, "type")) &&
!chartTypes.includes(spec.type) &&
spec.type !== "horizontal-bar"
) {
return invalid(`chart.type must be one of: ${chartTypes.join(", ")}.`);
}
if (
spec.fit != null &&
(spec.type !== "scatter" ||
!["linear", "quadratic"].includes(spec.fit) ||
rows?.some((row) => !Number.isFinite(row[spec.x])))
)
return invalid("fit requires scatter, numeric X, and linear or quadratic.");
if (Array.isArray(spec.y)) {
const fields =
spec.y.length && spec.y.length <= 40 && spec.y.every(fieldName)
? spec.y
: ["measureA", "measureB"];
return invalid(
`chart.y must be a single field name, not an array. For multiple measures, use y: ${JSON.stringify(
fields[0],
)}, fields: ${JSON.stringify(fields)}.`,
);
}
// Existing wide-form charts may bind all measures through fields or a bar recipe.
const hasMeasureList =
wideMeasureTypes.includes(spec.type) &&
(spec.fields?.length ||
(spec.presentation && spec.barOptions?.series?.length));
if (
((!partial && !hasMeasureList) ||
(Object.hasOwn(spec, "y") && spec.y !== undefined)) &&
!fieldName(spec.y)
) {
return invalid("chart.y must be a nonempty string field name.");
}
const requiresX = !["histogram", "sankey"].includes(spec.type);
if (
((!partial && requiresX) || (spec.x != null && spec.x !== "")) &&
!fieldName(spec.x)
) {
return invalid("chart.x must be a nonempty string field name.");
}
if (spec.rowId !== undefined && !fieldName(spec.rowId))
return invalid("chart.rowId must be a nonempty string field name.");
for (const key of ["series", "source", "target"]) {
if (spec[key] != null && spec[key] !== "" && !fieldName(spec[key])) {
return invalid(`chart.${key} must be a single string field name.`);
}
}
for (const key of ["fields", "barFields", "stages"]) {
if (spec[key] == null) continue;
// An empty combination list clears bars; an empty measure/stage list cannot plot anything.
if (
!Array.isArray(spec[key]) ||
(key !== "barFields" && !spec[key].length)
) {
return invalid(
`chart.${key} must be a field list${
key === "barFields" ? "" : " with at least one field"
}.`,
);
}
if (!spec[key].every(fieldName)) {
return invalid(
`chart.${key} must contain only nonempty string field names.`,
);
}
}
if (
!partial &&
spec.type === "sankey" &&
(spec.stages ?? [spec.source ?? spec.x, spec.target ?? spec.series]).filter(
Boolean,
).length < 2
) {
return invalid(
"a Sankey chart needs at least two stage fields, using chart.stages or chart.source and chart.target.",
);
}
for (const key of ["valueDomain", "xDomain"]) {
if (spec[key] == null) continue;
if (
key === "xDomain"
? !["line", "scatter"].includes(spec.type)
: ![...wideMeasureTypes, "scatter"].includes(spec.type)
)
return invalid(`chart.${key} is not supported for this chart type.`);
const domain = spec[key];
if (
!Array.isArray(domain) ||
domain.length !== 2 ||
!domain.every(Number.isFinite) ||
domain[0] >= domain[1] ||
!Number.isFinite(domain[1] - domain[0])
)
return invalid(`chart.${key} must contain two increasing finite bounds.`);
if (
spec.type.toLowerCase().includes("bar") &&
(domain[0] > 0 || domain[1] < 0)
)
return invalid("bar valueDomain must include zero.");
if (spec.type.endsWith("100") && (domain[0] !== 0 || domain[1] !== 1))
return invalid("normalized stack valueDomain must be [0, 1].");
}
for (const axis of ["x", "y"]) {
const key = `${axis}Scale`;
const categorical = axis === "x" && spec[key] === "category";
if (categorical) {
if (!trendTypes.includes(spec.type))
return invalid(
"category xScale supports line, sparkline, area, and stackedArea charts only.",
);
if (
spec.xDomain != null ||
spec.referenceLines?.some((entry) => entry.axis === "x") ||
spec.referenceBands?.some((entry) => entry.axis === "x")
)
return invalid(
"category xScale cannot use X domains or X-axis references.",
);
} else if (spec[key] != null && !["linear", "log"].includes(spec[key]))
return invalid(
`chart.${key} must be "linear" or "log"${axis === "x" ? ', or "category" for trends' : ""}.`,
);
const logarithmic = spec[key] === "log";
const domain = axis === "x" ? spec.xDomain : spec.valueDomain;
if (logarithmic) {
const types =
axis === "x" ? ["line", "scatter"] : ["line", "area", "scatter"];
if (!types.includes(spec.type) || spec.barFields?.length)
return invalid(
`log ${key} supports ${types.join(", ")} charts only (unstacked).`,
);
if (
spec.rightAxisFields?.length ||
spec.annotations?.some((entry) => entry.kind !== "point")
)
return invalid(`log ${key} uses one value axis without annotations.`);
}
if (logarithmic && axis === "y" && spec.startAtZero === true)
return invalid(
"log yScale cannot start at zero; supply positive values.",
);
const domainKey = axis === "x" ? "xDomain" : "valueDomain";
if (logarithmic && domain && domain[0] <= 0)
return invalid(`log ${domainKey} must contain strictly positive bounds.`);
if (!logarithmic && !(domain && (axis === "x" || spec.type === "scatter")))
continue;
const fields =
axis === "x"
? [spec.x]
: spec.series || spec.type === "scatter"
? [spec.y]
: spec.fields ?? [spec.y];
for (const [index, row] of (rows ?? []).entries()) {
for (const field of fields) {
const value = row[field];
if (value === null && axis === "y" && spec.type !== "scatter") continue;
if (!Number.isFinite(value) || (logarithmic && value <= 0))
return invalid(
`${key} requires ${
logarithmic ? "strictly positive" : "finite numeric"
} values; row ${index + 1}, field ${JSON.stringify(
field,
)} is invalid.`,
);
if (domain && (value < domain[0] || value > domain[1]))
return invalid(`${domainKey} must contain all plotted values.`);
}
}
}
const featureError =
trendAxisError(spec, rows) ??
scatterAxisError(spec, rows) ??
valueFormatError(spec) ??
boxPlotSpecError(spec, rows) ??
histogramSpecError(spec, rows, { partial }) ??
standardFeatureError(spec, rows) ??
sankeyEdgeError(spec, rows);
return featureError ? invalid(featureError) : null;
}
export function assertChartSpec(spec, options) {
const error = getChartSpecError(spec, options);
if (error) throw new Error(error);
}
SHA-256: e58b247acc09772dba9214d96561b4113f9996ca2261052778b3d52860d9b55f