@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,762 +0,0 @@
1
- // gurulu-agentic-install.lib.cjs — Phase 14 B3 agentic install alpha.
2
- //
3
- // Takes a scanner output document (from scripts/gurulu-scan.mjs / .lib.cjs)
4
- // and produces the 10 `.gurulu/` artifacts that the runtime loader (Phase 13
5
- // B1) ingests. Every artifact is validated against schemas/gurulu/*.schema.json
6
- // before being written. No source code edits. No SDK injection. Config only.
7
- //
8
- // Exposed as CommonJS so ts-jest can require() it directly and the ESM CLI
9
- // wrapper can import it via createRequire.
10
-
11
- 'use strict';
12
-
13
- const INSTALL_AGENT_VERSION = '0.1.0';
14
- const DEFAULT_INGEST_ENDPOINT = 'https://ingest.gurulu.io/v1/events';
15
- const DEFAULT_SDK_VERSION = '0.1.0';
16
-
17
- // ---------------------------------------------------------------------------
18
- // Helpers
19
- // ---------------------------------------------------------------------------
20
-
21
- /** Map framework name from scanner to install-plan framework label. */
22
- function mapFrameworkName(name) {
23
- if (!name || name === 'unknown') return 'unknown';
24
- if (name === 'nextjs') return 'next';
25
- return name;
26
- }
27
-
28
- /** Map ORM name to dialect list (best-effort). */
29
- function ormDialects(ormName) {
30
- switch (ormName) {
31
- case 'prisma':
32
- case 'drizzle':
33
- case 'typeorm':
34
- case 'sequelize':
35
- case 'kysely':
36
- return ['postgresql'];
37
- case 'mongoose':
38
- return ['mongodb'];
39
- default:
40
- return [];
41
- }
42
- }
43
-
44
- /** Map auth name to install-plan auth strategy. */
45
- function authStrategy(authName) {
46
- switch (authName) {
47
- case 'nextauth':
48
- case 'lucia':
49
- case 'passport':
50
- return 'session';
51
- case 'clerk':
52
- case 'supabase':
53
- case 'firebase':
54
- return 'oauth';
55
- case 'custom-jwt':
56
- return 'jwt';
57
- default:
58
- return 'custom';
59
- }
60
- }
61
-
62
- /** Map op verb to past-tense event name fragment. */
63
- function opVerb(op) {
64
- if (!op) return 'changed';
65
- const lower = String(op).toLowerCase();
66
- if (lower.startsWith('create') || lower === 'insert' || lower === 'insertmany') return 'created';
67
- if (
68
- lower.startsWith('update') ||
69
- lower.startsWith('upsert') ||
70
- lower === 'findoneandupdate'
71
- )
72
- return 'updated';
73
- if (lower.startsWith('delete') || lower.startsWith('remove') || lower === 'findoneanddelete')
74
- return 'deleted';
75
- return lower;
76
- }
77
-
78
- /** Infer canonical event name from model + operation. */
79
- function inferEventName(model, op) {
80
- const safeModel = String(model || 'entity')
81
- .replace(/[^A-Za-z0-9_]/g, '')
82
- .toLowerCase();
83
- return `${safeModel || 'entity'}_${opVerb(op)}`;
84
- }
85
-
86
- /** Normalise CDC op name to schema enum (insert|update|delete). */
87
- function cdcOp(op) {
88
- const verb = opVerb(op);
89
- if (verb === 'created') return 'insert';
90
- if (verb === 'updated') return 'update';
91
- if (verb === 'deleted') return 'delete';
92
- return null;
93
- }
94
-
95
- // ---------------------------------------------------------------------------
96
- // Business surface derivation
97
- // ---------------------------------------------------------------------------
98
-
99
- const SURFACE_KEYWORDS = [
100
- { kind: 'signup', patterns: ['signup', 'register', 'sign-up', 'join', 'onboard'] },
101
- { kind: 'login', patterns: ['login', 'signin', 'sign-in', 'auth/callback'] },
102
- { kind: 'checkout', patterns: ['checkout', 'payment', 'cart', 'billing', 'order'] },
103
- { kind: 'subscription', patterns: ['subscribe', 'subscription', 'plan', 'pricing'] },
104
- { kind: 'lead', patterns: ['lead', 'contact', 'demo', 'newsletter'] },
105
- { kind: 'onboarding', patterns: ['welcome', 'onboarding', 'getting-started'] },
106
- ];
107
-
108
- const MODEL_SURFACE = new Map([
109
- ['user', 'signup'],
110
- ['users', 'signup'],
111
- ['account', 'signup'],
112
- ['accounts', 'signup'],
113
- ['profile', 'signup'],
114
- ['order', 'checkout'],
115
- ['orders', 'checkout'],
116
- ['payment', 'checkout'],
117
- ['payments', 'checkout'],
118
- ['cart', 'checkout'],
119
- ['invoice', 'checkout'],
120
- ['subscription', 'subscription'],
121
- ['subscriptions', 'subscription'],
122
- ['plan', 'subscription'],
123
- ['lead', 'lead'],
124
- ['leads', 'lead'],
125
- ['contact', 'lead'],
126
- ['contacts', 'lead'],
127
- ]);
128
-
129
- /** Scan routes + mutations to produce install-plan surfaces (with evidence). */
130
- function deriveBusinessSurfaces(scan) {
131
- const surfaces = new Map();
132
- const addEvidence = (kind, entry, evidence) => {
133
- if (!surfaces.has(kind)) {
134
- surfaces.set(kind, { kind, entry, confidence: 0.5, evidence: [] });
135
- }
136
- const s = surfaces.get(kind);
137
- if (!s.entry || s.entry === '/') s.entry = entry || s.entry;
138
- if (evidence && !s.evidence.includes(evidence)) s.evidence.push(evidence);
139
- s.confidence = Math.min(0.95, s.confidence + 0.1);
140
- };
141
-
142
- for (const route of scan.routes || []) {
143
- const p = (route.path || '').toLowerCase();
144
- for (const { kind, patterns } of SURFACE_KEYWORDS) {
145
- if (patterns.some((pat) => p.includes(pat))) {
146
- const method = (route.methods || []).includes('POST') ? 'POST' : (route.methods || ['*'])[0];
147
- addEvidence(kind, route.path, `${method} ${route.path}`);
148
- break;
149
- }
150
- }
151
- }
152
-
153
- for (const m of scan.mutations || []) {
154
- const key = String(m.model || '').toLowerCase();
155
- const kind = MODEL_SURFACE.get(key);
156
- if (kind) {
157
- addEvidence(
158
- kind,
159
- null,
160
- `${m.file}:${m.line} ${m.model}.${m.operation}`,
161
- );
162
- }
163
- }
164
-
165
- return Array.from(surfaces.values()).map((s) => ({
166
- ...s,
167
- entry: s.entry || '/',
168
- confidence: Number(s.confidence.toFixed(2)),
169
- }));
170
- }
171
-
172
- /** Build a suggested_milestones array from the derived surfaces. */
173
- function deriveMilestones(surfaces) {
174
- const out = [];
175
- for (const s of surfaces) {
176
- const type = ['signup', 'checkout', 'lead', 'onboarding'].includes(s.kind) ? s.kind : null;
177
- if (!type) continue;
178
- out.push({
179
- id: `ms_${type}`,
180
- type,
181
- description: `Auto-detected ${type} milestone`,
182
- });
183
- }
184
- // Always at least one milestone so downstream tooling has a seed.
185
- if (out.length === 0) {
186
- out.push({ id: 'ms_activation', type: 'activation', description: 'Default activation milestone' });
187
- }
188
- return out;
189
- }
190
-
191
- // ---------------------------------------------------------------------------
192
- // Artifact generators
193
- // ---------------------------------------------------------------------------
194
-
195
- /** install-plan.json — top-level discovery summary. */
196
- function generateInstallPlan(scan, opts) {
197
- const framework = scan.framework || { name: 'unknown' };
198
- const orm = scan.orm || { name: 'unknown' };
199
- const auth = scan.auth || { name: 'unknown' };
200
-
201
- const domains = Array.isArray(opts && opts.domains) && opts.domains.length > 0
202
- ? opts.domains.slice()
203
- : ['localhost'];
204
-
205
- const stack = {
206
- framework: {
207
- name: mapFrameworkName(framework.name),
208
- ...(framework.version ? { version: String(framework.version) } : {}),
209
- confidence: 0.9,
210
- },
211
- runtime: 'node:20',
212
- };
213
- if (orm.name && orm.name !== 'unknown') {
214
- stack.orm = { name: orm.name, dialects: ormDialects(orm.name) };
215
- }
216
- if (auth.name && auth.name !== 'unknown') {
217
- stack.auth = { provider: auth.name, strategy: authStrategy(auth.name) };
218
- }
219
-
220
- const surfaces = deriveBusinessSurfaces(scan);
221
- const suggested_milestones = deriveMilestones(surfaces);
222
-
223
- return {
224
- site_id: opts.siteId,
225
- generated_at: new Date().toISOString(),
226
- agent_version: INSTALL_AGENT_VERSION,
227
- domains,
228
- install_mode: 'observe',
229
- stack,
230
- surfaces,
231
- suggested_milestones,
232
- };
233
- }
234
-
235
- /** core-config.json — shared SDK runtime config. */
236
- function generateCoreConfig(scan, opts) {
237
- return {
238
- sdk_version: DEFAULT_SDK_VERSION,
239
- config_version: 1,
240
- ingest: {
241
- endpoint: DEFAULT_INGEST_ENDPOINT,
242
- region: 'eu',
243
- batch_size: 50,
244
- flush_interval_ms: 2000,
245
- },
246
- project: { id: opts.siteId },
247
- tenant: { id: opts.tenantId, mode: 'single' },
248
- identity: {
249
- anonymous_id_cookie: '_gurulu_aid',
250
- user_id_field: 'user.id',
251
- correlation_field: 'correlation_id',
252
- },
253
- consent_defaults: {
254
- analytics: true,
255
- marketing: false,
256
- strict_mode: true,
257
- },
258
- feature_flags: {},
259
- };
260
- }
261
-
262
- /** web.config.json — browser SDK config + route→flow heuristic. */
263
- function generateWebConfig(scan /*, opts*/) {
264
- const routes = [];
265
- const seen = new Set();
266
- for (const route of scan.routes || []) {
267
- const p = (route.path || '').toLowerCase();
268
- let flow = null;
269
- let milestone = null;
270
- for (const { kind, patterns } of SURFACE_KEYWORDS) {
271
- if (patterns.some((pat) => p.includes(pat))) {
272
- flow = `flow_${kind}`;
273
- if (['signup', 'checkout', 'lead', 'onboarding'].includes(kind)) {
274
- milestone = `ms_${kind}`;
275
- }
276
- break;
277
- }
278
- }
279
- if (!flow) continue;
280
- const entry = { pattern: route.path, flow };
281
- if (milestone) entry.milestone = milestone;
282
- const key = `${entry.pattern}::${entry.flow}`;
283
- if (seen.has(key)) continue;
284
- seen.add(key);
285
- routes.push(entry);
286
- }
287
- if (routes.length === 0) {
288
- routes.push({ pattern: '/', flow: 'flow_default' });
289
- }
290
-
291
- return {
292
- auto_track: {
293
- page_views: true,
294
- clicks: true,
295
- form_submits: true,
296
- web_vitals: true,
297
- errors: true,
298
- },
299
- routes,
300
- selectors: [],
301
- drift: {
302
- capture_scroll: true,
303
- capture_viewport: true,
304
- capture_referrer: true,
305
- capture_user_agent: true,
306
- },
307
- no_capture: ['input[type=password]', '[data-sensitive]'],
308
- inspector: { enabled: true, endpoint: 'https://inspector.gurulu.io' },
309
- playground: { enabled: false, endpoint: 'https://playground.gurulu.io' },
310
- };
311
- }
312
-
313
- /** app.config.json — mobile SDK skeleton (alpha doesn't auto-detect mobile). */
314
- function generateAppConfig(/* scan, opts */) {
315
- return {
316
- platform: 'ios',
317
- auto_screen_tracking: {
318
- enabled: true,
319
- screen_name_source: 'view_controller',
320
- ignore_patterns: [],
321
- },
322
- lifecycle: {
323
- track_install: true,
324
- track_update: true,
325
- track_foreground: true,
326
- track_background: false,
327
- },
328
- deep_links: [],
329
- push: { provider: 'none', track_opens: false },
330
- offline_queue: {
331
- max_events: 1000,
332
- max_bytes: 1048576,
333
- flush_on_network: true,
334
- },
335
- };
336
- }
337
-
338
- /** server-map.json — server endpoint → business event. */
339
- function generateServerMap(scan /*, opts*/) {
340
- const endpoints = [];
341
- for (const route of scan.routes || []) {
342
- const p = (route.path || '').toLowerCase();
343
- const methods = route.methods && route.methods.length > 0 ? route.methods : ['*'];
344
- let event = null;
345
- if (p.includes('checkout') || p.includes('order') || p.includes('payment')) {
346
- event = 'order_placed';
347
- } else if (p.includes('signup') || p.includes('register')) {
348
- event = 'user_registered';
349
- } else if (p.includes('subscribe') || p.includes('subscription')) {
350
- event = 'subscription_started';
351
- } else if (p.includes('lead') || p.includes('contact')) {
352
- event = 'lead_captured';
353
- }
354
- if (!event) continue;
355
- for (const method of methods) {
356
- if (method === '*' || method === 'GET' || method === 'HEAD' || method === 'OPTIONS') continue;
357
- endpoints.push({
358
- method,
359
- path: route.path,
360
- handler: route.file ? `${route.file}:${method}` : undefined,
361
- event,
362
- emit_on: 'success',
363
- });
364
- }
365
- }
366
- // server-map schema doesn't require minItems on endpoints, but an empty
367
- // map isn't useful — include a placeholder only when we have zero routes.
368
- return {
369
- identity: {
370
- header: 'x-gurulu-aid',
371
- cookie: '_gurulu_aid',
372
- trace_header: 'traceparent',
373
- },
374
- endpoints: endpoints.map((e) => {
375
- const out = { method: e.method, path: e.path, event: e.event, emit_on: e.emit_on };
376
- if (e.handler) out.handler = e.handler;
377
- return out;
378
- }),
379
- ignore: ['/api/health'],
380
- };
381
- }
382
-
383
- /**
384
- * Sprint E1.3b — singularize plural table/model names to canonical singular.
385
- * The scan layer normalises mutations as `{ op: '<model>.<operation>' }` so we
386
- * derive the operation from `m.op` when `m.operation` isn't present, and
387
- * collapse common irregular plurals to their singular form so e.g. raw-SQL
388
- * `INSERT INTO orders` and a Drizzle `pgTable('orders', ...)` both fold into
389
- * the same `order` row in db-map.
390
- */
391
- const SINGULARIZE_IRREGULARS = {
392
- users: 'user',
393
- orders: 'order',
394
- items: 'item',
395
- };
396
- function singularizeModelName(raw) {
397
- const lower = String(raw || '').toLowerCase();
398
- if (!lower) return lower;
399
- if (Object.prototype.hasOwnProperty.call(SINGULARIZE_IRREGULARS, lower)) {
400
- return SINGULARIZE_IRREGULARS[lower];
401
- }
402
- return lower;
403
- }
404
-
405
- /** db-map.json — table → event emitter mapping from detected mutations. */
406
- function generateDbMap(scan, opts) {
407
- const byModel = new Map();
408
- for (const m of scan.mutations || []) {
409
- const rawName = String(m.model || '').trim();
410
- if (!rawName) continue;
411
- const name = singularizeModelName(rawName);
412
- // Sprint E1.3b — `scan.mutations` from gurulu-scan.lib.cjs normalises the
413
- // operation as `m.op = "<model>.<operation>"` and drops `m.operation`.
414
- // Derive the operation verb from whichever field is populated.
415
- const operation =
416
- m.operation || (typeof m.op === 'string' ? m.op.split('.').pop() : null);
417
- const op = cdcOp(operation);
418
- if (!op) continue;
419
- if (!byModel.has(name)) byModel.set(name, new Set());
420
- const key = `${op}::${inferEventName(name, operation)}`;
421
- byModel.get(name).add(key);
422
- }
423
-
424
- const tables = [];
425
- for (const [name, opsSet] of byModel.entries()) {
426
- const emits = [];
427
- const seen = new Set();
428
- for (const entry of opsSet) {
429
- const [op, event] = entry.split('::');
430
- if (seen.has(event)) continue;
431
- seen.add(event);
432
- emits.push({ event, on: op });
433
- }
434
- if (emits.length === 0) continue;
435
- tables.push({ name, primary_key: 'id', emits });
436
- }
437
-
438
- // Schema requires tables.minItems === 1. Seed a placeholder so downstream
439
- // tooling has something to edit.
440
- if (tables.length === 0) {
441
- tables.push({
442
- name: 'users',
443
- primary_key: 'id',
444
- emits: [{ event: 'user_created', on: 'insert' }],
445
- });
446
- }
447
-
448
- return {
449
- connector: `conn_${(opts && opts.tenantId) || 'primary'}_db`,
450
- allowed_operations: ['insert', 'update', 'delete'],
451
- tables,
452
- truth_commit: { reconcile_interval_s: 300, strict: false },
453
- };
454
- }
455
-
456
- /** flow-seeds.json — pre-seeded flows from derived business surfaces. */
457
- function generateFlowSeeds(scan /*, opts*/) {
458
- const surfaces = deriveBusinessSurfaces(scan);
459
- const flows = [];
460
- for (const s of surfaces) {
461
- const flowName = `flow_${s.kind}`;
462
- const entryRef = s.entry || '/';
463
- const successEvent =
464
- s.kind === 'signup'
465
- ? 'user_registered'
466
- : s.kind === 'checkout'
467
- ? 'order_placed'
468
- : s.kind === 'subscription'
469
- ? 'subscription_started'
470
- : s.kind === 'lead'
471
- ? 'lead_captured'
472
- : `${s.kind}_complete`;
473
-
474
- flows.push({
475
- flowName,
476
- surface: 'hybrid',
477
- nodes: [
478
- { id: 'n1', kind: 'entry', ref: entryRef, next: ['n2'] },
479
- { id: 'n2', kind: 'page', ref: entryRef, next: ['n3'] },
480
- { id: 'n3', kind: 'event', ref: `${s.kind}_form_submitted`, next: ['n4'] },
481
- { id: 'n4', kind: 'server_event', ref: successEvent, next: ['n5'] },
482
- { id: 'n5', kind: 'success', ref: `${s.kind}_complete` },
483
- ],
484
- expectedOutcome: { event: successEvent, within_ms: 300000 },
485
- confidence: s.confidence,
486
- source: 'route_scan',
487
- });
488
- }
489
-
490
- // Schema requires flows.minItems === 1.
491
- if (flows.length === 0) {
492
- flows.push({
493
- flowName: 'flow_default',
494
- surface: 'web',
495
- nodes: [
496
- { id: 'n1', kind: 'entry', ref: '/', next: ['n2'] },
497
- { id: 'n2', kind: 'success', ref: 'page_viewed' },
498
- ],
499
- expectedOutcome: { event: 'page_viewed', within_ms: 60000 },
500
- confidence: 0.5,
501
- source: 'heuristic',
502
- });
503
- }
504
-
505
- return { generated_at: new Date().toISOString(), flows };
506
- }
507
-
508
- /** milestone-rules.json — milestone engine rules. */
509
- function generateMilestoneRules(scan /*, opts*/) {
510
- const surfaces = deriveBusinessSurfaces(scan);
511
- const kinds = new Set(surfaces.map((s) => s.kind));
512
- const rules = [];
513
-
514
- if (kinds.has('signup') || kinds.size === 0) {
515
- rules.push({
516
- id: 'rule_signup',
517
- milestone: 'signup',
518
- match: { event: 'signup_form_submitted' },
519
- success_signals: ['user_registered'],
520
- abandon_signals: ['page_leave'],
521
- error_signals: ['signup_error'],
522
- window: { max_duration_ms: 600000, idle_timeout_ms: 120000 },
523
- priority: 10,
524
- });
525
- }
526
- if (kinds.has('checkout')) {
527
- rules.push({
528
- id: 'rule_checkout',
529
- milestone: 'checkout',
530
- match: { event: 'checkout_started' },
531
- success_signals: ['order_placed'],
532
- abandon_signals: ['checkout_cancelled', 'page_leave'],
533
- error_signals: ['payment_failed'],
534
- window: { max_duration_ms: 900000, idle_timeout_ms: 180000 },
535
- priority: 20,
536
- });
537
- }
538
- if (kinds.has('lead')) {
539
- rules.push({
540
- id: 'rule_lead',
541
- milestone: 'lead',
542
- match: { event: 'lead_form_submitted' },
543
- success_signals: ['lead_captured'],
544
- abandon_signals: ['page_leave'],
545
- window: { max_duration_ms: 300000, idle_timeout_ms: 60000 },
546
- priority: 30,
547
- });
548
- }
549
- if (rules.length === 0) {
550
- // Guarantee minItems === 1 even when we somehow removed the signup rule.
551
- rules.push({
552
- id: 'rule_activation',
553
- milestone: 'activation',
554
- match: { event: 'page_viewed' },
555
- success_signals: ['session_active'],
556
- window: { max_duration_ms: 600000, idle_timeout_ms: 120000 },
557
- priority: 100,
558
- });
559
- }
560
- return { rules };
561
- }
562
-
563
- /** correlation-map.json — client ↔ server ↔ db event linking. */
564
- function generateCorrelationMap(scan /*, opts*/) {
565
- const surfaces = deriveBusinessSurfaces(scan);
566
- const kinds = new Set(surfaces.map((s) => s.kind));
567
- const links = [];
568
-
569
- if (kinds.has('signup') || kinds.size === 0) {
570
- links.push({
571
- from: { tier: 'client', event: 'signup_form_submitted' },
572
- to: { tier: 'server', event: 'user_registered' },
573
- via: 'correlation_id',
574
- window_ms: 60000,
575
- });
576
- }
577
- if (kinds.has('checkout')) {
578
- links.push({
579
- from: { tier: 'client', event: 'checkout_started' },
580
- to: { tier: 'server', event: 'order_placed' },
581
- via: 'correlation_id',
582
- window_ms: 60000,
583
- });
584
- links.push({
585
- from: { tier: 'server', event: 'order_placed' },
586
- to: { tier: 'db', event: 'order_created' },
587
- via: 'order_id',
588
- window_ms: 600000,
589
- });
590
- }
591
- if (links.length === 0) {
592
- // Belt-and-braces minItems guarantee.
593
- links.push({
594
- from: { tier: 'client', event: 'page_viewed' },
595
- to: { tier: 'server', event: 'page_viewed' },
596
- via: 'correlation_id',
597
- window_ms: 60000,
598
- });
599
- }
600
-
601
- return {
602
- correlation_field: 'correlation_id',
603
- ttl_ms: 300000,
604
- identity_propagation: {
605
- anonymous_to_user: true,
606
- carry_header: 'x-gurulu-aid',
607
- },
608
- links,
609
- };
610
- }
611
-
612
- /** connectors.json — external destinations placeholder (empty in alpha). */
613
- function generateConnectors(/* scan, opts */) {
614
- return { connectors: [] };
615
- }
616
-
617
- // ---------------------------------------------------------------------------
618
- // Top-level entry
619
- // ---------------------------------------------------------------------------
620
-
621
- /**
622
- * Generate all 10 artifacts from a scanner output and install options.
623
- *
624
- * @param {object} scanOutput — result of scripts/gurulu-scan.lib.cjs scanRepo()
625
- * @param {{ siteId: string, tenantId: string, outputPath?: string, domains?: string[] }} opts
626
- * @returns {{ artifacts: Record<string, object>, errors: Array<{file:string,message:string}> }}
627
- */
628
- function generateArtifacts(scanOutput, opts) {
629
- if (!opts || !opts.siteId || !opts.tenantId) {
630
- throw new Error('generateArtifacts: opts.siteId and opts.tenantId are required');
631
- }
632
- const scan = scanOutput || {};
633
- return {
634
- artifacts: {
635
- 'install-plan.json': generateInstallPlan(scan, opts),
636
- 'core-config.json': generateCoreConfig(scan, opts),
637
- 'web.config.json': generateWebConfig(scan, opts),
638
- 'app.config.json': generateAppConfig(scan, opts),
639
- 'server-map.json': generateServerMap(scan, opts),
640
- 'db-map.json': generateDbMap(scan, opts),
641
- 'flow-seeds.json': generateFlowSeeds(scan, opts),
642
- 'milestone-rules.json': generateMilestoneRules(scan, opts),
643
- 'correlation-map.json': generateCorrelationMap(scan, opts),
644
- 'connectors.json': generateConnectors(scan, opts),
645
- },
646
- errors: [],
647
- };
648
- }
649
-
650
- // ---------------------------------------------------------------------------
651
- // Validation
652
- // ---------------------------------------------------------------------------
653
-
654
- let _ajvInstance = null;
655
- function getAjv() {
656
- if (_ajvInstance) return _ajvInstance;
657
- // eslint-disable-next-line global-require
658
- const Ajv = require('ajv');
659
- _ajvInstance = new Ajv({ allErrors: true, format: 'full' });
660
- return _ajvInstance;
661
- }
662
-
663
- /**
664
- * Validate every artifact against its matching schema.
665
- *
666
- * @param {Record<string, object>} artifacts
667
- * @returns {{ ok: true } | { ok: false, errors: Array<{file:string,message:string}> }}
668
- */
669
- function validateArtifacts(artifacts) {
670
- // eslint-disable-next-line global-require
671
- const path = require('path');
672
- // eslint-disable-next-line global-require
673
- const fs = require('fs');
674
- const ajv = getAjv();
675
-
676
- const schemaDir = path.join(__dirname, '..', 'schemas', 'gurulu');
677
- const errors = [];
678
-
679
- for (const [filename, artifact] of Object.entries(artifacts)) {
680
- const schemaName = filename.replace(/\.json$/, '.schema.json');
681
- const schemaPath = path.join(schemaDir, schemaName);
682
- if (!fs.existsSync(schemaPath)) {
683
- errors.push({ file: filename, message: `schema not found: ${schemaName}` });
684
- continue;
685
- }
686
- let schema;
687
- try {
688
- schema = JSON.parse(fs.readFileSync(schemaPath, 'utf8'));
689
- } catch (err) {
690
- errors.push({ file: filename, message: `schema parse error: ${err.message}` });
691
- continue;
692
- }
693
- let validate;
694
- try {
695
- // Compile fresh each call to avoid ajv caching conflicts across runs.
696
- const freshAjv = new (require('ajv'))({ allErrors: true, format: 'full' });
697
- validate = freshAjv.compile(schema);
698
- } catch (err) {
699
- errors.push({ file: filename, message: `schema compile error: ${err.message}` });
700
- continue;
701
- }
702
- const valid = validate(artifact);
703
- if (!valid) {
704
- for (const e of validate.errors || []) {
705
- errors.push({
706
- file: filename,
707
- message: `${e.dataPath || '(root)'} ${e.message}`,
708
- });
709
- }
710
- }
711
- }
712
-
713
- return errors.length === 0 ? { ok: true } : { ok: false, errors };
714
- }
715
-
716
- // ---------------------------------------------------------------------------
717
- // Atomic writer
718
- // ---------------------------------------------------------------------------
719
-
720
- /**
721
- * Write artifacts to disk. Ensures the output directory exists and writes
722
- * each file with a trailing newline. Designed to be re-runnable.
723
- *
724
- * @param {Record<string, object>} artifacts
725
- * @param {string} outputPath
726
- */
727
- async function writeArtifacts(artifacts, outputPath) {
728
- // eslint-disable-next-line global-require
729
- const fs = require('fs/promises');
730
- // eslint-disable-next-line global-require
731
- const path = require('path');
732
- await fs.mkdir(outputPath, { recursive: true });
733
- for (const [filename, artifact] of Object.entries(artifacts)) {
734
- const filePath = path.join(outputPath, filename);
735
- await fs.writeFile(filePath, JSON.stringify(artifact, null, 2) + '\n', 'utf8');
736
- }
737
- }
738
-
739
- module.exports = {
740
- INSTALL_AGENT_VERSION,
741
- DEFAULT_INGEST_ENDPOINT,
742
- DEFAULT_SDK_VERSION,
743
- generateArtifacts,
744
- generateInstallPlan,
745
- generateCoreConfig,
746
- generateWebConfig,
747
- generateAppConfig,
748
- generateServerMap,
749
- generateDbMap,
750
- generateFlowSeeds,
751
- generateMilestoneRules,
752
- generateCorrelationMap,
753
- generateConnectors,
754
- deriveBusinessSurfaces,
755
- deriveMilestones,
756
- inferEventName,
757
- validateArtifacts,
758
- writeArtifacts,
759
- mapFrameworkName,
760
- ormDialects,
761
- authStrategy,
762
- };