ShtukbaseStandard
包文件→ .shtukbase/packages/keer-style/checks/stylelib.ts

checks/stylelib.ts

131 行, 6.4 KB.

文件按包中的原样显示:代码及其注释不做翻译。

  1. // Shared scanner of the keer-style checks. The working directory is the project root.
  2. // It reads the style files of the project (CSS, HTML, TSX/JSX/TS/JS, Vue, Svelte) and gives each check the parts
  3. // where style values live: CSS declarations, <style> blocks and style="…" attributes in HTML, string literals in code.
  4. // Skipped: pages laid by other packages (they keep their own style), hidden folders (.git, .shtukbase …), node_modules and build folders, files marked `@tokens` in their
  5. // first lines (a file of values), paths from `ignore:` of /design/keer-style.md, and any line with `keer-style: allow`.
  6. import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
  7. import { extname, join } from 'node:path';
  8. import { readPage } from '../../collections/checks/lib/pages.ts';
  9. export type Kind = 'css' | 'html' | 'code';
  10. export type Part = { file: string; line: number; text: string };
  11. export type Finding = string;
  12. const EXT: Record<string, Kind> = {
  13. '.css': 'css', '.scss': 'css', '.less': 'css', '.pcss': 'css',
  14. '.html': 'html', '.htm': 'html', '.vue': 'html', '.svelte': 'html',
  15. '.tsx': 'code', '.jsx': 'code', '.ts': 'code', '.js': 'code', '.mjs': 'code',
  16. };
  17. const SKIP_DIRS = new Set(['node_modules', 'dist', 'build', 'out', 'coverage', 'vendor', 'target']);
  18. export const CONFIG = 'design/keer-style.md';
  19. export const ALLOW = 'keer-style: allow';
  20. /** Paths (or folder prefixes) from `ignore:` of the style page; `*` matches any run of characters. */
  21. function ignores(root: string): RegExp[] {
  22. const page = join(root, CONFIG);
  23. if (!existsSync(page)) return [];
  24. const raw = readPage(page).fm.ignore;
  25. const list = Array.isArray(raw) ? raw.map(String) : [];
  26. return list.map((g) => {
  27. const clean = g.replace(/^\/+/, '');
  28. const re = clean.split('*').map((s) => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*');
  29. return new RegExp(`^${re}${clean.endsWith('/') ? '' : '(/|$)'}`);
  30. });
  31. }
  32. /** Pages that other packages laid (from .shtukbase/packages.lock): they keep their own style and are not checked. */
  33. export function foreignPages(root: string, own = 'keer-style'): Set<string> {
  34. const lock = join(root, '.shtukbase', 'packages.lock');
  35. const out = new Set<string>();
  36. if (!existsSync(lock)) return out;
  37. let pkg = '';
  38. for (const line of readFileSync(lock, 'utf8').split('\n')) {
  39. const p = line.match(/^ ([\w.-]+):\s*$/);
  40. if (p) { pkg = p[1]; continue; }
  41. const page = line.match(/^ ("?)([^":]+)\1:\s*\{/);
  42. if (page && pkg !== own) out.add(page[2]);
  43. }
  44. return out;
  45. }
  46. /** Style files of the project, relative paths with forward slashes. */
  47. export function styleFiles(root = process.cwd()): { file: string; kind: Kind; text: string }[] {
  48. const skip = ignores(root);
  49. const foreign = foreignPages(root);
  50. const out: { file: string; kind: Kind; text: string }[] = [];
  51. const visit = (rel: string) => {
  52. for (const name of readdirSync(join(root, rel)).sort()) {
  53. const r = rel ? `${rel}/${name}` : name;
  54. const st = statSync(join(root, r));
  55. if (st.isDirectory()) {
  56. if (name.startsWith('.') || SKIP_DIRS.has(name)) continue;
  57. visit(r);
  58. continue;
  59. }
  60. const kind = EXT[extname(name).toLowerCase()];
  61. if (!kind || name.endsWith('.d.ts') || foreign.has(r) || skip.some((re) => re.test(r))) continue;
  62. const text = readFileSync(join(root, r), 'utf8');
  63. if (text.slice(0, 600).includes('@tokens')) continue;
  64. out.push({ file: r, kind, text });
  65. }
  66. };
  67. visit('');
  68. return out;
  69. }
  70. /** Keeps only the characters of the given ranges; the rest becomes spaces, newlines stay (line numbers hold). */
  71. function keep(text: string, ranges: [number, number][]): string {
  72. const chars = text.split('').map((c) => (c === '\n' ? '\n' : ' '));
  73. for (const [a, b] of ranges) {
  74. for (let i = a; i < b; i++) chars[i] = text[i];
  75. if (b < chars.length && chars[b] !== '\n') chars[b] = ';'; // the closing quote ends any declaration
  76. }
  77. return chars.join('');
  78. }
  79. function stripCssComments(text: string): string {
  80. return text.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' '));
  81. }
  82. /** The text of a file reduced to where style values are written. */
  83. export function styleText(kind: Kind, text: string): string {
  84. if (kind === 'css') return stripCssComments(text);
  85. if (kind === 'html') {
  86. const ranges: [number, number][] = [];
  87. for (const m of text.matchAll(/<style[^>]*>([\s\S]*?)<\/style>/gi)) ranges.push([m.index! + m[0].indexOf(m[1]), m.index! + m[0].indexOf(m[1]) + m[1].length]);
  88. for (const m of text.matchAll(/\b(?:style|class|className)\s*=\s*(["'])([\s\S]*?)\1/g)) ranges.push([m.index! + m[0].length - 1 - m[2].length, m.index! + m[0].length - 1]);
  89. return stripCssComments(keep(text, ranges));
  90. }
  91. // code: string literals only (Tailwind classes, inline styles); comments are dropped first
  92. const noComments = text.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/(^|[^:"'`\\])\/\/[^\n]*/g, (m, p) => p + ' '.repeat(m.length - p.length));
  93. const ranges: [number, number][] = [];
  94. for (const m of noComments.matchAll(/(["'`])((?:\\.|(?!\1)[^\\\n])*)\1/g)) ranges.push([m.index! + 1, m.index! + 1 + m[2].length]);
  95. return keep(noComments, ranges);
  96. }
  97. /** CSS declarations `prop: value` in a reduced text: property, value, line of the property. */
  98. export function* declarations(text: string): Generator<{ prop: string; value: string; line: number }> {
  99. for (const m of text.matchAll(/(?<![\w-])(-{0,2}[a-zA-Z][\w-]*)\s*:\s*([^;{}"']+?)\s*(?=[;}"']|$)/gm)) {
  100. const line = text.slice(0, m.index!).split('\n').length;
  101. yield { prop: m[1].toLowerCase(), value: m[2], line };
  102. }
  103. }
  104. /** Class-like tokens (Tailwind) in a reduced text, with their line. */
  105. export function* classTokens(text: string): Generator<{ token: string; line: number }> {
  106. const lines = text.split('\n');
  107. for (let i = 0; i < lines.length; i++)
  108. for (const m of lines[i].matchAll(/[^\s"'`;]+/g)) yield { token: m[0], line: i + 1 };
  109. }
  110. export function allowed(source: string, line: number): boolean {
  111. return (source.split('\n')[line - 1] ?? '').includes(ALLOW);
  112. }
  113. /** Runs a check over the style files: prints findings, exit 1 when any. */
  114. export function run(check: (f: { file: string; kind: Kind; text: string; reduced: string }) => Finding[]): void {
  115. const out: Finding[] = [];
  116. for (const f of styleFiles()) out.push(...check({ ...f, reduced: styleText(f.kind, f.text) }));
  117. if (out.length) console.log(out.join('\n'));
  118. process.exitCode = out.length ? 1 : 0;
  119. }