@medivy/sdk 0.0.0-stage → 0.3.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/dist/client.js ADDED
@@ -0,0 +1,266 @@
1
+ // MP-248 — the runtime client of public API v1. Hand-written and small: the
2
+ // typed surface (every operation, its params and shapes) is generated into
3
+ // ./generated/v1.ts from docs/api/public-v1.openapi.json; this file only
4
+ // knows HTTP — auth header, URL building, Idempotency-Key, retries, timeouts,
5
+ // cursors, rate-limit headers and the error shape.
6
+ //
7
+ // Server-side only (Node ≥ 20, Bun, Deno): an org API key is a password for
8
+ // the whole organization and must never reach a browser. The API sends no
9
+ // CORS headers anyway; the constructor refuses to run where `document` exists.
10
+ import { MedivyApiError, MedivyConnectionError, MedivyError } from "./errors.js";
11
+ import { OPERATIONS, createResources } from "./generated/v1.js";
12
+ import { SDK_VERSION } from "./version.js";
13
+ export const DEFAULT_BASE_URL = "https://api.medivy.id";
14
+ /** Statuses worth retrying with the same request (and the same Idempotency-Key on a write). */
15
+ const RETRY_STATUS = new Set([429, 500, 502, 503, 504]);
16
+ function envApiKey() {
17
+ try {
18
+ return globalThis.process?.env?.MEDIVY_API_KEY || undefined;
19
+ }
20
+ catch {
21
+ return undefined; // Deno without --allow-env
22
+ }
23
+ }
24
+ const num = (v) => {
25
+ if (v === null || v.trim() === "")
26
+ return null;
27
+ const n = Number(v);
28
+ return Number.isFinite(n) ? n : null;
29
+ };
30
+ function rateLimitOf(h) {
31
+ return {
32
+ limit: num(h.get("ratelimit-limit")),
33
+ remaining: num(h.get("ratelimit-remaining")),
34
+ resetSeconds: num(h.get("ratelimit-reset")),
35
+ policy: h.get("ratelimit-policy"),
36
+ };
37
+ }
38
+ /** Retry-After: delta-seconds or an HTTP date → seconds (≥ 0), else null */
39
+ function retryAfterOf(h, now = Date.now()) {
40
+ const v = h.get("retry-after");
41
+ if (v === null)
42
+ return null;
43
+ const n = num(v);
44
+ if (n !== null)
45
+ return Math.max(0, n);
46
+ const t = Date.parse(v);
47
+ return Number.isNaN(t) ? null : Math.max(0, (t - now) / 1000);
48
+ }
49
+ function serializeQuery(names, query) {
50
+ if (!query)
51
+ return "";
52
+ const params = new URLSearchParams();
53
+ for (const [k, v] of Object.entries(query)) {
54
+ if (v === undefined || v === null)
55
+ continue;
56
+ // the server answers 400 on an unknown parameter; fail before sending instead
57
+ if (!names.includes(k))
58
+ throw new MedivyError(`Unknown query parameter "${k}" (expected one of: ${names.join(", ") || "none"})`);
59
+ params.set(k, String(v)); // booleans → "true" / "false", as the API's enums
60
+ }
61
+ const s = params.toString();
62
+ return s ? `?${s}` : "";
63
+ }
64
+ function sleep(ms, signal) {
65
+ if (ms <= 0)
66
+ return Promise.resolve();
67
+ return new Promise((resolve, reject) => {
68
+ if (signal?.aborted)
69
+ return reject(signal.reason);
70
+ const t = setTimeout(() => { signal?.removeEventListener("abort", onAbort); resolve(); }, ms);
71
+ const onAbort = () => { clearTimeout(t); reject(signal.reason); };
72
+ signal?.addEventListener("abort", onAbort, { once: true });
73
+ });
74
+ }
75
+ export class MedivyClient {
76
+ // private (#) so the key never shows in console.log / JSON.stringify / error dumps
77
+ #apiKey;
78
+ #fetch;
79
+ baseUrl;
80
+ timeoutMs;
81
+ maxRetries;
82
+ retryBaseDelayMs;
83
+ retryMaxDelayMs;
84
+ #userAgent;
85
+ #onResponse;
86
+ constructor(options = {}) {
87
+ if (typeof globalThis.document !== "undefined") {
88
+ throw new MedivyError("@medivy/sdk is server-side only: an org API key must never be shipped to a browser. Call Medivy from your backend.");
89
+ }
90
+ const apiKey = options.apiKey ?? envApiKey();
91
+ if (!apiKey)
92
+ throw new MedivyError("No API key: pass { apiKey } or set MEDIVY_API_KEY");
93
+ if (/\s/.test(apiKey))
94
+ throw new MedivyError("The API key contains whitespace — pass the key itself, without `Bearer `");
95
+ this.#apiKey = apiKey;
96
+ const f = options.fetch ?? globalThis.fetch;
97
+ if (typeof f !== "function")
98
+ throw new MedivyError("No fetch implementation: use Node ≥ 20, Bun or Deno, or pass { fetch }");
99
+ this.#fetch = f;
100
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
101
+ if (!/^https?:\/\//.test(this.baseUrl))
102
+ throw new MedivyError(`baseUrl must be an http(s) URL, got "${this.baseUrl}"`);
103
+ this.timeoutMs = options.timeoutMs ?? 30_000;
104
+ this.maxRetries = Math.max(0, options.maxRetries ?? 2);
105
+ this.retryBaseDelayMs = options.retryBaseDelayMs ?? 500;
106
+ this.retryMaxDelayMs = options.retryMaxDelayMs ?? 30_000;
107
+ this.#userAgent = `medivy-sdk-js/${SDK_VERSION}${options.userAgent ? ` ${options.userAgent}` : ""}`;
108
+ this.#onResponse = options.onResponse;
109
+ // the generated resources (client.products, client.sales, …) — see the interface merge below
110
+ Object.assign(this, createResources(this));
111
+ }
112
+ /** never print the key */
113
+ toJSON() {
114
+ return { baseUrl: this.baseUrl, timeoutMs: this.timeoutMs, maxRetries: this.maxRetries };
115
+ }
116
+ /**
117
+ * The body of one operation's 2xx answer (what the resource methods return).
118
+ * `options` (with `idempotencyKey`) is required for the writes in
119
+ * `IdempotencyKeyRequiredOperationId`.
120
+ */
121
+ async call(operationId, args = {}, ...[options]) {
122
+ return (await this.#send(operationId, args, options ?? {})).data;
123
+ }
124
+ /** One operation with its response metadata (request id, rate limit, idempotency replay). */
125
+ async request(operationId, args = {}, ...[options]) {
126
+ return this.#send(operationId, args, options ?? {});
127
+ }
128
+ async #send(operationId, args, options) {
129
+ const op = OPERATIONS[operationId];
130
+ if (!op)
131
+ throw new MedivyError(`Unknown operation "${String(operationId)}"`);
132
+ // MP-264 — no natural dedupe key: a generated key would be lost with this
133
+ // process, and a retry after a crash would create a second invoice / payment
134
+ if (op.idempotencyKeyRequired && (options.idempotencyKey === undefined || options.idempotencyKey === null || options.idempotencyKey === "")) {
135
+ throw new MedivyError(`${operationId}: idempotencyKey is required — pass your own stable key for this operation (e.g. derived from your invoice / payment id), stored before the call and reused on every retry. Nothing was sent.`, { code: "idempotency_key_required" });
136
+ }
137
+ let path = op.path;
138
+ for (const p of op.pathParams) {
139
+ const v = args.path?.[p];
140
+ if (typeof v !== "string" || !v)
141
+ throw new MedivyError(`${operationId}: path parameter "${p}" is required`);
142
+ path = path.replace(`{${p}}`, encodeURIComponent(v));
143
+ }
144
+ path += serializeQuery(op.queryParams, args.query);
145
+ const headers = { accept: "application/json", "user-agent": this.#userAgent };
146
+ for (const [k, v] of Object.entries(options.headers ?? {})) {
147
+ if (k.toLowerCase() === "authorization")
148
+ throw new MedivyError("Set the API key with { apiKey }, not an Authorization header");
149
+ headers[k.toLowerCase()] = v;
150
+ }
151
+ headers.authorization = `Bearer ${this.#apiKey}`;
152
+ let body;
153
+ if (op.body !== "none") {
154
+ body = JSON.stringify(op.body === "empty" ? {} : (args.body ?? {}));
155
+ headers["content-type"] = "application/json";
156
+ }
157
+ let idempotencyKey = null;
158
+ if (op.idempotencyKey) {
159
+ idempotencyKey = options.idempotencyKey ?? crypto.randomUUID();
160
+ if (!/^[\x21-\x7e]{1,255}$/.test(idempotencyKey))
161
+ throw new MedivyError("idempotencyKey must be 1–255 visible ASCII characters");
162
+ headers["idempotency-key"] = idempotencyKey;
163
+ }
164
+ const maxRetries = Math.max(0, options.maxRetries ?? this.maxRetries);
165
+ const timeoutMs = options.timeoutMs ?? this.timeoutMs;
166
+ for (let attempt = 1;; attempt++) {
167
+ if (options.signal?.aborted)
168
+ throw options.signal.reason;
169
+ const ctl = new AbortController();
170
+ let timedOut = false;
171
+ const timer = setTimeout(() => { timedOut = true; ctl.abort(); }, timeoutMs);
172
+ const onAbort = () => ctl.abort(options.signal.reason);
173
+ options.signal?.addEventListener("abort", onAbort, { once: true });
174
+ let res;
175
+ let text;
176
+ try {
177
+ res = await this.#fetch(this.baseUrl + path, { method: op.method, headers, body, signal: ctl.signal });
178
+ text = await res.text();
179
+ }
180
+ catch (cause) {
181
+ if (options.signal?.aborted)
182
+ throw options.signal.reason;
183
+ const err = new MedivyConnectionError(timedOut ? `${operationId}: timed out after ${timeoutMs} ms` : `${operationId}: connection failed (${cause?.message ?? cause})`, { cause, timedOut, operationId, idempotencyKey });
184
+ if (attempt > maxRetries)
185
+ throw err;
186
+ await sleep(this.#backoff(attempt, null), options.signal);
187
+ continue;
188
+ }
189
+ finally {
190
+ clearTimeout(timer);
191
+ options.signal?.removeEventListener("abort", onAbort);
192
+ }
193
+ const meta = {
194
+ operationId,
195
+ method: op.method,
196
+ path,
197
+ status: res.status,
198
+ requestId: res.headers.get("x-request-id"),
199
+ rateLimit: rateLimitOf(res.headers),
200
+ idempotencyReplayed: res.headers.get("idempotency-replayed") === "true",
201
+ idempotencyKey,
202
+ deprecation: res.headers.get("deprecation"),
203
+ sunset: res.headers.get("sunset"),
204
+ attempt,
205
+ };
206
+ try {
207
+ this.#onResponse?.(meta);
208
+ }
209
+ catch { /* a logging hook never fails the call */ }
210
+ let json = undefined;
211
+ try {
212
+ json = text ? JSON.parse(text) : undefined;
213
+ }
214
+ catch { /* non-JSON (e.g. a proxy page) */ }
215
+ if (res.ok) {
216
+ if (json === undefined)
217
+ throw new MedivyError(`${operationId}: expected a JSON body, got ${res.status} ${text ? "non-JSON" : "empty"}`);
218
+ return { data: json, meta };
219
+ }
220
+ const e = json?.error;
221
+ const err = new MedivyApiError({
222
+ status: res.status,
223
+ code: typeof e?.code === "string" ? e.code : res.status === 429 ? "rate_limited" : res.status >= 500 ? "internal_error" : "unknown_error",
224
+ message: typeof e?.message === "string" ? e.message : `HTTP ${res.status}`,
225
+ details: e?.details && typeof e.details === "object" ? e.details : undefined,
226
+ retryAfterSeconds: retryAfterOf(res.headers),
227
+ meta: { ...meta, requestId: (typeof e?.requestId === "string" ? e.requestId : null) ?? meta.requestId },
228
+ });
229
+ const retryable = RETRY_STATUS.has(res.status) || (res.status === 409 && err.code === "idempotency_in_progress");
230
+ // 501 not_implemented is final; everything 4xx except 429 / in-progress is final
231
+ if (!retryable || attempt > maxRetries)
232
+ throw err;
233
+ const wait = this.#backoff(attempt, err.retryAfterSeconds);
234
+ if (wait > this.retryMaxDelayMs)
235
+ throw err;
236
+ await sleep(wait, options.signal);
237
+ }
238
+ }
239
+ /** Every row of a paged list: follows `nextCursor` with the same filters and limit. */
240
+ async *paginate(operationId, args = {}, options = {}) {
241
+ const op = OPERATIONS[operationId];
242
+ if (!op?.paginated)
243
+ throw new MedivyError(`${String(operationId)} is not a paged list`);
244
+ let cursor = (args.query?.cursor) ?? null;
245
+ const seen = new Set();
246
+ for (;;) {
247
+ const query = { ...(args.query ?? {}), ...(cursor ? { cursor } : {}) };
248
+ const page = (await this.#send(operationId, { ...args, query }, options)).data;
249
+ for (const row of page.data)
250
+ yield row;
251
+ cursor = page.nextCursor ?? null;
252
+ if (!cursor)
253
+ return;
254
+ if (seen.has(cursor))
255
+ throw new MedivyError(`${operationId}: the API returned the same cursor twice`);
256
+ seen.add(cursor);
257
+ }
258
+ }
259
+ #backoff(attempt, retryAfterSeconds) {
260
+ if (retryAfterSeconds !== null)
261
+ return retryAfterSeconds * 1000;
262
+ const exp = this.retryBaseDelayMs * 2 ** (attempt - 1);
263
+ return Math.min(this.retryMaxDelayMs, exp / 2 + Math.random() * (exp / 2));
264
+ }
265
+ }
266
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,2EAA2E;AAC3E,yEAAyE;AACzE,8EAA8E;AAC9E,mDAAmD;AACnD,EAAE;AACF,4EAA4E;AAC5E,0EAA0E;AAC1E,+EAA+E;AAC/E,OAAO,EAAE,cAAc,EAAE,qBAAqB,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAChF,OAAO,EAAE,UAAU,EAAE,eAAe,EAAoF,MAAM,mBAAmB,CAAA;AAEjJ,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AAE1C,MAAM,CAAC,MAAM,gBAAgB,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F"}
@@ -0,0 +1,173 @@
1
+ import type { RateLimitInfo, ResponseMeta } from "./types.js";
2
+ /**
3
+ * Every error code public API v1 answers today, with its HTTP status.
4
+ * Kept equal to the server's catalog (workers/medivy-public-api/src/lib/errors.ts
5
+ * `ERROR_CODES`) by a unit test; a code the SDK doesn't know yet still arrives
6
+ * as a plain string.
7
+ */
8
+ export declare const KNOWN_ERROR_CODES: {
9
+ readonly invalid_request: 400;
10
+ readonly invalid_cursor: 400;
11
+ readonly unauthorized: 401;
12
+ readonly invalid_api_key: 401;
13
+ readonly api_key_disabled: 401;
14
+ readonly api_key_expired: 401;
15
+ readonly ip_not_allowed: 403;
16
+ readonly insufficient_scope: 403;
17
+ readonly forbidden: 403;
18
+ readonly outlet_not_allowed: 403;
19
+ readonly feature_disabled: 403;
20
+ readonly subscription_read_only: 403;
21
+ readonly member_deactivated: 403;
22
+ readonly not_found: 404;
23
+ readonly method_not_allowed: 405;
24
+ readonly conflict: 409;
25
+ readonly idempotency_in_progress: 409;
26
+ readonly duplicate_external_id: 409;
27
+ readonly duplicate_sku: 409;
28
+ readonly duplicate_invoice_number: 409;
29
+ readonly already_journaled: 409;
30
+ readonly invoice_not_received: 422;
31
+ readonly consignment_invoice: 422;
32
+ readonly accounting_period_closed: 422;
33
+ readonly posting_rule_missing: 422;
34
+ readonly unknown_pipeline: 422;
35
+ readonly unknown_stage: 422;
36
+ readonly virtual_account_active: 422;
37
+ readonly invoice_not_terminated: 422;
38
+ readonly nothing_to_reverse: 409;
39
+ readonly payload_too_large: 413;
40
+ readonly idempotency_key_reused: 422;
41
+ readonly unknown_contact: 422;
42
+ readonly unknown_variant: 422;
43
+ readonly unknown_unit: 422;
44
+ readonly unknown_batch: 422;
45
+ readonly duplicate_line_variant: 422;
46
+ readonly unknown_sales_channel: 422;
47
+ readonly unknown_payment_channel: 422;
48
+ readonly unknown_payment_term: 422;
49
+ readonly price_not_set: 422;
50
+ readonly price_mismatch: 422;
51
+ readonly unit_factor_mismatch: 422;
52
+ readonly discount_exceeds_amount: 422;
53
+ readonly insufficient_stock: 422;
54
+ readonly payment_total_mismatch: 422;
55
+ readonly sale_not_refundable: 422;
56
+ readonly unknown_sale_line: 422;
57
+ readonly refund_qty_exceeds_remaining: 422;
58
+ readonly credit_note_needs_customer: 422;
59
+ readonly invoice_not_draft: 422;
60
+ readonly invoice_has_no_lines: 422;
61
+ readonly invoice_not_payable: 422;
62
+ readonly amount_exceeds_balance: 422;
63
+ readonly unprocessable: 422;
64
+ readonly idempotency_key_required: 428;
65
+ readonly rate_limited: 429;
66
+ readonly internal_error: 500;
67
+ readonly not_implemented: 501;
68
+ readonly service_unavailable: 503;
69
+ };
70
+ export type KnownErrorCode = keyof typeof KNOWN_ERROR_CODES;
71
+ /** A known code, or one added to the API after this SDK version. */
72
+ export type ErrorCode = KnownErrorCode | (string & {});
73
+ /** The documented `details` of the write errors that carry one (docs/public-api-v1.md → Write error codes). */
74
+ export interface ErrorDetailsByCode {
75
+ duplicate_external_id: {
76
+ saleId: string;
77
+ };
78
+ price_mismatch: {
79
+ line: number;
80
+ unitPrice: number;
81
+ };
82
+ price_not_set: {
83
+ line: number;
84
+ };
85
+ unit_factor_mismatch: {
86
+ line: number;
87
+ unitFactor: number | null;
88
+ };
89
+ discount_exceeds_amount: {
90
+ line?: number;
91
+ field?: string;
92
+ maxAmount: number;
93
+ };
94
+ payment_total_mismatch: {
95
+ totalAmount: number;
96
+ paidAmount: number;
97
+ cashAmount: number;
98
+ };
99
+ insufficient_stock: {
100
+ variantId: string;
101
+ requested: number;
102
+ available: number;
103
+ shortages: {
104
+ variantId: string;
105
+ requested: number;
106
+ available: number;
107
+ }[];
108
+ };
109
+ refund_qty_exceeds_remaining: {
110
+ line: number;
111
+ remainingQty: number;
112
+ };
113
+ amount_exceeds_balance: {
114
+ remainingAmount: number;
115
+ };
116
+ }
117
+ export type ErrorDetails<C extends string> = C extends keyof ErrorDetailsByCode ? ErrorDetailsByCode[C] & Record<string, unknown> : Record<string, unknown>;
118
+ /** Codes of errors the SDK raises itself, before or without an HTTP answer. */
119
+ export type ClientErrorCode =
120
+ /** a write with no natural dedupe key was called without `idempotencyKey` (MP-264) — nothing was sent */
121
+ "idempotency_key_required";
122
+ /** Base class of everything the SDK throws. */
123
+ export declare class MedivyError extends Error {
124
+ /** a stable code when there is one: the API's (MedivyApiError) or the client's own (`ClientErrorCode`) */
125
+ readonly code: string | undefined;
126
+ constructor(message: string, options?: {
127
+ cause?: unknown;
128
+ code?: ClientErrorCode;
129
+ });
130
+ }
131
+ /** The API answered with a non-2xx status. */
132
+ export declare class MedivyApiError<C extends string = ErrorCode> extends MedivyError {
133
+ readonly status: number;
134
+ /** stable machine-readable code — branch on this */
135
+ readonly code: C;
136
+ /** `requestId` of the error body (= `X-Request-Id`) */
137
+ readonly requestId: string | null;
138
+ /** machine-readable context of some write errors, e.g. `{ saleId }` on duplicate_external_id */
139
+ readonly details: ErrorDetails<C> | undefined;
140
+ /** `Retry-After` in seconds (429, 503, 409 idempotency_in_progress) */
141
+ readonly retryAfterSeconds: number | null;
142
+ readonly rateLimit: RateLimitInfo;
143
+ readonly meta: ResponseMeta;
144
+ constructor(init: {
145
+ status: number;
146
+ code: C;
147
+ message: string;
148
+ details?: Record<string, unknown>;
149
+ retryAfterSeconds: number | null;
150
+ meta: ResponseMeta;
151
+ });
152
+ }
153
+ /** The request never got an HTTP answer (DNS, TLS, connection reset, timeout). */
154
+ export declare class MedivyConnectionError extends MedivyError {
155
+ /** true when the per-attempt timeout fired */
156
+ readonly timedOut: boolean;
157
+ readonly operationId: string;
158
+ /** the Idempotency-Key that was sent (writes): retry the same operation with it */
159
+ readonly idempotencyKey: string | null;
160
+ constructor(message: string, init: {
161
+ cause?: unknown;
162
+ timedOut: boolean;
163
+ operationId: string;
164
+ idempotencyKey: string | null;
165
+ });
166
+ }
167
+ /**
168
+ * Narrows an unknown error to a v1 API error, optionally with one code:
169
+ *
170
+ * if (isApiError(e, "duplicate_external_id")) e.details?.saleId
171
+ */
172
+ export declare function isApiError<C extends ErrorCode>(e: unknown, code?: C): e is MedivyApiError<C>;
173
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAE7D;;;;;GAKG;AACH,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsEpB,CAAA;AAEV,MAAM,MAAM,cAAc,GAAG,MAAM,OAAO,iBAAiB,CAAA;AAC3D,oEAAoE;AACpE,MAAM,MAAM,SAAS,GAAG,cAAc,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAA;AAEtD,+GAA+G;AAC/G,MAAM,WAAW,kBAAkB;IACjC,qBAAqB,EAAE;QAAE,MAAM,EAAE,MAAM,CAAA;KAAE,CAAA;IACzC,cAAc,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,CAAA;IACnD,aAAa,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAA;IAC/B,oBAAoB,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAA;IACjE,uBAAuB,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,CAAA;IAC7E,sBAAsB,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,CAAA;IACvF,kBAAkB,EAAE;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAC;QAAC,S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C,iBAAiB,EAAE,MAAM,GAAG,IAAI,CAAA;IACzC,QAAQ,CAAC,SAAS,EAAE,aAAa,CAAA;IACjC,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAA;gBAEf,IAAI,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,CAAC,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAAC,iBAAiB,EAAE,MAAM,GAAG,IAAI,CAAC;QAAC,IAAI,EAAE,YAAY,CAAA;KAAE;CAWxJ;AAED,kFAAkF;AAClF,qBAAa,qBAAsB,SAAQ,WAAW;IACpD,8CAA8C;IAC9C,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAA;IAC1B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;IAC5B,mFAAmF;IACnF,QAAQ,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI,CAAA;gBAC1B,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAC;QAAC,QAAQ,EAAE,OAAO,CAAC;QAAC,WAAW,EAAE,MAAM,CAAC;QAAC,cAAc,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE;CAO9H;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,CAAC,SAAS,SAAS,EAAE,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,cAAc,CAAC,CAAC,CAAC,CAE5F"}
package/dist/errors.js ADDED
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Every error code public API v1 answers today, with its HTTP status.
3
+ * Kept equal to the server's catalog (workers/medivy-public-api/src/lib/errors.ts
4
+ * `ERROR_CODES`) by a unit test; a code the SDK doesn't know yet still arrives
5
+ * as a plain string.
6
+ */
7
+ export const KNOWN_ERROR_CODES = {
8
+ // 400
9
+ invalid_request: 400,
10
+ invalid_cursor: 400,
11
+ // 401
12
+ unauthorized: 401,
13
+ invalid_api_key: 401,
14
+ api_key_disabled: 401,
15
+ api_key_expired: 401,
16
+ // 403
17
+ ip_not_allowed: 403,
18
+ insufficient_scope: 403,
19
+ forbidden: 403,
20
+ outlet_not_allowed: 403,
21
+ feature_disabled: 403,
22
+ subscription_read_only: 403,
23
+ member_deactivated: 403,
24
+ // 404 / 405
25
+ not_found: 404,
26
+ method_not_allowed: 405,
27
+ // 409
28
+ conflict: 409,
29
+ idempotency_in_progress: 409,
30
+ duplicate_external_id: 409,
31
+ duplicate_sku: 409,
32
+ duplicate_invoice_number: 409,
33
+ already_journaled: 409,
34
+ invoice_not_received: 422,
35
+ consignment_invoice: 422,
36
+ accounting_period_closed: 422,
37
+ posting_rule_missing: 422,
38
+ unknown_pipeline: 422,
39
+ unknown_stage: 422,
40
+ virtual_account_active: 422,
41
+ invoice_not_terminated: 422,
42
+ nothing_to_reverse: 409,
43
+ // 413
44
+ payload_too_large: 413,
45
+ // 422 — idempotency and the write business rules
46
+ idempotency_key_reused: 422,
47
+ unknown_contact: 422,
48
+ unknown_variant: 422,
49
+ unknown_unit: 422,
50
+ unknown_batch: 422,
51
+ duplicate_line_variant: 422,
52
+ unknown_sales_channel: 422,
53
+ unknown_payment_channel: 422,
54
+ unknown_payment_term: 422,
55
+ price_not_set: 422,
56
+ price_mismatch: 422,
57
+ unit_factor_mismatch: 422,
58
+ discount_exceeds_amount: 422,
59
+ insufficient_stock: 422,
60
+ payment_total_mismatch: 422,
61
+ sale_not_refundable: 422,
62
+ unknown_sale_line: 422,
63
+ refund_qty_exceeds_remaining: 422,
64
+ credit_note_needs_customer: 422,
65
+ invoice_not_draft: 422,
66
+ invoice_has_no_lines: 422,
67
+ invoice_not_payable: 422,
68
+ amount_exceeds_balance: 422,
69
+ unprocessable: 422,
70
+ // 428 / 429
71
+ idempotency_key_required: 428,
72
+ rate_limited: 429,
73
+ // 5xx
74
+ internal_error: 500,
75
+ not_implemented: 501,
76
+ service_unavailable: 503,
77
+ };
78
+ /** Base class of everything the SDK throws. */
79
+ export class MedivyError extends Error {
80
+ /** a stable code when there is one: the API's (MedivyApiError) or the client's own (`ClientErrorCode`) */
81
+ code;
82
+ constructor(message, options) {
83
+ super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);
84
+ this.name = "MedivyError";
85
+ this.code = options?.code;
86
+ }
87
+ }
88
+ /** The API answered with a non-2xx status. */
89
+ export class MedivyApiError extends MedivyError {
90
+ status;
91
+ /** stable machine-readable code — branch on this */
92
+ code;
93
+ /** `requestId` of the error body (= `X-Request-Id`) */
94
+ requestId;
95
+ /** machine-readable context of some write errors, e.g. `{ saleId }` on duplicate_external_id */
96
+ details;
97
+ /** `Retry-After` in seconds (429, 503, 409 idempotency_in_progress) */
98
+ retryAfterSeconds;
99
+ rateLimit;
100
+ meta;
101
+ constructor(init) {
102
+ super(`${init.code} (${init.status}): ${init.message}${init.meta.requestId ? ` [${init.meta.requestId}]` : ""}`);
103
+ this.name = "MedivyApiError";
104
+ this.status = init.status;
105
+ this.code = init.code;
106
+ this.requestId = init.meta.requestId;
107
+ this.details = init.details;
108
+ this.retryAfterSeconds = init.retryAfterSeconds;
109
+ this.rateLimit = init.meta.rateLimit;
110
+ this.meta = init.meta;
111
+ }
112
+ }
113
+ /** The request never got an HTTP answer (DNS, TLS, connection reset, timeout). */
114
+ export class MedivyConnectionError extends MedivyError {
115
+ /** true when the per-attempt timeout fired */
116
+ timedOut;
117
+ operationId;
118
+ /** the Idempotency-Key that was sent (writes): retry the same operation with it */
119
+ idempotencyKey;
120
+ constructor(message, init) {
121
+ super(message, { cause: init.cause });
122
+ this.name = "MedivyConnectionError";
123
+ this.timedOut = init.timedOut;
124
+ this.operationId = init.operationId;
125
+ this.idempotencyKey = init.idempotencyKey;
126
+ }
127
+ }
128
+ /**
129
+ * Narrows an unknown error to a v1 API error, optionally with one code:
130
+ *
131
+ * if (isApiError(e, "duplicate_external_id")) e.details?.saleId
132
+ */
133
+ export function isApiError(e, code) {
134
+ return e instanceof MedivyApiError && (code === undefined || e.code === code);
135
+ }
136
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AASA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B,MAAM;IACN,eAAe,EAAE,GAAG;IACpB,cAAc,EAAE,GAAG;IACnB,MAAM;IACN,YAAY,EAAE,GAAG;IACjB,eAAe,EAAE,GAAG;IACpB,gBAAgB,EAAE,GAAG;IACrB,eAAe,EAAE,GAAG;IACpB,MAAM;IACN,cAAc,EAAE,GAAG;IACnB,kBAAkB,EAAE,GAAG;IACvB,SAAS,EAAE,GAAG;IACd,kBAAkB,EAAE,GAAG;IACvB,gBAAgB,EAAE,GAAG;IACrB,sBAAsB,EAAE,GAAG;IAC3B,kBAAkB,EAAE,GAAG;IACvB,YAAY;IACZ,SAAS,EAAE,GAAG;IACd,kBAAkB,EAAE,GAAG;IACvB,MAAM;IACN,QAAQ,EAAE,GAAG;IACb,uBAAuB,EAAE,GAAG;IAC5B,qBAAqB,EAAE,GAAG;IAC1B,aAAa,EAAE,GAAG;IAClB,wBAAwB,EAAE,GAAG;IAC7B,iBAAiB,EAAE,GAAG;IACtB,oBAAoB,EAAE,GAAG;IACzB,mBAAmB,EAAE,GAAG;IACxB,wBAAwB,EAAE,GAAG;IAC7B,oBAAoB,EAAE,GAAG;IACzB,gBAAgB,EAAE,GAAG;IACrB,aAAa,EAAE,GAAG;IAClB,sBAAsB,EAAE,GAAG;IAC3B,sBAAsB,EAAE,GAAG;IAC3B,kBAAkB,EAAE,GAAG;IACvB,MAAM;IACN,iBAAiB,EAAE,GAAG;IACtB,iDAAiD;IACjD,sBAAsB,EAAE,GAAG;IAC3B,eAAe,EAAE,GAAG;IACpB,eAAe,EAAE,GAAG;IACpB,YAAY,EAAE,GAAG;IACjB,aAAa,EAAE,GAAG;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