@chipmobilesdk/rn-notification 0.1.2 → 0.2.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.
Files changed (69) hide show
  1. package/CHANGELOG.md +96 -42
  2. package/README.md +399 -306
  3. package/package.json +2 -1
  4. package/skills/sdk-rn-notification/SKILL.md +68 -3
  5. package/src/channel/migrate.ts +86 -12
  6. package/src/channel/tone-map.ts +130 -90
  7. package/src/channel/validate-tone.ts +61 -0
  8. package/src/contract/channel.ts +188 -89
  9. package/src/contract/diagnostics.ts +102 -102
  10. package/src/contract/errors.ts +130 -123
  11. package/src/contract/index.ts +10 -10
  12. package/src/contract/interaction.ts +62 -62
  13. package/src/contract/notification.ts +118 -118
  14. package/src/contract/permission.ts +60 -60
  15. package/src/contract/reconcile.ts +88 -88
  16. package/src/contract/recurrence.ts +123 -123
  17. package/src/diagnostics/burst.ts +101 -101
  18. package/src/diagnostics/events.ts +72 -72
  19. package/src/diagnostics/redact.ts +72 -72
  20. package/src/diagnostics/snapshot.ts +64 -64
  21. package/src/engine/adapter.ts +172 -79
  22. package/src/engine/notify-kit-engine.ts +761 -535
  23. package/src/index.ts +24 -0
  24. package/src/initialize.ts +174 -174
  25. package/src/interaction/index.ts +146 -146
  26. package/src/maintenance/cycle.ts +147 -147
  27. package/src/maintenance/permission-refresh.ts +41 -41
  28. package/src/maintenance/reanchor.ts +95 -95
  29. package/src/maintenance/toggle.ts +60 -60
  30. package/src/maintenance/verify.ts +83 -83
  31. package/src/maintenance/window-refresh.ts +61 -61
  32. package/src/permission/index.ts +183 -183
  33. package/src/permission/state.ts +77 -77
  34. package/src/push/envelope.ts +165 -165
  35. package/src/push/fcm-provider.ts +146 -146
  36. package/src/push/gate.ts +190 -190
  37. package/src/push/instructions.ts +109 -109
  38. package/src/push/provider-adapter.ts +54 -54
  39. package/src/push/signout.ts +65 -65
  40. package/src/reconcile/chunk.ts +53 -53
  41. package/src/reconcile/diff.ts +145 -145
  42. package/src/reconcile/duplicates.ts +73 -73
  43. package/src/reconcile/index.ts +14 -1
  44. package/src/reconcile/truncate.ts +56 -56
  45. package/src/recurrence/clock-guard.ts +71 -71
  46. package/src/recurrence/expand.ts +292 -292
  47. package/src/repeat/expiry.ts +55 -0
  48. package/src/repeat/index.ts +54 -0
  49. package/src/repeat/marker.ts +72 -0
  50. package/src/repeat/place.ts +73 -0
  51. package/src/schedule/anchor.ts +267 -267
  52. package/src/schedule/index.ts +184 -173
  53. package/src/schedule/partition.ts +85 -85
  54. package/src/schedule/resolve-moment.ts +80 -80
  55. package/src/schedule/validate-content.ts +111 -111
  56. package/src/schedule/validate-identifier.ts +126 -114
  57. package/src/state/caps.ts +71 -71
  58. package/src/state/interaction-buffer.ts +73 -73
  59. package/src/state/mmkv-store.ts +75 -71
  60. package/src/state/permission-history.ts +41 -41
  61. package/src/state/record.ts +258 -246
  62. package/src/state/reset.ts +41 -41
  63. package/src/state/series-ledger.ts +84 -84
  64. package/src/state/store.ts +40 -40
  65. package/src/testing/conformance/index.ts +248 -194
  66. package/src/testing/fake-engine.ts +469 -284
  67. package/src/testing/fake-provider.ts +129 -129
  68. package/src/testing/faults.ts +72 -72
  69. package/src/testing/measure.ts +337 -334
@@ -1,165 +1,165 @@
1
- /**
2
- * Payload normalization.
3
- *
4
- * Every provider's payload is reduced to one envelope shape before it reaches
5
- * the consumer, so changing provider costs consumer code nothing.
6
- *
7
- * Version handling is best-effort: a payload declaring a version this build
8
- * does not implement is still processed, honouring the fields it understands
9
- * and ignoring the rest. Servers deploy ahead of app adoption and old app
10
- * versions live on devices for months, so gating every server-side change on
11
- * app rollout is the more expensive failure.
12
- *
13
- * That is only safe under an append-only discipline — a released field's
14
- * meaning must never be repurposed. The version-skew diagnostic exists so a
15
- * misprocessing incident is traceable to the skew rather than investigated as a
16
- * logic defect.
17
- */
18
-
19
- import type { PushEnvelope } from './provider-adapter';
20
- import { DIAGNOSTIC_CODES, NotificationError } from '../contract/errors';
21
-
22
- /** The contract version this build implements. */
23
- export const IMPLEMENTED_PAYLOAD_VERSION = 1;
24
-
25
- const KINDS = new Set(['display', 'data', 'schedule', 'cancel']);
26
-
27
- function asRecord(value: unknown): Record<string, unknown> | undefined {
28
- return typeof value === 'object' && value !== null && !Array.isArray(value)
29
- ? (value as Record<string, unknown>)
30
- : undefined;
31
- }
32
-
33
- /**
34
- * Text, or nothing.
35
- *
36
- * Deliberately not `String(value)`: an object coerces to the literal string
37
- * "[object Object]", which would be rendered to the user as a notification
38
- * title. A field that is not text is treated as absent.
39
- */
40
- function asText(value: unknown): string | undefined {
41
- if (typeof value === 'string') return value;
42
- if (typeof value === 'number' && Number.isFinite(value)) return String(value);
43
- return undefined;
44
- }
45
-
46
- /** An epoch instant from either a number or an ISO-8601 string. */
47
- function asInstant(value: unknown): number {
48
- if (typeof value === 'number' && Number.isFinite(value)) return value;
49
- if (typeof value === 'string') return Date.parse(value);
50
- return Number.NaN;
51
- }
52
-
53
- /** Extracts and validates the contract version, which every payload must declare. */
54
- function readVersion(body: Record<string, unknown>): number {
55
- const raw = body.v;
56
- const version = typeof raw === 'number' ? raw : Number.parseInt(asText(raw) ?? '', 10);
57
-
58
- if (!Number.isInteger(version) || version < 1) {
59
- throw new NotificationError(
60
- DIAGNOSTIC_CODES.PAYLOAD_MALFORMED,
61
- 'Push payload carries no usable contract version. Every payload must declare `v` from the first release.',
62
- { received: typeof raw },
63
- );
64
- }
65
- return version;
66
- }
67
-
68
- function readKind(body: Record<string, unknown>): PushEnvelope['kind'] {
69
- const kind = asText(body.kind);
70
-
71
- if (kind === undefined || !KINDS.has(kind)) {
72
- throw new NotificationError(
73
- DIAGNOSTIC_CODES.PAYLOAD_MALFORMED,
74
- `Push payload declares unknown kind "${kind ?? ''}".`,
75
- { kind },
76
- );
77
- }
78
- return kind as PushEnvelope['kind'];
79
- }
80
-
81
- function readId(body: Record<string, unknown>): string {
82
- const id = asText(body.id);
83
-
84
- if (id === undefined || id.length === 0) {
85
- throw new NotificationError(
86
- DIAGNOSTIC_CODES.PAYLOAD_MALFORMED,
87
- 'Push payload carries no identifier.',
88
- );
89
- }
90
- return id;
91
- }
92
-
93
- function readContent(body: Record<string, unknown>): PushEnvelope['content'] {
94
- const content = asRecord(body.content);
95
- if (content === undefined) return undefined;
96
-
97
- return {
98
- title: asText(content.title) ?? '',
99
- body: asText(content.body) ?? '',
100
- subtitle: asText(content.subtitle),
101
- };
102
- }
103
-
104
- function readMoment(body: Record<string, unknown>): PushEnvelope['moment'] {
105
- const moment = asRecord(body.moment);
106
- if (moment === undefined) return undefined;
107
-
108
- return {
109
- at: asInstant(moment.at),
110
- anchoring: moment.anchoring === 'absolute' ? 'absolute' : 'wallClock',
111
- };
112
- }
113
-
114
- export interface NormalizeResult {
115
- readonly envelope: PushEnvelope;
116
- readonly versionSkew: boolean;
117
- }
118
-
119
- /**
120
- * Normalizes a raw provider payload.
121
- *
122
- * Throws only for a **structurally unparseable** payload — a broken message.
123
- * An unrecognized version is a healthy message from a newer contract and must
124
- * never collapse into the same condition.
125
- */
126
- export function normalizeEnvelope(raw: unknown, receivedAt: number): NormalizeResult {
127
- const record = asRecord(raw);
128
- if (record === undefined) {
129
- throw new NotificationError(
130
- DIAGNOSTIC_CODES.PAYLOAD_MALFORMED,
131
- 'Push payload is not an object and cannot be interpreted.',
132
- { received: Array.isArray(raw) ? 'array' : typeof raw },
133
- );
134
- }
135
-
136
- // Providers deliver the payload under a data bag; accept either shape so the
137
- // adapter does not have to reshape before handing it over.
138
- const body = asRecord(record.data) ?? record;
139
-
140
- const version = readVersion(body);
141
- const kind = readKind(body);
142
- const id = readId(body);
143
- const versionSkew = version !== IMPLEMENTED_PAYLOAD_VERSION;
144
-
145
- return {
146
- versionSkew,
147
- envelope: {
148
- version,
149
- kind,
150
- id,
151
- ownerTag: asText(body.ownerTag),
152
- content: readContent(body),
153
- tone: asText(body.tone),
154
- moment: readMoment(body),
155
- routing: asRecord(body.routing),
156
- // Falls back to the identifier, so a server that omits it still gets
157
- // de-duplication rather than silently losing it.
158
- dedupId: asText(body.dedupId) ?? id,
159
- receivedAt,
160
- versionSkew,
161
- // Fields this build does not understand are simply not read — that is
162
- // what best-effort processing means in practice.
163
- },
164
- };
165
- }
1
+ /**
2
+ * Payload normalization.
3
+ *
4
+ * Every provider's payload is reduced to one envelope shape before it reaches
5
+ * the consumer, so changing provider costs consumer code nothing.
6
+ *
7
+ * Version handling is best-effort: a payload declaring a version this build
8
+ * does not implement is still processed, honouring the fields it understands
9
+ * and ignoring the rest. Servers deploy ahead of app adoption and old app
10
+ * versions live on devices for months, so gating every server-side change on
11
+ * app rollout is the more expensive failure.
12
+ *
13
+ * That is only safe under an append-only discipline — a released field's
14
+ * meaning must never be repurposed. The version-skew diagnostic exists so a
15
+ * misprocessing incident is traceable to the skew rather than investigated as a
16
+ * logic defect.
17
+ */
18
+
19
+ import type { PushEnvelope } from './provider-adapter';
20
+ import { DIAGNOSTIC_CODES, NotificationError } from '../contract/errors';
21
+
22
+ /** The contract version this build implements. */
23
+ export const IMPLEMENTED_PAYLOAD_VERSION = 1;
24
+
25
+ const KINDS = new Set(['display', 'data', 'schedule', 'cancel']);
26
+
27
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
28
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
29
+ ? (value as Record<string, unknown>)
30
+ : undefined;
31
+ }
32
+
33
+ /**
34
+ * Text, or nothing.
35
+ *
36
+ * Deliberately not `String(value)`: an object coerces to the literal string
37
+ * "[object Object]", which would be rendered to the user as a notification
38
+ * title. A field that is not text is treated as absent.
39
+ */
40
+ function asText(value: unknown): string | undefined {
41
+ if (typeof value === 'string') return value;
42
+ if (typeof value === 'number' && Number.isFinite(value)) return String(value);
43
+ return undefined;
44
+ }
45
+
46
+ /** An epoch instant from either a number or an ISO-8601 string. */
47
+ function asInstant(value: unknown): number {
48
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
49
+ if (typeof value === 'string') return Date.parse(value);
50
+ return Number.NaN;
51
+ }
52
+
53
+ /** Extracts and validates the contract version, which every payload must declare. */
54
+ function readVersion(body: Record<string, unknown>): number {
55
+ const raw = body.v;
56
+ const version = typeof raw === 'number' ? raw : Number.parseInt(asText(raw) ?? '', 10);
57
+
58
+ if (!Number.isInteger(version) || version < 1) {
59
+ throw new NotificationError(
60
+ DIAGNOSTIC_CODES.PAYLOAD_MALFORMED,
61
+ 'Push payload carries no usable contract version. Every payload must declare `v` from the first release.',
62
+ { received: typeof raw },
63
+ );
64
+ }
65
+ return version;
66
+ }
67
+
68
+ function readKind(body: Record<string, unknown>): PushEnvelope['kind'] {
69
+ const kind = asText(body.kind);
70
+
71
+ if (kind === undefined || !KINDS.has(kind)) {
72
+ throw new NotificationError(
73
+ DIAGNOSTIC_CODES.PAYLOAD_MALFORMED,
74
+ `Push payload declares unknown kind "${kind ?? ''}".`,
75
+ { kind },
76
+ );
77
+ }
78
+ return kind as PushEnvelope['kind'];
79
+ }
80
+
81
+ function readId(body: Record<string, unknown>): string {
82
+ const id = asText(body.id);
83
+
84
+ if (id === undefined || id.length === 0) {
85
+ throw new NotificationError(
86
+ DIAGNOSTIC_CODES.PAYLOAD_MALFORMED,
87
+ 'Push payload carries no identifier.',
88
+ );
89
+ }
90
+ return id;
91
+ }
92
+
93
+ function readContent(body: Record<string, unknown>): PushEnvelope['content'] {
94
+ const content = asRecord(body.content);
95
+ if (content === undefined) return undefined;
96
+
97
+ return {
98
+ title: asText(content.title) ?? '',
99
+ body: asText(content.body) ?? '',
100
+ subtitle: asText(content.subtitle),
101
+ };
102
+ }
103
+
104
+ function readMoment(body: Record<string, unknown>): PushEnvelope['moment'] {
105
+ const moment = asRecord(body.moment);
106
+ if (moment === undefined) return undefined;
107
+
108
+ return {
109
+ at: asInstant(moment.at),
110
+ anchoring: moment.anchoring === 'absolute' ? 'absolute' : 'wallClock',
111
+ };
112
+ }
113
+
114
+ export interface NormalizeResult {
115
+ readonly envelope: PushEnvelope;
116
+ readonly versionSkew: boolean;
117
+ }
118
+
119
+ /**
120
+ * Normalizes a raw provider payload.
121
+ *
122
+ * Throws only for a **structurally unparseable** payload — a broken message.
123
+ * An unrecognized version is a healthy message from a newer contract and must
124
+ * never collapse into the same condition.
125
+ */
126
+ export function normalizeEnvelope(raw: unknown, receivedAt: number): NormalizeResult {
127
+ const record = asRecord(raw);
128
+ if (record === undefined) {
129
+ throw new NotificationError(
130
+ DIAGNOSTIC_CODES.PAYLOAD_MALFORMED,
131
+ 'Push payload is not an object and cannot be interpreted.',
132
+ { received: Array.isArray(raw) ? 'array' : typeof raw },
133
+ );
134
+ }
135
+
136
+ // Providers deliver the payload under a data bag; accept either shape so the
137
+ // adapter does not have to reshape before handing it over.
138
+ const body = asRecord(record.data) ?? record;
139
+
140
+ const version = readVersion(body);
141
+ const kind = readKind(body);
142
+ const id = readId(body);
143
+ const versionSkew = version !== IMPLEMENTED_PAYLOAD_VERSION;
144
+
145
+ return {
146
+ versionSkew,
147
+ envelope: {
148
+ version,
149
+ kind,
150
+ id,
151
+ ownerTag: asText(body.ownerTag),
152
+ content: readContent(body),
153
+ tone: asText(body.tone),
154
+ moment: readMoment(body),
155
+ routing: asRecord(body.routing),
156
+ // Falls back to the identifier, so a server that omits it still gets
157
+ // de-duplication rather than silently losing it.
158
+ dedupId: asText(body.dedupId) ?? id,
159
+ receivedAt,
160
+ versionSkew,
161
+ // Fields this build does not understand are simply not read — that is
162
+ // what best-effort processing means in practice.
163
+ },
164
+ };
165
+ }
@@ -1,146 +1,146 @@
1
- /**
2
- * The Firebase Cloud Messaging provider.
3
- *
4
- * Every `@react-native-firebase/messaging` import is confined to this file, so
5
- * the rest of the package — and every consuming app — stays free of provider
6
- * types. Substituting a provider is an adapter swap, not a rewrite.
7
- *
8
- * The module is required **lazily**. That matters more here than for the
9
- * engine: messaging is an *optional* peer dependency, and an app that never
10
- * enables push must not fail at import time for a package it deliberately did
11
- * not install.
12
- */
13
-
14
- import type {
15
- PushAvailability,
16
- PushProviderAdapter,
17
- } from './provider-adapter';
18
- import type { Unsubscribe } from '../contract/interaction';
19
-
20
- /** Minimal shape used from the SDK, so its full surface never leaks into typing. */
21
- interface MessagingModule {
22
- (): MessagingInstance;
23
- AuthorizationStatus?: Record<string, number>;
24
- }
25
-
26
- interface MessagingInstance {
27
- getToken(): Promise<string>;
28
- deleteToken(): Promise<void>;
29
- onTokenRefresh(handler: (token: string) => void): () => void;
30
- onMessage(handler: (message: unknown) => Promise<void> | void): () => void;
31
- setBackgroundMessageHandler(handler: (message: unknown) => Promise<void>): void;
32
- getInitialNotification(): Promise<unknown | null>;
33
- hasPermission?(): Promise<number>;
34
- isDeviceRegisteredForRemoteMessages?: boolean;
35
- }
36
-
37
- function loadMessaging(): MessagingModule | undefined {
38
- try {
39
- const module = require('@react-native-firebase/messaging') as { default: MessagingModule };
40
- return module.default;
41
- } catch {
42
- // Absent optional peer, or missing native module. Reported as
43
- // unavailability through the normal path rather than thrown at import.
44
- return undefined;
45
- }
46
- }
47
-
48
- export interface FcmProviderOptions {
49
- /** Injected in tests; production resolves the real module. */
50
- readonly module?: MessagingModule;
51
- /**
52
- * Registers the background message handler.
53
- *
54
- * Left to the consumer by default because the SDK requires it to be
55
- * registered at module scope in `index.js`, outside React's lifecycle — a
56
- * constraint the package documents rather than works around.
57
- */
58
- readonly onBackgroundMessage?: (message: unknown) => Promise<void>;
59
- }
60
-
61
- export function createFcmProvider(options: FcmProviderOptions = {}): PushProviderAdapter {
62
- let cached: MessagingModule | undefined = options.module;
63
- let resolved = options.module !== undefined;
64
-
65
- const messaging = (): MessagingInstance | undefined => {
66
- if (!resolved) {
67
- cached = loadMessaging();
68
- resolved = true;
69
- }
70
- return cached?.();
71
- };
72
-
73
- if (options.onBackgroundMessage !== undefined) {
74
- messaging()?.setBackgroundMessageHandler(options.onBackgroundMessage);
75
- }
76
-
77
- return {
78
- name: '@react-native-firebase/messaging',
79
-
80
- async getAvailability(): Promise<PushAvailability> {
81
- const instance = messaging();
82
-
83
- // A device without Google Play Services, or an app that never installed
84
- // the optional peer. Either way the local path is unaffected.
85
- if (instance === undefined) return 'unavailable';
86
-
87
- try {
88
- await instance.getToken();
89
- return 'available';
90
- } catch {
91
- // Registration can fail for reasons the SDK does not distinguish, so
92
- // `unknown` is reported rather than a guess at which one.
93
- return 'unknown';
94
- }
95
- },
96
-
97
- async getToken(): Promise<string> {
98
- const instance = messaging();
99
- if (instance === undefined) {
100
- throw new Error('Push provider is unavailable on this device.');
101
- }
102
- // Resolves only once a genuine token exists; the gate never presents an
103
- // empty value as if it were one.
104
- return instance.getToken();
105
- },
106
-
107
- onTokenChange(handler: (token: string) => void): Unsubscribe {
108
- const instance = messaging();
109
- if (instance === undefined) return () => undefined;
110
- return instance.onTokenRefresh(handler);
111
- },
112
-
113
- async invalidateToken(): Promise<boolean> {
114
- const instance = messaging();
115
- if (instance === undefined) return false;
116
-
117
- try {
118
- await instance.deleteToken();
119
- return true;
120
- } catch {
121
- // Reported as a failed invalidation rather than assumed successful —
122
- // the device may keep receiving the previous account's messages.
123
- return false;
124
- }
125
- },
126
-
127
- subscribeToMessages(handler: (raw: unknown) => void): Unsubscribe {
128
- const instance = messaging();
129
- if (instance === undefined) return () => undefined;
130
-
131
- // Foreground only. Background delivery arrives through the handler the
132
- // consumer registers at module scope, which the README documents.
133
- return instance.onMessage(message => {
134
- handler(message);
135
- });
136
- },
137
-
138
- async takeInitialMessage(): Promise<unknown | undefined> {
139
- const instance = messaging();
140
- if (instance === undefined) return undefined;
141
-
142
- const message = await instance.getInitialNotification();
143
- return message ?? undefined;
144
- },
145
- };
146
- }
1
+ /**
2
+ * The Firebase Cloud Messaging provider.
3
+ *
4
+ * Every `@react-native-firebase/messaging` import is confined to this file, so
5
+ * the rest of the package — and every consuming app — stays free of provider
6
+ * types. Substituting a provider is an adapter swap, not a rewrite.
7
+ *
8
+ * The module is required **lazily**. That matters more here than for the
9
+ * engine: messaging is an *optional* peer dependency, and an app that never
10
+ * enables push must not fail at import time for a package it deliberately did
11
+ * not install.
12
+ */
13
+
14
+ import type {
15
+ PushAvailability,
16
+ PushProviderAdapter,
17
+ } from './provider-adapter';
18
+ import type { Unsubscribe } from '../contract/interaction';
19
+
20
+ /** Minimal shape used from the SDK, so its full surface never leaks into typing. */
21
+ interface MessagingModule {
22
+ (): MessagingInstance;
23
+ AuthorizationStatus?: Record<string, number>;
24
+ }
25
+
26
+ interface MessagingInstance {
27
+ getToken(): Promise<string>;
28
+ deleteToken(): Promise<void>;
29
+ onTokenRefresh(handler: (token: string) => void): () => void;
30
+ onMessage(handler: (message: unknown) => Promise<void> | void): () => void;
31
+ setBackgroundMessageHandler(handler: (message: unknown) => Promise<void>): void;
32
+ getInitialNotification(): Promise<unknown | null>;
33
+ hasPermission?(): Promise<number>;
34
+ isDeviceRegisteredForRemoteMessages?: boolean;
35
+ }
36
+
37
+ function loadMessaging(): MessagingModule | undefined {
38
+ try {
39
+ const module = require('@react-native-firebase/messaging') as { default: MessagingModule };
40
+ return module.default;
41
+ } catch {
42
+ // Absent optional peer, or missing native module. Reported as
43
+ // unavailability through the normal path rather than thrown at import.
44
+ return undefined;
45
+ }
46
+ }
47
+
48
+ export interface FcmProviderOptions {
49
+ /** Injected in tests; production resolves the real module. */
50
+ readonly module?: MessagingModule;
51
+ /**
52
+ * Registers the background message handler.
53
+ *
54
+ * Left to the consumer by default because the SDK requires it to be
55
+ * registered at module scope in `index.js`, outside React's lifecycle — a
56
+ * constraint the package documents rather than works around.
57
+ */
58
+ readonly onBackgroundMessage?: (message: unknown) => Promise<void>;
59
+ }
60
+
61
+ export function createFcmProvider(options: FcmProviderOptions = {}): PushProviderAdapter {
62
+ let cached: MessagingModule | undefined = options.module;
63
+ let resolved = options.module !== undefined;
64
+
65
+ const messaging = (): MessagingInstance | undefined => {
66
+ if (!resolved) {
67
+ cached = loadMessaging();
68
+ resolved = true;
69
+ }
70
+ return cached?.();
71
+ };
72
+
73
+ if (options.onBackgroundMessage !== undefined) {
74
+ messaging()?.setBackgroundMessageHandler(options.onBackgroundMessage);
75
+ }
76
+
77
+ return {
78
+ name: '@react-native-firebase/messaging',
79
+
80
+ async getAvailability(): Promise<PushAvailability> {
81
+ const instance = messaging();
82
+
83
+ // A device without Google Play Services, or an app that never installed
84
+ // the optional peer. Either way the local path is unaffected.
85
+ if (instance === undefined) return 'unavailable';
86
+
87
+ try {
88
+ await instance.getToken();
89
+ return 'available';
90
+ } catch {
91
+ // Registration can fail for reasons the SDK does not distinguish, so
92
+ // `unknown` is reported rather than a guess at which one.
93
+ return 'unknown';
94
+ }
95
+ },
96
+
97
+ async getToken(): Promise<string> {
98
+ const instance = messaging();
99
+ if (instance === undefined) {
100
+ throw new Error('Push provider is unavailable on this device.');
101
+ }
102
+ // Resolves only once a genuine token exists; the gate never presents an
103
+ // empty value as if it were one.
104
+ return instance.getToken();
105
+ },
106
+
107
+ onTokenChange(handler: (token: string) => void): Unsubscribe {
108
+ const instance = messaging();
109
+ if (instance === undefined) return () => undefined;
110
+ return instance.onTokenRefresh(handler);
111
+ },
112
+
113
+ async invalidateToken(): Promise<boolean> {
114
+ const instance = messaging();
115
+ if (instance === undefined) return false;
116
+
117
+ try {
118
+ await instance.deleteToken();
119
+ return true;
120
+ } catch {
121
+ // Reported as a failed invalidation rather than assumed successful —
122
+ // the device may keep receiving the previous account's messages.
123
+ return false;
124
+ }
125
+ },
126
+
127
+ subscribeToMessages(handler: (raw: unknown) => void): Unsubscribe {
128
+ const instance = messaging();
129
+ if (instance === undefined) return () => undefined;
130
+
131
+ // Foreground only. Background delivery arrives through the handler the
132
+ // consumer registers at module scope, which the README documents.
133
+ return instance.onMessage(message => {
134
+ handler(message);
135
+ });
136
+ },
137
+
138
+ async takeInitialMessage(): Promise<unknown | undefined> {
139
+ const instance = messaging();
140
+ if (instance === undefined) return undefined;
141
+
142
+ const message = await instance.getInitialNotification();
143
+ return message ?? undefined;
144
+ },
145
+ };
146
+ }