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 path from "node:path";

import type { Plugin } from "vite";

import { validateDataAppManifest } from "../config/validate-manifest";
import { DATA_APP_REBUILT_EVENT } from "../constants/bundle";
import { DATA_APP_DIAGNOSTICS_CHANGED_EVENT } from "../constants/diagnostics-channel";
import { DATA_APP_MANIFEST_FILE_NAME } from "../constants/paths";

import { createAppBundle } from "./app-bundle";
import { DiagnosticsStore } from "./diagnostics-store";
import { getAppBundleMiddleware } from "./middlewares/app-bundle-middleware";
import { getDiagnosticsEndpointMiddleware } from "./middlewares/diagnostics-endpoint-middleware";
import { getIndexHtmlMiddleware } from "./middlewares/index-html-middleware";
import {
  loadDataAppVirtualModule,
  resolveDataAppVirtualId,
} from "./virtual-modules";

const BUNDLED_DIRECTORY = "src";

const isBundledFile = (root: string, file: string) => {
  const [topDirectory] = path.relative(root, file).split(path.sep);

  return topDirectory === BUNDLED_DIRECTORY;
};

export function dataAppSandboxDevPlugin(
  appSlug: string,
  allowedHosts: string[],
): Plugin {
  const diagnostics = new DiagnosticsStore();

  return {
    name: "metabase-data-app-dev",
    apply: "serve",

    resolveId: (id) => resolveDataAppVirtualId(id),

    load: (id) => loadDataAppVirtualModule(id, { appSlug, allowedHosts }),

    async configureServer(server) {
      const { root, mode } = server.config;

      const bundle = createAppBundle({
        root,
        mode,
        onError: (message) => server.config.logger.error(message),
      });

      server.middlewares.use(getAppBundleMiddleware(bundle));
      server.middlewares.use(
        getDiagnosticsEndpointMiddleware({
          store: diagnostics,
          getManifest: () => validateDataAppManifest(root, allowedHosts),
          getClients: () => server.ws.clients.size,
          getLastRebuildAt: () => bundle.lastRebuildAt,
          getBuildId: () => bundle.buildId,
          notifyChanged: () =>
            server.ws.send({
              type: "custom",
              event: DATA_APP_DIAGNOSTICS_CHANGED_EVENT,
            }),
        }),
      );

      server.watcher.on("all", async (_event, file) => {
        if (path.basename(file) === DATA_APP_MANIFEST_FILE_NAME) {
          server.ws.send({
            type: "custom",
            event: DATA_APP_DIAGNOSTICS_CHANGED_EVENT,
          });

          return;
        }

        if (isBundledFile(root, file) && (await bundle.rebuild())) {
          server.ws.send({ type: "custom", event: DATA_APP_REBUILT_EVENT });
        }
      });

      await bundle.rebuild();

      return () => {
        server.middlewares.use(getIndexHtmlMiddleware(server));
      };
    },
  };
}