@contractspec/lib.analytics 1.57.0 → 1.58.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.
Files changed (89) hide show
  1. package/dist/browser/churn/index.js +77 -0
  2. package/dist/browser/churn/predictor.js +77 -0
  3. package/dist/browser/cohort/index.js +117 -0
  4. package/dist/browser/cohort/tracker.js +117 -0
  5. package/dist/browser/funnel/analyzer.js +68 -0
  6. package/dist/browser/funnel/index.js +68 -0
  7. package/dist/browser/growth/hypothesis-generator.js +46 -0
  8. package/dist/browser/growth/index.js +46 -0
  9. package/dist/browser/index.js +723 -0
  10. package/dist/browser/lifecycle/index.js +287 -0
  11. package/dist/browser/lifecycle/metric-collectors.js +58 -0
  12. package/dist/browser/lifecycle/posthog-bridge.js +79 -0
  13. package/dist/browser/lifecycle/posthog-metric-source.js +205 -0
  14. package/dist/browser/posthog/event-source.js +138 -0
  15. package/dist/browser/posthog/index.js +138 -0
  16. package/dist/browser/types.js +0 -0
  17. package/dist/churn/index.d.ts +2 -2
  18. package/dist/churn/index.d.ts.map +1 -0
  19. package/dist/churn/index.js +77 -2
  20. package/dist/churn/predictor.d.ts +15 -19
  21. package/dist/churn/predictor.d.ts.map +1 -1
  22. package/dist/churn/predictor.js +72 -68
  23. package/dist/cohort/index.d.ts +2 -2
  24. package/dist/cohort/index.d.ts.map +1 -0
  25. package/dist/cohort/index.js +117 -2
  26. package/dist/cohort/tracker.d.ts +3 -7
  27. package/dist/cohort/tracker.d.ts.map +1 -1
  28. package/dist/cohort/tracker.js +106 -87
  29. package/dist/funnel/analyzer.d.ts +4 -8
  30. package/dist/funnel/analyzer.d.ts.map +1 -1
  31. package/dist/funnel/analyzer.js +67 -62
  32. package/dist/funnel/index.d.ts +2 -2
  33. package/dist/funnel/index.d.ts.map +1 -0
  34. package/dist/funnel/index.js +69 -3
  35. package/dist/growth/hypothesis-generator.d.ts +11 -15
  36. package/dist/growth/hypothesis-generator.d.ts.map +1 -1
  37. package/dist/growth/hypothesis-generator.js +46 -39
  38. package/dist/growth/index.d.ts +2 -2
  39. package/dist/growth/index.d.ts.map +1 -0
  40. package/dist/growth/index.js +47 -3
  41. package/dist/index.d.ts +8 -10
  42. package/dist/index.d.ts.map +1 -0
  43. package/dist/index.js +724 -12
  44. package/dist/lifecycle/index.d.ts +4 -4
  45. package/dist/lifecycle/index.d.ts.map +1 -0
  46. package/dist/lifecycle/index.js +287 -4
  47. package/dist/lifecycle/metric-collectors.d.ts +22 -26
  48. package/dist/lifecycle/metric-collectors.d.ts.map +1 -1
  49. package/dist/lifecycle/metric-collectors.js +55 -44
  50. package/dist/lifecycle/posthog-bridge.d.ts +9 -13
  51. package/dist/lifecycle/posthog-bridge.d.ts.map +1 -1
  52. package/dist/lifecycle/posthog-bridge.js +77 -25
  53. package/dist/lifecycle/posthog-metric-source.d.ts +40 -44
  54. package/dist/lifecycle/posthog-metric-source.d.ts.map +1 -1
  55. package/dist/lifecycle/posthog-metric-source.js +200 -180
  56. package/dist/node/churn/index.js +77 -0
  57. package/dist/node/churn/predictor.js +77 -0
  58. package/dist/node/cohort/index.js +117 -0
  59. package/dist/node/cohort/tracker.js +117 -0
  60. package/dist/node/funnel/analyzer.js +68 -0
  61. package/dist/node/funnel/index.js +68 -0
  62. package/dist/node/growth/hypothesis-generator.js +46 -0
  63. package/dist/node/growth/index.js +46 -0
  64. package/dist/node/index.js +723 -0
  65. package/dist/node/lifecycle/index.js +287 -0
  66. package/dist/node/lifecycle/metric-collectors.js +58 -0
  67. package/dist/node/lifecycle/posthog-bridge.js +79 -0
  68. package/dist/node/lifecycle/posthog-metric-source.js +205 -0
  69. package/dist/node/posthog/event-source.js +138 -0
  70. package/dist/node/posthog/index.js +138 -0
  71. package/dist/node/types.js +0 -0
  72. package/dist/posthog/event-source.d.ts +18 -22
  73. package/dist/posthog/event-source.d.ts.map +1 -1
  74. package/dist/posthog/event-source.js +131 -111
  75. package/dist/posthog/index.d.ts +2 -2
  76. package/dist/posthog/index.d.ts.map +1 -0
  77. package/dist/posthog/index.js +139 -3
  78. package/dist/types.d.ts +52 -55
  79. package/dist/types.d.ts.map +1 -1
  80. package/dist/types.js +1 -0
  81. package/package.json +189 -46
  82. package/dist/churn/predictor.js.map +0 -1
  83. package/dist/cohort/tracker.js.map +0 -1
  84. package/dist/funnel/analyzer.js.map +0 -1
  85. package/dist/growth/hypothesis-generator.js.map +0 -1
  86. package/dist/lifecycle/metric-collectors.js.map +0 -1
  87. package/dist/lifecycle/posthog-bridge.js.map +0 -1
  88. package/dist/lifecycle/posthog-metric-source.js.map +0 -1
  89. package/dist/posthog/event-source.js.map +0 -1
@@ -0,0 +1,77 @@
1
+ // src/churn/predictor.ts
2
+ import dayjs from "dayjs";
3
+
4
+ class ChurnPredictor {
5
+ recencyWeight;
6
+ frequencyWeight;
7
+ errorWeight;
8
+ decayDays;
9
+ constructor(options) {
10
+ this.recencyWeight = options?.recencyWeight ?? 0.5;
11
+ this.frequencyWeight = options?.frequencyWeight ?? 0.3;
12
+ this.errorWeight = options?.errorWeight ?? 0.2;
13
+ this.decayDays = options?.decayDays ?? 14;
14
+ }
15
+ score(events) {
16
+ const grouped = groupBy(events, (event) => event.userId);
17
+ const signals = [];
18
+ for (const [userId, userEvents] of grouped.entries()) {
19
+ const score = this.computeScore(userEvents);
20
+ signals.push({
21
+ userId,
22
+ score,
23
+ bucket: score >= 0.7 ? "high" : score >= 0.4 ? "medium" : "low",
24
+ drivers: this.drivers(userEvents)
25
+ });
26
+ }
27
+ return signals.sort((a, b) => b.score - a.score);
28
+ }
29
+ computeScore(events) {
30
+ if (!events.length)
31
+ return 0;
32
+ const sorted = events.sort((a, b) => dateMs(a) - dateMs(b));
33
+ const lastEvent = sorted[sorted.length - 1];
34
+ if (!lastEvent)
35
+ return 0;
36
+ const daysSinceLast = dayjs().diff(dayjs(lastEvent.timestamp), "day");
37
+ const recencyScore = Math.max(0, 1 - daysSinceLast / this.decayDays);
38
+ const windowStart = dayjs().subtract(this.decayDays, "day");
39
+ const recentEvents = sorted.filter((event) => dayjs(event.timestamp).isAfter(windowStart));
40
+ const averagePerDay = recentEvents.length / Math.max(this.decayDays, 1);
41
+ const frequencyScore = Math.min(1, averagePerDay * 5);
42
+ const errorEvents = recentEvents.filter((event) => typeof event.properties?.error !== "undefined" || /error|failed/i.test(event.name)).length;
43
+ const errorScore = Math.min(1, errorEvents / 3);
44
+ const score = recencyScore * this.recencyWeight + frequencyScore * this.frequencyWeight + (1 - errorScore) * this.errorWeight;
45
+ return Number(score.toFixed(3));
46
+ }
47
+ drivers(events) {
48
+ const drivers = [];
49
+ const sorted = events.sort((a, b) => dateMs(a) - dateMs(b));
50
+ const lastEvent = sorted[sorted.length - 1];
51
+ if (lastEvent) {
52
+ const days = dayjs().diff(dayjs(lastEvent.timestamp), "day");
53
+ if (days > this.decayDays)
54
+ drivers.push(`Inactive for ${days} days`);
55
+ }
56
+ const errorEvents = events.filter((event) => typeof event.properties?.error !== "undefined" || /error|failed/i.test(event.name));
57
+ if (errorEvents.length)
58
+ drivers.push(`${errorEvents.length} errors logged`);
59
+ return drivers;
60
+ }
61
+ }
62
+ function groupBy(items, selector) {
63
+ const map = new Map;
64
+ for (const item of items) {
65
+ const key = selector(item);
66
+ const list = map.get(key) ?? [];
67
+ list.push(item);
68
+ map.set(key, list);
69
+ }
70
+ return map;
71
+ }
72
+ function dateMs(event) {
73
+ return new Date(event.timestamp).getTime();
74
+ }
75
+ export {
76
+ ChurnPredictor
77
+ };
@@ -0,0 +1,77 @@
1
+ // src/churn/predictor.ts
2
+ import dayjs from "dayjs";
3
+
4
+ class ChurnPredictor {
5
+ recencyWeight;
6
+ frequencyWeight;
7
+ errorWeight;
8
+ decayDays;
9
+ constructor(options) {
10
+ this.recencyWeight = options?.recencyWeight ?? 0.5;
11
+ this.frequencyWeight = options?.frequencyWeight ?? 0.3;
12
+ this.errorWeight = options?.errorWeight ?? 0.2;
13
+ this.decayDays = options?.decayDays ?? 14;
14
+ }
15
+ score(events) {
16
+ const grouped = groupBy(events, (event) => event.userId);
17
+ const signals = [];
18
+ for (const [userId, userEvents] of grouped.entries()) {
19
+ const score = this.computeScore(userEvents);
20
+ signals.push({
21
+ userId,
22
+ score,
23
+ bucket: score >= 0.7 ? "high" : score >= 0.4 ? "medium" : "low",
24
+ drivers: this.drivers(userEvents)
25
+ });
26
+ }
27
+ return signals.sort((a, b) => b.score - a.score);
28
+ }
29
+ computeScore(events) {
30
+ if (!events.length)
31
+ return 0;
32
+ const sorted = events.sort((a, b) => dateMs(a) - dateMs(b));
33
+ const lastEvent = sorted[sorted.length - 1];
34
+ if (!lastEvent)
35
+ return 0;
36
+ const daysSinceLast = dayjs().diff(dayjs(lastEvent.timestamp), "day");
37
+ const recencyScore = Math.max(0, 1 - daysSinceLast / this.decayDays);
38
+ const windowStart = dayjs().subtract(this.decayDays, "day");
39
+ const recentEvents = sorted.filter((event) => dayjs(event.timestamp).isAfter(windowStart));
40
+ const averagePerDay = recentEvents.length / Math.max(this.decayDays, 1);
41
+ const frequencyScore = Math.min(1, averagePerDay * 5);
42
+ const errorEvents = recentEvents.filter((event) => typeof event.properties?.error !== "undefined" || /error|failed/i.test(event.name)).length;
43
+ const errorScore = Math.min(1, errorEvents / 3);
44
+ const score = recencyScore * this.recencyWeight + frequencyScore * this.frequencyWeight + (1 - errorScore) * this.errorWeight;
45
+ return Number(score.toFixed(3));
46
+ }
47
+ drivers(events) {
48
+ const drivers = [];
49
+ const sorted = events.sort((a, b) => dateMs(a) - dateMs(b));
50
+ const lastEvent = sorted[sorted.length - 1];
51
+ if (lastEvent) {
52
+ const days = dayjs().diff(dayjs(lastEvent.timestamp), "day");
53
+ if (days > this.decayDays)
54
+ drivers.push(`Inactive for ${days} days`);
55
+ }
56
+ const errorEvents = events.filter((event) => typeof event.properties?.error !== "undefined" || /error|failed/i.test(event.name));
57
+ if (errorEvents.length)
58
+ drivers.push(`${errorEvents.length} errors logged`);
59
+ return drivers;
60
+ }
61
+ }
62
+ function groupBy(items, selector) {
63
+ const map = new Map;
64
+ for (const item of items) {
65
+ const key = selector(item);
66
+ const list = map.get(key) ?? [];
67
+ list.push(item);
68
+ map.set(key, list);
69
+ }
70
+ return map;
71
+ }
72
+ function dateMs(event) {
73
+ return new Date(event.timestamp).getTime();
74
+ }
75
+ export {
76
+ ChurnPredictor
77
+ };
@@ -0,0 +1,117 @@
1
+ // src/cohort/tracker.ts
2
+ import dayjs from "dayjs";
3
+
4
+ class CohortTracker {
5
+ analyze(events, definition) {
6
+ const groupedByUser = groupBy(events, (event) => event.userId);
7
+ const cohorts = new Map;
8
+ for (const [userId, userEvents] of groupedByUser.entries()) {
9
+ userEvents.sort((a, b) => dateMs(a) - dateMs(b));
10
+ const signup = userEvents[0];
11
+ if (!signup)
12
+ continue;
13
+ const cohortKey = bucketKey(signup.timestamp, definition.bucket);
14
+ const builder = cohorts.get(cohortKey) ?? new CohortStatsBuilder(cohortKey, definition);
15
+ builder.addUser(userId);
16
+ for (const event of userEvents) {
17
+ builder.addEvent(userId, event);
18
+ }
19
+ cohorts.set(cohortKey, builder);
20
+ }
21
+ return {
22
+ definition,
23
+ cohorts: [...cohorts.values()].map((builder) => builder.build())
24
+ };
25
+ }
26
+ }
27
+
28
+ class CohortStatsBuilder {
29
+ key;
30
+ definition;
31
+ users = new Set;
32
+ retentionMap = new Map;
33
+ ltv = 0;
34
+ constructor(key, definition) {
35
+ this.key = key;
36
+ this.definition = definition;
37
+ }
38
+ addUser(userId) {
39
+ this.users.add(userId);
40
+ }
41
+ addEvent(userId, event) {
42
+ const period = bucketDiff(this.key, event.timestamp, this.definition.bucket);
43
+ if (period < 0 || period >= this.definition.periods)
44
+ return;
45
+ const bucket = this.retentionMap.get(period) ?? new Set;
46
+ bucket.add(userId);
47
+ this.retentionMap.set(period, bucket);
48
+ const amount = typeof event.properties?.amount === "number" ? event.properties.amount : 0;
49
+ this.ltv += amount;
50
+ }
51
+ build() {
52
+ const totalUsers = this.users.size || 1;
53
+ const retention = [];
54
+ for (let period = 0;period < this.definition.periods; period++) {
55
+ const active = this.retentionMap.get(period)?.size ?? 0;
56
+ retention.push(Number((active / totalUsers).toFixed(3)));
57
+ }
58
+ return {
59
+ cohortKey: this.key,
60
+ users: this.users.size,
61
+ retention,
62
+ ltv: Number(this.ltv.toFixed(2))
63
+ };
64
+ }
65
+ }
66
+ function groupBy(items, selector) {
67
+ const map = new Map;
68
+ for (const item of items) {
69
+ const key = selector(item);
70
+ const list = map.get(key) ?? [];
71
+ list.push(item);
72
+ map.set(key, list);
73
+ }
74
+ return map;
75
+ }
76
+ function bucketKey(timestamp, bucket) {
77
+ const dt = dayjs(timestamp);
78
+ switch (bucket) {
79
+ case "day":
80
+ return dt.startOf("day").format("YYYY-MM-DD");
81
+ case "week":
82
+ return dt.startOf("week").format("YYYY-[W]WW");
83
+ case "month":
84
+ default:
85
+ return dt.startOf("month").format("YYYY-MM");
86
+ }
87
+ }
88
+ function bucketDiff(cohortKey, timestamp, bucket) {
89
+ const start = parseBucketKey(cohortKey, bucket);
90
+ const target = dayjs(timestamp);
91
+ switch (bucket) {
92
+ case "day":
93
+ return target.diff(start, "day");
94
+ case "week":
95
+ return target.diff(start, "week");
96
+ case "month":
97
+ default:
98
+ return target.diff(start, "month");
99
+ }
100
+ }
101
+ function parseBucketKey(key, bucket) {
102
+ switch (bucket) {
103
+ case "day":
104
+ return dayjs(key, "YYYY-MM-DD");
105
+ case "week":
106
+ return dayjs(key.replace("W", ""), "YYYY-ww");
107
+ case "month":
108
+ default:
109
+ return dayjs(key, "YYYY-MM");
110
+ }
111
+ }
112
+ function dateMs(event) {
113
+ return new Date(event.timestamp).getTime();
114
+ }
115
+ export {
116
+ CohortTracker
117
+ };
@@ -0,0 +1,117 @@
1
+ // src/cohort/tracker.ts
2
+ import dayjs from "dayjs";
3
+
4
+ class CohortTracker {
5
+ analyze(events, definition) {
6
+ const groupedByUser = groupBy(events, (event) => event.userId);
7
+ const cohorts = new Map;
8
+ for (const [userId, userEvents] of groupedByUser.entries()) {
9
+ userEvents.sort((a, b) => dateMs(a) - dateMs(b));
10
+ const signup = userEvents[0];
11
+ if (!signup)
12
+ continue;
13
+ const cohortKey = bucketKey(signup.timestamp, definition.bucket);
14
+ const builder = cohorts.get(cohortKey) ?? new CohortStatsBuilder(cohortKey, definition);
15
+ builder.addUser(userId);
16
+ for (const event of userEvents) {
17
+ builder.addEvent(userId, event);
18
+ }
19
+ cohorts.set(cohortKey, builder);
20
+ }
21
+ return {
22
+ definition,
23
+ cohorts: [...cohorts.values()].map((builder) => builder.build())
24
+ };
25
+ }
26
+ }
27
+
28
+ class CohortStatsBuilder {
29
+ key;
30
+ definition;
31
+ users = new Set;
32
+ retentionMap = new Map;
33
+ ltv = 0;
34
+ constructor(key, definition) {
35
+ this.key = key;
36
+ this.definition = definition;
37
+ }
38
+ addUser(userId) {
39
+ this.users.add(userId);
40
+ }
41
+ addEvent(userId, event) {
42
+ const period = bucketDiff(this.key, event.timestamp, this.definition.bucket);
43
+ if (period < 0 || period >= this.definition.periods)
44
+ return;
45
+ const bucket = this.retentionMap.get(period) ?? new Set;
46
+ bucket.add(userId);
47
+ this.retentionMap.set(period, bucket);
48
+ const amount = typeof event.properties?.amount === "number" ? event.properties.amount : 0;
49
+ this.ltv += amount;
50
+ }
51
+ build() {
52
+ const totalUsers = this.users.size || 1;
53
+ const retention = [];
54
+ for (let period = 0;period < this.definition.periods; period++) {
55
+ const active = this.retentionMap.get(period)?.size ?? 0;
56
+ retention.push(Number((active / totalUsers).toFixed(3)));
57
+ }
58
+ return {
59
+ cohortKey: this.key,
60
+ users: this.users.size,
61
+ retention,
62
+ ltv: Number(this.ltv.toFixed(2))
63
+ };
64
+ }
65
+ }
66
+ function groupBy(items, selector) {
67
+ const map = new Map;
68
+ for (const item of items) {
69
+ const key = selector(item);
70
+ const list = map.get(key) ?? [];
71
+ list.push(item);
72
+ map.set(key, list);
73
+ }
74
+ return map;
75
+ }
76
+ function bucketKey(timestamp, bucket) {
77
+ const dt = dayjs(timestamp);
78
+ switch (bucket) {
79
+ case "day":
80
+ return dt.startOf("day").format("YYYY-MM-DD");
81
+ case "week":
82
+ return dt.startOf("week").format("YYYY-[W]WW");
83
+ case "month":
84
+ default:
85
+ return dt.startOf("month").format("YYYY-MM");
86
+ }
87
+ }
88
+ function bucketDiff(cohortKey, timestamp, bucket) {
89
+ const start = parseBucketKey(cohortKey, bucket);
90
+ const target = dayjs(timestamp);
91
+ switch (bucket) {
92
+ case "day":
93
+ return target.diff(start, "day");
94
+ case "week":
95
+ return target.diff(start, "week");
96
+ case "month":
97
+ default:
98
+ return target.diff(start, "month");
99
+ }
100
+ }
101
+ function parseBucketKey(key, bucket) {
102
+ switch (bucket) {
103
+ case "day":
104
+ return dayjs(key, "YYYY-MM-DD");
105
+ case "week":
106
+ return dayjs(key.replace("W", ""), "YYYY-ww");
107
+ case "month":
108
+ default:
109
+ return dayjs(key, "YYYY-MM");
110
+ }
111
+ }
112
+ function dateMs(event) {
113
+ return new Date(event.timestamp).getTime();
114
+ }
115
+ export {
116
+ CohortTracker
117
+ };
@@ -0,0 +1,68 @@
1
+ // src/funnel/analyzer.ts
2
+ class FunnelAnalyzer {
3
+ analyze(events, definition) {
4
+ const windowMs = (definition.windowHours ?? 72) * 60 * 60 * 1000;
5
+ const eventsByUser = groupByUser(events);
6
+ const stepCounts = definition.steps.map(() => 0);
7
+ for (const userEvents of eventsByUser.values()) {
8
+ const completionIndex = this.evaluateUser(userEvents, definition.steps, windowMs);
9
+ completionIndex.forEach((hit, stepIdx) => {
10
+ if (hit) {
11
+ stepCounts[stepIdx] = (stepCounts[stepIdx] ?? 0) + 1;
12
+ }
13
+ });
14
+ }
15
+ const totalUsers = eventsByUser.size;
16
+ const steps = definition.steps.map((step, index) => {
17
+ const prevCount = index === 0 ? totalUsers : stepCounts[index - 1] || 1;
18
+ const count = stepCounts[index] ?? 0;
19
+ const conversionRate = prevCount === 0 ? 0 : Number((count / prevCount).toFixed(3));
20
+ const dropOffRate = Number((1 - conversionRate).toFixed(3));
21
+ return { step, count, conversionRate, dropOffRate };
22
+ });
23
+ return {
24
+ definition,
25
+ totalUsers,
26
+ steps
27
+ };
28
+ }
29
+ evaluateUser(events, steps, windowMs) {
30
+ const sorted = [...events].sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
31
+ const completion = Array(steps.length).fill(false);
32
+ let cursor = 0;
33
+ let anchorTime;
34
+ for (const event of sorted) {
35
+ const step = steps[cursor];
36
+ if (!step)
37
+ break;
38
+ if (event.name !== step.eventName)
39
+ continue;
40
+ if (step.match && !step.match(event))
41
+ continue;
42
+ const eventTime = new Date(event.timestamp).getTime();
43
+ if (cursor === 0) {
44
+ anchorTime = eventTime;
45
+ completion[cursor] = true;
46
+ cursor += 1;
47
+ continue;
48
+ }
49
+ if (anchorTime && eventTime - anchorTime <= windowMs) {
50
+ completion[cursor] = true;
51
+ cursor += 1;
52
+ }
53
+ }
54
+ return completion;
55
+ }
56
+ }
57
+ function groupByUser(events) {
58
+ const map = new Map;
59
+ for (const event of events) {
60
+ const list = map.get(event.userId) ?? [];
61
+ list.push(event);
62
+ map.set(event.userId, list);
63
+ }
64
+ return map;
65
+ }
66
+ export {
67
+ FunnelAnalyzer
68
+ };
@@ -0,0 +1,68 @@
1
+ // src/funnel/analyzer.ts
2
+ class FunnelAnalyzer {
3
+ analyze(events, definition) {
4
+ const windowMs = (definition.windowHours ?? 72) * 60 * 60 * 1000;
5
+ const eventsByUser = groupByUser(events);
6
+ const stepCounts = definition.steps.map(() => 0);
7
+ for (const userEvents of eventsByUser.values()) {
8
+ const completionIndex = this.evaluateUser(userEvents, definition.steps, windowMs);
9
+ completionIndex.forEach((hit, stepIdx) => {
10
+ if (hit) {
11
+ stepCounts[stepIdx] = (stepCounts[stepIdx] ?? 0) + 1;
12
+ }
13
+ });
14
+ }
15
+ const totalUsers = eventsByUser.size;
16
+ const steps = definition.steps.map((step, index) => {
17
+ const prevCount = index === 0 ? totalUsers : stepCounts[index - 1] || 1;
18
+ const count = stepCounts[index] ?? 0;
19
+ const conversionRate = prevCount === 0 ? 0 : Number((count / prevCount).toFixed(3));
20
+ const dropOffRate = Number((1 - conversionRate).toFixed(3));
21
+ return { step, count, conversionRate, dropOffRate };
22
+ });
23
+ return {
24
+ definition,
25
+ totalUsers,
26
+ steps
27
+ };
28
+ }
29
+ evaluateUser(events, steps, windowMs) {
30
+ const sorted = [...events].sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
31
+ const completion = Array(steps.length).fill(false);
32
+ let cursor = 0;
33
+ let anchorTime;
34
+ for (const event of sorted) {
35
+ const step = steps[cursor];
36
+ if (!step)
37
+ break;
38
+ if (event.name !== step.eventName)
39
+ continue;
40
+ if (step.match && !step.match(event))
41
+ continue;
42
+ const eventTime = new Date(event.timestamp).getTime();
43
+ if (cursor === 0) {
44
+ anchorTime = eventTime;
45
+ completion[cursor] = true;
46
+ cursor += 1;
47
+ continue;
48
+ }
49
+ if (anchorTime && eventTime - anchorTime <= windowMs) {
50
+ completion[cursor] = true;
51
+ cursor += 1;
52
+ }
53
+ }
54
+ return completion;
55
+ }
56
+ }
57
+ function groupByUser(events) {
58
+ const map = new Map;
59
+ for (const event of events) {
60
+ const list = map.get(event.userId) ?? [];
61
+ list.push(event);
62
+ map.set(event.userId, list);
63
+ }
64
+ return map;
65
+ }
66
+ export {
67
+ FunnelAnalyzer
68
+ };
@@ -0,0 +1,46 @@
1
+ // src/growth/hypothesis-generator.ts
2
+ class GrowthHypothesisGenerator {
3
+ minDelta;
4
+ constructor(options) {
5
+ this.minDelta = options?.minDelta ?? 0.05;
6
+ }
7
+ generate(metrics) {
8
+ return metrics.map((metric) => this.fromMetric(metric)).filter((hypothesis) => Boolean(hypothesis));
9
+ }
10
+ fromMetric(metric) {
11
+ const change = this.delta(metric);
12
+ if (Math.abs(change) < this.minDelta)
13
+ return null;
14
+ const direction = change > 0 ? "rising" : "declining";
15
+ const statement = this.statement(metric, change, direction);
16
+ return {
17
+ statement,
18
+ metric: metric.name,
19
+ confidence: Math.abs(change) > 0.2 ? "high" : "medium",
20
+ impact: this.impact(metric)
21
+ };
22
+ }
23
+ delta(metric) {
24
+ if (metric.previous == null)
25
+ return 0;
26
+ const prev = metric.previous || 1;
27
+ return (metric.current - prev) / Math.abs(prev);
28
+ }
29
+ impact(metric) {
30
+ if (metric.target && metric.current < metric.target * 0.8)
31
+ return "high";
32
+ if (metric.target && metric.current < metric.target)
33
+ return "medium";
34
+ return "low";
35
+ }
36
+ statement(metric, change, direction) {
37
+ const percent = Math.abs(parseFloat((change * 100).toFixed(1)));
38
+ if (direction === "declining") {
39
+ return `${metric.name} is down ${percent}% vs last period; test new onboarding prompts to recover activation.`;
40
+ }
41
+ return `${metric.name} grew ${percent}% period-over-period; double down with expanded experiment or pricing test.`;
42
+ }
43
+ }
44
+ export {
45
+ GrowthHypothesisGenerator
46
+ };
@@ -0,0 +1,46 @@
1
+ // src/growth/hypothesis-generator.ts
2
+ class GrowthHypothesisGenerator {
3
+ minDelta;
4
+ constructor(options) {
5
+ this.minDelta = options?.minDelta ?? 0.05;
6
+ }
7
+ generate(metrics) {
8
+ return metrics.map((metric) => this.fromMetric(metric)).filter((hypothesis) => Boolean(hypothesis));
9
+ }
10
+ fromMetric(metric) {
11
+ const change = this.delta(metric);
12
+ if (Math.abs(change) < this.minDelta)
13
+ return null;
14
+ const direction = change > 0 ? "rising" : "declining";
15
+ const statement = this.statement(metric, change, direction);
16
+ return {
17
+ statement,
18
+ metric: metric.name,
19
+ confidence: Math.abs(change) > 0.2 ? "high" : "medium",
20
+ impact: this.impact(metric)
21
+ };
22
+ }
23
+ delta(metric) {
24
+ if (metric.previous == null)
25
+ return 0;
26
+ const prev = metric.previous || 1;
27
+ return (metric.current - prev) / Math.abs(prev);
28
+ }
29
+ impact(metric) {
30
+ if (metric.target && metric.current < metric.target * 0.8)
31
+ return "high";
32
+ if (metric.target && metric.current < metric.target)
33
+ return "medium";
34
+ return "low";
35
+ }
36
+ statement(metric, change, direction) {
37
+ const percent = Math.abs(parseFloat((change * 100).toFixed(1)));
38
+ if (direction === "declining") {
39
+ return `${metric.name} is down ${percent}% vs last period; test new onboarding prompts to recover activation.`;
40
+ }
41
+ return `${metric.name} grew ${percent}% period-over-period; double down with expanded experiment or pricing test.`;
42
+ }
43
+ }
44
+ export {
45
+ GrowthHypothesisGenerator
46
+ };