generated from rudderlabs/rudder-repo-template
-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
288 lines (240 loc) · 8.28 KB
/
index.js
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
const alias = {
userId: 'properties.alias',
previousId: ['properties.distinct_id'],
}
const page = {
name: 'properties.name',
'properties.category': 'properties.category',
'properties.host': 'properties.$host',
'properties.url': 'properties.$current_url',
'properties.path': 'properties.$pathname',
'properties.referrer': 'properties.$referrer',
'properties.initial_referrer': 'properties.$initial_referrer',
'properties.referring_domain': 'properties.$referring_domain',
'properties.initial_referring_domain': 'properties.$initial_referring_domain',
}
const identify = {
'context.traits': '$set',
traits: '$set',
}
const group = {
groupId: 'groupId',
traits: 'traits',
}
const track = {
event: 'event',
}
const constants = {
'context.app.name': 'PostHogPlugin',
channel: 's2s',
}
// TODO: handle "context.channel" better
const generic = {
'context.os.name': 'properties.$os',
'context.browser': 'properties.$browser',
'context.page.host': 'properties.$host',
'context.page.url': 'properties.$current_url',
'context.page.path': 'properties.$pathname',
'context.page.referrer': 'properties.$referrer',
'context.page.initial_referrer': 'properties.$initial_referrer',
'context.page.referring_domain': 'properties.$referring_domain',
'context.app.version': 'properties.posthog_version',
'context.page.initial_referring_domain': 'properties.$initial_referring_domain',
'context.browser_version': 'properties.$browser_version',
'context.screen.height': 'properties.$screen_height',
'context.screen.width': 'properties.$screen_width',
'context.library.name': 'properties.$lib',
'context.library.version': 'properties.$lib_version',
'context.ip': 'ip',
messageId: '$insert_id',
originalTimestamp: 'timestamp',
userId: ['$user_id', 'distinct_id'],
anonymousId: ['properties.$anon_distinct_id', 'properties.$device_id', 'properties.distinct_id'],
'context.active_feature_flags': 'properties.$active_feature_flags',
'context.posthog_version': 'properties.posthog_version',
'context.has_slack_webhook': 'properties.has_slack_webhook',
'context.token': 'properties.token',
}
const autoCapture = {
event: 'properties.$event_type',
'properties.elements': 'properties.$elements',
}
const eventToMapping = {
$identify: { type: 'identify', mapping: identify },
$create_alias: { type: 'alias', mapping: alias },
$pageview: { type: 'page', mapping: page },
$page: { type: 'page', mapping: page },
$group: { type: 'group', mapping: group },
$autocapture: { type: 'track', mapping: autoCapture },
default: { type: 'track', mapping: track },
}
function set(target, path, value) {
let keys = path.split('.')
let len = keys.length
for (let i = 0; i < len; i++) {
let prop = keys[i]
if (!isObject(target[prop])) {
target[prop] = {}
}
if (i === len - 1) {
result(target, prop, value)
break
}
target = target[prop]
}
}
function result(target, path, value) {
target[path] = value
}
function isObject(val) {
return val !== null && (typeof val === 'object' || typeof val === 'function')
}
// Ref: https://github.com/jonschlinkert/get-value
function get(target, path, options) {
if (!isObject(options)) {
options = { default: options }
}
if (!isValidObject(target)) {
return typeof options.default !== 'undefined' ? options.default : target
}
if (typeof path === 'number') {
path = String(path)
}
const isArray = Array.isArray(path)
const isString = typeof path === 'string'
const splitChar = options.separator || '.'
const joinChar = options.joinChar || (typeof splitChar === 'string' ? splitChar : '.')
if (!isString && !isArray) {
return target
}
if (isString && path in target) {
return isValid(path, target, options) ? target[path] : options.default
}
let segs = isArray ? path : split(path, splitChar, options)
let len = segs.length
let idx = 0
do {
let prop = segs[idx]
if (typeof prop === 'number') {
prop = String(prop)
}
while (prop && prop.slice(-1) === '\\') {
prop = join([prop.slice(0, -1), segs[++idx] || ''], joinChar, options)
}
if (prop in target) {
if (!isValid(prop, target, options)) {
return options.default
}
target = target[prop]
} else {
let hasProp = false
let n = idx + 1
while (n < len) {
prop = join([prop, segs[n++]], joinChar, options)
if ((hasProp = prop in target)) {
if (!isValid(prop, target, options)) {
return options.default
}
target = target[prop]
idx = n - 1
break
}
}
if (!hasProp) {
return options.default
}
}
} while (++idx < len && isValidObject(target))
if (idx === len) {
return target
}
return options.default
}
function join(segs, joinChar, options) {
if (typeof options.join === 'function') {
return options.join(segs)
}
return segs[0] + joinChar + segs[1]
}
function split(path, splitChar, options) {
if (typeof options.split === 'function') {
return options.split(path)
}
return path.split(splitChar)
}
function isValid(key, target, options) {
if (typeof options.isValid === 'function') {
return options.isValid(key, target)
}
return true
}
function isValidObject(val) {
return isObject(val) || Array.isArray(val) || typeof val === 'function'
}
export async function setupPlugin({ config, global, jobs }) {
const rudderBase64AuthToken = Buffer.from(`${config.writeKey}:`).toString('base64')
global.rudderAuthHeader = {
headers: {
Authorization: `Basic ${rudderBase64AuthToken}`,
},
}
global.writeKey = config.writeKey
global.dataPlaneUrl = config.dataPlaneUrl
}
export async function exportEvents(events, { global }) {
const payload = {
batch: events.map(constructRudderPayload),
sentAt: new Date().toISOString(),
}
await fetch(global.dataPlaneUrl, {
headers: {
'Content-Type': 'application/json',
...global.rudderAuthHeader.headers,
},
body: JSON.stringify(payload),
method: 'POST',
})
console.log(`Successfully uploaded ${payload.batch.length} events to RudderStack`)
}
function constructRudderPayload(event) {
let rudderPayload = {}
// add const value props
constructPayload(rudderPayload, event, constants, true)
// add generic props
constructPayload(rudderPayload, event, generic)
// get specific event props
const eventName = get(event, 'event')
const { type, mapping } = eventToMapping[eventName] ? eventToMapping[eventName] : eventToMapping['default']
//set Rudder payload type
set(rudderPayload, 'type', type)
// set Rudder event props
constructPayload(rudderPayload, event, mapping)
// add all pther posthog keys under props not starting with $ to Rudder payload properties
Object.keys(event.properties).forEach((propKey) => {
if (propKey.slice(0, 1) != '$' && event.properties[propKey] != undefined && event.properties[propKey] != null) {
set(rudderPayload, `properties.${propKey}`, event.properties[propKey])
}
})
return rudderPayload
}
function constructPayload(outPayload, inPayload, mapping, direct = false) {
Object.keys(mapping).forEach((rudderKeyPath) => {
let pHKeyPath = mapping[rudderKeyPath]
let pHKeyVal = undefined
if (direct) {
pHKeyVal = pHKeyPath
} else if (Array.isArray(pHKeyPath)) {
for (let i = 0; i < pHKeyPath.length; i++) {
pHKeyVal = get(inPayload, pHKeyPath[i])
if (pHKeyVal) {
break
}
}
} else {
pHKeyVal = get(inPayload, pHKeyPath)
}
if (pHKeyVal != undefined && pHKeyVal != null) {
set(outPayload, rudderKeyPath, pHKeyVal)
}
})
}