@ninetailed/experience.js 2.0.0-beta.2 → 2.0.0-beta.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.esm.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import get$2 from 'lodash/get';
2
2
  import unionBy from 'lodash/unionBy';
3
3
  import { buildEmptyCache, buildTrackEvent, buildIdentifyEvent, buildPageEvent } from '@ninetailed/experience.js-shared';
4
+ import * as loglevel from 'loglevel';
4
5
  import Analytics from 'analytics';
5
6
  import flatten from 'lodash/flatten';
6
7
  import find from 'lodash/find';
7
8
  import includes from 'lodash/includes';
8
9
  import pickBy from 'lodash/pickBy';
10
+ import { murmur3 } from 'murmurhash-js';
9
11
 
10
12
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
11
13
 
@@ -177,9 +179,9 @@ var engineUserAgent = getBuiltIn$6('navigator', 'userAgent') || '';
177
179
  var global$D = global$H;
178
180
  var userAgent$3 = engineUserAgent;
179
181
 
180
- var process$4 = global$D.process;
182
+ var process$3 = global$D.process;
181
183
  var Deno = global$D.Deno;
182
- var versions = process$4 && process$4.versions || Deno && Deno.version;
184
+ var versions = process$3 && process$3.versions || Deno && Deno.version;
183
185
  var v8 = versions && versions.v8;
184
186
  var match, version;
185
187
 
@@ -883,14 +885,14 @@ var isCallable$a = isCallable$j;
883
885
  var replacement = /#|\.prototype\./;
884
886
 
885
887
  var isForced$2 = function (feature, detection) {
886
- var value = data[normalize(feature)];
888
+ var value = data[normalize$1(feature)];
887
889
  return value == POLYFILL ? true
888
890
  : value == NATIVE ? false
889
891
  : isCallable$a(detection) ? fails$a(detection)
890
892
  : !!detection;
891
893
  };
892
894
 
893
- var normalize = isForced$2.normalize = function (string) {
895
+ var normalize$1 = isForced$2.normalize = function (string) {
894
896
  return String(string).replace(replacement, '.').toLowerCase();
895
897
  };
896
898
 
@@ -1405,7 +1407,7 @@ var IS_NODE$2 = engineIsNode;
1405
1407
 
1406
1408
  var set$1 = global$d.setImmediate;
1407
1409
  var clear = global$d.clearImmediate;
1408
- var process$3 = global$d.process;
1410
+ var process$2 = global$d.process;
1409
1411
  var Dispatch = global$d.Dispatch;
1410
1412
  var Function$1 = global$d.Function;
1411
1413
  var MessageChannel = global$d.MessageChannel;
@@ -1461,7 +1463,7 @@ if (!set$1 || !clear) {
1461
1463
  // Node.js 0.8-
1462
1464
  if (IS_NODE$2) {
1463
1465
  defer = function (id) {
1464
- process$3.nextTick(runner(id));
1466
+ process$2.nextTick(runner(id));
1465
1467
  };
1466
1468
  // Sphere (JS game engine) Dispatch API
1467
1469
  } else if (Dispatch && Dispatch.now) {
@@ -1527,7 +1529,7 @@ var IS_NODE$1 = engineIsNode;
1527
1529
 
1528
1530
  var MutationObserver = global$b.MutationObserver || global$b.WebKitMutationObserver;
1529
1531
  var document$2 = global$b.document;
1530
- var process$2 = global$b.process;
1532
+ var process$1 = global$b.process;
1531
1533
  var Promise$1 = global$b.Promise;
1532
1534
  // Node.js 11 shows ExperimentalWarning on getting `queueMicrotask`
1533
1535
  var queueMicrotaskDescriptor = getOwnPropertyDescriptor$1(global$b, 'queueMicrotask');
@@ -1539,7 +1541,7 @@ var flush, head, last, notify$1, toggle, node, promise, then;
1539
1541
  if (!queueMicrotask) {
1540
1542
  flush = function () {
1541
1543
  var parent, fn;
1542
- if (IS_NODE$1 && (parent = process$2.domain)) parent.exit();
1544
+ if (IS_NODE$1 && (parent = process$1.domain)) parent.exit();
1543
1545
  while (head) {
1544
1546
  fn = head.fn;
1545
1547
  head = head.next;
@@ -1576,7 +1578,7 @@ if (!queueMicrotask) {
1576
1578
  // Node.js without promises
1577
1579
  } else if (IS_NODE$1) {
1578
1580
  notify$1 = function () {
1579
- process$2.nextTick(flush);
1581
+ process$1.nextTick(flush);
1580
1582
  };
1581
1583
  // for other environments - macrotask based on:
1582
1584
  // - setImmediate
@@ -1722,7 +1724,7 @@ var PromiseConstructor = NativePromise;
1722
1724
  var PromisePrototype = NativePromisePrototype;
1723
1725
  var TypeError$3 = global$9.TypeError;
1724
1726
  var document$1 = global$9.document;
1725
- var process$1 = global$9.process;
1727
+ var process = global$9.process;
1726
1728
  var newPromiseCapability = newPromiseCapabilityModule.f;
1727
1729
  var newGenericPromiseCapability = newPromiseCapability;
1728
1730
 
@@ -1844,7 +1846,7 @@ var onUnhandled = function (state) {
1844
1846
  if (IS_UNHANDLED) {
1845
1847
  result = perform(function () {
1846
1848
  if (IS_NODE) {
1847
- process$1.emit('unhandledRejection', value, promise);
1849
+ process.emit('unhandledRejection', value, promise);
1848
1850
  } else dispatchEvent(UNHANDLED_REJECTION, promise, value);
1849
1851
  });
1850
1852
  // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
@@ -1862,7 +1864,7 @@ var onHandleUnhandled = function (state) {
1862
1864
  call$5(task, global$9, function () {
1863
1865
  var promise = state.facade;
1864
1866
  if (IS_NODE) {
1865
- process$1.emit('rejectionHandled', promise);
1867
+ process.emit('rejectionHandled', promise);
1866
1868
  } else dispatchEvent(REJECTION_HANDLED, promise, state.value);
1867
1869
  });
1868
1870
  };
@@ -1949,7 +1951,7 @@ if (FORCED) {
1949
1951
  state.parent = true;
1950
1952
  reaction.ok = isCallable$5(onFulfilled) ? onFulfilled : true;
1951
1953
  reaction.fail = isCallable$5(onRejected) && onRejected;
1952
- reaction.domain = IS_NODE ? process$1.domain : undefined;
1954
+ reaction.domain = IS_NODE ? process.domain : undefined;
1953
1955
  if (state.state == PENDING) state.reactions.add(reaction);
1954
1956
  else microtask(function () {
1955
1957
  callReaction(reaction, state);
@@ -2220,724 +2222,14 @@ const buildClientNinetailedRequestContext = () => ({
2220
2222
  }
2221
2223
  });
2222
2224
 
2223
- var browser = {exports: {}};
2224
-
2225
- /**
2226
- * Helpers.
2227
- */
2228
-
2229
- var s = 1000;
2230
- var m = s * 60;
2231
- var h = m * 60;
2232
- var d = h * 24;
2233
- var w = d * 7;
2234
- var y = d * 365.25;
2235
-
2236
- /**
2237
- * Parse or format the given `val`.
2238
- *
2239
- * Options:
2240
- *
2241
- * - `long` verbose formatting [false]
2242
- *
2243
- * @param {String|Number} val
2244
- * @param {Object} [options]
2245
- * @throws {Error} throw an error if val is not a non-empty string or a number
2246
- * @return {String|Number}
2247
- * @api public
2248
- */
2249
-
2250
- var ms = function(val, options) {
2251
- options = options || {};
2252
- var type = typeof val;
2253
- if (type === 'string' && val.length > 0) {
2254
- return parse(val);
2255
- } else if (type === 'number' && isFinite(val)) {
2256
- return options.long ? fmtLong(val) : fmtShort(val);
2257
- }
2258
- throw new Error(
2259
- 'val is not a non-empty string or a valid number. val=' +
2260
- JSON.stringify(val)
2261
- );
2262
- };
2263
-
2264
- /**
2265
- * Parse the given `str` and return milliseconds.
2266
- *
2267
- * @param {String} str
2268
- * @return {Number}
2269
- * @api private
2270
- */
2271
-
2272
- function parse(str) {
2273
- str = String(str);
2274
- if (str.length > 100) {
2275
- return;
2276
- }
2277
- var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
2278
- str
2279
- );
2280
- if (!match) {
2281
- return;
2282
- }
2283
- var n = parseFloat(match[1]);
2284
- var type = (match[2] || 'ms').toLowerCase();
2285
- switch (type) {
2286
- case 'years':
2287
- case 'year':
2288
- case 'yrs':
2289
- case 'yr':
2290
- case 'y':
2291
- return n * y;
2292
- case 'weeks':
2293
- case 'week':
2294
- case 'w':
2295
- return n * w;
2296
- case 'days':
2297
- case 'day':
2298
- case 'd':
2299
- return n * d;
2300
- case 'hours':
2301
- case 'hour':
2302
- case 'hrs':
2303
- case 'hr':
2304
- case 'h':
2305
- return n * h;
2306
- case 'minutes':
2307
- case 'minute':
2308
- case 'mins':
2309
- case 'min':
2310
- case 'm':
2311
- return n * m;
2312
- case 'seconds':
2313
- case 'second':
2314
- case 'secs':
2315
- case 'sec':
2316
- case 's':
2317
- return n * s;
2318
- case 'milliseconds':
2319
- case 'millisecond':
2320
- case 'msecs':
2321
- case 'msec':
2322
- case 'ms':
2323
- return n;
2324
- default:
2325
- return undefined;
2326
- }
2327
- }
2328
-
2329
- /**
2330
- * Short format for `ms`.
2331
- *
2332
- * @param {Number} ms
2333
- * @return {String}
2334
- * @api private
2335
- */
2336
-
2337
- function fmtShort(ms) {
2338
- var msAbs = Math.abs(ms);
2339
- if (msAbs >= d) {
2340
- return Math.round(ms / d) + 'd';
2341
- }
2342
- if (msAbs >= h) {
2343
- return Math.round(ms / h) + 'h';
2344
- }
2345
- if (msAbs >= m) {
2346
- return Math.round(ms / m) + 'm';
2347
- }
2348
- if (msAbs >= s) {
2349
- return Math.round(ms / s) + 's';
2350
- }
2351
- return ms + 'ms';
2352
- }
2353
-
2354
- /**
2355
- * Long format for `ms`.
2356
- *
2357
- * @param {Number} ms
2358
- * @return {String}
2359
- * @api private
2360
- */
2361
-
2362
- function fmtLong(ms) {
2363
- var msAbs = Math.abs(ms);
2364
- if (msAbs >= d) {
2365
- return plural(ms, msAbs, d, 'day');
2366
- }
2367
- if (msAbs >= h) {
2368
- return plural(ms, msAbs, h, 'hour');
2369
- }
2370
- if (msAbs >= m) {
2371
- return plural(ms, msAbs, m, 'minute');
2372
- }
2373
- if (msAbs >= s) {
2374
- return plural(ms, msAbs, s, 'second');
2375
- }
2376
- return ms + ' ms';
2377
- }
2378
-
2379
- /**
2380
- * Pluralization helper.
2381
- */
2382
-
2383
- function plural(ms, msAbs, n, name) {
2384
- var isPlural = msAbs >= n * 1.5;
2385
- return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
2386
- }
2387
-
2388
- /**
2389
- * This is the common logic for both the Node.js and web browser
2390
- * implementations of `debug()`.
2391
- */
2392
-
2393
- function setup(env) {
2394
- createDebug.debug = createDebug;
2395
- createDebug.default = createDebug;
2396
- createDebug.coerce = coerce;
2397
- createDebug.disable = disable;
2398
- createDebug.enable = enable;
2399
- createDebug.enabled = enabled;
2400
- createDebug.humanize = ms;
2401
- createDebug.destroy = destroy;
2402
-
2403
- Object.keys(env).forEach(key => {
2404
- createDebug[key] = env[key];
2405
- });
2406
-
2407
- /**
2408
- * The currently active debug mode names, and names to skip.
2409
- */
2410
-
2411
- createDebug.names = [];
2412
- createDebug.skips = [];
2413
-
2414
- /**
2415
- * Map of special "%n" handling functions, for the debug "format" argument.
2416
- *
2417
- * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
2418
- */
2419
- createDebug.formatters = {};
2420
-
2421
- /**
2422
- * Selects a color for a debug namespace
2423
- * @param {String} namespace The namespace string for the debug instance to be colored
2424
- * @return {Number|String} An ANSI color code for the given namespace
2425
- * @api private
2426
- */
2427
- function selectColor(namespace) {
2428
- let hash = 0;
2429
-
2430
- for (let i = 0; i < namespace.length; i++) {
2431
- hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
2432
- hash |= 0; // Convert to 32bit integer
2433
- }
2434
-
2435
- return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
2436
- }
2437
- createDebug.selectColor = selectColor;
2438
-
2439
- /**
2440
- * Create a debugger with the given `namespace`.
2441
- *
2442
- * @param {String} namespace
2443
- * @return {Function}
2444
- * @api public
2445
- */
2446
- function createDebug(namespace) {
2447
- let prevTime;
2448
- let enableOverride = null;
2449
- let namespacesCache;
2450
- let enabledCache;
2451
-
2452
- function debug(...args) {
2453
- // Disabled?
2454
- if (!debug.enabled) {
2455
- return;
2456
- }
2457
-
2458
- const self = debug;
2459
-
2460
- // Set `diff` timestamp
2461
- const curr = Number(new Date());
2462
- const ms = curr - (prevTime || curr);
2463
- self.diff = ms;
2464
- self.prev = prevTime;
2465
- self.curr = curr;
2466
- prevTime = curr;
2467
-
2468
- args[0] = createDebug.coerce(args[0]);
2469
-
2470
- if (typeof args[0] !== 'string') {
2471
- // Anything else let's inspect with %O
2472
- args.unshift('%O');
2473
- }
2474
-
2475
- // Apply any `formatters` transformations
2476
- let index = 0;
2477
- args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
2478
- // If we encounter an escaped % then don't increase the array index
2479
- if (match === '%%') {
2480
- return '%';
2481
- }
2482
- index++;
2483
- const formatter = createDebug.formatters[format];
2484
- if (typeof formatter === 'function') {
2485
- const val = args[index];
2486
- match = formatter.call(self, val);
2487
-
2488
- // Now we need to remove `args[index]` since it's inlined in the `format`
2489
- args.splice(index, 1);
2490
- index--;
2491
- }
2492
- return match;
2493
- });
2494
-
2495
- // Apply env-specific formatting (colors, etc.)
2496
- createDebug.formatArgs.call(self, args);
2497
-
2498
- const logFn = self.log || createDebug.log;
2499
- logFn.apply(self, args);
2500
- }
2501
-
2502
- debug.namespace = namespace;
2503
- debug.useColors = createDebug.useColors();
2504
- debug.color = createDebug.selectColor(namespace);
2505
- debug.extend = extend;
2506
- debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
2507
-
2508
- Object.defineProperty(debug, 'enabled', {
2509
- enumerable: true,
2510
- configurable: false,
2511
- get: () => {
2512
- if (enableOverride !== null) {
2513
- return enableOverride;
2514
- }
2515
- if (namespacesCache !== createDebug.namespaces) {
2516
- namespacesCache = createDebug.namespaces;
2517
- enabledCache = createDebug.enabled(namespace);
2518
- }
2519
-
2520
- return enabledCache;
2521
- },
2522
- set: v => {
2523
- enableOverride = v;
2524
- }
2525
- });
2526
-
2527
- // Env-specific initialization logic for debug instances
2528
- if (typeof createDebug.init === 'function') {
2529
- createDebug.init(debug);
2530
- }
2531
-
2532
- return debug;
2533
- }
2534
-
2535
- function extend(namespace, delimiter) {
2536
- const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
2537
- newDebug.log = this.log;
2538
- return newDebug;
2539
- }
2540
-
2541
- /**
2542
- * Enables a debug mode by namespaces. This can include modes
2543
- * separated by a colon and wildcards.
2544
- *
2545
- * @param {String} namespaces
2546
- * @api public
2547
- */
2548
- function enable(namespaces) {
2549
- createDebug.save(namespaces);
2550
- createDebug.namespaces = namespaces;
2551
-
2552
- createDebug.names = [];
2553
- createDebug.skips = [];
2554
-
2555
- let i;
2556
- const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
2557
- const len = split.length;
2558
-
2559
- for (i = 0; i < len; i++) {
2560
- if (!split[i]) {
2561
- // ignore empty strings
2562
- continue;
2563
- }
2564
-
2565
- namespaces = split[i].replace(/\*/g, '.*?');
2566
-
2567
- if (namespaces[0] === '-') {
2568
- createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
2569
- } else {
2570
- createDebug.names.push(new RegExp('^' + namespaces + '$'));
2571
- }
2572
- }
2573
- }
2574
-
2575
- /**
2576
- * Disable debug output.
2577
- *
2578
- * @return {String} namespaces
2579
- * @api public
2580
- */
2581
- function disable() {
2582
- const namespaces = [
2583
- ...createDebug.names.map(toNamespace),
2584
- ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
2585
- ].join(',');
2586
- createDebug.enable('');
2587
- return namespaces;
2588
- }
2589
-
2590
- /**
2591
- * Returns true if the given mode name is enabled, false otherwise.
2592
- *
2593
- * @param {String} name
2594
- * @return {Boolean}
2595
- * @api public
2596
- */
2597
- function enabled(name) {
2598
- if (name[name.length - 1] === '*') {
2599
- return true;
2600
- }
2601
-
2602
- let i;
2603
- let len;
2604
-
2605
- for (i = 0, len = createDebug.skips.length; i < len; i++) {
2606
- if (createDebug.skips[i].test(name)) {
2607
- return false;
2608
- }
2609
- }
2610
-
2611
- for (i = 0, len = createDebug.names.length; i < len; i++) {
2612
- if (createDebug.names[i].test(name)) {
2613
- return true;
2614
- }
2615
- }
2616
-
2617
- return false;
2618
- }
2619
-
2620
- /**
2621
- * Convert regexp to namespace
2622
- *
2623
- * @param {RegExp} regxep
2624
- * @return {String} namespace
2625
- * @api private
2626
- */
2627
- function toNamespace(regexp) {
2628
- return regexp.toString()
2629
- .substring(2, regexp.toString().length - 2)
2630
- .replace(/\.\*\?$/, '*');
2631
- }
2632
-
2633
- /**
2634
- * Coerce `val`.
2635
- *
2636
- * @param {Mixed} val
2637
- * @return {Mixed}
2638
- * @api private
2639
- */
2640
- function coerce(val) {
2641
- if (val instanceof Error) {
2642
- return val.stack || val.message;
2643
- }
2644
- return val;
2645
- }
2646
-
2647
- /**
2648
- * XXX DO NOT USE. This is a temporary stub function.
2649
- * XXX It WILL be removed in the next major release.
2650
- */
2651
- function destroy() {
2652
- console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
2653
- }
2654
-
2655
- createDebug.enable(createDebug.load());
2656
-
2657
- return createDebug;
2658
- }
2659
-
2660
- var common = setup;
2661
-
2662
- /* eslint-env browser */
2663
-
2664
- (function (module, exports) {
2665
- /**
2666
- * This is the web browser implementation of `debug()`.
2667
- */
2668
-
2669
- exports.formatArgs = formatArgs;
2670
- exports.save = save;
2671
- exports.load = load;
2672
- exports.useColors = useColors;
2673
- exports.storage = localstorage();
2674
- exports.destroy = (() => {
2675
- let warned = false;
2676
-
2677
- return () => {
2678
- if (!warned) {
2679
- warned = true;
2680
- console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
2681
- }
2682
- };
2683
- })();
2684
-
2685
- /**
2686
- * Colors.
2687
- */
2688
-
2689
- exports.colors = [
2690
- '#0000CC',
2691
- '#0000FF',
2692
- '#0033CC',
2693
- '#0033FF',
2694
- '#0066CC',
2695
- '#0066FF',
2696
- '#0099CC',
2697
- '#0099FF',
2698
- '#00CC00',
2699
- '#00CC33',
2700
- '#00CC66',
2701
- '#00CC99',
2702
- '#00CCCC',
2703
- '#00CCFF',
2704
- '#3300CC',
2705
- '#3300FF',
2706
- '#3333CC',
2707
- '#3333FF',
2708
- '#3366CC',
2709
- '#3366FF',
2710
- '#3399CC',
2711
- '#3399FF',
2712
- '#33CC00',
2713
- '#33CC33',
2714
- '#33CC66',
2715
- '#33CC99',
2716
- '#33CCCC',
2717
- '#33CCFF',
2718
- '#6600CC',
2719
- '#6600FF',
2720
- '#6633CC',
2721
- '#6633FF',
2722
- '#66CC00',
2723
- '#66CC33',
2724
- '#9900CC',
2725
- '#9900FF',
2726
- '#9933CC',
2727
- '#9933FF',
2728
- '#99CC00',
2729
- '#99CC33',
2730
- '#CC0000',
2731
- '#CC0033',
2732
- '#CC0066',
2733
- '#CC0099',
2734
- '#CC00CC',
2735
- '#CC00FF',
2736
- '#CC3300',
2737
- '#CC3333',
2738
- '#CC3366',
2739
- '#CC3399',
2740
- '#CC33CC',
2741
- '#CC33FF',
2742
- '#CC6600',
2743
- '#CC6633',
2744
- '#CC9900',
2745
- '#CC9933',
2746
- '#CCCC00',
2747
- '#CCCC33',
2748
- '#FF0000',
2749
- '#FF0033',
2750
- '#FF0066',
2751
- '#FF0099',
2752
- '#FF00CC',
2753
- '#FF00FF',
2754
- '#FF3300',
2755
- '#FF3333',
2756
- '#FF3366',
2757
- '#FF3399',
2758
- '#FF33CC',
2759
- '#FF33FF',
2760
- '#FF6600',
2761
- '#FF6633',
2762
- '#FF9900',
2763
- '#FF9933',
2764
- '#FFCC00',
2765
- '#FFCC33'
2766
- ];
2767
-
2768
- /**
2769
- * Currently only WebKit-based Web Inspectors, Firefox >= v31,
2770
- * and the Firebug extension (any Firefox version) are known
2771
- * to support "%c" CSS customizations.
2772
- *
2773
- * TODO: add a `localStorage` variable to explicitly enable/disable colors
2774
- */
2775
-
2776
- // eslint-disable-next-line complexity
2777
- function useColors() {
2778
- // NB: In an Electron preload script, document will be defined but not fully
2779
- // initialized. Since we know we're in Chrome, we'll just detect this case
2780
- // explicitly
2781
- if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
2782
- return true;
2783
- }
2784
-
2785
- // Internet Explorer and Edge do not support colors.
2786
- if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
2787
- return false;
2788
- }
2789
-
2790
- // Is webkit? http://stackoverflow.com/a/16459606/376773
2791
- // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
2792
- return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
2793
- // Is firebug? http://stackoverflow.com/a/398120/376773
2794
- (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
2795
- // Is firefox >= v31?
2796
- // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
2797
- (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
2798
- // Double check webkit in userAgent just in case we are in a worker
2799
- (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
2800
- }
2801
-
2802
- /**
2803
- * Colorize log arguments if enabled.
2804
- *
2805
- * @api public
2806
- */
2807
-
2808
- function formatArgs(args) {
2809
- args[0] = (this.useColors ? '%c' : '') +
2810
- this.namespace +
2811
- (this.useColors ? ' %c' : ' ') +
2812
- args[0] +
2813
- (this.useColors ? '%c ' : ' ') +
2814
- '+' + module.exports.humanize(this.diff);
2815
-
2816
- if (!this.useColors) {
2817
- return;
2818
- }
2819
-
2820
- const c = 'color: ' + this.color;
2821
- args.splice(1, 0, c, 'color: inherit');
2822
-
2823
- // The final "%c" is somewhat tricky, because there could be other
2824
- // arguments passed either before or after the %c, so we need to
2825
- // figure out the correct index to insert the CSS into
2826
- let index = 0;
2827
- let lastC = 0;
2828
- args[0].replace(/%[a-zA-Z%]/g, match => {
2829
- if (match === '%%') {
2830
- return;
2831
- }
2832
- index++;
2833
- if (match === '%c') {
2834
- // We only are interested in the *last* %c
2835
- // (the user may have provided their own)
2836
- lastC = index;
2837
- }
2838
- });
2839
-
2840
- args.splice(lastC, 0, c);
2841
- }
2842
-
2843
- /**
2844
- * Invokes `console.debug()` when available.
2845
- * No-op when `console.debug` is not a "function".
2846
- * If `console.debug` is not available, falls back
2847
- * to `console.log`.
2848
- *
2849
- * @api public
2850
- */
2851
- exports.log = console.debug || console.log || (() => {});
2852
-
2853
- /**
2854
- * Save `namespaces`.
2855
- *
2856
- * @param {String} namespaces
2857
- * @api private
2858
- */
2859
- function save(namespaces) {
2860
- try {
2861
- if (namespaces) {
2862
- exports.storage.setItem('debug', namespaces);
2863
- } else {
2864
- exports.storage.removeItem('debug');
2865
- }
2866
- } catch (error) {
2867
- // Swallow
2868
- // XXX (@Qix-) should we be logging these?
2869
- }
2870
- }
2871
-
2872
- /**
2873
- * Load `namespaces`.
2874
- *
2875
- * @return {String} returns the previously persisted debug modes
2876
- * @api private
2877
- */
2878
- function load() {
2879
- let r;
2880
- try {
2881
- r = exports.storage.getItem('debug');
2882
- } catch (error) {
2883
- // Swallow
2884
- // XXX (@Qix-) should we be logging these?
2885
- }
2886
-
2887
- // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
2888
- if (!r && typeof process !== 'undefined' && 'env' in process) {
2889
- r = process.env.DEBUG;
2890
- }
2891
-
2892
- return r;
2893
- }
2894
-
2895
- /**
2896
- * Localstorage attempts to return the localstorage.
2897
- *
2898
- * This is necessary because safari throws
2899
- * when a user disables cookies/localstorage
2900
- * and you attempt to access it.
2901
- *
2902
- * @return {LocalStorage}
2903
- * @api private
2904
- */
2905
-
2906
- function localstorage() {
2907
- try {
2908
- // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
2909
- // The Browser also has localStorage in the global context.
2910
- return localStorage;
2911
- } catch (error) {
2912
- // Swallow
2913
- // XXX (@Qix-) should we be logging these?
2914
- }
2915
- }
2916
-
2917
- module.exports = common(exports);
2918
-
2919
- const {formatters} = module.exports;
2920
-
2921
- /**
2922
- * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
2923
- */
2924
-
2925
- formatters.j = function (v) {
2926
- try {
2927
- return JSON.stringify(v);
2928
- } catch (error) {
2929
- return '[UnexpectedJSONParseError]: ' + error.message;
2930
- }
2931
- };
2932
- }(browser, browser.exports));
2933
-
2934
- var Debug = browser.exports;
2935
-
2936
- const log = Debug('ninetailed:experience-sdk');
2937
2225
  const enable = () => {
2938
- Debug.enable('ninetailed:experience-sdk');
2226
+ loglevel.enableAll();
2227
+ };
2228
+ const disable = () => {
2229
+ loglevel.disableAll();
2939
2230
  };
2940
- const disable = () => Debug.disable();
2231
+ const Logger = loglevel.getLogger('ninetailed:experience.js');
2232
+ const log = Logger.log;
2941
2233
 
2942
2234
  const BASE_URL = 'https://api.ninetailed.co';
2943
2235
 
@@ -4558,12 +3850,12 @@ const selectActiveExperiments = (experiments, profile) => {
4558
3850
  };
4559
3851
 
4560
3852
  /**
4561
- * We can use any personalization as eglible experience
3853
+ * We can use any personalization as eligible experience
4562
3854
  * When going for an experiment we can only select a active experiment when 1 or more experiments are active
4563
3855
  * If the profile is not in any active experiments, we can select any expermiment
4564
3856
  */
4565
3857
 
4566
- const selectEglibleExperiences = ({
3858
+ const selectEligibleExperiences = ({
4567
3859
  experiences,
4568
3860
  activeExperiments
4569
3861
  }) => {
@@ -4572,23 +3864,70 @@ const selectEglibleExperiences = ({
4572
3864
  }));
4573
3865
  };
4574
3866
 
3867
+ const LOWER_BOUND = 0;
3868
+ const UPPER_BOUND = 4294967295;
3869
+
3870
+ const normalize = (val, min, max) => (val - min) / (max - min);
3871
+
3872
+ const getRandom = text => {
3873
+ const hash = murmur3(text, 0);
3874
+ const random = normalize(hash, LOWER_BOUND, UPPER_BOUND);
3875
+ return random;
3876
+ };
3877
+
3878
+ const getTrafficRandom = (profile, experience) => getRandom(`traffic-${experience.id}-${profile.id}`);
3879
+ const getDistributionRandom = (profile, experience) => getRandom(`distribution-${experience.id}-${profile.id}`);
3880
+
3881
+ const isExperienceMatch = ({
3882
+ experience,
3883
+ activeExperiments,
3884
+ profile
3885
+ }) => {
3886
+ const trafficRandom = getTrafficRandom(profile, experience);
3887
+ log(`The traffic random factor for experience ${experience.id} is ${trafficRandom}. It's traffic allocation is set to ${experience.trafficAllocation}.`);
3888
+ const isInTrafficRange = experience.trafficAllocation > trafficRandom;
3889
+ const matchesAudience = !experience.audience || includes(profile.audiences, experience.audience.id);
3890
+ const hasActiveExperiment = !!find(activeExperiments, {
3891
+ id: experience.id
3892
+ });
3893
+ log(`Is the profile in traffic allocation range? ${isInTrafficRange ? 'yes' : 'no'}.\n
3894
+ Does the profile match the audience of the experience? ${matchesAudience ? 'yes' : 'no'}.\n
3895
+ Is there an active experiment for this profile? ${hasActiveExperiment ? 'yes' : 'no'}.`);
3896
+ return isInTrafficRange && (matchesAudience || // if the expriment is active already then it's selectible without further contraints to be fullfilled
3897
+ hasActiveExperiment);
3898
+ };
3899
+
4575
3900
  const selectExperience = ({
4576
3901
  experiences,
4577
3902
  activeExperiments,
4578
3903
  profile
4579
3904
  }) => {
4580
- const eglibleExperiences = selectEglibleExperiences({
3905
+ const eligibleExperiences = selectEligibleExperiences({
4581
3906
  experiences,
4582
3907
  activeExperiments
4583
3908
  });
4584
- const selectedExperience = eglibleExperiences.find(experience => // TODO check traffic allocation
4585
- includes(profile.audiences, experience.audience.id) || // if the expriment is active already then it's selectible without further contraints to be fullfilled
4586
- find(activeExperiments, {
4587
- id: experience.id
3909
+ const selectedExperience = eligibleExperiences.find(experience => isExperienceMatch({
3910
+ experience,
3911
+ activeExperiments,
3912
+ profile
4588
3913
  }));
4589
3914
  return selectedExperience;
4590
3915
  };
4591
3916
 
3917
+ const selectDistribution = ({
3918
+ experience,
3919
+ profile
3920
+ }) => {
3921
+ const distributionRandom = getDistributionRandom(profile, experience);
3922
+ log(`The distribution random factor for experience ${experience.id} is ${distributionRandom}. It's distribution is set to ${JSON.stringify(experience.distribution, null, 2)}.`);
3923
+ const distribution = find(experience.distribution, ({
3924
+ start,
3925
+ end
3926
+ }) => distributionRandom >= start && distributionRandom <= end // this overlaps on one value for each boundary but we just find the first match
3927
+ );
3928
+ return distribution;
3929
+ };
3930
+
4592
3931
  const selectVariant = ({
4593
3932
  baseline,
4594
3933
  experience,
@@ -4598,20 +3937,17 @@ const selectVariant = ({
4598
3937
 
4599
3938
  if (!variants.length) {
4600
3939
  return null;
4601
- } // Personalization
4602
-
3940
+ }
4603
3941
 
4604
3942
  if (experience.type === 'nt_personalization') {
4605
- // TODO check holdout
4606
3943
  // Personalization Expriences can have only one variant.
4607
3944
  return variants[0];
4608
- } // Experiment
4609
-
3945
+ }
4610
3946
 
4611
- const distribution = find(experience.distribution, ({
4612
- start,
4613
- end
4614
- }) => profile.random > start && profile.random < end);
3947
+ const distribution = selectDistribution({
3948
+ experience,
3949
+ profile
3950
+ });
4615
3951
 
4616
3952
  if (!distribution) {
4617
3953
  return null;
@@ -4640,4 +3976,4 @@ const selectVariant = ({
4640
3976
  return variant;
4641
3977
  };
4642
3978
 
4643
- export { NINETAILED_TRACKER_EVENTS, Ninetailed, PLUGIN_NAME, ninetailedPlugin, selectActiveExperiments, selectEglibleExperiences, selectExperience, selectBaselineWithVariants as selectExperienceBaselineWithVariants, selectVariant as selectExperienceVariant, selectVariants as selectExperienceVariants, selectHasVariants as selectHasExperienceVariants, selectVariant$1 as selectVariant };
3979
+ export { NINETAILED_TRACKER_EVENTS, Ninetailed, PLUGIN_NAME, isExperienceMatch, ninetailedPlugin, selectActiveExperiments, selectDistribution, selectEligibleExperiences, selectExperience, selectBaselineWithVariants as selectExperienceBaselineWithVariants, selectVariant as selectExperienceVariant, selectVariants as selectExperienceVariants, selectHasVariants as selectHasExperienceVariants, selectVariant$1 as selectVariant };