@first-to-fly/crm-sdk 1.4.0 → 1.4.2

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
@@ -135,150 +135,242 @@ and **without a reverse proxy**. Your server obtains a short-lived CRM bearer (v
135
135
  of the two auth options below) and hands it to the iframe over a secure `MessageChannel`.
136
136
  Two modules do the heavy lifting: `embed-server` (Node/Bun) and `embed-host` (browser).
137
137
 
138
- ### Choosing a server auth approach
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 reference sections
140
+ > [that follow it](#server-the-exchange-reference) document the API and edge cases.
139
141
 
140
- | | Option A — API-key | Option B — Signed assertion |
141
- |---|---|---|
142
- | **Setup** | CRM team gives you `app_id` + `app_secret` | You generate an RS256/ES256 keypair; CRM team registers your JWKS URL |
143
- | **Shared secret** | `app_secret` on your server | None — private key stays on your server |
144
- | **Peer dep** | None | `jose` (`npm i jose`) |
145
- | **Helper** | `createEmbedSessionWithKey` | `createEmbedSession` (or `mintCrmAssertion` + `exchangeAssertion`) |
142
+ ### Integration walkthrough — new system, start to finish
146
143
 
147
- ### How it works (Option A — API-key)
144
+ The whole integration is **three moving parts**:
148
145
 
149
146
  ```
150
- [your server] [browser] [CRM]
151
- createEmbedSessionWithKey(user) ─exchange─▶ CRM bearer
152
- │
153
- createCrmEmbedHost({ iframe, getBearer })
154
- │ ready → channel-init → ack
155
- └──────── auth-tokens ─────────▶ CRM iframe loads
147
+ 1. YOUR SERVER exchanges app_id + app_secret + {your user} → a short-lived CRM bearer
148
+ 2. YOUR FRONTEND renders <CrmEmbed> (or embed-host) which loads the CRM iframe with that bearer
149
+ 3. (optional) YOUR SERVER calls CRM REST APIs with the same bearer
156
150
  ```
157
151
 
158
- ### How it works (Option B — Signed assertion)
152
+ You never touch cookies, JWTs, or a reverse proxy. The SDK does the token handshake.
153
+
154
+ #### Step 0 — Get your credentials (one-time)
155
+
156
+ Ask the CRM team for four things and put them in your environment:
157
+
158
+ | Value | Example env var | What it is |
159
+ |---|---|---|
160
+ | App ID | `CRM_APP_ID` | Public identifier for your integration (`emb_…`) |
161
+ | App secret | `CRM_APP_SECRET` | **Server-only** secret — never ship to the browser (`sk_…`) |
162
+ | Exchange base URL | `CRM_BASE_URL` | CRM API origin your server calls, e.g. `https://api.crm.example.com` |
163
+ | Embed origin | `CRM_EMBED_URL` | CRM app origin the iframe loads, e.g. `https://crm.example.com` |
164
+
165
+ A CRM admin binds your app to exactly one CRM **workspace** — that's the data your
166
+ users will see. Your users are matched into that workspace **by verified email**, so
167
+ the `email` you send in Step 1 must be one the CRM trusts.
168
+
169
+ #### Step 1 — Add a session endpoint on your server
170
+
171
+ This is the only server code you need — a POST endpoint that swaps your credentials +
172
+ the signed-in user for a short-lived CRM bearer. **Keep `app_secret` on the server** —
173
+ this endpoint is the trust boundary; authenticate it as you would any of your own APIs.
174
+
175
+ `createCrmSessionHandler` gives you a ready-made Web `(Request) => Response` handler
176
+ (Next.js route handlers, Hono, Bun.serve, Deno, Cloudflare Workers). You supply an
177
+ `authenticate` callback that returns the signed-in user; it runs the exchange and maps
178
+ errors to HTTP responses for you:
179
+
180
+ ```typescript
181
+ // app/api/crm/session/route.ts (Next.js) — or any Web-standard handler
182
+ import { createCrmSessionHandler } from '@first-to-fly/crm-sdk/embed-server';
159
183
 
184
+ export const POST = createCrmSessionHandler({
185
+ appId: process.env.CRM_APP_ID!,
186
+ appSecret: process.env.CRM_APP_SECRET!,
187
+ crmBaseUrl: process.env.CRM_BASE_URL!,
188
+ authenticate: async (req) => {
189
+ const user = await getMyUser(req); // your auth — throw to reject (→ 401)
190
+ return {
191
+ id: user.id, // stable id in YOUR system
192
+ email: user.email, // verified email — the CRM matches the user by this
193
+ role: 'member', // 'member' | 'admin' (CRM caps to the install's max role)
194
+ name: user.name, // optional
195
+ };
196
+ },
197
+ });
160
198
  ```
161
- [your server] [browser] [CRM]
162
- createEmbedSession(user) ─mint+exchange─▶ CRM bearer
163
- │
164
- createCrmEmbedHost({ iframe, getBearer })
165
- │ ready → channel-init → ack
166
- └──────── auth-tokens ─────────▶ CRM iframe loads
199
+
200
+ On Express/Koa (which don't use Web `Request`/`Response`), call
201
+ `createEmbedSessionWithKey` directly instead — see
202
+ [Server: the exchange](#server-the-exchange-reference).
203
+
204
+ #### Step 2 — Drop the CRM into your frontend
205
+
206
+ **React (recommended)** — one component; it handles the iframe, the MessageChannel
207
+ handshake, bearer refresh on expiry, and loading/error/retry. `crmSession('/api/crm/session')`
208
+ is a helper that POSTs to your Step 1 endpoint and returns the shape `<CrmEmbed>` wants:
209
+
210
+ ```tsx
211
+ import { CrmEmbed, crmSession } from '@first-to-fly/crm-sdk/embed-react';
212
+
213
+ export function CrmPage() {
214
+ return (
215
+ <div style={{ height: '100vh' }}>
216
+ <CrmEmbed
217
+ crmEmbedOrigin={import.meta.env.VITE_CRM_EMBED_URL} // the embed origin from Step 0
218
+ getSession={crmSession('/api/crm/session')}
219
+ />
220
+ </div>
221
+ );
222
+ }
167
223
  ```
168
224
 
169
- ---
225
+ `getSession()` returns `{ accessToken, workspaceId, expiresIn? }` — pass your own async
226
+ function if you need custom fetch options. The component sizes to its container, so give
227
+ the parent a real height.
228
+
229
+ **Not using React?** Use the low-level `embed-host` instead — see
230
+ [Browser: host the iframe](#browser-host-the-iframe-low-level).
170
231
 
171
- ### Option A: API-key auth (simpler, no keypair)
232
+ That's a working embed. Steps 3 and 4 are optional.
233
+
234
+ #### Step 3 — (Optional) Put CRM sections in YOUR navigation
235
+
236
+ By default the CRM shows its own in-iframe nav. If you'd rather drive it from your
237
+ own app shell, set `hostProvidesNav` (hides the CRM's nav) and steer it via the ref:
238
+
239
+ ```tsx
240
+ import { useRef } from 'react';
241
+ import { CrmEmbed, crmSession, type CrmEmbedHandle } from '@first-to-fly/crm-sdk/embed-react';
242
+
243
+ function Shell() {
244
+ const crm = useRef<CrmEmbedHandle>(null);
245
+ return (
246
+ <>
247
+ <nav>
248
+ <button onClick={() => crm.current?.navigate('/')}>Dashboard</button>
249
+ <button onClick={() => crm.current?.navigate('/contacts')}>Contacts</button>
250
+ <button onClick={() => crm.current?.navigate('/leads')}>Leads</button>
251
+ </nav>
252
+ <CrmEmbed
253
+ ref={crm}
254
+ crmEmbedOrigin={import.meta.env.VITE_CRM_EMBED_URL}
255
+ getSession={crmSession('/api/crm/session')}
256
+ hostProvidesNav // hide the CRM's own nav
257
+ initialPath="/contacts" // deep-link on first load
258
+ onRouteChange={(path) => console.log('CRM at', path)} // keep your nav in sync
259
+ />
260
+ </>
261
+ );
262
+ }
263
+ ```
172
264
 
173
- #### One-time setup
265
+ `navigate()` never reloads the iframe (it's a postMessage), so switching sections is
266
+ instant and preserves CRM state. See [Host-driven navigation](#host-driven-navigation).
174
267
 
175
- 1. Ask the CRM team to register your app. They give you an **`app_id`** and **`app_secret`**.
176
- An admin in the CRM binds your app to a CRM workspace.
177
- 2. Ask the CRM team for their **exchange base URL** and **embed origin**.
268
+ #### Step 4 — (Optional) Call CRM APIs from your server
178
269
 
179
- #### Server: exchange credentials for a bearer
270
+ The same bearer from Step 1 works against the typed REST client — handy for syncing
271
+ data or building your own screens. See [Calling CRM APIs from your backend](#calling-crm-apis-from-your-backend):
180
272
 
181
273
  ```typescript
182
- import { createEmbedSessionWithKey } from '@first-to-fly/crm-sdk/embed-server';
274
+ import { createCrmApiClient } from '@first-to-fly/crm-sdk/api';
183
275
 
184
- // Endpoint your frontend calls to (re)obtain a CRM bearer:
185
- app.post('/api/crm/session', async (req, res) => {
186
- const user = req.user; // your authenticated user
187
- const session = await createEmbedSessionWithKey(
188
- {
189
- appId: process.env.CRM_APP_ID!,
190
- appSecret: process.env.CRM_APP_SECRET!,
191
- user: {
192
- id: user.id, // stable id in YOUR system
193
- email: user.email,
194
- role: 'member', // 'member' | 'admin'
195
- name: user.name, // optional
196
- avatar_url: user.avatar, // optional
197
- },
198
- },
199
- { crmBaseUrl: process.env.CRM_BASE_URL! }, // e.g. https://api.crm.example.com
200
- );
201
- // { accessToken, expiresIn, workspaceId, user, role }
202
- res.json(session);
276
+ const crm = createCrmApiClient({
277
+ crmBaseUrl: process.env.CRM_BASE_URL!,
278
+ accessToken: session.accessToken, // from createEmbedSessionWithKey
203
279
  });
280
+ const { items } = await crm.contacts.list({ page: 1, pageSize: 25 });
204
281
  ```
205
282
 
206
- A rejected exchange throws `CrmExchangeError` with `.status` and `.code`
207
- (e.g. `SUBAPP_DISABLED`, `IDENTITY_CONFLICT`).
283
+ #### Environment checklist
284
+
285
+ | Where | Variable | Notes |
286
+ |---|---|---|
287
+ | Server | `CRM_APP_ID` | from Step 0 |
288
+ | Server | `CRM_APP_SECRET` | **server-only** — never expose to the browser |
289
+ | Server | `CRM_BASE_URL` | exchange/API origin (`https://api.crm.…`) |
290
+ | Frontend | `CRM_EMBED_URL` / `VITE_CRM_EMBED_URL` | embed origin (`https://crm.…`), matches the iframe origin exactly |
291
+
292
+ #### Troubleshooting
293
+
294
+ | Symptom | Likely cause | Fix |
295
+ |---|---|---|
296
+ | Session endpoint 4xx, `SUBAPP_DISABLED` | your app isn't enabled / not bound to a workspace | ask the CRM admin to enable + bind it |
297
+ | Session endpoint 4xx, `IDENTITY_CONFLICT` | the email maps to a different existing CRM user | send a verified email that matches (or none exists yet, so it links) |
298
+ | Iframe blank / refuses to load | `crmEmbedOrigin` mismatch, or your origin isn't in the CRM's `frame-ancestors` | match the origin exactly; ask the CRM team to allowlist your origin |
299
+ | Iframe loads then goes blank after a while | bearer expired and `getSession` didn't return a fresh one | make `getSession` re-call your endpoint every time (don't cache) |
300
+ | `navigate()` seems to do nothing | called before the handshake finished | it no-ops until wired — it'll work once the iframe is ready; wire it via the `ref` |
301
+
302
+ #### Security model (worth knowing)
303
+
304
+ - The bearer is **short-lived** and **scoped to one workspace** (the one bound to your
305
+ app). An embed token is pinned to that workspace — it can't be pivoted to another.
306
+ - Users are identified by **verified email** and just-in-time linked into the workspace;
307
+ the `role` you request is **capped** by the install's max role.
308
+ - `app_secret` is the only long-lived secret. It stays on your server behind the Step 1
309
+ endpoint — the browser only ever sees short-lived bearers.
208
310
 
209
311
  ---
210
312
 
211
- ### Option B: Signed-assertion auth (zero shared-secret)
313
+ ### How it works
212
314
 
213
- > **Requires an assertion-capable CRM endpoint.** These helpers are retained for
214
- > partners integrating against a CRM that still exposes the RS256/JWKS assertion
215
- > exchange. The First-to-Fly hosted CRM now uses **Option A (API-key)** only, so
216
- > use Option A there. Confirm with the CRM team which flow their deployment supports
217
- > before choosing Option B.
315
+ Auth is a single credential exchange — no cookies, no reverse proxy, no keypair:
218
316
 
219
- #### One-time setup
317
+ ```
318
+ [your server] [browser] [CRM]
319
+ createEmbedSessionWithKey(user) ─exchange─▶ CRM bearer
320
+ │
321
+ createCrmEmbedHost({ iframe, getBearer })
322
+ │ ready → channel-init → ack
323
+ └──────── auth-tokens ─────────▶ CRM iframe loads
324
+ ```
220
325
 
221
- 1. Generate an RS256 (or ES256) key pair. Keep the private key on your server.
222
- 2. Serve your **public JWKS** at a public `https` URL (see `getCrmEmbedJwks` below).
223
- 3. Give the CRM team your **`client_id`** (issuer) and **JWKS URL**. They register your
224
- app and enable it. An admin in the CRM binds your **`org_id`** to a CRM workspace.
225
- 4. Ask the CRM team for their **exchange base URL** and **embed origin**.
326
+ ### Server: the exchange (reference)
226
327
 
227
- #### Server: mint + exchange
328
+ The [walkthrough](#step-1--add-a-session-endpoint-on-your-server) covers the fast path
329
+ with `createCrmSessionHandler`. Under the hood it calls `createEmbedSessionWithKey`,
330
+ which you can also use directly if you wire the endpoint yourself:
228
331
 
229
332
  ```typescript
230
- import { createEmbedSession, getCrmEmbedJwks } from '@first-to-fly/crm-sdk/embed-server';
231
-
232
- const config = {
233
- iss: process.env.CRM_CLIENT_ID!, // == the client_id the CRM registered
234
- privateKeyPem: process.env.CRM_PRIVATE_KEY_PEM!,
235
- publicKeyPem: process.env.CRM_PUBLIC_KEY_PEM!,
236
- // alg: 'RS256' (default) or 'ES256'
237
- };
333
+ import { createEmbedSessionWithKey } from '@first-to-fly/crm-sdk/embed-server';
238
334
 
239
335
  // Endpoint your frontend calls to (re)obtain a CRM bearer:
240
- app.post('/api/crm/session', async (req, res) => {
336
+ app.post('/api/crm/session', requireAuth, async (req, res) => {
241
337
  const user = req.user; // your authenticated user
242
- const session = await createEmbedSession(
338
+ const session = await createEmbedSessionWithKey(
243
339
  {
244
- sub: user.id, // stable id in YOUR system
245
- email: user.email,
246
- requestedRole: 'admin', // CRM clamps to the install's max_role
247
- orgId: user.orgId, // CRM resolves the workspace from this
248
- fullName: user.name, // optional
249
- avatarUrl: user.avatar, // optional
340
+ appId: process.env.CRM_APP_ID!,
341
+ appSecret: process.env.CRM_APP_SECRET!,
342
+ user: {
343
+ id: user.id, // stable id in YOUR system
344
+ email: user.email, // verified email — the CRM matches the user by this
345
+ role: 'member', // 'member' | 'admin' (CRM caps to the install's max role)
346
+ name: user.name, // optional
347
+ avatar_url: user.avatar, // optional
348
+ },
250
349
  },
251
- config,
252
350
  { crmBaseUrl: process.env.CRM_BASE_URL! }, // e.g. https://api.crm.example.com
253
351
  );
254
352
  // { accessToken, expiresIn, workspaceId, user, role }
255
353
  res.json(session);
256
354
  });
257
-
258
- // Publish your public JWKS so the CRM can verify your assertions:
259
- app.get('/crm-embed/jwks', async (_req, res) => res.json(await getCrmEmbedJwks(config)));
260
355
  ```
261
356
 
262
- Prefer to split minting and exchange? Use `mintCrmAssertion(input, config)` and
263
- `exchangeAssertion(assertion, { crmBaseUrl })` directly. A rejected exchange throws
264
- `CrmExchangeError` with `.status` and `.code` (e.g. `IDENTITY_CONFLICT`,
265
- `WORKSPACE_NOT_OWNED`).
266
-
267
- Requires `jose` (peer dependency): `npm i jose`.
357
+ A rejected exchange throws `CrmExchangeError` with `.status` and `.code`
358
+ (e.g. `SUBAPP_DISABLED`, `IDENTITY_CONFLICT`). `createCrmSessionHandler` maps that to
359
+ the HTTP response for you.
268
360
 
269
361
  ---
270
362
 
271
- ### Browser: host the iframe (same for both options)
363
+ ### Browser: host the iframe (low-level)
364
+
365
+ `<CrmEmbed>` (below) is the easy path for React. If you're not on React, wire the host
366
+ yourself with `embed-host`. The `crmSession()` helper turns your `/session` endpoint
367
+ into the `getSession`/`getBearer` callbacks:
272
368
 
273
369
  ```typescript
274
- import { createCrmEmbedHost, buildCrmEmbedUrl } from '@first-to-fly/crm-sdk/embed-host';
370
+ import { createCrmEmbedHost, buildCrmEmbedUrl, crmSession } from '@first-to-fly/crm-sdk/embed-host';
275
371
 
276
372
  const CRM_ORIGIN = 'https://app.crm.example.com';
277
-
278
- async function getSession() {
279
- const res = await fetch('/api/crm/session', { method: 'POST' });
280
- return res.json(); // { accessToken, workspaceId, ... }
281
- }
373
+ const getSession = crmSession('/api/crm/session'); // POSTs, returns { accessToken, workspaceId }
282
374
 
283
375
  const { workspaceId } = await getSession();
284
376
  const iframe = document.querySelector('#crm') as HTMLIFrameElement;
@@ -302,11 +394,9 @@ host.dispose();
302
394
  ### Requirements & gotchas
303
395
 
304
396
  - `getBearer` is called on connect **and** whenever the CRM's session expires — always
305
- return a fresh bearer (call your `/session` endpoint again).
397
+ return a fresh bearer (call your `/session` endpoint again). `crmSession()` does this.
306
398
  - `crmOrigin` must exactly match the iframe's origin, and the CRM must allow your origin
307
399
  in its `frame-ancestors` (the CRM team configures this).
308
- - Assertions (Option B) are single-use and live ≤120s — always mint fresh; never cache one.
309
- - `jose` is only required for Option B (`embed-server` assertion path): `npm i jose`.
310
400
 
311
401
  ### React embed component
312
402
 
@@ -321,18 +411,56 @@ npm install @first-to-fly/crm-sdk react
321
411
  ```
322
412
 
323
413
  ```tsx
324
- import { CrmEmbed } from '@first-to-fly/crm-sdk/embed-react';
414
+ import { CrmEmbed, crmSession } from '@first-to-fly/crm-sdk/embed-react';
325
415
 
326
416
  <CrmEmbed
327
417
  crmEmbedOrigin="https://crm.example.com"
328
- getSession={async () => (await fetch('/api/crm/session', { method: 'POST' })).json()}
418
+ getSession={crmSession('/api/crm/session')}
329
419
  />
330
420
  ```
331
421
 
332
422
  `getSession()` must resolve to `{ accessToken, workspaceId, expiresIn? }` —
333
- typically from your own backend endpoint running `createEmbedSessionWithKey`.
334
- Optional props: `className`, `style`, `title`, `onReady`, `onError`,
335
- `renderLoading`, `renderError`.
423
+ typically from your own backend endpoint running `createCrmSessionHandler` /
424
+ `createEmbedSessionWithKey`. The `crmSession(url)` helper wraps the fetch; pass your
425
+ own async function if you need custom fetch options. Optional props: `className`,
426
+ `style`, `title`, `onReady`, `onError`, `renderLoading`, `renderError`.
427
+
428
+ #### Host-driven navigation
429
+
430
+ The host (e.g. an app shell) can drive the embedded CRM's section navigation and
431
+ supply its own chrome:
432
+
433
+ - **`ref` → `navigate(path)`** — imperatively navigate the embedded CRM without
434
+ reloading the iframe (e.g. from your own nav). No-ops safely before the iframe
435
+ is wired.
436
+ - **`onRouteChange?(path)`** — fires when the CRM navigates internally; use it to
437
+ keep a host-supplied nav in sync.
438
+ - **`hostProvidesNav?`** — when `true`, the CRM **hides its own in-iframe nav**
439
+ (the host supplies it), signalled via `?hostnav=1` on the iframe URL.
440
+ - **`initialPath?`** — a CRM sub-path (e.g. `/contacts`) to deep-link on **first
441
+ load only**; later navigation goes through the ref's `navigate()`.
442
+
443
+ ```tsx
444
+ import { useRef } from 'react';
445
+ import { CrmEmbed, crmSession, type CrmEmbedHandle } from '@first-to-fly/crm-sdk/embed-react';
446
+
447
+ function Shell() {
448
+ const crm = useRef<CrmEmbedHandle>(null);
449
+ return (
450
+ <>
451
+ <button onClick={() => crm.current?.navigate('/contacts')}>Contacts</button>
452
+ <CrmEmbed
453
+ ref={crm}
454
+ crmEmbedOrigin="https://crm.example.com"
455
+ getSession={crmSession('/api/crm/session')}
456
+ hostProvidesNav
457
+ initialPath="/contacts"
458
+ onRouteChange={(path) => console.log('CRM at', path)}
459
+ />
460
+ </>
461
+ );
462
+ }
463
+ ```
336
464
 
337
465
  React is an **optional peer dependency** — only pull in this entry if you use
338
466
  React. The low-level `embed-host` remains available for non-React consumers.
@@ -1,2 +1,2 @@
1
- "use strict";var d=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var p=Object.getOwnPropertyNames;var f=Object.prototype.hasOwnProperty;var y=(e,t)=>{for(var i in t)d(e,i,{get:t[i],enumerable:!0})},v=(e,t,i,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of p(t))!f.call(e,n)&&n!==i&&d(e,n,{get:()=>t[n],enumerable:!(o=u(t,n))||o.enumerable});return e};var C=e=>v(d({},"__esModule",{value:!0}),e);var b={};y(b,{buildCrmEmbedUrl:()=>w,createCrmEmbedHost:()=>E});module.exports=C(b);function M(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function w(e,t){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(t)}`}function E(e){let t=e.windowTarget??window,i=e.createChannel??(()=>new MessageChannel),o=e.devAllowAnyOrigin?"*":e.crmOrigin,n=null,a="",c=!1;async function g(){try{let r=await e.getBearer();n?.postMessage({type:"auth-tokens",accessToken:r.accessToken,refreshToken:r.refreshToken??""})}catch(r){e.onError?.(r)}}function l(r){let s=r.data;if(s)if(s.type==="channel-ack"){if(s.nonce!==a)return;g()}else s.type==="route-change"?e.onRouteChange?.(s.path):s.type==="resize"?e.onResize?.(s.height):s.type==="session-expired"&&(g(),n?.postMessage({type:"session-refreshed"}))}function h(){n?.close();let r=i();n=r.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,[r.port2])}function m(r){c||r.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&r.origin!==e.crmOrigin||M(r.data)&&h())}return t.addEventListener("message",m),{navigate(r){n?.postMessage({type:"navigate",path:r})},dispose(){c=!0,t.removeEventListener("message",m),n?.close(),n=null}}}0&&(module.exports={buildCrmEmbedUrl,createCrmEmbedHost});
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
@@ -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 assertion exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSession() (see ./embed-server).\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n\n async function deliverBearer(): Promise<void> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n } catch (err) {\n opts.onError?.(err);\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow).\n void deliverBearer();\n port?.postMessage({ type: 'session-refreshed' });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sBAAAE,EAAA,uBAAAC,IAAA,eAAAC,EAAAJ,GAsEA,SAASK,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CASO,SAASJ,EAAiBK,EAAmBC,EAA6B,CAC/E,MAAO,GAAGD,EAAU,QAAQ,MAAO,EAAE,CAAC,UAAU,mBAAmBC,CAAW,CAAC,EACjF,CAMO,SAASL,EAAmBM,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,IAAMd,EAAOc,EAAE,KACf,GAAKd,EACL,GAAIA,EAAK,OAAS,cAAe,CAC/B,GAAIA,EAAK,QAAUQ,EAAO,OACrBE,EAAc,CACrB,MAAWV,EAAK,OAAS,eACvBG,EAAK,gBAAgBH,EAAK,IAAI,EACrBA,EAAK,OAAS,SACvBG,EAAK,WAAWH,EAAK,MAAM,EAClBA,EAAK,OAAS,oBAElBU,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,WACjDJ,EAAQmB,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","__toCommonJS","isReady","data","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,OAAOA,CACT,CACF,CASO,SAASX,EAAiBY,EAAmBC,EAA6B,CAC/E,MAAO,GAAGD,EAAU,QAAQ,MAAO,EAAE,CAAC,UAAU,mBAAmBC,CAAW,CAAC,EACjF,CAMO,SAASZ,EAAmBa,EAAyC,CAC1E,IAAMC,EAASD,EAAK,cAAgB,OAC9BE,EAAcF,EAAK,gBAAkB,IAAM,IAAI,gBAC/CG,EAAeH,EAAK,kBAAoB,IAAMA,EAAK,UAErDI,EAA2B,KAC3BC,EAAQ,GACRC,EAAW,GAEf,eAAeC,GAAkC,CAC/C,GAAI,CACF,IAAMC,EAAS,MAAMR,EAAK,UAAU,EACpC,OAAAI,GAAM,YAAY,CAChB,KAAM,cACN,YAAaI,EAAO,YACpB,aAAcA,EAAO,cAAgB,EACvC,CAAC,EACM,EACT,OAASC,EAAK,CACZ,OAAAT,EAAK,UAAUS,CAAG,EACX,EACT,CACF,CAEA,SAASC,EAAcC,EAAqC,CAC1D,IAAMpB,EAAOoB,EAAE,KACf,GAAKpB,EACL,GAAIA,EAAK,OAAS,cAAe,CAC/B,GAAIA,EAAK,QAAUc,EAAO,OACrBE,EAAc,CACrB,MAAWhB,EAAK,OAAS,eACvBS,EAAK,gBAAgBT,EAAK,IAAI,EACrBA,EAAK,OAAS,SACvBS,EAAK,WAAWT,EAAK,MAAM,EAClBA,EAAK,OAAS,mBAIlBgB,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"]}
@@ -16,7 +16,7 @@
16
16
  *
17
17
  * @packageDocumentation
18
18
  */
19
- /** A CRM bearer (from the assertion exchange). refreshToken is unused today. */
19
+ /** A CRM bearer (from the credential exchange). refreshToken is unused today. */
20
20
  interface CrmBearer {
21
21
  accessToken: string;
22
22
  refreshToken?: string;
@@ -32,7 +32,8 @@ interface CrmEmbedHostOptions {
32
32
  /**
33
33
  * Returns a fresh CRM bearer. Called once on connect and again whenever the
34
34
  * CRM reports its session expired. Typically calls your own backend endpoint
35
- * that runs createEmbedSession() (see ./embed-server).
35
+ * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}
36
+ * helper wraps that fetch for you.
36
37
  */
37
38
  getBearer: () => Promise<CrmBearer>;
38
39
  /** Called when the CRM navigates internally (e.g. "/contacts"). */
@@ -57,6 +58,23 @@ interface CrmEmbedHost {
57
58
  /** Tear down the channel and listeners. Call on unmount. */
58
59
  dispose: () => void;
59
60
  }
61
+ /** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */
62
+ interface CrmSessionResult {
63
+ accessToken: string;
64
+ workspaceId: string;
65
+ expiresIn?: number;
66
+ }
67
+ /**
68
+ * Build a `getSession()` that POSTs to your own session endpoint and returns
69
+ * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`
70
+ * on the server, so you don't hand-write the fetch/parse.
71
+ *
72
+ * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />
73
+ *
74
+ * On a non-2xx response it throws an Error carrying the server's `error` code.
75
+ * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).
76
+ */
77
+ declare function crmSession(url: string, init?: RequestInit): () => Promise<CrmSessionResult>;
60
78
  /**
61
79
  * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,
62
80
  * so the workspaceId segment is only a routing hint.
@@ -71,4 +89,4 @@ declare function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): strin
71
89
  */
72
90
  declare function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost;
73
91
 
74
- export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, buildCrmEmbedUrl, createCrmEmbedHost };
92
+ export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, type CrmSessionResult, buildCrmEmbedUrl, createCrmEmbedHost, crmSession };
@@ -16,7 +16,7 @@
16
16
  *
17
17
  * @packageDocumentation
18
18
  */
19
- /** A CRM bearer (from the assertion exchange). refreshToken is unused today. */
19
+ /** A CRM bearer (from the credential exchange). refreshToken is unused today. */
20
20
  interface CrmBearer {
21
21
  accessToken: string;
22
22
  refreshToken?: string;
@@ -32,7 +32,8 @@ interface CrmEmbedHostOptions {
32
32
  /**
33
33
  * Returns a fresh CRM bearer. Called once on connect and again whenever the
34
34
  * CRM reports its session expired. Typically calls your own backend endpoint
35
- * that runs createEmbedSession() (see ./embed-server).
35
+ * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}
36
+ * helper wraps that fetch for you.
36
37
  */
37
38
  getBearer: () => Promise<CrmBearer>;
38
39
  /** Called when the CRM navigates internally (e.g. "/contacts"). */
@@ -57,6 +58,23 @@ interface CrmEmbedHost {
57
58
  /** Tear down the channel and listeners. Call on unmount. */
58
59
  dispose: () => void;
59
60
  }
61
+ /** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */
62
+ interface CrmSessionResult {
63
+ accessToken: string;
64
+ workspaceId: string;
65
+ expiresIn?: number;
66
+ }
67
+ /**
68
+ * Build a `getSession()` that POSTs to your own session endpoint and returns
69
+ * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`
70
+ * on the server, so you don't hand-write the fetch/parse.
71
+ *
72
+ * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />
73
+ *
74
+ * On a non-2xx response it throws an Error carrying the server's `error` code.
75
+ * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).
76
+ */
77
+ declare function crmSession(url: string, init?: RequestInit): () => Promise<CrmSessionResult>;
60
78
  /**
61
79
  * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,
62
80
  * so the workspaceId segment is only a routing hint.
@@ -71,4 +89,4 @@ declare function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): strin
71
89
  */
72
90
  declare function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost;
73
91
 
74
- export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, buildCrmEmbedUrl, createCrmEmbedHost };
92
+ export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, type CrmSessionResult, buildCrmEmbedUrl, createCrmEmbedHost, crmSession };
@@ -1,2 +1,2 @@
1
- function h(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function u(e,s){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(s)}`}function p(e){let s=e.windowTarget??window,c=e.createChannel??(()=>new MessageChannel),g=e.devAllowAnyOrigin?"*":e.crmOrigin,r=null,i="",o=!1;async function a(){try{let n=await e.getBearer();r?.postMessage({type:"auth-tokens",accessToken:n.accessToken,refreshToken:n.refreshToken??""})}catch(n){e.onError?.(n)}}function m(n){let t=n.data;if(t)if(t.type==="channel-ack"){if(t.nonce!==i)return;a()}else t.type==="route-change"?e.onRouteChange?.(t.path):t.type==="resize"?e.onResize?.(t.height):t.type==="session-expired"&&(a(),r?.postMessage({type:"session-refreshed"}))}function l(){r?.close();let n=c();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},g,[n.port2])}function d(n){o||n.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&n.origin!==e.crmOrigin||h(n.data)&&l())}return s.addEventListener("message",d),{navigate(n){r?.postMessage({type:"navigate",path:n})},dispose(){o=!0,s.removeEventListener("message",d),r?.close(),r=null}}}export{u as buildCrmEmbedUrl,p as createCrmEmbedHost};
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