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.
package/CHANGELOG.md CHANGED
@@ -1,10 +1,36 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.1
4
+
5
+ Fixes from a release audit of the local viewer and the CLI:
6
+
7
+ - **`--strict` now fails when a cartridge on the cartridge path isn't in the workspace** (`missing-cartridge`, blocking), because it may override what was traced. Cartridges that live in another repository can be listed in the new `externalCartridges` option (`.sfcc-perf.json` or the API); they are then reported as information (`external-cartridge`).
8
+ - **Exit codes: an incomplete trace under `--strict` (3) now wins over a budget (2)**, and its numbers aren't checked against the budget (`"budgetSkipped": true` in `--json`). Before, a partial model could be reported as a budget failure.
9
+ - **The printed `npx sfcc-perf show …` command is safe to paste:** paths are single-quoted on macOS/Linux (nothing in a folder name is run or expanded), never start with `-`, and on Windows a path with `$`, `` ` ``, `%` or `!` is named instead of quoted. The browser opener uses no shell on any platform.
10
+ - **`show` checks its input before writing anything:** reports over 5 MB, files that aren't reports and the `--json` summary are rejected in the terminal with the reason, using the same validation as the viewer. It won't replace an existing file it didn't write, or follow a link.
11
+ - The generated page has a content security policy (only its own scripts, no network), and source links in it must be `http(s)`.
12
+ - `--json --open` now writes the report and opens it (it silently did nothing).
13
+ - `show` without a file picks the newest real report in the report folder, using the same folder rule as the trace command.
14
+ - The waterfall no longer calls itself the worst-case request: it's the modeled sequence of the slowest path, and it says that branches can appear one after another. "Add a cache node" is gone from the viewer.
15
+ - The README says what a shared HTML page contains.
16
+ - **The viewer keeps the report's context.** Reports now embed their code-derived findings (with workspace-relative locations) and coverage locations; the viewer's Analysis view shows *Trace completeness* and *Findings from the code* next to the live *Findings from the model*. Export JSON keeps the report's entry, summary, coverage and findings and marks whether the model was edited, so an export reopens with its comparison against the original report.
17
+ - **Reset to report:** after any edit, a *Reset to report* button (comparison strip, top bar, mobile report bar and More menu, and the empty canvas) restores the report as it was opened. Hiding the comparison strip no longer discards the report's metadata; *Compare with report* brings it back, and an incomplete trace stays flagged.
18
+ - **Phones** get a report bar under the header: the entry, an *Incomplete trace* flag when it applies, and report → now.
19
+ - P50/P95/P99 are labelled *score* everywhere in the viewer, with a tooltip explaining path-weighted scores.
20
+ - Accessibility: the opening notice no longer covers the Outline (bottom-left on desktop, and clicks pass through it); keyboard focus stays inside an open mobile sheet; the selected view and panel tab are exposed as pressed; latency inputs have labels.
21
+ - **Untrusted projects:** source is only read from inside the `--root` folders - a file that links outside (a symlink) is not read and is reported as a blocking `outside-workspace` gap (an entry file you name explicitly is still read). The default or configured report folder must really be inside the project, and report files are never written through a symbolic link; `--out` / `--out-dir` are used as given.
22
+
23
+ Also in this release:
24
+
25
+ - **`sfcc-perf show` opens just the one report.** The local viewer no longer has the web tool's start screen, modes, examples, new flow / clear canvas, importing another file, scenarios, or adding blocks (drag and drop or the mobile "+"), and the blocks panel that went with them. Inspecting and adjusting the report - views, Outline, Inspector, model defaults, the report → now comparison, export - is unchanged. The bundle is smaller (874 KB, was 898 KB).
26
+ - Reports no longer record the web analyzer's commit: the `meta.engineRev` field and the "engine portfolio@…" note in the header are gone; `generator: sfcc-perf@<version>` identifies the engine. `ENGINE_SOURCE_REV` is deprecated (it now returns `sfcc-perf@<version>`).
27
+ - The engine and the viewer are now this package's own source rather than copies synced from the web analyzer; the viewer uses the same engine code as the CLI.
28
+
3
29
  ## 0.1.0
4
30
 
5
31
  First release as **`sfcc-perf`**. It continues `sfcc-performance-analyser` 0.2.0 (its history is below): the package now has the same name as its command, so `npx sfcc-perf …` works without installing first. Moving over: `npm uninstall sfcc-performance-analyser && npm install --save-dev sfcc-perf`, and change imports to `from "sfcc-perf"`. The `sfcc-perf` command, `.sfcc-perf.json`, the API and the report format are unchanged; the long `sfcc-performance-analyser` command is gone, and reports say `generator: "sfcc-perf@0.1.0"`.
6
32
 
7
- - **New: `sfcc-perf show <report.md>`** opens a report in the SFCC Performance Analyzer on your machine. The web analyzer's UI is bundled into the package; `show` writes one self-contained, offline HTML file next to the report (Waterfall, Flow, Analysis, Outline, findings, what-if edits with a *report → now* comparison) and opens it in the browser. Without a file it shows the newest report; `--out` and `--no-open` control the output.
33
+ - **New: `sfcc-perf show <report.md>`** opens a report in the SFCC Performance Analyzer on your machine. The web analyzer's UI is bundled into the package; `show` writes one self-contained, offline HTML file next to the report (Waterfall, Flow, Analysis, Outline, findings, what-if edits with a *report → now* comparison) and opens it in the browser. The page holds that one report: examples, modes, new or imported flows, scenarios and adding blocks are left out of the bundled UI. Without a file it shows the newest report; `--out` and `--no-open` control the output.
8
34
  - Every run that writes a report ends with the `npx sfcc-perf show …` command for it; `--open` traces and opens in one step.
9
35
  - **Fixed: `--strict` could pass a trace that skipped work.** A function called through an array or object (`var handlers = [load]; handlers[0]()`) was silently dropped while the trace still reported `complete: true`. Now:
10
36
  - a constant index into a literal array is followed (`handlers[0]()`);
package/README.md CHANGED
@@ -69,7 +69,13 @@ Open it in the analyzer (locally, offline):
69
69
  npx sfcc-perf show reports/Product-Show.md
70
70
  ```
71
71
 
72
- `sfcc-perf show <report.md>` writes `reports/Product-Show.html` next to the report and opens it in your browser. It's the web analyzer itself (the same UI, bundled into the package), with the report already loaded: Waterfall, Flow and Analysis views, every operation in the Outline, findings, and a *report → now* comparison while you change latencies, cache rates or branches. The file is self-contained - no server, no network, nothing uploaded - so you can also attach it to a pull request or send it to someone.
72
+ `sfcc-perf show <report.md>` writes `reports/Product-Show.html` next to the report and opens it in your browser. It's the web analyzer itself (the same UI, bundled into the package), with the report already loaded: Waterfall, Flow and Analysis views, every operation in the Outline, findings, and a *report → now* comparison while you change latencies, cache rates or branches. It shows that one report only: unlike the web tool there are no examples, modes, new or imported flows, and no adding blocks, so there is no blocks panel either. The file is self-contained - no server, no network, nothing uploaded - and a content security policy stops it loading or sending anything.
73
+
74
+ The Analysis view also shows the report's *Trace completeness* and the *Findings from the code* the trace made (they don't change as you edit). After any edit, *Reset to report* puts the report back as it was opened; Export JSON keeps the report's context, so an export reopens with its comparison against the original report. On a phone, a bar under the header shows the entry, whether the trace is complete, and report → now.
75
+
76
+ It opens a `.md` report written by sfcc-perf or a model JSON exported from the analyzer (not the `--json` summary, which `show` rejects), up to 5 MB, and checks it before writing the page. It replaces an existing `.html` only if sfcc-perf wrote it.
77
+
78
+ > **Before you share the page:** it contains the whole report - every traced operation with its cartridge, file and line, service IDs and the relative links to your source - the same as the `.md`. Share it where you'd share the code.
73
79
 
74
80
  ```bash
75
81
  sfcc-perf show # the newest report in the report folder
@@ -83,15 +89,21 @@ In CI (`CI` set) or with `--no-open` / `SFCC_PERF_NO_OPEN=1` it only writes the
83
89
  |---|---|
84
90
  | 0 | OK |
85
91
  | 1 | An entry couldn't be traced (unknown route, missing implementation, invalid options/config, …) |
86
- | 2 | A latency budget was exceeded |
87
92
  | 3 | `--strict` (or `"strict": true`) and a trace is incomplete |
93
+ | 2 | A latency budget was exceeded |
94
+
95
+ When several apply, the first in this order wins. Under `--strict`, an incomplete trace is never checked against a budget: it fails with 3, and `--json` marks it `"budgetSkipped": true`.
88
96
 
89
97
  ### Trace completeness
90
98
 
91
- Every result says whether the tracer could follow everything it supports on the path. Unresolved `require()`s and middleware, the call-depth limit, files with syntax errors, dynamic hook names, unresolvable dynamic templates and calls whose target is picked at runtime from something the tracer can't see (`handlers[name]()` on a parameter, `list[0]()`, `getHandler()()` returning an unknown function) make a trace **incomplete**: the report shows a warning at the top and a *Trace completeness* section, and `--json` includes `complete` and `coverageIssues`. Without `--strict` an incomplete trace still exits 0 (with a warning on stderr); use `--strict` in CI so budgets are never checked against a partial model. A requested implementation that doesn't exist (an `api.json` endpoint, hook function or job step function that isn't exported) is always an error.
99
+ Every result says whether the tracer could follow everything it supports on the path. Cartridges on the cartridge path that aren't in the workspace, unresolved `require()`s and middleware, the call-depth limit, files with syntax errors, dynamic hook names, unresolvable dynamic templates and calls whose target is picked at runtime from something the tracer can't see (`handlers[name]()` on a parameter, `list[0]()`, `getHandler()()` returning an unknown function) make a trace **incomplete**: the report shows a warning at the top and a *Trace completeness* section, and `--json` includes `complete` and `coverageIssues`. Without `--strict` an incomplete trace still exits 0 (with a warning on stderr); use `--strict` in CI so budgets are never checked against a partial model. A requested implementation that doesn't exist (an `api.json` endpoint, hook function or job step function that isn't exported) is always an error.
100
+
101
+ A missing cartridge counts because it may override what was traced. If some cartridges on the path live in another repository (a LINK cartridge, a shared plugin), list them in `"externalCartridges"` in `.sfcc-perf.json`: they're then reported as information, not as a gap.
92
102
 
93
103
  Dispatch through a literal array or object the tracer can see is followed: `handlers[0]()` traces that element, and `handlers[key]()` / `handlers.forEach(function (h) { h(); })` trace every member as equal-share alternatives, like `switch` cases.
94
104
 
105
+ Only files inside the `--root` folders are read: a source file that is a symbolic link to somewhere else is skipped and reported as an incomplete trace (`outside-workspace`), so tracing an unfamiliar repository can't read other files on your machine. An entry file you name explicitly is read wherever it is. Reports go to the project's report folder only if it's really inside the project, and never through a symbolic link; `--out` / `--out-dir` are used as given.
106
+
95
107
  *Complete* means complete coverage of the constructs the tracer supports, not a guarantee about runtime behaviour: calls on objects it can't identify (a parameter's `.process()`, a platform object's methods it doesn't catalogue) are not followed and don't mark a trace incomplete.
96
108
 
97
109
  ### CI example (GitHub Actions)
@@ -108,7 +120,7 @@ Commit the `.sfcc-perf.json` that `sfcc-perf init` writes (or pass `--cartridge-
108
120
  with: { name: sfcc-perf-reports, path: .sfcc-perf/reports }
109
121
  ```
110
122
 
111
- Without it in `package.json`, pin a version: `npx --yes sfcc-perf@0.1.0 --all --strict --cartridge-path "app_custom:app_storefront_base"`.
123
+ Without it in `package.json`, pin a version: `npx --yes sfcc-perf@0.1.1 --all --strict --cartridge-path "app_custom:app_storefront_base"`.
112
124
 
113
125
  ## Config file
114
126
 
@@ -117,6 +129,7 @@ Without it in `package.json`, pin a version: `npx --yes sfcc-perf@0.1.0 --all --
117
129
  ```json
118
130
  {
119
131
  "cartridgePath": "app_custom:int_payment:app_storefront_base",
132
+ "externalCartridges": ["int_payment"],
120
133
  "conditionalProbability": 0.5,
121
134
  "loopIterations": 5,
122
135
  "cacheHitRate": 0.8,
package/dist/analyze.d.ts CHANGED
@@ -11,6 +11,8 @@ export interface AnalyzeOptions extends TraceOptions {
11
11
  cartridgePath: string;
12
12
  cacheHitRate: number;
13
13
  latencyOverrides: Partial<Record<OperationType, Partial<LatencyProfile>>>;
14
+ /** Cartridges on the cartridge path that live in another repository: expected to be missing here (not a blocking gap). */
15
+ externalCartridges?: string[];
14
16
  }
15
17
  export declare const DEFAULT_OPTIONS: AnalyzeOptions;
16
18
  /** Coverage kinds that mean the model is probably missing work (fail under --strict). */
@@ -53,6 +55,7 @@ export declare function createSession(roots: string[], options?: Partial<Analyze
53
55
  cartridgePath: string;
54
56
  cacheHitRate: number;
55
57
  latencyOverrides: Partial<Record<OperationType, Partial<LatencyProfile>>>;
58
+ externalCartridges?: string[];
56
59
  conditionalProbability: number;
57
60
  loopIterations: number;
58
61
  maxDepth: number;
@@ -63,4 +66,6 @@ export declare function buildModelDefaults(opts: AnalyzeOptions): ModelDefaultsS
63
66
  /** Trace one entry point end to end and evaluate it with the web analyzer's engine. Reads `.sfcc-perf.json`; `options` override it. */
64
67
  export declare function runAnalysis(roots: string[], entryId: string, options?: Partial<AnalyzeOptions>): AnalysisRun;
65
68
  /** Analyse one entry with an existing session. Each call starts from fresh trace state. */
66
- export declare function analyzeWith(ws: SfccWorkspace, tracer: Tracer, opts: AnalyzeOptions, entryId: string): AnalysisRun;
69
+ export declare function analyzeWith(ws: SfccWorkspace, tracer: Tracer, opts: AnalyzeOptions, entryId: string, { allowExternalEntry }?: {
70
+ allowExternalEntry?: boolean;
71
+ }): AnalysisRun;
package/dist/analyze.js CHANGED
@@ -25,9 +25,10 @@ exports.DEFAULT_OPTIONS = {
25
25
  scanTemplates: true,
26
26
  cacheHitRate: 0.8,
27
27
  latencyOverrides: {},
28
+ externalCartridges: [],
28
29
  };
29
30
  /** Coverage kinds that mean the model is probably missing work (fail under --strict). */
30
- exports.BLOCKING_COVERAGE = new Set(["depth-limit", "unresolved-require", "parse-error", "unresolved-middleware", "dynamic-hook", "missing-hook-function", "dynamic-template", "missing-super-module", "dynamic-call"]);
31
+ exports.BLOCKING_COVERAGE = new Set(["depth-limit", "unresolved-require", "parse-error", "unresolved-middleware", "dynamic-hook", "missing-hook-function", "dynamic-template", "missing-super-module", "dynamic-call", "missing-cartridge", "outside-workspace"]);
31
32
  /**
32
33
  * Discovers cartridges once so several entries can be analysed with the same
33
34
  * parsed sources. Options come from `.sfcc-perf.json` in the first root
@@ -77,11 +78,11 @@ function runAnalysis(roots, entryId, options = {}) {
77
78
  return analyzeWith(ws, tracer, opts, entryId);
78
79
  }
79
80
  /** Analyse one entry with an existing session. Each call starts from fresh trace state. */
80
- function analyzeWith(ws, tracer, opts, entryId) {
81
+ function analyzeWith(ws, tracer, opts, entryId, { allowExternalEntry = true } = {}) {
81
82
  if (ws.cartridges.length === 0)
82
83
  throw new Error("No SFCC cartridges found (folders containing a `cartridge/` directory).");
83
84
  tracer.beginAnalysis();
84
- const trace = (0, entries_1.traceEntry)(ws, tracer, entryId);
85
+ const trace = (0, entries_1.traceEntry)(ws, tracer, entryId, allowExternalEntry);
85
86
  const modelDefaults = buildModelDefaults(opts);
86
87
  const model = (0, buildModel_1.buildModel)(trace, modelDefaults);
87
88
  // Same budget as the web analyzer, so every report the CLI writes can be imported there.
@@ -96,6 +97,23 @@ function analyzeWith(ws, tracer, opts, entryId) {
96
97
  const job = rootData.jobConfig ? (0, jobEngine_1.analyzeJobThroughput)(model.nodes, model.edges, modelDefaults, model.rootId, rootData.jobConfig) : null;
97
98
  for (const file of tracer.parseErrorsInRun())
98
99
  tracer.addCoverage({ kind: "parse-error", message: `${ws.display(file)} has syntax errors - parts of it may be missing from the trace`, file });
100
+ // Source that resolves outside the workspace through a symlink isn't read - say so rather than modelling less.
101
+ for (const file of ws.outsideFiles) {
102
+ if (tracer.usedModules.has(file))
103
+ tracer.addCoverage({ kind: "outside-workspace", message: `${ws.display(file)} links to a file outside the workspace - it was not read (only files inside --root folders are traced)`, file });
104
+ }
105
+ // A cartridge on the path that isn't here may override what was traced. Blocking unless declared as living elsewhere.
106
+ for (const name of ws.missingCartridges) {
107
+ if ((opts.externalCartridges ?? []).includes(name)) {
108
+ tracer.addCoverage({ kind: "external-cartridge", message: `cartridge "${name}" is on the cartridge path but in another repository (externalCartridges) - anything it overrides is not traced` });
109
+ }
110
+ else {
111
+ tracer.addCoverage({
112
+ kind: "missing-cartridge",
113
+ message: `cartridge "${name}" is on the cartridge path (${opts.cartridgePath}) but not in this workspace - anything it overrides is not traced. Add its folder with --root, or list it in "externalCartridges" if it lives in another repository`,
114
+ });
115
+ }
116
+ }
99
117
  const issues = tracer.coverage.map((c) => ({ ...c, blocking: exports.BLOCKING_COVERAGE.has(c.kind) }));
100
118
  const coverage = { complete: !issues.some((i) => i.blocking), issues };
101
119
  return {
package/dist/cli.js CHANGED
@@ -8,6 +8,7 @@ exports.main = main;
8
8
  exports.cliEntry = cliEntry;
9
9
  const node_fs_1 = __importDefault(require("node:fs"));
10
10
  const node_path_1 = __importDefault(require("node:path"));
11
+ const node_crypto_1 = require("node:crypto");
11
12
  const analyze_1 = require("./analyze");
12
13
  const config_1 = require("./config");
13
14
  const setup_1 = require("./setup");
@@ -206,16 +207,13 @@ function run(argv) {
206
207
  return 0;
207
208
  }
208
209
  const args = parsed;
209
- const { config, file: configFile } = (0, config_1.loadConfig)(args.roots[0], args.configFile);
210
- const { reportDirectory, entries: configEntries, budgets, strict: configStrict, ...configOptions } = config;
210
+ const loaded = (0, config_1.loadConfig)(args.roots[0], args.configFile);
211
+ const { reportDirectory: _reportDirectory, entries: configEntries, budgets, strict: configStrict, ...configOptions } = loaded.config;
212
+ const configFile = loaded.file;
211
213
  const strict = args.strict || configStrict === true;
212
- if (reportDirectory && configFile) {
213
- const base = node_path_1.default.dirname(configFile);
214
- const resolved = node_path_1.default.resolve(base, reportDirectory);
215
- if (node_path_1.default.relative(base, resolved).startsWith("..") || node_path_1.default.isAbsolute(node_path_1.default.relative(base, resolved))) {
216
- throw new validate_1.ConfigError([`reportDirectory "${reportDirectory}" points outside the project (${base}); use --out-dir for an explicit location`], configFile);
217
- }
218
- }
214
+ const explicitOutput = args.outDir || (!args.all && args.entries.length === 1 && args.out);
215
+ if (_reportDirectory && !explicitOutput)
216
+ (0, config_1.projectReportDirectory)(args.roots[0], loaded);
219
217
  const { ws, tracer, opts } = (0, analyze_1.createSession)(args.roots, { ...configOptions, ...args.options }, { readConfig: false });
220
218
  const pathLabel = args.options.cartridgePath ? "--cartridge-path" : `from ${configFile ? node_path_1.default.basename(configFile) : "config"}`;
221
219
  if (args.list || (!args.all && args.entries.length === 0)) {
@@ -243,7 +241,6 @@ function run(argv) {
243
241
  process.stderr.write(`Note: ${w}\n`);
244
242
  const ids = args.all ? (configEntries?.length ? configEntries : (0, entries_1.listEntryPoints)(ws, tracer).map((e) => e.id)) : args.entries;
245
243
  const single = ids.length === 1 && !args.all;
246
- const outDir = args.outDir ?? (configFile && reportDirectory ? node_path_1.default.resolve(node_path_1.default.dirname(configFile), reportDirectory) : node_path_1.default.resolve(args.roots[0], reportDirectory ?? ".sfcc-perf/reports"));
247
244
  const results = [];
248
245
  let failed = false;
249
246
  let incomplete = false;
@@ -251,7 +248,7 @@ function run(argv) {
251
248
  for (const id of ids) {
252
249
  let run;
253
250
  try {
254
- run = (0, analyze_1.analyzeWith)(ws, tracer, opts, id);
251
+ run = (0, analyze_1.analyzeWith)(ws, tracer, opts, id, { allowExternalEntry: !args.all });
255
252
  }
256
253
  catch (e) {
257
254
  errors++;
@@ -260,7 +257,10 @@ function run(argv) {
260
257
  continue;
261
258
  }
262
259
  const budget = { ...((0, config_1.budgetFor)(run.trace.entry.id, budgets) ?? {}), ...args.cliBudget };
263
- const violations = (0, config_1.checkBudget)(run, Object.keys(budget).length ? budget : null);
260
+ const hasBudget = Object.keys(budget).length > 0;
261
+ // Under --strict an incomplete trace fails as incomplete (exit 3); its numbers are never checked against a budget.
262
+ const budgetSkipped = hasBudget && strict && !run.coverage.complete;
263
+ const violations = budgetSkipped ? [] : (0, config_1.checkBudget)(run, hasBudget ? budget : null);
264
264
  if (violations.length)
265
265
  failed = true;
266
266
  let reportFile = null;
@@ -268,12 +268,23 @@ function run(argv) {
268
268
  if (toStdout) {
269
269
  process.stdout.write((0, markdown_1.renderMarkdown)(run));
270
270
  }
271
- else if (!(args.json && single && !args.out && !args.outDir)) {
272
- reportFile = single && args.out ? args.out : node_path_1.default.join(outDir, `${id.replace(/[^\w.-]+/g, "_")}.md`);
271
+ else if (!(args.json && single && !args.out && !args.outDir && !args.open)) {
272
+ if (single && args.out) {
273
+ reportFile = args.out;
274
+ }
275
+ else {
276
+ const outDir = args.outDir ?? (0, config_1.projectReportDirectory)(args.roots[0], loaded);
277
+ const displayId = (0, markdown_1.reportEntryId)(run);
278
+ // Keep similarly named external entries distinct without exposing their directory in the filename.
279
+ const fileId = displayId === run.trace.entry.id ? id : `${displayId}-${(0, node_crypto_1.createHash)("sha256").update(run.trace.entry.id).digest("hex").slice(0, 12)}`;
280
+ reportFile = node_path_1.default.join(outDir, `${fileId.replace(/[^\w.-]+/g, "_")}.md`);
281
+ }
273
282
  node_fs_1.default.mkdirSync(node_path_1.default.dirname(reportFile), { recursive: true });
283
+ if (isSymlink(reportFile))
284
+ throw new validate_1.ConfigError([`${node_path_1.default.relative(process.cwd(), reportFile) || reportFile} is a symbolic link - not writing through it; remove it or use --out`], "report file");
274
285
  node_fs_1.default.writeFileSync(reportFile, (0, markdown_1.renderMarkdown)(run, { reportDir: node_path_1.default.dirname(reportFile) }));
275
286
  }
276
- const s = summary(run, reportFile, violations);
287
+ const s = { ...summary(run, reportFile, violations), ...(budgetSkipped ? { budgetSkipped: true } : {}) };
277
288
  results.push(s);
278
289
  if (!args.json && !toStdout) {
279
290
  process.stderr.write(`${violations.length ? "✗" : "✓"} ${id}: avg ${s.averageMs} ms · p95 ${s.p95Ms ?? "–"} ms · ${s.operations} ops${reportFile ? ` → ${node_path_1.default.relative(process.cwd(), reportFile)}` : ""}\n`);
@@ -284,6 +295,8 @@ function run(argv) {
284
295
  incomplete = true;
285
296
  const blocking = run.coverage.issues.filter((i) => i.blocking);
286
297
  process.stderr.write(` ${strict ? "incomplete trace" : "warning: incomplete trace"} (${blocking.length} issue${blocking.length === 1 ? "" : "s"}): ${blocking.slice(0, 3).map((i) => i.message).join("; ")}${blocking.length > 3 ? "; …" : ""}\n`);
298
+ if (budgetSkipped)
299
+ process.stderr.write(` budget not checked: the trace is incomplete\n`);
287
300
  }
288
301
  }
289
302
  if (args.json)
@@ -299,14 +312,23 @@ function run(argv) {
299
312
  else if (written.length && !args.json) {
300
313
  process.stderr.write(`\nOpen ${written.length === 1 ? "it" : "a report"} in the analyzer (locally, offline):\n ${(0, show_1.showCommandFor)(written[0])}\n`);
301
314
  }
315
+ // Precedence: an entry that couldn't be traced (1), then an incomplete trace under --strict (3), then budgets (2).
302
316
  if (errors > 0)
303
317
  return 1;
304
- if (failed)
305
- return 2;
306
318
  if (strict && incomplete)
307
319
  return 3;
320
+ if (failed)
321
+ return 2;
308
322
  return 0;
309
323
  }
324
+ function isSymlink(file) {
325
+ try {
326
+ return node_fs_1.default.lstatSync(file).isSymbolicLink();
327
+ }
328
+ catch {
329
+ return false;
330
+ }
331
+ }
310
332
  /** Light pre-parse for the setup flow (the full parser runs in main()). */
311
333
  function flagValues(argv, flag) {
312
334
  const out = [];
package/dist/config.d.ts CHANGED
@@ -33,6 +33,9 @@ export declare function findConfigFile(root: string): string | null;
33
33
  */
34
34
  export declare function defaultRoot(cwd?: string): string;
35
35
  export declare function loadConfig(root: string, explicitFile?: string): LoadedConfig;
36
+ /** Resolve the project's report folder without creating it. Missing directories
37
+ * inherit the real location of their nearest existing ancestor. */
38
+ export declare function projectReportDirectory(root: string, { config, file }: LoadedConfig): string;
36
39
  export interface BudgetViolation {
37
40
  entryId: string;
38
41
  metric: keyof Budget;
package/dist/config.js CHANGED
@@ -7,6 +7,7 @@ exports.CONFIG_FILE_NAMES = void 0;
7
7
  exports.findConfigFile = findConfigFile;
8
8
  exports.defaultRoot = defaultRoot;
9
9
  exports.loadConfig = loadConfig;
10
+ exports.projectReportDirectory = projectReportDirectory;
10
11
  exports.budgetFor = budgetFor;
11
12
  exports.parseCartridgePath = parseCartridgePath;
12
13
  exports.saveProjectConfig = saveProjectConfig;
@@ -54,6 +55,36 @@ function loadConfig(root, explicitFile) {
54
55
  (0, validate_1.validateConfig)(parsed, file);
55
56
  return { config: parsed, file };
56
57
  }
58
+ /** Resolve the project's report folder without creating it. Missing directories
59
+ * inherit the real location of their nearest existing ancestor. */
60
+ function projectReportDirectory(root, { config, file }) {
61
+ const base = config.reportDirectory && file ? node_path_1.default.dirname(file) : root;
62
+ const dir = node_path_1.default.resolve(base, config.reportDirectory ?? ".sfcc-perf/reports");
63
+ const isOutside = (relative) => relative === ".." || relative.startsWith(".." + node_path_1.default.sep) || node_path_1.default.isAbsolute(relative);
64
+ if (isOutside(node_path_1.default.relative(base, dir))) {
65
+ throw new validate_1.ConfigError([`reportDirectory "${config.reportDirectory}" points outside the project (${base}); use --out-dir for an explicit location`], file ?? "report folder");
66
+ }
67
+ const realBase = node_fs_1.default.realpathSync(base);
68
+ let ancestor = dir;
69
+ for (;;) {
70
+ try {
71
+ const realAncestor = node_fs_1.default.realpathSync(ancestor);
72
+ const realDir = node_path_1.default.resolve(realAncestor, node_path_1.default.relative(ancestor, dir));
73
+ if (isOutside(node_path_1.default.relative(realBase, realDir))) {
74
+ throw new validate_1.ConfigError([`the report folder ${dir} leads outside the project (to ${realDir}); use --out-dir for an explicit location`], file ?? "report folder");
75
+ }
76
+ return dir;
77
+ }
78
+ catch (error) {
79
+ if (error.code !== "ENOENT")
80
+ throw error;
81
+ // An existing symlink with a missing target cannot be resolved safely.
82
+ if (ancestor === node_path_1.default.dirname(ancestor) || node_fs_1.default.lstatSync(ancestor, { throwIfNoEntry: false }))
83
+ throw error;
84
+ ancestor = node_path_1.default.dirname(ancestor);
85
+ }
86
+ }
87
+ }
57
88
  function budgetFor(entryId, budgets) {
58
89
  if (!budgets)
59
90
  return null;
@@ -1 +1,5 @@
1
- export declare const ENGINE_SOURCE_REV = "c09e7ac";
1
+ /**
2
+ * @deprecated The engine is part of this package and versioned with it; use `GENERATOR_VERSION`.
3
+ * (It used to be the web analyzer's commit the engine was copied from.)
4
+ */
5
+ export declare const ENGINE_SOURCE_REV = "sfcc-perf@0.1.1";
@@ -1,4 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ENGINE_SOURCE_REV = void 0;
4
- exports.ENGINE_SOURCE_REV = "c09e7ac";
4
+ const markdown_1 = require("../report/markdown");
5
+ /**
6
+ * @deprecated The engine is part of this package and versioned with it; use `GENERATOR_VERSION`.
7
+ * (It used to be the web analyzer's commit the engine was copied from.)
8
+ */
9
+ exports.ENGINE_SOURCE_REV = `sfcc-perf@${markdown_1.GENERATOR_VERSION}`;
@@ -0,0 +1,4 @@
1
+ import type { FlowEdge, FlowNode } from "./types";
2
+ /** Repositions nodes only - never adds, removes, or rewires an edge. Falls
3
+ * back to BFS depth-from-roots on a cyclic graph rather than throwing. */
4
+ export declare function autoLayout(nodes: FlowNode[], edges: FlowEdge[]): FlowNode[];
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.autoLayout = autoLayout;
4
+ const graphEngine_1 = require("./graphEngine");
5
+ // Generous enough to clear a node card even when its name is long enough
6
+ // that the card grows past its ~210px min-width (the header's `truncate`
7
+ // only bites once a flex ancestor constrains the width, which the
8
+ // unconstrained outer card currently doesn't) - spacing is the cheaper,
9
+ // more robust guard against overlap than assuming a fixed card size.
10
+ const X_STEP = 320;
11
+ const Y_STEP = 170;
12
+ function depthFromRoots(nodes, edges) {
13
+ const { outgoing, incoming } = (0, graphEngine_1.buildAdjacency)(nodes, edges);
14
+ const depth = new Map();
15
+ const roots = nodes.filter((n) => (incoming.get(n.id)?.length ?? 0) === 0);
16
+ const queue = roots.length > 0 ? roots.map((n) => n.id) : nodes.length > 0 ? [nodes[0].id] : [];
17
+ for (const id of queue)
18
+ depth.set(id, 0);
19
+ while (queue.length > 0) {
20
+ const id = queue.shift();
21
+ const d = depth.get(id) ?? 0;
22
+ for (const e of outgoing.get(id) ?? []) {
23
+ const existing = depth.get(e.target);
24
+ if (existing === undefined || d + 1 > existing) {
25
+ depth.set(e.target, d + 1);
26
+ queue.push(e.target);
27
+ }
28
+ }
29
+ }
30
+ for (const n of nodes)
31
+ if (!depth.has(n.id))
32
+ depth.set(n.id, 0);
33
+ return depth;
34
+ }
35
+ /** Repositions nodes only - never adds, removes, or rewires an edge. Falls
36
+ * back to BFS depth-from-roots on a cyclic graph rather than throwing. */
37
+ function autoLayout(nodes, edges) {
38
+ const depth = depthFromRoots(nodes, edges);
39
+ const byDepth = new Map();
40
+ for (const n of nodes) {
41
+ const d = depth.get(n.id) ?? 0;
42
+ if (!byDepth.has(d))
43
+ byDepth.set(d, []);
44
+ byDepth.get(d).push(n.id);
45
+ }
46
+ const positions = new Map();
47
+ for (const [d, ids] of byDepth) {
48
+ const count = ids.length;
49
+ ids.forEach((id, i) => {
50
+ const y = (i - (count - 1) / 2) * Y_STEP;
51
+ positions.set(id, { x: d * X_STEP, y });
52
+ });
53
+ }
54
+ return nodes.map((n) => ({ ...n, position: positions.get(n.id) ?? n.position }));
55
+ }
@@ -0,0 +1,30 @@
1
+ import type { OperationCategory } from "./types";
2
+ import type { FlowEdge, FlowNode, ModelDefaultsState } from "./types";
3
+ export type TimelineRow = {
4
+ nodeId: string;
5
+ name: string;
6
+ start: number;
7
+ end: number;
8
+ isAsync: boolean;
9
+ isBackground: boolean;
10
+ branch: "hit" | "miss" | null;
11
+ onCriticalPath: boolean;
12
+ category: OperationCategory;
13
+ };
14
+ export type Timeline = {
15
+ rows: TimelineRow[];
16
+ httpResponseMs: number;
17
+ maxEnd: number;
18
+ };
19
+ /**
20
+ * Waterfall data for the single worst-case (highest `max`-field latency)
21
+ * path through the graph. Bar widths use `avg`, not `max`, so the trace
22
+ * reads as the shape of the slow path, at normal speed - the `max` field is
23
+ * only used to pick *which* path to draw.
24
+ *
25
+ * evaluateEndpointField's recursion shape depends only on the graph, not on
26
+ * which metric field is being evaluated, so completedPaths[i] refers to the
27
+ * identical node sequence across different field calls - the same index can
28
+ * be reused to pull the `avg`-field per-node contributions for that path.
29
+ */
30
+ export declare function computeTimeline(nodes: FlowNode[], edges: FlowEdge[], modelDefaults: ModelDefaultsState, rootId: string, criticalPathIds: string[]): Timeline | null;
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.computeTimeline = computeTimeline;
4
+ const semantics_1 = require("./semantics");
5
+ const graphEngine_1 = require("./graphEngine");
6
+ const pathEngine_1 = require("./pathEngine");
7
+ /**
8
+ * Waterfall data for the single worst-case (highest `max`-field latency)
9
+ * path through the graph. Bar widths use `avg`, not `max`, so the trace
10
+ * reads as the shape of the slow path, at normal speed - the `max` field is
11
+ * only used to pick *which* path to draw.
12
+ *
13
+ * evaluateEndpointField's recursion shape depends only on the graph, not on
14
+ * which metric field is being evaluated, so completedPaths[i] refers to the
15
+ * identical node sequence across different field calls - the same index can
16
+ * be reused to pull the `avg`-field per-node contributions for that path.
17
+ */
18
+ function computeTimeline(nodes, edges, modelDefaults, rootId, criticalPathIds) {
19
+ const { nodes: scoped, edges: scopedEdges } = (0, graphEngine_1.reachableSubgraph)(nodes, edges, [rootId]);
20
+ if (scoped.length === 0)
21
+ return null;
22
+ const maxResult = (0, pathEngine_1.evaluateEndpointField)(nodes, edges, modelDefaults, rootId, "max");
23
+ if (maxResult.completedPaths.length === 0)
24
+ return null;
25
+ let worstIdx = 0;
26
+ maxResult.completedPaths.forEach((p, i) => {
27
+ if (p.latency > maxResult.completedPaths[worstIdx].latency)
28
+ worstIdx = i;
29
+ });
30
+ const avgResult = (0, pathEngine_1.evaluateEndpointField)(nodes, edges, modelDefaults, rootId, "avg");
31
+ const worstPath = avgResult.completedPaths[worstIdx];
32
+ const stepMs = avgResult.stepMs[worstIdx];
33
+ if (!worstPath)
34
+ return null;
35
+ const nodesById = new Map(scoped.map((n) => [n.id, n]));
36
+ const { incoming } = (0, graphEngine_1.buildAdjacency)(scoped, scopedEdges);
37
+ let cursor = 0;
38
+ let httpResponseMs = 0;
39
+ const rows = worstPath.nodeIds
40
+ .map((nodeId, i) => {
41
+ const node = nodesById.get(nodeId);
42
+ if (!node)
43
+ return null;
44
+ const hasIncoming = (incoming.get(nodeId)?.length ?? 0) > 0;
45
+ const isAsync = (0, semantics_1.getExecutionSemantics)(node, hasIncoming).kind === "async";
46
+ const width = stepMs[i] ?? 0;
47
+ const start = cursor;
48
+ const end = start + width;
49
+ const prevId = i > 0 ? worstPath.nodeIds[i - 1] : null;
50
+ const inboundEdge = prevId ? scopedEdges.find((e) => e.source === prevId && e.target === nodeId) : undefined;
51
+ const branch = inboundEdge?.sourceHandle === "hit" ? "hit" : inboundEdge?.sourceHandle === "miss" ? "miss" : null;
52
+ if (!isAsync) {
53
+ cursor = end;
54
+ httpResponseMs = end;
55
+ }
56
+ return {
57
+ nodeId,
58
+ name: node.data.name,
59
+ start,
60
+ end,
61
+ isAsync,
62
+ isBackground: isAsync,
63
+ branch,
64
+ onCriticalPath: criticalPathIds.includes(nodeId),
65
+ category: node.data.category,
66
+ };
67
+ })
68
+ .filter((r) => r !== null);
69
+ const maxEnd = Math.max(httpResponseMs, ...rows.map((r) => r.end), 0);
70
+ return { rows, httpResponseMs, maxEnd };
71
+ }
@@ -0,0 +1,90 @@
1
+ import type { FlowEdge, FlowNode, ModelDefaultsState, SfccModelingMode } from "../engine/types";
2
+ /**
3
+ * Reads either this tool's own "Export JSON" file or a Markdown trace report
4
+ * from the sfcc-perf npm package (formerly sfcc-performance-analyser) / VS Code extension (which
5
+ * embed the same JSON between `sfcc-perf-model` markers), validates it, and
6
+ * returns a model the store can load.
7
+ */
8
+ export type ImportedTraceMeta = {
9
+ generator?: string;
10
+ generatedAt?: string;
11
+ entry?: {
12
+ id: string;
13
+ kind?: string;
14
+ label?: string;
15
+ httpMethod?: string | null;
16
+ };
17
+ cartridgePath?: string;
18
+ summary?: {
19
+ averageMs?: number;
20
+ p50Ms?: number | null;
21
+ p95Ms?: number | null;
22
+ p99Ms?: number | null;
23
+ minMs?: number;
24
+ maxMs?: number;
25
+ criticalPathMs?: number;
26
+ operationCount?: number;
27
+ };
28
+ coverage?: {
29
+ complete?: boolean;
30
+ issues?: {
31
+ kind: string;
32
+ blocking: boolean;
33
+ message: string;
34
+ file?: string;
35
+ line?: number;
36
+ }[];
37
+ };
38
+ /** Findings from reading the code, carried over from the report (the graph rules are recomputed live). */
39
+ codeFindings?: CodeFinding[];
40
+ /** Set on a model exported from the viewer: when, and whether it differs from the report it was opened from. */
41
+ exported?: {
42
+ at: string;
43
+ edited: boolean;
44
+ };
45
+ engineRev?: string;
46
+ };
47
+ export type CodeFinding = {
48
+ id: string;
49
+ title: string;
50
+ severity: "info" | "warning";
51
+ detail: string;
52
+ why: string;
53
+ locations: {
54
+ file: string;
55
+ line?: number;
56
+ }[];
57
+ };
58
+ export type ImportedModel = {
59
+ mode: SfccModelingMode | null;
60
+ nodes: FlowNode[];
61
+ edges: FlowEdge[];
62
+ modelDefaults: ModelDefaultsState;
63
+ activeRootId: string | null;
64
+ meta: ImportedTraceMeta | null;
65
+ source: "markdown" | "json";
66
+ };
67
+ export type ImportSummary = {
68
+ label: string;
69
+ operations: number;
70
+ averageMs: number;
71
+ reportAverageMs: number | null;
72
+ };
73
+ export type ImportResult = {
74
+ ok: true;
75
+ model: ImportedModel;
76
+ summary: ImportSummary;
77
+ warnings: string[];
78
+ } | {
79
+ ok: false;
80
+ error: string;
81
+ problems: string[];
82
+ };
83
+ export declare const MAX_IMPORT_BYTES: number;
84
+ /** Checks a picked/dropped file before reading it. Returns problems (empty = fine). */
85
+ export declare function checkImportFile(file: {
86
+ name: string;
87
+ size: number;
88
+ type?: string;
89
+ }): string[];
90
+ export declare function parseImportedModel(text: string): ImportResult;