@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/index.js
CHANGED
|
@@ -1,7 +1,1997 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
1
|
+
// src/models.ts
|
|
2
|
+
var MatchedAccountType = {
|
|
3
|
+
Personal: "PERSONAL",
|
|
4
|
+
Natural: "NATURAL",
|
|
5
|
+
Juristic: "JURISTIC"
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
class BankList {
|
|
9
|
+
items;
|
|
10
|
+
constructor(items) {
|
|
11
|
+
this.items = items;
|
|
12
|
+
}
|
|
13
|
+
get length() {
|
|
14
|
+
return this.items.length;
|
|
15
|
+
}
|
|
16
|
+
find(code) {
|
|
17
|
+
return this.items.find((bank) => bank.code === code);
|
|
18
|
+
}
|
|
19
|
+
[Symbol.iterator]() {
|
|
20
|
+
return this.items[Symbol.iterator]();
|
|
21
|
+
}
|
|
22
|
+
toJSON() {
|
|
23
|
+
return this.items;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
var BankAccountType = {
|
|
27
|
+
Natural: "NATURAL",
|
|
28
|
+
Juristic: "JURISTIC"
|
|
29
|
+
};
|
|
30
|
+
var MatchMode = {
|
|
31
|
+
Name: "NAME",
|
|
32
|
+
Number: "NUMBER",
|
|
33
|
+
NameNumber: "NAME_NUMBER"
|
|
34
|
+
};
|
|
35
|
+
var JobStatus = {
|
|
36
|
+
Queued: "queued",
|
|
37
|
+
Processing: "processing",
|
|
38
|
+
Retrying: "retrying",
|
|
39
|
+
Done: "done",
|
|
40
|
+
Failed: "failed"
|
|
41
|
+
};
|
|
42
|
+
function pick(spec, raw) {
|
|
43
|
+
if (spec === 0 || raw === null || typeof raw !== "object")
|
|
44
|
+
return raw;
|
|
45
|
+
if (Array.isArray(spec)) {
|
|
46
|
+
const item = spec[0];
|
|
47
|
+
return Array.isArray(raw) ? raw.map((value) => pick(item, value)) : raw;
|
|
48
|
+
}
|
|
49
|
+
if (Array.isArray(raw))
|
|
50
|
+
return raw;
|
|
51
|
+
const shape = spec;
|
|
52
|
+
const out = {};
|
|
53
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
54
|
+
const child = shape[key];
|
|
55
|
+
if (child !== undefined && Object.hasOwn(shape, key))
|
|
56
|
+
out[key] = pick(child, value);
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
var autoRenew = { expired: 0, quota: 0, createdAt: 0, expiresAt: 0 };
|
|
61
|
+
var applicationQuota = { used: 0, max: 0, remaining: 0, totalUsed: 0 };
|
|
62
|
+
var infoShape = {
|
|
63
|
+
application: { name: 0, autoRenew, quota: applicationQuota },
|
|
64
|
+
branch: {
|
|
65
|
+
name: 0,
|
|
66
|
+
isActive: 0,
|
|
67
|
+
quota: { used: 0, totalUsed: 0 }
|
|
68
|
+
},
|
|
69
|
+
account: { email: 0, credit: 0 },
|
|
70
|
+
product: { name: 0 }
|
|
71
|
+
};
|
|
72
|
+
var accountNumber = { type: 0, account: 0 };
|
|
73
|
+
var slipAccount = {
|
|
74
|
+
name: { th: 0, en: 0 },
|
|
75
|
+
bank: accountNumber,
|
|
76
|
+
proxy: accountNumber
|
|
77
|
+
};
|
|
78
|
+
var slipBank = { id: 0, name: 0, short: 0 };
|
|
79
|
+
var slipParty = { bank: slipBank, account: slipAccount };
|
|
80
|
+
var bankSlipShape = {
|
|
81
|
+
payload: 0,
|
|
82
|
+
transRef: 0,
|
|
83
|
+
date: 0,
|
|
84
|
+
countryCode: 0,
|
|
85
|
+
amount: {
|
|
86
|
+
amount: 0,
|
|
87
|
+
local: { amount: 0, currency: 0 }
|
|
88
|
+
},
|
|
89
|
+
fee: 0,
|
|
90
|
+
ref1: 0,
|
|
91
|
+
ref2: 0,
|
|
92
|
+
ref3: 0,
|
|
93
|
+
sender: slipParty,
|
|
94
|
+
receiver: { ...slipParty, merchantId: 0 }
|
|
95
|
+
};
|
|
96
|
+
var matchedAccount = {
|
|
97
|
+
bank: { nameTh: 0, nameEn: 0, code: 0, shortCode: 0 },
|
|
98
|
+
nameTh: 0,
|
|
99
|
+
nameEn: 0,
|
|
100
|
+
type: 0,
|
|
101
|
+
bankNumber: 0
|
|
102
|
+
};
|
|
103
|
+
var bankSlipResultShape = {
|
|
104
|
+
remark: 0,
|
|
105
|
+
isDuplicate: 0,
|
|
106
|
+
matchedAccount,
|
|
107
|
+
amountInOrder: 0,
|
|
108
|
+
amountInSlip: 0,
|
|
109
|
+
isAmountMatched: 0,
|
|
110
|
+
rawSlip: bankSlipShape
|
|
111
|
+
};
|
|
112
|
+
var trueWalletSlipShape = {
|
|
113
|
+
transactionId: 0,
|
|
114
|
+
date: 0,
|
|
115
|
+
amount: 0,
|
|
116
|
+
sender: { name: 0, phone: 0 },
|
|
117
|
+
receiver: { name: 0, phone: 0 }
|
|
118
|
+
};
|
|
119
|
+
var trueWalletResultShape = {
|
|
120
|
+
...bankSlipResultShape,
|
|
121
|
+
rawSlip: trueWalletSlipShape
|
|
122
|
+
};
|
|
123
|
+
var bankShape = {
|
|
124
|
+
code: 0,
|
|
125
|
+
nameTh: 0,
|
|
126
|
+
nameEn: 0,
|
|
127
|
+
shortCode: 0,
|
|
128
|
+
swiftCode: 0,
|
|
129
|
+
extraVerify: [{ value: 0, label: 0 }]
|
|
130
|
+
};
|
|
131
|
+
var bankAccountShape = {
|
|
132
|
+
id: 0,
|
|
133
|
+
bankCode: 0,
|
|
134
|
+
bankNumber: 0,
|
|
135
|
+
nameTh: 0,
|
|
136
|
+
nameEn: 0,
|
|
137
|
+
type: 0,
|
|
138
|
+
extraVerify: 0,
|
|
139
|
+
matchMode: 0,
|
|
140
|
+
createdAt: 0,
|
|
141
|
+
updatedAt: 0,
|
|
142
|
+
deletedAt: 0
|
|
143
|
+
};
|
|
144
|
+
var bankAccountPageShape = {
|
|
145
|
+
items: [bankAccountShape],
|
|
146
|
+
total: 0,
|
|
147
|
+
page: 0,
|
|
148
|
+
limit: 0
|
|
149
|
+
};
|
|
150
|
+
var jobShape = {
|
|
151
|
+
jobId: 0,
|
|
152
|
+
batchId: 0,
|
|
153
|
+
status: 0,
|
|
154
|
+
result: { status: 0, data: bankSlipResultShape },
|
|
155
|
+
error: {
|
|
156
|
+
code: 0,
|
|
157
|
+
message: 0,
|
|
158
|
+
webhook: 0,
|
|
159
|
+
url: 0,
|
|
160
|
+
status: 0,
|
|
161
|
+
at: 0
|
|
162
|
+
},
|
|
163
|
+
attempts: 0,
|
|
164
|
+
createdAt: 0,
|
|
165
|
+
updatedAt: 0,
|
|
166
|
+
branchId: 0,
|
|
167
|
+
serviceId: 0,
|
|
168
|
+
callbackEventId: 0,
|
|
169
|
+
callbackProtocol: 0,
|
|
170
|
+
callbackDelivery: { state: 0, httpStatus: 0 }
|
|
171
|
+
};
|
|
172
|
+
var webhookEventShape = {
|
|
173
|
+
jobId: 0,
|
|
174
|
+
batchId: 0,
|
|
175
|
+
status: 0,
|
|
176
|
+
data: bankSlipResultShape,
|
|
177
|
+
error: { code: 0, message: 0 },
|
|
178
|
+
timestamp: 0
|
|
179
|
+
};
|
|
180
|
+
var shapes = {
|
|
181
|
+
Info: infoShape,
|
|
182
|
+
BankSlip: bankSlipShape,
|
|
183
|
+
BankSlipResult: bankSlipResultShape,
|
|
184
|
+
TrueWalletSlip: trueWalletSlipShape,
|
|
185
|
+
TrueWalletResult: trueWalletResultShape,
|
|
186
|
+
BankAccount: bankAccountShape,
|
|
187
|
+
BankAccountPage: bankAccountPageShape,
|
|
188
|
+
LinkResult: { linked: 0 },
|
|
189
|
+
UnlinkResult: { unlinked: 0 },
|
|
190
|
+
JobSubmission: { jobId: 0 },
|
|
191
|
+
BatchSubmission: {
|
|
192
|
+
batchId: 0,
|
|
193
|
+
jobs: [{ jobId: 0, index: 0 }]
|
|
194
|
+
},
|
|
195
|
+
Job: jobShape,
|
|
196
|
+
WebhookEvent: webhookEventShape,
|
|
197
|
+
V1Me: {
|
|
198
|
+
application: 0,
|
|
199
|
+
usedQuota: 0,
|
|
200
|
+
maxQuota: 0,
|
|
201
|
+
remainingQuota: 0,
|
|
202
|
+
expiredAt: 0,
|
|
203
|
+
currentCredit: 0
|
|
204
|
+
},
|
|
205
|
+
QrCode: { image: 0, mime: 0, payload: 0 }
|
|
206
|
+
};
|
|
207
|
+
function parseModel(name, raw) {
|
|
208
|
+
if (name === "BankList") {
|
|
209
|
+
const items = Array.isArray(raw) ? pick([bankShape], raw) : [];
|
|
210
|
+
return new BankList(items);
|
|
211
|
+
}
|
|
212
|
+
const value = pick(shapes[name], raw);
|
|
213
|
+
if (value === null || typeof value !== "object") {
|
|
214
|
+
return {};
|
|
215
|
+
}
|
|
216
|
+
return value;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// src/core/errors.ts
|
|
220
|
+
class EasySlipError extends Error {
|
|
221
|
+
constructor(message, options) {
|
|
222
|
+
super(message, options);
|
|
223
|
+
this.name = new.target.name;
|
|
224
|
+
}
|
|
225
|
+
toString() {
|
|
226
|
+
return `${this.name}: ${this.message}`;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
class ApiError extends EasySlipError {
|
|
231
|
+
status;
|
|
232
|
+
code;
|
|
233
|
+
requestId;
|
|
234
|
+
rawBody;
|
|
235
|
+
headers;
|
|
236
|
+
details;
|
|
237
|
+
retryAfter;
|
|
238
|
+
rateLimit;
|
|
239
|
+
#sensitiveRawBody;
|
|
240
|
+
constructor(init) {
|
|
241
|
+
super(init.message);
|
|
242
|
+
this.status = init.status;
|
|
243
|
+
this.code = init.code;
|
|
244
|
+
this.requestId = init.requestId;
|
|
245
|
+
this.rawBody = init.rawBody;
|
|
246
|
+
this.#sensitiveRawBody = init.sensitiveRawBody ?? init.rawBody;
|
|
247
|
+
this.headers = init.headers;
|
|
248
|
+
this.details = init.details ?? null;
|
|
249
|
+
this.retryAfter = init.retryAfter ?? null;
|
|
250
|
+
this.rateLimit = init.rateLimit ?? null;
|
|
251
|
+
}
|
|
252
|
+
sensitiveRawBody() {
|
|
253
|
+
return this.#sensitiveRawBody;
|
|
254
|
+
}
|
|
255
|
+
toString() {
|
|
256
|
+
return `${this.name}: [${this.status}${this.code ? ` ${this.code}` : ""}] ${this.message}`;
|
|
257
|
+
}
|
|
258
|
+
toJSON() {
|
|
259
|
+
return {
|
|
260
|
+
name: this.name,
|
|
261
|
+
message: this.message,
|
|
262
|
+
status: this.status,
|
|
263
|
+
code: this.code,
|
|
264
|
+
requestId: this.requestId,
|
|
265
|
+
details: this.details,
|
|
266
|
+
retryAfter: this.retryAfter,
|
|
267
|
+
rateLimit: this.rateLimit,
|
|
268
|
+
headers: this.headers,
|
|
269
|
+
rawBody: this.rawBody
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
class AuthenticationError extends ApiError {
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
class PermissionDeniedError extends ApiError {
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
class QuotaExceededError extends PermissionDeniedError {
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
class InvalidRequestError extends ApiError {
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
class InvalidImageError extends InvalidRequestError {
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
class InvalidUrlError extends InvalidRequestError {
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
class DuplicateSlipError extends InvalidRequestError {
|
|
293
|
+
slip;
|
|
294
|
+
constructor(init) {
|
|
295
|
+
super(init);
|
|
296
|
+
this.slip = init.slip ?? null;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
class NotFoundError extends ApiError {
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
class SlipNotFoundError extends NotFoundError {
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
class SlipPendingError extends NotFoundError {
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
class ConflictError extends ApiError {
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
class RateLimitError extends ApiError {
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
class ServerError extends ApiError {
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
class ServiceUnavailableError extends ServerError {
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
class NetworkError extends EasySlipError {
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
class RequestTimeoutError extends NetworkError {
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
class InputError extends EasySlipError {
|
|
328
|
+
code;
|
|
329
|
+
constructor(code, message, options) {
|
|
330
|
+
super(message, options);
|
|
331
|
+
this.code = code;
|
|
332
|
+
}
|
|
333
|
+
toString() {
|
|
334
|
+
return `${this.name}: [${this.code}] ${this.message}`;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
class WebhookSignatureError extends EasySlipError {
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
class JobWaitTimeoutError extends EasySlipError {
|
|
342
|
+
lastJob;
|
|
343
|
+
constructor(message, lastJob) {
|
|
344
|
+
super(message);
|
|
345
|
+
this.lastJob = lastJob;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
class BatchSubmitError extends EasySlipError {
|
|
350
|
+
submitted;
|
|
351
|
+
failedChunk;
|
|
352
|
+
constructor(submitted, failedChunk, cause) {
|
|
353
|
+
super(`batch chunk ${failedChunk} failed after ${submitted.length} accepted: ${String(cause instanceof Error ? cause.message : cause)}`, { cause });
|
|
354
|
+
this.submitted = submitted;
|
|
355
|
+
this.failedChunk = failedChunk;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
var apiErrorClasses = {
|
|
359
|
+
ApiError,
|
|
360
|
+
AuthenticationError,
|
|
361
|
+
PermissionDeniedError,
|
|
362
|
+
QuotaExceededError,
|
|
363
|
+
InvalidRequestError,
|
|
364
|
+
InvalidImageError,
|
|
365
|
+
InvalidUrlError,
|
|
366
|
+
DuplicateSlipError,
|
|
367
|
+
NotFoundError,
|
|
368
|
+
SlipNotFoundError,
|
|
369
|
+
SlipPendingError,
|
|
370
|
+
ConflictError,
|
|
371
|
+
RateLimitError,
|
|
372
|
+
ServerError,
|
|
373
|
+
ServiceUnavailableError
|
|
374
|
+
};
|
|
375
|
+
function apiErrorClass(name) {
|
|
376
|
+
return apiErrorClasses[name];
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// src/core/meta.ts
|
|
380
|
+
function attachMeta(value, meta) {
|
|
381
|
+
Object.defineProperty(value, "meta", { value: meta, enumerable: false });
|
|
382
|
+
return value;
|
|
383
|
+
}
|
|
384
|
+
function headersToRecord(headers) {
|
|
385
|
+
const out = {};
|
|
386
|
+
if (headers instanceof Headers) {
|
|
387
|
+
headers.forEach((value, key) => {
|
|
388
|
+
out[key.toLowerCase()] = value;
|
|
389
|
+
});
|
|
390
|
+
return out;
|
|
391
|
+
}
|
|
392
|
+
for (const [key, value] of Object.entries(headers))
|
|
393
|
+
out[key.toLowerCase()] = value;
|
|
394
|
+
return out;
|
|
395
|
+
}
|
|
396
|
+
function requestIdFrom(headers) {
|
|
397
|
+
return headers["x-request-id"] || headers["cf-ray"] || null;
|
|
398
|
+
}
|
|
399
|
+
function toInt(value) {
|
|
400
|
+
if (value === undefined || !/^\s*-?\d+\s*$/.test(value))
|
|
401
|
+
return null;
|
|
402
|
+
return Number.parseInt(value, 10);
|
|
403
|
+
}
|
|
404
|
+
function rateLimitFrom(headers) {
|
|
405
|
+
const limit = toInt(headers["x-ratelimit-limit"]);
|
|
406
|
+
const remaining = toInt(headers["x-ratelimit-remaining"]);
|
|
407
|
+
const reset = toInt(headers["x-ratelimit-reset"]);
|
|
408
|
+
if (limit === null || remaining === null || reset === null)
|
|
409
|
+
return null;
|
|
410
|
+
return { limit, remaining, reset };
|
|
411
|
+
}
|
|
412
|
+
function retryAfterFrom(headers, now = Date.now()) {
|
|
413
|
+
const raw = headers["retry-after"]?.trim();
|
|
414
|
+
if (!raw)
|
|
415
|
+
return null;
|
|
416
|
+
if (/^\d+$/.test(raw))
|
|
417
|
+
return Number.parseInt(raw, 10);
|
|
418
|
+
const at = Date.parse(raw);
|
|
419
|
+
if (Number.isNaN(at))
|
|
420
|
+
return null;
|
|
421
|
+
return Math.max(0, Math.ceil((at - now) / 1000));
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// src/core/call.ts
|
|
425
|
+
async function call(transport, model, spec) {
|
|
426
|
+
const { data, meta } = await transport.request(spec);
|
|
427
|
+
return attachMeta(parseModel(model, data), meta);
|
|
428
|
+
}
|
|
429
|
+
function requestOptions(options) {
|
|
430
|
+
if (!options)
|
|
431
|
+
return {};
|
|
432
|
+
const out = {};
|
|
433
|
+
if (options.signal !== undefined)
|
|
434
|
+
out.signal = options.signal;
|
|
435
|
+
if (options.timeout !== undefined)
|
|
436
|
+
out.timeout = options.timeout;
|
|
437
|
+
if (options.maxRetries !== undefined)
|
|
438
|
+
out.maxRetries = options.maxRetries;
|
|
439
|
+
return out;
|
|
440
|
+
}
|
|
441
|
+
function defined(source, keys) {
|
|
442
|
+
const out = {};
|
|
443
|
+
if (!source)
|
|
444
|
+
return out;
|
|
445
|
+
for (const key of keys) {
|
|
446
|
+
if (source[key] !== undefined)
|
|
447
|
+
out[key] = source[key];
|
|
448
|
+
}
|
|
449
|
+
return out;
|
|
450
|
+
}
|
|
451
|
+
function imageForm(field, file, fields) {
|
|
452
|
+
const form = new FormData;
|
|
453
|
+
for (const [key, value] of Object.entries(fields))
|
|
454
|
+
form.append(key, String(value));
|
|
455
|
+
form.append(field, new Blob([file.bytes], { type: file.contentType }), file.filename);
|
|
456
|
+
return form;
|
|
457
|
+
}
|
|
458
|
+
function requireString(value, name) {
|
|
459
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
460
|
+
throw new InputError("INVALID_ARGUMENT", `${name} must be a non-empty string`);
|
|
461
|
+
}
|
|
462
|
+
return value;
|
|
463
|
+
}
|
|
464
|
+
function requireId(value, name = "id") {
|
|
465
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) {
|
|
466
|
+
throw new InputError("INVALID_ARGUMENT", `${name} must be a positive integer`);
|
|
467
|
+
}
|
|
468
|
+
return value;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// src/core/error-codes.ts
|
|
472
|
+
var errorCodes = {
|
|
473
|
+
v1: {
|
|
474
|
+
unauthorized: "AuthenticationError",
|
|
475
|
+
access_denied: "PermissionDeniedError",
|
|
476
|
+
account_not_verified: "PermissionDeniedError",
|
|
477
|
+
application_expired: "PermissionDeniedError",
|
|
478
|
+
application_deactivated: "PermissionDeniedError",
|
|
479
|
+
quota_exceeded: "QuotaExceededError",
|
|
480
|
+
invalid_payload: "InvalidRequestError",
|
|
481
|
+
invalid_check_duplicate: "InvalidRequestError",
|
|
482
|
+
invalid_request: "InvalidRequestError",
|
|
483
|
+
invalid_type: "InvalidRequestError",
|
|
484
|
+
invalid_transaction_id: "InvalidRequestError",
|
|
485
|
+
invalid_sender_name: "InvalidRequestError",
|
|
486
|
+
invalid_receiver_name: "InvalidRequestError",
|
|
487
|
+
invalid_receiver_phone: "InvalidRequestError",
|
|
488
|
+
invalid_date: "InvalidRequestError",
|
|
489
|
+
invalid_amount: "InvalidRequestError",
|
|
490
|
+
invalid_image: "InvalidImageError",
|
|
491
|
+
invalid_wallet_qr: "InvalidImageError",
|
|
492
|
+
invalid_base64: "InvalidImageError",
|
|
493
|
+
image_size_too_large: "InvalidImageError",
|
|
494
|
+
invalid_url: "InvalidUrlError",
|
|
495
|
+
url_unreachable: "InvalidUrlError",
|
|
496
|
+
duplicate_slip: "DuplicateSlipError",
|
|
497
|
+
slip_not_found: "SlipNotFoundError",
|
|
498
|
+
qrcode_not_found: "SlipNotFoundError",
|
|
499
|
+
slip_pending: "SlipPendingError",
|
|
500
|
+
not_found: "NotFoundError",
|
|
501
|
+
rate_limit_exceeded: "RateLimitError",
|
|
502
|
+
server_error: "ServerError",
|
|
503
|
+
api_server_error: "ServerError",
|
|
504
|
+
renewal_temporarily_unavailable: "ServiceUnavailableError"
|
|
505
|
+
},
|
|
506
|
+
v2: {
|
|
507
|
+
MISSING_API_KEY: "AuthenticationError",
|
|
508
|
+
INVALID_API_KEY: "AuthenticationError",
|
|
509
|
+
BRANCH_INACTIVE: "PermissionDeniedError",
|
|
510
|
+
SERVICE_BANNED: "PermissionDeniedError",
|
|
511
|
+
SERVICE_DELETED: "PermissionDeniedError",
|
|
512
|
+
USER_BANNED: "PermissionDeniedError",
|
|
513
|
+
IP_NOT_ALLOWED: "PermissionDeniedError",
|
|
514
|
+
SERVICE_EXPIRED: "PermissionDeniedError",
|
|
515
|
+
QUOTA_EXCEEDED: "QuotaExceededError",
|
|
516
|
+
VALIDATION_ERROR: "InvalidRequestError",
|
|
517
|
+
INVALID_BANK_CODE: "InvalidRequestError",
|
|
518
|
+
INVALID_EXTRA_VERIFY: "InvalidRequestError",
|
|
519
|
+
INVALID_MATCH_MODE: "InvalidRequestError",
|
|
520
|
+
IMAGE_SIZE_TOO_LARGE: "InvalidImageError",
|
|
521
|
+
INVALID_IMAGE_FORMAT: "InvalidImageError",
|
|
522
|
+
INVALID_IMAGE_TYPE: "InvalidImageError",
|
|
523
|
+
INVALID_IMAGE: "InvalidImageError",
|
|
524
|
+
INVALID_WALLET_QR: "InvalidImageError",
|
|
525
|
+
URL_PROTOCOL_NOT_ALLOWED: "InvalidUrlError",
|
|
526
|
+
URL_INVALID_IP_RANGE: "InvalidUrlError",
|
|
527
|
+
IMAGE_URL_UNREACHABLE: "InvalidUrlError",
|
|
528
|
+
INVALID_CALLBACK_URL: "InvalidUrlError",
|
|
529
|
+
SLIP_NOT_FOUND: "SlipNotFoundError",
|
|
530
|
+
SLIP_PENDING: "SlipPendingError",
|
|
531
|
+
BANK_ACCOUNT_NOT_FOUND: "NotFoundError",
|
|
532
|
+
JOB_NOT_FOUND: "NotFoundError",
|
|
533
|
+
NOT_FOUND: "NotFoundError",
|
|
534
|
+
BANK_ACCOUNT_DUPLICATE: "ConflictError",
|
|
535
|
+
RATE_LIMIT_EXCEEDED: "RateLimitError",
|
|
536
|
+
API_SERVER_ERROR: "ServerError",
|
|
537
|
+
INTERNAL_SERVER_ERROR: "ServerError",
|
|
538
|
+
RENEWAL_TEMPORARILY_UNAVAILABLE: "ServiceUnavailableError",
|
|
539
|
+
CALLBACK_UNAVAILABLE: "ServiceUnavailableError"
|
|
540
|
+
}
|
|
541
|
+
};
|
|
542
|
+
var statusFallback = {
|
|
543
|
+
400: "InvalidRequestError",
|
|
544
|
+
401: "AuthenticationError",
|
|
545
|
+
403: "PermissionDeniedError",
|
|
546
|
+
404: "NotFoundError",
|
|
547
|
+
409: "ConflictError",
|
|
548
|
+
429: "RateLimitError",
|
|
549
|
+
500: "ServerError",
|
|
550
|
+
502: "ServerError",
|
|
551
|
+
503: "ServiceUnavailableError",
|
|
552
|
+
504: "ServerError"
|
|
553
|
+
};
|
|
554
|
+
|
|
555
|
+
// src/core/redact.ts
|
|
556
|
+
var REDACTED = "[REDACTED]";
|
|
557
|
+
var AUTH_HEADERS = new Set(["authorization", "proxy-authorization"]);
|
|
558
|
+
var MAX_CAUSE_DEPTH = 3;
|
|
559
|
+
var noRedact = { text: (value) => value, carries: () => false };
|
|
560
|
+
var utf8 = new TextDecoder;
|
|
561
|
+
function percentDecode(text) {
|
|
562
|
+
if (!text.includes("%"))
|
|
563
|
+
return text;
|
|
564
|
+
return text.replace(/(?:%[0-9a-fA-F]{2})+/g, (run) => {
|
|
565
|
+
const bytes = new Uint8Array(run.length / 3);
|
|
566
|
+
for (let i = 0;i < bytes.length; i++) {
|
|
567
|
+
bytes[i] = Number.parseInt(run.slice(i * 3 + 1, i * 3 + 3), 16);
|
|
568
|
+
}
|
|
569
|
+
return utf8.decode(bytes);
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
var JSON_ESCAPES = {
|
|
573
|
+
'"': '"',
|
|
574
|
+
"\\": "\\",
|
|
575
|
+
"/": "/",
|
|
576
|
+
b: "\b",
|
|
577
|
+
f: "\f",
|
|
578
|
+
n: `
|
|
579
|
+
`,
|
|
580
|
+
r: "\r",
|
|
581
|
+
t: "\t"
|
|
582
|
+
};
|
|
583
|
+
function jsonUnescape(text) {
|
|
584
|
+
if (!text.includes("\\"))
|
|
585
|
+
return text;
|
|
586
|
+
return text.replace(/\\(u[0-9a-fA-F]{4}|["\\/bfnrt])/g, (_, seq) => seq.length === 5 ? String.fromCharCode(Number.parseInt(seq.slice(1), 16)) : JSON_ESCAPES[seq]);
|
|
587
|
+
}
|
|
588
|
+
function percentPattern(apiKey) {
|
|
589
|
+
const hex = (byte) => [...byte.toString(16).padStart(2, "0")].map((d) => /[a-f]/.test(d) ? `[${d}${d.toUpperCase()}]` : d).join("");
|
|
590
|
+
const parts = [...apiKey].map((char) => {
|
|
591
|
+
const literal = char.replace(/[.*+?^${}()|[\]\\/-]/g, "\\$&");
|
|
592
|
+
const encoded = [...new TextEncoder().encode(char)].map((b) => `%${hex(b)}`).join("");
|
|
593
|
+
return `(?:${literal}|${encoded})`;
|
|
594
|
+
});
|
|
595
|
+
return new RegExp(parts.join(""), "g");
|
|
596
|
+
}
|
|
597
|
+
function redactor(apiKey) {
|
|
598
|
+
if (apiKey.length < 4)
|
|
599
|
+
return noRedact;
|
|
600
|
+
const pattern = percentPattern(apiKey);
|
|
601
|
+
const carries = (value) => {
|
|
602
|
+
let views = [value];
|
|
603
|
+
const seen = new Set(views);
|
|
604
|
+
for (let level = 0;level <= 3; level++) {
|
|
605
|
+
if (views.some((view) => view.includes(apiKey)))
|
|
606
|
+
return true;
|
|
607
|
+
const next = [];
|
|
608
|
+
for (const view of views) {
|
|
609
|
+
for (const decoded of [percentDecode(view), jsonUnescape(view)]) {
|
|
610
|
+
if (!seen.has(decoded)) {
|
|
611
|
+
seen.add(decoded);
|
|
612
|
+
next.push(decoded);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
if (next.length === 0)
|
|
617
|
+
return false;
|
|
618
|
+
views = next;
|
|
619
|
+
}
|
|
620
|
+
return false;
|
|
621
|
+
};
|
|
622
|
+
return {
|
|
623
|
+
carries,
|
|
624
|
+
text(value) {
|
|
625
|
+
if (!value)
|
|
626
|
+
return value;
|
|
627
|
+
const out = value.replace(pattern, REDACTED);
|
|
628
|
+
return carries(out) ? REDACTED : out;
|
|
629
|
+
}
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
function redactHeaders(headers, redact) {
|
|
633
|
+
const out = {};
|
|
634
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
635
|
+
out[name] = AUTH_HEADERS.has(name.toLowerCase()) || redact.carries(value) ? REDACTED : value;
|
|
636
|
+
}
|
|
637
|
+
return out;
|
|
638
|
+
}
|
|
639
|
+
function defineValue(target, key, value) {
|
|
640
|
+
Object.defineProperty(target, key, {
|
|
641
|
+
value,
|
|
642
|
+
enumerable: true,
|
|
643
|
+
writable: true,
|
|
644
|
+
configurable: true
|
|
645
|
+
});
|
|
646
|
+
}
|
|
647
|
+
function redactJson(value, redact) {
|
|
648
|
+
if (typeof value === "string")
|
|
649
|
+
return redact.text(value);
|
|
650
|
+
if (Array.isArray(value)) {
|
|
651
|
+
const out = value.map((item) => redactJson(item, redact));
|
|
652
|
+
return out.some((item, i) => item !== value[i]) ? out : value;
|
|
653
|
+
}
|
|
654
|
+
if (value === null || typeof value !== "object")
|
|
655
|
+
return value;
|
|
656
|
+
let changed = false;
|
|
657
|
+
const out = {};
|
|
658
|
+
for (const [key, item] of Object.entries(value)) {
|
|
659
|
+
const safeKey = redact.text(key);
|
|
660
|
+
const safeItem = redactJson(item, redact);
|
|
661
|
+
if (safeKey !== key || safeItem !== item)
|
|
662
|
+
changed = true;
|
|
663
|
+
defineValue(out, safeKey, safeItem);
|
|
664
|
+
}
|
|
665
|
+
return changed ? out : value;
|
|
666
|
+
}
|
|
667
|
+
function redactBody(text, body, redact) {
|
|
668
|
+
if (body === undefined)
|
|
669
|
+
return { rawBody: redact.text(text), body };
|
|
670
|
+
const safe = redactJson(body, redact);
|
|
671
|
+
return { rawBody: safe === body ? text : JSON.stringify(safe), body: safe };
|
|
672
|
+
}
|
|
673
|
+
function read(source, key) {
|
|
674
|
+
try {
|
|
675
|
+
return source[key];
|
|
676
|
+
} catch {
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
function typeName(source) {
|
|
681
|
+
if (source instanceof Error)
|
|
682
|
+
return String(read(source, "name") ?? "Error");
|
|
683
|
+
if (source === null)
|
|
684
|
+
return "null";
|
|
685
|
+
if (typeof source !== "object")
|
|
686
|
+
return typeof source;
|
|
687
|
+
const ctor = read(source, "constructor");
|
|
688
|
+
return typeof ctor?.name === "string" && ctor.name ? ctor.name : "Object";
|
|
689
|
+
}
|
|
690
|
+
function messageOf(source) {
|
|
691
|
+
if (typeof source === "string")
|
|
692
|
+
return source;
|
|
693
|
+
const message = read(source, "message");
|
|
694
|
+
if (typeof message === "string")
|
|
695
|
+
return message;
|
|
696
|
+
if (source instanceof Error || source !== null && typeof source === "object")
|
|
697
|
+
return "";
|
|
698
|
+
return String(source);
|
|
699
|
+
}
|
|
700
|
+
function sanitizeCause(cause, redact, depth = 1) {
|
|
701
|
+
const copy = new Error(redact.text(messageOf(cause)));
|
|
702
|
+
copy.name = redact.text(typeName(cause));
|
|
703
|
+
copy.stack = `${copy.name}: ${copy.message}`;
|
|
704
|
+
for (const field of ["code", "errno"]) {
|
|
705
|
+
const value = cause !== null && typeof cause === "object" ? read(cause, field) : undefined;
|
|
706
|
+
if (typeof value === "string")
|
|
707
|
+
defineValue(copy, field, redact.text(value));
|
|
708
|
+
else if (typeof value === "number") {
|
|
709
|
+
defineValue(copy, field, redact.carries(String(value)) ? REDACTED : value);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
const inner = cause !== null && typeof cause === "object" ? read(cause, "cause") : undefined;
|
|
713
|
+
if (inner !== undefined && depth < MAX_CAUSE_DEPTH) {
|
|
714
|
+
Object.defineProperty(copy, "cause", {
|
|
715
|
+
value: sanitizeCause(inner, redact, depth + 1),
|
|
716
|
+
enumerable: false,
|
|
717
|
+
writable: true,
|
|
718
|
+
configurable: true
|
|
719
|
+
});
|
|
720
|
+
}
|
|
721
|
+
return copy;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
// src/core/http.ts
|
|
725
|
+
var RETRY_STATUS = new Set([500, 502, 503, 504]);
|
|
726
|
+
var MAX_RETRY_AFTER_SECONDS = 60;
|
|
727
|
+
var CONNECT_CODES = new Set([
|
|
728
|
+
"ECONNREFUSED",
|
|
729
|
+
"ENOTFOUND",
|
|
730
|
+
"EAI_AGAIN",
|
|
731
|
+
"EAI_NONAME",
|
|
732
|
+
"EAI_FAIL",
|
|
733
|
+
"EHOSTUNREACH",
|
|
734
|
+
"ENETUNREACH",
|
|
735
|
+
"EADDRNOTAVAIL",
|
|
736
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
737
|
+
"ConnectionRefused",
|
|
738
|
+
"FailedToOpenSocket",
|
|
739
|
+
"DNSException"
|
|
740
|
+
]);
|
|
741
|
+
function errorCodesOf(error, depth = 0) {
|
|
742
|
+
if (!error || typeof error !== "object" || depth > 3)
|
|
743
|
+
return [];
|
|
744
|
+
const e = error;
|
|
745
|
+
const out = typeof e.code === "string" ? [e.code] : [];
|
|
746
|
+
out.push(...errorCodesOf(e.cause, depth + 1));
|
|
747
|
+
if (Array.isArray(e.errors))
|
|
748
|
+
for (const inner of e.errors)
|
|
749
|
+
out.push(...errorCodesOf(inner, depth + 1));
|
|
750
|
+
return out;
|
|
751
|
+
}
|
|
752
|
+
function isConnectFailure(error) {
|
|
753
|
+
return errorCodesOf(error).some((code) => CONNECT_CODES.has(code) || code.startsWith("ERR_TLS_") || code.startsWith("ERR_SSL_") || code.includes("CERT") || code.startsWith("UNABLE_TO_"));
|
|
754
|
+
}
|
|
755
|
+
function backoffDelay(attempt, random = Math.random) {
|
|
756
|
+
const base = Math.min(8000, 500 * 2 ** attempt);
|
|
757
|
+
return base * (0.5 + random() * 0.5);
|
|
758
|
+
}
|
|
759
|
+
function parseJson(text) {
|
|
760
|
+
if (!text)
|
|
761
|
+
return;
|
|
762
|
+
try {
|
|
763
|
+
return JSON.parse(text);
|
|
764
|
+
} catch {
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
function isObject(value) {
|
|
769
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
770
|
+
}
|
|
771
|
+
function errorFromResponse(api, status, headers, text, parsed, duplicateSlip, redact) {
|
|
772
|
+
const { rawBody, body } = redactBody(text, parsed, redact);
|
|
773
|
+
let code = null;
|
|
774
|
+
let message = "";
|
|
775
|
+
let details = null;
|
|
776
|
+
let slipData;
|
|
777
|
+
if (isObject(body)) {
|
|
778
|
+
if (api === "v2" && isObject(body.error)) {
|
|
779
|
+
if (typeof body.error.code === "string")
|
|
780
|
+
code = body.error.code;
|
|
781
|
+
if (typeof body.error.message === "string")
|
|
782
|
+
message = body.error.message;
|
|
783
|
+
} else if (api === "v1") {
|
|
784
|
+
if (typeof body.message === "string") {
|
|
785
|
+
code = body.message;
|
|
786
|
+
message = body.message;
|
|
787
|
+
}
|
|
788
|
+
if (typeof body.details === "string" || Array.isArray(body.details)) {
|
|
789
|
+
details = body.details;
|
|
790
|
+
}
|
|
791
|
+
slipData = body.data;
|
|
792
|
+
} else if (typeof body.message === "string") {
|
|
793
|
+
message = body.message;
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
const className = (code !== null ? errorCodes[api][code] : undefined) ?? statusFallback[status] ?? (status >= 500 ? "ServerError" : "ApiError");
|
|
797
|
+
const ErrorClass = apiErrorClass(className);
|
|
798
|
+
const slip = className === "DuplicateSlipError" && isObject(slipData) ? parseModel(duplicateSlip ?? "BankSlip", slipData) : null;
|
|
799
|
+
const safeHeaders = redactHeaders(headers, redact);
|
|
800
|
+
return new ErrorClass({
|
|
801
|
+
status,
|
|
802
|
+
code,
|
|
803
|
+
message: message || `HTTP ${status}`,
|
|
804
|
+
requestId: requestIdFrom(safeHeaders),
|
|
805
|
+
rawBody,
|
|
806
|
+
sensitiveRawBody: text,
|
|
807
|
+
headers: safeHeaders,
|
|
808
|
+
details,
|
|
809
|
+
retryAfter: retryAfterFrom(headers),
|
|
810
|
+
rateLimit: rateLimitFrom(headers),
|
|
811
|
+
slip
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
function decodeResponse(api, status, rawHeaders, text, duplicateSlip, redact = noRedact) {
|
|
815
|
+
const headers = headersToRecord(rawHeaders);
|
|
816
|
+
const body = parseJson(text);
|
|
817
|
+
const ok = status >= 200 && status < 300;
|
|
818
|
+
const successEnvelope = isObject(body) && (api === "v2" ? body.success === true : ("data" in body));
|
|
819
|
+
if (!ok || !successEnvelope) {
|
|
820
|
+
throw errorFromResponse(api, status, headers, text, body, duplicateSlip, redact);
|
|
821
|
+
}
|
|
822
|
+
const safeHeaders = redactHeaders(headers, redact);
|
|
823
|
+
const meta = {
|
|
824
|
+
status,
|
|
825
|
+
requestId: requestIdFrom(safeHeaders),
|
|
826
|
+
message: api === "v2" && typeof body.message === "string" ? redact.text(body.message) : null,
|
|
827
|
+
rateLimit: rateLimitFrom(headers),
|
|
828
|
+
headers: safeHeaders
|
|
829
|
+
};
|
|
830
|
+
return { data: body.data, meta };
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
class Transport {
|
|
834
|
+
#config;
|
|
835
|
+
constructor(config) {
|
|
836
|
+
this.#config = config;
|
|
837
|
+
}
|
|
838
|
+
get config() {
|
|
839
|
+
const { apiKey: _apiKey, ...rest } = this.#config;
|
|
840
|
+
return rest;
|
|
841
|
+
}
|
|
842
|
+
#url(spec) {
|
|
843
|
+
const base = (spec.api === "v1" ? this.#config.v1BaseUrl : this.#config.v2BaseUrl).replace(/\/+$/, "");
|
|
844
|
+
const params = new URLSearchParams;
|
|
845
|
+
for (const [key, value] of Object.entries(spec.query ?? {})) {
|
|
846
|
+
if (value !== undefined)
|
|
847
|
+
params.append(key, value);
|
|
848
|
+
}
|
|
849
|
+
const qs = params.toString();
|
|
850
|
+
return `${base}${spec.path}${qs ? `?${qs}` : ""}`;
|
|
851
|
+
}
|
|
852
|
+
async request(spec) {
|
|
853
|
+
const config = this.#config;
|
|
854
|
+
const maxRetries = Math.max(0, spec.maxRetries ?? config.maxRetries);
|
|
855
|
+
const timeout = spec.timeout ?? config.timeout;
|
|
856
|
+
const url = this.#url(spec);
|
|
857
|
+
const apiKey = await config.apiKey();
|
|
858
|
+
const redact = redactor(apiKey);
|
|
859
|
+
const headers = {
|
|
860
|
+
Authorization: `Bearer ${apiKey}`,
|
|
861
|
+
Accept: "application/json",
|
|
862
|
+
"User-Agent": config.userAgent
|
|
863
|
+
};
|
|
864
|
+
let body;
|
|
865
|
+
if (spec.form) {
|
|
866
|
+
body = spec.form;
|
|
867
|
+
} else if (spec.json !== undefined) {
|
|
868
|
+
body = JSON.stringify(spec.json);
|
|
869
|
+
headers["Content-Type"] = "application/json";
|
|
870
|
+
}
|
|
871
|
+
for (let attempt = 0;; attempt++) {
|
|
872
|
+
spec.signal?.throwIfAborted();
|
|
873
|
+
const controller = new AbortController;
|
|
874
|
+
let timedOut = false;
|
|
875
|
+
const timer = setTimeout(() => {
|
|
876
|
+
timedOut = true;
|
|
877
|
+
controller.abort();
|
|
878
|
+
}, timeout);
|
|
879
|
+
const onAbort = () => controller.abort(spec.signal?.reason);
|
|
880
|
+
spec.signal?.addEventListener("abort", onAbort, { once: true });
|
|
881
|
+
let status;
|
|
882
|
+
let responseHeaders;
|
|
883
|
+
let text;
|
|
884
|
+
try {
|
|
885
|
+
const response = await config.fetch(url, {
|
|
886
|
+
method: spec.method,
|
|
887
|
+
headers,
|
|
888
|
+
body,
|
|
889
|
+
signal: controller.signal
|
|
890
|
+
});
|
|
891
|
+
status = response.status;
|
|
892
|
+
responseHeaders = response.headers;
|
|
893
|
+
text = await response.text();
|
|
894
|
+
} catch (rawCause) {
|
|
895
|
+
if (spec.signal?.aborted)
|
|
896
|
+
throw spec.signal.reason;
|
|
897
|
+
const cause = sanitizeCause(rawCause, redact);
|
|
898
|
+
const error = timedOut ? new RequestTimeoutError(`no response within ${timeout} ms`, { cause }) : new NetworkError(`request failed: ${cause.message}`, { cause });
|
|
899
|
+
const retryable = attempt < maxRetries && (spec.retry === "safe" || !timedOut && isConnectFailure(rawCause));
|
|
900
|
+
if (!retryable)
|
|
901
|
+
throw error;
|
|
902
|
+
spec.signal?.throwIfAborted();
|
|
903
|
+
await config.sleep(backoffDelay(attempt, config.random), spec.signal);
|
|
904
|
+
continue;
|
|
905
|
+
} finally {
|
|
906
|
+
clearTimeout(timer);
|
|
907
|
+
spec.signal?.removeEventListener("abort", onAbort);
|
|
908
|
+
}
|
|
909
|
+
try {
|
|
910
|
+
return decodeResponse(spec.api, status, responseHeaders, text, spec.duplicateSlip, redact);
|
|
911
|
+
} catch (error) {
|
|
912
|
+
const apiError = error;
|
|
913
|
+
const retryable = attempt < maxRetries && (status === 429 || spec.retry === "safe" && RETRY_STATUS.has(status));
|
|
914
|
+
if (!retryable)
|
|
915
|
+
throw apiError;
|
|
916
|
+
const retryAfter = apiError.retryAfter;
|
|
917
|
+
if (retryAfter !== null && retryAfter > MAX_RETRY_AFTER_SECONDS)
|
|
918
|
+
throw apiError;
|
|
919
|
+
const delay = retryAfter !== null ? retryAfter * 1000 : backoffDelay(attempt, config.random);
|
|
920
|
+
spec.signal?.throwIfAborted();
|
|
921
|
+
await config.sleep(delay, spec.signal);
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
// src/core/runtime.ts
|
|
928
|
+
var g = globalThis;
|
|
929
|
+
function readEnv(name) {
|
|
930
|
+
try {
|
|
931
|
+
if (g.Deno?.env)
|
|
932
|
+
return g.Deno.env.get(name) || undefined;
|
|
933
|
+
return g.process?.env?.[name] || undefined;
|
|
934
|
+
} catch {
|
|
935
|
+
return;
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
function runtimeToken() {
|
|
939
|
+
if (g.Bun?.version)
|
|
940
|
+
return `bun/${g.Bun.version}`;
|
|
941
|
+
if (g.Deno?.version?.deno)
|
|
942
|
+
return `deno/${g.Deno.version.deno}`;
|
|
943
|
+
if (g.process?.versions?.node)
|
|
944
|
+
return `node/${g.process.versions.node}`;
|
|
945
|
+
return "edge/unknown";
|
|
946
|
+
}
|
|
947
|
+
var fsPromise;
|
|
948
|
+
function loadFs() {
|
|
949
|
+
fsPromise ??= import("node:fs/promises").then((mod) => mod.default ?? mod, () => null);
|
|
950
|
+
return fsPromise;
|
|
951
|
+
}
|
|
952
|
+
function sleep(ms, signal) {
|
|
953
|
+
return new Promise((resolve, reject) => {
|
|
954
|
+
if (signal?.aborted) {
|
|
955
|
+
reject(signal.reason);
|
|
956
|
+
return;
|
|
957
|
+
}
|
|
958
|
+
const onAbort = () => {
|
|
959
|
+
clearTimeout(timer);
|
|
960
|
+
reject(signal?.reason);
|
|
961
|
+
};
|
|
962
|
+
const timer = setTimeout(() => {
|
|
963
|
+
signal?.removeEventListener("abort", onAbort);
|
|
964
|
+
resolve();
|
|
965
|
+
}, ms);
|
|
966
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
967
|
+
});
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
// src/core/settings.ts
|
|
971
|
+
var settings = {
|
|
972
|
+
baseUrls: {
|
|
973
|
+
v1: "https://api.easyslip.com/v1",
|
|
974
|
+
v2: "https://api.easyslip.com/v2"
|
|
975
|
+
},
|
|
976
|
+
userAgentProduct: "easyslip-js",
|
|
977
|
+
webhook: {
|
|
978
|
+
signatureHeader: "X-EasySlip-Signature",
|
|
979
|
+
signaturePrefix: "sha256="
|
|
980
|
+
},
|
|
981
|
+
env: {
|
|
982
|
+
apiKey: "EASYSLIP_API_KEY",
|
|
983
|
+
apiKeyFile: "EASYSLIP_API_KEY_FILE",
|
|
984
|
+
webhookSecret: "EASYSLIP_WEBHOOK_SECRET",
|
|
985
|
+
v1BaseUrl: "EASYSLIP_V1_BASE_URL",
|
|
986
|
+
v2BaseUrl: "EASYSLIP_V2_BASE_URL"
|
|
987
|
+
}
|
|
988
|
+
};
|
|
989
|
+
|
|
990
|
+
// src/resources/bank-accounts.ts
|
|
991
|
+
var CREATE_KEYS = [
|
|
992
|
+
"bankCode",
|
|
993
|
+
"bankNumber",
|
|
994
|
+
"nameTh",
|
|
995
|
+
"nameEn",
|
|
996
|
+
"type",
|
|
997
|
+
"extraVerify",
|
|
998
|
+
"matchMode"
|
|
999
|
+
];
|
|
1000
|
+
function listQuery(params) {
|
|
1001
|
+
return {
|
|
1002
|
+
type: params?.type,
|
|
1003
|
+
bankCode: params?.bankCode,
|
|
1004
|
+
page: params?.page === undefined ? undefined : String(params.page),
|
|
1005
|
+
limit: params?.limit === undefined ? undefined : String(params.limit)
|
|
1006
|
+
};
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
class BankAccounts {
|
|
1010
|
+
#t;
|
|
1011
|
+
constructor(transport) {
|
|
1012
|
+
this.#t = transport;
|
|
1013
|
+
}
|
|
1014
|
+
async list(params, options) {
|
|
1015
|
+
return call(this.#t, "BankAccountPage", {
|
|
1016
|
+
...requestOptions(options),
|
|
1017
|
+
api: "v2",
|
|
1018
|
+
method: "GET",
|
|
1019
|
+
path: "/bank-accounts",
|
|
1020
|
+
query: listQuery(params),
|
|
1021
|
+
retry: "safe"
|
|
1022
|
+
});
|
|
1023
|
+
}
|
|
1024
|
+
async listAll(params, options) {
|
|
1025
|
+
return call(this.#t, "BankAccountPage", {
|
|
1026
|
+
...requestOptions(options),
|
|
1027
|
+
api: "v2",
|
|
1028
|
+
method: "GET",
|
|
1029
|
+
path: "/bank-accounts/all",
|
|
1030
|
+
query: listQuery(params),
|
|
1031
|
+
retry: "safe"
|
|
1032
|
+
});
|
|
1033
|
+
}
|
|
1034
|
+
async get(id, options) {
|
|
1035
|
+
requireId(id);
|
|
1036
|
+
return call(this.#t, "BankAccount", {
|
|
1037
|
+
...requestOptions(options),
|
|
1038
|
+
api: "v2",
|
|
1039
|
+
method: "GET",
|
|
1040
|
+
path: `/bank-accounts/${id}`,
|
|
1041
|
+
retry: "safe"
|
|
1042
|
+
});
|
|
1043
|
+
}
|
|
1044
|
+
async create(params, options) {
|
|
1045
|
+
return call(this.#t, "BankAccount", {
|
|
1046
|
+
...requestOptions(options),
|
|
1047
|
+
api: "v2",
|
|
1048
|
+
method: "POST",
|
|
1049
|
+
path: "/bank-accounts",
|
|
1050
|
+
json: defined(params, CREATE_KEYS),
|
|
1051
|
+
retry: "write"
|
|
1052
|
+
});
|
|
1053
|
+
}
|
|
1054
|
+
async update(id, params, options) {
|
|
1055
|
+
requireId(id);
|
|
1056
|
+
return call(this.#t, "BankAccount", {
|
|
1057
|
+
...requestOptions(options),
|
|
1058
|
+
api: "v2",
|
|
1059
|
+
method: "PATCH",
|
|
1060
|
+
path: `/bank-accounts/${id}`,
|
|
1061
|
+
json: defined(params, CREATE_KEYS),
|
|
1062
|
+
retry: "write"
|
|
1063
|
+
});
|
|
1064
|
+
}
|
|
1065
|
+
async link(id, options) {
|
|
1066
|
+
requireId(id);
|
|
1067
|
+
return call(this.#t, "LinkResult", {
|
|
1068
|
+
...requestOptions(options),
|
|
1069
|
+
api: "v2",
|
|
1070
|
+
method: "POST",
|
|
1071
|
+
path: `/bank-accounts/${id}/link`,
|
|
1072
|
+
retry: "safe"
|
|
1073
|
+
});
|
|
1074
|
+
}
|
|
1075
|
+
async unlink(id, options) {
|
|
1076
|
+
requireId(id);
|
|
1077
|
+
return call(this.#t, "UnlinkResult", {
|
|
1078
|
+
...requestOptions(options),
|
|
1079
|
+
api: "v2",
|
|
1080
|
+
method: "DELETE",
|
|
1081
|
+
path: `/bank-accounts/${id}/link`,
|
|
1082
|
+
retry: "write"
|
|
1083
|
+
});
|
|
1084
|
+
}
|
|
1085
|
+
iterate(params, options) {
|
|
1086
|
+
return this.#walk((p) => this.list(p, options), params);
|
|
1087
|
+
}
|
|
1088
|
+
iterateAll(params, options) {
|
|
1089
|
+
return this.#walk((p) => this.listAll(p, options), params);
|
|
1090
|
+
}
|
|
1091
|
+
async* #walk(fetchPage, params) {
|
|
1092
|
+
let page = params?.page ?? 1;
|
|
1093
|
+
const limit = params?.limit ?? 100;
|
|
1094
|
+
while (true) {
|
|
1095
|
+
const result = await fetchPage({ ...params, page, limit });
|
|
1096
|
+
yield* result.items;
|
|
1097
|
+
if (result.items.length === 0 || page * limit >= result.total)
|
|
1098
|
+
return;
|
|
1099
|
+
page++;
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
// src/resources/banks.ts
|
|
1105
|
+
class Banks {
|
|
1106
|
+
#t;
|
|
1107
|
+
constructor(transport) {
|
|
1108
|
+
this.#t = transport;
|
|
1109
|
+
}
|
|
1110
|
+
async list(options) {
|
|
1111
|
+
return call(this.#t, "BankList", {
|
|
1112
|
+
...requestOptions(options),
|
|
1113
|
+
api: "v2",
|
|
1114
|
+
method: "GET",
|
|
1115
|
+
path: "/banks",
|
|
1116
|
+
retry: "safe"
|
|
1117
|
+
});
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
// src/core/files.ts
|
|
1122
|
+
var MAX_IMAGE_BYTES = 4 * 1024 * 1024;
|
|
1123
|
+
var types = [
|
|
1124
|
+
{
|
|
1125
|
+
type: "image/jpeg",
|
|
1126
|
+
ext: "jpg",
|
|
1127
|
+
test: (b) => b[0] === 255 && b[1] === 216 && b[2] === 255
|
|
1128
|
+
},
|
|
1129
|
+
{
|
|
1130
|
+
type: "image/png",
|
|
1131
|
+
ext: "png",
|
|
1132
|
+
test: (b) => b[0] === 137 && b[1] === 80 && b[2] === 78 && b[3] === 71
|
|
1133
|
+
},
|
|
1134
|
+
{
|
|
1135
|
+
type: "image/gif",
|
|
1136
|
+
ext: "gif",
|
|
1137
|
+
test: (b) => b[0] === 71 && b[1] === 73 && b[2] === 70 && b[3] === 56
|
|
1138
|
+
},
|
|
1139
|
+
{
|
|
1140
|
+
type: "image/webp",
|
|
1141
|
+
ext: "webp",
|
|
1142
|
+
test: (b) => ascii(b, 0, 4) === "RIFF" && ascii(b, 8, 12) === "WEBP" && b.length >= 12
|
|
1143
|
+
}
|
|
1144
|
+
];
|
|
1145
|
+
function ascii(bytes, start, end) {
|
|
1146
|
+
return String.fromCharCode(...bytes.subarray(start, end));
|
|
1147
|
+
}
|
|
1148
|
+
function sniffImageType(bytes) {
|
|
1149
|
+
const hit = types.find((t) => t.test(bytes));
|
|
1150
|
+
return hit ? { type: hit.type, ext: hit.ext } : null;
|
|
1151
|
+
}
|
|
1152
|
+
function tooLarge(size) {
|
|
1153
|
+
return new InputError("FILE_TOO_LARGE", `file is ${size} bytes; the API accepts at most ${MAX_IMAGE_BYTES} bytes`);
|
|
1154
|
+
}
|
|
1155
|
+
async function collect(chunks, maxBytes) {
|
|
1156
|
+
const parts = [];
|
|
1157
|
+
let size = 0;
|
|
1158
|
+
const encoder = new TextEncoder;
|
|
1159
|
+
for await (const chunk of chunks) {
|
|
1160
|
+
const part = typeof chunk === "string" ? encoder.encode(chunk) : chunk;
|
|
1161
|
+
size += part.byteLength;
|
|
1162
|
+
if (size > maxBytes)
|
|
1163
|
+
throw tooLarge(size);
|
|
1164
|
+
parts.push(part);
|
|
1165
|
+
}
|
|
1166
|
+
const out = new Uint8Array(size);
|
|
1167
|
+
let offset = 0;
|
|
1168
|
+
for (const part of parts) {
|
|
1169
|
+
out.set(part, offset);
|
|
1170
|
+
offset += part.byteLength;
|
|
1171
|
+
}
|
|
1172
|
+
return out;
|
|
1173
|
+
}
|
|
1174
|
+
async function* readStream(stream) {
|
|
1175
|
+
const reader = stream.getReader();
|
|
1176
|
+
try {
|
|
1177
|
+
while (true) {
|
|
1178
|
+
const { done, value } = await reader.read();
|
|
1179
|
+
if (done)
|
|
1180
|
+
return;
|
|
1181
|
+
yield value;
|
|
1182
|
+
}
|
|
1183
|
+
} finally {
|
|
1184
|
+
reader.releaseLock();
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
async function readPath(path, maxBytes) {
|
|
1188
|
+
const fs = await loadFs();
|
|
1189
|
+
if (!fs) {
|
|
1190
|
+
throw new InputError("FILE_NOT_READABLE", "file paths need a runtime with a file system; pass bytes, a Blob or a stream");
|
|
1191
|
+
}
|
|
1192
|
+
let info;
|
|
1193
|
+
try {
|
|
1194
|
+
info = await fs.stat(path);
|
|
1195
|
+
} catch (cause) {
|
|
1196
|
+
throw new InputError("FILE_NOT_READABLE", `cannot read ${String(path)}`, { cause });
|
|
1197
|
+
}
|
|
1198
|
+
if (!info.isFile())
|
|
1199
|
+
throw new InputError("FILE_NOT_READABLE", `not a file: ${String(path)}`);
|
|
1200
|
+
if (info.size > maxBytes)
|
|
1201
|
+
throw tooLarge(info.size);
|
|
1202
|
+
try {
|
|
1203
|
+
return await fs.readFile(path);
|
|
1204
|
+
} catch (cause) {
|
|
1205
|
+
throw new InputError("FILE_NOT_READABLE", `cannot read ${String(path)}`, { cause });
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
async function readBytes(input, maxBytes) {
|
|
1209
|
+
if (typeof input === "string" || input instanceof URL)
|
|
1210
|
+
return readPath(input, maxBytes);
|
|
1211
|
+
if (input instanceof Uint8Array)
|
|
1212
|
+
return input;
|
|
1213
|
+
if (input instanceof ArrayBuffer)
|
|
1214
|
+
return new Uint8Array(input);
|
|
1215
|
+
if (typeof Blob !== "undefined" && input instanceof Blob) {
|
|
1216
|
+
if (input.size > maxBytes)
|
|
1217
|
+
throw tooLarge(input.size);
|
|
1218
|
+
return new Uint8Array(await input.arrayBuffer());
|
|
1219
|
+
}
|
|
1220
|
+
if (typeof ReadableStream !== "undefined" && input instanceof ReadableStream) {
|
|
1221
|
+
return collect(readStream(input), maxBytes);
|
|
1222
|
+
}
|
|
1223
|
+
if (input && typeof input[Symbol.asyncIterator] === "function") {
|
|
1224
|
+
return collect(input, maxBytes);
|
|
1225
|
+
}
|
|
1226
|
+
throw new InputError("INVALID_ARGUMENT", "file must be a path, URL, Uint8Array, ArrayBuffer, Blob or stream");
|
|
1227
|
+
}
|
|
1228
|
+
async function prepareFile(input, maxBytes = MAX_IMAGE_BYTES) {
|
|
1229
|
+
const raw = await readBytes(input, maxBytes);
|
|
1230
|
+
if (raw.byteLength === 0)
|
|
1231
|
+
throw new InputError("EMPTY_FILE", "file is empty");
|
|
1232
|
+
if (raw.byteLength > maxBytes)
|
|
1233
|
+
throw tooLarge(raw.byteLength);
|
|
1234
|
+
const kind = sniffImageType(raw);
|
|
1235
|
+
if (!kind) {
|
|
1236
|
+
throw new InputError("UNSUPPORTED_FILE_TYPE", "file is not a JPEG, PNG, GIF or WebP image");
|
|
1237
|
+
}
|
|
1238
|
+
return { bytes: new Uint8Array(raw), contentType: kind.type, filename: `slip.${kind.ext}` };
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
// src/resources/verify.ts
|
|
1242
|
+
var OPTION_KEYS = ["remark", "matchAccount", "matchAmount", "checkDuplicate"];
|
|
1243
|
+
function verifyFields(options) {
|
|
1244
|
+
return defined(options, OPTION_KEYS);
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
class Verify {
|
|
1248
|
+
#t;
|
|
1249
|
+
constructor(transport) {
|
|
1250
|
+
this.#t = transport;
|
|
1251
|
+
}
|
|
1252
|
+
async bankByPayload(payload, options) {
|
|
1253
|
+
requireString(payload, "payload");
|
|
1254
|
+
return call(this.#t, "BankSlipResult", {
|
|
1255
|
+
...requestOptions(options),
|
|
1256
|
+
api: "v2",
|
|
1257
|
+
method: "POST",
|
|
1258
|
+
path: "/verify/bank",
|
|
1259
|
+
json: { payload, ...verifyFields(options) },
|
|
1260
|
+
retry: "billed"
|
|
1261
|
+
});
|
|
1262
|
+
}
|
|
1263
|
+
async bankByImage(file, options) {
|
|
1264
|
+
const prepared = await prepareFile(file);
|
|
1265
|
+
return call(this.#t, "BankSlipResult", {
|
|
1266
|
+
...requestOptions(options),
|
|
1267
|
+
api: "v2",
|
|
1268
|
+
method: "POST",
|
|
1269
|
+
path: "/verify/bank",
|
|
1270
|
+
form: imageForm("image", prepared, verifyFields(options)),
|
|
1271
|
+
retry: "billed"
|
|
1272
|
+
});
|
|
1273
|
+
}
|
|
1274
|
+
async bankByBase64(base64, options) {
|
|
1275
|
+
requireString(base64, "base64");
|
|
1276
|
+
return call(this.#t, "BankSlipResult", {
|
|
1277
|
+
...requestOptions(options),
|
|
1278
|
+
api: "v2",
|
|
1279
|
+
method: "POST",
|
|
1280
|
+
path: "/verify/bank",
|
|
1281
|
+
json: { base64, ...verifyFields(options) },
|
|
1282
|
+
retry: "billed"
|
|
1283
|
+
});
|
|
1284
|
+
}
|
|
1285
|
+
async bankByUrl(url, options) {
|
|
1286
|
+
requireString(url, "url");
|
|
1287
|
+
return call(this.#t, "BankSlipResult", {
|
|
1288
|
+
...requestOptions(options),
|
|
1289
|
+
api: "v2",
|
|
1290
|
+
method: "POST",
|
|
1291
|
+
path: "/verify/bank",
|
|
1292
|
+
json: { url, ...verifyFields(options) },
|
|
1293
|
+
retry: "billed"
|
|
1294
|
+
});
|
|
1295
|
+
}
|
|
1296
|
+
async truewalletByPayload(payload, options) {
|
|
1297
|
+
requireString(payload, "payload");
|
|
1298
|
+
return call(this.#t, "TrueWalletResult", {
|
|
1299
|
+
...requestOptions(options),
|
|
1300
|
+
api: "v2",
|
|
1301
|
+
method: "POST",
|
|
1302
|
+
path: "/verify/truewallet",
|
|
1303
|
+
json: { payload, ...verifyFields(options) },
|
|
1304
|
+
retry: "billed"
|
|
1305
|
+
});
|
|
1306
|
+
}
|
|
1307
|
+
async truewalletByImage(file, options) {
|
|
1308
|
+
const prepared = await prepareFile(file);
|
|
1309
|
+
return call(this.#t, "TrueWalletResult", {
|
|
1310
|
+
...requestOptions(options),
|
|
1311
|
+
api: "v2",
|
|
1312
|
+
method: "POST",
|
|
1313
|
+
path: "/verify/truewallet",
|
|
1314
|
+
form: imageForm("image", prepared, verifyFields(options)),
|
|
1315
|
+
retry: "billed"
|
|
1316
|
+
});
|
|
1317
|
+
}
|
|
1318
|
+
async truewalletByBase64(base64, options) {
|
|
1319
|
+
requireString(base64, "base64");
|
|
1320
|
+
return call(this.#t, "TrueWalletResult", {
|
|
1321
|
+
...requestOptions(options),
|
|
1322
|
+
api: "v2",
|
|
1323
|
+
method: "POST",
|
|
1324
|
+
path: "/verify/truewallet",
|
|
1325
|
+
json: { base64, ...verifyFields(options) },
|
|
1326
|
+
retry: "billed"
|
|
1327
|
+
});
|
|
1328
|
+
}
|
|
1329
|
+
async truewalletByUrl(url, options) {
|
|
1330
|
+
requireString(url, "url");
|
|
1331
|
+
return call(this.#t, "TrueWalletResult", {
|
|
1332
|
+
...requestOptions(options),
|
|
1333
|
+
api: "v2",
|
|
1334
|
+
method: "POST",
|
|
1335
|
+
path: "/verify/truewallet",
|
|
1336
|
+
json: { url, ...verifyFields(options) },
|
|
1337
|
+
retry: "billed"
|
|
1338
|
+
});
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
// src/resources/jobs.ts
|
|
1343
|
+
var BATCH_MAX = 100;
|
|
1344
|
+
var SLIP_KEYS = ["payload", "remark", "matchAccount", "matchAmount", "checkDuplicate"];
|
|
1345
|
+
|
|
1346
|
+
class Jobs {
|
|
1347
|
+
#t;
|
|
1348
|
+
#sleep;
|
|
1349
|
+
#timeout;
|
|
1350
|
+
constructor(transport) {
|
|
1351
|
+
this.#t = transport;
|
|
1352
|
+
this.#sleep = transport.config.sleep;
|
|
1353
|
+
this.#timeout = transport.config.timeout;
|
|
1354
|
+
}
|
|
1355
|
+
async submitBank(payload, options) {
|
|
1356
|
+
requireString(payload, "payload");
|
|
1357
|
+
const json = { payload, ...verifyFields(options) };
|
|
1358
|
+
if (options?.callbackUrl !== undefined)
|
|
1359
|
+
json.callbackUrl = options.callbackUrl;
|
|
1360
|
+
return call(this.#t, "JobSubmission", {
|
|
1361
|
+
...requestOptions(options),
|
|
1362
|
+
api: "v2",
|
|
1363
|
+
method: "POST",
|
|
1364
|
+
path: "/verify/bank/async",
|
|
1365
|
+
json,
|
|
1366
|
+
retry: "billed"
|
|
1367
|
+
});
|
|
1368
|
+
}
|
|
1369
|
+
async submitBankBatch(slips, options) {
|
|
1370
|
+
if (!Array.isArray(slips) || slips.length === 0) {
|
|
1371
|
+
throw new InputError("EMPTY_BATCH", "slips must contain at least one slip");
|
|
1372
|
+
}
|
|
1373
|
+
if (slips.length > BATCH_MAX) {
|
|
1374
|
+
throw new InputError("BATCH_TOO_LARGE", `a batch takes at most ${BATCH_MAX} slips; use submitBankMany for more`);
|
|
1375
|
+
}
|
|
1376
|
+
for (const slip of slips)
|
|
1377
|
+
requireString(slip?.payload, "slip payload");
|
|
1378
|
+
const json = {};
|
|
1379
|
+
if (options?.callbackUrl !== undefined)
|
|
1380
|
+
json.callbackUrl = options.callbackUrl;
|
|
1381
|
+
json.slips = slips.map((slip) => defined(slip, SLIP_KEYS));
|
|
1382
|
+
return call(this.#t, "BatchSubmission", {
|
|
1383
|
+
...requestOptions(options),
|
|
1384
|
+
api: "v2",
|
|
1385
|
+
method: "POST",
|
|
1386
|
+
path: "/verify/bank/batch",
|
|
1387
|
+
json,
|
|
1388
|
+
retry: "billed"
|
|
1389
|
+
});
|
|
1390
|
+
}
|
|
1391
|
+
async submitBankMany(slips, options) {
|
|
1392
|
+
if (!Array.isArray(slips) || slips.length === 0) {
|
|
1393
|
+
throw new InputError("EMPTY_BATCH", "slips must contain at least one slip");
|
|
1394
|
+
}
|
|
1395
|
+
const submitted = [];
|
|
1396
|
+
for (let start = 0, chunk = 0;start < slips.length; start += BATCH_MAX, chunk++) {
|
|
1397
|
+
try {
|
|
1398
|
+
submitted.push(await this.submitBankBatch(slips.slice(start, start + BATCH_MAX), options));
|
|
1399
|
+
} catch (cause) {
|
|
1400
|
+
throw new BatchSubmitError(submitted, chunk, cause);
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
return submitted;
|
|
1404
|
+
}
|
|
1405
|
+
async get(jobId, options) {
|
|
1406
|
+
requireString(jobId, "jobId");
|
|
1407
|
+
return call(this.#t, "Job", {
|
|
1408
|
+
...requestOptions(options),
|
|
1409
|
+
api: "v2",
|
|
1410
|
+
method: "GET",
|
|
1411
|
+
path: `/verify/bank/jobs/${encodeURIComponent(jobId)}`,
|
|
1412
|
+
retry: "safe"
|
|
1413
|
+
});
|
|
1414
|
+
}
|
|
1415
|
+
async waitForJob(jobId, options) {
|
|
1416
|
+
requireString(jobId, "jobId");
|
|
1417
|
+
const interval = Math.max(500, options?.interval ?? 2000);
|
|
1418
|
+
const timeout = options?.timeout ?? 600000;
|
|
1419
|
+
if (!Number.isFinite(timeout) || timeout < 0) {
|
|
1420
|
+
throw new InputError("INVALID_ARGUMENT", "timeout must be a number >= 0");
|
|
1421
|
+
}
|
|
1422
|
+
const caller = options?.signal;
|
|
1423
|
+
caller?.throwIfAborted();
|
|
1424
|
+
const deadline = Date.now() + timeout;
|
|
1425
|
+
let last = null;
|
|
1426
|
+
const expired = () => new JobWaitTimeoutError(`job ${jobId} ${last ? `still ${last.status}` : "not read"} after ${timeout} ms`, last);
|
|
1427
|
+
const budget = new AbortController;
|
|
1428
|
+
const reason = new Error("waitForJob deadline");
|
|
1429
|
+
const timer = setTimeout(() => budget.abort(reason), timeout);
|
|
1430
|
+
const onAbort = () => budget.abort(caller?.reason);
|
|
1431
|
+
caller?.addEventListener("abort", onAbort, { once: true });
|
|
1432
|
+
const deadlinePassed = () => budget.signal.reason === reason && !caller?.aborted;
|
|
1433
|
+
const stopped = new Promise((_, reject) => {
|
|
1434
|
+
budget.signal.addEventListener("abort", () => reject(budget.signal.reason), {
|
|
1435
|
+
once: true
|
|
1436
|
+
});
|
|
1437
|
+
});
|
|
1438
|
+
stopped.catch(() => {});
|
|
1439
|
+
try {
|
|
1440
|
+
while (true) {
|
|
1441
|
+
const left = deadline - Date.now();
|
|
1442
|
+
if (left <= 0)
|
|
1443
|
+
throw expired();
|
|
1444
|
+
const capped = left < this.#timeout;
|
|
1445
|
+
let job;
|
|
1446
|
+
try {
|
|
1447
|
+
job = await Promise.race([
|
|
1448
|
+
this.get(jobId, {
|
|
1449
|
+
signal: budget.signal,
|
|
1450
|
+
timeout: Math.max(1, Math.min(this.#timeout, left))
|
|
1451
|
+
}),
|
|
1452
|
+
stopped
|
|
1453
|
+
]);
|
|
1454
|
+
} catch (error) {
|
|
1455
|
+
if (deadlinePassed())
|
|
1456
|
+
throw expired();
|
|
1457
|
+
if (capped && error instanceof RequestTimeoutError && !caller?.aborted) {
|
|
1458
|
+
throw expired();
|
|
1459
|
+
}
|
|
1460
|
+
throw error;
|
|
1461
|
+
}
|
|
1462
|
+
if (Date.now() >= deadline)
|
|
1463
|
+
throw expired();
|
|
1464
|
+
last = job;
|
|
1465
|
+
if (job.status === "done" || job.status === "failed")
|
|
1466
|
+
return job;
|
|
1467
|
+
const wait = Math.min(interval, deadline - Date.now());
|
|
1468
|
+
if (wait <= 0)
|
|
1469
|
+
throw expired();
|
|
1470
|
+
try {
|
|
1471
|
+
await Promise.race([this.#sleep(wait, budget.signal), stopped]);
|
|
1472
|
+
} catch (error) {
|
|
1473
|
+
if (deadlinePassed())
|
|
1474
|
+
throw expired();
|
|
1475
|
+
throw error;
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
} finally {
|
|
1479
|
+
clearTimeout(timer);
|
|
1480
|
+
caller?.removeEventListener("abort", onAbort);
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
// src/resources/v1.ts
|
|
1486
|
+
function decodeBase64(text) {
|
|
1487
|
+
const binary = atob(text);
|
|
1488
|
+
const out = new Uint8Array(binary.length);
|
|
1489
|
+
for (let i = 0;i < binary.length; i++)
|
|
1490
|
+
out[i] = binary.charCodeAt(i);
|
|
1491
|
+
return out;
|
|
1492
|
+
}
|
|
1493
|
+
function boolString(value) {
|
|
1494
|
+
return value ? "true" : "false";
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
class V1 {
|
|
1498
|
+
#t;
|
|
1499
|
+
constructor(transport) {
|
|
1500
|
+
this.#t = transport;
|
|
1501
|
+
}
|
|
1502
|
+
async getMe(options) {
|
|
1503
|
+
return call(this.#t, "V1Me", {
|
|
1504
|
+
...requestOptions(options),
|
|
1505
|
+
api: "v1",
|
|
1506
|
+
method: "GET",
|
|
1507
|
+
path: "/me",
|
|
1508
|
+
retry: "safe"
|
|
1509
|
+
});
|
|
1510
|
+
}
|
|
1511
|
+
async verifyBankByPayload(payload, options) {
|
|
1512
|
+
requireString(payload, "payload");
|
|
1513
|
+
return call(this.#t, "BankSlip", {
|
|
1514
|
+
...requestOptions(options),
|
|
1515
|
+
api: "v1",
|
|
1516
|
+
method: "GET",
|
|
1517
|
+
path: "/verify",
|
|
1518
|
+
query: {
|
|
1519
|
+
payload,
|
|
1520
|
+
checkDuplicate: options?.checkDuplicate === undefined ? undefined : boolString(options.checkDuplicate)
|
|
1521
|
+
},
|
|
1522
|
+
retry: "billed",
|
|
1523
|
+
duplicateSlip: "BankSlip"
|
|
1524
|
+
});
|
|
1525
|
+
}
|
|
1526
|
+
async verifyBankByImage(file, options) {
|
|
1527
|
+
const prepared = await prepareFile(file);
|
|
1528
|
+
const fields = {};
|
|
1529
|
+
if (options?.checkDuplicate !== undefined) {
|
|
1530
|
+
fields.checkDuplicate = boolString(options.checkDuplicate);
|
|
1531
|
+
}
|
|
1532
|
+
return call(this.#t, "BankSlip", {
|
|
1533
|
+
...requestOptions(options),
|
|
1534
|
+
api: "v1",
|
|
1535
|
+
method: "POST",
|
|
1536
|
+
path: "/verify",
|
|
1537
|
+
form: imageForm("file", prepared, fields),
|
|
1538
|
+
retry: "billed",
|
|
1539
|
+
duplicateSlip: "BankSlip"
|
|
1540
|
+
});
|
|
1541
|
+
}
|
|
1542
|
+
async verifyBankByBase64(base64, options) {
|
|
1543
|
+
requireString(base64, "base64");
|
|
1544
|
+
const json = { image: base64 };
|
|
1545
|
+
if (options?.checkDuplicate !== undefined)
|
|
1546
|
+
json.checkDuplicate = options.checkDuplicate;
|
|
1547
|
+
return call(this.#t, "BankSlip", {
|
|
1548
|
+
...requestOptions(options),
|
|
1549
|
+
api: "v1",
|
|
1550
|
+
method: "POST",
|
|
1551
|
+
path: "/verify",
|
|
1552
|
+
json,
|
|
1553
|
+
retry: "billed",
|
|
1554
|
+
duplicateSlip: "BankSlip"
|
|
1555
|
+
});
|
|
1556
|
+
}
|
|
1557
|
+
async verifyBankByUrl(url, options) {
|
|
1558
|
+
requireString(url, "url");
|
|
1559
|
+
const json = { url };
|
|
1560
|
+
if (options?.checkDuplicate !== undefined)
|
|
1561
|
+
json.checkDuplicate = options.checkDuplicate;
|
|
1562
|
+
return call(this.#t, "BankSlip", {
|
|
1563
|
+
...requestOptions(options),
|
|
1564
|
+
api: "v1",
|
|
1565
|
+
method: "POST",
|
|
1566
|
+
path: "/verify",
|
|
1567
|
+
json,
|
|
1568
|
+
retry: "billed",
|
|
1569
|
+
duplicateSlip: "BankSlip"
|
|
1570
|
+
});
|
|
1571
|
+
}
|
|
1572
|
+
async verifyTruemoneyByPayload(payload, options) {
|
|
1573
|
+
requireString(payload, "payload");
|
|
1574
|
+
const json = { payload };
|
|
1575
|
+
if (options?.checkDuplicate !== undefined)
|
|
1576
|
+
json.checkDuplicate = options.checkDuplicate;
|
|
1577
|
+
return call(this.#t, "TrueWalletSlip", {
|
|
1578
|
+
...requestOptions(options),
|
|
1579
|
+
api: "v1",
|
|
1580
|
+
method: "POST",
|
|
1581
|
+
path: "/verify/truewallet",
|
|
1582
|
+
json,
|
|
1583
|
+
retry: "billed",
|
|
1584
|
+
duplicateSlip: "TrueWalletSlip"
|
|
1585
|
+
});
|
|
1586
|
+
}
|
|
1587
|
+
async verifyTruemoneyByImage(file, options) {
|
|
1588
|
+
const prepared = await prepareFile(file);
|
|
1589
|
+
const fields = {};
|
|
1590
|
+
if (options?.checkDuplicate !== undefined) {
|
|
1591
|
+
fields.checkDuplicate = boolString(options.checkDuplicate);
|
|
1592
|
+
}
|
|
1593
|
+
return call(this.#t, "TrueWalletSlip", {
|
|
1594
|
+
...requestOptions(options),
|
|
1595
|
+
api: "v1",
|
|
1596
|
+
method: "POST",
|
|
1597
|
+
path: "/verify/truewallet",
|
|
1598
|
+
form: imageForm("file", prepared, fields),
|
|
1599
|
+
retry: "billed",
|
|
1600
|
+
duplicateSlip: "TrueWalletSlip"
|
|
1601
|
+
});
|
|
1602
|
+
}
|
|
1603
|
+
async generateQr(request, options) {
|
|
1604
|
+
if (!request || typeof request !== "object") {
|
|
1605
|
+
throw new InputError("INVALID_ARGUMENT", "request must be an object with a type");
|
|
1606
|
+
}
|
|
1607
|
+
const result = await call(this.#t, "QrCode", {
|
|
1608
|
+
...requestOptions(options),
|
|
1609
|
+
api: "v1",
|
|
1610
|
+
method: "POST",
|
|
1611
|
+
path: "/qr/generate",
|
|
1612
|
+
json: request,
|
|
1613
|
+
retry: "safe"
|
|
1614
|
+
});
|
|
1615
|
+
Object.defineProperty(result, "imageBytes", {
|
|
1616
|
+
value: () => decodeBase64(result.image),
|
|
1617
|
+
enumerable: false
|
|
1618
|
+
});
|
|
1619
|
+
return result;
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
// src/version.ts
|
|
1624
|
+
var VERSION = "1.1.0";
|
|
1625
|
+
|
|
1626
|
+
// src/client.ts
|
|
1627
|
+
function keyFromFile(path) {
|
|
1628
|
+
let cached;
|
|
1629
|
+
return () => {
|
|
1630
|
+
cached ??= (async () => {
|
|
1631
|
+
const fs = await loadFs();
|
|
1632
|
+
if (!fs) {
|
|
1633
|
+
throw new InputError("FILE_NOT_READABLE", `${settings.env.apiKeyFile} needs a runtime with a file system`);
|
|
1634
|
+
}
|
|
1635
|
+
let text;
|
|
1636
|
+
try {
|
|
1637
|
+
text = new TextDecoder().decode(await fs.readFile(path));
|
|
1638
|
+
} catch (cause) {
|
|
1639
|
+
throw new InputError("FILE_NOT_READABLE", `cannot read ${settings.env.apiKeyFile}`, {
|
|
1640
|
+
cause
|
|
1641
|
+
});
|
|
1642
|
+
}
|
|
1643
|
+
const key = text.trim();
|
|
1644
|
+
if (!key)
|
|
1645
|
+
throw new InputError("INVALID_ARGUMENT", `${settings.env.apiKeyFile} is empty`);
|
|
1646
|
+
return key;
|
|
1647
|
+
})();
|
|
1648
|
+
cached.catch(() => {
|
|
1649
|
+
cached = undefined;
|
|
1650
|
+
});
|
|
1651
|
+
return cached;
|
|
1652
|
+
};
|
|
1653
|
+
}
|
|
1654
|
+
function checkNumber(value, name, min) {
|
|
1655
|
+
if (value !== undefined && (!Number.isFinite(value) || value < min)) {
|
|
1656
|
+
throw new InputError("INVALID_ARGUMENT", `${name} must be a number >= ${min}`);
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
|
|
1660
|
+
class Client {
|
|
1661
|
+
verify;
|
|
1662
|
+
banks;
|
|
1663
|
+
bankAccounts;
|
|
1664
|
+
jobs;
|
|
1665
|
+
v1;
|
|
1666
|
+
v2BaseUrl;
|
|
1667
|
+
v1BaseUrl;
|
|
1668
|
+
timeout;
|
|
1669
|
+
maxRetries;
|
|
1670
|
+
#transport;
|
|
1671
|
+
constructor(options = {}) {
|
|
1672
|
+
checkNumber(options.timeout, "timeout", 1);
|
|
1673
|
+
checkNumber(options.maxRetries, "maxRetries", 0);
|
|
1674
|
+
let apiKey;
|
|
1675
|
+
const key = options.apiKey ?? readEnv(settings.env.apiKey);
|
|
1676
|
+
if (key !== undefined) {
|
|
1677
|
+
if (typeof key !== "string" || key.trim() === "") {
|
|
1678
|
+
throw new InputError("INVALID_ARGUMENT", "apiKey must be a non-empty string");
|
|
1679
|
+
}
|
|
1680
|
+
const value = key.trim();
|
|
1681
|
+
apiKey = () => Promise.resolve(value);
|
|
1682
|
+
} else {
|
|
1683
|
+
const file = readEnv(settings.env.apiKeyFile);
|
|
1684
|
+
if (!file) {
|
|
1685
|
+
throw new InputError("INVALID_ARGUMENT", `no API key: pass apiKey or set ${settings.env.apiKey} or ${settings.env.apiKeyFile}`);
|
|
1686
|
+
}
|
|
1687
|
+
apiKey = keyFromFile(file);
|
|
1688
|
+
}
|
|
1689
|
+
if (!options.fetch && typeof globalThis.fetch !== "function") {
|
|
1690
|
+
throw new InputError("INVALID_ARGUMENT", "no fetch: pass options.fetch");
|
|
1691
|
+
}
|
|
1692
|
+
this.v2BaseUrl = options.v2BaseUrl ?? readEnv(settings.env.v2BaseUrl) ?? settings.baseUrls.v2;
|
|
1693
|
+
this.v1BaseUrl = options.v1BaseUrl ?? readEnv(settings.env.v1BaseUrl) ?? settings.baseUrls.v1;
|
|
1694
|
+
this.timeout = options.timeout ?? 30000;
|
|
1695
|
+
this.maxRetries = Math.floor(options.maxRetries ?? 2);
|
|
1696
|
+
this.#transport = new Transport({
|
|
1697
|
+
v1BaseUrl: this.v1BaseUrl,
|
|
1698
|
+
v2BaseUrl: this.v2BaseUrl,
|
|
1699
|
+
timeout: this.timeout,
|
|
1700
|
+
maxRetries: this.maxRetries,
|
|
1701
|
+
userAgent: `${settings.userAgentProduct}/${VERSION} ${runtimeToken()}`,
|
|
1702
|
+
fetch: options.fetch ?? ((input, init) => globalThis.fetch(input, init)),
|
|
1703
|
+
sleep: options.sleep ?? sleep,
|
|
1704
|
+
random: options.random ?? Math.random,
|
|
1705
|
+
apiKey
|
|
1706
|
+
});
|
|
1707
|
+
this.verify = new Verify(this.#transport);
|
|
1708
|
+
this.banks = new Banks(this.#transport);
|
|
1709
|
+
this.bankAccounts = new BankAccounts(this.#transport);
|
|
1710
|
+
this.jobs = new Jobs(this.#transport);
|
|
1711
|
+
this.v1 = new V1(this.#transport);
|
|
1712
|
+
}
|
|
1713
|
+
get userAgent() {
|
|
1714
|
+
return this.#transport.config.userAgent;
|
|
1715
|
+
}
|
|
1716
|
+
async getInfo(options) {
|
|
1717
|
+
return call(this.#transport, "Info", {
|
|
1718
|
+
...requestOptions(options),
|
|
1719
|
+
api: "v2",
|
|
1720
|
+
method: "GET",
|
|
1721
|
+
path: "/info",
|
|
1722
|
+
retry: "safe"
|
|
1723
|
+
});
|
|
1724
|
+
}
|
|
1725
|
+
toJSON() {
|
|
1726
|
+
return {
|
|
1727
|
+
v2BaseUrl: this.v2BaseUrl,
|
|
1728
|
+
v1BaseUrl: this.v1BaseUrl,
|
|
1729
|
+
timeout: this.timeout,
|
|
1730
|
+
maxRetries: this.maxRetries
|
|
1731
|
+
};
|
|
1732
|
+
}
|
|
1733
|
+
toString() {
|
|
1734
|
+
return `Client(${this.v2BaseUrl})`;
|
|
1735
|
+
}
|
|
1736
|
+
[Symbol.for("nodejs.util.inspect.custom")]() {
|
|
1737
|
+
return `Client ${JSON.stringify(this.toJSON())}`;
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
// src/core/sha256.ts
|
|
1741
|
+
var K = new Uint32Array([
|
|
1742
|
+
1116352408,
|
|
1743
|
+
1899447441,
|
|
1744
|
+
3049323471,
|
|
1745
|
+
3921009573,
|
|
1746
|
+
961987163,
|
|
1747
|
+
1508970993,
|
|
1748
|
+
2453635748,
|
|
1749
|
+
2870763221,
|
|
1750
|
+
3624381080,
|
|
1751
|
+
310598401,
|
|
1752
|
+
607225278,
|
|
1753
|
+
1426881987,
|
|
1754
|
+
1925078388,
|
|
1755
|
+
2162078206,
|
|
1756
|
+
2614888103,
|
|
1757
|
+
3248222580,
|
|
1758
|
+
3835390401,
|
|
1759
|
+
4022224774,
|
|
1760
|
+
264347078,
|
|
1761
|
+
604807628,
|
|
1762
|
+
770255983,
|
|
1763
|
+
1249150122,
|
|
1764
|
+
1555081692,
|
|
1765
|
+
1996064986,
|
|
1766
|
+
2554220882,
|
|
1767
|
+
2821834349,
|
|
1768
|
+
2952996808,
|
|
1769
|
+
3210313671,
|
|
1770
|
+
3336571891,
|
|
1771
|
+
3584528711,
|
|
1772
|
+
113926993,
|
|
1773
|
+
338241895,
|
|
1774
|
+
666307205,
|
|
1775
|
+
773529912,
|
|
1776
|
+
1294757372,
|
|
1777
|
+
1396182291,
|
|
1778
|
+
1695183700,
|
|
1779
|
+
1986661051,
|
|
1780
|
+
2177026350,
|
|
1781
|
+
2456956037,
|
|
1782
|
+
2730485921,
|
|
1783
|
+
2820302411,
|
|
1784
|
+
3259730800,
|
|
1785
|
+
3345764771,
|
|
1786
|
+
3516065817,
|
|
1787
|
+
3600352804,
|
|
1788
|
+
4094571909,
|
|
1789
|
+
275423344,
|
|
1790
|
+
430227734,
|
|
1791
|
+
506948616,
|
|
1792
|
+
659060556,
|
|
1793
|
+
883997877,
|
|
1794
|
+
958139571,
|
|
1795
|
+
1322822218,
|
|
1796
|
+
1537002063,
|
|
1797
|
+
1747873779,
|
|
1798
|
+
1955562222,
|
|
1799
|
+
2024104815,
|
|
1800
|
+
2227730452,
|
|
1801
|
+
2361852424,
|
|
1802
|
+
2428436474,
|
|
1803
|
+
2756734187,
|
|
1804
|
+
3204031479,
|
|
1805
|
+
3329325298
|
|
1806
|
+
]);
|
|
1807
|
+
function sha256(data) {
|
|
1808
|
+
const bitLength = data.length * 8;
|
|
1809
|
+
const padded = new Uint8Array(data.length + 9 + 63 >> 6 << 6 >>> 0);
|
|
1810
|
+
padded.set(data);
|
|
1811
|
+
padded[data.length] = 128;
|
|
1812
|
+
const view = new DataView(padded.buffer);
|
|
1813
|
+
view.setUint32(padded.length - 8, Math.floor(bitLength / 4294967296));
|
|
1814
|
+
view.setUint32(padded.length - 4, bitLength >>> 0);
|
|
1815
|
+
const h = new Uint32Array([
|
|
1816
|
+
1779033703,
|
|
1817
|
+
3144134277,
|
|
1818
|
+
1013904242,
|
|
1819
|
+
2773480762,
|
|
1820
|
+
1359893119,
|
|
1821
|
+
2600822924,
|
|
1822
|
+
528734635,
|
|
1823
|
+
1541459225
|
|
1824
|
+
]);
|
|
1825
|
+
const w = new Uint32Array(64);
|
|
1826
|
+
for (let offset = 0;offset < padded.length; offset += 64) {
|
|
1827
|
+
for (let i = 0;i < 16; i++)
|
|
1828
|
+
w[i] = view.getUint32(offset + i * 4);
|
|
1829
|
+
for (let i = 16;i < 64; i++) {
|
|
1830
|
+
const w15 = w[i - 15];
|
|
1831
|
+
const w2 = w[i - 2];
|
|
1832
|
+
const s0 = (w15 >>> 7 | w15 << 25) ^ (w15 >>> 18 | w15 << 14) ^ w15 >>> 3;
|
|
1833
|
+
const s1 = (w2 >>> 17 | w2 << 15) ^ (w2 >>> 19 | w2 << 13) ^ w2 >>> 10;
|
|
1834
|
+
w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
|
|
1835
|
+
}
|
|
1836
|
+
let a = h[0];
|
|
1837
|
+
let b = h[1];
|
|
1838
|
+
let c = h[2];
|
|
1839
|
+
let d = h[3];
|
|
1840
|
+
let e = h[4];
|
|
1841
|
+
let f = h[5];
|
|
1842
|
+
let g = h[6];
|
|
1843
|
+
let hh = h[7];
|
|
1844
|
+
for (let i = 0;i < 64; i++) {
|
|
1845
|
+
const S1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7);
|
|
1846
|
+
const ch = e & f ^ ~e & g;
|
|
1847
|
+
const t1 = hh + S1 + ch + K[i] + w[i] >>> 0;
|
|
1848
|
+
const S0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10);
|
|
1849
|
+
const maj = a & b ^ a & c ^ b & c;
|
|
1850
|
+
const t2 = S0 + maj >>> 0;
|
|
1851
|
+
hh = g;
|
|
1852
|
+
g = f;
|
|
1853
|
+
f = e;
|
|
1854
|
+
e = d + t1 >>> 0;
|
|
1855
|
+
d = c;
|
|
1856
|
+
c = b;
|
|
1857
|
+
b = a;
|
|
1858
|
+
a = t1 + t2 >>> 0;
|
|
1859
|
+
}
|
|
1860
|
+
h[0] = h[0] + a >>> 0;
|
|
1861
|
+
h[1] = h[1] + b >>> 0;
|
|
1862
|
+
h[2] = h[2] + c >>> 0;
|
|
1863
|
+
h[3] = h[3] + d >>> 0;
|
|
1864
|
+
h[4] = h[4] + e >>> 0;
|
|
1865
|
+
h[5] = h[5] + f >>> 0;
|
|
1866
|
+
h[6] = h[6] + g >>> 0;
|
|
1867
|
+
h[7] = h[7] + hh >>> 0;
|
|
1868
|
+
}
|
|
1869
|
+
const out = new Uint8Array(32);
|
|
1870
|
+
const outView = new DataView(out.buffer);
|
|
1871
|
+
for (let i = 0;i < 8; i++)
|
|
1872
|
+
outView.setUint32(i * 4, h[i]);
|
|
1873
|
+
return out;
|
|
1874
|
+
}
|
|
1875
|
+
function hmacSha256(key, message) {
|
|
1876
|
+
const block = new Uint8Array(64);
|
|
1877
|
+
block.set(key.length > 64 ? sha256(key) : key);
|
|
1878
|
+
const inner = new Uint8Array(64 + message.length);
|
|
1879
|
+
const outer = new Uint8Array(64 + 32);
|
|
1880
|
+
for (let i = 0;i < 64; i++) {
|
|
1881
|
+
inner[i] = block[i] ^ 54;
|
|
1882
|
+
outer[i] = block[i] ^ 92;
|
|
1883
|
+
}
|
|
1884
|
+
inner.set(message, 64);
|
|
1885
|
+
outer.set(sha256(inner), 64);
|
|
1886
|
+
return sha256(outer);
|
|
1887
|
+
}
|
|
1888
|
+
function toHex(bytes) {
|
|
1889
|
+
let out = "";
|
|
1890
|
+
for (const byte of bytes)
|
|
1891
|
+
out += byte.toString(16).padStart(2, "0");
|
|
1892
|
+
return out;
|
|
1893
|
+
}
|
|
1894
|
+
|
|
1895
|
+
// src/webhooks.ts
|
|
1896
|
+
var WEBHOOK_SIGNATURE_HEADER = settings.webhook.signatureHeader;
|
|
1897
|
+
var PREFIX = settings.webhook.signaturePrefix;
|
|
1898
|
+
var SIGNATURE = /^[0-9a-f]{64}$/;
|
|
1899
|
+
function toBytes(body) {
|
|
1900
|
+
if (typeof body === "string")
|
|
1901
|
+
return new TextEncoder().encode(body);
|
|
1902
|
+
if (body instanceof ArrayBuffer)
|
|
1903
|
+
return new Uint8Array(body);
|
|
1904
|
+
if (body instanceof Uint8Array)
|
|
1905
|
+
return body;
|
|
1906
|
+
throw new InputError("INVALID_ARGUMENT", "webhook body must be a string or bytes");
|
|
1907
|
+
}
|
|
1908
|
+
function secretOrEnv(secret) {
|
|
1909
|
+
const value = secret ?? readEnv(settings.env.webhookSecret);
|
|
1910
|
+
if (!value) {
|
|
1911
|
+
throw new InputError("INVALID_ARGUMENT", `no webhook secret: pass one or set ${settings.env.webhookSecret}`);
|
|
1912
|
+
}
|
|
1913
|
+
return value;
|
|
1914
|
+
}
|
|
1915
|
+
function equalConstantTime(a, b) {
|
|
1916
|
+
if (a.length !== b.length)
|
|
1917
|
+
return false;
|
|
1918
|
+
let diff = 0;
|
|
1919
|
+
for (let i = 0;i < a.length; i++)
|
|
1920
|
+
diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
1921
|
+
return diff === 0;
|
|
1922
|
+
}
|
|
1923
|
+
function verifyWebhookSignature(rawBody, signatureHeader, secret) {
|
|
1924
|
+
const key = secretOrEnv(secret);
|
|
1925
|
+
const header = Array.isArray(signatureHeader) ? signatureHeader[0] : signatureHeader;
|
|
1926
|
+
if (typeof header !== "string" || !header.startsWith(PREFIX))
|
|
1927
|
+
return false;
|
|
1928
|
+
const given = header.slice(PREFIX.length);
|
|
1929
|
+
if (!SIGNATURE.test(given))
|
|
1930
|
+
return false;
|
|
1931
|
+
const expected = toHex(hmacSha256(new TextEncoder().encode(key), toBytes(rawBody)));
|
|
1932
|
+
return equalConstantTime(given, expected);
|
|
1933
|
+
}
|
|
1934
|
+
function parseWebhookEvent(rawBody) {
|
|
1935
|
+
const text = typeof rawBody === "string" ? rawBody : new TextDecoder().decode(toBytes(rawBody));
|
|
1936
|
+
let value;
|
|
1937
|
+
try {
|
|
1938
|
+
value = JSON.parse(text);
|
|
1939
|
+
} catch (cause) {
|
|
1940
|
+
throw new InputError("INVALID_ARGUMENT", "webhook body is not JSON", { cause });
|
|
1941
|
+
}
|
|
1942
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
1943
|
+
throw new InputError("INVALID_ARGUMENT", "webhook body is not a JSON object");
|
|
1944
|
+
}
|
|
1945
|
+
const fields = value;
|
|
1946
|
+
if (typeof fields.jobId !== "string" || typeof fields.status !== "string" || typeof fields.timestamp !== "string") {
|
|
1947
|
+
throw new InputError("INVALID_ARGUMENT", "webhook body must contain jobId, status and timestamp");
|
|
1948
|
+
}
|
|
1949
|
+
return parseModel("WebhookEvent", value);
|
|
1950
|
+
}
|
|
1951
|
+
function constructWebhookEvent(rawBody, signatureHeader, secret) {
|
|
1952
|
+
if (!verifyWebhookSignature(rawBody, signatureHeader, secret)) {
|
|
1953
|
+
throw new WebhookSignatureError(`webhook signature in ${WEBHOOK_SIGNATURE_HEADER} is missing or does not match`);
|
|
1954
|
+
}
|
|
1955
|
+
return parseWebhookEvent(rawBody);
|
|
1956
|
+
}
|
|
1957
|
+
export {
|
|
1958
|
+
ApiError,
|
|
1959
|
+
AuthenticationError,
|
|
1960
|
+
BATCH_MAX,
|
|
1961
|
+
BankAccountType,
|
|
1962
|
+
BankList,
|
|
1963
|
+
BatchSubmitError,
|
|
1964
|
+
Client,
|
|
1965
|
+
ConflictError,
|
|
1966
|
+
DuplicateSlipError,
|
|
1967
|
+
Client as EasySlip,
|
|
1968
|
+
EasySlipError,
|
|
1969
|
+
InputError,
|
|
1970
|
+
InvalidImageError,
|
|
1971
|
+
InvalidRequestError,
|
|
1972
|
+
InvalidUrlError,
|
|
1973
|
+
JobStatus,
|
|
1974
|
+
JobWaitTimeoutError,
|
|
1975
|
+
MAX_IMAGE_BYTES,
|
|
1976
|
+
MatchMode,
|
|
1977
|
+
MatchedAccountType,
|
|
1978
|
+
NetworkError,
|
|
1979
|
+
NotFoundError,
|
|
1980
|
+
PermissionDeniedError,
|
|
1981
|
+
QuotaExceededError,
|
|
1982
|
+
RateLimitError,
|
|
1983
|
+
RequestTimeoutError,
|
|
1984
|
+
ServerError,
|
|
1985
|
+
ServiceUnavailableError,
|
|
1986
|
+
SlipNotFoundError,
|
|
1987
|
+
SlipPendingError,
|
|
1988
|
+
VERSION,
|
|
1989
|
+
WEBHOOK_SIGNATURE_HEADER,
|
|
1990
|
+
WebhookSignatureError,
|
|
1991
|
+
constructWebhookEvent,
|
|
1992
|
+
parseModel,
|
|
1993
|
+
parseWebhookEvent,
|
|
1994
|
+
pick,
|
|
1995
|
+
shapes,
|
|
1996
|
+
verifyWebhookSignature
|
|
1997
|
+
};
|