Repository navigation
Expand file tree
/
Copy pathcheck-module.mjs
More file actions
182 lines (157 loc) · 6.65 KB
/
Copy pathcheck-module.mjs
File metadata and controls
182 lines (157 loc) · 6.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
/* Static checks that run without a browser.
*
* 1. Syntax — node --check on each module.
* 2. Bindings — $-prefixed handles that are used but never declared.
* 3. Elements — getElementById lookups with no matching id in the HTML.
*
* (2) and (3) exist because both are ReferenceErrors or null derefs that only
* surface when the page runs, and a module-level one takes the whole simulator
* down with "failed to start". Deleting a screen is exactly when they happen.
*/
import { access, readFile, writeFile } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import { spawn } from 'node:child_process';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
const mainModule = new URL('./src/main.js', import.meta.url);
const homeModule = new URL('./src/home.js', import.meta.url);
const legacyHtml = new URL('./index.html', import.meta.url);
const checkFiles = [];
try {
await access(mainModule);
checkFiles.push(fileURLToPath(mainModule));
} catch {
const html = await readFile(legacyHtml, 'utf8');
const match = html.match(/<script type="module">([\s\S]*?)<\/script>/);
if (!match) {
throw new Error('Could not find src/main.js or inline <script type="module"> block');
}
const outFile = join(tmpdir(), 'drone-simulator-inline-module.mjs');
await writeFile(outFile, match[1], 'utf8');
checkFiles.push(outFile);
}
try {
await access(homeModule);
checkFiles.push(fileURLToPath(homeModule));
} catch {}
/* ---- 1. syntax ---- */
for (const checkFile of checkFiles) {
const child = spawn(process.execPath, ['--check', checkFile], { stdio: 'inherit' });
const code = await new Promise((resolve) => child.on('close', resolve));
if (code !== 0) {
process.exit(code ?? 1);
}
}
const PAGES_TO_STAMP = ['./index.html', './game.html'];
const problems = [];
/* ---- 2. undeclared $handles ----
* Deliberately scanned raw. Trying to strip comments and literals first is what
* you reach for, but a template literal holding `${a ? {x:1} : 2}` defeats any
* regex-level stripper and silently eats half the file, which turns this check
* into one that always passes. Raw text can only produce a false *declaration*
* (harmless) or flag a name that appears solely in prose (worth knowing). */
for (const file of checkFiles) {
const code = await readFile(file, 'utf8');
const declared = new Set();
for (const m of code.matchAll(/(?:const|let|var|function)\s+(\$[\w$]+)/g)) declared.add(m[1]);
/* Multi-declarator lines and destructuring: const $a = …, $b = … */
for (const m of code.matchAll(/[,{([]\s*(\$[\w$]+)\s*[=,;){\]]/g)) declared.add(m[1]);
const used = new Map();
for (const m of code.matchAll(/(?<![\w$.'"`])(\$[\w$]+)/g)) {
if (!used.has(m[1])) used.set(m[1], code.slice(0, m.index).split('\n').length);
}
for (const [name, line] of used) {
if (!declared.has(name)) problems.push(`${file}:${line} ${name} is used but never declared`);
}
}
/* ---- 3. top-level use before declaration ----
* Top-level statements run in order, so a const declared further down the file
* is in its temporal dead zone and throws at module scope — which takes the
* whole simulator down with "failed to start". Functions are hoisted, so the
* risk is only for unindented statements; this keys off column 0 rather than
* trying to parse scopes.
*
* Comments and quoted strings are removed line by line first. Without that,
* `getElementById('cmp-objectives')` reads as a use of `objectives`, and
* `{ rings: 0 }` as a use of `rings` — the object-key guard covers the latter. */
for (const file of checkFiles) {
const code = await readFile(file, 'utf8');
const raw = code.split('\n');
let inBlock = false;
const lines = raw.map((line) => {
let out = line;
if (inBlock) {
const close = out.indexOf('*/');
if (close === -1) return '';
out = out.slice(close + 2);
inBlock = false;
}
out = out.replace(/\/\*[\s\S]*?\*\//g, ' ');
const open = out.indexOf('/*');
if (open !== -1) { inBlock = true; out = out.slice(0, open); }
return out
.replace(/\/\/.*$/, '')
.replace(/'(?:\\.|[^'\\])*'/g, "''")
.replace(/"(?:\\.|[^"\\])*"/g, '""');
});
const declLine = new Map();
lines.forEach((line, i) => {
const m = /^(?:const|let)\s+([A-Za-z_$][\w$]*)/.exec(line);
if (m && !declLine.has(m[1])) declLine.set(m[1], i);
});
lines.forEach((line, i) => {
if (/^\s/.test(line) || !line.trim()) return; // indented => inside a body
if (/^(?:function|class|import|export)\b/.test(line)) return;
for (const [name, at] of declLine) {
if (at <= i) continue;
const esc = name.replace(/\$/g, '\\$');
/* Not after a dot/word, and not an object key (`name:`). */
const used = new RegExp(`(?<![\\w$.])${esc}(?![\\w$])(?!\\s*:)`).test(line);
if (used) problems.push(`${file}:${i + 1} ${name} is used before its declaration on line ${at + 1}`);
}
});
}
/* ---- 3. getElementById targets ---- */
const pages = [
['./game.html', './src/main.js'],
['./index.html', './src/home.js'],
];
for (const [pagePath, scriptPath] of pages) {
let page, script;
try {
page = await readFile(new URL(pagePath, import.meta.url), 'utf8');
script = await readFile(new URL(scriptPath, import.meta.url), 'utf8');
} catch {
continue;
}
const ids = new Set([...page.matchAll(/id="([^"]+)"/g)].map((m) => m[1]));
for (const m of script.matchAll(/getElementById\(['"]([^'"$]+)['"]\)/g)) {
if (!ids.has(m[1])) {
const line = script.slice(0, m.index).split('\n').length;
problems.push(`${scriptPath}:${line} #${m[1]} not found in ${pagePath}`);
}
}
}
/* ---- 4. asset cache-busters match file contents ----
* A ?v= token that does not track the file is worse than none: the browser
* keeps serving the previous version and the fix looks like it never shipped. */
for (const page of PAGES_TO_STAMP) {
let html;
try { html = await readFile(new URL(page, import.meta.url), 'utf8'); }
catch { continue; }
for (const m of html.matchAll(/(?:src|href)="(\.\/[^"?]+\.(?:js|css))\?v=([^"]*)"/g)) {
let contents;
try { contents = await readFile(new URL(m[1], import.meta.url)); }
catch { continue; }
const want = createHash('sha256').update(contents).digest('hex').slice(0, 8);
if (m[2] !== want) {
problems.push(`${page} ${m[1]}?v=${m[2]} is stale (expected ${want}) — run: npm run stamp`);
}
}
}
if (problems.length) {
console.error(`\n${problems.length} problem(s):\n` + problems.map((p) => ` ${p}`).join('\n'));
process.exit(1);
}
console.log(`checked ${checkFiles.length} modules — syntax, $bindings, element ids all clean`);