@adatechnology/notification-client 0.4.0 → 0.5.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.
- package/dist/index.cjs +7 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -193,6 +193,13 @@ function createNotificationClient(config) {
|
|
|
193
193
|
if (!payload?.data) throw new Error("notification-client: restoreDefault n\xE3o devolveu o template");
|
|
194
194
|
return payload.data;
|
|
195
195
|
},
|
|
196
|
+
async listTemplateDefinitions() {
|
|
197
|
+
const payload = await request({
|
|
198
|
+
method: "GET",
|
|
199
|
+
path: "/notification-template-definitions"
|
|
200
|
+
});
|
|
201
|
+
return payload?.data ?? [];
|
|
202
|
+
},
|
|
196
203
|
async listTemplateVariables() {
|
|
197
204
|
const payload = await request({
|
|
198
205
|
method: "GET",
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/httpClient.ts","../src/deviceRegistration.ts","../src/streamSubscription.ts","../src/webPush.ts","../src/expoPush.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nexport { createNotificationClient } from './httpClient'\nexport type {\n NotificationClient,\n NotificationClientConfig,\n ListNotificationsOptions,\n ListNotificationsPage,\n RegisterDeviceInput,\n NotificationApiError,\n} from './httpClient'\n\nexport { createDeviceRegistration } from './deviceRegistration'\nexport type {\n DeviceRegistrationConfig,\n DeviceRegistrationHandle,\n DeviceRegistrationStorage,\n RegisterOptions,\n} from './deviceRegistration'\n\nexport { subscribeToNotificationStream } from './streamSubscription'\nexport type {\n NotificationStreamEvent,\n NotificationStreamSubscription,\n SubscribeToNotificationStreamParams,\n} from './streamSubscription'\n\nexport {\n isWebPushSupported,\n urlBase64ToUint8Array,\n arrayBufferToBase64Url,\n subscribeWebPush,\n unsubscribeWebPush,\n getWebPushSubscription,\n getStandardWebPushServiceWorkerScript,\n} from './webPush'\nexport type { SubscribeWebPushOptions } from './webPush'\n\nexport { getExpoPushToken, createExpoPushRegistration } from './expoPush'\nexport type {\n ExpoNotificationsModule,\n ExpoPermissionResponse,\n ExpoPushTokenResult,\n GetExpoPushTokenOptions,\n CreateExpoPushRegistrationConfig,\n} from './expoPush'\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Cliente HTTP tipado pelas 13 rotas do módulo. **Isomórfico e sem DOM**: `fetch` é injetável e o\n * default é o global — é o que permite o mesmo pacote rodar no React Native do cawme e no PWA do\n * quickcart, sem o `-ui` (que tem `react-dom` e Tailwind) entrar no bundle mobile.\n */\n\nimport type {\n DeviceRegistration,\n NotificationPreference,\n NotificationSummary,\n NotificationTemplate,\n NotificationCategoryPolicy,\n TemplateVariableCatalog,\n UpsertTemplateBody,\n WebPushSubscription,\n SendPushDirectBody,\n SendPushDirectResult,\n BroadcastPushBody,\n BroadcastPushResult,\n} from '@adatechnology/notification-contracts'\n\nexport type NotificationClientConfig = {\n /** Base do host, sem barra final: `https://api.exemplo.com/v1`. */\n readonly baseUrl: string\n /**\n * Devolve o header de autorização a cada chamada — função, não string, porque o token do host\n * rotaciona e capturar o valor no boot deixaria o cliente com uma credencial vencida.\n */\n readonly getAuthHeaders?: () => Promise<Record<string, string>> | Record<string, string>\n readonly fetchImpl?: typeof fetch\n}\n\nexport type ListNotificationsOptions = {\n readonly category?: string\n readonly read?: boolean\n readonly cursor?: string\n readonly perPage?: number\n}\n\nexport type ListNotificationsPage = {\n readonly data: readonly NotificationSummary[]\n readonly nextCursor?: string\n readonly unreadCount: number\n}\n\nexport type RegisterDeviceInput = {\n readonly platform: 'ios' | 'android' | 'web'\n readonly driver: 'expo' | 'fcm'\n readonly token: string\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n}\n\nexport type NotificationApiError = Error & {\n readonly status: number\n readonly code: string\n readonly issues?: readonly { path: string; message: string }[]\n}\n\nfunction buildApiError(status: number, payload: unknown): NotificationApiError {\n const envelope = payload as {\n error?: { code?: string; message?: string; issues?: { path: string; message: string }[] }\n }\n const error = new Error(envelope?.error?.message ?? `Falha na requisição (${status}).`) as NotificationApiError\n return Object.assign(error, {\n status,\n code: envelope?.error?.code ?? 'NOTIFICATION_UNKNOWN_ERROR',\n issues: envelope?.error?.issues,\n })\n}\n\nexport type NotificationClient = {\n listNotifications(options?: ListNotificationsOptions): Promise<ListNotificationsPage>\n countUnread(): Promise<number>\n markAsRead(id: string): Promise<NotificationSummary>\n markAllAsRead(): Promise<number>\n deleteNotification(id: string): Promise<void>\n registerDevice(input: RegisterDeviceInput): Promise<DeviceRegistration>\n unregisterDevice(id: string): Promise<void>\n getPreferences(): Promise<readonly NotificationPreference[]>\n updatePreferences(preferences: readonly NotificationPreference[]): Promise<readonly NotificationPreference[]>\n /** O teto de canais da empresa por categoria — acima da preferência de quem recebe. */\n getCategoryPolicies(): Promise<readonly NotificationCategoryPolicy[]>\n /** Substitui a política das categorias enviadas; as demais ficam intactas. */\n updateCategoryPolicies(\n policies: readonly NotificationCategoryPolicy[],\n ): Promise<readonly NotificationCategoryPolicy[]>\n listTemplates(): Promise<readonly NotificationTemplate[]>\n /**\n * Cria uma VERSÃO nova do template, não edita a atual.\n *\n * O módulo versiona por `key`+`channel`+`locale`: a versão anterior fica legível para auditoria, e\n * a leitura só devolve a ativa mais alta. Então \"editar a copy\" e \"reverter\" são a mesma operação\n * — o que a tela de configuração precisa para alguém corrigir um texto sem medo.\n */\n upsertTemplate(input: UpsertTemplateBody): Promise<NotificationTemplate>\n /**\n * \"Remover\" é desativar: o servidor derruba todas as versões ativas da identidade e mantém as\n * linhas, porque entrega já enviada precisa continuar auditável com o texto que usou.\n */\n deactivateTemplate(id: string): Promise<void>\n /**\n * \"Restaurar padrão\": o servidor grava uma versão nova com o conteúdo embutido do modelo padrão\n * (`notification.standard-email`). 400 se o id não é dele; 409 se a restauração é recusada.\n */\n restoreDefault(id: string): Promise<NotificationTemplate>\n /** O catálogo de variáveis por chave — é o que a tela mostra como lista clicável. */\n listTemplateVariables(): Promise<TemplateVariableCatalog>\n /** Base + headers, para o assinante de SSE reaproveitar a mesma configuração. */\n resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }>\n /** Obtém a chave pública VAPID do servidor para inscrição Web Push no navegador */\n getVapidPublicKey(): Promise<string>\n /** Dispara uma notificação push direta (para token, user ou subscription) */\n sendPush(input: SendPushDirectBody): Promise<SendPushDirectResult>\n /** Dispara push em broadcast por tópico ou filtro */\n broadcastPush(input: BroadcastPushBody): Promise<BroadcastPushResult>\n /** Registra uma assinatura Web Push nativa (PWA) no backend */\n registerWebPush(\n subscription: WebPushSubscription,\n options?: { readonly appVersion?: string; readonly locale?: string; readonly timezone?: string },\n ): Promise<DeviceRegistration>\n}\n\nexport function createNotificationClient(config: NotificationClientConfig): NotificationClient {\n const fetchImpl = config.fetchImpl ?? fetch\n const baseUrl = config.baseUrl.endsWith('/') ? config.baseUrl.slice(0, -1) : config.baseUrl\n\n async function request<TResponse>(params: {\n method: string\n path: string\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown\n }): Promise<TResponse | undefined> {\n const fullPath = `${baseUrl}${params.path}`\n const isAbsolute = fullPath.startsWith('http://') || fullPath.startsWith('https://')\n const fallbackBase =\n typeof window !== 'undefined' && window.location?.origin ? window.location.origin : 'http://localhost'\n const url = new URL(fullPath, isAbsolute ? undefined : fallbackBase)\n for (const [key, value] of Object.entries(params.query ?? {})) {\n if (value !== undefined) url.searchParams.set(key, String(value))\n }\n\n const authHeaders = (await config.getAuthHeaders?.()) ?? {}\n const finalUrl = isAbsolute || typeof window !== 'undefined' ? url.toString() : `${url.pathname}${url.search}`\n const response = await fetchImpl(finalUrl, {\n method: params.method,\n headers: { ...(params.body === undefined ? {} : { 'Content-Type': 'application/json' }), ...authHeaders },\n body: params.body === undefined ? undefined : JSON.stringify(params.body),\n })\n\n if (response.status === 204) return undefined\n\n const text = await response.text()\n const payload: unknown = text === '' ? undefined : JSON.parse(text)\n if (!response.ok) throw buildApiError(response.status, payload)\n return payload as TResponse\n }\n\n return {\n async listNotifications(options): Promise<ListNotificationsPage> {\n const payload = await request<{\n data: NotificationSummary[]\n pagination: { nextCursor?: string }\n meta: { unreadCount: number }\n }>({\n method: 'GET',\n path: '/notifications',\n query: { category: options?.category, read: options?.read, cursor: options?.cursor, perPage: options?.perPage },\n })\n\n return {\n data: payload?.data ?? [],\n nextCursor: payload?.pagination.nextCursor,\n unreadCount: payload?.meta.unreadCount ?? 0,\n }\n },\n\n async countUnread(): Promise<number> {\n const payload = await request<{ data: { unreadCount: number } }>({\n method: 'GET',\n path: '/notifications/unread-count',\n })\n return payload?.data.unreadCount ?? 0\n },\n\n async markAsRead(id): Promise<NotificationSummary> {\n const payload = await request<{ data: NotificationSummary }>({\n method: 'PATCH',\n path: `/notifications/${encodeURIComponent(id)}/read`,\n })\n if (!payload) throw new Error('notification-client: resposta vazia em markAsRead')\n return payload.data\n },\n\n async markAllAsRead(): Promise<number> {\n const payload = await request<{ data: { updated: number } }>({ method: 'POST', path: '/notifications/read-all' })\n return payload?.data.updated ?? 0\n },\n\n async deleteNotification(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notifications/${encodeURIComponent(id)}` })\n },\n\n async registerDevice(input): Promise<DeviceRegistration> {\n const payload = await request<{ data: DeviceRegistration }>({\n method: 'POST',\n path: '/notification-devices',\n body: input,\n })\n if (!payload) throw new Error('notification-client: resposta vazia em registerDevice')\n return payload.data\n },\n\n async unregisterDevice(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notification-devices/${encodeURIComponent(id)}` })\n },\n\n async getPreferences(): Promise<readonly NotificationPreference[]> {\n const payload = await request<{ data: NotificationPreference[] }>({\n method: 'GET',\n path: '/notification-preferences',\n })\n return payload?.data ?? []\n },\n\n async updatePreferences(preferences): Promise<readonly NotificationPreference[]> {\n const payload = await request<{ data: NotificationPreference[] }>({\n method: 'PUT',\n path: '/notification-preferences',\n body: { preferences },\n })\n return payload?.data ?? []\n },\n\n async listTemplates(): Promise<readonly NotificationTemplate[]> {\n const payload = await request<{ data: NotificationTemplate[] }>({\n method: 'GET',\n path: '/notification-templates',\n })\n return payload?.data ?? []\n },\n\n async getCategoryPolicies(): Promise<readonly NotificationCategoryPolicy[]> {\n const payload = await request<{ data: NotificationCategoryPolicy[] }>({\n method: 'GET',\n path: '/notification-category-policies',\n })\n return payload?.data ?? []\n },\n\n async updateCategoryPolicies(policies): Promise<readonly NotificationCategoryPolicy[]> {\n const payload = await request<{ data: NotificationCategoryPolicy[] }>({\n method: 'PUT',\n path: '/notification-category-policies',\n body: { policies },\n })\n return payload?.data ?? []\n },\n\n async deactivateTemplate(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notification-templates/${encodeURIComponent(id)}` })\n },\n\n async restoreDefault(id): Promise<NotificationTemplate> {\n const payload = await request<{ data: NotificationTemplate }>({\n method: 'POST',\n path: `/notification-templates/${encodeURIComponent(id)}/restore-default`,\n })\n if (!payload?.data) throw new Error('notification-client: restoreDefault não devolveu o template')\n return payload.data\n },\n\n async listTemplateVariables(): Promise<TemplateVariableCatalog> {\n const payload = await request<{ data: TemplateVariableCatalog }>({\n method: 'GET',\n path: '/notification-template-variables',\n })\n return payload?.data ?? {}\n },\n\n async upsertTemplate(input: UpsertTemplateBody): Promise<NotificationTemplate> {\n const payload = await request<{ data: NotificationTemplate }>({\n method: 'POST',\n path: '/notification-templates',\n body: input,\n })\n // Sem fallback: a rota responde 201 com o template criado, e devolver `undefined as never`\n // aqui esconderia uma mudança de contrato até estourar na tela.\n if (!payload?.data) throw new Error('notification-client: upsertTemplate não devolveu o template')\n return payload.data\n },\n\n async resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }> {\n return { url: `${baseUrl}/notifications/stream`, headers: (await config.getAuthHeaders?.()) ?? {} }\n },\n\n async getVapidPublicKey(): Promise<string> {\n const payload = await request<{ data: { publicKey: string } }>({\n method: 'GET',\n path: '/push/vapid-public-key',\n })\n if (!payload?.data?.publicKey) throw new Error('notification-client: chave pública VAPID não retornada')\n return payload.data.publicKey\n },\n\n async sendPush(input: SendPushDirectBody): Promise<SendPushDirectResult> {\n const payload = await request<{ data: SendPushDirectResult }>({\n method: 'POST',\n path: '/push/send',\n body: input,\n })\n if (!payload?.data) throw new Error('notification-client: resposta vazia ao enviar push')\n return payload.data\n },\n\n async broadcastPush(input: BroadcastPushBody): Promise<BroadcastPushResult> {\n const payload = await request<{ data: BroadcastPushResult }>({\n method: 'POST',\n path: '/push/broadcast',\n body: input,\n })\n if (!payload?.data) throw new Error('notification-client: resposta vazia em broadcastPush')\n return payload.data\n },\n\n async registerWebPush(\n subscription: WebPushSubscription,\n options?: { readonly appVersion?: string; readonly locale?: string; readonly timezone?: string },\n ): Promise<DeviceRegistration> {\n const payload = await request<{ data: DeviceRegistration }>({\n method: 'POST',\n path: '/notification-devices',\n body: {\n platform: 'web',\n driver: 'webpush',\n token: JSON.stringify(subscription),\n appVersion: options?.appVersion,\n locale: options?.locale,\n timezone: options?.timezone,\n },\n })\n if (!payload?.data) throw new Error('notification-client: resposta vazia em registerWebPush')\n return payload.data\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Registro de dispositivo para push. **Não importa `expo-notifications` nem `firebase`**: recebe\n * `getToken` por injeção. É o que mantém o pacote isomórfico — o cawme passa o token do Expo, o\n * PWA do quickcart passa o do FCM web, e nenhum dos dois carrega o SDK do outro.\n */\n\nimport type { DeviceRegistration } from '@adatechnology/notification-contracts'\n\nimport type { NotificationClient, RegisterDeviceInput } from './httpClient'\n\nexport type DeviceRegistrationConfig = {\n readonly client: NotificationClient\n readonly driver: 'expo' | 'fcm'\n /** `undefined` = permissão negada ou indisponível; o registro é pulado sem erro. */\n getToken(): Promise<string | undefined>\n /** Persiste o id entre execuções, para o logout conseguir remover o device certo. */\n readonly storage?: DeviceRegistrationStorage\n}\n\n/** `AsyncStorage` do RN e `localStorage` do web satisfazem esta forma (via wrapper trivial). */\nexport type DeviceRegistrationStorage = {\n getItem(key: string): Promise<string | null> | string | null\n setItem(key: string, value: string): Promise<void> | void\n removeItem(key: string): Promise<void> | void\n}\n\nexport type RegisterOptions = {\n readonly platform: 'ios' | 'android' | 'web'\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n}\n\nexport type DeviceRegistrationHandle = {\n /** Idempotente: chamar de novo com o mesmo token reativa o registro em vez de duplicar. */\n register(options: RegisterOptions): Promise<DeviceRegistration | undefined>\n /** No logout — sem isto, o aparelho continuaria recebendo push do usuário anterior. */\n unregister(): Promise<void>\n}\n\nconst STORAGE_KEY = 'adatechnology:notification:device-id'\n\nexport function createDeviceRegistration(config: DeviceRegistrationConfig): DeviceRegistrationHandle {\n async function rememberDeviceId(deviceId: string): Promise<void> {\n await config.storage?.setItem(STORAGE_KEY, deviceId)\n }\n\n return {\n async register(options): Promise<DeviceRegistration | undefined> {\n const token = await config.getToken()\n // Permissão negada é o caminho normal, não erro: o usuário pode recusar push e o resto do\n // app continua funcionando (inbox e e-mail seguem).\n if (!token) return undefined\n\n const input: RegisterDeviceInput = {\n platform: options.platform,\n driver: config.driver,\n token,\n appVersion: options.appVersion,\n locale: options.locale,\n timezone: options.timezone,\n }\n\n const device = await config.client.registerDevice(input)\n await rememberDeviceId(device.id)\n return device\n },\n\n async unregister(): Promise<void> {\n const deviceId = await config.storage?.getItem(STORAGE_KEY)\n if (!deviceId) return\n\n await config.client.unregisterDevice(deviceId)\n await config.storage?.removeItem(STORAGE_KEY)\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Assinatura do SSE do inbox.\n *\n * **Não usa `EventSource`**, apesar de ser a API óbvia: `EventSource` não aceita headers, e a\n * autenticação do host é `Authorization: Bearer`. Passar token por query string violaria\n * `security.md` §Privacy (credencial em URL vaza em log de proxy e histórico). Além disso o React\n * Native não tem `EventSource` nativo. Ler o corpo por `fetch` + `ReadableStream` resolve os dois\n * de uma vez, e é o que roda igual no web e no RN moderno.\n */\n\nexport type NotificationStreamEvent = {\n readonly event: string\n readonly data: unknown\n}\n\nexport type SubscribeToNotificationStreamParams = {\n readonly url: string\n readonly headers: Record<string, string>\n readonly onEvent: (event: NotificationStreamEvent) => void\n readonly onError?: (error: Error) => void\n readonly fetchImpl?: typeof fetch\n /** Reconexão com backoff; `0` desliga (o chamador cuida). */\n readonly reconnectDelayMs?: number\n}\n\nexport type NotificationStreamSubscription = {\n close(): void\n}\n\nconst DEFAULT_RECONNECT_DELAY_MS = 3000\n\nfunction parseSseBlock(block: string): NotificationStreamEvent | undefined {\n let eventName = 'message'\n const dataLines: string[] = []\n\n for (const line of block.split('\\n')) {\n // Comentário SSE — é o heartbeat do servidor, e não deve virar evento no cliente.\n if (line.startsWith(':')) continue\n if (line.startsWith('event:')) eventName = line.slice('event:'.length).trim()\n if (line.startsWith('data:')) dataLines.push(line.slice('data:'.length).trim())\n }\n\n if (dataLines.length === 0) return undefined\n\n const raw = dataLines.join('\\n')\n try {\n return { event: eventName, data: JSON.parse(raw) }\n } catch {\n return { event: eventName, data: raw }\n }\n}\n\nexport function subscribeToNotificationStream(\n params: SubscribeToNotificationStreamParams,\n): NotificationStreamSubscription {\n const fetchImpl = params.fetchImpl ?? fetch\n const controller = new AbortController()\n let closed = false\n\n async function connect(): Promise<void> {\n const response = await fetchImpl(params.url, {\n headers: { ...params.headers, Accept: 'text/event-stream' },\n signal: controller.signal,\n })\n\n if (!response.ok || !response.body) throw new Error(`SSE falhou com status ${response.status}`)\n\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n\n for (;;) {\n const { value, done } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n // Eventos SSE são separados por linha em branco; o resto fica no buffer porque um chunk\n // de rede pode cortar um evento no meio.\n const blocks = buffer.split('\\n\\n')\n buffer = blocks.pop() ?? ''\n\n for (const block of blocks) {\n const event = parseSseBlock(block)\n if (event) params.onEvent(event)\n }\n }\n }\n\n async function runWithReconnect(): Promise<void> {\n const delay = params.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS\n\n while (!closed) {\n try {\n await connect()\n } catch (error) {\n if (closed) return\n params.onError?.(error instanceof Error ? error : new Error(String(error)))\n }\n\n // Conexão encerrada pelo servidor (deploy, timeout de proxy) é o caso comum — reconectar é\n // o comportamento certo, e sem `delay` viraria laço apertado contra um servidor caído.\n if (closed || delay === 0) return\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n }\n\n void runWithReconnect()\n\n return {\n close(): void {\n closed = true\n controller.abort()\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Helpers isomórficos para Web Push nativo (W3C Push API) em PWAs.\n * Não depende de Firebase nem de bibliotecas externas: funciona nativamente no Chrome,\n * Firefox, Edge e Safari (iOS 16.4+ e macOS).\n */\n\nimport type { WebPushSubscription } from '@adatechnology/notification-contracts'\n\nexport type SubscribeWebPushOptions = {\n readonly vapidPublicKey: string\n readonly serviceWorkerRegistration?: ServiceWorkerRegistration\n}\n\n/**\n * Converte chave pública VAPID em base64url para Uint8Array.\n * Exigido pelo navegador em `pushManager.subscribe({ applicationServerKey })`.\n */\nexport function urlBase64ToUint8Array(base64String: string): Uint8Array {\n const padding = '='.repeat((4 - (base64String.length % 4)) % 4)\n const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/')\n const rawData = atob(base64)\n const outputArray = new Uint8Array(rawData.length)\n\n for (let i = 0; i < rawData.length; ++i) {\n outputArray[i] = rawData.charCodeAt(i)\n }\n return outputArray\n}\n\nexport function arrayBufferToBase64Url(buffer: ArrayBufferLike | ArrayBuffer | null): string {\n if (!buffer) return ''\n const bytes = new Uint8Array(buffer as ArrayBuffer)\n let binary = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n binary += String.fromCharCode(bytes[i])\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n/**\n * Verifica se o ambiente de execução suporta Web Push nativo via Service Worker.\n */\nexport function isWebPushSupported(): boolean {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') return false\n return 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window\n}\n\n/**\n * Inscreve o navegador no Push Service nativo usando as chaves VAPID fornecidas.\n * Retorna `undefined` caso a permissão seja negada pelo usuário (caminho normal, sem lançar erro).\n */\nexport async function subscribeWebPush(options: SubscribeWebPushOptions): Promise<WebPushSubscription | undefined> {\n if (!isWebPushSupported()) return undefined\n\n if (Notification.permission === 'default') {\n const permission = await Notification.requestPermission()\n if (permission !== 'granted') return undefined\n } else if (Notification.permission !== 'granted') {\n return undefined\n }\n\n const registration = options.serviceWorkerRegistration ?? (await navigator.serviceWorker.ready)\n const applicationServerKey = urlBase64ToUint8Array(options.vapidPublicKey)\n\n let subscription = await registration.pushManager.getSubscription()\n if (!subscription) {\n subscription = await registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: applicationServerKey as unknown as BufferSource,\n })\n }\n\n const p256dh = arrayBufferToBase64Url(subscription.getKey('p256dh'))\n const auth = arrayBufferToBase64Url(subscription.getKey('auth'))\n\n return {\n endpoint: subscription.endpoint,\n keys: { p256dh, auth },\n expirationTime: subscription.expirationTime,\n }\n}\n\n/**\n * Remove a inscrição ativa de push no navegador.\n */\nexport async function unsubscribeWebPush(serviceWorkerRegistration?: ServiceWorkerRegistration): Promise<boolean> {\n if (!isWebPushSupported()) return false\n\n const registration = serviceWorkerRegistration ?? (await navigator.serviceWorker.ready)\n const subscription = await registration.pushManager.getSubscription()\n if (!subscription) return false\n\n return subscription.unsubscribe()\n}\n\n/**\n * Obtém a inscrição ativa de push no navegador se já existir.\n */\nexport async function getWebPushSubscription(\n serviceWorkerRegistration?: ServiceWorkerRegistration,\n): Promise<WebPushSubscription | undefined> {\n if (!isWebPushSupported()) return undefined\n\n const registration = serviceWorkerRegistration ?? (await navigator.serviceWorker.ready)\n const subscription = await registration.pushManager.getSubscription()\n if (!subscription) return undefined\n\n const p256dh = arrayBufferToBase64Url(subscription.getKey('p256dh'))\n const auth = arrayBufferToBase64Url(subscription.getKey('auth'))\n\n return {\n endpoint: subscription.endpoint,\n keys: { p256dh, auth },\n expirationTime: subscription.expirationTime,\n }\n}\n\n/**\n * Retorna o script padrão do Service Worker para manipulação de notificações em PWAs.\n */\nexport function getStandardWebPushServiceWorkerScript(): string {\n return `\nself.addEventListener('push', (event) => {\n if (!event.data) return;\n let payload;\n try {\n payload = event.data.json();\n } catch {\n payload = { title: 'Notificação', body: event.data.text() };\n }\n\n const title = payload.title || 'Nova Notificação';\n const options = {\n body: payload.body || '',\n icon: payload.icon || '/pwa-192x192.png',\n badge: payload.badge || '/badge-72x72.png',\n tag: payload.tag,\n data: payload.data || { url: payload.url || '/' },\n };\n\n event.waitUntil(self.registration.showNotification(title, options));\n});\n\nself.addEventListener('notificationclick', (event) => {\n event.notification.close();\n const targetUrl = event.notification.data?.url || '/';\n\n event.waitUntil(\n clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {\n for (const client of clientList) {\n if (client.url === targetUrl && 'focus' in client) {\n return client.focus();\n }\n }\n if (clients.openWindow) {\n return clients.openWindow(targetUrl);\n }\n })\n );\n});\n`.trim()\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Helper de push para React Native com Expo.\n * **Não importa `expo-notifications` estaticamente**: recebe o módulo por injeção\n * (duck-typing) para não poluir nem quebrar o bundle web/PWA.\n */\n\nimport {\n createDeviceRegistration,\n type DeviceRegistrationHandle,\n type DeviceRegistrationStorage,\n} from './deviceRegistration'\nimport type { NotificationClient } from './httpClient'\n\nexport type ExpoPermissionResponse = {\n readonly status: string\n readonly granted: boolean\n}\n\nexport type ExpoPushTokenResult = {\n readonly data: string\n}\n\nexport interface ExpoNotificationsModule {\n getPermissionsAsync(): Promise<ExpoPermissionResponse>\n requestPermissionsAsync(): Promise<ExpoPermissionResponse>\n getExpoPushTokenAsync(options?: { projectId?: string }): Promise<ExpoPushTokenResult>\n setNotificationChannelAsync?(\n channelId: string,\n channel: {\n name: string\n importance: number\n sound?: boolean\n vibrationPattern?: number[]\n },\n ): Promise<unknown>\n}\n\nexport type GetExpoPushTokenOptions = {\n readonly module: ExpoNotificationsModule\n readonly projectId?: string\n readonly channelId?: string\n readonly channelName?: string\n}\n\n/**\n * Solicita permissões e obtém o Expo Push Token.\n * Se a permissão for negada, devolve `undefined` (caminho normal, sem erro).\n */\nexport async function getExpoPushToken(options: GetExpoPushTokenOptions): Promise<string | undefined> {\n const { module } = options\n\n const currentPerms = await module.getPermissionsAsync()\n let isGranted = currentPerms.granted\n\n if (!isGranted) {\n const requested = await module.requestPermissionsAsync()\n isGranted = requested.granted\n }\n\n if (!isGranted) return undefined\n\n if (typeof module.setNotificationChannelAsync === 'function') {\n await module.setNotificationChannelAsync(options.channelId ?? 'default', {\n name: options.channelName ?? 'Geral',\n importance: 4, // Android IMPORTANCE_HIGH\n sound: true,\n })\n }\n\n const tokenResult = await module.getExpoPushTokenAsync({\n projectId: options.projectId,\n })\n\n return tokenResult.data\n}\n\nexport type CreateExpoPushRegistrationConfig = {\n readonly client: NotificationClient\n readonly module: ExpoNotificationsModule\n readonly projectId?: string\n readonly storage?: DeviceRegistrationStorage\n}\n\n/**\n * Cria o ciclo de vida completo de registro do dispositivo Expo integrado ao NotificationClient.\n */\nexport function createExpoPushRegistration(config: CreateExpoPushRegistrationConfig): DeviceRegistrationHandle {\n return createDeviceRegistration({\n client: config.client,\n driver: 'expo',\n storage: config.storage,\n getToken: () => getExpoPushToken({ module: config.module, projectId: config.projectId }),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;AC8DA,SAASA,cAAcC,QAAgBC,SAAgB;AACrD,QAAMC,WAAWD;AAGjB,QAAME,QAAQ,IAAIC,MAAMF,UAAUC,OA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QAAwC;AACjF,SAAOC,yBAAyB;IAC9BC,QAAQF,OAAOE;IACfC,QAAQ;IACRC,SAASJ,OAAOI;IAChBC,UAAU,6BAAM1B,iBAAiB;MAAEE,QAAQmB,OAAOnB;MAAQgB,WAAWG,OAAOH;IAAU,CAAA,GAA5E;EACZ,CAAA;AACF;AAPgBE;","names":["buildApiError","status","payload","envelope","error","Error","message","Object","assign","code","issues","createNotificationClient","config","fetchImpl","fetch","baseUrl","endsWith","slice","request","params","fullPath","path","isAbsolute","startsWith","fallbackBase","window","location","origin","url","URL","undefined","key","value","entries","query","searchParams","set","String","authHeaders","getAuthHeaders","finalUrl","toString","pathname","search","response","method","headers","body","JSON","stringify","text","parse","ok","listNotifications","options","category","read","cursor","perPage","data","nextCursor","pagination","unreadCount","meta","countUnread","markAsRead","id","encodeURIComponent","markAllAsRead","updated","deleteNotification","registerDevice","input","unregisterDevice","getPreferences","updatePreferences","preferences","listTemplates","getCategoryPolicies","updateCategoryPolicies","policies","deactivateTemplate","restoreDefault","listTemplateVariables","upsertTemplate","resolveStreamRequest","getVapidPublicKey","publicKey","sendPush","broadcastPush","registerWebPush","subscription","platform","driver","token","appVersion","locale","timezone","STORAGE_KEY","createDeviceRegistration","config","rememberDeviceId","deviceId","storage","setItem","register","options","token","getToken","undefined","input","platform","driver","appVersion","locale","timezone","device","client","registerDevice","id","unregister","getItem","unregisterDevice","removeItem","DEFAULT_RECONNECT_DELAY_MS","parseSseBlock","block","eventName","dataLines","line","split","startsWith","slice","length","trim","push","undefined","raw","join","event","data","JSON","parse","subscribeToNotificationStream","params","fetchImpl","fetch","controller","AbortController","closed","connect","response","url","headers","Accept","signal","ok","body","Error","status","reader","getReader","decoder","TextDecoder","buffer","value","done","read","decode","stream","blocks","pop","onEvent","runWithReconnect","delay","reconnectDelayMs","error","onError","String","Promise","resolve","setTimeout","close","abort","urlBase64ToUint8Array","base64String","padding","repeat","length","base64","replace","rawData","atob","outputArray","Uint8Array","i","charCodeAt","arrayBufferToBase64Url","buffer","bytes","binary","byteLength","String","fromCharCode","btoa","isWebPushSupported","window","navigator","subscribeWebPush","options","undefined","Notification","permission","requestPermission","registration","serviceWorkerRegistration","serviceWorker","ready","applicationServerKey","vapidPublicKey","subscription","pushManager","getSubscription","subscribe","userVisibleOnly","p256dh","getKey","auth","endpoint","keys","expirationTime","unsubscribeWebPush","unsubscribe","getWebPushSubscription","getStandardWebPushServiceWorkerScript","trim","getExpoPushToken","options","module","currentPerms","getPermissionsAsync","isGranted","granted","requested","requestPermissionsAsync","undefined","setNotificationChannelAsync","channelId","name","channelName","importance","sound","tokenResult","getExpoPushTokenAsync","projectId","data","createExpoPushRegistration","config","createDeviceRegistration","client","driver","storage","getToken"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/httpClient.ts","../src/deviceRegistration.ts","../src/streamSubscription.ts","../src/webPush.ts","../src/expoPush.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nexport { createNotificationClient } from './httpClient'\nexport type {\n NotificationClient,\n NotificationClientConfig,\n ListNotificationsOptions,\n ListNotificationsPage,\n RegisterDeviceInput,\n NotificationApiError,\n} from './httpClient'\n\nexport { createDeviceRegistration } from './deviceRegistration'\nexport type {\n DeviceRegistrationConfig,\n DeviceRegistrationHandle,\n DeviceRegistrationStorage,\n RegisterOptions,\n} from './deviceRegistration'\n\nexport { subscribeToNotificationStream } from './streamSubscription'\nexport type {\n NotificationStreamEvent,\n NotificationStreamSubscription,\n SubscribeToNotificationStreamParams,\n} from './streamSubscription'\n\nexport {\n isWebPushSupported,\n urlBase64ToUint8Array,\n arrayBufferToBase64Url,\n subscribeWebPush,\n unsubscribeWebPush,\n getWebPushSubscription,\n getStandardWebPushServiceWorkerScript,\n} from './webPush'\nexport type { SubscribeWebPushOptions } from './webPush'\n\nexport { getExpoPushToken, createExpoPushRegistration } from './expoPush'\nexport type {\n ExpoNotificationsModule,\n ExpoPermissionResponse,\n ExpoPushTokenResult,\n GetExpoPushTokenOptions,\n CreateExpoPushRegistrationConfig,\n} from './expoPush'\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Cliente HTTP tipado pelas 13 rotas do módulo. **Isomórfico e sem DOM**: `fetch` é injetável e o\n * default é o global — é o que permite o mesmo pacote rodar no React Native do cawme e no PWA do\n * quickcart, sem o `-ui` (que tem `react-dom` e Tailwind) entrar no bundle mobile.\n */\n\nimport type {\n DeviceRegistration,\n NotificationPreference,\n NotificationSummary,\n NotificationTemplate,\n NotificationCategoryPolicy,\n TemplateEditorItem,\n TemplateVariableCatalog,\n UpsertTemplateBody,\n WebPushSubscription,\n SendPushDirectBody,\n SendPushDirectResult,\n BroadcastPushBody,\n BroadcastPushResult,\n} from '@adatechnology/notification-contracts'\n\nexport type NotificationClientConfig = {\n /** Base do host, sem barra final: `https://api.exemplo.com/v1`. */\n readonly baseUrl: string\n /**\n * Devolve o header de autorização a cada chamada — função, não string, porque o token do host\n * rotaciona e capturar o valor no boot deixaria o cliente com uma credencial vencida.\n */\n readonly getAuthHeaders?: () => Promise<Record<string, string>> | Record<string, string>\n readonly fetchImpl?: typeof fetch\n}\n\nexport type ListNotificationsOptions = {\n readonly category?: string\n readonly read?: boolean\n readonly cursor?: string\n readonly perPage?: number\n}\n\nexport type ListNotificationsPage = {\n readonly data: readonly NotificationSummary[]\n readonly nextCursor?: string\n readonly unreadCount: number\n}\n\nexport type RegisterDeviceInput = {\n readonly platform: 'ios' | 'android' | 'web'\n readonly driver: 'expo' | 'fcm'\n readonly token: string\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n}\n\nexport type NotificationApiError = Error & {\n readonly status: number\n readonly code: string\n readonly issues?: readonly { path: string; message: string }[]\n}\n\nfunction buildApiError(status: number, payload: unknown): NotificationApiError {\n const envelope = payload as {\n error?: { code?: string; message?: string; issues?: { path: string; message: string }[] }\n }\n const error = new Error(envelope?.error?.message ?? `Falha na requisição (${status}).`) as NotificationApiError\n return Object.assign(error, {\n status,\n code: envelope?.error?.code ?? 'NOTIFICATION_UNKNOWN_ERROR',\n issues: envelope?.error?.issues,\n })\n}\n\nexport type NotificationClient = {\n listNotifications(options?: ListNotificationsOptions): Promise<ListNotificationsPage>\n countUnread(): Promise<number>\n markAsRead(id: string): Promise<NotificationSummary>\n markAllAsRead(): Promise<number>\n deleteNotification(id: string): Promise<void>\n registerDevice(input: RegisterDeviceInput): Promise<DeviceRegistration>\n unregisterDevice(id: string): Promise<void>\n getPreferences(): Promise<readonly NotificationPreference[]>\n updatePreferences(preferences: readonly NotificationPreference[]): Promise<readonly NotificationPreference[]>\n /** O teto de canais da empresa por categoria — acima da preferência de quem recebe. */\n getCategoryPolicies(): Promise<readonly NotificationCategoryPolicy[]>\n /** Substitui a política das categorias enviadas; as demais ficam intactas. */\n updateCategoryPolicies(\n policies: readonly NotificationCategoryPolicy[],\n ): Promise<readonly NotificationCategoryPolicy[]>\n listTemplates(): Promise<readonly NotificationTemplate[]>\n /**\n * Cria uma VERSÃO nova do template, não edita a atual.\n *\n * O módulo versiona por `key`+`channel`+`locale`: a versão anterior fica legível para auditoria, e\n * a leitura só devolve a ativa mais alta. Então \"editar a copy\" e \"reverter\" são a mesma operação\n * — o que a tela de configuração precisa para alguém corrigir um texto sem medo.\n */\n upsertTemplate(input: UpsertTemplateBody): Promise<NotificationTemplate>\n /**\n * \"Remover\" é desativar: o servidor derruba todas as versões ativas da identidade e mantém as\n * linhas, porque entrega já enviada precisa continuar auditável com o texto que usou.\n */\n deactivateTemplate(id: string): Promise<void>\n /**\n * \"Restaurar padrão\": o servidor grava uma versão nova com o conteúdo embutido do modelo padrão\n * (`notification.standard-email`). 400 se o id não é dele; 409 se a restauração é recusada.\n */\n restoreDefault(id: string): Promise<NotificationTemplate>\n /** O catálogo de variáveis por chave — é o que a tela mostra como lista clicável. */\n listTemplateVariables(): Promise<TemplateVariableCatalog>\n /** Templates declarados pelo host: rótulo, variáveis, texto padrão e a versão atual (para o editor). */\n listTemplateDefinitions(): Promise<TemplateEditorItem[]>\n /** Base + headers, para o assinante de SSE reaproveitar a mesma configuração. */\n resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }>\n /** Obtém a chave pública VAPID do servidor para inscrição Web Push no navegador */\n getVapidPublicKey(): Promise<string>\n /** Dispara uma notificação push direta (para token, user ou subscription) */\n sendPush(input: SendPushDirectBody): Promise<SendPushDirectResult>\n /** Dispara push em broadcast por tópico ou filtro */\n broadcastPush(input: BroadcastPushBody): Promise<BroadcastPushResult>\n /** Registra uma assinatura Web Push nativa (PWA) no backend */\n registerWebPush(\n subscription: WebPushSubscription,\n options?: { readonly appVersion?: string; readonly locale?: string; readonly timezone?: string },\n ): Promise<DeviceRegistration>\n}\n\nexport function createNotificationClient(config: NotificationClientConfig): NotificationClient {\n const fetchImpl = config.fetchImpl ?? fetch\n const baseUrl = config.baseUrl.endsWith('/') ? config.baseUrl.slice(0, -1) : config.baseUrl\n\n async function request<TResponse>(params: {\n method: string\n path: string\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown\n }): Promise<TResponse | undefined> {\n const fullPath = `${baseUrl}${params.path}`\n const isAbsolute = fullPath.startsWith('http://') || fullPath.startsWith('https://')\n const fallbackBase =\n typeof window !== 'undefined' && window.location?.origin ? window.location.origin : 'http://localhost'\n const url = new URL(fullPath, isAbsolute ? undefined : fallbackBase)\n for (const [key, value] of Object.entries(params.query ?? {})) {\n if (value !== undefined) url.searchParams.set(key, String(value))\n }\n\n const authHeaders = (await config.getAuthHeaders?.()) ?? {}\n const finalUrl = isAbsolute || typeof window !== 'undefined' ? url.toString() : `${url.pathname}${url.search}`\n const response = await fetchImpl(finalUrl, {\n method: params.method,\n headers: { ...(params.body === undefined ? {} : { 'Content-Type': 'application/json' }), ...authHeaders },\n body: params.body === undefined ? undefined : JSON.stringify(params.body),\n })\n\n if (response.status === 204) return undefined\n\n const text = await response.text()\n const payload: unknown = text === '' ? undefined : JSON.parse(text)\n if (!response.ok) throw buildApiError(response.status, payload)\n return payload as TResponse\n }\n\n return {\n async listNotifications(options): Promise<ListNotificationsPage> {\n const payload = await request<{\n data: NotificationSummary[]\n pagination: { nextCursor?: string }\n meta: { unreadCount: number }\n }>({\n method: 'GET',\n path: '/notifications',\n query: { category: options?.category, read: options?.read, cursor: options?.cursor, perPage: options?.perPage },\n })\n\n return {\n data: payload?.data ?? [],\n nextCursor: payload?.pagination.nextCursor,\n unreadCount: payload?.meta.unreadCount ?? 0,\n }\n },\n\n async countUnread(): Promise<number> {\n const payload = await request<{ data: { unreadCount: number } }>({\n method: 'GET',\n path: '/notifications/unread-count',\n })\n return payload?.data.unreadCount ?? 0\n },\n\n async markAsRead(id): Promise<NotificationSummary> {\n const payload = await request<{ data: NotificationSummary }>({\n method: 'PATCH',\n path: `/notifications/${encodeURIComponent(id)}/read`,\n })\n if (!payload) throw new Error('notification-client: resposta vazia em markAsRead')\n return payload.data\n },\n\n async markAllAsRead(): Promise<number> {\n const payload = await request<{ data: { updated: number } }>({ method: 'POST', path: '/notifications/read-all' })\n return payload?.data.updated ?? 0\n },\n\n async deleteNotification(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notifications/${encodeURIComponent(id)}` })\n },\n\n async registerDevice(input): Promise<DeviceRegistration> {\n const payload = await request<{ data: DeviceRegistration }>({\n method: 'POST',\n path: '/notification-devices',\n body: input,\n })\n if (!payload) throw new Error('notification-client: resposta vazia em registerDevice')\n return payload.data\n },\n\n async unregisterDevice(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notification-devices/${encodeURIComponent(id)}` })\n },\n\n async getPreferences(): Promise<readonly NotificationPreference[]> {\n const payload = await request<{ data: NotificationPreference[] }>({\n method: 'GET',\n path: '/notification-preferences',\n })\n return payload?.data ?? []\n },\n\n async updatePreferences(preferences): Promise<readonly NotificationPreference[]> {\n const payload = await request<{ data: NotificationPreference[] }>({\n method: 'PUT',\n path: '/notification-preferences',\n body: { preferences },\n })\n return payload?.data ?? []\n },\n\n async listTemplates(): Promise<readonly NotificationTemplate[]> {\n const payload = await request<{ data: NotificationTemplate[] }>({\n method: 'GET',\n path: '/notification-templates',\n })\n return payload?.data ?? []\n },\n\n async getCategoryPolicies(): Promise<readonly NotificationCategoryPolicy[]> {\n const payload = await request<{ data: NotificationCategoryPolicy[] }>({\n method: 'GET',\n path: '/notification-category-policies',\n })\n return payload?.data ?? []\n },\n\n async updateCategoryPolicies(policies): Promise<readonly NotificationCategoryPolicy[]> {\n const payload = await request<{ data: NotificationCategoryPolicy[] }>({\n method: 'PUT',\n path: '/notification-category-policies',\n body: { policies },\n })\n return payload?.data ?? []\n },\n\n async deactivateTemplate(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notification-templates/${encodeURIComponent(id)}` })\n },\n\n async restoreDefault(id): Promise<NotificationTemplate> {\n const payload = await request<{ data: NotificationTemplate }>({\n method: 'POST',\n path: `/notification-templates/${encodeURIComponent(id)}/restore-default`,\n })\n if (!payload?.data) throw new Error('notification-client: restoreDefault não devolveu o template')\n return payload.data\n },\n\n async listTemplateDefinitions(): Promise<TemplateEditorItem[]> {\n const payload = await request<{ data: TemplateEditorItem[] }>({\n method: 'GET',\n path: '/notification-template-definitions',\n })\n return payload?.data ?? []\n },\n\n async listTemplateVariables(): Promise<TemplateVariableCatalog> {\n const payload = await request<{ data: TemplateVariableCatalog }>({\n method: 'GET',\n path: '/notification-template-variables',\n })\n return payload?.data ?? {}\n },\n\n async upsertTemplate(input: UpsertTemplateBody): Promise<NotificationTemplate> {\n const payload = await request<{ data: NotificationTemplate }>({\n method: 'POST',\n path: '/notification-templates',\n body: input,\n })\n // Sem fallback: a rota responde 201 com o template criado, e devolver `undefined as never`\n // aqui esconderia uma mudança de contrato até estourar na tela.\n if (!payload?.data) throw new Error('notification-client: upsertTemplate não devolveu o template')\n return payload.data\n },\n\n async resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }> {\n return { url: `${baseUrl}/notifications/stream`, headers: (await config.getAuthHeaders?.()) ?? {} }\n },\n\n async getVapidPublicKey(): Promise<string> {\n const payload = await request<{ data: { publicKey: string } }>({\n method: 'GET',\n path: '/push/vapid-public-key',\n })\n if (!payload?.data?.publicKey) throw new Error('notification-client: chave pública VAPID não retornada')\n return payload.data.publicKey\n },\n\n async sendPush(input: SendPushDirectBody): Promise<SendPushDirectResult> {\n const payload = await request<{ data: SendPushDirectResult }>({\n method: 'POST',\n path: '/push/send',\n body: input,\n })\n if (!payload?.data) throw new Error('notification-client: resposta vazia ao enviar push')\n return payload.data\n },\n\n async broadcastPush(input: BroadcastPushBody): Promise<BroadcastPushResult> {\n const payload = await request<{ data: BroadcastPushResult }>({\n method: 'POST',\n path: '/push/broadcast',\n body: input,\n })\n if (!payload?.data) throw new Error('notification-client: resposta vazia em broadcastPush')\n return payload.data\n },\n\n async registerWebPush(\n subscription: WebPushSubscription,\n options?: { readonly appVersion?: string; readonly locale?: string; readonly timezone?: string },\n ): Promise<DeviceRegistration> {\n const payload = await request<{ data: DeviceRegistration }>({\n method: 'POST',\n path: '/notification-devices',\n body: {\n platform: 'web',\n driver: 'webpush',\n token: JSON.stringify(subscription),\n appVersion: options?.appVersion,\n locale: options?.locale,\n timezone: options?.timezone,\n },\n })\n if (!payload?.data) throw new Error('notification-client: resposta vazia em registerWebPush')\n return payload.data\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Registro de dispositivo para push. **Não importa `expo-notifications` nem `firebase`**: recebe\n * `getToken` por injeção. É o que mantém o pacote isomórfico — o cawme passa o token do Expo, o\n * PWA do quickcart passa o do FCM web, e nenhum dos dois carrega o SDK do outro.\n */\n\nimport type { DeviceRegistration } from '@adatechnology/notification-contracts'\n\nimport type { NotificationClient, RegisterDeviceInput } from './httpClient'\n\nexport type DeviceRegistrationConfig = {\n readonly client: NotificationClient\n readonly driver: 'expo' | 'fcm'\n /** `undefined` = permissão negada ou indisponível; o registro é pulado sem erro. */\n getToken(): Promise<string | undefined>\n /** Persiste o id entre execuções, para o logout conseguir remover o device certo. */\n readonly storage?: DeviceRegistrationStorage\n}\n\n/** `AsyncStorage` do RN e `localStorage` do web satisfazem esta forma (via wrapper trivial). */\nexport type DeviceRegistrationStorage = {\n getItem(key: string): Promise<string | null> | string | null\n setItem(key: string, value: string): Promise<void> | void\n removeItem(key: string): Promise<void> | void\n}\n\nexport type RegisterOptions = {\n readonly platform: 'ios' | 'android' | 'web'\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n}\n\nexport type DeviceRegistrationHandle = {\n /** Idempotente: chamar de novo com o mesmo token reativa o registro em vez de duplicar. */\n register(options: RegisterOptions): Promise<DeviceRegistration | undefined>\n /** No logout — sem isto, o aparelho continuaria recebendo push do usuário anterior. */\n unregister(): Promise<void>\n}\n\nconst STORAGE_KEY = 'adatechnology:notification:device-id'\n\nexport function createDeviceRegistration(config: DeviceRegistrationConfig): DeviceRegistrationHandle {\n async function rememberDeviceId(deviceId: string): Promise<void> {\n await config.storage?.setItem(STORAGE_KEY, deviceId)\n }\n\n return {\n async register(options): Promise<DeviceRegistration | undefined> {\n const token = await config.getToken()\n // Permissão negada é o caminho normal, não erro: o usuário pode recusar push e o resto do\n // app continua funcionando (inbox e e-mail seguem).\n if (!token) return undefined\n\n const input: RegisterDeviceInput = {\n platform: options.platform,\n driver: config.driver,\n token,\n appVersion: options.appVersion,\n locale: options.locale,\n timezone: options.timezone,\n }\n\n const device = await config.client.registerDevice(input)\n await rememberDeviceId(device.id)\n return device\n },\n\n async unregister(): Promise<void> {\n const deviceId = await config.storage?.getItem(STORAGE_KEY)\n if (!deviceId) return\n\n await config.client.unregisterDevice(deviceId)\n await config.storage?.removeItem(STORAGE_KEY)\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Assinatura do SSE do inbox.\n *\n * **Não usa `EventSource`**, apesar de ser a API óbvia: `EventSource` não aceita headers, e a\n * autenticação do host é `Authorization: Bearer`. Passar token por query string violaria\n * `security.md` §Privacy (credencial em URL vaza em log de proxy e histórico). Além disso o React\n * Native não tem `EventSource` nativo. Ler o corpo por `fetch` + `ReadableStream` resolve os dois\n * de uma vez, e é o que roda igual no web e no RN moderno.\n */\n\nexport type NotificationStreamEvent = {\n readonly event: string\n readonly data: unknown\n}\n\nexport type SubscribeToNotificationStreamParams = {\n readonly url: string\n readonly headers: Record<string, string>\n readonly onEvent: (event: NotificationStreamEvent) => void\n readonly onError?: (error: Error) => void\n readonly fetchImpl?: typeof fetch\n /** Reconexão com backoff; `0` desliga (o chamador cuida). */\n readonly reconnectDelayMs?: number\n}\n\nexport type NotificationStreamSubscription = {\n close(): void\n}\n\nconst DEFAULT_RECONNECT_DELAY_MS = 3000\n\nfunction parseSseBlock(block: string): NotificationStreamEvent | undefined {\n let eventName = 'message'\n const dataLines: string[] = []\n\n for (const line of block.split('\\n')) {\n // Comentário SSE — é o heartbeat do servidor, e não deve virar evento no cliente.\n if (line.startsWith(':')) continue\n if (line.startsWith('event:')) eventName = line.slice('event:'.length).trim()\n if (line.startsWith('data:')) dataLines.push(line.slice('data:'.length).trim())\n }\n\n if (dataLines.length === 0) return undefined\n\n const raw = dataLines.join('\\n')\n try {\n return { event: eventName, data: JSON.parse(raw) }\n } catch {\n return { event: eventName, data: raw }\n }\n}\n\nexport function subscribeToNotificationStream(\n params: SubscribeToNotificationStreamParams,\n): NotificationStreamSubscription {\n const fetchImpl = params.fetchImpl ?? fetch\n const controller = new AbortController()\n let closed = false\n\n async function connect(): Promise<void> {\n const response = await fetchImpl(params.url, {\n headers: { ...params.headers, Accept: 'text/event-stream' },\n signal: controller.signal,\n })\n\n if (!response.ok || !response.body) throw new Error(`SSE falhou com status ${response.status}`)\n\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n\n for (;;) {\n const { value, done } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n // Eventos SSE são separados por linha em branco; o resto fica no buffer porque um chunk\n // de rede pode cortar um evento no meio.\n const blocks = buffer.split('\\n\\n')\n buffer = blocks.pop() ?? ''\n\n for (const block of blocks) {\n const event = parseSseBlock(block)\n if (event) params.onEvent(event)\n }\n }\n }\n\n async function runWithReconnect(): Promise<void> {\n const delay = params.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS\n\n while (!closed) {\n try {\n await connect()\n } catch (error) {\n if (closed) return\n params.onError?.(error instanceof Error ? error : new Error(String(error)))\n }\n\n // Conexão encerrada pelo servidor (deploy, timeout de proxy) é o caso comum — reconectar é\n // o comportamento certo, e sem `delay` viraria laço apertado contra um servidor caído.\n if (closed || delay === 0) return\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n }\n\n void runWithReconnect()\n\n return {\n close(): void {\n closed = true\n controller.abort()\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Helpers isomórficos para Web Push nativo (W3C Push API) em PWAs.\n * Não depende de Firebase nem de bibliotecas externas: funciona nativamente no Chrome,\n * Firefox, Edge e Safari (iOS 16.4+ e macOS).\n */\n\nimport type { WebPushSubscription } from '@adatechnology/notification-contracts'\n\nexport type SubscribeWebPushOptions = {\n readonly vapidPublicKey: string\n readonly serviceWorkerRegistration?: ServiceWorkerRegistration\n}\n\n/**\n * Converte chave pública VAPID em base64url para Uint8Array.\n * Exigido pelo navegador em `pushManager.subscribe({ applicationServerKey })`.\n */\nexport function urlBase64ToUint8Array(base64String: string): Uint8Array {\n const padding = '='.repeat((4 - (base64String.length % 4)) % 4)\n const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/')\n const rawData = atob(base64)\n const outputArray = new Uint8Array(rawData.length)\n\n for (let i = 0; i < rawData.length; ++i) {\n outputArray[i] = rawData.charCodeAt(i)\n }\n return outputArray\n}\n\nexport function arrayBufferToBase64Url(buffer: ArrayBufferLike | ArrayBuffer | null): string {\n if (!buffer) return ''\n const bytes = new Uint8Array(buffer as ArrayBuffer)\n let binary = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n binary += String.fromCharCode(bytes[i])\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n/**\n * Verifica se o ambiente de execução suporta Web Push nativo via Service Worker.\n */\nexport function isWebPushSupported(): boolean {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') return false\n return 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window\n}\n\n/**\n * Inscreve o navegador no Push Service nativo usando as chaves VAPID fornecidas.\n * Retorna `undefined` caso a permissão seja negada pelo usuário (caminho normal, sem lançar erro).\n */\nexport async function subscribeWebPush(options: SubscribeWebPushOptions): Promise<WebPushSubscription | undefined> {\n if (!isWebPushSupported()) return undefined\n\n if (Notification.permission === 'default') {\n const permission = await Notification.requestPermission()\n if (permission !== 'granted') return undefined\n } else if (Notification.permission !== 'granted') {\n return undefined\n }\n\n const registration = options.serviceWorkerRegistration ?? (await navigator.serviceWorker.ready)\n const applicationServerKey = urlBase64ToUint8Array(options.vapidPublicKey)\n\n let subscription = await registration.pushManager.getSubscription()\n if (!subscription) {\n subscription = await registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: applicationServerKey as unknown as BufferSource,\n })\n }\n\n const p256dh = arrayBufferToBase64Url(subscription.getKey('p256dh'))\n const auth = arrayBufferToBase64Url(subscription.getKey('auth'))\n\n return {\n endpoint: subscription.endpoint,\n keys: { p256dh, auth },\n expirationTime: subscription.expirationTime,\n }\n}\n\n/**\n * Remove a inscrição ativa de push no navegador.\n */\nexport async function unsubscribeWebPush(serviceWorkerRegistration?: ServiceWorkerRegistration): Promise<boolean> {\n if (!isWebPushSupported()) return false\n\n const registration = serviceWorkerRegistration ?? (await navigator.serviceWorker.ready)\n const subscription = await registration.pushManager.getSubscription()\n if (!subscription) return false\n\n return subscription.unsubscribe()\n}\n\n/**\n * Obtém a inscrição ativa de push no navegador se já existir.\n */\nexport async function getWebPushSubscription(\n serviceWorkerRegistration?: ServiceWorkerRegistration,\n): Promise<WebPushSubscription | undefined> {\n if (!isWebPushSupported()) return undefined\n\n const registration = serviceWorkerRegistration ?? (await navigator.serviceWorker.ready)\n const subscription = await registration.pushManager.getSubscription()\n if (!subscription) return undefined\n\n const p256dh = arrayBufferToBase64Url(subscription.getKey('p256dh'))\n const auth = arrayBufferToBase64Url(subscription.getKey('auth'))\n\n return {\n endpoint: subscription.endpoint,\n keys: { p256dh, auth },\n expirationTime: subscription.expirationTime,\n }\n}\n\n/**\n * Retorna o script padrão do Service Worker para manipulação de notificações em PWAs.\n */\nexport function getStandardWebPushServiceWorkerScript(): string {\n return `\nself.addEventListener('push', (event) => {\n if (!event.data) return;\n let payload;\n try {\n payload = event.data.json();\n } catch {\n payload = { title: 'Notificação', body: event.data.text() };\n }\n\n const title = payload.title || 'Nova Notificação';\n const options = {\n body: payload.body || '',\n icon: payload.icon || '/pwa-192x192.png',\n badge: payload.badge || '/badge-72x72.png',\n tag: payload.tag,\n data: payload.data || { url: payload.url || '/' },\n };\n\n event.waitUntil(self.registration.showNotification(title, options));\n});\n\nself.addEventListener('notificationclick', (event) => {\n event.notification.close();\n const targetUrl = event.notification.data?.url || '/';\n\n event.waitUntil(\n clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {\n for (const client of clientList) {\n if (client.url === targetUrl && 'focus' in client) {\n return client.focus();\n }\n }\n if (clients.openWindow) {\n return clients.openWindow(targetUrl);\n }\n })\n );\n});\n`.trim()\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Helper de push para React Native com Expo.\n * **Não importa `expo-notifications` estaticamente**: recebe o módulo por injeção\n * (duck-typing) para não poluir nem quebrar o bundle web/PWA.\n */\n\nimport {\n createDeviceRegistration,\n type DeviceRegistrationHandle,\n type DeviceRegistrationStorage,\n} from './deviceRegistration'\nimport type { NotificationClient } from './httpClient'\n\nexport type ExpoPermissionResponse = {\n readonly status: string\n readonly granted: boolean\n}\n\nexport type ExpoPushTokenResult = {\n readonly data: string\n}\n\nexport interface ExpoNotificationsModule {\n getPermissionsAsync(): Promise<ExpoPermissionResponse>\n requestPermissionsAsync(): Promise<ExpoPermissionResponse>\n getExpoPushTokenAsync(options?: { projectId?: string }): Promise<ExpoPushTokenResult>\n setNotificationChannelAsync?(\n channelId: string,\n channel: {\n name: string\n importance: number\n sound?: boolean\n vibrationPattern?: number[]\n },\n ): Promise<unknown>\n}\n\nexport type GetExpoPushTokenOptions = {\n readonly module: ExpoNotificationsModule\n readonly projectId?: string\n readonly channelId?: string\n readonly channelName?: string\n}\n\n/**\n * Solicita permissões e obtém o Expo Push Token.\n * Se a permissão for negada, devolve `undefined` (caminho normal, sem erro).\n */\nexport async function getExpoPushToken(options: GetExpoPushTokenOptions): Promise<string | undefined> {\n const { module } = options\n\n const currentPerms = await module.getPermissionsAsync()\n let isGranted = currentPerms.granted\n\n if (!isGranted) {\n const requested = await module.requestPermissionsAsync()\n isGranted = requested.granted\n }\n\n if (!isGranted) return undefined\n\n if (typeof module.setNotificationChannelAsync === 'function') {\n await module.setNotificationChannelAsync(options.channelId ?? 'default', {\n name: options.channelName ?? 'Geral',\n importance: 4, // Android IMPORTANCE_HIGH\n sound: true,\n })\n }\n\n const tokenResult = await module.getExpoPushTokenAsync({\n projectId: options.projectId,\n })\n\n return tokenResult.data\n}\n\nexport type CreateExpoPushRegistrationConfig = {\n readonly client: NotificationClient\n readonly module: ExpoNotificationsModule\n readonly projectId?: string\n readonly storage?: DeviceRegistrationStorage\n}\n\n/**\n * Cria o ciclo de vida completo de registro do dispositivo Expo integrado ao NotificationClient.\n */\nexport function createExpoPushRegistration(config: CreateExpoPushRegistrationConfig): DeviceRegistrationHandle {\n return createDeviceRegistration({\n client: config.client,\n driver: 'expo',\n storage: config.storage,\n getToken: () => getExpoPushToken({ module: config.module, projectId: config.projectId }),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;AC+DA,SAASA,cAAcC,QAAgBC,SAAgB;AACrD,QAAMC,WAAWD;AAGjB,QAAME,QAAQ,IAAIC,MAAMF,UAAUC,OAAOE,WAA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MC,cAAc,MAAMd,QAAOe,sBAAsB;IACrDC,WAAWjB,QAAQiB;EACrB,CAAA;AAEA,SAAOF,YAAYG;AACrB;AA1BsBnB;AAsCf,SAASoB,2BAA2BC,QAAwC;AACjF,SAAOC,yBAAyB;IAC9BC,QAAQF,OAAOE;IACfC,QAAQ;IACRC,SAASJ,OAAOI;IAChBC,UAAU,6BAAM1B,iBAAiB;MAAEE,QAAQmB,OAAOnB;MAAQgB,WAAWG,OAAOH;IAAU,CAAA,GAA5E;EACZ,CAAA;AACF;AAPgBE;","names":["buildApiError","status","payload","envelope","error","Error","message","Object","assign","code","issues","createNotificationClient","config","fetchImpl","fetch","baseUrl","endsWith","slice","request","params","fullPath","path","isAbsolute","startsWith","fallbackBase","window","location","origin","url","URL","undefined","key","value","entries","query","searchParams","set","String","authHeaders","getAuthHeaders","finalUrl","toString","pathname","search","response","method","headers","body","JSON","stringify","text","parse","ok","listNotifications","options","category","read","cursor","perPage","data","nextCursor","pagination","unreadCount","meta","countUnread","markAsRead","id","encodeURIComponent","markAllAsRead","updated","deleteNotification","registerDevice","input","unregisterDevice","getPreferences","updatePreferences","preferences","listTemplates","getCategoryPolicies","updateCategoryPolicies","policies","deactivateTemplate","restoreDefault","listTemplateDefinitions","listTemplateVariables","upsertTemplate","resolveStreamRequest","getVapidPublicKey","publicKey","sendPush","broadcastPush","registerWebPush","subscription","platform","driver","token","appVersion","locale","timezone","STORAGE_KEY","createDeviceRegistration","config","rememberDeviceId","deviceId","storage","setItem","register","options","token","getToken","undefined","input","platform","driver","appVersion","locale","timezone","device","client","registerDevice","id","unregister","getItem","unregisterDevice","removeItem","DEFAULT_RECONNECT_DELAY_MS","parseSseBlock","block","eventName","dataLines","line","split","startsWith","slice","length","trim","push","undefined","raw","join","event","data","JSON","parse","subscribeToNotificationStream","params","fetchImpl","fetch","controller","AbortController","closed","connect","response","url","headers","Accept","signal","ok","body","Error","status","reader","getReader","decoder","TextDecoder","buffer","value","done","read","decode","stream","blocks","pop","onEvent","runWithReconnect","delay","reconnectDelayMs","error","onError","String","Promise","resolve","setTimeout","close","abort","urlBase64ToUint8Array","base64String","padding","repeat","length","base64","replace","rawData","atob","outputArray","Uint8Array","i","charCodeAt","arrayBufferToBase64Url","buffer","bytes","binary","byteLength","String","fromCharCode","btoa","isWebPushSupported","window","navigator","subscribeWebPush","options","undefined","Notification","permission","requestPermission","registration","serviceWorkerRegistration","serviceWorker","ready","applicationServerKey","vapidPublicKey","subscription","pushManager","getSubscription","subscribe","userVisibleOnly","p256dh","getKey","auth","endpoint","keys","expirationTime","unsubscribeWebPush","unsubscribe","getWebPushSubscription","getStandardWebPushServiceWorkerScript","trim","getExpoPushToken","options","module","currentPerms","getPermissionsAsync","isGranted","granted","requested","requestPermissionsAsync","undefined","setNotificationChannelAsync","channelId","name","channelName","importance","sound","tokenResult","getExpoPushTokenAsync","projectId","data","createExpoPushRegistration","config","createDeviceRegistration","client","driver","storage","getToken"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { NotificationSummary, DeviceRegistration, NotificationPreference, NotificationCategoryPolicy, NotificationTemplate, UpsertTemplateBody, TemplateVariableCatalog, SendPushDirectBody, SendPushDirectResult, BroadcastPushBody, BroadcastPushResult, WebPushSubscription } from '@adatechnology/notification-contracts';
|
|
1
|
+
import { NotificationSummary, DeviceRegistration, NotificationPreference, NotificationCategoryPolicy, NotificationTemplate, UpsertTemplateBody, TemplateVariableCatalog, TemplateEditorItem, SendPushDirectBody, SendPushDirectResult, BroadcastPushBody, BroadcastPushResult, WebPushSubscription } from '@adatechnology/notification-contracts';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
@@ -80,6 +80,8 @@ type NotificationClient = {
|
|
|
80
80
|
restoreDefault(id: string): Promise<NotificationTemplate>;
|
|
81
81
|
/** O catálogo de variáveis por chave — é o que a tela mostra como lista clicável. */
|
|
82
82
|
listTemplateVariables(): Promise<TemplateVariableCatalog>;
|
|
83
|
+
/** Templates declarados pelo host: rótulo, variáveis, texto padrão e a versão atual (para o editor). */
|
|
84
|
+
listTemplateDefinitions(): Promise<TemplateEditorItem[]>;
|
|
83
85
|
/** Base + headers, para o assinante de SSE reaproveitar a mesma configuração. */
|
|
84
86
|
resolveStreamRequest(): Promise<{
|
|
85
87
|
url: string;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { NotificationSummary, DeviceRegistration, NotificationPreference, NotificationCategoryPolicy, NotificationTemplate, UpsertTemplateBody, TemplateVariableCatalog, SendPushDirectBody, SendPushDirectResult, BroadcastPushBody, BroadcastPushResult, WebPushSubscription } from '@adatechnology/notification-contracts';
|
|
1
|
+
import { NotificationSummary, DeviceRegistration, NotificationPreference, NotificationCategoryPolicy, NotificationTemplate, UpsertTemplateBody, TemplateVariableCatalog, TemplateEditorItem, SendPushDirectBody, SendPushDirectResult, BroadcastPushBody, BroadcastPushResult, WebPushSubscription } from '@adatechnology/notification-contracts';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
@@ -80,6 +80,8 @@ type NotificationClient = {
|
|
|
80
80
|
restoreDefault(id: string): Promise<NotificationTemplate>;
|
|
81
81
|
/** O catálogo de variáveis por chave — é o que a tela mostra como lista clicável. */
|
|
82
82
|
listTemplateVariables(): Promise<TemplateVariableCatalog>;
|
|
83
|
+
/** Templates declarados pelo host: rótulo, variáveis, texto padrão e a versão atual (para o editor). */
|
|
84
|
+
listTemplateDefinitions(): Promise<TemplateEditorItem[]>;
|
|
83
85
|
/** Base + headers, para o assinante de SSE reaproveitar a mesma configuração. */
|
|
84
86
|
resolveStreamRequest(): Promise<{
|
|
85
87
|
url: string;
|
package/dist/index.js
CHANGED
|
@@ -158,6 +158,13 @@ function createNotificationClient(config) {
|
|
|
158
158
|
if (!payload?.data) throw new Error("notification-client: restoreDefault n\xE3o devolveu o template");
|
|
159
159
|
return payload.data;
|
|
160
160
|
},
|
|
161
|
+
async listTemplateDefinitions() {
|
|
162
|
+
const payload = await request({
|
|
163
|
+
method: "GET",
|
|
164
|
+
path: "/notification-template-definitions"
|
|
165
|
+
});
|
|
166
|
+
return payload?.data ?? [];
|
|
167
|
+
},
|
|
161
168
|
async listTemplateVariables() {
|
|
162
169
|
const payload = await request({
|
|
163
170
|
method: "GET",
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/httpClient.ts","../src/deviceRegistration.ts","../src/streamSubscription.ts","../src/webPush.ts","../src/expoPush.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Cliente HTTP tipado pelas 13 rotas do módulo. **Isomórfico e sem DOM**: `fetch` é injetável e o\n * default é o global — é o que permite o mesmo pacote rodar no React Native do cawme e no PWA do\n * quickcart, sem o `-ui` (que tem `react-dom` e Tailwind) entrar no bundle mobile.\n */\n\nimport type {\n DeviceRegistration,\n NotificationPreference,\n NotificationSummary,\n NotificationTemplate,\n NotificationCategoryPolicy,\n TemplateVariableCatalog,\n UpsertTemplateBody,\n WebPushSubscription,\n SendPushDirectBody,\n SendPushDirectResult,\n BroadcastPushBody,\n BroadcastPushResult,\n} from '@adatechnology/notification-contracts'\n\nexport type NotificationClientConfig = {\n /** Base do host, sem barra final: `https://api.exemplo.com/v1`. */\n readonly baseUrl: string\n /**\n * Devolve o header de autorização a cada chamada — função, não string, porque o token do host\n * rotaciona e capturar o valor no boot deixaria o cliente com uma credencial vencida.\n */\n readonly getAuthHeaders?: () => Promise<Record<string, string>> | Record<string, string>\n readonly fetchImpl?: typeof fetch\n}\n\nexport type ListNotificationsOptions = {\n readonly category?: string\n readonly read?: boolean\n readonly cursor?: string\n readonly perPage?: number\n}\n\nexport type ListNotificationsPage = {\n readonly data: readonly NotificationSummary[]\n readonly nextCursor?: string\n readonly unreadCount: number\n}\n\nexport type RegisterDeviceInput = {\n readonly platform: 'ios' | 'android' | 'web'\n readonly driver: 'expo' | 'fcm'\n readonly token: string\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n}\n\nexport type NotificationApiError = Error & {\n readonly status: number\n readonly code: string\n readonly issues?: readonly { path: string; message: string }[]\n}\n\nfunction buildApiError(status: number, payload: unknown): NotificationApiError {\n const envelope = payload as {\n error?: { code?: string; message?: string; issues?: { path: string; message: string }[] }\n }\n const error = new Error(envelope?.error?.message ?? `Falha na requisição (${status}).`) as NotificationApiError\n return Object.assign(error, {\n status,\n code: envelope?.error?.code ?? 'NOTIFICATION_UNKNOWN_ERROR',\n issues: envelope?.error?.issues,\n })\n}\n\nexport type NotificationClient = {\n listNotifications(options?: ListNotificationsOptions): Promise<ListNotificationsPage>\n countUnread(): Promise<number>\n markAsRead(id: string): Promise<NotificationSummary>\n markAllAsRead(): Promise<number>\n deleteNotification(id: string): Promise<void>\n registerDevice(input: RegisterDeviceInput): Promise<DeviceRegistration>\n unregisterDevice(id: string): Promise<void>\n getPreferences(): Promise<readonly NotificationPreference[]>\n updatePreferences(preferences: readonly NotificationPreference[]): Promise<readonly NotificationPreference[]>\n /** O teto de canais da empresa por categoria — acima da preferência de quem recebe. */\n getCategoryPolicies(): Promise<readonly NotificationCategoryPolicy[]>\n /** Substitui a política das categorias enviadas; as demais ficam intactas. */\n updateCategoryPolicies(\n policies: readonly NotificationCategoryPolicy[],\n ): Promise<readonly NotificationCategoryPolicy[]>\n listTemplates(): Promise<readonly NotificationTemplate[]>\n /**\n * Cria uma VERSÃO nova do template, não edita a atual.\n *\n * O módulo versiona por `key`+`channel`+`locale`: a versão anterior fica legível para auditoria, e\n * a leitura só devolve a ativa mais alta. Então \"editar a copy\" e \"reverter\" são a mesma operação\n * — o que a tela de configuração precisa para alguém corrigir um texto sem medo.\n */\n upsertTemplate(input: UpsertTemplateBody): Promise<NotificationTemplate>\n /**\n * \"Remover\" é desativar: o servidor derruba todas as versões ativas da identidade e mantém as\n * linhas, porque entrega já enviada precisa continuar auditável com o texto que usou.\n */\n deactivateTemplate(id: string): Promise<void>\n /**\n * \"Restaurar padrão\": o servidor grava uma versão nova com o conteúdo embutido do modelo padrão\n * (`notification.standard-email`). 400 se o id não é dele; 409 se a restauração é recusada.\n */\n restoreDefault(id: string): Promise<NotificationTemplate>\n /** O catálogo de variáveis por chave — é o que a tela mostra como lista clicável. */\n listTemplateVariables(): Promise<TemplateVariableCatalog>\n /** Base + headers, para o assinante de SSE reaproveitar a mesma configuração. */\n resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }>\n /** Obtém a chave pública VAPID do servidor para inscrição Web Push no navegador */\n getVapidPublicKey(): Promise<string>\n /** Dispara uma notificação push direta (para token, user ou subscription) */\n sendPush(input: SendPushDirectBody): Promise<SendPushDirectResult>\n /** Dispara push em broadcast por tópico ou filtro */\n broadcastPush(input: BroadcastPushBody): Promise<BroadcastPushResult>\n /** Registra uma assinatura Web Push nativa (PWA) no backend */\n registerWebPush(\n subscription: WebPushSubscription,\n options?: { readonly appVersion?: string; readonly locale?: string; readonly timezone?: string },\n ): Promise<DeviceRegistration>\n}\n\nexport function createNotificationClient(config: NotificationClientConfig): NotificationClient {\n const fetchImpl = config.fetchImpl ?? fetch\n const baseUrl = config.baseUrl.endsWith('/') ? config.baseUrl.slice(0, -1) : config.baseUrl\n\n async function request<TResponse>(params: {\n method: string\n path: string\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown\n }): Promise<TResponse | undefined> {\n const fullPath = `${baseUrl}${params.path}`\n const isAbsolute = fullPath.startsWith('http://') || fullPath.startsWith('https://')\n const fallbackBase =\n typeof window !== 'undefined' && window.location?.origin ? window.location.origin : 'http://localhost'\n const url = new URL(fullPath, isAbsolute ? undefined : fallbackBase)\n for (const [key, value] of Object.entries(params.query ?? {})) {\n if (value !== undefined) url.searchParams.set(key, String(value))\n }\n\n const authHeaders = (await config.getAuthHeaders?.()) ?? {}\n const finalUrl = isAbsolute || typeof window !== 'undefined' ? url.toString() : `${url.pathname}${url.search}`\n const response = await fetchImpl(finalUrl, {\n method: params.method,\n headers: { ...(params.body === undefined ? {} : { 'Content-Type': 'application/json' }), ...authHeaders },\n body: params.body === undefined ? undefined : JSON.stringify(params.body),\n })\n\n if (response.status === 204) return undefined\n\n const text = await response.text()\n const payload: unknown = text === '' ? undefined : JSON.parse(text)\n if (!response.ok) throw buildApiError(response.status, payload)\n return payload as TResponse\n }\n\n return {\n async listNotifications(options): Promise<ListNotificationsPage> {\n const payload = await request<{\n data: NotificationSummary[]\n pagination: { nextCursor?: string }\n meta: { unreadCount: number }\n }>({\n method: 'GET',\n path: '/notifications',\n query: { category: options?.category, read: options?.read, cursor: options?.cursor, perPage: options?.perPage },\n })\n\n return {\n data: payload?.data ?? [],\n nextCursor: payload?.pagination.nextCursor,\n unreadCount: payload?.meta.unreadCount ?? 0,\n }\n },\n\n async countUnread(): Promise<number> {\n const payload = await request<{ data: { unreadCount: number } }>({\n method: 'GET',\n path: '/notifications/unread-count',\n })\n return payload?.data.unreadCount ?? 0\n },\n\n async markAsRead(id): Promise<NotificationSummary> {\n const payload = await request<{ data: NotificationSummary }>({\n method: 'PATCH',\n path: `/notifications/${encodeURIComponent(id)}/read`,\n })\n if (!payload) throw new Error('notification-client: resposta vazia em markAsRead')\n return payload.data\n },\n\n async markAllAsRead(): Promise<number> {\n const payload = await request<{ data: { updated: number } }>({ method: 'POST', path: '/notifications/read-all' })\n return payload?.data.updated ?? 0\n },\n\n async deleteNotification(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notifications/${encodeURIComponent(id)}` })\n },\n\n async registerDevice(input): Promise<DeviceRegistration> {\n const payload = await request<{ data: DeviceRegistration }>({\n method: 'POST',\n path: '/notification-devices',\n body: input,\n })\n if (!payload) throw new Error('notification-client: resposta vazia em registerDevice')\n return payload.data\n },\n\n async unregisterDevice(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notification-devices/${encodeURIComponent(id)}` })\n },\n\n async getPreferences(): Promise<readonly NotificationPreference[]> {\n const payload = await request<{ data: NotificationPreference[] }>({\n method: 'GET',\n path: '/notification-preferences',\n })\n return payload?.data ?? []\n },\n\n async updatePreferences(preferences): Promise<readonly NotificationPreference[]> {\n const payload = await request<{ data: NotificationPreference[] }>({\n method: 'PUT',\n path: '/notification-preferences',\n body: { preferences },\n })\n return payload?.data ?? []\n },\n\n async listTemplates(): Promise<readonly NotificationTemplate[]> {\n const payload = await request<{ data: NotificationTemplate[] }>({\n method: 'GET',\n path: '/notification-templates',\n })\n return payload?.data ?? []\n },\n\n async getCategoryPolicies(): Promise<readonly NotificationCategoryPolicy[]> {\n const payload = await request<{ data: NotificationCategoryPolicy[] }>({\n method: 'GET',\n path: '/notification-category-policies',\n })\n return payload?.data ?? []\n },\n\n async updateCategoryPolicies(policies): Promise<readonly NotificationCategoryPolicy[]> {\n const payload = await request<{ data: NotificationCategoryPolicy[] }>({\n method: 'PUT',\n path: '/notification-category-policies',\n body: { policies },\n })\n return payload?.data ?? []\n },\n\n async deactivateTemplate(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notification-templates/${encodeURIComponent(id)}` })\n },\n\n async restoreDefault(id): Promise<NotificationTemplate> {\n const payload = await request<{ data: NotificationTemplate }>({\n method: 'POST',\n path: `/notification-templates/${encodeURIComponent(id)}/restore-default`,\n })\n if (!payload?.data) throw new Error('notification-client: restoreDefault não devolveu o template')\n return payload.data\n },\n\n async listTemplateVariables(): Promise<TemplateVariableCatalog> {\n const payload = await request<{ data: TemplateVariableCatalog }>({\n method: 'GET',\n path: '/notification-template-variables',\n })\n return payload?.data ?? {}\n },\n\n async upsertTemplate(input: UpsertTemplateBody): Promise<NotificationTemplate> {\n const payload = await request<{ data: NotificationTemplate }>({\n method: 'POST',\n path: '/notification-templates',\n body: input,\n })\n // Sem fallback: a rota responde 201 com o template criado, e devolver `undefined as never`\n // aqui esconderia uma mudança de contrato até estourar na tela.\n if (!payload?.data) throw new Error('notification-client: upsertTemplate não devolveu o template')\n return payload.data\n },\n\n async resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }> {\n return { url: `${baseUrl}/notifications/stream`, headers: (await config.getAuthHeaders?.()) ?? {} }\n },\n\n async getVapidPublicKey(): Promise<string> {\n const payload = await request<{ data: { publicKey: string } }>({\n method: 'GET',\n path: '/push/vapid-public-key',\n })\n if (!payload?.data?.publicKey) throw new Error('notification-client: chave pública VAPID não retornada')\n return payload.data.publicKey\n },\n\n async sendPush(input: SendPushDirectBody): Promise<SendPushDirectResult> {\n const payload = await request<{ data: SendPushDirectResult }>({\n method: 'POST',\n path: '/push/send',\n body: input,\n })\n if (!payload?.data) throw new Error('notification-client: resposta vazia ao enviar push')\n return payload.data\n },\n\n async broadcastPush(input: BroadcastPushBody): Promise<BroadcastPushResult> {\n const payload = await request<{ data: BroadcastPushResult }>({\n method: 'POST',\n path: '/push/broadcast',\n body: input,\n })\n if (!payload?.data) throw new Error('notification-client: resposta vazia em broadcastPush')\n return payload.data\n },\n\n async registerWebPush(\n subscription: WebPushSubscription,\n options?: { readonly appVersion?: string; readonly locale?: string; readonly timezone?: string },\n ): Promise<DeviceRegistration> {\n const payload = await request<{ data: DeviceRegistration }>({\n method: 'POST',\n path: '/notification-devices',\n body: {\n platform: 'web',\n driver: 'webpush',\n token: JSON.stringify(subscription),\n appVersion: options?.appVersion,\n locale: options?.locale,\n timezone: options?.timezone,\n },\n })\n if (!payload?.data) throw new Error('notification-client: resposta vazia em registerWebPush')\n return payload.data\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Registro de dispositivo para push. **Não importa `expo-notifications` nem `firebase`**: recebe\n * `getToken` por injeção. É o que mantém o pacote isomórfico — o cawme passa o token do Expo, o\n * PWA do quickcart passa o do FCM web, e nenhum dos dois carrega o SDK do outro.\n */\n\nimport type { DeviceRegistration } from '@adatechnology/notification-contracts'\n\nimport type { NotificationClient, RegisterDeviceInput } from './httpClient'\n\nexport type DeviceRegistrationConfig = {\n readonly client: NotificationClient\n readonly driver: 'expo' | 'fcm'\n /** `undefined` = permissão negada ou indisponível; o registro é pulado sem erro. */\n getToken(): Promise<string | undefined>\n /** Persiste o id entre execuções, para o logout conseguir remover o device certo. */\n readonly storage?: DeviceRegistrationStorage\n}\n\n/** `AsyncStorage` do RN e `localStorage` do web satisfazem esta forma (via wrapper trivial). */\nexport type DeviceRegistrationStorage = {\n getItem(key: string): Promise<string | null> | string | null\n setItem(key: string, value: string): Promise<void> | void\n removeItem(key: string): Promise<void> | void\n}\n\nexport type RegisterOptions = {\n readonly platform: 'ios' | 'android' | 'web'\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n}\n\nexport type DeviceRegistrationHandle = {\n /** Idempotente: chamar de novo com o mesmo token reativa o registro em vez de duplicar. */\n register(options: RegisterOptions): Promise<DeviceRegistration | undefined>\n /** No logout — sem isto, o aparelho continuaria recebendo push do usuário anterior. */\n unregister(): Promise<void>\n}\n\nconst STORAGE_KEY = 'adatechnology:notification:device-id'\n\nexport function createDeviceRegistration(config: DeviceRegistrationConfig): DeviceRegistrationHandle {\n async function rememberDeviceId(deviceId: string): Promise<void> {\n await config.storage?.setItem(STORAGE_KEY, deviceId)\n }\n\n return {\n async register(options): Promise<DeviceRegistration | undefined> {\n const token = await config.getToken()\n // Permissão negada é o caminho normal, não erro: o usuário pode recusar push e o resto do\n // app continua funcionando (inbox e e-mail seguem).\n if (!token) return undefined\n\n const input: RegisterDeviceInput = {\n platform: options.platform,\n driver: config.driver,\n token,\n appVersion: options.appVersion,\n locale: options.locale,\n timezone: options.timezone,\n }\n\n const device = await config.client.registerDevice(input)\n await rememberDeviceId(device.id)\n return device\n },\n\n async unregister(): Promise<void> {\n const deviceId = await config.storage?.getItem(STORAGE_KEY)\n if (!deviceId) return\n\n await config.client.unregisterDevice(deviceId)\n await config.storage?.removeItem(STORAGE_KEY)\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Assinatura do SSE do inbox.\n *\n * **Não usa `EventSource`**, apesar de ser a API óbvia: `EventSource` não aceita headers, e a\n * autenticação do host é `Authorization: Bearer`. Passar token por query string violaria\n * `security.md` §Privacy (credencial em URL vaza em log de proxy e histórico). Além disso o React\n * Native não tem `EventSource` nativo. Ler o corpo por `fetch` + `ReadableStream` resolve os dois\n * de uma vez, e é o que roda igual no web e no RN moderno.\n */\n\nexport type NotificationStreamEvent = {\n readonly event: string\n readonly data: unknown\n}\n\nexport type SubscribeToNotificationStreamParams = {\n readonly url: string\n readonly headers: Record<string, string>\n readonly onEvent: (event: NotificationStreamEvent) => void\n readonly onError?: (error: Error) => void\n readonly fetchImpl?: typeof fetch\n /** Reconexão com backoff; `0` desliga (o chamador cuida). */\n readonly reconnectDelayMs?: number\n}\n\nexport type NotificationStreamSubscription = {\n close(): void\n}\n\nconst DEFAULT_RECONNECT_DELAY_MS = 3000\n\nfunction parseSseBlock(block: string): NotificationStreamEvent | undefined {\n let eventName = 'message'\n const dataLines: string[] = []\n\n for (const line of block.split('\\n')) {\n // Comentário SSE — é o heartbeat do servidor, e não deve virar evento no cliente.\n if (line.startsWith(':')) continue\n if (line.startsWith('event:')) eventName = line.slice('event:'.length).trim()\n if (line.startsWith('data:')) dataLines.push(line.slice('data:'.length).trim())\n }\n\n if (dataLines.length === 0) return undefined\n\n const raw = dataLines.join('\\n')\n try {\n return { event: eventName, data: JSON.parse(raw) }\n } catch {\n return { event: eventName, data: raw }\n }\n}\n\nexport function subscribeToNotificationStream(\n params: SubscribeToNotificationStreamParams,\n): NotificationStreamSubscription {\n const fetchImpl = params.fetchImpl ?? fetch\n const controller = new AbortController()\n let closed = false\n\n async function connect(): Promise<void> {\n const response = await fetchImpl(params.url, {\n headers: { ...params.headers, Accept: 'text/event-stream' },\n signal: controller.signal,\n })\n\n if (!response.ok || !response.body) throw new Error(`SSE falhou com status ${response.status}`)\n\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n\n for (;;) {\n const { value, done } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n // Eventos SSE são separados por linha em branco; o resto fica no buffer porque um chunk\n // de rede pode cortar um evento no meio.\n const blocks = buffer.split('\\n\\n')\n buffer = blocks.pop() ?? ''\n\n for (const block of blocks) {\n const event = parseSseBlock(block)\n if (event) params.onEvent(event)\n }\n }\n }\n\n async function runWithReconnect(): Promise<void> {\n const delay = params.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS\n\n while (!closed) {\n try {\n await connect()\n } catch (error) {\n if (closed) return\n params.onError?.(error instanceof Error ? error : new Error(String(error)))\n }\n\n // Conexão encerrada pelo servidor (deploy, timeout de proxy) é o caso comum — reconectar é\n // o comportamento certo, e sem `delay` viraria laço apertado contra um servidor caído.\n if (closed || delay === 0) return\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n }\n\n void runWithReconnect()\n\n return {\n close(): void {\n closed = true\n controller.abort()\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Helpers isomórficos para Web Push nativo (W3C Push API) em PWAs.\n * Não depende de Firebase nem de bibliotecas externas: funciona nativamente no Chrome,\n * Firefox, Edge e Safari (iOS 16.4+ e macOS).\n */\n\nimport type { WebPushSubscription } from '@adatechnology/notification-contracts'\n\nexport type SubscribeWebPushOptions = {\n readonly vapidPublicKey: string\n readonly serviceWorkerRegistration?: ServiceWorkerRegistration\n}\n\n/**\n * Converte chave pública VAPID em base64url para Uint8Array.\n * Exigido pelo navegador em `pushManager.subscribe({ applicationServerKey })`.\n */\nexport function urlBase64ToUint8Array(base64String: string): Uint8Array {\n const padding = '='.repeat((4 - (base64String.length % 4)) % 4)\n const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/')\n const rawData = atob(base64)\n const outputArray = new Uint8Array(rawData.length)\n\n for (let i = 0; i < rawData.length; ++i) {\n outputArray[i] = rawData.charCodeAt(i)\n }\n return outputArray\n}\n\nexport function arrayBufferToBase64Url(buffer: ArrayBufferLike | ArrayBuffer | null): string {\n if (!buffer) return ''\n const bytes = new Uint8Array(buffer as ArrayBuffer)\n let binary = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n binary += String.fromCharCode(bytes[i])\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n/**\n * Verifica se o ambiente de execução suporta Web Push nativo via Service Worker.\n */\nexport function isWebPushSupported(): boolean {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') return false\n return 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window\n}\n\n/**\n * Inscreve o navegador no Push Service nativo usando as chaves VAPID fornecidas.\n * Retorna `undefined` caso a permissão seja negada pelo usuário (caminho normal, sem lançar erro).\n */\nexport async function subscribeWebPush(options: SubscribeWebPushOptions): Promise<WebPushSubscription | undefined> {\n if (!isWebPushSupported()) return undefined\n\n if (Notification.permission === 'default') {\n const permission = await Notification.requestPermission()\n if (permission !== 'granted') return undefined\n } else if (Notification.permission !== 'granted') {\n return undefined\n }\n\n const registration = options.serviceWorkerRegistration ?? (await navigator.serviceWorker.ready)\n const applicationServerKey = urlBase64ToUint8Array(options.vapidPublicKey)\n\n let subscription = await registration.pushManager.getSubscription()\n if (!subscription) {\n subscription = await registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: applicationServerKey as unknown as BufferSource,\n })\n }\n\n const p256dh = arrayBufferToBase64Url(subscription.getKey('p256dh'))\n const auth = arrayBufferToBase64Url(subscription.getKey('auth'))\n\n return {\n endpoint: subscription.endpoint,\n keys: { p256dh, auth },\n expirationTime: subscription.expirationTime,\n }\n}\n\n/**\n * Remove a inscrição ativa de push no navegador.\n */\nexport async function unsubscribeWebPush(serviceWorkerRegistration?: ServiceWorkerRegistration): Promise<boolean> {\n if (!isWebPushSupported()) return false\n\n const registration = serviceWorkerRegistration ?? (await navigator.serviceWorker.ready)\n const subscription = await registration.pushManager.getSubscription()\n if (!subscription) return false\n\n return subscription.unsubscribe()\n}\n\n/**\n * Obtém a inscrição ativa de push no navegador se já existir.\n */\nexport async function getWebPushSubscription(\n serviceWorkerRegistration?: ServiceWorkerRegistration,\n): Promise<WebPushSubscription | undefined> {\n if (!isWebPushSupported()) return undefined\n\n const registration = serviceWorkerRegistration ?? (await navigator.serviceWorker.ready)\n const subscription = await registration.pushManager.getSubscription()\n if (!subscription) return undefined\n\n const p256dh = arrayBufferToBase64Url(subscription.getKey('p256dh'))\n const auth = arrayBufferToBase64Url(subscription.getKey('auth'))\n\n return {\n endpoint: subscription.endpoint,\n keys: { p256dh, auth },\n expirationTime: subscription.expirationTime,\n }\n}\n\n/**\n * Retorna o script padrão do Service Worker para manipulação de notificações em PWAs.\n */\nexport function getStandardWebPushServiceWorkerScript(): string {\n return `\nself.addEventListener('push', (event) => {\n if (!event.data) return;\n let payload;\n try {\n payload = event.data.json();\n } catch {\n payload = { title: 'Notificação', body: event.data.text() };\n }\n\n const title = payload.title || 'Nova Notificação';\n const options = {\n body: payload.body || '',\n icon: payload.icon || '/pwa-192x192.png',\n badge: payload.badge || '/badge-72x72.png',\n tag: payload.tag,\n data: payload.data || { url: payload.url || '/' },\n };\n\n event.waitUntil(self.registration.showNotification(title, options));\n});\n\nself.addEventListener('notificationclick', (event) => {\n event.notification.close();\n const targetUrl = event.notification.data?.url || '/';\n\n event.waitUntil(\n clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {\n for (const client of clientList) {\n if (client.url === targetUrl && 'focus' in client) {\n return client.focus();\n }\n }\n if (clients.openWindow) {\n return clients.openWindow(targetUrl);\n }\n })\n );\n});\n`.trim()\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Helper de push para React Native com Expo.\n * **Não importa `expo-notifications` estaticamente**: recebe o módulo por injeção\n * (duck-typing) para não poluir nem quebrar o bundle web/PWA.\n */\n\nimport {\n createDeviceRegistration,\n type DeviceRegistrationHandle,\n type DeviceRegistrationStorage,\n} from './deviceRegistration'\nimport type { NotificationClient } from './httpClient'\n\nexport type ExpoPermissionResponse = {\n readonly status: string\n readonly granted: boolean\n}\n\nexport type ExpoPushTokenResult = {\n readonly data: string\n}\n\nexport interface ExpoNotificationsModule {\n getPermissionsAsync(): Promise<ExpoPermissionResponse>\n requestPermissionsAsync(): Promise<ExpoPermissionResponse>\n getExpoPushTokenAsync(options?: { projectId?: string }): Promise<ExpoPushTokenResult>\n setNotificationChannelAsync?(\n channelId: string,\n channel: {\n name: string\n importance: number\n sound?: boolean\n vibrationPattern?: number[]\n },\n ): Promise<unknown>\n}\n\nexport type GetExpoPushTokenOptions = {\n readonly module: ExpoNotificationsModule\n readonly projectId?: string\n readonly channelId?: string\n readonly channelName?: string\n}\n\n/**\n * Solicita permissões e obtém o Expo Push Token.\n * Se a permissão for negada, devolve `undefined` (caminho normal, sem erro).\n */\nexport async function getExpoPushToken(options: GetExpoPushTokenOptions): Promise<string | undefined> {\n const { module } = options\n\n const currentPerms = await module.getPermissionsAsync()\n let isGranted = currentPerms.granted\n\n if (!isGranted) {\n const requested = await module.requestPermissionsAsync()\n isGranted = requested.granted\n }\n\n if (!isGranted) return undefined\n\n if (typeof module.setNotificationChannelAsync === 'function') {\n await module.setNotificationChannelAsync(options.channelId ?? 'default', {\n name: options.channelName ?? 'Geral',\n importance: 4, // Android IMPORTANCE_HIGH\n sound: true,\n })\n }\n\n const tokenResult = await module.getExpoPushTokenAsync({\n projectId: options.projectId,\n })\n\n return tokenResult.data\n}\n\nexport type CreateExpoPushRegistrationConfig = {\n readonly client: NotificationClient\n readonly module: ExpoNotificationsModule\n readonly projectId?: string\n readonly storage?: DeviceRegistrationStorage\n}\n\n/**\n * Cria o ciclo de vida completo de registro do dispositivo Expo integrado ao NotificationClient.\n */\nexport function createExpoPushRegistration(config: CreateExpoPushRegistrationConfig): DeviceRegistrationHandle {\n return createDeviceRegistration({\n client: config.client,\n driver: 'expo',\n storage: config.storage,\n getToken: () => getExpoPushToken({ module: config.module, projectId: config.projectId }),\n })\n}\n"],"mappings":";;;;AA8DA,SAASA,cAAcC,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EACrB,CAAA;AAEA,SAAOF,YAAYG;AACrB;AA1BsBnB;AAsCf,SAASoB,2BAA2BC,QAAwC;AACjF,SAAOC,yBAAyB;IAC9BC,QAAQF,OAAOE;IACfC,QAAQ;IACRC,SAASJ,OAAOI;IAChBC,UAAU,6BAAM1B,iBAAiB;MAAEE,QAAQmB,OAAOnB;MAAQgB,WAAWG,OAAOH;IAAU,CAAA,GAA5E;EACZ,CAAA;AACF;AAPgBE;","names":["buildApiError","status","payload","envelope","error","Error","message","Object","assign","code","issues","createNotificationClient","config","fetchImpl","fetch","baseUrl","endsWith","slice","request","params","fullPath","path","isAbsolute","startsWith","fallbackBase","window","location","origin","url","URL","undefined","key","value","entries","query","searchParams","set","String","authHeaders","getAuthHeaders","finalUrl","toString","pathname","search","response","method","headers","body","JSON","stringify","text","parse","ok","listNotifications","options","category","read","cursor","perPage","data","nextCursor","pagination","unreadCount","meta","countUnread","markAsRead","id","encodeURIComponent","markAllAsRead","updated","deleteNotification","registerDevice","input","unregisterDevice","getPreferences","updatePreferences","preferences","listTemplates","getCategoryPolicies","updateCategoryPolicies","policies","deactivateTemplate","restoreDefault","listTemplateVariables","upsertTemplate","resolveStreamRequest","getVapidPublicKey","publicKey","sendPush","broadcastPush","registerWebPush","subscription","platform","driver","token","appVersion","locale","timezone","STORAGE_KEY","createDeviceRegistration","config","rememberDeviceId","deviceId","storage","setItem","register","options","token","getToken","undefined","input","platform","driver","appVersion","locale","timezone","device","client","registerDevice","id","unregister","getItem","unregisterDevice","removeItem","DEFAULT_RECONNECT_DELAY_MS","parseSseBlock","block","eventName","dataLines","line","split","startsWith","slice","length","trim","push","undefined","raw","join","event","data","JSON","parse","subscribeToNotificationStream","params","fetchImpl","fetch","controller","AbortController","closed","connect","response","url","headers","Accept","signal","ok","body","Error","status","reader","getReader","decoder","TextDecoder","buffer","value","done","read","decode","stream","blocks","pop","onEvent","runWithReconnect","delay","reconnectDelayMs","error","onError","String","Promise","resolve","setTimeout","close","abort","urlBase64ToUint8Array","base64String","padding","repeat","length","base64","replace","rawData","atob","outputArray","Uint8Array","i","charCodeAt","arrayBufferToBase64Url","buffer","bytes","binary","byteLength","String","fromCharCode","btoa","isWebPushSupported","window","navigator","subscribeWebPush","options","undefined","Notification","permission","requestPermission","registration","serviceWorkerRegistration","serviceWorker","ready","applicationServerKey","vapidPublicKey","subscription","pushManager","getSubscription","subscribe","userVisibleOnly","p256dh","getKey","auth","endpoint","keys","expirationTime","unsubscribeWebPush","unsubscribe","getWebPushSubscription","getStandardWebPushServiceWorkerScript","trim","getExpoPushToken","options","module","currentPerms","getPermissionsAsync","isGranted","granted","requested","requestPermissionsAsync","undefined","setNotificationChannelAsync","channelId","name","channelName","importance","sound","tokenResult","getExpoPushTokenAsync","projectId","data","createExpoPushRegistration","config","createDeviceRegistration","client","driver","storage","getToken"]}
|
|
1
|
+
{"version":3,"sources":["../src/httpClient.ts","../src/deviceRegistration.ts","../src/streamSubscription.ts","../src/webPush.ts","../src/expoPush.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Cliente HTTP tipado pelas 13 rotas do módulo. **Isomórfico e sem DOM**: `fetch` é injetável e o\n * default é o global — é o que permite o mesmo pacote rodar no React Native do cawme e no PWA do\n * quickcart, sem o `-ui` (que tem `react-dom` e Tailwind) entrar no bundle mobile.\n */\n\nimport type {\n DeviceRegistration,\n NotificationPreference,\n NotificationSummary,\n NotificationTemplate,\n NotificationCategoryPolicy,\n TemplateEditorItem,\n TemplateVariableCatalog,\n UpsertTemplateBody,\n WebPushSubscription,\n SendPushDirectBody,\n SendPushDirectResult,\n BroadcastPushBody,\n BroadcastPushResult,\n} from '@adatechnology/notification-contracts'\n\nexport type NotificationClientConfig = {\n /** Base do host, sem barra final: `https://api.exemplo.com/v1`. */\n readonly baseUrl: string\n /**\n * Devolve o header de autorização a cada chamada — função, não string, porque o token do host\n * rotaciona e capturar o valor no boot deixaria o cliente com uma credencial vencida.\n */\n readonly getAuthHeaders?: () => Promise<Record<string, string>> | Record<string, string>\n readonly fetchImpl?: typeof fetch\n}\n\nexport type ListNotificationsOptions = {\n readonly category?: string\n readonly read?: boolean\n readonly cursor?: string\n readonly perPage?: number\n}\n\nexport type ListNotificationsPage = {\n readonly data: readonly NotificationSummary[]\n readonly nextCursor?: string\n readonly unreadCount: number\n}\n\nexport type RegisterDeviceInput = {\n readonly platform: 'ios' | 'android' | 'web'\n readonly driver: 'expo' | 'fcm'\n readonly token: string\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n}\n\nexport type NotificationApiError = Error & {\n readonly status: number\n readonly code: string\n readonly issues?: readonly { path: string; message: string }[]\n}\n\nfunction buildApiError(status: number, payload: unknown): NotificationApiError {\n const envelope = payload as {\n error?: { code?: string; message?: string; issues?: { path: string; message: string }[] }\n }\n const error = new Error(envelope?.error?.message ?? `Falha na requisição (${status}).`) as NotificationApiError\n return Object.assign(error, {\n status,\n code: envelope?.error?.code ?? 'NOTIFICATION_UNKNOWN_ERROR',\n issues: envelope?.error?.issues,\n })\n}\n\nexport type NotificationClient = {\n listNotifications(options?: ListNotificationsOptions): Promise<ListNotificationsPage>\n countUnread(): Promise<number>\n markAsRead(id: string): Promise<NotificationSummary>\n markAllAsRead(): Promise<number>\n deleteNotification(id: string): Promise<void>\n registerDevice(input: RegisterDeviceInput): Promise<DeviceRegistration>\n unregisterDevice(id: string): Promise<void>\n getPreferences(): Promise<readonly NotificationPreference[]>\n updatePreferences(preferences: readonly NotificationPreference[]): Promise<readonly NotificationPreference[]>\n /** O teto de canais da empresa por categoria — acima da preferência de quem recebe. */\n getCategoryPolicies(): Promise<readonly NotificationCategoryPolicy[]>\n /** Substitui a política das categorias enviadas; as demais ficam intactas. */\n updateCategoryPolicies(\n policies: readonly NotificationCategoryPolicy[],\n ): Promise<readonly NotificationCategoryPolicy[]>\n listTemplates(): Promise<readonly NotificationTemplate[]>\n /**\n * Cria uma VERSÃO nova do template, não edita a atual.\n *\n * O módulo versiona por `key`+`channel`+`locale`: a versão anterior fica legível para auditoria, e\n * a leitura só devolve a ativa mais alta. Então \"editar a copy\" e \"reverter\" são a mesma operação\n * — o que a tela de configuração precisa para alguém corrigir um texto sem medo.\n */\n upsertTemplate(input: UpsertTemplateBody): Promise<NotificationTemplate>\n /**\n * \"Remover\" é desativar: o servidor derruba todas as versões ativas da identidade e mantém as\n * linhas, porque entrega já enviada precisa continuar auditável com o texto que usou.\n */\n deactivateTemplate(id: string): Promise<void>\n /**\n * \"Restaurar padrão\": o servidor grava uma versão nova com o conteúdo embutido do modelo padrão\n * (`notification.standard-email`). 400 se o id não é dele; 409 se a restauração é recusada.\n */\n restoreDefault(id: string): Promise<NotificationTemplate>\n /** O catálogo de variáveis por chave — é o que a tela mostra como lista clicável. */\n listTemplateVariables(): Promise<TemplateVariableCatalog>\n /** Templates declarados pelo host: rótulo, variáveis, texto padrão e a versão atual (para o editor). */\n listTemplateDefinitions(): Promise<TemplateEditorItem[]>\n /** Base + headers, para o assinante de SSE reaproveitar a mesma configuração. */\n resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }>\n /** Obtém a chave pública VAPID do servidor para inscrição Web Push no navegador */\n getVapidPublicKey(): Promise<string>\n /** Dispara uma notificação push direta (para token, user ou subscription) */\n sendPush(input: SendPushDirectBody): Promise<SendPushDirectResult>\n /** Dispara push em broadcast por tópico ou filtro */\n broadcastPush(input: BroadcastPushBody): Promise<BroadcastPushResult>\n /** Registra uma assinatura Web Push nativa (PWA) no backend */\n registerWebPush(\n subscription: WebPushSubscription,\n options?: { readonly appVersion?: string; readonly locale?: string; readonly timezone?: string },\n ): Promise<DeviceRegistration>\n}\n\nexport function createNotificationClient(config: NotificationClientConfig): NotificationClient {\n const fetchImpl = config.fetchImpl ?? fetch\n const baseUrl = config.baseUrl.endsWith('/') ? config.baseUrl.slice(0, -1) : config.baseUrl\n\n async function request<TResponse>(params: {\n method: string\n path: string\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown\n }): Promise<TResponse | undefined> {\n const fullPath = `${baseUrl}${params.path}`\n const isAbsolute = fullPath.startsWith('http://') || fullPath.startsWith('https://')\n const fallbackBase =\n typeof window !== 'undefined' && window.location?.origin ? window.location.origin : 'http://localhost'\n const url = new URL(fullPath, isAbsolute ? undefined : fallbackBase)\n for (const [key, value] of Object.entries(params.query ?? {})) {\n if (value !== undefined) url.searchParams.set(key, String(value))\n }\n\n const authHeaders = (await config.getAuthHeaders?.()) ?? {}\n const finalUrl = isAbsolute || typeof window !== 'undefined' ? url.toString() : `${url.pathname}${url.search}`\n const response = await fetchImpl(finalUrl, {\n method: params.method,\n headers: { ...(params.body === undefined ? {} : { 'Content-Type': 'application/json' }), ...authHeaders },\n body: params.body === undefined ? undefined : JSON.stringify(params.body),\n })\n\n if (response.status === 204) return undefined\n\n const text = await response.text()\n const payload: unknown = text === '' ? undefined : JSON.parse(text)\n if (!response.ok) throw buildApiError(response.status, payload)\n return payload as TResponse\n }\n\n return {\n async listNotifications(options): Promise<ListNotificationsPage> {\n const payload = await request<{\n data: NotificationSummary[]\n pagination: { nextCursor?: string }\n meta: { unreadCount: number }\n }>({\n method: 'GET',\n path: '/notifications',\n query: { category: options?.category, read: options?.read, cursor: options?.cursor, perPage: options?.perPage },\n })\n\n return {\n data: payload?.data ?? [],\n nextCursor: payload?.pagination.nextCursor,\n unreadCount: payload?.meta.unreadCount ?? 0,\n }\n },\n\n async countUnread(): Promise<number> {\n const payload = await request<{ data: { unreadCount: number } }>({\n method: 'GET',\n path: '/notifications/unread-count',\n })\n return payload?.data.unreadCount ?? 0\n },\n\n async markAsRead(id): Promise<NotificationSummary> {\n const payload = await request<{ data: NotificationSummary }>({\n method: 'PATCH',\n path: `/notifications/${encodeURIComponent(id)}/read`,\n })\n if (!payload) throw new Error('notification-client: resposta vazia em markAsRead')\n return payload.data\n },\n\n async markAllAsRead(): Promise<number> {\n const payload = await request<{ data: { updated: number } }>({ method: 'POST', path: '/notifications/read-all' })\n return payload?.data.updated ?? 0\n },\n\n async deleteNotification(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notifications/${encodeURIComponent(id)}` })\n },\n\n async registerDevice(input): Promise<DeviceRegistration> {\n const payload = await request<{ data: DeviceRegistration }>({\n method: 'POST',\n path: '/notification-devices',\n body: input,\n })\n if (!payload) throw new Error('notification-client: resposta vazia em registerDevice')\n return payload.data\n },\n\n async unregisterDevice(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notification-devices/${encodeURIComponent(id)}` })\n },\n\n async getPreferences(): Promise<readonly NotificationPreference[]> {\n const payload = await request<{ data: NotificationPreference[] }>({\n method: 'GET',\n path: '/notification-preferences',\n })\n return payload?.data ?? []\n },\n\n async updatePreferences(preferences): Promise<readonly NotificationPreference[]> {\n const payload = await request<{ data: NotificationPreference[] }>({\n method: 'PUT',\n path: '/notification-preferences',\n body: { preferences },\n })\n return payload?.data ?? []\n },\n\n async listTemplates(): Promise<readonly NotificationTemplate[]> {\n const payload = await request<{ data: NotificationTemplate[] }>({\n method: 'GET',\n path: '/notification-templates',\n })\n return payload?.data ?? []\n },\n\n async getCategoryPolicies(): Promise<readonly NotificationCategoryPolicy[]> {\n const payload = await request<{ data: NotificationCategoryPolicy[] }>({\n method: 'GET',\n path: '/notification-category-policies',\n })\n return payload?.data ?? []\n },\n\n async updateCategoryPolicies(policies): Promise<readonly NotificationCategoryPolicy[]> {\n const payload = await request<{ data: NotificationCategoryPolicy[] }>({\n method: 'PUT',\n path: '/notification-category-policies',\n body: { policies },\n })\n return payload?.data ?? []\n },\n\n async deactivateTemplate(id): Promise<void> {\n await request({ method: 'DELETE', path: `/notification-templates/${encodeURIComponent(id)}` })\n },\n\n async restoreDefault(id): Promise<NotificationTemplate> {\n const payload = await request<{ data: NotificationTemplate }>({\n method: 'POST',\n path: `/notification-templates/${encodeURIComponent(id)}/restore-default`,\n })\n if (!payload?.data) throw new Error('notification-client: restoreDefault não devolveu o template')\n return payload.data\n },\n\n async listTemplateDefinitions(): Promise<TemplateEditorItem[]> {\n const payload = await request<{ data: TemplateEditorItem[] }>({\n method: 'GET',\n path: '/notification-template-definitions',\n })\n return payload?.data ?? []\n },\n\n async listTemplateVariables(): Promise<TemplateVariableCatalog> {\n const payload = await request<{ data: TemplateVariableCatalog }>({\n method: 'GET',\n path: '/notification-template-variables',\n })\n return payload?.data ?? {}\n },\n\n async upsertTemplate(input: UpsertTemplateBody): Promise<NotificationTemplate> {\n const payload = await request<{ data: NotificationTemplate }>({\n method: 'POST',\n path: '/notification-templates',\n body: input,\n })\n // Sem fallback: a rota responde 201 com o template criado, e devolver `undefined as never`\n // aqui esconderia uma mudança de contrato até estourar na tela.\n if (!payload?.data) throw new Error('notification-client: upsertTemplate não devolveu o template')\n return payload.data\n },\n\n async resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }> {\n return { url: `${baseUrl}/notifications/stream`, headers: (await config.getAuthHeaders?.()) ?? {} }\n },\n\n async getVapidPublicKey(): Promise<string> {\n const payload = await request<{ data: { publicKey: string } }>({\n method: 'GET',\n path: '/push/vapid-public-key',\n })\n if (!payload?.data?.publicKey) throw new Error('notification-client: chave pública VAPID não retornada')\n return payload.data.publicKey\n },\n\n async sendPush(input: SendPushDirectBody): Promise<SendPushDirectResult> {\n const payload = await request<{ data: SendPushDirectResult }>({\n method: 'POST',\n path: '/push/send',\n body: input,\n })\n if (!payload?.data) throw new Error('notification-client: resposta vazia ao enviar push')\n return payload.data\n },\n\n async broadcastPush(input: BroadcastPushBody): Promise<BroadcastPushResult> {\n const payload = await request<{ data: BroadcastPushResult }>({\n method: 'POST',\n path: '/push/broadcast',\n body: input,\n })\n if (!payload?.data) throw new Error('notification-client: resposta vazia em broadcastPush')\n return payload.data\n },\n\n async registerWebPush(\n subscription: WebPushSubscription,\n options?: { readonly appVersion?: string; readonly locale?: string; readonly timezone?: string },\n ): Promise<DeviceRegistration> {\n const payload = await request<{ data: DeviceRegistration }>({\n method: 'POST',\n path: '/notification-devices',\n body: {\n platform: 'web',\n driver: 'webpush',\n token: JSON.stringify(subscription),\n appVersion: options?.appVersion,\n locale: options?.locale,\n timezone: options?.timezone,\n },\n })\n if (!payload?.data) throw new Error('notification-client: resposta vazia em registerWebPush')\n return payload.data\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Registro de dispositivo para push. **Não importa `expo-notifications` nem `firebase`**: recebe\n * `getToken` por injeção. É o que mantém o pacote isomórfico — o cawme passa o token do Expo, o\n * PWA do quickcart passa o do FCM web, e nenhum dos dois carrega o SDK do outro.\n */\n\nimport type { DeviceRegistration } from '@adatechnology/notification-contracts'\n\nimport type { NotificationClient, RegisterDeviceInput } from './httpClient'\n\nexport type DeviceRegistrationConfig = {\n readonly client: NotificationClient\n readonly driver: 'expo' | 'fcm'\n /** `undefined` = permissão negada ou indisponível; o registro é pulado sem erro. */\n getToken(): Promise<string | undefined>\n /** Persiste o id entre execuções, para o logout conseguir remover o device certo. */\n readonly storage?: DeviceRegistrationStorage\n}\n\n/** `AsyncStorage` do RN e `localStorage` do web satisfazem esta forma (via wrapper trivial). */\nexport type DeviceRegistrationStorage = {\n getItem(key: string): Promise<string | null> | string | null\n setItem(key: string, value: string): Promise<void> | void\n removeItem(key: string): Promise<void> | void\n}\n\nexport type RegisterOptions = {\n readonly platform: 'ios' | 'android' | 'web'\n readonly appVersion?: string\n readonly locale?: string\n readonly timezone?: string\n}\n\nexport type DeviceRegistrationHandle = {\n /** Idempotente: chamar de novo com o mesmo token reativa o registro em vez de duplicar. */\n register(options: RegisterOptions): Promise<DeviceRegistration | undefined>\n /** No logout — sem isto, o aparelho continuaria recebendo push do usuário anterior. */\n unregister(): Promise<void>\n}\n\nconst STORAGE_KEY = 'adatechnology:notification:device-id'\n\nexport function createDeviceRegistration(config: DeviceRegistrationConfig): DeviceRegistrationHandle {\n async function rememberDeviceId(deviceId: string): Promise<void> {\n await config.storage?.setItem(STORAGE_KEY, deviceId)\n }\n\n return {\n async register(options): Promise<DeviceRegistration | undefined> {\n const token = await config.getToken()\n // Permissão negada é o caminho normal, não erro: o usuário pode recusar push e o resto do\n // app continua funcionando (inbox e e-mail seguem).\n if (!token) return undefined\n\n const input: RegisterDeviceInput = {\n platform: options.platform,\n driver: config.driver,\n token,\n appVersion: options.appVersion,\n locale: options.locale,\n timezone: options.timezone,\n }\n\n const device = await config.client.registerDevice(input)\n await rememberDeviceId(device.id)\n return device\n },\n\n async unregister(): Promise<void> {\n const deviceId = await config.storage?.getItem(STORAGE_KEY)\n if (!deviceId) return\n\n await config.client.unregisterDevice(deviceId)\n await config.storage?.removeItem(STORAGE_KEY)\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Assinatura do SSE do inbox.\n *\n * **Não usa `EventSource`**, apesar de ser a API óbvia: `EventSource` não aceita headers, e a\n * autenticação do host é `Authorization: Bearer`. Passar token por query string violaria\n * `security.md` §Privacy (credencial em URL vaza em log de proxy e histórico). Além disso o React\n * Native não tem `EventSource` nativo. Ler o corpo por `fetch` + `ReadableStream` resolve os dois\n * de uma vez, e é o que roda igual no web e no RN moderno.\n */\n\nexport type NotificationStreamEvent = {\n readonly event: string\n readonly data: unknown\n}\n\nexport type SubscribeToNotificationStreamParams = {\n readonly url: string\n readonly headers: Record<string, string>\n readonly onEvent: (event: NotificationStreamEvent) => void\n readonly onError?: (error: Error) => void\n readonly fetchImpl?: typeof fetch\n /** Reconexão com backoff; `0` desliga (o chamador cuida). */\n readonly reconnectDelayMs?: number\n}\n\nexport type NotificationStreamSubscription = {\n close(): void\n}\n\nconst DEFAULT_RECONNECT_DELAY_MS = 3000\n\nfunction parseSseBlock(block: string): NotificationStreamEvent | undefined {\n let eventName = 'message'\n const dataLines: string[] = []\n\n for (const line of block.split('\\n')) {\n // Comentário SSE — é o heartbeat do servidor, e não deve virar evento no cliente.\n if (line.startsWith(':')) continue\n if (line.startsWith('event:')) eventName = line.slice('event:'.length).trim()\n if (line.startsWith('data:')) dataLines.push(line.slice('data:'.length).trim())\n }\n\n if (dataLines.length === 0) return undefined\n\n const raw = dataLines.join('\\n')\n try {\n return { event: eventName, data: JSON.parse(raw) }\n } catch {\n return { event: eventName, data: raw }\n }\n}\n\nexport function subscribeToNotificationStream(\n params: SubscribeToNotificationStreamParams,\n): NotificationStreamSubscription {\n const fetchImpl = params.fetchImpl ?? fetch\n const controller = new AbortController()\n let closed = false\n\n async function connect(): Promise<void> {\n const response = await fetchImpl(params.url, {\n headers: { ...params.headers, Accept: 'text/event-stream' },\n signal: controller.signal,\n })\n\n if (!response.ok || !response.body) throw new Error(`SSE falhou com status ${response.status}`)\n\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n\n for (;;) {\n const { value, done } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n // Eventos SSE são separados por linha em branco; o resto fica no buffer porque um chunk\n // de rede pode cortar um evento no meio.\n const blocks = buffer.split('\\n\\n')\n buffer = blocks.pop() ?? ''\n\n for (const block of blocks) {\n const event = parseSseBlock(block)\n if (event) params.onEvent(event)\n }\n }\n }\n\n async function runWithReconnect(): Promise<void> {\n const delay = params.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS\n\n while (!closed) {\n try {\n await connect()\n } catch (error) {\n if (closed) return\n params.onError?.(error instanceof Error ? error : new Error(String(error)))\n }\n\n // Conexão encerrada pelo servidor (deploy, timeout de proxy) é o caso comum — reconectar é\n // o comportamento certo, e sem `delay` viraria laço apertado contra um servidor caído.\n if (closed || delay === 0) return\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n }\n\n void runWithReconnect()\n\n return {\n close(): void {\n closed = true\n controller.abort()\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Helpers isomórficos para Web Push nativo (W3C Push API) em PWAs.\n * Não depende de Firebase nem de bibliotecas externas: funciona nativamente no Chrome,\n * Firefox, Edge e Safari (iOS 16.4+ e macOS).\n */\n\nimport type { WebPushSubscription } from '@adatechnology/notification-contracts'\n\nexport type SubscribeWebPushOptions = {\n readonly vapidPublicKey: string\n readonly serviceWorkerRegistration?: ServiceWorkerRegistration\n}\n\n/**\n * Converte chave pública VAPID em base64url para Uint8Array.\n * Exigido pelo navegador em `pushManager.subscribe({ applicationServerKey })`.\n */\nexport function urlBase64ToUint8Array(base64String: string): Uint8Array {\n const padding = '='.repeat((4 - (base64String.length % 4)) % 4)\n const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/')\n const rawData = atob(base64)\n const outputArray = new Uint8Array(rawData.length)\n\n for (let i = 0; i < rawData.length; ++i) {\n outputArray[i] = rawData.charCodeAt(i)\n }\n return outputArray\n}\n\nexport function arrayBufferToBase64Url(buffer: ArrayBufferLike | ArrayBuffer | null): string {\n if (!buffer) return ''\n const bytes = new Uint8Array(buffer as ArrayBuffer)\n let binary = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n binary += String.fromCharCode(bytes[i])\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n/**\n * Verifica se o ambiente de execução suporta Web Push nativo via Service Worker.\n */\nexport function isWebPushSupported(): boolean {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') return false\n return 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window\n}\n\n/**\n * Inscreve o navegador no Push Service nativo usando as chaves VAPID fornecidas.\n * Retorna `undefined` caso a permissão seja negada pelo usuário (caminho normal, sem lançar erro).\n */\nexport async function subscribeWebPush(options: SubscribeWebPushOptions): Promise<WebPushSubscription | undefined> {\n if (!isWebPushSupported()) return undefined\n\n if (Notification.permission === 'default') {\n const permission = await Notification.requestPermission()\n if (permission !== 'granted') return undefined\n } else if (Notification.permission !== 'granted') {\n return undefined\n }\n\n const registration = options.serviceWorkerRegistration ?? (await navigator.serviceWorker.ready)\n const applicationServerKey = urlBase64ToUint8Array(options.vapidPublicKey)\n\n let subscription = await registration.pushManager.getSubscription()\n if (!subscription) {\n subscription = await registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: applicationServerKey as unknown as BufferSource,\n })\n }\n\n const p256dh = arrayBufferToBase64Url(subscription.getKey('p256dh'))\n const auth = arrayBufferToBase64Url(subscription.getKey('auth'))\n\n return {\n endpoint: subscription.endpoint,\n keys: { p256dh, auth },\n expirationTime: subscription.expirationTime,\n }\n}\n\n/**\n * Remove a inscrição ativa de push no navegador.\n */\nexport async function unsubscribeWebPush(serviceWorkerRegistration?: ServiceWorkerRegistration): Promise<boolean> {\n if (!isWebPushSupported()) return false\n\n const registration = serviceWorkerRegistration ?? (await navigator.serviceWorker.ready)\n const subscription = await registration.pushManager.getSubscription()\n if (!subscription) return false\n\n return subscription.unsubscribe()\n}\n\n/**\n * Obtém a inscrição ativa de push no navegador se já existir.\n */\nexport async function getWebPushSubscription(\n serviceWorkerRegistration?: ServiceWorkerRegistration,\n): Promise<WebPushSubscription | undefined> {\n if (!isWebPushSupported()) return undefined\n\n const registration = serviceWorkerRegistration ?? (await navigator.serviceWorker.ready)\n const subscription = await registration.pushManager.getSubscription()\n if (!subscription) return undefined\n\n const p256dh = arrayBufferToBase64Url(subscription.getKey('p256dh'))\n const auth = arrayBufferToBase64Url(subscription.getKey('auth'))\n\n return {\n endpoint: subscription.endpoint,\n keys: { p256dh, auth },\n expirationTime: subscription.expirationTime,\n }\n}\n\n/**\n * Retorna o script padrão do Service Worker para manipulação de notificações em PWAs.\n */\nexport function getStandardWebPushServiceWorkerScript(): string {\n return `\nself.addEventListener('push', (event) => {\n if (!event.data) return;\n let payload;\n try {\n payload = event.data.json();\n } catch {\n payload = { title: 'Notificação', body: event.data.text() };\n }\n\n const title = payload.title || 'Nova Notificação';\n const options = {\n body: payload.body || '',\n icon: payload.icon || '/pwa-192x192.png',\n badge: payload.badge || '/badge-72x72.png',\n tag: payload.tag,\n data: payload.data || { url: payload.url || '/' },\n };\n\n event.waitUntil(self.registration.showNotification(title, options));\n});\n\nself.addEventListener('notificationclick', (event) => {\n event.notification.close();\n const targetUrl = event.notification.data?.url || '/';\n\n event.waitUntil(\n clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {\n for (const client of clientList) {\n if (client.url === targetUrl && 'focus' in client) {\n return client.focus();\n }\n }\n if (clients.openWindow) {\n return clients.openWindow(targetUrl);\n }\n })\n );\n});\n`.trim()\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Helper de push para React Native com Expo.\n * **Não importa `expo-notifications` estaticamente**: recebe o módulo por injeção\n * (duck-typing) para não poluir nem quebrar o bundle web/PWA.\n */\n\nimport {\n createDeviceRegistration,\n type DeviceRegistrationHandle,\n type DeviceRegistrationStorage,\n} from './deviceRegistration'\nimport type { NotificationClient } from './httpClient'\n\nexport type ExpoPermissionResponse = {\n readonly status: string\n readonly granted: boolean\n}\n\nexport type ExpoPushTokenResult = {\n readonly data: string\n}\n\nexport interface ExpoNotificationsModule {\n getPermissionsAsync(): Promise<ExpoPermissionResponse>\n requestPermissionsAsync(): Promise<ExpoPermissionResponse>\n getExpoPushTokenAsync(options?: { projectId?: string }): Promise<ExpoPushTokenResult>\n setNotificationChannelAsync?(\n channelId: string,\n channel: {\n name: string\n importance: number\n sound?: boolean\n vibrationPattern?: number[]\n },\n ): Promise<unknown>\n}\n\nexport type GetExpoPushTokenOptions = {\n readonly module: ExpoNotificationsModule\n readonly projectId?: string\n readonly channelId?: string\n readonly channelName?: string\n}\n\n/**\n * Solicita permissões e obtém o Expo Push Token.\n * Se a permissão for negada, devolve `undefined` (caminho normal, sem erro).\n */\nexport async function getExpoPushToken(options: GetExpoPushTokenOptions): Promise<string | undefined> {\n const { module } = options\n\n const currentPerms = await module.getPermissionsAsync()\n let isGranted = currentPerms.granted\n\n if (!isGranted) {\n const requested = await module.requestPermissionsAsync()\n isGranted = requested.granted\n }\n\n if (!isGranted) return undefined\n\n if (typeof module.setNotificationChannelAsync === 'function') {\n await module.setNotificationChannelAsync(options.channelId ?? 'default', {\n name: options.channelName ?? 'Geral',\n importance: 4, // Android IMPORTANCE_HIGH\n sound: true,\n })\n }\n\n const tokenResult = await module.getExpoPushTokenAsync({\n projectId: options.projectId,\n })\n\n return tokenResult.data\n}\n\nexport type CreateExpoPushRegistrationConfig = {\n readonly client: NotificationClient\n readonly module: ExpoNotificationsModule\n readonly projectId?: string\n readonly storage?: DeviceRegistrationStorage\n}\n\n/**\n * Cria o ciclo de vida completo de registro do dispositivo Expo integrado ao NotificationClient.\n */\nexport function createExpoPushRegistration(config: CreateExpoPushRegistrationConfig): DeviceRegistrationHandle {\n return createDeviceRegistration({\n client: config.client,\n driver: 'expo',\n storage: config.storage,\n getToken: () => getExpoPushToken({ module: config.module, projectId: config.projectId }),\n })\n}\n"],"mappings":";;;;AA+DA,SAASA,cAAcC,QAAgBC,SAAgB;AACrD,QAAMC,WAAWD;AAGjB,QAAME,QAAQ,IAAIC,MAAMF,UAAUC,OAAOE,WAAW,8BAAwBL,MAAAA,IAAU;AACtF,SAAOM,OAAOC,OAAOJ,OAAO;IAC1BH;IACAQ,MAAMN,UAAUC,OAAOK,QAAQ;IAC/BC,QAAQP,UAAUC,OAAOM;EAC3B,CAAA;AACF;AAVSV;AAkEF,SAASW,yBAAyBC,QAAgC;AACvE,QAAMC,YAAYD,OAAOC,aAAaC;AACtC,QAAMC,UAAUH,OAAOG,QAAQC,SAAS,GAAA,IAAOJ,OAAOG,QAAQE,MAAM,GAAG,EAAC,IAAKL,OAAOG;AAEpF,iBAAeG,QAAmBC,QAKjC;AACC,UAAMC,WAAW,GAAGL,OAAAA,GAAUI,OAAOE,IAAI;AACzC,UAAMC,aAAaF,SAASG,WAAW,SAAA,KAAcH,SAASG,WAAW,UAAA;AACzE,UAAMC,eACJ,OAAOC,WAAW,eAAeA,OAAOC,UAAUC,SAASF,OAAOC,SAASC,SAAS;AACtF,UAAMC,MAAM,IAAIC,IAAIT,UAAUE,aAAaQ,SAAYN,YAAAA;AACvD,eAAW,CAACO,KAAKC,KAAAA,KAAUzB,OAAO0B,QAAQd,OAAOe,SAAS,CAAC,CAAA,GA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AACd,SAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAuCPC,KAAI;AACN;AAzCgBD;;;ACxEhB,eAAsBE,iBAAiBC,SAAgC;AACrE,QAAM,EAAEC,OAAM,IAAKD;AAEnB,QAAME,eAAe,MAAMD,OAAOE,oBAAmB;AACrD,MAAIC,YAAYF,aAAaG;AAE7B,MAAI,CAACD,WAAW;AACd,UAAME,YAAY,MAAML,OAAOM,wBAAuB;AACtDH,gBAAYE,UAAUD;EACxB;AAEA,MAAI,CAACD,UAAW,QAAOI;AAEvB,MAAI,OAAOP,OAAOQ,gCAAgC,YAAY;AAC5D,UAAMR,OAAOQ,4BAA4BT,QAAQU,aAAa,WAAW;MACvEC,MAAMX,QAAQY,eAAe;MAC7BC,YAAY;MACZC,OAAO;IACT,CAAA;EACF;AAEA,QAAMC,cAAc,MAAMd,OAAOe,sBAAsB;IACrDC,WAAWjB,QAAQiB;EACrB,CAAA;AAEA,SAAOF,YAAYG;AACrB;AA1BsBnB;AAsCf,SAASoB,2BAA2BC,QAAwC;AACjF,SAAOC,yBAAyB;IAC9BC,QAAQF,OAAOE;IACfC,QAAQ;IACRC,SAASJ,OAAOI;IAChBC,UAAU,6BAAM1B,iBAAiB;MAAEE,QAAQmB,OAAOnB;MAAQgB,WAAWG,OAAOH;IAAU,CAAA,GAA5E;EACZ,CAAA;AACF;AAPgBE;","names":["buildApiError","status","payload","envelope","error","Error","message","Object","assign","code","issues","createNotificationClient","config","fetchImpl","fetch","baseUrl","endsWith","slice","request","params","fullPath","path","isAbsolute","startsWith","fallbackBase","window","location","origin","url","URL","undefined","key","value","entries","query","searchParams","set","String","authHeaders","getAuthHeaders","finalUrl","toString","pathname","search","response","method","headers","body","JSON","stringify","text","parse","ok","listNotifications","options","category","read","cursor","perPage","data","nextCursor","pagination","unreadCount","meta","countUnread","markAsRead","id","encodeURIComponent","markAllAsRead","updated","deleteNotification","registerDevice","input","unregisterDevice","getPreferences","updatePreferences","preferences","listTemplates","getCategoryPolicies","updateCategoryPolicies","policies","deactivateTemplate","restoreDefault","listTemplateDefinitions","listTemplateVariables","upsertTemplate","resolveStreamRequest","getVapidPublicKey","publicKey","sendPush","broadcastPush","registerWebPush","subscription","platform","driver","token","appVersion","locale","timezone","STORAGE_KEY","createDeviceRegistration","config","rememberDeviceId","deviceId","storage","setItem","register","options","token","getToken","undefined","input","platform","driver","appVersion","locale","timezone","device","client","registerDevice","id","unregister","getItem","unregisterDevice","removeItem","DEFAULT_RECONNECT_DELAY_MS","parseSseBlock","block","eventName","dataLines","line","split","startsWith","slice","length","trim","push","undefined","raw","join","event","data","JSON","parse","subscribeToNotificationStream","params","fetchImpl","fetch","controller","AbortController","closed","connect","response","url","headers","Accept","signal","ok","body","Error","status","reader","getReader","decoder","TextDecoder","buffer","value","done","read","decode","stream","blocks","pop","onEvent","runWithReconnect","delay","reconnectDelayMs","error","onError","String","Promise","resolve","setTimeout","close","abort","urlBase64ToUint8Array","base64String","padding","repeat","length","base64","replace","rawData","atob","outputArray","Uint8Array","i","charCodeAt","arrayBufferToBase64Url","buffer","bytes","binary","byteLength","String","fromCharCode","btoa","isWebPushSupported","window","navigator","subscribeWebPush","options","undefined","Notification","permission","requestPermission","registration","serviceWorkerRegistration","serviceWorker","ready","applicationServerKey","vapidPublicKey","subscription","pushManager","getSubscription","subscribe","userVisibleOnly","p256dh","getKey","auth","endpoint","keys","expirationTime","unsubscribeWebPush","unsubscribe","getWebPushSubscription","getStandardWebPushServiceWorkerScript","trim","getExpoPushToken","options","module","currentPerms","getPermissionsAsync","isGranted","granted","requested","requestPermissionsAsync","undefined","setNotificationChannelAsync","channelId","name","channelName","importance","sound","tokenResult","getExpoPushTokenAsync","projectId","data","createExpoPushRegistration","config","createDeviceRegistration","client","driver","storage","getToken"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adatechnology/notification-client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Isomorphic notification client — typed HTTP, device registration and SSE. Runs in React Native, web, Node and Bun.",
|
|
6
6
|
"publishConfig": {
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
"dist"
|
|
22
22
|
],
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@adatechnology/notification-contracts": "0.
|
|
24
|
+
"@adatechnology/notification-contracts": "0.6.0"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
27
|
"@types/bun": "1.3.14",
|