sfcc-perf 0.1.0 → 0.1.1

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.
@@ -0,0 +1,402 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_IMPORT_BYTES = void 0;
4
+ exports.checkImportFile = checkImportFile;
5
+ exports.parseImportedModel = parseImportedModel;
6
+ const defaults_1 = require("../engine/defaults");
7
+ const nodeFactory_1 = require("../engine/nodeFactory");
8
+ const validateGraph_1 = require("../engine/validateGraph");
9
+ const analyzeEndpoint_1 = require("../engine/analyzeEndpoint");
10
+ exports.MAX_IMPORT_BYTES = 5 * 1024 * 1024;
11
+ const ACCEPTED_EXTENSIONS = /\.(md|markdown|json)$/i;
12
+ const MODES = new Set(["storefront", "api", "job", "integration"]);
13
+ const KNOWN_TYPES = new Set(Object.keys(defaults_1.OPERATION_LABELS));
14
+ const MAX_NODES = 2000;
15
+ const MAX_EDGES = MAX_NODES * 4;
16
+ const MAX_LATENCY_MS = 600000;
17
+ const PROFILE_KEYS = ["min", "avg", "p50", "p95", "p99", "max"];
18
+ /** Percentiles must not decrease along this chain; avg must lie between min and max (same rule as the npm package's latencyOverrides). */
19
+ const PERCENTILE_ORDER = ["min", "p50", "p95", "p99", "max"];
20
+ const NPX_HINT = "Generate one with `npx sfcc-perf <route> --out report.md`.";
21
+ const fail = (problems) => ({ ok: false, error: problems[0], problems });
22
+ /** Checks a picked/dropped file before reading it. Returns problems (empty = fine). */
23
+ function checkImportFile(file) {
24
+ const problems = [];
25
+ if (!ACCEPTED_EXTENSIONS.test(file.name))
26
+ problems.push(`"${file.name}" isn't a .md report or .json export.`);
27
+ if (file.size === 0)
28
+ problems.push(`"${file.name}" is empty.`);
29
+ if (file.size > exports.MAX_IMPORT_BYTES)
30
+ problems.push(`"${file.name}" is ${(file.size / 1024 / 1024).toFixed(1)} MB; the limit is 5 MB.`);
31
+ return problems;
32
+ }
33
+ function extractJson(text) {
34
+ const trimmed = text.replace(/^/, "").trim();
35
+ if (trimmed.startsWith("{"))
36
+ return { json: trimmed, source: "json" };
37
+ const marked = /<!--\s*sfcc-perf-model:begin\s*-->\s*```(?:json)?\s*([\s\S]*?)```\s*<!--\s*sfcc-perf-model:end\s*-->/.exec(text);
38
+ if (marked)
39
+ return { json: marked[1], source: "markdown" };
40
+ return null;
41
+ }
42
+ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
43
+ const finiteIn = (v, min, max) => typeof v === "number" && Number.isFinite(v) && v >= min && v <= max;
44
+ const oneOf = (v, values) => typeof v === "string" && values.includes(v);
45
+ const optional = (v, ok) => v === undefined || ok(v);
46
+ /** Ordering problems of a (possibly partial) latency profile, for the fields it has. */
47
+ function orderingProblems(p) {
48
+ const out = [];
49
+ const present = PERCENTILE_ORDER.filter((k) => typeof p[k] === "number");
50
+ for (let i = 1; i < present.length; i++) {
51
+ const a = p[present[i - 1]];
52
+ const b = p[present[i]];
53
+ if (a > b)
54
+ out.push(`${present[i - 1]} (${a}) is greater than ${present[i]} (${b})`);
55
+ }
56
+ if (typeof p.avg === "number" && ((typeof p.min === "number" && p.avg < p.min) || (typeof p.max === "number" && p.avg > p.max)))
57
+ out.push(`avg (${p.avg}) is outside min-max`);
58
+ return out;
59
+ }
60
+ function validateNodes(nodes, problems) {
61
+ const ids = new Set();
62
+ nodes.forEach((n, i) => {
63
+ const where = `Operation #${i + 1}`;
64
+ if (!isObj(n) || typeof n.id !== "string" || !n.id) {
65
+ problems.push(`${where} has no id.`);
66
+ return;
67
+ }
68
+ if (ids.has(n.id))
69
+ problems.push(`Operation id "${n.id}" appears twice.`);
70
+ ids.add(n.id);
71
+ const d = n.data;
72
+ if (!isObj(d)) {
73
+ problems.push(`${where} ("${n.id}") has no data.`);
74
+ return;
75
+ }
76
+ const name = typeof d.name === "string" ? d.name : n.id;
77
+ const bad = (msg) => problems.push(`"${name}": ${msg}`);
78
+ if (typeof d.type !== "string" || !KNOWN_TYPES.has(d.type))
79
+ problems.push(`"${name}" has an unknown operation type ${JSON.stringify(d.type)}.`);
80
+ if (d.profileId !== undefined && (typeof d.profileId !== "string" || !KNOWN_TYPES.has(d.profileId)))
81
+ bad(`unknown profileId ${JSON.stringify(d.profileId)}.`);
82
+ if (typeof d.name !== "string")
83
+ problems.push(`${where} ("${n.id}") has no name.`);
84
+ if (!isObj(d.overrides))
85
+ problems.push(`"${name}" has no latency overrides object.`);
86
+ else
87
+ for (const [k, v] of Object.entries(d.overrides)) {
88
+ if (!PROFILE_KEYS.includes(k))
89
+ bad(`unknown latency field "${k}" (expected ${PROFILE_KEYS.join(", ")}).`);
90
+ else if (!finiteIn(v, 0, MAX_LATENCY_MS))
91
+ bad(`latency ${k} must be a number between 0 and ${MAX_LATENCY_MS} ms (got ${JSON.stringify(v)}).`);
92
+ }
93
+ if (d.executionProbability !== undefined && !finiteIn(d.executionProbability, 0, 1))
94
+ bad(`executionProbability must be between 0 and 1 (got ${JSON.stringify(d.executionProbability)}).`);
95
+ if (d.operationCount !== undefined && !(finiteIn(d.operationCount, 1, 100000) && Number.isInteger(d.operationCount)))
96
+ bad(`operationCount must be a whole number ≥ 1 (got ${JSON.stringify(d.operationCount)}).`);
97
+ if (d.hitRate !== undefined && !finiteIn(d.hitRate, 0, 1))
98
+ bad("hitRate must be between 0 and 1.");
99
+ if (!optional(d.executionMode, (v) => oneOf(v, ["blocking", "async"])))
100
+ bad(`executionMode must be "blocking" or "async".`);
101
+ if (!optional(d.parallelMode, (v) => oneOf(v, ["sequential", "parallel"])))
102
+ bad(`parallelMode must be "sequential" or "parallel".`);
103
+ if (!optional(d.branchMode, (v) => oneOf(v, ["exclusive", "independent"])))
104
+ bad(`branchMode must be "exclusive" or "independent".`);
105
+ if (!optional(d.timeoutMs, (v) => finiteIn(v, 1, MAX_LATENCY_MS)))
106
+ bad(`timeoutMs must be between 1 and ${MAX_LATENCY_MS}.`);
107
+ if (!optional(d.failureProbability, (v) => finiteIn(v, 0, 1)))
108
+ bad("failureProbability must be between 0 and 1.");
109
+ if (d.retry !== undefined && !(isObj(d.retry) && finiteIn(d.retry.count, 0, 10) && Number.isInteger(d.retry.count) && finiteIn(d.retry.probability, 0, 1)))
110
+ bad("retry must be { count: 0-10, probability: 0-1 }.");
111
+ for (const k of ["expansions", "responseSizeKb", "recordCount", "batchSizeRecords", "payloadSizeKb"]) {
112
+ if (!optional(d[k], (v) => finiteIn(v, 0, 1e9)))
113
+ bad(`${k} must be a number ≥ 0.`);
114
+ }
115
+ if (d.branches !== undefined) {
116
+ if (!Array.isArray(d.branches) || d.branches.length > 50)
117
+ bad("branches must be a list (at most 50).");
118
+ else
119
+ d.branches.forEach((b, j) => {
120
+ if (!isObj(b) || typeof b.id !== "string" || !finiteIn(b.probability, 0, 1) || !optional(b.label, (v) => typeof v === "string"))
121
+ bad(`branch #${j + 1} must have an id and a probability between 0 and 1.`);
122
+ });
123
+ }
124
+ if (d.hooks !== undefined && !(isObj(d.hooks) && Object.values(d.hooks).every((v) => typeof v === "boolean")))
125
+ bad("hooks must be an object of true/false flags.");
126
+ if (d.jobConfig !== undefined) {
127
+ const j = d.jobConfig;
128
+ const ok = isObj(j) &&
129
+ finiteIn(j.totalRecords, 0, 1e12) &&
130
+ finiteIn(j.chunkSize, 1, 1e9) &&
131
+ finiteIn(j.processingTimePerItemMs, 0, MAX_LATENCY_MS) &&
132
+ finiteIn(j.externalCallsPerItem, 0, 1000) &&
133
+ finiteIn(j.transactionSizeItems, 0, 1e9) &&
134
+ finiteIn(j.retryRate, 0, 1) &&
135
+ finiteIn(j.failureRate, 0, 1);
136
+ if (!ok)
137
+ bad("jobConfig has missing or out-of-range values.");
138
+ }
139
+ });
140
+ }
141
+ /** Model defaults: absent → site defaults; present → every field checked, profiles complete (no partial merge). */
142
+ function validateModelDefaults(raw, problems, warnings) {
143
+ const defaults = (0, defaults_1.createDefaultModelDefaults)();
144
+ if (raw === undefined)
145
+ return defaults;
146
+ if (!isObj(raw)) {
147
+ problems.push("modelDefaults must be an object.");
148
+ return defaults;
149
+ }
150
+ const out = { ...defaults, profiles: { ...defaults.profiles } };
151
+ if (raw.profiles !== undefined) {
152
+ if (!isObj(raw.profiles))
153
+ problems.push("modelDefaults.profiles must be an object keyed by operation type.");
154
+ else
155
+ for (const [type, p] of Object.entries(raw.profiles)) {
156
+ const where = `Model defaults for "${type}"`;
157
+ if (!KNOWN_TYPES.has(type)) {
158
+ problems.push(`${where}: unknown operation type.`);
159
+ continue;
160
+ }
161
+ if (!isObj(p)) {
162
+ problems.push(`${where} must be an object with ${PROFILE_KEYS.join(", ")}.`);
163
+ continue;
164
+ }
165
+ const missing = PROFILE_KEYS.filter((k) => p[k] === undefined);
166
+ const extra = Object.keys(p).filter((k) => !PROFILE_KEYS.includes(k));
167
+ const invalid = PROFILE_KEYS.filter((k) => p[k] !== undefined && !finiteIn(p[k], 0, MAX_LATENCY_MS));
168
+ if (missing.length)
169
+ problems.push(`${where} is incomplete: missing ${missing.join(", ")}.`);
170
+ if (extra.length)
171
+ problems.push(`${where} has unknown fields: ${extra.join(", ")}.`);
172
+ if (invalid.length)
173
+ problems.push(`${where}: ${invalid.join(", ")} must be numbers between 0 and ${MAX_LATENCY_MS} ms.`);
174
+ if (missing.length || extra.length || invalid.length)
175
+ continue;
176
+ const profile = Object.fromEntries(PROFILE_KEYS.map((k) => [k, p[k]]));
177
+ const order = orderingProblems(profile);
178
+ if (order.length)
179
+ warnings.push(`${where} look unusual: ${order.join("; ")}.`);
180
+ out.profiles[type] = profile;
181
+ }
182
+ }
183
+ if (raw.cacheHitRate !== undefined) {
184
+ if (!finiteIn(raw.cacheHitRate, 0, 1))
185
+ problems.push(`modelDefaults.cacheHitRate must be between 0 and 1 (got ${JSON.stringify(raw.cacheHitRate)}).`);
186
+ else
187
+ out.cacheHitRate = raw.cacheHitRate;
188
+ }
189
+ for (const k of ["serviceFrameworkTimeoutMs", "ocapiTimeoutMs", "scapiTimeoutMs"]) {
190
+ if (raw[k] === undefined)
191
+ continue;
192
+ if (!finiteIn(raw[k], 1, MAX_LATENCY_MS))
193
+ problems.push(`modelDefaults.${k} must be between 1 and ${MAX_LATENCY_MS} ms.`);
194
+ else
195
+ out[k] = raw[k];
196
+ }
197
+ return out;
198
+ }
199
+ /** Report metadata: optional, but when present it must have the documented shape (it drives warnings and the comparison strip). */
200
+ function validateMeta(raw, problems) {
201
+ if (raw === undefined || raw === null)
202
+ return null;
203
+ if (!isObj(raw)) {
204
+ problems.push("meta must be an object.");
205
+ return null;
206
+ }
207
+ const str = (v) => typeof v === "string";
208
+ const meta = {};
209
+ for (const k of ["generator", "generatedAt", "cartridgePath"]) {
210
+ if (raw[k] === undefined)
211
+ continue;
212
+ if (!str(raw[k]))
213
+ problems.push(`meta.${k} must be text.`);
214
+ else
215
+ meta[k] = raw[k];
216
+ }
217
+ if (raw.entry !== undefined) {
218
+ const e = raw.entry;
219
+ if (!isObj(e) || !str(e.id) || !optional(e.kind, str) || !optional(e.label, str) || !(e.httpMethod === undefined || e.httpMethod === null || str(e.httpMethod)))
220
+ problems.push("meta.entry must be { id, kind?, label?, httpMethod? } with text values.");
221
+ else
222
+ meta.entry = { id: e.id, kind: e.kind, label: e.label, httpMethod: e.httpMethod ?? null };
223
+ }
224
+ if (raw.summary !== undefined) {
225
+ const sm = raw.summary;
226
+ if (!isObj(sm))
227
+ problems.push("meta.summary must be an object.");
228
+ else {
229
+ const summary = {};
230
+ for (const k of ["averageMs", "minMs", "maxMs", "criticalPathMs", "operationCount"]) {
231
+ if (sm[k] === undefined)
232
+ continue;
233
+ if (!finiteIn(sm[k], 0, 1e9))
234
+ problems.push(`meta.summary.${k} must be a number ≥ 0.`);
235
+ else
236
+ summary[k] = sm[k];
237
+ }
238
+ for (const k of ["p50Ms", "p95Ms", "p99Ms"]) {
239
+ if (sm[k] === undefined)
240
+ continue;
241
+ if (sm[k] !== null && !finiteIn(sm[k], 0, 1e9))
242
+ problems.push(`meta.summary.${k} must be a number ≥ 0 or null.`);
243
+ else
244
+ summary[k] = sm[k];
245
+ }
246
+ meta.summary = summary;
247
+ }
248
+ }
249
+ if (raw.coverage !== undefined) {
250
+ const c = raw.coverage;
251
+ if (!isObj(c))
252
+ problems.push("meta.coverage must be an object.");
253
+ else if (c.complete !== undefined && typeof c.complete !== "boolean")
254
+ problems.push("meta.coverage.complete must be true or false.");
255
+ else if (c.issues !== undefined && !Array.isArray(c.issues))
256
+ problems.push("meta.coverage.issues must be a list.");
257
+ else {
258
+ const issues = c.issues ?? [];
259
+ const valid = issues.every((i) => isObj(i) && str(i.kind) && str(i.message) && typeof i.blocking === "boolean");
260
+ if (!valid)
261
+ problems.push("Each meta.coverage.issues entry must have kind, message and blocking (true/false).");
262
+ else
263
+ meta.coverage = {
264
+ complete: c.complete,
265
+ issues: issues.map((i) => ({ kind: i.kind, blocking: i.blocking, message: i.message, ...(str(i.file) ? { file: i.file } : {}), ...(finiteIn(i.line, 0, 1e9) ? { line: i.line } : {}) })),
266
+ };
267
+ }
268
+ }
269
+ if (raw.codeFindings !== undefined) {
270
+ const list = raw.codeFindings;
271
+ const okLocation = (l) => isObj(l) && str(l.file) && optional(l.line, (v) => finiteIn(v, 0, 1e9));
272
+ const ok = Array.isArray(list) &&
273
+ list.length <= 500 &&
274
+ list.every((f) => isObj(f) && str(f.title) && str(f.detail) && optional(f.why, str) && oneOf(f.severity, ["info", "warning"]) && optional(f.locations, (v) => Array.isArray(v) && v.every(okLocation)));
275
+ if (!ok)
276
+ problems.push("meta.codeFindings must be a list of { title, detail, severity: info|warning, locations: [{ file, line }] }.");
277
+ else
278
+ meta.codeFindings = list.map((f, i) => ({
279
+ id: str(f.id) ? f.id : `finding-${i}`,
280
+ title: f.title,
281
+ severity: f.severity,
282
+ detail: f.detail,
283
+ why: f.why ?? "",
284
+ locations: (f.locations ?? []).map((l) => ({ file: l.file, ...(typeof l.line === "number" ? { line: l.line } : {}) })),
285
+ }));
286
+ }
287
+ if (raw.exported !== undefined) {
288
+ const e = raw.exported;
289
+ if (!isObj(e) || !str(e.at) || typeof e.edited !== "boolean")
290
+ problems.push("meta.exported must be { at, edited }.");
291
+ else
292
+ meta.exported = { at: e.at, edited: e.edited };
293
+ }
294
+ if (raw.engineRev !== undefined && str(raw.engineRev))
295
+ meta.engineRev = raw.engineRev;
296
+ return meta;
297
+ }
298
+ /** The execution fields every block carries (probability, count, mode, profile), from the site's own block factory. */
299
+ function engineBasics(type, name) {
300
+ const { profileId, category, executionProbability, executionMode, operationCount, parallelMode, preset, overrides } = (0, nodeFactory_1.createOperationNodeData)(type, name);
301
+ return { profileId, category, executionProbability, executionMode, operationCount, parallelMode, preset, overrides };
302
+ }
303
+ const capProblems = (problems) => fail(problems.slice(0, 12).concat(problems.length > 12 ? [`…and ${problems.length - 12} more problems.`] : []));
304
+ function parseImportedModel(text) {
305
+ const extracted = extractJson(text);
306
+ if (!extracted) {
307
+ const looksLikeReport = /#\s*SFCC Performance Trace/.test(text);
308
+ return fail([
309
+ looksLikeReport
310
+ ? "This report has no model block — the section between `<!-- sfcc-perf-model:begin -->` and `<!-- sfcc-perf-model:end -->` is missing or was edited. Regenerate the report."
311
+ : `This file isn't a trace report: there's no sfcc-perf-model block in it. ${NPX_HINT}`,
312
+ ]);
313
+ }
314
+ let raw;
315
+ try {
316
+ raw = JSON.parse(extracted.json);
317
+ }
318
+ catch (e) {
319
+ return fail([`The embedded model isn't valid JSON (${e.message}). Was the report edited by hand? Regenerate it.`]);
320
+ }
321
+ if (!isObj(raw))
322
+ return fail(["The embedded model must be a JSON object."]);
323
+ const problems = [];
324
+ if (raw.version !== 1)
325
+ problems.push(`Unsupported model version ${JSON.stringify(raw.version)} — this site reads version 1.`);
326
+ if (raw.format !== undefined && raw.format !== "sfcc-perf-trace/v1")
327
+ problems.push(`Unsupported report format ${JSON.stringify(raw.format)}.`);
328
+ if (!Array.isArray(raw.nodes))
329
+ problems.push("The model has no operations list.");
330
+ if (!Array.isArray(raw.edges))
331
+ problems.push("The model has no connections list.");
332
+ if (problems.length)
333
+ return fail(problems);
334
+ const rawNodes = raw.nodes;
335
+ const rawEdges = raw.edges;
336
+ if (rawNodes.length === 0)
337
+ return fail(["The report contains no operations to import."]);
338
+ if (rawNodes.length > MAX_NODES)
339
+ return fail([`The model has ${rawNodes.length} operations; the limit is ${MAX_NODES}.`]);
340
+ if (rawEdges.length > MAX_EDGES)
341
+ return fail([`The model has ${rawEdges.length} connections; the limit is ${MAX_EDGES}.`]);
342
+ validateNodes(rawNodes, problems);
343
+ rawEdges.forEach((e, i) => {
344
+ if (!isObj(e) || typeof e.id !== "string" || typeof e.source !== "string" || typeof e.target !== "string")
345
+ problems.push(`Connection #${i + 1} is malformed.`);
346
+ else if (!(e.sourceHandle === undefined || e.sourceHandle === null || typeof e.sourceHandle === "string"))
347
+ problems.push(`Connection #${i + 1} has an invalid sourceHandle.`);
348
+ else if (e.data !== undefined && !(isObj(e.data) && optional(e.data.probability, (v) => finiteIn(v, 0, 1)) && optional(e.data.branchLabel, (v) => typeof v === "string")))
349
+ problems.push(`Connection #${i + 1} has invalid data (probability must be between 0 and 1).`);
350
+ });
351
+ const warnings = [];
352
+ const modelDefaults = validateModelDefaults(raw.modelDefaults, problems, warnings);
353
+ const meta = validateMeta(raw.meta, problems);
354
+ if (problems.length)
355
+ return capProblems(problems);
356
+ // Fill fields the engine needs that an older or hand-made file may leave out (never overriding what it has).
357
+ const nodes = rawNodes.map((n, i) => ({
358
+ ...n,
359
+ type: "operation",
360
+ data: { ...engineBasics(n.data.type, n.data.name), ...n.data },
361
+ position: isObj(n.position) && finiteIn(n.position.x, -1e6, 1e6) && finiteIn(n.position.y, -1e6, 1e6) ? n.position : { x: i * 260, y: 0 },
362
+ }));
363
+ const ids = new Set(nodes.map((n) => n.id));
364
+ const edges = rawEdges.filter((e) => ids.has(e.source) && ids.has(e.target)).map((e) => ({ ...e, type: "smoothstep" }));
365
+ const dropped = rawEdges.length - edges.length;
366
+ if (dropped > 0)
367
+ warnings.push(`${dropped} connection${dropped === 1 ? "" : "s"} pointed at missing operations and were skipped.`);
368
+ const roots = (0, analyzeEndpoint_1.findApiRoots)(nodes, edges);
369
+ const activeRootId = typeof raw.activeRootId === "string" && ids.has(raw.activeRootId) ? raw.activeRootId : roots.length === 1 ? roots[0].id : null;
370
+ if (!activeRootId)
371
+ return fail([roots.length === 0 ? "The model has no entry operation (every operation has an incoming connection)." : "The model has several entry operations and doesn't say which one to analyse."]);
372
+ const structural = (0, validateGraph_1.validateGraph)(nodes, edges, activeRootId).filter((g) => g.severity === "error");
373
+ if (structural.length)
374
+ return fail(structural.map((g) => `Flow structure: ${g.message}`));
375
+ const overBudget = (0, analyzeEndpoint_1.checkEvaluationBudget)(nodes, edges, activeRootId);
376
+ if (overBudget)
377
+ return fail([overBudget.message]);
378
+ if (meta?.coverage?.complete === false) {
379
+ const n = meta.coverage.issues?.filter((i) => i.blocking).length ?? 0;
380
+ warnings.push(`The trace is marked incomplete (${n} part${n === 1 ? "" : "s"} of the code couldn't be followed), so it may be missing work.`);
381
+ }
382
+ const mode = typeof raw.mode === "string" && MODES.has(raw.mode) ? raw.mode : null;
383
+ const analysis = (0, analyzeEndpoint_1.analyzeEndpoint)(nodes, edges, modelDefaults, activeRootId);
384
+ const engineErrors = analysis.warnings.filter((w) => w.severity === "error");
385
+ if (engineErrors.length)
386
+ return fail(engineErrors.map((w) => w.message));
387
+ const outputs = { average: analysis.averageLatency, minimum: analysis.minLatency, maximum: analysis.maxLatency, P50: analysis.p50, P95: analysis.p95, P99: analysis.p99, "critical path": analysis.criticalPathTotal };
388
+ const broken = Object.entries(outputs).filter(([, v]) => v !== null && !Number.isFinite(v));
389
+ if (broken.length)
390
+ return fail([`The model can't be calculated: ${broken.map(([k]) => k).join(", ")} came out as ${String(broken[0][1])}. Check its latency values and model defaults, or regenerate the report.`]);
391
+ const reportAvg = typeof meta?.summary?.averageMs === "number" ? meta.summary.averageMs : null;
392
+ if (reportAvg !== null && Math.abs(reportAvg - analysis.averageLatency) > Math.max(1, reportAvg * 0.01)) {
393
+ warnings.push(`The report says AVG ${Math.round(reportAvg)} ms but this site calculates ${Math.round(analysis.averageLatency)} ms — the report was probably made with a different engine version.`);
394
+ }
395
+ const operations = nodes.filter((n) => n.data.type !== "response" && n.id !== activeRootId).length;
396
+ return {
397
+ ok: true,
398
+ model: { mode, nodes, edges, modelDefaults, activeRootId, meta, source: extracted.source },
399
+ summary: { label: meta?.entry?.label ?? meta?.entry?.id ?? nodes.find((n) => n.id === activeRootId)?.data.name ?? "Imported model", operations, averageMs: analysis.averageLatency, reportAverageMs: reportAvg },
400
+ warnings,
401
+ };
402
+ }
@@ -2,11 +2,12 @@ import type { AnalysisRun } from "../analyze";
2
2
  export declare const REPORT_FORMAT = "sfcc-perf-trace/v1";
3
3
  export declare const MODEL_BEGIN = "<!-- sfcc-perf-model:begin -->";
4
4
  export declare const MODEL_END = "<!-- sfcc-perf-model:end -->";
5
- export declare const GENERATOR_VERSION = "0.1.0";
5
+ export declare const GENERATOR_VERSION = "0.1.1";
6
6
  export interface RenderOptions {
7
7
  /** Directory the .md will be written to - file links are made relative to it. */
8
8
  reportDir?: string;
9
9
  }
10
+ export declare function reportEntryId({ trace, ws }: AnalysisRun): string;
10
11
  /** The JSON block the web analyzer's "Import" reads. Superset of its own Export JSON shape. */
11
12
  export declare function buildModelPayload(run: AnalysisRun): {
12
13
  version: 1;
@@ -19,7 +20,6 @@ export declare function buildModelPayload(run: AnalysisRun): {
19
20
  activeRootId: string;
20
21
  meta: {
21
22
  generator: string;
22
- engineRev: string;
23
23
  generatedAt: string;
24
24
  entry: {
25
25
  id: string;
@@ -49,11 +49,24 @@ export declare function buildModelPayload(run: AnalysisRun): {
49
49
  coverage: {
50
50
  complete: boolean;
51
51
  issues: {
52
+ line?: number | undefined;
53
+ file?: string | undefined;
52
54
  kind: import("../trace/tracer").CoverageKind;
53
55
  blocking: boolean;
54
56
  message: string;
55
57
  }[];
56
58
  };
59
+ codeFindings: {
60
+ id: string;
61
+ title: string;
62
+ severity: "warning" | "info";
63
+ detail: string;
64
+ why: string;
65
+ locations: {
66
+ line?: number | undefined;
67
+ file: string;
68
+ }[];
69
+ }[];
57
70
  };
58
71
  };
59
72
  export declare function renderMarkdown(run: AnalysisRun, opts?: RenderOptions): string;
@@ -4,20 +4,44 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.GENERATOR_VERSION = exports.MODEL_END = exports.MODEL_BEGIN = exports.REPORT_FORMAT = void 0;
7
+ exports.reportEntryId = reportEntryId;
7
8
  exports.buildModelPayload = buildModelPayload;
8
9
  exports.renderMarkdown = renderMarkdown;
9
10
  const node_path_1 = __importDefault(require("node:path"));
10
- const ENGINE_VERSION_1 = require("../engine/ENGINE_VERSION");
11
11
  const defaults_1 = require("../engine/defaults");
12
12
  const exportMermaid_1 = require("../engine/exportMermaid");
13
13
  const latencyEngine_1 = require("../engine/latencyEngine");
14
14
  exports.REPORT_FORMAT = "sfcc-perf-trace/v1";
15
15
  exports.MODEL_BEGIN = "<!-- sfcc-perf-model:begin -->";
16
16
  exports.MODEL_END = "<!-- sfcc-perf-model:end -->";
17
- exports.GENERATOR_VERSION = "0.1.0";
17
+ exports.GENERATOR_VERSION = "0.1.1";
18
18
  const ms = (n) => (n === null || n === undefined || Number.isNaN(n) ? "–" : n >= 100 ? `${Math.round(n)} ms` : `${n.toFixed(1)} ms`);
19
19
  const pct = (n) => `${n.toFixed(n >= 10 ? 0 : 1)}%`;
20
20
  const esc = (s) => s.replace(/\|/g, "\\|").replace(/\n/g, " ");
21
+ function workspaceSourcePath(ws, file) {
22
+ for (const root of ws.roots) {
23
+ const relative = node_path_1.default.relative(root, file);
24
+ if (!node_path_1.default.isAbsolute(relative) && relative.split(node_path_1.default.sep)[0] !== ".." && ws.isInsideWorkspace(file)) {
25
+ return relative.split(node_path_1.default.sep).join("/");
26
+ }
27
+ }
28
+ return null;
29
+ }
30
+ function reportEntryId({ trace, ws }) {
31
+ const { entry } = trace;
32
+ return entry.kind === "function" && workspaceSourcePath(ws, entry.file) === null ? entry.label : entry.id;
33
+ }
34
+ function reportCoverageIssue(ws, issue) {
35
+ const { kind, blocking, message, file, line } = issue;
36
+ const location = file ? workspaceSourcePath(ws, file) ?? node_path_1.default.basename(file) : undefined;
37
+ return {
38
+ kind,
39
+ blocking,
40
+ message: file && location ? message.replaceAll(ws.display(file), () => location) : message,
41
+ ...(location ? { file: location } : {}),
42
+ ...(line ? { line } : {}),
43
+ };
44
+ }
21
45
  /** The JSON block the web analyzer's "Import" reads. Superset of its own Export JSON shape. */
22
46
  function buildModelPayload(run) {
23
47
  const { trace, model, analysis } = run;
@@ -32,9 +56,8 @@ function buildModelPayload(run) {
32
56
  activeRootId: model.rootId,
33
57
  meta: {
34
58
  generator: `sfcc-perf@${exports.GENERATOR_VERSION}`,
35
- engineRev: ENGINE_VERSION_1.ENGINE_SOURCE_REV,
36
59
  generatedAt: run.generatedAt.toISOString(),
37
- entry: { id: trace.entry.id, kind: trace.entry.kind, label: trace.entry.label, httpMethod: trace.httpMethod ?? null },
60
+ entry: { id: reportEntryId(run), kind: trace.entry.kind, label: trace.entry.label, httpMethod: trace.httpMethod ?? null },
38
61
  cartridgePath: run.ws.cartridgePath,
39
62
  cartridgePathSource: run.ws.cartridgePathSource,
40
63
  assumptions: {
@@ -56,8 +79,17 @@ function buildModelPayload(run) {
56
79
  percentiles: "path-weighted scores (each path's percentile profile weighted by path probability) - not statistical percentiles",
57
80
  coverage: {
58
81
  complete: run.coverage.complete,
59
- issues: run.coverage.issues.map((i) => ({ kind: i.kind, blocking: i.blocking, message: i.message })),
82
+ issues: run.coverage.issues.map((i) => reportCoverageIssue(run.ws, i)),
60
83
  },
84
+ // Findings from reading the code (N+1 in loops, raw HTTPClient, …): the viewer can't recompute these from the graph.
85
+ codeFindings: run.staticFindings.map((f) => ({
86
+ id: f.id,
87
+ title: f.title,
88
+ severity: f.severity,
89
+ detail: f.detail,
90
+ why: f.why,
91
+ locations: f.locations.flatMap((l) => (l.file ? [{ file: workspaceSourcePath(run.ws, l.file) ?? node_path_1.default.basename(l.file), ...(l.line ? { line: l.line } : {}) }] : [])),
92
+ })),
61
93
  },
62
94
  };
63
95
  }
@@ -68,8 +100,9 @@ function renderMarkdown(run, opts = {}) {
68
100
  const link = (file, line, text) => {
69
101
  if (!file)
70
102
  return text ?? "";
71
- const label = text ?? `${ws.display(file)}${line ? `:${line}` : ""}`;
72
- if (!opts.reportDir)
103
+ const source = workspaceSourcePath(ws, file);
104
+ const label = text ?? `${source ?? node_path_1.default.basename(file)}${line ? `:${line}` : ""}`;
105
+ if (!opts.reportDir || source === null)
73
106
  return `\`${label}\``;
74
107
  const rel = node_path_1.default.relative(opts.reportDir, file).split(node_path_1.default.sep).join("/");
75
108
  return `[${esc(label)}](${encodeURI(rel)}${line ? `#L${line}` : ""})`;
@@ -80,7 +113,7 @@ function renderMarkdown(run, opts = {}) {
80
113
  const L = [];
81
114
  L.push(`# SFCC Performance Trace — ${trace.entry.label}`);
82
115
  L.push("");
83
- L.push(`> Static trace by **sfcc-perf ${exports.GENERATOR_VERSION}** · engine \`portfolio@${ENGINE_VERSION_1.ENGINE_SOURCE_REV}\` · ${run.generatedAt.toISOString().replace("T", " ").slice(0, 16)} UTC `);
116
+ L.push(`> Static trace by **sfcc-perf ${exports.GENERATOR_VERSION}** · ${run.generatedAt.toISOString().replace("T", " ").slice(0, 16)} UTC `);
84
117
  L.push("> This is a **mock model**: operations come from your code, latencies are the SFCC Performance Analyzer's illustrative defaults (tool assumptions, not measurements). Upload this file to the web analyzer to inspect, tweak and compare.");
85
118
  L.push("");
86
119
  // Summary
@@ -121,7 +154,7 @@ function renderMarkdown(run, opts = {}) {
121
154
  // Endpoint
122
155
  L.push("## Endpoint");
123
156
  L.push("");
124
- L.push(`- **Entry:** \`${trace.entry.id}\` (${trace.entry.kind}${trace.httpMethod ? `, ${trace.httpMethod}` : ""}) — ${link(trace.entry.file, trace.entry.line)}`);
157
+ L.push(`- **Entry:** \`${reportEntryId(run)}\` (${trace.entry.kind}${trace.httpMethod ? `, ${trace.httpMethod}` : ""}) — ${link(trace.entry.file, trace.entry.line)}`);
125
158
  L.push(`- **Modeled as:** ${defaults_1.OPERATION_LABELS[trace.root.type]}${trace.presetKey ? ` · preset ${trace.presetKey}` : ""}`);
126
159
  L.push(`- **Cartridge path** (${run.ws.cartridgePathSource}): \`${run.ws.cartridgePath}\``);
127
160
  if (model.pageCache)
@@ -214,7 +247,7 @@ function renderMarkdown(run, opts = {}) {
214
247
  L.push(run.coverage.complete ? "✅ Complete (informational notes only):" : "⚠️ **Incomplete** — the model may be missing work from these places:");
215
248
  L.push("");
216
249
  for (const i of run.coverage.issues)
217
- L.push(`- ${i.blocking ? "⚠️" : "ℹ️"} \`${i.kind}\` — ${esc(i.message)}${i.file ? ` ${link(i.file, i.line)}` : ""}`);
250
+ L.push(`- ${i.blocking ? "⚠️" : "ℹ️"} \`${i.kind}\` — ${esc(reportCoverageIssue(ws, i).message)}${i.file ? ` ${link(i.file, i.line)}` : ""}`);
218
251
  }
219
252
  L.push("");
220
253
  L.push("## Assumptions");
package/dist/show.d.ts CHANGED
@@ -6,16 +6,36 @@
6
6
  */
7
7
  /** The bundled viewer (dist/viewer), next to the compiled CLI - or under dist/ when running from src (tests). */
8
8
  export declare function viewerAssetsDir(): string;
9
- /** The viewer page for one report. `sourceName` is shown in the page (usually the report's file name). */
9
+ /**
10
+ * The viewer page for one report. `sourceName` is shown in the page (usually the report's file name).
11
+ * A content security policy allows only the page's own two scripts (by hash) and nothing over the
12
+ * network, so a report can't make the page load or send anything.
13
+ */
10
14
  export declare function renderViewerHtml(reportText: string, sourceName: string): string;
11
- /** Writes the viewer for `reportFile` (default: next to it, same name, .html) and returns the HTML file's path. */
15
+ /**
16
+ * Reads and checks a report before any HTML is written: size, then the same validation the
17
+ * viewer applies (so a broken or wrong file fails here, in the terminal, not in the browser).
18
+ */
19
+ export declare function readReport(file: string): string;
20
+ /**
21
+ * Writes the viewer for `reportFile` (default: next to it, same name, .html) and returns the HTML file's path.
22
+ * Only replaces a file it wrote itself: never a symlink or some other HTML file of the same name.
23
+ */
12
24
  export declare function writeViewer(reportFile: string, outFile?: string): string;
13
25
  /** Opens a file in the default browser. Returns false when that isn't possible (no desktop, CI, …). */
14
26
  export declare function openInBrowser(file: string): boolean;
15
- /** Newest report (.md) in the project's report directory, for `sfcc-perf show` without a file. */
27
+ /** The project's report folder - the same rule the trace command uses (config `reportDirectory`, else .sfcc-perf/reports). */
28
+ export declare function reportDirectory(root?: string): string;
29
+ /** Newest trace report in the project's report folder, for `sfcc-perf show` without a file. Other files are ignored. */
16
30
  export declare function latestReport(root?: string): string | null;
17
- /** The command that opens a report, as printed after a run (relative path, quoted when needed). */
18
- export declare function showCommandFor(reportFile: string): string;
19
- export declare const SHOW_HELP = "Usage: sfcc-perf show [report.md] [--out FILE.html] [--no-open]\n\nOpens a trace report in the SFCC Performance Analyzer, locally: writes one\nself-contained HTML file (default: next to the report, same name, .html) and\nopens it in your browser. Nothing is uploaded; it works offline.\n\nWithout a file, the newest report in the report folder is used.\n --out FILE where to write the HTML file\n --no-open only write the file (also when CI or SFCC_PERF_NO_OPEN=1 is set)\n";
31
+ /**
32
+ * An argument as typed into a shell: unquoted when that's safe, otherwise quoted so nothing in it is
33
+ * interpreted. Returns null on Windows when no quoting is literal in both cmd and PowerShell
34
+ * (`$`, backtick, `%`, `!`): the caller then names the file instead of printing a command.
35
+ */
36
+ export declare function shellArg(value: string, platform?: NodeJS.Platform): string | null;
37
+ /** The command that opens a report, as printed after a run (relative path, quoted for the shell). */
38
+ export declare function showCommandFor(reportFile: string, platform?: NodeJS.Platform): string;
39
+ export declare const SHOW_HELP = "Usage: sfcc-perf show [report.md] [--out FILE.html] [--no-open]\n\nOpens a trace report in the SFCC Performance Analyzer, locally: writes one\nself-contained HTML file (default: next to the report, same name, .html) and\nopens it in your browser. Nothing is uploaded; it works offline.\n\nIt opens a .md report written by sfcc-perf, or a model JSON exported from the\nanalyzer (not the --json summary). Reports up to 5 MB.\n\nWithout a file, the newest report in the report folder is used.\n --out FILE where to write the HTML file\n --no-open only write the file (also when CI or SFCC_PERF_NO_OPEN=1 is set)\n";
20
40
  /** `sfcc-perf show …` - returns the exit code. */
21
41
  export declare function showMain(argv: string[]): number;