wp-shakedown 0.1.0 → 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 (44) hide show
  1. package/README.md +15 -3
  2. package/dist/cli.js +160 -3
  3. package/dist/diff.d.ts +2 -1
  4. package/dist/diff.js +5 -3
  5. package/dist/engines/config.js +1 -0
  6. package/dist/engines/custom.d.ts +10 -0
  7. package/dist/engines/custom.js +286 -0
  8. package/dist/engines/index.js +3 -1
  9. package/dist/engines/php-lint.js +1 -0
  10. package/dist/engines/phpstan.js +1 -0
  11. package/dist/engines/theme-check.d.ts +7 -0
  12. package/dist/engines/theme-check.js +109 -0
  13. package/dist/engines/theme-review.d.ts +24 -0
  14. package/dist/engines/theme-review.js +378 -0
  15. package/dist/engines/updates.d.ts +2 -0
  16. package/dist/engines/updates.js +6 -0
  17. package/dist/engines/wp-json.js +1 -0
  18. package/dist/hub.d.ts +32 -0
  19. package/dist/hub.js +99 -0
  20. package/dist/index.d.ts +5 -1
  21. package/dist/index.js +5 -1
  22. package/dist/mcp/tools.js +16 -2
  23. package/dist/profiles.d.ts +4 -0
  24. package/dist/profiles.js +41 -0
  25. package/dist/projects.d.ts +36 -0
  26. package/dist/projects.js +91 -0
  27. package/dist/report/html.js +1 -1
  28. package/dist/report/markdown.js +1 -1
  29. package/dist/runner.d.ts +4 -1
  30. package/dist/runner.js +16 -2
  31. package/dist/session.d.ts +4 -1
  32. package/dist/session.js +10 -2
  33. package/dist/types.d.ts +30 -0
  34. package/dist/types.js +2 -0
  35. package/dist/ui/server.js +218 -55
  36. package/package.json +2 -1
  37. package/php-tools/composer.json +29 -1
  38. package/php-tools/composer.lock +22 -1
  39. package/php-tools/theme-check.php +239 -0
  40. package/ui/dist/assets/index-DXwdz_Wu.css +2 -0
  41. package/ui/dist/assets/index-V8IOqxHa.js +54 -0
  42. package/ui/dist/index.html +2 -2
  43. package/ui/dist/assets/index-7zN46ssH.js +0 -54
  44. package/ui/dist/assets/index-B1axZya5.css +0 -2
@@ -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;
@@ -0,0 +1,378 @@
1
+ import { readFileSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { walk } from './custom.js';
4
+ import { latestWordPress } from './updates.js';
5
+ const DOCS = 'https://github.com/alexposlushnyak/wp-shakedown/blob/main/docs/explanation/theme-review-feedback.md';
6
+ const MAX_FILE = 2 * 1024 * 1024;
7
+ export function loadTheme(ctx) {
8
+ const { root, files } = walk(ctx.target);
9
+ const cache = new Map();
10
+ const read = (file) => {
11
+ let text = cache.get(file);
12
+ if (text === undefined) {
13
+ const full = path.join(root, file);
14
+ text = statSync(full).size > MAX_FILE ? '' : readFileSync(full, 'utf8');
15
+ cache.set(file, text);
16
+ }
17
+ return text;
18
+ };
19
+ const head = files.includes('style.css') ? read('style.css').slice(0, 8192) : '';
20
+ const header = (name) => {
21
+ const m = new RegExp(`^[ \\t/*#@]*${name}[ \\t]*:[ \\t]*(.*)$`, 'im').exec(head);
22
+ const v = m?.[1]?.replace(/\*\/\s*$/, '').trim();
23
+ return v ? v : undefined;
24
+ };
25
+ return {
26
+ ctx,
27
+ name: header('Theme Name') ?? ctx.target.name,
28
+ files,
29
+ read,
30
+ header,
31
+ readme: files.includes('readme.txt') ? read('readme.txt') : undefined,
32
+ isBlock: files.includes('templates/index.html'),
33
+ isChild: header('Template') !== undefined,
34
+ };
35
+ }
36
+ /** The share of recent theme reviews that raised each rule. */
37
+ const SHARE = {
38
+ 'untranslated-text': 23,
39
+ 'text-in-template': 23,
40
+ 'readme-headers': 18,
41
+ 'tested-up-to': 13,
42
+ 'asset-licenses': 31,
43
+ 'skip-link': 13,
44
+ 'minified-without-source': 11,
45
+ 'pot-missing': 5,
46
+ 'placeholder-content': 7,
47
+ 'readme-copyright': 17,
48
+ 'link-underline': 10,
49
+ 'plugin-territory': 6,
50
+ 'customizer-textareas': 5,
51
+ 'footer-copyright': 4,
52
+ 'remote-fonts': 7,
53
+ 'demo-content': 4,
54
+ };
55
+ function make(rule, severity, category, message, location, fix) {
56
+ return { rule, severity, category, message, location, hint: `${fix} Reviewers raised this in about ${SHARE[rule]}% of recent theme reviews.`, docs: DOCS };
57
+ }
58
+ const phpFiles = (t) => t.files.filter((f) => f.endsWith('.php'));
59
+ const ext = (f) => path.posix.extname(f).slice(1).toLowerCase();
60
+ const dir = (f) => (path.posix.dirname(f) === '.' ? '' : path.posix.dirname(f));
61
+ const isComment = (line) => /^(\*|\/\/|#)/.test(line.trim());
62
+ const cut = (s, n = 40) => (s.length > n ? `${s.slice(0, n)}...` : s);
63
+ /** Replaces every match with spaces and keeps the newlines, so line numbers stay right. */
64
+ const blank = (s, re) => s.replace(re, (m) => m.replace(/[^\n]/g, ' '));
65
+ /** The texts a visitor can read in a template, with their lines. Text in PHP blocks, comments, scripts and styles does not count. */
66
+ export function visibleTexts(source, kind) {
67
+ let s = source;
68
+ if (kind === 'php')
69
+ s = blank(s, /<\?(?:php|=)[\s\S]*?(?:\?>|$)/g);
70
+ s = blank(s, /<!--[\s\S]*?(?:-->|$)/g);
71
+ s = blank(s, /<(script|style)\b[\s\S]*?<\/\1\s*>/gi);
72
+ const found = [];
73
+ for (const m of s.matchAll(/>([^<>]*)</g))
74
+ found.push({ index: m.index + 1 + m[1].search(/\S|$/), text: m[1] });
75
+ for (const m of s.matchAll(/\b(?:alt|title|placeholder|aria-label)\s*=\s*"([^"]*)"/gi))
76
+ found.push({ index: m.index + m[0].indexOf('"') + 1, text: m[1] });
77
+ found.sort((a, b) => a.index - b.index);
78
+ const out = [];
79
+ for (const { index, text } of found) {
80
+ if (!/\p{L}{3,}/u.test(text.replace(/&(?:#\d+|#x[0-9a-f]+|[a-z]+);/gi, ' ')))
81
+ continue;
82
+ const line = s.slice(0, index).split('\n').length;
83
+ if (out.length && out[out.length - 1].line === line)
84
+ continue;
85
+ out.push({ line, text: text.trim().replace(/\s+/g, ' ') });
86
+ }
87
+ return out;
88
+ }
89
+ /** Calls `fn` for each line of a file, leaving out comment lines when asked. */
90
+ function eachLine(text, fn, skipComments = false) {
91
+ text.split('\n').forEach((line, i) => {
92
+ if (!skipComments || !isComment(line))
93
+ fn(line, i + 1);
94
+ });
95
+ }
96
+ export const rules = {
97
+ 'untranslated-text': (t) => phpFiles(t).flatMap((file) => visibleTexts(t.read(file), 'php').map(({ line, text }) => make('untranslated-text', 'warning', 'i18n', `The text "${cut(text)}" is not passed through a translation function.`, { file, line }, 'Wrap it in esc_html_e() or esc_attr_e() with the text domain of the theme.'))),
98
+ 'text-in-template': (t) => !t.isBlock
99
+ ? []
100
+ : t.files
101
+ .filter((f) => f.endsWith('.html') && /^(templates|parts)\//.test(f))
102
+ .flatMap((file) => visibleTexts(t.read(file), 'html').map(({ line, text }) => make('text-in-template', 'info', 'i18n', `The text "${cut(text)}" sits in an HTML template, where it cannot be translated.`, { file, line }, 'Move it into a PHP pattern and wrap it in a translation function.'))),
103
+ 'readme-headers': (t) => {
104
+ const fix = 'Follow the readme.txt format of the theme directory.';
105
+ const out = [];
106
+ const add = (message, line) => {
107
+ out.push(make('readme-headers', 'warning', 'other', message, { file: 'readme.txt', ...(line ? { line } : {}) }, fix));
108
+ };
109
+ if (t.readme === undefined) {
110
+ const wrong = t.files.find((f) => !f.includes('/') && /^readme\.(txt|md)$/i.test(f));
111
+ if (wrong)
112
+ out.push(make('readme-headers', 'warning', 'other', `The readme is named ${wrong}. Name it readme.txt.`, { file: wrong }, fix));
113
+ return out;
114
+ }
115
+ const lines = t.readme.split(/\r?\n/);
116
+ const first = lines.findIndex((l) => l.trim() !== '');
117
+ if (first < 0 || !/^===\s*.+?\s*===\s*$/.test(lines[first]))
118
+ add('readme.txt does not start with the theme name between === signs.', 1);
119
+ const value = (name) => {
120
+ const m = new RegExp(`^${name}\\s*:\\s*(.*)$`, 'im').exec(t.readme);
121
+ return m ? m[1].trim() : undefined;
122
+ };
123
+ for (const name of ['Contributors', 'Requires at least', 'Tested up to', 'Requires PHP', 'License', 'License URI']) {
124
+ if (value(name) === undefined)
125
+ add(`readme.txt has no "${name}:" line.`);
126
+ }
127
+ for (const name of ['Requires at least', 'Tested up to', 'Requires PHP', 'License']) {
128
+ const r = value(name);
129
+ const s = t.header(name);
130
+ // "GPLv2 or later" and "GNU General Public License v2 or later" name one license.
131
+ const norm = (v) => (name === 'License' ? v.toLowerCase().replace(/gnu\s+general\s+public\s+licen[sc]e/g, 'gpl').replace(/version/g, 'v').replace(/[^a-z0-9]/g, '') : v.toLowerCase());
132
+ if (r !== undefined && s !== undefined && norm(r) !== norm(s))
133
+ add(`"${name}" is ${r} in readme.txt and ${s} in style.css. Use the same value in both.`);
134
+ }
135
+ if (!/^==\s*Changelog\s*==/im.test(t.readme))
136
+ add('readme.txt has no Changelog section.');
137
+ return out;
138
+ },
139
+ 'tested-up-to': async (t) => {
140
+ const fromStyle = t.header('Tested up to');
141
+ const file = fromStyle !== undefined ? 'style.css' : 'readme.txt';
142
+ const value = fromStyle ?? (t.readme ? /^Tested up to\s*:\s*(.*)$/im.exec(t.readme)?.[1]?.trim() : undefined);
143
+ const have = value ? /^(\d+)\.(\d+)/.exec(value) : null;
144
+ if (!value || !have)
145
+ return [];
146
+ let latest;
147
+ try {
148
+ latest = await latestWordPress(t.ctx.signal);
149
+ }
150
+ catch {
151
+ // The note below covers every way the service can fail.
152
+ }
153
+ const want = latest ? /^(\d+)\.(\d+)/.exec(latest) : null;
154
+ if (!want) {
155
+ t.ctx.note('Could not ask wordpress.org for the latest version, so the Tested up to rule was left out.');
156
+ return [];
157
+ }
158
+ const older = Number(have[1]) < Number(want[1]) || (Number(have[1]) === Number(want[1]) && Number(have[2]) < Number(want[2]));
159
+ if (!older)
160
+ return [];
161
+ return [make('tested-up-to', 'warning', 'compatibility', `Tested up to is ${value}. The latest WordPress is ${want[1]}.${want[2]}.`, { file }, 'Test the theme with the latest WordPress and update the header.')];
162
+ },
163
+ 'asset-licenses': (t) => {
164
+ if (t.readme === undefined)
165
+ return [];
166
+ const readme = t.readme.toLowerCase();
167
+ const out = [];
168
+ const fix = 'List each bundled image with its copyright holder, license and source URL. A line that names the folder covers every file in it.';
169
+ const group = (exts) => {
170
+ const m = new Map();
171
+ for (const f of t.files) {
172
+ if (!exts.includes(ext(f)))
173
+ continue;
174
+ m.set(dir(f), [...(m.get(dir(f)) ?? []), f]);
175
+ }
176
+ return m;
177
+ };
178
+ for (const [folder, files] of group(['png', 'jpg', 'jpeg', 'webp', 'gif', 'svg', 'avif'])) {
179
+ const uncovered = files.filter((f) => {
180
+ const name = path.posix.basename(f).toLowerCase();
181
+ if (folder === '' && /^screenshot\./.test(name))
182
+ return false;
183
+ const base = name.slice(0, name.length - path.posix.extname(name).length);
184
+ return !((folder !== '' && readme.includes(folder.toLowerCase())) || readme.includes(name) || (base.length >= 4 && readme.includes(base)));
185
+ });
186
+ if (!uncovered.length)
187
+ continue;
188
+ const where = folder === '' ? 'the theme folder' : folder;
189
+ const message = uncovered.length === 1 ? `1 image in ${where} is not listed in readme.txt.` : `${uncovered.length} images in ${where} are not listed in readme.txt.`;
190
+ out.push(make('asset-licenses', 'warning', 'other', message, { file: uncovered[0] }, fix));
191
+ }
192
+ const shot = t.files.find((f) => /^screenshot\.(png|jpg|jpeg|webp)$/i.test(f));
193
+ if (shot && !readme.includes('screenshot')) {
194
+ out.push(make('asset-licenses', 'warning', 'other', 'readme.txt does not say where the images in the screenshot come from.', { file: shot }, fix));
195
+ }
196
+ const licenses = new Set(t.files.filter((f) => /^(ofl|license|licence|copying)/i.test(path.posix.basename(f))).map(dir));
197
+ for (const [folder, files] of group(['woff', 'woff2', 'ttf', 'otf'])) {
198
+ if (licenses.has(folder) || licenses.has(dir(folder)) || (folder !== '' && readme.includes(folder.toLowerCase())))
199
+ continue;
200
+ // "FiraSans-Bold.woff2" is covered by a readme that says "Fira Sans".
201
+ const squashed = readme.replace(/[^a-z0-9]/g, '');
202
+ const family = (f) => path.posix.basename(f).split(/[-_.]/)[0].toLowerCase().replace(/[^a-z0-9]/g, '');
203
+ const uncovered = files.filter((f) => family(f).length < 3 || !squashed.includes(family(f)));
204
+ if (!uncovered.length)
205
+ continue;
206
+ out.push(make('asset-licenses', 'warning', 'other', `The fonts in ${folder === '' ? 'the theme folder' : folder} have no license file, and readme.txt does not list them.`, { file: uncovered[0] }, 'Put the license file of the font next to it and name the font, its license and its source in readme.txt.'));
207
+ }
208
+ return out;
209
+ },
210
+ 'skip-link': (t) => {
211
+ if (t.isChild)
212
+ return [];
213
+ if (t.isBlock) {
214
+ const has = t.files.some((f) => f.endsWith('.html') && /^(templates|parts)\//.test(f) && /"tagName"\s*:\s*"main"/.test(t.read(f)));
215
+ return has
216
+ ? []
217
+ : [make('skip-link', 'warning', 'accessibility', 'No template has a group with the tag name main, so WordPress adds no skip link.', { file: 'templates/index.html' }, 'Set the HTML element of the main content group to main.')];
218
+ }
219
+ const has = phpFiles(t).some((f) => (t.read(f).match(/<a\b[^>]*>/gi) ?? []).some((tag) => /\bhref\s*=\s*["']#/i.test(tag) && /\bclass\s*=\s*["'][^"']*skip/i.test(tag)));
220
+ return has
221
+ ? []
222
+ : [make('skip-link', 'warning', 'accessibility', 'No skip link to the main content was found.', t.files.includes('header.php') ? { file: 'header.php' } : {}, 'Add a link right after wp_body_open() that points to the id of the main element.')];
223
+ },
224
+ 'minified-without-source': (t) => {
225
+ const names = new Set(t.files.map((f) => path.posix.basename(f)));
226
+ return t.files
227
+ .filter((f) => /\.min\.(js|css)$/.test(f) && !names.has(path.posix.basename(f).replace(/\.min\.(js|css)$/, '.$1')))
228
+ .map((file) => make('minified-without-source', 'warning', 'other', `${file} has no readable source in the theme.`, { file }, 'Ship the original file next to it, or ship the file without minification.'));
229
+ },
230
+ 'pot-missing': (t) => {
231
+ const ready = /translation-ready/i.test(t.header('Tags') ?? '');
232
+ if (!ready || t.files.some((f) => f.endsWith('.pot')))
233
+ return [];
234
+ return [
235
+ make('pot-missing', 'info', 'i18n', 'The theme has the tag translation-ready but no .pot file.', { file: 'style.css' }, `Generate one with: wp i18n make-pot . languages/${path.basename(t.ctx.target.path)}.pot`),
236
+ ];
237
+ },
238
+ 'placeholder-content': (t) => {
239
+ const out = [];
240
+ const fix = 'Demo content must not point at real people, and a link has to lead somewhere.';
241
+ for (const file of t.files.filter((f) => /^(templates|parts|patterns)\//.test(f) && /\.(html|php)$/.test(f))) {
242
+ const empty = [];
243
+ eachLine(t.read(file), (line, n) => {
244
+ if (/@author|@package|@link|@see/.test(line))
245
+ return;
246
+ const email = [...line.matchAll(/[A-Za-z0-9._%+-]+@([A-Za-z0-9.-]+\.[A-Za-z]{2,})/g)].find((m) => !['example.com', 'example.org', 'example.net'].includes(m[1].toLowerCase()));
247
+ if (email)
248
+ out.push(make('placeholder-content', 'warning', 'other', `The address ${email[0]} looks real. Use a placeholder such as hello@example.com.`, { file, line: n }, fix));
249
+ if ((line.match(/<a\b[^>]*\bhref\s*=\s*["']#["'][^>]*>/gi) ?? []).some((tag) => !/\brole\s*=\s*["']button["']/i.test(tag) && !/\baria-controls\b/i.test(tag))) {
250
+ empty.push(n);
251
+ }
252
+ });
253
+ // Patterns are full of these. One finding per file keeps the report readable.
254
+ if (empty.length) {
255
+ out.push(make('placeholder-content', 'info', 'other', empty.length === 1 ? 'A link points to "#".' : `${empty.length} links point to "#".`, { file, line: empty[0] }, fix));
256
+ }
257
+ }
258
+ return out;
259
+ },
260
+ 'readme-copyright': (t) => {
261
+ if (t.readme === undefined)
262
+ return [];
263
+ const out = [];
264
+ const name = t.header('Theme Name');
265
+ if (name && !t.readme.split('\n').some((l) => /(copyright|\(c\)|©)[^\n]{0,20}\d{4}/i.test(l) && l.toLowerCase().includes(name.toLowerCase()))) {
266
+ out.push(make('readme-copyright', 'warning', 'other', 'readme.txt has no copyright notice that names the theme.', { file: 'readme.txt' }, `Add a line such as "${name} WordPress Theme, Copyright ${new Date().getFullYear()} ${t.header('Author') ?? 'the author'}".`));
267
+ }
268
+ const license = t.files.find((f) => /^(license|licence)(\.txt|\.md)?$/i.test(f));
269
+ if (license && !t.read(license).includes('TERMS AND CONDITIONS FOR COPYING')) {
270
+ out.push(make('readme-copyright', 'info', 'other', `${license} does not hold the full text of the GPL.`, { file: license }, 'Use the full license text from gnu.org.'));
271
+ }
272
+ return out;
273
+ },
274
+ 'link-underline': (t) => {
275
+ if (!t.files.includes('theme.json'))
276
+ return [];
277
+ let json;
278
+ try {
279
+ json = JSON.parse(t.read('theme.json'));
280
+ }
281
+ catch {
282
+ return [];
283
+ }
284
+ const own = json?.styles?.elements?.link?.typography?.textDecoration;
285
+ const inContent = json?.styles?.blocks?.['core/post-content']?.elements?.link?.typography?.textDecoration;
286
+ if (own !== 'none' || (inContent !== undefined && inContent !== 'none'))
287
+ return [];
288
+ return [make('link-underline', 'warning', 'accessibility', 'Links are not underlined (styles.elements.link in theme.json).', { file: 'theme.json' }, 'Underline links inside content, so they differ from the text by more than color.')];
289
+ },
290
+ 'plugin-territory': (t) => {
291
+ const patterns = [
292
+ [/<meta\s+name=["']description/i, 'The theme prints a meta description. SEO metadata belongs in a plugin.'],
293
+ [/<meta\s+property=["']og:/i, 'The theme prints Open Graph tags. Social metadata belongs in a plugin.'],
294
+ [/application\/ld\+json/i, 'The theme prints structured data. That belongs in a plugin.'],
295
+ [/\bwp_mail\s*\(/, 'The theme sends mail with wp_mail(). That belongs in a plugin.'],
296
+ [/wp_ajax_nopriv_/, 'The theme registers an AJAX action for visitors who are not logged in. That belongs in a plugin.'],
297
+ [/\bregister_rest_route\s*\(/, 'The theme registers a REST route. That belongs in a plugin.'],
298
+ ];
299
+ const out = [];
300
+ for (const file of phpFiles(t)) {
301
+ eachLine(t.read(file), (line, n) => {
302
+ for (const [re, message] of patterns)
303
+ if (re.test(line))
304
+ out.push(make('plugin-territory', 'warning', 'correctness', message, { file, line: n }, 'Move this into a plugin, or remove it.'));
305
+ }, true);
306
+ }
307
+ return out;
308
+ },
309
+ 'customizer-textareas': (t) => {
310
+ let n = 0;
311
+ for (const f of phpFiles(t))
312
+ n += (t.read(f).match(/['"]type['"]\s*=>\s*['"]textarea['"]|WP_Customize_Code_Editor_Control/g) ?? []).length;
313
+ return n > 3
314
+ ? [make('customizer-textareas', 'info', 'other', `The Customizer has ${n} textarea controls. Reviewers ask for three at most.`, {}, 'Keep content in the editor and use the Customizer for design options.')]
315
+ : [];
316
+ },
317
+ 'footer-copyright': (t) => {
318
+ const names = [t.header('Theme Name'), t.header('Author')].filter((v) => !!v && v.length >= 3).map((v) => v.toLowerCase());
319
+ if (!names.length)
320
+ return [];
321
+ const out = [];
322
+ const files = t.files.filter((f) => f === 'footer.php' || /^parts\/footer[^/]*\.html$/.test(f) || (/^patterns\//.test(f) && path.posix.basename(f).includes('footer')));
323
+ for (const file of files) {
324
+ eachLine(t.read(file), (line, n) => {
325
+ const low = line.toLowerCase();
326
+ if ((line.includes('©') || low.includes('&copy;') || low.includes('copyright')) && names.some((v) => low.includes(v))) {
327
+ out.push(make('footer-copyright', 'warning', 'other', 'A copyright line names the theme or its author.', { file, line: n }, 'On a site the copyright belongs to the site. Use the site title, for example the Site Title block.'));
328
+ }
329
+ }, true);
330
+ }
331
+ return out;
332
+ },
333
+ 'remote-fonts': (t) => {
334
+ const out = [];
335
+ for (const file of t.files.filter((f) => ['php', 'css', 'scss', 'html', 'json', 'js'].includes(ext(f)))) {
336
+ eachLine(t.read(file), (line, n) => {
337
+ const host = ['fonts.googleapis.com', 'fonts.gstatic.com', 'use.typekit.net', 'fonts.bunny.net'].find((h) => line.includes(h));
338
+ if (host)
339
+ out.push(make('remote-fonts', 'warning', 'other', `Fonts are loaded from ${host}.`, { file, line: n }, 'Bundle the font files in the theme.'));
340
+ });
341
+ }
342
+ return out;
343
+ },
344
+ 'demo-content': (t) => {
345
+ const out = [];
346
+ for (const file of phpFiles(t)) {
347
+ eachLine(t.read(file), (line, n) => {
348
+ if (line.includes('ocdi/') || /\bwp_insert_user\s*\(/.test(line) || /\bwp_create_category\s*\(/.test(line)) {
349
+ out.push(make('demo-content', 'warning', 'correctness', 'The theme imports demo content or creates content of its own.', { file, line: n }, 'That belongs in a plugin. A theme must not add content to the site.'));
350
+ }
351
+ }, true);
352
+ }
353
+ return out;
354
+ },
355
+ };
356
+ export const themeReview = {
357
+ id: 'theme-review',
358
+ title: 'Theme review feedback',
359
+ kinds: ['theme'],
360
+ experimental: true,
361
+ async run(ctx) {
362
+ const theme = loadTheme(ctx);
363
+ const out = [];
364
+ const failed = [];
365
+ for (const [id, rule] of Object.entries(rules)) {
366
+ try {
367
+ out.push(...(await rule(theme)));
368
+ }
369
+ catch (err) {
370
+ failed.push(err);
371
+ ctx.note(`The rule ${id} could not run: ${err instanceof Error ? err.message : String(err)}`);
372
+ }
373
+ }
374
+ if (failed.length === Object.keys(rules).length)
375
+ throw failed[0];
376
+ return out;
377
+ },
378
+ };
@@ -1,4 +1,6 @@
1
1
  import type { Engine } from '../types.ts';
2
2
  /** Whole days from a YYYY-MM-DD start of the text to now. Undefined when the text has no date. */
3
3
  export declare function daysSince(dateText: string, now: Date): number | undefined;
4
+ /** The latest WordPress version, or undefined when the service gives none. Throws Unreachable when it cannot be reached. */
5
+ export declare function latestWordPress(signal?: AbortSignal): Promise<string | undefined>;
4
6
  export declare const updates: Engine;
@@ -10,6 +10,12 @@ export function daysSince(dateText, now) {
10
10
  return undefined;
11
11
  return Math.floor((now.getTime() - Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]))) / 86400000);
12
12
  }
13
+ /** The latest WordPress version, or undefined when the service gives none. Throws Unreachable when it cannot be reached. */
14
+ export async function latestWordPress(signal) {
15
+ const offers = rec((await getJson('https://api.wordpress.org/core/version-check/1.7/', { ttlMs: HALF_DAY, ...(signal ? { signal } : {}) })).data)?.offers;
16
+ const latest = rec(Array.isArray(offers) ? offers[0] : undefined)?.version;
17
+ return typeof latest === 'string' ? latest : undefined;
18
+ }
13
19
  export const updates = {
14
20
  id: 'updates',
15
21
  title: 'Updates',
@@ -101,6 +101,7 @@ export const wpJson = {
101
101
  id: 'wp-json',
102
102
  title: 'theme.json and block.json',
103
103
  kinds: ['theme', 'plugin'],
104
+ depth: 'quick',
104
105
  async run({ target, signal }) {
105
106
  const files = jsonFiles(target);
106
107
  const out = [];
package/dist/hub.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ import type { Project } from './projects.ts';
2
+ import type { SessionOptions } from './session.ts';
3
+ import type { RunEvent, RunResult, Severity } from './types.ts';
4
+ export interface HubRow {
5
+ /** The target name once the run has started, the base name of the path before. */
6
+ name: string;
7
+ path: string;
8
+ /** failed: the run itself threw. */
9
+ state: 'waiting' | 'running' | 'done' | 'failed';
10
+ /** Jobs of the run, 0 before it starts. */
11
+ total: number;
12
+ /** Engines finished so far. */
13
+ done: number;
14
+ /** "wpcs" or "wpcs theme:twentytwenty" while an engine runs. */
15
+ current?: string;
16
+ result?: RunResult;
17
+ reportFile?: string;
18
+ error?: string;
19
+ }
20
+ export interface HubOptions {
21
+ jobs: number;
22
+ session: Omit<SessionOptions, 'input' | 'onEvent'>;
23
+ onChange?: (rows: HubRow[], changed: HubRow, event?: RunEvent) => void;
24
+ }
25
+ /** Runs the sessions with at most `jobs` at a time. One run that throws makes that row failed and nothing more. */
26
+ export declare function runMany(inputs: string[], opts: HubOptions): Promise<HubRow[]>;
27
+ /** One line per row for the live view. */
28
+ export declare function hubLines(rows: HubRow[], width: number): string[];
29
+ /** 2 when a run failed or any run's exit code is 2, else 1 when any is 1, else 0. */
30
+ export declare function hubExitCode(rows: HubRow[], failOn: Severity | 'never'): 0 | 1 | 2;
31
+ /** The text table of the project list: a header row and one row per project, columns padded with spaces. */
32
+ export declare function projectTable(projects: Project[]): string;