posthog-node 4.16.0 → 4.17.1

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.
Files changed (67) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lib/edge/index.cjs +3919 -0
  3. package/lib/edge/index.cjs.map +1 -0
  4. package/lib/edge/index.mjs +3893 -0
  5. package/lib/edge/index.mjs.map +1 -0
  6. package/lib/index.d.ts +921 -859
  7. package/lib/{index.cjs.js → node/index.cjs} +3576 -3595
  8. package/lib/node/index.cjs.map +1 -0
  9. package/lib/{index.esm.js → node/index.mjs} +3577 -3593
  10. package/lib/node/index.mjs.map +1 -0
  11. package/package.json +31 -4
  12. package/index.ts +0 -3
  13. package/lib/index.cjs.js.map +0 -1
  14. package/lib/index.esm.js.map +0 -1
  15. package/lib/posthog-core/src/eventemitter.d.ts +0 -8
  16. package/lib/posthog-core/src/featureFlagUtils.d.ts +0 -34
  17. package/lib/posthog-core/src/index.d.ts +0 -259
  18. package/lib/posthog-core/src/lz-string.d.ts +0 -8
  19. package/lib/posthog-core/src/storage-memory.d.ts +0 -6
  20. package/lib/posthog-core/src/types.d.ts +0 -422
  21. package/lib/posthog-core/src/utils.d.ts +0 -20
  22. package/lib/posthog-core/src/vendor/uuidv7.d.ts +0 -179
  23. package/lib/posthog-node/index.d.ts +0 -3
  24. package/lib/posthog-node/src/crypto-helpers.d.ts +0 -3
  25. package/lib/posthog-node/src/crypto.d.ts +0 -2
  26. package/lib/posthog-node/src/error-tracking.d.ts +0 -12
  27. package/lib/posthog-node/src/extensions/error-tracking/autocapture.d.ts +0 -3
  28. package/lib/posthog-node/src/extensions/error-tracking/context-lines.d.ts +0 -6
  29. package/lib/posthog-node/src/extensions/error-tracking/error-conversion.d.ts +0 -2
  30. package/lib/posthog-node/src/extensions/error-tracking/reduceable-cache.d.ts +0 -12
  31. package/lib/posthog-node/src/extensions/error-tracking/stack-trace.d.ts +0 -15
  32. package/lib/posthog-node/src/extensions/error-tracking/type-checking.d.ts +0 -7
  33. package/lib/posthog-node/src/extensions/error-tracking/types.d.ts +0 -57
  34. package/lib/posthog-node/src/extensions/express.d.ts +0 -17
  35. package/lib/posthog-node/src/extensions/sentry-integration.d.ts +0 -51
  36. package/lib/posthog-node/src/feature-flags.d.ts +0 -84
  37. package/lib/posthog-node/src/fetch.d.ts +0 -11
  38. package/lib/posthog-node/src/lazy.d.ts +0 -23
  39. package/lib/posthog-node/src/posthog-node.d.ts +0 -98
  40. package/lib/posthog-node/src/types.d.ts +0 -229
  41. package/lib/posthog-node/test/test-utils.d.ts +0 -18
  42. package/src/crypto-helpers.ts +0 -36
  43. package/src/crypto.ts +0 -22
  44. package/src/error-tracking.ts +0 -67
  45. package/src/extensions/error-tracking/autocapture.ts +0 -65
  46. package/src/extensions/error-tracking/context-lines.ts +0 -425
  47. package/src/extensions/error-tracking/error-conversion.ts +0 -262
  48. package/src/extensions/error-tracking/reduceable-cache.ts +0 -39
  49. package/src/extensions/error-tracking/stack-trace.ts +0 -269
  50. package/src/extensions/error-tracking/type-checking.ts +0 -40
  51. package/src/extensions/error-tracking/types.ts +0 -65
  52. package/src/extensions/express.ts +0 -37
  53. package/src/extensions/sentry-integration.ts +0 -196
  54. package/src/feature-flags.ts +0 -864
  55. package/src/fetch.ts +0 -39
  56. package/src/lazy.ts +0 -55
  57. package/src/posthog-node.ts +0 -668
  58. package/src/types.ts +0 -257
  59. package/test/crypto.spec.ts +0 -36
  60. package/test/extensions/error-conversion.spec.ts +0 -44
  61. package/test/extensions/sentry-integration.spec.ts +0 -164
  62. package/test/feature-flags.decide.spec.ts +0 -380
  63. package/test/feature-flags.spec.ts +0 -4683
  64. package/test/lazy.spec.ts +0 -71
  65. package/test/posthog-node.spec.ts +0 -1341
  66. package/test/test-utils.ts +0 -111
  67. package/tsconfig.json +0 -7
package/src/crypto.ts DELETED
@@ -1,22 +0,0 @@
1
- /// <reference lib="dom" />
2
-
3
- import { getNodeCrypto, getWebCrypto } from './crypto-helpers'
4
-
5
- export async function hashSHA1(text: string): Promise<string> {
6
- // Try Node.js crypto first
7
- const nodeCrypto = await getNodeCrypto()
8
- if (nodeCrypto) {
9
- return nodeCrypto.createHash('sha1').update(text).digest('hex')
10
- }
11
-
12
- const webCrypto = await getWebCrypto()
13
-
14
- // Fall back to Web Crypto API
15
- if (webCrypto) {
16
- const hashBuffer = await webCrypto.digest('SHA-1', new TextEncoder().encode(text))
17
- const hashArray = Array.from(new Uint8Array(hashBuffer))
18
- return hashArray.map((byte) => byte.toString(16).padStart(2, '0')).join('')
19
- }
20
-
21
- throw new Error('No crypto implementation available. Tried Node Crypto API and Web SubtleCrypto API')
22
- }
@@ -1,67 +0,0 @@
1
- import { EventHint } from './extensions/error-tracking/types'
2
- import { addUncaughtExceptionListener, addUnhandledRejectionListener } from './extensions/error-tracking/autocapture'
3
- import { PostHog, PostHogOptions } from './posthog-node'
4
- import { uuidv7 } from 'posthog-core/src/vendor/uuidv7'
5
- import { propertiesFromUnknownInput } from './extensions/error-tracking/error-conversion'
6
- import { EventMessage } from './types'
7
- import { defaultStackParser } from './extensions/error-tracking/stack-trace'
8
-
9
- const SHUTDOWN_TIMEOUT = 2000
10
-
11
- export default class ErrorTracking {
12
- private client: PostHog
13
- private _exceptionAutocaptureEnabled: boolean
14
-
15
- static async captureException(
16
- client: PostHog,
17
- error: unknown,
18
- hint: EventHint,
19
- distinctId?: string,
20
- additionalProperties?: Record<string | number, any>
21
- ): Promise<void> {
22
- const properties: EventMessage['properties'] = { ...additionalProperties }
23
-
24
- // Given stateless nature of Node SDK we capture exceptions using personless processing when no
25
- // user can be determined because a distinct_id is not provided e.g. exception autocapture
26
- if (!distinctId) {
27
- properties.$process_person_profile = false
28
- }
29
-
30
- const exceptionProperties = await propertiesFromUnknownInput(defaultStackParser, error, hint)
31
-
32
- client.capture({
33
- event: '$exception',
34
- distinctId: distinctId || uuidv7(),
35
- properties: {
36
- ...exceptionProperties,
37
- ...properties,
38
- },
39
- })
40
- }
41
-
42
- constructor(client: PostHog, options: PostHogOptions) {
43
- this.client = client
44
- this._exceptionAutocaptureEnabled = options.enableExceptionAutocapture || false
45
-
46
- this.startAutocaptureIfEnabled()
47
- }
48
-
49
- private startAutocaptureIfEnabled(): void {
50
- if (this.isEnabled()) {
51
- addUncaughtExceptionListener(this.onException.bind(this), this.onFatalError.bind(this))
52
- addUnhandledRejectionListener(this.onException.bind(this))
53
- }
54
- }
55
-
56
- private onException(exception: unknown, hint: EventHint): void {
57
- ErrorTracking.captureException(this.client, exception, hint)
58
- }
59
-
60
- private async onFatalError(): Promise<void> {
61
- await this.client.shutdown(SHUTDOWN_TIMEOUT)
62
- }
63
-
64
- isEnabled(): boolean {
65
- return !this.client.isDisabled && this._exceptionAutocaptureEnabled
66
- }
67
- }
@@ -1,65 +0,0 @@
1
- // Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry
2
- // Licensed under the MIT License
3
-
4
- import { EventHint } from 'posthog-node/src/extensions/error-tracking/types'
5
-
6
- type ErrorHandler = { _posthogErrorHandler: boolean } & ((error: Error) => void)
7
-
8
- function makeUncaughtExceptionHandler(
9
- captureFn: (exception: Error, hint: EventHint) => void,
10
- onFatalFn: () => void
11
- ): ErrorHandler {
12
- let calledFatalError: boolean = false
13
-
14
- return Object.assign(
15
- (error: Error): void => {
16
- // Attaching a listener to `uncaughtException` will prevent the node process from exiting. We generally do not
17
- // want to alter this behaviour so we check for other listeners that users may have attached themselves and adjust
18
- // exit behaviour of the SDK accordingly:
19
- // - If other listeners are attached, do not exit.
20
- // - If the only listener attached is ours, exit.
21
- const userProvidedListenersCount = global.process.listeners('uncaughtException').filter((listener) => {
22
- // There are 2 listeners we ignore:
23
- return (
24
- // as soon as we're using domains this listener is attached by node itself
25
- listener.name !== 'domainUncaughtExceptionClear' &&
26
- // the handler we register in this integration
27
- (listener as ErrorHandler)._posthogErrorHandler !== true
28
- )
29
- }).length
30
-
31
- const processWouldExit = userProvidedListenersCount === 0
32
-
33
- captureFn(error, {
34
- mechanism: {
35
- type: 'onuncaughtexception',
36
- handled: false,
37
- },
38
- })
39
-
40
- if (!calledFatalError && processWouldExit) {
41
- calledFatalError = true
42
- onFatalFn()
43
- }
44
- },
45
- { _posthogErrorHandler: true }
46
- )
47
- }
48
-
49
- export function addUncaughtExceptionListener(
50
- captureFn: (exception: Error, hint: EventHint) => void,
51
- onFatalFn: () => void
52
- ): void {
53
- global.process.on('uncaughtException', makeUncaughtExceptionHandler(captureFn, onFatalFn))
54
- }
55
-
56
- export function addUnhandledRejectionListener(captureFn: (exception: unknown, hint: EventHint) => void): void {
57
- global.process.on('unhandledRejection', (reason: unknown) => {
58
- captureFn(reason, {
59
- mechanism: {
60
- type: 'onunhandledrejection',
61
- handled: false,
62
- },
63
- })
64
- })
65
- }
@@ -1,425 +0,0 @@
1
- // Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry
2
- // Licensed under the MIT License
3
-
4
- import { StackFrame } from './types'
5
- import { ReduceableCache } from './reduceable-cache'
6
- import { Lazy } from 'posthog-node/src/lazy'
7
-
8
- const nodeFs = new Lazy(async () => {
9
- try {
10
- return await import('fs')
11
- } catch {
12
- return undefined
13
- }
14
- })
15
-
16
- export async function getNodeFs(): Promise<typeof import('fs') | undefined> {
17
- return await nodeFs.getValue()
18
- }
19
-
20
- const nodeReadline = new Lazy(async () => {
21
- try {
22
- return await import('readline')
23
- } catch {
24
- return undefined
25
- }
26
- })
27
-
28
- export async function getNodeReadline(): Promise<typeof import('readline') | undefined> {
29
- return await nodeReadline.getValue()
30
- }
31
-
32
- const LRU_FILE_CONTENTS_CACHE = new ReduceableCache<string, Record<number, string>>(25)
33
- const LRU_FILE_CONTENTS_FS_READ_FAILED = new ReduceableCache<string, 1>(20)
34
- const DEFAULT_LINES_OF_CONTEXT = 7
35
- // Determines the upper bound of lineno/colno that we will attempt to read. Large colno values are likely to be
36
- // minified code while large lineno values are likely to be bundled code.
37
- // Exported for testing purposes.
38
- export const MAX_CONTEXTLINES_COLNO: number = 1000
39
- export const MAX_CONTEXTLINES_LINENO: number = 10000
40
-
41
- type ReadlineRange = [start: number, end: number]
42
-
43
- export async function addSourceContext(frames: StackFrame[]): Promise<StackFrame[]> {
44
- // keep a lookup map of which files we've already enqueued to read,
45
- // so we don't enqueue the same file multiple times which would cause multiple i/o reads
46
- const filesToLines: Record<string, number[]> = {}
47
-
48
- // Maps preserve insertion order, so we iterate in reverse, starting at the
49
- // outermost frame and closer to where the exception has occurred (poor mans priority)
50
- for (let i = frames.length - 1; i >= 0; i--) {
51
- const frame: StackFrame | undefined = frames[i]
52
- const filename = frame?.filename
53
-
54
- if (
55
- !frame ||
56
- typeof filename !== 'string' ||
57
- typeof frame.lineno !== 'number' ||
58
- shouldSkipContextLinesForFile(filename) ||
59
- shouldSkipContextLinesForFrame(frame)
60
- ) {
61
- continue
62
- }
63
-
64
- const filesToLinesOutput = filesToLines[filename]
65
- if (!filesToLinesOutput) {
66
- filesToLines[filename] = []
67
- }
68
- filesToLines[filename].push(frame.lineno)
69
- }
70
-
71
- const files = Object.keys(filesToLines)
72
- if (files.length == 0) {
73
- return frames
74
- }
75
-
76
- const readlinePromises: Promise<void>[] = []
77
- for (const file of files) {
78
- // If we failed to read this before, dont try reading it again.
79
- if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file)) {
80
- continue
81
- }
82
-
83
- const filesToLineRanges = filesToLines[file]
84
- if (!filesToLineRanges) {
85
- continue
86
- }
87
-
88
- // Sort ranges so that they are sorted by line increasing order and match how the file is read.
89
- filesToLineRanges.sort((a, b) => a - b)
90
- // Check if the contents are already in the cache and if we can avoid reading the file again.
91
- const ranges = makeLineReaderRanges(filesToLineRanges)
92
- if (ranges.every((r) => rangeExistsInContentCache(file, r))) {
93
- continue
94
- }
95
-
96
- const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {})
97
- readlinePromises.push(getContextLinesFromFile(file, ranges, cache))
98
- }
99
-
100
- // The promise rejections are caught in order to prevent them from short circuiting Promise.all
101
- await Promise.all(readlinePromises).catch(() => {})
102
-
103
- // Perform the same loop as above, but this time we can assume all files are in the cache
104
- // and attempt to add source context to frames.
105
- if (frames && frames.length > 0) {
106
- addSourceContextToFrames(frames, LRU_FILE_CONTENTS_CACHE)
107
- }
108
-
109
- // Once we're finished processing an exception reduce the files held in the cache
110
- // so that we don't indefinetly increase the size of this map
111
- LRU_FILE_CONTENTS_CACHE.reduce()
112
-
113
- return frames
114
- }
115
-
116
- /**
117
- * Extracts lines from a file and stores them in a cache.
118
- */
119
- function getContextLinesFromFile(path: string, ranges: ReadlineRange[], output: Record<number, string>): Promise<void> {
120
- return new Promise((resolve) => {
121
- // KLUDGE: edge runtimes do not support node:fs or node:readline
122
- // until we have separate packages for each environment this will skip
123
- // trying to access the filesystem when not accessible
124
- Promise.all([getNodeFs(), getNodeReadline()]).then(([nodeFs, nodeReadline]) => {
125
- if (!nodeFs || !nodeReadline) {
126
- resolve()
127
- return
128
- }
129
-
130
- // It is important *not* to have any async code between createInterface and the 'line' event listener
131
- // as it will cause the 'line' event to
132
- // be emitted before the listener is attached.
133
- const stream = nodeFs.createReadStream(path)
134
- const lineReaded = nodeReadline.createInterface({
135
- input: stream,
136
- })
137
-
138
- // We need to explicitly destroy the stream to prevent memory leaks,
139
- // removing the listeners on the readline interface is not enough.
140
- // See: https://github.com/nodejs/node/issues/9002 and https://github.com/getsentry/sentry-javascript/issues/14892
141
- function destroyStreamAndResolve(): void {
142
- stream.destroy()
143
- resolve()
144
- }
145
-
146
- // Init at zero and increment at the start of the loop because lines are 1 indexed.
147
- let lineNumber = 0
148
- let currentRangeIndex = 0
149
- const range = ranges[currentRangeIndex]
150
- if (range === undefined) {
151
- // We should never reach this point, but if we do, we should resolve the promise to prevent it from hanging.
152
- destroyStreamAndResolve()
153
- return
154
- }
155
- let rangeStart = range[0]
156
- let rangeEnd = range[1]
157
-
158
- // We use this inside Promise.all, so we need to resolve the promise even if there is an error
159
- // to prevent Promise.all from short circuiting the rest.
160
- function onStreamError(): void {
161
- // Mark file path as failed to read and prevent multiple read attempts.
162
- LRU_FILE_CONTENTS_FS_READ_FAILED.set(path, 1)
163
- lineReaded.close()
164
- lineReaded.removeAllListeners()
165
- destroyStreamAndResolve()
166
- }
167
-
168
- // We need to handle the error event to prevent the process from crashing in < Node 16
169
- // https://github.com/nodejs/node/pull/31603
170
- stream.on('error', onStreamError)
171
- lineReaded.on('error', onStreamError)
172
- lineReaded.on('close', destroyStreamAndResolve)
173
-
174
- lineReaded.on('line', (line) => {
175
- lineNumber++
176
- if (lineNumber < rangeStart) {
177
- return
178
- }
179
-
180
- // !Warning: This mutates the cache by storing the snipped line into the cache.
181
- output[lineNumber] = snipLine(line, 0)
182
-
183
- if (lineNumber >= rangeEnd) {
184
- if (currentRangeIndex === ranges.length - 1) {
185
- // We need to close the file stream and remove listeners, else the reader will continue to run our listener;
186
- lineReaded.close()
187
- lineReaded.removeAllListeners()
188
- return
189
- }
190
- currentRangeIndex++
191
- const range = ranges[currentRangeIndex]
192
- if (range === undefined) {
193
- // This should never happen as it means we have a bug in the context.
194
- lineReaded.close()
195
- lineReaded.removeAllListeners()
196
- return
197
- }
198
- rangeStart = range[0]
199
- rangeEnd = range[1]
200
- }
201
- })
202
- })
203
- })
204
- }
205
-
206
- /** Adds context lines to frames */
207
- function addSourceContextToFrames(frames: StackFrame[], cache: ReduceableCache<string, Record<number, string>>): void {
208
- for (const frame of frames) {
209
- // Only add context if we have a filename and it hasn't already been added
210
- if (frame.filename && frame.context_line === undefined && typeof frame.lineno === 'number') {
211
- const contents = cache.get(frame.filename)
212
- if (contents === undefined) {
213
- continue
214
- }
215
-
216
- addContextToFrame(frame.lineno, frame, contents)
217
- }
218
- }
219
- }
220
-
221
- /**
222
- * Resolves context lines before and after the given line number and appends them to the frame;
223
- */
224
- function addContextToFrame(lineno: number, frame: StackFrame, contents: Record<number, string> | undefined): void {
225
- // When there is no line number in the frame, attaching context is nonsensical and will even break grouping.
226
- // We already check for lineno before calling this, but since StackFrame lineno is optional, we check it again.
227
- if (frame.lineno === undefined || contents === undefined) {
228
- return
229
- }
230
-
231
- frame.pre_context = []
232
- for (let i = makeRangeStart(lineno); i < lineno; i++) {
233
- // We always expect the start context as line numbers cannot be negative. If we dont find a line, then
234
- // something went wrong somewhere. Clear the context and return without adding any linecontext.
235
- const line = contents[i]
236
- if (line === undefined) {
237
- clearLineContext(frame)
238
- return
239
- }
240
-
241
- frame.pre_context.push(line)
242
- }
243
-
244
- // We should always have the context line. If we dont, something went wrong, so we clear the context and return
245
- // without adding any linecontext.
246
- if (contents[lineno] === undefined) {
247
- clearLineContext(frame)
248
- return
249
- }
250
-
251
- frame.context_line = contents[lineno]
252
-
253
- const end = makeRangeEnd(lineno)
254
- frame.post_context = []
255
- for (let i = lineno + 1; i <= end; i++) {
256
- // Since we dont track when the file ends, we cant clear the context if we dont find a line as it could
257
- // just be that we reached the end of the file.
258
- const line = contents[i]
259
- if (line === undefined) {
260
- break
261
- }
262
- frame.post_context.push(line)
263
- }
264
- }
265
-
266
- /**
267
- * Clears the context lines from a frame, used to reset a frame to its original state
268
- * if we fail to resolve all context lines for it.
269
- */
270
- function clearLineContext(frame: StackFrame): void {
271
- delete frame.pre_context
272
- delete frame.context_line
273
- delete frame.post_context
274
- }
275
-
276
- /**
277
- * Determines if context lines should be skipped for a file.
278
- * - .min.(mjs|cjs|js) files are and not useful since they dont point to the original source
279
- * - node: prefixed modules are part of the runtime and cannot be resolved to a file
280
- * - data: skip json, wasm and inline js https://nodejs.org/api/esm.html#data-imports
281
- */
282
- function shouldSkipContextLinesForFile(path: string): boolean {
283
- // Test the most common prefix and extension first. These are the ones we
284
- // are most likely to see in user applications and are the ones we can break out of first.
285
- return (
286
- path.startsWith('node:') ||
287
- path.endsWith('.min.js') ||
288
- path.endsWith('.min.cjs') ||
289
- path.endsWith('.min.mjs') ||
290
- path.startsWith('data:')
291
- )
292
- }
293
-
294
- /**
295
- * Determines if we should skip contextlines based off the max lineno and colno values.
296
- */
297
- function shouldSkipContextLinesForFrame(frame: StackFrame): boolean {
298
- if (frame.lineno !== undefined && frame.lineno > MAX_CONTEXTLINES_LINENO) {
299
- return true
300
- }
301
- if (frame.colno !== undefined && frame.colno > MAX_CONTEXTLINES_COLNO) {
302
- return true
303
- }
304
- return false
305
- }
306
-
307
- /**
308
- * Checks if we have all the contents that we need in the cache.
309
- */
310
- function rangeExistsInContentCache(file: string, range: ReadlineRange): boolean {
311
- const contents = LRU_FILE_CONTENTS_CACHE.get(file)
312
- if (contents === undefined) {
313
- return false
314
- }
315
-
316
- for (let i = range[0]; i <= range[1]; i++) {
317
- if (contents[i] === undefined) {
318
- return false
319
- }
320
- }
321
-
322
- return true
323
- }
324
-
325
- /**
326
- * Creates contiguous ranges of lines to read from a file. In the case where context lines overlap,
327
- * the ranges are merged to create a single range.
328
- */
329
- function makeLineReaderRanges(lines: number[]): ReadlineRange[] {
330
- if (!lines.length) {
331
- return []
332
- }
333
-
334
- let i = 0
335
- const line = lines[0]
336
-
337
- if (typeof line !== 'number') {
338
- return []
339
- }
340
-
341
- let current = makeContextRange(line)
342
- const out: ReadlineRange[] = []
343
- while (true) {
344
- if (i === lines.length - 1) {
345
- out.push(current)
346
- break
347
- }
348
-
349
- // If the next line falls into the current range, extend the current range to lineno + linecontext.
350
- const next = lines[i + 1]
351
- if (typeof next !== 'number') {
352
- break
353
- }
354
- if (next <= current[1]) {
355
- current[1] = next + DEFAULT_LINES_OF_CONTEXT
356
- } else {
357
- out.push(current)
358
- current = makeContextRange(next)
359
- }
360
-
361
- i++
362
- }
363
-
364
- return out
365
- }
366
- // Determine start and end indices for context range (inclusive);
367
- function makeContextRange(line: number): [start: number, end: number] {
368
- return [makeRangeStart(line), makeRangeEnd(line)]
369
- }
370
- // Compute inclusive end context range
371
- function makeRangeStart(line: number): number {
372
- return Math.max(1, line - DEFAULT_LINES_OF_CONTEXT)
373
- }
374
- // Compute inclusive start context range
375
- function makeRangeEnd(line: number): number {
376
- return line + DEFAULT_LINES_OF_CONTEXT
377
- }
378
-
379
- /**
380
- * Get or init map value
381
- */
382
- function emplace<T extends ReduceableCache<K, V>, K extends string, V>(map: T, key: K, contents: V): V {
383
- const value = map.get(key)
384
-
385
- if (value === undefined) {
386
- map.set(key, contents)
387
- return contents
388
- }
389
-
390
- return value
391
- }
392
-
393
- function snipLine(line: string, colno: number): string {
394
- let newLine = line
395
- const lineLength = newLine.length
396
- if (lineLength <= 150) {
397
- return newLine
398
- }
399
- if (colno > lineLength) {
400
- colno = lineLength
401
- }
402
-
403
- let start = Math.max(colno - 60, 0)
404
- if (start < 5) {
405
- start = 0
406
- }
407
-
408
- let end = Math.min(start + 140, lineLength)
409
- if (end > lineLength - 5) {
410
- end = lineLength
411
- }
412
- if (end === lineLength) {
413
- start = Math.max(end - 140, 0)
414
- }
415
-
416
- newLine = newLine.slice(start, end)
417
- if (start > 0) {
418
- newLine = `...${newLine}`
419
- }
420
- if (end < lineLength) {
421
- newLine += '...'
422
- }
423
-
424
- return newLine
425
- }