@replicer/sdk 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hetyna S.r.l.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,149 @@
1
- # Temporary Holding Version
1
+ # @replicer/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Typed JavaScript/TypeScript client for the [Replicer](https://replicer.ai) API. Zero dependencies, uses the platform `fetch` (Node 18+, Bun, Deno, edge runtimes).
4
+
5
+ ```bash
6
+ npm install @replicer/sdk
7
+ ```
8
+
9
+ ## Quick start
10
+
11
+ ```ts
12
+ import { Replicer, ReplicerError } from '@replicer/sdk'
13
+
14
+ const replicer = new Replicer({ apiKey: process.env.REPLICER_API_KEY! })
15
+
16
+ try {
17
+ const { call_id, status } = await replicer.call.createPhoneCall({
18
+ agent_id: 'agent_123',
19
+ to_number: '+39111111111',
20
+ dynamic_variables: { company: 'Acme' },
21
+ })
22
+ console.log(call_id, status) // "pending"
23
+
24
+ const call = await replicer.call.get(call_id)
25
+
26
+ const { data, pagination } = await replicer.call.list({ status: 'completed', limit: 10 })
27
+ console.log(data.length, pagination.total_pages)
28
+ }
29
+ catch (err) {
30
+ if (err instanceof ReplicerError) {
31
+ console.error(err.status, err.code, err.message, err.requestId)
32
+ if (err.status === 429) console.error(`retry in ${err.retryAfter}s`)
33
+ }
34
+ else throw err
35
+ }
36
+ ```
37
+
38
+ > Keep your API key on the server. Never ship it to browsers or mobile apps.
39
+
40
+ Parameters and response fields are **snake_case**, exactly as on the wire.
41
+
42
+ ## Resources
43
+
44
+ | Resource | Methods |
45
+ |----------|---------|
46
+ | `replicer.call` | `createPhoneCall`, `cancel`, `cancelCampaignPending`, `list`, `get` |
47
+ | `replicer.campaign` | `create`, `get`, `list`, `start` |
48
+ | `replicer.phoneNumber` | `list`, `provisionInbound`, `deprovisionInbound` |
49
+ | `replicer.knowledgeBase` | `create`, `retrieve`, `list`, `delete`, `addSources`, `deleteSource`, `update`, `presignFile`, `completeFile`, `failFile`, `reindex`, `updateSource`, `updateChunk`, `getSource`, `presignFileDownload` |
50
+ | `replicer.contact` | `list`, `create` |
51
+ | `replicer.agent` | `list` |
52
+ | `replicer.calendar` | `listCalendars`, `listEvents`, `createEvent`, `updateEvent`, `cancelEvent` |
53
+ | `replicer.message` | `list`, `get`, `sendSms`, `sendWhatsapp`, `sendEmail` |
54
+ | `replicer.tts` | `create`, `list`, `get` |
55
+ | `replicer.webhookEndpoint` | `create`, `list`, `get`, `update`, `delete`, `rotateSecret`, `test`, `listDeliveries`, `listDeliveryAttempts`, `redeliver` |
56
+ | `replicer.event` | `list`, `get` |
57
+
58
+ Single-resource methods resolve to the JSON body exactly as the API returns it (for example `createPhoneCall` resolves to `{ call_id, status }`). List methods resolve to `{ data, pagination: { page, limit, total, total_pages } }` and accept `page` / `limit` (1..100, default 20) plus resource filters:
59
+
60
+ ```ts
61
+ await replicer.call.list({ status: 'completed', direction: 'outbound', date_from: '2026-01-01T00:00:00Z' })
62
+ await replicer.campaign.list({ status: 'running' })
63
+ await replicer.contact.list({ search: 'ann' })
64
+ await replicer.calendar.listEvents({ calendar_id: 'cal_1', status: 'confirmed', date_from: '2026-01-01T00:00:00Z' })
65
+ await replicer.message.list({ channel: 'sms', status: 'failed', date_from: '2026-11-01T00:00:00Z' })
66
+ await replicer.tts.list({ status: 'completed' })
67
+ ```
68
+
69
+ Deleting a knowledge base resolves to `undefined` (HTTP 204).
70
+
71
+ `message.send*` methods queue the message and resolve to `{ id, task_id, channel, status: 'queued' }`: follow it with `message.get(id)` or the `message.updated` webhook (`task_id` is a deprecated alias of `id`). `tts.create` resolves to `{ id, status: 'queued', character_count }` (poll with `tts.get`).
72
+
73
+ ## Idempotency
74
+
75
+ `call.createPhoneCall`, `campaign.create`, `message.sendSms` / `sendWhatsapp` / `sendEmail`, `tts.create` and `webhookEndpoint.create` accept an `idempotency_key`. A retry with the same key and the same body returns what the first request created and never creates, sends or bills twice; the same key with a different body rejects with `422 idempotency_key_reuse`.
76
+
77
+ ```ts
78
+ await replicer.message.sendSms({ to: '+39111111111', body: 'See you at 3pm', idempotency_key: `reminder-${appointmentId}` })
79
+ ```
80
+
81
+ ## Errors
82
+
83
+ Any non-2xx response, network failure, or non-JSON 2xx response rejects with a `ReplicerError`:
84
+
85
+ | Field | Meaning |
86
+ |-------|---------|
87
+ | `status` | HTTP status, `0` for network failures |
88
+ | `code` | `body.code` when sent (`validation_error`, `not_found`, ...), else `network_error`, `invalid_response` or `http_<status>` |
89
+ | `message` / `errorMessage` | The API's `error` string when present, else the raw body or status text |
90
+ | `body` | Parsed JSON error body, or raw text when not JSON |
91
+ | `path` | Request path |
92
+ | `requestId` | `x-request-id` response header, when present |
93
+ | `retryAfter` | Seconds from `Retry-After` (429), when provided |
94
+
95
+ ## Options
96
+
97
+ ```ts
98
+ new Replicer({
99
+ apiKey: '…', // required
100
+ baseURL: 'https://api.replicer.ai', // default
101
+ fetch: customFetch, // optional
102
+ })
103
+ ```
104
+
105
+ ## Webhooks
106
+
107
+ Manage endpoints with `replicer.webhookEndpoint` (scope `webhooks:manage`). The signing secret is returned only by `create` and `rotateSecret`:
108
+
109
+ ```ts
110
+ const endpoint = await replicer.webhookEndpoint.create({
111
+ url: 'https://example.com/replicer/webhooks',
112
+ events: ['call.ended', 'call.analyzed', 'message.updated'],
113
+ })
114
+ saveSecret(endpoint.secret) // whsec_…, shown once
115
+
116
+ const result = await replicer.webhookEndpoint.test(endpoint.id, { event_type: 'call.ended' })
117
+ console.log(result.status, result.status_code)
118
+ ```
119
+
120
+ Every delivery is signed: `Replicer-Signature: t=<unix seconds>,v1=<hex>`, where `v1` is the hex HMAC-SHA256 of `"{t}.{raw body}"` with the endpoint secret. Verify it with the server-only subpath (it uses `node:crypto`, so the main entry stays edge/browser-bundle friendly):
121
+
122
+ ```ts
123
+ import { constructEvent, WebhookSignatureError } from '@replicer/sdk/webhooks'
124
+ import type { AnyWebhookEvent } from '@replicer/sdk'
125
+
126
+ app.post('/replicer/webhooks', express.raw({ type: 'application/json' }), async (req, res) => {
127
+ let event: AnyWebhookEvent
128
+ try {
129
+ event = constructEvent({
130
+ payload: req.body, // raw body (Buffer or string), never re-serialized JSON
131
+ header: req.header('replicer-signature'),
132
+ secret: process.env.REPLICER_WEBHOOK_SECRET!, // or secrets: [newSecret, oldSecret] during a rotation
133
+ }) as AnyWebhookEvent
134
+ }
135
+ catch (err) {
136
+ if (err instanceof WebhookSignatureError) return res.status(400).end()
137
+ throw err
138
+ }
139
+ if (await alreadyProcessed(event.id)) return res.status(200).end() // at-least-once: de-duplicate on event.id
140
+ res.status(200).end()
141
+ // …handle event.type / event.data
142
+ })
143
+ ```
144
+
145
+ `verifyWebhookSignature({ payload, header, secret | secrets, toleranceSeconds = 300 })` returns a boolean instead of throwing. Signatures older (or newer) than `toleranceSeconds` are rejected.
146
+
147
+ ## Route table
148
+
149
+ `ROUTES` (`{ method, path, sdk, request, response, status, errors }[]`) is exported and drives every SDK method; it is checked against the public route table in CI.
package/dist/index.cjs ADDED
@@ -0,0 +1,345 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
24
+ ROUTES: () => ROUTES,
25
+ Replicer: () => Replicer,
26
+ ReplicerError: () => ReplicerError
27
+ });
28
+ module.exports = __toCommonJS(index_exports);
29
+
30
+ // src/errors.ts
31
+ var ReplicerError = class extends Error {
32
+ /** HTTP status code (0 when the request never produced a response). */
33
+ status;
34
+ /** `body.code` when the API sent one, else `network_error`, `invalid_response` or `http_<status>`. */
35
+ code;
36
+ /** Parsed JSON error body, or the raw response text when it was not JSON. */
37
+ body;
38
+ /** Request path (without the base URL or query string). */
39
+ path;
40
+ /** `x-request-id` response header, when present. */
41
+ requestId;
42
+ /** Seconds to wait before retrying (from `Retry-After` on a 429), when provided. */
43
+ retryAfter;
44
+ constructor(init) {
45
+ super(init.message, init.cause === void 0 ? void 0 : { cause: init.cause });
46
+ this.name = "ReplicerError";
47
+ this.status = init.status;
48
+ this.code = init.code;
49
+ this.body = init.body;
50
+ this.path = init.path ?? "";
51
+ this.requestId = init.requestId;
52
+ this.retryAfter = init.retryAfter;
53
+ }
54
+ /** Best human-readable message: the API's `error` string, else the raw text body, else `message`. */
55
+ get errorMessage() {
56
+ if (this.body && typeof this.body === "object" && typeof this.body.error === "string") {
57
+ return this.body.error;
58
+ }
59
+ if (typeof this.body === "string" && this.body !== "") return this.body;
60
+ return this.message;
61
+ }
62
+ };
63
+
64
+ // src/routes.ts
65
+ var ROUTES = [
66
+ { method: "POST", path: "/v1/create-phone-call", sdk: "call.createPhoneCall", request: "CreatePhoneCallInput", response: "EnqueueCallResponse", status: 202, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [422, "idempotency_key_reuse"], [429, "rate_limit_exceeded"], [429, "rate_limited"], [502, "bad_gateway"]] },
67
+ { method: "POST", path: "/v1/cancel-call", sdk: "call.cancel", request: "CancelCallInput", response: "OkResponse", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [429, "rate_limit_exceeded"], [502, "bad_gateway"]] },
68
+ { method: "POST", path: "/v1/cancel-campaign-pending", sdk: "call.cancelCampaignPending", request: "CancelCampaignPendingInput", response: "CancelCampaignPendingResponse", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [429, "rate_limit_exceeded"]] },
69
+ { method: "GET", path: "/v1/list-calls", sdk: "call.list", request: "ListCallsParams", response: "Page<Call>", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [429, "rate_limit_exceeded"]] },
70
+ { method: "GET", path: "/v1/get-call/:id", sdk: "call.get", request: "none", response: "Call", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [429, "rate_limit_exceeded"]] },
71
+ { method: "POST", path: "/v1/campaigns", sdk: "campaign.create", request: "CreateCampaignInput", response: "CreateCampaignResponse", status: 201, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "forbidden"], [403, "insufficient_scope"], [404, "not_found"], [409, "conflict"], [422, "idempotency_key_reuse"], [422, "validation_error"], [429, "rate_limit_exceeded"]] },
72
+ { method: "GET", path: "/v1/campaigns/:id", sdk: "campaign.get", request: "none", response: "GetCampaignResponse", status: 200, errors: [[401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [429, "rate_limit_exceeded"]] },
73
+ { method: "GET", path: "/v1/list-campaigns", sdk: "campaign.list", request: "ListCampaignsParams", response: "Page<Campaign>", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [429, "rate_limit_exceeded"]] },
74
+ { method: "POST", path: "/v1/start-campaign/:id", sdk: "campaign.start", request: "none", response: "StartCampaignResponse", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [402, "insufficient_balance"], [403, "forbidden"], [403, "insufficient_scope"], [404, "not_found"], [429, "rate_limit_exceeded"]] },
75
+ { method: "GET", path: "/v1/list-phone-numbers", sdk: "phoneNumber.list", request: "PageParams", response: "Page<PhoneNumber>", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [429, "rate_limit_exceeded"]] },
76
+ { method: "POST", path: "/v1/phone-numbers/inbound", sdk: "phoneNumber.provisionInbound", request: "ProvisionInboundInput", response: "ProvisionInboundResponse", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [403, "test_mode_unsupported"], [404, "not_found"], [409, "conflict"], [429, "rate_limit_exceeded"], [502, "bad_gateway"]] },
77
+ { method: "DELETE", path: "/v1/phone-numbers/inbound/:id", sdk: "phoneNumber.deprovisionInbound", request: "DeprovisionInboundParams", response: "OkResponse", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [403, "test_mode_unsupported"], [404, "not_found"], [429, "rate_limit_exceeded"], [502, "bad_gateway"]] },
78
+ { method: "POST", path: "/v1/create-knowledge-base", sdk: "knowledgeBase.create", request: "KnowledgeBaseCreateInput", response: "KnowledgeBaseSourcesResponse", status: 201, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [403, "quota_exceeded"], [429, "rate_limit_exceeded"], [503, "internal_error"]] },
79
+ { method: "GET", path: "/v1/get-knowledge-base/:id", sdk: "knowledgeBase.retrieve", request: "none", response: "KnowledgeBaseResponse", status: 200, errors: [[401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [429, "rate_limit_exceeded"], [503, "internal_error"]] },
80
+ { method: "GET", path: "/v1/list-knowledge-bases", sdk: "knowledgeBase.list", request: "none", response: "KnowledgeBaseListResponse", status: 200, errors: [[401, "unauthorized"], [403, "insufficient_scope"], [429, "rate_limit_exceeded"], [503, "internal_error"]] },
81
+ { method: "DELETE", path: "/v1/delete-knowledge-base/:id", sdk: "knowledgeBase.delete", request: "none", response: "none", status: 204, errors: [[401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [429, "rate_limit_exceeded"], [503, "internal_error"]] },
82
+ { method: "POST", path: "/v1/add-knowledge-base-sources/:id", sdk: "knowledgeBase.addSources", request: "KnowledgeBaseAddSourcesInput", response: "KnowledgeBaseSourcesResponse", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [403, "quota_exceeded"], [404, "not_found"], [429, "rate_limit_exceeded"], [503, "internal_error"]] },
83
+ { method: "DELETE", path: "/v1/delete-knowledge-base-source/:source_id", sdk: "knowledgeBase.deleteSource", request: "DeleteKnowledgeBaseSourceParams", response: "KnowledgeBaseResponse", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [429, "rate_limit_exceeded"], [503, "internal_error"]] },
84
+ { method: "PATCH", path: "/v1/update-knowledge-base/:id", sdk: "knowledgeBase.update", request: "KnowledgeBaseUpdateInput", response: "KnowledgeBaseResponse", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [429, "rate_limit_exceeded"], [503, "internal_error"]] },
85
+ { method: "POST", path: "/v1/presign-knowledge-base-file/:id", sdk: "knowledgeBase.presignFile", request: "PresignFileInput", response: "PresignFileResponse", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [403, "quota_exceeded"], [404, "not_found"], [429, "rate_limit_exceeded"], [503, "internal_error"]] },
86
+ { method: "POST", path: "/v1/complete-knowledge-base-file/:id/:source_id", sdk: "knowledgeBase.completeFile", request: "none", response: "KnowledgeBaseResponse", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [409, "conflict"], [429, "rate_limit_exceeded"], [503, "internal_error"]] },
87
+ { method: "POST", path: "/v1/fail-knowledge-base-file/:id/:source_id", sdk: "knowledgeBase.failFile", request: "FailFileInput", response: "KnowledgeBaseResponse", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [409, "conflict"], [429, "rate_limit_exceeded"], [503, "internal_error"]] },
88
+ { method: "PUT", path: "/v1/reindex-knowledge-base/:id", sdk: "knowledgeBase.reindex", request: "none", response: "KnowledgeBaseResponse", status: 200, errors: [[401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [409, "conflict"], [429, "rate_limit_exceeded"], [503, "internal_error"]] },
89
+ { method: "PATCH", path: "/v1/update-knowledge-base-source/:id/:source_id", sdk: "knowledgeBase.updateSource", request: "UpdateSourceInput", response: "KnowledgeBaseResponse", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [429, "rate_limit_exceeded"], [503, "internal_error"]] },
90
+ { method: "PATCH", path: "/v1/update-knowledge-base-chunk/:id/:chunk_id", sdk: "knowledgeBase.updateChunk", request: "UpdateChunkInput", response: "OkResponse", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [429, "rate_limit_exceeded"], [503, "internal_error"]] },
91
+ { method: "GET", path: "/v1/get-knowledge-base-source/:id/:source_id", sdk: "knowledgeBase.getSource", request: "none", response: "KnowledgeBaseSourceDetail", status: 200, errors: [[401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [429, "rate_limit_exceeded"], [503, "internal_error"]] },
92
+ { method: "GET", path: "/v1/presign-knowledge-base-file-download/:id/:source_id", sdk: "knowledgeBase.presignFileDownload", request: "none", response: "PresignFileDownloadResponse", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [409, "conflict"], [429, "rate_limit_exceeded"], [503, "internal_error"]] },
93
+ { method: "GET", path: "/v1/list-contacts", sdk: "contact.list", request: "ListContactsParams", response: "Page<Contact>", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [429, "rate_limit_exceeded"]] },
94
+ { method: "POST", path: "/v1/create-contact", sdk: "contact.create", request: "CreateContactInput", response: "CreateContactResponse", status: 201, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [429, "rate_limit_exceeded"]] },
95
+ { method: "GET", path: "/v1/list-agents", sdk: "agent.list", request: "PageParams", response: "Page<Agent>", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [429, "rate_limit_exceeded"]] },
96
+ { method: "GET", path: "/v1/list-calendars", sdk: "calendar.listCalendars", request: "PageParams", response: "Page<Calendar>", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [429, "rate_limit_exceeded"]] },
97
+ { method: "GET", path: "/v1/list-calendar-events", sdk: "calendar.listEvents", request: "ListCalendarEventsParams", response: "Page<CalendarEvent>", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [429, "rate_limit_exceeded"]] },
98
+ { method: "POST", path: "/v1/create-calendar-event", sdk: "calendar.createEvent", request: "CreateCalendarEventInput", response: "CreateCalendarEventResponse", status: 201, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [409, "conflict"], [429, "rate_limit_exceeded"]] },
99
+ { method: "PATCH", path: "/v1/update-calendar-event/:id", sdk: "calendar.updateEvent", request: "UpdateCalendarEventInput", response: "CalendarEvent", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [409, "conflict"], [429, "rate_limit_exceeded"]] },
100
+ { method: "POST", path: "/v1/cancel-calendar-event/:id", sdk: "calendar.cancelEvent", request: "none", response: "CalendarEvent", status: 200, errors: [[401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [409, "conflict"], [429, "rate_limit_exceeded"]] },
101
+ { method: "GET", path: "/v1/list-messages", sdk: "message.list", request: "ListMessagesParams", response: "Page<Message>", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [429, "rate_limit_exceeded"]] },
102
+ { method: "GET", path: "/v1/get-message/:id", sdk: "message.get", request: "none", response: "Message", status: 200, errors: [[401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [429, "rate_limit_exceeded"]] },
103
+ { method: "POST", path: "/v1/send-sms", sdk: "message.sendSms", request: "SendSmsInput", response: "SendMessageResponse", status: 202, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [409, "conflict"], [422, "channel_not_configured"], [422, "idempotency_key_reuse"], [422, "sender_not_supported"], [422, "validation_error"], [429, "rate_limit_exceeded"], [502, "bad_gateway"]] },
104
+ { method: "POST", path: "/v1/send-whatsapp", sdk: "message.sendWhatsapp", request: "SendWhatsappInput", response: "SendMessageResponse", status: 202, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [409, "conflict"], [422, "channel_not_configured"], [422, "idempotency_key_reuse"], [422, "media_not_supported"], [422, "validation_error"], [429, "rate_limit_exceeded"], [502, "bad_gateway"]] },
105
+ { method: "POST", path: "/v1/send-email", sdk: "message.sendEmail", request: "SendEmailInput", response: "SendMessageResponse", status: 202, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [409, "conflict"], [422, "channel_not_configured"], [422, "email_provider_not_supported"], [422, "idempotency_key_reuse"], [422, "validation_error"], [429, "rate_limit_exceeded"], [502, "bad_gateway"]] },
106
+ { method: "POST", path: "/v1/create-tts", sdk: "tts.create", request: "CreateTtsInput", response: "CreateTtsResponse", status: 201, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [409, "conflict"], [422, "idempotency_key_reuse"], [422, "validation_error"], [429, "rate_limit_exceeded"], [502, "bad_gateway"], [503, "service_unavailable"]] },
107
+ { method: "GET", path: "/v1/list-tts", sdk: "tts.list", request: "ListTtsParams", response: "Page<TtsGeneration>", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [429, "rate_limit_exceeded"]] },
108
+ { method: "GET", path: "/v1/get-tts/:id", sdk: "tts.get", request: "none", response: "TtsGeneration", status: 200, errors: [[401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [429, "rate_limit_exceeded"]] },
109
+ { method: "POST", path: "/v1/create-webhook-endpoint", sdk: "webhookEndpoint.create", request: "CreateWebhookEndpointInput", response: "WebhookEndpointWithSecret", status: 201, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [409, "conflict"], [409, "webhook_endpoint_limit"], [422, "idempotency_key_reuse"], [422, "validation_error"], [429, "rate_limit_exceeded"], [503, "service_unavailable"]] },
110
+ { method: "GET", path: "/v1/list-webhook-endpoints", sdk: "webhookEndpoint.list", request: "PageParams", response: "Page<WebhookEndpoint>", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [429, "rate_limit_exceeded"]] },
111
+ { method: "GET", path: "/v1/get-webhook-endpoint/:id", sdk: "webhookEndpoint.get", request: "none", response: "WebhookEndpoint", status: 200, errors: [[401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [429, "rate_limit_exceeded"]] },
112
+ { method: "PATCH", path: "/v1/update-webhook-endpoint/:id", sdk: "webhookEndpoint.update", request: "UpdateWebhookEndpointInput", response: "WebhookEndpoint", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [409, "webhook_endpoint_key_revoked"], [409, "webhook_endpoint_admin_disabled"], [429, "rate_limit_exceeded"]] },
113
+ { method: "DELETE", path: "/v1/delete-webhook-endpoint/:id", sdk: "webhookEndpoint.delete", request: "none", response: "OkResponse", status: 200, errors: [[401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [429, "rate_limit_exceeded"]] },
114
+ { method: "POST", path: "/v1/rotate-webhook-endpoint-secret/:id", sdk: "webhookEndpoint.rotateSecret", request: "none", response: "WebhookEndpointWithSecret", status: 200, errors: [[401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [409, "conflict"], [429, "rate_limit_exceeded"], [503, "service_unavailable"]] },
115
+ { method: "POST", path: "/v1/test-webhook-endpoint/:id", sdk: "webhookEndpoint.test", request: "TestWebhookEndpointInput", response: "TestWebhookEndpointResponse", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [409, "conflict"], [429, "rate_limit_exceeded"], [429, "rate_limited"]] },
116
+ { method: "GET", path: "/v1/list-webhook-deliveries", sdk: "webhookEndpoint.listDeliveries", request: "ListWebhookDeliveriesParams", response: "Page<WebhookDelivery>", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [429, "rate_limit_exceeded"]] },
117
+ { method: "GET", path: "/v1/list-webhook-delivery-attempts", sdk: "webhookEndpoint.listDeliveryAttempts", request: "ListWebhookDeliveryAttemptsParams", response: "Page<WebhookDeliveryAttempt>", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [429, "rate_limit_exceeded"]] },
118
+ { method: "POST", path: "/v1/redeliver-webhook-delivery/:id", sdk: "webhookEndpoint.redeliver", request: "none", response: "WebhookDelivery", status: 201, errors: [[401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [409, "conflict"], [409, "redelivery_limit"], [409, "webhook_endpoint_key_revoked"], [429, "rate_limit_exceeded"]] },
119
+ { method: "GET", path: "/v1/list-events", sdk: "event.list", request: "ListEventsParams", response: "Page<WebhookEventEnvelope>", status: 200, errors: [[400, "validation_error"], [401, "unauthorized"], [403, "insufficient_scope"], [429, "rate_limit_exceeded"]] },
120
+ { method: "GET", path: "/v1/get-event/:id", sdk: "event.get", request: "none", response: "WebhookEventEnvelope", status: 200, errors: [[401, "unauthorized"], [403, "insufficient_scope"], [404, "not_found"], [429, "rate_limit_exceeded"]] }
121
+ ];
122
+
123
+ // src/client.ts
124
+ var DEFAULT_BASE_URL = "https://api.replicer.ai";
125
+ var ROUTE_BY_SDK = new Map(ROUTES.map((r) => [r.sdk, r]));
126
+ var Replicer = class {
127
+ apiKey;
128
+ baseURL;
129
+ fetchImpl;
130
+ constructor(options) {
131
+ if (!options || typeof options.apiKey !== "string" || options.apiKey.trim() === "") {
132
+ throw new TypeError("Replicer: `apiKey` is required");
133
+ }
134
+ const impl = options.fetch ?? globalThis.fetch;
135
+ if (typeof impl !== "function") {
136
+ throw new TypeError("Replicer: no global `fetch` found; pass one via the `fetch` option");
137
+ }
138
+ this.apiKey = options.apiKey;
139
+ this.baseURL = (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
140
+ this.fetchImpl = impl.bind(globalThis);
141
+ }
142
+ call = {
143
+ createPhoneCall: (input) => this.request("call.createPhoneCall", { body: input }),
144
+ cancel: (call_id) => this.request("call.cancel", { body: { call_id } }),
145
+ cancelCampaignPending: (campaign_id) => this.request("call.cancelCampaignPending", { body: { campaign_id } }),
146
+ list: (params) => this.request("call.list", { query: params }),
147
+ get: (id) => this.request("call.get", { params: { id } })
148
+ };
149
+ campaign = {
150
+ create: (input) => this.request("campaign.create", { body: input }),
151
+ /** Includes up to 1,000 contacts (`contacts_truncated` tells whether there are more). */
152
+ get: (id) => this.request("campaign.get", { params: { id } }),
153
+ list: (params) => this.request("campaign.list", { query: params }),
154
+ /** Starts a campaign, or resumes one paused by `call.cancelCampaignPending`. */
155
+ start: (id) => this.request("campaign.start", { params: { id } })
156
+ };
157
+ phoneNumber = {
158
+ /** Your organization's phone numbers; `id` is the `from_number_id` for `call.createPhoneCall`. */
159
+ list: (params) => this.request("phoneNumber.list", { query: params }),
160
+ provisionInbound: (input) => this.request("phoneNumber.provisionInbound", { body: input }),
161
+ deprovisionInbound: (id, trunk_id, rule_id) => this.request("phoneNumber.deprovisionInbound", { params: { id }, query: { trunk_id, rule_id } })
162
+ };
163
+ knowledgeBase = {
164
+ create: (input) => this.request("knowledgeBase.create", { body: input }),
165
+ retrieve: (knowledgeBaseId) => this.request("knowledgeBase.retrieve", { params: { id: knowledgeBaseId } }),
166
+ list: () => this.request("knowledgeBase.list"),
167
+ delete: (knowledgeBaseId) => this.request("knowledgeBase.delete", { params: { id: knowledgeBaseId } }),
168
+ addSources: (knowledgeBaseId, input) => this.request("knowledgeBase.addSources", { params: { id: knowledgeBaseId }, body: input }),
169
+ deleteSource: (sourceId, knowledgeBaseId) => this.request("knowledgeBase.deleteSource", {
170
+ params: { source_id: sourceId },
171
+ query: { knowledge_base_id: knowledgeBaseId }
172
+ }),
173
+ update: (knowledgeBaseId, input) => this.request("knowledgeBase.update", { params: { id: knowledgeBaseId }, body: input }),
174
+ presignFile: (knowledgeBaseId, input) => this.request("knowledgeBase.presignFile", { params: { id: knowledgeBaseId }, body: input }),
175
+ completeFile: (knowledgeBaseId, sourceId) => this.request("knowledgeBase.completeFile", {
176
+ params: { id: knowledgeBaseId, source_id: sourceId },
177
+ body: {}
178
+ }),
179
+ failFile: (knowledgeBaseId, sourceId, input) => this.request("knowledgeBase.failFile", {
180
+ params: { id: knowledgeBaseId, source_id: sourceId },
181
+ body: input ?? {}
182
+ }),
183
+ reindex: (knowledgeBaseId) => this.request("knowledgeBase.reindex", { params: { id: knowledgeBaseId }, body: {} }),
184
+ updateSource: (knowledgeBaseId, sourceId, input) => this.request("knowledgeBase.updateSource", {
185
+ params: { id: knowledgeBaseId, source_id: sourceId },
186
+ body: input
187
+ }),
188
+ updateChunk: (knowledgeBaseId, chunkId, input) => this.request("knowledgeBase.updateChunk", {
189
+ params: { id: knowledgeBaseId, chunk_id: chunkId },
190
+ body: input
191
+ }),
192
+ getSource: (knowledgeBaseId, sourceId) => this.request("knowledgeBase.getSource", {
193
+ params: { id: knowledgeBaseId, source_id: sourceId }
194
+ }),
195
+ presignFileDownload: (knowledgeBaseId, sourceId) => this.request("knowledgeBase.presignFileDownload", {
196
+ params: { id: knowledgeBaseId, source_id: sourceId }
197
+ })
198
+ };
199
+ contact = {
200
+ list: (params) => this.request("contact.list", { query: params }),
201
+ create: (input) => this.request("contact.create", { body: input })
202
+ };
203
+ agent = {
204
+ list: (params) => this.request("agent.list", { query: params })
205
+ };
206
+ calendar = {
207
+ /** Active calendars with their active event types: the source of `calendar_id` and `event_type_id`. */
208
+ listCalendars: (params) => this.request("calendar.listCalendars", { query: params }),
209
+ listEvents: (params) => this.request("calendar.listEvents", { query: params }),
210
+ createEvent: (input) => this.request("calendar.createEvent", { body: input }),
211
+ /** Reschedules a confirmed event (`start_time`) and/or edits customer fields, notes and metadata. */
212
+ updateEvent: (id, input) => this.request("calendar.updateEvent", { params: { id }, body: input }),
213
+ /** Soft cancel: the event stays listed with status `cancelled`. Cancelling twice is a no-op. */
214
+ cancelEvent: (id) => this.request("calendar.cancelEvent", { params: { id }, body: {} })
215
+ };
216
+ message = {
217
+ list: (params) => this.request("message.list", { query: params }),
218
+ /** One message by id (the `id` of a send response), with its current delivery `status`. */
219
+ get: (id) => this.request("message.get", { params: { id } }),
220
+ sendSms: (input) => this.request("message.sendSms", { body: input }),
221
+ sendWhatsapp: (input) => this.request("message.sendWhatsapp", { body: input }),
222
+ sendEmail: (input) => this.request("message.sendEmail", { body: input })
223
+ };
224
+ tts = {
225
+ create: (input) => this.request("tts.create", { body: input }),
226
+ list: (params) => this.request("tts.list", { query: params }),
227
+ get: (id) => this.request("tts.get", { params: { id } })
228
+ };
229
+ webhookEndpoint = {
230
+ /** Resolves with the signing `secret`, shown only here and in `rotateSecret`. */
231
+ create: (input) => this.request("webhookEndpoint.create", { body: input }),
232
+ list: (params) => this.request("webhookEndpoint.list", { query: params }),
233
+ get: (id) => this.request("webhookEndpoint.get", { params: { id } }),
234
+ update: (id, input) => this.request("webhookEndpoint.update", { params: { id }, body: input }),
235
+ delete: (id) => this.request("webhookEndpoint.delete", { params: { id } }),
236
+ /** New secret now; the previous one keeps signing deliveries for 24 hours. */
237
+ rotateSecret: (id) => this.request("webhookEndpoint.rotateSecret", { params: { id }, body: {} }),
238
+ /** Sends a test event (`livemode: false`) and waits up to 12 seconds for its first attempt. */
239
+ test: (id, input) => this.request("webhookEndpoint.test", { params: { id }, body: input ?? {} }),
240
+ listDeliveries: (params) => this.request("webhookEndpoint.listDeliveries", { query: params }),
241
+ /** HTTP attempts of one delivery, oldest first. */
242
+ listDeliveryAttempts: (params) => this.request("webhookEndpoint.listDeliveryAttempts", { query: params }),
243
+ /** Sends the event of a delivery again (same event id and body) as a new delivery. Events from the last 30 days only. */
244
+ redeliver: (deliveryId) => this.request("webhookEndpoint.redeliver", { params: { id: deliveryId }, body: {} })
245
+ };
246
+ event = {
247
+ /** Events of the last 30 days as delivered (each item is the parsed envelope). */
248
+ list: (params) => this.request("event.list", { query: params }),
249
+ get: (id) => this.request("event.get", { params: { id } })
250
+ };
251
+ async request(sdk, opts = {}) {
252
+ const route = ROUTE_BY_SDK.get(sdk);
253
+ if (!route) throw new Error(`Replicer: unknown route ${sdk}`);
254
+ const params = opts.params ?? {};
255
+ const path = route.path.replace(/:([A-Za-z_]+)/g, (_m, name) => {
256
+ const value = params[name];
257
+ if (typeof value !== "string" || value === "" || value === "." || value === "..") {
258
+ throw new ReplicerError({
259
+ status: 0,
260
+ code: "validation_error",
261
+ message: `Replicer: invalid \`${name}\` path parameter`,
262
+ path: route.path
263
+ });
264
+ }
265
+ return encodeURIComponent(value);
266
+ });
267
+ const qs = buildQuery(opts.query);
268
+ const url = `${this.baseURL}${path}${qs ? `?${qs}` : ""}`;
269
+ const headers = {
270
+ authorization: `Bearer ${this.apiKey}`,
271
+ accept: "application/json"
272
+ };
273
+ let body;
274
+ if (opts.body !== void 0) {
275
+ headers["content-type"] = "application/json";
276
+ body = JSON.stringify(opts.body);
277
+ }
278
+ let res;
279
+ try {
280
+ res = await this.fetchImpl(url, { method: route.method, headers, body });
281
+ } catch (cause) {
282
+ throw new ReplicerError({
283
+ status: 0,
284
+ code: "network_error",
285
+ message: `Request to ${route.method} ${path} failed: ${cause instanceof Error ? cause.message : String(cause)}`,
286
+ path,
287
+ cause
288
+ });
289
+ }
290
+ const requestId = res.headers.get("x-request-id") ?? void 0;
291
+ const text = await res.text();
292
+ let parsed;
293
+ let isJson = false;
294
+ if (text) {
295
+ try {
296
+ parsed = JSON.parse(text);
297
+ isJson = true;
298
+ } catch {
299
+ isJson = false;
300
+ }
301
+ }
302
+ if (!res.ok) {
303
+ const errBody = isJson && parsed && typeof parsed === "object" ? parsed : void 0;
304
+ const retryAfterRaw = res.headers.get("retry-after");
305
+ const retryAfter = retryAfterRaw !== null && retryAfterRaw.trim() !== "" && Number.isFinite(Number(retryAfterRaw)) ? Number(retryAfterRaw) : void 0;
306
+ throw new ReplicerError({
307
+ status: res.status,
308
+ code: typeof errBody?.code === "string" && errBody.code ? errBody.code : `http_${res.status}`,
309
+ message: typeof errBody?.error === "string" && errBody.error ? errBody.error : text || res.statusText || `HTTP ${res.status}`,
310
+ body: isJson ? parsed : text,
311
+ path,
312
+ requestId,
313
+ retryAfter
314
+ });
315
+ }
316
+ if (res.status === 204) return void 0;
317
+ if (!isJson) {
318
+ throw new ReplicerError({
319
+ status: res.status,
320
+ code: "invalid_response",
321
+ message: `Expected a JSON response from ${route.method} ${path}`,
322
+ body: text,
323
+ path,
324
+ requestId
325
+ });
326
+ }
327
+ return parsed;
328
+ }
329
+ };
330
+ function buildQuery(query) {
331
+ if (!query) return "";
332
+ const params = new URLSearchParams();
333
+ for (const [key, value] of Object.entries(query)) {
334
+ if (value === void 0 || value === null) continue;
335
+ params.set(key, String(value));
336
+ }
337
+ return params.toString();
338
+ }
339
+ // Annotate the CommonJS export names for ESM import in node:
340
+ 0 && (module.exports = {
341
+ DEFAULT_BASE_URL,
342
+ ROUTES,
343
+ Replicer,
344
+ ReplicerError
345
+ });