@first-to-fly/crm-sdk 1.6.0 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +198 -5
- package/dist/api.d.cts +2 -2
- package/dist/api.d.ts +2 -2
- package/dist/{crm-contracts-iWWbB6Ga.d.cts → crm-contracts-BiR0JbKC.d.cts} +78 -1
- package/dist/{crm-contracts-iWWbB6Ga.d.ts → crm-contracts-BiR0JbKC.d.ts} +78 -1
- package/dist/embed-host.cjs +1 -1
- package/dist/embed-host.cjs.map +1 -1
- package/dist/embed-host.d.cts +107 -7
- package/dist/embed-host.d.ts +107 -7
- package/dist/embed-host.js +1 -1
- package/dist/embed-host.js.map +1 -1
- package/dist/embed-react.cjs +1 -1
- package/dist/embed-react.cjs.map +1 -1
- package/dist/embed-react.d.cts +80 -1
- package/dist/embed-react.d.ts +80 -1
- package/dist/embed-react.js +1 -1
- package/dist/embed-react.js.map +1 -1
- package/dist/partner.cjs +1 -1
- package/dist/partner.cjs.map +1 -1
- package/dist/partner.d.cts +67 -7
- package/dist/partner.d.ts +67 -7
- package/dist/partner.js +1 -1
- package/dist/partner.js.map +1 -1
- package/package.json +1 -1
package/dist/partner.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { y as ContactChangesQuery } from './crm-contracts-
|
|
1
|
+
import { R as PartnerWorkspaceUpsertBody$1, J as PartnerWorkspaceDetail$1, N as PartnerWorkspacePatchBody$1, S as PartnerWorkspaceUsage, z as ContactRefUpsertBody, A as ContactRefUpsertResult, H as PartnerContactEraseResult, F as PartnerContactEraseByIdentityBody, G as PartnerContactEraseByIdentityResult, x as ContactChanges } from './crm-contracts-BiR0JbKC.js';
|
|
2
|
+
export { y as ContactChangesQuery } from './crm-contracts-BiR0JbKC.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Internal HTTP helper for the server-side `partner` entry point. Not part of the
|
|
@@ -37,14 +37,19 @@ type FetchLike = typeof fetch;
|
|
|
37
37
|
* Errors are {@link CrmPartnerError}: `status` is the HTTP status (0 for a
|
|
38
38
|
* network failure or timeout), `code` is the CRM's short error code (or
|
|
39
39
|
* `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` /
|
|
40
|
-
* `invalid_limit` / `HTTP_<status>`).
|
|
40
|
+
* `invalid_limit` / `invalid_cap` / `invalid_date` / `invalid_identity` / `HTTP_<status>`).
|
|
41
41
|
* The message never contains the key, a secret or a response body.
|
|
42
42
|
*
|
|
43
|
-
* Contact sync (`upsertContact`, `eraseContact`, `listContactChanges`) acts in a
|
|
43
|
+
* Contact sync (`upsertContact`, `eraseContact`, `eraseContactsByIdentity`, `listContactChanges`) acts in a
|
|
44
44
|
* provisioned workspace as your product, with the same partner key. A disabled
|
|
45
45
|
* workspace refuses upserts (409 `WORKSPACE_DISABLED`; not retryable) but still
|
|
46
46
|
* erases and lists.
|
|
47
47
|
*
|
|
48
|
+
* AI for the workspace is metered in credits (1 credit = US$0.001). `aiMonthlyCapCredits` is
|
|
49
|
+
* the monthly cap you set per workspace: `null` = no cap, `0` = AI off, N = N credits per UTC
|
|
50
|
+
* calendar month. A workspace created without one gets 5000. `getWorkspaceUsage` reports use
|
|
51
|
+
* over a date range.
|
|
52
|
+
*
|
|
48
53
|
* Retryable: `status` 409 (`PROVISIONING_IN_PROGRESS`, another call for the ref is
|
|
49
54
|
* running) and 503 (`SERVICE_BUSY`). Wait a few seconds (the CRM sends
|
|
50
55
|
* `Retry-After: 5`) and repeat the same call; provisioning resumes where it stopped.
|
|
@@ -57,7 +62,7 @@ type FetchLike = typeof fetch;
|
|
|
57
62
|
declare class CrmPartnerError extends Error {
|
|
58
63
|
/** HTTP status; 0 when the CRM could not be reached (network failure or timeout). 409 and 503 mean retry shortly. */
|
|
59
64
|
readonly status: number;
|
|
60
|
-
/** The CRM's error code, or `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` / `invalid_limit` / `HTTP_<status>`. */
|
|
65
|
+
/** The CRM's error code, or `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` / `invalid_limit` / `invalid_cap` / `invalid_date` / `invalid_identity` / `HTTP_<status>`. */
|
|
61
66
|
readonly code: string;
|
|
62
67
|
constructor(status: number, code: string);
|
|
63
68
|
}
|
|
@@ -76,6 +81,8 @@ interface CrmPartnerClientOptions {
|
|
|
76
81
|
/** Per-request timeout in ms. Default 15000. */
|
|
77
82
|
timeoutMs?: number;
|
|
78
83
|
}
|
|
84
|
+
/** Upper bound the CRM accepts for `aiMonthlyCapCredits` (100 million credits). */
|
|
85
|
+
declare const AI_MONTHLY_CAP_MAX_CREDITS = 100000000;
|
|
79
86
|
/** Fields every workspace response carries. */
|
|
80
87
|
interface PartnerWorkspace {
|
|
81
88
|
externalRef: string;
|
|
@@ -84,6 +91,31 @@ interface PartnerWorkspace {
|
|
|
84
91
|
/** Null until provisioning has created the embed app. */
|
|
85
92
|
embedAppId: string | null;
|
|
86
93
|
enabled: boolean;
|
|
94
|
+
/**
|
|
95
|
+
* Monthly AI cap in credits: `null` = no cap (also what an older CRM that does not report it
|
|
96
|
+
* returns), `0` = AI off, N = N credits per UTC calendar month.
|
|
97
|
+
*/
|
|
98
|
+
aiMonthlyCapCredits: number | null;
|
|
99
|
+
}
|
|
100
|
+
/** Body of {@link CrmPartnerClient.upsertWorkspace}. */
|
|
101
|
+
type PartnerWorkspaceUpsertBody = Omit<PartnerWorkspaceUpsertBody$1, 'ai_monthly_cap_credits'> & {
|
|
102
|
+
/**
|
|
103
|
+
* Monthly AI cap in credits (integer, 0 to {@link AI_MONTHLY_CAP_MAX_CREDITS}, or `null` for none).
|
|
104
|
+
* Omit on create for the default of 5000; omit on a later call to leave it unchanged.
|
|
105
|
+
*/
|
|
106
|
+
aiMonthlyCapCredits?: number | null;
|
|
107
|
+
};
|
|
108
|
+
/** Body of {@link CrmPartnerClient.updateWorkspace}. At least one field is required. */
|
|
109
|
+
type PartnerWorkspacePatchBody = Omit<PartnerWorkspacePatchBody$1, 'ai_monthly_cap_credits'> & {
|
|
110
|
+
/** Monthly AI cap in credits; `null` removes the cap, `0` switches AI off. */
|
|
111
|
+
aiMonthlyCapCredits?: number | null;
|
|
112
|
+
};
|
|
113
|
+
/** Query of {@link CrmPartnerClient.getWorkspaceUsage}: UTC calendar dates, `to` inclusive. */
|
|
114
|
+
interface PartnerUsageRange {
|
|
115
|
+
/** `YYYY-MM-DD` (UTC), or a `Date` whose UTC date is used. */
|
|
116
|
+
from: string | Date;
|
|
117
|
+
/** `YYYY-MM-DD` (UTC) or a `Date`; the whole day is included. At most 12 months after `from`. */
|
|
118
|
+
to: string | Date;
|
|
87
119
|
}
|
|
88
120
|
/**
|
|
89
121
|
* Result of {@link CrmPartnerClient.upsertWorkspace}. `created: true` (HTTP 201)
|
|
@@ -102,6 +134,14 @@ type PartnerWorkspaceUpsertResult = (PartnerWorkspace & {
|
|
|
102
134
|
interface PartnerWorkspaceDetail extends PartnerWorkspace {
|
|
103
135
|
/** Provisioning progress; `active` once the workspace is ready for sessions. */
|
|
104
136
|
state: PartnerWorkspaceDetail$1['state'];
|
|
137
|
+
/**
|
|
138
|
+
* AI credits used in the current UTC month (`period` is `YYYY-MM`); null until the workspace
|
|
139
|
+
* exists, or when talking to a CRM that does not report it.
|
|
140
|
+
*/
|
|
141
|
+
ai: {
|
|
142
|
+
period: string;
|
|
143
|
+
usedCredits: number;
|
|
144
|
+
} | null;
|
|
105
145
|
}
|
|
106
146
|
/** Result of {@link CrmPartnerClient.rotateWorkspaceSecret}. The old secret stops working at once. */
|
|
107
147
|
interface PartnerRotatedSecret {
|
|
@@ -113,12 +153,21 @@ interface CrmPartnerClient {
|
|
|
113
153
|
* Idempotent: provisions the workspace for `externalRef`, or resumes/returns it. Optional
|
|
114
154
|
* `currency` (ISO 4217) and `timezone` (IANA) are applied on create and on any later call that
|
|
115
155
|
* sends them; an invalid value is a 400 `VALIDATION_ERROR` and nothing is provisioned.
|
|
156
|
+
* `aiMonthlyCapCredits` sets the monthly AI cap (see {@link PartnerWorkspaceUpsertBody}).
|
|
116
157
|
*/
|
|
117
158
|
upsertWorkspace(externalRef: string, body: PartnerWorkspaceUpsertBody): Promise<PartnerWorkspaceUpsertResult>;
|
|
118
159
|
/** Provisioning status, or `null` when the CRM does not know this ref (404). */
|
|
119
160
|
getWorkspace(externalRef: string): Promise<PartnerWorkspaceDetail | null>;
|
|
120
|
-
/** Enable/disable the embed app
|
|
161
|
+
/** Enable/disable the embed app, rename the workspace or set its monthly AI cap. At least one field is required. */
|
|
121
162
|
updateWorkspace(externalRef: string, patch: PartnerWorkspacePatchBody): Promise<PartnerWorkspace>;
|
|
163
|
+
/**
|
|
164
|
+
* AI usage of the workspace from `from` to `to` (UTC dates, `to` inclusive, at most 12 months):
|
|
165
|
+
* totals, then the same figures by operation, model and day, plus the current month's cap and
|
|
166
|
+
* the embedded assistant's tokens (which are recorded but not capped). Returned as the CRM
|
|
167
|
+
* sends it (snake_case). `cost_usd` is the provider cost; credits are what the cap counts.
|
|
168
|
+
* Resolves `null` for a ref the CRM does not know or that has no workspace yet (404).
|
|
169
|
+
*/
|
|
170
|
+
getWorkspaceUsage(externalRef: string, range: PartnerUsageRange): Promise<PartnerWorkspaceUsage | null>;
|
|
122
171
|
/** Replace the embed app secret. Throws a 404 error for an unknown or not-yet-active ref. */
|
|
123
172
|
rotateWorkspaceSecret(externalRef: string): Promise<PartnerRotatedSecret>;
|
|
124
173
|
/**
|
|
@@ -137,6 +186,17 @@ interface CrmPartnerClient {
|
|
|
137
186
|
* also resolves `null`; use `getWorkspace` to tell them apart.
|
|
138
187
|
*/
|
|
139
188
|
eraseContact(externalRef: string, contactRef: string): Promise<PartnerContactEraseResult | null>;
|
|
189
|
+
/**
|
|
190
|
+
* PDPA erasure of the contacts that match a person's phone (E.164) or email (case-insensitive)
|
|
191
|
+
* and that your product never linked by ref, such as a parent who wrote first on WhatsApp.
|
|
192
|
+
* Send `ref` (the erased person's own `contactRef`) so a contact linked only to that ref is
|
|
193
|
+
* erased too. A matched contact with any other ref (another person of yours, or another
|
|
194
|
+
* product) is left alone and counted in `skipped_linked_elsewhere`, so a shared family number
|
|
195
|
+
* survives. At least one of `phone` or `email` is required (a client-side 400
|
|
196
|
+
* `invalid_identity` otherwise). Works while the workspace is disabled. No match resolves
|
|
197
|
+
* `erased: 0`. Resolves `null` for an unknown workspace (404).
|
|
198
|
+
*/
|
|
199
|
+
eraseContactsByIdentity(externalRef: string, identity: PartnerContactEraseByIdentityBody): Promise<PartnerContactEraseByIdentityResult | null>;
|
|
140
200
|
/**
|
|
141
201
|
* One page of the contacts changes feed (oldest first, includes deleted contacts). Pass `since`
|
|
142
202
|
* for the first page and the returned `next_cursor` as `cursor` until it is null. `limit` is 1
|
|
@@ -150,4 +210,4 @@ interface CrmPartnerClient {
|
|
|
150
210
|
}
|
|
151
211
|
declare function createCrmPartnerClient(opts: CrmPartnerClientOptions): CrmPartnerClient;
|
|
152
212
|
|
|
153
|
-
export { CONTACT_CHANGES_MAX_LIMIT, CONTACT_REF_PATTERN, ContactChanges, ContactRefUpsertBody, ContactRefUpsertResult, type CrmPartnerClient, type CrmPartnerClientOptions, CrmPartnerError, EXTERNAL_REF_PATTERN, PartnerContactEraseResult, type PartnerRotatedSecret, type PartnerWorkspace, type PartnerWorkspaceDetail, PartnerWorkspacePatchBody, PartnerWorkspaceUpsertBody, type PartnerWorkspaceUpsertResult, createCrmPartnerClient };
|
|
213
|
+
export { AI_MONTHLY_CAP_MAX_CREDITS, CONTACT_CHANGES_MAX_LIMIT, CONTACT_REF_PATTERN, ContactChanges, ContactRefUpsertBody, ContactRefUpsertResult, type CrmPartnerClient, type CrmPartnerClientOptions, CrmPartnerError, EXTERNAL_REF_PATTERN, PartnerContactEraseByIdentityBody, PartnerContactEraseByIdentityResult, PartnerContactEraseResult, type PartnerRotatedSecret, type PartnerUsageRange, type PartnerWorkspace, type PartnerWorkspaceDetail, type PartnerWorkspacePatchBody, type PartnerWorkspaceUpsertBody, type PartnerWorkspaceUpsertResult, PartnerWorkspaceUsage, createCrmPartnerClient };
|
package/dist/partner.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function
|
|
1
|
+
function W(e){return e.replace(/\/+$/,"").replace(/\/api$/,"")}function R(e,p){let y=e??globalThis.fetch;if(typeof y!="function")throw new Error(`${p}: no fetch implementation available. Pass \`fetch\` explicitly.`);return y}async function x(e,p,y,h){let P=new AbortController,i=!1,c=setTimeout(()=>{i=!0,P.abort()},p);try{let f={Accept:"application/json",...h.headers},C=h.body!==void 0;C&&(f["Content-Type"]="application/json");let s=await e(y,{method:h.method,headers:f,body:C?JSON.stringify(h.body):void 0,signal:P.signal}),n=await s.json().catch(()=>null);return i?{ok:!1,kind:"timeout"}:{ok:!0,status:s.status,json:n}}catch{return{ok:!1,kind:i?"timeout":"network"}}finally{clearTimeout(c)}}var U=/^[A-Za-z0-9_.:-]{1,60}$/;function A(e,p,y){let h=`HTTP_${p}`,P=i=>typeof i!="string"||!U.test(i)||y.some(c=>c&&i.includes(c))?null:i;if(e&&typeof e=="object"){let i=e,c=i.error;return P(i.code)??P(c)??(c&&typeof c=="object"?P(c.code):null)??h}return h}var m=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var l=class e extends Error{constructor(p,y){super(p===0?`CRM partner API unreachable (${y})`:`CRM partner API ${p} ${y}`),this.name="CrmPartnerError",this.status=p,this.code=y,Object.setPrototypeOf(this,e.prototype)}},I=/^[A-Za-z0-9_-]{1,64}$/,$=/^[A-Za-z0-9._:-]{1,200}$/,j=200,D=1e8,w=e=>({externalRef:e.external_ref,workspaceId:e.workspace_id,embedAppId:e.embed_app_id,enabled:e.enabled,aiMonthlyCapCredits:typeof e.ai_monthly_cap_credits=="number"?e.ai_monthly_cap_credits:null}),M=/^\d{4}-\d{2}-\d{2}$/;function E(e){let p=e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e;if(typeof p!="string"||!M.test(p)||Number.isNaN(Date.parse(`${p}T00:00:00Z`))||new Date(`${p}T00:00:00Z`).toISOString().slice(0,10)!==p)throw new l(400,"invalid_date");return p}function T(e){if(e==null)return e;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>D)throw new l(400,"invalid_cap");return e}var B=e=>e===null||typeof e=="string";function b(e){return m(e)&&typeof e.external_ref=="string"&&B(e.workspace_id)&&B(e.embed_app_id)&&typeof e.enabled=="boolean"}function F(e){if(!e.crmBaseUrl)throw new Error("createCrmPartnerClient: `crmBaseUrl` is required.");if(!e.partnerKey)throw new Error("createCrmPartnerClient: `partnerKey` is required.");let p=R(e.fetch,"createCrmPartnerClient"),y=e.timeoutMs??15e3,h=`${W(e.crmBaseUrl)}/api/partner/v1/workspaces`,P=[e.partnerKey];function i(s){if(typeof s!="string"||!I.test(s))throw new l(400,"invalid_external_ref");return s}async function c(s,n,o){let t=await x(p,y,`${h}/${n}`,{method:s,headers:{Authorization:`Bearer ${e.partnerKey}`},body:o});if(!t.ok)throw new l(0,t.kind);if(t.status<200||t.status>=300)throw new l(t.status,A(t.json,t.status,P));return{status:t.status,json:t.json}}let f=s=>new l(s,"bad_response");function C(s){if(typeof s!="string"||!$.test(s))throw new l(400,"invalid_contact_ref");return s}return{async upsertWorkspace(s,n){let o=i(s),{aiMonthlyCapCredits:t,...r}=n,a=T(t),u=a===void 0?r:{...r,ai_monthly_cap_credits:a},{status:g,json:k}=await c("PUT",o,u);if(!b(k))throw f(g);let d=k;if(d.created===!0){let _=d.embed_app_secret;if(typeof _!="string"||!_)throw f(g);return{...w(d),created:!0,embedAppSecret:_}}if(d.created===!1)return{...w(d),created:!1};throw f(g)},async getWorkspace(s){let n=i(s);try{let{status:o,json:t}=await c("GET",n);if(!b(t)||typeof t.state!="string")throw f(o);let r=t.ai;return{...w(t),state:t.state,ai:m(r)&&typeof r.period=="string"&&typeof r.used_credits=="number"?{period:r.period,usedCredits:r.used_credits}:null}}catch(o){if(o instanceof l&&o.status===404)return null;throw o}},async updateWorkspace(s,n){let o=i(s),t={};n.enabled!==void 0&&(t.enabled=n.enabled),n.name!==void 0&&(t.name=n.name);let r=T(n.aiMonthlyCapCredits);r!==void 0&&(t.ai_monthly_cap_credits=r);let{status:a,json:u}=await c("PATCH",o,t);if(!b(u))throw f(a);return w(u)},async getWorkspaceUsage(s,n){let o=i(s),t=new URLSearchParams({from:E(n.from),to:E(n.to)});try{let{status:r,json:a}=await c("GET",`${o}/usage?${t.toString()}`);if(!m(a)||!m(a.totals)||!m(a.cap)||!Array.isArray(a.by_operation))throw f(r);return a}catch(r){if(r instanceof l&&r.status===404)return null;throw r}},async rotateWorkspaceSecret(s){let n=i(s),{status:o,json:t}=await c("POST",`${n}/rotate-secret`),r=t;if(!m(t)||typeof r?.embed_app_id!="string"||typeof r.embed_app_secret!="string"||!r.embed_app_secret)throw f(o);return{embedAppId:r.embed_app_id,embedAppSecret:r.embed_app_secret}},async upsertContact(s,n,o){let t=i(s),r=C(n),{status:a,json:u}=await c("PUT",`${t}/contacts/${encodeURIComponent(r)}`,o);if(!m(u)||!m(u.contact)||typeof u.created!="boolean"||typeof u.consent_applied!="boolean")throw f(a);return u},async eraseContact(s,n){let o=i(s),t=C(n);try{let{status:r,json:a}=await c("DELETE",`${o}/contacts/${encodeURIComponent(t)}`);if(!m(a)||a.erased!==!0||typeof a.contact_id!="string")throw f(r);return a}catch(r){if(r instanceof l&&r.status===404)return null;throw r}},async eraseContactsByIdentity(s,n){let o=i(s),t=typeof n?.phone=="string"?n.phone.trim():void 0,r=typeof n?.email=="string"?n.email.trim():void 0,a=t!==void 0&&/\d/.test(t),u=r!==void 0&&r.includes("@");if(n?.phone!==void 0&&!a||n?.email!==void 0&&!u||!a&&!u)throw new l(400,"invalid_identity");n.ref!==void 0&&C(n.ref);let g={};a&&(g.phone=t),u&&(g.email=r),n.ref!==void 0&&(g.ref=n.ref);try{let{status:k,json:d}=await c("POST",`${o}/contacts/erase-by-identity`,g);if(!m(d)||typeof d.erased!="number"||!Array.isArray(d.contact_ids)||typeof d.skipped_linked_elsewhere!="number")throw f(k);return d}catch(k){if(k instanceof l&&k.status===404)return null;throw k}},async listContactChanges(s,n={}){let o=i(s),{since:t,cursor:r,limit:a}=n;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>j))throw new l(400,"invalid_limit");let u=new URLSearchParams;t!==void 0&&u.set("since",t),r!==void 0&&u.set("cursor",r),a!==void 0&&u.set("limit",String(a));let g=u.toString(),{status:k,json:d}=await c("GET",`${o}/contacts/changes${g?`?${g}`:""}`);if(!m(d)||!Array.isArray(d.items)||!(d.next_cursor===null||typeof d.next_cursor=="string"))throw f(k);return d}}}export{D as AI_MONTHLY_CAP_MAX_CREDITS,j as CONTACT_CHANGES_MAX_LIMIT,$ as CONTACT_REF_PATTERN,l as CrmPartnerError,I as EXTERNAL_REF_PATTERN,F as createCrmPartnerClient};
|
|
2
2
|
//# sourceMappingURL=partner.js.map
|
package/dist/partner.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server-http.ts","../src/partner.ts"],"sourcesContent":["/**\n * Internal HTTP helper for the server-side `partner` entry point. Not part of the\n * public API (no package export points here).\n *\n * It never puts a request header, a request body or a response body into an\n * error: callers get the HTTP status, a short sanitized error code, or a\n * transport failure kind, and nothing else.\n */\n\nexport type FetchLike = typeof fetch;\n\nexport const DEFAULT_TIMEOUT_MS = 15_000;\n\nexport type Transport =\n | { ok: true; status: number; json: unknown }\n | { ok: false; kind: 'timeout' | 'network' };\n\n/** Strip trailing slashes and a trailing `/api`, so callers can pass either form. */\nexport function normalizeBase(crmBaseUrl: string): string {\n return crmBaseUrl.replace(/\\/+$/, '').replace(/\\/api$/, '');\n}\n\nexport function resolveFetch(fetchImpl: FetchLike | undefined, who: string): FetchLike {\n const f = fetchImpl ?? globalThis.fetch;\n if (typeof f !== 'function') {\n throw new Error(`${who}: no fetch implementation available. Pass \\`fetch\\` explicitly.`);\n }\n return f;\n}\n\n/**\n * One request with a hard timeout covering headers AND body. Returns the parsed\n * JSON (null when the body is empty or not JSON) or a transport failure kind.\n */\nexport async function sendJson(\n fetchImpl: FetchLike,\n timeoutMs: number,\n url: string,\n init: { method: string; headers: Record<string, string>; body?: unknown },\n): Promise<Transport> {\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs);\n try {\n const headers: Record<string, string> = { Accept: 'application/json', ...init.headers };\n const hasBody = init.body !== undefined;\n if (hasBody) headers['Content-Type'] = 'application/json';\n const res = await fetchImpl(url, {\n method: init.method,\n headers,\n body: hasBody ? JSON.stringify(init.body) : undefined,\n signal: controller.signal,\n });\n const json: unknown = await res.json().catch(() => null);\n if (timedOut) return { ok: false, kind: 'timeout' };\n return { ok: true, status: res.status, json };\n } catch {\n return { ok: false, kind: timedOut ? 'timeout' : 'network' };\n } finally {\n clearTimeout(timer);\n }\n}\n\nconst SAFE_CODE = /^[A-Za-z0-9_.:-]{1,60}$/;\n\n/**\n * A short machine code from an error body, or `HTTP_<status>`. Accepts\n * `{ error: { code } }`, `{ error: \"code\" }` and `{ code }`. A value that is not\n * a short identifier (a sentence, a long string) or that contains one of the\n * `redact` strings (credentials) is dropped, so a code is always safe to log.\n */\nexport function errorCodeFrom(json: unknown, status: number, redact: readonly string[]): string {\n const fallback = `HTTP_${status}`;\n const pick = (v: unknown): string | null => {\n if (typeof v !== 'string' || !SAFE_CODE.test(v)) return null;\n return redact.some((r) => r && v.includes(r)) ? null : v;\n };\n if (json && typeof json === 'object') {\n const o = json as Record<string, unknown>;\n const err = o.error;\n return (\n pick(o.code)\n ?? pick(err)\n ?? (err && typeof err === 'object' ? pick((err as Record<string, unknown>).code) : null)\n ?? fallback\n );\n }\n return fallback;\n}\n\nexport const isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v);\n","/**\n * CRM Partner SDK (server side ONLY).\n *\n * A product that embeds the CRM (a \"partner\") provisions one CRM workspace per\n * customer of its own, keyed by the customer's id in the product (`externalRef`).\n * The call authenticates with ONE platform key (`ptk_...`) that can create and\n * manage workspaces for every customer of the partner.\n *\n * **Never run this in a browser, a mobile app or any client bundle.** The partner\n * key is a platform-wide secret and the responses carry per-workspace embed\n * secrets. Keep both in server-side configuration and never log them.\n *\n * ```ts\n * import { createCrmPartnerClient } from '@first-to-fly/crm-sdk/partner';\n *\n * const partner = createCrmPartnerClient({\n * crmBaseUrl: process.env.CRM_BASE_URL!,\n * partnerKey: process.env.CRM_PARTNER_KEY!,\n * });\n * const ws = await partner.upsertWorkspace(tenantId, { name: 'Acme School' });\n * if (ws.created) saveSecret(tenantId, ws.embedAppId, ws.embedAppSecret); // shown once\n * ```\n *\n * Errors are {@link CrmPartnerError}: `status` is the HTTP status (0 for a\n * network failure or timeout), `code` is the CRM's short error code (or\n * `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` /\n * `invalid_limit` / `HTTP_<status>`).\n * The message never contains the key, a secret or a response body.\n *\n * Contact sync (`upsertContact`, `eraseContact`, `listContactChanges`) acts in a\n * provisioned workspace as your product, with the same partner key. A disabled\n * workspace refuses upserts (409 `WORKSPACE_DISABLED`; not retryable) but still\n * erases and lists.\n *\n * Retryable: `status` 409 (`PROVISIONING_IN_PROGRESS`, another call for the ref is\n * running) and 503 (`SERVICE_BUSY`). Wait a few seconds (the CRM sends\n * `Retry-After: 5`) and repeat the same call; provisioning resumes where it stopped.\n * 500 and status 0 are also safe to repeat.\n *\n * @packageDocumentation\n */\n\nimport {\n DEFAULT_TIMEOUT_MS,\n errorCodeFrom,\n isRecord,\n normalizeBase,\n resolveFetch,\n sendJson,\n type FetchLike,\n} from './server-http';\nimport type {\n ContactChanges,\n ContactChangesQuery,\n ContactRefUpsertBody,\n ContactRefUpsertResult,\n PartnerContactEraseResult,\n PartnerWorkspaceCreated,\n PartnerWorkspaceDetail as WirePartnerWorkspaceDetail,\n PartnerWorkspaceExisting,\n PartnerWorkspacePatchBody,\n PartnerWorkspaceSecret,\n PartnerWorkspaceStatus,\n PartnerWorkspaceUpsertBody,\n} from './generated/crm-contracts';\n\n// ─── Error class ─────────────────────────────────────────────────────────────\n\n/** A failed partner API call. The message never includes the key, secrets or response bodies. */\nexport class CrmPartnerError extends Error {\n /** HTTP status; 0 when the CRM could not be reached (network failure or timeout). 409 and 503 mean retry shortly. */\n readonly status: number;\n /** The CRM's error code, or `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` / `invalid_limit` / `HTTP_<status>`. */\n readonly code: string;\n\n constructor(status: number, code: string) {\n super(status === 0 ? `CRM partner API unreachable (${code})` : `CRM partner API ${status} ${code}`);\n this.name = 'CrmPartnerError';\n this.status = status;\n this.code = code;\n Object.setPrototypeOf(this, CrmPartnerError.prototype);\n }\n}\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Same pattern the CRM enforces on `externalRef`. */\nexport const EXTERNAL_REF_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;\n\n/** Same pattern the CRM enforces on a `contactRef`. */\nexport const CONTACT_REF_PATTERN = /^[A-Za-z0-9._:-]{1,200}$/;\nexport const CONTACT_CHANGES_MAX_LIMIT = 200;\n\nexport interface CrmPartnerClientOptions {\n /** CRM base URL, e.g. `https://crm.example.com` (a trailing `/api` is tolerated). */\n crmBaseUrl: string;\n /** Partner key (`ptk_...`). Server-side secret. */\n partnerKey: string;\n /** Custom fetch (tests, proxies). Defaults to the global `fetch`. */\n fetch?: FetchLike;\n /** Per-request timeout in ms. Default 15000. */\n timeoutMs?: number;\n}\n\n/** Fields every workspace response carries. */\nexport interface PartnerWorkspace {\n externalRef: string;\n /** Null until provisioning has created the workspace. */\n workspaceId: string | null;\n /** Null until provisioning has created the embed app. */\n embedAppId: string | null;\n enabled: boolean;\n}\n\n/**\n * Result of {@link CrmPartnerClient.upsertWorkspace}. `created: true` (HTTP 201)\n * is the one call that carries `embedAppSecret`, shown once: store it. A repeat\n * call (HTTP 200) has `created: false` and no secret; use `rotateWorkspaceSecret`\n * if it was lost.\n */\nexport type PartnerWorkspaceUpsertResult =\n | (PartnerWorkspace & { created: true; embedAppSecret: string })\n | (PartnerWorkspace & { created: false; embedAppSecret?: undefined });\n\n/** Result of {@link CrmPartnerClient.getWorkspace}. */\nexport interface PartnerWorkspaceDetail extends PartnerWorkspace {\n /** Provisioning progress; `active` once the workspace is ready for sessions. */\n state: WirePartnerWorkspaceDetail['state'];\n}\n\n/** Result of {@link CrmPartnerClient.rotateWorkspaceSecret}. The old secret stops working at once. */\nexport interface PartnerRotatedSecret {\n embedAppId: string;\n embedAppSecret: string;\n}\n\nexport interface CrmPartnerClient {\n /**\n * Idempotent: provisions the workspace for `externalRef`, or resumes/returns it. Optional\n * `currency` (ISO 4217) and `timezone` (IANA) are applied on create and on any later call that\n * sends them; an invalid value is a 400 `VALIDATION_ERROR` and nothing is provisioned.\n */\n upsertWorkspace(externalRef: string, body: PartnerWorkspaceUpsertBody): Promise<PartnerWorkspaceUpsertResult>;\n /** Provisioning status, or `null` when the CRM does not know this ref (404). */\n getWorkspace(externalRef: string): Promise<PartnerWorkspaceDetail | null>;\n /** Enable/disable the embed app or rename the workspace. At least one field is required. */\n updateWorkspace(externalRef: string, patch: PartnerWorkspacePatchBody): Promise<PartnerWorkspace>;\n /** Replace the embed app secret. Throws a 404 error for an unknown or not-yet-active ref. */\n rotateWorkspaceSecret(externalRef: string): Promise<PartnerRotatedSecret>;\n /**\n * Idempotent upsert of the contact for `contactRef` (your own key for the person) in the\n * workspace: finds it by ref (then phone, then email) or creates it. `whatsapp_consent`\n * only applies when its `recorded_at` is newer than the stored one and the parent has\n * not replied STOP (`consent_applied` says whether it did). `team_ref` + `team_name` file\n * the contact under your team, created if new. Fails with 409 `WORKSPACE_DISABLED` while the\n * workspace is disabled and 404 for an unknown workspace.\n */\n upsertContact(externalRef: string, contactRef: string, body: ContactRefUpsertBody): Promise<ContactRefUpsertResult>;\n /**\n * PDPA erasure: overwrites the contact's personal data, soft-deletes it and removes its refs.\n * Resolves `null` when the CRM has no contact for this ref (404: never synced, or already\n * erased). Works while the workspace is disabled. An unknown workspace is also a 404, so it\n * also resolves `null`; use `getWorkspace` to tell them apart.\n */\n eraseContact(externalRef: string, contactRef: string): Promise<PartnerContactEraseResult | null>;\n /**\n * One page of the contacts changes feed (oldest first, includes deleted contacts). Pass `since`\n * for the first page and the returned `next_cursor` as `cursor` until it is null. `limit` is 1\n * to 200 (default 100). Works while the workspace is disabled; an unknown workspace throws 404.\n */\n listContactChanges(externalRef: string, query?: { since?: string; cursor?: string; limit?: number }): Promise<ContactChanges>;\n}\n\n// ─── Implementation ──────────────────────────────────────────────────────────\n\nconst fromStatus = (w: PartnerWorkspaceStatus): PartnerWorkspace => ({\n externalRef: w.external_ref,\n workspaceId: w.workspace_id,\n embedAppId: w.embed_app_id,\n enabled: w.enabled,\n});\n\nconst isNullableString = (v: unknown): v is string | null => v === null || typeof v === 'string';\n\nfunction isStatus(v: unknown): v is PartnerWorkspaceStatus {\n return isRecord(v)\n && typeof v.external_ref === 'string'\n && isNullableString(v.workspace_id)\n && isNullableString(v.embed_app_id)\n && typeof v.enabled === 'boolean';\n}\n\nexport function createCrmPartnerClient(opts: CrmPartnerClientOptions): CrmPartnerClient {\n if (!opts.crmBaseUrl) throw new Error('createCrmPartnerClient: `crmBaseUrl` is required.');\n if (!opts.partnerKey) throw new Error('createCrmPartnerClient: `partnerKey` is required.');\n const fetchImpl = resolveFetch(opts.fetch, 'createCrmPartnerClient');\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const base = `${normalizeBase(opts.crmBaseUrl)}/api/partner/v1/workspaces`;\n const redact = [opts.partnerKey];\n\n function checkRef(externalRef: string): string {\n if (typeof externalRef !== 'string' || !EXTERNAL_REF_PATTERN.test(externalRef)) {\n throw new CrmPartnerError(400, 'invalid_external_ref');\n }\n return externalRef;\n }\n\n async function call(method: string, path: string, body?: unknown): Promise<{ status: number; json: unknown }> {\n const res = await sendJson(fetchImpl, timeoutMs, `${base}/${path}`, {\n method,\n headers: { Authorization: `Bearer ${opts.partnerKey}` },\n body,\n });\n if (!res.ok) throw new CrmPartnerError(0, res.kind);\n if (res.status < 200 || res.status >= 300) {\n throw new CrmPartnerError(res.status, errorCodeFrom(res.json, res.status, redact));\n }\n return { status: res.status, json: res.json };\n }\n\n const bad = (status: number) => new CrmPartnerError(status, 'bad_response');\n\n function checkContactRef(contactRef: string): string {\n if (typeof contactRef !== 'string' || !CONTACT_REF_PATTERN.test(contactRef)) {\n throw new CrmPartnerError(400, 'invalid_contact_ref');\n }\n return contactRef;\n }\n\n return {\n async upsertWorkspace(externalRef, body) {\n const ref = checkRef(externalRef);\n const { status, json } = await call('PUT', ref, body);\n if (!isStatus(json)) throw bad(status);\n const wire = json as PartnerWorkspaceCreated | PartnerWorkspaceExisting;\n if (wire.created === true) {\n const secret = (wire as PartnerWorkspaceCreated).embed_app_secret;\n if (typeof secret !== 'string' || !secret) throw bad(status);\n return { ...fromStatus(wire), created: true, embedAppSecret: secret };\n }\n if (wire.created === false) return { ...fromStatus(wire), created: false };\n throw bad(status);\n },\n\n async getWorkspace(externalRef) {\n const ref = checkRef(externalRef);\n try {\n const { status, json } = await call('GET', ref);\n if (!isStatus(json) || typeof (json as Record<string, unknown>).state !== 'string') throw bad(status);\n return { ...fromStatus(json), state: (json as unknown as WirePartnerWorkspaceDetail).state };\n } catch (err) {\n if (err instanceof CrmPartnerError && err.status === 404) return null;\n throw err;\n }\n },\n\n async updateWorkspace(externalRef, patch) {\n const ref = checkRef(externalRef);\n const body: PartnerWorkspacePatchBody = {};\n if (patch.enabled !== undefined) body.enabled = patch.enabled;\n if (patch.name !== undefined) body.name = patch.name;\n const { status, json } = await call('PATCH', ref, body);\n if (!isStatus(json)) throw bad(status);\n return fromStatus(json);\n },\n\n async rotateWorkspaceSecret(externalRef) {\n const ref = checkRef(externalRef);\n const { status, json } = await call('POST', `${ref}/rotate-secret`);\n const w = json as Partial<PartnerWorkspaceSecret> | null;\n if (!isRecord(json) || typeof w?.embed_app_id !== 'string' || typeof w.embed_app_secret !== 'string' || !w.embed_app_secret) {\n throw bad(status);\n }\n return { embedAppId: w.embed_app_id, embedAppSecret: w.embed_app_secret };\n },\n\n async upsertContact(externalRef, contactRef, body) {\n const ref = checkRef(externalRef);\n const cref = checkContactRef(contactRef);\n const { status, json } = await call('PUT', `${ref}/contacts/${encodeURIComponent(cref)}`, body);\n if (!isRecord(json) || !isRecord(json.contact) || typeof json.created !== 'boolean' || typeof json.consent_applied !== 'boolean') {\n throw bad(status);\n }\n return json as unknown as ContactRefUpsertResult;\n },\n\n async eraseContact(externalRef, contactRef) {\n const ref = checkRef(externalRef);\n const cref = checkContactRef(contactRef);\n try {\n const { status, json } = await call('DELETE', `${ref}/contacts/${encodeURIComponent(cref)}`);\n if (!isRecord(json) || json.erased !== true || typeof json.contact_id !== 'string') throw bad(status);\n return json as unknown as PartnerContactEraseResult;\n } catch (err) {\n if (err instanceof CrmPartnerError && err.status === 404) return null;\n throw err;\n }\n },\n\n async listContactChanges(externalRef, query = {}) {\n const ref = checkRef(externalRef);\n const { since, cursor, limit } = query;\n if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > CONTACT_CHANGES_MAX_LIMIT)) {\n throw new CrmPartnerError(400, 'invalid_limit');\n }\n const qs = new URLSearchParams();\n if (since !== undefined) qs.set('since', since);\n if (cursor !== undefined) qs.set('cursor', cursor);\n if (limit !== undefined) qs.set('limit', String(limit));\n const q = qs.toString();\n const { status, json } = await call('GET', `${ref}/contacts/changes${q ? `?${q}` : ''}`);\n if (!isRecord(json) || !Array.isArray(json.items) || !(json.next_cursor === null || typeof json.next_cursor === 'string')) {\n throw bad(status);\n }\n return json as unknown as ContactChanges;\n },\n };\n}\n\n// Re-exported so partner code can type its inputs without importing the contracts module.\nexport type {\n ContactChanges,\n ContactChangesQuery,\n ContactRefUpsertBody,\n ContactRefUpsertResult,\n PartnerContactEra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AAM4C,EAAK,IAAI,gBACXH,IAAU,QAAWG,EAAG,IAAI,QAASH,CAAK,EAC1CC,IAAW,QAAWE,EAAG,IAAI,SAAUF,CAAM,EAC7CC,IAAU,QAAWC,EAAG,IAAI,QAAS,OAAOD,CAAK,CAAC,EACtD,IAAME,EAAID,EAAG,SAAS,EAChB,CAAE,OAAA1C,EAAQ,KAAAgC,CAAK,EAAI,MAAMX,EAAK,MAAO,GAAGU,CAAG,oBAAoBY,EAAI,IAAIA,CAAC,GAAK,EAAE,EAAE,EACvF,GAAI,CAACjC,EAASsB,CAAI,GAAK,CAAC,MAAM,QAAQA,EAAK,KAAK,GAAK,EAAEA,EAAK,cAAgB,MAAQ,OAAOA,EAAK,aAAgB,UAC9G,MAAMJ,EAAI5B,CAAM,EAElB,OAAOgC,CACT,CACF,CACF","names":["normalizeBase","crmBaseUrl","resolveFetch","fetchImpl","who","f","sendJson","timeoutMs","url","init","controller","timedOut","timer","headers","hasBody","res","json","SAFE_CODE","errorCodeFrom","status","redact","fallback","pick","v","r","err","isRecord","CrmPartnerError","_CrmPartnerError","status","code","EXTERNAL_REF_PATTERN","CONTACT_REF_PATTERN","CONTACT_CHANGES_MAX_LIMIT","fromStatus","w","isNullableString","v","isStatus","isRecord","createCrmPartnerClient","opts","fetchImpl","resolveFetch","timeoutMs","base","normalizeBase","redact","checkRef","externalRef","call","method","path","body","res","sendJson","errorCodeFrom","bad","checkContactRef","contactRef","ref","json","wire","secret","err","patch","cref","query","since","cursor","limit","qs","q"]}
|
|
1
|
+
{"version":3,"sources":["../src/server-http.ts","../src/partner.ts"],"sourcesContent":["/**\n * Internal HTTP helper for the server-side `partner` entry point. Not part of the\n * public API (no package export points here).\n *\n * It never puts a request header, a request body or a response body into an\n * error: callers get the HTTP status, a short sanitized error code, or a\n * transport failure kind, and nothing else.\n */\n\nexport type FetchLike = typeof fetch;\n\nexport const DEFAULT_TIMEOUT_MS = 15_000;\n\nexport type Transport =\n | { ok: true; status: number; json: unknown }\n | { ok: false; kind: 'timeout' | 'network' };\n\n/** Strip trailing slashes and a trailing `/api`, so callers can pass either form. */\nexport function normalizeBase(crmBaseUrl: string): string {\n return crmBaseUrl.replace(/\\/+$/, '').replace(/\\/api$/, '');\n}\n\nexport function resolveFetch(fetchImpl: FetchLike | undefined, who: string): FetchLike {\n const f = fetchImpl ?? globalThis.fetch;\n if (typeof f !== 'function') {\n throw new Error(`${who}: no fetch implementation available. Pass \\`fetch\\` explicitly.`);\n }\n return f;\n}\n\n/**\n * One request with a hard timeout covering headers AND body. Returns the parsed\n * JSON (null when the body is empty or not JSON) or a transport failure kind.\n */\nexport async function sendJson(\n fetchImpl: FetchLike,\n timeoutMs: number,\n url: string,\n init: { method: string; headers: Record<string, string>; body?: unknown },\n): Promise<Transport> {\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs);\n try {\n const headers: Record<string, string> = { Accept: 'application/json', ...init.headers };\n const hasBody = init.body !== undefined;\n if (hasBody) headers['Content-Type'] = 'application/json';\n const res = await fetchImpl(url, {\n method: init.method,\n headers,\n body: hasBody ? JSON.stringify(init.body) : undefined,\n signal: controller.signal,\n });\n const json: unknown = await res.json().catch(() => null);\n if (timedOut) return { ok: false, kind: 'timeout' };\n return { ok: true, status: res.status, json };\n } catch {\n return { ok: false, kind: timedOut ? 'timeout' : 'network' };\n } finally {\n clearTimeout(timer);\n }\n}\n\nconst SAFE_CODE = /^[A-Za-z0-9_.:-]{1,60}$/;\n\n/**\n * A short machine code from an error body, or `HTTP_<status>`. Accepts\n * `{ error: { code } }`, `{ error: \"code\" }` and `{ code }`. A value that is not\n * a short identifier (a sentence, a long string) or that contains one of the\n * `redact` strings (credentials) is dropped, so a code is always safe to log.\n */\nexport function errorCodeFrom(json: unknown, status: number, redact: readonly string[]): string {\n const fallback = `HTTP_${status}`;\n const pick = (v: unknown): string | null => {\n if (typeof v !== 'string' || !SAFE_CODE.test(v)) return null;\n return redact.some((r) => r && v.includes(r)) ? null : v;\n };\n if (json && typeof json === 'object') {\n const o = json as Record<string, unknown>;\n const err = o.error;\n return (\n pick(o.code)\n ?? pick(err)\n ?? (err && typeof err === 'object' ? pick((err as Record<string, unknown>).code) : null)\n ?? fallback\n );\n }\n return fallback;\n}\n\nexport const isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v);\n","/**\n * CRM Partner SDK (server side ONLY).\n *\n * A product that embeds the CRM (a \"partner\") provisions one CRM workspace per\n * customer of its own, keyed by the customer's id in the product (`externalRef`).\n * The call authenticates with ONE platform key (`ptk_...`) that can create and\n * manage workspaces for every customer of the partner.\n *\n * **Never run this in a browser, a mobile app or any client bundle.** The partner\n * key is a platform-wide secret and the responses carry per-workspace embed\n * secrets. Keep both in server-side configuration and never log them.\n *\n * ```ts\n * import { createCrmPartnerClient } from '@first-to-fly/crm-sdk/partner';\n *\n * const partner = createCrmPartnerClient({\n * crmBaseUrl: process.env.CRM_BASE_URL!,\n * partnerKey: process.env.CRM_PARTNER_KEY!,\n * });\n * const ws = await partner.upsertWorkspace(tenantId, { name: 'Acme School' });\n * if (ws.created) saveSecret(tenantId, ws.embedAppId, ws.embedAppSecret); // shown once\n * ```\n *\n * Errors are {@link CrmPartnerError}: `status` is the HTTP status (0 for a\n * network failure or timeout), `code` is the CRM's short error code (or\n * `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` /\n * `invalid_limit` / `invalid_cap` / `invalid_date` / `invalid_identity` / `HTTP_<status>`).\n * The message never contains the key, a secret or a response body.\n *\n * Contact sync (`upsertContact`, `eraseContact`, `eraseContactsByIdentity`, `listContactChanges`) acts in a\n * provisioned workspace as your product, with the same partner key. A disabled\n * workspace refuses upserts (409 `WORKSPACE_DISABLED`; not retryable) but still\n * erases and lists.\n *\n * AI for the workspace is metered in credits (1 credit = US$0.001). `aiMonthlyCapCredits` is\n * the monthly cap you set per workspace: `null` = no cap, `0` = AI off, N = N credits per UTC\n * calendar month. A workspace created without one gets 5000. `getWorkspaceUsage` reports use\n * over a date range.\n *\n * Retryable: `status` 409 (`PROVISIONING_IN_PROGRESS`, another call for the ref is\n * running) and 503 (`SERVICE_BUSY`). Wait a few seconds (the CRM sends\n * `Retry-After: 5`) and repeat the same call; provisioning resumes where it stopped.\n * 500 and status 0 are also safe to repeat.\n *\n * @packageDocumentation\n */\n\nimport {\n DEFAULT_TIMEOUT_MS,\n errorCodeFrom,\n isRecord,\n normalizeBase,\n resolveFetch,\n sendJson,\n type FetchLike,\n} from './server-http';\nimport type {\n ContactChanges,\n ContactChangesQuery,\n ContactRefUpsertBody,\n ContactRefUpsertResult,\n PartnerContactEraseByIdentityBody,\n PartnerContactEraseByIdentityResult,\n PartnerContactEraseResult,\n PartnerWorkspaceCreated,\n PartnerWorkspaceDetail as WirePartnerWorkspaceDetail,\n PartnerWorkspaceExisting,\n PartnerWorkspacePatchBody as WirePartnerWorkspacePatchBody,\n PartnerWorkspaceSecret,\n PartnerWorkspaceStatus,\n PartnerWorkspaceUpsertBody as WirePartnerWorkspaceUpsertBody,\n PartnerWorkspaceUsage,\n} from './generated/crm-contracts';\n\n// ─── Error class ─────────────────────────────────────────────────────────────\n\n/** A failed partner API call. The message never includes the key, secrets or response bodies. */\nexport class CrmPartnerError extends Error {\n /** HTTP status; 0 when the CRM could not be reached (network failure or timeout). 409 and 503 mean retry shortly. */\n readonly status: number;\n /** The CRM's error code, or `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` / `invalid_limit` / `invalid_cap` / `invalid_date` / `invalid_identity` / `HTTP_<status>`. */\n readonly code: string;\n\n constructor(status: number, code: string) {\n super(status === 0 ? `CRM partner API unreachable (${code})` : `CRM partner API ${status} ${code}`);\n this.name = 'CrmPartnerError';\n this.status = status;\n this.code = code;\n Object.setPrototypeOf(this, CrmPartnerError.prototype);\n }\n}\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Same pattern the CRM enforces on `externalRef`. */\nexport const EXTERNAL_REF_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;\n\n/** Same pattern the CRM enforces on a `contactRef`. */\nexport const CONTACT_REF_PATTERN = /^[A-Za-z0-9._:-]{1,200}$/;\nexport const CONTACT_CHANGES_MAX_LIMIT = 200;\n\nexport interface CrmPartnerClientOptions {\n /** CRM base URL, e.g. `https://crm.example.com` (a trailing `/api` is tolerated). */\n crmBaseUrl: string;\n /** Partner key (`ptk_...`). Server-side secret. */\n partnerKey: string;\n /** Custom fetch (tests, proxies). Defaults to the global `fetch`. */\n fetch?: FetchLike;\n /** Per-request timeout in ms. Default 15000. */\n timeoutMs?: number;\n}\n\n/** Upper bound the CRM accepts for `aiMonthlyCapCredits` (100 million credits). */\nexport const AI_MONTHLY_CAP_MAX_CREDITS = 100_000_000;\n\n/** Fields every workspace response carries. */\nexport interface PartnerWorkspace {\n externalRef: string;\n /** Null until provisioning has created the workspace. */\n workspaceId: string | null;\n /** Null until provisioning has created the embed app. */\n embedAppId: string | null;\n enabled: boolean;\n /**\n * Monthly AI cap in credits: `null` = no cap (also what an older CRM that does not report it\n * returns), `0` = AI off, N = N credits per UTC calendar month.\n */\n aiMonthlyCapCredits: number | null;\n}\n\n/** Body of {@link CrmPartnerClient.upsertWorkspace}. */\nexport type PartnerWorkspaceUpsertBody = Omit<WirePartnerWorkspaceUpsertBody, 'ai_monthly_cap_credits'> & {\n /**\n * Monthly AI cap in credits (integer, 0 to {@link AI_MONTHLY_CAP_MAX_CREDITS}, or `null` for none).\n * Omit on create for the default of 5000; omit on a later call to leave it unchanged.\n */\n aiMonthlyCapCredits?: number | null;\n};\n\n/** Body of {@link CrmPartnerClient.updateWorkspace}. At least one field is required. */\nexport type PartnerWorkspacePatchBody = Omit<WirePartnerWorkspacePatchBody, 'ai_monthly_cap_credits'> & {\n /** Monthly AI cap in credits; `null` removes the cap, `0` switches AI off. */\n aiMonthlyCapCredits?: number | null;\n};\n\n/** Query of {@link CrmPartnerClient.getWorkspaceUsage}: UTC calendar dates, `to` inclusive. */\nexport interface PartnerUsageRange {\n /** `YYYY-MM-DD` (UTC), or a `Date` whose UTC date is used. */\n from: string | Date;\n /** `YYYY-MM-DD` (UTC) or a `Date`; the whole day is included. At most 12 months after `from`. */\n to: string | Date;\n}\n\n/**\n * Result of {@link CrmPartnerClient.upsertWorkspace}. `created: true` (HTTP 201)\n * is the one call that carries `embedAppSecret`, shown once: store it. A repeat\n * call (HTTP 200) has `created: false` and no secret; use `rotateWorkspaceSecret`\n * if it was lost.\n */\nexport type PartnerWorkspaceUpsertResult =\n | (PartnerWorkspace & { created: true; embedAppSecret: string })\n | (PartnerWorkspace & { created: false; embedAppSecret?: undefined });\n\n/** Result of {@link CrmPartnerClient.getWorkspace}. */\nexport interface PartnerWorkspaceDetail extends PartnerWorkspace {\n /** Provisioning progress; `active` once the workspace is ready for sessions. */\n state: WirePartnerWorkspaceDetail['state'];\n /**\n * AI credits used in the current UTC month (`period` is `YYYY-MM`); null until the workspace\n * exists, or when talking to a CRM that does not report it.\n */\n ai: { period: string; usedCredits: number } | null;\n}\n\n/** Result of {@link CrmPartnerClient.rotateWorkspaceSecret}. The old secret stops working at once. */\nexport interface PartnerRotatedSecret {\n embedAppId: string;\n embedAppSecret: string;\n}\n\nexport interface CrmPartnerClient {\n /**\n * Idempotent: provisions the workspace for `externalRef`, or resumes/returns it. Optional\n * `currency` (ISO 4217) and `timezone` (IANA) are applied on create and on any later call that\n * sends them; an invalid value is a 400 `VALIDATION_ERROR` and nothing is provisioned.\n * `aiMonthlyCapCredits` sets the monthly AI cap (see {@link PartnerWorkspaceUpsertBody}).\n */\n upsertWorkspace(externalRef: string, body: PartnerWorkspaceUpsertBody): Promise<PartnerWorkspaceUpsertResult>;\n /** Provisioning status, or `null` when the CRM does not know this ref (404). */\n getWorkspace(externalRef: string): Promise<PartnerWorkspaceDetail | null>;\n /** Enable/disable the embed app, rename the workspace or set its monthly AI cap. At least one field is required. */\n updateWorkspace(externalRef: string, patch: PartnerWorkspacePatchBody): Promise<PartnerWorkspace>;\n /**\n * AI usage of the workspace from `from` to `to` (UTC dates, `to` inclusive, at most 12 months):\n * totals, then the same figures by operation, model and day, plus the current month's cap and\n * the embedded assistant's tokens (which are recorded but not capped). Returned as the CRM\n * sends it (snake_case). `cost_usd` is the provider cost; credits are what the cap counts.\n * Resolves `null` for a ref the CRM does not know or that has no workspace yet (404).\n */\n getWorkspaceUsage(externalRef: string, range: PartnerUsageRange): Promise<PartnerWorkspaceUsage | null>;\n /** Replace the embed app secret. Throws a 404 error for an unknown or not-yet-active ref. */\n rotateWorkspaceSecret(externalRef: string): Promise<PartnerRotatedSecret>;\n /**\n * Idempotent upsert of the contact for `contactRef` (your own key for the person) in the\n * workspace: finds it by ref (then phone, then email) or creates it. `whatsapp_consent`\n * only applies when its `recorded_at` is newer than the stored one and the parent has\n * not replied STOP (`consent_applied` says whether it did). `team_ref` + `team_name` file\n * the contact under your team, created if new. Fails with 409 `WORKSPACE_DISABLED` while the\n * workspace is disabled and 404 for an unknown workspace.\n */\n upsertContact(externalRef: string, contactRef: string, body: ContactRefUpsertBody): Promise<ContactRefUpsertResult>;\n /**\n * PDPA erasure: overwrites the contact's personal data, soft-deletes it and removes its refs.\n * Resolves `null` when the CRM has no contact for this ref (404: never synced, or already\n * erased). Works while the workspace is disabled. An unknown workspace is also a 404, so it\n * also resolves `null`; use `getWorkspace` to tell them apart.\n */\n eraseContact(externalRef: string, contactRef: string): Promise<PartnerContactEraseResult | null>;\n /**\n * PDPA erasure of the contacts that match a person's phone (E.164) or email (case-insensitive)\n * and that your product never linked by ref, such as a parent who wrote first on WhatsApp.\n * Send `ref` (the erased person's own `contactRef`) so a contact linked only to that ref is\n * erased too. A matched contact with any other ref (another person of yours, or another\n * product) is left alone and counted in `skipped_linked_elsewhere`, so a shared family number\n * survives. At least one of `phone` or `email` is required (a client-side 400\n * `invalid_identity` otherwise). Works while the workspace is disabled. No match resolves\n * `erased: 0`. Resolves `null` for an unknown workspace (404).\n */\n eraseContactsByIdentity(externalRef: string, identity: PartnerContactEraseByIdentityBody): Promise<PartnerContactEraseByIdentityResult | null>;\n /**\n * One page of the contacts changes feed (oldest first, includes deleted contacts). Pass `since`\n * for the first page and the returned `next_cursor` as `cursor` until it is null. `limit` is 1\n * to 200 (default 100). Works while the workspace is disabled; an unknown workspace throws 404.\n */\n listContactChanges(externalRef: string, query?: { since?: string; cursor?: string; limit?: number }): Promise<ContactChanges>;\n}\n\n// ─── Implementation ──────────────────────────────────────────────────────────\n\nconst fromStatus = (w: PartnerWorkspaceStatus): PartnerWorkspace => ({\n externalRef: w.external_ref,\n workspaceId: w.workspace_id,\n embedAppId: w.embed_app_id,\n enabled: w.enabled,\n // Absent on a CRM from before the AI cap: reported as no cap.\n aiMonthlyCapCredits: typeof w.ai_monthly_cap_credits === 'number' ? w.ai_monthly_cap_credits : null,\n});\n\nconst USAGE_DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/** `YYYY-MM-DD` as given, or the UTC date of a `Date`; anything else is a 400 `invalid_date`. */\nfunction usageDate(value: string | Date): string {\n const text = value instanceof Date && !Number.isNaN(value.getTime()) ? value.toISOString().slice(0, 10) : value;\n if (typeof text !== 'string' || !USAGE_DATE.test(text)\n || Number.isNaN(Date.parse(`${text}T00:00:00Z`))\n || new Date(`${text}T00:00:00Z`).toISOString().slice(0, 10) !== text) {\n throw new CrmPartnerError(400, 'invalid_date');\n }\n return text;\n}\n\n/** Throws a 400 `invalid_cap` for anything the CRM would refuse, so a typo never leaves the process. */\nfunction checkCap(cap: number | null | undefined): number | null | undefined {\n if (cap === undefined || cap === null) return cap;\n if (typeof cap !== 'number' || !Number.isInteger(cap) || cap < 0 || cap > AI_MONTHLY_CAP_MAX_CREDITS) {\n throw new CrmPartnerError(400, 'invalid_cap');\n }\n return cap;\n}\n\nconst isNullableString = (v: unknown): v is string | null => v === null || typeof v === 'string';\n\nfunction isStatus(v: unknown): v is PartnerWorkspaceStatus {\n return isRecord(v)\n && typeof v.external_ref === 'string'\n && isNullableString(v.workspace_id)\n && isNullableString(v.embed_app_id)\n && typeof v.enabled === 'boolean';\n}\n\nexport function createCrmPartnerClient(opts: CrmPartnerClientOptions): CrmPartnerClient {\n if (!opts.crmBaseUrl) throw new Error('createCrmPartnerClient: `crmBaseUrl` is required.');\n if (!opts.partnerKey) throw new Error('createCrmPartnerClient: `partnerKey` is required.');\n const fetchImpl = resolveFetch(opts.fetch, 'createCrmPartnerClient');\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const base = `${normalizeBase(opts.crmBaseUrl)}/api/partner/v1/workspaces`;\n const redact = [opts.partnerKey];\n\n function checkRef(externalRef: string): string {\n if (typeof externalRef !== 'string' || !EXTERNAL_REF_PATTERN.test(externalRef)) {\n throw new CrmPartnerError(400, 'invalid_external_ref');\n }\n return externalRef;\n }\n\n async function call(method: string, path: string, body?: unknown): Promise<{ status: number; json: unknown }> {\n const res = await sendJson(fetchImpl, timeoutMs, `${base}/${path}`, {\n method,\n headers: { Authorization: `Bearer ${opts.partnerKey}` },\n body,\n });\n if (!res.ok) throw new CrmPartnerError(0, res.kind);\n if (res.status < 200 || res.status >= 300) {\n throw new CrmPartnerError(res.status, errorCodeFrom(res.json, res.status, redact));\n }\n return { status: res.status, json: res.json };\n }\n\n const bad = (status: number) => new CrmPartnerError(status, 'bad_response');\n\n function checkContactRef(contactRef: string): string {\n if (typeof contactRef !== 'string' || !CONTACT_REF_PATTERN.test(contactRef)) {\n throw new CrmPartnerError(400, 'invalid_contact_ref');\n }\n return contactRef;\n }\n\n return {\n async upsertWorkspace(externalRef, body) {\n const ref = checkRef(externalRef);\n const { aiMonthlyCapCredits, ...rest } = body;\n const cap = checkCap(aiMonthlyCapCredits);\n const wireBody: WirePartnerWorkspaceUpsertBody = cap === undefined ? rest : { ...rest, ai_monthly_cap_credits: cap };\n const { status, json } = await call('PUT', ref, wireBody);\n if (!isStatus(json)) throw bad(status);\n const wire = json as PartnerWorkspaceCreated | PartnerWorkspaceExisting;\n if (wire.created === true) {\n const secret = (wire as PartnerWorkspaceCreated).embed_app_secret;\n if (typeof secret !== 'string' || !secret) throw bad(status);\n return { ...fromStatus(wire), created: true, embedAppSecret: secret };\n }\n if (wire.created === false) return { ...fromStatus(wire), created: false };\n throw bad(status);\n },\n\n async getWorkspace(externalRef) {\n const ref = checkRef(externalRef);\n try {\n const { status, json } = await call('GET', ref);\n if (!isStatus(json) || typeof (json as Record<string, unknown>).state !== 'string') throw bad(status);\n const ai = (json as unknown as WirePartnerWorkspaceDetail).ai;\n return {\n ...fromStatus(json),\n state: (json as unknown as WirePartnerWorkspaceDetail).state,\n ai: isRecord(ai) && typeof ai.period === 'string' && typeof ai.used_credits === 'number'\n ? { period: ai.period, usedCredits: ai.used_credits }\n : null,\n };\n } catch (err) {\n if (err instanceof CrmPartnerError && err.status === 404) return null;\n throw err;\n }\n },\n\n async updateWorkspace(externalRef, patch) {\n const ref = checkRef(externalRef);\n const body: WirePartnerWorkspacePatchBody = {};\n if (patch.enabled !== undefined) body.enabled = patch.enabled;\n if (patch.name !== undefined) body.name = patch.name;\n const cap = checkCap(patch.aiMonthlyCapCredits);\n if (cap !== undefined) body.ai_monthly_cap_credits = cap;\n const { status, json } = await call('PATCH', ref, body);\n if (!isStatus(json)) throw bad(status);\n return fromStatus(json);\n },\n\n async getWorkspaceUsage(externalRef, range) {\n const ref = checkRef(externalRef);\n const qs = new URLSearchParams({ from: usageDate(range.from), to: usageDate(range.to) });\n try {\n const { status, json } = await call('GET', `${ref}/usage?${qs.toString()}`);\n if (!isRecord(json) || !isRecord(json.totals) || !isRecord(json.cap) || !Array.isArray(json.by_operation)) throw bad(status);\n return json as unknown as PartnerWorkspaceUsage;\n } catch (err) {\n if (err instanceof CrmPartnerError && err.status === 404) return null;\n throw err;\n }\n },\n\n async rotateWorkspaceSecret(externalRef) {\n const ref = checkRef(externalRef);\n const { status, json } = await call('POST', `${ref}/rotate-secret`);\n const w = json as Partial<PartnerWorkspaceSecret> | null;\n if (!isRecord(json) || typeof w?.embed_app_id !== 'string' || typeof w.embed_app_secret !== 'string' || !w.embed_app_secret) {\n throw bad(status);\n }\n return { embedAppId: w.embed_app_id, embedAppSecret: w.embed_app_secret };\n },\n\n async upsertContact(externalRef, contactRef, body) {\n const ref = checkRef(externalRef);\n const cref = checkContactRef(contactRef);\n const { status, json } = await call('PUT', `${ref}/contacts/${encodeURIComponent(cref)}`, body);\n if (!isRecord(json) || !isRecord(json.contact) || typeof json.created !== 'boolean' || typeof json.consent_applied !== 'boolean') {\n throw bad(status);\n }\n return json as unknown as ContactRefUpsertResult;\n },\n\n async eraseContact(externalRef, contactRef) {\n const ref = checkRef(externalRef);\n const cref = checkContactRef(contactRef);\n try {\n const { status, json } = await call('DELETE', `${ref}/contacts/${encodeURIComponent(cref)}`);\n if (!isRecord(json) || json.erased !== true || typeof json.contact_id !== 'string') throw bad(status);\n return json as unknown as PartnerContactEraseResult;\n } catch (err) {\n if (err instanceof CrmPartnerError && err.status === 404) return null;\n throw err;\n }\n },\n\n async eraseContactsByIdentity(externalRef, identity) {\n const ref = checkRef(externalRef);\n const phone = typeof identity?.phone === 'string' ? identity.phone.trim() : undefined;\n const email = typeof identity?.email === 'string' ? identity.email.trim() : undefined;\n const hasPhone = phone !== undefined && /\\d/.test(phone);\n const hasEmail = email !== undefined && email.includes('@');\n if ((identity?.phone !== undefined && !hasPhone) || (identity?.email !== undefined && !hasEmail) || (!hasPhone && !hasEmail)) {\n throw new CrmPartnerError(400, 'invalid_identity');\n }\n if (identity.ref !== undefined) checkContactRef(identity.ref);\n const body: PartnerContactEraseByIdentityBody = {};\n if (hasPhone) body.phone = phone;\n if (hasEmail) body.email = email;\n if (identity.ref !== undefined) body.ref = identity.ref;\n try {\n const { status, json } = await call('POST', `${ref}/contacts/erase-by-identity`, body);\n if (\n !isRecord(json)\n || typeof json.erased !== 'number'\n || !Array.isArray(json.contact_ids)\n || typeof json.skipped_linked_elsewhere !== 'number'\n ) {\n throw bad(status);\n }\n return json as unknown as PartnerContactEraseByIdentityResult;\n } catch (err) {\n if (err instanceof CrmPartnerError && err.status === 404) return null;\n throw err;\n }\n },\n\n async listContactChanges(externalRef, query = {}) {\n const ref = checkRef(externalRef);\n const { since, cursor, limit } = query;\n if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > CONTACT_CHANGES_MAX_LIMIT)) {\n throw new CrmPartnerError(400, 'invalid_limit');\n }\n const qs = new URLSearchParams();\n if (since !== undefined) qs.set('since', since);\n if (cursor !== undefined) qs.set('cursor', cursor);\n if (limit !== undefined) qs.set('limit', String(limit));\n const q = qs.toString();\n const { status, json } = await call('GET', `${ref}/contacts/changes${q ? `?${q}` : ''}`);\n if (!isRecord(json) || !Array.isArray(json.items) || !(json.next_cursor === null || typeof json.next_cursor === 'string')) {\n throw bad(status);\n }\n return json as unknown as ContactChanges;\n },\n };\n}\n\n// Re-exported so partner code can type its inputs without importing the contracts module.\nexport type {\n ContactChanges,\n ContactChangesQuery,\n ContactRefUpsertBody,\n ContactRefUpsertResult,\n PartnerContactEraseByIdentityBody,\n PartnerContactEraseByIdentityResult,\n PartnerContactEraseResult,\n PartnerWorkspaceUsage,\n};\n"],"mappings":"AAkBO,SAASA,EAAcC,EAA4B,CACxD,OAAOA,EAAW,QAAQ,OAAQ,EAAE,EAAE,QAAQ,SAAU,EAAE,CAC5D,CAEO,SAASC,EAAaC,EAAkCC,EAAwB,CACrF,IAAMC,EAAIF,GAAa,WAAW,MAClC,GAAI,OAAOE,GAAM,WACf,MAAM,IAAI,MAAM,GAAGD,CAAG,iEAAiE,EAEzF,OAAOC,CACT,CAMA,eAAsBC,EACpBH,EACAI,EACAC,EACAC,EACoB,CACpB,IAAMC,EAAa,IAAI,gBACnBC,EAAW,GACTC,EAAQ,WAAW,IAAM,CAC7BD,EAAW,GACXD,EAAW,MAAM,CACnB,EAAGH,CAAS,EACZ,GAAI,CACF,IAAMM,EAAkC,CAAE,OAAQ,mBAAoB,GAAGJ,EAAK,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AE,EAAE,EACvF,GAAI,CAAC3C,EAASyB,CAAI,GAAK,CAAC,MAAM,QAAQA,EAAK,KAAK,GAAK,EAAEA,EAAK,cAAgB,MAAQ,OAAOA,EAAK,aAAgB,UAC9G,MAAMP,EAAInC,CAAM,EAElB,OAAO0C,CACT,CACF,CACF","names":["normalizeBase","crmBaseUrl","resolveFetch","fetchImpl","who","f","sendJson","timeoutMs","url","init","controller","timedOut","timer","headers","hasBody","res","json","SAFE_CODE","errorCodeFrom","status","redact","fallback","pick","v","r","o","err","isRecord","CrmPartnerError","_CrmPartnerError","status","code","EXTERNAL_REF_PATTERN","CONTACT_REF_PATTERN","CONTACT_CHANGES_MAX_LIMIT","AI_MONTHLY_CAP_MAX_CREDITS","fromStatus","w","USAGE_DATE","usageDate","value","text","checkCap","cap","isNullableString","v","isStatus","isRecord","createCrmPartnerClient","opts","fetchImpl","resolveFetch","timeoutMs","base","normalizeBase","redact","checkRef","externalRef","call","method","path","body","res","sendJson","errorCodeFrom","bad","checkContactRef","contactRef","ref","aiMonthlyCapCredits","rest","wireBody","json","wire","secret","ai","err","patch","range","qs","cref","identity","phone","email","hasPhone","hasEmail","query","since","cursor","limit","q"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@first-to-fly/crm-sdk",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.10.0",
|
|
4
4
|
"description": "CRM SDK — embed third-party apps inside the CRM, or embed the CRM inside your own SaaS (proxy-free, signed-assertion or API-key auth)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.cjs",
|