codepen-commander 1.2.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 (93) hide show
  1. package/README.md +104 -10
  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 +553 -37
  13. package/commands/deploy.js +164 -154
  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 +222 -365
  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 +179 -240
  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/workflows/create-pen.js +254 -0
  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/create-pen.js +0 -251
  91. package/commands/meta.js +0 -184
  92. package/utils/prompts.js +0 -316
  93. /package/{types.js → api/types.js} +0 -0
package/commands/push.js CHANGED
@@ -1,406 +1,263 @@
1
+ import path from 'node:path';
1
2
  import { CodePenClient } from '../api/client.js';
2
- import { buildSyncedFileMap, findProject, PROJECT_CONFIG_FILENAME, writeProjectConfig, } from '../config/project.js';
3
- import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
4
- import { createPenFromDirectory } from './create-pen.js';
5
- import { computeSyncDiff, hasDiffChanges } from '../sync/diff.js';
6
- import { scanLocalFiles } from '../sync/fs.js';
7
- import { analyzeInfoSync, buildInfoUpdatePatch, buildPenInfoConfigFields, formatInfoValue, hashPenInfo, isCompletePenInfo, } from '../sync/info.js';
8
- import { applyCompilerPatchesToDisk } from '../sync/materialize.js';
9
- import { fmt, printBuildSummary, shortId } from '../utils/format.js';
10
- import { CliError, printJsonResponse } from '../utils/json.js';
11
- import { isInteractive } from '../utils/prompts.js';
12
- export async function executePush(client, project, options = {}) {
13
- const silent = Boolean(options.silent);
14
- const [pen, remoteFiles, localFiles] = await Promise.all([
15
- client.getPen(project.config.pen_id),
16
- client.getPenFiles(project.config.pen_id),
17
- scanLocalFiles(project.rootDir),
18
- ]);
19
- if (pen.editor === 'Classic') {
20
- throw new CliError(403, 'This is a Classic Pen, which is read-only in CodePen API v2. Only CodePen 2.0 Pens can be pushed.');
21
- }
22
- const localHead = project.config.last_synced_version_id;
23
- const remoteHead = pen.saved_version?.id ?? null;
24
- if (remoteHead && localHead && remoteHead !== localHead && !options.force) {
25
- throw new CliError(409, `Remote Pen head (${shortId(remoteHead)}) has moved ahead of your last synced version (${shortId(localHead)}).\n` +
26
- 'Run `cdpn status` to inspect differences, `cdpn pull` to sync remote changes, or `cdpn push --force` to overwrite.', {
27
- local_head: localHead,
28
- remote_head: remoteHead,
29
- });
30
- }
31
- const diff = await computeSyncDiff({
32
- localFiles,
33
- remoteFiles,
34
- baseline: project.config.files,
35
- downloadFile: (url) => client.downloadFile(url),
36
- });
37
- const infoAnalysis = analyzeInfoSync(project.config.info, project.config.last_synced_info_hash, pen);
38
- if (infoAnalysis.localChanged && infoAnalysis.remoteChanged && !options.force) {
39
- const fields = infoAnalysis.changes.map((c) => c.field).join(', ');
40
- throw new CliError(409, `Remote Pen info has changed since your last sync, and you also have local info edits in ${PROJECT_CONFIG_FILENAME} (${fields}).\n` +
41
- 'Run `cdpn status` to inspect differences, `cdpn pull` to sync remote changes, or `cdpn push --force` to overwrite.', {
42
- info_changes: infoAnalysis.changes,
43
- });
44
- }
45
- const hasFileChanges = hasDiffChanges(diff);
46
- const shouldPushInfo = infoAnalysis.changes.length > 0 && (infoAnalysis.localChanged || Boolean(options.force));
47
- const infoChangesToPush = shouldPushInfo ? infoAnalysis.changes : [];
48
- // Validate info patch constraints up-front before making any write API calls
49
- const infoPatch = shouldPushInfo ? buildInfoUpdatePatch(infoChangesToPush) : null;
50
- if (!hasFileChanges && !shouldPushInfo) {
51
- let backfilledLegacyInfo = false;
52
- if (!options.dryRun && infoAnalysis.changes.length === 0) {
53
- const remoteHash = hashPenInfo(infoAnalysis.remoteInfo);
54
- const needsInfoUpgrade = !infoAnalysis.tracked ||
55
- !isCompletePenInfo(project.config.info) ||
56
- project.config.last_synced_info_hash !== remoteHash;
57
- if (needsInfoUpgrade) {
58
- backfilledLegacyInfo = !infoAnalysis.tracked;
59
- const nextConfig = {
60
- ...project.config,
61
- ...buildPenInfoConfigFields(pen),
62
- };
63
- await writeProjectConfig(project.rootDir, nextConfig);
64
- project.config = nextConfig;
65
- }
66
- }
67
- if (!silent) {
68
- if (infoAnalysis.remoteChanged) {
69
- console.log(`${fmt.cyan('ℹ')} No local changes to push. Remote Pen info has changed on CodePen — run \`cdpn pull\` to update ${PROJECT_CONFIG_FILENAME}, or \`cdpn push --force\` to overwrite.`);
70
- }
71
- else {
72
- console.log(`${fmt.green('✓')} Everything is up to date — nothing to push.`);
73
- if (backfilledLegacyInfo) {
74
- console.log(fmt.dim(` Added Pen info to ${PROJECT_CONFIG_FILENAME}.`));
75
- }
76
- }
3
+ import { findNearestConfig } from '../config/project.js';
4
+ import { PROJECT_CONFIG_FILENAME } from '../constants.js';
5
+ import { CliError } from '../errors.js';
6
+ import { assertValidVersionLabel, resolveAccessOrVisibility } from '../utils/cli-options.js';
7
+ import { fmt, shortId } from '../utils/format.js';
8
+ import { printJsonResponse } from '../utils/json.js';
9
+ import { defaultOutput } from '../utils/output.js';
10
+ import { isInteractive } from '../utils/prompts/index.js';
11
+ import { getGlobalProfileOption, resolveCommandAuth } from '../workflows/auth-context.js';
12
+ import { runBatchPush } from '../workflows/batch-pens.js';
13
+ import { offerBatchAllFallback, resolveBatchCommandTarget, } from '../workflows/batch-target.js';
14
+ import { createPenFromDirectory } from '../workflows/create-pen.js';
15
+ import { fetchLinkedPenOrHandleMissing } from '../workflows/missing-pen.js';
16
+ import { executePush } from '../workflows/push-pen.js';
17
+ export async function runPushCommand(options = {}) {
18
+ const output = options.output ?? defaultOutput;
19
+ const cwd = path.resolve(options.cwd ?? process.cwd());
20
+ const jsonMode = Boolean(options.json);
21
+ const interactive = !jsonMode && (options.interactive ?? isInteractive());
22
+ assertValidVersionLabel(options.label);
23
+ const resolvedAccess = resolveAccessOrVisibility(options.access, options.visibility);
24
+ const executeBatch = async (rootDir, discovered) => {
25
+ if (options.title?.trim()) {
26
+ throw new CliError(400, '--title cannot be used when pushing multiple Pens in a directory tree.');
77
27
  }
28
+ const batch = await runBatchPush({
29
+ rootDir,
30
+ discovered,
31
+ label: options.label,
32
+ force: options.force,
33
+ dryRun: options.dryRun,
34
+ wait: options.wait,
35
+ access: resolvedAccess,
36
+ password: options.password,
37
+ json: jsonMode,
38
+ interactive,
39
+ explicitProfile: options.explicitProfile,
40
+ baseUrl: options.baseUrl,
41
+ env: options.env,
42
+ homeDir: options.homeDir,
43
+ output,
44
+ prompts: options.prompts,
45
+ });
78
46
  return {
79
- pushed: false,
80
- dryRun: Boolean(options.dryRun),
81
- pen,
82
- versionId: remoteHead,
83
- build: pen.saved_version?.build ?? null,
84
- changes: { added: [], modified: [], deleted: [] },
85
- infoChanges: [],
86
- appliedPatches: [],
87
- remoteInfoChanged: infoAnalysis.remoteChanged,
47
+ pushed: !batch.dryRun && (batch.counts.pushed > 0 || batch.counts.created > 0),
48
+ created: !batch.dryRun && batch.counts.created > 0,
49
+ dryRun: batch.dryRun,
50
+ batch,
51
+ ...(batch.exitCode !== undefined ? { exitCode: batch.exitCode } : {}),
88
52
  };
89
- }
90
- const changes = {
91
- added: diff.added.map((item) => item.path),
92
- modified: diff.modified.map((item) => item.path),
93
- deleted: diff.deleted.map((item) => item.path),
94
53
  };
95
- if (!silent) {
96
- console.log(`${options.dryRun ? 'Dry-run pushing' : 'Pushing'} changes to ${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)}:`);
97
- for (const item of diff.added)
98
- console.log(` ${fmt.green('+')} ${item.path}`);
99
- for (const item of diff.modified)
100
- console.log(` ${fmt.yellow('~')} ${item.path}`);
101
- for (const item of diff.deleted)
102
- console.log(` ${fmt.red('-')} ${item.path}`);
103
- for (const change of infoChangesToPush) {
104
- console.log(` ${fmt.yellow('~')} info.${change.field}: ${formatInfoValue(change.field, change.remote)} → ${formatInfoValue(change.field, change.local)}`);
105
- }
54
+ const resolvedTarget = await resolveBatchCommandTarget({
55
+ commandName: 'push',
56
+ cwd,
57
+ target: options.target,
58
+ interactive,
59
+ output,
60
+ prompts: options.prompts,
61
+ });
62
+ if (resolvedTarget.mode === 'batch') {
63
+ return executeBatch(resolvedTarget.rootDir, resolvedTarget.discovered);
106
64
  }
107
- let finalBuild = pen.saved_version?.build ?? null;
108
- let finalVersionId = remoteHead;
109
- let appliedPatches = [];
110
- let updatedPen = pen;
111
- let finalRemoteFiles;
112
- let localShaByPath;
113
- if (hasFileChanges) {
114
- const fileChanges = [];
115
- const binaryUploads = [];
116
- for (const item of [...diff.added, ...diff.modified]) {
117
- const local = item.local;
118
- // Note: CodePen API returns 400 on empty multipart parts, so 0-byte files always go as text JSON
119
- if (local.isBinary && local.buffer.length > 0) {
120
- binaryUploads.push({ path: item.path, content: local.buffer });
121
- }
122
- else {
123
- fileChanges.push({
124
- path: item.path,
125
- content: local.textContent ?? '',
126
- });
127
- }
128
- }
129
- for (const item of diff.deleted) {
130
- fileChanges.push({
131
- path: item.path,
132
- delete: true,
133
- });
65
+ const targetCwd = resolvedTarget.targetDir;
66
+ const nearest = await findNearestConfig(targetCwd);
67
+ if (!nearest) {
68
+ const fallback = await offerBatchAllFallback({
69
+ commandName: 'push',
70
+ targetDir: targetCwd,
71
+ fromExplicitDir: resolvedTarget.fromExplicitDir,
72
+ displayDir: resolvedTarget.displayDir,
73
+ dryRun: options.dryRun,
74
+ interactive,
75
+ output,
76
+ prompts: options.prompts,
77
+ });
78
+ if (fallback.action === 'batch') {
79
+ return executeBatch(targetCwd, fallback.discovered);
134
80
  }
135
- const expectedVersionId = options.force ? undefined : (localHead ?? remoteHead ?? undefined);
136
- const shouldWait = options.wait !== false;
137
- if (!silent) {
138
- console.log(shouldWait ? '\nUploading and building on CodePen…' : '\nUploading to CodePen…');
81
+ if (fallback.action === 'canceled') {
82
+ return { pushed: false, created: false, dryRun: Boolean(options.dryRun), aborted: true };
139
83
  }
140
- const writeResult = await client.writePenFiles(pen.id, {
141
- files: fileChanges,
142
- ...(options.label ? { label: options.label } : {}),
143
- ...(expectedVersionId ? { expected_version_id: expectedVersionId } : {}),
144
- ...(options.dryRun ? { dry_run: true } : {}),
145
- wait: shouldWait ? 45 : 0,
146
- }, binaryUploads);
147
- finalBuild = writeResult.build;
148
- if (finalBuild && shouldWait) {
149
- let lastStatus = `${finalBuild.status}:${finalBuild.id}`;
150
- finalBuild = await client.settleBuild(finalBuild, {
151
- onUpdate: (b) => {
152
- if (silent)
153
- return;
154
- const key = `${b.status}:${b.id}`;
155
- if (key !== lastStatus) {
156
- lastStatus = key;
157
- if (b.status === 'Running' || b.status === 'Queued') {
158
- console.log(fmt.dim(` Build ${shortId(b.id)}: ${b.status}…`));
159
- }
160
- else if (b.status === 'Canceled' && b.next_id) {
161
- console.log(fmt.dim(' Compiler requested patches — waiting for converged rebuild…'));
162
- }
163
- }
164
- },
165
- });
84
+ }
85
+ // First-time push: no linked .cdpn.json found -> push local folder as a brand-new CodePen 2.0 Pen
86
+ if (!nearest || !nearest.linked) {
87
+ if (options.dryRun) {
88
+ throw new CliError(400, nearest
89
+ ? `${PROJECT_CONFIG_FILENAME} in ${nearest.rootDir} is not linked to an online Pen yet. --dry-run is only supported for an existing synced Pen.`
90
+ : `No ${PROJECT_CONFIG_FILENAME} found. --dry-run is only supported for an existing synced Pen.`);
166
91
  }
167
- if (finalBuild && !silent) {
168
- printBuildSummary(finalBuild);
92
+ const targetDir = nearest ? nearest.rootDir : targetCwd;
93
+ const folderDisplay = path.relative(cwd, targetDir) || '.';
94
+ if (!jsonMode) {
95
+ output.log(fmt.dim(nearest
96
+ ? `Found unlinked ${PROJECT_CONFIG_FILENAME} with saved Pen info — pushing this local folder as a new CodePen 2.0 Pen.`
97
+ : `No ${PROJECT_CONFIG_FILENAME} found — pushing this local folder as a new CodePen 2.0 Pen.`));
169
98
  }
170
- finalVersionId = finalBuild?.version_id ?? writeResult.version?.id ?? null;
171
- appliedPatches = finalBuild?.applied_patches ?? [];
172
- updatedPen = writeResult.pen ?? pen;
173
- if (!options.dryRun) {
174
- // Re-read the converged version's source files so we write back any compiler patches
175
- let convergedFiles = writeResult.version?.files;
176
- if (finalVersionId && (appliedPatches.length > 0 || !convergedFiles)) {
177
- const version = await client.getVersion(finalVersionId);
178
- convergedFiles = version.files;
179
- }
180
- if (finalBuild && appliedPatches.length > 0) {
181
- await applyCompilerPatchesToDisk({
182
- client,
183
- rootDir: project.rootDir,
184
- patches: appliedPatches,
185
- convergedFiles,
186
- });
187
- if (!silent) {
188
- console.log(fmt.cyan('✓ Synced compiler patches back to local folder.'));
189
- }
190
- }
191
- // Re-scan local hashes so .cdpn.json reflects exact post-patch local state
192
- const postPushLocalFiles = await scanLocalFiles(project.rootDir);
193
- localShaByPath = new Map();
194
- for (const [p, lf] of postPushLocalFiles) {
195
- localShaByPath.set(p, lf.sha256);
196
- }
197
- finalRemoteFiles = convergedFiles ?? (await client.getPenFiles(pen.id));
198
- // If an info PATCH is still pending, persist the synced file manifest now while preserving
199
- // unpushed local `info` so a subsequent info validation error never leaves version metadata stale.
200
- if (shouldPushInfo) {
201
- const intermediateConfig = {
202
- url: project.config.url || updatedPen.urls.editor,
203
- pen_id: updatedPen.id,
204
- ...(project.config.profile ? { profile: project.config.profile } : {}),
205
- last_synced_version_id: finalVersionId,
206
- ...(project.config.last_synced_info_hash
207
- ? { last_synced_info_hash: project.config.last_synced_info_hash }
208
- : {}),
209
- editor: updatedPen.editor,
210
- ...(project.config.info !== undefined ? { info: project.config.info } : {}),
211
- files: buildSyncedFileMap(finalRemoteFiles, localShaByPath),
212
- };
213
- await writeProjectConfig(project.rootDir, intermediateConfig);
214
- project.config = intermediateConfig;
215
- }
99
+ const created = await createPenFromDirectory({
100
+ targetDir,
101
+ folderDisplay,
102
+ explicitProfile: options.explicitProfile,
103
+ title: options.title,
104
+ access: resolvedAccess,
105
+ password: options.password,
106
+ force: options.force,
107
+ wait: options.wait,
108
+ silent: jsonMode,
109
+ output,
110
+ baseUrl: options.baseUrl,
111
+ interactive,
112
+ env: options.env,
113
+ homeDir: options.homeDir,
114
+ prompts: options.prompts,
115
+ });
116
+ if (!created) {
117
+ return { pushed: false, created: false, dryRun: false, aborted: true };
216
118
  }
217
- }
218
- if (options.dryRun) {
219
- if (!silent) {
220
- console.log(`\n${fmt.cyan('ℹ')} Dry run complete — no changes were saved to CodePen` +
221
- (hasFileChanges && finalVersionId
222
- ? ` ${fmt.dim(`(ephemeral version ${shortId(finalVersionId)})`)}.`
223
- : '.'));
119
+ const buildFailed = created.build?.status === 'Failed';
120
+ if (jsonMode) {
121
+ printJsonResponse(buildFailed ? 422 : 201, buildFailed
122
+ ? `Created Pen ${created.pen.title || 'Untitled'} (${created.pen.id}), but the initial build failed.`
123
+ : `Created Pen ${created.pen.title || 'Untitled'} (${created.pen.id}).`, {
124
+ pushed: true,
125
+ created: true,
126
+ dry_run: false,
127
+ pen: created.pen,
128
+ profile: created.auth.profile,
129
+ folder: folderDisplay,
130
+ root_dir: created.project.rootDir,
131
+ config_path: created.project.configPath,
132
+ version_id: created.versionId,
133
+ build: created.build,
134
+ }, output);
224
135
  }
225
136
  return {
226
- pushed: false,
227
- dryRun: true,
228
- pen: updatedPen,
229
- versionId: hasFileChanges ? finalVersionId : remoteHead,
230
- build: hasFileChanges ? finalBuild : null,
231
- changes,
232
- infoChanges: infoChangesToPush,
233
- appliedPatches,
137
+ pushed: true,
138
+ created: true,
139
+ dryRun: false,
140
+ pen: created.pen,
141
+ versionId: created.versionId,
142
+ build: created.build,
143
+ ...(created.exitCode !== undefined ? { exitCode: created.exitCode } : {}),
234
144
  };
235
145
  }
236
- if (shouldPushInfo && infoPatch) {
237
- if (!silent) {
238
- console.log('\nUpdating Pen info on CodePen…');
239
- }
240
- updatedPen = await client.updatePen(pen.id, infoPatch);
241
- }
242
- const nextConfig = {
243
- url: project.config.url || updatedPen.urls.editor,
244
- pen_id: updatedPen.id,
245
- ...(project.config.profile ? { profile: project.config.profile } : {}),
246
- last_synced_version_id: hasFileChanges ? finalVersionId : project.config.last_synced_version_id,
247
- editor: updatedPen.editor,
248
- ...buildPenInfoConfigFields(updatedPen),
249
- ...(hasFileChanges && finalRemoteFiles && localShaByPath
250
- ? { files: buildSyncedFileMap(finalRemoteFiles, localShaByPath) }
251
- : project.config.files
252
- ? { files: project.config.files }
253
- : {}),
146
+ const project = {
147
+ rootDir: nearest.rootDir,
148
+ configPath: nearest.configPath,
149
+ config: nearest.config,
254
150
  };
255
- await writeProjectConfig(project.rootDir, nextConfig);
256
- project.config = nextConfig;
257
- if (!silent) {
258
- if (hasFileChanges && !shouldPushInfo && infoAnalysis.remoteChanged) {
259
- console.log(fmt.cyan(`ℹ Synced remote Pen info into ${PROJECT_CONFIG_FILENAME}.`));
151
+ const auth = await resolveCommandAuth({
152
+ explicitProfile: options.explicitProfile,
153
+ project,
154
+ interactive,
155
+ persistProfileToProject: !jsonMode,
156
+ output,
157
+ env: options.env,
158
+ homeDir: options.homeDir,
159
+ selectProfile: options.prompts?.select,
160
+ });
161
+ const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
162
+ const penLookup = await fetchLinkedPenOrHandleMissing({
163
+ client,
164
+ project,
165
+ auth,
166
+ commandName: 'push',
167
+ interactive,
168
+ json: jsonMode,
169
+ output,
170
+ prompts: options.prompts,
171
+ });
172
+ if (!penLookup.found) {
173
+ return { pushed: false, created: false, dryRun: Boolean(options.dryRun), aborted: true };
174
+ }
175
+ const result = await executePush(client, project, {
176
+ label: options.label,
177
+ force: options.force,
178
+ dryRun: options.dryRun,
179
+ wait: options.wait,
180
+ title: options.title,
181
+ access: resolvedAccess,
182
+ password: options.password,
183
+ json: jsonMode,
184
+ prefetchedPen: penLookup.pen,
185
+ silent: jsonMode,
186
+ output,
187
+ });
188
+ const hasFileChanges = result.changes.added.length > 0 ||
189
+ result.changes.modified.length > 0 ||
190
+ result.changes.deleted.length > 0;
191
+ const buildFailed = hasFileChanges && result.build?.status === 'Failed';
192
+ if (jsonMode) {
193
+ const payload = {
194
+ pushed: result.pushed,
195
+ created: false,
196
+ dry_run: result.dryRun,
197
+ pen: result.pen,
198
+ profile: auth.profile,
199
+ version_id: result.versionId,
200
+ build: result.build,
201
+ changes: result.changes,
202
+ info_changes: result.infoChanges,
203
+ applied_patches: result.appliedPatches,
204
+ };
205
+ if (result.dryRun) {
206
+ printJsonResponse(buildFailed ? 422 : 200, buildFailed
207
+ ? 'Dry run completed, but the build failed.'
208
+ : 'Dry run complete — no changes were saved to CodePen.', payload, output);
260
209
  }
261
- else if (hasFileChanges && !infoAnalysis.tracked) {
262
- console.log(fmt.dim(`Added Pen info to ${PROJECT_CONFIG_FILENAME}.`));
210
+ else if (!result.pushed) {
211
+ printJsonResponse(200, result.remoteInfoChanged
212
+ ? `No local changes to push. Remote Pen info has changed on CodePen — run \`cdpn pull\` to update ${PROJECT_CONFIG_FILENAME}, or \`cdpn push --force\` to overwrite.`
213
+ : 'Everything is up to date — nothing to push.', payload, output);
263
214
  }
264
- }
265
- if (hasFileChanges && finalBuild?.status === 'Failed') {
266
- if (!silent) {
267
- console.log(`\n${fmt.yellow('!')} Files were saved as version ${fmt.dim(shortId(finalVersionId))}, but the build failed.`);
215
+ else if (buildFailed) {
216
+ printJsonResponse(422, `Files were saved as version ${shortId(result.versionId)}, but the build failed.`, payload, output);
268
217
  }
269
- process.exitCode = 1;
270
- }
271
- else if (!silent) {
272
- if (hasFileChanges) {
273
- console.log(`\n${fmt.green('✓')} Pushed successfully ${fmt.dim(`(version ${shortId(finalVersionId)})`)}`);
274
- console.log(` Preview: ${fmt.cyan(updatedPen.urls.preview)}`);
218
+ else if (!hasFileChanges && result.infoChanges.length > 0) {
219
+ printJsonResponse(200, `Updated Pen info (${result.infoChanges.map((c) => c.field).join(', ')}).`, payload, output);
275
220
  }
276
221
  else {
277
- console.log(`\n${fmt.green('✓')} Updated Pen info successfully.`);
278
- console.log(` Editor: ${fmt.cyan(updatedPen.urls.editor)}`);
279
- console.log(` Preview: ${fmt.cyan(updatedPen.urls.preview)}`);
222
+ printJsonResponse(200, `Pushed successfully (version ${shortId(result.versionId)}).`, payload, output);
280
223
  }
281
224
  }
282
225
  return {
283
- pushed: true,
284
- dryRun: false,
285
- pen: updatedPen,
286
- versionId: finalVersionId,
287
- build: finalBuild,
288
- changes,
289
- infoChanges: infoChangesToPush,
290
- appliedPatches,
226
+ pushed: result.pushed,
227
+ created: false,
228
+ dryRun: result.dryRun,
229
+ pen: result.pen,
230
+ versionId: result.versionId,
231
+ build: result.build,
232
+ changes: result.changes,
233
+ infoChanges: result.infoChanges,
234
+ appliedPatches: result.appliedPatches,
235
+ ...(result.exitCode !== undefined ? { exitCode: result.exitCode } : {}),
291
236
  };
292
237
  }
293
238
  export function registerPushCommand(program) {
294
239
  program
295
240
  .command('push')
296
- .description('Push local file and Pen info changes to CodePen (or push an unlinked demo folder as a new Pen)')
241
+ .argument('[target]', 'Directory path to push, or "all" to push all Pens in subdirectories')
242
+ .allowExcessArguments(false)
243
+ .description('Push local file and Pen info changes to CodePen (pass "all" to walk subdirectories, or push an unlinked folder as a new Pen)')
297
244
  .option('-m, --label <label>', 'Label for the saved version (max 80 chars)')
298
245
  .option('-f, --force', 'Overwrite remote head if moved (or skip missing index.html prompt on first push)')
299
- .option('--dry-run', 'Build proposed changes without saving them to the Pen head')
246
+ .option('--dry-run', 'Preview changes without saving them to CodePen')
300
247
  .option('--no-wait', 'Return as soon as files are saved without waiting for the build')
301
248
  .option('-t, --title <title>', 'Title for the new Pen when pushing an unlinked folder for the first time')
302
249
  .option('--access <level>', 'Privacy for a new Pen: Public, Private, Protected, or Collaborators')
250
+ .option('--visibility <level>', 'Alias for --access')
303
251
  .option('--password <password>', 'Password for a new Protected Pen (min 8 chars)')
304
252
  .option('--json', 'Output push result as JSON')
305
- .action(async (options, command) => {
306
- if (options.label && options.label.length > 80) {
307
- throw new CliError(400, 'Version label must be at most 80 characters.');
308
- }
309
- const explicitProfile = getGlobalProfileOption(command);
310
- const project = await findProject(process.cwd());
311
- // First-time push: no .cdpn.json found -> push local folder as a brand-new CodePen 2.0 Pen
312
- if (!project) {
313
- if (options.dryRun) {
314
- throw new CliError(400, `No ${PROJECT_CONFIG_FILENAME} found. --dry-run is only supported for an existing synced Pen.`);
315
- }
316
- if (!options.json) {
317
- console.log(fmt.dim(`No ${PROJECT_CONFIG_FILENAME} found — pushing this local folder as a new CodePen 2.0 Pen.`));
318
- }
319
- const created = await createPenFromDirectory({
320
- targetDir: process.cwd(),
321
- folderDisplay: '.',
322
- explicitProfile,
323
- title: options.title,
324
- access: options.access,
325
- password: options.password,
326
- force: options.force,
327
- wait: options.wait,
328
- silent: Boolean(options.json),
329
- interactive: !options.json && isInteractive(),
330
- });
331
- if (created && options.json) {
332
- const buildFailed = created.build?.status === 'Failed';
333
- if (buildFailed) {
334
- process.exitCode = 1;
335
- }
336
- printJsonResponse(buildFailed ? 422 : 201, buildFailed
337
- ? `Created Pen ${created.pen.title || 'Untitled'} (${created.pen.id}), but the initial build failed.`
338
- : `Created Pen ${created.pen.title || 'Untitled'} (${created.pen.id}).`, {
339
- pushed: true,
340
- created: true,
341
- dry_run: false,
342
- pen: created.pen,
343
- profile: created.auth.profile,
344
- folder: '.',
345
- root_dir: created.project.rootDir,
346
- config_path: created.project.configPath,
347
- version_id: created.versionId,
348
- build: created.build,
349
- });
350
- }
351
- return;
352
- }
353
- const auth = await resolveCommandAuth({
354
- explicitProfile,
355
- project,
356
- interactive: !options.json && isInteractive(),
357
- persistProfileToProject: !options.json,
358
- });
359
- const client = new CodePenClient({ apiKey: auth.apiKey });
360
- const result = await executePush(client, project, {
253
+ .action(async (target, options, command) => {
254
+ const result = await runPushCommand({
361
255
  ...options,
362
- silent: Boolean(options.json),
256
+ target,
257
+ explicitProfile: getGlobalProfileOption(command),
363
258
  });
364
- if (options.json) {
365
- const hasFileChanges = result.changes.added.length > 0 ||
366
- result.changes.modified.length > 0 ||
367
- result.changes.deleted.length > 0;
368
- const buildFailed = hasFileChanges && result.build?.status === 'Failed';
369
- const payload = {
370
- pushed: result.pushed,
371
- created: false,
372
- dry_run: result.dryRun,
373
- pen: result.pen,
374
- profile: auth.profile,
375
- version_id: result.versionId,
376
- build: result.build,
377
- changes: result.changes,
378
- info_changes: result.infoChanges,
379
- applied_patches: result.appliedPatches,
380
- };
381
- if (result.dryRun) {
382
- if (buildFailed) {
383
- process.exitCode = 1;
384
- }
385
- printJsonResponse(buildFailed ? 422 : 200, buildFailed
386
- ? 'Dry run completed, but the build failed.'
387
- : 'Dry run complete — no changes were saved to CodePen.', payload);
388
- }
389
- else if (!result.pushed) {
390
- printJsonResponse(200, result.remoteInfoChanged
391
- ? `No local changes to push. Remote Pen info has changed on CodePen — run \`cdpn pull\` to update ${PROJECT_CONFIG_FILENAME}, or \`cdpn push --force\` to overwrite.`
392
- : 'Everything is up to date — nothing to push.', payload);
393
- }
394
- else if (buildFailed) {
395
- process.exitCode = 1;
396
- printJsonResponse(422, `Files were saved as version ${shortId(result.versionId)}, but the build failed.`, payload);
397
- }
398
- else if (!hasFileChanges && result.infoChanges.length > 0) {
399
- printJsonResponse(200, `Updated Pen info (${result.infoChanges.map((c) => c.field).join(', ')}).`, payload);
400
- }
401
- else {
402
- printJsonResponse(200, `Pushed successfully (version ${shortId(result.versionId)}).`, payload);
403
- }
259
+ if (result.exitCode !== undefined) {
260
+ process.exitCode = result.exitCode;
404
261
  }
405
262
  });
406
263
  }