@first-to-fly/crm-sdk 1.10.0 → 1.12.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
@@ -6,7 +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
+ | **Provision workspaces, sync contacts, run the partner message channel and verify its webhook from your backend** | `@first-to-fly/crm-sdk/partner` | server only |
10
10
 
11
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).
12
12
 
@@ -281,6 +281,9 @@ const crm = createCrmApiClient({
281
281
  const { items } = await crm.contacts.list({ page: 1, pageSize: 25 });
282
282
  ```
283
283
 
284
+ If you build your own chat screen, read each conversation's `send_policy` to know
285
+ whether a reply may be sent. See [Can a reply be sent?](#can-a-reply-be-sent-send_policy).
286
+
284
287
  #### Environment checklist
285
288
 
286
289
  | Where | Variable | Notes |
@@ -563,11 +566,18 @@ With `hostProvidesNav`, render your own nav and call the ref's `navigate(path)`
563
566
  | Contacts | `/contacts` | detail at `/contacts/:id`; `/contacts/email-suppressions` |
564
567
  | Leads (pipeline) | `/leads` | `/pipelines` is an alias; detail at `/leads/:id` |
565
568
  | 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.
569
+ | Settings | `/settings` | opens `/settings/profile`; also `/settings/business`, `/settings/appearance`; shows links to the sections below |
570
+ | Channels (connect WhatsApp and others) | `/settings/channels` | `/settings/channels/signatures` for email signatures |
571
+ | AI replies | `/conversation-ai` | opens `/conversation-ai/summary`; also `/intent`, `/auto-reply`, `/suggestion`, `/assistant`, `/models` |
572
+ | AI agents | `/ai-agents` | `/ai-agents/add`, `/ai-agents/:id`, `/ai-agents/:id/edit`, `/ai-agents/:id/playground` |
573
+ | Automations | `/automations` | `/automations/:id`, `/automations/:id/edit` |
574
+ | Templates | `/templates` | |
575
+ | Knowledge bases | `/knowledge-bases` | `/knowledge-bases/:id`, `/knowledge-bases/:id/articles/new`, `/knowledge-bases/:id/articles/:documentId` |
576
+
577
+ Everything the school sets up itself is reachable. External tools, billing, members,
578
+ API keys, apps, imports and exports are not routes of the embed. Pages and options the
579
+ workspace's plan or product-managed policy does not include (for example workflow web
580
+ calls, lead creation and incoming webhooks) are hidden or rejected by the CRM itself.
571
581
 
572
582
  `onRouteChange(path)` is the navigation event: it fires on first load and on every
573
583
  in-frame navigation with the sub-path under the embed base (for example `/`, `/comms`,
@@ -772,6 +782,209 @@ Request and response types (`ContactRefUpsertBody`, `ContactRefUpsertResult`,
772
782
  `ContactChanges`, `ContactChangesQuery`, `PartnerContactEraseResult`) are generated
773
783
  from the CRM's contracts and exported from `@first-to-fly/crm-sdk/partner`.
774
784
 
785
+ ### Partner message channel
786
+
787
+ A product that has its own in-app messages can hand its customers' messages to the CRM.
788
+ Staff reply in the CRM inbox, and each reply comes back to your product as a signed webhook
789
+ and from a change feed. Messages are keyed by your own ids: `contactRef` (the person, as in
790
+ contact sync), `threadRef` (the conversation) and `messageRef` (the message). Everything
791
+ here uses the **partner key** and runs on your server.
792
+
793
+ #### 1. Enable the channel
794
+
795
+ ```typescript
796
+ await partner.updateWorkspace('tenant_1', { partnerChannelEnabled: true }); // or on upsertWorkspace
797
+ ```
798
+
799
+ With the channel off, message pushes are refused with `409` / `PARTNER_CHANNEL_DISABLED`.
800
+ The feed, the webhook methods and thread deletion still work.
801
+
802
+ #### 2. Register the webhook
803
+
804
+ ```typescript
805
+ const { url, secret } = await partner.setWebhook({ url: 'https://partner.example/hooks/crm' });
806
+ if (secret) await saveWebhookSecret(secret); // returned only the first time: store it
807
+
808
+ await partner.getWebhook(); // { url, hasSecret: true } or null. Never returns the secret
809
+ const rotated = await partner.rotateWebhookSecret(); // { secret }: the old secret stops working at once, with no overlap
810
+ await partner.deleteWebhook(); // resolves also when none is registered
811
+ ```
812
+
813
+ - The URL must be `https`. Plain `http` to localhost is accepted only by a CRM running in
814
+ local development or test.
815
+ - Registration does not check where the URL points. A delivery to a host that resolves to a
816
+ private, loopback, link-local or otherwise non-public address, or to `localhost`,
817
+ `*.localhost` or `*.local`, is not sent and counts as a failed attempt. URLs with credentials
818
+ (`https://user:pass@...`) and URLs over 2048 characters are refused with 400.
819
+ - `deleteWebhook` removes the registration. A per-workspace `webhookUrl` override (set on the
820
+ workspace upsert or patch) is kept and applies again if a webhook is registered later.
821
+
822
+ #### 3. Push a message
823
+
824
+ ```typescript
825
+ const { conversationId, messageId, created } = await partner.sendPartnerMessage('tenant_1', {
826
+ contactRef: 'customer:1', // must already be synced with upsertContact
827
+ threadRef: 'thread:1',
828
+ messageRef: 'msg:1',
829
+ body: 'Hello, I would like to change my booking.', // plain text, 1 to 10,000 characters
830
+ sentAt: new Date(), // a Date, or ISO 8601 with an offset
831
+ title: 'Booking change', // optional
832
+ teamRef: 'team:1', // optional; the team is created if new
833
+ });
834
+ ```
835
+
836
+ Idempotent on `messageRef`: a repeat returns the same ids with `created: false` and changes
837
+ nothing. Failures are `CrmPartnerError` with these codes:
838
+
839
+ | `code` | Status | What to do |
840
+ |---|---|---|
841
+ | `NOT_FOUND` | 404 | The workspace is unknown. Check `externalRef`. |
842
+ | `VALIDATION_ERROR` | 400 | A field is invalid (for example a ref outside `[A-Za-z0-9._:-]{1,200}`, or an empty or over-long `body`). Fix the request; retrying does not help. |
843
+ | `CONTACT_NOT_FOUND` | 404 | The contact is not synced (or was deleted in the CRM). Sync it with `upsertContact`, then retry. |
844
+ | `PARTNER_CHANNEL_DISABLED`, `WORKSPACE_DISABLED` | 409 | The channel or the workspace is switched off. Retry once it is switched on again. |
845
+ | `MESSAGE_REF_CONFLICT` | 409 | The `messageRef` is already used on another thread. Retrying does not help; use a new `messageRef`. |
846
+ | `THREAD_CONTACT_MISMATCH` | 409 | The thread belongs to another contact. Retrying does not help; use a new `threadRef`. |
847
+ | `RATE_LIMITED` | 429 | More than 300 pushes in 60 seconds for this workspace (every call counts). Wait and retry. |
848
+ | `SERVICE_BUSY` | 503 | The CRM is busy. Wait and retry. |
849
+
850
+ A `sentAt` more than 5 minutes ahead of the CRM's clock is replaced by the server time. All
851
+ partner calls also share a limit of 120 a minute per IP. 429 and 503 carry a `Retry-After`
852
+ header (see "Retrying" below).
853
+
854
+ #### 4. Receive staff replies by webhook
855
+
856
+ Verify the request with `verifyPartnerWebhook` on the **raw body**, exactly the bytes
857
+ received. A framework that parses the JSON and serialises it again changes the bytes and the
858
+ signature no longer matches. With Express, keep the raw body for this route:
859
+
860
+ ```typescript
861
+ import express from 'express';
862
+ import { verifyPartnerWebhook, PartnerWebhookVerificationError } from '@first-to-fly/crm-sdk/partner';
863
+
864
+ const app = express();
865
+
866
+ app.post('/hooks/crm', express.raw({ type: 'application/json', limit: '1mb' }), async (req, res) => {
867
+ try {
868
+ const event = verifyPartnerWebhook({
869
+ rawBody: req.body.toString('utf8'), // a Buffer, because of express.raw
870
+ headers: req.headers,
871
+ secret: await loadWebhookSecret(),
872
+ // toleranceSeconds: 300 (default)
873
+ });
874
+ // Deduplicate on messageId: the same reply can arrive more than once.
875
+ await saveReplyOnce(event.messageId, event); // event.threadRef, event.body, event.sender.name, ...
876
+ res.sendStatus(204); // only now: the event is saved
877
+ } catch (error) {
878
+ if (error instanceof PartnerWebhookVerificationError) {
879
+ res.sendStatus(401);
880
+ return;
881
+ }
882
+ res.sendStatus(500); // the CRM retries
883
+ }
884
+ });
885
+ ```
886
+
887
+ The event is `{ event: 'partner_message.sent', deliveryId, externalRef, threadRef,
888
+ conversationId, messageId, body, sentAt, sender: { userRef, name } }`. `sender.userRef` is
889
+ `null` when the staff member has no id of yours. `verifyPartnerWebhook` checks, in this order:
890
+ both headers are present (`missing_headers`), the timestamp is within the tolerance of now in
891
+ either direction (`stale_timestamp`), the signature matches (`bad_signature`) and only then
892
+ that the body is the expected event (`bad_payload`). The error's `reason` carries the reason;
893
+ its message never contains the secret, the signature or the body. A present but malformed
894
+ timestamp counts as stale; a missing one is `missing_headers`. Passing an empty secret, a non-string body or a non-finite or
895
+ negative `toleranceSeconds` is a bug in your code and throws a `TypeError`, not a verification
896
+ error.
897
+
898
+ - Answer `2xx` only after the event is durably saved. The whole response, body included, must
899
+ finish within 10 seconds and the response body must be at most 64 KB (65,536 bytes). A `2xx`
900
+ with a larger body counts as a failed attempt and the reply is sent again. Send an empty
901
+ body. Any other status, any redirect and any timeout also counts as a failed attempt.
902
+ - A failed attempt is retried after 30 seconds, doubling up to 30 minutes, for 24 hours from
903
+ when the reply was sent. If nothing accepts the reply in that time, staff see it as failed
904
+ to send.
905
+ - Deduplicate on `messageId` (or `deliveryId`): the same reply can arrive more than once,
906
+ and can arrive both by the webhook and by the feed.
907
+ - Reply bodies can be long.
908
+ - A delivery for a thread you have just deleted can still arrive for up to about 10 seconds (an
909
+ attempt already in flight). Drop it instead of recreating the thread.
910
+
911
+ #### 5. Reconcile with the feed
912
+
913
+ The feed lists every staff reply, oldest first, so you can catch anything the webhook missed.
914
+
915
+ ```typescript
916
+ async function pollReplies(tenantId: string) {
917
+ let cursor = (await loadCursor(tenantId)) ?? undefined; // undefined on the very first poll
918
+ while (true) {
919
+ const page = await partner.listPartnerMessageChanges(tenantId, { cursor, limit: 100 });
920
+ if (page.items.length === 0) {
921
+ // Same cursor back: keep it for the next poll. Null only when there was no cursor and no rows.
922
+ if (page.nextCursor) await saveCursor(tenantId, page.nextCursor);
923
+ return;
924
+ }
925
+ for (const reply of page.items) await saveReplyOnce(reply.messageId, reply); // persist first
926
+ await saveCursor(tenantId, page.nextCursor!); // ...then advance; the next call acknowledges this page
927
+ cursor = page.nextCursor!;
928
+ }
929
+ }
930
+ ```
931
+
932
+ - Presenting a `cursor` acknowledges every row before it, so save a page durably before calling
933
+ again with its `nextCursor`. Loop until `items` is empty and store the cursor that last call
934
+ returns for the next poll. `nextCursor` is `null` only when no cursor was sent and there are
935
+ no rows.
936
+ - Never construct a cursor, and never reuse one across workspaces. A `400` /
937
+ `VALIDATION_ERROR` on a stored cursor means drop it and start again with none.
938
+ - Rows are kept 30 days. A reply appears a few seconds after it is sent, so an empty page does
939
+ not mean nothing is pending.
940
+ - `delivered` rows are included. A call with no cursor re-reads the retained rows and
941
+ acknowledges nothing, so it works as a periodic reconcile; deduplicate on `messageId`.
942
+ - `deliveryStatus` is `pending` (still owed to you), `delivered` (taken by your webhook or
943
+ acknowledged through the feed) or `failed` (not taken within 24 hours; staff see it as not
944
+ sent). Paging past a `failed` row marks it delivered and returns the message to sent.
945
+ - A feed-only integration (no webhook) must poll at least a few times a day: a reply not
946
+ taken within 24 hours shows as failed to staff, and the last page is acknowledged only by
947
+ the following call.
948
+ - An erased thread or contact disappears from the feed, so absence does not mean the reply was
949
+ never sent.
950
+
951
+ #### 6. Delete a thread
952
+
953
+ ```typescript
954
+ const { deleted } = await partner.deletePartnerConversation('tenant_1', 'thread:1');
955
+ ```
956
+
957
+ Permanently deletes the conversation, its messages and any replies still owed to you; the
958
+ contact stays. It is idempotent (`deleted: false` when nothing matched). Cancel your own
959
+ pending retries for that thread first: a later push with the same `threadRef` creates a new
960
+ conversation. Erasing a contact (`eraseContact`) also deletes that contact's threads on this
961
+ channel.
962
+
963
+ #### Retrying
964
+
965
+ `429` carries `Retry-After: 60` (the limit window) and `503` carries `Retry-After: 5`.
966
+ `CrmPartnerError` carries `status` and `code` only and does not expose the header, so use
967
+ those values: retry `429` (`RATE_LIMITED`) after about 60 seconds and `503` (`SERVICE_BUSY`)
968
+ after about 5, and retry `status` `0` (network or timeout) the same way. The 120 a minute
969
+ per-IP limit covers every partner call from that address, so a single server reaches it before
970
+ the 300 a minute per-workspace push limit.
971
+
972
+ ```typescript
973
+ async function sendWithRetry(input: PartnerMessageInput) {
974
+ for (let attempt = 0; ; attempt++) {
975
+ try {
976
+ return await partner.sendPartnerMessage('tenant_1', input);
977
+ } catch (error) {
978
+ if (!(error instanceof CrmPartnerError) || ![0, 429, 503].includes(error.status) || attempt >= 5) throw error;
979
+ const waitMs = error.status === 429 ? 60_000 : 5_000 * 2 ** attempt; // Retry-After: 60 / 5
980
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
981
+ }
982
+ }
983
+ }
984
+ ```
985
+
986
+ Repeating a push is safe: it is idempotent on `messageRef`.
987
+
775
988
  ## Calling CRM APIs from your backend
776
989
 
777
990
  Once your server has a CRM bearer (from `createEmbedSessionWithKey`) — or an
@@ -788,7 +1001,7 @@ against the `/public/*` endpoints (see [Server-to-server](#server-to-server-with
788
1001
 
789
1002
  | Case | `status` | `code` |
790
1003
  |---|---|---|
791
- | non-2xx response | the HTTP status | `error.code` / `error` string / `HTTP_<status>` |
1004
+ | non-2xx response | the HTTP status | `error.code` / top-level `code` / `error` string / `HTTP_<status>` |
792
1005
  | 2xx with `{ success: false }` (server mislabel) | the HTTP status (e.g. 200) | as above |
793
1006
  | network / DNS / connection failure | `0` | `NETWORK_ERROR` |
794
1007
  | request exceeded `timeoutMs` | `0` | `TIMEOUT` |
@@ -849,6 +1062,69 @@ try {
849
1062
  }
850
1063
  ```
851
1064
 
1065
+ ### Can a reply be sent? `send_policy`
1066
+
1067
+ Every conversation the CRM returns (`crm.conversations.list`, `.get`, and the
1068
+ other conversation responses) carries `send_policy`. It says what may be sent in
1069
+ that conversation right now. The CRM builds it from the rules its send check
1070
+ enforces for the window, consent and blocking (the window and consent parts are
1071
+ the same code), so you do not have to copy those rules into your app.
1072
+
1073
+ | Field | Meaning |
1074
+ |---|---|
1075
+ | `free_text` | `'open'` when a normal reply may be sent now, else `'closed'`. |
1076
+ | `window` | `'24h'` when replies are only allowed for 24 hours after the contact's last message on this channel. `'none'` when there is no time limit. |
1077
+ | `closes_at` | When the 24-hour window closes (ISO time). It stays set, in the past, after the window has closed. `null` when `window` is `'none'` or the contact has not messaged yet. |
1078
+ | `reason` | Why `free_text` is `'closed'`: `blocked` (contact or conversation is blocked), `suppressed` (email only: the contact's address is on the workspace's Do Not Email list), `opted_out` (contact opted out of WhatsApp), `consent_required` (contact has not opted in to WhatsApp and is outside the 24 hours), `window_closed`, `no_inbound_message` (the contact has never messaged on this channel), `not_supported` (SMS and voice have no reply). `null` when open. |
1079
+ | `template` | `true` when an approved WhatsApp template may be sent. Only official WhatsApp has templates. |
1080
+ | `template_reason` | Set when WhatsApp consent is the only thing stopping a template: `consent_required` or `opted_out`. Otherwise `null`. |
1081
+ | `human_agent` | Messenger only. `available`: the 24 hours have passed and the contact messaged within 7 days, so a reply with the Human Agent tag is allowed. `enabled`: the conversation's Human Agent switch is on and `available` is true. `expires_at`: the contact's last message plus 7 days. Human Agent never makes `free_text` `'open'`: the send must carry `tag: 'HUMAN_AGENT'` and `messaging_type: 'MESSAGE_TAG'`. |
1082
+
1083
+ How to use it:
1084
+
1085
+ - Show a reply box when `free_text` is `'open'`.
1086
+ - Offer a template when `template` is `true`.
1087
+ - Show `closes_at` as the time replies close. If it has passed while your screen
1088
+ was open, treat the conversation as closed and read it again.
1089
+ - When `free_text` is `'closed'`, use `reason` to tell the user why.
1090
+ - Do not work the window out yourself from `metadata.is_within_24h_window` or
1091
+ `channel_info.channel_windows`. Those fields stay for older clients;
1092
+ `is_within_24h_window` is true when any channel is inside its window, not the
1093
+ one being replied on.
1094
+
1095
+ ```typescript
1096
+ const conversation = await crm.conversations.get(conversationId);
1097
+ const { free_text, closes_at, reason, template } = conversation.send_policy;
1098
+
1099
+ if (free_text === 'open') {
1100
+ // show the reply box; if closes_at is set, replies close at that time
1101
+ } else if (template) {
1102
+ // WhatsApp outside the 24 hours: only a template can be sent
1103
+ } else {
1104
+ // no reply possible: explain with `reason`
1105
+ }
1106
+ ```
1107
+
1108
+ Channels with no time limit: email, WhatsApp Web, web chat, Telegram, website
1109
+ forms and the partner app channel. Official WhatsApp, Messenger and Instagram
1110
+ have the 24-hour window.
1111
+
1112
+ In a product-managed workspace, WhatsApp consent also applies on official
1113
+ WhatsApp and WhatsApp Web (WhatsApp Web groups are exempt). A contact who opted
1114
+ out gets nothing. A contact who has not opted in can be answered with free text
1115
+ for 24 hours after their last message, and cannot be sent a template; on
1116
+ WhatsApp Web this is the one case where `window` is `'24h'`.
1117
+
1118
+ The policy describes the conversation on its own channel (`metadata.channel`).
1119
+ For a merged conversation that is the channel of the conversation you read, not
1120
+ of the other conversations merged into it.
1121
+
1122
+ The server still checks every send, and it checks more than the policy states:
1123
+ the channel may be disconnected, the contact may have no address on that channel,
1124
+ or the window may have closed since you read the policy. So a send can still be
1125
+ refused when the policy said open. Handle the error from `messages.send` as
1126
+ before.
1127
+
852
1128
  ### Server-to-server with an API key
853
1129
 
854
1130
  For machine-to-machine calls you can pass an `X-API-Key` instead of a bearer:
package/dist/api.cjs CHANGED
@@ -1,2 +1,2 @@
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});
1
+ "use strict";var E=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var $=Object.prototype.hasOwnProperty;var I=(s,r)=>{for(var n in r)E(s,n,{get:r[n],enumerable:!0})},O=(s,r,n,a)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of q(r))!$.call(s,o)&&o!==n&&E(s,o,{get:()=>r[o],enumerable:!(a=Q(r,o))||a.enumerable});return s};var M=s=>O(E({},"__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(r,n,a,o,c){super(a),this.name="CrmApiError",this.status=r,this.code=n,this.body=o,c&&"cause"in c&&(this.cause=c.cause),Object.setPrototypeOf(this,s.prototype)}};function A(s){if(!s)return"";let r=new URLSearchParams;for(let[a,o]of Object.entries(s))if(o!=null)if(Array.isArray(o))for(let c of o)c!=null&&r.append(a,String(c));else r.append(a,String(o));let n=r.toString();return n?`?${n}`:""}function L(s){return typeof s=="object"&&s!==null&&"success"in s}function S(s,r){let n=L(s)&&s.success===!1?s:void 0,a=n?.error,o=typeof n?.message=="string"?n.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=typeof n?.code=="string"&&n.code.trim()?n.code:void 0,i=f??e??t??`HTTP_${r}`,p=C??o??t??`CRM request failed with status ${r}`;return{code:i,message:p}}function U(s){let{crmBaseUrl:r,accessToken:n,apiKey:a}=s;if(!n&&!a)throw new Error("createCrmApiClient: exactly one of `accessToken` or `apiKey` is required (got neither).");if(n&&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=r.replace(/\/+$/,""),f=c.endsWith("/api")?c:`${c}/api`,C=n?{Authorization:`Bearer ${n}`}:{"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 g;try{g=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 v=u instanceof Error?u.message:"CRM request failed (network error)";throw new m(0,"NETWORK_ERROR",v,u,{cause:u})}finally{T!==void 0&&clearTimeout(T)}let l=await g.text(),d=l;if(l)try{d=JSON.parse(l)}catch{d=l}let R=L(d)&&d.success===!1;if(!g.ok||R){let{code:u,message:v}=S(d,g.status);throw new m(g.status,u,v,d)}if(L(d)&&d.success===!0)return d.data;if(l!=="")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 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,CAYr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AAmBiB,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?: unknown;\n code?: 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 * For envelope errors: nested `error.code`, top-level `code`, string\n * `error`, or `HTTP_<status>`, in that order. 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\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 envelopeCode = typeof envelope?.code === 'string' && envelope.code.trim() ? envelope.code : undefined;\n const code = errorObjCode ?? envelopeCode ?? 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,GAqIO,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,OAAOA,GAAM,UAAYA,IAAM,MAAQ,YAAaA,CAC7D,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CAAE,CAAC,EAAE,EAC1E,OAAS3C,GAAS6B,EAAiB,OAAQ,YAAa,CAAE,KAAA7B,CAAK,CAAC,EAChE,OAAQ,CAAC2C,EAAI3C,IAAS6B,EAAiB,MAAO,aAAa,mBAAmBc,CAAE,CAAC,GAAI,CAAE,KAAA3C,CAAK,CAAC,EAC7F,OAAS2C,GAAOd,EAAc,SAAU,aAAa,mBAAmBc,CAAE,CAAC,EAAE,CAC/E,EACA,cAAe,CACb,KAAOxC,GACL0B,EAAoC,MAAO,iBAAkB,CAAE,MAAO1B,CAAqB,CAAC,EAC9F,IAAMwC,GAAOd,EAAsB,MAAO,kBAAkB,mBAAmBc,CAAE,CAAC,EAAE,EACpF,OAAQ,CAACA,EAAI3C,IACX6B,EAAsB,MAAO,kBAAkB,mBAAmBc,CAAE,CAAC,GAAI,CAAE,KAAA3C,CAAK,CAAC,EACnF,SAAU,CACR,KAAM,CAAC8C,EAAgB3C,IACrB0B,EACE,MACA,kBAAkB,mBAAmBiB,CAAc,CAAC,YACpD,CAAE,MAAO3C,CAAqB,CAChC,EACF,KAAM,CAAC2C,EAAgB9C,IACrB6B,EACE,OACA,kBAAkB,mBAAmBiB,CAAc,CAAC,YACpD,CAAE,KAAA9C,CAAK,CACT,CACJ,CACF,EACA,KAAM,CACJ,KAAOG,GAAU0B,EAAoC,MAAO,QAAS,CAAE,MAAO1B,CAAqB,CAAC,EACpG,OAASH,GAAS6B,EAAa,OAAQ,QAAS,CAAE,KAAA7B,CAAK,CAAC,CAC1D,EACA,QAAA6B,CACF,CACF,CAEA,IAAOnC,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","envelopeCode","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"]}
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-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';
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-Cezh6uNS.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 PartnerInboundMessageBody, J as PartnerInboundMessageResult, K as PartnerMessageChange, N as PartnerMessageChanges, O as PartnerMessageChangesQuery, Q as PartnerThreadDeleteResult, R as PartnerWebhookCreated, S as PartnerWebhookGet, U as PartnerWebhookPutBody, V as PartnerWebhookRotate, W as PartnerWebhookUpdated, X as PartnerWorkspaceCreated, Y as PartnerWorkspaceDetail, Z as PartnerWorkspaceExisting, _ as PartnerWorkspacePatchBody, $ as PartnerWorkspaceSecret, a0 as PartnerWorkspaceStatus, a1 as PartnerWorkspaceUpsertBody, a2 as PartnerWorkspaceUsage, a3 as PartnerWorkspaceUsageQuery, a4 as TagList } from './crm-contracts-Cezh6uNS.cjs';
3
3
 
4
4
  /**
5
5
  * Typed CRM REST API client for SaaS backends.
@@ -76,8 +76,8 @@ declare class CrmApiError extends Error {
76
76
  /** HTTP status code (0 for network errors / timeouts). */
77
77
  readonly status: number;
78
78
  /**
79
- * Machine-readable code. For envelope errors: the object `error.code`, else
80
- * the string `error`, else `HTTP_<status>`. For transport failures:
79
+ * For envelope errors: nested `error.code`, top-level `code`, string
80
+ * `error`, or `HTTP_<status>`, in that order. For transport failures:
81
81
  * `NETWORK_ERROR` or `TIMEOUT`.
82
82
  */
83
83
  readonly code: string;
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-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';
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-Cezh6uNS.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 PartnerInboundMessageBody, J as PartnerInboundMessageResult, K as PartnerMessageChange, N as PartnerMessageChanges, O as PartnerMessageChangesQuery, Q as PartnerThreadDeleteResult, R as PartnerWebhookCreated, S as PartnerWebhookGet, U as PartnerWebhookPutBody, V as PartnerWebhookRotate, W as PartnerWebhookUpdated, X as PartnerWorkspaceCreated, Y as PartnerWorkspaceDetail, Z as PartnerWorkspaceExisting, _ as PartnerWorkspacePatchBody, $ as PartnerWorkspaceSecret, a0 as PartnerWorkspaceStatus, a1 as PartnerWorkspaceUpsertBody, a2 as PartnerWorkspaceUsage, a3 as PartnerWorkspaceUsageQuery, a4 as TagList } from './crm-contracts-Cezh6uNS.js';
3
3
 
4
4
  /**
5
5
  * Typed CRM REST API client for SaaS backends.
@@ -76,8 +76,8 @@ declare class CrmApiError extends Error {
76
76
  /** HTTP status code (0 for network errors / timeouts). */
77
77
  readonly status: number;
78
78
  /**
79
- * Machine-readable code. For envelope errors: the object `error.code`, else
80
- * the string `error`, else `HTTP_<status>`. For transport failures:
79
+ * For envelope errors: nested `error.code`, top-level `code`, string
80
+ * `error`, or `HTTP_<status>`, in that order. For transport failures:
81
81
  * `NETWORK_ERROR` or `TIMEOUT`.
82
82
  */
83
83
  readonly code: string;
package/dist/api.js CHANGED
@@ -1,2 +1,2 @@
1
- var g=class n extends Error{constructor(c,a,o,i,r){super(o),this.name="CrmApiError",this.status=c,this.code=a,this.body=i,r&&"cause"in r&&(this.cause=r.cause),Object.setPrototypeOf(this,n.prototype)}};function w(n){if(!n)return"";let c=new URLSearchParams;for(let[o,i]of Object.entries(n))if(i!=null)if(Array.isArray(i))for(let r of i)r!=null&&c.append(o,String(r));else c.append(o,String(i));let a=c.toString();return a?`?${a}`:""}function v(n){return typeof n=="object"&&n!==null&&"success"in n}function R(n,c){let a=v(n)&&n.success===!1?n:void 0,o=a?.error,i=typeof a?.message=="string"?a.message:void 0,r=o&&typeof o=="object"?o:void 0,f=typeof r?.code=="string"?r.code:void 0,C=typeof r?.message=="string"?r.message:void 0,t=typeof o=="string"?o:void 0,e=f??t??`HTTP_${c}`,s=C??i??t??`CRM request failed with status ${c}`;return{code:e,message:s}}function Q(n){let{crmBaseUrl:c,accessToken:a,apiKey:o}=n;if(!a&&!o)throw new Error("createCrmApiClient: exactly one of `accessToken` or `apiKey` is required (got neither).");if(a&&o)throw new Error("createCrmApiClient: provide only one of `accessToken` or `apiKey` (got both).");let i=n.fetch??globalThis.fetch;if(typeof i!="function")throw new Error("createCrmApiClient: no fetch implementation available. Pass `fetch` explicitly.");let r=c.replace(/\/+$/,""),f=r.endsWith("/api")?r:`${r}/api`,C=a?{Authorization:`Bearer ${a}`}:{"X-API-Key":o};async function t(e,s,p={}){let b=`${f}${s}${w(p.query)}`,L={...C},h=p.body!==void 0;h&&(L["Content-Type"]="application/json");let y=p.timeoutMs??n.timeoutMs,P=y!==void 0?new AbortController:void 0,k=!1,T;P&&y!==void 0&&(T=setTimeout(()=>{k=!0,P.abort()},y));let m;try{m=await i(b,{method:e,headers:L,body:h?JSON.stringify(p.body):void 0,signal:P?.signal})}catch(u){if(k||u instanceof Error&&u.name==="AbortError")throw new g(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 g(0,"NETWORK_ERROR",E,u,{cause:u})}finally{T!==void 0&&clearTimeout(T)}let l=await m.text(),d=l;if(l)try{d=JSON.parse(l)}catch{d=l}let U=v(d)&&d.success===!1;if(!m.ok||U){let{code:u,message:E}=R(d,m.status);throw new g(m.status,u,E,d)}if(v(d)&&d.success===!0)return d.data;if(l!=="")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,s)=>t("PUT",`/contacts/${encodeURIComponent(e)}`,{body:s}),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,s)=>t("PUT",`/leads/${encodeURIComponent(e)}`,{body:s}),delete:e=>t("DELETE",`/leads/${encodeURIComponent(e)}`)},tasks:{list:e=>t("GET","/tasks",{query:e}),update:(e,s,p)=>t("PATCH",`/leads/${encodeURIComponent(e)}/tasks/${encodeURIComponent(s)}`,{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,s)=>t("PUT",`/products/${encodeURIComponent(e)}`,{body:s}),delete:e=>t("DELETE",`/products/${encodeURIComponent(e)}`)},conversations:{list:e=>t("GET","/conversations",{query:e}),get:e=>t("GET",`/conversations/${encodeURIComponent(e)}`),update:(e,s)=>t("PUT",`/conversations/${encodeURIComponent(e)}`,{body:s}),messages:{list:(e,s)=>t("GET",`/conversations/${encodeURIComponent(e)}/messages`,{query:s}),send:(e,s)=>t("POST",`/conversations/${encodeURIComponent(e)}/messages`,{body:s})}},tags:{list:e=>t("GET","/tags",{query:e}),create:e=>t("POST","/tags",{body:e})},request:t}}var q=Q;export{g as CrmApiError,Q as createCrmApiClient,q as default};
1
+ var l=class n extends Error{constructor(c,r,a,i,o){super(a),this.name="CrmApiError",this.status=c,this.code=r,this.body=i,o&&"cause"in o&&(this.cause=o.cause),Object.setPrototypeOf(this,n.prototype)}};function w(n){if(!n)return"";let c=new URLSearchParams;for(let[a,i]of Object.entries(n))if(i!=null)if(Array.isArray(i))for(let o of i)o!=null&&c.append(a,String(o));else c.append(a,String(i));let r=c.toString();return r?`?${r}`:""}function E(n){return typeof n=="object"&&n!==null&&"success"in n}function R(n,c){let r=E(n)&&n.success===!1?n:void 0,a=r?.error,i=typeof r?.message=="string"?r.message:void 0,o=a&&typeof a=="object"?a:void 0,f=typeof o?.code=="string"?o.code:void 0,C=typeof o?.message=="string"?o.message:void 0,t=typeof a=="string"?a:void 0,e=typeof r?.code=="string"&&r.code.trim()?r.code:void 0,s=f??e??t??`HTTP_${c}`,p=C??i??t??`CRM request failed with status ${c}`;return{code:s,message:p}}function Q(n){let{crmBaseUrl:c,accessToken:r,apiKey:a}=n;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 i=n.fetch??globalThis.fetch;if(typeof i!="function")throw new Error("createCrmApiClient: no fetch implementation available. Pass `fetch` explicitly.");let o=c.replace(/\/+$/,""),f=o.endsWith("/api")?o:`${o}/api`,C=r?{Authorization:`Bearer ${r}`}:{"X-API-Key":a};async function t(e,s,p={}){let b=`${f}${s}${w(p.query)}`,L={...C},h=p.body!==void 0;h&&(L["Content-Type"]="application/json");let y=p.timeoutMs??n.timeoutMs,P=y!==void 0?new AbortController:void 0,k=!1,T;P&&y!==void 0&&(T=setTimeout(()=>{k=!0,P.abort()},y));let m;try{m=await i(b,{method:e,headers:L,body:h?JSON.stringify(p.body):void 0,signal:P?.signal})}catch(u){if(k||u instanceof Error&&u.name==="AbortError")throw new l(0,"TIMEOUT",`CRM request timed out after ${y}ms`,u,{cause:u});let v=u instanceof Error?u.message:"CRM request failed (network error)";throw new l(0,"NETWORK_ERROR",v,u,{cause:u})}finally{T!==void 0&&clearTimeout(T)}let g=await m.text(),d=g;if(g)try{d=JSON.parse(g)}catch{d=g}let U=E(d)&&d.success===!1;if(!m.ok||U){let{code:u,message:v}=R(d,m.status);throw new l(m.status,u,v,d)}if(E(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,s)=>t("PUT",`/contacts/${encodeURIComponent(e)}`,{body:s}),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,s)=>t("PUT",`/leads/${encodeURIComponent(e)}`,{body:s}),delete:e=>t("DELETE",`/leads/${encodeURIComponent(e)}`)},tasks:{list:e=>t("GET","/tasks",{query:e}),update:(e,s,p)=>t("PATCH",`/leads/${encodeURIComponent(e)}/tasks/${encodeURIComponent(s)}`,{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,s)=>t("PUT",`/products/${encodeURIComponent(e)}`,{body:s}),delete:e=>t("DELETE",`/products/${encodeURIComponent(e)}`)},conversations:{list:e=>t("GET","/conversations",{query:e}),get:e=>t("GET",`/conversations/${encodeURIComponent(e)}`),update:(e,s)=>t("PUT",`/conversations/${encodeURIComponent(e)}`,{body:s}),messages:{list:(e,s)=>t("GET",`/conversations/${encodeURIComponent(e)}/messages`,{query:s}),send:(e,s)=>t("POST",`/conversations/${encodeURIComponent(e)}/messages`,{body:s})}},tags:{list:e=>t("GET","/tags",{query:e}),create:e=>t("POST","/tags",{body:e})},request:t}}var q=Q;export{l as CrmApiError,Q as createCrmApiClient,q as default};
2
2
  //# sourceMappingURL=api.js.map