wp-shakedown 0.0.0-stage → 0.2.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 (116) hide show
  1. package/LICENSE +340 -0
  2. package/README.md +74 -2
  3. package/dist/baseline.d.ts +6 -0
  4. package/dist/baseline.js +41 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +296 -0
  7. package/dist/diff.d.ts +8 -0
  8. package/dist/diff.js +26 -0
  9. package/dist/engines/config.d.ts +3 -0
  10. package/dist/engines/config.js +134 -0
  11. package/dist/engines/custom.d.ts +10 -0
  12. package/dist/engines/custom.js +286 -0
  13. package/dist/engines/eslint.d.ts +8 -0
  14. package/dist/engines/eslint.js +96 -0
  15. package/dist/engines/index.d.ts +2 -0
  16. package/dist/engines/index.js +14 -0
  17. package/dist/engines/integrity.d.ts +2 -0
  18. package/dist/engines/integrity.js +108 -0
  19. package/dist/engines/php-compat.d.ts +2 -0
  20. package/dist/engines/php-compat.js +26 -0
  21. package/dist/engines/php-lint.d.ts +6 -0
  22. package/dist/engines/php-lint.js +42 -0
  23. package/dist/engines/phpstan.d.ts +11 -0
  24. package/dist/engines/phpstan.js +103 -0
  25. package/dist/engines/stylelint.d.ts +4 -0
  26. package/dist/engines/stylelint.js +63 -0
  27. package/dist/engines/theme-check.d.ts +7 -0
  28. package/dist/engines/theme-check.js +109 -0
  29. package/dist/engines/theme-review.d.ts +24 -0
  30. package/dist/engines/theme-review.js +378 -0
  31. package/dist/engines/updates.d.ts +6 -0
  32. package/dist/engines/updates.js +78 -0
  33. package/dist/engines/vulnerabilities.d.ts +22 -0
  34. package/dist/engines/vulnerabilities.js +128 -0
  35. package/dist/engines/wp-json.d.ts +18 -0
  36. package/dist/engines/wp-json.js +134 -0
  37. package/dist/engines/wpcs.d.ts +7 -0
  38. package/dist/engines/wpcs.js +60 -0
  39. package/dist/exec.d.ts +12 -0
  40. package/dist/exec.js +19 -0
  41. package/dist/fingerprint.d.ts +10 -0
  42. package/dist/fingerprint.js +29 -0
  43. package/dist/health/install.d.ts +16 -0
  44. package/dist/health/install.js +68 -0
  45. package/dist/home.d.ts +2 -0
  46. package/dist/home.js +6 -0
  47. package/dist/hub.d.ts +32 -0
  48. package/dist/hub.js +99 -0
  49. package/dist/index.d.ts +42 -0
  50. package/dist/index.js +36 -0
  51. package/dist/js/files.d.ts +4 -0
  52. package/dist/js/files.js +47 -0
  53. package/dist/js/tools.d.ts +3 -0
  54. package/dist/js/tools.js +67 -0
  55. package/dist/mcp/server.d.ts +9 -0
  56. package/dist/mcp/server.js +91 -0
  57. package/dist/mcp/tools.d.ts +26 -0
  58. package/dist/mcp/tools.js +163 -0
  59. package/dist/net.d.ts +18 -0
  60. package/dist/net.js +68 -0
  61. package/dist/php/files.d.ts +3 -0
  62. package/dist/php/files.js +53 -0
  63. package/dist/php/php.d.ts +4 -0
  64. package/dist/php/php.js +25 -0
  65. package/dist/php/phpcs.d.ts +25 -0
  66. package/dist/php/phpcs.js +55 -0
  67. package/dist/php/tools.d.ts +3 -0
  68. package/dist/php/tools.js +66 -0
  69. package/dist/profiles.d.ts +4 -0
  70. package/dist/profiles.js +41 -0
  71. package/dist/progress.d.ts +3 -0
  72. package/dist/progress.js +13 -0
  73. package/dist/projects.d.ts +36 -0
  74. package/dist/projects.js +91 -0
  75. package/dist/report/escape.d.ts +1 -0
  76. package/dist/report/escape.js +4 -0
  77. package/dist/report/html.d.ts +2 -0
  78. package/dist/report/html.js +100 -0
  79. package/dist/report/json.d.ts +2 -0
  80. package/dist/report/json.js +3 -0
  81. package/dist/report/markdown.d.ts +5 -0
  82. package/dist/report/markdown.js +92 -0
  83. package/dist/report/sarif.d.ts +2 -0
  84. package/dist/report/sarif.js +44 -0
  85. package/dist/report/write.d.ts +9 -0
  86. package/dist/report/write.js +48 -0
  87. package/dist/runner.d.ts +14 -0
  88. package/dist/runner.js +166 -0
  89. package/dist/session.d.ts +22 -0
  90. package/dist/session.js +39 -0
  91. package/dist/target.d.ts +5 -0
  92. package/dist/target.js +114 -0
  93. package/dist/types.d.ts +165 -0
  94. package/dist/types.js +6 -0
  95. package/dist/ui/server.d.ts +13 -0
  96. package/dist/ui/server.js +458 -0
  97. package/dist/version.d.ts +1 -0
  98. package/dist/version.js +3 -0
  99. package/dist/versions.d.ts +9 -0
  100. package/dist/versions.js +35 -0
  101. package/js-tools/eslint.config.mjs +19 -0
  102. package/js-tools/package-lock.json +7004 -0
  103. package/js-tools/package.json +13 -0
  104. package/js-tools/stylelint.config.mjs +4 -0
  105. package/package.json +58 -4
  106. package/php-tools/composer.json +68 -0
  107. package/php-tools/composer.lock +889 -0
  108. package/php-tools/theme-check.php +239 -0
  109. package/ui/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  110. package/ui/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  111. package/ui/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  112. package/ui/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  113. package/ui/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  114. package/ui/dist/assets/index-DXwdz_Wu.css +2 -0
  115. package/ui/dist/assets/index-V8IOqxHa.js +54 -0
  116. package/ui/dist/index.html +14 -0
@@ -0,0 +1,66 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { exec, NotFound } from '../exec.js';
6
+ import { home } from '../home.js';
7
+ import { EngineSkipped } from '../types.js';
8
+ import { phpVersion } from './php.js';
9
+ // Resolves to the package root from both src/php and dist/php.
10
+ const bundled = fileURLToPath(new URL('../../php-tools/', import.meta.url));
11
+ let cached;
12
+ export function resetToolsCache() {
13
+ cached = undefined;
14
+ }
15
+ const lastLine = (s) => s.split('\n').map((l) => l.trim()).filter(Boolean).pop() ?? '';
16
+ async function install(note) {
17
+ const hash = createHash('sha256').update(readFileSync(path.join(bundled, 'composer.lock'))).digest('hex').slice(0, 8);
18
+ const dir = path.join(home(), 'tools', `php-${hash}`);
19
+ if (existsSync(path.join(dir, 'vendor', 'bin', 'phpcs')))
20
+ return dir;
21
+ await phpVersion();
22
+ const composer = process.env.WP_SHAKEDOWN_COMPOSER || 'composer';
23
+ const noComposer = new EngineSkipped('Composer is not installed. wp-shakedown uses it once to fetch PHPCS and the WordPress standards. Get it from https://getcomposer.org or set WP_SHAKEDOWN_COMPOSER to its path.');
24
+ try {
25
+ if ((await exec(composer, ['--version'])).code !== 0)
26
+ throw noComposer;
27
+ }
28
+ catch (err) {
29
+ throw err instanceof NotFound ? noComposer : err;
30
+ }
31
+ note('Installing the PHP tools. This happens once.');
32
+ const tmp = `${dir}.tmp-${process.pid}`;
33
+ rmSync(tmp, { recursive: true, force: true });
34
+ mkdirSync(tmp, { recursive: true });
35
+ for (const f of ['composer.json', 'composer.lock'])
36
+ copyFileSync(path.join(bundled, f), path.join(tmp, f));
37
+ // shortcut: composer runs without a shell, so composer.bat on Windows is not found. Spawn through a shell there when Windows support is tested.
38
+ const r = await exec(composer, ['install', '--no-dev', '--no-interaction', '--no-progress', '--working-dir', tmp]);
39
+ if (r.code !== 0) {
40
+ rmSync(tmp, { recursive: true, force: true });
41
+ throw new Error(`Composer could not install the PHP tools: ${lastLine(r.stderr) || lastLine(r.stdout)}`);
42
+ }
43
+ try {
44
+ renameSync(tmp, dir);
45
+ }
46
+ catch {
47
+ // Another process installed the tools first.
48
+ rmSync(tmp, { recursive: true, force: true });
49
+ }
50
+ if (!existsSync(path.join(dir, 'vendor', 'bin', 'phpcs'))) {
51
+ throw new Error(`Composer finished, but PHPCS is not in "${dir}".`);
52
+ }
53
+ return dir;
54
+ }
55
+ /** The folder that holds vendor/bin/phpcs. Installs it on first use. */
56
+ export function phpTools(note) {
57
+ if (!cached) {
58
+ const p = install(note);
59
+ cached = p;
60
+ p.catch(() => {
61
+ if (cached === p)
62
+ cached = undefined;
63
+ });
64
+ }
65
+ return cached;
66
+ }
@@ -0,0 +1,4 @@
1
+ import type { Profile, Target } from './types.ts';
2
+ export declare const profiles: Profile[];
3
+ /** The engine IDs a profile runs on this target. Throws when the profile is unknown or does not fit the target. */
4
+ export declare function profileEngines(id: string, target: Target): string[];
@@ -0,0 +1,41 @@
1
+ export const profiles = [
2
+ {
3
+ id: 'wporg-theme',
4
+ title: 'WordPress.org theme directory',
5
+ summary: 'What the theme directory of wordpress.org checks before a review: Theme Check, PHP that parses, the WordPress standards and theme.json. With experimental checks on, also what reviewers ask for most.',
6
+ kinds: ['theme'],
7
+ engines: ['php-lint', 'theme-check', 'theme-review', 'wpcs', 'php-compat', 'wp-json'],
8
+ },
9
+ {
10
+ id: 'envato',
11
+ title: 'ThemeForest',
12
+ summary: 'What Envato checks on a theme for ThemeForest: its own version of Theme Check, PHP that parses, the WordPress standards and theme.json.',
13
+ kinds: ['theme'],
14
+ engines: ['php-lint', 'theme-check', 'wpcs', 'php-compat', 'wp-json'],
15
+ },
16
+ {
17
+ id: 'wporg-plugin',
18
+ title: 'WordPress.org plugin directory',
19
+ summary: 'What the plugin directory of wordpress.org checks in code: PHP that parses, the Plugin Check review rules and PHP versions.',
20
+ kinds: ['plugin'],
21
+ engines: ['php-lint', 'wpcs', 'php-compat'],
22
+ },
23
+ {
24
+ id: 'site',
25
+ title: 'WordPress site',
26
+ summary: 'Whether a WordPress folder is intact, current and safe to run. Leaves out code style in themes and plugins.',
27
+ kinds: ['install'],
28
+ engines: ['integrity', 'updates', 'vulnerabilities', 'config', 'php-lint', 'php-compat'],
29
+ },
30
+ ];
31
+ const KIND = { theme: 'a theme', plugin: 'a plugin', install: 'a WordPress folder', url: 'a site URL' };
32
+ /** The engine IDs a profile runs on this target. Throws when the profile is unknown or does not fit the target. */
33
+ export function profileEngines(id, target) {
34
+ const profile = profiles.find((p) => p.id === id);
35
+ if (!profile)
36
+ throw new Error(`Unknown profile "${id}". Known profiles: ${profiles.map((p) => p.id).join(', ')}.`);
37
+ if (!profile.kinds.includes(target.kind)) {
38
+ throw new Error(`The ${id} profile checks ${profile.kinds.map((k) => KIND[k]).join(' or ')}. "${target.name}" is ${KIND[target.kind]}.`);
39
+ }
40
+ return [...profile.engines];
41
+ }
@@ -0,0 +1,3 @@
1
+ import type { RunEvent } from './types.ts';
2
+ /** One line of progress for the terminal, or undefined when the event needs none. */
3
+ export declare function progressLine(e: RunEvent): string | undefined;
@@ -0,0 +1,13 @@
1
+ /** One line of progress for the terminal, or undefined when the event needs none. */
2
+ export function progressLine(e) {
3
+ if (e.type === 'engine:note')
4
+ return ` ${e.engine}${e.unit ? ' ' + e.unit : ''}: ${e.message}`;
5
+ if (e.type !== 'engine:end')
6
+ return undefined;
7
+ const r = e.run;
8
+ const who = `${r.engine}${r.unit ? ' ' + r.unit : ''}`;
9
+ if (r.status === 'ok') {
10
+ return `ok ${who}: ${r.findings} ${r.findings === 1 ? 'finding' : 'findings'}, ${(r.durationMs / 1000).toFixed(1)}s`;
11
+ }
12
+ return `${r.status} ${who}: ${r.reason}`;
13
+ }
@@ -0,0 +1,36 @@
1
+ import type { Depth, Summary, TargetKind } from './types.ts';
2
+ /** A folder the user keeps in the hub, with what the last run found. */
3
+ export interface Project {
4
+ /** Stable for a path. Short enough to type. */
5
+ id: string;
6
+ path: string;
7
+ name: string;
8
+ /** Absent when the folder is gone or is no longer a theme, a plugin or a WordPress folder. */
9
+ kind?: TargetKind;
10
+ /** Themes and plugins inside a WordPress folder. */
11
+ units: number;
12
+ /** Why the folder cannot be tested now. */
13
+ problem?: string;
14
+ last?: {
15
+ finishedAt: string;
16
+ summary: Summary;
17
+ /** Engines that failed, so the report is incomplete. */
18
+ failed: number;
19
+ profile?: string;
20
+ depth?: Depth;
21
+ /** The folder that holds the report files. */
22
+ dir: string;
23
+ };
24
+ }
25
+ export declare const projectId: (p: string) => string;
26
+ /** The projects in the order they were added, each with the result of its last run. */
27
+ export declare function listProjects(): Project[];
28
+ /** Adds a folder. Throws when it is not a theme, a plugin or a WordPress folder. `added` is false when it was there already. */
29
+ export declare function addProject(input: string, now?: () => Date): {
30
+ project: Project;
31
+ added: boolean;
32
+ };
33
+ /** Finds a project by its ID, its path or its name. A name that fits more than one project fits none. */
34
+ export declare function findProject(key: string): Project | undefined;
35
+ /** Takes a project off the list. Its reports stay. Returns false when no project fits. */
36
+ export declare function removeProject(key: string): boolean;
@@ -0,0 +1,91 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { home } from './home.js';
5
+ import { defaultReportDir, readPreviousRun } from './report/write.js';
6
+ import { detectTarget } from './target.js';
7
+ const file = () => path.join(home(), 'projects.json');
8
+ export const projectId = (p) => createHash('sha256').update(p).digest('hex').slice(0, 8);
9
+ function read() {
10
+ try {
11
+ const data = JSON.parse(readFileSync(file(), 'utf8'));
12
+ if (data?.schema === 1 && Array.isArray(data.projects)) {
13
+ return { schema: 1, projects: data.projects.filter((p) => typeof p?.path === 'string' && path.isAbsolute(p.path)) };
14
+ }
15
+ }
16
+ catch {
17
+ // No file yet, or one that cannot be read. Both mean an empty list.
18
+ }
19
+ return { schema: 1, projects: [] };
20
+ }
21
+ function write(data) {
22
+ mkdirSync(home(), { recursive: true });
23
+ // Write next to the file and rename, so a reader never sees half a file.
24
+ const tmp = `${file()}.${process.pid}.tmp`;
25
+ writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n');
26
+ renameSync(tmp, file());
27
+ }
28
+ function describe(p) {
29
+ let target;
30
+ try {
31
+ target = detectTarget(p);
32
+ }
33
+ catch (err) {
34
+ return { id: projectId(p), path: p, name: path.basename(p), units: 0, problem: err instanceof Error ? err.message : String(err) };
35
+ }
36
+ const dir = defaultReportDir(target);
37
+ const run = readPreviousRun(dir);
38
+ return {
39
+ id: projectId(p),
40
+ path: p,
41
+ name: target.name,
42
+ kind: target.kind,
43
+ units: target.units.length,
44
+ ...(run
45
+ ? {
46
+ last: {
47
+ finishedAt: run.finishedAt,
48
+ summary: run.summary,
49
+ failed: run.engines.filter((e) => e.status === 'failed').length,
50
+ ...(run.profile ? { profile: run.profile } : {}),
51
+ ...(run.depth ? { depth: run.depth } : {}),
52
+ dir,
53
+ },
54
+ }
55
+ : {}),
56
+ };
57
+ }
58
+ /** The projects in the order they were added, each with the result of its last run. */
59
+ export function listProjects() {
60
+ return read().projects.map((p) => describe(p.path));
61
+ }
62
+ /** Adds a folder. Throws when it is not a theme, a plugin or a WordPress folder. `added` is false when it was there already. */
63
+ export function addProject(input, now = () => new Date()) {
64
+ const target = detectTarget(input);
65
+ const data = read();
66
+ const added = !data.projects.some((p) => p.path === target.path);
67
+ if (added) {
68
+ data.projects.push({ path: target.path, addedAt: now().toISOString() });
69
+ write(data);
70
+ }
71
+ return { project: describe(target.path), added };
72
+ }
73
+ /** Finds a project by its ID, its path or its name. A name that fits more than one project fits none. */
74
+ export function findProject(key) {
75
+ const all = listProjects();
76
+ const abs = path.resolve(key);
77
+ const exact = all.find((p) => p.id === key || p.path === abs);
78
+ if (exact)
79
+ return exact;
80
+ const named = all.filter((p) => p.name.toLowerCase() === key.toLowerCase());
81
+ return named.length === 1 ? named[0] : undefined;
82
+ }
83
+ /** Takes a project off the list. Its reports stay. Returns false when no project fits. */
84
+ export function removeProject(key) {
85
+ const found = findProject(key);
86
+ if (!found)
87
+ return false;
88
+ const data = read();
89
+ write({ schema: 1, projects: data.projects.filter((p) => p.path !== found.path) });
90
+ return true;
91
+ }
@@ -0,0 +1 @@
1
+ export declare function escapeHtml(s: string): string;
@@ -0,0 +1,4 @@
1
+ const MAP = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
2
+ export function escapeHtml(s) {
3
+ return s.replace(/[&<>"']/g, (c) => MAP[c]);
4
+ }
@@ -0,0 +1,2 @@
1
+ import type { RunDiff, RunResult } from '../types.ts';
2
+ export declare function toHtml(result: RunResult, diff?: RunDiff): string;
@@ -0,0 +1,100 @@
1
+ import { escapeHtml as e } from './escape.js';
2
+ import { groupName, noEngineLine, summaryLine } from './markdown.js';
3
+ const STYLE = `
4
+ :root { color-scheme: light dark; --bg: #fff; --fg: #1d2327; --muted: #646970; --line: #dcdcde; --accent: #2271b1; }
5
+ @media (prefers-color-scheme: dark) { :root { --bg: #14181c; --fg: #e4e7ea; --muted: #9aa3ab; --line: #333a41; --accent: #72aee6; } }
6
+ body { font: 16px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; background: var(--bg); color: var(--fg); max-width: 60rem; margin: 2rem auto; padding: 0 1rem; }
7
+ h1, h2, h3 { line-height: 1.25; }
8
+ table { border-collapse: collapse; width: 100%; margin: 1rem 0; }
9
+ th, td { text-align: left; vertical-align: top; padding: 0.4rem 0.6rem; border-bottom: 1px solid var(--line); }
10
+ code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.9em; }
11
+ a { color: var(--accent); }
12
+ .muted { color: var(--muted); }
13
+ `;
14
+ const oneLine = (s) => s.replace(/\s*\r?\n\s*/g, ' ');
15
+ function docsLink(docs) {
16
+ return /^https?:\/\//.test(docs) ? `<a href="${e(docs)}">${e(docs)}</a>` : e(docs);
17
+ }
18
+ function diffList(title, items) {
19
+ if (!items.length)
20
+ return '';
21
+ const li = items
22
+ .map((f) => `<li>${e(groupName(f))}: ${e(f.severity)} <code>${e(f.id)}</code>${f.location.line !== undefined ? ` line ${e(String(f.location.line))}` : ''}: ${e(oneLine(f.message))} (${e(f.engine)}: ${e(f.rule)})</li>`)
23
+ .join('\n');
24
+ return `<h3>${title}</h3>\n<ul>\n${li}\n</ul>\n`;
25
+ }
26
+ export function toHtml(result, diff) {
27
+ const t = result.target;
28
+ let body = `<h1>wp-shakedown report</h1>
29
+ <p>Target: ${e(t.kind)} "${e(t.name)}" at ${e(t.path)}<br>
30
+ ${result.profile ? `Profile: ${e(result.profile)}<br>\n` : ''}${result.depth && result.depth !== 'standard' ? `Depth: ${e(result.depth)}<br>\n` : ''}${result.experimental ? 'Experimental checks: on<br>\n' : ''}Run: ${e(result.finishedAt)}, wp-shakedown ${e(result.tool.version)}</p>
31
+ <h2>Summary</h2>
32
+ <p>${e(summaryLine(result))}</p>
33
+ `;
34
+ if (result.engines.length === 0) {
35
+ body += `<p>${e(noEngineLine(result))}</p>\n`;
36
+ }
37
+ else {
38
+ const rows = result.engines
39
+ .map((r) => `<tr><td>${e(r.engine)}</td><td>${e(r.unit ?? '-')}</td><td>${e(r.status)}${r.reason ? e(`: ${r.reason}`) : ''}</td><td>${e(String(r.findings))}</td></tr>`)
40
+ .join('\n');
41
+ body += `<table>\n<thead><tr><th>Engine</th><th>Part</th><th>Status</th><th>Findings</th></tr></thead>\n<tbody>\n${rows}\n</tbody>\n</table>\n`;
42
+ }
43
+ if (diff) {
44
+ body += `<h2>Since the last run</h2>\n<p>${diff.fixed.length} fixed, ${diff.added.length} new, ${diff.open.length} still open.</p>\n`;
45
+ body += diffList('New:', diff.added) + diffList('Fixed:', diff.fixed);
46
+ }
47
+ body += '<h2>Findings</h2>\n';
48
+ const active = result.findings.filter((f) => !f.suppressed);
49
+ if (active.length === 0)
50
+ body += '<p>No findings.</p>\n';
51
+ const groups = new Map();
52
+ for (const f of active) {
53
+ const g = groups.get(groupName(f));
54
+ if (g)
55
+ g.push(f);
56
+ else
57
+ groups.set(groupName(f), [f]);
58
+ }
59
+ for (const [name, items] of groups) {
60
+ const rows = items
61
+ .map((f) => {
62
+ let msg = e(oneLine(f.message));
63
+ if (f.hint)
64
+ msg += `<br><span class="muted">Fix: ${e(oneLine(f.hint))}</span>`;
65
+ if (f.docs)
66
+ msg += `<br><span class="muted">Docs: ${docsLink(oneLine(f.docs))}</span>`;
67
+ return `<tr><td>${e(f.severity)}</td><td><code>${e(f.id)}</code></td><td>${e(String(f.location.line ?? ''))}</td><td>${msg}</td><td>${e(f.engine)}: ${e(f.rule)}</td></tr>`;
68
+ })
69
+ .join('\n');
70
+ body += `<h3>${e(name)}</h3>\n<table>\n<thead><tr><th>Severity</th><th>ID</th><th>Line</th><th>Message</th><th>Rule</th></tr></thead>\n<tbody>\n${rows}\n</tbody>\n</table>\n`;
71
+ }
72
+ const suppressed = result.findings.filter((f) => f.suppressed);
73
+ if (suppressed.length) {
74
+ const li = suppressed
75
+ .map((f) => `<li><code>${e(f.id)}</code> ${e(f.engine)}: ${e(f.rule)}. Reason: ${e(oneLine(f.suppressed.reason))}</li>`)
76
+ .join('\n');
77
+ body += `<h2>Suppressed</h2>\n<ul>\n${li}\n</ul>\n`;
78
+ }
79
+ if (result.staleBaseline.length) {
80
+ const li = result.staleBaseline.map((id) => `<li><code>${e(id)}</code></li>`).join('\n');
81
+ body += `<h2>Stale baseline entries</h2>\n<p>These baseline entries match nothing now. Remove them.</p>\n<ul>\n${li}\n</ul>\n`;
82
+ }
83
+ if (result.engines.length) {
84
+ const ids = [...new Set(result.engines.map((r) => r.engine))];
85
+ const li = ids.map((id) => `<li><code>${e(`wp-shakedown run "${t.path}" --engine ${id}`)}</code></li>`).join('\n');
86
+ body += `<h2>Run again</h2>\n<ul>\n${li}\n</ul>\n`;
87
+ }
88
+ return `<!doctype html>
89
+ <html lang="en">
90
+ <head>
91
+ <meta charset="utf-8">
92
+ <meta name="viewport" content="width=device-width, initial-scale=1">
93
+ <title>wp-shakedown report: ${e(t.name)}</title>
94
+ <style>${STYLE}</style>
95
+ </head>
96
+ <body>
97
+ ${body}</body>
98
+ </html>
99
+ `;
100
+ }
@@ -0,0 +1,2 @@
1
+ import type { RunResult } from '../types.ts';
2
+ export declare function toJson(result: RunResult): string;
@@ -0,0 +1,3 @@
1
+ export function toJson(result) {
2
+ return JSON.stringify(result, null, 2) + '\n';
3
+ }
@@ -0,0 +1,5 @@
1
+ import type { Finding, RunDiff, RunResult } from '../types.ts';
2
+ export declare function summaryLine(result: RunResult): string;
3
+ export declare function noEngineLine(result: RunResult): string;
4
+ export declare function groupName(f: Finding): string;
5
+ export declare function toMarkdown(result: RunResult, diff?: RunDiff): string;
@@ -0,0 +1,92 @@
1
+ const oneLine = (s) => s.replace(/\s*\r?\n\s*/g, ' ');
2
+ const cell = (s) => oneLine(s).replace(/\|/g, '\\|');
3
+ const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
4
+ export function summaryLine(result) {
5
+ const s = result.summary;
6
+ const base = `${plural(s.error, 'error', 'errors')}, ${plural(s.warning, 'warning', 'warnings')}, ${plural(s.info, 'note', 'notes')}.`;
7
+ return s.suppressed > 0 ? `${base} ${s.suppressed} suppressed.` : base;
8
+ }
9
+ export function noEngineLine(result) {
10
+ const label = { theme: 'theme', plugin: 'plugin', install: 'WordPress folder', url: 'site URL' }[result.target.kind];
11
+ return `No engine ran. This version has no engine for a ${label} yet.`;
12
+ }
13
+ export function groupName(f) {
14
+ return f.location.file ?? f.location.url ?? '(no file)';
15
+ }
16
+ function findingText(f) {
17
+ const line = f.location.line !== undefined ? ` line ${f.location.line}` : '';
18
+ return `${f.severity} \`${f.id}\`${line}: ${oneLine(f.message)} (${f.engine}: ${f.rule})`;
19
+ }
20
+ export function toMarkdown(result, diff) {
21
+ const out = [];
22
+ out.push('# wp-shakedown report');
23
+ out.push(`- Target: ${result.target.kind} "${result.target.name}" at ${result.target.path}${result.profile ? `\n- Profile: ${result.profile}` : ''}${result.depth && result.depth !== 'standard' ? `\n- Depth: ${result.depth}` : ''}${result.experimental ? '\n- Experimental checks: on' : ''}\n- Run: ${result.finishedAt}, wp-shakedown ${result.tool.version}`);
24
+ const summary = ['## Summary', summaryLine(result)];
25
+ if (result.engines.length === 0) {
26
+ summary.push(noEngineLine(result));
27
+ }
28
+ else {
29
+ const rows = result.engines.map((e) => `| ${cell(e.engine)} | ${cell(e.unit ?? '-')} | ${e.status}${e.reason ? cell(`: ${e.reason}`) : ''} | ${e.findings} |`);
30
+ summary.push(['| Engine | Part | Status | Findings |', '|---|---|---|---|', ...rows].join('\n'));
31
+ }
32
+ out.push(...summary);
33
+ if (diff) {
34
+ out.push('## Since the last run', `${diff.fixed.length} fixed, ${diff.added.length} new, ${diff.open.length} still open.`);
35
+ const list = (title, all) => {
36
+ const items = all.filter((f) => f.category !== 'standards');
37
+ if (items.length)
38
+ out.push(`${title}\n\n${items.map((f) => `- ${groupName(f)}: ${findingText(f)}`).join('\n')}`);
39
+ };
40
+ list('New:', diff.added);
41
+ list('Fixed:', diff.fixed);
42
+ }
43
+ out.push('## Findings');
44
+ const active = result.findings.filter((f) => !f.suppressed);
45
+ // A real theme has thousands of style findings. Listed one by one they bury the few that matter, so they are counted per rule below.
46
+ const detail = active.filter((f) => f.category !== 'standards');
47
+ const style = active.filter((f) => f.category === 'standards');
48
+ if (active.length === 0)
49
+ out.push('No findings.');
50
+ else if (detail.length === 0)
51
+ out.push('No findings apart from code style.');
52
+ const groups = new Map();
53
+ for (const f of detail) {
54
+ const g = groups.get(groupName(f));
55
+ if (g)
56
+ g.push(f);
57
+ else
58
+ groups.set(groupName(f), [f]);
59
+ }
60
+ for (const [name, items] of groups) {
61
+ const lines = items.map((f) => {
62
+ let s = `- ${findingText(f)}`;
63
+ if (f.hint)
64
+ s += `\n Fix: ${oneLine(f.hint)}`;
65
+ if (f.docs)
66
+ s += `\n Docs: ${oneLine(f.docs)}`;
67
+ return s;
68
+ });
69
+ out.push(`### ${name}`, lines.join('\n'));
70
+ }
71
+ if (style.length) {
72
+ const counts = new Map();
73
+ for (const f of style)
74
+ counts.set(`${f.engine}: ${f.rule}`, (counts.get(`${f.engine}: ${f.rule}`) ?? 0) + 1);
75
+ const rows = [...counts]
76
+ .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
77
+ .map(([rule, n]) => `| ${cell(rule)} | ${n} |`);
78
+ out.push('## Code style', `${plural(style.length, 'style finding', 'style findings')} in ${plural(counts.size, 'rule', 'rules')}. report.json lists each one with its file and line.`, ['| Rule | Findings |', '|---|---|', ...rows].join('\n'));
79
+ }
80
+ const suppressed = result.findings.filter((f) => f.suppressed);
81
+ if (suppressed.length) {
82
+ out.push('## Suppressed', suppressed.map((f) => `- \`${f.id}\` ${f.engine}: ${f.rule}. Reason: ${oneLine(f.suppressed.reason)}`).join('\n'));
83
+ }
84
+ if (result.staleBaseline.length) {
85
+ out.push('## Stale baseline entries', 'These baseline entries match nothing now. Remove them.', result.staleBaseline.map((id) => `- \`${id}\``).join('\n'));
86
+ }
87
+ if (result.engines.length) {
88
+ const ids = [...new Set(result.engines.map((e) => e.engine))];
89
+ out.push('## Run again', ids.map((id) => `- \`wp-shakedown run "${result.target.path}" --engine ${id}\``).join('\n'));
90
+ }
91
+ return out.join('\n\n') + '\n';
92
+ }
@@ -0,0 +1,2 @@
1
+ import type { RunResult } from '../types.ts';
2
+ export declare function toSarif(result: RunResult): string;
@@ -0,0 +1,44 @@
1
+ const LEVEL = { error: 'error', warning: 'warning', info: 'note' };
2
+ export function toSarif(result) {
3
+ const rules = new Map();
4
+ for (const f of result.findings) {
5
+ const id = `${f.engine}/${f.rule}`;
6
+ const rule = rules.get(id) ?? { id };
7
+ if (f.docs && !rule.helpUri)
8
+ rule.helpUri = f.docs;
9
+ rules.set(id, rule);
10
+ }
11
+ const results = result.findings.map((f) => {
12
+ // SARIF wants a URI, so a space in a file path has to be encoded.
13
+ const uri = f.location.file !== undefined ? encodeURI(f.location.file) : f.location.url;
14
+ const region = f.location.line !== undefined
15
+ ? { startLine: f.location.line, ...(f.location.column !== undefined ? { startColumn: f.location.column } : {}) }
16
+ : undefined;
17
+ return {
18
+ ruleId: `${f.engine}/${f.rule}`,
19
+ level: LEVEL[f.severity],
20
+ message: { text: f.message },
21
+ partialFingerprints: { 'wpShakedown/v1': f.id },
22
+ ...(uri !== undefined ? { locations: [{ physicalLocation: { artifactLocation: { uri }, ...(region ? { region } : {}) } }] } : {}),
23
+ ...(f.suppressed ? { suppressions: [{ kind: 'external', justification: f.suppressed.reason }] } : {}),
24
+ };
25
+ });
26
+ const sarif = {
27
+ $schema: 'https://json.schemastore.org/sarif-2.1.0.json',
28
+ version: '2.1.0',
29
+ runs: [
30
+ {
31
+ tool: {
32
+ driver: {
33
+ name: 'wp-shakedown',
34
+ version: result.tool.version,
35
+ informationUri: 'https://github.com/alexposlushnyak/wp-shakedown',
36
+ rules: [...rules.values()],
37
+ },
38
+ },
39
+ results,
40
+ },
41
+ ],
42
+ };
43
+ return JSON.stringify(sarif, null, 2) + '\n';
44
+ }
@@ -0,0 +1,9 @@
1
+ import type { RunDiff, RunResult, Target } from '../types.ts';
2
+ export declare function defaultReportDir(target: Target): string;
3
+ export declare function readPreviousRun(dir: string): RunResult | undefined;
4
+ /** Throws when the report folder is the target or inside it. Call it before a run, so a long run is not wasted. */
5
+ export declare function assertReportDir(target: {
6
+ kind: string;
7
+ path: string;
8
+ }, dir: string): void;
9
+ export declare function writeReports(result: RunResult, dir: string, diff?: RunDiff): string[];
@@ -0,0 +1,48 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { home } from '../home.js';
5
+ import { toHtml } from './html.js';
6
+ import { toJson } from './json.js';
7
+ import { toMarkdown } from './markdown.js';
8
+ import { toSarif } from './sarif.js';
9
+ export function defaultReportDir(target) {
10
+ const slug = target.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40).replace(/-+$/, '') || 'target';
11
+ const hash = createHash('sha256').update(target.path).digest('hex').slice(0, 8);
12
+ return path.join(home(), 'reports', `${slug}-${hash}`);
13
+ }
14
+ export function readPreviousRun(dir) {
15
+ try {
16
+ const data = JSON.parse(readFileSync(path.join(dir, 'report.json'), 'utf8'));
17
+ return data?.schema === 1 && Array.isArray(data.findings) && Array.isArray(data.engines) ? data : undefined;
18
+ }
19
+ catch {
20
+ return undefined;
21
+ }
22
+ }
23
+ /** Throws when the report folder is the target or inside it. Call it before a run, so a long run is not wasted. */
24
+ export function assertReportDir(target, dir) {
25
+ if (target.kind === 'url')
26
+ return;
27
+ // shortcut: compares the paths as given. A symlink that points into the target passes. Resolve real paths if that happens.
28
+ const rel = path.relative(target.path, path.resolve(dir));
29
+ if (rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))) {
30
+ throw new Error(`The report folder "${dir}" is inside the target. wp-shakedown never writes into what it tests. Pass --out with a folder elsewhere.`);
31
+ }
32
+ }
33
+ export function writeReports(result, dir, diff) {
34
+ assertReportDir(result.target, dir);
35
+ const out = path.resolve(dir);
36
+ mkdirSync(out, { recursive: true });
37
+ const files = [
38
+ ['report.md', toMarkdown(result, diff)],
39
+ ['report.json', toJson(result)],
40
+ ['report.sarif', toSarif(result)],
41
+ ['report.html', toHtml(result, diff)],
42
+ ];
43
+ return files.map(([name, text]) => {
44
+ const p = path.join(out, name);
45
+ writeFileSync(p, text);
46
+ return p;
47
+ });
48
+ }
@@ -0,0 +1,14 @@
1
+ import type { Baseline, Depth, Engine, RunEvent, RunResult, Severity, Target } from './types.ts';
2
+ export interface RunOptions {
3
+ engines: Engine[];
4
+ only?: string[];
5
+ profile?: string;
6
+ depth?: Depth;
7
+ experimental?: boolean;
8
+ baseline?: Baseline;
9
+ signal?: AbortSignal;
10
+ onEvent?: (e: RunEvent) => void;
11
+ now?: () => Date;
12
+ }
13
+ export declare function run(target: Target, opts: RunOptions): Promise<RunResult>;
14
+ export declare function exitCode(result: RunResult, failOn: Severity | 'never'): 0 | 1 | 2;