@saptools/service-flow 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +27 -7
- package/TECHNICAL-NOTE.md +7 -0
- package/dist/chunk-SIKIGT42.js +1166 -0
- package/dist/chunk-SIKIGT42.js.map +1 -0
- package/dist/cli.js +106 -20
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/package.json +2 -1
- package/dist/chunk-RFBHT6BQ.js +0 -686
- package/dist/chunk-RFBHT6BQ.js.map +0 -1
|
@@ -0,0 +1,1166 @@
|
|
|
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
|
+
function matchingParen(text, open) {
|
|
373
|
+
let depth = 0;
|
|
374
|
+
let quote;
|
|
375
|
+
let escaped = false;
|
|
376
|
+
for (let i = open; i < text.length; i += 1) {
|
|
377
|
+
const ch = text[i] ?? "";
|
|
378
|
+
if (quote) {
|
|
379
|
+
if (escaped) escaped = false;
|
|
380
|
+
else if (ch === "\\") escaped = true;
|
|
381
|
+
else if (ch === quote) quote = void 0;
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
if (ch === '"' || ch === "'" || ch === "`") {
|
|
385
|
+
quote = ch;
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
if (ch === "(") depth += 1;
|
|
389
|
+
if (ch === ")") {
|
|
390
|
+
depth -= 1;
|
|
391
|
+
if (depth === 0) return i;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
return -1;
|
|
395
|
+
}
|
|
396
|
+
function argumentForCall(expr, marker) {
|
|
397
|
+
const idx = expr.indexOf(marker);
|
|
398
|
+
if (idx < 0) return void 0;
|
|
399
|
+
const open = expr.indexOf("(", idx + marker.length);
|
|
400
|
+
if (open < 0) return void 0;
|
|
401
|
+
const close = matchingParen(expr, open);
|
|
402
|
+
return close > open ? expr.slice(open + 1, close).trim() : void 0;
|
|
403
|
+
}
|
|
404
|
+
function entityFromArg(arg) {
|
|
405
|
+
if (!arg) return void 0;
|
|
406
|
+
const first = arg.split(",")[0]?.trim();
|
|
407
|
+
if (!first) return void 0;
|
|
408
|
+
return stripQuotes(first).replace(/^this\./, "");
|
|
409
|
+
}
|
|
410
|
+
function extractQueryEntity(expr) {
|
|
411
|
+
return entityFromArg(argumentForCall(expr, "SELECT.one.from")) ?? entityFromArg(argumentForCall(expr, "SELECT.from")) ?? entityFromArg(argumentForCall(expr, "INSERT.into")) ?? entityFromArg(argumentForCall(expr, "UPDATE")) ?? entityFromArg(argumentForCall(expr, "DELETE.from"));
|
|
412
|
+
}
|
|
413
|
+
async function parseOutboundCalls(repoPath, filePath) {
|
|
414
|
+
const text = await fs6.readFile(path7.join(repoPath, filePath), "utf8");
|
|
415
|
+
const out = [];
|
|
416
|
+
for (const m of text.matchAll(/(\w+)\.send\s*\(\s*\{([\s\S]*?)\}\s*\)/g)) {
|
|
417
|
+
const body = m[2] ?? "";
|
|
418
|
+
const query = firstArg2(body, "query");
|
|
419
|
+
const op = firstArg2(body, "path") ?? firstArg2(body, "event");
|
|
420
|
+
out.push({
|
|
421
|
+
callType: query ? "remote_query" : "remote_action",
|
|
422
|
+
serviceVariableName: m[1],
|
|
423
|
+
method: stripQuotes(firstArg2(body, "method") ?? "POST"),
|
|
424
|
+
operationPathExpr: op ? `/${stripQuotes(op).replace(/^\//, "")}` : void 0,
|
|
425
|
+
queryEntity: extractQueryEntity(query ?? ""),
|
|
426
|
+
payloadSummary: summarizeExpression(body),
|
|
427
|
+
sourceFile: normalizePath(filePath),
|
|
428
|
+
sourceLine: lineOf3(text, m.index ?? 0),
|
|
429
|
+
confidence: op || query ? 0.8 : 0.4
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
for (const m of text.matchAll(/cds\.run\s*\(/g)) {
|
|
433
|
+
const open = (m.index ?? 0) + m[0].lastIndexOf("(");
|
|
434
|
+
const close = matchingParen(text, open);
|
|
435
|
+
const expr = close > open ? text.slice(open + 1, close) : "";
|
|
436
|
+
const entity = extractQueryEntity(expr);
|
|
437
|
+
out.push({
|
|
438
|
+
callType: "local_db_query",
|
|
439
|
+
queryEntity: entity,
|
|
440
|
+
payloadSummary: summarizeExpression(expr),
|
|
441
|
+
sourceFile: normalizePath(filePath),
|
|
442
|
+
sourceLine: lineOf3(text, m.index ?? 0),
|
|
443
|
+
confidence: entity ? 0.9 : 0.55,
|
|
444
|
+
unresolvedReason: entity ? void 0 : "Could not resolve CAP query target entity from nested expression"
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
for (const m of text.matchAll(
|
|
448
|
+
/(\w+)\.(emit|publish|on)\s*\(\s*(['"`])([^'"`]+)\3/g
|
|
449
|
+
))
|
|
450
|
+
out.push({
|
|
451
|
+
callType: m[2] === "on" ? "async_subscribe" : "async_emit",
|
|
452
|
+
serviceVariableName: m[1],
|
|
453
|
+
eventNameExpr: m[4],
|
|
454
|
+
sourceFile: normalizePath(filePath),
|
|
455
|
+
sourceLine: lineOf3(text, m.index ?? 0),
|
|
456
|
+
confidence: 0.8
|
|
457
|
+
});
|
|
458
|
+
for (const m of text.matchAll(
|
|
459
|
+
/(?:axios\s*\(|executeHttpRequest\s*\(|useOrFetchDestination\s*\()([\s\S]*?)\)/g
|
|
460
|
+
))
|
|
461
|
+
out.push({
|
|
462
|
+
callType: "external_http",
|
|
463
|
+
payloadSummary: summarizeExpression(m[1] ?? ""),
|
|
464
|
+
sourceFile: normalizePath(filePath),
|
|
465
|
+
sourceLine: lineOf3(text, m.index ?? 0),
|
|
466
|
+
confidence: 0.7,
|
|
467
|
+
unresolvedReason: "External HTTP destination is outside indexed CAP services"
|
|
468
|
+
});
|
|
469
|
+
for (const m of text.matchAll(
|
|
470
|
+
/cds\.services(?:\[['"]([^'"]+)['"]\]|\.(\w+))\.(\w+)\s*\(/g
|
|
471
|
+
))
|
|
472
|
+
out.push({
|
|
473
|
+
callType: "local_service_call",
|
|
474
|
+
operationPathExpr: `/${m[3] ?? ""}`,
|
|
475
|
+
payloadSummary: m[1] ?? m[2],
|
|
476
|
+
sourceFile: normalizePath(filePath),
|
|
477
|
+
sourceLine: lineOf3(text, m.index ?? 0),
|
|
478
|
+
confidence: 0.75
|
|
479
|
+
});
|
|
480
|
+
return out;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// src/parsers/service-binding-parser.ts
|
|
484
|
+
import fs7 from "fs/promises";
|
|
485
|
+
import path8 from "path";
|
|
486
|
+
import ts3 from "typescript";
|
|
487
|
+
function lineOf4(sf, node) {
|
|
488
|
+
return sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;
|
|
489
|
+
}
|
|
490
|
+
function stringValue(node) {
|
|
491
|
+
if (!node) return void 0;
|
|
492
|
+
if (ts3.isStringLiteralLike(node) || ts3.isNoSubstitutionTemplateLiteral(node))
|
|
493
|
+
return node.text;
|
|
494
|
+
if (ts3.isTemplateExpression(node))
|
|
495
|
+
return node.getText().replace(/^`|`$/g, "");
|
|
496
|
+
return node.getText();
|
|
497
|
+
}
|
|
498
|
+
function placeholders(value) {
|
|
499
|
+
return [...(value ?? "").matchAll(/\$\{\s*(\w+)\s*\}/g)].map((m) => m[1] ?? "").filter(Boolean);
|
|
500
|
+
}
|
|
501
|
+
function connectFactFromCall(call) {
|
|
502
|
+
const expr = call.expression;
|
|
503
|
+
if (!ts3.isPropertyAccessExpression(expr) || expr.name.text !== "to")
|
|
504
|
+
return void 0;
|
|
505
|
+
const inner = expr.expression;
|
|
506
|
+
if (!ts3.isPropertyAccessExpression(inner) || inner.name.text !== "connect" || inner.expression.getText() !== "cds")
|
|
507
|
+
return void 0;
|
|
508
|
+
const first = call.arguments[0];
|
|
509
|
+
if (!first) return void 0;
|
|
510
|
+
if (ts3.isStringLiteralLike(first) || ts3.isNoSubstitutionTemplateLiteral(first))
|
|
511
|
+
return { alias: first.text, isDynamic: false, placeholders: [] };
|
|
512
|
+
if (!ts3.isObjectLiteralExpression(first))
|
|
513
|
+
return {
|
|
514
|
+
servicePathExpr: first.getText(),
|
|
515
|
+
isDynamic: true,
|
|
516
|
+
placeholders: []
|
|
517
|
+
};
|
|
518
|
+
let destinationExpr;
|
|
519
|
+
let servicePathExpr;
|
|
520
|
+
function visitObject(obj) {
|
|
521
|
+
for (const prop of obj.properties) {
|
|
522
|
+
if (!ts3.isPropertyAssignment(prop)) continue;
|
|
523
|
+
const name = ts3.isIdentifier(prop.name) || ts3.isStringLiteralLike(prop.name) ? prop.name.text : void 0;
|
|
524
|
+
if (name === "destination")
|
|
525
|
+
destinationExpr = stringValue(prop.initializer);
|
|
526
|
+
if (name === "path" || name === "servicePath")
|
|
527
|
+
servicePathExpr = stringValue(prop.initializer);
|
|
528
|
+
if (ts3.isObjectLiteralExpression(prop.initializer))
|
|
529
|
+
visitObject(prop.initializer);
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
visitObject(first);
|
|
533
|
+
const ph = [
|
|
534
|
+
...placeholders(destinationExpr),
|
|
535
|
+
...placeholders(servicePathExpr)
|
|
536
|
+
];
|
|
537
|
+
return {
|
|
538
|
+
destinationExpr,
|
|
539
|
+
servicePathExpr,
|
|
540
|
+
isDynamic: ph.length > 0 || !destinationExpr && !servicePathExpr,
|
|
541
|
+
placeholders: ph
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
function unwrapCall(expr) {
|
|
545
|
+
if (ts3.isAwaitExpression(expr)) return unwrapCall(expr.expression);
|
|
546
|
+
if (ts3.isCallExpression(expr)) return expr;
|
|
547
|
+
return void 0;
|
|
548
|
+
}
|
|
549
|
+
function findConnectInExpression(expr) {
|
|
550
|
+
const direct = unwrapCall(expr);
|
|
551
|
+
if (direct) {
|
|
552
|
+
const fact = connectFactFromCall(direct);
|
|
553
|
+
if (fact) return fact;
|
|
554
|
+
}
|
|
555
|
+
let found;
|
|
556
|
+
function visit(node) {
|
|
557
|
+
if (found) return;
|
|
558
|
+
if (ts3.isCallExpression(node)) found = connectFactFromCall(node);
|
|
559
|
+
if (!found) ts3.forEachChild(node, visit);
|
|
560
|
+
}
|
|
561
|
+
visit(expr);
|
|
562
|
+
return found;
|
|
563
|
+
}
|
|
564
|
+
async function readSource(abs) {
|
|
565
|
+
try {
|
|
566
|
+
const text = await fs7.readFile(abs, "utf8");
|
|
567
|
+
return ts3.createSourceFile(
|
|
568
|
+
abs,
|
|
569
|
+
text,
|
|
570
|
+
ts3.ScriptTarget.Latest,
|
|
571
|
+
true,
|
|
572
|
+
ts3.ScriptKind.TS
|
|
573
|
+
);
|
|
574
|
+
} catch {
|
|
575
|
+
return void 0;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
async function resolveImport(repoPath, fromFile, spec) {
|
|
579
|
+
if (!spec.startsWith(".")) return void 0;
|
|
580
|
+
const base = path8.resolve(repoPath, path8.dirname(fromFile), spec);
|
|
581
|
+
for (const candidate of [
|
|
582
|
+
base,
|
|
583
|
+
`${base}.ts`,
|
|
584
|
+
`${base}.js`,
|
|
585
|
+
path8.join(base, "index.ts"),
|
|
586
|
+
path8.join(base, "index.js")
|
|
587
|
+
]) {
|
|
588
|
+
try {
|
|
589
|
+
const st = await fs7.stat(candidate);
|
|
590
|
+
if (st.isFile()) return normalizePath(path8.relative(repoPath, candidate));
|
|
591
|
+
} catch {
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
return void 0;
|
|
595
|
+
}
|
|
596
|
+
async function importsFor(repoPath, filePath, sf) {
|
|
597
|
+
const imports = [];
|
|
598
|
+
for (const stmt of sf.statements) {
|
|
599
|
+
if (!ts3.isImportDeclaration(stmt) || !ts3.isStringLiteralLike(stmt.moduleSpecifier))
|
|
600
|
+
continue;
|
|
601
|
+
const sourceFile = await resolveImport(
|
|
602
|
+
repoPath,
|
|
603
|
+
filePath,
|
|
604
|
+
stmt.moduleSpecifier.text
|
|
605
|
+
);
|
|
606
|
+
const clause = stmt.importClause;
|
|
607
|
+
if (!clause) continue;
|
|
608
|
+
if (clause.name)
|
|
609
|
+
imports.push({
|
|
610
|
+
localName: clause.name.text,
|
|
611
|
+
exportedName: "default",
|
|
612
|
+
sourceFile
|
|
613
|
+
});
|
|
614
|
+
const bindings = clause.namedBindings;
|
|
615
|
+
if (bindings && ts3.isNamedImports(bindings))
|
|
616
|
+
for (const el of bindings.elements)
|
|
617
|
+
imports.push({
|
|
618
|
+
localName: el.name.text,
|
|
619
|
+
exportedName: el.propertyName?.text ?? el.name.text,
|
|
620
|
+
sourceFile
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
return imports;
|
|
624
|
+
}
|
|
625
|
+
async function helperBindings(repoPath, filePath) {
|
|
626
|
+
const sf = await readSource(path8.join(repoPath, filePath));
|
|
627
|
+
if (!sf) return [];
|
|
628
|
+
const sourceFileAst = sf;
|
|
629
|
+
const out = [];
|
|
630
|
+
for (const stmt of sf.statements) {
|
|
631
|
+
const exported = ts3.canHaveModifiers(stmt) ? ts3.getModifiers(stmt)?.some(
|
|
632
|
+
(m) => m.kind === ts3.SyntaxKind.ExportKeyword
|
|
633
|
+
) ?? false : false;
|
|
634
|
+
if (ts3.isFunctionDeclaration(stmt) && stmt.name) {
|
|
635
|
+
let fact;
|
|
636
|
+
stmt.forEachChild(function visit(node) {
|
|
637
|
+
if (!fact && ts3.isReturnStatement(node) && node.expression)
|
|
638
|
+
fact = findConnectInExpression(node.expression);
|
|
639
|
+
if (!fact) ts3.forEachChild(node, visit);
|
|
640
|
+
});
|
|
641
|
+
if (fact && exported)
|
|
642
|
+
out.push({
|
|
643
|
+
...fact,
|
|
644
|
+
exportedName: stmt.name.text,
|
|
645
|
+
sourceFile: normalizePath(filePath),
|
|
646
|
+
sourceLine: lineOf4(sf, stmt)
|
|
647
|
+
});
|
|
648
|
+
}
|
|
649
|
+
if (ts3.isVariableStatement(stmt))
|
|
650
|
+
for (const decl of stmt.declarationList.declarations) {
|
|
651
|
+
if (!ts3.isIdentifier(decl.name) || !decl.initializer) continue;
|
|
652
|
+
const fact = findConnectInExpression(decl.initializer);
|
|
653
|
+
if (fact && exported)
|
|
654
|
+
out.push({
|
|
655
|
+
...fact,
|
|
656
|
+
exportedName: decl.name.text,
|
|
657
|
+
sourceFile: normalizePath(filePath),
|
|
658
|
+
sourceLine: lineOf4(sourceFileAst, decl)
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
return out;
|
|
663
|
+
}
|
|
664
|
+
async function parseServiceBindings(repoPath, filePath) {
|
|
665
|
+
const sf = await readSource(path8.join(repoPath, filePath));
|
|
666
|
+
if (!sf) return [];
|
|
667
|
+
const sourceFileAst = sf;
|
|
668
|
+
const out = [];
|
|
669
|
+
const imports = await importsFor(repoPath, filePath, sf);
|
|
670
|
+
const helperCache = /* @__PURE__ */ new Map();
|
|
671
|
+
async function importedHelper(localName) {
|
|
672
|
+
const imp = imports.find((i) => i.localName === localName && i.sourceFile);
|
|
673
|
+
if (!imp?.sourceFile) return void 0;
|
|
674
|
+
if (!helperCache.has(imp.sourceFile))
|
|
675
|
+
helperCache.set(
|
|
676
|
+
imp.sourceFile,
|
|
677
|
+
await helperBindings(repoPath, imp.sourceFile)
|
|
678
|
+
);
|
|
679
|
+
const helper = helperCache.get(imp.sourceFile)?.find((h) => h.exportedName === imp.exportedName);
|
|
680
|
+
return helper ? { imp, helper } : void 0;
|
|
681
|
+
}
|
|
682
|
+
async function recordVariable(decl) {
|
|
683
|
+
if (!ts3.isIdentifier(decl.name) || !decl.initializer) return;
|
|
684
|
+
const call = unwrapCall(decl.initializer);
|
|
685
|
+
if (!call) return;
|
|
686
|
+
const direct = connectFactFromCall(call);
|
|
687
|
+
if (direct)
|
|
688
|
+
out.push({
|
|
689
|
+
variableName: decl.name.text,
|
|
690
|
+
...direct,
|
|
691
|
+
sourceFile: normalizePath(filePath),
|
|
692
|
+
sourceLine: lineOf4(sourceFileAst, decl)
|
|
693
|
+
});
|
|
694
|
+
else if (ts3.isIdentifier(call.expression)) {
|
|
695
|
+
const resolved = await importedHelper(call.expression.text);
|
|
696
|
+
if (resolved)
|
|
697
|
+
out.push({
|
|
698
|
+
variableName: decl.name.text,
|
|
699
|
+
alias: resolved.helper.alias,
|
|
700
|
+
destinationExpr: resolved.helper.destinationExpr,
|
|
701
|
+
servicePathExpr: resolved.helper.servicePathExpr,
|
|
702
|
+
isDynamic: resolved.helper.isDynamic,
|
|
703
|
+
placeholders: resolved.helper.placeholders,
|
|
704
|
+
sourceFile: normalizePath(filePath),
|
|
705
|
+
sourceLine: lineOf4(sourceFileAst, decl),
|
|
706
|
+
helperChain: [
|
|
707
|
+
{
|
|
708
|
+
callerVariable: decl.name.text,
|
|
709
|
+
importedHelper: call.expression.text,
|
|
710
|
+
importSource: resolved.imp.sourceFile,
|
|
711
|
+
exportedSymbol: resolved.imp.exportedName,
|
|
712
|
+
helperSourceFile: resolved.helper.sourceFile,
|
|
713
|
+
helperSourceLine: resolved.helper.sourceLine
|
|
714
|
+
}
|
|
715
|
+
]
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
const declarations = [];
|
|
720
|
+
function collectDeclarations(node) {
|
|
721
|
+
if (ts3.isVariableDeclaration(node)) declarations.push(node);
|
|
722
|
+
ts3.forEachChild(node, collectDeclarations);
|
|
723
|
+
}
|
|
724
|
+
collectDeclarations(sourceFileAst);
|
|
725
|
+
for (const decl of declarations) await recordVariable(decl);
|
|
726
|
+
return out;
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
// src/linker/dynamic-edge-resolver.ts
|
|
730
|
+
function applyVariables(template, vars) {
|
|
731
|
+
if (!template) return void 0;
|
|
732
|
+
return template.replace(
|
|
733
|
+
/\$\{\s*(\w+)\s*\}/g,
|
|
734
|
+
(_m, key) => vars[key] ?? `\${${key}}`
|
|
735
|
+
);
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
// src/linker/service-resolver.ts
|
|
739
|
+
function rows(db, operationPath, workspaceId) {
|
|
740
|
+
return db.prepare(
|
|
741
|
+
`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,0 score,'' reasons
|
|
742
|
+
FROM cds_operations o JOIN cds_services s ON s.id=o.service_id JOIN repositories r ON r.id=s.repo_id
|
|
743
|
+
WHERE (? IS NULL OR r.workspace_id=?) AND (o.operation_path=? OR o.operation_name=?) ORDER BY r.name,s.service_path,o.operation_name`
|
|
744
|
+
).all(
|
|
745
|
+
workspaceId,
|
|
746
|
+
workspaceId,
|
|
747
|
+
operationPath,
|
|
748
|
+
operationPath.replace(/^\//, "")
|
|
749
|
+
);
|
|
750
|
+
}
|
|
751
|
+
function resolveOperation(db, signals, workspaceId) {
|
|
752
|
+
if (!signals.operationPath)
|
|
753
|
+
return {
|
|
754
|
+
status: "unresolved",
|
|
755
|
+
candidates: [],
|
|
756
|
+
reasons: ["missing_operation_path"]
|
|
757
|
+
};
|
|
758
|
+
const candidates = rows(db, signals.operationPath, workspaceId).map((c) => ({
|
|
759
|
+
...c,
|
|
760
|
+
score: 0.2,
|
|
761
|
+
reasons: ["operation_path_match"]
|
|
762
|
+
}));
|
|
763
|
+
if (candidates.length === 0)
|
|
764
|
+
return {
|
|
765
|
+
status: "unresolved",
|
|
766
|
+
candidates: [],
|
|
767
|
+
reasons: ["no_operation_candidates"]
|
|
768
|
+
};
|
|
769
|
+
const hasStrongSignal = Boolean(
|
|
770
|
+
signals.servicePath || signals.alias || signals.destination || signals.hasExplicitOverride
|
|
771
|
+
);
|
|
772
|
+
for (const c of candidates) {
|
|
773
|
+
if (signals.servicePath && c.servicePath === signals.servicePath) {
|
|
774
|
+
c.score += 0.75;
|
|
775
|
+
c.reasons.push("exact_service_path");
|
|
776
|
+
}
|
|
777
|
+
if (signals.servicePath && c.servicePath !== signals.servicePath) {
|
|
778
|
+
c.score -= 0.1;
|
|
779
|
+
c.reasons.push("service_path_mismatch");
|
|
780
|
+
}
|
|
781
|
+
if (signals.hasExplicitOverride) {
|
|
782
|
+
c.score += 0.2;
|
|
783
|
+
c.reasons.push("explicit_dynamic_override");
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
candidates.sort(
|
|
787
|
+
(a, b) => b.score - a.score || a.repoName.localeCompare(b.repoName)
|
|
788
|
+
);
|
|
789
|
+
const best = candidates[0];
|
|
790
|
+
const second = candidates[1];
|
|
791
|
+
if (signals.isDynamic && !signals.hasExplicitOverride && !signals.servicePath)
|
|
792
|
+
return {
|
|
793
|
+
status: "dynamic",
|
|
794
|
+
candidates,
|
|
795
|
+
reasons: ["dynamic_target_without_override"]
|
|
796
|
+
};
|
|
797
|
+
if (!hasStrongSignal)
|
|
798
|
+
return {
|
|
799
|
+
status: candidates.length > 1 ? "ambiguous" : "unresolved",
|
|
800
|
+
candidates,
|
|
801
|
+
reasons: ["operation_path_only_has_no_strong_target_signal"]
|
|
802
|
+
};
|
|
803
|
+
if (best && best.score >= 0.9 && (!second || best.score - second.score >= 0.25))
|
|
804
|
+
return {
|
|
805
|
+
status: "resolved",
|
|
806
|
+
target: best,
|
|
807
|
+
candidates,
|
|
808
|
+
reasons: best.reasons
|
|
809
|
+
};
|
|
810
|
+
return {
|
|
811
|
+
status: candidates.length > 1 ? "ambiguous" : "unresolved",
|
|
812
|
+
candidates,
|
|
813
|
+
reasons: ["candidate_score_below_resolution_threshold"]
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
// src/linker/helper-package-linker.ts
|
|
818
|
+
function linkHelperPackages(db, workspaceId) {
|
|
819
|
+
const repos = db.prepare(
|
|
820
|
+
"SELECT id,name,dependencies_json FROM repositories WHERE workspace_id=?"
|
|
821
|
+
).all(workspaceId);
|
|
822
|
+
let count = 0;
|
|
823
|
+
for (const repo of repos) {
|
|
824
|
+
const deps = JSON.parse(repo.dependencies_json);
|
|
825
|
+
for (const dep of Object.keys(deps)) {
|
|
826
|
+
const helper = repos.find((r) => r.name === dep || dep.endsWith(r.name));
|
|
827
|
+
if (helper) {
|
|
828
|
+
db.prepare(
|
|
829
|
+
"INSERT INTO graph_edges(workspace_id,edge_type,from_kind,from_id,to_kind,to_id,confidence,evidence_json,is_dynamic) VALUES(?,?,?,?,?,?,?,?,?)"
|
|
830
|
+
).run(
|
|
831
|
+
workspaceId,
|
|
832
|
+
"REPO_IMPORTS_HELPER_PACKAGE",
|
|
833
|
+
"repo",
|
|
834
|
+
String(repo.id),
|
|
835
|
+
"repo",
|
|
836
|
+
String(helper.id),
|
|
837
|
+
0.9,
|
|
838
|
+
JSON.stringify({ dependency: dep }),
|
|
839
|
+
0
|
|
840
|
+
);
|
|
841
|
+
count += 1;
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
return count;
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
// src/linker/cross-repo-linker.ts
|
|
849
|
+
function linkWorkspace(db, workspaceId, vars = {}) {
|
|
850
|
+
db.prepare("DELETE FROM graph_edges WHERE workspace_id=?").run(workspaceId);
|
|
851
|
+
let edges = linkHelperPackages(db, workspaceId);
|
|
852
|
+
let unresolved = 0;
|
|
853
|
+
const calls = db.prepare(
|
|
854
|
+
`SELECT c.*,r.name repoName,b.alias,b.destination_expr destinationExpr,b.service_path_expr servicePathExpr,b.is_dynamic isDynamic,b.placeholders_json placeholdersJson,b.helper_chain_json helperChainJson,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=?`
|
|
855
|
+
).all(workspaceId);
|
|
856
|
+
for (const call of calls) {
|
|
857
|
+
const callType = String(call.call_type);
|
|
858
|
+
const op = applyVariables(String(call.operation_path_expr ?? ""), vars);
|
|
859
|
+
const servicePath = applyVariables(
|
|
860
|
+
call.servicePathExpr ?? call.requireServicePath,
|
|
861
|
+
vars
|
|
862
|
+
);
|
|
863
|
+
const destination = call.destinationExpr ?? call.requireDestination;
|
|
864
|
+
const isDynamic = Boolean(Number(call.isDynamic ?? 0));
|
|
865
|
+
const resolution = callType.startsWith("remote") ? resolveOperation(
|
|
866
|
+
db,
|
|
867
|
+
{
|
|
868
|
+
servicePath,
|
|
869
|
+
operationPath: op,
|
|
870
|
+
alias: call.alias,
|
|
871
|
+
destination,
|
|
872
|
+
isDynamic,
|
|
873
|
+
hasExplicitOverride: Object.keys(vars).length > 0
|
|
874
|
+
},
|
|
875
|
+
workspaceId
|
|
876
|
+
) : { status: "unresolved", candidates: [], reasons: [] };
|
|
877
|
+
const target = resolution.target;
|
|
878
|
+
const evidence = {
|
|
879
|
+
sourceFile: call.source_file,
|
|
880
|
+
sourceLine: call.source_line,
|
|
881
|
+
file: call.source_file,
|
|
882
|
+
line: call.source_line,
|
|
883
|
+
repo: call.repoName,
|
|
884
|
+
serviceAlias: call.alias,
|
|
885
|
+
destination,
|
|
886
|
+
servicePath,
|
|
887
|
+
operationPath: op,
|
|
888
|
+
targetRepo: target?.repoName,
|
|
889
|
+
targetOperation: target?.operationName,
|
|
890
|
+
helperChain: call.helperChainJson ? JSON.parse(String(call.helperChainJson)) : void 0,
|
|
891
|
+
candidates: resolution.candidates,
|
|
892
|
+
candidateCount: resolution.candidates.length,
|
|
893
|
+
resolutionStatus: resolution.status,
|
|
894
|
+
resolutionReasons: resolution.reasons
|
|
895
|
+
};
|
|
896
|
+
if (target) {
|
|
897
|
+
db.prepare(
|
|
898
|
+
"INSERT INTO graph_edges(workspace_id,edge_type,from_kind,from_id,to_kind,to_id,confidence,evidence_json,is_dynamic) VALUES(?,?,?,?,?,?,?,?,?)"
|
|
899
|
+
).run(
|
|
900
|
+
workspaceId,
|
|
901
|
+
"REMOTE_CALL_RESOLVES_TO_OPERATION",
|
|
902
|
+
"call",
|
|
903
|
+
String(call.id),
|
|
904
|
+
"operation",
|
|
905
|
+
String(target.operationId),
|
|
906
|
+
target.score,
|
|
907
|
+
JSON.stringify(evidence),
|
|
908
|
+
isDynamic ? 1 : 0
|
|
909
|
+
);
|
|
910
|
+
edges += 1;
|
|
911
|
+
} else {
|
|
912
|
+
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" : resolution.status === "dynamic" ? "DYNAMIC_EDGE_CANDIDATE" : "UNRESOLVED_EDGE";
|
|
913
|
+
db.prepare(
|
|
914
|
+
"INSERT INTO graph_edges(workspace_id,edge_type,from_kind,from_id,to_kind,to_id,confidence,evidence_json,is_dynamic,unresolved_reason) VALUES(?,?,?,?,?,?,?,?,?,?)"
|
|
915
|
+
).run(
|
|
916
|
+
workspaceId,
|
|
917
|
+
edgeType,
|
|
918
|
+
"call",
|
|
919
|
+
String(call.id),
|
|
920
|
+
callType.startsWith("async_") ? "event" : "external",
|
|
921
|
+
String(call.event_name_expr ?? call.query_entity ?? op ?? call.id),
|
|
922
|
+
Number(call.confidence ?? 0.2),
|
|
923
|
+
JSON.stringify(evidence),
|
|
924
|
+
isDynamic || resolution.status === "dynamic" ? 1 : 0,
|
|
925
|
+
String(
|
|
926
|
+
call.unresolved_reason ?? (resolution.status === "ambiguous" ? "Ambiguous operation candidates require a strong service signal" : resolution.status === "dynamic" ? "Dynamic target requires runtime variable overrides" : "No indexed target operation matched")
|
|
927
|
+
)
|
|
928
|
+
);
|
|
929
|
+
edges += 1;
|
|
930
|
+
unresolved += edgeType === "UNRESOLVED_EDGE" ? 1 : 0;
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
return { edgeCount: edges, unresolvedCount: unresolved };
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
// src/trace/trace-engine.ts
|
|
937
|
+
function normalizeOperation(value) {
|
|
938
|
+
if (!value) return void 0;
|
|
939
|
+
return value.startsWith("/") ? value.slice(1) : value;
|
|
940
|
+
}
|
|
941
|
+
function positiveDepth(value) {
|
|
942
|
+
return Number.isFinite(value) && value > 0 ? Math.floor(value) : 25;
|
|
943
|
+
}
|
|
944
|
+
function sourceFilesForStart(db, repoId, start) {
|
|
945
|
+
const handler = start.handler;
|
|
946
|
+
const operation = normalizeOperation(start.operation ?? start.operationPath);
|
|
947
|
+
if (!handler && !operation) return void 0;
|
|
948
|
+
const rows2 = db.prepare(
|
|
949
|
+
`SELECT DISTINCT hc.source_file sourceFile
|
|
950
|
+
FROM handler_classes hc LEFT JOIN handler_methods hm ON hm.handler_class_id=hc.id
|
|
951
|
+
WHERE (? IS NULL OR hc.repo_id=?) AND (? IS NULL OR hc.class_name=? OR hm.method_name=?)
|
|
952
|
+
AND (? IS NULL OR hm.decorator_value=? OR hm.method_name=?)`
|
|
953
|
+
).all(
|
|
954
|
+
repoId,
|
|
955
|
+
repoId,
|
|
956
|
+
handler,
|
|
957
|
+
handler,
|
|
958
|
+
handler,
|
|
959
|
+
operation,
|
|
960
|
+
operation,
|
|
961
|
+
operation
|
|
962
|
+
);
|
|
963
|
+
if (rows2.length === 0) return void 0;
|
|
964
|
+
return new Set(rows2.map((row) => row.sourceFile).filter(Boolean));
|
|
965
|
+
}
|
|
966
|
+
function startScope(db, start) {
|
|
967
|
+
const repo = start.repo ? db.prepare(
|
|
968
|
+
"SELECT id,name FROM repositories WHERE name=? OR package_name=?"
|
|
969
|
+
).get(start.repo, start.repo) : void 0;
|
|
970
|
+
if (start.repo && !repo) return { repo, selectorMatched: false };
|
|
971
|
+
const sourceFiles = sourceFilesForStart(db, repo?.id, start);
|
|
972
|
+
const hasSelector = Boolean(
|
|
973
|
+
start.handler ?? start.operation ?? start.operationPath
|
|
974
|
+
);
|
|
975
|
+
return {
|
|
976
|
+
repo,
|
|
977
|
+
sourceFiles,
|
|
978
|
+
selectorMatched: !hasSelector || sourceFiles !== void 0
|
|
979
|
+
};
|
|
980
|
+
}
|
|
981
|
+
function handlerFilesForOperation(db, operationId) {
|
|
982
|
+
const op = db.prepare(
|
|
983
|
+
`SELECT o.operation_name operationName,o.operation_path operationPath,s.repo_id repoId
|
|
984
|
+
FROM cds_operations o JOIN cds_services s ON s.id=o.service_id WHERE o.id=?`
|
|
985
|
+
).get(operationId);
|
|
986
|
+
if (!op) return /* @__PURE__ */ new Set();
|
|
987
|
+
const operation = normalizeOperation(op.operationPath ?? op.operationName);
|
|
988
|
+
const rows2 = db.prepare(
|
|
989
|
+
`SELECT DISTINCT hc.source_file sourceFile FROM handler_classes hc
|
|
990
|
+
JOIN handler_methods hm ON hm.handler_class_id=hc.id
|
|
991
|
+
WHERE hc.repo_id=? AND (hm.decorator_value=? OR hm.method_name=? OR hm.decorator_value=?)`
|
|
992
|
+
).all(op.repoId, operation, operation, op.operationName);
|
|
993
|
+
return new Set(rows2.map((row) => row.sourceFile).filter(Boolean));
|
|
994
|
+
}
|
|
995
|
+
function includeCall(type, options) {
|
|
996
|
+
if (!options.includeDb && type === "local_db_query") return false;
|
|
997
|
+
if (!options.includeExternal && type === "external_http") return false;
|
|
998
|
+
if (!options.includeAsync && type.startsWith("async_")) return false;
|
|
999
|
+
return true;
|
|
1000
|
+
}
|
|
1001
|
+
function graphForCalls(db, callIds) {
|
|
1002
|
+
const map = /* @__PURE__ */ new Map();
|
|
1003
|
+
if (callIds.length === 0) return map;
|
|
1004
|
+
const rows2 = db.prepare(
|
|
1005
|
+
`SELECT * FROM graph_edges WHERE from_kind='call' AND from_id IN (${callIds.map(() => "?").join(",")}) ORDER BY id`
|
|
1006
|
+
).all(...callIds);
|
|
1007
|
+
for (const row of rows2) {
|
|
1008
|
+
const id = Number(row.from_id);
|
|
1009
|
+
map.set(id, [...map.get(id) ?? [], row]);
|
|
1010
|
+
}
|
|
1011
|
+
return map;
|
|
1012
|
+
}
|
|
1013
|
+
function candidatesFromEvidence(evidence) {
|
|
1014
|
+
return Array.isArray(evidence.candidates) ? evidence.candidates.filter(
|
|
1015
|
+
(candidate) => typeof candidate === "object" && candidate !== null
|
|
1016
|
+
) : [];
|
|
1017
|
+
}
|
|
1018
|
+
function evidenceWithRuntimeVariables(evidence, vars) {
|
|
1019
|
+
if (!vars || Object.keys(vars).length === 0) return evidence;
|
|
1020
|
+
const servicePath = typeof evidence.servicePath === "string" ? applyVariables(evidence.servicePath, vars) : void 0;
|
|
1021
|
+
const operationPath = typeof evidence.operationPath === "string" ? applyVariables(evidence.operationPath, vars) : void 0;
|
|
1022
|
+
const candidates = candidatesFromEvidence(evidence);
|
|
1023
|
+
const matched = servicePath ? candidates.find((candidate) => candidate.servicePath === servicePath) : void 0;
|
|
1024
|
+
return {
|
|
1025
|
+
...evidence,
|
|
1026
|
+
servicePath: servicePath ?? evidence.servicePath,
|
|
1027
|
+
operationPath: operationPath ?? evidence.operationPath,
|
|
1028
|
+
runtimeVariablesApplied: true,
|
|
1029
|
+
runtimeResolvedCandidate: matched ? {
|
|
1030
|
+
repoName: matched.repoName,
|
|
1031
|
+
servicePath: matched.servicePath,
|
|
1032
|
+
operationPath: matched.operationPath,
|
|
1033
|
+
operationName: matched.operationName,
|
|
1034
|
+
score: matched.score
|
|
1035
|
+
} : void 0
|
|
1036
|
+
};
|
|
1037
|
+
}
|
|
1038
|
+
function edgeTarget(row, evidence) {
|
|
1039
|
+
const runtimeCandidate = evidence.runtimeResolvedCandidate;
|
|
1040
|
+
if (runtimeCandidate?.servicePath && runtimeCandidate.operationPath)
|
|
1041
|
+
return `${runtimeCandidate.servicePath}${runtimeCandidate.operationPath}`;
|
|
1042
|
+
const servicePath = typeof evidence.servicePath === "string" ? evidence.servicePath : void 0;
|
|
1043
|
+
const operationPath = typeof evidence.operationPath === "string" ? evidence.operationPath : void 0;
|
|
1044
|
+
const targetOperation = typeof evidence.targetOperation === "string" ? evidence.targetOperation : void 0;
|
|
1045
|
+
const targetRepo = typeof evidence.targetRepo === "string" ? evidence.targetRepo : "";
|
|
1046
|
+
return servicePath && operationPath ? `${servicePath}${operationPath}` : targetOperation ? `${targetRepo}:${targetOperation}` : row.to_id;
|
|
1047
|
+
}
|
|
1048
|
+
function trace(db, start, options) {
|
|
1049
|
+
const scope = startScope(db, start);
|
|
1050
|
+
const diagnostics = db.prepare(
|
|
1051
|
+
"SELECT severity,code,message,source_file sourceFile,source_line sourceLine FROM diagnostics WHERE (? IS NULL OR repo_id=?)"
|
|
1052
|
+
).all(scope.repo?.id, scope.repo?.id);
|
|
1053
|
+
if (!scope.selectorMatched)
|
|
1054
|
+
diagnostics.unshift({
|
|
1055
|
+
severity: "warning",
|
|
1056
|
+
code: "trace_start_not_found",
|
|
1057
|
+
message: "No handler source matched the requested trace start selector"
|
|
1058
|
+
});
|
|
1059
|
+
const maxDepth = positiveDepth(options.depth);
|
|
1060
|
+
const edges = [];
|
|
1061
|
+
const nodes = /* @__PURE__ */ new Map();
|
|
1062
|
+
const queue = scope.selectorMatched ? [{ repoId: scope.repo?.id, files: scope.sourceFiles, depth: 1 }] : [];
|
|
1063
|
+
const seenScopes = /* @__PURE__ */ new Set();
|
|
1064
|
+
const seenEdges = /* @__PURE__ */ new Set();
|
|
1065
|
+
while (queue.length > 0) {
|
|
1066
|
+
const current = queue.shift();
|
|
1067
|
+
if (!current || current.depth > maxDepth) continue;
|
|
1068
|
+
const key = `${current.repoId ?? "*"}:${[...current.files ?? /* @__PURE__ */ new Set(["*"])].sort().join(",")}`;
|
|
1069
|
+
if (seenScopes.has(key)) continue;
|
|
1070
|
+
seenScopes.add(key);
|
|
1071
|
+
const calls = db.prepare(
|
|
1072
|
+
`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`
|
|
1073
|
+
).all(current.repoId, current.repoId);
|
|
1074
|
+
const filtered = calls.filter(
|
|
1075
|
+
(c) => (!current.files || current.files.has(String(c.source_file))) && includeCall(String(c.call_type), options)
|
|
1076
|
+
);
|
|
1077
|
+
const graph = graphForCalls(
|
|
1078
|
+
db,
|
|
1079
|
+
filtered.map((c) => Number(c.id))
|
|
1080
|
+
);
|
|
1081
|
+
for (const call of filtered) {
|
|
1082
|
+
const callNode = `call:${call.id}`;
|
|
1083
|
+
nodes.set(callNode, {
|
|
1084
|
+
id: callNode,
|
|
1085
|
+
kind: "outbound_call",
|
|
1086
|
+
repo: call.repoName,
|
|
1087
|
+
file: call.source_file,
|
|
1088
|
+
line: call.source_line,
|
|
1089
|
+
callType: call.call_type
|
|
1090
|
+
});
|
|
1091
|
+
const graphRows = graph.get(Number(call.id)) ?? [];
|
|
1092
|
+
for (const row of graphRows) {
|
|
1093
|
+
if (seenEdges.has(Number(row.id))) continue;
|
|
1094
|
+
seenEdges.add(Number(row.id));
|
|
1095
|
+
const rawEvidence = JSON.parse(
|
|
1096
|
+
String(row.evidence_json || "{}")
|
|
1097
|
+
);
|
|
1098
|
+
const evidence = evidenceWithRuntimeVariables(
|
|
1099
|
+
rawEvidence,
|
|
1100
|
+
options.vars
|
|
1101
|
+
);
|
|
1102
|
+
const targetNode = `${row.to_kind}:${row.to_id}`;
|
|
1103
|
+
nodes.set(targetNode, {
|
|
1104
|
+
id: targetNode,
|
|
1105
|
+
kind: row.to_kind,
|
|
1106
|
+
label: row.to_id,
|
|
1107
|
+
...evidence
|
|
1108
|
+
});
|
|
1109
|
+
const to = edgeTarget(row, evidence);
|
|
1110
|
+
edges.push({
|
|
1111
|
+
step: current.depth,
|
|
1112
|
+
type: String(call.call_type),
|
|
1113
|
+
from: `${call.repoName}:${call.source_file}`,
|
|
1114
|
+
to,
|
|
1115
|
+
evidence,
|
|
1116
|
+
confidence: Number(row.confidence ?? call.confidence),
|
|
1117
|
+
unresolvedReason: row.unresolved_reason
|
|
1118
|
+
});
|
|
1119
|
+
if (row.to_kind === "operation" && current.depth < maxDepth) {
|
|
1120
|
+
const files = handlerFilesForOperation(db, row.to_id);
|
|
1121
|
+
if (files.size > 0) {
|
|
1122
|
+
const targetRepoId = db.prepare(
|
|
1123
|
+
"SELECT s.repo_id repoId FROM cds_operations o JOIN cds_services s ON s.id=o.service_id WHERE o.id=?"
|
|
1124
|
+
).get(row.to_id)?.repoId;
|
|
1125
|
+
const nextKey = `${targetRepoId ?? "*"}:${[...files].sort().join(",")}`;
|
|
1126
|
+
if (seenScopes.has(nextKey))
|
|
1127
|
+
edges.push({
|
|
1128
|
+
step: current.depth + 1,
|
|
1129
|
+
type: "cycle",
|
|
1130
|
+
from: to,
|
|
1131
|
+
to: nextKey,
|
|
1132
|
+
evidence: { ...evidence, cycle: true },
|
|
1133
|
+
confidence: 1,
|
|
1134
|
+
unresolvedReason: "Cycle detected; downstream scope already visited"
|
|
1135
|
+
});
|
|
1136
|
+
else
|
|
1137
|
+
queue.push({
|
|
1138
|
+
repoId: targetRepoId,
|
|
1139
|
+
files,
|
|
1140
|
+
depth: current.depth + 1
|
|
1141
|
+
});
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
return { start, nodes: [...nodes.values()], edges, diagnostics };
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
export {
|
|
1151
|
+
normalizePath,
|
|
1152
|
+
stripQuotes,
|
|
1153
|
+
discoverRepositories,
|
|
1154
|
+
parsePackageJson,
|
|
1155
|
+
parseCdsFile,
|
|
1156
|
+
parseDecorators,
|
|
1157
|
+
parseHandlerRegistrations,
|
|
1158
|
+
redactText,
|
|
1159
|
+
redactValue,
|
|
1160
|
+
parseOutboundCalls,
|
|
1161
|
+
parseServiceBindings,
|
|
1162
|
+
applyVariables,
|
|
1163
|
+
linkWorkspace,
|
|
1164
|
+
trace
|
|
1165
|
+
};
|
|
1166
|
+
//# sourceMappingURL=chunk-SIKIGT42.js.map
|