codepen-commander 0.0.0-stage → 1.0.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 +371 -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
package/commands/fork.js
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { CodePenClient } from '../api/client.js';
|
|
4
|
+
import { CodePenApiError } from '../api/errors.js';
|
|
5
|
+
import { buildSyncedFileMap, hasProjectConfigInDir, normalizePenReference, slugifyTitle, suggestFolderName, writeProjectConfig, } from '../config/project.js';
|
|
6
|
+
import { isDirectoryNonEmpty } from '../sync/fs.js';
|
|
7
|
+
import { syncRemoteFilesToDisk } from '../sync/materialize.js';
|
|
8
|
+
import { fmt, printBuildSummary, shortId } from '../utils/format.js';
|
|
9
|
+
import { CliError, printJsonResponse } from '../utils/json.js';
|
|
10
|
+
import { isInteractive, promptConfirm, promptSecret, promptSelect, promptText, } from '../utils/prompts.js';
|
|
11
|
+
import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
|
|
12
|
+
import { normalizeAccess } from './create-pen.js';
|
|
13
|
+
import { assertEmptyTargetDirectory } from './scaffold.js';
|
|
14
|
+
import { findUnmatchedStoredOwner, handlePenNotFoundOnFetch, handleUnownedPenAccess, } from './unowned-pen.js';
|
|
15
|
+
const FORK_NON_EMPTY_HINT = 'Choose a different target folder (e.g. `cdpn fork <url> my-fork`) or remove existing files first.';
|
|
16
|
+
async function isPathOccupied(candidatePath) {
|
|
17
|
+
try {
|
|
18
|
+
const stat = await fs.lstat(candidatePath);
|
|
19
|
+
if (!stat.isDirectory())
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
if (error.code === 'ENOENT') {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
28
|
+
return (await hasProjectConfigInDir(candidatePath)) || (await isDirectoryNonEmpty(candidatePath));
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Generates an available default folder name for a forked Pen, automatically appending
|
|
32
|
+
* `-fork` (or `-fork-2`, etc.) if the original Pen's folder name is already occupied.
|
|
33
|
+
*/
|
|
34
|
+
async function suggestAvailableForkFolder(cwd, baseName) {
|
|
35
|
+
if (!(await isPathOccupied(path.resolve(cwd, baseName)))) {
|
|
36
|
+
return baseName;
|
|
37
|
+
}
|
|
38
|
+
const withFork = `${baseName}-fork`;
|
|
39
|
+
if (!(await isPathOccupied(path.resolve(cwd, withFork)))) {
|
|
40
|
+
return withFork;
|
|
41
|
+
}
|
|
42
|
+
for (let i = 2; i <= 100; i++) {
|
|
43
|
+
const candidate = `${baseName}-fork-${i}`;
|
|
44
|
+
if (!(await isPathOccupied(path.resolve(cwd, candidate)))) {
|
|
45
|
+
return candidate;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return `${baseName}-fork-${Date.now()}`;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Forks an existing CodePen Pen via `POST /v2/pens/{id}/fork` and downloads the new fork
|
|
52
|
+
* into a local folder linked with `.cdpn.json`.
|
|
53
|
+
*/
|
|
54
|
+
export async function forkPenCommand(options) {
|
|
55
|
+
const cwd = path.resolve(options.cwd ?? process.cwd());
|
|
56
|
+
const jsonMode = Boolean(options.json);
|
|
57
|
+
const interactive = (options.interactive ?? isInteractive()) && !jsonMode;
|
|
58
|
+
const textImpl = options.prompts?.text ?? promptText;
|
|
59
|
+
const confirmImpl = options.prompts?.confirm ?? promptConfirm;
|
|
60
|
+
const selectImpl = options.prompts?.select ?? promptSelect;
|
|
61
|
+
const secretImpl = options.prompts?.secret ?? promptSecret;
|
|
62
|
+
const { apiIdentifier, originalUrl } = normalizePenReference(options.urlArg);
|
|
63
|
+
if (options.tags && options.tags.length > 5) {
|
|
64
|
+
throw new CliError(400, 'CodePen allows at most 5 tags per Pen.');
|
|
65
|
+
}
|
|
66
|
+
const explicitAccess = normalizeAccess(options.access);
|
|
67
|
+
if (explicitAccess === 'Protected' && options.password !== undefined && options.password.length < 8) {
|
|
68
|
+
throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
|
|
69
|
+
}
|
|
70
|
+
if (explicitAccess === 'Protected' && !options.password && !interactive) {
|
|
71
|
+
throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
|
|
72
|
+
}
|
|
73
|
+
// If target folder was passed explicitly, validate before hitting the network
|
|
74
|
+
let targetDir = null;
|
|
75
|
+
let folderDisplay = options.folderArg?.trim() || '';
|
|
76
|
+
if (folderDisplay) {
|
|
77
|
+
targetDir = path.resolve(cwd, folderDisplay);
|
|
78
|
+
if (!options.allowOverwrite) {
|
|
79
|
+
await assertEmptyTargetDirectory(targetDir, folderDisplay, {
|
|
80
|
+
commandName: 'fork',
|
|
81
|
+
nonEmptyHint: FORK_NON_EMPTY_HINT,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const clonePastedForkUrl = async (pastedUrl) => {
|
|
86
|
+
const { clonePenCommand } = await import('./clone.js');
|
|
87
|
+
const cloned = await clonePenCommand({
|
|
88
|
+
urlArg: pastedUrl,
|
|
89
|
+
folderArg: options.folderArg,
|
|
90
|
+
cwd,
|
|
91
|
+
baseUrl: options.baseUrl,
|
|
92
|
+
interactive,
|
|
93
|
+
env: options.env,
|
|
94
|
+
homeDir: options.homeDir,
|
|
95
|
+
openBrowser: options.openBrowser,
|
|
96
|
+
allowBrowserFallback: false,
|
|
97
|
+
prompts: {
|
|
98
|
+
text: textImpl,
|
|
99
|
+
confirm: confirmImpl,
|
|
100
|
+
select: selectImpl,
|
|
101
|
+
secret: secretImpl,
|
|
102
|
+
},
|
|
103
|
+
});
|
|
104
|
+
if (!cloned || !cloned.project) {
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
return {
|
|
108
|
+
sourcePen: null,
|
|
109
|
+
pen: cloned.pen,
|
|
110
|
+
versionId: cloned.pen.saved_version?.id ?? null,
|
|
111
|
+
build: null,
|
|
112
|
+
writtenPaths: cloned.writtenPaths,
|
|
113
|
+
auth: cloned.auth,
|
|
114
|
+
project: cloned.project,
|
|
115
|
+
forkedInBrowser: true,
|
|
116
|
+
};
|
|
117
|
+
};
|
|
118
|
+
if (!options.resolvedAuth && !options.sourcePen) {
|
|
119
|
+
const unmatched = await findUnmatchedStoredOwner({
|
|
120
|
+
originalUrl,
|
|
121
|
+
explicitProfile: options.explicitProfile,
|
|
122
|
+
env: options.env,
|
|
123
|
+
homeDir: options.homeDir,
|
|
124
|
+
});
|
|
125
|
+
if (unmatched && originalUrl) {
|
|
126
|
+
const pastedUrl = await handleUnownedPenAccess({
|
|
127
|
+
action: 'fork',
|
|
128
|
+
penUrl: originalUrl,
|
|
129
|
+
urlOwner: unmatched.urlOwner,
|
|
130
|
+
availableProfiles: unmatched.availableProfiles,
|
|
131
|
+
interactive,
|
|
132
|
+
allowBrowserFallback: options.allowBrowserFallback,
|
|
133
|
+
confirmImpl,
|
|
134
|
+
textImpl,
|
|
135
|
+
openBrowserImpl: options.openBrowser,
|
|
136
|
+
});
|
|
137
|
+
if (!pastedUrl) {
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
return clonePastedForkUrl(pastedUrl);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const auth = options.resolvedAuth ??
|
|
144
|
+
(await resolveCommandAuth({
|
|
145
|
+
explicitProfile: options.explicitProfile,
|
|
146
|
+
urlHint: originalUrl ?? options.urlArg,
|
|
147
|
+
promptMessage: 'Which CodePen profile should be used to fork this Pen?',
|
|
148
|
+
interactive,
|
|
149
|
+
env: options.env,
|
|
150
|
+
homeDir: options.homeDir,
|
|
151
|
+
selectProfile: selectImpl,
|
|
152
|
+
}));
|
|
153
|
+
const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
|
|
154
|
+
let sourcePen;
|
|
155
|
+
if (options.sourcePen) {
|
|
156
|
+
sourcePen = options.sourcePen;
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
if (!jsonMode) {
|
|
160
|
+
console.log(`Fetching Pen ${fmt.cyan(apiIdentifier)}…`);
|
|
161
|
+
}
|
|
162
|
+
try {
|
|
163
|
+
sourcePen = await client.getPen(apiIdentifier);
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
if (error instanceof CodePenApiError && error.status === 404) {
|
|
167
|
+
const pastedUrl = await handlePenNotFoundOnFetch({
|
|
168
|
+
action: 'fork',
|
|
169
|
+
apiIdentifier,
|
|
170
|
+
originalUrl,
|
|
171
|
+
auth,
|
|
172
|
+
client,
|
|
173
|
+
interactive,
|
|
174
|
+
allowBrowserFallback: options.allowBrowserFallback,
|
|
175
|
+
confirmImpl,
|
|
176
|
+
textImpl,
|
|
177
|
+
openBrowserImpl: options.openBrowser,
|
|
178
|
+
});
|
|
179
|
+
if (!pastedUrl) {
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
return clonePastedForkUrl(pastedUrl);
|
|
183
|
+
}
|
|
184
|
+
throw error;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
// CodePen API requires a password when forking a Protected Pen (unless access is overridden)
|
|
188
|
+
const effectiveAccess = explicitAccess ?? sourcePen.access;
|
|
189
|
+
let password = options.password;
|
|
190
|
+
if (effectiveAccess === 'Protected' && (!password || password.length < 8)) {
|
|
191
|
+
if (!interactive) {
|
|
192
|
+
throw new CliError(400, 'Forking a Protected Pen requires --password with at least 8 characters (or pass --access Public/Private).');
|
|
193
|
+
}
|
|
194
|
+
for (;;) {
|
|
195
|
+
password = await secretImpl('Password for Protected fork (min 8 characters)');
|
|
196
|
+
if (password.length >= 8)
|
|
197
|
+
break;
|
|
198
|
+
console.log(fmt.yellow('Password must be at least 8 characters.'));
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
const title = options.title?.trim() || undefined;
|
|
202
|
+
// Determine target folder if omitted (asked interactively or generated cleanly) BEFORE calling fork
|
|
203
|
+
if (!targetDir) {
|
|
204
|
+
const baseName = (title ? slugifyTitle(title) : null) ?? suggestFolderName(sourcePen);
|
|
205
|
+
const defaultFolder = await suggestAvailableForkFolder(cwd, baseName);
|
|
206
|
+
if (interactive) {
|
|
207
|
+
const chosen = (await textImpl('Target folder', defaultFolder)).trim();
|
|
208
|
+
folderDisplay = chosen || defaultFolder;
|
|
209
|
+
}
|
|
210
|
+
else {
|
|
211
|
+
folderDisplay = defaultFolder;
|
|
212
|
+
}
|
|
213
|
+
targetDir = path.resolve(cwd, folderDisplay);
|
|
214
|
+
await assertEmptyTargetDirectory(targetDir, folderDisplay, {
|
|
215
|
+
commandName: 'fork',
|
|
216
|
+
nonEmptyHint: FORK_NON_EMPTY_HINT,
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
const shouldWait = options.wait !== false;
|
|
220
|
+
if (!jsonMode) {
|
|
221
|
+
console.log(`\nForking ${fmt.bold(sourcePen.title || 'Untitled')} ${fmt.dim(`(${sourcePen.id})`)}…`);
|
|
222
|
+
}
|
|
223
|
+
const forked = await client.forkPen(sourcePen.id, {
|
|
224
|
+
...(title ? { title } : {}),
|
|
225
|
+
...(options.description ? { description: options.description } : {}),
|
|
226
|
+
...(options.tags && options.tags.length > 0 ? { tags: options.tags } : {}),
|
|
227
|
+
...(explicitAccess ? { access: explicitAccess } : {}),
|
|
228
|
+
...(effectiveAccess === 'Protected' && password ? { password } : {}),
|
|
229
|
+
wait: shouldWait ? 45 : 0,
|
|
230
|
+
});
|
|
231
|
+
let finalBuild = forked.build ?? null;
|
|
232
|
+
if (finalBuild && shouldWait) {
|
|
233
|
+
finalBuild = await client.settleBuild(finalBuild);
|
|
234
|
+
if (!jsonMode) {
|
|
235
|
+
printBuildSummary(finalBuild);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
await fs.mkdir(targetDir, { recursive: true });
|
|
239
|
+
const finalVersionId = finalBuild?.version_id ?? forked.saved_version?.id ?? null;
|
|
240
|
+
const remoteFiles = finalVersionId
|
|
241
|
+
? (await client.getVersion(finalVersionId)).files ?? (await client.getPenFiles(forked.id))
|
|
242
|
+
: await client.getPenFiles(forked.id);
|
|
243
|
+
const materialized = await syncRemoteFilesToDisk({
|
|
244
|
+
client,
|
|
245
|
+
rootDir: targetDir,
|
|
246
|
+
remoteFiles,
|
|
247
|
+
pruneRemoved: false,
|
|
248
|
+
});
|
|
249
|
+
const config = {
|
|
250
|
+
url: forked.urls.editor,
|
|
251
|
+
pen_id: forked.id,
|
|
252
|
+
...(auth.profile ? { profile: auth.profile } : {}),
|
|
253
|
+
last_synced_version_id: finalVersionId,
|
|
254
|
+
editor: forked.editor,
|
|
255
|
+
files: buildSyncedFileMap(remoteFiles, materialized.localSha256ByPath),
|
|
256
|
+
};
|
|
257
|
+
const configPath = await writeProjectConfig(targetDir, config);
|
|
258
|
+
const buildFailed = finalBuild?.status === 'Failed';
|
|
259
|
+
if (buildFailed) {
|
|
260
|
+
process.exitCode = 1;
|
|
261
|
+
}
|
|
262
|
+
if (jsonMode) {
|
|
263
|
+
const code = buildFailed ? 422 : 201;
|
|
264
|
+
const message = buildFailed
|
|
265
|
+
? `Forked ${forked.title || 'Untitled'}, but the initial build failed.`
|
|
266
|
+
: `Forked ${forked.title || 'Untitled'} into ${folderDisplay}.`;
|
|
267
|
+
printJsonResponse(code, message, {
|
|
268
|
+
pen: forked,
|
|
269
|
+
source_pen: sourcePen,
|
|
270
|
+
profile: auth.profile,
|
|
271
|
+
folder: folderDisplay,
|
|
272
|
+
root_dir: targetDir,
|
|
273
|
+
config_path: configPath,
|
|
274
|
+
version_id: finalVersionId,
|
|
275
|
+
build: finalBuild,
|
|
276
|
+
written_paths: materialized.writtenPaths,
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
else {
|
|
280
|
+
if (buildFailed) {
|
|
281
|
+
console.log(`\n${fmt.yellow('!')} Forked ${fmt.bold(forked.title || 'Untitled')} ${fmt.dim(`(${forked.id})`)}, but the initial build failed.`);
|
|
282
|
+
}
|
|
283
|
+
else {
|
|
284
|
+
console.log(`\n${fmt.green('✓')} Forked ${fmt.bold(forked.title || 'Untitled')} ${fmt.dim(`(${forked.id})`)}`);
|
|
285
|
+
}
|
|
286
|
+
console.log(` From: ${fmt.dim(sourcePen.urls.editor)}`);
|
|
287
|
+
if (auth.profile) {
|
|
288
|
+
console.log(` Profile: ${fmt.cyan(auth.profile)}`);
|
|
289
|
+
}
|
|
290
|
+
console.log(` Visibility: ${forked.access}`);
|
|
291
|
+
console.log(` Folder: ${fmt.cyan(folderDisplay)}`);
|
|
292
|
+
console.log(` Files: ${materialized.writtenPaths.length} downloaded`);
|
|
293
|
+
console.log(` Editor: ${fmt.cyan(forked.urls.editor)}`);
|
|
294
|
+
console.log(` Preview: ${fmt.cyan(forked.urls.preview)}`);
|
|
295
|
+
console.log(` Version: ${fmt.dim(shortId(finalVersionId))}`);
|
|
296
|
+
}
|
|
297
|
+
return {
|
|
298
|
+
sourcePen,
|
|
299
|
+
pen: forked,
|
|
300
|
+
versionId: finalVersionId,
|
|
301
|
+
build: finalBuild,
|
|
302
|
+
writtenPaths: materialized.writtenPaths,
|
|
303
|
+
auth,
|
|
304
|
+
project: {
|
|
305
|
+
rootDir: targetDir,
|
|
306
|
+
configPath,
|
|
307
|
+
config,
|
|
308
|
+
},
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
export function registerForkCommand(program) {
|
|
312
|
+
program
|
|
313
|
+
.command('fork <url> [folder]')
|
|
314
|
+
.description('Fork an existing CodePen Pen and download it into a local folder')
|
|
315
|
+
.option('-t, --title <title>', 'Title for the forked Pen (defaults to the original Pen’s title)')
|
|
316
|
+
.option('-d, --description <text>', 'Description for the forked Pen')
|
|
317
|
+
.option('--tags <tags>', 'Comma-separated tags (up to 5)')
|
|
318
|
+
.option('--access <level>', 'Privacy: Public, Private, Protected, or Collaborators')
|
|
319
|
+
.option('--password <password>', 'Password (min 8 chars; required for Protected forks)')
|
|
320
|
+
.option('--no-wait', 'Return as soon as files are saved without waiting for the build')
|
|
321
|
+
.option('--json', 'Output fork result as JSON')
|
|
322
|
+
.action(async (urlArg, folderArg, options, command) => {
|
|
323
|
+
const tags = options.tags
|
|
324
|
+
? options.tags
|
|
325
|
+
.split(',')
|
|
326
|
+
.map((t) => t.trim())
|
|
327
|
+
.filter(Boolean)
|
|
328
|
+
: undefined;
|
|
329
|
+
await forkPenCommand({
|
|
330
|
+
urlArg,
|
|
331
|
+
folderArg,
|
|
332
|
+
explicitProfile: getGlobalProfileOption(command),
|
|
333
|
+
title: options.title,
|
|
334
|
+
description: options.description,
|
|
335
|
+
tags,
|
|
336
|
+
access: options.access,
|
|
337
|
+
password: options.password,
|
|
338
|
+
wait: options.wait,
|
|
339
|
+
json: options.json,
|
|
340
|
+
});
|
|
341
|
+
});
|
|
342
|
+
}
|
package/commands/list.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { CodePenClient } from '../api/client.js';
|
|
2
|
+
import { fmt, formatDate, formatTable } from '../utils/format.js';
|
|
3
|
+
import { CliError, printJsonResponse } from '../utils/json.js';
|
|
4
|
+
import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
|
|
5
|
+
const VALID_SORTS = new Set(['created', 'updated', 'popularity', 'title']);
|
|
6
|
+
const VALID_DIRECTIONS = new Set(['asc', 'desc']);
|
|
7
|
+
export function registerListCommand(program) {
|
|
8
|
+
program
|
|
9
|
+
.command('list')
|
|
10
|
+
.alias('ls')
|
|
11
|
+
.description('List and search your Pens on CodePen')
|
|
12
|
+
.option('-s, --search <term>', 'Filter by title or description')
|
|
13
|
+
.option('--access <levels>', 'Comma-separated access levels: Public,Private,Protected,Collaborators')
|
|
14
|
+
.option('--deployed', 'Show only deployed Pens')
|
|
15
|
+
.option('--not-deployed', 'Show only non-deployed Pens')
|
|
16
|
+
.option('--templates', 'Show only Pens marked as templates')
|
|
17
|
+
.option('--tags <tags>', 'Comma-separated tags (up to 3)')
|
|
18
|
+
.option('--editor <type>', 'Filter by editor: V2 or Classic')
|
|
19
|
+
.option('--sort <field>', 'Sort by: created, updated, popularity, or title', 'updated')
|
|
20
|
+
.option('--direction <dir>', 'Sort direction: asc or desc', 'desc')
|
|
21
|
+
.option('-n, --limit <count>', 'Maximum number of Pens to show', '20')
|
|
22
|
+
.option('--json', 'Output Pens as JSON')
|
|
23
|
+
.action(async (options, command) => {
|
|
24
|
+
if (options.deployed && options.notDeployed) {
|
|
25
|
+
throw new CliError(400, 'Cannot combine --deployed and --not-deployed.');
|
|
26
|
+
}
|
|
27
|
+
const limit = Number.parseInt(options.limit ?? '20', 10);
|
|
28
|
+
if (Number.isNaN(limit) || limit < 1) {
|
|
29
|
+
throw new CliError(400, '--limit must be a positive integer.');
|
|
30
|
+
}
|
|
31
|
+
const sort = (options.sort ?? 'updated').toLowerCase();
|
|
32
|
+
if (!VALID_SORTS.has(sort)) {
|
|
33
|
+
throw new CliError(400, `Invalid --sort value "${options.sort}". Use: created, updated, popularity, or title.`);
|
|
34
|
+
}
|
|
35
|
+
const direction = (options.direction ?? 'desc').toLowerCase();
|
|
36
|
+
if (!VALID_DIRECTIONS.has(direction)) {
|
|
37
|
+
throw new CliError(400, `Invalid --direction value "${options.direction}". Use: asc or desc.`);
|
|
38
|
+
}
|
|
39
|
+
let editor;
|
|
40
|
+
if (options.editor) {
|
|
41
|
+
const lower = options.editor.trim().toLowerCase();
|
|
42
|
+
if (lower === 'v2')
|
|
43
|
+
editor = 'V2';
|
|
44
|
+
else if (lower === 'classic')
|
|
45
|
+
editor = 'Classic';
|
|
46
|
+
else
|
|
47
|
+
throw new CliError(400, `Invalid --editor value "${options.editor}". Use: V2 or Classic.`);
|
|
48
|
+
}
|
|
49
|
+
const deployed = options.deployed ? true : options.notDeployed ? false : undefined;
|
|
50
|
+
const template = options.templates ? true : undefined;
|
|
51
|
+
const auth = await resolveCommandAuth({
|
|
52
|
+
explicitProfile: getGlobalProfileOption(command),
|
|
53
|
+
interactive: options.json ? false : undefined,
|
|
54
|
+
promptMessage: 'Which CodePen profile would you like to list Pens for?',
|
|
55
|
+
});
|
|
56
|
+
const client = new CodePenClient({ apiKey: auth.apiKey });
|
|
57
|
+
const pens = [];
|
|
58
|
+
let pageResult = await client.listPens({
|
|
59
|
+
per_page: Math.min(limit, 100),
|
|
60
|
+
sort: sort,
|
|
61
|
+
direction: direction,
|
|
62
|
+
search_term: options.search,
|
|
63
|
+
access: options.access,
|
|
64
|
+
deployed,
|
|
65
|
+
template,
|
|
66
|
+
tags: options.tags,
|
|
67
|
+
editor,
|
|
68
|
+
});
|
|
69
|
+
pens.push(...pageResult.items);
|
|
70
|
+
while (pens.length < limit && pageResult.links.next) {
|
|
71
|
+
pageResult = await client.listPensPageByUrl(pageResult.links.next);
|
|
72
|
+
pens.push(...pageResult.items);
|
|
73
|
+
}
|
|
74
|
+
const sliced = pens.slice(0, limit);
|
|
75
|
+
if (options.json) {
|
|
76
|
+
const message = sliced.length === 0 ? 'No matching Pens found.' : `Found ${sliced.length} Pen(s).`;
|
|
77
|
+
printJsonResponse(200, message, sliced);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (sliced.length === 0) {
|
|
81
|
+
console.log(fmt.dim('No matching Pens found.'));
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
const rows = sliced.map((pen) => {
|
|
85
|
+
const editorBadge = pen.editor === 'V2' ? fmt.green('V2') : fmt.dim('Classic');
|
|
86
|
+
const deployBadge = pen.deployment ? fmt.cyan('live') : fmt.dim('—');
|
|
87
|
+
const accessLabel = pen.template ? `${pen.access} ${fmt.dim('(template)')}` : pen.access;
|
|
88
|
+
const title = (pen.title || 'Untitled').slice(0, 36);
|
|
89
|
+
return [
|
|
90
|
+
fmt.bold(title),
|
|
91
|
+
editorBadge,
|
|
92
|
+
accessLabel,
|
|
93
|
+
deployBadge,
|
|
94
|
+
fmt.dim(formatDate(pen.updated_at)),
|
|
95
|
+
fmt.cyan(pen.urls.editor),
|
|
96
|
+
];
|
|
97
|
+
});
|
|
98
|
+
console.log(formatTable(['Title', 'Editor', 'Access', 'Live', 'Updated', 'URL'], rows));
|
|
99
|
+
if (pageResult.links.next || pens.length > limit) {
|
|
100
|
+
console.log(fmt.dim(`\nShowing ${sliced.length} Pen(s). Pass --limit <n> to see more.`));
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
}
|
package/commands/meta.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { CodePenClient } from '../api/client.js';
|
|
2
|
+
import { requireProject } from '../config/project.js';
|
|
3
|
+
import { fmt, formatDate, shortId } from '../utils/format.js';
|
|
4
|
+
import { CliError, printJsonResponse } from '../utils/json.js';
|
|
5
|
+
import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
|
|
6
|
+
const VALID_ACCESS = new Set(['public', 'private', 'protected', 'collaborators']);
|
|
7
|
+
function parseBooleanOption(raw, flagName) {
|
|
8
|
+
const lower = raw.trim().toLowerCase();
|
|
9
|
+
if (lower === 'true' || lower === '1' || lower === 'yes' || lower === 'on')
|
|
10
|
+
return true;
|
|
11
|
+
if (lower === 'false' || lower === '0' || lower === 'no' || lower === 'off')
|
|
12
|
+
return false;
|
|
13
|
+
throw new CliError(400, `Invalid boolean value "${raw}" for ${flagName}. Use true or false.`);
|
|
14
|
+
}
|
|
15
|
+
function renderPenInfo(pen, profile) {
|
|
16
|
+
console.log(`${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)}`);
|
|
17
|
+
if (profile) {
|
|
18
|
+
console.log(`Profile: ${fmt.cyan(profile)}`);
|
|
19
|
+
}
|
|
20
|
+
if (pen.description) {
|
|
21
|
+
console.log(`Description: ${pen.description}`);
|
|
22
|
+
}
|
|
23
|
+
console.log(`Editor: ${pen.editor}`);
|
|
24
|
+
console.log(`Access: ${pen.access}${pen.template ? fmt.dim(' · Template') : ''}`);
|
|
25
|
+
console.log(`Tags: ${pen.tags.length > 0 ? pen.tags.join(', ') : fmt.dim('none')}`);
|
|
26
|
+
console.log(`Stats: ${pen.views_count} views · ${pen.loves_count} loves`);
|
|
27
|
+
console.log(`Editor URL: ${fmt.cyan(pen.urls.editor)}`);
|
|
28
|
+
console.log(`Preview URL: ${fmt.cyan(pen.urls.preview)}`);
|
|
29
|
+
if (pen.deployment) {
|
|
30
|
+
console.log(`Deployed: ${fmt.cyan(pen.deployment.url)} ${fmt.dim(`(v ${shortId(pen.deployment.version_id)})`)}`);
|
|
31
|
+
if (pen.deployment.custom_domains.length > 0) {
|
|
32
|
+
console.log(`Domains: ${pen.deployment.custom_domains.join(', ')}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
console.log(`Deployed: ${fmt.dim('not deployed')}`);
|
|
37
|
+
}
|
|
38
|
+
console.log(`Created: ${fmt.dim(formatDate(pen.created_at))}`);
|
|
39
|
+
console.log(`Updated: ${fmt.dim(formatDate(pen.updated_at))}`);
|
|
40
|
+
}
|
|
41
|
+
function renderPenSettings(settings) {
|
|
42
|
+
const boolText = (b) => (b ? fmt.green('true') : fmt.dim('false'));
|
|
43
|
+
console.log(`auto_deploy: ${boolText(settings.auto_deploy)}`);
|
|
44
|
+
console.log(`auto_run: ${boolText(settings.auto_run)}`);
|
|
45
|
+
console.log(`auto_save: ${boolText(settings.auto_save)}`);
|
|
46
|
+
console.log(`indent_with: ${fmt.cyan(settings.indent_with)}`);
|
|
47
|
+
console.log(`tab_size: ${fmt.cyan(String(settings.tab_size))}`);
|
|
48
|
+
}
|
|
49
|
+
export function registerMetaCommands(program) {
|
|
50
|
+
program
|
|
51
|
+
.command('info')
|
|
52
|
+
.description('Show or update Pen metadata (title, description, tags, access, template)')
|
|
53
|
+
.option('-t, --title <title>', 'Update Pen title')
|
|
54
|
+
.option('-d, --description <text>', 'Update Pen description')
|
|
55
|
+
.option('--tags <tags>', 'Replace tags with comma-separated list (pass "" to clear)')
|
|
56
|
+
.option('--access <level>', 'Update access: Public, Private, Protected, or Collaborators')
|
|
57
|
+
.option('--password <password>', 'Set/replace password (min 8 chars; for Protected Pens)')
|
|
58
|
+
.option('--template <bool>', 'Set template flag (true/false)')
|
|
59
|
+
.option('--json', 'Output Pen metadata as JSON')
|
|
60
|
+
.action(async (options, command) => {
|
|
61
|
+
const project = await requireProject();
|
|
62
|
+
const auth = await resolveCommandAuth({
|
|
63
|
+
explicitProfile: getGlobalProfileOption(command),
|
|
64
|
+
project,
|
|
65
|
+
interactive: options.json ? false : undefined,
|
|
66
|
+
persistProfileToProject: !options.json,
|
|
67
|
+
});
|
|
68
|
+
const client = new CodePenClient({ apiKey: auth.apiKey });
|
|
69
|
+
const patch = {};
|
|
70
|
+
if (options.title !== undefined)
|
|
71
|
+
patch.title = options.title;
|
|
72
|
+
if (options.description !== undefined)
|
|
73
|
+
patch.description = options.description;
|
|
74
|
+
if (options.tags !== undefined) {
|
|
75
|
+
patch.tags = options.tags
|
|
76
|
+
.split(',')
|
|
77
|
+
.map((t) => t.trim())
|
|
78
|
+
.filter(Boolean);
|
|
79
|
+
}
|
|
80
|
+
if (options.access !== undefined) {
|
|
81
|
+
const lower = options.access.trim().toLowerCase();
|
|
82
|
+
if (!VALID_ACCESS.has(lower)) {
|
|
83
|
+
throw new CliError(400, `Invalid --access "${options.access}". Use: Public, Private, Protected, or Collaborators.`);
|
|
84
|
+
}
|
|
85
|
+
patch.access = (lower[0].toUpperCase() + lower.slice(1));
|
|
86
|
+
}
|
|
87
|
+
if (options.password !== undefined) {
|
|
88
|
+
if (options.password.length < 8) {
|
|
89
|
+
throw new CliError(400, 'Password must be at least 8 characters.');
|
|
90
|
+
}
|
|
91
|
+
patch.password = options.password;
|
|
92
|
+
}
|
|
93
|
+
if (options.template !== undefined) {
|
|
94
|
+
patch.template = parseBooleanOption(options.template, '--template');
|
|
95
|
+
}
|
|
96
|
+
const hasUpdates = Object.keys(patch).length > 0;
|
|
97
|
+
const pen = hasUpdates
|
|
98
|
+
? await client.updatePen(project.config.pen_id, patch)
|
|
99
|
+
: await client.getPen(project.config.pen_id);
|
|
100
|
+
if (options.json) {
|
|
101
|
+
printJsonResponse(200, hasUpdates ? 'Updated Pen metadata.' : 'Fetched Pen metadata.', pen);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (hasUpdates) {
|
|
105
|
+
console.log(`${fmt.green('✓')} Updated Pen metadata.\n`);
|
|
106
|
+
}
|
|
107
|
+
renderPenInfo(pen, auth.profile);
|
|
108
|
+
});
|
|
109
|
+
program
|
|
110
|
+
.command('settings')
|
|
111
|
+
.description('View or update Pen editor & deploy settings')
|
|
112
|
+
.option('--auto-deploy <bool>', 'Auto-deploy on save (true/false)')
|
|
113
|
+
.option('--auto-run <bool>', 'Auto-run preview (true/false)')
|
|
114
|
+
.option('--auto-save <bool>', 'Auto-save in editor (true/false)')
|
|
115
|
+
.option('--indent-with <mode>', 'Indentation style: tabs or spaces')
|
|
116
|
+
.option('--tab-size <n>', 'Tab size (integer between 1 and 6)')
|
|
117
|
+
.option('--json', 'Output settings as JSON')
|
|
118
|
+
.action(async (options, command) => {
|
|
119
|
+
const project = await requireProject();
|
|
120
|
+
const auth = await resolveCommandAuth({
|
|
121
|
+
explicitProfile: getGlobalProfileOption(command),
|
|
122
|
+
project,
|
|
123
|
+
interactive: options.json ? false : undefined,
|
|
124
|
+
persistProfileToProject: !options.json,
|
|
125
|
+
});
|
|
126
|
+
const client = new CodePenClient({ apiKey: auth.apiKey });
|
|
127
|
+
const patch = {};
|
|
128
|
+
if (options.autoDeploy !== undefined) {
|
|
129
|
+
patch.auto_deploy = parseBooleanOption(options.autoDeploy, '--auto-deploy');
|
|
130
|
+
}
|
|
131
|
+
if (options.autoRun !== undefined) {
|
|
132
|
+
patch.auto_run = parseBooleanOption(options.autoRun, '--auto-run');
|
|
133
|
+
}
|
|
134
|
+
if (options.autoSave !== undefined) {
|
|
135
|
+
patch.auto_save = parseBooleanOption(options.autoSave, '--auto-save');
|
|
136
|
+
}
|
|
137
|
+
if (options.indentWith !== undefined) {
|
|
138
|
+
const lower = options.indentWith.trim().toLowerCase();
|
|
139
|
+
if (lower !== 'tabs' && lower !== 'spaces') {
|
|
140
|
+
throw new CliError(400, 'Invalid --indent-with value. Use "tabs" or "spaces".');
|
|
141
|
+
}
|
|
142
|
+
patch.indent_with = lower;
|
|
143
|
+
}
|
|
144
|
+
if (options.tabSize !== undefined) {
|
|
145
|
+
const parsed = Number.parseInt(options.tabSize, 10);
|
|
146
|
+
if (Number.isNaN(parsed) || parsed < 1 || parsed > 6) {
|
|
147
|
+
throw new CliError(400, '--tab-size must be an integer between 1 and 6.');
|
|
148
|
+
}
|
|
149
|
+
patch.tab_size = parsed;
|
|
150
|
+
}
|
|
151
|
+
const hasUpdates = Object.keys(patch).length > 0;
|
|
152
|
+
const settings = hasUpdates
|
|
153
|
+
? await client.updateSettings(project.config.pen_id, patch)
|
|
154
|
+
: (await client.getPen(project.config.pen_id)).settings;
|
|
155
|
+
if (options.json) {
|
|
156
|
+
printJsonResponse(200, hasUpdates ? 'Updated Pen settings.' : 'Fetched Pen settings.', settings);
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
if (hasUpdates) {
|
|
160
|
+
console.log(`${fmt.green('✓')} Updated Pen settings.\n`);
|
|
161
|
+
}
|
|
162
|
+
renderPenSettings(settings);
|
|
163
|
+
});
|
|
164
|
+
}
|