@first-to-fly/crm-sdk 1.3.0 → 1.4.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 CHANGED
@@ -308,6 +308,35 @@ host.dispose();
308
308
  - Assertions (Option B) are single-use and live ≤120s — always mint fresh; never cache one.
309
309
  - `jose` is only required for Option B (`embed-server` assertion path): `npm i jose`.
310
310
 
311
+ ### React embed component
312
+
313
+ If you use React, `@first-to-fly/crm-sdk/embed-react` wraps all of the above
314
+ (iframe, MessageChannel handshake, bearer refresh on expiry, and
315
+ loading/error/retry states) into a single drop-in `<CrmEmbed>` component. You
316
+ just supply `getSession` (returns the CRM bearer + the workspace to embed) and
317
+ the CRM embed origin.
318
+
319
+ ```bash
320
+ npm install @first-to-fly/crm-sdk react
321
+ ```
322
+
323
+ ```tsx
324
+ import { CrmEmbed } from '@first-to-fly/crm-sdk/embed-react';
325
+
326
+ <CrmEmbed
327
+ crmEmbedOrigin="https://crm.example.com"
328
+ getSession={async () => (await fetch('/api/crm/session', { method: 'POST' })).json()}
329
+ />
330
+ ```
331
+
332
+ `getSession()` must resolve to `{ accessToken, workspaceId, expiresIn? }` —
333
+ typically from your own backend endpoint running `createEmbedSessionWithKey`.
334
+ Optional props: `className`, `style`, `title`, `onReady`, `onError`,
335
+ `renderLoading`, `renderError`.
336
+
337
+ React is an **optional peer dependency** — only pull in this entry if you use
338
+ React. The low-level `embed-host` remains available for non-React consumers.
339
+
311
340
  ## Calling CRM APIs from your backend
312
341
 
313
342
  Once your server has a CRM bearer (from `createEmbedSessionWithKey`) — or an
@@ -0,0 +1,2 @@
1
+ "use strict";var M=Object.defineProperty;var B=Object.getOwnPropertyDescriptor;var N=Object.getOwnPropertyNames;var U=Object.prototype.hasOwnProperty;var W=(e,n)=>{for(var i in n)M(e,i,{get:n[i],enumerable:!0})},z=(e,n,i,u)=>{if(n&&typeof n=="object"||typeof n=="function")for(let t of N(n))!U.call(e,t)&&t!==i&&M(e,t,{get:()=>n[t],enumerable:!(u=B(n,t))||u.enumerable});return e};var D=e=>z(M({},"__esModule",{value:!0}),e);var q={};W(q,{CrmEmbed:()=>H,default:()=>j});module.exports=D(q);var o=require("react");function F(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function O(e,n){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(n)}`}function x(e){let n=e.windowTarget??window,i=e.createChannel??(()=>new MessageChannel),u=e.devAllowAnyOrigin?"*":e.crmOrigin,t=null,g="",f=!1;async function p(){try{let r=await e.getBearer();t?.postMessage({type:"auth-tokens",accessToken:r.accessToken,refreshToken:r.refreshToken??""})}catch(r){e.onError?.(r)}}function y(r){let a=r.data;if(a)if(a.type==="channel-ack"){if(a.nonce!==g)return;p()}else a.type==="route-change"?e.onRouteChange?.(a.path):a.type==="resize"?e.onResize?.(a.height):a.type==="session-expired"&&(p(),t?.postMessage({type:"session-refreshed"}))}function C(){t?.close();let r=i();t=r.port1,g=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,t.onmessage=y,t.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:g},u,[r.port2])}function E(r){f||r.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&r.origin!==e.crmOrigin||F(r.data)&&C())}return n.addEventListener("message",E),{navigate(r){t?.postMessage({type:"navigate",path:r})},dispose(){f=!0,n.removeEventListener("message",E),t?.close(),t=null}}}var s=require("react/jsx-runtime"),$={width:"100%",height:"100%",border:0};function T(e){return e instanceof Error?e:new Error(String(e))}function _(){return(0,s.jsx)("div",{children:"Loading CRM\u2026"})}function Y(e,n){return(0,s.jsxs)("div",{children:[(0,s.jsxs)("p",{children:["Couldn\u2019t load the CRM: ",e.message]}),(0,s.jsx)("button",{type:"button",onClick:n,children:"Try again"})]})}function H(e){let{getSession:n,crmEmbedOrigin:i,className:u,style:t,title:g="CRM",onReady:f,onError:p,renderLoading:y,renderError:C}=e,E=(0,o.useRef)(null),[r,a]=(0,o.useState)(null),[R,S]=(0,o.useState)(null),[k,h]=(0,o.useState)(null),[P,A]=(0,o.useState)(0),v=(0,o.useRef)(null),w=(0,o.useRef)(n),L=(0,o.useRef)(f),b=(0,o.useRef)(p);(0,o.useEffect)(()=>{w.current=n,L.current=f,b.current=p});let I=(0,o.useCallback)(()=>{v.current=null,h(null),a(null),S(null),A(d=>d+1)},[]);return(0,o.useEffect)(()=>{let d=!1;return(async()=>{try{let l=await w.current();if(d)return;v.current={accessToken:l.accessToken},S(l.workspaceId),a(O(i,l.workspaceId))}catch(l){if(d)return;let c=T(l);h(c),b.current?.(c)}})(),()=>{d=!0}},[i,P]),(0,o.useEffect)(()=>{let d=E.current;if(!d||!r||!R)return;let l=null;try{l=x({iframe:d,crmOrigin:i,getBearer:async()=>{let c=v.current;return c?(v.current=null,c):{accessToken:(await w.current()).accessToken}},onError:c=>{let m=T(c);h(m),b.current?.(m)}})}catch(c){let m=T(c);h(m),b.current?.(m);return}return L.current?.({workspaceId:R}),()=>{l?.dispose()}},[r,R,i]),k?(0,s.jsx)(s.Fragment,{children:C?C(k,I):Y(k,I)}):r?(0,s.jsx)("iframe",{ref:E,src:r,title:g,className:u,style:{...$,...t}}):(0,s.jsx)(s.Fragment,{children:y?y():_()})}var j=H;0&&(module.exports={CrmEmbed});
2
+ //# sourceMappingURL=embed-react.cjs.map
@@ -0,0 +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 * `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 useCallback, useEffect, useRef, useState,\n} from 'react';\nimport type { CSSProperties, ReactNode } from 'react';\n\nimport {\n buildCrmEmbedUrl,\n createCrmEmbedHost,\n type CrmBearer,\n type CrmEmbedHost,\n} from './embed-host';\n\n/** What a partner's `getSession()` must resolve to. */\nexport interface CrmEmbedSession {\n /** Short-lived CRM bearer (access token) to hand to the iframe. */\n accessToken: string;\n /** The workspace to embed; used to build the iframe URL. */\n workspaceId: string;\n /** Optional TTL hint (seconds). Not required by the component today. */\n expiresIn?: number;\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 /** 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 */\nexport function CrmEmbed(props: CrmEmbedProps): ReactNode {\n const {\n getSession,\n crmEmbedOrigin,\n className,\n style,\n title = 'CRM',\n onReady,\n onError,\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 // Keep the latest callbacks in refs so the effects DON'T depend on their\n // identity. Partners routinely pass inline `getSession`/`onReady`/`onError`;\n // depending on them directly would re-run Phase 1 (re-fetch the session) and\n // 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 useEffect(() => {\n getSessionRef.current = getSession;\n onReadyRef.current = onReady;\n onErrorRef.current = onError;\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 — never on unrelated\n // parent re-renders (callbacks 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 setEmbedUrl(buildCrmEmbedUrl(crmEmbedOrigin, session.workspaceId));\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, 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 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 // Only signal ready once the host is actually wired.\n onReadyRef.current?.({ workspaceId });\n\n return () => { host?.dispose(); };\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\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 assertion 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 createEmbedSession() (see ./embed-server).\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/**\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<void> {\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 } catch (err) {\n opts.onError?.(err);\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).\n void deliverBearer();\n port?.postMessage({ type: 'session-refreshed' });\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,EAAA,GAAAC,EAAAD,EAAA,cAAAE,EAAA,YAAAC,IAAA,eAAAC,EAAAJ,GAmBA,IAAAK,EAEO,iBCiDP,SAASC,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CASO,SAASC,EAAiBC,EAAmBC,EAA6B,CAC/E,MAAO,GAAGD,EAAU,QAAQ,MAAO,EAAE,CAAC,UAAU,mBAAmBC,CAAW,CAAC,EACjF,CAMO,SAASC,EAAmBC,EAAyC,CAC1E,IAAMC,EAASD,EAAK,cAAgB,OAC9BE,EAAcF,EAAK,gBAAkB,IAAM,IAAI,gBAC/CG,EAAeH,EAAK,kBAAoB,IAAMA,EAAK,UAErDI,EAA2B,KAC3BC,EAAQ,GACRC,EAAW,GAEf,eAAeC,GAA+B,CAC5C,GAAI,CACF,IAAMC,EAAS,MAAMR,EAAK,UAAU,EACpCI,GAAM,YAAY,CAChB,KAAM,cACN,YAAaI,EAAO,YACpB,aAAcA,EAAO,cAAgB,EACvC,CAAC,CACH,OAASC,EAAK,CACZT,EAAK,UAAUS,CAAG,CACpB,CACF,CAEA,SAASC,EAAcC,EAAqC,CAC1D,IAAMhB,EAAOgB,EAAE,KACf,GAAKhB,EACL,GAAIA,EAAK,OAAS,cAAe,CAC/B,GAAIA,EAAK,QAAUU,EAAO,OACrBE,EAAc,CACrB,MAAWZ,EAAK,OAAS,eACvBK,EAAK,gBAAgBL,EAAK,IAAI,EACrBA,EAAK,OAAS,SAC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B,aAAU,IAAM,CACd,IAAMW,EAASjB,EAAU,QACzB,GAAI,CAACiB,GAAU,CAAChB,GAAY,CAACE,EAAa,OAE1C,IAAIe,EAA4B,KAChC,GAAI,CACFA,EAAOC,EAAmB,CACxB,OAAAF,EACA,UAAWzB,EACX,UAAW,SAAY,CACrB,IAAM4B,EAASZ,EAAgB,QAC/B,OAAIY,GACFZ,EAAgB,QAAU,KACnBY,GAGF,CAAE,aADO,MAAMX,EAAc,QAAQ,GACd,WAAY,CAC5C,EACA,QAAUzB,GAAQ,CAChB,IAAMgC,EAAIjC,EAAQC,CAAG,EACrBqB,EAASW,CAAC,EACVL,EAAW,UAAUK,CAAC,CACxB,CACF,CAAC,CACH,OAAShC,EAAK,CACZ,IAAMgC,EAAIjC,EAAQC,CAAG,EACrBqB,EAASW,CAAC,EACVL,EAAW,UAAUK,CAAC,EACtB,MACF,CAGA,OAAAN,EAAW,UAAU,CAAE,YAAAP,CAAY,CAAC,EAE7B,IAAM,CAAEe,GAAM,QAAQ,CAAG,CAClC,EAAG,CAACjB,EAAUE,EAAaX,CAAc,CAAC,EAEtCL,KACK,mBAAG,SAAAY,EAAcA,EAAYZ,EAAOC,CAAK,EAAIF,EAAaC,EAAOC,CAAK,EAAE,EAG5Ea,KAKH,OAAC,UACC,IAAKD,EACL,IAAKC,EACL,MAAON,EACP,UAAWF,EACX,MAAO,CAAE,GAAGX,EAAsB,GAAGY,CAAM,EAC7C,KAVO,mBAAG,SAAAI,EAAgBA,EAAc,EAAIb,EAAe,EAAE,CAYjE,CAEA,IAAOoC,EAAQhC","names":["embed_react_exports","__export","CrmEmbed","embed_react_default","__toCommonJS","import_react","isReady","data","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","startHandshake","channel","onWindowMessage","event","path","import_jsx_runtime","DEFAULT_IFRAME_STYLE","toError","err","DefaultLoading","DefaultError","error","retry","CrmEmbed","props","getSession","crmEmbedOrigin","className","style","title","onReady","onError","renderLoading","renderError","iframeRef","embedUrl","setEmbedUrl","workspaceId","setWorkspaceId","setError","attempt","setAttempt","primedBearerRef","getSessionRef","onReadyRef","onErrorRef","n","cancelled","session","buildCrmEmbedUrl","e","iframe","host","createCrmEmbedHost","primed","embed_react_default"]}
@@ -0,0 +1,66 @@
1
+ import { CSSProperties, ReactNode } from 'react';
2
+
3
+ /**
4
+ * Drop-in React component that embeds the First To Fly CRM as a cross-origin
5
+ * iframe, authenticated WITHOUT cookies.
6
+ *
7
+ * This wraps the low-level {@link ./embed-host | embed-host} helpers into a
8
+ * single component. You supply a `getSession()` that returns a CRM bearer plus
9
+ * the workspace to embed (typically by calling your own backend endpoint that
10
+ * runs `createEmbedSessionWithKey`), and the component handles:
11
+ * - resolving the session and building the iframe URL,
12
+ * - rendering the iframe and running the MessageChannel handshake,
13
+ * - reusing the initial bearer (no double-mint) and re-minting on expiry,
14
+ * - loading / error / retry states.
15
+ *
16
+ * `react` is an OPTIONAL peer dependency — only pull in this entry if you use
17
+ * React. Non-React consumers can keep using `./embed-host` directly.
18
+ *
19
+ * @packageDocumentation
20
+ */
21
+
22
+ /** What a partner's `getSession()` must resolve to. */
23
+ interface CrmEmbedSession {
24
+ /** Short-lived CRM bearer (access token) to hand to the iframe. */
25
+ accessToken: string;
26
+ /** The workspace to embed; used to build the iframe URL. */
27
+ workspaceId: string;
28
+ /** Optional TTL hint (seconds). Not required by the component today. */
29
+ expiresIn?: number;
30
+ }
31
+ interface CrmEmbedProps {
32
+ /**
33
+ * Resolves a CRM bearer + the workspace to embed. Called once on mount (and
34
+ * again on retry / session expiry). Typically calls your own backend endpoint
35
+ * that runs `createEmbedSessionWithKey`.
36
+ */
37
+ getSession: () => Promise<CrmEmbedSession>;
38
+ /**
39
+ * The CRM embed base origin, e.g. "https://crm.example.com". The iframe URL
40
+ * is `buildCrmEmbedUrl(crmEmbedOrigin, workspaceId)` and this origin is also
41
+ * used as the postMessage targetOrigin.
42
+ */
43
+ crmEmbedOrigin: string;
44
+ /** Class applied to the iframe. */
45
+ className?: string;
46
+ /** Inline style merged onto the iframe (overrides the fill-container default). */
47
+ style?: CSSProperties;
48
+ /** Iframe title (accessibility). Defaults to "CRM". */
49
+ title?: string;
50
+ /** Called after the iframe URL is built and mounted. */
51
+ onReady?: (info: {
52
+ workspaceId: string;
53
+ }) => void;
54
+ /** Called on any session / handshake error. */
55
+ onError?: (error: Error) => void;
56
+ /** Custom loading UI. Defaults to a minimal message. */
57
+ renderLoading?: () => ReactNode;
58
+ /** Custom error UI. Defaults to the message + a Retry button. */
59
+ renderError?: (error: Error, retry: () => void) => ReactNode;
60
+ }
61
+ /**
62
+ * Embed the First To Fly CRM in a React app. See {@link CrmEmbedProps}.
63
+ */
64
+ declare function CrmEmbed(props: CrmEmbedProps): ReactNode;
65
+
66
+ export { CrmEmbed, type CrmEmbedProps, type CrmEmbedSession, CrmEmbed as default };
@@ -0,0 +1,66 @@
1
+ import { CSSProperties, ReactNode } from 'react';
2
+
3
+ /**
4
+ * Drop-in React component that embeds the First To Fly CRM as a cross-origin
5
+ * iframe, authenticated WITHOUT cookies.
6
+ *
7
+ * This wraps the low-level {@link ./embed-host | embed-host} helpers into a
8
+ * single component. You supply a `getSession()` that returns a CRM bearer plus
9
+ * the workspace to embed (typically by calling your own backend endpoint that
10
+ * runs `createEmbedSessionWithKey`), and the component handles:
11
+ * - resolving the session and building the iframe URL,
12
+ * - rendering the iframe and running the MessageChannel handshake,
13
+ * - reusing the initial bearer (no double-mint) and re-minting on expiry,
14
+ * - loading / error / retry states.
15
+ *
16
+ * `react` is an OPTIONAL peer dependency — only pull in this entry if you use
17
+ * React. Non-React consumers can keep using `./embed-host` directly.
18
+ *
19
+ * @packageDocumentation
20
+ */
21
+
22
+ /** What a partner's `getSession()` must resolve to. */
23
+ interface CrmEmbedSession {
24
+ /** Short-lived CRM bearer (access token) to hand to the iframe. */
25
+ accessToken: string;
26
+ /** The workspace to embed; used to build the iframe URL. */
27
+ workspaceId: string;
28
+ /** Optional TTL hint (seconds). Not required by the component today. */
29
+ expiresIn?: number;
30
+ }
31
+ interface CrmEmbedProps {
32
+ /**
33
+ * Resolves a CRM bearer + the workspace to embed. Called once on mount (and
34
+ * again on retry / session expiry). Typically calls your own backend endpoint
35
+ * that runs `createEmbedSessionWithKey`.
36
+ */
37
+ getSession: () => Promise<CrmEmbedSession>;
38
+ /**
39
+ * The CRM embed base origin, e.g. "https://crm.example.com". The iframe URL
40
+ * is `buildCrmEmbedUrl(crmEmbedOrigin, workspaceId)` and this origin is also
41
+ * used as the postMessage targetOrigin.
42
+ */
43
+ crmEmbedOrigin: string;
44
+ /** Class applied to the iframe. */
45
+ className?: string;
46
+ /** Inline style merged onto the iframe (overrides the fill-container default). */
47
+ style?: CSSProperties;
48
+ /** Iframe title (accessibility). Defaults to "CRM". */
49
+ title?: string;
50
+ /** Called after the iframe URL is built and mounted. */
51
+ onReady?: (info: {
52
+ workspaceId: string;
53
+ }) => void;
54
+ /** Called on any session / handshake error. */
55
+ onError?: (error: Error) => void;
56
+ /** Custom loading UI. Defaults to a minimal message. */
57
+ renderLoading?: () => ReactNode;
58
+ /** Custom error UI. Defaults to the message + a Retry button. */
59
+ renderError?: (error: Error, retry: () => void) => ReactNode;
60
+ }
61
+ /**
62
+ * Embed the First To Fly CRM in a React app. See {@link CrmEmbedProps}.
63
+ */
64
+ declare function CrmEmbed(props: CrmEmbedProps): ReactNode;
65
+
66
+ export { CrmEmbed, type CrmEmbedProps, type CrmEmbedSession, CrmEmbed as default };
@@ -0,0 +1,2 @@
1
+ import{useCallback as W,useEffect as T,useRef as f,useState as b}from"react";function U(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function x(e,o){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(o)}`}function H(e){let o=e.windowTarget??window,c=e.createChannel??(()=>new MessageChannel),R=e.devAllowAnyOrigin?"*":e.crmOrigin,n=null,l="",u=!1;async function m(){try{let r=await e.getBearer();n?.postMessage({type:"auth-tokens",accessToken:r.accessToken,refreshToken:r.refreshToken??""})}catch(r){e.onError?.(r)}}function E(r){let t=r.data;if(t)if(t.type==="channel-ack"){if(t.nonce!==l)return;m()}else t.type==="route-change"?e.onRouteChange?.(t.path):t.type==="resize"?e.onResize?.(t.height):t.type==="session-expired"&&(m(),n?.postMessage({type:"session-refreshed"}))}function y(){n?.close();let r=c();n=r.port1,l=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,n.onmessage=E,n.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:l},R,[r.port2])}function g(r){u||r.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&r.origin!==e.crmOrigin||U(r.data)&&y())}return o.addEventListener("message",g),{navigate(r){n?.postMessage({type:"navigate",path:r})},dispose(){u=!0,o.removeEventListener("message",g),n?.close(),n=null}}}import{Fragment as A,jsx as p,jsxs as P}from"react/jsx-runtime";var z={width:"100%",height:"100%",border:0};function S(e){return e instanceof Error?e:new Error(String(e))}function D(){return p("div",{children:"Loading CRM\u2026"})}function F(e,o){return P("div",{children:[P("p",{children:["Couldn\u2019t load the CRM: ",e.message]}),p("button",{type:"button",onClick:o,children:"Try again"})]})}function $(e){let{getSession:o,crmEmbedOrigin:c,className:R,style:n,title:l="CRM",onReady:u,onError:m,renderLoading:E,renderError:y}=e,g=f(null),[r,t]=b(null),[k,L]=b(null),[w,C]=b(null),[B,N]=b(0),h=f(null),M=f(o),I=f(u),v=f(m);T(()=>{M.current=o,I.current=u,v.current=m});let O=W(()=>{h.current=null,C(null),t(null),L(null),N(i=>i+1)},[]);return T(()=>{let i=!1;return(async()=>{try{let a=await M.current();if(i)return;h.current={accessToken:a.accessToken},L(a.workspaceId),t(x(c,a.workspaceId))}catch(a){if(i)return;let s=S(a);C(s),v.current?.(s)}})(),()=>{i=!0}},[c,B]),T(()=>{let i=g.current;if(!i||!r||!k)return;let a=null;try{a=H({iframe:i,crmOrigin:c,getBearer:async()=>{let s=h.current;return s?(h.current=null,s):{accessToken:(await M.current()).accessToken}},onError:s=>{let d=S(s);C(d),v.current?.(d)}})}catch(s){let d=S(s);C(d),v.current?.(d);return}return I.current?.({workspaceId:k}),()=>{a?.dispose()}},[r,k,c]),w?p(A,{children:y?y(w,O):F(w,O)}):r?p("iframe",{ref:g,src:r,title:l,className:R,style:{...z,...n}}):p(A,{children:E?E():D()})}var q=$;export{$ as CrmEmbed,q as default};
2
+ //# sourceMappingURL=embed-react.js.map
@@ -0,0 +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 * `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 useCallback, useEffect, useRef, useState,\n} from 'react';\nimport type { CSSProperties, ReactNode } from 'react';\n\nimport {\n buildCrmEmbedUrl,\n createCrmEmbedHost,\n type CrmBearer,\n type CrmEmbedHost,\n} from './embed-host';\n\n/** What a partner's `getSession()` must resolve to. */\nexport interface CrmEmbedSession {\n /** Short-lived CRM bearer (access token) to hand to the iframe. */\n accessToken: string;\n /** The workspace to embed; used to build the iframe URL. */\n workspaceId: string;\n /** Optional TTL hint (seconds). Not required by the component today. */\n expiresIn?: number;\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 /** 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 */\nexport function CrmEmbed(props: CrmEmbedProps): ReactNode {\n const {\n getSession,\n crmEmbedOrigin,\n className,\n style,\n title = 'CRM',\n onReady,\n onError,\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 // Keep the latest callbacks in refs so the effects DON'T depend on their\n // identity. Partners routinely pass inline `getSession`/`onReady`/`onError`;\n // depending on them directly would re-run Phase 1 (re-fetch the session) and\n // 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 useEffect(() => {\n getSessionRef.current = getSession;\n onReadyRef.current = onReady;\n onErrorRef.current = onError;\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 — never on unrelated\n // parent re-renders (callbacks 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 setEmbedUrl(buildCrmEmbedUrl(crmEmbedOrigin, session.workspaceId));\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, 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 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 // Only signal ready once the host is actually wired.\n onReadyRef.current?.({ workspaceId });\n\n return () => { host?.dispose(); };\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\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 assertion 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 createEmbedSession() (see ./embed-server).\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/**\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<void> {\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 } catch (err) {\n opts.onError?.(err);\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).\n void deliverBearer();\n port?.postMessage({ type: 'session-refreshed' });\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":"AAmBA,OACE,eAAAA,EAAa,aAAAC,EAAW,UAAAC,EAAQ,YAAAC,MAC3B,QCiDP,SAASC,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CASO,SAASC,EAAiBC,EAAmBC,EAA6B,CAC/E,MAAO,GAAGD,EAAU,QAAQ,MAAO,EAAE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CAAG,EACrBuB,EAASa,CAAC,EACVP,EAAW,UAAUO,CAAC,EACtB,MACF,CAGA,OAAAR,EAAW,UAAU,CAAE,YAAAP,CAAY,CAAC,EAE7B,IAAM,CAAEiB,GAAM,QAAQ,CAAG,CAClC,EAAG,CAACpB,EAAUG,EAAab,CAAc,CAAC,EAEtCL,EACKP,EAAAD,EAAA,CAAG,SAAAoB,EAAcA,EAAYZ,EAAOC,CAAK,EAAIF,EAAaC,EAAOC,CAAK,EAAE,EAG5Ec,EAKHtB,EAAC,UACC,IAAKoB,EACL,IAAKE,EACL,MAAOP,EACP,UAAWF,EACX,MAAO,CAAE,GAAGX,EAAsB,GAAGY,CAAM,EAC7C,EAVOd,EAAAD,EAAA,CAAG,SAAAmB,EAAgBA,EAAc,EAAIb,EAAe,EAAE,CAYjE,CAEA,IAAOwC,EAAQpC","names":["useCallback","useEffect","useRef","useState","isReady","data","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","startHandshake","channel","onWindowMessage","event","path","Fragment","jsx","jsxs","DEFAULT_IFRAME_STYLE","toError","err","DefaultLoading","DefaultError","error","retry","CrmEmbed","props","getSession","crmEmbedOrigin","className","style","title","onReady","onError","renderLoading","renderError","iframeRef","useRef","embedUrl","setEmbedUrl","useState","workspaceId","setWorkspaceId","setError","attempt","setAttempt","primedBearerRef","getSessionRef","onReadyRef","onErrorRef","useEffect","useCallback","n","cancelled","session","buildCrmEmbedUrl","e","iframe","host","createCrmEmbedHost","primed","embed_react_default"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@first-to-fly/crm-sdk",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "CRM SDK — embed third-party apps inside the CRM, or embed the CRM inside your own SaaS (proxy-free, signed-assertion or API-key auth)",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -29,6 +29,16 @@
29
29
  "default": "./dist/embed-host.cjs"
30
30
  }
31
31
  },
32
+ "./embed-react": {
33
+ "import": {
34
+ "types": "./dist/embed-react.d.ts",
35
+ "default": "./dist/embed-react.js"
36
+ },
37
+ "require": {
38
+ "types": "./dist/embed-react.d.cts",
39
+ "default": "./dist/embed-react.cjs"
40
+ }
41
+ },
32
42
  "./embed-server": {
33
43
  "import": {
34
44
  "types": "./dist/embed-server.d.ts",
@@ -75,17 +85,26 @@
75
85
  "author": "First to Fly",
76
86
  "license": "MIT",
77
87
  "peerDependencies": {
78
- "jose": ">=5"
88
+ "jose": ">=5",
89
+ "react": ">=17"
79
90
  },
80
91
  "peerDependenciesMeta": {
81
92
  "jose": {
82
93
  "optional": true
94
+ },
95
+ "react": {
96
+ "optional": true
83
97
  }
84
98
  },
85
99
  "devDependencies": {
86
100
  "jose": "^5.9.6",
101
+ "@testing-library/react": "^16.1.0",
87
102
  "@types/jsdom": "^28.0.0",
103
+ "@types/react": "^18.3.12",
104
+ "@types/react-dom": "^18.3.1",
88
105
  "jsdom": "^28.1.0",
106
+ "react": "^18.3.1",
107
+ "react-dom": "^18.3.1",
89
108
  "tsup": "^8.5.1",
90
109
  "typescript": "^5.9.3",
91
110
  "vitest": "^4.0.18"