@miguelmorales13/nestkit 0.22.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +171 -2
  2. package/dist/auth/index.cjs +1 -1
  3. package/dist/auth/index.js +1 -1
  4. package/dist/auth/oauth/index.cjs +1 -1
  5. package/dist/auth/oauth/index.js +1 -1
  6. package/dist/bootstrap/index.cjs +4 -4
  7. package/dist/bootstrap/index.js +3 -3
  8. package/dist/{chunk-FNUZGYUF.cjs → chunk-ALIKVFOV.cjs} +2 -2
  9. package/dist/{chunk-UNEVXCFW.js → chunk-PFHHLB7B.js} +1 -1
  10. package/dist/errors/index.cjs +5 -5
  11. package/dist/errors/index.js +4 -4
  12. package/dist/index.cjs +13 -13
  13. package/dist/index.js +15 -15
  14. package/dist/payments/adapters/mercadopago-connect.d.ts +70 -0
  15. package/dist/payments/adapters/mercadopago.terminal.d.ts +57 -0
  16. package/dist/payments/index.cjs +153 -1
  17. package/dist/payments/index.d.ts +3 -1
  18. package/dist/payments/index.js +152 -0
  19. package/dist/payments/payments.port.d.ts +24 -0
  20. package/dist/push/channels/fcm.channel.d.ts +73 -0
  21. package/dist/push/channels/webpush.channel.d.ts +62 -0
  22. package/dist/push/index.cjs +449 -0
  23. package/dist/push/index.d.ts +9 -0
  24. package/dist/push/index.js +449 -0
  25. package/dist/push/push.module.d.ts +40 -0
  26. package/dist/push/push.options.d.ts +40 -0
  27. package/dist/push/push.port.d.ts +148 -0
  28. package/dist/push/push.service.d.ts +31 -0
  29. package/dist/security/index.cjs +35 -0
  30. package/dist/security/index.d.ts +2 -0
  31. package/dist/security/index.js +35 -0
  32. package/dist/security/signed-state.d.ts +42 -0
  33. package/package.json +20 -4
  34. package/dist/{chunk-A2DGK4ZL.js → chunk-2DUEQKOI.js} +3 -3
  35. package/dist/{chunk-MSTXS3MU.cjs → chunk-LSDY6ETG.cjs} +3 -3
@@ -0,0 +1,449 @@
1
+ import {
2
+ translate
3
+ } from "../chunk-X4PQJZ4G.js";
4
+ import "../chunk-TCAMLNUZ.js";
5
+ import "../chunk-ETRUVZTJ.js";
6
+ import {
7
+ isI18nMessage
8
+ } from "../chunk-VVMRZEIW.js";
9
+ import {
10
+ __decorateClass
11
+ } from "../chunk-4MGIQFAJ.js";
12
+
13
+ // src/push/push.port.ts
14
+ var PUSH = /* @__PURE__ */ Symbol("PUSH");
15
+ var PUSH_DEVICE_STORE = /* @__PURE__ */ Symbol("PUSH_DEVICE_STORE");
16
+
17
+ // src/push/push.options.ts
18
+ var PUSH_OPTIONS = /* @__PURE__ */ Symbol("PUSH_OPTIONS");
19
+
20
+ // src/push/push.module.ts
21
+ import { Global, Logger as Logger2, Module } from "@nestjs/common";
22
+
23
+ // src/push/channels/fcm.channel.ts
24
+ import { readFileSync } from "fs";
25
+ import jwt from "jsonwebtoken";
26
+ var FCM_SCOPES = "https://www.googleapis.com/auth/firebase.messaging https://www.googleapis.com/auth/cloud-platform";
27
+ var DEFAULT_TOKEN_URI = "https://oauth2.googleapis.com/token";
28
+ var IID_URL = "https://iid.googleapis.com/iid/v1";
29
+ var STALE_CODES = /* @__PURE__ */ new Set(["UNREGISTERED", "SENDER_ID_MISMATCH"]);
30
+ var FcmChannel = class {
31
+ constructor(options) {
32
+ this.kind = "fcm";
33
+ this.account = parseServiceAccount(options.serviceAccount);
34
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
35
+ }
36
+ get projectId() {
37
+ return this.account.project_id;
38
+ }
39
+ async send(device, message) {
40
+ if (device.kind !== "fcm") return { code: "wrong_channel", message: "Not an FCM device.", stale: false };
41
+ return this.post({ token: device.token }, message);
42
+ }
43
+ async sendToTopic(topic, message) {
44
+ const result = await this.post({ topic }, message);
45
+ if ("code" in result) throw new Error(`FCM topic send failed: ${result.code} ${result.message}`);
46
+ return result;
47
+ }
48
+ async subscribeToTopic(tokens, topic) {
49
+ await this.topicBatch("batchAdd", tokens, topic);
50
+ }
51
+ async unsubscribeFromTopic(tokens, topic) {
52
+ await this.topicBatch("batchRemove", tokens, topic);
53
+ }
54
+ /** The FCM v1 message for a target. Exported through the instance so a test can pin the exact bytes. */
55
+ buildMessage(target, message) {
56
+ return toFcmMessage(target, message);
57
+ }
58
+ async post(target, message, retried = false) {
59
+ const accessToken = await this.accessToken();
60
+ let response;
61
+ try {
62
+ response = await this.fetchImpl(`https://fcm.googleapis.com/v1/projects/${this.account.project_id}/messages:send`, {
63
+ method: "POST",
64
+ headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
65
+ body: JSON.stringify({ message: toFcmMessage(target, message) })
66
+ });
67
+ } catch (cause) {
68
+ return { code: "unreachable", message: cause instanceof Error ? cause.message : String(cause), stale: false };
69
+ }
70
+ const body = await readBody(response);
71
+ if (response.ok) {
72
+ return { id: body?.name ?? null };
73
+ }
74
+ if (response.status === 401 && !retried) {
75
+ this.token = void 0;
76
+ return this.post(target, message, true);
77
+ }
78
+ const error = body?.error;
79
+ const fcmCode = error?.details?.find((d) => d.errorCode)?.errorCode;
80
+ const code = fcmCode ?? error?.status ?? String(response.status);
81
+ return {
82
+ code,
83
+ message: error?.message ?? `HTTP ${response.status}`,
84
+ // Only FCM's own verdict counts. A 404 alone, or INVALID_ARGUMENT, can
85
+ // come from a malformed payload — deleting a live token over that
86
+ // loses the device for nothing.
87
+ stale: STALE_CODES.has(code)
88
+ };
89
+ }
90
+ async topicBatch(op, tokens, topic) {
91
+ if (tokens.length === 0) return;
92
+ const accessToken = await this.accessToken();
93
+ const response = await this.fetchImpl(`${IID_URL}:${op}`, {
94
+ method: "POST",
95
+ headers: {
96
+ Authorization: `Bearer ${accessToken}`,
97
+ "Content-Type": "application/json",
98
+ access_token_auth: "true"
99
+ },
100
+ body: JSON.stringify({ to: `/topics/${topic}`, registration_tokens: tokens })
101
+ });
102
+ if (!response.ok) {
103
+ throw new Error(`FCM topic ${op} failed: HTTP ${response.status} ${JSON.stringify(await readBody(response)).slice(0, 200)}`);
104
+ }
105
+ }
106
+ /**
107
+ * The OAuth2 access token, minted from a self-signed JWT and kept until
108
+ * a minute before it expires. Concurrent sends share one in-flight
109
+ * request rather than each minting their own.
110
+ */
111
+ accessToken() {
112
+ if (this.token && this.token.expiresAt - 6e4 > Date.now()) return Promise.resolve(this.token.value);
113
+ this.tokenInFlight ??= this.mintAccessToken().finally(() => {
114
+ this.tokenInFlight = void 0;
115
+ });
116
+ return this.tokenInFlight;
117
+ }
118
+ async mintAccessToken() {
119
+ const tokenUri = this.account.token_uri ?? DEFAULT_TOKEN_URI;
120
+ const assertion = jwt.sign(
121
+ { scope: FCM_SCOPES },
122
+ this.account.private_key,
123
+ { algorithm: "RS256", issuer: this.account.client_email, audience: tokenUri, expiresIn: 3600 }
124
+ );
125
+ const response = await this.fetchImpl(tokenUri, {
126
+ method: "POST",
127
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
128
+ body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion })
129
+ });
130
+ const body = await readBody(response);
131
+ if (!response.ok || !body?.access_token) {
132
+ throw new Error(`FCM: could not obtain an access token: ${body?.error ?? response.status} ${body?.error_description ?? ""}`.trim());
133
+ }
134
+ this.token = { value: body.access_token, expiresAt: Date.now() + (body.expires_in ?? 3600) * 1e3 };
135
+ return body.access_token;
136
+ }
137
+ };
138
+ function parseServiceAccount(input) {
139
+ let account;
140
+ if (typeof input !== "string") {
141
+ account = input;
142
+ } else {
143
+ const trimmed = input.trim();
144
+ const json = trimmed.startsWith("{") ? trimmed : readFileSync(trimmed, "utf8");
145
+ account = JSON.parse(json);
146
+ }
147
+ for (const field of ["project_id", "client_email", "private_key"]) {
148
+ if (!account[field]) throw new Error(`PushModule: the Firebase service account has no "${field}".`);
149
+ }
150
+ return { ...account, private_key: account.private_key.replace(/\\n/g, "\n") };
151
+ }
152
+ async function readBody(response) {
153
+ const text = await response.text();
154
+ try {
155
+ return text ? JSON.parse(text) : void 0;
156
+ } catch {
157
+ return text;
158
+ }
159
+ }
160
+ function stringifyData(data) {
161
+ const out = {};
162
+ for (const [key, value] of Object.entries(data)) {
163
+ if (value === void 0 || value === null) continue;
164
+ out[key] = typeof value === "string" ? value : JSON.stringify(value);
165
+ }
166
+ return out;
167
+ }
168
+ function toFcmMessage(target, m) {
169
+ const high = m.priority !== "normal";
170
+ const data = stringifyData({
171
+ ...m.data,
172
+ link: m.link,
173
+ actions: m.actions?.length ? m.actions : void 0,
174
+ category: m.category,
175
+ ...m.dataOnly ? { title: m.title, body: m.body, imageUrl: m.imageUrl, icon: m.icon, badge: m.badge } : {}
176
+ });
177
+ const message = { ...target, data };
178
+ if (!m.dataOnly) {
179
+ message.notification = compact({ title: m.title, body: m.body, image: m.imageUrl });
180
+ }
181
+ message.android = compact({
182
+ priority: high ? "high" : "normal",
183
+ collapse_key: m.collapseKey,
184
+ ttl: m.ttlSeconds !== void 0 ? `${m.ttlSeconds}s` : void 0,
185
+ notification: m.dataOnly ? void 0 : compact({
186
+ channel_id: m.androidChannelId,
187
+ sound: m.sound ?? "default",
188
+ image: m.imageUrl,
189
+ notification_count: m.badge
190
+ })
191
+ });
192
+ message.apns = compact({
193
+ headers: compact({
194
+ "apns-push-type": m.dataOnly ? "background" : "alert",
195
+ "apns-priority": m.dataOnly ? "5" : high ? "10" : "5",
196
+ "apns-collapse-id": m.collapseKey,
197
+ "apns-expiration": m.ttlSeconds !== void 0 ? String(Math.floor(Date.now() / 1e3) + m.ttlSeconds) : void 0
198
+ }),
199
+ payload: {
200
+ aps: m.dataOnly ? { "content-available": 1 } : compact({
201
+ sound: m.sound ?? "default",
202
+ badge: m.badge,
203
+ category: m.category,
204
+ "mutable-content": m.imageUrl ? 1 : void 0
205
+ })
206
+ },
207
+ fcm_options: m.imageUrl && !m.dataOnly ? { image: m.imageUrl } : void 0
208
+ });
209
+ message.webpush = compact({
210
+ headers: compact({
211
+ TTL: m.ttlSeconds !== void 0 ? String(m.ttlSeconds) : void 0,
212
+ Urgency: high ? "high" : "normal"
213
+ }),
214
+ notification: m.dataOnly ? void 0 : compact({
215
+ title: m.title,
216
+ body: m.body,
217
+ icon: m.icon,
218
+ image: m.imageUrl,
219
+ tag: m.collapseKey,
220
+ actions: m.actions?.map((a) => compact({ action: a.id, title: a.title, icon: a.icon })),
221
+ data: compact({ link: m.link, actions: m.actions })
222
+ }),
223
+ fcm_options: m.link?.startsWith("https://") && !m.dataOnly ? { link: m.link } : void 0
224
+ });
225
+ return message;
226
+ }
227
+ function compact(object) {
228
+ const out = {};
229
+ for (const [key, value] of Object.entries(object)) {
230
+ if (value === void 0) continue;
231
+ if (typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length === 0) continue;
232
+ out[key] = value;
233
+ }
234
+ return out;
235
+ }
236
+
237
+ // src/push/channels/webpush.channel.ts
238
+ var WebPushChannel = class {
239
+ constructor(options, lib) {
240
+ this.options = options;
241
+ this.kind = "webpush";
242
+ if (!options.subject || !options.publicKey || !options.privateKey) {
243
+ throw new Error("PushModule: webPush needs subject, publicKey and privateKey (VAPID_SUBJECT, VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY).");
244
+ }
245
+ if (lib) this.libPromise = Promise.resolve(this.configure(lib));
246
+ }
247
+ lib() {
248
+ this.libPromise ??= import("web-push").then((m) => this.configure(m.default ?? m));
249
+ return this.libPromise;
250
+ }
251
+ configure(lib) {
252
+ lib.setVapidDetails(this.options.subject, this.options.publicKey, this.options.privateKey);
253
+ return lib;
254
+ }
255
+ /** The JSON the worker gets. On the instance so a test can pin it. */
256
+ buildPayload(message) {
257
+ const payload = { title: message.title, body: message.body };
258
+ if (message.icon) payload.icon = message.icon;
259
+ if (message.imageUrl) payload.image = message.imageUrl;
260
+ if (message.badge !== void 0) payload.badge = message.badge;
261
+ if (message.collapseKey) payload.tag = message.collapseKey;
262
+ if (message.link) payload.link = message.link;
263
+ if (message.actions?.length) {
264
+ payload.actions = message.actions.map((a) => ({ action: a.id, title: a.title, ...a.icon ? { icon: a.icon } : {}, ...a.link ? { link: a.link } : {} }));
265
+ }
266
+ if (message.data && Object.keys(message.data).length) payload.data = message.data;
267
+ return payload;
268
+ }
269
+ async send(device, message) {
270
+ if (device.kind !== "webpush") return { code: "wrong_channel", message: "Not a Web Push subscription.", stale: false };
271
+ const lib = await this.lib();
272
+ try {
273
+ await lib.sendNotification(
274
+ { endpoint: device.endpoint, keys: device.keys },
275
+ JSON.stringify(this.buildPayload(message)),
276
+ {
277
+ TTL: message.ttlSeconds,
278
+ urgency: message.priority === "normal" ? "normal" : "high",
279
+ topic: message.collapseKey
280
+ }
281
+ );
282
+ return { id: null };
283
+ } catch (cause) {
284
+ const status = cause.statusCode;
285
+ return {
286
+ code: status !== void 0 ? String(status) : "unreachable",
287
+ message: cause instanceof Error ? cause.message : String(cause),
288
+ stale: status === 404 || status === 410
289
+ };
290
+ }
291
+ }
292
+ };
293
+
294
+ // src/push/push.service.ts
295
+ import { Logger } from "@nestjs/common";
296
+ var PushService = class _PushService {
297
+ constructor(channels, devices, concurrency = 20) {
298
+ this.devices = devices;
299
+ this.concurrency = concurrency;
300
+ this.logger = new Logger(_PushService.name);
301
+ this.byKind = {};
302
+ for (const channel of channels) this.byKind[channel.kind] = channel;
303
+ }
304
+ channels() {
305
+ return { fcm: Boolean(this.byKind.fcm), webpush: Boolean(this.byKind.webpush) };
306
+ }
307
+ async send(devices, message, options = {}) {
308
+ const list = Array.isArray(devices) ? devices : [devices];
309
+ const resolved = resolveMessage(message, options.lang);
310
+ const result = { sent: 0, failed: [], ids: [] };
311
+ if (list.length === 0) return result;
312
+ const outcomes = await mapLimit(list, this.concurrency, async (device) => {
313
+ const channel = this.byKind[device.kind];
314
+ if (!channel) {
315
+ return { device, code: "channel_not_configured", message: `No ${device.kind} channel is configured.`, stale: false };
316
+ }
317
+ const outcome = await channel.send(device, resolved);
318
+ return "code" in outcome ? { device, ...outcome } : outcome;
319
+ });
320
+ for (const outcome of outcomes) {
321
+ if ("code" in outcome) {
322
+ result.failed.push(outcome);
323
+ result.ids.push(null);
324
+ } else {
325
+ result.sent += 1;
326
+ result.ids.push(outcome.id);
327
+ }
328
+ }
329
+ return result;
330
+ }
331
+ async sendToUser(userId, message, options = {}) {
332
+ if (!this.devices) throw new Error("PushModule: sendToUser needs a PushDeviceStorePort bound to PUSH_DEVICE_STORE.");
333
+ const stored = await this.devices.listByUser(userId);
334
+ const result = await this.send(stored.map((s) => s.device), message, options);
335
+ const dead = stored.filter((s) => result.failed.some((f) => f.stale && f.device === s.device));
336
+ await Promise.all(
337
+ dead.map(
338
+ (s) => this.devices.remove(s.id).catch(
339
+ (error) => this.logger.warn(`Could not remove stale device ${s.id}: ${error instanceof Error ? error.message : String(error)}`)
340
+ )
341
+ )
342
+ );
343
+ return result;
344
+ }
345
+ async sendToTopic(topic, message, options = {}) {
346
+ return this.fcm().sendToTopic(topic, resolveMessage(message, options.lang));
347
+ }
348
+ subscribeToTopic(tokens, topic) {
349
+ return this.fcm().subscribeToTopic(tokens, topic);
350
+ }
351
+ unsubscribeFromTopic(tokens, topic) {
352
+ return this.fcm().unsubscribeFromTopic(tokens, topic);
353
+ }
354
+ fcm() {
355
+ const channel = this.byKind.fcm;
356
+ if (!channel) throw new Error("PushModule: topics need the FCM channel configured.");
357
+ return channel;
358
+ }
359
+ };
360
+ function resolveMessage(message, lang) {
361
+ const text = (value) => isI18nMessage(value) ? translate(value, { lang }) : String(value);
362
+ return {
363
+ ...message,
364
+ title: text(message.title),
365
+ body: text(message.body),
366
+ actions: message.actions?.map((a) => ({ ...a, title: text(a.title) }))
367
+ };
368
+ }
369
+ async function mapLimit(items, limit, fn) {
370
+ const results = new Array(items.length);
371
+ let next = 0;
372
+ const worker = async () => {
373
+ while (next < items.length) {
374
+ const index = next++;
375
+ results[index] = await fn(items[index]);
376
+ }
377
+ };
378
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
379
+ return results;
380
+ }
381
+
382
+ // src/push/push.module.ts
383
+ var env = (k) => process.env[k] || void 0;
384
+ function resolvePushOptions(options = {}) {
385
+ const serviceAccount = env("FIREBASE_SERVICE_ACCOUNT") ?? env("FIREBASE_SERVICE_ACCOUNT_FILE") ?? env("GOOGLE_APPLICATION_CREDENTIALS");
386
+ const subject = env("VAPID_SUBJECT");
387
+ return {
388
+ fcm: options.fcm ?? (serviceAccount ? { serviceAccount } : void 0),
389
+ webPush: options.webPush ?? (subject ? { subject, publicKey: env("VAPID_PUBLIC_KEY") ?? "", privateKey: env("VAPID_PRIVATE_KEY") ?? "" } : void 0),
390
+ whenUnconfigured: options.whenUnconfigured ?? "warn"
391
+ };
392
+ }
393
+ function createPushChannels(options = {}) {
394
+ const resolved = resolvePushOptions(options);
395
+ const channels = [];
396
+ if (resolved.fcm) channels.push(new FcmChannel(resolved.fcm));
397
+ if (resolved.webPush) channels.push(new WebPushChannel(resolved.webPush));
398
+ if (channels.length === 0) {
399
+ const message = "PushModule: no channel configured (fcm / webPush, or FIREBASE_SERVICE_ACCOUNT / VAPID_*). Push is off.";
400
+ if (resolved.whenUnconfigured === "throw") throw new Error(message);
401
+ new Logger2("PushModule").warn(message);
402
+ }
403
+ return channels;
404
+ }
405
+ var PushModule = class {
406
+ static forRoot(options = {}) {
407
+ const { deviceStore, imports, ...pushOptions } = options;
408
+ const providers = [
409
+ { provide: PUSH_OPTIONS, useValue: pushOptions },
410
+ ...deviceStore ? [deviceStore] : [],
411
+ {
412
+ provide: PUSH,
413
+ useFactory: (store) => new PushService(createPushChannels(pushOptions), store ?? void 0),
414
+ inject: [{ token: PUSH_DEVICE_STORE, optional: true }]
415
+ }
416
+ ];
417
+ return { module: PushModule, imports: imports ?? [], providers, exports: [PUSH, PUSH_OPTIONS] };
418
+ }
419
+ static forRootAsync(config) {
420
+ const providers = [
421
+ { provide: PUSH_OPTIONS, useFactory: config.useFactory, inject: config.inject ?? [] },
422
+ ...config.deviceStore ? [config.deviceStore] : [],
423
+ {
424
+ provide: PUSH,
425
+ useFactory: (options, store) => new PushService(createPushChannels(options), store ?? void 0),
426
+ inject: [PUSH_OPTIONS, { token: PUSH_DEVICE_STORE, optional: true }]
427
+ }
428
+ ];
429
+ return { module: PushModule, imports: config.imports ?? [], providers, exports: [PUSH, PUSH_OPTIONS] };
430
+ }
431
+ };
432
+ PushModule = __decorateClass([
433
+ Global(),
434
+ Module({})
435
+ ], PushModule);
436
+ export {
437
+ FcmChannel,
438
+ PUSH,
439
+ PUSH_DEVICE_STORE,
440
+ PUSH_OPTIONS,
441
+ PushModule,
442
+ PushService,
443
+ WebPushChannel,
444
+ createPushChannels,
445
+ parseServiceAccount,
446
+ resolveMessage,
447
+ resolvePushOptions,
448
+ toFcmMessage
449
+ };
@@ -0,0 +1,40 @@
1
+ import { type DynamicModule, type Provider } from '@nestjs/common';
2
+ import { type PushOptions } from './push.options.js';
3
+ import { type PushChannelPort } from './push.port.js';
4
+ /**
5
+ * Merges explicit options with the environment. Recognised vars: fcm
6
+ * `FIREBASE_SERVICE_ACCOUNT` (the JSON), `FIREBASE_SERVICE_ACCOUNT_FILE` or
7
+ * `GOOGLE_APPLICATION_CREDENTIALS` (a path); web push `VAPID_SUBJECT`,
8
+ * `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY`. Pass `false` to switch a channel
9
+ * off even when its env is set.
10
+ */
11
+ export declare function resolvePushOptions(options?: PushOptions): PushOptions;
12
+ /** Builds the channels the options select; a channel given but broken (bad JSON, missing key) throws. */
13
+ export declare function createPushChannels(options?: PushOptions): PushChannelPort[];
14
+ /**
15
+ * Push notifications to native apps (FCM) and browsers (Web Push) behind one
16
+ * port. Register once and inject `@Inject(PUSH) push: PushPort`.
17
+ *
18
+ * ```ts
19
+ * PushModule.forRoot() // whatever the env configures
20
+ * PushModule.forRoot({ fcm: { serviceAccount }, webPush: false })
21
+ * PushModule.forRoot({ imports: [MiStoreModule], deviceStore: { provide: PUSH_DEVICE_STORE, useExisting: MiStore } })
22
+ * ```
23
+ *
24
+ * Unlike `email`, an unconfigured module warns instead of throwing by
25
+ * default: the Firebase credential is typically a post-deploy step, and a
26
+ * missing push channel must not take the whole API down. `whenUnconfigured:
27
+ * 'throw'` restores the strict rule.
28
+ */
29
+ export declare class PushModule {
30
+ static forRoot(options?: PushOptions & {
31
+ deviceStore?: Provider;
32
+ imports?: any[];
33
+ }): DynamicModule;
34
+ static forRootAsync(config: {
35
+ imports?: any[];
36
+ inject?: any[];
37
+ useFactory: (...args: any[]) => PushOptions | Promise<PushOptions>;
38
+ deviceStore?: Provider;
39
+ }): DynamicModule;
40
+ }
@@ -0,0 +1,40 @@
1
+ /** DI token carrying the resolved {@link PushOptions}. */
2
+ export declare const PUSH_OPTIONS: unique symbol;
3
+ /** The Firebase service account, as the JSON Google hands out. Only these fields are used. */
4
+ export interface FirebaseServiceAccount {
5
+ project_id: string;
6
+ client_email: string;
7
+ private_key: string;
8
+ /** Defaults to `https://oauth2.googleapis.com/token`. */
9
+ token_uri?: string;
10
+ }
11
+ export interface FcmOptions {
12
+ /**
13
+ * The service account: the parsed JSON, the JSON as a string
14
+ * (`FIREBASE_SERVICE_ACCOUNT`), or a path to the file
15
+ * (`FIREBASE_SERVICE_ACCOUNT_FILE` / `GOOGLE_APPLICATION_CREDENTIALS`).
16
+ */
17
+ serviceAccount: FirebaseServiceAccount | string;
18
+ /** For tests. Defaults to the global `fetch`. */
19
+ fetchImpl?: typeof fetch;
20
+ }
21
+ export interface WebPushOptions {
22
+ /** `mailto:` or `https:` — who to contact about this sender. `VAPID_SUBJECT`. */
23
+ subject: string;
24
+ publicKey: string;
25
+ privateKey: string;
26
+ }
27
+ export interface PushOptions {
28
+ /** Native apps through Firebase Cloud Messaging. Off when omitted and no env is set. */
29
+ fcm?: FcmOptions | false;
30
+ /** Browsers through the Web Push protocol (VAPID). Off when omitted and no env is set. */
31
+ webPush?: WebPushOptions | false;
32
+ /**
33
+ * What to do when neither channel is configured. `'warn'` (default) logs
34
+ * once at boot and every send comes back failed with
35
+ * `channel_not_configured` — the app stays up, push is simply off, which
36
+ * is the right outcome when the credential is a post-deploy step. `'throw'`
37
+ * refuses to boot instead.
38
+ */
39
+ whenUnconfigured?: 'warn' | 'throw';
40
+ }
@@ -0,0 +1,148 @@
1
+ import type { I18nMessage } from '../i18n/message.js';
2
+ /** DI token for the {@link PushPort}. Inject with `@Inject(PUSH)`. */
3
+ export declare const PUSH: unique symbol;
4
+ /** Bind to a {@link PushDeviceStorePort} to get `sendToUser` and automatic pruning. Optional. */
5
+ export declare const PUSH_DEVICE_STORE: unique symbol;
6
+ /** A native app's FCM registration token (iOS, Android — or web through the Firebase SDK). */
7
+ export interface FcmDevice {
8
+ kind: 'fcm';
9
+ token: string;
10
+ }
11
+ /** A browser's Web Push subscription, as `PushManager.subscribe()` returned it. */
12
+ export interface WebPushDevice {
13
+ kind: 'webpush';
14
+ endpoint: string;
15
+ keys: {
16
+ p256dh: string;
17
+ auth: string;
18
+ };
19
+ }
20
+ export type PushDevice = FcmDevice | WebPushDevice;
21
+ /** A button on the notification. */
22
+ export interface PushAction {
23
+ /** What the client receives when it is tapped. Stable, like an error code. */
24
+ id: string;
25
+ title: string | I18nMessage;
26
+ /** Where that button takes the person. Absolute `https` URL, or the app's own deep link. */
27
+ link?: string;
28
+ /** Web only: the button's icon URL. */
29
+ icon?: string;
30
+ }
31
+ /**
32
+ * One notification, the same for every platform. Each channel translates
33
+ * it into what its platform can show — and what it cannot, it ships in
34
+ * `data` so the app can (see `dataOnly` and the README).
35
+ */
36
+ export interface PushMessage {
37
+ title: string | I18nMessage;
38
+ body: string | I18nMessage;
39
+ /** Large picture. iOS needs a Notification Service Extension to show it. */
40
+ imageUrl?: string;
41
+ /** Small icon, web only (Android uses the app's; iOS has none). */
42
+ icon?: string;
43
+ /** Where a tap on the notification body goes. `https` URL for the web; a deep link for the apps. */
44
+ link?: string;
45
+ /** Buttons. Native on the web; iOS shows them for the registered `category`; Android only when the app renders (`dataOnly`). */
46
+ actions?: PushAction[];
47
+ /**
48
+ * Arbitrary key/values the app receives. FCM only carries strings; other
49
+ * values are JSON-encoded. `link`, `actions` and `category` are added here
50
+ * too, so a client that builds its own notification has everything.
51
+ */
52
+ data?: Record<string, unknown>;
53
+ /** iOS: the `UNNotificationCategory` identifier the app registered — that is what gives it buttons. */
54
+ category?: string;
55
+ /** Android: the notification channel (required on Android 8+ for the sound/priority the channel defines). */
56
+ androidChannelId?: string;
57
+ /** Badge count (iOS, and web where supported). */
58
+ badge?: number;
59
+ /** Sound file name, or `default`. Default `default`. */
60
+ sound?: string;
61
+ /** Replaces an earlier notification with the same tag/collapse key instead of stacking. */
62
+ collapseKey?: string;
63
+ /** Seconds the platform may hold the message for an offline device. */
64
+ ttlSeconds?: number;
65
+ /** `high` wakes the device now; `normal` may wait for the next batch. Default `high`. */
66
+ priority?: 'high' | 'normal';
67
+ /**
68
+ * Ship everything in `data` and no `notification` block: the app receives
69
+ * it in the background handler and renders the notification itself — the
70
+ * only way to get buttons on Android, and to fully control look and
71
+ * behaviour on both platforms. Web Push is always this: the service
72
+ * worker renders.
73
+ */
74
+ dataOnly?: boolean;
75
+ }
76
+ export interface PushFailure {
77
+ device: PushDevice;
78
+ /** Provider's code (`UNREGISTERED`, `QUOTA_EXCEEDED`, `410`…) or `channel_not_configured`. */
79
+ code: string;
80
+ message: string;
81
+ /**
82
+ * The device is gone for good — app uninstalled, token rotated,
83
+ * subscription expired. The caller should delete it; `sendToUser` does.
84
+ * Never set for a transient or ambiguous failure: deleting a live device
85
+ * over a malformed payload loses it for nothing.
86
+ */
87
+ stale: boolean;
88
+ }
89
+ export interface PushResult {
90
+ sent: number;
91
+ failed: PushFailure[];
92
+ /** Provider message ids, in device order, for the ones that went. */
93
+ ids: (string | null)[];
94
+ }
95
+ export interface SendOptions {
96
+ /** Language for `I18nMessage` titles and bodies. Defaults to the request's, then the i18n fallback. */
97
+ lang?: string;
98
+ }
99
+ /**
100
+ * What the app sees: one `send`, whatever the device. Each channel behind
101
+ * it (FCM, Web Push) is configured or not; a device whose channel is off
102
+ * comes back as a failure, never as a throw — one dead channel must not
103
+ * stop the others, and a missing credential must not stop the app.
104
+ */
105
+ export interface PushPort {
106
+ send(devices: PushDevice | PushDevice[], message: PushMessage, options?: SendOptions): Promise<PushResult>;
107
+ /** FCM topics. Fails as a whole when FCM is not configured. */
108
+ sendToTopic(topic: string, message: PushMessage, options?: SendOptions): Promise<{
109
+ id: string | null;
110
+ }>;
111
+ subscribeToTopic(tokens: string[], topic: string): Promise<void>;
112
+ unsubscribeFromTopic(tokens: string[], topic: string): Promise<void>;
113
+ /** Which channels are live. For a settings screen, or to skip work. */
114
+ channels(): {
115
+ fcm: boolean;
116
+ webpush: boolean;
117
+ };
118
+ /** All of a user's devices, with stale ones deleted afterwards. Needs `PUSH_DEVICE_STORE`. */
119
+ sendToUser(userId: string, message: PushMessage, options?: SendOptions): Promise<PushResult>;
120
+ }
121
+ /** A device row the consumer keeps: the device, plus the id to delete it by. */
122
+ export interface StoredPushDevice {
123
+ id: string;
124
+ device: PushDevice;
125
+ }
126
+ /**
127
+ * Persistence for a user's devices. Registration (upsert on token, platform,
128
+ * user agent…) stays the consumer's; this is only what sending needs.
129
+ */
130
+ export interface PushDeviceStorePort {
131
+ listByUser(userId: string): Promise<StoredPushDevice[]>;
132
+ remove(id: string): Promise<void>;
133
+ }
134
+ /** One platform's plumbing. */
135
+ export interface PushChannelPort {
136
+ readonly kind: PushDevice['kind'];
137
+ send(device: PushDevice, message: ResolvedPushMessage): Promise<{
138
+ id: string | null;
139
+ } | Omit<PushFailure, 'device'>>;
140
+ }
141
+ /** A message with every `I18nMessage` already turned into text. */
142
+ export type ResolvedPushMessage = Omit<PushMessage, 'title' | 'body' | 'actions'> & {
143
+ title: string;
144
+ body: string;
145
+ actions?: (Omit<PushAction, 'title'> & {
146
+ title: string;
147
+ })[];
148
+ };