@rivium/push-web 0.1.6 → 0.1.8

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 CHANGED
@@ -50,6 +50,25 @@ cp node_modules/@rivium/push-web/service-worker.js public/rivium-push-sw.js
50
50
  curl -o public/rivium-push-sw.js https://unpkg.com/@rivium/push-web/service-worker.js
51
51
  ```
52
52
 
53
+ Let the SDK register it (`init()` does this for you). It registers the worker
54
+ with its API key and device id on the URL, and mirrors the same values into
55
+ IndexedDB under `rivium-push` / `config`.
56
+
57
+ The worker needs those two values to confirm delivery and to re-register a
58
+ subscription the browser replaces. It reads the URL first and falls back to
59
+ storage, so it keeps working even when something else registered
60
+ `/rivium-push-sw.js` without the query string - your own
61
+ `navigator.serviceWorker.register` call, another library, or a hot reload in
62
+ development. Nothing secret is stored: the API key is public and already in
63
+ your page.
64
+
65
+ Where IndexedDB is unavailable (private windows, blocked site data), only the
66
+ URL is used, exactly as before. A worker with neither says so in the console:
67
+
68
+ ```
69
+ [RiviumPush SW] Delivery ack skipped - no SDK config in the worker URL or in storage
70
+ ```
71
+
53
72
  ## Quick Start
54
73
 
55
74
  ```typescript
@@ -295,6 +314,47 @@ await riviumPush.inbox.markAllAsRead();
295
314
  Messages are cached per device and restored on the next page load. The cache is
296
315
  dropped when the user changes (`setUserId` / `clearUserId`).
297
316
 
317
+ ## In-App Messages
318
+
319
+ In-app messages are campaigns shown inside your page — a modal, banner,
320
+ fullscreen takeover or card — when a trigger fires. `riviumPush.inApp` needs a
321
+ registered device.
322
+
323
+ ```typescript
324
+ const riviumPush = new RiviumPush({
325
+ apiKey: 'rv_live_your_api_key',
326
+ inApp: {
327
+ display: 'auto', // 'manual' to render your own UI
328
+ autoTrigger: false, // true fires session-start + app-open on page load
329
+ bannerPosition: 'top',
330
+ },
331
+ });
332
+
333
+ riviumPush.inApp.onMessageReady((message) => console.log(message.name));
334
+ riviumPush.inApp.onButtonClicked((message, button) => {
335
+ if (button.action === 'custom') doSomething(button.value);
336
+ });
337
+ riviumPush.inApp.onDismissed((message) => console.log('closed', message.id));
338
+
339
+ await riviumPush.inApp.triggerOnAppOpen();
340
+ await riviumPush.inApp.triggerEvent('purchase_completed', { plan: 'pro' });
341
+ ```
342
+
343
+ The built-in UI renders into a **shadow DOM** root, so your page's CSS can never
344
+ break it and the SDK's CSS never leaks into your page. Modals and fullscreen
345
+ messages are dialogs (`role="dialog"`, `aria-modal`, focus trap, focus restored
346
+ on close, dismissible with Escape or a backdrop click); banners and cards are
347
+ polite live regions. Reduced-motion preferences are respected.
348
+
349
+ With `display: 'manual'` nothing is inserted into the page: you get
350
+ `onMessageReady` and render the message yourself, then call
351
+ `riviumPush.inApp.recordImpression(id, 'button_click', buttonId)` and
352
+ `riviumPush.inApp.dismissCurrentMessage()` as the user interacts.
353
+
354
+ Eligible messages are cached per device for 5 minutes, and impression counts,
355
+ schedules and `minSessionCount` are enforced locally as well as on the server.
356
+ The cache is dropped when the user changes (`setUserId` / `clearUserId`).
357
+
298
358
  ## Delivery Tracking
299
359
 
300
360
  Notifications are confirmed as `delivered` automatically: Web Push arrivals by
@@ -0,0 +1,262 @@
1
+ /**
2
+ * In-App Messages for the RiviumPush Web SDK.
3
+ *
4
+ * An in-app message is a campaign the server keeps for a device and the SDK
5
+ * shows inside the page — a modal, a banner, a fullscreen takeover or a card —
6
+ * when a trigger fires (app open, session start or a custom event).
7
+ *
8
+ * Reachable as `push.inApp` once the SDK is constructed; network calls need
9
+ * a registered device (`register()`).
10
+ *
11
+ * The built-in UI renders into a shadow DOM root, so the host page's CSS can
12
+ * never break it and the SDK's CSS never leaks into the page. Apps that want
13
+ * to render their own UI set `display: 'manual'` and use `onMessageReady`.
14
+ *
15
+ * @packageDocumentation
16
+ */
17
+ /** How a message is presented. */
18
+ export type InAppMessageType = 'modal' | 'banner' | 'fullscreen' | 'card';
19
+ /** What makes a message eligible to show. */
20
+ export type InAppTriggerType = 'on_app_open' | 'on_event' | 'on_session_start' | 'scheduled' | 'manual';
21
+ /** What a button does when clicked. */
22
+ export type InAppButtonAction = 'dismiss' | 'deep_link' | 'url' | 'custom';
23
+ /** Visual weight of a button. */
24
+ export type InAppButtonStyle = 'primary' | 'secondary' | 'text' | 'destructive';
25
+ /** Interaction reported to the server. */
26
+ export type InAppImpressionAction = 'impression' | 'click' | 'dismiss' | 'button_click';
27
+ /** Where a banner is anchored. */
28
+ export type InAppBannerPosition = 'top' | 'bottom';
29
+ /** An action button on an in-app message. */
30
+ export interface InAppButton {
31
+ /** Button id, reported with the click */
32
+ id: string;
33
+ /** Button label */
34
+ text: string;
35
+ /** What the button does */
36
+ action: InAppButtonAction;
37
+ /** URL or deep link for the `url` / `deep_link` actions */
38
+ value?: string;
39
+ /** Visual style (default: `primary`) */
40
+ style?: InAppButtonStyle;
41
+ }
42
+ /** Content of an in-app message, in one locale. */
43
+ export interface InAppMessageContent {
44
+ /** Message title */
45
+ title: string;
46
+ /** Message body */
47
+ body: string;
48
+ /** Large image URL */
49
+ imageUrl?: string;
50
+ /** Background colour, e.g. "#FFFFFF" */
51
+ backgroundColor?: string;
52
+ /** Text colour, e.g. "#111111" */
53
+ textColor?: string;
54
+ /** Action buttons */
55
+ buttons?: InAppButton[];
56
+ /** Banner anchor; falls back to the `inApp.bannerPosition` config */
57
+ position?: InAppBannerPosition;
58
+ }
59
+ /** Content for one locale. */
60
+ export interface InAppLocalization {
61
+ /** Locale tag, e.g. "fr" or "fr-CA" */
62
+ locale: string;
63
+ /** Content for that locale */
64
+ content: InAppMessageContent;
65
+ }
66
+ /** A single in-app message campaign. */
67
+ export interface InAppMessage {
68
+ /** Server-side message id */
69
+ id: string;
70
+ /** Internal campaign name */
71
+ name: string;
72
+ /** How the message is presented */
73
+ type: InAppMessageType;
74
+ /** Default content */
75
+ content: InAppMessageContent;
76
+ /** Per-locale content, when configured */
77
+ localizations?: InAppLocalization[];
78
+ /** What makes the message eligible */
79
+ triggerType: InAppTriggerType;
80
+ /** Event name for the `on_event` trigger */
81
+ triggerEvent?: string | null;
82
+ /** Extra trigger conditions */
83
+ triggerConditions?: Record<string, any> | null;
84
+ /** ISO date before which the message is not shown */
85
+ startDate?: string | null;
86
+ /** ISO date after which the message is not shown */
87
+ endDate?: string | null;
88
+ /** How many times this device may see the message */
89
+ maxImpressions: number;
90
+ /** Sessions required before the message may show */
91
+ minSessionCount: number;
92
+ /** Delay between the trigger and the display */
93
+ delaySeconds: number;
94
+ /** Higher priority wins when several messages qualify */
95
+ priority: number;
96
+ }
97
+ /** Options for {@link InAppMessages.fetchMessages}. */
98
+ export interface InAppFilter {
99
+ /** Only messages with this trigger */
100
+ trigger?: InAppTriggerType;
101
+ /** Only messages bound to this event name */
102
+ event?: string;
103
+ /** Preferred locale for localized content, e.g. "fr" */
104
+ locale?: string;
105
+ }
106
+ /** Configuration for the in-app module (`RiviumPushConfig.inApp`). */
107
+ export interface InAppConfig {
108
+ /** Turn in-app messages off entirely (default: true) */
109
+ enabled?: boolean;
110
+ /**
111
+ * `auto` renders the built-in shadow-DOM UI (default).
112
+ * `manual` renders nothing and only fires `onMessageReady`, so the app can
113
+ * draw its own UI. It still reports the impression.
114
+ */
115
+ display?: 'auto' | 'manual';
116
+ /**
117
+ * Fire `on_session_start` and `on_app_open` automatically on page load
118
+ * (default: false — call `triggerOnAppOpen()` when your app is ready).
119
+ */
120
+ autoTrigger?: boolean;
121
+ /** Where banners are anchored when the content does not say (default: top) */
122
+ bannerPosition?: InAppBannerPosition;
123
+ /** Locale used to pick localized content (default: the browser locale) */
124
+ locale?: string;
125
+ }
126
+ /** Called when a message is ready to be displayed. */
127
+ export type OnInAppMessageReadyCallback = (message: InAppMessage) => void;
128
+ /** Called when a button on a message is clicked. */
129
+ export type OnInAppButtonClickedCallback = (message: InAppMessage, button: InAppButton) => void;
130
+ /** Called when a message is dismissed. */
131
+ export type OnInAppDismissedCallback = (message: InAppMessage) => void;
132
+ /**
133
+ * Wiring the SDK passes to the in-app module. Not part of the public API.
134
+ * @internal
135
+ */
136
+ export interface InAppDependencies {
137
+ serverUrl: string;
138
+ getApiKey: () => string;
139
+ getDeviceId: () => string | null;
140
+ getUserId: () => string | null;
141
+ log: (level: number, message: string, ...args: any[]) => void;
142
+ config?: InAppConfig;
143
+ }
144
+ /** Inputs the eligibility rules are evaluated against. */
145
+ export interface InAppEligibilityContext {
146
+ /** Trigger being evaluated */
147
+ trigger: InAppTriggerType;
148
+ /** Event name, for the `on_event` trigger */
149
+ event?: string;
150
+ /** Sessions this device has started */
151
+ sessionCount: number;
152
+ /** Impressions this device already had, per message id */
153
+ impressions: Record<string, number>;
154
+ /** Evaluation time in epoch milliseconds */
155
+ now: number;
156
+ }
157
+ /**
158
+ * Whether a message may be shown for this trigger. Pure, so the frequency and
159
+ * schedule rules can be reasoned about (and tested) on their own.
160
+ */
161
+ export declare function isInAppMessageEligible(message: InAppMessage, context: InAppEligibilityContext): boolean;
162
+ /** Eligible messages for a trigger, highest priority first. */
163
+ export declare function selectInAppMessages(messages: InAppMessage[], context: InAppEligibilityContext): InAppMessage[];
164
+ /**
165
+ * In-App Messages client.
166
+ *
167
+ * ```typescript
168
+ * push.inApp.onButtonClicked((message, button) => console.log(button.id));
169
+ * await push.inApp.triggerOnAppOpen();
170
+ * await push.inApp.triggerEvent('purchase_completed');
171
+ * ```
172
+ */
173
+ export declare class InAppMessages {
174
+ private readonly deps;
175
+ private cachedMessages;
176
+ private impressions;
177
+ private sessionCount;
178
+ private lastFetch;
179
+ /** Device the in-memory cache was loaded for, so identity changes reload. */
180
+ private loadedKey;
181
+ private onMessageReadyCallback;
182
+ private onButtonClickedCallback;
183
+ private onDismissedCallback;
184
+ private presentation;
185
+ private showing;
186
+ private pendingTimer;
187
+ /** @internal */
188
+ constructor(deps: InAppDependencies);
189
+ /**
190
+ * Listen for a message becoming ready to display. Fires for the built-in UI
191
+ * too; with `display: 'manual'` it is the only signal you get.
192
+ * Returns a function that removes the listener.
193
+ */
194
+ onMessageReady(callback: OnInAppMessageReadyCallback): () => void;
195
+ /**
196
+ * Listen for button clicks. `custom` buttons do nothing on their own —
197
+ * handle them here.
198
+ * Returns a function that removes the listener.
199
+ */
200
+ onButtonClicked(callback: OnInAppButtonClickedCallback): () => void;
201
+ /**
202
+ * Listen for a message being dismissed (close button, backdrop, Escape or
203
+ * a `dismiss` button).
204
+ * Returns a function that removes the listener.
205
+ */
206
+ onDismissed(callback: OnInAppDismissedCallback): () => void;
207
+ /**
208
+ * Fetch the messages this device is eligible for and cache them. Messages
209
+ * are filtered again locally before anything is shown.
210
+ */
211
+ fetchMessages(filter?: InAppFilter): Promise<InAppMessage[]>;
212
+ /** Messages cached locally — available immediately, no network call. */
213
+ getCachedMessages(): InAppMessage[];
214
+ /** Sessions this device has started. */
215
+ getSessionCount(): number;
216
+ /** Evaluate `on_app_open` messages and show the best match. */
217
+ triggerOnAppOpen(): Promise<void>;
218
+ /**
219
+ * Evaluate `on_event` messages bound to `name`. `properties` are matched
220
+ * against a message's `triggerConditions` when both are present.
221
+ */
222
+ triggerEvent(name: string, properties?: Record<string, any>): Promise<void>;
223
+ /** Count a new session and evaluate `on_session_start` messages. */
224
+ triggerSessionStart(): Promise<void>;
225
+ /**
226
+ * Start a session on page load: counts the session and, when
227
+ * `inApp.autoTrigger` is on, fires `on_session_start` then `on_app_open`.
228
+ * @internal
229
+ */
230
+ startSession(): void;
231
+ /** Show a cached message by id, ignoring its trigger. */
232
+ showMessage(messageId: string): Promise<void>;
233
+ /** Close the message currently on screen, if any. */
234
+ dismissCurrentMessage(): void;
235
+ /**
236
+ * Report an interaction. Called for you by the built-in UI; call it yourself
237
+ * when you render messages with `display: 'manual'`. Never throws.
238
+ */
239
+ recordImpression(messageId: string, action: InAppImpressionAction, buttonId?: string): Promise<void>;
240
+ /** Drop cached messages, impression counts and the session count. */
241
+ clearCache(): void;
242
+ /**
243
+ * Point the module at a new identity. Campaign eligibility and impression
244
+ * counts belong to the previous user, so they are dropped.
245
+ * @internal
246
+ */
247
+ onIdentityChanged(): void;
248
+ private trigger;
249
+ /** Shows a message: reports the impression once, then renders or delegates. */
250
+ private present;
251
+ private handleButtonClick;
252
+ /** Tears the UI down once, reports the dismissal once. */
253
+ private finishPresentation;
254
+ private incrementSessionCount;
255
+ private locale;
256
+ private storageKey;
257
+ /** Restores the persisted state the first time it is needed per device. */
258
+ private ensureLoaded;
259
+ private persist;
260
+ }
261
+ /** Exact locale match first, then the language part, then the default content. */
262
+ export declare function localizedContent(message: InAppMessage, locale: string): InAppMessageContent;
package/dist/index.d.ts CHANGED
@@ -16,9 +16,12 @@
16
16
  */
17
17
  import { SDK_NAME, SDK_VERSION } from './version';
18
18
  import { RiviumInbox } from './inbox';
19
+ import { InAppMessages, type InAppConfig } from './in-app';
19
20
  export { SDK_NAME, SDK_VERSION };
20
21
  export { RiviumInbox } from './inbox';
21
22
  export type { InboxContent, InboxFilter, InboxMessage, InboxMessagesResponse, InboxMessageStatus, OnInboxMessageCallback, OnInboxStatusChangeCallback, OnInboxUnreadCountCallback, } from './inbox';
23
+ export { InAppMessages, isInAppMessageEligible, selectInAppMessages, localizedContent } from './in-app';
24
+ export type { InAppBannerPosition, InAppButton, InAppButtonAction, InAppButtonStyle, InAppConfig, InAppEligibilityContext, InAppFilter, InAppImpressionAction, InAppLocalization, InAppMessage, InAppMessageContent, InAppMessageType, InAppTriggerType, OnInAppButtonClickedCallback, OnInAppDismissedCallback, OnInAppMessageReadyCallback, } from './in-app';
22
25
  /**
23
26
  * Standardized error codes for RiviumPush SDK.
24
27
  * These codes help developers identify and handle specific error scenarios.
@@ -212,6 +215,12 @@ export interface RiviumPushConfig {
212
215
  * permission is already granted. Errors are logged, never thrown.
213
216
  */
214
217
  autoRefresh?: boolean;
218
+ /**
219
+ * In-App Messages options. Omit it to keep the defaults: the built-in
220
+ * shadow-DOM UI, triggered by your calls to `inApp.triggerOnAppOpen()` /
221
+ * `inApp.triggerEvent()`.
222
+ */
223
+ inApp?: InAppConfig;
215
224
  }
216
225
  /**
217
226
  * Notification action button
@@ -390,6 +399,11 @@ declare class RiviumPush {
390
399
  * a registered device.
391
400
  */
392
401
  readonly inbox: RiviumInbox;
402
+ /**
403
+ * In-App Messages. Listeners can be attached immediately; network calls
404
+ * need a registered device.
405
+ */
406
+ readonly inApp: InAppMessages;
393
407
  constructor(config: RiviumPushConfig);
394
408
  /**
395
409
  * Fetch MQTT and VAPID configuration from server
@@ -568,6 +582,15 @@ declare class RiviumPush {
568
582
  private handleVisibilityChange;
569
583
  private checkInitialMessage;
570
584
  private registerServiceWorker;
585
+ /**
586
+ * Keeps `rivium-push` / `config` up to date for the service worker.
587
+ *
588
+ * Rewritten on every load, so a device id or server URL that changed does
589
+ * not leave a stale record behind. Best-effort: private browsing and
590
+ * blocked site data make IndexedDB unavailable, and the worker then falls
591
+ * back to its URL exactly as before.
592
+ */
593
+ private storeServiceWorkerConfig;
571
594
  private requestNotificationPermission;
572
595
  /**
573
596
  * Whether an existing subscription was created with the given VAPID key.