fair-analytics-client-api
Version:
The Fair Analytics client API
248 lines (195 loc) • 6.52 kB
JavaScript
var index = typeof fetch=='function' ? fetch : function(url, options) {
options = options || {};
return new Promise( function (resolve, reject) {
var request = new XMLHttpRequest();
request.open(options.method || 'get', url);
for (var i in options.headers) {
request.setRequestHeader(i, options.headers[i]);
}
request.withCredentials = options.credentials=='include';
request.onload = function () {
resolve(response());
};
request.onerror = reject;
request.send(options.body);
function response() {
var keys = [],
all = [],
headers = {},
header;
request.getAllResponseHeaders().replace(/^(.*?):\s*([\s\S]*?)$/gm, function (m, key, value) {
keys.push(key = key.toLowerCase());
all.push([key, value]);
header = headers[key];
headers[key] = header ? (header + "," + value) : value;
});
return {
ok: (request.status/200|0) == 1, // 200-399
status: request.status,
statusText: request.statusText,
url: request.responseURL,
clone: response,
text: function () { return Promise.resolve(request.responseText); },
json: function () { return Promise.resolve(request.responseText).then(JSON.parse); },
xml: function () { return Promise.resolve(request.responseXML); },
blob: function () { return Promise.resolve(new Blob([request.response])); },
headers: {
keys: function () { return keys; },
entries: function () { return all; },
get: function (n) { return headers[n.toLowerCase()]; },
has: function (n) { return n.toLowerCase() in headers; }
}
};
}
});
};
var unfetch_es = Object.freeze({
default: index
});
var require$$0 = ( unfetch_es && index ) || unfetch_es;
var browser = window.fetch = require$$0;
var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var browserCuid = createCommonjsModule(function (module) {
/**
* cuid.js
* Collision-resistant UID generator for browsers and node.
* Sequential for fast db lookups and recency sorting.
* Safe for element IDs and server-side lookups.
*
* Extracted from CLCTR
*
* Copyright (c) Eric Elliott 2012
* MIT License
*/
/*global window, navigator, document, require, process, module */
(function (app) {
'use strict';
var namespace = 'cuid',
c = 0,
blockSize = 4,
base = 36,
discreteValues = Math.pow(base, blockSize),
pad = function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
},
randomBlock = function randomBlock() {
return pad((Math.random() *
discreteValues << 0)
.toString(base), blockSize);
},
safeCounter = function () {
c = (c < discreteValues) ? c : 0;
c++; // this is not subliminal
return c - 1;
},
api = function cuid() {
// Starting with a lowercase letter makes
// it HTML element ID friendly.
var letter = 'c', // hard-coded allows for sequential access
// timestamp
// warning: this exposes the exact date and time
// that the uid was created.
timestamp = (new Date().getTime()).toString(base),
// Prevent same-machine collisions.
counter,
// A few chars to generate distinct ids for different
// clients (so different computers are far less
// likely to generate the same id)
fingerprint = api.fingerprint(),
// Grab some more chars from Math.random()
random = randomBlock() + randomBlock();
counter = pad(safeCounter().toString(base), blockSize);
return (letter + timestamp + counter + fingerprint + random);
};
api.slug = function slug() {
var date = new Date().getTime().toString(36),
counter,
print = api.fingerprint().slice(0,1) +
api.fingerprint().slice(-1),
random = randomBlock().slice(-2);
counter = safeCounter().toString(36).slice(-4);
return date.slice(-2) +
counter + print + random;
};
api.globalCount = function globalCount() {
// We want to cache the results of this
var cache = (function calc() {
var i,
count = 0;
for (i in window) {
count++;
}
return count;
}());
api.globalCount = function () { return cache; };
return cache;
};
api.fingerprint = function browserPrint() {
return pad((navigator.mimeTypes.length +
navigator.userAgent.length).toString(36) +
api.globalCount().toString(36), 4);
};
// don't change anything from here down.
if (app.register) {
app.register(namespace, api);
} else {
module.exports = api;
}
}(commonjsGlobal.applitude || commonjsGlobal));
});
function checkStatus(res) {
if (res.ok) {
return res;
} else {
var err = new Error(res.statusText);
err.response = res;
return Promise.reject(err);
}
}
function fairAnalytics() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
url = _ref.url;
if (!url) {
throw new Error('You must provide the "url" of your Fair Analytics instance');
}
var anonymousSessionId = 'NA';
var localStorageKey = '__fa__';
try {
var faConf = window.localStorage.getItem(localStorageKey);
if (faConf && faConf.anonymousSessionId) {
anonymousSessionId = faConf.anonymousSessionId;
} else {
try {
var _faConf = {
anonymousSessionId: browserCuid()
};
window.localStorage.setItem(localStorageKey, _faConf);
anonymousSessionId = _faConf.anonymousSessionId;
} catch (e) {
console.warn('Error while setting anonymousSessionId "NA" will be used', e);
}
}
} catch (e) {
console.warn('Error while setting anonymousSessionId, "NA" will be used', e);
}
var send = function send() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (!opts.event) {
return Promise.reject(new Error('You must provide the "event" parameter'));
}
opts.anonymousSessionId = anonymousSessionId;
return browser(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(opts)
}).then(checkStatus);
};
return { send: send };
}
module.exports = fairAnalytics;