Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
require("../chunk-9hOWP6kD.cjs");
const require_FluidProvider = require("../FluidProvider-BvVjhwrv.cjs");
require("../ScreenRenderer-Ce8MJPnR.cjs");
require("../use-account-BBSExzPb.cjs");
require("../use-optional-store-CIM4spDu.cjs");
require("../mysite-api-context-DtEXblIV.cjs");
require("../ContactsTranslationBridge-Dx_1jAxz.cjs");
require("../registry-context-Ds0_y48D.cjs");
require("../WidgetInteractionContext-BiQvdkPb.cjs");
require("../RepUserContext-BiKQBY47.cjs");
require("../QuickLinksWidget-DUdlJGwE.cjs");
require("../WidgetRenderStateContext-CUkarAnq.cjs");
require("../static-dict-adapter-C7G0SEJY.cjs");
require("../SearchSort-BVc7PJ_Q.cjs");
require("../use-share-link-BU1azuL9.cjs");
require("../translation-api-context-factory-B6BS_JmA.cjs");
require("../shell-translation-api-context-uGur0Kah.cjs");
require("../error-state-bqYzR5FT.cjs");
require("../PointsWidget-CcENjU_h.cjs");
require("../task-composer-form-C8r1rqjv.cjs");
require("../ShopWidget-C_R5RGoe.cjs");
require("../LayoutWidget-CzM4gn1-.cjs");
require("../registries-DiCQ4oFx.cjs");
require("../fields-D__8kJeJ.cjs");
require("../TextWidget-Bu3yJ6TJ.cjs");
require("../AlertWidget-B4g4x-Qx.cjs");
require("../BulletListWidget-CEWflAL0.cjs");
require("../preview-context-DI7oT-If.cjs");
require("../CalendarWidget-M1_WyHA_.cjs");
require("../CardWidget-BWwI1G0Z.cjs");
require("../purify.es-8tE4K6lU.cjs");
require("../MediaRenderer-DKCnoI18.cjs");
require("../CarouselWidget-ubKaW_XJ.cjs");
require("../CatchUpWidget-DoKtO53d.cjs");
require("../src-DCYVQ8hc.cjs");
require("../ChartWidget-C1YDCNZz.cjs");
require("../ContainerWidget-DVQxqY3k.cjs");
require("../EmbedWidget-D1lbYjuL.cjs");
require("../ImageWidget-CFjq42Nx.cjs");
require("../LinkWidget-dihF4cKM.cjs");
require("../ListWidget-BALU0iQQ.cjs");
require("../MySiteWidget-BD1ICh_2.cjs");
require("../NestedWidget-0YTK04F7.cjs");
require("../QuickShareWidget-CESDDIcr.cjs");
require("../RecentActivityWidget-7tACMQqV.cjs");
require("../SeparatorWidget-DVnbbshP.cjs");
require("../SpacerWidget-5oBsx8_A.cjs");
require("../TableWidget-BrDvinFN.cjs");
require("../ToDoWidget-aSYTB02O.cjs");
require("../VideoWidget-B4SzSxTv.cjs");
require("../translation-adapter-CkgtjiOT.cjs");
require("../translation-adapter-BMvv-Nqx.cjs");
require("../translation-adapter-CRb5EiLL.cjs");
const require_widget_package_utils = require("../widget-package-utils-CJp6o3RD.cjs");
const require_protocol = require("../protocol-DIE_XooL.cjs");
let react = require("react");
let react_jsx_runtime = require("react/jsx-runtime");
let react_dom_client = require("react-dom/client");
//#region src/preview/PreviewRenderer.tsx
/**
* Renders a single widget inside the preview iframe, driven by
* postMessage commands from the builder.
*
* Lifecycle:
*   1. Sends `ready` event on mount
*   2. Waits for `auth` command → calls onAuth()
*   3. Waits for `render-widget` command → renders the widget
*   4. Reports dimensions via ResizeObserver
*/
function PreviewRenderer({ widgetRegistry, onAuth, builderOrigin, skipReady = false }) {
	const [widget, setWidget] = (0, react.useState)(null);
	const [error, setError] = (0, react.useState)(null);
	const containerRef = (0, react.useRef)(null);
	const sentReady = (0, react.useRef)(false);
	const sendToBuilder = (0, react.useCallback)((event) => {
		if (!builderOrigin) return;
		window.parent.postMessage(event, builderOrigin);
	}, [builderOrigin]);
	(0, react.useEffect)(() => {
		if (skipReady) return;
		if (sentReady.current) return;
		sentReady.current = true;
		sendToBuilder({ type: "ready" });
	}, [sendToBuilder, skipReady]);
	const sentAuthReady = (0, react.useRef)(false);
	(0, react.useEffect)(() => {
		if (!skipReady) return;
		if (sentAuthReady.current) return;
		sentAuthReady.current = true;
		sendToBuilder({ type: "auth-ready" });
	}, [sendToBuilder, skipReady]);
	(0, react.useEffect)(() => {
		if (!builderOrigin) return;
		function handleMessage(event) {
			if (event.origin !== builderOrigin) return;
			if (!require_protocol.isPreviewCommand(event.data)) return;
			const command = event.data;
			switch (command.type) {
				case "auth":
					onAuth(command.token);
					if (!sentAuthReady.current) {
						sentAuthReady.current = true;
						sendToBuilder({ type: "auth-ready" });
					}
					break;
				case "render-widget":
					setError(null);
					setWidget({
						widgetType: command.widgetType,
						props: command.props
					});
					break;
				case "select-widget": break;
				case "unmount-widget":
					setWidget(null);
					setError(null);
					break;
				default:
			}
		}
		window.addEventListener("message", handleMessage);
		return () => window.removeEventListener("message", handleMessage);
	}, [
		builderOrigin,
		onAuth,
		sendToBuilder
	]);
	(0, react.useEffect)(() => {
		const container = containerRef.current;
		if (!container || !widget) return;
		const observer = new ResizeObserver((entries) => {
			const entry = entries[0];
			if (!entry) return;
			const { width, height } = entry.contentRect;
			sendToBuilder({
				type: "widget-rendered",
				widgetType: widget.widgetType,
				dimensions: {
					width: Math.ceil(width),
					height: Math.ceil(height)
				}
			});
		});
		observer.observe(container);
		return () => observer.disconnect();
	}, [widget, sendToBuilder]);
	(0, react.useEffect)(() => {
		const hot = {}.hot;
		if (hot) {
			const handler = () => sendToBuilder({ type: "widget-hmr" });
			hot.on("vite:afterUpdate", handler);
			return () => hot.off("vite:afterUpdate", handler);
		}
	}, [sendToBuilder]);
	const WidgetComponent = widget ? widgetRegistry[widget.widgetType] : void 0;
	(0, react.useEffect)(() => {
		if (!widget) return;
		if (!widgetRegistry[widget.widgetType]) sendToBuilder({
			type: "widget-error",
			widgetType: widget.widgetType,
			error: `Unknown widget type: ${widget.widgetType}`
		});
	}, [
		widget,
		widgetRegistry,
		sendToBuilder
	]);
	if (!widget) return null;
	if (!WidgetComponent) return null;
	if (error) return null;
	return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
		ref: containerRef,
		onClick: () => sendToBuilder({
			type: "widget-clicked",
			widgetType: widget.widgetType
		}),
		children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ErrorBoundary, {
			widgetType: widget.widgetType,
			onError: (err) => {
				setError(err);
				sendToBuilder({
					type: "widget-error",
					widgetType: widget.widgetType,
					error: err
				});
			},
			children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(WidgetComponent, { ...widget.props })
		}, widget.widgetType)
	});
}
var ErrorBoundary = class extends react.Component {
	constructor(props) {
		super(props);
		this.state = { hasError: false };
	}
	static getDerivedStateFromError() {
		return { hasError: true };
	}
	componentDidCatch(error) {
		this.props.onError(error.message);
	}
	render() {
		if (this.state.hasError) return null;
		return this.props.children;
	}
};
//#endregion
//#region src/preview/preview-entry.tsx
/**
* Preview iframe bootstrap function.
*
* Called from the portal project's src/preview-entry.tsx with the
* customWidgets array from portal.config.ts. Mirrors the createPortal()
* pattern — SDK handles the wiring, user project provides the widgets.
*
* Two-phase auth handshake:
*   Phase 1: Send `ready`, wait for `auth` command, store token
*   Phase 2: Mount provider stack + PreviewRenderer, send `auth-ready`
*/
function createPreview(options = {}) {
	const { customWidgets = [], widgetPackages = [], rootId = "preview-root" } = options;
	const dedupedWidgetPackages = require_widget_package_utils.dedupeWidgetPackagesByPackageIdAndVersion(widgetPackages);
	const initialWidgetRegistry = require_widget_package_utils.mergeRegisteredWidgetsIntoRegistry(require_widget_package_utils.buildWidgetRegistry(customWidgets), require_widget_package_utils.installAndReadFluidWidgetsRegistry());
	const rawBuilderOrigin = new URLSearchParams(window.location.search).get("builderOrigin");
	const builderOrigin = rawBuilderOrigin && require_protocol.isAllowedOrigin(rawBuilderOrigin) ? rawBuilderOrigin : null;
	if (builderOrigin) window.parent.postMessage({ type: "ready" }, builderOrigin);
	function handleAuthMessage(event) {
		if (event.origin !== builderOrigin) return;
		if (typeof event.data !== "object" || event.data === null || event.data.type !== "auth") return;
		window.removeEventListener("message", handleAuthMessage);
		const command = event.data;
		mountApp({
			initialWidgetRegistry,
			widgetPackages: dedupedWidgetPackages,
			builderOrigin,
			rootId,
			authToken: command.token
		});
	}
	if (builderOrigin) window.addEventListener("message", handleAuthMessage);
	else {
		const rootElement = document.getElementById(rootId);
		if (rootElement) {
			rootElement.style.cssText = "display:flex;align-items:center;justify-content:center;height:100vh;font-family:system-ui;color:#888;font-size:14px";
			rootElement.textContent = rawBuilderOrigin ? `Preview unavailable — origin "${rawBuilderOrigin}" is not allowed` : "Preview unavailable — missing builderOrigin parameter";
		}
	}
}
function mountApp({ initialWidgetRegistry, widgetPackages, builderOrigin, rootId, authToken }) {
	const rootElement = document.getElementById(rootId);
	if (!rootElement) return;
	const iframeOrigin = window.location.origin;
	const tree = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react.StrictMode, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(PreviewRuntimeWidgetBootstrap, {
		fluidConfig: require_widget_package_utils.createDefaultFluidConfig({
			baseUrl: iframeOrigin,
			getAuthToken: () => authToken
		}),
		initialWidgetRegistry,
		widgetPackageLoadPromise: builderOrigin && widgetPackages.length ? require_widget_package_utils.loadWidgetPackages(widgetPackages) : void 0,
		builderOrigin
	}) });
	(0, react_dom_client.createRoot)(rootElement).render(tree);
}
function PreviewRuntimeWidgetBootstrap({ fluidConfig, initialWidgetRegistry, widgetPackageLoadPromise, builderOrigin }) {
	const [runtimeWidgetState, setRuntimeWidgetState] = (0, react.useState)(() => ({
		widgetRegistry: initialWidgetRegistry,
		packageLoadSettled: !widgetPackageLoadPromise
	}));
	(0, react.useEffect)(() => {
		if (!widgetPackageLoadPromise) {
			setRuntimeWidgetState({
				widgetRegistry: initialWidgetRegistry,
				packageLoadSettled: true
			});
			return;
		}
		let cancelled = false;
		setRuntimeWidgetState({
			widgetRegistry: initialWidgetRegistry,
			packageLoadSettled: false
		});
		widgetPackageLoadPromise.then((summary) => {
			if (cancelled) return;
			setRuntimeWidgetState({
				widgetRegistry: require_widget_package_utils.mergeRegisteredWidgetsIntoRegistry(initialWidgetRegistry, summary.registeredWidgets),
				packageLoadSettled: true
			});
		}).catch((error) => {
			if (cancelled) return;
			console.error("[portal] Failed to load preview widget packages:", error);
			setRuntimeWidgetState({
				widgetRegistry: initialWidgetRegistry,
				packageLoadSettled: true
			});
		});
		return () => {
			cancelled = true;
		};
	}, [initialWidgetRegistry, widgetPackageLoadPromise]);
	return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_FluidProvider.FluidProvider, {
		config: fluidConfig,
		widgetRegistry: runtimeWidgetState.widgetRegistry,
		children: runtimeWidgetState.packageLoadSettled ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(PreviewRenderer, {
			widgetRegistry: runtimeWidgetState.widgetRegistry,
			onAuth: () => {},
			builderOrigin,
			skipReady: true
		}) : null
	});
}
//#endregion
exports.createPreview = createPreview;

//# sourceMappingURL=preview-entry.cjs.map