posthog-node 1.1.5

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ Copyright (c) 2020 PostHog (part of Hiberly Inc)
2
+
3
+ Copyright (c) 2013 Segment Inc. friends@segment.com
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,24 @@
1
+ # PostHog Node.js Library
2
+
3
+ [![npm package](https://img.shields.io/npm/v/posthog-node?style=flat-square)](https://www.npmjs.com/package/posthog-node)
4
+ [![MIT License](https://img.shields.io/badge/License-MIT-red.svg?style=flat-square)](https://opensource.org/licenses/MIT)
5
+
6
+ Please see [PostHog Docs](https://posthog.com/docs).
7
+ Specifically, [Node.js library details](https://posthog.com/docs/libraries/node).
8
+
9
+ ## Releasing a new version
10
+
11
+ Just bump up `version` in `package.json` on the main branch and the new version will be published automatically.
12
+
13
+ It's advised to use `bump patch/minor/major` label on PRs - that way the above will be done automatically
14
+ when the PR is merged.
15
+
16
+ Courtesy of GitHub Actions.
17
+
18
+ ## Thanks
19
+
20
+ This library is largely based on the `analytics-node` package.
21
+
22
+ ## Questions?
23
+
24
+ ### [Join our Slack community.](https://posthog.com/slack)
package/cli.js ADDED
@@ -0,0 +1,72 @@
1
+ #!/usr/bin/env node
2
+ 'use strict'
3
+
4
+ const program = require('commander')
5
+ const PostHog = require('.')
6
+ const pkg = require('./package')
7
+
8
+ const toObject = (str) => JSON.parse(str)
9
+
10
+ program
11
+ .version(pkg.version)
12
+ .option('-k, --apiKey <key>', 'the PostHog api key to use')
13
+ .option('-h, --host <host>', 'the PostHog API hostname to use')
14
+ .option('-t, --type <type>', 'the PostHog message type')
15
+
16
+ .option('-d, --distinctId <id>', 'the distinct id to send the event as')
17
+
18
+ .option('-e, --event <event>', 'the event name to send with the event')
19
+ .option('-p, --properties <properties>', 'the event properties to send (JSON-encoded)', toObject)
20
+
21
+ .option('-a, --alias <previousId>', 'alias for the distinct id')
22
+
23
+ .parse(process.argv)
24
+
25
+ if (program.args.length !== 0) {
26
+ program.help()
27
+ }
28
+
29
+ const apiKey = program.apiKey
30
+ const host = program.host
31
+ const type = program.type
32
+
33
+ const distinctId = program.distinctId
34
+
35
+ const event = program.event
36
+ const properties = program.properties
37
+ const alias = program.alias
38
+
39
+ const run = (method, args) => {
40
+ const posthog = new PostHog(apiKey, { host, flushAt: 1 })
41
+ posthog[method](args, (err) => {
42
+ if (err) {
43
+ console.error(err.stack)
44
+ process.exit(1)
45
+ }
46
+ })
47
+ }
48
+
49
+ switch (type) {
50
+ case 'capture':
51
+ run('capture', {
52
+ event,
53
+ properties,
54
+ distinctId,
55
+ })
56
+ break
57
+ case 'identify':
58
+ run('identify', {
59
+ properties,
60
+ distinctId,
61
+ })
62
+ break
63
+ case 'alias':
64
+ run('alias', {
65
+ alias,
66
+ distinctId,
67
+ })
68
+ break
69
+ default:
70
+ console.error('invalid type:', type)
71
+ process.exit(1)
72
+ }
@@ -0,0 +1,94 @@
1
+ var type = require('component-type')
2
+ var join = require('join-component')
3
+ var assert = require('assert')
4
+
5
+ // PostHog messages can be a maximum of 32 kB.
6
+ var MAX_SIZE = 32 << 10
7
+
8
+ module.exports = eventValidation
9
+
10
+ /**
11
+ * Validate an event.
12
+ */
13
+
14
+ function eventValidation(event, type) {
15
+ validateGenericEvent(event)
16
+ type = type || event.type
17
+ assert(type, 'You must pass an event type.')
18
+ switch (type) {
19
+ case 'capture':
20
+ return validateCaptureEvent(event)
21
+ case 'identify':
22
+ return validateIdentifyEvent(event)
23
+ case 'alias':
24
+ return validateAliasEvent(event)
25
+ default:
26
+ assert(0, 'Invalid event type: "' + type + '"')
27
+ }
28
+ }
29
+
30
+ /**
31
+ * Validate a "capture" event.
32
+ */
33
+
34
+ function validateCaptureEvent(event) {
35
+ assert(event.distinctId, 'You must pass a "distinctId".')
36
+ assert(event.event, 'You must pass an "event".')
37
+ }
38
+
39
+ /**
40
+ * Validate a "identify" event.
41
+ */
42
+
43
+ function validateIdentifyEvent(event) {
44
+ assert(event.distinctId, 'You must pass a "distinctId".')
45
+ }
46
+
47
+ /**
48
+ * Validate an "alias" event.
49
+ */
50
+
51
+ function validateAliasEvent(event) {
52
+ assert(event.distinctId, 'You must pass a "distinctId".')
53
+ assert(event.alias, 'You must pass a "alias".')
54
+ }
55
+
56
+ /**
57
+ * Validation rules.
58
+ */
59
+
60
+ var genericValidationRules = {
61
+ event: 'string',
62
+ properties: 'object',
63
+ alias: 'string',
64
+ timestamp: 'date',
65
+ distinctId: 'string',
66
+ type: 'string',
67
+ }
68
+
69
+ /**
70
+ * Validate an event object.
71
+ */
72
+
73
+ function validateGenericEvent(event) {
74
+ assert(type(event) === 'object', 'You must pass a message object.')
75
+ var json = JSON.stringify(event)
76
+ // Strings are variable byte encoded, so json.length is not sufficient.
77
+ assert(Buffer.byteLength(json, 'utf8') < MAX_SIZE, 'Your message must be < 32 kB.')
78
+
79
+ for (var key in genericValidationRules) {
80
+ var val = event[key]
81
+ if (!val) continue
82
+ var rule = genericValidationRules[key]
83
+ if (type(rule) !== 'array') {
84
+ rule = [rule]
85
+ }
86
+ var a = rule[0] === 'object' ? 'an' : 'a'
87
+ assert(
88
+ rule.some(function (e) {
89
+ return type(val) === e
90
+ }),
91
+ '"' + key + '" must be ' + a + ' ' + join(rule, 'or') + '.'
92
+ )
93
+ }
94
+ }
@@ -0,0 +1,145 @@
1
+ const axios = require('axios')
2
+ const crypto = require('crypto')
3
+ const ms = require('ms')
4
+ const version = require('./package.json').version
5
+
6
+ const LONG_SCALE = 0xfffffffffffffff
7
+
8
+
9
+ class FeatureFlagsPoller {
10
+ constructor({ pollingInterval, personalApiKey, projectApiKey, timeout, host, featureFlagCalledCallback }) {
11
+ this.pollingInterval = pollingInterval
12
+ this.personalApiKey = personalApiKey
13
+ this.featureFlags = []
14
+ this.loadedSuccessfullyOnce = false
15
+ this.timeout = timeout
16
+ this.projectApiKey = projectApiKey
17
+ this.featureFlagCalledCallback = featureFlagCalledCallback
18
+ this.host = host
19
+ this.poller = null
20
+
21
+ void this.loadFeatureFlags()
22
+ }
23
+
24
+ async isFeatureEnabled(key, distinctId, defaultResult = false) {
25
+ await this.loadFeatureFlags()
26
+
27
+ if (!this.loadedSuccessfullyOnce) {
28
+ return defaultResult
29
+ }
30
+
31
+ let featureFlag = null
32
+
33
+ for (const flag of this.featureFlags) {
34
+ if (key === flag.key) {
35
+ featureFlag = flag
36
+ break
37
+ }
38
+ }
39
+
40
+ if (!featureFlag) {
41
+ return defaultResult
42
+ }
43
+
44
+ let isFlagEnabledResponse
45
+
46
+ if (featureFlag.is_simple_flag) {
47
+ isFlagEnabledResponse = this._isSimpleFlagEnabled({
48
+ key,
49
+ distinctId,
50
+ rolloutPercentage: featureFlag.rolloutPercentage,
51
+ })
52
+ } else {
53
+ const res = await this._request({ path: 'decide', method: 'POST', data: { distinct_id: distinctId } })
54
+ isFlagEnabledResponse = res.data.featureFlags.indexOf(key) >= 0
55
+ }
56
+
57
+ this.featureFlagCalledCallback(key, distinctId, isFlagEnabledResponse)
58
+ return isFlagEnabledResponse
59
+ }
60
+
61
+ async loadFeatureFlags(forceReload = false) {
62
+ if (!this.loadedSuccessfullyOnce || forceReload) {
63
+ await this._loadFeatureFlags()
64
+ }
65
+ }
66
+
67
+ /* istanbul ignore next */
68
+ async _loadFeatureFlags() {
69
+ if (this.poller) {
70
+ clearTimeout(this.poller)
71
+ this.poller = null
72
+ }
73
+ this.poller = setTimeout(() => this._loadFeatureFlags(), this.pollingInterval)
74
+
75
+ const res = await this._request({ path: 'api/feature_flag', usePersonalApiKey: true })
76
+
77
+ if (res && res.status === 401) {
78
+ throw new Error(
79
+ `Your personalApiKey is invalid. Are you sure you're not using your Project API key? More information: https://posthog.com/docs/api/overview`
80
+ )
81
+ }
82
+
83
+ this.featureFlags = res.data.results.filter(flag => flag.active)
84
+ this.loadedSuccessfullyOnce = true
85
+ }
86
+
87
+ // sha1('a.b') should equal '69f6642c9d71b463485b4faf4e989dc3fe77a8c6'
88
+ // integerRepresentationOfHashSubset / LONG_SCALE for sha1('a.b') should equal 0.4139158829615955
89
+ _isSimpleFlagEnabled({ key, distinctId, rolloutPercentage }) {
90
+ if (!rolloutPercentage) {
91
+ return true
92
+ }
93
+ const sha1Hash = crypto.createHash('sha1')
94
+ sha1Hash.update(`${key}.${distinctId}`)
95
+ const integerRepresentationOfHashSubset = parseInt(sha1Hash.digest('hex').slice(0, 15), 16)
96
+ return integerRepresentationOfHashSubset / LONG_SCALE <= rolloutPercentage / 100
97
+ }
98
+
99
+ /* istanbul ignore next */
100
+ async _request({ path, method = 'GET', usePersonalApiKey = false, data = {} }) {
101
+ let url = `${this.host}/${path}/`
102
+ let headers = {
103
+ 'Content-Type': 'application/json',
104
+ }
105
+
106
+ if (usePersonalApiKey) {
107
+ headers = { ...headers, Authorization: `Bearer ${this.personalApiKey}` }
108
+ url = url + `?token=${this.projectApiKey}`
109
+ } else {
110
+ data = { ...data, token: this.projectApiKey }
111
+ }
112
+
113
+ if (typeof window === 'undefined') {
114
+ headers['user-agent'] = `posthog-node/${version}`
115
+ }
116
+
117
+ const req = {
118
+ method: method,
119
+ url: url,
120
+ headers: headers,
121
+ data: JSON.stringify(data),
122
+ }
123
+
124
+ if (this.timeout) {
125
+ req.timeout = typeof this.timeout === 'string' ? ms(this.timeout) : this.timeout
126
+ }
127
+
128
+ let res
129
+ try {
130
+ res = await axios(req)
131
+ } catch (err) {
132
+ throw new Error(`Request to ${path} failed with error: ${err.message}`)
133
+ }
134
+
135
+ return res
136
+ }
137
+
138
+ stopPoller() {
139
+ clearTimeout(this.poller)
140
+ }
141
+ }
142
+
143
+ module.exports = {
144
+ FeatureFlagsPoller,
145
+ }
package/index.d.ts ADDED
@@ -0,0 +1,84 @@
1
+ // Type definitions for posthog-node
2
+ // Project: Posthog
3
+
4
+ declare module 'posthog-node' {
5
+ interface Option {
6
+ flushAt?: number
7
+ flushInterval?: number
8
+ host?: string
9
+ enable?: boolean
10
+ personalApiKey?: string
11
+ featureFlagsPollingInterval?: number
12
+ }
13
+ interface IdentifyMessage {
14
+ distinctId: string
15
+ properties?: Record<string | number, any>
16
+ }
17
+
18
+ interface EventMessage extends IdentifyMessage {
19
+ event: string
20
+ }
21
+
22
+ export default class PostHog {
23
+ constructor(apiKey: string, options?: Option)
24
+ /**
25
+ * @description Capture allows you to capture anything a user does within your system,
26
+ * which you can later use in PostHog to find patterns in usage,
27
+ * work out which features to improve or where people are giving up.
28
+ * A capture call requires:
29
+ * @param distinctId which uniquely identifies your user
30
+ * @param event We recommend using [verb] [noun], like movie played or movie updated to easily identify what your events mean later on.
31
+ * @param properties OPTIONAL | which can be a dict with any information you'd like to add
32
+ */
33
+ capture({ distinctId, event, properties }: EventMessage): void
34
+
35
+ /**
36
+ * @description Identify lets you add metadata on your users so you can more easily identify who they are in PostHog,
37
+ * and even do things like segment users by these properties.
38
+ * An identify call requires:
39
+ * @param distinctId which uniquely identifies your user
40
+ * @param properties with a dict with any key: value pairs
41
+ */
42
+ identify({ distinctId, properties }: IdentifyMessage): void
43
+
44
+ /**
45
+ * @description To marry up whatever a user does before they sign up or log in with what they do after you need to make an alias call.
46
+ * This will allow you to answer questions like "Which marketing channels leads to users churning after a month?"
47
+ * or "What do users do on our website before signing up?"
48
+ * In a purely back-end implementation, this means whenever an anonymous user does something, you'll want to send a session ID with the capture call.
49
+ * Then, when that users signs up, you want to do an alias call with the session ID and the newly created user ID.
50
+ * The same concept applies for when a user logs in. If you're using PostHog in the front-end and back-end,
51
+ * doing the identify call in the frontend will be enough.:
52
+ * @param distinctId the current unique id
53
+ * @param alias the unique ID of the user before
54
+ */
55
+ alias(data: { distinctId: string; alias: string }): void
56
+
57
+
58
+ /**
59
+ * @description PostHog feature flags (https://posthog.com/docs/features/feature-flags)
60
+ * allow you to safely deploy and roll back new features. Once you've created a feature flag in PostHog,
61
+ * you can use this method to check if the flag is on for a given user, allowing you to create logic to turn
62
+ * features on and off for different user groups or individual users.
63
+ * IMPORTANT: To use this method, you need to specify `personalApiKey` in your config! More info: https://posthog.com/docs/api/overview
64
+ * @param key the unique key of your feature flag
65
+ * @param distinctId the current unique id
66
+ * @param defaultResult optional - default value to be returned if the feature flag is not on for the user
67
+ */
68
+ isFeatureEnabled(key: string, distinctId: string, defaultResult?: boolean): Promise<boolean>
69
+
70
+
71
+ /**
72
+ * @description Force an immediate reload of the polled feature flags. Please note that they are
73
+ * already polled automatically at a regular interval.
74
+ */
75
+ reloadFeatureFlags(): Promise<void>
76
+
77
+ /**
78
+ * @description Flushes the events still in the queue and clears the feature flags poller to allow for
79
+ * a clean shutdown.
80
+ */
81
+ shutdown(): void
82
+ }
83
+
84
+ }
package/index.js ADDED
@@ -0,0 +1,331 @@
1
+ 'use strict'
2
+
3
+ const assert = require('assert')
4
+ const removeSlash = require('remove-trailing-slash')
5
+ const axios = require('axios')
6
+ const axiosRetry = require('axios-retry')
7
+ const ms = require('ms')
8
+ const version = require('./package.json').version
9
+ const looselyValidate = require('./event-validation')
10
+ const { FeatureFlagsPoller } = require('./feature-flags')
11
+
12
+ const setImmediate = global.setImmediate || process.nextTick.bind(process)
13
+ const noop = () => {}
14
+
15
+ const FIVE_MINUTES = 5 * 60 * 1000
16
+ class PostHog {
17
+ /**
18
+ * Initialize a new `PostHog` with your PostHog project's `apiKey` and an
19
+ * optional dictionary of `options`.
20
+ *
21
+ * @param {String} apiKey
22
+ * @param {Object} [options] (optional)
23
+ * @property {Number} flushAt (default: 20)
24
+ * @property {Number} flushInterval (default: 10000)
25
+ * @property {String} host (default: 'https://app.posthog.com')
26
+ * @property {Boolean} enable (default: true)
27
+ * @property {String} featureFlagsPollingInterval (default: 300000)
28
+ * @property {String} personalApiKey
29
+ */
30
+
31
+ constructor(apiKey, options) {
32
+ options = options || {}
33
+
34
+ assert(apiKey, "You must pass your PostHog project's api key.")
35
+
36
+ this.queue = []
37
+ this.apiKey = apiKey
38
+ this.host = removeSlash(options.host || 'https://app.posthog.com')
39
+ this.timeout = options.timeout || false
40
+ this.flushAt = Math.max(options.flushAt, 1) || 20
41
+ this.flushInterval = typeof options.flushInterval === 'number' ? options.flushInterval : 10000
42
+ this.flushed = false
43
+ this.personalApiKey = options.personalApiKey
44
+
45
+ Object.defineProperty(this, 'enable', {
46
+ configurable: false,
47
+ writable: false,
48
+ enumerable: true,
49
+ value: typeof options.enable === 'boolean' ? options.enable : true,
50
+ })
51
+
52
+ axiosRetry(axios, {
53
+ retries: options.retryCount || 3,
54
+ retryCondition: this._isErrorRetryable,
55
+ retryDelay: axiosRetry.exponentialDelay,
56
+ })
57
+
58
+ if (this.personalApiKey) {
59
+ const featureFlagCalledCallback = (key, distinctId, isFlagEnabledResponse) => {
60
+ this.capture({
61
+ distinctId,
62
+ event: '$feature_flag_called',
63
+ properties: {
64
+ $feature_flag: key,
65
+ $feature_flag_response: isFlagEnabledResponse,
66
+ },
67
+ })
68
+ }
69
+
70
+ this.featureFlagsPoller = new FeatureFlagsPoller({
71
+ pollingInterval:
72
+ typeof options.featureFlagsPollingInterval === 'number'
73
+ ? options.featureFlagsPollingInterval
74
+ : FIVE_MINUTES,
75
+ personalApiKey: options.personalApiKey,
76
+ projectApiKey: apiKey,
77
+ timeout: options.timeout || false,
78
+ host: this.host,
79
+ featureFlagCalledCallback,
80
+ })
81
+ }
82
+ }
83
+
84
+ _validate(message, type) {
85
+ try {
86
+ looselyValidate(message, type)
87
+ } catch (e) {
88
+ if (e.message === 'Your message must be < 32 kB.') {
89
+ console.log(
90
+ 'Your message must be < 32 kB.',
91
+ JSON.stringify(message)
92
+ )
93
+ return
94
+ }
95
+ throw e
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Send an identify `message`.
101
+ *
102
+ * @param {Object} message
103
+ * @param {Function} [callback] (optional)
104
+ * @return {PostHog}
105
+ */
106
+
107
+ identify(message, callback) {
108
+ this._validate(message, 'identify')
109
+
110
+ const apiMessage = Object.assign({}, message, {
111
+ $set: message.properties || {},
112
+ event: '$identify',
113
+ properties: {
114
+ $lib: 'posthog-node',
115
+ $lib_version: version,
116
+ },
117
+ })
118
+
119
+ this.enqueue('identify', apiMessage, callback)
120
+ return this
121
+ }
122
+
123
+ /**
124
+ * Send a capture `message`.
125
+ *
126
+ * @param {Object} message
127
+ * @param {Function} [callback] (optional)
128
+ * @return {PostHog}
129
+ */
130
+
131
+ capture(message, callback) {
132
+ this._validate(message, 'capture')
133
+
134
+ const apiMessage = Object.assign({}, message, {
135
+ properties: Object.assign({}, message.properties, {
136
+ $lib: 'posthog-node',
137
+ $lib_version: version,
138
+ }),
139
+ })
140
+
141
+ this.enqueue('capture', apiMessage, callback)
142
+ return this
143
+ }
144
+
145
+ /**
146
+ * Send an alias `message`.
147
+ *
148
+ * @param {Object} message
149
+ * @param {Function} [callback] (optional)
150
+ * @return {PostHog}
151
+ */
152
+
153
+ alias(message, callback) {
154
+ this._validate(message, 'alias')
155
+
156
+ const apiMessage = Object.assign({}, message, {
157
+ event: '$create_alias',
158
+ properties: {
159
+ distinct_id: message.distinctId || message.distinct_id,
160
+ alias: message.alias,
161
+ $lib: 'posthog-node',
162
+ $lib_version: version,
163
+ },
164
+ })
165
+ delete apiMessage.alias
166
+ delete apiMessage.distinctId
167
+ apiMessage.distinct_id = message.distinctId || message.distinct_id
168
+
169
+ this.enqueue('alias', apiMessage, callback)
170
+ return this
171
+ }
172
+
173
+ /**
174
+ * Add a `message` of type `type` to the queue and
175
+ * check whether it should be flushed.
176
+ *
177
+ * @param {String} type
178
+ * @param {Object} message
179
+ * @param {Function} [callback] (optional)
180
+ * @api private
181
+ */
182
+
183
+ enqueue(type, message, callback) {
184
+ callback = callback || noop
185
+
186
+ if (!this.enable) {
187
+ return setImmediate(callback)
188
+ }
189
+
190
+ message = Object.assign({}, message)
191
+ message.type = type
192
+ message.library = 'posthog-node'
193
+ message.library_version = version
194
+
195
+ if (!message.timestamp) {
196
+ message.timestamp = new Date()
197
+ }
198
+
199
+ if (message.distinctId) {
200
+ message.distinct_id = message.distinctId
201
+ delete message.distinctId
202
+ }
203
+
204
+ this.queue.push({ message, callback })
205
+
206
+ if (!this.flushed) {
207
+ this.flushed = true
208
+ this.flush()
209
+ return
210
+ }
211
+
212
+ if (this.queue.length >= this.flushAt) {
213
+ this.flush()
214
+ }
215
+
216
+ if (this.flushInterval && !this.timer) {
217
+ this.timer = setTimeout(() => this.flush(), this.flushInterval)
218
+ }
219
+ }
220
+
221
+ async isFeatureEnabled(key, distinctId, defaultResult) {
222
+ assert(this.personalApiKey, 'You have to specify the option personalApiKey to use feature flags.')
223
+ return await this.featureFlagsPoller.isFeatureEnabled(key, distinctId, defaultResult)
224
+ }
225
+
226
+ async reloadFeatureFlags() {
227
+ await this.featureFlagsPoller.loadFeatureFlags(true)
228
+ }
229
+
230
+ /**
231
+ * Flush the current queue
232
+ *
233
+ * @param {Function} [callback] (optional)
234
+ * @return {PostHog}
235
+ */
236
+
237
+ flush(callback) {
238
+ callback = callback || noop
239
+
240
+ if (!this.enable) {
241
+ return setImmediate(callback)
242
+ }
243
+
244
+ if (this.timer) {
245
+ clearTimeout(this.timer)
246
+ this.timer = null
247
+ }
248
+
249
+ if (!this.queue.length) {
250
+ return setImmediate(callback)
251
+ }
252
+
253
+ const items = this.queue.splice(0, this.flushAt)
254
+ const callbacks = items.map((item) => item.callback)
255
+ const messages = items.map((item) => item.message)
256
+
257
+ const data = {
258
+ api_key: this.apiKey,
259
+ batch: messages,
260
+ }
261
+
262
+ const done = (err) => {
263
+ callbacks.forEach((callback) => callback(err))
264
+ callback(err, data)
265
+ }
266
+
267
+ // Don't set the user agent if we're not on a browser. The latest spec allows
268
+ // the User-Agent header (see https://fetch.spec.whatwg.org/#terminology-headers
269
+ // and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader),
270
+ // but browsers such as Chrome and Safari have not caught up.
271
+ const headers = {}
272
+ if (typeof window === 'undefined') {
273
+ headers['user-agent'] = `posthog-node/${version}`
274
+ }
275
+
276
+ const req = {
277
+ method: 'POST',
278
+ url: `${this.host}/batch/`,
279
+ data,
280
+ headers,
281
+ }
282
+
283
+ if (this.timeout) {
284
+ req.timeout = typeof this.timeout === 'string' ? ms(this.timeout) : this.timeout
285
+ }
286
+
287
+ axios(req)
288
+ .then(() => done())
289
+ .catch((err) => {
290
+ if (err.response) {
291
+ const error = new Error(err.response.statusText)
292
+ return done(error)
293
+ }
294
+
295
+ done(err)
296
+ })
297
+ }
298
+
299
+ shutdown() {
300
+ if (this.personalApiKey) {
301
+ this.featureFlagsPoller.stopPoller()
302
+ }
303
+ this.flush()
304
+ }
305
+
306
+ _isErrorRetryable(error) {
307
+ // Retry Network Errors.
308
+ if (axiosRetry.isNetworkError(error)) {
309
+ return true
310
+ }
311
+
312
+ if (!error.response) {
313
+ // Cannot determine if the request can be retried
314
+ return false
315
+ }
316
+
317
+ // Retry Server Errors (5xx).
318
+ if (error.response.status >= 500 && error.response.status <= 599) {
319
+ return true
320
+ }
321
+
322
+ // Retry if rate limited.
323
+ if (error.response.status === 429) {
324
+ return true
325
+ }
326
+
327
+ return false
328
+ }
329
+ }
330
+
331
+ module.exports = PostHog
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "posthog-node",
3
+ "version": "1.1.5",
4
+ "description": "PostHog Node.js integration",
5
+ "license": "MIT",
6
+ "repository": "PostHog/posthog-node",
7
+ "author": {
8
+ "name": "PostHog",
9
+ "email": "hey@posthog.com",
10
+ "url": "https://posthog.com"
11
+ },
12
+ "engines": {
13
+ "node": ">=4"
14
+ },
15
+ "size-limit": [
16
+ {
17
+ "limit": "25 KB",
18
+ "path": "index.js"
19
+ }
20
+ ],
21
+ "scripts": {
22
+ "dependencies": "yarn",
23
+ "size": "size-limit",
24
+ "test": "nyc ava tests/*.js",
25
+ "report-coverage": "nyc report --reporter=lcov > coverage.lcov && codecov",
26
+ "format": "prettier --write ."
27
+ },
28
+ "files": [
29
+ "index.js",
30
+ "index.d.ts",
31
+ "event-validation.js",
32
+ "cli.js",
33
+ "feature-flags.js"
34
+ ],
35
+ "bin": {
36
+ "posthog": "cli.js"
37
+ },
38
+ "keywords": [
39
+ "posthog",
40
+ "stats",
41
+ "analysis",
42
+ "funnels"
43
+ ],
44
+ "dependencies": {
45
+ "axios": "^0.21.1",
46
+ "axios-retry": "^3.1.9",
47
+ "component-type": "^1.2.1",
48
+ "join-component": "^1.1.0",
49
+ "md5": "^2.3.0",
50
+ "ms": "^2.1.3",
51
+ "remove-trailing-slash": "^0.1.1",
52
+ "uuid": "^8.3.2"
53
+ },
54
+ "devDependencies": {
55
+ "ava": "^0.25.0",
56
+ "basic-auth": "^2.0.1",
57
+ "body-parser": "^1.17.1",
58
+ "codecov": "^3.0.0",
59
+ "commander": "^2.9.0",
60
+ "delay": "^4.2.0",
61
+ "express": "^4.15.2",
62
+ "nyc": "^14.1.1",
63
+ "pify": "^4.0.1",
64
+ "prettier": "^2.3.1",
65
+ "sinon": "^7.3.2",
66
+ "size-limit": "^1.3.5",
67
+ "snyk": "^1.171.1"
68
+ }
69
+ }