@posthog/core 1.69.5 → 1.69.7

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.
@@ -6,10 +6,267 @@ const isValidRegex = (pattern)=>{
6
6
  }
7
7
  return true;
8
8
  };
9
+ const quantifierAt = (pattern, index)=>{
10
+ const character = pattern[index];
11
+ if ('*' === character) return {
12
+ length: 1,
13
+ min: 0,
14
+ max: 1 / 0
15
+ };
16
+ if ('+' === character) return {
17
+ length: 1,
18
+ min: 1,
19
+ max: 1 / 0
20
+ };
21
+ if ('?' === character) return {
22
+ length: 1,
23
+ min: 0,
24
+ max: 1
25
+ };
26
+ if ('{' !== character) return null;
27
+ const repetition = /^\{(\d+)(,(\d*))?\}/.exec(pattern.slice(index));
28
+ if (!repetition) return null;
29
+ const min = Number(repetition[1]);
30
+ const max = repetition[2] ? '' === repetition[3] ? 1 / 0 : Number(repetition[3]) : min;
31
+ return {
32
+ length: repetition[0].length,
33
+ min,
34
+ max
35
+ };
36
+ };
37
+ const newGroup = (flags)=>({
38
+ atoms: [],
39
+ variable: false,
40
+ complex: false,
41
+ flags
42
+ });
43
+ const MODIFIER_GROUP_PREFIX = /^\(\?([ims]*)(?:-([ims]*))?:/;
44
+ const applyModifiers = (flags, added, removed)=>[
45
+ 'i',
46
+ 's'
47
+ ].filter((flag)=>removed.indexOf(flag) < 0 && (flags + added).indexOf(flag) >= 0).join('');
48
+ const ESCAPED_CONTROL_CHARACTERS = {
49
+ n: '\n',
50
+ r: '\r',
51
+ t: '\t',
52
+ f: '\f',
53
+ v: '\v'
54
+ };
55
+ const isRequiredLiteral = (atom)=>void 0 !== atom.literal && atom.min === atom.max && atom.min > 0;
56
+ const MAX_DELIMITER_CHECKS = 10000;
57
+ const spellings = (character, ignoreCase)=>ignoreCase ? [
58
+ character,
59
+ character.toUpperCase()
60
+ ] : [
61
+ character
62
+ ];
63
+ const collectGroupFacts = (group, ignoreCase)=>{
64
+ const facts = {
65
+ delimiterPositions: Object.create(null),
66
+ optionalLiterals: Object.create(null),
67
+ literalsBySpelling: Object.create(null),
68
+ nonLiteralSources: [],
69
+ variableTermsBefore: [],
70
+ variableTerms: 0
71
+ };
72
+ const seenSources = Object.create(null);
73
+ group.atoms.forEach((atom, position)=>{
74
+ facts.variableTermsBefore.push(facts.variableTerms);
75
+ if (atom.max > atom.min) facts.variableTerms++;
76
+ const literal = atom.literal;
77
+ if (void 0 === literal) {
78
+ if (!atom.zeroWidth && !seenSources[atom.source]) {
79
+ seenSources[atom.source] = true;
80
+ facts.nonLiteralSources.push(atom.source);
81
+ }
82
+ return;
83
+ }
84
+ if (isRequiredLiteral(atom)) (facts.delimiterPositions[literal] ||= []).push(position);
85
+ else facts.optionalLiterals[literal] = true;
86
+ spellings(literal, ignoreCase).forEach((spelling)=>{
87
+ const owner = facts.literalsBySpelling[spelling];
88
+ facts.literalsBySpelling[spelling] = void 0 === owner || owner === literal ? literal : null;
89
+ });
90
+ });
91
+ return facts;
92
+ };
93
+ const compileAtomTests = (sources, flags)=>sources.map((source)=>{
94
+ try {
95
+ return new RegExp(`^(?:${source})$`, flags);
96
+ } catch {
97
+ return /[^]/;
98
+ }
99
+ });
100
+ const isSoleMatchOf = (delimiter, facts, ignoreCase, atomTests)=>!facts.optionalLiterals[delimiter] && spellings(delimiter, ignoreCase).every((spelling)=>facts.literalsBySpelling[spelling] === delimiter) && !atomTests.some((atomTest)=>atomTest.test(delimiter));
101
+ const hasAtMostOneVariableTermPerSegment = (occurrences, facts)=>{
102
+ const before = facts.variableTermsBefore;
103
+ for(let i = 0; i < occurrences.length; i++){
104
+ const end = i + 1 < occurrences.length ? before[occurrences[i + 1]] : facts.variableTerms + before[occurrences[0]];
105
+ if (end - before[occurrences[i]] > 1) return false;
106
+ }
107
+ return true;
108
+ };
109
+ const isDelimiterSplit = (group)=>{
110
+ if (group.complex) return false;
111
+ const ignoreCase = group.flags.indexOf('i') >= 0;
112
+ const facts = collectGroupFacts(group, ignoreCase);
113
+ const delimiters = Object.keys(facts.delimiterPositions);
114
+ if (0 === delimiters.length || facts.nonLiteralSources.length * delimiters.length > MAX_DELIMITER_CHECKS) return false;
115
+ const atomTests = compileAtomTests(facts.nonLiteralSources, group.flags);
116
+ return delimiters.some((delimiter)=>isSoleMatchOf(delimiter, facts, ignoreCase, atomTests) && hasAtMostOneVariableTermPerSegment(facts.delimiterPositions[delimiter], facts));
117
+ };
118
+ const hasNestedQuantifier = (pattern)=>{
119
+ const groups = [
120
+ newGroup('')
121
+ ];
122
+ let closedGroup;
123
+ let lastAtom;
124
+ let previousWasQuantifier = false;
125
+ for(let index = 0; index < pattern.length; index++){
126
+ const character = pattern[index];
127
+ const justClosed = closedGroup;
128
+ const atomBefore = lastAtom;
129
+ const isLazyModifier = previousWasQuantifier && '?' === character;
130
+ closedGroup = void 0;
131
+ lastAtom = void 0;
132
+ previousWasQuantifier = false;
133
+ const current = groups[groups.length - 1];
134
+ if (isLazyModifier) continue;
135
+ const quantifier = justClosed || atomBefore ? quantifierAt(pattern, index) : null;
136
+ if (quantifier) {
137
+ if (justClosed && quantifier.max > 1 && justClosed.variable && !isDelimiterSplit(justClosed)) return true;
138
+ if (atomBefore) {
139
+ atomBefore.min *= quantifier.min;
140
+ atomBefore.max *= quantifier.max;
141
+ }
142
+ current.variable ||= quantifier.max > quantifier.min;
143
+ index += quantifier.length - 1;
144
+ previousWasQuantifier = true;
145
+ continue;
146
+ }
147
+ let atom;
148
+ if ('\\' === character) {
149
+ const escaped = pattern[index + 1] ?? '';
150
+ index++;
151
+ if (/[uxckpP0-9]/.test(escaped)) {
152
+ current.complex = true;
153
+ atom = {
154
+ source: '[^]',
155
+ min: 1,
156
+ max: 1
157
+ };
158
+ } else atom = 'b' === escaped || 'B' === escaped ? {
159
+ source: '',
160
+ zeroWidth: true,
161
+ min: 1,
162
+ max: 1
163
+ } : /[dDwWsS]/.test(escaped) ? {
164
+ source: `\\${escaped}`,
165
+ min: 1,
166
+ max: 1
167
+ } : {
168
+ source: `\\${escaped}`,
169
+ literal: ESCAPED_CONTROL_CHARACTERS[escaped] ?? escaped,
170
+ min: 1,
171
+ max: 1
172
+ };
173
+ } else if ('[' === character) {
174
+ const start = index;
175
+ for(index++; index < pattern.length && ']' !== pattern[index]; index++)if ('\\' === pattern[index]) index++;
176
+ atom = {
177
+ source: pattern.slice(start, index + 1),
178
+ min: 1,
179
+ max: 1
180
+ };
181
+ } else if ('(' === character) {
182
+ const group = newGroup(current.flags);
183
+ if ('?' === pattern[index + 1]) {
184
+ const rest = pattern.slice(index);
185
+ const prefix = /^\(\?(?::|=|!|<=|<!|<[^>]*>)/.exec(rest);
186
+ const modifiers = prefix ? null : MODIFIER_GROUP_PREFIX.exec(rest);
187
+ if (prefix) {
188
+ index += prefix[0].length - 1;
189
+ group.complex = /^\(\?<?[=!]/.test(prefix[0]);
190
+ } else if (modifiers) {
191
+ index += modifiers[0].length - 1;
192
+ group.complex = true;
193
+ group.flags = applyModifiers(current.flags, modifiers[1], modifiers[2] ?? '');
194
+ } else {
195
+ index++;
196
+ group.complex = true;
197
+ }
198
+ }
199
+ groups.push(group);
200
+ } else if (')' === character) {
201
+ if (groups.length > 1) {
202
+ const group = groups.pop();
203
+ const parent = groups[groups.length - 1];
204
+ parent.variable ||= group.variable;
205
+ parent.complex = true;
206
+ closedGroup = group;
207
+ }
208
+ } else if ('|' === character) current.complex = true;
209
+ else atom = '^' === character || '$' === character ? {
210
+ source: '',
211
+ zeroWidth: true,
212
+ min: 1,
213
+ max: 1
214
+ } : '.' === character ? {
215
+ source: '.',
216
+ min: 1,
217
+ max: 1
218
+ } : {
219
+ source: character,
220
+ literal: character,
221
+ min: 1,
222
+ max: 1
223
+ };
224
+ if (atom) {
225
+ current.atoms.push(atom);
226
+ lastAtom = atom;
227
+ }
228
+ }
229
+ return false;
230
+ };
231
+ const MAX_COMPILED_PATTERNS = 100;
232
+ const INVALID = 'invalid';
233
+ const UNSAFE = 'unsafe';
234
+ const compiledPatterns = new Map();
235
+ const warnedPatterns = new Set();
236
+ const warnRejectedPattern = (pattern)=>{
237
+ try {
238
+ let warn = "u" > typeof console ? console.warn : void 0;
239
+ while('function' == typeof warn && '__rrweb_original__' in warn)warn = warn.__rrweb_original__;
240
+ if ('function' == typeof warn) warn.call(console, '[PostHog]', `Ignoring regex "${pattern}": a repeated group containing repetition can stall matching, so filters using it never match.`);
241
+ } catch {}
242
+ };
243
+ const compilePattern = (pattern)=>{
244
+ if ('string' != typeof pattern) return INVALID;
245
+ const cached = compiledPatterns.get(pattern);
246
+ if (void 0 !== cached) return cached;
247
+ let compiled;
248
+ try {
249
+ compiled = new RegExp(pattern);
250
+ } catch {
251
+ compiled = INVALID;
252
+ }
253
+ if (compiled !== INVALID && hasNestedQuantifier(pattern)) {
254
+ compiled = UNSAFE;
255
+ if (!warnedPatterns.has(pattern) && warnedPatterns.size < MAX_COMPILED_PATTERNS) {
256
+ warnedPatterns.add(pattern);
257
+ warnRejectedPattern(pattern);
258
+ }
259
+ }
260
+ if (compiledPatterns.size >= MAX_COMPILED_PATTERNS) compiledPatterns.clear();
261
+ compiledPatterns.set(pattern, compiled);
262
+ return compiled;
263
+ };
264
+ const isUnsafePattern = (pattern)=>compilePattern(pattern) === UNSAFE;
9
265
  const isMatchingRegex = (value, pattern)=>{
10
- if (!isValidRegex(pattern)) return false;
266
+ const regex = compilePattern(pattern);
267
+ if (regex === INVALID || regex === UNSAFE) return false;
11
268
  try {
12
- return new RegExp(pattern).test(value);
269
+ return regex.test(value);
13
270
  } catch {
14
271
  return false;
15
272
  }
@@ -19,7 +276,7 @@ const propertyComparisons = {
19
276
  exact: (targets, values)=>values.some((value)=>targets.some((target)=>value === target)),
20
277
  is_not: (targets, values)=>values.every((value)=>targets.every((target)=>value !== target)),
21
278
  regex: (targets, values)=>values.some((value)=>targets.some((target)=>isMatchingRegex(value, target))),
22
- not_regex: (targets, values)=>values.every((value)=>targets.every((target)=>!isMatchingRegex(value, target))),
279
+ not_regex: (targets, values)=>!targets.some(isUnsafePattern) && values.every((value)=>targets.every((target)=>!isMatchingRegex(value, target))),
23
280
  icontains: (targets, values)=>values.map(toLowerCase).some((value)=>targets.map(toLowerCase).some((target)=>value.includes(target))),
24
281
  not_icontains: (targets, values)=>values.map(toLowerCase).every((value)=>targets.map(toLowerCase).every((target)=>!value.includes(target))),
25
282
  gt: (targets, values)=>values.some((value)=>{
@@ -43,4 +300,4 @@ function matchPropertyFilters(propertyFilters, eventProperties) {
43
300
  ]);
44
301
  });
45
302
  }
46
- export { isMatchingRegex, isValidRegex, matchPropertyFilters, propertyComparisons };
303
+ export { hasNestedQuantifier, isMatchingRegex, isValidRegex, matchPropertyFilters, propertyComparisons };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@posthog/core",
3
- "version": "1.69.5",
3
+ "version": "1.69.7",
4
4
  "bugs": {
5
5
  "url": "https://github.com/PostHog/posthog-js/issues"
6
6
  },
@@ -277,6 +277,14 @@ function isPostHogEventProperties(value: JsonType | undefined): value is PostHog
277
277
  return value !== null && typeof value === 'object' && !Array.isArray(value)
278
278
  }
279
279
 
280
+ // A stored queue entry `_flushRoute` can send: an object whose `message` is an object.
281
+ function isWellFormedQueueItem(item: unknown): item is PostHogQueueItem {
282
+ if (typeof item !== 'object' || item === null || Array.isArray(item)) {
283
+ return false
284
+ }
285
+ return isPostHogEventProperties((item as PostHogQueueItem).message)
286
+ }
287
+
280
288
  /**
281
289
  * Outcome of a logs batch send. Keeps HTTP error classification inside core so
282
290
  * PostHogLogs doesn't need to know about specific error types.
@@ -1701,7 +1709,9 @@ export abstract class PostHogCoreStateless {
1701
1709
  throw firstError
1702
1710
  }
1703
1711
 
1704
- this._events.emit('flush', sentMessages)
1712
+ if (sentMessages.length > 0) {
1713
+ this._events.emit('flush', sentMessages)
1714
+ }
1705
1715
  }
1706
1716
 
1707
1717
  protected shouldRetainBatchOnError(error: unknown): boolean {
@@ -1712,6 +1722,21 @@ export abstract class PostHogCoreStateless {
1712
1722
  const queueKey = this.persistedQueueKeyForRoute(route)
1713
1723
  let queue = this.getPersistedProperty<PostHogQueueItem[]>(queueKey) || []
1714
1724
 
1725
+ // Storage can hand back entries that aren't queue items, e.g. after a failed write or a custom storage bug.
1726
+ // Every flush would throw on them, so they are dropped from the stored queue first.
1727
+ const wellFormedQueue = queue.filter(isWellFormedQueueItem)
1728
+ if (wellFormedQueue.length < queue.length) {
1729
+ const dropped = queue.length - wellFormedQueue.length
1730
+ this._logger.warn(`Dropped ${dropped} malformed event(s) from the stored queue.`)
1731
+ this.setPersistedProperty<PostHogQueueItem[]>(queueKey, wellFormedQueue)
1732
+ this._dequeuedMessagesCount += dropped
1733
+ queue = wellFormedQueue
1734
+ if (!queue.length) {
1735
+ await this.flushStorage()
1736
+ return
1737
+ }
1738
+ }
1739
+
1715
1740
  if (!queue.length) {
1716
1741
  return
1717
1742
  }