@stagepass/cli 1.0.1 → 2.0.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.
@@ -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,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.');
@@ -0,0 +1,338 @@
1
+ import { escapeRegExp } from './domain.js';
2
+ import { escapeCaddyQuotedString, validateRoot } from './paths.js';
3
+ import { buildOriginAllowlistRegex, validateOriginList } from './origins.js';
4
+
5
+ /** Marker written inside every Stagepass-managed site block. */
6
+ export const BLOCK_VERSION = 'v2';
7
+
8
+ /**
9
+ * Sensitive path / extension blocking (always on).
10
+ * Hidden segments: any path component starting with "." (.git, .env, .DS_Store, …).
11
+ * Also: node_modules trees and private key / cert / db / log file extensions.
12
+ */
13
+ export const BLOCKED_PATH_REGEXP =
14
+ '(?i)((^|/)\\.|((^|/)node_modules(/|$))|\\.(pem|key|p12|pfx|crt|cer|sqlite|db|log)$)';
15
+
16
+ export const SENSITIVE_BLOCK_DOCS = Object.freeze({
17
+ hiddenSegments: 'Any URL path segment starting with "." (e.g. /.git, /.env, /.npmrc)',
18
+ directories: ['node_modules'],
19
+ extensions: ['.pem', '.key', '.p12', '.pfx', '.crt', '.cer', '.sqlite', '.db', '.log'],
20
+ });
21
+
22
+ /**
23
+ * @typedef {object} SiteBlockOptions
24
+ * @property {boolean} [allowAllOrigins]
25
+ * @property {string[]} [origins]
26
+ */
27
+
28
+ /**
29
+ * @param {string} domain - normalized foo.sp
30
+ * @param {string} root - absolute project path
31
+ * @param {SiteBlockOptions} [options]
32
+ * @returns {string} full block including START/END markers
33
+ */
34
+ export function renderSiteBlock(domain, root, options = {}) {
35
+ const rootResult = validateRoot(root);
36
+ if (!rootResult.ok) {
37
+ throw new Error(rootResult.error);
38
+ }
39
+
40
+ const allowAllOrigins = options.allowAllOrigins === true;
41
+ const originsResult = validateOriginList(options.origins || []);
42
+ if (!originsResult.ok) {
43
+ throw new Error(originsResult.error);
44
+ }
45
+ const origins = originsResult.origins;
46
+
47
+ const quotedRoot = `"${escapeCaddyQuotedString(rootResult.path)}"`;
48
+ const optionsComment = formatOptionsComment({ allowAllOrigins, origins });
49
+
50
+ const lines = [
51
+ `# START: ${domain}`,
52
+ `# stagepass-block: ${BLOCK_VERSION}`,
53
+ optionsComment,
54
+ `${domain} {`,
55
+ // tls must stay at site level (not inside handle) — Caddy rejects it as an HTTP handler
56
+ ' tls internal',
57
+ '',
58
+ ` @blocked path_regexp blocked ${BLOCKED_PATH_REGEXP}`,
59
+ ' handle @blocked {',
60
+ ' respond 404',
61
+ ' }',
62
+ '',
63
+ ];
64
+
65
+ if (allowAllOrigins) {
66
+ lines.push(...allowAllCorsLines());
67
+ } else {
68
+ lines.push(...allowlistCorsLines(origins));
69
+ }
70
+
71
+ lines.push(
72
+ '',
73
+ ' handle {',
74
+ ` root * ${quotedRoot}`,
75
+ ' php_fastcgi 127.0.0.1:9000',
76
+ ' file_server'
77
+ );
78
+
79
+ if (allowAllOrigins) {
80
+ lines.push(' header Access-Control-Allow-Origin *');
81
+ } else {
82
+ lines.push(
83
+ ' header @cors_origin Access-Control-Allow-Origin "{http.request.header.Origin}"',
84
+ ' header @cors_origin Vary Origin'
85
+ );
86
+ }
87
+
88
+ lines.push(' }', '}', `# END: ${domain}`);
89
+
90
+ return lines.join('\n');
91
+ }
92
+
93
+ function formatOptionsComment({ allowAllOrigins, origins }) {
94
+ const parts = [`allowAllOrigins=${allowAllOrigins ? 'true' : 'false'}`];
95
+ if (origins.length > 0) {
96
+ parts.push(`origins=${origins.join(',')}`);
97
+ }
98
+ return `# stagepass-options: ${parts.join(' ')}`;
99
+ }
100
+
101
+ function allowAllCorsLines() {
102
+ return [
103
+ ' @options method OPTIONS',
104
+ ' handle @options {',
105
+ ' header Access-Control-Allow-Origin *',
106
+ ' header Access-Control-Allow-Methods "GET, HEAD, POST, OPTIONS"',
107
+ ' header Access-Control-Allow-Headers "{http.request.header.Access-Control-Request-Headers}"',
108
+ ' header Access-Control-Max-Age 86400',
109
+ ' header Access-Control-Allow-Private-Network true',
110
+ ' respond 204',
111
+ ' }',
112
+ ];
113
+ }
114
+
115
+ function allowlistCorsLines(origins) {
116
+ const originRe = buildOriginAllowlistRegex(origins);
117
+ return [
118
+ ` @cors_origin header_regexp Origin ${originRe}`,
119
+ ' @cors_preflight {',
120
+ ' method OPTIONS',
121
+ ` header_regexp Origin ${originRe}`,
122
+ ' }',
123
+ ' handle @cors_preflight {',
124
+ ' header Access-Control-Allow-Origin "{http.request.header.Origin}"',
125
+ ' header Vary Origin',
126
+ ' header Access-Control-Allow-Methods "GET, HEAD, POST, OPTIONS"',
127
+ ' header Access-Control-Allow-Headers "{http.request.header.Access-Control-Request-Headers}"',
128
+ ' header Access-Control-Max-Age 86400',
129
+ ' header Access-Control-Allow-Private-Network true',
130
+ ' respond 204',
131
+ ' }',
132
+ ' @options method OPTIONS',
133
+ ' handle @options {',
134
+ ' respond 204',
135
+ ' }',
136
+ ];
137
+ }
138
+
139
+ /**
140
+ * Parse Stagepass START/END blocks from a Caddyfile.
141
+ * @param {string} content
142
+ */
143
+ export function parseBlocks(content) {
144
+ const re = /# START: ([^\n]+)\n([\s\S]*?)# END: \1/g;
145
+ const blocks = [];
146
+ let match;
147
+ while ((match = re.exec(content)) !== null) {
148
+ const domain = match[1].trim();
149
+ const inner = match[2];
150
+ const full = match[0];
151
+ const isLegacy = !/# stagepass-block:\s*v\d+/m.test(full);
152
+ const options = parseOptionsFromBlock(full);
153
+ const root = extractRootFromBlock(inner);
154
+ blocks.push({
155
+ domain,
156
+ full,
157
+ inner,
158
+ isLegacy,
159
+ options,
160
+ root,
161
+ index: match.index,
162
+ length: full.length,
163
+ });
164
+ }
165
+ return blocks;
166
+ }
167
+
168
+ /**
169
+ * @param {string} blockText
170
+ */
171
+ export function parseOptionsFromBlock(blockText) {
172
+ const defaults = { allowAllOrigins: false, origins: [] };
173
+ const line = blockText.match(/^# stagepass-options:\s*(.+)$/m);
174
+ if (!line) {
175
+ if (!/# stagepass-block:/m.test(blockText)) {
176
+ return { allowAllOrigins: true, origins: [] };
177
+ }
178
+ return defaults;
179
+ }
180
+
181
+ const text = line[1];
182
+ const allowMatch = text.match(/allowAllOrigins=(true|false)/);
183
+ const allowAllOrigins = allowMatch ? allowMatch[1] === 'true' : false;
184
+ const originsMatch = text.match(/origins=([^\s]+)/);
185
+ let origins = [];
186
+ if (originsMatch) {
187
+ const list = validateOriginList(originsMatch[1].split(',').filter(Boolean));
188
+ origins = list.ok ? list.origins : [];
189
+ }
190
+ return { allowAllOrigins, origins };
191
+ }
192
+
193
+ /**
194
+ * Extract root path from `root * "..."` inside a site block body.
195
+ * @param {string} inner
196
+ * @returns {string|null}
197
+ */
198
+ export function extractRootFromBlock(inner) {
199
+ const m = inner.match(/root\s+\*\s+"((?:\\.|[^"\\])*)"/);
200
+ if (!m) return null;
201
+ return m[1].replace(/\\"/g, '"').replace(/\\\\/g, '\\');
202
+ }
203
+
204
+ /**
205
+ * Replace or append a site block for domain. Preserves foreign content.
206
+ * @param {string} content
207
+ * @param {string} domain
208
+ * @param {string} newBlock
209
+ */
210
+ export function upsertBlock(content, domain, newBlock) {
211
+ const start = `# START: ${domain}`;
212
+ const end = `# END: ${domain}`;
213
+ const regex = new RegExp(
214
+ `${escapeRegExp(start)}[\\s\\S]*?${escapeRegExp(end)}`,
215
+ 'g'
216
+ );
217
+ const trimmed = newBlock.trim();
218
+ if (regex.test(content)) {
219
+ return content.replace(regex, trimmed);
220
+ }
221
+ const base = content.trim();
222
+ return base ? `${base}\n\n${trimmed}\n` : `${trimmed}\n`;
223
+ }
224
+
225
+ /**
226
+ * Remove a site block for domain.
227
+ * @param {string} content
228
+ * @param {string} domain
229
+ */
230
+ export function removeBlock(content, domain) {
231
+ const start = `# START: ${domain}`;
232
+ const end = `# END: ${domain}`;
233
+ const regex = new RegExp(
234
+ `${escapeRegExp(start)}[\\s\\S]*?${escapeRegExp(end)}`,
235
+ 'g'
236
+ );
237
+ if (!regex.test(content)) {
238
+ return { content, removed: false };
239
+ }
240
+ let next = content.replace(regex, '').trim();
241
+ next = next.replace(/\n{3,}/g, '\n\n');
242
+ return { content: next, removed: true };
243
+ }
244
+
245
+ /**
246
+ * Migrate legacy (pre-v2) Stagepass blocks to the current renderer.
247
+ *
248
+ * Legacy blocks get allowAllOrigins=true so existing Webflow embedding keeps working.
249
+ *
250
+ * @param {string} content
251
+ * @param {object} [opts]
252
+ * @param {(msg: string) => void} [opts.warn]
253
+ */
254
+ export function migrateLegacyContent(content, opts = {}) {
255
+ const warn = opts.warn || (() => {});
256
+ const blocks = parseBlocks(content);
257
+ const legacy = blocks.filter((b) => b.isLegacy);
258
+
259
+ if (legacy.length === 0) {
260
+ return { content, changed: false, migrated: [], skipped: [], warnings: [] };
261
+ }
262
+
263
+ let next = content;
264
+ const migrated = [];
265
+ const skipped = [];
266
+ const warnings = [];
267
+
268
+ const ordered = [...legacy].sort((a, b) => b.index - a.index);
269
+
270
+ for (const block of ordered) {
271
+ if (!block.root) {
272
+ const reason = 'could not parse root path';
273
+ skipped.push({ domain: block.domain, reason });
274
+ const msg = `Left legacy block ${block.domain} unchanged (${reason}).`;
275
+ warnings.push(msg);
276
+ warn(msg);
277
+ continue;
278
+ }
279
+
280
+ const rootCheck = validateRoot(block.root);
281
+ if (!rootCheck.ok) {
282
+ const reason = rootCheck.error;
283
+ skipped.push({ domain: block.domain, reason });
284
+ const msg = `Left legacy block ${block.domain} unchanged (${reason}).`;
285
+ warnings.push(msg);
286
+ warn(msg);
287
+ continue;
288
+ }
289
+
290
+ let newBlock;
291
+ try {
292
+ newBlock = renderSiteBlock(block.domain, rootCheck.path, {
293
+ allowAllOrigins: true,
294
+ origins: [],
295
+ });
296
+ } catch (e) {
297
+ const reason = e.message || String(e);
298
+ skipped.push({ domain: block.domain, reason });
299
+ const msg = `Left legacy block ${block.domain} unchanged (${reason}).`;
300
+ warnings.push(msg);
301
+ warn(msg);
302
+ continue;
303
+ }
304
+
305
+ next =
306
+ next.slice(0, block.index) +
307
+ newBlock.trim() +
308
+ next.slice(block.index + block.length);
309
+ migrated.push({ domain: block.domain, root: rootCheck.path });
310
+ }
311
+
312
+ next = next.replace(/\n{3,}/g, '\n\n');
313
+ if (next.trim()) {
314
+ next = `${next.trim()}\n`;
315
+ } else {
316
+ next = '';
317
+ }
318
+
319
+ return {
320
+ content: next,
321
+ changed: migrated.length > 0,
322
+ migrated,
323
+ skipped,
324
+ warnings,
325
+ };
326
+ }
327
+
328
+ /**
329
+ * Format a timestamp for Caddyfile.bak-YYYYMMDD-HHMMSS
330
+ * @param {Date} [date]
331
+ */
332
+ export function formatBackupStamp(date = new Date()) {
333
+ const pad = (n) => String(n).padStart(2, '0');
334
+ return (
335
+ `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}` +
336
+ `-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`
337
+ );
338
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * DNS label: 1–63 chars, [a-z0-9], hyphens only in the middle.
3
+ */
4
+ const LABEL_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
5
+
6
+ /** Characters that must never appear in a domain written into the Caddyfile. */
7
+ const UNSAFE_DOMAIN_RE = /[\s#"'{}$\\;()[\],=<>]/;
8
+
9
+ /**
10
+ * Convert a folder name into a DNS-safe slug.
11
+ * @param {string} name
12
+ * @returns {string}
13
+ */
14
+ export function slugifyFolderName(name) {
15
+ return String(name)
16
+ .toLowerCase()
17
+ .replace(/[^a-z0-9]+/g, '-')
18
+ .replace(/^-+|-+$/g, '')
19
+ .slice(0, 63);
20
+ }
21
+
22
+ /**
23
+ * Validate DNS labels for a hostname (without trailing .sp).
24
+ * @param {string} host
25
+ * @returns {boolean}
26
+ */
27
+ export function isValidHostnameLabels(host) {
28
+ if (!host || host.length > 243) return false;
29
+ if (host.includes('..')) return false;
30
+ const labels = host.split('.');
31
+ if (labels.length === 0) return false;
32
+ return labels.every((label) => LABEL_RE.test(label));
33
+ }
34
+
35
+ /**
36
+ * Normalize and validate a Stagepass domain.
37
+ * Accepts "foo", "foo.sp", "Foo.SP"; returns "foo.sp".
38
+ *
39
+ * @param {string} input
40
+ * @returns {{ ok: true, domain: string } | { ok: false, error: string }}
41
+ */
42
+ export function validateDomain(input) {
43
+ if (typeof input !== 'string' || input.trim() === '') {
44
+ return { ok: false, error: 'Domain is empty.' };
45
+ }
46
+
47
+ let raw = input.trim().toLowerCase();
48
+
49
+ // Strip accidental URL wrappers
50
+ raw = raw.replace(/^https?:\/\//, '').replace(/\/+$/, '');
51
+
52
+ if (UNSAFE_DOMAIN_RE.test(raw) || /[\x00-\x1f\x7f]/.test(raw)) {
53
+ return {
54
+ ok: false,
55
+ error: 'Domain contains invalid characters (spaces, quotes, braces, #, etc.).',
56
+ };
57
+ }
58
+
59
+ if (raw.endsWith('.sp')) {
60
+ raw = raw.slice(0, -3);
61
+ }
62
+
63
+ if (!raw) {
64
+ return { ok: false, error: 'Domain is empty after removing .sp suffix.' };
65
+ }
66
+
67
+ if (!isValidHostnameLabels(raw)) {
68
+ return {
69
+ ok: false,
70
+ error:
71
+ 'Domain must use DNS-safe labels ([a-z0-9], inner hyphens, 1–63 chars per label).',
72
+ };
73
+ }
74
+
75
+ const domain = `${raw}.sp`;
76
+ if (domain.length > 253) {
77
+ return { ok: false, error: 'Domain is too long.' };
78
+ }
79
+
80
+ return { ok: true, domain };
81
+ }
82
+
83
+ /**
84
+ * Resolve the target .sp domain from an explicit argument or the folder name.
85
+ * When derived from a folder and invalid, attempts to slugify.
86
+ *
87
+ * @param {string|undefined} domainArg
88
+ * @param {string} folderName
89
+ * @returns {{ ok: true, domain: string, slugged?: boolean, fromFolder?: boolean } | { ok: false, error: string }}
90
+ */
91
+ export function resolveLinkDomain(domainArg, folderName) {
92
+ if (domainArg !== undefined && domainArg !== null && String(domainArg).trim() !== '') {
93
+ const result = validateDomain(String(domainArg));
94
+ if (!result.ok) return result;
95
+ return { ok: true, domain: result.domain, fromFolder: false };
96
+ }
97
+
98
+ const rawFolder = String(folderName || '');
99
+ const direct = validateDomain(rawFolder);
100
+ if (direct.ok) {
101
+ return { ok: true, domain: direct.domain, fromFolder: true, slugged: false };
102
+ }
103
+
104
+ const slug = slugifyFolderName(rawFolder);
105
+ if (!slug) {
106
+ return {
107
+ ok: false,
108
+ error: `Folder name "${rawFolder}" cannot be converted to a valid .sp domain. Pass an explicit domain.`,
109
+ };
110
+ }
111
+
112
+ const slugged = validateDomain(slug);
113
+ if (!slugged.ok) {
114
+ return {
115
+ ok: false,
116
+ error: `Could not derive a valid domain from folder "${rawFolder}".`,
117
+ };
118
+ }
119
+
120
+ return { ok: true, domain: slugged.domain, fromFolder: true, slugged: true };
121
+ }
122
+
123
+ export function escapeRegExp(string) {
124
+ return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
125
+ }