@saptools/service-flow 0.1.2 → 0.1.4

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.
@@ -1,742 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/discovery/discover-repositories.ts
4
- import fs from "fs/promises";
5
- import path2 from "path";
6
-
7
- // src/utils/path-utils.ts
8
- import path from "path";
9
- function normalizePath(value) {
10
- return value.split(path.sep).join("/");
11
- }
12
- function relativePath(root, value) {
13
- return normalizePath(path.relative(root, value) || ".");
14
- }
15
- function ensureLeadingSlash(value) {
16
- return value.startsWith("/") ? value : `/${value}`;
17
- }
18
- function stripQuotes(value) {
19
- return value.replace(/^['"`]|['"`]$/g, "");
20
- }
21
-
22
- // src/discovery/discover-repositories.ts
23
- async function discoverRepositories(rootPath, ignore) {
24
- const root = path2.resolve(rootPath);
25
- const ignored = new Set(ignore);
26
- const found = [];
27
- async function walk(dir) {
28
- const rel = relativePath(root, dir);
29
- if (rel !== "." && rel.split("/").some((part) => ignored.has(part))) return;
30
- let entries;
31
- try {
32
- entries = await fs.readdir(dir, { withFileTypes: true });
33
- } catch {
34
- return;
35
- }
36
- if (entries.some((e) => e.name === ".git" || e.name === ".git-fixture")) {
37
- found.push({
38
- name: path2.basename(dir),
39
- absolutePath: dir,
40
- relativePath: relativePath(root, dir),
41
- isGitRepo: true
42
- });
43
- return;
44
- }
45
- for (const entry of entries)
46
- if (entry.isDirectory() && !ignore.includes(entry.name))
47
- await walk(path2.join(dir, entry.name));
48
- }
49
- await walk(root);
50
- return found.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
51
- }
52
-
53
- // src/parsers/package-json-parser.ts
54
- import fs2 from "fs/promises";
55
- import path3 from "path";
56
- function recordOfString(value) {
57
- if (!value || typeof value !== "object") return {};
58
- return Object.fromEntries(
59
- Object.entries(value).filter(([, v]) => typeof v === "string")
60
- );
61
- }
62
- function readRequires(cds) {
63
- const requires = cds && typeof cds === "object" && "requires" in cds ? cds.requires : void 0;
64
- if (!requires || typeof requires !== "object") return [];
65
- return Object.entries(requires).flatMap(([alias, raw]) => {
66
- if (!raw || typeof raw !== "object") return [];
67
- const obj = raw;
68
- const credentials = obj.credentials && typeof obj.credentials === "object" ? obj.credentials : {};
69
- return [
70
- {
71
- alias,
72
- kind: typeof obj.kind === "string" ? obj.kind : void 0,
73
- model: typeof obj.model === "string" ? obj.model : void 0,
74
- destination: typeof credentials.destination === "string" ? credentials.destination : void 0,
75
- servicePath: typeof credentials.path === "string" ? credentials.path : void 0,
76
- requestTimeout: typeof credentials.requestTimeout === "number" ? credentials.requestTimeout : void 0,
77
- rawJson: JSON.stringify(raw)
78
- }
79
- ];
80
- });
81
- }
82
- async function parsePackageJson(repoPath) {
83
- try {
84
- const raw = await fs2.readFile(path3.join(repoPath, "package.json"), "utf8");
85
- const json = JSON.parse(raw);
86
- return {
87
- packageName: typeof json.name === "string" ? json.name : void 0,
88
- packageVersion: typeof json.version === "string" ? json.version : void 0,
89
- dependencies: {
90
- ...recordOfString(json.dependencies),
91
- ...recordOfString(json.devDependencies)
92
- },
93
- cdsRequires: readRequires(json.cds),
94
- scripts: recordOfString(json.scripts)
95
- };
96
- } catch {
97
- return { dependencies: {}, cdsRequires: [], scripts: {} };
98
- }
99
- }
100
-
101
- // src/parsers/cds-parser.ts
102
- import fs3 from "fs/promises";
103
- import path4 from "path";
104
- function lineOf(text, index) {
105
- return text.slice(0, index).split("\n").length;
106
- }
107
- function maskCommentsAndStrings(text) {
108
- let out = "";
109
- let mode = "code";
110
- for (let i = 0; i < text.length; i += 1) {
111
- const c = text[i] ?? "";
112
- const n = text[i + 1] ?? "";
113
- if (mode === "code" && c === "/" && n === "/") {
114
- mode = "line";
115
- out += " ";
116
- i += 1;
117
- continue;
118
- }
119
- if (mode === "code" && c === "/" && n === "*") {
120
- mode = "block";
121
- out += " ";
122
- i += 1;
123
- continue;
124
- }
125
- if (mode === "line" && c === "\n") mode = "code";
126
- if (mode === "block" && c === "*" && n === "/") {
127
- mode = "code";
128
- out += " ";
129
- i += 1;
130
- continue;
131
- }
132
- if (mode === "code" && (c === "'" || c === '"' || c === "`")) {
133
- mode = c === "'" ? "single" : c === '"' ? "double" : "template";
134
- out += " ";
135
- continue;
136
- }
137
- if (mode === "single" && c === "'" || mode === "double" && c === '"' || mode === "template" && c === "`")
138
- mode = "code";
139
- out += mode === "code" || c === "\n" ? c : " ";
140
- }
141
- return out;
142
- }
143
- function readAnnotation(text, index) {
144
- if (text[index] !== "@") return void 0;
145
- let i = index + 1;
146
- while (/\s/.test(text[i] ?? "")) i += 1;
147
- if (text[i] !== "(") return void 0;
148
- let depth = 0;
149
- for (; i < text.length; i += 1) {
150
- if (text[i] === "(") depth += 1;
151
- if (text[i] === ")") depth -= 1;
152
- if (depth === 0) return { end: i + 1, raw: text.slice(index, i + 1) };
153
- }
154
- return void 0;
155
- }
156
- function collectAnnotations(text, index) {
157
- let i = index;
158
- let raw = "";
159
- while (i < text.length) {
160
- while (/\s/.test(text[i] ?? "")) i += 1;
161
- const annotation = readAnnotation(text, i);
162
- if (!annotation) break;
163
- raw += annotation.raw;
164
- i = annotation.end;
165
- }
166
- return { end: i, raw };
167
- }
168
- function pathAnnotation(raw) {
169
- return /path\s*:\s*['"]([^'"]+)['"]/s.exec(raw)?.[1];
170
- }
171
- function matchingBrace(text, open) {
172
- let depth = 0;
173
- for (let i = open; i < text.length; i += 1) {
174
- if (text[i] === "{") depth += 1;
175
- if (text[i] === "}") depth -= 1;
176
- if (depth === 0) return i;
177
- }
178
- return text.length - 1;
179
- }
180
- function operationsFromBody(text, maskedBody, bodyOffset, filePath) {
181
- return [...maskedBody.matchAll(/\b(action|function|event)\s+(\w+)\s*(?:\(([^)]*)\))?\s*(?:returns\s+([^;{]+))?/g)].map((m) => ({
182
- operationType: m[1] ?? "action",
183
- operationName: m[2] ?? "unknown",
184
- operationPath: ensureLeadingSlash(m[2] ?? "unknown"),
185
- paramsJson: JSON.stringify((m[3] ?? "").split(",").map((part) => part.trim()).filter(Boolean)),
186
- returnType: m[4]?.trim(),
187
- sourceFile: normalizePath(filePath),
188
- sourceLine: lineOf(text, bodyOffset + (m.index ?? 0))
189
- }));
190
- }
191
- async function parseCdsFile(repoPath, filePath) {
192
- const absolute = path4.join(repoPath, filePath);
193
- const text = await fs3.readFile(absolute, "utf8");
194
- const masked = maskCommentsAndStrings(text);
195
- const namespace = /namespace\s+([\w.]+)\s*;/.exec(masked)?.[1];
196
- const services = [];
197
- const pendingAnnotations = [];
198
- for (const a of masked.matchAll(/@\s*\(/g)) {
199
- const annotation = collectAnnotations(masked, a.index ?? 0);
200
- pendingAnnotations.push(annotation);
201
- }
202
- const serviceRegex = /\b(extend\s+)?service\s+([\w.]+)\b/g;
203
- let match;
204
- while (match = serviceRegex.exec(masked)) {
205
- const afterName = collectAnnotations(masked, serviceRegex.lastIndex);
206
- const open = masked.indexOf("{", afterName.end);
207
- if (open === -1) continue;
208
- const matchIndex = match.index;
209
- const prefix = pendingAnnotations.filter((a) => a.end <= matchIndex && matchIndex - a.end < 8).map((a) => a.raw).join("");
210
- const annotations = `${prefix}${afterName.raw}`;
211
- const end = matchingBrace(masked, open);
212
- const body = masked.slice(open + 1, end);
213
- const name = match[2] ?? "UnknownService";
214
- const serviceName = name.split(".").pop() ?? name;
215
- const servicePath = ensureLeadingSlash(pathAnnotation(annotations) ?? serviceName);
216
- services.push({
217
- namespace,
218
- serviceName,
219
- qualifiedName: name.includes(".") ? name : namespace ? `${namespace}.${name}` : name,
220
- servicePath,
221
- isExtend: Boolean(match[1]),
222
- sourceFile: normalizePath(filePath),
223
- sourceLine: lineOf(text, match.index),
224
- operations: operationsFromBody(text, body, open + 1, filePath)
225
- });
226
- serviceRegex.lastIndex = end + 1;
227
- }
228
- const baseOps = new Map(services.filter((s) => !s.isExtend).map((s) => [s.qualifiedName, s.operations]));
229
- for (const service of services.filter((s) => s.isExtend && s.operations.length === 0)) {
230
- const inherited = baseOps.get(service.qualifiedName) ?? baseOps.get(service.serviceName);
231
- if (inherited) service.operations = inherited.map((op) => ({ ...op, sourceFile: service.sourceFile, sourceLine: service.sourceLine }));
232
- }
233
- return services;
234
- }
235
-
236
- // src/parsers/decorator-parser.ts
237
- import fs4 from "fs/promises";
238
- import path5 from "path";
239
- import ts2 from "typescript";
240
-
241
- // src/parsers/ts-project.ts
242
- import ts from "typescript";
243
- function createSourceFile(filePath, text) {
244
- return ts.createSourceFile(
245
- filePath,
246
- text,
247
- ts.ScriptTarget.Latest,
248
- true,
249
- filePath.endsWith(".js") ? ts.ScriptKind.JS : ts.ScriptKind.TS
250
- );
251
- }
252
-
253
- // src/parsers/decorator-parser.ts
254
- function line(sf, pos) {
255
- return sf.getLineAndCharacterOfPosition(pos).line + 1;
256
- }
257
- function decs(node) {
258
- return ts2.canHaveDecorators(node) ? [...ts2.getDecorators(node) ?? []] : [];
259
- }
260
- function callName(d) {
261
- const e = d.expression;
262
- return ts2.isCallExpression(e) ? e.expression.getText() : e.getText();
263
- }
264
- function firstArg(d) {
265
- const e = d.expression;
266
- return ts2.isCallExpression(e) && e.arguments[0] ? e.arguments[0].getText() : "";
267
- }
268
- async function parseDecorators(repoPath, filePath) {
269
- const text = await fs4.readFile(path5.join(repoPath, filePath), "utf8");
270
- const sf = createSourceFile(filePath, text);
271
- const constants = /* @__PURE__ */ new Map();
272
- const handlers = [];
273
- function visit(node) {
274
- if (ts2.isVariableDeclaration(node) && ts2.isIdentifier(node.name) && node.initializer && ts2.isStringLiteralLike(node.initializer))
275
- constants.set(node.name.text, node.initializer.text);
276
- if (ts2.isClassDeclaration(node)) {
277
- const className = node.name?.text ?? "AnonymousHandler";
278
- const hasHandler = decs(node).some((d) => callName(d) === "Handler");
279
- const methods = node.members.filter(ts2.isMethodDeclaration).flatMap(
280
- (m) => decs(m).filter(
281
- (d) => ["Func", "Action", "On", "Event"].includes(callName(d))
282
- ).map((d) => {
283
- const raw = firstArg(d);
284
- const value = raw.startsWith('"') || raw.startsWith("'") || raw.startsWith("`") ? stripQuotes(raw) : constants.get(raw) ?? (raw.endsWith(".name") ? raw.split(".").at(-2) : void 0);
285
- return {
286
- methodName: m.name.getText(),
287
- decoratorKind: callName(d),
288
- decoratorValue: value,
289
- decoratorRawExpression: raw,
290
- sourceFile: normalizePath(filePath),
291
- sourceLine: line(sf, m.getStart())
292
- };
293
- })
294
- );
295
- if (hasHandler || methods.length > 0)
296
- handlers.push({
297
- className,
298
- sourceFile: normalizePath(filePath),
299
- sourceLine: line(sf, node.getStart()),
300
- methods
301
- });
302
- }
303
- ts2.forEachChild(node, visit);
304
- }
305
- visit(sf);
306
- return handlers;
307
- }
308
-
309
- // src/parsers/handler-registration-parser.ts
310
- import fs5 from "fs/promises";
311
- import path6 from "path";
312
- function lineOf2(text, idx) {
313
- return text.slice(0, idx).split("\n").length;
314
- }
315
- async function parseHandlerRegistrations(repoPath, filePath) {
316
- const text = await fs5.readFile(path6.join(repoPath, filePath), "utf8");
317
- const out = [];
318
- for (const m of text.matchAll(
319
- /createCombinedHandler\s*\(|srv\.prepend\s*\(|cds\.serve\s*\(/g
320
- ))
321
- out.push({
322
- registrationFile: normalizePath(filePath),
323
- registrationLine: lineOf2(text, m.index ?? 0),
324
- registrationKind: m[0].startsWith("cds") ? "cds.serve" : "combined-handler",
325
- confidence: 0.8
326
- });
327
- for (const m of text.matchAll(
328
- /(?:const|export\s+const)\s+handlers\s*=\s*\[([\s\S]*?)\]/g
329
- ))
330
- for (const c of (m[1] ?? "").matchAll(/\b(\w+Handler)\b/g))
331
- out.push({
332
- className: c[1],
333
- registrationFile: normalizePath(filePath),
334
- registrationLine: lineOf2(text, (m.index ?? 0) + (c.index ?? 0)),
335
- registrationKind: "handler-array",
336
- confidence: 0.9
337
- });
338
- return out;
339
- }
340
-
341
- // src/utils/redaction.ts
342
- var SENSITIVE = /authorization|cookie|token|secret|password|key|credential/i;
343
- function redactText(text) {
344
- return text.replace(
345
- /(authorization|cookie|token|secret|password|key|credential)\s*[:=]\s*(['"`]?)[^,'"`}\s]+\2/gi,
346
- "$1: [REDACTED]"
347
- );
348
- }
349
- function redactValue(value) {
350
- if (Array.isArray(value)) return value.map(redactValue);
351
- if (value && typeof value === "object") {
352
- const out = {};
353
- for (const [k, v] of Object.entries(value))
354
- out[k] = SENSITIVE.test(k) ? "[REDACTED]" : redactValue(v);
355
- return out;
356
- }
357
- return typeof value === "string" ? redactText(value) : value;
358
- }
359
- function summarizeExpression(text) {
360
- return redactText(text).slice(0, 240);
361
- }
362
-
363
- // src/parsers/outbound-call-parser.ts
364
- import fs6 from "fs/promises";
365
- import path7 from "path";
366
- function lineOf3(text, idx) {
367
- return text.slice(0, idx).split("\n").length;
368
- }
369
- function firstArg2(body, key) {
370
- return new RegExp(`${key}\\s*:\\s*([^,}\\n]+)`).exec(body)?.[1]?.trim();
371
- }
372
- async function parseOutboundCalls(repoPath, filePath) {
373
- const text = await fs6.readFile(path7.join(repoPath, filePath), "utf8");
374
- const out = [];
375
- for (const m of text.matchAll(/(\w+)\.send\s*\(\s*\{([\s\S]*?)\}\s*\)/g)) {
376
- const body = m[2] ?? "";
377
- const query = firstArg2(body, "query");
378
- const op = firstArg2(body, "path");
379
- out.push({
380
- callType: query ? "remote_query" : "remote_action",
381
- serviceVariableName: m[1],
382
- method: stripQuotes(firstArg2(body, "method") ?? "POST"),
383
- operationPathExpr: op ? stripQuotes(op) : void 0,
384
- queryEntity: /SELECT(?:\.one)?\.from\(([\w.]+)\)/.exec(query ?? "")?.[1],
385
- payloadSummary: summarizeExpression(body),
386
- sourceFile: normalizePath(filePath),
387
- sourceLine: lineOf3(text, m.index ?? 0),
388
- confidence: op || query ? 0.8 : 0.4
389
- });
390
- }
391
- for (const m of text.matchAll(/cds\.run\s*\(([\s\S]*?)\)/g))
392
- out.push({
393
- callType: "local_db_query",
394
- queryEntity: /(?:SELECT(?:\.one)?\.from|INSERT\.into|UPDATE|DELETE\.from)\(([\w.]+)\)/.exec(m[1] ?? "")?.[1],
395
- payloadSummary: summarizeExpression(m[1] ?? ""),
396
- sourceFile: normalizePath(filePath),
397
- sourceLine: lineOf3(text, m.index ?? 0),
398
- confidence: 0.85
399
- });
400
- for (const m of text.matchAll(
401
- /(\w+)\.(emit|publish|on)\s*\(\s*(['"`])([^'"`]+)\3/g
402
- ))
403
- out.push({
404
- callType: m[2] === "on" ? "async_subscribe" : "async_emit",
405
- serviceVariableName: m[1],
406
- eventNameExpr: m[4],
407
- sourceFile: normalizePath(filePath),
408
- sourceLine: lineOf3(text, m.index ?? 0),
409
- confidence: 0.8
410
- });
411
- for (const m of text.matchAll(
412
- /(?:axios\s*\(|executeHttpRequest\s*\(|useOrFetchDestination\s*\()([\s\S]*?)\)/g
413
- ))
414
- out.push({
415
- callType: "external_http",
416
- payloadSummary: summarizeExpression(m[1] ?? ""),
417
- sourceFile: normalizePath(filePath),
418
- sourceLine: lineOf3(text, m.index ?? 0),
419
- confidence: 0.7,
420
- unresolvedReason: "External HTTP destination is outside indexed CAP services"
421
- });
422
- for (const m of text.matchAll(
423
- /cds\.services(?:\[['"]([^'"]+)['"]\]|\.(\w+))\.(\w+)\s*\(/g
424
- ))
425
- out.push({
426
- callType: "local_service_call",
427
- operationPathExpr: `/${m[3] ?? ""}`,
428
- payloadSummary: m[1] ?? m[2],
429
- sourceFile: normalizePath(filePath),
430
- sourceLine: lineOf3(text, m.index ?? 0),
431
- confidence: 0.75
432
- });
433
- return out;
434
- }
435
-
436
- // src/parsers/service-binding-parser.ts
437
- import fs7 from "fs/promises";
438
- import path8 from "path";
439
- function lineOf4(text, idx) {
440
- return text.slice(0, idx).split("\n").length;
441
- }
442
- function placeholders(value) {
443
- return [...(value ?? "").matchAll(/\$\{\s*(\w+)\s*\}/g)].map((m) => m[1] ?? "").filter(Boolean);
444
- }
445
- async function parseServiceBindings(repoPath, filePath) {
446
- const text = await fs7.readFile(path8.join(repoPath, filePath), "utf8");
447
- const out = [];
448
- for (const m of text.matchAll(
449
- /(?:const|let|this\.)\s*(\w+)\s*=\s*(?:await\s*)?cds\.connect\.to\((['"`])([^'"`]+)\2\)/g
450
- ))
451
- out.push({
452
- variableName: m[1] ?? "service",
453
- alias: m[3],
454
- isDynamic: false,
455
- placeholders: [],
456
- sourceFile: normalizePath(filePath),
457
- sourceLine: lineOf4(text, m.index ?? 0)
458
- });
459
- for (const m of text.matchAll(
460
- /(?:const|let|this\.)\s*(\w+)\s*=\s*(?:await\s*)?cds\.connect\.to\(\{([\s\S]*?)\}\s*\)/g
461
- )) {
462
- const body = m[2] ?? "";
463
- const destination = /destination\s*:\s*([^,\n]+)/.exec(body)?.[1];
464
- const servicePath = /path\s*:\s*([^,\n]+)/.exec(body)?.[1];
465
- const dest = destination ? stripQuotes(destination.trim()) : void 0;
466
- const svc = servicePath ? stripQuotes(servicePath.trim()) : void 0;
467
- const ph = [...placeholders(dest), ...placeholders(svc)];
468
- out.push({
469
- variableName: m[1] ?? "service",
470
- destinationExpr: dest,
471
- servicePathExpr: svc,
472
- isDynamic: ph.length > 0,
473
- placeholders: ph,
474
- sourceFile: normalizePath(filePath),
475
- sourceLine: lineOf4(text, m.index ?? 0)
476
- });
477
- }
478
- for (const m of text.matchAll(
479
- /(?:function\s+(\w+)\s*\([^)]*\)\s*\{[\s\S]*?return|const\s+(\w+)\s*=\s*(?:async\s*)?\([^)]*\)\s*=>)\s+(?:await\s*)?cds\.connect\.to\((['"`])([^'"`]+)\3\)/g
480
- ))
481
- out.push({
482
- variableName: m[1] ?? m[2] ?? "connect",
483
- alias: m[4],
484
- isDynamic: false,
485
- placeholders: [],
486
- sourceFile: normalizePath(filePath),
487
- sourceLine: lineOf4(text, m.index ?? 0)
488
- });
489
- const helperAliases = new Map(out.filter((b) => b.alias).map((b) => [b.variableName, b]));
490
- for (const m of text.matchAll(/(?:const|let)\s+(\w+)\s*=\s*(?:await\s*)?(\w+)\s*\(/g)) {
491
- const helper = helperAliases.get(m[2] ?? "");
492
- if (!helper) continue;
493
- out.push({
494
- ...helper,
495
- variableName: m[1] ?? "service",
496
- sourceFile: normalizePath(filePath),
497
- sourceLine: lineOf4(text, m.index ?? 0)
498
- });
499
- }
500
- return out;
501
- }
502
-
503
- // src/linker/dynamic-edge-resolver.ts
504
- function applyVariables(template, vars) {
505
- if (!template) return void 0;
506
- return template.replace(
507
- /\$\{\s*(\w+)\s*\}/g,
508
- (_m, key) => vars[key] ?? `\${${key}}`
509
- );
510
- }
511
-
512
- // src/linker/service-resolver.ts
513
- function findOperation(db, servicePath, operationPath, workspaceId) {
514
- if (!operationPath) return void 0;
515
- const row = db.prepare(
516
- `SELECT o.id operationId,r.name repoName,s.service_path servicePath,o.operation_path operationPath,o.operation_name operationName,o.source_file sourceFile,o.source_line sourceLine
517
- FROM cds_operations o
518
- JOIN cds_services s ON s.id=o.service_id
519
- JOIN repositories r ON r.id=s.repo_id
520
- WHERE (? IS NULL OR r.workspace_id=?)
521
- AND (? IS NULL OR s.service_path=?)
522
- AND (o.operation_path=? OR o.operation_name=?)
523
- ORDER BY CASE WHEN s.service_path=? THEN 0 ELSE 1 END
524
- LIMIT 1`
525
- ).get(
526
- workspaceId,
527
- workspaceId,
528
- servicePath,
529
- servicePath,
530
- operationPath,
531
- operationPath.replace(/^\//, ""),
532
- servicePath
533
- );
534
- return row;
535
- }
536
-
537
- // src/linker/helper-package-linker.ts
538
- function linkHelperPackages(db, workspaceId) {
539
- const repos = db.prepare(
540
- "SELECT id,name,dependencies_json FROM repositories WHERE workspace_id=?"
541
- ).all(workspaceId);
542
- let count = 0;
543
- for (const repo of repos) {
544
- const deps = JSON.parse(repo.dependencies_json);
545
- for (const dep of Object.keys(deps)) {
546
- const helper = repos.find((r) => r.name === dep || dep.endsWith(r.name));
547
- if (helper) {
548
- db.prepare(
549
- "INSERT INTO graph_edges(workspace_id,edge_type,from_kind,from_id,to_kind,to_id,confidence,evidence_json,is_dynamic) VALUES(?,?,?,?,?,?,?,?,?)"
550
- ).run(
551
- workspaceId,
552
- "REPO_IMPORTS_HELPER_PACKAGE",
553
- "repo",
554
- String(repo.id),
555
- "repo",
556
- String(helper.id),
557
- 0.9,
558
- JSON.stringify({ dependency: dep }),
559
- 0
560
- );
561
- count += 1;
562
- }
563
- }
564
- }
565
- return count;
566
- }
567
-
568
- // src/linker/cross-repo-linker.ts
569
- function linkWorkspace(db, workspaceId, vars = {}) {
570
- db.prepare("DELETE FROM graph_edges WHERE workspace_id=?").run(workspaceId);
571
- let edges = linkHelperPackages(db, workspaceId);
572
- let unresolved = 0;
573
- const calls = db.prepare(
574
- `SELECT c.*,r.name repoName,b.alias,b.destination_expr destinationExpr,b.service_path_expr servicePathExpr,b.is_dynamic isDynamic,b.placeholders_json placeholdersJson,req.service_path requireServicePath,req.destination requireDestination FROM outbound_calls c JOIN repositories r ON r.id=c.repo_id LEFT JOIN service_bindings b ON b.id=c.service_binding_id LEFT JOIN cds_requires req ON req.repo_id=c.repo_id AND req.alias=b.alias WHERE r.workspace_id=?`
575
- ).all(workspaceId);
576
- for (const call of calls) {
577
- const callType = String(call.call_type);
578
- const op = applyVariables(String(call.operation_path_expr ?? ""), vars);
579
- const servicePath = applyVariables(
580
- call.servicePathExpr ?? call.requireServicePath,
581
- vars
582
- );
583
- const target = callType.startsWith("remote") ? findOperation(db, servicePath, op, workspaceId) : void 0;
584
- const evidence = {
585
- sourceFile: call.source_file,
586
- sourceLine: call.source_line,
587
- serviceAlias: call.alias,
588
- destination: call.destinationExpr ?? call.requireDestination,
589
- servicePath,
590
- operationPath: op,
591
- targetRepo: target?.repoName,
592
- targetOperation: target?.operationName
593
- };
594
- if (target) {
595
- db.prepare(
596
- "INSERT INTO graph_edges(workspace_id,edge_type,from_kind,from_id,to_kind,to_id,confidence,evidence_json,is_dynamic) VALUES(?,?,?,?,?,?,?,?,?)"
597
- ).run(
598
- workspaceId,
599
- "REMOTE_CALL_RESOLVES_TO_OPERATION",
600
- "call",
601
- String(call.id),
602
- "operation",
603
- String(target.operationId),
604
- call.isDynamic ? 0.6 : 0.9,
605
- JSON.stringify(evidence),
606
- call.isDynamic ? 1 : 0
607
- );
608
- edges += 1;
609
- } else {
610
- const edgeType = callType === "local_db_query" ? "HANDLER_RUNS_DB_QUERY" : callType === "external_http" ? "HANDLER_CALLS_EXTERNAL_HTTP" : callType === "async_emit" ? "HANDLER_EMITS_EVENT" : callType === "async_subscribe" ? "EVENT_CONSUMED_BY_HANDLER" : call.isDynamic ? "DYNAMIC_EDGE_CANDIDATE" : "UNRESOLVED_EDGE";
611
- db.prepare(
612
- "INSERT INTO graph_edges(workspace_id,edge_type,from_kind,from_id,to_kind,to_id,confidence,evidence_json,is_dynamic,unresolved_reason) VALUES(?,?,?,?,?,?,?,?,?,?)"
613
- ).run(
614
- workspaceId,
615
- edgeType,
616
- "call",
617
- String(call.id),
618
- callType.startsWith("async_") ? "event" : "external",
619
- String(call.event_name_expr ?? call.query_entity ?? op ?? call.id),
620
- Number(call.confidence ?? 0.2),
621
- JSON.stringify(evidence),
622
- call.isDynamic ? 1 : 0,
623
- String(call.unresolved_reason ?? "No indexed target operation matched")
624
- );
625
- edges += 1;
626
- unresolved += edgeType === "UNRESOLVED_EDGE" ? 1 : 0;
627
- }
628
- }
629
- return { edgeCount: edges, unresolvedCount: unresolved };
630
- }
631
-
632
- // src/trace/trace-engine.ts
633
- function normalizeOperation(value) {
634
- if (!value) return void 0;
635
- return value.startsWith("/") ? value.slice(1) : value;
636
- }
637
- function positiveDepth(value) {
638
- return Number.isFinite(value) && value > 0 ? Math.floor(value) : 25;
639
- }
640
- function sourceFilesForStart(db, repoId, start) {
641
- const handler = start.handler;
642
- const operation = normalizeOperation(start.operation ?? start.operationPath);
643
- if (!handler && !operation) return void 0;
644
- const rows = db.prepare(`SELECT DISTINCT hc.source_file sourceFile
645
- FROM handler_classes hc LEFT JOIN handler_methods hm ON hm.handler_class_id=hc.id
646
- WHERE (? IS NULL OR hc.repo_id=?) AND (? IS NULL OR hc.class_name=? OR hm.method_name=?)
647
- AND (? IS NULL OR hm.decorator_value=? OR hm.method_name=?)`).all(repoId, repoId, handler, handler, handler, operation, operation, operation);
648
- if (rows.length === 0) return void 0;
649
- return new Set(rows.map((row) => row.sourceFile).filter(Boolean));
650
- }
651
- function startScope(db, start) {
652
- const repo = start.repo ? db.prepare("SELECT id,name FROM repositories WHERE name=? OR package_name=?").get(start.repo, start.repo) : void 0;
653
- if (start.repo && !repo) return { repo, selectorMatched: false };
654
- const sourceFiles = sourceFilesForStart(db, repo?.id, start);
655
- const hasSelector = Boolean(start.handler ?? start.operation ?? start.operationPath);
656
- return { repo, sourceFiles, selectorMatched: !hasSelector || sourceFiles !== void 0 };
657
- }
658
- function handlerFilesForOperation(db, operationId) {
659
- const op = db.prepare(`SELECT o.operation_name operationName,o.operation_path operationPath,s.repo_id repoId
660
- FROM cds_operations o JOIN cds_services s ON s.id=o.service_id WHERE o.id=?`).get(operationId);
661
- if (!op) return /* @__PURE__ */ new Set();
662
- const operation = normalizeOperation(op.operationPath ?? op.operationName);
663
- const rows = db.prepare(`SELECT DISTINCT hc.source_file sourceFile FROM handler_classes hc
664
- JOIN handler_methods hm ON hm.handler_class_id=hc.id
665
- WHERE hc.repo_id=? AND (hm.decorator_value=? OR hm.method_name=? OR hm.decorator_value=?)`).all(op.repoId, operation, operation, op.operationName);
666
- return new Set(rows.map((row) => row.sourceFile).filter(Boolean));
667
- }
668
- function includeCall(type, options) {
669
- if (!options.includeDb && type === "local_db_query") return false;
670
- if (!options.includeExternal && type === "external_http") return false;
671
- if (!options.includeAsync && type.startsWith("async_")) return false;
672
- return true;
673
- }
674
- function graphForCalls(db, callIds) {
675
- const map = /* @__PURE__ */ new Map();
676
- if (callIds.length === 0) return map;
677
- const rows = db.prepare(`SELECT * FROM graph_edges WHERE from_kind='call' AND from_id IN (${callIds.map(() => "?").join(",")}) ORDER BY id`).all(...callIds);
678
- for (const row of rows) {
679
- const id = Number(row.from_id);
680
- map.set(id, [...map.get(id) ?? [], row]);
681
- }
682
- return map;
683
- }
684
- function trace(db, start, options) {
685
- const scope = startScope(db, start);
686
- const diagnostics = db.prepare("SELECT severity,code,message,source_file sourceFile,source_line sourceLine FROM diagnostics WHERE (? IS NULL OR repo_id=?)").all(scope.repo?.id, scope.repo?.id);
687
- if (!scope.selectorMatched) diagnostics.unshift({ severity: "warning", code: "trace_start_not_found", message: "No handler source matched the requested trace start selector" });
688
- const maxDepth = positiveDepth(options.depth);
689
- const edges = [];
690
- const nodes = /* @__PURE__ */ new Map();
691
- const queue = scope.selectorMatched ? [{ repoId: scope.repo?.id, files: scope.sourceFiles, depth: 1 }] : [];
692
- const seenScopes = /* @__PURE__ */ new Set();
693
- while (queue.length > 0) {
694
- const current = queue.shift();
695
- if (!current || current.depth > maxDepth) continue;
696
- const key = `${current.repoId ?? "*"}:${[...current.files ?? /* @__PURE__ */ new Set(["*"])].sort().join(",")}:${current.depth}`;
697
- if (seenScopes.has(key)) continue;
698
- seenScopes.add(key);
699
- const calls = db.prepare(`SELECT c.*,r.name repoName FROM outbound_calls c JOIN repositories r ON r.id=c.repo_id WHERE (? IS NULL OR c.repo_id=?) ORDER BY c.source_file,c.source_line`).all(current.repoId, current.repoId);
700
- const filtered = calls.filter((c) => (!current.files || current.files.has(String(c.source_file))) && includeCall(String(c.call_type), options));
701
- const graph = graphForCalls(db, filtered.map((c) => Number(c.id)));
702
- for (const call of filtered) {
703
- const callNode = `call:${call.id}`;
704
- nodes.set(callNode, { id: callNode, kind: "outbound_call", repo: call.repoName, file: call.source_file, line: call.source_line, callType: call.call_type });
705
- const graphRows = graph.get(Number(call.id)) ?? [];
706
- for (const row of graphRows) {
707
- const evidence = JSON.parse(String(row.evidence_json || "{}"));
708
- const targetNode = `${row.to_kind}:${row.to_id}`;
709
- nodes.set(targetNode, { id: targetNode, kind: row.to_kind, label: row.to_id, ...evidence });
710
- const servicePath = typeof evidence.servicePath === "string" ? evidence.servicePath : void 0;
711
- const operationPath = typeof evidence.operationPath === "string" ? evidence.operationPath : void 0;
712
- const targetOperation = typeof evidence.targetOperation === "string" ? evidence.targetOperation : void 0;
713
- const targetRepo = typeof evidence.targetRepo === "string" ? evidence.targetRepo : "";
714
- const to = servicePath && operationPath ? `${servicePath}${operationPath}` : targetOperation ? `${targetRepo}:${targetOperation}` : row.to_id;
715
- edges.push({ step: current.depth, type: String(call.call_type), from: `${call.repoName}:${call.source_file}`, to, evidence, confidence: Number(row.confidence ?? call.confidence), unresolvedReason: row.unresolved_reason });
716
- if (row.to_kind === "operation" && current.depth < maxDepth) {
717
- const files = handlerFilesForOperation(db, row.to_id);
718
- if (files.size > 0) queue.push({ files, depth: current.depth + 1 });
719
- }
720
- }
721
- }
722
- }
723
- return { start, nodes: [...nodes.values()], edges, diagnostics };
724
- }
725
-
726
- export {
727
- normalizePath,
728
- stripQuotes,
729
- discoverRepositories,
730
- parsePackageJson,
731
- parseCdsFile,
732
- parseDecorators,
733
- parseHandlerRegistrations,
734
- redactText,
735
- redactValue,
736
- parseOutboundCalls,
737
- parseServiceBindings,
738
- applyVariables,
739
- linkWorkspace,
740
- trace
741
- };
742
- //# sourceMappingURL=chunk-6U4QKQEL.js.map