This repository was archived by the owner on Sep 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathnormalize.ts
106 lines (88 loc) · 2.38 KB
/
normalize.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
'use strict';
import { Message } from './types';
/**
* Module Dependencies.
*/
var debug = require('debug')('analytics.js:normalize');
var defaults = require('@ndhoule/defaults');
var each = require('./utils/each');
var includes = require('@ndhoule/includes');
var map = require('./utils/map');
var type = require('component-type');
var { v4: uuidv4 } = require('uuid');
var md5 = require('spark-md5').hash;
/**
* HOP.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `normalize`
*/
module.exports = normalize;
/**
* Toplevel properties.
*/
var toplevel = ['integrations', 'anonymousId', 'timestamp', 'context'];
/**
* Normalize `msg` based on integrations `list`.
*/
interface NormalizedMessage {
integrations?: {
[key: string]: string;
};
context?: unknown;
}
function normalize(msg: Message, list: Array<any>): NormalizedMessage {
var lower = map(function (s) {
return s.toLowerCase();
}, list);
var opts: Message = msg.options || {};
var integrations = opts.integrations || {};
var providers = opts.providers || {};
var context = opts.context || {};
var ret: {
integrations?: { [key: string]: string };
context?: unknown;
} = {};
debug('<-', msg);
// integrations.
each(function (value: string, key: string) {
if (!integration(key)) return;
if (!has.call(integrations, key)) integrations[key] = value;
delete opts[key];
}, opts);
// providers.
delete opts.providers;
each(function (value: string, key: string) {
if (!integration(key)) return;
if (type(integrations[key]) === 'object') return;
if (has.call(integrations, key) && typeof providers[key] === 'boolean')
return;
integrations[key] = value;
}, providers);
// move all toplevel options to msg
// and the rest to context.
each(function (_value: any, key: string | number) {
if (includes(key, toplevel)) {
ret[key] = opts[key];
} else {
context[key] = opts[key];
}
}, opts);
// generate and attach a messageId to msg
msg.messageId = 'ajs-' + md5(window.JSON.stringify(msg) + uuidv4());
// cleanup
delete msg.options;
ret.integrations = integrations;
ret.context = context;
ret = defaults(ret, msg);
debug('->', ret);
return ret;
function integration(name: string) {
return !!(
includes(name, list) ||
name.toLowerCase() === 'all' ||
includes(name.toLowerCase(), lower)
);
}
}