@adatechnology/notification-client 0.1.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +66 -0
- package/dist/index.cjs +280 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +132 -0
- package/dist/index.d.ts +132 -0
- package/dist/index.js +253 -0
- package/dist/index.js.map +1 -0
- package/package.json +36 -0
package/README.md
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# @adatechnology/notification-client
|
|
2
|
+
|
|
3
|
+
Cliente **isomórfico** das rotas de notificação: HTTP tipado, registro de device e stream de
|
|
4
|
+
tempo real. Roda em React Native, web, Node e Bun com o mesmo código.
|
|
5
|
+
|
|
6
|
+
Sem dependência de framework — o `notification-ui` é construído sobre ele, mas não é obrigatório.
|
|
7
|
+
|
|
8
|
+
## Instalação
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
bun add @adatechnology/notification-client
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Uso
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { createNotificationClient } from '@adatechnology/notification-client'
|
|
18
|
+
|
|
19
|
+
const client = createNotificationClient({
|
|
20
|
+
baseUrl: 'https://api.exemplo.com/v1',
|
|
21
|
+
getAuthHeaders: async () => ({ authorization: `Bearer ${await session.accessToken()}` }),
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
const page = await client.listNotifications({ cursor })
|
|
25
|
+
const unread = await client.countUnread()
|
|
26
|
+
await client.markAsRead(notificationId)
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
`getAuthHeaders` é função, não valor: token de vida curta é renovado entre uma chamada e outra, e
|
|
30
|
+
capturar o header no boot deixaria o cliente autenticando com credencial vencida depois de 15
|
|
31
|
+
minutos.
|
|
32
|
+
|
|
33
|
+
## Tempo real sem `EventSource`
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
const { url, headers } = await client.resolveStreamRequest()
|
|
37
|
+
|
|
38
|
+
const subscription = subscribeToNotificationStream({
|
|
39
|
+
url,
|
|
40
|
+
headers,
|
|
41
|
+
onEvent: () => queryClient.invalidateQueries(),
|
|
42
|
+
})
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`resolveStreamRequest` existe para o assinante reaproveitar a base e os headers já resolvidos, em
|
|
46
|
+
vez de o chamador remontar a URL e o token por fora e os dois saírem de sincronia.
|
|
47
|
+
|
|
48
|
+
**A `EventSource` da plataforma não é usada, de propósito.** Ela não aceita cabeçalho — o token
|
|
49
|
+
teria que ir na query string, onde vaza para log de servidor, histórico e referer
|
|
50
|
+
(`security.md` §8). E o React Native não a tem nativamente. A implementação usa `fetch` +
|
|
51
|
+
`ReadableStream`, que resolve os dois problemas de uma vez e funciona igual nos quatro ambientes.
|
|
52
|
+
|
|
53
|
+
Reconexão com backoff exponencial e retomada por `Last-Event-ID` estão incluídas.
|
|
54
|
+
|
|
55
|
+
## Registro de device
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
import { createDeviceRegistration } from '@adatechnology/notification-client'
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Registra o token de push e **remove no logout** — device que continua registrado depois da saída
|
|
62
|
+
manda notificação da conta antiga para o aparelho.
|
|
63
|
+
|
|
64
|
+
## Licença
|
|
65
|
+
|
|
66
|
+
MIT © Ada Technology
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
+
|
|
21
|
+
// src/index.ts
|
|
22
|
+
var index_exports = {};
|
|
23
|
+
__export(index_exports, {
|
|
24
|
+
createDeviceRegistration: () => createDeviceRegistration,
|
|
25
|
+
createNotificationClient: () => createNotificationClient,
|
|
26
|
+
subscribeToNotificationStream: () => subscribeToNotificationStream
|
|
27
|
+
});
|
|
28
|
+
module.exports = __toCommonJS(index_exports);
|
|
29
|
+
|
|
30
|
+
// src/httpClient.ts
|
|
31
|
+
function buildApiError(status, payload) {
|
|
32
|
+
const envelope = payload;
|
|
33
|
+
const error = new Error(envelope?.error?.message ?? `Falha na requisi\xE7\xE3o (${status}).`);
|
|
34
|
+
return Object.assign(error, {
|
|
35
|
+
status,
|
|
36
|
+
code: envelope?.error?.code ?? "NOTIFICATION_UNKNOWN_ERROR",
|
|
37
|
+
issues: envelope?.error?.issues
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
__name(buildApiError, "buildApiError");
|
|
41
|
+
function createNotificationClient(config) {
|
|
42
|
+
const fetchImpl = config.fetchImpl ?? fetch;
|
|
43
|
+
const baseUrl = config.baseUrl.endsWith("/") ? config.baseUrl.slice(0, -1) : config.baseUrl;
|
|
44
|
+
async function request(params) {
|
|
45
|
+
const url = new URL(`${baseUrl}${params.path}`);
|
|
46
|
+
for (const [key, value] of Object.entries(params.query ?? {})) {
|
|
47
|
+
if (value !== void 0) url.searchParams.set(key, String(value));
|
|
48
|
+
}
|
|
49
|
+
const authHeaders = await config.getAuthHeaders?.() ?? {};
|
|
50
|
+
const response = await fetchImpl(url.toString(), {
|
|
51
|
+
method: params.method,
|
|
52
|
+
headers: {
|
|
53
|
+
...params.body === void 0 ? {} : {
|
|
54
|
+
"Content-Type": "application/json"
|
|
55
|
+
},
|
|
56
|
+
...authHeaders
|
|
57
|
+
},
|
|
58
|
+
body: params.body === void 0 ? void 0 : JSON.stringify(params.body)
|
|
59
|
+
});
|
|
60
|
+
if (response.status === 204) return void 0;
|
|
61
|
+
const text = await response.text();
|
|
62
|
+
const payload = text === "" ? void 0 : JSON.parse(text);
|
|
63
|
+
if (!response.ok) throw buildApiError(response.status, payload);
|
|
64
|
+
return payload;
|
|
65
|
+
}
|
|
66
|
+
__name(request, "request");
|
|
67
|
+
return {
|
|
68
|
+
async listNotifications(options) {
|
|
69
|
+
const payload = await request({
|
|
70
|
+
method: "GET",
|
|
71
|
+
path: "/notifications",
|
|
72
|
+
query: {
|
|
73
|
+
category: options?.category,
|
|
74
|
+
read: options?.read,
|
|
75
|
+
cursor: options?.cursor,
|
|
76
|
+
perPage: options?.perPage
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
return {
|
|
80
|
+
data: payload?.data ?? [],
|
|
81
|
+
nextCursor: payload?.pagination.nextCursor,
|
|
82
|
+
unreadCount: payload?.meta.unreadCount ?? 0
|
|
83
|
+
};
|
|
84
|
+
},
|
|
85
|
+
async countUnread() {
|
|
86
|
+
const payload = await request({
|
|
87
|
+
method: "GET",
|
|
88
|
+
path: "/notifications/unread-count"
|
|
89
|
+
});
|
|
90
|
+
return payload?.data.unreadCount ?? 0;
|
|
91
|
+
},
|
|
92
|
+
async markAsRead(id) {
|
|
93
|
+
const payload = await request({
|
|
94
|
+
method: "PATCH",
|
|
95
|
+
path: `/notifications/${encodeURIComponent(id)}/read`
|
|
96
|
+
});
|
|
97
|
+
if (!payload) throw new Error("notification-client: resposta vazia em markAsRead");
|
|
98
|
+
return payload.data;
|
|
99
|
+
},
|
|
100
|
+
async markAllAsRead() {
|
|
101
|
+
const payload = await request({
|
|
102
|
+
method: "POST",
|
|
103
|
+
path: "/notifications/read-all"
|
|
104
|
+
});
|
|
105
|
+
return payload?.data.updated ?? 0;
|
|
106
|
+
},
|
|
107
|
+
async deleteNotification(id) {
|
|
108
|
+
await request({
|
|
109
|
+
method: "DELETE",
|
|
110
|
+
path: `/notifications/${encodeURIComponent(id)}`
|
|
111
|
+
});
|
|
112
|
+
},
|
|
113
|
+
async registerDevice(input) {
|
|
114
|
+
const payload = await request({
|
|
115
|
+
method: "POST",
|
|
116
|
+
path: "/notification-devices",
|
|
117
|
+
body: input
|
|
118
|
+
});
|
|
119
|
+
if (!payload) throw new Error("notification-client: resposta vazia em registerDevice");
|
|
120
|
+
return payload.data;
|
|
121
|
+
},
|
|
122
|
+
async unregisterDevice(id) {
|
|
123
|
+
await request({
|
|
124
|
+
method: "DELETE",
|
|
125
|
+
path: `/notification-devices/${encodeURIComponent(id)}`
|
|
126
|
+
});
|
|
127
|
+
},
|
|
128
|
+
async getPreferences() {
|
|
129
|
+
const payload = await request({
|
|
130
|
+
method: "GET",
|
|
131
|
+
path: "/notification-preferences"
|
|
132
|
+
});
|
|
133
|
+
return payload?.data ?? [];
|
|
134
|
+
},
|
|
135
|
+
async updatePreferences(preferences) {
|
|
136
|
+
const payload = await request({
|
|
137
|
+
method: "PUT",
|
|
138
|
+
path: "/notification-preferences",
|
|
139
|
+
body: {
|
|
140
|
+
preferences
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
return payload?.data ?? [];
|
|
144
|
+
},
|
|
145
|
+
async listTemplates() {
|
|
146
|
+
const payload = await request({
|
|
147
|
+
method: "GET",
|
|
148
|
+
path: "/notification-templates"
|
|
149
|
+
});
|
|
150
|
+
return payload?.data ?? [];
|
|
151
|
+
},
|
|
152
|
+
async resolveStreamRequest() {
|
|
153
|
+
return {
|
|
154
|
+
url: `${baseUrl}/notifications/stream`,
|
|
155
|
+
headers: await config.getAuthHeaders?.() ?? {}
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
__name(createNotificationClient, "createNotificationClient");
|
|
161
|
+
|
|
162
|
+
// src/deviceRegistration.ts
|
|
163
|
+
var STORAGE_KEY = "adatechnology:notification:device-id";
|
|
164
|
+
function createDeviceRegistration(config) {
|
|
165
|
+
async function rememberDeviceId(deviceId) {
|
|
166
|
+
await config.storage?.setItem(STORAGE_KEY, deviceId);
|
|
167
|
+
}
|
|
168
|
+
__name(rememberDeviceId, "rememberDeviceId");
|
|
169
|
+
return {
|
|
170
|
+
async register(options) {
|
|
171
|
+
const token = await config.getToken();
|
|
172
|
+
if (!token) return void 0;
|
|
173
|
+
const input = {
|
|
174
|
+
platform: options.platform,
|
|
175
|
+
driver: config.driver,
|
|
176
|
+
token,
|
|
177
|
+
appVersion: options.appVersion,
|
|
178
|
+
locale: options.locale,
|
|
179
|
+
timezone: options.timezone
|
|
180
|
+
};
|
|
181
|
+
const device = await config.client.registerDevice(input);
|
|
182
|
+
await rememberDeviceId(device.id);
|
|
183
|
+
return device;
|
|
184
|
+
},
|
|
185
|
+
async unregister() {
|
|
186
|
+
const deviceId = await config.storage?.getItem(STORAGE_KEY);
|
|
187
|
+
if (!deviceId) return;
|
|
188
|
+
await config.client.unregisterDevice(deviceId);
|
|
189
|
+
await config.storage?.removeItem(STORAGE_KEY);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
__name(createDeviceRegistration, "createDeviceRegistration");
|
|
194
|
+
|
|
195
|
+
// src/streamSubscription.ts
|
|
196
|
+
var DEFAULT_RECONNECT_DELAY_MS = 3e3;
|
|
197
|
+
function parseSseBlock(block) {
|
|
198
|
+
let eventName = "message";
|
|
199
|
+
const dataLines = [];
|
|
200
|
+
for (const line of block.split("\n")) {
|
|
201
|
+
if (line.startsWith(":")) continue;
|
|
202
|
+
if (line.startsWith("event:")) eventName = line.slice("event:".length).trim();
|
|
203
|
+
if (line.startsWith("data:")) dataLines.push(line.slice("data:".length).trim());
|
|
204
|
+
}
|
|
205
|
+
if (dataLines.length === 0) return void 0;
|
|
206
|
+
const raw = dataLines.join("\n");
|
|
207
|
+
try {
|
|
208
|
+
return {
|
|
209
|
+
event: eventName,
|
|
210
|
+
data: JSON.parse(raw)
|
|
211
|
+
};
|
|
212
|
+
} catch {
|
|
213
|
+
return {
|
|
214
|
+
event: eventName,
|
|
215
|
+
data: raw
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
__name(parseSseBlock, "parseSseBlock");
|
|
220
|
+
function subscribeToNotificationStream(params) {
|
|
221
|
+
const fetchImpl = params.fetchImpl ?? fetch;
|
|
222
|
+
const controller = new AbortController();
|
|
223
|
+
let closed = false;
|
|
224
|
+
async function connect() {
|
|
225
|
+
const response = await fetchImpl(params.url, {
|
|
226
|
+
headers: {
|
|
227
|
+
...params.headers,
|
|
228
|
+
Accept: "text/event-stream"
|
|
229
|
+
},
|
|
230
|
+
signal: controller.signal
|
|
231
|
+
});
|
|
232
|
+
if (!response.ok || !response.body) throw new Error(`SSE falhou com status ${response.status}`);
|
|
233
|
+
const reader = response.body.getReader();
|
|
234
|
+
const decoder = new TextDecoder();
|
|
235
|
+
let buffer = "";
|
|
236
|
+
for (; ; ) {
|
|
237
|
+
const { value, done } = await reader.read();
|
|
238
|
+
if (done) break;
|
|
239
|
+
buffer += decoder.decode(value, {
|
|
240
|
+
stream: true
|
|
241
|
+
});
|
|
242
|
+
const blocks = buffer.split("\n\n");
|
|
243
|
+
buffer = blocks.pop() ?? "";
|
|
244
|
+
for (const block of blocks) {
|
|
245
|
+
const event = parseSseBlock(block);
|
|
246
|
+
if (event) params.onEvent(event);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
__name(connect, "connect");
|
|
251
|
+
async function runWithReconnect() {
|
|
252
|
+
const delay = params.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS;
|
|
253
|
+
while (!closed) {
|
|
254
|
+
try {
|
|
255
|
+
await connect();
|
|
256
|
+
} catch (error) {
|
|
257
|
+
if (closed) return;
|
|
258
|
+
params.onError?.(error instanceof Error ? error : new Error(String(error)));
|
|
259
|
+
}
|
|
260
|
+
if (closed || delay === 0) return;
|
|
261
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
__name(runWithReconnect, "runWithReconnect");
|
|
265
|
+
void runWithReconnect();
|
|
266
|
+
return {
|
|
267
|
+
close() {
|
|
268
|
+
closed = true;
|
|
269
|
+
controller.abort();
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
__name(subscribeToNotificationStream, "subscribeToNotificationStream");
|
|
274
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
275
|
+
0 && (module.exports = {
|
|
276
|
+
createDeviceRegistration,
|
|
277
|
+
createNotificationClient,
|
|
278
|
+
subscribeToNotificationStream
|
|
279
|
+
});
|
|
280
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +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"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { NotificationSummary, DeviceRegistration, NotificationPreference, NotificationTemplate } from '@adatechnology/notification-contracts';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
5
|
+
*
|
|
6
|
+
* Cliente HTTP tipado pelas 13 rotas do módulo. **Isomórfico e sem DOM**: `fetch` é injetável e o
|
|
7
|
+
* default é o global — é o que permite o mesmo pacote rodar no React Native do cawme e no PWA do
|
|
8
|
+
* quickcart, sem o `-ui` (que tem `react-dom` e Tailwind) entrar no bundle mobile.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
type NotificationClientConfig = {
|
|
12
|
+
/** Base do host, sem barra final: `https://api.exemplo.com/v1`. */
|
|
13
|
+
readonly baseUrl: string;
|
|
14
|
+
/**
|
|
15
|
+
* Devolve o header de autorização a cada chamada — função, não string, porque o token do host
|
|
16
|
+
* rotaciona e capturar o valor no boot deixaria o cliente com uma credencial vencida.
|
|
17
|
+
*/
|
|
18
|
+
readonly getAuthHeaders?: () => Promise<Record<string, string>> | Record<string, string>;
|
|
19
|
+
readonly fetchImpl?: typeof fetch;
|
|
20
|
+
};
|
|
21
|
+
type ListNotificationsOptions = {
|
|
22
|
+
readonly category?: string;
|
|
23
|
+
readonly read?: boolean;
|
|
24
|
+
readonly cursor?: string;
|
|
25
|
+
readonly perPage?: number;
|
|
26
|
+
};
|
|
27
|
+
type ListNotificationsPage = {
|
|
28
|
+
readonly data: readonly NotificationSummary[];
|
|
29
|
+
readonly nextCursor?: string;
|
|
30
|
+
readonly unreadCount: number;
|
|
31
|
+
};
|
|
32
|
+
type RegisterDeviceInput = {
|
|
33
|
+
readonly platform: 'ios' | 'android' | 'web';
|
|
34
|
+
readonly driver: 'expo' | 'fcm';
|
|
35
|
+
readonly token: string;
|
|
36
|
+
readonly appVersion?: string;
|
|
37
|
+
readonly locale?: string;
|
|
38
|
+
readonly timezone?: string;
|
|
39
|
+
};
|
|
40
|
+
type NotificationApiError = Error & {
|
|
41
|
+
readonly status: number;
|
|
42
|
+
readonly code: string;
|
|
43
|
+
readonly issues?: readonly {
|
|
44
|
+
path: string;
|
|
45
|
+
message: string;
|
|
46
|
+
}[];
|
|
47
|
+
};
|
|
48
|
+
type NotificationClient = {
|
|
49
|
+
listNotifications(options?: ListNotificationsOptions): Promise<ListNotificationsPage>;
|
|
50
|
+
countUnread(): Promise<number>;
|
|
51
|
+
markAsRead(id: string): Promise<NotificationSummary>;
|
|
52
|
+
markAllAsRead(): Promise<number>;
|
|
53
|
+
deleteNotification(id: string): Promise<void>;
|
|
54
|
+
registerDevice(input: RegisterDeviceInput): Promise<DeviceRegistration>;
|
|
55
|
+
unregisterDevice(id: string): Promise<void>;
|
|
56
|
+
getPreferences(): Promise<readonly NotificationPreference[]>;
|
|
57
|
+
updatePreferences(preferences: readonly NotificationPreference[]): Promise<readonly NotificationPreference[]>;
|
|
58
|
+
listTemplates(): Promise<readonly NotificationTemplate[]>;
|
|
59
|
+
/** Base + headers, para o assinante de SSE reaproveitar a mesma configuração. */
|
|
60
|
+
resolveStreamRequest(): Promise<{
|
|
61
|
+
url: string;
|
|
62
|
+
headers: Record<string, string>;
|
|
63
|
+
}>;
|
|
64
|
+
};
|
|
65
|
+
declare function createNotificationClient(config: NotificationClientConfig): NotificationClient;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
69
|
+
*
|
|
70
|
+
* Registro de dispositivo para push. **Não importa `expo-notifications` nem `firebase`**: recebe
|
|
71
|
+
* `getToken` por injeção. É o que mantém o pacote isomórfico — o cawme passa o token do Expo, o
|
|
72
|
+
* PWA do quickcart passa o do FCM web, e nenhum dos dois carrega o SDK do outro.
|
|
73
|
+
*/
|
|
74
|
+
|
|
75
|
+
type DeviceRegistrationConfig = {
|
|
76
|
+
readonly client: NotificationClient;
|
|
77
|
+
readonly driver: 'expo' | 'fcm';
|
|
78
|
+
/** `undefined` = permissão negada ou indisponível; o registro é pulado sem erro. */
|
|
79
|
+
getToken(): Promise<string | undefined>;
|
|
80
|
+
/** Persiste o id entre execuções, para o logout conseguir remover o device certo. */
|
|
81
|
+
readonly storage?: DeviceRegistrationStorage;
|
|
82
|
+
};
|
|
83
|
+
/** `AsyncStorage` do RN e `localStorage` do web satisfazem esta forma (via wrapper trivial). */
|
|
84
|
+
type DeviceRegistrationStorage = {
|
|
85
|
+
getItem(key: string): Promise<string | null> | string | null;
|
|
86
|
+
setItem(key: string, value: string): Promise<void> | void;
|
|
87
|
+
removeItem(key: string): Promise<void> | void;
|
|
88
|
+
};
|
|
89
|
+
type RegisterOptions = {
|
|
90
|
+
readonly platform: 'ios' | 'android' | 'web';
|
|
91
|
+
readonly appVersion?: string;
|
|
92
|
+
readonly locale?: string;
|
|
93
|
+
readonly timezone?: string;
|
|
94
|
+
};
|
|
95
|
+
type DeviceRegistrationHandle = {
|
|
96
|
+
/** Idempotente: chamar de novo com o mesmo token reativa o registro em vez de duplicar. */
|
|
97
|
+
register(options: RegisterOptions): Promise<DeviceRegistration | undefined>;
|
|
98
|
+
/** No logout — sem isto, o aparelho continuaria recebendo push do usuário anterior. */
|
|
99
|
+
unregister(): Promise<void>;
|
|
100
|
+
};
|
|
101
|
+
declare function createDeviceRegistration(config: DeviceRegistrationConfig): DeviceRegistrationHandle;
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
105
|
+
*
|
|
106
|
+
* Assinatura do SSE do inbox.
|
|
107
|
+
*
|
|
108
|
+
* **Não usa `EventSource`**, apesar de ser a API óbvia: `EventSource` não aceita headers, e a
|
|
109
|
+
* autenticação do host é `Authorization: Bearer`. Passar token por query string violaria
|
|
110
|
+
* `security.md` §Privacy (credencial em URL vaza em log de proxy e histórico). Além disso o React
|
|
111
|
+
* Native não tem `EventSource` nativo. Ler o corpo por `fetch` + `ReadableStream` resolve os dois
|
|
112
|
+
* de uma vez, e é o que roda igual no web e no RN moderno.
|
|
113
|
+
*/
|
|
114
|
+
type NotificationStreamEvent = {
|
|
115
|
+
readonly event: string;
|
|
116
|
+
readonly data: unknown;
|
|
117
|
+
};
|
|
118
|
+
type SubscribeToNotificationStreamParams = {
|
|
119
|
+
readonly url: string;
|
|
120
|
+
readonly headers: Record<string, string>;
|
|
121
|
+
readonly onEvent: (event: NotificationStreamEvent) => void;
|
|
122
|
+
readonly onError?: (error: Error) => void;
|
|
123
|
+
readonly fetchImpl?: typeof fetch;
|
|
124
|
+
/** Reconexão com backoff; `0` desliga (o chamador cuida). */
|
|
125
|
+
readonly reconnectDelayMs?: number;
|
|
126
|
+
};
|
|
127
|
+
type NotificationStreamSubscription = {
|
|
128
|
+
close(): void;
|
|
129
|
+
};
|
|
130
|
+
declare function subscribeToNotificationStream(params: SubscribeToNotificationStreamParams): NotificationStreamSubscription;
|
|
131
|
+
|
|
132
|
+
export { type DeviceRegistrationConfig, type DeviceRegistrationHandle, type DeviceRegistrationStorage, type ListNotificationsOptions, type ListNotificationsPage, type NotificationApiError, type NotificationClient, type NotificationClientConfig, type NotificationStreamEvent, type NotificationStreamSubscription, type RegisterDeviceInput, type RegisterOptions, type SubscribeToNotificationStreamParams, createDeviceRegistration, createNotificationClient, subscribeToNotificationStream };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { NotificationSummary, DeviceRegistration, NotificationPreference, NotificationTemplate } from '@adatechnology/notification-contracts';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
5
|
+
*
|
|
6
|
+
* Cliente HTTP tipado pelas 13 rotas do módulo. **Isomórfico e sem DOM**: `fetch` é injetável e o
|
|
7
|
+
* default é o global — é o que permite o mesmo pacote rodar no React Native do cawme e no PWA do
|
|
8
|
+
* quickcart, sem o `-ui` (que tem `react-dom` e Tailwind) entrar no bundle mobile.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
type NotificationClientConfig = {
|
|
12
|
+
/** Base do host, sem barra final: `https://api.exemplo.com/v1`. */
|
|
13
|
+
readonly baseUrl: string;
|
|
14
|
+
/**
|
|
15
|
+
* Devolve o header de autorização a cada chamada — função, não string, porque o token do host
|
|
16
|
+
* rotaciona e capturar o valor no boot deixaria o cliente com uma credencial vencida.
|
|
17
|
+
*/
|
|
18
|
+
readonly getAuthHeaders?: () => Promise<Record<string, string>> | Record<string, string>;
|
|
19
|
+
readonly fetchImpl?: typeof fetch;
|
|
20
|
+
};
|
|
21
|
+
type ListNotificationsOptions = {
|
|
22
|
+
readonly category?: string;
|
|
23
|
+
readonly read?: boolean;
|
|
24
|
+
readonly cursor?: string;
|
|
25
|
+
readonly perPage?: number;
|
|
26
|
+
};
|
|
27
|
+
type ListNotificationsPage = {
|
|
28
|
+
readonly data: readonly NotificationSummary[];
|
|
29
|
+
readonly nextCursor?: string;
|
|
30
|
+
readonly unreadCount: number;
|
|
31
|
+
};
|
|
32
|
+
type RegisterDeviceInput = {
|
|
33
|
+
readonly platform: 'ios' | 'android' | 'web';
|
|
34
|
+
readonly driver: 'expo' | 'fcm';
|
|
35
|
+
readonly token: string;
|
|
36
|
+
readonly appVersion?: string;
|
|
37
|
+
readonly locale?: string;
|
|
38
|
+
readonly timezone?: string;
|
|
39
|
+
};
|
|
40
|
+
type NotificationApiError = Error & {
|
|
41
|
+
readonly status: number;
|
|
42
|
+
readonly code: string;
|
|
43
|
+
readonly issues?: readonly {
|
|
44
|
+
path: string;
|
|
45
|
+
message: string;
|
|
46
|
+
}[];
|
|
47
|
+
};
|
|
48
|
+
type NotificationClient = {
|
|
49
|
+
listNotifications(options?: ListNotificationsOptions): Promise<ListNotificationsPage>;
|
|
50
|
+
countUnread(): Promise<number>;
|
|
51
|
+
markAsRead(id: string): Promise<NotificationSummary>;
|
|
52
|
+
markAllAsRead(): Promise<number>;
|
|
53
|
+
deleteNotification(id: string): Promise<void>;
|
|
54
|
+
registerDevice(input: RegisterDeviceInput): Promise<DeviceRegistration>;
|
|
55
|
+
unregisterDevice(id: string): Promise<void>;
|
|
56
|
+
getPreferences(): Promise<readonly NotificationPreference[]>;
|
|
57
|
+
updatePreferences(preferences: readonly NotificationPreference[]): Promise<readonly NotificationPreference[]>;
|
|
58
|
+
listTemplates(): Promise<readonly NotificationTemplate[]>;
|
|
59
|
+
/** Base + headers, para o assinante de SSE reaproveitar a mesma configuração. */
|
|
60
|
+
resolveStreamRequest(): Promise<{
|
|
61
|
+
url: string;
|
|
62
|
+
headers: Record<string, string>;
|
|
63
|
+
}>;
|
|
64
|
+
};
|
|
65
|
+
declare function createNotificationClient(config: NotificationClientConfig): NotificationClient;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
69
|
+
*
|
|
70
|
+
* Registro de dispositivo para push. **Não importa `expo-notifications` nem `firebase`**: recebe
|
|
71
|
+
* `getToken` por injeção. É o que mantém o pacote isomórfico — o cawme passa o token do Expo, o
|
|
72
|
+
* PWA do quickcart passa o do FCM web, e nenhum dos dois carrega o SDK do outro.
|
|
73
|
+
*/
|
|
74
|
+
|
|
75
|
+
type DeviceRegistrationConfig = {
|
|
76
|
+
readonly client: NotificationClient;
|
|
77
|
+
readonly driver: 'expo' | 'fcm';
|
|
78
|
+
/** `undefined` = permissão negada ou indisponível; o registro é pulado sem erro. */
|
|
79
|
+
getToken(): Promise<string | undefined>;
|
|
80
|
+
/** Persiste o id entre execuções, para o logout conseguir remover o device certo. */
|
|
81
|
+
readonly storage?: DeviceRegistrationStorage;
|
|
82
|
+
};
|
|
83
|
+
/** `AsyncStorage` do RN e `localStorage` do web satisfazem esta forma (via wrapper trivial). */
|
|
84
|
+
type DeviceRegistrationStorage = {
|
|
85
|
+
getItem(key: string): Promise<string | null> | string | null;
|
|
86
|
+
setItem(key: string, value: string): Promise<void> | void;
|
|
87
|
+
removeItem(key: string): Promise<void> | void;
|
|
88
|
+
};
|
|
89
|
+
type RegisterOptions = {
|
|
90
|
+
readonly platform: 'ios' | 'android' | 'web';
|
|
91
|
+
readonly appVersion?: string;
|
|
92
|
+
readonly locale?: string;
|
|
93
|
+
readonly timezone?: string;
|
|
94
|
+
};
|
|
95
|
+
type DeviceRegistrationHandle = {
|
|
96
|
+
/** Idempotente: chamar de novo com o mesmo token reativa o registro em vez de duplicar. */
|
|
97
|
+
register(options: RegisterOptions): Promise<DeviceRegistration | undefined>;
|
|
98
|
+
/** No logout — sem isto, o aparelho continuaria recebendo push do usuário anterior. */
|
|
99
|
+
unregister(): Promise<void>;
|
|
100
|
+
};
|
|
101
|
+
declare function createDeviceRegistration(config: DeviceRegistrationConfig): DeviceRegistrationHandle;
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
105
|
+
*
|
|
106
|
+
* Assinatura do SSE do inbox.
|
|
107
|
+
*
|
|
108
|
+
* **Não usa `EventSource`**, apesar de ser a API óbvia: `EventSource` não aceita headers, e a
|
|
109
|
+
* autenticação do host é `Authorization: Bearer`. Passar token por query string violaria
|
|
110
|
+
* `security.md` §Privacy (credencial em URL vaza em log de proxy e histórico). Além disso o React
|
|
111
|
+
* Native não tem `EventSource` nativo. Ler o corpo por `fetch` + `ReadableStream` resolve os dois
|
|
112
|
+
* de uma vez, e é o que roda igual no web e no RN moderno.
|
|
113
|
+
*/
|
|
114
|
+
type NotificationStreamEvent = {
|
|
115
|
+
readonly event: string;
|
|
116
|
+
readonly data: unknown;
|
|
117
|
+
};
|
|
118
|
+
type SubscribeToNotificationStreamParams = {
|
|
119
|
+
readonly url: string;
|
|
120
|
+
readonly headers: Record<string, string>;
|
|
121
|
+
readonly onEvent: (event: NotificationStreamEvent) => void;
|
|
122
|
+
readonly onError?: (error: Error) => void;
|
|
123
|
+
readonly fetchImpl?: typeof fetch;
|
|
124
|
+
/** Reconexão com backoff; `0` desliga (o chamador cuida). */
|
|
125
|
+
readonly reconnectDelayMs?: number;
|
|
126
|
+
};
|
|
127
|
+
type NotificationStreamSubscription = {
|
|
128
|
+
close(): void;
|
|
129
|
+
};
|
|
130
|
+
declare function subscribeToNotificationStream(params: SubscribeToNotificationStreamParams): NotificationStreamSubscription;
|
|
131
|
+
|
|
132
|
+
export { type DeviceRegistrationConfig, type DeviceRegistrationHandle, type DeviceRegistrationStorage, type ListNotificationsOptions, type ListNotificationsPage, type NotificationApiError, type NotificationClient, type NotificationClientConfig, type NotificationStreamEvent, type NotificationStreamSubscription, type RegisterDeviceInput, type RegisterOptions, type SubscribeToNotificationStreamParams, createDeviceRegistration, createNotificationClient, subscribeToNotificationStream };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
3
|
+
|
|
4
|
+
// src/httpClient.ts
|
|
5
|
+
function buildApiError(status, payload) {
|
|
6
|
+
const envelope = payload;
|
|
7
|
+
const error = new Error(envelope?.error?.message ?? `Falha na requisi\xE7\xE3o (${status}).`);
|
|
8
|
+
return Object.assign(error, {
|
|
9
|
+
status,
|
|
10
|
+
code: envelope?.error?.code ?? "NOTIFICATION_UNKNOWN_ERROR",
|
|
11
|
+
issues: envelope?.error?.issues
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
__name(buildApiError, "buildApiError");
|
|
15
|
+
function createNotificationClient(config) {
|
|
16
|
+
const fetchImpl = config.fetchImpl ?? fetch;
|
|
17
|
+
const baseUrl = config.baseUrl.endsWith("/") ? config.baseUrl.slice(0, -1) : config.baseUrl;
|
|
18
|
+
async function request(params) {
|
|
19
|
+
const url = new URL(`${baseUrl}${params.path}`);
|
|
20
|
+
for (const [key, value] of Object.entries(params.query ?? {})) {
|
|
21
|
+
if (value !== void 0) url.searchParams.set(key, String(value));
|
|
22
|
+
}
|
|
23
|
+
const authHeaders = await config.getAuthHeaders?.() ?? {};
|
|
24
|
+
const response = await fetchImpl(url.toString(), {
|
|
25
|
+
method: params.method,
|
|
26
|
+
headers: {
|
|
27
|
+
...params.body === void 0 ? {} : {
|
|
28
|
+
"Content-Type": "application/json"
|
|
29
|
+
},
|
|
30
|
+
...authHeaders
|
|
31
|
+
},
|
|
32
|
+
body: params.body === void 0 ? void 0 : JSON.stringify(params.body)
|
|
33
|
+
});
|
|
34
|
+
if (response.status === 204) return void 0;
|
|
35
|
+
const text = await response.text();
|
|
36
|
+
const payload = text === "" ? void 0 : JSON.parse(text);
|
|
37
|
+
if (!response.ok) throw buildApiError(response.status, payload);
|
|
38
|
+
return payload;
|
|
39
|
+
}
|
|
40
|
+
__name(request, "request");
|
|
41
|
+
return {
|
|
42
|
+
async listNotifications(options) {
|
|
43
|
+
const payload = await request({
|
|
44
|
+
method: "GET",
|
|
45
|
+
path: "/notifications",
|
|
46
|
+
query: {
|
|
47
|
+
category: options?.category,
|
|
48
|
+
read: options?.read,
|
|
49
|
+
cursor: options?.cursor,
|
|
50
|
+
perPage: options?.perPage
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
return {
|
|
54
|
+
data: payload?.data ?? [],
|
|
55
|
+
nextCursor: payload?.pagination.nextCursor,
|
|
56
|
+
unreadCount: payload?.meta.unreadCount ?? 0
|
|
57
|
+
};
|
|
58
|
+
},
|
|
59
|
+
async countUnread() {
|
|
60
|
+
const payload = await request({
|
|
61
|
+
method: "GET",
|
|
62
|
+
path: "/notifications/unread-count"
|
|
63
|
+
});
|
|
64
|
+
return payload?.data.unreadCount ?? 0;
|
|
65
|
+
},
|
|
66
|
+
async markAsRead(id) {
|
|
67
|
+
const payload = await request({
|
|
68
|
+
method: "PATCH",
|
|
69
|
+
path: `/notifications/${encodeURIComponent(id)}/read`
|
|
70
|
+
});
|
|
71
|
+
if (!payload) throw new Error("notification-client: resposta vazia em markAsRead");
|
|
72
|
+
return payload.data;
|
|
73
|
+
},
|
|
74
|
+
async markAllAsRead() {
|
|
75
|
+
const payload = await request({
|
|
76
|
+
method: "POST",
|
|
77
|
+
path: "/notifications/read-all"
|
|
78
|
+
});
|
|
79
|
+
return payload?.data.updated ?? 0;
|
|
80
|
+
},
|
|
81
|
+
async deleteNotification(id) {
|
|
82
|
+
await request({
|
|
83
|
+
method: "DELETE",
|
|
84
|
+
path: `/notifications/${encodeURIComponent(id)}`
|
|
85
|
+
});
|
|
86
|
+
},
|
|
87
|
+
async registerDevice(input) {
|
|
88
|
+
const payload = await request({
|
|
89
|
+
method: "POST",
|
|
90
|
+
path: "/notification-devices",
|
|
91
|
+
body: input
|
|
92
|
+
});
|
|
93
|
+
if (!payload) throw new Error("notification-client: resposta vazia em registerDevice");
|
|
94
|
+
return payload.data;
|
|
95
|
+
},
|
|
96
|
+
async unregisterDevice(id) {
|
|
97
|
+
await request({
|
|
98
|
+
method: "DELETE",
|
|
99
|
+
path: `/notification-devices/${encodeURIComponent(id)}`
|
|
100
|
+
});
|
|
101
|
+
},
|
|
102
|
+
async getPreferences() {
|
|
103
|
+
const payload = await request({
|
|
104
|
+
method: "GET",
|
|
105
|
+
path: "/notification-preferences"
|
|
106
|
+
});
|
|
107
|
+
return payload?.data ?? [];
|
|
108
|
+
},
|
|
109
|
+
async updatePreferences(preferences) {
|
|
110
|
+
const payload = await request({
|
|
111
|
+
method: "PUT",
|
|
112
|
+
path: "/notification-preferences",
|
|
113
|
+
body: {
|
|
114
|
+
preferences
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
return payload?.data ?? [];
|
|
118
|
+
},
|
|
119
|
+
async listTemplates() {
|
|
120
|
+
const payload = await request({
|
|
121
|
+
method: "GET",
|
|
122
|
+
path: "/notification-templates"
|
|
123
|
+
});
|
|
124
|
+
return payload?.data ?? [];
|
|
125
|
+
},
|
|
126
|
+
async resolveStreamRequest() {
|
|
127
|
+
return {
|
|
128
|
+
url: `${baseUrl}/notifications/stream`,
|
|
129
|
+
headers: await config.getAuthHeaders?.() ?? {}
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
__name(createNotificationClient, "createNotificationClient");
|
|
135
|
+
|
|
136
|
+
// src/deviceRegistration.ts
|
|
137
|
+
var STORAGE_KEY = "adatechnology:notification:device-id";
|
|
138
|
+
function createDeviceRegistration(config) {
|
|
139
|
+
async function rememberDeviceId(deviceId) {
|
|
140
|
+
await config.storage?.setItem(STORAGE_KEY, deviceId);
|
|
141
|
+
}
|
|
142
|
+
__name(rememberDeviceId, "rememberDeviceId");
|
|
143
|
+
return {
|
|
144
|
+
async register(options) {
|
|
145
|
+
const token = await config.getToken();
|
|
146
|
+
if (!token) return void 0;
|
|
147
|
+
const input = {
|
|
148
|
+
platform: options.platform,
|
|
149
|
+
driver: config.driver,
|
|
150
|
+
token,
|
|
151
|
+
appVersion: options.appVersion,
|
|
152
|
+
locale: options.locale,
|
|
153
|
+
timezone: options.timezone
|
|
154
|
+
};
|
|
155
|
+
const device = await config.client.registerDevice(input);
|
|
156
|
+
await rememberDeviceId(device.id);
|
|
157
|
+
return device;
|
|
158
|
+
},
|
|
159
|
+
async unregister() {
|
|
160
|
+
const deviceId = await config.storage?.getItem(STORAGE_KEY);
|
|
161
|
+
if (!deviceId) return;
|
|
162
|
+
await config.client.unregisterDevice(deviceId);
|
|
163
|
+
await config.storage?.removeItem(STORAGE_KEY);
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
__name(createDeviceRegistration, "createDeviceRegistration");
|
|
168
|
+
|
|
169
|
+
// src/streamSubscription.ts
|
|
170
|
+
var DEFAULT_RECONNECT_DELAY_MS = 3e3;
|
|
171
|
+
function parseSseBlock(block) {
|
|
172
|
+
let eventName = "message";
|
|
173
|
+
const dataLines = [];
|
|
174
|
+
for (const line of block.split("\n")) {
|
|
175
|
+
if (line.startsWith(":")) continue;
|
|
176
|
+
if (line.startsWith("event:")) eventName = line.slice("event:".length).trim();
|
|
177
|
+
if (line.startsWith("data:")) dataLines.push(line.slice("data:".length).trim());
|
|
178
|
+
}
|
|
179
|
+
if (dataLines.length === 0) return void 0;
|
|
180
|
+
const raw = dataLines.join("\n");
|
|
181
|
+
try {
|
|
182
|
+
return {
|
|
183
|
+
event: eventName,
|
|
184
|
+
data: JSON.parse(raw)
|
|
185
|
+
};
|
|
186
|
+
} catch {
|
|
187
|
+
return {
|
|
188
|
+
event: eventName,
|
|
189
|
+
data: raw
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
__name(parseSseBlock, "parseSseBlock");
|
|
194
|
+
function subscribeToNotificationStream(params) {
|
|
195
|
+
const fetchImpl = params.fetchImpl ?? fetch;
|
|
196
|
+
const controller = new AbortController();
|
|
197
|
+
let closed = false;
|
|
198
|
+
async function connect() {
|
|
199
|
+
const response = await fetchImpl(params.url, {
|
|
200
|
+
headers: {
|
|
201
|
+
...params.headers,
|
|
202
|
+
Accept: "text/event-stream"
|
|
203
|
+
},
|
|
204
|
+
signal: controller.signal
|
|
205
|
+
});
|
|
206
|
+
if (!response.ok || !response.body) throw new Error(`SSE falhou com status ${response.status}`);
|
|
207
|
+
const reader = response.body.getReader();
|
|
208
|
+
const decoder = new TextDecoder();
|
|
209
|
+
let buffer = "";
|
|
210
|
+
for (; ; ) {
|
|
211
|
+
const { value, done } = await reader.read();
|
|
212
|
+
if (done) break;
|
|
213
|
+
buffer += decoder.decode(value, {
|
|
214
|
+
stream: true
|
|
215
|
+
});
|
|
216
|
+
const blocks = buffer.split("\n\n");
|
|
217
|
+
buffer = blocks.pop() ?? "";
|
|
218
|
+
for (const block of blocks) {
|
|
219
|
+
const event = parseSseBlock(block);
|
|
220
|
+
if (event) params.onEvent(event);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
__name(connect, "connect");
|
|
225
|
+
async function runWithReconnect() {
|
|
226
|
+
const delay = params.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS;
|
|
227
|
+
while (!closed) {
|
|
228
|
+
try {
|
|
229
|
+
await connect();
|
|
230
|
+
} catch (error) {
|
|
231
|
+
if (closed) return;
|
|
232
|
+
params.onError?.(error instanceof Error ? error : new Error(String(error)));
|
|
233
|
+
}
|
|
234
|
+
if (closed || delay === 0) return;
|
|
235
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
__name(runWithReconnect, "runWithReconnect");
|
|
239
|
+
void runWithReconnect();
|
|
240
|
+
return {
|
|
241
|
+
close() {
|
|
242
|
+
closed = true;
|
|
243
|
+
controller.abort();
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
__name(subscribeToNotificationStream, "subscribeToNotificationStream");
|
|
248
|
+
export {
|
|
249
|
+
createDeviceRegistration,
|
|
250
|
+
createNotificationClient,
|
|
251
|
+
subscribeToNotificationStream
|
|
252
|
+
};
|
|
253
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +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,KAAUjB,OAAOkB,QAAQN,OAAOO,SAAS,CAAC,CAAA,GAAI;AAC7D,UAAIF,UAAUG,OAAWP,KAAIQ,aAAaC,IAAIN,KAAKO,OAAON,KAAAA,CAAAA;IAC5D;AAEA,UAAMO,cAAe,MAAMnB,OAAOoB,iBAAc,KAAS,CAAC;AAC1D,UAAMC,WAAW,MAAMpB,UAAUO,IAAIc,SAAQ,GAAI;MAC/CC,QAAQhB,OAAOgB;MACfC,SAAS;QAAE,GAAIjB,OAAOkB,SAASV,SAAY,CAAC,IAAI;UAAE,gBAAgB;QAAmB;QAAI,GAAGI;MAAY;MACxGM,MAAM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ApiError","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"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@adatechnology/notification-client",
|
|
3
|
+
"version": "0.1.0-rc.1",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"description": "Isomorphic notification client — typed HTTP, device registration and SSE. Runs in React Native, web, Node and Bun.",
|
|
6
|
+
"publishConfig": {
|
|
7
|
+
"access": "public"
|
|
8
|
+
},
|
|
9
|
+
"type": "module",
|
|
10
|
+
"main": "dist/index.js",
|
|
11
|
+
"types": "dist/index.d.ts",
|
|
12
|
+
"sideEffects": false,
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"import": "./dist/index.js",
|
|
17
|
+
"require": "./dist/index.cjs"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"dist"
|
|
22
|
+
],
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@adatechnology/notification-contracts": "0.1.0-rc.1"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"@types/bun": "1.3.14",
|
|
28
|
+
"tsup": "^8.5.1",
|
|
29
|
+
"typescript": "^5.7.3"
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "tsup",
|
|
33
|
+
"check": "tsc -p tsconfig.json --noEmit",
|
|
34
|
+
"test": "bun test"
|
|
35
|
+
}
|
|
36
|
+
}
|