@first-to-fly/crm-sdk 1.4.3 → 1.5.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 +84 -1
- package/dist/api.cjs +1 -1
- package/dist/api.cjs.map +1 -1
- package/dist/api.d.cts +5 -711
- package/dist/api.d.ts +5 -711
- package/dist/api.js +1 -1
- package/dist/api.js.map +1 -1
- package/dist/crm-contracts-DLY_TSwy.d.cts +1012 -0
- package/dist/crm-contracts-DLY_TSwy.d.ts +1012 -0
- package/dist/partner.cjs +2 -0
- package/dist/partner.cjs.map +1 -0
- package/dist/partner.d.cts +149 -0
- package/dist/partner.d.ts +149 -0
- package/dist/partner.js +2 -0
- package/dist/partner.js.map +1 -0
- package/package.json +11 -1
package/README.md
CHANGED
|
@@ -6,6 +6,7 @@ The CRM SDK supports **two integration directions**:
|
|
|
6
6
|
|---|---|---|
|
|
7
7
|
| **Embed an app _inside_ the CRM** (guest app in the CRM's iframe) | `@first-to-fly/crm-sdk` | browser |
|
|
8
8
|
| **Embed _the CRM_ inside your SaaS** (host the CRM's iframe) | `@first-to-fly/crm-sdk/embed-host` + `@first-to-fly/crm-sdk/embed-server` | browser + server |
|
|
9
|
+
| **Provision workspaces / sync contacts from your backend** | `@first-to-fly/crm-sdk/partner` | server only |
|
|
9
10
|
|
|
10
11
|
The first is documented under [Quick Start](#quick-start). The second — the proxy-free, cookie-less embed — is under [Embedding the CRM in your SaaS](#embedding-the-crm-in-your-saas).
|
|
11
12
|
|
|
@@ -465,6 +466,86 @@ function Shell() {
|
|
|
465
466
|
React is an **optional peer dependency** — only pull in this entry if you use
|
|
466
467
|
React. The low-level `embed-host` remains available for non-React consumers.
|
|
467
468
|
|
|
469
|
+
## Server-side partner provisioning
|
|
470
|
+
|
|
471
|
+
For a product that embeds the CRM for many customers of its own. One platform key
|
|
472
|
+
(`ptk_...`, issued by the CRM operator) provisions a CRM workspace per customer,
|
|
473
|
+
keyed by the customer's id in your product (`externalRef`, `[A-Za-z0-9_-]{1,64}`).
|
|
474
|
+
|
|
475
|
+
> **Server only.** The partner key is a platform-wide secret and responses carry
|
|
476
|
+
> per-workspace embed secrets. Never import `@first-to-fly/crm-sdk/partner` in a
|
|
477
|
+
> browser or mobile bundle, and never log the key or a secret.
|
|
478
|
+
|
|
479
|
+
```typescript
|
|
480
|
+
import { createCrmPartnerClient, CrmPartnerError } from '@first-to-fly/crm-sdk/partner';
|
|
481
|
+
|
|
482
|
+
const partner = createCrmPartnerClient({
|
|
483
|
+
crmBaseUrl: process.env.CRM_BASE_URL!,
|
|
484
|
+
partnerKey: process.env.CRM_PARTNER_KEY!,
|
|
485
|
+
// timeoutMs: 15000 (default), fetch: customFetch (optional)
|
|
486
|
+
});
|
|
487
|
+
|
|
488
|
+
// Idempotent. HTTP 201 the first time (secret shown once), 200 afterwards (no secret).
|
|
489
|
+
const ws = await partner.upsertWorkspace(tenantId, { name: 'Acme School' });
|
|
490
|
+
if (ws.created) store(tenantId, ws.embedAppId, ws.embedAppSecret);
|
|
491
|
+
|
|
492
|
+
const status = await partner.getWorkspace(tenantId); // null when the CRM does not know the ref
|
|
493
|
+
await partner.updateWorkspace(tenantId, { enabled: false }); // or { name } or both
|
|
494
|
+
const { embedAppId, embedAppSecret } = await partner.rotateWorkspaceSecret(tenantId); // old secret dies now
|
|
495
|
+
```
|
|
496
|
+
|
|
497
|
+
Every failure is a `CrmPartnerError` with `status` (HTTP status, `0` for network
|
|
498
|
+
failure or timeout) and `code` (the CRM's error code, or `timeout`, `network`,
|
|
499
|
+
`bad_response`, `invalid_external_ref`, `invalid_contact_ref`, `invalid_limit`, `HTTP_<status>`). Its message never
|
|
500
|
+
contains the key, a secret or a response body. `externalRef` is validated before
|
|
501
|
+
any request is made.
|
|
502
|
+
|
|
503
|
+
### Contact sync
|
|
504
|
+
|
|
505
|
+
The same client keeps your own people (parents, guardians, customers) in sync with
|
|
506
|
+
the contacts of a workspace you provisioned, using your own key per contact
|
|
507
|
+
(`contactRef`, `[A-Za-z0-9._:-]{1,200}`). These calls use the **partner key** and act
|
|
508
|
+
as your product: no embed session is involved, and staff sessions in the workspace
|
|
509
|
+
stay `member`. Setting `team_ref` or WhatsApp consent and erasing are allowed here
|
|
510
|
+
because the product, not a staff member, is making the call.
|
|
511
|
+
|
|
512
|
+
```typescript
|
|
513
|
+
// Idempotent upsert (ref, then phone, then email). Field names are the CRM's own (snake_case).
|
|
514
|
+
const { contact, created, matched_by, consent_applied } = await partner.upsertContact(tenantId, 'guardian:42', {
|
|
515
|
+
name: 'Mei Tan',
|
|
516
|
+
phone: '+6591234567',
|
|
517
|
+
team_ref: 'centre-1', // files the contact under your team, created if new
|
|
518
|
+
team_name: 'Centre One', // used only when the team is created
|
|
519
|
+
whatsapp_consent: { status: 'opted_in', source: 'signup_form', recorded_at: new Date().toISOString() },
|
|
520
|
+
attributes: { plan: 'gold' },
|
|
521
|
+
});
|
|
522
|
+
|
|
523
|
+
// PDPA erasure. Resolves null when there is nothing to erase (404). Works even while the workspace is disabled.
|
|
524
|
+
await partner.eraseContact(tenantId, 'guardian:42');
|
|
525
|
+
|
|
526
|
+
// Changes feed: oldest first, includes deleted contacts. Page until next_cursor is null.
|
|
527
|
+
let page = await partner.listContactChanges(tenantId, { since: '2026-01-01T00:00:00Z', limit: 100 });
|
|
528
|
+
while (true) {
|
|
529
|
+
handle(page.items);
|
|
530
|
+
if (!page.next_cursor) break;
|
|
531
|
+
page = await partner.listContactChanges(tenantId, { cursor: page.next_cursor });
|
|
532
|
+
}
|
|
533
|
+
```
|
|
534
|
+
|
|
535
|
+
- `upsertContact` on a disabled workspace (`updateWorkspace(..., { enabled: false })`)
|
|
536
|
+
fails with `409` / `WORKSPACE_DISABLED`; `eraseContact` and `listContactChanges` still work.
|
|
537
|
+
- A parent's inbound STOP is never overridden by a product opt-in, unless its
|
|
538
|
+
`source` is `parent_request`; an older consent record never replaces a newer one
|
|
539
|
+
(`consent_applied` says whether yours was written).
|
|
540
|
+
- An unknown workspace is `404` / `NOT_FOUND`; a plan limit on a new contact is `402`
|
|
541
|
+
/ `SUBSCRIPTION_LIMIT_EXCEEDED`.
|
|
542
|
+
- `contactRef` and `limit` (1 to 200) are validated before any request is made
|
|
543
|
+
(`invalid_contact_ref`, `invalid_limit`).
|
|
544
|
+
|
|
545
|
+
Request and response types (`ContactRefUpsertBody`, `ContactRefUpsertResult`,
|
|
546
|
+
`ContactChanges`, `ContactChangesQuery`, `PartnerContactEraseResult`) are generated
|
|
547
|
+
from the CRM's contracts and exported from `@first-to-fly/crm-sdk/partner`.
|
|
548
|
+
|
|
468
549
|
## Calling CRM APIs from your backend
|
|
469
550
|
|
|
470
551
|
Once your server has a CRM bearer (from `createEmbedSessionWithKey`) — or an
|
|
@@ -565,9 +646,11 @@ await crm.request('POST', '/public/leads', { body: { name: 'Web lead', email: 'x
|
|
|
565
646
|
### Available resources
|
|
566
647
|
|
|
567
648
|
`contacts`, `leads`, `products` (`.list/.get/.create/.update/.delete`),
|
|
568
|
-
`tasks` (`.list
|
|
649
|
+
`tasks` (`.list`; legacy-only `.update`), `conversations`
|
|
569
650
|
(`.list/.get/.update` + `.messages.list/.send`), and `tags` (`.list/.create`) —
|
|
570
651
|
plus the generic `request<T>(method, path, { query?, body? })`.
|
|
652
|
+
Create and update Activity tasks through `/activities` using `request()` until a
|
|
653
|
+
typed Activities resource is added.
|
|
571
654
|
|
|
572
655
|
### Regenerating types
|
|
573
656
|
|
package/dist/api.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var v=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var
|
|
1
|
+
"use strict";var v=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var $=Object.prototype.hasOwnProperty;var I=(s,n)=>{for(var r in n)v(s,r,{get:n[r],enumerable:!0})},O=(s,n,r,a)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of q(n))!$.call(s,o)&&o!==r&&v(s,o,{get:()=>n[o],enumerable:!(a=Q(n,o))||a.enumerable});return s};var M=s=>O(v({},"__esModule",{value:!0}),s);var G={};I(G,{CrmApiError:()=>m,createCrmApiClient:()=>U,default:()=>x});module.exports=M(G);var m=class s extends Error{constructor(n,r,a,o,c){super(a),this.name="CrmApiError",this.status=n,this.code=r,this.body=o,c&&"cause"in c&&(this.cause=c.cause),Object.setPrototypeOf(this,s.prototype)}};function A(s){if(!s)return"";let n=new URLSearchParams;for(let[a,o]of Object.entries(s))if(o!=null)if(Array.isArray(o))for(let c of o)c!=null&&n.append(a,String(c));else n.append(a,String(o));let r=n.toString();return r?`?${r}`:""}function L(s){return typeof s=="object"&&s!==null&&"success"in s}function S(s,n){let r=L(s)&&s.success===!1?s:void 0,a=r?.error,o=typeof r?.message=="string"?r.message:void 0,c=a&&typeof a=="object"?a:void 0,f=typeof c?.code=="string"?c.code:void 0,C=typeof c?.message=="string"?c.message:void 0,t=typeof a=="string"?a:void 0,e=f??t??`HTTP_${n}`,i=C??o??t??`CRM request failed with status ${n}`;return{code:e,message:i}}function U(s){let{crmBaseUrl:n,accessToken:r,apiKey:a}=s;if(!r&&!a)throw new Error("createCrmApiClient: exactly one of `accessToken` or `apiKey` is required (got neither).");if(r&&a)throw new Error("createCrmApiClient: provide only one of `accessToken` or `apiKey` (got both).");let o=s.fetch??globalThis.fetch;if(typeof o!="function")throw new Error("createCrmApiClient: no fetch implementation available. Pass `fetch` explicitly.");let c=n.replace(/\/+$/,""),f=c.endsWith("/api")?c:`${c}/api`,C=r?{Authorization:`Bearer ${r}`}:{"X-API-Key":a};async function t(e,i,p={}){let w=`${f}${i}${A(p.query)}`,h={...C},k=p.body!==void 0;k&&(h["Content-Type"]="application/json");let y=p.timeoutMs??s.timeoutMs,P=y!==void 0?new AbortController:void 0,b=!1,T;P&&y!==void 0&&(T=setTimeout(()=>{b=!0,P.abort()},y));let l;try{l=await o(w,{method:e,headers:h,body:k?JSON.stringify(p.body):void 0,signal:P?.signal})}catch(u){if(b||u instanceof Error&&u.name==="AbortError")throw new m(0,"TIMEOUT",`CRM request timed out after ${y}ms`,u,{cause:u});let E=u instanceof Error?u.message:"CRM request failed (network error)";throw new m(0,"NETWORK_ERROR",E,u,{cause:u})}finally{T!==void 0&&clearTimeout(T)}let g=await l.text(),d=g;if(g)try{d=JSON.parse(g)}catch{d=g}let R=L(d)&&d.success===!1;if(!l.ok||R){let{code:u,message:E}=S(d,l.status);throw new m(l.status,u,E,d)}if(L(d)&&d.success===!0)return d.data;if(g!=="")return d}return{contacts:{list:e=>t("GET","/contacts",{query:e}),get:e=>t("GET",`/contacts/${encodeURIComponent(e)}`),create:e=>t("POST","/contacts",{body:e}),update:(e,i)=>t("PUT",`/contacts/${encodeURIComponent(e)}`,{body:i}),delete:e=>t("DELETE",`/contacts/${encodeURIComponent(e)}`)},leads:{list:e=>t("GET","/leads",{query:e}),get:e=>t("GET",`/leads/${encodeURIComponent(e)}`),create:e=>t("POST","/leads",{body:e}),update:(e,i)=>t("PUT",`/leads/${encodeURIComponent(e)}`,{body:i}),delete:e=>t("DELETE",`/leads/${encodeURIComponent(e)}`)},tasks:{list:e=>t("GET","/tasks",{query:e}),update:(e,i,p)=>t("PATCH",`/leads/${encodeURIComponent(e)}/tasks/${encodeURIComponent(i)}`,{body:p})},products:{list:e=>t("GET","/products",{query:e}),get:e=>t("GET",`/products/${encodeURIComponent(e)}`),create:e=>t("POST","/products",{body:e}),update:(e,i)=>t("PUT",`/products/${encodeURIComponent(e)}`,{body:i}),delete:e=>t("DELETE",`/products/${encodeURIComponent(e)}`)},conversations:{list:e=>t("GET","/conversations",{query:e}),get:e=>t("GET",`/conversations/${encodeURIComponent(e)}`),update:(e,i)=>t("PUT",`/conversations/${encodeURIComponent(e)}`,{body:i}),messages:{list:(e,i)=>t("GET",`/conversations/${encodeURIComponent(e)}/messages`,{query:i}),send:(e,i)=>t("POST",`/conversations/${encodeURIComponent(e)}/messages`,{body:i})}},tags:{list:e=>t("GET","/tags",{query:e}),create:e=>t("POST","/tags",{body:e})},request:t}}var x=U;0&&(module.exports={CrmApiError,createCrmApiClient});
|
|
2
2
|
//# sourceMappingURL=api.cjs.map
|
package/dist/api.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/api.ts"],"sourcesContent":["/**\n * Typed CRM REST API client for SaaS backends.\n *\n * Construct with `createCrmApiClient({ crmBaseUrl, accessToken | apiKey })` and\n * call typed resource methods (contacts, leads, conversations, messages, tasks,\n * products, tags) or the generic `request<T>()` escape hatch. Every method\n * returns the UNWRAPPED `data` from the CRM's `{ success, data }` envelope.\n *\n * Auth:\n * - `accessToken` (from `createEmbedSessionWithKey().data.access_token`) is\n * sent as `Authorization: Bearer <token>` and covers the full API surface.\n * The typed resource methods below hit `/api/*` routes that require this\n * **Bearer** token.\n * - `apiKey` (`crm_live_...`) is sent as `X-API-Key` and today only guards\n * `/api/public/*`. An `apiKey` client should use the generic `request()`\n * against those `/public/*` endpoints, NOT the typed resource methods.\n *\n * Error handling — every failure is thrown as a {@link CrmApiError} so callers\n * can `catch (e) { if (e instanceof CrmApiError) ... }`:\n * - non-2xx responses, AND 2xx responses the server mislabels with an\n * `{ success: false }` envelope, throw with the HTTP `status` and a code\n * derived from the body.\n * - network / DNS / connection failures throw with `status: 0` and\n * `code: 'NETWORK_ERROR'`.\n * - a request that exceeds `timeoutMs` (via `AbortController`) throws with\n * `status: 0` and `code: 'TIMEOUT'`.\n *\n * Timeouts — pass `timeoutMs` on the client (default for all requests) and/or\n * per request. If unset there is no timeout.\n *\n * @packageDocumentation\n */\n\nimport type {\n Contact,\n ContactCreate,\n ContactUpdate,\n ContactQuery,\n ContactList,\n Lead,\n LeadCreate,\n LeadUpdate,\n LeadQuery,\n Task,\n TaskCreate,\n TaskUpdate,\n TaskQuery,\n Conversation,\n ConversationQuery,\n ConversationUpdate,\n Message,\n MessageQuery,\n MessageCreate,\n Product,\n ProductCreate,\n ProductUpdate,\n ProductQuery,\n Tag,\n TagCreate,\n TagQuery,\n TagWithUsage,\n ListEnvelope,\n} from './generated/crm-contracts';\n\nexport type * from './generated/crm-contracts';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\ntype FetchLike = typeof fetch;\n\n/** Options for {@link createCrmApiClient}. Exactly one of accessToken / apiKey. */\nexport interface CrmApiClientOptions {\n /** Base URL of the CRM, e.g. `https://crm.example.com` (no trailing `/api`). */\n crmBaseUrl: string;\n /** Bearer token from `createEmbedSessionWithKey` — full API surface. */\n accessToken?: string;\n /** Server-to-server API key (`crm_live_...`) — `/api/public/*` only today. */\n apiKey?: string;\n /** Custom fetch implementation (e.g. for Node < 18 or testing). */\n fetch?: FetchLike;\n /**\n * Default per-request timeout in milliseconds, enforced via `AbortController`.\n * On timeout the request throws a {@link CrmApiError} (`status: 0`,\n * `code: 'TIMEOUT'`). If unset (default), requests have no timeout.\n */\n timeoutMs?: number;\n}\n\n/** CRM success envelope. */\ninterface SuccessEnvelope<T> {\n success: true;\n data: T;\n message?: string;\n meta?: Record<string, unknown>;\n}\n\n/** CRM error envelope. */\ninterface ErrorEnvelope {\n success: false;\n error: string;\n message?: string;\n details?: string;\n}\n\ntype QueryPrimitive = string | number | boolean;\ntype QueryValue =\n | QueryPrimitive\n | Array<QueryPrimitive>\n | undefined\n | null;\ntype QueryParams = Record<string, QueryValue>;\n\ninterface RequestOptions {\n query?: QueryParams;\n body?: unknown;\n /**\n * Per-request timeout in milliseconds (overrides the client `timeoutMs`).\n * On timeout the request throws a {@link CrmApiError} (`status: 0`,\n * `code: 'TIMEOUT'`).\n */\n timeoutMs?: number;\n}\n\n/**\n * Error thrown for any failed CRM request:\n * - a non-2xx HTTP response,\n * - a 2xx response carrying an `{ success: false }` envelope (server mislabel),\n * - a network/DNS/connection failure (`status: 0`, `code: 'NETWORK_ERROR'`),\n * - a timeout / abort (`status: 0`, `code: 'TIMEOUT'`).\n */\nexport class CrmApiError extends Error {\n /** HTTP status code (0 for network errors / timeouts). */\n readonly status: number;\n /**\n * Machine-readable code. For envelope errors: the object `error.code`, else\n * the string `error`, else `HTTP_<status>`. For transport failures:\n * `NETWORK_ERROR` or `TIMEOUT`.\n */\n readonly code: string;\n /** Parsed response body, or the underlying error for transport failures. */\n readonly body: unknown;\n\n constructor(\n status: number,\n code: string,\n message: string,\n body: unknown,\n options?: { cause?: unknown },\n ) {\n super(message);\n this.name = 'CrmApiError';\n this.status = status;\n this.code = code;\n this.body = body;\n // Preserve the underlying error (network/abort) without requiring the\n // ES2022 `cause` constructor option.\n if (options && 'cause' in options) {\n (this as { cause?: unknown }).cause = options.cause;\n }\n Object.setPrototypeOf(this, CrmApiError.prototype);\n }\n}\n\n/** The client returned by {@link createCrmApiClient}. */\nexport interface CrmApiClient {\n contacts: {\n list(query?: ContactQuery): Promise<ContactList>;\n get(id: string): Promise<Contact>;\n create(body: ContactCreate): Promise<Contact>;\n update(id: string, body: ContactUpdate): Promise<Contact>;\n delete(id: string): Promise<void>;\n };\n leads: {\n list(query?: LeadQuery): Promise<ListEnvelope<Lead>>;\n get(id: string): Promise<Lead>;\n create(body: LeadCreate): Promise<Lead>;\n update(id: string, body: LeadUpdate): Promise<Lead>;\n delete(id: string): Promise<void>;\n };\n tasks: {\n list(query?: TaskQuery): Promise<ListEnvelope<Task>>;\n create(leadId: string, body: TaskCreate): Promise<Task>;\n update(leadId: string, taskId: string, body: TaskUpdate): Promise<Task>;\n };\n products: {\n list(query?: ProductQuery): Promise<ListEnvelope<Product>>;\n get(id: string): Promise<Product>;\n create(body: ProductCreate): Promise<Product>;\n update(id: string, body: ProductUpdate): Promise<Product>;\n delete(id: string): Promise<void>;\n };\n conversations: {\n list(query?: ConversationQuery): Promise<ListEnvelope<Conversation>>;\n get(id: string): Promise<Conversation>;\n update(id: string, body: ConversationUpdate): Promise<Conversation>;\n messages: {\n list(\n conversationId: string,\n query?: MessageQuery,\n ): Promise<ListEnvelope<Message>>;\n send(conversationId: string, body: MessageCreate): Promise<Message>;\n };\n };\n tags: {\n list(query?: TagQuery): Promise<ListEnvelope<TagWithUsage>>;\n create(body: TagCreate): Promise<Tag>;\n };\n /** Generic escape hatch — returns the unwrapped `data` typed as `T`. */\n request<T>(\n method: string,\n path: string,\n options?: RequestOptions,\n ): Promise<T>;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Serialize query params. Array values are appended as repeated params\n * (`?tag=a&tag=b`); `undefined`/`null` values (and array elements) are skipped.\n *\n * NOTE on the CRM's `tags` filter: the CRM's contacts/leads query schemas expect\n * `tags` as a single comma-separated string (`?tags=a,b`), which the server\n * splits on `,`. If you pass `tags` as an array here it becomes repeated params\n * (`?tags=a&tags=b`), which those endpoints will NOT parse as multiple tags —\n * pass a comma-joined string for that specific field. All other core query\n * fields are primitives. No core query field is a nested object.\n */\nfunction serializeQuery(query?: QueryParams): string {\n if (!query) return '';\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue;\n if (Array.isArray(value)) {\n for (const el of value) {\n if (el === undefined || el === null) continue;\n params.append(key, String(el));\n }\n } else {\n params.append(key, String(value));\n }\n }\n const qs = params.toString();\n return qs ? `?${qs}` : '';\n}\n\nfunction isEnvelope(v: unknown): v is SuccessEnvelope<unknown> | ErrorEnvelope {\n return typeof v === 'object' && v !== null && 'success' in v;\n}\n\n/** Derive `{ code, message }` from a parsed CRM error envelope + HTTP status. */\nfunction deriveError(parsed: unknown, status: number): { code: string; message: string } {\n const envelope =\n isEnvelope(parsed) && parsed.success === false\n ? (parsed as ErrorEnvelope & { error?: unknown })\n : undefined;\n const rawError: unknown = envelope?.error;\n const envMessage =\n typeof envelope?.message === 'string' ? envelope.message : undefined;\n\n // error can be a string (\"human string\" or a code) OR an object { code, message }.\n const errorObj =\n rawError && typeof rawError === 'object'\n ? (rawError as { code?: unknown; message?: unknown })\n : undefined;\n const errorObjCode =\n typeof errorObj?.code === 'string' ? errorObj.code : undefined;\n const errorObjMessage =\n typeof errorObj?.message === 'string' ? errorObj.message : undefined;\n const errorStr = typeof rawError === 'string' ? rawError : undefined;\n\n const code = errorObjCode ?? errorStr ?? `HTTP_${status}`;\n const message =\n errorObjMessage ??\n envMessage ??\n errorStr ??\n `CRM request failed with status ${status}`;\n\n return { code, message };\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\nexport function createCrmApiClient(opts: CrmApiClientOptions): CrmApiClient {\n const { crmBaseUrl, accessToken, apiKey } = opts;\n\n if (!accessToken && !apiKey) {\n throw new Error(\n 'createCrmApiClient: exactly one of `accessToken` or `apiKey` is required (got neither).',\n );\n }\n if (accessToken && apiKey) {\n throw new Error(\n 'createCrmApiClient: provide only one of `accessToken` or `apiKey` (got both).',\n );\n }\n\n const fetchImpl: FetchLike = opts.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== 'function') {\n throw new Error(\n 'createCrmApiClient: no fetch implementation available. Pass `fetch` explicitly.',\n );\n }\n\n // Normalize base: strip trailing slash, then ensure it ends with `/api`.\n const trimmed = crmBaseUrl.replace(/\\/+$/, '');\n const apiBase = trimmed.endsWith('/api') ? trimmed : `${trimmed}/api`;\n\n const authHeaders: Record<string, string> = accessToken\n ? { Authorization: `Bearer ${accessToken}` }\n : { 'X-API-Key': apiKey as string };\n\n async function request<T>(\n method: string,\n path: string,\n options: RequestOptions = {},\n ): Promise<T> {\n const url = `${apiBase}${path}${serializeQuery(options.query)}`;\n const headers: Record<string, string> = { ...authHeaders };\n const hasBody = options.body !== undefined;\n if (hasBody) headers['Content-Type'] = 'application/json';\n\n const timeoutMs = options.timeoutMs ?? opts.timeoutMs;\n const controller =\n timeoutMs !== undefined ? new AbortController() : undefined;\n let timedOut = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n if (controller && timeoutMs !== undefined) {\n timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs);\n }\n\n let res: Response;\n try {\n res = await fetchImpl(url, {\n method,\n headers,\n body: hasBody ? JSON.stringify(options.body) : undefined,\n signal: controller?.signal,\n });\n } catch (err) {\n // Network error, DNS failure, connection refused, or abort/timeout.\n if (\n timedOut ||\n (err instanceof Error && err.name === 'AbortError')\n ) {\n throw new CrmApiError(\n 0,\n 'TIMEOUT',\n `CRM request timed out after ${timeoutMs}ms`,\n err,\n { cause: err },\n );\n }\n const message =\n err instanceof Error ? err.message : 'CRM request failed (network error)';\n throw new CrmApiError(0, 'NETWORK_ERROR', message, err, { cause: err });\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n\n // Parse body (JSON when possible, else raw text).\n const text = await res.text();\n let parsed: unknown = text;\n if (text) {\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = text;\n }\n }\n\n // Treat an `{ success: false }` envelope as an error regardless of HTTP\n // status — a server can mislabel an error as 2xx.\n const isEnvelopeError = isEnvelope(parsed) && parsed.success === false;\n if (!res.ok || isEnvelopeError) {\n const { code, message } = deriveError(parsed, res.status);\n throw new CrmApiError(res.status, code, message, parsed);\n }\n\n // Unwrap `{ success, data }`.\n if (isEnvelope(parsed) && parsed.success === true) {\n return parsed.data as T;\n }\n\n // Empty 2xx body (e.g. 204 / empty DELETE) → undefined, not \"\".\n if (text === '') {\n return undefined as T;\n }\n\n // Non-enveloped 2xx response — return the raw parsed body.\n return parsed as T;\n }\n\n return {\n contacts: {\n list: (query) => request<ContactList>('GET', '/contacts', { query: query as QueryParams }),\n get: (id) => request<Contact>('GET', `/contacts/${encodeURIComponent(id)}`),\n create: (body) => request<Contact>('POST', '/contacts', { body }),\n update: (id, body) => request<Contact>('PUT', `/contacts/${encodeURIComponent(id)}`, { body }),\n delete: (id) => request<void>('DELETE', `/contacts/${encodeURIComponent(id)}`),\n },\n leads: {\n list: (query) => request<ListEnvelope<Lead>>('GET', '/leads', { query: query as QueryParams }),\n get: (id) => request<Lead>('GET', `/leads/${encodeURIComponent(id)}`),\n create: (body) => request<Lead>('POST', '/leads', { body }),\n update: (id, body) => request<Lead>('PUT', `/leads/${encodeURIComponent(id)}`, { body }),\n delete: (id) => request<void>('DELETE', `/leads/${encodeURIComponent(id)}`),\n },\n tasks: {\n list: (query) => request<ListEnvelope<Task>>('GET', '/tasks', { query: query as QueryParams }),\n create: (leadId, body) =>\n request<Task>('POST', `/leads/${encodeURIComponent(leadId)}/tasks`, { body }),\n update: (leadId, taskId, body) =>\n request<Task>(\n 'PATCH',\n `/leads/${encodeURIComponent(leadId)}/tasks/${encodeURIComponent(taskId)}`,\n { body },\n ),\n },\n products: {\n list: (query) => request<ListEnvelope<Product>>('GET', '/products', { query: query as QueryParams }),\n get: (id) => request<Product>('GET', `/products/${encodeURIComponent(id)}`),\n create: (body) => request<Product>('POST', '/products', { body }),\n update: (id, body) => request<Product>('PUT', `/products/${encodeURIComponent(id)}`, { body }),\n delete: (id) => request<void>('DELETE', `/products/${encodeURIComponent(id)}`),\n },\n conversations: {\n list: (query) =>\n request<ListEnvelope<Conversation>>('GET', '/conversations', { query: query as QueryParams }),\n get: (id) => request<Conversation>('GET', `/conversations/${encodeURIComponent(id)}`),\n update: (id, body) =>\n request<Conversation>('PUT', `/conversations/${encodeURIComponent(id)}`, { body }),\n messages: {\n list: (conversationId, query) =>\n request<ListEnvelope<Message>>(\n 'GET',\n `/conversations/${encodeURIComponent(conversationId)}/messages`,\n { query: query as QueryParams },\n ),\n send: (conversationId, body) =>\n request<Message>(\n 'POST',\n `/conversations/${encodeURIComponent(conversationId)}/messages`,\n { body },\n ),\n },\n },\n tags: {\n list: (query) => request<ListEnvelope<TagWithUsage>>('GET', '/tags', { query: query as QueryParams }),\n create: (body) => request<Tag>('POST', '/tags', { body }),\n },\n request,\n };\n}\n\nexport default createCrmApiClient;\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iBAAAE,EAAA,uBAAAC,EAAA,YAAAC,IAAA,eAAAC,EAAAL,GAoIO,IAAME,EAAN,MAAMI,UAAoB,KAAM,CAYrC,YACEC,EACAC,EACAC,E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E,KAAA1C,CAAK,CAAC,EACnF,SAAU,CACR,KAAM,CAAC6C,EAAgB1C,IACrByB,EACE,MACA,kBAAkB,mBAAmBiB,CAAc,CAAC,YACpD,CAAE,MAAO1C,CAAqB,CAChC,EACF,KAAM,CAAC0C,EAAgB7C,IACrB4B,EACE,OACA,kBAAkB,mBAAmBiB,CAAc,CAAC,YACpD,CAAE,KAAA7C,CAAK,CACT,CACJ,CACF,EACA,KAAM,CACJ,KAAOG,GAAUyB,EAAoC,MAAO,QAAS,CAAE,MAAOzB,CAAqB,CAAC,EACpG,OAASH,GAAS4B,EAAa,OAAQ,QAAS,CAAE,KAAA5B,CAAK,CAAC,CAC1D,EACA,QAAA4B,CACF,CACF,CAEA,IAAOlC,EAAQD","names":["api_exports","__export","CrmApiError","createCrmApiClient","api_default","__toCommonJS","_CrmApiError","status","code","message","body","options","serializeQuery","query","params","key","value","el","qs","isEnvelope","v","deriveError","parsed","envelope","rawError","envMessage","errorObj","errorObjCode","errorObjMessage","errorStr","opts","crmBaseUrl","accessToken","apiKey","fetchImpl","trimmed","apiBase","authHeaders","request","method","path","url","headers","hasBody","timeoutMs","controller","timedOut","timer","res","err","text","isEnvelopeError","id","leadId","taskId","conversationId"]}
|
|
1
|
+
{"version":3,"sources":["../src/api.ts"],"sourcesContent":["/**\n * Typed CRM REST API client for SaaS backends.\n *\n * Construct with `createCrmApiClient({ crmBaseUrl, accessToken | apiKey })` and\n * call typed resource methods (contacts, leads, conversations, messages, tasks,\n * products, tags) or the generic `request<T>()` escape hatch. Every method\n * returns the UNWRAPPED `data` from the CRM's `{ success, data }` envelope.\n *\n * Auth:\n * - `accessToken` (from `createEmbedSessionWithKey().data.access_token`) is\n * sent as `Authorization: Bearer <token>` and covers the full API surface.\n * The typed resource methods below hit `/api/*` routes that require this\n * **Bearer** token.\n * - `apiKey` (`crm_live_...`) is sent as `X-API-Key` and today only guards\n * `/api/public/*`. An `apiKey` client should use the generic `request()`\n * against those `/public/*` endpoints, NOT the typed resource methods.\n *\n * Error handling — every failure is thrown as a {@link CrmApiError} so callers\n * can `catch (e) { if (e instanceof CrmApiError) ... }`:\n * - non-2xx responses, AND 2xx responses the server mislabels with an\n * `{ success: false }` envelope, throw with the HTTP `status` and a code\n * derived from the body.\n * - network / DNS / connection failures throw with `status: 0` and\n * `code: 'NETWORK_ERROR'`.\n * - a request that exceeds `timeoutMs` (via `AbortController`) throws with\n * `status: 0` and `code: 'TIMEOUT'`.\n *\n * Timeouts — pass `timeoutMs` on the client (default for all requests) and/or\n * per request. If unset there is no timeout.\n *\n * @packageDocumentation\n */\n\nimport type {\n Contact,\n ContactCreate,\n ContactUpdate,\n ContactQuery,\n ContactList,\n Lead,\n LeadCreate,\n LeadUpdate,\n LeadQuery,\n LegacyTask,\n LegacyTaskUpdate,\n Task,\n TaskQuery,\n Conversation,\n ConversationQuery,\n ConversationUpdate,\n Message,\n MessageQuery,\n MessageCreate,\n Product,\n ProductCreate,\n ProductUpdate,\n ProductQuery,\n Tag,\n TagCreate,\n TagQuery,\n TagWithUsage,\n ListEnvelope,\n} from './generated/crm-contracts';\n\nexport type * from './generated/crm-contracts';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\ntype FetchLike = typeof fetch;\n\n/** Options for {@link createCrmApiClient}. Exactly one of accessToken / apiKey. */\nexport interface CrmApiClientOptions {\n /** Base URL of the CRM, e.g. `https://crm.example.com` (no trailing `/api`). */\n crmBaseUrl: string;\n /** Bearer token from `createEmbedSessionWithKey` — full API surface. */\n accessToken?: string;\n /** Server-to-server API key (`crm_live_...`) — `/api/public/*` only today. */\n apiKey?: string;\n /** Custom fetch implementation (e.g. for Node < 18 or testing). */\n fetch?: FetchLike;\n /**\n * Default per-request timeout in milliseconds, enforced via `AbortController`.\n * On timeout the request throws a {@link CrmApiError} (`status: 0`,\n * `code: 'TIMEOUT'`). If unset (default), requests have no timeout.\n */\n timeoutMs?: number;\n}\n\n/** CRM success envelope. */\ninterface SuccessEnvelope<T> {\n success: true;\n data: T;\n message?: string;\n meta?: Record<string, unknown>;\n}\n\n/** CRM error envelope. */\ninterface ErrorEnvelope {\n success: false;\n error: string;\n message?: string;\n details?: string;\n}\n\ntype QueryPrimitive = string | number | boolean;\ntype QueryValue =\n | QueryPrimitive\n | Array<QueryPrimitive>\n | undefined\n | null;\ntype QueryParams = Record<string, QueryValue>;\n\ninterface RequestOptions {\n query?: QueryParams;\n body?: unknown;\n /**\n * Per-request timeout in milliseconds (overrides the client `timeoutMs`).\n * On timeout the request throws a {@link CrmApiError} (`status: 0`,\n * `code: 'TIMEOUT'`).\n */\n timeoutMs?: number;\n}\n\n/**\n * Error thrown for any failed CRM request:\n * - a non-2xx HTTP response,\n * - a 2xx response carrying an `{ success: false }` envelope (server mislabel),\n * - a network/DNS/connection failure (`status: 0`, `code: 'NETWORK_ERROR'`),\n * - a timeout / abort (`status: 0`, `code: 'TIMEOUT'`).\n */\nexport class CrmApiError extends Error {\n /** HTTP status code (0 for network errors / timeouts). */\n readonly status: number;\n /**\n * Machine-readable code. For envelope errors: the object `error.code`, else\n * the string `error`, else `HTTP_<status>`. For transport failures:\n * `NETWORK_ERROR` or `TIMEOUT`.\n */\n readonly code: string;\n /** Parsed response body, or the underlying error for transport failures. */\n readonly body: unknown;\n\n constructor(\n status: number,\n code: string,\n message: string,\n body: unknown,\n options?: { cause?: unknown },\n ) {\n super(message);\n this.name = 'CrmApiError';\n this.status = status;\n this.code = code;\n this.body = body;\n // Preserve the underlying error (network/abort) without requiring the\n // ES2022 `cause` constructor option.\n if (options && 'cause' in options) {\n (this as { cause?: unknown }).cause = options.cause;\n }\n Object.setPrototypeOf(this, CrmApiError.prototype);\n }\n}\n\n/** The client returned by {@link createCrmApiClient}. */\nexport interface CrmApiClient {\n contacts: {\n list(query?: ContactQuery): Promise<ContactList>;\n get(id: string): Promise<Contact>;\n create(body: ContactCreate): Promise<Contact>;\n update(id: string, body: ContactUpdate): Promise<Contact>;\n delete(id: string): Promise<void>;\n };\n leads: {\n list(query?: LeadQuery): Promise<ListEnvelope<Lead>>;\n get(id: string): Promise<Lead>;\n create(body: LeadCreate): Promise<Lead>;\n update(id: string, body: LeadUpdate): Promise<Lead>;\n delete(id: string): Promise<void>;\n };\n tasks: {\n list(query?: TaskQuery): Promise<ListEnvelope<Task>>;\n /** @deprecated Updates only existing legacy Lead Tasks. Update Activity tasks through `/activities/:id`. */\n update(leadId: string, taskId: string, body: LegacyTaskUpdate): Promise<LegacyTask>;\n };\n products: {\n list(query?: ProductQuery): Promise<ListEnvelope<Product>>;\n get(id: string): Promise<Product>;\n create(body: ProductCreate): Promise<Product>;\n update(id: string, body: ProductUpdate): Promise<Product>;\n delete(id: string): Promise<void>;\n };\n conversations: {\n list(query?: ConversationQuery): Promise<ListEnvelope<Conversation>>;\n get(id: string): Promise<Conversation>;\n update(id: string, body: ConversationUpdate): Promise<Conversation>;\n messages: {\n list(\n conversationId: string,\n query?: MessageQuery,\n ): Promise<ListEnvelope<Message>>;\n send(conversationId: string, body: MessageCreate): Promise<Message>;\n };\n };\n tags: {\n list(query?: TagQuery): Promise<ListEnvelope<TagWithUsage>>;\n create(body: TagCreate): Promise<Tag>;\n };\n /** Generic escape hatch — returns the unwrapped `data` typed as `T`. */\n request<T>(\n method: string,\n path: string,\n options?: RequestOptions,\n ): Promise<T>;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Serialize query params. Array values are appended as repeated params\n * (`?tag=a&tag=b`); `undefined`/`null` values (and array elements) are skipped.\n *\n * NOTE on the CRM's `tags` filter: the CRM's contacts/leads query schemas expect\n * `tags` as a single comma-separated string (`?tags=a,b`), which the server\n * splits on `,`. If you pass `tags` as an array here it becomes repeated params\n * (`?tags=a&tags=b`), which those endpoints will NOT parse as multiple tags —\n * pass a comma-joined string for that specific field. All other core query\n * fields are primitives. No core query field is a nested object.\n */\nfunction serializeQuery(query?: QueryParams): string {\n if (!query) return '';\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue;\n if (Array.isArray(value)) {\n for (const el of value) {\n if (el === undefined || el === null) continue;\n params.append(key, String(el));\n }\n } else {\n params.append(key, String(value));\n }\n }\n const qs = params.toString();\n return qs ? `?${qs}` : '';\n}\n\nfunction isEnvelope(v: unknown): v is SuccessEnvelope<unknown> | ErrorEnvelope {\n return typeof v === 'object' && v !== null && 'success' in v;\n}\n\n/** Derive `{ code, message }` from a parsed CRM error envelope + HTTP status. */\nfunction deriveError(parsed: unknown, status: number): { code: string; message: string } {\n const envelope =\n isEnvelope(parsed) && parsed.success === false\n ? (parsed as ErrorEnvelope & { error?: unknown })\n : undefined;\n const rawError: unknown = envelope?.error;\n const envMessage =\n typeof envelope?.message === 'string' ? envelope.message : undefined;\n\n // error can be a string (\"human string\" or a code) OR an object { code, message }.\n const errorObj =\n rawError && typeof rawError === 'object'\n ? (rawError as { code?: unknown; message?: unknown })\n : undefined;\n const errorObjCode =\n typeof errorObj?.code === 'string' ? errorObj.code : undefined;\n const errorObjMessage =\n typeof errorObj?.message === 'string' ? errorObj.message : undefined;\n const errorStr = typeof rawError === 'string' ? rawError : undefined;\n\n const code = errorObjCode ?? errorStr ?? `HTTP_${status}`;\n const message =\n errorObjMessage ??\n envMessage ??\n errorStr ??\n `CRM request failed with status ${status}`;\n\n return { code, message };\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\nexport function createCrmApiClient(opts: CrmApiClientOptions): CrmApiClient {\n const { crmBaseUrl, accessToken, apiKey } = opts;\n\n if (!accessToken && !apiKey) {\n throw new Error(\n 'createCrmApiClient: exactly one of `accessToken` or `apiKey` is required (got neither).',\n );\n }\n if (accessToken && apiKey) {\n throw new Error(\n 'createCrmApiClient: provide only one of `accessToken` or `apiKey` (got both).',\n );\n }\n\n const fetchImpl: FetchLike = opts.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== 'function') {\n throw new Error(\n 'createCrmApiClient: no fetch implementation available. Pass `fetch` explicitly.',\n );\n }\n\n // Normalize base: strip trailing slash, then ensure it ends with `/api`.\n const trimmed = crmBaseUrl.replace(/\\/+$/, '');\n const apiBase = trimmed.endsWith('/api') ? trimmed : `${trimmed}/api`;\n\n const authHeaders: Record<string, string> = accessToken\n ? { Authorization: `Bearer ${accessToken}` }\n : { 'X-API-Key': apiKey as string };\n\n async function request<T>(\n method: string,\n path: string,\n options: RequestOptions = {},\n ): Promise<T> {\n const url = `${apiBase}${path}${serializeQuery(options.query)}`;\n const headers: Record<string, string> = { ...authHeaders };\n const hasBody = options.body !== undefined;\n if (hasBody) headers['Content-Type'] = 'application/json';\n\n const timeoutMs = options.timeoutMs ?? opts.timeoutMs;\n const controller =\n timeoutMs !== undefined ? new AbortController() : undefined;\n let timedOut = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n if (controller && timeoutMs !== undefined) {\n timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs);\n }\n\n let res: Response;\n try {\n res = await fetchImpl(url, {\n method,\n headers,\n body: hasBody ? JSON.stringify(options.body) : undefined,\n signal: controller?.signal,\n });\n } catch (err) {\n // Network error, DNS failure, connection refused, or abort/timeout.\n if (\n timedOut ||\n (err instanceof Error && err.name === 'AbortError')\n ) {\n throw new CrmApiError(\n 0,\n 'TIMEOUT',\n `CRM request timed out after ${timeoutMs}ms`,\n err,\n { cause: err },\n );\n }\n const message =\n err instanceof Error ? err.message : 'CRM request failed (network error)';\n throw new CrmApiError(0, 'NETWORK_ERROR', message, err, { cause: err });\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n\n // Parse body (JSON when possible, else raw text).\n const text = await res.text();\n let parsed: unknown = text;\n if (text) {\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = text;\n }\n }\n\n // Treat an `{ success: false }` envelope as an error regardless of HTTP\n // status — a server can mislabel an error as 2xx.\n const isEnvelopeError = isEnvelope(parsed) && parsed.success === false;\n if (!res.ok || isEnvelopeError) {\n const { code, message } = deriveError(parsed, res.status);\n throw new CrmApiError(res.status, code, message, parsed);\n }\n\n // Unwrap `{ success, data }`.\n if (isEnvelope(parsed) && parsed.success === true) {\n return parsed.data as T;\n }\n\n // Empty 2xx body (e.g. 204 / empty DELETE) → undefined, not \"\".\n if (text === '') {\n return undefined as T;\n }\n\n // Non-enveloped 2xx response — return the raw parsed body.\n return parsed as T;\n }\n\n return {\n contacts: {\n list: (query) => request<ContactList>('GET', '/contacts', { query: query as QueryParams }),\n get: (id) => request<Contact>('GET', `/contacts/${encodeURIComponent(id)}`),\n create: (body) => request<Contact>('POST', '/contacts', { body }),\n update: (id, body) => request<Contact>('PUT', `/contacts/${encodeURIComponent(id)}`, { body }),\n delete: (id) => request<void>('DELETE', `/contacts/${encodeURIComponent(id)}`),\n },\n leads: {\n list: (query) => request<ListEnvelope<Lead>>('GET', '/leads', { query: query as QueryParams }),\n get: (id) => request<Lead>('GET', `/leads/${encodeURIComponent(id)}`),\n create: (body) => request<Lead>('POST', '/leads', { body }),\n update: (id, body) => request<Lead>('PUT', `/leads/${encodeURIComponent(id)}`, { body }),\n delete: (id) => request<void>('DELETE', `/leads/${encodeURIComponent(id)}`),\n },\n tasks: {\n list: (query) => request<ListEnvelope<Task>>('GET', '/tasks', { query: query as QueryParams }),\n update: (leadId, taskId, body) =>\n request<LegacyTask>(\n 'PATCH',\n `/leads/${encodeURIComponent(leadId)}/tasks/${encodeURIComponent(taskId)}`,\n { body },\n ),\n },\n products: {\n list: (query) => request<ListEnvelope<Product>>('GET', '/products', { query: query as QueryParams }),\n get: (id) => request<Product>('GET', `/products/${encodeURIComponent(id)}`),\n create: (body) => request<Product>('POST', '/products', { body }),\n update: (id, body) => request<Product>('PUT', `/products/${encodeURIComponent(id)}`, { body }),\n delete: (id) => request<void>('DELETE', `/products/${encodeURIComponent(id)}`),\n },\n conversations: {\n list: (query) =>\n request<ListEnvelope<Conversation>>('GET', '/conversations', { query: query as QueryParams }),\n get: (id) => request<Conversation>('GET', `/conversations/${encodeURIComponent(id)}`),\n update: (id, body) =>\n request<Conversation>('PUT', `/conversations/${encodeURIComponent(id)}`, { body }),\n messages: {\n list: (conversationId, query) =>\n request<ListEnvelope<Message>>(\n 'GET',\n `/conversations/${encodeURIComponent(conversationId)}/messages`,\n { query: query as QueryParams },\n ),\n send: (conversationId, body) =>\n request<Message>(\n 'POST',\n `/conversations/${encodeURIComponent(conversationId)}/messages`,\n { body },\n ),\n },\n },\n tags: {\n list: (query) => request<ListEnvelope<TagWithUsage>>('GET', '/tags', { query: query as QueryParams }),\n create: (body) => request<Tag>('POST', '/tags', { body }),\n },\n request,\n };\n}\n\nexport default createCrmApiClient;\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iBAAAE,EAAA,uBAAAC,EAAA,YAAAC,IAAA,eAAAC,EAAAL,GAoIO,IAAME,EAAN,MAAMI,UAAoB,KAAM,CAYrC,YACEC,EACAC,EACAC,EACAC,EACAC,EACA,CACA,MAAMF,CAAO,EACb,KAAK,KAAO,cACZ,KAAK,OAASF,EACd,KAAK,KAAOC,EACZ,KAAK,KAAOE,EAGRC,GAAW,UAAWA,IACvB,KAA6B,MAAQA,EAAQ,OAEhD,OAAO,eAAe,KAAML,EAAY,SAAS,CACnD,CACF,EAqEA,SAASM,EAAeC,EAA6B,CACnD,GAAI,CAACA,EAAO,MAAO,GACnB,IAAMC,EAAS,IAAI,gBACnB,OAAW,CAACC,EAAKC,CAAK,IAAK,OAAO,QAAQH,CAAK,EAC7C,GAA2BG,GAAU,KACrC,GAAI,MAAM,QAAQA,CAAK,EACrB,QAAWC,KAAMD,EACSC,GAAO,MAC/BH,EAAO,OAAOC,EAAK,OAAOE,CAAE,CAAC,OAG/BH,EAAO,OAAOC,EAAK,OAAOC,CAAK,CAAC,EAGpC,IAAME,EAAKJ,EAAO,SAAS,EAC3B,OAAOI,EAAK,IAAIA,CAAE,GAAK,EACzB,CAEA,SAASC,EAAWC,EAA2D,CAC7E,OAAO,OAAO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AiB,OAAQ,YAAa,CAAE,KAAA5B,CAAK,CAAC,EAChE,OAAQ,CAAC0C,EAAI1C,IAAS4B,EAAiB,MAAO,aAAa,mBAAmBc,CAAE,CAAC,GAAI,CAAE,KAAA1C,CAAK,CAAC,EAC7F,OAAS0C,GAAOd,EAAc,SAAU,aAAa,mBAAmBc,CAAE,CAAC,EAAE,CAC/E,EACA,cAAe,CACb,KAAOvC,GACLyB,EAAoC,MAAO,iBAAkB,CAAE,MAAOzB,CAAqB,CAAC,EAC9F,IAAMuC,GAAOd,EAAsB,MAAO,kBAAkB,mBAAmBc,CAAE,CAAC,EAAE,EACpF,OAAQ,CAACA,EAAI1C,IACX4B,EAAsB,MAAO,kBAAkB,mBAAmBc,CAAE,CAAC,GAAI,CAAE,KAAA1C,CAAK,CAAC,EACnF,SAAU,CACR,KAAM,CAAC6C,EAAgB1C,IACrByB,EACE,MACA,kBAAkB,mBAAmBiB,CAAc,CAAC,YACpD,CAAE,MAAO1C,CAAqB,CAChC,EACF,KAAM,CAAC0C,EAAgB7C,IACrB4B,EACE,OACA,kBAAkB,mBAAmBiB,CAAc,CAAC,YACpD,CAAE,KAAA7C,CAAK,CACT,CACJ,CACF,EACA,KAAM,CACJ,KAAOG,GAAUyB,EAAoC,MAAO,QAAS,CAAE,MAAOzB,CAAqB,CAAC,EACpG,OAASH,GAAS4B,EAAa,OAAQ,QAAS,CAAE,KAAA5B,CAAK,CAAC,CAC1D,EACA,QAAA4B,CACF,CACF,CAEA,IAAOlC,EAAQD","names":["api_exports","__export","CrmApiError","createCrmApiClient","api_default","__toCommonJS","_CrmApiError","status","code","message","body","options","serializeQuery","query","params","key","value","el","qs","isEnvelope","v","deriveError","parsed","envelope","rawError","envMessage","errorObj","errorObjCode","errorObjMessage","errorStr","opts","crmBaseUrl","accessToken","apiKey","fetchImpl","trimmed","apiBase","authHeaders","request","method","path","url","headers","hasBody","timeoutMs","controller","timedOut","timer","res","err","text","isEnvelopeError","id","leadId","taskId","conversationId"]}
|