@first-to-fly/crm-sdk 1.4.1 → 1.4.3
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 +2 -2
- package/dist/embed-host.cjs +1 -1
- package/dist/embed-host.cjs.map +1 -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 +6 -9
- package/dist/embed-react.d.ts +6 -9
- package/dist/embed-react.js +1 -1
- package/dist/embed-react.js.map +1 -1
- package/dist/embed-server.cjs +1 -1
- package/dist/embed-server.cjs.map +1 -1
- package/dist/embed-server.d.cts +6 -2
- package/dist/embed-server.d.ts +6 -2
- package/dist/embed-server.js +1 -1
- package/dist/embed-server.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -136,8 +136,8 @@ of the two auth options below) and hands it to the iframe over a secure `Message
|
|
|
136
136
|
Two modules do the heavy lifting: `embed-server` (Node/Bun) and `embed-host` (browser).
|
|
137
137
|
|
|
138
138
|
> **New here? Start with the walkthrough below.** It takes you from zero to a working
|
|
139
|
-
> embed using the API-key flow (what new systems use). The
|
|
140
|
-
> that follow it document
|
|
139
|
+
> embed using the API-key flow (what new systems use). The reference sections
|
|
140
|
+
> [that follow it](#server-the-exchange-reference) document the API and edge cases.
|
|
141
141
|
|
|
142
142
|
### Integration walkthrough — new system, start to finish
|
|
143
143
|
|
package/dist/embed-host.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var c=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var
|
|
1
|
+
"use strict";var c=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var p=Object.getOwnPropertyNames;var y=Object.prototype.hasOwnProperty;var C=(e,r)=>{for(var t in r)c(e,t,{get:r[t],enumerable:!0})},v=(e,r,t,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of p(r))!y.call(e,n)&&n!==t&&c(e,n,{get:()=>r[n],enumerable:!(o=h(r,n))||o.enumerable});return e};var w=e=>v(c({},"__esModule",{value:!0}),e);var R={};C(R,{buildCrmEmbedUrl:()=>b,createCrmEmbedHost:()=>E,crmSession:()=>k});module.exports=w(R);function M(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function k(e,r){return async()=>{let t=await fetch(e,{method:"POST",...r}),o=await t.json().catch(()=>({}));if(!t.ok){let a=o?.error;throw new Error(a?`CRM session failed: ${a}`:`CRM session failed (HTTP ${t.status})`)}let n=o;if(typeof n?.accessToken!="string"||typeof n?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return n}}function b(e,r){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(r)}`}function E(e){let r=e.windowTarget??window,t=e.createChannel??(()=>new MessageChannel),o=e.devAllowAnyOrigin?"*":e.crmOrigin,n=null,a="",d=!1;async function g(){try{let s=await e.getBearer();return n?.postMessage({type:"auth-tokens",accessToken:s.accessToken,refreshToken:s.refreshToken??""}),!0}catch(s){return e.onError?.(s),!1}}function l(s){let i=s.data;if(i)if(i.type==="channel-ack"){if(i.nonce!==a)return;g()}else i.type==="route-change"?e.onRouteChange?.(i.path):i.type==="resize"?e.onResize?.(i.height):i.type==="session-expired"&&g().then(f=>{f&&n?.postMessage({type:"session-refreshed"})})}function u(){n?.close();let s=t();n=s.port1,a=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,n.onmessage=l,n.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:a},o,[s.port2])}function m(s){d||s.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&s.origin!==e.crmOrigin||M(s.data)&&u())}return r.addEventListener("message",m),{navigate(s){n?.postMessage({type:"navigate",path:s})},dispose(){d=!0,r.removeEventListener("message",m),n?.close(),n=null}}}0&&(module.exports={buildCrmEmbedUrl,createCrmEmbedHost,crmSession});
|
|
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 return body 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<void> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n } catch (err) {\n opts.onError?.(err);\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow).\n void deliverBearer();\n port?.postMessage({ type: 'session-refreshed' });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,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,MAC3C,MAAM,IAAI,MACRC,EAAO,uBAAuBA,CAAI,GAAK,4BAA4BF,EAAI,MAAM,GAC/E,CACF,CACA,OAAOC,CACT,CACF,CASO,SAAST,EAAiBW,EAAmBC,EAA6B,CAC/E,MAAO,GAAGD,EAAU,QAAQ,MAAO,EAAE,CAAC,UAAU,mBAAmBC,CAAW,CAAC,EACjF,CAMO,SAASX,EAAmBY,EAAyC,CAC1E,IAAMC,EAASD,EAAK,cAAgB,OAC9BE,EAAcF,EAAK,gBAAkB,IAAM,IAAI,gBAC/CG,EAAeH,EAAK,kBAAoB,IAAMA,EAAK,UAErDI,EAA2B,KAC3BC,EAAQ,GACRC,EAAW,GAEf,eAAeC,GAA+B,CAC5C,GAAI,CACF,IAAMC,EAAS,MAAMR,EAAK,UAAU,EACpCI,GAAM,YAAY,CAChB,KAAM,cACN,YAAaI,EAAO,YACpB,aAAcA,EAAO,cAAgB,EACvC,CAAC,CACH,OAASC,EAAK,CACZT,EAAK,UAAUS,CAAG,CACpB,CACF,CAEA,SAASC,EAAcC,EAAqC,CAC1D,IAAMnB,EAAOmB,EAAE,KACf,GAAKnB,EACL,GAAIA,EAAK,OAAS,cAAe,CAC/B,GAAIA,EAAK,QAAUa,EAAO,OACrBE,EAAc,CACrB,MAAWf,EAAK,OAAS,eACvBQ,EAAK,gBAAgBR,EAAK,IAAI,EACrBA,EAAK,OAAS,SACvBQ,EAAK,WAAWR,EAAK,MAAM,EAClBA,EAAK,OAAS,oBAElBe,EAAc,EACnBH,GAAM,YAAY,CAAE,KAAM,mBAAoB,CAAC,EAEnD,CAEA,SAASQ,GAAuB,CAC9BR,GAAM,MAAM,EACZ,IAAMS,EAAUX,EAAY,EAC5BE,EAAOS,EAAQ,MACfR,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,CAACU,EAAQ,KAAK,CAChB,CACF,CAEA,SAASC,EAAgBC,EAA2B,CAC9CT,GACAS,EAAM,SAAWf,EAAK,OAAO,gBAC7B,CAACA,EAAK,mBAAqBe,EAAM,SAAWf,EAAK,WACjDT,EAAQwB,EAAM,IAAI,GAAGH,EAAe,EAC1C,CAEA,OAAAX,EAAO,iBAAiB,UAAWa,CAAgC,EAE5D,CACL,SAASE,EAAoB,CAC3BZ,GAAM,YAAY,CAAE,KAAM,WAAY,KAAAY,CAAK,CAAC,CAC9C,EACA,SAAgB,CACdV,EAAW,GACXL,EAAO,oBAAoB,UAAWa,CAAgC,EACtEV,GAAM,MAAM,EACZA,EAAO,IACT,CACF,CACF","names":["embed_host_exports","__export","buildCrmEmbedUrl","createCrmEmbedHost","crmSession","__toCommonJS","isReady","data","url","init","res","body","code","crmOrigin","workspaceId","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","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 *\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,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,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AAM,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"]}
|
package/dist/embed-host.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function
|
|
1
|
+
function f(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function h(e,t){return async()=>{let o=await fetch(e,{method:"POST",...t}),a=await o.json().catch(()=>({}));if(!o.ok){let i=a?.error;throw new Error(i?`CRM session failed: ${i}`:`CRM session failed (HTTP ${o.status})`)}let r=a;if(typeof r?.accessToken!="string"||typeof r?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return r}}function p(e,t){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(t)}`}function y(e){let t=e.windowTarget??window,o=e.createChannel??(()=>new MessageChannel),a=e.devAllowAnyOrigin?"*":e.crmOrigin,r=null,i="",c=!1;async function d(){try{let n=await e.getBearer();return r?.postMessage({type:"auth-tokens",accessToken:n.accessToken,refreshToken:n.refreshToken??""}),!0}catch(n){return e.onError?.(n),!1}}function m(n){let s=n.data;if(s)if(s.type==="channel-ack"){if(s.nonce!==i)return;d()}else s.type==="route-change"?e.onRouteChange?.(s.path):s.type==="resize"?e.onResize?.(s.height):s.type==="session-expired"&&d().then(u=>{u&&r?.postMessage({type:"session-refreshed"})})}function l(){r?.close();let n=o();r=n.port1,i=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,r.onmessage=m,r.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:i},a,[n.port2])}function g(n){c||n.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&n.origin!==e.crmOrigin||f(n.data)&&l())}return t.addEventListener("message",g),{navigate(n){r?.postMessage({type:"navigate",path:n})},dispose(){c=!0,t.removeEventListener("message",g),r?.close(),r=null}}}export{p as buildCrmEmbedUrl,y as createCrmEmbedHost,h as crmSession};
|
|
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 return body 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<void> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n } catch (err) {\n opts.onError?.(err);\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow).\n void deliverBearer();\n port?.postMessage({ type: 'session-refreshed' });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"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,OAAOC,CACT,CACF,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C9CT,GACAS,EAAM,SAAWf,EAAK,OAAO,gBAC7B,CAACA,EAAK,mBAAqBe,EAAM,SAAWf,EAAK,WACjDZ,EAAQ2B,EAAM,IAAI,GAAGH,EAAe,EAC1C,CAEA,OAAAX,EAAO,iBAAiB,UAAWa,CAAgC,EAE5D,CACL,SAASE,EAAoB,CAC3BZ,GAAM,YAAY,CAAE,KAAM,WAAY,KAAAY,CAAK,CAAC,CAC9C,EACA,SAAgB,CACdV,EAAW,GACXL,EAAO,oBAAoB,UAAWa,CAAgC,EACtEV,GAAM,MAAM,EACZA,EAAO,IACT,CACF,CACF","names":["isReady","data","crmSession","url","init","res","body","code","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","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 *\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,E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CAAE,KAAM,mBAAoB,CAAC,CACzD,CAAC,CAEL,CAEA,SAASS,GAAuB,CAC9BT,GAAM,MAAM,EACZ,IAAMU,EAAUZ,EAAY,EAC5BE,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,WACjDb,EAAQ6B,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":["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"]}
|
package/dist/embed-react.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var P=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var G=(e,t)=>{for(var o in t)P(e,o,{get:t[o],enumerable:!0})},J=(e,t,o,c)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of q(t))!Y.call(e,r)&&r!==o&&P(e,r,{get:()=>t[r],enumerable:!(c=j(t,r))||c.enumerable});return e};var K=e=>J(P({},"__esModule",{value:!0}),e);var re={};G(re,{CrmEmbed:()=>z,crmSession:()=>U,default:()=>ee});module.exports=K(re);var n=require("react");function Q(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function U(e,t){return async()=>{let o=await fetch(e,{method:"POST",...t}),c=await o.json().catch(()=>({}));if(!o.ok){let m=c?.error;throw new Error(m?`CRM session failed: ${m}`:`CRM session failed (HTTP ${o.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 $(e,t){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(t)}`}function W(e){let t=e.windowTarget??window,o=e.createChannel??(()=>new MessageChannel),c=e.devAllowAnyOrigin?"*":e.crmOrigin,r=null,m="",p=!1;async function C(){try{let s=await e.getBearer();return r?.postMessage({type:"auth-tokens",accessToken:s.accessToken,refreshToken:s.refreshToken??""}),!0}catch(s){return e.onError?.(s),!1}}function h(s){let d=s.data;if(d)if(d.type==="channel-ack"){if(d.nonce!==m)return;C()}else d.type==="route-change"?e.onRouteChange?.(d.path):d.type==="resize"?e.onResize?.(d.height):d.type==="session-expired"&&C().then(y=>{y&&r?.postMessage({type:"session-refreshed"})})}function E(){r?.close();let s=o();r=s.port1,m=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,r.onmessage=h,r.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:m},c,[s.port2])}function f(s){p||s.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&s.origin!==e.crmOrigin||Q(s.data)&&E())}return t.addEventListener("message",f),{navigate(s){r?.postMessage({type:"navigate",path:s})},dispose(){p=!0,t.removeEventListener("message",f),r?.close(),r=null}}}var a=require("react/jsx-runtime");var V={width:"100%",height:"100%",border:0};function H(e){return e instanceof Error?e:new Error(String(e))}function X(){return(0,a.jsx)("div",{children:"Loading CRM\u2026"})}function Z(e,t){return(0,a.jsxs)("div",{children:[(0,a.jsxs)("p",{children:["Couldn\u2019t load the CRM: ",e.message]}),(0,a.jsx)("button",{type:"button",onClick:t,children:"Try again"})]})}var z=(0,n.forwardRef)(function(t,o){let{getSession:c,crmEmbedOrigin:r,className:m,style:p,title:C="CRM",onReady:h,onError:E,onRouteChange:f,hostProvidesNav:s,initialPath:d,renderLoading:y,renderError:I}=t,x=(0,n.useRef)(null),[R,L]=(0,n.useState)(null),[k,O]=(0,n.useState)(null),[M,v]=(0,n.useState)(null),[D,F]=(0,n.useState)(0),b=(0,n.useRef)(null),S=(0,n.useRef)(null);(0,n.useImperativeHandle)(o,()=>({navigate:l=>{S.current?.navigate(l)}}),[]);let T=(0,n.useRef)(c),N=(0,n.useRef)(h),w=(0,n.useRef)(E),A=(0,n.useRef)(f);(0,n.useEffect)(()=>{T.current=c,N.current=h,w.current=E,A.current=f});let _=(0,n.useRef)(d),B=(0,n.useCallback)(()=>{b.current=null,v(null),L(null),O(null),F(l=>l+1)},[]);return(0,n.useEffect)(()=>{let l=!1;return(async()=>{try{let u=await T.current();if(l)return;b.current={accessToken:u.accessToken},O(u.workspaceId);let g=$(r,u.workspaceId)+(_.current??"")+(s?"?hostnav=1":"");L(g)}catch(u){if(l)return;let i=H(u);v(i),w.current?.(i)}})(),()=>{l=!0}},[r,s,D]),(0,n.useEffect)(()=>{let l=x.current;if(!l||!R||!k)return;let u=null;try{u=W({iframe:l,crmOrigin:r,getBearer:async()=>{let i=b.current;return i?(b.current=null,i):{accessToken:(await T.current()).accessToken}},onRouteChange:i=>{A.current?.(i)},onError:i=>{let g=H(i);v(g),w.current?.(g)}})}catch(i){let g=H(i);v(g),w.current?.(g);return}return S.current=u,N.current?.({workspaceId:k}),()=>{u?.dispose(),S.current=null}},[R,k,r]),M?(0,a.jsx)(a.Fragment,{children:I?I(M,B):Z(M,B)}):R?(0,a.jsx)("iframe",{ref:x,src:R,title:C,className:m,style:{...V,...p}}):(0,a.jsx)(a.Fragment,{children:y?y():X()})}),ee=z;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/** What a partner's `getSession()` must resolve to. */\nexport interface CrmEmbedSession {\n /** Short-lived CRM bearer (access token) to hand to the iframe. */\n accessToken: string;\n /** The workspace to embed; used to build the iframe URL. */\n workspaceId: string;\n /** Optional TTL hint (seconds). Not required by the component today. */\n expiresIn?: number;\n}\n\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 return body 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<void> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n } catch (err) {\n opts.onError?.(err);\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow).\n void deliverBearer();\n port?.postMessage({ type: 'session-refreshed' });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"yaAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,cAAAE,EAAA,eAAAC,EAAA,YAAAC,KAAA,eAAAC,EAAAL,IAwBA,IAAAM,EAEO,iBC6CP,SAASC,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CAmBO,SAASC,EACdC,EACAC,EACiC,CACjC,MAAO,UAAuC,CAC5C,IAAMC,EAAM,MAAM,MAAMF,EAAK,CAAE,OAAQ,OAAQ,GAAGC,CAAK,CAAC,EAClDE,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,GAAI,CAACA,EAAI,GAAI,CACX,IAAME,EAAQD,GAA6B,MAC3C,MAAM,IAAI,MACRC,EAAO,uBAAuBA,CAAI,GAAK,4BAA4BF,EAAI,MAAM,GAC/E,CACF,CACA,OAAOC,CACT,CACF,CASO,SAASE,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,cAAg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CAAE,aADO,MAAMd,EAAc,QAAQ,GACd,WAAY,CAC5C,EACA,cAAgBD,GAAS,CAAEI,EAAiB,UAAUJ,CAAI,CAAG,EAC7D,QAAU9B,GAAQ,CAChB,IAAMyC,EAAI1C,EAAQC,CAAG,EACrByB,EAASgB,CAAC,EACVR,EAAW,UAAUQ,CAAC,CACxB,CACF,CAAC,CACH,OAASzC,EAAK,CACZ,IAAMyC,EAAI1C,EAAQC,CAAG,EACrByB,EAASgB,CAAC,EACVR,EAAW,UAAUQ,CAAC,EACtB,MACF,CAEA,OAAAZ,EAAQ,QAAUc,EAGlBX,EAAW,UAAU,CAAE,YAAAT,CAAY,CAAC,EAE7B,IAAM,CACXoB,GAAM,QAAQ,EACdd,EAAQ,QAAU,IACpB,CACF,EAAG,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","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","startHandshake","channel","onWindowMessage","event","path","import_jsx_runtime","DEFAULT_IFRAME_STYLE","toError","err","DefaultLoading","DefaultError","error","retry","CrmEmbed","props","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 type CrmBearer,\n type CrmEmbedHost,\n type CrmSessionResult,\n} from './embed-host';\n\n// Re-export the session-fetch helper so React users can get it from one entry:\n// import { CrmEmbed, crmSession } from '@first-to-fly/crm-sdk/embed-react';\nexport { crmSession, type CrmSessionResult };\n\n/**\n * What a partner's `getSession()` must resolve to. Alias of {@link CrmSessionResult}\n * (the browser-side session shape) — kept as a named export for back-compat; both\n * are `{ accessToken, workspaceId, expiresIn? }`.\n */\nexport type CrmEmbedSession = CrmSessionResult;\n\n/**\n * Imperative handle exposed via `ref`. Lets a host drive the embedded CRM's\n * navigation without re-rendering the iframe.\n */\nexport interface CrmEmbedHandle {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n}\n\nexport interface CrmEmbedProps {\n /**\n * Resolves a CRM bearer + the workspace to embed. Called once on mount (and\n * again on retry / session expiry). Typically calls your own backend endpoint\n * that runs `createEmbedSessionWithKey`.\n */\n getSession: () => Promise<CrmEmbedSession>;\n /**\n * The CRM embed base origin, e.g. \"https://crm.example.com\". The iframe URL\n * is `buildCrmEmbedUrl(crmEmbedOrigin, workspaceId)` and this origin is also\n * used as the postMessage targetOrigin.\n */\n crmEmbedOrigin: string;\n /** Class applied to the iframe. */\n className?: string;\n /** Inline style merged onto the iframe (overrides the fill-container default). */\n style?: CSSProperties;\n /** Iframe title (accessibility). Defaults to \"CRM\". */\n title?: string;\n /** Called after the iframe URL is built and mounted. */\n onReady?: (info: { workspaceId: string }) => void;\n /** Called on any session / handshake error. */\n onError?: (error: Error) => void;\n /**\n * Called when the CRM navigates internally (e.g. \"/contacts\"). Use this to\n * keep a host-supplied nav in sync with the embedded CRM's current section.\n */\n onRouteChange?: (path: string) => void;\n /**\n * When true, the CRM hides its own in-iframe nav (the host supplies it).\n * Signalled to the CRM by appending `?hostnav=1` to the iframe URL. Drive\n * navigation yourself via the ref's `navigate()`.\n */\n hostProvidesNav?: boolean;\n /**\n * Initial CRM sub-path to deep-link on FIRST load (e.g. \"/contacts\").\n * Only applied to the initial iframe URL — later changes do NOT reload the\n * iframe; use the ref's `navigate()` for in-session navigation.\n */\n initialPath?: string;\n /** Custom loading UI. Defaults to a minimal message. */\n renderLoading?: () => ReactNode;\n /** Custom error UI. Defaults to the message + a Retry button. */\n renderError?: (error: Error, retry: () => void) => ReactNode;\n}\n\nconst DEFAULT_IFRAME_STYLE: CSSProperties = {\n width: '100%',\n height: '100%',\n border: 0,\n};\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n\nfunction DefaultLoading(): ReactNode {\n return <div>Loading CRM…</div>;\n}\n\nfunction DefaultError(error: Error, retry: () => void): ReactNode {\n return (\n <div>\n <p>Couldn’t load the CRM: {error.message}</p>\n <button type=\"button\" onClick={retry}>Try again</button>\n </div>\n );\n}\n\n/**\n * Embed the First To Fly CRM in a React app. See {@link CrmEmbedProps}.\n *\n * Accepts a `ref` of type {@link CrmEmbedHandle} exposing `navigate(path)` so a\n * host can drive the embedded CRM's section navigation.\n */\nexport const CrmEmbed = forwardRef<CrmEmbedHandle, CrmEmbedProps>(\n function CrmEmbed(props, ref): ReactNode {\n const {\n getSession,\n crmEmbedOrigin,\n className,\n style,\n title = 'CRM',\n onReady,\n onError,\n onRouteChange,\n hostProvidesNav,\n initialPath,\n renderLoading,\n renderError,\n } = props;\n\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const [embedUrl, setEmbedUrl] = useState<string | null>(null);\n const [workspaceId, setWorkspaceId] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [attempt, setAttempt] = useState(0);\n\n // Bearer minted during session resolution — reused for the host's first\n // getBearer() so a single getSession() call covers both phases (no double-mint).\n const primedBearerRef = useRef<CrmBearer | null>(null);\n\n // The created host, so the imperative `navigate()` can reach it.\n const hostRef = useRef<CrmEmbedHost | null>(null);\n\n // Expose the imperative navigate(). No-ops safely before the host is wired.\n useImperativeHandle(ref, () => ({\n navigate: (path: string) => { hostRef.current?.navigate(path); },\n }), []);\n\n // Keep the latest callbacks in refs so the effects DON'T depend on their\n // identity. Partners routinely pass inline `getSession`/`onReady`/`onError`/\n // `onRouteChange`; depending on them directly would re-run Phase 1 (re-fetch\n // the session) and tear down + recreate the host on every parent re-render.\n const getSessionRef = useRef(getSession);\n const onReadyRef = useRef(onReady);\n const onErrorRef = useRef(onError);\n const onRouteChangeRef = useRef(onRouteChange);\n useEffect(() => {\n getSessionRef.current = getSession;\n onReadyRef.current = onReady;\n onErrorRef.current = onError;\n onRouteChangeRef.current = onRouteChange;\n });\n\n // Capture initialPath ONCE — it only seeds the first load. Later changes go\n // through the imperative navigate() and must NOT rebuild/reload the iframe.\n const initialPathRef = useRef(initialPath);\n\n const retry = useCallback(() => {\n primedBearerRef.current = null;\n setError(null);\n setEmbedUrl(null);\n setWorkspaceId(null);\n setAttempt((n) => n + 1);\n }, []);\n\n // Phase 1: resolve the session, prime the bearer, and build the iframe URL.\n // Re-runs only on retry (`attempt`) or a changed origin/hostnav — never on\n // unrelated parent re-renders (callbacks + initialPath are read from refs).\n useEffect(() => {\n let cancelled = false;\n\n void (async () => {\n try {\n const session = await getSessionRef.current();\n if (cancelled) return;\n primedBearerRef.current = { accessToken: session.accessToken };\n setWorkspaceId(session.workspaceId);\n const base = buildCrmEmbedUrl(crmEmbedOrigin, session.workspaceId);\n const url = base + (initialPathRef.current ?? '') + (hostProvidesNav ? '?hostnav=1' : '');\n setEmbedUrl(url);\n } catch (err) {\n if (cancelled) return;\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n }\n })();\n\n return () => { cancelled = true; };\n }, [crmEmbedOrigin, hostProvidesNav, attempt]);\n\n // Phase 2: once the iframe URL is known, wire the MessageChannel host.\n useEffect(() => {\n const iframe = iframeRef.current;\n if (!iframe || !embedUrl || !workspaceId) return undefined;\n\n let host: CrmEmbedHost | null = null;\n try {\n host = createCrmEmbedHost({\n iframe,\n crmOrigin: crmEmbedOrigin,\n getBearer: async () => {\n const primed = primedBearerRef.current;\n if (primed) {\n primedBearerRef.current = null;\n return primed;\n }\n const session = await getSessionRef.current();\n return { accessToken: session.accessToken };\n },\n onRouteChange: (path) => { onRouteChangeRef.current?.(path); },\n onError: (err) => {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n },\n });\n } catch (err) {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n return undefined;\n }\n\n hostRef.current = host;\n\n // Only signal ready once the host is actually wired.\n onReadyRef.current?.({ workspaceId });\n\n return () => {\n host?.dispose();\n hostRef.current = null;\n };\n }, [embedUrl, workspaceId, crmEmbedOrigin]);\n\n if (error) {\n return <>{renderError ? renderError(error, retry) : DefaultError(error, retry)}</>;\n }\n\n if (!embedUrl) {\n return <>{renderLoading ? renderLoading() : DefaultLoading()}</>;\n }\n\n return (\n <iframe\n ref={iframeRef}\n src={embedUrl}\n title={title}\n className={className}\n style={{ ...DEFAULT_IFRAME_STYLE, ...style }}\n />\n );\n },\n);\n\nexport default CrmEmbed;\n","/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n const result = body as Partial<CrmSessionResult>;\n // A malformed 2xx (e.g. `{}`) would otherwise cast cleanly and later build an\n // `/embed/undefined` URL — fail at the boundary with a clear message instead.\n if (typeof result?.accessToken !== 'string' || typeof result?.workspaceId !== 'string') {\n throw new Error('CRM session response is missing accessToken/workspaceId');\n }\n return result as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n\n async function deliverBearer(): Promise<boolean> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n return true;\n } catch (err) {\n opts.onError?.(err);\n return false;\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow). Only tell the\n // CRM the session refreshed once a fresh bearer was ACTUALLY delivered —\n // otherwise a failed re-mint leaves the iframe believing it's authenticated.\n void deliverBearer().then((ok) => {\n if (ok) port?.postMessage({ type: 'session-refreshed' });\n });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"yaAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,cAAAE,EAAA,eAAAC,EAAA,YAAAC,KAAA,eAAAC,EAAAL,IAwBA,IAAAM,EAEO,iBC6CP,SAASC,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CAmBO,SAASC,EACdC,EACAC,EACiC,CACjC,MAAO,UAAuC,CAC5C,IAAMC,EAAM,MAAM,MAAMF,EAAK,CAAE,OAAQ,OAAQ,GAAGC,CAAK,CAAC,EAClDE,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,GAAI,CAACA,EAAI,GAAI,CACX,IAAME,EAAQD,GAA6B,MAC3C,MAAM,IAAI,MACRC,EAAO,uBAAuBA,CAAI,GAAK,4BAA4BF,EAAI,MAAM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bed","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"]}
|
package/dist/embed-react.d.cts
CHANGED
|
@@ -19,15 +19,12 @@ interface CrmSessionResult {
|
|
|
19
19
|
*/
|
|
20
20
|
declare function crmSession(url: string, init?: RequestInit): () => Promise<CrmSessionResult>;
|
|
21
21
|
|
|
22
|
-
/**
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
/** Optional TTL hint (seconds). Not required by the component today. */
|
|
29
|
-
expiresIn?: number;
|
|
30
|
-
}
|
|
22
|
+
/**
|
|
23
|
+
* What a partner's `getSession()` must resolve to. Alias of {@link CrmSessionResult}
|
|
24
|
+
* (the browser-side session shape) — kept as a named export for back-compat; both
|
|
25
|
+
* are `{ accessToken, workspaceId, expiresIn? }`.
|
|
26
|
+
*/
|
|
27
|
+
type CrmEmbedSession = CrmSessionResult;
|
|
31
28
|
/**
|
|
32
29
|
* Imperative handle exposed via `ref`. Lets a host drive the embedded CRM's
|
|
33
30
|
* navigation without re-rendering the iframe.
|
package/dist/embed-react.d.ts
CHANGED
|
@@ -19,15 +19,12 @@ interface CrmSessionResult {
|
|
|
19
19
|
*/
|
|
20
20
|
declare function crmSession(url: string, init?: RequestInit): () => Promise<CrmSessionResult>;
|
|
21
21
|
|
|
22
|
-
/**
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
/** Optional TTL hint (seconds). Not required by the component today. */
|
|
29
|
-
expiresIn?: number;
|
|
30
|
-
}
|
|
22
|
+
/**
|
|
23
|
+
* What a partner's `getSession()` must resolve to. Alias of {@link CrmSessionResult}
|
|
24
|
+
* (the browser-side session shape) — kept as a named export for back-compat; both
|
|
25
|
+
* are `{ accessToken, workspaceId, expiresIn? }`.
|
|
26
|
+
*/
|
|
27
|
+
type CrmEmbedSession = CrmSessionResult;
|
|
31
28
|
/**
|
|
32
29
|
* Imperative handle exposed via `ref`. Lets a host drive the embedded CRM's
|
|
33
30
|
* navigation without re-rendering the iframe.
|
package/dist/embed-react.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{forwardRef as G,useCallback as J,useEffect as
|
|
1
|
+
import{forwardRef as G,useCallback as J,useEffect as H,useImperativeHandle as K,useRef as l,useState as k}from"react";function q(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function Y(e,s){return async()=>{let u=await fetch(e,{method:"POST",...s}),m=await u.json().catch(()=>({}));if(!u.ok){let c=m?.error;throw new Error(c?`CRM session failed: ${c}`:`CRM session failed (HTTP ${u.status})`)}let r=m;if(typeof r?.accessToken!="string"||typeof r?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return r}}function $(e,s){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(s)}`}function W(e){let s=e.windowTarget??window,u=e.createChannel??(()=>new MessageChannel),m=e.devAllowAnyOrigin?"*":e.crmOrigin,r=null,c="",p=!1;async function C(){try{let n=await e.getBearer();return r?.postMessage({type:"auth-tokens",accessToken:n.accessToken,refreshToken:n.refreshToken??""}),!0}catch(n){return e.onError?.(n),!1}}function h(n){let o=n.data;if(o)if(o.type==="channel-ack"){if(o.nonce!==c)return;C()}else o.type==="route-change"?e.onRouteChange?.(o.path):o.type==="resize"?e.onResize?.(o.height):o.type==="session-expired"&&C().then(y=>{y&&r?.postMessage({type:"session-refreshed"})})}function E(){r?.close();let n=u();r=n.port1,c=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,r.onmessage=h,r.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:c},m,[n.port2])}function g(n){p||n.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&n.origin!==e.crmOrigin||q(n.data)&&E())}return s.addEventListener("message",g),{navigate(n){r?.postMessage({type:"navigate",path:n})},dispose(){p=!0,s.removeEventListener("message",g),r?.close(),r=null}}}import{Fragment as D,jsx as f,jsxs as z}from"react/jsx-runtime";var Q={width:"100%",height:"100%",border:0};function I(e){return e instanceof Error?e:new Error(String(e))}function V(){return f("div",{children:"Loading CRM\u2026"})}function X(e,s){return z("div",{children:[z("p",{children:["Couldn\u2019t load the CRM: ",e.message]}),f("button",{type:"button",onClick:s,children:"Try again"})]})}var Z=G(function(s,u){let{getSession:m,crmEmbedOrigin:r,className:c,style:p,title:C="CRM",onReady:h,onError:E,onRouteChange:g,hostProvidesNav:n,initialPath:o,renderLoading:y,renderError:x}=s,L=l(null),[R,O]=k(null),[M,N]=k(null),[S,v]=k(null),[F,_]=k(0),b=l(null),T=l(null);K(u,()=>({navigate:i=>{T.current?.navigate(i)}}),[]);let P=l(m),A=l(h),w=l(E),B=l(g);H(()=>{P.current=m,A.current=h,w.current=E,B.current=g});let j=l(o),U=J(()=>{b.current=null,v(null),O(null),N(null),_(i=>i+1)},[]);return H(()=>{let i=!1;return(async()=>{try{let a=await P.current();if(i)return;b.current={accessToken:a.accessToken},N(a.workspaceId);let d=$(r,a.workspaceId)+(j.current??"")+(n?"?hostnav=1":"");O(d)}catch(a){if(i)return;let t=I(a);v(t),w.current?.(t)}})(),()=>{i=!0}},[r,n,F]),H(()=>{let i=L.current;if(!i||!R||!M)return;let a=null;try{a=W({iframe:i,crmOrigin:r,getBearer:async()=>{let t=b.current;return t?(b.current=null,t):{accessToken:(await P.current()).accessToken}},onRouteChange:t=>{B.current?.(t)},onError:t=>{let d=I(t);v(d),w.current?.(d)}})}catch(t){let d=I(t);v(d),w.current?.(d);return}return T.current=a,A.current?.({workspaceId:M}),()=>{a?.dispose(),T.current=null}},[R,M,r]),S?f(D,{children:x?x(S,U):X(S,U)}):R?f("iframe",{ref:L,src:R,title:C,className:c,style:{...Q,...p}}):f(D,{children:y?y():V()})}),te=Z;export{Z as CrmEmbed,Y as crmSession,te as default};
|
|
2
2
|
//# sourceMappingURL=embed-react.js.map
|
package/dist/embed-react.js.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/** What a partner's `getSession()` must resolve to. */\nexport interface CrmEmbedSession {\n /** Short-lived CRM bearer (access token) to hand to the iframe. */\n accessToken: string;\n /** The workspace to embed; used to build the iframe URL. */\n workspaceId: string;\n /** Optional TTL hint (seconds). Not required by the component today. */\n expiresIn?: number;\n}\n\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 return body 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<void> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n } catch (err) {\n opts.onError?.(err);\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow).\n void deliverBearer();\n port?.postMessage({ type: 'session-refreshed' });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"AAwBA,OACE,cAAAA,EAAY,eAAAC,EAAa,aAAAC,EAAW,uBAAAC,EAAqB,UAAAC,EAAQ,YAAAC,MAC5D,QC6CP,SAASC,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CAmBO,SAASC,EACdC,EACAC,EACiC,CACjC,MAAO,UAAuC,CAC5C,IAAMC,EAAM,MAAM,MAAMF,EAAK,CAAE,OAAQ,OAAQ,GAAGC,CAAK,CAAC,EAClDE,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,GAAI,CAACA,EAAI,GAAI,CACX,IAAME,EAAQD,GAA6B,MAC3C,MAAM,IAAI,MACRC,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AAM,CACnC,EAAG,CAACjC,EAAgBO,EAAiBY,CAAO,CAAC,EAG7CU,EAAU,IAAM,CACd,IAAMS,EAAS3B,EAAU,QACzB,GAAI,CAAC2B,GAAU,CAACzB,GAAY,CAACG,EAAa,OAE1C,IAAIuB,EAA4B,KAChC,GAAI,CACFA,EAAOC,EAAmB,CACxB,OAAAF,EACA,UAAWtC,EACX,UAAW,SAAY,CACrB,IAAMyC,EAASpB,EAAgB,QAC/B,OAAIoB,GACFpB,EAAgB,QAAU,KACnBoB,GAGF,CAAE,aADO,MAAMhB,EAAc,QAAQ,GACd,WAAY,CAC5C,EACA,cAAgBD,GAAS,CAAEI,EAAiB,UAAUJ,CAAI,CAAG,EAC7D,QAAUpC,GAAQ,CAChB,IAAMiD,EAAIlD,EAAQC,CAAG,EACrB8B,EAASmB,CAAC,EACVV,EAAW,UAAUU,CAAC,CACxB,CACF,CAAC,CACH,OAASjD,EAAK,CACZ,IAAMiD,EAAIlD,EAAQC,CAAG,EACrB8B,EAASmB,CAAC,EACVV,EAAW,UAAUU,CAAC,EACtB,MACF,CAEA,OAAAf,EAAQ,QAAUiB,EAGlBb,EAAW,UAAU,CAAE,YAAAV,CAAY,CAAC,EAE7B,IAAM,CACXuB,GAAM,QAAQ,EACdjB,EAAQ,QAAU,IACpB,CACF,EAAG,CAACT,EAAUG,EAAahB,CAAc,CAAC,EAEtCR,EACKF,EAAAoD,EAAA,CAAG,SAAAhC,EAAcA,EAAYlB,EAAOC,CAAK,EAAIF,EAAaC,EAAOC,CAAK,EAAE,EAG5EoB,EAKHvB,EAAC,UACC,IAAKqB,EACL,IAAKE,EACL,MAAOV,EACP,UAAWF,EACX,MAAO,CAAE,GAAGf,EAAsB,GAAGgB,CAAM,EAC7C,EAVOZ,EAAAoD,EAAA,CAAG,SAAAjC,EAAgBA,EAAc,EAAIpB,EAAe,EAAE,CAYjE,CACF,EAEOsD,GAAQhD","names":["forwardRef","useCallback","useEffect","useImperativeHandle","useRef","useState","isReady","data","crmSession","url","init","res","body","code","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","startHandshake","channel","onWindowMessage","event","path","Fragment","jsx","jsxs","DEFAULT_IFRAME_STYLE","toError","err","DefaultLoading","jsx","DefaultError","error","retry","jsxs","CrmEmbed","forwardRef","props","ref","getSession","crmEmbedOrigin","className","style","title","onReady","onError","onRouteChange","hostProvidesNav","initialPath","renderLoading","renderError","iframeRef","useRef","embedUrl","setEmbedUrl","useState","workspaceId","setWorkspaceId","setError","attempt","setAttempt","primedBearerRef","hostRef","useImperativeHandle","path","getSessionRef","onReadyRef","onErrorRef","onRouteChangeRef","useEffect","initialPathRef","useCallback","n","cancelled","session","url","buildCrmEmbedUrl","e","iframe","host","createCrmEmbedHost","primed","Fragment","embed_react_default"]}
|
|
1
|
+
{"version":3,"sources":["../src/embed-react.tsx","../src/embed-host.ts"],"sourcesContent":["/**\n * Drop-in React component that embeds the First To Fly CRM as a cross-origin\n * iframe, authenticated WITHOUT cookies.\n *\n * This wraps the low-level {@link ./embed-host | embed-host} helpers into a\n * single component. You supply a `getSession()` that returns a CRM bearer plus\n * the workspace to embed (typically by calling your own backend endpoint that\n * runs `createEmbedSessionWithKey`), and the component handles:\n * - resolving the session and building the iframe URL,\n * - rendering the iframe and running the MessageChannel handshake,\n * - reusing the initial bearer (no double-mint) and re-minting on expiry,\n * - loading / error / retry states.\n *\n * A host (e.g. an app shell) can drive the embedded CRM's section navigation\n * imperatively via a ref (`navigate(path)`), observe the CRM's own navigation\n * via `onRouteChange`, deep-link an `initialPath` on first load, and hide the\n * CRM's in-iframe nav via `hostProvidesNav` (when the host supplies its own).\n *\n * `react` is an OPTIONAL peer dependency — only pull in this entry if you use\n * React. Non-React consumers can keep using `./embed-host` directly.\n *\n * @packageDocumentation\n */\n\nimport {\n forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState,\n} from 'react';\nimport type { CSSProperties, ReactNode } from 'react';\n\nimport {\n buildCrmEmbedUrl,\n createCrmEmbedHost,\n crmSession,\n type CrmBearer,\n type CrmEmbedHost,\n type CrmSessionResult,\n} from './embed-host';\n\n// Re-export the session-fetch helper so React users can get it from one entry:\n// import { CrmEmbed, crmSession } from '@first-to-fly/crm-sdk/embed-react';\nexport { crmSession, type CrmSessionResult };\n\n/**\n * What a partner's `getSession()` must resolve to. Alias of {@link CrmSessionResult}\n * (the browser-side session shape) — kept as a named export for back-compat; both\n * are `{ accessToken, workspaceId, expiresIn? }`.\n */\nexport type CrmEmbedSession = CrmSessionResult;\n\n/**\n * Imperative handle exposed via `ref`. Lets a host drive the embedded CRM's\n * navigation without re-rendering the iframe.\n */\nexport interface CrmEmbedHandle {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n}\n\nexport interface CrmEmbedProps {\n /**\n * Resolves a CRM bearer + the workspace to embed. Called once on mount (and\n * again on retry / session expiry). Typically calls your own backend endpoint\n * that runs `createEmbedSessionWithKey`.\n */\n getSession: () => Promise<CrmEmbedSession>;\n /**\n * The CRM embed base origin, e.g. \"https://crm.example.com\". The iframe URL\n * is `buildCrmEmbedUrl(crmEmbedOrigin, workspaceId)` and this origin is also\n * used as the postMessage targetOrigin.\n */\n crmEmbedOrigin: string;\n /** Class applied to the iframe. */\n className?: string;\n /** Inline style merged onto the iframe (overrides the fill-container default). */\n style?: CSSProperties;\n /** Iframe title (accessibility). Defaults to \"CRM\". */\n title?: string;\n /** Called after the iframe URL is built and mounted. */\n onReady?: (info: { workspaceId: string }) => void;\n /** Called on any session / handshake error. */\n onError?: (error: Error) => void;\n /**\n * Called when the CRM navigates internally (e.g. \"/contacts\"). Use this to\n * keep a host-supplied nav in sync with the embedded CRM's current section.\n */\n onRouteChange?: (path: string) => void;\n /**\n * When true, the CRM hides its own in-iframe nav (the host supplies it).\n * Signalled to the CRM by appending `?hostnav=1` to the iframe URL. Drive\n * navigation yourself via the ref's `navigate()`.\n */\n hostProvidesNav?: boolean;\n /**\n * Initial CRM sub-path to deep-link on FIRST load (e.g. \"/contacts\").\n * Only applied to the initial iframe URL — later changes do NOT reload the\n * iframe; use the ref's `navigate()` for in-session navigation.\n */\n initialPath?: string;\n /** Custom loading UI. Defaults to a minimal message. */\n renderLoading?: () => ReactNode;\n /** Custom error UI. Defaults to the message + a Retry button. */\n renderError?: (error: Error, retry: () => void) => ReactNode;\n}\n\nconst DEFAULT_IFRAME_STYLE: CSSProperties = {\n width: '100%',\n height: '100%',\n border: 0,\n};\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n\nfunction DefaultLoading(): ReactNode {\n return <div>Loading CRM…</div>;\n}\n\nfunction DefaultError(error: Error, retry: () => void): ReactNode {\n return (\n <div>\n <p>Couldn’t load the CRM: {error.message}</p>\n <button type=\"button\" onClick={retry}>Try again</button>\n </div>\n );\n}\n\n/**\n * Embed the First To Fly CRM in a React app. See {@link CrmEmbedProps}.\n *\n * Accepts a `ref` of type {@link CrmEmbedHandle} exposing `navigate(path)` so a\n * host can drive the embedded CRM's section navigation.\n */\nexport const CrmEmbed = forwardRef<CrmEmbedHandle, CrmEmbedProps>(\n function CrmEmbed(props, ref): ReactNode {\n const {\n getSession,\n crmEmbedOrigin,\n className,\n style,\n title = 'CRM',\n onReady,\n onError,\n onRouteChange,\n hostProvidesNav,\n initialPath,\n renderLoading,\n renderError,\n } = props;\n\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const [embedUrl, setEmbedUrl] = useState<string | null>(null);\n const [workspaceId, setWorkspaceId] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [attempt, setAttempt] = useState(0);\n\n // Bearer minted during session resolution — reused for the host's first\n // getBearer() so a single getSession() call covers both phases (no double-mint).\n const primedBearerRef = useRef<CrmBearer | null>(null);\n\n // The created host, so the imperative `navigate()` can reach it.\n const hostRef = useRef<CrmEmbedHost | null>(null);\n\n // Expose the imperative navigate(). No-ops safely before the host is wired.\n useImperativeHandle(ref, () => ({\n navigate: (path: string) => { hostRef.current?.navigate(path); },\n }), []);\n\n // Keep the latest callbacks in refs so the effects DON'T depend on their\n // identity. Partners routinely pass inline `getSession`/`onReady`/`onError`/\n // `onRouteChange`; depending on them directly would re-run Phase 1 (re-fetch\n // the session) and tear down + recreate the host on every parent re-render.\n const getSessionRef = useRef(getSession);\n const onReadyRef = useRef(onReady);\n const onErrorRef = useRef(onError);\n const onRouteChangeRef = useRef(onRouteChange);\n useEffect(() => {\n getSessionRef.current = getSession;\n onReadyRef.current = onReady;\n onErrorRef.current = onError;\n onRouteChangeRef.current = onRouteChange;\n });\n\n // Capture initialPath ONCE — it only seeds the first load. Later changes go\n // through the imperative navigate() and must NOT rebuild/reload the iframe.\n const initialPathRef = useRef(initialPath);\n\n const retry = useCallback(() => {\n primedBearerRef.current = null;\n setError(null);\n setEmbedUrl(null);\n setWorkspaceId(null);\n setAttempt((n) => n + 1);\n }, []);\n\n // Phase 1: resolve the session, prime the bearer, and build the iframe URL.\n // Re-runs only on retry (`attempt`) or a changed origin/hostnav — never on\n // unrelated parent re-renders (callbacks + initialPath are read from refs).\n useEffect(() => {\n let cancelled = false;\n\n void (async () => {\n try {\n const session = await getSessionRef.current();\n if (cancelled) return;\n primedBearerRef.current = { accessToken: session.accessToken };\n setWorkspaceId(session.workspaceId);\n const base = buildCrmEmbedUrl(crmEmbedOrigin, session.workspaceId);\n const url = base + (initialPathRef.current ?? '') + (hostProvidesNav ? '?hostnav=1' : '');\n setEmbedUrl(url);\n } catch (err) {\n if (cancelled) return;\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n }\n })();\n\n return () => { cancelled = true; };\n }, [crmEmbedOrigin, hostProvidesNav, attempt]);\n\n // Phase 2: once the iframe URL is known, wire the MessageChannel host.\n useEffect(() => {\n const iframe = iframeRef.current;\n if (!iframe || !embedUrl || !workspaceId) return undefined;\n\n let host: CrmEmbedHost | null = null;\n try {\n host = createCrmEmbedHost({\n iframe,\n crmOrigin: crmEmbedOrigin,\n getBearer: async () => {\n const primed = primedBearerRef.current;\n if (primed) {\n primedBearerRef.current = null;\n return primed;\n }\n const session = await getSessionRef.current();\n return { accessToken: session.accessToken };\n },\n onRouteChange: (path) => { onRouteChangeRef.current?.(path); },\n onError: (err) => {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n },\n });\n } catch (err) {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n return undefined;\n }\n\n hostRef.current = host;\n\n // Only signal ready once the host is actually wired.\n onReadyRef.current?.({ workspaceId });\n\n return () => {\n host?.dispose();\n hostRef.current = null;\n };\n }, [embedUrl, workspaceId, crmEmbedOrigin]);\n\n if (error) {\n return <>{renderError ? renderError(error, retry) : DefaultError(error, retry)}</>;\n }\n\n if (!embedUrl) {\n return <>{renderLoading ? renderLoading() : DefaultLoading()}</>;\n }\n\n return (\n <iframe\n ref={iframeRef}\n src={embedUrl}\n title={title}\n className={className}\n style={{ ...DEFAULT_IFRAME_STYLE, ...style }}\n />\n );\n },\n);\n\nexport default CrmEmbed;\n","/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n const result = body as Partial<CrmSessionResult>;\n // A malformed 2xx (e.g. `{}`) would otherwise cast cleanly and later build an\n // `/embed/undefined` URL — fail at the boundary with a clear message instead.\n if (typeof result?.accessToken !== 'string' || typeof result?.workspaceId !== 'string') {\n throw new Error('CRM session response is missing accessToken/workspaceId');\n }\n return result as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n\n async function deliverBearer(): Promise<boolean> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n return true;\n } catch (err) {\n opts.onError?.(err);\n return false;\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow). Only tell the\n // CRM the session refreshed once a fresh bearer was ACTUALLY delivered —\n // otherwise a failed re-mint leaves the iframe believing it's authenticated.\n void deliverBearer().then((ok) => {\n if (ok) port?.postMessage({ type: 'session-refreshed' });\n });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"AAwBA,OACE,cAAAA,EAAY,eAAAC,EAAa,aAAAC,EAAW,uBAAAC,EAAqB,UAAAC,EAAQ,YAAAC,MAC5D,QC6CP,SAASC,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAAC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Bb,EAAW,UAAU,CAAE,YAAAV,CAAY,CAAC,EAE7B,IAAM,CACXuB,GAAM,QAAQ,EACdjB,EAAQ,QAAU,IACpB,CACF,EAAG,CAACT,EAAUG,EAAahB,CAAc,CAAC,EAEtCR,EACKF,EAAAoD,EAAA,CAAG,SAAAhC,EAAcA,EAAYlB,EAAOC,CAAK,EAAIF,EAAaC,EAAOC,CAAK,EAAE,EAG5EoB,EAKHvB,EAAC,UACC,IAAKqB,EACL,IAAKE,EACL,MAAOV,EACP,UAAWF,EACX,MAAO,CAAE,GAAGf,EAAsB,GAAGgB,CAAM,EAC7C,EAVOZ,EAAAoD,EAAA,CAAG,SAAAjC,EAAgBA,EAAc,EAAIpB,EAAe,EAAE,CAYjE,CACF,EAEOsD,GAAQhD","names":["forwardRef","useCallback","useEffect","useImperativeHandle","useRef","useState","isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path","Fragment","jsx","jsxs","DEFAULT_IFRAME_STYLE","toError","err","DefaultLoading","jsx","DefaultError","error","retry","jsxs","CrmEmbed","forwardRef","props","ref","getSession","crmEmbedOrigin","className","style","title","onReady","onError","onRouteChange","hostProvidesNav","initialPath","renderLoading","renderError","iframeRef","useRef","embedUrl","setEmbedUrl","useState","workspaceId","setWorkspaceId","setError","attempt","setAttempt","primedBearerRef","hostRef","useImperativeHandle","path","getSessionRef","onReadyRef","onErrorRef","onRouteChangeRef","useEffect","initialPathRef","useCallback","n","cancelled","session","url","buildCrmEmbedUrl","e","iframe","host","createCrmEmbedHost","primed","Fragment","embed_react_default"]}
|
package/dist/embed-server.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var p=Object.defineProperty;var m=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var g=Object.prototype.hasOwnProperty;var f=(e,r)=>{for(var s in r)p(e,s,{get:r[s],enumerable:!0})},h=(e,r,s,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of l(r))!g.call(e,n)&&n!==s&&p(e,n,{get:()=>r[n],enumerable:!(t=m(r,n))||t.enumerable});return e};var S=e=>h(p({},"__esModule",{value:!0}),e);var w={};f(w,{CrmExchangeError:()=>i,createCrmSessionHandler:()=>E,createEmbedSessionWithKey:()=>u});module.exports=S(w);var i=class extends Error{constructor(s,t,n,o){super(s);this.status=t;this.code=n;this.detail=o;this.name="CrmExchangeError"}},y=e=>e.replace(/\/$/,"");function b(e){let r=e.access_token,s=e.workspace?.id;if(typeof r!="string"||r.length===0)throw new i("CRM response missing access_token",502,"MALFORMED_RESPONSE",e);if(typeof s!="string"||s.length===0)throw new i("CRM response missing workspace id",502,"MALFORMED_RESPONSE",e);return{accessToken:r,expiresIn:e.expires_in,workspaceId:s,user:e.user,role:e.role}}async function u(e,r){let s=r.fetch??fetch,t=`${y(r.crmBaseUrl)}/api/auth/exchange`,n=await s(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e.appId,app_secret:e.appSecret,user:e.user})}),o=await n.json().catch(()=>({}));if(!n.ok){let a=o?.error?.code??`HTTP_${n.status}`,d=o?.error?.message??"CRM exchange failed";throw new i(d,n.status,a,o)}return b(o?.data??{})}var c=(e,r)=>new Response(JSON.stringify(e),{status:r,headers:{"content-type":"application/json"}});function E(e){return async r=>{let s;try{s=await e.authenticate(r)}catch(t){let n=t?.status,o=typeof n=="number"?n:401,a=t?.code??"UNAUTHORIZED";return typeof n!="number"&&console.error("[crm-sdk] createCrmSessionHandler: authenticate() threw unexpectedly",t),c({error:a},o)}if(!s)return c({error:"UNAUTHORIZED"},401);try{let t=await u({appId:e.appId,appSecret:e.appSecret,user:s},{crmBaseUrl:e.crmBaseUrl,fetch:e.fetch});return c(t,200)}catch(t){return t instanceof i?c({error:t.code},t.status):(console.error("[crm-sdk] createCrmSessionHandler: session exchange failed",t),c({error:"CRM_SESSION_FAILED"},502))}}}0&&(module.exports={CrmExchangeError,createCrmSessionHandler,createEmbedSessionWithKey});
|
|
2
2
|
//# sourceMappingURL=embed-server.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/embed-server.ts"],"sourcesContent":["/**\n * CRM Embed Server SDK (server side).\n *\n * Use this in YOUR SaaS backend to authenticate the embedded CRM. Your server\n * POSTs the signed-in user's identity plus your registered `app_id`/`app_secret`\n * to the CRM and gets back a short-lived CRM bearer. Hand that bearer to the CRM\n * iframe via `embed-host` / `embed-react` (see ./embed-host, ./embed-react).\n *\n * Two ways to use it:\n * - {@link createCrmSessionHandler} — a ready-made Web `(Request) => Response`\n * endpoint (Next route handlers, Hono, Bun.serve, Deno, Cloudflare Workers).\n * - {@link createEmbedSessionWithKey} — the underlying call, if you want to\n * wire the endpoint yourself.\n *\n * Works in Node and Bun (or any environment with a global `fetch`). No crypto /\n * keypair / `jose` dependency — auth is a plain credential exchange.\n *\n * @packageDocumentation\n */\n\n// ─── Error class ─────────────────────────────────────────────────────────────\n\n/** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */\nexport class CrmExchangeError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly code: string,\n public readonly detail?: unknown,\n ) {\n super(message);\n this.name = 'CrmExchangeError';\n }\n}\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** The end-user being embedded into the CRM. */\nexport interface EmbedUser {\n /** Stable id for this user in YOUR system. */\n id: string;\n /** Verified email — the CRM matches/links the user by this. */\n email: string;\n /** Requested role; the CRM caps it to the install's configured max role. */\n role: 'member' | 'admin';\n /** Optional display name for first-time provisioning. */\n name?: string;\n /** Optional avatar URL for first-time provisioning. */\n avatar_url?: string;\n}\n\n/** Input for {@link createEmbedSessionWithKey}. */\nexport interface CreateEmbedSessionWithKeyInput {\n appId: string;\n appSecret: string;\n user: EmbedUser;\n}\n\n/** The CRM session returned by the exchange. */\nexport interface EmbedSession {\n /** Short-lived CRM bearer to hand to the iframe. */\n accessToken: string;\n /** TTL hint in seconds. */\n expiresIn?: number;\n /** The CRM workspace the user was provisioned into. */\n workspaceId?: string;\n /** The provisioned CRM user. */\n user?: { id: string; email: string; full_name?: string };\n /** The effective role the CRM granted (may be capped below the requested one). */\n role?: string;\n}\n\n// ─── Core exchange ───────────────────────────────────────────────────────────\n\nconst trimTrailingSlash = (url: string): string => url.replace(/\\/$/, '');\n\n/** Map the CRM's `{ data: { access_token, ... } }` envelope to an EmbedSession. */\nfunction toEmbedSession(data: Record<string, any>): EmbedSession {\n return {\n accessToken: data.access_token,\n expiresIn: data.expires_in,\n workspaceId: data.workspace?.id,\n user: data.user,\n role: data.role,\n };\n}\n\n/**\n * Exchange app credentials + user identity for a short-lived CRM bearer.\n *\n * POSTs `{ app_id, app_secret, user }` to `${crmBaseUrl}/api/auth/exchange`\n * and maps the CRM response to an {@link EmbedSession}. On non-2xx, throws\n * {@link CrmExchangeError} with `.status` and `.code`.\n *\n * @example\n * ```typescript\n * const session = await createEmbedSessionWithKey(\n * { appId: process.env.CRM_APP_ID!, appSecret: process.env.CRM_APP_SECRET!, user },\n * { crmBaseUrl: process.env.CRM_BASE_URL! },\n * );\n * // { accessToken, expiresIn, workspaceId, user, role }\n * ```\n */\nexport async function createEmbedSessionWithKey(\n input: CreateEmbedSessionWithKeyInput,\n opts: { crmBaseUrl: string; fetch?: typeof fetch },\n): Promise<EmbedSession> {\n const doFetch = opts.fetch ?? fetch;\n const url = `${trimTrailingSlash(opts.crmBaseUrl)}/api/auth/exchange`;\n const res = await doFetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n app_id: input.appId,\n app_secret: input.appSecret,\n user: input.user,\n }),\n });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = body?.error?.code ?? `HTTP_${res.status}`;\n const msg = body?.error?.message ?? 'CRM exchange failed';\n throw new CrmExchangeError(msg, res.status, code, body);\n }\n return toEmbedSession(body?.data ?? {});\n}\n\n// ─── Ready-made session endpoint ─────────────────────────────────────────────\n\n/** Options for {@link createCrmSessionHandler}. */\nexport interface CrmSessionHandlerOptions {\n appId: string;\n appSecret: string;\n /** CRM exchange base URL, e.g. \"https://api.crm.example.com\". */\n crmBaseUrl: string;\n /**\n * Resolve the signed-in user for a request. Return an {@link EmbedUser} to\n * proceed, or throw to reject. A thrown error with a numeric `.status` uses\n * that status; anything else becomes `401`.\n */\n authenticate: (req: Request) => EmbedUser | Promise<EmbedUser>;\n /** Override fetch (tests / custom agents). Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\nconst jsonResponse = (body: unknown, status: number): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n });\n\n/**\n * Build a Web-standard `(Request) => Promise<Response>` session endpoint. Drop it\n * into any runtime that speaks Web `Request`/`Response` — Next.js route handlers,\n * Hono, Bun.serve, Deno, Cloudflare Workers. (For Express/Koa, adapt the handler\n * or call {@link createEmbedSessionWithKey} directly.)\n *\n * It authenticates the request via your `authenticate` callback, runs the\n * credential exchange, and returns the {@link EmbedSession} as JSON — exactly the\n * shape `<CrmEmbed getSession>` / `crmSession()` expect. Errors map uniformly:\n * a rejected exchange returns `CrmExchangeError.status` + `{ error: code }`; a\n * failed `authenticate` returns its `.status` (or `401`).\n *\n * @example\n * ```typescript\n * // app/api/crm/session/route.ts (Next.js)\n * export const POST = createCrmSessionHandler({\n * appId: process.env.CRM_APP_ID!,\n * appSecret: process.env.CRM_APP_SECRET!,\n * crmBaseUrl: process.env.CRM_BASE_URL!,\n * authenticate: (req) => getMyUser(req), // return EmbedUser, or throw to 401\n * });\n * ```\n */\nexport function createCrmSessionHandler(\n opts: CrmSessionHandlerOptions,\n): (req: Request) => Promise<Response> {\n return async (req: Request): Promise<Response> => {\n let user: EmbedUser;\n try {\n user = await opts.authenticate(req);\n } catch (err) {\n const status = typeof (err as { status?: unknown })?.status === 'number'\n ? (err as { status: number }).status\n : 401;\n const code = (err as { code?: string })?.code ?? 'UNAUTHORIZED';\n return jsonResponse({ error: code }, status);\n }\n if (!user) return jsonResponse({ error: 'UNAUTHORIZED' }, 401);\n\n try {\n const session = await createEmbedSessionWithKey(\n { appId: opts.appId, appSecret: opts.appSecret, user },\n { crmBaseUrl: opts.crmBaseUrl, fetch: opts.fetch },\n );\n return jsonResponse(session, 200);\n } catch (err) {\n if (err instanceof CrmExchangeError) {\n return jsonResponse({ error: err.code }, err.status);\n }\n return jsonResponse({ error: 'CRM_SESSION_FAILED' }, 502);\n }\n };\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sBAAAE,EAAA,4BAAAC,EAAA,8BAAAC,IAAA,eAAAC,EAAAL,GAuBO,IAAME,EAAN,cAA+B,KAAM,CAC1C,YACEI,EACgBC,EACAC,EACAC,EAChB,CACA,MAAMH,CAAO,EAJG,YAAAC,EACA,UAAAC,EACA,YAAAC,EAGhB,KAAK,KAAO,kBACd,CACF,EAyCMC,EAAqBC,GAAwBA,EAAI,QAAQ,MAAO,EAAE,EAGxE,SAASC,EAAeC,EAAyC,CAC/D,MAAO,CACL,YAAaA,EAAK,aAClB,UAAWA,EAAK,WAChB,YAAaA,EAAK,WAAW,GAC7B,KAAMA,EAAK,KACX,KAAMA,EAAK,IACb,CACF,CAkBA,eAAsBT,EACpBU,EACAC,EACuB,CACvB,IAAMC,EAAUD,EAAK,OAAS,MACxBJ,EAAM,GAAGD,EAAkBK,EAAK,UAAU,CAAC,qBAC3CE,EAAM,MAAMD,EAAQL,EAAK,CAC7B,OAAQ,OACR,QAAS,CAAE,eAAgB,kBAAmB,EAC9C,KAAM,KAAK,UAAU,CACnB,OAAQG,EAAM,MACd,WAAYA,EAAM,UAClB,KAAMA,EAAM,IACd,CAAC,CACH,CAAC,EACKI,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,GAAI,CAACA,EAAI,GAAI,CACX,IAAMT,EAAOU,GAAM,OAAO,MAAQ,QAAQD,EAAI,MAAM,GAC9CE,EAAMD,GAAM,OAAO,SAAW,sBACpC,MAAM,IAAIhB,EAAiBiB,EAAKF,EAAI,OAAQT,EAAMU,CAAI,CACxD,CACA,OAAON,EAAeM,GAAM,MAAQ,CAAC,CAAC,CACxC,CAoBA,IAAME,EAAe,CAACF,EAAeX,IACnC,IAAI,SAAS,KAAK,UAAUW,CAAI,EAAG,CACjC,OAAAX,EACA,QAAS,CAAE,eAAgB,kBAAmB,CAChD,CAAC,EAyBI,SAASJ,EACdY,EACqC,CACrC,MAAO,OAAOM,GAAoC,CAChD,IAAIC,EACJ,GAAI,CACFA,EAAO,MAAMP,EAAK,aAAaM,CAAG,CACpC,OAASE,EAAK,CACZ,IAAMhB,EAAS,OAAQgB,GAA8B,QAAW,SAC3DA,EAA2B,OAC5B,IACEf,EAAQe,GAA2B,MAAQ,eACjD,OAAOH,EAAa,CAAE,MAAOZ,CAAK,EAAGD,CAAM,CAC7C,CACA,GAAI,CAACe,EAAM,OAAOF,EAAa,CAAE,MAAO,cAAe,EAAG,GAAG,EAE7D,GAAI,CACF,IAAMI,EAAU,MAAMpB,EACpB,CAAE,MAAOW,EAAK,MAAO,UAAWA,EAAK,UAAW,KAAAO,CAAK,EACrD,CAAE,WAAYP,EAAK,WAAY,MAAOA,EAAK,KAAM,CACnD,EACA,OAAOK,EAAaI,EAAS,GAAG,CAClC,OAASD,EAAK,CACZ,OAAIA,aAAerB,EACVkB,EAAa,CAAE,MAAOG,EAAI,IAAK,EAAGA,EAAI,MAAM,EAE9CH,EAAa,CAAE,MAAO,oBAAqB,EAAG,GAAG,CAC1D,CACF,CACF","names":["embed_server_exports","__export","CrmExchangeError","createCrmSessionHandler","createEmbedSessionWithKey","__toCommonJS","message","status","code","detail","trimTrailingSlash","url","toEmbedSession","data","input","opts","doFetch","res","body","msg","jsonResponse","req","user","err","session"]}
|
|
1
|
+
{"version":3,"sources":["../src/embed-server.ts"],"sourcesContent":["/**\n * CRM Embed Server SDK (server side).\n *\n * Use this in YOUR SaaS backend to authenticate the embedded CRM. Your server\n * POSTs the signed-in user's identity plus your registered `app_id`/`app_secret`\n * to the CRM and gets back a short-lived CRM bearer. Hand that bearer to the CRM\n * iframe via `embed-host` / `embed-react` (see ./embed-host, ./embed-react).\n *\n * Two ways to use it:\n * - {@link createCrmSessionHandler} — a ready-made Web `(Request) => Response`\n * endpoint (Next route handlers, Hono, Bun.serve, Deno, Cloudflare Workers).\n * - {@link createEmbedSessionWithKey} — the underlying call, if you want to\n * wire the endpoint yourself.\n *\n * Works in Node and Bun (or any environment with a global `fetch`). No crypto /\n * keypair / `jose` dependency — auth is a plain credential exchange.\n *\n * @packageDocumentation\n */\n\n// ─── Error class ─────────────────────────────────────────────────────────────\n\n/** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */\nexport class CrmExchangeError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly code: string,\n public readonly detail?: unknown,\n ) {\n super(message);\n this.name = 'CrmExchangeError';\n }\n}\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** The end-user being embedded into the CRM. */\nexport interface EmbedUser {\n /** Stable id for this user in YOUR system. */\n id: string;\n /** Verified email — the CRM matches/links the user by this. */\n email: string;\n /** Requested role; the CRM caps it to the install's configured max role. */\n role: 'member' | 'admin';\n /** Optional display name for first-time provisioning. */\n name?: string;\n /** Optional avatar URL for first-time provisioning. */\n avatar_url?: string;\n}\n\n/** Input for {@link createEmbedSessionWithKey}. */\nexport interface CreateEmbedSessionWithKeyInput {\n appId: string;\n appSecret: string;\n user: EmbedUser;\n}\n\n/** The CRM session returned by the exchange. */\nexport interface EmbedSession {\n /** Short-lived CRM bearer to hand to the iframe. */\n accessToken: string;\n /** TTL hint in seconds. */\n expiresIn?: number;\n /**\n * The CRM workspace the user was provisioned into. Always present on a\n * successful exchange (validated in `toEmbedSession`), so the browser can\n * build the embed URL without a further check.\n */\n workspaceId: string;\n /** The provisioned CRM user. */\n user?: { id: string; email: string; full_name?: string };\n /** The effective role the CRM granted (may be capped below the requested one). */\n role?: string;\n}\n\n// ─── Core exchange ───────────────────────────────────────────────────────────\n\nconst trimTrailingSlash = (url: string): string => url.replace(/\\/$/, '');\n\n/**\n * Map the CRM's `{ data: { access_token, ... } }` envelope to an EmbedSession.\n * Validates the two fields the type promises as non-optional so a malformed 2xx\n * fails loudly here (the one construction boundary) instead of surfacing later\n * as an `/embed/undefined` URL or an undefined bearer in the iframe.\n */\nfunction toEmbedSession(data: Record<string, any>): EmbedSession {\n const accessToken = data.access_token;\n const workspaceId = data.workspace?.id;\n if (typeof accessToken !== 'string' || accessToken.length === 0) {\n throw new CrmExchangeError('CRM response missing access_token', 502, 'MALFORMED_RESPONSE', data);\n }\n if (typeof workspaceId !== 'string' || workspaceId.length === 0) {\n throw new CrmExchangeError('CRM response missing workspace id', 502, 'MALFORMED_RESPONSE', data);\n }\n return {\n accessToken,\n expiresIn: data.expires_in,\n workspaceId,\n user: data.user,\n role: data.role,\n };\n}\n\n/**\n * Exchange app credentials + user identity for a short-lived CRM bearer.\n *\n * POSTs `{ app_id, app_secret, user }` to `${crmBaseUrl}/api/auth/exchange`\n * and maps the CRM response to an {@link EmbedSession}. On non-2xx, throws\n * {@link CrmExchangeError} with `.status` and `.code`.\n *\n * @example\n * ```typescript\n * const session = await createEmbedSessionWithKey(\n * { appId: process.env.CRM_APP_ID!, appSecret: process.env.CRM_APP_SECRET!, user },\n * { crmBaseUrl: process.env.CRM_BASE_URL! },\n * );\n * // { accessToken, expiresIn, workspaceId, user, role }\n * ```\n */\nexport async function createEmbedSessionWithKey(\n input: CreateEmbedSessionWithKeyInput,\n opts: { crmBaseUrl: string; fetch?: typeof fetch },\n): Promise<EmbedSession> {\n const doFetch = opts.fetch ?? fetch;\n const url = `${trimTrailingSlash(opts.crmBaseUrl)}/api/auth/exchange`;\n const res = await doFetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n app_id: input.appId,\n app_secret: input.appSecret,\n user: input.user,\n }),\n });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = body?.error?.code ?? `HTTP_${res.status}`;\n const msg = body?.error?.message ?? 'CRM exchange failed';\n throw new CrmExchangeError(msg, res.status, code, body);\n }\n return toEmbedSession(body?.data ?? {});\n}\n\n// ─── Ready-made session endpoint ─────────────────────────────────────────────\n\n/** Options for {@link createCrmSessionHandler}. */\nexport interface CrmSessionHandlerOptions {\n appId: string;\n appSecret: string;\n /** CRM exchange base URL, e.g. \"https://api.crm.example.com\". */\n crmBaseUrl: string;\n /**\n * Resolve the signed-in user for a request. Return an {@link EmbedUser} to\n * proceed, or throw to reject. A thrown error with a numeric `.status` uses\n * that status; anything else becomes `401`.\n */\n authenticate: (req: Request) => EmbedUser | Promise<EmbedUser>;\n /** Override fetch (tests / custom agents). Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\nconst jsonResponse = (body: unknown, status: number): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n });\n\n/**\n * Build a Web-standard `(Request) => Promise<Response>` session endpoint. Drop it\n * into any runtime that speaks Web `Request`/`Response` — Next.js route handlers,\n * Hono, Bun.serve, Deno, Cloudflare Workers. (For Express/Koa, adapt the handler\n * or call {@link createEmbedSessionWithKey} directly.)\n *\n * It authenticates the request via your `authenticate` callback, runs the\n * credential exchange, and returns the {@link EmbedSession} as JSON — exactly the\n * shape `<CrmEmbed getSession>` / `crmSession()` expect. Errors map uniformly:\n * a rejected exchange returns `CrmExchangeError.status` + `{ error: code }`; a\n * failed `authenticate` returns its `.status` (or `401`).\n *\n * @example\n * ```typescript\n * // app/api/crm/session/route.ts (Next.js)\n * export const POST = createCrmSessionHandler({\n * appId: process.env.CRM_APP_ID!,\n * appSecret: process.env.CRM_APP_SECRET!,\n * crmBaseUrl: process.env.CRM_BASE_URL!,\n * authenticate: (req) => getMyUser(req), // return EmbedUser, or throw to 401\n * });\n * ```\n */\nexport function createCrmSessionHandler(\n opts: CrmSessionHandlerOptions,\n): (req: Request) => Promise<Response> {\n return async (req: Request): Promise<Response> => {\n let user: EmbedUser;\n try {\n user = await opts.authenticate(req);\n } catch (err) {\n const rawStatus = (err as { status?: unknown })?.status;\n const status = typeof rawStatus === 'number' ? rawStatus : 401;\n const code = (err as { code?: string })?.code ?? 'UNAUTHORIZED';\n // A throw with no explicit numeric status is more likely a real fault (DB\n // timeout, bug in the callback) than an auth rejection — log it so it isn't\n // hidden behind a misleading 401, mirroring the exchange handler below.\n if (typeof rawStatus !== 'number') {\n console.error('[crm-sdk] createCrmSessionHandler: authenticate() threw unexpectedly', err);\n }\n return jsonResponse({ error: code }, status);\n }\n // A falsy return is also treated as unauthenticated (defensive: a partner whose\n // lookup returns null/undefined yields a clean 401, not a downstream 502).\n if (!user) return jsonResponse({ error: 'UNAUTHORIZED' }, 401);\n\n try {\n const session = await createEmbedSessionWithKey(\n { appId: opts.appId, appSecret: opts.appSecret, user },\n { crmBaseUrl: opts.crmBaseUrl, fetch: opts.fetch },\n );\n return jsonResponse(session, 200);\n } catch (err) {\n if (err instanceof CrmExchangeError) {\n return jsonResponse({ error: err.code }, err.status);\n }\n // Unexpected (network failure, misconfig, bug) — don't discard the stack\n // behind a bare 502; log it server-side so the failure is debuggable.\n console.error('[crm-sdk] createCrmSessionHandler: session exchange failed', err);\n return jsonResponse({ error: 'CRM_SESSION_FAILED' }, 502);\n }\n };\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sBAAAE,EAAA,4BAAAC,EAAA,8BAAAC,IAAA,eAAAC,EAAAL,GAuBO,IAAME,EAAN,cAA+B,KAAM,CAC1C,YACEI,EACgBC,EACAC,EACAC,EAChB,CACA,MAAMH,CAAO,EAJG,YAAAC,EACA,UAAAC,EACA,YAAAC,EAGhB,KAAK,KAAO,kBACd,CACF,EA6CMC,EAAqBC,GAAwBA,EAAI,QAAQ,MAAO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MAAMP,EAAK,aAAaM,CAAG,CACpC,OAASE,EAAK,CACZ,IAAMC,EAAaD,GAA8B,OAC3ClB,EAAS,OAAOmB,GAAc,SAAWA,EAAY,IACrDlB,EAAQiB,GAA2B,MAAQ,eAIjD,OAAI,OAAOC,GAAc,UACvB,QAAQ,MAAM,uEAAwED,CAAG,EAEpFH,EAAa,CAAE,MAAOd,CAAK,EAAGD,CAAM,CAC7C,CAGA,GAAI,CAACiB,EAAM,OAAOF,EAAa,CAAE,MAAO,cAAe,EAAG,GAAG,EAE7D,GAAI,CACF,IAAMK,EAAU,MAAMvB,EACpB,CAAE,MAAOa,EAAK,MAAO,UAAWA,EAAK,UAAW,KAAAO,CAAK,EACrD,CAAE,WAAYP,EAAK,WAAY,MAAOA,EAAK,KAAM,CACnD,EACA,OAAOK,EAAaK,EAAS,GAAG,CAClC,OAASF,EAAK,CACZ,OAAIA,aAAevB,EACVoB,EAAa,CAAE,MAAOG,EAAI,IAAK,EAAGA,EAAI,MAAM,GAIrD,QAAQ,MAAM,6DAA8DA,CAAG,EACxEH,EAAa,CAAE,MAAO,oBAAqB,EAAG,GAAG,EAC1D,CACF,CACF","names":["embed_server_exports","__export","CrmExchangeError","createCrmSessionHandler","createEmbedSessionWithKey","__toCommonJS","message","status","code","detail","trimTrailingSlash","url","toEmbedSession","data","accessToken","workspaceId","input","opts","doFetch","res","body","msg","jsonResponse","req","user","err","rawStatus","session"]}
|
package/dist/embed-server.d.cts
CHANGED
|
@@ -49,8 +49,12 @@ interface EmbedSession {
|
|
|
49
49
|
accessToken: string;
|
|
50
50
|
/** TTL hint in seconds. */
|
|
51
51
|
expiresIn?: number;
|
|
52
|
-
/**
|
|
53
|
-
|
|
52
|
+
/**
|
|
53
|
+
* The CRM workspace the user was provisioned into. Always present on a
|
|
54
|
+
* successful exchange (validated in `toEmbedSession`), so the browser can
|
|
55
|
+
* build the embed URL without a further check.
|
|
56
|
+
*/
|
|
57
|
+
workspaceId: string;
|
|
54
58
|
/** The provisioned CRM user. */
|
|
55
59
|
user?: {
|
|
56
60
|
id: string;
|
package/dist/embed-server.d.ts
CHANGED
|
@@ -49,8 +49,12 @@ interface EmbedSession {
|
|
|
49
49
|
accessToken: string;
|
|
50
50
|
/** TTL hint in seconds. */
|
|
51
51
|
expiresIn?: number;
|
|
52
|
-
/**
|
|
53
|
-
|
|
52
|
+
/**
|
|
53
|
+
* The CRM workspace the user was provisioned into. Always present on a
|
|
54
|
+
* successful exchange (validated in `toEmbedSession`), so the browser can
|
|
55
|
+
* build the embed URL without a further check.
|
|
56
|
+
*/
|
|
57
|
+
workspaceId: string;
|
|
54
58
|
/** The provisioned CRM user. */
|
|
55
59
|
user?: {
|
|
56
60
|
id: string;
|
package/dist/embed-server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var i=class extends Error{constructor(t,r,n,o){super(t);this.status=r;this.code=n;this.detail=o;this.name="CrmExchangeError"}},u=e=>e.replace(/\/$/,"");function d(e){return{accessToken:
|
|
1
|
+
var i=class extends Error{constructor(t,r,n,o){super(t);this.status=r;this.code=n;this.detail=o;this.name="CrmExchangeError"}},u=e=>e.replace(/\/$/,"");function d(e){let s=e.access_token,t=e.workspace?.id;if(typeof s!="string"||s.length===0)throw new i("CRM response missing access_token",502,"MALFORMED_RESPONSE",e);if(typeof t!="string"||t.length===0)throw new i("CRM response missing workspace id",502,"MALFORMED_RESPONSE",e);return{accessToken:s,expiresIn:e.expires_in,workspaceId:t,user:e.user,role:e.role}}async function m(e,s){let t=s.fetch??fetch,r=`${u(s.crmBaseUrl)}/api/auth/exchange`,n=await t(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e.appId,app_secret:e.appSecret,user:e.user})}),o=await n.json().catch(()=>({}));if(!n.ok){let a=o?.error?.code??`HTTP_${n.status}`,p=o?.error?.message??"CRM exchange failed";throw new i(p,n.status,a,o)}return d(o?.data??{})}var c=(e,s)=>new Response(JSON.stringify(e),{status:s,headers:{"content-type":"application/json"}});function l(e){return async s=>{let t;try{t=await e.authenticate(s)}catch(r){let n=r?.status,o=typeof n=="number"?n:401,a=r?.code??"UNAUTHORIZED";return typeof n!="number"&&console.error("[crm-sdk] createCrmSessionHandler: authenticate() threw unexpectedly",r),c({error:a},o)}if(!t)return c({error:"UNAUTHORIZED"},401);try{let r=await m({appId:e.appId,appSecret:e.appSecret,user:t},{crmBaseUrl:e.crmBaseUrl,fetch:e.fetch});return c(r,200)}catch(r){return r instanceof i?c({error:r.code},r.status):(console.error("[crm-sdk] createCrmSessionHandler: session exchange failed",r),c({error:"CRM_SESSION_FAILED"},502))}}}export{i as CrmExchangeError,l as createCrmSessionHandler,m as createEmbedSessionWithKey};
|
|
2
2
|
//# sourceMappingURL=embed-server.js.map
|
package/dist/embed-server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/embed-server.ts"],"sourcesContent":["/**\n * CRM Embed Server SDK (server side).\n *\n * Use this in YOUR SaaS backend to authenticate the embedded CRM. Your server\n * POSTs the signed-in user's identity plus your registered `app_id`/`app_secret`\n * to the CRM and gets back a short-lived CRM bearer. Hand that bearer to the CRM\n * iframe via `embed-host` / `embed-react` (see ./embed-host, ./embed-react).\n *\n * Two ways to use it:\n * - {@link createCrmSessionHandler} — a ready-made Web `(Request) => Response`\n * endpoint (Next route handlers, Hono, Bun.serve, Deno, Cloudflare Workers).\n * - {@link createEmbedSessionWithKey} — the underlying call, if you want to\n * wire the endpoint yourself.\n *\n * Works in Node and Bun (or any environment with a global `fetch`). No crypto /\n * keypair / `jose` dependency — auth is a plain credential exchange.\n *\n * @packageDocumentation\n */\n\n// ─── Error class ─────────────────────────────────────────────────────────────\n\n/** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */\nexport class CrmExchangeError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly code: string,\n public readonly detail?: unknown,\n ) {\n super(message);\n this.name = 'CrmExchangeError';\n }\n}\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** The end-user being embedded into the CRM. */\nexport interface EmbedUser {\n /** Stable id for this user in YOUR system. */\n id: string;\n /** Verified email — the CRM matches/links the user by this. */\n email: string;\n /** Requested role; the CRM caps it to the install's configured max role. */\n role: 'member' | 'admin';\n /** Optional display name for first-time provisioning. */\n name?: string;\n /** Optional avatar URL for first-time provisioning. */\n avatar_url?: string;\n}\n\n/** Input for {@link createEmbedSessionWithKey}. */\nexport interface CreateEmbedSessionWithKeyInput {\n appId: string;\n appSecret: string;\n user: EmbedUser;\n}\n\n/** The CRM session returned by the exchange. */\nexport interface EmbedSession {\n /** Short-lived CRM bearer to hand to the iframe. */\n accessToken: string;\n /** TTL hint in seconds. */\n expiresIn?: number;\n /** The CRM workspace the user was provisioned into. */\n workspaceId?: string;\n /** The provisioned CRM user. */\n user?: { id: string; email: string; full_name?: string };\n /** The effective role the CRM granted (may be capped below the requested one). */\n role?: string;\n}\n\n// ─── Core exchange ───────────────────────────────────────────────────────────\n\nconst trimTrailingSlash = (url: string): string => url.replace(/\\/$/, '');\n\n/** Map the CRM's `{ data: { access_token, ... } }` envelope to an EmbedSession. */\nfunction toEmbedSession(data: Record<string, any>): EmbedSession {\n return {\n accessToken: data.access_token,\n expiresIn: data.expires_in,\n workspaceId: data.workspace?.id,\n user: data.user,\n role: data.role,\n };\n}\n\n/**\n * Exchange app credentials + user identity for a short-lived CRM bearer.\n *\n * POSTs `{ app_id, app_secret, user }` to `${crmBaseUrl}/api/auth/exchange`\n * and maps the CRM response to an {@link EmbedSession}. On non-2xx, throws\n * {@link CrmExchangeError} with `.status` and `.code`.\n *\n * @example\n * ```typescript\n * const session = await createEmbedSessionWithKey(\n * { appId: process.env.CRM_APP_ID!, appSecret: process.env.CRM_APP_SECRET!, user },\n * { crmBaseUrl: process.env.CRM_BASE_URL! },\n * );\n * // { accessToken, expiresIn, workspaceId, user, role }\n * ```\n */\nexport async function createEmbedSessionWithKey(\n input: CreateEmbedSessionWithKeyInput,\n opts: { crmBaseUrl: string; fetch?: typeof fetch },\n): Promise<EmbedSession> {\n const doFetch = opts.fetch ?? fetch;\n const url = `${trimTrailingSlash(opts.crmBaseUrl)}/api/auth/exchange`;\n const res = await doFetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n app_id: input.appId,\n app_secret: input.appSecret,\n user: input.user,\n }),\n });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = body?.error?.code ?? `HTTP_${res.status}`;\n const msg = body?.error?.message ?? 'CRM exchange failed';\n throw new CrmExchangeError(msg, res.status, code, body);\n }\n return toEmbedSession(body?.data ?? {});\n}\n\n// ─── Ready-made session endpoint ─────────────────────────────────────────────\n\n/** Options for {@link createCrmSessionHandler}. */\nexport interface CrmSessionHandlerOptions {\n appId: string;\n appSecret: string;\n /** CRM exchange base URL, e.g. \"https://api.crm.example.com\". */\n crmBaseUrl: string;\n /**\n * Resolve the signed-in user for a request. Return an {@link EmbedUser} to\n * proceed, or throw to reject. A thrown error with a numeric `.status` uses\n * that status; anything else becomes `401`.\n */\n authenticate: (req: Request) => EmbedUser | Promise<EmbedUser>;\n /** Override fetch (tests / custom agents). Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\nconst jsonResponse = (body: unknown, status: number): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n });\n\n/**\n * Build a Web-standard `(Request) => Promise<Response>` session endpoint. Drop it\n * into any runtime that speaks Web `Request`/`Response` — Next.js route handlers,\n * Hono, Bun.serve, Deno, Cloudflare Workers. (For Express/Koa, adapt the handler\n * or call {@link createEmbedSessionWithKey} directly.)\n *\n * It authenticates the request via your `authenticate` callback, runs the\n * credential exchange, and returns the {@link EmbedSession} as JSON — exactly the\n * shape `<CrmEmbed getSession>` / `crmSession()` expect. Errors map uniformly:\n * a rejected exchange returns `CrmExchangeError.status` + `{ error: code }`; a\n * failed `authenticate` returns its `.status` (or `401`).\n *\n * @example\n * ```typescript\n * // app/api/crm/session/route.ts (Next.js)\n * export const POST = createCrmSessionHandler({\n * appId: process.env.CRM_APP_ID!,\n * appSecret: process.env.CRM_APP_SECRET!,\n * crmBaseUrl: process.env.CRM_BASE_URL!,\n * authenticate: (req) => getMyUser(req), // return EmbedUser, or throw to 401\n * });\n * ```\n */\nexport function createCrmSessionHandler(\n opts: CrmSessionHandlerOptions,\n): (req: Request) => Promise<Response> {\n return async (req: Request): Promise<Response> => {\n let user: EmbedUser;\n try {\n user = await opts.authenticate(req);\n } catch (err) {\n const status = typeof (err as { status?: unknown })?.status === 'number'\n ? (err as { status: number }).status\n : 401;\n const code = (err as { code?: string })?.code ?? 'UNAUTHORIZED';\n return jsonResponse({ error: code }, status);\n }\n if (!user) return jsonResponse({ error: 'UNAUTHORIZED' }, 401);\n\n try {\n const session = await createEmbedSessionWithKey(\n { appId: opts.appId, appSecret: opts.appSecret, user },\n { crmBaseUrl: opts.crmBaseUrl, fetch: opts.fetch },\n );\n return jsonResponse(session, 200);\n } catch (err) {\n if (err instanceof CrmExchangeError) {\n return jsonResponse({ error: err.code }, err.status);\n }\n return jsonResponse({ error: 'CRM_SESSION_FAILED' }, 502);\n }\n };\n}\n"],"mappings":"AAuBO,IAAMA,EAAN,cAA+B,KAAM,CAC1C,YACEC,EACgBC,EACAC,EACAC,EAChB,CACA,MAAMH,CAAO,EAJG,YAAAC,EACA,UAAAC,EACA,YAAAC,EAGhB,KAAK,KAAO,kBACd,CACF,EAyCMC,EAAqBC,GAAwBA,EAAI,QAAQ,MAAO,EAAE,EAGxE,SAASC,EAAeC,EAAyC,CAC/D,MAAO,CACL,YAAaA,EAAK,aAClB,UAAWA,EAAK,WAChB,YAAaA,EAAK,WAAW,GAC7B,KAAMA,EAAK,KACX,KAAMA,EAAK,IACb,CACF,CAkBA,eAAsBC,EACpBC,EACAC,EACuB,CACvB,IAAMC,EAAUD,EAAK,OAAS,MACxBL,EAAM,GAAGD,EAAkBM,EAAK,UAAU,CAAC,qBAC3CE,EAAM,MAAMD,EAA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AAI,MAAM,EAE9CJ,EAAa,CAAE,MAAO,oBAAqB,EAAG,GAAG,CAC1D,CACF,CACF","names":["CrmExchangeError","message","status","code","detail","trimTrailingSlash","url","toEmbedSession","data","createEmbedSessionWithKey","input","opts","doFetch","res","body","msg","jsonResponse","createCrmSessionHandler","req","user","err","session"]}
|
|
1
|
+
{"version":3,"sources":["../src/embed-server.ts"],"sourcesContent":["/**\n * CRM Embed Server SDK (server side).\n *\n * Use this in YOUR SaaS backend to authenticate the embedded CRM. Your server\n * POSTs the signed-in user's identity plus your registered `app_id`/`app_secret`\n * to the CRM and gets back a short-lived CRM bearer. Hand that bearer to the CRM\n * iframe via `embed-host` / `embed-react` (see ./embed-host, ./embed-react).\n *\n * Two ways to use it:\n * - {@link createCrmSessionHandler} — a ready-made Web `(Request) => Response`\n * endpoint (Next route handlers, Hono, Bun.serve, Deno, Cloudflare Workers).\n * - {@link createEmbedSessionWithKey} — the underlying call, if you want to\n * wire the endpoint yourself.\n *\n * Works in Node and Bun (or any environment with a global `fetch`). No crypto /\n * keypair / `jose` dependency — auth is a plain credential exchange.\n *\n * @packageDocumentation\n */\n\n// ─── Error class ─────────────────────────────────────────────────────────────\n\n/** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */\nexport class CrmExchangeError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly code: string,\n public readonly detail?: unknown,\n ) {\n super(message);\n this.name = 'CrmExchangeError';\n }\n}\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** The end-user being embedded into the CRM. */\nexport interface EmbedUser {\n /** Stable id for this user in YOUR system. */\n id: string;\n /** Verified email — the CRM matches/links the user by this. */\n email: string;\n /** Requested role; the CRM caps it to the install's configured max role. */\n role: 'member' | 'admin';\n /** Optional display name for first-time provisioning. */\n name?: string;\n /** Optional avatar URL for first-time provisioning. */\n avatar_url?: string;\n}\n\n/** Input for {@link createEmbedSessionWithKey}. */\nexport interface CreateEmbedSessionWithKeyInput {\n appId: string;\n appSecret: string;\n user: EmbedUser;\n}\n\n/** The CRM session returned by the exchange. */\nexport interface EmbedSession {\n /** Short-lived CRM bearer to hand to the iframe. */\n accessToken: string;\n /** TTL hint in seconds. */\n expiresIn?: number;\n /**\n * The CRM workspace the user was provisioned into. Always present on a\n * successful exchange (validated in `toEmbedSession`), so the browser can\n * build the embed URL without a further check.\n */\n workspaceId: string;\n /** The provisioned CRM user. */\n user?: { id: string; email: string; full_name?: string };\n /** The effective role the CRM granted (may be capped below the requested one). */\n role?: string;\n}\n\n// ─── Core exchange ───────────────────────────────────────────────────────────\n\nconst trimTrailingSlash = (url: string): string => url.replace(/\\/$/, '');\n\n/**\n * Map the CRM's `{ data: { access_token, ... } }` envelope to an EmbedSession.\n * Validates the two fields the type promises as non-optional so a malformed 2xx\n * fails loudly here (the one construction boundary) instead of surfacing later\n * as an `/embed/undefined` URL or an undefined bearer in the iframe.\n */\nfunction toEmbedSession(data: Record<string, any>): EmbedSession {\n const accessToken = data.access_token;\n const workspaceId = data.workspace?.id;\n if (typeof accessToken !== 'string' || accessToken.length === 0) {\n throw new CrmExchangeError('CRM response missing access_token', 502, 'MALFORMED_RESPONSE', data);\n }\n if (typeof workspaceId !== 'string' || workspaceId.length === 0) {\n throw new CrmExchangeError('CRM response missing workspace id', 502, 'MALFORMED_RESPONSE', data);\n }\n return {\n accessToken,\n expiresIn: data.expires_in,\n workspaceId,\n user: data.user,\n role: data.role,\n };\n}\n\n/**\n * Exchange app credentials + user identity for a short-lived CRM bearer.\n *\n * POSTs `{ app_id, app_secret, user }` to `${crmBaseUrl}/api/auth/exchange`\n * and maps the CRM response to an {@link EmbedSession}. On non-2xx, throws\n * {@link CrmExchangeError} with `.status` and `.code`.\n *\n * @example\n * ```typescript\n * const session = await createEmbedSessionWithKey(\n * { appId: process.env.CRM_APP_ID!, appSecret: process.env.CRM_APP_SECRET!, user },\n * { crmBaseUrl: process.env.CRM_BASE_URL! },\n * );\n * // { accessToken, expiresIn, workspaceId, user, role }\n * ```\n */\nexport async function createEmbedSessionWithKey(\n input: CreateEmbedSessionWithKeyInput,\n opts: { crmBaseUrl: string; fetch?: typeof fetch },\n): Promise<EmbedSession> {\n const doFetch = opts.fetch ?? fetch;\n const url = `${trimTrailingSlash(opts.crmBaseUrl)}/api/auth/exchange`;\n const res = await doFetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n app_id: input.appId,\n app_secret: input.appSecret,\n user: input.user,\n }),\n });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = body?.error?.code ?? `HTTP_${res.status}`;\n const msg = body?.error?.message ?? 'CRM exchange failed';\n throw new CrmExchangeError(msg, res.status, code, body);\n }\n return toEmbedSession(body?.data ?? {});\n}\n\n// ─── Ready-made session endpoint ─────────────────────────────────────────────\n\n/** Options for {@link createCrmSessionHandler}. */\nexport interface CrmSessionHandlerOptions {\n appId: string;\n appSecret: string;\n /** CRM exchange base URL, e.g. \"https://api.crm.example.com\". */\n crmBaseUrl: string;\n /**\n * Resolve the signed-in user for a request. Return an {@link EmbedUser} to\n * proceed, or throw to reject. A thrown error with a numeric `.status` uses\n * that status; anything else becomes `401`.\n */\n authenticate: (req: Request) => EmbedUser | Promise<EmbedUser>;\n /** Override fetch (tests / custom agents). Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\nconst jsonResponse = (body: unknown, status: number): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n });\n\n/**\n * Build a Web-standard `(Request) => Promise<Response>` session endpoint. Drop it\n * into any runtime that speaks Web `Request`/`Response` — Next.js route handlers,\n * Hono, Bun.serve, Deno, Cloudflare Workers. (For Express/Koa, adapt the handler\n * or call {@link createEmbedSessionWithKey} directly.)\n *\n * It authenticates the request via your `authenticate` callback, runs the\n * credential exchange, and returns the {@link EmbedSession} as JSON — exactly the\n * shape `<CrmEmbed getSession>` / `crmSession()` expect. Errors map uniformly:\n * a rejected exchange returns `CrmExchangeError.status` + `{ error: code }`; a\n * failed `authenticate` returns its `.status` (or `401`).\n *\n * @example\n * ```typescript\n * // app/api/crm/session/route.ts (Next.js)\n * export const POST = createCrmSessionHandler({\n * appId: process.env.CRM_APP_ID!,\n * appSecret: process.env.CRM_APP_SECRET!,\n * crmBaseUrl: process.env.CRM_BASE_URL!,\n * authenticate: (req) => getMyUser(req), // return EmbedUser, or throw to 401\n * });\n * ```\n */\nexport function createCrmSessionHandler(\n opts: CrmSessionHandlerOptions,\n): (req: Request) => Promise<Response> {\n return async (req: Request): Promise<Response> => {\n let user: EmbedUser;\n try {\n user = await opts.authenticate(req);\n } catch (err) {\n const rawStatus = (err as { status?: unknown })?.status;\n const status = typeof rawStatus === 'number' ? rawStatus : 401;\n const code = (err as { code?: string })?.code ?? 'UNAUTHORIZED';\n // A throw with no explicit numeric status is more likely a real fault (DB\n // timeout, bug in the callback) than an auth rejection — log it so it isn't\n // hidden behind a misleading 401, mirroring the exchange handler below.\n if (typeof rawStatus !== 'number') {\n console.error('[crm-sdk] createCrmSessionHandler: authenticate() threw unexpectedly', err);\n }\n return jsonResponse({ error: code }, status);\n }\n // A falsy return is also treated as unauthenticated (defensive: a partner whose\n // lookup returns null/undefined yields a clean 401, not a downstream 502).\n if (!user) return jsonResponse({ error: 'UNAUTHORIZED' }, 401);\n\n try {\n const session = await createEmbedSessionWithKey(\n { appId: opts.appId, appSecret: opts.appSecret, user },\n { crmBaseUrl: opts.crmBaseUrl, fetch: opts.fetch },\n );\n return jsonResponse(session, 200);\n } catch (err) {\n if (err instanceof CrmExchangeError) {\n return jsonResponse({ error: err.code }, err.status);\n }\n // Unexpected (network failure, misconfig, bug) — don't discard the stack\n // behind a bare 502; log it server-side so the failure is debuggable.\n console.error('[crm-sdk] createCrmSessionHandler: session exchange failed', err);\n return jsonResponse({ error: 'CRM_SESSION_FAILED' }, 502);\n }\n };\n}\n"],"mappings":"AAuBO,IAAMA,EAAN,cAA+B,KAAM,CAC1C,YACEC,EACgBC,EACAC,EACAC,EAChB,CACA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AS,CAAE,eAAgB,kBAAmB,CAChD,CAAC,EAyBI,SAASiB,EACdN,EACqC,CACrC,MAAO,OAAOO,GAAoC,CAChD,IAAIC,EACJ,GAAI,CACFA,EAAO,MAAMR,EAAK,aAAaO,CAAG,CACpC,OAASE,EAAK,CACZ,IAAMC,EAAaD,GAA8B,OAC3CpB,EAAS,OAAOqB,GAAc,SAAWA,EAAY,IACrDpB,EAAQmB,GAA2B,MAAQ,eAIjD,OAAI,OAAOC,GAAc,UACvB,QAAQ,MAAM,uEAAwED,CAAG,EAEpFJ,EAAa,CAAE,MAAOf,CAAK,EAAGD,CAAM,CAC7C,CAGA,GAAI,CAACmB,EAAM,OAAOH,EAAa,CAAE,MAAO,cAAe,EAAG,GAAG,EAE7D,GAAI,CACF,IAAMM,EAAU,MAAMb,EACpB,CAAE,MAAOE,EAAK,MAAO,UAAWA,EAAK,UAAW,KAAAQ,CAAK,EACrD,CAAE,WAAYR,EAAK,WAAY,MAAOA,EAAK,KAAM,CACnD,EACA,OAAOK,EAAaM,EAAS,GAAG,CAClC,OAASF,EAAK,CACZ,OAAIA,aAAetB,EACVkB,EAAa,CAAE,MAAOI,EAAI,IAAK,EAAGA,EAAI,MAAM,GAIrD,QAAQ,MAAM,6DAA8DA,CAAG,EACxEJ,EAAa,CAAE,MAAO,oBAAqB,EAAG,GAAG,EAC1D,CACF,CACF","names":["CrmExchangeError","message","status","code","detail","trimTrailingSlash","url","toEmbedSession","data","accessToken","workspaceId","createEmbedSessionWithKey","input","opts","doFetch","res","body","msg","jsonResponse","createCrmSessionHandler","req","user","err","rawStatus","session"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@first-to-fly/crm-sdk",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.3",
|
|
4
4
|
"description": "CRM SDK — embed third-party apps inside the CRM, or embed the CRM inside your own SaaS (proxy-free, signed-assertion or API-key auth)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.cjs",
|