Skip to content

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

Allow full async lazy-loading Embedding SDK chunks (#75985)

Romeo Van Snickf9fe25703143
diff --git a/.github/scripts/measure-bundle-sizes.js b/.github/scripts/measure-bundle-sizes.js
index 42f965b24d0..52464facc15 100644
--- a/.github/scripts/measure-bundle-sizes.js
+++ b/.github/scripts/measure-bundle-sizes.js
@@ -16,15 +16,13 @@ const isBundleWanted = bundle => !bundleFilter || bundleFilter.has(bundle);
const SDK_ROOT = "resources/frontend_client/app/embedding-sdk";
/**
- * Async SDK chunks are unreachable today: the bootstrap manifest lists only the
- * chunked entry's INITIAL chunks and output.publicPath is "", so import() chunks
- * are emitted but never fetched. So they're excluded from "total" (which equals
- * "initial"). There's no reliable way to detect loadability from the build
- * artifacts, so this is a manual flag: flip it to true in the same change that
- * lands the publicPath fix, and "total" will include the lazy chunks while
- * "initial" stays the eager first-load set.
+ * Async SDK chunks are reachable now that the runtime publicPath is set, so the
+ * bootstrap can fetch import() chunks on demand. "total" therefore includes the
+ * lazy chunks while "initial" stays the eager first-load set. There's no reliable
+ * way to detect loadability from the build artifacts, so this stays a manual flag:
+ * it was flipped to true alongside the publicPath fix.
*/
-const SDK_ASYNC_CHUNKS_LOADABLE = false;
+const SDK_ASYNC_CHUNKS_LOADABLE = true;
// The chunk runtime is inlined into the bootstrap, never sent as a standalone file.
const SDK_RUNTIME_RE = /embedding-sdk-chunk-runtime\./;
diff --git a/frontend/src/embedding-sdk-bundle/embedding-sdk-bootstrap.ts b/frontend/src/embedding-sdk-bundle/embedding-sdk-bootstrap.ts
index 791579cabbc..2891f2061b4 100644
--- a/frontend/src/embedding-sdk-bundle/embedding-sdk-bootstrap.ts
+++ b/frontend/src/embedding-sdk-bundle/embedding-sdk-bootstrap.ts
@@ -24,6 +24,15 @@ const scriptUrl =
(document.currentScript as HTMLScriptElement | null)?.src || "";
const baseUrl = new URL("./", scriptUrl).href;
+// Expose the SDK asset directory so the chunked entry can set webpack's
+// runtime publicPath for on-demand chunks (e.g. PDF/image export). The entry
+// executes asynchronously, after chunks load, so document.currentScript is no
+// longer reliable there — we resolve the base here while it still is.
+window.METABASE_EMBEDDING_SDK_ASSET_BASE_URL = new URL(
+ "embedding-sdk/",
+ baseUrl,
+).href;
+
function loadScript(filename: string): Promise<string> {
const url = `${baseUrl}${filename}`;
return new Promise((resolve, reject) => {
diff --git a/frontend/src/embedding-sdk-bundle/index.ts b/frontend/src/embedding-sdk-bundle/index.ts
index 2da6c9b3575..37cf9de2b0e 100644
--- a/frontend/src/embedding-sdk-bundle/index.ts
+++ b/frontend/src/embedding-sdk-bundle/index.ts
@@ -1,16 +1,8 @@
/* eslint-disable import/order */
-// Dynamic chunks (e.g. await import("./sandbox")) must load from the Metabase
-// origin, not the host page. This chunk is served at
-// `<metabase>/app/embedding-sdk/chunks/embedding-sdk-chunked.<hash>.js`; its
-// parent directory is the publicPath webpack needs for sibling chunks.
-// eslint-disable-next-line no-var
-declare var __webpack_public_path__: string;
-const currentScriptUrl = (document.currentScript as HTMLScriptElement | null)
- ?.src;
-if (currentScriptUrl) {
- __webpack_public_path__ = new URL("../", currentScriptUrl).href;
-}
+// Must run before any dynamic import(): sets webpack's runtime publicPath so
+// on-demand chunks load from the Metabase-hosted SDK asset directory.
+import "./lib/sdk-public-path";
import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";
diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-public-path.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-public-path.ts
new file mode 100644
index 00000000000..391b65ff507
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-public-path.ts
@@ -0,0 +1,64 @@
+/**
+ * Sets webpack's runtime `publicPath` (`__webpack_require__.p`) so that
+ * on-demand chunks (created by dynamic `import()` — e.g. PDF/image export) are
+ * fetched from the Metabase-hosted SDK asset directory rather than the host
+ * application's origin.
+ *
+ * Without this, an on-demand chunk would be requested relative to the host
+ * page's base URL (where the SDK chunks don't exist) and fail with a
+ * `ChunkLoadError`. This is why those dependencies used to be force-imported
+ * eagerly in `./sdk-specific-imports`.
+ *
+ * Both the chunked bootstrap and the legacy monolithic bundle are served from
+ * `app/embedding-sdk.js`, with their split/on-demand chunks living one level
+ * below at `app/embedding-sdk/chunks/`. The two delivery paths discover the
+ * base differently:
+ *
+ * - Chunked bundle: the bootstrap computes the base and exposes it on
+ * `window.METABASE_EMBEDDING_SDK_ASSET_BASE_URL` before loading chunks.
+ * `document.currentScript` is unreliable here because the entry executes
+ * asynchronously, after the chunk scripts have loaded.
+ * - Legacy monolithic bundle: loaded directly as a classic script, so
+ * `document.currentScript` is valid during this module's synchronous
+ * evaluation and we derive the base from it.
+ *
+ * This module must be imported before any dynamic `import()` can run (it is the
+ * first import of the bundle entry), so the assignment lands before the first
+ * `__webpack_require__.e` call.
+ */
+
+// Provided by webpack/rspack at build time; the `declare` emits no runtime code,
+// so the assignment below is rewritten to set the runtime's `publicPath`.
+declare let __webpack_public_path__: string;
+
+const resolveAssetBaseUrl = (): string | undefined => {
+ const fromGlobal =
+ typeof window !== "undefined"
+ ? window.METABASE_EMBEDDING_SDK_ASSET_BASE_URL
+ : undefined;
+
+ if (typeof fromGlobal === "string" && fromGlobal.length > 0) {
+ return fromGlobal;
+ }
+
+ if (typeof document === "undefined") {
+ return undefined;
+ }
+
+ const scriptUrl = (document.currentScript as HTMLScriptElement | null)?.src;
+
+ if (!scriptUrl) {
+ return undefined;
+ }
+
+ // e.g. ".../app/embedding-sdk.js" -> ".../app/embedding-sdk/"
+ return new URL("embedding-sdk/", new URL("./", scriptUrl)).href;
+};
+
+const assetBaseUrl = resolveAssetBaseUrl();
+
+if (assetBaseUrl) {
+ __webpack_public_path__ = assetBaseUrl;
+}
+
+export {};
diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-specific-imports.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-specific-imports.ts
index d32c909dfe9..230f66292ad 100644
--- a/frontend/src/embedding-sdk-bundle/lib/sdk-specific-imports.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-specific-imports.ts
@@ -9,34 +9,10 @@
import "./polyfill/use-sync-external-store";
/**
- * We need to manually import them here to make sure they are included in the bundle
- * as they're dynamically loaded in the main codebase.
- *
- * This will crash the main app if it's included in the new iframe embedding plugin,
- * as we chunk-split these two dependencies to make it only dynamically loadable.
- */
-import "html2canvas-pro";
-import "jspdf";
-
-/**
- * The map renderer (and leaflet) is lazily chunk-split in the main app, but the
- * SDK bundle can't fetch on-demand chunks at runtime. Importing it eagerly here
- * pulls it into the preloaded SDK bundle so the `import()` in `Map.tsx` resolves
- * from an already-loaded chunk instead of 404ing.
- */
-import "metabase/visualizations/visualizations/Map/MapRenderer";
-
-// react-virtualized powers the pivot table grid and is lazily imported in the
-// main app. The SDK bundle can't fetch on-demand chunks at runtime, so force the
-// pivot table module to be included eagerly here.
-import "metabase/visualizations/visualizations/PivotTable/PivotTableInner";
-
-/**
- * EChartsRenderer (and all of echarts) is loaded as an on-demand chunk in the
- * main app (see EChartsRenderer/lazy.ts) to keep echarts out of the initial
- * bundle. The SDK loads its code eagerly via a build-time manifest and can't
- * fetch on-demand chunks in a host app (they'd fail with a ChunkLoadError), so
- * we force EChartsRenderer into the bundle here. The dynamic `import()` then
- * resolves from the already-loaded module instead of fetching a chunk.
+ * NOTE: heavy dependencies that are lazily imported in the main codebase
+ * (`jspdf`, `html2canvas-pro` for PDF / image export; `react-virtualized` via
+ * the pivot table grid; `leaflet` via the map renderer) are intentionally NOT
+ * eagerly imported here. They are loaded on demand via dynamic `import()`, so
+ * they no longer weigh down the SDK's critical-path bundle. On-demand chunks
+ * resolve against the runtime `publicPath` set in `./sdk-public-path`.
*/
-import "metabase/visualizations/components/EChartsRenderer/EChartsRenderer";
diff --git a/frontend/src/embedding-sdk-shared/types/globals.d.ts b/frontend/src/embedding-sdk-shared/types/globals.d.ts
index 07816a445eb..e1f510865e4 100644
--- a/frontend/src/embedding-sdk-shared/types/globals.d.ts
+++ b/frontend/src/embedding-sdk-shared/types/globals.d.ts
@@ -7,6 +7,8 @@ interface Window {
ReactDOMServer?: unknown;
METABASE_EMBEDDING_SDK_BUNDLE?: import("embedding-sdk-bundle/types/sdk-bundle").MetabaseEmbeddingSdkBundleExports;
+ METABASE_EMBEDDING_SDK_ASSET_BASE_URL?: string; // Base URL for on-demand SDK chunks; set by the bootstrap
+
METABASE_PROVIDER_PROPS_STORE?: import("embedding-sdk-shared/lib/ensure-metabase-provider-props-store").MetabaseProviderPropsStore;
METABASE_EMBEDDING_SDK_PACKAGE_BUILD_INFO?: import("metabase/embedding-sdk/types/build-info").BuildInfo;
METABASE_EMBEDDING_SDK_BUNDLE_BUILD_INFO?: import("metabase/embedding-sdk/types/build-info").BuildInfo;