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: show an error instead on the SDK on an unsupported React (#82435)
Mahatthana (Kelvin) Nomsawadi08c63a6b0fd3
diff --git a/e2e/runner/run_cypress_local.ts b/e2e/runner/run_cypress_local.tsindex f23550e095c..b01bbace9bb 100644--- a/e2e/runner/run_cypress_local.ts+++ b/e2e/runner/run_cypress_local.ts@@ -122,6 +122,7 @@ const init = async () => {await runCypress({configFile: "e2e/support/cypress-embedding-sdk-component-test.config.js",testingType: "component",+ ...userOverrides,});}diff --git a/e2e/test-component/scenarios/embedding-sdk/unsupported-react-version.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/unsupported-react-version.cy.spec.tsxnew file mode 100644index 00000000000..f64258a0c6f--- /dev/null+++ b/e2e/test-component/scenarios/embedding-sdk/unsupported-react-version.cy.spec.tsx@@ -0,0 +1,159 @@+import {+ StaticQuestion,+ useMetabaseAuthStatus,+ useMetabot,+} from "@metabase/embedding-sdk-react";+import { DataAppDevProvider } from "@metabase/embedding-sdk-react/data-app-dev";+import * as React from "react";++import { ORDERS_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";+import {+ DEFAULT_SDK_AUTH_PROVIDER_CONFIG,+ getSdkBundleScriptElement,+ mountSdk,+ mountSdkContent,+} from "e2e/support/helpers/embedding-sdk-component-testing";+import { signInAsAdminAndEnableEmbeddingSdk } from "e2e/support/helpers/embedding-sdk-testing";+import { mockAuthProviderAndJwtSignIn } from "e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers";+import { deleteConflictingCljsGlobals } from "metabase/embedding-sdk/test/delete-conflicting-cljs-globals";++// MINIMUM_SUPPORTED_REACT_MAJOR_VERSION in host-react-version.ts, which is what+// the check compares against. When that moves to 19, change this to 19:+// the spec then fakes a React 18 host and expects the React 19 message. Until+// someone does, every assertion here is wrong and the spec fails.+const MINIMUM_SUPPORTED_REACT_MAJOR = 18;++const UNSUPPORTED_HOST_REACT_MAJOR = MINIMUM_SUPPORTED_REACT_MAJOR - 1;++const UNSUPPORTED_REACT_ERROR = `The Metabase modular embedding SDK requires React ${MINIMUM_SUPPORTED_REACT_MAJOR} or newer, but this application is running React ${UNSUPPORTED_HOST_REACT_MAJOR}. Upgrade your application to React ${MINIMUM_SUPPORTED_REACT_MAJOR} to display embedded content.`;++// Component tests keep the page between tests, so each test has to load the+// bundle again: it reads the host React and logs the error only once per load.+const sdkBundleCleanup = () => {+ getSdkBundleScriptElement()?.remove();+ // Unjustified type cast. FIXME+ delete (window as any).METABASE_EMBEDDING_SDK_BUNDLE;+ // Unjustified type cast. FIXME+ delete (window as any).METABASE_PROVIDER_PROPS_STORE;+ // Unjustified type cast. FIXME+ delete (window as any).METABASE_EMBEDDING_SDK_AUTH_STATE;+ // Unjustified type cast. FIXME+ delete (window as any).webpackChunkembedding_sdk_bundle;+ // Unjustified type cast. FIXME+ delete (window as any).webpackChunkembedding_sdk_legacy;+ deleteConflictingCljsGlobals();+};++describe("scenarios > embedding-sdk > unsupported-react-version", () => {+ beforeEach(() => {+ sdkBundleCleanup();++ signInAsAdminAndEnableEmbeddingSdk();++ cy.signOut();++ mockAuthProviderAndJwtSignIn();++ cy.window().then((win) => {+ cy.spy(win.console, "error").as("consoleError");++ // Only the version string is faked, standing in for any React older+ // than the SDK supports: the bundle reads the host's React from this+ // global when it loads, while the test keeps rendering with the real one.+ Object.assign(win, {+ METABASE_REACT: {+ ...React,+ version: `${UNSUPPORTED_HOST_REACT_MAJOR}.0.0`,+ },+ });+ });+ });++ it("shows an error in place of each SDK component and keeps the host app rendering", () => {+ mountSdkContent(+ <>+ <div data-testid="host-app-content">host app content</div>+ <StaticQuestion questionId={ORDERS_QUESTION_ID} />+ <StaticQuestion questionId={ORDERS_QUESTION_ID} />+ </>,+ // The SDK components never load, so there is no user request to wait on.+ { waitForUser: false },+ );++ cy.findAllByTestId("sdk-unsupported-react-version-error")+ .should("have.length", 2)+ .each((errorBox) => {+ cy.wrap(errorBox).should("have.text", UNSUPPORTED_REACT_ERROR);+ });+ cy.findByTestId("host-app-content").should("be.visible");+ cy.get("[data-cy-root]").findByText("Product ID").should("not.exist");++ assertUnsupportedReactErrorLoggedOnce();+ });++ // A hooks-only host renders nothing, so the console error is what says the+ // bundle loaded and ran the check, and the hook's value is what says the+ // entry behind it was swapped out (see sdk-bundle-exports.ts).+ it("does not start the SDK, so useMetabaseAuthStatus stays uninitialized", () => {+ mountSdkContent(<AuthStatus />, { waitForUser: false });++ assertUnsupportedReactErrorLoggedOnce();++ cy.findByTestId("host-hook-value").should("have.text", "uninitialized");+ cy.findByTestId("sdk-unsupported-react-version-error").should("not.exist");+ });++ it("does not render the Metabot subscriber, so useMetabot stays empty", () => {+ mountSdkContent(<Metabot />, { waitForUser: false });++ assertUnsupportedReactErrorLoggedOnce();++ cy.findByTestId("host-hook-value").should("have.text", "none");+ cy.findByTestId("sdk-unsupported-react-version-error").should("not.exist");+ });++ // A data app is built as its own Vite project and previewed with `npm run+ // dev`, so the React it runs is its author's while the bundle comes from the+ // instance. DataAppDevProvider is what that dev server mounts; a deployed+ // data app runs Metabase's own React and cannot mismatch.+ it("replaces a data app in dev mode with the error", () => {+ mountSdk(+ <DataAppDevProvider+ appSlug="unsupported-react-version"+ authConfig={DEFAULT_SDK_AUTH_PROVIDER_CONFIG}+ >+ <div data-testid="data-app-content">data app content</div>+ </DataAppDevProvider>,+ );++ assertUnsupportedReactErrorLoggedOnce();++ cy.findByTestId("sdk-unsupported-react-version-error").should(+ "have.text",+ UNSUPPORTED_REACT_ERROR,+ );+ cy.findByTestId("data-app-content").should("not.exist");+ });+});++function AuthStatus() {+ const authStatus = useMetabaseAuthStatus();++ return <div data-testid="host-hook-value">{authStatus?.status}</div>;+}++function Metabot() {+ const metabot = useMetabot();++ return <div data-testid="host-hook-value">{metabot ? "ready" : "none"}</div>;+}++function assertUnsupportedReactErrorLoggedOnce() {+ cy.get<sinon.SinonSpy>("@consoleError").should((consoleError) => {+ const unsupportedReactErrors = consoleError.args.filter(+ ([message]) => message === UNSUPPORTED_REACT_ERROR,+ );++ expect(unsupportedReactErrors).to.have.length(1);+ });+}diff --git a/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/jwt.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/jwt.unit.spec.tsxindex 81dfeb5ca80..d65462716eb 100644--- a/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/jwt.unit.spec.tsx+++ b/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/jwt.unit.spec.tsx@@ -27,6 +27,7 @@ import { setup as baseSetup } from "./setup";// Jest runs React 18 on localhost, which shows the React 18 warning banner.// Mock React 19 so the spec only sees the usage problems it tests.jest.mock("embedding-sdk-bundle/lib/host-react-version", () => ({+ ...jest.requireActual("embedding-sdk-bundle/lib/host-react-version"),getHostReactMajorVersion: () => 19,}));diff --git a/frontend/build/embedding-sdk/constants/external-dependencies.js b/frontend/build/embedding-sdk/constants/external-dependencies.jsindex 96a76c55f2b..50bfd5bee97 100644--- a/frontend/build/embedding-sdk/constants/external-dependencies.js+++ b/frontend/build/embedding-sdk/constants/external-dependencies.js@@ -1,5 +1,6 @@/**- * The SDK should never bundle React itself+ * The SDK bundle never includes React. Each import below resolves at runtime to+ * the host app's React, which the SDK package puts on these globals.** @type {Readonly<{* react: "METABASE_REACT";diff --git a/frontend/src/embedding-sdk-bundle/components/private/MetabotSubscriber/MetabotSubscriber.tsx b/frontend/src/embedding-sdk-bundle/components/private/MetabotSubscriber/MetabotSubscriber.tsxindex 7bd47e76cdd..08e2c95e041 100644--- a/frontend/src/embedding-sdk-bundle/components/private/MetabotSubscriber/MetabotSubscriber.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/MetabotSubscriber/MetabotSubscriber.tsx@@ -2,6 +2,10 @@ import { useEffect } from "react";import { METABOT_SDK_EE_PLUGIN } from "embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion";import { useMetabot } from "embedding-sdk-bundle/hooks/public/use-metabot";+import {+ isHostReactVersionSupported,+ useLogUnsupportedReactVersion,+} from "embedding-sdk-bundle/lib/host-react-version";import type { SdkStore } from "embedding-sdk-bundle/store/types";import { publishMetabotState } from "embedding-sdk-shared/lib/metabot-state-channel";import { MetabaseReduxProvider } from "metabase/redux";@@ -19,10 +23,20 @@ const MetabotStatePublisher = () => {return null;};-export const MetabotSubscriber = ({ store }: Props) => (+const MetabotSubscriberOnSupportedReact = ({ store }: Props) => (<MetabaseReduxProvider store={store}><METABOT_SDK_EE_PLUGIN.MetabotProvider><MetabotStatePublisher /></METABOT_SDK_EE_PLUGIN.MetabotProvider></MetabaseReduxProvider>);++const UnsupportedReactVersionMetabotSubscriber = () => {+ useLogUnsupportedReactVersion();++ return null;+};++export const MetabotSubscriber = isHostReactVersionSupported()+ ? MetabotSubscriberOnSupportedReact+ : UnsupportedReactVersionMetabotSubscriber;diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkThemeProvider.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkThemeProvider.tsxindex c25d5abb7c1..6556ebbd993 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkThemeProvider.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkThemeProvider.tsx@@ -2,8 +2,10 @@import { Global } from "@emotion/react";import { useContext, useId, useMemo } from "react";+import { UnsupportedReactVersionError } from "embedding-sdk-bundle/components/private/UnsupportedReactVersionError/UnsupportedReactVersionError";import { DEFAULT_FONT } from "embedding-sdk-bundle/config";import { useEmbeddingThemeOverride } from "embedding-sdk-bundle/hooks/private/use-embedding-theme-override";+import { isHostReactVersionSupported } from "embedding-sdk-bundle/lib/host-react-version";import type { SdkStore } from "embedding-sdk-bundle/store/types";import { EnsureSingleInstance } from "embedding-sdk-shared/components/EnsureSingleInstance/EnsureSingleInstance";import {@@ -98,11 +100,19 @@ export const SdkThemeProviderWithStore = ({store,theme,children,-}: Props & { store: SdkStore }) => (- <MetabaseReduxProvider store={store}>- <SdkThemeProvider theme={theme}>{children}</SdkThemeProvider>- </MetabaseReduxProvider>-);+}: Props & { store: SdkStore }) => {+ // The data-app dev preview is the whole page, so the error replaces it+ // rather than rendering the app without its providers.+ if (!isHostReactVersionSupported()) {+ return <UnsupportedReactVersionError />;+ }++ return (+ <MetabaseReduxProvider store={store}>+ <SdkThemeProvider theme={theme}>{children}</SdkThemeProvider>+ </MetabaseReduxProvider>+ );+};function GlobalSdkCssVariables({forceDynamicBrandRamp,diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemDisplay-simple-embedding.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemDisplay-simple-embedding.unit.spec.tsxindex 7bfd173547f..c4cf686752e 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemDisplay-simple-embedding.unit.spec.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemDisplay-simple-embedding.unit.spec.tsx@@ -29,7 +29,11 @@ jest.mock("metabase/visualizations/register", () => ({// Jest runs React 18 on localhost, which shows the React 18 warning banner.// Each test sets the host React major version instead.+// Without the real module behind it, isHostReactVersionSupported is undefined+// here, and anything that loads the SDK hooks throws: each of them calls that+// check when its module loads.jest.mock("embedding-sdk-bundle/lib/host-react-version", () => ({+ ...jest.requireActual("embedding-sdk-bundle/lib/host-react-version"),getHostReactMajorVersion: jest.fn(),}));diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemDisplay.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemDisplay.unit.spec.tsxindex 25b41b696df..4f7f9f5f92e 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemDisplay.unit.spec.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemDisplay.unit.spec.tsx@@ -39,7 +39,11 @@ jest.mock("metabase/visualizations/register", () => ({// Jest runs React 18 on localhost, which shows the React 18 warning banner.// Each test sets the host React major version instead.+// Without the real module behind it, isHostReactVersionSupported is undefined+// here, and anything that loads the SDK hooks throws: each of them calls that+// check when its module loads.jest.mock("embedding-sdk-bundle/lib/host-react-version", () => ({+ ...jest.requireActual("embedding-sdk-bundle/lib/host-react-version"),getHostReactMajorVersion: jest.fn(),}));diff --git a/frontend/src/embedding-sdk-bundle/components/private/UnsupportedReactVersionError/UnsupportedReactVersionError.tsx b/frontend/src/embedding-sdk-bundle/components/private/UnsupportedReactVersionError/UnsupportedReactVersionError.tsxnew file mode 100644index 00000000000..ea53e8f0ffb--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/private/UnsupportedReactVersionError/UnsupportedReactVersionError.tsx@@ -0,0 +1,35 @@+import { useEffect } from "react";++import {+ getUnsupportedReactVersionMessage,+ logUnsupportedReactVersionOnce,+} from "embedding-sdk-bundle/lib/host-react-version";+import { colors } from "metabase/ui/colors/colors";++// Rendered in place of the SDK when the host React is too old for it, so it+// must stay plain React and DOM: nothing here may need the newer React.+export function UnsupportedReactVersionError() {+ useEffect(() => {+ logUnsupportedReactVersionOnce();+ }, []);++ return (+ <div+ role="alert"+ data-testid="sdk-unsupported-react-version-error"+ style={{+ display: "flex",+ alignItems: "center",+ padding: "1.25rem 1rem",+ background: colors["background_surface-error-subtle"],+ color: colors["text-secondary"],+ border: `0.5px solid ${colors["feedback-negative-strong"]}`,+ borderRadius: "12px",+ textAlign: "center",+ lineHeight: "1.4rem",+ }}+ >+ {getUnsupportedReactVersionMessage()}+ </div>+ );+}diff --git a/frontend/src/embedding-sdk-bundle/components/private/UnsupportedReactVersionError/UnsupportedReactVersionError.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/private/UnsupportedReactVersionError/UnsupportedReactVersionError.unit.spec.tsxnew file mode 100644index 00000000000..900266195ed--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/private/UnsupportedReactVersionError/UnsupportedReactVersionError.unit.spec.tsx@@ -0,0 +1,30 @@+import { render, screen } from "__support__/ui";++import { UnsupportedReactVersionError } from "./UnsupportedReactVersionError";++// React 17 because MINIMUM_SUPPORTED_REACT_MAJOR_VERSION in host-react-version.ts+// is 18. When that moves to 19, fake 18 here and update the message.+jest.mock("react", () => ({+ ...jest.requireActual("react"),+ version: "17.0.2",+}));++const UNSUPPORTED_REACT_MESSAGE =+ "The Metabase modular embedding SDK requires React 18 or newer, but this application is running React 17. Upgrade your application to React 18 to display embedded content.";++describe("UnsupportedReactVersionError", () => {+ it("shows the unsupported React message and logs it to the console", () => {+ const consoleError = jest+ .spyOn(console, "error")+ .mockImplementation(() => {});++ render(<UnsupportedReactVersionError />);++ expect(screen.getByRole("alert")).toHaveTextContent(+ UNSUPPORTED_REACT_MESSAGE,+ );+ expect(consoleError).toHaveBeenCalledWith(UNSUPPORTED_REACT_MESSAGE);++ consoleError.mockRestore();+ });+});diff --git a/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsx b/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsxindex a38eb8919ca..2aa5eda08e4 100644--- a/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsx@@ -9,6 +9,7 @@ import { useArePluginsReady } from "embedding-sdk-bundle/hooks/private/use-are-pimport { useInitDataInternal } from "embedding-sdk-bundle/hooks/private/use-init-data";import { useNormalizeComponentProviderProps } from "embedding-sdk-bundle/hooks/private/use-normalize-component-provider-props";import { useSdkCustomLoader } from "embedding-sdk-bundle/hooks/private/use-sdk-custom-loader";+import { isHostReactVersionSupported } from "embedding-sdk-bundle/lib/host-react-version";import { getSdkStore } from "embedding-sdk-bundle/store";import {setErrorComponent,@@ -36,6 +37,7 @@ import { SCOPED_CSS_RESET } from "../../private/PublicComponentStylesWrapper";import { SdkFontsGlobalStyles } from "../../private/SdkGlobalFontsStyles";import { PortalContainer } from "../../private/SdkPortalContainer";import { SdkUsageProblemDisplay } from "../../private/SdkUsageProblem";+import { UnsupportedReactVersionError } from "../../private/UnsupportedReactVersionError/UnsupportedReactVersionError";import { METABOT_SDK_EE_PLUGIN } from "../MetabotQuestion/MetabotQuestion";export type ComponentProviderInternalProps = ComponentProviderProps & {@@ -206,6 +208,12 @@ export const ComponentProvider = memo(function ComponentProvider({reduxStoreRef.current = props.reduxStore ?? getSdkStore();}+ // Bail out before any provider mounts: a too-old host React would throw+ // deep inside them and take the host app down with it.+ if (!isHostReactVersionSupported()) {+ return <UnsupportedReactVersionError />;+ }+return (<MetabaseReduxProvider store={reduxStoreRef.current}><METABOT_SDK_EE_PLUGIN.MetabotProvider>diff --git a/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.unit.spec.tsxindex 61cb85a24bb..5a6c817a59d 100644--- a/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.unit.spec.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.unit.spec.tsx@@ -7,11 +7,52 @@ jest.mock("embedding-sdk-bundle/hooks/private/use-init-data", () => ({useInitDataInternal: jest.fn(),}));+jest.mock("embedding-sdk-bundle/lib/host-react-version", () => ({+ ...jest.requireActual("embedding-sdk-bundle/lib/host-react-version"),+ isHostReactVersionSupported: jest.fn(() => true),+}));++import { render, screen } from "__support__/ui";import { useInitSdkTracker } from "embedding-sdk-bundle/analytics/tracker";+import { isHostReactVersionSupported } from "embedding-sdk-bundle/lib/host-react-version";import { renderWithSDKProviders } from "embedding-sdk-bundle/test/__support__/ui";+import { ComponentProvider } from "./ComponentProvider";+const mockUseInitSdkTracker = jest.mocked(useInitSdkTracker);+describe("ComponentProvider — unsupported host React", () => {+ let consoleError: jest.SpyInstance;++ beforeEach(() => {+ consoleError = jest.spyOn(console, "error").mockImplementation(() => {});+ });++ afterEach(() => {+ consoleError.mockRestore();+ jest.mocked(isHostReactVersionSupported).mockReturnValue(true);+ });++ it("renders the unsupported React error instead of the SDK", () => {+ jest.mocked(isHostReactVersionSupported).mockReturnValue(false);++ // renderWithSDKProviders mounts ComponentProviderInternal, below the guard.+ render(+ <ComponentProvider+ authConfig={{ metabaseInstanceUrl: "https://metabase.example.com" }}+ >+ <div>sdk content</div>+ </ComponentProvider>,+ );++ expect(+ screen.getByTestId("sdk-unsupported-react-version-error"),+ ).toBeInTheDocument();+ expect(screen.queryByText("sdk content")).not.toBeInTheDocument();+ expect(mockUseInitSdkTracker).not.toHaveBeenCalled();+ });+});+describe("ComponentProvider — tracker wiring", () => {beforeEach(() => {jest.clearAllMocks();diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.tsindex 7e8dc23b948..e222f509656 100644--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.ts+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.ts@@ -2,6 +2,10 @@ import { useEffect, useSyncExternalStore } from "react";import { useMount } from "react-use";import _ from "underscore";+import {+ isHostReactVersionSupported,+ useLogUnsupportedReactVersion,+} from "embedding-sdk-bundle/lib/host-react-version";import {ensureMetabaseProviderPropsStore,useMetabaseProviderPropsStore,@@ -69,7 +73,7 @@ interface InitDataLoaderParameters {isLocalHost?: boolean;}-export const useInitData = () => {+const useInitDataOnSupportedReact = () => {const {state: { props, internalProps },} = useMetabaseProviderPropsStore();@@ -101,6 +105,10 @@ export const useInitData = () => {});};+export const useInitData = isHostReactVersionSupported()+ ? useInitDataOnSupportedReact+ : useLogUnsupportedReactVersion;+export const useInitDataInternal = ({reduxStore,isGuestEmbed,diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-log-version-info/use-log-version-info-unsupported-react.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/hooks/private/use-log-version-info/use-log-version-info-unsupported-react.unit.spec.tsxnew file mode 100644index 00000000000..d2a5f10b376--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-log-version-info/use-log-version-info-unsupported-react.unit.spec.tsx@@ -0,0 +1,49 @@+import { renderHook } from "@testing-library/react";++import { getBuildInfo } from "embedding-sdk-shared/lib/get-build-info";++import { useLogVersionInfo } from "./use-log-version-info";++// The hook is picked when its module loads, so the check is faked rather+// than the React version: the real module cannot be re-loaded per test.+jest.mock("embedding-sdk-bundle/lib/host-react-version", () => ({+ ...jest.requireActual("embedding-sdk-bundle/lib/host-react-version"),+ isHostReactVersionSupported: () => false,+}));++jest.mock("embedding-sdk-shared/lib/get-build-info", () => ({+ getBuildInfo: jest.fn(),+}));++const UNSUPPORTED_REACT_MESSAGE_START =+ "The Metabase modular embedding SDK requires React";++describe("useLogVersionInfo on an unsupported host React", () => {+ let consoleWarnSpy: jest.SpyInstance;+ let consoleErrorSpy: jest.SpyInstance;++ beforeEach(() => {+ consoleWarnSpy = jest.spyOn(console, "warn").mockImplementation(() => {});+ consoleErrorSpy = jest.spyOn(console, "error").mockImplementation(() => {});++ // Versions the real hook warns about, so silence here means it never ran.+ // Its own spec covers the warning it prints on a supported React.+ // Unjustified type cast. FIXME+ (getBuildInfo as jest.Mock)+ .mockReturnValueOnce({ version: "0.55.10" })+ .mockReturnValueOnce({ version: "v1.52.0" });+ });++ afterEach(() => {+ jest.restoreAllMocks();+ });++ it("reports the React version instead of the SDK versions", () => {+ renderHook(() => useLogVersionInfo());++ expect(consoleWarnSpy).not.toHaveBeenCalled();+ expect(consoleErrorSpy).toHaveBeenCalledWith(+ expect.stringContaining(UNSUPPORTED_REACT_MESSAGE_START),+ );+ });+});diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-log-version-info/use-log-version-info.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-log-version-info/use-log-version-info.tsindex 68bc8e3fb81..3b5d3f2a0df 100644--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-log-version-info/use-log-version-info.ts+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-log-version-info/use-log-version-info.ts@@ -1,7 +1,11 @@import { useEffect } from "react";import { getIsLocalhost } from "embedding-sdk-bundle/lib/get-is-localhost";-import { getHostReactMajorVersion } from "embedding-sdk-bundle/lib/host-react-version";+import {+ getHostReactMajorVersion,+ isHostReactVersionSupported,+ useLogUnsupportedReactVersion,+} from "embedding-sdk-bundle/lib/host-react-version";import { printUsageProblemToConsole } from "embedding-sdk-bundle/lib/print-usage-problem";import { useMetabaseProviderPropsStore } from "embedding-sdk-bundle/lib/provider-props-store";import { toWarning } from "embedding-sdk-bundle/lib/usage-problem";@@ -12,7 +16,7 @@ import {isSdkPackageCompatibleWithSdkBundle,} from "embedding-sdk-shared/lib/version-utils";-export const useLogVersionInfo = () => {+const useLogVersionInfoOnSupportedReact = () => {const {state: { props },} = useMetabaseProviderPropsStore();@@ -66,3 +70,7 @@ export const useLogVersionInfo = () => {}}, []);};++export const useLogVersionInfo = isHostReactVersionSupported()+ ? useLogVersionInfoOnSupportedReact+ : useLogUnsupportedReactVersion;diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-log-version-info/use-log-version-info.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/hooks/private/use-log-version-info/use-log-version-info.unit.spec.tsxindex 56ef5cd1a31..d257d9c78ab 100644--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-log-version-info/use-log-version-info.unit.spec.tsx+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-log-version-info/use-log-version-info.unit.spec.tsx@@ -18,6 +18,7 @@ jest.mock("embedding-sdk-bundle/lib/get-is-localhost", () => ({}));jest.mock("embedding-sdk-bundle/lib/host-react-version", () => ({+ ...jest.requireActual("embedding-sdk-bundle/lib/host-react-version"),getHostReactMajorVersion: jest.fn(),}));diff --git a/frontend/src/embedding-sdk-bundle/lib/host-react-version.ts b/frontend/src/embedding-sdk-bundle/lib/host-react-version.tsindex ccaf086da29..ff2b2f4f5ef 100644--- a/frontend/src/embedding-sdk-bundle/lib/host-react-version.ts+++ b/frontend/src/embedding-sdk-bundle/lib/host-react-version.ts@@ -1,4 +1,7 @@-import { version as reactVersion } from "react";+import { version as reactVersion, useEffect } from "react";++// Raise this when the SDK bundle starts to need a newer React major.+const MINIMUM_SUPPORTED_REACT_MAJOR_VERSION = 18;export function getHostReactMajorVersion(): number | null {const majorVersion = parseInt(reactVersion, 10);@@ -6,3 +9,40 @@ export function getHostReactMajorVersion(): number | null {// Should be very rare: only when the host's `react` module has no usable `version`.return Number.isNaN(majorVersion) ? null : majorVersion;}++// An unknown version is treated as supported: rendering is better than+// blocking on a detection gap.+export function isHostReactVersionSupported(): boolean {+ const majorVersion = getHostReactMajorVersion();++ return (+ majorVersion === null ||+ majorVersion >= MINIMUM_SUPPORTED_REACT_MAJOR_VERSION+ );+}++export function getUnsupportedReactVersionMessage(): string {+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- only shown on an unsupported host React version+ return `The Metabase modular embedding SDK requires React ${MINIMUM_SUPPORTED_REACT_MAJOR_VERSION} or newer, but this application is running React ${getHostReactMajorVersion()}. Upgrade your application to React ${MINIMUM_SUPPORTED_REACT_MAJOR_VERSION} to display embedded content.`;+}++let hasLoggedUnsupportedReactVersion = false;++// Every unsupported React check calls this, so the console gets one message+// per page even when nothing renders the error component.+export function logUnsupportedReactVersionOnce() {+ if (hasLoggedUnsupportedReactVersion) {+ return;+ }++ console.error(getUnsupportedReactVersionMessage());+ hasLoggedUnsupportedReactVersion = true;+}++// Stands in for the SDK hooks the package calls outside ComponentProvider,+// where there is no error box to show.+export function useLogUnsupportedReactVersion() {+ useEffect(() => {+ logUnsupportedReactVersionOnce();+ }, []);+}diff --git a/frontend/src/embedding-sdk-bundle/lib/host-react-version.unit.spec.ts b/frontend/src/embedding-sdk-bundle/lib/host-react-version.unit.spec.tsindex d5d6eb5f3ef..148122acc35 100644--- a/frontend/src/embedding-sdk-bundle/lib/host-react-version.unit.spec.ts+++ b/frontend/src/embedding-sdk-bundle/lib/host-react-version.unit.spec.ts@@ -1,5 +1,12 @@-import { getHostReactMajorVersion } from "./host-react-version";+import {+ getHostReactMajorVersion,+ getUnsupportedReactVersionMessage,+ isHostReactVersionSupported,+ logUnsupportedReactVersionOnce,+} from "./host-react-version";+// MINIMUM_SUPPORTED_REACT_MAJOR_VERSION is 18, so React 17 stands in for an+// unsupported host throughout. When it moves to 19, move these versions up by one.let mockReactVersion: string | undefined;jest.mock("react", () => ({@@ -26,3 +33,58 @@ describe("getHostReactMajorVersion", () => {expect(getHostReactMajorVersion()).toBeNull();});});++describe("isHostReactVersionSupported", () => {+ it("does not support React 17", () => {+ mockReactVersion = "17.0.2";++ expect(isHostReactVersionSupported()).toBe(false);+ });++ it("supports React 18", () => {+ mockReactVersion = "18.3.1";++ expect(isHostReactVersionSupported()).toBe(true);+ });++ it("supports React 19", () => {+ mockReactVersion = "19.0.0";++ expect(isHostReactVersionSupported()).toBe(true);+ });++ it("treats an unknown host React version as supported", () => {+ mockReactVersion = undefined;++ expect(isHostReactVersionSupported()).toBe(true);+ });+});++describe("getUnsupportedReactVersionMessage", () => {+ it("names the required and the detected React major versions", () => {+ mockReactVersion = "17.0.2";++ expect(getUnsupportedReactVersionMessage()).toBe(+ "The Metabase modular embedding SDK requires React 18 or newer, but this application is running React 17. Upgrade your application to React 18 to display embedded content.",+ );+ });+});++describe("logUnsupportedReactVersionOnce", () => {+ it("logs the unsupported React message once across calls", () => {+ mockReactVersion = "17.0.2";+ const consoleError = jest+ .spyOn(console, "error")+ .mockImplementation(() => {});++ logUnsupportedReactVersionOnce();+ logUnsupportedReactVersionOnce();++ expect(consoleError).toHaveBeenCalledTimes(1);+ expect(consoleError).toHaveBeenCalledWith(+ "The Metabase modular embedding SDK requires React 18 or newer, but this application is running React 17. Upgrade your application to React 18 to display embedded content.",+ );++ consoleError.mockRestore();+ });+});diff --git a/frontend/src/metabase/embedding-sdk/lib/define-global-dependencies.ts b/frontend/src/metabase/embedding-sdk/lib/define-global-dependencies.tsindex b3d4b567379..e66a1500e0f 100644--- a/frontend/src/metabase/embedding-sdk/lib/define-global-dependencies.ts+++ b/frontend/src/metabase/embedding-sdk/lib/define-global-dependencies.ts@@ -17,7 +17,9 @@ const CONFIG: Record<ExternalDependenciesGlobalName, any> = {METABASE_REACT_DOM_SERVER: ReactDOMServer,};-// Put External Dependencies to the global object, so it can be used by the SDK bundle+// Put External Dependencies to the global object, so it can be used by the SDK+// bundle. The React here is the host app's, since the package is installed and+// bundled by the host; the bundle has none of its own.export function defineGlobalDependencies() {if (typeof window === "undefined") {return;