codepen-commander 1.0.0 → 1.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.
package/README.md CHANGED
@@ -123,7 +123,7 @@ All commands accept the global `--profile <name>` flag to override the active pr
123
123
  | `cdpn auth logout [profile] [--all] [--json]` | Remove a specific profile or delete `~/.cdpn` completely |
124
124
  | `cdpn new [folder] [--template <id\|url\|title>] [--as-template] [--json]` | Scaffold a brand-new 2.0 Pen from a CodePen Template (or CodePen default starter) into a new or empty folder |
125
125
  | `cdpn fork <url> [folder] [--title ...] [--access ...] [--json]` | Fork one of your own 2.0 Pens into a local folder (for other users' Pens, offers to open in browser to fork and clone back) |
126
- | `cdpn clone <url> [folder] [--force] [--json]` | Clone a CodePen Pen into a local folder (auto-matches stored profile by URL owner; offers browser fork-and-clone fallback for unowned Pens) |
126
+ | `cdpn clone <url> [folder] [--force] [--json]` | Clone a CodePen Pen into a local folder (auto-matches stored profile by URL owner; offers to convert Classic Pens or clone them unlinked; offers browser fork-and-clone fallback for unowned Pens) |
127
127
  | `cdpn pull [--force] [--json]` | Pull latest remote changes into an existing cloned folder (requires `.cdpn.json`) |
128
128
  | `cdpn status [--json]` | Show active profile, file diffs (added/modified/deleted), remote head, build & deployment status |
129
129
  | `cdpn push [-m <label>] [--force] [--dry-run] [--no-wait] [--json]` | Push local changes (text & binary + deletions), or push an unlinked local demo folder as a new Pen (checks `index.html`, asks account, title, and visibility) |
package/commands/clone.js CHANGED
@@ -6,12 +6,52 @@ import { DEFAULT_PROFILE_NAME, findMatchingProfile } from '../config/auth.js';
6
6
  import { buildSyncedFileMap, extractCodePenOwnerFromUrl, hasProjectConfigInDir, normalizePenReference, PROJECT_CONFIG_FILENAME, suggestFolderName, writeProjectConfig, } from '../config/project.js';
7
7
  import { isDirectoryNonEmpty } from '../sync/fs.js';
8
8
  import { syncRemoteFilesToDisk } from '../sync/materialize.js';
9
+ import { openBrowser, validateBrowserUrl } from '../utils/browser.js';
9
10
  import { fmt, shortId } from '../utils/format.js';
10
11
  import { CliError, printJsonResponse } from '../utils/json.js';
11
12
  import { isInteractive, promptConfirm, promptSecret, promptSelect, promptText, } from '../utils/prompts.js';
12
13
  import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
13
14
  import { forkPenCommand } from './fork.js';
14
15
  import { findUnmatchedStoredOwner, handlePenNotFoundOnFetch, handleUnownedPenAccess, } from './unowned-pen.js';
16
+ function validateEditorBrowserUrl(rawUrl) {
17
+ let candidate = rawUrl.trim();
18
+ try {
19
+ const parsed = new URL(candidate);
20
+ if (parsed.protocol === 'http:') {
21
+ parsed.protocol = 'https:';
22
+ }
23
+ candidate = parsed.toString();
24
+ }
25
+ catch {
26
+ // Let validateBrowserUrl throw a clean validation error
27
+ }
28
+ const safeUrl = validateBrowserUrl(candidate);
29
+ const host = new URL(safeUrl).hostname.toLowerCase();
30
+ const isCodePenHost = host === 'codepen.io' || host.endsWith('.codepen.io');
31
+ if (!isCodePenHost) {
32
+ throw new CliError(400, `Refusing to open non-CodePen URL in browser: ${host}`);
33
+ }
34
+ return safeUrl;
35
+ }
36
+ async function promptClassicRetryChoice(selectImpl) {
37
+ return selectImpl('How would you like to proceed?', [
38
+ {
39
+ value: 'retry',
40
+ label: 'Check again / paste 2.0 Pen URL',
41
+ description: 're-fetch after converting or enter the new URL',
42
+ },
43
+ {
44
+ value: 'clone-unlinked',
45
+ label: 'Just clone without linking',
46
+ description: `download files without ${PROJECT_CONFIG_FILENAME}`,
47
+ },
48
+ {
49
+ value: 'cancel',
50
+ label: 'Cancel',
51
+ description: 'abort clone',
52
+ },
53
+ ], 0);
54
+ }
15
55
  async function resolveCurrentUsername(client, auth, penOwner) {
16
56
  // Fast path: named profile already matches the Pen owner
17
57
  if (auth.profile &&
@@ -38,6 +78,162 @@ async function resolveCurrentUsername(client, auth, penOwner) {
38
78
  }
39
79
  return null;
40
80
  }
81
+ async function handleClassicPenClone(params) {
82
+ const { pen, apiIdentifier, effectiveUrl, options, selectImpl, textImpl } = params;
83
+ let currentAuth = params.auth;
84
+ let currentClient = params.client;
85
+ let fallbackPen = pen;
86
+ const makeFallbackResult = (action) => ({
87
+ action,
88
+ pen: fallbackPen,
89
+ effectiveUrl,
90
+ auth: currentAuth,
91
+ client: currentClient,
92
+ isOwnedByAnotherUser: false,
93
+ penOwner: null,
94
+ currentUsername: null,
95
+ });
96
+ console.log(`\n${fmt.yellow('This is a Classic (v1) Pen, which is read-only through CodePen API v2 and cannot be synced.')}`);
97
+ console.log('You can convert it to a CodePen 2.0 Pen in the browser using the dropdown on the Save button.\n');
98
+ const initialChoice = await selectImpl('How would you like to proceed?', [
99
+ {
100
+ value: 'convert',
101
+ label: 'Open the Pen to convert it first',
102
+ description: 'open in browser, then clone linked',
103
+ },
104
+ {
105
+ value: 'clone-unlinked',
106
+ label: 'Just clone without linking',
107
+ description: `download files without ${PROJECT_CONFIG_FILENAME}`,
108
+ },
109
+ ], 0);
110
+ if (initialChoice === 'clone-unlinked') {
111
+ return makeFallbackResult('clone-unlinked');
112
+ }
113
+ const editorUrl = validateEditorBrowserUrl(pen.urls.editor || effectiveUrl);
114
+ const openImpl = options.openBrowser ?? openBrowser;
115
+ const opened = await openImpl(editorUrl);
116
+ if (opened) {
117
+ console.log(`\n${fmt.green('✓')} Opened ${fmt.cyan(editorUrl)} in your browser.`);
118
+ }
119
+ else {
120
+ console.log(`\n${fmt.yellow('!')} Could not launch a browser automatically. Open this URL manually:\n ${fmt.cyan(editorUrl)}`);
121
+ }
122
+ console.log(fmt.dim('In CodePen, use the dropdown on the Save button to convert this Pen to CodePen 2.0.'));
123
+ for (;;) {
124
+ console.log('');
125
+ const pasted = (await textImpl('Press Enter once converted to re-fetch & clone (or paste the new 2.0 Pen URL)')).trim();
126
+ let targetApiId = apiIdentifier;
127
+ let pastedOriginalUrl;
128
+ if (pasted) {
129
+ try {
130
+ const normalized = normalizePenReference(pasted);
131
+ targetApiId = normalized.apiIdentifier;
132
+ pastedOriginalUrl = normalized.originalUrl;
133
+ }
134
+ catch (error) {
135
+ const msg = error instanceof Error ? error.message : String(error);
136
+ console.log(`\n${fmt.yellow('!')} ${msg}\n`);
137
+ const nextAction = await promptClassicRetryChoice(selectImpl);
138
+ if (nextAction === 'retry')
139
+ continue;
140
+ if (nextAction === 'clone-unlinked')
141
+ return makeFallbackResult('clone-unlinked');
142
+ console.log('Aborted.');
143
+ return makeFallbackResult('cancel');
144
+ }
145
+ if (!options.explicitProfile && currentAuth.source === 'file' && pastedOriginalUrl) {
146
+ const matchedProfile = findMatchingProfile(currentAuth.availableProfiles, pastedOriginalUrl);
147
+ if (matchedProfile && matchedProfile !== currentAuth.profile) {
148
+ currentAuth = await resolveCommandAuth({
149
+ explicitProfile: matchedProfile,
150
+ interactive: true,
151
+ env: options.env,
152
+ homeDir: options.homeDir,
153
+ });
154
+ currentClient = new CodePenClient({ apiKey: currentAuth.apiKey, baseUrl: options.baseUrl });
155
+ console.log(fmt.dim(`Using profile "${matchedProfile}" (matches Pen owner).`));
156
+ }
157
+ }
158
+ }
159
+ console.log(`Fetching Pen ${fmt.cyan(targetApiId)}…`);
160
+ let refetched;
161
+ try {
162
+ refetched = await currentClient.getPen(targetApiId);
163
+ }
164
+ catch (error) {
165
+ const msg = error instanceof CodePenApiError
166
+ ? error.formatForUser()
167
+ : error instanceof Error
168
+ ? error.message
169
+ : String(error);
170
+ console.log(`\n${fmt.yellow('!')} Could not fetch Pen ${targetApiId}: ${msg}\n`);
171
+ const nextAction = await promptClassicRetryChoice(selectImpl);
172
+ if (nextAction === 'retry')
173
+ continue;
174
+ if (nextAction === 'clone-unlinked')
175
+ return makeFallbackResult('clone-unlinked');
176
+ console.log('Aborted.');
177
+ return makeFallbackResult('cancel');
178
+ }
179
+ const refetchedOwner = extractCodePenOwnerFromUrl(refetched.urls.editor) ??
180
+ (pastedOriginalUrl ? extractCodePenOwnerFromUrl(pastedOriginalUrl) : null);
181
+ if (refetchedOwner &&
182
+ !options.explicitProfile &&
183
+ currentAuth.source === 'file' &&
184
+ currentAuth.profile?.toLowerCase() !== refetchedOwner.toLowerCase()) {
185
+ const matchedStoredProfile = findMatchingProfile(currentAuth.availableProfiles, refetched.urls.editor);
186
+ if (matchedStoredProfile && matchedStoredProfile !== currentAuth.profile) {
187
+ currentAuth = await resolveCommandAuth({
188
+ explicitProfile: matchedStoredProfile,
189
+ interactive: true,
190
+ env: options.env,
191
+ homeDir: options.homeDir,
192
+ });
193
+ currentClient = new CodePenClient({ apiKey: currentAuth.apiKey, baseUrl: options.baseUrl });
194
+ console.log(fmt.dim(`Using profile "${matchedStoredProfile}" (matches Pen owner).`));
195
+ }
196
+ }
197
+ if (refetched.editor !== 'Classic') {
198
+ const detectedUsername = refetchedOwner
199
+ ? await resolveCurrentUsername(currentClient, currentAuth, refetchedOwner)
200
+ : null;
201
+ const ownedByOther = Boolean(refetchedOwner &&
202
+ detectedUsername &&
203
+ refetchedOwner.toLowerCase() !== detectedUsername.toLowerCase());
204
+ const resolvedUrl = pasted
205
+ ? (pastedOriginalUrl ?? refetched.urls.editor)
206
+ : (refetched.urls.editor || effectiveUrl);
207
+ if (!ownedByOther) {
208
+ console.log(`\n${fmt.green('✓')} Pen is now CodePen 2.0 ${fmt.dim(`(${refetched.id})`)} — continuing linked clone.`);
209
+ }
210
+ return {
211
+ action: ownedByOther ? 'clone-unlinked' : 'clone-linked',
212
+ pen: refetched,
213
+ effectiveUrl: resolvedUrl,
214
+ auth: currentAuth,
215
+ client: currentClient,
216
+ isOwnedByAnotherUser: ownedByOther,
217
+ penOwner: refetchedOwner,
218
+ currentUsername: detectedUsername,
219
+ };
220
+ }
221
+ if (!pasted) {
222
+ fallbackPen = refetched;
223
+ }
224
+ console.log(`\n${fmt.yellow('!')} ${fmt.bold(refetched.title || 'Untitled')} is still a Classic (v1) Pen on CodePen.`);
225
+ console.log(fmt.dim('Make sure you converted it to 2.0 via the Save button dropdown (or paste the new 2.0 Pen URL if CodePen opened a new one).\n'));
226
+ const nextAction = await promptClassicRetryChoice(selectImpl);
227
+ if (nextAction === 'retry') {
228
+ continue;
229
+ }
230
+ if (nextAction === 'clone-unlinked') {
231
+ return makeFallbackResult('clone-unlinked');
232
+ }
233
+ console.log('Aborted.');
234
+ return makeFallbackResult('cancel');
235
+ }
236
+ }
41
237
  async function ensureCloneTargetReady(targetDir, folderDisplay, options) {
42
238
  try {
43
239
  const stat = await fs.lstat(targetDir);
@@ -74,6 +270,10 @@ async function ensureCloneTargetReady(targetDir, folderDisplay, options) {
74
270
  * instead (interactively). If not forked, downloads files locally without writing `.cdpn.json`
75
271
  * so the local folder is not linked to an online Pen owned by another user.
76
272
  *
273
+ * When the Pen is a Classic (v1) Pen (read-only through CodePen API v2), interactively offers
274
+ * a choice to open it in the browser to convert to CodePen 2.0 first (waiting to re-fetch or
275
+ * accept the new 2.0 URL for a linked clone) or to clone it locally without writing `.cdpn.json`.
276
+ *
77
277
  * Returns `null` if the user cancels interactively.
78
278
  */
79
279
  export async function clonePenCommand(options) {
@@ -181,7 +381,7 @@ export async function clonePenCommand(options) {
181
381
  throw error;
182
382
  }
183
383
  // Check whether this Pen belongs to a stored profile (handles Pen IDs / preview URLs without an owner in the input)
184
- const penOwner = extractCodePenOwnerFromUrl(pen.urls.editor) ??
384
+ let penOwner = extractCodePenOwnerFromUrl(pen.urls.editor) ??
185
385
  (originalUrl ? extractCodePenOwnerFromUrl(originalUrl) : null);
186
386
  if (penOwner &&
187
387
  !options.explicitProfile &&
@@ -201,8 +401,9 @@ export async function clonePenCommand(options) {
201
401
  }
202
402
  }
203
403
  }
204
- const currentUsername = penOwner ? await resolveCurrentUsername(client, auth, penOwner) : null;
205
- const isOwnedByAnotherUser = Boolean(penOwner && currentUsername && penOwner.toLowerCase() !== currentUsername.toLowerCase());
404
+ let currentUsername = penOwner ? await resolveCurrentUsername(client, auth, penOwner) : null;
405
+ let isOwnedByAnotherUser = Boolean(penOwner && currentUsername && penOwner.toLowerCase() !== currentUsername.toLowerCase());
406
+ let effectiveUrl = originalUrl ?? pen.urls.editor;
206
407
  if (isOwnedByAnotherUser && penOwner && currentUsername) {
207
408
  if (!jsonMode) {
208
409
  console.log(fmt.yellow(`\nThis Pen belongs to ${fmt.bold(penOwner)} (your current account is ${fmt.bold(currentUsername)}).`));
@@ -245,6 +446,28 @@ export async function clonePenCommand(options) {
245
446
  }
246
447
  }
247
448
  }
449
+ if (pen.editor === 'Classic' && !isOwnedByAnotherUser && interactive) {
450
+ const classicResolution = await handleClassicPenClone({
451
+ pen,
452
+ apiIdentifier,
453
+ effectiveUrl,
454
+ auth,
455
+ client,
456
+ options,
457
+ selectImpl,
458
+ textImpl,
459
+ });
460
+ if (classicResolution.action === 'cancel') {
461
+ return null;
462
+ }
463
+ pen = classicResolution.pen;
464
+ effectiveUrl = classicResolution.effectiveUrl;
465
+ auth = classicResolution.auth;
466
+ client = classicResolution.client;
467
+ isOwnedByAnotherUser = classicResolution.isOwnedByAnotherUser;
468
+ penOwner = classicResolution.penOwner;
469
+ currentUsername = classicResolution.currentUsername;
470
+ }
248
471
  if (!targetDir) {
249
472
  const defaultFolder = suggestFolderName(pen);
250
473
  if (interactive) {
@@ -271,7 +494,8 @@ export async function clonePenCommand(options) {
271
494
  remoteFiles,
272
495
  pruneRemoved: false,
273
496
  });
274
- if (isOwnedByAnotherUser) {
497
+ const isUnlinked = isOwnedByAnotherUser || pen.editor === 'Classic';
498
+ if (isUnlinked) {
275
499
  if (jsonMode) {
276
500
  printJsonResponse(200, `Cloned ${pen.title || 'Untitled'} into ${targetFolderDisplay} (unlinked local copy).`, {
277
501
  pen,
@@ -287,10 +511,16 @@ export async function clonePenCommand(options) {
287
511
  }
288
512
  else {
289
513
  console.log(`\n${fmt.green('✓')} Cloned ${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)} into ${fmt.cyan(targetFolderDisplay)} ${fmt.dim('(unlinked local copy)')}`);
290
- console.log(` Source: ${fmt.dim(originalUrl ?? pen.urls.editor)}`);
514
+ console.log(` Source: ${fmt.dim(effectiveUrl)}`);
291
515
  console.log(` Files: ${result.writtenPaths.length} downloaded`);
292
- console.log(fmt.yellow(`\nNote: No ${PROJECT_CONFIG_FILENAME} was created because this Pen belongs to ${penOwner}, not ${currentUsername}.\n` +
293
- `Run \`cdpn push\` inside ${targetFolderDisplay} later to publish it as a new Pen under your account, or \`cdpn fork ${originalUrl ?? pen.urls.editor}\` to fork it on CodePen.`));
516
+ if (isOwnedByAnotherUser) {
517
+ console.log(fmt.yellow(`\nNote: No ${PROJECT_CONFIG_FILENAME} was created because this Pen belongs to ${penOwner}, not ${currentUsername}.\n` +
518
+ `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.`));
519
+ }
520
+ else {
521
+ console.log(fmt.yellow(`\nNote: No ${PROJECT_CONFIG_FILENAME} was created because this is a Classic (v1) Pen (read-only through CodePen API v2).\n` +
522
+ `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.`));
523
+ }
294
524
  }
295
525
  return {
296
526
  pen,
@@ -304,7 +534,7 @@ export async function clonePenCommand(options) {
304
534
  }
305
535
  const syncedFiles = buildSyncedFileMap(remoteFiles, result.localSha256ByPath);
306
536
  const config = {
307
- url: originalUrl ?? pen.urls.editor,
537
+ url: effectiveUrl,
308
538
  pen_id: pen.id,
309
539
  ...(auth.profile ? { profile: auth.profile } : {}),
310
540
  last_synced_version_id: pen.saved_version?.id ?? null,
@@ -335,9 +565,6 @@ export async function clonePenCommand(options) {
335
565
  console.log(` Version: ${fmt.dim(shortId(pen.saved_version.id))}`);
336
566
  }
337
567
  console.log(` Config: ${fmt.dim(path.join(targetFolderDisplay, PROJECT_CONFIG_FILENAME))}`);
338
- if (pen.editor === 'Classic') {
339
- console.log(fmt.yellow('\nNote: This is a Classic Pen (read-only through CodePen API v2). You can clone and pull files, but pushing and deploying require a CodePen 2.0 Pen.'));
340
- }
341
568
  }
342
569
  return {
343
570
  pen,
@@ -356,7 +583,7 @@ export async function clonePenCommand(options) {
356
583
  export function registerCloneCommand(program) {
357
584
  program
358
585
  .command('clone <url> [folder]')
359
- .description('Clone a CodePen Pen into a local folder (offers to fork if owned by another user)')
586
+ .description('Clone a CodePen Pen into a local folder (offers to convert Classic Pens or fork unowned Pens)')
360
587
  .option('-f, --force', 'Overwrite files if the target directory already exists and is not empty')
361
588
  .option('--json', 'Output clone result as JSON')
362
589
  .action(async (urlArg, folderArg, options, command) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codepen-commander",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Sync local folders with CodePen 2.0 Pens via the CodePen API v2",
5
5
  "license": "MIT",
6
6
  "type": "module",