@adatechnology/push-provider 0.1.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,54 @@
1
+ # @adatechnology/push-provider
2
+
3
+ Push por **Expo** e **FCM** atrás de uma porta só. Stateless: recebe token e mensagem, devolve
4
+ resultado classificado. Não guarda estado, não conhece banco, não sabe o que é uma notificação —
5
+ isso é o `notification-module`.
6
+
7
+ ## Instalação
8
+
9
+ ```bash
10
+ bun add @adatechnology/push-provider
11
+ ```
12
+
13
+ O `firebase-admin` é peer **opcional**, carregado por `import()` dinâmico só quando o driver FCM é
14
+ usado de fato. Quem manda push só por Expo não instala os ~50 MB do SDK do Firebase.
15
+
16
+ ## Uso
17
+
18
+ ```ts
19
+ import { createPushProvider } from '@adatechnology/push-provider'
20
+
21
+ const push = createPushProvider({ driver: 'expo' })
22
+ // ou: createPushProvider({ driver: 'fcm', serviceAccount })
23
+ ```
24
+
25
+ Também dá para instanciar direto: `createExpoPushProvider`, `createFcmPushProvider`.
26
+
27
+ ## O resultado é classificado, e é o ponto do pacote
28
+
29
+ ```ts
30
+ const result = await push.send({ token, title, body, data })
31
+ ```
32
+
33
+ | `outcome` | Quando | O que o módulo faz |
34
+ |---|---|---|
35
+ | `sent` | aceito pelo provedor | grava `providerMessageId` |
36
+ | `retriable` | 429, 5xx, rede | reenfileira com backoff |
37
+ | `permanent` | payload inválido, credencial errada | marca falha, **sem retry** |
38
+ | `invalid-target` | `DeviceNotRegistered`, `UNREGISTERED` | **desativa o device** |
39
+
40
+ `invalid-target` é separado de `permanent` de propósito. Token de push morre o tempo todo — app
41
+ desinstalado, reinstalado, cache limpo. Sem essa distinção, cada usuário que troca de celular
42
+ deixa para trás um token que a fila tenta para sempre.
43
+
44
+ Traduzir o vocabulário de erro do provedor é responsabilidade **daqui**: só este pacote sabe que
45
+ `DeviceNotRegistered` do Expo e `UNREGISTERED` do FCM significam a mesma coisa.
46
+
47
+ ## Envio em lote
48
+
49
+ O Expo aceita até 100 mensagens por chamada, e o driver fatia sozinho. Cada item volta com o
50
+ próprio `outcome` — um token morto no lote não invalida os outros 99.
51
+
52
+ ## Licença
53
+
54
+ MIT © Ada Technology
package/dist/index.cjs ADDED
@@ -0,0 +1,267 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/index.ts
32
+ var index_exports = {};
33
+ __export(index_exports, {
34
+ createExpoPushProvider: () => createExpoPushProvider,
35
+ createFcmPushProvider: () => createFcmPushProvider,
36
+ createPushProvider: () => createPushProvider,
37
+ isFcmError: () => isFcmError,
38
+ sendExpoPushBatch: () => sendExpoPushBatch
39
+ });
40
+ module.exports = __toCommonJS(index_exports);
41
+
42
+ // src/ExpoPushProvider.ts
43
+ var import_notification_contracts = require("@adatechnology/notification-contracts");
44
+ var EXPO_PUSH_URL = "https://exp.host/--/api/v2/push/send";
45
+ var EXPO_PUSH_CHUNK_SIZE = 100;
46
+ function chunkArray(items, size) {
47
+ const chunks = [];
48
+ for (let offset = 0; offset < items.length; offset += size) {
49
+ chunks.push(items.slice(offset, offset + size));
50
+ }
51
+ return chunks;
52
+ }
53
+ __name(chunkArray, "chunkArray");
54
+ function classifyExpoTicket(ticket) {
55
+ if (ticket.status === "ok") return {
56
+ outcome: "sent",
57
+ providerMessageId: ticket.id
58
+ };
59
+ const errorCode = ticket.details?.error ?? "unknown";
60
+ if (errorCode === "DeviceNotRegistered") return {
61
+ outcome: "invalid_target",
62
+ errorCode
63
+ };
64
+ if (errorCode === "MessageRateExceeded") return {
65
+ outcome: "retriable",
66
+ errorCode
67
+ };
68
+ return {
69
+ outcome: "permanent",
70
+ errorCode
71
+ };
72
+ }
73
+ __name(classifyExpoTicket, "classifyExpoTicket");
74
+ function classifyHttpStatus(status) {
75
+ if (status === 429 || status >= 500) return {
76
+ outcome: "retriable",
77
+ errorCode: `http_${status}`
78
+ };
79
+ return {
80
+ outcome: "permanent",
81
+ errorCode: `http_${status}`
82
+ };
83
+ }
84
+ __name(classifyHttpStatus, "classifyHttpStatus");
85
+ async function sendExpoPushChunk(messages, config) {
86
+ const fetchImpl = config.fetchImpl ?? fetch;
87
+ const headers = {
88
+ Accept: "application/json",
89
+ "Content-Type": "application/json"
90
+ };
91
+ if (config.accessToken) headers.Authorization = `Bearer ${config.accessToken}`;
92
+ const response = await fetchImpl(EXPO_PUSH_URL, {
93
+ method: "POST",
94
+ headers,
95
+ body: JSON.stringify(messages)
96
+ });
97
+ if (!response.ok) {
98
+ const outcome = classifyHttpStatus(response.status);
99
+ return messages.map(() => outcome);
100
+ }
101
+ const payload = await response.json();
102
+ return payload.data.map(classifyExpoTicket);
103
+ }
104
+ __name(sendExpoPushChunk, "sendExpoPushChunk");
105
+ async function sendExpoPushBatch(messages, config = {}) {
106
+ const chunks = chunkArray(messages, EXPO_PUSH_CHUNK_SIZE);
107
+ const chunkResults = await Promise.all(chunks.map((chunk) => sendExpoPushChunk(chunk, config)));
108
+ return chunkResults.flat();
109
+ }
110
+ __name(sendExpoPushBatch, "sendExpoPushBatch");
111
+ function createExpoPushProvider(config = {}) {
112
+ return {
113
+ driver: import_notification_contracts.PUSH_DRIVER.EXPO,
114
+ async send(params) {
115
+ const message = {
116
+ to: params.token,
117
+ title: params.title,
118
+ body: params.body,
119
+ data: params.data,
120
+ badge: params.badge
121
+ };
122
+ const [result] = await sendExpoPushBatch([
123
+ message
124
+ ], config);
125
+ return result;
126
+ }
127
+ };
128
+ }
129
+ __name(createExpoPushProvider, "createExpoPushProvider");
130
+
131
+ // src/FcmPushProvider.ts
132
+ var import_notification_contracts2 = require("@adatechnology/notification-contracts");
133
+
134
+ // src/FcmMessagingClient.ts
135
+ function isFcmError(error) {
136
+ return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string";
137
+ }
138
+ __name(isFcmError, "isFcmError");
139
+
140
+ // src/FcmPushProvider.ts
141
+ var INVALID_TARGET_CODES = /* @__PURE__ */ new Set([
142
+ "messaging/registration-token-not-registered",
143
+ "messaging/invalid-registration-token"
144
+ ]);
145
+ var RETRIABLE_CODES = /* @__PURE__ */ new Set([
146
+ "messaging/message-rate-exceeded",
147
+ "messaging/device-message-rate-exceeded",
148
+ "messaging/quota-exceeded",
149
+ "messaging/unavailable",
150
+ "messaging/internal-error"
151
+ ]);
152
+ function classifyFcmError(error) {
153
+ if (!isFcmError(error)) return {
154
+ outcome: "retriable",
155
+ errorCode: "unknown"
156
+ };
157
+ if (INVALID_TARGET_CODES.has(error.code)) return {
158
+ outcome: "invalid_target",
159
+ errorCode: error.code
160
+ };
161
+ if (RETRIABLE_CODES.has(error.code)) return {
162
+ outcome: "retriable",
163
+ errorCode: error.code
164
+ };
165
+ return {
166
+ outcome: "permanent",
167
+ errorCode: error.code
168
+ };
169
+ }
170
+ __name(classifyFcmError, "classifyFcmError");
171
+ function buildFcmMessage(params) {
172
+ const base = {
173
+ token: params.token,
174
+ notification: {
175
+ title: params.title,
176
+ body: params.body
177
+ },
178
+ data: params.data
179
+ };
180
+ if (params.platform === import_notification_contracts2.DEVICE_PLATFORM.WEB) {
181
+ return {
182
+ ...base,
183
+ webpush: {
184
+ notification: {
185
+ title: params.title,
186
+ body: params.body
187
+ }
188
+ }
189
+ };
190
+ }
191
+ if (params.platform === import_notification_contracts2.DEVICE_PLATFORM.IOS) {
192
+ return {
193
+ ...base,
194
+ apns: {
195
+ payload: {
196
+ aps: {
197
+ badge: params.badge
198
+ }
199
+ }
200
+ }
201
+ };
202
+ }
203
+ return params.badge === void 0 ? base : {
204
+ ...base,
205
+ android: {
206
+ notification: {
207
+ notificationCount: params.badge
208
+ }
209
+ }
210
+ };
211
+ }
212
+ __name(buildFcmMessage, "buildFcmMessage");
213
+ async function initFirebaseMessaging(config) {
214
+ if (!config.serviceAccountJson) throw new import_notification_contracts2.ConfigMissingError("serviceAccountJson");
215
+ const admin = await import("firebase-admin");
216
+ const appName = config.appName ?? "adatechnology-notification-push";
217
+ const existingApp = admin.apps.find((app2) => app2?.name === appName);
218
+ const app = existingApp ?? admin.initializeApp({
219
+ credential: admin.credential.cert(JSON.parse(config.serviceAccountJson))
220
+ }, appName);
221
+ return admin.messaging(app);
222
+ }
223
+ __name(initFirebaseMessaging, "initFirebaseMessaging");
224
+ function createFcmPushProvider(config = {}) {
225
+ let clientPromise;
226
+ function resolveClient() {
227
+ if (config.messagingClient) return Promise.resolve(config.messagingClient);
228
+ clientPromise ??= initFirebaseMessaging(config);
229
+ return clientPromise;
230
+ }
231
+ __name(resolveClient, "resolveClient");
232
+ return {
233
+ driver: import_notification_contracts2.PUSH_DRIVER.FCM,
234
+ async send(params) {
235
+ const client = await resolveClient();
236
+ try {
237
+ const providerMessageId = await client.send(buildFcmMessage(params));
238
+ return {
239
+ outcome: "sent",
240
+ providerMessageId
241
+ };
242
+ } catch (error) {
243
+ return classifyFcmError(error);
244
+ }
245
+ }
246
+ };
247
+ }
248
+ __name(createFcmPushProvider, "createFcmPushProvider");
249
+
250
+ // src/PushProviderFactory.ts
251
+ var import_notification_contracts3 = require("@adatechnology/notification-contracts");
252
+ function createPushProvider(params) {
253
+ if (params.driver === import_notification_contracts3.PUSH_DRIVER.EXPO) return createExpoPushProvider(params);
254
+ if (params.driver === import_notification_contracts3.PUSH_DRIVER.FCM) return createFcmPushProvider(params);
255
+ const _exhaustive = params;
256
+ throw new Error(`Driver de push desconhecido: ${String(_exhaustive.driver)}`);
257
+ }
258
+ __name(createPushProvider, "createPushProvider");
259
+ // Annotate the CommonJS export names for ESM import in node:
260
+ 0 && (module.exports = {
261
+ createExpoPushProvider,
262
+ createFcmPushProvider,
263
+ createPushProvider,
264
+ isFcmError,
265
+ sendExpoPushBatch
266
+ });
267
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/ExpoPushProvider.ts","../src/FcmPushProvider.ts","../src/FcmMessagingClient.ts","../src/PushProviderFactory.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nexport { createExpoPushProvider, sendExpoPushBatch } from './ExpoPushProvider'\nexport type { ExpoPushProviderConfig } from './ExpoPushProvider'\nexport type { ExpoPushMessage, ExpoPushTicket, ExpoPushResponse } from './expoTypes'\n\nexport { createFcmPushProvider } from './FcmPushProvider'\nexport type { FcmPushProviderConfig } from './FcmPushProvider'\nexport type { FcmMessage, FcmError, FcmMessagingClient } from './FcmMessagingClient'\nexport { isFcmError } from './FcmMessagingClient'\n\nexport { createPushProvider } from './PushProviderFactory'\nexport type { CreatePushProviderParams } from './PushProviderFactory'\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { PUSH_DRIVER } from '@adatechnology/notification-contracts'\nimport type { DeliveryAttemptResult, PushDriverPort, SendPushParams } from '@adatechnology/notification-contracts'\n\nimport type { ExpoPushMessage, ExpoPushResponse, ExpoPushTicket } from './expoTypes'\n\nconst EXPO_PUSH_URL = 'https://exp.host/--/api/v2/push/send'\n\n// Limite documentado da API — enviar mais que isso na mesma chamada é rejeitado pela Expo.\nconst EXPO_PUSH_CHUNK_SIZE = 100\n\nexport type ExpoPushProviderConfig = {\n /** Access token de organização Expo (EAS) — opcional para apps standalone sem EAS. */\n readonly accessToken?: string\n /** Injeção para teste; produção usa o `fetch` global. */\n readonly fetchImpl?: typeof fetch\n}\n\nfunction chunkArray<T>(items: readonly T[], size: number): T[][] {\n const chunks: T[][] = []\n for (let offset = 0; offset < items.length; offset += size) {\n chunks.push(items.slice(offset, offset + size) as T[])\n }\n return chunks\n}\n\n// Ticket de erro documentado pela Expo — \"apaga o token\" é sempre DeviceNotRegistered.\nfunction classifyExpoTicket(ticket: ExpoPushTicket): DeliveryAttemptResult {\n if (ticket.status === 'ok') return { outcome: 'sent', providerMessageId: ticket.id }\n\n const errorCode = ticket.details?.error ?? 'unknown'\n if (errorCode === 'DeviceNotRegistered') return { outcome: 'invalid_target', errorCode }\n if (errorCode === 'MessageRateExceeded') return { outcome: 'retriable', errorCode }\n // MessageTooBig, InvalidCredentials e qualquer código novo: tratar como definitivo é mais seguro\n // que retry silencioso — o host vê o erro no primeiro delivery em vez de gastar 5 tentativas.\n return { outcome: 'permanent', errorCode }\n}\n\nfunction classifyHttpStatus(status: number): DeliveryAttemptResult {\n if (status === 429 || status >= 500) return { outcome: 'retriable', errorCode: `http_${status}` }\n return { outcome: 'permanent', errorCode: `http_${status}` }\n}\n\nasync function sendExpoPushChunk(\n messages: readonly ExpoPushMessage[],\n config: ExpoPushProviderConfig,\n): Promise<DeliveryAttemptResult[]> {\n const fetchImpl = config.fetchImpl ?? fetch\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n }\n if (config.accessToken) headers.Authorization = `Bearer ${config.accessToken}`\n\n const response = await fetchImpl(EXPO_PUSH_URL, {\n method: 'POST',\n headers,\n body: JSON.stringify(messages),\n })\n\n if (!response.ok) {\n const outcome = classifyHttpStatus(response.status)\n return messages.map(() => outcome)\n }\n\n const payload = (await response.json()) as ExpoPushResponse\n return payload.data.map(classifyExpoTicket)\n}\n\n/**\n * Envio em lote — usado internamente por `send()` (lote de 1) e exportado para o `notification-module`\n * poder despachar várias entregas na mesma janela de dispatch sem uma chamada HTTP por token.\n */\nexport async function sendExpoPushBatch(\n messages: readonly ExpoPushMessage[],\n config: ExpoPushProviderConfig = {},\n): Promise<DeliveryAttemptResult[]> {\n const chunks = chunkArray(messages, EXPO_PUSH_CHUNK_SIZE)\n const chunkResults = await Promise.all(chunks.map((chunk) => sendExpoPushChunk(chunk, config)))\n return chunkResults.flat()\n}\n\nexport function createExpoPushProvider(config: ExpoPushProviderConfig = {}): PushDriverPort {\n return {\n driver: PUSH_DRIVER.EXPO,\n async send(params: SendPushParams): Promise<DeliveryAttemptResult> {\n const message: ExpoPushMessage = {\n to: params.token,\n title: params.title,\n body: params.body,\n data: params.data,\n badge: params.badge,\n }\n\n const [result] = await sendExpoPushBatch([message], config)\n return result\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { ConfigMissingError, DEVICE_PLATFORM, PUSH_DRIVER } from '@adatechnology/notification-contracts'\nimport type { DeliveryAttemptResult, PushDriverPort, SendPushParams } from '@adatechnology/notification-contracts'\n\nimport { isFcmError, type FcmMessage, type FcmMessagingClient } from './FcmMessagingClient'\n\nexport type FcmPushProviderConfig = {\n /** Conteúdo do JSON de credencial de serviço (nunca um caminho de arquivo — evita I/O no boot). */\n readonly serviceAccountJson?: string\n /** Nome do app do firebase-admin; só relevante se o processo hospeda mais de um. */\n readonly appName?: string\n /** Injeção de teste — presente, o `firebase-admin` real nunca é importado. */\n readonly messagingClient?: FcmMessagingClient\n}\n\n// admin.messaging(): FirebaseMessagingError.code documentado pelo SDK.\nconst INVALID_TARGET_CODES = new Set([\n 'messaging/registration-token-not-registered',\n 'messaging/invalid-registration-token',\n])\nconst RETRIABLE_CODES = new Set([\n 'messaging/message-rate-exceeded',\n 'messaging/device-message-rate-exceeded',\n 'messaging/quota-exceeded',\n 'messaging/unavailable',\n 'messaging/internal-error',\n])\n\nfunction classifyFcmError(error: unknown): DeliveryAttemptResult {\n if (!isFcmError(error)) return { outcome: 'retriable', errorCode: 'unknown' }\n if (INVALID_TARGET_CODES.has(error.code)) return { outcome: 'invalid_target', errorCode: error.code }\n if (RETRIABLE_CODES.has(error.code)) return { outcome: 'retriable', errorCode: error.code }\n return { outcome: 'permanent', errorCode: error.code }\n}\n\n/**\n * Web push usa o mesmo `messaging().send()` do FCM — só o bloco `webpush` muda. É o que permite\n * validar o canal push inteiro pelo PWA do quickcart, sem depender de um app mobile.\n */\nfunction buildFcmMessage(params: SendPushParams): FcmMessage {\n const base = {\n token: params.token,\n notification: { title: params.title, body: params.body },\n data: params.data,\n }\n\n if (params.platform === DEVICE_PLATFORM.WEB) {\n return { ...base, webpush: { notification: { title: params.title, body: params.body } } }\n }\n if (params.platform === DEVICE_PLATFORM.IOS) {\n return { ...base, apns: { payload: { aps: { badge: params.badge } } } }\n }\n return params.badge === undefined ? base : { ...base, android: { notification: { notificationCount: params.badge } } }\n}\n\n// firebase-admin (~40 MB) só é importado quando o driver FCM é de fato usado sem cliente injetado\n// — quem só usa Expo, ou quem testa com dublê, nunca carrega o SDK.\nasync function initFirebaseMessaging(config: FcmPushProviderConfig): Promise<FcmMessagingClient> {\n if (!config.serviceAccountJson) throw new ConfigMissingError('serviceAccountJson')\n\n const admin = await import('firebase-admin')\n const appName = config.appName ?? 'adatechnology-notification-push'\n const existingApp = admin.apps.find((app) => app?.name === appName)\n const app =\n existingApp ??\n admin.initializeApp({ credential: admin.credential.cert(JSON.parse(config.serviceAccountJson)) }, appName)\n\n return admin.messaging(app)\n}\n\nexport function createFcmPushProvider(config: FcmPushProviderConfig = {}): PushDriverPort {\n let clientPromise: Promise<FcmMessagingClient> | undefined\n\n function resolveClient(): Promise<FcmMessagingClient> {\n if (config.messagingClient) return Promise.resolve(config.messagingClient)\n clientPromise ??= initFirebaseMessaging(config)\n return clientPromise\n }\n\n return {\n driver: PUSH_DRIVER.FCM,\n async send(params: SendPushParams): Promise<DeliveryAttemptResult> {\n const client = await resolveClient()\n try {\n const providerMessageId = await client.send(buildFcmMessage(params))\n return { outcome: 'sent', providerMessageId }\n } catch (error) {\n return classifyFcmError(error)\n }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\n/**\n * Forma mínima que o `admin.messaging()` do `firebase-admin` já satisfaz. Declarada por\n * estrutura — e não importada do pacote — para que os testes injetem um dublê sem carregar o SDK\n * real, e para o provider não amarrar a versão exata do `firebase-admin` do consumidor.\n */\nexport type FcmMessage = {\n readonly token: string\n readonly notification: { readonly title: string; readonly body: string }\n readonly data?: Readonly<Record<string, string>>\n readonly android?: { readonly notification?: { readonly notificationCount?: number } }\n readonly apns?: { readonly payload: { readonly aps: { readonly badge?: number } } }\n /** Presente só quando o token é de web push — o mesmo `send()` atende os três destinos. */\n readonly webpush?: { readonly notification?: { readonly title?: string; readonly body?: string } }\n}\n\nexport type FcmError = {\n readonly code: string\n readonly message: string\n}\n\nexport type FcmMessagingClient = {\n send(message: FcmMessage): Promise<string>\n}\n\nexport function isFcmError(error: unknown): error is FcmError {\n return typeof error === 'object' && error !== null && 'code' in error && typeof (error as FcmError).code === 'string'\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { PUSH_DRIVER } from '@adatechnology/notification-contracts'\nimport type { PushDriverPort } from '@adatechnology/notification-contracts'\n\nimport { createExpoPushProvider, type ExpoPushProviderConfig } from './ExpoPushProvider'\nimport { createFcmPushProvider, type FcmPushProviderConfig } from './FcmPushProvider'\n\nexport type CreatePushProviderParams =\n | ({ readonly driver: typeof PUSH_DRIVER.EXPO } & ExpoPushProviderConfig)\n | ({ readonly driver: typeof PUSH_DRIVER.FCM } & FcmPushProviderConfig)\n\nexport function createPushProvider(params: CreatePushProviderParams): PushDriverPort {\n if (params.driver === PUSH_DRIVER.EXPO) return createExpoPushProvider(params)\n if (params.driver === PUSH_DRIVER.FCM) return createFcmPushProvider(params)\n\n const _exhaustive: never = params\n throw new Error(`Driver de push desconhecido: ${String((_exhaustive as { driver?: unknown }).driver)}`)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;ACIA,oCAA4B;AAK5B,IAAMA,gBAAgB;AAGtB,IAAMC,uBAAuB;AAS7B,SAASC,WAAcC,OAAqBC,MAAY;AACtD,QAAMC,SAAgB,CAAA;AACtB,WAASC,SAAS,GAAGA,SAASH,MAAMI,QAAQD,UAAUF,MAAM;AAC1DC,WAAOG,KAAKL,MAAMM,MAAMH,QAAQA,SAASF,IAAAA,CAAAA;EAC3C;AACA,SAAOC;AACT;AANSH;AAST,SAASQ,mBAAmBC,QAAsB;AAChD,MAAIA,OAAOC,WAAW,KAAM,QAAO;IAAEC,SAAS;IAAQC,mBAAmBH,OAAOI;EAAG;AAEnF,QAAMC,YAAYL,OAAOM,SAASC,SAAS;AAC3C,MAAIF,cAAc,sBAAuB,QAAO;IAAEH,SAAS;IAAkBG;EAAU;AACvF,MAAIA,cAAc,sBAAuB,QAAO;IAAEH,SAAS;IAAaG;EAAU;AAGlF,SAAO;IAAEH,SAAS;IAAaG;EAAU;AAC3C;AATSN;AAWT,SAASS,mBAAmBP,QAAc;AACxC,MAAIA,WAAW,OAAOA,UAAU,IAAK,QAAO;IAAEC,SAAS;IAAaG,WAAW,QAAQJ,MAAAA;EAAS;AAChG,SAAO;IAAEC,SAAS;IAAaG,WAAW,QAAQJ,MAAAA;EAAS;AAC7D;AAHSO;AAKT,eAAeC,kBACbC,UACAC,QAA8B;AAE9B,QAAMC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MAAM,OAAO,gBAAA;AAC3B,QAAMC,UAAUJ,OAAOI,WAAW;AAClC,QAAMC,cAAcF,MAAMG,KAAKC,KAAK,CAACC,SAAQA,MAAKC,SAASL,OAAAA;AAC3D,QAAMI,MACJH,eACAF,MAAMO,cAAc;IAAEC,YAAYR,MAAMQ,WAAWC,KAAKC,KAAKC,MAAMd,OAAOC,kBAAkB,CAAA;EAAG,GAAGG,OAAAA;AAEpG,SAAOD,MAAMY,UAAUP,GAAAA;AACzB;AAXeT;AAaR,SAASiB,sBAAsBhB,SAAgC,CAAC,GAAC;AACtE,MAAIiB;AAEJ,WAASC,gBAAAA;AACP,QAAIlB,OAAOmB,gBAAiB,QAAOC,QAAQC,QAAQrB,OAAOmB,eAAe;AACzEF,sBAAkBlB,sBAAsBC,MAAAA;AACxC,WAAOiB;EACT;AAJSC;AAMT,SAAO;IACLI,QAAQC,2CAAYC;IACpB,MAAMC,KAAK7C,QAAsB;AAC/B,YAAM8C,SAAS,MAAMR,cAAAA;AACrB,UAAI;AACF,cAAMS,oBAAoB,MAAMD,OAAOD,KAAK9C,gBAAgBC,MAAAA,CAAAA;AAC5D,eAAO;UAAEL,SAAS;UAAQoD;QAAkB;MAC9C,SAAStD,OAAO;AACd,eAAOD,iBAAiBC,KAAAA;MAC1B;IACF;EACF;AACF;AArBgB2C;;;AErEhB,IAAAY,iCAA4B;AAUrB,SAASC,mBAAmBC,QAAgC;AACjE,MAAIA,OAAOC,WAAWC,2CAAYC,KAAM,QAAOC,uBAAuBJ,MAAAA;AACtE,MAAIA,OAAOC,WAAWC,2CAAYG,IAAK,QAAOC,sBAAsBN,MAAAA;AAEpE,QAAMO,cAAqBP;AAC3B,QAAM,IAAIQ,MAAM,gCAAgCC,OAAQF,YAAqCN,MAAM,CAAA,EAAG;AACxG;AANgBF;","names":["EXPO_PUSH_URL","EXPO_PUSH_CHUNK_SIZE","chunkArray","items","size","chunks","offset","length","push","slice","classifyExpoTicket","ticket","status","outcome","providerMessageId","id","errorCode","details","error","classifyHttpStatus","sendExpoPushChunk","messages","config","fetchImpl","fetch","headers","Accept","accessToken","Authorization","response","method","body","JSON","stringify","ok","map","payload","json","data","sendExpoPushBatch","chunkResults","Promise","all","chunk","flat","createExpoPushProvider","driver","PUSH_DRIVER","EXPO","send","params","message","to","token","title","badge","result","import_notification_contracts","isFcmError","error","code","INVALID_TARGET_CODES","Set","RETRIABLE_CODES","classifyFcmError","error","isFcmError","outcome","errorCode","has","code","buildFcmMessage","params","base","token","notification","title","body","data","platform","DEVICE_PLATFORM","WEB","webpush","IOS","apns","payload","aps","badge","undefined","android","notificationCount","initFirebaseMessaging","config","serviceAccountJson","ConfigMissingError","admin","appName","existingApp","apps","find","app","name","initializeApp","credential","cert","JSON","parse","messaging","createFcmPushProvider","clientPromise","resolveClient","messagingClient","Promise","resolve","driver","PUSH_DRIVER","FCM","send","client","providerMessageId","import_notification_contracts","createPushProvider","params","driver","PUSH_DRIVER","EXPO","createExpoPushProvider","FCM","createFcmPushProvider","_exhaustive","Error","String"]}
@@ -0,0 +1,113 @@
1
+ import { PushDriverPort, DeliveryAttemptResult, PUSH_DRIVER } from '@adatechnology/notification-contracts';
2
+
3
+ /**
4
+ * Copyright (c) 2026 Ada Technology. MIT License.
5
+ */
6
+ type ExpoPushMessage = {
7
+ readonly to: string;
8
+ readonly title: string;
9
+ readonly body: string;
10
+ readonly data?: Readonly<Record<string, string>>;
11
+ readonly badge?: number;
12
+ };
13
+ type ExpoPushTicket = {
14
+ readonly status: 'ok';
15
+ readonly id: string;
16
+ } | {
17
+ readonly status: 'error';
18
+ readonly message: string;
19
+ readonly details?: {
20
+ readonly error?: string;
21
+ };
22
+ };
23
+ type ExpoPushResponse = {
24
+ readonly data: readonly ExpoPushTicket[];
25
+ };
26
+
27
+ /**
28
+ * Copyright (c) 2026 Ada Technology. MIT License.
29
+ */
30
+
31
+ type ExpoPushProviderConfig = {
32
+ /** Access token de organização Expo (EAS) — opcional para apps standalone sem EAS. */
33
+ readonly accessToken?: string;
34
+ /** Injeção para teste; produção usa o `fetch` global. */
35
+ readonly fetchImpl?: typeof fetch;
36
+ };
37
+ /**
38
+ * Envio em lote — usado internamente por `send()` (lote de 1) e exportado para o `notification-module`
39
+ * poder despachar várias entregas na mesma janela de dispatch sem uma chamada HTTP por token.
40
+ */
41
+ declare function sendExpoPushBatch(messages: readonly ExpoPushMessage[], config?: ExpoPushProviderConfig): Promise<DeliveryAttemptResult[]>;
42
+ declare function createExpoPushProvider(config?: ExpoPushProviderConfig): PushDriverPort;
43
+
44
+ /**
45
+ * Copyright (c) 2026 Ada Technology. MIT License.
46
+ */
47
+ /**
48
+ * Forma mínima que o `admin.messaging()` do `firebase-admin` já satisfaz. Declarada por
49
+ * estrutura — e não importada do pacote — para que os testes injetem um dublê sem carregar o SDK
50
+ * real, e para o provider não amarrar a versão exata do `firebase-admin` do consumidor.
51
+ */
52
+ type FcmMessage = {
53
+ readonly token: string;
54
+ readonly notification: {
55
+ readonly title: string;
56
+ readonly body: string;
57
+ };
58
+ readonly data?: Readonly<Record<string, string>>;
59
+ readonly android?: {
60
+ readonly notification?: {
61
+ readonly notificationCount?: number;
62
+ };
63
+ };
64
+ readonly apns?: {
65
+ readonly payload: {
66
+ readonly aps: {
67
+ readonly badge?: number;
68
+ };
69
+ };
70
+ };
71
+ /** Presente só quando o token é de web push — o mesmo `send()` atende os três destinos. */
72
+ readonly webpush?: {
73
+ readonly notification?: {
74
+ readonly title?: string;
75
+ readonly body?: string;
76
+ };
77
+ };
78
+ };
79
+ type FcmError = {
80
+ readonly code: string;
81
+ readonly message: string;
82
+ };
83
+ type FcmMessagingClient = {
84
+ send(message: FcmMessage): Promise<string>;
85
+ };
86
+ declare function isFcmError(error: unknown): error is FcmError;
87
+
88
+ /**
89
+ * Copyright (c) 2026 Ada Technology. MIT License.
90
+ */
91
+
92
+ type FcmPushProviderConfig = {
93
+ /** Conteúdo do JSON de credencial de serviço (nunca um caminho de arquivo — evita I/O no boot). */
94
+ readonly serviceAccountJson?: string;
95
+ /** Nome do app do firebase-admin; só relevante se o processo hospeda mais de um. */
96
+ readonly appName?: string;
97
+ /** Injeção de teste — presente, o `firebase-admin` real nunca é importado. */
98
+ readonly messagingClient?: FcmMessagingClient;
99
+ };
100
+ declare function createFcmPushProvider(config?: FcmPushProviderConfig): PushDriverPort;
101
+
102
+ /**
103
+ * Copyright (c) 2026 Ada Technology. MIT License.
104
+ */
105
+
106
+ type CreatePushProviderParams = ({
107
+ readonly driver: typeof PUSH_DRIVER.EXPO;
108
+ } & ExpoPushProviderConfig) | ({
109
+ readonly driver: typeof PUSH_DRIVER.FCM;
110
+ } & FcmPushProviderConfig);
111
+ declare function createPushProvider(params: CreatePushProviderParams): PushDriverPort;
112
+
113
+ export { type CreatePushProviderParams, type ExpoPushMessage, type ExpoPushProviderConfig, type ExpoPushResponse, type ExpoPushTicket, type FcmError, type FcmMessage, type FcmMessagingClient, type FcmPushProviderConfig, createExpoPushProvider, createFcmPushProvider, createPushProvider, isFcmError, sendExpoPushBatch };
@@ -0,0 +1,113 @@
1
+ import { PushDriverPort, DeliveryAttemptResult, PUSH_DRIVER } from '@adatechnology/notification-contracts';
2
+
3
+ /**
4
+ * Copyright (c) 2026 Ada Technology. MIT License.
5
+ */
6
+ type ExpoPushMessage = {
7
+ readonly to: string;
8
+ readonly title: string;
9
+ readonly body: string;
10
+ readonly data?: Readonly<Record<string, string>>;
11
+ readonly badge?: number;
12
+ };
13
+ type ExpoPushTicket = {
14
+ readonly status: 'ok';
15
+ readonly id: string;
16
+ } | {
17
+ readonly status: 'error';
18
+ readonly message: string;
19
+ readonly details?: {
20
+ readonly error?: string;
21
+ };
22
+ };
23
+ type ExpoPushResponse = {
24
+ readonly data: readonly ExpoPushTicket[];
25
+ };
26
+
27
+ /**
28
+ * Copyright (c) 2026 Ada Technology. MIT License.
29
+ */
30
+
31
+ type ExpoPushProviderConfig = {
32
+ /** Access token de organização Expo (EAS) — opcional para apps standalone sem EAS. */
33
+ readonly accessToken?: string;
34
+ /** Injeção para teste; produção usa o `fetch` global. */
35
+ readonly fetchImpl?: typeof fetch;
36
+ };
37
+ /**
38
+ * Envio em lote — usado internamente por `send()` (lote de 1) e exportado para o `notification-module`
39
+ * poder despachar várias entregas na mesma janela de dispatch sem uma chamada HTTP por token.
40
+ */
41
+ declare function sendExpoPushBatch(messages: readonly ExpoPushMessage[], config?: ExpoPushProviderConfig): Promise<DeliveryAttemptResult[]>;
42
+ declare function createExpoPushProvider(config?: ExpoPushProviderConfig): PushDriverPort;
43
+
44
+ /**
45
+ * Copyright (c) 2026 Ada Technology. MIT License.
46
+ */
47
+ /**
48
+ * Forma mínima que o `admin.messaging()` do `firebase-admin` já satisfaz. Declarada por
49
+ * estrutura — e não importada do pacote — para que os testes injetem um dublê sem carregar o SDK
50
+ * real, e para o provider não amarrar a versão exata do `firebase-admin` do consumidor.
51
+ */
52
+ type FcmMessage = {
53
+ readonly token: string;
54
+ readonly notification: {
55
+ readonly title: string;
56
+ readonly body: string;
57
+ };
58
+ readonly data?: Readonly<Record<string, string>>;
59
+ readonly android?: {
60
+ readonly notification?: {
61
+ readonly notificationCount?: number;
62
+ };
63
+ };
64
+ readonly apns?: {
65
+ readonly payload: {
66
+ readonly aps: {
67
+ readonly badge?: number;
68
+ };
69
+ };
70
+ };
71
+ /** Presente só quando o token é de web push — o mesmo `send()` atende os três destinos. */
72
+ readonly webpush?: {
73
+ readonly notification?: {
74
+ readonly title?: string;
75
+ readonly body?: string;
76
+ };
77
+ };
78
+ };
79
+ type FcmError = {
80
+ readonly code: string;
81
+ readonly message: string;
82
+ };
83
+ type FcmMessagingClient = {
84
+ send(message: FcmMessage): Promise<string>;
85
+ };
86
+ declare function isFcmError(error: unknown): error is FcmError;
87
+
88
+ /**
89
+ * Copyright (c) 2026 Ada Technology. MIT License.
90
+ */
91
+
92
+ type FcmPushProviderConfig = {
93
+ /** Conteúdo do JSON de credencial de serviço (nunca um caminho de arquivo — evita I/O no boot). */
94
+ readonly serviceAccountJson?: string;
95
+ /** Nome do app do firebase-admin; só relevante se o processo hospeda mais de um. */
96
+ readonly appName?: string;
97
+ /** Injeção de teste — presente, o `firebase-admin` real nunca é importado. */
98
+ readonly messagingClient?: FcmMessagingClient;
99
+ };
100
+ declare function createFcmPushProvider(config?: FcmPushProviderConfig): PushDriverPort;
101
+
102
+ /**
103
+ * Copyright (c) 2026 Ada Technology. MIT License.
104
+ */
105
+
106
+ type CreatePushProviderParams = ({
107
+ readonly driver: typeof PUSH_DRIVER.EXPO;
108
+ } & ExpoPushProviderConfig) | ({
109
+ readonly driver: typeof PUSH_DRIVER.FCM;
110
+ } & FcmPushProviderConfig);
111
+ declare function createPushProvider(params: CreatePushProviderParams): PushDriverPort;
112
+
113
+ export { type CreatePushProviderParams, type ExpoPushMessage, type ExpoPushProviderConfig, type ExpoPushResponse, type ExpoPushTicket, type FcmError, type FcmMessage, type FcmMessagingClient, type FcmPushProviderConfig, createExpoPushProvider, createFcmPushProvider, createPushProvider, isFcmError, sendExpoPushBatch };
package/dist/index.js ADDED
@@ -0,0 +1,228 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/ExpoPushProvider.ts
5
+ import { PUSH_DRIVER } from "@adatechnology/notification-contracts";
6
+ var EXPO_PUSH_URL = "https://exp.host/--/api/v2/push/send";
7
+ var EXPO_PUSH_CHUNK_SIZE = 100;
8
+ function chunkArray(items, size) {
9
+ const chunks = [];
10
+ for (let offset = 0; offset < items.length; offset += size) {
11
+ chunks.push(items.slice(offset, offset + size));
12
+ }
13
+ return chunks;
14
+ }
15
+ __name(chunkArray, "chunkArray");
16
+ function classifyExpoTicket(ticket) {
17
+ if (ticket.status === "ok") return {
18
+ outcome: "sent",
19
+ providerMessageId: ticket.id
20
+ };
21
+ const errorCode = ticket.details?.error ?? "unknown";
22
+ if (errorCode === "DeviceNotRegistered") return {
23
+ outcome: "invalid_target",
24
+ errorCode
25
+ };
26
+ if (errorCode === "MessageRateExceeded") return {
27
+ outcome: "retriable",
28
+ errorCode
29
+ };
30
+ return {
31
+ outcome: "permanent",
32
+ errorCode
33
+ };
34
+ }
35
+ __name(classifyExpoTicket, "classifyExpoTicket");
36
+ function classifyHttpStatus(status) {
37
+ if (status === 429 || status >= 500) return {
38
+ outcome: "retriable",
39
+ errorCode: `http_${status}`
40
+ };
41
+ return {
42
+ outcome: "permanent",
43
+ errorCode: `http_${status}`
44
+ };
45
+ }
46
+ __name(classifyHttpStatus, "classifyHttpStatus");
47
+ async function sendExpoPushChunk(messages, config) {
48
+ const fetchImpl = config.fetchImpl ?? fetch;
49
+ const headers = {
50
+ Accept: "application/json",
51
+ "Content-Type": "application/json"
52
+ };
53
+ if (config.accessToken) headers.Authorization = `Bearer ${config.accessToken}`;
54
+ const response = await fetchImpl(EXPO_PUSH_URL, {
55
+ method: "POST",
56
+ headers,
57
+ body: JSON.stringify(messages)
58
+ });
59
+ if (!response.ok) {
60
+ const outcome = classifyHttpStatus(response.status);
61
+ return messages.map(() => outcome);
62
+ }
63
+ const payload = await response.json();
64
+ return payload.data.map(classifyExpoTicket);
65
+ }
66
+ __name(sendExpoPushChunk, "sendExpoPushChunk");
67
+ async function sendExpoPushBatch(messages, config = {}) {
68
+ const chunks = chunkArray(messages, EXPO_PUSH_CHUNK_SIZE);
69
+ const chunkResults = await Promise.all(chunks.map((chunk) => sendExpoPushChunk(chunk, config)));
70
+ return chunkResults.flat();
71
+ }
72
+ __name(sendExpoPushBatch, "sendExpoPushBatch");
73
+ function createExpoPushProvider(config = {}) {
74
+ return {
75
+ driver: PUSH_DRIVER.EXPO,
76
+ async send(params) {
77
+ const message = {
78
+ to: params.token,
79
+ title: params.title,
80
+ body: params.body,
81
+ data: params.data,
82
+ badge: params.badge
83
+ };
84
+ const [result] = await sendExpoPushBatch([
85
+ message
86
+ ], config);
87
+ return result;
88
+ }
89
+ };
90
+ }
91
+ __name(createExpoPushProvider, "createExpoPushProvider");
92
+
93
+ // src/FcmPushProvider.ts
94
+ import { ConfigMissingError, DEVICE_PLATFORM, PUSH_DRIVER as PUSH_DRIVER2 } from "@adatechnology/notification-contracts";
95
+
96
+ // src/FcmMessagingClient.ts
97
+ function isFcmError(error) {
98
+ return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string";
99
+ }
100
+ __name(isFcmError, "isFcmError");
101
+
102
+ // src/FcmPushProvider.ts
103
+ var INVALID_TARGET_CODES = /* @__PURE__ */ new Set([
104
+ "messaging/registration-token-not-registered",
105
+ "messaging/invalid-registration-token"
106
+ ]);
107
+ var RETRIABLE_CODES = /* @__PURE__ */ new Set([
108
+ "messaging/message-rate-exceeded",
109
+ "messaging/device-message-rate-exceeded",
110
+ "messaging/quota-exceeded",
111
+ "messaging/unavailable",
112
+ "messaging/internal-error"
113
+ ]);
114
+ function classifyFcmError(error) {
115
+ if (!isFcmError(error)) return {
116
+ outcome: "retriable",
117
+ errorCode: "unknown"
118
+ };
119
+ if (INVALID_TARGET_CODES.has(error.code)) return {
120
+ outcome: "invalid_target",
121
+ errorCode: error.code
122
+ };
123
+ if (RETRIABLE_CODES.has(error.code)) return {
124
+ outcome: "retriable",
125
+ errorCode: error.code
126
+ };
127
+ return {
128
+ outcome: "permanent",
129
+ errorCode: error.code
130
+ };
131
+ }
132
+ __name(classifyFcmError, "classifyFcmError");
133
+ function buildFcmMessage(params) {
134
+ const base = {
135
+ token: params.token,
136
+ notification: {
137
+ title: params.title,
138
+ body: params.body
139
+ },
140
+ data: params.data
141
+ };
142
+ if (params.platform === DEVICE_PLATFORM.WEB) {
143
+ return {
144
+ ...base,
145
+ webpush: {
146
+ notification: {
147
+ title: params.title,
148
+ body: params.body
149
+ }
150
+ }
151
+ };
152
+ }
153
+ if (params.platform === DEVICE_PLATFORM.IOS) {
154
+ return {
155
+ ...base,
156
+ apns: {
157
+ payload: {
158
+ aps: {
159
+ badge: params.badge
160
+ }
161
+ }
162
+ }
163
+ };
164
+ }
165
+ return params.badge === void 0 ? base : {
166
+ ...base,
167
+ android: {
168
+ notification: {
169
+ notificationCount: params.badge
170
+ }
171
+ }
172
+ };
173
+ }
174
+ __name(buildFcmMessage, "buildFcmMessage");
175
+ async function initFirebaseMessaging(config) {
176
+ if (!config.serviceAccountJson) throw new ConfigMissingError("serviceAccountJson");
177
+ const admin = await import("firebase-admin");
178
+ const appName = config.appName ?? "adatechnology-notification-push";
179
+ const existingApp = admin.apps.find((app2) => app2?.name === appName);
180
+ const app = existingApp ?? admin.initializeApp({
181
+ credential: admin.credential.cert(JSON.parse(config.serviceAccountJson))
182
+ }, appName);
183
+ return admin.messaging(app);
184
+ }
185
+ __name(initFirebaseMessaging, "initFirebaseMessaging");
186
+ function createFcmPushProvider(config = {}) {
187
+ let clientPromise;
188
+ function resolveClient() {
189
+ if (config.messagingClient) return Promise.resolve(config.messagingClient);
190
+ clientPromise ??= initFirebaseMessaging(config);
191
+ return clientPromise;
192
+ }
193
+ __name(resolveClient, "resolveClient");
194
+ return {
195
+ driver: PUSH_DRIVER2.FCM,
196
+ async send(params) {
197
+ const client = await resolveClient();
198
+ try {
199
+ const providerMessageId = await client.send(buildFcmMessage(params));
200
+ return {
201
+ outcome: "sent",
202
+ providerMessageId
203
+ };
204
+ } catch (error) {
205
+ return classifyFcmError(error);
206
+ }
207
+ }
208
+ };
209
+ }
210
+ __name(createFcmPushProvider, "createFcmPushProvider");
211
+
212
+ // src/PushProviderFactory.ts
213
+ import { PUSH_DRIVER as PUSH_DRIVER3 } from "@adatechnology/notification-contracts";
214
+ function createPushProvider(params) {
215
+ if (params.driver === PUSH_DRIVER3.EXPO) return createExpoPushProvider(params);
216
+ if (params.driver === PUSH_DRIVER3.FCM) return createFcmPushProvider(params);
217
+ const _exhaustive = params;
218
+ throw new Error(`Driver de push desconhecido: ${String(_exhaustive.driver)}`);
219
+ }
220
+ __name(createPushProvider, "createPushProvider");
221
+ export {
222
+ createExpoPushProvider,
223
+ createFcmPushProvider,
224
+ createPushProvider,
225
+ isFcmError,
226
+ sendExpoPushBatch
227
+ };
228
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ExpoPushProvider.ts","../src/FcmPushProvider.ts","../src/FcmMessagingClient.ts","../src/PushProviderFactory.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { PUSH_DRIVER } from '@adatechnology/notification-contracts'\nimport type { DeliveryAttemptResult, PushDriverPort, SendPushParams } from '@adatechnology/notification-contracts'\n\nimport type { ExpoPushMessage, ExpoPushResponse, ExpoPushTicket } from './expoTypes'\n\nconst EXPO_PUSH_URL = 'https://exp.host/--/api/v2/push/send'\n\n// Limite documentado da API — enviar mais que isso na mesma chamada é rejeitado pela Expo.\nconst EXPO_PUSH_CHUNK_SIZE = 100\n\nexport type ExpoPushProviderConfig = {\n /** Access token de organização Expo (EAS) — opcional para apps standalone sem EAS. */\n readonly accessToken?: string\n /** Injeção para teste; produção usa o `fetch` global. */\n readonly fetchImpl?: typeof fetch\n}\n\nfunction chunkArray<T>(items: readonly T[], size: number): T[][] {\n const chunks: T[][] = []\n for (let offset = 0; offset < items.length; offset += size) {\n chunks.push(items.slice(offset, offset + size) as T[])\n }\n return chunks\n}\n\n// Ticket de erro documentado pela Expo — \"apaga o token\" é sempre DeviceNotRegistered.\nfunction classifyExpoTicket(ticket: ExpoPushTicket): DeliveryAttemptResult {\n if (ticket.status === 'ok') return { outcome: 'sent', providerMessageId: ticket.id }\n\n const errorCode = ticket.details?.error ?? 'unknown'\n if (errorCode === 'DeviceNotRegistered') return { outcome: 'invalid_target', errorCode }\n if (errorCode === 'MessageRateExceeded') return { outcome: 'retriable', errorCode }\n // MessageTooBig, InvalidCredentials e qualquer código novo: tratar como definitivo é mais seguro\n // que retry silencioso — o host vê o erro no primeiro delivery em vez de gastar 5 tentativas.\n return { outcome: 'permanent', errorCode }\n}\n\nfunction classifyHttpStatus(status: number): DeliveryAttemptResult {\n if (status === 429 || status >= 500) return { outcome: 'retriable', errorCode: `http_${status}` }\n return { outcome: 'permanent', errorCode: `http_${status}` }\n}\n\nasync function sendExpoPushChunk(\n messages: readonly ExpoPushMessage[],\n config: ExpoPushProviderConfig,\n): Promise<DeliveryAttemptResult[]> {\n const fetchImpl = config.fetchImpl ?? fetch\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n }\n if (config.accessToken) headers.Authorization = `Bearer ${config.accessToken}`\n\n const response = await fetchImpl(EXPO_PUSH_URL, {\n method: 'POST',\n headers,\n body: JSON.stringify(messages),\n })\n\n if (!response.ok) {\n const outcome = classifyHttpStatus(response.status)\n return messages.map(() => outcome)\n }\n\n const payload = (await response.json()) as ExpoPushResponse\n return payload.data.map(classifyExpoTicket)\n}\n\n/**\n * Envio em lote — usado internamente por `send()` (lote de 1) e exportado para o `notification-module`\n * poder despachar várias entregas na mesma janela de dispatch sem uma chamada HTTP por token.\n */\nexport async function sendExpoPushBatch(\n messages: readonly ExpoPushMessage[],\n config: ExpoPushProviderConfig = {},\n): Promise<DeliveryAttemptResult[]> {\n const chunks = chunkArray(messages, EXPO_PUSH_CHUNK_SIZE)\n const chunkResults = await Promise.all(chunks.map((chunk) => sendExpoPushChunk(chunk, config)))\n return chunkResults.flat()\n}\n\nexport function createExpoPushProvider(config: ExpoPushProviderConfig = {}): PushDriverPort {\n return {\n driver: PUSH_DRIVER.EXPO,\n async send(params: SendPushParams): Promise<DeliveryAttemptResult> {\n const message: ExpoPushMessage = {\n to: params.token,\n title: params.title,\n body: params.body,\n data: params.data,\n badge: params.badge,\n }\n\n const [result] = await sendExpoPushBatch([message], config)\n return result\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { ConfigMissingError, DEVICE_PLATFORM, PUSH_DRIVER } from '@adatechnology/notification-contracts'\nimport type { DeliveryAttemptResult, PushDriverPort, SendPushParams } from '@adatechnology/notification-contracts'\n\nimport { isFcmError, type FcmMessage, type FcmMessagingClient } from './FcmMessagingClient'\n\nexport type FcmPushProviderConfig = {\n /** Conteúdo do JSON de credencial de serviço (nunca um caminho de arquivo — evita I/O no boot). */\n readonly serviceAccountJson?: string\n /** Nome do app do firebase-admin; só relevante se o processo hospeda mais de um. */\n readonly appName?: string\n /** Injeção de teste — presente, o `firebase-admin` real nunca é importado. */\n readonly messagingClient?: FcmMessagingClient\n}\n\n// admin.messaging(): FirebaseMessagingError.code documentado pelo SDK.\nconst INVALID_TARGET_CODES = new Set([\n 'messaging/registration-token-not-registered',\n 'messaging/invalid-registration-token',\n])\nconst RETRIABLE_CODES = new Set([\n 'messaging/message-rate-exceeded',\n 'messaging/device-message-rate-exceeded',\n 'messaging/quota-exceeded',\n 'messaging/unavailable',\n 'messaging/internal-error',\n])\n\nfunction classifyFcmError(error: unknown): DeliveryAttemptResult {\n if (!isFcmError(error)) return { outcome: 'retriable', errorCode: 'unknown' }\n if (INVALID_TARGET_CODES.has(error.code)) return { outcome: 'invalid_target', errorCode: error.code }\n if (RETRIABLE_CODES.has(error.code)) return { outcome: 'retriable', errorCode: error.code }\n return { outcome: 'permanent', errorCode: error.code }\n}\n\n/**\n * Web push usa o mesmo `messaging().send()` do FCM — só o bloco `webpush` muda. É o que permite\n * validar o canal push inteiro pelo PWA do quickcart, sem depender de um app mobile.\n */\nfunction buildFcmMessage(params: SendPushParams): FcmMessage {\n const base = {\n token: params.token,\n notification: { title: params.title, body: params.body },\n data: params.data,\n }\n\n if (params.platform === DEVICE_PLATFORM.WEB) {\n return { ...base, webpush: { notification: { title: params.title, body: params.body } } }\n }\n if (params.platform === DEVICE_PLATFORM.IOS) {\n return { ...base, apns: { payload: { aps: { badge: params.badge } } } }\n }\n return params.badge === undefined ? base : { ...base, android: { notification: { notificationCount: params.badge } } }\n}\n\n// firebase-admin (~40 MB) só é importado quando o driver FCM é de fato usado sem cliente injetado\n// — quem só usa Expo, ou quem testa com dublê, nunca carrega o SDK.\nasync function initFirebaseMessaging(config: FcmPushProviderConfig): Promise<FcmMessagingClient> {\n if (!config.serviceAccountJson) throw new ConfigMissingError('serviceAccountJson')\n\n const admin = await import('firebase-admin')\n const appName = config.appName ?? 'adatechnology-notification-push'\n const existingApp = admin.apps.find((app) => app?.name === appName)\n const app =\n existingApp ??\n admin.initializeApp({ credential: admin.credential.cert(JSON.parse(config.serviceAccountJson)) }, appName)\n\n return admin.messaging(app)\n}\n\nexport function createFcmPushProvider(config: FcmPushProviderConfig = {}): PushDriverPort {\n let clientPromise: Promise<FcmMessagingClient> | undefined\n\n function resolveClient(): Promise<FcmMessagingClient> {\n if (config.messagingClient) return Promise.resolve(config.messagingClient)\n clientPromise ??= initFirebaseMessaging(config)\n return clientPromise\n }\n\n return {\n driver: PUSH_DRIVER.FCM,\n async send(params: SendPushParams): Promise<DeliveryAttemptResult> {\n const client = await resolveClient()\n try {\n const providerMessageId = await client.send(buildFcmMessage(params))\n return { outcome: 'sent', providerMessageId }\n } catch (error) {\n return classifyFcmError(error)\n }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\n/**\n * Forma mínima que o `admin.messaging()` do `firebase-admin` já satisfaz. Declarada por\n * estrutura — e não importada do pacote — para que os testes injetem um dublê sem carregar o SDK\n * real, e para o provider não amarrar a versão exata do `firebase-admin` do consumidor.\n */\nexport type FcmMessage = {\n readonly token: string\n readonly notification: { readonly title: string; readonly body: string }\n readonly data?: Readonly<Record<string, string>>\n readonly android?: { readonly notification?: { readonly notificationCount?: number } }\n readonly apns?: { readonly payload: { readonly aps: { readonly badge?: number } } }\n /** Presente só quando o token é de web push — o mesmo `send()` atende os três destinos. */\n readonly webpush?: { readonly notification?: { readonly title?: string; readonly body?: string } }\n}\n\nexport type FcmError = {\n readonly code: string\n readonly message: string\n}\n\nexport type FcmMessagingClient = {\n send(message: FcmMessage): Promise<string>\n}\n\nexport function isFcmError(error: unknown): error is FcmError {\n return typeof error === 'object' && error !== null && 'code' in error && typeof (error as FcmError).code === 'string'\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { PUSH_DRIVER } from '@adatechnology/notification-contracts'\nimport type { PushDriverPort } from '@adatechnology/notification-contracts'\n\nimport { createExpoPushProvider, type ExpoPushProviderConfig } from './ExpoPushProvider'\nimport { createFcmPushProvider, type FcmPushProviderConfig } from './FcmPushProvider'\n\nexport type CreatePushProviderParams =\n | ({ readonly driver: typeof PUSH_DRIVER.EXPO } & ExpoPushProviderConfig)\n | ({ readonly driver: typeof PUSH_DRIVER.FCM } & FcmPushProviderConfig)\n\nexport function createPushProvider(params: CreatePushProviderParams): PushDriverPort {\n if (params.driver === PUSH_DRIVER.EXPO) return createExpoPushProvider(params)\n if (params.driver === PUSH_DRIVER.FCM) return createFcmPushProvider(params)\n\n const _exhaustive: never = params\n throw new Error(`Driver de push desconhecido: ${String((_exhaustive as { driver?: unknown }).driver)}`)\n}\n"],"mappings":";;;;AAIA,SAASA,mBAAmB;AAK5B,IAAMC,gBAAgB;AAGtB,IAAMC,uBAAuB;AAS7B,SAASC,WAAcC,OAAqBC,MAAY;AACtD,QAAMC,SAAgB,CAAA;AACtB,WAASC,SAAS,GAAGA,SAASH,MAAMI,QAAQD,UAAUF,MAAM;AAC1DC,WAAOG,KAAKL,MAAMM,MAAMH,QAAQA,SAASF,IAAAA,CAAAA;EAC3C;AACA,SAAOC;AACT;AANSH;AAST,SAASQ,mBAAmBC,QAAsB;AAChD,MAAIA,OAAOC,WAAW,KAAM,QAAO;IAAEC,SAAS;IAAQC,mBAAmBH,OAAOI;EAAG;AAEnF,QAAMC,YAAYL,OAAOM,SAASC,SAAS;AAC3C,MAAIF,cAAc,sBAAuB,QAAO;IAAEH,SAAS;IAAkBG;EAAU;AACvF,MAAIA,cAAc,sBAAuB,QAAO;IAAEH,SAAS;IAAaG;EAAU;AAGlF,SAAO;IAAEH,SAAS;IAAaG;EAAU;AAC3C;AATSN;AAWT,SAASS,mBAAmBP,QAAc;AACxC,MAAIA,WAAW,OAAOA,UAAU,IAAK,QAAO;IAAEC,SAAS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AAIQ,MAAM,gCAAgCC,OAAQF,YAAqCN,MAAM,CAAA,EAAG;AACxG;AANgBF;","names":["PUSH_DRIVER","EXPO_PUSH_URL","EXPO_PUSH_CHUNK_SIZE","chunkArray","items","size","chunks","offset","length","push","slice","classifyExpoTicket","ticket","status","outcome","providerMessageId","id","errorCode","details","error","classifyHttpStatus","sendExpoPushChunk","messages","config","fetchImpl","fetch","headers","Accept","accessToken","Authorization","response","method","body","JSON","stringify","ok","map","payload","json","data","sendExpoPushBatch","chunkResults","Promise","all","chunk","flat","createExpoPushProvider","driver","PUSH_DRIVER","EXPO","send","params","message","to","token","title","badge","result","ConfigMissingError","DEVICE_PLATFORM","PUSH_DRIVER","isFcmError","error","code","INVALID_TARGET_CODES","Set","RETRIABLE_CODES","classifyFcmError","error","isFcmError","outcome","errorCode","has","code","buildFcmMessage","params","base","token","notification","title","body","data","platform","DEVICE_PLATFORM","WEB","webpush","IOS","apns","payload","aps","badge","undefined","android","notificationCount","initFirebaseMessaging","config","serviceAccountJson","ConfigMissingError","admin","appName","existingApp","apps","find","app","name","initializeApp","credential","cert","JSON","parse","messaging","createFcmPushProvider","clientPromise","resolveClient","messagingClient","Promise","resolve","driver","PUSH_DRIVER","FCM","send","client","providerMessageId","PUSH_DRIVER","createPushProvider","params","driver","PUSH_DRIVER","EXPO","createExpoPushProvider","FCM","createFcmPushProvider","_exhaustive","Error","String"]}
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@adatechnology/push-provider",
3
+ "version": "0.1.0-rc.1",
4
+ "description": "Stateless push notification providers (Expo, FCM) behind a single port — part of the notification trio",
5
+ "license": "MIT",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "type": "module",
10
+ "main": "dist/index.js",
11
+ "types": "dist/index.d.ts",
12
+ "sideEffects": false,
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js",
17
+ "require": "./dist/index.cjs"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "dependencies": {
24
+ "@adatechnology/notification-contracts": "0.1.0-rc.1"
25
+ },
26
+ "peerDependencies": {
27
+ "firebase-admin": ">=12 <14"
28
+ },
29
+ "peerDependenciesMeta": {
30
+ "firebase-admin": {
31
+ "optional": true
32
+ }
33
+ },
34
+ "devDependencies": {
35
+ "@types/bun": "1.3.14",
36
+ "firebase-admin": "^13.7.0",
37
+ "tsup": "^8.5.1",
38
+ "typescript": "^5.7.3"
39
+ },
40
+ "scripts": {
41
+ "build": "tsup",
42
+ "check": "tsc -p tsconfig.json --noEmit",
43
+ "test": "bun test"
44
+ }
45
+ }