Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

2.7 KB
Raw Blame
import fs from "node:fs";
import path from "node:path";

import { load as parseYaml } from "js-yaml";

import { DATA_APP_MANIFEST_FILE_NAME } from "../constants/paths";
import type { DataAppManifestStatus } from "../types/manifest-status";

const asNonEmptyString = (value: unknown): string | null => {
  if (
    typeof value !== "string" &&
    typeof value !== "number" &&
    typeof value !== "boolean"
  ) {
    return null;
  }

  const trimmed = String(value).trim();

  return trimmed || null;
};

const compareAllowedHosts = (
  prevHosts: string[],
  nextHosts: string[],
): boolean => {
  const normalize = (hosts: string[]) =>
    hosts.map((entry) => entry.trim().toLowerCase()).sort();

  const [prev, next] = [normalize(prevHosts), normalize(nextHosts)];

  return (
    prev.length === next.length &&
    prev.every((entry, index) => entry === next[index])
  );
};

/**
 * Not a full validator: the manifest rules live in the backend's data-apps schemas
 * and a copy here would drift. This only adds what the backend cannot see —
 * this machine's disk, and what the dev server booted with.
 */
export function validateDataAppManifest(
  appRoot: string,
  initialAllowedHosts: string[],
): DataAppManifestStatus {
  const manifestPath = path.join(appRoot, DATA_APP_MANIFEST_FILE_NAME);

  const status: DataAppManifestStatus = {
    exists: fs.existsSync(manifestPath),
    name: null,
    bundlePath: null,
    bundlePathExists: false,
    allowedHosts: [],
    errors: [],
    warnings: [],
    restartRequired: false,
  };

  if (!status.exists) {
    return status;
  }

  let parsed: unknown;
  try {
    parsed = parseYaml(fs.readFileSync(manifestPath, "utf8"));
  } catch (error) {
    status.errors.push(
      `Could not parse ${DATA_APP_MANIFEST_FILE_NAME}: ${
        error instanceof Error ? error.message : String(error)
      }`,
    );

    return status;
  }

  // js-yaml types the parse result is `unknown`
  const fields = (parsed ?? {}) as Record<string, unknown>;
  const manifestValue = (key: string): unknown => fields[key];

  status.name = asNonEmptyString(manifestValue("name"));
  status.bundlePath = asNonEmptyString(manifestValue("path"));

  if (status.bundlePath != null) {
    status.bundlePathExists = fs.existsSync(
      path.join(appRoot, status.bundlePath),
    );

    if (!status.bundlePathExists) {
      status.warnings.push(
        `"${status.bundlePath}" does not exist — run \`npm run build\` before committing, or sync will fail.`,
      );
    }
  }

  const rawHosts = manifestValue("allowed_hosts");

  status.allowedHosts = Array.isArray(rawHosts)
    ? rawHosts.map((entry) => String(entry))
    : [];

  status.restartRequired = !compareAllowedHosts(
    initialAllowedHosts,
    status.allowedHosts,
  );

  return status;
}