Skip to content
This repository was archived by the owner on Sep 3, 2022. It is now read-only.

Remove utils and @ndhoule/keys #194

Merged
merged 7 commits into from
Sep 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,25 @@
{
"extends": ["@segment/eslint-config/browser/legacy", "prettier"]
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint"
],
"extends": [
"@segment/eslint-config/browser/legacy",
"prettier",
"plugin:@typescript-eslint/recommended"
],
"rules": {
"no-use-before-define": "warn",
"no-var": "warn",
"prefer-const": "warn",
"prefer-rest-params": "warn",
"prefer-spread": "warn",
"strict": "warn",
"@typescript-eslint/adjacent-overload-signatures": "warn",
"@typescript-eslint/ban-ts-comment": "warn",
"@typescript-eslint/ban-types": "warn",
"@typescript-eslint/no-empty-function": "warn",
"@typescript-eslint/no-this-alias": "warn",
"@typescript-eslint/no-var-requires": "warn"
}
}
7 changes: 7 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
# 4.1.0 / 2020-09-14

- Replaces `utils/clone` with `lodash.deepclone`
- Replaces `utils/map` with `Array.prototype.map`
- Replaces `utils/each` with `Array.prototype.each`
- Removes the `utils` directory and tests

# 4.0.4 / 2020-09-11

- Change the arguments of the main methods to be optional in the typedef to match the documentation. (#203)
Expand Down
107 changes: 60 additions & 47 deletions lib/analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
SegmentIntegration
} from './types';

import cloneDeep from 'lodash.clonedeep'

var _analytics = global.analytics;

/*
Expand All @@ -27,18 +29,14 @@ var DestinationMiddlewareChain = require('./middleware')
var Page = require('segmentio-facade').Page;
var Track = require('segmentio-facade').Track;
var bindAll = require('bind-all');
var clone = require('./utils/clone');
var extend = require('extend');
var cookie = require('./cookie');
var metrics = require('./metrics');
var debug = require('debug');
var defaults = require('@ndhoule/defaults');
var each = require('./utils/each');
var foldl = require('@ndhoule/foldl');
var group = require('./group');
var is = require('is');
var isMeta = require('@segment/is-meta');
var keys = require('@ndhoule/keys');
var memory = require('./memory');
var nextTick = require('next-tick');
var normalize = require('./normalize');
Expand Down Expand Up @@ -69,8 +67,9 @@ function Analytics() {
this.log = debug('analytics.js');
bindAll(this);

var self = this;
this.on('initialize', function(settings, options) {

const self = this;
this.on('initialize', function(_, options) {
if (options.initialPageview) self.page();
self._parseQuery(window.location.search);
});
Expand Down Expand Up @@ -169,13 +168,16 @@ Analytics.prototype.init = Analytics.prototype.initialize = function(

// clean unknown integrations from settings
var self = this;
each(function(_opts: unknown, name: string | number) {
var Integration = self.Integrations[name];
if (!Integration) delete settings[name];
}, settings);
Object.keys(settings).forEach(key => {
var Integration = self.Integrations[key];
if (!Integration) delete settings[key];
});

// add integrations
each(function(opts: unknown, name: string | number) {
Object.keys(settings).forEach(key => {
const opts = settings[key]
const name = key

// Don't load disabled integrations
if (options.integrations) {
if (
Expand All @@ -186,13 +188,13 @@ Analytics.prototype.init = Analytics.prototype.initialize = function(
}
}

var Integration = self.Integrations[name];
var clonedOpts = {};
const Integration = self.Integrations[name];
const clonedOpts = {};
extend(true, clonedOpts, opts); // deep clone opts
var integration = new Integration(clonedOpts);
const integration = new Integration(clonedOpts);
self.log('initialize %o - %o', name, opts);
self.add(integration);
}, settings);
});

var integrations = this._integrations;

Expand All @@ -202,7 +204,7 @@ Analytics.prototype.init = Analytics.prototype.initialize = function(

// make ready callback
var readyCallCount = 0;
var integrationCount = keys(integrations).length;
var integrationCount = Object.keys(integrations).length;
var ready = function() {
readyCallCount++;
if (readyCallCount >= integrationCount) {
Expand All @@ -219,14 +221,15 @@ Analytics.prototype.init = Analytics.prototype.initialize = function(
// initialize integrations, passing ready
// create a list of any integrations that did not initialize - this will be passed with all events for replay support:
this.failedInitializations = [];
var initialPageSkipped = false;
each(function(integration) {
let initialPageSkipped = false;
Object.keys(integrations).forEach(key => {
const integration = integrations[key]
if (
options.initialPageview &&
integration.options.initialPageview === false
) {
// We've assumed one initial pageview, so make sure we don't count the first page call.
var page = integration.page;
let page = integration.page;
integration.page = function() {
if (initialPageSkipped) {
return page.apply(this, arguments);
Expand All @@ -246,7 +249,7 @@ Analytics.prototype.init = Analytics.prototype.initialize = function(
});
integration.initialize();
} catch (e) {
var integrationName = integration.name;
let integrationName = integration.name;
metrics.increment('analytics_js.integration.invoke.error', {
method: 'initialize',
integration_name: integration.name
Expand All @@ -257,7 +260,7 @@ Analytics.prototype.init = Analytics.prototype.initialize = function(

integration.ready();
}
}, integrations);
});

// backwards compat with angular plugin and used for init logic checks
this.initialized = true;
Expand Down Expand Up @@ -466,37 +469,44 @@ Analytics.prototype.track = function(
*/

Analytics.prototype.trackClick = Analytics.prototype.trackLink = function(
links: Element | Array<unknown>,
links: Element | Array<Element> | JQuery,
event: any,
properties?: any
): SegmentAnalytics {
let elements: Array<Element> = []
if (!links) return this;
// always arrays, handles jquery
if (type(links) === 'element') links = [links];
if (links instanceof Element) {
elements = [links]
} else if ("toArray" in links) {
elements = links.toArray()
} else {
elements = links as Array<Element>
}

var self = this;
each(function(el) {
elements.forEach(el => {
if (type(el) !== 'element') {
throw new TypeError('Must pass HTMLElement to `analytics.trackLink`.');
}
on(el, 'click', function(e) {
var ev = is.fn(event) ? event(el) : event;
var props = is.fn(properties) ? properties(el) : properties;
var href =
on(el, 'click', (e) => {
const ev = is.fn(event) ? event(el) : event;
const props = is.fn(properties) ? properties(el) : properties;
const href =
el.getAttribute('href') ||
el.getAttributeNS('http://www.w3.org/1999/xlink', 'href') ||
el.getAttribute('xlink:href');

self.track(ev, props);
this.track(ev, props);

// @ts-ignore
if (href && el.target !== '_blank' && !isMeta(e)) {
prevent(e);
self._callback(function() {
this._callback(function() {
window.location.href = href;
});
}
});
}, links);
});

return this;
};
Expand All @@ -522,18 +532,19 @@ Analytics.prototype.trackSubmit = Analytics.prototype.trackForm = function(
// always arrays, handles jquery
if (type(forms) === 'element') forms = [forms];

var self = this;
each(function(el: { submit: () => void }) {
const elements = forms as Array<unknown>

elements.forEach((el: { submit: () => void }) => {
if (type(el) !== 'element')
throw new TypeError('Must pass HTMLElement to `analytics.trackForm`.');
function handler(e) {
const handler = (e) => {
prevent(e);

var ev = is.fn(event) ? event(el) : event;
var props = is.fn(properties) ? properties(el) : properties;
self.track(ev, props);
const ev = is.fn(event) ? event(el) : event;
const props = is.fn(properties) ? properties(el) : properties;
this.track(ev, props);

self._callback(function() {
this._callback(function() {
el.submit();
});
}
Expand All @@ -546,7 +557,7 @@ Analytics.prototype.trackSubmit = Analytics.prototype.trackForm = function(
} else {
on(el, 'submit', handler);
}
}, forms);
});

return this;
};
Expand Down Expand Up @@ -583,7 +594,7 @@ Analytics.prototype.page = function(
(name = category), (category = null);
/* eslint-enable no-unused-expressions, no-sequences */

properties = clone(properties) || {};
properties = cloneDeep(properties) || {};
if (name) properties.name = name;
if (category) properties.category = category;

Expand All @@ -595,7 +606,7 @@ Analytics.prototype.page = function(
// Mirror user overrides to `options.context.page` (but exclude custom properties)
// (Any page defaults get applied in `this.normalize` for consistency.)
// Weird, yeah--moving special props to `context.page` will fix this in the long term.
var overrides = pick(keys(defs), properties);
var overrides = pick(Object.keys(defs), properties);
if (!is.empty(overrides)) {
options = options || {};
options.context = options.context || {};
Expand Down Expand Up @@ -796,9 +807,11 @@ Analytics.prototype._invoke = function(
return this;

function applyIntegrationMiddlewares(facade) {
var failedInitializations = self.failedInitializations || [];
each(function(integration, name) {
var facadeCopy = extend(true, new Facade({}), facade);
let failedInitializations = self.failedInitializations || [];
Object.keys(self._integrations).forEach(key => {
const integration = self._integrations[key]
const { name } = integration
const facadeCopy = extend(true, new Facade({}), facade);

if (!facadeCopy.enabled(name)) return;
// Check if an integration failed to initialize.
Expand Down Expand Up @@ -882,7 +895,7 @@ Analytics.prototype._invoke = function(
);
}
}
}, self._integrations);
});
}
};

Expand Down Expand Up @@ -957,7 +970,7 @@ Analytics.prototype.normalize = function(msg: {
context: { page };
anonymousId: string;
}): object {
msg = normalize(msg, keys(this._integrations));
msg = normalize(msg, Object.keys(this._integrations));
if (msg.anonymousId) user.anonymousId(msg.anonymousId);
msg.anonymousId = user.anonymousId();

Expand Down
6 changes: 3 additions & 3 deletions lib/cookie.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
'use strict';

import { CookieOptions } from './types';
import cloneDeep from 'lodash.clonedeep'

/**
* Module dependencies.
*/

var bindAll = require('bind-all');
var clone = require('./utils/clone');
var cookie = require('@segment/cookie');
var debug = require('debug')('analytics.js:cookie');
var defaults = require('@ndhoule/defaults');
Expand Down Expand Up @@ -65,7 +65,7 @@ Cookie.prototype.options = function(options?: CookieOptions) {
Cookie.prototype.set = function(key: string, value?: object | string): boolean {
try {
value = window.JSON.stringify(value);
cookie(key, value === 'null' ? null : value, clone(this._options));
cookie(key, value === 'null' ? null : value, cloneDeep(this._options));
return true;
} catch (e) {
return false;
Expand All @@ -92,7 +92,7 @@ Cookie.prototype.get = function(key: string): object {

Cookie.prototype.remove = function(key: string): boolean {
try {
cookie(key, null, clone(this._options));
cookie(key, null, cloneDeep(this._options));
return true;
} catch (e) {
return false;
Expand Down
4 changes: 2 additions & 2 deletions lib/entity.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
'use strict';

import { InitOptions } from './types';
import cloneDeep from 'lodash.clonedeep'

/*
* Module dependencies.
*/

var clone = require('./utils/clone');
var cookie = require('./cookie');
var debug = require('debug')('analytics:entity');
var defaults = require('@ndhoule/defaults');
Expand Down Expand Up @@ -198,7 +198,7 @@ Entity.prototype._getTraits = function(): object {
var ret = this._options.persist
? store.get(this._options.localStorage.key)
: this._traits;
return ret ? isodateTraverse(clone(ret)) : {};
return ret ? isodateTraverse(cloneDeep(ret)) : {};
};

/**
Expand Down
7 changes: 4 additions & 3 deletions lib/memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
* Module Dependencies.
*/

import cloneDeep from 'lodash.clonedeep'

var bindAll = require('bind-all');
var clone = require('./utils/clone');

/**
* HOP.
Expand All @@ -32,7 +33,7 @@ function Memory() {
*/

Memory.prototype.set = function(key: string, value: unknown): boolean {
this.store[key] = clone(value);
this.store[key] = cloneDeep(value);
return true;
};

Expand All @@ -42,7 +43,7 @@ Memory.prototype.set = function(key: string, value: unknown): boolean {

Memory.prototype.get = function(key: string): unknown | undefined {
if (!has.call(this.store, key)) return;
return clone(this.store[key]);
return cloneDeep(this.store[key]);
};

/**
Expand Down
Loading