New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@pusher/push-notifications-web

Package Overview
Dependencies
Maintainers
9
Versions
19
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@pusher/push-notifications-web - npm Package Compare versions

Comparing version 0.9.1 to 0.9.2-beta

1485

dist/push-notifications-esm.js

@@ -0,1 +1,59 @@

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {

@@ -35,11 +93,32 @@ if (key in obj) {

function doRequest({
method,
path,
body = null,
headers = {}
}) {
const options = {
method,
headers
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
}
}
function _iterableToArray(iter) {
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
function doRequest(_ref) {
var method = _ref.method,
path = _ref.path,
_ref$body = _ref.body,
body = _ref$body === void 0 ? null : _ref$body,
_ref$headers = _ref.headers,
headers = _ref$headers === void 0 ? {} : _ref$headers;
var options = {
method: method,
headers: headers
};

@@ -54,37 +133,104 @@

return fetch(path, options).then(async response => {
if (!response.ok) {
await handleError(response);
}
return fetch(path, options).then(
/*#__PURE__*/
function () {
var _ref2 = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(response) {
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (response.ok) {
_context.next = 3;
break;
}
try {
return await response.json();
} catch (_) {
return null;
}
});
_context.next = 3;
return handleError(response);
case 3:
_context.prev = 3;
_context.next = 6;
return response.json();
case 6:
return _context.abrupt("return", _context.sent);
case 9:
_context.prev = 9;
_context.t0 = _context["catch"](3);
return _context.abrupt("return", null);
case 12:
case "end":
return _context.stop();
}
}
}, _callee, null, [[3, 9]]);
}));
return function (_x) {
return _ref2.apply(this, arguments);
};
}());
}
async function handleError(response) {
let errorMessage;
function handleError(_x2) {
return _handleError.apply(this, arguments);
}
try {
const {
error = 'Unknown error',
description = 'No description'
} = await response.json();
errorMessage = `Unexpected status code ${response.status}: ${error}, ${description}`;
} catch (_) {
errorMessage = `Unexpected status code ${response.status}: Cannot parse error response`;
}
function _handleError() {
_handleError = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee2(response) {
var errorMessage, _ref3, _ref3$error, error, _ref3$description, description;
throw new Error(errorMessage);
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.prev = 0;
_context2.next = 3;
return response.json();
case 3:
_ref3 = _context2.sent;
_ref3$error = _ref3.error;
error = _ref3$error === void 0 ? 'Unknown error' : _ref3$error;
_ref3$description = _ref3.description;
description = _ref3$description === void 0 ? 'No description' : _ref3$description;
errorMessage = "Unexpected status code ".concat(response.status, ": ").concat(error, ", ").concat(description);
_context2.next = 14;
break;
case 11:
_context2.prev = 11;
_context2.t0 = _context2["catch"](0);
errorMessage = "Unexpected status code ".concat(response.status, ": Cannot parse error response");
case 14:
throw new Error(errorMessage);
case 15:
case "end":
return _context2.stop();
}
}
}, _callee2, null, [[0, 11]]);
}));
return _handleError.apply(this, arguments);
}
class TokenProvider {
constructor({
url,
queryParams,
headers
} = {}) {
var TokenProvider =
/*#__PURE__*/
function () {
function TokenProvider() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
url = _ref.url,
queryParams = _ref.queryParams,
headers = _ref.headers;
_classCallCheck(this, TokenProvider);
this.url = url;

@@ -95,21 +241,56 @@ this.queryParams = queryParams;

async fetchToken(userId) {
let queryParams = _objectSpread({
user_id: userId
}, this.queryParams);
_createClass(TokenProvider, [{
key: "fetchToken",
value: function () {
var _fetchToken = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(userId) {
var queryParams, encodedParams, options, response;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
queryParams = _objectSpread({
user_id: userId
}, this.queryParams);
encodedParams = Object.entries(queryParams).map(function (kv) {
return kv.map(encodeURIComponent).join('=');
}).join('&');
options = {
method: 'GET',
path: "".concat(this.url, "?").concat(encodedParams),
headers: this.headers
};
_context.next = 5;
return doRequest(options);
const encodedParams = Object.entries(queryParams).map(kv => kv.map(encodeURIComponent).join('=')).join('&');
const options = {
method: 'GET',
path: `${this.url}?${encodedParams}`,
headers: this.headers
};
let response = await doRequest(options);
return response;
}
case 5:
response = _context.sent;
return _context.abrupt("return", response);
}
case 7:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
class DeviceStateStore {
constructor(instanceId) {
function fetchToken(_x) {
return _fetchToken.apply(this, arguments);
}
return fetchToken;
}()
}]);
return TokenProvider;
}();
var DeviceStateStore =
/*#__PURE__*/
function () {
function DeviceStateStore(instanceId) {
_classCallCheck(this, DeviceStateStore);
this._instanceId = instanceId;

@@ -119,218 +300,381 @@ this._dbConn = null;

get _dbName() {
return `beams-${this._instanceId}`;
}
_createClass(DeviceStateStore, [{
key: "connect",
value: function connect() {
var _this = this;
get isConnected() {
return this._dbConn !== null;
}
return new Promise(function (resolve, reject) {
var request = indexedDB.open(_this._dbName);
connect() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(this._dbName);
request.onsuccess = function (event) {
var db = event.target.result;
_this._dbConn = db;
request.onsuccess = event => {
const db = event.target.result;
this._dbConn = db;
_this._readState().then(function (state) {
return state === null ? _this.clear() : Promise.resolve();
}).then(resolve);
};
this._readState().then(state => state === null ? this.clear() : Promise.resolve()).then(resolve);
};
request.onupgradeneeded = function (event) {
var db = event.target.result;
db.createObjectStore('beams', {
keyPath: 'instance_id'
});
};
request.onupgradeneeded = event => {
const db = event.target.result;
db.createObjectStore('beams', {
keyPath: 'instance_id'
});
};
request.onerror = function (event) {
var error = new Error("Database error: ".concat(event.target.error));
reject(error);
};
});
}
}, {
key: "clear",
value: function clear() {
return this._writeState({
instance_id: this._instanceId,
device_id: null,
token: null,
user_id: null
});
}
}, {
key: "_readState",
value: function _readState() {
var _this2 = this;
request.onerror = event => {
const error = new Error(`Database error: ${event.target.error}`);
reject(error);
};
});
}
if (!this.isConnected) {
throw new Error('Cannot read value: DeviceStateStore not connected to IndexedDB');
}
clear() {
return this._writeState({
instance_id: this._instanceId,
device_id: null,
token: null,
user_id: null
});
}
return new Promise(function (resolve, reject) {
var request = _this2._dbConn.transaction('beams').objectStore('beams').get(_this2._instanceId);
_readState() {
if (!this.isConnected) {
throw new Error('Cannot read value: DeviceStateStore not connected to IndexedDB');
request.onsuccess = function (event) {
var state = event.target.result;
if (!state) {
resolve(null);
}
resolve(state);
};
request.onerror = function (event) {
reject(event.target.error);
};
});
}
}, {
key: "_readProperty",
value: function () {
var _readProperty2 = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(name) {
var state;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return this._readState();
return new Promise((resolve, reject) => {
const request = this._dbConn.transaction('beams').objectStore('beams').get(this._instanceId);
case 2:
state = _context.sent;
request.onsuccess = event => {
const state = event.target.result;
if (!(state === null)) {
_context.next = 5;
break;
}
if (!state) {
resolve(null);
}
return _context.abrupt("return", null);
resolve(state);
};
case 5:
return _context.abrupt("return", state[name] || null);
request.onerror = event => {
reject(event.target.error);
};
});
}
case 6:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
async _readProperty(name) {
const state = await this._readState();
function _readProperty(_x) {
return _readProperty2.apply(this, arguments);
}
if (state === null) {
return null;
return _readProperty;
}()
}, {
key: "_writeState",
value: function _writeState(state) {
var _this3 = this;
if (!this.isConnected) {
throw new Error('Cannot write value: DeviceStateStore not connected to IndexedDB');
}
return new Promise(function (resolve, reject) {
var request = _this3._dbConn.transaction('beams', 'readwrite').objectStore('beams').put(state);
request.onsuccess = function (_) {
resolve();
};
request.onerror = function (event) {
reject(event.target.error);
};
});
}
}, {
key: "_writeProperty",
value: function () {
var _writeProperty2 = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee2(name, value) {
var state;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this._readState();
return state[name] || null;
}
case 2:
state = _context2.sent;
state[name] = value;
_context2.next = 6;
return this._writeState(state);
_writeState(state) {
if (!this.isConnected) {
throw new Error('Cannot write value: DeviceStateStore not connected to IndexedDB');
case 6:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function _writeProperty(_x2, _x3) {
return _writeProperty2.apply(this, arguments);
}
return _writeProperty;
}()
}, {
key: "getToken",
value: function getToken() {
return this._readProperty('token');
}
}, {
key: "setToken",
value: function setToken(token) {
return this._writeProperty('token', token);
}
}, {
key: "getDeviceId",
value: function getDeviceId() {
return this._readProperty('device_id');
}
}, {
key: "setDeviceId",
value: function setDeviceId(deviceId) {
return this._writeProperty('device_id', deviceId);
}
}, {
key: "getUserId",
value: function getUserId() {
return this._readProperty('user_id');
}
}, {
key: "setUserId",
value: function setUserId(userId) {
return this._writeProperty('user_id', userId);
}
}, {
key: "getLastSeenSdkVersion",
value: function getLastSeenSdkVersion() {
return this._readProperty('last_seen_sdk_version');
}
}, {
key: "setLastSeenSdkVersion",
value: function setLastSeenSdkVersion(sdkVersion) {
return this._writeProperty('last_seen_sdk_version', sdkVersion);
}
}, {
key: "getLastSeenUserAgent",
value: function getLastSeenUserAgent() {
return this._readProperty('last_seen_user_agent');
}
}, {
key: "setLastSeenUserAgent",
value: function setLastSeenUserAgent(userAgent) {
return this._writeProperty('last_seen_user_agent', userAgent);
}
}, {
key: "_dbName",
get: function get() {
return "beams-".concat(this._instanceId);
}
}, {
key: "isConnected",
get: function get() {
return this._dbConn !== null;
}
}]);
return new Promise((resolve, reject) => {
const request = this._dbConn.transaction('beams', 'readwrite').objectStore('beams').put(state);
return DeviceStateStore;
}();
request.onsuccess = _ => {
resolve();
};
var version = "0.9.2-beta";
request.onerror = event => {
reject(event.target.error);
};
});
}
var SERVICE_WORKER_URL = "/service-worker.js?pusherBeamsWebSDKVersion=".concat(version);
function init(_x) {
return _init.apply(this, arguments);
}
async _writeProperty(name, value) {
const state = await this._readState();
state[name] = value;
await this._writeState(state);
}
function _init() {
_init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee10(config) {
var instanceId, _config$endpointOverr, endpointOverride, _config$serviceWorker, serviceWorkerRegistration, deviceStateStore, deviceId, token, userId, instance, deviceExists;
getToken() {
return this._readProperty('token');
}
return regeneratorRuntime.wrap(function _callee10$(_context10) {
while (1) {
switch (_context10.prev = _context10.next) {
case 0:
if (config) {
_context10.next = 2;
break;
}
setToken(token) {
return this._writeProperty('token', token);
}
throw new Error('Config object required');
getDeviceId() {
return this._readProperty('device_id');
}
case 2:
instanceId = config.instanceId, _config$endpointOverr = config.endpointOverride, endpointOverride = _config$endpointOverr === void 0 ? null : _config$endpointOverr, _config$serviceWorker = config.serviceWorkerRegistration, serviceWorkerRegistration = _config$serviceWorker === void 0 ? null : _config$serviceWorker;
setDeviceId(deviceId) {
return this._writeProperty('device_id', deviceId);
}
if (!(instanceId === undefined)) {
_context10.next = 5;
break;
}
getUserId() {
return this._readProperty('user_id');
}
throw new Error('Instance ID is required');
setUserId(userId) {
return this._writeProperty('user_id', userId);
}
case 5:
if (!(typeof instanceId !== 'string')) {
_context10.next = 7;
break;
}
getLastSeenSdkVersion() {
return this._readProperty('last_seen_sdk_version');
}
throw new Error('Instance ID must be a string');
setLastSeenSdkVersion(sdkVersion) {
return this._writeProperty('last_seen_sdk_version', sdkVersion);
}
case 7:
if (!(instanceId.length === 0)) {
_context10.next = 9;
break;
}
getLastSeenUserAgent() {
return this._readProperty('last_seen_user_agent');
}
throw new Error('Instance ID cannot be empty');
setLastSeenUserAgent(userAgent) {
return this._writeProperty('last_seen_user_agent', userAgent);
}
case 9:
if (window.indexedDB) {
_context10.next = 11;
break;
}
}
throw new Error('Pusher Beams does not support this browser version (IndexedDB not supported)');
var version = "0.9.1";
case 11:
if ('showNotification' in ServiceWorkerRegistration.prototype) {
_context10.next = 13;
break;
}
const SERVICE_WORKER_URL = `/service-worker.js?pusherBeamsWebSDKVersion=${version}`;
async function init(config) {
if (!config) {
throw new Error('Config object required');
}
throw new Error('Pusher Beams does not support this browser version (ServiceWorkerRegistration not supported)');
const {
instanceId,
endpointOverride = null,
serviceWorkerRegistration = null
} = config;
case 13:
if ('PushManager' in window) {
_context10.next = 15;
break;
}
if (instanceId === undefined) {
throw new Error('Instance ID is required');
}
throw new Error('Pusher Beams does not support this browser version (PushManager not supported)');
if (typeof instanceId !== 'string') {
throw new Error('Instance ID must be a string');
}
case 15:
deviceStateStore = new DeviceStateStore(instanceId);
_context10.next = 18;
return deviceStateStore.connect();
if (instanceId.length === 0) {
throw new Error('Instance ID cannot be empty');
}
case 18:
_context10.next = 20;
return deviceStateStore.getDeviceId();
if (!window.indexedDB) {
throw new Error('Pusher Beams does not support this browser version (IndexedDB not supported)');
}
case 20:
deviceId = _context10.sent;
_context10.next = 23;
return deviceStateStore.getToken();
if (!('showNotification' in ServiceWorkerRegistration.prototype)) {
throw new Error('Pusher Beams does not support this browser version (ServiceWorkerRegistration not supported)');
}
case 23:
token = _context10.sent;
_context10.next = 26;
return deviceStateStore.getUserId();
if (!('PushManager' in window)) {
throw new Error('Pusher Beams does not support this browser version (PushManager not supported)');
}
case 26:
userId = _context10.sent;
instance = new PushNotificationsInstance({
instanceId: instanceId,
deviceId: deviceId,
token: token,
userId: userId,
serviceWorkerRegistration: serviceWorkerRegistration,
deviceStateStore: deviceStateStore,
endpointOverride: endpointOverride
});
deviceExists = deviceId !== null;
const deviceStateStore = new DeviceStateStore(instanceId);
await deviceStateStore.connect();
const deviceId = await deviceStateStore.getDeviceId();
const token = await deviceStateStore.getToken();
const userId = await deviceStateStore.getUserId();
const instance = new PushNotificationsInstance({
instanceId,
deviceId,
token,
userId,
serviceWorkerRegistration,
deviceStateStore,
endpointOverride
});
const deviceExists = deviceId !== null;
if (!deviceExists) {
_context10.next = 37;
break;
}
if (deviceExists) {
try {
await instance._updateDeviceMetadata();
} catch (_) {// Best effort, do nothing if this fails.
}
}
_context10.prev = 30;
_context10.next = 33;
return instance._updateDeviceMetadata();
return instance;
case 33:
_context10.next = 37;
break;
case 35:
_context10.prev = 35;
_context10.t0 = _context10["catch"](30);
case 37:
return _context10.abrupt("return", instance);
case 38:
case "end":
return _context10.stop();
}
}
}, _callee10, null, [[30, 35]]);
}));
return _init.apply(this, arguments);
}
class PushNotificationsInstance {
constructor({
instanceId,
deviceId,
token,
userId,
serviceWorkerRegistration,
deviceStateStore,
endpointOverride = null
}) {
var PushNotificationsInstance =
/*#__PURE__*/
function () {
function PushNotificationsInstance(_ref) {
var instanceId = _ref.instanceId,
deviceId = _ref.deviceId,
token = _ref.token,
userId = _ref.userId,
serviceWorkerRegistration = _ref.serviceWorkerRegistration,
deviceStateStore = _ref.deviceStateStore,
_ref$endpointOverride = _ref.endpointOverride,
endpointOverride = _ref$endpointOverride === void 0 ? null : _ref$endpointOverride;
_classCallCheck(this, PushNotificationsInstance);
this.instanceId = instanceId;

@@ -344,8 +688,8 @@ this.deviceId = deviceId;

if (serviceWorkerRegistration) {
const serviceWorkerScope = serviceWorkerRegistration.scope;
const currentURL = window.location.href;
const scopeMatchesCurrentPage = currentURL.startsWith(serviceWorkerScope);
var serviceWorkerScope = serviceWorkerRegistration.scope;
var currentURL = window.location.href;
var scopeMatchesCurrentPage = currentURL.startsWith(serviceWorkerScope);
if (!scopeMatchesCurrentPage) {
throw new Error(`Could not initialize Pusher web push: current page not in serviceWorkerRegistration scope (${serviceWorkerScope})`);
throw new Error("Could not initialize Pusher web push: current page not in serviceWorkerRegistration scope (".concat(serviceWorkerScope, ")"));
}

@@ -357,211 +701,544 @@ }

get _baseURL() {
if (this._endpoint !== null) {
return this._endpoint;
}
_createClass(PushNotificationsInstance, [{
key: "start",
value: function () {
var _start = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee() {
var _ref2, publicKey, token, deviceId;
return `https://${this.instanceId}.pushnotifications.pusher.com`;
}
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (isSupportedBrowser()) {
_context.next = 3;
break;
}
async start() {
// Temporary whilst we only support Chrome in Beta release
if (!isSupportedBrowser()) {
console.warn('Pusher Web Push Notifications only supports Google Chrome (whilst in Beta)');
return this;
}
console.warn('Pusher Web Push Notifications only supports Google Chrome (whilst in Beta)');
return _context.abrupt("return", this);
if (this.deviceId !== null) {
return this;
}
case 3:
if (!(this.deviceId !== null)) {
_context.next = 5;
break;
}
const {
vapidPublicKey: publicKey
} = await this._getPublicKey(); // register with pushManager, get endpoint etc
return _context.abrupt("return", this);
const token = await this._getPushToken(publicKey); // get device id from errol
case 5:
_context.next = 7;
return this._getPublicKey();
const deviceId = await this._registerDevice(token);
await this._deviceStateStore.setToken(token);
await this._deviceStateStore.setDeviceId(deviceId);
await this._deviceStateStore.setLastSeenSdkVersion(version);
await this._deviceStateStore.setLastSeenUserAgent(window.navigator.userAgent);
this.token = token;
this.deviceId = deviceId;
return this;
}
case 7:
_ref2 = _context.sent;
publicKey = _ref2.vapidPublicKey;
_context.next = 11;
return this._getPushToken(publicKey);
async setUserId(userId, tokenProvider) {
// Temporary whilst we only support Chrome in Beta release
if (!isSupportedBrowser()) {
console.warn('Pusher Web Push Notifications only supports Google Chrome (whilst in Beta)');
return;
}
case 11:
token = _context.sent;
_context.next = 14;
return this._registerDevice(token);
if (this.deviceId === null) {
const error = new Error('.start must be called before .setUserId');
return Promise.reject(error);
}
case 14:
deviceId = _context.sent;
_context.next = 17;
return this._deviceStateStore.setToken(token);
if (typeof userId !== 'string') {
throw new Error(`User ID must be a string (was ${userId})`);
}
case 17:
_context.next = 19;
return this._deviceStateStore.setDeviceId(deviceId);
if (userId === '') {
throw new Error('User ID cannot be the empty string');
}
case 19:
_context.next = 21;
return this._deviceStateStore.setLastSeenSdkVersion(version);
if (this.userId !== null && this.userId !== userId) {
throw new Error('Changing the `userId` is not allowed.');
}
case 21:
_context.next = 23;
return this._deviceStateStore.setLastSeenUserAgent(window.navigator.userAgent);
const path = `${this._baseURL}/device_api/v1/instances/${encodeURIComponent(this.instanceId)}/devices/web/${this.deviceId}/user`;
const {
token: beamsAuthToken
} = await tokenProvider.fetchToken(userId);
const options = {
method: 'PUT',
path,
headers: {
Authorization: `Bearer ${beamsAuthToken}`
case 23:
this.token = token;
this.deviceId = deviceId;
return _context.abrupt("return", this);
case 26:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function start() {
return _start.apply(this, arguments);
}
};
await doRequest(options);
this.userId = userId;
return this._deviceStateStore.setUserId(userId);
}
async stop() {
// Temporary whilst we only support Chrome in Beta release
if (!isSupportedBrowser()) {
console.warn('Pusher Web Push Notifications only supports Google Chrome (whilst in Beta)');
return;
}
return start;
}()
}, {
key: "setUserId",
value: function () {
var _setUserId = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee2(userId, tokenProvider) {
var error, path, _ref3, beamsAuthToken, options;
if (this.deviceId === null) {
return;
}
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (isSupportedBrowser()) {
_context2.next = 3;
break;
}
await this._deleteDevice();
await this._deviceStateStore.clear();
this.deviceId = null;
this.token = null;
this.userId = null;
}
console.warn('Pusher Web Push Notifications only supports Google Chrome (whilst in Beta)');
return _context2.abrupt("return");
async clearAllState() {
// Temporary whilst we only support Chrome in Beta release
if (!isSupportedBrowser()) {
console.warn('Pusher Web Push Notifications only supports Google Chrome (whilst in Beta)');
return;
}
case 3:
if (!(this.deviceId === null)) {
_context2.next = 6;
break;
}
await this.stop();
await this.start();
}
error = new Error('.start must be called before .setUserId');
return _context2.abrupt("return", Promise.reject(error));
async _getPublicKey() {
const path = `${this._baseURL}/device_api/v1/instances/${encodeURIComponent(this.instanceId)}/web-vapid-public-key`;
const options = {
method: 'GET',
path
};
return doRequest(options);
}
case 6:
if (!(typeof userId !== 'string')) {
_context2.next = 8;
break;
}
async _getPushToken(publicKey) {
try {
let reg;
throw new Error("User ID must be a string (was ".concat(userId, ")"));
if (this._serviceWorkerRegistration) {
reg = this._serviceWorkerRegistration; // TODO: Call update only when we detect an SDK change
} else {
// Check that service worker file exists
const {
status: swStatusCode
} = await fetch(SERVICE_WORKER_URL);
case 8:
if (!(userId === '')) {
_context2.next = 10;
break;
}
if (swStatusCode !== 200) {
throw new Error('Cannot start SDK, service worker missing: No file found at /service-worker.js');
}
throw new Error('User ID cannot be the empty string');
window.navigator.serviceWorker.register(SERVICE_WORKER_URL, {
// explicitly opting out of `importScripts` caching just in case our
// customers decides to host and serve the imported scripts and
// accidentally set `Cache-Control` to something other than `max-age=0`
updateViaCache: 'none'
});
reg = await window.navigator.serviceWorker.ready;
case 10:
if (!(this.userId !== null && this.userId !== userId)) {
_context2.next = 12;
break;
}
throw new Error('Changing the `userId` is not allowed.');
case 12:
path = "".concat(this._baseURL, "/device_api/v1/instances/").concat(encodeURIComponent(this.instanceId), "/devices/web/").concat(this.deviceId, "/user");
_context2.next = 15;
return tokenProvider.fetchToken(userId);
case 15:
_ref3 = _context2.sent;
beamsAuthToken = _ref3.token;
options = {
method: 'PUT',
path: path,
headers: {
Authorization: "Bearer ".concat(beamsAuthToken)
}
};
_context2.next = 20;
return doRequest(options);
case 20:
this.userId = userId;
return _context2.abrupt("return", this._deviceStateStore.setUserId(userId));
case 22:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function setUserId(_x2, _x3) {
return _setUserId.apply(this, arguments);
}
const sub = await reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUInt8Array(publicKey)
});
return btoa(JSON.stringify(sub));
} catch (e) {
return Promise.reject(e);
}
}
return setUserId;
}()
}, {
key: "stop",
value: function () {
var _stop = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee3() {
return regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (isSupportedBrowser()) {
_context3.next = 3;
break;
}
async _registerDevice(token) {
const path = `${this._baseURL}/device_api/v1/instances/${encodeURIComponent(this.instanceId)}/devices/web`;
const device = {
token,
metadata: {
sdkVersion: version
console.warn('Pusher Web Push Notifications only supports Google Chrome (whilst in Beta)');
return _context3.abrupt("return");
case 3:
if (!(this.deviceId === null)) {
_context3.next = 5;
break;
}
return _context3.abrupt("return");
case 5:
_context3.next = 7;
return this._deleteDevice();
case 7:
_context3.next = 9;
return this._deviceStateStore.clear();
case 9:
this.deviceId = null;
this.token = null;
this.userId = null;
case 12:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function stop() {
return _stop.apply(this, arguments);
}
};
const options = {
method: 'POST',
path,
body: device
};
const response = await doRequest(options);
return response.id;
}
async _deleteDevice() {
const path = `${this._baseURL}/device_api/v1/instances/${encodeURIComponent(this.instanceId)}/devices/web/${encodeURIComponent(this.deviceId)}`;
const options = {
method: 'DELETE',
path
};
await doRequest(options);
}
/**
* Submit SDK version and browser details (via the user agent) to Pusher Beams.
*/
return stop;
}()
}, {
key: "clearAllState",
value: function () {
var _clearAllState = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee4() {
return regeneratorRuntime.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (isSupportedBrowser()) {
_context4.next = 3;
break;
}
console.warn('Pusher Web Push Notifications only supports Google Chrome (whilst in Beta)');
return _context4.abrupt("return");
async _updateDeviceMetadata() {
const userAgent = window.navigator.userAgent;
const storedUserAgent = await this._deviceStateStore.getLastSeenUserAgent();
const storedSdkVersion = await this._deviceStateStore.getLastSeenSdkVersion();
case 3:
_context4.next = 5;
return this.stop();
if (userAgent === storedUserAgent && version === storedSdkVersion) {
// Nothing to do
return;
case 5:
_context4.next = 7;
return this.start();
case 7:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function clearAllState() {
return _clearAllState.apply(this, arguments);
}
return clearAllState;
}()
}, {
key: "_getPublicKey",
value: function () {
var _getPublicKey2 = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee5() {
var path, options;
return regeneratorRuntime.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
path = "".concat(this._baseURL, "/device_api/v1/instances/").concat(encodeURIComponent(this.instanceId), "/web-vapid-public-key");
options = {
method: 'GET',
path: path
};
return _context5.abrupt("return", doRequest(options));
case 3:
case "end":
return _context5.stop();
}
}
}, _callee5, this);
}));
function _getPublicKey() {
return _getPublicKey2.apply(this, arguments);
}
return _getPublicKey;
}()
}, {
key: "_getPushToken",
value: function () {
var _getPushToken2 = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee6(publicKey) {
var reg, _ref4, swStatusCode, sub;
return regeneratorRuntime.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
_context6.prev = 0;
if (!this._serviceWorkerRegistration) {
_context6.next = 5;
break;
}
reg = this._serviceWorkerRegistration; // TODO: Call update only when we detect an SDK change
_context6.next = 15;
break;
case 5:
_context6.next = 7;
return fetch(SERVICE_WORKER_URL);
case 7:
_ref4 = _context6.sent;
swStatusCode = _ref4.status;
if (!(swStatusCode !== 200)) {
_context6.next = 11;
break;
}
throw new Error('Cannot start SDK, service worker missing: No file found at /service-worker.js');
case 11:
window.navigator.serviceWorker.register(SERVICE_WORKER_URL, {
// explicitly opting out of `importScripts` caching just in case our
// customers decides to host and serve the imported scripts and
// accidentally set `Cache-Control` to something other than `max-age=0`
updateViaCache: 'none'
});
_context6.next = 14;
return window.navigator.serviceWorker.ready;
case 14:
reg = _context6.sent;
case 15:
_context6.next = 17;
return reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUInt8Array(publicKey)
});
case 17:
sub = _context6.sent;
return _context6.abrupt("return", btoa(JSON.stringify(sub)));
case 21:
_context6.prev = 21;
_context6.t0 = _context6["catch"](0);
return _context6.abrupt("return", Promise.reject(_context6.t0));
case 24:
case "end":
return _context6.stop();
}
}
}, _callee6, this, [[0, 21]]);
}));
function _getPushToken(_x4) {
return _getPushToken2.apply(this, arguments);
}
return _getPushToken;
}()
}, {
key: "_registerDevice",
value: function () {
var _registerDevice2 = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee7(token) {
var path, device, options, response;
return regeneratorRuntime.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
path = "".concat(this._baseURL, "/device_api/v1/instances/").concat(encodeURIComponent(this.instanceId), "/devices/web");
device = {
token: token,
metadata: {
sdkVersion: version
}
};
options = {
method: 'POST',
path: path,
body: device
};
_context7.next = 5;
return doRequest(options);
case 5:
response = _context7.sent;
return _context7.abrupt("return", response.id);
case 7:
case "end":
return _context7.stop();
}
}
}, _callee7, this);
}));
function _registerDevice(_x5) {
return _registerDevice2.apply(this, arguments);
}
return _registerDevice;
}()
}, {
key: "_deleteDevice",
value: function () {
var _deleteDevice2 = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee8() {
var path, options;
return regeneratorRuntime.wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
path = "".concat(this._baseURL, "/device_api/v1/instances/").concat(encodeURIComponent(this.instanceId), "/devices/web/").concat(encodeURIComponent(this.deviceId));
options = {
method: 'DELETE',
path: path
};
_context8.next = 4;
return doRequest(options);
case 4:
case "end":
return _context8.stop();
}
}
}, _callee8, this);
}));
function _deleteDevice() {
return _deleteDevice2.apply(this, arguments);
}
return _deleteDevice;
}()
/**
* Submit SDK version and browser details (via the user agent) to Pusher Beams.
*/
}, {
key: "_updateDeviceMetadata",
value: function () {
var _updateDeviceMetadata2 = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee9() {
var userAgent, storedUserAgent, storedSdkVersion, path, metadata, options;
return regeneratorRuntime.wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
userAgent = window.navigator.userAgent;
_context9.next = 3;
return this._deviceStateStore.getLastSeenUserAgent();
case 3:
storedUserAgent = _context9.sent;
_context9.next = 6;
return this._deviceStateStore.getLastSeenSdkVersion();
case 6:
storedSdkVersion = _context9.sent;
if (!(userAgent === storedUserAgent && version === storedSdkVersion)) {
_context9.next = 9;
break;
}
return _context9.abrupt("return");
case 9:
path = "".concat(this._baseURL, "/device_api/v1/instances/").concat(encodeURIComponent(this.instanceId), "/devices/web/").concat(this.deviceId, "/metadata");
metadata = {
sdkVersion: version
};
options = {
method: 'PUT',
path: path,
body: metadata
};
_context9.next = 14;
return doRequest(options);
case 14:
_context9.next = 16;
return this._deviceStateStore.setLastSeenSdkVersion(version);
case 16:
_context9.next = 18;
return this._deviceStateStore.setLastSeenUserAgent(userAgent);
case 18:
case "end":
return _context9.stop();
}
}
}, _callee9, this);
}));
function _updateDeviceMetadata() {
return _updateDeviceMetadata2.apply(this, arguments);
}
return _updateDeviceMetadata;
}()
}, {
key: "_baseURL",
get: function get() {
if (this._endpoint !== null) {
return this._endpoint;
}
return "https://".concat(this.instanceId, ".pushnotifications.pusher.com");
}
}]);
const path = `${this._baseURL}/device_api/v1/instances/${encodeURIComponent(this.instanceId)}/devices/web/${this.deviceId}/metadata`;
const metadata = {
sdkVersion: version
};
const options = {
method: 'PUT',
path,
body: metadata
};
await doRequest(options);
await this._deviceStateStore.setLastSeenSdkVersion(version);
await this._deviceStateStore.setLastSeenUserAgent(userAgent);
}
return PushNotificationsInstance;
}();
}
function urlBase64ToUInt8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
const rawData = window.atob(base64);
return Uint8Array.from([...rawData].map(char => char.charCodeAt(0)));
var padding = '='.repeat((4 - base64String.length % 4) % 4);
var base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
var rawData = window.atob(base64);
return Uint8Array.from(_toConsumableArray(rawData).map(function (_char) {
return _char.charCodeAt(0);
}));
}

@@ -574,8 +1251,8 @@ /**

function isSupportedBrowser() {
const winNav = window.navigator;
const vendorName = winNav.vendor;
const isChromium = window.chrome !== null && typeof window.chrome !== 'undefined';
const isOpera = winNav.userAgent.indexOf('OPR') > -1;
const isIEedge = winNav.userAgent.indexOf('Edge') > -1;
const isChrome = isChromium && vendorName === 'Google Inc.' && !isIEedge && !isOpera;
var winNav = window.navigator;
var vendorName = winNav.vendor;
var isChromium = window.chrome !== null && typeof window.chrome !== 'undefined';
var isOpera = winNav.userAgent.indexOf('OPR') > -1;
var isIEedge = winNav.userAgent.indexOf('Edge') > -1;
var isChrome = isChromium && vendorName === 'Google Inc.' && !isIEedge && !isOpera;
return isChrome || isOpera;

@@ -582,0 +1259,0 @@ }

{
"name": "@pusher/push-notifications-web",
"version": "0.9.1",
"version": "0.9.2-beta",
"description": "",

@@ -14,3 +14,3 @@ "main": "dist/push-notifications-esm.js",

"test:e2e": "jest ./end-to-end-tests/* --runInBand",
"prepublishchecks": "npm run lint && npm run test:unit && npm run build:cdn && npm run build:esm && npm run test:e2e",
"prepublishchecks": "npm run lint && npm run test:unit && npm run build:cdn && npm run build:esm",
"prepublishOnly": "publish-please guard",

@@ -17,0 +17,0 @@ "publish-please": "publish-please"

@@ -18,2 +18,3 @@ import resolve from 'rollup-plugin-node-resolve';

babel({
presets: ['@babel/preset-env'],
plugins: ['@babel/proposal-object-rest-spread'],

@@ -20,0 +21,0 @@ exclude: ['node_modules/**'],

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc