@gurulu/cli 0.4.6 → 1.0.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 (180) hide show
  1. package/LICENSE +92 -0
  2. package/README.md +35 -106
  3. package/dist/bin.d.ts +3 -0
  4. package/dist/bin.d.ts.map +1 -0
  5. package/dist/bin.js +25410 -0
  6. package/dist/commands/auth.d.ts +23 -20
  7. package/dist/commands/auth.d.ts.map +1 -0
  8. package/dist/commands/doctor.d.ts +20 -6
  9. package/dist/commands/doctor.d.ts.map +1 -0
  10. package/dist/commands/init.d.ts +25 -11
  11. package/dist/commands/init.d.ts.map +1 -0
  12. package/dist/commands/pull.d.ts +13 -0
  13. package/dist/commands/pull.d.ts.map +1 -0
  14. package/dist/commands/push.d.ts +40 -0
  15. package/dist/commands/push.d.ts.map +1 -0
  16. package/dist/commands/validate.d.ts +36 -0
  17. package/dist/commands/validate.d.ts.map +1 -0
  18. package/dist/index.d.ts +4 -1
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.js +24985 -853
  21. package/dist/lib/api.d.ts +139 -0
  22. package/dist/lib/api.d.ts.map +1 -0
  23. package/dist/lib/codegen.d.ts +4 -0
  24. package/dist/lib/codegen.d.ts.map +1 -0
  25. package/dist/lib/config.d.ts +43 -0
  26. package/dist/lib/config.d.ts.map +1 -0
  27. package/package.json +40 -20
  28. package/bin/gurulu.js +0 -2
  29. package/dist/api-client.d.ts +0 -33
  30. package/dist/api-client.js +0 -175
  31. package/dist/commands/add-server.d.ts +0 -9
  32. package/dist/commands/add-server.js +0 -162
  33. package/dist/commands/alerts.d.ts +0 -27
  34. package/dist/commands/alerts.js +0 -309
  35. package/dist/commands/api-keys.d.ts +0 -20
  36. package/dist/commands/api-keys.js +0 -130
  37. package/dist/commands/attribution.d.ts +0 -22
  38. package/dist/commands/attribution.js +0 -111
  39. package/dist/commands/audiences.d.ts +0 -23
  40. package/dist/commands/audiences.js +0 -243
  41. package/dist/commands/audit.d.ts +0 -20
  42. package/dist/commands/audit.js +0 -130
  43. package/dist/commands/auth.js +0 -249
  44. package/dist/commands/chat.d.ts +0 -18
  45. package/dist/commands/chat.js +0 -117
  46. package/dist/commands/config.d.ts +0 -10
  47. package/dist/commands/config.js +0 -92
  48. package/dist/commands/consent.d.ts +0 -27
  49. package/dist/commands/consent.js +0 -233
  50. package/dist/commands/conversion-paths.d.ts +0 -19
  51. package/dist/commands/conversion-paths.js +0 -55
  52. package/dist/commands/db.d.ts +0 -25
  53. package/dist/commands/db.js +0 -330
  54. package/dist/commands/destinations.d.ts +0 -20
  55. package/dist/commands/destinations.js +0 -191
  56. package/dist/commands/doctor.js +0 -360
  57. package/dist/commands/errors.d.ts +0 -27
  58. package/dist/commands/errors.js +0 -121
  59. package/dist/commands/events.d.ts +0 -33
  60. package/dist/commands/events.js +0 -349
  61. package/dist/commands/experiments.d.ts +0 -22
  62. package/dist/commands/experiments.js +0 -264
  63. package/dist/commands/funnels.d.ts +0 -17
  64. package/dist/commands/funnels.js +0 -203
  65. package/dist/commands/goals.d.ts +0 -18
  66. package/dist/commands/goals.js +0 -214
  67. package/dist/commands/heatmap.d.ts +0 -27
  68. package/dist/commands/heatmap.js +0 -112
  69. package/dist/commands/identity.d.ts +0 -29
  70. package/dist/commands/identity.js +0 -328
  71. package/dist/commands/init.js +0 -215
  72. package/dist/commands/insights.d.ts +0 -10
  73. package/dist/commands/insights.js +0 -65
  74. package/dist/commands/install.d.ts +0 -259
  75. package/dist/commands/install.js +0 -1590
  76. package/dist/commands/login.d.ts +0 -20
  77. package/dist/commands/login.js +0 -170
  78. package/dist/commands/logout.d.ts +0 -10
  79. package/dist/commands/logout.js +0 -41
  80. package/dist/commands/playground.d.ts +0 -11
  81. package/dist/commands/playground.js +0 -47
  82. package/dist/commands/releases.d.ts +0 -17
  83. package/dist/commands/releases.js +0 -54
  84. package/dist/commands/replay.d.ts +0 -18
  85. package/dist/commands/replay.js +0 -64
  86. package/dist/commands/secrets.d.ts +0 -19
  87. package/dist/commands/secrets.js +0 -145
  88. package/dist/commands/sites.d.ts +0 -18
  89. package/dist/commands/sites.js +0 -139
  90. package/dist/commands/skad.d.ts +0 -18
  91. package/dist/commands/skad.js +0 -53
  92. package/dist/commands/sourcemap.d.ts +0 -33
  93. package/dist/commands/sourcemap.js +0 -204
  94. package/dist/commands/status.d.ts +0 -7
  95. package/dist/commands/status.js +0 -136
  96. package/dist/commands/upgrade.d.ts +0 -21
  97. package/dist/commands/upgrade.js +0 -183
  98. package/dist/commands/warehouse.d.ts +0 -20
  99. package/dist/commands/warehouse.js +0 -65
  100. package/dist/commands/warehouses.d.ts +0 -17
  101. package/dist/commands/warehouses.js +0 -182
  102. package/dist/commands/watch.d.ts +0 -45
  103. package/dist/commands/watch.js +0 -258
  104. package/dist/commands/whoami.d.ts +0 -9
  105. package/dist/commands/whoami.js +0 -50
  106. package/dist/config.d.ts +0 -75
  107. package/dist/config.js +0 -329
  108. package/dist/frameworks/detect.d.ts +0 -8
  109. package/dist/frameworks/detect.js +0 -444
  110. package/dist/install-intent-proposal.d.ts +0 -99
  111. package/dist/install-intent-proposal.js +0 -202
  112. package/dist/utils/api.d.ts +0 -20
  113. package/dist/utils/api.js +0 -47
  114. package/dist/utils/config.d.ts +0 -13
  115. package/dist/utils/config.js +0 -30
  116. package/dist/utils/confirm.d.ts +0 -17
  117. package/dist/utils/confirm.js +0 -40
  118. package/dist/utils/dry-run.d.ts +0 -20
  119. package/dist/utils/dry-run.js +0 -67
  120. package/dist/utils/from-file.d.ts +0 -9
  121. package/dist/utils/from-file.js +0 -72
  122. package/dist/utils/redact.d.ts +0 -14
  123. package/dist/utils/redact.js +0 -48
  124. package/dist/utils/ui.d.ts +0 -14
  125. package/dist/utils/ui.js +0 -59
  126. package/scripts/.gitkeep +0 -0
  127. package/scripts/README-gurulu-agentic-install.md +0 -114
  128. package/scripts/README-gurulu-scan.md +0 -98
  129. package/scripts/audit-cli-scopes.mjs +0 -204
  130. package/scripts/backfill-tenant-id.mjs +0 -172
  131. package/scripts/backfill-tenant-links.ts +0 -252
  132. package/scripts/backup-clickhouse.sh +0 -27
  133. package/scripts/backup-postgres.sh +0 -19
  134. package/scripts/bootstrap-runtime-schema.mjs +0 -87
  135. package/scripts/bootstrap-stripe.mjs +0 -158
  136. package/scripts/gurulu-agentic-install.lib.cjs +0 -762
  137. package/scripts/gurulu-agentic-install.mjs +0 -623
  138. package/scripts/gurulu-scan.lib.cjs +0 -1509
  139. package/scripts/gurulu-scan.mjs +0 -91
  140. package/scripts/gurulu-verify-install.lib.cjs +0 -334
  141. package/scripts/gurulu-verify-install.mjs +0 -59
  142. package/scripts/init-ssl.sh +0 -26
  143. package/scripts/migrate-flow-graph-enums.sh +0 -86
  144. package/scripts/monitor-disk.sh +0 -24
  145. package/scripts/patches/astro.patch.cjs +0 -74
  146. package/scripts/patches/auto-instrument/ast-helper.cjs +0 -480
  147. package/scripts/patches/auto-instrument/astro.cjs +0 -273
  148. package/scripts/patches/auto-instrument/express.cjs +0 -383
  149. package/scripts/patches/auto-instrument/fastify.cjs +0 -262
  150. package/scripts/patches/auto-instrument/hono.cjs +0 -392
  151. package/scripts/patches/auto-instrument/index.cjs +0 -80
  152. package/scripts/patches/auto-instrument/nestjs.cjs +0 -286
  153. package/scripts/patches/auto-instrument/nextjs-app-router.cjs +0 -345
  154. package/scripts/patches/auto-instrument/nextjs-pages.cjs +0 -361
  155. package/scripts/patches/auto-instrument/remix.cjs +0 -168
  156. package/scripts/patches/auto-instrument/sdk-helper-map.cjs +0 -241
  157. package/scripts/patches/auto-instrument/singleton-helper.cjs +0 -193
  158. package/scripts/patches/auto-instrument/sveltekit.cjs +0 -161
  159. package/scripts/patches/auto-instrument/vite-react.cjs +0 -37
  160. package/scripts/patches/auto-instrument/vue.cjs +0 -196
  161. package/scripts/patches/express.patch.cjs +0 -99
  162. package/scripts/patches/fastify.patch.cjs +0 -108
  163. package/scripts/patches/index.cjs +0 -300
  164. package/scripts/patches/nestjs.patch.cjs +0 -112
  165. package/scripts/patches/nextjs-app-router.patch.cjs +0 -97
  166. package/scripts/patches/nextjs-pages.patch.cjs +0 -97
  167. package/scripts/patches/remix.patch.cjs +0 -75
  168. package/scripts/patches/sveltekit.patch.cjs +0 -72
  169. package/scripts/patches/vite-react.patch.cjs +0 -73
  170. package/scripts/patches/vue.patch.cjs +0 -82
  171. package/scripts/renew-ssl.sh +0 -14
  172. package/scripts/resolve-migration.sh +0 -23
  173. package/scripts/seed-cli-dev-keys.mjs +0 -130
  174. package/scripts/seed-test-data.mjs +0 -391
  175. package/scripts/spike-browserless.ts +0 -65
  176. package/scripts/tenant-pivot-consistency-check.mjs +0 -205
  177. package/scripts/tenant-pivot-phase-3-cleanup.lib.cjs +0 -258
  178. package/scripts/tenant-pivot-phase-3-cleanup.mjs +0 -98
  179. package/scripts/test-identity-resolution.ts +0 -804
  180. package/scripts/validate-gurulu-schemas.mjs +0 -79
@@ -1,168 +0,0 @@
1
- // scripts/patches/auto-instrument/remix.cjs — Phase 20 W1 A3.
2
- //
3
- // Auto-instruments Remix route modules. Remix routes export `loader` and
4
- // `action` functions from files under `app/routes/**`. We map a Proposed
5
- // Event with `source.route = 'POST /cart/add'` onto `app/routes/cart.add.tsx`
6
- // (Remix flat routes) or `app/routes/cart/add.tsx`, then inject a
7
- // `gurulu.track(...)` call into the `action` (writes) or `loader` (reads).
8
-
9
- const fs = require('fs');
10
- const path = require('path');
11
-
12
- const ast = require('./ast-helper.cjs');
13
- const singleton = require('./singleton-helper.cjs');
14
-
15
- const NAME = 'auto-instrument-remix';
16
- const SUPPORTED = ['remix'];
17
-
18
- function parseEventRoute(routeStr) {
19
- if (!routeStr || typeof routeStr !== 'string') return null;
20
- const m = routeStr.trim().match(/^([A-Z]+)\s+(\/.*)$/);
21
- if (!m) return null;
22
- return { method: m[1].toUpperCase(), urlPath: m[2].replace(/\/+$/, '') || '/' };
23
- }
24
-
25
- function routeToCandidates(urlPath) {
26
- const cleaned = urlPath.replace(/^\//, '').replace(/\/+$/, '');
27
- const segments = cleaned.split('/').filter(Boolean);
28
- if (segments.length === 0) segments.push('_index');
29
- const exts = ['ts', 'tsx', 'js', 'jsx'];
30
- const out = [];
31
- // Nested: app/routes/cart/add.tsx
32
- for (const ext of exts) {
33
- out.push(path.posix.join('app', 'routes', ...segments) + `.${ext}`);
34
- out.push(path.posix.join('app', 'routes', ...segments, `index.${ext}`));
35
- }
36
- // Flat routes: app/routes/cart.add.tsx
37
- for (const ext of exts) {
38
- out.push(path.posix.join('app', 'routes', segments.join('.')) + `.${ext}`);
39
- }
40
- return out;
41
- }
42
-
43
- function astInstrumentFile(source, method, events, opts = {}) {
44
- const tree = ast.parseSource(source);
45
- // Reads → `loader`, writes → `action`. Per Remix convention.
46
- const exportName = method === 'GET' || method === 'HEAD' ? 'loader' : 'action';
47
- const fns = ast.findExportedFunction(tree, exportName);
48
- if (fns.length === 0) return { ok: false, reason: `${exportName}-not-found` };
49
- const target = fns[0];
50
- if (ast.hasInstrumentedMarker(target.fn)) {
51
- return {
52
- ok: true,
53
- after: source,
54
- instrumented: [],
55
- skipped: events.map((e) => ({ event: e.name, reason: 'already-instrumented' })),
56
- changed: false,
57
- };
58
- }
59
- const stmts = events.map((e) => ast.buildTrackStatement(e.name, e.autoProperties));
60
- ast.injectTrackBeforeLastReturn(target.fn, target.body, stmts);
61
- // Sprint D / D4 — alias-aware import.
62
- const specifier = ast.resolveGuruluImportSpecifier(opts.repoRoot, opts.relPath);
63
- ast.ensureGuruluImport(tree, specifier);
64
- const after = ast.generateSource(tree, source);
65
- return {
66
- ok: true,
67
- after,
68
- instrumented: events.map((e) => e.name),
69
- skipped: [],
70
- changed: true,
71
- };
72
- }
73
-
74
- function instrumentEvents(ctx, events) {
75
- const helper = singleton.ensureSingletonHelper(ctx, 'remix');
76
- const changes = [...helper.changes];
77
- const notes = [...helper.notes];
78
- let eventsInstrumented = 0;
79
- let eventsSkipped = 0;
80
-
81
- if (helper.collision) {
82
- return {
83
- changes: [],
84
- notes,
85
- filesModified: 0,
86
- eventsInstrumented: 0,
87
- eventsSkipped: events ? events.length : 0,
88
- collision: true,
89
- };
90
- }
91
-
92
- const groups = new Map();
93
- for (const e of events || []) {
94
- const parsed = parseEventRoute(e && e.source && e.source.route);
95
- if (!parsed) {
96
- notes.push(`skip:${e && e.name}:no-source-route`);
97
- eventsSkipped++;
98
- continue;
99
- }
100
- const candidates = routeToCandidates(parsed.urlPath);
101
- const found = candidates.find((rel) => fs.existsSync(path.join(ctx.repoRoot, rel)));
102
- if (!found) {
103
- notes.push(`skip:${e.name}:route-file-not-found`);
104
- eventsSkipped++;
105
- continue;
106
- }
107
- const key = `${found}::${parsed.method}`;
108
- if (!groups.has(key)) groups.set(key, { relPath: found, method: parsed.method, events: [] });
109
- groups.get(key).events.push(e);
110
- }
111
-
112
- for (const group of groups.values()) {
113
- const abs = path.join(ctx.repoRoot, group.relPath);
114
- const before = fs.readFileSync(abs, 'utf8');
115
- // Sprint D / D4 — pass repoRoot + relPath to the import resolver.
116
- const fileOpts = { repoRoot: (ctx && ctx.repoRoot) || null, relPath: group.relPath };
117
- let res;
118
- try {
119
- res = astInstrumentFile(before, group.method, group.events, fileOpts);
120
- } catch (err) {
121
- const msg = (err && err.message) || String(err);
122
- // eslint-disable-next-line no-console
123
- console.warn(`[auto-instrument] patch.fallback ${group.relPath}: ${msg}`);
124
- notes.push(`patch.fallback:${group.relPath}:${msg}`);
125
- continue;
126
- }
127
- if (!res.ok) {
128
- for (const e of group.events) {
129
- notes.push(`skip:${e.name}:${res.reason}`);
130
- eventsSkipped++;
131
- }
132
- continue;
133
- }
134
- for (const s of res.skipped || []) {
135
- notes.push(`skip:${s.event}:${s.reason}`);
136
- eventsSkipped++;
137
- }
138
- if (res.changed) {
139
- changes.push({
140
- relPath: group.relPath,
141
- before,
142
- after: res.after,
143
- reason: `auto-instrument-remix`,
144
- type: 'auto-instrument',
145
- });
146
- eventsInstrumented += (res.instrumented || []).length;
147
- }
148
- }
149
-
150
- const filesModified = changes.filter((c) => c.type === 'auto-instrument').length;
151
- return { changes, notes, filesModified, eventsInstrumented, eventsSkipped, collision: false };
152
- }
153
-
154
- function ensureSingletonHelper(ctx) {
155
- return singleton.ensureSingletonHelper(ctx, 'remix');
156
- }
157
-
158
- module.exports = {
159
- name: NAME,
160
- supportedFrameworks: SUPPORTED,
161
- ensureSingletonHelper,
162
- instrumentEvents,
163
- _internals: {
164
- parseEventRoute,
165
- routeToCandidates,
166
- astInstrumentFile,
167
- },
168
- };
@@ -1,241 +0,0 @@
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
- };
@@ -1,193 +0,0 @@
1
- // scripts/patches/auto-instrument/singleton-helper.cjs — Phase 18.7 B5.
2
- //
3
- // Shared utility for the per-framework auto-instrument modules. Responsible
4
- // for:
5
- //
6
- // 1. Creating a `src/lib/gurulu.ts` singleton that constructs the
7
- // `@gurulu/node` Gurulu client from env vars.
8
- // 2. Adding `@gurulu/node` to the target repo's `package.json` dependencies
9
- // if missing.
10
- // 3. Appending `GURULU_SITE_ID` / `GURULU_SECRET_KEY` / `GURULU_INGEST_URL`
11
- // env vars to `.env.local` (Next.js) or `.env` (Express/other).
12
- //
13
- // None of these helpers shell out — they produce in-memory `change` records
14
- // that the caller can thread through the existing `applyPlan()` backup +
15
- // patch-log infrastructure. That way auto-instrument patches participate in
16
- // the same `--rollback` flow as the script-tag patches.
17
- //
18
- // Pure Node, zero deps. Idempotency is achieved via the
19
- // `// @gurulu-instrumented` marker + JSON dep deduplication.
20
-
21
- const fs = require('fs');
22
- const path = require('path');
23
-
24
- const HELPER_MARKER = '// @gurulu-instrumented';
25
- const HELPER_REL_PATH = 'src/lib/gurulu.ts';
26
- const NODE_DEP = '@gurulu/node';
27
- const NODE_DEP_VERSION = '^0.1.0';
28
-
29
- function buildHelperContent() {
30
- return (
31
- `${HELPER_MARKER}\n` +
32
- `// Auto-generated by Gurulu agentic install (phase 18.7).\n` +
33
- `// Edit to customize the singleton, but keep the @gurulu-instrumented\n` +
34
- `// marker so \`gurulu install --rollback\` can find this file.\n` +
35
- `import { Gurulu } from '@gurulu/node';\n\n` +
36
- `export const gurulu = new Gurulu({\n` +
37
- ` siteId: process.env.GURULU_SITE_ID ?? '',\n` +
38
- ` apiKey: process.env.GURULU_SECRET_KEY ?? '',\n` +
39
- ` endpoint: process.env.GURULU_INGEST_URL ?? 'https://gurulu.io',\n` +
40
- `});\n`
41
- );
42
- }
43
-
44
- /**
45
- * Plan a singleton helper file change. Returns a `change` record compatible
46
- * with `patches.applyPlan()` or `null` if the helper already exists with our
47
- * marker (idempotent). Throws when the file exists but does not carry the
48
- * marker — that indicates a collision with user code and refuses to
49
- * overwrite.
50
- */
51
- function planSingletonHelper(ctx) {
52
- const repoRoot = ctx.repoRoot;
53
- const abs = path.join(repoRoot, HELPER_REL_PATH);
54
- if (fs.existsSync(abs)) {
55
- const existing = fs.readFileSync(abs, 'utf8');
56
- if (existing.includes(HELPER_MARKER)) {
57
- return { change: null, reason: 'helper-exists' };
58
- }
59
- const err = new Error(
60
- `auto-instrument: refusing to overwrite existing ${HELPER_REL_PATH} ` +
61
- `(no @gurulu-instrumented marker). Delete or rename the file to proceed.`,
62
- );
63
- err.code = 'GURULU_HELPER_COLLISION';
64
- throw err;
65
- }
66
- return {
67
- change: {
68
- relPath: HELPER_REL_PATH,
69
- before: '',
70
- after: buildHelperContent(),
71
- reason: 'create-singleton-helper',
72
- },
73
- reason: 'helper-created',
74
- };
75
- }
76
-
77
- /**
78
- * Plan the `package.json` edit that adds `@gurulu/node` to dependencies if
79
- * missing. Returns a change record or null when already present.
80
- */
81
- function planPackageJsonDependency(ctx) {
82
- const abs = path.join(ctx.repoRoot, 'package.json');
83
- if (!fs.existsSync(abs)) {
84
- return { change: null, reason: 'package-json-missing' };
85
- }
86
- const before = fs.readFileSync(abs, 'utf8');
87
- let pkg;
88
- try {
89
- pkg = JSON.parse(before);
90
- } catch {
91
- return { change: null, reason: 'package-json-invalid' };
92
- }
93
- const deps = pkg.dependencies || {};
94
- if (deps[NODE_DEP]) {
95
- return { change: null, reason: 'node-dep-present' };
96
- }
97
- pkg.dependencies = { ...deps, [NODE_DEP]: NODE_DEP_VERSION };
98
- // Preserve the trailing newline convention.
99
- const trailing = before.endsWith('\n') ? '\n' : '';
100
- const after = JSON.stringify(pkg, null, 2) + trailing;
101
- return {
102
- change: {
103
- relPath: 'package.json',
104
- before,
105
- after,
106
- reason: 'add-gurulu-node-dep',
107
- },
108
- reason: 'node-dep-added',
109
- };
110
- }
111
-
112
- /**
113
- * Plan the `.env.local` / `.env` edit that appends the GURULU_* keys. Never
114
- * overwrites existing values. Returns a change record or null when all keys
115
- * are already present.
116
- */
117
- function planEnvFile(ctx, framework) {
118
- const isNext = !!(framework && /^nextjs/.test(framework));
119
- const filename = isNext ? '.env.local' : '.env';
120
- const abs = path.join(ctx.repoRoot, filename);
121
- const before = fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : '';
122
- const presentKeys = new Set(
123
- before
124
- .split('\n')
125
- .map((l) => l.trim())
126
- .filter((l) => l && !l.startsWith('#'))
127
- .map((l) => l.split('=')[0].trim()),
128
- );
129
- const want = {
130
- GURULU_SITE_ID: '',
131
- GURULU_SECRET_KEY: '',
132
- GURULU_INGEST_URL: 'https://gurulu.io',
133
- };
134
- const missing = Object.entries(want).filter(([k]) => !presentKeys.has(k));
135
- if (missing.length === 0) {
136
- return { change: null, reason: 'env-already-present' };
137
- }
138
- const separator = before && !before.endsWith('\n') ? '\n' : '';
139
- const header = before ? '' : '# Gurulu agentic install (phase 18.7)\n';
140
- const newLines = missing.map(([k, v]) => `${k}=${v}`).join('\n');
141
- const after = before + separator + header + newLines + '\n';
142
- return {
143
- change: {
144
- relPath: filename,
145
- before,
146
- after,
147
- reason: 'append-gurulu-env',
148
- },
149
- reason: 'env-added',
150
- addedKeys: missing.map(([k]) => k),
151
- };
152
- }
153
-
154
- /**
155
- * Convenience: plan all three prerequisite changes at once. Returns
156
- * `{ changes: [...], notes: [...] }` following the same shape the
157
- * per-framework instrument modules return, so it can be merged directly by
158
- * callers.
159
- */
160
- function ensureSingletonHelper(ctx, framework) {
161
- const changes = [];
162
- const notes = [];
163
- try {
164
- const helper = planSingletonHelper(ctx);
165
- if (helper.change) changes.push(helper.change);
166
- else notes.push(`singleton:${helper.reason}`);
167
- } catch (err) {
168
- if (err.code === 'GURULU_HELPER_COLLISION') {
169
- notes.push(`singleton-collision:${err.message}`);
170
- return { changes: [], notes, collision: true };
171
- }
172
- throw err;
173
- }
174
- const dep = planPackageJsonDependency(ctx);
175
- if (dep.change) changes.push(dep.change);
176
- else notes.push(`package-json:${dep.reason}`);
177
- const env = planEnvFile(ctx, framework);
178
- if (env.change) changes.push(env.change);
179
- else notes.push(`env:${env.reason}`);
180
- return { changes, notes, collision: false };
181
- }
182
-
183
- module.exports = {
184
- HELPER_MARKER,
185
- HELPER_REL_PATH,
186
- NODE_DEP,
187
- NODE_DEP_VERSION,
188
- buildHelperContent,
189
- planSingletonHelper,
190
- planPackageJsonDependency,
191
- planEnvFile,
192
- ensureSingletonHelper,
193
- };