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.
- package/README.md +104 -10
- package/api/client.js +129 -106
- package/cli.js +34 -29
- package/commands/auth/default.js +40 -0
- package/commands/auth/index.js +83 -0
- package/commands/auth/list.js +78 -0
- package/commands/auth/login.js +136 -0
- package/commands/auth/logout.js +186 -0
- package/commands/auth/status.js +212 -0
- package/commands/build.js +256 -0
- package/commands/clone.js +13 -581
- package/commands/delete.js +553 -37
- package/commands/deploy.js +164 -154
- package/commands/domains.js +83 -39
- package/commands/fork.js +13 -317
- package/commands/info.js +152 -0
- package/commands/init.js +375 -0
- package/commands/list.js +95 -78
- package/commands/new.js +155 -83
- package/commands/open.js +29 -19
- package/commands/privacy.js +52 -36
- package/commands/pull.js +123 -110
- package/commands/push.js +222 -365
- package/commands/restore.js +251 -0
- package/commands/rollback.js +141 -0
- package/commands/serve.js +119 -0
- package/commands/settings.js +126 -0
- package/commands/shell.js +305 -0
- package/commands/status.js +133 -39
- package/commands/sync.js +330 -0
- package/commands/undeploy.js +102 -0
- package/commands/unlink.js +191 -0
- package/commands/versions.js +100 -163
- package/config/auth.js +4 -374
- package/config/pen-blocks.js +166 -0
- package/config/project.js +179 -240
- package/config/user-store.js +364 -0
- package/constants.js +42 -0
- package/errors.js +17 -0
- package/package.json +1 -1
- package/shell/index.html +79 -0
- package/shell/scripts.js +276 -0
- package/shell/styles.css +492 -0
- package/site/blocks/classic.js +270 -0
- package/site/blocks/context.js +63 -0
- package/site/blocks/index.js +4 -0
- package/site/blocks/packages.js +242 -0
- package/site/blocks/unsupported-page.js +328 -0
- package/site/builder.js +475 -0
- package/site/detect.js +65 -0
- package/site/ignore-files.js +90 -0
- package/site/manifest.js +227 -0
- package/site/server.js +483 -0
- package/site/shell.js +363 -0
- package/sync/fs.js +19 -17
- package/sync/info.js +6 -81
- package/utils/browser.js +17 -10
- package/utils/cli-options.js +79 -0
- package/utils/codepen-url.js +183 -0
- package/utils/format.js +39 -30
- package/utils/fs-safe.js +95 -0
- package/utils/html.js +40 -1
- package/utils/json.js +4 -19
- package/utils/output.js +37 -0
- package/utils/package-paths.js +51 -0
- package/utils/prompts/index.js +5 -0
- package/utils/prompts/multi-select.js +185 -0
- package/utils/prompts/secret.js +65 -0
- package/utils/prompts/select.js +141 -0
- package/utils/prompts/text.js +99 -0
- package/utils/prompts/tty-list.js +165 -0
- package/utils/prompts/types.js +35 -0
- package/utils/strings.js +98 -0
- package/utils/watcher.js +82 -0
- package/{commands → workflows}/auth-context.js +13 -7
- package/workflows/batch-pens.js +1647 -0
- package/workflows/batch-target.js +184 -0
- package/workflows/classic-convert.js +241 -0
- package/workflows/clone-pen.js +381 -0
- package/workflows/create-pen.js +254 -0
- package/workflows/discover-pens.js +91 -0
- package/workflows/fork-pen.js +314 -0
- package/workflows/missing-pen.js +212 -0
- package/workflows/pull-pen.js +204 -0
- package/workflows/push-pen.js +318 -0
- package/{commands → workflows}/scaffold.js +4 -3
- package/workflows/sync-pen.js +227 -0
- package/{commands → workflows}/unowned-pen.js +16 -12
- package/commands/auth.js +0 -593
- package/commands/create-pen.js +0 -251
- package/commands/meta.js +0 -184
- package/utils/prompts.js +0 -316
- /package/{types.js → api/types.js} +0 -0
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { CodePenClient } from '../api/client.js';
|
|
2
|
+
import { findNearestConfig } from '../config/project.js';
|
|
3
|
+
import { CODEPEN_DELETED_ITEMS_URL, PROJECT_CONFIG_FILENAME } from '../constants.js';
|
|
4
|
+
import { CliError } from '../errors.js';
|
|
5
|
+
import { normalizePenReference } from '../utils/codepen-url.js';
|
|
6
|
+
import { fmt, formatDate } from '../utils/format.js';
|
|
7
|
+
import { printJsonResponse } from '../utils/json.js';
|
|
8
|
+
import { defaultOutput } from '../utils/output.js';
|
|
9
|
+
import { isInteractive, promptSelect } from '../utils/prompts/index.js';
|
|
10
|
+
import { getGlobalProfileOption, resolveCommandAuth } from '../workflows/auth-context.js';
|
|
11
|
+
import { findProjectPenInTrash, isRemotePenNotFoundError } from '../workflows/missing-pen.js';
|
|
12
|
+
function emitRestoreSuccess(params) {
|
|
13
|
+
const { pen, auth, project, restored, alreadyActive, trashItem, json, output } = params;
|
|
14
|
+
const title = pen.title || trashItem?.title || 'Untitled';
|
|
15
|
+
if (json) {
|
|
16
|
+
const message = alreadyActive
|
|
17
|
+
? `Pen ${title} (${pen.id}) is already active on CodePen (not in Deleted Items).`
|
|
18
|
+
: `Restored ${title} (${pen.id}) from CodePen Trash.`;
|
|
19
|
+
printJsonResponse(200, message, {
|
|
20
|
+
pen,
|
|
21
|
+
pen_id: pen.id,
|
|
22
|
+
title,
|
|
23
|
+
profile: auth.profile,
|
|
24
|
+
editor_url: pen.urls.editor,
|
|
25
|
+
restored,
|
|
26
|
+
already_active: alreadyActive,
|
|
27
|
+
linked_project: project !== null,
|
|
28
|
+
...(trashItem ? { trash_item: trashItem } : {}),
|
|
29
|
+
}, output);
|
|
30
|
+
}
|
|
31
|
+
else if (alreadyActive) {
|
|
32
|
+
output.log(`${fmt.green('✓')} Pen ${fmt.bold(title)} ${fmt.dim(`(${pen.id})`)} is already active on CodePen ${fmt.dim('(not in Deleted Items)')}.`);
|
|
33
|
+
if (auth.profile) {
|
|
34
|
+
output.log(` Profile: ${fmt.cyan(auth.profile)}`);
|
|
35
|
+
}
|
|
36
|
+
output.log(` Editor: ${fmt.cyan(pen.urls.editor)}`);
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
output.log(`\n${fmt.boldGreen('✓')} Restored ${fmt.bold(title)} ${fmt.dim(`(${pen.id})`)} from CodePen Trash!`);
|
|
40
|
+
if (auth.profile) {
|
|
41
|
+
output.log(` Profile: ${fmt.cyan(auth.profile)}`);
|
|
42
|
+
}
|
|
43
|
+
output.log(` Editor: ${fmt.cyan(pen.urls.editor)}`);
|
|
44
|
+
if (project) {
|
|
45
|
+
output.log(` ${fmt.dim(`${PROJECT_CONFIG_FILENAME} is still linked — run \`cdpn status\` to inspect or \`cdpn push\` / \`cdpn pull\` to sync.`)}`);
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
output.log(` ${fmt.dim(`Tip: Run \`cdpn clone ${pen.urls.editor}\` to clone it locally.`)}`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
pen,
|
|
53
|
+
auth,
|
|
54
|
+
project,
|
|
55
|
+
restored,
|
|
56
|
+
alreadyActive,
|
|
57
|
+
trashItem,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Restores a deleted Pen from CodePen Deleted Items (Trash) via `POST /v2/pens/{id}/restore`.
|
|
62
|
+
*
|
|
63
|
+
* Resolution order:
|
|
64
|
+
* 1. Explicit `[pen]` URL or ID argument (`cdpn restore <id|url>`).
|
|
65
|
+
* 2. Linked `.cdpn.json` in the current or parent directory (`cdpn restore`).
|
|
66
|
+
* 3. Interactive Trash picker (`GET /v2/trash`) when invoked outside any Pen folder.
|
|
67
|
+
*
|
|
68
|
+
* Returns `null` when invoked interactively outside a Pen folder and Trash has no deleted Pens.
|
|
69
|
+
*/
|
|
70
|
+
export async function runRestoreCommand(options = {}) {
|
|
71
|
+
const output = options.output ?? defaultOutput;
|
|
72
|
+
const cwd = options.cwd ?? process.cwd();
|
|
73
|
+
const jsonMode = Boolean(options.json);
|
|
74
|
+
const interactive = !jsonMode && (options.interactive ?? isInteractive());
|
|
75
|
+
const selectImpl = options.prompts?.select ?? promptSelect;
|
|
76
|
+
const trimmedPenArg = options.penArg?.trim();
|
|
77
|
+
// Case 1: Explicit Pen ID or URL provided
|
|
78
|
+
if (trimmedPenArg) {
|
|
79
|
+
const ref = normalizePenReference(trimmedPenArg);
|
|
80
|
+
const auth = await resolveCommandAuth({
|
|
81
|
+
explicitProfile: options.explicitProfile,
|
|
82
|
+
urlHint: ref.originalUrl,
|
|
83
|
+
autoSelectUrlMatch: true,
|
|
84
|
+
interactive,
|
|
85
|
+
promptMessage: 'Which CodePen profile owns this Pen?',
|
|
86
|
+
output,
|
|
87
|
+
env: options.env,
|
|
88
|
+
homeDir: options.homeDir,
|
|
89
|
+
selectProfile: selectImpl,
|
|
90
|
+
});
|
|
91
|
+
const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
|
|
92
|
+
// Check if Pen is already active (not in Trash)
|
|
93
|
+
try {
|
|
94
|
+
const activePen = await client.getPen(ref.apiIdentifier);
|
|
95
|
+
return emitRestoreSuccess({
|
|
96
|
+
pen: activePen,
|
|
97
|
+
auth,
|
|
98
|
+
project: null,
|
|
99
|
+
restored: false,
|
|
100
|
+
alreadyActive: true,
|
|
101
|
+
trashItem: null,
|
|
102
|
+
json: jsonMode,
|
|
103
|
+
output,
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
if (!isRemotePenNotFoundError(error)) {
|
|
108
|
+
throw error;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
const trashItem = await client.findTrashedPen(ref.apiIdentifier);
|
|
112
|
+
if (!trashItem) {
|
|
113
|
+
const profileHint = auth.profile ? ` (active profile: ${auth.profile})` : '';
|
|
114
|
+
throw new CliError(404, `Pen "${trimmedPenArg}" was not found in CodePen’s Deleted Items (Trash)${profileHint}.\n` +
|
|
115
|
+
`It may have already expired or been permanently deleted, or belongs to a different account/profile.\n` +
|
|
116
|
+
`Check ${CODEPEN_DELETED_ITEMS_URL} or re-run with --profile <name>.`, {
|
|
117
|
+
pen_id: ref.apiIdentifier,
|
|
118
|
+
profile: auth.profile,
|
|
119
|
+
in_trash: false,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
const restoredPen = await client.restorePen(trashItem.item_id);
|
|
123
|
+
return emitRestoreSuccess({
|
|
124
|
+
pen: restoredPen,
|
|
125
|
+
auth,
|
|
126
|
+
project: null,
|
|
127
|
+
restored: true,
|
|
128
|
+
alreadyActive: false,
|
|
129
|
+
trashItem,
|
|
130
|
+
json: jsonMode,
|
|
131
|
+
output,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
// Case 2: Look for `.cdpn.json` in current or parent directory
|
|
135
|
+
const nearest = await findNearestConfig(cwd);
|
|
136
|
+
if (nearest && !nearest.linked) {
|
|
137
|
+
throw new CliError(404, `${PROJECT_CONFIG_FILENAME} in ${nearest.rootDir} only contains Pen info and is not linked to an online Pen.\n` +
|
|
138
|
+
'Pass a Pen URL or ID (`cdpn restore <url-or-id>`) to restore a specific deleted Pen, or run `cdpn push` to publish this folder as a new Pen.');
|
|
139
|
+
}
|
|
140
|
+
if (nearest && nearest.linked) {
|
|
141
|
+
const project = {
|
|
142
|
+
rootDir: nearest.rootDir,
|
|
143
|
+
configPath: nearest.configPath,
|
|
144
|
+
config: nearest.config,
|
|
145
|
+
};
|
|
146
|
+
const auth = await resolveCommandAuth({
|
|
147
|
+
explicitProfile: options.explicitProfile,
|
|
148
|
+
project,
|
|
149
|
+
interactive,
|
|
150
|
+
persistProfileToProject: false,
|
|
151
|
+
output,
|
|
152
|
+
env: options.env,
|
|
153
|
+
homeDir: options.homeDir,
|
|
154
|
+
selectProfile: selectImpl,
|
|
155
|
+
});
|
|
156
|
+
const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
|
|
157
|
+
try {
|
|
158
|
+
const activePen = await client.getPen(project.config.pen_id);
|
|
159
|
+
return emitRestoreSuccess({
|
|
160
|
+
pen: activePen,
|
|
161
|
+
auth,
|
|
162
|
+
project,
|
|
163
|
+
restored: false,
|
|
164
|
+
alreadyActive: true,
|
|
165
|
+
trashItem: null,
|
|
166
|
+
json: jsonMode,
|
|
167
|
+
output,
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
catch (error) {
|
|
171
|
+
if (!isRemotePenNotFoundError(error)) {
|
|
172
|
+
throw error;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
const trashItem = await findProjectPenInTrash(client, project);
|
|
176
|
+
if (!trashItem) {
|
|
177
|
+
const displayTitle = project.config.info?.title || 'Untitled';
|
|
178
|
+
const profileHint = auth.profile ? ` (active profile: ${auth.profile})` : '';
|
|
179
|
+
throw new CliError(404, `Pen "${displayTitle}" (${project.config.pen_id}) was not found in CodePen’s Deleted Items (Trash)${profileHint}.\n` +
|
|
180
|
+
'It may have been permanently deleted or expired after 3 days, or belongs to a different account/profile.\n' +
|
|
181
|
+
`Run \`cdpn unlink\` to clear the remote link in ${PROJECT_CONFIG_FILENAME} (keeping local files and Pen info), or re-run with --profile <name>.`, {
|
|
182
|
+
pen_id: project.config.pen_id,
|
|
183
|
+
url: project.config.url,
|
|
184
|
+
profile: auth.profile,
|
|
185
|
+
in_trash: false,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
const restoredPen = await client.restorePen(trashItem.item_id);
|
|
189
|
+
return emitRestoreSuccess({
|
|
190
|
+
pen: restoredPen,
|
|
191
|
+
auth,
|
|
192
|
+
project,
|
|
193
|
+
restored: true,
|
|
194
|
+
alreadyActive: false,
|
|
195
|
+
trashItem,
|
|
196
|
+
json: jsonMode,
|
|
197
|
+
output,
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
// Case 3: No `.cdpn.json` and no explicit `[pen]` argument
|
|
201
|
+
if (!interactive) {
|
|
202
|
+
throw new CliError(400, `No ${PROJECT_CONFIG_FILENAME} found in this directory or any parent directory.\n` +
|
|
203
|
+
'Pass a Pen URL or ID (`cdpn restore <url-or-id>`) or run `cdpn restore` interactively to pick a Pen from CodePen Trash.');
|
|
204
|
+
}
|
|
205
|
+
const auth = await resolveCommandAuth({
|
|
206
|
+
explicitProfile: options.explicitProfile,
|
|
207
|
+
interactive,
|
|
208
|
+
promptMessage: 'Which CodePen profile would you like to inspect Trash for?',
|
|
209
|
+
output,
|
|
210
|
+
env: options.env,
|
|
211
|
+
homeDir: options.homeDir,
|
|
212
|
+
selectProfile: selectImpl,
|
|
213
|
+
});
|
|
214
|
+
const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
|
|
215
|
+
const trashPage = await client.listTrash({ per_page: 50, sort: 'updated', direction: 'desc' });
|
|
216
|
+
const trashedPens = trashPage.items.filter((item) => item.type === 'Pen');
|
|
217
|
+
if (trashedPens.length === 0) {
|
|
218
|
+
output.log(fmt.dim('No deleted Pens found in CodePen Trash.'));
|
|
219
|
+
return null;
|
|
220
|
+
}
|
|
221
|
+
const selectedItemId = await selectImpl('Select a deleted Pen to restore from CodePen Trash:', trashedPens.map((item) => ({
|
|
222
|
+
value: item.item_id,
|
|
223
|
+
label: `${item.title || 'Untitled'} (${item.item_id})`,
|
|
224
|
+
description: `deleted ${formatDate(item.deleted_at)} · expires ${formatDate(item.expires_at)}`,
|
|
225
|
+
})), 0);
|
|
226
|
+
const chosen = trashedPens.find((item) => item.item_id === selectedItemId) ?? null;
|
|
227
|
+
const restoredPen = await client.restorePen(selectedItemId);
|
|
228
|
+
return emitRestoreSuccess({
|
|
229
|
+
pen: restoredPen,
|
|
230
|
+
auth,
|
|
231
|
+
project: null,
|
|
232
|
+
restored: true,
|
|
233
|
+
alreadyActive: false,
|
|
234
|
+
trashItem: chosen,
|
|
235
|
+
json: jsonMode,
|
|
236
|
+
output,
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
export function registerRestoreCommand(program) {
|
|
240
|
+
program
|
|
241
|
+
.command('restore [pen]')
|
|
242
|
+
.description('Restore a deleted Pen from CodePen Deleted Items (Trash)')
|
|
243
|
+
.option('--json', 'Output restore result as JSON')
|
|
244
|
+
.action(async (penArg, options, command) => {
|
|
245
|
+
await runRestoreCommand({
|
|
246
|
+
penArg,
|
|
247
|
+
json: options.json,
|
|
248
|
+
explicitProfile: getGlobalProfileOption(command),
|
|
249
|
+
});
|
|
250
|
+
});
|
|
251
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { CodePenClient } from '../api/client.js';
|
|
2
|
+
import { buildSyncedFileMap, requireProject, writeProjectConfig } from '../config/project.js';
|
|
3
|
+
import { CliError } from '../errors.js';
|
|
4
|
+
import { scanLocalFiles } from '../sync/fs.js';
|
|
5
|
+
import { buildPenInfoConfigFields } from '../sync/info.js';
|
|
6
|
+
import { syncRemoteFilesToDisk } from '../sync/materialize.js';
|
|
7
|
+
import { assertValidVersionLabel } from '../utils/cli-options.js';
|
|
8
|
+
import { fmt, formatDate, shortId } from '../utils/format.js';
|
|
9
|
+
import { printJsonResponse } from '../utils/json.js';
|
|
10
|
+
import { defaultOutput } from '../utils/output.js';
|
|
11
|
+
import { isInteractive, promptConfirm, promptSelect, } from '../utils/prompts/index.js';
|
|
12
|
+
import { getGlobalProfileOption, resolveCommandAuth } from '../workflows/auth-context.js';
|
|
13
|
+
import { fetchLinkedPenOrHandleMissing } from '../workflows/missing-pen.js';
|
|
14
|
+
export async function runRollbackCommand(options = {}) {
|
|
15
|
+
const output = options.output ?? defaultOutput;
|
|
16
|
+
const jsonMode = Boolean(options.json);
|
|
17
|
+
const interactive = !jsonMode && (options.interactive ?? isInteractive());
|
|
18
|
+
const selectImpl = options.prompts?.select ?? promptSelect;
|
|
19
|
+
const confirmImpl = options.prompts?.confirm ?? promptConfirm;
|
|
20
|
+
assertValidVersionLabel(options.label);
|
|
21
|
+
const project = await requireProject(options.cwd ?? process.cwd());
|
|
22
|
+
const auth = await resolveCommandAuth({
|
|
23
|
+
explicitProfile: options.explicitProfile,
|
|
24
|
+
project,
|
|
25
|
+
interactive,
|
|
26
|
+
persistProfileToProject: !jsonMode,
|
|
27
|
+
output,
|
|
28
|
+
env: options.env,
|
|
29
|
+
homeDir: options.homeDir,
|
|
30
|
+
selectProfile: options.prompts?.selectProfile,
|
|
31
|
+
});
|
|
32
|
+
const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
|
|
33
|
+
const penLookup = await fetchLinkedPenOrHandleMissing({
|
|
34
|
+
client,
|
|
35
|
+
project,
|
|
36
|
+
auth,
|
|
37
|
+
commandName: 'rollback',
|
|
38
|
+
interactive,
|
|
39
|
+
json: jsonMode,
|
|
40
|
+
output,
|
|
41
|
+
prompts: options.prompts,
|
|
42
|
+
});
|
|
43
|
+
if (!penLookup.found) {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
let targetVersionId = options.versionIdArg?.trim();
|
|
47
|
+
if (!targetVersionId) {
|
|
48
|
+
if (!interactive) {
|
|
49
|
+
throw new CliError(400, 'Missing <version-id>. Run `cdpn versions` to list available version IDs.');
|
|
50
|
+
}
|
|
51
|
+
const page = await client.listVersions(project.config.pen_id, {
|
|
52
|
+
per_page: 10,
|
|
53
|
+
sort: 'created',
|
|
54
|
+
direction: 'desc',
|
|
55
|
+
});
|
|
56
|
+
if (page.items.length === 0) {
|
|
57
|
+
throw new CliError(404, 'No saved versions available to restore.');
|
|
58
|
+
}
|
|
59
|
+
targetVersionId = await selectImpl('Select a version to restore to head:', page.items.map((v) => ({
|
|
60
|
+
value: v.id,
|
|
61
|
+
label: `${shortId(v.id)}${v.label ? ` — ${v.label}` : ''}`,
|
|
62
|
+
description: `${v.build?.status ?? 'Unknown'} · ${formatDate(v.created_at)}${v.deployed ? ' · deployed' : ''}`,
|
|
63
|
+
})), 0);
|
|
64
|
+
}
|
|
65
|
+
if (!options.yes) {
|
|
66
|
+
if (!interactive) {
|
|
67
|
+
throw new CliError(400, 'Refusing to rollback in non-interactive mode without --yes.');
|
|
68
|
+
}
|
|
69
|
+
const ok = await confirmImpl(`Restore version ${fmt.cyan(targetVersionId)} as the new head and overwrite local files?`, false);
|
|
70
|
+
if (!ok) {
|
|
71
|
+
output.log('Aborted.');
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (!jsonMode) {
|
|
76
|
+
output.log(`Restoring version ${fmt.cyan(shortId(targetVersionId))}…`);
|
|
77
|
+
}
|
|
78
|
+
const updatedPen = await client.restoreVersion(project.config.pen_id, targetVersionId, options.label);
|
|
79
|
+
const newHeadId = updatedPen.saved_version?.id ?? null;
|
|
80
|
+
const [localFiles, remoteFiles] = await Promise.all([
|
|
81
|
+
scanLocalFiles(project.rootDir),
|
|
82
|
+
client.getPenFiles(updatedPen.id),
|
|
83
|
+
]);
|
|
84
|
+
const materialized = await syncRemoteFilesToDisk({
|
|
85
|
+
client,
|
|
86
|
+
rootDir: project.rootDir,
|
|
87
|
+
remoteFiles,
|
|
88
|
+
existingLocalPaths: localFiles.keys(),
|
|
89
|
+
pruneRemoved: true,
|
|
90
|
+
});
|
|
91
|
+
await writeProjectConfig(project.rootDir, {
|
|
92
|
+
url: project.config.url || updatedPen.urls.editor,
|
|
93
|
+
pen_id: updatedPen.id,
|
|
94
|
+
...(project.config.profile ? { profile: project.config.profile } : {}),
|
|
95
|
+
last_synced_version_id: newHeadId,
|
|
96
|
+
editor: updatedPen.editor,
|
|
97
|
+
...buildPenInfoConfigFields(updatedPen),
|
|
98
|
+
files: buildSyncedFileMap(remoteFiles, materialized.localSha256ByPath),
|
|
99
|
+
});
|
|
100
|
+
if (jsonMode) {
|
|
101
|
+
printJsonResponse(200, `Restored version ${targetVersionId} to head.`, {
|
|
102
|
+
pen: updatedPen,
|
|
103
|
+
profile: auth.profile ?? project.config.profile ?? null,
|
|
104
|
+
restored_version_id: targetVersionId,
|
|
105
|
+
new_version_id: newHeadId,
|
|
106
|
+
written_paths: materialized.writtenPaths,
|
|
107
|
+
deleted_paths: materialized.deletedPaths,
|
|
108
|
+
}, output);
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
output.log(`\n${fmt.green('✓')} Restored version ${fmt.dim(shortId(targetVersionId))} → new head ${fmt.dim(shortId(newHeadId))}`);
|
|
112
|
+
output.log(` Synced ${materialized.writtenPaths.length} file(s)` +
|
|
113
|
+
(materialized.deletedPaths.length > 0
|
|
114
|
+
? `, removed ${materialized.deletedPaths.length} file(s)`
|
|
115
|
+
: ''));
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
pen: updatedPen,
|
|
119
|
+
restoredVersionId: targetVersionId,
|
|
120
|
+
newVersionId: newHeadId,
|
|
121
|
+
writtenPaths: materialized.writtenPaths,
|
|
122
|
+
deletedPaths: materialized.deletedPaths,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
export function registerRollbackCommand(program) {
|
|
126
|
+
program
|
|
127
|
+
.command('rollback [version-id]')
|
|
128
|
+
.description('Restore an older saved version to head and sync files locally')
|
|
129
|
+
.option('-m, --label <label>', 'Optional label for the restored version (max 80 chars)')
|
|
130
|
+
.option('-y, --yes', 'Skip confirmation prompt')
|
|
131
|
+
.option('--json', 'Output rollback result as JSON')
|
|
132
|
+
.action(async (versionIdArg, options, command) => {
|
|
133
|
+
await runRollbackCommand({
|
|
134
|
+
versionIdArg,
|
|
135
|
+
label: options.label,
|
|
136
|
+
yes: options.yes,
|
|
137
|
+
json: options.json,
|
|
138
|
+
explicitProfile: getGlobalProfileOption(command),
|
|
139
|
+
});
|
|
140
|
+
});
|
|
141
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { DEFAULT_SERVE_PORT, startDevServer, } from '../site/server.js';
|
|
3
|
+
import { openBrowser } from '../utils/browser.js';
|
|
4
|
+
import { fmt } from '../utils/format.js';
|
|
5
|
+
import { defaultOutput } from '../utils/output.js';
|
|
6
|
+
function formatMissingCodepenTip(cdpnState) {
|
|
7
|
+
if (cdpnState === 'linked-v2') {
|
|
8
|
+
return 'No .codepen/ folder found — serving as plain static files. Run `cdpn pull` to restore it from CodePen, or `cdpn push` to sync.';
|
|
9
|
+
}
|
|
10
|
+
if (cdpnState === 'unlinked') {
|
|
11
|
+
return 'No .codepen/ folder found — serving as plain static files. Run `cdpn push` to push to CodePen and generate .codepen/pen.config.json.';
|
|
12
|
+
}
|
|
13
|
+
if (cdpnState === 'linked-classic') {
|
|
14
|
+
return 'No .codepen/ folder found (Classic Pen) — serving as plain static files.';
|
|
15
|
+
}
|
|
16
|
+
return 'No .codepen/ folder found — serving as plain static files.';
|
|
17
|
+
}
|
|
18
|
+
export async function runServeCommand(options = {}) {
|
|
19
|
+
const output = options.output ?? defaultOutput;
|
|
20
|
+
const cwd = path.resolve(options.cwd ?? process.cwd());
|
|
21
|
+
const env = options.env ?? process.env;
|
|
22
|
+
const rawPort = options.port ?? env.PORT ?? String(DEFAULT_SERVE_PORT);
|
|
23
|
+
const openBrowserImpl = options.openBrowserImpl ?? openBrowser;
|
|
24
|
+
const running = await startDevServer({
|
|
25
|
+
targetDir: options.dirArg ?? '.',
|
|
26
|
+
port: rawPort,
|
|
27
|
+
allowEphemeralPort: options.allowEphemeralPort,
|
|
28
|
+
explicitShell: options.shell,
|
|
29
|
+
site: {
|
|
30
|
+
title: options.title,
|
|
31
|
+
subtitle: options.subtitle,
|
|
32
|
+
footer: options.footer,
|
|
33
|
+
},
|
|
34
|
+
homeDir: options.homeDir,
|
|
35
|
+
cwd,
|
|
36
|
+
onManifestUpdate(updatedCount) {
|
|
37
|
+
output.log(`${fmt.cyan('↻')} Updated demo index ${fmt.dim(`(${updatedCount} ${updatedCount === 1 ? 'demo' : 'demos'})`)}`);
|
|
38
|
+
},
|
|
39
|
+
onWatchError(error) {
|
|
40
|
+
output.error(`${fmt.yellow('!')} Watch warning: ${error.message}`);
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
const displayDir = path.relative(cwd, running.inspection.rootDir) || '.';
|
|
44
|
+
output.log('');
|
|
45
|
+
if (running.mode === 'pen') {
|
|
46
|
+
const titleSuffix = running.inspection.penTitle
|
|
47
|
+
? ` ${fmt.dim(`(${running.inspection.penTitle})`)}`
|
|
48
|
+
: '';
|
|
49
|
+
output.log(`${fmt.boldGreen('✓')} ${fmt.bold('Serving Pen')} ${fmt.magenta(displayDir)}${titleSuffix}`);
|
|
50
|
+
if (!running.inspection.hasCodepenDir) {
|
|
51
|
+
output.log(` ${fmt.boldYellow('!')} ${fmt.dim(formatMissingCodepenTip(running.inspection.cdpnState))}`);
|
|
52
|
+
}
|
|
53
|
+
else if (running.inspection.penBlocks) {
|
|
54
|
+
const blocks = running.inspection.penBlocks;
|
|
55
|
+
const enabled = [];
|
|
56
|
+
if (blocks.hasClassic)
|
|
57
|
+
enabled.push('classic');
|
|
58
|
+
if (blocks.hasPackages)
|
|
59
|
+
enabled.push('packages');
|
|
60
|
+
if (enabled.length > 0) {
|
|
61
|
+
output.log(` ${fmt.dim('Blocks:')} ${fmt.cyan(enabled.join(', '))}`);
|
|
62
|
+
}
|
|
63
|
+
if (blocks.unsupportedBlocks.length > 0) {
|
|
64
|
+
output.log(` ${fmt.boldYellow('!')} ${fmt.yellow(`Unsupported block(s): ${blocks.unsupportedBlocks.join(', ')} (browser will display an info page).`)}`);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (options.shell) {
|
|
68
|
+
output.log(` ${fmt.dim('Note: --shell is only used when serving a directory of Pens.')}`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
const countLabel = `${running.demoCount} ${running.demoCount === 1 ? 'demo' : 'demos'}`;
|
|
73
|
+
output.log(`${fmt.boldGreen('✓')} ${fmt.bold('Serving demo directory')} ${fmt.magenta(displayDir)} ${fmt.dim(`(${countLabel})`)}`);
|
|
74
|
+
if (running.inspection.hasIndexHtml) {
|
|
75
|
+
output.log(` ${fmt.dim('Index:')} custom ${fmt.cyan('index.html')} ${fmt.dim('(preserving existing index.html)')}`);
|
|
76
|
+
}
|
|
77
|
+
else if (running.shell && running.shell.source !== 'builtin') {
|
|
78
|
+
const sourceLabel = running.shell.source === 'flag' ? '--shell' : '~/.cdpn';
|
|
79
|
+
output.log(` ${fmt.dim('Shell:')} ${fmt.magenta(running.shell.dir)} ${fmt.dim(`(${sourceLabel})`)}`);
|
|
80
|
+
}
|
|
81
|
+
output.log(` ${fmt.dim('Watch:')} watching subdirectories for changes ${fmt.dim('(in-memory demos.json)')}`);
|
|
82
|
+
if (running.demoCount === 0) {
|
|
83
|
+
output.log(` ${fmt.boldYellow('!')} ${fmt.dim('No .cdpn.json demos found. Run `cdpn init` inside a demo folder to mark it as a CodePen demo.')}`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
output.log(` ${fmt.dim('URL:')} ${fmt.boldCyan(running.url)}`);
|
|
87
|
+
output.log(` ${fmt.dim('Press Ctrl+C to stop.')}\n`);
|
|
88
|
+
if (options.open) {
|
|
89
|
+
const launched = await openBrowserImpl(running.url, { allowLocalhostHttp: true });
|
|
90
|
+
if (!launched) {
|
|
91
|
+
output.log(fmt.yellow(`Could not launch browser automatically. Open ${running.url} manually.`));
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return running;
|
|
95
|
+
}
|
|
96
|
+
export function registerServeCommand(program) {
|
|
97
|
+
program
|
|
98
|
+
.command('serve [dir]')
|
|
99
|
+
.description('Serve a local CodePen Pen or a directory of Pens on 127.0.0.1')
|
|
100
|
+
.option('-p, --port <port>', `Port to listen on (default: PORT env var or ${DEFAULT_SERVE_PORT})`)
|
|
101
|
+
.option('-o, --open', 'Open the local server URL in your browser')
|
|
102
|
+
.option('--shell <dir>', 'Custom shell directory for the demo index page (overrides ~/.cdpn)')
|
|
103
|
+
.option('--title <text>', 'Custom title for the demo index page (defaults to folder name)')
|
|
104
|
+
.option('--subtitle <text>', 'Custom subtitle for the demo index page')
|
|
105
|
+
.option('--footer <text>', 'Custom footer for the demo index page')
|
|
106
|
+
.action(async (dirArg, options) => {
|
|
107
|
+
const running = await runServeCommand({
|
|
108
|
+
dirArg,
|
|
109
|
+
...options,
|
|
110
|
+
});
|
|
111
|
+
const shutdown = () => {
|
|
112
|
+
void running.close().finally(() => {
|
|
113
|
+
process.exit(0);
|
|
114
|
+
});
|
|
115
|
+
};
|
|
116
|
+
process.on('SIGINT', shutdown);
|
|
117
|
+
process.on('SIGTERM', shutdown);
|
|
118
|
+
});
|
|
119
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { CodePenClient } from '../api/client.js';
|
|
2
|
+
import { requireProject } from '../config/project.js';
|
|
3
|
+
import { CliError } from '../errors.js';
|
|
4
|
+
import { parseBooleanOption } from '../utils/cli-options.js';
|
|
5
|
+
import { fmt } from '../utils/format.js';
|
|
6
|
+
import { printJsonResponse } from '../utils/json.js';
|
|
7
|
+
import { defaultOutput } from '../utils/output.js';
|
|
8
|
+
import { isInteractive } from '../utils/prompts/index.js';
|
|
9
|
+
import { getGlobalProfileOption, resolveCommandAuth } from '../workflows/auth-context.js';
|
|
10
|
+
import { fetchLinkedPenOrHandleMissing, handleMissingRemotePen, isRemotePenNotFoundError, } from '../workflows/missing-pen.js';
|
|
11
|
+
function renderPenSettings(settings, output) {
|
|
12
|
+
const boolText = (b) => (b ? fmt.green('true') : fmt.dim('false'));
|
|
13
|
+
output.log(`auto_deploy: ${boolText(settings.auto_deploy)}`);
|
|
14
|
+
output.log(`auto_run: ${boolText(settings.auto_run)}`);
|
|
15
|
+
output.log(`auto_save: ${boolText(settings.auto_save)}`);
|
|
16
|
+
output.log(`indent_with: ${fmt.cyan(settings.indent_with)}`);
|
|
17
|
+
output.log(`tab_size: ${fmt.cyan(String(settings.tab_size))}`);
|
|
18
|
+
}
|
|
19
|
+
export async function runSettingsCommand(options = {}) {
|
|
20
|
+
const output = options.output ?? defaultOutput;
|
|
21
|
+
const interactive = !options.json && (options.interactive ?? isInteractive());
|
|
22
|
+
const project = await requireProject(options.cwd ?? process.cwd());
|
|
23
|
+
const auth = await resolveCommandAuth({
|
|
24
|
+
explicitProfile: options.explicitProfile,
|
|
25
|
+
project,
|
|
26
|
+
interactive,
|
|
27
|
+
persistProfileToProject: !options.json,
|
|
28
|
+
output,
|
|
29
|
+
env: options.env,
|
|
30
|
+
homeDir: options.homeDir,
|
|
31
|
+
selectProfile: options.selectProfile,
|
|
32
|
+
});
|
|
33
|
+
const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
|
|
34
|
+
const patch = {};
|
|
35
|
+
if (options.autoDeploy !== undefined) {
|
|
36
|
+
patch.auto_deploy = parseBooleanOption(options.autoDeploy, '--auto-deploy');
|
|
37
|
+
}
|
|
38
|
+
if (options.autoRun !== undefined) {
|
|
39
|
+
patch.auto_run = parseBooleanOption(options.autoRun, '--auto-run');
|
|
40
|
+
}
|
|
41
|
+
if (options.autoSave !== undefined) {
|
|
42
|
+
patch.auto_save = parseBooleanOption(options.autoSave, '--auto-save');
|
|
43
|
+
}
|
|
44
|
+
if (options.indentWith !== undefined) {
|
|
45
|
+
const lower = options.indentWith.trim().toLowerCase();
|
|
46
|
+
if (lower !== 'tabs' && lower !== 'spaces') {
|
|
47
|
+
throw new CliError(400, 'Invalid --indent-with value. Use "tabs" or "spaces".');
|
|
48
|
+
}
|
|
49
|
+
patch.indent_with = lower;
|
|
50
|
+
}
|
|
51
|
+
if (options.tabSize !== undefined) {
|
|
52
|
+
const parsed = Number.parseInt(options.tabSize, 10);
|
|
53
|
+
if (Number.isNaN(parsed) || parsed < 1 || parsed > 6) {
|
|
54
|
+
throw new CliError(400, '--tab-size must be an integer between 1 and 6.');
|
|
55
|
+
}
|
|
56
|
+
patch.tab_size = parsed;
|
|
57
|
+
}
|
|
58
|
+
const hasUpdates = Object.keys(patch).length > 0;
|
|
59
|
+
let settings;
|
|
60
|
+
if (hasUpdates) {
|
|
61
|
+
try {
|
|
62
|
+
settings = await client.updateSettings(project.config.pen_id, patch);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
if (!isRemotePenNotFoundError(error)) {
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
const resolution = await handleMissingRemotePen({
|
|
69
|
+
client,
|
|
70
|
+
project,
|
|
71
|
+
auth,
|
|
72
|
+
commandName: 'settings',
|
|
73
|
+
interactive,
|
|
74
|
+
json: options.json,
|
|
75
|
+
output,
|
|
76
|
+
prompts: options.prompts,
|
|
77
|
+
});
|
|
78
|
+
if (resolution.action !== 'recovered') {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
settings = await client.updateSettings(project.config.pen_id, patch);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
const penLookup = await fetchLinkedPenOrHandleMissing({
|
|
86
|
+
client,
|
|
87
|
+
project,
|
|
88
|
+
auth,
|
|
89
|
+
commandName: 'settings',
|
|
90
|
+
interactive,
|
|
91
|
+
json: options.json,
|
|
92
|
+
output,
|
|
93
|
+
prompts: options.prompts,
|
|
94
|
+
});
|
|
95
|
+
if (!penLookup.found) {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
settings = penLookup.pen.settings;
|
|
99
|
+
}
|
|
100
|
+
if (options.json) {
|
|
101
|
+
printJsonResponse(200, hasUpdates ? 'Updated Pen settings.' : 'Fetched Pen settings.', settings, output);
|
|
102
|
+
return { settings, updated: hasUpdates, auth, project };
|
|
103
|
+
}
|
|
104
|
+
if (hasUpdates) {
|
|
105
|
+
output.log(`${fmt.green('✓')} Updated Pen settings.\n`);
|
|
106
|
+
}
|
|
107
|
+
renderPenSettings(settings, output);
|
|
108
|
+
return { settings, updated: hasUpdates, auth, project };
|
|
109
|
+
}
|
|
110
|
+
export function registerSettingsCommand(program) {
|
|
111
|
+
program
|
|
112
|
+
.command('settings')
|
|
113
|
+
.description('View or update Pen editor & deploy settings')
|
|
114
|
+
.option('--auto-deploy <bool>', 'Auto-deploy on save (true/false)')
|
|
115
|
+
.option('--auto-run <bool>', 'Auto-run preview (true/false)')
|
|
116
|
+
.option('--auto-save <bool>', 'Auto-save in editor (true/false)')
|
|
117
|
+
.option('--indent-with <mode>', 'Indentation style: tabs or spaces')
|
|
118
|
+
.option('--tab-size <n>', 'Tab size (integer between 1 and 6)')
|
|
119
|
+
.option('--json', 'Output settings as JSON')
|
|
120
|
+
.action(async (options, command) => {
|
|
121
|
+
await runSettingsCommand({
|
|
122
|
+
...options,
|
|
123
|
+
explicitProfile: getGlobalProfileOption(command),
|
|
124
|
+
});
|
|
125
|
+
});
|
|
126
|
+
}
|