movoice 0.0.0-stage → 0.1.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.
Files changed (125) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +302 -2
  3. package/dist/cjs/client.d.ts +49 -0
  4. package/dist/cjs/client.d.ts.map +1 -0
  5. package/dist/cjs/client.js +66 -0
  6. package/dist/cjs/client.js.map +1 -0
  7. package/dist/cjs/errors.d.ts +115 -0
  8. package/dist/cjs/errors.d.ts.map +1 -0
  9. package/dist/cjs/errors.js +252 -0
  10. package/dist/cjs/errors.js.map +1 -0
  11. package/dist/cjs/http.d.ts +99 -0
  12. package/dist/cjs/http.d.ts.map +1 -0
  13. package/dist/cjs/http.js +281 -0
  14. package/dist/cjs/http.js.map +1 -0
  15. package/dist/cjs/index.d.ts +15 -0
  16. package/dist/cjs/index.d.ts.map +1 -0
  17. package/dist/cjs/index.js +32 -0
  18. package/dist/cjs/index.js.map +1 -0
  19. package/dist/cjs/package.json +1 -0
  20. package/dist/cjs/pagination.d.ts +67 -0
  21. package/dist/cjs/pagination.d.ts.map +1 -0
  22. package/dist/cjs/pagination.js +111 -0
  23. package/dist/cjs/pagination.js.map +1 -0
  24. package/dist/cjs/resources/account.d.ts +23 -0
  25. package/dist/cjs/resources/account.d.ts.map +1 -0
  26. package/dist/cjs/resources/account.js +29 -0
  27. package/dist/cjs/resources/account.js.map +1 -0
  28. package/dist/cjs/resources/agents.d.ts +43 -0
  29. package/dist/cjs/resources/agents.d.ts.map +1 -0
  30. package/dist/cjs/resources/agents.js +73 -0
  31. package/dist/cjs/resources/agents.js.map +1 -0
  32. package/dist/cjs/resources/appointments.d.ts +42 -0
  33. package/dist/cjs/resources/appointments.d.ts.map +1 -0
  34. package/dist/cjs/resources/appointments.js +102 -0
  35. package/dist/cjs/resources/appointments.js.map +1 -0
  36. package/dist/cjs/resources/calls.d.ts +62 -0
  37. package/dist/cjs/resources/calls.d.ts.map +1 -0
  38. package/dist/cjs/resources/calls.js +91 -0
  39. package/dist/cjs/resources/calls.js.map +1 -0
  40. package/dist/cjs/resources/contacts.d.ts +26 -0
  41. package/dist/cjs/resources/contacts.d.ts.map +1 -0
  42. package/dist/cjs/resources/contacts.js +55 -0
  43. package/dist/cjs/resources/contacts.js.map +1 -0
  44. package/dist/cjs/resources/memory.d.ts +27 -0
  45. package/dist/cjs/resources/memory.d.ts.map +1 -0
  46. package/dist/cjs/resources/memory.js +38 -0
  47. package/dist/cjs/resources/memory.js.map +1 -0
  48. package/dist/cjs/resources/messages.d.ts +35 -0
  49. package/dist/cjs/resources/messages.d.ts.map +1 -0
  50. package/dist/cjs/resources/messages.js +62 -0
  51. package/dist/cjs/resources/messages.js.map +1 -0
  52. package/dist/cjs/resources/numbers.d.ts +21 -0
  53. package/dist/cjs/resources/numbers.d.ts.map +1 -0
  54. package/dist/cjs/resources/numbers.js +37 -0
  55. package/dist/cjs/resources/numbers.js.map +1 -0
  56. package/dist/cjs/types.d.ts +519 -0
  57. package/dist/cjs/types.d.ts.map +1 -0
  58. package/dist/cjs/types.js +18 -0
  59. package/dist/cjs/types.js.map +1 -0
  60. package/dist/cjs/webhooks.d.ts +92 -0
  61. package/dist/cjs/webhooks.d.ts.map +1 -0
  62. package/dist/cjs/webhooks.js +129 -0
  63. package/dist/cjs/webhooks.js.map +1 -0
  64. package/dist/esm/client.d.ts +49 -0
  65. package/dist/esm/client.d.ts.map +1 -0
  66. package/dist/esm/client.js +62 -0
  67. package/dist/esm/client.js.map +1 -0
  68. package/dist/esm/errors.d.ts +115 -0
  69. package/dist/esm/errors.d.ts.map +1 -0
  70. package/dist/esm/errors.js +237 -0
  71. package/dist/esm/errors.js.map +1 -0
  72. package/dist/esm/http.d.ts +99 -0
  73. package/dist/esm/http.d.ts.map +1 -0
  74. package/dist/esm/http.js +277 -0
  75. package/dist/esm/http.js.map +1 -0
  76. package/dist/esm/index.d.ts +15 -0
  77. package/dist/esm/index.d.ts.map +1 -0
  78. package/dist/esm/index.js +11 -0
  79. package/dist/esm/index.js.map +1 -0
  80. package/dist/esm/package.json +1 -0
  81. package/dist/esm/pagination.d.ts +67 -0
  82. package/dist/esm/pagination.d.ts.map +1 -0
  83. package/dist/esm/pagination.js +106 -0
  84. package/dist/esm/pagination.js.map +1 -0
  85. package/dist/esm/resources/account.d.ts +23 -0
  86. package/dist/esm/resources/account.d.ts.map +1 -0
  87. package/dist/esm/resources/account.js +25 -0
  88. package/dist/esm/resources/account.js.map +1 -0
  89. package/dist/esm/resources/agents.d.ts +43 -0
  90. package/dist/esm/resources/agents.d.ts.map +1 -0
  91. package/dist/esm/resources/agents.js +69 -0
  92. package/dist/esm/resources/agents.js.map +1 -0
  93. package/dist/esm/resources/appointments.d.ts +42 -0
  94. package/dist/esm/resources/appointments.d.ts.map +1 -0
  95. package/dist/esm/resources/appointments.js +97 -0
  96. package/dist/esm/resources/appointments.js.map +1 -0
  97. package/dist/esm/resources/calls.d.ts +62 -0
  98. package/dist/esm/resources/calls.d.ts.map +1 -0
  99. package/dist/esm/resources/calls.js +87 -0
  100. package/dist/esm/resources/calls.js.map +1 -0
  101. package/dist/esm/resources/contacts.d.ts +26 -0
  102. package/dist/esm/resources/contacts.d.ts.map +1 -0
  103. package/dist/esm/resources/contacts.js +51 -0
  104. package/dist/esm/resources/contacts.js.map +1 -0
  105. package/dist/esm/resources/memory.d.ts +27 -0
  106. package/dist/esm/resources/memory.d.ts.map +1 -0
  107. package/dist/esm/resources/memory.js +34 -0
  108. package/dist/esm/resources/memory.js.map +1 -0
  109. package/dist/esm/resources/messages.d.ts +35 -0
  110. package/dist/esm/resources/messages.d.ts.map +1 -0
  111. package/dist/esm/resources/messages.js +58 -0
  112. package/dist/esm/resources/messages.js.map +1 -0
  113. package/dist/esm/resources/numbers.d.ts +21 -0
  114. package/dist/esm/resources/numbers.d.ts.map +1 -0
  115. package/dist/esm/resources/numbers.js +33 -0
  116. package/dist/esm/resources/numbers.js.map +1 -0
  117. package/dist/esm/types.d.ts +519 -0
  118. package/dist/esm/types.d.ts.map +1 -0
  119. package/dist/esm/types.js +17 -0
  120. package/dist/esm/types.js.map +1 -0
  121. package/dist/esm/webhooks.d.ts +92 -0
  122. package/dist/esm/webhooks.d.ts.map +1 -0
  123. package/dist/esm/webhooks.js +124 -0
  124. package/dist/esm/webhooks.js.map +1 -0
  125. package/package.json +64 -4
@@ -0,0 +1,252 @@
1
+ "use strict";
2
+ /**
3
+ * One error type, whatever the API actually sent.
4
+ *
5
+ * The API now answers every failure in one shape:
6
+ *
7
+ * { "success": false, "error": { "code": "NOT_FOUND", "message": "..." } }
8
+ *
9
+ * It did not always. Until the envelopes were unified there were four at once: this
10
+ * one, an auth variant with no `success` field and lowercase codes, and two where
11
+ * `error` was a bare string that was sometimes a reason code and sometimes an English
12
+ * sentence. This module still reads all of them, deliberately — a proxy or an older
13
+ * deployment can still produce the old shapes, and being tolerant on the way in costs
14
+ * nothing. What it emits is always the same: one class hierarchy, with `code`
15
+ * upper-cased so `forbidden` and `FORBIDDEN` both arrive as `"FORBIDDEN"`.
16
+ *
17
+ * The raw values are kept on `rawCode` and `body` for anyone who needs to see what
18
+ * really came back.
19
+ *
20
+ * @module errors
21
+ */
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.InvalidResponseError = exports.ConnectionError = exports.ApiError = exports.RateLimitError = exports.InsufficientBalanceError = exports.ConflictError = exports.NotFoundError = exports.InvalidRequestError = exports.PermissionError = exports.AuthenticationError = exports.MovoiceError = void 0;
24
+ exports.errorFromResponse = errorFromResponse;
25
+ /**
26
+ * Base class for everything this library throws. Catch this to catch all of it.
27
+ *
28
+ * try { await mv.calls.create({ ... }); }
29
+ * catch (err) {
30
+ * if (err instanceof MovoiceError) console.error(err.code, err.message);
31
+ * }
32
+ */
33
+ class MovoiceError extends Error {
34
+ code;
35
+ status;
36
+ rawCode;
37
+ details;
38
+ body;
39
+ constructor(init) {
40
+ super(init.message, init.cause !== undefined ? { cause: init.cause } : undefined);
41
+ this.name = new.target.name;
42
+ this.code = init.code;
43
+ this.status = init.status;
44
+ this.rawCode = init.rawCode;
45
+ this.details = init.details;
46
+ this.body = init.body;
47
+ // Keeps `instanceof` working when the SDK is compiled down to ES5 by a consumer.
48
+ Object.setPrototypeOf(this, new.target.prototype);
49
+ }
50
+ /**
51
+ * True when retrying the identical request could plausibly succeed. Note this is
52
+ * about the error, not about the request: the SDK will not automatically retry a
53
+ * POST that may already have placed a call or sent a message, even when this is
54
+ * true. See `docs/retries` in the README.
55
+ */
56
+ get isRetryable() {
57
+ if (this.code === "RATE_LIMITED")
58
+ return true;
59
+ if (this.code === "CONNECTION_ERROR" || this.code === "TIMEOUT")
60
+ return true;
61
+ return this.status !== undefined && this.status >= 500;
62
+ }
63
+ }
64
+ exports.MovoiceError = MovoiceError;
65
+ /** 401 — the key is missing, malformed, expired, or unknown. */
66
+ class AuthenticationError extends MovoiceError {
67
+ }
68
+ exports.AuthenticationError = AuthenticationError;
69
+ /**
70
+ * 403 — the key is real but is not allowed to do this.
71
+ *
72
+ * Usually a missing scope: `details.required` lists the scopes the endpoint wanted.
73
+ * A legacy `mvai_` key lands here for everything except widget access.
74
+ */
75
+ class PermissionError extends MovoiceError {
76
+ /** The scopes the endpoint required, when the API said. */
77
+ get requiredScopes() {
78
+ const req = this.details?.required;
79
+ return Array.isArray(req) ? req : undefined;
80
+ }
81
+ }
82
+ exports.PermissionError = PermissionError;
83
+ /** 400 / 422 — the request was understood and rejected. */
84
+ class InvalidRequestError extends MovoiceError {
85
+ /**
86
+ * Per-field validation messages, when the failure was a schema validation.
87
+ * Shape is `{ phoneNumber: ["Invalid phone number"] }`.
88
+ */
89
+ get fieldErrors() {
90
+ const errs = this.details?.errors;
91
+ return errs && typeof errs === "object" ? errs : undefined;
92
+ }
93
+ }
94
+ exports.InvalidRequestError = InvalidRequestError;
95
+ /** 404 — no such agent or call on this account. Also returned for another account's ids. */
96
+ class NotFoundError extends MovoiceError {
97
+ }
98
+ exports.NotFoundError = NotFoundError;
99
+ /** 409 — the request conflicts with the current state. */
100
+ class ConflictError extends MovoiceError {
101
+ }
102
+ exports.ConflictError = ConflictError;
103
+ /** 402 — plan allowance and wallet are both empty. Top up, then retry. */
104
+ class InsufficientBalanceError extends MovoiceError {
105
+ }
106
+ exports.InsufficientBalanceError = InsufficientBalanceError;
107
+ /** 429 — too many requests for this key. */
108
+ class RateLimitError extends MovoiceError {
109
+ /** Seconds to wait, from the `Retry-After` header, when the API sent one. */
110
+ retryAfter;
111
+ constructor(init) {
112
+ super(init);
113
+ this.retryAfter = init.retryAfter;
114
+ }
115
+ }
116
+ exports.RateLimitError = RateLimitError;
117
+ /** 5xx — the failure was on our side, not in your request. */
118
+ class ApiError extends MovoiceError {
119
+ }
120
+ exports.ApiError = ApiError;
121
+ /**
122
+ * The request never completed: DNS, TLS, socket, timeout, or an aborted signal.
123
+ * Nothing was necessarily *not* done — a timeout can still have reached the server.
124
+ */
125
+ class ConnectionError extends MovoiceError {
126
+ }
127
+ exports.ConnectionError = ConnectionError;
128
+ /** A response came back, but it was not the JSON envelope the API is supposed to send. */
129
+ class InvalidResponseError extends MovoiceError {
130
+ }
131
+ exports.InvalidResponseError = InvalidResponseError;
132
+ // ---------------------------------------------------------------------------
133
+ // Normalisation
134
+ // ---------------------------------------------------------------------------
135
+ /**
136
+ * Pull `{ code, message, details }` out of whichever envelope this is.
137
+ *
138
+ * Both envelopes nest the useful part under `error`, so the presence or absence of
139
+ * `success` does not actually matter for reading it — which is exactly why the SDK
140
+ * can hide the difference. Anything unrecognisable falls back to the status text.
141
+ */
142
+ function readErrorBody(body) {
143
+ if (!body || typeof body !== "object")
144
+ return {};
145
+ const err = body.error;
146
+ if (!err)
147
+ return {};
148
+ // The third shape. Pre-dial refusals send `{ error: "DAILY_SPEND_CAP", message: "..." }`
149
+ // where `error` is a bare string carrying the REASON CODE and the sentence arrives
150
+ // alongside it. /v1/memory/recall uses the same key for the message itself, with no
151
+ // sibling. So a sibling `message` decides which of the two this is.
152
+ if (typeof err === "string") {
153
+ const sibling = body.message;
154
+ return typeof sibling === "string"
155
+ ? { rawCode: err, message: sibling }
156
+ : { message: err };
157
+ }
158
+ if (typeof err !== "object")
159
+ return {};
160
+ const e = err;
161
+ return {
162
+ rawCode: typeof e.code === "string" ? e.code : undefined,
163
+ message: typeof e.message === "string" ? e.message : undefined,
164
+ details: e.details && typeof e.details === "object"
165
+ ? e.details
166
+ : undefined,
167
+ };
168
+ }
169
+ /** Fallback messages, so an error is never just a bare status number. */
170
+ const STATUS_FALLBACK = {
171
+ 400: "The request was rejected.",
172
+ 401: "The API key is missing, expired, or not recognised.",
173
+ 402: "Your plan allowance and wallet balance are both exhausted.",
174
+ 403: "This API key is not allowed to perform that action.",
175
+ 404: "Not found on this account.",
176
+ 409: "That conflicts with the current state.",
177
+ 422: "The request could not be processed.",
178
+ 429: "Rate limit exceeded for this API key.",
179
+ 500: "Something failed on the Movoice side.",
180
+ 503: "The service is temporarily unavailable.",
181
+ };
182
+ /**
183
+ * Build the right error class from an HTTP response.
184
+ *
185
+ * The class is chosen by status first and code second, because status is the one
186
+ * thing both envelopes agree on.
187
+ */
188
+ function errorFromResponse(status, body, headers) {
189
+ const { rawCode, message, details } = readErrorBody(body);
190
+ const code = (rawCode ? rawCode.toUpperCase() : statusToCode(status));
191
+ const init = {
192
+ message: message ?? STATUS_FALLBACK[status] ?? `Request failed with status ${status}.`,
193
+ code,
194
+ status,
195
+ rawCode,
196
+ details,
197
+ body,
198
+ };
199
+ switch (status) {
200
+ case 401:
201
+ return new AuthenticationError(init);
202
+ case 402:
203
+ return new InsufficientBalanceError(init);
204
+ case 403:
205
+ return new PermissionError(init);
206
+ case 404:
207
+ return new NotFoundError(init);
208
+ case 409:
209
+ return new ConflictError(init);
210
+ case 400:
211
+ case 422:
212
+ return new InvalidRequestError(init);
213
+ case 429: {
214
+ const raw = headers?.get("retry-after");
215
+ const parsed = raw ? Number.parseInt(raw, 10) : Number.NaN;
216
+ return new RateLimitError({
217
+ ...init,
218
+ retryAfter: Number.isFinite(parsed) ? parsed : undefined,
219
+ });
220
+ }
221
+ default:
222
+ if (status >= 500)
223
+ return new ApiError(init);
224
+ return new MovoiceError(init);
225
+ }
226
+ }
227
+ /** Used only when the body carried no code of its own. */
228
+ function statusToCode(status) {
229
+ switch (status) {
230
+ case 400:
231
+ return "BAD_REQUEST";
232
+ case 401:
233
+ return "UNAUTHORIZED";
234
+ case 402:
235
+ return "PAYMENT_REQUIRED";
236
+ case 403:
237
+ return "FORBIDDEN";
238
+ case 404:
239
+ return "NOT_FOUND";
240
+ case 409:
241
+ return "CONFLICT";
242
+ case 422:
243
+ return "UNPROCESSABLE_ENTITY";
244
+ case 429:
245
+ return "RATE_LIMITED";
246
+ case 503:
247
+ return "SERVICE_UNAVAILABLE";
248
+ default:
249
+ return status >= 500 ? "INTERNAL_ERROR" : "BAD_REQUEST";
250
+ }
251
+ }
252
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;GAmBG;;;AAgNH,8CA0CC;AA9MD;;;;;;;GAOG;AACH,MAAa,YAAa,SAAQ,KAAK;IAC5B,IAAI,CAAmB;IACvB,MAAM,CAAU;IAChB,OAAO,CAAU;IACjB,OAAO,CAA2B;IAClC,IAAI,CAAW;IAExB,YAAY,IAAsB;QAChC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;QAClF,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC;QAC5B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;QACtB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC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G;YACN,OAAO,cAAc,CAAC;QACxB,KAAK,GAAG;YACN,OAAO,kBAAkB,CAAC;QAC5B,KAAK,GAAG;YACN,OAAO,WAAW,CAAC;QACrB,KAAK,GAAG;YACN,OAAO,WAAW,CAAC;QACrB,KAAK,GAAG;YACN,OAAO,UAAU,CAAC;QACpB,KAAK,GAAG;YACN,OAAO,sBAAsB,CAAC;QAChC,KAAK,GAAG;YACN,OAAO,cAAc,CAAC;QACxB,KAAK,GAAG;YACN,OAAO,qBAAqB,CAAC;QAC/B;YACE,OAAO,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,aAAa,CAAC;IAC5D,CAAC;AACH,CAAC"}
@@ -0,0 +1,99 @@
1
+ /**
2
+ * The transport. Everything that is true of every request lives here: the key, the
3
+ * base URL, timeouts, retries, and unwrapping the response envelope.
4
+ *
5
+ * Resource modules (agents, calls, ...) never touch fetch directly — they describe
6
+ * a request and let this decide how it is actually made.
7
+ *
8
+ * @module http
9
+ */
10
+ import type { PaginationMeta } from "./types.js";
11
+ /** The `fetch` signature the SDK needs. Lets you inject one for tests or a proxy. */
12
+ export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
13
+ export interface ClientOptions {
14
+ /**
15
+ * Your secret API key — `mv_live_...` or `mv_test_...`.
16
+ *
17
+ * Publishable keys (`mv_pk_...`) are rejected: they exist for the chat widget in a
18
+ * browser and cannot call these endpoints. Never put a secret key in client-side
19
+ * code; it can place calls and spend your balance.
20
+ */
21
+ apiKey: string;
22
+ /** Defaults to `https://app.movoice.ai`. Set this to point at a staging deploy. */
23
+ baseUrl?: string;
24
+ /** Milliseconds before a single attempt is abandoned. Default 30000. */
25
+ timeout?: number;
26
+ /**
27
+ * How many times to retry a failed attempt. Default 2.
28
+ *
29
+ * Only ever applied to requests that are safe to repeat — see `retryableMethod`.
30
+ * A call or a message is never retried by the SDK, because the first attempt may
31
+ * have succeeded and you would be billed twice.
32
+ */
33
+ maxRetries?: number;
34
+ /** Supply your own fetch. Defaults to the runtime's global. */
35
+ fetch?: FetchLike;
36
+ /** Extra headers sent with every request. Cannot override `Authorization`. */
37
+ defaultHeaders?: Record<string, string>;
38
+ }
39
+ export interface RequestOptions {
40
+ /** Abort the request from your own code. Combined with the client timeout. */
41
+ signal?: AbortSignal;
42
+ /** Override the client timeout for this one call, in milliseconds. */
43
+ timeout?: number;
44
+ /**
45
+ * Sent as the `Idempotency-Key` header, 8 to 255 characters. Use one key per action you mean to
46
+ * happen once (for example `call-${leadId}-${attempt}`). Retrying with the same key never acts
47
+ * twice: the first answer comes back instead. With a key, the SDK also retries the request
48
+ * itself after a timeout or a 5xx, because the key makes that safe.
49
+ *
50
+ * Accepted by `calls.create`, `agents.create`, `agents.update`, `appointments.create`,
51
+ * `appointments.cancel` and `appointments.reschedule`. Anywhere else it throws before sending,
52
+ * because a key the server ignores would only look like protection.
53
+ */
54
+ idempotencyKey?: string;
55
+ }
56
+ /** Internal description of one request, built by a resource module. */
57
+ export interface RequestSpec {
58
+ method: "GET" | "POST" | "PATCH" | "DELETE";
59
+ /** Path below the API root, e.g. `/agents` — `/api/v1` is added here. */
60
+ path: string;
61
+ query?: Record<string, string | number | boolean | undefined | null>;
62
+ body?: unknown;
63
+ /** True when this route honours an `Idempotency-Key` header. */
64
+ acceptsIdempotencyKey?: boolean;
65
+ }
66
+ /** A response plus the pagination block, for list endpoints. */
67
+ export interface RawPage<T> {
68
+ data: T[];
69
+ pagination?: PaginationMeta;
70
+ }
71
+ export declare class HttpClient {
72
+ readonly baseUrl: string;
73
+ private readonly apiKey;
74
+ private readonly timeout;
75
+ private readonly maxRetries;
76
+ private readonly fetchImpl;
77
+ private readonly defaultHeaders;
78
+ constructor(options: ClientOptions);
79
+ /** Make a request and return the unwrapped `data` payload. */
80
+ request<T>(spec: RequestSpec, options?: RequestOptions): Promise<T>;
81
+ /**
82
+ * Make a request and return the body EXACTLY as it arrived, without looking for an
83
+ * envelope.
84
+ *
85
+ * Only /memory/recall needs this: it is the one endpoint that answers with a bare
86
+ * object and no `data` wrapper. Errors are still turned into exceptions the normal
87
+ * way — it is only the success shape that differs.
88
+ */
89
+ requestRaw<T>(spec: RequestSpec, options?: RequestOptions): Promise<T>;
90
+ /** Make a request to a list endpoint and keep the pagination block. */
91
+ requestPage<T>(spec: RequestSpec, options?: RequestOptions): Promise<RawPage<T>>;
92
+ private send;
93
+ private attempt;
94
+ private headers;
95
+ private buildUrl;
96
+ private parseSuccess;
97
+ private shouldRetry;
98
+ }
99
+ //# sourceMappingURL=http.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../src/http.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAQH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,qFAAqF;AACrF,MAAM,MAAM,SAAS,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAEjF,MAAM,WAAW,aAAa;IAC5B;;;;;;OAMG;IACH,MAAM,EAAE,MAAM,CAAC;IACf,mFAAmF;IACnF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,wEAAwE;IACxE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;;;OAMG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,+DAA+D;IAC/D,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB,8EAA8E;IAC9E,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACzC;AAED,MAAM,WAAW,cAAc;IAC7B,8EAA8E;IAC9E,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,sEAAsE;IACtE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;;;;;;OASG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,uEAAuE;AACvE,MAAM,WAAW,WAAW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1B,OAAO,CAAC,WAAW;CASpB"}
@@ -0,0 +1,281 @@
1
+ "use strict";
2
+ /**
3
+ * The transport. Everything that is true of every request lives here: the key, the
4
+ * base URL, timeouts, retries, and unwrapping the response envelope.
5
+ *
6
+ * Resource modules (agents, calls, ...) never touch fetch directly — they describe
7
+ * a request and let this decide how it is actually made.
8
+ *
9
+ * @module http
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.HttpClient = void 0;
13
+ const errors_js_1 = require("./errors.js");
14
+ const DEFAULT_BASE_URL = "https://app.movoice.ai";
15
+ const API_ROOT = "/api/v1";
16
+ const DEFAULT_TIMEOUT_MS = 30_000;
17
+ const DEFAULT_MAX_RETRIES = 2;
18
+ const SDK_VERSION = "0.1.0";
19
+ /**
20
+ * A GET can always be repeated. A POST, PATCH or DELETE cannot be assumed to be —
21
+ * `POST /v1/calls` places a real call and `POST /v1/messages` spends real money, and
22
+ * a 500 does not tell you whether the work happened before the failure.
23
+ *
24
+ * The one exception is 429: a rate-limited request was refused before it did
25
+ * anything, so repeating it is safe whatever the method. That case is handled
26
+ * separately in `shouldRetry`.
27
+ */
28
+ function retryableMethod(method) {
29
+ return method === "GET";
30
+ }
31
+ /**
32
+ * A write that carries an Idempotency-Key the route honours can be repeated too: the server keeps
33
+ * the first answer under that key and hands it back instead of acting again.
34
+ */
35
+ function retryable(spec, options) {
36
+ return retryableMethod(spec.method) || (!!spec.acceptsIdempotencyKey && !!options.idempotencyKey);
37
+ }
38
+ class HttpClient {
39
+ baseUrl;
40
+ apiKey;
41
+ timeout;
42
+ maxRetries;
43
+ fetchImpl;
44
+ defaultHeaders;
45
+ constructor(options) {
46
+ const key = options.apiKey?.trim();
47
+ if (!key) {
48
+ throw new errors_js_1.MovoiceError({
49
+ message: "No API key. Create one at https://app.movoice.ai/developer and pass it as `new Movoice({ apiKey })`.",
50
+ code: "UNAUTHORIZED",
51
+ });
52
+ }
53
+ if (key.startsWith("mv_pk_")) {
54
+ throw new errors_js_1.MovoiceError({
55
+ message: "That is a publishable key. Publishable keys (mv_pk_) only work with the chat widget in a browser and cannot call the API. Use a secret key (mv_live_ or mv_test_) from https://app.movoice.ai/developer, and keep it on your server.",
56
+ code: "FORBIDDEN",
57
+ });
58
+ }
59
+ const fetchImpl = options.fetch ?? globalThis.fetch;
60
+ if (!fetchImpl) {
61
+ throw new errors_js_1.MovoiceError({
62
+ message: "No fetch available in this runtime. Use Node 18 or newer, or pass your own with `new Movoice({ apiKey, fetch })`.",
63
+ code: "CONNECTION_ERROR",
64
+ });
65
+ }
66
+ this.apiKey = key;
67
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
68
+ this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
69
+ this.maxRetries = Math.max(0, options.maxRetries ?? DEFAULT_MAX_RETRIES);
70
+ this.fetchImpl = fetchImpl;
71
+ this.defaultHeaders = options.defaultHeaders ?? {};
72
+ }
73
+ /** Make a request and return the unwrapped `data` payload. */
74
+ async request(spec, options = {}) {
75
+ const envelope = await this.send(spec, options);
76
+ return envelope.data;
77
+ }
78
+ /**
79
+ * Make a request and return the body EXACTLY as it arrived, without looking for an
80
+ * envelope.
81
+ *
82
+ * Only /memory/recall needs this: it is the one endpoint that answers with a bare
83
+ * object and no `data` wrapper. Errors are still turned into exceptions the normal
84
+ * way — it is only the success shape that differs.
85
+ */
86
+ async requestRaw(spec, options = {}) {
87
+ // send() always hands back an envelope shape so it has one return type; in raw mode
88
+ // the untouched body is parked on `data`. Returning the wrapper instead of the body
89
+ // is an easy mistake — it type-checks, because T is unconstrained.
90
+ const wrapped = await this.send(spec, options, { envelope: false });
91
+ return wrapped.data;
92
+ }
93
+ /** Make a request to a list endpoint and keep the pagination block. */
94
+ async requestPage(spec, options = {}) {
95
+ const envelope = await this.send(spec, options);
96
+ if (!Array.isArray(envelope.data)) {
97
+ throw new errors_js_1.InvalidResponseError({
98
+ message: `Expected a list from ${spec.path} but got ${typeof envelope.data}.`,
99
+ code: "INVALID_RESPONSE",
100
+ body: envelope,
101
+ });
102
+ }
103
+ return { data: envelope.data, pagination: envelope.meta?.pagination };
104
+ }
105
+ async send(spec, options, mode = { envelope: true }) {
106
+ checkIdempotencyKey(spec, options);
107
+ const url = this.buildUrl(spec);
108
+ let lastError;
109
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
110
+ try {
111
+ const response = await this.attempt(url, spec, options);
112
+ if (response.ok)
113
+ return await this.parseSuccess(response, spec, mode.envelope);
114
+ const body = await readJsonSafely(response);
115
+ const error = (0, errors_js_1.errorFromResponse)(response.status, body, response.headers);
116
+ if (!this.shouldRetry(error, spec, options, attempt))
117
+ throw error;
118
+ lastError = error;
119
+ }
120
+ catch (err) {
121
+ // A thrown MovoiceError is either a decided failure (rethrown above) or a
122
+ // transport failure we may retry; anything else is a genuine transport fault.
123
+ const error = err instanceof errors_js_1.MovoiceError ? err : toConnectionError(err, options.signal);
124
+ if (!this.shouldRetry(error, spec, options, attempt))
125
+ throw error;
126
+ lastError = error;
127
+ }
128
+ await sleep(backoffMs(attempt, lastError));
129
+ }
130
+ // Loop exhausted: the last attempt was retryable but we ran out of retries.
131
+ throw lastError ?? new errors_js_1.ConnectionError({ message: "Request failed.", code: "CONNECTION_ERROR" });
132
+ }
133
+ async attempt(url, spec, options) {
134
+ const timeoutMs = options.timeout ?? this.timeout;
135
+ const controller = new AbortController();
136
+ const onAbort = () => controller.abort(options.signal?.reason);
137
+ if (options.signal) {
138
+ if (options.signal.aborted)
139
+ onAbort();
140
+ else
141
+ options.signal.addEventListener("abort", onAbort, { once: true });
142
+ }
143
+ const timer = setTimeout(() => controller.abort(new TimeoutSignal()), timeoutMs);
144
+ try {
145
+ return await this.fetchImpl(url, {
146
+ method: spec.method,
147
+ headers: this.headers(spec, options),
148
+ body: spec.body === undefined ? undefined : JSON.stringify(spec.body),
149
+ signal: controller.signal,
150
+ });
151
+ }
152
+ finally {
153
+ clearTimeout(timer);
154
+ options.signal?.removeEventListener("abort", onAbort);
155
+ }
156
+ }
157
+ headers(spec, options) {
158
+ const headers = {
159
+ ...this.defaultHeaders,
160
+ Accept: "application/json",
161
+ Authorization: `Bearer ${this.apiKey}`,
162
+ "User-Agent": `movoice-node/${SDK_VERSION}`,
163
+ };
164
+ if (spec.body !== undefined)
165
+ headers["Content-Type"] = "application/json";
166
+ if (spec.acceptsIdempotencyKey && options.idempotencyKey)
167
+ headers["Idempotency-Key"] = options.idempotencyKey;
168
+ return headers;
169
+ }
170
+ buildUrl(spec) {
171
+ const url = new URL(`${this.baseUrl}${API_ROOT}${spec.path}`);
172
+ for (const [key, value] of Object.entries(spec.query ?? {})) {
173
+ if (value === undefined || value === null || value === "")
174
+ continue;
175
+ url.searchParams.set(key, String(value));
176
+ }
177
+ return url.toString();
178
+ }
179
+ async parseSuccess(response, spec, expectEnvelope) {
180
+ const body = await readJsonSafely(response);
181
+ // 204 No Content: DELETE answers this way and there is nothing to unwrap.
182
+ if (response.status === 204 || body === undefined) {
183
+ return { success: true, data: undefined };
184
+ }
185
+ if (!expectEnvelope) {
186
+ // Hand the body back untouched, wrapped only so send() has one return type.
187
+ return { success: true, data: body };
188
+ }
189
+ if (!body || typeof body !== "object" || !("data" in body)) {
190
+ throw new errors_js_1.InvalidResponseError({
191
+ message: `${spec.method} ${spec.path} returned ${response.status} but not the expected response envelope.`,
192
+ code: "INVALID_RESPONSE",
193
+ status: response.status,
194
+ body,
195
+ });
196
+ }
197
+ return body;
198
+ }
199
+ shouldRetry(error, spec, options, attempt) {
200
+ if (attempt >= this.maxRetries)
201
+ return false;
202
+ // Refused before doing any work, so repeating it cannot double-charge.
203
+ if (error.code === "RATE_LIMITED")
204
+ return true;
205
+ // A caller-supplied abort is a decision, not a fault.
206
+ if (options.signal?.aborted)
207
+ return false;
208
+ if (!retryable(spec, options))
209
+ return false;
210
+ return error.isRetryable;
211
+ }
212
+ }
213
+ exports.HttpClient = HttpClient;
214
+ /** A key on a route that ignores it, or a key the server would refuse, fails here, before anything is sent. */
215
+ function checkIdempotencyKey(spec, options) {
216
+ const key = options.idempotencyKey;
217
+ if (key === undefined)
218
+ return;
219
+ if (!spec.acceptsIdempotencyKey) {
220
+ throw new errors_js_1.MovoiceError({
221
+ message: `${spec.method} ${spec.path} does not accept an Idempotency-Key, so the key would not protect anything. Remove it.`,
222
+ code: "BAD_REQUEST",
223
+ });
224
+ }
225
+ if (typeof key !== "string" || key.length < 8 || key.length > 255) {
226
+ throw new errors_js_1.MovoiceError({
227
+ message: "An Idempotency-Key must be 8 to 255 characters.",
228
+ code: "BAD_REQUEST",
229
+ });
230
+ }
231
+ }
232
+ /** Marker used as the abort reason so a timeout is distinguishable from a user abort. */
233
+ class TimeoutSignal {
234
+ isMovoiceTimeout = true;
235
+ }
236
+ function toConnectionError(err, userSignal) {
237
+ const isAbort = err instanceof Error && err.name === "AbortError";
238
+ if (isAbort && userSignal?.aborted) {
239
+ return new errors_js_1.ConnectionError({
240
+ message: "The request was aborted.",
241
+ code: "CONNECTION_ERROR",
242
+ cause: err,
243
+ });
244
+ }
245
+ if (isAbort) {
246
+ return new errors_js_1.ConnectionError({
247
+ message: "The request timed out. It may still have been processed — check before retrying anything that spends money.",
248
+ code: "TIMEOUT",
249
+ cause: err,
250
+ });
251
+ }
252
+ return new errors_js_1.ConnectionError({
253
+ message: err instanceof Error ? `Could not reach the Movoice API: ${err.message}` : "Could not reach the Movoice API.",
254
+ code: "CONNECTION_ERROR",
255
+ cause: err,
256
+ });
257
+ }
258
+ async function readJsonSafely(response) {
259
+ const text = await response.text().catch(() => "");
260
+ if (!text)
261
+ return undefined;
262
+ try {
263
+ return JSON.parse(text);
264
+ }
265
+ catch {
266
+ // An HTML error page from a proxy, most likely. Keep it for the error body.
267
+ return { error: { message: text.slice(0, 500) } };
268
+ }
269
+ }
270
+ /** Exponential backoff with jitter, or the server's own Retry-After when it sent one. */
271
+ function backoffMs(attempt, error) {
272
+ const retryAfter = error?.retryAfter;
273
+ if (typeof retryAfter === "number" && retryAfter > 0)
274
+ return Math.min(retryAfter * 1000, 60_000);
275
+ const base = Math.min(500 * 2 ** attempt, 8_000);
276
+ return base + Math.random() * 250;
277
+ }
278
+ function sleep(ms) {
279
+ return new Promise((resolve) => setTimeout(resolve, ms));
280
+ }
281
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../../src/http.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;AAEH,2CAKqB;AA8DrB,MAAM,gBAAgB,GAAG,wBAAwB,CAAC;AAClD,MAAM,QAAQ,GAAG,SAAS,CAAC;AAC3B,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAClC,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAC9B,MAAM,WAAW,GAAG,OAAO,CAAC;AAE5B;;;;;;;;GAQG;AACH,SAAS,eAAe,CAAC,MAA6B;IACpD,OAAO,MAAM,KAAK,KAAK,CAAC;AAC1B,CAAC;AAED;;;GAGG;AACH,SAAS,SAAS,CAAC,IAAiB,EAAE,OAAuB;IAC3D,OAAO,eAAe,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,qBAAqB,IAAI,CAAC,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;AACpG,CAAC;AAeD,MAAa,UAAU;IACZ,OAAO,CAAS;IACR,MAAM,CAAS;IACf,OAAO,CAAS;IAChB,UAAU,CAAS;IACnB,SAAS,CAAY;IACrB,cAAc,CAAyB;IAExD,YAAY,OAAsB;QAChC,MAAM,GAAG,GAAG,OAAO,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC;QACnC,IAAI,CAAC,GAAG,EAAE,CAAC;YACT,MAAM,IAAI,wBAAY,CAAC;gBACrB,OAAO,EACL,sGAAsG;gBACxG,IAAI,EAAE,cAAc;aACrB,CAAC,CAAC;QACL,CAAC;QACD,IAAI,GAAG,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CA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