@first-to-fly/crm-sdk 1.4.3 → 1.6.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 +117 -1
- package/dist/api.cjs +1 -1
- package/dist/api.cjs.map +1 -1
- package/dist/api.d.cts +5 -711
- package/dist/api.d.ts +5 -711
- package/dist/api.js +1 -1
- package/dist/api.js.map +1 -1
- package/dist/crm-contracts-iWWbB6Ga.d.cts +1017 -0
- package/dist/crm-contracts-iWWbB6Ga.d.ts +1017 -0
- package/dist/embed-host.cjs +1 -1
- package/dist/embed-host.cjs.map +1 -1
- package/dist/embed-host.d.cts +36 -1
- package/dist/embed-host.d.ts +36 -1
- 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 +16 -1
- package/dist/embed-react.d.ts +16 -1
- package/dist/embed-react.js +1 -1
- package/dist/embed-react.js.map +1 -1
- package/dist/partner.cjs +2 -0
- package/dist/partner.cjs.map +1 -0
- package/dist/partner.d.cts +153 -0
- package/dist/partner.d.ts +153 -0
- package/dist/partner.js +2 -0
- package/dist/partner.js.map +1 -0
- package/package.json +11 -1
package/dist/embed-host.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var d=Object.defineProperty;var y=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var w=(e,t)=>{for(var s in t)d(e,s,{get:t[s],enumerable:!0})},M=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of x(t))!v.call(e,n)&&n!==s&&d(e,n,{get:()=>t[n],enumerable:!(i=y(t,n))||i.enumerable});return e};var H=e=>M(d({},"__esModule",{value:!0}),e);var P={};w(P,{buildCrmEmbedUrl:()=>I,createCrmEmbedHost:()=>O,crmSession:()=>b,hostContextQuery:()=>R,normalizeHostContext:()=>m});module.exports=H(P);var k=["light","dark","system"],E=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;function m(e){let t={};return e?.theme&&k.includes(e.theme)&&(t.theme=e.theme),typeof e?.locale=="string"&&E.test(e.locale.trim())&&(t.locale=e.locale.trim()),t}function R(e){let t=m(e),s=[];return t.theme&&s.push(`theme=${encodeURIComponent(t.theme)}`),t.locale&&s.push(`locale=${encodeURIComponent(t.locale)}`),s}function T(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function b(e,t){return async()=>{let s=await fetch(e,{method:"POST",...t}),i=await s.json().catch(()=>({}));if(!s.ok){let a=i?.error;throw new Error(a?`CRM session failed: ${a}`:`CRM session failed (HTTP ${s.status})`)}let n=i;if(typeof n?.accessToken!="string"||typeof n?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return n}}function I(e,t){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(t)}`}function O(e){let t=e.windowTarget??window,s=e.createChannel??(()=>new MessageChannel),i=e.devAllowAnyOrigin?"*":e.crmOrigin,n=null,a="",l=!1,c=m(e.hostContext);function g(){if(!n||c.theme===void 0&&c.locale===void 0)return;let r={type:"crm:host-context",...c};n.postMessage(r)}async function C(){try{let r=await e.getBearer();return n?.postMessage({type:"auth-tokens",accessToken:r.accessToken,refreshToken:r.refreshToken??""}),g(),!0}catch(r){return e.onError?.(r),!1}}function h(r){let o=r.data;if(o)if(o.type==="channel-ack"){if(o.nonce!==a)return;C()}else o.type==="route-change"?e.onRouteChange?.(o.path):o.type==="resize"?e.onResize?.(o.height):o.type==="session-expired"&&C().then(p=>{p&&n?.postMessage({type:"session-refreshed"})})}function f(){n?.close();let r=s();n=r.port1,a=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,n.onmessage=h,n.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:a},i,[r.port2])}function u(r){l||r.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&r.origin!==e.crmOrigin||T(r.data)&&f())}return t.addEventListener("message",u),{navigate(r){n?.postMessage({type:"navigate",path:r})},setContext(r){c={...c,...m(r)},g()},dispose(){l=!0,t.removeEventListener("message",u),n?.close(),n=null}}}0&&(module.exports={buildCrmEmbedUrl,createCrmEmbedHost,crmSession,hostContextQuery,normalizeHostContext});
|
|
2
2
|
//# sourceMappingURL=embed-host.cjs.map
|
package/dist/embed-host.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/embed-host.ts"],"sourcesContent":["/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n const result = body as Partial<CrmSessionResult>;\n // A malformed 2xx (e.g. `{}`) would otherwise cast cleanly and later build an\n // `/embed/undefined` URL — fail at the boundary with a clear message instead.\n if (typeof result?.accessToken !== 'string' || typeof result?.workspaceId !== 'string') {\n throw new Error('CRM session response is missing accessToken/workspaceId');\n }\n return result as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n\n async function deliverBearer(): Promise<boolean> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n return true;\n } catch (err) {\n opts.onError?.(err);\n return false;\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow). Only tell the\n // CRM the session refreshed once a fresh bearer was ACTUALLY delivered —\n // otherwise a failed re-mint leaves the iframe believing it's authenticated.\n void deliverBearer().then((ok) => {\n if (ok) port?.postMessage({ type: 'session-refreshed' });\n });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sBAAAE,EAAA,uBAAAC,EAAA,eAAAC,IAAA,eAAAC,EAAAL,GAuEA,SAASM,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CAmBO,SAASH,EACdI,EACAC,EACiC,CACjC,MAAO,UAAuC,CAC5C,IAAMC,EAAM,MAAM,MAAMF,EAAK,CAAE,OAAQ,OAAQ,GAAGC,CAAK,CAAC,EAClDE,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,GAAI,CAACA,EAAI,GAAI,CACX,IAAME,EAAQD,GAA6B,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EAAOU,EAAQ,MACfT,EAAQ,WAAW,QAAQ,aAAa,GAAK,KAAK,OAAO,KAAK,OAAO,CAAC,EAAE,MAAM,CAAC,CAAC,GAChFD,EAAK,UAAYM,EACjBN,EAAK,QAAQ,EACbJ,EAAK,OAAO,eAAe,YACzB,CAAE,KAAM,eAAgB,MAAAK,CAAM,EAC9BF,EACA,CAACW,EAAQ,KAAK,CAChB,CACF,CAEA,SAASC,EAAgBC,EAA2B,CAC9CV,GACAU,EAAM,SAAWhB,EAAK,OAAO,gBAC7B,CAACA,EAAK,mBAAqBgB,EAAM,SAAWhB,EAAK,WACjDV,EAAQ0B,EAAM,IAAI,GAAGH,EAAe,EAC1C,CAEA,OAAAZ,EAAO,iBAAiB,UAAWc,CAAgC,EAE5D,CACL,SAASE,EAAoB,CAC3Bb,GAAM,YAAY,CAAE,KAAM,WAAY,KAAAa,CAAK,CAAC,CAC9C,EACA,SAAgB,CACdX,EAAW,GACXL,EAAO,oBAAoB,UAAWc,CAAgC,EACtEX,GAAM,MAAM,EACZA,EAAO,IACT,CACF,CACF","names":["embed_host_exports","__export","buildCrmEmbedUrl","createCrmEmbedHost","crmSession","__toCommonJS","isReady","data","url","init","res","body","code","result","crmOrigin","workspaceId","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path"]}
|
|
1
|
+
{"version":3,"sources":["../src/embed-host.ts"],"sourcesContent":["/**\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? } 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=` and `?locale=`), 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 * 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\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\n/**\n * Keeps only values the CRM understands: a known theme and a well-formed language tag.\n * Anything else is dropped, so a bad value can never reach the iframe URL or the message.\n */\nexport function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext {\n const out: CrmHostContext = {};\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` and `locale` as URL query pairs (e.g. `[\"theme=dark\", \"locale=zh-CN\"]`). */\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 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(): void {\n if (!port || (context.theme === undefined && context.locale === 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 context = { ...context, ...normalizeHostContext(ctx) };\n sendContext();\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,sBAAAE,EAAA,uBAAAC,EAAA,eAAAC,EAAA,qBAAAC,EAAA,yBAAAC,IAAA,eAAAC,EAAAP,GAgDA,IAAMQ,EAAiC,CAAC,QAAS,OAAQ,QAAQ,EAC3DC,EAAa,4CAMZ,SAASH,EAAqBI,EAAiD,CACpF,IAAMC,EAAsB,CAAC,EAC7B,OAAID,GAAK,OAASF,EAAY,SAASE,EAAI,KAAK,IAAGC,EAAI,MAAQD,EAAI,OAC/D,OAAOA,GAAK,QAAW,UAAYD,EAAW,KAAKC,EAAI,OAAO,KAAK,CAAC,IAAGC,EAAI,OAASD,EAAI,OAAO,KAAK,GACjGC,CACT,CAGO,SAASN,EAAiBK,EAA2C,CAC1E,IAAME,EAAQN,EAAqBI,CAAG,EAChCG,EAAkB,CAAC,EACzB,OAAID,EAAM,OAAOC,EAAM,KAAK,SAAS,mBAAmBD,EAAM,KAAK,CAAC,EAAE,EAClEA,EAAM,QAAQC,EAAM,KAAK,UAAU,mBAAmBD,EAAM,MAAM,CAAC,EAAE,EAClEC,CACT,CAwDA,SAASC,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CAmBO,SAASX,EACdY,EAC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["embed_host_exports","__export","buildCrmEmbedUrl","createCrmEmbedHost","crmSession","hostContextQuery","normalizeHostContext","__toCommonJS","HOST_THEMES","BCP47_LIKE","ctx","out","clean","pairs","isReady","data","url","init","res","body","code","result","crmOrigin","workspaceId","opts","target","makeChannel","targetOrigin","port","nonce","disposed","context","sendContext","msg","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path"]}
|
package/dist/embed-host.d.cts
CHANGED
|
@@ -13,6 +13,10 @@
|
|
|
13
13
|
* 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)
|
|
14
14
|
* 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }
|
|
15
15
|
* - on 'session-expired' the host re-fetches a bearer and re-sends it.
|
|
16
|
+
* 6. host sends { type: 'crm:host-context', theme?, locale? } on the same port,
|
|
17
|
+
* right after the bearer and again whenever {@link CrmEmbedHost.setContext} is called.
|
|
18
|
+
* The first values also ride on the iframe URL (`?theme=` and `?locale=`), so the
|
|
19
|
+
* frame paints in the right theme before the handshake finishes.
|
|
16
20
|
*
|
|
17
21
|
* @packageDocumentation
|
|
18
22
|
*/
|
|
@@ -21,6 +25,29 @@ interface CrmBearer {
|
|
|
21
25
|
accessToken: string;
|
|
22
26
|
refreshToken?: string;
|
|
23
27
|
}
|
|
28
|
+
/** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */
|
|
29
|
+
type CrmHostTheme = 'light' | 'dark' | 'system';
|
|
30
|
+
/**
|
|
31
|
+
* Look and language the host passes to the embedded CRM. Both are optional; an omitted
|
|
32
|
+
* field leaves the CRM's own behaviour unchanged. The CRM applies them for the embed only
|
|
33
|
+
* and never saves them to the user's account.
|
|
34
|
+
*/
|
|
35
|
+
interface CrmHostContext {
|
|
36
|
+
theme?: CrmHostTheme;
|
|
37
|
+
/** BCP 47 language tag, e.g. "en" or "zh-CN". */
|
|
38
|
+
locale?: string;
|
|
39
|
+
}
|
|
40
|
+
/** The message the host posts on the channel port to update {@link CrmHostContext}. */
|
|
41
|
+
interface CrmHostContextMessage extends CrmHostContext {
|
|
42
|
+
type: 'crm:host-context';
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Keeps only values the CRM understands: a known theme and a well-formed language tag.
|
|
46
|
+
* Anything else is dropped, so a bad value can never reach the iframe URL or the message.
|
|
47
|
+
*/
|
|
48
|
+
declare function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext;
|
|
49
|
+
/** `theme` and `locale` as URL query pairs (e.g. `["theme=dark", "locale=zh-CN"]`). */
|
|
50
|
+
declare function hostContextQuery(ctx: CrmHostContext | undefined): string[];
|
|
24
51
|
interface CrmEmbedHostOptions {
|
|
25
52
|
/** The <iframe> element that loads the CRM embed URL. */
|
|
26
53
|
iframe: HTMLIFrameElement;
|
|
@@ -42,6 +69,8 @@ interface CrmEmbedHostOptions {
|
|
|
42
69
|
onResize?: (height: number) => void;
|
|
43
70
|
/** Called on any handshake/bearer error. */
|
|
44
71
|
onError?: (err: unknown) => void;
|
|
72
|
+
/** Initial theme/locale, sent to the CRM once the channel is up. Change it with `setContext()`. */
|
|
73
|
+
hostContext?: CrmHostContext;
|
|
45
74
|
/**
|
|
46
75
|
* DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).
|
|
47
76
|
* NEVER enable in production — it disables the origin check.
|
|
@@ -55,6 +84,12 @@ interface CrmEmbedHostOptions {
|
|
|
55
84
|
interface CrmEmbedHost {
|
|
56
85
|
/** Tell the CRM to navigate to a sub-path, e.g. "/contacts" or "/leads/123". */
|
|
57
86
|
navigate: (path: string) => void;
|
|
87
|
+
/**
|
|
88
|
+
* Update the theme and/or language of the embedded CRM. Sent over the established
|
|
89
|
+
* channel only, never broadcast with a wildcard origin. Fields you leave out keep
|
|
90
|
+
* their last value; before the channel is up the latest values go out on connect.
|
|
91
|
+
*/
|
|
92
|
+
setContext: (ctx: CrmHostContext) => void;
|
|
58
93
|
/** Tear down the channel and listeners. Call on unmount. */
|
|
59
94
|
dispose: () => void;
|
|
60
95
|
}
|
|
@@ -89,4 +124,4 @@ declare function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): strin
|
|
|
89
124
|
*/
|
|
90
125
|
declare function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost;
|
|
91
126
|
|
|
92
|
-
export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, type CrmSessionResult, buildCrmEmbedUrl, createCrmEmbedHost, crmSession };
|
|
127
|
+
export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, type CrmHostContext, type CrmHostContextMessage, type CrmHostTheme, type CrmSessionResult, buildCrmEmbedUrl, createCrmEmbedHost, crmSession, hostContextQuery, normalizeHostContext };
|
package/dist/embed-host.d.ts
CHANGED
|
@@ -13,6 +13,10 @@
|
|
|
13
13
|
* 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)
|
|
14
14
|
* 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }
|
|
15
15
|
* - on 'session-expired' the host re-fetches a bearer and re-sends it.
|
|
16
|
+
* 6. host sends { type: 'crm:host-context', theme?, locale? } on the same port,
|
|
17
|
+
* right after the bearer and again whenever {@link CrmEmbedHost.setContext} is called.
|
|
18
|
+
* The first values also ride on the iframe URL (`?theme=` and `?locale=`), so the
|
|
19
|
+
* frame paints in the right theme before the handshake finishes.
|
|
16
20
|
*
|
|
17
21
|
* @packageDocumentation
|
|
18
22
|
*/
|
|
@@ -21,6 +25,29 @@ interface CrmBearer {
|
|
|
21
25
|
accessToken: string;
|
|
22
26
|
refreshToken?: string;
|
|
23
27
|
}
|
|
28
|
+
/** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */
|
|
29
|
+
type CrmHostTheme = 'light' | 'dark' | 'system';
|
|
30
|
+
/**
|
|
31
|
+
* Look and language the host passes to the embedded CRM. Both are optional; an omitted
|
|
32
|
+
* field leaves the CRM's own behaviour unchanged. The CRM applies them for the embed only
|
|
33
|
+
* and never saves them to the user's account.
|
|
34
|
+
*/
|
|
35
|
+
interface CrmHostContext {
|
|
36
|
+
theme?: CrmHostTheme;
|
|
37
|
+
/** BCP 47 language tag, e.g. "en" or "zh-CN". */
|
|
38
|
+
locale?: string;
|
|
39
|
+
}
|
|
40
|
+
/** The message the host posts on the channel port to update {@link CrmHostContext}. */
|
|
41
|
+
interface CrmHostContextMessage extends CrmHostContext {
|
|
42
|
+
type: 'crm:host-context';
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Keeps only values the CRM understands: a known theme and a well-formed language tag.
|
|
46
|
+
* Anything else is dropped, so a bad value can never reach the iframe URL or the message.
|
|
47
|
+
*/
|
|
48
|
+
declare function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext;
|
|
49
|
+
/** `theme` and `locale` as URL query pairs (e.g. `["theme=dark", "locale=zh-CN"]`). */
|
|
50
|
+
declare function hostContextQuery(ctx: CrmHostContext | undefined): string[];
|
|
24
51
|
interface CrmEmbedHostOptions {
|
|
25
52
|
/** The <iframe> element that loads the CRM embed URL. */
|
|
26
53
|
iframe: HTMLIFrameElement;
|
|
@@ -42,6 +69,8 @@ interface CrmEmbedHostOptions {
|
|
|
42
69
|
onResize?: (height: number) => void;
|
|
43
70
|
/** Called on any handshake/bearer error. */
|
|
44
71
|
onError?: (err: unknown) => void;
|
|
72
|
+
/** Initial theme/locale, sent to the CRM once the channel is up. Change it with `setContext()`. */
|
|
73
|
+
hostContext?: CrmHostContext;
|
|
45
74
|
/**
|
|
46
75
|
* DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).
|
|
47
76
|
* NEVER enable in production — it disables the origin check.
|
|
@@ -55,6 +84,12 @@ interface CrmEmbedHostOptions {
|
|
|
55
84
|
interface CrmEmbedHost {
|
|
56
85
|
/** Tell the CRM to navigate to a sub-path, e.g. "/contacts" or "/leads/123". */
|
|
57
86
|
navigate: (path: string) => void;
|
|
87
|
+
/**
|
|
88
|
+
* Update the theme and/or language of the embedded CRM. Sent over the established
|
|
89
|
+
* channel only, never broadcast with a wildcard origin. Fields you leave out keep
|
|
90
|
+
* their last value; before the channel is up the latest values go out on connect.
|
|
91
|
+
*/
|
|
92
|
+
setContext: (ctx: CrmHostContext) => void;
|
|
58
93
|
/** Tear down the channel and listeners. Call on unmount. */
|
|
59
94
|
dispose: () => void;
|
|
60
95
|
}
|
|
@@ -89,4 +124,4 @@ declare function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): strin
|
|
|
89
124
|
*/
|
|
90
125
|
declare function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost;
|
|
91
126
|
|
|
92
|
-
export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, type CrmSessionResult, buildCrmEmbedUrl, createCrmEmbedHost, crmSession };
|
|
127
|
+
export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, type CrmHostContext, type CrmHostContextMessage, type CrmHostTheme, type CrmSessionResult, buildCrmEmbedUrl, createCrmEmbedHost, crmSession, hostContextQuery, normalizeHostContext };
|
package/dist/embed-host.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function
|
|
1
|
+
var p=["light","dark","system"],y=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;function m(e){let n={};return e?.theme&&p.includes(e.theme)&&(n.theme=e.theme),typeof e?.locale=="string"&&y.test(e.locale.trim())&&(n.locale=e.locale.trim()),n}function v(e){let n=m(e),s=[];return n.theme&&s.push(`theme=${encodeURIComponent(n.theme)}`),n.locale&&s.push(`locale=${encodeURIComponent(n.locale)}`),s}function x(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function w(e,n){return async()=>{let s=await fetch(e,{method:"POST",...n}),c=await s.json().catch(()=>({}));if(!s.ok){let i=c?.error;throw new Error(i?`CRM session failed: ${i}`:`CRM session failed (HTTP ${s.status})`)}let r=c;if(typeof r?.accessToken!="string"||typeof r?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return r}}function M(e,n){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(n)}`}function H(e){let n=e.windowTarget??window,s=e.createChannel??(()=>new MessageChannel),c=e.devAllowAnyOrigin?"*":e.crmOrigin,r=null,i="",d=!1,a=m(e.hostContext);function l(){if(!r||a.theme===void 0&&a.locale===void 0)return;let t={type:"crm:host-context",...a};r.postMessage(t)}async function g(){try{let t=await e.getBearer();return r?.postMessage({type:"auth-tokens",accessToken:t.accessToken,refreshToken:t.refreshToken??""}),l(),!0}catch(t){return e.onError?.(t),!1}}function u(t){let o=t.data;if(o)if(o.type==="channel-ack"){if(o.nonce!==i)return;g()}else o.type==="route-change"?e.onRouteChange?.(o.path):o.type==="resize"?e.onResize?.(o.height):o.type==="session-expired"&&g().then(f=>{f&&r?.postMessage({type:"session-refreshed"})})}function h(){r?.close();let t=s();r=t.port1,i=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,r.onmessage=u,r.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:i},c,[t.port2])}function C(t){d||t.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&t.origin!==e.crmOrigin||x(t.data)&&h())}return n.addEventListener("message",C),{navigate(t){r?.postMessage({type:"navigate",path:t})},setContext(t){a={...a,...m(t)},l()},dispose(){d=!0,n.removeEventListener("message",C),r?.close(),r=null}}}export{M as buildCrmEmbedUrl,H as createCrmEmbedHost,w as crmSession,v as hostContextQuery,m as normalizeHostContext};
|
|
2
2
|
//# sourceMappingURL=embed-host.js.map
|
package/dist/embed-host.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/embed-host.ts"],"sourcesContent":["/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n const result = body as Partial<CrmSessionResult>;\n // A malformed 2xx (e.g. `{}`) would otherwise cast cleanly and later build an\n // `/embed/undefined` URL — fail at the boundary with a clear message instead.\n if (typeof result?.accessToken !== 'string' || typeof result?.workspaceId !== 'string') {\n throw new Error('CRM session response is missing accessToken/workspaceId');\n }\n return result as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n\n async function deliverBearer(): Promise<boolean> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n return true;\n } catch (err) {\n opts.onError?.(err);\n return false;\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow). Only tell the\n // CRM the session refreshed once a fresh bearer was ACTUALLY delivered —\n // otherwise a failed re-mint leaves the iframe believing it's authenticated.\n void deliverBearer().then((ok) => {\n if (ok) port?.postMessage({ type: 'session-refreshed' });\n });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"AAuEA,SAASA,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CAmBO,SAASC,EACdC,EACAC,EACiC,CACjC,MAAO,UAAuC,CAC5C,IAAMC,EAAM,MAAM,MAAMF,EAAK,CAAE,OAAQ,OAAQ,GAAGC,CAAK,CAAC,EAClDE,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,GAAI,CAACA,EAAI,GAAI,CACX,IAAME,EAAQD,GAA6B,MAC3C,MAAM,IAAI,MACRC,EAAO,uBAAuBA,CAAI,GAAK,4BAA4BF,EAAI,MAAM,GAC/E,CACF,CACA,IAAMG,EAASF,EAGf,GAAI,OAAOE,GAAQ,aAAgB,UAAY,OAAOA,GAAQ,aAAgB,SAC5E,MAAM,IAAI,MAAM,yDAAyD,EAE3E,OAAOA,CACT,CACF,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,GAAkC,CAC/C,GAAI,CACF,IAAMC,EAAS,MAAMR,EAAK,UAAU,EACpC,OAAAI,GAAM,YAAY,CAChB,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AM,EACZA,EAAO,IACT,CACF,CACF","names":["isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path"]}
|
|
1
|
+
{"version":3,"sources":["../src/embed-host.ts"],"sourcesContent":["/**\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? } 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=` and `?locale=`), 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 * 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\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\n/**\n * Keeps only values the CRM understands: a known theme and a well-formed language tag.\n * Anything else is dropped, so a bad value can never reach the iframe URL or the message.\n */\nexport function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext {\n const out: CrmHostContext = {};\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` and `locale` as URL query pairs (e.g. `[\"theme=dark\", \"locale=zh-CN\"]`). */\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 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(): void {\n if (!port || (context.theme === undefined && context.locale === 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 context = { ...context, ...normalizeHostContext(ctx) };\n sendContext();\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":"AAgDA,IAAMA,EAAiC,CAAC,QAAS,OAAQ,QAAQ,EAC3DC,EAAa,4CAMZ,SAASC,EAAqBC,EAAiD,CACpF,IAAMC,EAAsB,CAAC,EAC7B,OAAID,GAAK,OAASH,EAAY,SAASG,EAAI,KAAK,IAAGC,EAAI,MAAQD,EAAI,OAC/D,OAAOA,GAAK,QAAW,UAAYF,EAAW,KAAKE,EAAI,OAAO,K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,gBAC7B,CAACA,EAAK,mBAAqBmB,EAAM,SAAWnB,EAAK,WACjDb,EAAQgC,EAAM,IAAI,GAAGH,EAAe,EAC1C,CAEA,OAAAf,EAAO,iBAAiB,UAAWiB,CAAgC,EAE5D,CACL,SAASE,EAAoB,CAC3BhB,GAAM,YAAY,CAAE,KAAM,WAAY,KAAAgB,CAAK,CAAC,CAC9C,EACA,WAAWtC,EAA2B,CACpCyB,EAAU,CAAE,GAAGA,EAAS,GAAG1B,EAAqBC,CAAG,CAAE,EACrD0B,EAAY,CACd,EACA,SAAgB,CACdF,EAAW,GACXL,EAAO,oBAAoB,UAAWiB,CAAgC,EACtEd,GAAM,MAAM,EACZA,EAAO,IACT,CACF,CACF","names":["HOST_THEMES","BCP47_LIKE","normalizeHostContext","ctx","out","hostContextQuery","clean","pairs","isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","context","sendContext","msg","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path"]}
|
package/dist/embed-react.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var I=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var ee=Object.prototype.hasOwnProperty;var te=(e,t)=>{for(var s in t)I(e,s,{get:t[s],enumerable:!0})},re=(e,t,s,l)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of X(t))!ee.call(e,r)&&r!==s&&I(e,r,{get:()=>t[r],enumerable:!(l=V(t,r))||l.enumerable});return e};var ne=e=>re(I({},"__esModule",{value:!0}),e);var de={};te(de,{CrmEmbed:()=>Q,crmSession:()=>_,default:()=>me});module.exports=ne(de);var n=require("react");var oe=["light","dark","system"],se=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;function L(e){let t={};return e?.theme&&oe.includes(e.theme)&&(t.theme=e.theme),typeof e?.locale=="string"&&se.test(e.locale.trim())&&(t.locale=e.locale.trim()),t}function F(e){let t=L(e),s=[];return t.theme&&s.push(`theme=${encodeURIComponent(t.theme)}`),t.locale&&s.push(`locale=${encodeURIComponent(t.locale)}`),s}function ie(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function _(e,t){return async()=>{let s=await fetch(e,{method:"POST",...t}),l=await s.json().catch(()=>({}));if(!s.ok){let g=l?.error;throw new Error(g?`CRM session failed: ${g}`:`CRM session failed (HTTP ${s.status})`)}let r=l;if(typeof r?.accessToken!="string"||typeof r?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return r}}function j(e,t){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(t)}`}function q(e){let t=e.windowTarget??window,s=e.createChannel??(()=>new MessageChannel),l=e.devAllowAnyOrigin?"*":e.crmOrigin,r=null,g="",h=!1,C=L(e.hostContext);function f(){if(!r||C.theme===void 0&&C.locale===void 0)return;let o={type:"crm:host-context",...C};r.postMessage(o)}async function p(){try{let o=await e.getBearer();return r?.postMessage({type:"auth-tokens",accessToken:o.accessToken,refreshToken:o.refreshToken??""}),f(),!0}catch(o){return e.onError?.(o),!1}}function y(o){let i=o.data;if(i)if(i.type==="channel-ack"){if(i.nonce!==g)return;p()}else i.type==="route-change"?e.onRouteChange?.(i.path):i.type==="resize"?e.onResize?.(i.height):i.type==="session-expired"&&p().then(v=>{v&&r?.postMessage({type:"session-refreshed"})})}function E(){r?.close();let o=s();r=o.port1,g=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,r.onmessage=y,r.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:g},l,[o.port2])}function R(o){h||o.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&o.origin!==e.crmOrigin||ie(o.data)&&E())}return t.addEventListener("message",R),{navigate(o){r?.postMessage({type:"navigate",path:o})},setContext(o){C={...C,...L(o)},f()},dispose(){h=!0,t.removeEventListener("message",R),r?.close(),r=null}}}var c=require("react/jsx-runtime");var ae={width:"100%",height:"100%",border:0};function O(e){return e instanceof Error?e:new Error(String(e))}function ce(){return(0,c.jsx)("div",{children:"Loading CRM\u2026"})}function le(e,t){return(0,c.jsxs)("div",{children:[(0,c.jsxs)("p",{children:["Couldn\u2019t load the CRM: ",e.message]}),(0,c.jsx)("button",{type:"button",onClick:t,children:"Try again"})]})}var Q=(0,n.forwardRef)(function(t,s){let{getSession:l,crmEmbedOrigin:r,className:g,style:h,title:C="CRM",onReady:f,onError:p,onRouteChange:y,hostProvidesNav:E,initialPath:R,theme:o,locale:i,renderLoading:v,renderError:A}=t,N=(0,n.useRef)(null),[b,B]=(0,n.useState)(null),[M,U]=(0,n.useState)(null),[T,x]=(0,n.useState)(null),[Z,K]=(0,n.useState)(0),w=(0,n.useRef)(null),H=(0,n.useRef)(null);(0,n.useImperativeHandle)(s,()=>({navigate:m=>{H.current?.navigate(m)}}),[]);let S=(0,n.useRef)(l),$=(0,n.useRef)(f),k=(0,n.useRef)(p),z=(0,n.useRef)(y);(0,n.useEffect)(()=>{S.current=l,$.current=f,k.current=p,z.current=y});let Y=(0,n.useRef)(R),P=(0,n.useRef)({theme:o,locale:i});P.current={theme:o,locale:i};let W=(0,n.useCallback)(()=>{w.current=null,x(null),B(null),U(null),K(m=>m+1)},[]);return(0,n.useEffect)(()=>{let m=!1;return(async()=>{try{let d=await S.current();if(m)return;w.current={accessToken:d.accessToken},U(d.workspaceId);let a=j(r,d.workspaceId),u=Y.current??"",D=[...E?["hostnav=1"]:[],...F(P.current)],G=u.includes("?")?"&":"?",J=a+u+(D.length>0?G+D.join("&"):"");B(J)}catch(d){if(m)return;let a=O(d);x(a),k.current?.(a)}})(),()=>{m=!0}},[r,E,Z]),(0,n.useEffect)(()=>{let m=N.current;if(!m||!b||!M)return;let d=null;try{d=q({iframe:m,crmOrigin:r,getBearer:async()=>{let a=w.current;return a?(w.current=null,a):{accessToken:(await S.current()).accessToken}},hostContext:P.current,onRouteChange:a=>{z.current?.(a)},onError:a=>{let u=O(a);x(u),k.current?.(u)}})}catch(a){let u=O(a);x(u),k.current?.(u);return}return H.current=d,$.current?.({workspaceId:M}),()=>{d?.dispose(),H.current=null}},[b,M,r]),(0,n.useEffect)(()=>{H.current?.setContext({theme:o,locale:i})},[o,i]),T?(0,c.jsx)(c.Fragment,{children:A?A(T,W):le(T,W)}):b?(0,c.jsx)("iframe",{ref:N,src:b,title:C,className:g,style:{...ae,...h}}):(0,c.jsx)(c.Fragment,{children:v?v():ce()})}),me=Q;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 type CrmBearer,\n type CrmEmbedHost,\n type CrmSessionResult,\n} from './embed-host';\n\n// Re-export the session-fetch helper so React users can get it from one entry:\n// import { CrmEmbed, crmSession } from '@first-to-fly/crm-sdk/embed-react';\nexport { crmSession, type CrmSessionResult };\n\n/**\n * What a partner's `getSession()` must resolve to. Alias of {@link CrmSessionResult}\n * (the browser-side session shape) — kept as a named export for back-compat; both\n * are `{ accessToken, workspaceId, expiresIn? }`.\n */\nexport type CrmEmbedSession = CrmSessionResult;\n\n/**\n * Imperative handle exposed via `ref`. Lets a host drive the embedded CRM's\n * navigation without re-rendering the iframe.\n */\nexport interface CrmEmbedHandle {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n}\n\nexport interface CrmEmbedProps {\n /**\n * Resolves a CRM bearer + the workspace to embed. Called once on mount (and\n * again on retry / session expiry). Typically calls your own backend endpoint\n * that runs `createEmbedSessionWithKey`.\n */\n getSession: () => Promise<CrmEmbedSession>;\n /**\n * The CRM embed base origin, e.g. \"https://crm.example.com\". The iframe URL\n * is `buildCrmEmbedUrl(crmEmbedOrigin, workspaceId)` and this origin is also\n * used as the postMessage targetOrigin.\n */\n crmEmbedOrigin: string;\n /** Class applied to the iframe. */\n className?: string;\n /** Inline style merged onto the iframe (overrides the fill-container default). */\n style?: CSSProperties;\n /** Iframe title (accessibility). Defaults to \"CRM\". */\n title?: string;\n /** Called after the iframe URL is built and mounted. */\n onReady?: (info: { workspaceId: string }) => void;\n /** Called on any session / handshake error. */\n onError?: (error: Error) => void;\n /**\n * Called when the CRM navigates internally (e.g. \"/contacts\"). Use this to\n * keep a host-supplied nav in sync with the embedded CRM's current section.\n */\n onRouteChange?: (path: string) => void;\n /**\n * When true, the CRM hides its own in-iframe nav (the host supplies it).\n * Signalled to the CRM by appending `?hostnav=1` to the iframe URL. Drive\n * navigation yourself via the ref's `navigate()`.\n */\n hostProvidesNav?: boolean;\n /**\n * Initial CRM sub-path to deep-link on FIRST load (e.g. \"/contacts\").\n * Only applied to the initial iframe URL — later changes do NOT reload the\n * iframe; use the ref's `navigate()` for in-session navigation.\n */\n initialPath?: string;\n /** Custom loading UI. Defaults to a minimal message. */\n renderLoading?: () => ReactNode;\n /** Custom error UI. Defaults to the message + a Retry button. */\n renderError?: (error: Error, retry: () => void) => ReactNode;\n}\n\nconst DEFAULT_IFRAME_STYLE: CSSProperties = {\n width: '100%',\n height: '100%',\n border: 0,\n};\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n\nfunction DefaultLoading(): ReactNode {\n return <div>Loading CRM…</div>;\n}\n\nfunction DefaultError(error: Error, retry: () => void): ReactNode {\n return (\n <div>\n <p>Couldn’t load the CRM: {error.message}</p>\n <button type=\"button\" onClick={retry}>Try again</button>\n </div>\n );\n}\n\n/**\n * Embed the First To Fly CRM in a React app. See {@link CrmEmbedProps}.\n *\n * Accepts a `ref` of type {@link CrmEmbedHandle} exposing `navigate(path)` so a\n * host can drive the embedded CRM's section navigation.\n */\nexport const CrmEmbed = forwardRef<CrmEmbedHandle, CrmEmbedProps>(\n function CrmEmbed(props, ref): ReactNode {\n const {\n getSession,\n crmEmbedOrigin,\n className,\n style,\n title = 'CRM',\n onReady,\n onError,\n onRouteChange,\n hostProvidesNav,\n initialPath,\n renderLoading,\n renderError,\n } = props;\n\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const [embedUrl, setEmbedUrl] = useState<string | null>(null);\n const [workspaceId, setWorkspaceId] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [attempt, setAttempt] = useState(0);\n\n // Bearer minted during session resolution — reused for the host's first\n // getBearer() so a single getSession() call covers both phases (no double-mint).\n const primedBearerRef = useRef<CrmBearer | null>(null);\n\n // The created host, so the imperative `navigate()` can reach it.\n const hostRef = useRef<CrmEmbedHost | null>(null);\n\n // Expose the imperative navigate(). No-ops safely before the host is wired.\n useImperativeHandle(ref, () => ({\n navigate: (path: string) => { hostRef.current?.navigate(path); },\n }), []);\n\n // Keep the latest callbacks in refs so the effects DON'T depend on their\n // identity. Partners routinely pass inline `getSession`/`onReady`/`onError`/\n // `onRouteChange`; depending on them directly would re-run Phase 1 (re-fetch\n // the session) and tear down + recreate the host on every parent re-render.\n const getSessionRef = useRef(getSession);\n const onReadyRef = useRef(onReady);\n const onErrorRef = useRef(onError);\n const onRouteChangeRef = useRef(onRouteChange);\n useEffect(() => {\n getSessionRef.current = getSession;\n onReadyRef.current = onReady;\n onErrorRef.current = onError;\n onRouteChangeRef.current = onRouteChange;\n });\n\n // Capture initialPath ONCE — it only seeds the first load. Later changes go\n // through the imperative navigate() and must NOT rebuild/reload the iframe.\n const initialPathRef = useRef(initialPath);\n\n const retry = useCallback(() => {\n primedBearerRef.current = null;\n setError(null);\n setEmbedUrl(null);\n setWorkspaceId(null);\n setAttempt((n) => n + 1);\n }, []);\n\n // Phase 1: resolve the session, prime the bearer, and build the iframe URL.\n // Re-runs only on retry (`attempt`) or a changed origin/hostnav — never on\n // unrelated parent re-renders (callbacks + initialPath are read from refs).\n useEffect(() => {\n let cancelled = false;\n\n void (async () => {\n try {\n const session = await getSessionRef.current();\n if (cancelled) return;\n primedBearerRef.current = { accessToken: session.accessToken };\n setWorkspaceId(session.workspaceId);\n const base = buildCrmEmbedUrl(crmEmbedOrigin, session.workspaceId);\n const url = base + (initialPathRef.current ?? '') + (hostProvidesNav ? '?hostnav=1' : '');\n setEmbedUrl(url);\n } catch (err) {\n if (cancelled) return;\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n }\n })();\n\n return () => { cancelled = true; };\n }, [crmEmbedOrigin, hostProvidesNav, attempt]);\n\n // Phase 2: once the iframe URL is known, wire the MessageChannel host.\n useEffect(() => {\n const iframe = iframeRef.current;\n if (!iframe || !embedUrl || !workspaceId) return undefined;\n\n let host: CrmEmbedHost | null = null;\n try {\n host = createCrmEmbedHost({\n iframe,\n crmOrigin: crmEmbedOrigin,\n getBearer: async () => {\n const primed = primedBearerRef.current;\n if (primed) {\n primedBearerRef.current = null;\n return primed;\n }\n const session = await getSessionRef.current();\n return { accessToken: session.accessToken };\n },\n onRouteChange: (path) => { onRouteChangeRef.current?.(path); },\n onError: (err) => {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n },\n });\n } catch (err) {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n return undefined;\n }\n\n hostRef.current = host;\n\n // Only signal ready once the host is actually wired.\n onReadyRef.current?.({ workspaceId });\n\n return () => {\n host?.dispose();\n hostRef.current = null;\n };\n }, [embedUrl, workspaceId, crmEmbedOrigin]);\n\n if (error) {\n return <>{renderError ? renderError(error, retry) : DefaultError(error, retry)}</>;\n }\n\n if (!embedUrl) {\n return <>{renderLoading ? renderLoading() : DefaultLoading()}</>;\n }\n\n return (\n <iframe\n ref={iframeRef}\n src={embedUrl}\n title={title}\n className={className}\n style={{ ...DEFAULT_IFRAME_STYLE, ...style }}\n />\n );\n },\n);\n\nexport default CrmEmbed;\n","/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n const result = body as Partial<CrmSessionResult>;\n // A malformed 2xx (e.g. `{}`) would otherwise cast cleanly and later build an\n // `/embed/undefined` URL — fail at the boundary with a clear message instead.\n if (typeof result?.accessToken !== 'string' || typeof result?.workspaceId !== 'string') {\n throw new Error('CRM session response is missing accessToken/workspaceId');\n }\n return result as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n\n async function deliverBearer(): Promise<boolean> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n return true;\n } catch (err) {\n opts.onError?.(err);\n return false;\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow). Only tell the\n // CRM the session refreshed once a fresh bearer was ACTUALLY delivered —\n // otherwise a failed re-mint leaves the iframe believing it's authenticated.\n void deliverBearer().then((ok) => {\n if (ok) port?.postMessage({ type: 'session-refreshed' });\n });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"yaAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,cAAAE,EAAA,eAAAC,EAAA,YAAAC,KAAA,eAAAC,EAAAL,IAwBA,IAAAM,EAEO,iBC6CP,SAASC,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,S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G,CAACR,EAAUE,EAAad,CAAc,CAAC,EAEtCN,KACK,mBAAG,SAAAgB,EAAcA,EAAYhB,EAAOC,CAAK,EAAIF,EAAaC,EAAOC,CAAK,EAAE,EAG5EiB,KAKH,OAAC,UACC,IAAKD,EACL,IAAKC,EACL,MAAOT,EACP,UAAWF,EACX,MAAO,CAAE,GAAGZ,EAAsB,GAAGa,CAAM,EAC7C,KAVO,mBAAG,SAAAO,EAAgBA,EAAc,EAAIjB,EAAe,EAAE,CAYjE,CACF,EAEO6C,GAAQzC","names":["embed_react_exports","__export","CrmEmbed","crmSession","embed_react_default","__toCommonJS","import_react","isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path","import_jsx_runtime","DEFAULT_IFRAME_STYLE","toError","err","DefaultLoading","DefaultError","error","retry","CrmEmbed","props","ref","getSession","crmEmbedOrigin","className","style","title","onReady","onError","onRouteChange","hostProvidesNav","initialPath","renderLoading","renderError","iframeRef","embedUrl","setEmbedUrl","workspaceId","setWorkspaceId","setError","attempt","setAttempt","primedBearerRef","hostRef","path","getSessionRef","onReadyRef","onErrorRef","onRouteChangeRef","initialPathRef","n","cancelled","session","url","buildCrmEmbedUrl","e","iframe","host","createCrmEmbedHost","primed","embed_react_default"]}
|
|
1
|
+
{"version":3,"sources":["../src/embed-react.tsx","../src/embed-host.ts"],"sourcesContent":["/**\n * Drop-in React component that embeds the First To Fly CRM as a cross-origin\n * iframe, authenticated WITHOUT cookies.\n *\n * This wraps the low-level {@link ./embed-host | embed-host} helpers into a\n * single component. You supply a `getSession()` that returns a CRM bearer plus\n * the workspace to embed (typically by calling your own backend endpoint that\n * runs `createEmbedSessionWithKey`), and the component handles:\n * - resolving the session and building the iframe URL,\n * - rendering the iframe and running the MessageChannel handshake,\n * - reusing the initial bearer (no double-mint) and re-minting on expiry,\n * - loading / error / retry states.\n *\n * A host (e.g. an app shell) can drive the embedded CRM's section navigation\n * imperatively via a ref (`navigate(path)`), observe the CRM's own navigation\n * via `onRouteChange`, deep-link an `initialPath` on first load, and hide the\n * CRM's in-iframe nav via `hostProvidesNav` (when the host supplies its own).\n *\n * `react` is an OPTIONAL peer dependency — only pull in this entry if you use\n * React. Non-React consumers can keep using `./embed-host` directly.\n *\n * @packageDocumentation\n */\n\nimport {\n forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState,\n} from 'react';\nimport type { CSSProperties, ReactNode } from 'react';\n\nimport {\n buildCrmEmbedUrl,\n createCrmEmbedHost,\n crmSession,\n hostContextQuery,\n type CrmBearer,\n type CrmEmbedHost,\n type 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 { crmSession, type CrmSessionResult, type CrmHostTheme };\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 /** 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 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 });\n hostContextRef.current = { theme, locale };\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 useEffect(() => {\n hostRef.current?.setContext({ theme, locale });\n }, [theme, locale]);\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? } 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=` and `?locale=`), 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 * 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\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\n/**\n * Keeps only values the CRM understands: a known theme and a well-formed language tag.\n * Anything else is dropped, so a bad value can never reach the iframe URL or the message.\n */\nexport function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext {\n const out: CrmHostContext = {};\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` and `locale` as URL query pairs (e.g. `[\"theme=dark\", \"locale=zh-CN\"]`). */\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 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(): void {\n if (!port || (context.theme === undefined && context.locale === 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 context = { ...context, ...normalizeHostContext(ctx) };\n sendContext();\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":"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,CACH,OAAShD,EAAK,CACZ,IAAMgD,EAAIjD,EAAQC,CAAG,EACrB2B,EAASqB,CAAC,EACVb,EAAW,UAAUa,CAAC,EACtB,MACF,CAEA,OAAAjB,EAAQ,QAAUmB,EAGlBhB,EAAW,UAAU,CAAE,YAAAT,CAAY,CAAC,EAE7B,IAAM,CACXyB,GAAM,QAAQ,EACdnB,EAAQ,QAAU,IACpB,CACF,EAAG,CAACR,EAAUE,EAAahB,CAAc,CAAC,KAG1C,aAAU,IAAM,CACdsB,EAAQ,SAAS,WAAW,CAAE,MAAAb,EAAO,OAAAC,CAAO,CAAC,CAC/C,EAAG,CAACD,EAAOC,CAAM,CAAC,EAEdhB,KACK,mBAAG,SAAAkB,EAAcA,EAAYlB,EAAOC,CAAK,EAAIF,GAAaC,EAAOC,CAAK,EAAE,EAG5EmB,KAKH,OAAC,UACC,IAAKD,EACL,IAAKC,EACL,MAAOX,EACP,UAAWF,EACX,MAAO,CAAE,GAAGZ,GAAsB,GAAGa,CAAM,EAC7C,KAVO,mBAAG,SAAAS,EAAgBA,EAAc,EAAInB,GAAe,EAAE,CAYjE,CACF,EAEOoD,GAAQhD","names":["embed_react_exports","__export","CrmEmbed","crmSession","embed_react_default","__toCommonJS","import_react","HOST_THEMES","BCP47_LIKE","normalizeHostContext","ctx","out","hostContextQuery","clean","pairs","isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","context","sendContext","msg","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path","import_jsx_runtime","DEFAULT_IFRAME_STYLE","toError","err","DefaultLoading","DefaultError","error","retry","CrmEmbed","props","ref","getSession","crmEmbedOrigin","className","style","title","onReady","onError","onRouteChange","hostProvidesNav","initialPath","theme","locale","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","embed_react_default"]}
|
package/dist/embed-react.d.cts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
2
|
import { CSSProperties, ReactNode } from 'react';
|
|
3
3
|
|
|
4
|
+
/** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */
|
|
5
|
+
type CrmHostTheme = 'light' | 'dark' | 'system';
|
|
4
6
|
/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */
|
|
5
7
|
interface CrmSessionResult {
|
|
6
8
|
accessToken: string;
|
|
@@ -75,6 +77,19 @@ interface CrmEmbedProps {
|
|
|
75
77
|
* iframe; use the ref's `navigate()` for in-session navigation.
|
|
76
78
|
*/
|
|
77
79
|
initialPath?: string;
|
|
80
|
+
/**
|
|
81
|
+
* Theme for the embedded CRM: `light`, `dark`, or `system` (follow the visitor's OS).
|
|
82
|
+
* The first value rides on the iframe URL as `?theme=`; a later change is posted to
|
|
83
|
+
* the frame over the channel (`crm:host-context`) without reloading it. The CRM applies
|
|
84
|
+
* it for the embed only and never saves it to the user's account. Omitted: the CRM keeps
|
|
85
|
+
* its default (light) look.
|
|
86
|
+
*/
|
|
87
|
+
theme?: CrmHostTheme;
|
|
88
|
+
/**
|
|
89
|
+
* Language for the embedded CRM as a BCP 47 tag, e.g. "en" or "zh-CN". Sent like `theme`
|
|
90
|
+
* (`?locale=`, then `crm:host-context`). Omitted: the CRM keeps its own language.
|
|
91
|
+
*/
|
|
92
|
+
locale?: string;
|
|
78
93
|
/** Custom loading UI. Defaults to a minimal message. */
|
|
79
94
|
renderLoading?: () => ReactNode;
|
|
80
95
|
/** Custom error UI. Defaults to the message + a Retry button. */
|
|
@@ -88,4 +103,4 @@ interface CrmEmbedProps {
|
|
|
88
103
|
*/
|
|
89
104
|
declare const CrmEmbed: react.ForwardRefExoticComponent<CrmEmbedProps & react.RefAttributes<CrmEmbedHandle>>;
|
|
90
105
|
|
|
91
|
-
export { CrmEmbed, type CrmEmbedHandle, type CrmEmbedProps, type CrmEmbedSession, type CrmSessionResult, crmSession, CrmEmbed as default };
|
|
106
|
+
export { CrmEmbed, type CrmEmbedHandle, type CrmEmbedProps, type CrmEmbedSession, type CrmHostTheme, type CrmSessionResult, crmSession, CrmEmbed as default };
|
package/dist/embed-react.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
2
|
import { CSSProperties, ReactNode } from 'react';
|
|
3
3
|
|
|
4
|
+
/** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */
|
|
5
|
+
type CrmHostTheme = 'light' | 'dark' | 'system';
|
|
4
6
|
/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */
|
|
5
7
|
interface CrmSessionResult {
|
|
6
8
|
accessToken: string;
|
|
@@ -75,6 +77,19 @@ interface CrmEmbedProps {
|
|
|
75
77
|
* iframe; use the ref's `navigate()` for in-session navigation.
|
|
76
78
|
*/
|
|
77
79
|
initialPath?: string;
|
|
80
|
+
/**
|
|
81
|
+
* Theme for the embedded CRM: `light`, `dark`, or `system` (follow the visitor's OS).
|
|
82
|
+
* The first value rides on the iframe URL as `?theme=`; a later change is posted to
|
|
83
|
+
* the frame over the channel (`crm:host-context`) without reloading it. The CRM applies
|
|
84
|
+
* it for the embed only and never saves it to the user's account. Omitted: the CRM keeps
|
|
85
|
+
* its default (light) look.
|
|
86
|
+
*/
|
|
87
|
+
theme?: CrmHostTheme;
|
|
88
|
+
/**
|
|
89
|
+
* Language for the embedded CRM as a BCP 47 tag, e.g. "en" or "zh-CN". Sent like `theme`
|
|
90
|
+
* (`?locale=`, then `crm:host-context`). Omitted: the CRM keeps its own language.
|
|
91
|
+
*/
|
|
92
|
+
locale?: string;
|
|
78
93
|
/** Custom loading UI. Defaults to a minimal message. */
|
|
79
94
|
renderLoading?: () => ReactNode;
|
|
80
95
|
/** Custom error UI. Defaults to the message + a Retry button. */
|
|
@@ -88,4 +103,4 @@ interface CrmEmbedProps {
|
|
|
88
103
|
*/
|
|
89
104
|
declare const CrmEmbed: react.ForwardRefExoticComponent<CrmEmbedProps & react.RefAttributes<CrmEmbedHandle>>;
|
|
90
105
|
|
|
91
|
-
export { CrmEmbed, type CrmEmbedHandle, type CrmEmbedProps, type CrmEmbedSession, type CrmSessionResult, crmSession, CrmEmbed as default };
|
|
106
|
+
export { CrmEmbed, type CrmEmbedHandle, type CrmEmbedProps, type CrmEmbedSession, 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 ne,useCallback as oe,useEffect as M,useImperativeHandle as se,useRef as m,useState as T}from"react";var X=["light","dark","system"],ee=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;function O(e){let n={};return e?.theme&&X.includes(e.theme)&&(n.theme=e.theme),typeof e?.locale=="string"&&ee.test(e.locale.trim())&&(n.locale=e.locale.trim()),n}function _(e){let n=O(e),i=[];return n.theme&&i.push(`theme=${encodeURIComponent(n.theme)}`),n.locale&&i.push(`locale=${encodeURIComponent(n.locale)}`),i}function te(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function re(e,n){return async()=>{let i=await fetch(e,{method:"POST",...n}),u=await i.json().catch(()=>({}));if(!i.ok){let d=u?.error;throw new Error(d?`CRM session failed: ${d}`:`CRM session failed (HTTP ${i.status})`)}let r=u;if(typeof r?.accessToken!="string"||typeof r?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return r}}function j(e,n){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(n)}`}function q(e){let n=e.windowTarget??window,i=e.createChannel??(()=>new MessageChannel),u=e.devAllowAnyOrigin?"*":e.crmOrigin,r=null,d="",h=!1,g=O(e.hostContext);function C(){if(!r||g.theme===void 0&&g.locale===void 0)return;let t={type:"crm:host-context",...g};r.postMessage(t)}async function f(){try{let t=await e.getBearer();return r?.postMessage({type:"auth-tokens",accessToken:t.accessToken,refreshToken:t.refreshToken??""}),C(),!0}catch(t){return e.onError?.(t),!1}}function y(t){let o=t.data;if(o)if(o.type==="channel-ack"){if(o.nonce!==d)return;f()}else o.type==="route-change"?e.onRouteChange?.(o.path):o.type==="resize"?e.onResize?.(o.height):o.type==="session-expired"&&f().then(v=>{v&&r?.postMessage({type:"session-refreshed"})})}function E(){r?.close();let t=i();r=t.port1,d=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,r.onmessage=y,r.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:d},u,[t.port2])}function R(t){h||t.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&t.origin!==e.crmOrigin||te(t.data)&&E())}return n.addEventListener("message",R),{navigate(t){r?.postMessage({type:"navigate",path:t})},setContext(t){g={...g,...O(t)},C()},dispose(){h=!0,n.removeEventListener("message",R),r?.close(),r=null}}}import{Fragment as Z,jsx as p,jsxs as Q}from"react/jsx-runtime";var ie={width:"100%",height:"100%",border:0};function A(e){return e instanceof Error?e:new Error(String(e))}function ae(){return p("div",{children:"Loading CRM\u2026"})}function ce(e,n){return Q("div",{children:[Q("p",{children:["Couldn\u2019t load the CRM: ",e.message]}),p("button",{type:"button",onClick:n,children:"Try again"})]})}var le=ne(function(n,i){let{getSession:u,crmEmbedOrigin:r,className:d,style:h,title:g="CRM",onReady:C,onError:f,onRouteChange:y,hostProvidesNav:E,initialPath:R,theme:t,locale:o,renderLoading:v,renderError:N}=n,B=m(null),[b,U]=T(null),[S,$]=T(null),[P,x]=T(null),[K,Y]=T(0),w=m(null),H=m(null);se(i,()=>({navigate:a=>{H.current?.navigate(a)}}),[]);let I=m(u),z=m(C),k=m(f),W=m(y);M(()=>{I.current=u,z.current=C,k.current=f,W.current=y});let G=m(R),L=m({theme:t,locale:o});L.current={theme:t,locale:o};let D=oe(()=>{w.current=null,x(null),U(null),$(null),Y(a=>a+1)},[]);return M(()=>{let a=!1;return(async()=>{try{let c=await I.current();if(a)return;w.current={accessToken:c.accessToken},$(c.workspaceId);let s=j(r,c.workspaceId),l=G.current??"",F=[...E?["hostnav=1"]:[],..._(L.current)],J=l.includes("?")?"&":"?",V=s+l+(F.length>0?J+F.join("&"):"");U(V)}catch(c){if(a)return;let s=A(c);x(s),k.current?.(s)}})(),()=>{a=!0}},[r,E,K]),M(()=>{let a=B.current;if(!a||!b||!S)return;let c=null;try{c=q({iframe:a,crmOrigin:r,getBearer:async()=>{let s=w.current;return s?(w.current=null,s):{accessToken:(await I.current()).accessToken}},hostContext:L.current,onRouteChange:s=>{W.current?.(s)},onError:s=>{let l=A(s);x(l),k.current?.(l)}})}catch(s){let l=A(s);x(l),k.current?.(l);return}return H.current=c,z.current?.({workspaceId:S}),()=>{c?.dispose(),H.current=null}},[b,S,r]),M(()=>{H.current?.setContext({theme:t,locale:o})},[t,o]),P?p(Z,{children:N?N(P,D):ce(P,D)}):b?p("iframe",{ref:B,src:b,title:g,className:d,style:{...ie,...h}}):p(Z,{children:v?v():ae()})}),ge=le;export{le as CrmEmbed,re as crmSession,ge as default};
|
|
2
2
|
//# sourceMappingURL=embed-react.js.map
|