@adatechnology/notification-client 0.1.0-rc.1 → 0.1.0-rc.2
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 +9 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -1
- package/dist/index.d.ts +9 -1
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -149,6 +149,15 @@ function createNotificationClient(config) {
|
|
|
149
149
|
});
|
|
150
150
|
return payload?.data ?? [];
|
|
151
151
|
},
|
|
152
|
+
async upsertTemplate(input) {
|
|
153
|
+
const payload = await request({
|
|
154
|
+
method: "POST",
|
|
155
|
+
path: "/notification-templates",
|
|
156
|
+
body: input
|
|
157
|
+
});
|
|
158
|
+
if (!payload?.data) throw new Error("notification-client: upsertTemplate n\xE3o devolveu o template");
|
|
159
|
+
return payload.data;
|
|
160
|
+
},
|
|
152
161
|
async resolveStreamRequest() {
|
|
153
162
|
return {
|
|
154
163
|
url: `${baseUrl}/notifications/stream`,
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/httpClient.ts","../src/deviceRegistration.ts","../src/streamSubscription.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","/**\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} 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 listTemplates(): Promise<readonly NotificationTemplate[]>\n /** Base + headers, para o assinante de SSE reaproveitar a mesma configuração. */\n resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }>\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 url = new URL(`${baseUrl}${params.path}`)\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 response = await fetchImpl(url.toString(), {\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 resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }> {\n return { url: `${baseUrl}/notifications/stream`, headers: (await config.getAuthHeaders?.()) ?? {} }\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;ACsDA,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;AA2BF,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,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AA3BeW;AA6Bf,iBAAeuB,mBAAAA;AACb,UAAMC,QAAQ9B,OAAO+B,oBAAoBnD;AAEzC,WAAO,CAACyB,QAAQ;AACd,UAAI;AACF,cAAMC,QAAAA;MACR,SAAS0B,OAAO;AACd,YAAI3B,OAAQ;AACZL,eAAOiC,UAAUD,iBAAiBlB,QAAQkB,QAAQ,IAAIlB,MAAMoB,OAAOF,KAAAA,CAAAA,CAAAA;MACrE;AAIA,UAAI3B,UAAUyB,UAAU,EAAG;AAC3B,YAAM,IAAIK,QAAQ,CAACC,YAAYC,WAAWD,SAASN,KAAAA,CAAAA;IACrD;EACF;AAhBeD;AAkBf,OAAKA,iBAAAA;AAEL,SAAO;IACLS,QAAAA;AACEjC,eAAS;AACTF,iBAAWoC,MAAK;IAClB;EACF;AACF;AA9DgBxC;","names":["buildApiError","status","payload","envelope","error","Error","message","Object","assign","code","issues","createNotificationClient","config","fetchImpl","fetch","baseUrl","endsWith","slice","request","params","url","URL","path","key","value","entries","query","undefined","searchParams","set","String","authHeaders","getAuthHeaders","response","toString","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","resolveStreamRequest","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"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/httpClient.ts","../src/deviceRegistration.ts","../src/streamSubscription.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","/**\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 UpsertTemplateBody,\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 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 /** Base + headers, para o assinante de SSE reaproveitar a mesma configuração. */\n resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }>\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 url = new URL(`${baseUrl}${params.path}`)\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 response = await fetchImpl(url.toString(), {\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 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}\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;ACuDA,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;AAmCF,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,MAAM,IAAIC,IAAI,GAAGN,OAAAA,GAAUI,OAAOG,IAAI,EAAE;AAC9C,eAAW,CAACC,KAAKC,KAAAA,KAAUjB,OAAOkB,QAAQN,OAAOO,SAAS,CAAC,CAAA,GAAI;AAC7D,UAAIF,UAAUG,OAAWP,KAA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F;AA3BeW;AA6Bf,iBAAeuB,mBAAAA;AACb,UAAMC,QAAQ9B,OAAO+B,oBAAoBnD;AAEzC,WAAO,CAACyB,QAAQ;AACd,UAAI;AACF,cAAMC,QAAAA;MACR,SAAS0B,OAAO;AACd,YAAI3B,OAAQ;AACZL,eAAOiC,UAAUD,iBAAiBlB,QAAQkB,QAAQ,IAAIlB,MAAMoB,OAAOF,KAAAA,CAAAA,CAAAA;MACrE;AAIA,UAAI3B,UAAUyB,UAAU,EAAG;AAC3B,YAAM,IAAIK,QAAQ,CAACC,YAAYC,WAAWD,SAASN,KAAAA,CAAAA;IACrD;EACF;AAhBeD;AAkBf,OAAKA,iBAAAA;AAEL,SAAO;IACLS,QAAAA;AACEjC,eAAS;AACTF,iBAAWoC,MAAK;IAClB;EACF;AACF;AA9DgBxC;","names":["buildApiError","status","payload","envelope","error","Error","message","Object","assign","code","issues","createNotificationClient","config","fetchImpl","fetch","baseUrl","endsWith","slice","request","params","url","URL","path","key","value","entries","query","undefined","searchParams","set","String","authHeaders","getAuthHeaders","response","toString","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","upsertTemplate","resolveStreamRequest","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"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { NotificationSummary, DeviceRegistration, NotificationPreference, NotificationTemplate } from '@adatechnology/notification-contracts';
|
|
1
|
+
import { NotificationSummary, DeviceRegistration, NotificationPreference, NotificationTemplate, UpsertTemplateBody } from '@adatechnology/notification-contracts';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
@@ -56,6 +56,14 @@ type NotificationClient = {
|
|
|
56
56
|
getPreferences(): Promise<readonly NotificationPreference[]>;
|
|
57
57
|
updatePreferences(preferences: readonly NotificationPreference[]): Promise<readonly NotificationPreference[]>;
|
|
58
58
|
listTemplates(): Promise<readonly NotificationTemplate[]>;
|
|
59
|
+
/**
|
|
60
|
+
* Cria uma VERSÃO nova do template, não edita a atual.
|
|
61
|
+
*
|
|
62
|
+
* O módulo versiona por `key`+`channel`+`locale`: a versão anterior fica legível para auditoria, e
|
|
63
|
+
* a leitura só devolve a ativa mais alta. Então "editar a copy" e "reverter" são a mesma operação
|
|
64
|
+
* — o que a tela de configuração precisa para alguém corrigir um texto sem medo.
|
|
65
|
+
*/
|
|
66
|
+
upsertTemplate(input: UpsertTemplateBody): Promise<NotificationTemplate>;
|
|
59
67
|
/** Base + headers, para o assinante de SSE reaproveitar a mesma configuração. */
|
|
60
68
|
resolveStreamRequest(): Promise<{
|
|
61
69
|
url: string;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { NotificationSummary, DeviceRegistration, NotificationPreference, NotificationTemplate } from '@adatechnology/notification-contracts';
|
|
1
|
+
import { NotificationSummary, DeviceRegistration, NotificationPreference, NotificationTemplate, UpsertTemplateBody } from '@adatechnology/notification-contracts';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
@@ -56,6 +56,14 @@ type NotificationClient = {
|
|
|
56
56
|
getPreferences(): Promise<readonly NotificationPreference[]>;
|
|
57
57
|
updatePreferences(preferences: readonly NotificationPreference[]): Promise<readonly NotificationPreference[]>;
|
|
58
58
|
listTemplates(): Promise<readonly NotificationTemplate[]>;
|
|
59
|
+
/**
|
|
60
|
+
* Cria uma VERSÃO nova do template, não edita a atual.
|
|
61
|
+
*
|
|
62
|
+
* O módulo versiona por `key`+`channel`+`locale`: a versão anterior fica legível para auditoria, e
|
|
63
|
+
* a leitura só devolve a ativa mais alta. Então "editar a copy" e "reverter" são a mesma operação
|
|
64
|
+
* — o que a tela de configuração precisa para alguém corrigir um texto sem medo.
|
|
65
|
+
*/
|
|
66
|
+
upsertTemplate(input: UpsertTemplateBody): Promise<NotificationTemplate>;
|
|
59
67
|
/** Base + headers, para o assinante de SSE reaproveitar a mesma configuração. */
|
|
60
68
|
resolveStreamRequest(): Promise<{
|
|
61
69
|
url: string;
|
package/dist/index.js
CHANGED
|
@@ -123,6 +123,15 @@ function createNotificationClient(config) {
|
|
|
123
123
|
});
|
|
124
124
|
return payload?.data ?? [];
|
|
125
125
|
},
|
|
126
|
+
async upsertTemplate(input) {
|
|
127
|
+
const payload = await request({
|
|
128
|
+
method: "POST",
|
|
129
|
+
path: "/notification-templates",
|
|
130
|
+
body: input
|
|
131
|
+
});
|
|
132
|
+
if (!payload?.data) throw new Error("notification-client: upsertTemplate n\xE3o devolveu o template");
|
|
133
|
+
return payload.data;
|
|
134
|
+
},
|
|
126
135
|
async resolveStreamRequest() {
|
|
127
136
|
return {
|
|
128
137
|
url: `${baseUrl}/notifications/stream`,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/httpClient.ts","../src/deviceRegistration.ts","../src/streamSubscription.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} 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 listTemplates(): Promise<readonly NotificationTemplate[]>\n /** Base + headers, para o assinante de SSE reaproveitar a mesma configuração. */\n resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }>\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 url = new URL(`${baseUrl}${params.path}`)\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 response = await fetchImpl(url.toString(), {\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 resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }> {\n return { url: `${baseUrl}/notifications/stream`, headers: (await config.getAuthHeaders?.()) ?? {} }\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"],"mappings":";;;;AAsDA,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;AA2BF,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,MAAM,IAAIC,IAAI,GAAGN,OAAAA,GAAUI,OAAOG,IAAI,EAAE;AAC9C,eAAW,CAACC,KAAKC,KAAAA,KAAU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QAAAA;MACR,SAAS0B,OAAO;AACd,YAAI3B,OAAQ;AACZL,eAAOiC,UAAUD,iBAAiBlB,QAAQkB,QAAQ,IAAIlB,MAAMoB,OAAOF,KAAAA,CAAAA,CAAAA;MACrE;AAIA,UAAI3B,UAAUyB,UAAU,EAAG;AAC3B,YAAM,IAAIK,QAAQ,CAACC,YAAYC,WAAWD,SAASN,KAAAA,CAAAA;IACrD;EACF;AAhBeD;AAkBf,OAAKA,iBAAAA;AAEL,SAAO;IACLS,QAAAA;AACEjC,eAAS;AACTF,iBAAWoC,MAAK;IAClB;EACF;AACF;AA9DgBxC;","names":["buildApiError","status","payload","envelope","error","Error","message","Object","assign","code","issues","createNotificationClient","config","fetchImpl","fetch","baseUrl","endsWith","slice","request","params","url","URL","path","key","value","entries","query","undefined","searchParams","set","String","authHeaders","getAuthHeaders","response","toString","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","resolveStreamRequest","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"]}
|
|
1
|
+
{"version":3,"sources":["../src/httpClient.ts","../src/deviceRegistration.ts","../src/streamSubscription.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 UpsertTemplateBody,\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 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 /** Base + headers, para o assinante de SSE reaproveitar a mesma configuração. */\n resolveStreamRequest(): Promise<{ url: string; headers: Record<string, string> }>\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 url = new URL(`${baseUrl}${params.path}`)\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 response = await fetchImpl(url.toString(), {\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 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}\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"],"mappings":";;;;AA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UAAUD,OAAOQ,KAAK;MAC3CC,SAAS;QAAE,GAAGT,OAAOS;QAASC,QAAQ;MAAoB;MAC1DC,QAAQR,WAAWQ;IACrB,CAAA;AAEA,QAAI,CAACJ,SAASK,MAAM,CAACL,SAASM,KAAM,OAAM,IAAIC,MAAM,yBAAyBP,SAASQ,MAAM,EAAE;AAE9F,UAAMC,SAAST,SAASM,KAAKI,UAAS;AACtC,UAAMC,UAAU,IAAIC,YAAAA;AACpB,QAAIC,SAAS;AAEb,eAAS;AACP,YAAM,EAAEC,OAAOC,KAAI,IAAK,MAAMN,OAAOO,KAAI;AACzC,UAAID,KAAM;AAEVF,gBAAUF,QAAQM,OAAOH,OAAO;QAAEI,QAAQ;MAAK,CAAA;AAG/C,YAAMC,SAASN,OAAOlC,MAAM,MAAA;AAC5BkC,eAASM,OAAOC,IAAG,KAAM;AAEzB,iBAAW7C,SAAS4C,QAAQ;AAC1B,cAAM/B,QAAQd,cAAcC,KAAAA;AAC5B,YAAIa,MAAOK,QAAO4B,QAAQjC,KAAAA;MAC5B;IACF;EACF;AA3BeW;AA6Bf,iBAAeuB,mBAAAA;AACb,UAAMC,QAAQ9B,OAAO+B,oBAAoBnD;AAEzC,WAAO,CAACyB,QAAQ;AACd,UAAI;AACF,cAAMC,QAAAA;MACR,SAAS0B,OAAO;AACd,YAAI3B,OAAQ;AACZL,eAAOiC,UAAUD,iBAAiBlB,QAAQkB,QAAQ,IAAIlB,MAAMoB,OAAOF,KAAAA,CAAAA,CAAAA;MACrE;AAIA,UAAI3B,UAAUyB,UAAU,EAAG;AAC3B,YAAM,IAAIK,QAAQ,CAACC,YAAYC,WAAWD,SAASN,KAAAA,CAAAA;IACrD;EACF;AAhBeD;AAkBf,OAAKA,iBAAAA;AAEL,SAAO;IACLS,QAAAA;AACEjC,eAAS;AACTF,iBAAWoC,MAAK;IAClB;EACF;AACF;AA9DgBxC;","names":["buildApiError","status","payload","envelope","error","Error","message","Object","assign","code","issues","createNotificationClient","config","fetchImpl","fetch","baseUrl","endsWith","slice","request","params","url","URL","path","key","value","entries","query","undefined","searchParams","set","String","authHeaders","getAuthHeaders","response","toString","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","upsertTemplate","resolveStreamRequest","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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adatechnology/notification-client",
|
|
3
|
-
"version": "0.1.0-rc.
|
|
3
|
+
"version": "0.1.0-rc.2",
|
|
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.1.0-rc.
|
|
24
|
+
"@adatechnology/notification-contracts": "0.1.0-rc.2"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
27
|
"@types/bun": "1.3.14",
|