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,103 @@
1
+ import { existsSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { exec } from '../exec.js';
5
+ import { home } from '../home.js';
6
+ import { phpFiles } from '../php/files.js';
7
+ import { phpBinary, phpVersion } from '../php/php.js';
8
+ import { phpTools } from '../php/tools.js';
9
+ const q = (p) => `'${p.replace(/'/g, "''")}'`;
10
+ export function neon(opts) {
11
+ const lines = [
12
+ 'includes:',
13
+ `\t- ${q(`${opts.tools}/vendor/szepeviktor/phpstan-wordpress/extension.neon`)}`,
14
+ 'parameters:',
15
+ '\tlevel: 5',
16
+ '\tpaths:',
17
+ `\t\t- ${q(opts.target)}`,
18
+ `\ttmpDir: ${q(opts.tmpDir)}`,
19
+ ];
20
+ if (opts.exclude.length)
21
+ lines.push('\texcludePaths:', '\t\tanalyse:', ...opts.exclude.map((e) => `\t\t\t- ${q(e)}`));
22
+ if (opts.vendor)
23
+ lines.push('\tscanDirectories:', `\t\t- ${q(opts.vendor)}`);
24
+ return lines.join('\n') + '\n';
25
+ }
26
+ export function parsePhpstan(json, base) {
27
+ let data;
28
+ try {
29
+ data = JSON.parse(json);
30
+ }
31
+ catch {
32
+ throw new Error('PHPStan returned output that is not JSON.');
33
+ }
34
+ if (!data || typeof data.files !== 'object' || data.files === null)
35
+ throw new Error('PHPStan returned output that is not JSON.');
36
+ if (data.errors?.length)
37
+ throw new Error(`PHPStan stopped: ${data.errors[0]}`);
38
+ const out = [];
39
+ for (const [abs, f] of Object.entries(data.files)) {
40
+ const rel = path.relative(base, abs);
41
+ const file = rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel.split(path.sep).join('/') : abs;
42
+ for (const m of f.messages ?? []) {
43
+ out.push({
44
+ rule: m.identifier ?? 'phpstan',
45
+ severity: 'warning',
46
+ category: 'correctness',
47
+ message: m.message,
48
+ location: { file, ...(typeof m.line === 'number' ? { line: m.line } : {}) },
49
+ ...(m.tip ? { hint: m.tip.replace(/\s*\n\s*/g, ' ') } : {}),
50
+ });
51
+ }
52
+ }
53
+ return out;
54
+ }
55
+ const isDir = (p) => existsSync(p) && statSync(p).isDirectory();
56
+ export const phpstan = {
57
+ id: 'phpstan',
58
+ title: 'PHPStan',
59
+ kinds: ['theme', 'plugin'],
60
+ depth: 'deep',
61
+ async run({ target, signal, note }) {
62
+ await phpVersion();
63
+ const tools = await phpTools(note);
64
+ const isFile = statSync(target.path).isFile();
65
+ const base = isFile ? path.dirname(target.path) : target.path;
66
+ const exclude = isFile ? [] : [path.join(base, 'vendor'), path.join(base, 'node_modules')].filter(isDir);
67
+ const vendor = !isFile && isDir(path.join(base, 'vendor')) ? path.join(base, 'vendor') : undefined;
68
+ if (!isFile && ['phpstan.neon', 'phpstan.neon.dist', 'phpstan.dist.neon'].some((n) => existsSync(path.join(base, n)))) {
69
+ note('The project has its own PHPStan config. wp-shakedown uses its own settings at level 5.');
70
+ }
71
+ const files = phpFiles(target.path);
72
+ // PHPStan stops with an error when it has no file to read. A block theme can have no PHP at all.
73
+ if (files.length === 0)
74
+ return [];
75
+ const cfgDir = mkdtempSync(path.join(os.tmpdir(), 'wps-phpstan-'));
76
+ const analyse = async (broken) => {
77
+ const cfgFile = path.join(cfgDir, 'phpstan.neon');
78
+ writeFileSync(cfgFile, neon({ tools, target: target.path, isFile, tmpDir: path.join(home(), 'cache', 'phpstan'), ...(vendor ? { vendor } : {}), exclude: [...exclude, ...broken] }));
79
+ const r = await exec(phpBinary(), ['-d', 'memory_limit=1G', path.join(tools, 'vendor', 'bin', 'phpstan'), 'analyse', '-c', cfgFile, '--error-format=json', '--no-progress', '--no-interaction', '--memory-limit=1G'], { cwd: base, ...(signal ? { signal } : {}) });
80
+ if (!r.stdout.trim().startsWith('{')) {
81
+ const line = [r.stderr, r.stdout]
82
+ .flatMap((s) => s.split('\n').map((l) => l.trim()))
83
+ .find((l) => l && !l.startsWith('Warning: Module'));
84
+ throw new Error(`PHPStan stopped: ${line ?? 'no output'}`);
85
+ }
86
+ return parsePhpstan(r.stdout, base);
87
+ };
88
+ try {
89
+ const found = await analyse([]);
90
+ // When a file does not parse, PHPStan reports that and nothing else. Run again without those files.
91
+ const broken = [...new Set(found.filter((f) => f.rule === 'phpstan.parse').map((f) => path.join(base, f.location.file)))];
92
+ if (broken.length === 0)
93
+ return found;
94
+ note(`Left out ${broken.length} ${broken.length === 1 ? 'file' : 'files'} that PHP cannot parse. php-lint reports them.`);
95
+ if (broken.length >= files.length)
96
+ return [];
97
+ return (await analyse(broken)).filter((f) => f.rule !== 'phpstan.parse');
98
+ }
99
+ finally {
100
+ rmSync(cfgDir, { recursive: true, force: true });
101
+ }
102
+ },
103
+ };
@@ -0,0 +1,4 @@
1
+ import type { Category, Engine, RawFinding } from '../types.ts';
2
+ export declare function categoriseCss(rule: string): Category;
3
+ export declare function parseStylelint(json: string, base: string): RawFinding[];
4
+ export declare const stylelint: Engine;
@@ -0,0 +1,63 @@
1
+ import path from 'node:path';
2
+ import { exec } from '../exec.js';
3
+ import { isGenerated, sourceFiles } from '../js/files.js';
4
+ import { jsTools } from '../js/tools.js';
5
+ import { chunks, firstLine, posixRelative } from './eslint.js';
6
+ export function categoriseCss(rule) {
7
+ return /(-no-unknown$|-no-invalid|^no-invalid-|no-duplicate-|^block-no-empty$|-no-shorthand-property-overrides$|^string-no-newline$|^no-empty-source$|-no-missing-generic-family-keyword$|^no-irregular-whitespace$)/.test(rule)
8
+ ? 'correctness'
9
+ : 'standards';
10
+ }
11
+ export function parseStylelint(json, base) {
12
+ let data;
13
+ try {
14
+ data = JSON.parse(json);
15
+ }
16
+ catch {
17
+ data = null;
18
+ }
19
+ if (!Array.isArray(data))
20
+ throw new Error('Stylelint returned output that is not JSON.');
21
+ const out = [];
22
+ for (const f of data) {
23
+ for (const w of f.warnings ?? []) {
24
+ const message = w.text.endsWith(` (${w.rule})`) ? w.text.slice(0, -` (${w.rule})`.length) : w.text;
25
+ const location = { file: posixRelative(base, f.source), line: w.line, column: w.column };
26
+ if (w.rule === 'CssSyntaxError') {
27
+ out.push({ rule: 'syntax', severity: 'error', category: 'correctness', message, location });
28
+ continue;
29
+ }
30
+ const category = categoriseCss(w.rule);
31
+ out.push({ rule: w.rule, severity: category === 'standards' ? 'info' : 'warning', category, message, location });
32
+ }
33
+ }
34
+ return out;
35
+ }
36
+ export const stylelint = {
37
+ id: 'stylelint',
38
+ title: 'CSS',
39
+ kinds: ['theme', 'plugin'],
40
+ async run({ target, signal, note }) {
41
+ const files = sourceFiles(target.path, ['.css', '.scss']).filter((f) => !isGenerated(f));
42
+ if (files.length === 0)
43
+ return [];
44
+ const tools = await jsTools(note);
45
+ const out = [];
46
+ for (const chunk of chunks(files, 200)) {
47
+ if (signal?.aborted)
48
+ break;
49
+ const r = await exec(process.execPath, [
50
+ path.join(tools, 'node_modules', 'stylelint', 'bin', 'stylelint.mjs'),
51
+ '--config', path.join(tools, 'stylelint.config.mjs'), '--config-basedir', tools,
52
+ '--formatter', 'json', '--allow-empty-input',
53
+ ...chunk.map((f) => posixRelative(target.path, f)),
54
+ ], { cwd: target.path, ...(signal ? { signal } : {}) });
55
+ // Stylelint prints its JSON to stderr when it finds problems.
56
+ const text = r.stdout.trim() || r.stderr.trim();
57
+ if (!text.startsWith('['))
58
+ throw new Error(`Stylelint stopped: ${firstLine(r.stderr) || firstLine(r.stdout)}`);
59
+ out.push(...parseStylelint(text, target.path));
60
+ }
61
+ return out;
62
+ },
63
+ };
@@ -0,0 +1,7 @@
1
+ import type { Engine, RawFinding } from '../types.ts';
2
+ export interface ThemeCheckMessage {
3
+ check: string;
4
+ html: string;
5
+ }
6
+ export declare function toFindings(messages: ThemeCheckMessage[], isFile: (rel: string) => boolean): RawFinding[];
7
+ export declare const themeCheck: Engine;
@@ -0,0 +1,109 @@
1
+ import { statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { exec } from '../exec.js';
5
+ import { phpBinary, phpVersion } from '../php/php.js';
6
+ import { phpTools } from '../php/tools.js';
7
+ // Resolves to the package root from both src/engines and dist/engines.
8
+ const runner = fileURLToPath(new URL('../../php-tools/theme-check.php', import.meta.url));
9
+ const ENTITIES = [
10
+ [/&lt;/g, '<'],
11
+ [/&gt;/g, '>'],
12
+ [/&quot;/g, '"'],
13
+ [/&#0?39;/g, "'"],
14
+ [/&amp;/g, '&'],
15
+ ];
16
+ const text = (html) => {
17
+ let s = html.replace(/<[^>]*>/g, '');
18
+ for (const [re, to] of ENTITIES)
19
+ s = s.replace(re, to);
20
+ return s.replace(/\s+/g, ' ').trim();
21
+ };
22
+ const SECURITY = ['bad-things', 'worms', 'escaping', 'iframe', 'non-printable', 'included-zip'];
23
+ const I18N = ['i18n', 'textdomain'];
24
+ const COMPAT = ['deprecated', 'deprecated-param', 'version-php', 'version-tested', 'php-short-tags'];
25
+ function categoryOf(rule) {
26
+ if (SECURITY.includes(rule))
27
+ return 'security';
28
+ if (I18N.includes(rule))
29
+ return 'i18n';
30
+ if (COMPAT.includes(rule))
31
+ return 'compatibility';
32
+ if (rule === 'screen-reader-text')
33
+ return 'accessibility';
34
+ // Not 'standards': the reports count that category per rule as code style, and a theme requirement must be listed.
35
+ return 'correctness';
36
+ }
37
+ export function toFindings(messages, isFile) {
38
+ const out = [];
39
+ for (const m of messages) {
40
+ const lead = /<span[^>]*tc-lead[^>]*>([\s\S]*?)<\/span>/.exec(m.html);
41
+ const type = lead ? text(lead[1]).toUpperCase() : '';
42
+ const severity = type === 'REQUIRED' ? 'error' : type === 'WARNING' ? 'warning' : 'info';
43
+ let rest = (lead ? m.html.slice(lead.index + lead[0].length) : m.html).replace(/^\s*:\s*/, '');
44
+ const lines = new Set();
45
+ for (const pre of rest.matchAll(/<pre[^>]*>[\s\S]*?<\/pre>/g)) {
46
+ for (const l of pre[0].matchAll(/Line (\d+):/g))
47
+ lines.add(Number(l[1]));
48
+ }
49
+ rest = rest.replace(/<pre[^>]*>[\s\S]*?<\/pre>/g, '');
50
+ const docs = /href=["'](https?:\/\/[^"']+)["']/.exec(rest)?.[1];
51
+ let file;
52
+ for (const s of rest.matchAll(/<strong>([\s\S]*?)<\/strong>/g)) {
53
+ const candidate = text(s[1]);
54
+ if (isFile(candidate)) {
55
+ file = candidate;
56
+ break;
57
+ }
58
+ }
59
+ const rule = m.check.replace(/_Check$/, '').toLowerCase().replace(/_/g, '-');
60
+ const base = { rule, severity, category: categoryOf(rule), message: text(rest), ...(docs ? { docs } : {}) };
61
+ const sorted = [...lines].sort((a, b) => a - b);
62
+ if (sorted.length === 0)
63
+ out.push({ ...base, location: file ? { file } : {} });
64
+ else
65
+ for (const line of sorted)
66
+ out.push({ ...base, location: { ...(file ? { file } : {}), line } });
67
+ }
68
+ return out;
69
+ }
70
+ const lastLine = (s) => s.split('\n').map((l) => l.trim()).filter(Boolean).pop() ?? '';
71
+ export const themeCheck = {
72
+ id: 'theme-check',
73
+ title: 'Theme Check',
74
+ kinds: ['theme'],
75
+ depth: 'quick',
76
+ variant: (profile) => (profile === 'envato' ? 'envato' : undefined),
77
+ async run({ target, signal, note, profile }) {
78
+ await phpVersion();
79
+ const tools = await phpTools(note);
80
+ const r = await exec(phpBinary(), ['-d', 'memory_limit=-1', runner, path.join(tools, 'vendor', ...(profile === 'envato' ? ['envato', 'envato-theme-check'] : ['theme-check', 'theme-check'])), target.path], signal ? { signal } : {});
81
+ if (r.code !== 0) {
82
+ const line = lastLine(r.stderr).replace(/^PHP /, '').replace(/^Fatal error: /, '');
83
+ throw new Error(`Theme Check stopped: ${line || `PHP exited with code ${r.code}.`}`);
84
+ }
85
+ let data;
86
+ try {
87
+ data = JSON.parse(r.stdout);
88
+ }
89
+ catch {
90
+ throw new Error('Theme Check returned output that is not JSON.');
91
+ }
92
+ if (!data || !Array.isArray(data.messages))
93
+ throw new Error('Theme Check returned output that is not JSON.');
94
+ if (typeof data.missingParent === 'string' && data.missingParent !== '') {
95
+ note(`The parent theme "${data.missingParent}" is not next to this theme. Checks that look for template code may report it missing.`);
96
+ }
97
+ return toFindings(data.messages, (rel) => {
98
+ if (rel === '' || rel.includes('..'))
99
+ return false;
100
+ try {
101
+ return statSync(path.join(target.path, rel), { throwIfNoEntry: false })?.isFile() === true;
102
+ }
103
+ catch {
104
+ // The text was a list of names or something else that is not a path.
105
+ return false;
106
+ }
107
+ });
108
+ },
109
+ };
@@ -0,0 +1,24 @@
1
+ import type { Engine, EngineContext, RawFinding } from '../types.ts';
2
+ export interface Theme {
3
+ ctx: EngineContext;
4
+ name: string;
5
+ /** POSIX paths relative to the theme folder, sorted. */
6
+ files: string[];
7
+ /** The text of a file. Empty for a file over 2 MB. */
8
+ read(file: string): string;
9
+ /** A header of style.css, or undefined. */
10
+ header(name: string): string | undefined;
11
+ /** The text of readme.txt, undefined when the theme has none. */
12
+ readme: string | undefined;
13
+ isBlock: boolean;
14
+ isChild: boolean;
15
+ }
16
+ export type Rule = (theme: Theme) => RawFinding[] | Promise<RawFinding[]>;
17
+ export declare function loadTheme(ctx: EngineContext): Theme;
18
+ /** The texts a visitor can read in a template, with their lines. Text in PHP blocks, comments, scripts and styles does not count. */
19
+ export declare function visibleTexts(source: string, kind: 'php' | 'html'): {
20
+ line: number;
21
+ text: string;
22
+ }[];
23
+ export declare const rules: Record<string, Rule>;
24
+ export declare const themeReview: Engine;