@first-to-fly/crm-sdk 1.5.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/embed-react.tsx","../src/embed-host.ts"],"sourcesContent":["/**\n * Drop-in React component that embeds the First To Fly CRM as a cross-origin\n * iframe, authenticated WITHOUT cookies.\n *\n * This wraps the low-level {@link ./embed-host | embed-host} helpers into a\n * single component. You supply a `getSession()` that returns a CRM bearer plus\n * the workspace to embed (typically by calling your own backend endpoint that\n * runs `createEmbedSessionWithKey`), and the component handles:\n * - resolving the session and building the iframe URL,\n * - rendering the iframe and running the MessageChannel handshake,\n * - reusing the initial bearer (no double-mint) and re-minting on expiry,\n * - loading / error / retry states.\n *\n * A host (e.g. an app shell) can drive the embedded CRM's section navigation\n * imperatively via a ref (`navigate(path)`), observe the CRM's own navigation\n * via `onRouteChange`, deep-link an `initialPath` on first load, and hide the\n * CRM's in-iframe nav via `hostProvidesNav` (when the host supplies its own).\n *\n * `react` is an OPTIONAL peer dependency — only pull in this entry if you use\n * React. Non-React consumers can keep using `./embed-host` directly.\n *\n * @packageDocumentation\n */\n\nimport {\n forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState,\n} from 'react';\nimport type { CSSProperties, ReactNode } from 'react';\n\nimport {\n buildCrmEmbedUrl,\n createCrmEmbedHost,\n crmSession,\n type CrmBearer,\n type CrmEmbedHost,\n type CrmSessionResult,\n} from './embed-host';\n\n// Re-export the session-fetch helper so React users can get it from one entry:\n// import { CrmEmbed, crmSession } from '@first-to-fly/crm-sdk/embed-react';\nexport { crmSession, type CrmSessionResult };\n\n/**\n * What a partner's `getSession()` must resolve to. Alias of {@link CrmSessionResult}\n * (the browser-side session shape) — kept as a named export for back-compat; both\n * are `{ accessToken, workspaceId, expiresIn? }`.\n */\nexport type CrmEmbedSession = CrmSessionResult;\n\n/**\n * Imperative handle exposed via `ref`. Lets a host drive the embedded CRM's\n * navigation without re-rendering the iframe.\n */\nexport interface CrmEmbedHandle {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n}\n\nexport interface CrmEmbedProps {\n /**\n * Resolves a CRM bearer + the workspace to embed. Called once on mount (and\n * again on retry / session expiry). Typically calls your own backend endpoint\n * that runs `createEmbedSessionWithKey`.\n */\n getSession: () => Promise<CrmEmbedSession>;\n /**\n * The CRM embed base origin, e.g. \"https://crm.example.com\". The iframe URL\n * is `buildCrmEmbedUrl(crmEmbedOrigin, workspaceId)` and this origin is also\n * used as the postMessage targetOrigin.\n */\n crmEmbedOrigin: string;\n /** Class applied to the iframe. */\n className?: string;\n /** Inline style merged onto the iframe (overrides the fill-container default). */\n style?: CSSProperties;\n /** Iframe title (accessibility). Defaults to \"CRM\". */\n title?: string;\n /** Called after the iframe URL is built and mounted. */\n onReady?: (info: { workspaceId: string }) => void;\n /** Called on any session / handshake error. */\n onError?: (error: Error) => void;\n /**\n * Called when the CRM navigates internally (e.g. \"/contacts\"). Use this to\n * keep a host-supplied nav in sync with the embedded CRM's current section.\n */\n onRouteChange?: (path: string) => void;\n /**\n * When true, the CRM hides its own in-iframe nav (the host supplies it).\n * Signalled to the CRM by appending `?hostnav=1` to the iframe URL. Drive\n * navigation yourself via the ref's `navigate()`.\n */\n hostProvidesNav?: boolean;\n /**\n * Initial CRM sub-path to deep-link on FIRST load (e.g. \"/contacts\").\n * Only applied to the initial iframe URL — later changes do NOT reload the\n * iframe; use the ref's `navigate()` for in-session navigation.\n */\n initialPath?: string;\n /** Custom loading UI. Defaults to a minimal message. */\n renderLoading?: () => ReactNode;\n /** Custom error UI. Defaults to the message + a Retry button. */\n renderError?: (error: Error, retry: () => void) => ReactNode;\n}\n\nconst DEFAULT_IFRAME_STYLE: CSSProperties = {\n width: '100%',\n height: '100%',\n border: 0,\n};\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n\nfunction DefaultLoading(): ReactNode {\n return <div>Loading CRM…</div>;\n}\n\nfunction DefaultError(error: Error, retry: () => void): ReactNode {\n return (\n <div>\n <p>Couldn’t load the CRM: {error.message}</p>\n <button type=\"button\" onClick={retry}>Try again</button>\n </div>\n );\n}\n\n/**\n * Embed the First To Fly CRM in a React app. See {@link CrmEmbedProps}.\n *\n * Accepts a `ref` of type {@link CrmEmbedHandle} exposing `navigate(path)` so a\n * host can drive the embedded CRM's section navigation.\n */\nexport const CrmEmbed = forwardRef<CrmEmbedHandle, CrmEmbedProps>(\n function CrmEmbed(props, ref): ReactNode {\n const {\n getSession,\n crmEmbedOrigin,\n className,\n style,\n title = 'CRM',\n onReady,\n onError,\n onRouteChange,\n hostProvidesNav,\n initialPath,\n renderLoading,\n renderError,\n } = props;\n\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const [embedUrl, setEmbedUrl] = useState<string | null>(null);\n const [workspaceId, setWorkspaceId] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [attempt, setAttempt] = useState(0);\n\n // Bearer minted during session resolution — reused for the host's first\n // getBearer() so a single getSession() call covers both phases (no double-mint).\n const primedBearerRef = useRef<CrmBearer | null>(null);\n\n // The created host, so the imperative `navigate()` can reach it.\n const hostRef = useRef<CrmEmbedHost | null>(null);\n\n // Expose the imperative navigate(). No-ops safely before the host is wired.\n useImperativeHandle(ref, () => ({\n navigate: (path: string) => { hostRef.current?.navigate(path); },\n }), []);\n\n // Keep the latest callbacks in refs so the effects DON'T depend on their\n // identity. Partners routinely pass inline `getSession`/`onReady`/`onError`/\n // `onRouteChange`; depending on them directly would re-run Phase 1 (re-fetch\n // the session) and tear down + recreate the host on every parent re-render.\n const getSessionRef = useRef(getSession);\n const onReadyRef = useRef(onReady);\n const onErrorRef = useRef(onError);\n const onRouteChangeRef = useRef(onRouteChange);\n useEffect(() => {\n getSessionRef.current = getSession;\n onReadyRef.current = onReady;\n onErrorRef.current = onError;\n onRouteChangeRef.current = onRouteChange;\n });\n\n // Capture initialPath ONCE — it only seeds the first load. Later changes go\n // through the imperative navigate() and must NOT rebuild/reload the iframe.\n const initialPathRef = useRef(initialPath);\n\n const retry = useCallback(() => {\n primedBearerRef.current = null;\n setError(null);\n setEmbedUrl(null);\n setWorkspaceId(null);\n setAttempt((n) => n + 1);\n }, []);\n\n // Phase 1: resolve the session, prime the bearer, and build the iframe URL.\n // Re-runs only on retry (`attempt`) or a changed origin/hostnav — never on\n // unrelated parent re-renders (callbacks + initialPath are read from refs).\n useEffect(() => {\n let cancelled = false;\n\n void (async () => {\n try {\n const session = await getSessionRef.current();\n if (cancelled) return;\n primedBearerRef.current = { accessToken: session.accessToken };\n setWorkspaceId(session.workspaceId);\n const base = buildCrmEmbedUrl(crmEmbedOrigin, session.workspaceId);\n const url = base + (initialPathRef.current ?? '') + (hostProvidesNav ? '?hostnav=1' : '');\n setEmbedUrl(url);\n } catch (err) {\n if (cancelled) return;\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n }\n })();\n\n return () => { cancelled = true; };\n }, [crmEmbedOrigin, hostProvidesNav, attempt]);\n\n // Phase 2: once the iframe URL is known, wire the MessageChannel host.\n useEffect(() => {\n const iframe = iframeRef.current;\n if (!iframe || !embedUrl || !workspaceId) return undefined;\n\n let host: CrmEmbedHost | null = null;\n try {\n host = createCrmEmbedHost({\n iframe,\n crmOrigin: crmEmbedOrigin,\n getBearer: async () => {\n const primed = primedBearerRef.current;\n if (primed) {\n primedBearerRef.current = null;\n return primed;\n }\n const session = await getSessionRef.current();\n return { accessToken: session.accessToken };\n },\n onRouteChange: (path) => { onRouteChangeRef.current?.(path); },\n onError: (err) => {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n },\n });\n } catch (err) {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n return undefined;\n }\n\n hostRef.current = host;\n\n // Only signal ready once the host is actually wired.\n onReadyRef.current?.({ workspaceId });\n\n return () => {\n host?.dispose();\n hostRef.current = null;\n };\n }, [embedUrl, workspaceId, crmEmbedOrigin]);\n\n if (error) {\n return <>{renderError ? renderError(error, retry) : DefaultError(error, retry)}</>;\n }\n\n if (!embedUrl) {\n return <>{renderLoading ? renderLoading() : DefaultLoading()}</>;\n }\n\n return (\n <iframe\n ref={iframeRef}\n src={embedUrl}\n title={title}\n className={className}\n style={{ ...DEFAULT_IFRAME_STYLE, ...style }}\n />\n );\n },\n);\n\nexport default CrmEmbed;\n","/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n const result = body as Partial<CrmSessionResult>;\n // A malformed 2xx (e.g. `{}`) would otherwise cast cleanly and later build an\n // `/embed/undefined` URL — fail at the boundary with a clear message instead.\n if (typeof result?.accessToken !== 'string' || typeof result?.workspaceId !== 'string') {\n throw new Error('CRM session response is missing accessToken/workspaceId');\n }\n return result as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n\n async function deliverBearer(): Promise<boolean> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n return true;\n } catch (err) {\n opts.onError?.(err);\n return false;\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow). Only tell the\n // CRM the session refreshed once a fresh bearer was ACTUALLY delivered —\n // otherwise a failed re-mint leaves the iframe believing it's authenticated.\n void deliverBearer().then((ok) => {\n if (ok) port?.postMessage({ type: 'session-refreshed' });\n });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"yaAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,cAAAE,EAAA,eAAAC,EAAA,YAAAC,KAAA,eAAAC,EAAAL,IAwBA,IAAAM,EAEO,iBC6CP,SAASC,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CAmBO,SAASC,EACdC,EACAC,EACiC,CACjC,MAAO,UAAuC,CAC5C,IAAMC,EAAM,MAAM,MAAMF,EAAK,CAAE,OAAQ,OAAQ,GAAGC,CAAK,CAAC,EAClDE,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,GAAI,CAACA,EAAI,GAAI,CACX,IAAME,EAAQD,GAA6B,MAC3C,MAAM,IAAI,MACRC,EAAO,uBAAuBA,CAAI,GAAK,4BAA4BF,EAAI,MAAM,GAC/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Session","embed_react_default","__toCommonJS","import_react","isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path","import_jsx_runtime","DEFAULT_IFRAME_STYLE","toError","err","DefaultLoading","DefaultError","error","retry","CrmEmbed","props","ref","getSession","crmEmbedOrigin","className","style","title","onReady","onError","onRouteChange","hostProvidesNav","initialPath","renderLoading","renderError","iframeRef","embedUrl","setEmbedUrl","workspaceId","setWorkspaceId","setError","attempt","setAttempt","primedBearerRef","hostRef","path","getSessionRef","onReadyRef","onErrorRef","onRouteChangeRef","initialPathRef","n","cancelled","session","url","buildCrmEmbedUrl","e","iframe","host","createCrmEmbedHost","primed","embed_react_default"]}
1
+ {"version":3,"sources":["../src/embed-react.tsx","../src/embed-host.ts"],"sourcesContent":["/**\n * Drop-in React component that embeds the First To Fly CRM as a cross-origin\n * iframe, authenticated WITHOUT cookies.\n *\n * This wraps the low-level {@link ./embed-host | embed-host} helpers into a\n * single component. You supply a `getSession()` that returns a CRM bearer plus\n * the workspace to embed (typically by calling your own backend endpoint that\n * runs `createEmbedSessionWithKey`), and the component handles:\n * - resolving the session and building the iframe URL,\n * - rendering the iframe and running the MessageChannel handshake,\n * - reusing the initial bearer (no double-mint) and re-minting on expiry,\n * - loading / error / retry states.\n *\n * A host (e.g. an app shell) can drive the embedded CRM's section navigation\n * imperatively via a ref (`navigate(path)`), observe the CRM's own navigation\n * via `onRouteChange`, deep-link an `initialPath` on first load, and hide the\n * CRM's in-iframe nav via `hostProvidesNav` (when the host supplies its own).\n *\n * `react` is an OPTIONAL peer dependency — only pull in this entry if you use\n * React. Non-React consumers can keep using `./embed-host` directly.\n *\n * @packageDocumentation\n */\n\nimport {\n forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState,\n} from 'react';\nimport type { CSSProperties, ReactNode } from 'react';\n\nimport {\n buildCrmEmbedUrl,\n createCrmEmbedHost,\n crmSession,\n hostContextQuery,\n type CrmBearer,\n type CrmEmbedHost,\n type CrmHostBrand,\n type CrmHostTheme,\n type CrmSessionResult,\n} from './embed-host';\n\n// Re-export the session-fetch helper so React users can get it from one entry:\n// import { CrmEmbed, crmSession } from '@first-to-fly/crm-sdk/embed-react';\nexport {\n crmSession, type CrmSessionResult, type CrmHostTheme, type CrmHostBrand,\n};\n\n/**\n * What a partner's `getSession()` must resolve to. Alias of {@link CrmSessionResult}\n * (the browser-side session shape) — kept as a named export for back-compat; both\n * are `{ accessToken, workspaceId, expiresIn? }`.\n */\nexport type CrmEmbedSession = CrmSessionResult;\n\n/**\n * Imperative handle exposed via `ref`. Lets a host drive the embedded CRM's\n * navigation without re-rendering the iframe.\n */\nexport interface CrmEmbedHandle {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n}\n\nexport interface CrmEmbedProps {\n /**\n * Resolves a CRM bearer + the workspace to embed. Called once on mount (and\n * again on retry / session expiry). Typically calls your own backend endpoint\n * that runs `createEmbedSessionWithKey`.\n */\n getSession: () => Promise<CrmEmbedSession>;\n /**\n * The CRM embed base origin, e.g. \"https://crm.example.com\". The iframe URL\n * is `buildCrmEmbedUrl(crmEmbedOrigin, workspaceId)` and this origin is also\n * used as the postMessage targetOrigin.\n */\n crmEmbedOrigin: string;\n /** Class applied to the iframe. */\n className?: string;\n /** Inline style merged onto the iframe (overrides the fill-container default). */\n style?: CSSProperties;\n /** Iframe title (accessibility). Defaults to \"CRM\". */\n title?: string;\n /** Called after the iframe URL is built and mounted. */\n onReady?: (info: { workspaceId: string }) => void;\n /** Called on any session / handshake error. */\n onError?: (error: Error) => void;\n /**\n * Called when the CRM navigates internally (e.g. \"/contacts\"). Use this to\n * keep a host-supplied nav in sync with the embedded CRM's current section.\n */\n onRouteChange?: (path: string) => void;\n /**\n * When true, the CRM hides its own in-iframe nav (the host supplies it).\n * Signalled to the CRM by appending `?hostnav=1` to the iframe URL. Drive\n * navigation yourself via the ref's `navigate()`.\n */\n hostProvidesNav?: boolean;\n /**\n * Initial CRM sub-path to deep-link on FIRST load (e.g. \"/contacts\").\n * Only applied to the initial iframe URL — later changes do NOT reload the\n * iframe; use the ref's `navigate()` for in-session navigation.\n */\n initialPath?: string;\n /**\n * Theme for the embedded CRM: `light`, `dark`, or `system` (follow the visitor's OS).\n * The first value rides on the iframe URL as `?theme=`; a later change is posted to\n * the frame over the channel (`crm:host-context`) without reloading it. The CRM applies\n * it for the embed only and never saves it to the user's account. Omitted: the CRM keeps\n * its default (light) look.\n */\n theme?: CrmHostTheme;\n /**\n * Language for the embedded CRM as a BCP 47 tag, e.g. \"en\" or \"zh-CN\". Sent like `theme`\n * (`?locale=`, then `crm:host-context`). Omitted: the CRM keeps its own language.\n */\n locale?: string;\n /**\n * Brand tokens (accent, surfaces, border, radius, fonts) so the CRM looks like part of\n * your app. First value rides on the iframe URL as `?brand=` (base64url JSON); changes\n * are posted over the channel without a reload. Invalid fields are dropped. Pass the\n * tokens for your CURRENT theme and change the object when the theme toggles. See\n * {@link CrmHostBrand}. Omitted: the CRM keeps its own look.\n */\n brand?: CrmHostBrand;\n /** Custom loading UI. Defaults to a minimal message. */\n renderLoading?: () => ReactNode;\n /** Custom error UI. Defaults to the message + a Retry button. */\n renderError?: (error: Error, retry: () => void) => ReactNode;\n}\n\nconst DEFAULT_IFRAME_STYLE: CSSProperties = {\n width: '100%',\n height: '100%',\n border: 0,\n};\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n\nfunction DefaultLoading(): ReactNode {\n return <div>Loading CRM…</div>;\n}\n\nfunction DefaultError(error: Error, retry: () => void): ReactNode {\n return (\n <div>\n <p>Couldn’t load the CRM: {error.message}</p>\n <button type=\"button\" onClick={retry}>Try again</button>\n </div>\n );\n}\n\n/**\n * Embed the First To Fly CRM in a React app. See {@link CrmEmbedProps}.\n *\n * Accepts a `ref` of type {@link CrmEmbedHandle} exposing `navigate(path)` so a\n * host can drive the embedded CRM's section navigation.\n */\nexport const CrmEmbed = forwardRef<CrmEmbedHandle, CrmEmbedProps>(\n function CrmEmbed(props, ref): ReactNode {\n const {\n getSession,\n crmEmbedOrigin,\n className,\n style,\n title = 'CRM',\n onReady,\n onError,\n onRouteChange,\n hostProvidesNav,\n initialPath,\n theme,\n locale,\n brand,\n renderLoading,\n renderError,\n } = props;\n\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const [embedUrl, setEmbedUrl] = useState<string | null>(null);\n const [workspaceId, setWorkspaceId] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [attempt, setAttempt] = useState(0);\n\n // Bearer minted during session resolution — reused for the host's first\n // getBearer() so a single getSession() call covers both phases (no double-mint).\n const primedBearerRef = useRef<CrmBearer | null>(null);\n\n // The created host, so the imperative `navigate()` can reach it.\n const hostRef = useRef<CrmEmbedHost | null>(null);\n\n // Expose the imperative navigate(). No-ops safely before the host is wired.\n useImperativeHandle(ref, () => ({\n navigate: (path: string) => { hostRef.current?.navigate(path); },\n }), []);\n\n // Keep the latest callbacks in refs so the effects DON'T depend on their\n // identity. Partners routinely pass inline `getSession`/`onReady`/`onError`/\n // `onRouteChange`; depending on them directly would re-run Phase 1 (re-fetch\n // the session) and tear down + recreate the host on every parent re-render.\n const getSessionRef = useRef(getSession);\n const onReadyRef = useRef(onReady);\n const onErrorRef = useRef(onError);\n const onRouteChangeRef = useRef(onRouteChange);\n useEffect(() => {\n getSessionRef.current = getSession;\n onReadyRef.current = onReady;\n onErrorRef.current = onError;\n onRouteChangeRef.current = onRouteChange;\n });\n\n // Capture initialPath ONCE — it only seeds the first load. Later changes go\n // through the imperative navigate() and must NOT rebuild/reload the iframe.\n const initialPathRef = useRef(initialPath);\n\n // Latest theme/locale. The first values seed the iframe URL and the host; later changes\n // are pushed through the channel by the effect below, never by rebuilding the iframe.\n const hostContextRef = useRef({ theme, locale, brand });\n hostContextRef.current = { theme, locale, brand };\n\n const retry = useCallback(() => {\n primedBearerRef.current = null;\n setError(null);\n setEmbedUrl(null);\n setWorkspaceId(null);\n setAttempt((n) => n + 1);\n }, []);\n\n // Phase 1: resolve the session, prime the bearer, and build the iframe URL.\n // Re-runs only on retry (`attempt`) or a changed origin/hostnav — never on\n // unrelated parent re-renders (callbacks + initialPath are read from refs).\n useEffect(() => {\n let cancelled = false;\n\n void (async () => {\n try {\n const session = await getSessionRef.current();\n if (cancelled) return;\n primedBearerRef.current = { accessToken: session.accessToken };\n setWorkspaceId(session.workspaceId);\n const base = buildCrmEmbedUrl(crmEmbedOrigin, session.workspaceId);\n const path = initialPathRef.current ?? '';\n const query = [...(hostProvidesNav ? ['hostnav=1'] : []), ...hostContextQuery(hostContextRef.current)];\n const separator = path.includes('?') ? '&' : '?';\n const url = base + path + (query.length > 0 ? separator + query.join('&') : '');\n setEmbedUrl(url);\n } catch (err) {\n if (cancelled) return;\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n }\n })();\n\n return () => { cancelled = true; };\n }, [crmEmbedOrigin, hostProvidesNav, attempt]);\n\n // Phase 2: once the iframe URL is known, wire the MessageChannel host.\n useEffect(() => {\n const iframe = iframeRef.current;\n if (!iframe || !embedUrl || !workspaceId) return undefined;\n\n let host: CrmEmbedHost | null = null;\n try {\n host = createCrmEmbedHost({\n iframe,\n crmOrigin: crmEmbedOrigin,\n getBearer: async () => {\n const primed = primedBearerRef.current;\n if (primed) {\n primedBearerRef.current = null;\n return primed;\n }\n const session = await getSessionRef.current();\n return { accessToken: session.accessToken };\n },\n hostContext: hostContextRef.current,\n onRouteChange: (path) => { onRouteChangeRef.current?.(path); },\n onError: (err) => {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n },\n });\n } catch (err) {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n return undefined;\n }\n\n hostRef.current = host;\n\n // Only signal ready once the host is actually wired.\n onReadyRef.current?.({ workspaceId });\n\n return () => {\n host?.dispose();\n hostRef.current = null;\n };\n }, [embedUrl, workspaceId, crmEmbedOrigin]);\n\n // Phase 3: a theme/locale change after mount is sent to the frame, not a reload.\n // Compared by content, so an inline `brand={{...}}` does not re-send on every render.\n const brandKey = JSON.stringify(brand ?? null);\n const hadBrandRef = useRef(false);\n useEffect(() => {\n // Clear the frame's brand only if one was sent before; otherwise leave the field out.\n const brandUpdate = brand ? { brand } : (hadBrandRef.current ? { brand: null } : {});\n hadBrandRef.current = !!brand;\n hostRef.current?.setContext({ theme, locale, ...brandUpdate });\n // eslint-disable-next-line react-hooks/exhaustive-deps -- brandKey stands in for brand\n }, [theme, locale, brandKey]);\n\n if (error) {\n return <>{renderError ? renderError(error, retry) : DefaultError(error, retry)}</>;\n }\n\n if (!embedUrl) {\n return <>{renderLoading ? renderLoading() : DefaultLoading()}</>;\n }\n\n return (\n <iframe\n ref={iframeRef}\n src={embedUrl}\n title={title}\n className={className}\n style={{ ...DEFAULT_IFRAME_STYLE, ...style }}\n />\n );\n },\n);\n\nexport default CrmEmbed;\n","/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n * 6. host sends { type: 'crm:host-context', theme?, locale?, brand? } on the same port,\n * right after the bearer and again whenever {@link CrmEmbedHost.setContext} is called.\n * The first values also ride on the iframe URL (`?theme=`, `?locale=` and `?brand=`), so the\n * frame paints in the right theme before the handshake finishes.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\n/** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */\nexport type CrmHostTheme = 'light' | 'dark' | 'system';\n\n/**\n * Brand tokens that make the embedded CRM look like part of the host. All optional.\n * Colours are `#rgb` or `#rrggbb`; invalid values are dropped, never sent.\n * Pass the values for the host's CURRENT theme and send a new brand when it toggles.\n * No remote font is loaded: a family the visitor's system lacks falls back to the CRM's.\n */\nexport interface CrmHostBrand {\n /** Buttons, selected tabs, focus rings, chart accent. */\n accent?: string;\n /** Text on the accent. Defaults to white or near-black, whichever reads better. */\n accentForeground?: string;\n /** Page background. */\n background?: string;\n /** Cards, popovers and inputs. Defaults to `background`. */\n surface?: string;\n /** Hairlines and input borders. Derived from background and foreground when omitted. */\n border?: string;\n /** Body text. */\n foreground?: string;\n /** Secondary text. Derived when omitted. */\n mutedForeground?: string;\n /** Corner radius for controls, `0px` to `24px`, e.g. `\"6px\"`. Larger surfaces scale from it. */\n radius?: string;\n /** UI font family list, e.g. `\"Inter, system-ui\"`. Letters, digits, spaces, commas, quotes, hyphens, underscores; max 160 chars. */\n fontFamily?: string;\n /** Font for page titles, same rules as `fontFamily`, e.g. `\"Fraunces, Georgia, serif\"`. */\n displayFontFamily?: string;\n}\n\n/**\n * Look and language the host passes to the embedded CRM. Both are optional; an omitted\n * field leaves the CRM's own behaviour unchanged. The CRM applies them for the embed only\n * and never saves them to the user's account.\n */\nexport interface CrmHostContext {\n theme?: CrmHostTheme;\n /** BCP 47 language tag, e.g. \"en\" or \"zh-CN\". */\n locale?: string;\n /**\n * Host brand tokens. A new brand REPLACES the previous one; `null` (setContext only)\n * returns the CRM to its own look. Omitted: unchanged.\n */\n brand?: CrmHostBrand | null;\n}\n\n/** The message the host posts on the channel port to update {@link CrmHostContext}. */\nexport interface CrmHostContextMessage extends CrmHostContext {\n type: 'crm:host-context';\n}\n\nconst HOST_THEMES: readonly string[] = ['light', 'dark', 'system'];\nconst BCP47_LIKE = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;\n\nconst HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;\nconst RADIUS_PX = /^(\\d{1,2}(?:\\.\\d{1,2})?)px$/;\nconst FONT_CHARS = /^[A-Za-z0-9 ,'\"_-]+$/;\nconst FONT_MAX = 160;\n/** The encoded `?brand=` value never exceeds this; a longer one would be ignored by the CRM. */\nconst BRAND_PARAM_MAX = 1500;\nconst BRAND_COLOR_KEYS = [\n 'accent', 'accentForeground', 'background', 'surface', 'border', 'foreground', 'mutedForeground',\n] as const;\n\nfunction cleanFont(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const v = value.trim();\n if (!v || v.length > FONT_MAX || !FONT_CHARS.test(v)) return undefined;\n if ((v.match(/\"/g)?.length ?? 0) % 2 !== 0 || (v.match(/'/g)?.length ?? 0) % 2 !== 0) return undefined;\n return v;\n}\n\n/**\n * Keeps only valid brand fields: hex colours (lower-cased `#rrggbb`), a `0-24px` radius and\n * safe font-family lists. Returns undefined when nothing valid is left.\n */\nexport function normalizeHostBrand(brand: CrmHostBrand | undefined | null): CrmHostBrand | undefined {\n if (!brand || typeof brand !== 'object' || Array.isArray(brand)) return undefined;\n const out: CrmHostBrand = {};\n for (const key of BRAND_COLOR_KEYS) {\n const raw = brand[key];\n if (typeof raw === 'string' && HEX_COLOR.test(raw.trim())) {\n let hex = raw.trim().toLowerCase();\n if (hex.length === 4) hex = `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`;\n out[key] = hex;\n }\n }\n if (typeof brand.radius === 'string') {\n const m = RADIUS_PX.exec(brand.radius.trim());\n if (m && Number(m[1]) <= 24) out.radius = `${Number(m[1])}px`;\n }\n const fontFamily = cleanFont(brand.fontFamily);\n if (fontFamily) out.fontFamily = fontFamily;\n const displayFontFamily = cleanFont(brand.displayFontFamily);\n if (displayFontFamily) out.displayFontFamily = displayFontFamily;\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** Encodes a brand for the `?brand=` query value (base64url JSON), or null when empty or too long. */\nexport function encodeHostBrand(brand: CrmHostBrand | undefined | null): string | null {\n const clean = normalizeHostBrand(brand);\n if (!clean) return null;\n const bytes = new TextEncoder().encode(JSON.stringify(clean));\n let bin = '';\n bytes.forEach((b) => { bin += String.fromCharCode(b); });\n const encoded = btoa(bin).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n return encoded.length <= BRAND_PARAM_MAX ? encoded : null;\n}\n\n/**\n * Keeps only values the CRM understands: a known theme, a well-formed language tag and a\n * valid brand. Anything else is dropped, so a bad value can never reach the iframe URL or\n * the message. `brand: null` is kept so a message can clear an earlier brand.\n */\nexport function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext {\n const out: CrmHostContext = {};\n if (ctx?.brand === null) out.brand = null;\n else {\n const brand = normalizeHostBrand(ctx?.brand);\n if (brand) out.brand = brand;\n }\n if (ctx?.theme && HOST_THEMES.includes(ctx.theme)) out.theme = ctx.theme;\n if (typeof ctx?.locale === 'string' && BCP47_LIKE.test(ctx.locale.trim())) out.locale = ctx.locale.trim();\n return out;\n}\n\n/** `theme`, `locale` and `brand` as URL query pairs (e.g. `[\"theme=dark\", \"locale=zh-CN\", \"brand=eyJ...\"]`). */\nexport function hostContextQuery(ctx: CrmHostContext | undefined): string[] {\n const clean = normalizeHostContext(ctx);\n const pairs: string[] = [];\n if (clean.theme) pairs.push(`theme=${encodeURIComponent(clean.theme)}`);\n if (clean.locale) pairs.push(`locale=${encodeURIComponent(clean.locale)}`);\n const brand = clean.brand ? encodeHostBrand(clean.brand) : null;\n if (brand) pairs.push(`brand=${brand}`);\n return pairs;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /** Initial theme/locale, sent to the CRM once the channel is up. Change it with `setContext()`. */\n hostContext?: CrmHostContext;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /**\n * Update the theme and/or language of the embedded CRM. Sent over the established\n * channel only, never broadcast with a wildcard origin. Fields you leave out keep\n * their last value; before the channel is up the latest values go out on connect.\n */\n setContext: (ctx: CrmHostContext) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n const result = body as Partial<CrmSessionResult>;\n // A malformed 2xx (e.g. `{}`) would otherwise cast cleanly and later build an\n // `/embed/undefined` URL — fail at the boundary with a clear message instead.\n if (typeof result?.accessToken !== 'string' || typeof result?.workspaceId !== 'string') {\n throw new Error('CRM session response is missing accessToken/workspaceId');\n }\n return result as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n let context: CrmHostContext = normalizeHostContext(opts.hostContext);\n\n function sendContext(extra?: { brand: null }): void {\n if (extra) {\n port?.postMessage({ type: 'crm:host-context', ...context, ...extra } satisfies CrmHostContextMessage);\n return;\n }\n if (!port || (context.theme === undefined && context.locale === undefined && context.brand === undefined)) return;\n const msg: CrmHostContextMessage = { type: 'crm:host-context', ...context };\n port.postMessage(msg);\n }\n\n async function deliverBearer(): Promise<boolean> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n sendContext();\n return true;\n } catch (err) {\n opts.onError?.(err);\n return false;\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow). Only tell the\n // CRM the session refreshed once a fresh bearer was ACTUALLY delivered —\n // otherwise a failed re-mint leaves the iframe believing it's authenticated.\n void deliverBearer().then((ok) => {\n if (ok) port?.postMessage({ type: 'session-refreshed' });\n });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n setContext(ctx: CrmHostContext): void {\n const next = normalizeHostContext(ctx);\n context = { ...context, ...next };\n if (next.brand === null) delete context.brand; // cleared: send null once, then forget it\n sendContext(next.brand === null ? { brand: null } : undefined);\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"mbAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,cAAAE,EAAA,eAAAC,EAAA,YAAAC,KAAA,eAAAC,GAAAL,IAwBA,IAAAM,EAEO,iBCwDP,IAAMC,GAAiC,CAAC,QAAS,OAAQ,QAAQ,EAC3DC,GAAa,4CAEbC,GAAY,kCACZC,GAAY,8BACZC,GAAa,uBAInB,IAAMC,GAAmB,CACvB,SAAU,mBAAoB,aAAc,UAAW,SAAU,aAAc,iBACjF,EAEA,SAASC,EAAUC,EAAoC,CACrD,GAAI,OAAOA,GAAU,SAAU,OAC/B,IAAMC,EAAID,EAAM,KAAK,EACrB,GAAI,GAACC,GAAKA,EAAE,OAAS,KAAY,CAACC,GAAW,KAAKD,CAAC,IAC9C,GAAAA,EAAE,MAAM,IAAI,GAAG,QAAU,GAAK,IAAM,IAAMA,EAAE,MAAM,IAAI,GAAG,QAAU,GAAK,IAAM,GACnF,OAAOA,CACT,CAMO,SAASE,EAAmBC,EAAkE,CACnG,GAAI,CAACA,GAAS,OAAOA,GAAU,UAAY,MAAM,QAAQA,CAAK,EAAG,OACjE,IAAMC,EAAoB,CAAC,EAC3B,QAAWC,KAAOR,GAAkB,CAClC,IAAMS,EAAMH,EAAME,CAAG,EACrB,GAAI,OAAOC,GAAQ,UAAYC,GAAU,KAAKD,EAAI,KAAK,CAAC,EAAG,CACzD,IAAIE,EAAMF,EAAI,KAAK,EAAE,YAAY,EAC7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AAUJ,CAAI,CAAG,EAC7D,QAAUjC,GAAQ,CAChB,IAAMiD,EAAIlD,EAAQC,CAAG,EACrB4B,EAASqB,CAAC,EACVb,EAAW,UAAUa,CAAC,CACxB,CACF,CAAC,CACH,OAASjD,EAAK,CACZ,IAAMiD,EAAIlD,EAAQC,CAAG,EACrB4B,EAASqB,CAAC,EACVb,EAAW,UAAUa,CAAC,EACtB,MACF,CAEA,OAAAjB,EAAQ,QAAUmB,EAGlBhB,EAAW,UAAU,CAAE,YAAAT,CAAY,CAAC,EAE7B,IAAM,CACXyB,GAAM,QAAQ,EACdnB,EAAQ,QAAU,IACpB,CACF,EAAG,CAACR,EAAUE,EAAajB,CAAc,CAAC,EAI1C,IAAM6C,GAAW,KAAK,UAAUlC,GAAS,IAAI,EACvCmC,KAAc,UAAO,EAAK,EAShC,SARA,aAAU,IAAM,CAEd,IAAMC,EAAcpC,EAAQ,CAAE,MAAAA,CAAM,EAAKmC,EAAY,QAAU,CAAE,MAAO,IAAK,EAAI,CAAC,EAClFA,EAAY,QAAU,CAAC,CAACnC,EACxBY,EAAQ,SAAS,WAAW,CAAE,MAAAd,EAAO,OAAAC,EAAQ,GAAGqC,CAAY,CAAC,CAE/D,EAAG,CAACtC,EAAOC,EAAQmC,EAAQ,CAAC,EAExBnD,KACK,mBAAG,SAAAmB,EAAcA,EAAYnB,EAAOC,CAAK,EAAIF,GAAaC,EAAOC,CAAK,EAAE,EAG5EoB,KAKH,OAAC,UACC,IAAKD,EACL,IAAKC,EACL,MAAOZ,EACP,UAAWF,EACX,MAAO,CAAE,GAAGZ,GAAsB,GAAGa,CAAM,EAC7C,KAVO,mBAAG,SAAAU,EAAgBA,EAAc,EAAIpB,GAAe,EAAE,CAYjE,CACF,EAEOwD,GAAQpD","names":["embed_react_exports","__export","CrmEmbed","crmSession","embed_react_default","__toCommonJS","import_react","HOST_THEMES","BCP47_LIKE","HEX_COLOR","RADIUS_PX","FONT_CHARS","BRAND_COLOR_KEYS","cleanFont","value","v","FONT_CHARS","normalizeHostBrand","brand","out","key","raw","HEX_COLOR","hex","m","RADIUS_PX","fontFamily","displayFontFamily","encodeHostBrand","clean","bytes","bin","b","encoded","normalizeHostContext","ctx","HOST_THEMES","BCP47_LIKE","hostContextQuery","pairs","isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","context","sendContext","extra","msg","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path","next","import_jsx_runtime","DEFAULT_IFRAME_STYLE","toError","err","DefaultLoading","DefaultError","error","retry","CrmEmbed","props","ref","getSession","crmEmbedOrigin","className","style","title","onReady","onError","onRouteChange","hostProvidesNav","initialPath","theme","locale","brand","renderLoading","renderError","iframeRef","embedUrl","setEmbedUrl","workspaceId","setWorkspaceId","setError","attempt","setAttempt","primedBearerRef","hostRef","path","getSessionRef","onReadyRef","onErrorRef","onRouteChangeRef","initialPathRef","hostContextRef","n","cancelled","session","base","buildCrmEmbedUrl","query","hostContextQuery","separator","url","e","iframe","host","createCrmEmbedHost","primed","brandKey","hadBrandRef","brandUpdate","embed_react_default"]}
@@ -1,6 +1,36 @@
1
1
  import * as react from 'react';
2
2
  import { CSSProperties, ReactNode } from 'react';
3
3
 
4
+ /** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */
5
+ type CrmHostTheme = 'light' | 'dark' | 'system';
6
+ /**
7
+ * Brand tokens that make the embedded CRM look like part of the host. All optional.
8
+ * Colours are `#rgb` or `#rrggbb`; invalid values are dropped, never sent.
9
+ * Pass the values for the host's CURRENT theme and send a new brand when it toggles.
10
+ * No remote font is loaded: a family the visitor's system lacks falls back to the CRM's.
11
+ */
12
+ interface CrmHostBrand {
13
+ /** Buttons, selected tabs, focus rings, chart accent. */
14
+ accent?: string;
15
+ /** Text on the accent. Defaults to white or near-black, whichever reads better. */
16
+ accentForeground?: string;
17
+ /** Page background. */
18
+ background?: string;
19
+ /** Cards, popovers and inputs. Defaults to `background`. */
20
+ surface?: string;
21
+ /** Hairlines and input borders. Derived from background and foreground when omitted. */
22
+ border?: string;
23
+ /** Body text. */
24
+ foreground?: string;
25
+ /** Secondary text. Derived when omitted. */
26
+ mutedForeground?: string;
27
+ /** Corner radius for controls, `0px` to `24px`, e.g. `"6px"`. Larger surfaces scale from it. */
28
+ radius?: string;
29
+ /** UI font family list, e.g. `"Inter, system-ui"`. Letters, digits, spaces, commas, quotes, hyphens, underscores; max 160 chars. */
30
+ fontFamily?: string;
31
+ /** Font for page titles, same rules as `fontFamily`, e.g. `"Fraunces, Georgia, serif"`. */
32
+ displayFontFamily?: string;
33
+ }
4
34
  /** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */
5
35
  interface CrmSessionResult {
6
36
  accessToken: string;
@@ -75,6 +105,27 @@ interface CrmEmbedProps {
75
105
  * iframe; use the ref's `navigate()` for in-session navigation.
76
106
  */
77
107
  initialPath?: string;
108
+ /**
109
+ * Theme for the embedded CRM: `light`, `dark`, or `system` (follow the visitor's OS).
110
+ * The first value rides on the iframe URL as `?theme=`; a later change is posted to
111
+ * the frame over the channel (`crm:host-context`) without reloading it. The CRM applies
112
+ * it for the embed only and never saves it to the user's account. Omitted: the CRM keeps
113
+ * its default (light) look.
114
+ */
115
+ theme?: CrmHostTheme;
116
+ /**
117
+ * Language for the embedded CRM as a BCP 47 tag, e.g. "en" or "zh-CN". Sent like `theme`
118
+ * (`?locale=`, then `crm:host-context`). Omitted: the CRM keeps its own language.
119
+ */
120
+ locale?: string;
121
+ /**
122
+ * Brand tokens (accent, surfaces, border, radius, fonts) so the CRM looks like part of
123
+ * your app. First value rides on the iframe URL as `?brand=` (base64url JSON); changes
124
+ * are posted over the channel without a reload. Invalid fields are dropped. Pass the
125
+ * tokens for your CURRENT theme and change the object when the theme toggles. See
126
+ * {@link CrmHostBrand}. Omitted: the CRM keeps its own look.
127
+ */
128
+ brand?: CrmHostBrand;
78
129
  /** Custom loading UI. Defaults to a minimal message. */
79
130
  renderLoading?: () => ReactNode;
80
131
  /** Custom error UI. Defaults to the message + a Retry button. */
@@ -88,4 +139,4 @@ interface CrmEmbedProps {
88
139
  */
89
140
  declare const CrmEmbed: react.ForwardRefExoticComponent<CrmEmbedProps & react.RefAttributes<CrmEmbedHandle>>;
90
141
 
91
- export { CrmEmbed, type CrmEmbedHandle, type CrmEmbedProps, type CrmEmbedSession, type CrmSessionResult, crmSession, CrmEmbed as default };
142
+ export { CrmEmbed, type CrmEmbedHandle, type CrmEmbedProps, type CrmEmbedSession, type CrmHostBrand, type CrmHostTheme, type CrmSessionResult, crmSession, CrmEmbed as default };
@@ -1,6 +1,36 @@
1
1
  import * as react from 'react';
2
2
  import { CSSProperties, ReactNode } from 'react';
3
3
 
4
+ /** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */
5
+ type CrmHostTheme = 'light' | 'dark' | 'system';
6
+ /**
7
+ * Brand tokens that make the embedded CRM look like part of the host. All optional.
8
+ * Colours are `#rgb` or `#rrggbb`; invalid values are dropped, never sent.
9
+ * Pass the values for the host's CURRENT theme and send a new brand when it toggles.
10
+ * No remote font is loaded: a family the visitor's system lacks falls back to the CRM's.
11
+ */
12
+ interface CrmHostBrand {
13
+ /** Buttons, selected tabs, focus rings, chart accent. */
14
+ accent?: string;
15
+ /** Text on the accent. Defaults to white or near-black, whichever reads better. */
16
+ accentForeground?: string;
17
+ /** Page background. */
18
+ background?: string;
19
+ /** Cards, popovers and inputs. Defaults to `background`. */
20
+ surface?: string;
21
+ /** Hairlines and input borders. Derived from background and foreground when omitted. */
22
+ border?: string;
23
+ /** Body text. */
24
+ foreground?: string;
25
+ /** Secondary text. Derived when omitted. */
26
+ mutedForeground?: string;
27
+ /** Corner radius for controls, `0px` to `24px`, e.g. `"6px"`. Larger surfaces scale from it. */
28
+ radius?: string;
29
+ /** UI font family list, e.g. `"Inter, system-ui"`. Letters, digits, spaces, commas, quotes, hyphens, underscores; max 160 chars. */
30
+ fontFamily?: string;
31
+ /** Font for page titles, same rules as `fontFamily`, e.g. `"Fraunces, Georgia, serif"`. */
32
+ displayFontFamily?: string;
33
+ }
4
34
  /** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */
5
35
  interface CrmSessionResult {
6
36
  accessToken: string;
@@ -75,6 +105,27 @@ interface CrmEmbedProps {
75
105
  * iframe; use the ref's `navigate()` for in-session navigation.
76
106
  */
77
107
  initialPath?: string;
108
+ /**
109
+ * Theme for the embedded CRM: `light`, `dark`, or `system` (follow the visitor's OS).
110
+ * The first value rides on the iframe URL as `?theme=`; a later change is posted to
111
+ * the frame over the channel (`crm:host-context`) without reloading it. The CRM applies
112
+ * it for the embed only and never saves it to the user's account. Omitted: the CRM keeps
113
+ * its default (light) look.
114
+ */
115
+ theme?: CrmHostTheme;
116
+ /**
117
+ * Language for the embedded CRM as a BCP 47 tag, e.g. "en" or "zh-CN". Sent like `theme`
118
+ * (`?locale=`, then `crm:host-context`). Omitted: the CRM keeps its own language.
119
+ */
120
+ locale?: string;
121
+ /**
122
+ * Brand tokens (accent, surfaces, border, radius, fonts) so the CRM looks like part of
123
+ * your app. First value rides on the iframe URL as `?brand=` (base64url JSON); changes
124
+ * are posted over the channel without a reload. Invalid fields are dropped. Pass the
125
+ * tokens for your CURRENT theme and change the object when the theme toggles. See
126
+ * {@link CrmHostBrand}. Omitted: the CRM keeps its own look.
127
+ */
128
+ brand?: CrmHostBrand;
78
129
  /** Custom loading UI. Defaults to a minimal message. */
79
130
  renderLoading?: () => ReactNode;
80
131
  /** Custom error UI. Defaults to the message + a Retry button. */
@@ -88,4 +139,4 @@ interface CrmEmbedProps {
88
139
  */
89
140
  declare const CrmEmbed: react.ForwardRefExoticComponent<CrmEmbedProps & react.RefAttributes<CrmEmbedHandle>>;
90
141
 
91
- export { CrmEmbed, type CrmEmbedHandle, type CrmEmbedProps, type CrmEmbedSession, type CrmSessionResult, crmSession, CrmEmbed as default };
142
+ export { CrmEmbed, type CrmEmbedHandle, type CrmEmbedProps, type CrmEmbedSession, type CrmHostBrand, type CrmHostTheme, type CrmSessionResult, crmSession, CrmEmbed as default };
@@ -1,2 +1,2 @@
1
- import{forwardRef as G,useCallback as J,useEffect as H,useImperativeHandle as K,useRef as l,useState as k}from"react";function q(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function Y(e,s){return async()=>{let u=await fetch(e,{method:"POST",...s}),m=await u.json().catch(()=>({}));if(!u.ok){let c=m?.error;throw new Error(c?`CRM session failed: ${c}`:`CRM session failed (HTTP ${u.status})`)}let r=m;if(typeof r?.accessToken!="string"||typeof r?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return r}}function $(e,s){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(s)}`}function W(e){let s=e.windowTarget??window,u=e.createChannel??(()=>new MessageChannel),m=e.devAllowAnyOrigin?"*":e.crmOrigin,r=null,c="",p=!1;async function C(){try{let n=await e.getBearer();return r?.postMessage({type:"auth-tokens",accessToken:n.accessToken,refreshToken:n.refreshToken??""}),!0}catch(n){return e.onError?.(n),!1}}function h(n){let o=n.data;if(o)if(o.type==="channel-ack"){if(o.nonce!==c)return;C()}else o.type==="route-change"?e.onRouteChange?.(o.path):o.type==="resize"?e.onResize?.(o.height):o.type==="session-expired"&&C().then(y=>{y&&r?.postMessage({type:"session-refreshed"})})}function E(){r?.close();let n=u();r=n.port1,c=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,r.onmessage=h,r.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:c},m,[n.port2])}function g(n){p||n.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&n.origin!==e.crmOrigin||q(n.data)&&E())}return s.addEventListener("message",g),{navigate(n){r?.postMessage({type:"navigate",path:n})},dispose(){p=!0,s.removeEventListener("message",g),r?.close(),r=null}}}import{Fragment as D,jsx as f,jsxs as z}from"react/jsx-runtime";var Q={width:"100%",height:"100%",border:0};function I(e){return e instanceof Error?e:new Error(String(e))}function V(){return f("div",{children:"Loading CRM\u2026"})}function X(e,s){return z("div",{children:[z("p",{children:["Couldn\u2019t load the CRM: ",e.message]}),f("button",{type:"button",onClick:s,children:"Try again"})]})}var Z=G(function(s,u){let{getSession:m,crmEmbedOrigin:r,className:c,style:p,title:C="CRM",onReady:h,onError:E,onRouteChange:g,hostProvidesNav:n,initialPath:o,renderLoading:y,renderError:x}=s,L=l(null),[R,O]=k(null),[M,N]=k(null),[S,v]=k(null),[F,_]=k(0),b=l(null),T=l(null);K(u,()=>({navigate:i=>{T.current?.navigate(i)}}),[]);let P=l(m),A=l(h),w=l(E),B=l(g);H(()=>{P.current=m,A.current=h,w.current=E,B.current=g});let j=l(o),U=J(()=>{b.current=null,v(null),O(null),N(null),_(i=>i+1)},[]);return H(()=>{let i=!1;return(async()=>{try{let a=await P.current();if(i)return;b.current={accessToken:a.accessToken},N(a.workspaceId);let d=$(r,a.workspaceId)+(j.current??"")+(n?"?hostnav=1":"");O(d)}catch(a){if(i)return;let t=I(a);v(t),w.current?.(t)}})(),()=>{i=!0}},[r,n,F]),H(()=>{let i=L.current;if(!i||!R||!M)return;let a=null;try{a=W({iframe:i,crmOrigin:r,getBearer:async()=>{let t=b.current;return t?(b.current=null,t):{accessToken:(await P.current()).accessToken}},onRouteChange:t=>{B.current?.(t)},onError:t=>{let d=I(t);v(d),w.current?.(d)}})}catch(t){let d=I(t);v(d),w.current?.(d);return}return T.current=a,A.current?.({workspaceId:M}),()=>{a?.dispose(),T.current=null}},[R,M,r]),S?f(D,{children:x?x(S,U):X(S,U)}):R?f("iframe",{ref:L,src:R,title:C,className:c,style:{...Q,...p}}):f(D,{children:y?y():V()})}),te=Z;export{Z as CrmEmbed,Y as crmSession,te as default};
1
+ import{forwardRef as fe,useCallback as ge,useEffect as M,useImperativeHandle as Ce,useRef as m,useState as T}from"react";var oe=["light","dark","system"],se=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/,ie=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i,ae=/^(\d{1,2}(?:\.\d{1,2})?)px$/,ce=/^[A-Za-z0-9 ,'"_-]+$/;var de=["accent","accentForeground","background","surface","border","foreground","mutedForeground"];function j(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||t.length>160||!ce.test(t))&&!((t.match(/"/g)?.length??0)%2!==0||(t.match(/'/g)?.length??0)%2!==0))return t}function K(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of de){let a=e[n];if(typeof a=="string"&&ie.test(a.trim())){let c=a.trim().toLowerCase();c.length===4&&(c=`#${c[1]}${c[1]}${c[2]}${c[2]}${c[3]}${c[3]}`),t[n]=c}}if(typeof e.radius=="string"){let n=ae.exec(e.radius.trim());n&&Number(n[1])<=24&&(t.radius=`${Number(n[1])}px`)}let o=j(e.fontFamily);o&&(t.fontFamily=o);let i=j(e.displayFontFamily);return i&&(t.displayFontFamily=i),Object.keys(t).length>0?t:void 0}function le(e){let t=K(e);if(!t)return null;let o=new TextEncoder().encode(JSON.stringify(t)),i="";o.forEach(a=>{i+=String.fromCharCode(a)});let n=btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return n.length<=1500?n:null}function F(e){let t={};if(e?.brand===null)t.brand=null;else{let o=K(e?.brand);o&&(t.brand=o)}return e?.theme&&oe.includes(e.theme)&&(t.theme=e.theme),typeof e?.locale=="string"&&se.test(e.locale.trim())&&(t.locale=e.locale.trim()),t}function Z(e){let t=F(e),o=[];t.theme&&o.push(`theme=${encodeURIComponent(t.theme)}`),t.locale&&o.push(`locale=${encodeURIComponent(t.locale)}`);let i=t.brand?le(t.brand):null;return i&&o.push(`brand=${i}`),o}function ue(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function me(e,t){return async()=>{let o=await fetch(e,{method:"POST",...t}),i=await o.json().catch(()=>({}));if(!o.ok){let a=i?.error;throw new Error(a?`CRM session failed: ${a}`:`CRM session failed (HTTP ${o.status})`)}let n=i;if(typeof n?.accessToken!="string"||typeof n?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return n}}function q(e,t){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(t)}`}function J(e){let t=e.windowTarget??window,o=e.createChannel??(()=>new MessageChannel),i=e.devAllowAnyOrigin?"*":e.crmOrigin,n=null,a="",c=!1,u=F(e.hostContext);function p(r){if(r){n?.postMessage({type:"crm:host-context",...u,...r});return}if(!n||u.theme===void 0&&u.locale===void 0&&u.brand===void 0)return;let s={type:"crm:host-context",...u};n.postMessage(s)}async function h(){try{let r=await e.getBearer();return n?.postMessage({type:"auth-tokens",accessToken:r.accessToken,refreshToken:r.refreshToken??""}),p(),!0}catch(r){return e.onError?.(r),!1}}function b(r){let s=r.data;if(s)if(s.type==="channel-ack"){if(s.nonce!==a)return;h()}else s.type==="route-change"?e.onRouteChange?.(s.path):s.type==="resize"?e.onResize?.(s.height):s.type==="session-expired"&&h().then(C=>{C&&n?.postMessage({type:"session-refreshed"})})}function E(){n?.close();let r=o();n=r.port1,a=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,n.onmessage=b,n.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:a},i,[r.port2])}function R(r){c||r.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&r.origin!==e.crmOrigin||ue(r.data)&&E())}return t.addEventListener("message",R),{navigate(r){n?.postMessage({type:"navigate",path:r})},setContext(r){let s=F(r);u={...u,...s},s.brand===null&&delete u.brand,p(s.brand===null?{brand:null}:void 0)},dispose(){c=!0,t.removeEventListener("message",R),n?.close(),n=null}}}import{Fragment as Y,jsx as y,jsxs as Q}from"react/jsx-runtime";var pe={width:"100%",height:"100%",border:0};function O(e){return e instanceof Error?e:new Error(String(e))}function he(){return y("div",{children:"Loading CRM\u2026"})}function ye(e,t){return Q("div",{children:[Q("p",{children:["Couldn\u2019t load the CRM: ",e.message]}),y("button",{type:"button",onClick:t,children:"Try again"})]})}var be=fe(function(t,o){let{getSession:i,crmEmbedOrigin:n,className:a,style:c,title:u="CRM",onReady:p,onError:h,onRouteChange:b,hostProvidesNav:E,initialPath:R,theme:r,locale:s,brand:C,renderLoading:N,renderError:$}=t,I=m(null),[x,L]=T(null),[S,_]=T(null),[A,v]=T(null),[G,V]=T(0),H=m(null),k=m(null);Ce(o,()=>({navigate:l=>{k.current?.navigate(l)}}),[]);let B=m(i),U=m(p),w=m(h),z=m(b);M(()=>{B.current=i,U.current=p,w.current=h,z.current=b});let ee=m(R),P=m({theme:r,locale:s,brand:C});P.current={theme:r,locale:s,brand:C};let D=ge(()=>{H.current=null,v(null),L(null),_(null),V(l=>l+1)},[]);M(()=>{let l=!1;return(async()=>{try{let f=await B.current();if(l)return;H.current={accessToken:f.accessToken},_(f.workspaceId);let d=q(n,f.workspaceId),g=ee.current??"",W=[...E?["hostnav=1"]:[],...Z(P.current)],ne=g.includes("?")?"&":"?",re=d+g+(W.length>0?ne+W.join("&"):"");L(re)}catch(f){if(l)return;let d=O(f);v(d),w.current?.(d)}})(),()=>{l=!0}},[n,E,G]),M(()=>{let l=I.current;if(!l||!x||!S)return;let f=null;try{f=J({iframe:l,crmOrigin:n,getBearer:async()=>{let d=H.current;return d?(H.current=null,d):{accessToken:(await B.current()).accessToken}},hostContext:P.current,onRouteChange:d=>{z.current?.(d)},onError:d=>{let g=O(d);v(g),w.current?.(g)}})}catch(d){let g=O(d);v(g),w.current?.(g);return}return k.current=f,U.current?.({workspaceId:S}),()=>{f?.dispose(),k.current=null}},[x,S,n]);let te=JSON.stringify(C??null),X=m(!1);return M(()=>{let l=C?{brand:C}:X.current?{brand:null}:{};X.current=!!C,k.current?.setContext({theme:r,locale:s,...l})},[r,s,te]),A?y(Y,{children:$?$(A,D):ye(A,D)}):x?y("iframe",{ref:I,src:x,title:u,className:a,style:{...pe,...c}}):y(Y,{children:N?N():he()})}),ve=be;export{be as CrmEmbed,me as crmSession,ve as default};
2
2
  //# sourceMappingURL=embed-react.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/embed-react.tsx","../src/embed-host.ts"],"sourcesContent":["/**\n * Drop-in React component that embeds the First To Fly CRM as a cross-origin\n * iframe, authenticated WITHOUT cookies.\n *\n * This wraps the low-level {@link ./embed-host | embed-host} helpers into a\n * single component. You supply a `getSession()` that returns a CRM bearer plus\n * the workspace to embed (typically by calling your own backend endpoint that\n * runs `createEmbedSessionWithKey`), and the component handles:\n * - resolving the session and building the iframe URL,\n * - rendering the iframe and running the MessageChannel handshake,\n * - reusing the initial bearer (no double-mint) and re-minting on expiry,\n * - loading / error / retry states.\n *\n * A host (e.g. an app shell) can drive the embedded CRM's section navigation\n * imperatively via a ref (`navigate(path)`), observe the CRM's own navigation\n * via `onRouteChange`, deep-link an `initialPath` on first load, and hide the\n * CRM's in-iframe nav via `hostProvidesNav` (when the host supplies its own).\n *\n * `react` is an OPTIONAL peer dependency — only pull in this entry if you use\n * React. Non-React consumers can keep using `./embed-host` directly.\n *\n * @packageDocumentation\n */\n\nimport {\n forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState,\n} from 'react';\nimport type { CSSProperties, ReactNode } from 'react';\n\nimport {\n buildCrmEmbedUrl,\n createCrmEmbedHost,\n crmSession,\n type CrmBearer,\n type CrmEmbedHost,\n type CrmSessionResult,\n} from './embed-host';\n\n// Re-export the session-fetch helper so React users can get it from one entry:\n// import { CrmEmbed, crmSession } from '@first-to-fly/crm-sdk/embed-react';\nexport { crmSession, type CrmSessionResult };\n\n/**\n * What a partner's `getSession()` must resolve to. Alias of {@link CrmSessionResult}\n * (the browser-side session shape) — kept as a named export for back-compat; both\n * are `{ accessToken, workspaceId, expiresIn? }`.\n */\nexport type CrmEmbedSession = CrmSessionResult;\n\n/**\n * Imperative handle exposed via `ref`. Lets a host drive the embedded CRM's\n * navigation without re-rendering the iframe.\n */\nexport interface CrmEmbedHandle {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n}\n\nexport interface CrmEmbedProps {\n /**\n * Resolves a CRM bearer + the workspace to embed. Called once on mount (and\n * again on retry / session expiry). Typically calls your own backend endpoint\n * that runs `createEmbedSessionWithKey`.\n */\n getSession: () => Promise<CrmEmbedSession>;\n /**\n * The CRM embed base origin, e.g. \"https://crm.example.com\". The iframe URL\n * is `buildCrmEmbedUrl(crmEmbedOrigin, workspaceId)` and this origin is also\n * used as the postMessage targetOrigin.\n */\n crmEmbedOrigin: string;\n /** Class applied to the iframe. */\n className?: string;\n /** Inline style merged onto the iframe (overrides the fill-container default). */\n style?: CSSProperties;\n /** Iframe title (accessibility). Defaults to \"CRM\". */\n title?: string;\n /** Called after the iframe URL is built and mounted. */\n onReady?: (info: { workspaceId: string }) => void;\n /** Called on any session / handshake error. */\n onError?: (error: Error) => void;\n /**\n * Called when the CRM navigates internally (e.g. \"/contacts\"). Use this to\n * keep a host-supplied nav in sync with the embedded CRM's current section.\n */\n onRouteChange?: (path: string) => void;\n /**\n * When true, the CRM hides its own in-iframe nav (the host supplies it).\n * Signalled to the CRM by appending `?hostnav=1` to the iframe URL. Drive\n * navigation yourself via the ref's `navigate()`.\n */\n hostProvidesNav?: boolean;\n /**\n * Initial CRM sub-path to deep-link on FIRST load (e.g. \"/contacts\").\n * Only applied to the initial iframe URL — later changes do NOT reload the\n * iframe; use the ref's `navigate()` for in-session navigation.\n */\n initialPath?: string;\n /** Custom loading UI. Defaults to a minimal message. */\n renderLoading?: () => ReactNode;\n /** Custom error UI. Defaults to the message + a Retry button. */\n renderError?: (error: Error, retry: () => void) => ReactNode;\n}\n\nconst DEFAULT_IFRAME_STYLE: CSSProperties = {\n width: '100%',\n height: '100%',\n border: 0,\n};\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n\nfunction DefaultLoading(): ReactNode {\n return <div>Loading CRM…</div>;\n}\n\nfunction DefaultError(error: Error, retry: () => void): ReactNode {\n return (\n <div>\n <p>Couldn’t load the CRM: {error.message}</p>\n <button type=\"button\" onClick={retry}>Try again</button>\n </div>\n );\n}\n\n/**\n * Embed the First To Fly CRM in a React app. See {@link CrmEmbedProps}.\n *\n * Accepts a `ref` of type {@link CrmEmbedHandle} exposing `navigate(path)` so a\n * host can drive the embedded CRM's section navigation.\n */\nexport const CrmEmbed = forwardRef<CrmEmbedHandle, CrmEmbedProps>(\n function CrmEmbed(props, ref): ReactNode {\n const {\n getSession,\n crmEmbedOrigin,\n className,\n style,\n title = 'CRM',\n onReady,\n onError,\n onRouteChange,\n hostProvidesNav,\n initialPath,\n renderLoading,\n renderError,\n } = props;\n\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const [embedUrl, setEmbedUrl] = useState<string | null>(null);\n const [workspaceId, setWorkspaceId] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [attempt, setAttempt] = useState(0);\n\n // Bearer minted during session resolution — reused for the host's first\n // getBearer() so a single getSession() call covers both phases (no double-mint).\n const primedBearerRef = useRef<CrmBearer | null>(null);\n\n // The created host, so the imperative `navigate()` can reach it.\n const hostRef = useRef<CrmEmbedHost | null>(null);\n\n // Expose the imperative navigate(). No-ops safely before the host is wired.\n useImperativeHandle(ref, () => ({\n navigate: (path: string) => { hostRef.current?.navigate(path); },\n }), []);\n\n // Keep the latest callbacks in refs so the effects DON'T depend on their\n // identity. Partners routinely pass inline `getSession`/`onReady`/`onError`/\n // `onRouteChange`; depending on them directly would re-run Phase 1 (re-fetch\n // the session) and tear down + recreate the host on every parent re-render.\n const getSessionRef = useRef(getSession);\n const onReadyRef = useRef(onReady);\n const onErrorRef = useRef(onError);\n const onRouteChangeRef = useRef(onRouteChange);\n useEffect(() => {\n getSessionRef.current = getSession;\n onReadyRef.current = onReady;\n onErrorRef.current = onError;\n onRouteChangeRef.current = onRouteChange;\n });\n\n // Capture initialPath ONCE — it only seeds the first load. Later changes go\n // through the imperative navigate() and must NOT rebuild/reload the iframe.\n const initialPathRef = useRef(initialPath);\n\n const retry = useCallback(() => {\n primedBearerRef.current = null;\n setError(null);\n setEmbedUrl(null);\n setWorkspaceId(null);\n setAttempt((n) => n + 1);\n }, []);\n\n // Phase 1: resolve the session, prime the bearer, and build the iframe URL.\n // Re-runs only on retry (`attempt`) or a changed origin/hostnav — never on\n // unrelated parent re-renders (callbacks + initialPath are read from refs).\n useEffect(() => {\n let cancelled = false;\n\n void (async () => {\n try {\n const session = await getSessionRef.current();\n if (cancelled) return;\n primedBearerRef.current = { accessToken: session.accessToken };\n setWorkspaceId(session.workspaceId);\n const base = buildCrmEmbedUrl(crmEmbedOrigin, session.workspaceId);\n const url = base + (initialPathRef.current ?? '') + (hostProvidesNav ? '?hostnav=1' : '');\n setEmbedUrl(url);\n } catch (err) {\n if (cancelled) return;\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n }\n })();\n\n return () => { cancelled = true; };\n }, [crmEmbedOrigin, hostProvidesNav, attempt]);\n\n // Phase 2: once the iframe URL is known, wire the MessageChannel host.\n useEffect(() => {\n const iframe = iframeRef.current;\n if (!iframe || !embedUrl || !workspaceId) return undefined;\n\n let host: CrmEmbedHost | null = null;\n try {\n host = createCrmEmbedHost({\n iframe,\n crmOrigin: crmEmbedOrigin,\n getBearer: async () => {\n const primed = primedBearerRef.current;\n if (primed) {\n primedBearerRef.current = null;\n return primed;\n }\n const session = await getSessionRef.current();\n return { accessToken: session.accessToken };\n },\n onRouteChange: (path) => { onRouteChangeRef.current?.(path); },\n onError: (err) => {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n },\n });\n } catch (err) {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n return undefined;\n }\n\n hostRef.current = host;\n\n // Only signal ready once the host is actually wired.\n onReadyRef.current?.({ workspaceId });\n\n return () => {\n host?.dispose();\n hostRef.current = null;\n };\n }, [embedUrl, workspaceId, crmEmbedOrigin]);\n\n if (error) {\n return <>{renderError ? renderError(error, retry) : DefaultError(error, retry)}</>;\n }\n\n if (!embedUrl) {\n return <>{renderLoading ? renderLoading() : DefaultLoading()}</>;\n }\n\n return (\n <iframe\n ref={iframeRef}\n src={embedUrl}\n title={title}\n className={className}\n style={{ ...DEFAULT_IFRAME_STYLE, ...style }}\n />\n );\n },\n);\n\nexport default CrmEmbed;\n","/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n const result = body as Partial<CrmSessionResult>;\n // A malformed 2xx (e.g. `{}`) would otherwise cast cleanly and later build an\n // `/embed/undefined` URL — fail at the boundary with a clear message instead.\n if (typeof result?.accessToken !== 'string' || typeof result?.workspaceId !== 'string') {\n throw new Error('CRM session response is missing accessToken/workspaceId');\n }\n return result as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n\n async function deliverBearer(): Promise<boolean> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n return true;\n } catch (err) {\n opts.onError?.(err);\n return false;\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow). Only tell the\n // CRM the session refreshed once a fresh bearer was ACTUALLY delivered —\n // otherwise a failed re-mint leaves the iframe believing it's authenticated.\n void deliverBearer().then((ok) => {\n if (ok) port?.postMessage({ type: 'session-refreshed' });\n });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"AAwBA,OACE,cAAAA,EAAY,eAAAC,EAAa,aAAAC,EAAW,uBAAAC,EAAqB,UAAAC,EAAQ,YAAAC,MAC5D,QC6CP,SAASC,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CAmBO,SAASC,EACdC,EACAC,EACiC,CACjC,MAAO,UAAuC,CAC5C,IAAMC,EAAM,MAAM,MAAMF,EAAK,CAAE,OAAQ,OAAQ,GAAGC,CAAK,CAAC,EAClDE,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,GAAI,CAACA,EAAI,GAAI,CACX,IAAME,EAAQD,GAA6B,MAC3C,MAAM,IAAI,MACRC,EAAO,uBAAuBA,CAAI,GAAK,4BAA4BF,EAAI,MAAM,GAC/E,CACF,CACA,IAAMG,EAASF,EAGf,GAAI,OAAOE,GAAQ,aAAgB,UAAY,OAAOA,GAAQ,aAAgB,SAC5E,MAAM,IAAI,MAAM,y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ef","useState","isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path","Fragment","jsx","jsxs","DEFAULT_IFRAME_STYLE","toError","err","DefaultLoading","jsx","DefaultError","error","retry","jsxs","CrmEmbed","forwardRef","props","ref","getSession","crmEmbedOrigin","className","style","title","onReady","onError","onRouteChange","hostProvidesNav","initialPath","renderLoading","renderError","iframeRef","useRef","embedUrl","setEmbedUrl","useState","workspaceId","setWorkspaceId","setError","attempt","setAttempt","primedBearerRef","hostRef","useImperativeHandle","path","getSessionRef","onReadyRef","onErrorRef","onRouteChangeRef","useEffect","initialPathRef","useCallback","n","cancelled","session","url","buildCrmEmbedUrl","e","iframe","host","createCrmEmbedHost","primed","Fragment","embed_react_default"]}
1
+ {"version":3,"sources":["../src/embed-react.tsx","../src/embed-host.ts"],"sourcesContent":["/**\n * Drop-in React component that embeds the First To Fly CRM as a cross-origin\n * iframe, authenticated WITHOUT cookies.\n *\n * This wraps the low-level {@link ./embed-host | embed-host} helpers into a\n * single component. You supply a `getSession()` that returns a CRM bearer plus\n * the workspace to embed (typically by calling your own backend endpoint that\n * runs `createEmbedSessionWithKey`), and the component handles:\n * - resolving the session and building the iframe URL,\n * - rendering the iframe and running the MessageChannel handshake,\n * - reusing the initial bearer (no double-mint) and re-minting on expiry,\n * - loading / error / retry states.\n *\n * A host (e.g. an app shell) can drive the embedded CRM's section navigation\n * imperatively via a ref (`navigate(path)`), observe the CRM's own navigation\n * via `onRouteChange`, deep-link an `initialPath` on first load, and hide the\n * CRM's in-iframe nav via `hostProvidesNav` (when the host supplies its own).\n *\n * `react` is an OPTIONAL peer dependency — only pull in this entry if you use\n * React. Non-React consumers can keep using `./embed-host` directly.\n *\n * @packageDocumentation\n */\n\nimport {\n forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState,\n} from 'react';\nimport type { CSSProperties, ReactNode } from 'react';\n\nimport {\n buildCrmEmbedUrl,\n createCrmEmbedHost,\n crmSession,\n hostContextQuery,\n type CrmBearer,\n type CrmEmbedHost,\n type CrmHostBrand,\n type CrmHostTheme,\n type CrmSessionResult,\n} from './embed-host';\n\n// Re-export the session-fetch helper so React users can get it from one entry:\n// import { CrmEmbed, crmSession } from '@first-to-fly/crm-sdk/embed-react';\nexport {\n crmSession, type CrmSessionResult, type CrmHostTheme, type CrmHostBrand,\n};\n\n/**\n * What a partner's `getSession()` must resolve to. Alias of {@link CrmSessionResult}\n * (the browser-side session shape) — kept as a named export for back-compat; both\n * are `{ accessToken, workspaceId, expiresIn? }`.\n */\nexport type CrmEmbedSession = CrmSessionResult;\n\n/**\n * Imperative handle exposed via `ref`. Lets a host drive the embedded CRM's\n * navigation without re-rendering the iframe.\n */\nexport interface CrmEmbedHandle {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n}\n\nexport interface CrmEmbedProps {\n /**\n * Resolves a CRM bearer + the workspace to embed. Called once on mount (and\n * again on retry / session expiry). Typically calls your own backend endpoint\n * that runs `createEmbedSessionWithKey`.\n */\n getSession: () => Promise<CrmEmbedSession>;\n /**\n * The CRM embed base origin, e.g. \"https://crm.example.com\". The iframe URL\n * is `buildCrmEmbedUrl(crmEmbedOrigin, workspaceId)` and this origin is also\n * used as the postMessage targetOrigin.\n */\n crmEmbedOrigin: string;\n /** Class applied to the iframe. */\n className?: string;\n /** Inline style merged onto the iframe (overrides the fill-container default). */\n style?: CSSProperties;\n /** Iframe title (accessibility). Defaults to \"CRM\". */\n title?: string;\n /** Called after the iframe URL is built and mounted. */\n onReady?: (info: { workspaceId: string }) => void;\n /** Called on any session / handshake error. */\n onError?: (error: Error) => void;\n /**\n * Called when the CRM navigates internally (e.g. \"/contacts\"). Use this to\n * keep a host-supplied nav in sync with the embedded CRM's current section.\n */\n onRouteChange?: (path: string) => void;\n /**\n * When true, the CRM hides its own in-iframe nav (the host supplies it).\n * Signalled to the CRM by appending `?hostnav=1` to the iframe URL. Drive\n * navigation yourself via the ref's `navigate()`.\n */\n hostProvidesNav?: boolean;\n /**\n * Initial CRM sub-path to deep-link on FIRST load (e.g. \"/contacts\").\n * Only applied to the initial iframe URL — later changes do NOT reload the\n * iframe; use the ref's `navigate()` for in-session navigation.\n */\n initialPath?: string;\n /**\n * Theme for the embedded CRM: `light`, `dark`, or `system` (follow the visitor's OS).\n * The first value rides on the iframe URL as `?theme=`; a later change is posted to\n * the frame over the channel (`crm:host-context`) without reloading it. The CRM applies\n * it for the embed only and never saves it to the user's account. Omitted: the CRM keeps\n * its default (light) look.\n */\n theme?: CrmHostTheme;\n /**\n * Language for the embedded CRM as a BCP 47 tag, e.g. \"en\" or \"zh-CN\". Sent like `theme`\n * (`?locale=`, then `crm:host-context`). Omitted: the CRM keeps its own language.\n */\n locale?: string;\n /**\n * Brand tokens (accent, surfaces, border, radius, fonts) so the CRM looks like part of\n * your app. First value rides on the iframe URL as `?brand=` (base64url JSON); changes\n * are posted over the channel without a reload. Invalid fields are dropped. Pass the\n * tokens for your CURRENT theme and change the object when the theme toggles. See\n * {@link CrmHostBrand}. Omitted: the CRM keeps its own look.\n */\n brand?: CrmHostBrand;\n /** Custom loading UI. Defaults to a minimal message. */\n renderLoading?: () => ReactNode;\n /** Custom error UI. Defaults to the message + a Retry button. */\n renderError?: (error: Error, retry: () => void) => ReactNode;\n}\n\nconst DEFAULT_IFRAME_STYLE: CSSProperties = {\n width: '100%',\n height: '100%',\n border: 0,\n};\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n\nfunction DefaultLoading(): ReactNode {\n return <div>Loading CRM…</div>;\n}\n\nfunction DefaultError(error: Error, retry: () => void): ReactNode {\n return (\n <div>\n <p>Couldn’t load the CRM: {error.message}</p>\n <button type=\"button\" onClick={retry}>Try again</button>\n </div>\n );\n}\n\n/**\n * Embed the First To Fly CRM in a React app. See {@link CrmEmbedProps}.\n *\n * Accepts a `ref` of type {@link CrmEmbedHandle} exposing `navigate(path)` so a\n * host can drive the embedded CRM's section navigation.\n */\nexport const CrmEmbed = forwardRef<CrmEmbedHandle, CrmEmbedProps>(\n function CrmEmbed(props, ref): ReactNode {\n const {\n getSession,\n crmEmbedOrigin,\n className,\n style,\n title = 'CRM',\n onReady,\n onError,\n onRouteChange,\n hostProvidesNav,\n initialPath,\n theme,\n locale,\n brand,\n renderLoading,\n renderError,\n } = props;\n\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const [embedUrl, setEmbedUrl] = useState<string | null>(null);\n const [workspaceId, setWorkspaceId] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [attempt, setAttempt] = useState(0);\n\n // Bearer minted during session resolution — reused for the host's first\n // getBearer() so a single getSession() call covers both phases (no double-mint).\n const primedBearerRef = useRef<CrmBearer | null>(null);\n\n // The created host, so the imperative `navigate()` can reach it.\n const hostRef = useRef<CrmEmbedHost | null>(null);\n\n // Expose the imperative navigate(). No-ops safely before the host is wired.\n useImperativeHandle(ref, () => ({\n navigate: (path: string) => { hostRef.current?.navigate(path); },\n }), []);\n\n // Keep the latest callbacks in refs so the effects DON'T depend on their\n // identity. Partners routinely pass inline `getSession`/`onReady`/`onError`/\n // `onRouteChange`; depending on them directly would re-run Phase 1 (re-fetch\n // the session) and tear down + recreate the host on every parent re-render.\n const getSessionRef = useRef(getSession);\n const onReadyRef = useRef(onReady);\n const onErrorRef = useRef(onError);\n const onRouteChangeRef = useRef(onRouteChange);\n useEffect(() => {\n getSessionRef.current = getSession;\n onReadyRef.current = onReady;\n onErrorRef.current = onError;\n onRouteChangeRef.current = onRouteChange;\n });\n\n // Capture initialPath ONCE — it only seeds the first load. Later changes go\n // through the imperative navigate() and must NOT rebuild/reload the iframe.\n const initialPathRef = useRef(initialPath);\n\n // Latest theme/locale. The first values seed the iframe URL and the host; later changes\n // are pushed through the channel by the effect below, never by rebuilding the iframe.\n const hostContextRef = useRef({ theme, locale, brand });\n hostContextRef.current = { theme, locale, brand };\n\n const retry = useCallback(() => {\n primedBearerRef.current = null;\n setError(null);\n setEmbedUrl(null);\n setWorkspaceId(null);\n setAttempt((n) => n + 1);\n }, []);\n\n // Phase 1: resolve the session, prime the bearer, and build the iframe URL.\n // Re-runs only on retry (`attempt`) or a changed origin/hostnav — never on\n // unrelated parent re-renders (callbacks + initialPath are read from refs).\n useEffect(() => {\n let cancelled = false;\n\n void (async () => {\n try {\n const session = await getSessionRef.current();\n if (cancelled) return;\n primedBearerRef.current = { accessToken: session.accessToken };\n setWorkspaceId(session.workspaceId);\n const base = buildCrmEmbedUrl(crmEmbedOrigin, session.workspaceId);\n const path = initialPathRef.current ?? '';\n const query = [...(hostProvidesNav ? ['hostnav=1'] : []), ...hostContextQuery(hostContextRef.current)];\n const separator = path.includes('?') ? '&' : '?';\n const url = base + path + (query.length > 0 ? separator + query.join('&') : '');\n setEmbedUrl(url);\n } catch (err) {\n if (cancelled) return;\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n }\n })();\n\n return () => { cancelled = true; };\n }, [crmEmbedOrigin, hostProvidesNav, attempt]);\n\n // Phase 2: once the iframe URL is known, wire the MessageChannel host.\n useEffect(() => {\n const iframe = iframeRef.current;\n if (!iframe || !embedUrl || !workspaceId) return undefined;\n\n let host: CrmEmbedHost | null = null;\n try {\n host = createCrmEmbedHost({\n iframe,\n crmOrigin: crmEmbedOrigin,\n getBearer: async () => {\n const primed = primedBearerRef.current;\n if (primed) {\n primedBearerRef.current = null;\n return primed;\n }\n const session = await getSessionRef.current();\n return { accessToken: session.accessToken };\n },\n hostContext: hostContextRef.current,\n onRouteChange: (path) => { onRouteChangeRef.current?.(path); },\n onError: (err) => {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n },\n });\n } catch (err) {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n return undefined;\n }\n\n hostRef.current = host;\n\n // Only signal ready once the host is actually wired.\n onReadyRef.current?.({ workspaceId });\n\n return () => {\n host?.dispose();\n hostRef.current = null;\n };\n }, [embedUrl, workspaceId, crmEmbedOrigin]);\n\n // Phase 3: a theme/locale change after mount is sent to the frame, not a reload.\n // Compared by content, so an inline `brand={{...}}` does not re-send on every render.\n const brandKey = JSON.stringify(brand ?? null);\n const hadBrandRef = useRef(false);\n useEffect(() => {\n // Clear the frame's brand only if one was sent before; otherwise leave the field out.\n const brandUpdate = brand ? { brand } : (hadBrandRef.current ? { brand: null } : {});\n hadBrandRef.current = !!brand;\n hostRef.current?.setContext({ theme, locale, ...brandUpdate });\n // eslint-disable-next-line react-hooks/exhaustive-deps -- brandKey stands in for brand\n }, [theme, locale, brandKey]);\n\n if (error) {\n return <>{renderError ? renderError(error, retry) : DefaultError(error, retry)}</>;\n }\n\n if (!embedUrl) {\n return <>{renderLoading ? renderLoading() : DefaultLoading()}</>;\n }\n\n return (\n <iframe\n ref={iframeRef}\n src={embedUrl}\n title={title}\n className={className}\n style={{ ...DEFAULT_IFRAME_STYLE, ...style }}\n />\n );\n },\n);\n\nexport default CrmEmbed;\n","/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n * 6. host sends { type: 'crm:host-context', theme?, locale?, brand? } on the same port,\n * right after the bearer and again whenever {@link CrmEmbedHost.setContext} is called.\n * The first values also ride on the iframe URL (`?theme=`, `?locale=` and `?brand=`), so the\n * frame paints in the right theme before the handshake finishes.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\n/** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */\nexport type CrmHostTheme = 'light' | 'dark' | 'system';\n\n/**\n * Brand tokens that make the embedded CRM look like part of the host. All optional.\n * Colours are `#rgb` or `#rrggbb`; invalid values are dropped, never sent.\n * Pass the values for the host's CURRENT theme and send a new brand when it toggles.\n * No remote font is loaded: a family the visitor's system lacks falls back to the CRM's.\n */\nexport interface CrmHostBrand {\n /** Buttons, selected tabs, focus rings, chart accent. */\n accent?: string;\n /** Text on the accent. Defaults to white or near-black, whichever reads better. */\n accentForeground?: string;\n /** Page background. */\n background?: string;\n /** Cards, popovers and inputs. Defaults to `background`. */\n surface?: string;\n /** Hairlines and input borders. Derived from background and foreground when omitted. */\n border?: string;\n /** Body text. */\n foreground?: string;\n /** Secondary text. Derived when omitted. */\n mutedForeground?: string;\n /** Corner radius for controls, `0px` to `24px`, e.g. `\"6px\"`. Larger surfaces scale from it. */\n radius?: string;\n /** UI font family list, e.g. `\"Inter, system-ui\"`. Letters, digits, spaces, commas, quotes, hyphens, underscores; max 160 chars. */\n fontFamily?: string;\n /** Font for page titles, same rules as `fontFamily`, e.g. `\"Fraunces, Georgia, serif\"`. */\n displayFontFamily?: string;\n}\n\n/**\n * Look and language the host passes to the embedded CRM. Both are optional; an omitted\n * field leaves the CRM's own behaviour unchanged. The CRM applies them for the embed only\n * and never saves them to the user's account.\n */\nexport interface CrmHostContext {\n theme?: CrmHostTheme;\n /** BCP 47 language tag, e.g. \"en\" or \"zh-CN\". */\n locale?: string;\n /**\n * Host brand tokens. A new brand REPLACES the previous one; `null` (setContext only)\n * returns the CRM to its own look. Omitted: unchanged.\n */\n brand?: CrmHostBrand | null;\n}\n\n/** The message the host posts on the channel port to update {@link CrmHostContext}. */\nexport interface CrmHostContextMessage extends CrmHostContext {\n type: 'crm:host-context';\n}\n\nconst HOST_THEMES: readonly string[] = ['light', 'dark', 'system'];\nconst BCP47_LIKE = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;\n\nconst HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;\nconst RADIUS_PX = /^(\\d{1,2}(?:\\.\\d{1,2})?)px$/;\nconst FONT_CHARS = /^[A-Za-z0-9 ,'\"_-]+$/;\nconst FONT_MAX = 160;\n/** The encoded `?brand=` value never exceeds this; a longer one would be ignored by the CRM. */\nconst BRAND_PARAM_MAX = 1500;\nconst BRAND_COLOR_KEYS = [\n 'accent', 'accentForeground', 'background', 'surface', 'border', 'foreground', 'mutedForeground',\n] as const;\n\nfunction cleanFont(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const v = value.trim();\n if (!v || v.length > FONT_MAX || !FONT_CHARS.test(v)) return undefined;\n if ((v.match(/\"/g)?.length ?? 0) % 2 !== 0 || (v.match(/'/g)?.length ?? 0) % 2 !== 0) return undefined;\n return v;\n}\n\n/**\n * Keeps only valid brand fields: hex colours (lower-cased `#rrggbb`), a `0-24px` radius and\n * safe font-family lists. Returns undefined when nothing valid is left.\n */\nexport function normalizeHostBrand(brand: CrmHostBrand | undefined | null): CrmHostBrand | undefined {\n if (!brand || typeof brand !== 'object' || Array.isArray(brand)) return undefined;\n const out: CrmHostBrand = {};\n for (const key of BRAND_COLOR_KEYS) {\n const raw = brand[key];\n if (typeof raw === 'string' && HEX_COLOR.test(raw.trim())) {\n let hex = raw.trim().toLowerCase();\n if (hex.length === 4) hex = `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`;\n out[key] = hex;\n }\n }\n if (typeof brand.radius === 'string') {\n const m = RADIUS_PX.exec(brand.radius.trim());\n if (m && Number(m[1]) <= 24) out.radius = `${Number(m[1])}px`;\n }\n const fontFamily = cleanFont(brand.fontFamily);\n if (fontFamily) out.fontFamily = fontFamily;\n const displayFontFamily = cleanFont(brand.displayFontFamily);\n if (displayFontFamily) out.displayFontFamily = displayFontFamily;\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** Encodes a brand for the `?brand=` query value (base64url JSON), or null when empty or too long. */\nexport function encodeHostBrand(brand: CrmHostBrand | undefined | null): string | null {\n const clean = normalizeHostBrand(brand);\n if (!clean) return null;\n const bytes = new TextEncoder().encode(JSON.stringify(clean));\n let bin = '';\n bytes.forEach((b) => { bin += String.fromCharCode(b); });\n const encoded = btoa(bin).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n return encoded.length <= BRAND_PARAM_MAX ? encoded : null;\n}\n\n/**\n * Keeps only values the CRM understands: a known theme, a well-formed language tag and a\n * valid brand. Anything else is dropped, so a bad value can never reach the iframe URL or\n * the message. `brand: null` is kept so a message can clear an earlier brand.\n */\nexport function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext {\n const out: CrmHostContext = {};\n if (ctx?.brand === null) out.brand = null;\n else {\n const brand = normalizeHostBrand(ctx?.brand);\n if (brand) out.brand = brand;\n }\n if (ctx?.theme && HOST_THEMES.includes(ctx.theme)) out.theme = ctx.theme;\n if (typeof ctx?.locale === 'string' && BCP47_LIKE.test(ctx.locale.trim())) out.locale = ctx.locale.trim();\n return out;\n}\n\n/** `theme`, `locale` and `brand` as URL query pairs (e.g. `[\"theme=dark\", \"locale=zh-CN\", \"brand=eyJ...\"]`). */\nexport function hostContextQuery(ctx: CrmHostContext | undefined): string[] {\n const clean = normalizeHostContext(ctx);\n const pairs: string[] = [];\n if (clean.theme) pairs.push(`theme=${encodeURIComponent(clean.theme)}`);\n if (clean.locale) pairs.push(`locale=${encodeURIComponent(clean.locale)}`);\n const brand = clean.brand ? encodeHostBrand(clean.brand) : null;\n if (brand) pairs.push(`brand=${brand}`);\n return pairs;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /** Initial theme/locale, sent to the CRM once the channel is up. Change it with `setContext()`. */\n hostContext?: CrmHostContext;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /**\n * Update the theme and/or language of the embedded CRM. Sent over the established\n * channel only, never broadcast with a wildcard origin. Fields you leave out keep\n * their last value; before the channel is up the latest values go out on connect.\n */\n setContext: (ctx: CrmHostContext) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n const result = body as Partial<CrmSessionResult>;\n // A malformed 2xx (e.g. `{}`) would otherwise cast cleanly and later build an\n // `/embed/undefined` URL — fail at the boundary with a clear message instead.\n if (typeof result?.accessToken !== 'string' || typeof result?.workspaceId !== 'string') {\n throw new Error('CRM session response is missing accessToken/workspaceId');\n }\n return result as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n let context: CrmHostContext = normalizeHostContext(opts.hostContext);\n\n function sendContext(extra?: { brand: null }): void {\n if (extra) {\n port?.postMessage({ type: 'crm:host-context', ...context, ...extra } satisfies CrmHostContextMessage);\n return;\n }\n if (!port || (context.theme === undefined && context.locale === undefined && context.brand === undefined)) return;\n const msg: CrmHostContextMessage = { type: 'crm:host-context', ...context };\n port.postMessage(msg);\n }\n\n async function deliverBearer(): Promise<boolean> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n sendContext();\n return true;\n } catch (err) {\n opts.onError?.(err);\n return false;\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow). Only tell the\n // CRM the session refreshed once a fresh bearer was ACTUALLY delivered —\n // otherwise a failed re-mint leaves the iframe believing it's authenticated.\n void deliverBearer().then((ok) => {\n if (ok) port?.postMessage({ type: 'session-refreshed' });\n });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n setContext(ctx: CrmHostContext): void {\n const next = normalizeHostContext(ctx);\n context = { ...context, ...next };\n if (next.brand === null) delete context.brand; // cleared: send null once, then forget it\n sendContext(next.brand === null ? { brand: null } : undefined);\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"AAwBA,OACE,cAAAA,GAAY,eAAAC,GAAa,aAAAC,EAAW,uBAAAC,GAAqB,UAAAC,EAAQ,YAAAC,MAC5D,QCwDP,IAAMC,GAAiC,CAAC,QAAS,OAAQ,QAAQ,EAC3DC,GAAa,4CAEbC,GAAY,kCACZC,GAAY,8BACZC,GAAa,uBAInB,IAAMC,GAAmB,CACvB,SAAU,mBAAoB,aAAc,UAAW,SAAU,aAAc,iBACjF,EAEA,SAASC,EAAUC,EAAoC,CACrD,GAAI,OAAOA,GAAU,SAAU,OAC/B,IAAMC,EAAID,EAAM,KAAK,EACrB,GAAI,GAACC,GAAKA,EAAE,OAAS,KAAY,CAACC,GAAW,KAAKD,CAAC,IAC9C,GAAAA,EAAE,MAAM,IAAI,GAAG,QAAU,GAAK,IAAM,IAAMA,EAAE,MAAM,IAAI,GAAG,QAAU,GAAK,IAAM,GACnF,OAAOA,CACT,CAMO,SAASE,EAAmBC,EAAkE,CACnG,GAAI,CAACA,GAAS,OAAOA,GAAU,UAAY,MAAM,QAAQA,CAAK,EAAG,OACjE,IAAMC,EAAoB,CAAC,EAC3B,QAAWC,KAAOR,GAAkB,CAClC,IAAMS,EAAMH,EAAME,CAAG,EACrB,GAAI,OAAOC,GAAQ,UAAYC,GAAU,KAAKD,EAAI,KAAK,CAAC,EAAG,CACzD,IAAIE,EAAMF,EAAI,KAA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","useCallback","useEffect","useImperativeHandle","useRef","useState","HOST_THEMES","BCP47_LIKE","HEX_COLOR","RADIUS_PX","FONT_CHARS","BRAND_COLOR_KEYS","cleanFont","value","v","FONT_CHARS","normalizeHostBrand","brand","out","key","raw","HEX_COLOR","hex","m","RADIUS_PX","fontFamily","displayFontFamily","encodeHostBrand","clean","bytes","bin","b","encoded","normalizeHostContext","ctx","HOST_THEMES","BCP47_LIKE","hostContextQuery","pairs","isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","context","sendContext","extra","msg","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path","next","Fragment","jsx","jsxs","DEFAULT_IFRAME_STYLE","toError","err","DefaultLoading","jsx","DefaultError","error","retry","jsxs","CrmEmbed","forwardRef","props","ref","getSession","crmEmbedOrigin","className","style","title","onReady","onError","onRouteChange","hostProvidesNav","initialPath","theme","locale","brand","renderLoading","renderError","iframeRef","useRef","embedUrl","setEmbedUrl","useState","workspaceId","setWorkspaceId","setError","attempt","setAttempt","primedBearerRef","hostRef","useImperativeHandle","path","getSessionRef","onReadyRef","onErrorRef","onRouteChangeRef","useEffect","initialPathRef","hostContextRef","useCallback","n","cancelled","session","base","buildCrmEmbedUrl","query","hostContextQuery","separator","url","e","iframe","host","createCrmEmbedHost","primed","brandKey","hadBrandRef","brandUpdate","Fragment","embed_react_default"]}
package/dist/partner.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var C=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var B=Object.prototype.hasOwnProperty;var I=(e,s)=>{for(var p in s)C(e,p,{get:s[p],enumerable:!0})},F=(e,s,p,f)=>{if(s&&typeof s=="object"||typeof s=="function")for(let l of j(s))!B.call(e,l)&&l!==p&&C(e,l,{get:()=>s[l],enumerable:!(f=$(s,l))||f.enumerable});return e};var L=e=>F(C({},"__esModule",{value:!0}),e);var N={};I(N,{CONTACT_CHANGES_MAX_LIMIT:()=>S,CONTACT_REF_PATTERN:()=>E,CrmPartnerError:()=>k,EXTERNAL_REF_PATTERN:()=>T,createCrmPartnerClient:()=>D});module.exports=L(N);function R(e){return e.replace(/\/+$/,"").replace(/\/api$/,"")}function _(e,s){let p=e??globalThis.fetch;if(typeof p!="function")throw new Error(`${s}: no fetch implementation available. Pass \`fetch\` explicitly.`);return p}async function W(e,s,p,f){let l=new AbortController,c=!1,u=setTimeout(()=>{c=!0,l.abort()},s);try{let m={Accept:"application/json",...f.headers},y=f.body!==void 0;y&&(m["Content-Type"]="application/json");let r=await e(p,{method:f.method,headers:m,body:y?JSON.stringify(f.body):void 0,signal:l.signal}),o=await r.json().catch(()=>null);return c?{ok:!1,kind:"timeout"}:{ok:!0,status:r.status,json:o}}catch{return{ok:!1,kind:c?"timeout":"network"}}finally{clearTimeout(u)}}var O=/^[A-Za-z0-9_.:-]{1,60}$/;function x(e,s,p){let f=`HTTP_${s}`,l=c=>typeof c!="string"||!O.test(c)||p.some(u=>u&&c.includes(u))?null:c;if(e&&typeof e=="object"){let c=e,u=c.error;return l(c.code)??l(u)??(u&&typeof u=="object"?l(u.code):null)??f}return f}var g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var k=class e extends Error{constructor(s,p){super(s===0?`CRM partner API unreachable (${p})`:`CRM partner API ${s} ${p}`),this.name="CrmPartnerError",this.status=s,this.code=p,Object.setPrototypeOf(this,e.prototype)}},T=/^[A-Za-z0-9_-]{1,64}$/,E=/^[A-Za-z0-9._:-]{1,200}$/,S=200,h=e=>({externalRef:e.external_ref,workspaceId:e.workspace_id,embedAppId:e.embed_app_id,enabled:e.enabled}),A=e=>e===null||typeof e=="string";function w(e){return g(e)&&typeof e.external_ref=="string"&&A(e.workspace_id)&&A(e.embed_app_id)&&typeof e.enabled=="boolean"}function D(e){if(!e.crmBaseUrl)throw new Error("createCrmPartnerClient: `crmBaseUrl` is required.");if(!e.partnerKey)throw new Error("createCrmPartnerClient: `partnerKey` is required.");let s=_(e.fetch,"createCrmPartnerClient"),p=e.timeoutMs??15e3,f=`${R(e.crmBaseUrl)}/api/partner/v1/workspaces`,l=[e.partnerKey];function c(r){if(typeof r!="string"||!T.test(r))throw new k(400,"invalid_external_ref");return r}async function u(r,o,i){let t=await W(s,p,`${f}/${o}`,{method:r,headers:{Authorization:`Bearer ${e.partnerKey}`},body:i});if(!t.ok)throw new k(0,t.kind);if(t.status<200||t.status>=300)throw new k(t.status,x(t.json,t.status,l));return{status:t.status,json:t.json}}let m=r=>new k(r,"bad_response");function y(r){if(typeof r!="string"||!E.test(r))throw new k(400,"invalid_contact_ref");return r}return{async upsertWorkspace(r,o){let i=c(r),{status:t,json:a}=await u("PUT",i,o);if(!w(a))throw m(t);let n=a;if(n.created===!0){let d=n.embed_app_secret;if(typeof d!="string"||!d)throw m(t);return{...h(n),created:!0,embedAppSecret:d}}if(n.created===!1)return{...h(n),created:!1};throw m(t)},async getWorkspace(r){let o=c(r);try{let{status:i,json:t}=await u("GET",o);if(!w(t)||typeof t.state!="string")throw m(i);return{...h(t),state:t.state}}catch(i){if(i instanceof k&&i.status===404)return null;throw i}},async updateWorkspace(r,o){let i=c(r),t={};o.enabled!==void 0&&(t.enabled=o.enabled),o.name!==void 0&&(t.name=o.name);let{status:a,json:n}=await u("PATCH",i,t);if(!w(n))throw m(a);return h(n)},async rotateWorkspaceSecret(r){let o=c(r),{status:i,json:t}=await u("POST",`${o}/rotate-secret`),a=t;if(!g(t)||typeof a?.embed_app_id!="string"||typeof a.embed_app_secret!="string"||!a.embed_app_secret)throw m(i);return{embedAppId:a.embed_app_id,embedAppSecret:a.embed_app_secret}},async upsertContact(r,o,i){let t=c(r),a=y(o),{status:n,json:d}=await u("PUT",`${t}/contacts/${encodeURIComponent(a)}`,i);if(!g(d)||!g(d.contact)||typeof d.created!="boolean"||typeof d.consent_applied!="boolean")throw m(n);return d},async eraseContact(r,o){let i=c(r),t=y(o);try{let{status:a,json:n}=await u("DELETE",`${i}/contacts/${encodeURIComponent(t)}`);if(!g(n)||n.erased!==!0||typeof n.contact_id!="string")throw m(a);return n}catch(a){if(a instanceof k&&a.status===404)return null;throw a}},async listContactChanges(r,o={}){let i=c(r),{since:t,cursor:a,limit:n}=o;if(n!==void 0&&(!Number.isInteger(n)||n<1||n>S))throw new k(400,"invalid_limit");let d=new URLSearchParams;t!==void 0&&d.set("since",t),a!==void 0&&d.set("cursor",a),n!==void 0&&d.set("limit",String(n));let b=d.toString(),{status:U,json:P}=await u("GET",`${i}/contacts/changes${b?`?${b}`:""}`);if(!g(P)||!Array.isArray(P.items)||!(P.next_cursor===null||typeof P.next_cursor=="string"))throw m(U);return P}}}0&&(module.exports={CONTACT_CHANGES_MAX_LIMIT,CONTACT_REF_PATTERN,CrmPartnerError,EXTERNAL_REF_PATTERN,createCrmPartnerClient});
1
+ "use strict";var b=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var O=Object.prototype.hasOwnProperty;var N=(e,a)=>{for(var d in a)b(e,d,{get:a[d],enumerable:!0})},F=(e,a,d,g)=>{if(a&&typeof a=="object"||typeof a=="function")for(let y of M(a))!O.call(e,y)&&y!==d&&b(e,y,{get:()=>a[y],enumerable:!(g=D(a,y))||g.enumerable});return e};var L=e=>F(b({},"__esModule",{value:!0}),e);var Z={};N(Z,{AI_MONTHLY_CAP_MAX_CREDITS:()=>j,CONTACT_CHANGES_MAX_LIMIT:()=>$,CONTACT_REF_PATTERN:()=>I,CrmPartnerError:()=>f,EXTERNAL_REF_PATTERN:()=>S,createCrmPartnerClient:()=>K});module.exports=L(Z);function R(e){return e.replace(/\/+$/,"").replace(/\/api$/,"")}function x(e,a){let d=e??globalThis.fetch;if(typeof d!="function")throw new Error(`${a}: no fetch implementation available. Pass \`fetch\` explicitly.`);return d}async function A(e,a,d,g){let y=new AbortController,c=!1,u=setTimeout(()=>{c=!0,y.abort()},a);try{let m={Accept:"application/json",...g.headers},C=g.body!==void 0;C&&(m["Content-Type"]="application/json");let s=await e(d,{method:g.method,headers:m,body:C?JSON.stringify(g.body):void 0,signal:y.signal}),n=await s.json().catch(()=>null);return c?{ok:!1,kind:"timeout"}:{ok:!0,status:s.status,json:n}}catch{return{ok:!1,kind:c?"timeout":"network"}}finally{clearTimeout(u)}}var q=/^[A-Za-z0-9_.:-]{1,60}$/;function E(e,a,d){let g=`HTTP_${a}`,y=c=>typeof c!="string"||!q.test(c)||d.some(u=>u&&c.includes(u))?null:c;if(e&&typeof e=="object"){let c=e,u=c.error;return y(c.code)??y(u)??(u&&typeof u=="object"?y(u.code):null)??g}return g}var k=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var f=class e extends Error{constructor(a,d){super(a===0?`CRM partner API unreachable (${d})`:`CRM partner API ${a} ${d}`),this.name="CrmPartnerError",this.status=a,this.code=d,Object.setPrototypeOf(this,e.prototype)}},S=/^[A-Za-z0-9_-]{1,64}$/,I=/^[A-Za-z0-9._:-]{1,200}$/,$=200,j=1e8,w=e=>({externalRef:e.external_ref,workspaceId:e.workspace_id,embedAppId:e.embed_app_id,enabled:e.enabled,aiMonthlyCapCredits:typeof e.ai_monthly_cap_credits=="number"?e.ai_monthly_cap_credits:null}),G=/^\d{4}-\d{2}-\d{2}$/;function T(e){let a=e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e;if(typeof a!="string"||!G.test(a)||Number.isNaN(Date.parse(`${a}T00:00:00Z`))||new Date(`${a}T00:00:00Z`).toISOString().slice(0,10)!==a)throw new f(400,"invalid_date");return a}function B(e){if(e==null)return e;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>j)throw new f(400,"invalid_cap");return e}var U=e=>e===null||typeof e=="string";function W(e){return k(e)&&typeof e.external_ref=="string"&&U(e.workspace_id)&&U(e.embed_app_id)&&typeof e.enabled=="boolean"}function K(e){if(!e.crmBaseUrl)throw new Error("createCrmPartnerClient: `crmBaseUrl` is required.");if(!e.partnerKey)throw new Error("createCrmPartnerClient: `partnerKey` is required.");let a=x(e.fetch,"createCrmPartnerClient"),d=e.timeoutMs??15e3,g=`${R(e.crmBaseUrl)}/api/partner/v1/workspaces`,y=[e.partnerKey];function c(s){if(typeof s!="string"||!S.test(s))throw new f(400,"invalid_external_ref");return s}async function u(s,n,i){let t=await A(a,d,`${g}/${n}`,{method:s,headers:{Authorization:`Bearer ${e.partnerKey}`},body:i});if(!t.ok)throw new f(0,t.kind);if(t.status<200||t.status>=300)throw new f(t.status,E(t.json,t.status,y));return{status:t.status,json:t.json}}let m=s=>new f(s,"bad_response");function C(s){if(typeof s!="string"||!I.test(s))throw new f(400,"invalid_contact_ref");return s}return{async upsertWorkspace(s,n){let i=c(s),{aiMonthlyCapCredits:t,...r}=n,o=B(t),p=o===void 0?r:{...r,ai_monthly_cap_credits:o},{status:h,json:P}=await u("PUT",i,p);if(!W(P))throw m(h);let l=P;if(l.created===!0){let _=l.embed_app_secret;if(typeof _!="string"||!_)throw m(h);return{...w(l),created:!0,embedAppSecret:_}}if(l.created===!1)return{...w(l),created:!1};throw m(h)},async getWorkspace(s){let n=c(s);try{let{status:i,json:t}=await u("GET",n);if(!W(t)||typeof t.state!="string")throw m(i);let r=t.ai;return{...w(t),state:t.state,ai:k(r)&&typeof r.period=="string"&&typeof r.used_credits=="number"?{period:r.period,usedCredits:r.used_credits}:null}}catch(i){if(i instanceof f&&i.status===404)return null;throw i}},async updateWorkspace(s,n){let i=c(s),t={};n.enabled!==void 0&&(t.enabled=n.enabled),n.name!==void 0&&(t.name=n.name);let r=B(n.aiMonthlyCapCredits);r!==void 0&&(t.ai_monthly_cap_credits=r);let{status:o,json:p}=await u("PATCH",i,t);if(!W(p))throw m(o);return w(p)},async getWorkspaceUsage(s,n){let i=c(s),t=new URLSearchParams({from:T(n.from),to:T(n.to)});try{let{status:r,json:o}=await u("GET",`${i}/usage?${t.toString()}`);if(!k(o)||!k(o.totals)||!k(o.cap)||!Array.isArray(o.by_operation))throw m(r);return o}catch(r){if(r instanceof f&&r.status===404)return null;throw r}},async rotateWorkspaceSecret(s){let n=c(s),{status:i,json:t}=await u("POST",`${n}/rotate-secret`),r=t;if(!k(t)||typeof r?.embed_app_id!="string"||typeof r.embed_app_secret!="string"||!r.embed_app_secret)throw m(i);return{embedAppId:r.embed_app_id,embedAppSecret:r.embed_app_secret}},async upsertContact(s,n,i){let t=c(s),r=C(n),{status:o,json:p}=await u("PUT",`${t}/contacts/${encodeURIComponent(r)}`,i);if(!k(p)||!k(p.contact)||typeof p.created!="boolean"||typeof p.consent_applied!="boolean")throw m(o);return p},async eraseContact(s,n){let i=c(s),t=C(n);try{let{status:r,json:o}=await u("DELETE",`${i}/contacts/${encodeURIComponent(t)}`);if(!k(o)||o.erased!==!0||typeof o.contact_id!="string")throw m(r);return o}catch(r){if(r instanceof f&&r.status===404)return null;throw r}},async eraseContactsByIdentity(s,n){let i=c(s),t=typeof n?.phone=="string"?n.phone.trim():void 0,r=typeof n?.email=="string"?n.email.trim():void 0,o=t!==void 0&&/\d/.test(t),p=r!==void 0&&r.includes("@");if(n?.phone!==void 0&&!o||n?.email!==void 0&&!p||!o&&!p)throw new f(400,"invalid_identity");n.ref!==void 0&&C(n.ref);let h={};o&&(h.phone=t),p&&(h.email=r),n.ref!==void 0&&(h.ref=n.ref);try{let{status:P,json:l}=await u("POST",`${i}/contacts/erase-by-identity`,h);if(!k(l)||typeof l.erased!="number"||!Array.isArray(l.contact_ids)||typeof l.skipped_linked_elsewhere!="number")throw m(P);return l}catch(P){if(P instanceof f&&P.status===404)return null;throw P}},async listContactChanges(s,n={}){let i=c(s),{since:t,cursor:r,limit:o}=n;if(o!==void 0&&(!Number.isInteger(o)||o<1||o>$))throw new f(400,"invalid_limit");let p=new URLSearchParams;t!==void 0&&p.set("since",t),r!==void 0&&p.set("cursor",r),o!==void 0&&p.set("limit",String(o));let h=p.toString(),{status:P,json:l}=await u("GET",`${i}/contacts/changes${h?`?${h}`:""}`);if(!k(l)||!Array.isArray(l.items)||!(l.next_cursor===null||typeof l.next_cursor=="string"))throw m(P);return l}}}0&&(module.exports={AI_MONTHLY_CAP_MAX_CREDITS,CONTACT_CHANGES_MAX_LIMIT,CONTACT_REF_PATTERN,CrmPartnerError,EXTERNAL_REF_PATTERN,createCrmPartnerClient});
2
2
  //# sourceMappingURL=partner.cjs.map