@first-to-fly/crm-sdk 1.3.0 → 1.4.1
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 +257 -100
- package/dist/embed-host.cjs +1 -1
- package/dist/embed-host.cjs.map +1 -1
- package/dist/embed-host.d.cts +21 -3
- package/dist/embed-host.d.ts +21 -3
- package/dist/embed-host.js +1 -1
- package/dist/embed-host.js.map +1 -1
- package/dist/embed-react.cjs +2 -0
- package/dist/embed-react.cjs.map +1 -0
- package/dist/embed-react.d.cts +94 -0
- package/dist/embed-react.d.ts +94 -0
- package/dist/embed-react.js +2 -0
- package/dist/embed-react.js.map +1 -0
- package/dist/embed-server.cjs +1 -1
- package/dist/embed-server.cjs.map +1 -1
- package/dist/embed-server.d.cts +58 -80
- package/dist/embed-server.d.ts +58 -80
- package/dist/embed-server.js +1 -1
- package/dist/embed-server.js.map +1 -1
- package/package.json +19 -7
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
|
-
|
|
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](#choosing-a-server-auth-approach)
|
|
140
|
+
> that follow it document every option and edge case.
|
|
139
141
|
|
|
140
|
-
|
|
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
|
-
|
|
144
|
+
The whole integration is **three moving parts**:
|
|
148
145
|
|
|
149
146
|
```
|
|
150
|
-
|
|
151
|
-
|
|
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
|
-
|
|
152
|
+
You never touch cookies, JWTs, or a reverse proxy. The SDK does the token handshake.
|
|
159
153
|
|
|
160
|
-
|
|
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
|
|
167
|
-
```
|
|
154
|
+
#### Step 0 — Get your credentials (one-time)
|
|
168
155
|
|
|
169
|
-
|
|
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` |
|
|
170
164
|
|
|
171
|
-
|
|
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.
|
|
172
168
|
|
|
173
|
-
####
|
|
169
|
+
#### Step 1 — Add a session endpoint on your server
|
|
174
170
|
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
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.
|
|
178
174
|
|
|
179
|
-
|
|
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:
|
|
180
179
|
|
|
181
180
|
```typescript
|
|
182
|
-
|
|
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';
|
|
183
183
|
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
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
|
+
});
|
|
198
|
+
```
|
|
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>
|
|
200
221
|
);
|
|
201
|
-
|
|
202
|
-
|
|
222
|
+
}
|
|
223
|
+
```
|
|
224
|
+
|
|
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).
|
|
231
|
+
|
|
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
|
+
```
|
|
264
|
+
|
|
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).
|
|
267
|
+
|
|
268
|
+
#### Step 4 — (Optional) Call CRM APIs from your server
|
|
269
|
+
|
|
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):
|
|
272
|
+
|
|
273
|
+
```typescript
|
|
274
|
+
import { createCrmApiClient } from '@first-to-fly/crm-sdk/api';
|
|
275
|
+
|
|
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
|
-
|
|
207
|
-
|
|
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
|
-
###
|
|
313
|
+
### How it works
|
|
212
314
|
|
|
213
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 {
|
|
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
|
|
338
|
+
const session = await createEmbedSessionWithKey(
|
|
243
339
|
{
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
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
|
-
|
|
263
|
-
|
|
264
|
-
|
|
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 (
|
|
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,76 @@ 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
|
-
|
|
309
|
-
|
|
400
|
+
|
|
401
|
+
### React embed component
|
|
402
|
+
|
|
403
|
+
If you use React, `@first-to-fly/crm-sdk/embed-react` wraps all of the above
|
|
404
|
+
(iframe, MessageChannel handshake, bearer refresh on expiry, and
|
|
405
|
+
loading/error/retry states) into a single drop-in `<CrmEmbed>` component. You
|
|
406
|
+
just supply `getSession` (returns the CRM bearer + the workspace to embed) and
|
|
407
|
+
the CRM embed origin.
|
|
408
|
+
|
|
409
|
+
```bash
|
|
410
|
+
npm install @first-to-fly/crm-sdk react
|
|
411
|
+
```
|
|
412
|
+
|
|
413
|
+
```tsx
|
|
414
|
+
import { CrmEmbed, crmSession } from '@first-to-fly/crm-sdk/embed-react';
|
|
415
|
+
|
|
416
|
+
<CrmEmbed
|
|
417
|
+
crmEmbedOrigin="https://crm.example.com"
|
|
418
|
+
getSession={crmSession('/api/crm/session')}
|
|
419
|
+
/>
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
`getSession()` must resolve to `{ accessToken, workspaceId, expiresIn? }` —
|
|
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
|
+
```
|
|
464
|
+
|
|
465
|
+
React is an **optional peer dependency** — only pull in this entry if you use
|
|
466
|
+
React. The low-level `embed-host` remains available for non-React consumers.
|
|
310
467
|
|
|
311
468
|
## Calling CRM APIs from your backend
|
|
312
469
|
|
package/dist/embed-host.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var c=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var p=Object.prototype.hasOwnProperty;var y=(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 f(r))!p.call(e,n)&&n!==t&&c(e,n,{get:()=>r[n],enumerable:!(o=h(r,n))||o.enumerable});return e};var C=e=>v(c({},"__esModule",{value:!0}),e);var k={};y(k,{buildCrmEmbedUrl:()=>b,createCrmEmbedHost:()=>E,crmSession:()=>M});module.exports=C(k);function w(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function M(e,r){return async()=>{let t=await fetch(e,{method:"POST",...r}),o=await t.json().catch(()=>({}));if(!t.ok){let n=o?.error;throw new Error(n?`CRM session failed: ${n}`:`CRM session failed (HTTP ${t.status})`)}return o}}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();n?.postMessage({type:"auth-tokens",accessToken:s.accessToken,refreshToken:s.refreshToken??""})}catch(s){e.onError?.(s)}}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(),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||w(s.data)&&u())}return r.addEventListener("message",m),{navigate(s){n?.postMessage({type:"navigate",path:s})},dispose(){d=!0,r.removeEventListener("message",m),n?.close(),n=null}}}0&&(module.exports={buildCrmEmbedUrl,createCrmEmbedHost,crmSession});
|
|
2
2
|
//# sourceMappingURL=embed-host.cjs.map
|
package/dist/embed-host.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/embed-host.ts"],"sourcesContent":["/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the
|
|
1
|
+
{"version":3,"sources":["../src/embed-host.ts"],"sourcesContent":["/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n return body as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n\n async function deliverBearer(): Promise<void> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n } catch (err) {\n opts.onError?.(err);\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow).\n void deliverBearer();\n port?.postMessage({ type: 'session-refreshed' });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sBAAAE,EAAA,uBAAAC,EAAA,eAAAC,IAAA,eAAAC,EAAAL,GAuEA,SAASM,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CAmBO,SAASH,EACdI,EACAC,EACiC,CACjC,MAAO,UAAuC,CAC5C,IAAMC,EAAM,MAAM,MAAMF,EAAK,CAAE,OAAQ,OAAQ,GAAGC,CAAK,CAAC,EAClDE,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,GAAI,CAACA,EAAI,GAAI,CACX,IAAME,EAAQD,GAA6B,MAC3C,MAAM,IAAI,MACRC,EAAO,uBAAuBA,CAAI,GAAK,4BAA4BF,EAAI,MAAM,GAC/E,CACF,CACA,OAAOC,CACT,CACF,CASO,SAAST,EAAiBW,EAAmBC,EAA6B,CAC/E,MAAO,GAAGD,EAAU,QAAQ,MAAO,EAAE,CAAC,UAAU,mBAAmBC,CAAW,CAAC,EACjF,CAMO,SAASX,EAAmBY,EAAyC,CAC1E,IAAMC,EAASD,EAAK,cAAgB,OAC9BE,EAAcF,EAAK,gBAAkB,IAAM,IAAI,gBAC/CG,EAAeH,EAAK,kBAAoB,IAAMA,EAAK,UAErDI,EAA2B,KAC3BC,EAAQ,GACRC,EAAW,GAEf,eAAeC,GAA+B,CAC5C,GAAI,CACF,IAAMC,EAAS,MAAMR,EAAK,UAAU,EACpCI,GAAM,YAAY,CAChB,KAAM,cACN,YAAaI,EAAO,YACpB,aAAcA,EAAO,cAAgB,EACvC,CAAC,CACH,OAASC,EAAK,CACZT,EAAK,UAAUS,CAAG,CACpB,CACF,CAEA,SAASC,EAAcC,EAAqC,CAC1D,IAAMnB,EAAOmB,EAAE,KACf,GAAKnB,EACL,GAAIA,EAAK,OAAS,cAAe,CAC/B,GAAIA,EAAK,QAAUa,EAAO,OACrBE,EAAc,CACrB,MAAWf,EAAK,OAAS,eACvBQ,EAAK,gBAAgBR,EAAK,IAAI,EACrBA,EAAK,OAAS,SACvBQ,EAAK,WAAWR,EAAK,MAAM,EAClBA,EAAK,OAAS,oBAElBe,EAAc,EACnBH,GAAM,YAAY,CAAE,KAAM,mBAAoB,CAAC,EAEnD,CAEA,SAASQ,GAAuB,CAC9BR,GAAM,MAAM,EACZ,IAAMS,EAAUX,EAAY,EAC5BE,EAAOS,EAAQ,MACfR,EAAQ,WAAW,QAAQ,aAAa,GAAK,KAAK,OAAO,KAAK,OAAO,CAAC,EAAE,MAAM,CAAC,CAAC,GAChFD,EAAK,UAAYM,EACjBN,EAAK,QAAQ,EACbJ,EAAK,OAAO,eAAe,YACzB,CAAE,KAAM,eAAgB,MAAAK,CAAM,EAC9BF,EACA,CAACU,EAAQ,KAAK,CAChB,CACF,CAEA,SAASC,EAAgBC,EAA2B,CAC9CT,GACAS,EAAM,SAAWf,EAAK,OAAO,gBAC7B,CAACA,EAAK,mBAAqBe,EAAM,SAAWf,EAAK,WACjDT,EAAQwB,EAAM,IAAI,GAAGH,EAAe,EAC1C,CAEA,OAAAX,EAAO,iBAAiB,UAAWa,CAAgC,EAE5D,CACL,SAASE,EAAoB,CAC3BZ,GAAM,YAAY,CAAE,KAAM,WAAY,KAAAY,CAAK,CAAC,CAC9C,EACA,SAAgB,CACdV,EAAW,GACXL,EAAO,oBAAoB,UAAWa,CAAgC,EACtEV,GAAM,MAAM,EACZA,EAAO,IACT,CACF,CACF","names":["embed_host_exports","__export","buildCrmEmbedUrl","createCrmEmbedHost","crmSession","__toCommonJS","isReady","data","url","init","res","body","code","crmOrigin","workspaceId","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","startHandshake","channel","onWindowMessage","event","path"]}
|
package/dist/embed-host.d.cts
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
*
|
|
17
17
|
* @packageDocumentation
|
|
18
18
|
*/
|
|
19
|
-
/** A CRM bearer (from the
|
|
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
|
|
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 };
|
package/dist/embed-host.d.ts
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
*
|
|
17
17
|
* @packageDocumentation
|
|
18
18
|
*/
|
|
19
|
-
/** A CRM bearer (from the
|
|
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
|
|
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 };
|
package/dist/embed-host.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function
|
|
1
|
+
function u(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function h(e,t){return async()=>{let i=await fetch(e,{method:"POST",...t}),o=await i.json().catch(()=>({}));if(!i.ok){let r=o?.error;throw new Error(r?`CRM session failed: ${r}`:`CRM session failed (HTTP ${i.status})`)}return o}}function f(e,t){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(t)}`}function p(e){let t=e.windowTarget??window,i=e.createChannel??(()=>new MessageChannel),o=e.devAllowAnyOrigin?"*":e.crmOrigin,r=null,a="",c=!1;async function d(){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 s=n.data;if(s)if(s.type==="channel-ack"){if(s.nonce!==a)return;d()}else s.type==="route-change"?e.onRouteChange?.(s.path):s.type==="resize"?e.onResize?.(s.height):s.type==="session-expired"&&(d(),r?.postMessage({type:"session-refreshed"}))}function l(){r?.close();let n=i();r=n.port1,a=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,r.onmessage=m,r.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:a},o,[n.port2])}function g(n){c||n.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&n.origin!==e.crmOrigin||u(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{f as buildCrmEmbedUrl,p as createCrmEmbedHost,h as crmSession};
|
|
2
2
|
//# sourceMappingURL=embed-host.js.map
|