@easyslip/sdk 0.0.0-stage → 1.0.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 (87) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/LICENSE +21 -0
  3. package/README.md +595 -2
  4. package/README.th.md +610 -0
  5. package/dist/cjs/client.d.ts +59 -0
  6. package/dist/cjs/client.js +150 -0
  7. package/dist/cjs/core/call.d.ts +18 -0
  8. package/dist/cjs/core/call.js +60 -0
  9. package/dist/cjs/core/error-codes.d.ts +8 -0
  10. package/dist/cjs/core/error-codes.js +87 -0
  11. package/dist/cjs/core/errors.d.ts +162 -0
  12. package/dist/cjs/core/errors.js +210 -0
  13. package/dist/cjs/core/files.d.ts +20 -0
  14. package/dist/cjs/core/files.js +131 -0
  15. package/dist/cjs/core/http.d.ts +65 -0
  16. package/dist/cjs/core/http.js +242 -0
  17. package/dist/cjs/core/meta.d.ts +33 -0
  18. package/dist/cjs/core/meta.js +52 -0
  19. package/dist/cjs/core/redact.d.ts +43 -0
  20. package/dist/cjs/core/redact.js +208 -0
  21. package/dist/cjs/core/runtime.d.ts +16 -0
  22. package/dist/cjs/core/runtime.js +86 -0
  23. package/dist/cjs/core/settings.d.ts +19 -0
  24. package/dist/cjs/core/settings.js +22 -0
  25. package/dist/cjs/core/sha256.d.ts +6 -0
  26. package/dist/cjs/core/sha256.js +101 -0
  27. package/dist/cjs/index.d.ts +13 -0
  28. package/dist/cjs/index.js +55 -0
  29. package/dist/cjs/models.d.ts +398 -0
  30. package/dist/cjs/models.js +234 -0
  31. package/dist/cjs/package.json +1 -0
  32. package/dist/cjs/resources/bank-accounts.d.ts +63 -0
  33. package/dist/cjs/resources/bank-accounts.js +126 -0
  34. package/dist/cjs/resources/banks.d.ts +10 -0
  35. package/dist/cjs/resources/banks.js +22 -0
  36. package/dist/cjs/resources/jobs.d.ts +64 -0
  37. package/dist/cjs/resources/jobs.js +177 -0
  38. package/dist/cjs/resources/v1.d.ts +88 -0
  39. package/dist/cjs/resources/v1.js +137 -0
  40. package/dist/cjs/resources/verify.d.ts +39 -0
  41. package/dist/cjs/resources/verify.js +105 -0
  42. package/dist/cjs/version.d.ts +2 -0
  43. package/dist/cjs/version.js +5 -0
  44. package/dist/cjs/webhooks.d.ts +26 -0
  45. package/dist/cjs/webhooks.js +92 -0
  46. package/dist/esm/client.d.ts +59 -0
  47. package/dist/esm/client.js +146 -0
  48. package/dist/esm/core/call.d.ts +18 -0
  49. package/dist/esm/core/call.js +52 -0
  50. package/dist/esm/core/error-codes.d.ts +8 -0
  51. package/dist/esm/core/error-codes.js +84 -0
  52. package/dist/esm/core/errors.d.ts +162 -0
  53. package/dist/esm/core/errors.js +184 -0
  54. package/dist/esm/core/files.d.ts +20 -0
  55. package/dist/esm/core/files.js +126 -0
  56. package/dist/esm/core/http.d.ts +65 -0
  57. package/dist/esm/core/http.js +235 -0
  58. package/dist/esm/core/meta.d.ts +33 -0
  59. package/dist/esm/core/meta.js +45 -0
  60. package/dist/esm/core/redact.d.ts +43 -0
  61. package/dist/esm/core/redact.js +198 -0
  62. package/dist/esm/core/runtime.d.ts +16 -0
  63. package/dist/esm/core/runtime.js +47 -0
  64. package/dist/esm/core/settings.d.ts +19 -0
  65. package/dist/esm/core/settings.js +19 -0
  66. package/dist/esm/core/sha256.d.ts +6 -0
  67. package/dist/esm/core/sha256.js +96 -0
  68. package/dist/esm/index.d.ts +13 -0
  69. package/dist/esm/index.js +7 -0
  70. package/dist/esm/models.d.ts +398 -0
  71. package/dist/esm/models.js +228 -0
  72. package/dist/esm/package.json +1 -0
  73. package/dist/esm/resources/bank-accounts.d.ts +63 -0
  74. package/dist/esm/resources/bank-accounts.js +122 -0
  75. package/dist/esm/resources/banks.d.ts +10 -0
  76. package/dist/esm/resources/banks.js +18 -0
  77. package/dist/esm/resources/jobs.d.ts +64 -0
  78. package/dist/esm/resources/jobs.js +173 -0
  79. package/dist/esm/resources/v1.d.ts +88 -0
  80. package/dist/esm/resources/v1.js +133 -0
  81. package/dist/esm/resources/verify.d.ts +39 -0
  82. package/dist/esm/resources/verify.js +100 -0
  83. package/dist/esm/version.d.ts +2 -0
  84. package/dist/esm/version.js +2 -0
  85. package/dist/esm/webhooks.d.ts +26 -0
  86. package/dist/esm/webhooks.js +86 -0
  87. package/package.json +80 -5
@@ -0,0 +1,210 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BatchSubmitError = exports.JobWaitTimeoutError = exports.WebhookSignatureError = exports.InputError = exports.RequestTimeoutError = exports.NetworkError = exports.ServiceUnavailableError = exports.ServerError = exports.RateLimitError = exports.ConflictError = exports.SlipPendingError = exports.SlipNotFoundError = exports.NotFoundError = exports.DuplicateSlipError = exports.InvalidUrlError = exports.InvalidImageError = exports.InvalidRequestError = exports.QuotaExceededError = exports.PermissionDeniedError = exports.AuthenticationError = exports.ApiError = exports.EasySlipError = void 0;
4
+ exports.apiErrorClass = apiErrorClass;
5
+ /** Base class of every error this SDK throws. */
6
+ class EasySlipError extends Error {
7
+ constructor(message, options) {
8
+ super(message, options);
9
+ this.name = new.target.name;
10
+ }
11
+ toString() {
12
+ return `${this.name}: ${this.message}`;
13
+ }
14
+ }
15
+ exports.EasySlipError = EasySlipError;
16
+ /**
17
+ * The API answered with an error status. Subclasses tell the kind of error; `code` holds the
18
+ * exact API error code (for example `SLIP_NOT_FOUND` on v2, `slip_not_found` on v1).
19
+ *
20
+ * If the server echoed your API key back, the SDK has replaced it with `[REDACTED]` in the
21
+ * message, `rawBody`, `headers` and `details`, and `Authorization` header values are always
22
+ * `[REDACTED]`. Only {@link sensitiveRawBody} returns the body as received.
23
+ */
24
+ class ApiError extends EasySlipError {
25
+ /** HTTP status code. */
26
+ status;
27
+ /** API error code, or null when the body was not JSON. */
28
+ code;
29
+ /** `x-request-id` header, else `cf-ray`, else null. */
30
+ requestId;
31
+ /** The response body, with the API key replaced by `[REDACTED]` if the server echoed it. */
32
+ rawBody;
33
+ /** Response headers with lower-case names, redacted like `rawBody`. */
34
+ headers;
35
+ /** v1 `details`, when present. */
36
+ details;
37
+ /** Seconds from the `Retry-After` header, when present. */
38
+ retryAfter;
39
+ /** Rate limit counters, when the API sent them. */
40
+ rateLimit;
41
+ #sensitiveRawBody;
42
+ constructor(init) {
43
+ super(init.message);
44
+ this.status = init.status;
45
+ this.code = init.code;
46
+ this.requestId = init.requestId;
47
+ this.rawBody = init.rawBody;
48
+ this.#sensitiveRawBody = init.sensitiveRawBody ?? init.rawBody;
49
+ this.headers = init.headers;
50
+ this.details = init.details ?? null;
51
+ this.retryAfter = init.retryAfter ?? null;
52
+ this.rateLimit = init.rateLimit ?? null;
53
+ }
54
+ /**
55
+ * The response body exactly as received, without redaction. It can contain your API key if
56
+ * the server echoed the request: treat it as a secret and never log it.
57
+ */
58
+ sensitiveRawBody() {
59
+ return this.#sensitiveRawBody;
60
+ }
61
+ toString() {
62
+ return `${this.name}: [${this.status}${this.code ? ` ${this.code}` : ''}] ${this.message}`;
63
+ }
64
+ /** The redacted fields, for `JSON.stringify(error)`. */
65
+ toJSON() {
66
+ return {
67
+ name: this.name,
68
+ message: this.message,
69
+ status: this.status,
70
+ code: this.code,
71
+ requestId: this.requestId,
72
+ details: this.details,
73
+ retryAfter: this.retryAfter,
74
+ rateLimit: this.rateLimit,
75
+ headers: this.headers,
76
+ rawBody: this.rawBody,
77
+ };
78
+ }
79
+ }
80
+ exports.ApiError = ApiError;
81
+ /** The API key is missing, malformed or unknown. */
82
+ class AuthenticationError extends ApiError {
83
+ }
84
+ exports.AuthenticationError = AuthenticationError;
85
+ /** The key is valid but the account, branch or IP may not call this endpoint. */
86
+ class PermissionDeniedError extends ApiError {
87
+ }
88
+ exports.PermissionDeniedError = PermissionDeniedError;
89
+ /** The service quota is used up. Nothing was charged. */
90
+ class QuotaExceededError extends PermissionDeniedError {
91
+ }
92
+ exports.QuotaExceededError = QuotaExceededError;
93
+ /** The API rejected the request body, query or parameters. */
94
+ class InvalidRequestError extends ApiError {
95
+ }
96
+ exports.InvalidRequestError = InvalidRequestError;
97
+ /** The image is missing, too large, not an image, or not a slip of the right kind. */
98
+ class InvalidImageError extends InvalidRequestError {
99
+ }
100
+ exports.InvalidImageError = InvalidImageError;
101
+ /** An image URL or callback URL was refused. */
102
+ class InvalidUrlError extends InvalidRequestError {
103
+ }
104
+ exports.InvalidUrlError = InvalidUrlError;
105
+ /** v1 only: the slip was verified before. `slip` holds the original slip. */
106
+ class DuplicateSlipError extends InvalidRequestError {
107
+ /** The original slip the API sent with the error. */
108
+ slip;
109
+ constructor(init) {
110
+ super(init);
111
+ this.slip = init.slip ?? null;
112
+ }
113
+ }
114
+ exports.DuplicateSlipError = DuplicateSlipError;
115
+ /** The resource does not exist or is not visible to this branch. */
116
+ class NotFoundError extends ApiError {
117
+ }
118
+ exports.NotFoundError = NotFoundError;
119
+ /** The bank or wallet could not find the slip, or the image has no QR code. */
120
+ class SlipNotFoundError extends NotFoundError {
121
+ }
122
+ exports.SlipNotFoundError = SlipNotFoundError;
123
+ /** Bangkok Bank slip from the last few minutes. Try again later. */
124
+ class SlipPendingError extends NotFoundError {
125
+ }
126
+ exports.SlipPendingError = SlipPendingError;
127
+ /** The request conflicts with existing data, such as a duplicate bank account. */
128
+ class ConflictError extends ApiError {
129
+ }
130
+ exports.ConflictError = ConflictError;
131
+ /** Too many requests. `retryAfter` says how long to wait. */
132
+ class RateLimitError extends ApiError {
133
+ }
134
+ exports.RateLimitError = RateLimitError;
135
+ /** 5xx from the API or an upstream bank service. */
136
+ class ServerError extends ApiError {
137
+ }
138
+ exports.ServerError = ServerError;
139
+ /** 503: a dependency is briefly unavailable. Usually sent with `retryAfter`. */
140
+ class ServiceUnavailableError extends ServerError {
141
+ }
142
+ exports.ServiceUnavailableError = ServiceUnavailableError;
143
+ /** No HTTP response arrived (DNS, connect, TLS, connection reset). */
144
+ class NetworkError extends EasySlipError {
145
+ }
146
+ exports.NetworkError = NetworkError;
147
+ /** The client timeout fired before a response arrived. */
148
+ class RequestTimeoutError extends NetworkError {
149
+ }
150
+ exports.RequestTimeoutError = RequestTimeoutError;
151
+ /** The SDK rejected an argument before sending anything. */
152
+ class InputError extends EasySlipError {
153
+ /** Why the argument was rejected. */
154
+ code;
155
+ constructor(code, message, options) {
156
+ super(message, options);
157
+ this.code = code;
158
+ }
159
+ toString() {
160
+ return `${this.name}: [${this.code}] ${this.message}`;
161
+ }
162
+ }
163
+ exports.InputError = InputError;
164
+ /** A webhook signature header is missing, malformed or does not match the raw body. */
165
+ class WebhookSignatureError extends EasySlipError {
166
+ }
167
+ exports.WebhookSignatureError = WebhookSignatureError;
168
+ /** `waitForJob` gave up before the job finished. */
169
+ class JobWaitTimeoutError extends EasySlipError {
170
+ /** The last job state seen. */
171
+ lastJob;
172
+ constructor(message, lastJob) {
173
+ super(message);
174
+ this.lastJob = lastJob;
175
+ }
176
+ }
177
+ exports.JobWaitTimeoutError = JobWaitTimeoutError;
178
+ /** `submitBankMany` failed part way. Batches already accepted keep running. */
179
+ class BatchSubmitError extends EasySlipError {
180
+ /** Batches the API accepted before the failure. */
181
+ submitted;
182
+ /** 0-based index of the chunk of 100 that failed. */
183
+ failedChunk;
184
+ constructor(submitted, failedChunk, cause) {
185
+ super(`batch chunk ${failedChunk} failed after ${submitted.length} accepted: ${String(cause instanceof Error ? cause.message : cause)}`, { cause });
186
+ this.submitted = submitted;
187
+ this.failedChunk = failedChunk;
188
+ }
189
+ }
190
+ exports.BatchSubmitError = BatchSubmitError;
191
+ const apiErrorClasses = {
192
+ ApiError,
193
+ AuthenticationError,
194
+ PermissionDeniedError,
195
+ QuotaExceededError,
196
+ InvalidRequestError,
197
+ InvalidImageError,
198
+ InvalidUrlError,
199
+ DuplicateSlipError,
200
+ NotFoundError,
201
+ SlipNotFoundError,
202
+ SlipPendingError,
203
+ ConflictError,
204
+ RateLimitError,
205
+ ServerError,
206
+ ServiceUnavailableError,
207
+ };
208
+ function apiErrorClass(name) {
209
+ return apiErrorClasses[name];
210
+ }
@@ -0,0 +1,20 @@
1
+ /** Largest image the API accepts, in bytes (4 MB). */
2
+ export declare const MAX_IMAGE_BYTES: number;
3
+ /**
4
+ * An image to upload: a file path (Node, Bun, Deno), a `file:` URL, bytes (`Uint8Array`,
5
+ * `Buffer`, `ArrayBuffer`), a `Blob` or `File`, a web `ReadableStream`, or any async iterable
6
+ * of byte chunks such as a Node readable stream.
7
+ */
8
+ export type FileInput = string | URL | Uint8Array | ArrayBuffer | Blob | ReadableStream<Uint8Array> | AsyncIterable<Uint8Array | string>;
9
+ export interface PreparedFile {
10
+ bytes: Uint8Array<ArrayBuffer>;
11
+ contentType: string;
12
+ filename: string;
13
+ }
14
+ /** Image type from the first bytes, or null when it is not JPEG, PNG, GIF or WebP. */
15
+ export declare function sniffImageType(bytes: Uint8Array): {
16
+ type: string;
17
+ ext: string;
18
+ } | null;
19
+ /** Reads an image input, checks its size and type, and names it `slip.<ext>`. */
20
+ export declare function prepareFile(input: FileInput, maxBytes?: number): Promise<PreparedFile>;
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_IMAGE_BYTES = void 0;
4
+ exports.sniffImageType = sniffImageType;
5
+ exports.prepareFile = prepareFile;
6
+ const errors_js_1 = require("./errors.js");
7
+ const runtime_js_1 = require("./runtime.js");
8
+ /** Largest image the API accepts, in bytes (4 MB). */
9
+ exports.MAX_IMAGE_BYTES = 4 * 1024 * 1024;
10
+ const types = [
11
+ {
12
+ type: 'image/jpeg',
13
+ ext: 'jpg',
14
+ test: (b) => b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff,
15
+ },
16
+ {
17
+ type: 'image/png',
18
+ ext: 'png',
19
+ test: (b) => b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47,
20
+ },
21
+ {
22
+ type: 'image/gif',
23
+ ext: 'gif',
24
+ test: (b) => b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x38,
25
+ },
26
+ {
27
+ type: 'image/webp',
28
+ ext: 'webp',
29
+ test: (b) => ascii(b, 0, 4) === 'RIFF' && ascii(b, 8, 12) === 'WEBP' && b.length >= 12,
30
+ },
31
+ ];
32
+ function ascii(bytes, start, end) {
33
+ return String.fromCharCode(...bytes.subarray(start, end));
34
+ }
35
+ /** Image type from the first bytes, or null when it is not JPEG, PNG, GIF or WebP. */
36
+ function sniffImageType(bytes) {
37
+ const hit = types.find((t) => t.test(bytes));
38
+ return hit ? { type: hit.type, ext: hit.ext } : null;
39
+ }
40
+ function tooLarge(size) {
41
+ return new errors_js_1.InputError('FILE_TOO_LARGE', `file is ${size} bytes; the API accepts at most ${exports.MAX_IMAGE_BYTES} bytes`);
42
+ }
43
+ async function collect(chunks, maxBytes) {
44
+ const parts = [];
45
+ let size = 0;
46
+ const encoder = new TextEncoder();
47
+ for await (const chunk of chunks) {
48
+ const part = typeof chunk === 'string' ? encoder.encode(chunk) : chunk;
49
+ size += part.byteLength;
50
+ if (size > maxBytes)
51
+ throw tooLarge(size);
52
+ parts.push(part);
53
+ }
54
+ const out = new Uint8Array(size);
55
+ let offset = 0;
56
+ for (const part of parts) {
57
+ out.set(part, offset);
58
+ offset += part.byteLength;
59
+ }
60
+ return out;
61
+ }
62
+ async function* readStream(stream) {
63
+ const reader = stream.getReader();
64
+ try {
65
+ while (true) {
66
+ const { done, value } = await reader.read();
67
+ if (done)
68
+ return;
69
+ yield value;
70
+ }
71
+ }
72
+ finally {
73
+ reader.releaseLock();
74
+ }
75
+ }
76
+ async function readPath(path, maxBytes) {
77
+ const fs = await (0, runtime_js_1.loadFs)();
78
+ if (!fs) {
79
+ throw new errors_js_1.InputError('FILE_NOT_READABLE', 'file paths need a runtime with a file system; pass bytes, a Blob or a stream');
80
+ }
81
+ let info;
82
+ try {
83
+ info = await fs.stat(path);
84
+ }
85
+ catch (cause) {
86
+ throw new errors_js_1.InputError('FILE_NOT_READABLE', `cannot read ${String(path)}`, { cause });
87
+ }
88
+ if (!info.isFile())
89
+ throw new errors_js_1.InputError('FILE_NOT_READABLE', `not a file: ${String(path)}`);
90
+ if (info.size > maxBytes)
91
+ throw tooLarge(info.size);
92
+ try {
93
+ return await fs.readFile(path);
94
+ }
95
+ catch (cause) {
96
+ throw new errors_js_1.InputError('FILE_NOT_READABLE', `cannot read ${String(path)}`, { cause });
97
+ }
98
+ }
99
+ async function readBytes(input, maxBytes) {
100
+ if (typeof input === 'string' || input instanceof URL)
101
+ return readPath(input, maxBytes);
102
+ if (input instanceof Uint8Array)
103
+ return input;
104
+ if (input instanceof ArrayBuffer)
105
+ return new Uint8Array(input);
106
+ if (typeof Blob !== 'undefined' && input instanceof Blob) {
107
+ if (input.size > maxBytes)
108
+ throw tooLarge(input.size);
109
+ return new Uint8Array(await input.arrayBuffer());
110
+ }
111
+ if (typeof ReadableStream !== 'undefined' && input instanceof ReadableStream) {
112
+ return collect(readStream(input), maxBytes);
113
+ }
114
+ if (input && typeof input[Symbol.asyncIterator] === 'function') {
115
+ return collect(input, maxBytes);
116
+ }
117
+ throw new errors_js_1.InputError('INVALID_ARGUMENT', 'file must be a path, URL, Uint8Array, ArrayBuffer, Blob or stream');
118
+ }
119
+ /** Reads an image input, checks its size and type, and names it `slip.<ext>`. */
120
+ async function prepareFile(input, maxBytes = exports.MAX_IMAGE_BYTES) {
121
+ const raw = await readBytes(input, maxBytes);
122
+ if (raw.byteLength === 0)
123
+ throw new errors_js_1.InputError('EMPTY_FILE', 'file is empty');
124
+ if (raw.byteLength > maxBytes)
125
+ throw tooLarge(raw.byteLength);
126
+ const kind = sniffImageType(raw);
127
+ if (!kind) {
128
+ throw new errors_js_1.InputError('UNSUPPORTED_FILE_TYPE', 'file is not a JPEG, PNG, GIF or WebP image');
129
+ }
130
+ return { bytes: new Uint8Array(raw), contentType: kind.type, filename: `slip.${kind.ext}` };
131
+ }
@@ -0,0 +1,65 @@
1
+ import { type ResponseMeta } from './meta.js';
2
+ import { type Redactor } from './redact.js';
3
+ /** Which API version a call goes to. */
4
+ export type ApiVersion = 'v1' | 'v2';
5
+ /**
6
+ * How a call may be retried.
7
+ * - `safe`: reads and idempotent calls. Retried on network errors, 429 and 5xx.
8
+ * - `write`: creates and changes. Retried only when the request never left, and on 429.
9
+ * - `billed`: calls that can spend quota. Same rule as `write`, so a slip is never billed twice.
10
+ */
11
+ export type RetryClass = 'safe' | 'write' | 'billed';
12
+ /** Options every call accepts. */
13
+ export interface RequestOptions {
14
+ /** Cancels the call, including any wait between retries. */
15
+ signal?: AbortSignal;
16
+ /** Per-attempt timeout in milliseconds for this call. */
17
+ timeout?: number;
18
+ /** Retries for this call. */
19
+ maxRetries?: number;
20
+ }
21
+ export interface RequestSpec extends RequestOptions {
22
+ api: ApiVersion;
23
+ method: 'GET' | 'POST' | 'PATCH' | 'DELETE';
24
+ path: string;
25
+ query?: Record<string, string | undefined>;
26
+ json?: unknown;
27
+ form?: FormData;
28
+ retry: RetryClass;
29
+ /** Which slip model a v1 `duplicate_slip` error carries. */
30
+ duplicateSlip?: 'BankSlip' | 'TrueWalletSlip';
31
+ }
32
+ export interface RawResponse {
33
+ data: unknown;
34
+ meta: ResponseMeta;
35
+ }
36
+ /** The part of `fetch` the SDK uses. */
37
+ export type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
38
+ export interface TransportConfig {
39
+ v1BaseUrl: string;
40
+ v2BaseUrl: string;
41
+ timeout: number;
42
+ maxRetries: number;
43
+ userAgent: string;
44
+ fetch: FetchLike;
45
+ sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
46
+ random: () => number;
47
+ apiKey: () => Promise<string>;
48
+ }
49
+ /** True when a fetch failure happened before the request was sent (DNS, connect, TLS). */
50
+ export declare function isConnectFailure(error: unknown): boolean;
51
+ /** Backoff before retry number `attempt` (0-based), in milliseconds. */
52
+ export declare function backoffDelay(attempt: number, random?: () => number): number;
53
+ /**
54
+ * Turns one HTTP response into `{ data, meta }`, or throws the mapped {@link ApiError}.
55
+ * `redact` removes the API key from everything taken from the response.
56
+ * Exported for the conformance tests; SDK users never need it.
57
+ */
58
+ export declare function decodeResponse(api: ApiVersion, status: number, rawHeaders: Headers | Record<string, string>, text: string, duplicateSlip?: RequestSpec['duplicateSlip'], redact?: Redactor): RawResponse;
59
+ /** Sends requests with auth, timeouts and the retry rules. Holds the API key privately. */
60
+ export declare class Transport {
61
+ #private;
62
+ constructor(config: TransportConfig);
63
+ get config(): Readonly<Omit<TransportConfig, 'apiKey'>>;
64
+ request(spec: RequestSpec): Promise<RawResponse>;
65
+ }
@@ -0,0 +1,242 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Transport = void 0;
4
+ exports.isConnectFailure = isConnectFailure;
5
+ exports.backoffDelay = backoffDelay;
6
+ exports.decodeResponse = decodeResponse;
7
+ const models_js_1 = require("../models.js");
8
+ const error_codes_js_1 = require("./error-codes.js");
9
+ const errors_js_1 = require("./errors.js");
10
+ const meta_js_1 = require("./meta.js");
11
+ const redact_js_1 = require("./redact.js");
12
+ const RETRY_STATUS = new Set([500, 502, 503, 504]);
13
+ const MAX_RETRY_AFTER_SECONDS = 60;
14
+ // Error codes that mean the request bytes never left this machine.
15
+ const CONNECT_CODES = new Set([
16
+ 'ECONNREFUSED',
17
+ 'ENOTFOUND',
18
+ 'EAI_AGAIN',
19
+ 'EAI_NONAME',
20
+ 'EAI_FAIL',
21
+ 'EHOSTUNREACH',
22
+ 'ENETUNREACH',
23
+ 'EADDRNOTAVAIL',
24
+ 'UND_ERR_CONNECT_TIMEOUT',
25
+ 'ConnectionRefused',
26
+ 'FailedToOpenSocket',
27
+ 'DNSException',
28
+ ]);
29
+ function errorCodesOf(error, depth = 0) {
30
+ if (!error || typeof error !== 'object' || depth > 3)
31
+ return [];
32
+ const e = error;
33
+ const out = typeof e.code === 'string' ? [e.code] : [];
34
+ out.push(...errorCodesOf(e.cause, depth + 1));
35
+ if (Array.isArray(e.errors))
36
+ for (const inner of e.errors)
37
+ out.push(...errorCodesOf(inner, depth + 1));
38
+ return out;
39
+ }
40
+ /** True when a fetch failure happened before the request was sent (DNS, connect, TLS). */
41
+ function isConnectFailure(error) {
42
+ return errorCodesOf(error).some((code) => CONNECT_CODES.has(code) ||
43
+ code.startsWith('ERR_TLS_') ||
44
+ code.startsWith('ERR_SSL_') ||
45
+ code.includes('CERT') ||
46
+ code.startsWith('UNABLE_TO_'));
47
+ }
48
+ /** Backoff before retry number `attempt` (0-based), in milliseconds. */
49
+ function backoffDelay(attempt, random = Math.random) {
50
+ const base = Math.min(8000, 500 * 2 ** attempt);
51
+ return base * (0.5 + random() * 0.5);
52
+ }
53
+ function parseJson(text) {
54
+ if (!text)
55
+ return undefined;
56
+ try {
57
+ return JSON.parse(text);
58
+ }
59
+ catch {
60
+ return undefined;
61
+ }
62
+ }
63
+ function isObject(value) {
64
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
65
+ }
66
+ function errorFromResponse(api, status, headers, text, parsed, duplicateSlip, redact) {
67
+ // Every field below is read from the redacted body.
68
+ const { rawBody, body } = (0, redact_js_1.redactBody)(text, parsed, redact);
69
+ let code = null;
70
+ let message = '';
71
+ let details = null;
72
+ let slipData;
73
+ if (isObject(body)) {
74
+ if (api === 'v2' && isObject(body.error)) {
75
+ if (typeof body.error.code === 'string')
76
+ code = body.error.code;
77
+ if (typeof body.error.message === 'string')
78
+ message = body.error.message;
79
+ }
80
+ else if (api === 'v1') {
81
+ if (typeof body.message === 'string') {
82
+ code = body.message;
83
+ message = body.message;
84
+ }
85
+ if (typeof body.details === 'string' || Array.isArray(body.details)) {
86
+ details = body.details;
87
+ }
88
+ slipData = body.data;
89
+ }
90
+ else if (typeof body.message === 'string') {
91
+ message = body.message;
92
+ }
93
+ }
94
+ const className = (code !== null ? error_codes_js_1.errorCodes[api][code] : undefined) ??
95
+ error_codes_js_1.statusFallback[status] ??
96
+ (status >= 500 ? 'ServerError' : 'ApiError');
97
+ const ErrorClass = (0, errors_js_1.apiErrorClass)(className);
98
+ const slip = className === 'DuplicateSlipError' && isObject(slipData)
99
+ ? (0, models_js_1.parseModel)(duplicateSlip ?? 'BankSlip', slipData)
100
+ : null;
101
+ const safeHeaders = (0, redact_js_1.redactHeaders)(headers, redact);
102
+ return new ErrorClass({
103
+ status,
104
+ code,
105
+ message: message || `HTTP ${status}`,
106
+ requestId: (0, meta_js_1.requestIdFrom)(safeHeaders),
107
+ rawBody,
108
+ sensitiveRawBody: text,
109
+ headers: safeHeaders,
110
+ details,
111
+ retryAfter: (0, meta_js_1.retryAfterFrom)(headers),
112
+ rateLimit: (0, meta_js_1.rateLimitFrom)(headers),
113
+ slip,
114
+ });
115
+ }
116
+ /**
117
+ * Turns one HTTP response into `{ data, meta }`, or throws the mapped {@link ApiError}.
118
+ * `redact` removes the API key from everything taken from the response.
119
+ * Exported for the conformance tests; SDK users never need it.
120
+ */
121
+ function decodeResponse(api, status, rawHeaders, text, duplicateSlip, redact = redact_js_1.noRedact) {
122
+ const headers = (0, meta_js_1.headersToRecord)(rawHeaders);
123
+ const body = parseJson(text);
124
+ const ok = status >= 200 && status < 300;
125
+ const successEnvelope = isObject(body) && (api === 'v2' ? body.success === true : 'data' in body);
126
+ if (!ok || !successEnvelope) {
127
+ throw errorFromResponse(api, status, headers, text, body, duplicateSlip, redact);
128
+ }
129
+ const safeHeaders = (0, redact_js_1.redactHeaders)(headers, redact);
130
+ const meta = {
131
+ status,
132
+ requestId: (0, meta_js_1.requestIdFrom)(safeHeaders),
133
+ message: api === 'v2' && typeof body.message === 'string' ? redact.text(body.message) : null,
134
+ rateLimit: (0, meta_js_1.rateLimitFrom)(headers),
135
+ headers: safeHeaders,
136
+ };
137
+ return { data: body.data, meta };
138
+ }
139
+ /** Sends requests with auth, timeouts and the retry rules. Holds the API key privately. */
140
+ class Transport {
141
+ #config;
142
+ constructor(config) {
143
+ this.#config = config;
144
+ }
145
+ get config() {
146
+ const { apiKey: _apiKey, ...rest } = this.#config;
147
+ return rest;
148
+ }
149
+ #url(spec) {
150
+ const base = (spec.api === 'v1' ? this.#config.v1BaseUrl : this.#config.v2BaseUrl).replace(/\/+$/, '');
151
+ const params = new URLSearchParams();
152
+ for (const [key, value] of Object.entries(spec.query ?? {})) {
153
+ if (value !== undefined)
154
+ params.append(key, value);
155
+ }
156
+ const qs = params.toString();
157
+ return `${base}${spec.path}${qs ? `?${qs}` : ''}`;
158
+ }
159
+ async request(spec) {
160
+ const config = this.#config;
161
+ const maxRetries = Math.max(0, spec.maxRetries ?? config.maxRetries);
162
+ const timeout = spec.timeout ?? config.timeout;
163
+ const url = this.#url(spec);
164
+ const apiKey = await config.apiKey();
165
+ const redact = (0, redact_js_1.redactor)(apiKey);
166
+ const headers = {
167
+ Authorization: `Bearer ${apiKey}`,
168
+ Accept: 'application/json',
169
+ 'User-Agent': config.userAgent,
170
+ };
171
+ let body;
172
+ if (spec.form) {
173
+ body = spec.form;
174
+ }
175
+ else if (spec.json !== undefined) {
176
+ body = JSON.stringify(spec.json);
177
+ headers['Content-Type'] = 'application/json';
178
+ }
179
+ for (let attempt = 0;; attempt++) {
180
+ spec.signal?.throwIfAborted();
181
+ const controller = new AbortController();
182
+ let timedOut = false;
183
+ const timer = setTimeout(() => {
184
+ timedOut = true;
185
+ controller.abort();
186
+ }, timeout);
187
+ const onAbort = () => controller.abort(spec.signal?.reason);
188
+ spec.signal?.addEventListener('abort', onAbort, { once: true });
189
+ let status;
190
+ let responseHeaders;
191
+ let text;
192
+ try {
193
+ const response = await config.fetch(url, {
194
+ method: spec.method,
195
+ headers,
196
+ body,
197
+ signal: controller.signal,
198
+ });
199
+ status = response.status;
200
+ responseHeaders = response.headers;
201
+ text = await response.text();
202
+ }
203
+ catch (rawCause) {
204
+ if (spec.signal?.aborted)
205
+ throw spec.signal.reason;
206
+ // Classified from the original below; only the sanitized copy is kept.
207
+ const cause = (0, redact_js_1.sanitizeCause)(rawCause, redact);
208
+ const error = timedOut
209
+ ? new errors_js_1.RequestTimeoutError(`no response within ${timeout} ms`, { cause })
210
+ : new errors_js_1.NetworkError(`request failed: ${cause.message}`, { cause });
211
+ const retryable = attempt < maxRetries &&
212
+ (spec.retry === 'safe' || (!timedOut && isConnectFailure(rawCause)));
213
+ if (!retryable)
214
+ throw error;
215
+ spec.signal?.throwIfAborted();
216
+ await config.sleep(backoffDelay(attempt, config.random), spec.signal);
217
+ continue;
218
+ }
219
+ finally {
220
+ clearTimeout(timer);
221
+ spec.signal?.removeEventListener('abort', onAbort);
222
+ }
223
+ try {
224
+ return decodeResponse(spec.api, status, responseHeaders, text, spec.duplicateSlip, redact);
225
+ }
226
+ catch (error) {
227
+ const apiError = error;
228
+ const retryable = attempt < maxRetries &&
229
+ (status === 429 || (spec.retry === 'safe' && RETRY_STATUS.has(status)));
230
+ if (!retryable)
231
+ throw apiError;
232
+ const retryAfter = apiError.retryAfter;
233
+ if (retryAfter !== null && retryAfter > MAX_RETRY_AFTER_SECONDS)
234
+ throw apiError;
235
+ const delay = retryAfter !== null ? retryAfter * 1000 : backoffDelay(attempt, config.random);
236
+ spec.signal?.throwIfAborted();
237
+ await config.sleep(delay, spec.signal);
238
+ }
239
+ }
240
+ }
241
+ }
242
+ exports.Transport = Transport;