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
@@ -0,0 +1,381 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { CodePenClient } from '../api/client.js';
4
+ import { CodePenApiError } from '../api/errors.js';
5
+ import { findMatchingProfile } from '../config/auth.js';
6
+ import { buildSyncedFileMap, hasProjectConfigInDir, writeProjectConfig, } from '../config/project.js';
7
+ import { PROJECT_CONFIG_FILENAME } from '../constants.js';
8
+ import { CliError } from '../errors.js';
9
+ import { isDirectoryNonEmpty } from '../sync/fs.js';
10
+ import { buildPenInfoConfigFields } from '../sync/info.js';
11
+ import { syncRemoteFilesToDisk } from '../sync/materialize.js';
12
+ import { extractCodePenOwnerFromUrl, normalizePenReference, suggestFolderName, } from '../utils/codepen-url.js';
13
+ import { fmt, shortId } from '../utils/format.js';
14
+ import { printJsonResponse } from '../utils/json.js';
15
+ import { defaultOutput } from '../utils/output.js';
16
+ import { isInteractive, promptConfirm, promptSecret, promptSelect, promptText, } from '../utils/prompts/index.js';
17
+ import { resolveCommandAuth } from './auth-context.js';
18
+ import { handleClassicPenClone, resolveCurrentUsername } from './classic-convert.js';
19
+ import { findUnmatchedStoredOwner, handlePenNotFoundOnFetch, handleUnownedPenAccess, } from './unowned-pen.js';
20
+ async function ensureCloneTargetReady(targetDir, folderDisplay, options) {
21
+ try {
22
+ const stat = await fs.lstat(targetDir);
23
+ if (!stat.isDirectory()) {
24
+ throw new CliError(409, `Target path ${targetDir} already exists and is not a directory.`);
25
+ }
26
+ }
27
+ catch (error) {
28
+ if (error.code === 'ENOENT') {
29
+ return true;
30
+ }
31
+ throw error;
32
+ }
33
+ const [hasExistingConfig, nonEmpty] = await Promise.all([
34
+ hasProjectConfigInDir(targetDir),
35
+ isDirectoryNonEmpty(targetDir),
36
+ ]);
37
+ if ((nonEmpty || hasExistingConfig) && !options.force) {
38
+ if (!options.interactive) {
39
+ throw new CliError(409, `Target directory ${targetDir} is not empty. Pass --force to overwrite.`);
40
+ }
41
+ const ok = await options.confirmImpl(`Directory ${fmt.bold(folderDisplay)} already exists and is not empty. Continue and overwrite matching files?`, false);
42
+ if (!ok) {
43
+ options.output.log('Aborted.');
44
+ return false;
45
+ }
46
+ }
47
+ return true;
48
+ }
49
+ /**
50
+ * Clones an existing CodePen Pen into a local folder.
51
+ *
52
+ * When the Pen's owner does not match the current authenticated account, offers to fork it
53
+ * instead (interactively, via the optional `forkUnowned` hook). If not forked, downloads files
54
+ * locally without writing `.cdpn.json` so the local folder is not linked to an online Pen owned
55
+ * by another user.
56
+ *
57
+ * When the Pen is a Classic (v1) Pen (read-only through CodePen API v2), interactively offers
58
+ * a choice to open it in the browser to convert to CodePen 2.0 first (waiting to re-fetch or
59
+ * accept the new 2.0 URL for a linked clone) or to clone it locally without writing `.cdpn.json`.
60
+ *
61
+ * Returns `null` if the user cancels interactively.
62
+ */
63
+ export async function clonePenWorkflow(options) {
64
+ const output = options.output ?? defaultOutput;
65
+ const cwd = path.resolve(options.cwd ?? process.cwd());
66
+ const jsonMode = Boolean(options.json);
67
+ const interactive = (options.interactive ?? isInteractive()) && !jsonMode;
68
+ const force = Boolean(options.force);
69
+ const textImpl = options.prompts?.text ?? promptText;
70
+ const confirmImpl = options.prompts?.confirm ?? promptConfirm;
71
+ const secretImpl = options.prompts?.secret ?? promptSecret;
72
+ const selectImpl = options.prompts?.select ?? promptSelect;
73
+ const { apiIdentifier, originalUrl } = normalizePenReference(options.urlArg);
74
+ // If target folder was passed explicitly, validate before hitting the network
75
+ let targetFolderDisplay = options.folderArg?.trim() || '';
76
+ let targetDir = null;
77
+ if (targetFolderDisplay) {
78
+ targetDir = path.resolve(cwd, targetFolderDisplay);
79
+ const ready = await ensureCloneTargetReady(targetDir, targetFolderDisplay, {
80
+ force,
81
+ interactive,
82
+ output,
83
+ confirmImpl,
84
+ });
85
+ if (!ready) {
86
+ return null;
87
+ }
88
+ }
89
+ const unmatched = await findUnmatchedStoredOwner({
90
+ originalUrl,
91
+ explicitProfile: options.explicitProfile,
92
+ env: options.env,
93
+ homeDir: options.homeDir,
94
+ });
95
+ if (unmatched && originalUrl) {
96
+ const pastedUrl = await handleUnownedPenAccess({
97
+ action: 'clone',
98
+ penUrl: originalUrl,
99
+ urlOwner: unmatched.urlOwner,
100
+ availableProfiles: unmatched.availableProfiles,
101
+ interactive,
102
+ allowBrowserFallback: options.allowBrowserFallback,
103
+ output,
104
+ confirmImpl,
105
+ textImpl,
106
+ openBrowserImpl: options.openBrowser,
107
+ });
108
+ if (!pastedUrl) {
109
+ return null;
110
+ }
111
+ return clonePenWorkflow({
112
+ ...options,
113
+ urlArg: pastedUrl,
114
+ explicitProfile: undefined,
115
+ allowBrowserFallback: false,
116
+ });
117
+ }
118
+ let auth = await resolveCommandAuth({
119
+ explicitProfile: options.explicitProfile,
120
+ urlHint: originalUrl ?? options.urlArg,
121
+ autoSelectUrlMatch: true,
122
+ promptMessage: 'Which CodePen profile should be used for this Pen?',
123
+ interactive,
124
+ output,
125
+ env: options.env,
126
+ homeDir: options.homeDir,
127
+ selectProfile: selectImpl,
128
+ });
129
+ let client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
130
+ if (!jsonMode &&
131
+ !options.explicitProfile &&
132
+ auth.source === 'file' &&
133
+ auth.profile &&
134
+ auth.availableProfiles.length > 1 &&
135
+ findMatchingProfile(auth.availableProfiles, originalUrl ?? options.urlArg) === auth.profile) {
136
+ output.log(fmt.dim(`Using profile "${auth.profile}" (matches Pen owner).`));
137
+ }
138
+ if (!jsonMode) {
139
+ output.log(`Fetching Pen ${fmt.cyan(apiIdentifier)}…`);
140
+ }
141
+ let pen;
142
+ try {
143
+ pen = await client.getPen(apiIdentifier);
144
+ }
145
+ catch (error) {
146
+ if (error instanceof CodePenApiError && error.status === 404) {
147
+ const pastedUrl = await handlePenNotFoundOnFetch({
148
+ action: 'clone',
149
+ apiIdentifier,
150
+ originalUrl,
151
+ auth,
152
+ client,
153
+ interactive,
154
+ allowBrowserFallback: options.allowBrowserFallback,
155
+ output,
156
+ confirmImpl,
157
+ textImpl,
158
+ openBrowserImpl: options.openBrowser,
159
+ });
160
+ if (!pastedUrl) {
161
+ return null;
162
+ }
163
+ return clonePenWorkflow({
164
+ ...options,
165
+ urlArg: pastedUrl,
166
+ explicitProfile: undefined,
167
+ allowBrowserFallback: false,
168
+ });
169
+ }
170
+ throw error;
171
+ }
172
+ // Check whether this Pen belongs to a stored profile (handles Pen IDs / preview URLs without an owner in the input)
173
+ let penOwner = extractCodePenOwnerFromUrl(pen.urls.editor) ??
174
+ (originalUrl ? extractCodePenOwnerFromUrl(originalUrl) : null);
175
+ if (penOwner &&
176
+ !options.explicitProfile &&
177
+ auth.source === 'file' &&
178
+ auth.profile?.toLowerCase() !== penOwner.toLowerCase()) {
179
+ const matchedStoredProfile = findMatchingProfile(auth.availableProfiles, pen.urls.editor);
180
+ if (matchedStoredProfile && matchedStoredProfile !== auth.profile) {
181
+ auth = await resolveCommandAuth({
182
+ explicitProfile: matchedStoredProfile,
183
+ interactive,
184
+ output,
185
+ env: options.env,
186
+ homeDir: options.homeDir,
187
+ });
188
+ client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
189
+ if (!jsonMode) {
190
+ output.log(fmt.dim(`Using profile "${matchedStoredProfile}" (matches Pen owner).`));
191
+ }
192
+ }
193
+ }
194
+ let currentUsername = penOwner ? await resolveCurrentUsername(client, auth, penOwner) : null;
195
+ let isOwnedByAnotherUser = Boolean(penOwner && currentUsername && penOwner.toLowerCase() !== currentUsername.toLowerCase());
196
+ let effectiveUrl = originalUrl ?? pen.urls.editor;
197
+ if (isOwnedByAnotherUser && penOwner && currentUsername) {
198
+ if (!jsonMode) {
199
+ output.log(fmt.yellow(`\nThis Pen belongs to ${fmt.bold(penOwner)} (your current account is ${fmt.bold(currentUsername)}).`));
200
+ }
201
+ if (interactive && options.forkUnowned) {
202
+ const shouldFork = await confirmImpl(`Fork this Pen under ${currentUsername} instead?`, true);
203
+ if (shouldFork) {
204
+ const forkedResult = await options.forkUnowned({
205
+ urlArg: options.urlArg,
206
+ folderArg: options.folderArg,
207
+ cwd,
208
+ resolvedAuth: auth,
209
+ sourcePen: pen,
210
+ allowOverwrite: Boolean(targetDir),
211
+ output,
212
+ baseUrl: options.baseUrl,
213
+ interactive,
214
+ env: options.env,
215
+ homeDir: options.homeDir,
216
+ openBrowser: options.openBrowser,
217
+ prompts: {
218
+ text: textImpl,
219
+ confirm: confirmImpl,
220
+ select: selectImpl,
221
+ secret: secretImpl,
222
+ },
223
+ });
224
+ if (!forkedResult) {
225
+ return null;
226
+ }
227
+ return {
228
+ pen: forkedResult.pen,
229
+ sourcePen: forkedResult.sourcePen ?? undefined,
230
+ rootDir: forkedResult.project.rootDir,
231
+ writtenPaths: forkedResult.writtenPaths,
232
+ auth: forkedResult.auth,
233
+ forked: true,
234
+ linked: true,
235
+ project: forkedResult.project,
236
+ ...(forkedResult.exitCode !== undefined ? { exitCode: forkedResult.exitCode } : {}),
237
+ };
238
+ }
239
+ }
240
+ }
241
+ if (pen.editor === 'Classic' && !isOwnedByAnotherUser && interactive) {
242
+ const classicResolution = await handleClassicPenClone({
243
+ pen,
244
+ apiIdentifier,
245
+ effectiveUrl,
246
+ auth,
247
+ client,
248
+ explicitProfile: options.explicitProfile,
249
+ baseUrl: options.baseUrl,
250
+ env: options.env,
251
+ homeDir: options.homeDir,
252
+ openBrowserImpl: options.openBrowser,
253
+ output,
254
+ selectImpl,
255
+ textImpl,
256
+ });
257
+ if (classicResolution.action === 'cancel') {
258
+ return null;
259
+ }
260
+ pen = classicResolution.pen;
261
+ effectiveUrl = classicResolution.effectiveUrl;
262
+ auth = classicResolution.auth;
263
+ client = classicResolution.client;
264
+ isOwnedByAnotherUser = classicResolution.isOwnedByAnotherUser;
265
+ penOwner = classicResolution.penOwner;
266
+ currentUsername = classicResolution.currentUsername;
267
+ }
268
+ if (!targetDir) {
269
+ const defaultFolder = suggestFolderName(pen);
270
+ if (interactive) {
271
+ const chosen = (await textImpl('Target folder', defaultFolder)).trim();
272
+ targetFolderDisplay = chosen || defaultFolder;
273
+ }
274
+ else {
275
+ targetFolderDisplay = defaultFolder;
276
+ }
277
+ targetDir = path.resolve(cwd, targetFolderDisplay);
278
+ const ready = await ensureCloneTargetReady(targetDir, targetFolderDisplay, {
279
+ force,
280
+ interactive,
281
+ output,
282
+ confirmImpl,
283
+ });
284
+ if (!ready) {
285
+ return null;
286
+ }
287
+ }
288
+ const remoteFiles = await client.getPenFiles(pen.id);
289
+ const result = await syncRemoteFilesToDisk({
290
+ client,
291
+ rootDir: targetDir,
292
+ remoteFiles,
293
+ pruneRemoved: false,
294
+ });
295
+ const isUnlinked = isOwnedByAnotherUser || pen.editor === 'Classic';
296
+ if (isUnlinked) {
297
+ if (jsonMode) {
298
+ printJsonResponse(200, `Cloned ${pen.title || 'Untitled'} into ${targetFolderDisplay} (unlinked local copy).`, {
299
+ pen,
300
+ linked: false,
301
+ forked: false,
302
+ profile: auth.profile,
303
+ folder: targetFolderDisplay,
304
+ root_dir: targetDir,
305
+ config_path: null,
306
+ version_id: pen.saved_version?.id ?? null,
307
+ written_paths: result.writtenPaths,
308
+ }, output);
309
+ }
310
+ else {
311
+ output.log(`\n${fmt.green('✓')} Cloned ${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)} into ${fmt.cyan(targetFolderDisplay)} ${fmt.dim('(unlinked local copy)')}`);
312
+ output.log(` Source: ${fmt.dim(effectiveUrl)}`);
313
+ output.log(` Files: ${result.writtenPaths.length} downloaded`);
314
+ if (isOwnedByAnotherUser) {
315
+ output.log(fmt.yellow(`\nNote: No ${PROJECT_CONFIG_FILENAME} was created because this Pen belongs to ${penOwner}, not ${currentUsername}.\n` +
316
+ `Run \`cdpn push\` inside ${targetFolderDisplay} later to publish it as a new Pen under your account, or \`cdpn fork ${effectiveUrl}\` to fork it on CodePen.`));
317
+ }
318
+ else {
319
+ output.log(fmt.yellow(`\nNote: No ${PROJECT_CONFIG_FILENAME} was created because this is a Classic (v1) Pen (read-only through CodePen API v2).\n` +
320
+ `Run \`cdpn push\` inside ${targetFolderDisplay} later to publish it as a new CodePen 2.0 Pen, or convert it to 2.0 on CodePen via the Save button dropdown and re-clone.`));
321
+ }
322
+ }
323
+ return {
324
+ pen,
325
+ rootDir: targetDir,
326
+ writtenPaths: result.writtenPaths,
327
+ auth,
328
+ forked: false,
329
+ linked: false,
330
+ project: null,
331
+ };
332
+ }
333
+ const syncedFiles = buildSyncedFileMap(remoteFiles, result.localSha256ByPath);
334
+ const config = {
335
+ url: effectiveUrl,
336
+ pen_id: pen.id,
337
+ ...(auth.profile ? { profile: auth.profile } : {}),
338
+ last_synced_version_id: pen.saved_version?.id ?? null,
339
+ editor: pen.editor,
340
+ ...buildPenInfoConfigFields(pen),
341
+ files: syncedFiles,
342
+ };
343
+ const configPath = await writeProjectConfig(targetDir, config);
344
+ if (jsonMode) {
345
+ printJsonResponse(200, `Cloned ${pen.title || 'Untitled'} into ${targetFolderDisplay}.`, {
346
+ pen,
347
+ linked: true,
348
+ forked: false,
349
+ profile: auth.profile,
350
+ folder: targetFolderDisplay,
351
+ root_dir: targetDir,
352
+ config_path: configPath,
353
+ version_id: pen.saved_version?.id ?? null,
354
+ written_paths: result.writtenPaths,
355
+ }, output);
356
+ }
357
+ else {
358
+ output.log(`\n${fmt.green('✓')} Cloned ${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)} into ${fmt.cyan(targetFolderDisplay)}`);
359
+ if (auth.profile) {
360
+ output.log(` Profile: ${fmt.cyan(auth.profile)}`);
361
+ }
362
+ output.log(` Files: ${result.writtenPaths.length} downloaded`);
363
+ if (pen.saved_version) {
364
+ output.log(` Version: ${fmt.dim(shortId(pen.saved_version.id))}`);
365
+ }
366
+ output.log(` Config: ${fmt.dim(path.join(targetFolderDisplay, PROJECT_CONFIG_FILENAME))}`);
367
+ }
368
+ return {
369
+ pen,
370
+ rootDir: targetDir,
371
+ writtenPaths: result.writtenPaths,
372
+ auth,
373
+ forked: false,
374
+ linked: true,
375
+ project: {
376
+ rootDir: targetDir,
377
+ configPath,
378
+ config,
379
+ },
380
+ };
381
+ }
@@ -1,70 +1,52 @@
1
1
  import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { CodePenClient } from '../api/client.js';
4
- import { buildSyncedFileMap, hasProjectConfigInDir, PROJECT_CONFIG_FILENAME, readProjectConfigFile, writeProjectConfig, } from '../config/project.js';
4
+ import { buildSyncedFileMap, hasProjectConfigInDir, readProjectConfigFile, writeProjectConfig, } from '../config/project.js';
5
+ import { MAX_PEN_TAGS, MIN_PROTECTED_PASSWORD_LENGTH, PEN_ACCESS_CHOICES, PROJECT_CONFIG_FILENAME, } from '../constants.js';
6
+ import { CliError } from '../errors.js';
5
7
  import { scanLocalFiles } from '../sync/fs.js';
6
8
  import { buildPenInfoConfigFields, hasAnyPenInfoFields } from '../sync/info.js';
7
9
  import { syncRemoteFilesToDisk } from '../sync/materialize.js';
10
+ import { assertValidProtectedPassword, normalizeAccess, resolveAccessOrVisibility, } from '../utils/cli-options.js';
8
11
  import { fmt, printBuildSummary, shortId } from '../utils/format.js';
9
12
  import { extractHtmlTitle } from '../utils/html.js';
10
- import { CliError } from '../utils/json.js';
11
- import { isInteractive, promptConfirm, promptSecret, promptSelect, promptText, } from '../utils/prompts.js';
13
+ import { defaultOutput } from '../utils/output.js';
14
+ import { isInteractive, promptConfirm, promptSecret, promptSelect, promptText, } from '../utils/prompts/index.js';
12
15
  import { resolveCommandAuth } from './auth-context.js';
13
- const VALID_ACCESS = new Set(['public', 'private', 'protected', 'collaborators']);
14
- export function normalizeAccess(raw) {
15
- if (!raw)
16
- return undefined;
17
- const lower = raw.trim().toLowerCase();
18
- if (!VALID_ACCESS.has(lower)) {
19
- throw new CliError(400, `Invalid access level "${raw}". Use: Public, Private, Protected, or Collaborators.`);
20
- }
21
- return (lower[0].toUpperCase() + lower.slice(1));
22
- }
16
+ export { normalizeAccess };
23
17
  /**
24
18
  * Validates or interactively prompts for Pen visibility (`Public` default, `Private`,
25
19
  * `Protected`, or `Collaborators`) and password when `Protected` is chosen.
26
20
  */
27
21
  export async function resolveVisibilityAndPassword(options) {
22
+ const output = options.output ?? defaultOutput;
28
23
  const selectImpl = options.prompts?.select ?? promptSelect;
29
24
  const secretImpl = options.prompts?.secret ?? promptSecret;
30
- let access = normalizeAccess(options.rawAccess);
31
- if (access === 'Protected' && options.rawPassword !== undefined && options.rawPassword.length < 8) {
32
- throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
33
- }
34
- if (access === 'Protected' && !options.rawPassword && !options.interactive) {
35
- throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
36
- }
25
+ let access = resolveAccessOrVisibility(options.rawAccess, options.rawVisibility);
26
+ assertValidProtectedPassword(access, options.rawPassword, options.interactive);
37
27
  if (!access) {
38
28
  if (options.interactive) {
39
- access = await selectImpl('Pen visibility:', [
40
- { value: 'Public', label: 'Public', description: 'visible to everyone (default)' },
41
- { value: 'Private', label: 'Private', description: 'visible only to you / your team' },
42
- {
43
- value: 'Protected',
44
- label: 'Protected',
45
- description: 'password-protected (min 8 characters)',
46
- },
47
- {
48
- value: 'Collaborators',
49
- label: 'Collaborators',
50
- description: 'visible only to you and collaborators',
51
- },
52
- ], 0);
29
+ const choices = PEN_ACCESS_CHOICES.map((c) => ({
30
+ value: c.value,
31
+ label: c.label,
32
+ description: c.value === 'Public' ? `${c.description} (default)` : c.description,
33
+ }));
34
+ access = await selectImpl('Pen visibility:', choices, 0);
53
35
  }
54
36
  else {
55
37
  access = 'Public';
56
38
  }
57
39
  }
58
40
  let password = options.rawPassword;
59
- if (access === 'Protected' && (!password || password.length < 8)) {
41
+ if (access === 'Protected' && (!password || password.length < MIN_PROTECTED_PASSWORD_LENGTH)) {
60
42
  if (!options.interactive) {
61
- throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
43
+ assertValidProtectedPassword(access, password, false);
62
44
  }
63
45
  for (;;) {
64
- password = await secretImpl('Password for Protected Pen (min 8 characters)');
65
- if (password.length >= 8)
46
+ password = await secretImpl(`Password for Protected Pen (min ${MIN_PROTECTED_PASSWORD_LENGTH} characters)`);
47
+ if (password.length >= MIN_PROTECTED_PASSWORD_LENGTH)
66
48
  break;
67
- console.log(fmt.yellow('Password must be at least 8 characters.'));
49
+ output.log(fmt.yellow(`Password must be at least ${MIN_PROTECTED_PASSWORD_LENGTH} characters.`));
68
50
  }
69
51
  }
70
52
  return {
@@ -72,44 +54,40 @@ export async function resolveVisibilityAndPassword(options) {
72
54
  ...(access === 'Protected' && password ? { password } : {}),
73
55
  };
74
56
  }
75
- export function printMissingIndexHtmlWarning(targetDir, fileCount) {
57
+ export function printMissingIndexHtmlWarning(targetDir, fileCount, output = defaultOutput) {
76
58
  const headline = ' WARNING: No index.html found in this folder! ';
77
59
  const border = '═'.repeat(headline.length);
78
- console.log('');
79
- console.log(fmt.yellow(fmt.bold(`╔${border}╗`)));
80
- console.log(fmt.yellow(fmt.bold(`║${headline}║`)));
81
- console.log(fmt.yellow(fmt.bold(`╚${border}╝`)));
82
- console.log(fmt.yellow(`CodePen expects an index.html file at the root of your demo.\n` +
60
+ output.log('');
61
+ output.log(fmt.yellow(fmt.bold(`╔${border}╗`)));
62
+ output.log(fmt.yellow(fmt.bold(`║${headline}║`)));
63
+ output.log(fmt.yellow(fmt.bold(`╚${border}╝`)));
64
+ output.log(fmt.yellow(`CodePen expects an index.html file at the root of your demo.\n` +
83
65
  `Double-check that you are in the right folder before pushing:\n` +
84
66
  ` Folder: ${targetDir} (${fileCount} file(s) found)`));
85
- console.log('');
67
+ output.log('');
86
68
  }
87
69
  /**
88
70
  * First-time Pen creation flow used by `cdpn push` and `cdpn deploy` when invoked inside
89
71
  * an unlinked local demo folder (including one with retained `info` in `.cdpn.json` from
90
- * `cdpn delete --keep-info`):
72
+ * `cdpn delete --cleanup`):
91
73
  *
92
74
  * 1. Checks for `/index.html`; if absent, displays a prominent warning and asks for confirmation.
93
75
  * 2. Resolves or asks which CodePen account/profile to push to (when multiple keys are in `~/.cdpn`).
94
76
  * 3. Uses retained `info.title` (or `--title`), otherwise asks for a title (pre-filled from `index.html`'s `<title>`).
95
- * 4. Uses retained `info.access` (or `--access`), otherwise asks for visibility (`Public` default, `Private`,
96
- * `Protected`, or `Collaborators`), prompting for a password if `Protected`.
77
+ * 4. Uses retained `info.access` (or `--access`/`--visibility`), otherwise asks for visibility (`Public` default,
78
+ * `Private`, `Protected`, or `Collaborators`), prompting for a password if `Protected`.
97
79
  * 5. Carries over retained `description`, `tags`, and `template` from `.cdpn.json` when present.
98
80
  */
99
81
  export async function createPenFromDirectory(options) {
82
+ const output = options.output ?? defaultOutput;
100
83
  const silent = Boolean(options.silent);
101
84
  const interactive = silent ? false : (options.interactive ?? isInteractive());
102
85
  const confirmImpl = options.prompts?.confirm ?? promptConfirm;
103
86
  const textImpl = options.prompts?.text ?? promptText;
104
87
  const selectImpl = options.prompts?.select ?? promptSelect;
105
- // Validate explicit CLI --access / --password early before reading config or scanning
106
- const explicitAccess = normalizeAccess(options.access);
107
- if (explicitAccess === 'Protected' && options.password !== undefined && options.password.length < 8) {
108
- throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
109
- }
110
- if (explicitAccess === 'Protected' && !options.password && !interactive) {
111
- throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
112
- }
88
+ // Validate explicit CLI --access / --visibility / --password early before reading config or scanning
89
+ const explicitAccess = resolveAccessOrVisibility(options.access, options.visibility);
90
+ assertValidProtectedPassword(explicitAccess, options.password, interactive);
113
91
  const targetDir = path.resolve(options.targetDir);
114
92
  const folderDisplay = options.folderDisplay;
115
93
  let retainedInfo;
@@ -120,21 +98,15 @@ export async function createPenFromDirectory(options) {
120
98
  }
121
99
  retainedInfo = existing.config.info;
122
100
  }
123
- const effectiveRawAccess = options.access ?? retainedInfo?.access;
124
- const effectiveAccess = normalizeAccess(effectiveRawAccess);
101
+ const effectiveAccess = explicitAccess ?? normalizeAccess(retainedInfo?.access);
125
102
  const effectiveDescription = options.description !== undefined ? options.description : retainedInfo?.description;
126
103
  const effectiveTags = options.tags !== undefined ? options.tags : retainedInfo?.tags;
127
104
  const effectiveTemplate = options.template !== undefined ? options.template : retainedInfo?.template;
128
105
  // Validate effective metadata constraints early before scanning or prompting
129
- if (effectiveTags && effectiveTags.length > 5) {
130
- throw new CliError(400, `CodePen allows at most 5 tags per Pen (found ${effectiveTags.length}${options.tags === undefined ? ` in ${PROJECT_CONFIG_FILENAME}` : ''}).`);
131
- }
132
- if (effectiveAccess === 'Protected' && options.password !== undefined && options.password.length < 8) {
133
- throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
134
- }
135
- if (effectiveAccess === 'Protected' && !options.password && !interactive) {
136
- throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
106
+ if (effectiveTags && effectiveTags.length > MAX_PEN_TAGS) {
107
+ throw new CliError(400, `CodePen allows at most ${MAX_PEN_TAGS} tags per Pen (found ${effectiveTags.length}${options.tags === undefined ? ` in ${PROJECT_CONFIG_FILENAME}` : ''}).`);
137
108
  }
109
+ assertValidProtectedPassword(effectiveAccess, options.password, interactive);
138
110
  const scanned = await scanLocalFiles(targetDir);
139
111
  if (scanned.size === 0) {
140
112
  throw new CliError(400, retainedInfo !== undefined
@@ -146,7 +118,7 @@ export async function createPenFromDirectory(options) {
146
118
  // 1. Check for index.html before pushing a local demo for the first time
147
119
  if (!indexFile) {
148
120
  if (!silent) {
149
- printMissingIndexHtmlWarning(targetDir, scanned.size);
121
+ printMissingIndexHtmlWarning(targetDir, scanned.size, output);
150
122
  }
151
123
  if (!options.force) {
152
124
  if (!interactive) {
@@ -154,7 +126,7 @@ export async function createPenFromDirectory(options) {
154
126
  }
155
127
  const ok = await confirmImpl('Are you sure you want to push this folder without an index.html?', false);
156
128
  if (!ok) {
157
- console.log('Aborted.');
129
+ output.log('Aborted.');
158
130
  return null;
159
131
  }
160
132
  }
@@ -164,6 +136,7 @@ export async function createPenFromDirectory(options) {
164
136
  explicitProfile: options.explicitProfile,
165
137
  promptMessage: 'Which CodePen account/profile would you like to push to?',
166
138
  interactive,
139
+ output,
167
140
  env: options.env,
168
141
  homeDir: options.homeDir,
169
142
  selectProfile: selectImpl,
@@ -184,11 +157,12 @@ export async function createPenFromDirectory(options) {
184
157
  title = defaultTitle;
185
158
  }
186
159
  }
187
- // 4. Resolve visibility (explicit --access > retained info.access > interactive picker / Public default)
160
+ // 4. Resolve visibility (explicit --access/--visibility > retained info.access > interactive picker / Public default)
188
161
  const { access, password } = await resolveVisibilityAndPassword({
189
- rawAccess: effectiveRawAccess,
162
+ rawAccess: effectiveAccess,
190
163
  rawPassword: options.password,
191
164
  interactive,
165
+ output,
192
166
  prompts: options.prompts,
193
167
  });
194
168
  const textFiles = [];
@@ -204,9 +178,9 @@ export async function createPenFromDirectory(options) {
204
178
  const shouldWait = options.wait !== false;
205
179
  if (!silent) {
206
180
  if (hasAnyPenInfoFields(retainedInfo)) {
207
- console.log(fmt.dim(`Using saved Pen info from ${PROJECT_CONFIG_FILENAME}.`));
181
+ output.log(fmt.dim(`Using saved Pen info from ${PROJECT_CONFIG_FILENAME}.`));
208
182
  }
209
- console.log(`\nCreating new Pen from ${textFiles.length + binaryFiles.length} local file(s)…`);
183
+ output.log(`\nCreating new Pen from ${textFiles.length + binaryFiles.length} local file(s)…`);
210
184
  }
211
185
  const created = await client.createPen({
212
186
  ...(title ? { title } : {}),
@@ -222,7 +196,7 @@ export async function createPenFromDirectory(options) {
222
196
  if (finalBuild && shouldWait) {
223
197
  finalBuild = await client.settleBuild(finalBuild);
224
198
  if (!silent) {
225
- printBuildSummary(finalBuild);
199
+ printBuildSummary(finalBuild, output);
226
200
  }
227
201
  }
228
202
  await fs.mkdir(targetDir, { recursive: true });
@@ -246,24 +220,24 @@ export async function createPenFromDirectory(options) {
246
220
  files: buildSyncedFileMap(remoteFiles, materialized.localSha256ByPath),
247
221
  };
248
222
  const configPath = await writeProjectConfig(targetDir, config);
249
- if (finalBuild?.status === 'Failed') {
223
+ const buildFailed = finalBuild?.status === 'Failed';
224
+ if (buildFailed) {
250
225
  if (!silent) {
251
- console.log(`\n${fmt.yellow('!')} Created Pen ${fmt.bold(created.title || 'Untitled')} ${fmt.dim(`(${created.id})`)}, but the initial build failed.`);
226
+ output.log(`\n${fmt.yellow('!')} Created Pen ${fmt.bold(created.title || 'Untitled')} ${fmt.dim(`(${created.id})`)}, but the initial build failed.`);
252
227
  }
253
- process.exitCode = 1;
254
228
  }
255
229
  else if (!silent) {
256
- console.log(`\n${fmt.green('✓')} Created Pen ${fmt.bold(created.title || 'Untitled')} ${fmt.dim(`(${created.id})`)}`);
230
+ output.log(`\n${fmt.green('✓')} Created Pen ${fmt.bold(created.title || 'Untitled')} ${fmt.dim(`(${created.id})`)}`);
257
231
  }
258
232
  if (!silent) {
259
233
  if (auth.profile) {
260
- console.log(` Profile: ${fmt.cyan(auth.profile)}`);
234
+ output.log(` Profile: ${fmt.cyan(auth.profile)}`);
261
235
  }
262
- console.log(` Visibility: ${created.access}`);
263
- console.log(` Folder: ${fmt.cyan(folderDisplay)}`);
264
- console.log(` Editor: ${fmt.cyan(created.urls.editor)}`);
265
- console.log(` Preview: ${fmt.cyan(created.urls.preview)}`);
266
- console.log(` Version: ${fmt.dim(shortId(finalVersionId))}`);
236
+ output.log(` Visibility: ${created.access}`);
237
+ output.log(` Folder: ${fmt.cyan(folderDisplay)}`);
238
+ output.log(` Editor: ${fmt.cyan(created.urls.editor)}`);
239
+ output.log(` Preview: ${fmt.cyan(created.urls.preview)}`);
240
+ output.log(` Version: ${fmt.dim(shortId(finalVersionId))}`);
267
241
  }
268
242
  return {
269
243
  pen: created,
@@ -275,5 +249,6 @@ export async function createPenFromDirectory(options) {
275
249
  configPath,
276
250
  config,
277
251
  },
252
+ ...(buildFailed ? { exitCode: 1 } : {}),
278
253
  };
279
254
  }