@stagepass/cli 1.0.1 → 2.1.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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +216 -0
  3. package/TESTING-macos.md +58 -0
  4. package/bin/index.js +2 -76
  5. package/package.json +10 -4
  6. package/src/cli.js +320 -0
  7. package/src/commands/autostart.js +85 -0
  8. package/src/commands/certs.js +185 -0
  9. package/src/commands/daemon.js +126 -0
  10. package/src/commands/doctor.js +56 -0
  11. package/src/commands/link.js +145 -57
  12. package/src/commands/new.js +368 -0
  13. package/src/commands/npm-run.js +84 -0
  14. package/src/commands/reload.js +14 -11
  15. package/src/commands/start.js +21 -4
  16. package/src/commands/stop.js +15 -0
  17. package/src/commands/unlink.js +17 -30
  18. package/src/commands/upgrade.js +198 -0
  19. package/src/lib/autostart.js +360 -0
  20. package/src/lib/caddyfile.js +338 -0
  21. package/src/lib/cdn-snippets.js +27 -0
  22. package/src/lib/certs.js +476 -0
  23. package/src/lib/doctor.js +503 -0
  24. package/src/lib/domain.js +125 -0
  25. package/src/lib/exec.js +71 -0
  26. package/src/lib/migrate.js +96 -0
  27. package/src/lib/origins.js +160 -0
  28. package/src/lib/paths.js +132 -0
  29. package/src/lib/platform.js +47 -0
  30. package/src/lib/project-name.js +47 -0
  31. package/src/lib/projects.js +181 -0
  32. package/src/lib/remote-url.js +63 -0
  33. package/src/lib/scaffold.js +186 -0
  34. package/src/lib/snippets.js +83 -0
  35. package/src/lib/spawn.js +30 -0
  36. package/templates/project/AGENTS.md.tmpl +37 -0
  37. package/templates/project/README.md.tmpl +44 -0
  38. package/templates/project/jsconfig.json.tmpl +14 -0
  39. package/templates/project/scripts/build.mjs +110 -0
  40. package/templates/project/src/main.js.tmpl +29 -0
  41. package/templates/project/src/main.ts.tmpl +29 -0
  42. package/templates/project/src/styles.css.tmpl +8 -0
  43. package/templates/project/src/styles.scss.tmpl +8 -0
  44. package/templates/project/stagepass.json.tmpl +8 -0
  45. package/templates/project/tsconfig.json.tmpl +13 -0
  46. package/src/commands/__tests__/link.test.js +0 -113
  47. package/src/commands/__tests__/reload.test.js +0 -72
  48. package/src/commands/__tests__/unlink.test.js +0 -90
@@ -0,0 +1,368 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'node:path';
3
+ import readline from 'node:readline/promises';
4
+ import { stdin as input, stdout as output } from 'node:process';
5
+ import chalk from 'chalk';
6
+ import { createRequire } from 'module';
7
+ import { defaultExec } from '../lib/exec.js';
8
+ import { defaultSpawn } from '../lib/spawn.js';
9
+ import { validateProjectName } from '../lib/project-name.js';
10
+ import { validateGitRemote } from '../lib/remote-url.js';
11
+ import {
12
+ defaultTemplatesRoot,
13
+ planScaffoldFiles,
14
+ findConflicts,
15
+ } from '../lib/scaffold.js';
16
+ import {
17
+ buildWebflowSnippets,
18
+ printWebflowSnippets,
19
+ } from '../lib/snippets.js';
20
+
21
+ const require = createRequire(import.meta.url);
22
+ const { version: cliVersion } = require('../../package.json');
23
+
24
+ /**
25
+ * Resolve a boolean flag that may appear as --foo / --no-foo.
26
+ * Only argv is trusted: Commander defaults negated pairs to true, which would
27
+ * break defaults like --install (off unless passed).
28
+ *
29
+ * @param {object} _options
30
+ * @param {string} key
31
+ * @param {string[]} argv
32
+ * @param {boolean|undefined} defaultValue undefined = still unset
33
+ */
34
+ export function resolveBoolFlag(_options, key, argv, defaultValue) {
35
+ const pos = `--${key}`;
36
+ const neg = `--no-${key}`;
37
+ if (argv.includes(neg)) return false;
38
+ if (argv.includes(pos)) return true;
39
+ return defaultValue;
40
+ }
41
+
42
+ /**
43
+ * @param {object} options Commander options
44
+ * @param {object} [deps]
45
+ */
46
+ async function resolveAuthor(options, deps) {
47
+ if (options.author != null && String(options.author).trim() !== '') {
48
+ return String(options.author).trim();
49
+ }
50
+ const exec = deps.exec || defaultExec;
51
+ try {
52
+ const { stdout } = await exec('git', ['config', 'user.name']);
53
+ return String(stdout || '').trim();
54
+ } catch {
55
+ return '';
56
+ }
57
+ }
58
+
59
+ /**
60
+ * @param {import('node:readline/promises').Interface} rl
61
+ * @param {string} question
62
+ * @param {string} [defaultValue]
63
+ */
64
+ async function ask(rl, question, defaultValue = '') {
65
+ const suffix = defaultValue ? ` (${defaultValue})` : '';
66
+ const answer = await rl.question(`${question}${suffix}: `);
67
+ const trimmed = String(answer || '').trim();
68
+ return trimmed === '' ? defaultValue : trimmed;
69
+ }
70
+
71
+ /**
72
+ * @param {import('node:readline/promises').Interface} rl
73
+ * @param {string} question
74
+ * @param {boolean} defaultYes
75
+ */
76
+ async function askYesNo(rl, question, defaultYes) {
77
+ const hint = defaultYes ? 'Y/n' : 'y/N';
78
+ const answer = await rl.question(`${question} (${hint}): `);
79
+ const trimmed = String(answer || '').trim().toLowerCase();
80
+ if (trimmed === '') return defaultYes;
81
+ if (['y', 'yes'].includes(trimmed)) return true;
82
+ if (['n', 'no'].includes(trimmed)) return false;
83
+ return defaultYes;
84
+ }
85
+
86
+ /**
87
+ * Merge flags + optional interactive prompts into a resolved config.
88
+ * @param {string|undefined} nameArg
89
+ * @param {object} options
90
+ * @param {object} deps
91
+ */
92
+ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
93
+ const isTty =
94
+ deps.isTTY != null ? Boolean(deps.isTTY) : Boolean(input.isTTY);
95
+ const interactive = isTty && options.yes !== true;
96
+ const authorDefault = await resolveAuthor(options, deps);
97
+ const argv = Array.isArray(deps.argv) ? deps.argv : process.argv;
98
+
99
+ /** @type {string} */
100
+ let name = nameArg ? String(nameArg).trim() : '';
101
+ /** @type {string} */
102
+ let dir = options.dir != null ? String(options.dir) : '';
103
+ let lang = options.lang === 'js' || options.lang === 'ts' ? options.lang : '';
104
+ let styles =
105
+ options.styles === 'css' || options.styles === 'scss' ? options.styles : '';
106
+
107
+ // Prefer argv for --foo / --no-foo so Commander default quirks do not flip defaults.
108
+ let modules = resolveBoolFlag(options, 'modules', argv, undefined);
109
+ let git = resolveBoolFlag(options, 'git', argv, undefined);
110
+ let install = resolveBoolFlag(options, 'install', argv, undefined);
111
+ let remote = options.remote != null ? String(options.remote).trim() : '';
112
+
113
+ if (interactive) {
114
+ const rl =
115
+ deps.createReadline?.() ||
116
+ readline.createInterface({ input, output });
117
+ try {
118
+ if (!name) {
119
+ name = await ask(rl, 'Project name (DNS-safe)');
120
+ }
121
+ if (!dir) {
122
+ dir = await ask(rl, 'Directory', name || '.');
123
+ }
124
+ if (!options.author) {
125
+ const nextAuthor = await ask(rl, 'Author', authorDefault);
126
+ options = { ...options, author: nextAuthor };
127
+ }
128
+ if (!lang) {
129
+ const raw = await ask(rl, 'Language (ts|js)', 'ts');
130
+ lang = raw === 'js' ? 'js' : 'ts';
131
+ }
132
+ if (!styles) {
133
+ const raw = await ask(rl, 'Styles (scss|css)', 'scss');
134
+ styles = raw === 'css' ? 'css' : 'scss';
135
+ }
136
+ if (modules === undefined) {
137
+ modules = await askYesNo(rl, 'Include @stagepass/modules?', true);
138
+ }
139
+ if (git === undefined) {
140
+ git = await askYesNo(rl, 'Initialize git repository?', true);
141
+ }
142
+ if (git && !remote) {
143
+ remote = await ask(rl, 'Git remote URL (optional)', '');
144
+ }
145
+ if (install === undefined) {
146
+ install = await askYesNo(rl, 'Run npm install now?', false);
147
+ }
148
+ } finally {
149
+ rl.close();
150
+ }
151
+ }
152
+
153
+ // Non-interactive / --yes defaults
154
+ if (!name) {
155
+ return { ok: false, error: 'Project name is required (pass [name] or use a TTY).' };
156
+ }
157
+ const nameCheck = validateProjectName(name);
158
+ if (!nameCheck.ok) {
159
+ return { ok: false, error: nameCheck.error };
160
+ }
161
+ name = nameCheck.name;
162
+
163
+ if (!dir) dir = name;
164
+ if (!lang) lang = 'ts';
165
+ if (!styles) styles = 'scss';
166
+ if (modules === undefined) modules = true;
167
+ if (git === undefined) git = true;
168
+ if (install === undefined) install = false;
169
+
170
+ if (lang !== 'ts' && lang !== 'js') {
171
+ return { ok: false, error: 'Language must be ts or js.' };
172
+ }
173
+ if (styles !== 'scss' && styles !== 'css') {
174
+ return { ok: false, error: 'Styles must be scss or css.' };
175
+ }
176
+
177
+ const remoteCheck = validateGitRemote(remote);
178
+ if (!remoteCheck.ok) {
179
+ return { ok: false, error: remoteCheck.error };
180
+ }
181
+ if (remoteCheck.remote && !git) {
182
+ return {
183
+ ok: false,
184
+ error: 'A git remote requires git init. Pass --git or omit --no-git.',
185
+ };
186
+ }
187
+
188
+ const author =
189
+ options.author != null && String(options.author).trim() !== ''
190
+ ? String(options.author).trim()
191
+ : authorDefault;
192
+
193
+ return {
194
+ ok: true,
195
+ config: {
196
+ name,
197
+ dir,
198
+ author,
199
+ lang,
200
+ styles,
201
+ modules,
202
+ git,
203
+ remote: remoteCheck.remote,
204
+ install,
205
+ dryRun: options.dryRun === true,
206
+ loaderVersion: deps.cliVersion || cliVersion,
207
+ },
208
+ };
209
+ }
210
+
211
+ /**
212
+ * Scaffold a new Stagepass project.
213
+ *
214
+ * @param {string|undefined} nameArg
215
+ * @param {object} [options]
216
+ * @param {object} [deps]
217
+ * @returns {Promise<number>} exit code
218
+ */
219
+ export async function createNew(nameArg, options = {}, deps = {}) {
220
+ const fse = deps.fs || fs;
221
+ const exec = deps.exec || defaultExec;
222
+ const spawn = deps.spawn || defaultSpawn;
223
+ const log = deps.log || console.log;
224
+ const error = deps.error || console.error;
225
+ const cwd = deps.cwd || process.cwd();
226
+ const templatesRoot = deps.templatesRoot || defaultTemplatesRoot();
227
+
228
+ const resolved = await resolveNewOptions(nameArg, options, deps);
229
+ if (!resolved.ok) {
230
+ error(chalk.red(resolved.error));
231
+ return 1;
232
+ }
233
+
234
+ const config = resolved.config;
235
+ const targetDir = path.isAbsolute(config.dir)
236
+ ? config.dir
237
+ : path.resolve(cwd, config.dir);
238
+
239
+ const templatesRootResolved = path.resolve(templatesRoot);
240
+ const readTemplate = async (rel) => {
241
+ const abs = path.resolve(templatesRootResolved, rel);
242
+ const relToRoot = path.relative(templatesRootResolved, abs);
243
+ if (
244
+ relToRoot.startsWith('..') ||
245
+ path.isAbsolute(relToRoot) ||
246
+ relToRoot.split(path.sep).includes('..')
247
+ ) {
248
+ throw new Error(`Template path escapes templates root: ${rel}`);
249
+ }
250
+ return fse.readFile(abs, 'utf8');
251
+ };
252
+
253
+ let files;
254
+ try {
255
+ files = await planScaffoldFiles(config, { readTemplate });
256
+ } catch (err) {
257
+ error(chalk.red(err instanceof Error ? err.message : String(err)));
258
+ return 1;
259
+ }
260
+
261
+ for (const file of files) {
262
+ const rel = String(file.relativePath || '');
263
+ if (
264
+ !rel ||
265
+ path.isAbsolute(rel) ||
266
+ rel.split(/[\\/]/).includes('..')
267
+ ) {
268
+ error(chalk.red(`Refusing unsafe output path: ${rel || '(empty)'}`));
269
+ return 1;
270
+ }
271
+ }
272
+
273
+ const conflicts = await findConflicts(targetDir, files, fse);
274
+ if (conflicts.length > 0) {
275
+ error(chalk.red('Refusing to overwrite existing files:'));
276
+ for (const rel of conflicts) {
277
+ error(` ${rel}`);
278
+ }
279
+ return 1;
280
+ }
281
+
282
+ if (config.dryRun) {
283
+ log(chalk.bold(`Dry run: would create project in ${targetDir}`));
284
+ for (const file of files) {
285
+ log(` ${file.relativePath}`);
286
+ }
287
+ if (config.git) log(' (git init)');
288
+ if (config.remote) log(` (git remote add origin ${config.remote})`);
289
+ if (config.install) log(' (npm install)');
290
+ return 0;
291
+ }
292
+
293
+ await fse.ensureDir(targetDir);
294
+
295
+ for (const file of files) {
296
+ const abs = path.resolve(targetDir, file.relativePath);
297
+ const relToTarget = path.relative(targetDir, abs);
298
+ if (
299
+ relToTarget.startsWith('..') ||
300
+ path.isAbsolute(relToTarget) ||
301
+ relToTarget.split(path.sep).includes('..')
302
+ ) {
303
+ error(chalk.red(`Refusing to write outside project directory: ${file.relativePath}`));
304
+ return 1;
305
+ }
306
+ await fse.ensureDir(path.dirname(abs));
307
+ await fse.writeFile(abs, file.contents, 'utf8');
308
+ }
309
+
310
+ if (config.git) {
311
+ try {
312
+ await exec('git', ['init'], { cwd: targetDir });
313
+ if (config.remote) {
314
+ await exec('git', ['remote', 'add', 'origin', config.remote], {
315
+ cwd: targetDir,
316
+ });
317
+ }
318
+ } catch (err) {
319
+ error(
320
+ chalk.red(
321
+ `Git setup failed: ${err instanceof Error ? err.message : String(err)}`
322
+ )
323
+ );
324
+ return 1;
325
+ }
326
+ }
327
+
328
+ if (config.install) {
329
+ try {
330
+ const result = await spawn('npm', ['install'], {
331
+ cwd: targetDir,
332
+ stdio: 'inherit',
333
+ shell: false,
334
+ env: process.env,
335
+ });
336
+ if (result.code !== 0) {
337
+ error(chalk.red(`npm install exited with code ${result.code}`));
338
+ return typeof result.code === 'number' ? result.code : 1;
339
+ }
340
+ } catch (err) {
341
+ error(
342
+ chalk.red(
343
+ `npm install failed: ${err instanceof Error ? err.message : String(err)}`
344
+ )
345
+ );
346
+ return 1;
347
+ }
348
+ }
349
+
350
+ log(chalk.green(`Created Stagepass project at ${targetDir}`));
351
+ log(chalk.dim('Next:'));
352
+ if (!config.install) {
353
+ log(` cd ${path.relative(cwd, targetDir) || '.'} && npm install`);
354
+ }
355
+ log(' npm run build');
356
+ log(` stagepass link ${config.name} --origin my-project.webflow.io`);
357
+
358
+ const snippets = buildWebflowSnippets({
359
+ version: config.loaderVersion,
360
+ modules: config.modules,
361
+ });
362
+ printWebflowSnippets(snippets, log);
363
+
364
+ return 0;
365
+ }
366
+
367
+ /** Commander-facing alias */
368
+ export const newProject = createNew;
@@ -0,0 +1,84 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'path';
3
+ import chalk from 'chalk';
4
+ import { defaultSpawn } from '../lib/spawn.js';
5
+
6
+ /**
7
+ * Run an npm lifecycle script in cwd via spawn (no shell).
8
+ *
9
+ * @param {string} scriptName
10
+ * @param {object} [options]
11
+ * @param {boolean} [options.verbose]
12
+ * @param {object} [deps]
13
+ * @param {typeof fs} [deps.fs]
14
+ * @param {string} [deps.cwd]
15
+ * @param {import('../lib/spawn.js').SpawnFn} [deps.spawn]
16
+ * @param {(msg?: string) => void} [deps.log]
17
+ * @param {(msg?: string) => void} [deps.error]
18
+ * @returns {Promise<number>} exit code
19
+ */
20
+ export async function runNpmScript(scriptName, options = {}, deps = {}) {
21
+ const fse = deps.fs || fs;
22
+ const cwd = deps.cwd || process.cwd();
23
+ const spawn = deps.spawn || defaultSpawn;
24
+ const log = deps.log || console.log;
25
+ const error = deps.error || console.error;
26
+ const pkgPath = path.join(cwd, 'package.json');
27
+
28
+ if (!(await fse.pathExists(pkgPath))) {
29
+ error(chalk.red('No package.json found in the current directory.'));
30
+ return 1;
31
+ }
32
+
33
+ let pkg;
34
+ try {
35
+ pkg = JSON.parse(await fse.readFile(pkgPath, 'utf8'));
36
+ } catch {
37
+ error(chalk.red('package.json is not valid JSON.'));
38
+ return 1;
39
+ }
40
+
41
+ if (!pkg.scripts || typeof pkg.scripts[scriptName] !== 'string') {
42
+ error(
43
+ chalk.red(
44
+ `No "${scriptName}" script in package.json. Add one, or run this command inside a Stagepass project created with \`stagepass new\`.`
45
+ )
46
+ );
47
+ return 1;
48
+ }
49
+
50
+ if (options.verbose) {
51
+ log(chalk.dim(`Running: npm run ${scriptName}`));
52
+ }
53
+
54
+ try {
55
+ const result = await spawn('npm', ['run', scriptName], {
56
+ cwd,
57
+ stdio: 'inherit',
58
+ shell: false,
59
+ env: process.env,
60
+ });
61
+ return typeof result.code === 'number' ? result.code : 1;
62
+ } catch (err) {
63
+ error(chalk.red(err instanceof Error ? err.message : String(err)));
64
+ return 1;
65
+ }
66
+ }
67
+
68
+ /**
69
+ * @param {object} [options]
70
+ * @param {object} [deps]
71
+ * @returns {Promise<number>}
72
+ */
73
+ export async function watch(options = {}, deps = {}) {
74
+ return runNpmScript('watch', options, deps);
75
+ }
76
+
77
+ /**
78
+ * @param {object} [options]
79
+ * @param {object} [deps]
80
+ * @returns {Promise<number>}
81
+ */
82
+ export async function build(options = {}, deps = {}) {
83
+ return runNpmScript('build', options, deps);
84
+ }
@@ -1,37 +1,40 @@
1
- import path from 'path';
2
- import os from 'os';
3
1
  import chalk from 'chalk';
4
2
  import { execa } from 'execa';
5
3
  import ora from 'ora';
6
4
  import fs from 'fs-extra';
5
+ import { getCaddyfilePath, getProjectsPath } from '../lib/paths.js';
6
+ import {
7
+ ensureCaddyfileMigrated,
8
+ warnIfAllowAllOriginsActive,
9
+ } from '../lib/migrate.js';
7
10
 
8
11
  export async function reload(options = {}) {
9
- const caddyDir = path.join(os.homedir(), '.stagepass');
10
- const caddyFilePath = path.join(caddyDir, 'Caddyfile');
12
+ const caddyFilePath = getCaddyfilePath();
13
+ const projectsPath = getProjectsPath();
11
14
 
12
15
  const spinner = ora('Reloading Caddy...').start();
13
16
 
14
- // Check if Caddyfile exists
15
- if (!await fs.pathExists(caddyFilePath)) {
17
+ if (!(await fs.pathExists(caddyFilePath))) {
16
18
  spinner.fail('No Caddyfile found. Run "stagepass link" first.');
17
19
  return;
18
20
  }
19
21
 
20
- // Check if Caddy is running
21
22
  try {
22
23
  await execa('caddy', ['version'], { stdio: 'ignore' });
23
- } catch (e) {
24
+ } catch {
24
25
  spinner.fail('Caddy is not installed or not accessible.');
25
26
  console.log(chalk.dim(' Run "stagepass setup" to install dependencies.'));
26
27
  return;
27
28
  }
28
29
 
29
- // Reload Caddy
30
30
  try {
31
+ spinner.stop();
32
+ await ensureCaddyfileMigrated({ caddyfilePath: caddyFilePath, projectsPath });
33
+ await warnIfAllowAllOriginsActive({ caddyfilePath: caddyFilePath });
34
+ spinner.start('Reloading Caddy...');
35
+
31
36
  const stdioMode = options.verbose ? 'inherit' : 'ignore';
32
-
33
37
  await execa('caddy', ['reload', '--config', caddyFilePath], { stdio: stdioMode });
34
-
35
38
  spinner.succeed('Caddy reloaded successfully.');
36
39
  } catch (error) {
37
40
  spinner.fail('Failed to reload Caddy.');
@@ -1,10 +1,19 @@
1
1
  import { execa } from 'execa';
2
2
  import chalk from 'chalk';
3
3
  import path from 'path';
4
- import os from 'os';
5
4
  import fs from 'fs-extra';
6
5
  import inquirer from 'inquirer';
7
6
  import ora from 'ora';
7
+ import {
8
+ getCaddyfilePath,
9
+ getServerLogPath,
10
+ getStagepassDir,
11
+ getProjectsPath,
12
+ } from '../lib/paths.js';
13
+ import {
14
+ ensureCaddyfileMigrated,
15
+ warnIfAllowAllOriginsActive,
16
+ } from '../lib/migrate.js';
8
17
 
9
18
  // --- HELPERS ---
10
19
 
@@ -53,9 +62,10 @@ async function killProcess(proc) {
53
62
  // --- MAIN COMMAND ---
54
63
 
55
64
  export async function start(options = {}) {
56
- const caddyDir = path.join(os.homedir(), '.stagepass');
57
- const caddyFile = path.join(caddyDir, 'Caddyfile');
58
- const logFile = path.join(caddyDir, 'server.log');
65
+ const caddyDir = getStagepassDir();
66
+ const caddyFile = getCaddyfilePath();
67
+ const logFile = getServerLogPath();
68
+ const projectsPath = getProjectsPath();
59
69
 
60
70
  console.log(chalk.bold('\nšŸš€ Starting Stagepass...'));
61
71
 
@@ -91,6 +101,13 @@ export async function start(options = {}) {
91
101
  }
92
102
  }
93
103
 
104
+ // 2b. Migrate legacy Caddyfile blocks before boot
105
+ await fs.ensureDir(caddyDir);
106
+ if (await fs.pathExists(caddyFile)) {
107
+ await ensureCaddyfileMigrated({ caddyfilePath: caddyFile, projectsPath });
108
+ await warnIfAllowAllOriginsActive({ caddyfilePath: caddyFile });
109
+ }
110
+
94
111
  // 3. Boot services
95
112
  const spinner = ora('Booting background services...').start();
96
113
 
@@ -1,6 +1,7 @@
1
1
  import { execa } from 'execa';
2
2
  import chalk from 'chalk';
3
3
  import ora from 'ora';
4
+ import { getAutostartStatus } from '../lib/autostart.js';
4
5
 
5
6
  export async function stop(options = {}) {
6
7
  console.log(chalk.bold('\nšŸ›‘ Stopping Stagepass...'));
@@ -34,6 +35,20 @@ export async function stop(options = {}) {
34
35
  console.log(chalk.green('āœ” Services stopped.'));
35
36
  }
36
37
 
38
+ // Non-breaking hint only: existing stop semantics stay unchanged.
39
+ try {
40
+ const status = await getAutostartStatus();
41
+ if (status.loaded || status.plistExists) {
42
+ console.log(
43
+ chalk.dim(
44
+ 'Autostart is enabled; Caddy may start again at next login. Use `stagepass autostart off` to disable permanently.'
45
+ )
46
+ );
47
+ }
48
+ } catch {
49
+ // ignore status failures
50
+ }
51
+
37
52
  } catch (error) {
38
53
  if (!options.verbose) spinner.fail('Error stopping services.');
39
54
  console.error(chalk.red(error.message));
@@ -1,67 +1,54 @@
1
1
  import fs from 'fs-extra';
2
2
  import path from 'path';
3
- import os from 'os';
4
3
  import chalk from 'chalk';
5
4
  import { execa } from 'execa';
6
5
  import ora from 'ora';
7
-
8
- function escapeRegExp(string) {
9
- return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
10
- }
6
+ import { resolveLinkDomain } from '../lib/domain.js';
7
+ import { removeBlock } from '../lib/caddyfile.js';
8
+ import { getCaddyfilePath, getProjectsPath } from '../lib/paths.js';
9
+ import { removeProject } from '../lib/projects.js';
11
10
 
12
11
  export async function unlink(domain, options = {}) {
13
12
  const currentDir = process.cwd();
13
+ const folderName = path.basename(currentDir);
14
14
 
15
- // Domain Logic
16
- let targetDomain = domain;
17
- if (!targetDomain) {
18
- targetDomain = path.basename(currentDir);
15
+ const resolved = resolveLinkDomain(domain, folderName);
16
+ if (!resolved.ok) {
17
+ console.log(chalk.red(`āŒ ${resolved.error}`));
18
+ return;
19
19
  }
20
- targetDomain = targetDomain.replace(/\.sp$/, '') + '.sp';
21
20
 
22
- // Config Paths
23
- const caddyDir = path.join(os.homedir(), '.stagepass');
24
- const caddyFilePath = path.join(caddyDir, 'Caddyfile');
21
+ const targetDomain = resolved.domain;
22
+ const caddyFilePath = getCaddyfilePath();
23
+ const projectsPath = getProjectsPath();
25
24
 
26
25
  const spinner = ora(`Unlinking ${chalk.bold(targetDomain)}...`).start();
27
26
 
28
- // 1. Read Config
29
27
  try {
30
- if (!await fs.pathExists(caddyFilePath)) {
28
+ if (!(await fs.pathExists(caddyFilePath))) {
31
29
  spinner.warn('No Caddyfile found. Nothing to unlink.');
32
30
  return;
33
31
  }
34
32
 
35
33
  let content = await fs.readFile(caddyFilePath, 'utf-8');
34
+ const result = removeBlock(content, targetDomain);
36
35
 
37
- const blockStart = `# START: ${targetDomain}`;
38
- const blockEnd = `# END: ${targetDomain}`;
39
- const regex = new RegExp(`${escapeRegExp(blockStart)}[\\s\\S]*?${escapeRegExp(blockEnd)}`, 'g');
40
-
41
- if (!regex.test(content)) {
36
+ if (!result.removed) {
42
37
  spinner.warn(`Domain ${chalk.bold(targetDomain)} is not linked.`);
43
38
  return;
44
39
  }
45
40
 
46
- // Remove the block
47
- content = content.replace(regex, '').trim();
48
-
49
- // Clean up multiple empty lines
50
- content = content.replace(/\n{3,}/g, '\n\n');
51
-
52
- await fs.writeFile(caddyFilePath, content);
41
+ await fs.writeFile(caddyFilePath, result.content ? `${result.content}\n` : '', 'utf-8');
42
+ await removeProject(targetDomain, projectsPath);
53
43
  } catch (e) {
54
44
  spinner.fail('Failed to update config.');
55
45
  if (options.verbose) console.error(e);
56
46
  return;
57
47
  }
58
48
 
59
- // 2. Reload Caddy
60
49
  try {
61
50
  const stdioMode = options.verbose ? 'inherit' : 'ignore';
62
-
63
51
  await execa('caddy', ['reload', '--config', caddyFilePath], { stdio: stdioMode });
64
-
65
52
  spinner.succeed(`Unlinked: ${targetDomain}`);
66
53
  } catch (error) {
67
54
  spinner.warn('Config updated, but Caddy reload failed.');