@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.
@@ -1,13 +1,6 @@
1
- import type { CaptureLogOptions, LogAttributeValue, LogSeverityLevel } from '@posthog/types'
1
+ import type { CaptureLogOptions, LogSeverityLevel } from '@posthog/types'
2
2
  import type { LogSdkContext } from './types'
3
- import {
4
- buildOtlpLogRecord,
5
- buildOtlpLogsPayload,
6
- getOtlpSeverityNumber,
7
- getOtlpSeverityText,
8
- toOtlpAnyValue,
9
- toOtlpKeyValueList,
10
- } from './logs-utils'
3
+ import { buildOtlpLogRecord, buildOtlpLogsPayload, getOtlpSeverityNumber, getOtlpSeverityText } from './logs-utils'
11
4
 
12
5
  const browserSdkContext: LogSdkContext = {
13
6
  distinctId: 'user-123',
@@ -64,317 +57,6 @@ describe('logs-utils', () => {
64
57
  })
65
58
  })
66
59
 
67
- describe('toOtlpAnyValue', () => {
68
- it('converts strings', () => {
69
- expect(toOtlpAnyValue('hello')).toEqual({ stringValue: 'hello' })
70
- })
71
-
72
- it('converts integers to decimal strings', () => {
73
- expect(toOtlpAnyValue(42)).toEqual({ intValue: '42' })
74
- expect(toOtlpAnyValue(0)).toEqual({ intValue: '0' })
75
- expect(toOtlpAnyValue(-7)).toEqual({ intValue: '-7' })
76
- })
77
-
78
- // Spec: outside int64 it is a stringValue, never an intValue.
79
- it('converts integers outside int64 to stringValue', () => {
80
- expect(toOtlpAnyValue(2 ** 63)).toEqual({ stringValue: '9223372036854775808' })
81
- expect(toOtlpAnyValue(-(2 ** 64))).toEqual({ stringValue: '-18446744073709551616' })
82
- expect(toOtlpAnyValue(1e21)).toEqual({ stringValue: '1000000000000000000000' })
83
- })
84
-
85
- it('logs a debug line when an integer falls outside int64', () => {
86
- const logger = { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(), critical: jest.fn() }
87
- toOtlpAnyValue(2 ** 63, logger as any)
88
- expect(logger.debug).toHaveBeenCalledWith(expect.stringContaining('outside the int64 range'))
89
- })
90
-
91
- it('keeps int64 min as intValue', () => {
92
- // In range, but `String` renders it 192 below int64 min, so the decimal
93
- // has to come from BigInt.
94
- expect(toOtlpAnyValue(-(2 ** 63))).toEqual({ intValue: '-9223372036854775808' })
95
- })
96
-
97
- it('keeps large in-range integers exact', () => {
98
- expect(toOtlpAnyValue(Number.MAX_SAFE_INTEGER)).toEqual({ intValue: '9007199254740991' })
99
- // The largest double below 2^63 — no double exists between the two.
100
- expect(toOtlpAnyValue(9223372036854774784)).toEqual({ intValue: '9223372036854774784' })
101
- expect(toOtlpAnyValue(2 ** 62)).toEqual({ intValue: '4611686018427387904' })
102
- })
103
-
104
- it('converts floats to doubleValue', () => {
105
- expect(toOtlpAnyValue(3.14)).toEqual({ doubleValue: 3.14 })
106
- })
107
-
108
- it('converts booleans', () => {
109
- expect(toOtlpAnyValue(true)).toEqual({ boolValue: true })
110
- expect(toOtlpAnyValue(false)).toEqual({ boolValue: false })
111
- })
112
-
113
- // JSON has no representation for non-finite floats; without explicit
114
- // handling, JSON.stringify silently turns them into `null` and the value
115
- // is lost server-side.
116
- it('converts NaN to stringValue', () => {
117
- expect(toOtlpAnyValue(NaN)).toEqual({ stringValue: 'NaN' })
118
- })
119
-
120
- it('converts +Infinity to stringValue', () => {
121
- expect(toOtlpAnyValue(Infinity)).toEqual({ stringValue: 'Infinity' })
122
- })
123
-
124
- it('converts -Infinity to stringValue', () => {
125
- expect(toOtlpAnyValue(-Infinity)).toEqual({ stringValue: '-Infinity' })
126
- })
127
-
128
- it('converts arrays of strings to arrayValue', () => {
129
- expect(toOtlpAnyValue(['a', 'b'])).toEqual({
130
- arrayValue: { values: [{ stringValue: 'a' }, { stringValue: 'b' }] },
131
- })
132
- })
133
-
134
- it('converts mixed primitive arrays recursively', () => {
135
- expect(toOtlpAnyValue([1, 'x', true])).toEqual({
136
- arrayValue: {
137
- values: [{ intValue: '1' }, { stringValue: 'x' }, { boolValue: true }],
138
- },
139
- })
140
- })
141
-
142
- it('converts plain objects to kvlistValue', () => {
143
- expect(toOtlpAnyValue({ a: 1, b: 'two' })).toEqual({
144
- kvlistValue: {
145
- values: [
146
- { key: 'a', value: { intValue: '1' } },
147
- { key: 'b', value: { stringValue: 'two' } },
148
- ],
149
- },
150
- })
151
- })
152
-
153
- it('converts nested objects recursively', () => {
154
- expect(toOtlpAnyValue({ outer: { inner: 1 } })).toEqual({
155
- kvlistValue: {
156
- values: [
157
- {
158
- key: 'outer',
159
- value: { kvlistValue: { values: [{ key: 'inner', value: { intValue: '1' } }] } },
160
- },
161
- ],
162
- },
163
- })
164
- })
165
-
166
- it('drops null and undefined keys inside objects', () => {
167
- expect(toOtlpAnyValue({ kept: 1, gone: null, alsoGone: undefined })).toEqual({
168
- kvlistValue: { values: [{ key: 'kept', value: { intValue: '1' } }] },
169
- })
170
- })
171
-
172
- // Not in LogAttributeValue, but reachable at runtime from untyped callers.
173
- it('encodes Dates as ISO strings', () => {
174
- expect(toOtlpAnyValue(new Date('2026-08-20T10:00:00.000Z') as unknown as LogAttributeValue)).toEqual({
175
- stringValue: '2026-08-20T10:00:00.000Z',
176
- })
177
- })
178
-
179
- it('marks circular references instead of recursing', () => {
180
- const cyclic: Record<string, unknown> = { name: 'root' }
181
- cyclic.self = cyclic
182
- expect(toOtlpAnyValue(cyclic)).toEqual({
183
- kvlistValue: {
184
- values: [
185
- { key: 'name', value: { stringValue: 'root' } },
186
- { key: 'self', value: { stringValue: '[Circular]' } },
187
- ],
188
- },
189
- })
190
- })
191
-
192
- // An escaping error would surface in the caller's application code.
193
- it('does not throw on an object nested past the depth cap', () => {
194
- let deep: Record<string, unknown> = { end: true }
195
- for (let i = 0; i < 25000; i++) {
196
- deep = { next: deep }
197
- }
198
- expect(() => toOtlpAnyValue(deep)).not.toThrow()
199
- })
200
-
201
- it('truncates at exactly 20 levels instead of recursing', () => {
202
- let deep: Record<string, unknown> = { end: true }
203
- for (let i = 0; i < 25; i++) {
204
- deep = { next: deep }
205
- }
206
- const encoded = JSON.stringify(toOtlpAnyValue(deep))
207
- expect(encoded).toContain('[Truncated]')
208
- expect(encoded.split('"next"').length - 1).toBe(20)
209
- })
210
-
211
- it('marks a throwing getter without losing the rest of the object', () => {
212
- const attrs = {
213
- ok: 1,
214
- get bad(): number {
215
- throw new Error('getter blew up')
216
- },
217
- }
218
- expect(() => toOtlpKeyValueList(attrs)).not.toThrow()
219
- expect(toOtlpKeyValueList(attrs)).toEqual([
220
- { key: 'ok', value: { intValue: '1' } },
221
- { key: 'bad', value: { stringValue: '[Unserializable]' } },
222
- ])
223
- })
224
-
225
- // for...in walks the prototype chain once own keys are exhausted.
226
- it('ignores inherited enumerable properties', () => {
227
- const inherited: Record<string, unknown> = Object.create({ fromPrototype: 'leaked' })
228
- inherited.own = 1
229
- expect(toOtlpAnyValue(inherited)).toEqual({
230
- kvlistValue: { values: [{ key: 'own', value: { intValue: '1' } }] },
231
- })
232
- })
233
-
234
- // `String(fn)` would put the function's source text on the wire.
235
- it('marks function and symbol values instead of stringifying them', () => {
236
- expect(toOtlpAnyValue({ handler: () => 1, retries: 2 } as unknown as LogAttributeValue)).toEqual({
237
- kvlistValue: {
238
- values: [
239
- { key: 'handler', value: { stringValue: '[Function]' } },
240
- { key: 'retries', value: { intValue: '2' } },
241
- ],
242
- },
243
- })
244
- expect(toOtlpAnyValue({ sym: Symbol('x') } as unknown as LogAttributeValue)).toEqual({
245
- kvlistValue: { values: [{ key: 'sym', value: { stringValue: 'Symbol(x)' } }] },
246
- })
247
- })
248
-
249
- // dayjs, Decimal, ORM documents.
250
- it('honours toJSON', () => {
251
- const wrapped = { toJSON: () => ({ amount: 5 }) }
252
- expect(toOtlpAnyValue(wrapped as unknown as LogAttributeValue)).toEqual({
253
- kvlistValue: { values: [{ key: 'amount', value: { intValue: '5' } }] },
254
- })
255
- })
256
-
257
- it('falls back to the plain walk when toJSON throws', () => {
258
- const wrapped = {
259
- kept: 1,
260
- toJSON: () => {
261
- throw new Error('nope')
262
- },
263
- }
264
- expect(toOtlpAnyValue(wrapped as unknown as LogAttributeValue)).toEqual({
265
- kvlistValue: {
266
- values: [
267
- { key: 'kept', value: { intValue: '1' } },
268
- { key: 'toJSON', value: { stringValue: '[Function]' } },
269
- ],
270
- },
271
- })
272
- })
273
-
274
- // A toJSON returning its own object is a cycle like any other.
275
- it('marks a cycle that runs through toJSON', () => {
276
- const cyclic: Record<string, unknown> = {}
277
- cyclic.toJSON = () => ({ inner: cyclic })
278
- expect(toOtlpAnyValue(cyclic)).toEqual({
279
- kvlistValue: { values: [{ key: 'inner', value: { stringValue: '[Circular]' } }] },
280
- })
281
- })
282
-
283
- // Both `null` and `{}` here are rejected for the whole request; iOS and
284
- // Android drop them too.
285
- it('drops holes and nullish elements from arrays', () => {
286
- // eslint-disable-next-line no-sparse-arrays
287
- expect(toOtlpAnyValue([1, , 3])).toEqual({
288
- arrayValue: { values: [{ intValue: '1' }, { intValue: '3' }] },
289
- })
290
- expect(toOtlpAnyValue([1, null, undefined, 3])).toEqual({
291
- arrayValue: { values: [{ intValue: '1' }, { intValue: '3' }] },
292
- })
293
- })
294
-
295
- it('stops encoding array items once the node budget is spent', () => {
296
- const row: Record<string, number> = {}
297
- for (let i = 0; i < 20; i++) {
298
- row[`k${i}`] = i
299
- }
300
- const wide = Array.from({ length: 1000 }, () => ({ ...row }))
301
- const values = toOtlpAnyValue(wide).arrayValue!.values
302
- expect(values[values.length - 1]).toEqual({ stringValue: '[Truncated]' })
303
- // One marker, not one per unencodable item.
304
- expect(values.filter((v) => v.stringValue === '[Truncated]')).toHaveLength(1)
305
- })
306
-
307
- it('caps a shared object graph instead of expanding it', () => {
308
- let graph: Record<string, unknown> = { leaf: true }
309
- for (let i = 0; i < 20; i++) {
310
- graph = { a: graph, b: graph }
311
- }
312
- const encoded = JSON.stringify(toOtlpAnyValue(graph))
313
- expect(encoded).toContain('[Truncated]')
314
- expect(encoded.length).toBeLessThan(1_000_000)
315
- })
316
-
317
- it('caps a very wide object without inventing an attribute key', () => {
318
- const wide: Record<string, number> = {}
319
- for (let i = 0; i < 5000; i++) {
320
- wide[`k${i}`] = i
321
- }
322
- const logger = { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(), critical: jest.fn() }
323
- const values = toOtlpAnyValue(wide, logger as any).kvlistValue!.values
324
- expect(values).toHaveLength(1000)
325
- expect(values.every((v) => v.key.startsWith('k'))).toBe(true)
326
- expect(logger.debug).toHaveBeenCalledWith(expect.stringContaining('truncated'))
327
- })
328
-
329
- // Why the encoder does not delegate to toJsonSafeValue: that maps them to null.
330
- it('keeps non-finite floats as strings inside nested objects', () => {
331
- expect(toOtlpAnyValue({ nested: { ratio: NaN } })).toEqual({
332
- kvlistValue: {
333
- values: [
334
- {
335
- key: 'nested',
336
- value: { kvlistValue: { values: [{ key: 'ratio', value: { stringValue: 'NaN' } }] } },
337
- },
338
- ],
339
- },
340
- })
341
- })
342
-
343
- // A lone surrogate survives JSON.stringify as a \uD800 escape, which the
344
- // server rejects for the whole request.
345
- it('replaces unpaired surrogates in values and keys', () => {
346
- expect(toOtlpAnyValue('ok\ud83d')).toEqual({ stringValue: 'ok\ufffd' })
347
- expect(toOtlpAnyValue({ nested: 'ok\ud83d' })).toEqual({
348
- kvlistValue: { values: [{ key: 'nested', value: { stringValue: 'ok\ufffd' } }] },
349
- })
350
- expect(toOtlpKeyValueList({ 'key\ud83d': 1 })).toEqual([{ key: 'key\ufffd', value: { intValue: '1' } }])
351
- })
352
-
353
- it('encodes empty containers with an explicit values array', () => {
354
- expect(toOtlpAnyValue({})).toEqual({ kvlistValue: { values: [] } })
355
- expect(toOtlpAnyValue([])).toEqual({ arrayValue: { values: [] } })
356
- })
357
-
358
- it('keeps a Date whose toISOString is overridden out of the wire format', () => {
359
- const broken = new Date('2026-08-20T10:00:00.000Z')
360
-
361
- ;(broken as any).toISOString = () => ({})
362
- expect(typeof toOtlpAnyValue(broken as unknown as LogAttributeValue).stringValue).toBe('string')
363
- })
364
-
365
- it('encodes sibling references to one object twice, not as circular', () => {
366
- const shared = { id: 1 }
367
- expect(toOtlpAnyValue({ a: shared, b: shared })).toEqual({
368
- kvlistValue: {
369
- values: [
370
- { key: 'a', value: { kvlistValue: { values: [{ key: 'id', value: { intValue: '1' } }] } } },
371
- { key: 'b', value: { kvlistValue: { values: [{ key: 'id', value: { intValue: '1' } }] } } },
372
- ],
373
- },
374
- })
375
- })
376
- })
377
-
378
60
  describe('buildOtlpLogRecord attribute reads', () => {
379
61
  // Reading `options.attributes` happens before the encoder's per-key guard.
380
62
  it('marks an attribute whose getter throws without dropping the record', () => {
@@ -425,36 +107,6 @@ describe('logs-utils', () => {
425
107
  })
426
108
  })
427
109
 
428
- describe('toOtlpKeyValueList', () => {
429
- it('converts a record to key-value list', () => {
430
- expect(
431
- toOtlpKeyValueList({
432
- name: 'test',
433
- count: 5,
434
- active: true,
435
- })
436
- ).toEqual([
437
- { key: 'name', value: { stringValue: 'test' } },
438
- { key: 'count', value: { intValue: '5' } },
439
- { key: 'active', value: { boolValue: true } },
440
- ])
441
- })
442
-
443
- it('handles empty record', () => {
444
- expect(toOtlpKeyValueList({})).toEqual([])
445
- })
446
-
447
- it('skips null and undefined values', () => {
448
- expect(
449
- toOtlpKeyValueList({
450
- kept: 'yes',
451
- nullish: null,
452
- missing: undefined,
453
- })
454
- ).toEqual([{ key: 'kept', value: { stringValue: 'yes' } }])
455
- })
456
- })
457
-
458
110
  describe('buildOtlpLogRecord', () => {
459
111
  it('builds a minimal log record', () => {
460
112
  const record = buildOtlpLogRecord({ body: 'hello world' }, minimalSdkContext)
@@ -2,8 +2,6 @@ import type {
2
2
  CaptureLogOptions,
3
3
  LogAttributeValue,
4
4
  LogSeverityLevel,
5
- OtlpAnyValue,
6
- OtlpKeyValue,
7
5
  OtlpLogRecord,
8
6
  OtlpLogsPayload,
9
7
  OtlpSeverityEntry,
@@ -11,17 +9,9 @@ import type {
11
9
  } from '@posthog/types'
12
10
  import type { Logger } from '../types'
13
11
  import type { LogSdkContext, ResolvedPostHogLogsConfig } from './types'
14
- import { isArray, isBoolean, isNull, isNullish, isNumber, isUndefined } from '../utils'
15
- import {
16
- CIRCULAR_VALUE,
17
- FUNCTION_VALUE,
18
- MAX_JSON_SAFE_VALUE_DEPTH,
19
- MAX_JSON_SAFE_VALUE_ITEMS,
20
- MAX_JSON_SAFE_VALUE_NODES,
21
- sanitizeString,
22
- TRUNCATED_VALUE,
23
- UNSERIALIZABLE_VALUE,
24
- } from '../utils/json-utils'
12
+ import { isNullish, isNumber, isUndefined } from '../utils'
13
+ import { sanitizeString, UNSERIALIZABLE_VALUE } from '../utils/json-utils'
14
+ import { toOtlpKeyValueList } from '../utils/otlp-any-value'
25
15
 
26
16
  // ============================================================================
27
17
  // Severity mapping
@@ -46,200 +36,6 @@ export function getOtlpSeverityNumber(level: LogSeverityLevel): number {
46
36
  return (OTLP_SEVERITY_MAP[level] || DEFAULT_OTLP_SEVERITY).number
47
37
  }
48
38
 
49
- // ============================================================================
50
- // OTLP AnyValue conversion
51
- // ============================================================================
52
-
53
- // 2^63 — one past int64 max.
54
- const INT64_RANGE_LIMIT = 9223372036854775808
55
-
56
- const propertyIsEnumerable = Object.prototype.propertyIsEnumerable
57
-
58
- interface EncodeState {
59
- /** Containers on the current path, so a back-reference becomes a marker. */
60
- ancestors: WeakSet<object>
61
- remainingNodes: number
62
- }
63
-
64
- function newState(): EncodeState {
65
- return { ancestors: new WeakSet(), remainingNodes: MAX_JSON_SAFE_VALUE_NODES }
66
- }
67
-
68
- export function toOtlpAnyValue(value: LogAttributeValue, logger?: Logger): OtlpAnyValue {
69
- try {
70
- return encodeAnyValue(value, logger, newState(), 0)
71
- } catch {
72
- // Runs inside `captureLog` and the metrics flush: an error escaping here
73
- // surfaces in the caller's own code.
74
- return { stringValue: UNSERIALIZABLE_VALUE }
75
- }
76
- }
77
-
78
- export function toOtlpKeyValueList(attrs: Record<string, LogAttributeValue>, logger?: Logger): OtlpKeyValue[] {
79
- try {
80
- return encodeKeyValueList(attrs, logger, newState(), 0)
81
- } catch {
82
- return []
83
- }
84
- }
85
-
86
- function encodeAnyValue(
87
- value: LogAttributeValue,
88
- logger: Logger | undefined,
89
- state: EncodeState,
90
- depth: number
91
- ): OtlpAnyValue {
92
- if (state.remainingNodes <= 0) {
93
- return { stringValue: TRUNCATED_VALUE }
94
- }
95
- state.remainingNodes--
96
-
97
- if (isBoolean(value)) {
98
- return { boolValue: value }
99
- }
100
- // typeof, not core's isNumber, which excludes NaN — proto3 JSON distinguishes
101
- // a non-finite float from an ordinary string.
102
- if (typeof value === 'number') {
103
- if (!Number.isFinite(value)) {
104
- return { stringValue: String(value) }
105
- }
106
- if (Number.isInteger(value)) {
107
- if (Number.isSafeInteger(value)) {
108
- return { intValue: String(value) }
109
- }
110
- // Past MAX_SAFE_INTEGER only BigInt gives the double's exact decimal:
111
- // `String(-(2**63))` lands 192 below int64 min, outside the field it is
112
- // about to be parsed into. Without BigInt the value rides as a string,
113
- // which is never range-checked.
114
- if (typeof BigInt === 'undefined') {
115
- return { stringValue: String(value) }
116
- }
117
- const decimal = BigInt(value).toString()
118
- if (value >= INT64_RANGE_LIMIT || value < -INT64_RANGE_LIMIT) {
119
- // An out-of-range intValue 400s the whole logs request; on the metrics
120
- // path it is swallowed server-side and the metric just disappears.
121
- logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`)
122
- return { stringValue: decimal }
123
- }
124
- return { intValue: decimal }
125
- }
126
- return { doubleValue: value }
127
- }
128
- if (typeof value === 'string') {
129
- return { stringValue: sanitizeString(value) }
130
- }
131
- // `String(value)` would put a function's source text on the wire.
132
- if (typeof value === 'function') {
133
- return { stringValue: FUNCTION_VALUE }
134
- }
135
- if (typeof value === 'symbol') {
136
- return { stringValue: String(value) }
137
- }
138
- if (typeof value === 'object' && value !== null) {
139
- if (state.ancestors.has(value)) {
140
- return { stringValue: CIRCULAR_VALUE }
141
- }
142
- if (depth >= MAX_JSON_SAFE_VALUE_DEPTH) {
143
- return { stringValue: TRUNCATED_VALUE }
144
- }
145
- if (value instanceof Date) {
146
- const time = value.getTime()
147
- const iso = Number.isFinite(time) ? value.toISOString() : String(value)
148
- // An overridden toISOString can return a non-string, which the server
149
- // refuses for the whole request.
150
- return { stringValue: typeof iso === 'string' ? sanitizeString(iso) : String(iso) }
151
- }
152
- // Registered before the toJSON probe: a toJSON returning a structure that
153
- // references its own object is a cycle like any other.
154
- state.ancestors.add(value)
155
- try {
156
- // The representation a value defines for itself — dayjs, Decimal, an ORM
157
- // document, and a cross-realm Date that fails the `instanceof` above.
158
- try {
159
- const toJSON = (value as { toJSON?: unknown }).toJSON
160
- if (typeof toJSON === 'function') {
161
- return encodeAnyValue(toJSON.call(value) as LogAttributeValue, logger, state, depth + 1)
162
- }
163
- } catch {
164
- // A throwing toJSON falls through to the plain walk.
165
- }
166
- if (isArray(value)) {
167
- return { arrayValue: { values: encodeArrayValues(value, logger, state, depth + 1) } }
168
- }
169
- return {
170
- kvlistValue: {
171
- values: encodeKeyValueList(value as Record<string, LogAttributeValue>, logger, state, depth + 1),
172
- },
173
- }
174
- } finally {
175
- // Siblings that reference the same object are duplication, not a cycle.
176
- state.ancestors.delete(value)
177
- }
178
- }
179
- return { stringValue: sanitizeString(String(value)) }
180
- }
181
-
182
- function encodeArrayValues(
183
- values: unknown[],
184
- logger: Logger | undefined,
185
- state: EncodeState,
186
- depth: number
187
- ): OtlpAnyValue[] {
188
- const result: OtlpAnyValue[] = []
189
- const itemCount = Math.min(values.length, MAX_JSON_SAFE_VALUE_ITEMS)
190
- let index = 0
191
- for (; index < itemCount && state.remainingNodes > 0; index++) {
192
- try {
193
- const element = index in values ? values[index] : undefined
194
- // Dropped, as iOS and Android do: proto3 JSON has no null AnyValue, and
195
- // both `null` and `{}` here are rejected for the whole request.
196
- if (isNullish(element)) {
197
- continue
198
- }
199
- result.push(encodeAnyValue(element as LogAttributeValue, logger, state, depth))
200
- } catch {
201
- result.push({ stringValue: UNSERIALIZABLE_VALUE })
202
- }
203
- }
204
- if (values.length > index) {
205
- result.push({ stringValue: TRUNCATED_VALUE })
206
- }
207
- return result
208
- }
209
-
210
- function encodeKeyValueList(
211
- attrs: Record<string, LogAttributeValue>,
212
- logger: Logger | undefined,
213
- state: EncodeState,
214
- depth: number
215
- ): OtlpKeyValue[] {
216
- const result: OtlpKeyValue[] = []
217
- for (const key in attrs) {
218
- // for...in walks the prototype chain once own keys are exhausted. Skipped
219
- // rather than broken out of: a proxy can yield keys in any order.
220
- if (!propertyIsEnumerable.call(attrs, key)) {
221
- continue
222
- }
223
- if (result.length >= MAX_JSON_SAFE_VALUE_ITEMS || state.remainingNodes <= 0) {
224
- // Reported rather than written into the attributes: a synthetic key would
225
- // land in the user's own namespace and could collide with a real one.
226
- logger?.debug('Attributes truncated: the value exceeds the OTLP encoder budget')
227
- break
228
- }
229
- try {
230
- const value = attrs[key]
231
- if (isNull(value) || isUndefined(value)) {
232
- continue
233
- }
234
- result.push({ key: sanitizeString(key), value: encodeAnyValue(value, logger, state, depth) })
235
- } catch {
236
- // A getter that throws costs its own key, not the whole record.
237
- result.push({ key: sanitizeString(key), value: { stringValue: UNSERIALIZABLE_VALUE } })
238
- }
239
- }
240
- return result
241
- }
242
-
243
39
  // ============================================================================
244
40
  // OTLP LogRecord construction
245
41
  // ============================================================================
@@ -10,7 +10,7 @@ import type {
10
10
  } from '@posthog/types'
11
11
  import type { Logger } from '../types'
12
12
  import { isArray, safeSetTimeout } from '../utils'
13
- import { toOtlpKeyValueList } from '../logs/logs-utils'
13
+ import { toOtlpKeyValueList } from '../utils/otlp-any-value'
14
14
  import {
15
15
  DEFAULT_HISTOGRAM_BOUNDS,
16
16
  bucketIndexFor,
@@ -1,5 +1,5 @@
1
1
  import type { MetricAttributeValue, OtlpMetric, OtlpMetricsPayload } from '@posthog/types'
2
- import { toOtlpKeyValueList } from '../logs/logs-utils'
2
+ import { toOtlpKeyValueList } from '../utils/otlp-any-value'
3
3
  import type { ResolvedPostHogMetricsConfig } from './types'
4
4
 
5
5
  /**