Skip to content

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

refactor(sdk): Restructure the data-app dev server (#78251)

Timofey Kachalov1152608228a6
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/bundle.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/bundle.ts
deleted file mode 100644
index 8a6678438a3..00000000000
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/bundle.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-/**
- * Build/runtime constants shared by the data-app dev server preset and its dev
- * plugin. The sandbox globals contract itself lives with the sandbox
- * (`metabase-enterprise/data_apps/sandbox/globals.ts`); it's re-exported here
- * so the dev preset keeps a single import site.
- */
-
-export {
- DATA_APP_EXTERNALS,
- DATA_APP_FACTORY_GLOBAL,
- DATA_APP_GLOBALS,
- DATA_APP_GLOBAL_NAMES,
-} from "metabase-enterprise/data_apps/sandbox/globals";
-
-/** The app entry the IIFE is built from. */
-export const DATA_APP_ENTRY = "src/index.tsx";
-
-/** Dev-only URL the dev entry fetches the freshly-built IIFE bundle from. */
-export const DATA_APP_BUNDLE_URL = "/@data-app-bundle.js";
-
-/** Custom HMR event the dev plugin emits on rebuild so the dev entry soft-reloads. */
-export const DATA_APP_REBUILT_EVENT = "data-app:rebuilt";
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/build-config.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/build-config.ts
index 45d149d2754..6ad02e9e089 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/build-config.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/build-config.ts
@@ -7,19 +7,8 @@ import {
DATA_APP_EXTERNALS,
DATA_APP_FACTORY_GLOBAL,
DATA_APP_GLOBALS,
-} from "../bundle";
+} from "../constants/bundle";
-/**
- * The data-app bundle contract, shared by `vite build` (production) and the dev
- * server's in-memory membrane build so both emit the same shape: one IIFE that
- * assigns the app factory to `__dataAppFactory__`, with React + the SDK left
- * external and mapped to the globals the sandbox endows. `fileName` is the only
- * difference — the shipped `index.js` vs the dev `data-app-bundle.js`.
- *
- * `assetsInlineLimit: () => true` forces every imported asset (images, fonts, …)
- * to be base64-inlined: the backend serves one bundle file, so the build must
- * emit a single self-contained `.js` with no sidecar assets.
- */
export function dataAppLibBuild(fileName: string) {
return {
assetsInlineLimit: () => true,
@@ -36,11 +25,6 @@ export function dataAppLibBuild(fileName: string) {
};
}
-/**
- * Plugins every data-app build needs: inline imported CSS into the JS (the IIFE
- * has no HTML to link a stylesheet), and let SVGs be imported as React
- * components via `vite-plugin-svgr`.
- */
export function dataAppBuildPlugins() {
return [cssInjectedByJsPlugin(), svgr()];
}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/dev-connect-src.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/dev-connect-src.ts
index bfbb41ca742..f68f5eaa2ce 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/dev-connect-src.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/dev-connect-src.ts
@@ -6,22 +6,6 @@ const toOrigin = (url: string | undefined): string | undefined => {
}
};
-/**
- * Dev-server CSP mirroring what Metabase emits for a data app in production:
- *
- * - `connect-src`: the app may reach its `allowed_hosts` (plus the Metabase
- * instance, for the SDK's own calls) and the Vite dev server / HMR websocket
- * — nothing else. So a `fetch`/XHR a production data app couldn't make is
- * blocked in `npm run dev` too, instead of silently working locally.
- * - `form-action`: restricts native `<form action="…">` submits to the app's
- * `allowed_hosts` (mirroring `connect-src`); with none declared it is
- * `'none'`, blocking every native submit. Client-side `onSubmit` handlers
- * still work — they preventDefault, so no submission is ever checked.
- * - `frame-src`: the app may embed / navigate to `'self'` and its
- * `allowed_hosts` (mirroring production, where declared hosts are added to
- * `frame-src`), so an `<iframe>`/navigation a production app couldn't make
- * is blocked in `npm run dev` too.
- */
export const buildDevCsp = (
allowedHosts: string[],
metabaseUrl: string | undefined,
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/env-prefix.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/env-prefix.ts
index cd32af4b663..79046a30ee3 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/env-prefix.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/env-prefix.ts
@@ -1,13 +1,9 @@
import type { ConfigEnv } from "vite";
/**
- * The env-var prefix Vite exposes to `import.meta.env` for a data app.
- *
- * The app's `DATA_APP_*` vars (including the dev `DATA_APP_MB_API_KEY` kept in
- * `.env.local`) are exposed to the bundle in the dev preview ONLY. A production
- * `vite build` gets `undefined` (Vite's default `VITE_` prefix), so those dev
- * secrets can never be statically inlined into the shipped `dist/index.js` that
- * Metabase serves to users — even if app code reads `import.meta.env.DATA_APP_*`.
+ * `DATA_APP_*` vars are exposed to the bundle in the dev preview ONLY. A
+ * production build gets `undefined`, so dev secrets can never be inlined into the
+ * shipped `dist/index.js` — even if app code reads `import.meta.env.DATA_APP_*`.
*/
export function dataAppEnvPrefix(
command: ConfigEnv["command"],
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/find-env-root.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/find-env-root.ts
index f76f11facc6..48f812ef592 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/find-env-root.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/find-env-root.ts
@@ -1,13 +1,9 @@
import fs from "node:fs";
import path from "node:path";
-// How many parent dirs above the app to search for `.env.local`. Covers the
-// deepest supported layout where the app is synced into a parent repo as
-// `<repo>/data_apps/<app>` (2 levels deep). `.git` is a hard stop — `.env.local`
-// lives at the repo root, so we never search above it.
+// Covers the deepest layout, `<repo>/data_apps/<app>`. `.git` is a hard stop.
const MAX_ENV_SEARCH_DEPTH = 2;
-/** Walk up from `start` to the dir holding `.env.local` (or the git root). */
export function findEnvRoot(start: string): string {
let dir = start;
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/read-manifest.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/read-manifest.ts
index 484da2510ad..f2348484c48 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/read-manifest.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/read-manifest.ts
@@ -3,10 +3,6 @@ import path from "node:path";
import { load as parseYaml } from "js-yaml";
-/**
- * The app's parsed `data_app.yaml` manifest, validated and normalized:
- * `allowed_hosts` is guaranteed to be a list of strings.
- */
export type DataAppManifest = {
allowed_hosts?: string[];
};
@@ -38,10 +34,6 @@ const parseAllowedHosts = (
return value;
};
-/**
- * Read, parse, and normalize the app's `data_app.yaml` manifest.
- * Returns null when the app has no manifest.
- */
export const readManifest = (
appRoot: string,
): { manifestPath: string; manifest: DataAppManifest } | null => {
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/bundle.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/bundle.ts
new file mode 100644
index 00000000000..a7f85b8fdb0
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/bundle.ts
@@ -0,0 +1,12 @@
+export {
+ DATA_APP_EXTERNALS,
+ DATA_APP_FACTORY_GLOBAL,
+ DATA_APP_GLOBALS,
+ DATA_APP_GLOBAL_NAMES,
+} from "metabase-enterprise/data_apps/sandbox/globals";
+
+export const DATA_APP_ENTRY = "src/index.tsx";
+
+export const DATA_APP_BUNDLE_URL = "/@data-app-bundle.js";
+
+export const DATA_APP_REBUILT_EVENT = "data-app:rebuilt";
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/bundle.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/bundle.unit.spec.ts
similarity index 100%
rename from enterprise/frontend/src/embedding-sdk-package/data-app-dev/bundle.unit.spec.ts
rename to enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/bundle.unit.spec.ts
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/index-html.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/index-html.ts
new file mode 100644
index 00000000000..5fcf8b3da7b
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/index-html.ts
@@ -0,0 +1,22 @@
+// A namespace import stays single-line so the disable covers the reported line.
+// eslint-disable-next-line metabase/no-external-references-for-sdk-package-code
+import * as dataAppVirtualModules from "build-configs/embedding-sdk/constants/data-app-virtual-modules";
+
+const { DATA_APP_DEV_ENTRY_VIRTUAL_ID } = dataAppVirtualModules;
+
+/** The preview shell. There is no index.html on disk; the dev server serves this. */
+export const INDEX_HTML = `<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Data App Dev Preview</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module">
+ import ${JSON.stringify(DATA_APP_DEV_ENTRY_VIRTUAL_ID)};
+ </script>
+ </body>
+</html>
+`;
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/paths.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/paths.ts
new file mode 100644
index 00000000000..dd19e2f182f
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/paths.ts
@@ -0,0 +1 @@
+export const DATA_APP_DEV_ENTRY_FILE_NAME = "data-app-dev-entry.js";
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/app-bundle.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/app-bundle.ts
new file mode 100644
index 00000000000..c69a5b7d062
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/app-bundle.ts
@@ -0,0 +1,111 @@
+import { type Connect, type Rollup, build } from "vite";
+
+import { dataAppBuildPlugins, dataAppLibBuild } from "../config/build-config";
+import { getDataAppDefine } from "../config/define";
+import { DATA_APP_BUNDLE_URL } from "../constants/bundle";
+
+export interface AppBundleOptions {
+ root: string;
+ mode: string;
+ onError: (message: string) => void;
+}
+
+export interface AppBundle {
+ /** Resolves `true` only for the call that produced fresh output. */
+ rebuild: () => Promise<boolean>;
+ readonly code: string;
+}
+
+export function createAppBundle({
+ root,
+ mode,
+ onError,
+}: AppBundleOptions): AppBundle {
+ let code = "";
+ let building = false;
+ let stale = false;
+
+ const buildOnce = async (): Promise<boolean> => {
+ try {
+ const result = await build({
+ root,
+ mode,
+ configFile: false,
+ define: getDataAppDefine(mode),
+ logLevel: "warn",
+ plugins: dataAppBuildPlugins(),
+ build: {
+ write: false,
+ minify: mode === "production",
+ ...dataAppLibBuild("data-app-bundle.js"),
+ },
+ });
+
+ const outputs = Array.isArray(result) ? result : [result];
+
+ code =
+ outputs
+ .flatMap((output) => ("output" in output ? output.output : []))
+ .find((chunk): chunk is Rollup.OutputChunk => chunk.type === "chunk")
+ ?.code ?? "";
+
+ return true;
+ } catch (error) {
+ onError(
+ `[data-app-dev] failed to build the app bundle: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+
+ return false;
+ }
+ };
+
+ return {
+ rebuild: async () => {
+ if (building) {
+ stale = true;
+
+ return false;
+ }
+
+ building = true;
+ try {
+ let built = false;
+ do {
+ stale = false;
+ built = await buildOnce();
+ } while (stale);
+
+ return built;
+ } finally {
+ building = false;
+ }
+ },
+
+ get code() {
+ return code;
+ },
+ };
+}
+
+export const serveAppBundle =
+ (bundle: AppBundle): Connect.NextHandleFunction =>
+ (req, res, next) => {
+ if (req.url?.split("?")[0] !== DATA_APP_BUNDLE_URL) {
+ next();
+
+ return;
+ }
+
+ if (!bundle.code) {
+ res.statusCode = 503;
+ res.setHeader("Content-Type", "text/plain");
+ res.end("data-app bundle is not built — see the dev server logs.");
+
+ return;
+ }
+
+ res.setHeader("Content-Type", "text/javascript");
+ res.end(bundle.code);
+ };
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/app-bundle.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/app-bundle.unit.spec.ts
new file mode 100644
index 00000000000..50fc5071d89
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/app-bundle.unit.spec.ts
@@ -0,0 +1,104 @@
+import { build } from "vite";
+
+import { createAppBundle } from "./app-bundle";
+
+jest.mock("vite", () => ({ build: jest.fn() }));
+
+const mockedBuild: jest.Mock = jest.mocked(build);
+
+const rollupOutput = (code: string) => ({ output: [{ type: "chunk", code }] });
+
+const flushPending = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+let onError: jest.Mock;
+
+const setup = () => {
+ onError = jest.fn();
+
+ return createAppBundle({ root: "/app", mode: "development", onError });
+};
+
+beforeEach(() => {
+ mockedBuild.mockReset();
+ mockedBuild.mockResolvedValue(rollupOutput("built"));
+});
+
+describe("createAppBundle", () => {
+ it("exposes the built chunk", async () => {
+ const bundle = setup();
+
+ expect(await bundle.rebuild()).toBe(true);
+
+ expect(bundle.code).toBe("built");
+ });
+
+ it("reports a build failure instead of throwing at the dev server", async () => {
+ const bundle = setup();
+ mockedBuild.mockRejectedValue(new Error("syntax error in App.tsx"));
+
+ // A failed build must leave the server running: the author fixes the file
+ // and the next save rebuilds.
+ expect(await bundle.rebuild()).toBe(false);
+ expect(onError).toHaveBeenCalledWith(
+ expect.stringContaining("syntax error in App.tsx"),
+ );
+ });
+
+ it("keeps the last good bundle when a later build fails", async () => {
+ const bundle = setup();
+ await bundle.rebuild();
+
+ mockedBuild.mockRejectedValue(new Error("nope"));
+ await bundle.rebuild();
+
+ // Serving nothing would blank the preview on every typo mid-edit.
+ expect(bundle.code).toBe("built");
+ });
+
+ it("coalesces overlapping rebuilds into one repeat, notifying once", async () => {
+ const bundle = setup();
+ // One resolver per started build, so each can be finished independently.
+ const finishBuild: Array<() => void> = [];
+ mockedBuild.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finishBuild.push(() => resolve(rollupOutput("built")));
+ }),
+ );
+
+ const first = bundle.rebuild();
+ await flushPending();
+
+ // Three more saves land while the first build is still running.
+ const overlapping = await Promise.all([
+ bundle.rebuild(),
+ bundle.rebuild(),
+ bundle.rebuild(),
+ ]);
+
+ finishBuild[0]();
+ await flushPending();
+ finishBuild[1]();
+
+ // A save during a build must not queue its own build — it marks the output
+ // stale and the runner repeats once. Only the call that produced fresh
+ // output reloads the page, so a burst of saves reloads it once, not once
+ // per file.
+ expect(overlapping).toEqual([false, false, false]);
+ expect(await first).toBe(true);
+ expect(mockedBuild).toHaveBeenCalledTimes(2);
+ });
+
+ it("does not repeat when nothing arrived during the build", async () => {
+ const bundle = setup();
+
+ await bundle.rebuild();
+ await bundle.rebuild();
+
+ expect(mockedBuild).toHaveBeenCalledTimes(2);
+ });
+
+ it("holds no code until something is built", () => {
+ expect(setup().code).toBe("");
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.ts
index 63139d8486d..532ad69a3a4 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.ts
@@ -1,243 +1,50 @@
-import fs from "node:fs";
import path from "node:path";
-import { fileURLToPath } from "node:url";
-import { type Plugin, type Rollup, build } from "vite";
+import type { Plugin } from "vite";
-// Build-time string constants shared with the rspack config; bundled as values,
-// so this references no app runtime code (cf. `use-load-sdk-bundle.ts`). A
-// namespace import stays single-line so the disable covers the reported line.
-// eslint-disable-next-line metabase/no-external-references-for-sdk-package-code
-import * as dataAppVirtualModules from "build-configs/embedding-sdk/constants/data-app-virtual-modules";
+import { DATA_APP_REBUILT_EVENT } from "../constants/bundle";
-import { DATA_APP_BUNDLE_URL, DATA_APP_REBUILT_EVENT } from "../bundle";
-import { dataAppBuildPlugins, dataAppLibBuild } from "../config/build-config";
-import { getDataAppDefine } from "../config/define";
+import { createAppBundle, serveAppBundle } from "./app-bundle";
+import { serveIndexHtml } from "./serve-index-html";
+import {
+ loadDataAppVirtualModule,
+ resolveDataAppVirtualId,
+} from "./virtual-modules";
-// Virtual modules the dev server provides. The dev server serves a synthetic
-// `index.html` (below) that imports the dev entry; the dev entry imports the
-// config (the app's allowed hosts + the bundle URL/event). The dev entry is the
-// prebuilt `data-app-dev-entry.js` (bundled by the SDK's browser build, shipped
-// next to this bundle in `dist`); it keeps React + `@metabase/embedding-sdk-react`
-// external so the consumer's Vite resolves them to its single instance.
-const { DATA_APP_DEV_CONFIG_VIRTUAL_ID, DATA_APP_DEV_ENTRY_VIRTUAL_ID } =
- dataAppVirtualModules;
-
-const DEV_ENTRY_SOURCE_PATH = fileURLToPath(
- new URL("data-app-dev-entry.js", import.meta.url),
-);
-
-// The dev server's HTML shell, served synthetically so the app scaffold needs no
-// `index.html`. It just boots the dev entry (resolved + served as a virtual
-// module below), which injects the baseline reset CSS itself (the same file the
-// production iframe loads).
-const INDEX_HTML = `<!doctype html>
-<html lang="en">
- <head>
- <meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>Data App Dev Preview</title>
- </head>
- <body>
- <div id="root"></div>
- <script type="module">
- import ${JSON.stringify(DATA_APP_DEV_ENTRY_VIRTUAL_ID)};
- </script>
- </body>
-</html>
-`;
-
-// Rollup/Vite's virtual-module marker: a leading NUL byte tells Rollup core and
-// other plugins that an id is synthetic, so they don't try to resolve/load it
-// from disk. It's a convention (not a public export), so we spell it out; Vite
-// encodes it as `__x00__` in dev URLs.
-const RESOLVED_PREFIX = "\0";
-
-/**
- * Makes `npm run dev` run the app through the real Near-Membrane sandbox instead
- * of mounting it un-sandboxed, so dev behaves like production — including for
- * third-party libraries the app bundles.
- *
- * The membrane evaluates a code string, not Vite's module graph, so the app is
- * built in-memory as the production IIFE on server start and on every `src/`
- * change, served at `DATA_APP_BUNDLE_URL`. Instead of a full page reload it emits
- * `DATA_APP_REBUILT_EVENT`, and the dev entry re-evaluates the new bundle in the
- * live sandbox and re-renders in place — preserving the loaded SDK + auth (a
- * soft reload; component state still resets, since the app is an opaque bundle).
- */
export function dataAppSandboxDevPlugin(
appSlug: string,
allowedHosts: string[],
): Plugin {
- let bundleCode = "";
-
- const rebuild = async (root: string, mode: string) => {
- const result = await build({
- root,
- mode,
- configFile: false,
- define: getDataAppDefine(mode),
- logLevel: "warn",
- plugins: dataAppBuildPlugins(),
- build: {
- write: false,
- minify: mode === "production",
- ...dataAppLibBuild("data-app-bundle.js"),
- },
- });
-
- const outputs = Array.isArray(result) ? result : [result];
-
- bundleCode =
- outputs
- .flatMap((output) => ("output" in output ? output.output : []))
- .find((chunk): chunk is Rollup.OutputChunk => chunk.type === "chunk")
- ?.code ?? "";
- };
-
return {
name: "metabase-data-app-dev",
apply: "serve",
- resolveId(id) {
- if (
- id === DATA_APP_DEV_ENTRY_VIRTUAL_ID ||
- id === DATA_APP_DEV_CONFIG_VIRTUAL_ID
- ) {
- return RESOLVED_PREFIX + id;
- }
- },
-
- load(id) {
- if (id === RESOLVED_PREFIX + DATA_APP_DEV_ENTRY_VIRTUAL_ID) {
- return fs.readFileSync(DEV_ENTRY_SOURCE_PATH, "utf8");
- }
+ resolveId: (id) => resolveDataAppVirtualId(id),
- if (id === RESOLVED_PREFIX + DATA_APP_DEV_CONFIG_VIRTUAL_ID) {
- return [
- `export const allowedHosts = ${JSON.stringify(allowedHosts)};`,
- `export const appSlug = ${JSON.stringify(appSlug)};`,
- `export const bundleUrl = ${JSON.stringify(DATA_APP_BUNDLE_URL)};`,
- `export const rebuiltEvent = ${JSON.stringify(DATA_APP_REBUILT_EVENT)};`,
- ].join("\n");
- }
- },
+ load: (id) => loadDataAppVirtualModule(id, { appSlug, allowedHosts }),
async configureServer(server) {
const { root, mode } = server.config;
- const safeRebuild = async (): Promise<boolean> => {
- try {
- await rebuild(root, mode);
-
- return true;
- } catch (error) {
- server.config.logger.error(
- `[data-app-dev] failed to build the app bundle: ${
- error instanceof Error ? error.message : String(error)
- }`,
- );
-
- return false;
- }
- };
-
- // Coalesce rebuilds: at most one Vite build runs at a time, and changes
- // that arrive mid-build collapse into a single follow-up — so a burst of
- // saves can't back up a queue of full rebuilds (or fire a soft reload each).
- let building = false;
- let pending = false;
- const rebuildAndNotify = async () => {
- if (building) {
- pending = true;
- return;
- }
-
- building = true;
- try {
- let built = false;
- do {
- pending = false;
- built = await safeRebuild();
- } while (pending);
-
- if (built) {
- server.ws.send({ type: "custom", event: DATA_APP_REBUILT_EVENT });
- }
- } finally {
- building = false;
- }
- };
-
- // Initial build; no client is connected yet, so nothing to notify.
- await safeRebuild();
-
- server.middlewares.use((req, res, next) => {
- if (req.url?.split("?")[0] !== DATA_APP_BUNDLE_URL) {
- next();
-
- return;
- }
-
- if (!bundleCode) {
- res.statusCode = 503;
- res.setHeader("Content-Type", "text/plain");
- res.end("data-app bundle is not built — see the dev server logs.");
+ const bundle = createAppBundle({
+ root,
+ mode,
+ onError: (message) => server.config.logger.error(message),
+ });
- return;
- }
+ await bundle.rebuild();
- res.setHeader("Content-Type", "text/javascript");
- res.end(bundleCode);
- });
+ server.middlewares.use(serveAppBundle(bundle));
const srcDir = `${path.sep}src${path.sep}`;
-
server.watcher.on("change", async (file) => {
- if (file.includes(srcDir)) {
- await rebuildAndNotify();
+ if (file.includes(srcDir) && (await bundle.rebuild())) {
+ server.ws.send({ type: "custom", event: DATA_APP_REBUILT_EVENT });
}
});
- // Serve the synthetic index.html as a POST middleware (after Vite's
- // transform/asset middlewares) so it only catches navigation requests —
- // the initial load and any deep link / SPA route, not module/asset fetches.
- // `transformIndexHtml` injects the HMR client + resolves the entry import.
return () => {
- server.middlewares.use(async (req, res, next) => {
- if (
- req.method !== "GET" ||
- !req.headers.accept?.includes("text/html")
- ) {
- next();
-
- return;
- }
-
- try {
- const html = await server.transformIndexHtml(
- req.url ?? "/",
- INDEX_HTML,
- );
-
- res.statusCode = 200;
-
- // Apply the configured `server.headers` (our CSP) to this document.
- const configuredHeaders = server.config.server.headers;
- if (configuredHeaders) {
- for (const [name, value] of Object.entries(configuredHeaders)) {
- if (value != null) {
- res.setHeader(name, value);
- }
- }
- }
-
- res.setHeader("Content-Type", "text/html");
- res.end(html);
- } catch (error) {
- next(error);
- }
- });
+ server.middlewares.use(serveIndexHtml(server));
};
},
};
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.unit.spec.ts
index 7119b0f6eb4..d10da12fef6 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.unit.spec.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.unit.spec.ts
@@ -8,7 +8,10 @@ import {
DATA_APP_DEV_ENTRY_VIRTUAL_ID,
} from "build-configs/embedding-sdk/constants/data-app-virtual-modules";
-import { DATA_APP_BUNDLE_URL, DATA_APP_REBUILT_EVENT } from "../bundle";
+import {
+ DATA_APP_BUNDLE_URL,
+ DATA_APP_REBUILT_EVENT,
+} from "../constants/bundle";
import { dataAppSandboxDevPlugin } from "./plugin";
@@ -219,11 +222,9 @@ describe("dataAppSandboxDevPlugin", () => {
});
describe("synthetic index.html document", () => {
- // The document middleware is the second one registered: the bundle
- // middleware from `configureServer` (index 0), then this one from the
- // returned late hook (index 1).
+ // Registered by the post-hook, so it's always the last one added.
const getDocumentMiddleware = (server: FakeServer) =>
- server.middlewares.use.mock.calls[1][0];
+ server.middlewares.use.mock.calls.at(-1)[0];
it("serves the transformed shell with the configured CSP for navigations", async () => {
const { server } = await setup();
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/serve-index-html.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/serve-index-html.ts
new file mode 100644
index 00000000000..2ef45e6e91e
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/serve-index-html.ts
@@ -0,0 +1,35 @@
+import type { Connect, ViteDevServer } from "vite";
+
+import { INDEX_HTML } from "../constants/index-html";
+
+export const serveIndexHtml =
+ (server: ViteDevServer): Connect.NextHandleFunction =>
+ async (req, res, next) => {
+ if (req.method !== "GET" || !req.headers.accept?.includes("text/html")) {
+ next();
+
+ return;
+ }
+
+ try {
+ const html = await server.transformIndexHtml(req.url ?? "/", INDEX_HTML);
+
+ res.statusCode = 200;
+
+ // This response bypasses the static-file layer that would apply them, and
+ // one of them is the CSP the preview needs to match production.
+ const configuredHeaders = server.config.server.headers;
+ if (configuredHeaders) {
+ for (const [name, value] of Object.entries(configuredHeaders)) {
+ if (value != null) {
+ res.setHeader(name, value);
+ }
+ }
+ }
+
+ res.setHeader("Content-Type", "text/html");
+ res.end(html);
+ } catch (error) {
+ next(error);
+ }
+ };
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/virtual-modules.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/virtual-modules.ts
new file mode 100644
index 00000000000..90b6b207756
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/virtual-modules.ts
@@ -0,0 +1,50 @@
+import fs from "node:fs";
+import { fileURLToPath } from "node:url";
+
+// A namespace import stays single-line so the disable covers the reported line.
+// eslint-disable-next-line metabase/no-external-references-for-sdk-package-code
+import * as dataAppVirtualModules from "build-configs/embedding-sdk/constants/data-app-virtual-modules";
+
+import {
+ DATA_APP_BUNDLE_URL,
+ DATA_APP_REBUILT_EVENT,
+} from "../constants/bundle";
+import { DATA_APP_DEV_ENTRY_FILE_NAME } from "../constants/paths";
+
+const { DATA_APP_DEV_CONFIG_VIRTUAL_ID, DATA_APP_DEV_ENTRY_VIRTUAL_ID } =
+ dataAppVirtualModules;
+
+// Rollup's virtual-module marker: a leading NUL tells plugins the id is synthetic.
+const RESOLVED_PREFIX = "\0";
+
+const DEV_ENTRY_SOURCE_PATH = fileURLToPath(
+ new URL(DATA_APP_DEV_ENTRY_FILE_NAME, import.meta.url),
+);
+
+export const resolveDataAppVirtualId = (id: string): string | undefined =>
+ id === DATA_APP_DEV_ENTRY_VIRTUAL_ID || id === DATA_APP_DEV_CONFIG_VIRTUAL_ID
+ ? RESOLVED_PREFIX + id
+ : undefined;
+
+export interface DataAppVirtualConfig {
+ appSlug: string;
+ allowedHosts: string[];
+}
+
+export const loadDataAppVirtualModule = (
+ id: string,
+ { appSlug, allowedHosts }: DataAppVirtualConfig,
+): string | undefined => {
+ if (id === RESOLVED_PREFIX + DATA_APP_DEV_ENTRY_VIRTUAL_ID) {
+ return fs.readFileSync(DEV_ENTRY_SOURCE_PATH, "utf8");
+ }
+
+ if (id === RESOLVED_PREFIX + DATA_APP_DEV_CONFIG_VIRTUAL_ID) {
+ return [
+ `export const allowedHosts = ${JSON.stringify(allowedHosts)};`,
+ `export const appSlug = ${JSON.stringify(appSlug)};`,
+ `export const bundleUrl = ${JSON.stringify(DATA_APP_BUNDLE_URL)};`,
+ `export const rebuiltEvent = ${JSON.stringify(DATA_APP_REBUILT_EVENT)};`,
+ ].join("\n");
+ }
+};
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.ts
index 65e1984867c..e5a1d21a9a4 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.ts
@@ -16,16 +16,6 @@ import { findEnvRoot } from "./config/find-env-root";
import { readManifest } from "./config/read-manifest";
import { dataAppSandboxDevPlugin } from "./dev-plugin/plugin";
-/**
- * The contract plugin array used by {@link dataAppConfig}. It bundles the React
- * plugin, inlines imported CSS, adds SVG-as-component support, runs `npm run dev`
- * through the real Near-Membrane sandbox (so dev behaves like production), serves
- * the dev entry, and applies the bundle contract — the IIFE entry/format + the
- * React/SDK externals/globals — through a `config` hook that Vite merges *over*
- * the user's config, so it can't be accidentally overridden.
- *
- * Internal: apps configure through {@link dataAppConfig}, not this directly.
- */
function dataAppVitePlugin(): PluginOption[] {
const appRoot = process.cwd();
const envDir = findEnvRoot(appRoot);
@@ -48,17 +38,13 @@ function dataAppVitePlugin(): PluginOption[] {
dataAppSandboxDevPlugin(appSlug, allowedHosts),
{
name: "metabase-data-app",
- // Merged over the user's config (`mergeConfig(userConfig, this)`), so these
- // win — the bundle Metabase loads always matches what dev runs. `loadEnv`
- // needs the mode, which is only known here in the `config` hook.
+ // Merged over the user's config, so these win — the bundle Metabase loads
+ // always matches what dev runs.
config: (_config: UserConfig, env: ConfigEnv): UserConfig => ({
define: getDataAppDefine(env.mode),
envDir,
- // Dev preview only — keeps `.env.local` secrets out of prod builds. See
- // `dataAppEnvPrefix`.
envPrefix: dataAppEnvPrefix(env.command),
- // The dev plugin serves a synthetic index.html, so there's no file on
- // disk for Vite's default HTML/SPA middleware to find.
+ // The dev plugin serves a synthetic index.html; there's no file on disk.
appType: "custom",
build: {
outDir: "dist",
@@ -79,29 +65,12 @@ function dataAppVitePlugin(): PluginOption[] {
];
}
-/** Default dev server port; override via `dataAppConfig({ port })`. */
const DEFAULT_DEV_PORT = 5174;
export interface DataAppConfigOverrides {
- /** Dev server port. Defaults to 5174. */
port?: number;
}
-/**
- * The complete Vite config for a Metabase data app — the only thing a template
- * `vite.config.ts` needs:
- *
- * ```ts
- * import { dataAppConfig } from "@metabase/embedding-sdk-react/data-app-dev/config";
- *
- * export default dataAppConfig();
- * ```
- *
- * `overrides` exposes only a curated set of knobs (currently just `port`, which
- * defaults to 5174). The contract plugin that enforces the bundle format +
- * sandbox is always applied and is intentionally NOT overridable, so a data app
- * can't drift from what Metabase loads.
- */
export function dataAppConfig({
port = DEFAULT_DEV_PORT,
}: DataAppConfigOverrides = {}): UserConfig {
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/vite-env.d.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/vite-env.d.ts
index 2dee926c97a..c34ddb9a54c 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/vite-env.d.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/vite-env.d.ts
@@ -1,9 +1,3 @@
-// Ambient types for `dev-entry.tsx` (bundled by rspack, but type-checked by the
-// main program). The dev app's env vars + Vite's `import.meta.env`/`.hot` and the
-// dev plugin's config virtual module are declared here so `dev-entry.tsx` checks
-// against real shapes. No other code declares `ImportMeta`, so this is the sole
-// (global) declaration; the interfaces merge with the built-in `ImportMeta.url`.
-
interface ImportMetaEnv {
readonly DATA_APP_MB_URL: string;
readonly DATA_APP_MB_API_KEY: string;