codepen-commander 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +103 -11
  2. package/api/client.js +129 -106
  3. package/cli.js +34 -29
  4. package/commands/auth/default.js +40 -0
  5. package/commands/auth/index.js +83 -0
  6. package/commands/auth/list.js +78 -0
  7. package/commands/auth/login.js +136 -0
  8. package/commands/auth/logout.js +186 -0
  9. package/commands/auth/status.js +212 -0
  10. package/commands/build.js +256 -0
  11. package/commands/clone.js +13 -581
  12. package/commands/delete.js +548 -80
  13. package/commands/deploy.js +164 -169
  14. package/commands/domains.js +83 -39
  15. package/commands/fork.js +13 -317
  16. package/commands/info.js +152 -0
  17. package/commands/init.js +375 -0
  18. package/commands/list.js +95 -78
  19. package/commands/new.js +155 -83
  20. package/commands/open.js +29 -19
  21. package/commands/privacy.js +52 -36
  22. package/commands/pull.js +123 -110
  23. package/commands/push.js +221 -376
  24. package/commands/restore.js +251 -0
  25. package/commands/rollback.js +141 -0
  26. package/commands/serve.js +119 -0
  27. package/commands/settings.js +126 -0
  28. package/commands/shell.js +305 -0
  29. package/commands/status.js +133 -39
  30. package/commands/sync.js +330 -0
  31. package/commands/undeploy.js +102 -0
  32. package/commands/unlink.js +191 -0
  33. package/commands/versions.js +100 -163
  34. package/config/auth.js +4 -374
  35. package/config/pen-blocks.js +166 -0
  36. package/config/project.js +103 -231
  37. package/config/user-store.js +364 -0
  38. package/constants.js +42 -0
  39. package/errors.js +17 -0
  40. package/package.json +1 -1
  41. package/shell/index.html +79 -0
  42. package/shell/scripts.js +276 -0
  43. package/shell/styles.css +492 -0
  44. package/site/blocks/classic.js +270 -0
  45. package/site/blocks/context.js +63 -0
  46. package/site/blocks/index.js +4 -0
  47. package/site/blocks/packages.js +242 -0
  48. package/site/blocks/unsupported-page.js +328 -0
  49. package/site/builder.js +475 -0
  50. package/site/detect.js +65 -0
  51. package/site/ignore-files.js +90 -0
  52. package/site/manifest.js +227 -0
  53. package/site/server.js +483 -0
  54. package/site/shell.js +363 -0
  55. package/sync/fs.js +19 -17
  56. package/sync/info.js +6 -81
  57. package/utils/browser.js +17 -10
  58. package/utils/cli-options.js +79 -0
  59. package/utils/codepen-url.js +183 -0
  60. package/utils/format.js +39 -30
  61. package/utils/fs-safe.js +95 -0
  62. package/utils/html.js +40 -1
  63. package/utils/json.js +4 -19
  64. package/utils/output.js +37 -0
  65. package/utils/package-paths.js +51 -0
  66. package/utils/prompts/index.js +5 -0
  67. package/utils/prompts/multi-select.js +185 -0
  68. package/utils/prompts/secret.js +65 -0
  69. package/utils/prompts/select.js +141 -0
  70. package/utils/prompts/text.js +99 -0
  71. package/utils/prompts/tty-list.js +165 -0
  72. package/utils/prompts/types.js +35 -0
  73. package/utils/strings.js +98 -0
  74. package/utils/watcher.js +82 -0
  75. package/{commands → workflows}/auth-context.js +13 -7
  76. package/workflows/batch-pens.js +1647 -0
  77. package/workflows/batch-target.js +184 -0
  78. package/workflows/classic-convert.js +241 -0
  79. package/workflows/clone-pen.js +381 -0
  80. package/{commands → workflows}/create-pen.js +59 -84
  81. package/workflows/discover-pens.js +91 -0
  82. package/workflows/fork-pen.js +314 -0
  83. package/workflows/missing-pen.js +212 -0
  84. package/workflows/pull-pen.js +204 -0
  85. package/workflows/push-pen.js +318 -0
  86. package/{commands → workflows}/scaffold.js +4 -3
  87. package/workflows/sync-pen.js +227 -0
  88. package/{commands → workflows}/unowned-pen.js +16 -12
  89. package/commands/auth.js +0 -593
  90. package/commands/meta.js +0 -184
  91. package/utils/prompts.js +0 -316
  92. /package/{types.js → api/types.js} +0 -0
package/site/shell.js ADDED
@@ -0,0 +1,363 @@
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { getConfiguredShellDir } from '../config/user-store.js';
5
+ import { CliError } from '../errors.js';
6
+ import { isWithinRoot, resolveSafeFile } from '../utils/fs-safe.js';
7
+ import { escapeHtml } from '../utils/html.js';
8
+ import { resolveBuiltinShellDir } from '../utils/package-paths.js';
9
+ import { formatFolderTitle, hasControlChars } from '../utils/strings.js';
10
+ export { resolveBuiltinShellDir };
11
+ export const CORE_SHELL_FILES = ['index.html', 'styles.css', 'scripts.js'];
12
+ export const DEFAULT_SITE_SUBTITLE = 'A collection of self-contained web demos.';
13
+ export const DEFAULT_SITE_FOOTER = 'Powered by codepen-commander.';
14
+ export const CODEPEN_COMMANDER_NPM_URL = 'https://www.npmjs.com/package/codepen-commander';
15
+ const MAX_SHELL_WALK_DEPTH = 8;
16
+ export function expandHomePath(rawPath, homeDir) {
17
+ const trimmed = rawPath.trim();
18
+ const resolvedHome = homeDir ?? os.homedir();
19
+ if (trimmed === '~') {
20
+ return resolvedHome;
21
+ }
22
+ if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
23
+ return path.join(resolvedHome, trimmed.slice(2));
24
+ }
25
+ return trimmed;
26
+ }
27
+ /**
28
+ * Lists all non-hidden regular files (relative POSIX paths) inside a shell directory,
29
+ * strictly enforcing directory containment and skipping symlinks.
30
+ */
31
+ export async function listShellAssetFiles(shellRealpath) {
32
+ const files = [];
33
+ async function walk(currentDir, relPrefix, depth) {
34
+ if (depth > MAX_SHELL_WALK_DEPTH)
35
+ return;
36
+ let entries;
37
+ try {
38
+ entries = await fs.readdir(currentDir, { withFileTypes: true });
39
+ }
40
+ catch {
41
+ return;
42
+ }
43
+ for (const entry of entries) {
44
+ if (entry.name.startsWith('.') || entry.name === 'node_modules')
45
+ continue;
46
+ const fullPath = path.join(currentDir, entry.name);
47
+ if (!isWithinRoot(fullPath, shellRealpath))
48
+ continue;
49
+ let lstat;
50
+ try {
51
+ lstat = await fs.lstat(fullPath);
52
+ }
53
+ catch {
54
+ continue;
55
+ }
56
+ if (lstat.isSymbolicLink())
57
+ continue;
58
+ const realPath = await fs.realpath(fullPath);
59
+ if (!isWithinRoot(realPath, shellRealpath))
60
+ continue;
61
+ const relPosix = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
62
+ if (lstat.isDirectory()) {
63
+ await walk(realPath, relPosix, depth + 1);
64
+ }
65
+ else if (lstat.isFile()) {
66
+ files.push(relPosix);
67
+ }
68
+ }
69
+ }
70
+ await walk(shellRealpath, '', 0);
71
+ return files.sort((a, b) => a.localeCompare(b));
72
+ }
73
+ /**
74
+ * Validates that a custom shell directory exists, is a directory, and contains at least
75
+ * one core shell file (`index.html`, `styles.css`, or `scripts.js`).
76
+ */
77
+ export async function validateShellDir(rawPath, options = {}) {
78
+ const trimmed = rawPath.trim();
79
+ if (!trimmed || hasControlChars(trimmed)) {
80
+ throw new CliError(400, 'Shell directory path cannot be empty or contain control characters.');
81
+ }
82
+ const expanded = expandHomePath(trimmed, options.homeDir);
83
+ const baseCwd = path.resolve(options.cwd ?? process.cwd());
84
+ const resolved = path.resolve(baseCwd, expanded);
85
+ let stat;
86
+ try {
87
+ stat = await fs.stat(resolved);
88
+ }
89
+ catch (error) {
90
+ if (error.code === 'ENOENT') {
91
+ const hint = options.sourceLabel === 'config'
92
+ ? ' Update it with `cdpn shell set <dir>` or reset with `cdpn shell reset`.'
93
+ : ' Run `cdpn shell export <dir>` to create one from the built-in shell.';
94
+ throw new CliError(404, `Shell directory not found: ${resolved}.${hint}`);
95
+ }
96
+ throw error;
97
+ }
98
+ if (!stat.isDirectory()) {
99
+ throw new CliError(400, `Shell path is not a directory: ${resolved}`);
100
+ }
101
+ const realpath = await fs.realpath(resolved);
102
+ const files = await listShellAssetFiles(realpath);
103
+ const hasCoreFile = CORE_SHELL_FILES.some((name) => files.includes(name));
104
+ if (!hasCoreFile) {
105
+ throw new CliError(400, `Shell directory ${resolved} must contain at least one of: ${CORE_SHELL_FILES.join(', ')}.\n` +
106
+ 'Run `cdpn shell export <dir>` to copy the built-in shell as a starting point.');
107
+ }
108
+ return { dir: resolved, realpath, files };
109
+ }
110
+ /**
111
+ * Resolves the active shell directory with precedence:
112
+ * 1. Explicit `--shell <dir>` CLI flag
113
+ * 2. Configured `config.shell` in `~/.cdpn`
114
+ * 3. Built-in packaged `shell/` directory
115
+ */
116
+ export async function resolveActiveShell(options = {}) {
117
+ const builtin = await resolveBuiltinShellDir();
118
+ if (options.explicitShell !== undefined) {
119
+ const validated = await validateShellDir(options.explicitShell, {
120
+ cwd: options.cwd,
121
+ homeDir: options.homeDir,
122
+ sourceLabel: 'flag',
123
+ });
124
+ return {
125
+ source: 'flag',
126
+ dir: validated.dir,
127
+ realpath: validated.realpath,
128
+ builtinDir: builtin.dir,
129
+ builtinRealpath: builtin.realpath,
130
+ };
131
+ }
132
+ const configured = await getConfiguredShellDir({ homeDir: options.homeDir });
133
+ if (configured) {
134
+ const validated = await validateShellDir(configured, {
135
+ cwd: options.homeDir ?? os.homedir(),
136
+ homeDir: options.homeDir,
137
+ sourceLabel: 'config',
138
+ });
139
+ return {
140
+ source: 'config',
141
+ dir: validated.dir,
142
+ realpath: validated.realpath,
143
+ builtinDir: builtin.dir,
144
+ builtinRealpath: builtin.realpath,
145
+ };
146
+ }
147
+ return {
148
+ source: 'builtin',
149
+ dir: builtin.dir,
150
+ realpath: builtin.realpath,
151
+ builtinDir: builtin.dir,
152
+ builtinRealpath: builtin.realpath,
153
+ };
154
+ }
155
+ /**
156
+ * Resolves a request pathname (e.g. `/`, `/styles.css`, `/favicon.svg`) against
157
+ * the active shell directory, falling back to the built-in shell for missing core files.
158
+ */
159
+ export async function resolveShellAssetForRequest(rawPathname, shell) {
160
+ let decodedPath;
161
+ try {
162
+ decodedPath = decodeURIComponent(rawPathname);
163
+ }
164
+ catch {
165
+ return null;
166
+ }
167
+ if (decodedPath.includes('\0') || decodedPath.includes('\\')) {
168
+ return null;
169
+ }
170
+ const normalizedPath = decodedPath === '/' ? '/index.html' : decodedPath;
171
+ const segments = normalizedPath.split('/').filter(Boolean);
172
+ if (segments.length === 0)
173
+ return null;
174
+ for (const segment of segments) {
175
+ if (segment === '.' || segment === '..' || segment.startsWith('.')) {
176
+ return null;
177
+ }
178
+ }
179
+ const relPosix = segments.join('/');
180
+ const isIndexHtml = relPosix === 'index.html';
181
+ const primary = await resolveSafeFile(path.resolve(shell.realpath, ...segments), shell.realpath);
182
+ if (primary) {
183
+ return {
184
+ filePath: primary.realPath,
185
+ fromBuiltin: shell.source === 'builtin',
186
+ isIndexHtml,
187
+ };
188
+ }
189
+ if (shell.source !== 'builtin' && CORE_SHELL_FILES.includes(relPosix)) {
190
+ const fallback = await resolveSafeFile(path.resolve(shell.builtinRealpath, ...segments), shell.builtinRealpath);
191
+ if (fallback) {
192
+ return {
193
+ filePath: fallback.realPath,
194
+ fromBuiltin: true,
195
+ isIndexHtml,
196
+ };
197
+ }
198
+ }
199
+ return null;
200
+ }
201
+ function renderFooterHtml(footerText) {
202
+ return escapeHtml(footerText).replaceAll('codepen-commander', `<a href="${CODEPEN_COMMANDER_NPM_URL}" target="_blank" rel="noopener noreferrer">codepen-commander</a>`);
203
+ }
204
+ export function resolveSiteMetadata(rootDir, overrides = {}) {
205
+ const folderName = path.basename(path.resolve(rootDir));
206
+ const defaultTitle = formatFolderTitle(folderName) || 'CodePen Demos';
207
+ return {
208
+ title: typeof overrides.title === 'string' && overrides.title.trim()
209
+ ? overrides.title.trim()
210
+ : defaultTitle,
211
+ subtitle: typeof overrides.subtitle === 'string' ? overrides.subtitle.trim() : DEFAULT_SITE_SUBTITLE,
212
+ footer: typeof overrides.footer === 'string' ? overrides.footer.trim() : DEFAULT_SITE_FOOTER,
213
+ };
214
+ }
215
+ const MISSING_DEMO_WARNING_TEMPLATE_ID = 'missing-demo-warning-template';
216
+ /**
217
+ * Removes `<template id="...">...</template>` blocks matching `templateId` without regex
218
+ * backtracking, trimming any surrounding indentation/blank line cleanly.
219
+ */
220
+ function stripTemplateById(html, templateId) {
221
+ const lower = html.toLowerCase();
222
+ const targetId = templateId.toLowerCase();
223
+ const idDouble = `id="${targetId}"`;
224
+ const idSingle = `id='${targetId}'`;
225
+ const idUnquoted = `id=${targetId}`;
226
+ let result = '';
227
+ let cursor = 0;
228
+ while (cursor < html.length) {
229
+ const openIdx = lower.indexOf('<template', cursor);
230
+ if (openIdx === -1) {
231
+ result += html.slice(cursor);
232
+ break;
233
+ }
234
+ const afterTagName = lower[openIdx + '<template'.length];
235
+ if (afterTagName !== undefined &&
236
+ afterTagName !== '>' &&
237
+ afterTagName !== '/' &&
238
+ !/\s/.test(afterTagName)) {
239
+ result += html.slice(cursor, openIdx + '<template'.length);
240
+ cursor = openIdx + '<template'.length;
241
+ continue;
242
+ }
243
+ const openEndIdx = lower.indexOf('>', openIdx);
244
+ if (openEndIdx === -1) {
245
+ result += html.slice(cursor);
246
+ break;
247
+ }
248
+ const openTagLower = lower.slice(openIdx, openEndIdx + 1);
249
+ const hasUnquotedId = (() => {
250
+ let idx = openTagLower.indexOf(idUnquoted);
251
+ while (idx !== -1) {
252
+ const before = openTagLower[idx - 1];
253
+ const after = openTagLower[idx + idUnquoted.length];
254
+ if (before !== undefined &&
255
+ /\s/.test(before) &&
256
+ (after === undefined || after === '>' || after === '/' || /\s/.test(after))) {
257
+ return true;
258
+ }
259
+ idx = openTagLower.indexOf(idUnquoted, idx + idUnquoted.length);
260
+ }
261
+ return false;
262
+ })();
263
+ const matchesId = openTagLower.includes(idDouble) || openTagLower.includes(idSingle) || hasUnquotedId;
264
+ if (!matchesId) {
265
+ result += html.slice(cursor, openEndIdx + 1);
266
+ cursor = openEndIdx + 1;
267
+ continue;
268
+ }
269
+ let depth = 1;
270
+ let searchPos = openEndIdx + 1;
271
+ let closeEndIdx = -1;
272
+ while (depth > 0 && searchPos < lower.length) {
273
+ const nextOpen = lower.indexOf('<template', searchPos);
274
+ const nextClose = lower.indexOf('</template', searchPos);
275
+ if (nextClose === -1) {
276
+ break;
277
+ }
278
+ if (nextOpen !== -1 && nextOpen < nextClose) {
279
+ const ch = lower[nextOpen + '<template'.length];
280
+ if (ch === '>' || ch === '/' || (ch !== undefined && /\s/.test(ch))) {
281
+ depth++;
282
+ }
283
+ searchPos = nextOpen + '<template'.length;
284
+ }
285
+ else {
286
+ const closeTagEnd = lower.indexOf('>', nextClose);
287
+ if (closeTagEnd === -1) {
288
+ break;
289
+ }
290
+ depth--;
291
+ if (depth === 0) {
292
+ closeEndIdx = closeTagEnd + 1;
293
+ }
294
+ searchPos = closeTagEnd + 1;
295
+ }
296
+ }
297
+ if (closeEndIdx === -1) {
298
+ result += html.slice(cursor);
299
+ break;
300
+ }
301
+ let trimStart = openIdx;
302
+ while (trimStart > cursor && (html[trimStart - 1] === ' ' || html[trimStart - 1] === '\t')) {
303
+ trimStart--;
304
+ }
305
+ let trimEnd = closeEndIdx;
306
+ while (trimEnd < html.length && (html[trimEnd] === ' ' || html[trimEnd] === '\t')) {
307
+ trimEnd++;
308
+ }
309
+ if (html[trimEnd] === '\r' && html[trimEnd + 1] === '\n') {
310
+ trimEnd += 2;
311
+ }
312
+ else if (html[trimEnd] === '\n') {
313
+ trimEnd += 1;
314
+ }
315
+ if (trimStart >= cursor + 2 && html[trimStart - 1] === '\n' && html[trimStart - 2] === '\n') {
316
+ trimStart -= 1;
317
+ }
318
+ else if (trimStart >= cursor + 4 &&
319
+ html[trimStart - 1] === '\n' &&
320
+ html[trimStart - 2] === '\r' &&
321
+ html[trimStart - 3] === '\n' &&
322
+ html[trimStart - 4] === '\r') {
323
+ trimStart -= 2;
324
+ }
325
+ result += html.slice(cursor, trimStart);
326
+ cursor = trimEnd;
327
+ }
328
+ return result;
329
+ }
330
+ export function renderShellIndexHtml(templateHtml, site, options = {}) {
331
+ const rendered = templateHtml
332
+ .replaceAll('{{SITE_TITLE}}', escapeHtml(site.title))
333
+ .replaceAll('{{SITE_SUBTITLE}}', escapeHtml(site.subtitle))
334
+ .replaceAll('{{SITE_FOOTER}}', renderFooterHtml(site.footer));
335
+ if (options.includeMissingDemoWarning === false) {
336
+ return stripTemplateById(rendered, MISSING_DEMO_WARNING_TEMPLATE_ID);
337
+ }
338
+ return rendered;
339
+ }
340
+ /**
341
+ * Copies the built-in shell files (`index.html`, `styles.css`, `scripts.js`) into `targetDir`.
342
+ */
343
+ export async function exportBuiltinShell(targetDir) {
344
+ const builtin = await resolveBuiltinShellDir();
345
+ const resolvedTarget = path.resolve(targetDir);
346
+ if (resolvedTarget === builtin.realpath ||
347
+ isWithinRoot(resolvedTarget, builtin.realpath)) {
348
+ throw new CliError(400, 'Refusing to export shell inside the codepen-commander package directory.');
349
+ }
350
+ await fs.mkdir(resolvedTarget, { recursive: true });
351
+ const files = await listShellAssetFiles(builtin.realpath);
352
+ const copiedFiles = [];
353
+ for (const relPosix of files) {
354
+ const srcPath = path.join(builtin.realpath, ...relPosix.split('/'));
355
+ const destPath = path.join(resolvedTarget, ...relPosix.split('/'));
356
+ if (!isWithinRoot(destPath, resolvedTarget))
357
+ continue;
358
+ await fs.mkdir(path.dirname(destPath), { recursive: true });
359
+ await fs.copyFile(srcPath, destPath);
360
+ copiedFiles.push(relPosix);
361
+ }
362
+ return { targetDir: resolvedTarget, copiedFiles };
363
+ }
package/sync/fs.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import crypto from 'node:crypto';
2
2
  import fs from 'node:fs/promises';
3
3
  import path from 'node:path';
4
- import { MAX_FILE_BYTES } from '../api/client.js';
5
- import { PROJECT_CONFIG_FILENAME } from '../config/project.js';
6
- export const IGNORE_FILENAME = '.cdpnignore';
4
+ import { IGNORE_FILENAME, MAX_FILE_BYTES, PROJECT_CONFIG_FILENAME, } from '../constants.js';
5
+ import { CliError } from '../errors.js';
6
+ import { isWithinRoot } from '../utils/fs-safe.js';
7
+ import { hasControlChars } from '../utils/strings.js';
8
+ export { IGNORE_FILENAME };
7
9
  const BUILTIN_IGNORED_SEGMENTS = new Set([
8
10
  PROJECT_CONFIG_FILENAME,
9
11
  IGNORE_FILENAME,
@@ -44,30 +46,30 @@ export function isBinaryBuffer(buffer) {
44
46
  */
45
47
  export function normalizePenPath(rawPath) {
46
48
  if (typeof rawPath !== 'string' || rawPath.length === 0) {
47
- throw new Error('File path cannot be empty.');
49
+ throw new CliError(400, 'File path cannot be empty.');
48
50
  }
49
- if (rawPath.includes('\0') || /[\x00-\x1f\x7f]/.test(rawPath)) {
50
- throw new Error(`Invalid control character in file path: ${JSON.stringify(rawPath)}`);
51
+ if (hasControlChars(rawPath)) {
52
+ throw new CliError(400, `Invalid control character in file path: ${JSON.stringify(rawPath)}`);
51
53
  }
52
54
  if (rawPath.includes('\\')) {
53
- throw new Error(`Backslashes are not allowed in Pen file paths: ${rawPath}`);
55
+ throw new CliError(400, `Backslashes are not allowed in Pen file paths: ${rawPath}`);
54
56
  }
55
57
  if (/^[A-Za-z]:/.test(rawPath)) {
56
- throw new Error(`Drive-letter paths are not allowed: ${rawPath}`);
58
+ throw new CliError(400, `Drive-letter paths are not allowed: ${rawPath}`);
57
59
  }
58
60
  const trimmed = rawPath.replace(/^\/+/, '');
59
61
  if (!trimmed) {
60
- throw new Error(`Invalid empty Pen file path: ${rawPath}`);
62
+ throw new CliError(400, `Invalid empty Pen file path: ${rawPath}`);
61
63
  }
62
64
  const segments = trimmed.split('/');
63
65
  for (const seg of segments) {
64
66
  if (!seg || seg === '.' || seg === '..') {
65
- throw new Error(`Unsafe path segment in Pen file path: ${rawPath}`);
67
+ throw new CliError(400, `Unsafe path segment in Pen file path: ${rawPath}`);
66
68
  }
67
69
  }
68
70
  const normalized = `/${segments.join('/')}`;
69
71
  if (segments[0] === PROJECT_CONFIG_FILENAME || segments[0] === '.git') {
70
- throw new Error(`Refusing to touch reserved path: ${normalized}`);
72
+ throw new CliError(400, `Refusing to touch reserved path: ${normalized}`);
71
73
  }
72
74
  return normalized;
73
75
  }
@@ -79,8 +81,8 @@ export function resolveSafeLocalPath(rootDir, penPath) {
79
81
  const resolvedRoot = path.resolve(rootDir);
80
82
  const relative = normalizedPenPath.slice(1).split('/').join(path.sep);
81
83
  const resolvedTarget = path.resolve(resolvedRoot, relative);
82
- if (!resolvedTarget.startsWith(resolvedRoot + path.sep)) {
83
- throw new Error(`Path escapes project root boundary: ${penPath}`);
84
+ if (!isWithinRoot(resolvedTarget, resolvedRoot)) {
85
+ throw new CliError(400, `Path escapes project root boundary: ${penPath}`);
84
86
  }
85
87
  return resolvedTarget;
86
88
  }
@@ -151,7 +153,7 @@ export async function scanLocalFiles(rootDir) {
151
153
  continue;
152
154
  }
153
155
  const fullPath = path.join(currentDir, entry.name);
154
- if (!fullPath.startsWith(resolvedRoot + path.sep)) {
156
+ if (!isWithinRoot(fullPath, resolvedRoot)) {
155
157
  continue;
156
158
  }
157
159
  const stat = await fs.lstat(fullPath);
@@ -164,7 +166,7 @@ export async function scanLocalFiles(rootDir) {
164
166
  }
165
167
  else if (stat.isFile()) {
166
168
  if (stat.size > MAX_FILE_BYTES) {
167
- throw new Error(`Local file ${penPath} is ${Math.round(stat.size / (1024 * 1024))} MB, exceeding CodePen's 30 MB per-file limit.`);
169
+ throw new CliError(400, `Local file ${penPath} is ${Math.round(stat.size / (1024 * 1024))} MB, exceeding CodePen's 30 MB per-file limit.`);
168
170
  }
169
171
  const buffer = await fs.readFile(fullPath);
170
172
  const binary = isBinaryBuffer(buffer);
@@ -191,7 +193,7 @@ async function assertNoSymlinksInRelativePath(rootDir, penPath) {
191
193
  try {
192
194
  const stat = await fs.lstat(current);
193
195
  if (stat.isSymbolicLink()) {
194
- throw new Error(`Refusing to write through symlink at ${penPath}`);
196
+ throw new CliError(400, `Refusing to write through symlink at ${penPath}`);
195
197
  }
196
198
  }
197
199
  catch (error) {
@@ -225,7 +227,7 @@ export async function deleteLocalFile(rootDir, penPath) {
225
227
  export async function pruneEmptyDirs(rootDir, startDir) {
226
228
  const resolvedRoot = path.resolve(rootDir);
227
229
  let current = path.resolve(startDir);
228
- while (current !== resolvedRoot && current.startsWith(resolvedRoot + path.sep)) {
230
+ while (current !== resolvedRoot && isWithinRoot(current, resolvedRoot)) {
229
231
  try {
230
232
  const entries = await fs.readdir(current);
231
233
  if (entries.length > 0) {
package/sync/info.js CHANGED
@@ -1,14 +1,9 @@
1
1
  import crypto from 'node:crypto';
2
- import { CliError } from '../utils/json.js';
2
+ import { normalizePartialPenInfo, parsePenInfoInput, } from '../config/project.js';
3
+ import { MAX_PEN_TAGS } from '../constants.js';
4
+ import { CliError } from '../errors.js';
5
+ export { normalizePartialPenInfo, parsePenInfoInput };
3
6
  export const PEN_INFO_FIELDS = ['title', 'description', 'tags', 'access', 'template'];
4
- const VALID_ACCESS = new Set(['public', 'private', 'protected', 'collaborators']);
5
- function parseAccessValue(raw) {
6
- const lower = raw.trim().toLowerCase();
7
- if (!VALID_ACCESS.has(lower)) {
8
- return null;
9
- }
10
- return (lower[0].toUpperCase() + lower.slice(1));
11
- }
12
7
  /**
13
8
  * Extracts editable Pen metadata from a CodePen API v2 `Pen` payload.
14
9
  * Intentionally excludes `password` (never stored in `.cdpn.json`) and volatile read-only stats.
@@ -39,23 +34,6 @@ export function canonicalizePenInfo(info) {
39
34
  template: info.template,
40
35
  };
41
36
  }
42
- /**
43
- * Orders defined keys of a (potentially partial) `PenInfo` object consistently for writing `.cdpn.json`.
44
- */
45
- export function normalizePartialPenInfo(info) {
46
- const ordered = {};
47
- if (info.title !== undefined)
48
- ordered.title = info.title;
49
- if (info.description !== undefined)
50
- ordered.description = info.description;
51
- if (info.tags !== undefined)
52
- ordered.tags = [...info.tags];
53
- if (info.access !== undefined)
54
- ordered.access = info.access;
55
- if (info.template !== undefined)
56
- ordered.template = info.template;
57
- return ordered;
58
- }
59
37
  export function hasAnyPenInfoFields(info) {
60
38
  if (!info)
61
39
  return false;
@@ -89,59 +67,6 @@ export function buildPenInfoConfigFields(pen) {
89
67
  last_synced_info_hash: hashPenInfo(info),
90
68
  };
91
69
  }
92
- /**
93
- * Validates and normalizes the optional `info` object parsed from `.cdpn.json`.
94
- * Returns `undefined` when absent (backwards-compatible with older `.cdpn.json` files).
95
- */
96
- export function parsePenInfoInput(raw, configLabel = '.cdpn.json') {
97
- if (raw === undefined || raw === null) {
98
- return undefined;
99
- }
100
- if (typeof raw !== 'object' || Array.isArray(raw)) {
101
- throw new CliError(400, `Invalid ${configLabel}: "info" must be a JSON object.`);
102
- }
103
- const record = raw;
104
- if (Object.hasOwn(record, 'password') && record.password !== undefined) {
105
- throw new CliError(400, `Invalid ${configLabel}: "info.password" is not supported (passwords must not be stored in ${configLabel}).\n` +
106
- 'Use `cdpn privacy protected` or `cdpn info --access Protected --password <password>` instead.');
107
- }
108
- const parsed = {};
109
- if (record.title !== undefined) {
110
- if (typeof record.title !== 'string') {
111
- throw new CliError(400, `Invalid ${configLabel}: "info.title" must be a string.`);
112
- }
113
- parsed.title = record.title;
114
- }
115
- if (record.description !== undefined) {
116
- if (typeof record.description !== 'string') {
117
- throw new CliError(400, `Invalid ${configLabel}: "info.description" must be a string.`);
118
- }
119
- parsed.description = record.description;
120
- }
121
- if (record.tags !== undefined) {
122
- if (!Array.isArray(record.tags) || !record.tags.every((t) => typeof t === 'string')) {
123
- throw new CliError(400, `Invalid ${configLabel}: "info.tags" must be an array of strings.`);
124
- }
125
- parsed.tags = record.tags.map((t) => t.trim()).filter(Boolean);
126
- }
127
- if (record.access !== undefined) {
128
- if (typeof record.access !== 'string') {
129
- throw new CliError(400, `Invalid ${configLabel}: "info.access" must be one of Public, Private, Protected, or Collaborators.`);
130
- }
131
- const normalizedAccess = parseAccessValue(record.access);
132
- if (!normalizedAccess) {
133
- throw new CliError(400, `Invalid ${configLabel}: "info.access" value "${record.access}" is invalid. Use: Public, Private, Protected, or Collaborators.`);
134
- }
135
- parsed.access = normalizedAccess;
136
- }
137
- if (record.template !== undefined) {
138
- if (typeof record.template !== 'boolean') {
139
- throw new CliError(400, `Invalid ${configLabel}: "info.template" must be a boolean.`);
140
- }
141
- parsed.template = record.template;
142
- }
143
- return parsed;
144
- }
145
70
  function areTagArraysEqual(a, b) {
146
71
  if (a.length !== b.length)
147
72
  return false;
@@ -255,8 +180,8 @@ export function buildInfoUpdatePatch(changes) {
255
180
  break;
256
181
  case 'tags': {
257
182
  const tags = item.local;
258
- if (tags.length > 5) {
259
- throw new CliError(400, `CodePen allows at most 5 tags per Pen (found ${tags.length} in .cdpn.json).`);
183
+ if (tags.length > MAX_PEN_TAGS) {
184
+ throw new CliError(400, `CodePen allows at most ${MAX_PEN_TAGS} tags per Pen (found ${tags.length} in .cdpn.json).`);
260
185
  }
261
186
  patch.tags = [...tags];
262
187
  break;
package/utils/browser.js CHANGED
@@ -1,29 +1,36 @@
1
1
  import { execFile } from 'node:child_process';
2
+ import { CliError } from '../errors.js';
3
+ import { hasControlChars, isLoopbackHost } from './strings.js';
2
4
  /**
3
- * Validates that a URL is a clean HTTPS URL with no control characters.
5
+ * Validates that a URL is a clean HTTPS URL (or localhost HTTP when explicitly allowed)
6
+ * with no control characters.
4
7
  */
5
- export function validateBrowserUrl(rawUrl) {
6
- if (/[\x00-\x1f\x7f]/.test(rawUrl)) {
7
- throw new Error('URL contains invalid control characters.');
8
+ export function validateBrowserUrl(rawUrl, options = {}) {
9
+ if (hasControlChars(rawUrl)) {
10
+ throw new CliError(400, 'URL contains invalid control characters.');
8
11
  }
9
12
  let parsed;
10
13
  try {
11
14
  parsed = new URL(rawUrl);
12
15
  }
13
16
  catch {
14
- throw new Error(`Invalid URL: ${rawUrl}`);
17
+ throw new CliError(400, `Invalid URL: ${rawUrl}`);
15
18
  }
16
- if (parsed.protocol !== 'https:') {
17
- throw new Error(`Refusing to open non-HTTPS URL in browser: ${parsed.protocol}`);
19
+ const allowedLocalHttp = Boolean(options.allowLocalhostHttp) &&
20
+ parsed.protocol === 'http:' &&
21
+ isLoopbackHost(parsed.hostname);
22
+ if (parsed.protocol !== 'https:' && !allowedLocalHttp) {
23
+ throw new CliError(400, `Refusing to open non-HTTPS URL in browser: ${parsed.protocol}`);
18
24
  }
19
25
  return parsed.toString();
20
26
  }
21
27
  /**
22
- * Opens an HTTPS URL in the user's default browser without invoking a shell.
28
+ * Opens an HTTPS URL (or localhost HTTP URL when `allowLocalhostHttp` is true) in the user's
29
+ * default browser without invoking a shell.
23
30
  * Returns `true` if the launcher succeeded, or `false` if unavailable (e.g. headless/SSH).
24
31
  */
25
- export async function openBrowser(rawUrl) {
26
- const safeUrl = validateBrowserUrl(rawUrl);
32
+ export async function openBrowser(rawUrl, options = {}) {
33
+ const safeUrl = validateBrowserUrl(rawUrl, options);
27
34
  let command;
28
35
  let args;
29
36
  if (process.platform === 'darwin') {