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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -463,6 +463,32 @@ function Shell() {
463
463
  }
464
464
  ```
465
465
 
466
+ #### Host theme and language
467
+
468
+ Pass the host's current look and language so the embedded CRM matches your app:
469
+
470
+ - **`theme?`** — `'light' | 'dark' | 'system'`. `system` follows the visitor's OS setting.
471
+ - **`locale?`** — a BCP 47 tag such as `'en'` or `'zh-CN'`.
472
+
473
+ ```tsx
474
+ <CrmEmbed
475
+ crmEmbedOrigin="https://crm.example.com"
476
+ getSession={crmSession('/api/crm/session')}
477
+ theme={isDark ? 'dark' : 'light'}
478
+ locale={i18n.language}
479
+ />
480
+ ```
481
+
482
+ The first values go on the iframe URL (`?theme=dark&locale=zh-CN`), so the frame paints
483
+ in the right theme from the start. When either prop changes later, the component posts
484
+ `{ type: 'crm:host-context', theme?, locale? }` to the frame over the already
485
+ established, origin-checked channel (no reload, no wildcard `postMessage`).
486
+ Non-React hosts call `host.setContext({ theme, locale })` on the `createCrmEmbedHost`
487
+ handle and may pass `hostContext` to it. Omit both props and the CRM behaves as before.
488
+ The CRM applies them for the embed only and never saves them to the user's account.
489
+ The CRM currently ships English text only, so `locale` sets the frame's `lang`
490
+ attribute for now and translated screens follow as they are added.
491
+
466
492
  React is an **optional peer dependency** — only pull in this entry if you use
467
493
  React. The low-level `embed-host` remains available for non-React consumers.
468
494
 
@@ -486,9 +512,16 @@ const partner = createCrmPartnerClient({
486
512
  });
487
513
 
488
514
  // Idempotent. HTTP 201 the first time (secret shown once), 200 afterwards (no secret).
489
- const ws = await partner.upsertWorkspace(tenantId, { name: 'Acme School' });
515
+ const ws = await partner.upsertWorkspace(tenantId, {
516
+ name: 'Acme School',
517
+ currency: 'SGD', // optional, ISO 4217; new workspaces otherwise start as USD
518
+ timezone: 'Asia/Singapore', // optional, IANA name; otherwise UTC
519
+ });
490
520
  if (ws.created) store(tenantId, ws.embedAppId, ws.embedAppSecret);
491
521
 
522
+ // currency and timezone are applied on create and on any later call that sends them;
523
+ // leaving them out never changes what the workspace already has. An invalid code or zone is a 400.
524
+
492
525
  const status = await partner.getWorkspace(tenantId); // null when the CRM does not know the ref
493
526
  await partner.updateWorkspace(tenantId, { enabled: false }); // or { name } or both
494
527
  const { embedAppId, embedAppSecret } = await partner.rotateWorkspaceSecret(tenantId); // old secret dies now
package/dist/api.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as ContactQuery, a as ContactList, b as Contact, c as ContactCreate, d as ContactUpdate, L as LeadQuery, e as ListEnvelope, f as Lead, g as LeadCreate, h as LeadUpdate, T as TaskQuery, i as Task, j as LegacyTaskUpdate, k as LegacyTask, P as ProductQuery, l as Product, m as ProductCreate, n as ProductUpdate, o as ConversationQuery, p as Conversation, q as ConversationUpdate, M as MessageQuery, r as Message, s as MessageCreate, t as TagQuery, u as TagWithUsage, v as TagCreate, w as Tag } from './crm-contracts-DLY_TSwy.cjs';
2
- export { x as ContactChanges, y as ContactChangesQuery, z as ContactRefUpsertBody, A as ContactRefUpsertResult, B as LeadCapture, D as LeadNote, E as LeadNoteCreate, F as PartnerContactEraseResult, G as PartnerWorkspaceCreated, H as PartnerWorkspaceDetail, I as PartnerWorkspaceExisting, J as PartnerWorkspacePatchBody, K as PartnerWorkspaceSecret, N as PartnerWorkspaceStatus, O as PartnerWorkspaceUpsertBody, Q as TagList } from './crm-contracts-DLY_TSwy.cjs';
1
+ import { C as ContactQuery, a as ContactList, b as Contact, c as ContactCreate, d as ContactUpdate, L as LeadQuery, e as ListEnvelope, f as Lead, g as LeadCreate, h as LeadUpdate, T as TaskQuery, i as Task, j as LegacyTaskUpdate, k as LegacyTask, P as ProductQuery, l as Product, m as ProductCreate, n as ProductUpdate, o as ConversationQuery, p as Conversation, q as ConversationUpdate, M as MessageQuery, r as Message, s as MessageCreate, t as TagQuery, u as TagWithUsage, v as TagCreate, w as Tag } from './crm-contracts-iWWbB6Ga.cjs';
2
+ export { x as ContactChanges, y as ContactChangesQuery, z as ContactRefUpsertBody, A as ContactRefUpsertResult, B as LeadCapture, D as LeadNote, E as LeadNoteCreate, F as PartnerContactEraseResult, G as PartnerWorkspaceCreated, H as PartnerWorkspaceDetail, I as PartnerWorkspaceExisting, J as PartnerWorkspacePatchBody, K as PartnerWorkspaceSecret, N as PartnerWorkspaceStatus, O as PartnerWorkspaceUpsertBody, Q as TagList } from './crm-contracts-iWWbB6Ga.cjs';
3
3
 
4
4
  /**
5
5
  * Typed CRM REST API client for SaaS backends.
package/dist/api.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as ContactQuery, a as ContactList, b as Contact, c as ContactCreate, d as ContactUpdate, L as LeadQuery, e as ListEnvelope, f as Lead, g as LeadCreate, h as LeadUpdate, T as TaskQuery, i as Task, j as LegacyTaskUpdate, k as LegacyTask, P as ProductQuery, l as Product, m as ProductCreate, n as ProductUpdate, o as ConversationQuery, p as Conversation, q as ConversationUpdate, M as MessageQuery, r as Message, s as MessageCreate, t as TagQuery, u as TagWithUsage, v as TagCreate, w as Tag } from './crm-contracts-DLY_TSwy.js';
2
- export { x as ContactChanges, y as ContactChangesQuery, z as ContactRefUpsertBody, A as ContactRefUpsertResult, B as LeadCapture, D as LeadNote, E as LeadNoteCreate, F as PartnerContactEraseResult, G as PartnerWorkspaceCreated, H as PartnerWorkspaceDetail, I as PartnerWorkspaceExisting, J as PartnerWorkspacePatchBody, K as PartnerWorkspaceSecret, N as PartnerWorkspaceStatus, O as PartnerWorkspaceUpsertBody, Q as TagList } from './crm-contracts-DLY_TSwy.js';
1
+ import { C as ContactQuery, a as ContactList, b as Contact, c as ContactCreate, d as ContactUpdate, L as LeadQuery, e as ListEnvelope, f as Lead, g as LeadCreate, h as LeadUpdate, T as TaskQuery, i as Task, j as LegacyTaskUpdate, k as LegacyTask, P as ProductQuery, l as Product, m as ProductCreate, n as ProductUpdate, o as ConversationQuery, p as Conversation, q as ConversationUpdate, M as MessageQuery, r as Message, s as MessageCreate, t as TagQuery, u as TagWithUsage, v as TagCreate, w as Tag } from './crm-contracts-iWWbB6Ga.js';
2
+ export { x as ContactChanges, y as ContactChangesQuery, z as ContactRefUpsertBody, A as ContactRefUpsertResult, B as LeadCapture, D as LeadNote, E as LeadNoteCreate, F as PartnerContactEraseResult, G as PartnerWorkspaceCreated, H as PartnerWorkspaceDetail, I as PartnerWorkspaceExisting, J as PartnerWorkspacePatchBody, K as PartnerWorkspaceSecret, N as PartnerWorkspaceStatus, O as PartnerWorkspaceUpsertBody, Q as TagList } from './crm-contracts-iWWbB6Ga.js';
3
3
 
4
4
  /**
5
5
  * Typed CRM REST API client for SaaS backends.
@@ -126,6 +126,7 @@ type Contact = {
126
126
  whatsapp_consent?: ("opted_in" | "opted_out" | "unknown") | undefined;
127
127
  whatsapp_consent_source?: (string | undefined) | null;
128
128
  whatsapp_consent_at?: (string | undefined) | null;
129
+ product_synced?: boolean | undefined;
129
130
  metadata?: {
130
131
  [x: string]: unknown;
131
132
  } | undefined;
@@ -193,6 +194,7 @@ type ContactList = {
193
194
  whatsapp_consent?: ("opted_in" | "opted_out" | "unknown") | undefined;
194
195
  whatsapp_consent_source?: (string | undefined) | null;
195
196
  whatsapp_consent_at?: (string | undefined) | null;
197
+ product_synced?: boolean | undefined;
196
198
  metadata?: {
197
199
  [x: string]: unknown;
198
200
  } | undefined;
@@ -281,6 +283,7 @@ type ContactRefUpsertResult = {
281
283
  whatsapp_consent?: ("opted_in" | "opted_out" | "unknown") | undefined;
282
284
  whatsapp_consent_source?: (string | undefined) | null;
283
285
  whatsapp_consent_at?: (string | undefined) | null;
286
+ product_synced?: boolean | undefined;
284
287
  metadata?: {
285
288
  [x: string]: unknown;
286
289
  } | undefined;
@@ -343,6 +346,8 @@ type ContactChanges = {
343
346
  };
344
347
  type PartnerWorkspaceUpsertBody = {
345
348
  name: string;
349
+ currency?: string | undefined;
350
+ timezone?: string | undefined;
346
351
  };
347
352
  type PartnerWorkspacePatchBody = {
348
353
  enabled?: boolean | undefined;
@@ -126,6 +126,7 @@ type Contact = {
126
126
  whatsapp_consent?: ("opted_in" | "opted_out" | "unknown") | undefined;
127
127
  whatsapp_consent_source?: (string | undefined) | null;
128
128
  whatsapp_consent_at?: (string | undefined) | null;
129
+ product_synced?: boolean | undefined;
129
130
  metadata?: {
130
131
  [x: string]: unknown;
131
132
  } | undefined;
@@ -193,6 +194,7 @@ type ContactList = {
193
194
  whatsapp_consent?: ("opted_in" | "opted_out" | "unknown") | undefined;
194
195
  whatsapp_consent_source?: (string | undefined) | null;
195
196
  whatsapp_consent_at?: (string | undefined) | null;
197
+ product_synced?: boolean | undefined;
196
198
  metadata?: {
197
199
  [x: string]: unknown;
198
200
  } | undefined;
@@ -281,6 +283,7 @@ type ContactRefUpsertResult = {
281
283
  whatsapp_consent?: ("opted_in" | "opted_out" | "unknown") | undefined;
282
284
  whatsapp_consent_source?: (string | undefined) | null;
283
285
  whatsapp_consent_at?: (string | undefined) | null;
286
+ product_synced?: boolean | undefined;
284
287
  metadata?: {
285
288
  [x: string]: unknown;
286
289
  } | undefined;
@@ -343,6 +346,8 @@ type ContactChanges = {
343
346
  };
344
347
  type PartnerWorkspaceUpsertBody = {
345
348
  name: string;
349
+ currency?: string | undefined;
350
+ timezone?: string | undefined;
346
351
  };
347
352
  type PartnerWorkspacePatchBody = {
348
353
  enabled?: boolean | undefined;
@@ -1,2 +1,2 @@
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});
1
+ "use strict";var d=Object.defineProperty;var y=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var w=(e,t)=>{for(var s in t)d(e,s,{get:t[s],enumerable:!0})},M=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of x(t))!v.call(e,n)&&n!==s&&d(e,n,{get:()=>t[n],enumerable:!(i=y(t,n))||i.enumerable});return e};var H=e=>M(d({},"__esModule",{value:!0}),e);var P={};w(P,{buildCrmEmbedUrl:()=>I,createCrmEmbedHost:()=>O,crmSession:()=>b,hostContextQuery:()=>R,normalizeHostContext:()=>m});module.exports=H(P);var k=["light","dark","system"],E=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;function m(e){let t={};return e?.theme&&k.includes(e.theme)&&(t.theme=e.theme),typeof e?.locale=="string"&&E.test(e.locale.trim())&&(t.locale=e.locale.trim()),t}function R(e){let t=m(e),s=[];return t.theme&&s.push(`theme=${encodeURIComponent(t.theme)}`),t.locale&&s.push(`locale=${encodeURIComponent(t.locale)}`),s}function T(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function b(e,t){return async()=>{let s=await fetch(e,{method:"POST",...t}),i=await s.json().catch(()=>({}));if(!s.ok){let a=i?.error;throw new Error(a?`CRM session failed: ${a}`:`CRM session failed (HTTP ${s.status})`)}let n=i;if(typeof n?.accessToken!="string"||typeof n?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return n}}function I(e,t){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(t)}`}function O(e){let t=e.windowTarget??window,s=e.createChannel??(()=>new MessageChannel),i=e.devAllowAnyOrigin?"*":e.crmOrigin,n=null,a="",l=!1,c=m(e.hostContext);function g(){if(!n||c.theme===void 0&&c.locale===void 0)return;let r={type:"crm:host-context",...c};n.postMessage(r)}async function C(){try{let r=await e.getBearer();return n?.postMessage({type:"auth-tokens",accessToken:r.accessToken,refreshToken:r.refreshToken??""}),g(),!0}catch(r){return e.onError?.(r),!1}}function h(r){let o=r.data;if(o)if(o.type==="channel-ack"){if(o.nonce!==a)return;C()}else o.type==="route-change"?e.onRouteChange?.(o.path):o.type==="resize"?e.onResize?.(o.height):o.type==="session-expired"&&C().then(p=>{p&&n?.postMessage({type:"session-refreshed"})})}function f(){n?.close();let r=s();n=r.port1,a=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,n.onmessage=h,n.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:a},i,[r.port2])}function u(r){l||r.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&r.origin!==e.crmOrigin||T(r.data)&&f())}return t.addEventListener("message",u),{navigate(r){n?.postMessage({type:"navigate",path:r})},setContext(r){c={...c,...m(r)},g()},dispose(){l=!0,t.removeEventListener("message",u),n?.close(),n=null}}}0&&(module.exports={buildCrmEmbedUrl,createCrmEmbedHost,crmSession,hostContextQuery,normalizeHostContext});
2
2
  //# sourceMappingURL=embed-host.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/embed-host.ts"],"sourcesContent":["/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n const result = body as Partial<CrmSessionResult>;\n // A malformed 2xx (e.g. `{}`) would otherwise cast cleanly and later build an\n // `/embed/undefined` URL — fail at the boundary with a clear message instead.\n if (typeof result?.accessToken !== 'string' || typeof result?.workspaceId !== 'string') {\n throw new Error('CRM session response is missing accessToken/workspaceId');\n }\n return result as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n\n async function deliverBearer(): Promise<boolean> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n return true;\n } catch (err) {\n opts.onError?.(err);\n return false;\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow). Only tell the\n // CRM the session refreshed once a fresh bearer was ACTUALLY delivered —\n // otherwise a failed re-mint leaves the iframe believing it's authenticated.\n void deliverBearer().then((ok) => {\n if (ok) port?.postMessage({ type: 'session-refreshed' });\n });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sBAAAE,EAAA,uBAAAC,EAAA,eAAAC,IAAA,eAAAC,EAAAL,GAuEA,SAASM,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CAmBO,SAASH,EACdI,EACAC,EACiC,CACjC,MAAO,UAAuC,CAC5C,IAAMC,E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BAIlBgB,EAAc,EAAE,KAAMK,GAAO,CAC5BA,GAAIR,GAAM,YAAY,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,WACjDV,EAAQ0B,EAAM,IAAI,GAAGH,EAAe,EAC1C,CAEA,OAAAZ,EAAO,iBAAiB,UAAWc,CAAgC,EAE5D,CACL,SAASE,EAAoB,CAC3Bb,GAAM,YAAY,CAAE,KAAM,WAAY,KAAAa,CAAK,CAAC,CAC9C,EACA,SAAgB,CACdX,EAAW,GACXL,EAAO,oBAAoB,UAAWc,CAAgC,EACtEX,GAAM,MAAM,EACZA,EAAO,IACT,CACF,CACF","names":["embed_host_exports","__export","buildCrmEmbedUrl","createCrmEmbedHost","crmSession","__toCommonJS","isReady","data","url","init","res","body","code","result","crmOrigin","workspaceId","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path"]}
1
+ {"version":3,"sources":["../src/embed-host.ts"],"sourcesContent":["/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n * 6. host sends { type: 'crm:host-context', theme?, locale? } on the same port,\n * right after the bearer and again whenever {@link CrmEmbedHost.setContext} is called.\n * The first values also ride on the iframe URL (`?theme=` and `?locale=`), so the\n * frame paints in the right theme before the handshake finishes.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\n/** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */\nexport type CrmHostTheme = 'light' | 'dark' | 'system';\n\n/**\n * Look and language the host passes to the embedded CRM. Both are optional; an omitted\n * field leaves the CRM's own behaviour unchanged. The CRM applies them for the embed only\n * and never saves them to the user's account.\n */\nexport interface CrmHostContext {\n theme?: CrmHostTheme;\n /** BCP 47 language tag, e.g. \"en\" or \"zh-CN\". */\n locale?: string;\n}\n\n/** The message the host posts on the channel port to update {@link CrmHostContext}. */\nexport interface CrmHostContextMessage extends CrmHostContext {\n type: 'crm:host-context';\n}\n\nconst HOST_THEMES: readonly string[] = ['light', 'dark', 'system'];\nconst BCP47_LIKE = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;\n\n/**\n * Keeps only values the CRM understands: a known theme and a well-formed language tag.\n * Anything else is dropped, so a bad value can never reach the iframe URL or the message.\n */\nexport function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext {\n const out: CrmHostContext = {};\n if (ctx?.theme && HOST_THEMES.includes(ctx.theme)) out.theme = ctx.theme;\n if (typeof ctx?.locale === 'string' && BCP47_LIKE.test(ctx.locale.trim())) out.locale = ctx.locale.trim();\n return out;\n}\n\n/** `theme` and `locale` as URL query pairs (e.g. `[\"theme=dark\", \"locale=zh-CN\"]`). */\nexport function hostContextQuery(ctx: CrmHostContext | undefined): string[] {\n const clean = normalizeHostContext(ctx);\n const pairs: string[] = [];\n if (clean.theme) pairs.push(`theme=${encodeURIComponent(clean.theme)}`);\n if (clean.locale) pairs.push(`locale=${encodeURIComponent(clean.locale)}`);\n return pairs;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /** Initial theme/locale, sent to the CRM once the channel is up. Change it with `setContext()`. */\n hostContext?: CrmHostContext;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /**\n * Update the theme and/or language of the embedded CRM. Sent over the established\n * channel only, never broadcast with a wildcard origin. Fields you leave out keep\n * their last value; before the channel is up the latest values go out on connect.\n */\n setContext: (ctx: CrmHostContext) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n const result = body as Partial<CrmSessionResult>;\n // A malformed 2xx (e.g. `{}`) would otherwise cast cleanly and later build an\n // `/embed/undefined` URL — fail at the boundary with a clear message instead.\n if (typeof result?.accessToken !== 'string' || typeof result?.workspaceId !== 'string') {\n throw new Error('CRM session response is missing accessToken/workspaceId');\n }\n return result as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n let context: CrmHostContext = normalizeHostContext(opts.hostContext);\n\n function sendContext(): void {\n if (!port || (context.theme === undefined && context.locale === undefined)) return;\n const msg: CrmHostContextMessage = { type: 'crm:host-context', ...context };\n port.postMessage(msg);\n }\n\n async function deliverBearer(): Promise<boolean> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n sendContext();\n return true;\n } catch (err) {\n opts.onError?.(err);\n return false;\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow). Only tell the\n // CRM the session refreshed once a fresh bearer was ACTUALLY delivered —\n // otherwise a failed re-mint leaves the iframe believing it's authenticated.\n void deliverBearer().then((ok) => {\n if (ok) port?.postMessage({ type: 'session-refreshed' });\n });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n setContext(ctx: CrmHostContext): void {\n context = { ...context, ...normalizeHostContext(ctx) };\n sendContext();\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sBAAAE,EAAA,uBAAAC,EAAA,eAAAC,EAAA,qBAAAC,EAAA,yBAAAC,IAAA,eAAAC,EAAAP,GAgDA,IAAMQ,EAAiC,CAAC,QAAS,OAAQ,QAAQ,EAC3DC,EAAa,4CAMZ,SAASH,EAAqBI,EAAiD,CACpF,IAAMC,EAAsB,CAAC,EAC7B,OAAID,GAAK,OAASF,EAAY,SAASE,EAAI,KAAK,IAAGC,EAAI,MAAQD,EAAI,OAC/D,OAAOA,GAAK,QAAW,UAAYD,EAAW,KAAKC,EAAI,OAAO,KAAK,CAAC,IAAGC,EAAI,OAASD,EAAI,OAAO,KAAK,GACjGC,CACT,CAGO,SAASN,EAAiBK,EAA2C,CAC1E,IAAME,EAAQN,EAAqBI,CAAG,EAChCG,EAAkB,CAAC,EACzB,OAAID,EAAM,OAAOC,EAAM,KAAK,SAAS,mBAAmBD,EAAM,KAAK,CAAC,EAAE,EAClEA,EAAM,QAAQC,EAAM,KAAK,UAAU,mBAAmBD,EAA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CAAE,GAAGA,EAAS,GAAGzB,EAAqBI,CAAG,CAAE,EACrDsB,EAAY,CACd,EACA,SAAgB,CACdF,EAAW,GACXL,EAAO,oBAAoB,UAAWiB,CAAgC,EACtEd,GAAM,MAAM,EACZA,EAAO,IACT,CACF,CACF","names":["embed_host_exports","__export","buildCrmEmbedUrl","createCrmEmbedHost","crmSession","hostContextQuery","normalizeHostContext","__toCommonJS","HOST_THEMES","BCP47_LIKE","ctx","out","clean","pairs","isReady","data","url","init","res","body","code","result","crmOrigin","workspaceId","opts","target","makeChannel","targetOrigin","port","nonce","disposed","context","sendContext","msg","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path"]}
@@ -13,6 +13,10 @@
13
13
  * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)
14
14
  * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }
15
15
  * - on 'session-expired' the host re-fetches a bearer and re-sends it.
16
+ * 6. host sends { type: 'crm:host-context', theme?, locale? } on the same port,
17
+ * right after the bearer and again whenever {@link CrmEmbedHost.setContext} is called.
18
+ * The first values also ride on the iframe URL (`?theme=` and `?locale=`), so the
19
+ * frame paints in the right theme before the handshake finishes.
16
20
  *
17
21
  * @packageDocumentation
18
22
  */
@@ -21,6 +25,29 @@ interface CrmBearer {
21
25
  accessToken: string;
22
26
  refreshToken?: string;
23
27
  }
28
+ /** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */
29
+ type CrmHostTheme = 'light' | 'dark' | 'system';
30
+ /**
31
+ * Look and language the host passes to the embedded CRM. Both are optional; an omitted
32
+ * field leaves the CRM's own behaviour unchanged. The CRM applies them for the embed only
33
+ * and never saves them to the user's account.
34
+ */
35
+ interface CrmHostContext {
36
+ theme?: CrmHostTheme;
37
+ /** BCP 47 language tag, e.g. "en" or "zh-CN". */
38
+ locale?: string;
39
+ }
40
+ /** The message the host posts on the channel port to update {@link CrmHostContext}. */
41
+ interface CrmHostContextMessage extends CrmHostContext {
42
+ type: 'crm:host-context';
43
+ }
44
+ /**
45
+ * Keeps only values the CRM understands: a known theme and a well-formed language tag.
46
+ * Anything else is dropped, so a bad value can never reach the iframe URL or the message.
47
+ */
48
+ declare function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext;
49
+ /** `theme` and `locale` as URL query pairs (e.g. `["theme=dark", "locale=zh-CN"]`). */
50
+ declare function hostContextQuery(ctx: CrmHostContext | undefined): string[];
24
51
  interface CrmEmbedHostOptions {
25
52
  /** The <iframe> element that loads the CRM embed URL. */
26
53
  iframe: HTMLIFrameElement;
@@ -42,6 +69,8 @@ interface CrmEmbedHostOptions {
42
69
  onResize?: (height: number) => void;
43
70
  /** Called on any handshake/bearer error. */
44
71
  onError?: (err: unknown) => void;
72
+ /** Initial theme/locale, sent to the CRM once the channel is up. Change it with `setContext()`. */
73
+ hostContext?: CrmHostContext;
45
74
  /**
46
75
  * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).
47
76
  * NEVER enable in production — it disables the origin check.
@@ -55,6 +84,12 @@ interface CrmEmbedHostOptions {
55
84
  interface CrmEmbedHost {
56
85
  /** Tell the CRM to navigate to a sub-path, e.g. "/contacts" or "/leads/123". */
57
86
  navigate: (path: string) => void;
87
+ /**
88
+ * Update the theme and/or language of the embedded CRM. Sent over the established
89
+ * channel only, never broadcast with a wildcard origin. Fields you leave out keep
90
+ * their last value; before the channel is up the latest values go out on connect.
91
+ */
92
+ setContext: (ctx: CrmHostContext) => void;
58
93
  /** Tear down the channel and listeners. Call on unmount. */
59
94
  dispose: () => void;
60
95
  }
@@ -89,4 +124,4 @@ declare function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): strin
89
124
  */
90
125
  declare function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost;
91
126
 
92
- export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, type CrmSessionResult, buildCrmEmbedUrl, createCrmEmbedHost, crmSession };
127
+ export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, type CrmHostContext, type CrmHostContextMessage, type CrmHostTheme, type CrmSessionResult, buildCrmEmbedUrl, createCrmEmbedHost, crmSession, hostContextQuery, normalizeHostContext };
@@ -13,6 +13,10 @@
13
13
  * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)
14
14
  * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }
15
15
  * - on 'session-expired' the host re-fetches a bearer and re-sends it.
16
+ * 6. host sends { type: 'crm:host-context', theme?, locale? } on the same port,
17
+ * right after the bearer and again whenever {@link CrmEmbedHost.setContext} is called.
18
+ * The first values also ride on the iframe URL (`?theme=` and `?locale=`), so the
19
+ * frame paints in the right theme before the handshake finishes.
16
20
  *
17
21
  * @packageDocumentation
18
22
  */
@@ -21,6 +25,29 @@ interface CrmBearer {
21
25
  accessToken: string;
22
26
  refreshToken?: string;
23
27
  }
28
+ /** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */
29
+ type CrmHostTheme = 'light' | 'dark' | 'system';
30
+ /**
31
+ * Look and language the host passes to the embedded CRM. Both are optional; an omitted
32
+ * field leaves the CRM's own behaviour unchanged. The CRM applies them for the embed only
33
+ * and never saves them to the user's account.
34
+ */
35
+ interface CrmHostContext {
36
+ theme?: CrmHostTheme;
37
+ /** BCP 47 language tag, e.g. "en" or "zh-CN". */
38
+ locale?: string;
39
+ }
40
+ /** The message the host posts on the channel port to update {@link CrmHostContext}. */
41
+ interface CrmHostContextMessage extends CrmHostContext {
42
+ type: 'crm:host-context';
43
+ }
44
+ /**
45
+ * Keeps only values the CRM understands: a known theme and a well-formed language tag.
46
+ * Anything else is dropped, so a bad value can never reach the iframe URL or the message.
47
+ */
48
+ declare function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext;
49
+ /** `theme` and `locale` as URL query pairs (e.g. `["theme=dark", "locale=zh-CN"]`). */
50
+ declare function hostContextQuery(ctx: CrmHostContext | undefined): string[];
24
51
  interface CrmEmbedHostOptions {
25
52
  /** The <iframe> element that loads the CRM embed URL. */
26
53
  iframe: HTMLIFrameElement;
@@ -42,6 +69,8 @@ interface CrmEmbedHostOptions {
42
69
  onResize?: (height: number) => void;
43
70
  /** Called on any handshake/bearer error. */
44
71
  onError?: (err: unknown) => void;
72
+ /** Initial theme/locale, sent to the CRM once the channel is up. Change it with `setContext()`. */
73
+ hostContext?: CrmHostContext;
45
74
  /**
46
75
  * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).
47
76
  * NEVER enable in production — it disables the origin check.
@@ -55,6 +84,12 @@ interface CrmEmbedHostOptions {
55
84
  interface CrmEmbedHost {
56
85
  /** Tell the CRM to navigate to a sub-path, e.g. "/contacts" or "/leads/123". */
57
86
  navigate: (path: string) => void;
87
+ /**
88
+ * Update the theme and/or language of the embedded CRM. Sent over the established
89
+ * channel only, never broadcast with a wildcard origin. Fields you leave out keep
90
+ * their last value; before the channel is up the latest values go out on connect.
91
+ */
92
+ setContext: (ctx: CrmHostContext) => void;
58
93
  /** Tear down the channel and listeners. Call on unmount. */
59
94
  dispose: () => void;
60
95
  }
@@ -89,4 +124,4 @@ declare function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): strin
89
124
  */
90
125
  declare function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost;
91
126
 
92
- export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, type CrmSessionResult, buildCrmEmbedUrl, createCrmEmbedHost, crmSession };
127
+ export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, type CrmHostContext, type CrmHostContextMessage, type CrmHostTheme, type CrmSessionResult, buildCrmEmbedUrl, createCrmEmbedHost, crmSession, hostContextQuery, normalizeHostContext };
@@ -1,2 +1,2 @@
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};
1
+ var p=["light","dark","system"],y=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;function m(e){let n={};return e?.theme&&p.includes(e.theme)&&(n.theme=e.theme),typeof e?.locale=="string"&&y.test(e.locale.trim())&&(n.locale=e.locale.trim()),n}function v(e){let n=m(e),s=[];return n.theme&&s.push(`theme=${encodeURIComponent(n.theme)}`),n.locale&&s.push(`locale=${encodeURIComponent(n.locale)}`),s}function x(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function w(e,n){return async()=>{let s=await fetch(e,{method:"POST",...n}),c=await s.json().catch(()=>({}));if(!s.ok){let i=c?.error;throw new Error(i?`CRM session failed: ${i}`:`CRM session failed (HTTP ${s.status})`)}let r=c;if(typeof r?.accessToken!="string"||typeof r?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return r}}function M(e,n){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(n)}`}function H(e){let n=e.windowTarget??window,s=e.createChannel??(()=>new MessageChannel),c=e.devAllowAnyOrigin?"*":e.crmOrigin,r=null,i="",d=!1,a=m(e.hostContext);function l(){if(!r||a.theme===void 0&&a.locale===void 0)return;let t={type:"crm:host-context",...a};r.postMessage(t)}async function g(){try{let t=await e.getBearer();return r?.postMessage({type:"auth-tokens",accessToken:t.accessToken,refreshToken:t.refreshToken??""}),l(),!0}catch(t){return e.onError?.(t),!1}}function u(t){let o=t.data;if(o)if(o.type==="channel-ack"){if(o.nonce!==i)return;g()}else o.type==="route-change"?e.onRouteChange?.(o.path):o.type==="resize"?e.onResize?.(o.height):o.type==="session-expired"&&g().then(f=>{f&&r?.postMessage({type:"session-refreshed"})})}function h(){r?.close();let t=s();r=t.port1,i=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,r.onmessage=u,r.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:i},c,[t.port2])}function C(t){d||t.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&t.origin!==e.crmOrigin||x(t.data)&&h())}return n.addEventListener("message",C),{navigate(t){r?.postMessage({type:"navigate",path:t})},setContext(t){a={...a,...m(t)},l()},dispose(){d=!0,n.removeEventListener("message",C),r?.close(),r=null}}}export{M as buildCrmEmbedUrl,H as createCrmEmbedHost,w as crmSession,v as hostContextQuery,m as normalizeHostContext};
2
2
  //# sourceMappingURL=embed-host.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/embed-host.ts"],"sourcesContent":["/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n const result = body as Partial<CrmSessionResult>;\n // A malformed 2xx (e.g. `{}`) would otherwise cast cleanly and later build an\n // `/embed/undefined` URL — fail at the boundary with a clear message instead.\n if (typeof result?.accessToken !== 'string' || typeof result?.workspaceId !== 'string') {\n throw new Error('CRM session response is missing accessToken/workspaceId');\n }\n return result as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n\n async function deliverBearer(): Promise<boolean> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n return true;\n } catch (err) {\n opts.onError?.(err);\n return false;\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow). Only tell the\n // CRM the session refreshed once a fresh bearer was ACTUALLY delivered —\n // otherwise a failed re-mint leaves the iframe believing it's authenticated.\n void deliverBearer().then((ok) => {\n if (ok) port?.postMessage({ type: 'session-refreshed' });\n });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"AAuEA,SAASA,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CAmBO,SAASC,EACdC,EACAC,EACiC,CACjC,MAAO,UAAuC,CAC5C,IAAMC,EAAM,MAAM,MAAMF,EAAK,CAAE,OAAQ,OAAQ,GAAGC,CAAK,CAAC,EAClDE,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,GAAI,CAACA,EAAI,GAAI,CACX,IAAME,EAAQD,GAA6B,MAC3C,MAAM,IAAI,MACRC,EAAO,uBAAuBA,CAAI,GAAK,4BAA4BF,EAAI,MAAM,GAC/E,CACF,CACA,IAAMG,EAASF,EAGf,GAAI,OAAOE,GAAQ,aAAgB,UAAY,OAAOA,GAAQ,aAAgB,SAC5E,MAAM,IAAI,MAAM,yDAAyD,EAE3E,OAAOA,CACT,CACF,CASO,SAASC,EAAiBC,EAAmBC,EAA6B,CAC/E,MAAO,GAAGD,EAAU,QAAQ,MAAO,EAAE,CAAC,UAAU,mBAAmBC,CAAW,CAAC,EACjF,CAMO,SAASC,EAAmBC,EAAyC,CAC1E,IAAMC,EAASD,EAAK,cAAgB,OAC9BE,EAAcF,EAAK,gBAAkB,IAAM,IAAI,gBAC/CG,EAAeH,EAAK,kBAAoB,IAAMA,EAAK,UAErDI,EAA2B,K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AM,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"]}
1
+ {"version":3,"sources":["../src/embed-host.ts"],"sourcesContent":["/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n * 6. host sends { type: 'crm:host-context', theme?, locale? } on the same port,\n * right after the bearer and again whenever {@link CrmEmbedHost.setContext} is called.\n * The first values also ride on the iframe URL (`?theme=` and `?locale=`), so the\n * frame paints in the right theme before the handshake finishes.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\n/** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */\nexport type CrmHostTheme = 'light' | 'dark' | 'system';\n\n/**\n * Look and language the host passes to the embedded CRM. Both are optional; an omitted\n * field leaves the CRM's own behaviour unchanged. The CRM applies them for the embed only\n * and never saves them to the user's account.\n */\nexport interface CrmHostContext {\n theme?: CrmHostTheme;\n /** BCP 47 language tag, e.g. \"en\" or \"zh-CN\". */\n locale?: string;\n}\n\n/** The message the host posts on the channel port to update {@link CrmHostContext}. */\nexport interface CrmHostContextMessage extends CrmHostContext {\n type: 'crm:host-context';\n}\n\nconst HOST_THEMES: readonly string[] = ['light', 'dark', 'system'];\nconst BCP47_LIKE = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;\n\n/**\n * Keeps only values the CRM understands: a known theme and a well-formed language tag.\n * Anything else is dropped, so a bad value can never reach the iframe URL or the message.\n */\nexport function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext {\n const out: CrmHostContext = {};\n if (ctx?.theme && HOST_THEMES.includes(ctx.theme)) out.theme = ctx.theme;\n if (typeof ctx?.locale === 'string' && BCP47_LIKE.test(ctx.locale.trim())) out.locale = ctx.locale.trim();\n return out;\n}\n\n/** `theme` and `locale` as URL query pairs (e.g. `[\"theme=dark\", \"locale=zh-CN\"]`). */\nexport function hostContextQuery(ctx: CrmHostContext | undefined): string[] {\n const clean = normalizeHostContext(ctx);\n const pairs: string[] = [];\n if (clean.theme) pairs.push(`theme=${encodeURIComponent(clean.theme)}`);\n if (clean.locale) pairs.push(`locale=${encodeURIComponent(clean.locale)}`);\n return pairs;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /** Initial theme/locale, sent to the CRM once the channel is up. Change it with `setContext()`. */\n hostContext?: CrmHostContext;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /**\n * Update the theme and/or language of the embedded CRM. Sent over the established\n * channel only, never broadcast with a wildcard origin. Fields you leave out keep\n * their last value; before the channel is up the latest values go out on connect.\n */\n setContext: (ctx: CrmHostContext) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n const result = body as Partial<CrmSessionResult>;\n // A malformed 2xx (e.g. `{}`) would otherwise cast cleanly and later build an\n // `/embed/undefined` URL — fail at the boundary with a clear message instead.\n if (typeof result?.accessToken !== 'string' || typeof result?.workspaceId !== 'string') {\n throw new Error('CRM session response is missing accessToken/workspaceId');\n }\n return result as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n let context: CrmHostContext = normalizeHostContext(opts.hostContext);\n\n function sendContext(): void {\n if (!port || (context.theme === undefined && context.locale === undefined)) return;\n const msg: CrmHostContextMessage = { type: 'crm:host-context', ...context };\n port.postMessage(msg);\n }\n\n async function deliverBearer(): Promise<boolean> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n sendContext();\n return true;\n } catch (err) {\n opts.onError?.(err);\n return false;\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow). Only tell the\n // CRM the session refreshed once a fresh bearer was ACTUALLY delivered —\n // otherwise a failed re-mint leaves the iframe believing it's authenticated.\n void deliverBearer().then((ok) => {\n if (ok) port?.postMessage({ type: 'session-refreshed' });\n });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n setContext(ctx: CrmHostContext): void {\n context = { ...context, ...normalizeHostContext(ctx) };\n sendContext();\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"AAgDA,IAAMA,EAAiC,CAAC,QAAS,OAAQ,QAAQ,EAC3DC,EAAa,4CAMZ,SAASC,EAAqBC,EAAiD,CACpF,IAAMC,EAAsB,CAAC,EAC7B,OAAID,G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AK,CAAM,EAC9BF,EACA,CAACc,EAAQ,KAAK,CAChB,CACF,CAEA,SAASC,EAAgBC,EAA2B,CAC9Cb,GACAa,EAAM,SAAWnB,EAAK,OAAO,gBAC7B,CAACA,EAAK,mBAAqBmB,EAAM,SAAWnB,EAAK,WACjDb,EAAQgC,EAAM,IAAI,GAAGH,EAAe,EAC1C,CAEA,OAAAf,EAAO,iBAAiB,UAAWiB,CAAgC,EAE5D,CACL,SAASE,EAAoB,CAC3BhB,GAAM,YAAY,CAAE,KAAM,WAAY,KAAAgB,CAAK,CAAC,CAC9C,EACA,WAAWtC,EAA2B,CACpCyB,EAAU,CAAE,GAAGA,EAAS,GAAG1B,EAAqBC,CAAG,CAAE,EACrD0B,EAAY,CACd,EACA,SAAgB,CACdF,EAAW,GACXL,EAAO,oBAAoB,UAAWiB,CAAgC,EACtEd,GAAM,MAAM,EACZA,EAAO,IACT,CACF,CACF","names":["HOST_THEMES","BCP47_LIKE","normalizeHostContext","ctx","out","hostContextQuery","clean","pairs","isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","context","sendContext","msg","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path"]}
@@ -1,2 +1,2 @@
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});
1
+ "use strict";var I=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var ee=Object.prototype.hasOwnProperty;var te=(e,t)=>{for(var s in t)I(e,s,{get:t[s],enumerable:!0})},re=(e,t,s,l)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of X(t))!ee.call(e,r)&&r!==s&&I(e,r,{get:()=>t[r],enumerable:!(l=V(t,r))||l.enumerable});return e};var ne=e=>re(I({},"__esModule",{value:!0}),e);var de={};te(de,{CrmEmbed:()=>Q,crmSession:()=>_,default:()=>me});module.exports=ne(de);var n=require("react");var oe=["light","dark","system"],se=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;function L(e){let t={};return e?.theme&&oe.includes(e.theme)&&(t.theme=e.theme),typeof e?.locale=="string"&&se.test(e.locale.trim())&&(t.locale=e.locale.trim()),t}function F(e){let t=L(e),s=[];return t.theme&&s.push(`theme=${encodeURIComponent(t.theme)}`),t.locale&&s.push(`locale=${encodeURIComponent(t.locale)}`),s}function ie(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function _(e,t){return async()=>{let s=await fetch(e,{method:"POST",...t}),l=await s.json().catch(()=>({}));if(!s.ok){let g=l?.error;throw new Error(g?`CRM session failed: ${g}`:`CRM session failed (HTTP ${s.status})`)}let r=l;if(typeof r?.accessToken!="string"||typeof r?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return r}}function j(e,t){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(t)}`}function q(e){let t=e.windowTarget??window,s=e.createChannel??(()=>new MessageChannel),l=e.devAllowAnyOrigin?"*":e.crmOrigin,r=null,g="",h=!1,C=L(e.hostContext);function f(){if(!r||C.theme===void 0&&C.locale===void 0)return;let o={type:"crm:host-context",...C};r.postMessage(o)}async function p(){try{let o=await e.getBearer();return r?.postMessage({type:"auth-tokens",accessToken:o.accessToken,refreshToken:o.refreshToken??""}),f(),!0}catch(o){return e.onError?.(o),!1}}function y(o){let i=o.data;if(i)if(i.type==="channel-ack"){if(i.nonce!==g)return;p()}else i.type==="route-change"?e.onRouteChange?.(i.path):i.type==="resize"?e.onResize?.(i.height):i.type==="session-expired"&&p().then(v=>{v&&r?.postMessage({type:"session-refreshed"})})}function E(){r?.close();let o=s();r=o.port1,g=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,r.onmessage=y,r.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:g},l,[o.port2])}function R(o){h||o.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&o.origin!==e.crmOrigin||ie(o.data)&&E())}return t.addEventListener("message",R),{navigate(o){r?.postMessage({type:"navigate",path:o})},setContext(o){C={...C,...L(o)},f()},dispose(){h=!0,t.removeEventListener("message",R),r?.close(),r=null}}}var c=require("react/jsx-runtime");var ae={width:"100%",height:"100%",border:0};function O(e){return e instanceof Error?e:new Error(String(e))}function ce(){return(0,c.jsx)("div",{children:"Loading CRM\u2026"})}function le(e,t){return(0,c.jsxs)("div",{children:[(0,c.jsxs)("p",{children:["Couldn\u2019t load the CRM: ",e.message]}),(0,c.jsx)("button",{type:"button",onClick:t,children:"Try again"})]})}var Q=(0,n.forwardRef)(function(t,s){let{getSession:l,crmEmbedOrigin:r,className:g,style:h,title:C="CRM",onReady:f,onError:p,onRouteChange:y,hostProvidesNav:E,initialPath:R,theme:o,locale:i,renderLoading:v,renderError:A}=t,N=(0,n.useRef)(null),[b,B]=(0,n.useState)(null),[M,U]=(0,n.useState)(null),[T,x]=(0,n.useState)(null),[Z,K]=(0,n.useState)(0),w=(0,n.useRef)(null),H=(0,n.useRef)(null);(0,n.useImperativeHandle)(s,()=>({navigate:m=>{H.current?.navigate(m)}}),[]);let S=(0,n.useRef)(l),$=(0,n.useRef)(f),k=(0,n.useRef)(p),z=(0,n.useRef)(y);(0,n.useEffect)(()=>{S.current=l,$.current=f,k.current=p,z.current=y});let Y=(0,n.useRef)(R),P=(0,n.useRef)({theme:o,locale:i});P.current={theme:o,locale:i};let W=(0,n.useCallback)(()=>{w.current=null,x(null),B(null),U(null),K(m=>m+1)},[]);return(0,n.useEffect)(()=>{let m=!1;return(async()=>{try{let d=await S.current();if(m)return;w.current={accessToken:d.accessToken},U(d.workspaceId);let a=j(r,d.workspaceId),u=Y.current??"",D=[...E?["hostnav=1"]:[],...F(P.current)],G=u.includes("?")?"&":"?",J=a+u+(D.length>0?G+D.join("&"):"");B(J)}catch(d){if(m)return;let a=O(d);x(a),k.current?.(a)}})(),()=>{m=!0}},[r,E,Z]),(0,n.useEffect)(()=>{let m=N.current;if(!m||!b||!M)return;let d=null;try{d=q({iframe:m,crmOrigin:r,getBearer:async()=>{let a=w.current;return a?(w.current=null,a):{accessToken:(await S.current()).accessToken}},hostContext:P.current,onRouteChange:a=>{z.current?.(a)},onError:a=>{let u=O(a);x(u),k.current?.(u)}})}catch(a){let u=O(a);x(u),k.current?.(u);return}return H.current=d,$.current?.({workspaceId:M}),()=>{d?.dispose(),H.current=null}},[b,M,r]),(0,n.useEffect)(()=>{H.current?.setContext({theme:o,locale:i})},[o,i]),T?(0,c.jsx)(c.Fragment,{children:A?A(T,W):le(T,W)}):b?(0,c.jsx)("iframe",{ref:N,src:b,title:C,className:g,style:{...ae,...h}}):(0,c.jsx)(c.Fragment,{children:v?v():ce()})}),me=Q;0&&(module.exports={CrmEmbed,crmSession});
2
2
  //# sourceMappingURL=embed-react.cjs.map