@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.
@@ -0,0 +1,2576 @@
1
+ import { setTimeout } from "node:timers/promises";
2
+ // src/core/errors.ts
3
+ /** The shared base of the five error classes; consumers use the {@link PaylovError} union. */
4
+ var PaylovBaseError = class extends Error {
5
+ constructor(message) {
6
+ super(message);
7
+ Error.captureStackTrace(this, new.target);
8
+ }
9
+ /**
10
+ * Returns SDK diagnostic metadata only.
11
+ *
12
+ * @example
13
+ * logger.error('paylov call failed', error.toJSON());
14
+ */
15
+ toJSON() {
16
+ return {
17
+ name: this.name,
18
+ kind: this.kind,
19
+ code: this.code,
20
+ message: this.message,
21
+ ...this.diagnosticDetails()
22
+ };
23
+ }
24
+ };
25
+ /**
26
+ * The SDK rejected a call locally, before any I/O: a parameter, an amount or the configuration
27
+ * broke a rule. This is an integration bug, never a gateway answer. Messages name the field,
28
+ * never its value.
29
+ *
30
+ * @example
31
+ * catch (error) {
32
+ * if (error instanceof PaylovInputError) logger.error('invalid paylov call', error.toJSON());
33
+ * throw error;
34
+ * }
35
+ */
36
+ var PaylovInputError = class extends PaylovBaseError {
37
+ name = "PaylovInputError";
38
+ kind = "input";
39
+ code;
40
+ /**
41
+ * SDK parameter path such as `items[0].priceTiyin`; `undefined` when the params or
42
+ * configuration object itself, or a choice between its top-level keys, broke the rule.
43
+ */
44
+ field;
45
+ rule;
46
+ constructor(init) {
47
+ super(init.message);
48
+ this.code = init.code;
49
+ this.field = init.field;
50
+ this.rule = init.rule;
51
+ }
52
+ diagnosticDetails() {
53
+ return {
54
+ field: this.field,
55
+ rule: this.rule
56
+ };
57
+ }
58
+ };
59
+ /**
60
+ * The client was closed with `close()`. Nothing was sent, or the gateway rejected the request
61
+ * before running it; a new client, on this process or another, can make the call.
62
+ *
63
+ * @example
64
+ * catch (error) {
65
+ * if (error instanceof PaylovClientClosedError) return serviceUnavailable();
66
+ * throw error;
67
+ * }
68
+ */
69
+ var PaylovClientClosedError = class extends PaylovBaseError {
70
+ name = "PaylovClientClosedError";
71
+ kind = "closed";
72
+ code = "sdk_client_closed";
73
+ constructor() {
74
+ super("PaylovClient is closed; create a new client");
75
+ }
76
+ diagnosticDetails() {
77
+ return {};
78
+ }
79
+ };
80
+ /**
81
+ * The gateway answered with an error code. Unknown codes keep this class; narrow with
82
+ * {@link isPaylovApiError}.
83
+ *
84
+ * @example
85
+ * catch (error) {
86
+ * if (isPaylovApiError(error, 'rate_limit_exceeded')) await wait(error.retryAfterSeconds ?? 60);
87
+ * else throw error;
88
+ * }
89
+ */
90
+ var PaylovApiError = class extends PaylovBaseError {
91
+ name = "PaylovApiError";
92
+ kind = "api";
93
+ code;
94
+ httpStatus;
95
+ /** Static endpoint identity, e.g. `"POST /merchant/receipts/pay/"`. */
96
+ endpoint;
97
+ /**
98
+ * Wire field paths such as `items.0.title`, for `validation_error`, `field_not_valid` and
99
+ * `field_required` only. Names, never messages or values; not translated to SDK names.
100
+ */
101
+ fields;
102
+ /**
103
+ * Seconds until a retry can succeed, from 1 to 3600: for `rate_limit_exceeded`, from the
104
+ * `Retry-After` header (nothing retries a 429); for `card_is_blocked`,
105
+ * the rest of the card's block after repeated wrong one-time codes.
106
+ */
107
+ retryAfterSeconds;
108
+ constructor(init) {
109
+ super(`Paylov returned ${init.code} (HTTP ${init.httpStatus}) for ${init.endpoint}`);
110
+ this.code = init.code;
111
+ this.httpStatus = init.httpStatus;
112
+ this.endpoint = init.endpoint;
113
+ this.fields = init.fields;
114
+ this.retryAfterSeconds = init.retryAfterSeconds;
115
+ }
116
+ diagnosticDetails() {
117
+ return {
118
+ httpStatus: this.httpStatus,
119
+ endpoint: this.endpoint,
120
+ fields: this.fields,
121
+ retryAfterSeconds: this.retryAfterSeconds
122
+ };
123
+ }
124
+ };
125
+ /**
126
+ * The response did not match the endpoint's declared contract. After a POST the operation may
127
+ * have executed: reconcile through the method's documented status read.
128
+ *
129
+ * @example
130
+ * catch (error) {
131
+ * if (error instanceof PaylovProtocolError) metrics.increment('paylov.protocol', error.toJSON());
132
+ * throw error;
133
+ * }
134
+ */
135
+ var PaylovProtocolError = class extends PaylovBaseError {
136
+ name = "PaylovProtocolError";
137
+ kind = "protocol";
138
+ code;
139
+ httpStatus;
140
+ endpoint;
141
+ /** The decoded location that failed, e.g. `result.card.status`; never its value. */
142
+ path;
143
+ constructor(init) {
144
+ super(init.code === "sdk_malformed_response" ? `Paylov response for ${init.endpoint} has an unexpected shape` + (init.path !== void 0 ? ` at "${init.path}"` : "") : `Paylov returned HTTP ${init.httpStatus} for ${init.endpoint} without a usable error body`);
145
+ this.code = init.code;
146
+ this.httpStatus = init.httpStatus;
147
+ this.endpoint = init.endpoint;
148
+ this.path = init.path;
149
+ }
150
+ diagnosticDetails() {
151
+ return {
152
+ httpStatus: this.httpStatus,
153
+ endpoint: this.endpoint,
154
+ path: this.path
155
+ };
156
+ }
157
+ };
158
+ const CONNECTION_MESSAGES = {
159
+ sdk_timeout: "Paylov request timed out",
160
+ sdk_network_error: "Paylov request failed before the response was fully received",
161
+ sdk_aborted: "Paylov request was aborted by the caller"
162
+ };
163
+ /**
164
+ * No usable response: DNS, TCP or TLS failure, a reset, the SDK timeout, or the caller's abort.
165
+ * The underlying error is discarded: an injected transport can embed URLs, headers, bodies and
166
+ * credentials anywhere in it. Once `isSent`, the operation of a POST may have executed.
167
+ *
168
+ * @example
169
+ * catch (error) {
170
+ * if (error instanceof PaylovConnectionError && error.code === 'sdk_timeout') {
171
+ * metrics.increment('paylov.timeout', { endpoint: error.endpoint });
172
+ * }
173
+ * throw error;
174
+ * }
175
+ */
176
+ var PaylovConnectionError = class extends PaylovBaseError {
177
+ name = "PaylovConnectionError";
178
+ kind = "connection";
179
+ code;
180
+ endpoint;
181
+ /**
182
+ * Whether an attempt of the call reached the transport. `false` only for an `sdk_aborted` that
183
+ * fired before anything was sent, so nothing can have executed.
184
+ */
185
+ isSent;
186
+ /** For `sdk_timeout` only: the per-attempt deadline that expired. */
187
+ timeoutMs;
188
+ constructor(init) {
189
+ const message = init.isSent ? CONNECTION_MESSAGES[init.code] : `${CONNECTION_MESSAGES[init.code]} before it was sent`;
190
+ super(init.timeoutMs !== void 0 ? `${message} after ${init.timeoutMs} ms` : message);
191
+ this.code = init.code;
192
+ this.endpoint = init.endpoint;
193
+ this.isSent = init.isSent;
194
+ this.timeoutMs = init.timeoutMs;
195
+ }
196
+ diagnosticDetails() {
197
+ return {
198
+ endpoint: this.endpoint,
199
+ isSent: this.isSent,
200
+ timeoutMs: this.timeoutMs
201
+ };
202
+ }
203
+ };
204
+ /** `sdk_invalid_input` for a method parameter. */
205
+ function invalidInput(message, field, rule) {
206
+ return new PaylovInputError({
207
+ code: "sdk_invalid_input",
208
+ message,
209
+ field,
210
+ rule
211
+ });
212
+ }
213
+ /** `sdk_invalid_amount` for an amount parameter. */
214
+ function invalidAmount(message, field, rule) {
215
+ return new PaylovInputError({
216
+ code: "sdk_invalid_amount",
217
+ message,
218
+ field,
219
+ rule
220
+ });
221
+ }
222
+ /** `sdk_config_error` for constructor configuration. */
223
+ function configError(message, field, rule) {
224
+ return new PaylovInputError({
225
+ code: "sdk_config_error",
226
+ message,
227
+ field,
228
+ rule
229
+ });
230
+ }
231
+ function clientClosedError() {
232
+ return new PaylovClientClosedError();
233
+ }
234
+ /** `sdk_malformed_response` for a 2xx body that does not match its documented shape. */
235
+ function malformedResponse(context, path) {
236
+ return new PaylovProtocolError({
237
+ code: "sdk_malformed_response",
238
+ ...context,
239
+ path
240
+ });
241
+ }
242
+ /** `sdk_unexpected_status` for a non-2xx without a usable error body. */
243
+ function unexpectedStatus(context) {
244
+ return new PaylovProtocolError({
245
+ code: "sdk_unexpected_status",
246
+ ...context
247
+ });
248
+ }
249
+ /** `sdk_aborted` for the caller's abort; `isSent` once an attempt of the call reached fetch. */
250
+ function abortedError(endpoint, isSent) {
251
+ return new PaylovConnectionError({
252
+ code: "sdk_aborted",
253
+ endpoint,
254
+ isSent
255
+ });
256
+ }
257
+ /**
258
+ * True for anything this SDK throws; narrows to the {@link PaylovError} union.
259
+ *
260
+ * @example
261
+ * catch (error) {
262
+ * if (!isPaylovError(error)) throw error;
263
+ * metrics.increment('paylov.failure', { kind: error.kind, code: error.code });
264
+ * }
265
+ */
266
+ function isPaylovError(error) {
267
+ return error instanceof PaylovBaseError;
268
+ }
269
+ /**
270
+ * True when the operation may have executed although the call failed: a protocol error, a
271
+ * connection error once a request was sent, or a gateway error with HTTP status 500 or above.
272
+ * Reconcile such a call through the method's documented status read before repeating it. False
273
+ * for input and closed-client errors, for an abort before anything was sent, for other gateway
274
+ * errors, and for anything the SDK did not throw.
275
+ *
276
+ * @example
277
+ * catch (error) {
278
+ * if (isPaylovOutcomeUnknown(error)) return queueReconciliation(transactionId);
279
+ * throw error;
280
+ * }
281
+ */
282
+ function isPaylovOutcomeUnknown(error) {
283
+ if (!isPaylovError(error)) return false;
284
+ if (error.kind === "api") return error.httpStatus >= 500;
285
+ if (error.kind === "connection") return error.isSent;
286
+ return error.kind === "protocol";
287
+ }
288
+ function isPaylovApiError(error, ...codes) {
289
+ return error instanceof PaylovApiError && (codes.length === 0 || codes.includes(error.code));
290
+ }
291
+ // src/core/numbers.ts
292
+ /** Number guards shared by money, time and decoding. */
293
+ /** A count, an id, a timestamp in seconds, or an amount in a minor unit. */
294
+ function isNonNegativeSafeInteger(value) {
295
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
296
+ }
297
+ // src/core/money.ts
298
+ /** Integer-tiyin money guards and converters (1 SUM = 100 tiyin). No float touches an amount. */
299
+ const DECIMAL_SUM = /^(\d+)(?:\.(\d{1,2}))?$/;
300
+ /** Every public amount and every wire minor-unit amount is a non-negative safe integer. */
301
+ const isTiyin = isNonNegativeSafeInteger;
302
+ /**
303
+ * Validates a caller amount. `label` prefixes the message (a method context); messages never
304
+ * quote a rejected value.
305
+ */
306
+ function readTiyin(value, field, label = field) {
307
+ if (value === void 0) throw invalidAmount(`${label} is required`, field, "required");
308
+ if (!isTiyin(value)) throw invalidAmount(`${label} must be a non-negative safe integer`, field, "type");
309
+ return value;
310
+ }
311
+ /** A wire SUM amount as tiyin, or `undefined` when it is not a non-negative safe whole SUM. */
312
+ function wireSumToTiyin(sum) {
313
+ if (!isNonNegativeSafeInteger(sum)) return void 0;
314
+ const amountTiyin = sum * 100;
315
+ return Number.isSafeInteger(amountTiyin) ? amountTiyin : void 0;
316
+ }
317
+ /** A tiyin amount as wire whole SUM, or `undefined` when it is not a whole SUM amount. */
318
+ function tiyinToWireSum(amountTiyin) {
319
+ return isTiyin(amountTiyin) && amountTiyin % 100 === 0 ? amountTiyin / 100 : void 0;
320
+ }
321
+ /**
322
+ * Converts SUM to tiyin exactly: a whole-SUM safe integer, or a decimal string with at most two
323
+ * fraction digits. Pass a string for fractional SUM; a fractional number is rejected.
324
+ *
325
+ * @throws {@link PaylovInputError} `sdk_invalid_amount` for a negative, fractional or unsafe
326
+ * number, a malformed string, or a result too large to express in tiyin.
327
+ *
328
+ * @example
329
+ * sumToTiyin(1000); // 100000
330
+ * sumToTiyin('12.5'); // 1250
331
+ * sumToTiyin(10.5); // throws PaylovInputError sdk_invalid_amount
332
+ */
333
+ function sumToTiyin(sum) {
334
+ if (typeof sum === "number") {
335
+ const amountTiyin = wireSumToTiyin(sum);
336
+ if (amountTiyin === void 0) throw invalidAmount("sum must be a non-negative whole SUM safe integer", "sum", "type");
337
+ return amountTiyin;
338
+ }
339
+ const match = typeof sum === "string" ? DECIMAL_SUM.exec(sum) : null;
340
+ if (match === null) throw invalidAmount("sum must be a decimal string with at most 2 fraction digits", "sum", "format");
341
+ const [, whole = "", fraction = ""] = match;
342
+ const amountTiyin = Number(whole) * 100 + Number(fraction.padEnd(2, "0"));
343
+ if (!Number.isSafeInteger(amountTiyin)) throw invalidAmount("sum is too large to express in tiyin", "sum", "range");
344
+ return amountTiyin;
345
+ }
346
+ /**
347
+ * Formats a tiyin amount for display: ASCII-space thousands, `.` decimals, always two decimals.
348
+ * Locale-independent, so output is identical on every Node ICU build. Never send it on the wire.
349
+ *
350
+ * @throws {@link PaylovInputError} `sdk_invalid_amount` when `amountTiyin` is not a non-negative
351
+ * safe integer, so validate computed values such as balance deltas before display.
352
+ *
353
+ * @example
354
+ * formatSum(2_500_000); // '25 000.00'
355
+ * formatSum(5); // '0.05'
356
+ */
357
+ function formatSum(amountTiyin) {
358
+ readTiyin(amountTiyin, "amountTiyin");
359
+ const digits = String(amountTiyin).padStart(3, "0");
360
+ return `${digits.slice(0, -2).replace(/\B(?=(\d{3})+(?!\d))/g, " ")}.${digits.slice(-2)}`;
361
+ }
362
+ // src/core/time.ts
363
+ /**
364
+ * Strict wire timestamp parsers. Each returns `undefined` for a malformed string or an impossible
365
+ * calendar date. Tashkent is a fixed +05:00 offset without DST, so no time-zone database is
366
+ * consulted.
367
+ */
368
+ const LOCAL_DATE_TIME = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/;
369
+ const ISO_DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;
370
+ const MINUTE_MS = 6e4;
371
+ /** Capture groups 1–6 as wall-clock components. */
372
+ function wallClockOf(match) {
373
+ const at = (group) => Number(match[group]);
374
+ return [
375
+ at(1),
376
+ at(2),
377
+ at(3),
378
+ at(4),
379
+ at(5),
380
+ at(6)
381
+ ];
382
+ }
383
+ /**
384
+ * Epoch milliseconds of wall-clock components read as UTC, or `undefined` when they do not
385
+ * round-trip (Feb 30, hour 24, ...). `setUTCFullYear` keeps years below 100 literal.
386
+ */
387
+ function wallClockMs(parts) {
388
+ const [year, month, day, hour, minute, second] = parts;
389
+ const date = /* @__PURE__ */ new Date(0);
390
+ date.setUTCFullYear(year, month - 1, day);
391
+ date.setUTCHours(hour, minute, second, 0);
392
+ return [
393
+ date.getUTCFullYear(),
394
+ date.getUTCMonth() + 1,
395
+ date.getUTCDate(),
396
+ date.getUTCHours(),
397
+ date.getUTCMinutes(),
398
+ date.getUTCSeconds()
399
+ ].every((value, index) => value === parts[index]) ? date.getTime() : void 0;
400
+ }
401
+ /** A four-digit year plus an offset of under a day always lies inside the `Date` range. */
402
+ function parseLocal(value, offsetMinutes) {
403
+ const match = LOCAL_DATE_TIME.exec(value);
404
+ const ms = match === null ? void 0 : wallClockMs(wallClockOf(match));
405
+ return ms === void 0 ? void 0 : /* @__PURE__ */ new Date(ms - offsetMinutes * MINUTE_MS);
406
+ }
407
+ /** `YYYY-MM-DD HH:mm:ss` in Tashkent time. */
408
+ function parseTashkentDateTime(value) {
409
+ return parseLocal(value, 300);
410
+ }
411
+ /** `YYYY-MM-DD HH:mm:ss` in UTC. */
412
+ function parseUtcDateTime(value) {
413
+ return parseLocal(value, 0);
414
+ }
415
+ /** Minutes east of UTC for groups 8–10 of an ISO match; `Z` leaves them unset. */
416
+ function isoOffsetMinutes(match) {
417
+ if (match[8] === void 0) return 0;
418
+ const hours = Number(match[9]);
419
+ const minutes = Number(match[10]);
420
+ if (hours > 23 || minutes > 59) return void 0;
421
+ return (match[8] === "-" ? -1 : 1) * (hours * 60 + minutes);
422
+ }
423
+ /** ISO 8601 with `Z` or `±HH:MM`; fractions beyond milliseconds are truncated. */
424
+ function parseIsoDateTime(value) {
425
+ const match = ISO_DATE_TIME.exec(value);
426
+ if (match === null) return void 0;
427
+ const ms = wallClockMs(wallClockOf(match));
428
+ const offset = isoOffsetMinutes(match);
429
+ if (ms === void 0 || offset === void 0) return void 0;
430
+ const fractionMs = Number((match[7] ?? "").padEnd(3, "0").slice(0, 3));
431
+ return /* @__PURE__ */ new Date(ms + fractionMs - offset * MINUTE_MS);
432
+ }
433
+ /** Non-negative safe-integer unix seconds inside the `Date` range. */
434
+ function fromUnixSeconds(value) {
435
+ if (!isNonNegativeSafeInteger(value)) return void 0;
436
+ const date = /* @__PURE__ */ new Date(value * 1e3);
437
+ return Number.isFinite(date.getTime()) ? date : void 0;
438
+ }
439
+ // src/core/decoding.ts
440
+ /**
441
+ * Response decoding primitives. A decoder takes the value and the path reported on failure, and
442
+ * throws {@link DecodeFailure}, which only {@link decodePayload} turns into a public error.
443
+ * Rejected values never enter errors: only the path does.
444
+ */
445
+ /** A decoded value broke its decoder at `path`. Internal: never surfaced as it is. */
446
+ var DecodeFailure = class extends Error {
447
+ path;
448
+ constructor(path) {
449
+ super(`undecodable value at "${path}"`);
450
+ this.path = path;
451
+ }
452
+ };
453
+ /**
454
+ * Decodes a response payload from `root` (`result` or `body`); a failure becomes
455
+ * `sdk_malformed_response` at its path, with the response's endpoint and status.
456
+ */
457
+ function decodePayload(response, root, decode) {
458
+ try {
459
+ return decode(response.payload, root);
460
+ } catch (error) {
461
+ if (error instanceof DecodeFailure) throw malformedResponse(response.context, error.path);
462
+ throw error;
463
+ }
464
+ }
465
+ /** A canonical UUID in either case. */
466
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
467
+ /** Deeper JSON is rejected instead of copied: recursion this deep would overflow the stack. */
468
+ const MAX_JSON_DEPTH = 64;
469
+ /** 4 to 6 leading digits, a `*` mask, the last 4 (docs 6+4, DEV 4+4). */
470
+ const MASKED_PAN = /^\d{4,6}\*+\d{4}$/;
471
+ /** A non-array object. */
472
+ function isRecord(value) {
473
+ return typeof value === "object" && value !== null && !Array.isArray(value);
474
+ }
475
+ function isUuid(value) {
476
+ return typeof value === "string" && UUID.test(value);
477
+ }
478
+ /**
479
+ * Copies a parsed JSON tree into typed JSON values; `undefined` when it holds anything else or
480
+ * nests deeper than 64 levels.
481
+ */
482
+ function toJsonValue(value, depth = 0) {
483
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
484
+ if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
485
+ if (depth >= MAX_JSON_DEPTH) return void 0;
486
+ if (Array.isArray(value)) {
487
+ const items = [];
488
+ for (const item of value) {
489
+ const json = toJsonValue(item, depth + 1);
490
+ if (json === void 0) return void 0;
491
+ items.push(json);
492
+ }
493
+ return items;
494
+ }
495
+ return isRecord(value) ? toJsonObject(value, depth) : void 0;
496
+ }
497
+ function toJsonObject(value, depth = 0) {
498
+ const entries = [];
499
+ for (const [key, child] of Object.entries(value)) {
500
+ const json = toJsonValue(child, depth + 1);
501
+ if (json === void 0) return void 0;
502
+ entries.push([key, json]);
503
+ }
504
+ return Object.fromEntries(entries);
505
+ }
506
+ function asRecord(value, path) {
507
+ if (!isRecord(value)) throw new DecodeFailure(path);
508
+ return value;
509
+ }
510
+ function readFields(value, path) {
511
+ const record = asRecord(value, path);
512
+ return (key, decode) => decode(record[key], `${path}.${key}`);
513
+ }
514
+ /** Decodes the single field `key` of a record. */
515
+ function fieldOf(key, decode) {
516
+ return (value, path) => readFields(value, path)(key, decode);
517
+ }
518
+ function asString(value, path) {
519
+ if (typeof value !== "string") throw new DecodeFailure(path);
520
+ return value;
521
+ }
522
+ function asNonEmptyString(value, path) {
523
+ const text = asString(value, path);
524
+ if (text === "") throw new DecodeFailure(path);
525
+ return text;
526
+ }
527
+ function asUuid(value, path) {
528
+ if (!isUuid(value)) throw new DecodeFailure(path);
529
+ return value;
530
+ }
531
+ function asBoolean(value, path) {
532
+ if (typeof value !== "boolean") throw new DecodeFailure(path);
533
+ return value;
534
+ }
535
+ /** A count, an id or a lifetime in seconds. */
536
+ function asNonNegativeInteger(value, path) {
537
+ if (!isNonNegativeSafeInteger(value)) throw new DecodeFailure(path);
538
+ return value;
539
+ }
540
+ /** A wire amount already in tiyin. */
541
+ const asTiyin = asNonNegativeInteger;
542
+ /** A wire amount in whole SUM, as tiyin. */
543
+ function asTiyinFromSum(value, path) {
544
+ const amountTiyin = wireSumToTiyin(value);
545
+ if (amountTiyin === void 0) throw new DecodeFailure(path);
546
+ return amountTiyin;
547
+ }
548
+ /** Anything else may be a full PAN, so it is rejected without being retained. */
549
+ function asMaskedPan(value, path) {
550
+ const pan = asString(value, path);
551
+ if (!MASKED_PAN.test(pan)) throw new DecodeFailure(path);
552
+ return pan;
553
+ }
554
+ /** One of a closed set of wire values. Response unions stay open: use this for wire literals. */
555
+ function asLiteral(...values) {
556
+ return (value, path) => {
557
+ const match = values.find((candidate) => candidate === value);
558
+ if (match === void 0) throw new DecodeFailure(path);
559
+ return match;
560
+ };
561
+ }
562
+ function asJsonObject(value, path) {
563
+ const json = toJsonObject(asRecord(value, path));
564
+ if (json === void 0) throw new DecodeFailure(path);
565
+ return json;
566
+ }
567
+ /** A documented `T | null` field; an absent key is malformed. */
568
+ function nullable(decode) {
569
+ return (value, path) => value === null ? null : decode(value, path);
570
+ }
571
+ /** A field the gateway may omit or null; both read as `null`. */
572
+ function nullish(decode) {
573
+ return (value, path) => value === null || value === void 0 ? null : decode(value, path);
574
+ }
575
+ /** Decodes each item, reporting failures at `<path>[<index>]`. */
576
+ function arrayOf(decodeItem) {
577
+ return (value, path) => {
578
+ if (!Array.isArray(value)) throw new DecodeFailure(path);
579
+ return value.map((item, index) => decodeItem(item, `${path}[${index}]`));
580
+ };
581
+ }
582
+ function dateDecoder(parse) {
583
+ return (value, path) => {
584
+ const date = parse(asString(value, path));
585
+ if (date === void 0) throw new DecodeFailure(path);
586
+ return date;
587
+ };
588
+ }
589
+ /** `YYYY-MM-DD HH:mm:ss` in Tashkent time (fixed +05:00). */
590
+ const asTashkentDateTime = dateDecoder(parseTashkentDateTime);
591
+ /** `YYYY-MM-DD HH:mm:ss` in UTC. */
592
+ const asUtcDateTime = dateDecoder(parseUtcDateTime);
593
+ /** ISO 8601 with an explicit offset. */
594
+ const asIsoDateTime = dateDecoder(parseIsoDateTime);
595
+ /** Non-negative integer Unix seconds, as a JSON number. */
596
+ const asUnixDateTime = (value, path) => {
597
+ const date = typeof value === "number" ? fromUnixSeconds(value) : void 0;
598
+ if (date === void 0) throw new DecodeFailure(path);
599
+ return date;
600
+ };
601
+ // src/core/errorDetails.ts
602
+ /**
603
+ * Closed decoders for the few facts a gateway `error` carries beyond its code. `message` is never
604
+ * read: Paylov documents it as display text not to be parsed. Everything in `data` but field names
605
+ * and the card-block delay is discarded: upstream integrations (Didox, WLCM) embed third-party
606
+ * text and values there.
607
+ */
608
+ const MAX_FIELDS = 32;
609
+ const FIELD_SEGMENT = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
610
+ const INDEX_SEGMENT = /^\d{1,9}$/;
611
+ const RETRY_AFTER_HEADER = /^\d{1,4}$/;
612
+ const MAX_RETRY_AFTER_SECONDS = 3600;
613
+ /** A numeric key is an array index only below a named key; top level it is a JSON offset. */
614
+ function isFieldSegment(key, depth) {
615
+ return FIELD_SEGMENT.test(key) || depth > 0 && INDEX_SEGMENT.test(key);
616
+ }
617
+ /** Flattens the key paths of a validation `data` map, keeping names only. */
618
+ function collectFieldPaths(value, prefix, paths) {
619
+ if (paths.length >= MAX_FIELDS) return;
620
+ if (isRecord(value)) {
621
+ for (const [key, child] of Object.entries(value)) if (isFieldSegment(key, prefix.length)) collectFieldPaths(child, [...prefix, key], paths);
622
+ return;
623
+ }
624
+ if (Array.isArray(value) && value.some(isRecord)) {
625
+ value.forEach((child, index) => {
626
+ if (isRecord(child)) collectFieldPaths(child, [...prefix, String(index)], paths);
627
+ });
628
+ return;
629
+ }
630
+ if (prefix.length > 0 && paths.length < MAX_FIELDS) paths.push(prefix.join("."));
631
+ }
632
+ function isFieldPath(value) {
633
+ return typeof value === "string" && value.split(".").every((segment, depth) => isFieldSegment(segment, depth));
634
+ }
635
+ /**
636
+ * `validation_error` maps field names to messages; `field_not_valid` and `field_required` name one
637
+ * field as `data.field`. Live, `field_not_valid` also sends the bare name and `field_required`
638
+ * sends no `data` at all.
639
+ */
640
+ function decodeFields(code, data) {
641
+ switch (code) {
642
+ case "validation_error": {
643
+ const paths = [];
644
+ collectFieldPaths(data, [], paths);
645
+ return paths;
646
+ }
647
+ case "field_not_valid":
648
+ case "field_required": {
649
+ const field = isRecord(data) ? data["field"] : data;
650
+ return isFieldPath(field) ? [field] : [];
651
+ }
652
+ default: return [];
653
+ }
654
+ }
655
+ function asRetryDelay(seconds) {
656
+ return typeof seconds === "number" && Number.isInteger(seconds) && seconds >= 1 && seconds <= MAX_RETRY_AFTER_SECONDS ? seconds : void 0;
657
+ }
658
+ /** Only the delta-seconds form of `Retry-After`; an HTTP-date reports no delay. */
659
+ function decodeRateLimitDelay(retryAfter) {
660
+ const header = retryAfter?.trim();
661
+ return header !== void 0 && RETRY_AFTER_HEADER.test(header) ? asRetryDelay(Number(header)) : void 0;
662
+ }
663
+ /** A blocked card reports the rest of its block as `data.sec_to_retry`. */
664
+ function decodeCardBlockDelay(data) {
665
+ return asRetryDelay(isRecord(data) ? data["sec_to_retry"] : void 0);
666
+ }
667
+ function decodeRetryAfter(code, data, retryAfter) {
668
+ if (code === "rate_limit_exceeded") return decodeRateLimitDelay(retryAfter);
669
+ if (code === "card_is_blocked") return decodeCardBlockDelay(data);
670
+ }
671
+ /**
672
+ * The public details of one enveloped gateway error; absent facts are `undefined`. `retryAfter`
673
+ * is the response's `Retry-After` header, the only header read.
674
+ */
675
+ function decodeErrorDetails(code, error, retryAfter) {
676
+ const fields = decodeFields(code, error["data"]);
677
+ const retryAfterSeconds = decodeRetryAfter(code, error["data"], retryAfter);
678
+ return {
679
+ fields: fields.length > 0 ? fields : void 0,
680
+ retryAfterSeconds
681
+ };
682
+ }
683
+ // src/core/envelope.ts
684
+ /**
685
+ * The only interpreter of raw Paylov response bodies. Every observed REST failure, the token,
686
+ * revoke and onboarding endpoints included, is `{result: null, error: {code, message, data?}}`.
687
+ * Success depends on the shape the endpoint declares; the SDK never guesses it.
688
+ */
689
+ const WIRE_ERROR_CODE = /^[a-z][a-z0-9_]{0,127}$/;
690
+ /** Error codes are identifiers, never arbitrary response text. */
691
+ function isWireErrorCode(value) {
692
+ return typeof value === "string" && WIRE_ERROR_CODE.test(value);
693
+ }
694
+ function isSuccessStatus(httpStatus) {
695
+ return httpStatus >= 200 && httpStatus < 300;
696
+ }
697
+ /** The validated `error.code` a body carries, for logger events and the 401 replay rule. */
698
+ function envelopeErrorCode(body) {
699
+ const error = isRecord(body) ? body["error"] : void 0;
700
+ const code = isRecord(error) ? error["code"] : void 0;
701
+ return isWireErrorCode(code) ? code : void 0;
702
+ }
703
+ /** A body that is neither a declared success nor a decodable error. */
704
+ function unusableBody(context) {
705
+ return isSuccessStatus(context.httpStatus) ? malformedResponse(context) : unexpectedStatus(context);
706
+ }
707
+ function apiError(code, error, context, retryAfter) {
708
+ return new PaylovApiError({
709
+ code,
710
+ ...context,
711
+ ...decodeErrorDetails(code, error, retryAfter)
712
+ });
713
+ }
714
+ function unwrapResult(body, context) {
715
+ const result = body["result"];
716
+ if (result === null || result === void 0) throw malformedResponse(context, "result");
717
+ return result;
718
+ }
719
+ function successPayload(body, context, shape) {
720
+ if (shape === "array") {
721
+ if (!Array.isArray(body)) throw malformedResponse(context);
722
+ return body;
723
+ }
724
+ if (!isRecord(body)) throw malformedResponse(context);
725
+ if (shape === "flat") return body;
726
+ return unwrapResult(body, context);
727
+ }
728
+ /**
729
+ * Returns the success payload as `unknown` for the owning decoder, or throws: `PaylovApiError`
730
+ * for a decodable `error`, `PaylovProtocolError` for anything else. `retryAfter` is the
731
+ * response's `Retry-After` header.
732
+ */
733
+ function normalizeResponse(body, context, shape, retryAfter) {
734
+ const error = isRecord(body) ? body["error"] : void 0;
735
+ if (error !== null && error !== void 0) {
736
+ const code = isRecord(error) ? error["code"] : void 0;
737
+ if (!isRecord(error) || !isWireErrorCode(code)) throw unusableBody(context);
738
+ throw apiError(code, error, context, retryAfter);
739
+ }
740
+ if (!isSuccessStatus(context.httpStatus)) throw unexpectedStatus(context);
741
+ return successPayload(body, context, shape);
742
+ }
743
+ // src/core/lifecycle.ts
744
+ /** Client open/closed state and caller cancellation, shared by the transport and token manager. */
745
+ /**
746
+ * The open/closed state one `PaylovClient` shares across its transports and token manager.
747
+ * Closing never aborts a request already sent; it refuses every later send.
748
+ */
749
+ var ClientLifecycle = class {
750
+ #closed = false;
751
+ get closed() {
752
+ return this.#closed;
753
+ }
754
+ close() {
755
+ this.#closed = true;
756
+ }
757
+ assertOpen() {
758
+ if (this.#closed) throw clientClosedError();
759
+ }
760
+ };
761
+ /** Rejects a wait once its signal fires; never surfaced, so it carries nothing. */
762
+ var AbortedWait = class extends Error {};
763
+ /**
764
+ * Settles with `promise`, or rejects once `signal` aborts, whichever comes first. Raced against
765
+ * fetch and the body read, so the deadline holds even for a fetch that ignores its signal.
766
+ */
767
+ function raceAbort(promise, signal) {
768
+ return new Promise((resolve, reject) => {
769
+ const onAbort = () => {
770
+ reject(new AbortedWait());
771
+ };
772
+ if (signal.aborted) onAbort();
773
+ signal.addEventListener("abort", onAbort, { once: true });
774
+ promise.then(resolve, reject).finally(() => {
775
+ signal.removeEventListener("abort", onAbort);
776
+ });
777
+ });
778
+ }
779
+ /**
780
+ * Waits for `promise` unless the caller's `signal` aborts first, then rejects with `aborted()`.
781
+ * Only the wait is abandoned: a shared operation behind `promise` (a token grant) keeps running
782
+ * for its other waiters.
783
+ */
784
+ async function untilAborted(promise, signal, aborted) {
785
+ if (signal === void 0) return promise;
786
+ try {
787
+ return await raceAbort(promise, signal);
788
+ } catch (error) {
789
+ if (signal.aborted) throw aborted();
790
+ throw error;
791
+ }
792
+ }
793
+ // src/core/http.ts
794
+ /** Transport: URL construction, deadlines, abort, metadata logging, GET-only retries, 401 replay. */
795
+ const DEFAULT_TIMEOUT_MS = 3e4;
796
+ const MAX_RETRIES = 2;
797
+ const BASE_DELAY_MS = 200;
798
+ /**
799
+ * Transient gateway failures. 429 is excluded: the token endpoint asks for tens of seconds
800
+ * (`retryAfterSeconds`), which a sub-second backoff would only spend against the same window.
801
+ */
802
+ const RETRYABLE_STATUSES = /* @__PURE__ */ new Set([
803
+ 500,
804
+ 502,
805
+ 503,
806
+ 504
807
+ ]);
808
+ const RATE_LIMITED = 429;
809
+ /** Whether a GET that received `httpStatus` is retried. */
810
+ function isRetryableStatus(httpStatus) {
811
+ return RETRYABLE_STATUSES.has(httpStatus);
812
+ }
813
+ function noop() {}
814
+ /** A logger, sync or async, must never delay or fail a request. */
815
+ function callHookSafely(run) {
816
+ Promise.try(run).catch(noop);
817
+ }
818
+ /** Opens one logged attempt; the returned function closes it. */
819
+ function logAttempt(logger, method, endpoint, attempt) {
820
+ const event = {
821
+ method,
822
+ endpoint,
823
+ attempt
824
+ };
825
+ if (logger?.onRequest !== void 0) callHookSafely(() => logger.onRequest?.(event));
826
+ const startedAt = Date.now();
827
+ return (httpStatus, errorCode) => {
828
+ if (logger?.onResponse === void 0) return;
829
+ const response = {
830
+ ...event,
831
+ httpStatus,
832
+ durationMs: Date.now() - startedAt,
833
+ ...errorCode !== void 0 ? { errorCode } : {}
834
+ };
835
+ callHookSafely(() => logger.onResponse?.(response));
836
+ };
837
+ }
838
+ /** The static identity logs and errors carry, e.g. `"GET /merchant/userCard/getCard/{cardId}/"`. */
839
+ function endpointName(endpoint) {
840
+ return `${endpoint.method} ${endpoint.route}`;
841
+ }
842
+ /** Rejects a lone surrogate before `encodeURIComponent` throws an unwrapped native error. */
843
+ function encodeComponent(value, field) {
844
+ if (!value.isWellFormed()) throw invalidInput(`${field} must contain well-formed Unicode`, field, "format");
845
+ return encodeURIComponent(value);
846
+ }
847
+ /** Keeps an identifier inside one path segment; URL parsers normalize even encoded dot segments. */
848
+ function encodePathSegment(value, field) {
849
+ if (value === "." || value === "..") throw invalidInput(`${field} must not be a dot path segment`, field, "format");
850
+ return encodeComponent(value, field);
851
+ }
852
+ /** The route with each `{name}` filled; failures name the placeholder, the SDK parameter. */
853
+ function fillRoute(route, values = {}) {
854
+ let path = route;
855
+ for (const [name, value] of Object.entries(values)) {
856
+ const segment = encodePathSegment(value, name);
857
+ path = path.replace(`{${name}}`, () => segment);
858
+ }
859
+ return path;
860
+ }
861
+ function buildUrl(origin, route, options) {
862
+ const path = fillRoute(route, options.path);
863
+ const pairs = Object.entries(options.query ?? {}).flatMap(([key, value]) => value === void 0 ? [] : [`${encodeURIComponent(key)}=${encodeComponent(String(value), key)}`]);
864
+ return pairs.length > 0 ? `${origin}${path}?${pairs.join("&")}` : `${origin}${path}`;
865
+ }
866
+ function requestHeaders(custom = {}, hasBody) {
867
+ return {
868
+ accept: "application/json",
869
+ ...custom,
870
+ ...hasBody ? { "content-type": "application/json" } : {}
871
+ };
872
+ }
873
+ /** Unparseable bodies become `undefined`; the normalizer classifies them by status. */
874
+ async function readJson(response) {
875
+ const raw = await response.text();
876
+ try {
877
+ return JSON.parse(raw);
878
+ } catch {
879
+ return;
880
+ }
881
+ }
882
+ function defaultSleep(ms, signal) {
883
+ return setTimeout(ms, void 0, signal === void 0 ? {} : { signal });
884
+ }
885
+ function failureCode(callerSignal, timeout) {
886
+ if (callerSignal?.aborted === true) return "sdk_aborted";
887
+ return timeout.aborted ? "sdk_timeout" : "sdk_network_error";
888
+ }
889
+ /** Whether a GET may retry: a connection failure other than an abort, or a transient status. */
890
+ function isTransientFailure(outcome) {
891
+ return outcome.kind === "failed" ? outcome.failure.code !== "sdk_aborted" : isRetryableStatus(outcome.response.status);
892
+ }
893
+ /**
894
+ * Only the gateway's own authentication rejection is replayed. Bearer authentication is expected
895
+ * to reject before any handler runs (an inference: every captured 401 answered a GET), so the
896
+ * rejected request should not have executed. A bare 401 (a proxy) proves nothing about the token.
897
+ * The token transport has no AuthProvider.
898
+ */
899
+ function isTokenRejection(outcome) {
900
+ return outcome.kind === "received" && outcome.response.status === 401 && outcome.errorCode === "permission_denied" && outcome.authorization !== void 0;
901
+ }
902
+ function prepareRequest(origin, endpoint, options) {
903
+ const body = options.body === void 0 ? void 0 : JSON.stringify(options.body);
904
+ return {
905
+ method: endpoint.method,
906
+ endpoint: endpointName(endpoint),
907
+ shape: endpoint.shape,
908
+ url: buildUrl(origin, endpoint.route, options),
909
+ headers: requestHeaders(options.headers, body !== void 0),
910
+ body,
911
+ signal: options.signal
912
+ };
913
+ }
914
+ /** Rechecked after the synchronous request hook, which may close the client or abort. */
915
+ function refusalAfterHook(lifecycle, signal, aborted) {
916
+ if (lifecycle?.closed === true) return clientClosedError();
917
+ return signal?.aborted === true ? aborted() : void 0;
918
+ }
919
+ function createHttpClient(config) {
920
+ const fetchImpl = config.fetch ?? ((input, init) => globalThis.fetch(input, init));
921
+ const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
922
+ const { auth, lifecycle, logger, origin } = config;
923
+ const sleep = config.sleep ?? defaultSleep;
924
+ const random = config.random ?? Math.random;
925
+ /** Exponential backoff for the 1-based retry number, with jitter in `[0.5, 1]`. */
926
+ function backoffMs(retryNumber) {
927
+ return BASE_DELAY_MS * 2 ** (retryNumber - 1) * (.5 + random() * .5);
928
+ }
929
+ /**
930
+ * One fetch and its body read under one deadline, so a gateway that sends headers and then
931
+ * stalls cannot hang the call. Every failure becomes a connection error without a cause.
932
+ */
933
+ async function exchange(url, init, endpoint, callerSignal) {
934
+ const timeout = AbortSignal.timeout(timeoutMs);
935
+ const signal = callerSignal === void 0 ? timeout : AbortSignal.any([timeout, callerSignal]);
936
+ const failed = () => {
937
+ const code = failureCode(callerSignal, timeout);
938
+ return {
939
+ kind: "failed",
940
+ failure: new PaylovConnectionError({
941
+ code,
942
+ endpoint,
943
+ isSent: true,
944
+ timeoutMs: code === "sdk_timeout" ? timeoutMs : void 0
945
+ })
946
+ };
947
+ };
948
+ let response;
949
+ try {
950
+ response = await raceAbort(fetchImpl(url, {
951
+ ...init,
952
+ signal
953
+ }), signal);
954
+ } catch {
955
+ return failed();
956
+ }
957
+ if (response.status >= 300 && response.status < 400) {
958
+ response.body?.cancel().catch(noop);
959
+ return {
960
+ kind: "received",
961
+ response,
962
+ body: void 0
963
+ };
964
+ }
965
+ try {
966
+ return {
967
+ kind: "received",
968
+ response,
969
+ body: await raceAbort(readJson(response), signal)
970
+ };
971
+ } catch {
972
+ return response.status === RATE_LIMITED && callerSignal?.aborted !== true ? {
973
+ kind: "received",
974
+ response,
975
+ body: void 0
976
+ } : failed();
977
+ }
978
+ }
979
+ /**
980
+ * One authorized, logged attempt. Refusals before the fetch throw; fetch failures return.
981
+ * `isSent` tells whether an earlier attempt of the call reached fetch.
982
+ */
983
+ async function sendAttempt(prepared, attempt, isSent) {
984
+ const { method, endpoint, signal } = prepared;
985
+ const aborted = () => abortedError(endpoint, isSent);
986
+ if (signal?.aborted === true) throw aborted();
987
+ const authorization = auth === void 0 ? void 0 : await untilAborted(auth.authorize(), signal, aborted);
988
+ lifecycle?.assertOpen();
989
+ const closeAttempt = logAttempt(logger, method, endpoint, attempt);
990
+ const refusal = refusalAfterHook(lifecycle, signal, aborted);
991
+ if (refusal !== void 0) {
992
+ closeAttempt(0, refusal.code);
993
+ throw refusal;
994
+ }
995
+ const init = {
996
+ method,
997
+ redirect: "manual",
998
+ headers: authorization === void 0 ? prepared.headers : {
999
+ ...prepared.headers,
1000
+ authorization: authorization.header
1001
+ },
1002
+ ...prepared.body !== void 0 ? { body: prepared.body } : {}
1003
+ };
1004
+ const outcome = await exchange(prepared.url, init, endpoint, signal);
1005
+ if (outcome.kind === "failed") {
1006
+ closeAttempt(0, outcome.failure.code);
1007
+ return outcome;
1008
+ }
1009
+ const errorCode = envelopeErrorCode(outcome.body);
1010
+ closeAttempt(outcome.response.status, errorCode);
1011
+ return {
1012
+ ...outcome,
1013
+ errorCode,
1014
+ authorization
1015
+ };
1016
+ }
1017
+ async function request(endpoint, options = {}) {
1018
+ const prepared = prepareRequest(origin, endpoint, options);
1019
+ const { signal } = prepared;
1020
+ const abortedAfterSend = () => abortedError(prepared.endpoint, true);
1021
+ const retryable = endpoint.method === "GET";
1022
+ let retriesUsed = 0;
1023
+ let replayed = false;
1024
+ let isSent = false;
1025
+ for (let attempt = 1;; attempt += 1) {
1026
+ const outcome = await sendAttempt(prepared, attempt, isSent);
1027
+ isSent = true;
1028
+ if (!replayed && isTokenRejection(outcome)) {
1029
+ replayed = true;
1030
+ auth?.invalidate(outcome.authorization.generation);
1031
+ continue;
1032
+ }
1033
+ if (retryable && retriesUsed < MAX_RETRIES && isTransientFailure(outcome)) {
1034
+ retriesUsed += 1;
1035
+ await untilAborted(sleep(backoffMs(retriesUsed), signal), signal, abortedAfterSend);
1036
+ continue;
1037
+ }
1038
+ if (outcome.kind === "failed") throw outcome.failure;
1039
+ const { response } = outcome;
1040
+ const context = {
1041
+ endpoint: prepared.endpoint,
1042
+ httpStatus: response.status
1043
+ };
1044
+ const retryAfter = response.headers.get("retry-after");
1045
+ return {
1046
+ payload: normalizeResponse(outcome.body, context, prepared.shape, retryAfter),
1047
+ context
1048
+ };
1049
+ }
1050
+ }
1051
+ return { request };
1052
+ }
1053
+ // src/core/auth.ts
1054
+ /**
1055
+ * OAuth2 token management and revocation. Every `oauth2` snake_case wire name stays here and in
1056
+ * `fake.ts`.
1057
+ */
1058
+ const ENDPOINTS$9 = {
1059
+ token: {
1060
+ method: "POST",
1061
+ route: "/merchant/oauth2/token/",
1062
+ shape: "flat"
1063
+ },
1064
+ revoke: {
1065
+ method: "POST",
1066
+ route: "/merchant/oauth2/revoke/",
1067
+ shape: "flat"
1068
+ }
1069
+ };
1070
+ const REVOKE_ENDPOINT = endpointName(ENDPOINTS$9.revoke);
1071
+ const REFRESH_MARGIN_MS = 6e4;
1072
+ /** Used when a token-endpoint 429 carries no usable `Retry-After` delay. */
1073
+ const DEFAULT_COOL_DOWN_SECONDS = 60;
1074
+ function ignore() {}
1075
+ /** Never surfaced: `close()` swallows it. */
1076
+ function abandonedClose() {
1077
+ return abortedError(REVOKE_ENDPOINT, false);
1078
+ }
1079
+ function basicAuthHeader(consumerKey, consumerSecret) {
1080
+ return `Basic ${Buffer.from(`${consumerKey}:${consumerSecret}`, "utf8").toString("base64")}`;
1081
+ }
1082
+ /**
1083
+ * A lifetime in seconds as the epoch-ms deadline from `issuedAt`. No upper cap: 3600 / 2592000
1084
+ * are today's values, and a guessed cap would fail every login if Paylov changed them. Only a
1085
+ * zero or unsafe deadline is rejected.
1086
+ */
1087
+ function deadlineFrom(issuedAt) {
1088
+ return (value, path) => {
1089
+ const lifetime = asNonNegativeInteger(value, path);
1090
+ const ms = issuedAt + lifetime * 1e3;
1091
+ if (lifetime === 0 || !Number.isSafeInteger(ms)) throw new DecodeFailure(path);
1092
+ return ms;
1093
+ };
1094
+ }
1095
+ /** Failures name the field, never its value: the same body holds the tokens. */
1096
+ function decodeTokenSet(issuedAt) {
1097
+ const asDeadline = deadlineFrom(issuedAt);
1098
+ return (value, path) => {
1099
+ const field = readFields(value, path);
1100
+ field("token_type", asNonEmptyString);
1101
+ return {
1102
+ accessToken: field("access_token", asNonEmptyString),
1103
+ refreshToken: field("refresh_token", asNonEmptyString),
1104
+ accessExpiresAt: field("expires_in", asDeadline),
1105
+ refreshExpiresAt: field("refresh_expires_in", asDeadline)
1106
+ };
1107
+ };
1108
+ }
1109
+ /**
1110
+ * Lazy, process-local, single-flight credential manager. It refreshes 60 s before expiry and
1111
+ * adopts each new pair at once, because a refresh rotates the refresh token.
1112
+ *
1113
+ * - A refresh rejected with `invalid_grant` falls back to one password grant. Nothing else does:
1114
+ * `invalid_client`, a 429 or a connection failure would fail the password grant too, and
1115
+ * failed password attempts lock the merchant account.
1116
+ * - An enveloped `invalid_grant` on the password grant is latched: every later `authorize()`
1117
+ * rethrows it without I/O. A bare 401/403 (a proxy) is not a credential verdict and does not.
1118
+ * - A token-endpoint HTTP 429 starts a cool-down, decoded envelope or not; until it ends
1119
+ * `authorize()` rethrows it without I/O.
1120
+ */
1121
+ var TokenManager = class {
1122
+ #config;
1123
+ #lifecycle;
1124
+ #now;
1125
+ #tokens;
1126
+ #generation = 0;
1127
+ #grant;
1128
+ #rejectedPassword;
1129
+ #coolDown;
1130
+ #closing;
1131
+ constructor(config) {
1132
+ this.#config = config;
1133
+ this.#lifecycle = config.lifecycle;
1134
+ this.#now = config.now ?? Date.now;
1135
+ }
1136
+ /** Callers race the shared grant against their own signal; this never takes one. */
1137
+ async authorize() {
1138
+ this.#lifecycle.assertOpen();
1139
+ if (this.#rejectedPassword !== void 0) throw this.#rejectedPassword;
1140
+ const coolDown = this.#coolDown;
1141
+ if (coolDown !== void 0 && this.#now() < coolDown.until) throw coolDown.error;
1142
+ const tokens = this.#tokens;
1143
+ if (tokens !== void 0 && this.#now() < tokens.accessExpiresAt - REFRESH_MARGIN_MS) return this.#context(tokens);
1144
+ return await this.#sharedGrant();
1145
+ }
1146
+ /** Expires only the access token of that generation, keeping the cheaper refresh grant. */
1147
+ invalidate(generation) {
1148
+ const tokens = this.#tokens;
1149
+ if (tokens !== void 0 && generation === this.#generation) this.#tokens = {
1150
+ ...tokens,
1151
+ accessExpiresAt: 0
1152
+ };
1153
+ }
1154
+ /**
1155
+ * Closes the lifecycle, waits for an in-flight grant to settle, then revokes the newest access
1156
+ * token held. Concurrent calls share one revocation; the signal abandons only this wait. Never
1157
+ * rejects: the revoke attempt's logger events report a failed revocation.
1158
+ */
1159
+ async close(signal) {
1160
+ this.#closing ??= this.#closeAndRevoke();
1161
+ await untilAborted(this.#closing, signal, abandonedClose).catch(ignore);
1162
+ }
1163
+ #sharedGrant() {
1164
+ if (this.#grant !== void 0) return this.#grant;
1165
+ const grant = Promise.withResolvers();
1166
+ this.#grant = grant.promise;
1167
+ this.#refreshOrLogin().finally(() => {
1168
+ this.#grant = void 0;
1169
+ }).then(grant.resolve, grant.reject);
1170
+ return grant.promise;
1171
+ }
1172
+ async #refreshOrLogin() {
1173
+ const tokens = this.#tokens;
1174
+ if (tokens !== void 0 && this.#now() < tokens.refreshExpiresAt) try {
1175
+ return await this.#requestTokens({
1176
+ grant_type: "refresh_token",
1177
+ refresh_token: tokens.refreshToken
1178
+ });
1179
+ } catch (error) {
1180
+ if (!isPaylovApiError(error, "invalid_grant")) throw error;
1181
+ this.#tokens = void 0;
1182
+ }
1183
+ this.#lifecycle.assertOpen();
1184
+ try {
1185
+ return await this.#requestTokens({
1186
+ grant_type: "password",
1187
+ username: this.#config.username,
1188
+ password: this.#config.password
1189
+ });
1190
+ } catch (error) {
1191
+ if (isPaylovApiError(error, "invalid_grant")) {
1192
+ this.#rejectedPassword = error;
1193
+ this.#tokens = void 0;
1194
+ }
1195
+ throw error;
1196
+ }
1197
+ }
1198
+ async #requestTokens(body) {
1199
+ const { http, consumerKey, consumerSecret } = this.#config;
1200
+ let response;
1201
+ try {
1202
+ response = await http.request(ENDPOINTS$9.token, {
1203
+ headers: { authorization: basicAuthHeader(consumerKey, consumerSecret) },
1204
+ body
1205
+ });
1206
+ } catch (error) {
1207
+ if ((error instanceof PaylovApiError || error instanceof PaylovProtocolError) && error.httpStatus === 429) this.#startCoolDown(error);
1208
+ throw error;
1209
+ }
1210
+ const tokens = decodePayload(response, "body", decodeTokenSet(this.#now()));
1211
+ this.#tokens = tokens;
1212
+ this.#generation += 1;
1213
+ this.#lifecycle.assertOpen();
1214
+ return this.#context(tokens);
1215
+ }
1216
+ #startCoolDown(error) {
1217
+ const seconds = (error instanceof PaylovApiError ? error.retryAfterSeconds : void 0) ?? DEFAULT_COOL_DOWN_SECONDS;
1218
+ this.#coolDown = {
1219
+ until: this.#now() + seconds * 1e3,
1220
+ error
1221
+ };
1222
+ }
1223
+ async #closeAndRevoke() {
1224
+ this.#lifecycle.close();
1225
+ await this.#grant?.catch(() => void 0);
1226
+ const accessToken = this.#tokens?.accessToken;
1227
+ this.#tokens = void 0;
1228
+ if (accessToken === void 0) return;
1229
+ await this.#config.http.request(ENDPOINTS$9.revoke, { body: { token: accessToken } }).catch(ignore);
1230
+ }
1231
+ #context(tokens) {
1232
+ return {
1233
+ header: `Bearer ${tokens.accessToken}`,
1234
+ generation: this.#generation
1235
+ };
1236
+ }
1237
+ };
1238
+ // src/core/config.ts
1239
+ /** Constructor configuration shared by the network surfaces: origin, timeout, fetch, logger. */
1240
+ /** Node timers support at most a signed 32-bit millisecond delay. */
1241
+ const MAX_TIMEOUT_MS = 2147483647;
1242
+ function isFetchLike(value) {
1243
+ return typeof value === "function";
1244
+ }
1245
+ /** The caller's own logger object is kept, so class-based hooks keep their receiver. */
1246
+ function assertLogger(value) {
1247
+ if (!isRecord(value)) throw configError("logger must be an object", "logger", "type");
1248
+ for (const name of ["onRequest", "onResponse"]) {
1249
+ const hook = value[name];
1250
+ if (hook !== void 0 && typeof hook !== "function") throw configError(`logger.${name} must be a function`, `logger.${name}`, "type");
1251
+ }
1252
+ }
1253
+ /** `timeoutMs`, `fetch` and `logger` from a configuration; only the options given. */
1254
+ function readTransportConfig(config) {
1255
+ const timeoutMs = config.optionalInteger("timeoutMs", {
1256
+ min: 1,
1257
+ max: MAX_TIMEOUT_MS
1258
+ });
1259
+ const fetch = config.raw("fetch");
1260
+ if (fetch !== void 0 && !isFetchLike(fetch)) throw configError("fetch must be a function", "fetch", "type");
1261
+ const logger = config.raw("logger");
1262
+ if (logger !== void 0) assertLogger(logger);
1263
+ return {
1264
+ ...timeoutMs !== void 0 ? { timeoutMs } : {},
1265
+ ...fetch !== void 0 ? { fetch } : {},
1266
+ ...logger !== void 0 ? { logger } : {}
1267
+ };
1268
+ }
1269
+ /**
1270
+ * A bare `https` origin. Every path starts with `/merchant/`, so a `.../merchant` base would
1271
+ * request `/merchant/merchant/...`; every call carries credentials, so cleartext is refused.
1272
+ * Credentials, a query or a fragment are checked on the text as given, before normalization.
1273
+ */
1274
+ function readHttpsOrigin(config, key) {
1275
+ const text = config.string(key).trim();
1276
+ const url = URL.parse(text);
1277
+ if (url === null || url.protocol !== "https:" && url.protocol !== "http:") throw configError(`${key} must be an absolute https URL`, key, "format");
1278
+ if (url.protocol !== "https:") throw configError(`${key} must use https`, key, "format");
1279
+ if (url.username !== "" || url.password !== "" || /[?#]/.test(text)) throw configError(`${key} must not include credentials, a query or a fragment`, key, "format");
1280
+ if (url.pathname !== "/") throw configError(`${key} must be an origin without a path, e.g. https://dev.gw.paylov.uz`, key, "format");
1281
+ return url.origin;
1282
+ }
1283
+ /** The transport of a network surface: its `baseUrl` origin and its transport options. */
1284
+ function readSurfaceTransport(config) {
1285
+ return {
1286
+ origin: readHttpsOrigin(config, "baseUrl"),
1287
+ ...readTransportConfig(config)
1288
+ };
1289
+ }
1290
+ // src/core/params.ts
1291
+ /**
1292
+ * Caller-input parsing. Malformed values become SDK input errors before any I/O; messages name
1293
+ * the method and field, never the value, because values carry credentials, card data and
1294
+ * personal data. Exceptions thrown by caller getters or proxies propagate unchanged.
1295
+ */
1296
+ /**
1297
+ * A closed set for `literal()` that lists every member of the public union `T`, so the two cannot
1298
+ * drift: a missing or foreign member fails to compile.
1299
+ *
1300
+ * @example
1301
+ * const DECISIONS = everyLiteral<WebhookDecisionWord>()(['accept', 'maintenance']);
1302
+ */
1303
+ function everyLiteral() {
1304
+ return (values) => values;
1305
+ }
1306
+ var ParamsReader = class ParamsReader {
1307
+ #record;
1308
+ #context;
1309
+ #code;
1310
+ /** The field path of this object, e.g. `items[0]`; empty at the top level. */
1311
+ #path;
1312
+ constructor(record, context, code, path) {
1313
+ this.#record = record;
1314
+ this.#context = context;
1315
+ this.#code = code;
1316
+ this.#path = path;
1317
+ }
1318
+ string(key) {
1319
+ return this.#checkString(key, this.#required(key));
1320
+ }
1321
+ optionalString(key) {
1322
+ const value = this.#read(key);
1323
+ return value === void 0 ? void 0 : this.#checkString(key, value);
1324
+ }
1325
+ integer(key) {
1326
+ return this.#checkInteger(key, this.#required(key));
1327
+ }
1328
+ optionalInteger(key, range) {
1329
+ const value = this.#read(key);
1330
+ return value === void 0 ? void 0 : this.#checkInteger(key, value, range);
1331
+ }
1332
+ optionalBoolean(key) {
1333
+ const value = this.#read(key);
1334
+ return value === void 0 ? void 0 : this.#checkBoolean(key, value);
1335
+ }
1336
+ literal(key, values) {
1337
+ return this.#checkLiteral(key, this.#required(key), values);
1338
+ }
1339
+ optionalLiteral(key, values) {
1340
+ const value = this.#read(key);
1341
+ return value === void 0 ? void 0 : this.#checkLiteral(key, value, values);
1342
+ }
1343
+ url(key) {
1344
+ return this.#checkUrl(key, this.#required(key));
1345
+ }
1346
+ optionalUrl(key) {
1347
+ const value = this.#read(key);
1348
+ return value === void 0 ? void 0 : this.#checkUrl(key, value);
1349
+ }
1350
+ json(key) {
1351
+ return this.#checkJson(key, this.#required(key));
1352
+ }
1353
+ optionalJson(key) {
1354
+ const value = this.#read(key);
1355
+ return value === void 0 ? void 0 : this.#checkJson(key, value);
1356
+ }
1357
+ stringRecord(key, pattern) {
1358
+ const value = this.#required(key);
1359
+ if (!isRecord(value)) throw this.#error(key, "type", "must be an object");
1360
+ const checked = [];
1361
+ for (const [name, entry] of Object.entries(value)) {
1362
+ if (typeof entry !== "string") throw this.#error(key, "type", "values must be strings");
1363
+ if (!(pattern.test(name) && pattern.test(entry))) throw this.#error(key, "format", "has a key or value that is not allowed");
1364
+ checked.push([name, entry]);
1365
+ }
1366
+ return Object.fromEntries(checked);
1367
+ }
1368
+ array(key, item) {
1369
+ return this.#checkArray(key, this.#required(key), item);
1370
+ }
1371
+ optionalArray(key, item) {
1372
+ const value = this.#read(key);
1373
+ return value === void 0 ? void 0 : this.#checkArray(key, value, item);
1374
+ }
1375
+ object(key, read) {
1376
+ return read(this.#child(key, this.#required(key)));
1377
+ }
1378
+ optionalObject(key, read) {
1379
+ const value = this.#read(key);
1380
+ return value === void 0 ? void 0 : read(this.#child(key, value));
1381
+ }
1382
+ exclusive(keys) {
1383
+ const present = keys.filter((key) => this.#read(key) !== void 0);
1384
+ const [only] = present;
1385
+ if (only === void 0 || present.length > 1) {
1386
+ const scope = this.#path === "" ? this.#context : `${this.#context}: ${this.#path}`;
1387
+ throw new PaylovInputError({
1388
+ code: this.#code,
1389
+ message: `${scope} requires exactly one of ${keys.join(", ")}`,
1390
+ field: this.#path === "" ? void 0 : this.#path,
1391
+ rule: "exclusive"
1392
+ });
1393
+ }
1394
+ return only;
1395
+ }
1396
+ tiyin(key) {
1397
+ const field = this.#field(key);
1398
+ return readTiyin(this.#read(key), field, `${this.#context}: ${field}`);
1399
+ }
1400
+ optionalTiyin(key) {
1401
+ return this.#read(key) === void 0 ? void 0 : this.tiyin(key);
1402
+ }
1403
+ tiyinAsWholeSum(key) {
1404
+ const sum = tiyinToWireSum(this.tiyin(key));
1405
+ if (sum === void 0) {
1406
+ const field = this.#field(key);
1407
+ throw invalidAmount(`${this.#context}: ${field} must be a whole number of SUM (a multiple of 100)`, field, "format");
1408
+ }
1409
+ return sum;
1410
+ }
1411
+ raw(key) {
1412
+ return this.#read(key);
1413
+ }
1414
+ #field(key) {
1415
+ return this.#path === "" ? key : `${this.#path}.${key}`;
1416
+ }
1417
+ #error(key, rule, text) {
1418
+ const field = this.#field(key);
1419
+ return new PaylovInputError({
1420
+ code: this.#code,
1421
+ message: `${this.#context}: ${field} ${text}`,
1422
+ field,
1423
+ rule
1424
+ });
1425
+ }
1426
+ /** Own properties only: an inherited value is not a parameter the caller passed. */
1427
+ #read(key) {
1428
+ return Object.hasOwn(this.#record, key) ? this.#record[key] : void 0;
1429
+ }
1430
+ #required(key) {
1431
+ const value = this.#read(key);
1432
+ if (value === void 0) throw this.#error(key, "required", "is required");
1433
+ return value;
1434
+ }
1435
+ #checkString(key, value) {
1436
+ if (typeof value !== "string") throw this.#error(key, "type", "must be a string");
1437
+ if (value.trim() === "") throw this.#error(key, "required", "must not be blank");
1438
+ return value;
1439
+ }
1440
+ #checkInteger(key, value, range) {
1441
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) throw this.#error(key, "type", "must be a safe integer");
1442
+ if (range !== void 0 && (value < range.min || value > range.max)) throw this.#error(key, "range", `must be between ${range.min} and ${range.max}`);
1443
+ return value;
1444
+ }
1445
+ #checkBoolean(key, value) {
1446
+ if (typeof value !== "boolean") throw this.#error(key, "type", "must be a boolean");
1447
+ return value;
1448
+ }
1449
+ #checkLiteral(key, value, values) {
1450
+ const match = values.find((candidate) => candidate === value);
1451
+ if (match === void 0) throw this.#error(key, "format", `must be one of ${values.map(String).join(", ")}`);
1452
+ return match;
1453
+ }
1454
+ #checkUrl(key, value) {
1455
+ const text = this.#checkString(key, value);
1456
+ const protocol = URL.parse(text)?.protocol;
1457
+ if (protocol !== "http:" && protocol !== "https:") throw this.#error(key, "format", "must be an absolute http(s) URL");
1458
+ return text;
1459
+ }
1460
+ /** Serializer exceptions are discarded: a cycle or a BigInt says nothing the caller needs. */
1461
+ #checkJson(key, value) {
1462
+ if (!isRecord(value)) throw this.#error(key, "type", "must be a JSON object");
1463
+ let snapshot;
1464
+ try {
1465
+ snapshot = JSON.parse(JSON.stringify(value));
1466
+ } catch {
1467
+ throw this.#error(key, "type", "must be JSON-serializable");
1468
+ }
1469
+ const json = isRecord(snapshot) ? toJsonObject(snapshot) : void 0;
1470
+ if (json === void 0) throw this.#error(key, "type", "must be a JSON object");
1471
+ return json;
1472
+ }
1473
+ #checkArray(key, value, item) {
1474
+ if (!Array.isArray(value)) throw this.#error(key, "type", "must be an array");
1475
+ const items = value;
1476
+ return Array.from(items, (element, index) => item(this.#child(`${key}[${index}]`, element), index));
1477
+ }
1478
+ #child(key, value) {
1479
+ if (!isRecord(value)) throw this.#error(key, "type", "must be an object");
1480
+ return new ParamsReader(value, this.#context, this.#code, this.#field(key));
1481
+ }
1482
+ };
1483
+ function readObject(value, context, code) {
1484
+ if (!isRecord(value)) throw new PaylovInputError({
1485
+ code,
1486
+ message: `${context} expects an object`,
1487
+ field: void 0,
1488
+ rule: "type"
1489
+ });
1490
+ return new ParamsReader(value, context, code, "");
1491
+ }
1492
+ /** Method parameters; failures are `sdk_invalid_input` (`sdk_invalid_amount` for amounts). */
1493
+ function readParams(value, method) {
1494
+ return readObject(value, method, "sdk_invalid_input");
1495
+ }
1496
+ /** Constructor configuration; failures are `sdk_config_error`. */
1497
+ function readConfig(value, surface) {
1498
+ return readObject(value, surface, "sdk_config_error");
1499
+ }
1500
+ /** The `signal` of a method's `PaylovCallOptions`; anything but an `AbortSignal` is rejected. */
1501
+ function readCallSignal(options, method) {
1502
+ if (options === void 0) return void 0;
1503
+ const signal = readParams(options, `${method} options`).raw("signal");
1504
+ if (signal === void 0 || signal instanceof AbortSignal) return signal;
1505
+ throw invalidInput(`${method} options: signal must be an AbortSignal`, "signal", "type");
1506
+ }
1507
+ // src/core/call.ts
1508
+ /**
1509
+ * The plumbing every endpoint method shares: read the call's input, send to a declared endpoint,
1510
+ * decode, and map the endpoint's miss code to a value.
1511
+ */
1512
+ /**
1513
+ * A method's parameters and the signal of its call options, both validated before any I/O.
1514
+ *
1515
+ * @example
1516
+ * const method = 'holds.release';
1517
+ * const { input, signal } = readCall(params, options, method);
1518
+ */
1519
+ function readCall(params, options, method) {
1520
+ return {
1521
+ input: readParams(params, method),
1522
+ signal: readCallSignal(options, method)
1523
+ };
1524
+ }
1525
+ /**
1526
+ * Sends one request to `endpoint` and decodes its payload. Logs and errors carry the route
1527
+ * template, never the identifiers. Decode failures are reported under `result` for the enveloped
1528
+ * shapes and under `body` for the others.
1529
+ *
1530
+ * @example
1531
+ * return send(http, ENDPOINTS.get, { path: { cardId }, signal }, decodeFetchedCard);
1532
+ */
1533
+ async function send(http, endpoint, request, decode) {
1534
+ return decodePayload(await http.request(endpoint, request), endpoint.shape === "envelope" ? "result" : "body", decode);
1535
+ }
1536
+ /**
1537
+ * Resolves to `fallback` when `call` rejects with the endpoint's `miss` code; every other
1538
+ * failure, a decode failure included, propagates.
1539
+ *
1540
+ * @example
1541
+ * return orOnMiss(send(http, ENDPOINTS.get, { query, signal }, decodeHold), ENDPOINTS.get, null);
1542
+ */
1543
+ async function orOnMiss(call, endpoint, fallback) {
1544
+ try {
1545
+ return await call;
1546
+ } catch (error) {
1547
+ if (isPaylovApiError(error, endpoint.miss)) return fallback;
1548
+ throw error;
1549
+ }
1550
+ }
1551
+ // src/shared/otpSms.ts
1552
+ /** Reads `sms`; use with `params.optionalObject`. */
1553
+ function readOtpSms(sms) {
1554
+ return {
1555
+ hash: sms.optionalString("hash"),
1556
+ templateId: sms.optionalInteger("templateId")
1557
+ };
1558
+ }
1559
+ // src/cards/decoders.ts
1560
+ const decodeFlatStatus = (value, path) => {
1561
+ const status = readFields(value, path);
1562
+ return {
1563
+ isActive: status("is_active", asBoolean),
1564
+ processingStatus: status("status_message", asString),
1565
+ isSmsEnabled: status("sms_info", asBoolean)
1566
+ };
1567
+ };
1568
+ /**
1569
+ * Each endpoint has exactly one status layout and never falls back to the other, so a layout
1570
+ * change surfaces as `sdk_malformed_response`. An error inside the confirm status is an inactive
1571
+ * status: `is_active: false` with the reason in `status_message`.
1572
+ */
1573
+ function cardDecoder(decodeStatus) {
1574
+ return (value, path) => {
1575
+ const card = readFields(value, path);
1576
+ const cardName = card("cardName", nullable(asString));
1577
+ return {
1578
+ cardId: card("cardId", asString),
1579
+ userId: card("userId", asString),
1580
+ holderName: card("owner", asString),
1581
+ cardName: cardName === "" ? null : cardName,
1582
+ maskedCardNumber: card("number", asMaskedPan),
1583
+ balanceTiyin: card("balance", asTiyin),
1584
+ bankId: card("bankId", asString),
1585
+ bankName: card("bankName", nullish(asString)),
1586
+ vendor: card("vendor", asString),
1587
+ processing: card("processing", asString),
1588
+ ...card("status", decodeStatus)
1589
+ };
1590
+ };
1591
+ }
1592
+ /** Confirm and the bind session carry a flat `status`. */
1593
+ const decodeFlatCard = cardDecoder(decodeFlatStatus);
1594
+ /** `getCard` and `getAllUserCards` nest it as `status.result`. */
1595
+ const decodeNestedCard = cardDecoder(fieldOf("result", decodeFlatStatus));
1596
+ const decodeConfirmedCard = fieldOf("card", decodeFlatCard);
1597
+ const decodeFetchedCard = fieldOf("card", decodeNestedCard);
1598
+ const decodeCardList = fieldOf("cards", arrayOf(decodeNestedCard));
1599
+ const decodePanBindingStarted = (value, path) => {
1600
+ const result = readFields(value, path);
1601
+ return {
1602
+ cardId: result("cid", asString),
1603
+ otpSentPhone: result("otpSentPhone", asString)
1604
+ };
1605
+ };
1606
+ const decodeBindLinkCreated = (value, path) => {
1607
+ const result = readFields(value, path);
1608
+ return {
1609
+ token: result("token", asString),
1610
+ bindUrl: result("bindUrl", asString),
1611
+ expiresAt: result("expiresAt", asIsoDateTime)
1612
+ };
1613
+ };
1614
+ /** Only a `confirmed` session has a card; any other state's `card` is not read. */
1615
+ const decodeBindSession = (value, path) => {
1616
+ const result = readFields(value, path);
1617
+ const status = result("state", asString);
1618
+ if (status !== "confirmed") return {
1619
+ isBound: false,
1620
+ status,
1621
+ card: null
1622
+ };
1623
+ return {
1624
+ isBound: true,
1625
+ status,
1626
+ card: result("card", decodeFlatCard)
1627
+ };
1628
+ };
1629
+ /** `{match: boolean}`, the documented answer of the phone check. */
1630
+ const decodeMatch = fieldOf("match", asBoolean);
1631
+ /** Delete answers `result: true`; the envelope alone signals its success. */
1632
+ const decodeDeleted = () => void 0;
1633
+ // src/cards/resource.ts
1634
+ const ENDPOINTS$8 = {
1635
+ createBindLink: {
1636
+ method: "POST",
1637
+ route: "/merchant/userCard/createBindLink/",
1638
+ shape: "envelope"
1639
+ },
1640
+ getBindSession: {
1641
+ method: "GET",
1642
+ route: "/merchant/userCard/bindSession/{token}/status/",
1643
+ shape: "envelope"
1644
+ },
1645
+ startPanBinding: {
1646
+ method: "POST",
1647
+ route: "/merchant/userCard/createUserCard/",
1648
+ shape: "envelope"
1649
+ },
1650
+ confirmPanBinding: {
1651
+ method: "POST",
1652
+ route: "/merchant/userCard/confirmUserCardCreate/",
1653
+ shape: "envelope"
1654
+ },
1655
+ get: {
1656
+ method: "GET",
1657
+ route: "/merchant/userCard/getCard/{cardId}/",
1658
+ shape: "envelope"
1659
+ },
1660
+ list: {
1661
+ method: "GET",
1662
+ route: "/merchant/userCard/getAllUserCards/",
1663
+ shape: "envelope"
1664
+ },
1665
+ delete: {
1666
+ method: "DELETE",
1667
+ route: "/merchant/userCard/deleteUserCard/",
1668
+ shape: "envelope"
1669
+ },
1670
+ checkPhone: {
1671
+ method: "POST",
1672
+ route: "/merchant/userCard/checkPhoneMatch/",
1673
+ shape: "envelope"
1674
+ }
1675
+ };
1676
+ function createCardsResource(http) {
1677
+ return {
1678
+ async createBindLink(params, options) {
1679
+ const { input, signal } = readCall(params, options, "cards.createBindLink");
1680
+ const body = {
1681
+ userId: input.string("userId"),
1682
+ returnUrl: input.optionalUrl("returnUrl")
1683
+ };
1684
+ return send(http, ENDPOINTS$8.createBindLink, {
1685
+ body,
1686
+ signal
1687
+ }, decodeBindLinkCreated);
1688
+ },
1689
+ async getBindSession(params, options) {
1690
+ const { input, signal } = readCall(params, options, "cards.getBindSession");
1691
+ const path = { token: input.string("token") };
1692
+ return send(http, ENDPOINTS$8.getBindSession, {
1693
+ path,
1694
+ signal
1695
+ }, decodeBindSession);
1696
+ },
1697
+ async startPanBinding(params, options) {
1698
+ const { input, signal } = readCall(params, options, "cards.startPanBinding");
1699
+ const body = {
1700
+ userId: input.string("userId"),
1701
+ cardNumber: input.string("cardNumber"),
1702
+ expireDate: input.string("cardExpiry"),
1703
+ phoneNumber: input.optionalString("phoneNumber"),
1704
+ sms: input.optionalObject("sms", readOtpSms)
1705
+ };
1706
+ return send(http, ENDPOINTS$8.startPanBinding, {
1707
+ body,
1708
+ signal
1709
+ }, decodePanBindingStarted);
1710
+ },
1711
+ async confirmPanBinding(params, options) {
1712
+ const { input, signal } = readCall(params, options, "cards.confirmPanBinding");
1713
+ const body = {
1714
+ cardId: input.string("cardId"),
1715
+ otp: input.string("otp"),
1716
+ cardName: input.optionalString("cardName"),
1717
+ pinfl: input.optionalString("pinfl")
1718
+ };
1719
+ return send(http, ENDPOINTS$8.confirmPanBinding, {
1720
+ body,
1721
+ signal
1722
+ }, decodeConfirmedCard);
1723
+ },
1724
+ async get(params, options) {
1725
+ const { input, signal } = readCall(params, options, "cards.get");
1726
+ const path = { cardId: input.string("cardId") };
1727
+ return send(http, ENDPOINTS$8.get, {
1728
+ path,
1729
+ signal
1730
+ }, decodeFetchedCard);
1731
+ },
1732
+ async list(params, options) {
1733
+ const { input, signal } = readCall(params, options, "cards.list");
1734
+ const query = { userId: input.string("userId") };
1735
+ return send(http, ENDPOINTS$8.list, {
1736
+ query,
1737
+ signal
1738
+ }, decodeCardList);
1739
+ },
1740
+ async delete(params, options) {
1741
+ const { input, signal } = readCall(params, options, "cards.delete");
1742
+ const query = { userCardId: input.string("cardId") };
1743
+ return send(http, ENDPOINTS$8.delete, {
1744
+ query,
1745
+ signal
1746
+ }, decodeDeleted);
1747
+ },
1748
+ async checkPhone(params, options) {
1749
+ const { input, signal } = readCall(params, options, "cards.checkPhone");
1750
+ const body = {
1751
+ cardId: input.string("cardId"),
1752
+ phoneNumber: input.string("phoneNumber")
1753
+ };
1754
+ return send(http, ENDPOINTS$8.checkPhone, {
1755
+ body,
1756
+ signal
1757
+ }, decodeMatch);
1758
+ }
1759
+ };
1760
+ }
1761
+ // src/shared/receiptItems.ts
1762
+ /** Reads one item; use with `params.array` or `params.optionalArray`. */
1763
+ function readReceiptItem(item) {
1764
+ const base = {
1765
+ title: item.string("title"),
1766
+ price: item.tiyin("priceTiyin"),
1767
+ discount: item.optionalTiyin("discountTiyin"),
1768
+ count: item.integer("count"),
1769
+ code: item.string("code"),
1770
+ vat_percent: item.integer("vatPercent"),
1771
+ package_code: item.string("packageCode")
1772
+ };
1773
+ return item.exclusive(["tin", "pinfl"]) === "tin" ? {
1774
+ ...base,
1775
+ tin: item.string("tin")
1776
+ } : {
1777
+ ...base,
1778
+ pinfl: item.string("pinfl")
1779
+ };
1780
+ }
1781
+ // src/shared/transactions.ts
1782
+ /** Transaction shapes shared by the features that create, look up or read transactions. */
1783
+ /**
1784
+ * Decodes a status string, replacing each wire spelling in `statusByWire` with the SDK's word.
1785
+ * Other values pass through unchanged.
1786
+ */
1787
+ function statusDecoder(statusByWire) {
1788
+ return (value, path) => {
1789
+ const status = asString(value, path);
1790
+ return statusByWire.get(status) ?? status;
1791
+ };
1792
+ }
1793
+ /** Decodes `{ transactionId }`. */
1794
+ const decodeTransactionReference = (value, path) => ({ transactionId: fieldOf("transactionId", asString)(value, path) });
1795
+ /**
1796
+ * Reads a {@link TransactionLookup}: a `transactionId` or an `externalId`. The result carries
1797
+ * only the key given, ready to send.
1798
+ */
1799
+ function readTransactionLookup(input) {
1800
+ return input.exclusive(["transactionId", "externalId"]) === "transactionId" ? { transactionId: input.string("transactionId") } : { externalId: input.string("externalId") };
1801
+ }
1802
+ // src/fiscalization/decoders.ts
1803
+ const decodeOfdReceipt = (value, path) => {
1804
+ const field = readFields(value, path);
1805
+ return {
1806
+ receiptId: field("receiptId", asNonNegativeInteger),
1807
+ receiptUrl: field("receiptUrl", asString),
1808
+ terminalId: field("terminalId", asString),
1809
+ fiscalSign: field("fiscalSign", asString)
1810
+ };
1811
+ };
1812
+ const decodeFiscalReceiptRegistered = fieldOf("ofd", decodeOfdReceipt);
1813
+ /**
1814
+ * A known transaction without a receipt answers `success: false` with `receiptUrl` and
1815
+ * `isRefund` null and the other receipt keys absent (W c274); an unknown id is an API error.
1816
+ */
1817
+ const decodeReceiptLookup = (value, path) => {
1818
+ const field = readFields(value, path);
1819
+ if (!field("success", asBoolean)) return null;
1820
+ return {
1821
+ ...decodeOfdReceipt(value, path),
1822
+ isRefund: field("isRefund", asBoolean)
1823
+ };
1824
+ };
1825
+ const decodeReceiptRefunded = (value, path) => {
1826
+ const field = readFields(value, path);
1827
+ return {
1828
+ refund: field("ofd", fieldOf("refund", decodeOfdReceipt)),
1829
+ sale: field("sale", decodeOfdReceipt)
1830
+ };
1831
+ };
1832
+ /** `result.error` sits beside `success` and is ignored; only `success: true` is a success. */
1833
+ const decodeAttachConfirmation = (value, path) => {
1834
+ if (!fieldOf("success", asBoolean)(value, path)) throw new DecodeFailure(`${path}.success`);
1835
+ };
1836
+ /**
1837
+ * `data` is `null` (self-employed), the number 200 (a negative entrepreneur check, discarded) or
1838
+ * the high-income object, whose `status` is the answer while `success` only says the check ran.
1839
+ */
1840
+ const decodeActivityTypeDetails = (value, path) => {
1841
+ if (value === null || value === void 0 || typeof value === "number") return {
1842
+ status: void 0,
1843
+ activityNames: []
1844
+ };
1845
+ const field = readFields(value, path);
1846
+ return {
1847
+ status: field("status", asBoolean),
1848
+ activityNames: field("activityNames", arrayOf(asString))
1849
+ };
1850
+ };
1851
+ /** The upstream `reason` is free text from the tax service and is never read. */
1852
+ const decodeActivityTypeCheck = (value, path) => {
1853
+ const field = readFields(value, path);
1854
+ const success = field("success", asBoolean);
1855
+ const { status = true, activityNames } = field("data", decodeActivityTypeDetails);
1856
+ return {
1857
+ isConfirmed: success && status,
1858
+ activityNames
1859
+ };
1860
+ };
1861
+ // src/fiscalization/resource.ts
1862
+ const ENDPOINTS$7 = {
1863
+ registerReceipt: {
1864
+ method: "POST",
1865
+ route: "/merchant/fiscalization/register/",
1866
+ shape: "envelope"
1867
+ },
1868
+ getReceipt: {
1869
+ method: "GET",
1870
+ route: "/merchant/fiscalization/status/",
1871
+ shape: "envelope",
1872
+ miss: "ofd_check_not_found"
1873
+ },
1874
+ attachReceipt: {
1875
+ method: "POST",
1876
+ route: "/merchant/fiscalization/set-receipt/",
1877
+ shape: "envelope"
1878
+ },
1879
+ refundReceipt: {
1880
+ method: "POST",
1881
+ route: "/merchant/fiscalization/refund/",
1882
+ shape: "envelope"
1883
+ },
1884
+ checkActivityType: {
1885
+ method: "POST",
1886
+ route: "/merchant/fiscalization/activity-types/",
1887
+ shape: "envelope"
1888
+ }
1889
+ };
1890
+ const ACTIVITY_TYPES = everyLiteral()([
1891
+ "individual_entrepreneur",
1892
+ "self_employed",
1893
+ "high_income"
1894
+ ]);
1895
+ const WIRE_ACTIVITY_TYPES = {
1896
+ individual_entrepreneur: 1,
1897
+ self_employed: 2,
1898
+ high_income: 3
1899
+ };
1900
+ function createFiscalizationResource(http) {
1901
+ return {
1902
+ async registerReceipt(params, options) {
1903
+ const { input, signal } = readCall(params, options, "fiscalization.registerReceipt");
1904
+ const lookup = readTransactionLookup(input);
1905
+ const body = {
1906
+ ...lookup.transactionId === void 0 ? {
1907
+ ...lookup,
1908
+ phoneNumber: input.string("phoneNumber")
1909
+ } : lookup,
1910
+ items: input.array("items", readReceiptItem)
1911
+ };
1912
+ return send(http, ENDPOINTS$7.registerReceipt, {
1913
+ body,
1914
+ signal
1915
+ }, decodeFiscalReceiptRegistered);
1916
+ },
1917
+ async getReceipt(params, options) {
1918
+ const { input, signal } = readCall(params, options, "fiscalization.getReceipt");
1919
+ const query = {
1920
+ ...readTransactionLookup(input),
1921
+ refunded: input.optionalBoolean("isRefund")
1922
+ };
1923
+ return orOnMiss(send(http, ENDPOINTS$7.getReceipt, {
1924
+ query,
1925
+ signal
1926
+ }, decodeReceiptLookup), ENDPOINTS$7.getReceipt, null);
1927
+ },
1928
+ async attachReceipt(params, options) {
1929
+ const { input, signal } = readCall(params, options, "fiscalization.attachReceipt");
1930
+ const body = {
1931
+ transactionId: input.string("transactionId"),
1932
+ externalId: input.optionalString("externalId"),
1933
+ terminalId: input.string("terminalId"),
1934
+ dateTime: input.string("issuedAtRaw"),
1935
+ fiscalSign: input.string("fiscalSign"),
1936
+ qrCodeUrl: input.string("receiptUrl"),
1937
+ receiptId: input.integer("receiptId")
1938
+ };
1939
+ return send(http, ENDPOINTS$7.attachReceipt, {
1940
+ body,
1941
+ signal
1942
+ }, decodeAttachConfirmation);
1943
+ },
1944
+ async refundReceipt(params, options) {
1945
+ const { input, signal } = readCall(params, options, "fiscalization.refundReceipt");
1946
+ const body = { receiptId: input.integer("receiptId") };
1947
+ return send(http, ENDPOINTS$7.refundReceipt, {
1948
+ body,
1949
+ signal
1950
+ }, decodeReceiptRefunded);
1951
+ },
1952
+ async checkActivityType(params, options) {
1953
+ const { input, signal } = readCall(params, options, "fiscalization.checkActivityType");
1954
+ const body = {
1955
+ pinfl: input.string("pinfl"),
1956
+ activityType: WIRE_ACTIVITY_TYPES[input.literal("activityType", ACTIVITY_TYPES)]
1957
+ };
1958
+ return send(http, ENDPOINTS$7.checkActivityType, {
1959
+ body,
1960
+ signal
1961
+ }, decodeActivityTypeCheck);
1962
+ }
1963
+ };
1964
+ }
1965
+ // src/gateway/decoders.ts
1966
+ const decodeStatus = (value, path) => {
1967
+ fieldOf("status", asLiteral("ok"))(value, path);
1968
+ };
1969
+ const decodeBank = (value, path) => {
1970
+ const field = readFields(value, path);
1971
+ return {
1972
+ bankId: String(field("id", asNonNegativeInteger)),
1973
+ name: field("name", asString),
1974
+ officialName: field("official_name", nullable(asString))
1975
+ };
1976
+ };
1977
+ const decodeBanks = arrayOf(decodeBank);
1978
+ // src/gateway/resource.ts
1979
+ const ENDPOINTS$6 = {
1980
+ getStatus: {
1981
+ method: "GET",
1982
+ route: "/merchant/status/",
1983
+ shape: "flat"
1984
+ },
1985
+ listBanks: {
1986
+ method: "GET",
1987
+ route: "/merchant/bankList/",
1988
+ shape: "array"
1989
+ }
1990
+ };
1991
+ /** `anonymousHttp` sends no `Authorization`: `status/` needs none and must not trigger a login. */
1992
+ function createGatewayResource(http, anonymousHttp) {
1993
+ return {
1994
+ async getStatus(options) {
1995
+ const signal = readCallSignal(options, "gateway.getStatus");
1996
+ return send(anonymousHttp, ENDPOINTS$6.getStatus, { signal }, decodeStatus);
1997
+ },
1998
+ async listBanks(options) {
1999
+ const signal = readCallSignal(options, "gateway.listBanks");
2000
+ return send(http, ENDPOINTS$6.listBanks, { signal }, decodeBanks);
2001
+ }
2002
+ };
2003
+ }
2004
+ // src/holds/decoders.ts
2005
+ /** The SDK's word for each wire status it renames. */
2006
+ const HOLD_STATUS_BY_WIRE = /* @__PURE__ */ new Map([
2007
+ ["hold", "held"],
2008
+ ["paid", "captured"],
2009
+ ["cancelled", "released"]
2010
+ ]);
2011
+ const decodeHoldStatus = statusDecoder(HOLD_STATUS_BY_WIRE);
2012
+ /** `hold/charge/` result; `payedAt` is UTC. */
2013
+ const decodeHoldCaptured = (value, path) => {
2014
+ const field = readFields(value, path);
2015
+ return {
2016
+ ...decodeTransactionReference(value, path),
2017
+ cardId: field("cardId", asString),
2018
+ capturedAt: field("payedAt", asUtcDateTime)
2019
+ };
2020
+ };
2021
+ /** `hold/status/` result; `amount` is whole SUM, `payedAt` and `cancelTime` are UTC. */
2022
+ const decodeHold = (value, path) => {
2023
+ const field = readFields(value, path);
2024
+ return {
2025
+ transactionId: field("transactionId", asString),
2026
+ status: field("status", decodeHoldStatus),
2027
+ amountTiyin: field("amount", asTiyinFromSum),
2028
+ capturedAt: field("payedAt", nullable(asUtcDateTime)),
2029
+ releasedAt: field("cancelTime", nullable(asUtcDateTime)),
2030
+ serviceId: field("serviceId", asString)
2031
+ };
2032
+ };
2033
+ // src/holds/resource.ts
2034
+ const ENDPOINTS$5 = {
2035
+ create: {
2036
+ method: "POST",
2037
+ route: "/merchant/payment/hold/create/",
2038
+ shape: "envelope"
2039
+ },
2040
+ capture: {
2041
+ method: "POST",
2042
+ route: "/merchant/payment/hold/charge/",
2043
+ shape: "envelope"
2044
+ },
2045
+ release: {
2046
+ method: "POST",
2047
+ route: "/merchant/payment/hold/dismiss/",
2048
+ shape: "envelope"
2049
+ },
2050
+ get: {
2051
+ method: "GET",
2052
+ route: "/merchant/payment/hold/status/",
2053
+ shape: "envelope",
2054
+ miss: "transaction_not_found"
2055
+ }
2056
+ };
2057
+ function createHoldsResource(http) {
2058
+ return {
2059
+ async create(params, options) {
2060
+ const { input, signal } = readCall(params, options, "holds.create");
2061
+ const body = {
2062
+ userId: input.string("userId"),
2063
+ cardId: input.string("cardId"),
2064
+ amount: input.tiyinAsWholeSum("amountTiyin"),
2065
+ time: input.integer("durationMinutes"),
2066
+ externalId: input.string("externalId"),
2067
+ account: input.optionalJson("account"),
2068
+ serviceId: input.optionalString("serviceId")
2069
+ };
2070
+ return send(http, ENDPOINTS$5.create, {
2071
+ body,
2072
+ signal
2073
+ }, decodeTransactionReference);
2074
+ },
2075
+ async capture(params, options) {
2076
+ const { input, signal } = readCall(params, options, "holds.capture");
2077
+ const body = {
2078
+ transactionId: input.string("transactionId"),
2079
+ amount: input.tiyinAsWholeSum("amountTiyin")
2080
+ };
2081
+ return send(http, ENDPOINTS$5.capture, {
2082
+ body,
2083
+ signal
2084
+ }, decodeHoldCaptured);
2085
+ },
2086
+ async release(params, options) {
2087
+ const { input, signal } = readCall(params, options, "holds.release");
2088
+ const body = { transactionId: input.string("transactionId") };
2089
+ return send(http, ENDPOINTS$5.release, {
2090
+ body,
2091
+ signal
2092
+ }, decodeTransactionReference);
2093
+ },
2094
+ async get(params, options) {
2095
+ const { input, signal } = readCall(params, options, "holds.get");
2096
+ const query = readTransactionLookup(input);
2097
+ return orOnMiss(send(http, ENDPOINTS$5.get, {
2098
+ query,
2099
+ signal
2100
+ }, decodeHold), ENDPOINTS$5.get, null);
2101
+ }
2102
+ };
2103
+ }
2104
+ // src/payments/decoders.ts
2105
+ /** `payment/cancel/` result. */
2106
+ const decodePaymentRefunded = (value, path) => {
2107
+ const field = readFields(value, path);
2108
+ return {
2109
+ ...decodeTransactionReference(value, path),
2110
+ refundedAt: field("cancelTime", asTashkentDateTime)
2111
+ };
2112
+ };
2113
+ /** `paymentWithoutRegistration/` result; the echoed `extId` and the `code` are withheld. */
2114
+ const decodePanPaymentStarted = (value, path) => {
2115
+ const field = readFields(value, path);
2116
+ return {
2117
+ ...decodeTransactionReference(value, path),
2118
+ otpSentPhone: field("otpSentPhone", asString)
2119
+ };
2120
+ };
2121
+ // src/payments/resource.ts
2122
+ const ENDPOINTS$4 = {
2123
+ create: {
2124
+ method: "POST",
2125
+ route: "/merchant/receipts/create/",
2126
+ shape: "envelope"
2127
+ },
2128
+ pay: {
2129
+ method: "POST",
2130
+ route: "/merchant/receipts/pay/",
2131
+ shape: "envelope"
2132
+ },
2133
+ refund: {
2134
+ method: "POST",
2135
+ route: "/merchant/payment/cancel/",
2136
+ shape: "envelope"
2137
+ },
2138
+ startPanPayment: {
2139
+ method: "POST",
2140
+ route: "/merchant/paymentWithoutRegistration/",
2141
+ shape: "envelope"
2142
+ },
2143
+ confirmPanPayment: {
2144
+ method: "POST",
2145
+ route: "/merchant/confirmPayment/",
2146
+ shape: "envelope"
2147
+ }
2148
+ };
2149
+ function createPaymentsResource(http) {
2150
+ return {
2151
+ async create(params, options) {
2152
+ const { input, signal } = readCall(params, options, "payments.create");
2153
+ const body = {
2154
+ amount: input.tiyinAsWholeSum("amountTiyin"),
2155
+ account: input.optionalJson("account") ?? {},
2156
+ userId: input.optionalString("userId")
2157
+ };
2158
+ return send(http, ENDPOINTS$4.create, {
2159
+ body,
2160
+ signal
2161
+ }, decodeTransactionReference);
2162
+ },
2163
+ async pay(params, options) {
2164
+ const { input, signal } = readCall(params, options, "payments.pay");
2165
+ const body = {
2166
+ transactionId: input.string("transactionId"),
2167
+ cardId: input.string("cardId"),
2168
+ userId: input.string("userId")
2169
+ };
2170
+ return send(http, ENDPOINTS$4.pay, {
2171
+ body,
2172
+ signal
2173
+ }, decodeTransactionReference);
2174
+ },
2175
+ async refund(params, options) {
2176
+ const { input, signal } = readCall(params, options, "payments.refund");
2177
+ const body = { transactionId: input.string("transactionId") };
2178
+ return send(http, ENDPOINTS$4.refund, {
2179
+ body,
2180
+ signal
2181
+ }, decodePaymentRefunded);
2182
+ },
2183
+ async startPanPayment(params, options) {
2184
+ const { input, signal } = readCall(params, options, "payments.startPanPayment");
2185
+ const body = {
2186
+ cardNumber: input.string("cardNumber"),
2187
+ expireDate: input.string("cardExpiry"),
2188
+ amount: input.tiyinAsWholeSum("amountTiyin"),
2189
+ account: input.optionalJson("account") ?? {},
2190
+ sms: input.optionalObject("sms", readOtpSms)
2191
+ };
2192
+ return send(http, ENDPOINTS$4.startPanPayment, {
2193
+ body,
2194
+ signal
2195
+ }, decodePanPaymentStarted);
2196
+ },
2197
+ async confirmPanPayment(params, options) {
2198
+ const { input, signal } = readCall(params, options, "payments.confirmPanPayment");
2199
+ const body = {
2200
+ transactionId: input.string("transactionId"),
2201
+ otp: input.string("otp"),
2202
+ sms: input.optionalObject("sms", readOtpSms)
2203
+ };
2204
+ return send(http, ENDPOINTS$4.confirmPanPayment, {
2205
+ body,
2206
+ signal
2207
+ }, decodeTransactionReference);
2208
+ }
2209
+ };
2210
+ }
2211
+ // src/splits/decoders.ts
2212
+ /** One `splitPayment/status/` entry; `amount` is tiyin. */
2213
+ const decodeSplitShare = (value, path) => {
2214
+ const field = readFields(value, path);
2215
+ return {
2216
+ recipientId: field("recipientId", asString),
2217
+ amountTiyin: field("amount", asTiyin),
2218
+ status: field("status", asString),
2219
+ createdAtRaw: field("createdAt", asString)
2220
+ };
2221
+ };
2222
+ /** `splitPayment/status/` result: one entry per recipient. */
2223
+ const decodeSplitShares = arrayOf(decodeSplitShare);
2224
+ // src/splits/resource.ts
2225
+ const ENDPOINTS$3 = {
2226
+ create: {
2227
+ method: "POST",
2228
+ route: "/merchant/splitPayment/",
2229
+ shape: "envelope"
2230
+ },
2231
+ get: {
2232
+ method: "GET",
2233
+ route: "/merchant/splitPayment/status/",
2234
+ shape: "envelope"
2235
+ }
2236
+ };
2237
+ function readRecipient(recipient) {
2238
+ return {
2239
+ recipientId: recipient.string("recipientId"),
2240
+ amount: recipient.tiyin("amountTiyin"),
2241
+ items: recipient.optionalArray("items", readReceiptItem)
2242
+ };
2243
+ }
2244
+ function createSplitsResource(http) {
2245
+ return {
2246
+ async create(params, options) {
2247
+ const { input, signal } = readCall(params, options, "splits.create");
2248
+ const body = {
2249
+ transactionId: input.string("transactionId"),
2250
+ recipients: input.array("recipients", readRecipient),
2251
+ resendOFD: input.optionalBoolean("resendOfd")
2252
+ };
2253
+ return send(http, ENDPOINTS$3.create, {
2254
+ body,
2255
+ signal
2256
+ }, decodeTransactionReference);
2257
+ },
2258
+ async get(params, options) {
2259
+ const { input, signal } = readCall(params, options, "splits.get");
2260
+ const query = { transactionId: input.string("transactionId") };
2261
+ return send(http, ENDPOINTS$3.get, {
2262
+ query,
2263
+ signal
2264
+ }, decodeSplitShares);
2265
+ }
2266
+ };
2267
+ }
2268
+ // src/subMerchants/decoders.ts
2269
+ /** `subMerchant/merchant-create/` result. */
2270
+ const decodeSubMerchantCreated = (value, path) => {
2271
+ const field = readFields(value, path);
2272
+ return {
2273
+ subMerchantId: field("id", asString),
2274
+ name: field("name", asString)
2275
+ };
2276
+ };
2277
+ // src/subMerchants/resource.ts
2278
+ const ENDPOINTS$2 = { create: {
2279
+ method: "POST",
2280
+ route: "/merchant/subMerchant/merchant-create/",
2281
+ shape: "envelope"
2282
+ } };
2283
+ function readOrganization(organization) {
2284
+ return {
2285
+ name: organization.string("name"),
2286
+ director_pinfl: organization.string("directorPinfl"),
2287
+ account_number: organization.string("accountNumber"),
2288
+ oked: organization.string("oked"),
2289
+ legal_name: organization.optionalString("legalName"),
2290
+ director_fio: organization.optionalString("directorFullName"),
2291
+ director_passport: organization.optionalString("directorPassport"),
2292
+ director_passport_valid_to: organization.optionalString("directorPassportValidTo"),
2293
+ director_birth_date: organization.optionalString("directorBirthDate"),
2294
+ director_nationality: organization.optionalString("directorNationality"),
2295
+ dr_nationality_for_uzcard: organization.optionalString("directorNationalityUzcard"),
2296
+ dr_nationality_for_humo: organization.optionalString("directorNationalityHumo"),
2297
+ mfo: organization.optionalString("mfo")
2298
+ };
2299
+ }
2300
+ function createSubMerchantsResource(http) {
2301
+ return { async create(params, options) {
2302
+ const { input, signal } = readCall(params, options, "subMerchants.create");
2303
+ const organization = input.optionalObject("organization", readOrganization);
2304
+ const pinfl = input.optionalString("pinfl");
2305
+ const needsTin = organization !== void 0 || pinfl === void 0;
2306
+ const body = {
2307
+ name: input.string("name"),
2308
+ tin: needsTin ? input.string("tin") : input.optionalString("tin"),
2309
+ pinfl,
2310
+ external_id: input.optionalString("externalId"),
2311
+ create_new_organization: organization === void 0 ? void 0 : true,
2312
+ organization,
2313
+ self_employee_service: input.optionalBoolean("isSelfEmployed"),
2314
+ ofd_vat_percent: input.optionalInteger("ofdVatPercent"),
2315
+ SPIC: input.optionalString("spic"),
2316
+ spic_package_code: input.optionalString("spicPackageCode")
2317
+ };
2318
+ return send(http, ENDPOINTS$2.create, {
2319
+ body,
2320
+ signal
2321
+ }, decodeSubMerchantCreated);
2322
+ } };
2323
+ }
2324
+ // src/transactions/decoders.ts
2325
+ /**
2326
+ * The SDK's word for each wire status it renames. The fake encodes a word as its first wire
2327
+ * spelling here.
2328
+ */
2329
+ const TRANSACTION_STATUS_BY_WIRE = /* @__PURE__ */ new Map([
2330
+ ["waiting", "held"],
2331
+ ["payed", "paid"],
2332
+ ["cancel", "refunded"],
2333
+ ["refunded", "refunded"]
2334
+ ]);
2335
+ const decodeTransactionStatus = statusDecoder(TRANSACTION_STATUS_BY_WIRE);
2336
+ const decodeFiscalReceiptSummary = (value, path) => {
2337
+ const receipt = readFields(value, path);
2338
+ return {
2339
+ receiptId: receipt("receipt_id", asNonNegativeInteger),
2340
+ receiptUrl: receipt("qr_code_url", asString),
2341
+ issuedAtRaw: receipt("date_time", asString),
2342
+ isRefund: receipt("is_refund", asBoolean)
2343
+ };
2344
+ };
2345
+ /**
2346
+ * Withholds `owner` (cardholder name), the float SUM `amount`, the label `transaction_type` and
2347
+ * `account`, which reads `{}` whatever was sent [OPEN Q87].
2348
+ */
2349
+ const decodeTransaction = (value, path) => {
2350
+ const transaction = readFields(value, path);
2351
+ return {
2352
+ transactionId: transaction("id", asString),
2353
+ externalId: transaction("external_id", nullable(asString)),
2354
+ userId: transaction("userId", nullable(asString)),
2355
+ cardId: transaction("card_id", nullable(asString)),
2356
+ maskedCardNumber: transaction("cardNumber", nullable(asMaskedPan)),
2357
+ amountTiyin: transaction("amount_in_tiyin", asTiyin),
2358
+ status: transaction("status", decodeTransactionStatus),
2359
+ declineCode: transaction("error_message", nullable(asString)),
2360
+ paidOrCreatedAt: transaction("date", asTashkentDateTime),
2361
+ cancelledAt: transaction("cancel_time", nullable(asTashkentDateTime)),
2362
+ isHold: transaction("is_hold", asBoolean),
2363
+ isSplit: transaction("is_split", asBoolean),
2364
+ isA2c: transaction("is_a2c", asBoolean),
2365
+ isCheckout: transaction("via_link", nullable(asBoolean)) === true,
2366
+ fiscalReceipts: transaction("ofd", arrayOf(decodeFiscalReceiptSummary))
2367
+ };
2368
+ };
2369
+ const decodeTransactionPage = (value, path) => {
2370
+ const page = readFields(value, path);
2371
+ return {
2372
+ total: page("totalTransaction", asNonNegativeInteger),
2373
+ transactions: page("transactions", arrayOf(decodeTransaction))
2374
+ };
2375
+ };
2376
+ const decodeRows = fieldOf("transactions", arrayOf(decodeTransaction));
2377
+ /**
2378
+ * The `getTransactions?id=` result: no row is a miss. Without a usable `id` the endpoint lists
2379
+ * paid transactions instead, so any other row, or more than one, is malformed.
2380
+ */
2381
+ function decodeRequestedTransaction(transactionId) {
2382
+ return (value, path) => {
2383
+ const rows = decodeRows(value, path);
2384
+ const [row] = rows;
2385
+ if (row === void 0) return null;
2386
+ if (rows.length > 1 || row.transactionId.toLowerCase() !== transactionId.toLowerCase()) throw new DecodeFailure(`${path}.transactions`);
2387
+ return row;
2388
+ };
2389
+ }
2390
+ /** `getTransactions/rrn/{id}/` result. */
2391
+ const decodeRrn = fieldOf("rrn", asString);
2392
+ // src/transactions/resource.ts
2393
+ const ENDPOINTS$1 = {
2394
+ getTransactions: {
2395
+ method: "GET",
2396
+ route: "/merchant/getTransactions/",
2397
+ shape: "envelope"
2398
+ },
2399
+ getRrn: {
2400
+ method: "GET",
2401
+ route: "/merchant/getTransactions/rrn/{transactionId}/",
2402
+ shape: "envelope"
2403
+ }
2404
+ };
2405
+ function createTransactionsResource(http) {
2406
+ return {
2407
+ async get(params, options) {
2408
+ const { input, signal } = readCall(params, options, "transactions.get");
2409
+ const transactionId = input.string("transactionId");
2410
+ return send(http, ENDPOINTS$1.getTransactions, {
2411
+ query: { id: transactionId },
2412
+ signal
2413
+ }, decodeRequestedTransaction(transactionId));
2414
+ },
2415
+ async list(params, options) {
2416
+ const { input, signal } = readCall(params ?? {}, options, "transactions.list");
2417
+ const query = {
2418
+ beginDate: input.optionalString("fromDate"),
2419
+ endDate: input.optionalString("toDate"),
2420
+ page: input.optionalInteger("page")
2421
+ };
2422
+ return send(http, ENDPOINTS$1.getTransactions, {
2423
+ query,
2424
+ signal
2425
+ }, decodeTransactionPage);
2426
+ },
2427
+ async getRrn(params, options) {
2428
+ const { input, signal } = readCall(params, options, "transactions.getRrn");
2429
+ const transactionId = input.string("transactionId");
2430
+ return send(http, ENDPOINTS$1.getRrn, {
2431
+ path: { transactionId },
2432
+ signal
2433
+ }, decodeRrn);
2434
+ }
2435
+ };
2436
+ }
2437
+ // src/shared/checkoutAmount.ts
2438
+ /**
2439
+ * A checkout amount in the minor unit of its currency, shared by the checkout link and the
2440
+ * check/perform callbacks. The wire carries one integer plus a numeric currency code.
2441
+ */
2442
+ /** The `CheckoutCurrency` values, for runtime checks. */
2443
+ const CHECKOUT_CURRENCIES = everyLiteral()([860, 840]);
2444
+ /** Reads a checkout amount object under `key`; failures are `sdk_invalid_amount`. */
2445
+ function readCheckoutAmount(params, key) {
2446
+ return params.object(key, (amount) => amount.literal("currency", CHECKOUT_CURRENCIES) === 860 ? {
2447
+ currency: 860,
2448
+ amountTiyin: amount.tiyin("amountTiyin")
2449
+ } : {
2450
+ currency: 840,
2451
+ amountCents: amount.tiyin("amountCents")
2452
+ });
2453
+ }
2454
+ /** The integer the wire carries for the amount. */
2455
+ function minorUnitsOf(amount) {
2456
+ return amount.currency === 860 ? amount.amountTiyin : amount.amountCents;
2457
+ }
2458
+ /** Decodes a wire minor-unit amount and currency code, or `undefined` when either is invalid. */
2459
+ function decodeCheckoutAmount(minorUnits, currency) {
2460
+ if (!isNonNegativeSafeInteger(minorUnits)) return void 0;
2461
+ if (currency === 860) return {
2462
+ currency,
2463
+ amountTiyin: minorUnits
2464
+ };
2465
+ if (currency === 840) return {
2466
+ currency,
2467
+ amountCents: minorUnits
2468
+ };
2469
+ }
2470
+ // src/onboarding/decoders.ts
2471
+ /** `{"status":"ok"}` means the token is usable. */
2472
+ const decodeTokenUsable = (value, path) => {
2473
+ fieldOf("status", asLiteral("ok"))(value, path);
2474
+ return true;
2475
+ };
2476
+ /** Failures name the field, never its value: the same body holds the consumer secret. */
2477
+ const decodeOnboardingCompleted = (value, path) => {
2478
+ const field = readFields(value, path);
2479
+ return {
2480
+ consumerKey: field("consumer_key", asString),
2481
+ consumerSecret: field("consumer_secret", asString),
2482
+ username: field("username", asString)
2483
+ };
2484
+ };
2485
+ // src/onboarding/client.ts
2486
+ /** The operator onboarding step that issues merchant API credentials. */
2487
+ const ENDPOINTS = {
2488
+ checkToken: {
2489
+ method: "GET",
2490
+ route: "/merchant/onboarding/",
2491
+ shape: "flat",
2492
+ miss: "invalid_or_expired"
2493
+ },
2494
+ complete: {
2495
+ method: "POST",
2496
+ route: "/merchant/onboarding/",
2497
+ shape: "flat"
2498
+ }
2499
+ };
2500
+ /**
2501
+ * Completes Paylov merchant onboarding with the single-use token Paylov issues. It needs no
2502
+ * merchant credentials and is an operator step, run once, not part of a running integration.
2503
+ * The token travels in the query string and is never logged; the password and the issued
2504
+ * consumer secret never reach logger events or errors.
2505
+ *
2506
+ * @example
2507
+ * const onboarding = new PaylovOnboarding({ baseUrl: 'https://dev.gw.paylov.uz' });
2508
+ * if (!(await onboarding.checkToken({ token: onboardingToken }))) {
2509
+ * throw new Error('onboarding token is consumed or expired; ask Paylov for a new one');
2510
+ * }
2511
+ *
2512
+ * @throws {@link PaylovInputError} `sdk_config_error` for malformed configuration.
2513
+ */
2514
+ var PaylovOnboarding = class {
2515
+ #http;
2516
+ constructor(config) {
2517
+ this.#http = createHttpClient(readSurfaceTransport(readConfig(config, "PaylovOnboarding config")));
2518
+ }
2519
+ /**
2520
+ * Checks whether an onboarding token can still be used (`GET /merchant/onboarding/?token=`).
2521
+ * Resolves `false` when Paylov reports the token unknown, consumed or expired
2522
+ * (`invalid_or_expired`).
2523
+ *
2524
+ * @throws {@link PaylovApiError} any other gateway error, e.g. `validation_error`.
2525
+ *
2526
+ * @example
2527
+ * const usable = await onboarding.checkToken({ token: onboardingToken });
2528
+ * if (!usable) throw new Error('ask Paylov for a new onboarding token');
2529
+ */
2530
+ async checkToken(params, options) {
2531
+ const { input, signal } = readCall(params, options, "onboarding.checkToken");
2532
+ const query = { token: input.string("token") };
2533
+ return orOnMiss(send(this.#http, ENDPOINTS.checkToken, {
2534
+ query,
2535
+ signal
2536
+ }, decodeTokenUsable), ENDPOINTS.checkToken, false);
2537
+ }
2538
+ /**
2539
+ * Sets the merchant API username and password and returns the issued credentials
2540
+ * (`POST /merchant/onboarding/?token=`). The token is single-use and `consumerSecret` is shown
2541
+ * only once: persist the whole result before doing anything else. The account stays inactive
2542
+ * until Paylov activates it; until then a `PaylovClient` with these credentials fails with
2543
+ * `invalid_grant`.
2544
+ *
2545
+ * Recovery: never retried. When `isPaylovOutcomeUnknown(error)`, the credentials may have been
2546
+ * issued and lost: call `checkToken`; `true` means `complete` can run again, `false` that the
2547
+ * token was used, so ask Paylov to reissue the credentials.
2548
+ *
2549
+ * @throws {@link PaylovApiError} `validation_error` (see `fields`), or `invalid_or_expired`
2550
+ * for an unknown, used or expired token.
2551
+ *
2552
+ * @example
2553
+ * const credentials = await onboarding.complete({
2554
+ * token: onboardingToken,
2555
+ * username: merchantUsername,
2556
+ * password: merchantPassword,
2557
+ * });
2558
+ * await secretManager.store('paylov', credentials);
2559
+ */
2560
+ async complete(params, options) {
2561
+ const { input, signal } = readCall(params, options, "onboarding.complete");
2562
+ const query = { token: input.string("token") };
2563
+ const body = {
2564
+ username: input.string("username"),
2565
+ password: input.string("password")
2566
+ };
2567
+ return send(this.#http, ENDPOINTS.complete, {
2568
+ query,
2569
+ body,
2570
+ signal
2571
+ }, decodeOnboardingCompleted);
2572
+ }
2573
+ };
2574
+ export { tiyinToWireSum as $, readConfig as A, decodeErrorDetails as B, WIRE_ACTIVITY_TYPES as C, createCardsResource as D, ENDPOINTS$8 as E, createHttpClient as F, asTiyin as G, asJsonObject as H, endpointName as I, fieldOf as J, asUnixDateTime as K, isRetryableStatus as L, readSurfaceTransport as M, ENDPOINTS$9 as N, everyLiteral as O, TokenManager as P, sumToTiyin as Q, ClientLifecycle as R, ENDPOINTS$7 as S, readTransactionLookup as T, asNonEmptyString as U, DecodeFailure as V, asRecord as W, readFields as X, isRecord as Y, formatSum as Z, createHoldsResource as _, minorUnitsOf as a, PaylovProtocolError as at, createGatewayResource as b, createTransactionsResource as c, isPaylovApiError as ct, createSubMerchantsResource as d, wireSumToTiyin as et, ENDPOINTS$3 as f, ENDPOINTS$5 as g, createPaymentsResource as h, decodeCheckoutAmount as i, PaylovInputError as it, readParams as j, readCallSignal as k, TRANSACTION_STATUS_BY_WIRE as l, isPaylovError as lt, ENDPOINTS$4 as m, PaylovOnboarding as n, PaylovClientClosedError as nt, readCheckoutAmount as o, configError as ot, createSplitsResource as p, asUuid as q, CHECKOUT_CURRENCIES as r, PaylovConnectionError as rt, ENDPOINTS$1 as s, invalidInput as st, ENDPOINTS as t, PaylovApiError as tt, ENDPOINTS$2 as u, isPaylovOutcomeUnknown as ut, HOLD_STATUS_BY_WIRE as v, createFiscalizationResource as w, ACTIVITY_TYPES as x, ENDPOINTS$6 as y, isWireErrorCode as z };
2575
+
2576
+ //# sourceMappingURL=client-DOu4B-bL.js.map