### Initialize Pusher Beams Client Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/quick-start.md Import the SDK and initialize the client with your instance ID. Ensure you call `start()` to begin the registration process. This is the basic setup for using the SDK. ```javascript import * as PusherPushNotifications from '@pusher/push-notifications-web'; const beamsClient = new PusherPushNotifications.Client({ instanceId: 'YOUR_INSTANCE_ID' }); // Start registration await beamsClient.start(); ``` -------------------------------- ### Error Handling Example Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/README.md Demonstrates how to handle potential errors when starting the SDK, checking for specific error messages related to browser support or security contexts. ```javascript try { await client.start(); } catch (error) { if (error.message.includes('Service Workers not supported')) { // Browser too old } else if (error.message.includes('secure contexts')) { // Not HTTPS } } ``` -------------------------------- ### start() Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/api-reference/client.md Initializes the SDK and registers the device with Pusher Beams. This method must be called before using any interest or user-related functionalities. ```APIDOC ## start() ### Description Initialize the SDK and register the device with Pusher Beams. This must be called before using interest or user-related methods. ### Signature ```typescript start(): Promise ``` ### Returns A promise that resolves when registration is complete. Does not return if web push is not supported. ### Throws None ### Example ```javascript await beamsClient.start(); console.log('Device registered:', await beamsClient.getDeviceId()); ``` ``` -------------------------------- ### Accessing Device State Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/api-reference/service-worker.md Example of how to retrieve and log device information using the `statePromise`. Ensure `statePromise` is awaited to get the device state object. ```javascript const state = await statePromise; console.log('Device:', state.deviceId); console.log('User:', state.userId); console.log('App in background:', state.appInBackground); ``` -------------------------------- ### Basic Token Provider Setup Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/configuration.md Initialize a TokenProvider with the essential endpoint URL for fetching authentication tokens. ```javascript const tokenProvider = new PusherPushNotifications.TokenProvider({ url: 'https://your-backend.com/beams-auth' }); ``` -------------------------------- ### Start Pusher Beams Client Source: https://github.com/pusher/push-notifications-web/blob/master/example.html Initialize the Beams client with your instance ID and attach an event listener to a button to start the client. Handles success and error logging. ```javascript const beamsClient = new PusherPushNotifications.Client({ instanceId: '2e65aab4-a26e-4cca-a9e6-b68589627a8d', }); document.querySelector('#start').addEventListener('click', function() { beamsClient .start() .then(() => { console.log('Successfully started beams client'); }) .catch((err) => { console.error('Error starting beams client', err); }); }); ``` -------------------------------- ### Catch SDK Not Started Error Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/errors.md This error indicates that an operation was attempted before the SDK was properly started with `.start()`. Call `.start()` before using methods like `addDeviceInterest()`. ```javascript try { await beamsClient.addDeviceInterest('sports'); } catch (error) { if (error.message.includes('SDK not registered with Beams')) { // Call start() first await beamsClient.start(); await beamsClient.addDeviceInterest('sports'); } } ``` -------------------------------- ### Method Signature Example Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/README.md Illustrates the format for asynchronous method signatures, including parameters and return types. ```typescript async methodName(param: string): Promise ``` -------------------------------- ### Handle SDK Not Started Error - JavaScript Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/quick-start.md Gracefully handle cases where SDK methods are called before the SDK has been successfully started. This snippet demonstrates how to automatically start the SDK and retry the operation. ```javascript try { await beamsClient.addDeviceInterest('sports'); } catch (error) { if (error.message.includes('SDK not registered with Beams')) { await beamsClient.start(); await beamsClient.addDeviceInterest('sports'); } } ``` -------------------------------- ### Client Class and Methods Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/README.md Documentation for the `Client` class, including its constructor and all public instance methods. This covers parameters, return types, error conditions, and provides usage examples. ```APIDOC ## Client Class ### Description Documentation for the `Client` class, which is the primary interface for interacting with the Push Notifications service from the client-side. It includes details on initialization, methods for managing subscriptions, and handling push notifications. ### Constructor - `Client(options: ClientOptions)`: Initializes a new instance of the `Client`. ### Methods - All public instance methods of the `Client` class are documented here, including their parameters, return types, and potential error conditions. ### Usage Examples Code snippets demonstrating how to use the `Client` class and its methods. ``` -------------------------------- ### TypeScript Import for Push Notifications Web SDK Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md This example demonstrates how to import and initialize the SDK client using TypeScript, including type definitions. ```typescript import { Client, ClientOptions, TokenProvider, TokenProviderOptions, ITokenProvider, RegistrationState } from '@pusher/push-notifications-web'; const options: ClientOptions = { instanceId: 'id' }; const client: Client = new Client(options); ``` -------------------------------- ### Custom Token Provider Implementation Example Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/types.md Example of a custom token provider implementation that fetches an authentication token from a custom endpoint. Ensure the endpoint returns a JSON object with an 'authToken' property. ```typescript class MyTokenProvider implements ITokenProvider { async fetchToken(userId: string): Promise { const response = await fetch('/my-auth-endpoint', { method: 'POST', body: JSON.stringify({ userId }) }); const data = await response.json(); return { token: data.authToken }; } } ``` -------------------------------- ### Initialize Pusher Beams in Vue Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/quick-start.md Initialize the Pusher Push Notifications client within the `mounted()` hook of a Vue component. This example also demonstrates how to start the client, retrieve the device ID, and fetch current interests. ```javascript import * as PusherPushNotifications from '@pusher/push-notifications-web'; export default { data() { return { client: null, interests: [], deviceId: null }; }, async mounted() { try { this.client = new PusherPushNotifications.Client({ instanceId: process.env.VUE_APP_BEAMS_INSTANCE_ID }); await this.client.start(); this.deviceId = await this.client.getDeviceId(); const result = await this.client.getDeviceInterests(); this.interests = result.interests; } catch (error) { console.error('Failed to initialize Beams:', error); } }, methods: { async addInterest(name) { try { await this.client.addDeviceInterest(name); this.interests.push(name); } catch (error) { console.error('Error adding interest:', error); } } } }; ``` -------------------------------- ### Catch Common Errors - JavaScript Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/quick-start.md Implement robust error handling for the `beamsClient.start()` method. This example catches specific errors related to configuration, browser support, and security contexts (HTTPS/localhost). ```javascript try { await beamsClient.start(); } catch (error) { if (error.message === 'Config object required') { console.error('Missing config'); } else if (error.message.includes('Service Workers not supported')) { console.error('Browser too old for notifications'); } else if (error.message.includes('secure contexts')) { console.error('Must use HTTPS or localhost'); } else { console.error('Unexpected error:', error); } } ``` -------------------------------- ### Example Custom Notification Handler Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/configuration.md Implement a custom notification handler within the `onNotificationReceived` callback. This example shows conditional display during business hours and logging device state. ```javascript self.PusherPushNotifications.onNotificationReceived = async ({ payload, pushEvent, handleNotification, statePromise }) => { // Show notification only during business hours const hour = new Date().getHours(); if (hour >= 9 && hour < 17) { await handleNotification(payload); } // Or handle notification completely custom way const state = await statePromise; console.log('Device:', state.deviceId); }; ``` -------------------------------- ### Catch setUserId Before Start Error Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/errors.md This error occurs if `setUserId()` is called prior to the completion of `start()`. Ensure that `start()` has finished before calling `setUserId()`. ```javascript try { const tokenProvider = new PusherPushNotifications.TokenProvider({ url: '...' }); await beamsClient.setUserId('alice', tokenProvider); } catch (error) { if (error.message === '.start must be called before .setUserId') { // Ensure start() completes first await beamsClient.start(); await beamsClient.setUserId('alice', tokenProvider); } } ``` -------------------------------- ### Custom ITokenProvider Implementation Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Implement the ITokenProvider interface to provide a custom method for fetching authentication tokens. This example shows a basic implementation using the fetch API. ```typescript class CustomTokenProvider implements ITokenProvider { async fetchToken(userId: string): Promise { const response = await fetch('/custom-token-endpoint', { method: 'POST', body: JSON.stringify({ userId }) }); const data = await response.json(); return { token: data.token }; } } ``` -------------------------------- ### Configure Service Worker Callback Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/quick-start.md Set up a callback in your service worker to handle incoming notifications. This example logs the payload and displays the notification. ```javascript self.PusherPushNotifications.onNotificationReceived = async ({ payload, pushEvent, handleNotification, statePromise }) => { // Custom handling console.log('Received notification:', payload); // Display notification await handleNotification(payload); }; ``` -------------------------------- ### Configure Beams Client for Development Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/configuration.md Configure the Pusher Beams client and token provider for a development environment, using local host URLs and specific instance IDs. This setup is useful for testing with a local backend. ```javascript const isDev = process.env.NODE_ENV === 'development'; const beamsClient = new PusherPushNotifications.Client({ instanceId: isDev ? 'dev-instance' : 'prod-instance', endpointOverride: isDev ? 'http://localhost:3000' : undefined }); const tokenProvider = new PusherPushNotifications.TokenProvider({ url: isDev ? 'http://localhost:3000/beams-token' : 'https://api.example.com/beams-token', queryParams: isDev ? { debug: 'true' } : {} }); ``` -------------------------------- ### Service Worker Setup and Event Listeners Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/module-structure.md The `service-worker.js` file sets up the global `self.PusherPushNotifications` object and registers event listeners for incoming push notifications and user interactions with notifications. ```javascript // Sets up: self.PusherPushNotifications = { ... } // Registers event listeners: self.addEventListener('push', ...) self.addEventListener('notificationclick', ...) ``` -------------------------------- ### Configure Beams Client for Multi-Environment Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/configuration.md Set up Pusher Beams client and token provider configurations for different environments (development, staging, production) using an environment configuration object. This promotes consistent setup across deployment stages. ```javascript const envConfig = { development: { instanceId: 'dev-12345', apiUrl: 'http://localhost:3000', endpointOverride: 'http://localhost:3001' }, staging: { instanceId: 'staging-12345', apiUrl: 'https://staging-api.example.com' }, production: { instanceId: 'prod-12345', apiUrl: 'https://api.example.com' } }; const env = process.env.NODE_ENV || 'development'; const config = envConfig[env]; const beamsClient = new PusherPushNotifications.Client({ instanceId: config.instanceId, endpointOverride: config.endpointOverride }); const tokenProvider = new PusherPushNotifications.TokenProvider({ url: `${config.apiUrl}/beams-auth` }); ``` -------------------------------- ### Type-Safe Pusher Beams Integration in TypeScript Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/quick-start.md Demonstrates type-safe initialization and usage of the Pusher Push Notifications client and token provider in TypeScript. Includes examples for setting user ID with a token provider and checking the registration state. ```typescript import { Client, TokenProvider, RegistrationState, ClientOptions, TokenProviderOptions, ITokenProvider } from '@pusher/push-notifications-web'; // Initialize client with types const clientOptions: ClientOptions = { instanceId: process.env.REACT_APP_BEAMS_INSTANCE_ID! }; const client: Client = new Client(clientOptions); // Initialize token provider with types const tokenOptions: TokenProviderOptions = { url: `${process.env.REACT_APP_API_URL}/beams-token`, headers: { 'Authorization': `Bearer ${getAuthToken()}` } }; const tokenProvider: ITokenProvider = new TokenProvider(tokenOptions); // Use with type checking async function authenticate(userId: string): Promise { await client.setUserId(userId, tokenProvider); } async function checkState(): Promise { return await client.getRegistrationState(); } ``` -------------------------------- ### Run End-to-End Tests Source: https://github.com/pusher/push-notifications-web/blob/master/running-end-to-end-tests.md Execute the end-to-end test suite. Ensure ChromeDriver is installed and matches your Chrome browser version. ```bash npm run test:e2e ``` -------------------------------- ### Clear All State Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Use `clearAllState()` to clear all SDK state and re-register with a new device ID. This is equivalent to calling `stop()` followed by `start()`. ```typescript clearAllState(): Promise ``` -------------------------------- ### Get Public Key Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/endpoints.md Retrieve the VAPID public key for web push subscription. This is used internally by Client.start() to subscribe to web push with PushManager. ```APIDOC ## GET /device_api/v1/instances/{instanceId}/web-vapid-public-key ### Description Retrieve the VAPID public key for web push subscription. ### Method GET ### Endpoint /device_api/v1/instances/{instanceId}/web-vapid-public-key ### Response #### Success Response (200 OK) - **vapidPublicKey** (string) - Base64-encoded VAPID public key for web push ### Response Example ```json { "vapidPublicKey": "string" } ``` ``` -------------------------------- ### Associate Device with User Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Link the device to an authenticated user using `setUserId()`. This requires a `userId` and a `tokenProvider` object with a `fetchToken(userId)` method. Note that the user ID cannot be changed after it's set; to switch users, you must call `stop()` and then `start()`. ```javascript const tokenProvider = new TokenProvider({ url: '/beams-auth' }); await client.setUserId('alice@example.com', tokenProvider); ``` -------------------------------- ### Configure Service Worker from Main App Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/configuration.md Communicate with the service worker from your main application code to configure notification handling. This example shows how to signal the service worker to use a custom handler. ```javascript if ('serviceWorker' in navigator) { navigator.serviceWorker.ready.then((reg) => { // Communicate with service worker reg.active.postMessage({ type: 'CONFIGURE', config: { onNotificationReceived: true // Signal to use custom handler } }); }); } ``` -------------------------------- ### Validate Interest Names - JavaScript Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/quick-start.md Ensure that device interest names adhere to the SDK's naming conventions. This example shows how to catch errors caused by invalid characters (like spaces) and provides a corrected version using underscores. ```javascript try { await beamsClient.addDeviceInterest('my interest'); // space not allowed } catch (error) { if (error.message.includes('forbidden character')) { await beamsClient.addDeviceInterest('my_interest'); // use underscore } } ``` -------------------------------- ### Check Browser Support for Beams Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/quick-start.md Checks if the browser supports necessary Web APIs for Pusher Beams, including Notifications, PushManager, Service Workers, IndexedDB, and secure context. Demonstrates starting Beams or logging a fallback message. ```javascript function isBeamsSupported() { return ( 'Notification' in window && 'PushManager' in window && 'serviceWorker' in navigator && 'indexedDB' in window && window.isSecureContext ); } if (isBeamsSupported()) { await beamsClient.start(); } else { console.log('Notifications not supported, using fallback'); // Show banner or use alternative notification method } ``` -------------------------------- ### Client.start() Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Initiates the device registration process. This method should be called to register the device with the push notification service. ```APIDOC ## Method: Client.start() ### Description Register device ### Signature `() => Promise` ``` -------------------------------- ### Get Device ID Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Retrieve the unique device ID using `getDeviceId()`. This method requires `start()` to have been called previously and returns a promise resolving to the device ID string. ```typescript getDeviceId(): Promise ``` -------------------------------- ### JavaScript Client Initialization Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/README.md Shows how to initialize the client in JavaScript. ```javascript // JavaScript code examples const client = new Client({ instanceId: 'id' }); ``` -------------------------------- ### TypeScript Client Initialization Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/README.md Demonstrates client initialization in TypeScript with explicit type annotations. ```typescript // TypeScript with types const client: Client = new Client({ instanceId: 'id' }); ``` -------------------------------- ### Client Constructor Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Initializes a new instance of the Client class. This is the main SDK class for managing device registration, interests, and authenticated users. ```APIDOC ## new Client(options: ClientOptions) ### Description Initializes a new instance of the Client class, which is the main SDK class for managing device registration, interests, and authenticated users. ### Parameters #### Request Body - **options** (ClientOptions, required) - Configuration object - **instanceId** (string, required) - Pusher Beams instance ID - **serviceWorkerRegistration** (ServiceWorkerRegistration, optional) - Pre-registered service worker - **endpointOverride** (string, optional) - Override API endpoint (testing only) ### Throws Various validation errors (see [errors.md](errors.md)) ### Request Example ```javascript const client = new Client({ instanceId: 'YOUR_INSTANCE_ID' }); ``` ``` -------------------------------- ### Client Configuration Defaults Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/configuration.md These are the default settings for the main client instance. The instanceId is required and must be provided. ```javascript { instanceId: undefined, // REQUIRED - no default serviceWorkerRegistration: null, // Auto-register if null endpointOverride: null // Use default Pusher endpoint } ``` -------------------------------- ### Initialize Pusher Beams Client for Production Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/configuration.md Set up the Pusher Beams client with a production instance ID and configure a token provider pointing to your server endpoint. Ensure environment variables for instance ID and API URL are set. ```javascript // Initialize with production instance ID const beamsClient = new PusherPushNotifications.Client({ instanceId: process.env.REACT_APP_BEAMS_INSTANCE_ID }); // Set up token provider with server endpoint const tokenProvider = new PusherPushNotifications.TokenProvider({ url: `${process.env.REACT_APP_API_URL}/beams-auth`, headers: { 'Authorization': `Bearer ${getAuthToken()}` } }); // Initialize SDK await beamsClient.start(); ``` -------------------------------- ### Get Device Identifier Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Retrieves the unique identifier assigned to the device by the push notification service. ```typescript getDeviceId: () => Promise ``` -------------------------------- ### Initialize and Register Device with Pusher Beams Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/api-reference/client.md Call this method to initialize the SDK and register the device. It must be called before using interest or user-related methods. It returns a promise that resolves upon successful registration. ```javascript await beamsClient.start(); console.log('Device registered:', await beamsClient.getDeviceId()); ``` -------------------------------- ### Client Class Methods Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/README.md The Client class provides methods for initializing the SDK, managing device registration and interests, and authenticating users. ```APIDOC ## Client Class Methods ### Description Provides core methods for interacting with the Push Notifications service, including device registration, interest management, and user authentication. ### Methods - **`start()`** - **Purpose**: Initialize SDK and register device. - **`stop()`** - **Purpose**: Unregister device. - **`addDeviceInterest(name)`** - **Purpose**: Subscribe to an interest. - **Parameters**: - `name` (string) - Required - The name of the interest to subscribe to. - **`removeDeviceInterest(name)`** - **Purpose**: Unsubscribe from an interest. - **Parameters**: - `name` (string) - Required - The name of the interest to unsubscribe from. - **`getDeviceInterests()`** - **Purpose**: List current device subscriptions. - **`setDeviceInterests(list)`** - **Purpose**: Replace all current subscriptions with a new list. - **Parameters**: - `list` (array) - Required - An array of interest names to set. - **`setUserId(id, tokenProvider)`** - **Purpose**: Authenticate a user with the service. - **Parameters**: - `id` (string) - Required - The user ID. - `tokenProvider` (ITokenProvider) - Required - An object implementing the ITokenProvider interface for authentication. - **`getRegistrationState()`** - **Purpose**: Check the current registration status of the device. ``` -------------------------------- ### Get All Subscribed Interests Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/quick-start.md Retrieve a list of all interests the device is currently subscribed to. The result contains an 'interests' array. ```javascript const result = await beamsClient.getDeviceInterests(); console.log(result.interests); // ['sports', 'news'] ``` -------------------------------- ### Instantiate TokenProvider Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/api-reference/token-provider.md Create a new TokenProvider instance with custom configuration for fetching authentication tokens. Specify the URL, query parameters, headers, and credentials policy. ```javascript const tokenProvider = new PusherPushNotifications.TokenProvider({ url: 'https://your-auth-server.com/beams-token', queryParams: { apiKey: 'your-api-key' }, headers: { 'X-Custom-Header': 'value' }, credentials: 'include' }); ``` -------------------------------- ### Importing Client API Components Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/module-structure.md Demonstrates how to import the public API components like Client, TokenProvider, and RegistrationState from the SDK. Supports both named and namespace imports. ```javascript // Named import import { Client, TokenProvider, RegistrationState } from '@pusher/push-notifications-web'; ``` ```javascript // Namespace import import * as PusherPushNotifications from '@pusher/push-notifications-web'; ``` -------------------------------- ### Get Device Registration State Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Retrieves the current registration state of the device, indicating whether it is registered, unregistering, etc. ```typescript getRegistrationState: () => Promise ``` -------------------------------- ### Get Current Authenticated User Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/quick-start.md Retrieve the user ID currently associated with the device. Returns null if no user is authenticated. ```javascript const userId = await beamsClient.getUserId(); console.log(userId); // 'alice@example.com' ``` -------------------------------- ### Client Initialization with Custom Service Worker Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/configuration.md Configure the client to use a pre-registered service worker. Ensure the service worker is registered before passing it to the Client constructor. ```javascript // Pre-register your service worker const swRegistration = await navigator.serviceWorker.register('/sw.js'); // Pass to Client const beamsClient = new PusherPushNotifications.Client({ instanceId: 'your-instance-id-here', serviceWorkerRegistration: swRegistration }); ``` -------------------------------- ### Get Device Interests Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/endpoints.md Retrieve the list of interests a device is subscribed to. This endpoint allows for paginated retrieval of interest subscriptions. ```APIDOC ## GET /device_api/v1/instances/{instanceId}/devices/web/{deviceId}/interests ### Description Retrieve the list of interests a device is subscribed to. ### Method GET ### Endpoint /device_api/v1/instances/{instanceId}/devices/web/{deviceId}/interests #### Query Parameters - **limit** (number) - Optional - Maximum number of interests to return - **cursor** (string) - Optional - Pagination cursor for additional results ### Response #### Success Response (200 OK) - **interests** (Array) - List of interest names - **responseMetadata.cursor** (string) - Pagination cursor for next page (if more results available) #### Response Example ```json { "interests": ["string"], "responseMetadata": { "cursor": "string" } } ``` ``` -------------------------------- ### Get Public Key Endpoint Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/endpoints.md Retrieves the VAPID public key for web push subscriptions. This is used internally by Client.start(). ```json { "vapidPublicKey": "string" } ``` -------------------------------- ### Initialize Pusher Beams Client Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/api-reference/client.md Instantiate the Pusher Beams client with your instance ID. Ensure your instance ID is valid and provided correctly. ```javascript const beamsClient = new PusherPushNotifications.Client({ instanceId: 'YOUR_INSTANCE_ID' }); ``` -------------------------------- ### Get Device Interests Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/endpoints.md Retrieve the list of interests a specific web device is subscribed to. Supports pagination with limit and cursor parameters. ```javascript const result = await beamsClient.getDeviceInterests(50); // Returns: { interests: ['sports', 'news'], responseMetadata: { cursor: '...' } } ``` -------------------------------- ### Set Up Token Provider Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/quick-start.md Configure a token provider with the URL of your authentication endpoint. This endpoint should generate and return a JWT for authenticating users. ```javascript const tokenProvider = new PusherPushNotifications.TokenProvider({ url: 'https://your-api.com/beams-token' }); ``` -------------------------------- ### Register Device with Client Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Initiates the device registration process. This is typically the first step before receiving notifications. ```typescript start: () => Promise ``` -------------------------------- ### Get Authenticated User ID Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/api-reference/client.md Retrieve the authenticated user ID associated with the device. This is useful for identifying which user is currently authenticated on the client. ```javascript const userId = await beamsClient.getUserId(); ``` -------------------------------- ### ClientOptions Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/types.md Configuration object passed to the `Client` constructor. It includes essential details for initializing the Pusher Beams client. ```APIDOC ## ClientOptions ### Description Configuration object passed to the `Client` constructor. ### Fields #### Path Parameters - **instanceId** (string) - Required - Your Pusher Beams instance ID from the Pusher dashboard - **serviceWorkerRegistration** (ServiceWorkerRegistration) - Optional - A pre-registered service worker. If not provided, the SDK automatically registers `/service-worker.js` - **endpointOverride** (string) - Optional - Override the default API endpoint. For internal testing only. ### Used By - `Client` constructor (required) ``` -------------------------------- ### ClientOptions Interface for Configuration Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Defines the configuration options available when initializing the main SDK client. ```typescript ClientOptions ``` -------------------------------- ### Get Authenticated User ID Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Retrieves the user ID associated with the device, if one has been set using `setUserId`. Returns null if no user is associated. ```typescript getUserId: () => Promise ``` -------------------------------- ### TokenProvider Constructor Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/api-reference/token-provider.md Initializes a new TokenProvider instance with configuration options for fetching authentication tokens. This includes the URL of the token endpoint, custom query parameters and headers, and the credentials policy for the fetch request. ```APIDOC ## Constructor TokenProvider ### Description Initializes a new TokenProvider instance with configuration options for fetching authentication tokens. This includes the URL of the token endpoint, custom query parameters and headers, and the credentials policy for the fetch request. ### Parameters #### options (TokenProviderOptions) - Required - Configuration object for the token provider - **url** (string) - Optional - The endpoint URL to fetch tokens from - **queryParams** (object) - Optional - Additional query parameters to append to every token request - **headers** (object) - Optional - HTTP headers to include in every token request - **credentials** (string) - Optional - Credentials policy for the fetch request (e.g., 'include', 'same-origin', 'omit') ### Example ```javascript const tokenProvider = new PusherPushNotifications.TokenProvider({ url: 'https://your-auth-server.com/beams-token', queryParams: { apiKey: 'your-api-key' }, headers: { 'X-Custom-Header': 'value' }, credentials: 'include' }); ``` ``` -------------------------------- ### Retrieve Unique Device Identifier Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/api-reference/client.md Use this method to get the unique identifier for the current device. It returns a promise that resolves to the device ID string. ```javascript const deviceId = await beamsClient.getDeviceId(); console.log('Device ID:', deviceId); ``` -------------------------------- ### Get Device ID - JavaScript Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/quick-start.md Retrieve the unique device ID for the current browser. This ID is used to target specific devices for push notifications. ```javascript const deviceId = await beamsClient.getDeviceId(); console.log(deviceId); // 'web-abc123...' ``` -------------------------------- ### Login to npm Source: https://github.com/pusher/push-notifications-web/blob/master/RELEASING.md Log in to the npm registry if you are not already authenticated. This command will prompt for your credentials. ```bash npm login ``` -------------------------------- ### Build Commands for Pusher Push Notifications Web SDK Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/module-structure.md Common build commands for the SDK, including building different module formats, the service worker, linting, formatting, and running various test suites. ```bash npm run build:esm # Build ESM version npm run build:cdn # Build CDN/UMD version npm run build:sw # Build service worker with version npm run lint # Run ESLint and Prettier npm run format # Format code with Prettier npm run test:unit # Run unit tests with Jest npm run test:ts # Run TypeScript type tests with tsd npm run test:e2e # Run end-to-end Selenium tests ``` -------------------------------- ### Get Device Interests Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/api-reference/client.md Retrieve the list of interests a device is subscribed to. Call this to see current subscriptions, optionally specifying a limit for the number of interests returned. ```javascript const result = await beamsClient.getDeviceInterests(50); console.log('Interests:', result.interests); ``` -------------------------------- ### TokenProvider Class and Interface Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/README.md Documentation for the `TokenProvider` class and the `ITokenProvider` interface, which are used for authentication and managing authentication tokens. ```APIDOC ## TokenProvider and ITokenProvider ### Description Documentation for the `TokenProvider` class and the `ITokenProvider` interface. This section details the mechanism for fetching and managing authentication tokens required for certain operations. ### TokenProvider Class - Details on the `TokenProvider` class, its methods, and how to instantiate it. ### ITokenProvider Interface - Specification of the `ITokenProvider` interface, outlining the contract for custom token providers. ### Token Fetching Mechanism - Explanation of how authentication tokens are fetched and refreshed. ``` -------------------------------- ### Get Authenticated User ID Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Retrieve the authenticated user ID using `getUserId()`. This returns a promise resolving to the user ID string or null if the user is not authenticated. ```typescript getUserId(): Promise ``` -------------------------------- ### Create Git Tag Source: https://github.com/pusher/push-notifications-web/blob/master/RELEASING.md Create a Git tag for the new version. Replace `` with the actual version number. ```bash git tag ``` -------------------------------- ### Minimal Client Initialization Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/configuration.md Initialize the Pusher Push Notifications client with only the required instanceId. This is the most basic configuration. ```javascript const beamsClient = new PusherPushNotifications.Client({ instanceId: 'your-instance-id-here' }); ``` -------------------------------- ### Publish Package with Publish Please Source: https://github.com/pusher/push-notifications-web/blob/master/RELEASING.md Use the 'publish-please' script to handle the npm package publishing process. Ensure you have the necessary permissions. ```bash npm run publish-please ``` -------------------------------- ### Handle 'Cannot change user ID' Error Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/errors.md Catch the error when attempting to call `setUserId()` with a different user ID than already set. To change the user ID, call `stop()` then `start()`. ```javascript try { await beamsClient.setUserId('alice', tokenProvider); // Later attempt to change user: await beamsClient.setUserId('bob', tokenProvider); // throws error } catch (error) { if (error.message === 'Changing the userId is not allowed.') { // Need to stop and restart for a different user await beamsClient.stop(); await beamsClient.start(); await beamsClient.setUserId('bob', tokenProvider); } } ``` -------------------------------- ### Client Constructor Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/api-reference/client.md Initializes a new instance of the Pusher Beams web SDK client. Requires an instance ID and optionally accepts a service worker registration or endpoint override. ```APIDOC ## Constructor ### Signature ```typescript constructor(options: ClientOptions) ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | options | [ClientOptions](#clientoptions) | Yes | — | Configuration object for the client | ### ClientOptions | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | instanceId | string | Yes | — | Your Pusher Beams instance ID | | serviceWorkerRegistration | ServiceWorkerRegistration | No | null | A pre-registered service worker registration. If not provided, the SDK will register `/service-worker.js` | | endpointOverride | string | No | null | Override the default API endpoint (for testing only) | ### Throws | Error | Condition | |-------|-----------| | `Config object required` | No config object provided | | `Instance ID is required` | `instanceId` not specified in config | | `Instance ID must be a string` | `instanceId` is not a string type | | `Instance ID cannot be empty` | `instanceId` is an empty string | | `IndexedDB not supported` | Browser does not support IndexedDB | | `Pusher Beams relies on Service Workers, which only work in secure contexts` | Page is not served over HTTPS or localhost | | `Service Workers not supported` | Browser does not support Service Workers | | `Web Push not supported` | Browser does not support Web Push API | | `Could not initialize Pusher web push: current page not in serviceWorkerRegistration scope` | Current page URL does not match the service worker registration scope | ### Example ```javascript const beamsClient = new PusherPushNotifications.Client({ instanceId: 'YOUR_INSTANCE_ID' }); ``` ### Instance Properties | Property | Type | Description | |----------|------|-------------| | instanceId | string | The Pusher Beams instance ID | | deviceId | string | The unique device identifier (populated after `start()`) | | userId | string | The authenticated user ID (populated after `setUserId()`) | ``` -------------------------------- ### Instantiate TokenProvider Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Create a new instance of TokenProvider with custom endpoint URL and headers. ```javascript const provider = new TokenProvider({ url: 'https://api.example.com/beams-token', headers: { 'X-API-Key': 'secret' } }); ``` -------------------------------- ### Get Device Registration State Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/api-reference/client.md Retrieve the current registration state of the device. This includes notification permissions and Beams registration status. Use this to determine if permission prompts are needed or if the device is already registered. ```javascript const state = await beamsClient.getRegistrationState(); if (state === PusherPushNotifications.RegistrationState.PERMISSION_PROMPT_REQUIRED) { console.log('Request notification permission'); } ``` -------------------------------- ### fetchToken Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/api-reference/token-provider.md Fetches an authentication token for a given user ID. This method is invoked by the Client.setUserId() method and constructs a GET request to the configured token endpoint, including user ID, custom parameters, headers, and credentials. ```APIDOC ## fetchToken(userId: string) ### Description Fetches an authentication token for a given user ID. This method is invoked by the Client.setUserId() method and constructs a GET request to the configured token endpoint, including user ID, custom parameters, headers, and credentials. ### Method GET ### Endpoint [Configured URL with appended query parameters] ### Parameters #### Query Parameters - **user_id** (string) - Required - The user identifier to fetch a token for - **[other queryParams]** (object) - Optional - Additional query parameters configured in the TokenProvider constructor ### Headers - **[configured headers]** (object) - Optional - HTTP headers configured in the TokenProvider constructor ### Request Example ``` https://your-auth-server.com/beams-token?user_id=alice@example.com&apiKey=your-api-key ``` ### Response #### Success Response (200) - **token** (string) - The authentication token ### Response Example ```json { "token": "your-jwt-token" } ``` ### Throws - HTTP error (wrapped in Error) - Server returns non-2xx status code - Network error - Fetch request fails ``` -------------------------------- ### Get Raw Push Subscription Token Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Retrieve the raw push subscription token using `getToken()`. This is an internal method and `getDeviceId()` should be used instead for most use cases. It returns a promise resolving to the token string or null. ```typescript getToken(): Promise ``` -------------------------------- ### Client Class Methods Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/MANIFEST.txt Documentation for the public methods available on the Client class, used for interacting with the Push Notifications service. ```APIDOC ## Client Class Methods ### Description Public methods of the Client class for interacting with the Push Notifications service. ### Methods - **constructor(options: ClientOptions)** - Initializes the Client with provided options. - **pushNotificationManager.subscribe(options: SubscribeOptions): Promise** - Subscribes the device to push notifications. - **pushNotificationManager.unsubscribe(options: UnsubscribeOptions): Promise** - Unsubscribes the device from push notifications. - **pushNotificationManager.getDeviceState(): Promise** - Retrieves the current device registration state. - **pushNotificationManager.addDeviceInterest(interest: string): Promise** - Adds a single interest to the device. - **pushNotificationManager.removeDeviceInterest(interest: string): Promise** - Removes a single interest from the device. - **pushNotificationManager.setDeviceInterests(interests: string[]): Promise** - Sets all interests for the device. - **pushNotificationManager.getDeviceInterests(): Promise** - Retrieves all interests for the device. - **pushNotificationManager.getDeviceId(): Promise** - Retrieves the unique device identifier. - **pushNotificationManager.getDeviceRegistrationState(): Promise** - Retrieves the device registration state. - **pushNotificationManager.setUserId(userId: string, tokenProvider: ITokenProvider): Promise** - Associates a user ID with the device and provides a token provider. - **pushNotificationManager.removeUserId(): Promise** - Removes the user association from the device. ### Parameters and Return Types Detailed parameter tables, return types, and error conditions for each method are documented in `api-reference/client.md`. ``` -------------------------------- ### Internal SDK Import Patterns Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/module-structure.md Shows how modules within the SDK import other internal modules. This illustrates the dependencies between different parts of the library. ```javascript // push-notifications.js import doRequest from './do-request'; import TokenProvider from './token-provider'; import DeviceStateStore from './device-state-store'; ``` ```javascript // token-provider.js import doRequest from './do-request'; ``` ```javascript // service-worker.js import doRequest from './do-request'; import DeviceStateStore from './device-state-store'; ``` ```javascript // do-request.js // (no imports) ``` ```javascript // device-state-store.js // (no imports) ``` -------------------------------- ### addDeviceInterest Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/api-reference/client.md Subscribes the device to an interest to receive notifications published to that interest. Ensure `.start()` has been called before using this method. ```APIDOC ## addDeviceInterest() ### Description Subscribe the device to an interest to receive notifications published to that interest. ### Signature ```typescript addDeviceInterest(interest: string): Promise ``` ### Parameters #### Path Parameters - **interest** (string) - Required - The interest name to subscribe to ### Throws - `Could not add Device Interest. SDK not registered with Beams. Did you call .start?` - `start()` has not been called - `Interest name is required` - Interest is null or undefined - `Interest {name} is not a string` - Interest is not a string type - `interest "{name}" contains a forbidden character. Allowed characters are: ASCII upper/lower-case letters, numbers or one of _-=@,.;` - Interest contains invalid characters - `Interest is longer than the maximum of 164 chars` - Interest exceeds maximum length ### Request Example ```javascript await beamsClient.addDeviceInterest('sports'); ``` ``` -------------------------------- ### Parallel Operations with Promise.all Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Utilize Promise.all to execute multiple independent SDK methods concurrently, improving performance by waiting for all to complete. ```javascript // Safe to run in parallel (no conflicts) const [deviceId, interests, state] = await Promise.all([ client.getDeviceId(), client.getDeviceInterests(), client.getRegistrationState() ]); ``` -------------------------------- ### Client Initialization with Endpoint Override for Testing Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/configuration.md Use the endpointOverride option to point the client to a custom API endpoint, useful for local development or testing with mock servers. ```javascript const beamsClient = new PusherPushNotifications.Client({ instanceId: 'test-instance', endpointOverride: 'http://localhost:3000' // local mock server }); ``` -------------------------------- ### Client Instance Properties Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Provides information about the properties available on an instance of the Client class, such as instanceId, deviceId, and userId. ```APIDOC ## Client Instance Properties ### instanceId #### Description The Pusher Beams instance ID. #### Type `string` (read-only) ### deviceId #### Description The unique device identifier, set after `start()` completes. Initially null. #### Type `string | null` ### userId #### Description The authenticated user ID, set after `setUserId()`. Initially null. #### Type `string | null` ``` -------------------------------- ### Get Registration and Permission State Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Retrieve the current device registration and permission state using `getRegistrationState()`. This returns a promise that resolves to one of several `RegistrationState` enum values, indicating whether permission is granted, required, or denied, and if the device is registered with Beams. ```javascript const state = await client.getRegistrationState(); if (state === RegistrationState.PERMISSION_PROMPT_REQUIRED) { console.log('User needs to grant permission'); } ``` -------------------------------- ### Client Class API Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/README.md The main SDK class with all methods documented. This class provides the primary interface for interacting with the Pusher Beams service. ```APIDOC ## Client Class ### Description The main SDK class with all methods documented. ### Methods (Specific methods are documented in `api-reference/client.md`) ### Configuration (Constructor options are documented in `configuration.md`) ``` -------------------------------- ### Check Registration State and Log Status Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/api-reference/registration-state.md Checks the current registration state and logs a message indicating whether the device is ready, requires permission, or has been denied. ```javascript const state = await beamsClient.getRegistrationState(); if (state === PusherPushNotifications.RegistrationState.PERMISSION_GRANTED_REGISTERED_WITH_BEAMS) { console.log('Device is ready to receive notifications'); } else if (state === PusherPushNotifications.RegistrationState.PERMISSION_PROMPT_REQUIRED) { console.log('Need to request notification permission'); } else if (state === PusherPushNotifications.RegistrationState.PERMISSION_DENIED) { console.log('User has denied permission'); } ``` -------------------------------- ### Sequential Operations with Async/Await Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Execute SDK methods in a specific order using async/await to ensure operations complete before the next one begins. ```javascript await client.start(); await client.addDeviceInterest('sports'); const interests = await client.getDeviceInterests(); ``` -------------------------------- ### TokenProviderOptions Interface for Configuration Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Defines the configuration options available when setting up a TokenProvider. ```typescript TokenProviderOptions ``` -------------------------------- ### TokenProvider Class Export Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/module-structure.md Demonstrates the default export of the TokenProvider class from its module. ```javascript export default class TokenProvider { ... } ``` -------------------------------- ### ClientOptions Interface for Pusher Beams Web SDK Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/types.md Defines the configuration options for the Client constructor. Requires an instanceId and optionally accepts a serviceWorkerRegistration or endpointOverride. ```typescript interface ClientOptions { instanceId: string; serviceWorkerRegistration?: ServiceWorkerRegistration; endpointOverride?: string; } ``` -------------------------------- ### TokenProvider Class Method Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/MANIFEST.txt Documentation for the public method of the TokenProvider class, used for fetching authentication tokens. ```APIDOC ## TokenProvider Class Method ### Description Public method of the TokenProvider class for fetching authentication tokens. ### Method - **fetchToken(user: { userId: string }): Promise** - Fetches an authentication token for a given user. ### Parameters and Return Types Detailed parameter tables, return types, and error conditions for this method are documented in `api-reference/token-provider.md`. ``` -------------------------------- ### Package JSON Entry Points Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/module-structure.md Defines the main JavaScript file and TypeScript type definitions for the package. ```json { "main": "dist/push-notifications-esm.js", "types": "index.d.ts" } ``` -------------------------------- ### TokenProviderOptions Interface for Pusher Beams Web SDK Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/types.md Defines the configuration options for the TokenProvider constructor. Accepts a URL for fetching tokens and optional query parameters, headers, and credentials. ```typescript interface TokenProviderOptions { url: string; queryParams?: { [key: string]: any }; headers?: { [key: string]: string }; credentials?: string; } ``` -------------------------------- ### Client.clearAllState() Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Clears all local state related to device registration and user association, then re-registers the device. This is useful for forcing a fresh registration. ```APIDOC ## Method: Client.clearAllState() ### Description Clear and re-register ### Signature `() => Promise` ``` -------------------------------- ### TokenProvider Class for Token Fetching Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md A utility class for fetching authentication tokens. Implement the ITokenProvider interface to create custom token providers. ```typescript TokenProvider ``` -------------------------------- ### TokenProvider Class API Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/README.md Handles authentication token fetching for the SDK. ```APIDOC ## TokenProvider Class ### Description Authentication token fetching. ### Methods (Specific methods are documented in `api-reference/token-provider.md`) ``` -------------------------------- ### Client.setDeviceInterests() Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/API.md Sets all of the device's interests to the provided list. This will replace any existing interests. ```APIDOC ## Method: Client.setDeviceInterests() ### Description Set all interests ### Signature `(interests: string[]) => Promise` ``` -------------------------------- ### Token Provider with Query Parameters Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/configuration.md Configure a TokenProvider to include additional query parameters in token requests. These are appended to the URL and useful for passing identifiers like API keys or version numbers. ```javascript const tokenProvider = new PusherPushNotifications.TokenProvider({ url: 'https://your-backend.com/beams-auth', queryParams: { apiKey: 'your-api-key', version: 'v1' } }); // Request will be: // GET https://your-backend.com/beams-auth?user_id=alice&apiKey=your-api-key&version=v1 ``` -------------------------------- ### Set Environment Variables for Beams Source: https://github.com/pusher/push-notifications-web/blob/master/_autodocs/quick-start.md Configure your environment variables in a .env file to set up your Pusher Beams instance ID, API URL, and environment type. ```bash REACT_APP_BEAMS_INSTANCE_ID=your-instance-id-here REACT_APP_API_URL=https://your-api.example.com REACT_APP_ENV=production ```