@stagepass/cli 2.2.6 → 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.
Files changed (50) hide show
  1. package/README.md +61 -13
  2. package/TESTING-macos.md +35 -8
  3. package/bin/index.js +4 -1
  4. package/package.json +9 -8
  5. package/src/cli.js +62 -7
  6. package/src/commands/certs.js +375 -19
  7. package/src/commands/daemon.js +75 -7
  8. package/src/commands/dev.js +419 -0
  9. package/src/commands/link.js +66 -25
  10. package/src/commands/new.js +397 -41
  11. package/src/commands/npm-run.js +8 -0
  12. package/src/commands/reload.js +2 -2
  13. package/src/commands/setup.js +5 -5
  14. package/src/commands/start.js +386 -83
  15. package/src/commands/stop.js +50 -31
  16. package/src/commands/unlink.js +8 -6
  17. package/src/commands/upgrade.js +51 -12
  18. package/src/lib/apply-site-block.js +48 -0
  19. package/src/lib/autostart.js +300 -3
  20. package/src/lib/caddyfile.js +72 -13
  21. package/src/lib/cdn-snippets.js +145 -3
  22. package/src/lib/certs.js +334 -47
  23. package/src/lib/dev-port.js +45 -0
  24. package/src/lib/doctor-site.js +61 -5
  25. package/src/lib/doctor.js +48 -4
  26. package/src/lib/ensure-running.js +89 -0
  27. package/src/lib/exec.js +72 -24
  28. package/src/lib/live-server.js +484 -0
  29. package/src/lib/node-engine.js +55 -0
  30. package/src/lib/notify.js +62 -0
  31. package/src/lib/origins.js +27 -5
  32. package/src/lib/package-versions.js +9 -0
  33. package/src/lib/paths.js +18 -0
  34. package/src/lib/php-fpm.js +33 -0
  35. package/src/lib/project-sync.js +165 -20
  36. package/src/lib/projects.js +137 -7
  37. package/src/lib/prompts.js +19 -0
  38. package/src/lib/registry.js +27 -6
  39. package/src/lib/scaffold.js +288 -11
  40. package/src/lib/site-detect.js +78 -25
  41. package/src/lib/snippets.js +14 -11
  42. package/src/lib/spinner.js +60 -0
  43. package/src/lib/versions.js +20 -8
  44. package/templates/project/AGENTS.md.tmpl +4 -3
  45. package/templates/project/README.md.tmpl +35 -6
  46. package/templates/project/api/README.md.tmpl +7 -0
  47. package/templates/project/examples/php/README.md.tmpl +18 -0
  48. package/templates/project/examples/php/form.php +105 -0
  49. package/templates/project/examples/php/proxy.php +171 -0
  50. package/templates/project/scripts/build.mjs +200 -37
@@ -12,6 +12,9 @@ import {
12
12
  } from './paths.js';
13
13
  import { defaultExec, resolveCommand } from './exec.js';
14
14
 
15
+ /** Default PATH used by macOS user LaunchAgents (no Homebrew). */
16
+ export const LAUNCHD_MINIMAL_PATH = '/usr/bin:/bin:/usr/sbin:/sbin';
17
+
15
18
  /**
16
19
  * Escape a string for use inside an XML plist text node.
17
20
  * @param {string} value
@@ -25,6 +28,33 @@ export function escapeXml(value) {
25
28
  .replace(/'/g, ''');
26
29
  }
27
30
 
31
+ /**
32
+ * Build LaunchAgent PATH: validated Homebrew bin/sbin + launchd minimal dirs.
33
+ * Does not inherit the interactive user environment.
34
+ * @param {string} brewPrefix Absolute Homebrew prefix (`brew --prefix`)
35
+ * @returns {string}
36
+ */
37
+ export function buildAutostartPathEnv(brewPrefix) {
38
+ if (typeof brewPrefix !== 'string' || brewPrefix.length === 0) {
39
+ throw new Error('brewPrefix is required');
40
+ }
41
+ if (!path.isAbsolute(brewPrefix)) {
42
+ throw new Error(`brewPrefix must be absolute (got: ${brewPrefix})`);
43
+ }
44
+ if (/[\r\n\0]/.test(brewPrefix)) {
45
+ throw new Error('brewPrefix must not contain control characters');
46
+ }
47
+ // `:` would split PATH entries; reject before embedding.
48
+ if (brewPrefix.includes(path.delimiter)) {
49
+ throw new Error(
50
+ `brewPrefix must not contain PATH delimiter (${path.delimiter})`
51
+ );
52
+ }
53
+ const bin = path.join(brewPrefix, 'bin');
54
+ const sbin = path.join(brewPrefix, 'sbin');
55
+ return `${bin}${path.delimiter}${sbin}${path.delimiter}${LAUNCHD_MINIMAL_PATH}`;
56
+ }
57
+
28
58
  /**
29
59
  * Build LaunchAgent ProgramArguments for `stagepass daemon`.
30
60
  * @param {{ nodePath: string, cliPath: string }} paths
@@ -64,6 +94,17 @@ export function buildLaunchctlPrintArgs(uid, label = LAUNCH_AGENT_LABEL) {
64
94
  return ['print', `gui/${uid}/${label}`];
65
95
  }
66
96
 
97
+ /**
98
+ * launchctl kickstart arguments (gui domain).
99
+ * `-k` kills any existing instance before starting.
100
+ * @param {number|string} uid
101
+ * @param {string} [label]
102
+ * @returns {string[]}
103
+ */
104
+ export function buildLaunchctlKickstartArgs(uid, label = LAUNCH_AGENT_LABEL) {
105
+ return ['kickstart', '-k', `gui/${uid}/${label}`];
106
+ }
107
+
67
108
  /**
68
109
  * Render a LaunchAgent plist that runs `stagepass daemon` at login.
69
110
  *
@@ -72,9 +113,13 @@ export function buildLaunchctlPrintArgs(uid, label = LAUNCH_AGENT_LABEL) {
72
113
  * same bind privileges as interactive `start` on macOS. If bind fails at
73
114
  * runtime, `daemon` logs a clear error and exits 0 so KeepAlive does not loop.
74
115
  *
116
+ * `pathEnv` is required so launchd (minimal PATH) can still resolve Homebrew
117
+ * `brew` / `caddy` by bare name without inheriting the interactive user env.
118
+ *
75
119
  * @param {object} opts
76
120
  * @param {string} opts.nodePath
77
121
  * @param {string} opts.cliPath
122
+ * @param {string} opts.pathEnv Validated PATH for EnvironmentVariables
78
123
  * @param {string} [opts.label]
79
124
  * @param {string} [opts.stdoutPath]
80
125
  * @param {string} [opts.stderrPath]
@@ -89,6 +134,13 @@ export function renderLaunchAgentPlist(opts) {
89
134
  const stdoutPath = opts.stdoutPath || getDaemonStdoutLogPath();
90
135
  const stderrPath = opts.stderrPath || getDaemonStderrLogPath();
91
136
  const workingDirectory = opts.workingDirectory || os.homedir();
137
+ const pathEnv = opts.pathEnv;
138
+ if (typeof pathEnv !== 'string' || pathEnv.length === 0) {
139
+ throw new Error('pathEnv is required for LaunchAgent EnvironmentVariables');
140
+ }
141
+ if (/[\r\n\0]/.test(pathEnv)) {
142
+ throw new Error('pathEnv must not contain control characters');
143
+ }
92
144
 
93
145
  const argXml = programArguments
94
146
  .map((a) => `\t\t<string>${escapeXml(a)}</string>`)
@@ -106,6 +158,11 @@ ${argXml}
106
158
  \t</array>
107
159
  \t<key>WorkingDirectory</key>
108
160
  \t<string>${escapeXml(workingDirectory)}</string>
161
+ \t<key>EnvironmentVariables</key>
162
+ \t<dict>
163
+ \t\t<key>PATH</key>
164
+ \t\t<string>${escapeXml(pathEnv)}</string>
165
+ \t</dict>
109
166
  \t<key>RunAtLoad</key>
110
167
  \t<true/>
111
168
  \t<key>KeepAlive</key>
@@ -220,6 +277,228 @@ export async function resolveAutostartPaths(opts = {}) {
220
277
  return { ok: true, nodePath, cliPath: cliCheck.path, error: null };
221
278
  }
222
279
 
280
+ /**
281
+ * True when `absolutePath` is the Homebrew prefix or a path beneath it.
282
+ * @param {string} absolutePath
283
+ * @param {string} brewPrefix
284
+ */
285
+ function isPathUnderPrefix(absolutePath, brewPrefix) {
286
+ return (
287
+ absolutePath === brewPrefix ||
288
+ absolutePath.startsWith(`${brewPrefix}${path.sep}`)
289
+ );
290
+ }
291
+
292
+ /**
293
+ * Validate a tool as launchd will see it: the PATH shim must live in
294
+ * `prefix/bin` or `prefix/sbin`. The realpath target may be under Cellar
295
+ * (normal Homebrew layout) but must remain under the same prefix, be a
296
+ * regular file, and be executable.
297
+ *
298
+ * @param {object} opts
299
+ * @param {string} opts.name
300
+ * @param {string} opts.shimPath Absolute path returned by `which` / PATH lookup
301
+ * @param {string} opts.brewPrefix
302
+ * @param {(p: string) => Promise<string>} opts.realpath
303
+ * @param {(p: string) => Promise<boolean>} opts.pathExists
304
+ * @param {(p: string) => Promise<import('node:fs').Stats>} opts.stat
305
+ * @returns {Promise<{ ok: true, path: string, canonicalPath: string } | { ok: false, error: string }>}
306
+ */
307
+ async function validatePrefixPathTool(opts) {
308
+ const { name, shimPath, brewPrefix, realpath, pathExists, stat } = opts;
309
+ const shimCheck = await requireAbsoluteExistingPath(shimPath, name, pathExists);
310
+ if (!shimCheck.ok) return shimCheck;
311
+
312
+ const prefixBin = path.join(brewPrefix, 'bin');
313
+ const prefixSbin = path.join(brewPrefix, 'sbin');
314
+ const shimDir = path.dirname(shimCheck.path);
315
+ if (shimDir !== prefixBin && shimDir !== prefixSbin) {
316
+ return {
317
+ ok: false,
318
+ error: `${name} PATH entry must be in ${prefixBin} or ${prefixSbin} (got ${shimDir}).`,
319
+ };
320
+ }
321
+
322
+ let canonicalPath;
323
+ try {
324
+ canonicalPath = await realpath(shimCheck.path);
325
+ } catch (error) {
326
+ return {
327
+ ok: false,
328
+ error: `Could not realpath ${name} at ${shimCheck.path}: ${
329
+ error instanceof Error ? error.message : String(error)
330
+ }`,
331
+ };
332
+ }
333
+
334
+ if (!isPathUnderPrefix(canonicalPath, brewPrefix)) {
335
+ return {
336
+ ok: false,
337
+ error: `${name} realpath (${canonicalPath}) is not under brew --prefix (${brewPrefix}).`,
338
+ };
339
+ }
340
+
341
+ let st;
342
+ try {
343
+ st = await stat(canonicalPath);
344
+ } catch (error) {
345
+ return {
346
+ ok: false,
347
+ error: `Could not stat ${name} at ${canonicalPath}: ${
348
+ error instanceof Error ? error.message : String(error)
349
+ }`,
350
+ };
351
+ }
352
+ if (!st.isFile()) {
353
+ return {
354
+ ok: false,
355
+ error: `${name} resolves to a non-file: ${canonicalPath}`,
356
+ };
357
+ }
358
+ if (!(st.mode & 0o111)) {
359
+ return {
360
+ ok: false,
361
+ error: `${name} is not executable: ${canonicalPath}`,
362
+ };
363
+ }
364
+
365
+ return { ok: true, path: shimCheck.path, canonicalPath };
366
+ }
367
+
368
+ /**
369
+ * Resolve Homebrew + Caddy for the LaunchAgent runtime environment.
370
+ * Uses the interactive enable-time PATH to locate tools, then records a
371
+ * launchd-safe PATH from the validated `brew --prefix` (Apple Silicon
372
+ * `/opt/homebrew` or Intel `/usr/local` via brew itself — not hardcoded).
373
+ *
374
+ * PATH shims must sit in `prefix/bin` or `prefix/sbin`. Realpaths may point
375
+ * into `Cellar/...` (standard Homebrew) as long as they stay under the prefix.
376
+ *
377
+ * @param {object} [opts]
378
+ * @param {import('./exec.js').ExecFn} [opts.exec]
379
+ * @param {(p: string) => Promise<string>} [opts.realpath]
380
+ * @param {(p: string) => Promise<boolean>} [opts.pathExists]
381
+ * @param {(p: string) => Promise<import('node:fs').Stats>} [opts.stat]
382
+ * @returns {Promise<{
383
+ * ok: boolean,
384
+ * error?: string,
385
+ * brewPath?: string,
386
+ * caddyPath?: string,
387
+ * brewPrefix?: string,
388
+ * pathEnv?: string,
389
+ * }>}
390
+ */
391
+ export async function resolveAutostartRuntimeEnvironment(opts = {}) {
392
+ const exec = opts.exec || defaultExec;
393
+ const realpath =
394
+ opts.realpath || ((p) => fs.realpath(p).then((r) => String(r)));
395
+ const pathExists = opts.pathExists || ((p) => fs.pathExists(p));
396
+ const stat = opts.stat || ((p) => fs.stat(p));
397
+
398
+ const brewWhich = await resolveCommand('brew', exec);
399
+ if (!brewWhich) {
400
+ return {
401
+ ok: false,
402
+ error:
403
+ 'Homebrew `brew` not found. Install Homebrew and ensure it is on PATH before enabling autostart.',
404
+ };
405
+ }
406
+ const brewShim = path.resolve(brewWhich);
407
+ const brewShimCheck = await requireAbsoluteExistingPath(
408
+ brewShim,
409
+ 'brew',
410
+ pathExists
411
+ );
412
+ if (!brewShimCheck.ok) {
413
+ return { ok: false, error: brewShimCheck.error };
414
+ }
415
+
416
+ let brewPrefix = '';
417
+ try {
418
+ // Invoke via the PATH shim (not Cellar realpath) — matches user `brew --prefix`.
419
+ const { stdout } = await exec(brewShimCheck.path, ['--prefix']);
420
+ brewPrefix = String(stdout || '').trim();
421
+ } catch (error) {
422
+ return {
423
+ ok: false,
424
+ error: `Could not read Homebrew prefix via brew --prefix: ${
425
+ error instanceof Error ? error.message : String(error)
426
+ }`,
427
+ };
428
+ }
429
+
430
+ if (!brewPrefix || !path.isAbsolute(brewPrefix) || /[\r\n\0]/.test(brewPrefix)) {
431
+ return {
432
+ ok: false,
433
+ error: `Invalid Homebrew prefix from brew --prefix: ${brewPrefix || '(empty)'}`,
434
+ };
435
+ }
436
+ if (brewPrefix.includes(path.delimiter)) {
437
+ return {
438
+ ok: false,
439
+ error: `Homebrew prefix contains PATH delimiter: ${brewPrefix}`,
440
+ };
441
+ }
442
+
443
+ const prefixBin = path.join(brewPrefix, 'bin');
444
+ if (!(await pathExists(prefixBin))) {
445
+ return {
446
+ ok: false,
447
+ error: `Homebrew prefix bin directory does not exist: ${prefixBin}`,
448
+ };
449
+ }
450
+
451
+ const brewTool = await validatePrefixPathTool({
452
+ name: 'brew',
453
+ shimPath: brewShimCheck.path,
454
+ brewPrefix,
455
+ realpath,
456
+ pathExists,
457
+ stat,
458
+ });
459
+ if (!brewTool.ok) {
460
+ return { ok: false, error: brewTool.error };
461
+ }
462
+
463
+ const caddyWhich = await resolveCommand('caddy', exec);
464
+ if (!caddyWhich) {
465
+ return {
466
+ ok: false,
467
+ error:
468
+ 'Caddy not found. Run `stagepass setup` (or `brew install caddy`) before enabling autostart.',
469
+ };
470
+ }
471
+ const caddyTool = await validatePrefixPathTool({
472
+ name: 'caddy',
473
+ shimPath: path.resolve(caddyWhich),
474
+ brewPrefix,
475
+ realpath,
476
+ pathExists,
477
+ stat,
478
+ });
479
+ if (!caddyTool.ok) {
480
+ return { ok: false, error: caddyTool.error };
481
+ }
482
+
483
+ let pathEnv;
484
+ try {
485
+ pathEnv = buildAutostartPathEnv(brewPrefix);
486
+ } catch (error) {
487
+ return {
488
+ ok: false,
489
+ error: error instanceof Error ? error.message : String(error),
490
+ };
491
+ }
492
+
493
+ return {
494
+ ok: true,
495
+ brewPath: brewTool.path,
496
+ caddyPath: caddyTool.path,
497
+ brewPrefix,
498
+ pathEnv,
499
+ };
500
+ }
501
+
223
502
  /**
224
503
  * @param {object} [opts]
225
504
  * @param {import('./exec.js').ExecFn} [opts.exec]
@@ -264,6 +543,7 @@ export async function getAutostartStatus(opts = {}) {
264
543
  export async function enableAutostart(opts = {}) {
265
544
  const exec = opts.exec || defaultExec;
266
545
  const uid = opts.uid ?? process.getuid?.() ?? os.userInfo().uid;
546
+ const pathExists = opts.pathExists || ((p) => fs.pathExists(p));
267
547
  const paths =
268
548
  opts.paths ||
269
549
  (await resolveAutostartPaths({
@@ -271,7 +551,7 @@ export async function enableAutostart(opts = {}) {
271
551
  argv1: opts.argv1,
272
552
  exec,
273
553
  realpath: opts.realpath,
274
- pathExists: opts.pathExists,
554
+ pathExists,
275
555
  }));
276
556
 
277
557
  if (!paths.ok) {
@@ -285,7 +565,6 @@ export async function enableAutostart(opts = {}) {
285
565
  error: 'Autostart nodePath and cliPath must be absolute.',
286
566
  };
287
567
  }
288
- const pathExists = opts.pathExists || ((p) => fs.pathExists(p));
289
568
  if (!(await pathExists(paths.nodePath)) || !(await pathExists(paths.cliPath))) {
290
569
  return {
291
570
  ok: false,
@@ -293,18 +572,36 @@ export async function enableAutostart(opts = {}) {
293
572
  };
294
573
  }
295
574
 
575
+ const runtime =
576
+ opts.runtime ||
577
+ (await resolveAutostartRuntimeEnvironment({
578
+ exec,
579
+ realpath: opts.realpath,
580
+ pathExists,
581
+ }));
582
+ if (!runtime.ok || !runtime.pathEnv) {
583
+ return {
584
+ ok: false,
585
+ error:
586
+ runtime.error ||
587
+ 'Could not resolve Homebrew/Caddy paths for LaunchAgent PATH.',
588
+ };
589
+ }
590
+
296
591
  const plistPath = opts.plistPath || getLaunchAgentPlistPath();
297
592
  const agentsDir = path.dirname(plistPath);
298
593
  const ensureDir = opts.ensureDir || ((p) => fs.ensureDir(p));
299
594
  const writeFile = opts.writeFile || ((p, c) => fs.writeFile(p, c, 'utf8'));
300
595
  const logsDir = opts.logsDir || getLogsDir();
301
596
 
597
+ // Write only after node/cli + Homebrew/Caddy prerequisites validate.
302
598
  await ensureDir(agentsDir);
303
599
  await ensureDir(logsDir);
304
600
 
305
601
  const plist = renderLaunchAgentPlist({
306
602
  nodePath: paths.nodePath,
307
603
  cliPath: paths.cliPath,
604
+ pathEnv: runtime.pathEnv,
308
605
  stdoutPath: opts.stdoutPath || getDaemonStdoutLogPath(),
309
606
  stderrPath: opts.stderrPath || getDaemonStderrLogPath(),
310
607
  workingDirectory: opts.workingDirectory || os.homedir(),
@@ -330,7 +627,7 @@ export async function enableAutostart(opts = {}) {
330
627
  };
331
628
  }
332
629
 
333
- return { ok: true, plistPath, paths, error: null };
630
+ return { ok: true, plistPath, paths, runtime, error: null };
334
631
  }
335
632
 
336
633
  /**
@@ -1,6 +1,7 @@
1
1
  import { escapeRegExp } from './domain.js';
2
2
  import { escapeCaddyQuotedString, validateRoot } from './paths.js';
3
3
  import { buildOriginAllowlistRegex, validateOriginList } from './origins.js';
4
+ import { isValidDevPort, normalizeDevPort } from './dev-port.js';
4
5
 
5
6
  /** Marker written inside every Stagepass-managed site block. */
6
7
  export const BLOCK_VERSION = 'v2';
@@ -23,8 +24,20 @@ export const SENSITIVE_BLOCK_DOCS = Object.freeze({
23
24
  * @typedef {object} SiteBlockOptions
24
25
  * @property {boolean} [allowAllOrigins]
25
26
  * @property {string[]} [origins]
27
+ * @property {boolean} [php] When false, omit php_fastcgi. Missing/undefined keeps PHP on (2.x backcompat).
28
+ * @property {number|null|undefined} [devPort] Live-reload SSE reverse_proxy port (1024..65535), only while `stagepass dev` runs.
26
29
  */
27
30
 
31
+ /**
32
+ * Whether a site block should enable PHP FastCGI.
33
+ * Explicit false disables; everything else (including missing) keeps the legacy on behaviour.
34
+ * @param {boolean|undefined} php
35
+ * @returns {boolean}
36
+ */
37
+ export function isPhpEnabled(php) {
38
+ return php !== false;
39
+ }
40
+
28
41
  /**
29
42
  * @param {string} domain - normalized foo.sp
30
43
  * @param {string} root - absolute project path
@@ -43,9 +56,16 @@ export function renderSiteBlock(domain, root, options = {}) {
43
56
  throw new Error(originsResult.error);
44
57
  }
45
58
  const origins = originsResult.origins;
59
+ const php = isPhpEnabled(options.php);
60
+ const devPort = normalizeDevPort(options.devPort);
61
+ if (options.devPort != null && options.devPort !== '' && !devPort) {
62
+ throw new Error(
63
+ `Invalid devPort ${String(options.devPort)} (must be an integer 1024..65535).`
64
+ );
65
+ }
46
66
 
47
67
  const quotedRoot = `"${escapeCaddyQuotedString(rootResult.path)}"`;
48
- const optionsComment = formatOptionsComment({ allowAllOrigins, origins });
68
+ const optionsComment = formatOptionsComment({ allowAllOrigins, origins, php, devPort });
49
69
 
50
70
  const lines = [
51
71
  `# START: ${domain}`,
@@ -68,13 +88,16 @@ export function renderSiteBlock(domain, root, options = {}) {
68
88
  lines.push(...allowlistCorsLines(origins));
69
89
  }
70
90
 
71
- lines.push(
72
- '',
73
- ' handle {',
74
- ` root * ${quotedRoot}`,
75
- ' php_fastcgi 127.0.0.1:9000',
76
- ' file_server'
77
- );
91
+ // Live-reload SSE must be before file_server so the path is not served from disk.
92
+ if (devPort && isValidDevPort(devPort)) {
93
+ lines.push(...liveReloadHandleLines(devPort, allowAllOrigins));
94
+ }
95
+
96
+ lines.push('', ' handle {', ` root * ${quotedRoot}`);
97
+ if (php) {
98
+ lines.push(' php_fastcgi 127.0.0.1:9000');
99
+ }
100
+ lines.push(' file_server');
78
101
 
79
102
  if (allowAllOrigins) {
80
103
  lines.push(' header Access-Control-Allow-Origin *');
@@ -90,14 +113,45 @@ export function renderSiteBlock(domain, root, options = {}) {
90
113
  return lines.join('\n');
91
114
  }
92
115
 
93
- function formatOptionsComment({ allowAllOrigins, origins }) {
94
- const parts = [`allowAllOrigins=${allowAllOrigins ? 'true' : 'false'}`];
116
+ function formatOptionsComment({ allowAllOrigins, origins, php, devPort }) {
117
+ const parts = [
118
+ `allowAllOrigins=${allowAllOrigins ? 'true' : 'false'}`,
119
+ `php=${php ? 'true' : 'false'}`,
120
+ ];
95
121
  if (origins.length > 0) {
96
122
  parts.push(`origins=${origins.join(',')}`);
97
123
  }
124
+ if (devPort && isValidDevPort(devPort)) {
125
+ parts.push(`devPort=${devPort}`);
126
+ }
98
127
  return `# stagepass-options: ${parts.join(' ')}`;
99
128
  }
100
129
 
130
+ /**
131
+ * reverse_proxy for /__stagepass/live with the same CORS / LNA policy as assets.
132
+ * Port is validated before call; still interpolated only as a decimal integer.
133
+ * @param {number} port
134
+ * @param {boolean} allowAllOrigins
135
+ */
136
+ function liveReloadHandleLines(port, allowAllOrigins) {
137
+ const lines = [
138
+ ' handle /__stagepass/live {',
139
+ ' reverse_proxy 127.0.0.1:' + String(port) + ' {',
140
+ ' flush_interval -1',
141
+ ' }',
142
+ ];
143
+ if (allowAllOrigins) {
144
+ lines.push(' header Access-Control-Allow-Origin *');
145
+ } else {
146
+ lines.push(
147
+ ' header @cors_origin Access-Control-Allow-Origin "{http.request.header.Origin}"',
148
+ ' header @cors_origin Vary Origin'
149
+ );
150
+ }
151
+ lines.push(' }', '');
152
+ return lines;
153
+ }
154
+
101
155
  function allowAllCorsLines() {
102
156
  return [
103
157
  ' @options method OPTIONS',
@@ -169,11 +223,12 @@ export function parseBlocks(content) {
169
223
  * @param {string} blockText
170
224
  */
171
225
  export function parseOptionsFromBlock(blockText) {
172
- const defaults = { allowAllOrigins: false, origins: [] };
226
+ const defaults = { allowAllOrigins: false, origins: [], php: undefined, devPort: undefined };
173
227
  const line = blockText.match(/^# stagepass-options:\s*(.+)$/m);
174
228
  if (!line) {
175
229
  if (!/# stagepass-block:/m.test(blockText)) {
176
- return { allowAllOrigins: true, origins: [] };
230
+ // Legacy pre-marker blocks always had PHP.
231
+ return { allowAllOrigins: true, origins: [], php: true, devPort: undefined };
177
232
  }
178
233
  return defaults;
179
234
  }
@@ -181,13 +236,17 @@ export function parseOptionsFromBlock(blockText) {
181
236
  const text = line[1];
182
237
  const allowMatch = text.match(/allowAllOrigins=(true|false)/);
183
238
  const allowAllOrigins = allowMatch ? allowMatch[1] === 'true' : false;
239
+ const phpMatch = text.match(/(?:^|\s)php=(true|false)(?:\s|$)/);
240
+ const php = phpMatch ? phpMatch[1] === 'true' : undefined;
184
241
  const originsMatch = text.match(/origins=([^\s]+)/);
185
242
  let origins = [];
186
243
  if (originsMatch) {
187
244
  const list = validateOriginList(originsMatch[1].split(',').filter(Boolean));
188
245
  origins = list.ok ? list.origins : [];
189
246
  }
190
- return { allowAllOrigins, origins };
247
+ const devPortMatch = text.match(/(?:^|\s)devPort=(\d+)(?:\s|$)/);
248
+ const devPort = devPortMatch ? normalizeDevPort(Number(devPortMatch[1])) : undefined;
249
+ return { allowAllOrigins, origins, php, devPort: devPort || undefined };
191
250
  }
192
251
 
193
252
  /**