@first-to-fly/crm-sdk 1.9.0 → 1.10.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.
- package/README.md +47 -0
- package/dist/embed-host.cjs +1 -1
- package/dist/embed-host.cjs.map +1 -1
- package/dist/embed-host.d.cts +61 -2
- package/dist/embed-host.d.ts +61 -2
- package/dist/embed-host.js +1 -1
- package/dist/embed-host.js.map +1 -1
- package/dist/embed-react.cjs +1 -1
- package/dist/embed-react.cjs.map +1 -1
- package/dist/embed-react.d.cts +44 -1
- package/dist/embed-react.d.ts +44 -1
- package/dist/embed-react.js +1 -1
- package/dist/embed-react.js.map +1 -1
- package/package.json +1 -1
package/dist/embed-react.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var w=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var de=Object.prototype.hasOwnProperty;var me=(e,t)=>{for(var r in t)w(e,r,{get:t[r],enumerable:!0})},fe=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ue(t))!de.call(e,n)&&n!==r&&w(e,n,{get:()=>t[n],enumerable:!(o=le(t,n))||o.enumerable});return e};var ge=e=>fe(w({},"__esModule",{value:!0}),e);var ve={};me(ve,{CrmEmbed:()=>te,crmSession:()=>G,default:()=>Ne});module.exports=ge(ve);var s=require("react");var Ce=["create-lead","open-person"];var pe=["light","dark","system"],he=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/,ye=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i,Ae=/^(\d{1,2}(?:\.\d{1,2})?)px$/,be=/^[A-Za-z0-9 ,'"_-]+$/;var He=["accent","accentForeground","background","surface","border","foreground","mutedForeground"];function J(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||t.length>160||!be.test(t))&&!((t.match(/"/g)?.length??0)%2!==0||(t.match(/'/g)?.length??0)%2!==0))return t}function Z(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of He){let l=e[n];if(typeof l=="string"&&ye.test(l.trim())){let c=l.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 r=J(e.fontFamily);r&&(t.fontFamily=r);let o=J(e.displayFontFamily);return o&&(t.displayFontFamily=o),Object.keys(t).length>0?t:void 0}function Ee(e){let t=Z(e);if(!t)return null;let r=new TextEncoder().encode(JSON.stringify(t)),o="";r.forEach(l=>{o+=String.fromCharCode(l)});let n=btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return n.length<=1500?n:null}function P(e){let t={};if(e?.brand===null)t.brand=null;else{let r=Z(e?.brand);r&&(t.brand=r)}if(e?.theme&&pe.includes(e.theme)&&(t.theme=e.theme),typeof e?.locale=="string"&&he.test(e.locale.trim())&&(t.locale=e.locale.trim()),Array.isArray(e?.capabilities)){let r=e.capabilities.filter(o=>Ce.includes(o));t.capabilities=[...new Set(r)].slice(0,8)}if(typeof e?.hostName=="string"){let r=e.hostName.trim();r&&r.length<=40&&!/[\u0000-\u001f\u007f]/.test(r)&&(t.hostName=r)}return t}function R(e,t,r){if(e===void 0)return r?null:void 0;if(typeof e!="string")return null;let o=e.trim();return o.length>t?null:o||(r?null:void 0)}function Re(e){if(!e||typeof e!="object")return null;let t=e;if(t.type!=="crm:host-action")return null;let r=R(t.requestId,64,!0);if(!r)return null;let o=t.contact;if(!o||typeof o!="object"||Array.isArray(o))return null;let n=o,l=R(n.crmContactId,100,!0);if(!l)return null;if(t.action==="open-person")return{requestId:r,action:"open-person",contact:{crmContactId:l}};if(t.action!=="create-lead")return null;let c=R(n.name,200,!1),A=R(n.phone,40,!1),d=R(n.email,320,!1),b=R(t.conversationId,100,!0),C=R(t.channel,40,!1),H=R(t.messageSnippet,280,!1);if([c,A,d,C,H].some(i=>i===null)||!b)return null;let E={crmContactId:l};c&&(E.name=c),A&&(E.phone=A),d&&(E.email=d);let g={requestId:r,action:"create-lead",contact:E,conversationId:b};return C&&(g.channel=C),H&&(g.messageSnippet=H),g}function Y(e){let t=P(e),r=[];t.theme&&r.push(`theme=${encodeURIComponent(t.theme)}`),t.locale&&r.push(`locale=${encodeURIComponent(t.locale)}`);let o=t.brand?Ee(t.brand):null;return o&&r.push(`brand=${o}`),r}function Me(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function G(e,t){return async()=>{let r=await fetch(e,{method:"POST",...t}),o=await r.json().catch(()=>({}));if(!r.ok){let l=o?.error;throw new Error(l?`CRM session failed: ${l}`:`CRM session failed (HTTP ${r.status})`)}let n=o;if(typeof n?.accessToken!="string"||typeof n?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return n}}function V(e,t){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(t)}`}function ee(e){let t=e.windowTarget??window,r=e.createChannel??(()=>new MessageChannel),o=e.devAllowAnyOrigin?"*":e.crmOrigin,n=null,l="",c=!1,A=!1,d=P(e.hostContext);function b(i){if(i){n?.postMessage({type:"crm:host-context",...d,...i});return}if(!n||Object.keys(d).length===0)return;let a={type:"crm:host-context",...d};n.postMessage(a)}async function C(){try{let i=await e.getBearer();return n?.postMessage({type:"auth-tokens",accessToken:i.accessToken,refreshToken:i.refreshToken??""}),b(),!0}catch(i){return e.onError?.(i),!1}}function H(i){let a=i.data;if(a)if(a.type==="channel-ack"){if(a.nonce!==l)return;c=!0,C()}else if(a.type==="route-change")e.onRouteChange?.(a.path);else if(a.type==="crm:host-action"){if(!c)return;let p=Re(a);p&&e.onHostAction?.(p)}else a.type==="resize"?e.onResize?.(a.height):a.type==="session-expired"&&C().then(p=>{p&&n?.postMessage({type:"session-refreshed"})})}function E(){n?.close(),c=!1;let i=r();n=i.port1,l=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,n.onmessage=H,n.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:l},o,[i.port2])}function g(i){A||i.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&i.origin!==e.crmOrigin||Me(i.data)&&E())}return t.addEventListener("message",g),{navigate(i){n?.postMessage({type:"navigate",path:i})},setContext(i){let a=P(i);d={...d,...a},a.brand===null&&delete d.brand,b(a.brand===null?{brand:null}:void 0)},dispose(){A=!0,t.removeEventListener("message",g),n?.close(),n=null}}}var f=require("react/jsx-runtime");var Ie={width:"100%",height:"100%",border:0};function B(e){return e instanceof Error?e:new Error(String(e))}function Te(){return(0,f.jsx)("div",{children:"Loading CRM\u2026"})}function _e(e,t){return(0,f.jsxs)("div",{children:[(0,f.jsxs)("p",{children:["Couldn\u2019t load the CRM: ",e.message]}),(0,f.jsx)("button",{type:"button",onClick:t,children:"Try again"})]})}var te=(0,s.forwardRef)(function(t,r){let{getSession:o,crmEmbedOrigin:n,className:l,style:c,title:A="CRM",onReady:d,onError:b,onRouteChange:C,hostProvidesNav:H,initialPath:E,theme:g,locale:i,brand:a,capabilities:p,hostName:M,onHostAction:L,renderLoading:X,renderError:F}=t,$=(0,s.useRef)(null),[I,q]=(0,s.useState)(null),[x,U]=(0,s.useState)(null),[S,T]=(0,s.useState)(null),[ne,re]=(0,s.useState)(0),_=(0,s.useRef)(null),N=(0,s.useRef)(null);(0,s.useImperativeHandle)(r,()=>({navigate:m=>{N.current?.navigate(m)}}),[]);let O=(0,s.useRef)(o),D=(0,s.useRef)(d),v=(0,s.useRef)(b),z=(0,s.useRef)(C),j=(0,s.useRef)(L);(0,s.useEffect)(()=>{O.current=o,D.current=d,v.current=b,z.current=C,j.current=L});let oe=(0,s.useRef)(E),k=(0,s.useRef)({theme:g,locale:i,brand:a,capabilities:p,hostName:M});k.current={theme:g,locale:i,brand:a,capabilities:p,hostName:M};let W=(0,s.useCallback)(()=>{_.current=null,T(null),q(null),U(null),re(m=>m+1)},[]);(0,s.useEffect)(()=>{let m=!1;return(async()=>{try{let h=await O.current();if(m)return;_.current={accessToken:h.accessToken},U(h.workspaceId);let u=V(n,h.workspaceId),y=oe.current??"",Q=[...H?["hostnav=1"]:[],...Y(k.current)],ae=y.includes("?")?"&":"?",ce=u+y+(Q.length>0?ae+Q.join("&"):"");q(ce)}catch(h){if(m)return;let u=B(h);T(u),v.current?.(u)}})(),()=>{m=!0}},[n,H,ne]),(0,s.useEffect)(()=>{let m=$.current;if(!m||!I||!x)return;let h=null;try{h=ee({iframe:m,crmOrigin:n,getBearer:async()=>{let u=_.current;return u?(_.current=null,u):{accessToken:(await O.current()).accessToken}},hostContext:k.current,onRouteChange:u=>{z.current?.(u)},onHostAction:u=>{j.current?.(u)},onError:u=>{let y=B(u);T(y),v.current?.(y)}})}catch(u){let y=B(u);T(y),v.current?.(y);return}return N.current=h,D.current?.({workspaceId:x}),()=>{h?.dispose(),N.current=null}},[I,x,n]);let se=JSON.stringify(a??null),ie=JSON.stringify(p??null),K=(0,s.useRef)(!1);return(0,s.useEffect)(()=>{let m=a?{brand:a}:K.current?{brand:null}:{};K.current=!!a,N.current?.setContext({theme:g,locale:i,capabilities:p,hostName:M,...m})},[g,i,se,ie,M]),S?(0,f.jsx)(f.Fragment,{children:F?F(S,W):_e(S,W)}):I?(0,f.jsx)("iframe",{ref:$,src:I,title:A,className:l,style:{...Ie,...c}}):(0,f.jsx)(f.Fragment,{children:X?X():Te()})}),Ne=te;0&&(module.exports={CrmEmbed,crmSession});
|
|
2
2
|
//# sourceMappingURL=embed-react.cjs.map
|
package/dist/embed-react.cjs.map
CHANGED
|
@@ -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 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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,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
|
+
{"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 CrmHostCapability,\n type CrmHostActionRequest,\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 type CrmHostCapability, type CrmHostActionRequest,\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 /**\n * Host actions the CRM may offer its users (\"create-lead\", \"open-person\"). List only what\n * `onHostAction` really handles. Sent over the channel, never in the URL. Gates the CRM's\n * UI only: authorise every action on your server too.\n */\n capabilities?: CrmHostCapability[];\n /** Short name of your app (max 40 chars), used on CRM buttons and cards, e.g. \"myEdu\". */\n hostName?: string;\n /** The user asked for a host action (create an enquiry, open a person). See `capabilities`. */\n onHostAction?: (request: CrmHostActionRequest) => void;\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 capabilities,\n hostName,\n onHostAction,\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 const onHostActionRef = useRef(onHostAction);\n useEffect(() => {\n getSessionRef.current = getSession;\n onReadyRef.current = onReady;\n onErrorRef.current = onError;\n onRouteChangeRef.current = onRouteChange;\n onHostActionRef.current = onHostAction;\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({\n theme, locale, brand, capabilities, hostName,\n });\n hostContextRef.current = {\n theme, locale, brand, capabilities, hostName,\n };\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 onHostAction: (request) => { onHostActionRef.current?.(request); },\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 capabilitiesKey = JSON.stringify(capabilities ?? 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({\n theme, locale, capabilities, hostName, ...brandUpdate,\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps -- brandKey and capabilitiesKey stand in for the objects\n }, [theme, locale, brandKey, capabilitiesKey, hostName]);\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 * The same message carries `capabilities` (which host actions the CRM may offer) and\n * `hostName` (a label for the host app). Those two ride on the channel only, never the URL.\n * 7. CRM iframe sends { type: 'crm:host-action', requestId, action: ... } when the user asks for\n * something only the host can do (see {@link CrmHostAction}). Delivered to `onHostAction`.\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/** Host actions the CRM may offer. The host lists the ones it implements in `capabilities`. */\nexport type CrmHostCapability = 'create-lead' | 'open-person';\n\n/** Who the user is acting on, as the CRM shows it. Only what the user can see is sent. */\nexport interface CrmHostActionContact {\n /** The CRM contact id. */\n crmContactId: string;\n name?: string;\n phone?: string;\n email?: string;\n}\n\n/**\n * Something the user asked the host to do from inside the embedded CRM.\n * Capabilities gate the CRM's UI only: the host MUST re-authorise every action server-side\n * and treat every field as untrusted input.\n */\nexport type CrmHostAction =\n | {\n action: 'create-lead';\n contact: CrmHostActionContact;\n conversationId: string;\n /** Channel of the conversation, e.g. \"whatsapp\". */\n channel?: string;\n /** The last inbound message text, at most 280 characters. */\n messageSnippet?: string;\n }\n | { action: 'open-person'; contact: { crmContactId: string } };\n\n/** A {@link CrmHostAction} as delivered to `onHostAction`, with the CRM's request id. */\nexport type CrmHostActionRequest = CrmHostAction & { requestId: string };\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 * Host actions the CRM may offer. Channel only (never in the URL). Known values only,\n * de-duplicated, at most 8. A new list REPLACES the old one; `[]` turns every action off.\n * Omitted: unchanged (none before the first value).\n */\n capabilities?: CrmHostCapability[];\n /** Short name of the host app (max 40 chars), shown on buttons and cards, e.g. \"myEdu\". Channel only. */\n hostName?: string;\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_CAPABILITIES: readonly string[] = ['create-lead', 'open-person'];\nconst CAPABILITIES_MAX = 8;\nconst HOST_NAME_MAX = 40;\nconst ACTION_REQUEST_ID_MAX = 64;\nconst ACTION_ID_MAX = 100;\nconst ACTION_NAME_MAX = 200;\nconst ACTION_EMAIL_MAX = 320;\nconst ACTION_PHONE_MAX = 40;\nconst ACTION_CHANNEL_MAX = 40;\n/** Longest `messageSnippet` the CRM sends and the host accepts. */\nexport const HOST_ACTION_SNIPPET_MAX = 280;\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 if (Array.isArray(ctx?.capabilities)) {\n const known = ctx.capabilities.filter((c): c is CrmHostCapability => HOST_CAPABILITIES.includes(c));\n out.capabilities = [...new Set(known)].slice(0, CAPABILITIES_MAX);\n }\n if (typeof ctx?.hostName === 'string') {\n const name = ctx.hostName.trim();\n if (name && name.length <= HOST_NAME_MAX && !/[\\u0000-\\u001f\\u007f]/.test(name)) out.hostName = name;\n }\n return out;\n}\n\nfunction boundedString(value: unknown, max: number, required: boolean): string | undefined | null {\n if (value === undefined) return required ? null : undefined;\n if (typeof value !== 'string') return null;\n const v = value.trim();\n if (v.length > max) return null;\n if (!v) return required ? null : undefined;\n return v;\n}\n\n/**\n * Validates a `crm:host-action` port message. Returns a clean request, or null when the\n * message is malformed, has an unknown action, or any field is too long. Unknown fields are\n * dropped. Never throws.\n */\nexport function parseHostActionMessage(data: unknown): CrmHostActionRequest | null {\n if (!data || typeof data !== 'object') return null;\n const m = data as Record<string, unknown>;\n if (m.type !== 'crm:host-action') return null;\n const requestId = boundedString(m.requestId, ACTION_REQUEST_ID_MAX, true);\n if (!requestId) return null;\n const c = m.contact;\n if (!c || typeof c !== 'object' || Array.isArray(c)) return null;\n const rc = c as Record<string, unknown>;\n const crmContactId = boundedString(rc.crmContactId, ACTION_ID_MAX, true);\n if (!crmContactId) return null;\n\n if (m.action === 'open-person') {\n return { requestId, action: 'open-person', contact: { crmContactId } };\n }\n if (m.action !== 'create-lead') return null;\n\n const name = boundedString(rc.name, ACTION_NAME_MAX, false);\n const phone = boundedString(rc.phone, ACTION_PHONE_MAX, false);\n const email = boundedString(rc.email, ACTION_EMAIL_MAX, false);\n const conversationId = boundedString(m.conversationId, ACTION_ID_MAX, true);\n const channel = boundedString(m.channel, ACTION_CHANNEL_MAX, false);\n const messageSnippet = boundedString(m.messageSnippet, HOST_ACTION_SNIPPET_MAX, false);\n if ([name, phone, email, channel, messageSnippet].some((v) => v === null) || !conversationId) return null;\n\n const contact: CrmHostActionContact = { crmContactId };\n if (name) contact.name = name;\n if (phone) contact.phone = phone;\n if (email) contact.email = email;\n const out: CrmHostActionRequest = {\n requestId, action: 'create-lead', contact, conversationId,\n };\n if (channel) out.channel = channel;\n if (messageSnippet) out.messageSnippet = messageSnippet;\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 /**\n * Called when the user asks for something only the host can do (a {@link CrmHostAction}).\n * Messages that are malformed, oversize or of an unknown action never reach it, and nothing\n * is delivered before the handshake completes. Re-authorise every action on your server.\n */\n onHostAction?: (request: CrmHostActionRequest) => void;\n /** Initial theme/locale/capabilities, 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 | { type: 'crm:host-action'; requestId: string };\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 acked = false;\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 || Object.keys(context).length === 0) 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 acked = true;\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'crm:host-action') {\n if (!acked) return; // nothing counts before the handshake completes\n const request = parseHostActionMessage(data);\n if (request) opts.onHostAction?.(request);\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 acked = false;\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,GAAA,eAAAC,EAAA,YAAAC,KAAA,eAAAC,GAAAL,IAwBA,IAAAM,EAEO,iBCoGP,IAAMC,GAAuC,CAAC,cAAe,aAAa,EAY1E,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,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AAG,SAAAsB,EAAcA,EAAYtB,EAAOC,CAAK,EAAIF,GAAaC,EAAOC,CAAK,EAAE,EAG5EuB,KAKH,OAAC,UACC,IAAKD,EACL,IAAKC,EACL,MAAOf,EACP,UAAWF,EACX,MAAO,CAAE,GAAGZ,GAAsB,GAAGa,CAAM,EAC7C,KAVO,mBAAG,SAAAa,EAAgBA,EAAc,EAAIvB,GAAe,EAAE,CAYjE,CACF,EAEO8D,GAAQ1D","names":["embed_react_exports","__export","CrmEmbed","crmSession","embed_react_default","__toCommonJS","import_react","HOST_CAPABILITIES","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","known","c","HOST_CAPABILITIES","name","boundedString","max","required","parseHostActionMessage","data","requestId","rc","crmContactId","phone","email","conversationId","channel","messageSnippet","contact","hostContextQuery","pairs","isReady","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","acked","disposed","context","sendContext","extra","msg","deliverBearer","bearer","err","onPortMessage","e","request","ok","startHandshake","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","capabilities","hostName","onHostAction","renderLoading","renderError","iframeRef","embedUrl","setEmbedUrl","workspaceId","setWorkspaceId","setError","attempt","setAttempt","primedBearerRef","hostRef","path","getSessionRef","onReadyRef","onErrorRef","onRouteChangeRef","onHostActionRef","initialPathRef","hostContextRef","n","cancelled","session","base","buildCrmEmbedUrl","query","hostContextQuery","separator","url","e","iframe","host","createCrmEmbedHost","primed","request","brandKey","capabilitiesKey","hadBrandRef","brandUpdate","embed_react_default"]}
|
package/dist/embed-react.d.cts
CHANGED
|
@@ -31,6 +31,39 @@ interface CrmHostBrand {
|
|
|
31
31
|
/** Font for page titles, same rules as `fontFamily`, e.g. `"Fraunces, Georgia, serif"`. */
|
|
32
32
|
displayFontFamily?: string;
|
|
33
33
|
}
|
|
34
|
+
/** Host actions the CRM may offer. The host lists the ones it implements in `capabilities`. */
|
|
35
|
+
type CrmHostCapability = 'create-lead' | 'open-person';
|
|
36
|
+
/** Who the user is acting on, as the CRM shows it. Only what the user can see is sent. */
|
|
37
|
+
interface CrmHostActionContact {
|
|
38
|
+
/** The CRM contact id. */
|
|
39
|
+
crmContactId: string;
|
|
40
|
+
name?: string;
|
|
41
|
+
phone?: string;
|
|
42
|
+
email?: string;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Something the user asked the host to do from inside the embedded CRM.
|
|
46
|
+
* Capabilities gate the CRM's UI only: the host MUST re-authorise every action server-side
|
|
47
|
+
* and treat every field as untrusted input.
|
|
48
|
+
*/
|
|
49
|
+
type CrmHostAction = {
|
|
50
|
+
action: 'create-lead';
|
|
51
|
+
contact: CrmHostActionContact;
|
|
52
|
+
conversationId: string;
|
|
53
|
+
/** Channel of the conversation, e.g. "whatsapp". */
|
|
54
|
+
channel?: string;
|
|
55
|
+
/** The last inbound message text, at most 280 characters. */
|
|
56
|
+
messageSnippet?: string;
|
|
57
|
+
} | {
|
|
58
|
+
action: 'open-person';
|
|
59
|
+
contact: {
|
|
60
|
+
crmContactId: string;
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
/** A {@link CrmHostAction} as delivered to `onHostAction`, with the CRM's request id. */
|
|
64
|
+
type CrmHostActionRequest = CrmHostAction & {
|
|
65
|
+
requestId: string;
|
|
66
|
+
};
|
|
34
67
|
/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */
|
|
35
68
|
interface CrmSessionResult {
|
|
36
69
|
accessToken: string;
|
|
@@ -126,6 +159,16 @@ interface CrmEmbedProps {
|
|
|
126
159
|
* {@link CrmHostBrand}. Omitted: the CRM keeps its own look.
|
|
127
160
|
*/
|
|
128
161
|
brand?: CrmHostBrand;
|
|
162
|
+
/**
|
|
163
|
+
* Host actions the CRM may offer its users ("create-lead", "open-person"). List only what
|
|
164
|
+
* `onHostAction` really handles. Sent over the channel, never in the URL. Gates the CRM's
|
|
165
|
+
* UI only: authorise every action on your server too.
|
|
166
|
+
*/
|
|
167
|
+
capabilities?: CrmHostCapability[];
|
|
168
|
+
/** Short name of your app (max 40 chars), used on CRM buttons and cards, e.g. "myEdu". */
|
|
169
|
+
hostName?: string;
|
|
170
|
+
/** The user asked for a host action (create an enquiry, open a person). See `capabilities`. */
|
|
171
|
+
onHostAction?: (request: CrmHostActionRequest) => void;
|
|
129
172
|
/** Custom loading UI. Defaults to a minimal message. */
|
|
130
173
|
renderLoading?: () => ReactNode;
|
|
131
174
|
/** Custom error UI. Defaults to the message + a Retry button. */
|
|
@@ -139,4 +182,4 @@ interface CrmEmbedProps {
|
|
|
139
182
|
*/
|
|
140
183
|
declare const CrmEmbed: react.ForwardRefExoticComponent<CrmEmbedProps & react.RefAttributes<CrmEmbedHandle>>;
|
|
141
184
|
|
|
142
|
-
export { CrmEmbed, type CrmEmbedHandle, type CrmEmbedProps, type CrmEmbedSession, type CrmHostBrand, type CrmHostTheme, type CrmSessionResult, crmSession, CrmEmbed as default };
|
|
185
|
+
export { CrmEmbed, type CrmEmbedHandle, type CrmEmbedProps, type CrmEmbedSession, type CrmHostActionRequest, type CrmHostBrand, type CrmHostCapability, type CrmHostTheme, type CrmSessionResult, crmSession, CrmEmbed as default };
|
package/dist/embed-react.d.ts
CHANGED
|
@@ -31,6 +31,39 @@ interface CrmHostBrand {
|
|
|
31
31
|
/** Font for page titles, same rules as `fontFamily`, e.g. `"Fraunces, Georgia, serif"`. */
|
|
32
32
|
displayFontFamily?: string;
|
|
33
33
|
}
|
|
34
|
+
/** Host actions the CRM may offer. The host lists the ones it implements in `capabilities`. */
|
|
35
|
+
type CrmHostCapability = 'create-lead' | 'open-person';
|
|
36
|
+
/** Who the user is acting on, as the CRM shows it. Only what the user can see is sent. */
|
|
37
|
+
interface CrmHostActionContact {
|
|
38
|
+
/** The CRM contact id. */
|
|
39
|
+
crmContactId: string;
|
|
40
|
+
name?: string;
|
|
41
|
+
phone?: string;
|
|
42
|
+
email?: string;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Something the user asked the host to do from inside the embedded CRM.
|
|
46
|
+
* Capabilities gate the CRM's UI only: the host MUST re-authorise every action server-side
|
|
47
|
+
* and treat every field as untrusted input.
|
|
48
|
+
*/
|
|
49
|
+
type CrmHostAction = {
|
|
50
|
+
action: 'create-lead';
|
|
51
|
+
contact: CrmHostActionContact;
|
|
52
|
+
conversationId: string;
|
|
53
|
+
/** Channel of the conversation, e.g. "whatsapp". */
|
|
54
|
+
channel?: string;
|
|
55
|
+
/** The last inbound message text, at most 280 characters. */
|
|
56
|
+
messageSnippet?: string;
|
|
57
|
+
} | {
|
|
58
|
+
action: 'open-person';
|
|
59
|
+
contact: {
|
|
60
|
+
crmContactId: string;
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
/** A {@link CrmHostAction} as delivered to `onHostAction`, with the CRM's request id. */
|
|
64
|
+
type CrmHostActionRequest = CrmHostAction & {
|
|
65
|
+
requestId: string;
|
|
66
|
+
};
|
|
34
67
|
/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */
|
|
35
68
|
interface CrmSessionResult {
|
|
36
69
|
accessToken: string;
|
|
@@ -126,6 +159,16 @@ interface CrmEmbedProps {
|
|
|
126
159
|
* {@link CrmHostBrand}. Omitted: the CRM keeps its own look.
|
|
127
160
|
*/
|
|
128
161
|
brand?: CrmHostBrand;
|
|
162
|
+
/**
|
|
163
|
+
* Host actions the CRM may offer its users ("create-lead", "open-person"). List only what
|
|
164
|
+
* `onHostAction` really handles. Sent over the channel, never in the URL. Gates the CRM's
|
|
165
|
+
* UI only: authorise every action on your server too.
|
|
166
|
+
*/
|
|
167
|
+
capabilities?: CrmHostCapability[];
|
|
168
|
+
/** Short name of your app (max 40 chars), used on CRM buttons and cards, e.g. "myEdu". */
|
|
169
|
+
hostName?: string;
|
|
170
|
+
/** The user asked for a host action (create an enquiry, open a person). See `capabilities`. */
|
|
171
|
+
onHostAction?: (request: CrmHostActionRequest) => void;
|
|
129
172
|
/** Custom loading UI. Defaults to a minimal message. */
|
|
130
173
|
renderLoading?: () => ReactNode;
|
|
131
174
|
/** Custom error UI. Defaults to the message + a Retry button. */
|
|
@@ -139,4 +182,4 @@ interface CrmEmbedProps {
|
|
|
139
182
|
*/
|
|
140
183
|
declare const CrmEmbed: react.ForwardRefExoticComponent<CrmEmbedProps & react.RefAttributes<CrmEmbedHandle>>;
|
|
141
184
|
|
|
142
|
-
export { CrmEmbed, type CrmEmbedHandle, type CrmEmbedProps, type CrmEmbedSession, type CrmHostBrand, type CrmHostTheme, type CrmSessionResult, crmSession, CrmEmbed as default };
|
|
185
|
+
export { CrmEmbed, type CrmEmbedHandle, type CrmEmbedProps, type CrmEmbedSession, type CrmHostActionRequest, type CrmHostBrand, type CrmHostCapability, type CrmHostTheme, type CrmSessionResult, crmSession, CrmEmbed as default };
|
package/dist/embed-react.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{forwardRef as
|
|
1
|
+
import{forwardRef as He,useCallback as Ee,useEffect as x,useImperativeHandle as Re,useRef as f,useState as S}from"react";var ue=["create-lead","open-person"];var de=["light","dark","system"],me=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/,fe=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i,ge=/^(\d{1,2}(?:\.\d{1,2})?)px$/,Ce=/^[A-Za-z0-9 ,'"_-]+$/;var pe=["accent","accentForeground","background","surface","border","foreground","mutedForeground"];function Z(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 Y(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of pe){let c=e[n];if(typeof c=="string"&&fe.test(c.trim())){let a=c.trim().toLowerCase();a.length===4&&(a=`#${a[1]}${a[1]}${a[2]}${a[2]}${a[3]}${a[3]}`),t[n]=a}}if(typeof e.radius=="string"){let n=ge.exec(e.radius.trim());n&&Number(n[1])<=24&&(t.radius=`${Number(n[1])}px`)}let r=Z(e.fontFamily);r&&(t.fontFamily=r);let o=Z(e.displayFontFamily);return o&&(t.displayFontFamily=o),Object.keys(t).length>0?t:void 0}function he(e){let t=Y(e);if(!t)return null;let r=new TextEncoder().encode(JSON.stringify(t)),o="";r.forEach(c=>{o+=String.fromCharCode(c)});let n=btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return n.length<=1500?n:null}function B(e){let t={};if(e?.brand===null)t.brand=null;else{let r=Y(e?.brand);r&&(t.brand=r)}if(e?.theme&&de.includes(e.theme)&&(t.theme=e.theme),typeof e?.locale=="string"&&me.test(e.locale.trim())&&(t.locale=e.locale.trim()),Array.isArray(e?.capabilities)){let r=e.capabilities.filter(o=>ue.includes(o));t.capabilities=[...new Set(r)].slice(0,8)}if(typeof e?.hostName=="string"){let r=e.hostName.trim();r&&r.length<=40&&!/[\u0000-\u001f\u007f]/.test(r)&&(t.hostName=r)}return t}function E(e,t,r){if(e===void 0)return r?null:void 0;if(typeof e!="string")return null;let o=e.trim();return o.length>t?null:o||(r?null:void 0)}function ye(e){if(!e||typeof e!="object")return null;let t=e;if(t.type!=="crm:host-action")return null;let r=E(t.requestId,64,!0);if(!r)return null;let o=t.contact;if(!o||typeof o!="object"||Array.isArray(o))return null;let n=o,c=E(n.crmContactId,100,!0);if(!c)return null;if(t.action==="open-person")return{requestId:r,action:"open-person",contact:{crmContactId:c}};if(t.action!=="create-lead")return null;let a=E(n.name,200,!1),y=E(n.phone,40,!1),u=E(n.email,320,!1),A=E(t.conversationId,100,!0),g=E(t.channel,40,!1),b=E(t.messageSnippet,280,!1);if([a,y,u,g,b].some(s=>s===null)||!A)return null;let H={crmContactId:c};a&&(H.name=a),y&&(H.phone=y),u&&(H.email=u);let m={requestId:r,action:"create-lead",contact:H,conversationId:A};return g&&(m.channel=g),b&&(m.messageSnippet=b),m}function G(e){let t=B(e),r=[];t.theme&&r.push(`theme=${encodeURIComponent(t.theme)}`),t.locale&&r.push(`locale=${encodeURIComponent(t.locale)}`);let o=t.brand?he(t.brand):null;return o&&r.push(`brand=${o}`),r}function Ae(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function be(e,t){return async()=>{let r=await fetch(e,{method:"POST",...t}),o=await r.json().catch(()=>({}));if(!r.ok){let c=o?.error;throw new Error(c?`CRM session failed: ${c}`:`CRM session failed (HTTP ${r.status})`)}let n=o;if(typeof n?.accessToken!="string"||typeof n?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return n}}function V(e,t){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(t)}`}function ee(e){let t=e.windowTarget??window,r=e.createChannel??(()=>new MessageChannel),o=e.devAllowAnyOrigin?"*":e.crmOrigin,n=null,c="",a=!1,y=!1,u=B(e.hostContext);function A(s){if(s){n?.postMessage({type:"crm:host-context",...u,...s});return}if(!n||Object.keys(u).length===0)return;let i={type:"crm:host-context",...u};n.postMessage(i)}async function g(){try{let s=await e.getBearer();return n?.postMessage({type:"auth-tokens",accessToken:s.accessToken,refreshToken:s.refreshToken??""}),A(),!0}catch(s){return e.onError?.(s),!1}}function b(s){let i=s.data;if(i)if(i.type==="channel-ack"){if(i.nonce!==c)return;a=!0,g()}else if(i.type==="route-change")e.onRouteChange?.(i.path);else if(i.type==="crm:host-action"){if(!a)return;let C=ye(i);C&&e.onHostAction?.(C)}else i.type==="resize"?e.onResize?.(i.height):i.type==="session-expired"&&g().then(C=>{C&&n?.postMessage({type:"session-refreshed"})})}function H(){n?.close(),a=!1;let s=r();n=s.port1,c=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,n.onmessage=b,n.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:c},o,[s.port2])}function m(s){y||s.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&s.origin!==e.crmOrigin||Ae(s.data)&&H())}return t.addEventListener("message",m),{navigate(s){n?.postMessage({type:"navigate",path:s})},setContext(s){let i=B(s);u={...u,...i},i.brand===null&&delete u.brand,A(i.brand===null?{brand:null}:void 0)},dispose(){y=!0,t.removeEventListener("message",m),n?.close(),n=null}}}import{Fragment as ne,jsx as R,jsxs as te}from"react/jsx-runtime";var Me={width:"100%",height:"100%",border:0};function L(e){return e instanceof Error?e:new Error(String(e))}function Ie(){return R("div",{children:"Loading CRM\u2026"})}function Te(e,t){return te("div",{children:[te("p",{children:["Couldn\u2019t load the CRM: ",e.message]}),R("button",{type:"button",onClick:t,children:"Try again"})]})}var _e=He(function(t,r){let{getSession:o,crmEmbedOrigin:n,className:c,style:a,title:y="CRM",onReady:u,onError:A,onRouteChange:g,hostProvidesNav:b,initialPath:H,theme:m,locale:s,brand:i,capabilities:C,hostName:M,onHostAction:X,renderLoading:F,renderError:$}=t,q=f(null),[I,U]=S(null),[O,D]=S(null),[k,T]=S(null),[re,oe]=S(0),_=f(null),N=f(null);Re(r,()=>({navigate:d=>{N.current?.navigate(d)}}),[]);let w=f(o),z=f(u),v=f(A),j=f(g),W=f(X);x(()=>{w.current=o,z.current=u,v.current=A,j.current=g,W.current=X});let se=f(H),P=f({theme:m,locale:s,brand:i,capabilities:C,hostName:M});P.current={theme:m,locale:s,brand:i,capabilities:C,hostName:M};let K=Ee(()=>{_.current=null,T(null),U(null),D(null),oe(d=>d+1)},[]);x(()=>{let d=!1;return(async()=>{try{let p=await w.current();if(d)return;_.current={accessToken:p.accessToken},D(p.workspaceId);let l=V(n,p.workspaceId),h=se.current??"",J=[...b?["hostnav=1"]:[],...G(P.current)],ce=h.includes("?")?"&":"?",le=l+h+(J.length>0?ce+J.join("&"):"");U(le)}catch(p){if(d)return;let l=L(p);T(l),v.current?.(l)}})(),()=>{d=!0}},[n,b,re]),x(()=>{let d=q.current;if(!d||!I||!O)return;let p=null;try{p=ee({iframe:d,crmOrigin:n,getBearer:async()=>{let l=_.current;return l?(_.current=null,l):{accessToken:(await w.current()).accessToken}},hostContext:P.current,onRouteChange:l=>{j.current?.(l)},onHostAction:l=>{W.current?.(l)},onError:l=>{let h=L(l);T(h),v.current?.(h)}})}catch(l){let h=L(l);T(h),v.current?.(h);return}return N.current=p,z.current?.({workspaceId:O}),()=>{p?.dispose(),N.current=null}},[I,O,n]);let ie=JSON.stringify(i??null),ae=JSON.stringify(C??null),Q=f(!1);return x(()=>{let d=i?{brand:i}:Q.current?{brand:null}:{};Q.current=!!i,N.current?.setContext({theme:m,locale:s,capabilities:C,hostName:M,...d})},[m,s,ie,ae,M]),k?R(ne,{children:$?$(k,K):Te(k,K)}):I?R("iframe",{ref:q,src:I,title:y,className:c,style:{...Me,...a}}):R(ne,{children:F?F():Ie()})}),Se=_e;export{_e as CrmEmbed,be as crmSession,Se as default};
|
|
2
2
|
//# sourceMappingURL=embed-react.js.map
|