@wave-rf/cloudflare-md-router 0.2.1 → 0.4.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/README.md +78 -1
- package/bin/cli.mjs +34 -0
- package/bin/dev.mjs +575 -0
- package/bin/lib.mjs +682 -0
- package/package.json +15 -5
- package/src/bots.ts +1 -1
- package/src/index.ts +2 -0
- package/src/worker.ts +134 -41
package/bin/lib.mjs
ADDED
|
@@ -0,0 +1,682 @@
|
|
|
1
|
+
/* Pure helpers for `cloudflare-md-router dev` (see bin/dev.mjs). Node built-ins only, plain JS so
|
|
2
|
+
* the CLI runs under any Node >=20 without a build step. Nothing here is imported by the Worker
|
|
3
|
+
* (`src/` never references `bin/`), so none of it can reach a Worker bundle. */
|
|
4
|
+
|
|
5
|
+
import { execFileSync } from "node:child_process";
|
|
6
|
+
import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
7
|
+
import { createRequire } from "node:module";
|
|
8
|
+
import { createServer } from "node:net";
|
|
9
|
+
import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
|
|
10
|
+
|
|
11
|
+
export const DEFAULT_PORT = 4321;
|
|
12
|
+
export const MAX_PORT = 65535;
|
|
13
|
+
export const PORT_TRIES = 20;
|
|
14
|
+
export const DEFAULT_OUT_DIR = "dist";
|
|
15
|
+
export const DEFAULT_OUT_DIR_FLAG = "--outDir";
|
|
16
|
+
export const DEFAULT_WATCH = ["src", "public"];
|
|
17
|
+
/** Root-level build inputs watched by default (exact names; `*` allowed only as a suffix). */
|
|
18
|
+
export const DEFAULT_ROOT_TRIGGERS = [
|
|
19
|
+
"astro.config.*",
|
|
20
|
+
"vite.config.*",
|
|
21
|
+
"tsconfig.json",
|
|
22
|
+
"package.json",
|
|
23
|
+
".env*",
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
/* ---------------------------------------------------------------- JSONC */
|
|
27
|
+
|
|
28
|
+
/** Strip `//` and block comments and trailing commas from JSONC, leaving string contents alone. */
|
|
29
|
+
export function stripJsonc(text) {
|
|
30
|
+
let out = "";
|
|
31
|
+
let i = 0;
|
|
32
|
+
const n = text.length;
|
|
33
|
+
while (i < n) {
|
|
34
|
+
const c = text[i];
|
|
35
|
+
const next = text[i + 1];
|
|
36
|
+
if (c === '"') {
|
|
37
|
+
let j = i + 1;
|
|
38
|
+
while (j < n && text[j] !== '"') j += text[j] === "\\" ? 2 : 1;
|
|
39
|
+
out += text.slice(i, j + 1);
|
|
40
|
+
i = j + 1;
|
|
41
|
+
} else if (c === "/" && next === "/") {
|
|
42
|
+
while (i < n && text[i] !== "\n") i++;
|
|
43
|
+
} else if (c === "/" && next === "*") {
|
|
44
|
+
const end = text.indexOf("*/", i + 2);
|
|
45
|
+
i = end === -1 ? n : end + 2;
|
|
46
|
+
} else {
|
|
47
|
+
out += c;
|
|
48
|
+
i++;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
// Trailing commas: a comma followed (after whitespace) by } or ], outside strings.
|
|
52
|
+
let res = "";
|
|
53
|
+
for (let k = 0; k < out.length; k++) {
|
|
54
|
+
const c = out[k];
|
|
55
|
+
if (c === '"') {
|
|
56
|
+
let j = k + 1;
|
|
57
|
+
while (j < out.length && out[j] !== '"') j += out[j] === "\\" ? 2 : 1;
|
|
58
|
+
res += out.slice(k, j + 1);
|
|
59
|
+
k = j;
|
|
60
|
+
} else if (c === ",") {
|
|
61
|
+
let j = k + 1;
|
|
62
|
+
while (j < out.length && /\s/.test(out[j])) j++;
|
|
63
|
+
if (out[j] !== "}" && out[j] !== "]") res += c;
|
|
64
|
+
} else {
|
|
65
|
+
res += c;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return res;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function parseJsonc(text) {
|
|
72
|
+
return JSON.parse(stripJsonc(text.replace(/^/, "")));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Quote one shell word (POSIX single quotes; left bare when plainly safe, or on Windows). */
|
|
76
|
+
export function shellQuote(word) {
|
|
77
|
+
if (/^[\w@%+=:,./-]+$/.test(word) || process.platform === "win32") return word;
|
|
78
|
+
return `'${word.replace(/'/g, "'\\''")}'`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/* ----------------------------------------------------------------- TOML */
|
|
82
|
+
|
|
83
|
+
/** Pull `assets.directory` and `main` out of a wrangler.toml — only the top-level (non-env) ones.
|
|
84
|
+
* Deliberately not a TOML parser: it understands `[assets]` tables and `assets = { … }` inline. */
|
|
85
|
+
export function parseWranglerToml(text) {
|
|
86
|
+
const result = {};
|
|
87
|
+
let table = "";
|
|
88
|
+
const str = String.raw`(?:"((?:[^"\\]|\\.)*)"|'([^']*)')`;
|
|
89
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
90
|
+
const line = raw.replace(/^\s+/, "");
|
|
91
|
+
const header = line.match(/^\[\s*([^\]]+?)\s*\]\s*(?:#.*)?$/);
|
|
92
|
+
if (header && !line.startsWith("[[")) {
|
|
93
|
+
table = header[1];
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (line.startsWith("[[")) {
|
|
97
|
+
table = "[[array]]";
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (table === "") {
|
|
101
|
+
const main = line.match(new RegExp(`^main\\s*=\\s*${str}`));
|
|
102
|
+
if (main) result.main = main[1] ?? main[2];
|
|
103
|
+
const inline = line.match(new RegExp(`^assets\\s*=\\s*\\{[^}]*?\\bdirectory\\s*=\\s*${str}`));
|
|
104
|
+
if (inline) result.assetsDirectory = inline[1] ?? inline[2];
|
|
105
|
+
} else if (table === "assets") {
|
|
106
|
+
const dir = line.match(new RegExp(`^directory\\s*=\\s*${str}`));
|
|
107
|
+
if (dir) result.assetsDirectory = dir[1] ?? dir[2];
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Find and read the wrangler config. Returns `{ file, assetsDirectory, main }` (each may be undefined). */
|
|
114
|
+
export function readWranglerConfig(root, explicit) {
|
|
115
|
+
if (explicit && !existsSync(resolve(root, explicit))) {
|
|
116
|
+
throw new Error(`config file ${resolve(root, explicit)} not found`);
|
|
117
|
+
}
|
|
118
|
+
const candidates = explicit
|
|
119
|
+
? [resolve(root, explicit)]
|
|
120
|
+
: ["wrangler.jsonc", "wrangler.json", "wrangler.toml"].map((f) => join(root, f));
|
|
121
|
+
const file = candidates.find((f) => existsSync(f));
|
|
122
|
+
if (!file) return { file: undefined };
|
|
123
|
+
const text = readFileSync(file, "utf8");
|
|
124
|
+
if (file.endsWith(".toml")) return { file, ...parseWranglerToml(text) };
|
|
125
|
+
let json;
|
|
126
|
+
try {
|
|
127
|
+
json = parseJsonc(text);
|
|
128
|
+
} catch (err) {
|
|
129
|
+
throw new Error(`could not parse ${file}: ${err.message}`);
|
|
130
|
+
}
|
|
131
|
+
const assets = json.assets;
|
|
132
|
+
return {
|
|
133
|
+
file,
|
|
134
|
+
main: typeof json.main === "string" ? json.main : undefined,
|
|
135
|
+
assetsDirectory: assets && typeof assets.directory === "string" ? assets.directory : undefined,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/* ------------------------------------------------------ package manager */
|
|
140
|
+
|
|
141
|
+
const LOCKFILES = [
|
|
142
|
+
["pnpm-lock.yaml", "pnpm"],
|
|
143
|
+
["yarn.lock", "yarn"],
|
|
144
|
+
["bun.lock", "bun"],
|
|
145
|
+
["bun.lockb", "bun"],
|
|
146
|
+
["package-lock.json", "npm"],
|
|
147
|
+
["npm-shrinkwrap.json", "npm"],
|
|
148
|
+
];
|
|
149
|
+
|
|
150
|
+
/** Lockfile → package manager, walking up from `root` (monorepo sites keep the lockfile at the
|
|
151
|
+
* workspace root). Falls back to package.json `packageManager`, then npm. */
|
|
152
|
+
export function detectPackageManager(root) {
|
|
153
|
+
let dir = resolve(root);
|
|
154
|
+
for (;;) {
|
|
155
|
+
for (const [file, pm] of LOCKFILES) if (existsSync(join(dir, file))) return pm;
|
|
156
|
+
const parent = dirname(dir);
|
|
157
|
+
if (parent === dir) break;
|
|
158
|
+
dir = parent;
|
|
159
|
+
}
|
|
160
|
+
try {
|
|
161
|
+
const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
|
162
|
+
const m = /^(pnpm|yarn|npm|bun)@/.exec(pkg.packageManager ?? "");
|
|
163
|
+
if (m) return m[1];
|
|
164
|
+
} catch {}
|
|
165
|
+
return "npm";
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** `[command, args]` that runs a package.json script. Extra args are forwarded to the script. */
|
|
169
|
+
export function runScriptCommand(pm, script, extra = []) {
|
|
170
|
+
if (pm === "npm") return ["npm", ["run", script, ...(extra.length ? ["--", ...extra] : [])]];
|
|
171
|
+
return [pm, ["run", script, ...extra]];
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** `[command, args]` that runs a locally-installed binary and NEVER downloads it. */
|
|
175
|
+
export function execLocalCommand(pm, bin, args = []) {
|
|
176
|
+
switch (pm) {
|
|
177
|
+
case "pnpm":
|
|
178
|
+
return ["pnpm", ["exec", bin, ...args]];
|
|
179
|
+
case "yarn":
|
|
180
|
+
return ["yarn", [bin, ...args]]; // yarn classic and berry both run local bins
|
|
181
|
+
case "bun":
|
|
182
|
+
return ["bun", ["x", "--no-install", bin, ...args]];
|
|
183
|
+
default:
|
|
184
|
+
return ["npm", ["exec", "--no", "--", bin, ...args]];
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** The JS entry of the site's locally-installed wrangler (its package.json `bin.wrangler`), or
|
|
189
|
+
* null if it can't be resolved — not installed, or a Yarn PnP install. Resolution only looks at
|
|
190
|
+
* what is on disk, so this never downloads anything. Running this file with `process.execPath`
|
|
191
|
+
* puts no package manager or shell between us and wrangler, so our signals reach it. */
|
|
192
|
+
export function resolveWranglerBin(root) {
|
|
193
|
+
const req = createRequire(join(root, "package.json"));
|
|
194
|
+
let pkgFile;
|
|
195
|
+
try {
|
|
196
|
+
pkgFile = req.resolve("wrangler/package.json");
|
|
197
|
+
} catch {
|
|
198
|
+
// A package whose `exports` hides package.json still has one on disk: look in the same dirs.
|
|
199
|
+
pkgFile = (req.resolve.paths("wrangler") ?? [])
|
|
200
|
+
.map((dir) => join(dir, "wrangler", "package.json"))
|
|
201
|
+
.find((f) => existsSync(f));
|
|
202
|
+
}
|
|
203
|
+
if (!pkgFile) return null;
|
|
204
|
+
let pkg;
|
|
205
|
+
try {
|
|
206
|
+
pkg = JSON.parse(readFileSync(pkgFile, "utf8"));
|
|
207
|
+
} catch {
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
const rel = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.wrangler;
|
|
211
|
+
if (typeof rel !== "string") return null;
|
|
212
|
+
const file = resolve(dirname(pkgFile), rel);
|
|
213
|
+
return existsSync(file) ? file : null;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/* ------------------------------------------------------------- processes */
|
|
217
|
+
|
|
218
|
+
/** `[pid, ppid]` for every process we can see: /proc on Linux (always there, even in slim
|
|
219
|
+
* containers without `ps`), `ps` elsewhere on POSIX. Empty on Windows or on any failure. */
|
|
220
|
+
export function processTable() {
|
|
221
|
+
try {
|
|
222
|
+
if (process.platform === "linux") {
|
|
223
|
+
const rows = [];
|
|
224
|
+
for (const name of readdirSync("/proc")) {
|
|
225
|
+
if (!/^\d+$/.test(name)) continue;
|
|
226
|
+
try {
|
|
227
|
+
const stat = readFileSync(`/proc/${name}/stat`, "utf8");
|
|
228
|
+
// Fields after the `(comm)`, which may itself contain spaces and parens: state ppid …
|
|
229
|
+
const ppid = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
|
|
230
|
+
rows.push([Number(name), ppid]);
|
|
231
|
+
} catch {} // exited while we were reading
|
|
232
|
+
}
|
|
233
|
+
return rows;
|
|
234
|
+
}
|
|
235
|
+
if (process.platform === "win32") return [];
|
|
236
|
+
const out = execFileSync("ps", ["-A", "-o", "pid=", "-o", "ppid="], {
|
|
237
|
+
encoding: "utf8",
|
|
238
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
239
|
+
});
|
|
240
|
+
return out
|
|
241
|
+
.split("\n")
|
|
242
|
+
.map((line) => line.trim().split(/\s+/).map(Number))
|
|
243
|
+
.filter((r) => r.length === 2 && r.every(Number.isInteger));
|
|
244
|
+
} catch {
|
|
245
|
+
return [];
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Every descendant of `pid` in a `[pid, ppid]` table (children first, then theirs). */
|
|
250
|
+
export function descendantsOf(table, pid) {
|
|
251
|
+
const found = [];
|
|
252
|
+
const queue = [pid];
|
|
253
|
+
while (queue.length > 0) {
|
|
254
|
+
const parent = queue.shift();
|
|
255
|
+
for (const [p, pp] of table) {
|
|
256
|
+
if (pp === parent && p !== pid && !found.includes(p)) {
|
|
257
|
+
found.push(p);
|
|
258
|
+
queue.push(p);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
return found;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Is `pid` (or, negative, process group `-pid`) still around? EPERM means it exists. */
|
|
266
|
+
export function isAlive(pid) {
|
|
267
|
+
try {
|
|
268
|
+
process.kill(pid, 0);
|
|
269
|
+
return true;
|
|
270
|
+
} catch (err) {
|
|
271
|
+
return err.code === "EPERM";
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/* ----------------------------------------------------------------- port */
|
|
276
|
+
|
|
277
|
+
/** A real TCP port, or null. "" / "0" / non-numeric / out of range are all rejected, because they
|
|
278
|
+
* would otherwise bind an ephemeral port or throw from inside the probe. */
|
|
279
|
+
export function parsePort(raw) {
|
|
280
|
+
if (raw === undefined || raw === "") return DEFAULT_PORT;
|
|
281
|
+
const port = Number(raw);
|
|
282
|
+
if (!Number.isInteger(port) || port < 1 || port > MAX_PORT) return null;
|
|
283
|
+
return port;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export const lastPortFor = (start, tries) => Math.min(start + tries - 1, MAX_PORT);
|
|
287
|
+
|
|
288
|
+
/** Bind errors that mean "this host has no usable IPv6", not "the port is taken". */
|
|
289
|
+
const IPV6_UNAVAILABLE = new Set(["EADDRNOTAVAIL", "EAFNOSUPPORT", "EPROTONOSUPPORT"]);
|
|
290
|
+
|
|
291
|
+
export function portFree(port, host) {
|
|
292
|
+
return new Promise((done) => {
|
|
293
|
+
const probe = createServer();
|
|
294
|
+
probe.once("error", (err) => done(host === "::1" && IPV6_UNAVAILABLE.has(err.code)));
|
|
295
|
+
probe.listen({ port, host, exclusive: true }, () => probe.close(() => done(true)));
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** First port in `[start, start+tries)` free on BOTH IPv4 and IPv6 loopback (wrangler binds both,
|
|
300
|
+
* and a squatter such as an `astro dev` elsewhere often holds only `::1`). */
|
|
301
|
+
export async function findFreePort(start, tries = PORT_TRIES, isFree = portFree) {
|
|
302
|
+
for (let port = start, last = lastPortFor(start, tries); port <= last; port++) {
|
|
303
|
+
if ((await isFree(port, "127.0.0.1")) && (await isFree(port, "::1"))) return port;
|
|
304
|
+
}
|
|
305
|
+
return null;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/* -------------------------------------------------------- output guard */
|
|
309
|
+
|
|
310
|
+
/** The filesystem calls the guard makes, injectable so a test can model a filesystem this machine
|
|
311
|
+
* doesn't have (a case-insensitive mount on Linux, where `realpath` keeps the caller's case). */
|
|
312
|
+
export const REAL_FS = {
|
|
313
|
+
stat: (p) => statSync(p, { bigint: true }), // bigint: a 64-bit inode survives exactly
|
|
314
|
+
realpath: (p) => realpathSync.native(p),
|
|
315
|
+
readdir: (p) => readdirSync(p),
|
|
316
|
+
exists: (p) => existsSync(p),
|
|
317
|
+
tracked: (root, dir) => gitTrackedFiles(root, dir),
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
/** The path as the filesystem spells it: symlinks resolved, then each existing segment matched
|
|
321
|
+
* against its parent's listing, so `SRC` becomes `src` on a case-insensitive volume even where
|
|
322
|
+
* `realpath` keeps the input's case (Linux on a macOS bind mount, WSL `/mnt/c`, ext4 casefold). A
|
|
323
|
+
* path that doesn't exist yet is canonicalised through its nearest existing ancestor. */
|
|
324
|
+
export function canonicalPath(p, fsx = REAL_FS) {
|
|
325
|
+
const abs = resolve(p);
|
|
326
|
+
const rest = [];
|
|
327
|
+
let real;
|
|
328
|
+
for (let dir = abs; ; dir = dirname(dir)) {
|
|
329
|
+
try {
|
|
330
|
+
real = fsx.realpath(dir);
|
|
331
|
+
break;
|
|
332
|
+
} catch {}
|
|
333
|
+
if (dirname(dir) === dir) return abs;
|
|
334
|
+
rest.unshift(basename(dir));
|
|
335
|
+
}
|
|
336
|
+
const top = parse(real).root;
|
|
337
|
+
let fixed = top;
|
|
338
|
+
for (const seg of real.slice(top.length).split(sep).filter(Boolean)) {
|
|
339
|
+
let name = seg;
|
|
340
|
+
try {
|
|
341
|
+
const entries = fsx.readdir(fixed);
|
|
342
|
+
if (!entries.includes(seg)) {
|
|
343
|
+
const lower = seg.toLowerCase();
|
|
344
|
+
const hits = entries.filter((e) => e.toLowerCase() === lower);
|
|
345
|
+
if (hits.length === 1) name = hits[0];
|
|
346
|
+
}
|
|
347
|
+
} catch {}
|
|
348
|
+
fixed = join(fixed, name);
|
|
349
|
+
}
|
|
350
|
+
return join(fixed, ...rest);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** Is `child` the same path as `parent`, or inside it? Both must already be canonical. */
|
|
354
|
+
export function isWithin(child, parent) {
|
|
355
|
+
const rel = relative(parent, child);
|
|
356
|
+
return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** `dev:ino` of a directory, or null if it doesn't exist or has no usable identity (an inode of 0,
|
|
360
|
+
* as some network, virtual and Windows volumes report) — callers then compare canonical paths. */
|
|
361
|
+
function dirId(p, fsx) {
|
|
362
|
+
try {
|
|
363
|
+
const st = fsx.stat(p);
|
|
364
|
+
if (st.ino === 0n || st.ino === 0) return null;
|
|
365
|
+
return `${st.dev}:${st.ino}`;
|
|
366
|
+
} catch {
|
|
367
|
+
return null;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** Directory identity, not spelling: is `child` the same directory as `parent`, or inside it? The
|
|
372
|
+
* child's existing ancestors (itself included) are compared to the parent by (dev, ino), so two
|
|
373
|
+
* spellings of one directory — case variants, bind aliases — can't slip past. Where the parent
|
|
374
|
+
* doesn't exist yet there is nothing to identify, so canonical paths are compared instead. */
|
|
375
|
+
export function dirWithin(child, parent, fsx = REAL_FS) {
|
|
376
|
+
const c = canonicalPath(child, fsx);
|
|
377
|
+
const p = canonicalPath(parent, fsx);
|
|
378
|
+
const pid = dirId(p, fsx);
|
|
379
|
+
if (pid === null) return isWithin(c, p);
|
|
380
|
+
for (let d = c; ; d = dirname(d)) {
|
|
381
|
+
if (dirId(d, fsx) === pid) return true;
|
|
382
|
+
if (dirname(d) === d) return false;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** Same directory, by identity when both exist. */
|
|
387
|
+
export function sameDir(a, b, fsx = REAL_FS) {
|
|
388
|
+
const ia = dirId(a, fsx);
|
|
389
|
+
const ib = dirId(b, fsx);
|
|
390
|
+
if (ia !== null && ib !== null) return ia === ib;
|
|
391
|
+
return canonicalPath(a, fsx) === canonicalPath(b, fsx);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** Git-tracked files under `dir`, relative to `root` (empty if not in a git work tree or no git).
|
|
395
|
+
* The pathspec is case-insensitive: git's own matching is case-sensitive even with
|
|
396
|
+
* core.ignorecase, and over-matching only makes the guard stricter. */
|
|
397
|
+
export function gitTrackedFiles(root, dir) {
|
|
398
|
+
if (!existsSync(dir)) return [];
|
|
399
|
+
try {
|
|
400
|
+
const spec = `:(icase,literal)${relative(root, dir)}`;
|
|
401
|
+
const out = execFileSync("git", ["-C", root, "ls-files", "-z", "--", spec], {
|
|
402
|
+
encoding: "utf8",
|
|
403
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
404
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
405
|
+
});
|
|
406
|
+
return out.split("\0").filter(Boolean);
|
|
407
|
+
} catch {
|
|
408
|
+
return [];
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** Refuse an output directory whose pruning would delete something that isn't build output. The
|
|
413
|
+
* loop makes `outDir` match each build exactly (and empties `staging` before each), so anything
|
|
414
|
+
* else in them is deleted. Throws a user-facing Error that says why and what to pass instead.
|
|
415
|
+
*
|
|
416
|
+
* Directories are compared by identity (see `dirWithin`), so `SRC`, a symlink or a bind alias
|
|
417
|
+
* can't slip past. The rules:
|
|
418
|
+
* - outDir must be strictly inside the site root (not the root, nor anywhere outside it);
|
|
419
|
+
* - it must not be, be inside, or enclose src/, public/, node_modules/ or .git/;
|
|
420
|
+
* - it must not be, or enclose, the wrangler config's directory;
|
|
421
|
+
* - the wrangler `main`'s directory (`workerDir`): if it is the root or config dir or above them,
|
|
422
|
+
* outDir must not be it or enclose it (already implied by the two rules above); if it lies inside
|
|
423
|
+
* the wrangler-configured assets directory, the config itself declares the Worker to be build
|
|
424
|
+
* output (Astro's adapter writes `dist/_worker.js`), so only an outDir equal to it or inside it is
|
|
425
|
+
* refused; anywhere else it is source, like src/;
|
|
426
|
+
* - outDir and staging must not hold a package.json or any git-tracked file. */
|
|
427
|
+
export function checkOutDir(
|
|
428
|
+
{ root, outDir, staging, configDir, workerDir, assetsDir, given },
|
|
429
|
+
fsx = REAL_FS
|
|
430
|
+
) {
|
|
431
|
+
const fix =
|
|
432
|
+
"Point --out-dir (or assets.directory in the wrangler config) at a directory only the build " +
|
|
433
|
+
"writes, such as dist/.";
|
|
434
|
+
const pruned = "it is emptied and refilled to match every build";
|
|
435
|
+
const rootC = canonicalPath(root, fsx);
|
|
436
|
+
const show = (p) => {
|
|
437
|
+
const c = canonicalPath(p, fsx);
|
|
438
|
+
return sameDir(c, rootC, fsx) ? ". (the site root)" : `${relative(rootC, c)}/`;
|
|
439
|
+
};
|
|
440
|
+
const refuse = (msg) => {
|
|
441
|
+
const name = given && resolve(configDir, given) !== outDir ? `${given} (${outDir})` : outDir;
|
|
442
|
+
throw new Error(`refusing output dir ${name}: ${msg}. ${fix}`);
|
|
443
|
+
};
|
|
444
|
+
const within = (a, b) => dirWithin(a, b, fsx);
|
|
445
|
+
|
|
446
|
+
if (sameDir(outDir, rootC, fsx) || !within(outDir, rootC)) {
|
|
447
|
+
refuse(`it must be a subdirectory of the site root ${root}, because ${pruned}`);
|
|
448
|
+
}
|
|
449
|
+
const leaves = ["src", "public", "node_modules", ".git"].map((d) => join(rootC, d));
|
|
450
|
+
const containers = [configDir];
|
|
451
|
+
if (workerDir) {
|
|
452
|
+
if (within(rootC, workerDir) || within(configDir, workerDir)) containers.push(workerDir);
|
|
453
|
+
else if (assetsDir && within(workerDir, assetsDir)) {
|
|
454
|
+
if (within(outDir, workerDir)) leaves.push(workerDir);
|
|
455
|
+
} else leaves.push(workerDir);
|
|
456
|
+
}
|
|
457
|
+
for (const d of leaves) {
|
|
458
|
+
if (within(outDir, d)) {
|
|
459
|
+
const how = sameDir(outDir, d, fsx) ? "" : "inside ";
|
|
460
|
+
refuse(`it is ${how}${show(d)}, which holds source, and ${pruned}`);
|
|
461
|
+
}
|
|
462
|
+
if (within(d, outDir)) refuse(`it contains ${show(d)}, which holds source, and ${pruned}`);
|
|
463
|
+
}
|
|
464
|
+
for (const d of containers) {
|
|
465
|
+
if (within(d, outDir)) {
|
|
466
|
+
const how = sameDir(outDir, d, fsx) ? "is" : "contains";
|
|
467
|
+
refuse(`it ${how} ${show(d)} (it holds the wrangler config or Worker), and ${pruned}`);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
for (const dir of [outDir, staging]) {
|
|
471
|
+
const d = canonicalPath(dir, fsx);
|
|
472
|
+
if (fsx.exists(join(d, "package.json"))) {
|
|
473
|
+
refuse(
|
|
474
|
+
`${show(d)} has a package.json, so it looks like a package, not build output, and ${pruned}`
|
|
475
|
+
);
|
|
476
|
+
}
|
|
477
|
+
const tracked = fsx.tracked(rootC, d);
|
|
478
|
+
if (tracked.length > 0) {
|
|
479
|
+
const sample = tracked.slice(0, 3).join(", ") + (tracked.length > 3 ? ", …" : "");
|
|
480
|
+
refuse(
|
|
481
|
+
`${show(d)} holds ${tracked.length} git-tracked file(s) (${sample}), and ${pruned}, so they ` +
|
|
482
|
+
`would be deleted. Build output is normally gitignored; if these really are build ` +
|
|
483
|
+
`output, untrack them (git rm -r --cached ${relative(rootC, d)})`
|
|
484
|
+
);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/* ------------------------------------------------------------ CLI args */
|
|
490
|
+
|
|
491
|
+
export const HELP = `cloudflare-md-router dev — production-faithful dev loop for a Worker + static assets site
|
|
492
|
+
|
|
493
|
+
Usage: cloudflare-md-router dev [options] [-- <extra wrangler dev args>]
|
|
494
|
+
|
|
495
|
+
--build <cmd> build command (default: the site's "build" script via its package manager).
|
|
496
|
+
Run through the shell with node_modules/.bin on PATH, so "astro build" works.
|
|
497
|
+
--out-dir <dir> served output dir (default: assets.directory from the wrangler config, else dist);
|
|
498
|
+
a relative path resolves against the wrangler config's directory. Emptied and
|
|
499
|
+
refilled on every build, so the site root, anything outside it, source dirs
|
|
500
|
+
(src, public, node_modules, .git, the Worker's), the config's dir, and a dir
|
|
501
|
+
with a package.json or git-tracked files are refused.
|
|
502
|
+
--out-dir-flag <f> flag used to point the build at the staging dir (default: ${DEFAULT_OUT_DIR_FLAG};
|
|
503
|
+
use "" to disable). Ignored if --build contains {outDir}.
|
|
504
|
+
--watch <path> extra path to rebuild on, repeatable or comma-separated, added to the defaults
|
|
505
|
+
(src, public, astro/vite config, tsconfig.json, package.json, .env*).
|
|
506
|
+
Directories recurse; anything else is a root-level file name (a trailing *
|
|
507
|
+
is a prefix match); nested file paths and missing dirs are skipped, with a
|
|
508
|
+
warning. The Worker dir is NOT watched: wrangler reloads it itself. Never
|
|
509
|
+
triggering: the output and staging dirs, node_modules, .git, .wrangler,
|
|
510
|
+
framework caches (.astro, .svelte-kit, .next, …), and paths below a watched
|
|
511
|
+
dir that git ignores — unless that watched dir is itself gitignored. Root-
|
|
512
|
+
level exact names, .env* and names you pass are never git-filtered; the
|
|
513
|
+
astro.config.* / vite.config.* globs are. Vite's *.timestamp-<ms>[-<hex>].[cm]?js
|
|
514
|
+
temp configs are skipped anywhere.
|
|
515
|
+
--no-default-watch watch only what --watch names
|
|
516
|
+
--port <n> first port to try (default: $PORT, else ${DEFAULT_PORT}); walks up to ${PORT_TRIES - 1} higher
|
|
517
|
+
--config <file> wrangler config (default: wrangler.jsonc, wrangler.json, wrangler.toml); must exist
|
|
518
|
+
--root <dir> site root (default: cwd)
|
|
519
|
+
--strict do not set MD_ROUTER_DEV=1 for the build (keep strict checks on)
|
|
520
|
+
--help, -h
|
|
521
|
+
|
|
522
|
+
Env: PORT, MD_ROUTER_DEV_BUILD, MD_ROUTER_DEV_STRICT=1. Flags win over env.
|
|
523
|
+
The build sees MD_ROUTER_DEV=1 (unless strict) and MD_ROUTER_DEV_OUT_DIR=<staging dir>.`;
|
|
524
|
+
|
|
525
|
+
const VALUE_FLAGS = new Set([
|
|
526
|
+
"--build",
|
|
527
|
+
"--out-dir",
|
|
528
|
+
"--out-dir-flag",
|
|
529
|
+
"--watch",
|
|
530
|
+
"--port",
|
|
531
|
+
"--config",
|
|
532
|
+
"--root",
|
|
533
|
+
]);
|
|
534
|
+
|
|
535
|
+
/** argv (after the `dev` subcommand) → raw flags. Throws a user-facing Error on bad input. */
|
|
536
|
+
export function parseArgs(argv) {
|
|
537
|
+
const flags = { watch: [], wranglerArgs: [] };
|
|
538
|
+
for (let i = 0; i < argv.length; i++) {
|
|
539
|
+
let arg = argv[i];
|
|
540
|
+
if (arg === "--") {
|
|
541
|
+
flags.wranglerArgs = argv.slice(i + 1);
|
|
542
|
+
break;
|
|
543
|
+
}
|
|
544
|
+
if (arg === "--help" || arg === "-h") flags.help = true;
|
|
545
|
+
else if (arg === "--strict") flags.strict = true;
|
|
546
|
+
else if (arg === "--no-default-watch") flags.noDefaultWatch = true;
|
|
547
|
+
else {
|
|
548
|
+
let value;
|
|
549
|
+
const eq = arg.indexOf("=");
|
|
550
|
+
if (arg.startsWith("--") && eq !== -1) {
|
|
551
|
+
value = arg.slice(eq + 1);
|
|
552
|
+
arg = arg.slice(0, eq);
|
|
553
|
+
}
|
|
554
|
+
if (!VALUE_FLAGS.has(arg)) throw new Error(`unknown option ${arg} (try --help)`);
|
|
555
|
+
if (value === undefined) {
|
|
556
|
+
value = argv[++i];
|
|
557
|
+
if (value === undefined) throw new Error(`${arg} needs a value`);
|
|
558
|
+
}
|
|
559
|
+
if (arg === "--watch") {
|
|
560
|
+
flags.watch.push(...value.split(",").filter(Boolean));
|
|
561
|
+
} else flags[arg.slice(2).replace(/-(\w)/g, (_, c) => c.toUpperCase())] = value;
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
return flags;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
const truthy = (v) => v !== undefined && v !== "" && v !== "0" && v.toLowerCase() !== "false";
|
|
568
|
+
|
|
569
|
+
/** Flags + env + the site on disk → everything the loop needs. Throws on invalid input. */
|
|
570
|
+
export function resolveOptions(flags, env, cwd) {
|
|
571
|
+
const root = resolve(cwd, flags.root ?? ".");
|
|
572
|
+
const wrangler = readWranglerConfig(root, flags.config);
|
|
573
|
+
|
|
574
|
+
const port = parsePort(flags.port ?? env.PORT);
|
|
575
|
+
if (port === null) {
|
|
576
|
+
throw new Error(
|
|
577
|
+
`port must be an integer 1-${MAX_PORT}, got ${JSON.stringify(flags.port ?? env.PORT)}`
|
|
578
|
+
);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
const outDirRaw = flags.outDir ?? wrangler.assetsDirectory ?? DEFAULT_OUT_DIR;
|
|
582
|
+
const configDir = wrangler.file ? dirname(wrangler.file) : root;
|
|
583
|
+
// Canonical (on-disk case, symlinks resolved), so the watcher's ignore check — which compares
|
|
584
|
+
// against paths built from what the filesystem reports — matches whatever spelling was passed.
|
|
585
|
+
const outDir = canonicalPath(resolve(configDir, outDirRaw));
|
|
586
|
+
const staging = join(dirname(outDir), `.dev-${basename(outDir)}`);
|
|
587
|
+
checkOutDir({
|
|
588
|
+
given: outDirRaw,
|
|
589
|
+
root,
|
|
590
|
+
outDir,
|
|
591
|
+
staging,
|
|
592
|
+
configDir,
|
|
593
|
+
workerDir: wrangler.main ? dirname(resolve(configDir, wrangler.main)) : undefined,
|
|
594
|
+
assetsDir: wrangler.assetsDirectory ? resolve(configDir, wrangler.assetsDirectory) : undefined,
|
|
595
|
+
});
|
|
596
|
+
|
|
597
|
+
const watch = [
|
|
598
|
+
...(flags.noDefaultWatch ? [] : [...DEFAULT_WATCH, ...DEFAULT_ROOT_TRIGGERS]),
|
|
599
|
+
...flags.watch,
|
|
600
|
+
];
|
|
601
|
+
|
|
602
|
+
const pm = detectPackageManager(root);
|
|
603
|
+
const buildOverride = flags.build ?? (env.MD_ROUTER_DEV_BUILD || undefined);
|
|
604
|
+
|
|
605
|
+
return {
|
|
606
|
+
root: canonicalPath(root),
|
|
607
|
+
port,
|
|
608
|
+
pm,
|
|
609
|
+
outDir,
|
|
610
|
+
staging,
|
|
611
|
+
wranglerConfig: wrangler.file,
|
|
612
|
+
watch,
|
|
613
|
+
userWatch: flags.watch,
|
|
614
|
+
outDirFlag: flags.outDirFlag ?? DEFAULT_OUT_DIR_FLAG,
|
|
615
|
+
buildOverride,
|
|
616
|
+
strict: flags.strict === true || truthy(env.MD_ROUTER_DEV_STRICT),
|
|
617
|
+
wranglerArgs: flags.wranglerArgs,
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/** The build invocation: `{ shell: string }` for a custom command, `{ cmd, args }` for the default. */
|
|
622
|
+
export function buildInvocation(opts) {
|
|
623
|
+
const stagingRel = relative(opts.root, opts.staging) || opts.staging;
|
|
624
|
+
if (opts.buildOverride) {
|
|
625
|
+
let command = opts.buildOverride;
|
|
626
|
+
if (command.includes("{outDir}")) {
|
|
627
|
+
command = command.split("{outDir}").join(shellQuote(stagingRel));
|
|
628
|
+
} else if (opts.outDirFlag) {
|
|
629
|
+
command = `${command} ${shellQuote(opts.outDirFlag)} ${shellQuote(stagingRel)}`;
|
|
630
|
+
}
|
|
631
|
+
return { shell: command };
|
|
632
|
+
}
|
|
633
|
+
const extra = opts.outDirFlag ? [opts.outDirFlag, stagingRel] : [];
|
|
634
|
+
const [cmd, args] = runScriptCommand(opts.pm, "build", extra);
|
|
635
|
+
return { cmd, args };
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/** Directories to watch recursively, and root-level file names (`*` suffix = prefix match) to
|
|
639
|
+
* match in the root directory. Entries that can't be watched land in `dropped` with the reason, so
|
|
640
|
+
* the caller can say so for the ones the user asked for (a default like `public` is just absent). */
|
|
641
|
+
export function classifyWatch(root, entries) {
|
|
642
|
+
const dirs = [];
|
|
643
|
+
const names = [];
|
|
644
|
+
const dropped = [];
|
|
645
|
+
for (const entry of entries) {
|
|
646
|
+
const abs = isAbsolute(entry) ? entry : join(root, entry);
|
|
647
|
+
let isDir = false;
|
|
648
|
+
try {
|
|
649
|
+
isDir = statSync(abs).isDirectory();
|
|
650
|
+
} catch {}
|
|
651
|
+
if (isDir) dirs.push(abs);
|
|
652
|
+
else if (entry.includes("/") || entry.includes(sep)) {
|
|
653
|
+
dropped.push({
|
|
654
|
+
entry,
|
|
655
|
+
why: existsSync(abs)
|
|
656
|
+
? "only directories and root-level file names can be watched; watch its directory"
|
|
657
|
+
: "no such directory",
|
|
658
|
+
});
|
|
659
|
+
}
|
|
660
|
+
// A plain name with no dot or `*` that isn't on disk is a directory that doesn't exist (yet),
|
|
661
|
+
// e.g. a site with no `public/`. Skip it; `.env` and `*.config.*` style names are kept.
|
|
662
|
+
else if (entry.includes("*") || entry.includes(".") || existsSync(abs)) names.push(entry);
|
|
663
|
+
else dropped.push({ entry, why: "no such directory" });
|
|
664
|
+
}
|
|
665
|
+
return { dirs, names, dropped };
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/** Does a root-level file name match a watch name (exact, or prefix when it ends in `*`, which
|
|
669
|
+
* covers `.env*` and `astro.config.*`)? */
|
|
670
|
+
export function matchesName(names, file) {
|
|
671
|
+
return names.some((n) => {
|
|
672
|
+
if (n.endsWith("*")) return file.startsWith(n.slice(0, -1));
|
|
673
|
+
return n === file;
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
/** Editor and tool droppings, skipped anywhere under a watched path: macOS Finder, vim swap/backup
|
|
678
|
+
* files, vim's fsync probe, and Vite's bundled temp config `*.timestamp-<ms>[-<hex>].[cm]?js` — written and
|
|
679
|
+
* deleted next to the config on every load by Vite 3-5 (`<ms>` alone in Vite 3, `-<hex>` added in
|
|
680
|
+
* 4-5); it matches the `vite.config.*` default and would loop. */
|
|
681
|
+
export const IGNORED =
|
|
682
|
+
/(^|\/)(\.DS_Store|4913|.*\.sw[px]|.*~|.*\.timestamp-\d+(-[0-9a-f]+)?\.[cm]?js)$/;
|