codepen-commander 1.1.0 → 1.2.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/commands/push.js CHANGED
@@ -4,6 +4,7 @@ import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
4
4
  import { createPenFromDirectory } from './create-pen.js';
5
5
  import { computeSyncDiff, hasDiffChanges } from '../sync/diff.js';
6
6
  import { scanLocalFiles } from '../sync/fs.js';
7
+ import { analyzeInfoSync, buildInfoUpdatePatch, buildPenInfoConfigFields, formatInfoValue, hashPenInfo, isCompletePenInfo, } from '../sync/info.js';
7
8
  import { applyCompilerPatchesToDisk } from '../sync/materialize.js';
8
9
  import { fmt, printBuildSummary, shortId } from '../utils/format.js';
9
10
  import { CliError, printJsonResponse } from '../utils/json.js';
@@ -33,9 +34,46 @@ export async function executePush(client, project, options = {}) {
33
34
  baseline: project.config.files,
34
35
  downloadFile: (url) => client.downloadFile(url),
35
36
  });
36
- if (!hasDiffChanges(diff)) {
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
+ }
37
67
  if (!silent) {
38
- console.log(`${fmt.green('✓')} Everything is up to date — nothing to push.`);
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
+ }
39
77
  }
40
78
  return {
41
79
  pushed: false,
@@ -44,7 +82,9 @@ export async function executePush(client, project, options = {}) {
44
82
  versionId: remoteHead,
45
83
  build: pen.saved_version?.build ?? null,
46
84
  changes: { added: [], modified: [], deleted: [] },
85
+ infoChanges: [],
47
86
  appliedPatches: [],
87
+ remoteInfoChanged: infoAnalysis.remoteChanged,
48
88
  };
49
89
  }
50
90
  const changes = {
@@ -60,122 +100,184 @@ export async function executePush(client, project, options = {}) {
60
100
  console.log(` ${fmt.yellow('~')} ${item.path}`);
61
101
  for (const item of diff.deleted)
62
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
+ }
63
106
  }
64
- const fileChanges = [];
65
- const binaryUploads = [];
66
- for (const item of [...diff.added, ...diff.modified]) {
67
- const local = item.local;
68
- // Note: CodePen API returns 400 on empty multipart parts, so 0-byte files always go as text JSON
69
- if (local.isBinary && local.buffer.length > 0) {
70
- binaryUploads.push({ path: item.path, content: local.buffer });
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
+ }
71
128
  }
72
- else {
129
+ for (const item of diff.deleted) {
73
130
  fileChanges.push({
74
131
  path: item.path,
75
- content: local.textContent ?? '',
132
+ delete: true,
76
133
  });
77
134
  }
78
- }
79
- for (const item of diff.deleted) {
80
- fileChanges.push({
81
- path: item.path,
82
- delete: true,
83
- });
84
- }
85
- const expectedVersionId = options.force ? undefined : (localHead ?? remoteHead ?? undefined);
86
- const shouldWait = options.wait !== false;
87
- if (!silent) {
88
- console.log(shouldWait ? '\nUploading and building on CodePen…' : '\nUploading to CodePen…');
89
- }
90
- const writeResult = await client.writePenFiles(pen.id, {
91
- files: fileChanges,
92
- ...(options.label ? { label: options.label } : {}),
93
- ...(expectedVersionId ? { expected_version_id: expectedVersionId } : {}),
94
- ...(options.dryRun ? { dry_run: true } : {}),
95
- wait: shouldWait ? 45 : 0,
96
- }, binaryUploads);
97
- let finalBuild = writeResult.build;
98
- if (finalBuild && shouldWait) {
99
- let lastStatus = `${finalBuild.status}:${finalBuild.id}`;
100
- finalBuild = await client.settleBuild(finalBuild, {
101
- onUpdate: (b) => {
102
- if (silent)
103
- return;
104
- const key = `${b.status}:${b.id}`;
105
- if (key !== lastStatus) {
106
- lastStatus = key;
107
- if (b.status === 'Running' || b.status === 'Queued') {
108
- console.log(fmt.dim(` Build ${shortId(b.id)}: ${b.status}…`));
109
- }
110
- else if (b.status === 'Canceled' && b.next_id) {
111
- console.log(fmt.dim(' Compiler requested patches — waiting for converged rebuild…'));
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…');
139
+ }
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
+ }
112
163
  }
164
+ },
165
+ });
166
+ }
167
+ if (finalBuild && !silent) {
168
+ printBuildSummary(finalBuild);
169
+ }
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.'));
113
189
  }
114
- },
115
- });
116
- }
117
- if (finalBuild && !silent) {
118
- printBuildSummary(finalBuild);
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
+ }
216
+ }
119
217
  }
120
- const finalVersionId = finalBuild?.version_id ?? writeResult.version?.id ?? null;
121
- const appliedPatches = finalBuild?.applied_patches ?? [];
122
218
  if (options.dryRun) {
123
219
  if (!silent) {
124
- console.log(`\n${fmt.cyan('ℹ')} Dry run complete — no changes were saved to CodePen head` +
125
- (finalVersionId ? ` ${fmt.dim(`(ephemeral version ${shortId(finalVersionId)})`)}.` : '.'));
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
+ : '.'));
126
224
  }
127
225
  return {
128
226
  pushed: false,
129
227
  dryRun: true,
130
- pen: writeResult.pen ?? pen,
131
- versionId: finalVersionId,
132
- build: finalBuild,
228
+ pen: updatedPen,
229
+ versionId: hasFileChanges ? finalVersionId : remoteHead,
230
+ build: hasFileChanges ? finalBuild : null,
133
231
  changes,
232
+ infoChanges: infoChangesToPush,
134
233
  appliedPatches,
135
234
  };
136
235
  }
137
- // Re-read the converged version's source files so we write back any compiler patches
138
- let convergedFiles = writeResult.version?.files;
139
- if (finalVersionId && (appliedPatches.length > 0 || !convergedFiles)) {
140
- const version = await client.getVersion(finalVersionId);
141
- convergedFiles = version.files;
142
- }
143
- if (finalBuild && appliedPatches.length > 0) {
144
- await applyCompilerPatchesToDisk({
145
- client,
146
- rootDir: project.rootDir,
147
- patches: appliedPatches,
148
- convergedFiles,
149
- });
236
+ if (shouldPushInfo && infoPatch) {
150
237
  if (!silent) {
151
- console.log(fmt.cyan('✓ Synced compiler patches back to local folder.'));
238
+ console.log('\nUpdating Pen info on CodePen…');
152
239
  }
240
+ updatedPen = await client.updatePen(pen.id, infoPatch);
153
241
  }
154
- // Re-scan local hashes so .cdpn.json reflects exact post-patch local state
155
- const postPushLocalFiles = await scanLocalFiles(project.rootDir);
156
- const localShaByPath = new Map();
157
- for (const [p, lf] of postPushLocalFiles) {
158
- localShaByPath.set(p, lf.sha256);
159
- }
160
- const finalRemoteFiles = convergedFiles ?? (await client.getPenFiles(pen.id));
161
- const updatedPen = writeResult.pen ?? pen;
162
- await writeProjectConfig(project.rootDir, {
242
+ const nextConfig = {
163
243
  url: project.config.url || updatedPen.urls.editor,
164
244
  pen_id: updatedPen.id,
165
245
  ...(project.config.profile ? { profile: project.config.profile } : {}),
166
- last_synced_version_id: finalVersionId,
246
+ last_synced_version_id: hasFileChanges ? finalVersionId : project.config.last_synced_version_id,
167
247
  editor: updatedPen.editor,
168
- files: buildSyncedFileMap(finalRemoteFiles, localShaByPath),
169
- });
170
- if (finalBuild?.status === 'Failed') {
248
+ ...buildPenInfoConfigFields(updatedPen),
249
+ ...(hasFileChanges && finalRemoteFiles && localShaByPath
250
+ ? { files: buildSyncedFileMap(finalRemoteFiles, localShaByPath) }
251
+ : project.config.files
252
+ ? { files: project.config.files }
253
+ : {}),
254
+ };
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}.`));
260
+ }
261
+ else if (hasFileChanges && !infoAnalysis.tracked) {
262
+ console.log(fmt.dim(`Added Pen info to ${PROJECT_CONFIG_FILENAME}.`));
263
+ }
264
+ }
265
+ if (hasFileChanges && finalBuild?.status === 'Failed') {
171
266
  if (!silent) {
172
267
  console.log(`\n${fmt.yellow('!')} Files were saved as version ${fmt.dim(shortId(finalVersionId))}, but the build failed.`);
173
268
  }
174
269
  process.exitCode = 1;
175
270
  }
176
271
  else if (!silent) {
177
- console.log(`\n${fmt.green('✓')} Pushed successfully ${fmt.dim(`(version ${shortId(finalVersionId)})`)}`);
178
- console.log(` Preview: ${fmt.cyan(updatedPen.urls.preview)}`);
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)}`);
275
+ }
276
+ 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)}`);
280
+ }
179
281
  }
180
282
  return {
181
283
  pushed: true,
@@ -184,13 +286,14 @@ export async function executePush(client, project, options = {}) {
184
286
  versionId: finalVersionId,
185
287
  build: finalBuild,
186
288
  changes,
289
+ infoChanges: infoChangesToPush,
187
290
  appliedPatches,
188
291
  };
189
292
  }
190
293
  export function registerPushCommand(program) {
191
294
  program
192
295
  .command('push')
193
- .description('Push local file changes to CodePen (or push an unlinked demo folder as a new Pen)')
296
+ .description('Push local file and Pen info changes to CodePen (or push an unlinked demo folder as a new Pen)')
194
297
  .option('-m, --label <label>', 'Label for the saved version (max 80 chars)')
195
298
  .option('-f, --force', 'Overwrite remote head if moved (or skip missing index.html prompt on first push)')
196
299
  .option('--dry-run', 'Build proposed changes without saving them to the Pen head')
@@ -259,7 +362,10 @@ export function registerPushCommand(program) {
259
362
  silent: Boolean(options.json),
260
363
  });
261
364
  if (options.json) {
262
- const buildFailed = result.build?.status === 'Failed';
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';
263
369
  const payload = {
264
370
  pushed: result.pushed,
265
371
  created: false,
@@ -269,6 +375,7 @@ export function registerPushCommand(program) {
269
375
  version_id: result.versionId,
270
376
  build: result.build,
271
377
  changes: result.changes,
378
+ info_changes: result.infoChanges,
272
379
  applied_patches: result.appliedPatches,
273
380
  };
274
381
  if (result.dryRun) {
@@ -277,15 +384,20 @@ export function registerPushCommand(program) {
277
384
  }
278
385
  printJsonResponse(buildFailed ? 422 : 200, buildFailed
279
386
  ? 'Dry run completed, but the build failed.'
280
- : 'Dry run complete — no changes were saved to CodePen head.', payload);
387
+ : 'Dry run complete — no changes were saved to CodePen.', payload);
281
388
  }
282
389
  else if (!result.pushed) {
283
- printJsonResponse(200, 'Everything is up to date — nothing to push.', payload);
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);
284
393
  }
285
394
  else if (buildFailed) {
286
395
  process.exitCode = 1;
287
396
  printJsonResponse(422, `Files were saved as version ${shortId(result.versionId)}, but the build failed.`, payload);
288
397
  }
398
+ else if (!hasFileChanges && result.infoChanges.length > 0) {
399
+ printJsonResponse(200, `Updated Pen info (${result.infoChanges.map((c) => c.field).join(', ')}).`, payload);
400
+ }
289
401
  else {
290
402
  printJsonResponse(200, `Pushed successfully (version ${shortId(result.versionId)}).`, payload);
291
403
  }