codepen-commander 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +179 -2
- package/api/client.js +364 -0
- package/api/errors.js +49 -0
- package/cli.js +125 -0
- package/commands/auth-context.js +139 -0
- package/commands/auth.js +593 -0
- package/commands/clone.js +598 -0
- package/commands/create-pen.js +249 -0
- package/commands/delete.js +98 -0
- package/commands/deploy.js +176 -0
- package/commands/domains.js +197 -0
- package/commands/fork.js +342 -0
- package/commands/list.js +103 -0
- package/commands/meta.js +164 -0
- package/commands/new.js +294 -0
- package/commands/open.js +174 -0
- package/commands/privacy.js +234 -0
- package/commands/pull.js +128 -0
- package/commands/push.js +294 -0
- package/commands/scaffold.js +127 -0
- package/commands/status.js +131 -0
- package/commands/unowned-pen.js +153 -0
- package/commands/versions.js +172 -0
- package/config/auth.js +470 -0
- package/config/project.js +365 -0
- package/package.json +21 -4
- package/sync/diff.js +105 -0
- package/sync/fs.js +253 -0
- package/sync/materialize.js +81 -0
- package/types.js +1 -0
- package/utils/browser.js +47 -0
- package/utils/format.js +107 -0
- package/utils/html.js +51 -0
- package/utils/json.js +122 -0
- package/utils/prompts.js +316 -0
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { CodePenClient } from '../api/client.js';
|
|
2
|
+
import { requireProjectInDir } from '../config/project.js';
|
|
3
|
+
import { fmt } from '../utils/format.js';
|
|
4
|
+
import { CliError, printJsonResponse } from '../utils/json.js';
|
|
5
|
+
import { isInteractive, promptConfirm, promptSecret, promptSelect, } from '../utils/prompts.js';
|
|
6
|
+
import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
|
|
7
|
+
import { normalizeAccess } from './create-pen.js';
|
|
8
|
+
const ACCESS_CHOICES = [
|
|
9
|
+
{ value: 'Public', label: 'Public', description: 'visible to everyone' },
|
|
10
|
+
{ value: 'Private', label: 'Private', description: 'unlisted; anyone with the link can view it' },
|
|
11
|
+
{ value: 'Protected', label: 'Protected', description: 'private and password-protected (min 8 chars)' },
|
|
12
|
+
{ value: 'Collaborators', label: 'Collaborators', description: 'private; visible only to you and collaborators' },
|
|
13
|
+
];
|
|
14
|
+
async function promptForProtectedPassword(secretImpl, promptLabel) {
|
|
15
|
+
for (;;) {
|
|
16
|
+
const pw = await secretImpl(promptLabel);
|
|
17
|
+
if (pw.length >= 8)
|
|
18
|
+
return pw;
|
|
19
|
+
console.log(fmt.yellow('Password must be at least 8 characters.'));
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Inspects or updates the privacy/access permissions of the Pen linked by `.cdpn.json`
|
|
24
|
+
* directly inside `options.cwd` (does not walk up to parent folders).
|
|
25
|
+
*/
|
|
26
|
+
export async function managePenPrivacy(options = {}) {
|
|
27
|
+
const cwd = options.cwd ?? process.cwd();
|
|
28
|
+
const interactive = (options.interactive ?? isInteractive()) && !options.json;
|
|
29
|
+
const selectImpl = options.prompts?.select ?? promptSelect;
|
|
30
|
+
const secretImpl = options.prompts?.secret ?? promptSecret;
|
|
31
|
+
const confirmImpl = options.prompts?.confirm ?? promptConfirm;
|
|
32
|
+
// Strictly requires `.cdpn.json` in the current folder
|
|
33
|
+
const project = await requireProjectInDir(cwd);
|
|
34
|
+
const requestedAccess = normalizeAccess(options.levelArg);
|
|
35
|
+
if (options.password !== undefined) {
|
|
36
|
+
if (options.password.length < 8) {
|
|
37
|
+
throw new CliError(400, 'Password must be at least 8 characters.');
|
|
38
|
+
}
|
|
39
|
+
if (requestedAccess && requestedAccess !== 'Protected') {
|
|
40
|
+
throw new CliError(400, '--password can only be used with Protected privacy.');
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
if (options.show && (requestedAccess || options.password !== undefined)) {
|
|
44
|
+
throw new CliError(400, 'Cannot combine --show with a privacy level or --password.');
|
|
45
|
+
}
|
|
46
|
+
const auth = await resolveCommandAuth({
|
|
47
|
+
explicitProfile: options.explicitProfile,
|
|
48
|
+
project,
|
|
49
|
+
interactive,
|
|
50
|
+
persistProfileToProject: !options.json,
|
|
51
|
+
env: options.env,
|
|
52
|
+
homeDir: options.homeDir,
|
|
53
|
+
selectProfile: selectImpl,
|
|
54
|
+
});
|
|
55
|
+
const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
|
|
56
|
+
const currentPen = await client.getPen(project.config.pen_id);
|
|
57
|
+
const previousAccess = currentPen.access;
|
|
58
|
+
// Read-only mode: `--show`, or no level/password in non-interactive / `--json` mode
|
|
59
|
+
if (options.show || (!requestedAccess && options.password === undefined && !interactive)) {
|
|
60
|
+
if (options.json) {
|
|
61
|
+
printJsonResponse(200, `Pen privacy is ${currentPen.access}.`, {
|
|
62
|
+
pen_id: currentPen.id,
|
|
63
|
+
title: currentPen.title,
|
|
64
|
+
access: currentPen.access,
|
|
65
|
+
editor: currentPen.editor,
|
|
66
|
+
profile: auth.profile ?? project.config.profile ?? null,
|
|
67
|
+
updated: false,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
console.log(`${fmt.bold(currentPen.title || 'Untitled')} ${fmt.dim(`(${currentPen.id})`)}`);
|
|
72
|
+
if (auth.profile) {
|
|
73
|
+
console.log(` Profile: ${fmt.cyan(auth.profile)}`);
|
|
74
|
+
}
|
|
75
|
+
console.log(` Privacy: ${fmt.cyan(currentPen.access)}`);
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
pen: currentPen,
|
|
79
|
+
previousAccess,
|
|
80
|
+
access: currentPen.access,
|
|
81
|
+
updated: false,
|
|
82
|
+
passwordUpdated: false,
|
|
83
|
+
auth,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
// Determine target access and password
|
|
87
|
+
let targetAccess;
|
|
88
|
+
let password = options.password;
|
|
89
|
+
if (requestedAccess) {
|
|
90
|
+
targetAccess = requestedAccess;
|
|
91
|
+
}
|
|
92
|
+
else if (options.password !== undefined) {
|
|
93
|
+
if (previousAccess !== 'Protected') {
|
|
94
|
+
throw new CliError(400, `This Pen is currently ${previousAccess}. To set a password and make it Protected, run \`cdpn privacy protected --password <password>\`.`);
|
|
95
|
+
}
|
|
96
|
+
targetAccess = 'Protected';
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
// Interactive picker with current privacy pre-selected
|
|
100
|
+
console.log(`Current privacy for ${fmt.bold(currentPen.title || 'Untitled')} ${fmt.dim(`(${currentPen.id})`)}: ${fmt.cyan(previousAccess)}\n`);
|
|
101
|
+
const defaultIndex = Math.max(0, ACCESS_CHOICES.findIndex((c) => c.value === previousAccess));
|
|
102
|
+
const selectOptions = ACCESS_CHOICES.map((choice) => ({
|
|
103
|
+
value: choice.value,
|
|
104
|
+
label: choice.label,
|
|
105
|
+
description: choice.value === previousAccess ? `${choice.description} (current)` : choice.description,
|
|
106
|
+
}));
|
|
107
|
+
targetAccess = await selectImpl('Set Pen privacy:', selectOptions, defaultIndex);
|
|
108
|
+
}
|
|
109
|
+
const patch = {};
|
|
110
|
+
let passwordUpdated = false;
|
|
111
|
+
if (targetAccess === 'Protected') {
|
|
112
|
+
if (previousAccess === 'Protected') {
|
|
113
|
+
// Already Protected: rotate password if explicitly requested, or confirm in picker flow
|
|
114
|
+
if (!password) {
|
|
115
|
+
if (!interactive) {
|
|
116
|
+
throw new CliError(400, 'This Pen is already Protected. Pass --password <new-password> (min 8 chars) to replace its password.');
|
|
117
|
+
}
|
|
118
|
+
if (!requestedAccess) {
|
|
119
|
+
const rotate = await confirmImpl('Pen is already Protected. Replace its password?', false);
|
|
120
|
+
if (!rotate) {
|
|
121
|
+
console.log(`Privacy unchanged (${fmt.cyan('Protected')}).`);
|
|
122
|
+
return {
|
|
123
|
+
pen: currentPen,
|
|
124
|
+
previousAccess,
|
|
125
|
+
access: previousAccess,
|
|
126
|
+
updated: false,
|
|
127
|
+
passwordUpdated: false,
|
|
128
|
+
auth,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
password = await promptForProtectedPassword(secretImpl, 'New password for Protected Pen (min 8 characters)');
|
|
133
|
+
}
|
|
134
|
+
patch.password = password;
|
|
135
|
+
passwordUpdated = true;
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
// Changing to Protected -> password is required by CodePen API
|
|
139
|
+
if (!password) {
|
|
140
|
+
if (!interactive) {
|
|
141
|
+
throw new CliError(400, 'Changing privacy to Protected requires --password with at least 8 characters.');
|
|
142
|
+
}
|
|
143
|
+
password = await promptForProtectedPassword(secretImpl, 'Password for Protected Pen (min 8 characters)');
|
|
144
|
+
}
|
|
145
|
+
patch.access = 'Protected';
|
|
146
|
+
patch.password = password;
|
|
147
|
+
passwordUpdated = true;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
else if (targetAccess !== previousAccess) {
|
|
151
|
+
patch.access = targetAccess;
|
|
152
|
+
}
|
|
153
|
+
// No-op when privacy did not change
|
|
154
|
+
if (Object.keys(patch).length === 0) {
|
|
155
|
+
if (options.json) {
|
|
156
|
+
printJsonResponse(200, `Privacy is already ${currentPen.access} — no changes made.`, {
|
|
157
|
+
pen_id: currentPen.id,
|
|
158
|
+
title: currentPen.title,
|
|
159
|
+
previous_access: previousAccess,
|
|
160
|
+
access: currentPen.access,
|
|
161
|
+
editor: currentPen.editor,
|
|
162
|
+
profile: auth.profile ?? project.config.profile ?? null,
|
|
163
|
+
password_updated: false,
|
|
164
|
+
updated: false,
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
console.log(`Privacy is already ${fmt.cyan(currentPen.access)} — no changes made.`);
|
|
169
|
+
}
|
|
170
|
+
return {
|
|
171
|
+
pen: currentPen,
|
|
172
|
+
previousAccess,
|
|
173
|
+
access: currentPen.access,
|
|
174
|
+
updated: false,
|
|
175
|
+
passwordUpdated: false,
|
|
176
|
+
auth,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
const updatedPen = await client.updatePen(project.config.pen_id, patch);
|
|
180
|
+
if (options.json) {
|
|
181
|
+
const message = previousAccess === updatedPen.access && passwordUpdated
|
|
182
|
+
? 'Updated password for Protected Pen.'
|
|
183
|
+
: `Updated privacy from ${previousAccess} to ${updatedPen.access}.`;
|
|
184
|
+
printJsonResponse(200, message, {
|
|
185
|
+
pen_id: updatedPen.id,
|
|
186
|
+
title: updatedPen.title,
|
|
187
|
+
previous_access: previousAccess,
|
|
188
|
+
access: updatedPen.access,
|
|
189
|
+
editor: updatedPen.editor,
|
|
190
|
+
profile: auth.profile ?? project.config.profile ?? null,
|
|
191
|
+
password_updated: passwordUpdated,
|
|
192
|
+
updated: true,
|
|
193
|
+
url: updatedPen.urls.editor,
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
else if (previousAccess === updatedPen.access && passwordUpdated) {
|
|
197
|
+
console.log(`\n${fmt.green('✓')} Updated password for Protected Pen ${fmt.bold(updatedPen.title || 'Untitled')} ${fmt.dim(`(${updatedPen.id})`)}`);
|
|
198
|
+
}
|
|
199
|
+
else {
|
|
200
|
+
console.log(`\n${fmt.green('✓')} Updated privacy for ${fmt.bold(updatedPen.title || 'Untitled')} ${fmt.dim(`(${updatedPen.id})`)}: ${fmt.dim(previousAccess)} → ${fmt.cyan(updatedPen.access)}`);
|
|
201
|
+
}
|
|
202
|
+
if (!options.json) {
|
|
203
|
+
if (auth.profile) {
|
|
204
|
+
console.log(` Profile: ${fmt.cyan(auth.profile)}`);
|
|
205
|
+
}
|
|
206
|
+
console.log(` Editor: ${fmt.cyan(updatedPen.urls.editor)}`);
|
|
207
|
+
}
|
|
208
|
+
return {
|
|
209
|
+
pen: updatedPen,
|
|
210
|
+
previousAccess,
|
|
211
|
+
access: updatedPen.access,
|
|
212
|
+
updated: true,
|
|
213
|
+
passwordUpdated,
|
|
214
|
+
auth,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
export function registerPrivacyCommand(program) {
|
|
218
|
+
program
|
|
219
|
+
.command('privacy [level]')
|
|
220
|
+
.alias('access')
|
|
221
|
+
.description('View or update a Pen’s privacy permissions (Public, Private, Protected, Collaborators; requires .cdpn.json in current folder)')
|
|
222
|
+
.option('--password <password>', 'Password for Protected privacy (min 8 chars; replaces password if already Protected)')
|
|
223
|
+
.option('--show', 'Show the current privacy level without prompting')
|
|
224
|
+
.option('--json', 'Output privacy status/result as JSON')
|
|
225
|
+
.action(async (levelArg, options, command) => {
|
|
226
|
+
await managePenPrivacy({
|
|
227
|
+
levelArg,
|
|
228
|
+
password: options.password,
|
|
229
|
+
show: options.show,
|
|
230
|
+
json: options.json,
|
|
231
|
+
explicitProfile: getGlobalProfileOption(command),
|
|
232
|
+
});
|
|
233
|
+
});
|
|
234
|
+
}
|
package/commands/pull.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { CodePenClient } from '../api/client.js';
|
|
2
|
+
import { buildSyncedFileMap, requireProject, writeProjectConfig, } from '../config/project.js';
|
|
3
|
+
import { detectLocalChangesFromBaseline } from '../sync/diff.js';
|
|
4
|
+
import { scanLocalFiles } from '../sync/fs.js';
|
|
5
|
+
import { syncRemoteFilesToDisk } from '../sync/materialize.js';
|
|
6
|
+
import { fmt, shortId } from '../utils/format.js';
|
|
7
|
+
import { CliError, printJsonResponse } from '../utils/json.js';
|
|
8
|
+
import { isInteractive, promptConfirm, promptSelect, } from '../utils/prompts.js';
|
|
9
|
+
import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
|
|
10
|
+
/**
|
|
11
|
+
* Pulls the latest remote files from CodePen into an existing cloned folder containing `.cdpn.json`.
|
|
12
|
+
* Returns `null` if the user cancels interactively when uncommitted local changes are present.
|
|
13
|
+
*/
|
|
14
|
+
export async function pullPenCommand(options = {}) {
|
|
15
|
+
const cwd = options.cwd ?? process.cwd();
|
|
16
|
+
const jsonMode = Boolean(options.json);
|
|
17
|
+
const interactive = (options.interactive ?? isInteractive()) && !jsonMode;
|
|
18
|
+
const force = Boolean(options.force);
|
|
19
|
+
const confirmImpl = options.prompts?.confirm ?? promptConfirm;
|
|
20
|
+
const selectImpl = options.prompts?.select ?? promptSelect;
|
|
21
|
+
const project = await requireProject(cwd);
|
|
22
|
+
const auth = await resolveCommandAuth({
|
|
23
|
+
explicitProfile: options.explicitProfile,
|
|
24
|
+
project,
|
|
25
|
+
interactive,
|
|
26
|
+
persistProfileToProject: !jsonMode,
|
|
27
|
+
env: options.env,
|
|
28
|
+
homeDir: options.homeDir,
|
|
29
|
+
selectProfile: selectImpl,
|
|
30
|
+
});
|
|
31
|
+
const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
|
|
32
|
+
const { rootDir, config } = project;
|
|
33
|
+
if (!jsonMode) {
|
|
34
|
+
console.log(`Pulling latest changes for ${fmt.cyan(config.pen_id)}…`);
|
|
35
|
+
}
|
|
36
|
+
const localFiles = await scanLocalFiles(rootDir);
|
|
37
|
+
const localDirty = detectLocalChangesFromBaseline(localFiles, config.files);
|
|
38
|
+
const dirtyCount = localDirty.added.length + localDirty.modified.length + localDirty.deleted.length;
|
|
39
|
+
if (dirtyCount > 0 && !force) {
|
|
40
|
+
if (!jsonMode) {
|
|
41
|
+
console.log(fmt.yellow('\nWarning: You have uncommitted local changes that will be overwritten:'));
|
|
42
|
+
for (const p of localDirty.added)
|
|
43
|
+
console.log(` ${fmt.green('+')} ${p} ${fmt.dim('(will be removed)')}`);
|
|
44
|
+
for (const p of localDirty.modified)
|
|
45
|
+
console.log(` ${fmt.yellow('~')} ${p} ${fmt.dim('(will be overwritten)')}`);
|
|
46
|
+
for (const p of localDirty.deleted)
|
|
47
|
+
console.log(` ${fmt.red('-')} ${p} ${fmt.dim('(will be restored)')}`);
|
|
48
|
+
}
|
|
49
|
+
if (!interactive) {
|
|
50
|
+
throw new CliError(409, 'Local changes detected. Commit/push them first, or re-run with --force.', { dirty_files: localDirty });
|
|
51
|
+
}
|
|
52
|
+
const ok = await confirmImpl('\nOverwrite local changes with remote version?', false);
|
|
53
|
+
if (!ok) {
|
|
54
|
+
console.log('Aborted.');
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const [pen, remoteFiles] = await Promise.all([
|
|
59
|
+
client.getPen(config.pen_id),
|
|
60
|
+
client.getPenFiles(config.pen_id),
|
|
61
|
+
]);
|
|
62
|
+
const result = await syncRemoteFilesToDisk({
|
|
63
|
+
client,
|
|
64
|
+
rootDir,
|
|
65
|
+
remoteFiles,
|
|
66
|
+
existingLocalPaths: localFiles.keys(),
|
|
67
|
+
pruneRemoved: true,
|
|
68
|
+
});
|
|
69
|
+
const syncedFiles = buildSyncedFileMap(remoteFiles, result.localSha256ByPath);
|
|
70
|
+
const profileToPersist = config.profile ?? auth.profile ?? undefined;
|
|
71
|
+
const nextConfig = {
|
|
72
|
+
url: config.url || pen.urls.editor,
|
|
73
|
+
pen_id: pen.id,
|
|
74
|
+
...(profileToPersist ? { profile: profileToPersist } : {}),
|
|
75
|
+
last_synced_version_id: pen.saved_version?.id ?? null,
|
|
76
|
+
editor: pen.editor,
|
|
77
|
+
files: syncedFiles,
|
|
78
|
+
};
|
|
79
|
+
const configPath = await writeProjectConfig(rootDir, nextConfig);
|
|
80
|
+
if (jsonMode) {
|
|
81
|
+
printJsonResponse(200, `Synced ${pen.title || 'Untitled'}.`, {
|
|
82
|
+
pen,
|
|
83
|
+
profile: profileToPersist ?? null,
|
|
84
|
+
root_dir: rootDir,
|
|
85
|
+
config_path: configPath,
|
|
86
|
+
version_id: pen.saved_version?.id ?? null,
|
|
87
|
+
written_paths: result.writtenPaths,
|
|
88
|
+
deleted_paths: result.deletedPaths,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
console.log(`\n${fmt.green('✓')} Synced ${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)}`);
|
|
93
|
+
if (auth.profile) {
|
|
94
|
+
console.log(` Profile: ${fmt.cyan(auth.profile)}`);
|
|
95
|
+
}
|
|
96
|
+
console.log(` Updated: ${result.writtenPaths.length} file(s)` +
|
|
97
|
+
(result.deletedPaths.length > 0 ? `, removed ${result.deletedPaths.length} deleted file(s)` : ''));
|
|
98
|
+
if (pen.saved_version) {
|
|
99
|
+
console.log(` Version: ${fmt.dim(shortId(pen.saved_version.id))}`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
pen,
|
|
104
|
+
writtenPaths: result.writtenPaths,
|
|
105
|
+
deletedPaths: result.deletedPaths,
|
|
106
|
+
auth,
|
|
107
|
+
project: {
|
|
108
|
+
rootDir,
|
|
109
|
+
configPath,
|
|
110
|
+
config: nextConfig,
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
export function registerPullCommand(program) {
|
|
115
|
+
program
|
|
116
|
+
.command('pull')
|
|
117
|
+
.allowExcessArguments(false)
|
|
118
|
+
.description('Pull latest changes from CodePen into an existing cloned folder (requires .cdpn.json)')
|
|
119
|
+
.option('-f, --force', 'Overwrite local changes without prompting')
|
|
120
|
+
.option('--json', 'Output pull result as JSON')
|
|
121
|
+
.action(async (options, command) => {
|
|
122
|
+
await pullPenCommand({
|
|
123
|
+
force: options.force,
|
|
124
|
+
json: options.json,
|
|
125
|
+
explicitProfile: getGlobalProfileOption(command),
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
}
|
package/commands/push.js
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
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 { applyCompilerPatchesToDisk } from '../sync/materialize.js';
|
|
8
|
+
import { fmt, printBuildSummary, shortId } from '../utils/format.js';
|
|
9
|
+
import { CliError, printJsonResponse } from '../utils/json.js';
|
|
10
|
+
import { isInteractive } from '../utils/prompts.js';
|
|
11
|
+
export async function executePush(client, project, options = {}) {
|
|
12
|
+
const silent = Boolean(options.silent);
|
|
13
|
+
const [pen, remoteFiles, localFiles] = await Promise.all([
|
|
14
|
+
client.getPen(project.config.pen_id),
|
|
15
|
+
client.getPenFiles(project.config.pen_id),
|
|
16
|
+
scanLocalFiles(project.rootDir),
|
|
17
|
+
]);
|
|
18
|
+
if (pen.editor === 'Classic') {
|
|
19
|
+
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.');
|
|
20
|
+
}
|
|
21
|
+
const localHead = project.config.last_synced_version_id;
|
|
22
|
+
const remoteHead = pen.saved_version?.id ?? null;
|
|
23
|
+
if (remoteHead && localHead && remoteHead !== localHead && !options.force) {
|
|
24
|
+
throw new CliError(409, `Remote Pen head (${shortId(remoteHead)}) has moved ahead of your last synced version (${shortId(localHead)}).\n` +
|
|
25
|
+
'Run `cdpn status` to inspect differences, `cdpn pull` to sync remote changes, or `cdpn push --force` to overwrite.', {
|
|
26
|
+
local_head: localHead,
|
|
27
|
+
remote_head: remoteHead,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
const diff = await computeSyncDiff({
|
|
31
|
+
localFiles,
|
|
32
|
+
remoteFiles,
|
|
33
|
+
baseline: project.config.files,
|
|
34
|
+
downloadFile: (url) => client.downloadFile(url),
|
|
35
|
+
});
|
|
36
|
+
if (!hasDiffChanges(diff)) {
|
|
37
|
+
if (!silent) {
|
|
38
|
+
console.log(`${fmt.green('✓')} Everything is up to date — nothing to push.`);
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
pushed: false,
|
|
42
|
+
dryRun: Boolean(options.dryRun),
|
|
43
|
+
pen,
|
|
44
|
+
versionId: remoteHead,
|
|
45
|
+
build: pen.saved_version?.build ?? null,
|
|
46
|
+
changes: { added: [], modified: [], deleted: [] },
|
|
47
|
+
appliedPatches: [],
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
const changes = {
|
|
51
|
+
added: diff.added.map((item) => item.path),
|
|
52
|
+
modified: diff.modified.map((item) => item.path),
|
|
53
|
+
deleted: diff.deleted.map((item) => item.path),
|
|
54
|
+
};
|
|
55
|
+
if (!silent) {
|
|
56
|
+
console.log(`${options.dryRun ? 'Dry-run pushing' : 'Pushing'} changes to ${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)}:`);
|
|
57
|
+
for (const item of diff.added)
|
|
58
|
+
console.log(` ${fmt.green('+')} ${item.path}`);
|
|
59
|
+
for (const item of diff.modified)
|
|
60
|
+
console.log(` ${fmt.yellow('~')} ${item.path}`);
|
|
61
|
+
for (const item of diff.deleted)
|
|
62
|
+
console.log(` ${fmt.red('-')} ${item.path}`);
|
|
63
|
+
}
|
|
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 });
|
|
71
|
+
}
|
|
72
|
+
else {
|
|
73
|
+
fileChanges.push({
|
|
74
|
+
path: item.path,
|
|
75
|
+
content: local.textContent ?? '',
|
|
76
|
+
});
|
|
77
|
+
}
|
|
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…'));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
if (finalBuild && !silent) {
|
|
118
|
+
printBuildSummary(finalBuild);
|
|
119
|
+
}
|
|
120
|
+
const finalVersionId = finalBuild?.version_id ?? writeResult.version?.id ?? null;
|
|
121
|
+
const appliedPatches = finalBuild?.applied_patches ?? [];
|
|
122
|
+
if (options.dryRun) {
|
|
123
|
+
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)})`)}.` : '.'));
|
|
126
|
+
}
|
|
127
|
+
return {
|
|
128
|
+
pushed: false,
|
|
129
|
+
dryRun: true,
|
|
130
|
+
pen: writeResult.pen ?? pen,
|
|
131
|
+
versionId: finalVersionId,
|
|
132
|
+
build: finalBuild,
|
|
133
|
+
changes,
|
|
134
|
+
appliedPatches,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
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
|
+
});
|
|
150
|
+
if (!silent) {
|
|
151
|
+
console.log(fmt.cyan('✓ Synced compiler patches back to local folder.'));
|
|
152
|
+
}
|
|
153
|
+
}
|
|
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, {
|
|
163
|
+
url: project.config.url || updatedPen.urls.editor,
|
|
164
|
+
pen_id: updatedPen.id,
|
|
165
|
+
...(project.config.profile ? { profile: project.config.profile } : {}),
|
|
166
|
+
last_synced_version_id: finalVersionId,
|
|
167
|
+
editor: updatedPen.editor,
|
|
168
|
+
files: buildSyncedFileMap(finalRemoteFiles, localShaByPath),
|
|
169
|
+
});
|
|
170
|
+
if (finalBuild?.status === 'Failed') {
|
|
171
|
+
if (!silent) {
|
|
172
|
+
console.log(`\n${fmt.yellow('!')} Files were saved as version ${fmt.dim(shortId(finalVersionId))}, but the build failed.`);
|
|
173
|
+
}
|
|
174
|
+
process.exitCode = 1;
|
|
175
|
+
}
|
|
176
|
+
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)}`);
|
|
179
|
+
}
|
|
180
|
+
return {
|
|
181
|
+
pushed: true,
|
|
182
|
+
dryRun: false,
|
|
183
|
+
pen: updatedPen,
|
|
184
|
+
versionId: finalVersionId,
|
|
185
|
+
build: finalBuild,
|
|
186
|
+
changes,
|
|
187
|
+
appliedPatches,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
export function registerPushCommand(program) {
|
|
191
|
+
program
|
|
192
|
+
.command('push')
|
|
193
|
+
.description('Push local file changes to CodePen (or push an unlinked demo folder as a new Pen)')
|
|
194
|
+
.option('-m, --label <label>', 'Label for the saved version (max 80 chars)')
|
|
195
|
+
.option('-f, --force', 'Overwrite remote head if moved (or skip missing index.html prompt on first push)')
|
|
196
|
+
.option('--dry-run', 'Build proposed changes without saving them to the Pen head')
|
|
197
|
+
.option('--no-wait', 'Return as soon as files are saved without waiting for the build')
|
|
198
|
+
.option('-t, --title <title>', 'Title for the new Pen when pushing an unlinked folder for the first time')
|
|
199
|
+
.option('--access <level>', 'Privacy for a new Pen: Public, Private, Protected, or Collaborators')
|
|
200
|
+
.option('--password <password>', 'Password for a new Protected Pen (min 8 chars)')
|
|
201
|
+
.option('--json', 'Output push result as JSON')
|
|
202
|
+
.action(async (options, command) => {
|
|
203
|
+
if (options.label && options.label.length > 80) {
|
|
204
|
+
throw new CliError(400, 'Version label must be at most 80 characters.');
|
|
205
|
+
}
|
|
206
|
+
const explicitProfile = getGlobalProfileOption(command);
|
|
207
|
+
const project = await findProject(process.cwd());
|
|
208
|
+
// First-time push: no .cdpn.json found -> push local folder as a brand-new CodePen 2.0 Pen
|
|
209
|
+
if (!project) {
|
|
210
|
+
if (options.dryRun) {
|
|
211
|
+
throw new CliError(400, `No ${PROJECT_CONFIG_FILENAME} found. --dry-run is only supported for an existing synced Pen.`);
|
|
212
|
+
}
|
|
213
|
+
if (!options.json) {
|
|
214
|
+
console.log(fmt.dim(`No ${PROJECT_CONFIG_FILENAME} found — pushing this local folder as a new CodePen 2.0 Pen.`));
|
|
215
|
+
}
|
|
216
|
+
const created = await createPenFromDirectory({
|
|
217
|
+
targetDir: process.cwd(),
|
|
218
|
+
folderDisplay: '.',
|
|
219
|
+
explicitProfile,
|
|
220
|
+
title: options.title,
|
|
221
|
+
access: options.access,
|
|
222
|
+
password: options.password,
|
|
223
|
+
force: options.force,
|
|
224
|
+
wait: options.wait,
|
|
225
|
+
silent: Boolean(options.json),
|
|
226
|
+
interactive: !options.json && isInteractive(),
|
|
227
|
+
});
|
|
228
|
+
if (created && options.json) {
|
|
229
|
+
const buildFailed = created.build?.status === 'Failed';
|
|
230
|
+
if (buildFailed) {
|
|
231
|
+
process.exitCode = 1;
|
|
232
|
+
}
|
|
233
|
+
printJsonResponse(buildFailed ? 422 : 201, buildFailed
|
|
234
|
+
? `Created Pen ${created.pen.title || 'Untitled'} (${created.pen.id}), but the initial build failed.`
|
|
235
|
+
: `Created Pen ${created.pen.title || 'Untitled'} (${created.pen.id}).`, {
|
|
236
|
+
pushed: true,
|
|
237
|
+
created: true,
|
|
238
|
+
dry_run: false,
|
|
239
|
+
pen: created.pen,
|
|
240
|
+
profile: created.auth.profile,
|
|
241
|
+
folder: '.',
|
|
242
|
+
root_dir: created.project.rootDir,
|
|
243
|
+
config_path: created.project.configPath,
|
|
244
|
+
version_id: created.versionId,
|
|
245
|
+
build: created.build,
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
const auth = await resolveCommandAuth({
|
|
251
|
+
explicitProfile,
|
|
252
|
+
project,
|
|
253
|
+
interactive: !options.json && isInteractive(),
|
|
254
|
+
persistProfileToProject: !options.json,
|
|
255
|
+
});
|
|
256
|
+
const client = new CodePenClient({ apiKey: auth.apiKey });
|
|
257
|
+
const result = await executePush(client, project, {
|
|
258
|
+
...options,
|
|
259
|
+
silent: Boolean(options.json),
|
|
260
|
+
});
|
|
261
|
+
if (options.json) {
|
|
262
|
+
const buildFailed = result.build?.status === 'Failed';
|
|
263
|
+
const payload = {
|
|
264
|
+
pushed: result.pushed,
|
|
265
|
+
created: false,
|
|
266
|
+
dry_run: result.dryRun,
|
|
267
|
+
pen: result.pen,
|
|
268
|
+
profile: auth.profile,
|
|
269
|
+
version_id: result.versionId,
|
|
270
|
+
build: result.build,
|
|
271
|
+
changes: result.changes,
|
|
272
|
+
applied_patches: result.appliedPatches,
|
|
273
|
+
};
|
|
274
|
+
if (result.dryRun) {
|
|
275
|
+
if (buildFailed) {
|
|
276
|
+
process.exitCode = 1;
|
|
277
|
+
}
|
|
278
|
+
printJsonResponse(buildFailed ? 422 : 200, buildFailed
|
|
279
|
+
? 'Dry run completed, but the build failed.'
|
|
280
|
+
: 'Dry run complete — no changes were saved to CodePen head.', payload);
|
|
281
|
+
}
|
|
282
|
+
else if (!result.pushed) {
|
|
283
|
+
printJsonResponse(200, 'Everything is up to date — nothing to push.', payload);
|
|
284
|
+
}
|
|
285
|
+
else if (buildFailed) {
|
|
286
|
+
process.exitCode = 1;
|
|
287
|
+
printJsonResponse(422, `Files were saved as version ${shortId(result.versionId)}, but the build failed.`, payload);
|
|
288
|
+
}
|
|
289
|
+
else {
|
|
290
|
+
printJsonResponse(200, `Pushed successfully (version ${shortId(result.versionId)}).`, payload);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
});
|
|
294
|
+
}
|