@isroilov_an/paylov 0.0.1
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 +35 -0
- package/LICENSE +21 -0
- package/README.md +81 -0
- package/dist/client-DOu4B-bL.js +2576 -0
- package/dist/client-DOu4B-bL.js.map +1 -0
- package/dist/index.d.ts +393 -0
- package/dist/index.js +458 -0
- package/dist/index.js.map +1 -0
- package/dist/testing.d.ts +198 -0
- package/dist/testing.js +1079 -0
- package/dist/testing.js.map +1 -0
- package/dist/types-Bj9umT2M.d.ts +1620 -0
- package/docs/usage/INDEX.md +30 -0
- package/docs/usage/cards.md +69 -0
- package/docs/usage/checkout.md +30 -0
- package/docs/usage/errors.md +107 -0
- package/docs/usage/fiscalization.md +62 -0
- package/docs/usage/holds.md +82 -0
- package/docs/usage/money-and-time.md +45 -0
- package/docs/usage/onboarding.md +28 -0
- package/docs/usage/payments.md +57 -0
- package/docs/usage/setup.md +85 -0
- package/docs/usage/splits.md +46 -0
- package/docs/usage/testing.md +132 -0
- package/docs/usage/transactions.md +43 -0
- package/docs/usage/webhooks.md +168 -0
- package/package.json +86 -0
package/dist/testing.js
ADDED
|
@@ -0,0 +1,1079 @@
|
|
|
1
|
+
import { $ as tiyinToWireSum, B as decodeErrorDetails, C as WIRE_ACTIVITY_TYPES, E as ENDPOINTS, I as endpointName, L as isRetryableStatus, N as ENDPOINTS$9, S as ENDPOINTS$1, T as readTransactionLookup, Y as isRecord, a as minorUnitsOf, et as wireSumToTiyin, f as ENDPOINTS$6, g as ENDPOINTS$3, j as readParams, l as TRANSACTION_STATUS_BY_WIRE, m as ENDPOINTS$5, s as ENDPOINTS$8, t as ENDPOINTS$4, u as ENDPOINTS$7, v as HOLD_STATUS_BY_WIRE, x as ACTIVITY_TYPES, y as ENDPOINTS$2, z as isWireErrorCode } from "./client-DOu4B-bL.js";
|
|
2
|
+
// src/core/fake.ts
|
|
3
|
+
/**
|
|
4
|
+
* The contract between the testing fake gateway and the per-surface reply tables, and the fake's
|
|
5
|
+
* inverses of core's own wire reads: token bodies, error details, and timestamps. Each surface
|
|
6
|
+
* encodes its own SDK results into wire payloads and decodes its own requests back into SDK
|
|
7
|
+
* params, so wire names stay in the owning feature. Only fakes and `testing/` load this module,
|
|
8
|
+
* so its token canaries ship only in the testing entry point's bundle.
|
|
9
|
+
*/
|
|
10
|
+
/** An encoder's answer for a result the gateway reports as the endpoint's `miss` error. */
|
|
11
|
+
const MISS = Symbol("paylov.fake.miss");
|
|
12
|
+
/** `{ [key]: value }`, or `{}` for a value the request omitted. */
|
|
13
|
+
function optionalEntry(key, value) {
|
|
14
|
+
const entry = {};
|
|
15
|
+
if (value !== void 0) entry[key] = value;
|
|
16
|
+
return entry;
|
|
17
|
+
}
|
|
18
|
+
/** The wire whole-SUM integer `key` as tiyin, the inverse of `encodeWholeSum`. */
|
|
19
|
+
function decodeWholeSum(params, key) {
|
|
20
|
+
const amountTiyin = wireSumToTiyin(params.integer(key));
|
|
21
|
+
if (amountTiyin === void 0) throw unencodable(key, "must be a non-negative SUM amount");
|
|
22
|
+
return amountTiyin;
|
|
23
|
+
}
|
|
24
|
+
function unencodable(field, rule) {
|
|
25
|
+
return /* @__PURE__ */ new TypeError(`${field} ${rule}`);
|
|
26
|
+
}
|
|
27
|
+
/** Wire whole SUM; throws `TypeError` for an amount with tiyin. */
|
|
28
|
+
function encodeWholeSum(amountTiyin, field) {
|
|
29
|
+
const sum = tiyinToWireSum(amountTiyin);
|
|
30
|
+
if (sum === void 0) throw unencodable(field, "must be a whole SUM amount in tiyin");
|
|
31
|
+
return sum;
|
|
32
|
+
}
|
|
33
|
+
const MINUTE_MS = 6e4;
|
|
34
|
+
function two(value) {
|
|
35
|
+
return String(value).padStart(2, "0");
|
|
36
|
+
}
|
|
37
|
+
/** Wall-clock `YYYY-MM-DD HH:mm:ss` of `date` at a fixed offset, as the time parsers read it. */
|
|
38
|
+
function localDateTimeOf(date, offsetMinutes, field) {
|
|
39
|
+
const ms = date.getTime();
|
|
40
|
+
const local = new Date(ms + offsetMinutes * MINUTE_MS);
|
|
41
|
+
const year = local.getUTCFullYear();
|
|
42
|
+
const isFourDigitYear = year >= 0 && year <= 9999;
|
|
43
|
+
if (!Number.isFinite(ms) || ms % 1e3 !== 0 || !isFourDigitYear) throw unencodable(field, "must be a valid date in whole seconds");
|
|
44
|
+
return `${`${String(year).padStart(4, "0")}-${two(local.getUTCMonth() + 1)}-${two(local.getUTCDate())}`} ${two(local.getUTCHours())}:${two(local.getUTCMinutes())}:${two(local.getUTCSeconds())}`;
|
|
45
|
+
}
|
|
46
|
+
/** Wire Tashkent `YYYY-MM-DD HH:mm:ss`; throws `TypeError` for sub-second or invalid dates. */
|
|
47
|
+
function tashkentDateTimeOf(date, field) {
|
|
48
|
+
return localDateTimeOf(date, 300, field);
|
|
49
|
+
}
|
|
50
|
+
/** Wire UTC `YYYY-MM-DD HH:mm:ss`; throws `TypeError` for sub-second or invalid dates. */
|
|
51
|
+
function utcDateTimeOf(date, field) {
|
|
52
|
+
return localDateTimeOf(date, 0, field);
|
|
53
|
+
}
|
|
54
|
+
/** Wire unix seconds; throws `TypeError` for sub-second, invalid or pre-1970 dates. */
|
|
55
|
+
function unixSecondsOf(date, field) {
|
|
56
|
+
const ms = date.getTime();
|
|
57
|
+
if (!Number.isFinite(ms) || ms < 0 || ms % 1e3 !== 0) throw unencodable(field, "must be a date from 1970 in whole seconds");
|
|
58
|
+
return ms / 1e3;
|
|
59
|
+
}
|
|
60
|
+
/** `T | null` encoded with `encode`, keeping `null`. */
|
|
61
|
+
function nullableOf(value, encode) {
|
|
62
|
+
return value === null ? null : encode(value);
|
|
63
|
+
}
|
|
64
|
+
/** What the fake gateway answers on the token and revoke endpoints; tokens are canaries. */
|
|
65
|
+
const FAKE_AUTH_BODIES = {
|
|
66
|
+
token: {
|
|
67
|
+
access_token: "EXAMPLE-FAKE-ACCESS-TOKEN-NOT-A-REAL-TOKEN",
|
|
68
|
+
refresh_token: "EXAMPLE-FAKE-REFRESH-TOKEN-NOT-A-REAL-TOKEN",
|
|
69
|
+
token_type: "Bearer",
|
|
70
|
+
expires_in: 3600,
|
|
71
|
+
refresh_expires_in: 2592e3
|
|
72
|
+
},
|
|
73
|
+
revoke: { status: "success" }
|
|
74
|
+
};
|
|
75
|
+
function nestFieldPaths(paths) {
|
|
76
|
+
const root = {};
|
|
77
|
+
for (const path of paths) {
|
|
78
|
+
const segments = path.split(".");
|
|
79
|
+
const leaf = segments.pop() ?? path;
|
|
80
|
+
let node = root;
|
|
81
|
+
for (const segment of segments) {
|
|
82
|
+
const child = node[segment];
|
|
83
|
+
const next = isRecord(child) ? { ...child } : {};
|
|
84
|
+
node[segment] = next;
|
|
85
|
+
node = next;
|
|
86
|
+
}
|
|
87
|
+
node[leaf] = ["invalid"];
|
|
88
|
+
}
|
|
89
|
+
return root;
|
|
90
|
+
}
|
|
91
|
+
function errorDataOf(code, fields, retryAfterSeconds) {
|
|
92
|
+
if (code === "field_not_valid" || code === "field_required") return { field: fields[0] ?? "" };
|
|
93
|
+
if (code === "card_is_blocked" && retryAfterSeconds !== void 0) return { sec_to_retry: retryAfterSeconds };
|
|
94
|
+
return nestFieldPaths(fields);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* A gateway error response that `decodeErrorDetails` reads back as `details`, when the gateway
|
|
98
|
+
* can express them for `code`; the caller verifies by decoding it.
|
|
99
|
+
*/
|
|
100
|
+
function encodeErrorDetails(code, details) {
|
|
101
|
+
const { fields = [], retryAfterSeconds } = details;
|
|
102
|
+
const isRateLimitDelay = code === "rate_limit_exceeded" && retryAfterSeconds !== void 0;
|
|
103
|
+
return {
|
|
104
|
+
error: {
|
|
105
|
+
code,
|
|
106
|
+
message: code,
|
|
107
|
+
data: errorDataOf(code, fields, retryAfterSeconds)
|
|
108
|
+
},
|
|
109
|
+
retryAfter: isRateLimitDelay ? String(retryAfterSeconds) : null
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
// src/shared/fake.ts
|
|
113
|
+
/**
|
|
114
|
+
* Wire encoders of the shared transaction shapes and request decoders of the shared request
|
|
115
|
+
* shapes, the inverses of `transactions.ts`, `receiptItems.ts` and `otpSms.ts`.
|
|
116
|
+
*/
|
|
117
|
+
/** The wire `{ transactionId }` that `decodeTransactionReference` reads. */
|
|
118
|
+
function encodeTransactionReference(reference) {
|
|
119
|
+
return { transactionId: reference.transactionId };
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* The first wire spelling `statusDecoder(statusByWire)` reads as `status`; a status the SDK does
|
|
123
|
+
* not rename passes through. Throws `TypeError` for a wire spelling the SDK never returns, which
|
|
124
|
+
* would read back renamed.
|
|
125
|
+
*/
|
|
126
|
+
function encodeStatus$1(statusByWire, status) {
|
|
127
|
+
for (const [wire, sdkStatus] of statusByWire) if (sdkStatus === status) return wire;
|
|
128
|
+
if (statusByWire.has(status)) throw new TypeError(`status ${status} is a wire spelling; the SDK reads it as ${String(statusByWire.get(status))}`);
|
|
129
|
+
return status;
|
|
130
|
+
}
|
|
131
|
+
/** A receipt line as `readReceiptItem` sent it. */
|
|
132
|
+
function decodeReceiptItem(item) {
|
|
133
|
+
const base = {
|
|
134
|
+
title: item.string("title"),
|
|
135
|
+
priceTiyin: item.tiyin("price"),
|
|
136
|
+
...optionalEntry("discountTiyin", item.optionalTiyin("discount")),
|
|
137
|
+
count: item.integer("count"),
|
|
138
|
+
code: item.string("code"),
|
|
139
|
+
vatPercent: item.integer("vat_percent"),
|
|
140
|
+
packageCode: item.string("package_code")
|
|
141
|
+
};
|
|
142
|
+
return item.exclusive(["tin", "pinfl"]) === "tin" ? {
|
|
143
|
+
...base,
|
|
144
|
+
tin: item.string("tin")
|
|
145
|
+
} : {
|
|
146
|
+
...base,
|
|
147
|
+
pinfl: item.string("pinfl")
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
/** The `sms` object as `readOtpSms` sent it. */
|
|
151
|
+
function decodeOtpSms(sms) {
|
|
152
|
+
return {
|
|
153
|
+
...optionalEntry("hash", sms.optionalString("hash")),
|
|
154
|
+
...optionalEntry("templateId", sms.optionalInteger("templateId"))
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
// src/cards/fake.ts
|
|
158
|
+
function encodeCardStatus(card) {
|
|
159
|
+
return {
|
|
160
|
+
is_active: card.isActive,
|
|
161
|
+
status_message: card.processingStatus,
|
|
162
|
+
sms_info: card.isSmsEnabled
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
function encodeCard(card, status) {
|
|
166
|
+
return {
|
|
167
|
+
cardId: card.cardId,
|
|
168
|
+
userId: card.userId,
|
|
169
|
+
owner: card.holderName,
|
|
170
|
+
cardName: card.cardName,
|
|
171
|
+
number: card.maskedCardNumber,
|
|
172
|
+
balance: card.balanceTiyin,
|
|
173
|
+
bankId: card.bankId,
|
|
174
|
+
bankName: card.bankName,
|
|
175
|
+
vendor: card.vendor,
|
|
176
|
+
processing: card.processing,
|
|
177
|
+
status
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
/** Confirm and the bind session send a flat `status`. */
|
|
181
|
+
function encodeFlatCard(card) {
|
|
182
|
+
return encodeCard(card, encodeCardStatus(card));
|
|
183
|
+
}
|
|
184
|
+
/** Reads nest the status as `status.result`. */
|
|
185
|
+
function encodeNestedCard(card) {
|
|
186
|
+
return encodeCard(card, { result: encodeCardStatus(card) });
|
|
187
|
+
}
|
|
188
|
+
function encodeBindLinkCreated(created) {
|
|
189
|
+
return {
|
|
190
|
+
token: created.token,
|
|
191
|
+
bindUrl: created.bindUrl,
|
|
192
|
+
expiresAt: created.expiresAt.toISOString()
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
function encodeBindSession(session) {
|
|
196
|
+
const card = session.card === null ? null : encodeFlatCard(session.card);
|
|
197
|
+
return {
|
|
198
|
+
state: session.status,
|
|
199
|
+
card
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
function encodePanBindingStarted(started) {
|
|
203
|
+
return {
|
|
204
|
+
cid: started.cardId,
|
|
205
|
+
otpSentPhone: started.otpSentPhone
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
function encodeConfirmedCard(card) {
|
|
209
|
+
return { card: encodeFlatCard(card) };
|
|
210
|
+
}
|
|
211
|
+
function encodeFetchedCard(card) {
|
|
212
|
+
return { card: encodeNestedCard(card) };
|
|
213
|
+
}
|
|
214
|
+
function encodeCardList(cards) {
|
|
215
|
+
return { cards: cards.map(encodeNestedCard) };
|
|
216
|
+
}
|
|
217
|
+
function encodeTrue() {
|
|
218
|
+
return true;
|
|
219
|
+
}
|
|
220
|
+
function encodeMatch(isMatch) {
|
|
221
|
+
return { match: isMatch };
|
|
222
|
+
}
|
|
223
|
+
function decodeCreateBindLinkRequest({ body }) {
|
|
224
|
+
return {
|
|
225
|
+
userId: body.string("userId"),
|
|
226
|
+
...optionalEntry("returnUrl", body.optionalString("returnUrl"))
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
function decodeBindSessionRequest({ path }) {
|
|
230
|
+
return { token: path.string("token") };
|
|
231
|
+
}
|
|
232
|
+
function decodeStartPanBindingRequest({ body }) {
|
|
233
|
+
return {
|
|
234
|
+
userId: body.string("userId"),
|
|
235
|
+
cardNumber: body.string("cardNumber"),
|
|
236
|
+
cardExpiry: body.string("expireDate"),
|
|
237
|
+
...optionalEntry("phoneNumber", body.optionalString("phoneNumber")),
|
|
238
|
+
...optionalEntry("sms", body.optionalObject("sms", decodeOtpSms))
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
function decodeConfirmPanBindingRequest({ body }) {
|
|
242
|
+
return {
|
|
243
|
+
cardId: body.string("cardId"),
|
|
244
|
+
otp: body.string("otp"),
|
|
245
|
+
...optionalEntry("cardName", body.optionalString("cardName")),
|
|
246
|
+
...optionalEntry("pinfl", body.optionalString("pinfl"))
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
function decodeGetRequest$3({ path }) {
|
|
250
|
+
return { cardId: path.string("cardId") };
|
|
251
|
+
}
|
|
252
|
+
function decodeListRequest$1({ query }) {
|
|
253
|
+
return { userId: query.string("userId") };
|
|
254
|
+
}
|
|
255
|
+
function decodeDeleteRequest({ query }) {
|
|
256
|
+
return { cardId: query.string("userCardId") };
|
|
257
|
+
}
|
|
258
|
+
function decodeCheckPhoneRequest({ body }) {
|
|
259
|
+
return {
|
|
260
|
+
cardId: body.string("cardId"),
|
|
261
|
+
phoneNumber: body.string("phoneNumber")
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
function createCardsFake(script) {
|
|
265
|
+
return {
|
|
266
|
+
createBindLink: script("cards.createBindLink", ENDPOINTS.createBindLink, encodeBindLinkCreated, decodeCreateBindLinkRequest),
|
|
267
|
+
getBindSession: script("cards.getBindSession", ENDPOINTS.getBindSession, encodeBindSession, decodeBindSessionRequest),
|
|
268
|
+
startPanBinding: script("cards.startPanBinding", ENDPOINTS.startPanBinding, encodePanBindingStarted, decodeStartPanBindingRequest),
|
|
269
|
+
confirmPanBinding: script("cards.confirmPanBinding", ENDPOINTS.confirmPanBinding, encodeConfirmedCard, decodeConfirmPanBindingRequest),
|
|
270
|
+
get: script("cards.get", ENDPOINTS.get, encodeFetchedCard, decodeGetRequest$3),
|
|
271
|
+
list: script("cards.list", ENDPOINTS.list, encodeCardList, decodeListRequest$1),
|
|
272
|
+
delete: script("cards.delete", ENDPOINTS.delete, encodeTrue, decodeDeleteRequest),
|
|
273
|
+
checkPhone: script("cards.checkPhone", ENDPOINTS.checkPhone, encodeMatch, decodeCheckPhoneRequest)
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
// src/fiscalization/fake.ts
|
|
277
|
+
function encodeOfdReceipt(receipt) {
|
|
278
|
+
return {
|
|
279
|
+
receiptId: receipt.receiptId,
|
|
280
|
+
receiptUrl: receipt.receiptUrl,
|
|
281
|
+
terminalId: receipt.terminalId,
|
|
282
|
+
fiscalSign: receipt.fiscalSign
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
function encodeRegistered(receipt) {
|
|
286
|
+
return { ofd: encodeOfdReceipt(receipt) };
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* A known transaction without a receipt answers `success: false`. An unknown `externalId` answers
|
|
290
|
+
* the endpoint's miss instead, which the SDK reads as the same `null`.
|
|
291
|
+
*/
|
|
292
|
+
function encodeReceiptLookup(receipt) {
|
|
293
|
+
if (receipt === null) return {
|
|
294
|
+
success: false,
|
|
295
|
+
receiptUrl: null,
|
|
296
|
+
isRefund: null
|
|
297
|
+
};
|
|
298
|
+
return {
|
|
299
|
+
success: true,
|
|
300
|
+
...encodeOfdReceipt(receipt),
|
|
301
|
+
isRefund: receipt.isRefund
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
function encodeAttached() {
|
|
305
|
+
return {
|
|
306
|
+
success: true,
|
|
307
|
+
error: null
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
function encodeRefunded(refunded) {
|
|
311
|
+
return {
|
|
312
|
+
ofd: { refund: encodeOfdReceipt(refunded.refund) },
|
|
313
|
+
sale: encodeOfdReceipt(refunded.sale)
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
/** Activity names make the high-income answer; none is the self-employed `data: null`. */
|
|
317
|
+
function encodeActivityTypeCheck(check) {
|
|
318
|
+
const { isConfirmed, activityNames } = check;
|
|
319
|
+
return activityNames.length > 0 ? {
|
|
320
|
+
success: true,
|
|
321
|
+
data: {
|
|
322
|
+
status: isConfirmed,
|
|
323
|
+
activityNames
|
|
324
|
+
}
|
|
325
|
+
} : {
|
|
326
|
+
success: isConfirmed,
|
|
327
|
+
data: null
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
function decodeRegisterRequest({ body }) {
|
|
331
|
+
const items = body.array("items", decodeReceiptItem);
|
|
332
|
+
const lookup = readTransactionLookup(body);
|
|
333
|
+
return lookup.transactionId === void 0 ? {
|
|
334
|
+
externalId: lookup.externalId,
|
|
335
|
+
phoneNumber: body.string("phoneNumber"),
|
|
336
|
+
items
|
|
337
|
+
} : {
|
|
338
|
+
transactionId: lookup.transactionId,
|
|
339
|
+
items
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
function decodeGetRequest$2({ query }) {
|
|
343
|
+
const refunded = query.optionalString("refunded");
|
|
344
|
+
return {
|
|
345
|
+
...readTransactionLookup(query),
|
|
346
|
+
...optionalEntry("isRefund", refunded === void 0 ? void 0 : refunded === "true")
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
function decodeAttachRequest({ body }) {
|
|
350
|
+
return {
|
|
351
|
+
transactionId: body.string("transactionId"),
|
|
352
|
+
terminalId: body.string("terminalId"),
|
|
353
|
+
issuedAtRaw: body.string("dateTime"),
|
|
354
|
+
fiscalSign: body.string("fiscalSign"),
|
|
355
|
+
receiptUrl: body.string("qrCodeUrl"),
|
|
356
|
+
receiptId: body.integer("receiptId"),
|
|
357
|
+
...optionalEntry("externalId", body.optionalString("externalId"))
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
function decodeRefundRequest$1({ body }) {
|
|
361
|
+
return { receiptId: body.integer("receiptId") };
|
|
362
|
+
}
|
|
363
|
+
function decodeActivityTypeRequest({ body }) {
|
|
364
|
+
const wire = body.integer("activityType");
|
|
365
|
+
const activityType = ACTIVITY_TYPES.find((type) => WIRE_ACTIVITY_TYPES[type] === wire);
|
|
366
|
+
if (activityType === void 0) throw new TypeError("activityType is not a known wire value");
|
|
367
|
+
return {
|
|
368
|
+
pinfl: body.string("pinfl"),
|
|
369
|
+
activityType
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
function createFiscalizationFake(script) {
|
|
373
|
+
return {
|
|
374
|
+
registerReceipt: script("fiscalization.registerReceipt", ENDPOINTS$1.registerReceipt, encodeRegistered, decodeRegisterRequest),
|
|
375
|
+
getReceipt: script("fiscalization.getReceipt", ENDPOINTS$1.getReceipt, encodeReceiptLookup, decodeGetRequest$2),
|
|
376
|
+
attachReceipt: script("fiscalization.attachReceipt", ENDPOINTS$1.attachReceipt, encodeAttached, decodeAttachRequest),
|
|
377
|
+
refundReceipt: script("fiscalization.refundReceipt", ENDPOINTS$1.refundReceipt, encodeRefunded, decodeRefundRequest$1),
|
|
378
|
+
checkActivityType: script("fiscalization.checkActivityType", ENDPOINTS$1.checkActivityType, encodeActivityTypeCheck, decodeActivityTypeRequest)
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
// src/gateway/fake.ts
|
|
382
|
+
function encodeStatus() {
|
|
383
|
+
return { status: "ok" };
|
|
384
|
+
}
|
|
385
|
+
/** A `bankId` that is not a decimal integer cannot come from the gateway and fails decoding. */
|
|
386
|
+
function encodeBanks(banks) {
|
|
387
|
+
return banks.map((bank) => ({
|
|
388
|
+
id: Number(bank.bankId),
|
|
389
|
+
name: bank.name,
|
|
390
|
+
official_name: bank.officialName
|
|
391
|
+
}));
|
|
392
|
+
}
|
|
393
|
+
function decodeNoParams() {}
|
|
394
|
+
function createGatewayFake(script) {
|
|
395
|
+
return {
|
|
396
|
+
getStatus: script("gateway.getStatus", ENDPOINTS$2.getStatus, encodeStatus, decodeNoParams),
|
|
397
|
+
listBanks: script("gateway.listBanks", ENDPOINTS$2.listBanks, encodeBanks, decodeNoParams)
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
// src/holds/fake.ts
|
|
401
|
+
function encodeHoldCaptured(captured) {
|
|
402
|
+
return {
|
|
403
|
+
...encodeTransactionReference(captured),
|
|
404
|
+
cardId: captured.cardId,
|
|
405
|
+
payedAt: utcDateTimeOf(captured.capturedAt, "capturedAt")
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
function encodeHoldReleased(released) {
|
|
409
|
+
return {
|
|
410
|
+
...encodeTransactionReference(released),
|
|
411
|
+
status: "cancelled"
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
function encodeHold(hold) {
|
|
415
|
+
if (hold === null) return MISS;
|
|
416
|
+
return {
|
|
417
|
+
transactionId: hold.transactionId,
|
|
418
|
+
status: encodeStatus$1(HOLD_STATUS_BY_WIRE, hold.status),
|
|
419
|
+
amount: encodeWholeSum(hold.amountTiyin, "amountTiyin"),
|
|
420
|
+
payedAt: nullableOf(hold.capturedAt, (date) => utcDateTimeOf(date, "capturedAt")),
|
|
421
|
+
cancelTime: nullableOf(hold.releasedAt, (date) => utcDateTimeOf(date, "releasedAt")),
|
|
422
|
+
serviceId: hold.serviceId
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
function decodeCreateRequest$3({ body }) {
|
|
426
|
+
return {
|
|
427
|
+
userId: body.string("userId"),
|
|
428
|
+
cardId: body.string("cardId"),
|
|
429
|
+
amountTiyin: decodeWholeSum(body, "amount"),
|
|
430
|
+
durationMinutes: body.integer("time"),
|
|
431
|
+
externalId: body.string("externalId"),
|
|
432
|
+
...optionalEntry("account", body.optionalJson("account")),
|
|
433
|
+
...optionalEntry("serviceId", body.optionalString("serviceId"))
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
function decodeCaptureRequest({ body }) {
|
|
437
|
+
return {
|
|
438
|
+
transactionId: body.string("transactionId"),
|
|
439
|
+
amountTiyin: decodeWholeSum(body, "amount")
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
function decodeReleaseRequest({ body }) {
|
|
443
|
+
return { transactionId: body.string("transactionId") };
|
|
444
|
+
}
|
|
445
|
+
function createHoldsFake(script) {
|
|
446
|
+
return {
|
|
447
|
+
create: script("holds.create", ENDPOINTS$3.create, encodeTransactionReference, decodeCreateRequest$3),
|
|
448
|
+
capture: script("holds.capture", ENDPOINTS$3.capture, encodeHoldCaptured, decodeCaptureRequest),
|
|
449
|
+
release: script("holds.release", ENDPOINTS$3.release, encodeHoldReleased, decodeReleaseRequest),
|
|
450
|
+
get: script("holds.get", ENDPOINTS$3.get, encodeHold, ({ query }) => readTransactionLookup(query))
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
// src/onboarding/fake.ts
|
|
454
|
+
function encodeTokenUsable(isUsable) {
|
|
455
|
+
return isUsable ? { status: "ok" } : MISS;
|
|
456
|
+
}
|
|
457
|
+
function encodeOnboardingCompleted(completed) {
|
|
458
|
+
return {
|
|
459
|
+
consumer_key: completed.consumerKey,
|
|
460
|
+
consumer_secret: completed.consumerSecret,
|
|
461
|
+
username: completed.username
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
function decodeCheckTokenRequest({ query }) {
|
|
465
|
+
return { token: query.string("token") };
|
|
466
|
+
}
|
|
467
|
+
/** The password is a credential, so it is never read back. */
|
|
468
|
+
function decodeCompleteRequest({ query, body }) {
|
|
469
|
+
return {
|
|
470
|
+
token: query.string("token"),
|
|
471
|
+
username: body.string("username")
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
function createOnboardingFake(script) {
|
|
475
|
+
return {
|
|
476
|
+
checkToken: script("onboarding.checkToken", ENDPOINTS$4.checkToken, encodeTokenUsable, decodeCheckTokenRequest),
|
|
477
|
+
complete: script("onboarding.complete", ENDPOINTS$4.complete, encodeOnboardingCompleted, decodeCompleteRequest)
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
// src/payments/fake.ts
|
|
481
|
+
function encodePaymentRefunded(refund) {
|
|
482
|
+
return {
|
|
483
|
+
...encodeTransactionReference(refund),
|
|
484
|
+
status: "cancelled",
|
|
485
|
+
cancelTime: tashkentDateTimeOf(refund.refundedAt, "refundedAt")
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
function encodePanPaymentStarted(started) {
|
|
489
|
+
return {
|
|
490
|
+
...encodeTransactionReference(started),
|
|
491
|
+
otpSentPhone: started.otpSentPhone
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
/** An absent `account` is sent as `{}`, so an empty one reads as absent. */
|
|
495
|
+
function decodeAccount(body) {
|
|
496
|
+
const account = body.json("account");
|
|
497
|
+
return optionalEntry("account", Object.keys(account).length === 0 ? void 0 : account);
|
|
498
|
+
}
|
|
499
|
+
function decodeCreateRequest$2({ body }) {
|
|
500
|
+
return {
|
|
501
|
+
amountTiyin: decodeWholeSum(body, "amount"),
|
|
502
|
+
...decodeAccount(body),
|
|
503
|
+
...optionalEntry("userId", body.optionalString("userId"))
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
function decodePayRequest({ body }) {
|
|
507
|
+
return {
|
|
508
|
+
transactionId: body.string("transactionId"),
|
|
509
|
+
cardId: body.string("cardId"),
|
|
510
|
+
userId: body.string("userId")
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
function decodeRefundRequest({ body }) {
|
|
514
|
+
return { transactionId: body.string("transactionId") };
|
|
515
|
+
}
|
|
516
|
+
function decodeStartPanPaymentRequest({ body }) {
|
|
517
|
+
return {
|
|
518
|
+
cardNumber: body.string("cardNumber"),
|
|
519
|
+
cardExpiry: body.string("expireDate"),
|
|
520
|
+
amountTiyin: decodeWholeSum(body, "amount"),
|
|
521
|
+
...decodeAccount(body),
|
|
522
|
+
...optionalEntry("sms", body.optionalObject("sms", decodeOtpSms))
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
function decodeConfirmPanPaymentRequest({ body }) {
|
|
526
|
+
return {
|
|
527
|
+
transactionId: body.string("transactionId"),
|
|
528
|
+
otp: body.string("otp"),
|
|
529
|
+
...optionalEntry("sms", body.optionalObject("sms", decodeOtpSms))
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
function createPaymentsFake(script) {
|
|
533
|
+
return {
|
|
534
|
+
create: script("payments.create", ENDPOINTS$5.create, encodeTransactionReference, decodeCreateRequest$2),
|
|
535
|
+
pay: script("payments.pay", ENDPOINTS$5.pay, encodeTransactionReference, decodePayRequest),
|
|
536
|
+
refund: script("payments.refund", ENDPOINTS$5.refund, encodePaymentRefunded, decodeRefundRequest),
|
|
537
|
+
startPanPayment: script("payments.startPanPayment", ENDPOINTS$5.startPanPayment, encodePanPaymentStarted, decodeStartPanPaymentRequest),
|
|
538
|
+
confirmPanPayment: script("payments.confirmPanPayment", ENDPOINTS$5.confirmPanPayment, encodeTransactionReference, decodeConfirmPanPaymentRequest)
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
// src/splits/fake.ts
|
|
542
|
+
function encodeSplitShares(shares) {
|
|
543
|
+
return shares.map((share) => ({
|
|
544
|
+
recipientId: share.recipientId,
|
|
545
|
+
amount: share.amountTiyin,
|
|
546
|
+
status: share.status,
|
|
547
|
+
createdAt: share.createdAtRaw
|
|
548
|
+
}));
|
|
549
|
+
}
|
|
550
|
+
/** Recipient amounts travel in tiyin. */
|
|
551
|
+
function decodeRecipient(recipient) {
|
|
552
|
+
return {
|
|
553
|
+
recipientId: recipient.string("recipientId"),
|
|
554
|
+
amountTiyin: recipient.tiyin("amount"),
|
|
555
|
+
...optionalEntry("items", recipient.optionalArray("items", decodeReceiptItem))
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
function decodeCreateRequest$1({ body }) {
|
|
559
|
+
return {
|
|
560
|
+
transactionId: body.string("transactionId"),
|
|
561
|
+
recipients: body.array("recipients", decodeRecipient),
|
|
562
|
+
...optionalEntry("resendOfd", body.optionalBoolean("resendOFD"))
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
function decodeGetRequest$1({ query }) {
|
|
566
|
+
return { transactionId: query.string("transactionId") };
|
|
567
|
+
}
|
|
568
|
+
function createSplitsFake(script) {
|
|
569
|
+
return {
|
|
570
|
+
create: script("splits.create", ENDPOINTS$6.create, encodeTransactionReference, decodeCreateRequest$1),
|
|
571
|
+
get: script("splits.get", ENDPOINTS$6.get, encodeSplitShares, decodeGetRequest$1)
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
// src/subMerchants/fake.ts
|
|
575
|
+
function encodeSubMerchantCreated(created) {
|
|
576
|
+
return {
|
|
577
|
+
id: created.subMerchantId,
|
|
578
|
+
name: created.name
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
function decodeOrganization(organization) {
|
|
582
|
+
const optionalField = (field, key) => optionalEntry(field, organization.optionalString(key));
|
|
583
|
+
return {
|
|
584
|
+
name: organization.string("name"),
|
|
585
|
+
directorPinfl: organization.string("director_pinfl"),
|
|
586
|
+
accountNumber: organization.string("account_number"),
|
|
587
|
+
oked: organization.string("oked"),
|
|
588
|
+
...optionalField("legalName", "legal_name"),
|
|
589
|
+
...optionalField("directorFullName", "director_fio"),
|
|
590
|
+
...optionalField("directorPassport", "director_passport"),
|
|
591
|
+
...optionalField("directorPassportValidTo", "director_passport_valid_to"),
|
|
592
|
+
...optionalField("directorBirthDate", "director_birth_date"),
|
|
593
|
+
...optionalField("directorNationality", "director_nationality"),
|
|
594
|
+
...optionalField("directorNationalityUzcard", "dr_nationality_for_uzcard"),
|
|
595
|
+
...optionalField("directorNationalityHumo", "dr_nationality_for_humo"),
|
|
596
|
+
...optionalField("mfo", "mfo")
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
function decodeCreateRequest({ body }) {
|
|
600
|
+
const tin = body.optionalString("tin");
|
|
601
|
+
const taxIds = tin === void 0 ? { pinfl: body.string("pinfl") } : {
|
|
602
|
+
tin,
|
|
603
|
+
...optionalEntry("pinfl", body.optionalString("pinfl")),
|
|
604
|
+
...optionalEntry("organization", body.optionalObject("organization", decodeOrganization))
|
|
605
|
+
};
|
|
606
|
+
return {
|
|
607
|
+
name: body.string("name"),
|
|
608
|
+
...taxIds,
|
|
609
|
+
...optionalEntry("externalId", body.optionalString("external_id")),
|
|
610
|
+
...optionalEntry("isSelfEmployed", body.optionalBoolean("self_employee_service")),
|
|
611
|
+
...optionalEntry("ofdVatPercent", body.optionalInteger("ofd_vat_percent")),
|
|
612
|
+
...optionalEntry("spic", body.optionalString("SPIC")),
|
|
613
|
+
...optionalEntry("spicPackageCode", body.optionalString("spic_package_code"))
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
function createSubMerchantsFake(script) {
|
|
617
|
+
return { create: script("subMerchants.create", ENDPOINTS$7.create, encodeSubMerchantCreated, decodeCreateRequest) };
|
|
618
|
+
}
|
|
619
|
+
// src/transactions/fake.ts
|
|
620
|
+
function encodeFiscalReceiptSummary(receipt) {
|
|
621
|
+
return {
|
|
622
|
+
receipt_id: receipt.receiptId,
|
|
623
|
+
qr_code_url: receipt.receiptUrl,
|
|
624
|
+
date_time: receipt.issuedAtRaw,
|
|
625
|
+
is_refund: receipt.isRefund
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
function encodeTransaction(transaction) {
|
|
629
|
+
return {
|
|
630
|
+
id: transaction.transactionId,
|
|
631
|
+
external_id: transaction.externalId,
|
|
632
|
+
userId: transaction.userId,
|
|
633
|
+
card_id: transaction.cardId,
|
|
634
|
+
cardNumber: transaction.maskedCardNumber,
|
|
635
|
+
amount_in_tiyin: transaction.amountTiyin,
|
|
636
|
+
status: encodeStatus$1(TRANSACTION_STATUS_BY_WIRE, transaction.status),
|
|
637
|
+
account: {},
|
|
638
|
+
error_message: transaction.declineCode,
|
|
639
|
+
date: tashkentDateTimeOf(transaction.paidOrCreatedAt, "paidOrCreatedAt"),
|
|
640
|
+
cancel_time: nullableOf(transaction.cancelledAt, (date) => tashkentDateTimeOf(date, "cancelledAt")),
|
|
641
|
+
is_hold: transaction.isHold,
|
|
642
|
+
is_split: transaction.isSplit,
|
|
643
|
+
is_a2c: transaction.isA2c,
|
|
644
|
+
via_link: transaction.isCheckout ? true : null,
|
|
645
|
+
ofd: transaction.fiscalReceipts.map(encodeFiscalReceiptSummary)
|
|
646
|
+
};
|
|
647
|
+
}
|
|
648
|
+
function encodeRequestedTransaction(transaction) {
|
|
649
|
+
return { transactions: transaction === null ? [] : [encodeTransaction(transaction)] };
|
|
650
|
+
}
|
|
651
|
+
function encodeTransactionPage(page) {
|
|
652
|
+
return {
|
|
653
|
+
totalTransaction: page.total,
|
|
654
|
+
transactions: page.transactions.map(encodeTransaction)
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
function encodeRrn(rrn) {
|
|
658
|
+
return { rrn };
|
|
659
|
+
}
|
|
660
|
+
/** `get` and `list` share the endpoint; only `get` sends an `id`. */
|
|
661
|
+
function isSingleRead({ query }) {
|
|
662
|
+
return query.raw("id") !== void 0;
|
|
663
|
+
}
|
|
664
|
+
function decodeGetRequest({ query }) {
|
|
665
|
+
return { transactionId: query.string("id") };
|
|
666
|
+
}
|
|
667
|
+
function decodeListRequest({ query }) {
|
|
668
|
+
const page = query.optionalString("page");
|
|
669
|
+
return {
|
|
670
|
+
...optionalEntry("fromDate", query.optionalString("beginDate")),
|
|
671
|
+
...optionalEntry("toDate", query.optionalString("endDate")),
|
|
672
|
+
...optionalEntry("page", page === void 0 ? void 0 : Number(page))
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
function decodeRrnRequest({ path }) {
|
|
676
|
+
return { transactionId: path.string("transactionId") };
|
|
677
|
+
}
|
|
678
|
+
function createTransactionsFake(script) {
|
|
679
|
+
return {
|
|
680
|
+
get: script("transactions.get", ENDPOINTS$8.getTransactions, encodeRequestedTransaction, decodeGetRequest, isSingleRead),
|
|
681
|
+
list: script("transactions.list", ENDPOINTS$8.getTransactions, encodeTransactionPage, decodeListRequest, (request) => !isSingleRead(request)),
|
|
682
|
+
getRrn: script("transactions.getRrn", ENDPOINTS$8.getRrn, encodeRrn, decodeRrnRequest)
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
// src/testing/gateway.ts
|
|
686
|
+
/** The scripted in-memory Paylov gateway behind the `@isroilov_an/paylov/testing` entry point. */
|
|
687
|
+
const BASE_URL = "https://gateway.example";
|
|
688
|
+
/** Not SDK or gateway codes, so a request the script cannot serve never reads as a real failure. */
|
|
689
|
+
const UNSCRIPTED_CODE = "fake_unscripted";
|
|
690
|
+
const UNREADABLE_CODE = "fake_unreadable_request";
|
|
691
|
+
const FAKE_FAILURE_STATUS = 501;
|
|
692
|
+
const RETRY_HINT = "the SDK retries a GET after a network error, a timeout or HTTP 500/502/503/504; script one answer per attempt or a persistent one";
|
|
693
|
+
/** The placeholder values of `path` under `route`, or `undefined` when it does not match. */
|
|
694
|
+
function routeValues(route, path) {
|
|
695
|
+
const pattern = RegExp.escape(route).replaceAll(/\\\{(\w+)\\\}/g, "(?<$1>[^/]+)");
|
|
696
|
+
const match = new RegExp(`^${pattern}$`).exec(path);
|
|
697
|
+
if (match === null) return void 0;
|
|
698
|
+
return Object.fromEntries(Object.entries(match.groups ?? {}).map(([name, value]) => [name, decodeURIComponent(value)]));
|
|
699
|
+
}
|
|
700
|
+
/** The parsed JSON body; anything else reads as no body, and never reaches an error. */
|
|
701
|
+
function parseBody(body) {
|
|
702
|
+
if (typeof body !== "string") return void 0;
|
|
703
|
+
try {
|
|
704
|
+
return JSON.parse(body);
|
|
705
|
+
} catch {
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
/** The request as `route` reads it, or `undefined` when its path does not match. */
|
|
710
|
+
function requestOf(route, url, body) {
|
|
711
|
+
const path = routeValues(route, url.pathname);
|
|
712
|
+
if (path === void 0) return void 0;
|
|
713
|
+
return {
|
|
714
|
+
body: readParams(isRecord(body) ? body : {}, "fake request body"),
|
|
715
|
+
query: readParams(Object.fromEntries(url.searchParams), "fake request query"),
|
|
716
|
+
path: readParams(path, "fake request path")
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
/** Whether the SDK retries the attempt `answer` serves on a GET. */
|
|
720
|
+
function isRetryableAnswer(answer) {
|
|
721
|
+
if (answer.kind === "respond") return isRetryableStatus(answer.httpStatus);
|
|
722
|
+
return true;
|
|
723
|
+
}
|
|
724
|
+
function jsonResponse(httpStatus, body, retryAfter = null) {
|
|
725
|
+
const headers = new Headers({ "content-type": "application/json" });
|
|
726
|
+
if (retryAfter !== null) headers.set("retry-after", retryAfter);
|
|
727
|
+
return new Response(JSON.stringify(body), {
|
|
728
|
+
status: httpStatus,
|
|
729
|
+
headers
|
|
730
|
+
});
|
|
731
|
+
}
|
|
732
|
+
function errorBody(error) {
|
|
733
|
+
return {
|
|
734
|
+
result: null,
|
|
735
|
+
error
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
function respond(httpStatus, body, retryAfter = null) {
|
|
739
|
+
return {
|
|
740
|
+
kind: "respond",
|
|
741
|
+
httpStatus,
|
|
742
|
+
body,
|
|
743
|
+
retryAfter
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
/** The success answer for `payload`, or the endpoint's not-found error for `MISS`. */
|
|
747
|
+
function replyAnswer(endpoint, payload) {
|
|
748
|
+
if (payload === MISS) return respond(400, errorBody({
|
|
749
|
+
code: endpoint.miss,
|
|
750
|
+
message: String(endpoint.miss)
|
|
751
|
+
}));
|
|
752
|
+
return respond(200, endpoint.shape === "envelope" ? {
|
|
753
|
+
result: payload,
|
|
754
|
+
error: null
|
|
755
|
+
} : payload);
|
|
756
|
+
}
|
|
757
|
+
/** Settles only when `signal` aborts, as a request the gateway never answers. */
|
|
758
|
+
function neverAnswered(signal) {
|
|
759
|
+
return new Promise((_resolve, reject) => {
|
|
760
|
+
const abort = () => {
|
|
761
|
+
reject(/* @__PURE__ */ new Error("The operation was aborted"));
|
|
762
|
+
};
|
|
763
|
+
if (signal?.aborted === true) abort();
|
|
764
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
function sameFields(requested, reported = []) {
|
|
768
|
+
return requested.length === reported.length && requested.every((f, i) => f === reported[i]);
|
|
769
|
+
}
|
|
770
|
+
/** A gateway error that the SDK decodes back into exactly the requested failure. */
|
|
771
|
+
function failureAnswer(code, failure) {
|
|
772
|
+
const { httpStatus = 400, fields, retryAfterSeconds } = failure;
|
|
773
|
+
if (!isWireErrorCode(code) || code.startsWith("sdk_")) throw new TypeError("code must be a gateway error code; script SDK connection failures with disconnect() or hang()");
|
|
774
|
+
if (!Number.isInteger(httpStatus) || httpStatus < 400 || httpStatus > 599) throw new TypeError("httpStatus must be an integer from 400 to 599");
|
|
775
|
+
const { error, retryAfter } = encodeErrorDetails(code, failure);
|
|
776
|
+
const reported = decodeErrorDetails(code, error, retryAfter);
|
|
777
|
+
if (!((fields === void 0 || sameFields(fields, reported.fields)) && (retryAfterSeconds === void 0 || retryAfterSeconds === reported.retryAfterSeconds))) throw new TypeError(`the gateway cannot report ${code} with these details at HTTP ${httpStatus}`);
|
|
778
|
+
return respond(httpStatus, errorBody(error), retryAfter);
|
|
779
|
+
}
|
|
780
|
+
async function respondWith(answer, signal) {
|
|
781
|
+
if (answer.kind === "disconnect") throw new TypeError("fetch failed");
|
|
782
|
+
if (answer.kind === "hang") return await neverAnswered(signal);
|
|
783
|
+
return jsonResponse(answer.httpStatus, answer.body, answer.retryAfter);
|
|
784
|
+
}
|
|
785
|
+
/**
|
|
786
|
+
* An in-memory Paylov gateway for application tests. Pass `clientConfig` (or `onboardingConfig`)
|
|
787
|
+
* to the SDK, script each expected call through the namespace that
|
|
788
|
+
* mirrors the client, then call `assertDone()`. Answers run through the SDK's real transport and
|
|
789
|
+
* decoders, so retries, the token lifecycle, errors and result types behave as against the
|
|
790
|
+
* gateway. Token and revoke requests are answered automatically. Each method's `requests` holds
|
|
791
|
+
* the params its served requests carried; requests never reach logs or errors.
|
|
792
|
+
*
|
|
793
|
+
* One-time answers are served in the order they were scripted, each to the first request of its
|
|
794
|
+
* method; a persistent answer (`{ persist: true }`) serves every request of its method that no
|
|
795
|
+
* one-time answer takes. Methods that send to the same gateway endpoint are told apart by their
|
|
796
|
+
* request, so each answer reaches only its own method. An unscripted request fails with
|
|
797
|
+
* `PaylovApiError` `fake_unscripted`, and a request the fake cannot read back into its method's
|
|
798
|
+
* params with `fake_unreadable_request`, both at HTTP 501 and reported by `assertDone()`.
|
|
799
|
+
*
|
|
800
|
+
* @example
|
|
801
|
+
* import { PaylovClient } from '@isroilov_an/paylov';
|
|
802
|
+
* import { PaylovFakeGateway } from '@isroilov_an/paylov/testing';
|
|
803
|
+
*
|
|
804
|
+
* const fake = new PaylovFakeGateway();
|
|
805
|
+
* const paylov = new PaylovClient(fake.clientConfig);
|
|
806
|
+
* fake.payments.create.reply({ transactionId: '00000000-0000-4000-8000-000000000001' });
|
|
807
|
+
* fake.payments.pay.fail('insufficient_funds');
|
|
808
|
+
*
|
|
809
|
+
* await expect(checkout(paylov, order)).rejects.toMatchObject({ code: 'insufficient_funds' });
|
|
810
|
+
* fake.assertDone();
|
|
811
|
+
*/
|
|
812
|
+
var PaylovFakeGateway = class {
|
|
813
|
+
gateway;
|
|
814
|
+
cards;
|
|
815
|
+
payments;
|
|
816
|
+
transactions;
|
|
817
|
+
holds;
|
|
818
|
+
splits;
|
|
819
|
+
fiscalization;
|
|
820
|
+
subMerchants;
|
|
821
|
+
onboarding;
|
|
822
|
+
/** The `fetch` that answers from the script; the configurations below already carry it. */
|
|
823
|
+
fetch;
|
|
824
|
+
/** A complete `PaylovClient` configuration with canary credentials; spread it to add options. */
|
|
825
|
+
clientConfig;
|
|
826
|
+
/** A complete `PaylovOnboarding` configuration. */
|
|
827
|
+
onboardingConfig;
|
|
828
|
+
#scripted = [];
|
|
829
|
+
#calls = [];
|
|
830
|
+
/** What `assertDone()` reports about requests the script could not serve. */
|
|
831
|
+
#unserved = [];
|
|
832
|
+
#lastServed;
|
|
833
|
+
constructor() {
|
|
834
|
+
const script = (method, endpoint, encode, decodeRequest, matches) => this.#script(method, endpoint, encode, decodeRequest, matches);
|
|
835
|
+
this.gateway = createGatewayFake(script);
|
|
836
|
+
this.cards = createCardsFake(script);
|
|
837
|
+
this.payments = createPaymentsFake(script);
|
|
838
|
+
this.transactions = createTransactionsFake(script);
|
|
839
|
+
this.holds = createHoldsFake(script);
|
|
840
|
+
this.splits = createSplitsFake(script);
|
|
841
|
+
this.fiscalization = createFiscalizationFake(script);
|
|
842
|
+
this.subMerchants = createSubMerchantsFake(script);
|
|
843
|
+
this.onboarding = createOnboardingFake(script);
|
|
844
|
+
this.fetch = (input, init) => this.#answer(input, init);
|
|
845
|
+
this.clientConfig = {
|
|
846
|
+
baseUrl: BASE_URL,
|
|
847
|
+
consumerKey: "EXAMPLE-FAKE-CONSUMER-KEY-NOT-A-REAL-CREDENTIAL",
|
|
848
|
+
consumerSecret: "EXAMPLE-FAKE-CONSUMER-SECRET-NOT-A-REAL-CREDENTIAL",
|
|
849
|
+
username: "EXAMPLE-FAKE-USERNAME-NOT-A-REAL-CREDENTIAL",
|
|
850
|
+
password: "EXAMPLE-FAKE-PASSWORD-NOT-A-REAL-CREDENTIAL",
|
|
851
|
+
fetch: this.fetch
|
|
852
|
+
};
|
|
853
|
+
this.onboardingConfig = {
|
|
854
|
+
baseUrl: BASE_URL,
|
|
855
|
+
fetch: this.fetch
|
|
856
|
+
};
|
|
857
|
+
}
|
|
858
|
+
/**
|
|
859
|
+
* Every request received so far, in order, token and revoke requests included. Each method's
|
|
860
|
+
* `requests` holds the params of its own requests.
|
|
861
|
+
*
|
|
862
|
+
* @example
|
|
863
|
+
* expect(fake.calls.map((call) => call.method)).toEqual([null, 'payments.create', 'payments.pay']);
|
|
864
|
+
*/
|
|
865
|
+
get calls() {
|
|
866
|
+
return [...this.#calls];
|
|
867
|
+
}
|
|
868
|
+
/**
|
|
869
|
+
* Throws when a request arrived unscripted or unreadable, or a scripted answer was never served.
|
|
870
|
+
*
|
|
871
|
+
* @example
|
|
872
|
+
* afterEach(() => fake.assertDone());
|
|
873
|
+
*/
|
|
874
|
+
assertDone() {
|
|
875
|
+
const problems = [...this.#unserved, ...this.#scripted.flatMap(({ route, persist, served }) => {
|
|
876
|
+
if (!persist) return [`unserved ${route.method} answer`];
|
|
877
|
+
return served ? [] : [`unserved persistent ${route.method} answer`];
|
|
878
|
+
})];
|
|
879
|
+
if (problems.length > 0) throw new Error(`PaylovFakeGateway: ${problems.join("; ")}`);
|
|
880
|
+
}
|
|
881
|
+
#script(method, endpoint, encode, decodeRequest, matches) {
|
|
882
|
+
const requests = [];
|
|
883
|
+
const route = {
|
|
884
|
+
method,
|
|
885
|
+
endpoint,
|
|
886
|
+
matches,
|
|
887
|
+
record: (request) => {
|
|
888
|
+
requests.push(decodeRequest(request));
|
|
889
|
+
}
|
|
890
|
+
};
|
|
891
|
+
const enqueue = (answer, schedule = {}) => {
|
|
892
|
+
this.#scripted.push({
|
|
893
|
+
route,
|
|
894
|
+
answer,
|
|
895
|
+
persist: schedule.persist === true,
|
|
896
|
+
served: false
|
|
897
|
+
});
|
|
898
|
+
};
|
|
899
|
+
return {
|
|
900
|
+
requests,
|
|
901
|
+
reply: (result, schedule) => {
|
|
902
|
+
enqueue(replyAnswer(endpoint, encode(result)), schedule);
|
|
903
|
+
},
|
|
904
|
+
fail: (code, failure = {}, schedule) => {
|
|
905
|
+
enqueue(failureAnswer(code, failure), schedule);
|
|
906
|
+
},
|
|
907
|
+
disconnect: (schedule) => {
|
|
908
|
+
enqueue({ kind: "disconnect" }, schedule);
|
|
909
|
+
},
|
|
910
|
+
hang: (schedule) => {
|
|
911
|
+
enqueue({ kind: "hang" }, schedule);
|
|
912
|
+
}
|
|
913
|
+
};
|
|
914
|
+
}
|
|
915
|
+
/** The first one-time answer for the request, else its first persistent answer. */
|
|
916
|
+
#scriptedFor(method, url, body) {
|
|
917
|
+
const candidates = this.#scripted.flatMap((scripted) => {
|
|
918
|
+
const { endpoint, matches } = scripted.route;
|
|
919
|
+
const request = endpoint.method === method ? requestOf(endpoint.route, url, body) : void 0;
|
|
920
|
+
return request !== void 0 && (matches?.(request) ?? true) ? [{
|
|
921
|
+
scripted,
|
|
922
|
+
request
|
|
923
|
+
}] : [];
|
|
924
|
+
});
|
|
925
|
+
return candidates.find(({ scripted }) => !scripted.persist) ?? candidates[0];
|
|
926
|
+
}
|
|
927
|
+
async #answer(input, init) {
|
|
928
|
+
const method = init.method ?? "GET";
|
|
929
|
+
const url = new URL(input);
|
|
930
|
+
const endpoint = `${method} ${url.pathname}`;
|
|
931
|
+
let found;
|
|
932
|
+
try {
|
|
933
|
+
found = this.#scriptedFor(method, url, parseBody(init.body));
|
|
934
|
+
found?.scripted.route.record(found.request);
|
|
935
|
+
} catch {
|
|
936
|
+
return this.#answerUnreadable(endpoint, found?.scripted.route.method);
|
|
937
|
+
}
|
|
938
|
+
if (found === void 0) return this.#answerUnmatched(method, url.pathname);
|
|
939
|
+
const { scripted } = found;
|
|
940
|
+
if (scripted.persist) scripted.served = true;
|
|
941
|
+
else this.#scripted.splice(this.#scripted.indexOf(scripted), 1);
|
|
942
|
+
this.#lastServed = {
|
|
943
|
+
endpoint,
|
|
944
|
+
isRetryable: method === "GET" && isRetryableAnswer(scripted.answer)
|
|
945
|
+
};
|
|
946
|
+
this.#calls.push({
|
|
947
|
+
method: scripted.route.method,
|
|
948
|
+
endpoint: endpointName(scripted.route.endpoint)
|
|
949
|
+
});
|
|
950
|
+
return await respondWith(scripted.answer, init.signal);
|
|
951
|
+
}
|
|
952
|
+
#answerUnreadable(endpoint, method) {
|
|
953
|
+
this.#calls.push({
|
|
954
|
+
method: null,
|
|
955
|
+
endpoint
|
|
956
|
+
});
|
|
957
|
+
const reader = method === void 0 ? "a request matcher" : `the ${method} request decoder`;
|
|
958
|
+
this.#unserved.push(`unreadable request ${endpoint} (${reader} threw)`);
|
|
959
|
+
const message = `the fake cannot read ${endpoint}`;
|
|
960
|
+
return jsonResponse(FAKE_FAILURE_STATUS, errorBody({
|
|
961
|
+
code: UNREADABLE_CODE,
|
|
962
|
+
message
|
|
963
|
+
}));
|
|
964
|
+
}
|
|
965
|
+
#answerUnmatched(method, path) {
|
|
966
|
+
const endpoint = `${method} ${path}`;
|
|
967
|
+
this.#calls.push({
|
|
968
|
+
method: null,
|
|
969
|
+
endpoint
|
|
970
|
+
});
|
|
971
|
+
if (method === ENDPOINTS$9.token.method && path === ENDPOINTS$9.token.route) return jsonResponse(200, FAKE_AUTH_BODIES.token);
|
|
972
|
+
if (method === ENDPOINTS$9.revoke.method && path === ENDPOINTS$9.revoke.route) return jsonResponse(200, FAKE_AUTH_BODIES.revoke);
|
|
973
|
+
const last = this.#lastServed;
|
|
974
|
+
const hint = last?.endpoint === endpoint && last.isRetryable ? ` (likely a retry: ${RETRY_HINT})` : "";
|
|
975
|
+
this.#unserved.push(`unscripted request ${endpoint}${hint}`);
|
|
976
|
+
const message = `no scripted answer for ${endpoint}`;
|
|
977
|
+
return jsonResponse(FAKE_FAILURE_STATUS, errorBody({
|
|
978
|
+
code: UNSCRIPTED_CODE,
|
|
979
|
+
message
|
|
980
|
+
}));
|
|
981
|
+
}
|
|
982
|
+
};
|
|
983
|
+
// src/webhooks/fake.ts
|
|
984
|
+
/** Wire encoders of webhook events, the inverse of `decoders.ts`, for testing requests. */
|
|
985
|
+
function encodeCheckoutParams(event) {
|
|
986
|
+
return {
|
|
987
|
+
account: event.account,
|
|
988
|
+
amount_tiyin: minorUnitsOf(event.amount),
|
|
989
|
+
currency: event.amount.currency
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
/** The body Paylov would deliver for `event`. */
|
|
993
|
+
function encodeWebhookEvent(event) {
|
|
994
|
+
switch (event.kind) {
|
|
995
|
+
case "transaction.check": return {
|
|
996
|
+
jsonrpc: "2.0",
|
|
997
|
+
id: event.id,
|
|
998
|
+
method: event.kind,
|
|
999
|
+
params: encodeCheckoutParams(event)
|
|
1000
|
+
};
|
|
1001
|
+
case "transaction.perform": {
|
|
1002
|
+
const params = {
|
|
1003
|
+
transaction_id: event.transactionId,
|
|
1004
|
+
...encodeCheckoutParams(event)
|
|
1005
|
+
};
|
|
1006
|
+
return {
|
|
1007
|
+
jsonrpc: "2.0",
|
|
1008
|
+
id: event.id,
|
|
1009
|
+
method: event.kind,
|
|
1010
|
+
params
|
|
1011
|
+
};
|
|
1012
|
+
}
|
|
1013
|
+
case "transaction.cancel": {
|
|
1014
|
+
const params = {
|
|
1015
|
+
transaction_id: event.transactionId,
|
|
1016
|
+
account: event.account,
|
|
1017
|
+
amount_in_tiyin: event.amountTiyin,
|
|
1018
|
+
cancel_time: unixSecondsOf(event.cancelledAt, "cancelledAt")
|
|
1019
|
+
};
|
|
1020
|
+
return {
|
|
1021
|
+
jsonrpc: "2.0",
|
|
1022
|
+
method: event.kind,
|
|
1023
|
+
params
|
|
1024
|
+
};
|
|
1025
|
+
}
|
|
1026
|
+
case "merchant.deposit": {
|
|
1027
|
+
const params = {
|
|
1028
|
+
id: event.depositId,
|
|
1029
|
+
merchant: event.merchantId,
|
|
1030
|
+
type: event.source,
|
|
1031
|
+
amount_in_tiyin: event.amountTiyin,
|
|
1032
|
+
create_time: unixSecondsOf(event.createdAt, "createdAt")
|
|
1033
|
+
};
|
|
1034
|
+
return {
|
|
1035
|
+
jsonrpc: "2.0",
|
|
1036
|
+
method: event.kind,
|
|
1037
|
+
params
|
|
1038
|
+
};
|
|
1039
|
+
}
|
|
1040
|
+
default: return {
|
|
1041
|
+
token: event.token,
|
|
1042
|
+
userId: event.userId,
|
|
1043
|
+
status: event.status,
|
|
1044
|
+
card: { cardId: event.cardId }
|
|
1045
|
+
};
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
// src/testing/webhooks.ts
|
|
1049
|
+
/** Authenticated webhook requests for testing a `PaylovWebhookReceiver` integration. */
|
|
1050
|
+
/**
|
|
1051
|
+
* The request Paylov would send for `event`, authenticated with the receiver's credentials, so
|
|
1052
|
+
* `receiver.receive(request)` returns `event`. Change the result to cover the `invalid`
|
|
1053
|
+
* outcomes. Throws `TypeError` for a time the wire cannot carry (sub-second or before 1970).
|
|
1054
|
+
*
|
|
1055
|
+
* @example
|
|
1056
|
+
* import { createWebhookRequest } from '@isroilov_an/paylov/testing';
|
|
1057
|
+
*
|
|
1058
|
+
* const request = createWebhookRequest(
|
|
1059
|
+
* {
|
|
1060
|
+
* kind: 'transaction.check',
|
|
1061
|
+
* id: 1,
|
|
1062
|
+
* account: { order_id: 'A-1024' },
|
|
1063
|
+
* amount: { currency: 860, amountTiyin: 50_000 },
|
|
1064
|
+
* },
|
|
1065
|
+
* { login: webhookLogin, password: webhookPassword },
|
|
1066
|
+
* );
|
|
1067
|
+
* const response = await handleWebhook(request); // your handler around receiver.receive
|
|
1068
|
+
*/
|
|
1069
|
+
function createWebhookRequest(event, credentials) {
|
|
1070
|
+
const pair = `${credentials.login}:${credentials.password}`;
|
|
1071
|
+
return {
|
|
1072
|
+
method: "POST",
|
|
1073
|
+
headers: { authorization: `Basic ${Buffer.from(pair, "utf8").toString("base64")}` },
|
|
1074
|
+
body: JSON.stringify(encodeWebhookEvent(event))
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
export { PaylovFakeGateway, createWebhookRequest };
|
|
1078
|
+
|
|
1079
|
+
//# sourceMappingURL=testing.js.map
|