@first-to-fly/crm-sdk 1.6.0 → 1.10.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,137 @@ 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
+
577
+ #### Host actions (create an enquiry, open a person)
578
+
579
+ Some things only your app can do, such as turning a chat with an unknown parent into a lead.
580
+ The embedded CRM can ask for them without knowing how your app works. You opt in per action:
581
+
582
+ ```tsx
583
+ <CrmEmbed
584
+ crmEmbedOrigin="https://app.crm.example.com"
585
+ getSession={crmSession('/api/crm/session')}
586
+ hostName="myEdu"
587
+ capabilities={['create-lead', 'open-person']}
588
+ onHostAction={(req) => {
589
+ if (req.action === 'create-lead') openEnquiryForm({ ...req.contact, note: req.messageSnippet });
590
+ if (req.action === 'open-person') router.push(`/people/by-crm-contact/${req.contact.crmContactId}`);
591
+ }}
592
+ />
593
+ ```
594
+
595
+ Low-level hosts pass the same `hostContext: { capabilities, hostName }` and `onHostAction` to
596
+ `createCrmEmbedHost`, and change them later with `setContext`.
597
+
598
+ - `capabilities` is channel-only (never in the iframe URL). Known values only (`create-lead`,
599
+ `open-person`), de-duplicated, at most 8. A new list replaces the old one; `[]` turns every
600
+ action off; omitted leaves it unchanged. With none, the CRM shows no host button.
601
+ - `hostName` (max 40 characters) is the label the CRM puts on its buttons and cards. When
602
+ absent the CRM says "the host app".
603
+ - Port message from the CRM: `{ type: 'crm:host-action', requestId, ...action }`, where the
604
+ action is one of:
605
+ - `{ action: 'create-lead', contact: { crmContactId, name?, phone?, email? }, conversationId, channel?, messageSnippet? }`.
606
+ `messageSnippet` is the last inbound message, at most 280 characters.
607
+ - `{ action: 'open-person', contact: { crmContactId } }`.
608
+ - Limits: `name` 200, `email` 320, `phone` 40, `channel` 40, ids 100, `messageSnippet` 280. A message
609
+ that is malformed, has an unknown action or any oversize field is dropped whole and never
610
+ reaches `onHostAction`. Nothing is delivered before the handshake completes.
611
+ - The handler gets `requestId` (the CRM's id for the click). Nothing is returned to the CRM.
612
+
613
+ **Security notes**
614
+
615
+ - Capabilities only decide what the CRM's UI offers. They are not authorisation. The embedded
616
+ page is a third-party document in your page: treat every field of every action as untrusted
617
+ input, check on your server that the signed-in user may do it, and never trust
618
+ `crmContactId` without looking it up for that user's workspace.
619
+ - Do not put contact details in URLs. Open your own form from in-memory state (or a server
620
+ side draft) rather than `?phone=...&name=...`, so names and numbers stay out of logs,
621
+ history and referrers.
622
+ - `hostName` and the snippet are plain text. Render them as text, never as HTML.
623
+
492
624
  React is an **optional peer dependency** — only pull in this entry if you use
493
625
  React. The low-level `embed-host` remains available for non-React consumers.
494
626
 
@@ -516,6 +648,7 @@ const ws = await partner.upsertWorkspace(tenantId, {
516
648
  name: 'Acme School',
517
649
  currency: 'SGD', // optional, ISO 4217; new workspaces otherwise start as USD
518
650
  timezone: 'Asia/Singapore', // optional, IANA name; otherwise UTC
651
+ aiMonthlyCapCredits: 5000, // optional, monthly AI cap in credits; see "AI cap and usage" below
519
652
  });
520
653
  if (ws.created) store(tenantId, ws.embedAppId, ws.embedAppSecret);
521
654
 
@@ -523,23 +656,74 @@ if (ws.created) store(tenantId, ws.embedAppId, ws.embedAppSecret);
523
656
  // leaving them out never changes what the workspace already has. An invalid code or zone is a 400.
524
657
 
525
658
  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
659
+ await partner.updateWorkspace(tenantId, { enabled: false }); // or { name }, { aiMonthlyCapCredits }, or several
527
660
  const { embedAppId, embedAppSecret } = await partner.rotateWorkspaceSecret(tenantId); // old secret dies now
528
661
  ```
529
662
 
530
663
  Every failure is a `CrmPartnerError` with `status` (HTTP status, `0` for network
531
664
  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
665
+ `bad_response`, `invalid_external_ref`, `invalid_contact_ref`, `invalid_limit`, `invalid_cap`,
666
+ `invalid_date`, `HTTP_<status>`). Its message never
533
667
  contains the key, a secret or a response body. `externalRef` is validated before
534
668
  any request is made.
535
669
 
670
+ ### AI cap and usage
671
+
672
+ AI in a provisioned workspace needs no CRM plan. It is metered in **credits**
673
+ (1 credit = US$0.001) and you set a monthly cap per workspace with
674
+ `aiMonthlyCapCredits`:
675
+
676
+ | value | meaning |
677
+ | --- | --- |
678
+ | omitted on create | the default, 5000 credits per month |
679
+ | `N` (integer, 0 to 100,000,000) | N credits per UTC calendar month |
680
+ | `0` | AI off |
681
+ | `null` | no cap |
682
+
683
+ Omitting it on a later `upsertWorkspace` leaves the cap as it is. The month is the
684
+ UTC calendar month. A call that would pass the cap is refused and the workspace's AI
685
+ features say so (an auto-reply hands the conversation to staff and pauses AI on it).
686
+ The check happens on the estimate before a call and again on the real cost after it,
687
+ so one operation can land slightly over the cap; background AI (summaries, intent
688
+ detection) also pauses once 80 percent is used. The embedded assistant is recorded
689
+ but never capped.
690
+
691
+ ```typescript
692
+ await partner.updateWorkspace(tenantId, { aiMonthlyCapCredits: 20000 }); // or 0, or null
693
+
694
+ const ws = await partner.getWorkspace(tenantId);
695
+ ws?.aiMonthlyCapCredits; // 20000
696
+ ws?.ai; // { period: '2026-11', usedCredits: 1234 }
697
+
698
+ // Usage over a range: UTC dates, `to` inclusive, at most 12 months. Strings or Dates.
699
+ const usage = await partner.getWorkspaceUsage(tenantId, { from: '2026-11-01', to: '2026-11-30' });
700
+ usage?.totals; // { credits, cost_usd, input_tokens, output_tokens, events, blocked_count }
701
+ usage?.by_operation; // same figures per operation, then by_model and by_day
702
+ usage?.cap; // the CURRENT month: { ai_monthly_cap_credits, period, used_credits, remaining_credits }
703
+ usage?.assistant; // { input_tokens, output_tokens, cost_usd } (estimate); not capped, not in the totals
704
+ ```
705
+
706
+ `credits` is the net movement of the credit counter (what the cap counts);
707
+ `cost_usd` is the provider cost. `getWorkspaceUsage` resolves `null` for an unknown
708
+ ref. The report keeps the CRM's snake_case field names, like the contact calls.
709
+
710
+ ### Roles
711
+
712
+ The sub-app the CRM creates for you allows sessions up to `admin`. You decide each
713
+ person's role on every sign-in (`user.role` in the exchange); the CRM never grants
714
+ more than you asked for or the sub-app allows. In a provisioned workspace the CRM
715
+ follows you both ways: a person you now assert as `member` is demoted when they next
716
+ sign in, and every request after that uses the lower role (permissions are read from
717
+ the membership on each request, not frozen in the token). Sub-apps created earlier with a `member` ceiling are raised to `admin` by
718
+ the next `upsertWorkspace` for that ref.
719
+
536
720
  ### Contact sync
537
721
 
538
722
  The same client keeps your own people (parents, guardians, customers) in sync with
539
723
  the contacts of a workspace you provisioned, using your own key per contact
540
724
  (`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
725
+ as your product: no embed session is involved, and a session is still one person's
726
+ role. Setting `team_ref` or WhatsApp consent and erasing are allowed here
543
727
  because the product, not a staff member, is making the call.
544
728
 
545
729
  ```typescript
@@ -556,6 +740,14 @@ const { contact, created, matched_by, consent_applied } = await partner.upsertCo
556
740
  // PDPA erasure. Resolves null when there is nothing to erase (404). Works even while the workspace is disabled.
557
741
  await partner.eraseContact(tenantId, 'guardian:42');
558
742
 
743
+ // PDPA erasure of contacts you never linked by ref (a parent who wrote first on WhatsApp).
744
+ // Matches phone digits or email (case-insensitive). Send `ref` so a contact linked only to
745
+ // that ref goes too. A contact with any other ref (another person of yours, or another
746
+ // product) is left alone and counted in skipped_linked_elsewhere. Resolves null for an
747
+ // unknown workspace; works while the workspace is disabled.
748
+ const r = await partner.eraseContactsByIdentity(tenantId, { phone: '+6591234567', email: 'mei@example.com', ref: 'guardian:42' });
749
+ // r = { erased: 1, contact_ids: ['...'], skipped_linked_elsewhere: 0 }
750
+
559
751
  // Changes feed: oldest first, includes deleted contacts. Page until next_cursor is null.
560
752
  let page = await partner.listContactChanges(tenantId, { since: '2026-01-01T00:00:00Z', limit: 100 });
561
753
  while (true) {
@@ -566,12 +758,13 @@ while (true) {
566
758
  ```
567
759
 
568
760
  - `upsertContact` on a disabled workspace (`updateWorkspace(..., { enabled: false })`)
569
- fails with `409` / `WORKSPACE_DISABLED`; `eraseContact` and `listContactChanges` still work.
761
+ fails with `409` / `WORKSPACE_DISABLED`; `eraseContact`, `eraseContactsByIdentity` and `listContactChanges` still work.
570
762
  - A parent's inbound STOP is never overridden by a product opt-in, unless its
571
763
  `source` is `parent_request`; an older consent record never replaces a newer one
572
764
  (`consent_applied` says whether yours was written).
573
765
  - An unknown workspace is `404` / `NOT_FOUND`; a plan limit on a new contact is `402`
574
766
  / `SUBSCRIPTION_LIMIT_EXCEEDED`.
767
+ - `eraseContactsByIdentity` needs a phone (with digits) or an email, else `invalid_identity` (400) before any request.
575
768
  - `contactRef` and `limit` (1 to 200) are validated before any request is made
576
769
  (`invalid_contact_ref`, `invalid_limit`).
577
770
 
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 y=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var E=Object.prototype.hasOwnProperty;var x=(e,n)=>{for(var t in n)y(e,t,{get:n[t],enumerable:!0})},O=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of T(n))!E.call(e,r)&&r!==t&&y(e,r,{get:()=>n[r],enumerable:!(o=b(n,r))||o.enumerable});return e};var N=e=>O(y({},"__esModule",{value:!0}),e);var z={};x(z,{HOST_ACTION_SNIPPET_MAX:()=>w,buildCrmEmbedUrl:()=>q,createCrmEmbedHost:()=>D,crmSession:()=>L,encodeHostBrand:()=>I,hostContextQuery:()=>$,normalizeHostBrand:()=>H,normalizeHostContext:()=>A,parseHostActionMessage:()=>_});module.exports=N(z);var R=["create-lead","open-person"];var w=280,k=["light","dark","system"],v=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/,S=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i,X=/^(\d{1,2}(?:\.\d{1,2})?)px$/,P=/^[A-Za-z0-9 ,'"_-]+$/;var F=["accent","accentForeground","background","surface","border","foreground","mutedForeground"];function M(e){if(typeof e!="string")return;let n=e.trim();if(!(!n||n.length>160||!P.test(n))&&!((n.match(/"/g)?.length??0)%2!==0||(n.match(/'/g)?.length??0)%2!==0))return n}function H(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n={};for(let r of F){let a=e[r];if(typeof a=="string"&&S.test(a.trim())){let i=a.trim().toLowerCase();i.length===4&&(i=`#${i[1]}${i[1]}${i[2]}${i[2]}${i[3]}${i[3]}`),n[r]=i}}if(typeof e.radius=="string"){let r=X.exec(e.radius.trim());r&&Number(r[1])<=24&&(n.radius=`${Number(r[1])}px`)}let t=M(e.fontFamily);t&&(n.fontFamily=t);let o=M(e.displayFontFamily);return o&&(n.displayFontFamily=o),Object.keys(n).length>0?n:void 0}function I(e){let n=H(e);if(!n)return null;let t=new TextEncoder().encode(JSON.stringify(n)),o="";t.forEach(a=>{o+=String.fromCharCode(a)});let r=btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return r.length<=1500?r:null}function A(e){let n={};if(e?.brand===null)n.brand=null;else{let t=H(e?.brand);t&&(n.brand=t)}if(e?.theme&&k.includes(e.theme)&&(n.theme=e.theme),typeof e?.locale=="string"&&v.test(e.locale.trim())&&(n.locale=e.locale.trim()),Array.isArray(e?.capabilities)){let t=e.capabilities.filter(o=>R.includes(o));n.capabilities=[...new Set(t)].slice(0,8)}if(typeof e?.hostName=="string"){let t=e.hostName.trim();t&&t.length<=40&&!/[\u0000-\u001f\u007f]/.test(t)&&(n.hostName=t)}return n}function d(e,n,t){if(e===void 0)return t?null:void 0;if(typeof e!="string")return null;let o=e.trim();return o.length>n?null:o||(t?null:void 0)}function _(e){if(!e||typeof e!="object")return null;let n=e;if(n.type!=="crm:host-action")return null;let t=d(n.requestId,64,!0);if(!t)return null;let o=n.contact;if(!o||typeof o!="object"||Array.isArray(o))return null;let r=o,a=d(r.crmContactId,100,!0);if(!a)return null;if(n.action==="open-person")return{requestId:t,action:"open-person",contact:{crmContactId:a}};if(n.action!=="create-lead")return null;let i=d(r.name,200,!1),u=d(r.phone,40,!1),l=d(r.email,320,!1),C=d(n.conversationId,100,!0),m=d(n.channel,40,!1),p=d(n.messageSnippet,280,!1);if([i,u,l,m,p].some(s=>s===null)||!C)return null;let f={crmContactId:a};i&&(f.name=i),u&&(f.phone=u),l&&(f.email=l);let g={requestId:t,action:"create-lead",contact:f,conversationId:C};return m&&(g.channel=m),p&&(g.messageSnippet=p),g}function $(e){let n=A(e),t=[];n.theme&&t.push(`theme=${encodeURIComponent(n.theme)}`),n.locale&&t.push(`locale=${encodeURIComponent(n.locale)}`);let o=n.brand?I(n.brand):null;return o&&t.push(`brand=${o}`),t}function B(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function L(e,n){return async()=>{let t=await fetch(e,{method:"POST",...n}),o=await t.json().catch(()=>({}));if(!t.ok){let a=o?.error;throw new Error(a?`CRM session failed: ${a}`:`CRM session failed (HTTP ${t.status})`)}let r=o;if(typeof r?.accessToken!="string"||typeof r?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return r}}function q(e,n){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(n)}`}function D(e){let n=e.windowTarget??window,t=e.createChannel??(()=>new MessageChannel),o=e.devAllowAnyOrigin?"*":e.crmOrigin,r=null,a="",i=!1,u=!1,l=A(e.hostContext);function C(s){if(s){r?.postMessage({type:"crm:host-context",...l,...s});return}if(!r||Object.keys(l).length===0)return;let c={type:"crm:host-context",...l};r.postMessage(c)}async function m(){try{let s=await e.getBearer();return r?.postMessage({type:"auth-tokens",accessToken:s.accessToken,refreshToken:s.refreshToken??""}),C(),!0}catch(s){return e.onError?.(s),!1}}function p(s){let c=s.data;if(c)if(c.type==="channel-ack"){if(c.nonce!==a)return;i=!0,m()}else if(c.type==="route-change")e.onRouteChange?.(c.path);else if(c.type==="crm:host-action"){if(!i)return;let h=_(c);h&&e.onHostAction?.(h)}else c.type==="resize"?e.onResize?.(c.height):c.type==="session-expired"&&m().then(h=>{h&&r?.postMessage({type:"session-refreshed"})})}function f(){r?.close(),i=!1;let s=t();r=s.port1,a=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,r.onmessage=p,r.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:a},o,[s.port2])}function g(s){u||s.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&s.origin!==e.crmOrigin||B(s.data)&&f())}return n.addEventListener("message",g),{navigate(s){r?.postMessage({type:"navigate",path:s})},setContext(s){let c=A(s);l={...l,...c},c.brand===null&&delete l.brand,C(c.brand===null?{brand:null}:void 0)},dispose(){u=!0,n.removeEventListener("message",g),r?.close(),r=null}}}0&&(module.exports={HOST_ACTION_SNIPPET_MAX,buildCrmEmbedUrl,createCrmEmbedHost,crmSession,encodeHostBrand,hostContextQuery,normalizeHostBrand,normalizeHostContext,parseHostActionMessage});
2
2
  //# sourceMappingURL=embed-host.cjs.map