@miguelmorales13/nestkit 0.22.0 → 0.24.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 (35) hide show
  1. package/README.md +171 -2
  2. package/dist/auth/index.cjs +1 -1
  3. package/dist/auth/index.js +1 -1
  4. package/dist/auth/oauth/index.cjs +1 -1
  5. package/dist/auth/oauth/index.js +1 -1
  6. package/dist/bootstrap/index.cjs +4 -4
  7. package/dist/bootstrap/index.js +3 -3
  8. package/dist/{chunk-FNUZGYUF.cjs → chunk-ALIKVFOV.cjs} +2 -2
  9. package/dist/{chunk-UNEVXCFW.js → chunk-PFHHLB7B.js} +1 -1
  10. package/dist/errors/index.cjs +5 -5
  11. package/dist/errors/index.js +4 -4
  12. package/dist/index.cjs +13 -13
  13. package/dist/index.js +15 -15
  14. package/dist/payments/adapters/mercadopago-connect.d.ts +70 -0
  15. package/dist/payments/adapters/mercadopago.terminal.d.ts +57 -0
  16. package/dist/payments/index.cjs +153 -1
  17. package/dist/payments/index.d.ts +3 -1
  18. package/dist/payments/index.js +152 -0
  19. package/dist/payments/payments.port.d.ts +24 -0
  20. package/dist/push/channels/fcm.channel.d.ts +73 -0
  21. package/dist/push/channels/webpush.channel.d.ts +62 -0
  22. package/dist/push/index.cjs +449 -0
  23. package/dist/push/index.d.ts +9 -0
  24. package/dist/push/index.js +449 -0
  25. package/dist/push/push.module.d.ts +40 -0
  26. package/dist/push/push.options.d.ts +40 -0
  27. package/dist/push/push.port.d.ts +148 -0
  28. package/dist/push/push.service.d.ts +31 -0
  29. package/dist/security/index.cjs +35 -0
  30. package/dist/security/index.d.ts +2 -0
  31. package/dist/security/index.js +35 -0
  32. package/dist/security/signed-state.d.ts +42 -0
  33. package/package.json +20 -4
  34. package/dist/{chunk-A2DGK4ZL.js → chunk-2DUEQKOI.js} +3 -3
  35. package/dist/{chunk-MSTXS3MU.cjs → chunk-LSDY6ETG.cjs} +3 -3
package/README.md CHANGED
@@ -13,7 +13,7 @@ está listo, la implementación no.
13
13
  con Google, Apple, Facebook, TikTok, GitHub, Microsoft, Discord, LinkedIn, enlace mágico, passkeys y verificación en dos pasos (`auth/oauth`) o con email y contraseña (`auth`), Stripe, cobro presencial en
14
14
  terminal Mercado Pago Point o Clip (`payments`), facturación CFDI 4.0 (`invoicing`), Telegram,
15
15
  WhatsApp, Instagram y Facebook Pages (`meta`), subida de archivos (`storage`), correo transaccional con Resend,
16
- Brevo o SMTP tras un puerto (`email`) y lectura de analítica (`umami`).
16
+ Brevo o SMTP tras un puerto (`email`), push a apps y navegadores con botones (`push`) y lectura de analítica (`umami`).
17
17
 
18
18
  ## ¿Para qué proyectos es esto?
19
19
 
@@ -1037,6 +1037,78 @@ desaparece sin ruido es un cliente preguntando dónde quedó su dinero.
1037
1037
  secreto del panel, y el id va **en minúsculas** (lo dice su propia documentación). Los ids reales
1038
1038
  son `ORD01J6…`, así que hashearlo como viene rechaza todas las notificaciones legítimas — y el
1039
1039
  síntoma parece un ataque, no un bug.
1040
+ - **Solo Point Smart 1 y Point Smart 2 pasan a modo PDV por API.** Confirmado con soporte de
1041
+ Mercado Pago, no es una limitación temporal: un Point Air trae hardware oficial de Mercado Pago,
1042
+ aparece en `listTerminals()` como cualquier otra, hasta puede traer su propio `storeId`/`posId` —
1043
+ y aun así se queda en `standalone` para siempre, porque ese modelo simplemente no tiene modo PDV.
1044
+ `setOperatingMode(ids, 'PDV')` rechaza un id no integrable **antes** de llamar a la API, con un
1045
+ mensaje que nombra el modelo — la respuesta real de Mercado Pago es un `400` seco,
1046
+ `"'$.terminals[0].id' - does not match pattern"`, que no menciona el modelo y parece un id mal
1047
+ formado. `listTerminals()` también marca cada terminal con `integrable`, para filtrar la lista
1048
+ ANTES de que alguien la elija.
1049
+ - **La terminal tiene que pertenecer a una jerarquía Sucursal → Caja → Terminal**, o la Orders API
1050
+ rechaza cualquier cobro con `PA_UNAUTHORIZED_RESULT_FROM_POLICIES` — un 403 que no menciona
1051
+ Sucursales por ningún lado. `createStore()` y `createPos()` arman esa jerarquía. **Antes de
1052
+ llamarlos, revisá `listTerminals()`**: una terminal emparejada alguna vez desde la app de
1053
+ Mercado Pago (celular) ya puede traer su propio `storeId`/`posId` — crear una Sucursal nueva en
1054
+ ese caso no falla, pero le deja al comercio una Sucursal de más en su panel que nadie usa.
1055
+
1056
+ ```ts
1057
+ const [terminal] = await pagos.listTerminals();
1058
+ if (!terminal.integrable) throw new Error('Esta terminal no puede operar por API — es un Point Air.');
1059
+
1060
+ let { storeId, posId } = terminal;
1061
+ if (!storeId || !posId) {
1062
+ storeId = await pagos.createStore({
1063
+ userId: sellerMpUserId, // el user_id de la CUENTA CONECTADA, no el de tu aplicación
1064
+ name: 'Sucursal Centro',
1065
+ location: { streetNumber: 'S/N', streetName: 'Centro', cityName: 'CDMX', stateName: 'CDMX', latitude: 19.4326, longitude: -99.1332 },
1066
+ businessHours: { monday: [{ open: '00:00', close: '23:59' }], /* ...los 7 días */ },
1067
+ });
1068
+ posId = await pagos.createPos({ storeId, name: 'Caja 1' });
1069
+ }
1070
+ await pagos.setOperatingMode([terminal.id], 'PDV'); // y reiniciar el aparato
1071
+ ```
1072
+
1073
+ #### Mercado Pago marketplace: conectar la cuenta de cada vendedor por OAuth
1074
+
1075
+ `MercadoPagoTerminalPayments` asume un `MERCADOPAGO_ACCESS_TOKEN` fijo — de una sola cuenta. Un
1076
+ marketplace (vos operás la aplicación, cada vendedor conecta la SUYA) necesita, además, `MercadoPagoConnect`:
1077
+
1078
+ ```ts
1079
+ import { MercadoPagoConnect } from '@miguelmorales13/nestkit/payments';
1080
+ import { signState, readState } from '@miguelmorales13/nestkit/security';
1081
+
1082
+ const connect = new MercadoPagoConnect({
1083
+ clientId: process.env.MERCADOPAGO_CLIENT_ID!,
1084
+ clientSecret: process.env.MERCADOPAGO_CLIENT_SECRET!,
1085
+ redirectUri: 'https://api.tuapp.com/mercadopago/callback',
1086
+ });
1087
+
1088
+ // 1. Arrancar la conexión — `state` viaja firmado, sin sesión ni cookie:
1089
+ const state = signState({ tenantId, sellerId }, { secret: JWT_SECRET, ttlMs: 20 * 60_000 });
1090
+ const url = connect.authorizationUrl(state);
1091
+
1092
+ // 2. En el callback:
1093
+ const datos = readState(query.state, { secret: JWT_SECRET, ttlMs: 20 * 60_000 });
1094
+ if (!datos) throw new Error('state inválido o caducado');
1095
+ const tokens = await connect.exchangeCode(query.code);
1096
+ await guardar(datos.tenantId, datos.sellerId, tokens); // cifrados — son las llaves del vendedor
1097
+
1098
+ // 3. Para cobrar, con el token de ESE vendedor (nunca uno fijo):
1099
+ const pagosDelVendedor = new MercadoPagoTerminalPayments({ accessToken: tokens.accessToken });
1100
+ ```
1101
+
1102
+ `scope=offline_access` va siempre (es el default): sin él, Mercado Pago entrega un access token de
1103
+ un solo uso, sin `refresh_token`, y la conexión deja de funcionar sola el día que expira. El
1104
+ `refresh_token` **rota en cada renovación** (`connect.refresh(tokens.refreshToken)`) — hay que
1105
+ persistir el resultado completo, no solo el access token nuevo.
1106
+
1107
+ `signState`/`readState` (`@miguelmorales13/nestkit/security`) son genéricos, no específicos de
1108
+ Mercado Pago: sirven para cualquier flujo de "conectar una cuenta de terceros por OAuth" que no
1109
+ quiera depender de una cookie — que en un consent screen con pasos extra (2FA, verificación por
1110
+ teléfono) puede desaparecer antes de que el navegador vuelva. El payload firmado es libre
1111
+ (`Record<string, string>`); qué va adentro lo decide quien conecta, no la librería.
1040
1112
 
1041
1113
  **Probar sin terminal.** Con credenciales de prueba existe un equipo virtual, serie `SBX0000001`
1042
1114
  (`NEWLAND_N950__SBX0000001`), y un endpoint que le impone el estado final a una orden — el webhook
@@ -1637,6 +1709,101 @@ directo a la biometría sin hoja de selección). Al registrar:
1637
1709
  `startRegistration({ optionsJSON: options })` y `POST /auth/passkeys/register`. Un
1638
1710
  `NotAllowedError` es la persona cancelando, no un fallo.
1639
1711
 
1712
+ ### `push` — notificaciones push con botones y redirección, a apps (FCM) y navegadores (Web Push)
1713
+
1714
+ Un puerto y dos canales a la vez: un usuario tiene un iPhone (Firebase Cloud Messaging) **y** un
1715
+ navegador (Web Push con VAPID), y `send()` manda a cada dispositivo por el suyo. FCM va por su API
1716
+ HTTP v1 con `fetch` —sin `firebase-admin`, que arrastra medio Google Cloud para lo que es un POST
1717
+ con un bearer—; el token de acceso se obtiene firmando un JWT con la cuenta de servicio.
1718
+
1719
+ ```ts
1720
+ import { PushModule, PUSH, PUSH_DEVICE_STORE, type PushPort } from '@miguelmorales13/nestkit/push';
1721
+
1722
+ @Module({
1723
+ imports: [
1724
+ PushModule.forRoot({
1725
+ // fcm: lee FIREBASE_SERVICE_ACCOUNT (el JSON) o FIREBASE_SERVICE_ACCOUNT_FILE / GOOGLE_APPLICATION_CREDENTIALS (ruta)
1726
+ // webPush: lee VAPID_SUBJECT, VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY
1727
+ imports: [MiStoreModule],
1728
+ deviceStore: { provide: PUSH_DEVICE_STORE, useExisting: MiStore }, // opcional: habilita sendToUser + poda
1729
+ }),
1730
+ ],
1731
+ })
1732
+ export class AppModule {}
1733
+ ```
1734
+
1735
+ ```ts
1736
+ @Injectable()
1737
+ export class RecordatoriosService {
1738
+ constructor(@Inject(PUSH) private readonly push: PushPort) {}
1739
+
1740
+ async pesoDiario(userId: string) {
1741
+ await this.push.sendToUser(userId, {
1742
+ title: t('push.peso.titulo'), // I18nMessage o string; se traduce con { lang }
1743
+ body: t('push.peso.cuerpo'),
1744
+ link: 'https://app.miapp.mx/peso', // a dónde va un toque en la notificación
1745
+ actions: [
1746
+ { id: 'registrar', title: 'Registrar', link: 'https://app.miapp.mx/peso/nuevo' },
1747
+ { id: 'luego', title: 'Más tarde' },
1748
+ ],
1749
+ category: 'PESO', // iOS: la UNNotificationCategory que registró la app
1750
+ androidChannelId: 'recordatorios',
1751
+ collapseKey: 'peso-diario', // reemplaza la de ayer en vez de apilarla
1752
+ data: { screen: 'peso' },
1753
+ }, { lang: user.locale });
1754
+ }
1755
+ }
1756
+ ```
1757
+
1758
+ `send(devices, message)` devuelve `{ sent, failed, ids }` y **nunca lanza por un dispositivo**: cada
1759
+ fallo trae `code` y `stale`. `stale: true` es la plataforma diciendo que ese dispositivo ya no existe
1760
+ (app desinstalada, token rotado, suscripción caducada — `UNREGISTERED`/`SENDER_ID_MISMATCH` en FCM,
1761
+ `404`/`410` en Web Push) y **solo eso**: un `INVALID_ARGUMENT` no borra nada, porque puede ser el
1762
+ payload y borrar por eso pierde un dispositivo vivo. `sendToUser` manda a todos los dispositivos que
1763
+ `PushDeviceStorePort.listByUser` devuelva y borra los `stale` con `remove(id)`. Registrar dispositivos
1764
+ (upsert por token, plataforma, agente) sigue siendo del proyecto.
1765
+
1766
+ **Sin credenciales, la API arranca igual** — un aviso en el log, `channels()` en `false` y cada envío
1767
+ falla con `channel_not_configured`. Es distinto de `email` a propósito: la cuenta de servicio de
1768
+ Firebase suele ser un paso manual post-deploy, y un canal de push caído no puede tumbar toda la API.
1769
+ `whenUnconfigured: 'throw'` devuelve la regla estricta. Un canal **pedido** y roto (JSON inválido,
1770
+ VAPID incompleto) sí lanza.
1771
+
1772
+ **Botones y redirección, con la verdad de cada plataforma.** Un mismo mensaje sale en cuatro
1773
+ dialectos, y lo que una plataforma no puede mostrar viaja en `data` (`link`, `actions`, `category`,
1774
+ como strings) para que la app lo haga:
1775
+
1776
+ | | Toque en la notificación | Botones (`actions`) |
1777
+ |---|---|---|
1778
+ | **Web** (FCM o Web Push) | `link` nativo (`fcm_options.link`, solo `https`) | nativos; el *service worker* enruta cada uno |
1779
+ | **iOS** | la app lee `data.link` en `onMessageOpenedApp` | por `category`: la app registra una `UNNotificationCategory` con esos botones y el mismo id |
1780
+ | **Android** | la app lee `data.link` | **no existen** en la notificación de sistema. Con `dataOnly: true` el mensaje va sin bloque `notification`, la app lo recibe en segundo plano y la pinta ella (p. ej. `flutter_local_notifications`) con botones |
1781
+
1782
+ `dataOnly` en iOS se manda como push de fondo (`content-available`, prioridad 5, `apns-push-type:
1783
+ background`, que APNs exige o lo descarta). Una imagen en iOS necesita una Notification Service
1784
+ Extension; el mensaje ya lleva `mutable-content: 1` para que pueda descargarla.
1785
+
1786
+ El *service worker* para Web Push, que es donde se decide qué botón abre qué:
1787
+
1788
+ ```js
1789
+ self.addEventListener('push', (e) => {
1790
+ const m = e.data.json(); // { title, body, icon, image, badge, tag, link, actions: [{ action, title, icon, link }], data }
1791
+ e.waitUntil(self.registration.showNotification(m.title, { body: m.body, icon: m.icon, image: m.image, tag: m.tag, actions: m.actions, data: m }));
1792
+ });
1793
+ self.addEventListener('notificationclick', (e) => {
1794
+ e.notification.close();
1795
+ const m = e.notification.data;
1796
+ const url = (m.actions?.find((a) => a.action === e.action) ?? {}).link ?? m.link;
1797
+ if (url) e.waitUntil(clients.openWindow(url));
1798
+ });
1799
+ ```
1800
+
1801
+ Temas de FCM: `sendToTopic('noticias', message)`, `subscribeToTopic(tokens, 'noticias')`,
1802
+ `unsubscribeFromTopic`. `priority` (`high` despierta el dispositivo), `ttlSeconds`, `badge`, `sound` e
1803
+ `imageUrl` se traducen a lo que cada plataforma llama igual. `web-push` se carga perezosamente y solo
1804
+ si hay canal web; para Web Push el proyecto expone la `VAPID_PUBLIC_KEY` al navegador y guarda la
1805
+ suscripción que `PushManager.subscribe()` devuelve.
1806
+
1640
1807
  ### `email` — correo transaccional con el proveedor como configuración
1641
1808
 
1642
1809
  Un puerto, `EmailPort`, y el proveedor detrás se elige en una línea: **Resend**, **Brevo** (antes
@@ -1885,13 +2052,15 @@ trae los datos.
1885
2052
  | `@miguelmorales13/nestkit/auth/oauth` | `OAuthAuthModule`, `OAuthAuthService`, `createOAuthController`, `googleProvider`, `appleProvider`, `facebookProvider`, `tiktokProvider`, `githubProvider`, `microsoftProvider`, `discordProvider`, `linkedinProvider`, `OAuthStorePort`, `RefreshTokenStorePort`, `MagicLinkStorePort`, `MagicLinkSenderPort`, `TwoFactorStorePort`, `PasskeyStorePort`, `WebAuthnPort`, stores en memoria, `totp`/`verifyTotp` |
1886
2053
  | `@miguelmorales13/nestkit/umami` | `UmamiModule`, `UmamiService` — lectura de la API de analítica |
1887
2054
  | `@miguelmorales13/nestkit/invoicing` | `InvoicingModule`, `INVOICING`, `InvoicingPort`, adaptadores `FacturapiInvoicing`/`FacturamaInvoicing` — CFDI 4.0 |
1888
- | `@miguelmorales13/nestkit/payments` | `PaymentsModule`, `TERMINAL_PAYMENTS`, `TerminalPaymentsPort`, adaptadores `MercadoPagoTerminalPayments`/`ClipTerminalPayments`, `createTerminalPaymentsWebhookController` |
2055
+ | `@miguelmorales13/nestkit/payments` | `PaymentsModule`, `TERMINAL_PAYMENTS`, `TerminalPaymentsPort`, adaptadores `MercadoPagoTerminalPayments`/`ClipTerminalPayments`, `MercadoPagoConnect` (OAuth marketplace), `isIntegrableTerminalModel`, `createTerminalPaymentsWebhookController` |
1889
2056
  | `@miguelmorales13/nestkit/storage` | `StorageModule`, `STORAGE`, `StoragePort`, adaptadores `LocalStorage`/`S3Storage`/`BunnyStorage` |
2057
+ | `@miguelmorales13/nestkit/push` | `PushModule`, `PUSH`, `PushPort`, `PUSH_DEVICE_STORE`, `PushDeviceStorePort`, canales `FcmChannel`/`WebPushChannel`, `toFcmMessage` |
1890
2058
  | `@miguelmorales13/nestkit/email` | `EmailModule`, `EMAIL`, `EmailPort`, adaptadores `ResendEmail`/`SmtpEmail`/`BrevoEmail`/`MemoryEmail` |
1891
2059
  | `@miguelmorales13/nestkit/email/resend` | `ResendModule`, `RESEND_CLIENT` |
1892
2060
  | `@miguelmorales13/nestkit/email/nodemailer` | `NodemailerModule`, `NODEMAILER_TRANSPORT` |
1893
2061
  | `@miguelmorales13/nestkit/i18n` | `I18nModule`, `t`, `translate`, `currentLanguage`, `I18nInterceptor`, `TranslatorPort`, `NestI18nTranslator`, `translateOr` |
1894
2062
  | `@miguelmorales13/nestkit/bootstrap` | `applyNestKitDefaults` |
2063
+ | `@miguelmorales13/nestkit/security` | `signState`/`readState` — CSRF de un flujo OAuth "conectar cuenta" firmado, sin cookie ni sesión |
1895
2064
 
1896
2065
  ## Cambios recientes
1897
2066
 
@@ -8,8 +8,8 @@ var _chunkFH5UNWWWcjs = require('../chunk-FH5UNWWW.cjs');
8
8
 
9
9
 
10
10
  var _chunkHDFPSA2Vcjs = require('../chunk-HDFPSA2V.cjs');
11
- require('../chunk-SDWHKPXI.cjs');
12
11
  require('../chunk-Q5Y33L7B.cjs');
12
+ require('../chunk-SDWHKPXI.cjs');
13
13
  require('../chunk-PNK5WMPP.cjs');
14
14
 
15
15
 
@@ -8,8 +8,8 @@ import {
8
8
  ForbiddenAppException,
9
9
  UnauthorizedAppException
10
10
  } from "../chunk-ZFIDAX7K.js";
11
- import "../chunk-ETRUVZTJ.js";
12
11
  import "../chunk-M3GQDRWR.js";
12
+ import "../chunk-ETRUVZTJ.js";
13
13
  import "../chunk-VVMRZEIW.js";
14
14
  import {
15
15
  __decorateClass,
@@ -7,8 +7,8 @@ var _chunkFH5UNWWWcjs = require('../../chunk-FH5UNWWW.cjs');
7
7
 
8
8
 
9
9
  var _chunkHDFPSA2Vcjs = require('../../chunk-HDFPSA2V.cjs');
10
- require('../../chunk-SDWHKPXI.cjs');
11
10
  require('../../chunk-Q5Y33L7B.cjs');
11
+ require('../../chunk-SDWHKPXI.cjs');
12
12
  require('../../chunk-PNK5WMPP.cjs');
13
13
 
14
14
 
@@ -7,8 +7,8 @@ import {
7
7
  UnauthorizedAppException,
8
8
  ValidationAppException
9
9
  } from "../../chunk-ZFIDAX7K.js";
10
- import "../../chunk-ETRUVZTJ.js";
11
10
  import "../../chunk-M3GQDRWR.js";
11
+ import "../../chunk-ETRUVZTJ.js";
12
12
  import "../../chunk-VVMRZEIW.js";
13
13
  import {
14
14
  __decorateClass,
@@ -1,14 +1,14 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunkFNUZGYUFcjs = require('../chunk-FNUZGYUF.cjs');
3
+ var _chunkALIKVFOVcjs = require('../chunk-ALIKVFOV.cjs');
4
4
  require('../chunk-3AUOOEQO.cjs');
5
- require('../chunk-MSTXS3MU.cjs');
5
+ require('../chunk-LSDY6ETG.cjs');
6
+ require('../chunk-Q5Y33L7B.cjs');
6
7
  require('../chunk-AXMW5JF7.cjs');
7
8
  require('../chunk-Y72D5L6I.cjs');
8
9
  require('../chunk-SDWHKPXI.cjs');
9
- require('../chunk-Q5Y33L7B.cjs');
10
10
  require('../chunk-PNK5WMPP.cjs');
11
11
  require('../chunk-2REOCMUD.cjs');
12
12
 
13
13
 
14
- exports.applyNestKitDefaults = _chunkFNUZGYUFcjs.applyNestKitDefaults;
14
+ exports.applyNestKitDefaults = _chunkALIKVFOVcjs.applyNestKitDefaults;
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  applyNestKitDefaults
3
- } from "../chunk-UNEVXCFW.js";
3
+ } from "../chunk-PFHHLB7B.js";
4
4
  import "../chunk-DYHSOULW.js";
5
- import "../chunk-A2DGK4ZL.js";
5
+ import "../chunk-2DUEQKOI.js";
6
+ import "../chunk-M3GQDRWR.js";
6
7
  import "../chunk-X4PQJZ4G.js";
7
8
  import "../chunk-TCAMLNUZ.js";
8
9
  import "../chunk-ETRUVZTJ.js";
9
- import "../chunk-M3GQDRWR.js";
10
10
  import "../chunk-VVMRZEIW.js";
11
11
  import "../chunk-4MGIQFAJ.js";
12
12
  export {
@@ -3,7 +3,7 @@
3
3
  var _chunk3AUOOEQOcjs = require('./chunk-3AUOOEQO.cjs');
4
4
 
5
5
 
6
- var _chunkMSTXS3MUcjs = require('./chunk-MSTXS3MU.cjs');
6
+ var _chunkLSDY6ETGcjs = require('./chunk-LSDY6ETG.cjs');
7
7
 
8
8
  // src/bootstrap/apply-defaults.ts
9
9
 
@@ -17,7 +17,7 @@ function applyNestKitDefaults(app, options = {}) {
17
17
  app.useGlobalPipes(
18
18
  new (0, _common.ValidationPipe)({ whitelist: true, transform: true, ...options.validation })
19
19
  );
20
- app.useGlobalFilters(new (0, _chunkMSTXS3MUcjs.GlobalExceptionFilter)());
20
+ app.useGlobalFilters(new (0, _chunkLSDY6ETGcjs.GlobalExceptionFilter)());
21
21
  app.useGlobalInterceptors(new (0, _chunk3AUOOEQOcjs.ResponseInterceptor)());
22
22
  if (options.swagger !== false) {
23
23
  const swaggerOptions = _nullishCoalesce(options.swagger, () => ( { title: "API" }));
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-DYHSOULW.js";
4
4
  import {
5
5
  GlobalExceptionFilter
6
- } from "./chunk-A2DGK4ZL.js";
6
+ } from "./chunk-2DUEQKOI.js";
7
7
 
8
8
  // src/bootstrap/apply-defaults.ts
9
9
  import {
@@ -8,13 +8,13 @@
8
8
  var _chunkHDFPSA2Vcjs = require('../chunk-HDFPSA2V.cjs');
9
9
 
10
10
 
11
- var _chunkMSTXS3MUcjs = require('../chunk-MSTXS3MU.cjs');
12
- require('../chunk-AXMW5JF7.cjs');
13
- require('../chunk-Y72D5L6I.cjs');
14
- require('../chunk-SDWHKPXI.cjs');
11
+ var _chunkLSDY6ETGcjs = require('../chunk-LSDY6ETG.cjs');
15
12
 
16
13
 
17
14
  var _chunkQ5Y33L7Bcjs = require('../chunk-Q5Y33L7B.cjs');
15
+ require('../chunk-AXMW5JF7.cjs');
16
+ require('../chunk-Y72D5L6I.cjs');
17
+ require('../chunk-SDWHKPXI.cjs');
18
18
  require('../chunk-PNK5WMPP.cjs');
19
19
  require('../chunk-2REOCMUD.cjs');
20
20
 
@@ -25,4 +25,4 @@ require('../chunk-2REOCMUD.cjs');
25
25
 
26
26
 
27
27
 
28
- exports.AppException = _chunkQ5Y33L7Bcjs.AppException; exports.ConflictAppException = _chunkHDFPSA2Vcjs.ConflictAppException; exports.ForbiddenAppException = _chunkHDFPSA2Vcjs.ForbiddenAppException; exports.GlobalExceptionFilter = _chunkMSTXS3MUcjs.GlobalExceptionFilter; exports.NotFoundAppException = _chunkHDFPSA2Vcjs.NotFoundAppException; exports.UnauthorizedAppException = _chunkHDFPSA2Vcjs.UnauthorizedAppException; exports.ValidationAppException = _chunkHDFPSA2Vcjs.ValidationAppException;
28
+ exports.AppException = _chunkQ5Y33L7Bcjs.AppException; exports.ConflictAppException = _chunkHDFPSA2Vcjs.ConflictAppException; exports.ForbiddenAppException = _chunkHDFPSA2Vcjs.ForbiddenAppException; exports.GlobalExceptionFilter = _chunkLSDY6ETGcjs.GlobalExceptionFilter; exports.NotFoundAppException = _chunkHDFPSA2Vcjs.NotFoundAppException; exports.UnauthorizedAppException = _chunkHDFPSA2Vcjs.UnauthorizedAppException; exports.ValidationAppException = _chunkHDFPSA2Vcjs.ValidationAppException;
@@ -8,13 +8,13 @@ import {
8
8
  } from "../chunk-ZFIDAX7K.js";
9
9
  import {
10
10
  GlobalExceptionFilter
11
- } from "../chunk-A2DGK4ZL.js";
12
- import "../chunk-X4PQJZ4G.js";
13
- import "../chunk-TCAMLNUZ.js";
14
- import "../chunk-ETRUVZTJ.js";
11
+ } from "../chunk-2DUEQKOI.js";
15
12
  import {
16
13
  AppException
17
14
  } from "../chunk-M3GQDRWR.js";
15
+ import "../chunk-X4PQJZ4G.js";
16
+ import "../chunk-TCAMLNUZ.js";
17
+ import "../chunk-ETRUVZTJ.js";
18
18
  import "../chunk-VVMRZEIW.js";
19
19
  import "../chunk-4MGIQFAJ.js";
20
20
  export {
package/dist/index.cjs CHANGED
@@ -14,40 +14,43 @@ var _chunkSPTDXUEDcjs = require('./chunk-SPTDXUED.cjs');
14
14
 
15
15
 
16
16
  var _chunkHVHYZXBBcjs = require('./chunk-HVHYZXBB.cjs');
17
+
18
+
19
+ var _chunkQS2W5XCQcjs = require('./chunk-QS2W5XCQ.cjs');
17
20
  require('./chunk-H2EHN366.cjs');
18
21
 
19
22
 
20
23
 
21
24
 
25
+ var _chunk52IOOHNXcjs = require('./chunk-52IOOHNX.cjs');
26
+ require('./chunk-W2T2VFLC.cjs');
22
27
 
23
28
 
24
- var _chunkAPUFKA4Kcjs = require('./chunk-APUFKA4K.cjs');
29
+ var _chunkALIKVFOVcjs = require('./chunk-ALIKVFOV.cjs');
25
30
 
26
31
 
32
+ var _chunk3AUOOEQOcjs = require('./chunk-3AUOOEQO.cjs');
33
+ require('./chunk-7SOM7EZP.cjs');
27
34
 
28
35
 
29
- var _chunk52IOOHNXcjs = require('./chunk-52IOOHNX.cjs');
30
- require('./chunk-W2T2VFLC.cjs');
31
36
 
32
37
 
33
- var _chunkFNUZGYUFcjs = require('./chunk-FNUZGYUF.cjs');
34
38
 
35
39
 
36
- var _chunk3AUOOEQOcjs = require('./chunk-3AUOOEQO.cjs');
40
+ var _chunkHDFPSA2Vcjs = require('./chunk-HDFPSA2V.cjs');
37
41
 
38
42
 
39
- var _chunkQS2W5XCQcjs = require('./chunk-QS2W5XCQ.cjs');
40
- require('./chunk-7SOM7EZP.cjs');
43
+ var _chunkLSDY6ETGcjs = require('./chunk-LSDY6ETG.cjs');
41
44
 
42
45
 
46
+ var _chunkQ5Y33L7Bcjs = require('./chunk-Q5Y33L7B.cjs');
43
47
 
44
48
 
45
49
 
46
50
 
47
- var _chunkHDFPSA2Vcjs = require('./chunk-HDFPSA2V.cjs');
48
51
 
49
52
 
50
- var _chunkMSTXS3MUcjs = require('./chunk-MSTXS3MU.cjs');
53
+ var _chunkAPUFKA4Kcjs = require('./chunk-APUFKA4K.cjs');
51
54
 
52
55
 
53
56
 
@@ -63,9 +66,6 @@ var _chunkY72D5L6Icjs = require('./chunk-Y72D5L6I.cjs');
63
66
  var _chunkSDWHKPXIcjs = require('./chunk-SDWHKPXI.cjs');
64
67
 
65
68
 
66
- var _chunkQ5Y33L7Bcjs = require('./chunk-Q5Y33L7B.cjs');
67
-
68
-
69
69
 
70
70
 
71
71
  var _chunkPNK5WMPPcjs = require('./chunk-PNK5WMPP.cjs');
@@ -108,4 +108,4 @@ require('./chunk-2REOCMUD.cjs');
108
108
 
109
109
 
110
110
 
111
- exports.AppException = _chunkQ5Y33L7Bcjs.AppException; exports.BaseCrudService = _chunk52IOOHNXcjs.BaseCrudService; exports.BaseResponseDto = _chunkQS2W5XCQcjs.BaseResponseDto; exports.ConflictAppException = _chunkHDFPSA2Vcjs.ConflictAppException; exports.ForbiddenAppException = _chunkHDFPSA2Vcjs.ForbiddenAppException; exports.GlobalExceptionFilter = _chunkMSTXS3MUcjs.GlobalExceptionFilter; exports.I18nInterceptor = _chunkAPUFKA4Kcjs.I18nInterceptor; exports.I18nMessage = _chunkPNK5WMPPcjs.I18nMessage; exports.I18nModule = _chunkAPUFKA4Kcjs.I18nModule; exports.ListQuery = _chunk52IOOHNXcjs.ListQuery; exports.NestI18nTranslator = _chunkAPUFKA4Kcjs.NestI18nTranslator; exports.NotFoundAppException = _chunkHDFPSA2Vcjs.NotFoundAppException; exports.PG_POOL = _chunkRF75KC63cjs.PG_POOL; exports.PgModule = _chunkRF75KC63cjs.PgModule; exports.REQUEST_ID_HEADER = _chunkHVHYZXBBcjs.REQUEST_ID_HEADER; exports.RequestContext = _chunkSDWHKPXIcjs.RequestContext; exports.RequestIdMiddleware = _chunkHVHYZXBBcjs.RequestIdMiddleware; exports.ResponseInterceptor = _chunk3AUOOEQOcjs.ResponseInterceptor; exports.SUPABASE_ANON_CLIENT = _chunkSPTDXUEDcjs.SUPABASE_ANON_CLIENT; exports.SUPABASE_SERVICE_ROLE_CLIENT = _chunkSPTDXUEDcjs.SUPABASE_SERVICE_ROLE_CLIENT; exports.SupabaseModule = _chunkSPTDXUEDcjs.SupabaseModule; exports.TrackingModule = _chunkHVHYZXBBcjs.TrackingModule; exports.UnauthorizedAppException = _chunkHDFPSA2Vcjs.UnauthorizedAppException; exports.ValidationAppException = _chunkHDFPSA2Vcjs.ValidationAppException; exports.applyNestKitDefaults = _chunkFNUZGYUFcjs.applyNestKitDefaults; exports.buildPageMeta = _chunkY72D5L6Icjs.buildPageMeta; exports.createCrudController = _chunk52IOOHNXcjs.createCrudController; exports.currentLanguage = _chunkAXMW5JF7cjs.currentLanguage; exports.isI18nMessage = _chunkPNK5WMPPcjs.isI18nMessage; exports.isPaginated = _chunkY72D5L6Icjs.isPaginated; exports.matchLanguage = _chunkAPUFKA4Kcjs.matchLanguage; exports.paginated = _chunkY72D5L6Icjs.paginated; exports.t = _chunkPNK5WMPPcjs.t; exports.translate = _chunkAXMW5JF7cjs.translate; exports.translateDeep = _chunkAXMW5JF7cjs.translateDeep; exports.translateOr = _chunkAPUFKA4Kcjs.translateOr; exports.withTenantScope = _chunkRF75KC63cjs.withTenantScope;
111
+ exports.AppException = _chunkQ5Y33L7Bcjs.AppException; exports.BaseCrudService = _chunk52IOOHNXcjs.BaseCrudService; exports.BaseResponseDto = _chunkQS2W5XCQcjs.BaseResponseDto; exports.ConflictAppException = _chunkHDFPSA2Vcjs.ConflictAppException; exports.ForbiddenAppException = _chunkHDFPSA2Vcjs.ForbiddenAppException; exports.GlobalExceptionFilter = _chunkLSDY6ETGcjs.GlobalExceptionFilter; exports.I18nInterceptor = _chunkAPUFKA4Kcjs.I18nInterceptor; exports.I18nMessage = _chunkPNK5WMPPcjs.I18nMessage; exports.I18nModule = _chunkAPUFKA4Kcjs.I18nModule; exports.ListQuery = _chunk52IOOHNXcjs.ListQuery; exports.NestI18nTranslator = _chunkAPUFKA4Kcjs.NestI18nTranslator; exports.NotFoundAppException = _chunkHDFPSA2Vcjs.NotFoundAppException; exports.PG_POOL = _chunkRF75KC63cjs.PG_POOL; exports.PgModule = _chunkRF75KC63cjs.PgModule; exports.REQUEST_ID_HEADER = _chunkHVHYZXBBcjs.REQUEST_ID_HEADER; exports.RequestContext = _chunkSDWHKPXIcjs.RequestContext; exports.RequestIdMiddleware = _chunkHVHYZXBBcjs.RequestIdMiddleware; exports.ResponseInterceptor = _chunk3AUOOEQOcjs.ResponseInterceptor; exports.SUPABASE_ANON_CLIENT = _chunkSPTDXUEDcjs.SUPABASE_ANON_CLIENT; exports.SUPABASE_SERVICE_ROLE_CLIENT = _chunkSPTDXUEDcjs.SUPABASE_SERVICE_ROLE_CLIENT; exports.SupabaseModule = _chunkSPTDXUEDcjs.SupabaseModule; exports.TrackingModule = _chunkHVHYZXBBcjs.TrackingModule; exports.UnauthorizedAppException = _chunkHDFPSA2Vcjs.UnauthorizedAppException; exports.ValidationAppException = _chunkHDFPSA2Vcjs.ValidationAppException; exports.applyNestKitDefaults = _chunkALIKVFOVcjs.applyNestKitDefaults; exports.buildPageMeta = _chunkY72D5L6Icjs.buildPageMeta; exports.createCrudController = _chunk52IOOHNXcjs.createCrudController; exports.currentLanguage = _chunkAXMW5JF7cjs.currentLanguage; exports.isI18nMessage = _chunkPNK5WMPPcjs.isI18nMessage; exports.isPaginated = _chunkY72D5L6Icjs.isPaginated; exports.matchLanguage = _chunkAPUFKA4Kcjs.matchLanguage; exports.paginated = _chunkY72D5L6Icjs.paginated; exports.t = _chunkPNK5WMPPcjs.t; exports.translate = _chunkAXMW5JF7cjs.translate; exports.translateDeep = _chunkAXMW5JF7cjs.translateDeep; exports.translateOr = _chunkAPUFKA4Kcjs.translateOr; exports.withTenantScope = _chunkRF75KC63cjs.withTenantScope;
package/dist/index.js CHANGED
@@ -14,14 +14,10 @@ import {
14
14
  RequestIdMiddleware,
15
15
  TrackingModule
16
16
  } from "./chunk-4PFAKLT3.js";
17
- import "./chunk-ODPSIFOB.js";
18
17
  import {
19
- I18nInterceptor,
20
- I18nModule,
21
- NestI18nTranslator,
22
- matchLanguage,
23
- translateOr
24
- } from "./chunk-6RAPVLJM.js";
18
+ BaseResponseDto
19
+ } from "./chunk-XX2HPTRU.js";
20
+ import "./chunk-ODPSIFOB.js";
25
21
  import {
26
22
  BaseCrudService,
27
23
  ListQuery,
@@ -30,13 +26,10 @@ import {
30
26
  import "./chunk-ZJMLEP5H.js";
31
27
  import {
32
28
  applyNestKitDefaults
33
- } from "./chunk-UNEVXCFW.js";
29
+ } from "./chunk-PFHHLB7B.js";
34
30
  import {
35
31
  ResponseInterceptor
36
32
  } from "./chunk-DYHSOULW.js";
37
- import {
38
- BaseResponseDto
39
- } from "./chunk-XX2HPTRU.js";
40
33
  import "./chunk-DQYAIQQ5.js";
41
34
  import {
42
35
  ConflictAppException,
@@ -47,7 +40,17 @@ import {
47
40
  } from "./chunk-ZFIDAX7K.js";
48
41
  import {
49
42
  GlobalExceptionFilter
50
- } from "./chunk-A2DGK4ZL.js";
43
+ } from "./chunk-2DUEQKOI.js";
44
+ import {
45
+ AppException
46
+ } from "./chunk-M3GQDRWR.js";
47
+ import {
48
+ I18nInterceptor,
49
+ I18nModule,
50
+ NestI18nTranslator,
51
+ matchLanguage,
52
+ translateOr
53
+ } from "./chunk-6RAPVLJM.js";
51
54
  import {
52
55
  currentLanguage,
53
56
  translate,
@@ -61,9 +64,6 @@ import {
61
64
  import {
62
65
  RequestContext
63
66
  } from "./chunk-ETRUVZTJ.js";
64
- import {
65
- AppException
66
- } from "./chunk-M3GQDRWR.js";
67
67
  import {
68
68
  I18nMessage,
69
69
  isI18nMessage,
@@ -0,0 +1,70 @@
1
+ export interface MercadoPagoConnectOptions {
2
+ /** From the Mercado Pago application, not from any connected seller. */
3
+ clientId: string;
4
+ clientSecret: string;
5
+ /** Must match, character for character, the Redirect URI registered on the application. */
6
+ redirectUri: string;
7
+ /**
8
+ * Defaults to `offline_access`. Mercado Pago documents this as the one
9
+ * thing that turns on `refresh_token` for the authorization-code flow —
10
+ * drop it and every connection stops working the moment its access token
11
+ * expires, with no way back short of sending the seller through consent
12
+ * again.
13
+ */
14
+ scope?: string;
15
+ /** Override for tests. Defaults to `https://api.mercadopago.com`. */
16
+ tokenBaseUrl?: string;
17
+ /** Override for tests. Defaults to `https://auth.mercadopago.com/authorization`. */
18
+ authorizeUrl?: string;
19
+ /** Override for tests. Defaults to the global `fetch`. */
20
+ fetchImpl?: typeof fetch;
21
+ }
22
+ /** A connected seller's tokens, ready to build a {@link MercadoPagoTerminalPayments} for them. */
23
+ export interface MercadoPagoConnectTokens {
24
+ accessToken: string;
25
+ refreshToken: string;
26
+ /** The seller's own Mercado Pago user id — what {@link MercadoPagoTerminalPayments.createStore} takes as `userId`. */
27
+ userId: string;
28
+ scope?: string;
29
+ liveMode?: boolean;
30
+ tokenType?: string;
31
+ expiresAt: Date;
32
+ }
33
+ /**
34
+ * Connects a seller's Mercado Pago account by OAuth: the marketplace flow a
35
+ * single fixed `MERCADOPAGO_ACCESS_TOKEN` (see
36
+ * {@link MercadoPagoTerminalPayments}) cannot cover — one integrator, many
37
+ * connected sellers, each operating their own terminals on their own
38
+ * tokens, none of them typed into a form by hand.
39
+ *
40
+ * This is deliberately a separate class from `MercadoPagoTerminalPayments`
41
+ * rather than an extra constructor mode: connecting a seller and charging a
42
+ * terminal happen at different times, usually in different parts of an
43
+ * application (an onboarding screen versus a checkout), and a seller's
44
+ * access token is the *output* of this class and the *input* to that one.
45
+ */
46
+ export declare class MercadoPagoConnect {
47
+ private readonly options;
48
+ private readonly tokenBaseUrl;
49
+ private readonly authorizeUrl;
50
+ private readonly fetchImpl;
51
+ constructor(options: MercadoPagoConnectOptions);
52
+ /**
53
+ * The consent-screen URL to send the seller to. `state` comes back
54
+ * untouched on your callback — sign it yourself (see
55
+ * `@miguelmorales13/nestkit/security`'s `signState`) if you need to prove
56
+ * your own application started the flow and tie the callback back to
57
+ * whoever did; Mercado Pago's redirect carries it, nothing more.
58
+ */
59
+ authorizationUrl(state?: string): string;
60
+ /** Trades the callback's `code` for the seller's tokens. */
61
+ exchangeCode(code: string): Promise<MercadoPagoConnectTokens>;
62
+ /**
63
+ * Renews an access token. Mercado Pago **rotates the refresh token on
64
+ * every renewal** — persist the whole result, not just `accessToken`, or
65
+ * the seller's connection silently stops renewing the first time this
66
+ * runs.
67
+ */
68
+ refresh(refreshToken: string): Promise<MercadoPagoConnectTokens>;
69
+ private token;
70
+ }
@@ -1,5 +1,14 @@
1
1
  import type { MercadoPagoPointOptions } from '../payments.options.js';
2
2
  import type { ChargeInput, Terminal, TerminalPayment, TerminalPaymentsPort, TerminalWebhookEvent, WebhookRequestLike } from '../payments.port.js';
3
+ /**
4
+ * Whether `terminalId` belongs to a model Mercado Pago will switch to PDV
5
+ * mode over the API. The id carries its model as a prefix
6
+ * (`NEWLAND_N950__SBX0000001`) — exactly the pattern
7
+ * `PATCH /terminals/v1/setup` validates and, for an unsupported model,
8
+ * rejects with a bare `"'$.terminals[0].id' - does not match pattern"` that
9
+ * names no model and suggests nothing is wrong with the id itself.
10
+ */
11
+ export declare function isIntegrableTerminalModel(terminalId: string): boolean;
3
12
  /**
4
13
  * Mercado Pago Point over the Orders API.
5
14
  *
@@ -42,6 +51,54 @@ export declare class MercadoPagoTerminalPayments implements TerminalPaymentsPort
42
51
  * expensive way to discover this.
43
52
  */
44
53
  setOperatingMode(terminalIds: string[], mode: 'PDV' | 'STANDALONE'): Promise<Terminal[]>;
54
+ /**
55
+ * Creates the "Store" a terminal has to belong to before the Orders API
56
+ * will accept a charge for it — Mercado Pago's own Point documentation
57
+ * describes a mandatory hierarchy, **Store → POS → Terminal**, and a
58
+ * terminal that only ever paired through the merchant app (standalone,
59
+ * never through this call) sits outside it: charging it fails with
60
+ * `PA_UNAUTHORIZED_RESULT_FROM_POLICIES`, a message that names no missing
61
+ * Store because the policy engine that rejects it does not know that is
62
+ * the reason either.
63
+ *
64
+ * `location` and `businessHours` are Mercado Pago requirements, not
65
+ * choices this method makes for you — filled with real values it is your
66
+ * integration's call whether to ask the merchant for them or default them.
67
+ *
68
+ * **Check {@link listTerminals} first.** A terminal paired through the app
69
+ * can already carry a `storeId`/`posId` of its own — Mercado Pago assigns
70
+ * them the moment it is paired, standalone or not. Calling this again for
71
+ * a terminal that already has one does not fail, but it litters the
72
+ * merchant's Mercado Pago panel with a Store nothing points at.
73
+ */
74
+ createStore(input: {
75
+ /** The Mercado Pago user id the Store belongs to — the seller's, from their OAuth connection, not the application's. */
76
+ userId: string;
77
+ name: string;
78
+ location: {
79
+ streetNumber: string;
80
+ streetName: string;
81
+ cityName: string;
82
+ stateName: string;
83
+ latitude: number;
84
+ longitude: number;
85
+ };
86
+ /** All seven days. Each is a list of open/close windows, `HH:MM` 24h. */
87
+ businessHours: Record<'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sunday', {
88
+ open: string;
89
+ close: string;
90
+ }[]>;
91
+ }): Promise<string>;
92
+ /**
93
+ * Creates the "POS" (register/cash-point) inside a Store — the second
94
+ * link in Mercado Pago's Store → POS → Terminal chain, and the one that
95
+ * actually takes a terminal out of `standalone` once it is assigned to it.
96
+ */
97
+ createPos(input: {
98
+ storeId: string;
99
+ name: string;
100
+ externalId?: string;
101
+ }): Promise<string>;
45
102
  /**
46
103
  * Forces a final status on an order created with **test credentials**, so a
47
104
  * whole flow — order, status change, webhook — can be exercised without a