@posthog/core 1.51.0 → 1.51.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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/error-tracking/parsers/index.ts"],"names":[],"mappings":"AA+BA,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,UAAU,CAAA;AAI7E,OAAO,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAA;AAChD,OAAO,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAC9C,OAAO,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAC9C,OAAO,EAAE,sBAAsB,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAA;AACxE,OAAO,EAAE,mBAAmB,EAAE,MAAM,QAAQ,CAAA;AAK5C,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,aAAa,CAAC,UAAU,CAAC,GAAG,UAAU,EAAE,CAcpF;AAMD,wBAAgB,wBAAwB,IAAI,WAAW,CAEtD;AAED,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,QAAQ,EAAE,GAAG,OAAO,EAAE,eAAe,EAAE,GAAG,WAAW,CAsChG"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/error-tracking/parsers/index.ts"],"names":[],"mappings":"AA+BA,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,UAAU,CAAA;AAI7E,OAAO,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAA;AAChD,OAAO,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAC9C,OAAO,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAC9C,OAAO,EAAE,sBAAsB,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAA;AACxE,OAAO,EAAE,mBAAmB,EAAE,MAAM,QAAQ,CAAA;AA4J5C,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,aAAa,CAAC,UAAU,CAAC,GAAG,UAAU,EAAE,CAcpF;AAMD,wBAAgB,wBAAwB,IAAI,WAAW,CAEtD;AAED,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,QAAQ,EAAE,GAAG,OAAO,EAAE,eAAe,EAAE,GAAG,WAAW,CAkFhG"}
@@ -46,6 +46,69 @@ const external_opera_js_namespaceObject = require("./opera.js");
46
46
  const external_node_js_namespaceObject = require("./node.js");
47
47
  const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
48
48
  const STACKTRACE_FRAME_LIMIT = 50;
49
+ const MAX_REPEATED_CYCLE_LENGTH = 10;
50
+ const STACKTRACE_LINE_LIMIT = 1000;
51
+ function isSameFrame(a, b) {
52
+ return a.filename === b.filename && a.function === b.function && a.module === b.module && a.lineno === b.lineno && a.colno === b.colno;
53
+ }
54
+ function collapseRepeatedCycle(frames) {
55
+ for(let length = 1; length <= MAX_REPEATED_CYCLE_LENGTH; length++){
56
+ const start = frames.length - 2 * length;
57
+ if (start < 0) break;
58
+ let isCycle = true;
59
+ for(let offset = 0; offset < length; offset++){
60
+ const inner = frames[start + offset];
61
+ if (!isSameFrame(inner, frames[start + length + offset])) {
62
+ isCycle = false;
63
+ break;
64
+ }
65
+ }
66
+ if (isCycle) {
67
+ for(let offset = 0; offset < length; offset++)frames[start + offset] = frames[start + length + offset];
68
+ frames.length = start + length;
69
+ return {
70
+ start,
71
+ length
72
+ };
73
+ }
74
+ }
75
+ }
76
+ function trimPartialCycle(frames, cycle) {
77
+ const copyEnd = cycle.start + cycle.length;
78
+ const partialLength = partialCycleLength(frames, cycle);
79
+ if (partialLength) frames.splice(copyEnd + partialLength === frames.length ? copyEnd : cycle.start, partialLength);
80
+ }
81
+ function innermostPartialCycleLength(frames, cycle) {
82
+ let partialStart = cycle.start;
83
+ while(partialStart > 0 && isSameFrame(frames[partialStart - 1], frames[partialStart - 1 + cycle.length]))partialStart--;
84
+ return cycle.start - partialStart;
85
+ }
86
+ function partialCycleLength(frames, cycle) {
87
+ const copyEnd = cycle.start + cycle.length;
88
+ let partialEnd = copyEnd;
89
+ while(partialEnd < frames.length && isSameFrame(frames[partialEnd], frames[partialEnd - cycle.length]))partialEnd++;
90
+ return partialEnd - copyEnd;
91
+ }
92
+ function survivingFrameCount(frames, cycles) {
93
+ const innermostCycle = cycles[0];
94
+ let count = frames.length - (innermostCycle ? innermostPartialCycleLength(frames, innermostCycle) : 0);
95
+ for (const cycle of cycles)count -= partialCycleLength(frames, cycle);
96
+ return count;
97
+ }
98
+ function canonicalizeCycleRotation(frames) {
99
+ const keys = frames.map((frame)=>`${frame.function}|${frame.filename}|${frame.lineno}|${frame.colno}|${frame.module}`);
100
+ let first = 0;
101
+ for(let i = 1; i < keys.length; i++)if (isSmallerRotation(keys, i, first)) first = i;
102
+ frames.push(...frames.splice(0, first));
103
+ }
104
+ function isSmallerRotation(keys, candidate, best) {
105
+ for(let offset = 0; offset < keys.length; offset++){
106
+ const left = keys[(candidate + offset) % keys.length];
107
+ const right = keys[(best + offset) % keys.length];
108
+ if (left !== right) return left < right;
109
+ }
110
+ return false;
111
+ }
49
112
  function reverseAndStripFrames(stack) {
50
113
  if (!stack.length) return [];
51
114
  const localStack = Array.from(stack);
@@ -66,7 +129,9 @@ function createStackParser(platform, ...parsers) {
66
129
  return (stack, skipFirstLines = 0)=>{
67
130
  const frames = [];
68
131
  const lines = stack.split('\n');
69
- for(let i = skipFirstLines; i < lines.length; i++){
132
+ const endLine = Math.min(lines.length, skipFirstLines + STACKTRACE_LINE_LIMIT);
133
+ const repeatedCycles = [];
134
+ for(let i = skipFirstLines; i < endLine; i++){
70
135
  const line = lines[i];
71
136
  if (line.length > 1024) continue;
72
137
  const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;
@@ -75,12 +140,32 @@ function createStackParser(platform, ...parsers) {
75
140
  const frame = parser(cleanedLine, platform);
76
141
  if (frame) {
77
142
  frames.push(frame);
143
+ const cycle = collapseRepeatedCycle(frames);
144
+ if (cycle) {
145
+ for(let i = repeatedCycles.length - 1; i >= 0; i--){
146
+ const previous = repeatedCycles[i];
147
+ if (previous.start + previous.length <= cycle.start) break;
148
+ repeatedCycles.pop();
149
+ }
150
+ repeatedCycles.push(cycle);
151
+ }
78
152
  break;
79
153
  }
80
154
  }
81
- if (frames.length >= STACKTRACE_FRAME_LIMIT) break;
155
+ if (survivingFrameCount(frames, repeatedCycles) >= STACKTRACE_FRAME_LIMIT) break;
82
156
  }
83
157
  }
158
+ const sections = [
159
+ ...repeatedCycles
160
+ ].sort((a, b)=>b.start - a.start);
161
+ const innermostSection = sections[sections.length - 1];
162
+ if (innermostSection) {
163
+ const trimmed = innermostPartialCycleLength(frames, innermostSection);
164
+ frames.splice(innermostSection.start - trimmed, trimmed);
165
+ for (const cycle of sections)cycle.start -= trimmed;
166
+ }
167
+ for (const cycle of sections)trimPartialCycle(frames, cycle);
168
+ if (repeatedCycles.some((cycle)=>0 === cycle.start && frames.length === cycle.length)) canonicalizeCycleRotation(frames);
84
169
  return reverseAndStripFrames(frames);
85
170
  };
86
171
  }
@@ -3,6 +3,69 @@ import { chromeStackLineParser } from "./chrome.mjs";
3
3
  import { geckoStackLineParser } from "./gecko.mjs";
4
4
  const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
5
5
  const STACKTRACE_FRAME_LIMIT = 50;
6
+ const MAX_REPEATED_CYCLE_LENGTH = 10;
7
+ const STACKTRACE_LINE_LIMIT = 1000;
8
+ function isSameFrame(a, b) {
9
+ return a.filename === b.filename && a.function === b.function && a.module === b.module && a.lineno === b.lineno && a.colno === b.colno;
10
+ }
11
+ function collapseRepeatedCycle(frames) {
12
+ for(let length = 1; length <= MAX_REPEATED_CYCLE_LENGTH; length++){
13
+ const start = frames.length - 2 * length;
14
+ if (start < 0) break;
15
+ let isCycle = true;
16
+ for(let offset = 0; offset < length; offset++){
17
+ const inner = frames[start + offset];
18
+ if (!isSameFrame(inner, frames[start + length + offset])) {
19
+ isCycle = false;
20
+ break;
21
+ }
22
+ }
23
+ if (isCycle) {
24
+ for(let offset = 0; offset < length; offset++)frames[start + offset] = frames[start + length + offset];
25
+ frames.length = start + length;
26
+ return {
27
+ start,
28
+ length
29
+ };
30
+ }
31
+ }
32
+ }
33
+ function trimPartialCycle(frames, cycle) {
34
+ const copyEnd = cycle.start + cycle.length;
35
+ const partialLength = partialCycleLength(frames, cycle);
36
+ if (partialLength) frames.splice(copyEnd + partialLength === frames.length ? copyEnd : cycle.start, partialLength);
37
+ }
38
+ function innermostPartialCycleLength(frames, cycle) {
39
+ let partialStart = cycle.start;
40
+ while(partialStart > 0 && isSameFrame(frames[partialStart - 1], frames[partialStart - 1 + cycle.length]))partialStart--;
41
+ return cycle.start - partialStart;
42
+ }
43
+ function partialCycleLength(frames, cycle) {
44
+ const copyEnd = cycle.start + cycle.length;
45
+ let partialEnd = copyEnd;
46
+ while(partialEnd < frames.length && isSameFrame(frames[partialEnd], frames[partialEnd - cycle.length]))partialEnd++;
47
+ return partialEnd - copyEnd;
48
+ }
49
+ function survivingFrameCount(frames, cycles) {
50
+ const innermostCycle = cycles[0];
51
+ let count = frames.length - (innermostCycle ? innermostPartialCycleLength(frames, innermostCycle) : 0);
52
+ for (const cycle of cycles)count -= partialCycleLength(frames, cycle);
53
+ return count;
54
+ }
55
+ function canonicalizeCycleRotation(frames) {
56
+ const keys = frames.map((frame)=>`${frame.function}|${frame.filename}|${frame.lineno}|${frame.colno}|${frame.module}`);
57
+ let first = 0;
58
+ for(let i = 1; i < keys.length; i++)if (isSmallerRotation(keys, i, first)) first = i;
59
+ frames.push(...frames.splice(0, first));
60
+ }
61
+ function isSmallerRotation(keys, candidate, best) {
62
+ for(let offset = 0; offset < keys.length; offset++){
63
+ const left = keys[(candidate + offset) % keys.length];
64
+ const right = keys[(best + offset) % keys.length];
65
+ if (left !== right) return left < right;
66
+ }
67
+ return false;
68
+ }
6
69
  function reverseAndStripFrames(stack) {
7
70
  if (!stack.length) return [];
8
71
  const localStack = Array.from(stack);
@@ -23,7 +86,9 @@ function createStackParser(platform, ...parsers) {
23
86
  return (stack, skipFirstLines = 0)=>{
24
87
  const frames = [];
25
88
  const lines = stack.split('\n');
26
- for(let i = skipFirstLines; i < lines.length; i++){
89
+ const endLine = Math.min(lines.length, skipFirstLines + STACKTRACE_LINE_LIMIT);
90
+ const repeatedCycles = [];
91
+ for(let i = skipFirstLines; i < endLine; i++){
27
92
  const line = lines[i];
28
93
  if (line.length > 1024) continue;
29
94
  const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;
@@ -32,12 +97,32 @@ function createStackParser(platform, ...parsers) {
32
97
  const frame = parser(cleanedLine, platform);
33
98
  if (frame) {
34
99
  frames.push(frame);
100
+ const cycle = collapseRepeatedCycle(frames);
101
+ if (cycle) {
102
+ for(let i = repeatedCycles.length - 1; i >= 0; i--){
103
+ const previous = repeatedCycles[i];
104
+ if (previous.start + previous.length <= cycle.start) break;
105
+ repeatedCycles.pop();
106
+ }
107
+ repeatedCycles.push(cycle);
108
+ }
35
109
  break;
36
110
  }
37
111
  }
38
- if (frames.length >= STACKTRACE_FRAME_LIMIT) break;
112
+ if (survivingFrameCount(frames, repeatedCycles) >= STACKTRACE_FRAME_LIMIT) break;
39
113
  }
40
114
  }
115
+ const sections = [
116
+ ...repeatedCycles
117
+ ].sort((a, b)=>b.start - a.start);
118
+ const innermostSection = sections[sections.length - 1];
119
+ if (innermostSection) {
120
+ const trimmed = innermostPartialCycleLength(frames, innermostSection);
121
+ frames.splice(innermostSection.start - trimmed, trimmed);
122
+ for (const cycle of sections)cycle.start -= trimmed;
123
+ }
124
+ for (const cycle of sections)trimPartialCycle(frames, cycle);
125
+ if (repeatedCycles.some((cycle)=>0 === cycle.start && frames.length === cycle.length)) canonicalizeCycleRotation(frames);
41
126
  return reverseAndStripFrames(frames);
42
127
  };
43
128
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@posthog/core",
3
- "version": "1.51.0",
3
+ "version": "1.51.1",
4
4
  "bugs": {
5
5
  "url": "https://github.com/PostHog/posthog-js/issues"
6
6
  },
@@ -70,7 +70,7 @@
70
70
  }
71
71
  },
72
72
  "dependencies": {
73
- "@posthog/types": "^1.409.1"
73
+ "@posthog/types": "^1.409.2"
74
74
  },
75
75
  "devDependencies": {
76
76
  "@rslib/core": "0.23.2",
@@ -29,7 +29,9 @@ describe('ErrorPropertiesBuilder', () => {
29
29
  const syntheticError = new Error()
30
30
  const frames = parseStack(syntheticError)
31
31
  expect(frames).toBeDefined()
32
- expect(frames).toHaveLength(15)
32
+ // The test runner calls itself once per nested describe block, and the parser keeps one copy
33
+ // of a repeated frame cycle, so those repeats count as a single frame here.
34
+ expect(frames).toHaveLength(13)
33
35
  })
34
36
  })
35
37
  })
@@ -0,0 +1,270 @@
1
+ import { createDefaultStackParser } from './index'
2
+
3
+ describe('createDefaultStackParser repeated cycle collapsing', () => {
4
+ const parse = createDefaultStackParser()
5
+
6
+ const OVERFLOW = 'RangeError: Maximum call stack size exceeded'
7
+
8
+ const frame = (func: string, line: number, column: number = 10): string =>
9
+ ` at ${func} (https://posthog.com/app.js:${line}:${column})`
10
+
11
+ function recursion(cycle: string[], repeats: number): string[] {
12
+ const frames: string[] = []
13
+
14
+ for (let i = 0; i < repeats; i++) {
15
+ cycle.forEach((func, index) => frames.push(frame(func, index + 1)))
16
+ }
17
+
18
+ return frames
19
+ }
20
+
21
+ // The runtime lists the innermost frame first and cuts the stack wherever the depth ran out, so
22
+ // `dropInnermost` is how many frames of the cycle that cut took off the innermost end.
23
+ function overflowStack(cycle: string[], repeats: number, dropInnermost: number = 0): string {
24
+ return [
25
+ OVERFLOW,
26
+ ...recursion(cycle, repeats).slice(dropInnermost),
27
+ frame('handleClick', 90),
28
+ frame('main', 91),
29
+ ].join('\n')
30
+ }
31
+
32
+ function names(stack: string): (string | undefined)[] {
33
+ return parse(stack).map((f) => f.function)
34
+ }
35
+
36
+ it('keeps one copy of a recursion cycle', () => {
37
+ expect(names(overflowStack(['a', 'b'], 30))).toEqual(['main', 'handleClick', 'b', 'a'])
38
+ })
39
+
40
+ it('keeps one copy when a single function calls itself', () => {
41
+ expect(names(overflowStack(['a'], 60))).toEqual(['main', 'handleClick', 'a'])
42
+ })
43
+
44
+ it('keeps the outer frames a recursion used to push past the frame limit', () => {
45
+ // Without collapsing, the frame limit is spent on the cycle and the frames that name the
46
+ // caller never reach the event.
47
+ const frames = names(overflowStack(['a', 'b'], 400))
48
+ expect(frames).toContain('main')
49
+ expect(frames).toContain('handleClick')
50
+ })
51
+
52
+ it('gives the same frames wherever the runtime cut the recursion', () => {
53
+ // The overflow can happen in either function of the pair, which used to change the frames and
54
+ // so open a new issue for every throw.
55
+ const pair = names(overflowStack(['a', 'b'], 30))
56
+ expect(names(overflowStack(['a', 'b'], 30, 1))).toEqual(pair)
57
+
58
+ const triple = names(overflowStack(['a', 'b', 'c'], 30))
59
+ expect(names(overflowStack(['a', 'b', 'c'], 30, 1))).toEqual(triple)
60
+ expect(names(overflowStack(['a', 'b', 'c'], 30, 2))).toEqual(triple)
61
+ })
62
+
63
+ it('gives the same frames when the runtime cut everything outside the recursion', () => {
64
+ // The runtime keeps the innermost frames, so a deep recursion can push every other frame out of
65
+ // the stack. Nothing then says which function of the cycle ran out of stack first.
66
+ const recursionOnly = (dropInnermost: number): (string | undefined)[] =>
67
+ names([OVERFLOW, ...recursion(['a', 'b'], 40).slice(dropInnermost)].join('\n'))
68
+
69
+ expect(recursionOnly(1)).toEqual(recursionOnly(0))
70
+ })
71
+
72
+ it('gives the same frames when the stack holds a second repeated section', () => {
73
+ // Stacks repeat outside the recursion too, such as a test runner that calls itself once per
74
+ // nested block. The frames of that section have to keep the recursion's own partial copy.
75
+ const withOuterRepeat = (dropInnermost: number): (string | undefined)[] =>
76
+ names(
77
+ [
78
+ OVERFLOW,
79
+ ...recursion(['a', 'b'], 30).slice(dropInnermost),
80
+ frame('handleClick', 90),
81
+ frame('walk', 91),
82
+ frame('walk', 91),
83
+ frame('main', 92),
84
+ ].join('\n')
85
+ )
86
+
87
+ expect(withOuterRepeat(0)).toEqual(['main', 'walk', 'handleClick', 'b', 'a'])
88
+ expect(withOuterRepeat(1)).toEqual(withOuterRepeat(0))
89
+ })
90
+
91
+ it('gives the same frames when a cycle that repeats a call site is all that is left', () => {
92
+ // One copy of a cycle can hold the same call site twice, and the innermost frame carries a
93
+ // column of its own, so a single frame does not say which rotation of the copy this throw is.
94
+ const cycle = [frame('a', 1, 10), frame('b', 2), frame('a', 1, 20), frame('c', 4)]
95
+ const lines: string[] = []
96
+
97
+ for (let i = 0; i < 30; i++) {
98
+ lines.push(...cycle)
99
+ }
100
+
101
+ const fromCut = (dropInnermost: number): (string | undefined)[] =>
102
+ names([OVERFLOW, ...lines.slice(dropInnermost)].join('\n'))
103
+
104
+ expect(fromCut(0)).toEqual(['c', 'a', 'b', 'a'])
105
+ expect(fromCut(1)).toEqual(fromCut(0))
106
+ expect(fromCut(2)).toEqual(fromCut(0))
107
+ expect(fromCut(3)).toEqual(fromCut(0))
108
+ })
109
+
110
+ it('reads the outer frames a leftover copy would have pushed past the frame limit', () => {
111
+ // The leftover copy is dropped once the whole stack is read, so it must not hold a slot of the
112
+ // frame limit while the parser is still reading the frames outside the recursion.
113
+ const callers: string[] = []
114
+
115
+ for (let i = 0; i < 48; i++) {
116
+ callers.push(frame(`c${i}`, i + 10))
117
+ }
118
+
119
+ const withCallers = (dropInnermost: number): (string | undefined)[] =>
120
+ names([OVERFLOW, ...recursion(['a', 'b'], 30).slice(dropInnermost), ...callers].join('\n'))
121
+
122
+ expect(withCallers(0)).toHaveLength(50)
123
+ expect(withCallers(1)).toEqual(withCallers(0))
124
+
125
+ // A distinct throw location is not a partial copy and must use a slot of the frame budget.
126
+ const withThrowColumn = [OVERFLOW, frame('a', 1, 4), ...recursion(['a', 'b'], 30).slice(1), ...callers].join('\n')
127
+ const frames = parse(withThrowColumn)
128
+ expect(frames).toHaveLength(50)
129
+ expect(frames.map((f) => f.function)).toEqual([...withCallers(0).slice(1), 'a'])
130
+ expect(frames[frames.length - 1]?.colno).toBe(4)
131
+ })
132
+
133
+ it('gives the same frames when the recursion path calls one function twice in a row', () => {
134
+ // A minified bundle holds one line number per function, so the two calls to `b` are told apart
135
+ // by their column alone. The kept copy holds both of them, and every cut agrees on it.
136
+ const cycle = [frame('a', 1), frame('b', 2, 10), frame('b', 2, 20)]
137
+ const lines: string[] = []
138
+
139
+ for (let i = 0; i < 30; i++) {
140
+ lines.push(...cycle)
141
+ }
142
+
143
+ const fromCut = (dropInnermost: number): (string | undefined)[] =>
144
+ names([OVERFLOW, ...lines.slice(dropInnermost), frame('handleClick', 90), frame('main', 91)].join('\n'))
145
+
146
+ expect(fromCut(0)).toEqual(['main', 'handleClick', 'b', 'b', 'a'])
147
+ expect(fromCut(1)).toEqual(fromCut(0))
148
+ expect(fromCut(2)).toEqual(fromCut(0))
149
+ })
150
+
151
+ it('keeps minified frames that share a name and a line but not a column', () => {
152
+ // A minified bundle puts every function on one line and hands out the same short names, so the
153
+ // column is all that tells two of them apart. Nothing repeats here, so no frame may be dropped.
154
+ const stack = [
155
+ 'Error: boom',
156
+ frame('i', 1, 310),
157
+ frame('t', 1, 4821),
158
+ frame('t', 1, 9137),
159
+ frame('r', 1, 2210),
160
+ frame('onClick', 1, 640),
161
+ ].join('\n')
162
+
163
+ expect(parse(stack).map((f) => `${f.function}:${f.colno}`)).toEqual([
164
+ 'onClick:640',
165
+ 'r:2210',
166
+ 't:9137',
167
+ 't:4821',
168
+ 'i:310',
169
+ ])
170
+ })
171
+
172
+ it.each(['Error: boom', OVERFLOW])('preserves the unnamed throw location for %s', (header) => {
173
+ // Even a confirmed recursion cannot establish that a different innermost column is redundant.
174
+ // Keep that location for both ordinary errors and overflow stacks.
175
+ const anonymous = (column: number): string => ` at https://posthog.com/app.js:1:${column}`
176
+
177
+ const withThrowColumn = (column: number): string[] => {
178
+ const lines = [anonymous(column)]
179
+
180
+ for (let i = 1; i < 40; i++) {
181
+ lines.push(anonymous(10))
182
+ }
183
+
184
+ return parse([header, ...lines, frame('handleClick', 90), frame('main', 91)].join('\n')).map(
185
+ (f) => `${f.function}:${f.colno}`
186
+ )
187
+ }
188
+
189
+ expect(withThrowColumn(4)).toEqual(['main:10', 'handleClick:10', '?:10', '?:4'])
190
+ expect(withThrowColumn(5)).toEqual(['main:10', 'handleClick:10', '?:10', '?:5'])
191
+ expect(withThrowColumn(10)).toEqual(['main:10', 'handleClick:10', '?:10'])
192
+ })
193
+
194
+ it('preserves the column of the call that ran out of stack', () => {
195
+ // Do not guess whether a different column is a redundant overflow location or a distinct throw.
196
+ const stack = [OVERFLOW, frame('a', 1, 4), ...recursion(['a', 'b'], 3).slice(1), frame('handleClick', 90)].join(
197
+ '\n'
198
+ )
199
+
200
+ expect(parse(stack).map((f) => `${f.function}:${f.colno}`)).toEqual(['handleClick:10', 'b:10', 'a:10', 'a:4'])
201
+ })
202
+
203
+ it('keeps frames that repeat without a complete second cycle', () => {
204
+ const stack = ['Error: boom', frame('a', 1), frame('b', 2), frame('a', 1), frame('main', 91)].join('\n')
205
+ expect(names(stack)).toEqual(['main', 'a', 'b', 'a'])
206
+ })
207
+
208
+ it('invalidates a cycle record subsumed by a later collapse', () => {
209
+ const stack = ['Error: boom', frame('a', 1), frame('b', 2), frame('a', 1), frame('a', 1), frame('b', 2)].join('\n')
210
+
211
+ expect(names(stack)).toEqual(['b', 'a'])
212
+ })
213
+
214
+ it('keeps disjoint cycle records when a later collapse subsumes another record', () => {
215
+ const stack = [
216
+ 'Error: boom',
217
+ frame('inner', 90),
218
+ frame('inner', 90),
219
+ frame('a', 1),
220
+ frame('b', 2),
221
+ frame('a', 1),
222
+ frame('a', 1),
223
+ frame('b', 2),
224
+ frame('outer', 91),
225
+ frame('outer', 91),
226
+ ].join('\n')
227
+
228
+ expect(names(stack)).toEqual(['outer', 'b', 'a', 'inner'])
229
+ })
230
+
231
+ it.each([4, 5])('preserves the throw column %i of an ordinary recursive error', (column) => {
232
+ const stack = [
233
+ 'Error: boom',
234
+ frame('recurse', 1, column),
235
+ frame('recurse', 1, 10),
236
+ frame('recurse', 1, 10),
237
+ frame('main', 91),
238
+ ].join('\n')
239
+
240
+ expect(parse(stack).map((f) => `${f.function}:${f.colno}`)).toEqual(['main:10', 'recurse:10', `recurse:${column}`])
241
+ })
242
+
243
+ it('keeps distinct innermost minified call sites for an ordinary error', () => {
244
+ const stack = ['Error: boom', frame('t', 1, 100), frame('t', 1, 200), frame('main', 91)].join('\n')
245
+
246
+ expect(parse(stack).map((f) => `${f.function}:${f.colno}`)).toEqual(['main:10', 't:200', 't:100'])
247
+ })
248
+
249
+ it('canonicalizes recursion-only cycles whose rotations differ only by columns', () => {
250
+ const cycle = [frame('a', 1, 10), frame('b', 1, 20), frame('a', 1, 30), frame('b', 1, 40)]
251
+ const lines: string[] = []
252
+
253
+ for (let i = 0; i < 30; i++) {
254
+ lines.push(...cycle)
255
+ }
256
+
257
+ const fromCut = (dropInnermost: number): string[] =>
258
+ parse([OVERFLOW, ...lines.slice(dropInnermost)].join('\n')).map((f) => `${f.function}:${f.colno}`)
259
+
260
+ expect(fromCut(0)).toEqual(['b:40', 'a:30', 'b:20', 'a:10'])
261
+ expect(fromCut(1)).toEqual(fromCut(0))
262
+ expect(fromCut(2)).toEqual(fromCut(0))
263
+ expect(fromCut(3)).toEqual(fromCut(0))
264
+ })
265
+
266
+ it('keeps calls to one function from different call sites', () => {
267
+ const stack = ['Error: boom', frame('a', 1), frame('a', 2), frame('a', 3), frame('main', 91)].join('\n')
268
+ expect(names(stack)).toEqual(['main', 'a', 'a', 'a'])
269
+ })
270
+ })
@@ -42,6 +42,157 @@ export { nodeStackLineParser } from './node'
42
42
  const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/
43
43
  const STACKTRACE_FRAME_LIMIT = 50
44
44
 
45
+ // A recursion spends the whole frame limit on one repeating cycle, so the frames that name the real
46
+ // culprit sit past the limit, and where the runtime cut the stack decides which frames are left.
47
+ // One fault can then open multiple error tracking issues. The parser keeps a single copy of an exact
48
+ // cycle instead, making room for outer frames and reducing depth-dependent differences without
49
+ // discarding distinct throw locations. Longer cycles are rare and cost an extra comparison pass.
50
+ const MAX_REPEATED_CYCLE_LENGTH = 10
51
+ // How many lines to read, now that a recursion no longer stops the parser at the frame limit.
52
+ const STACKTRACE_LINE_LIMIT = 1000
53
+
54
+ // A minified bundle puts many functions on one line and gives them the same short names, so the
55
+ // column is what tells two of them apart. Even a confirmed cycle must preserve a distinct throw
56
+ // location: the frame list alone cannot distinguish an overflow from an ordinary recursive error.
57
+ function isSameFrame(a: StackFrame, b: StackFrame): boolean {
58
+ return (
59
+ a.filename === b.filename &&
60
+ a.function === b.function &&
61
+ a.module === b.module &&
62
+ a.lineno === b.lineno &&
63
+ a.colno === b.colno
64
+ )
65
+ }
66
+
67
+ interface RepeatedCycle {
68
+ start: number
69
+ length: number
70
+ }
71
+
72
+ // Removes the cycle that ends at the last frame when the frames before it are the same cycle, and
73
+ // reports where the copy that was kept sits. This runs after every frame is added, so a recursion
74
+ // never grows past one copy of its cycle.
75
+ function collapseRepeatedCycle(frames: StackFrame[]): RepeatedCycle | undefined {
76
+ for (let length = 1; length <= MAX_REPEATED_CYCLE_LENGTH; length++) {
77
+ const start = frames.length - 2 * length
78
+ if (start < 0) {
79
+ return undefined
80
+ }
81
+
82
+ let isCycle = true
83
+ for (let offset = 0; offset < length; offset++) {
84
+ const inner = frames[start + offset] as StackFrame
85
+
86
+ if (!isSameFrame(inner, frames[start + length + offset] as StackFrame)) {
87
+ isCycle = false
88
+ break
89
+ }
90
+ }
91
+
92
+ if (isCycle) {
93
+ // Keep the outer copy of the matching frames.
94
+ for (let offset = 0; offset < length; offset++) {
95
+ frames[start + offset] = frames[start + length + offset] as StackFrame
96
+ }
97
+
98
+ frames.length = start + length
99
+ return { start, length }
100
+ }
101
+ }
102
+
103
+ return undefined
104
+ }
105
+
106
+ // The stack is cut wherever the depth ran out, so a part of the cycle can be left over next to the
107
+ // copy that was kept. That leftover part is what moved the fingerprint from one throw to the next.
108
+ // Remove it at the end the stack was cut at, so that the frame the code outside the cycle really
109
+ // called stays next to it.
110
+ function trimPartialCycle(frames: StackFrame[], cycle: RepeatedCycle): void {
111
+ const copyEnd = cycle.start + cycle.length
112
+ const partialLength = partialCycleLength(frames, cycle)
113
+
114
+ if (partialLength) {
115
+ frames.splice(copyEnd + partialLength === frames.length ? copyEnd : cycle.start, partialLength)
116
+ }
117
+ }
118
+
119
+ // Counts an exact partial copy left over at the innermost end.
120
+ function innermostPartialCycleLength(frames: StackFrame[], cycle: RepeatedCycle): number {
121
+ let partialStart = cycle.start
122
+
123
+ while (
124
+ partialStart > 0 &&
125
+ isSameFrame(frames[partialStart - 1] as StackFrame, frames[partialStart - 1 + cycle.length] as StackFrame)
126
+ ) {
127
+ partialStart--
128
+ }
129
+
130
+ return cycle.start - partialStart
131
+ }
132
+
133
+ // How much of the cycle is left over next to the copy that was kept.
134
+ function partialCycleLength(frames: StackFrame[], cycle: RepeatedCycle): number {
135
+ const copyEnd = cycle.start + cycle.length
136
+ let partialEnd = copyEnd
137
+
138
+ while (
139
+ partialEnd < frames.length &&
140
+ isSameFrame(frames[partialEnd] as StackFrame, frames[partialEnd - cycle.length] as StackFrame)
141
+ ) {
142
+ partialEnd++
143
+ }
144
+
145
+ return partialEnd - copyEnd
146
+ }
147
+
148
+ // The leftover copies are dropped once the whole stack is read, so the frame limit counts the
149
+ // frames that survive that. A leftover copy otherwise holds a slot while the loop runs, the parser
150
+ // stops before the outermost frames, and how many of them are read moves with where the stack was
151
+ // cut.
152
+ function survivingFrameCount(frames: StackFrame[], cycles: RepeatedCycle[]): number {
153
+ const innermostCycle = cycles[0]
154
+ let count = frames.length - (innermostCycle ? innermostPartialCycleLength(frames, innermostCycle) : 0)
155
+
156
+ for (const cycle of cycles) {
157
+ count -= partialCycleLength(frames, cycle)
158
+ }
159
+
160
+ return count
161
+ }
162
+
163
+ // When the runtime cut every frame outside the cycle, the trace is one copy of the cycle and
164
+ // nothing says which function of it ran out of stack first. Any rotation of the copy holds the same
165
+ // calls, so always keep the same one, and the fingerprint stays equal from one throw to the next.
166
+ function canonicalizeCycleRotation(frames: StackFrame[]): void {
167
+ const keys = frames.map(
168
+ (frame) => `${frame.function}|${frame.filename}|${frame.lineno}|${frame.colno}|${frame.module}`
169
+ )
170
+ let first = 0
171
+
172
+ for (let i = 1; i < keys.length; i++) {
173
+ if (isSmallerRotation(keys, i, first)) {
174
+ first = i
175
+ }
176
+ }
177
+
178
+ frames.push(...frames.splice(0, first))
179
+ }
180
+
181
+ // One copy of a cycle can hold the same call site more than once, so the smallest single frame does
182
+ // not name one rotation. Read both rotations from their first frame on, and the whole copy decides.
183
+ function isSmallerRotation(keys: string[], candidate: number, best: number): boolean {
184
+ for (let offset = 0; offset < keys.length; offset++) {
185
+ const left = keys[(candidate + offset) % keys.length] as string
186
+ const right = keys[(best + offset) % keys.length] as string
187
+
188
+ if (left !== right) {
189
+ return left < right
190
+ }
191
+ }
192
+
193
+ return false
194
+ }
195
+
45
196
  export function reverseAndStripFrames(stack: ReadonlyArray<StackFrame>): StackFrame[] {
46
197
  if (!stack.length) {
47
198
  return []
@@ -71,7 +222,13 @@ export function createStackParser(platform: Platform, ...parsers: StackLineParse
71
222
  const frames: StackFrame[] = []
72
223
  const lines = stack.split('\n')
73
224
 
74
- for (let i = skipFirstLines; i < lines.length; i++) {
225
+ const endLine = Math.min(lines.length, skipFirstLines + STACKTRACE_LINE_LIMIT)
226
+ // A stack can hold more than one repeated section, such as a recursion under a test runner that
227
+ // calls itself once per nested block. Keep every section, because each of them can be left with
228
+ // a partial copy, and one section must not take the place of another.
229
+ const repeatedCycles: RepeatedCycle[] = []
230
+
231
+ for (let i = skipFirstLines; i < endLine; i++) {
75
232
  const line = lines[i] as string
76
233
  // Ignore lines over 1kb as they are unlikely to be stack frames.
77
234
  // Many of the regular expressions use backtracking which results in run time that increases exponentially with
@@ -93,15 +250,53 @@ export function createStackParser(platform: Platform, ...parsers: StackLineParse
93
250
  const frame = parser(cleanedLine, platform)
94
251
  if (frame) {
95
252
  frames.push(frame)
253
+ const cycle = collapseRepeatedCycle(frames)
254
+ if (cycle) {
255
+ // A collapse replaces the suffix starting at cycle.start. Discard records that overlap
256
+ // that suffix, including a previous copy of this cycle, before counting or trimming.
257
+ // The remaining records stay ordered and refer only to untouched earlier frames.
258
+ for (let i = repeatedCycles.length - 1; i >= 0; i--) {
259
+ const previous = repeatedCycles[i] as RepeatedCycle
260
+ if (previous.start + previous.length <= cycle.start) {
261
+ break
262
+ }
263
+ repeatedCycles.pop()
264
+ }
265
+ repeatedCycles.push(cycle)
266
+ }
96
267
  break
97
268
  }
98
269
  }
99
270
 
100
- if (frames.length >= STACKTRACE_FRAME_LIMIT) {
271
+ if (survivingFrameCount(frames, repeatedCycles) >= STACKTRACE_FRAME_LIMIT) {
101
272
  break
102
273
  }
103
274
  }
104
275
 
276
+ // Trimming a section moves the frames after it, so work from the section furthest from the
277
+ // innermost frame and the positions recorded for the sections under it still hold.
278
+ const sections = [...repeatedCycles].sort((a, b) => b.start - a.start)
279
+ const innermostSection = sections[sections.length - 1]
280
+
281
+ // The innermost end goes first. Trimming a section rotates the copy it keeps, and the leftover
282
+ // only reads as part of the cycle while that copy still sits where the stack put it.
283
+ if (innermostSection) {
284
+ const trimmed = innermostPartialCycleLength(frames, innermostSection)
285
+ frames.splice(innermostSection.start - trimmed, trimmed)
286
+
287
+ for (const cycle of sections) {
288
+ cycle.start -= trimmed
289
+ }
290
+ }
291
+
292
+ for (const cycle of sections) {
293
+ trimPartialCycle(frames, cycle)
294
+ }
295
+
296
+ if (repeatedCycles.some((cycle) => cycle.start === 0 && frames.length === cycle.length)) {
297
+ canonicalizeCycleRotation(frames)
298
+ }
299
+
105
300
  return reverseAndStripFrames(frames)
106
301
  }
107
302
  }