@first-to-fly/crm-sdk 1.9.0 → 1.11.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 +264 -7
- package/dist/api.cjs +1 -1
- package/dist/api.cjs.map +1 -1
- package/dist/api.d.cts +4 -4
- package/dist/api.d.ts +4 -4
- package/dist/api.js +1 -1
- package/dist/api.js.map +1 -1
- package/dist/{crm-contracts-BiR0JbKC.d.cts → crm-contracts-BeC2pzgj.d.cts} +102 -5
- package/dist/{crm-contracts-BiR0JbKC.d.ts → crm-contracts-BeC2pzgj.d.ts} +102 -5
- package/dist/embed-host.cjs +1 -1
- package/dist/embed-host.cjs.map +1 -1
- package/dist/embed-host.d.cts +61 -2
- package/dist/embed-host.d.ts +61 -2
- 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 +44 -1
- package/dist/embed-react.d.ts +44 -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 +186 -11
- package/dist/partner.d.ts +186 -11
- package/dist/partner.js +1 -1
- package/dist/partner.js.map +1 -1
- package/package.json +6 -1
package/dist/api.js.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":"AAoIO,IAAMA,EAAN,MAAMC,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,CA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AS3C,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,IAAOkB,EAAQ3B","names":["CrmApiError","_CrmApiError","status","code","message","body","options","serializeQuery","query","params","key","value","el","qs","isEnvelope","v","deriveError","parsed","envelope","rawError","envMessage","errorObj","errorObjCode","errorObjMessage","errorStr","createCrmApiClient","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","api_default"]}
|
|
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":"AAqIO,IAAMA,EAAN,MAAMC,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,SAAS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AE,KAAA/C,CAAK,CACT,CACJ,CACF,EACA,KAAM,CACJ,KAAOG,GAAU2B,EAAoC,MAAO,QAAS,CAAE,MAAO3B,CAAqB,CAAC,EACpG,OAASH,GAAS8B,EAAa,OAAQ,QAAS,CAAE,KAAA9B,CAAK,CAAC,CAC1D,EACA,QAAA8B,CACF,CACF,CAEA,IAAOkB,EAAQ3B","names":["CrmApiError","_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","createCrmApiClient","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","api_default"]}
|
|
@@ -146,6 +146,9 @@ type Contact = {
|
|
|
146
146
|
merged_count?: number | undefined;
|
|
147
147
|
last_message_at?: (string | undefined) | null;
|
|
148
148
|
last_message_preview?: (string | undefined) | null;
|
|
149
|
+
last_message_sender?: (string | undefined) | null;
|
|
150
|
+
is_group?: boolean | undefined;
|
|
151
|
+
group_name?: (string | undefined) | null;
|
|
149
152
|
}[] | undefined;
|
|
150
153
|
email_suppression?: ({
|
|
151
154
|
id: string;
|
|
@@ -214,6 +217,9 @@ type ContactList = {
|
|
|
214
217
|
merged_count?: number | undefined;
|
|
215
218
|
last_message_at?: (string | undefined) | null;
|
|
216
219
|
last_message_preview?: (string | undefined) | null;
|
|
220
|
+
last_message_sender?: (string | undefined) | null;
|
|
221
|
+
is_group?: boolean | undefined;
|
|
222
|
+
group_name?: (string | undefined) | null;
|
|
217
223
|
}[] | undefined;
|
|
218
224
|
email_suppression?: ({
|
|
219
225
|
id: string;
|
|
@@ -303,6 +309,9 @@ type ContactRefUpsertResult = {
|
|
|
303
309
|
merged_count?: number | undefined;
|
|
304
310
|
last_message_at?: (string | undefined) | null;
|
|
305
311
|
last_message_preview?: (string | undefined) | null;
|
|
312
|
+
last_message_sender?: (string | undefined) | null;
|
|
313
|
+
is_group?: boolean | undefined;
|
|
314
|
+
group_name?: (string | undefined) | null;
|
|
306
315
|
}[] | undefined;
|
|
307
316
|
email_suppression?: ({
|
|
308
317
|
id: string;
|
|
@@ -349,11 +358,15 @@ type PartnerWorkspaceUpsertBody = {
|
|
|
349
358
|
ai_monthly_cap_credits?: (number | null) | undefined;
|
|
350
359
|
currency?: string | undefined;
|
|
351
360
|
timezone?: string | undefined;
|
|
361
|
+
partner_channel_enabled?: boolean | undefined;
|
|
362
|
+
webhook_url?: (string | null) | undefined;
|
|
352
363
|
};
|
|
353
364
|
type PartnerWorkspacePatchBody = {
|
|
354
365
|
enabled?: boolean | undefined;
|
|
355
366
|
name?: string | undefined;
|
|
356
367
|
ai_monthly_cap_credits?: (number | null) | undefined;
|
|
368
|
+
partner_channel_enabled?: boolean | undefined;
|
|
369
|
+
webhook_url?: (string | null) | undefined;
|
|
357
370
|
};
|
|
358
371
|
type PartnerWorkspaceCreated = {
|
|
359
372
|
external_ref: string;
|
|
@@ -361,6 +374,8 @@ type PartnerWorkspaceCreated = {
|
|
|
361
374
|
embed_app_id: string | null;
|
|
362
375
|
enabled: boolean;
|
|
363
376
|
ai_monthly_cap_credits: number | null;
|
|
377
|
+
partner_channel_enabled: boolean;
|
|
378
|
+
webhook_url: string | null;
|
|
364
379
|
embed_app_secret: string;
|
|
365
380
|
created: true;
|
|
366
381
|
};
|
|
@@ -370,6 +385,8 @@ type PartnerWorkspaceExisting = {
|
|
|
370
385
|
embed_app_id: string | null;
|
|
371
386
|
enabled: boolean;
|
|
372
387
|
ai_monthly_cap_credits: number | null;
|
|
388
|
+
partner_channel_enabled: boolean;
|
|
389
|
+
webhook_url: string | null;
|
|
373
390
|
created: false;
|
|
374
391
|
};
|
|
375
392
|
type PartnerWorkspaceStatus = {
|
|
@@ -378,6 +395,8 @@ type PartnerWorkspaceStatus = {
|
|
|
378
395
|
embed_app_id: string | null;
|
|
379
396
|
enabled: boolean;
|
|
380
397
|
ai_monthly_cap_credits: number | null;
|
|
398
|
+
partner_channel_enabled: boolean;
|
|
399
|
+
webhook_url: string | null;
|
|
381
400
|
};
|
|
382
401
|
type PartnerWorkspaceDetail = {
|
|
383
402
|
external_ref: string;
|
|
@@ -385,6 +404,8 @@ type PartnerWorkspaceDetail = {
|
|
|
385
404
|
embed_app_id: string | null;
|
|
386
405
|
enabled: boolean;
|
|
387
406
|
ai_monthly_cap_credits: number | null;
|
|
407
|
+
partner_channel_enabled: boolean;
|
|
408
|
+
webhook_url: string | null;
|
|
388
409
|
state: "pending" | "owner_created" | "workspace_created" | "app_installed" | "sub_app_created" | "active";
|
|
389
410
|
ai: {
|
|
390
411
|
period: string;
|
|
@@ -467,6 +488,76 @@ type PartnerContactEraseByIdentityResult = {
|
|
|
467
488
|
contact_ids: string[];
|
|
468
489
|
skipped_linked_elsewhere: number;
|
|
469
490
|
};
|
|
491
|
+
type PartnerInboundMessageBody = {
|
|
492
|
+
contact_ref: string;
|
|
493
|
+
thread_ref: string;
|
|
494
|
+
message_ref: string;
|
|
495
|
+
body: string;
|
|
496
|
+
sent_at: string;
|
|
497
|
+
title?: string | undefined;
|
|
498
|
+
team_ref?: string | undefined;
|
|
499
|
+
direction?: "inbound" | undefined;
|
|
500
|
+
};
|
|
501
|
+
type PartnerInboundMessageResult = {
|
|
502
|
+
conversation_id: string;
|
|
503
|
+
message_id: string;
|
|
504
|
+
created: boolean;
|
|
505
|
+
};
|
|
506
|
+
type PartnerThreadDeleteResult = {
|
|
507
|
+
deleted: boolean;
|
|
508
|
+
};
|
|
509
|
+
type PartnerMessageChangesQuery = {
|
|
510
|
+
cursor?: string | undefined;
|
|
511
|
+
limit?: number;
|
|
512
|
+
};
|
|
513
|
+
type PartnerMessageChange = {
|
|
514
|
+
delivery_id: string;
|
|
515
|
+
external_ref: string;
|
|
516
|
+
thread_ref: string;
|
|
517
|
+
conversation_id: string;
|
|
518
|
+
message_id: string;
|
|
519
|
+
body: string;
|
|
520
|
+
sent_at: string;
|
|
521
|
+
sender: {
|
|
522
|
+
user_ref: string | null;
|
|
523
|
+
name: string;
|
|
524
|
+
};
|
|
525
|
+
delivery_status: "pending" | "delivered" | "failed";
|
|
526
|
+
};
|
|
527
|
+
type PartnerMessageChanges = {
|
|
528
|
+
items: {
|
|
529
|
+
delivery_id: string;
|
|
530
|
+
external_ref: string;
|
|
531
|
+
thread_ref: string;
|
|
532
|
+
conversation_id: string;
|
|
533
|
+
message_id: string;
|
|
534
|
+
body: string;
|
|
535
|
+
sent_at: string;
|
|
536
|
+
sender: {
|
|
537
|
+
user_ref: string | null;
|
|
538
|
+
name: string;
|
|
539
|
+
};
|
|
540
|
+
delivery_status: "pending" | "delivered" | "failed";
|
|
541
|
+
}[];
|
|
542
|
+
next_cursor: string | null;
|
|
543
|
+
};
|
|
544
|
+
type PartnerWebhookPutBody = {
|
|
545
|
+
url: string;
|
|
546
|
+
};
|
|
547
|
+
type PartnerWebhookCreated = {
|
|
548
|
+
url: string;
|
|
549
|
+
secret: string;
|
|
550
|
+
};
|
|
551
|
+
type PartnerWebhookUpdated = {
|
|
552
|
+
url: string;
|
|
553
|
+
};
|
|
554
|
+
type PartnerWebhookGet = {
|
|
555
|
+
url: string;
|
|
556
|
+
has_secret: true;
|
|
557
|
+
};
|
|
558
|
+
type PartnerWebhookRotate = {
|
|
559
|
+
secret: string;
|
|
560
|
+
};
|
|
470
561
|
type LeadCreate = {
|
|
471
562
|
status?: string | undefined;
|
|
472
563
|
assigned_to?: (string | undefined) | null;
|
|
@@ -792,10 +883,11 @@ type ConversationQuery = {
|
|
|
792
883
|
page?: number;
|
|
793
884
|
limit?: number;
|
|
794
885
|
pageSize?: number;
|
|
886
|
+
cursor?: string | undefined;
|
|
795
887
|
search?: string | undefined;
|
|
796
888
|
assignment?: (("me" | "unassigned" | "assigned" | "others") | string) | undefined;
|
|
797
889
|
status?: string | string[];
|
|
798
|
-
channel?: ("whatsapp" | "whatsapp_web" | "messenger" | "instagram" | "email" | "sms" | "webchat" | "website_form" | "voice") | undefined;
|
|
890
|
+
channel?: ("whatsapp" | "whatsapp_web" | "messenger" | "instagram" | "email" | "sms" | "webchat" | "website_form" | "partner_app" | "voice") | undefined;
|
|
799
891
|
channel_id?: string | string[];
|
|
800
892
|
team_id?: string | string[];
|
|
801
893
|
tags?: string | undefined;
|
|
@@ -810,6 +902,9 @@ type ConversationQuery = {
|
|
|
810
902
|
exclude_groups?: boolean | undefined;
|
|
811
903
|
contact_id?: string | undefined;
|
|
812
904
|
lead_stage?: string | undefined;
|
|
905
|
+
/** A contact must belong to every selected audience */
|
|
906
|
+
audience_ids?: string;
|
|
907
|
+
audience_id?: (string | string) | undefined;
|
|
813
908
|
system_audience_id?: string | undefined;
|
|
814
909
|
};
|
|
815
910
|
type ConversationUpdate = {
|
|
@@ -841,7 +936,7 @@ type Conversation = {
|
|
|
841
936
|
metadata: {
|
|
842
937
|
conversation_status: ("active" | "blocked" | "archived" | "reopened" | "on_hold") | null;
|
|
843
938
|
statuses?: ("active" | "blocked" | "archived" | "reopened" | "on_hold")[];
|
|
844
|
-
channel: "whatsapp" | "whatsapp_web" | "sms" | "email" | "messenger" | "instagram" | "website_form" | "voice";
|
|
939
|
+
channel: "whatsapp" | "whatsapp_web" | "sms" | "email" | "messenger" | "instagram" | "website_form" | "partner_app" | "voice";
|
|
845
940
|
unread_count: number;
|
|
846
941
|
total_message_count: number;
|
|
847
942
|
is_within_24h_window: boolean;
|
|
@@ -872,6 +967,8 @@ type Conversation = {
|
|
|
872
967
|
created_at: string;
|
|
873
968
|
updated_at: string;
|
|
874
969
|
};
|
|
970
|
+
title: string | null;
|
|
971
|
+
thread_ref: string | null;
|
|
875
972
|
recipient_suppressed: boolean;
|
|
876
973
|
recipient_suppression?: ({
|
|
877
974
|
id: string;
|
|
@@ -893,7 +990,7 @@ type MessageQuery = {
|
|
|
893
990
|
};
|
|
894
991
|
type MessageCreate = {
|
|
895
992
|
message?: string | undefined;
|
|
896
|
-
channel?: ("sms" | "whatsapp" | "whatsapp_web" | "email" | "messenger" | "instagram" | "telegram" | "webchat" | "website_form") | undefined;
|
|
993
|
+
channel?: ("sms" | "whatsapp" | "whatsapp_web" | "email" | "messenger" | "instagram" | "telegram" | "webchat" | "website_form" | "partner_app") | undefined;
|
|
897
994
|
channel_id?: string | undefined;
|
|
898
995
|
target_conversation_id?: string | undefined;
|
|
899
996
|
reply_to_id?: string | undefined;
|
|
@@ -941,7 +1038,7 @@ type Message = {
|
|
|
941
1038
|
};
|
|
942
1039
|
message: string;
|
|
943
1040
|
direction: "inbound" | "outbound";
|
|
944
|
-
channel: "sms" | "whatsapp" | "email" | "messenger" | "instagram" | "website_form" | "voice";
|
|
1041
|
+
channel: "sms" | "whatsapp" | "email" | "messenger" | "instagram" | "website_form" | "partner_app" | "voice";
|
|
945
1042
|
status: "sent" | "delivered" | "read" | "failed";
|
|
946
1043
|
type: "text" | "image" | "video" | "audio" | "document" | "sticker" | "contacts" | "reaction" | "activity";
|
|
947
1044
|
message_sid?: string | undefined;
|
|
@@ -1091,4 +1188,4 @@ interface ListEnvelope<T> {
|
|
|
1091
1188
|
pageSize: number;
|
|
1092
1189
|
}
|
|
1093
1190
|
|
|
1094
|
-
export type { ContactRefUpsertResult as A, LeadCapture as B, ContactQuery as C, LeadNote as D, LeadNoteCreate as E, PartnerContactEraseByIdentityBody as F, PartnerContactEraseByIdentityResult as G, PartnerContactEraseResult as H,
|
|
1191
|
+
export type { PartnerWorkspaceSecret as $, ContactRefUpsertResult as A, LeadCapture as B, ContactQuery as C, LeadNote as D, LeadNoteCreate as E, PartnerContactEraseByIdentityBody as F, PartnerContactEraseByIdentityResult as G, PartnerContactEraseResult as H, PartnerInboundMessageBody as I, PartnerInboundMessageResult as J, PartnerMessageChange as K, LeadQuery as L, MessageQuery as M, PartnerMessageChanges as N, PartnerMessageChangesQuery as O, ProductQuery as P, PartnerThreadDeleteResult as Q, PartnerWebhookCreated as R, PartnerWebhookGet as S, TaskQuery as T, PartnerWebhookPutBody as U, PartnerWebhookRotate as V, PartnerWebhookUpdated as W, PartnerWorkspaceCreated as X, PartnerWorkspaceDetail as Y, PartnerWorkspaceExisting as Z, PartnerWorkspacePatchBody as _, ContactList as a, PartnerWorkspaceStatus as a0, PartnerWorkspaceUpsertBody as a1, PartnerWorkspaceUsage as a2, PartnerWorkspaceUsageQuery as a3, TagList as a4, Contact as b, ContactCreate as c, ContactUpdate as d, ListEnvelope as e, Lead as f, LeadCreate as g, LeadUpdate as h, Task as i, LegacyTaskUpdate as j, LegacyTask as k, Product as l, ProductCreate as m, ProductUpdate as n, ConversationQuery as o, Conversation as p, ConversationUpdate as q, Message as r, MessageCreate as s, TagQuery as t, TagWithUsage as u, TagCreate as v, Tag as w, ContactChanges as x, ContactChangesQuery as y, ContactRefUpsertBody as z };
|
|
@@ -146,6 +146,9 @@ type Contact = {
|
|
|
146
146
|
merged_count?: number | undefined;
|
|
147
147
|
last_message_at?: (string | undefined) | null;
|
|
148
148
|
last_message_preview?: (string | undefined) | null;
|
|
149
|
+
last_message_sender?: (string | undefined) | null;
|
|
150
|
+
is_group?: boolean | undefined;
|
|
151
|
+
group_name?: (string | undefined) | null;
|
|
149
152
|
}[] | undefined;
|
|
150
153
|
email_suppression?: ({
|
|
151
154
|
id: string;
|
|
@@ -214,6 +217,9 @@ type ContactList = {
|
|
|
214
217
|
merged_count?: number | undefined;
|
|
215
218
|
last_message_at?: (string | undefined) | null;
|
|
216
219
|
last_message_preview?: (string | undefined) | null;
|
|
220
|
+
last_message_sender?: (string | undefined) | null;
|
|
221
|
+
is_group?: boolean | undefined;
|
|
222
|
+
group_name?: (string | undefined) | null;
|
|
217
223
|
}[] | undefined;
|
|
218
224
|
email_suppression?: ({
|
|
219
225
|
id: string;
|
|
@@ -303,6 +309,9 @@ type ContactRefUpsertResult = {
|
|
|
303
309
|
merged_count?: number | undefined;
|
|
304
310
|
last_message_at?: (string | undefined) | null;
|
|
305
311
|
last_message_preview?: (string | undefined) | null;
|
|
312
|
+
last_message_sender?: (string | undefined) | null;
|
|
313
|
+
is_group?: boolean | undefined;
|
|
314
|
+
group_name?: (string | undefined) | null;
|
|
306
315
|
}[] | undefined;
|
|
307
316
|
email_suppression?: ({
|
|
308
317
|
id: string;
|
|
@@ -349,11 +358,15 @@ type PartnerWorkspaceUpsertBody = {
|
|
|
349
358
|
ai_monthly_cap_credits?: (number | null) | undefined;
|
|
350
359
|
currency?: string | undefined;
|
|
351
360
|
timezone?: string | undefined;
|
|
361
|
+
partner_channel_enabled?: boolean | undefined;
|
|
362
|
+
webhook_url?: (string | null) | undefined;
|
|
352
363
|
};
|
|
353
364
|
type PartnerWorkspacePatchBody = {
|
|
354
365
|
enabled?: boolean | undefined;
|
|
355
366
|
name?: string | undefined;
|
|
356
367
|
ai_monthly_cap_credits?: (number | null) | undefined;
|
|
368
|
+
partner_channel_enabled?: boolean | undefined;
|
|
369
|
+
webhook_url?: (string | null) | undefined;
|
|
357
370
|
};
|
|
358
371
|
type PartnerWorkspaceCreated = {
|
|
359
372
|
external_ref: string;
|
|
@@ -361,6 +374,8 @@ type PartnerWorkspaceCreated = {
|
|
|
361
374
|
embed_app_id: string | null;
|
|
362
375
|
enabled: boolean;
|
|
363
376
|
ai_monthly_cap_credits: number | null;
|
|
377
|
+
partner_channel_enabled: boolean;
|
|
378
|
+
webhook_url: string | null;
|
|
364
379
|
embed_app_secret: string;
|
|
365
380
|
created: true;
|
|
366
381
|
};
|
|
@@ -370,6 +385,8 @@ type PartnerWorkspaceExisting = {
|
|
|
370
385
|
embed_app_id: string | null;
|
|
371
386
|
enabled: boolean;
|
|
372
387
|
ai_monthly_cap_credits: number | null;
|
|
388
|
+
partner_channel_enabled: boolean;
|
|
389
|
+
webhook_url: string | null;
|
|
373
390
|
created: false;
|
|
374
391
|
};
|
|
375
392
|
type PartnerWorkspaceStatus = {
|
|
@@ -378,6 +395,8 @@ type PartnerWorkspaceStatus = {
|
|
|
378
395
|
embed_app_id: string | null;
|
|
379
396
|
enabled: boolean;
|
|
380
397
|
ai_monthly_cap_credits: number | null;
|
|
398
|
+
partner_channel_enabled: boolean;
|
|
399
|
+
webhook_url: string | null;
|
|
381
400
|
};
|
|
382
401
|
type PartnerWorkspaceDetail = {
|
|
383
402
|
external_ref: string;
|
|
@@ -385,6 +404,8 @@ type PartnerWorkspaceDetail = {
|
|
|
385
404
|
embed_app_id: string | null;
|
|
386
405
|
enabled: boolean;
|
|
387
406
|
ai_monthly_cap_credits: number | null;
|
|
407
|
+
partner_channel_enabled: boolean;
|
|
408
|
+
webhook_url: string | null;
|
|
388
409
|
state: "pending" | "owner_created" | "workspace_created" | "app_installed" | "sub_app_created" | "active";
|
|
389
410
|
ai: {
|
|
390
411
|
period: string;
|
|
@@ -467,6 +488,76 @@ type PartnerContactEraseByIdentityResult = {
|
|
|
467
488
|
contact_ids: string[];
|
|
468
489
|
skipped_linked_elsewhere: number;
|
|
469
490
|
};
|
|
491
|
+
type PartnerInboundMessageBody = {
|
|
492
|
+
contact_ref: string;
|
|
493
|
+
thread_ref: string;
|
|
494
|
+
message_ref: string;
|
|
495
|
+
body: string;
|
|
496
|
+
sent_at: string;
|
|
497
|
+
title?: string | undefined;
|
|
498
|
+
team_ref?: string | undefined;
|
|
499
|
+
direction?: "inbound" | undefined;
|
|
500
|
+
};
|
|
501
|
+
type PartnerInboundMessageResult = {
|
|
502
|
+
conversation_id: string;
|
|
503
|
+
message_id: string;
|
|
504
|
+
created: boolean;
|
|
505
|
+
};
|
|
506
|
+
type PartnerThreadDeleteResult = {
|
|
507
|
+
deleted: boolean;
|
|
508
|
+
};
|
|
509
|
+
type PartnerMessageChangesQuery = {
|
|
510
|
+
cursor?: string | undefined;
|
|
511
|
+
limit?: number;
|
|
512
|
+
};
|
|
513
|
+
type PartnerMessageChange = {
|
|
514
|
+
delivery_id: string;
|
|
515
|
+
external_ref: string;
|
|
516
|
+
thread_ref: string;
|
|
517
|
+
conversation_id: string;
|
|
518
|
+
message_id: string;
|
|
519
|
+
body: string;
|
|
520
|
+
sent_at: string;
|
|
521
|
+
sender: {
|
|
522
|
+
user_ref: string | null;
|
|
523
|
+
name: string;
|
|
524
|
+
};
|
|
525
|
+
delivery_status: "pending" | "delivered" | "failed";
|
|
526
|
+
};
|
|
527
|
+
type PartnerMessageChanges = {
|
|
528
|
+
items: {
|
|
529
|
+
delivery_id: string;
|
|
530
|
+
external_ref: string;
|
|
531
|
+
thread_ref: string;
|
|
532
|
+
conversation_id: string;
|
|
533
|
+
message_id: string;
|
|
534
|
+
body: string;
|
|
535
|
+
sent_at: string;
|
|
536
|
+
sender: {
|
|
537
|
+
user_ref: string | null;
|
|
538
|
+
name: string;
|
|
539
|
+
};
|
|
540
|
+
delivery_status: "pending" | "delivered" | "failed";
|
|
541
|
+
}[];
|
|
542
|
+
next_cursor: string | null;
|
|
543
|
+
};
|
|
544
|
+
type PartnerWebhookPutBody = {
|
|
545
|
+
url: string;
|
|
546
|
+
};
|
|
547
|
+
type PartnerWebhookCreated = {
|
|
548
|
+
url: string;
|
|
549
|
+
secret: string;
|
|
550
|
+
};
|
|
551
|
+
type PartnerWebhookUpdated = {
|
|
552
|
+
url: string;
|
|
553
|
+
};
|
|
554
|
+
type PartnerWebhookGet = {
|
|
555
|
+
url: string;
|
|
556
|
+
has_secret: true;
|
|
557
|
+
};
|
|
558
|
+
type PartnerWebhookRotate = {
|
|
559
|
+
secret: string;
|
|
560
|
+
};
|
|
470
561
|
type LeadCreate = {
|
|
471
562
|
status?: string | undefined;
|
|
472
563
|
assigned_to?: (string | undefined) | null;
|
|
@@ -792,10 +883,11 @@ type ConversationQuery = {
|
|
|
792
883
|
page?: number;
|
|
793
884
|
limit?: number;
|
|
794
885
|
pageSize?: number;
|
|
886
|
+
cursor?: string | undefined;
|
|
795
887
|
search?: string | undefined;
|
|
796
888
|
assignment?: (("me" | "unassigned" | "assigned" | "others") | string) | undefined;
|
|
797
889
|
status?: string | string[];
|
|
798
|
-
channel?: ("whatsapp" | "whatsapp_web" | "messenger" | "instagram" | "email" | "sms" | "webchat" | "website_form" | "voice") | undefined;
|
|
890
|
+
channel?: ("whatsapp" | "whatsapp_web" | "messenger" | "instagram" | "email" | "sms" | "webchat" | "website_form" | "partner_app" | "voice") | undefined;
|
|
799
891
|
channel_id?: string | string[];
|
|
800
892
|
team_id?: string | string[];
|
|
801
893
|
tags?: string | undefined;
|
|
@@ -810,6 +902,9 @@ type ConversationQuery = {
|
|
|
810
902
|
exclude_groups?: boolean | undefined;
|
|
811
903
|
contact_id?: string | undefined;
|
|
812
904
|
lead_stage?: string | undefined;
|
|
905
|
+
/** A contact must belong to every selected audience */
|
|
906
|
+
audience_ids?: string;
|
|
907
|
+
audience_id?: (string | string) | undefined;
|
|
813
908
|
system_audience_id?: string | undefined;
|
|
814
909
|
};
|
|
815
910
|
type ConversationUpdate = {
|
|
@@ -841,7 +936,7 @@ type Conversation = {
|
|
|
841
936
|
metadata: {
|
|
842
937
|
conversation_status: ("active" | "blocked" | "archived" | "reopened" | "on_hold") | null;
|
|
843
938
|
statuses?: ("active" | "blocked" | "archived" | "reopened" | "on_hold")[];
|
|
844
|
-
channel: "whatsapp" | "whatsapp_web" | "sms" | "email" | "messenger" | "instagram" | "website_form" | "voice";
|
|
939
|
+
channel: "whatsapp" | "whatsapp_web" | "sms" | "email" | "messenger" | "instagram" | "website_form" | "partner_app" | "voice";
|
|
845
940
|
unread_count: number;
|
|
846
941
|
total_message_count: number;
|
|
847
942
|
is_within_24h_window: boolean;
|
|
@@ -872,6 +967,8 @@ type Conversation = {
|
|
|
872
967
|
created_at: string;
|
|
873
968
|
updated_at: string;
|
|
874
969
|
};
|
|
970
|
+
title: string | null;
|
|
971
|
+
thread_ref: string | null;
|
|
875
972
|
recipient_suppressed: boolean;
|
|
876
973
|
recipient_suppression?: ({
|
|
877
974
|
id: string;
|
|
@@ -893,7 +990,7 @@ type MessageQuery = {
|
|
|
893
990
|
};
|
|
894
991
|
type MessageCreate = {
|
|
895
992
|
message?: string | undefined;
|
|
896
|
-
channel?: ("sms" | "whatsapp" | "whatsapp_web" | "email" | "messenger" | "instagram" | "telegram" | "webchat" | "website_form") | undefined;
|
|
993
|
+
channel?: ("sms" | "whatsapp" | "whatsapp_web" | "email" | "messenger" | "instagram" | "telegram" | "webchat" | "website_form" | "partner_app") | undefined;
|
|
897
994
|
channel_id?: string | undefined;
|
|
898
995
|
target_conversation_id?: string | undefined;
|
|
899
996
|
reply_to_id?: string | undefined;
|
|
@@ -941,7 +1038,7 @@ type Message = {
|
|
|
941
1038
|
};
|
|
942
1039
|
message: string;
|
|
943
1040
|
direction: "inbound" | "outbound";
|
|
944
|
-
channel: "sms" | "whatsapp" | "email" | "messenger" | "instagram" | "website_form" | "voice";
|
|
1041
|
+
channel: "sms" | "whatsapp" | "email" | "messenger" | "instagram" | "website_form" | "partner_app" | "voice";
|
|
945
1042
|
status: "sent" | "delivered" | "read" | "failed";
|
|
946
1043
|
type: "text" | "image" | "video" | "audio" | "document" | "sticker" | "contacts" | "reaction" | "activity";
|
|
947
1044
|
message_sid?: string | undefined;
|
|
@@ -1091,4 +1188,4 @@ interface ListEnvelope<T> {
|
|
|
1091
1188
|
pageSize: number;
|
|
1092
1189
|
}
|
|
1093
1190
|
|
|
1094
|
-
export type { ContactRefUpsertResult as A, LeadCapture as B, ContactQuery as C, LeadNote as D, LeadNoteCreate as E, PartnerContactEraseByIdentityBody as F, PartnerContactEraseByIdentityResult as G, PartnerContactEraseResult as H,
|
|
1191
|
+
export type { PartnerWorkspaceSecret as $, ContactRefUpsertResult as A, LeadCapture as B, ContactQuery as C, LeadNote as D, LeadNoteCreate as E, PartnerContactEraseByIdentityBody as F, PartnerContactEraseByIdentityResult as G, PartnerContactEraseResult as H, PartnerInboundMessageBody as I, PartnerInboundMessageResult as J, PartnerMessageChange as K, LeadQuery as L, MessageQuery as M, PartnerMessageChanges as N, PartnerMessageChangesQuery as O, ProductQuery as P, PartnerThreadDeleteResult as Q, PartnerWebhookCreated as R, PartnerWebhookGet as S, TaskQuery as T, PartnerWebhookPutBody as U, PartnerWebhookRotate as V, PartnerWebhookUpdated as W, PartnerWorkspaceCreated as X, PartnerWorkspaceDetail as Y, PartnerWorkspaceExisting as Z, PartnerWorkspacePatchBody as _, ContactList as a, PartnerWorkspaceStatus as a0, PartnerWorkspaceUpsertBody as a1, PartnerWorkspaceUsage as a2, PartnerWorkspaceUsageQuery as a3, TagList as a4, Contact as b, ContactCreate as c, ContactUpdate as d, ListEnvelope as e, Lead as f, LeadCreate as g, LeadUpdate as h, Task as i, LegacyTaskUpdate as j, LegacyTask as k, Product as l, ProductCreate as m, ProductUpdate as n, ConversationQuery as o, Conversation as p, ConversationUpdate as q, Message as r, MessageCreate as s, TagQuery as t, TagWithUsage as u, TagCreate as v, Tag as w, ContactChanges as x, ContactChangesQuery as y, ContactRefUpsertBody as z };
|
package/dist/embed-host.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var y=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var E=Object.prototype.hasOwnProperty;var x=(e,n)=>{for(var t in n)y(e,t,{get:n[t],enumerable:!0})},O=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of T(n))!E.call(e,r)&&r!==t&&y(e,r,{get:()=>n[r],enumerable:!(o=b(n,r))||o.enumerable});return e};var N=e=>O(y({},"__esModule",{value:!0}),e);var z={};x(z,{HOST_ACTION_SNIPPET_MAX:()=>w,buildCrmEmbedUrl:()=>q,createCrmEmbedHost:()=>D,crmSession:()=>L,encodeHostBrand:()=>I,hostContextQuery:()=>$,normalizeHostBrand:()=>H,normalizeHostContext:()=>A,parseHostActionMessage:()=>_});module.exports=N(z);var R=["create-lead","open-person"];var w=280,k=["light","dark","system"],v=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/,S=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i,X=/^(\d{1,2}(?:\.\d{1,2})?)px$/,P=/^[A-Za-z0-9 ,'"_-]+$/;var F=["accent","accentForeground","background","surface","border","foreground","mutedForeground"];function M(e){if(typeof e!="string")return;let n=e.trim();if(!(!n||n.length>160||!P.test(n))&&!((n.match(/"/g)?.length??0)%2!==0||(n.match(/'/g)?.length??0)%2!==0))return n}function H(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n={};for(let r of F){let a=e[r];if(typeof a=="string"&&S.test(a.trim())){let i=a.trim().toLowerCase();i.length===4&&(i=`#${i[1]}${i[1]}${i[2]}${i[2]}${i[3]}${i[3]}`),n[r]=i}}if(typeof e.radius=="string"){let r=X.exec(e.radius.trim());r&&Number(r[1])<=24&&(n.radius=`${Number(r[1])}px`)}let t=M(e.fontFamily);t&&(n.fontFamily=t);let o=M(e.displayFontFamily);return o&&(n.displayFontFamily=o),Object.keys(n).length>0?n:void 0}function I(e){let n=H(e);if(!n)return null;let t=new TextEncoder().encode(JSON.stringify(n)),o="";t.forEach(a=>{o+=String.fromCharCode(a)});let r=btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return r.length<=1500?r:null}function A(e){let n={};if(e?.brand===null)n.brand=null;else{let t=H(e?.brand);t&&(n.brand=t)}if(e?.theme&&k.includes(e.theme)&&(n.theme=e.theme),typeof e?.locale=="string"&&v.test(e.locale.trim())&&(n.locale=e.locale.trim()),Array.isArray(e?.capabilities)){let t=e.capabilities.filter(o=>R.includes(o));n.capabilities=[...new Set(t)].slice(0,8)}if(typeof e?.hostName=="string"){let t=e.hostName.trim();t&&t.length<=40&&!/[\u0000-\u001f\u007f]/.test(t)&&(n.hostName=t)}return n}function d(e,n,t){if(e===void 0)return t?null:void 0;if(typeof e!="string")return null;let o=e.trim();return o.length>n?null:o||(t?null:void 0)}function _(e){if(!e||typeof e!="object")return null;let n=e;if(n.type!=="crm:host-action")return null;let t=d(n.requestId,64,!0);if(!t)return null;let o=n.contact;if(!o||typeof o!="object"||Array.isArray(o))return null;let r=o,a=d(r.crmContactId,100,!0);if(!a)return null;if(n.action==="open-person")return{requestId:t,action:"open-person",contact:{crmContactId:a}};if(n.action!=="create-lead")return null;let i=d(r.name,200,!1),u=d(r.phone,40,!1),l=d(r.email,320,!1),C=d(n.conversationId,100,!0),m=d(n.channel,40,!1),p=d(n.messageSnippet,280,!1);if([i,u,l,m,p].some(s=>s===null)||!C)return null;let f={crmContactId:a};i&&(f.name=i),u&&(f.phone=u),l&&(f.email=l);let g={requestId:t,action:"create-lead",contact:f,conversationId:C};return m&&(g.channel=m),p&&(g.messageSnippet=p),g}function $(e){let n=A(e),t=[];n.theme&&t.push(`theme=${encodeURIComponent(n.theme)}`),n.locale&&t.push(`locale=${encodeURIComponent(n.locale)}`);let o=n.brand?I(n.brand):null;return o&&t.push(`brand=${o}`),t}function B(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function L(e,n){return async()=>{let t=await fetch(e,{method:"POST",...n}),o=await t.json().catch(()=>({}));if(!t.ok){let a=o?.error;throw new Error(a?`CRM session failed: ${a}`:`CRM session failed (HTTP ${t.status})`)}let r=o;if(typeof r?.accessToken!="string"||typeof r?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return r}}function q(e,n){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(n)}`}function D(e){let n=e.windowTarget??window,t=e.createChannel??(()=>new MessageChannel),o=e.devAllowAnyOrigin?"*":e.crmOrigin,r=null,a="",i=!1,u=!1,l=A(e.hostContext);function C(s){if(s){r?.postMessage({type:"crm:host-context",...l,...s});return}if(!r||Object.keys(l).length===0)return;let c={type:"crm:host-context",...l};r.postMessage(c)}async function m(){try{let s=await e.getBearer();return r?.postMessage({type:"auth-tokens",accessToken:s.accessToken,refreshToken:s.refreshToken??""}),C(),!0}catch(s){return e.onError?.(s),!1}}function p(s){let c=s.data;if(c)if(c.type==="channel-ack"){if(c.nonce!==a)return;i=!0,m()}else if(c.type==="route-change")e.onRouteChange?.(c.path);else if(c.type==="crm:host-action"){if(!i)return;let h=_(c);h&&e.onHostAction?.(h)}else c.type==="resize"?e.onResize?.(c.height):c.type==="session-expired"&&m().then(h=>{h&&r?.postMessage({type:"session-refreshed"})})}function f(){r?.close(),i=!1;let s=t();r=s.port1,a=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,r.onmessage=p,r.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:a},o,[s.port2])}function g(s){u||s.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&s.origin!==e.crmOrigin||B(s.data)&&f())}return n.addEventListener("message",g),{navigate(s){r?.postMessage({type:"navigate",path:s})},setContext(s){let c=A(s);l={...l,...c},c.brand===null&&delete l.brand,C(c.brand===null?{brand:null}:void 0)},dispose(){u=!0,n.removeEventListener("message",g),r?.close(),r=null}}}0&&(module.exports={HOST_ACTION_SNIPPET_MAX,buildCrmEmbedUrl,createCrmEmbedHost,crmSession,encodeHostBrand,hostContextQuery,normalizeHostBrand,normalizeHostContext,parseHostActionMessage});
|
|
2
2
|
//# sourceMappingURL=embed-host.cjs.map
|