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.
Files changed (71) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/LICENSE +21 -0
  3. package/README.md +179 -2
  4. package/dist/analyze.d.ts +66 -0
  5. package/dist/analyze.js +116 -0
  6. package/dist/cli.d.ts +9 -0
  7. package/dist/cli.js +369 -0
  8. package/dist/config.d.ts +53 -0
  9. package/dist/config.js +113 -0
  10. package/dist/data/benchmarks.d.ts +16 -0
  11. package/dist/data/benchmarks.js +21 -0
  12. package/dist/engine/ENGINE_VERSION.d.ts +1 -0
  13. package/dist/engine/ENGINE_VERSION.js +4 -0
  14. package/dist/engine/analyzeEndpoint.d.ts +23 -0
  15. package/dist/engine/analyzeEndpoint.js +197 -0
  16. package/dist/engine/benchmarkEngine.d.ts +18 -0
  17. package/dist/engine/benchmarkEngine.js +25 -0
  18. package/dist/engine/configuredProfile.d.ts +8 -0
  19. package/dist/engine/configuredProfile.js +137 -0
  20. package/dist/engine/defaults.d.ts +25 -0
  21. package/dist/engine/defaults.js +133 -0
  22. package/dist/engine/diagnostics.d.ts +20 -0
  23. package/dist/engine/diagnostics.js +259 -0
  24. package/dist/engine/exportMermaid.d.ts +2 -0
  25. package/dist/engine/exportMermaid.js +61 -0
  26. package/dist/engine/graphEngine.d.ts +19 -0
  27. package/dist/engine/graphEngine.js +80 -0
  28. package/dist/engine/jobEngine.d.ts +25 -0
  29. package/dist/engine/jobEngine.js +34 -0
  30. package/dist/engine/latencyEngine.d.ts +24 -0
  31. package/dist/engine/latencyEngine.js +60 -0
  32. package/dist/engine/nodeFactory.d.ts +4 -0
  33. package/dist/engine/nodeFactory.js +73 -0
  34. package/dist/engine/pathEngine.d.ts +32 -0
  35. package/dist/engine/pathEngine.js +232 -0
  36. package/dist/engine/provenance.d.ts +14 -0
  37. package/dist/engine/provenance.js +33 -0
  38. package/dist/engine/semantics.d.ts +15 -0
  39. package/dist/engine/semantics.js +57 -0
  40. package/dist/engine/types.d.ts +220 -0
  41. package/dist/engine/types.js +2 -0
  42. package/dist/engine/validateGraph.d.ts +2 -0
  43. package/dist/engine/validateGraph.js +56 -0
  44. package/dist/index.d.ts +30 -0
  45. package/dist/index.js +56 -0
  46. package/dist/report/markdown.d.ts +59 -0
  47. package/dist/report/markdown.js +276 -0
  48. package/dist/report/staticFindings.d.ts +20 -0
  49. package/dist/report/staticFindings.js +103 -0
  50. package/dist/setup.d.ts +22 -0
  51. package/dist/setup.js +121 -0
  52. package/dist/show.d.ts +21 -0
  53. package/dist/show.js +156 -0
  54. package/dist/trace/apiCatalog.d.ts +40 -0
  55. package/dist/trace/apiCatalog.js +173 -0
  56. package/dist/trace/buildModel.d.ts +39 -0
  57. package/dist/trace/buildModel.js +197 -0
  58. package/dist/trace/entries.d.ts +39 -0
  59. package/dist/trace/entries.js +422 -0
  60. package/dist/trace/parse.d.ts +19 -0
  61. package/dist/trace/parse.js +154 -0
  62. package/dist/trace/tracer.d.ts +283 -0
  63. package/dist/trace/tracer.js +1476 -0
  64. package/dist/trace/workspace.d.ts +61 -0
  65. package/dist/trace/workspace.js +248 -0
  66. package/dist/validate.d.ts +24 -0
  67. package/dist/validate.js +176 -0
  68. package/dist/viewer/THIRD_PARTY_NOTICES.md +1184 -0
  69. package/dist/viewer/viewer.css +1 -0
  70. package/dist/viewer/viewer.js +67 -0
  71. package/package.json +83 -4
package/dist/cli.js ADDED
@@ -0,0 +1,369 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.main = main;
8
+ exports.cliEntry = cliEntry;
9
+ const node_fs_1 = __importDefault(require("node:fs"));
10
+ const node_path_1 = __importDefault(require("node:path"));
11
+ const analyze_1 = require("./analyze");
12
+ const config_1 = require("./config");
13
+ const setup_1 = require("./setup");
14
+ const validate_1 = require("./validate");
15
+ const markdown_1 = require("./report/markdown");
16
+ const entries_1 = require("./trace/entries");
17
+ const show_1 = require("./show");
18
+ const HELP = `sfcc-perf ${markdown_1.GENERATOR_VERSION}
19
+ Static SFCC endpoint trace → latency model + Markdown report for the SFCC Performance Analyzer.
20
+
21
+ Usage:
22
+ sfcc-perf --list list every traceable entry point
23
+ sfcc-perf <entry> [<entry>...] trace entries, print the report (one entry) or write reports
24
+ sfcc-perf --all trace every entry (or "entries" from the config file)
25
+ sfcc-perf init set the cartridge path (as in Business Manager)
26
+ sfcc-perf show [report.md] open a report in the analyzer, locally (see show --help)
27
+
28
+ Entries:
29
+ Product-Show SFRA controller route
30
+ api:<api-name>/<endpoint> SCAPI Custom API endpoint
31
+ hook:<extension.point>[#function] hooks.json extension point
32
+ job:<step-type-id> steptypes.json job step
33
+ path/to/file.js#functionName any exported / top-level function
34
+
35
+ Options:
36
+ --root DIR workspace root (repeatable, default: cwd)
37
+ --config FILE config file (default: .sfcc-perf.json in the first root)
38
+ --cartridge-path P cartridge path as in Business Manager, e.g. "app_custom:int_x:app_storefront_base"
39
+ (required unless "cartridgePath" is in .sfcc-perf.json)
40
+ --no-prompt never ask questions (also when CI or SFCC_PERF_NO_PROMPT=1 is set)
41
+ --out FILE report file (single entry; default: stdout)
42
+ --out-dir DIR report folder for several entries (default: config reportDirectory or .sfcc-perf/reports)
43
+ --open also open the report in the analyzer (writes the .md and .html)
44
+ --json print a JSON summary instead of Markdown
45
+ --max-avg MS fail (exit 2) when a modeled average exceeds MS
46
+ --max-p95 MS fail (exit 2) when the path-weighted P95 score exceeds MS
47
+ --strict fail (exit 3) when the trace is incomplete (unresolved
48
+ requires/middleware, depth limit, parse errors, …)
49
+ --conditional N branch probability (default 0.5)
50
+ --loops N loop iteration assumption (default 5)
51
+ --hit-rate N cache hit rate (default 0.8)
52
+ --max-depth N call depth limit (default 20)
53
+ --no-templates do not scan ISML templates
54
+ --debug print full stack traces for errors (or set SFCC_PERF_DEBUG=1)
55
+
56
+ A cartridge path is required: it decides which cartridge overrides which, so it
57
+ is never guessed. In a terminal you're asked for it the first time (paste it from
58
+ Business Manager › Administration › Sites › Manage Sites › <site> › Settings);
59
+ in CI pass --cartridge-path or commit the .sfcc-perf.json that \`sfcc-perf init\` writes.
60
+ -v, --version print the version
61
+
62
+ Exit codes: 0 ok · 1 error · 2 budget exceeded · 3 incomplete trace (--strict)
63
+
64
+ Note: P50/P95/P99 are path-weighted scores from the web analyzer's model (each
65
+ path's percentile profile weighted by how likely the path is), not statistical
66
+ percentiles of a latency distribution. All values are modeled, not measured.
67
+ `;
68
+ function parseArgs(argv) {
69
+ const a = { roots: [], entries: [], all: false, list: false, json: false, open: false, strict: false, out: null, outDir: null, configFile: undefined, options: {}, cliBudget: {} };
70
+ const num = (flag, v) => (0, validate_1.parseNumberFlag)(flag, v);
71
+ for (let i = 0; i < argv.length; i++) {
72
+ const arg = argv[i];
73
+ const next = () => {
74
+ const v = argv[++i];
75
+ if (v === undefined)
76
+ throw new Error(`${arg} expects a value`);
77
+ return v;
78
+ };
79
+ switch (arg) {
80
+ case "-h":
81
+ case "--help":
82
+ return "help";
83
+ case "-v":
84
+ case "--version":
85
+ return "version";
86
+ case "--list":
87
+ a.list = true;
88
+ break;
89
+ case "--all":
90
+ a.all = true;
91
+ break;
92
+ case "--json":
93
+ a.json = true;
94
+ break;
95
+ case "--strict":
96
+ a.strict = true;
97
+ break;
98
+ case "--open":
99
+ a.open = true;
100
+ break;
101
+ case "--debug":
102
+ break; // handled in main()
103
+ case "--root":
104
+ a.roots.push(node_path_1.default.resolve(next()));
105
+ break;
106
+ case "--config":
107
+ a.configFile = next();
108
+ break;
109
+ case "--out":
110
+ a.out = node_path_1.default.resolve(next());
111
+ break;
112
+ case "--out-dir":
113
+ a.outDir = node_path_1.default.resolve(next());
114
+ break;
115
+ case "--no-prompt":
116
+ break; // handled in cliEntry()
117
+ case "--cartridge-path":
118
+ a.options.cartridgePath = next();
119
+ break;
120
+ case "--conditional":
121
+ a.options.conditionalProbability = num(arg, next());
122
+ break;
123
+ case "--loops":
124
+ a.options.loopIterations = num(arg, next());
125
+ break;
126
+ case "--hit-rate":
127
+ a.options.cacheHitRate = num(arg, next());
128
+ break;
129
+ case "--max-depth":
130
+ a.options.maxDepth = num(arg, next());
131
+ break;
132
+ case "--no-templates":
133
+ a.options.scanTemplates = false;
134
+ break;
135
+ case "--max-avg":
136
+ a.cliBudget.avg = num(arg, next());
137
+ break;
138
+ case "--max-p95":
139
+ a.cliBudget.p95 = num(arg, next());
140
+ break;
141
+ default:
142
+ if (arg.startsWith("-"))
143
+ throw new Error(`Unknown option ${arg} (see --help)`);
144
+ a.entries.push(arg);
145
+ }
146
+ }
147
+ if (a.roots.length === 0)
148
+ a.roots.push((0, config_1.defaultRoot)());
149
+ for (const [k, v] of Object.entries(a.cliBudget))
150
+ if (!(v > 0))
151
+ throw new validate_1.ConfigError([`--max-${k} must be greater than 0 (got ${v})`], "command line");
152
+ return a;
153
+ }
154
+ function summary(run, reportFile, violations) {
155
+ const a = run.analysis;
156
+ const r = (n) => (n === null ? null : Math.round(n * 10) / 10);
157
+ return {
158
+ entry: run.trace.entry.id,
159
+ kind: run.trace.entry.kind,
160
+ averageMs: r(a.averageLatency),
161
+ p50Ms: r(a.p50),
162
+ p95Ms: r(a.p95),
163
+ p99Ms: r(a.p99),
164
+ minMs: r(a.minLatency),
165
+ maxMs: r(a.maxLatency),
166
+ criticalPathMs: r(a.criticalPathTotal),
167
+ operations: run.model.nodes.length - 2,
168
+ findings: run.findings.length + run.staticFindings.length,
169
+ complete: run.coverage.complete,
170
+ coverageIssues: run.coverage.issues.map((i) => ({ kind: i.kind, blocking: i.blocking, message: i.message })),
171
+ report: reportFile,
172
+ budgetViolations: violations,
173
+ };
174
+ }
175
+ const debugEnabled = (argv) => argv.includes("--debug") || /^(1|true|yes)$/i.test(process.env.SFCC_PERF_DEBUG ?? "");
176
+ /** Error text for stderr: the message, plus the stack trace with --debug. Unexpected errors point at --debug and the issue tracker. */
177
+ function describeError(e, debug) {
178
+ const err = e instanceof Error ? e : new Error(String(e));
179
+ if (debug)
180
+ return err.stack ?? err.message;
181
+ if (err instanceof validate_1.ConfigError)
182
+ return err.message;
183
+ const internal = err instanceof TypeError || err instanceof RangeError || err instanceof ReferenceError;
184
+ return internal ? `${err.message}\n (this looks like a bug in sfcc-perf ${markdown_1.GENERATOR_VERSION} - rerun with --debug and include that output when reporting it)` : err.message;
185
+ }
186
+ /** Runs the CLI and returns its exit code. Errors are printed to stderr, never thrown. */
187
+ function main(argv) {
188
+ try {
189
+ if (argv[0] === "show")
190
+ return (0, show_1.showMain)(argv.slice(1));
191
+ return run(argv);
192
+ }
193
+ catch (e) {
194
+ process.stderr.write(`${e instanceof validate_1.ConfigError ? "" : "error: "}${describeError(e, debugEnabled(argv))}\n`);
195
+ return 1;
196
+ }
197
+ }
198
+ function run(argv) {
199
+ const parsed = parseArgs(argv);
200
+ if (parsed === "help") {
201
+ process.stdout.write(HELP);
202
+ return 0;
203
+ }
204
+ if (parsed === "version") {
205
+ process.stdout.write(`${markdown_1.GENERATOR_VERSION}\n`);
206
+ return 0;
207
+ }
208
+ 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;
211
+ 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
+ }
219
+ const { ws, tracer, opts } = (0, analyze_1.createSession)(args.roots, { ...configOptions, ...args.options }, { readConfig: false });
220
+ const pathLabel = args.options.cartridgePath ? "--cartridge-path" : `from ${configFile ? node_path_1.default.basename(configFile) : "config"}`;
221
+ if (args.list || (!args.all && args.entries.length === 0)) {
222
+ const list = (0, entries_1.listEntryPoints)(ws, tracer);
223
+ if (args.json) {
224
+ process.stdout.write(JSON.stringify({ cartridgePath: ws.cartridgePath, cartridgePathSource: ws.cartridgePathSource, entries: list.map((e) => ({ id: e.id, kind: e.kind, detail: e.detail, file: ws.display(e.file) })) }, null, 2) + "\n");
225
+ }
226
+ else {
227
+ process.stdout.write(`Cartridge path (${pathLabel}): ${ws.cartridgePath || "(no cartridges found)"}\n`);
228
+ if (configFile)
229
+ process.stdout.write(`Config: ${configFile}\n`);
230
+ for (const w of ws.warnings)
231
+ process.stdout.write(`Note: ${w}\n`);
232
+ process.stdout.write("\n");
233
+ for (const e of list)
234
+ process.stdout.write(`${e.id.padEnd(50)} ${e.detail}\n`);
235
+ if (!args.list)
236
+ process.stdout.write(`\n${HELP}`);
237
+ }
238
+ return 0;
239
+ }
240
+ if (!args.json)
241
+ for (const w of ws.warnings)
242
+ if (/aren't in this workspace/.test(w))
243
+ process.stderr.write(`Note: ${w}\n`);
244
+ const ids = args.all ? (configEntries?.length ? configEntries : (0, entries_1.listEntryPoints)(ws, tracer).map((e) => e.id)) : args.entries;
245
+ 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
+ const results = [];
248
+ let failed = false;
249
+ let incomplete = false;
250
+ let errors = 0;
251
+ for (const id of ids) {
252
+ let run;
253
+ try {
254
+ run = (0, analyze_1.analyzeWith)(ws, tracer, opts, id);
255
+ }
256
+ catch (e) {
257
+ errors++;
258
+ results.push({ entry: id, error: e.message });
259
+ process.stderr.write(`error: ${id}: ${describeError(e, debugEnabled(argv))}\n`);
260
+ continue;
261
+ }
262
+ 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);
264
+ if (violations.length)
265
+ failed = true;
266
+ let reportFile = null;
267
+ const toStdout = single && !args.out && !args.outDir && !args.json && !args.open;
268
+ if (toStdout) {
269
+ process.stdout.write((0, markdown_1.renderMarkdown)(run));
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`);
273
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(reportFile), { recursive: true });
274
+ node_fs_1.default.writeFileSync(reportFile, (0, markdown_1.renderMarkdown)(run, { reportDir: node_path_1.default.dirname(reportFile) }));
275
+ }
276
+ const s = summary(run, reportFile, violations);
277
+ results.push(s);
278
+ if (!args.json && !toStdout) {
279
+ 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`);
280
+ }
281
+ for (const v of violations)
282
+ process.stderr.write(` budget exceeded: ${v.metric} ${Math.round(v.actualMs)} ms > ${v.limitMs} ms\n`);
283
+ if (!run.coverage.complete) {
284
+ incomplete = true;
285
+ const blocking = run.coverage.issues.filter((i) => i.blocking);
286
+ 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`);
287
+ }
288
+ }
289
+ if (args.json)
290
+ process.stdout.write(JSON.stringify(single ? results[0] ?? null : results, null, 2) + "\n");
291
+ const written = results.flatMap((r) => ("report" in r && r.report ? [r.report] : []));
292
+ if (args.open && written.length) {
293
+ const html = (0, show_1.writeViewer)(written[0]);
294
+ const rel = node_path_1.default.relative(process.cwd(), html) || html;
295
+ process.stderr.write((0, show_1.openInBrowser)(html) ? `\nOpened ${rel} in your browser.\n` : `\nWrote ${rel} - open it in a browser.\n`);
296
+ if (written.length > 1)
297
+ process.stderr.write(`Open the others with: ${(0, show_1.showCommandFor)(written[1])}\n`);
298
+ }
299
+ else if (written.length && !args.json) {
300
+ process.stderr.write(`\nOpen ${written.length === 1 ? "it" : "a report"} in the analyzer (locally, offline):\n ${(0, show_1.showCommandFor)(written[0])}\n`);
301
+ }
302
+ if (errors > 0)
303
+ return 1;
304
+ if (failed)
305
+ return 2;
306
+ if (strict && incomplete)
307
+ return 3;
308
+ return 0;
309
+ }
310
+ /** Light pre-parse for the setup flow (the full parser runs in main()). */
311
+ function flagValues(argv, flag) {
312
+ const out = [];
313
+ argv.forEach((a, i) => {
314
+ if (a === flag && argv[i + 1] !== undefined)
315
+ out.push(argv[i + 1]);
316
+ });
317
+ return out;
318
+ }
319
+ /**
320
+ * CLI entry: `init`, or the first-run cartridge-path question (only in an
321
+ * interactive terminal, never in CI / --json / with --cartridge-path), then main().
322
+ */
323
+ async function cliEntry(argv, io = { input: process.stdin, output: process.stderr }, interactive = (0, setup_1.canPrompt)(argv)) {
324
+ const roots = flagValues(argv, "--root").map((r) => node_path_1.default.resolve(r));
325
+ if (roots.length === 0)
326
+ roots.push((0, config_1.defaultRoot)());
327
+ if (argv[0] === "init") {
328
+ if (!interactive && !(0, setup_1.canPrompt)([])) {
329
+ process.stderr.write(`sfcc-perf init needs an interactive terminal.\nIn CI, pass --cartridge-path "a:b:c" or commit a .sfcc-perf.json such as:\n { "cartridgePath": "app_custom:app_storefront_base" }\n`);
330
+ return 1;
331
+ }
332
+ try {
333
+ return (await (0, setup_1.promptCartridgePath)(roots, io, { reason: "init" })) ? 0 : 1;
334
+ }
335
+ catch (e) {
336
+ process.stderr.write(`error: ${e.message}\n`);
337
+ return 1;
338
+ }
339
+ }
340
+ // No cartridge path anywhere? Ask for it (a report needs one), unless this is CI / piped / --json.
341
+ if (interactive) {
342
+ let needed = false;
343
+ try {
344
+ needed = !(0, config_1.loadConfig)(roots[0], flagValues(argv, "--config")[0]).config.cartridgePath?.trim();
345
+ }
346
+ catch {
347
+ /* invalid config - main() reports it properly */
348
+ }
349
+ if (needed) {
350
+ try {
351
+ const answer = await (0, setup_1.promptCartridgePath)(roots, io, { reason: "missing" });
352
+ if (!answer)
353
+ return 1;
354
+ if (!answer.savedTo)
355
+ argv = [...argv, "--cartridge-path", answer.cartridgePath];
356
+ }
357
+ catch (e) {
358
+ process.stderr.write(`error: ${e.message}\n`);
359
+ return 1;
360
+ }
361
+ }
362
+ }
363
+ return main(argv);
364
+ }
365
+ if (require.main === module) {
366
+ void cliEntry(process.argv.slice(2)).then((code) => {
367
+ process.exitCode = code;
368
+ });
369
+ }
@@ -0,0 +1,53 @@
1
+ import type { AnalysisRun, AnalyzeOptions } from "./analyze";
2
+ export declare const CONFIG_FILE_NAMES: string[];
3
+ /** Latency budget for one entry point (milliseconds, modeled values). */
4
+ export interface Budget {
5
+ avg?: number;
6
+ p95?: number;
7
+ p99?: number;
8
+ max?: number;
9
+ }
10
+ /**
11
+ * Project config shared by the CLI, the programmatic API and the VS Code
12
+ * extension. Lives in `.sfcc-perf.json` at the repository root.
13
+ */
14
+ export interface SfccPerfConfig extends Partial<AnalyzeOptions> {
15
+ /** Where reports are written, relative to the config file. */
16
+ reportDirectory?: string;
17
+ /** Entry ids traced by `--all` when given; defaults to every discovered entry. */
18
+ entries?: string[];
19
+ /** Budgets keyed by entry id; `"*"` applies to every entry without its own budget. */
20
+ budgets?: Record<string, Budget>;
21
+ /** Treat an incomplete trace (unresolved requires, depth limit, …) as a failure. */
22
+ strict?: boolean;
23
+ }
24
+ export interface LoadedConfig {
25
+ config: SfccPerfConfig;
26
+ file: string | null;
27
+ }
28
+ export declare function findConfigFile(root: string): string | null;
29
+ /**
30
+ * The project root when no --root is given: the nearest folder (cwd or an
31
+ * ancestor) holding a config file, so running from inside a cartridge still
32
+ * uses the project's saved cartridge path. Falls back to cwd.
33
+ */
34
+ export declare function defaultRoot(cwd?: string): string;
35
+ export declare function loadConfig(root: string, explicitFile?: string): LoadedConfig;
36
+ export interface BudgetViolation {
37
+ entryId: string;
38
+ metric: keyof Budget;
39
+ limitMs: number;
40
+ actualMs: number;
41
+ }
42
+ export declare function budgetFor(entryId: string, budgets: Record<string, Budget> | undefined): Budget | null;
43
+ /**
44
+ * Normalises a cartridge path pasted from Business Manager: colon-separated
45
+ * cartridge names, surrounding whitespace/newlines and empty segments ignored.
46
+ */
47
+ export declare function parseCartridgePath(input: string): string[];
48
+ /**
49
+ * Merges `patch` into the project's config file (creating `.sfcc-perf.json`
50
+ * if there is none), keeping every other key. Returns the file written.
51
+ */
52
+ export declare function saveProjectConfig(root: string, patch: SfccPerfConfig): string;
53
+ export declare function checkBudget(run: AnalysisRun, budget: Budget | null): BudgetViolation[];
package/dist/config.js ADDED
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.CONFIG_FILE_NAMES = void 0;
7
+ exports.findConfigFile = findConfigFile;
8
+ exports.defaultRoot = defaultRoot;
9
+ exports.loadConfig = loadConfig;
10
+ exports.budgetFor = budgetFor;
11
+ exports.parseCartridgePath = parseCartridgePath;
12
+ exports.saveProjectConfig = saveProjectConfig;
13
+ exports.checkBudget = checkBudget;
14
+ const node_fs_1 = __importDefault(require("node:fs"));
15
+ const node_path_1 = __importDefault(require("node:path"));
16
+ const validate_1 = require("./validate");
17
+ exports.CONFIG_FILE_NAMES = [".sfcc-perf.json", "sfcc-perf.config.json"];
18
+ function findConfigFile(root) {
19
+ for (const name of exports.CONFIG_FILE_NAMES) {
20
+ const f = node_path_1.default.join(root, name);
21
+ if (node_fs_1.default.existsSync(f))
22
+ return f;
23
+ }
24
+ return null;
25
+ }
26
+ /**
27
+ * The project root when no --root is given: the nearest folder (cwd or an
28
+ * ancestor) holding a config file, so running from inside a cartridge still
29
+ * uses the project's saved cartridge path. Falls back to cwd.
30
+ */
31
+ function defaultRoot(cwd = process.cwd()) {
32
+ for (let dir = node_path_1.default.resolve(cwd);;) {
33
+ if (findConfigFile(dir))
34
+ return dir;
35
+ const parent = node_path_1.default.dirname(dir);
36
+ if (parent === dir)
37
+ return node_path_1.default.resolve(cwd);
38
+ dir = parent;
39
+ }
40
+ }
41
+ function loadConfig(root, explicitFile) {
42
+ const file = explicitFile ? node_path_1.default.resolve(root, explicitFile) : findConfigFile(root);
43
+ if (!file)
44
+ return { config: {}, file: null };
45
+ let parsed;
46
+ try {
47
+ parsed = JSON.parse(node_fs_1.default.readFileSync(file, "utf8"));
48
+ }
49
+ catch (e) {
50
+ throw new Error(`Cannot read ${file}: ${e.message}`);
51
+ }
52
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
53
+ throw new Error(`${file} must contain a JSON object.`);
54
+ (0, validate_1.validateConfig)(parsed, file);
55
+ return { config: parsed, file };
56
+ }
57
+ function budgetFor(entryId, budgets) {
58
+ if (!budgets)
59
+ return null;
60
+ const own = (k) => (Object.prototype.hasOwnProperty.call(budgets, k) ? budgets[k] : undefined);
61
+ return own(entryId) ?? own("*") ?? null;
62
+ }
63
+ /**
64
+ * Normalises a cartridge path pasted from Business Manager: colon-separated
65
+ * cartridge names, surrounding whitespace/newlines and empty segments ignored.
66
+ */
67
+ function parseCartridgePath(input) {
68
+ return input
69
+ .split(/[:\n]/)
70
+ .map((s) => s.trim())
71
+ .filter(Boolean);
72
+ }
73
+ /**
74
+ * Merges `patch` into the project's config file (creating `.sfcc-perf.json`
75
+ * if there is none), keeping every other key. Returns the file written.
76
+ */
77
+ function saveProjectConfig(root, patch) {
78
+ const file = findConfigFile(root) ?? node_path_1.default.join(root, exports.CONFIG_FILE_NAMES[0]);
79
+ let current = {};
80
+ if (node_fs_1.default.existsSync(file)) {
81
+ try {
82
+ const parsed = JSON.parse(node_fs_1.default.readFileSync(file, "utf8"));
83
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
84
+ current = parsed;
85
+ }
86
+ catch {
87
+ throw new Error(`${file} exists but isn't valid JSON - fix or remove it first.`);
88
+ }
89
+ }
90
+ const next = { ...current, ...patch };
91
+ for (const k of Object.keys(next))
92
+ if (next[k] === undefined)
93
+ delete next[k];
94
+ (0, validate_1.validateConfig)(next, file);
95
+ node_fs_1.default.writeFileSync(file, JSON.stringify(next, null, 2) + "\n");
96
+ return file;
97
+ }
98
+ function checkBudget(run, budget) {
99
+ if (!budget)
100
+ return [];
101
+ const a = run.analysis;
102
+ const actual = { avg: a.averageLatency, p95: a.p95, p99: a.p99, max: a.maxLatency };
103
+ const out = [];
104
+ for (const metric of Object.keys(budget)) {
105
+ const limit = budget[metric];
106
+ const value = actual[metric];
107
+ if (limit === undefined || value === null || value === undefined)
108
+ continue;
109
+ if (value > limit)
110
+ out.push({ entryId: run.trace.entry.id, metric, limitMs: limit, actualMs: value });
111
+ }
112
+ return out;
113
+ }
@@ -0,0 +1,16 @@
1
+ import type { SourceProvenance } from "../engine/types";
2
+ export type BenchmarkEntry = {
3
+ key: string;
4
+ label: string;
5
+ range: [number, number];
6
+ source: SourceProvenance;
7
+ notes?: string;
8
+ };
9
+ /**
10
+ * Comparison context only - never injected as a graph node or summed into a
11
+ * modeled result. See engine/benchmarkEngine.ts for the correctness
12
+ * guarantee. Every entry ships as "tool-assumption" with an explicit
13
+ * disclaimer; do not upgrade to "salesforce-reference" without an actual,
14
+ * linkable citation to Salesforce documentation.
15
+ */
16
+ export declare const SALESFORCE_REFERENCE_BENCHMARKS: Record<string, BenchmarkEntry>;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SALESFORCE_REFERENCE_BENCHMARKS = void 0;
4
+ const DISCLAIMER = "No public Salesforce benchmark is integrated in v1 - treat this as an illustrative modeling anchor, not an SLA or official constraint.";
5
+ const assumption = { sourceType: "tool-assumption", confidence: "low" };
6
+ /**
7
+ * Comparison context only - never injected as a graph node or summed into a
8
+ * modeled result. See engine/benchmarkEngine.ts for the correctness
9
+ * guarantee. Every entry ships as "tool-assumption" with an explicit
10
+ * disclaimer; do not upgrade to "salesforce-reference" without an actual,
11
+ * linkable citation to Salesforce documentation.
12
+ */
13
+ exports.SALESFORCE_REFERENCE_BENCHMARKS = {
14
+ "Home-Show": { key: "Home-Show", label: "Home-Show (SFRA)", range: [150, 350], source: assumption, notes: DISCLAIMER },
15
+ "Page-Show": { key: "Page-Show", label: "Page-Show (SFRA)", range: [150, 350], source: assumption, notes: DISCLAIMER },
16
+ "Product-Show": { key: "Product-Show", label: "Product-Show (SFRA)", range: [200, 400], source: assumption, notes: DISCLAIMER },
17
+ "Product-HitTile": { key: "Product-HitTile", label: "Product-HitTile (SFRA)", range: [80, 200], source: assumption, notes: DISCLAIMER },
18
+ "Search-Show": { key: "Search-Show", label: "Search-Show (SFRA)", range: [200, 450], source: assumption, notes: DISCLAIMER },
19
+ "Cart-Show": { key: "Cart-Show", label: "Cart-Show (SFRA)", range: [200, 400], source: assumption, notes: DISCLAIMER },
20
+ "OCAPI Request": { key: "OCAPI Request", label: "OCAPI Request (generic)", range: [150, 400], source: assumption, notes: DISCLAIMER },
21
+ };
@@ -0,0 +1 @@
1
+ export declare const ENGINE_SOURCE_REV = "c09e7ac";
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ENGINE_SOURCE_REV = void 0;
4
+ exports.ENGINE_SOURCE_REV = "c09e7ac";
@@ -0,0 +1,23 @@
1
+ import type { EndpointAnalysis, FlowEdge, FlowNode, GraphIssue, ModelDefaultsState } from "./types";
2
+ export declare function findApiRoots(nodes: FlowNode[], edges: FlowEdge[]): FlowNode[];
3
+ export declare function resolveActiveRoot(nodes: FlowNode[], edges: FlowEdge[], requestedRootId: string | null): string | null;
4
+ /**
5
+ * Evaluation budget, shared by the website and the npm package. Evaluation
6
+ * enumerates every root→end path (exclusive branches add paths, parallel
7
+ * branches multiply them) once per metric and twice more per cache, so both
8
+ * the path count and the total work (path steps × evaluations) are capped.
9
+ * At the work limit evaluation takes about half a second on a laptop; real
10
+ * traced endpoints are typically below 10,000 work units.
11
+ */
12
+ export declare const MAX_EVALUATION_PATHS = 20000;
13
+ export declare const MAX_EVALUATION_WORK = 2000000;
14
+ export type EvaluationCost = {
15
+ paths: number;
16
+ steps: number;
17
+ evaluations: number;
18
+ work: number;
19
+ };
20
+ export declare function evaluationCost(nodes: FlowNode[], edges: FlowEdge[], rootNodeId: string): EvaluationCost;
21
+ /** An error when the flow is too large to evaluate quickly, otherwise null. Cheap: counts paths without expanding them. */
22
+ export declare function checkEvaluationBudget(nodes: FlowNode[], edges: FlowEdge[], rootNodeId: string): GraphIssue | null;
23
+ export declare function analyzeEndpoint(nodes: FlowNode[], edges: FlowEdge[], modelDefaults: ModelDefaultsState, rootNodeId: string | null): EndpointAnalysis;