codepen-commander 1.1.0 → 1.3.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
@@ -80,10 +80,25 @@ Every synced Pen folder contains a `.cdpn.json` file at its root:
80
80
  "url": "https://codepen.io/username/pen/abcde",
81
81
  "pen_id": "01a08738-73f0-7847-b6a8-5789d289c158",
82
82
  "profile": "username",
83
- "last_synced_version_id": "01a08738-73f0-7848-b8bf-e8e7e91b1ae2"
83
+ "last_synced_version_id": "01a08738-73f0-7848-b8bf-e8e7e91b1ae2",
84
+ "last_synced_info_hash": "a1b2c3d4...",
85
+ "editor": "V2",
86
+ "info": {
87
+ "title": "My Awesome Pen",
88
+ "description": "A short description of the Pen",
89
+ "tags": ["css", "demo"],
90
+ "access": "Public",
91
+ "template": false
92
+ }
84
93
  }
85
94
  ```
86
95
 
96
+ The `info` section tracks the Pen’s editable metadata (`title`, `description`, `tags`, `access`, and `template`) and syncs automatically with `cdpn status`, `cdpn push`, `cdpn pull`, `cdpn info`, and `cdpn privacy`. Edit `info.title`, `info.tags`, etc. directly in `.cdpn.json` and run `cdpn push` to update them on CodePen (passwords for `Protected` Pens are never stored in `.cdpn.json`; use `cdpn privacy protected` or `cdpn info --access Protected --password ...` instead).
97
+
98
+ Older `.cdpn.json` files created without an `info` section remain fully supported: `cdpn` will never overwrite remote metadata when `info` is absent, and will seamlessly populate `info` on your next `cdpn pull` or `cdpn push`.
99
+
100
+ You can also run `cdpn delete --keep-info` to delete the online Pen while stripping `.cdpn.json` down to only its `info` section (unlinked). When you later push the folder for the first time with `cdpn push` or `cdpn deploy`, the saved `title`, `description`, `tags`, `access`, and `template` are reused automatically without re-prompting for title or visibility (explicit `--title` / `--access` flags still override them, and `Protected` Pens still prompt for or require `--password`).
101
+
87
102
  > **Why `.cdpn.json` instead of `.codepen`?**
88
103
  > CodePen 2.0 Pens already contain a `.codepen/` directory (housing `.codepen/pen.config.json`). Using `.cdpn.json` avoids filesystem collisions while allowing `.codepen/pen.config.json` to sync cleanly with CodePen.
89
104
 
@@ -124,9 +139,9 @@ All commands accept the global `--profile <name>` flag to override the active pr
124
139
  | `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
140
  | `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
141
  | `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
- | `cdpn pull [--force] [--json]` | Pull latest remote changes into an existing cloned folder (requires `.cdpn.json`) |
128
- | `cdpn status [--json]` | Show active profile, file diffs (added/modified/deleted), remote head, build & deployment status |
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) |
142
+ | `cdpn pull [--force] [--json]` | Pull latest remote file and Pen info changes into an existing cloned folder (requires `.cdpn.json`) |
143
+ | `cdpn status [--json]` | Show active profile, file and Pen info diffs, remote head, build & deployment status |
144
+ | `cdpn push [-m <label>] [--force] [--dry-run] [--no-wait] [--json]` | Push local file and `.cdpn.json` Pen info changes (text & binary + deletions), or push an unlinked local demo folder as a new Pen (reuses retained `.cdpn.json` `info` if present; otherwise checks `index.html`, asks account, title, and visibility) |
130
145
  | `cdpn deploy [--no-push] [--version <id>] [--force] [--json]` | Push local changes (creating a Pen first if unlinked) and deploy to CodePen Hosting |
131
146
  | `cdpn undeploy [--yes] [--json]` | Take down the live deployment (Pen & versions remain intact) |
132
147
  | `cdpn domains [list] [--json]` | Show the default deployed URL, custom domains, verification status, and required DNS records |
@@ -137,7 +152,7 @@ All commands accept the global `--profile <name>` flag to override the active pr
137
152
  | `cdpn versions [--limit <n>] [--json]` | List saved versions with build status, labels, and markers (`head`, `local`, `deployed`) |
138
153
  | `cdpn rollback [version-id] [-m <label>] [--yes] [--json]` | Restore an older saved version to head and sync files locally |
139
154
  | `cdpn privacy [level] [--password <pw>] [--show] [--json]` | View or update Pen privacy (`Public`, `Private`, `Protected`, `Collaborators`; alias: `cdpn access`; requires `.cdpn.json` in current folder) |
140
- | `cdpn delete [--yes] [--json]` | Delete the online Pen on CodePen (moves to Deleted Items for 3 days) and remove `.cdpn.json` while keeping local files untouched (aliases: `cdpn del`, `cdpn rm`) |
155
+ | `cdpn delete [--keep-info] [--yes] [--json]` | Delete the online Pen on CodePen (moves to Deleted Items for 3 days) and remove `.cdpn.json` — or keep only its `info` section with `--keep-info` for a later first push — while keeping local files untouched (aliases: `cdpn del`, `cdpn rm`) |
141
156
  | `cdpn info [--title ...] [--tags ...] [--access ...] [--template true\|false] [--json]` | View or update Pen metadata |
142
157
  | `cdpn settings [--auto-deploy ...] [--indent-with ...] [--json]` | View or update Pen editor & deployment settings |
143
158
 
package/commands/clone.js CHANGED
@@ -5,6 +5,7 @@ import { CodePenApiError } from '../api/errors.js';
5
5
  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
+ import { buildPenInfoConfigFields } from '../sync/info.js';
8
9
  import { syncRemoteFilesToDisk } from '../sync/materialize.js';
9
10
  import { openBrowser, validateBrowserUrl } from '../utils/browser.js';
10
11
  import { fmt, shortId } from '../utils/format.js';
@@ -539,6 +540,7 @@ export async function clonePenCommand(options) {
539
540
  ...(auth.profile ? { profile: auth.profile } : {}),
540
541
  last_synced_version_id: pen.saved_version?.id ?? null,
541
542
  editor: pen.editor,
543
+ ...buildPenInfoConfigFields(pen),
542
544
  files: syncedFiles,
543
545
  };
544
546
  const configPath = await writeProjectConfig(targetDir, config);
@@ -1,8 +1,9 @@
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, writeProjectConfig, } from '../config/project.js';
4
+ import { buildSyncedFileMap, hasProjectConfigInDir, PROJECT_CONFIG_FILENAME, readProjectConfigFile, writeProjectConfig, } from '../config/project.js';
5
5
  import { scanLocalFiles } from '../sync/fs.js';
6
+ import { buildPenInfoConfigFields, hasAnyPenInfoFields } from '../sync/info.js';
6
7
  import { syncRemoteFilesToDisk } from '../sync/materialize.js';
7
8
  import { fmt, printBuildSummary, shortId } from '../utils/format.js';
8
9
  import { extractHtmlTitle } from '../utils/html.js';
@@ -85,12 +86,15 @@ export function printMissingIndexHtmlWarning(targetDir, fileCount) {
85
86
  }
86
87
  /**
87
88
  * First-time Pen creation flow used by `cdpn push` and `cdpn deploy` when invoked inside
88
- * an unlinked local demo folder:
89
+ * an unlinked local demo folder (including one with retained `info` in `.cdpn.json` from
90
+ * `cdpn delete --keep-info`):
89
91
  *
90
92
  * 1. Checks for `/index.html`; if absent, displays a prominent warning and asks for confirmation.
91
93
  * 2. Resolves or asks which CodePen account/profile to push to (when multiple keys are in `~/.cdpn`).
92
- * 3. Asks for a title (pre-filled from `index.html`'s `<title>` when available).
93
- * 4. Asks for visibility (`Public` default, `Private`, `Protected`, or `Collaborators`).
94
+ * 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`.
97
+ * 5. Carries over retained `description`, `tags`, and `template` from `.cdpn.json` when present.
94
98
  */
95
99
  export async function createPenFromDirectory(options) {
96
100
  const silent = Boolean(options.silent);
@@ -98,23 +102,45 @@ export async function createPenFromDirectory(options) {
98
102
  const confirmImpl = options.prompts?.confirm ?? promptConfirm;
99
103
  const textImpl = options.prompts?.text ?? promptText;
100
104
  const selectImpl = options.prompts?.select ?? promptSelect;
101
- // Validate --access / --password early before prompting or scanning
102
- const prevalidatedAccess = normalizeAccess(options.access);
103
- if (prevalidatedAccess === 'Protected' && options.password !== undefined && options.password.length < 8) {
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) {
104
108
  throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
105
109
  }
106
- if (prevalidatedAccess === 'Protected' && !options.password && !interactive) {
110
+ if (explicitAccess === 'Protected' && !options.password && !interactive) {
107
111
  throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
108
112
  }
109
113
  const targetDir = path.resolve(options.targetDir);
110
114
  const folderDisplay = options.folderDisplay;
115
+ let retainedInfo;
111
116
  if (await hasProjectConfigInDir(targetDir)) {
112
- throw new CliError(409, `${targetDir} already contains ${PROJECT_CONFIG_FILENAME}. Use \`cdpn push\` to update the existing Pen.`);
117
+ const existing = await readProjectConfigFile(targetDir);
118
+ if (existing.linked) {
119
+ throw new CliError(409, `${targetDir} already contains ${PROJECT_CONFIG_FILENAME}. Use \`cdpn push\` to update the existing Pen.`);
120
+ }
121
+ retainedInfo = existing.config.info;
122
+ }
123
+ const effectiveRawAccess = options.access ?? retainedInfo?.access;
124
+ const effectiveAccess = normalizeAccess(effectiveRawAccess);
125
+ const effectiveDescription = options.description !== undefined ? options.description : retainedInfo?.description;
126
+ const effectiveTags = options.tags !== undefined ? options.tags : retainedInfo?.tags;
127
+ const effectiveTemplate = options.template !== undefined ? options.template : retainedInfo?.template;
128
+ // 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.');
113
137
  }
114
138
  const scanned = await scanLocalFiles(targetDir);
115
139
  if (scanned.size === 0) {
116
- throw new CliError(400, `No ${PROJECT_CONFIG_FILENAME} found and no syncable files in ${targetDir}.\n` +
117
- 'Run `cdpn clone <url>` to clone an existing Pen or `cdpn new` to scaffold a brand-new Pen.');
140
+ throw new CliError(400, retainedInfo !== undefined
141
+ ? `No syncable files found in ${targetDir} (only an unlinked ${PROJECT_CONFIG_FILENAME} is present).`
142
+ : `No ${PROJECT_CONFIG_FILENAME} found and no syncable files in ${targetDir}.\n` +
143
+ 'Run `cdpn clone <url>` to clone an existing Pen or `cdpn new` to scaffold a brand-new Pen.');
118
144
  }
119
145
  const indexFile = scanned.get('/index.html');
120
146
  // 1. Check for index.html before pushing a local demo for the first time
@@ -143,14 +169,14 @@ export async function createPenFromDirectory(options) {
143
169
  selectProfile: selectImpl,
144
170
  });
145
171
  const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
146
- // 3. Determine title (defaulting to index.html's <title> when present)
147
- const htmlTitle = indexFile && !indexFile.isBinary && indexFile.textContent
148
- ? extractHtmlTitle(indexFile.textContent)
149
- : null;
150
- const fallbackTitle = path.basename(targetDir) || 'Untitled';
151
- const defaultTitle = htmlTitle ?? fallbackTitle;
152
- let title = options.title?.trim();
172
+ // 3. Determine title (explicit --title > retained info.title > index.html <title> > folder basename)
173
+ let title = options.title?.trim() || retainedInfo?.title?.trim();
153
174
  if (!title) {
175
+ const htmlTitle = indexFile && !indexFile.isBinary && indexFile.textContent
176
+ ? extractHtmlTitle(indexFile.textContent)
177
+ : null;
178
+ const fallbackTitle = path.basename(targetDir) || 'Untitled';
179
+ const defaultTitle = htmlTitle ?? fallbackTitle;
154
180
  if (interactive) {
155
181
  title = (await textImpl('Pen title', defaultTitle)).trim() || defaultTitle;
156
182
  }
@@ -158,9 +184,9 @@ export async function createPenFromDirectory(options) {
158
184
  title = defaultTitle;
159
185
  }
160
186
  }
161
- // 4. Ask for visibility (Public by default, Private, Protected, or Collaborators)
187
+ // 4. Resolve visibility (explicit --access > retained info.access > interactive picker / Public default)
162
188
  const { access, password } = await resolveVisibilityAndPassword({
163
- rawAccess: options.access,
189
+ rawAccess: effectiveRawAccess,
164
190
  rawPassword: options.password,
165
191
  interactive,
166
192
  prompts: options.prompts,
@@ -177,15 +203,18 @@ export async function createPenFromDirectory(options) {
177
203
  }
178
204
  const shouldWait = options.wait !== false;
179
205
  if (!silent) {
206
+ if (hasAnyPenInfoFields(retainedInfo)) {
207
+ console.log(fmt.dim(`Using saved Pen info from ${PROJECT_CONFIG_FILENAME}.`));
208
+ }
180
209
  console.log(`\nCreating new Pen from ${textFiles.length + binaryFiles.length} local file(s)…`);
181
210
  }
182
211
  const created = await client.createPen({
183
212
  ...(title ? { title } : {}),
184
- ...(options.description ? { description: options.description } : {}),
185
- ...(options.tags && options.tags.length > 0 ? { tags: options.tags } : {}),
213
+ ...(effectiveDescription ? { description: effectiveDescription } : {}),
214
+ ...(effectiveTags && effectiveTags.length > 0 ? { tags: effectiveTags } : {}),
186
215
  access,
187
216
  ...(password ? { password } : {}),
188
- ...(options.template ? { template: true } : {}),
217
+ ...(effectiveTemplate ? { template: true } : {}),
189
218
  files: textFiles,
190
219
  wait: shouldWait ? 45 : 0,
191
220
  }, binaryFiles);
@@ -213,6 +242,7 @@ export async function createPenFromDirectory(options) {
213
242
  ...(auth.profile ? { profile: auth.profile } : {}),
214
243
  last_synced_version_id: finalVersionId,
215
244
  editor: created.editor,
245
+ ...buildPenInfoConfigFields(created),
216
246
  files: buildSyncedFileMap(remoteFiles, materialized.localSha256ByPath),
217
247
  };
218
248
  const configPath = await writeProjectConfig(targetDir, config);
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs/promises';
2
2
  import { CodePenClient } from '../api/client.js';
3
- import { PROJECT_CONFIG_FILENAME, requireProjectInDir, } from '../config/project.js';
3
+ import { PROJECT_CONFIG_FILENAME, requireProjectInDir, writeUnlinkedProjectInfo, } from '../config/project.js';
4
+ import { analyzeInfoSync, extractPenInfo, normalizePartialPenInfo } from '../sync/info.js';
4
5
  import { fmt } from '../utils/format.js';
5
6
  import { CliError, printJsonResponse } from '../utils/json.js';
6
7
  import { isInteractive, promptConfirm, promptSelect, } from '../utils/prompts.js';
@@ -9,12 +10,14 @@ export const CODEPEN_DELETED_ITEMS_URL = 'https://codepen.io/your-work?item_type
9
10
  /**
10
11
  * Deletes the online Pen linked to `.cdpn.json` directly inside `options.cwd`
11
12
  * (moves it to CodePen Deleted Items, restorable for 3 days) and removes `.cdpn.json`
12
- * only after the remote deletion succeeds. Local project files are kept untouched.
13
+ * (or retains only its `info` section when `keepInfo` is true) only after the remote
14
+ * deletion succeeds. Local project files are kept untouched.
13
15
  *
14
16
  * Returns `null` if the user cancels at the confirmation prompt.
15
17
  */
16
18
  export async function deletePenCommand(options = {}) {
17
19
  const cwd = options.cwd ?? process.cwd();
20
+ const keepInfo = Boolean(options.keepInfo);
18
21
  const interactive = (options.interactive ?? isInteractive()) && !options.json;
19
22
  const confirmImpl = options.prompts?.confirm ?? promptConfirm;
20
23
  const selectImpl = options.prompts?.select ?? promptSelect;
@@ -44,40 +47,83 @@ export async function deletePenCommand(options = {}) {
44
47
  if (pen.deployment) {
45
48
  console.log(` Live: ${fmt.yellow(pen.deployment.url)} ${fmt.dim('(will also be taken down)')}`);
46
49
  }
47
- console.log(fmt.dim(`\nLocal files will stay untouched; ${PROJECT_CONFIG_FILENAME} will be removed after deletion succeeds.`));
48
- const ok = await confirmImpl(`Delete this Pen on CodePen (moves to Deleted Items for 3 days) and remove ${PROJECT_CONFIG_FILENAME}?`, false);
50
+ console.log(fmt.dim(keepInfo
51
+ ? `\nLocal files will stay untouched; only the "info" section will be kept in ${PROJECT_CONFIG_FILENAME} after deletion succeeds.`
52
+ : `\nLocal files will stay untouched; ${PROJECT_CONFIG_FILENAME} will be removed after deletion succeeds.`));
53
+ const ok = await confirmImpl(keepInfo
54
+ ? `Delete this Pen on CodePen (moves to Deleted Items for 3 days) and keep only "info" in ${PROJECT_CONFIG_FILENAME}?`
55
+ : `Delete this Pen on CodePen (moves to Deleted Items for 3 days) and remove ${PROJECT_CONFIG_FILENAME}?`, false);
49
56
  if (!ok) {
50
57
  console.log('Aborted.');
51
58
  return null;
52
59
  }
53
60
  }
54
61
  await client.deletePen(project.config.pen_id);
55
- // Remove `.cdpn.json` only after remote deletion succeeded
56
- await fs.unlink(project.configPath);
62
+ // Modify or remove `.cdpn.json` only after remote deletion succeeded
63
+ let retainedInfo;
64
+ if (keepInfo) {
65
+ const remoteInfo = extractPenInfo(pen);
66
+ const infoAnalysis = analyzeInfoSync(project.config.info, project.config.last_synced_info_hash, pen);
67
+ retainedInfo =
68
+ infoAnalysis.localChanged && project.config.info
69
+ ? { ...remoteInfo, ...normalizePartialPenInfo(project.config.info) }
70
+ : remoteInfo;
71
+ await writeUnlinkedProjectInfo(project.rootDir, retainedInfo);
72
+ }
73
+ else {
74
+ await fs.unlink(project.configPath);
75
+ }
57
76
  if (options.json) {
58
- printJsonResponse(200, `Deleted ${pen.title || 'Untitled'} (${pen.id}) on CodePen and removed ${PROJECT_CONFIG_FILENAME}.`, {
59
- pen_id: pen.id,
60
- title: pen.title,
61
- profile: auth.profile,
62
- editor_url: pen.urls.editor,
63
- deleted: true,
64
- config_removed: true,
65
- restore_url: CODEPEN_DELETED_ITEMS_URL,
66
- });
77
+ if (keepInfo) {
78
+ printJsonResponse(200, `Deleted ${pen.title || 'Untitled'} (${pen.id}) on CodePen and retained info in ${PROJECT_CONFIG_FILENAME}.`, {
79
+ pen_id: pen.id,
80
+ title: pen.title,
81
+ profile: auth.profile,
82
+ editor_url: pen.urls.editor,
83
+ deleted: true,
84
+ config_removed: false,
85
+ info_retained: true,
86
+ info: retainedInfo,
87
+ restore_url: CODEPEN_DELETED_ITEMS_URL,
88
+ });
89
+ }
90
+ else {
91
+ printJsonResponse(200, `Deleted ${pen.title || 'Untitled'} (${pen.id}) on CodePen and removed ${PROJECT_CONFIG_FILENAME}.`, {
92
+ pen_id: pen.id,
93
+ title: pen.title,
94
+ profile: auth.profile,
95
+ editor_url: pen.urls.editor,
96
+ deleted: true,
97
+ config_removed: true,
98
+ info_retained: false,
99
+ restore_url: CODEPEN_DELETED_ITEMS_URL,
100
+ });
101
+ }
67
102
  }
68
103
  else {
69
104
  console.log(`\n${fmt.green('✓')} Deleted ${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)} on CodePen ${fmt.dim('(moved to Deleted Items; restorable for 3 days)')}`);
70
- if (auth.profile) {
71
- console.log(` Profile: ${fmt.cyan(auth.profile)}`);
105
+ if (keepInfo) {
106
+ if (auth.profile) {
107
+ console.log(` Profile: ${fmt.cyan(auth.profile)}`);
108
+ }
109
+ console.log(` Retained: ${fmt.cyan(`info in ${PROJECT_CONFIG_FILENAME}`)} ${fmt.dim('(unlinked; local files were kept untouched)')}`);
110
+ console.log(` Restore: ${fmt.dim(CODEPEN_DELETED_ITEMS_URL)}`);
111
+ }
112
+ else {
113
+ if (auth.profile) {
114
+ console.log(` Profile: ${fmt.cyan(auth.profile)}`);
115
+ }
116
+ console.log(` Removed: ${fmt.cyan(PROJECT_CONFIG_FILENAME)} ${fmt.dim('(local files were kept untouched)')}`);
117
+ console.log(` Restore: ${fmt.dim(CODEPEN_DELETED_ITEMS_URL)}`);
72
118
  }
73
- console.log(` Removed: ${fmt.cyan(PROJECT_CONFIG_FILENAME)} ${fmt.dim('(local files were kept untouched)')}`);
74
- console.log(` Restore: ${fmt.dim(CODEPEN_DELETED_ITEMS_URL)}`);
75
119
  }
76
120
  return {
77
121
  pen,
78
122
  project,
79
123
  auth,
80
- configRemoved: true,
124
+ configRemoved: !keepInfo,
125
+ infoRetained: keepInfo,
126
+ ...(retainedInfo ? { retainedInfo } : {}),
81
127
  };
82
128
  }
83
129
  export function registerDeleteCommand(program) {
@@ -86,11 +132,13 @@ export function registerDeleteCommand(program) {
86
132
  .aliases(['del', 'rm'])
87
133
  .allowExcessArguments(false)
88
134
  .description(`Delete the online Pen on CodePen (moves to Deleted Items) and remove ${PROJECT_CONFIG_FILENAME}`)
135
+ .option('--keep-info', `Keep Pen info in ${PROJECT_CONFIG_FILENAME} so it is reused on the next push`)
89
136
  .option('-y, --yes', 'Skip confirmation prompt')
90
137
  .option('--json', 'Output deletion result as JSON')
91
138
  .action(async (options, command) => {
92
139
  await deletePenCommand({
93
140
  yes: options.yes,
141
+ keepInfo: options.keepInfo,
94
142
  json: options.json,
95
143
  explicitProfile: getGlobalProfileOption(command),
96
144
  });
@@ -1,5 +1,6 @@
1
+ import path from 'node:path';
1
2
  import { CodePenClient } from '../api/client.js';
2
- import { findProject, PROJECT_CONFIG_FILENAME, requireProject } from '../config/project.js';
3
+ import { findNearestConfig, PROJECT_CONFIG_FILENAME, requireProject, } from '../config/project.js';
3
4
  import { fmt, shortId } from '../utils/format.js';
4
5
  import { CliError, printJsonResponse } from '../utils/json.js';
5
6
  import { isInteractive, promptConfirm } from '../utils/prompts.js';
@@ -23,7 +24,14 @@ export function registerDeployCommands(program) {
23
24
  throw new CliError(400, 'Version label must be at most 80 characters.');
24
25
  }
25
26
  const explicitProfile = getGlobalProfileOption(command);
26
- let project = await findProject(process.cwd());
27
+ const nearest = await findNearestConfig(process.cwd());
28
+ let project = nearest?.linked
29
+ ? {
30
+ rootDir: nearest.rootDir,
31
+ configPath: nearest.configPath,
32
+ config: nearest.config,
33
+ }
34
+ : null;
27
35
  let versionIdToDeploy = options.version;
28
36
  let client;
29
37
  let activeProfile;
@@ -31,15 +39,22 @@ export function registerDeployCommands(program) {
31
39
  let pushedChanges = false;
32
40
  if (!project) {
33
41
  if (options.push === false || options.version) {
34
- throw new CliError(404, `No ${PROJECT_CONFIG_FILENAME} found in this directory or any parent directory.\n` +
35
- 'Run `cdpn clone <url>` to clone a Pen or run `cdpn deploy` without --no-push/--version to create one first.');
42
+ throw new CliError(404, nearest
43
+ ? `${PROJECT_CONFIG_FILENAME} in ${nearest.rootDir} only contains Pen info and is not linked to an online Pen yet.\n` +
44
+ 'Run `cdpn deploy` without --no-push/--version to create and link it first.'
45
+ : `No ${PROJECT_CONFIG_FILENAME} found in this directory or any parent directory.\n` +
46
+ 'Run `cdpn clone <url>` to clone a Pen or run `cdpn deploy` without --no-push/--version to create one first.');
36
47
  }
48
+ const targetDir = nearest ? nearest.rootDir : process.cwd();
49
+ const folderDisplay = path.relative(process.cwd(), targetDir) || '.';
37
50
  if (!options.json) {
38
- console.log(fmt.dim(`No ${PROJECT_CONFIG_FILENAME} found — pushing this local folder as a new CodePen 2.0 Pen before deploying.`));
51
+ console.log(fmt.dim(nearest
52
+ ? `Found unlinked ${PROJECT_CONFIG_FILENAME} with saved Pen info — pushing this local folder as a new CodePen 2.0 Pen before deploying.`
53
+ : `No ${PROJECT_CONFIG_FILENAME} found — pushing this local folder as a new CodePen 2.0 Pen before deploying.`));
39
54
  }
40
55
  const created = await createPenFromDirectory({
41
- targetDir: process.cwd(),
42
- folderDisplay: '.',
56
+ targetDir,
57
+ folderDisplay,
43
58
  explicitProfile,
44
59
  title: options.title,
45
60
  access: options.access,
package/commands/fork.js CHANGED
@@ -4,6 +4,7 @@ import { CodePenClient } from '../api/client.js';
4
4
  import { CodePenApiError } from '../api/errors.js';
5
5
  import { buildSyncedFileMap, hasProjectConfigInDir, normalizePenReference, slugifyTitle, suggestFolderName, writeProjectConfig, } from '../config/project.js';
6
6
  import { isDirectoryNonEmpty } from '../sync/fs.js';
7
+ import { buildPenInfoConfigFields } from '../sync/info.js';
7
8
  import { syncRemoteFilesToDisk } from '../sync/materialize.js';
8
9
  import { fmt, printBuildSummary, shortId } from '../utils/format.js';
9
10
  import { CliError, printJsonResponse } from '../utils/json.js';
@@ -252,6 +253,7 @@ export async function forkPenCommand(options) {
252
253
  ...(auth.profile ? { profile: auth.profile } : {}),
253
254
  last_synced_version_id: finalVersionId,
254
255
  editor: forked.editor,
256
+ ...buildPenInfoConfigFields(forked),
255
257
  files: buildSyncedFileMap(remoteFiles, materialized.localSha256ByPath),
256
258
  };
257
259
  const configPath = await writeProjectConfig(targetDir, config);
package/commands/meta.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { CodePenClient } from '../api/client.js';
2
- import { requireProject } from '../config/project.js';
2
+ import { requireProject, writeProjectConfig } from '../config/project.js';
3
+ import { mergeUpdatedPenInfoIntoConfig } from '../sync/info.js';
3
4
  import { fmt, formatDate, shortId } from '../utils/format.js';
4
5
  import { CliError, printJsonResponse } from '../utils/json.js';
5
6
  import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
@@ -46,6 +47,68 @@ function renderPenSettings(settings) {
46
47
  console.log(`indent_with: ${fmt.cyan(settings.indent_with)}`);
47
48
  console.log(`tab_size: ${fmt.cyan(String(settings.tab_size))}`);
48
49
  }
50
+ export async function infoPenCommand(options = {}) {
51
+ const project = await requireProject(options.cwd ?? process.cwd());
52
+ const auth = await resolveCommandAuth({
53
+ explicitProfile: options.explicitProfile,
54
+ project,
55
+ interactive: options.json ? false : options.interactive,
56
+ persistProfileToProject: !options.json,
57
+ env: options.env,
58
+ homeDir: options.homeDir,
59
+ selectProfile: options.selectProfile,
60
+ });
61
+ const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
62
+ const patch = {};
63
+ if (options.title !== undefined)
64
+ patch.title = options.title;
65
+ if (options.description !== undefined)
66
+ patch.description = options.description;
67
+ if (options.tags !== undefined) {
68
+ const parsedTags = options.tags
69
+ .split(',')
70
+ .map((t) => t.trim())
71
+ .filter(Boolean);
72
+ if (parsedTags.length > 5) {
73
+ throw new CliError(400, 'CodePen allows at most 5 tags per Pen.');
74
+ }
75
+ patch.tags = parsedTags;
76
+ }
77
+ if (options.access !== undefined) {
78
+ const lower = options.access.trim().toLowerCase();
79
+ if (!VALID_ACCESS.has(lower)) {
80
+ throw new CliError(400, `Invalid --access "${options.access}". Use: Public, Private, Protected, or Collaborators.`);
81
+ }
82
+ patch.access = (lower[0].toUpperCase() + lower.slice(1));
83
+ }
84
+ if (options.password !== undefined) {
85
+ if (options.password.length < 8) {
86
+ throw new CliError(400, 'Password must be at least 8 characters.');
87
+ }
88
+ patch.password = options.password;
89
+ }
90
+ if (options.template !== undefined) {
91
+ patch.template = parseBooleanOption(options.template, '--template');
92
+ }
93
+ const hasUpdates = Object.keys(patch).length > 0;
94
+ const pen = hasUpdates
95
+ ? await client.updatePen(project.config.pen_id, patch)
96
+ : await client.getPen(project.config.pen_id);
97
+ if (hasUpdates) {
98
+ const nextConfig = mergeUpdatedPenInfoIntoConfig(project.config, pen, patch);
99
+ await writeProjectConfig(project.rootDir, nextConfig);
100
+ project.config = nextConfig;
101
+ }
102
+ if (options.json) {
103
+ printJsonResponse(200, hasUpdates ? 'Updated Pen metadata.' : 'Fetched Pen metadata.', pen);
104
+ return { pen, updated: hasUpdates, auth, project };
105
+ }
106
+ if (hasUpdates) {
107
+ console.log(`${fmt.green('✓')} Updated Pen metadata.\n`);
108
+ }
109
+ renderPenInfo(pen, auth.profile);
110
+ return { pen, updated: hasUpdates, auth, project };
111
+ }
49
112
  export function registerMetaCommands(program) {
50
113
  program
51
114
  .command('info')
@@ -58,53 +121,10 @@ export function registerMetaCommands(program) {
58
121
  .option('--template <bool>', 'Set template flag (true/false)')
59
122
  .option('--json', 'Output Pen metadata as JSON')
60
123
  .action(async (options, command) => {
61
- const project = await requireProject();
62
- const auth = await resolveCommandAuth({
124
+ await infoPenCommand({
125
+ ...options,
63
126
  explicitProfile: getGlobalProfileOption(command),
64
- project,
65
- interactive: options.json ? false : undefined,
66
- persistProfileToProject: !options.json,
67
127
  });
68
- const client = new CodePenClient({ apiKey: auth.apiKey });
69
- const patch = {};
70
- if (options.title !== undefined)
71
- patch.title = options.title;
72
- if (options.description !== undefined)
73
- patch.description = options.description;
74
- if (options.tags !== undefined) {
75
- patch.tags = options.tags
76
- .split(',')
77
- .map((t) => t.trim())
78
- .filter(Boolean);
79
- }
80
- if (options.access !== undefined) {
81
- const lower = options.access.trim().toLowerCase();
82
- if (!VALID_ACCESS.has(lower)) {
83
- throw new CliError(400, `Invalid --access "${options.access}". Use: Public, Private, Protected, or Collaborators.`);
84
- }
85
- patch.access = (lower[0].toUpperCase() + lower.slice(1));
86
- }
87
- if (options.password !== undefined) {
88
- if (options.password.length < 8) {
89
- throw new CliError(400, 'Password must be at least 8 characters.');
90
- }
91
- patch.password = options.password;
92
- }
93
- if (options.template !== undefined) {
94
- patch.template = parseBooleanOption(options.template, '--template');
95
- }
96
- const hasUpdates = Object.keys(patch).length > 0;
97
- const pen = hasUpdates
98
- ? await client.updatePen(project.config.pen_id, patch)
99
- : await client.getPen(project.config.pen_id);
100
- if (options.json) {
101
- printJsonResponse(200, hasUpdates ? 'Updated Pen metadata.' : 'Fetched Pen metadata.', pen);
102
- return;
103
- }
104
- if (hasUpdates) {
105
- console.log(`${fmt.green('✓')} Updated Pen metadata.\n`);
106
- }
107
- renderPenInfo(pen, auth.profile);
108
128
  });
109
129
  program
110
130
  .command('settings')
package/commands/new.js CHANGED
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import { CodePenClient } from '../api/client.js';
4
4
  import { buildSyncedFileMap, slugifyTitle, writeProjectConfig, } from '../config/project.js';
5
5
  import { isDirectoryNonEmpty } from '../sync/fs.js';
6
+ import { buildPenInfoConfigFields } from '../sync/info.js';
6
7
  import { syncRemoteFilesToDisk } from '../sync/materialize.js';
7
8
  import { fmt, formatDate, printBuildSummary, shortId } from '../utils/format.js';
8
9
  import { CliError, printJsonResponse } from '../utils/json.js';
@@ -202,6 +203,7 @@ export async function scaffoldNewPen(options = {}) {
202
203
  ...(auth.profile ? { profile: auth.profile } : {}),
203
204
  last_synced_version_id: finalVersionId,
204
205
  editor: created.editor,
206
+ ...buildPenInfoConfigFields(created),
205
207
  files: buildSyncedFileMap(remoteFiles, materialized.localSha256ByPath),
206
208
  };
207
209
  const configPath = await writeProjectConfig(targetDir, config);
@@ -1,5 +1,6 @@
1
1
  import { CodePenClient } from '../api/client.js';
2
- import { requireProjectInDir } from '../config/project.js';
2
+ import { requireProjectInDir, writeProjectConfig } from '../config/project.js';
3
+ import { mergeUpdatedPenInfoIntoConfig } from '../sync/info.js';
3
4
  import { fmt } from '../utils/format.js';
4
5
  import { CliError, printJsonResponse } from '../utils/json.js';
5
6
  import { isInteractive, promptConfirm, promptSecret, promptSelect, } from '../utils/prompts.js';
@@ -177,6 +178,9 @@ export async function managePenPrivacy(options = {}) {
177
178
  };
178
179
  }
179
180
  const updatedPen = await client.updatePen(project.config.pen_id, patch);
181
+ const nextConfig = mergeUpdatedPenInfoIntoConfig(project.config, updatedPen, patch);
182
+ await writeProjectConfig(project.rootDir, nextConfig);
183
+ project.config = nextConfig;
180
184
  if (options.json) {
181
185
  const message = previousAccess === updatedPen.access && passwordUpdated
182
186
  ? 'Updated password for Protected Pen.'