readme-guide 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +46 -2
- package/bin/readme-guide.mjs +125 -0
- package/package.json +43 -4
- package/rules/blocks.json +123 -0
- package/rules/conventions.json +39 -0
- package/rules/headings.json +556 -0
- package/rules/project-types.json +37 -0
- package/rules/rules.json +3575 -0
- package/src/checks/ai.js +41 -0
- package/src/checks/commands.js +248 -0
- package/src/checks/env.js +112 -0
- package/src/checks/folders.js +138 -0
- package/src/checks/license.js +137 -0
- package/src/checks/media.js +110 -0
- package/src/checks/structure.js +248 -0
- package/src/checks/types.js +55 -0
- package/src/checks/util.js +148 -0
- package/src/checks/versions.js +109 -0
- package/src/data.js +76 -0
- package/src/detect.js +83 -0
- package/src/explain.js +150 -0
- package/src/format.js +153 -0
- package/src/lint.js +142 -0
- package/src/markdown.js +424 -0
- package/src/project.js +86 -0
- package/src/sections.js +167 -0
- package/src/semver.js +104 -0
package/src/checks/ai.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// AI 讀得懂類規則:指代不明的片語、對 AI 說話的句子。只看程式碼以外的文字。
|
|
2
|
+
import { stripPlaceholders } from '../data.js';
|
|
3
|
+
import { proseLines } from './util.js';
|
|
4
|
+
|
|
5
|
+
const VAGUE_REFERENCES = [
|
|
6
|
+
/如上所述|如上所示|如上圖|如上表|如前所述|如前面所說|前面提到的?|照之前那樣|承上/g,
|
|
7
|
+
/同上(?=[\s,。、;))|]|$)/g,
|
|
8
|
+
/\bas (?:mentioned|described|shown|stated) (?:above|earlier|before|previously)\b/gi,
|
|
9
|
+
/\b(?:see|same as) above\b/gi,
|
|
10
|
+
/\bas before\b/gi,
|
|
11
|
+
];
|
|
12
|
+
|
|
13
|
+
const AI_DIRECTED = [
|
|
14
|
+
/你是一(?:個|位|名)[^,。,.\n]{0,12}?(?:AI|助理|助手|工程師|開發者|專家|程式設計師|顧問|設計師|寫手)/g,
|
|
15
|
+
/(?:^\s*(?:[-*+>]\s+|\d+[.)]\s+)?|[.!?。!?]\s*)You are (?:an? )?(?:expert|senior|helpful|professional|experienced|world-class)\b[^.!?。]*/gi,
|
|
16
|
+
/(?:^\s*(?:[-*+>]\s+|\d+[.)]\s+)?|[.!?。!?]\s*)You are an? (?:AI|assistant|coding assistant|language model)\b[^.!?。]*/gi,
|
|
17
|
+
/\bAs an AI\b[^.!?。]*/gi,
|
|
18
|
+
/\bignore (?:all )?(?:the )?previous instructions\b/gi,
|
|
19
|
+
/忽略(?:之前|先前|以上)(?:所有)?的?(?:指示|指令)/g,
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
function scan(ctx, patterns) {
|
|
23
|
+
const out = [];
|
|
24
|
+
for (const line of proseLines(ctx.md)) {
|
|
25
|
+
const text = stripPlaceholders(line.prose);
|
|
26
|
+
for (const pattern of patterns) {
|
|
27
|
+
for (const m of text.matchAll(pattern)) {
|
|
28
|
+
const phrase = m[0].replace(/^[^A-Za-z\p{Script=Han}]+/u, '').trim();
|
|
29
|
+
if (!phrase) continue;
|
|
30
|
+
const column = m.index + m[0].indexOf(phrase) + 1;
|
|
31
|
+
out.push({ messageKey: 'found', params: { text: phrase.length > 40 ? `${phrase.slice(0, 40)}…` : phrase }, line: line.line, column });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const checks = {
|
|
39
|
+
AIR001: (ctx) => scan(ctx, VAGUE_REFERENCES),
|
|
40
|
+
AIR005: (ctx) => scan(ctx, AI_DIRECTED),
|
|
41
|
+
};
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
// 指令類規則:程式碼區塊的語言、指令區塊的內容、套件管理工具與 scripts 是否對得上專案。
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { readPackageJson } from '../project.js';
|
|
4
|
+
import { stripPlaceholders } from '../data.js';
|
|
5
|
+
import { findSection } from '../sections.js';
|
|
6
|
+
import {
|
|
7
|
+
CJK_LETTER,
|
|
8
|
+
commandBlocks,
|
|
9
|
+
isDemoBlock,
|
|
10
|
+
commandLinesOf,
|
|
11
|
+
shellBlocks,
|
|
12
|
+
splitSegments,
|
|
13
|
+
stripPrompt,
|
|
14
|
+
stripQuotedAndComment,
|
|
15
|
+
tokenize,
|
|
16
|
+
} from './util.js';
|
|
17
|
+
|
|
18
|
+
const LOCKFILES = [
|
|
19
|
+
['pnpm-lock.yaml', 'pnpm'],
|
|
20
|
+
['yarn.lock', 'yarn'],
|
|
21
|
+
['package-lock.json', 'npm'],
|
|
22
|
+
['npm-shrinkwrap.json', 'npm'],
|
|
23
|
+
['bun.lock', 'bun'],
|
|
24
|
+
['bun.lockb', 'bun'],
|
|
25
|
+
];
|
|
26
|
+
const MANAGERS = ['npm', 'pnpm', 'yarn', 'bun'];
|
|
27
|
+
|
|
28
|
+
// 不帶 run 也會被當成 script 執行的常見名稱(只對這些名稱檢查,避免把套件附的指令誤判成 script)
|
|
29
|
+
const COMMON_SCRIPT_NAMES = new Set(['dev', 'serve', 'start', 'build', 'preview', 'lint', 'format', 'test', 'watch', 'generate', 'typecheck', 'type-check', 'storybook', 'e2e', 'coverage']);
|
|
30
|
+
// 套件管理工具自己的指令,不是 script
|
|
31
|
+
const PNPM_BUILTINS = new Set(['add', 'install', 'i', 'remove', 'rm', 'uninstall', 'update', 'up', 'upgrade', 'exec', 'dlx', 'create', 'init', 'publish', 'store', 'list', 'ls', 'why', 'outdated', 'audit', 'link', 'unlink', 'prune', 'rebuild', 'import', 'setup', 'env', 'config', 'fetch', 'deploy', 'patch', 'patch-commit', 'licenses', 'root', 'bin', 'pack', 'server', 'recursive', 'approve-builds', 'self-update', 'doctor']);
|
|
32
|
+
const YARN_BUILTINS = new Set(['add', 'install', 'remove', 'upgrade', 'up', 'init', 'dlx', 'create', 'workspace', 'workspaces', 'global', 'why', 'info', 'config', 'cache', 'set', 'plugin', 'version', 'pack', 'npm', 'node', 'exec', 'bin', 'link', 'unlink', 'constraints', 'explain', 'import', 'outdated', 'audit', 'publish', 'login', 'logout']);
|
|
33
|
+
|
|
34
|
+
/** 專案用的套件管理工具:鎖定檔與 packageManager 一致才算數 */
|
|
35
|
+
export function projectManager(project, pkg) {
|
|
36
|
+
const locks = LOCKFILES.filter(([file]) => project.exists(file));
|
|
37
|
+
const fromLock = [...new Set(locks.map(([, pm]) => pm))];
|
|
38
|
+
const fromField = typeof pkg?.packageManager === 'string' ? pkg.packageManager.split('@')[0] : null;
|
|
39
|
+
if (fromLock.length > 1) return null;
|
|
40
|
+
if (fromLock.length === 1) {
|
|
41
|
+
if (fromField && fromField !== fromLock[0]) return null;
|
|
42
|
+
return { name: fromLock[0], evidence: locks.find(([, pm]) => pm === fromLock[0])[0] };
|
|
43
|
+
}
|
|
44
|
+
if (fromField && MANAGERS.includes(fromField)) return { name: fromField, evidence: 'package.json packageManager' };
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 全域安裝工具(例如 npm install -g pnpm)不算專案的安裝指令 */
|
|
49
|
+
function isGlobalInstall(tokens) {
|
|
50
|
+
return tokens.includes('-g') || tokens.includes('--global') || (tokens[0] === 'yarn' && tokens[1] === 'global');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 每個指令區塊裡的指令(依出現順序) */
|
|
54
|
+
function* commandSegments(md) {
|
|
55
|
+
for (const block of commandBlocks(md)) {
|
|
56
|
+
for (const { line, text } of commandLinesOf(block)) {
|
|
57
|
+
for (const segment of splitSegments(text)) {
|
|
58
|
+
yield { block, line, segment, tokens: tokenize(segment) };
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* 從一個套件管理工具指令找出要執行的 script 名稱;不是執行 script 時傳回 null。
|
|
66
|
+
* @returns {{name:string, explicit:boolean}|null}
|
|
67
|
+
*/
|
|
68
|
+
function scriptOf(tokens, pkg) {
|
|
69
|
+
const [pm, ...rest] = tokens;
|
|
70
|
+
if (!MANAGERS.includes(pm) || rest.length === 0) return null;
|
|
71
|
+
// 指定其他子專案的指令(monorepo)不檢查
|
|
72
|
+
if (rest.some((t) => ['--filter', '-F', '-C', '--dir', '--prefix', '-w', '--workspace', '-r', '--recursive', '--workspaces'].includes(t) || t.startsWith('--filter=') || t.startsWith('--workspace='))) return null;
|
|
73
|
+
const args = rest.filter((t) => !t.startsWith('-'));
|
|
74
|
+
const [command, next] = args;
|
|
75
|
+
if (!command) return null;
|
|
76
|
+
if (command === 'run' || command === 'run-script') return next ? { name: next, explicit: true } : null;
|
|
77
|
+
if (['test', 't', 'tst'].includes(command)) return pm === 'bun' ? null : { name: 'test', explicit: true };
|
|
78
|
+
if (['start', 'stop', 'restart'].includes(command)) return pm === 'bun' ? null : { name: command, explicit: true, builtin: command };
|
|
79
|
+
if (pm === 'npm' || pm === 'bun') return null;
|
|
80
|
+
if (pm === 'pnpm' && PNPM_BUILTINS.has(command)) return null;
|
|
81
|
+
if (pm === 'yarn' && YARN_BUILTINS.has(command)) return null;
|
|
82
|
+
// pnpm dev、yarn build 這類省略 run 的寫法:只檢查常見的 script 名稱,而且不能是套件附的指令
|
|
83
|
+
const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
|
|
84
|
+
if (command in deps) return null;
|
|
85
|
+
if (COMMON_SCRIPT_NAMES.has(command) || command.includes(':')) return { name: command, explicit: false };
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// CMD003 檢查的區塊語言:會直接複製去執行的 shell,或沒標語言
|
|
90
|
+
const PROMPT_LANGS = new Set(['bash', 'sh', 'shell', 'zsh', '']);
|
|
91
|
+
// 行首的「$ 」提示符號;$HOME、$(…)、${…} 這種變數或子指令不算
|
|
92
|
+
const PROMPT_LINE = /^\s*\$\s+\S/;
|
|
93
|
+
|
|
94
|
+
export const checks = {
|
|
95
|
+
CMD003(ctx) {
|
|
96
|
+
const problems = [];
|
|
97
|
+
for (const block of ctx.md.codeBlocks) {
|
|
98
|
+
if (!PROMPT_LANGS.has(block.lang) || isDemoBlock(block)) continue;
|
|
99
|
+
const hits = block.lines.filter(({ text }) => PROMPT_LINE.test(text));
|
|
100
|
+
if (!hits.length) continue;
|
|
101
|
+
const first = hits[0].line;
|
|
102
|
+
const last = hits.at(-1).line;
|
|
103
|
+
const lines =
|
|
104
|
+
first === last
|
|
105
|
+
? { 'zh-TW': `第 ${first} 行`, en: `line ${first}` }
|
|
106
|
+
: { 'zh-TW': `第 ${first}–${last} 行`, en: `lines ${first}–${last}` };
|
|
107
|
+
problems.push({ messageKey: 'prompt', params: { lines }, line: first, column: hits[0].text.indexOf('$') + 1 });
|
|
108
|
+
}
|
|
109
|
+
return problems;
|
|
110
|
+
},
|
|
111
|
+
|
|
112
|
+
CMD002(ctx) {
|
|
113
|
+
return ctx.md.codeBlocks.filter((b) => b.lang === '').map((b) => ({ messageKey: 'missing', line: b.startLine, column: 1 }));
|
|
114
|
+
},
|
|
115
|
+
|
|
116
|
+
CMD004(ctx) {
|
|
117
|
+
const manager = projectManager(ctx.project, ctx.pkg);
|
|
118
|
+
if (!manager) return [];
|
|
119
|
+
const byBlock = new Map();
|
|
120
|
+
for (const item of commandSegments(ctx.md)) {
|
|
121
|
+
const pm = item.tokens[0];
|
|
122
|
+
if (!MANAGERS.includes(pm) || isGlobalInstall(item.tokens)) continue;
|
|
123
|
+
if (!byBlock.has(item.block)) byBlock.set(item.block, []);
|
|
124
|
+
byBlock.get(item.block).push({ ...item, pm });
|
|
125
|
+
}
|
|
126
|
+
const out = [];
|
|
127
|
+
for (const items of byBlock.values()) {
|
|
128
|
+
// 同一個區塊同時列了專案用的管理器,視為「列出多種做法」,不在這裡報
|
|
129
|
+
if (items.some((it) => it.pm === manager.name)) continue;
|
|
130
|
+
const reported = new Set();
|
|
131
|
+
for (const it of items) {
|
|
132
|
+
if (it.pm === manager.name || reported.has(it.line)) continue;
|
|
133
|
+
reported.add(it.line);
|
|
134
|
+
const column = it.block.lines.find((l) => l.line === it.line).text.indexOf(it.pm) + 1;
|
|
135
|
+
out.push({ messageKey: 'mismatch', params: { used: it.pm, expected: manager.name, evidence: manager.evidence }, line: it.line, column });
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return out;
|
|
139
|
+
},
|
|
140
|
+
|
|
141
|
+
CMD005(ctx) {
|
|
142
|
+
const { project } = ctx;
|
|
143
|
+
if (!ctx.pkg) return [];
|
|
144
|
+
const out = [];
|
|
145
|
+
const cache = new Map();
|
|
146
|
+
const pkgAt = (dir) => {
|
|
147
|
+
if (!cache.has(dir)) cache.set(dir, readPackageJson(project, dir));
|
|
148
|
+
return cache.get(dir);
|
|
149
|
+
};
|
|
150
|
+
let cwd = '.';
|
|
151
|
+
let lastBlock = null;
|
|
152
|
+
const cloneNames = new Set([project.name]);
|
|
153
|
+
for (const item of commandSegments(ctx.md)) {
|
|
154
|
+
const { tokens } = item;
|
|
155
|
+
// 切到子資料夾(或不知道切到哪)之後,下一個程式碼區塊在哪個資料夾執行就不確定了,先不檢查
|
|
156
|
+
if (item.block !== lastBlock) {
|
|
157
|
+
if (lastBlock && cwd !== '.') cwd = null;
|
|
158
|
+
lastBlock = item.block;
|
|
159
|
+
}
|
|
160
|
+
if (tokens[0] === 'git' && tokens[1] === 'clone') {
|
|
161
|
+
const url = tokens.slice(2).find((t) => !t.startsWith('-'));
|
|
162
|
+
const dirArg = tokens.slice(2).filter((t) => !t.startsWith('-'))[1];
|
|
163
|
+
if (url) cloneNames.add(url.replace(/\/+$/, '').split(/[/:]/).pop().replace(/\.git$/, ''));
|
|
164
|
+
if (dirArg) cloneNames.add(dirArg);
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
if (tokens[0] === 'cd') {
|
|
168
|
+
const target = tokens[1];
|
|
169
|
+
if (!target || target === '~') {
|
|
170
|
+
cwd = null;
|
|
171
|
+
} else if (cwd !== null && cloneNames.has(target.replace(/\/+$/, '')) && cwd === '.') {
|
|
172
|
+
cwd = '.';
|
|
173
|
+
} else if (cwd !== null) {
|
|
174
|
+
const next = path.posix.normalize(path.posix.join(cwd, target));
|
|
175
|
+
cwd = !next.startsWith('..') && project.isDir(next) ? next : null;
|
|
176
|
+
}
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
if (cwd === null) continue;
|
|
180
|
+
const pkg = pkgAt(cwd);
|
|
181
|
+
if (!pkg) continue;
|
|
182
|
+
const script = scriptOf(tokens, pkg);
|
|
183
|
+
if (!script) continue;
|
|
184
|
+
const scripts = pkg.scripts ?? {};
|
|
185
|
+
if (script.name in scripts) continue;
|
|
186
|
+
// npm start 沒有 start script 時,會改跑 server.js
|
|
187
|
+
if (script.builtin === 'start' && project.exists(cwd === '.' ? 'server.js' : `${cwd}/server.js`)) continue;
|
|
188
|
+
if (script.builtin === 'restart' || script.builtin === 'stop') continue;
|
|
189
|
+
const names = Object.keys(scripts);
|
|
190
|
+
const column = item.block.lines.find((l) => l.line === item.line).text.indexOf(tokens[0]) + 1;
|
|
191
|
+
out.push(
|
|
192
|
+
names.length
|
|
193
|
+
? { messageKey: 'missing', params: { script: script.name, available: { 'zh-TW': names.join('、'), en: names.join(', ') } }, line: item.line, column }
|
|
194
|
+
: { messageKey: 'noScripts', params: { script: script.name }, line: item.line, column },
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
return out;
|
|
198
|
+
},
|
|
199
|
+
|
|
200
|
+
CMD008(ctx) {
|
|
201
|
+
const out = [];
|
|
202
|
+
for (const block of shellBlocks(ctx.md)) {
|
|
203
|
+
for (const { line, text } of block.lines) {
|
|
204
|
+
const clean = stripPrompt(stripPlaceholders(text));
|
|
205
|
+
if (clean.trim() === '' || /^\s*#/.test(clean)) continue;
|
|
206
|
+
const column = text.length - text.trimStart().length + 1;
|
|
207
|
+
if (/^\s*(?:帳號|密碼|使用者名稱|account|password|passwd|username|user|email|login)\s*[::]/i.test(clean)) {
|
|
208
|
+
out.push({ messageKey: 'account', line, column });
|
|
209
|
+
} else if (/^\s*https?:\/\/\S+\s*$/i.test(clean)) {
|
|
210
|
+
out.push({ messageKey: 'url', line, column });
|
|
211
|
+
} else if (CJK_LETTER.test(stripQuotedAndComment(clean))) {
|
|
212
|
+
out.push({ messageKey: 'text', line, column });
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return out;
|
|
217
|
+
},
|
|
218
|
+
|
|
219
|
+
CMD010(ctx) {
|
|
220
|
+
const out = [];
|
|
221
|
+
const FULL_WIDTH = /[\u3000\uFF01-\uFF5E\u201C\u201D\u2018\u2019\u300C\u300D\u300E\u300F\u2014\u2013\u2026\u3001\u3002]/;
|
|
222
|
+
for (const block of shellBlocks(ctx.md)) {
|
|
223
|
+
for (const { line, text } of block.lines) {
|
|
224
|
+
const withoutPlaceholders = stripPlaceholders(text);
|
|
225
|
+
if (/^\s*(?:\$\s+)?#/.test(withoutPlaceholders)) continue;
|
|
226
|
+
const scan = stripQuotedAndComment(withoutPlaceholders);
|
|
227
|
+
// 有中文字的行交給 CMD008(那一行本來就不是指令)
|
|
228
|
+
if (CJK_LETTER.test(scan)) continue;
|
|
229
|
+
const m = scan.match(FULL_WIDTH);
|
|
230
|
+
if (m) out.push({ messageKey: 'found', params: { char: m[0] === '\u3000' ? { 'zh-TW': '全形空白', en: 'full-width space' } : m[0] }, line, column: m.index + 1 });
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return out;
|
|
234
|
+
},
|
|
235
|
+
|
|
236
|
+
CMD012(ctx) {
|
|
237
|
+
const test = ctx.pkg?.scripts?.test;
|
|
238
|
+
if (typeof test !== 'string' || /no test specified/i.test(test)) return [];
|
|
239
|
+
for (const item of commandSegments(ctx.md)) {
|
|
240
|
+
const t = item.tokens;
|
|
241
|
+
if (MANAGERS.includes(t[0]) && t.slice(1).some((x) => /^(?:test|t|tst)(?::|$)/.test(x))) return [];
|
|
242
|
+
if (t.some((x) => ['vitest', 'jest', 'mocha', 'ava', 'tap', 'playwright', 'cypress'].includes(x))) return [];
|
|
243
|
+
if (t[0] === 'node' && t.includes('--test')) return [];
|
|
244
|
+
}
|
|
245
|
+
const anchor = findSection(ctx.sections, 'testing') ?? findSection(ctx.sections, 'getting-started');
|
|
246
|
+
return [{ messageKey: 'missing', params: { command: test }, line: anchor?.line ?? null, column: anchor ? 1 : null }];
|
|
247
|
+
},
|
|
248
|
+
};
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// 環境變數與安全類規則。
|
|
2
|
+
import { stripPlaceholders } from '../data.js';
|
|
3
|
+
import { findSection, sectionText } from '../sections.js';
|
|
4
|
+
import { escapeRegExp } from './util.js';
|
|
5
|
+
|
|
6
|
+
const ENV_EXAMPLE_FILES = ['.env.example', '.env.sample', '.env.template', '.env.dist', '.env.local.example'];
|
|
7
|
+
|
|
8
|
+
/** 專案裡的環境變數範例檔 */
|
|
9
|
+
export function envExampleFile(project) {
|
|
10
|
+
return ENV_EXAMPLE_FILES.find((f) => project.exists(f)) ?? null;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** 解析範例檔裡的變數名稱 */
|
|
14
|
+
export function parseEnvKeys(text) {
|
|
15
|
+
const keys = [];
|
|
16
|
+
for (const line of text.split(/\r?\n/)) {
|
|
17
|
+
const m = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_.]*)\s*=/);
|
|
18
|
+
if (m && !keys.includes(m[1])) keys.push(m[1]);
|
|
19
|
+
}
|
|
20
|
+
return keys;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// 常見服務的金鑰開頭(只列格式,不列服務名稱)
|
|
24
|
+
const KEY_PREFIXES = [
|
|
25
|
+
/\b(?:sk|rk)_live_[0-9A-Za-z]{16,}/,
|
|
26
|
+
/\bsk-[A-Za-z0-9_-]{32,}/,
|
|
27
|
+
/\bAKIA[0-9A-Z]{16}\b/,
|
|
28
|
+
/\bgh[pousr]_[A-Za-z0-9]{30,}\b/,
|
|
29
|
+
/\bgithub_pat_[A-Za-z0-9_]{30,}/,
|
|
30
|
+
/\bxox[abprs]-[A-Za-z0-9-]{10,}/,
|
|
31
|
+
/\bAIza[0-9A-Za-z_-]{35}\b/,
|
|
32
|
+
/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----/,
|
|
33
|
+
/\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/,
|
|
34
|
+
];
|
|
35
|
+
const SECRET_WORD = /secret|token|passw(?:or)?d|pwd|api[_-]?key|private[_-]?key|access[_-]?key|client[_-]?key|金鑰|密鑰|密碼|權杖/i;
|
|
36
|
+
const FAKE_HINT = /your|example|sample|dummy|fake|placeholder|changeme|change_me|xxx|test|demo|redacted|\*{3}|\.{3}|<|>|請填|範例|自己的/i;
|
|
37
|
+
|
|
38
|
+
/** 字串的混亂程度(越高越像亂數產生的金鑰) */
|
|
39
|
+
function entropy(text) {
|
|
40
|
+
const counts = new Map();
|
|
41
|
+
for (const c of text) counts.set(c, (counts.get(c) ?? 0) + 1);
|
|
42
|
+
let result = 0;
|
|
43
|
+
for (const n of counts.values()) {
|
|
44
|
+
const p = n / text.length;
|
|
45
|
+
result -= p * Math.log2(p);
|
|
46
|
+
}
|
|
47
|
+
return result;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 像不像真的金鑰值 */
|
|
51
|
+
function looksLikeSecretValue(value) {
|
|
52
|
+
if (value.length < 16 || FAKE_HINT.test(value)) return false;
|
|
53
|
+
// 網址、檔案路徑、檔名不算
|
|
54
|
+
if (/^https?:|:\/\/|^\.{0,2}\//.test(value) || /\.[A-Za-z]{1,5}$/.test(value) || value.split('/').length > 2) return false;
|
|
55
|
+
if (/^[A-Z][A-Z0-9_]*$/.test(value)) return false; // 變數名稱本身
|
|
56
|
+
// 亂數產生的金鑰幾乎都同時有英文字母和數字;只有字母的多半是程式裡的名稱
|
|
57
|
+
if ((value.match(/\d/g) ?? []).length < 2 || (value.match(/[A-Za-z]/g) ?? []).length < 2) return false;
|
|
58
|
+
return entropy(value) >= 3.5;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export const checks = {
|
|
62
|
+
ENV001(ctx) {
|
|
63
|
+
const file = envExampleFile(ctx.project);
|
|
64
|
+
if (!file || findSection(ctx.sections, 'env') || ctx.typeDef.required.includes('env')) return [];
|
|
65
|
+
return [{ messageKey: 'missing', params: { file }, line: null, column: null }];
|
|
66
|
+
},
|
|
67
|
+
|
|
68
|
+
ENV002(ctx) {
|
|
69
|
+
const file = envExampleFile(ctx.project);
|
|
70
|
+
const section = findSection(ctx.sections, 'env');
|
|
71
|
+
if (!file || !section) return [];
|
|
72
|
+
const keys = parseEnvKeys(ctx.project.readText(file) ?? '');
|
|
73
|
+
const text = sectionText(ctx.md, section);
|
|
74
|
+
const missing = keys.filter((k) => !new RegExp(`(^|[^A-Za-z0-9_])${escapeRegExp(k)}([^A-Za-z0-9_]|$)`).test(text));
|
|
75
|
+
if (!missing.length) return [];
|
|
76
|
+
return [{ messageKey: 'missing', params: { file, names: { 'zh-TW': missing.join('、'), en: missing.join(', ') } }, line: section.line, column: 1 }];
|
|
77
|
+
},
|
|
78
|
+
|
|
79
|
+
ENV008(ctx) {
|
|
80
|
+
const file = envExampleFile(ctx.project);
|
|
81
|
+
const section = findSection(ctx.sections, 'getting-started');
|
|
82
|
+
if (!file || !section) return [];
|
|
83
|
+
if (/\.env\b/.test(sectionText(ctx.md, section))) return [];
|
|
84
|
+
return [{ messageKey: 'missing', params: { file }, line: section.line, column: 1 }];
|
|
85
|
+
},
|
|
86
|
+
|
|
87
|
+
ENV004(ctx) {
|
|
88
|
+
const out = [];
|
|
89
|
+
for (const line of ctx.md.lines) {
|
|
90
|
+
if (line.kind === 'blank' || line.kind === 'fence') continue;
|
|
91
|
+
const text = stripPlaceholders(line.raw);
|
|
92
|
+
let found = null;
|
|
93
|
+
for (const pattern of KEY_PREFIXES) {
|
|
94
|
+
const m = text.match(pattern);
|
|
95
|
+
if (m && !/x{4,}|\*{4,}|\.{3}/i.test(m[0]) && !FAKE_HINT.test(m[0])) {
|
|
96
|
+
found = m;
|
|
97
|
+
break;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (!found && SECRET_WORD.test(text)) {
|
|
101
|
+
for (const m of text.matchAll(/[A-Za-z0-9+/=_\-.]{16,}/g)) {
|
|
102
|
+
if (looksLikeSecretValue(m[0])) {
|
|
103
|
+
found = m;
|
|
104
|
+
break;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (found) out.push({ messageKey: 'found', line: line.line, column: found.index + 1 });
|
|
109
|
+
}
|
|
110
|
+
return out;
|
|
111
|
+
},
|
|
112
|
+
};
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// 資料夾結構類規則:「資料夾結構」章節列出的最上層項目,在專案裡找不找得到。
|
|
2
|
+
// 只在看得懂寫法時才檢查;看不懂的區塊整段跳過,寧可漏抓也不要誤判。
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { findSection, sectionCodeBlocks } from '../sections.js';
|
|
5
|
+
|
|
6
|
+
// 樹狀圖的分支符號:├── └── 與常見的純文字寫法 |-- `-- +--
|
|
7
|
+
const TREE_LINE = /^([\s│┃|]*?)(├──|└──|├─|└─|┣━+|┗━+|\|--|\|──|`--|\+--)\s*(.*)$/;
|
|
8
|
+
const TREE_FILLER = /^[\s│┃|]*$/;
|
|
9
|
+
// 「路徑+說明」寫法只檢查純文字區塊
|
|
10
|
+
const PLAIN_LANGS = new Set(['', 'text', 'txt', 'plain', 'plaintext', 'tree', 'none']);
|
|
11
|
+
// 不會放進 repo、或是建置後才產生的資料夾與檔案
|
|
12
|
+
const IGNORED = new Set([
|
|
13
|
+
'node_modules', 'dist', 'build', 'out', '.output', '.nuxt', '.next', '.svelte-kit', '.vercel', '.netlify', '.turbo',
|
|
14
|
+
'.cache', 'coverage', '.nyc_output', 'tmp', 'temp', 'logs', 'vendor', 'target', '__pycache__', '.venv', 'venv', 'env',
|
|
15
|
+
'.env', '.env.local', '.DS_Store', '.git', '.idea', '.vscode',
|
|
16
|
+
]);
|
|
17
|
+
const WILDCARD = /[*?…<>{}[\]$~\\]|\.\.\./;
|
|
18
|
+
|
|
19
|
+
/** 一行裡的項目名稱:去掉註解與說明,只留第一個字詞 */
|
|
20
|
+
function entryName(text) {
|
|
21
|
+
const name = text.trim().split(/\s+/)[0] ?? '';
|
|
22
|
+
return name.replace(/^\.\//, '');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 名稱看得懂:結尾是 / 的資料夾,或有副檔名的檔案 */
|
|
26
|
+
function isCheckable(name) {
|
|
27
|
+
if (!name || WILDCARD.test(name) || name.startsWith('/') || name.startsWith('#')) return false;
|
|
28
|
+
if (!/^[\w.@+-][\w.@+/-]*$/.test(name)) return false;
|
|
29
|
+
return name.endsWith('/') || /\.[A-Za-z0-9]{1,10}$/.test(name);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 最上層的名稱(「src/components/」只看 src) */
|
|
33
|
+
function topSegment(name) {
|
|
34
|
+
const trimmed = name.replace(/\/+$/, '');
|
|
35
|
+
return trimmed.split('/')[0];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** .gitignore 裡簡單的名稱(沒有萬用字元的),列在結構裡但沒進 repo 是正常的 */
|
|
39
|
+
function gitignored(project, dir) {
|
|
40
|
+
const names = new Set();
|
|
41
|
+
for (const file of new Set([path.posix.join(dir, '.gitignore'), '.gitignore'])) {
|
|
42
|
+
for (const line of (project.readText(file) ?? '').split(/\r?\n/)) {
|
|
43
|
+
const entry = line.trim().replace(/^\//, '').replace(/\/$/, '');
|
|
44
|
+
if (entry && !entry.startsWith('#') && !entry.startsWith('!') && !/[*?[]/.test(entry)) names.add(entry);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return names;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 第一行如果是根目錄,判斷它對到哪個資料夾;對不到就傳回 null(整段跳過) */
|
|
51
|
+
function resolveRoot(name, ctx) {
|
|
52
|
+
const clean = name.replace(/^\.\//, '').replace(/\/+$/, '');
|
|
53
|
+
if (clean === '' || clean === '.') return ctx.readmeDir;
|
|
54
|
+
const known = [ctx.project.name, ctx.pkg?.name, ctx.pkg?.name?.split('/').pop()].filter(Boolean);
|
|
55
|
+
if (known.includes(clean)) return ctx.readmeDir;
|
|
56
|
+
const sub = path.posix.join(ctx.readmeDir, clean);
|
|
57
|
+
return ctx.project.isDir(sub) ? sub : null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 從一個程式碼區塊找出最上層的項目。
|
|
62
|
+
* @returns {{base:string, entries:Array<{name:string,line:number,column:number}>}|null}
|
|
63
|
+
*/
|
|
64
|
+
function parseBlock(block, ctx) {
|
|
65
|
+
const rows = block.lines.filter(({ text }) => text.trim() !== '');
|
|
66
|
+
if (!rows.length) return null;
|
|
67
|
+
|
|
68
|
+
// 樹狀圖
|
|
69
|
+
if (rows.some(({ text }) => TREE_LINE.test(text))) {
|
|
70
|
+
let base = ctx.readmeDir;
|
|
71
|
+
const tree = [];
|
|
72
|
+
for (const [i, row] of rows.entries()) {
|
|
73
|
+
const m = row.text.match(TREE_LINE);
|
|
74
|
+
if (m) {
|
|
75
|
+
tree.push({ depth: m[1].length, text: m[3], row });
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (TREE_FILLER.test(row.text)) continue;
|
|
79
|
+
// 只接受第一行是根目錄
|
|
80
|
+
if (i !== 0 || tree.length) return null;
|
|
81
|
+
base = resolveRoot(entryName(row.text), ctx);
|
|
82
|
+
if (base === null) return null;
|
|
83
|
+
}
|
|
84
|
+
const top = Math.min(...tree.map((t) => t.depth));
|
|
85
|
+
const entries = tree
|
|
86
|
+
.filter((t) => t.depth === top)
|
|
87
|
+
.map((t) => ({ name: entryName(t.text), line: t.row.line, column: t.row.text.indexOf(t.text) + 1 }));
|
|
88
|
+
return { base, entries };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// 「路徑+說明」:每一行都要是「名稱 說明」,否則看不懂、整段跳過
|
|
92
|
+
if (!PLAIN_LANGS.has(block.lang)) return null;
|
|
93
|
+
const items = [];
|
|
94
|
+
for (const row of rows) {
|
|
95
|
+
const trimmed = row.text.trim();
|
|
96
|
+
if (/^(?:#|\/\/)/.test(trimmed)) continue;
|
|
97
|
+
const name = entryName(trimmed);
|
|
98
|
+
if (!isCheckable(name)) return null;
|
|
99
|
+
items.push({ name, indent: row.text.length - row.text.trimStart().length, line: row.line, column: row.text.indexOf(name) + 1 });
|
|
100
|
+
}
|
|
101
|
+
if (!items.length) return null;
|
|
102
|
+
let top = Math.min(...items.map((x) => x.indent));
|
|
103
|
+
let base = ctx.readmeDir;
|
|
104
|
+
const firstLevel = items.filter((x) => x.indent === top);
|
|
105
|
+
// 只有第一行在最外層、其他都縮排在它底下:第一行是根目錄
|
|
106
|
+
if (firstLevel.length === 1 && items[0] === firstLevel[0] && items.length > 1) {
|
|
107
|
+
base = resolveRoot(items[0].name, ctx);
|
|
108
|
+
if (base === null) return null;
|
|
109
|
+
top = Math.min(...items.slice(1).map((x) => x.indent));
|
|
110
|
+
return { base, entries: items.slice(1).filter((x) => x.indent === top) };
|
|
111
|
+
}
|
|
112
|
+
return { base, entries: firstLevel };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export const checks = {
|
|
116
|
+
STR016(ctx) {
|
|
117
|
+
const section = findSection(ctx.sections, 'structure');
|
|
118
|
+
if (!section) return [];
|
|
119
|
+
const problems = [];
|
|
120
|
+
const seen = new Set();
|
|
121
|
+
for (const block of sectionCodeBlocks(ctx.md, section)) {
|
|
122
|
+
const parsed = parseBlock(block, ctx);
|
|
123
|
+
if (!parsed) continue;
|
|
124
|
+
const ignored = gitignored(ctx.project, parsed.base);
|
|
125
|
+
for (const entry of parsed.entries) {
|
|
126
|
+
if (!isCheckable(entry.name)) continue;
|
|
127
|
+
const top = topSegment(entry.name);
|
|
128
|
+
if (IGNORED.has(top) || ignored.has(top) || ignored.has(entry.name.replace(/\/+$/, ''))) continue;
|
|
129
|
+
const rel = path.posix.join(parsed.base, top);
|
|
130
|
+
if (seen.has(rel) || ctx.project.exists(rel)) continue;
|
|
131
|
+
seen.add(rel);
|
|
132
|
+
const shown = entry.name.includes('/') ? `${top}/` : top;
|
|
133
|
+
problems.push({ messageKey: 'missing', params: { name: shown }, line: entry.line, column: entry.column });
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return problems;
|
|
137
|
+
},
|
|
138
|
+
};
|