← Files DataARCHIVED FILE

scripts/sync-chart-semantics.mjs

5.86 KB · Nov 19, 2026 · 00:12 UTC

↓ Download file

See the change to this file →

import { lstat, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";

const defaultPluginRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const entryPoints = ["core/bar-presentations.js", "config.js", "adapters/inline/physical-axes.js", "core/chart-data-shape.js", "core/chart-spec-validation.js", "core/chart-annotations.js"];
const destinationPath = "output_formats/html/src/charting/shared";
const posix = (path) => path.split(sep).join("/");

function inside(root, path) {
  const name = relative(root, path);
  return name !== ".." && !name.startsWith(`..${sep}`) && !isAbsolute(name);
}

async function regularFile(root, name) {
  let path = root;
  const parts = name.split("/");
  for (const [index, part] of parts.entries()) {
    path = join(path, part);
    const stat = await lstat(path);
    if (stat.isSymbolicLink() || (index === parts.length - 1 ? !stat.isFile() : !stat.isDirectory())) {
      throw new Error(`Chart semantics input must be a regular file: ${name}`);
    }
  }
  return readFile(path, "utf8");
}

// These Node/browser-independent modules use ordinary static ESM declarations.
// Keep this scanner dependency-free so distribution preparation needs only Node.
// This is intentionally not a general JavaScript parser: declarations must start
// on their own line, use quoted module names and ordinary semicolon-terminated
// import / export-from syntax. Extending that source shape requires extending
// this scanner and its closure tests, not silently omitting a dependency.
function moduleImports(source, name) {
  if (/\b(?:import\s*\(|require\s*\(|import\.meta)/u.test(source)) {
    throw new Error(`Chart semantics require static, local ESM imports: ${name}`);
  }
  const declarations = /(?:^|\n)\s*(?:import\s+(?:[^;]*?\s+from\s+)?|export\s+(?:\*|\{[^}]*\})\s+from\s+)["']([^"'\n]+)["']/gu;
  return [...source.matchAll(declarations)].map((match) => match[1]);
}

async function sourceClosure(sourceRoot) {
  const files = new Map();
  async function visit(name) {
    if (files.has(name)) return;
    const source = await regularFile(sourceRoot, name);
    files.set(name, source);
    for (const specifier of moduleImports(source, name)) {
      const target = resolve(sourceRoot, dirname(name), specifier);
      if (!specifier.startsWith(".") || extname(target) !== ".js" || !inside(sourceRoot, target)) {
        throw new Error(`Chart semantics must stay within the pure chart source tree: ${name} imports ${specifier}`);
      }
      await visit(posix(relative(sourceRoot, target)));
    }
  }
  for (const entry of entryPoints) await visit(entry);
  return new Map([...files].sort(([left], [right]) => left.localeCompare(right, "en")));
}

async function existingFiles(root) {
  const result = [];
  async function visit(path) {
    let entries;
    try { entries = await readdir(path, { withFileTypes: true }); }
    catch (error) { if (error.code === "ENOENT") return; throw error; }
    for (const entry of entries) {
      const child = join(path, entry.name);
      if (entry.isSymbolicLink() || (!entry.isFile() && !entry.isDirectory())) {
        throw new Error(`Chart semantics distribution cannot contain links or special files: ${child}`);
      }
      if (entry.isDirectory()) await visit(child);
      else result.push(posix(relative(root, child)));
    }
  }
  await visit(root);
  return result.sort();
}

/**
 * Distribute the canonical pure chart semantics with copied apps. The installed
 * plugin intentionally omits raw chart sources; re-exporting from that tree
 * would break relocated apps and source builds. Generated modules preserve the
 * canonical dependency layout and implementation verbatim. Maintain core once,
 * regenerate here, and check before building or packaging release artifacts.
 */
export async function syncChartSemantics({ pluginRoot = defaultPluginRoot, check = false } = {}) {
  const root = resolve(pluginRoot);
  const sourceRoot = join(root, "skills/visualize-data/src");
  const destinationRoot = join(root, destinationPath);
  const sources = await sourceClosure(sourceRoot);
  const generated = new Map([...sources].map(([name, source]) => [name,
    `// Generated by scripts/sync-chart-semantics.mjs from skills/visualize-data/src/${name}.\n`
      + "// Edit the canonical source and regenerate; do not edit this distribution copy.\n"
      + source,
  ]));
  const existing = await existingFiles(destinationRoot);
  const changed = [];
  for (const [name, source] of generated) {
    let current;
    try { current = await readFile(join(destinationRoot, name), "utf8"); }
    catch (error) { if (error.code !== "ENOENT") throw error; }
    if (current !== source) changed.push(name);
  }
  const obsolete = existing.filter((name) => !generated.has(name));
  if (check && (changed.length || obsolete.length)) {
    throw new Error(`Chart semantics distribution is out of date (${[...changed, ...obsolete].join(", ")}). Run node scripts/sync-chart-semantics.mjs before building or packaging.`);
  }
  if (!check) {
    for (const name of changed) {
      const target = join(destinationRoot, name);
      await mkdir(dirname(target), { recursive: true });
      await writeFile(target, generated.get(name));
    }
    for (const name of obsolete) await rm(join(destinationRoot, name));
  }
  return { files: [...generated.keys()], changed, obsolete };
}

if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
  const args = process.argv.slice(2);
  if (args.some((arg) => arg !== "--check") || args.length > 1) {
    throw new Error("Usage: node scripts/sync-chart-semantics.mjs [--check]");
  }
  const result = await syncChartSemantics({ check: args.includes("--check") });
  console.log(`${args.includes("--check") ? "Checked" : "Synchronized"} ${result.files.length} shared chart semantics modules.`);
}

SHA-256: 3ec5130e5459c8d64ebbe4df99a5be46000c61b39a45ba039229817b9a8d22ea