sfcc-perf 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +61 -0
- package/LICENSE +21 -0
- package/README.md +179 -2
- package/dist/analyze.d.ts +66 -0
- package/dist/analyze.js +116 -0
- package/dist/cli.d.ts +9 -0
- package/dist/cli.js +369 -0
- package/dist/config.d.ts +53 -0
- package/dist/config.js +113 -0
- package/dist/data/benchmarks.d.ts +16 -0
- package/dist/data/benchmarks.js +21 -0
- package/dist/engine/ENGINE_VERSION.d.ts +1 -0
- package/dist/engine/ENGINE_VERSION.js +4 -0
- package/dist/engine/analyzeEndpoint.d.ts +23 -0
- package/dist/engine/analyzeEndpoint.js +197 -0
- package/dist/engine/benchmarkEngine.d.ts +18 -0
- package/dist/engine/benchmarkEngine.js +25 -0
- package/dist/engine/configuredProfile.d.ts +8 -0
- package/dist/engine/configuredProfile.js +137 -0
- package/dist/engine/defaults.d.ts +25 -0
- package/dist/engine/defaults.js +133 -0
- package/dist/engine/diagnostics.d.ts +20 -0
- package/dist/engine/diagnostics.js +259 -0
- package/dist/engine/exportMermaid.d.ts +2 -0
- package/dist/engine/exportMermaid.js +61 -0
- package/dist/engine/graphEngine.d.ts +19 -0
- package/dist/engine/graphEngine.js +80 -0
- package/dist/engine/jobEngine.d.ts +25 -0
- package/dist/engine/jobEngine.js +34 -0
- package/dist/engine/latencyEngine.d.ts +24 -0
- package/dist/engine/latencyEngine.js +60 -0
- package/dist/engine/nodeFactory.d.ts +4 -0
- package/dist/engine/nodeFactory.js +73 -0
- package/dist/engine/pathEngine.d.ts +32 -0
- package/dist/engine/pathEngine.js +232 -0
- package/dist/engine/provenance.d.ts +14 -0
- package/dist/engine/provenance.js +33 -0
- package/dist/engine/semantics.d.ts +15 -0
- package/dist/engine/semantics.js +57 -0
- package/dist/engine/types.d.ts +220 -0
- package/dist/engine/types.js +2 -0
- package/dist/engine/validateGraph.d.ts +2 -0
- package/dist/engine/validateGraph.js +56 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +56 -0
- package/dist/report/markdown.d.ts +59 -0
- package/dist/report/markdown.js +276 -0
- package/dist/report/staticFindings.d.ts +20 -0
- package/dist/report/staticFindings.js +103 -0
- package/dist/setup.d.ts +22 -0
- package/dist/setup.js +121 -0
- package/dist/show.d.ts +21 -0
- package/dist/show.js +156 -0
- package/dist/trace/apiCatalog.d.ts +40 -0
- package/dist/trace/apiCatalog.js +173 -0
- package/dist/trace/buildModel.d.ts +39 -0
- package/dist/trace/buildModel.js +197 -0
- package/dist/trace/entries.d.ts +39 -0
- package/dist/trace/entries.js +422 -0
- package/dist/trace/parse.d.ts +19 -0
- package/dist/trace/parse.js +154 -0
- package/dist/trace/tracer.d.ts +283 -0
- package/dist/trace/tracer.js +1476 -0
- package/dist/trace/workspace.d.ts +61 -0
- package/dist/trace/workspace.js +248 -0
- package/dist/validate.d.ts +24 -0
- package/dist/validate.js +176 -0
- package/dist/viewer/THIRD_PARTY_NOTICES.md +1184 -0
- package/dist/viewer/viewer.css +1 -0
- package/dist/viewer/viewer.js +67 -0
- package/package.json +83 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
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
|
+
|
|
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.
|
|
8
|
+
- Every run that writes a report ends with the `npx sfcc-perf show …` command for it; `--open` traces and opens in one step.
|
|
9
|
+
- **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
|
+
- a constant index into a literal array is followed (`handlers[0]()`);
|
|
11
|
+
- a runtime key into a literal array/object whose members are all visible functions traces each member as an equal-share alternative (`routes[key]()`, `var h = list[i]; h()`, `list.forEach(function (h) { h(); })`);
|
|
12
|
+
- `make()()` traces the function `make` returns;
|
|
13
|
+
- anything else picked at runtime (`handlers[name]()` on a parameter, `list[0]()`, an unknown call result, `ProductMgr[method]()`) is a new blocking coverage issue, `dynamic-call`, with its file and line, so `--strict` exits 3.
|
|
14
|
+
- Constructed method names on platform objects (`image['get' + kind + 'URL']()`) and cost-free platform classes (`URLUtils[fn]()`) are not flagged.
|
|
15
|
+
- Docs: the CI example installs the package and uses the committed config; "complete" is documented as coverage of supported constructs.
|
|
16
|
+
- **Evaluation budget shared with the web analyzer.** The engine now counts paths exactly (without expanding them) and refuses models over 20,000 paths or 2,000,000 path steps across all evaluations, with the same message on the site and in the CLI, so every report the CLI writes can be imported. New API exports: `checkEvaluationBudget`, `evaluationCost`, `MAX_EVALUATION_PATHS`, `MAX_EVALUATION_WORK` (`MAX_MODEL_PATHS` is kept as an alias).
|
|
17
|
+
- `prepack` builds the package, so `npm pack` can't ship a stale `dist`.
|
|
18
|
+
|
|
19
|
+
## Earlier releases, as `sfcc-performance-analyser`
|
|
20
|
+
|
|
21
|
+
## 0.2.0
|
|
22
|
+
|
|
23
|
+
**Breaking: a cartridge path is now required.** It decides which cartridge overrides which, so it is never guessed from folder names any more.
|
|
24
|
+
|
|
25
|
+
- Give it with `--cartridge-path "a:b:c"` (as in Business Manager), `cartridgePath` in `.sfcc-perf.json`, or the VS Code setting. In a terminal you're asked the first time (a `site.xml` value is offered as the default) and can save it; `sfcc-perf init` sets it any time. In CI / with `--json` / `--no-prompt` a missing path exits 1 with instructions.
|
|
26
|
+
- The API (`runAnalysis`, `createSession`) now reads `.sfcc-perf.json`; options override it. A missing path throws `MissingCartridgePathError`.
|
|
27
|
+
- VS Code: asks for the path on first use, then keeps it in `.sfcc-perf.json`, workspace settings, or for one run; new *Set Cartridge Path…* command.
|
|
28
|
+
- Run from a subfolder (e.g. inside a cartridge) and the nearest `.sfcc-perf.json` above it is used as the project root.
|
|
29
|
+
- A folder with no cartridges says so instead of asking for a path; if `.sfcc-perf.json` can't be written (read-only checkout) the answer is used for that run only; cartridges on the path that aren't in the workspace are listed when a report runs.
|
|
30
|
+
- `module.superModule` with no base cartridge below it on the path is now an incomplete trace (`missing-super-module`) instead of a silently smaller model.
|
|
31
|
+
|
|
32
|
+
Fixes from testing on real SFRA and SiteGenesis codebases:
|
|
33
|
+
|
|
34
|
+
- **Fixed: crash "Cannot read properties of undefined (reading 'includes')"** on code using `.toString()`, `.valueOf()`, `.constructor`, … (0.1.0-0.1.2). Catalog lookups no longer match built-in object properties.
|
|
35
|
+
- DemandwareScript type annotations (`var x : String`, `function f(a : Number) : Boolean`) now parse, in `.ds` and `.js` files.
|
|
36
|
+
- Followed: `exports.x = obj.fn.bind(obj)`, `module.exports = new Ctor()` exports, methods calling each other through `this`, middleware exported as a whole module through index files (Babel-compiled `_require.x`), SiteGenesis `guard.ensure([...], action)` controllers, `ISML.renderTemplate` / `app.getView().render`, and `require('modules/…')` / bare requires from the global `modules` folder.
|
|
37
|
+
- Hooks: a name built at runtime (`'app.payment.processor.' + id`, `.concat(…)`, via a variable) fans out to every registered hook with that prefix that implements the function; a function name chosen at runtime fans out to every function the hook exports.
|
|
38
|
+
- Default call depth raised from 12 to 20 (deep SFRA model/decorator chains).
|
|
39
|
+
- Clearer errors (job modules in cartridges that aren't in the repo, files the parser can't read such as E4X XML); `--debug` prints stack traces; `--list` notes pipeline files, which aren't traced.
|
|
40
|
+
|
|
41
|
+
## 0.1.2
|
|
42
|
+
|
|
43
|
+
Fixes from a code review. **Results can change** compared with 0.1.0/0.1.1 — mostly they become more correct.
|
|
44
|
+
|
|
45
|
+
- **Fixed: wrong callbacks from cached traces.** A helper that calls a callback (`invoke(cb)`) was cached once and reused for every caller, so later entries — or later calls in the same route — could show the first caller's work. Traces are now cached per call (closure + arguments), never when cut off by the depth limit, and every analysis starts from fresh state (no leaking of coverage or guessed template names between entries in `--all` runs).
|
|
46
|
+
- **Fixed: branch probabilities.** With `conditionalProbability` p, an `if` branch now gets p and its `else` 1 − p (previously both got p); ternaries likewise; `switch` cases get equal shares that add up to 1; code after an unconditional `return`/`throw` is no longer modeled; after `if (…) { work; return }` the rest of the function gets 1 − p.
|
|
47
|
+
- **New: trace completeness.** Results report `coverage.complete` and `coverage.issues` (unresolved requires/middleware, depth limit, parse errors, dynamic hooks/templates). Reports show a warning and a *Trace completeness* section; `--json` adds `complete` and `coverageIssues`; `--strict` / `"strict": true` exits **3** for incomplete traces.
|
|
48
|
+
- **Changed: missing implementations are errors.** A Custom API endpoint, hook function or job step function that isn't exported now fails (exit 1) instead of producing an empty model that could pass a budget.
|
|
49
|
+
- **New: validation.** Options, `.sfcc-perf.json` (unknown keys, ranges, operation types, budget metrics, percentile ordering) and CLI numbers (`Infinity`, out-of-range values) are validated; errors list every problem. `reportDirectory` must stay inside the project.
|
|
50
|
+
- **Changed: P50/P95/P99 are labelled as path-weighted scores**, not statistical percentiles, in reports, JSON and help.
|
|
51
|
+
- **New: model size guard.** Models with more than 20,000 distinct paths are refused with a clear message instead of exhausting memory.
|
|
52
|
+
- **Dev:** Vitest 4, esbuild 0.28 (clears the dev-tool advisories); the engine sync marks copies of uncommitted engine changes as `-dirty`.
|
|
53
|
+
|
|
54
|
+
## 0.1.1
|
|
55
|
+
|
|
56
|
+
- Package no longer ships source maps (`.js.map` / `.d.ts.map`). They pointed at TypeScript sources that aren't published, so they only added size — the package is about half as big.
|
|
57
|
+
- No behaviour changes.
|
|
58
|
+
|
|
59
|
+
## 0.1.0
|
|
60
|
+
|
|
61
|
+
- First release: static tracing of SFRA routes, SCAPI Custom APIs, hooks, job steps and functions; latency model using the SFCC Performance Analyzer engine; Markdown report with an embedded model the web tool imports; `sfcc-perf` CLI with `--all`, `--json`, budgets and `.sfcc-perf.json`; typed API.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Rahul Anand
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,180 @@
|
|
|
1
|
-
#
|
|
1
|
+
# sfcc-perf
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**SFCC Performance Analyser** - statically traces Salesforce B2C Commerce (SFCC) endpoints **through your own cartridge code**, builds a latency model with the same engine as the [SFCC Performance Analyzer](https://www.rahulpunitanand.com/tools/sfcc-performance-analyzer) web tool, writes a Markdown report, and opens it in that same analyzer **on your machine** - waterfall, flow, outline, findings, what-if edits - with nothing uploaded.
|
|
4
|
+
|
|
5
|
+
It's static analysis: nothing runs on a sandbox, no credentials needed. Point it at the repository that contains your cartridges.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npx sfcc-perf init # paste your cartridge path from Business Manager
|
|
9
|
+
npx sfcc-perf --list
|
|
10
|
+
npx sfcc-perf Product-Show --out reports/Product-Show.md
|
|
11
|
+
npx sfcc-perf show reports/Product-Show.md # open it in the analyzer, locally
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Those commands work straight away with `npx`. To pin a version for your team and CI, add it to the repository:
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install --save-dev sfcc-perf
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
> Formerly published as `sfcc-performance-analyser`. Replace that dependency with `sfcc-perf`; the command (`sfcc-perf`), config file and report format are unchanged, and older reports still import into the web tool.
|
|
21
|
+
|
|
22
|
+
## Cartridge path (required)
|
|
23
|
+
|
|
24
|
+
The cartridge path decides which cartridge overrides which, so it is **required and never guessed** - a repo can contain dozens of cartridges, and several sites. Use the exact colon-separated list from *Business Manager › Administration › Sites › Manage Sites › <site> › Settings › Cartridges*:
|
|
25
|
+
|
|
26
|
+
- **Interactively:** the first time you run it in a terminal without one, you're asked for it (a `site.xml` value in the repo is offered as the default) and can save it to `.sfcc-perf.json`. `sfcc-perf init` asks again any time.
|
|
27
|
+
- **In CI / scripts:** commit the `.sfcc-perf.json` that `init` writes, or pass `--cartridge-path "app_custom:int_payment:app_storefront_base"`. Without either, the command exits 1 with instructions - it never stops to ask when there's no terminal, in CI, with `--json` or `--no-prompt`.
|
|
28
|
+
|
|
29
|
+
Cartridges on the path that aren't in the repo are skipped with a note; cartridge folders that aren't on the path are ignored.
|
|
30
|
+
|
|
31
|
+
Where it runs from: the nearest folder (the current one or above) with a `.sfcc-perf.json` is the project root, so running it inside a cartridge folder still uses the saved path. Without a config file it scans the current folder, or `--root <folder>`. A folder with no cartridges (folders containing a `cartridge/` directory) stops with that message instead of asking for a path. If `.sfcc-perf.json` can't be written (read-only checkout), the path you typed is used for that run only.
|
|
32
|
+
|
|
33
|
+
A controller using `module.superModule` needs the cartridge below it on the path (usually `app_storefront_base`). If that cartridge is missing, the report is marked as an incomplete trace, not passed off as a smaller model.
|
|
34
|
+
|
|
35
|
+
## What it traces
|
|
36
|
+
|
|
37
|
+
| Entry | Example id |
|
|
38
|
+
|---|---|
|
|
39
|
+
| SFRA controller route | `Product-Show` |
|
|
40
|
+
| SCAPI Custom API endpoint | `api:loyalty/getPoints` |
|
|
41
|
+
| OCAPI / SCAPI / custom hook | `hook:dw.ocapi.shop.basket.beforePATCH` |
|
|
42
|
+
| Job step (`steptypes.json`) | `job:custom.ExportOrders` |
|
|
43
|
+
| Any function | `cartridges/app_x/cartridge/scripts/foo.js#bar` |
|
|
44
|
+
|
|
45
|
+
It resolves the cartridge path, SFRA `extend`/`append`/`prepend`/`replace` chains, `*/cartridge/…` and `module.superModule` requires, helpers, models, `hooks.json` hooks, Service Framework calls (with timeouts from `services.xml`), `Transaction.wrap`, `CacheMgr` caches, the page cache, ISML remote includes / slots / content assets, branches and loops. Each SFCC API call becomes one of the web tool's operation blocks.
|
|
46
|
+
|
|
47
|
+
## CLI
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
sfcc-perf --list # every traceable entry point
|
|
51
|
+
sfcc-perf Product-Show # Markdown report to stdout
|
|
52
|
+
sfcc-perf Product-Show --out perf/Product-Show.md # … to a file
|
|
53
|
+
sfcc-perf Product-Show Cart-AddProduct --out-dir perf
|
|
54
|
+
sfcc-perf --all --json # every entry, JSON summary, reports in .sfcc-perf/reports
|
|
55
|
+
sfcc-perf --all --max-p95 900 # exit 2 if any modeled P95 score > 900 ms
|
|
56
|
+
sfcc-perf --all --strict # exit 3 if any trace is incomplete
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Run `sfcc-perf --help` for all options.
|
|
60
|
+
|
|
61
|
+
### Open a report locally
|
|
62
|
+
|
|
63
|
+
Every run that writes a report ends with the command to open it:
|
|
64
|
+
|
|
65
|
+
```text
|
|
66
|
+
✓ Product-Show: avg 507.1 ms · p95 1018.1 ms · 18 ops → reports/Product-Show.md
|
|
67
|
+
|
|
68
|
+
Open it in the analyzer (locally, offline):
|
|
69
|
+
npx sfcc-perf show reports/Product-Show.md
|
|
70
|
+
```
|
|
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.
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
sfcc-perf show # the newest report in the report folder
|
|
76
|
+
sfcc-perf show perf/Cart-Show.md --out cart.html --no-open
|
|
77
|
+
sfcc-perf Product-Show --open # trace, write the .md and .html, open it
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
In CI (`CI` set) or with `--no-open` / `SFCC_PERF_NO_OPEN=1` it only writes the file.
|
|
81
|
+
|
|
82
|
+
| Exit code | Meaning |
|
|
83
|
+
|---|---|
|
|
84
|
+
| 0 | OK |
|
|
85
|
+
| 1 | An entry couldn't be traced (unknown route, missing implementation, invalid options/config, …) |
|
|
86
|
+
| 2 | A latency budget was exceeded |
|
|
87
|
+
| 3 | `--strict` (or `"strict": true`) and a trace is incomplete |
|
|
88
|
+
|
|
89
|
+
### Trace completeness
|
|
90
|
+
|
|
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.
|
|
92
|
+
|
|
93
|
+
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
|
+
|
|
95
|
+
*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
|
+
|
|
97
|
+
### CI example (GitHub Actions)
|
|
98
|
+
|
|
99
|
+
Commit the `.sfcc-perf.json` that `sfcc-perf init` writes (or pass `--cartridge-path`), and add the package as a dev dependency:
|
|
100
|
+
|
|
101
|
+
```yaml
|
|
102
|
+
- uses: actions/setup-node@v4
|
|
103
|
+
with: { node-version: 20 }
|
|
104
|
+
- run: npm ci # sfcc-perf is in devDependencies
|
|
105
|
+
- run: npx sfcc-perf --all --strict --json > perf-summary.json
|
|
106
|
+
- uses: actions/upload-artifact@v4
|
|
107
|
+
if: always()
|
|
108
|
+
with: { name: sfcc-perf-reports, path: .sfcc-perf/reports }
|
|
109
|
+
```
|
|
110
|
+
|
|
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"`.
|
|
112
|
+
|
|
113
|
+
## Config file
|
|
114
|
+
|
|
115
|
+
`.sfcc-perf.json` in the repository root is read by the CLI, the API (`runAnalysis` / `createSession`) and the VS Code extension. The file is validated: unknown keys, out-of-range numbers, unknown operation types or budget metrics, and latency profiles whose percentiles are out of order are all reported as errors.
|
|
116
|
+
|
|
117
|
+
```json
|
|
118
|
+
{
|
|
119
|
+
"cartridgePath": "app_custom:int_payment:app_storefront_base",
|
|
120
|
+
"conditionalProbability": 0.5,
|
|
121
|
+
"loopIterations": 5,
|
|
122
|
+
"cacheHitRate": 0.8,
|
|
123
|
+
"maxDepth": 20,
|
|
124
|
+
"scanTemplates": true,
|
|
125
|
+
"latencyOverrides": { "serviceFrameworkCall": { "avg": 350, "p95": 900, "p99": 1200 } },
|
|
126
|
+
"reportDirectory": "perf-reports",
|
|
127
|
+
"strict": true,
|
|
128
|
+
"entries": ["Product-Show", "Search-Show", "Cart-AddProduct", "api:loyalty/getPoints"],
|
|
129
|
+
"budgets": {
|
|
130
|
+
"Product-Show": { "avg": 400, "p95": 900 },
|
|
131
|
+
"*": { "p95": 1500 }
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
Command-line flags override the file. `reportDirectory` must stay inside the project (use `--out-dir` for anywhere else). Budget metrics are `avg`, `p95`, `p99` and `max`.
|
|
137
|
+
|
|
138
|
+
## API
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
import fs from "node:fs";
|
|
142
|
+
import { runAnalysis, renderMarkdown, listEntryPoints, createSession, checkBudget } from "sfcc-perf";
|
|
143
|
+
|
|
144
|
+
const run = runAnalysis(["/path/to/repo"], "Product-Show"); // uses .sfcc-perf.json - or pass { cartridgePath: "…" }
|
|
145
|
+
run.analysis.averageLatency; // modeled average (ms)
|
|
146
|
+
run.analysis.p95; // path-weighted P95 score (see note below)
|
|
147
|
+
run.coverage.complete; // false if the tracer had to skip something
|
|
148
|
+
run.coverage.issues; // what was skipped and why
|
|
149
|
+
run.model.nodes; // the web tool's node/edge model
|
|
150
|
+
run.findings, run.staticFindings; // engine findings + code findings
|
|
151
|
+
fs.writeFileSync("Product-Show.md", renderMarkdown(run, { reportDir: "." }));
|
|
152
|
+
|
|
153
|
+
// Several entries with one parsed workspace (reads .sfcc-perf.json; options override it):
|
|
154
|
+
const { ws, tracer, opts } = createSession(["/path/to/repo"], { cartridgePath: "app_custom:app_storefront_base" });
|
|
155
|
+
for (const e of listEntryPoints(ws, tracer)) console.log(e.id, e.detail);
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Types are included. Options are validated at runtime; invalid values throw a `ConfigError` listing every problem, and a missing cartridge path throws `MissingCartridgePathError` (with the cartridge folders found). Each `analyzeWith` call starts from fresh trace state, so results don't depend on which entries a session analysed before.
|
|
159
|
+
|
|
160
|
+
## The report
|
|
161
|
+
|
|
162
|
+
Summary (average, P50/P95/P99, best/worst case, critical path, cache hit vs miss, reference range), the middleware chain, every operation with its source `file:line`, how often it runs and its share, the top contributors, findings (the web tool's rules plus code findings: N+1 in loops, raw `HTTPClient`, writes in GET, uncached rendered pages, missing service timeouts, full catalog scans), the call tree, a Mermaid flow, assumptions and coverage, and the embedded model the web tool imports (between `<!-- sfcc-perf-model:begin -->` and `<!-- sfcc-perf-model:end -->`).
|
|
163
|
+
|
|
164
|
+
Open it with `sfcc-perf show` (above), or on the [web analyzer](https://www.rahulpunitanand.com/tools/sfcc-performance-analyzer) click **Import** and choose the `.md`: either way it loads the traced flow, recomputes it with the same engine and shows a *report → now* comparison while you change values.
|
|
165
|
+
|
|
166
|
+
> These are **modeled** numbers built from the web analyzer's illustrative latency defaults, not measurements. Use them to compare designs and find the expensive path, not as SLAs.
|
|
167
|
+
>
|
|
168
|
+
> **About P50/P95/P99:** they are the web analyzer's *path-weighted scores* — each path's percentile profile weighted by how likely the path is — not statistical percentiles of the endpoint's latency distribution. A mix of fast and slow paths has a higher true P95 than this score. Budgets on `p95`/`p99` compare against these scores.
|
|
169
|
+
|
|
170
|
+
## Limits
|
|
171
|
+
|
|
172
|
+
Static analysis can't see runtime values: dynamic `require()` names, functions picked at runtime from containers it can't see, and calls on unknown receivers are skipped (each report's *Trace completeness* section lists what it couldn't resolve, except calls on unknown receivers, which are too common to flag). Branches use one assumed probability (`if` = p, `else` = 1 − p, `switch` cases equal shares) rather than real traffic. Very branchy models (over 20,000 distinct paths, or too much total path length to evaluate in about a second) are refused rather than evaluated slowly - the same limit as the web analyzer. Remote includes are counted at include cost only — trace the included route separately. Legacy XML pipelines are not supported.
|
|
173
|
+
|
|
174
|
+
## Requirements
|
|
175
|
+
|
|
176
|
+
Node.js 18 or newer to run (tested on 18 and 25). Developing the package (tests, build) needs Node 20.19+ or 22.12+ because of the test tooling.
|
|
177
|
+
|
|
178
|
+
## License
|
|
179
|
+
|
|
180
|
+
MIT
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { type BenchmarkComparison } from "./engine/benchmarkEngine";
|
|
2
|
+
import { type SfccFinding } from "./engine/diagnostics";
|
|
3
|
+
import { type JobThroughputResult } from "./engine/jobEngine";
|
|
4
|
+
import type { EndpointAnalysis, LatencyProfile, ModelDefaultsState, OperationType } from "./engine/types";
|
|
5
|
+
import { type ModelBuild } from "./trace/buildModel";
|
|
6
|
+
import { type TraceResult } from "./trace/entries";
|
|
7
|
+
import { type StaticFinding } from "./report/staticFindings";
|
|
8
|
+
import { Tracer, type CoverageIssue, type CoverageKind, type TraceOptions } from "./trace/tracer";
|
|
9
|
+
import { SfccWorkspace } from "./trace/workspace";
|
|
10
|
+
export interface AnalyzeOptions extends TraceOptions {
|
|
11
|
+
cartridgePath: string;
|
|
12
|
+
cacheHitRate: number;
|
|
13
|
+
latencyOverrides: Partial<Record<OperationType, Partial<LatencyProfile>>>;
|
|
14
|
+
}
|
|
15
|
+
export declare const DEFAULT_OPTIONS: AnalyzeOptions;
|
|
16
|
+
/** Coverage kinds that mean the model is probably missing work (fail under --strict). */
|
|
17
|
+
export declare const BLOCKING_COVERAGE: ReadonlySet<CoverageKind>;
|
|
18
|
+
export interface Coverage {
|
|
19
|
+
/** True when nothing on the traced path was skipped. */
|
|
20
|
+
complete: boolean;
|
|
21
|
+
/** Everything the tracer could not follow (blocking and informational). */
|
|
22
|
+
issues: (CoverageIssue & {
|
|
23
|
+
blocking: boolean;
|
|
24
|
+
})[];
|
|
25
|
+
}
|
|
26
|
+
export interface AnalysisRun {
|
|
27
|
+
ws: SfccWorkspace;
|
|
28
|
+
tracer: Tracer;
|
|
29
|
+
trace: TraceResult;
|
|
30
|
+
model: ModelBuild;
|
|
31
|
+
modelDefaults: ModelDefaultsState;
|
|
32
|
+
analysis: EndpointAnalysis;
|
|
33
|
+
findings: SfccFinding[];
|
|
34
|
+
staticFindings: StaticFinding[];
|
|
35
|
+
benchmark: BenchmarkComparison;
|
|
36
|
+
job: JobThroughputResult | null;
|
|
37
|
+
coverage: Coverage;
|
|
38
|
+
options: AnalyzeOptions;
|
|
39
|
+
generatedAt: Date;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Discovers cartridges once so several entries can be analysed with the same
|
|
43
|
+
* parsed sources. Options come from `.sfcc-perf.json` in the first root
|
|
44
|
+
* (unless `readConfig` is false) overridden by `options`; they are validated
|
|
45
|
+
* here (ConfigError). A cartridge path is required (MissingCartridgePathError).
|
|
46
|
+
*/
|
|
47
|
+
export declare function createSession(roots: string[], options?: Partial<AnalyzeOptions>, { readConfig }?: {
|
|
48
|
+
readConfig?: boolean;
|
|
49
|
+
}): {
|
|
50
|
+
ws: SfccWorkspace;
|
|
51
|
+
tracer: Tracer;
|
|
52
|
+
opts: {
|
|
53
|
+
cartridgePath: string;
|
|
54
|
+
cacheHitRate: number;
|
|
55
|
+
latencyOverrides: Partial<Record<OperationType, Partial<LatencyProfile>>>;
|
|
56
|
+
conditionalProbability: number;
|
|
57
|
+
loopIterations: number;
|
|
58
|
+
maxDepth: number;
|
|
59
|
+
scanTemplates: boolean;
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
export declare function buildModelDefaults(opts: AnalyzeOptions): ModelDefaultsState;
|
|
63
|
+
/** Trace one entry point end to end and evaluate it with the web analyzer's engine. Reads `.sfcc-perf.json`; `options` override it. */
|
|
64
|
+
export declare function runAnalysis(roots: string[], entryId: string, options?: Partial<AnalyzeOptions>): AnalysisRun;
|
|
65
|
+
/** 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;
|
package/dist/analyze.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.BLOCKING_COVERAGE = exports.DEFAULT_OPTIONS = void 0;
|
|
4
|
+
exports.createSession = createSession;
|
|
5
|
+
exports.buildModelDefaults = buildModelDefaults;
|
|
6
|
+
exports.runAnalysis = runAnalysis;
|
|
7
|
+
exports.analyzeWith = analyzeWith;
|
|
8
|
+
const analyzeEndpoint_1 = require("./engine/analyzeEndpoint");
|
|
9
|
+
const benchmarkEngine_1 = require("./engine/benchmarkEngine");
|
|
10
|
+
const defaults_1 = require("./engine/defaults");
|
|
11
|
+
const diagnostics_1 = require("./engine/diagnostics");
|
|
12
|
+
const jobEngine_1 = require("./engine/jobEngine");
|
|
13
|
+
const buildModel_1 = require("./trace/buildModel");
|
|
14
|
+
const entries_1 = require("./trace/entries");
|
|
15
|
+
const staticFindings_1 = require("./report/staticFindings");
|
|
16
|
+
const tracer_1 = require("./trace/tracer");
|
|
17
|
+
const workspace_1 = require("./trace/workspace");
|
|
18
|
+
const config_1 = require("./config");
|
|
19
|
+
const validate_1 = require("./validate");
|
|
20
|
+
exports.DEFAULT_OPTIONS = {
|
|
21
|
+
cartridgePath: "",
|
|
22
|
+
conditionalProbability: 0.5,
|
|
23
|
+
loopIterations: 5,
|
|
24
|
+
maxDepth: 20,
|
|
25
|
+
scanTemplates: true,
|
|
26
|
+
cacheHitRate: 0.8,
|
|
27
|
+
latencyOverrides: {},
|
|
28
|
+
};
|
|
29
|
+
/** 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
|
+
/**
|
|
32
|
+
* Discovers cartridges once so several entries can be analysed with the same
|
|
33
|
+
* parsed sources. Options come from `.sfcc-perf.json` in the first root
|
|
34
|
+
* (unless `readConfig` is false) overridden by `options`; they are validated
|
|
35
|
+
* here (ConfigError). A cartridge path is required (MissingCartridgePathError).
|
|
36
|
+
*/
|
|
37
|
+
function createSession(roots, options = {}, { readConfig = true } = {}) {
|
|
38
|
+
(0, validate_1.validateOptions)(options);
|
|
39
|
+
const fromFile = {};
|
|
40
|
+
if (readConfig && roots[0]) {
|
|
41
|
+
const { config } = (0, config_1.loadConfig)(roots[0]);
|
|
42
|
+
for (const k of Object.keys(exports.DEFAULT_OPTIONS))
|
|
43
|
+
if (config[k] !== undefined)
|
|
44
|
+
fromFile[k] = config[k];
|
|
45
|
+
}
|
|
46
|
+
const opts = { ...exports.DEFAULT_OPTIONS, ...stripUndefined(fromFile), ...stripUndefined(options) };
|
|
47
|
+
const ws = workspace_1.SfccWorkspace.discover(roots, opts.cartridgePath);
|
|
48
|
+
if (ws.allCartridges.length === 0)
|
|
49
|
+
throw new validate_1.ConfigError([`no cartridge folders (folders containing a "cartridge/" directory) found under ${roots.join(", ")} - run it from the repository that contains your cartridges, or pass --root <folder>`], "workspace");
|
|
50
|
+
if (ws.cartridgePathSource === "none")
|
|
51
|
+
throw new validate_1.MissingCartridgePathError(ws.allCartridges, ws.siteXmlSuggestion);
|
|
52
|
+
if (ws.cartridges.length === 0) {
|
|
53
|
+
throw new validate_1.ConfigError([
|
|
54
|
+
`none of the cartridges on the cartridge path are in this workspace (${opts.cartridgePath})`,
|
|
55
|
+
ws.allCartridges.length ? `cartridge folders found here: ${ws.allCartridges.slice(0, 30).join(", ")}${ws.allCartridges.length > 30 ? ", …" : ""}` : `no cartridge folders found under ${roots.join(", ")} - run it from the repository that contains your cartridges, or pass --root`,
|
|
56
|
+
], "cartridge path");
|
|
57
|
+
}
|
|
58
|
+
const tracer = new tracer_1.Tracer(ws, opts);
|
|
59
|
+
return { ws, tracer, opts };
|
|
60
|
+
}
|
|
61
|
+
function stripUndefined(o) {
|
|
62
|
+
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
|
|
63
|
+
}
|
|
64
|
+
function buildModelDefaults(opts) {
|
|
65
|
+
const md = (0, defaults_1.createDefaultModelDefaults)();
|
|
66
|
+
md.cacheHitRate = opts.cacheHitRate;
|
|
67
|
+
for (const [type, patch] of Object.entries(opts.latencyOverrides ?? {})) {
|
|
68
|
+
const key = type;
|
|
69
|
+
if (md.profiles[key] && patch)
|
|
70
|
+
md.profiles[key] = { ...md.profiles[key], ...patch };
|
|
71
|
+
}
|
|
72
|
+
return md;
|
|
73
|
+
}
|
|
74
|
+
/** Trace one entry point end to end and evaluate it with the web analyzer's engine. Reads `.sfcc-perf.json`; `options` override it. */
|
|
75
|
+
function runAnalysis(roots, entryId, options = {}) {
|
|
76
|
+
const { ws, tracer, opts } = createSession(roots, options);
|
|
77
|
+
return analyzeWith(ws, tracer, opts, entryId);
|
|
78
|
+
}
|
|
79
|
+
/** Analyse one entry with an existing session. Each call starts from fresh trace state. */
|
|
80
|
+
function analyzeWith(ws, tracer, opts, entryId) {
|
|
81
|
+
if (ws.cartridges.length === 0)
|
|
82
|
+
throw new Error("No SFCC cartridges found (folders containing a `cartridge/` directory).");
|
|
83
|
+
tracer.beginAnalysis();
|
|
84
|
+
const trace = (0, entries_1.traceEntry)(ws, tracer, entryId);
|
|
85
|
+
const modelDefaults = buildModelDefaults(opts);
|
|
86
|
+
const model = (0, buildModel_1.buildModel)(trace, modelDefaults);
|
|
87
|
+
// Same budget as the web analyzer, so every report the CLI writes can be imported there.
|
|
88
|
+
const overBudget = (0, analyzeEndpoint_1.checkEvaluationBudget)(model.nodes, model.edges, model.rootId);
|
|
89
|
+
if (overBudget) {
|
|
90
|
+
throw new Error(`${entryId}: ${overBudget.message.replace(/^This flow/, "the model")} Usually this comes from many caches or hooks in sequence: lower --max-depth or --loops, or trace a narrower entry.`);
|
|
91
|
+
}
|
|
92
|
+
const analysis = (0, analyzeEndpoint_1.analyzeEndpoint)(model.nodes, model.edges, modelDefaults, model.rootId);
|
|
93
|
+
const findings = (0, diagnostics_1.runSfccDiagnostics)(model.nodes, model.edges, analysis, modelDefaults);
|
|
94
|
+
const benchmark = (0, benchmarkEngine_1.compareToBenchmark)(analysis, trace.presetKey);
|
|
95
|
+
const rootData = model.nodes.find((n) => n.id === model.rootId).data;
|
|
96
|
+
const job = rootData.jobConfig ? (0, jobEngine_1.analyzeJobThroughput)(model.nodes, model.edges, modelDefaults, model.rootId, rootData.jobConfig) : null;
|
|
97
|
+
for (const file of tracer.parseErrorsInRun())
|
|
98
|
+
tracer.addCoverage({ kind: "parse-error", message: `${ws.display(file)} has syntax errors - parts of it may be missing from the trace`, file });
|
|
99
|
+
const issues = tracer.coverage.map((c) => ({ ...c, blocking: exports.BLOCKING_COVERAGE.has(c.kind) }));
|
|
100
|
+
const coverage = { complete: !issues.some((i) => i.blocking), issues };
|
|
101
|
+
return {
|
|
102
|
+
ws,
|
|
103
|
+
tracer,
|
|
104
|
+
trace,
|
|
105
|
+
model,
|
|
106
|
+
modelDefaults,
|
|
107
|
+
analysis,
|
|
108
|
+
findings,
|
|
109
|
+
staticFindings: (0, staticFindings_1.staticFindings)(trace, model, tracer),
|
|
110
|
+
benchmark,
|
|
111
|
+
job,
|
|
112
|
+
coverage,
|
|
113
|
+
options: opts,
|
|
114
|
+
generatedAt: new Date(),
|
|
115
|
+
};
|
|
116
|
+
}
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { type SetupIO } from "./setup";
|
|
3
|
+
/** Runs the CLI and returns its exit code. Errors are printed to stderr, never thrown. */
|
|
4
|
+
export declare function main(argv: string[]): number;
|
|
5
|
+
/**
|
|
6
|
+
* CLI entry: `init`, or the first-run cartridge-path question (only in an
|
|
7
|
+
* interactive terminal, never in CI / --json / with --cartridge-path), then main().
|
|
8
|
+
*/
|
|
9
|
+
export declare function cliEntry(argv: string[], io?: SetupIO, interactive?: boolean): Promise<number>;
|