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