The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
feat(sdk): speed up the embedding sdk loading time: do auth flow in parallel with bundle loading and split the bundle in chunks (#70015)
Nicolò Pretto10286754eea9
diff --git a/.github/actions/sdk-bundle-size-check/action.yml b/.github/actions/sdk-bundle-size-check/action.ymlindex bddc758ad71..f0bee84c950 100644--- a/.github/actions/sdk-bundle-size-check/action.yml+++ b/.github/actions/sdk-bundle-size-check/action.yml@@ -35,9 +35,22 @@ runs:with:name: metabase-${{ inputs.edition }}-${{ github.event.pull_request.head.sha || github.sha }}-uberjarpath: temp/current-uberjar- - name: Extract embedding-sdk.js from current uberjar+ - name: Extract embedding-sdk bundles from current uberjarshell: bash- run: unzip -j temp/current-uberjar/target/uberjar/metabase.jar frontend_client/app/embedding-sdk.js -d temp/current-bundle+ run: |+ # Try new layout first (app/embedding-sdk/legacy/), fall back to old layout (app/embedding-sdk.js)+ unzip -j temp/current-uberjar/target/uberjar/metabase.jar \+ "frontend_client/app/embedding-sdk/legacy/embedding-sdk.js" \+ -d temp/current-bundle 2>/dev/null || \+ unzip -j temp/current-uberjar/target/uberjar/metabase.jar \+ "frontend_client/app/embedding-sdk.js" \+ -d temp/current-bundle++ # Extract chunks directory if it exists (new layout only)+ mkdir -p temp/current-chunks+ unzip -j temp/current-uberjar/target/uberjar/metabase.jar \+ "frontend_client/app/embedding-sdk/chunks/*" \+ -d temp/current-chunks 2>/dev/null || true- name: Checkout base refuses: actions/checkout@v4with:@@ -53,13 +66,21 @@ runs:id: compareshell: bashrun: |+ # --- Legacy (monolithic) bundle comparison ---current_size=$(wc -c < temp/current-bundle/embedding-sdk.js) || { echo "::error::Failed to read current bundle"; exit 1; }- base_ref_size=$(wc -c < temp/base-ref-src/resources/frontend_client/app/embedding-sdk.js) || { echo "::error::Failed to read base-ref bundle"; exit 1; }++ # Base ref: try new layout first, fall back to old+ if [ -f "temp/base-ref-src/resources/frontend_client/app/embedding-sdk/legacy/embedding-sdk.js" ]; then+ base_ref_size=$(wc -c < "temp/base-ref-src/resources/frontend_client/app/embedding-sdk/legacy/embedding-sdk.js")+ else+ base_ref_size=$(wc -c < "temp/base-ref-src/resources/frontend_client/app/embedding-sdk.js")+ fi[ "$current_size" -gt 0 ] && [ "$base_ref_size" -gt 0 ] || { echo "::error::Bundle file is empty"; exit 1; }diff=$((current_size - base_ref_size))percent=$(( diff * 100 / base_ref_size ))+ echo "=== Legacy (monolithic) bundle ==="echo "Current size: $current_size bytes"echo "Base ref size: $base_ref_size bytes"echo "Difference: $diff bytes ($percent%)"@@ -75,3 +96,15 @@ runs:echo "status=$status" >> $GITHUB_OUTPUTecho "size_change_percent=$percent" >> $GITHUB_OUTPUT++ # --- Chunked bundle (informational) ---+ if ls temp/current-chunks/*.js 1>/dev/null 2>&1; then+ chunks_size=$(cat temp/current-chunks/*.js | wc -c)+ echo ""+ echo "=== Chunked bundle (bootstrap + chunks) ==="+ echo "Total chunked size: $chunks_size bytes"+ echo "chunks_size=$chunks_size" >> $GITHUB_OUTPUT+ else+ echo ""+ echo "No chunked bundle found (expected on master)"+ fidiff --git a/.gitignore b/.gitignoreindex 7fc31cee149..0fa671ec0ce 100644--- a/.gitignore+++ b/.gitignore@@ -65,6 +65,7 @@ cypress.env.json/resources/frontend_client/app/embed.js/resources/frontend_client/app/embedding-sdk.js/resources/frontend_client/app/embedding-sdk.js.map+/resources/frontend_client/app/embedding-sdk//resources/frontend_client/tmp-*//resources/frontend_client/embed.html/resources/frontend_client/embed-sdk.htmldiff --git a/e2e/test-component/scenarios/embedding-sdk/loading-performance.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/loading-performance.cy.spec.tsxindex f76819cdeeb..7f03b3585e4 100644--- a/e2e/test-component/scenarios/embedding-sdk/loading-performance.cy.spec.tsx+++ b/e2e/test-component/scenarios/embedding-sdk/loading-performance.cy.spec.tsx@@ -2,7 +2,10 @@ import { InteractiveQuestion } from "@metabase/embedding-sdk-react";import { ORDERS_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";-import { mountSdkContent } from "e2e/support/helpers/embedding-sdk-component-testing";+import {+ getSdkBundleScriptElement,+ mountSdkContent,+} from "e2e/support/helpers/embedding-sdk-component-testing";import {AUTH_PROVIDER_URL,METABASE_INSTANCE_URL,@@ -11,70 +14,478 @@ import {mockAuthProviderAndJwtSignIn,signInAsAdminAndEnableEmbeddingSdk,} from "e2e/support/helpers/embedding-sdk-testing";+import { deleteConflictingCljsGlobals } from "metabase/embedding-sdk/test/delete-conflicting-cljs-globals";+import { defer } from "metabase/lib/promise";++const { H } = cy;++const sdkBundleCleanup = () => {+ getSdkBundleScriptElement()?.remove();+ delete (window as any).METABASE_EMBEDDING_SDK_BUNDLE;+ delete (window as any).METABASE_PROVIDER_PROPS_STORE;+ delete (window as any).METABASE_EMBEDDING_SDK_AUTH_STATE;+ // Clean up webpack chunk registries so stale runtimes from a previous test+ // don't interfere with chunks loaded by the next test.+ delete (window as any).webpackChunkembedding_sdk_bundle;+ delete (window as any).webpackChunkembedding_sdk_legacy;+ deleteConflictingCljsGlobals();+};++describe(+ "scenarios > embedding-sdk > loading-performance",+ {+ tags: ["@skip-backward-compatibility"],+ // These test in some cases load a new SDK Bundle that in combination with the Component Testing is memory-consuming+ numTestsKeptInMemory: 1,+ },+ () => {+ beforeEach(() => {+ H.clearBrowserCache();+ sdkBundleCleanup();++ signInAsAdminAndEnableEmbeddingSdk();+ cy.signOut();+ mockAuthProviderAndJwtSignIn();+ });-describe("scenarios > embedding-sdk > loading-performance", () => {- beforeEach(() => {- signInAsAdminAndEnableEmbeddingSdk();- cy.signOut();- mockAuthProviderAndJwtSignIn();-- // Intercept SSO discovery request (without jwt parameter)- cy.intercept("GET", /\/auth\/sso(\?preferred_method=\w+)?$/).as(- "authSsoDiscovery",- );- // Intercept token exchange request (with jwt parameter)- cy.intercept("GET", /\/auth\/sso\?.*jwt=/).as("authSsoTokenExchange");- cy.intercept("GET", "/api/user/current").as("getCurrentUser");- cy.intercept("GET", "/api/session/properties").as("getSessionProperties");- });-- describe("Baseline: when jwtProviderUri is not provided", () => {- it("should make SSO discovery request, then token exchange", () => {- mountSdkContent(<InteractiveQuestion questionId={ORDERS_QUESTION_ID} />, {- sdkProviderProps: {- authConfig: {- metabaseInstanceUrl: METABASE_INSTANCE_URL,+ describe("Bundle loading modes", () => {+ it("useLegacyMonolithicBundle=true: loads monolithic bundle, renders question, correct URL and script element", () => {+ cy.log("Intercepting bundle request");+ cy.intercept("GET", "**/app/embedding-sdk.js?*").as("bundleRequest");++ cy.log("Mounting with useLegacyMonolithicBundle=true");+ mountSdkContent(+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />,+ {+ sdkProviderProps: {+ useLegacyMonolithicBundle: true,+ authConfig: { metabaseInstanceUrl: METABASE_INSTANCE_URL },+ },},- },+ );++ cy.log("Checking question renders");+ getSdkRoot().within(() => {+ cy.findByText("Orders").should("exist");+ cy.findByTestId("visualization-root").should("be.visible");+ });++ cy.log(+ "Checking request URL has packageVersion and useLegacyMonolithicBundle params",+ );+ cy.get("@bundleRequest.all").then((interceptions: any) => {+ expect(interceptions.length).to.be.greaterThan(0);+ expect(interceptions[0].request.url).to.include("packageVersion=");+ expect(interceptions[0].request.url).to.include(+ "useLegacyMonolithicBundle=true",+ );+ });++ cy.log("Checking window.METABASE_EMBEDDING_SDK_BUNDLE");+ cy.window()+ .its("METABASE_EMBEDDING_SDK_BUNDLE")+ .should("exist")+ .and("have.property", "InteractiveQuestion");++ cy.log("Checking script element has data-embedding-sdk-bundle attr");+ cy.document().then((doc) => {+ const script = doc.querySelector(+ '[data-embedding-sdk-bundle="true"]',+ );+ expect(script).to.not.be.null;+ });});- // Verify question renders- getSdkRoot().within(() => {- cy.findByText("Orders").should("exist");- cy.findByTestId("visualization-root").should("be.visible");+ it("useLegacyMonolithicBundle=false (default): loads bootstrap + chunks, renders question, correct URL and script element", () => {+ cy.log("Intercepting bundle request");+ cy.intercept("GET", "**/app/embedding-sdk.js?*").as("bundleRequest");+ cy.intercept("GET", "**/app/embedding-sdk/chunks/*.js").as(+ "chunkRequest",+ );++ cy.log("Mounting with default useLegacyMonolithicBundle value (false)");+ mountSdkContent(+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />,+ );++ cy.log("Checking question renders");+ getSdkRoot().within(() => {+ cy.findByText("Orders").should("exist");+ cy.findByTestId("visualization-root").should("be.visible");+ });++ cy.log(+ "Checking request URL has packageVersion but no useLegacyMonolithicBundle",+ );+ cy.get("@bundleRequest.all").then((interceptions: any) => {+ expect(interceptions.length).to.be.greaterThan(0);+ expect(interceptions[0].request.url).to.include("packageVersion=");+ expect(interceptions[0].request.url).to.not.include(+ "useLegacyMonolithicBundle",+ );+ });+ cy.log("Checking chunk requests happened (proves bootstrap path)");+ cy.get("@chunkRequest.all").then((interceptions: any) => {+ expect(interceptions.length).to.be.greaterThan(0);+ });++ cy.log("Checking window.METABASE_EMBEDDING_SDK_BUNDLE");+ cy.window().its("METABASE_EMBEDDING_SDK_BUNDLE").should("exist");++ cy.log("Checking script element has data-embedding-sdk-bundle attr");+ cy.document().then((doc) => {+ const script = doc.querySelector(+ '[data-embedding-sdk-bundle="true"]',+ );+ expect(script).to.not.be.null;+ });+ });+ });++ describe("Error handling", () => {+ it("shows error when bundle returns 404", () => {+ cy.log("Intercepting bundle with 404");+ cy.intercept("GET", "**/app/embedding-sdk.js*", { statusCode: 404 });++ mountSdkContent(+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />,+ { waitForUser: false },+ );++ cy.log("Checking error container is shown");+ cy.findByTestId("sdk-error-container").should(+ "contain.text",+ "Error loading the Embedded Analytics SDK",+ );});- // Baseline: discovery + token exchange- cy.get("@authSsoDiscovery.all").should("have.length", 1);- cy.get("@authSsoTokenExchange.all").should("have.length", 1);- cy.get("@getCurrentUser.all").should("have.length", 1);- cy.get("@getSessionProperties.all").should("have.length", 1);+ it("shows error when bundle has a network error (not 404)", () => {+ cy.log("Intercepting bundle with network error (forceNetworkError)");+ cy.intercept("GET", "**/app/embedding-sdk.js*", {+ forceNetworkError: true,+ });++ mountSdkContent(+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />,+ { waitForUser: false },+ );++ cy.log("Checking error container is shown");+ cy.findByTestId("sdk-error-container").should(+ "contain.text",+ "Error loading the Embedded Analytics SDK",+ );+ });++ it("shows error when chunk loading fails", () => {+ cy.log("Intercepting chunk requests with network error");+ cy.intercept("GET", /embedding-sdk\/chunks\/.*\.js/, {+ forceNetworkError: true,+ }).as("chunkRequest");++ cy.log("Mounting with bootstrap (default)");+ mountSdkContent(+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />,+ { waitForUser: false },+ );++ cy.log("Checking error container is shown");+ cy.findByTestId("sdk-error-container").should(+ "contain.text",+ "Error loading the Embedded Analytics SDK",+ );+ });});- });-- describe("when jwtProviderUri is provided", () => {- it("should skip the initial /auth/sso request", () => {- mountSdkContent(<InteractiveQuestion questionId={ORDERS_QUESTION_ID} />, {- sdkProviderProps: {- authConfig: {- metabaseInstanceUrl: METABASE_INSTANCE_URL,- preferredAuthMethod: "jwt",- jwtProviderUri: AUTH_PROVIDER_URL,++ describe("Loading behavior", () => {+ it("shows custom loader while bundle is loading", () => {+ const bundleRequestDeferred = defer<void>();++ cy.log("Intercepting bundle with deferred response");+ cy.intercept(+ {+ method: "GET",+ url: "**/app/embedding-sdk.js*",+ times: 1,+ },+ () => bundleRequestDeferred.promise,+ ).as("bundleRequest");++ mountSdkContent(+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />,+ {+ sdkProviderProps: {+ loaderComponent: () => <div>SDK is loading...</div>,+ },+ waitForUser: false,},- },+ );++ cy.log("Checking custom loader is rendered");+ cy.findByTestId("loading-indicator").should(+ "contain.text",+ "SDK is loading...",+ );++ cy.log("Resolving deferred bundle request");+ cy.then(() => bundleRequestDeferred.resolve());++ cy.log("Waiting for bundle to finish loading");+ cy.wait("@bundleRequest");++ cy.log("Checking question renders and loader disappears");+ getSdkRoot().within(() => {+ cy.findByText("Orders", { timeout: 20_000 }).should("exist");+ cy.findByTestId("visualization-root").should("be.visible");+ });+ cy.findByTestId("loading-indicator").should("not.exist");});- // Verify question renders- getSdkRoot().within(() => {- cy.findByText("Orders").should("exist");- cy.findByTestId("visualization-root").should("be.visible");+ it("no duplicate script elements on remount, store cleaned up on unmount", () => {+ cy.log("First mount");+ mountSdkContent(+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />,+ );++ getSdkRoot().within(() => {+ cy.findByText("Orders").should("exist");+ });++ cy.log("Checking 1 script element after first mount");+ cy.document().then((doc) => {+ const scripts = doc.querySelectorAll(+ '[data-embedding-sdk-bundle="true"]',+ );+ expect(scripts.length).to.equal(1);+ });++ cy.log("Remounting");+ mountSdkContent(+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />,+ );++ getSdkRoot().within(() => {+ cy.findByText("Orders").should("exist");+ });++ cy.log("Checking still 1 script element after remount");+ cy.document().then((doc) => {+ const scripts = doc.querySelectorAll(+ '[data-embedding-sdk-bundle="true"]',+ );+ expect(scripts.length).to.equal(1);+ });++ cy.log("Unmounting");+ cy.mount(<></>);++ cy.log("Checking METABASE_PROVIDER_PROPS_STORE cleaned up");+ cy.window().should((win) => {+ expect((win as any).METABASE_PROVIDER_PROPS_STORE).to.be.undefined;+ });+ });++ it("remount after loaded skips re-download", () => {+ cy.log("Intercepting bundle requests");+ cy.intercept("GET", "**/app/embedding-sdk.js?*").as("bundleRequest");++ cy.log("First mount");+ mountSdkContent(+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />,+ );++ getSdkRoot().within(() => {+ cy.findByText("Orders").should("exist");+ });++ cy.log("Checking bundle global exists");+ cy.window().its("METABASE_EMBEDDING_SDK_BUNDLE").should("exist");++ cy.log("Unmounting");+ cy.mount(<></>);++ cy.log("Remounting — should skip Loading state");+ mountSdkContent(+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />,+ );++ getSdkRoot().within(() => {+ cy.findByText("Orders").should("exist");+ });++ cy.log("Checking total bundle requests is at most 1");+ cy.get("@bundleRequest.all").then((interceptions: any) => {+ expect(interceptions.length).to.be.at.most(1);+ });+ });+ });++ describe("Auth request counts", () => {+ beforeEach(() => {+ cy.intercept("GET", /\/auth\/sso(\?preferred_method=\w+)?$/).as(+ "authSsoDiscovery",+ );+ cy.intercept("GET", /\/auth\/sso\?.*jwt=/).as("authSsoTokenExchange");+ cy.intercept("GET", "/api/user/current").as("getCurrentUser");+ cy.intercept("GET", "/api/session/properties").as(+ "getSessionProperties",+ );+ });++ it("without jwtProviderUri: makes SSO discovery request + token exchange", () => {+ mountSdkContent(+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />,+ {+ sdkProviderProps: {+ authConfig: {+ metabaseInstanceUrl: METABASE_INSTANCE_URL,+ },+ },+ },+ );++ getSdkRoot().within(() => {+ cy.findByText("Orders").should("exist");+ cy.findByTestId("visualization-root").should("be.visible");+ });++ cy.get("@authSsoDiscovery.all").should("have.length", 1);+ cy.get("@authSsoTokenExchange.all").should("have.length", 1);+ cy.get("@getCurrentUser.all").should("have.length", 1);+ cy.get("@getSessionProperties.all").should("have.length", 1);+ });++ it("with jwtProviderUri: skips SSO discovery", () => {+ mountSdkContent(+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />,+ {+ sdkProviderProps: {+ authConfig: {+ metabaseInstanceUrl: METABASE_INSTANCE_URL,+ preferredAuthMethod: "jwt",+ jwtProviderUri: AUTH_PROVIDER_URL,+ },+ },+ },+ );++ getSdkRoot().within(() => {+ cy.findByText("Orders").should("exist");+ cy.findByTestId("visualization-root").should("be.visible");+ });++ cy.get("@authSsoDiscovery.all").should("have.length", 0);+ cy.get("@authSsoTokenExchange.all").should("have.length", 1);+ cy.get("@getCurrentUser.all").should("have.length", 1);+ cy.get("@getSessionProperties.all").should("have.length", 1);+ });+ });++ describe("Bootstrap auth edge cases", () => {+ it("skips bootstrap auth when preferredAuthMethod is saml", () => {+ cy.log("Mounting with preferredAuthMethod: saml");+ mountSdkContent(+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />,+ {+ sdkProviderProps: {+ authConfig: {+ metabaseInstanceUrl: METABASE_INSTANCE_URL,+ preferredAuthMethod: "saml",+ },+ },+ },+ );++ cy.log("Checking bootstrap auth state is 'skipped'");+ cy.window()+ .its("METABASE_EMBEDDING_SDK_AUTH_STATE")+ .should("have.property", "status", "skipped");+ });++ it("skips bootstrap auth when SSO discovery returns SAML", () => {+ cy.log("Intercepting SSO discovery to return SAML for bootstrap");+ // This is a bit of an hack, on the first sso request we mock the saml response+ // then we don't, so that it finishes loading and we can check if the bootstrap auth was skipped+ let firstSsoDiscovery = true;+ cy.intercept("GET", "**/auth/sso*", (req) => {+ if (!req.url.includes("jwt=") && firstSsoDiscovery) {+ firstSsoDiscovery = false;+ req.reply({+ statusCode: 200,+ body: {+ method: "saml",+ url: "https://fake-saml-idp.example.com/sso",+ },+ });+ return;+ }+ req.continue();+ });++ cy.log("Mounting");+ mountSdkContent(+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />,+ {+ sdkProviderProps: {+ authConfig: { metabaseInstanceUrl: METABASE_INSTANCE_URL },+ },+ waitForUser: false,+ },+ );++ cy.log("Checking bootstrap auth state is 'skipped'");+ cy.window()+ .its("METABASE_EMBEDDING_SDK_AUTH_STATE")+ .should("have.property", "status", "skipped");});- // Optimized: no discovery, only token exchange- cy.get("@authSsoDiscovery.all").should("have.length", 0);- cy.get("@authSsoTokenExchange.all").should("have.length", 1);- cy.get("@getCurrentUser.all").should("have.length", 1);- cy.get("@getSessionProperties.all").should("have.length", 1);+ it("falls back to normal auth when bootstrap auth fails", () => {+ cy.log(+ "Intercepting first SSO discovery call to make bootstrap auth fail",+ );+ let bootstrapSsoFailed = false;+ cy.intercept("GET", "**/auth/sso*", (req) => {+ // Fail only the first SSO discovery call (no jwt= param).+ // This is the one made by the bootstrap auth.+ // Subsequent calls (normal auth fallback) pass through.+ if (!req.url.includes("jwt=") && !bootstrapSsoFailed) {+ bootstrapSsoFailed = true;+ req.reply({+ statusCode: 500,+ body: { error: "simulated bootstrap SSO failure" },+ });+ return;+ }+ req.continue();+ }).as("ssoRequest");++ cy.window().then((win) => {+ cy.spy(win.console, "warn").as("consoleWarn");+ });++ cy.log("Mounting");+ mountSdkContent(+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />,+ {+ sdkProviderProps: {+ authConfig: { metabaseInstanceUrl: METABASE_INSTANCE_URL },+ },+ waitForUser: false,+ },+ );++ cy.log("Checking question renders via normal auth fallback");+ getSdkRoot().within(() => {+ cy.findByText("Orders").should("exist");+ cy.findByTestId("visualization-root").should("be.visible");+ });++ cy.log("Checking fallback warning was logged");+ cy.get("@consoleWarn").should(+ "be.calledWithMatch",+ /Falling back to normal auth flow/,+ );+ });});- });-});+ },+);diff --git a/e2e/test-component/scenarios/embedding-sdk/sdk-bundle-error-handling.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/sdk-bundle-error-handling.cy.spec.tsxindex 42c75b31c93..b12eedb5908 100644--- a/e2e/test-component/scenarios/embedding-sdk/sdk-bundle-error-handling.cy.spec.tsx+++ b/e2e/test-component/scenarios/embedding-sdk/sdk-bundle-error-handling.cy.spec.tsx@@ -39,7 +39,7 @@ describe(sdkBundleCleanup();- cy.intercept("GET", "**/app/embedding-sdk.js", {+ cy.intercept("GET", "**/app/embedding-sdk.js?*", {statusCode: 404,});});diff --git a/e2e/test-component/scenarios/embedding-sdk/sdk-bundle.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/sdk-bundle.cy.spec.tsxindex c15e637ca6f..783e9b0ec65 100644--- a/e2e/test-component/scenarios/embedding-sdk/sdk-bundle.cy.spec.tsx+++ b/e2e/test-component/scenarios/embedding-sdk/sdk-bundle.cy.spec.tsx@@ -192,16 +192,10 @@ describe(it("should show a custom loader when the SDK bundle is loading", () => {sdkBundleCleanup();- const MINUTE = 60 * 1000;- cy.intercept("GET", "/api/card/*", (request) => {- /**- * Delay request for 10 min to avoid flakiness. We don't need the request to return, since we're testing the loading state.- * From observing the failed test log, it failed at 10.9s, and the timeout for finding the loading indicator was set to 10s.- * That means, Cypress started looking for the loading indicator after ~0.9s of the request being delayed.- */- request.continue(- () => new Promise((resolve) => setTimeout(resolve, 10 * MINUTE)),- );+ // Intercept the SDK bundle script and never respond,+ // keeping loadingState stuck at "Loading" so the Loader is rendered.+ cy.intercept("GET", "**/app/embedding-sdk.js*", () => {+ return new Promise(() => {}); // never resolves → request stays pending});mountSdkContent(diff --git a/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts b/enterprise/frontend/src/embedding-sdk-ee/auth/auth.tsindex 16f47a07c59..04111292239 100644--- a/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts+++ b/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts@@ -11,7 +11,10 @@ import {} from "embedding/auth-common";import * as MetabaseError from "embedding-sdk-bundle/errors";import { getIsLocalhost } from "embedding-sdk-bundle/lib/get-is-localhost";-import { PLUGIN_EMBEDDING_SDK_AUTH } from "embedding-sdk-bundle/store/auth";+import {+ PLUGIN_EMBEDDING_SDK_AUTH,+ refreshTokenAsync as refreshTokenAsyncAction,+} from "embedding-sdk-bundle/store/auth";import {getFetchRefreshTokenFn,getSessionTokenState,@@ -22,6 +25,9 @@ import type {} from "embedding-sdk-bundle/store/types";import type { MetabaseAuthConfig } from "embedding-sdk-bundle/types/auth-config";import { getBuildInfo } from "embedding-sdk-shared/lib/get-build-info";+import { getWindow } from "embedding-sdk-shared/lib/get-window";+import type { SdkAuthState } from "embedding-sdk-shared/types/auth-state";+import { SDK_AUTH_STATE_KEY } from "embedding-sdk-shared/types/auth-state";import { requestSessionTokenFromEmbedJs } from "metabase/embedding/embedding-iframe-sdk/utils";import {EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG,@@ -31,9 +37,11 @@ import { samlTokenStorage } from "metabase/embedding-sdk/lib/saml-token-storage"import type { MetabaseEmbeddingSessionToken } from "metabase/embedding-sdk/types/refresh-token";import api from "metabase/lib/api";import { createAsyncThunk } from "metabase/lib/redux";+import MetabaseSettings from "metabase/lib/settings";import { PLUGIN_EMBEDDING_SDK } from "metabase/plugins";-import { refreshSiteSettings } from "metabase/redux/settings";+import { loadSettings, refreshSiteSettings } from "metabase/redux/settings";import { refreshCurrentUser } from "metabase/redux/user";+import type { Settings } from "metabase-types/api";const GET_OR_REFRESH_SESSION = "sdk/token/GET_OR_REFRESH_SESSION";@@ -46,16 +54,65 @@ PLUGIN_EMBEDDING_SDK_AUTH.initAuth = async (authConfig: MetabaseAuthConfig & { isLocalHost?: boolean },{ dispatch }: { dispatch: SdkDispatch },) => {- const { metabaseInstanceUrl, preferredAuthMethod, apiKey, isLocalHost } =- authConfig;-- // This is needed because of how MetabaseAuthConfig is typed- const jwtProviderUri =- "jwtProviderUri" in authConfig ? authConfig.jwtProviderUri : undefined;+ const { metabaseInstanceUrl, apiKey, isLocalHost } = authConfig;- // remove any stale tokens that might be there from a previous session=+ // remove any stale tokens that might be there from a previous sessionsamlTokenStorage.remove();+ // Check if we can use the auth pre-fetched by the bootstrap chunk+ const earlyAuthStatus = getAuthState()?.status;+ if (earlyAuthStatus && earlyAuthStatus !== "skipped") {+ try {+ await waitForAuthCompletion();+ } catch {+ // Timeout or unexpected error — clear stale state and fall back to normal auth.+ clearAuthState();+ }+ const authState = getAuthState();+ // Clear the auth state after we read it, so that if `initAuth` is called again it doesn't retry to use the old state+ clearAuthState();++ if (+ authState?.status === "completed" &&+ authState.session &&+ authState.user &&+ authState.siteSettings+ ) {+ api.sessionToken = authState.session.id;+ // Store the session token in Redux so getOrRefreshSession finds it+ // and doesn't trigger a redundant token refresh on the first API call.+ dispatch(+ refreshTokenAsyncAction.fulfilled(authState.session, "", {+ metabaseInstanceUrl: authConfig.metabaseInstanceUrl,+ }),+ );+ dispatch(refreshCurrentUser.fulfilled(authState.user, "", undefined));+ dispatch(loadSettings(authState.siteSettings as Settings));+ MetabaseSettings.setAll(authState.siteSettings as Settings);++ // Set up the refresh handler so API calls can renew the token later.+ PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.getOrRefreshSessionHandler =+ async () => {+ const session = await dispatch(+ getOrRefreshSession(authConfig),+ ).unwrap();+ if (session?.id) {+ api.sessionToken = session.id;+ }+ };++ return;+ }+ // Bootstrap auth failed or returned incomplete data.+ // We don't throw otherwise the sdk will show the error component, the main bundle logic will+ // retry its own auth logic and handle the errors if it happens again.+ console.warn(+ "SDK: Bootstrap auth did not complete successfully (status: " ++ (authState?.status ?? "unknown") ++ "). Falling back to normal auth flow.",+ );+ }+// Setup JWT or API keyconst isValidInstanceUrl =metabaseInstanceUrl && metabaseInstanceUrl?.length > 0;@@ -71,11 +128,7 @@ PLUGIN_EMBEDDING_SDK_AUTH.initAuth = async (PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.getOrRefreshSessionHandler =async () => {const session = await dispatch(- getOrRefreshSession({- metabaseInstanceUrl,- preferredAuthMethod,- jwtProviderUri,- }),+ getOrRefreshSession(authConfig),).unwrap();if (session?.id) {api.sessionToken = session.id;@@ -83,15 +136,9 @@ PLUGIN_EMBEDDING_SDK_AUTH.initAuth = async (};try {// verify that the session is actually valid before proceeding- await dispatch(- getOrRefreshSession({- metabaseInstanceUrl,- preferredAuthMethod,- jwtProviderUri,- }),- ).unwrap();+ await dispatch(getOrRefreshSession(authConfig)).unwrap();} catch (e) {- // TODO: Fix this. For some reason the instanceof check keeps returning `false`. I'd rather not do this+ // TODO (Oisin 2025-05-27): Fix this. For some reason the instanceof check keeps returning `false`. I'd rather not do this// but due to time constraints this is what we have to do to make sure tests pass.// eslint-disable-next-line metabase/no-literal-metabase-strings -- error checking for better errors. should be improved in the future.if ((e as Error).name === "MetabaseError") {@@ -120,15 +167,7 @@ PLUGIN_EMBEDDING_SDK_AUTH.initAuth = async (};const refreshTokenImpl = async (- {- metabaseInstanceUrl,- preferredAuthMethod,- jwtProviderUri,- }: {- metabaseInstanceUrl: string;- preferredAuthMethod?: MetabaseAuthConfig["preferredAuthMethod"];- jwtProviderUri?: string;- },+ config: MetabaseAuthConfig,{ getState }: { getState: () => unknown },): Promise<MetabaseEmbeddingSessionToken | null> => {const state = getState() as SdkStoreState;@@ -140,9 +179,7 @@ const refreshTokenImpl = async (const customGetRefreshToken = getFetchRefreshTokenFn(state) ?? undefined;const session = await getRefreshToken({- metabaseInstanceUrl,- preferredAuthMethod,- jwtProviderUri,+ ...config,fetchRequestToken: customGetRefreshToken,});validateSession(session);@@ -161,14 +198,7 @@ PLUGIN_EMBEDDING_SDK_AUTH.refreshTokenAsync = refreshTokenImpl;export const getOrRefreshSession = createAsyncThunk(GET_OR_REFRESH_SESSION,- async (- authConfig: {- metabaseInstanceUrl: string;- preferredAuthMethod?: MetabaseAuthConfig["preferredAuthMethod"];- jwtProviderUri?: string;- },- { dispatch, getState },- ) => {+ async (authConfig: MetabaseAuthConfig, { dispatch, getState }) => {// necessary to ensure that we don't use a popup every time the user// refreshes the pageconst storedAuthToken = samlTokenStorage.get();@@ -206,12 +236,10 @@ const getRefreshToken = async ({preferredAuthMethod,jwtProviderUri,fetchRequestToken: customGetRequestToken,-}: {- metabaseInstanceUrl: string;- preferredAuthMethod?: MetabaseAuthConfig["preferredAuthMethod"];- jwtProviderUri?: string;- fetchRequestToken?: MetabaseAuthConfig["fetchRequestToken"];-}) => {+}: Pick<+ MetabaseAuthConfig,+ "metabaseInstanceUrl" | "fetchRequestToken" | "preferredAuthMethod"+> & { jwtProviderUri?: string }) => {const shouldSkipSsoDiscovery = jwtProviderUri !== undefined;const urlResponseJson = shouldSkipSsoDiscovery@@ -251,3 +279,45 @@ function getSdkRequestHeaders(hash?: string): Record<string, string> {...(hash && { "X-Metabase-SDK-JWT-Hash": hash }),};}++function getAuthState(): SdkAuthState | undefined {+ return getWindow()?.[SDK_AUTH_STATE_KEY];+}++function clearAuthState(): void {+ const win = getWindow();+ if (win) {+ delete win[SDK_AUTH_STATE_KEY];+ }+}++/**+ * Wait for the bootstrap auth to be complete.+ * Polls the window state until it's no longer "in-progress".+ */+async function waitForAuthCompletion(+ timeoutMs: number = 30000,+): Promise<SdkAuthState> {+ // early return if already completed+ if (getAuthState()?.status !== "in-progress") {+ return getAuthState() as SdkAuthState;+ }+ const startTime = Date.now();+ const pollInterval = 10;++ return new Promise((resolve, reject) => {+ const check = () => {+ const state = getAuthState();+ if (state?.status !== "in-progress") {+ resolve(state!);+ return;+ }+ if (Date.now() - startTime > timeoutMs) {+ reject(new Error("Timeout waiting for early auth to complete"));+ return;+ }+ setTimeout(check, pollInterval);+ };+ check();+ });+}diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/MetabaseProvider/MetabaseProvider.tsx b/enterprise/frontend/src/embedding-sdk-package/components/public/MetabaseProvider/MetabaseProvider.tsxindex 4a02cdf5bcb..7970e122c79 100644--- a/enterprise/frontend/src/embedding-sdk-package/components/public/MetabaseProvider/MetabaseProvider.tsx+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/MetabaseProvider/MetabaseProvider.tsx@@ -28,7 +28,9 @@ const MetabaseProviderInitDataWrapper = memo(function InitDataWrapper() {const MetabaseProviderInner = memo(function MetabaseProviderInner(props: Omit<MetabaseProviderProps, "children">,) {- useLoadSdkBundle(props.authConfig.metabaseInstanceUrl);+ useLoadSdkBundle(props.authConfig.metabaseInstanceUrl, {+ useLegacyMonolithicBundle: props.useLegacyMonolithicBundle ?? false,+ });const { isLoading } = useSdkLoadingState();diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/private/use-load-sdk-bundle.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/private/use-load-sdk-bundle.tsindex 9d2f02df365..d1e8f23e970 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/private/use-load-sdk-bundle.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/private/use-load-sdk-bundle.ts@@ -12,16 +12,73 @@ import {const ERROR_MESSAGE = "Failed to load Embedding SDK bundle";+const SDK_PACKAGE_VERSION = process.env.VERSION || "unknown";++/**+ * Dual-listen: resolves when the SDK bundle is ready, regardless of whether+ * the server responded with the bootstrap (new backend with packageVersion param)+ * or the monolithic bundle (old backend / useLegacyMonolithicBundle=true).+ *+ * - On script `load`: if `window.METABASE_EMBEDDING_SDK_BUNDLE` is already+ * set, the monolithic bundle ran synchronously → resolve.+ * - On `"metabase-sdk-bundle-loaded"` CustomEvent: the bootstrap loaded all+ * chunks and `index.ts` executed → resolve.+ * - First signal wins; all listeners are cleaned up after settling.+ */const waitForScriptLoading = (script: HTMLScriptElement) => {return new Promise<void>((resolve, reject) => {- script.addEventListener("load", () => resolve());- script.addEventListener("error", () => reject(new Error(ERROR_MESSAGE)));+ let settled = false;++ const settle = (onSettle: () => void) => {+ if (!settled) {+ settled = true;+ cleanup();+ onSettle();+ }+ };++ const onBundleEvent = () => {+ settle(() => resolve());+ };++ const onScriptLoad = () => {+ if (window.METABASE_EMBEDDING_SDK_BUNDLE) {+ // Old backend served the monolithic bundle (or new backend served+ // monolithic because no packageVersion param or useLegacyMonolithicBundle=true).+ // The global is set synchronously during script execution → resolve.+ settle(() => resolve());+ } else {+ // The bootstrap loaded. It will load chunks in parallel, and+ // index.ts will dispatch the custom event when done.+ }+ };++ const onScriptError = () => {+ settle(() => reject(new Error(ERROR_MESSAGE)));+ };++ const onBundleError = () => {+ settle(() => reject(new Error(ERROR_MESSAGE)));+ };++ const cleanup = () => {+ document.removeEventListener("metabase-sdk-bundle-loaded", onBundleEvent);+ document.removeEventListener("metabase-sdk-bundle-error", onBundleError);+ script.removeEventListener("load", onScriptLoad);+ script.removeEventListener("error", onScriptError);+ };++ document.addEventListener("metabase-sdk-bundle-loaded", onBundleEvent);+ document.addEventListener("metabase-sdk-bundle-error", onBundleError);+ script.addEventListener("load", onScriptLoad);+ script.addEventListener("error", onScriptError);});};const loadSdkBundle = (metabaseInstanceUrl: string,existingLoadingPromise: Promise<void> | null | undefined,+ useLegacyMonolithicBundle: boolean,): Promise<void> => {if (existingLoadingPromise) {return existingLoadingPromise;@@ -33,20 +90,42 @@ const loadSdkBundle = (return waitForScriptLoading(existingScript);}+ const baseUrl = `${+ process.env.EMBEDDING_SDK_BUNDLE_HOST || metabaseInstanceUrl+ }/${SDK_BUNDLE_FULL_PATH}`;+const script = document.createElement("script");script.async = true;script.dataset[SDK_BUNDLE_SCRIPT_DATA_ATTRIBUTE_PASCAL_CASED] = "true";- script.src = `${- process.env.EMBEDDING_SDK_BUNDLE_HOST || metabaseInstanceUrl- }/${SDK_BUNDLE_FULL_PATH}`;++ // New packages always send packageVersion so the backend can distinguish them+ // from old packages (which send no params and get the legacy bundle).+ // When useLegacyMonolithicBundle is true, we also add that param so the backend+ // serves the monolithic bundle even for new packages.+ const params = new URLSearchParams({+ packageVersion: SDK_PACKAGE_VERSION,+ });+ if (useLegacyMonolithicBundle) {+ params.set("useLegacyMonolithicBundle", "true");+ }+ script.src = `${baseUrl}?${params}`;document.body.appendChild(script);return waitForScriptLoading(script);};-export function useLoadSdkBundle(metabaseInstanceUrl: string) {+interface UseLoadSdkBundleOptions {+ useLegacyMonolithicBundle: boolean;+}++export function useLoadSdkBundle(+ metabaseInstanceUrl: string,+ options: UseLoadSdkBundleOptions,+) {+ const { useLegacyMonolithicBundle } = options;+useEffect(() => {const metabaseProviderPropsStore = ensureMetabaseProviderPropsStore();const { loadingPromise: existingLoadingPromise, loadingState } =@@ -70,6 +149,7 @@ export function useLoadSdkBundle(metabaseInstanceUrl: string) {const loadingPromise = loadSdkBundle(metabaseInstanceUrl,existingLoadingPromise,+ useLegacyMonolithicBundle,);metabaseProviderPropsStore.updateInternalProps({@@ -93,5 +173,5 @@ export function useLoadSdkBundle(metabaseInstanceUrl: string) {loadingError: SdkLoadingError.Error,});});- }, [metabaseInstanceUrl]);+ }, [metabaseInstanceUrl, useLegacyMonolithicBundle]);}diff --git a/frontend/build/embedding-sdk/constants/sdk-bundle.js b/frontend/build/embedding-sdk/constants/sdk-bundle.jsindex af4b5618fac..a2e2d914938 100644--- a/frontend/build/embedding-sdk/constants/sdk-bundle.js+++ b/frontend/build/embedding-sdk/constants/sdk-bundle.js@@ -1,7 +1,17 @@-const SDK_BUNDLE_PATH = "app";+const SDK_BUNDLE_PATH = "app/embedding-sdk";module.exports.SDK_BUNDLE_PATH = SDK_BUNDLE_PATH;+const SDK_BUNDLE_LEGACY_PATH = `${SDK_BUNDLE_PATH}/legacy`;+module.exports.SDK_BUNDLE_LEGACY_PATH = SDK_BUNDLE_LEGACY_PATH;+const SDK_BUNDLE_FILENAME = "embedding-sdk.js";-module.exports.SDK_BUNDLE_FILENAME = SDK_BUNDLE_FILENAME;+module.exports.SDK_BUNDLE_FILENAME = "embedding-sdk.js";++// Single URL used by the NPM package for all scenarios.+// The backend decides what to serve based on query params:+// - packageVersion present (no useLegacyMonolithicBundle) → bootstrap+// - packageVersion + useLegacyMonolithicBundle=true → legacy monolithic+// - no params (old packages) → legacy monolithic+module.exports.SDK_BUNDLE_FULL_PATH = `app/${SDK_BUNDLE_FILENAME}`;-module.exports.SDK_BUNDLE_FULL_PATH = `${SDK_BUNDLE_PATH}/${SDK_BUNDLE_FILENAME}`;+module.exports.SDK_BUNDLE_BOOTSTRAP_FILENAME = "embedding-sdk.js";diff --git a/frontend/src/embedding-sdk-bundle/bootstrap-auth.ts b/frontend/src/embedding-sdk-bundle/bootstrap-auth.tsnew file mode 100644index 00000000000..96059805096--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/bootstrap-auth.ts@@ -0,0 +1,229 @@+/**+ * Early auth initialization that runs in the bootstrap chunk.+ *+ * This starts authentication as soon as the auth config is available,+ * in parallel with loading the main bundle chunks.+ *+ * Uses shared auth functions from embedding/auth-common for SSO discovery,+ * JWT exchange, and session validation. Rspack inlines these into the bootstrap+ * bundle since the bootstrap entry is excluded from splitChunks.+ */++import {+ connectToInstanceAuthSso,+ jwtDefaultRefreshTokenFunction,+ validateSession,+} from "embedding/auth-common";+import * as MetabaseError from "embedding-sdk-bundle/errors";++type SdkAuthState = {+ status: "idle" | "in-progress" | "completed" | "error" | "skipped";+ session?: any;+ user?: any;+ siteSettings?: Record<string, any>;+ error?: Error;+};++const SDK_AUTH_STATE_KEY = "METABASE_EMBEDDING_SDK_AUTH_STATE";++function getWindow() {+ return typeof window !== "undefined" ? window : null;+}++function setAuthState(state: SdkAuthState): void {+ const win = getWindow();+ if (win) {+ win[SDK_AUTH_STATE_KEY] = state;+ }+}++function getAuthState(): SdkAuthState | undefined {+ return getWindow()?.[SDK_AUTH_STATE_KEY];+}++/**+ * Wait for the auth config to be available in the provider props store,+ * then start auth immediately.+ */+function waitForAuthConfigAndStartEarlyAuthFlow() {+ const win = getWindow();+ if (!win) {+ return;+ }++ // Check if auth already started (shouldn't happen, but defensive)+ if (getAuthState()?.status) {+ return;+ }++ // Subscribe to store changes+ const checkForAuthConfigAndStartJwtAuth = () => {+ const store = win.METABASE_PROVIDER_PROPS_STORE;++ if (!store) {+ return false;+ }++ const state = store.getState();+ const authConfig = state?.props?.authConfig;++ if (authConfig) {+ startJwtAuth(authConfig);+ return true;+ }+ return false;+ };++ // Check immediately+ if (checkForAuthConfigAndStartJwtAuth()) {+ return;+ }++ // Poll for store for a second. If the provider hasn't mounted by then we'll just do normal auth+ let attempts = 0;+ const maxAttempts = 100;+ const delay = 10;+ const checkInterval = () => {+ if (attempts >= maxAttempts) {+ setAuthState({ status: "skipped" });+ return;+ }++ attempts++;++ setTimeout(() => {+ if (!checkForAuthConfigAndStartJwtAuth()) {+ checkInterval();+ }+ }, delay);+ };++ checkInterval();+}++function startJwtAuth(authConfig: any) {+ // Bail out: API key auth or SAML — these can't done in parallel+ if (+ ("apiKey" in authConfig && authConfig.apiKey) ||+ authConfig.preferredAuthMethod === "saml"+ ) {+ setAuthState({ status: "skipped" });+ return;+ }++ setAuthState({ status: "in-progress" });++ performFullAuthFlow({+ metabaseInstanceUrl: authConfig.metabaseInstanceUrl,+ jwtProviderUri:+ "jwtProviderUri" in authConfig ? authConfig.jwtProviderUri : undefined,+ preferredAuthMethod:+ "preferredAuthMethod" in authConfig+ ? authConfig.preferredAuthMethod+ : undefined,+ fetchRequestToken:+ "fetchRequestToken" in authConfig+ ? authConfig.fetchRequestToken+ : undefined,+ })+ .then((result) => {+ if (result === null) {+ // Non-JWT auth method (e.g. SAML) — fall back to normal auth+ setAuthState({ status: "skipped" });+ return;+ }+ setAuthState({+ status: "completed",+ session: result.session,+ user: result.user,+ siteSettings: result.siteSettings,+ });+ })+ .catch((error) => {+ console.error("SDK Bootstrap Auth: Auth failed:", error);+ setAuthState({ status: "error", error });+ });+}++async function performFullAuthFlow(config: {+ metabaseInstanceUrl: string;+ jwtProviderUri?: string;+ preferredAuthMethod?: string;+ fetchRequestToken?: () => Promise<{ jwt: string }>;+}): Promise<{+ session: any;+ user: any;+ siteSettings: Record<string, any>;+} | null> {+ const headers = getSdkRequestHeaders();++ // Step 1: SSO discovery (skip if jwtProviderUri provided)+ const ssoResult = config.jwtProviderUri+ ? { method: "jwt" as const, url: config.jwtProviderUri }+ : await connectToInstanceAuthSso(config.metabaseInstanceUrl, {+ headers,+ preferredAuthMethod: config.preferredAuthMethod as+ | "jwt"+ | "saml"+ | undefined,+ });++ if (ssoResult.method !== "jwt") {+ // SAML (or any non-JWT method) requires a popup — can't be pre-fetched+ return null;+ }++ // Steps 2+3: Fetch JWT from customer backend + exchange for session token+ const session = await jwtDefaultRefreshTokenFunction(+ ssoResult.url,+ config.metabaseInstanceUrl,+ getSdkRequestHeaders(ssoResult.hash),+ config.fetchRequestToken ?? null,+ );++ validateSession(session);++ // Step 4: Fetch user and site settings in parallel (bootstrap-specific)+ const authHeaders = {+ ...headers,+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- header name+ "X-Metabase-Session": session.id,+ };++ const [user, siteSettings] = await Promise.all([+ fetch(`${config.metabaseInstanceUrl}/api/user/current`, {+ headers: authHeaders,+ }).then(async (r) => {+ if (!r.ok) {+ throw MetabaseError.USER_FETCH_FAILED();+ }+ return r.json();+ }),+ fetch(`${config.metabaseInstanceUrl}/api/session/properties`, {+ headers: authHeaders,+ }).then(async (r) => {+ if (!r.ok) {+ throw new Error(`Failed to fetch session properties: ${r.status}`);+ }+ return r.json();+ }),+ ]);++ return { session, user, siteSettings };+}++function getSdkRequestHeaders(hash?: string): Record<string, string> {+ return {+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- header name+ "X-Metabase-Client": "embedding-sdk-react",+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- header name+ "X-Metabase-Client-Version":+ getWindow()?.METABASE_EMBEDDING_SDK_PACKAGE_BUILD_INFO?.version ??+ "unknown",+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- header name+ ...(hash && { "X-Metabase-SDK-JWT-Hash": hash }),+ };+}++// Export the function to be called explicitly+export { waitForAuthConfigAndStartEarlyAuthFlow };diff --git a/frontend/src/embedding-sdk-bundle/embedding-sdk-bootstrap.ts b/frontend/src/embedding-sdk-bundle/embedding-sdk-bootstrap.tsnew file mode 100644index 00000000000..791579cabbc--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/embedding-sdk-bootstrap.ts@@ -0,0 +1,46 @@+import { waitForAuthConfigAndStartEarlyAuthFlow } from "./bootstrap-auth";++// Bootstrap entry point for the SDK bundle.+//+// On disk: `app/embedding-sdk/chunks/embedding-sdk.js`+// Served at: `app/embedding-sdk.js?packageVersion={version}` unless `useLegacyMonolithicBundle=true` is also passed+//+// At build time, the inject-bundle-manifest rspack plugin:+// 1. Replaces "__SDK_CHUNK_MANIFEST__" with the list of split chunk paths+// 2. Appends the rspack runtime at the end of this file+//+// Because the runtime is already inlined, __webpack_require__ is available+// when this script executes. The split chunks register themselves into+// the module system as they load.++// Start auth in parallel with chunk loading+waitForAuthConfigAndStartEarlyAuthFlow();++// Replaced at build time with { chunks: ["embedding-sdk/chunks/...js", ...] }+// Paths are relative to /app/ (the baseUrl derived from document.currentScript.src)+const manifest: { chunks: string[] } = "__SDK_CHUNK_MANIFEST__" as any;++const scriptUrl =+ (document.currentScript as HTMLScriptElement | null)?.src || "";+const baseUrl = new URL("./", scriptUrl).href;++function loadScript(filename: string): Promise<string> {+ const url = `${baseUrl}${filename}`;+ return new Promise((resolve, reject) => {+ const script = document.createElement("script");+ script.async = true;+ script.src = url;+ script.addEventListener("load", () => resolve(url));+ script.addEventListener("error", () =>+ reject(new Error(`Failed to load ${filename}`)),+ );+ document.head.appendChild(script);+ });+}++void Promise.all(manifest.chunks.map((filename) => loadScript(filename))).catch(+ (error) => {+ console.error("SDK Bootstrap: Failed to load bundle chunks:", error);+ document.dispatchEvent(new CustomEvent("metabase-sdk-bundle-error"));+ },+);diff --git a/frontend/src/embedding-sdk-bundle/index.ts b/frontend/src/embedding-sdk-bundle/index.tsindex 4572080e9e8..673982c7781 100644--- a/frontend/src/embedding-sdk-bundle/index.ts+++ b/frontend/src/embedding-sdk-bundle/index.ts@@ -77,3 +77,8 @@ const sdkBundleExports: MetabaseEmbeddingSdkBundleExports = {// Define a global export METABASE_EMBEDDING_SDK_BUNDLE for SDK packagewindow.METABASE_EMBEDDING_SDK_BUNDLE = sdkBundleExports;++// Signal that the bundle is ready. In the bootstrap flow (chunked loading),+// rspack defers entry execution until all chunks are registered, so this event+// fires only after everything is ready.+document.dispatchEvent(new CustomEvent("metabase-sdk-bundle-loaded"));diff --git a/frontend/src/embedding-sdk-bundle/types/metabase-provider.ts b/frontend/src/embedding-sdk-bundle/types/metabase-provider.tsindex ddd03b903b5..c50a8df452e 100644--- a/frontend/src/embedding-sdk-bundle/types/metabase-provider.ts+++ b/frontend/src/embedding-sdk-bundle/types/metabase-provider.ts@@ -66,4 +66,13 @@ export interface MetabaseProviderProps {* Whether to allow logging to the DevTools console. Defaults to true.**/allowConsoleLog?: boolean;++ /**+ * Whether to load the full SDK bundle directly as a single file (legacy behavior),+ * instead of the optimized bootstrap that loads chunks in parallel and starts+ * authentication early.+ *+ * Defaults to false (uses the optimized bootstrap loader).+ **/+ useLegacyMonolithicBundle?: boolean;}diff --git a/frontend/src/embedding-sdk-shared/types/auth-state.ts b/frontend/src/embedding-sdk-shared/types/auth-state.tsnew file mode 100644index 00000000000..0b77a3071a8--- /dev/null+++ b/frontend/src/embedding-sdk-shared/types/auth-state.ts@@ -0,0 +1,34 @@+import type { MetabaseEmbeddingSessionToken } from "metabase/embedding-sdk/types/refresh-token";+import type { User } from "metabase-types/api";++export const SDK_AUTH_STATE_KEY = "METABASE_EMBEDDING_SDK_AUTH_STATE";++/**+ * Status of the SDK authentication process.+ *+ * - "idle": No auth started+ * - "in-progress": Package is performing auth right now+ * - "completed": Package finished auth successfully, data is cached+ * - "error": Package auth failed, bundle should retry+ * - "skipped": Package explicitly skipped auth (useLegacyMonolithicBundle or non-JWT auth)+ */+export type SdkAuthStatus =+ | "idle"+ | "in-progress"+ | "completed"+ | "error"+ | "skipped";++/**+ * State of the SDK authentication shared between package and bundle via window.+ *+ * This allows the package to start auth while the bundle downloads,+ * and the bundle to use the pre-fetched auth data instead of re-fetching.+ */+export interface SdkAuthState {+ status: SdkAuthStatus;+ session?: MetabaseEmbeddingSessionToken;+ user?: User;+ siteSettings?: Record<string, any>;+ error?: Error;+}diff --git a/frontend/src/embedding-sdk-shared/types/globals.d.ts b/frontend/src/embedding-sdk-shared/types/globals.d.tsindex 4c8d6a22b35..c184b270db1 100644--- a/frontend/src/embedding-sdk-shared/types/globals.d.ts+++ b/frontend/src/embedding-sdk-shared/types/globals.d.ts@@ -11,4 +11,5 @@ interface Window {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;METABASE_EMBEDDING_SDK_IS_HOST_APP_IN_DEV_MODE?: boolean; // Added in v59+ METABASE_EMBEDDING_SDK_AUTH_STATE?: import("embedding-sdk-shared/types/auth-state").SdkAuthState;}diff --git a/rspack.embedding-sdk-bundle.config.js b/rspack.embedding-sdk-bundle.config.jsindex f0b67998cf4..f9713b8b27e 100644--- a/rspack.embedding-sdk-bundle.config.js+++ b/rspack.embedding-sdk-bundle.config.js@@ -25,9 +25,6 @@ const { CSS_CONFIG } = require("./frontend/build/shared/rspack/css-config");const {EXTERNAL_DEPENDENCIES,} = require("./frontend/build/embedding-sdk/constants/external-dependencies");-const {- CopyJsFromTmpDirectoryPlugin,-} = require("./frontend/build/shared/rspack/copy-js-from-tmp-directory-plugin");const {getBannerOptions,} = require("./frontend/build/shared/rspack/get-banner-options");@@ -35,6 +32,7 @@ const { SVGO_CONFIG } = require("./frontend/build/shared/rspack/svgo-config");const {SDK_BUNDLE_PATH,SDK_BUNDLE_FILENAME,+ SDK_BUNDLE_BOOTSTRAP_FILENAME,} = require("./frontend/build/embedding-sdk/constants/sdk-bundle");const {getBuildInfoValues,@@ -43,17 +41,19 @@ const {getSdkBundleVersionFromVersionProperties,} = require("./frontend/build/embedding-sdk/lib/get-sdk-bundle-version-from-version-properties");-const SDK_BUNDLE_SRC_PATH =- __dirname + "/frontend/src/embedding-sdk-bundle";+const SDK_BUNDLE_SRC_PATH = __dirname + "/frontend/src/embedding-sdk-bundle";const BUILD_PATH = __dirname + "/resources/frontend_client";-const TMP_BUILD_PATH = path.resolve(BUILD_PATH, "tmp-embed-js");+const SDK_OUTPUT_PATH = path.join(BUILD_PATH, SDK_BUNDLE_PATH);const ENTERPRISE_SRC_PATH =__dirname + "/enterprise/frontend/src/metabase-enterprise";const shouldAnalyzeBundles = process.env.SHOULD_ANALYZE_BUNDLES === "true";+// Name prefix for all chunked-entry output files (runtime, split chunks, entry)+const CHUNKED_PREFIX = "embedding-sdk-chunk";+const config = {...mainConfig,@@ -61,14 +61,41 @@ const config = {context: SDK_BUNDLE_SRC_PATH,- entry: "./index.ts",+ entry: {+ // Legacy monolithic bundle — backward compatible for old NPM packages.+ // Must remain a single file (splitChunks excludes it).+ "embedding-sdk": "./index.ts",+ // Bootstrap — tiny script that starts auth early and loads chunks+ "embedding-sdk-bootstrap": "./embedding-sdk-bootstrap.ts",+ // Chunked entry — same code as monolithic, but splitChunks splits it into+ // multiple smaller files for faster V8 parse+eval via parallel streaming.+ "embedding-sdk-chunked": {+ import: "./index.ts",+ runtime: "embedding-sdk-chunk-runtime",+ },+ },output: {- // we must use a different directory than the main rspack config,- // otherwise the path conflicts and the output bundle will not appear.- path: TMP_BUILD_PATH,+ path: SDK_OUTPUT_PATH,publicPath: "",- filename: SDK_BUNDLE_FILENAME,+ // Unique name prevents self["webpackChunk"] collisions when the SDK+ // is loaded on a page that already has another webpack/rspack runtime+ // (e.g. the main Metabase app, Cypress test runner, customer's own app).+ uniqueName: "embedding_sdk_bundle",+ // Split chunks and bootstrap go into chunks/ subfolder.+ // The legacy monolithic bundle goes into legacy/.+ // The backend serves chunks/ with far-future immutable cache headers.+ chunkFilename: "chunks/[id].[contenthash:8].js",+ filename: (pathData) => {+ switch (pathData.chunk?.name) {+ case "embedding-sdk-bootstrap":+ return `chunks/${SDK_BUNDLE_BOOTSTRAP_FILENAME}`;+ case "embedding-sdk":+ return `legacy/${SDK_BUNDLE_FILENAME}`;+ default:+ return "chunks/[name].[contenthash:8].js";+ }+ },},devtool: IS_DEV_MODE ? mainConfig.devtool : false,@@ -162,12 +189,48 @@ const config = {externals: EXTERNAL_DEPENDENCIES,- optimization: OPTIMIZATION_CONFIG,+ optimization: {+ ...OPTIMIZATION_CONFIG,++ // Scope hoisting: merges ES modules into fewer closures, reducing parse overhead+ concatenateModules: true,++ // Avoid wrapping entry points in an IIFE — removes unnecessary function wrapper+ avoidEntryIife: true,++ // Override splitChunks: split the chunked entry into multiple pieces,+ // but leave the legacy monolithic entry as a single file.+ splitChunks: {+ chunks: (chunk) => {+ // Only split chunks that belong to the chunked entry+ // (the entry itself + its runtime). Never split the legacy+ // monolithic "embedding-sdk" or the bootstrap.+ const name = chunk.name || "";+ return name.startsWith(CHUNKED_PREFIX);+ },+ // Keep chunk count low (~10-12) so HTTP/1.1 clients (no reverse proxy)+ // can load them in 1-2 waves (6 connections per domain).+ // maxSize is the primary lever — larger maxSize = fewer chunks.+ maxInitialRequests: 10,+ maxSize: 5_000_000,+ minSize: 100_000,+ cacheGroups: {+ vendors: {+ test: /[\\/]node_modules[\\/]/,+ // Use a fixed name prefix so rspack merges vendors into a few chunks+ // (governed by maxSize) rather than one-per-package.+ name: "vendor",+ reuseExistingChunk: true,+ },+ default: {+ minChunks: 1,+ reuseExistingChunk: true,+ },+ },+ },+ },plugins: [- new rspack.optimize.LimitChunkCountPlugin({- maxChunks: 1,- }),new rspack.BannerPlugin(getBannerOptions(LICENSE_TEXT)),new NodePolyfillPlugin(), // for crypto, among others// https://github.com/remarkjs/remark/discussions/903@@ -180,18 +243,114 @@ const config = {version: getSdkBundleVersionFromVersionProperties(),}),}),+ // Inject chunk manifest and hashes into the bootstrap so it can load+ // all the right files with cache-busting URLs.+ {+ name: "inject-bundle-manifest",+ apply(compiler) {+ compiler.hooks.compilation.tap(+ "inject-bundle-manifest",+ (compilation) => {+ compilation.hooks.processAssets.tap(+ {+ name: "inject-bundle-manifest",+ // Must run BEFORE minification (OPTIMIZE_SIZE = 8000).+ // The placeholder "__SDK_CHUNK_MANIFEST__" is a string literal+ // that the minifier constant-folds ("str".chunks → void 0)+ // if we don't replace it first.+ stage: rspack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE,+ },+ (assets) => {+ const bootstrapKey = `chunks/${SDK_BUNDLE_BOOTSTRAP_FILENAME}`;+ const bootstrapAsset = assets[bootstrapKey];+ if (!bootstrapAsset) {+ return;+ }++ // Collect ALL chunk files for the chunked entry using the+ // compilation's entrypoint API. This includes split chunks+ // with any name (e.g. default-vendors-*), not just those+ // matching CHUNKED_PREFIX.+ const entrypoint = compilation.entrypoints.get(+ "embedding-sdk-chunked",+ );+ const chunkFiles = [];+ if (entrypoint) {+ for (const chunk of entrypoint.chunks) {+ for (const file of chunk.files) {+ // In hot mode rspack may attach HMR payload files+ // (*.hot-update.js) to chunk.files. Those are not+ // executable bundle chunks and must never be loaded+ // by the bootstrap manifest.+ if (+ file.endsWith(".js") &&+ !file.includes(".hot-update.")+ ) {+ chunkFiles.push(file);+ }+ }+ }+ }+ chunkFiles.sort();++ // Separate the runtime from the rest — runtime gets inlined+ // into the bootstrap so we avoid an extra sequential request.+ const runtimeFile =+ chunkFiles.find((f) =>+ /^chunks\/embedding-sdk-chunk-runtime\.[^/]+\.js$/.test(f),+ ) || chunkFiles.find((f) => f.includes("chunk-runtime"));+ const otherFiles = chunkFiles.filter((f) => f !== runtimeFile);++ // Paths are relative to /app/ (the bootstrap's baseUrl).+ // Chunk asset keys already include "chunks/" prefix, so+ // prepend "embedding-sdk/" to get the full route path.+ const manifest = {+ chunks: otherFiles.map((f) => `embedding-sdk/${f}`),+ };++ // Read the runtime chunk source to inline it in the bootstrap+ const runtimeSource =+ runtimeFile && assets[runtimeFile]+ ? assets[runtimeFile].source()+ : "";++ if (!runtimeSource) {+ console.warn(+ "inject-bundle-manifest: runtime chunk not found, bootstrap will not work",+ );+ }++ let newSource = bootstrapAsset.source();++ // Inject the chunk manifest as JSON+ newSource = newSource.replace(+ /"__SDK_CHUNK_MANIFEST__"/g,+ JSON.stringify(manifest),+ );++ // Inline the runtime chunk source at the end of the bootstrap.+ // The runtime sets up __webpack_require__ and the chunk registry+ // that other chunks register into when they load.+ if (runtimeSource) {+ newSource +=+ "\n// --- Inlined runtime chunk ---\n" + runtimeSource;+ }++ compilation.updateAsset(+ bootstrapKey,+ new rspack.sources.RawSource(newSource),+ );+ },+ );+ },+ );+ },+ },shouldAnalyzeBundles &&new BundleAnalyzerPlugin({analyzerMode: "static",reportFilename: BUILD_PATH + "/dist/report.html",}),- CopyJsFromTmpDirectoryPlugin({- fileName: SDK_BUNDLE_FILENAME,- tmpPath: TMP_BUILD_PATH,- outputPath: path.join(BUILD_PATH, SDK_BUNDLE_PATH),- copySourceMap: true,- cleanupInDevMode: false,- }),].filter(Boolean),};diff --git a/src/metabase/server/middleware/embedding_sdk_bundle.clj b/src/metabase/server/middleware/embedding_sdk_bundle.cljindex 20a7c2180ab..30ca500ef12 100644--- a/src/metabase/server/middleware/embedding_sdk_bundle.clj+++ b/src/metabase/server/middleware/embedding_sdk_bundle.clj@@ -7,10 +7,12 @@(set! *warn-on-reflection* true)-(def ^:private bundle-resource "frontend_client/app/embedding-sdk.js")+(def ^:private bundle-resource "frontend_client/app/embedding-sdk/legacy/embedding-sdk.js")+(def ^:private bootstrap-resource "frontend_client/app/embedding-sdk/chunks/embedding-sdk.js")(def ^:private content-type "application/javascript; charset=UTF-8")-(def ^:private default-cache-header {"Cache-Control" "public, max-age=60"})-(def ^:private no-store-cache-header {"Cache-Control" "no-store"})+(def ^:private default-cache-header {"Cache-Control" "public, max-age=60"})+(def ^:private far-future-cache-header {"Cache-Control" "public, max-age=31536000, immutable"})+(def ^:private no-store-cache-header {"Cache-Control" "no-store"})(def ^:private vary-accept-encoding-header {"Vary" "Accept-Encoding"})(defn- not-found []@@ -25,17 +27,50 @@(defn- serve-for-prod [base request](let [resp (lib.etag-cache/with-etag base request)](cond-> resp- true (update :headers merge- default-cache-header- vary-accept-encoding-header)+ true (update :headers merge+ default-cache-header+ vary-accept-encoding-header)(= 200 (:status resp)) (response/content-type content-type))))+(defn- serve-resource-handler+ "Serve a JS resource with ETag + 60s caching in prod, no-store in dev."+ [resource]+ (fn [request]+ (let [base (response/resource-response resource)]+ (cond+ (nil? base) (not-found)+ config/is-prod? (serve-for-prod base request)+ :else (serve-for-dev base)))))+(defn serve-bundle-handler- "Serve /app/embedding-sdk.js. Prod: ETag + 60s caching (200/304). Dev: no-store."+ "Serve /app/embedding-sdk.js.+ When `packageVersion` query param is present and `useLegacyMonolithicBundle`+ is not `true`, serve the bootstrap entry (chunked loading with parallel auth).+ Otherwise, serve the legacy monolithic bundle (backward compat for old packages).+ Prod: ETag + 60s caching (200/304). Dev: no-store."[](fn [request]- (let [base (response/resource-response bundle-resource)]- (cond- (nil? base) (not-found)- config/is-prod? (serve-for-prod base request)- :else (serve-for-dev base)))))+ (let [package-version (get-in request [:query-params "packageVersion"])+ use-legacy (get-in request [:query-params "useLegacyMonolithicBundle"])+ use-bootstrap? (and (some? package-version)+ (not= "true" use-legacy))+ resource (if use-bootstrap?+ bootstrap-resource+ bundle-resource)]+ ((serve-resource-handler resource) request))))++(defn serve-chunk-handler+ "Serve /app/embedding-sdk/chunks/:filename — split chunks loaded by the bootstrap.+ Chunk filenames contain content hashes, so we always use far-future caching.+ Path traversal is prevented by the route regex `#\"[^/]+\\.js\"` which only allows+ leaf filenames ending in .js (no slashes). Additionally, Java's class loader+ resource-response returns nil for paths containing '..'"+ [filename]+ (let [resource (str "frontend_client/app/embedding-sdk/chunks/" filename)]+ (fn [_request]+ (let [base (response/resource-response resource)]+ (if (nil? base)+ (not-found)+ (-> base+ (update :headers merge far-future-cache-header vary-accept-encoding-header)+ (response/content-type content-type)))))))diff --git a/src/metabase/server/routes.clj b/src/metabase/server/routes.cljindex f54499b63fe..a5689268141 100644--- a/src/metabase/server/routes.clj+++ b/src/metabase/server/routes.clj@@ -71,6 +71,10 @@(defroutes ^:private static-files-handler(GET "/embedding-sdk.js" request((mw.embedding-sdk-bundle/serve-bundle-handler) request))+ ;; All SDK chunks live in embedding-sdk/chunks/ — filenames contain content+ ;; hashes, so we serve them with far-future immutable cache headers.+ (GET ["/embedding-sdk/chunks/:filename" :filename #"[^/]+\.js"] [filename :as request]+ ((mw.embedding-sdk-bundle/serve-chunk-handler filename) request));; fall back to serving _all_ other files under /app(route/resources "/" {:root "frontend_client/app"})diff --git a/test/metabase/server/middleware/embedding_sdk_bundle_test.clj b/test/metabase/server/middleware/embedding_sdk_bundle_test.cljindex 202c01d0ace..e36baef06b6 100644--- a/test/metabase/server/middleware/embedding_sdk_bundle_test.clj+++ b/test/metabase/server/middleware/embedding_sdk_bundle_test.clj@@ -1,5 +1,6 @@(ns metabase.server.middleware.embedding-sdk-bundle-test(:require+ [clojure.string :as str][clojure.test :refer :all][metabase.config.core :as config][metabase.server.lib.etag-cache :as lib.etag-cache]@@ -9,13 +10,13 @@(set! *warn-on-reflection* true)(def ^:private cache-header "public, max-age=60")+(def ^:private far-future-cache-header "public, max-age=31536000, immutable")(def ^:private js-ct "application/javascript; charset=UTF-8")(deftest serve-bundle-handler-prod-returns-304-and-adds-cache-header- (testing "Prod + ETag match → 304 with Cache-Control, ETag, Vary, TAO; no Content-Type"+ (testing "Prod + ETag match → 304 with Cache-Control, ETag, Vary; no Content-Type"(with-redefs [config/is-prod? trueresponse/resource-response (constantly {:status 200 :headers {} :body "dummy"})- ;; with-etag returns a 304 response with an ETaglib.etag-cache/with-etag (fn [_base _req]{:status 304:headers {"ETag" "\"abc\""}@@ -30,10 +31,9 @@(is (nil? (get-in resp [:headers "Content-Type"])) "304 should not include Content-Type")))))(deftest serve-bundle-handler-prod-returns-200-and-adds-cache-and-content-type- (testing "Prod + ETag miss → 200 with Cache-Control, ETag, Content-Type, Vary, TAO"+ (testing "Prod + ETag miss → 200 with Cache-Control, ETag, Content-Type, Vary"(with-redefs [config/is-prod? trueresponse/resource-response (constantly {:status 200 :headers {} :body "dummy"})- ;; with-etag returns a 200 response with an ETag appliedlib.etag-cache/with-etag (fn [base _req](update base :headers assoc "ETag" "\"abc\""))](let [handler (mw.embedding-sdk-bundle/serve-bundle-handler)@@ -43,30 +43,109 @@(is (= "\"abc\"" (get-in resp [:headers "ETag"])))(is (= js-ct (get-in resp [:headers "Content-Type"])))(is (= "Accept-Encoding" (get-in resp [:headers "Vary"])))- (is (= "dummy" (:body resp))))))+ (is (= "dummy" (:body resp)))))))- (deftest serve-bundle-handler-dev-skips-etag-and-sets-no-store- (testing "Dev skips with-etag and sets no-store + Content-Type, no prod-only headers"+(deftest serve-bundle-handler-dev-skips-etag-and-sets-no-store+ (testing "Dev skips with-etag and sets no-store + Content-Type, no prod-only headers"+ (with-redefs [config/is-prod? false+ response/resource-response (constantly {:status 200 :headers {} :body "dummy"})+ lib.etag-cache/with-etag (fn [& _]+ (throw (ex-info "with-etag should not be called in dev" {})))]+ (let [handler (mw.embedding-sdk-bundle/serve-bundle-handler)+ resp (handler {:headers {}})]+ (is (= 200 (:status resp)))+ (is (= "no-store" (get-in resp [:headers "Cache-Control"])))+ (is (= js-ct (get-in resp [:headers "Content-Type"])))+ (is (nil? (get-in resp [:headers "Vary"])))+ (is (= "dummy" (:body resp)))))))++(deftest serve-bundle-handler-404-propagates+ (testing "Missing resource → 404 with no-store; no prod-only headers"+ (with-redefs [config/is-prod? true+ response/resource-response (constantly nil)+ lib.etag-cache/with-etag (fn [& args] (throw (ex-info "Not expected for 404" {:args args})))]+ (let [handler (mw.embedding-sdk-bundle/serve-bundle-handler)+ resp (handler {:headers {}})]+ (is (= 404 (:status resp)))+ (is (= "no-store" (get-in resp [:headers "Cache-Control"])))+ (is (nil? (get-in resp [:headers "Vary"])))))))++;; -- Bundle routing: packageVersion triggers bootstrap, absence → legacy --++(deftest serve-bundle-handler-routes-by-query-param+ (testing "No query params (old package) → serves legacy resource"+ (let [requested-resource (atom nil)](with-redefs [config/is-prod? false- response/resource-response (constantly {:status 200 :headers {} :body "dummy"})- ;; If it were called in dev, we’d see this exception- lib.etag-cache/with-etag (fn [& _]- (throw (ex-info "with-etag should not be called in dev" {})))]+ response/resource-response (fn [resource]+ (reset! requested-resource resource)+ {:status 200 :headers {} :body "legacy-js"})](let [handler (mw.embedding-sdk-bundle/serve-bundle-handler)resp (handler {:headers {}})](is (= 200 (:status resp)))- (is (= "no-store" (get-in resp [:headers "Cache-Control"])))- (is (= js-ct (get-in resp [:headers "Content-Type"])))- (is (nil? (get-in resp [:headers "Vary"])))- (is (= "dummy" (:body resp))))))+ (is (str/includes? @requested-resource "legacy/"))))))++ (testing "packageVersion present → serves bootstrap resource"+ (let [requested-resource (atom nil)]+ (with-redefs [config/is-prod? false+ response/resource-response (fn [resource]+ (reset! requested-resource resource)+ {:status 200 :headers {} :body "bootstrap-js"})]+ (let [handler (mw.embedding-sdk-bundle/serve-bundle-handler)+ resp (handler {:headers {}+ :query-params {"packageVersion" "0.59.0"}})]+ (is (= 200 (:status resp)))+ (is (str/includes? @requested-resource "chunks/"))))))++ (testing "packageVersion + useLegacyMonolithicBundle=true → serves legacy resource"+ (let [requested-resource (atom nil)]+ (with-redefs [config/is-prod? false+ response/resource-response (fn [resource]+ (reset! requested-resource resource)+ {:status 200 :headers {} :body "legacy-js"})]+ (let [handler (mw.embedding-sdk-bundle/serve-bundle-handler)+ resp (handler {:headers {}+ :query-params {"packageVersion" "0.59.0"+ "useLegacyMonolithicBundle" "true"}})]+ (is (= 200 (:status resp)))+ (is (str/includes? @requested-resource "legacy/")))))))++;; -- Chunk handler (dynamic filenames with content hashes) --++(deftest serve-chunk-handler-returns-far-future-cache+ (testing "Chunk handler always returns far-future cache + Content-Type + Vary"+ (with-redefs [response/resource-response (constantly {:status 200 :headers {} :body "chunk-js"})]+ (let [handler (mw.embedding-sdk-bundle/serve-chunk-handler "embedding-sdk-chunk-runtime.a1b2c3d4.js")+ resp (handler {:headers {}})]+ (is (= 200 (:status resp)))+ (is (= far-future-cache-header (get-in resp [:headers "Cache-Control"])))+ (is (= js-ct (get-in resp [:headers "Content-Type"])))+ (is (= "Accept-Encoding" (get-in resp [:headers "Vary"]))))))++ (testing "Missing chunk resource → 404"+ (with-redefs [response/resource-response (constantly nil)]+ (let [handler (mw.embedding-sdk-bundle/serve-chunk-handler "embedding-sdk-chunk-nonexistent.js")+ resp (handler {:headers {}})]+ (is (= 404 (:status resp)))+ (is (= "no-store" (get-in resp [:headers "Cache-Control"])))))))++;; -- Path traversal protection --- (deftest serve-bundle-handler-404-propagates- (testing "Missing resource → 404 with no-store; no prod-only headers"- (with-redefs [config/is-prod? true- response/resource-response (constantly nil)- lib.etag-cache/with-etag (fn [& args] (throw (ex-info "Not expected for 404" {:args args})))]- (let [handler (mw.embedding-sdk-bundle/serve-bundle-handler)+(deftest serve-chunk-handler-traversal-returns-404+ (testing "traversal filenames return 404 even when the target file exists"+ ;; Place a real .js file on the classpath (inside resources/) and verify+ ;; that path traversal from the chunks directory cannot reach it.+ (let [tmp-file (java.io.File. "resources" "traversal-test-secret.js")]+ (try+ (spit tmp-file "should-not-be-served")+ ;; Sanity: the file IS reachable via resource-response directly+ (is (some? (response/resource-response "traversal-test-secret.js"))+ "Sanity check: temp file is on the classpath")+ ;; None of these traversal filenames should be able to reach it+ (doseq [filename ["../../../../traversal-test-secret.js"+ "../some/thing" "/etc/passwd" "." ".."]]+ (let [handler (mw.embedding-sdk-bundle/serve-chunk-handler filename)resp (handler {:headers {}})]- (is (= 404 (:status resp)))- (is (= "no-store" (get-in resp [:headers "Cache-Control"])))- (is (nil? (get-in resp [:headers "Vary"])))))))))+ (is (= 404 (:status resp))+ (str "Expected 404 for filename: " (pr-str filename)))))+ (finally+ (.delete tmp-file))))))