@first-to-fly/crm-sdk 1.6.0 → 1.9.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
@@ -469,6 +469,7 @@ Pass the host's current look and language so the embedded CRM matches your app:
469
469
 
470
470
  - **`theme?`** — `'light' | 'dark' | 'system'`. `system` follows the visitor's OS setting.
471
471
  - **`locale?`** — a BCP 47 tag such as `'en'` or `'zh-CN'`.
472
+ - **`brand?`** — see Host brand below.
472
473
 
473
474
  ```tsx
474
475
  <CrmEmbed
@@ -489,6 +490,90 @@ The CRM applies them for the embed only and never saves them to the user's accou
489
490
  The CRM currently ships English text only, so `locale` sets the frame's `lang`
490
491
  attribute for now and translated screens follow as they are added.
491
492
 
493
+ #### Host brand (look native, not framed)
494
+
495
+ Pass `brand` and set `hostProvidesNav` so the CRM reads as part of your app: the CRM
496
+ drops its own tab bar, the tinted "Welcome back" band becomes a plain page header, page
497
+ backgrounds follow your surface, and every button, tab, selected state, chart accent and
498
+ focus ring uses your accent.
499
+
500
+ ```tsx
501
+ <CrmEmbed
502
+ crmEmbedOrigin="https://crm.example.com"
503
+ getSession={crmSession('/api/crm/session')}
504
+ hostProvidesNav
505
+ theme={isDark ? 'dark' : 'light'}
506
+ brand={isDark ? DARK_BRAND : LIGHT_BRAND}
507
+ />
508
+
509
+ const LIGHT_BRAND = {
510
+ accent: '#1f2a44',
511
+ background: '#f6f5f2',
512
+ surface: '#ffffff',
513
+ border: '#e6e3dd',
514
+ foreground: '#1a1a1a',
515
+ radius: '6px',
516
+ fontFamily: 'Inter, system-ui',
517
+ displayFontFamily: 'Georgia, serif',
518
+ };
519
+ ```
520
+
521
+ `brand` fields (all optional; absent means the CRM keeps its own look):
522
+
523
+ | Field | Value | Used for |
524
+ | --- | --- | --- |
525
+ | `accent` | `#rgb` or `#rrggbb` | buttons, selected tabs and pills, focus ring, chart accent |
526
+ | `accentForeground` | hex | text on the accent (default: white or near-black, whichever reads better) |
527
+ | `background` | hex | page background |
528
+ | `surface` | hex | cards, popovers (default: `background`) |
529
+ | `border` | hex | hairlines and input borders (default: derived) |
530
+ | `foreground` | hex | body text |
531
+ | `mutedForeground` | hex | secondary text (default: derived) |
532
+ | `radius` | `0px` to `24px`, e.g. `6px` | control corners; larger surfaces scale from it |
533
+ | `fontFamily` | font-family list | UI text, e.g. `Inter, system-ui` |
534
+ | `displayFontFamily` | font-family list | page titles, e.g. `Fraunces, Georgia, serif` |
535
+
536
+ Rules:
537
+
538
+ - Invalid fields are dropped on both sides (the SDK before sending, the CRM on receipt):
539
+ colours must be hex, `radius` a `px` value from 0 to 24, and font lists may contain only
540
+ letters, digits, spaces, commas, quotes, hyphens and underscores (max 160 characters,
541
+ quotes balanced).
542
+ - Pass the tokens for your CURRENT theme and give `brand` a new value when your theme
543
+ toggles. A new brand replaces the previous one; remove the prop (React) or call
544
+ `host.setContext({ brand: null })` to return the CRM to its own look.
545
+ - The first brand rides on the iframe URL as `?brand=` (base64url JSON, at most 1500
546
+ characters, otherwise it is not sent in the URL), so the first paint is already
547
+ on-brand. Later changes go over the channel as
548
+ `{ type: 'crm:host-context', theme?, locale?, brand? }`, no reload.
549
+ - No remote font is ever loaded. The frame is a separate document, so a family that is
550
+ not installed on the visitor's device falls back to the CRM's system font stack.
551
+ Use a family that is also available on the device, or accept the fallback.
552
+ - Nothing is saved to the user's account.
553
+
554
+ #### Routes for your own navigation
555
+
556
+ With `hostProvidesNav`, render your own nav and call the ref's `navigate(path)` (or set
557
+ `initialPath`). These paths are stable:
558
+
559
+ | Section | Path | Notes |
560
+ | --- | --- | --- |
561
+ | Dashboard | `/` | |
562
+ | Inbox (conversations) | `/comms` | `/conversations` is an alias |
563
+ | Contacts | `/contacts` | detail at `/contacts/:id`; `/contacts/email-suppressions` |
564
+ | Leads (pipeline) | `/leads` | `/pipelines` is an alias; detail at `/leads/:id` |
565
+ | Activities | `/activities` | |
566
+ | Settings | `/settings` | opens `/settings/profile`; also `/settings/business`, `/settings/appearance` |
567
+
568
+ AI settings, Workflows, Templates and Knowledge bases are not routes of the embed today,
569
+ so there is nothing to link to. Sections the workspace's plan does not include are
570
+ rejected by the CRM itself.
571
+
572
+ `onRouteChange(path)` is the navigation event: it fires on first load and on every
573
+ in-frame navigation with the sub-path under the embed base (for example `/`, `/comms`,
574
+ `/contacts/42`, `/settings/business`), without a query string. Match by prefix to
575
+ highlight your own nav item, e.g. `/comms` and `/conversations` both mean Inbox.
576
+
492
577
  React is an **optional peer dependency** — only pull in this entry if you use
493
578
  React. The low-level `embed-host` remains available for non-React consumers.
494
579
 
@@ -516,6 +601,7 @@ const ws = await partner.upsertWorkspace(tenantId, {
516
601
  name: 'Acme School',
517
602
  currency: 'SGD', // optional, ISO 4217; new workspaces otherwise start as USD
518
603
  timezone: 'Asia/Singapore', // optional, IANA name; otherwise UTC
604
+ aiMonthlyCapCredits: 5000, // optional, monthly AI cap in credits; see "AI cap and usage" below
519
605
  });
520
606
  if (ws.created) store(tenantId, ws.embedAppId, ws.embedAppSecret);
521
607
 
@@ -523,23 +609,74 @@ if (ws.created) store(tenantId, ws.embedAppId, ws.embedAppSecret);
523
609
  // leaving them out never changes what the workspace already has. An invalid code or zone is a 400.
524
610
 
525
611
  const status = await partner.getWorkspace(tenantId); // null when the CRM does not know the ref
526
- await partner.updateWorkspace(tenantId, { enabled: false }); // or { name } or both
612
+ await partner.updateWorkspace(tenantId, { enabled: false }); // or { name }, { aiMonthlyCapCredits }, or several
527
613
  const { embedAppId, embedAppSecret } = await partner.rotateWorkspaceSecret(tenantId); // old secret dies now
528
614
  ```
529
615
 
530
616
  Every failure is a `CrmPartnerError` with `status` (HTTP status, `0` for network
531
617
  failure or timeout) and `code` (the CRM's error code, or `timeout`, `network`,
532
- `bad_response`, `invalid_external_ref`, `invalid_contact_ref`, `invalid_limit`, `HTTP_<status>`). Its message never
618
+ `bad_response`, `invalid_external_ref`, `invalid_contact_ref`, `invalid_limit`, `invalid_cap`,
619
+ `invalid_date`, `HTTP_<status>`). Its message never
533
620
  contains the key, a secret or a response body. `externalRef` is validated before
534
621
  any request is made.
535
622
 
623
+ ### AI cap and usage
624
+
625
+ AI in a provisioned workspace needs no CRM plan. It is metered in **credits**
626
+ (1 credit = US$0.001) and you set a monthly cap per workspace with
627
+ `aiMonthlyCapCredits`:
628
+
629
+ | value | meaning |
630
+ | --- | --- |
631
+ | omitted on create | the default, 5000 credits per month |
632
+ | `N` (integer, 0 to 100,000,000) | N credits per UTC calendar month |
633
+ | `0` | AI off |
634
+ | `null` | no cap |
635
+
636
+ Omitting it on a later `upsertWorkspace` leaves the cap as it is. The month is the
637
+ UTC calendar month. A call that would pass the cap is refused and the workspace's AI
638
+ features say so (an auto-reply hands the conversation to staff and pauses AI on it).
639
+ The check happens on the estimate before a call and again on the real cost after it,
640
+ so one operation can land slightly over the cap; background AI (summaries, intent
641
+ detection) also pauses once 80 percent is used. The embedded assistant is recorded
642
+ but never capped.
643
+
644
+ ```typescript
645
+ await partner.updateWorkspace(tenantId, { aiMonthlyCapCredits: 20000 }); // or 0, or null
646
+
647
+ const ws = await partner.getWorkspace(tenantId);
648
+ ws?.aiMonthlyCapCredits; // 20000
649
+ ws?.ai; // { period: '2026-11', usedCredits: 1234 }
650
+
651
+ // Usage over a range: UTC dates, `to` inclusive, at most 12 months. Strings or Dates.
652
+ const usage = await partner.getWorkspaceUsage(tenantId, { from: '2026-11-01', to: '2026-11-30' });
653
+ usage?.totals; // { credits, cost_usd, input_tokens, output_tokens, events, blocked_count }
654
+ usage?.by_operation; // same figures per operation, then by_model and by_day
655
+ usage?.cap; // the CURRENT month: { ai_monthly_cap_credits, period, used_credits, remaining_credits }
656
+ usage?.assistant; // { input_tokens, output_tokens, cost_usd } (estimate); not capped, not in the totals
657
+ ```
658
+
659
+ `credits` is the net movement of the credit counter (what the cap counts);
660
+ `cost_usd` is the provider cost. `getWorkspaceUsage` resolves `null` for an unknown
661
+ ref. The report keeps the CRM's snake_case field names, like the contact calls.
662
+
663
+ ### Roles
664
+
665
+ The sub-app the CRM creates for you allows sessions up to `admin`. You decide each
666
+ person's role on every sign-in (`user.role` in the exchange); the CRM never grants
667
+ more than you asked for or the sub-app allows. In a provisioned workspace the CRM
668
+ follows you both ways: a person you now assert as `member` is demoted when they next
669
+ sign in, and every request after that uses the lower role (permissions are read from
670
+ the membership on each request, not frozen in the token). Sub-apps created earlier with a `member` ceiling are raised to `admin` by
671
+ the next `upsertWorkspace` for that ref.
672
+
536
673
  ### Contact sync
537
674
 
538
675
  The same client keeps your own people (parents, guardians, customers) in sync with
539
676
  the contacts of a workspace you provisioned, using your own key per contact
540
677
  (`contactRef`, `[A-Za-z0-9._:-]{1,200}`). These calls use the **partner key** and act
541
- as your product: no embed session is involved, and staff sessions in the workspace
542
- stay `member`. Setting `team_ref` or WhatsApp consent and erasing are allowed here
678
+ as your product: no embed session is involved, and a session is still one person's
679
+ role. Setting `team_ref` or WhatsApp consent and erasing are allowed here
543
680
  because the product, not a staff member, is making the call.
544
681
 
545
682
  ```typescript
@@ -556,6 +693,14 @@ const { contact, created, matched_by, consent_applied } = await partner.upsertCo
556
693
  // PDPA erasure. Resolves null when there is nothing to erase (404). Works even while the workspace is disabled.
557
694
  await partner.eraseContact(tenantId, 'guardian:42');
558
695
 
696
+ // PDPA erasure of contacts you never linked by ref (a parent who wrote first on WhatsApp).
697
+ // Matches phone digits or email (case-insensitive). Send `ref` so a contact linked only to
698
+ // that ref goes too. A contact with any other ref (another person of yours, or another
699
+ // product) is left alone and counted in skipped_linked_elsewhere. Resolves null for an
700
+ // unknown workspace; works while the workspace is disabled.
701
+ const r = await partner.eraseContactsByIdentity(tenantId, { phone: '+6591234567', email: 'mei@example.com', ref: 'guardian:42' });
702
+ // r = { erased: 1, contact_ids: ['...'], skipped_linked_elsewhere: 0 }
703
+
559
704
  // Changes feed: oldest first, includes deleted contacts. Page until next_cursor is null.
560
705
  let page = await partner.listContactChanges(tenantId, { since: '2026-01-01T00:00:00Z', limit: 100 });
561
706
  while (true) {
@@ -566,12 +711,13 @@ while (true) {
566
711
  ```
567
712
 
568
713
  - `upsertContact` on a disabled workspace (`updateWorkspace(..., { enabled: false })`)
569
- fails with `409` / `WORKSPACE_DISABLED`; `eraseContact` and `listContactChanges` still work.
714
+ fails with `409` / `WORKSPACE_DISABLED`; `eraseContact`, `eraseContactsByIdentity` and `listContactChanges` still work.
570
715
  - A parent's inbound STOP is never overridden by a product opt-in, unless its
571
716
  `source` is `parent_request`; an older consent record never replaces a newer one
572
717
  (`consent_applied` says whether yours was written).
573
718
  - An unknown workspace is `404` / `NOT_FOUND`; a plan limit on a new contact is `402`
574
719
  / `SUBSCRIPTION_LIMIT_EXCEEDED`.
720
+ - `eraseContactsByIdentity` needs a phone (with digits) or an email, else `invalid_identity` (400) before any request.
575
721
  - `contactRef` and `limit` (1 to 200) are validated before any request is made
576
722
  (`invalid_contact_ref`, `invalid_limit`).
577
723
 
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-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';
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-BiR0JbKC.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 PartnerContactEraseByIdentityBody, G as PartnerContactEraseByIdentityResult, H as PartnerContactEraseResult, I as PartnerWorkspaceCreated, J as PartnerWorkspaceDetail, K as PartnerWorkspaceExisting, N as PartnerWorkspacePatchBody, O as PartnerWorkspaceSecret, Q as PartnerWorkspaceStatus, R as PartnerWorkspaceUpsertBody, S as PartnerWorkspaceUsage, U as PartnerWorkspaceUsageQuery, V as TagList } from './crm-contracts-BiR0JbKC.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-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';
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-BiR0JbKC.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 PartnerContactEraseByIdentityBody, G as PartnerContactEraseByIdentityResult, H as PartnerContactEraseResult, I as PartnerWorkspaceCreated, J as PartnerWorkspaceDetail, K as PartnerWorkspaceExisting, N as PartnerWorkspacePatchBody, O as PartnerWorkspaceSecret, Q as PartnerWorkspaceStatus, R as PartnerWorkspaceUpsertBody, S as PartnerWorkspaceUsage, U as PartnerWorkspaceUsageQuery, V as TagList } from './crm-contracts-BiR0JbKC.js';
3
3
 
4
4
  /**
5
5
  * Typed CRM REST API client for SaaS backends.
@@ -346,18 +346,21 @@ type ContactChanges = {
346
346
  };
347
347
  type PartnerWorkspaceUpsertBody = {
348
348
  name: string;
349
+ ai_monthly_cap_credits?: (number | null) | undefined;
349
350
  currency?: string | undefined;
350
351
  timezone?: string | undefined;
351
352
  };
352
353
  type PartnerWorkspacePatchBody = {
353
354
  enabled?: boolean | undefined;
354
355
  name?: string | undefined;
356
+ ai_monthly_cap_credits?: (number | null) | undefined;
355
357
  };
356
358
  type PartnerWorkspaceCreated = {
357
359
  external_ref: string;
358
360
  workspace_id: string | null;
359
361
  embed_app_id: string | null;
360
362
  enabled: boolean;
363
+ ai_monthly_cap_credits: number | null;
361
364
  embed_app_secret: string;
362
365
  created: true;
363
366
  };
@@ -366,6 +369,7 @@ type PartnerWorkspaceExisting = {
366
369
  workspace_id: string | null;
367
370
  embed_app_id: string | null;
368
371
  enabled: boolean;
372
+ ai_monthly_cap_credits: number | null;
369
373
  created: false;
370
374
  };
371
375
  type PartnerWorkspaceStatus = {
@@ -373,13 +377,19 @@ type PartnerWorkspaceStatus = {
373
377
  workspace_id: string | null;
374
378
  embed_app_id: string | null;
375
379
  enabled: boolean;
380
+ ai_monthly_cap_credits: number | null;
376
381
  };
377
382
  type PartnerWorkspaceDetail = {
378
383
  external_ref: string;
379
384
  workspace_id: string | null;
380
385
  embed_app_id: string | null;
381
386
  enabled: boolean;
387
+ ai_monthly_cap_credits: number | null;
382
388
  state: "pending" | "owner_created" | "workspace_created" | "app_installed" | "sub_app_created" | "active";
389
+ ai: {
390
+ period: string;
391
+ used_credits: number;
392
+ } | null;
383
393
  };
384
394
  type PartnerWorkspaceSecret = {
385
395
  embed_app_id: string;
@@ -390,6 +400,73 @@ type PartnerContactEraseResult = {
390
400
  contact_id: string;
391
401
  other_sources_removed: number;
392
402
  };
403
+ type PartnerWorkspaceUsageQuery = {
404
+ from: string;
405
+ to: string;
406
+ };
407
+ type PartnerWorkspaceUsage = {
408
+ external_ref: string;
409
+ workspace_id: string;
410
+ from: string;
411
+ to: string;
412
+ timezone: "UTC";
413
+ cap: {
414
+ ai_monthly_cap_credits: number | null;
415
+ period: string;
416
+ used_credits: number;
417
+ remaining_credits: number | null;
418
+ };
419
+ totals: {
420
+ credits: number;
421
+ cost_usd: number;
422
+ input_tokens: number;
423
+ output_tokens: number;
424
+ events: number;
425
+ blocked_count: number;
426
+ };
427
+ by_operation: {
428
+ credits: number;
429
+ cost_usd: number;
430
+ input_tokens: number;
431
+ output_tokens: number;
432
+ events: number;
433
+ blocked_count: number;
434
+ operation: string;
435
+ }[];
436
+ by_model: {
437
+ credits: number;
438
+ cost_usd: number;
439
+ input_tokens: number;
440
+ output_tokens: number;
441
+ events: number;
442
+ blocked_count: number;
443
+ model: string;
444
+ }[];
445
+ by_day: {
446
+ credits: number;
447
+ cost_usd: number;
448
+ input_tokens: number;
449
+ output_tokens: number;
450
+ events: number;
451
+ blocked_count: number;
452
+ day: string;
453
+ }[];
454
+ assistant: {
455
+ input_tokens: number;
456
+ output_tokens: number;
457
+ cost_usd: number;
458
+ };
459
+ };
460
+ type PartnerContactEraseByIdentityBody = {
461
+ phone?: string | undefined;
462
+ email?: string | undefined;
463
+ ref?: string | undefined;
464
+ };
465
+ type PartnerContactEraseByIdentityResult = {
466
+ erased: number;
467
+ contact_ids: string[];
468
+ skipped_linked_elsewhere: number;
469
+ };
393
470
  type LeadCreate = {
394
471
  status?: string | undefined;
395
472
  assigned_to?: (string | undefined) | null;
@@ -1014,4 +1091,4 @@ interface ListEnvelope<T> {
1014
1091
  pageSize: number;
1015
1092
  }
1016
1093
 
1017
- export type { ContactRefUpsertResult as A, LeadCapture as B, ContactQuery as C, LeadNote as D, LeadNoteCreate as E, PartnerContactEraseResult as F, PartnerWorkspaceCreated as G, PartnerWorkspaceDetail as H, PartnerWorkspaceExisting as I, PartnerWorkspacePatchBody as J, PartnerWorkspaceSecret as K, LeadQuery as L, MessageQuery as M, PartnerWorkspaceStatus as N, PartnerWorkspaceUpsertBody as O, ProductQuery as P, TagList as Q, TaskQuery as T, ContactList as a, Contact as b, ContactCreate as c, ContactUpdate as d, ListEnvelope as e, Lead as f, LeadCreate as g, LeadUpdate as h, Task as i, LegacyTaskUpdate as j, LegacyTask as k, Product as l, ProductCreate as m, ProductUpdate as n, ConversationQuery as o, Conversation as p, ConversationUpdate as q, Message as r, MessageCreate as s, TagQuery as t, TagWithUsage as u, TagCreate as v, Tag as w, ContactChanges as x, ContactChangesQuery as y, ContactRefUpsertBody as z };
1094
+ export type { ContactRefUpsertResult as A, LeadCapture as B, ContactQuery as C, LeadNote as D, LeadNoteCreate as E, PartnerContactEraseByIdentityBody as F, PartnerContactEraseByIdentityResult as G, PartnerContactEraseResult as H, PartnerWorkspaceCreated as I, PartnerWorkspaceDetail as J, PartnerWorkspaceExisting as K, LeadQuery as L, MessageQuery as M, PartnerWorkspacePatchBody as N, PartnerWorkspaceSecret as O, ProductQuery as P, PartnerWorkspaceStatus as Q, PartnerWorkspaceUpsertBody as R, PartnerWorkspaceUsage as S, TaskQuery as T, PartnerWorkspaceUsageQuery as U, TagList as V, ContactList as a, Contact as b, ContactCreate as c, ContactUpdate as d, ListEnvelope as e, Lead as f, LeadCreate as g, LeadUpdate as h, Task as i, LegacyTaskUpdate as j, LegacyTask as k, Product as l, ProductCreate as m, ProductUpdate as n, ConversationQuery as o, Conversation as p, ConversationUpdate as q, Message as r, MessageCreate as s, TagQuery as t, TagWithUsage as u, TagCreate as v, Tag as w, ContactChanges as x, ContactChangesQuery as y, ContactRefUpsertBody as z };
@@ -346,18 +346,21 @@ type ContactChanges = {
346
346
  };
347
347
  type PartnerWorkspaceUpsertBody = {
348
348
  name: string;
349
+ ai_monthly_cap_credits?: (number | null) | undefined;
349
350
  currency?: string | undefined;
350
351
  timezone?: string | undefined;
351
352
  };
352
353
  type PartnerWorkspacePatchBody = {
353
354
  enabled?: boolean | undefined;
354
355
  name?: string | undefined;
356
+ ai_monthly_cap_credits?: (number | null) | undefined;
355
357
  };
356
358
  type PartnerWorkspaceCreated = {
357
359
  external_ref: string;
358
360
  workspace_id: string | null;
359
361
  embed_app_id: string | null;
360
362
  enabled: boolean;
363
+ ai_monthly_cap_credits: number | null;
361
364
  embed_app_secret: string;
362
365
  created: true;
363
366
  };
@@ -366,6 +369,7 @@ type PartnerWorkspaceExisting = {
366
369
  workspace_id: string | null;
367
370
  embed_app_id: string | null;
368
371
  enabled: boolean;
372
+ ai_monthly_cap_credits: number | null;
369
373
  created: false;
370
374
  };
371
375
  type PartnerWorkspaceStatus = {
@@ -373,13 +377,19 @@ type PartnerWorkspaceStatus = {
373
377
  workspace_id: string | null;
374
378
  embed_app_id: string | null;
375
379
  enabled: boolean;
380
+ ai_monthly_cap_credits: number | null;
376
381
  };
377
382
  type PartnerWorkspaceDetail = {
378
383
  external_ref: string;
379
384
  workspace_id: string | null;
380
385
  embed_app_id: string | null;
381
386
  enabled: boolean;
387
+ ai_monthly_cap_credits: number | null;
382
388
  state: "pending" | "owner_created" | "workspace_created" | "app_installed" | "sub_app_created" | "active";
389
+ ai: {
390
+ period: string;
391
+ used_credits: number;
392
+ } | null;
383
393
  };
384
394
  type PartnerWorkspaceSecret = {
385
395
  embed_app_id: string;
@@ -390,6 +400,73 @@ type PartnerContactEraseResult = {
390
400
  contact_id: string;
391
401
  other_sources_removed: number;
392
402
  };
403
+ type PartnerWorkspaceUsageQuery = {
404
+ from: string;
405
+ to: string;
406
+ };
407
+ type PartnerWorkspaceUsage = {
408
+ external_ref: string;
409
+ workspace_id: string;
410
+ from: string;
411
+ to: string;
412
+ timezone: "UTC";
413
+ cap: {
414
+ ai_monthly_cap_credits: number | null;
415
+ period: string;
416
+ used_credits: number;
417
+ remaining_credits: number | null;
418
+ };
419
+ totals: {
420
+ credits: number;
421
+ cost_usd: number;
422
+ input_tokens: number;
423
+ output_tokens: number;
424
+ events: number;
425
+ blocked_count: number;
426
+ };
427
+ by_operation: {
428
+ credits: number;
429
+ cost_usd: number;
430
+ input_tokens: number;
431
+ output_tokens: number;
432
+ events: number;
433
+ blocked_count: number;
434
+ operation: string;
435
+ }[];
436
+ by_model: {
437
+ credits: number;
438
+ cost_usd: number;
439
+ input_tokens: number;
440
+ output_tokens: number;
441
+ events: number;
442
+ blocked_count: number;
443
+ model: string;
444
+ }[];
445
+ by_day: {
446
+ credits: number;
447
+ cost_usd: number;
448
+ input_tokens: number;
449
+ output_tokens: number;
450
+ events: number;
451
+ blocked_count: number;
452
+ day: string;
453
+ }[];
454
+ assistant: {
455
+ input_tokens: number;
456
+ output_tokens: number;
457
+ cost_usd: number;
458
+ };
459
+ };
460
+ type PartnerContactEraseByIdentityBody = {
461
+ phone?: string | undefined;
462
+ email?: string | undefined;
463
+ ref?: string | undefined;
464
+ };
465
+ type PartnerContactEraseByIdentityResult = {
466
+ erased: number;
467
+ contact_ids: string[];
468
+ skipped_linked_elsewhere: number;
469
+ };
393
470
  type LeadCreate = {
394
471
  status?: string | undefined;
395
472
  assigned_to?: (string | undefined) | null;
@@ -1014,4 +1091,4 @@ interface ListEnvelope<T> {
1014
1091
  pageSize: number;
1015
1092
  }
1016
1093
 
1017
- export type { ContactRefUpsertResult as A, LeadCapture as B, ContactQuery as C, LeadNote as D, LeadNoteCreate as E, PartnerContactEraseResult as F, PartnerWorkspaceCreated as G, PartnerWorkspaceDetail as H, PartnerWorkspaceExisting as I, PartnerWorkspacePatchBody as J, PartnerWorkspaceSecret as K, LeadQuery as L, MessageQuery as M, PartnerWorkspaceStatus as N, PartnerWorkspaceUpsertBody as O, ProductQuery as P, TagList as Q, TaskQuery as T, ContactList as a, Contact as b, ContactCreate as c, ContactUpdate as d, ListEnvelope as e, Lead as f, LeadCreate as g, LeadUpdate as h, Task as i, LegacyTaskUpdate as j, LegacyTask as k, Product as l, ProductCreate as m, ProductUpdate as n, ConversationQuery as o, Conversation as p, ConversationUpdate as q, Message as r, MessageCreate as s, TagQuery as t, TagWithUsage as u, TagCreate as v, Tag as w, ContactChanges as x, ContactChangesQuery as y, ContactRefUpsertBody as z };
1094
+ export type { ContactRefUpsertResult as A, LeadCapture as B, ContactQuery as C, LeadNote as D, LeadNoteCreate as E, PartnerContactEraseByIdentityBody as F, PartnerContactEraseByIdentityResult as G, PartnerContactEraseResult as H, PartnerWorkspaceCreated as I, PartnerWorkspaceDetail as J, PartnerWorkspaceExisting as K, LeadQuery as L, MessageQuery as M, PartnerWorkspacePatchBody as N, PartnerWorkspaceSecret as O, ProductQuery as P, PartnerWorkspaceStatus as Q, PartnerWorkspaceUpsertBody as R, PartnerWorkspaceUsage as S, TaskQuery as T, PartnerWorkspaceUsageQuery as U, TagList as V, ContactList as a, Contact as b, ContactCreate as c, ContactUpdate as d, ListEnvelope as e, Lead as f, LeadCreate as g, LeadUpdate as h, Task as i, LegacyTaskUpdate as j, LegacyTask as k, Product as l, ProductCreate as m, ProductUpdate as n, ConversationQuery as o, Conversation as p, ConversationUpdate as q, Message as r, MessageCreate as s, TagQuery as t, TagWithUsage as u, TagCreate as v, Tag as w, ContactChanges as x, ContactChangesQuery as y, ContactRefUpsertBody as z };
@@ -1,2 +1,2 @@
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});
1
+ "use strict";var m=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var w=(e,n)=>{for(var r in n)m(e,r,{get:n[r],enumerable:!0})},R=(e,n,r,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let t of M(n))!v.call(e,t)&&t!==r&&m(e,t,{get:()=>n[t],enumerable:!(o=H(n,t))||o.enumerable});return e};var k=e=>R(m({},"__esModule",{value:!0}),e);var L={};w(L,{buildCrmEmbedUrl:()=>P,createCrmEmbedHost:()=>I,crmSession:()=>_,encodeHostBrand:()=>p,hostContextQuery:()=>B,normalizeHostBrand:()=>u,normalizeHostContext:()=>l});module.exports=k(L);var E=["light","dark","system"],A=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/,T=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i,F=/^(\d{1,2}(?:\.\d{1,2})?)px$/,$=/^[A-Za-z0-9 ,'"_-]+$/;var O=["accent","accentForeground","background","surface","border","foreground","mutedForeground"];function h(e){if(typeof e!="string")return;let n=e.trim();if(!(!n||n.length>160||!$.test(n))&&!((n.match(/"/g)?.length??0)%2!==0||(n.match(/'/g)?.length??0)%2!==0))return n}function u(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n={};for(let t of O){let a=e[t];if(typeof a=="string"&&T.test(a.trim())){let c=a.trim().toLowerCase();c.length===4&&(c=`#${c[1]}${c[1]}${c[2]}${c[2]}${c[3]}${c[3]}`),n[t]=c}}if(typeof e.radius=="string"){let t=F.exec(e.radius.trim());t&&Number(t[1])<=24&&(n.radius=`${Number(t[1])}px`)}let r=h(e.fontFamily);r&&(n.fontFamily=r);let o=h(e.displayFontFamily);return o&&(n.displayFontFamily=o),Object.keys(n).length>0?n:void 0}function p(e){let n=u(e);if(!n)return null;let r=new TextEncoder().encode(JSON.stringify(n)),o="";r.forEach(a=>{o+=String.fromCharCode(a)});let t=btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return t.length<=1500?t:null}function l(e){let n={};if(e?.brand===null)n.brand=null;else{let r=u(e?.brand);r&&(n.brand=r)}return e?.theme&&E.includes(e.theme)&&(n.theme=e.theme),typeof e?.locale=="string"&&A.test(e.locale.trim())&&(n.locale=e.locale.trim()),n}function B(e){let n=l(e),r=[];n.theme&&r.push(`theme=${encodeURIComponent(n.theme)}`),n.locale&&r.push(`locale=${encodeURIComponent(n.locale)}`);let o=n.brand?p(n.brand):null;return o&&r.push(`brand=${o}`),r}function S(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function _(e,n){return async()=>{let r=await fetch(e,{method:"POST",...n}),o=await r.json().catch(()=>({}));if(!r.ok){let a=o?.error;throw new Error(a?`CRM session failed: ${a}`:`CRM session failed (HTTP ${r.status})`)}let t=o;if(typeof t?.accessToken!="string"||typeof t?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return t}}function P(e,n){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(n)}`}function I(e){let n=e.windowTarget??window,r=e.createChannel??(()=>new MessageChannel),o=e.devAllowAnyOrigin?"*":e.crmOrigin,t=null,a="",c=!1,d=l(e.hostContext);function g(s){if(s){t?.postMessage({type:"crm:host-context",...d,...s});return}if(!t||d.theme===void 0&&d.locale===void 0&&d.brand===void 0)return;let i={type:"crm:host-context",...d};t.postMessage(i)}async function f(){try{let s=await e.getBearer();return t?.postMessage({type:"auth-tokens",accessToken:s.accessToken,refreshToken:s.refreshToken??""}),g(),!0}catch(s){return e.onError?.(s),!1}}function y(s){let i=s.data;if(i)if(i.type==="channel-ack"){if(i.nonce!==a)return;f()}else i.type==="route-change"?e.onRouteChange?.(i.path):i.type==="resize"?e.onResize?.(i.height):i.type==="session-expired"&&f().then(b=>{b&&t?.postMessage({type:"session-refreshed"})})}function x(){t?.close();let s=r();t=s.port1,a=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,t.onmessage=y,t.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:a},o,[s.port2])}function C(s){c||s.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&s.origin!==e.crmOrigin||S(s.data)&&x())}return n.addEventListener("message",C),{navigate(s){t?.postMessage({type:"navigate",path:s})},setContext(s){let i=l(s);d={...d,...i},i.brand===null&&delete d.brand,g(i.brand===null?{brand:null}:void 0)},dispose(){c=!0,n.removeEventListener("message",C),t?.close(),t=null}}}0&&(module.exports={buildCrmEmbedUrl,createCrmEmbedHost,crmSession,encodeHostBrand,hostContextQuery,normalizeHostBrand,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 * 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,O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C,EAA2B,CAC9Cb,GACAa,EAAM,SAAWnB,EAAK,OAAO,gBAC7B,CAACA,EAAK,mBAAqBmB,EAAM,SAAWnB,EAAK,WACjDV,EAAQ6B,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,WAAWlC,EAA2B,CACpCqB,EAAU,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"]}
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?, brand? } 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=`, `?locale=` and `?brand=`), 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 * Brand tokens that make the embedded CRM look like part of the host. All optional.\n * Colours are `#rgb` or `#rrggbb`; invalid values are dropped, never sent.\n * Pass the values for the host's CURRENT theme and send a new brand when it toggles.\n * No remote font is loaded: a family the visitor's system lacks falls back to the CRM's.\n */\nexport interface CrmHostBrand {\n /** Buttons, selected tabs, focus rings, chart accent. */\n accent?: string;\n /** Text on the accent. Defaults to white or near-black, whichever reads better. */\n accentForeground?: string;\n /** Page background. */\n background?: string;\n /** Cards, popovers and inputs. Defaults to `background`. */\n surface?: string;\n /** Hairlines and input borders. Derived from background and foreground when omitted. */\n border?: string;\n /** Body text. */\n foreground?: string;\n /** Secondary text. Derived when omitted. */\n mutedForeground?: string;\n /** Corner radius for controls, `0px` to `24px`, e.g. `\"6px\"`. Larger surfaces scale from it. */\n radius?: string;\n /** UI font family list, e.g. `\"Inter, system-ui\"`. Letters, digits, spaces, commas, quotes, hyphens, underscores; max 160 chars. */\n fontFamily?: string;\n /** Font for page titles, same rules as `fontFamily`, e.g. `\"Fraunces, Georgia, serif\"`. */\n displayFontFamily?: string;\n}\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 * Host brand tokens. A new brand REPLACES the previous one; `null` (setContext only)\n * returns the CRM to its own look. Omitted: unchanged.\n */\n brand?: CrmHostBrand | null;\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\nconst HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;\nconst RADIUS_PX = /^(\\d{1,2}(?:\\.\\d{1,2})?)px$/;\nconst FONT_CHARS = /^[A-Za-z0-9 ,'\"_-]+$/;\nconst FONT_MAX = 160;\n/** The encoded `?brand=` value never exceeds this; a longer one would be ignored by the CRM. */\nconst BRAND_PARAM_MAX = 1500;\nconst BRAND_COLOR_KEYS = [\n 'accent', 'accentForeground', 'background', 'surface', 'border', 'foreground', 'mutedForeground',\n] as const;\n\nfunction cleanFont(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const v = value.trim();\n if (!v || v.length > FONT_MAX || !FONT_CHARS.test(v)) return undefined;\n if ((v.match(/\"/g)?.length ?? 0) % 2 !== 0 || (v.match(/'/g)?.length ?? 0) % 2 !== 0) return undefined;\n return v;\n}\n\n/**\n * Keeps only valid brand fields: hex colours (lower-cased `#rrggbb`), a `0-24px` radius and\n * safe font-family lists. Returns undefined when nothing valid is left.\n */\nexport function normalizeHostBrand(brand: CrmHostBrand | undefined | null): CrmHostBrand | undefined {\n if (!brand || typeof brand !== 'object' || Array.isArray(brand)) return undefined;\n const out: CrmHostBrand = {};\n for (const key of BRAND_COLOR_KEYS) {\n const raw = brand[key];\n if (typeof raw === 'string' && HEX_COLOR.test(raw.trim())) {\n let hex = raw.trim().toLowerCase();\n if (hex.length === 4) hex = `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`;\n out[key] = hex;\n }\n }\n if (typeof brand.radius === 'string') {\n const m = RADIUS_PX.exec(brand.radius.trim());\n if (m && Number(m[1]) <= 24) out.radius = `${Number(m[1])}px`;\n }\n const fontFamily = cleanFont(brand.fontFamily);\n if (fontFamily) out.fontFamily = fontFamily;\n const displayFontFamily = cleanFont(brand.displayFontFamily);\n if (displayFontFamily) out.displayFontFamily = displayFontFamily;\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** Encodes a brand for the `?brand=` query value (base64url JSON), or null when empty or too long. */\nexport function encodeHostBrand(brand: CrmHostBrand | undefined | null): string | null {\n const clean = normalizeHostBrand(brand);\n if (!clean) return null;\n const bytes = new TextEncoder().encode(JSON.stringify(clean));\n let bin = '';\n bytes.forEach((b) => { bin += String.fromCharCode(b); });\n const encoded = btoa(bin).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n return encoded.length <= BRAND_PARAM_MAX ? encoded : null;\n}\n\n/**\n * Keeps only values the CRM understands: a known theme, a well-formed language tag and a\n * valid brand. Anything else is dropped, so a bad value can never reach the iframe URL or\n * the message. `brand: null` is kept so a message can clear an earlier brand.\n */\nexport function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext {\n const out: CrmHostContext = {};\n if (ctx?.brand === null) out.brand = null;\n else {\n const brand = normalizeHostBrand(ctx?.brand);\n if (brand) out.brand = brand;\n }\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`, `locale` and `brand` as URL query pairs (e.g. `[\"theme=dark\", \"locale=zh-CN\", \"brand=eyJ...\"]`). */\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 const brand = clean.brand ? encodeHostBrand(clean.brand) : null;\n if (brand) pairs.push(`brand=${brand}`);\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(extra?: { brand: null }): void {\n if (extra) {\n port?.postMessage({ type: 'crm:host-context', ...context, ...extra } satisfies CrmHostContextMessage);\n return;\n }\n if (!port || (context.theme === undefined && context.locale === undefined && context.brand === 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 const next = normalizeHostContext(ctx);\n context = { ...context, ...next };\n if (next.brand === null) delete context.brand; // cleared: send null once, then forget it\n sendContext(next.brand === null ? { brand: null } : undefined);\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,oBAAAC,EAAA,qBAAAC,EAAA,uBAAAC,EAAA,yBAAAC,IAAA,eAAAC,EAAAT,GAkFA,IAAMU,EAAiC,CAAC,QAAS,OAAQ,QAAQ,EAC3DC,EAAa,4CAEbC,EAAY,kCACZC,EAAY,8BACZC,EAAa,uBAInB,IAAMC,EAAmB,CACvB,SAAU,mBAAoB,aAAc,UAAW,SAAU,aAAc,iBACjF,EAEA,SAASC,EAAUC,EAAoC,CACrD,GAAI,OAAOA,GAAU,SAAU,OAC/B,IAAMC,EAAID,EAAM,KAAK,EACrB,GAAI,GAACC,GAAKA,EAAE,OAAS,KAAY,CAACC,EAAW,KAAKD,CAAC,IAC9C,GAAAA,EAAE,MAAM,IAAI,GAAG,QAAU,GAAK,IAAM,IAAMA,EAAE,MAAM,IAAI,GAAG,QAAU,GAAK,IAAM,GACnF,OAAOA,CACT,CAMO,SAASE,EAAmBC,EAAkE,CACnG,GAAI,CAACA,GAAS,OAAOA,GAAU,UAAY,MAAM,QAAQA,CAAK,EAAG,OACjE,IAAMC,EAAoB,CA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,WAAWZ,EAAK,MAAM,EAClBA,EAAK,OAAS,mBAIlBuB,EAAc,EAAE,KAAMK,GAAO,CAC5BA,GAAIZ,GAAM,YAAY,CAAE,KAAM,mBAAoB,CAAC,CACzD,CAAC,CAEL,CAEA,SAASa,GAAuB,CAC9Bb,GAAM,MAAM,EACZ,IAAMc,EAAUhB,EAAY,EAC5BE,EAAOc,EAAQ,MACfb,EAAQ,WAAW,QAAQ,aAAa,GAAK,KAAK,OAAO,KAAK,OAAO,CAAC,EAAE,MAAM,CAAC,CAAC,GAChFD,EAAK,UAAYU,EACjBV,EAAK,QAAQ,EACbJ,EAAK,OAAO,eAAe,YACzB,CAAE,KAAM,eAAgB,MAAAK,CAAM,EAC9BF,EACA,CAACe,EAAQ,KAAK,CAChB,CACF,CAEA,SAASC,EAAgBC,EAA2B,CAC9Cd,GACAc,EAAM,SAAWpB,EAAK,OAAO,gBAC7B,CAACA,EAAK,mBAAqBoB,EAAM,SAAWpB,EAAK,WACjDb,EAAQiC,EAAM,IAAI,GAAGH,EAAe,EAC1C,CAEA,OAAAhB,EAAO,iBAAiB,UAAWkB,CAAgC,EAE5D,CACL,SAASE,EAAoB,CAC3BjB,GAAM,YAAY,CAAE,KAAM,WAAY,KAAAiB,CAAK,CAAC,CAC9C,EACA,WAAWvC,EAA2B,CACpC,IAAMwC,EAAOzC,EAAqBC,CAAG,EACrCyB,EAAU,CAAE,GAAGA,EAAS,GAAGe,CAAK,EAC5BA,EAAK,QAAU,MAAM,OAAOf,EAAQ,MACxCC,EAAYc,EAAK,QAAU,KAAO,CAAE,MAAO,IAAK,EAAI,MAAS,CAC/D,EACA,SAAgB,CACdhB,EAAW,GACXL,EAAO,oBAAoB,UAAWkB,CAAgC,EACtEf,GAAM,MAAM,EACZA,EAAO,IACT,CACF,CACF","names":["embed_host_exports","__export","buildCrmEmbedUrl","createCrmEmbedHost","crmSession","encodeHostBrand","hostContextQuery","normalizeHostBrand","normalizeHostContext","__toCommonJS","HOST_THEMES","BCP47_LIKE","HEX_COLOR","RADIUS_PX","FONT_CHARS","BRAND_COLOR_KEYS","cleanFont","value","v","FONT_CHARS","normalizeHostBrand","brand","out","key","raw","HEX_COLOR","hex","m","RADIUS_PX","fontFamily","displayFontFamily","encodeHostBrand","clean","bytes","bin","b","encoded","normalizeHostContext","ctx","HOST_THEMES","BCP47_LIKE","hostContextQuery","pairs","isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","context","sendContext","extra","msg","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path","next"]}