@stagepass/cli 2.2.7 → 2.3.0-beta.1
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 +37 -18
- package/TESTING-macos.md +28 -10
- package/bin/index.js +4 -1
- package/package.json +9 -8
- package/src/cli.js +62 -7
- package/src/commands/certs.js +375 -19
- package/src/commands/daemon.js +75 -7
- package/src/commands/dev.js +419 -0
- package/src/commands/link.js +64 -23
- package/src/commands/new.js +397 -41
- package/src/commands/npm-run.js +8 -0
- package/src/commands/start.js +196 -127
- package/src/commands/stop.js +10 -19
- package/src/commands/unlink.js +6 -4
- package/src/commands/upgrade.js +51 -12
- package/src/lib/apply-site-block.js +48 -0
- package/src/lib/caddyfile.js +72 -13
- package/src/lib/cdn-snippets.js +145 -3
- package/src/lib/certs.js +334 -47
- package/src/lib/dev-port.js +45 -0
- package/src/lib/doctor-site.js +61 -5
- package/src/lib/doctor.js +48 -4
- package/src/lib/ensure-running.js +89 -0
- package/src/lib/exec.js +72 -24
- package/src/lib/live-server.js +484 -0
- package/src/lib/node-engine.js +55 -0
- package/src/lib/notify.js +62 -0
- package/src/lib/origins.js +27 -5
- package/src/lib/package-versions.js +9 -0
- package/src/lib/paths.js +18 -0
- package/src/lib/php-fpm.js +33 -0
- package/src/lib/project-sync.js +165 -20
- package/src/lib/projects.js +137 -7
- package/src/lib/prompts.js +19 -0
- package/src/lib/registry.js +27 -6
- package/src/lib/scaffold.js +288 -11
- package/src/lib/site-detect.js +78 -25
- package/src/lib/snippets.js +14 -11
- package/src/lib/versions.js +20 -8
- package/templates/project/AGENTS.md.tmpl +4 -3
- package/templates/project/README.md.tmpl +35 -6
- package/templates/project/api/README.md.tmpl +7 -0
- package/templates/project/examples/php/README.md.tmpl +18 -0
- package/templates/project/examples/php/form.php +105 -0
- package/templates/project/examples/php/proxy.php +171 -0
- package/templates/project/scripts/build.mjs +200 -37
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import chalk from 'chalk';
|
|
2
|
+
import { defaultExec } from './exec.js';
|
|
3
|
+
import { parseLsofListenOutput } from './doctor.js';
|
|
4
|
+
import { findProjectByRoot } from './projects.js';
|
|
5
|
+
import { getProjectsPath } from './paths.js';
|
|
6
|
+
import { confirm as defaultConfirm } from './prompts.js';
|
|
7
|
+
|
|
8
|
+
/** Caddy listening on TCP 443 (same lsof parse as doctor); null if unknown. */
|
|
9
|
+
export async function isStagepassRunning(opts = {}) {
|
|
10
|
+
const exec = opts.exec || defaultExec;
|
|
11
|
+
try {
|
|
12
|
+
const { stdout } = await exec('lsof', ['-nP', '-iTCP:443', '-sTCP:LISTEN']);
|
|
13
|
+
return parseLsofListenOutput(stdout).some(
|
|
14
|
+
(l) => /caddy/i.test(l.command) || /caddy/i.test(l.name)
|
|
15
|
+
);
|
|
16
|
+
} catch (error) {
|
|
17
|
+
const err = /** @type {{ code?: string|number }} */ (error);
|
|
18
|
+
return err.code === 1 || err.code === '1' ? false : null;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Before watch/dev: offer start when down; warn when cwd is unlinked unless `unlinked: 'skip'`.
|
|
24
|
+
* @returns {Promise<{ running: boolean|null, linked: boolean, started: boolean }>}
|
|
25
|
+
*/
|
|
26
|
+
export async function ensureStagepassReady(options = {}, deps = {}) {
|
|
27
|
+
const log = deps.log || console.log;
|
|
28
|
+
const warn = (msg) => log(chalk.yellow(msg));
|
|
29
|
+
const cwd = deps.cwd || process.cwd();
|
|
30
|
+
const projectsPath = deps.projectsPath || getProjectsPath();
|
|
31
|
+
const isRunningFn = deps.isStagepassRunning || isStagepassRunning;
|
|
32
|
+
const findLinked = deps.findProjectByRoot || findProjectByRoot;
|
|
33
|
+
const confirm = deps.confirm || defaultConfirm;
|
|
34
|
+
const interactive =
|
|
35
|
+
options.yes !== true &&
|
|
36
|
+
!(deps.ci ?? process.env.CI) &&
|
|
37
|
+
Boolean(
|
|
38
|
+
(deps.stdin || process.stdin).isTTY && (deps.stdout || process.stdout).isTTY
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
let running = await isRunningFn({ exec: deps.exec });
|
|
42
|
+
let started = false;
|
|
43
|
+
|
|
44
|
+
if (running === false) {
|
|
45
|
+
const shouldStart =
|
|
46
|
+
options.yes === true ||
|
|
47
|
+
(interactive &&
|
|
48
|
+
(await confirm('Stagepass is not running. Start it now?', {
|
|
49
|
+
default: true,
|
|
50
|
+
})));
|
|
51
|
+
|
|
52
|
+
if (shouldStart && typeof deps.start === 'function') {
|
|
53
|
+
try {
|
|
54
|
+
const code = await deps.start({
|
|
55
|
+
verbose: options.verbose,
|
|
56
|
+
interactive: options.yes !== true && interactive,
|
|
57
|
+
exec: deps.exec,
|
|
58
|
+
confirm,
|
|
59
|
+
});
|
|
60
|
+
// start() must return 0 on success; undefined/non-zero means not started.
|
|
61
|
+
if (typeof code !== 'number' || code !== 0) {
|
|
62
|
+
warn('Could not start Stagepass. Run: stagepass start');
|
|
63
|
+
running = await isRunningFn({ exec: deps.exec });
|
|
64
|
+
} else {
|
|
65
|
+
running = await isRunningFn({ exec: deps.exec });
|
|
66
|
+
if (running === true) {
|
|
67
|
+
started = true;
|
|
68
|
+
} else {
|
|
69
|
+
warn('Could not start Stagepass. Run: stagepass start');
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
} catch {
|
|
73
|
+
warn('Could not start Stagepass. Run: stagepass start');
|
|
74
|
+
}
|
|
75
|
+
} else if (!shouldStart) {
|
|
76
|
+
warn('Stagepass is not running. Start it with: stagepass start');
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
let linked = true;
|
|
81
|
+
if (deps.unlinked !== 'skip') {
|
|
82
|
+
linked = Boolean(await findLinked(cwd, projectsPath));
|
|
83
|
+
if (!linked) {
|
|
84
|
+
warn('This directory is not linked to a .sp domain. Run: stagepass link');
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return { running, linked, started };
|
|
89
|
+
}
|
package/src/lib/exec.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { execFile as nodeExecFile } from 'node:child_process';
|
|
1
|
+
import { execFile as nodeExecFile, spawn } from 'node:child_process';
|
|
2
2
|
import { promisify } from 'node:util';
|
|
3
3
|
|
|
4
4
|
const execFileAsync = promisify(nodeExecFile);
|
|
@@ -14,42 +14,90 @@ const execFileAsync = promisify(nodeExecFile);
|
|
|
14
14
|
* @typedef {(file: string, args?: string[], options?: object) => Promise<ExecResult>} ExecFn
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
+
/**
|
|
18
|
+
* @param {NodeJS.ErrnoException & { stdout?: string, stderr?: string, code?: number|string, killed?: boolean, signal?: string }} err
|
|
19
|
+
* @returns {Error}
|
|
20
|
+
*/
|
|
21
|
+
function wrapExecError(err) {
|
|
22
|
+
const wrapped = new Error(err.message || String(err));
|
|
23
|
+
Object.assign(wrapped, {
|
|
24
|
+
code: err.code,
|
|
25
|
+
errno: err.errno,
|
|
26
|
+
stdout: err.stdout != null ? String(err.stdout) : '',
|
|
27
|
+
stderr: err.stderr != null ? String(err.stderr) : '',
|
|
28
|
+
killed: err.killed,
|
|
29
|
+
signal: err.signal,
|
|
30
|
+
});
|
|
31
|
+
return wrapped;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Wait for spawn exit when stdout/stderr are not captured pipes.
|
|
36
|
+
* Avoids execFile+encoding hanging while a daemon grandchild still holds
|
|
37
|
+
* inherited logfile FDs (public `stagepass start` non-verbose path).
|
|
38
|
+
* @param {string} file
|
|
39
|
+
* @param {string[]} args
|
|
40
|
+
* @param {object} options
|
|
41
|
+
* @returns {Promise<ExecResult>}
|
|
42
|
+
*/
|
|
43
|
+
function spawnWait(file, args, options) {
|
|
44
|
+
return new Promise((resolve, reject) => {
|
|
45
|
+
const child = spawn(file, args, { ...options, shell: false });
|
|
46
|
+
child.on('error', (error) => {
|
|
47
|
+
reject(wrapExecError(/** @type {NodeJS.ErrnoException} */ (error)));
|
|
48
|
+
});
|
|
49
|
+
child.on('close', (code, signal) => {
|
|
50
|
+
if (code === 0) {
|
|
51
|
+
resolve({ stdout: '', stderr: '', code: 0 });
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
const err = /** @type {NodeJS.ErrnoException & { code?: number|string, signal?: string }} */ (
|
|
55
|
+
new Error(`Command failed: ${file} ${args.join(' ')}`)
|
|
56
|
+
);
|
|
57
|
+
err.code = code == null ? signal || 1 : code;
|
|
58
|
+
err.signal = signal || undefined;
|
|
59
|
+
reject(wrapExecError(err));
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
17
64
|
/**
|
|
18
65
|
* Default execFile wrapper. Always uses argument arrays (never a shell string).
|
|
19
66
|
* @type {ExecFn}
|
|
20
67
|
*/
|
|
21
68
|
export async function defaultExec(file, args = [], options = {}) {
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
69
|
+
const stdio = options.stdio;
|
|
70
|
+
const inheritStdio = stdio === 'inherit';
|
|
71
|
+
const customStdio = inheritStdio || Array.isArray(stdio) || stdio === 'ignore';
|
|
72
|
+
|
|
73
|
+
// Capture-output path (doctor/certs/which): execFile + encoding.
|
|
74
|
+
// Custom stdio (start logfile FDs / inherit): spawn + wait for exit only.
|
|
75
|
+
if (customStdio) {
|
|
76
|
+
try {
|
|
77
|
+
return await spawnWait(file, args, { ...options, shell: false });
|
|
78
|
+
} catch (error) {
|
|
79
|
+
throw error instanceof Error ? error : wrapExecError(/** @type {any} */ (error));
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
32
83
|
try {
|
|
33
|
-
const result = await execFileAsync(file, args,
|
|
84
|
+
const result = await execFileAsync(file, args, {
|
|
85
|
+
encoding: 'utf8',
|
|
86
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
87
|
+
...options,
|
|
88
|
+
shell: false,
|
|
89
|
+
});
|
|
34
90
|
return {
|
|
35
91
|
stdout: result?.stdout != null ? String(result.stdout) : '',
|
|
36
92
|
stderr: result?.stderr != null ? String(result.stderr) : '',
|
|
37
93
|
code: 0,
|
|
38
94
|
};
|
|
39
95
|
} catch (error) {
|
|
40
|
-
|
|
41
|
-
|
|
96
|
+
throw wrapExecError(
|
|
97
|
+
/** @type {NodeJS.ErrnoException & { stdout?: string, stderr?: string, code?: number|string, killed?: boolean, signal?: string }} */ (
|
|
98
|
+
error
|
|
99
|
+
)
|
|
42
100
|
);
|
|
43
|
-
const wrapped = new Error(err.message || String(error));
|
|
44
|
-
Object.assign(wrapped, {
|
|
45
|
-
code: err.code,
|
|
46
|
-
errno: err.errno,
|
|
47
|
-
stdout: err.stdout != null ? String(err.stdout) : '',
|
|
48
|
-
stderr: err.stderr != null ? String(err.stderr) : '',
|
|
49
|
-
killed: /** @type {{ killed?: boolean }} */ (err).killed,
|
|
50
|
-
signal: /** @type {{ signal?: string }} */ (err).signal,
|
|
51
|
-
});
|
|
52
|
-
throw wrapped;
|
|
53
101
|
}
|
|
54
102
|
}
|
|
55
103
|
|
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local live-reload event server for `stagepass dev`.
|
|
3
|
+
* Binds 127.0.0.1 only. Serves Server-Sent Events at /__stagepass/live.
|
|
4
|
+
* No request data is reflected into responses.
|
|
5
|
+
*
|
|
6
|
+
* Change classification is content-based: identical rewrites (same bytes) are
|
|
7
|
+
* ignored. Only real CSS changes batch as `{type:'css'}`; any other real change
|
|
8
|
+
* is `{type:'reload'}`. `manifest.json`, dotfiles, `~` backups and `.map` files
|
|
9
|
+
* are ignored.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import http from 'node:http';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import { watch as fsWatch } from 'node:fs';
|
|
16
|
+
import { createHash } from 'node:crypto';
|
|
17
|
+
|
|
18
|
+
export const LIVE_PATH = '/__stagepass/live';
|
|
19
|
+
export const MAX_CONNECTIONS = 32;
|
|
20
|
+
export const HEARTBEAT_MS = 25_000;
|
|
21
|
+
export const DEFAULT_DEBOUNCE_MS = 100;
|
|
22
|
+
/** Skip hashing (treat as always-changed) above this size. */
|
|
23
|
+
export const MAX_HASH_BYTES = 4 * 1024 * 1024;
|
|
24
|
+
/** Bound memory for the content-hash map. */
|
|
25
|
+
export const MAX_TRACKED_FILES = 4096;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @param {string} projectRoot absolute project root
|
|
29
|
+
* @param {string} outDirRel relative output dir (e.g. "dist")
|
|
30
|
+
* @returns {{ ok: true, abs: string, rel: string } | { ok: false, error: string }}
|
|
31
|
+
*/
|
|
32
|
+
export function resolveOutputDir(projectRoot, outDirRel = 'dist') {
|
|
33
|
+
const root = path.resolve(projectRoot);
|
|
34
|
+
const raw = typeof outDirRel === 'string' && outDirRel.trim() ? outDirRel.trim() : 'dist';
|
|
35
|
+
if (path.isAbsolute(raw) || raw.includes('\0')) {
|
|
36
|
+
return { ok: false, error: 'Output directory must be a relative path inside the project.' };
|
|
37
|
+
}
|
|
38
|
+
const normalized = path.normalize(raw).replace(/\\/g, '/');
|
|
39
|
+
if (
|
|
40
|
+
normalized === '..' ||
|
|
41
|
+
normalized.startsWith('../') ||
|
|
42
|
+
normalized.split('/').includes('..')
|
|
43
|
+
) {
|
|
44
|
+
return { ok: false, error: 'Output directory must stay inside the project root.' };
|
|
45
|
+
}
|
|
46
|
+
const abs = path.resolve(root, normalized);
|
|
47
|
+
const relToRoot = path.relative(root, abs);
|
|
48
|
+
if (relToRoot.startsWith('..') || path.isAbsolute(relToRoot)) {
|
|
49
|
+
return { ok: false, error: 'Output directory must stay inside the project root.' };
|
|
50
|
+
}
|
|
51
|
+
return { ok: true, abs, rel: relToRoot.split(path.sep).join('/') || '.' };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Classify changed relative URL paths into css vs reload.
|
|
56
|
+
* @param {string[]} urlPaths
|
|
57
|
+
* @returns {'css'|'reload'}
|
|
58
|
+
*/
|
|
59
|
+
export function classifyChange(urlPaths) {
|
|
60
|
+
if (urlPaths.length === 0) return 'reload';
|
|
61
|
+
const onlyCss = urlPaths.every((p) => /\.css$/i.test(p.split('?')[0]));
|
|
62
|
+
return onlyCss ? 'css' : 'reload';
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* @param {string} base basename
|
|
67
|
+
* @returns {boolean}
|
|
68
|
+
*/
|
|
69
|
+
export function isIgnoredWatchBase(base) {
|
|
70
|
+
return (
|
|
71
|
+
base.startsWith('.') ||
|
|
72
|
+
base.endsWith('~') ||
|
|
73
|
+
base.endsWith('.map') ||
|
|
74
|
+
base === 'manifest.json'
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Turn an absolute file path under outAbs into a site-relative URL path
|
|
80
|
+
* (project-root relative, with leading slash). Returns null when outside or ignored.
|
|
81
|
+
* @param {string} fileAbs
|
|
82
|
+
* @param {string} projectRoot
|
|
83
|
+
* @param {string} outAbs
|
|
84
|
+
*/
|
|
85
|
+
export function toUrlPath(fileAbs, projectRoot, outAbs) {
|
|
86
|
+
const root = path.resolve(projectRoot);
|
|
87
|
+
const out = path.resolve(outAbs);
|
|
88
|
+
const file = path.resolve(fileAbs);
|
|
89
|
+
const relOut = path.relative(out, file);
|
|
90
|
+
if (relOut.startsWith('..') || path.isAbsolute(relOut)) return null;
|
|
91
|
+
const relProject = path.relative(root, file);
|
|
92
|
+
if (relProject.startsWith('..') || path.isAbsolute(relProject)) return null;
|
|
93
|
+
const base = path.basename(file);
|
|
94
|
+
if (isIgnoredWatchBase(base)) return null;
|
|
95
|
+
return '/' + relProject.split(path.sep).join('/');
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Resolve a path that must stay under outAbs (no escape). Returns null if outside.
|
|
100
|
+
* Does not follow the final path if missing (deletion); still rejects lexical escapes.
|
|
101
|
+
* @param {string} fileAbs
|
|
102
|
+
* @param {string} outAbs
|
|
103
|
+
* @returns {string|null}
|
|
104
|
+
*/
|
|
105
|
+
export function resolveUnderOutDir(fileAbs, outAbs) {
|
|
106
|
+
const out = path.resolve(outAbs);
|
|
107
|
+
const file = path.resolve(fileAbs);
|
|
108
|
+
const rel = path.relative(out, file);
|
|
109
|
+
if (rel.startsWith('..') || path.isAbsolute(rel) || rel.includes('\0')) return null;
|
|
110
|
+
return file;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* @param {string} fileAbs
|
|
115
|
+
* @param {number} [maxBytes]
|
|
116
|
+
* @returns {{ kind: 'missing' } | { kind: 'hash', hash: string } | { kind: 'large', token: string } | { kind: 'error' }}
|
|
117
|
+
*/
|
|
118
|
+
export function contentFingerprint(fileAbs, maxBytes = MAX_HASH_BYTES) {
|
|
119
|
+
try {
|
|
120
|
+
const st = fs.statSync(fileAbs);
|
|
121
|
+
if (!st.isFile()) return { kind: 'error' };
|
|
122
|
+
if (st.size > maxBytes) {
|
|
123
|
+
return { kind: 'large', token: `large:${st.size}:${Math.trunc(st.mtimeMs)}` };
|
|
124
|
+
}
|
|
125
|
+
const buf = fs.readFileSync(fileAbs);
|
|
126
|
+
return {
|
|
127
|
+
kind: 'hash',
|
|
128
|
+
hash: createHash('sha256').update(buf).digest('hex'),
|
|
129
|
+
};
|
|
130
|
+
} catch (err) {
|
|
131
|
+
if (err && typeof err === 'object' && 'code' in err && err.code === 'ENOENT') {
|
|
132
|
+
return { kind: 'missing' };
|
|
133
|
+
}
|
|
134
|
+
return { kind: 'error' };
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Format one SSE data event.
|
|
140
|
+
* @param {{ type: string, paths: string[] }} payload
|
|
141
|
+
*/
|
|
142
|
+
export function formatSseEvent(payload) {
|
|
143
|
+
return `data: ${JSON.stringify(payload)}\n\n`;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Walk files under dir (non-following for dirs outside via resolve). Soft-fail.
|
|
148
|
+
* @param {string} dirAbs
|
|
149
|
+
* @param {(fileAbs: string) => void} visit
|
|
150
|
+
*/
|
|
151
|
+
function walkFiles(dirAbs, visit) {
|
|
152
|
+
/** @type {string[]} */
|
|
153
|
+
const stack = [dirAbs];
|
|
154
|
+
while (stack.length) {
|
|
155
|
+
const dir = stack.pop();
|
|
156
|
+
let entries;
|
|
157
|
+
try {
|
|
158
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
159
|
+
} catch {
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
for (const ent of entries) {
|
|
163
|
+
const full = path.join(dir, ent.name);
|
|
164
|
+
if (ent.isDirectory()) {
|
|
165
|
+
stack.push(full);
|
|
166
|
+
} else if (ent.isFile()) {
|
|
167
|
+
visit(full);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* @typedef {object} LiveServerOptions
|
|
175
|
+
* @property {string} projectRoot
|
|
176
|
+
* @property {string} [outDir]
|
|
177
|
+
* @property {number} [debounceMs]
|
|
178
|
+
* @property {number} [maxConnections]
|
|
179
|
+
* @property {number} [heartbeatMs]
|
|
180
|
+
* @property {(msg: string) => void} [log]
|
|
181
|
+
*/
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Create the live-reload HTTP server (not yet listening).
|
|
185
|
+
* @param {LiveServerOptions} options
|
|
186
|
+
*/
|
|
187
|
+
export function createLiveServer(options) {
|
|
188
|
+
const projectRoot = path.resolve(options.projectRoot);
|
|
189
|
+
const outResolved = resolveOutputDir(projectRoot, options.outDir || 'dist');
|
|
190
|
+
if (!outResolved.ok) {
|
|
191
|
+
throw new Error(outResolved.error);
|
|
192
|
+
}
|
|
193
|
+
const outAbs = outResolved.abs;
|
|
194
|
+
const debounceMs =
|
|
195
|
+
typeof options.debounceMs === 'number' && options.debounceMs >= 0
|
|
196
|
+
? options.debounceMs
|
|
197
|
+
: DEFAULT_DEBOUNCE_MS;
|
|
198
|
+
const maxConnections =
|
|
199
|
+
typeof options.maxConnections === 'number' && options.maxConnections > 0
|
|
200
|
+
? options.maxConnections
|
|
201
|
+
: MAX_CONNECTIONS;
|
|
202
|
+
const heartbeatMs =
|
|
203
|
+
typeof options.heartbeatMs === 'number' && options.heartbeatMs > 0
|
|
204
|
+
? options.heartbeatMs
|
|
205
|
+
: HEARTBEAT_MS;
|
|
206
|
+
const log = options.log || (() => {});
|
|
207
|
+
|
|
208
|
+
/** @type {Set<import('node:http').ServerResponse>} */
|
|
209
|
+
const clients = new Set();
|
|
210
|
+
/** @type {Set<string>} */
|
|
211
|
+
const pending = new Set();
|
|
212
|
+
/** @type {ReturnType<typeof setTimeout>|null} */
|
|
213
|
+
let debounceTimer = null;
|
|
214
|
+
/** @type {import('node:fs').FSWatcher|null} */
|
|
215
|
+
let watcher = null;
|
|
216
|
+
/** @type {ReturnType<typeof setInterval>|null} */
|
|
217
|
+
let heartbeat = null;
|
|
218
|
+
/** @type {Map<string, string>} abs path → fingerprint token */
|
|
219
|
+
const fileHashes = new Map();
|
|
220
|
+
|
|
221
|
+
function rememberHash(fileAbs, token) {
|
|
222
|
+
if (fileHashes.has(fileAbs)) {
|
|
223
|
+
fileHashes.set(fileAbs, token);
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
if (fileHashes.size >= MAX_TRACKED_FILES) {
|
|
227
|
+
const first = fileHashes.keys().next().value;
|
|
228
|
+
if (first !== undefined) fileHashes.delete(first);
|
|
229
|
+
}
|
|
230
|
+
fileHashes.set(fileAbs, token);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function seedHashes() {
|
|
234
|
+
fileHashes.clear();
|
|
235
|
+
walkFiles(outAbs, (fileAbs) => {
|
|
236
|
+
const safe = resolveUnderOutDir(fileAbs, outAbs);
|
|
237
|
+
if (!safe) return;
|
|
238
|
+
if (isIgnoredWatchBase(path.basename(safe))) return;
|
|
239
|
+
const fp = contentFingerprint(safe);
|
|
240
|
+
if (fp.kind === 'hash') rememberHash(safe, fp.hash);
|
|
241
|
+
else if (fp.kind === 'large') rememberHash(safe, fp.token);
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Compare current disk content to the last known fingerprint.
|
|
247
|
+
* Updates the hash map when the file exists. Intended for flush time so
|
|
248
|
+
* mid-write fs.watch races do not create false positives.
|
|
249
|
+
* @param {string} fileAbs
|
|
250
|
+
* @returns {boolean} true when content actually changed (or deleted)
|
|
251
|
+
*/
|
|
252
|
+
function hasContentChanged(fileAbs) {
|
|
253
|
+
const safe = resolveUnderOutDir(fileAbs, outAbs);
|
|
254
|
+
if (!safe) return false;
|
|
255
|
+
|
|
256
|
+
const fp = contentFingerprint(safe);
|
|
257
|
+
if (fp.kind === 'missing') {
|
|
258
|
+
if (!fileHashes.has(safe)) return false;
|
|
259
|
+
fileHashes.delete(safe);
|
|
260
|
+
return true;
|
|
261
|
+
}
|
|
262
|
+
if (fp.kind === 'error') {
|
|
263
|
+
// Unreadable: treat as changed so we do not miss a real update.
|
|
264
|
+
return true;
|
|
265
|
+
}
|
|
266
|
+
const token = fp.kind === 'hash' ? fp.hash : fp.token;
|
|
267
|
+
const prev = fileHashes.get(safe);
|
|
268
|
+
if (prev === token) return false;
|
|
269
|
+
rememberHash(safe, token);
|
|
270
|
+
return true;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function broadcast(payload) {
|
|
274
|
+
const body = formatSseEvent(payload);
|
|
275
|
+
for (const res of clients) {
|
|
276
|
+
try {
|
|
277
|
+
res.write(body);
|
|
278
|
+
} catch {
|
|
279
|
+
clients.delete(res);
|
|
280
|
+
try {
|
|
281
|
+
res.end();
|
|
282
|
+
} catch {
|
|
283
|
+
/* ignore */
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function flushPending() {
|
|
290
|
+
debounceTimer = null;
|
|
291
|
+
if (pending.size === 0) return;
|
|
292
|
+
/** @type {string[]} */
|
|
293
|
+
const changed = [];
|
|
294
|
+
for (const fileAbs of pending) {
|
|
295
|
+
if (!hasContentChanged(fileAbs)) continue;
|
|
296
|
+
const urlPath = toUrlPath(fileAbs, projectRoot, outAbs);
|
|
297
|
+
if (urlPath) changed.push(urlPath);
|
|
298
|
+
}
|
|
299
|
+
pending.clear();
|
|
300
|
+
if (changed.length === 0) return;
|
|
301
|
+
const paths = [...new Set(changed)].sort();
|
|
302
|
+
const type = classifyChange(paths);
|
|
303
|
+
broadcast({ type, paths });
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function noteChange(fileAbs) {
|
|
307
|
+
const safe = resolveUnderOutDir(fileAbs, outAbs);
|
|
308
|
+
if (!safe) return;
|
|
309
|
+
// Ignore junk / manifest early; defer content compare until debounce flush
|
|
310
|
+
// so identical rewrites (and mid-write watch races) do not false-trigger.
|
|
311
|
+
if (!toUrlPath(safe, projectRoot, outAbs)) return;
|
|
312
|
+
pending.add(safe);
|
|
313
|
+
if (debounceTimer) clearTimeout(debounceTimer);
|
|
314
|
+
debounceTimer = setTimeout(flushPending, debounceMs);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function startWatch() {
|
|
318
|
+
try {
|
|
319
|
+
fs.mkdirSync(outAbs, { recursive: true });
|
|
320
|
+
} catch {
|
|
321
|
+
/* ignore */
|
|
322
|
+
}
|
|
323
|
+
seedHashes();
|
|
324
|
+
try {
|
|
325
|
+
watcher = fsWatch(outAbs, { recursive: true }, (_event, filename) => {
|
|
326
|
+
if (!filename) return;
|
|
327
|
+
const name = typeof filename === 'string' ? filename : String(filename);
|
|
328
|
+
// Join only; resolveUnderOutDir rejects escapes (including .. segments).
|
|
329
|
+
noteChange(path.join(outAbs, name));
|
|
330
|
+
});
|
|
331
|
+
watcher.on('error', () => {
|
|
332
|
+
/* keep server up; next change may recover */
|
|
333
|
+
});
|
|
334
|
+
} catch (err) {
|
|
335
|
+
log(
|
|
336
|
+
`Live reload: could not watch ${outAbs} (${err instanceof Error ? err.message : String(err)})`
|
|
337
|
+
);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function stopWatch() {
|
|
342
|
+
if (debounceTimer) {
|
|
343
|
+
clearTimeout(debounceTimer);
|
|
344
|
+
debounceTimer = null;
|
|
345
|
+
}
|
|
346
|
+
pending.clear();
|
|
347
|
+
fileHashes.clear();
|
|
348
|
+
if (watcher) {
|
|
349
|
+
try {
|
|
350
|
+
watcher.close();
|
|
351
|
+
} catch {
|
|
352
|
+
/* ignore */
|
|
353
|
+
}
|
|
354
|
+
watcher = null;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
const server = http.createServer((req, res) => {
|
|
359
|
+
const method = req.method || 'GET';
|
|
360
|
+
let pathname = '/';
|
|
361
|
+
try {
|
|
362
|
+
pathname = new URL(req.url || '/', 'http://127.0.0.1').pathname;
|
|
363
|
+
} catch {
|
|
364
|
+
pathname = '/';
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
if (pathname !== LIVE_PATH) {
|
|
368
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
369
|
+
res.end('Not found');
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
if (method === 'OPTIONS') {
|
|
374
|
+
res.writeHead(204);
|
|
375
|
+
res.end();
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
380
|
+
res.writeHead(405, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
381
|
+
res.end('Method not allowed');
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
if (clients.size >= maxConnections) {
|
|
386
|
+
res.writeHead(503, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
387
|
+
res.end('Too many connections');
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
res.writeHead(200, {
|
|
392
|
+
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
393
|
+
'Cache-Control': 'no-cache, no-transform',
|
|
394
|
+
Connection: 'keep-alive',
|
|
395
|
+
'X-Accel-Buffering': 'no',
|
|
396
|
+
});
|
|
397
|
+
if (method === 'HEAD') {
|
|
398
|
+
res.end();
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
res.write(': connected\n\n');
|
|
403
|
+
clients.add(res);
|
|
404
|
+
|
|
405
|
+
const onClose = () => {
|
|
406
|
+
clients.delete(res);
|
|
407
|
+
req.off('close', onClose);
|
|
408
|
+
};
|
|
409
|
+
req.on('close', onClose);
|
|
410
|
+
});
|
|
411
|
+
|
|
412
|
+
function startHeartbeat() {
|
|
413
|
+
heartbeat = setInterval(() => {
|
|
414
|
+
for (const res of clients) {
|
|
415
|
+
try {
|
|
416
|
+
res.write(': ping\n\n');
|
|
417
|
+
} catch {
|
|
418
|
+
clients.delete(res);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}, heartbeatMs);
|
|
422
|
+
if (typeof heartbeat.unref === 'function') heartbeat.unref();
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* @param {number} [port] 0 = ephemeral
|
|
427
|
+
* @returns {Promise<{ port: number, close: () => Promise<void> }>}
|
|
428
|
+
*/
|
|
429
|
+
function listen(port = 0) {
|
|
430
|
+
return new Promise((resolve, reject) => {
|
|
431
|
+
const onError = (err) => {
|
|
432
|
+
server.off('listening', onListening);
|
|
433
|
+
reject(err);
|
|
434
|
+
};
|
|
435
|
+
const onListening = () => {
|
|
436
|
+
server.off('error', onError);
|
|
437
|
+
const addr = server.address();
|
|
438
|
+
const bound =
|
|
439
|
+
addr && typeof addr === 'object' && typeof addr.port === 'number' ? addr.port : 0;
|
|
440
|
+
startWatch();
|
|
441
|
+
startHeartbeat();
|
|
442
|
+
resolve({
|
|
443
|
+
port: bound,
|
|
444
|
+
close: async () => {
|
|
445
|
+
if (heartbeat) {
|
|
446
|
+
clearInterval(heartbeat);
|
|
447
|
+
heartbeat = null;
|
|
448
|
+
}
|
|
449
|
+
stopWatch();
|
|
450
|
+
for (const res of clients) {
|
|
451
|
+
try {
|
|
452
|
+
res.end();
|
|
453
|
+
} catch {
|
|
454
|
+
/* ignore */
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
clients.clear();
|
|
458
|
+
await new Promise((resClose, rejClose) => {
|
|
459
|
+
server.close((err) => (err ? rejClose(err) : resClose()));
|
|
460
|
+
});
|
|
461
|
+
},
|
|
462
|
+
});
|
|
463
|
+
};
|
|
464
|
+
server.once('error', onError);
|
|
465
|
+
server.once('listening', onListening);
|
|
466
|
+
server.listen(port, '127.0.0.1');
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
return {
|
|
471
|
+
server,
|
|
472
|
+
listen,
|
|
473
|
+
/** @internal test helpers */
|
|
474
|
+
_clients: clients,
|
|
475
|
+
_noteChange: noteChange,
|
|
476
|
+
_flushPending: flushPending,
|
|
477
|
+
_broadcast: broadcast,
|
|
478
|
+
_fileHashes: fileHashes,
|
|
479
|
+
_seedHashes: seedHashes,
|
|
480
|
+
_hasContentChanged: hasContentChanged,
|
|
481
|
+
outAbs,
|
|
482
|
+
outRel: outResolved.rel,
|
|
483
|
+
};
|
|
484
|
+
}
|