@hanzo/event 0.3.2 → 0.3.3

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.
package/src/funnels.ts ADDED
@@ -0,0 +1,154 @@
1
+ // The ONE funnel registry. A funnel is DATA — an ordered list of event names —
2
+ // so the products, the Insights UI, and the docs can never drift: every step is
3
+ // a name from EVENTS (funnels.test.ts fails the build otherwise), and a GOAL that
4
+ // has a funnel points AT one of these rather than restating the steps.
5
+ //
6
+ // Why here and not in Insights: the taxonomy is code that all three surfaces
7
+ // already import (`@hanzo/event`). A funnel defined in the read lens could name
8
+ // an event no surface emits; a funnel defined next to EVENTS cannot.
9
+
10
+ import { EVENTS, PAGEVIEW } from './events'
11
+
12
+ /** The emitting surfaces — the closed set of `AnalyticsConfig.product` values.
13
+ * `product` is on every event, so a funnel scopes by product instead of every
14
+ * surface prefixing its event names. */
15
+ export const PRODUCTS = ['site', 'app', 'chat', 'console', 'admin', 'cloud'] as const
16
+ export type ProductId = (typeof PRODUCTS)[number]
17
+
18
+ export interface FunnelStep {
19
+ /** An EVENTS value (or PAGEVIEW). */
20
+ event: string
21
+ /** Human label for the Insights step. */
22
+ label: string
23
+ /** Property equality that qualifies the step, e.g. first_action{action:'api_call'}. */
24
+ where?: { property: string; equals: string }
25
+ }
26
+
27
+ export interface FunnelDef {
28
+ label: string
29
+ /** Surface(s) the steps are emitted from — matched against the `product` field. */
30
+ products: ProductId[]
31
+ /**
32
+ * How steps are joined:
33
+ * • 'person' — steps join on distinctId (one browser, or one logged-in
34
+ * person across surfaces). The normal case.
35
+ * • 'aggregate' — steps are emitted on DIFFERENT origins by a LOGGED-OUT
36
+ * visitor, so there is no shared id: hanzo.ai, hanzo.app and
37
+ * hanzo.chat each mint their own anonymousId in their own
38
+ * storage. Read these as step-over-step COUNTS, never as a
39
+ * per-person conversion. Honest by construction.
40
+ */
41
+ join: 'person' | 'aggregate'
42
+ steps: FunnelStep[]
43
+ }
44
+
45
+ const s = (event: string, label: string, where?: FunnelStep['where']): FunnelStep => ({
46
+ event,
47
+ label,
48
+ ...(where ? { where } : {}),
49
+ })
50
+
51
+ export const FUNNELS = {
52
+ /** hanzo.ai: land → sign up. IAM hosts the form, so `signup_submitted` is the
53
+ * redirect INTO IAM and `signup_completed` is the return at /auth/callback. */
54
+ signup: {
55
+ label: 'Signup',
56
+ products: ['site'],
57
+ join: 'person',
58
+ steps: [
59
+ s(PAGEVIEW, 'Landed'),
60
+ s(EVENTS.SIGNUP_VIEWED, 'Opened signup'),
61
+ s(EVENTS.SIGNUP_SUBMITTED, 'Redirected to Hanzo ID'),
62
+ s(EVENTS.SIGNUP_COMPLETED, 'Account created'),
63
+ s(EVENTS.FIRST_ACTION, 'First action'),
64
+ ],
65
+ },
66
+
67
+ /** The developer activation path: an account is worth nothing until a key has
68
+ * made a call. `first_action{action:'api_call'}` is emitted SERVER-SIDE by
69
+ * Cloud on an org's first successful /v1 request — a browser cannot see it. */
70
+ apiActivation: {
71
+ label: 'API activation',
72
+ products: ['site', 'cloud'],
73
+ join: 'person',
74
+ steps: [
75
+ s(EVENTS.SIGNUP_COMPLETED, 'Account created'),
76
+ s(EVENTS.API_KEY_CREATED, 'Key minted'),
77
+ s(EVENTS.FIRST_ACTION, 'First successful API call', {
78
+ property: 'action',
79
+ equals: 'api_call',
80
+ }),
81
+ ],
82
+ },
83
+
84
+ /** Upgrade intent → revenue. `order_completed{kind:'plan'}` is the Sale goal. */
85
+ upgrade: {
86
+ label: 'Upgrade',
87
+ products: ['site', 'app', 'console'],
88
+ join: 'person',
89
+ steps: [
90
+ s(EVENTS.PRICING_VIEWED, 'Viewed pricing'),
91
+ s(EVENTS.PLAN_CLICKED, 'Chose a plan'),
92
+ s(EVENTS.CHECKOUT_STARTED, 'Started checkout'),
93
+ s(EVENTS.ORDER_COMPLETED, 'Paid'),
94
+ ],
95
+ },
96
+
97
+ /** hanzo.app: describe → build → deploy → live URL. The whole product thesis
98
+ * in five steps; `deploy_succeeded` is the moment a live URL exists. */
99
+ appShip: {
100
+ label: 'Describe → ship',
101
+ products: ['app'],
102
+ join: 'person',
103
+ steps: [
104
+ s(PAGEVIEW, 'Landed'),
105
+ s(EVENTS.BUILD_STARTED, 'Described an app'),
106
+ s(EVENTS.GENERATION_COMPLETED, 'Got a working build'),
107
+ s(EVENTS.DEPLOY_STARTED, 'Hit publish'),
108
+ s(EVENTS.DEPLOY_SUCCEEDED, 'Live URL'),
109
+ ],
110
+ },
111
+
112
+ /** hanzo.chat: visit → first message → answer. `generation_completed` is what
113
+ * separates "typed something" from "got value". */
114
+ chatEngage: {
115
+ label: 'Chat engagement',
116
+ products: ['chat'],
117
+ join: 'person',
118
+ steps: [
119
+ s(PAGEVIEW, 'Landed'),
120
+ s(EVENTS.CHAT_STARTED, 'Started a conversation'),
121
+ s(EVENTS.CHAT_MESSAGE_SENT, 'Sent a message'),
122
+ s(EVENTS.GENERATION_COMPLETED, 'Got an answer'),
123
+ ],
124
+ },
125
+
126
+ /** The cross-surface handoff: the hanzo.ai composer forwards its prompt to
127
+ * hanzo.chat. Two origins, two anonymousIds — so this is an AGGREGATE funnel.
128
+ * The join is the `referrerProduct` property hanzo.chat reads off `?hz_ref=`,
129
+ * which makes the drop-off measurable without any cross-domain identity. */
130
+ siteToChat: {
131
+ label: 'Site → Chat handoff',
132
+ products: ['site', 'chat'],
133
+ join: 'aggregate',
134
+ steps: [
135
+ s(EVENTS.CHAT_STARTED, 'Submitted the hanzo.ai composer', {
136
+ property: 'source',
137
+ equals: 'composer',
138
+ }),
139
+ s(EVENTS.CHAT_STARTED, 'Landed in hanzo.chat', {
140
+ property: 'referrerProduct',
141
+ equals: 'site',
142
+ }),
143
+ s(EVENTS.GENERATION_COMPLETED, 'Got an answer'),
144
+ ],
145
+ },
146
+ } as const satisfies Record<string, FunnelDef>
147
+
148
+ export type FunnelId = keyof typeof FUNNELS
149
+
150
+ /** eventsOf flattens a funnel to its ordered event names — what a goal's `funnel`
151
+ * field carries, so the steps are defined exactly once (here). */
152
+ export function eventsOf(id: FunnelId): string[] {
153
+ return FUNNELS[id].steps.map((step) => step.event)
154
+ }
package/src/goals.ts CHANGED
@@ -1,44 +1,58 @@
1
1
  // Insights goals + cohorts, defined once as data so the console/insights UI and
2
2
  // every product agree on what "a Signup", "a Sale", and "upgrade intent" mean.
3
3
  // This is the machine-readable spec — the shared source of truth a sync step can
4
- // push into Insights, and what the guide documents.
4
+ // push into Insights, and what TAXONOMY.md documents.
5
+ //
6
+ // A goal answers "what counts as a conversion". A funnel answers "by what path".
7
+ // The paths live in funnels.ts and a goal REFERENCES one by id: the steps are
8
+ // written down exactly once.
5
9
 
6
10
  import { EVENTS } from './events'
11
+ import { eventsOf, type FunnelId } from './funnels'
7
12
 
8
13
  export interface GoalDef {
9
14
  /** Human label shown in Insights. */
10
15
  label: string
11
16
  /** The event whose occurrence counts as the goal conversion. */
12
17
  event: string
13
- /** Optional ordered funnel leading to the goal (for funnel insights). */
18
+ /** The funnel leading to the goal — an id into FUNNELS (see funnels.ts). */
19
+ funnelId?: FunnelId
20
+ /** The ordered event names of `funnelId`, derived — never hand-written. */
14
21
  funnel?: string[]
15
22
  /** Optional property equality filter that qualifies the conversion. */
16
23
  filter?: { property: string; equals: string }
17
24
  }
18
25
 
19
- export const GOALS: Record<'signup' | 'sale' | 'upgradeIntent', GoalDef> = {
20
- // Signup: the conversion is signup_completed; the funnel is the four steps.
26
+ export const GOALS: Record<'signup' | 'sale' | 'upgradeIntent' | 'activation', GoalDef> = {
27
+ // Signup: the conversion is signup_completed, along the site signup funnel.
21
28
  signup: {
22
29
  label: 'Signup',
23
30
  event: EVENTS.SIGNUP_COMPLETED,
24
- funnel: [
25
- EVENTS.SIGNUP_VIEWED,
26
- EVENTS.SIGNUP_SUBMITTED,
27
- EVENTS.SIGNUP_VERIFIED,
28
- EVENTS.FIRST_ACTION,
29
- ],
31
+ funnelId: 'signup',
32
+ funnel: eventsOf('signup'),
30
33
  },
31
34
  // Sale: a completed order qualified as a plan purchase (kind=plan).
32
35
  sale: {
33
36
  label: 'Sale',
34
37
  event: EVENTS.ORDER_COMPLETED,
38
+ funnelId: 'upgrade',
39
+ funnel: eventsOf('upgrade'),
35
40
  filter: { property: 'kind', equals: 'plan' },
36
41
  },
37
42
  // Upgrade intent: a plan click; pricing_viewed is the top of its funnel.
38
43
  upgradeIntent: {
39
44
  label: 'Upgrade Intent',
40
45
  event: EVENTS.PLAN_CLICKED,
41
- funnel: [EVENTS.PRICING_VIEWED, EVENTS.PLAN_CLICKED, EVENTS.CHECKOUT_STARTED],
46
+ funnelId: 'upgrade',
47
+ funnel: eventsOf('upgrade'),
48
+ },
49
+ // Activation: the ONE north-star conversion — an account that did the first
50
+ // valuable thing (a successful API call, a live app, a chat answer).
51
+ activation: {
52
+ label: 'Activation',
53
+ event: EVENTS.FIRST_ACTION,
54
+ funnelId: 'apiActivation',
55
+ funnel: eventsOf('apiActivation'),
42
56
  },
43
57
  }
44
58
 
package/src/index.ts CHANGED
@@ -15,6 +15,8 @@ export { EVENTS, PAGEVIEW } from './events'
15
15
  export type { EventName } from './events'
16
16
  export { GOALS, COHORTS } from './goals'
17
17
  export type { GoalDef, CohortDef } from './goals'
18
+ export { FUNNELS, PRODUCTS, eventsOf } from './funnels'
19
+ export type { FunnelDef, FunnelStep, FunnelId, ProductId } from './funnels'
18
20
  export {
19
21
  parseAttribution,
20
22
  deriveChannel,
package/src/scrub.ts CHANGED
@@ -70,7 +70,12 @@ function redactPAN(s: string): string {
70
70
  })
71
71
  }
72
72
 
73
- const RE_EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g
73
+ // Bounded to the RFC 5321 maxima (local-part 64, domain 255) for the same reason
74
+ // as the creds-in-URL rule: the unbounded form backtracks quadratically across a
75
+ // long run of local-part-legal characters that never reaches an '@' — measured at
76
+ // 20ms on an 8KB worst case, on the main thread, per captured error. No real
77
+ // address is excluded by these caps.
78
+ const RE_EMAIL = /[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g
74
79
  const RE_IPV4 = /\b(?:\d{1,3}\.){3}\d{1,3}\b/g
75
80
  const RE_IPV6 = /\b(?:[0-9A-Fa-f]{1,4}:){2,7}[0-9A-Fa-f]{1,4}\b/g
76
81
 
@@ -258,3 +258,55 @@ describe('fingerprint grouping (port of server model)', () => {
258
258
  expect(f1).not.toBe(f2)
259
259
  })
260
260
  })
261
+
262
+ // ── hostile thrown objects ─────────────────────────────────────────────────
263
+ //
264
+ // `name`, `message` and `stack` are ordinary getters. A thrown object is free to
265
+ // define any of them to throw, and the thrown value is the least trustworthy
266
+ // input this library handles. normalizeError must be TOTAL — buildSentryEvent
267
+ // throwing here meant the crash report was lost on both planes.
268
+
269
+ describe('normalizeError survives hostile input', () => {
270
+ const bomb = (prop: string) => {
271
+ const e = new Error('real message')
272
+ Object.defineProperty(e, prop, {
273
+ get() {
274
+ throw new Error(prop + ' bomb')
275
+ },
276
+ configurable: true,
277
+ })
278
+ return e
279
+ }
280
+
281
+ for (const prop of ['stack', 'message', 'name']) {
282
+ it(`a throwing ${prop} getter does not throw`, () => {
283
+ expect(() => normalizeError(bomb(prop))).not.toThrow()
284
+ const n = normalizeError(bomb(prop))
285
+ expect(typeof n.name).toBe('string')
286
+ expect(typeof n.message).toBe('string')
287
+ })
288
+ }
289
+
290
+ it('buildSentryEvent still produces a usable event from a getter bomb', () => {
291
+ const ev = buildSentryEvent({ error: bomb('stack'), identity: { product: 'test' } })
292
+ expect(ev.exception?.values[0].type).toBe('Error')
293
+ // The message survived because only `stack` was hostile.
294
+ expect(ev.exception?.values[0].value).toBe('real message')
295
+ expect(ev.exception?.values[0].stacktrace?.frames).toEqual([])
296
+ })
297
+
298
+ it('an object with a throwing toString is still reportable', () => {
299
+ const evil = {
300
+ toString() {
301
+ throw new Error('toString bomb')
302
+ },
303
+ }
304
+ expect(() => normalizeError(evil)).not.toThrow()
305
+ expect(() => buildSentryEvent({ error: evil, identity: {} })).not.toThrow()
306
+ })
307
+
308
+ it('a frozen/null-prototype throwable is still reportable', () => {
309
+ const weird = Object.freeze(Object.create(null)) as unknown
310
+ expect(() => buildSentryEvent({ error: weird, identity: {} })).not.toThrow()
311
+ })
312
+ })
package/src/sentry.ts CHANGED
@@ -148,13 +148,43 @@ export function framesFromStack(stack: string | undefined): SentryFrame[] {
148
148
  /** normalizeError coerces an unknown throwable into {name, message, stack}. */
149
149
  export function normalizeError(err: unknown): { name: string; message: string; stack?: string } {
150
150
  if (err instanceof Error) {
151
- return { name: err.name || 'Error', message: err.message || String(err), stack: err.stack }
151
+ // `name`, `message` and `stack` are ordinary getters, and the thrown object is
152
+ // the least trustworthy input this library handles — any of them may throw.
153
+ // Losing the whole report to a hostile getter is not acceptable.
154
+ const name = read(err, 'name')
155
+ const message = read(err, 'message')
156
+ const stack = read(err, 'stack')
157
+ return {
158
+ name: typeof name === 'string' && name ? name : 'Error',
159
+ message: typeof message === 'string' && message ? message : str(err),
160
+ stack: typeof stack === 'string' ? stack : undefined,
161
+ }
152
162
  }
153
163
  if (typeof err === 'string') return { name: 'Error', message: err }
154
164
  try {
155
- return { name: 'Error', message: JSON.stringify(err) }
165
+ return { name: 'Error', message: JSON.stringify(err) ?? str(err) }
166
+ } catch {
167
+ return { name: 'Error', message: str(err) }
168
+ }
169
+ }
170
+
171
+ /** read pulls a property off a possibly-hostile value without letting a throwing
172
+ * getter escape. */
173
+ function read(o: unknown, k: string): unknown {
174
+ try {
175
+ return (o as Record<string, unknown>)[k]
176
+ } catch {
177
+ return undefined
178
+ }
179
+ }
180
+
181
+ /** str coerces to a string without letting a throwing toString/Symbol.toPrimitive
182
+ * escape. */
183
+ function str(v: unknown): string {
184
+ try {
185
+ return String(v)
156
186
  } catch {
157
- return { name: 'Error', message: String(err) }
187
+ return '[unstringifiable]'
158
188
  }
159
189
  }
160
190
 
package/src/version.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  // The library version, stamped on every event (`libraryVersion`) and on the
2
2
  // Sentry `sdk` block. It lives alone so `sentry.ts` can read it without importing
3
3
  // `core.ts` — core imports sentry, so the reverse would be an import cycle.
4
- export const VERSION = '0.3.2'
4
+ export const VERSION = '0.3.3'