@withjoy/sdk-js
Version:
Joy Javascript SDK
1,309 lines (1,276 loc) • 473 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var Firebase = require('firebase/app');
require('firebase/auth');
require('firebase/database');
var PouchDB = _interopDefault(require('pouchdb-browser'));
var Subject = require('rxjs/Subject');
var Observable = require('rxjs/Observable');
require('rxjs/add/operator/publishReplay');
require('rxjs/add/operator/map');
require('rxjs/add/observable/combineLatest');
require('rxjs/add/operator/distinctUntilChanged');
require('rxjs/add/operator/pluck');
var rxjs = require('rxjs');
require('rxjs/add/observable/interval');
require('rxjs/add/operator/filter');
require('rxjs/add/operator/switchMap');
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
// Define Http Error Classes
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
var HttpError = /** @class */ (function (_super) {
__extends(HttpError, _super);
function HttpError(statusCode, name, message) {
var _this = _super.call(this, message) || this;
_this.name = (name) ? name : _this.name;
_this.stack = (_this.stack || '').split('\n').join();
_this.statusCode = statusCode;
return _this;
}
HttpError.prototype.isInformational = function () {
return this.statusCode >= 100 && this.statusCode < 200;
};
HttpError.prototype.isSuccessfull = function () {
return this.statusCode >= 200 && this.statusCode < 300;
};
HttpError.prototype.isRedirection = function () {
return this.statusCode >= 300 && this.statusCode < 400;
};
HttpError.prototype.isClient = function () {
return this.statusCode >= 400 && this.statusCode < 500;
};
HttpError.prototype.isServer = function () {
return this.statusCode >= 500;
};
return HttpError;
}(Error));
var createErrorClass = function (statusCode, name) {
return /** @class */ (function (_super) {
__extends(class_1, _super);
function class_1(message) {
return _super.call(this, statusCode, name, message) || this;
}
return class_1;
}(HttpError));
};
var client = {
BadRequest: createErrorClass(400, 'Bad Request'),
Unauthorized: createErrorClass(401, "Unauthorized"),
Forbidden: createErrorClass(403, "Forbidden"),
NotFound: createErrorClass(404, "Not Found"),
Conflict: createErrorClass(409, "Conflict"),
Gone: createErrorClass(410, "Gone"),
TooManyRequests: createErrorClass(429, "TooManyRequests")
};
var server = {
ApplicationException: createErrorClass(520, "Application Exception"),
InternalServerError: createErrorClass(500, "Internal Server Error"),
NotImplemented: createErrorClass(501, "Not Implemented"),
BadGateway: createErrorClass(502, "Bad Gateway"),
};
var jwt = require('jsonwebtoken');
/**
* A class to manage and deal with JWT Tokens
* @param token - a String containing the signed jwt token
* @constructor
*/
var JWT = /** @class */ (function () {
function JWT(token) {
this._token = token;
}
/**
* Generate a valid jwt token, generally for testing
*/
JWT.fromPayloadOptionsAndSecret = function (payload, options, secret) {
return new JWT(jwt.sign(payload, secret, options));
};
/**
* Get the internal token
* @returns {.qs.id_token|*|id_token}
*/
JWT.prototype.token = function () {
return this._token;
};
/**
* Decode the jwt contents
* @returns {object}
*/
JWT.prototype.decode = function () {
return jwt.decode(this.token());
};
/***
* Verify this signed token
* @param secret - Buffer containing the secret
* @param options - {issuer or audiance}
* @param callback (err, dataObj)
* @returns {*}
*/
JWT.prototype.verify = function (secret, options, callback) {
return jwt.verify(this.token(), secret, options, callback);
};
/**
* Gets the seconds remaining on this token before it expires
* @returns {number}
*/
JWT.prototype.timeLeft = function () {
var decoded;
try {
decoded = jwt.decode(this.token());
}
catch (err) {
decoded = null;
}
if (!decoded || !decoded.exp) {
return null;
}
return decoded.exp - Math.floor(Date.now() / 1000);
};
return JWT;
}());
var SLASH = '/';
var Url = /** @class */ (function () {
function Url() {
}
Url.getCurrent = function () {
return window.location.href;
};
/**
* Parse a url so that its components can be accessed individually, from:
* http://stackoverflow.com/questions/6644654/ but modified so it doesn't
* retain the HTML anchor elements (no orphaned DOM nodes).
*
* @param {String} path
* @returns {IUrlObject}
*/
Url.parse = function (path) {
var a = document.createElement('a');
a.href = path;
var obj = {
hash: '',
host: '',
hostname: '',
href: '',
origin: '',
pathname: '',
port: '',
protocol: '',
search: ''
};
Object.keys(obj).forEach(function (key) {
obj[key] = a[key];
});
return obj;
};
Url.parseSearch = function (search) {
var result = {};
search = search.replace('?', '');
search.split('&').forEach(function (str) {
var kv = str.split('=');
var key = kv[0];
var val = kv[1];
if (key && val) {
result[key] = val;
}
});
return result;
};
/**
* Build a url string from an object of url properties.
*
* @param {IUrlObject} obj
* @returns {string}
*/
Url.build = function (obj) {
obj.search = (typeof obj.search === 'object')
? Url.param(obj.search)
: obj.search;
return [
obj.origin,
obj.pathname,
obj.search,
obj.hash
].join('');
};
/**
* Join all arguments together into a URL string. Removes duplicate slashes
* (but leaves the double slashes in a protocol, eg: http://foo/bar/baz).
*
* @param args
* @returns {String}
*/
Url.join = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return Url.cleanSlashes(args.join(SLASH));
};
/**
* Serialize an object into a URL-friendly key1=val1&key2=val2 string.
*
* @param {Object} obj
* @returns {String}
*/
Url.param = function (obj) {
var pairs = Object.keys(obj).map(function (key) {
var k = encodeURIComponent(key);
var v = encodeURIComponent(obj[key]);
return k + '=' + v;
});
var str = pairs.join('&');
return (str) ? '?' + str : '';
};
/**
* Create an absolute URL from a given path. If the path is already
* absolute then it is returned as it is. Otherwise the path is made
* absolute using a base URL or current URL if base is not provided.
*
* @param {String} path
* @param {String} [base]
* @returns {String}
*/
Url.absolute = function (path, base) {
if (base === void 0) { base = Url.getCurrent(); }
var isAbsolute = (path.substr(0, 4) === 'http');
return (isAbsolute) ? path : Url.join(base, path);
};
/**
* Wrap a URL in slashes, ensuring no double slashes. Is careful not
* to destroy search parameters.
*
* Example:
* Url.wrapSlashes('foo/bar?baz=123'); -> '/foo/bar/?baz=123'
*
* @param {String} url
* @param {Boolean} last
* @param {Boolean} first
* @returns {string}
*/
Url.wrapSlashes = function (url, last, first) {
if (last === void 0) { last = true; }
if (first === void 0) { first = true; }
var split = url.split('?');
var search = split[1];
url = split[0];
url = (first && (url.substr(0, 4) !== 'http')) ? SLASH + url : url;
url = (last) ? url + SLASH : url;
url = (search) ? url + '?' + search : url;
return Url.cleanSlashes(url);
};
/**
* Remove double slashes from a url except when used in a protocol (https://).
*
* @param {String} url
* @returns {String}
*/
Url.cleanSlashes = function (url) {
return url
.replace(/([^:]\/)\/+/g, '$1') // remove from middle
.replace(/^\/\//, SLASH) // remove from beginning
.replace(/\/\/$/, SLASH); // remove from end
};
return Url;
}());
var HttpResource = /** @class */ (function () {
function HttpResource() {
this.baseUrl = '';
this.withCredentials = false;
this.headers = [];
this.contentJson = { name: 'Content-Type', data: 'application/json' };
}
/**
* GET requests
* @param {string} url
* @param {Array<IHeader>} headers
*/
HttpResource.prototype.get = function (url, headers) {
if (headers === void 0) { headers = []; }
return this.request(url, 'GET', headers);
};
/**
* PUT requests
* @param {string} url
* @param {Array<IHeader>} headers
* @param {any} [data]
*/
HttpResource.prototype.put = function (url, headers, data) {
if (headers === void 0) { headers = []; }
headers.push(this.contentJson);
return this.request(url, 'PUT', headers, JSON.stringify(data));
};
/**
* POST requests
* @param {string} url
* @param {Array<IHeader>} headers
* @param {any} [data]
*/
HttpResource.prototype.post = function (url, headers, data) {
if (headers === void 0) { headers = []; }
headers.push(this.contentJson);
return this.request(url, 'POST', headers, JSON.stringify(data));
};
/**
* DELETE requests
* @param {string} url
* @param {Array<IHeader>} headers
*/
HttpResource.prototype.delete = function (url, headers) {
if (headers === void 0) { headers = []; }
return this.request(url, 'DELETE', headers);
};
/**
* Sets the base url which is used on every request
* @param {string} url
*/
HttpResource.prototype.setBaseUrl = function (url) {
this.baseUrl = url;
};
/**
* Adds a header to a list which are added to every request
* @param {IHeader} header
* @returns {Function} to remove header
*/
HttpResource.prototype.addHeader = function (header) {
var _this = this;
this.headers.push(header);
return function () {
_this.headers = _this.headers.filter(function (item) {
return (item !== header);
});
};
};
/**
*
* @param options
* @returns url with query strings added, headers, data
*/
HttpResource.prototype.parseOptions = function (options) {
return {
url: (options.qs) ? Url.join.apply(Url, options.pathname) + Url.param(options.qs) : Url.join.apply(Url, options.pathname),
headers: (options.headers) ? options.headers : [],
data: (options.json) ? options.json : null
};
};
/**
* xhr requests
* @param {string} url
* @param {string} method
* @param {Array<IHeader>} headers
* @param {any} [data]
* @returns Promise
*/
HttpResource.prototype.request = function (url, method, headers, data) {
var _this = this;
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
var _url = _this.baseUrl + url;
var _headers = _this.headers.concat(headers);
xhr.open(method, _url);
xhr.withCredentials = _this.withCredentials;
_headers.forEach(function (header) {
xhr.setRequestHeader(header.name, header.data);
});
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 400) {
try {
resolve(JSON.parse(xhr.response));
}
catch (e) {
resolve(xhr.response);
}
}
else {
var err = new HttpError(xhr.status, "XHR: " + xhr.statusText, xhr.responseText);
reject(err);
}
};
xhr.onerror = function (err) {
reject(err);
};
if (method === 'POST' || method === 'PUT') {
xhr.send(data);
}
else {
xhr.send();
}
});
};
return HttpResource;
}());
/**
* secondsUntilTokenRefresh: 60,
secondsOkToUseTokenBeforeExpiry: 10,
*/
var Config = /** @class */ (function () {
function Config(env) {
this.env = env;
if (Object.keys(this.env).length === 0) {
this.env = process.env;
}
}
Object.defineProperty(Config.prototype, "auth0UserClientId", {
get: function () { return this.env.JOY_CONFIG_AUTH0_CLIENTID || "EsiknQLsU7Sy4Baqv7cZYM1xzifHQX3r"; },
enumerable: true,
configurable: true
});
Object.defineProperty(Config.prototype, "auth0Host", {
get: function () { return "withjoy.auth0.com"; },
enumerable: true,
configurable: true
});
Object.defineProperty(Config.prototype, "firebaseRoot", {
get: function () { return this.env.JOY_CONFIG_ROOT_FIREBASE || "https://joyauth.firebaseio.com"; },
enumerable: true,
configurable: true
});
Object.defineProperty(Config.prototype, "logEntriesBrowserAppToken", {
get: function () { return this.env.JOY_CONFIG_LE_TOKEN_BROWSER || null; },
enumerable: true,
configurable: true
});
Object.defineProperty(Config.prototype, "segmentWriteKey", {
get: function () { return this.env.JOY_CONFIG_SEGMENT_WRITE_KEY || "2xZJ98aly8fmfFDB9msDQlXsyVGVpUby"; },
enumerable: true,
configurable: true
});
Object.defineProperty(Config.prototype, "secondsUntilTokenRefresh", {
get: function () { return 60; },
enumerable: true,
configurable: true
});
Object.defineProperty(Config.prototype, "secondsOkToUseTokenBeforeExpiry", {
get: function () { return 10; },
enumerable: true,
configurable: true
});
Object.defineProperty(Config.prototype, "joyServiceConfig", {
get: function () {
return {
protocol: this.env.JOY_CONFIG_SERVICE_PROTOCOL || "https",
hostname: this.env.JOY_CONFIG_SERVICE_HOSTNAME || "rehearsal-api.withjoy.com",
port: this.env.JOY_CONFIG_SERVICE_PORT || 443,
routePrefix: this.env.JOY_CONFIG_SERVICE_ROUTE_PREFIX
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Config.prototype, "joyMediaServiceConfig", {
get: function () {
return {
protocol: this.env.JOY_CONFIG_MEDIA_SERVICE_PROTOCOL || "https",
hostname: this.env.JOY_CONFIG_MEDIA_SERVICE_HOSTNAME || "rehearsal-api.withjoy.com",
port: this.env.JOY_CONFIG_MEDIA_SERVICE_PORT || 443,
routePrefix: this.env.JOY_CONFIG_MEDIA_ROUTE_PREFIX
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Config.prototype, "joyRegistriesServiceConfig", {
get: function () {
return {
protocol: this.env.JOY_CONFIG_REGISTRIES_SERVICE_PROTOCOL || "https",
hostname: this.env.JOY_CONFIG_REGISTRIES_SERVICE_HOSTNAME || "ceremony-registries.withjoy.com",
port: this.env.JOY_CONFIG_REGISTRIES_SERVICE_PORT || 443,
routePrefix: this.env.JOY_CONFIG_REGISTRIES_ROUTE_PREFIX
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Config.prototype, "joyWebsiteConfig", {
get: function () {
return {
protocol: this.env.JOY_CONFIG_WEBSITE_PROTOCOL || "https",
hostname: this.env.JOY_CONFIG_WEBSITE_HOSTNAME || "rehearsal.withjoy.com",
port: this.env.JOY_CONFIG_WEBSITE_PORT || 443
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Config.prototype, "joyMarketingWebsiteConfig", {
get: function () {
return {
protocol: this.env.JOY_CONFIG_MARKETING_WEBSITE_PROTOCOL || "https",
hostname: this.env.JOY_CONFIG_MARKETING_WEBSITE_HOSTNAME || "rehearsal.withjoy.com",
port: this.env.JOY_CONFIG_MARKETING_WEBSITE_POST || 443
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Config.prototype, "joyBlissGatewayConfig", {
get: function () {
return {
protocol: this.env.JOY_CONFIG_BLISS_GATEWAY_PROTOCOL || "https",
hostname: this.env.JOY_CONFIG_BLISS_GATEWAY_HOSTNAME || "bliss-gateway.withjoy.com",
port: this.env.JOY_CONFIG_BLISS_GATEWAY_PORT || 443
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Config.prototype, "joySupportWebsiteConfig", {
get: function () {
return {
protocol: this.env.JOY_CONFIG_MARKETING_WEBSITE_PROTOCOL || "https",
hostname: this.env.JOY_CONFIG_MARKETING_WEBSITE_HOSTNAME || "help.withjoy.com",
port: this.env.JOY_CONFIG_MARKETING_WEBSITE_POST || 443
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Config.prototype, "appUrls", {
get: function () {
return {
ios: "https://itunes.apple.com/app/joy-wedding-app-website/id994411720?mt=8",
android: "https://play.google.com/store/apps/details?id=com.withjoy.joy"
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Config.prototype, "joyRedirectConfig", {
get: function () {
return {
protocol: this.env.JOY_CONFIG_REDIRECT_PROTOCOL || "https",
hostname: this.env.JOY_CONFIG_REDIRECT_HOSTNAME || "rehearsal-redirect.withjoy.com",
port: this.env.JOY_CONFIG_REDIRECT_PORT || 443,
routePrefix: this.env.JOY_CONFIG_REDIRECT_ROUTE_PREFIX
};
},
enumerable: true,
configurable: true
});
return Config;
}());
var getEnvOverrides = function (g) {
if (g.joyEnv) {
return g.joyEnv;
}
return {};
};
var globalObj = ((typeof window !== "undefined" && window) || {});
var config = new Config(getEnvOverrides(globalObj));
/**
* @license Copyright 2015 Logentries.
* Please view license at https://raw.github.com/logentries/le_js/master/LICENSE
*/
/*jslint browser:true*/
/*global define, module, exports, console, global */
/** @param {Object} window */
// export default function (root: any, factory) {
// if (typeof define === 'function' && define.amd) {
// // AMD. Register as an anonymous module.
// define(function() {
// return factory(root);
// });
// } else if (typeof exports === 'object') {
// // Node. Does not work with strict CommonJS, but
// // only CommonJS-like environments that support module.exports,
// // like Node.
// if (typeof global === 'object') {
// // Browserify. The calling object `this` does not reference window.
// // `global` and `this` are equivalent in Node, preferring global
// // adds support for Browserify.
// root = global;
// }
// module.exports = factory(root);
// } else {
// // Browser globals (root is window)
// root.LE = factory(root);
// }
// }(this || (typeof window == "undefined" ? global : window), function (window) {
// });
var factory = function (window) {
var _indexOf = function (array, obj) {
for (var i = 0; i < array.length; i++) {
if (obj === array[i]) {
return i;
}
}
return -1;
};
// Obtain a browser-specific XHR object
var _getAjaxObject = function () {
if (typeof XDomainRequest !== "undefined") {
// We're using IE8/9
return new XDomainRequest();
}
return new XMLHttpRequest();
};
/**
* A single log event stream.
* @constructor
* @param {Object} options
*/
function LogStream(options) {
/**
* @const
* @type {string} */
var _traceCode = options.trace ? (Math.random() + Math.PI).toString(36).substring(2, 10) : null;
/** @type {string} */
var _pageInfo = options.page_info;
/** @type {string} */
var _token = options.token;
/** @type {boolean} */
var _print = options.print;
/** @type {boolean} */
var _noFormat = options.no_format;
/** @type {boolean} */
var _SSL = function () {
if (typeof XDomainRequest === "undefined") {
return options.ssl;
}
// If we're relying on XDomainRequest, we
// must adhere to the page's encryption scheme.
return window.location.protocol === "https:" ? true : false;
}();
/** @type {string} */
var _endpoint;
if (window.LEENDPOINT) {
_endpoint = window.LEENDPOINT;
}
else if (_noFormat) {
_endpoint = "webhook.logentries.com/noformat";
}
else {
_endpoint = "js.logentries.com/v1";
}
_endpoint = (_SSL ? "https://" : "http://") + _endpoint + "/logs/" + _token;
/**
* Flag to prevent further invocations on network err
** @type {boolean} */
var _shouldCall = true;
/** @type {Array.<string>} */
var _backlog = [];
/** @type {boolean} */
var _active = false;
/** @type {boolean} */
var _sentPageInfo = false;
if (options.catchall) {
var oldHandler = window.onerror;
var newHandler = function (msg, url, line) {
_rawLog({ error: msg, line: line, location: url }).level('ERROR').send();
if (oldHandler) {
return oldHandler(msg, url, line);
}
else {
return false;
}
};
window.onerror = newHandler;
}
var _agentInfo = function () {
var nav = window.navigator || { doNotTrack: undefined };
var screen = window.screen || {};
var location = window.location || {};
return {
url: location.pathname,
referrer: document.referrer,
screen: {
width: screen.width,
height: screen.height
},
window: {
width: window.innerWidth,
height: window.innerHeight
},
browser: {
name: nav.appName,
version: nav.appVersion,
cookie_enabled: nav.cookieEnabled,
do_not_track: nav.doNotTrack
},
platform: nav.platform
};
};
var _getEvent = function () {
var raw = null;
var args = Array.prototype.slice.call(arguments);
if (args.length === 0) {
throw new Error("No arguments!");
}
else if (args.length === 1) {
raw = args[0];
}
else {
// Handle a variadic overload,
// e.g. _rawLog("some text ", x, " ...", 1);
raw = args;
}
return raw;
};
// Single arg stops the compiler arity warning
var _rawLog = function (msg) {
var event = _getEvent.apply(this, arguments);
var data = { event: event };
// Add agent info if required
if (_pageInfo !== 'never') {
if (!_sentPageInfo || _pageInfo === 'per-entry') {
_sentPageInfo = true;
if (typeof event.screen === "undefined" &&
typeof event.browser === "undefined")
_rawLog(_agentInfo()).level('PAGE').send();
}
}
if (_traceCode) {
data.trace = _traceCode;
}
return { level: function (l) {
// Don't log PAGE events to console
// PAGE events are generated for the agentInfo function
if (_print && typeof console !== "undefined" && l !== 'PAGE') {
var serialized = null;
if (typeof XDomainRequest !== "undefined") {
// We're using IE8/9
serialized = data.trace + ' ' + data.event;
}
try {
console[l.toLowerCase()].call(console, (serialized || data));
}
catch (ex) {
// IE compat fix
console.log((serialized || data));
}
}
data.level = l;
return { send: function () {
var cache = [];
var serialized = JSON.stringify(data, function (key, value) {
if (typeof value === "undefined") {
return "undefined";
}
else if (typeof value === "object" && value !== null) {
if (_indexOf(cache, value) !== -1) {
// We've seen this object before;
// return a placeholder instead to prevent
// cycles
return "<?>";
}
cache.push(value);
}
return value;
});
if (_active) {
_backlog.push(serialized);
}
else {
_apiCall(_token, serialized);
}
} };
} };
};
/** @expose */
this.log = _rawLog;
var _apiCall = function (token, data) {
_active = true;
var request = _getAjaxObject();
if (_shouldCall) {
if (request.constructor === XMLHttpRequest) {
// Currently we don't support fine-grained error
// handling in older versions of IE
request.onreadystatechange = function () {
if (request.readyState === 4) {
// Handle any errors
if (request.status >= 400) {
console.error("Couldn't submit events.");
if (request.status === 410) {
// This API version has been phased out
console.warn("This version of le_js is no longer supported!");
}
}
else {
if (request.status === 301) {
// Server issued a deprecation warning
console.warn("This version of le_js is deprecated! Consider upgrading.");
}
if (_backlog.length > 0) {
// Submit the next event in the backlog
_apiCall(token, _backlog.shift());
}
else {
_active = false;
}
}
}
};
}
else {
request.onload = function () {
if (_backlog.length > 0) {
// Submit the next event in the backlog
_apiCall(token, _backlog.shift());
}
else {
_active = false;
}
};
}
request.open("POST", _endpoint, true);
if (request.constructor === XMLHttpRequest) {
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.setRequestHeader('Content-type', 'application/json');
}
if (request.overrideMimeType) {
request.overrideMimeType('text');
}
request.send(data);
}
};
}
/**
* A single log object
* @constructor
* @param {Object} options
*/
function Logger(options) {
var logger;
// Default values
var dict = {
ssl: true,
catchall: false,
trace: true,
page_info: 'never',
print: false,
endpoint: null,
token: null
};
if (typeof options === "object")
for (var k in options)
dict[k] = options[k];
else
throw new Error("Invalid parameters for createLogStream()");
if (dict.token === null) {
throw new Error("Token not present.");
}
else {
logger = new LogStream(dict);
}
var _log = function (msg) {
if (logger) {
return logger.log.apply(this, arguments);
}
else
throw new Error("You must call LE.init(...) first.");
};
// The public interface
return {
log: function () {
_log.apply(this, arguments).level('LOG').send();
},
warn: function () {
_log.apply(this, arguments).level('WARN').send();
},
error: function () {
_log.apply(this, arguments).level('ERROR').send();
},
info: function () {
_log.apply(this, arguments).level('INFO').send();
}
};
}
// Array of Logger elements
var loggers = {};
var _getLogger = function (name) {
if (!loggers.hasOwnProperty(name))
throw new Error("Invalid name for logStream");
return loggers[name];
};
var _createLogStream = function (options) {
if (typeof options.name !== "string")
throw new Error("Name not present.");
else if (loggers.hasOwnProperty(options.name))
throw new Error("A logger with that name already exists!");
loggers[options.name] = Logger(options);
return true;
};
var _deprecatedInit = function (options) {
var dict = {
name: "default"
};
if (typeof options === "object")
for (var k in options)
dict[k] = options[k];
else if (typeof options === "string")
dict.token = options;
else
throw new Error("Invalid parameters for init()");
return _createLogStream(dict);
};
var _destroyLogStream = function (name) {
if (typeof name === 'undefined') {
name = 'default';
}
delete loggers[name];
};
// The public interface
return {
init: _deprecatedInit,
createLogStream: _createLogStream,
to: _getLogger,
destroy: _destroyLogStream,
log: function () {
for (var k in loggers)
loggers[k].log.apply(this, arguments);
},
warn: function () {
for (var k in loggers)
loggers[k].warn.apply(this, arguments);
},
error: function () {
for (var k in loggers)
loggers[k].error.apply(this, arguments);
},
info: function () {
for (var k in loggers)
loggers[k].info.apply(this, arguments);
}
};
};
var LE$1 = factory((undefined || (typeof window == "undefined" ? global : window)));
var extend$1 = require("extend");
var LE = null;
var leInited = false;
var buildLE = function (config) {
if (!leInited) {
if (!config.logEntriesBrowserAppToken) {
var emptyFunction = function () { };
LE = {
trace: emptyFunction,
debug: emptyFunction,
log: emptyFunction,
info: emptyFunction,
warn: emptyFunction,
error: emptyFunction
};
console.log("Browser Logging is disabled!");
}
else {
LE = LE$1;
console.log("Browser logging enabled: " + config.logEntriesBrowserAppToken);
LE.init({ token: config.logEntriesBrowserAppToken,
catchall: true,
trace: true,
page_info: "per-page",
print: false
});
}
}
leInited = true;
};
var LogSink = /** @class */ (function () {
function LogSink(config) {
buildLE(config);
}
LogSink.prototype._removeCommonProps = function (data) {
var consoleData = extend$1(true, {}, data);
delete consoleData.hostname;
delete consoleData.level;
delete consoleData._level;
delete consoleData.requestId;
delete consoleData.app;
delete consoleData.userUniqueId;
return consoleData;
};
LogSink.prototype.trace = function (obj) {
LE.log(obj);
};
LogSink.prototype.debug = function (obj) {
LE.log(obj);
};
LogSink.prototype.info = function (obj) {
LE.log(obj);
};
LogSink.prototype.warn = function (obj) {
LE.log(obj);
};
LogSink.prototype.error = function (obj) {
console.error(this._removeCommonProps(obj));
LE.log(obj);
};
LogSink.prototype.push = function (obj) {
if (obj.level >= 50) {
this.error(obj);
}
else if (obj.level >= 40) {
this.warn(obj);
}
else if (obj.level >= 30) {
this.info(obj);
}
else if (obj.level >= 20) {
this.debug(obj);
}
else {
this.trace(obj);
}
};
return LogSink;
}());
var extend$2 = require("extend");
var segmentInited = false;
var options = function () {
var isAdminRoute = window.location.pathname.indexOf("/edit") !== -1;
return {
integrations: {
Chameleon: isAdminRoute,
Intercom: isAdminRoute
}
};
};
var AnalyticsSink = /** @class */ (function () {
function AnalyticsSink(config$$1) {
this.buildSegment(config$$1);
}
AnalyticsSink.prototype.buildSegment = function (config$$1) {
if (!segmentInited) {
var segmentWriteKey = config$$1.segmentWriteKey, defineSegment;
// https://segment.com/docs/sources/website/analytics.js/quickstart/
defineSegment = function (writeKey) {
// Create a queue, but don't obliterate an existing one!
var analytics = globalObj.analytics = globalObj.analytics || [];
// If the real analytics.js is already on the page return.
if (analytics.initialize)
return;
// If the snippet was invoked already show an error.
if (analytics.invoked) {
if (globalObj.console && console.error) {
console.error('Segment snippet included twice.');
}
return;
}
// Invoked flag, to make sure the snippet
// is never invoked twice.
analytics.invoked = true;
// A list of the methods in Analytics.js to stub.
analytics.methods = [
'trackSubmit',
'trackClick',
'trackLink',
'trackForm',
'pageview',
'identify',
'reset',
'group',
'track',
'ready',
'alias',
'debug',
'page',
'once',
'off',
'on'
];
// Define a factory to create stubs. These are placeholders
// for methods in Analytics.js so that you never have to wait
// for it to load to actually record data. The `method` is
// stored as the first argument, so we can replay the data.
analytics.factory = function (method) {
return function () {
var args = Array.prototype.slice.call(arguments);
args.unshift(method);
analytics.push(args);
return analytics;
};
};
// For each of our methods, generate a queueing stub.
for (var i = 0; i < analytics.methods.length; i++) {
var key = analytics.methods[i];
analytics[key] = analytics.factory(key);
}
// Define a method to load Analytics.js from our CDN,
// and that will be sure to only ever load it once.
analytics.load = function (key, loadOptions) {
// Create an async script element based on your key.
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = ('https:' === document.location.protocol
? 'https://' : 'http://')
+ 'cdn.segment.com/analytics.js/v1/'
+ key + '/analytics.min.js';
// Insert our script next to the first script element.
var first = document.getElementsByTagName('script')[0];
first.parentNode.insertBefore(script, first);
analytics._loadOptions = loadOptions;
};
// Add a version to keep track of what's in the wild.
analytics.SNIPPET_VERSION = '4.1.0';
// Load Analytics.js with your key, which will automatically
// load the tools you've enabled for your account. Boosh!
try {
analytics.load(writeKey, options());
}
catch (err) {
if (globalObj.console && console.error) {
console.error('Error loading segment script');
}
}
// Make the first page call to load the integrations. If
// you'd like to manually name or tag the page, edit or
// move this call however you'd like.
analytics.page();
};
defineSegment(segmentWriteKey);
segmentInited = true;
}
};
AnalyticsSink.prototype._segment = function (method) {
var fields = [];
for (var _i = 1; _i < arguments.length; _i++) {
fields[_i - 1] = arguments[_i];
}
return globalObj.analytics[method].apply(globalObj.analytics, fields);
};
AnalyticsSink.prototype.identify = function (userId, profile) {
var This = this;
//This._ga("set", "&uid", userId);
var properties;
if (profile) {
properties = __assign({ email: profile.email, emailVerified: profile.email_verified, createdAt: profile.created_at, lastLoginTime: profile.lastLoginTime || profile.last_login, name: profile.name, lastName: profile.family_name, firstName: profile.given_name, nickname: profile.nickname, locale: profile.locale, avatar: profile.picture, devices: profile.devices, gender: profile.gender, clientId: profile.clientID, globalClientId: profile.global_client_id }, options());
}
if (globalObj.Appcues) {
globalObj.Appcues.identify(userId, properties);
}
This._segment("identify", userId, properties, function () {
return Promise.resolve();
});
};
AnalyticsSink.prototype.dimension = function (index, value) {
// Not used with Segment, bc dimension is set using identify
// This._ga("set", "dimension" + index, value);
return Promise.resolve();
};
AnalyticsSink.prototype.event = function (category, action, label, value, extraInfo, eventId) {
var This = this;
return new Promise(function (resolve) {
//This._ga("send", "event", {
// "eventCategory": category,
// "eventAction": action,
// "eventLabel": label || "",
// "eventValue": value || 0 // redundant if value already === 0 but oh well
//});
var properties = extend$2({}, extraInfo, { category: category, label: label, value: value, eventId: eventId }, options());
This._segment("track", action, properties, function () {
//window.alert("event: action: " + action + "; category:" + category);
return resolve();
});
});
};
AnalyticsSink.prototype.page = function (category, name, route, referrer, eventId) {
var This = this;
return new Promise(function (resolve) {
var data = {
page: route,
title: category,
referrer: null,
eventId: null
};
if (referrer) {
data.referrer = referrer;
}
if (typeof name === "string" && name.trim().length > 0) {
data.title += " - " + name;
}
if (eventId) {
data.eventId = eventId;
}
//This._ga("set", data);
//This._ga("send", "pageview");
//not passing any properties at this time
This._segment("page", data, options(), function () {
return resolve();
});
});
};
AnalyticsSink.prototype.exception = function (description, fatal) { return Promise.resolve(); };
AnalyticsSink.prototype.link = function (linkElementId, category, action, label, value, eventId) { return Promise.resolve(); };
AnalyticsSink.prototype.push = function (obj) {
var This = this;
if (obj.type === "identify") {
return This.identify(obj.userId, obj.profile);
}
else if (obj.type === "setEvent") {
return This.dimension(1, obj.eventId);
}
else if (obj.type === "clearEvent") {
return This.dimension(1, null);
}
else if (obj.type === "event") {
return This.event(obj.category, obj.action, obj.label, obj.value, obj.extraInfo, obj.eventId);
}
else if (obj.type === "page") {