@posthog/core 1.49.2 → 1.50.0
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/dist/featureFlagLocalEvaluation.d.ts +1 -1
- package/dist/featureFlagLocalEvaluation.d.ts.map +1 -1
- package/dist/featureFlagLocalEvaluation.js +149 -10
- package/dist/featureFlagLocalEvaluation.mjs +149 -10
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +35 -31
- package/dist/index.mjs +2 -1
- package/dist/logs/logs-utils.d.ts +1 -3
- package/dist/logs/logs-utils.d.ts.map +1 -1
- package/dist/logs/logs-utils.js +5 -158
- package/dist/logs/logs-utils.mjs +4 -151
- package/dist/metrics/index.js +2 -2
- package/dist/metrics/index.mjs +1 -1
- package/dist/metrics/metrics-utils.js +2 -2
- package/dist/metrics/metrics-utils.mjs +1 -1
- package/dist/utils/otlp-any-value.d.ts +5 -0
- package/dist/utils/otlp-any-value.d.ts.map +1 -0
- package/dist/utils/otlp-any-value.js +203 -0
- package/dist/utils/otlp-any-value.mjs +166 -0
- package/dist/utils/user-agent-utils.d.ts +4 -4
- package/dist/utils/user-agent-utils.d.ts.map +1 -1
- package/dist/utils/user-agent-utils.js +16 -0
- package/dist/utils/user-agent-utils.mjs +16 -0
- package/package.json +1 -1
- package/src/featureFlagLocalEvaluation.ts +199 -12
- package/src/index.ts +1 -2
- package/src/logs/logs-utils.spec.ts +2 -350
- package/src/logs/logs-utils.ts +3 -207
- package/src/metrics/index.ts +1 -1
- package/src/metrics/metrics-utils.ts +1 -1
- package/src/utils/otlp-any-value.spec.ts +361 -0
- package/src/utils/otlp-any-value.ts +225 -0
- package/src/utils/user-agent-utils.ts +22 -6
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
import type { LogAttributeValue } from '@posthog/types'
|
|
2
|
+
import { toOtlpAnyValue, toOtlpKeyValueList } from './otlp-any-value'
|
|
3
|
+
|
|
4
|
+
describe('otlp-any-value', () => {
|
|
5
|
+
describe('toOtlpAnyValue', () => {
|
|
6
|
+
it('converts strings', () => {
|
|
7
|
+
expect(toOtlpAnyValue('hello')).toEqual({ stringValue: 'hello' })
|
|
8
|
+
})
|
|
9
|
+
|
|
10
|
+
it('converts integers to decimal strings', () => {
|
|
11
|
+
expect(toOtlpAnyValue(42)).toEqual({ intValue: '42' })
|
|
12
|
+
expect(toOtlpAnyValue(0)).toEqual({ intValue: '0' })
|
|
13
|
+
expect(toOtlpAnyValue(-7)).toEqual({ intValue: '-7' })
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
// Spec: outside int64 it is a stringValue, never an intValue.
|
|
17
|
+
it('converts integers outside int64 to stringValue', () => {
|
|
18
|
+
expect(toOtlpAnyValue(2 ** 63)).toEqual({ stringValue: '9223372036854775808' })
|
|
19
|
+
expect(toOtlpAnyValue(-(2 ** 64))).toEqual({ stringValue: '-18446744073709551616' })
|
|
20
|
+
expect(toOtlpAnyValue(1e21)).toEqual({ stringValue: '1000000000000000000000' })
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
it('logs a debug line when an integer falls outside int64', () => {
|
|
24
|
+
const logger = { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(), critical: jest.fn() }
|
|
25
|
+
toOtlpAnyValue(2 ** 63, logger as any)
|
|
26
|
+
expect(logger.debug).toHaveBeenCalledWith(expect.stringContaining('outside the int64 range'))
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('keeps int64 min as intValue', () => {
|
|
30
|
+
// In range, but `String` renders it 192 below int64 min, so the decimal
|
|
31
|
+
// has to come from BigInt.
|
|
32
|
+
expect(toOtlpAnyValue(-(2 ** 63))).toEqual({ intValue: '-9223372036854775808' })
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('keeps large in-range integers exact', () => {
|
|
36
|
+
expect(toOtlpAnyValue(Number.MAX_SAFE_INTEGER)).toEqual({ intValue: '9007199254740991' })
|
|
37
|
+
// The largest double below 2^63 — no double exists between the two.
|
|
38
|
+
expect(toOtlpAnyValue(9223372036854774784)).toEqual({ intValue: '9223372036854774784' })
|
|
39
|
+
expect(toOtlpAnyValue(2 ** 62)).toEqual({ intValue: '4611686018427387904' })
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it('converts a bigint inside int64 to a stringified intValue', () => {
|
|
43
|
+
// Span attributes accept bigint; a log attribute reaching here is typed
|
|
44
|
+
// out but still encodes correctly.
|
|
45
|
+
expect(toOtlpAnyValue(9007199254740993n as unknown as LogAttributeValue)).toEqual({
|
|
46
|
+
intValue: '9007199254740993',
|
|
47
|
+
})
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
it('converts a bigint beyond int64 to a string, with a warning', () => {
|
|
51
|
+
const logger = { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(), critical: jest.fn() }
|
|
52
|
+
expect(toOtlpAnyValue(18446744073709551616n as unknown as LogAttributeValue, logger as any)).toEqual({
|
|
53
|
+
stringValue: '18446744073709551616',
|
|
54
|
+
})
|
|
55
|
+
expect(logger.debug).toHaveBeenCalled()
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('converts floats to doubleValue', () => {
|
|
59
|
+
expect(toOtlpAnyValue(3.14)).toEqual({ doubleValue: 3.14 })
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('converts booleans', () => {
|
|
63
|
+
expect(toOtlpAnyValue(true)).toEqual({ boolValue: true })
|
|
64
|
+
expect(toOtlpAnyValue(false)).toEqual({ boolValue: false })
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
// JSON has no representation for non-finite floats; without explicit
|
|
68
|
+
// handling, JSON.stringify silently turns them into `null` and the value
|
|
69
|
+
// is lost server-side.
|
|
70
|
+
it('converts NaN to stringValue', () => {
|
|
71
|
+
expect(toOtlpAnyValue(NaN)).toEqual({ stringValue: 'NaN' })
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
it('converts +Infinity to stringValue', () => {
|
|
75
|
+
expect(toOtlpAnyValue(Infinity)).toEqual({ stringValue: 'Infinity' })
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
it('converts -Infinity to stringValue', () => {
|
|
79
|
+
expect(toOtlpAnyValue(-Infinity)).toEqual({ stringValue: '-Infinity' })
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
it('converts arrays of strings to arrayValue', () => {
|
|
83
|
+
expect(toOtlpAnyValue(['a', 'b'])).toEqual({
|
|
84
|
+
arrayValue: { values: [{ stringValue: 'a' }, { stringValue: 'b' }] },
|
|
85
|
+
})
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
it('converts mixed primitive arrays recursively', () => {
|
|
89
|
+
expect(toOtlpAnyValue([1, 'x', true])).toEqual({
|
|
90
|
+
arrayValue: {
|
|
91
|
+
values: [{ intValue: '1' }, { stringValue: 'x' }, { boolValue: true }],
|
|
92
|
+
},
|
|
93
|
+
})
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
it('converts plain objects to kvlistValue', () => {
|
|
97
|
+
expect(toOtlpAnyValue({ a: 1, b: 'two' })).toEqual({
|
|
98
|
+
kvlistValue: {
|
|
99
|
+
values: [
|
|
100
|
+
{ key: 'a', value: { intValue: '1' } },
|
|
101
|
+
{ key: 'b', value: { stringValue: 'two' } },
|
|
102
|
+
],
|
|
103
|
+
},
|
|
104
|
+
})
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
it('converts nested objects recursively', () => {
|
|
108
|
+
expect(toOtlpAnyValue({ outer: { inner: 1 } })).toEqual({
|
|
109
|
+
kvlistValue: {
|
|
110
|
+
values: [
|
|
111
|
+
{
|
|
112
|
+
key: 'outer',
|
|
113
|
+
value: { kvlistValue: { values: [{ key: 'inner', value: { intValue: '1' } }] } },
|
|
114
|
+
},
|
|
115
|
+
],
|
|
116
|
+
},
|
|
117
|
+
})
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
it('drops null and undefined keys inside objects', () => {
|
|
121
|
+
expect(toOtlpAnyValue({ kept: 1, gone: null, alsoGone: undefined })).toEqual({
|
|
122
|
+
kvlistValue: { values: [{ key: 'kept', value: { intValue: '1' } }] },
|
|
123
|
+
})
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
// Not in LogAttributeValue, but reachable at runtime from untyped callers.
|
|
127
|
+
it('encodes Dates as ISO strings', () => {
|
|
128
|
+
expect(toOtlpAnyValue(new Date('2026-08-20T10:00:00.000Z') as unknown as LogAttributeValue)).toEqual({
|
|
129
|
+
stringValue: '2026-08-20T10:00:00.000Z',
|
|
130
|
+
})
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
it('marks circular references instead of recursing', () => {
|
|
134
|
+
const cyclic: Record<string, unknown> = { name: 'root' }
|
|
135
|
+
cyclic.self = cyclic
|
|
136
|
+
expect(toOtlpAnyValue(cyclic)).toEqual({
|
|
137
|
+
kvlistValue: {
|
|
138
|
+
values: [
|
|
139
|
+
{ key: 'name', value: { stringValue: 'root' } },
|
|
140
|
+
{ key: 'self', value: { stringValue: '[Circular]' } },
|
|
141
|
+
],
|
|
142
|
+
},
|
|
143
|
+
})
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
// An escaping error would surface in the caller's application code.
|
|
147
|
+
it('does not throw on an object nested past the depth cap', () => {
|
|
148
|
+
let deep: Record<string, unknown> = { end: true }
|
|
149
|
+
for (let i = 0; i < 25000; i++) {
|
|
150
|
+
deep = { next: deep }
|
|
151
|
+
}
|
|
152
|
+
expect(() => toOtlpAnyValue(deep)).not.toThrow()
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
it('truncates at exactly 20 levels instead of recursing', () => {
|
|
156
|
+
let deep: Record<string, unknown> = { end: true }
|
|
157
|
+
for (let i = 0; i < 25; i++) {
|
|
158
|
+
deep = { next: deep }
|
|
159
|
+
}
|
|
160
|
+
const encoded = JSON.stringify(toOtlpAnyValue(deep))
|
|
161
|
+
expect(encoded).toContain('[Truncated]')
|
|
162
|
+
expect(encoded.split('"next"').length - 1).toBe(20)
|
|
163
|
+
})
|
|
164
|
+
|
|
165
|
+
it('marks a throwing getter without losing the rest of the object', () => {
|
|
166
|
+
const attrs = {
|
|
167
|
+
ok: 1,
|
|
168
|
+
get bad(): number {
|
|
169
|
+
throw new Error('getter blew up')
|
|
170
|
+
},
|
|
171
|
+
}
|
|
172
|
+
expect(() => toOtlpKeyValueList(attrs)).not.toThrow()
|
|
173
|
+
expect(toOtlpKeyValueList(attrs)).toEqual([
|
|
174
|
+
{ key: 'ok', value: { intValue: '1' } },
|
|
175
|
+
{ key: 'bad', value: { stringValue: '[Unserializable]' } },
|
|
176
|
+
])
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
// for...in walks the prototype chain once own keys are exhausted.
|
|
180
|
+
it('ignores inherited enumerable properties', () => {
|
|
181
|
+
const inherited: Record<string, unknown> = Object.create({ fromPrototype: 'leaked' })
|
|
182
|
+
inherited.own = 1
|
|
183
|
+
expect(toOtlpAnyValue(inherited)).toEqual({
|
|
184
|
+
kvlistValue: { values: [{ key: 'own', value: { intValue: '1' } }] },
|
|
185
|
+
})
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
// `String(fn)` would put the function's source text on the wire.
|
|
189
|
+
it('marks function and symbol values instead of stringifying them', () => {
|
|
190
|
+
expect(toOtlpAnyValue({ handler: () => 1, retries: 2 } as unknown as LogAttributeValue)).toEqual({
|
|
191
|
+
kvlistValue: {
|
|
192
|
+
values: [
|
|
193
|
+
{ key: 'handler', value: { stringValue: '[Function]' } },
|
|
194
|
+
{ key: 'retries', value: { intValue: '2' } },
|
|
195
|
+
],
|
|
196
|
+
},
|
|
197
|
+
})
|
|
198
|
+
expect(toOtlpAnyValue({ sym: Symbol('x') } as unknown as LogAttributeValue)).toEqual({
|
|
199
|
+
kvlistValue: { values: [{ key: 'sym', value: { stringValue: 'Symbol(x)' } }] },
|
|
200
|
+
})
|
|
201
|
+
})
|
|
202
|
+
|
|
203
|
+
// dayjs, Decimal, ORM documents.
|
|
204
|
+
it('honours toJSON', () => {
|
|
205
|
+
const wrapped = { toJSON: () => ({ amount: 5 }) }
|
|
206
|
+
expect(toOtlpAnyValue(wrapped as unknown as LogAttributeValue)).toEqual({
|
|
207
|
+
kvlistValue: { values: [{ key: 'amount', value: { intValue: '5' } }] },
|
|
208
|
+
})
|
|
209
|
+
})
|
|
210
|
+
|
|
211
|
+
it('falls back to the plain walk when toJSON throws', () => {
|
|
212
|
+
const wrapped = {
|
|
213
|
+
kept: 1,
|
|
214
|
+
toJSON: () => {
|
|
215
|
+
throw new Error('nope')
|
|
216
|
+
},
|
|
217
|
+
}
|
|
218
|
+
expect(toOtlpAnyValue(wrapped as unknown as LogAttributeValue)).toEqual({
|
|
219
|
+
kvlistValue: {
|
|
220
|
+
values: [
|
|
221
|
+
{ key: 'kept', value: { intValue: '1' } },
|
|
222
|
+
{ key: 'toJSON', value: { stringValue: '[Function]' } },
|
|
223
|
+
],
|
|
224
|
+
},
|
|
225
|
+
})
|
|
226
|
+
})
|
|
227
|
+
|
|
228
|
+
// A toJSON returning its own object is a cycle like any other.
|
|
229
|
+
it('marks a cycle that runs through toJSON', () => {
|
|
230
|
+
const cyclic: Record<string, unknown> = {}
|
|
231
|
+
cyclic.toJSON = () => ({ inner: cyclic })
|
|
232
|
+
expect(toOtlpAnyValue(cyclic)).toEqual({
|
|
233
|
+
kvlistValue: { values: [{ key: 'inner', value: { stringValue: '[Circular]' } }] },
|
|
234
|
+
})
|
|
235
|
+
})
|
|
236
|
+
|
|
237
|
+
// Both `null` and `{}` here are rejected for the whole request; iOS and
|
|
238
|
+
// Android drop them too.
|
|
239
|
+
it('drops holes and nullish elements from arrays', () => {
|
|
240
|
+
// eslint-disable-next-line no-sparse-arrays
|
|
241
|
+
expect(toOtlpAnyValue([1, , 3])).toEqual({
|
|
242
|
+
arrayValue: { values: [{ intValue: '1' }, { intValue: '3' }] },
|
|
243
|
+
})
|
|
244
|
+
expect(toOtlpAnyValue([1, null, undefined, 3])).toEqual({
|
|
245
|
+
arrayValue: { values: [{ intValue: '1' }, { intValue: '3' }] },
|
|
246
|
+
})
|
|
247
|
+
})
|
|
248
|
+
|
|
249
|
+
it('stops encoding array items once the node budget is spent', () => {
|
|
250
|
+
const row: Record<string, number> = {}
|
|
251
|
+
for (let i = 0; i < 20; i++) {
|
|
252
|
+
row[`k${i}`] = i
|
|
253
|
+
}
|
|
254
|
+
const wide = Array.from({ length: 1000 }, () => ({ ...row }))
|
|
255
|
+
const values = toOtlpAnyValue(wide).arrayValue!.values
|
|
256
|
+
expect(values[values.length - 1]).toEqual({ stringValue: '[Truncated]' })
|
|
257
|
+
// One marker, not one per unencodable item.
|
|
258
|
+
expect(values.filter((v) => v.stringValue === '[Truncated]')).toHaveLength(1)
|
|
259
|
+
})
|
|
260
|
+
|
|
261
|
+
it('caps a shared object graph instead of expanding it', () => {
|
|
262
|
+
let graph: Record<string, unknown> = { leaf: true }
|
|
263
|
+
for (let i = 0; i < 20; i++) {
|
|
264
|
+
graph = { a: graph, b: graph }
|
|
265
|
+
}
|
|
266
|
+
const encoded = JSON.stringify(toOtlpAnyValue(graph))
|
|
267
|
+
expect(encoded).toContain('[Truncated]')
|
|
268
|
+
expect(encoded.length).toBeLessThan(1_000_000)
|
|
269
|
+
})
|
|
270
|
+
|
|
271
|
+
it('caps a very wide object without inventing an attribute key', () => {
|
|
272
|
+
const wide: Record<string, number> = {}
|
|
273
|
+
for (let i = 0; i < 5000; i++) {
|
|
274
|
+
wide[`k${i}`] = i
|
|
275
|
+
}
|
|
276
|
+
const logger = { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(), critical: jest.fn() }
|
|
277
|
+
const values = toOtlpAnyValue(wide, logger as any).kvlistValue!.values
|
|
278
|
+
expect(values).toHaveLength(1000)
|
|
279
|
+
expect(values.every((v) => v.key.startsWith('k'))).toBe(true)
|
|
280
|
+
expect(logger.debug).toHaveBeenCalledWith(expect.stringContaining('truncated'))
|
|
281
|
+
})
|
|
282
|
+
|
|
283
|
+
// Why the encoder does not delegate to toJsonSafeValue: that maps them to null.
|
|
284
|
+
it('keeps non-finite floats as strings inside nested objects', () => {
|
|
285
|
+
expect(toOtlpAnyValue({ nested: { ratio: NaN } })).toEqual({
|
|
286
|
+
kvlistValue: {
|
|
287
|
+
values: [
|
|
288
|
+
{
|
|
289
|
+
key: 'nested',
|
|
290
|
+
value: { kvlistValue: { values: [{ key: 'ratio', value: { stringValue: 'NaN' } }] } },
|
|
291
|
+
},
|
|
292
|
+
],
|
|
293
|
+
},
|
|
294
|
+
})
|
|
295
|
+
})
|
|
296
|
+
|
|
297
|
+
// A lone surrogate survives JSON.stringify as a \uD800 escape, which the
|
|
298
|
+
// server rejects for the whole request.
|
|
299
|
+
it('replaces unpaired surrogates in values and keys', () => {
|
|
300
|
+
expect(toOtlpAnyValue('ok\ud83d')).toEqual({ stringValue: 'ok\ufffd' })
|
|
301
|
+
expect(toOtlpAnyValue({ nested: 'ok\ud83d' })).toEqual({
|
|
302
|
+
kvlistValue: { values: [{ key: 'nested', value: { stringValue: 'ok\ufffd' } }] },
|
|
303
|
+
})
|
|
304
|
+
expect(toOtlpKeyValueList({ 'key\ud83d': 1 })).toEqual([{ key: 'key\ufffd', value: { intValue: '1' } }])
|
|
305
|
+
})
|
|
306
|
+
|
|
307
|
+
it('encodes empty containers with an explicit values array', () => {
|
|
308
|
+
expect(toOtlpAnyValue({})).toEqual({ kvlistValue: { values: [] } })
|
|
309
|
+
expect(toOtlpAnyValue([])).toEqual({ arrayValue: { values: [] } })
|
|
310
|
+
})
|
|
311
|
+
|
|
312
|
+
it('keeps a Date whose toISOString is overridden out of the wire format', () => {
|
|
313
|
+
const broken = new Date('2026-08-20T10:00:00.000Z')
|
|
314
|
+
|
|
315
|
+
;(broken as any).toISOString = () => ({})
|
|
316
|
+
expect(typeof toOtlpAnyValue(broken as unknown as LogAttributeValue).stringValue).toBe('string')
|
|
317
|
+
})
|
|
318
|
+
|
|
319
|
+
it('encodes sibling references to one object twice, not as circular', () => {
|
|
320
|
+
const shared = { id: 1 }
|
|
321
|
+
expect(toOtlpAnyValue({ a: shared, b: shared })).toEqual({
|
|
322
|
+
kvlistValue: {
|
|
323
|
+
values: [
|
|
324
|
+
{ key: 'a', value: { kvlistValue: { values: [{ key: 'id', value: { intValue: '1' } }] } } },
|
|
325
|
+
{ key: 'b', value: { kvlistValue: { values: [{ key: 'id', value: { intValue: '1' } }] } } },
|
|
326
|
+
],
|
|
327
|
+
},
|
|
328
|
+
})
|
|
329
|
+
})
|
|
330
|
+
})
|
|
331
|
+
|
|
332
|
+
describe('toOtlpKeyValueList', () => {
|
|
333
|
+
it('converts a record to key-value list', () => {
|
|
334
|
+
expect(
|
|
335
|
+
toOtlpKeyValueList({
|
|
336
|
+
name: 'test',
|
|
337
|
+
count: 5,
|
|
338
|
+
active: true,
|
|
339
|
+
})
|
|
340
|
+
).toEqual([
|
|
341
|
+
{ key: 'name', value: { stringValue: 'test' } },
|
|
342
|
+
{ key: 'count', value: { intValue: '5' } },
|
|
343
|
+
{ key: 'active', value: { boolValue: true } },
|
|
344
|
+
])
|
|
345
|
+
})
|
|
346
|
+
|
|
347
|
+
it('handles empty record', () => {
|
|
348
|
+
expect(toOtlpKeyValueList({})).toEqual([])
|
|
349
|
+
})
|
|
350
|
+
|
|
351
|
+
it('skips null and undefined values', () => {
|
|
352
|
+
expect(
|
|
353
|
+
toOtlpKeyValueList({
|
|
354
|
+
kept: 'yes',
|
|
355
|
+
nullish: null,
|
|
356
|
+
missing: undefined,
|
|
357
|
+
})
|
|
358
|
+
).toEqual([{ key: 'kept', value: { stringValue: 'yes' } }])
|
|
359
|
+
})
|
|
360
|
+
})
|
|
361
|
+
})
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// The OTLP `AnyValue` encoder, shared by the logs, metrics and traces senders.
|
|
2
|
+
//
|
|
3
|
+
// Every value here comes from application code, so the encoder's job is to
|
|
4
|
+
// produce a payload the ingestion service accepts no matter what it is handed.
|
|
5
|
+
// A value the server refuses doesn't fail on its own — it 400s the whole
|
|
6
|
+
// request, taking every other record in the batch with it.
|
|
7
|
+
|
|
8
|
+
import type { OtlpAnyValue, OtlpKeyValue } from '@posthog/types'
|
|
9
|
+
import type { Logger } from '../types'
|
|
10
|
+
import { isArray, isBoolean, isNull, isNullish, isUndefined } from './type-utils'
|
|
11
|
+
import {
|
|
12
|
+
CIRCULAR_VALUE,
|
|
13
|
+
FUNCTION_VALUE,
|
|
14
|
+
MAX_JSON_SAFE_VALUE_DEPTH,
|
|
15
|
+
MAX_JSON_SAFE_VALUE_ITEMS,
|
|
16
|
+
MAX_JSON_SAFE_VALUE_NODES,
|
|
17
|
+
sanitizeString,
|
|
18
|
+
TRUNCATED_VALUE,
|
|
19
|
+
UNSERIALIZABLE_VALUE,
|
|
20
|
+
} from './json-utils'
|
|
21
|
+
|
|
22
|
+
// 2^63 — one past int64 max.
|
|
23
|
+
const INT64_RANGE_LIMIT = 9223372036854775808
|
|
24
|
+
|
|
25
|
+
// The same bound for the bigint branch. A decimal string rather than a `n`
|
|
26
|
+
// literal: this module reaches the browser bundle, which compiles to ES5, and
|
|
27
|
+
// a bigint literal there is a syntax error rather than a runtime fallback.
|
|
28
|
+
const INT64_RANGE_LIMIT_DECIMAL = '9223372036854775808'
|
|
29
|
+
|
|
30
|
+
const propertyIsEnumerable = Object.prototype.propertyIsEnumerable
|
|
31
|
+
|
|
32
|
+
interface EncodeState {
|
|
33
|
+
/** Containers on the current path, so a back-reference becomes a marker. */
|
|
34
|
+
ancestors: WeakSet<object>
|
|
35
|
+
remainingNodes: number
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function newState(): EncodeState {
|
|
39
|
+
return { ancestors: new WeakSet(), remainingNodes: MAX_JSON_SAFE_VALUE_NODES }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function toOtlpAnyValue(value: unknown, logger?: Logger): OtlpAnyValue {
|
|
43
|
+
try {
|
|
44
|
+
return encodeAnyValue(value, logger, newState(), 0)
|
|
45
|
+
} catch {
|
|
46
|
+
// Runs inside `captureLog`, the metrics flush and span encoding: an error
|
|
47
|
+
// escaping here surfaces in the caller's own code.
|
|
48
|
+
return { stringValue: UNSERIALIZABLE_VALUE }
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function toOtlpKeyValueList(attrs: Record<string, unknown>, logger?: Logger): OtlpKeyValue[] {
|
|
53
|
+
try {
|
|
54
|
+
return encodeKeyValueList(attrs, logger, newState(), 0)
|
|
55
|
+
} catch {
|
|
56
|
+
return []
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function encodeBigInt(value: bigint, logger: Logger | undefined): OtlpAnyValue {
|
|
61
|
+
const decimal = value.toString()
|
|
62
|
+
const limit = BigInt(INT64_RANGE_LIMIT_DECIMAL)
|
|
63
|
+
if (value >= limit || value < -limit) {
|
|
64
|
+
logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`)
|
|
65
|
+
return { stringValue: decimal }
|
|
66
|
+
}
|
|
67
|
+
return { intValue: decimal }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function encodeAnyValue(value: unknown, logger: Logger | undefined, state: EncodeState, depth: number): OtlpAnyValue {
|
|
71
|
+
if (state.remainingNodes <= 0) {
|
|
72
|
+
return { stringValue: TRUNCATED_VALUE }
|
|
73
|
+
}
|
|
74
|
+
state.remainingNodes--
|
|
75
|
+
|
|
76
|
+
if (isBoolean(value)) {
|
|
77
|
+
return { boolValue: value }
|
|
78
|
+
}
|
|
79
|
+
// Reaching this branch proves BigInt exists, so the limit can be built here
|
|
80
|
+
// rather than at module load.
|
|
81
|
+
if (typeof value === 'bigint') {
|
|
82
|
+
return encodeBigInt(value, logger)
|
|
83
|
+
}
|
|
84
|
+
// typeof, not core's isNumber, which excludes NaN — proto3 JSON distinguishes
|
|
85
|
+
// a non-finite float from an ordinary string.
|
|
86
|
+
if (typeof value === 'number') {
|
|
87
|
+
if (!Number.isFinite(value)) {
|
|
88
|
+
return { stringValue: String(value) }
|
|
89
|
+
}
|
|
90
|
+
if (Number.isInteger(value)) {
|
|
91
|
+
if (Number.isSafeInteger(value)) {
|
|
92
|
+
return { intValue: String(value) }
|
|
93
|
+
}
|
|
94
|
+
// Past MAX_SAFE_INTEGER only BigInt gives the double's exact decimal:
|
|
95
|
+
// `String(-(2**63))` lands 192 below int64 min, outside the field it is
|
|
96
|
+
// about to be parsed into. Without BigInt the value rides as a string,
|
|
97
|
+
// which is never range-checked.
|
|
98
|
+
if (typeof BigInt === 'undefined') {
|
|
99
|
+
return { stringValue: String(value) }
|
|
100
|
+
}
|
|
101
|
+
const decimal = BigInt(value).toString()
|
|
102
|
+
if (value >= INT64_RANGE_LIMIT || value < -INT64_RANGE_LIMIT) {
|
|
103
|
+
// An out-of-range intValue 400s the whole logs request; on the metrics
|
|
104
|
+
// path it is swallowed server-side and the metric just disappears.
|
|
105
|
+
logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`)
|
|
106
|
+
return { stringValue: decimal }
|
|
107
|
+
}
|
|
108
|
+
return { intValue: decimal }
|
|
109
|
+
}
|
|
110
|
+
return { doubleValue: value }
|
|
111
|
+
}
|
|
112
|
+
if (typeof value === 'string') {
|
|
113
|
+
return { stringValue: sanitizeString(value) }
|
|
114
|
+
}
|
|
115
|
+
// `String(value)` would put a function's source text on the wire.
|
|
116
|
+
if (typeof value === 'function') {
|
|
117
|
+
return { stringValue: FUNCTION_VALUE }
|
|
118
|
+
}
|
|
119
|
+
if (typeof value === 'symbol') {
|
|
120
|
+
return { stringValue: String(value) }
|
|
121
|
+
}
|
|
122
|
+
if (typeof value === 'object' && value !== null) {
|
|
123
|
+
if (state.ancestors.has(value)) {
|
|
124
|
+
return { stringValue: CIRCULAR_VALUE }
|
|
125
|
+
}
|
|
126
|
+
if (depth >= MAX_JSON_SAFE_VALUE_DEPTH) {
|
|
127
|
+
return { stringValue: TRUNCATED_VALUE }
|
|
128
|
+
}
|
|
129
|
+
if (value instanceof Date) {
|
|
130
|
+
const time = value.getTime()
|
|
131
|
+
const iso = Number.isFinite(time) ? value.toISOString() : String(value)
|
|
132
|
+
// An overridden toISOString can return a non-string, which the server
|
|
133
|
+
// refuses for the whole request.
|
|
134
|
+
return { stringValue: typeof iso === 'string' ? sanitizeString(iso) : String(iso) }
|
|
135
|
+
}
|
|
136
|
+
// Registered before the toJSON probe: a toJSON returning a structure that
|
|
137
|
+
// references its own object is a cycle like any other.
|
|
138
|
+
state.ancestors.add(value)
|
|
139
|
+
try {
|
|
140
|
+
// The representation a value defines for itself — dayjs, Decimal, an ORM
|
|
141
|
+
// document, and a cross-realm Date that fails the `instanceof` above.
|
|
142
|
+
try {
|
|
143
|
+
const toJSON = (value as { toJSON?: unknown }).toJSON
|
|
144
|
+
if (typeof toJSON === 'function') {
|
|
145
|
+
return encodeAnyValue(toJSON.call(value), logger, state, depth + 1)
|
|
146
|
+
}
|
|
147
|
+
} catch {
|
|
148
|
+
// A throwing toJSON falls through to the plain walk.
|
|
149
|
+
}
|
|
150
|
+
if (isArray(value)) {
|
|
151
|
+
return { arrayValue: { values: encodeArrayValues(value, logger, state, depth + 1) } }
|
|
152
|
+
}
|
|
153
|
+
return {
|
|
154
|
+
kvlistValue: {
|
|
155
|
+
values: encodeKeyValueList(value as Record<string, unknown>, logger, state, depth + 1),
|
|
156
|
+
},
|
|
157
|
+
}
|
|
158
|
+
} finally {
|
|
159
|
+
// Siblings that reference the same object are duplication, not a cycle.
|
|
160
|
+
state.ancestors.delete(value)
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return { stringValue: sanitizeString(String(value)) }
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function encodeArrayValues(
|
|
167
|
+
values: unknown[],
|
|
168
|
+
logger: Logger | undefined,
|
|
169
|
+
state: EncodeState,
|
|
170
|
+
depth: number
|
|
171
|
+
): OtlpAnyValue[] {
|
|
172
|
+
const result: OtlpAnyValue[] = []
|
|
173
|
+
const itemCount = Math.min(values.length, MAX_JSON_SAFE_VALUE_ITEMS)
|
|
174
|
+
let index = 0
|
|
175
|
+
for (; index < itemCount && state.remainingNodes > 0; index++) {
|
|
176
|
+
try {
|
|
177
|
+
const element = index in values ? values[index] : undefined
|
|
178
|
+
// Dropped: proto3 JSON has no null AnyValue, and both `null` and `{}` here
|
|
179
|
+
// are rejected for the whole request.
|
|
180
|
+
if (isNullish(element)) {
|
|
181
|
+
continue
|
|
182
|
+
}
|
|
183
|
+
result.push(encodeAnyValue(element, logger, state, depth))
|
|
184
|
+
} catch {
|
|
185
|
+
result.push({ stringValue: UNSERIALIZABLE_VALUE })
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (values.length > index) {
|
|
189
|
+
result.push({ stringValue: TRUNCATED_VALUE })
|
|
190
|
+
}
|
|
191
|
+
return result
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function encodeKeyValueList(
|
|
195
|
+
attrs: Record<string, unknown>,
|
|
196
|
+
logger: Logger | undefined,
|
|
197
|
+
state: EncodeState,
|
|
198
|
+
depth: number
|
|
199
|
+
): OtlpKeyValue[] {
|
|
200
|
+
const result: OtlpKeyValue[] = []
|
|
201
|
+
for (const key in attrs) {
|
|
202
|
+
// for...in walks the prototype chain once own keys are exhausted. Skipped
|
|
203
|
+
// rather than broken out of: a proxy can yield keys in any order.
|
|
204
|
+
if (!propertyIsEnumerable.call(attrs, key)) {
|
|
205
|
+
continue
|
|
206
|
+
}
|
|
207
|
+
if (result.length >= MAX_JSON_SAFE_VALUE_ITEMS || state.remainingNodes <= 0) {
|
|
208
|
+
// Reported rather than written into the attributes: a synthetic key would
|
|
209
|
+
// land in the user's own namespace and could collide with a real one.
|
|
210
|
+
logger?.debug('Attributes truncated: the value exceeds the OTLP encoder budget')
|
|
211
|
+
break
|
|
212
|
+
}
|
|
213
|
+
try {
|
|
214
|
+
const value = attrs[key]
|
|
215
|
+
if (isNull(value) || isUndefined(value)) {
|
|
216
|
+
continue
|
|
217
|
+
}
|
|
218
|
+
result.push({ key: sanitizeString(key), value: encodeAnyValue(value, logger, state, depth) })
|
|
219
|
+
} catch {
|
|
220
|
+
// A getter that throws costs its own key, not the whole record.
|
|
221
|
+
result.push({ key: sanitizeString(key), value: { stringValue: UNSERIALIZABLE_VALUE } })
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return result
|
|
225
|
+
}
|
|
@@ -57,10 +57,16 @@ const DUCKDUCKGO = 'DuckDuckGo'
|
|
|
57
57
|
const PALE_MOON = 'Pale Moon'
|
|
58
58
|
const WATERFOX = 'Waterfox'
|
|
59
59
|
const BRAVE = 'Brave'
|
|
60
|
+
const CLAUDE = 'Claude'
|
|
61
|
+
const CODEX = 'Codex'
|
|
62
|
+
const CHATGPT = 'ChatGPT'
|
|
60
63
|
const GOOGLE_SEARCH_APP = 'Google Search App'
|
|
61
64
|
|
|
62
65
|
const BROWSER_VERSION_REGEX_SUFFIX = '(\\d+(\\.\\d+)?)'
|
|
63
66
|
const DEFAULT_BROWSER_VERSION_REGEX = new RegExp('Version/' + BROWSER_VERSION_REGEX_SUFFIX)
|
|
67
|
+
const AI_APP_VERSION_REGEX = new RegExp(
|
|
68
|
+
'(' + CLAUDE + '|' + CODEX + '|' + CHATGPT + ')\\/' + BROWSER_VERSION_REGEX_SUFFIX
|
|
69
|
+
)
|
|
64
70
|
|
|
65
71
|
/**
|
|
66
72
|
* Hints from sources outside the User-Agent string. These let us identify Brave
|
|
@@ -82,10 +88,10 @@ function browserFromHints(hints: BrowserDetectionHints | undefined): string | nu
|
|
|
82
88
|
}
|
|
83
89
|
|
|
84
90
|
/**
|
|
85
|
-
* Opt-in tweaks to UA-string detection.
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
*
|
|
91
|
+
* Opt-in tweaks to UA-string detection. Turning one on reattributes browsers
|
|
92
|
+
* that were previously reported as something else, so the host SDK gates
|
|
93
|
+
* shifts big enough to move users' metrics behind its `2026-05-30` config
|
|
94
|
+
* defaults. Smaller reattributions ship unconditionally in `detectBrowser`.
|
|
89
95
|
*/
|
|
90
96
|
export interface BrowserDetectionOptions {
|
|
91
97
|
// Surface the Google Search App as its own browser via its `GSA/` UA marker
|
|
@@ -181,8 +187,9 @@ export const detectBrowser = function (
|
|
|
181
187
|
} else if (includes(user_agent, EDGE) || includes(user_agent, 'Edg/')) {
|
|
182
188
|
return MICROSOFT_EDGE
|
|
183
189
|
}
|
|
184
|
-
// Chromium forks that DO stamp themselves into the
|
|
185
|
-
// checked before Chrome because their UA also contains
|
|
190
|
+
// Chromium forks and Chromium-based apps that DO stamp themselves into the
|
|
191
|
+
// UA. These must be checked before Chrome because their UA also contains
|
|
192
|
+
// `Chrome/`.
|
|
186
193
|
else if (includes(user_agent, VIVALDI + '/')) {
|
|
187
194
|
return VIVALDI
|
|
188
195
|
} else if (includes(user_agent, 'YaBrowser/')) {
|
|
@@ -191,6 +198,12 @@ export const detectBrowser = function (
|
|
|
191
198
|
return WHALE
|
|
192
199
|
} else if (includes(user_agent, DUCKDUCKGO + '/') || includes(user_agent, 'Ddg/')) {
|
|
193
200
|
return DUCKDUCKGO
|
|
201
|
+
} else if (includes(user_agent, CLAUDE + '/')) {
|
|
202
|
+
return CLAUDE
|
|
203
|
+
} else if (includes(user_agent, CODEX + '/')) {
|
|
204
|
+
return CODEX
|
|
205
|
+
} else if (includes(user_agent, CHATGPT + '/')) {
|
|
206
|
+
return CHATGPT
|
|
194
207
|
} else if (includes(user_agent, 'FBIOS')) {
|
|
195
208
|
return FACEBOOK + ' ' + MOBILE
|
|
196
209
|
} else if (includes(user_agent, 'UCWEB') || includes(user_agent, 'UCBrowser')) {
|
|
@@ -257,6 +270,9 @@ const versionRegexes: Record<string, RegExp[]> = {
|
|
|
257
270
|
// Brave don't, which is why hint-based Brave detection returns a null
|
|
258
271
|
// version: we have no UA marker to parse.
|
|
259
272
|
[BRAVE]: [new RegExp(BRAVE + '\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
|
|
273
|
+
[CLAUDE]: [AI_APP_VERSION_REGEX],
|
|
274
|
+
[CODEX]: [AI_APP_VERSION_REGEX],
|
|
275
|
+
[CHATGPT]: [AI_APP_VERSION_REGEX],
|
|
260
276
|
// DuckDuckGo on iOS uses `Ddg/`, on Android/desktop preview it uses `DuckDuckGo/`.
|
|
261
277
|
[DUCKDUCKGO]: [new RegExp('(DuckDuckGo|Ddg)\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
|
|
262
278
|
[PALE_MOON]: [new RegExp('PaleMoon\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
|