@gurulu/cli 0.4.0 → 0.4.2

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 (38) hide show
  1. package/dist/commands/add-server.js +13 -6
  2. package/dist/commands/alerts.d.ts +5 -0
  3. package/dist/commands/alerts.js +43 -15
  4. package/dist/commands/audiences.d.ts +3 -0
  5. package/dist/commands/audiences.js +34 -7
  6. package/dist/commands/events.d.ts +6 -0
  7. package/dist/commands/events.js +182 -1
  8. package/dist/commands/experiments.d.ts +4 -0
  9. package/dist/commands/experiments.js +46 -15
  10. package/dist/commands/funnels.d.ts +17 -0
  11. package/dist/commands/funnels.js +203 -0
  12. package/dist/commands/goals.d.ts +18 -0
  13. package/dist/commands/goals.js +214 -0
  14. package/dist/commands/install.d.ts +8 -0
  15. package/dist/commands/install.js +57 -1
  16. package/dist/commands/sourcemap.d.ts +17 -5
  17. package/dist/commands/sourcemap.js +73 -6
  18. package/dist/commands/watch.d.ts +45 -0
  19. package/dist/commands/watch.js +258 -0
  20. package/dist/frameworks/detect.js +29 -7
  21. package/dist/index.js +158 -13
  22. package/package.json +1 -1
  23. package/scripts/gurulu-agentic-install.mjs +275 -3
  24. package/scripts/gurulu-scan.lib.cjs +539 -19
  25. package/scripts/patches/auto-instrument/ast-helper.cjs +158 -10
  26. package/scripts/patches/auto-instrument/astro.cjs +12 -6
  27. package/scripts/patches/auto-instrument/express.cjs +23 -8
  28. package/scripts/patches/auto-instrument/fastify.cjs +7 -3
  29. package/scripts/patches/auto-instrument/hono.cjs +392 -0
  30. package/scripts/patches/auto-instrument/index.cjs +2 -0
  31. package/scripts/patches/auto-instrument/nestjs.cjs +7 -3
  32. package/scripts/patches/auto-instrument/nextjs-app-router.cjs +40 -13
  33. package/scripts/patches/auto-instrument/nextjs-pages.cjs +23 -10
  34. package/scripts/patches/auto-instrument/remix.cjs +7 -3
  35. package/scripts/patches/auto-instrument/sdk-helper-map.cjs +241 -0
  36. package/scripts/patches/auto-instrument/sveltekit.cjs +7 -3
  37. package/scripts/patches/auto-instrument/vue.cjs +7 -3
  38. package/scripts/patches/index.cjs +6 -0
@@ -0,0 +1,241 @@
1
+ // scripts/patches/auto-instrument/sdk-helper-map.cjs — Sprint D / D1.
2
+ //
3
+ // CommonJS port of the canonical event → typed SDK helper map. Mirrors a
4
+ // subset of `src/lib/intelligence/sdk-helper-mapping.ts` so the auto-
5
+ // instrumenter (a pure-Node CJS pipeline) can pick a typed helper like
6
+ // `gurulu.purchase({...})` instead of the generic `gurulu.track('$purchase',
7
+ // {...})` when an event matches a known canonical name.
8
+ //
9
+ // We intentionally only encode the *server* mapping here — the auto-
10
+ // instrumenter writes Node/server-side route handlers, never web/iOS/Android
11
+ // code. The TS file remains the source of truth for the multi-platform
12
+ // onboarding UI.
13
+ //
14
+ // Schema:
15
+ // eventName → {
16
+ // method: 'purchase' // bare method on `gurulu` singleton
17
+ // args: [arg-spec, ...] // ordered positional arg specs
18
+ // }
19
+ //
20
+ // Each arg-spec is either:
21
+ // { kind: 'object', props: [{ name, propName, required, default? }] }
22
+ // → emits `{ propName: <expr from ctx[name]>, ... }`
23
+ // { kind: 'value', name }
24
+ // → emits the JS expression bound to property `name` (or undefined)
25
+ //
26
+ // `selectHelper(eventName, propMap)` returns null when no typed helper
27
+ // applies to the given event/properties. Callers fall back to the generic
28
+ // `gurulu.track(name, {...})` form. This function is pure — it does not
29
+ // require any AST/Babel APIs.
30
+
31
+ // Common property aliases. The `propMap` callers feed us is keyed by the
32
+ // extracted property `name`, but typed helpers expect canonical fields like
33
+ // `value`, `currency`, `transactionId`. We accept any of the listed aliases.
34
+ const PROP_ALIASES = {
35
+ value: ['value', 'amount', 'total', 'price', 'revenue'],
36
+ currency: ['currency', 'currency_code', 'currencyCode'],
37
+ transactionId: ['transactionId', 'transaction_id', 'orderId', 'order_id', 'id'],
38
+ orderId: ['orderId', 'order_id'],
39
+ userId: ['userId', 'user_id', 'uid'],
40
+ email: ['email', 'user_email'],
41
+ method: ['method', 'auth_method', 'provider'],
42
+ plan: ['plan', 'plan_id', 'planId', 'subscription_plan'],
43
+ query: ['query', 'q', 'search_term', 'searchTerm'],
44
+ };
45
+
46
+ // Server-side typed helpers. Each entry's `method` is the bare method name
47
+ // on the `gurulu` singleton (`gurulu.<method>(...)`). When `args` is a single
48
+ // object spec we emit `gurulu.<method>({ ... })`. Multiple arg-specs would
49
+ // emit positional args, but no current helper needs that shape.
50
+ const HELPER_MAP = {
51
+ $purchase: {
52
+ method: 'purchase',
53
+ args: [
54
+ {
55
+ kind: 'object',
56
+ props: [
57
+ { name: 'value', propName: 'value', required: true },
58
+ { name: 'currency', propName: 'currency', required: true },
59
+ { name: 'transactionId', propName: 'transaction_id', required: false },
60
+ ],
61
+ },
62
+ ],
63
+ },
64
+ $payment_succeeded: {
65
+ method: 'paymentSucceeded',
66
+ args: [
67
+ {
68
+ kind: 'object',
69
+ props: [
70
+ { name: 'userId', propName: 'userId', required: false },
71
+ { name: 'value', propName: 'amount', required: true },
72
+ { name: 'currency', propName: 'currency', required: true },
73
+ { name: 'orderId', propName: 'orderId', required: false },
74
+ ],
75
+ },
76
+ ],
77
+ },
78
+ $order_placed: {
79
+ method: 'orderPlaced',
80
+ args: [
81
+ {
82
+ kind: 'object',
83
+ props: [
84
+ { name: 'userId', propName: 'userId', required: false },
85
+ { name: 'orderId', propName: 'orderId', required: true },
86
+ { name: 'value', propName: 'total', required: true },
87
+ { name: 'currency', propName: 'currency', required: true },
88
+ ],
89
+ },
90
+ ],
91
+ },
92
+ $subscription_started: {
93
+ method: 'subscriptionStarted',
94
+ args: [
95
+ {
96
+ kind: 'object',
97
+ props: [
98
+ { name: 'userId', propName: 'userId', required: false },
99
+ { name: 'plan', propName: 'plan', required: true },
100
+ { name: 'value', propName: 'amount', required: false },
101
+ { name: 'currency', propName: 'currency', required: false },
102
+ ],
103
+ },
104
+ ],
105
+ },
106
+ $subscription_created: {
107
+ method: 'subscriptionStarted',
108
+ args: [
109
+ {
110
+ kind: 'object',
111
+ props: [
112
+ { name: 'userId', propName: 'userId', required: false },
113
+ { name: 'plan', propName: 'plan', required: true },
114
+ { name: 'value', propName: 'amount', required: false },
115
+ { name: 'currency', propName: 'currency', required: false },
116
+ ],
117
+ },
118
+ ],
119
+ },
120
+ $signup: {
121
+ method: 'userCreated',
122
+ args: [
123
+ {
124
+ kind: 'object',
125
+ props: [
126
+ { name: 'userId', propName: 'userId', required: true },
127
+ { name: 'email', propName: 'email', required: false },
128
+ ],
129
+ },
130
+ ],
131
+ },
132
+ $signup_completed: {
133
+ method: 'userCreated',
134
+ args: [
135
+ {
136
+ kind: 'object',
137
+ props: [
138
+ { name: 'userId', propName: 'userId', required: true },
139
+ { name: 'email', propName: 'email', required: false },
140
+ ],
141
+ },
142
+ ],
143
+ },
144
+ $account_created: {
145
+ method: 'userCreated',
146
+ args: [
147
+ {
148
+ kind: 'object',
149
+ props: [
150
+ { name: 'userId', propName: 'userId', required: true },
151
+ { name: 'email', propName: 'email', required: false },
152
+ ],
153
+ },
154
+ ],
155
+ },
156
+ };
157
+
158
+ /**
159
+ * Given an extractedProperties array (each `{ name, source }` where `source`
160
+ * is a JS expression string), build a lookup of `canonicalName → expression`
161
+ * resolving the alias table. Unknown names pass through under their raw key.
162
+ */
163
+ function buildPropertyLookup(extractedProperties) {
164
+ const raw = {};
165
+ const resolved = {};
166
+ if (!Array.isArray(extractedProperties)) {
167
+ return { raw, resolved };
168
+ }
169
+ for (const prop of extractedProperties) {
170
+ if (!prop || !prop.name || !prop.source) continue;
171
+ raw[prop.name] = prop.source;
172
+ }
173
+ // Resolve aliases — for each canonical key, the first alias hit wins.
174
+ for (const [canonical, aliases] of Object.entries(PROP_ALIASES)) {
175
+ for (const alias of aliases) {
176
+ if (Object.prototype.hasOwnProperty.call(raw, alias)) {
177
+ resolved[canonical] = raw[alias];
178
+ break;
179
+ }
180
+ }
181
+ }
182
+ return { raw, resolved };
183
+ }
184
+
185
+ /**
186
+ * Pick a typed helper for the given event + properties. Returns:
187
+ * { method, argExpressions: ['<expr>', ...] } — when the helper applies
188
+ * null — when no helper applies
189
+ *
190
+ * The caller is responsible for parsing each argExpression string into an AST
191
+ * node (e.g. via `parser.parseExpression`) and emitting the corresponding
192
+ * `gurulu.<method>(...)` call. We deliberately stay AST-free here so this
193
+ * module can be unit-tested without Babel.
194
+ */
195
+ function selectHelper(eventName, extractedProperties) {
196
+ const helper = HELPER_MAP[eventName];
197
+ if (!helper) return null;
198
+
199
+ const lookup = buildPropertyLookup(extractedProperties);
200
+ const argExpressions = [];
201
+
202
+ for (const argSpec of helper.args) {
203
+ if (argSpec.kind === 'object') {
204
+ const objectEntries = [];
205
+ let missingRequired = false;
206
+ for (const prop of argSpec.props) {
207
+ const expr = lookup.resolved[prop.name] || lookup.raw[prop.name];
208
+ if (expr) {
209
+ objectEntries.push(`${prop.propName}: ${expr}`);
210
+ } else if (prop.required) {
211
+ missingRequired = true;
212
+ break;
213
+ }
214
+ }
215
+ if (missingRequired) return null;
216
+ argExpressions.push(`{ ${objectEntries.join(', ')} }`);
217
+ } else if (argSpec.kind === 'value') {
218
+ const expr = lookup.resolved[argSpec.name] || lookup.raw[argSpec.name];
219
+ if (!expr) return null;
220
+ argExpressions.push(expr);
221
+ }
222
+ }
223
+
224
+ return { method: helper.method, argExpressions };
225
+ }
226
+
227
+ /**
228
+ * Returns the list of canonical event names that have typed helpers wired.
229
+ * Useful for tests and observability.
230
+ */
231
+ function getMappedEventNames() {
232
+ return Object.keys(HELPER_MAP);
233
+ }
234
+
235
+ module.exports = {
236
+ PROP_ALIASES,
237
+ HELPER_MAP,
238
+ buildPropertyLookup,
239
+ selectHelper,
240
+ getMappedEventNames,
241
+ };
@@ -35,7 +35,7 @@ function routeToCandidates(urlPath) {
35
35
  return out;
36
36
  }
37
37
 
38
- function astInstrumentFile(source, method, events) {
38
+ function astInstrumentFile(source, method, events, opts = {}) {
39
39
  const tree = ast.parseSource(source);
40
40
  const fns = ast.findExportedFunction(tree, method);
41
41
  if (fns.length === 0) return { ok: false, reason: `${method}-not-found` };
@@ -51,7 +51,9 @@ function astInstrumentFile(source, method, events) {
51
51
  }
52
52
  const stmts = events.map((e) => ast.buildTrackStatement(e.name, e.autoProperties));
53
53
  ast.injectTrackBeforeLastReturn(target.fn, target.body, stmts);
54
- ast.ensureGuruluImport(tree);
54
+ // Sprint D / D4 — alias-aware import.
55
+ const specifier = ast.resolveGuruluImportSpecifier(opts.repoRoot, opts.relPath);
56
+ ast.ensureGuruluImport(tree, specifier);
55
57
  const after = ast.generateSource(tree, source);
56
58
  return {
57
59
  ok: true,
@@ -103,9 +105,11 @@ function instrumentEvents(ctx, events) {
103
105
  for (const group of groups.values()) {
104
106
  const abs = path.join(ctx.repoRoot, group.relPath);
105
107
  const before = fs.readFileSync(abs, 'utf8');
108
+ // Sprint D / D4 — pass repoRoot + relPath to the import resolver.
109
+ const fileOpts = { repoRoot: (ctx && ctx.repoRoot) || null, relPath: group.relPath };
106
110
  let res;
107
111
  try {
108
- res = astInstrumentFile(before, group.method, group.events);
112
+ res = astInstrumentFile(before, group.method, group.events, fileOpts);
109
113
  } catch (err) {
110
114
  const msg = (err && err.message) || String(err);
111
115
  // eslint-disable-next-line no-console
@@ -70,7 +70,7 @@ function findEventHandler(tree) {
70
70
  return found;
71
71
  }
72
72
 
73
- function astInstrumentFile(source, events) {
73
+ function astInstrumentFile(source, events, opts = {}) {
74
74
  const tree = ast.parseSource(source);
75
75
  const target = findEventHandler(tree);
76
76
  if (!target) return { ok: false, reason: 'event-handler-not-found' };
@@ -85,7 +85,9 @@ function astInstrumentFile(source, events) {
85
85
  }
86
86
  const stmts = events.map((e) => ast.buildTrackStatement(e.name, e.autoProperties));
87
87
  ast.injectTrackBeforeLastReturn(target.fn, target.body, stmts);
88
- ast.ensureGuruluImport(tree);
88
+ // Sprint D / D4 — alias-aware import.
89
+ const specifier = ast.resolveGuruluImportSpecifier(opts.repoRoot, opts.relPath);
90
+ ast.ensureGuruluImport(tree, specifier);
89
91
  const after = ast.generateSource(tree, source);
90
92
  return {
91
93
  ok: true,
@@ -137,9 +139,11 @@ function instrumentEvents(ctx, events) {
137
139
  for (const group of groups.values()) {
138
140
  const abs = path.join(ctx.repoRoot, group.relPath);
139
141
  const before = fs.readFileSync(abs, 'utf8');
142
+ // Sprint D / D4 — pass repoRoot + relPath to the import resolver.
143
+ const fileOpts = { repoRoot: (ctx && ctx.repoRoot) || null, relPath: group.relPath };
140
144
  let res;
141
145
  try {
142
- res = astInstrumentFile(before, group.events);
146
+ res = astInstrumentFile(before, group.events, fileOpts);
143
147
  } catch (err) {
144
148
  const msg = (err && err.message) || String(err);
145
149
  // eslint-disable-next-line no-console
@@ -42,6 +42,12 @@ const PATCHERS = [
42
42
  ];
43
43
 
44
44
  const PATCHER_BY_NAME = {
45
+ // Sprint D / D3 — `nextjs` (bare) is the alias most agents emit. Resolve it
46
+ // to the App Router patcher (the modern default). The Pages Router can
47
+ // still be selected explicitly via `nextjs-pages`. Auto-detection (in the
48
+ // PATCHERS array above) handles the case where a project actually uses
49
+ // Pages Router and the agent passed `auto`.
50
+ nextjs: nextAppRouter,
45
51
  'nextjs-app': nextAppRouter,
46
52
  'nextjs-app-router': nextAppRouter,
47
53
  'nextjs-pages': nextPages,