@miguelmorales13/nestkit 0.11.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/README.md +619 -35
  2. package/dist/audit/audit.module.d.ts +23 -0
  3. package/dist/audit/audit.options.d.ts +16 -0
  4. package/dist/audit/audit.port.d.ts +37 -0
  5. package/dist/audit/audit.service.d.ts +29 -0
  6. package/dist/audit/index.cjs +72 -0
  7. package/dist/audit/index.d.ts +7 -0
  8. package/dist/audit/index.js +72 -0
  9. package/dist/audit/sinks.d.ts +18 -0
  10. package/dist/auth/index.cjs +12 -10
  11. package/dist/auth/index.js +5 -3
  12. package/dist/auth/oauth/http.d.ts +10 -3
  13. package/dist/auth/oauth/index.cjs +189 -29
  14. package/dist/auth/oauth/index.d.ts +6 -4
  15. package/dist/auth/oauth/index.js +169 -9
  16. package/dist/auth/oauth/magic-link.dto.d.ts +6 -0
  17. package/dist/auth/oauth/memory-magic-link.store.d.ts +19 -0
  18. package/dist/auth/oauth/oauth-auth.service.d.ts +46 -5
  19. package/dist/auth/oauth/oauth.controller.d.ts +5 -1
  20. package/dist/auth/oauth/oauth.options.d.ts +34 -1
  21. package/dist/auth/oauth/oauth.ports.d.ts +38 -0
  22. package/dist/bootstrap/index.cjs +9 -6
  23. package/dist/bootstrap/index.js +8 -5
  24. package/dist/{chunk-TJHRABML.cjs → chunk-3AUOOEQO.cjs} +12 -7
  25. package/dist/{chunk-NVCI3CQI.cjs → chunk-4HHZFOVC.cjs} +10 -5
  26. package/dist/{chunk-EYURGACO.js → chunk-4PFAKLT3.js} +1 -1
  27. package/dist/chunk-52IOOHNX.cjs +205 -0
  28. package/dist/chunk-6RAPVLJM.js +212 -0
  29. package/dist/{chunk-7I2Y7V52.js → chunk-A2DGK4ZL.js} +26 -3
  30. package/dist/chunk-APUFKA4K.cjs +212 -0
  31. package/dist/chunk-AXMW5JF7.cjs +83 -0
  32. package/dist/{chunk-KDAA6GFF.js → chunk-DYHSOULW.js} +12 -7
  33. package/dist/chunk-ETRUVZTJ.js +43 -0
  34. package/dist/{chunk-54ZXIB5T.cjs → chunk-FNUZGYUF.cjs} +4 -4
  35. package/dist/{chunk-FDNGAYTZ.cjs → chunk-HDFPSA2V.cjs} +6 -6
  36. package/dist/{chunk-V2M75FN3.cjs → chunk-HVHYZXBB.cjs} +2 -2
  37. package/dist/chunk-IFNYRZP2.js +205 -0
  38. package/dist/{chunk-A3B2EY4V.js → chunk-IKXSVEJ7.js} +7 -2
  39. package/dist/{chunk-YFYHLYHN.js → chunk-M3GQDRWR.js} +7 -1
  40. package/dist/{chunk-J7TURDAL.cjs → chunk-MSTXS3MU.cjs} +28 -5
  41. package/dist/chunk-PNK5WMPP.cjs +30 -0
  42. package/dist/chunk-Q5Y33L7B.cjs +19 -0
  43. package/dist/{chunk-ZA56XBCK.cjs → chunk-SDWHKPXI.cjs} +23 -0
  44. package/dist/chunk-TCAMLNUZ.js +27 -0
  45. package/dist/{chunk-AOCF5QCZ.js → chunk-UNEVXCFW.js} +2 -2
  46. package/dist/chunk-VVMRZEIW.js +30 -0
  47. package/dist/chunk-W2T2VFLC.cjs +57 -0
  48. package/dist/chunk-X4PQJZ4G.js +83 -0
  49. package/dist/chunk-Y72D5L6I.cjs +27 -0
  50. package/dist/{chunk-ORWJ7LES.js → chunk-ZFIDAX7K.js} +1 -1
  51. package/dist/chunk-ZJMLEP5H.js +57 -0
  52. package/dist/crud/crud.controller.d.ts +3 -1
  53. package/dist/crud/crud.service.d.ts +63 -4
  54. package/dist/crud/index.cjs +7 -2
  55. package/dist/crud/index.d.ts +2 -1
  56. package/dist/crud/index.js +6 -1
  57. package/dist/crud/list-query.dto.d.ts +23 -0
  58. package/dist/crud/repository.port.d.ts +33 -1
  59. package/dist/errors/app.exception.d.ts +9 -1
  60. package/dist/errors/common.exceptions.d.ts +6 -5
  61. package/dist/errors/global-exception.filter.d.ts +9 -0
  62. package/dist/errors/index.cjs +8 -5
  63. package/dist/errors/index.js +9 -6
  64. package/dist/i18n/i18n.interceptor.d.ts +16 -0
  65. package/dist/i18n/i18n.module.d.ts +49 -3
  66. package/dist/i18n/index.cjs +26 -2
  67. package/dist/i18n/index.d.ts +8 -0
  68. package/dist/i18n/index.js +25 -1
  69. package/dist/i18n/locale.d.ts +53 -0
  70. package/dist/i18n/message.d.ts +36 -0
  71. package/dist/i18n/nestjs-i18n.translator.d.ts +9 -0
  72. package/dist/i18n/runtime.d.ts +55 -0
  73. package/dist/i18n/translator.port.d.ts +29 -0
  74. package/dist/idempotency/idempotency.interceptor.d.ts +35 -0
  75. package/dist/idempotency/idempotency.module.d.ts +27 -0
  76. package/dist/idempotency/idempotency.options.d.ts +29 -0
  77. package/dist/idempotency/idempotency.port.d.ts +43 -0
  78. package/dist/idempotency/index.cjs +207 -0
  79. package/dist/idempotency/index.d.ts +7 -0
  80. package/dist/idempotency/index.js +207 -0
  81. package/dist/idempotency/memory.store.d.ts +24 -0
  82. package/dist/index.cjs +48 -15
  83. package/dist/index.js +51 -18
  84. package/dist/invoicing/adapters/facturama.invoicing.d.ts +50 -0
  85. package/dist/invoicing/adapters/facturapi.invoicing.d.ts +35 -0
  86. package/dist/invoicing/amounts.d.ts +52 -0
  87. package/dist/invoicing/index.cjs +578 -0
  88. package/dist/invoicing/index.d.ts +11 -0
  89. package/dist/invoicing/index.js +578 -0
  90. package/dist/invoicing/invoicing.module.d.ts +42 -0
  91. package/dist/invoicing/invoicing.options.d.ts +51 -0
  92. package/dist/invoicing/invoicing.port.d.ts +156 -0
  93. package/dist/invoicing/lines.d.ts +21 -0
  94. package/dist/invoicing/provider-http.d.ts +21 -0
  95. package/dist/payments/adapters/clip.terminal.d.ts +101 -0
  96. package/dist/payments/adapters/mercadopago.terminal.d.ts +74 -0
  97. package/dist/payments/index.cjs +796 -0
  98. package/dist/payments/index.d.ts +12 -0
  99. package/dist/payments/index.js +796 -0
  100. package/dist/payments/money.d.ts +20 -0
  101. package/dist/payments/payments-webhook.controller.d.ts +30 -0
  102. package/dist/payments/payments.module.d.ts +45 -0
  103. package/dist/payments/payments.options.d.ts +84 -0
  104. package/dist/payments/payments.port.d.ts +174 -0
  105. package/dist/payments/provider-http.d.ts +26 -0
  106. package/dist/response/api-response.d.ts +7 -0
  107. package/dist/response/index.cjs +12 -4
  108. package/dist/response/index.d.ts +2 -0
  109. package/dist/response/index.js +12 -4
  110. package/dist/response/paginated.d.ts +25 -0
  111. package/dist/response/response.interceptor.d.ts +4 -0
  112. package/dist/stripe/index.cjs +4 -3
  113. package/dist/stripe/index.js +3 -2
  114. package/dist/tracking/index.cjs +3 -3
  115. package/dist/tracking/index.d.ts +1 -1
  116. package/dist/tracking/index.js +2 -2
  117. package/dist/tracking/request-context.d.ts +32 -0
  118. package/package.json +25 -3
  119. package/dist/chunk-3CLYZC3T.cjs +0 -104
  120. package/dist/chunk-EBO6UKHL.js +0 -20
  121. package/dist/chunk-IYUUYCP5.js +0 -36
  122. package/dist/chunk-JOVBJDJ2.js +0 -104
  123. package/dist/chunk-M3EL5O6T.cjs +0 -36
  124. package/dist/chunk-R7BVS6CI.cjs +0 -13
  125. /package/dist/{chunk-MR2IFCZE.cjs → chunk-H2EHN366.cjs} +0 -0
  126. /package/dist/{chunk-NAK4WDKS.js → chunk-ODPSIFOB.js} +0 -0
@@ -0,0 +1,796 @@
1
+ import {
2
+ UnauthorizedAppException,
3
+ ValidationAppException
4
+ } from "../chunk-ZFIDAX7K.js";
5
+ import {
6
+ AppException
7
+ } from "../chunk-M3GQDRWR.js";
8
+ import "../chunk-VVMRZEIW.js";
9
+ import {
10
+ __decorateClass,
11
+ __decorateParam
12
+ } from "../chunk-4MGIQFAJ.js";
13
+
14
+ // src/payments/payments.port.ts
15
+ var TERMINAL_PAYMENTS = /* @__PURE__ */ Symbol("TERMINAL_PAYMENTS");
16
+
17
+ // src/payments/payments.options.ts
18
+ var PAYMENTS_OPTIONS = /* @__PURE__ */ Symbol("PAYMENTS_OPTIONS");
19
+
20
+ // src/payments/payments.module.ts
21
+ import { Global, Module } from "@nestjs/common";
22
+
23
+ // src/payments/adapters/mercadopago.terminal.ts
24
+ import { createHmac, randomUUID, timingSafeEqual } from "crypto";
25
+
26
+ // src/payments/money.ts
27
+ function assertCents(cents, field = "amountCents") {
28
+ if (!Number.isInteger(cents)) {
29
+ throw new ValidationAppException(`${field} must be an integer number of cents, got ${cents}`, {
30
+ [field]: cents
31
+ });
32
+ }
33
+ if (cents < 0) {
34
+ throw new ValidationAppException(`${field} must not be negative, got ${cents}`, { [field]: cents });
35
+ }
36
+ if (!Number.isSafeInteger(cents)) {
37
+ throw new ValidationAppException(`${field} is out of safe integer range`, { [field]: cents });
38
+ }
39
+ }
40
+ function centsToDecimalString(cents) {
41
+ const sign = cents < 0 ? "-" : "";
42
+ const abs = Math.abs(cents);
43
+ return `${sign}${Math.floor(abs / 100)}.${String(abs % 100).padStart(2, "0")}`;
44
+ }
45
+ function decimalToCents(value) {
46
+ const text = typeof value === "number" ? value.toFixed(2) : value.trim();
47
+ const match = /^(-?)(\d+)(?:\.(\d{1,2}))?$/.exec(text);
48
+ if (!match) {
49
+ throw new ValidationAppException(`Cannot read "${text}" as a decimal amount`, { value });
50
+ }
51
+ const [, sign, whole, fraction = ""] = match;
52
+ const cents = Number(whole) * 100 + Number(fraction.padEnd(2, "0"));
53
+ return sign === "-" ? -cents : cents;
54
+ }
55
+
56
+ // src/payments/provider-http.ts
57
+ import { HttpStatus } from "@nestjs/common";
58
+ var TerminalPaymentProviderException = class extends AppException {
59
+ constructor(provider, status, body, message) {
60
+ super(
61
+ "TERMINAL_PAYMENT_PROVIDER_ERROR",
62
+ message ?? `${provider} rejected the request (HTTP ${status})`,
63
+ HttpStatus.BAD_GATEWAY,
64
+ { provider, status, body }
65
+ );
66
+ }
67
+ };
68
+ var UnsupportedByProviderException = class extends AppException {
69
+ constructor(provider, message) {
70
+ super("TERMINAL_PAYMENT_UNSUPPORTED", message, HttpStatus.BAD_REQUEST, { provider });
71
+ }
72
+ };
73
+ async function requestJson(provider, fetchImpl, url, init) {
74
+ let response;
75
+ try {
76
+ response = await fetchImpl(url, init);
77
+ } catch (cause) {
78
+ throw new TerminalPaymentProviderException(
79
+ provider,
80
+ 0,
81
+ { error: cause instanceof Error ? cause.message : String(cause) },
82
+ `${provider} is unreachable`
83
+ );
84
+ }
85
+ const text = await response.text();
86
+ let body = void 0;
87
+ if (text) {
88
+ try {
89
+ body = JSON.parse(text);
90
+ } catch {
91
+ body = text;
92
+ }
93
+ }
94
+ if (!response.ok) {
95
+ throw new TerminalPaymentProviderException(provider, response.status, body);
96
+ }
97
+ return body;
98
+ }
99
+
100
+ // src/payments/adapters/mercadopago.terminal.ts
101
+ var PROVIDER = "mercadopago";
102
+ var DEFAULT_BASE_URL = "https://api.mercadopago.com";
103
+ function toStatus(status) {
104
+ switch (status) {
105
+ case "created":
106
+ case "action_required":
107
+ return "pending";
108
+ case "at_terminal":
109
+ return "at_terminal";
110
+ case "processed":
111
+ return "approved";
112
+ case "failed":
113
+ return "rejected";
114
+ case "canceled":
115
+ return "cancelled";
116
+ case "expired":
117
+ return "expired";
118
+ case "refunded":
119
+ return "refunded";
120
+ default:
121
+ return "unknown";
122
+ }
123
+ }
124
+ function assertReference(reference) {
125
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(reference)) {
126
+ throw new ValidationAppException(
127
+ "reference must be 1-64 characters of letters, digits, hyphens or underscores for Mercado Pago",
128
+ { reference }
129
+ );
130
+ }
131
+ }
132
+ var MercadoPagoTerminalPayments = class {
133
+ constructor(options) {
134
+ this.options = options;
135
+ this.provider = PROVIDER;
136
+ if (!options.accessToken) {
137
+ throw new Error("MercadoPagoTerminalPayments: accessToken is required (MERCADOPAGO_ACCESS_TOKEN).");
138
+ }
139
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
140
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
141
+ }
142
+ headers(extra = {}) {
143
+ return {
144
+ authorization: `Bearer ${this.options.accessToken}`,
145
+ "content-type": "application/json",
146
+ ...extra
147
+ };
148
+ }
149
+ async listTerminals() {
150
+ const terminals = [];
151
+ const limit = 50;
152
+ let offset = 0;
153
+ for (; ; ) {
154
+ const page = await requestJson(PROVIDER, this.fetchImpl, `${this.baseUrl}/terminals/v1/list?limit=${limit}&offset=${offset}`, {
155
+ method: "GET",
156
+ headers: this.headers()
157
+ });
158
+ const batch = page.data?.terminals ?? page.terminals ?? [];
159
+ for (const terminal of batch) {
160
+ terminals.push({
161
+ id: terminal.id,
162
+ // Mercado Pago's list says nothing about connectivity.
163
+ online: void 0,
164
+ operatingMode: terminal.operating_mode === "PDV" ? "pdv" : terminal.operating_mode === "STANDALONE" ? "standalone" : "unknown",
165
+ raw: terminal
166
+ });
167
+ }
168
+ offset += batch.length;
169
+ const total = page.paging?.total ?? terminals.length;
170
+ if (batch.length === 0 || terminals.length >= total) return terminals;
171
+ }
172
+ }
173
+ async charge(input) {
174
+ assertCents(input.amountCents);
175
+ if (input.tipCents !== void 0) {
176
+ throw new UnsupportedByProviderException(
177
+ PROVIDER,
178
+ "Mercado Pago Point orders have no tip field \u2014 the terminal collects tips on its own if the store has them enabled. Drop tipCents, or use the Clip adapter."
179
+ );
180
+ }
181
+ if (input.webhookUrl) {
182
+ throw new UnsupportedByProviderException(
183
+ PROVIDER,
184
+ 'Mercado Pago notifies the URL configured in Your integrations -> Webhooks, not one passed per order. Configure it there (topic "Order") and drop webhookUrl.'
185
+ );
186
+ }
187
+ assertReference(input.reference);
188
+ const printOnTerminal = this.options.printOnTerminal ?? (input.printReceipt === false ? "no_ticket" : void 0);
189
+ const order = await requestJson(PROVIDER, this.fetchImpl, `${this.baseUrl}/v1/orders`, {
190
+ method: "POST",
191
+ headers: this.headers({ "x-idempotency-key": input.idempotencyKey ?? randomUUID() }),
192
+ body: JSON.stringify({
193
+ type: "point",
194
+ external_reference: input.reference,
195
+ description: input.description,
196
+ expiration_time: input.expiresInMinutes === void 0 ? void 0 : `PT${input.expiresInMinutes}M`,
197
+ transactions: { payments: [{ amount: centsToDecimalString(input.amountCents) }] },
198
+ config: {
199
+ point: {
200
+ terminal_id: input.terminalId,
201
+ print_on_terminal: printOnTerminal
202
+ }
203
+ }
204
+ })
205
+ });
206
+ return this.toPayment(order, input.amountCents);
207
+ }
208
+ async get(id) {
209
+ const order = await requestJson(PROVIDER, this.fetchImpl, `${this.baseUrl}/v1/orders/${encodeURIComponent(id)}`, {
210
+ method: "GET",
211
+ headers: this.headers()
212
+ });
213
+ return this.toPayment(order);
214
+ }
215
+ async cancel(id) {
216
+ const order = await requestJson(
217
+ PROVIDER,
218
+ this.fetchImpl,
219
+ `${this.baseUrl}/v1/orders/${encodeURIComponent(id)}/cancel`,
220
+ {
221
+ method: "POST",
222
+ headers: this.headers({
223
+ "x-idempotency-key": randomUUID(),
224
+ // Without this header an order the terminal has already picked up
225
+ // cannot be cancelled at all, which is most of them: the terminal
226
+ // fetches within seconds. Mercado Pago still refuses once the card
227
+ // is in, and that refusal surfaces as a provider error.
228
+ "x-allow-cancelable-status": "at_terminal"
229
+ })
230
+ }
231
+ );
232
+ return this.toPayment(order);
233
+ }
234
+ /**
235
+ * Refunds a settled order: the whole thing, or `amountCents` of it.
236
+ *
237
+ * Mercado Pago allows this for card payments within 90 days, only while the
238
+ * order is `processed`, and it is not idempotent on its own — the header is,
239
+ * for 24 hours. A partial refund has to name the payment it is refunding,
240
+ * which is why the order is read first: the id the caller holds is the
241
+ * order's, and the API wants the payment's.
242
+ */
243
+ async refund(id, options = {}) {
244
+ let body;
245
+ if (options.amountCents !== void 0) {
246
+ assertCents(options.amountCents);
247
+ const order = await this.get(id);
248
+ const paymentId = order.raw.transactions?.payments?.[0]?.id;
249
+ if (!paymentId) {
250
+ throw new TerminalPaymentProviderException(
251
+ PROVIDER,
252
+ 200,
253
+ order.raw,
254
+ "Cannot refund part of an order that carries no payment id"
255
+ );
256
+ }
257
+ body = JSON.stringify({
258
+ transactions: [{ id: paymentId, amount: centsToDecimalString(options.amountCents) }]
259
+ });
260
+ }
261
+ const refunded = await requestJson(
262
+ PROVIDER,
263
+ this.fetchImpl,
264
+ `${this.baseUrl}/v1/orders/${encodeURIComponent(id)}/refund`,
265
+ {
266
+ method: "POST",
267
+ // An empty body is what "refund everything" looks like here.
268
+ headers: this.headers({ "x-idempotency-key": randomUUID() }),
269
+ body
270
+ }
271
+ );
272
+ return this.toPayment(refunded);
273
+ }
274
+ /**
275
+ * Puts terminals into the mode that makes them answer the API at all.
276
+ *
277
+ * A terminal ships in `STANDALONE`, where it runs the merchant app and
278
+ * **ignores API charges without saying so**. `PDV` is the integrated mode,
279
+ * and the terminal has to be **restarted** for the change to take — an
280
+ * unrestarted terminal keeps swallowing charges, which is the single most
281
+ * expensive way to discover this.
282
+ */
283
+ async setOperatingMode(terminalIds, mode) {
284
+ const response = await requestJson(
285
+ PROVIDER,
286
+ this.fetchImpl,
287
+ `${this.baseUrl}/terminals/v1/setup`,
288
+ {
289
+ method: "PATCH",
290
+ headers: this.headers(),
291
+ body: JSON.stringify({ terminals: terminalIds.map((id) => ({ id, operating_mode: mode })) })
292
+ }
293
+ );
294
+ return (response.terminals ?? []).map((terminal) => ({
295
+ id: terminal.id,
296
+ operatingMode: terminal.operating_mode === "PDV" ? "pdv" : terminal.operating_mode === "STANDALONE" ? "standalone" : "unknown",
297
+ raw: terminal
298
+ }));
299
+ }
300
+ /**
301
+ * Forces a final status on an order created with **test credentials**, so a
302
+ * whole flow — order, status change, webhook — can be exercised without a
303
+ * terminal in the room.
304
+ *
305
+ * This is the reason this integration is testable at all: pair it with the
306
+ * virtual device serial `SBX0000001` (e.g. `NEWLAND_N950__SBX0000001`) and
307
+ * the notification that arrives is the same one production sends. Takes up
308
+ * to 10 seconds to land, 40 for `action_required`. Against production
309
+ * credentials it does nothing but fail.
310
+ */
311
+ async simulateStatus(orderId, event) {
312
+ await requestJson(
313
+ PROVIDER,
314
+ this.fetchImpl,
315
+ `${this.baseUrl}/v1/orders/${encodeURIComponent(orderId)}/events`,
316
+ {
317
+ method: "POST",
318
+ headers: this.headers(),
319
+ body: JSON.stringify({
320
+ status: event.status,
321
+ status_detail: event.statusDetail,
322
+ payment_method_id: event.paymentMethodId,
323
+ payment_method_type: event.paymentMethodType,
324
+ installments: event.installments
325
+ })
326
+ }
327
+ );
328
+ }
329
+ /**
330
+ * Verifies the `x-signature` header: HMAC-SHA256 of
331
+ * `id:<data.id>;request-id:<x-request-id>;ts:<ts>;` keyed with the webhook
332
+ * secret, compared in constant time.
333
+ *
334
+ * The id is lowercased before hashing, per Mercado Pago's own rule for
335
+ * alphanumeric ids — an order id like `ORD01J6...` hashed as sent never
336
+ * matches, and the failure looks exactly like a forged request.
337
+ */
338
+ verifyWebhook(request) {
339
+ const secret = this.options.webhookSecret;
340
+ if (!secret) {
341
+ throw new Error(
342
+ "MercadoPagoTerminalPayments: webhookSecret is not set (MERCADOPAGO_WEBHOOK_SECRET) \u2014 refusing to accept an unverifiable notification."
343
+ );
344
+ }
345
+ const header = (name) => {
346
+ const value = request.headers[name] ?? request.headers[name.toLowerCase()];
347
+ return Array.isArray(value) ? value[0] : value;
348
+ };
349
+ const signature = header("x-signature");
350
+ const requestId = header("x-request-id");
351
+ if (!signature || !requestId) {
352
+ throw new UnauthorizedAppException("Missing Mercado Pago webhook signature headers", void 0, "INVALID_WEBHOOK_SIGNATURE");
353
+ }
354
+ const parts = new Map(
355
+ signature.split(",").map((part) => {
356
+ const index = part.indexOf("=");
357
+ return [part.slice(0, index).trim(), part.slice(index + 1).trim()];
358
+ })
359
+ );
360
+ const ts = parts.get("ts");
361
+ const received = parts.get("v1");
362
+ const body = request.body;
363
+ const dataId = String(request.query?.["data.id"] ?? body?.data?.id ?? "");
364
+ if (!ts || !received || !dataId) {
365
+ throw new UnauthorizedAppException("Malformed Mercado Pago webhook signature", void 0, "INVALID_WEBHOOK_SIGNATURE");
366
+ }
367
+ const manifest = `id:${dataId.toLowerCase()};request-id:${requestId};ts:${ts};`;
368
+ const expected = createHmac("sha256", secret).update(manifest).digest();
369
+ const provided = Buffer.from(received, "hex");
370
+ if (provided.length !== expected.length || !timingSafeEqual(provided, expected)) {
371
+ throw new UnauthorizedAppException("Invalid Mercado Pago webhook signature", void 0, "INVALID_WEBHOOK_SIGNATURE");
372
+ }
373
+ return { provider: PROVIDER, paymentId: dataId, action: body?.action, raw: request.body };
374
+ }
375
+ toPayment(order, requestedCents) {
376
+ const payments = order.transactions?.payments ?? [];
377
+ const sum = (field) => {
378
+ const values = payments.map((p) => p[field]).filter((v) => typeof v === "string");
379
+ return values.length ? values.reduce((total, v) => total + decimalToCents(v), 0) : void 0;
380
+ };
381
+ if (!order.id) {
382
+ throw new TerminalPaymentProviderException(PROVIDER, 200, order, "Mercado Pago returned an order with no id");
383
+ }
384
+ return {
385
+ id: order.id,
386
+ provider: PROVIDER,
387
+ status: toStatus(order.status),
388
+ amountCents: sum("amount") ?? requestedCents ?? 0,
389
+ paidCents: sum("paid_amount"),
390
+ reference: order.external_reference,
391
+ terminalId: order.config?.point?.terminal_id,
392
+ createdAt: order.created_date ? new Date(order.created_date) : void 0,
393
+ raw: order
394
+ };
395
+ }
396
+ };
397
+
398
+ // src/payments/adapters/clip.terminal.ts
399
+ import { timingSafeEqual as timingSafeEqual2 } from "crypto";
400
+ var PROVIDER2 = "clip";
401
+ var DEFAULT_BASE_URL2 = "https://api.payclip.io";
402
+ var DEFAULT_API_BASE_URL = "https://api.payclip.com";
403
+ function toStatus2(status) {
404
+ switch (status?.toUpperCase()) {
405
+ case "PENDING":
406
+ return "pending";
407
+ case "COMPLETED":
408
+ return "approved";
409
+ case "FAILED":
410
+ return "rejected";
411
+ default:
412
+ return "unknown";
413
+ }
414
+ }
415
+ var ClipTerminalPayments = class {
416
+ constructor(options) {
417
+ this.options = options;
418
+ this.provider = PROVIDER2;
419
+ if (!options.apiKey || !options.secretKey) {
420
+ throw new Error("ClipTerminalPayments: apiKey and secretKey are required (CLIP_API_KEY / CLIP_SECRET_KEY).");
421
+ }
422
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL2).replace(/\/$/, "");
423
+ this.apiBaseUrl = (options.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\/$/, "");
424
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
425
+ this.token = Buffer.from(`${options.apiKey}:${options.secretKey}`).toString("base64");
426
+ }
427
+ headers(extra = {}) {
428
+ return {
429
+ authorization: `Basic ${this.token}`,
430
+ "content-type": "application/json",
431
+ ...extra
432
+ };
433
+ }
434
+ url(path) {
435
+ return `${this.baseUrl}/f2f/pinpad/v1${path}`;
436
+ }
437
+ /**
438
+ * Clip's device status, which is a heartbeat: a reader that has not checked
439
+ * in for 20 seconds turns `expired`, not `inactive`. Both mean "do not send
440
+ * a charge there right now", so both map to offline; `unknown` means the
441
+ * account does not have the feature on, which is not a statement about the
442
+ * device at all and stays `undefined`.
443
+ */
444
+ async listTerminals() {
445
+ const devices = await requestJson(
446
+ PROVIDER2,
447
+ this.fetchImpl,
448
+ this.url("/devices/status"),
449
+ { method: "GET", headers: this.headers() }
450
+ );
451
+ return (devices ?? []).map((device) => ({
452
+ id: device.serial_number,
453
+ online: device.status === "active" ? true : device.status === "inactive" || device.status === "expired" ? false : void 0,
454
+ raw: device
455
+ }));
456
+ }
457
+ async charge(input) {
458
+ assertCents(input.amountCents);
459
+ if (input.tipCents !== void 0) assertCents(input.tipCents, "tipCents");
460
+ if (input.expiresInMinutes !== void 0) {
461
+ throw new UnsupportedByProviderException(
462
+ PROVIDER2,
463
+ "A Clip charge has no expiry of its own. Cancel it yourself, or set a device-level timeout with setKioskMode({ enabled: true, timeoutSeconds })."
464
+ );
465
+ }
466
+ if (input.description) {
467
+ throw new UnsupportedByProviderException(
468
+ PROVIDER2,
469
+ "Clip PinPad charges carry no description \u2014 the reader shows the amount only. Put the detail in `reference`, which Clip does store and hand back."
470
+ );
471
+ }
472
+ const created = await requestJson(PROVIDER2, this.fetchImpl, this.url("/payment"), {
473
+ method: "POST",
474
+ headers: this.headers(),
475
+ body: JSON.stringify({
476
+ // Clip takes a JSON number here. Formatting from cents via the decimal
477
+ // string keeps the float from being built by arithmetic.
478
+ amount: Number(centsToDecimalString(input.amountCents)),
479
+ tip_amount: input.tipCents === void 0 ? void 0 : Number(centsToDecimalString(input.tipCents)),
480
+ reference: input.reference,
481
+ serial_number_pos: input.terminalId,
482
+ webhook_url: input.webhookUrl,
483
+ preferences: input.printReceipt === void 0 && input.tipCents === void 0 ? void 0 : {
484
+ is_auto_print_receipt_enabled: input.printReceipt,
485
+ is_tip_enabled: input.tipCents === void 0 ? void 0 : true
486
+ }
487
+ })
488
+ });
489
+ return {
490
+ id: created.pinpad_request_id,
491
+ provider: PROVIDER2,
492
+ status: "pending",
493
+ amountCents: created.amount === void 0 ? input.amountCents : decimalToCents(created.amount),
494
+ reference: created.reference ?? input.reference,
495
+ terminalId: created.serial_number_pos ?? input.terminalId,
496
+ raw: created
497
+ };
498
+ }
499
+ async get(id) {
500
+ const payment = await requestJson(
501
+ PROVIDER2,
502
+ this.fetchImpl,
503
+ `${this.url("/payment")}?pinpadRequestId=${encodeURIComponent(id)}`,
504
+ { method: "GET", headers: this.headers() }
505
+ );
506
+ return {
507
+ id: payment.pinpad_request_id ?? id,
508
+ provider: PROVIDER2,
509
+ status: toStatus2(payment.status),
510
+ amountCents: payment.amount === void 0 ? 0 : decimalToCents(payment.amount),
511
+ paidCents: payment.amount_paid === void 0 ? void 0 : decimalToCents(payment.amount_paid),
512
+ tipCents: payment.tip_amount === void 0 ? void 0 : decimalToCents(payment.tip_amount),
513
+ reference: payment.reference,
514
+ createdAt: payment.create_date ? new Date(payment.create_date) : void 0,
515
+ raw: payment
516
+ };
517
+ }
518
+ /**
519
+ * Withdraws a queued charge — and only a queued one. Clip accepts this
520
+ * "if the payment attempt has not yet been picked up by the terminal"; after
521
+ * that the reader owns it and it has to be cancelled on the device.
522
+ */
523
+ async cancel(id) {
524
+ const cancelled = await requestJson(
525
+ PROVIDER2,
526
+ this.fetchImpl,
527
+ `${this.url("/payment")}/${encodeURIComponent(id)}`,
528
+ { method: "DELETE", headers: this.headers() }
529
+ );
530
+ return {
531
+ id: cancelled.pinpad_request_id ?? id,
532
+ provider: PROVIDER2,
533
+ status: "cancelled",
534
+ amountCents: cancelled.amount === void 0 ? 0 : decimalToCents(cancelled.amount),
535
+ reference: cancelled.reference,
536
+ terminalId: cancelled.serial_number_pos,
537
+ raw: cancelled
538
+ };
539
+ }
540
+ /**
541
+ * The charge plus the transactions behind it, which is where the ids that
542
+ * can be refunded live. Split payments produce more than one.
543
+ */
544
+ async getWithTransactions(id) {
545
+ const detailed = await requestJson(
546
+ PROVIDER2,
547
+ this.fetchImpl,
548
+ `${this.url("/payment")}?pinpadRequestId=${encodeURIComponent(id)}`,
549
+ { method: "GET", headers: this.headers({ "Pinpad-Include-Detail": "true" }) }
550
+ );
551
+ return {
552
+ payment: {
553
+ id: detailed.pinpad_request_id ?? id,
554
+ provider: PROVIDER2,
555
+ status: toStatus2(detailed.status),
556
+ amountCents: detailed.amount === void 0 ? 0 : decimalToCents(detailed.amount),
557
+ paidCents: detailed.amount_paid === void 0 ? void 0 : decimalToCents(detailed.amount_paid),
558
+ tipCents: detailed.tip_amount === void 0 ? void 0 : decimalToCents(detailed.tip_amount),
559
+ reference: detailed.reference,
560
+ createdAt: detailed.create_date ? new Date(detailed.create_date) : void 0,
561
+ raw: detailed
562
+ },
563
+ transactions: detailed.detail?.results ?? []
564
+ };
565
+ }
566
+ /**
567
+ * Refunds a settled charge.
568
+ *
569
+ * Two calls, because Clip refunds a **transaction** and the id you hold is a
570
+ * PinPad request: the transaction id has to be read out of the charge's
571
+ * detail first. The refund itself lives on the other host
572
+ * (`api.payclip.com`), with the same Basic credentials.
573
+ */
574
+ async refund(id, options = {}) {
575
+ if (options.amountCents !== void 0) assertCents(options.amountCents, "amountCents");
576
+ const { transactions } = await this.getWithTransactions(id);
577
+ const approved = transactions.filter((t) => t.status === "approved" && (t.transaction_id ?? t.id));
578
+ if (approved.length === 0) {
579
+ throw new UnsupportedByProviderException(
580
+ PROVIDER2,
581
+ `Clip charge ${id} has no approved transaction to refund \u2014 read it with getWithTransactions() to see why.`
582
+ );
583
+ }
584
+ if (approved.length > 1) {
585
+ throw new UnsupportedByProviderException(
586
+ PROVIDER2,
587
+ `Clip charge ${id} settled as ${approved.length} transactions (a split payment). Refund each one explicitly against api.payclip.com/refunds \u2014 refunding "the charge" would be a guess about which.`
588
+ );
589
+ }
590
+ const transaction = approved[0];
591
+ const amount = options.amountCents !== void 0 ? Number(centsToDecimalString(options.amountCents)) : Number(transaction.paid_amount ?? transaction.amount ?? 0);
592
+ await requestJson(PROVIDER2, this.fetchImpl, `${this.apiBaseUrl}/refunds`, {
593
+ method: "POST",
594
+ headers: this.headers(),
595
+ body: JSON.stringify({
596
+ amount,
597
+ reason: options.reason ?? "Refund requested",
598
+ reference: { type: "transaction", id: transaction.transaction_id ?? transaction.id }
599
+ })
600
+ });
601
+ return this.get(id);
602
+ }
603
+ /**
604
+ * Cancels whatever is queued on a reader, when you do not have the request
605
+ * id — a terminal left waiting after a crash, typically. Same limit as
606
+ * {@link cancel}: only before the device picks it up.
607
+ */
608
+ async cancelByTerminal(serialNumber) {
609
+ const cancelled = await requestJson(
610
+ PROVIDER2,
611
+ this.fetchImpl,
612
+ `${this.url("/payment/serial-number")}/${encodeURIComponent(serialNumber)}`,
613
+ { method: "DELETE", headers: this.headers() }
614
+ );
615
+ return {
616
+ id: cancelled.pinpad_request_id ?? "",
617
+ provider: PROVIDER2,
618
+ status: "cancelled",
619
+ amountCents: cancelled.amount === void 0 ? 0 : decimalToCents(cancelled.amount),
620
+ reference: cancelled.reference,
621
+ terminalId: cancelled.serial_number_pos ?? serialNumber,
622
+ raw: cancelled
623
+ };
624
+ }
625
+ /**
626
+ * Kiosk mode: the reader stays on the payment screen and nobody can walk out
627
+ * of it, for unattended terminals. `timeoutSeconds` auto-cancels an
628
+ * untouched charge; without it a kiosk waits forever.
629
+ *
630
+ * Up to 25 serial numbers per call, which is Clip's limit, not ours.
631
+ */
632
+ async setKioskMode(serialNumbers, preferences) {
633
+ if (serialNumbers.length === 0 || serialNumbers.length > 25) {
634
+ throw new UnsupportedByProviderException(
635
+ PROVIDER2,
636
+ `Clip takes 1 to 25 devices per preferences call, got ${serialNumbers.length}.`
637
+ );
638
+ }
639
+ await requestJson(PROVIDER2, this.fetchImpl, this.url("/devices"), {
640
+ method: "POST",
641
+ headers: this.headers(),
642
+ body: JSON.stringify({
643
+ devices: serialNumbers,
644
+ preferences: {
645
+ is_kiosk_mode_enabled: preferences.enabled,
646
+ timeout_seg: preferences.timeoutSeconds
647
+ }
648
+ })
649
+ });
650
+ }
651
+ /**
652
+ * Clip signs nothing. The notification is `{ id, origin, event_type }` over
653
+ * plain POST, so there is no signature to check and no way to tell Clip's
654
+ * request from anyone else's.
655
+ *
656
+ * What is left is to make the URL itself the credential: register a
657
+ * `webhook_url` carrying a random token and require it back here. That does
658
+ * not authenticate Clip — it only keeps a stranger from making your service
659
+ * do lookups — which is precisely why the event carries an id and never a
660
+ * status. The status comes from `get()`, over an authenticated call, every
661
+ * time.
662
+ */
663
+ verifyWebhook(request) {
664
+ const expected = this.options.webhookPathSecret;
665
+ if (expected) {
666
+ const headerValue = request.headers["x-webhook-token"] ?? request.headers["X-Webhook-Token"];
667
+ const provided = String(
668
+ (Array.isArray(headerValue) ? headerValue[0] : headerValue) ?? request.query?.["token"] ?? ""
669
+ );
670
+ const a = Buffer.from(provided);
671
+ const b = Buffer.from(expected);
672
+ if (a.length !== b.length || !timingSafeEqual2(a, b)) {
673
+ throw new UnauthorizedAppException("Invalid Clip webhook token", void 0, "INVALID_WEBHOOK_SIGNATURE");
674
+ }
675
+ }
676
+ const body = request.body;
677
+ const paymentId = body?.id;
678
+ if (!paymentId) {
679
+ throw new UnauthorizedAppException("Clip webhook carried no payment id", void 0, "INVALID_WEBHOOK_PAYLOAD");
680
+ }
681
+ return { provider: PROVIDER2, paymentId, action: body?.event_type, raw: request.body };
682
+ }
683
+ };
684
+
685
+ // src/payments/payments.module.ts
686
+ var env = (key) => process.env[key] || void 0;
687
+ function resolvePaymentsOptions(options = {}) {
688
+ return {
689
+ provider: options.provider ?? env("PAYMENTS_PROVIDER"),
690
+ mercadopago: options.mercadopago ?? (env("MERCADOPAGO_ACCESS_TOKEN") ? {
691
+ accessToken: env("MERCADOPAGO_ACCESS_TOKEN"),
692
+ webhookSecret: env("MERCADOPAGO_WEBHOOK_SECRET")
693
+ } : void 0),
694
+ clip: options.clip ?? (env("CLIP_API_KEY") ? {
695
+ apiKey: env("CLIP_API_KEY"),
696
+ secretKey: env("CLIP_SECRET_KEY") ?? "",
697
+ webhookPathSecret: env("CLIP_WEBHOOK_SECRET")
698
+ } : void 0)
699
+ };
700
+ }
701
+ function createTerminalPaymentsAdapter(options) {
702
+ const resolved = resolvePaymentsOptions(options);
703
+ switch (resolved.provider) {
704
+ case "mercadopago":
705
+ if (!resolved.mercadopago)
706
+ throw new Error('PaymentsModule: provider "mercadopago" selected but no mercadopago options / MERCADOPAGO_* env set.');
707
+ return new MercadoPagoTerminalPayments(resolved.mercadopago);
708
+ case "clip":
709
+ if (!resolved.clip)
710
+ throw new Error('PaymentsModule: provider "clip" selected but no clip options / CLIP_* env set.');
711
+ return new ClipTerminalPayments(resolved.clip);
712
+ case void 0:
713
+ throw new Error("PaymentsModule: no provider selected \u2014 pass `provider` or set PAYMENTS_PROVIDER.");
714
+ default:
715
+ throw new Error(`PaymentsModule: unknown provider "${resolved.provider}".`);
716
+ }
717
+ }
718
+ var PaymentsModule = class {
719
+ static forRoot(options = {}) {
720
+ const providers = [
721
+ { provide: PAYMENTS_OPTIONS, useValue: options },
722
+ { provide: TERMINAL_PAYMENTS, useFactory: () => createTerminalPaymentsAdapter(options) }
723
+ ];
724
+ return { module: PaymentsModule, providers, exports: [TERMINAL_PAYMENTS, PAYMENTS_OPTIONS] };
725
+ }
726
+ static forRootAsync(config) {
727
+ const providers = [
728
+ {
729
+ provide: PAYMENTS_OPTIONS,
730
+ useFactory: config.useFactory,
731
+ inject: config.inject ?? []
732
+ },
733
+ {
734
+ provide: TERMINAL_PAYMENTS,
735
+ useFactory: (options) => createTerminalPaymentsAdapter(options),
736
+ inject: [PAYMENTS_OPTIONS]
737
+ }
738
+ ];
739
+ return {
740
+ module: PaymentsModule,
741
+ imports: config.imports ?? [],
742
+ providers,
743
+ exports: [TERMINAL_PAYMENTS, PAYMENTS_OPTIONS]
744
+ };
745
+ }
746
+ };
747
+ PaymentsModule = __decorateClass([
748
+ Global(),
749
+ Module({})
750
+ ], PaymentsModule);
751
+
752
+ // src/payments/payments-webhook.controller.ts
753
+ import { Controller, Inject, Post, Query, Req } from "@nestjs/common";
754
+ function createTerminalPaymentsWebhookController(options) {
755
+ let TerminalPaymentsWebhookControllerHost = class {
756
+ constructor(payments) {
757
+ this.payments = payments;
758
+ }
759
+ async handleWebhook(req, query) {
760
+ const request = req;
761
+ const event = this.payments.verifyWebhook({
762
+ headers: request.headers ?? {},
763
+ query: request.query ?? query,
764
+ body: request.body
765
+ });
766
+ const payment = await this.payments.get(event.paymentId);
767
+ await options.handlers[payment.status]?.(payment, event);
768
+ return { received: true };
769
+ }
770
+ };
771
+ __decorateClass([
772
+ Post(),
773
+ __decorateParam(0, Req()),
774
+ __decorateParam(1, Query())
775
+ ], TerminalPaymentsWebhookControllerHost.prototype, "handleWebhook", 1);
776
+ TerminalPaymentsWebhookControllerHost = __decorateClass([
777
+ Controller(options.path ?? "payments/webhook"),
778
+ __decorateParam(0, Inject(TERMINAL_PAYMENTS))
779
+ ], TerminalPaymentsWebhookControllerHost);
780
+ return TerminalPaymentsWebhookControllerHost;
781
+ }
782
+ export {
783
+ ClipTerminalPayments,
784
+ MercadoPagoTerminalPayments,
785
+ PAYMENTS_OPTIONS,
786
+ PaymentsModule,
787
+ TERMINAL_PAYMENTS,
788
+ TerminalPaymentProviderException,
789
+ UnsupportedByProviderException,
790
+ assertCents,
791
+ centsToDecimalString,
792
+ createTerminalPaymentsAdapter,
793
+ createTerminalPaymentsWebhookController,
794
+ decimalToCents,
795
+ resolvePaymentsOptions
796
+ };