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
|
@@ -0,0 +1,371 @@
|
|
|
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 { DEFAULT_PROFILE_NAME, findMatchingProfile } from '../config/auth.js';
|
|
6
|
+
import { buildSyncedFileMap, extractCodePenOwnerFromUrl, hasProjectConfigInDir, normalizePenReference, PROJECT_CONFIG_FILENAME, suggestFolderName, writeProjectConfig, } from '../config/project.js';
|
|
7
|
+
import { isDirectoryNonEmpty } from '../sync/fs.js';
|
|
8
|
+
import { syncRemoteFilesToDisk } from '../sync/materialize.js';
|
|
9
|
+
import { fmt, shortId } from '../utils/format.js';
|
|
10
|
+
import { CliError, printJsonResponse } from '../utils/json.js';
|
|
11
|
+
import { isInteractive, promptConfirm, promptSecret, promptSelect, promptText, } from '../utils/prompts.js';
|
|
12
|
+
import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
|
|
13
|
+
import { forkPenCommand } from './fork.js';
|
|
14
|
+
import { findUnmatchedStoredOwner, handlePenNotFoundOnFetch, handleUnownedPenAccess, } from './unowned-pen.js';
|
|
15
|
+
async function resolveCurrentUsername(client, auth, penOwner) {
|
|
16
|
+
// Fast path: named profile already matches the Pen owner
|
|
17
|
+
if (auth.profile &&
|
|
18
|
+
auth.profile !== DEFAULT_PROFILE_NAME &&
|
|
19
|
+
auth.profile.toLowerCase() === penOwner.toLowerCase()) {
|
|
20
|
+
return auth.profile;
|
|
21
|
+
}
|
|
22
|
+
// Inspect one Pen owned by this API key to discover the actual CodePen account username
|
|
23
|
+
// (handles CODEPEN_API_KEY env var, "default" profile, and custom profile aliases)
|
|
24
|
+
try {
|
|
25
|
+
const samplePen = await client.verifyAuth();
|
|
26
|
+
const detected = samplePen?.urls?.editor
|
|
27
|
+
? extractCodePenOwnerFromUrl(samplePen.urls.editor)
|
|
28
|
+
: null;
|
|
29
|
+
if (detected) {
|
|
30
|
+
return detected;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
// Fall back to profile name if the account has no Pens or listing fails
|
|
35
|
+
}
|
|
36
|
+
if (auth.profile && auth.profile !== DEFAULT_PROFILE_NAME) {
|
|
37
|
+
return auth.profile;
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
async function ensureCloneTargetReady(targetDir, folderDisplay, options) {
|
|
42
|
+
try {
|
|
43
|
+
const stat = await fs.lstat(targetDir);
|
|
44
|
+
if (!stat.isDirectory()) {
|
|
45
|
+
throw new CliError(409, `Target path ${targetDir} already exists and is not a directory.`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
if (error.code === 'ENOENT') {
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
throw error;
|
|
53
|
+
}
|
|
54
|
+
const [hasExistingConfig, nonEmpty] = await Promise.all([
|
|
55
|
+
hasProjectConfigInDir(targetDir),
|
|
56
|
+
isDirectoryNonEmpty(targetDir),
|
|
57
|
+
]);
|
|
58
|
+
if ((nonEmpty || hasExistingConfig) && !options.force) {
|
|
59
|
+
if (!options.interactive) {
|
|
60
|
+
throw new CliError(409, `Target directory ${targetDir} is not empty. Pass --force to overwrite.`);
|
|
61
|
+
}
|
|
62
|
+
const ok = await options.confirmImpl(`Directory ${fmt.bold(folderDisplay)} already exists and is not empty. Continue and overwrite matching files?`, false);
|
|
63
|
+
if (!ok) {
|
|
64
|
+
console.log('Aborted.');
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Clones an existing CodePen Pen into a local folder.
|
|
72
|
+
*
|
|
73
|
+
* When the Pen's owner does not match the current authenticated account, offers to fork it
|
|
74
|
+
* instead (interactively). If not forked, downloads files locally without writing `.cdpn.json`
|
|
75
|
+
* so the local folder is not linked to an online Pen owned by another user.
|
|
76
|
+
*
|
|
77
|
+
* Returns `null` if the user cancels interactively.
|
|
78
|
+
*/
|
|
79
|
+
export async function clonePenCommand(options) {
|
|
80
|
+
const cwd = path.resolve(options.cwd ?? process.cwd());
|
|
81
|
+
const jsonMode = Boolean(options.json);
|
|
82
|
+
const interactive = (options.interactive ?? isInteractive()) && !jsonMode;
|
|
83
|
+
const force = Boolean(options.force);
|
|
84
|
+
const textImpl = options.prompts?.text ?? promptText;
|
|
85
|
+
const confirmImpl = options.prompts?.confirm ?? promptConfirm;
|
|
86
|
+
const secretImpl = options.prompts?.secret ?? promptSecret;
|
|
87
|
+
const selectImpl = options.prompts?.select ?? promptSelect;
|
|
88
|
+
const { apiIdentifier, originalUrl } = normalizePenReference(options.urlArg);
|
|
89
|
+
// If target folder was passed explicitly, validate before hitting the network
|
|
90
|
+
let targetFolderDisplay = options.folderArg?.trim() || '';
|
|
91
|
+
let targetDir = null;
|
|
92
|
+
if (targetFolderDisplay) {
|
|
93
|
+
targetDir = path.resolve(cwd, targetFolderDisplay);
|
|
94
|
+
const ready = await ensureCloneTargetReady(targetDir, targetFolderDisplay, {
|
|
95
|
+
force,
|
|
96
|
+
interactive,
|
|
97
|
+
confirmImpl,
|
|
98
|
+
});
|
|
99
|
+
if (!ready) {
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const unmatched = await findUnmatchedStoredOwner({
|
|
104
|
+
originalUrl,
|
|
105
|
+
explicitProfile: options.explicitProfile,
|
|
106
|
+
env: options.env,
|
|
107
|
+
homeDir: options.homeDir,
|
|
108
|
+
});
|
|
109
|
+
if (unmatched && originalUrl) {
|
|
110
|
+
const pastedUrl = await handleUnownedPenAccess({
|
|
111
|
+
action: 'clone',
|
|
112
|
+
penUrl: originalUrl,
|
|
113
|
+
urlOwner: unmatched.urlOwner,
|
|
114
|
+
availableProfiles: unmatched.availableProfiles,
|
|
115
|
+
interactive,
|
|
116
|
+
allowBrowserFallback: options.allowBrowserFallback,
|
|
117
|
+
confirmImpl,
|
|
118
|
+
textImpl,
|
|
119
|
+
openBrowserImpl: options.openBrowser,
|
|
120
|
+
});
|
|
121
|
+
if (!pastedUrl) {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
return clonePenCommand({
|
|
125
|
+
...options,
|
|
126
|
+
urlArg: pastedUrl,
|
|
127
|
+
explicitProfile: undefined,
|
|
128
|
+
allowBrowserFallback: false,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
let auth = await resolveCommandAuth({
|
|
132
|
+
explicitProfile: options.explicitProfile,
|
|
133
|
+
urlHint: originalUrl ?? options.urlArg,
|
|
134
|
+
autoSelectUrlMatch: true,
|
|
135
|
+
promptMessage: 'Which CodePen profile should be used for this Pen?',
|
|
136
|
+
interactive,
|
|
137
|
+
env: options.env,
|
|
138
|
+
homeDir: options.homeDir,
|
|
139
|
+
selectProfile: selectImpl,
|
|
140
|
+
});
|
|
141
|
+
let client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
|
|
142
|
+
if (!jsonMode &&
|
|
143
|
+
!options.explicitProfile &&
|
|
144
|
+
auth.source === 'file' &&
|
|
145
|
+
auth.profile &&
|
|
146
|
+
auth.availableProfiles.length > 1 &&
|
|
147
|
+
findMatchingProfile(auth.availableProfiles, originalUrl ?? options.urlArg) === auth.profile) {
|
|
148
|
+
console.log(fmt.dim(`Using profile "${auth.profile}" (matches Pen owner).`));
|
|
149
|
+
}
|
|
150
|
+
if (!jsonMode) {
|
|
151
|
+
console.log(`Fetching Pen ${fmt.cyan(apiIdentifier)}…`);
|
|
152
|
+
}
|
|
153
|
+
let pen;
|
|
154
|
+
try {
|
|
155
|
+
pen = await client.getPen(apiIdentifier);
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
if (error instanceof CodePenApiError && error.status === 404) {
|
|
159
|
+
const pastedUrl = await handlePenNotFoundOnFetch({
|
|
160
|
+
action: 'clone',
|
|
161
|
+
apiIdentifier,
|
|
162
|
+
originalUrl,
|
|
163
|
+
auth,
|
|
164
|
+
client,
|
|
165
|
+
interactive,
|
|
166
|
+
allowBrowserFallback: options.allowBrowserFallback,
|
|
167
|
+
confirmImpl,
|
|
168
|
+
textImpl,
|
|
169
|
+
openBrowserImpl: options.openBrowser,
|
|
170
|
+
});
|
|
171
|
+
if (!pastedUrl) {
|
|
172
|
+
return null;
|
|
173
|
+
}
|
|
174
|
+
return clonePenCommand({
|
|
175
|
+
...options,
|
|
176
|
+
urlArg: pastedUrl,
|
|
177
|
+
explicitProfile: undefined,
|
|
178
|
+
allowBrowserFallback: false,
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
throw error;
|
|
182
|
+
}
|
|
183
|
+
// Check whether this Pen belongs to a stored profile (handles Pen IDs / preview URLs without an owner in the input)
|
|
184
|
+
const penOwner = extractCodePenOwnerFromUrl(pen.urls.editor) ??
|
|
185
|
+
(originalUrl ? extractCodePenOwnerFromUrl(originalUrl) : null);
|
|
186
|
+
if (penOwner &&
|
|
187
|
+
!options.explicitProfile &&
|
|
188
|
+
auth.source === 'file' &&
|
|
189
|
+
auth.profile?.toLowerCase() !== penOwner.toLowerCase()) {
|
|
190
|
+
const matchedStoredProfile = findMatchingProfile(auth.availableProfiles, pen.urls.editor);
|
|
191
|
+
if (matchedStoredProfile && matchedStoredProfile !== auth.profile) {
|
|
192
|
+
auth = await resolveCommandAuth({
|
|
193
|
+
explicitProfile: matchedStoredProfile,
|
|
194
|
+
interactive,
|
|
195
|
+
env: options.env,
|
|
196
|
+
homeDir: options.homeDir,
|
|
197
|
+
});
|
|
198
|
+
client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
|
|
199
|
+
if (!jsonMode) {
|
|
200
|
+
console.log(fmt.dim(`Using profile "${matchedStoredProfile}" (matches Pen owner).`));
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
const currentUsername = penOwner ? await resolveCurrentUsername(client, auth, penOwner) : null;
|
|
205
|
+
const isOwnedByAnotherUser = Boolean(penOwner && currentUsername && penOwner.toLowerCase() !== currentUsername.toLowerCase());
|
|
206
|
+
if (isOwnedByAnotherUser && penOwner && currentUsername) {
|
|
207
|
+
if (!jsonMode) {
|
|
208
|
+
console.log(fmt.yellow(`\nThis Pen belongs to ${fmt.bold(penOwner)} (your current account is ${fmt.bold(currentUsername)}).`));
|
|
209
|
+
}
|
|
210
|
+
if (interactive) {
|
|
211
|
+
const shouldFork = await confirmImpl(`Fork this Pen under ${currentUsername} instead?`, true);
|
|
212
|
+
if (shouldFork) {
|
|
213
|
+
const forkedResult = await forkPenCommand({
|
|
214
|
+
urlArg: options.urlArg,
|
|
215
|
+
folderArg: options.folderArg,
|
|
216
|
+
cwd,
|
|
217
|
+
resolvedAuth: auth,
|
|
218
|
+
sourcePen: pen,
|
|
219
|
+
allowOverwrite: Boolean(targetDir),
|
|
220
|
+
baseUrl: options.baseUrl,
|
|
221
|
+
interactive,
|
|
222
|
+
env: options.env,
|
|
223
|
+
homeDir: options.homeDir,
|
|
224
|
+
openBrowser: options.openBrowser,
|
|
225
|
+
prompts: {
|
|
226
|
+
text: textImpl,
|
|
227
|
+
confirm: confirmImpl,
|
|
228
|
+
select: selectImpl,
|
|
229
|
+
secret: secretImpl,
|
|
230
|
+
},
|
|
231
|
+
});
|
|
232
|
+
if (!forkedResult) {
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
return {
|
|
236
|
+
pen: forkedResult.pen,
|
|
237
|
+
sourcePen: forkedResult.sourcePen ?? undefined,
|
|
238
|
+
rootDir: forkedResult.project.rootDir,
|
|
239
|
+
writtenPaths: forkedResult.writtenPaths,
|
|
240
|
+
auth: forkedResult.auth,
|
|
241
|
+
forked: true,
|
|
242
|
+
linked: true,
|
|
243
|
+
project: forkedResult.project,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
if (!targetDir) {
|
|
249
|
+
const defaultFolder = suggestFolderName(pen);
|
|
250
|
+
if (interactive) {
|
|
251
|
+
const chosen = (await textImpl('Target folder', defaultFolder)).trim();
|
|
252
|
+
targetFolderDisplay = chosen || defaultFolder;
|
|
253
|
+
}
|
|
254
|
+
else {
|
|
255
|
+
targetFolderDisplay = defaultFolder;
|
|
256
|
+
}
|
|
257
|
+
targetDir = path.resolve(cwd, targetFolderDisplay);
|
|
258
|
+
const ready = await ensureCloneTargetReady(targetDir, targetFolderDisplay, {
|
|
259
|
+
force,
|
|
260
|
+
interactive,
|
|
261
|
+
confirmImpl,
|
|
262
|
+
});
|
|
263
|
+
if (!ready) {
|
|
264
|
+
return null;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
const remoteFiles = await client.getPenFiles(pen.id);
|
|
268
|
+
const result = await syncRemoteFilesToDisk({
|
|
269
|
+
client,
|
|
270
|
+
rootDir: targetDir,
|
|
271
|
+
remoteFiles,
|
|
272
|
+
pruneRemoved: false,
|
|
273
|
+
});
|
|
274
|
+
if (isOwnedByAnotherUser) {
|
|
275
|
+
if (jsonMode) {
|
|
276
|
+
printJsonResponse(200, `Cloned ${pen.title || 'Untitled'} into ${targetFolderDisplay} (unlinked local copy).`, {
|
|
277
|
+
pen,
|
|
278
|
+
linked: false,
|
|
279
|
+
forked: false,
|
|
280
|
+
profile: auth.profile,
|
|
281
|
+
folder: targetFolderDisplay,
|
|
282
|
+
root_dir: targetDir,
|
|
283
|
+
config_path: null,
|
|
284
|
+
version_id: pen.saved_version?.id ?? null,
|
|
285
|
+
written_paths: result.writtenPaths,
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
else {
|
|
289
|
+
console.log(`\n${fmt.green('✓')} Cloned ${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)} into ${fmt.cyan(targetFolderDisplay)} ${fmt.dim('(unlinked local copy)')}`);
|
|
290
|
+
console.log(` Source: ${fmt.dim(originalUrl ?? pen.urls.editor)}`);
|
|
291
|
+
console.log(` Files: ${result.writtenPaths.length} downloaded`);
|
|
292
|
+
console.log(fmt.yellow(`\nNote: No ${PROJECT_CONFIG_FILENAME} was created because this Pen belongs to ${penOwner}, not ${currentUsername}.\n` +
|
|
293
|
+
`Run \`cdpn push\` inside ${targetFolderDisplay} later to publish it as a new Pen under your account, or \`cdpn fork ${originalUrl ?? pen.urls.editor}\` to fork it on CodePen.`));
|
|
294
|
+
}
|
|
295
|
+
return {
|
|
296
|
+
pen,
|
|
297
|
+
rootDir: targetDir,
|
|
298
|
+
writtenPaths: result.writtenPaths,
|
|
299
|
+
auth,
|
|
300
|
+
forked: false,
|
|
301
|
+
linked: false,
|
|
302
|
+
project: null,
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
const syncedFiles = buildSyncedFileMap(remoteFiles, result.localSha256ByPath);
|
|
306
|
+
const config = {
|
|
307
|
+
url: originalUrl ?? pen.urls.editor,
|
|
308
|
+
pen_id: pen.id,
|
|
309
|
+
...(auth.profile ? { profile: auth.profile } : {}),
|
|
310
|
+
last_synced_version_id: pen.saved_version?.id ?? null,
|
|
311
|
+
editor: pen.editor,
|
|
312
|
+
files: syncedFiles,
|
|
313
|
+
};
|
|
314
|
+
const configPath = await writeProjectConfig(targetDir, config);
|
|
315
|
+
if (jsonMode) {
|
|
316
|
+
printJsonResponse(200, `Cloned ${pen.title || 'Untitled'} into ${targetFolderDisplay}.`, {
|
|
317
|
+
pen,
|
|
318
|
+
linked: true,
|
|
319
|
+
forked: false,
|
|
320
|
+
profile: auth.profile,
|
|
321
|
+
folder: targetFolderDisplay,
|
|
322
|
+
root_dir: targetDir,
|
|
323
|
+
config_path: configPath,
|
|
324
|
+
version_id: pen.saved_version?.id ?? null,
|
|
325
|
+
written_paths: result.writtenPaths,
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
else {
|
|
329
|
+
console.log(`\n${fmt.green('✓')} Cloned ${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)} into ${fmt.cyan(targetFolderDisplay)}`);
|
|
330
|
+
if (auth.profile) {
|
|
331
|
+
console.log(` Profile: ${fmt.cyan(auth.profile)}`);
|
|
332
|
+
}
|
|
333
|
+
console.log(` Files: ${result.writtenPaths.length} downloaded`);
|
|
334
|
+
if (pen.saved_version) {
|
|
335
|
+
console.log(` Version: ${fmt.dim(shortId(pen.saved_version.id))}`);
|
|
336
|
+
}
|
|
337
|
+
console.log(` Config: ${fmt.dim(path.join(targetFolderDisplay, PROJECT_CONFIG_FILENAME))}`);
|
|
338
|
+
if (pen.editor === 'Classic') {
|
|
339
|
+
console.log(fmt.yellow('\nNote: This is a Classic Pen (read-only through CodePen API v2). You can clone and pull files, but pushing and deploying require a CodePen 2.0 Pen.'));
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
return {
|
|
343
|
+
pen,
|
|
344
|
+
rootDir: targetDir,
|
|
345
|
+
writtenPaths: result.writtenPaths,
|
|
346
|
+
auth,
|
|
347
|
+
forked: false,
|
|
348
|
+
linked: true,
|
|
349
|
+
project: {
|
|
350
|
+
rootDir: targetDir,
|
|
351
|
+
configPath,
|
|
352
|
+
config,
|
|
353
|
+
},
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
export function registerCloneCommand(program) {
|
|
357
|
+
program
|
|
358
|
+
.command('clone <url> [folder]')
|
|
359
|
+
.description('Clone a CodePen Pen into a local folder (offers to fork if owned by another user)')
|
|
360
|
+
.option('-f, --force', 'Overwrite files if the target directory already exists and is not empty')
|
|
361
|
+
.option('--json', 'Output clone result as JSON')
|
|
362
|
+
.action(async (urlArg, folderArg, options, command) => {
|
|
363
|
+
await clonePenCommand({
|
|
364
|
+
urlArg,
|
|
365
|
+
folderArg,
|
|
366
|
+
force: options.force,
|
|
367
|
+
json: options.json,
|
|
368
|
+
explicitProfile: getGlobalProfileOption(command),
|
|
369
|
+
});
|
|
370
|
+
});
|
|
371
|
+
}
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { CodePenClient } from '../api/client.js';
|
|
4
|
+
import { buildSyncedFileMap, hasProjectConfigInDir, PROJECT_CONFIG_FILENAME, writeProjectConfig, } from '../config/project.js';
|
|
5
|
+
import { scanLocalFiles } from '../sync/fs.js';
|
|
6
|
+
import { syncRemoteFilesToDisk } from '../sync/materialize.js';
|
|
7
|
+
import { fmt, printBuildSummary, shortId } from '../utils/format.js';
|
|
8
|
+
import { extractHtmlTitle } from '../utils/html.js';
|
|
9
|
+
import { CliError } from '../utils/json.js';
|
|
10
|
+
import { isInteractive, promptConfirm, promptSecret, promptSelect, promptText, } from '../utils/prompts.js';
|
|
11
|
+
import { resolveCommandAuth } from './auth-context.js';
|
|
12
|
+
const VALID_ACCESS = new Set(['public', 'private', 'protected', 'collaborators']);
|
|
13
|
+
export function normalizeAccess(raw) {
|
|
14
|
+
if (!raw)
|
|
15
|
+
return undefined;
|
|
16
|
+
const lower = raw.trim().toLowerCase();
|
|
17
|
+
if (!VALID_ACCESS.has(lower)) {
|
|
18
|
+
throw new CliError(400, `Invalid access level "${raw}". Use: Public, Private, Protected, or Collaborators.`);
|
|
19
|
+
}
|
|
20
|
+
return (lower[0].toUpperCase() + lower.slice(1));
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Validates or interactively prompts for Pen visibility (`Public` default, `Private`,
|
|
24
|
+
* `Protected`, or `Collaborators`) and password when `Protected` is chosen.
|
|
25
|
+
*/
|
|
26
|
+
export async function resolveVisibilityAndPassword(options) {
|
|
27
|
+
const selectImpl = options.prompts?.select ?? promptSelect;
|
|
28
|
+
const secretImpl = options.prompts?.secret ?? promptSecret;
|
|
29
|
+
let access = normalizeAccess(options.rawAccess);
|
|
30
|
+
if (access === 'Protected' && options.rawPassword !== undefined && options.rawPassword.length < 8) {
|
|
31
|
+
throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
|
|
32
|
+
}
|
|
33
|
+
if (access === 'Protected' && !options.rawPassword && !options.interactive) {
|
|
34
|
+
throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
|
|
35
|
+
}
|
|
36
|
+
if (!access) {
|
|
37
|
+
if (options.interactive) {
|
|
38
|
+
access = await selectImpl('Pen visibility:', [
|
|
39
|
+
{ value: 'Public', label: 'Public', description: 'visible to everyone (default)' },
|
|
40
|
+
{ value: 'Private', label: 'Private', description: 'visible only to you / your team' },
|
|
41
|
+
{
|
|
42
|
+
value: 'Protected',
|
|
43
|
+
label: 'Protected',
|
|
44
|
+
description: 'password-protected (min 8 characters)',
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
value: 'Collaborators',
|
|
48
|
+
label: 'Collaborators',
|
|
49
|
+
description: 'visible only to you and collaborators',
|
|
50
|
+
},
|
|
51
|
+
], 0);
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
access = 'Public';
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
let password = options.rawPassword;
|
|
58
|
+
if (access === 'Protected' && (!password || password.length < 8)) {
|
|
59
|
+
if (!options.interactive) {
|
|
60
|
+
throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
|
|
61
|
+
}
|
|
62
|
+
for (;;) {
|
|
63
|
+
password = await secretImpl('Password for Protected Pen (min 8 characters)');
|
|
64
|
+
if (password.length >= 8)
|
|
65
|
+
break;
|
|
66
|
+
console.log(fmt.yellow('Password must be at least 8 characters.'));
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
access,
|
|
71
|
+
...(access === 'Protected' && password ? { password } : {}),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
export function printMissingIndexHtmlWarning(targetDir, fileCount) {
|
|
75
|
+
const headline = ' WARNING: No index.html found in this folder! ';
|
|
76
|
+
const border = '═'.repeat(headline.length);
|
|
77
|
+
console.log('');
|
|
78
|
+
console.log(fmt.yellow(fmt.bold(`╔${border}╗`)));
|
|
79
|
+
console.log(fmt.yellow(fmt.bold(`║${headline}║`)));
|
|
80
|
+
console.log(fmt.yellow(fmt.bold(`╚${border}╝`)));
|
|
81
|
+
console.log(fmt.yellow(`CodePen expects an index.html file at the root of your demo.\n` +
|
|
82
|
+
`Double-check that you are in the right folder before pushing:\n` +
|
|
83
|
+
` Folder: ${targetDir} (${fileCount} file(s) found)`));
|
|
84
|
+
console.log('');
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* First-time Pen creation flow used by `cdpn push` and `cdpn deploy` when invoked inside
|
|
88
|
+
* an unlinked local demo folder:
|
|
89
|
+
*
|
|
90
|
+
* 1. Checks for `/index.html`; if absent, displays a prominent warning and asks for confirmation.
|
|
91
|
+
* 2. Resolves or asks which CodePen account/profile to push to (when multiple keys are in `~/.cdpn`).
|
|
92
|
+
* 3. Asks for a title (pre-filled from `index.html`'s `<title>` when available).
|
|
93
|
+
* 4. Asks for visibility (`Public` default, `Private`, `Protected`, or `Collaborators`).
|
|
94
|
+
*/
|
|
95
|
+
export async function createPenFromDirectory(options) {
|
|
96
|
+
const silent = Boolean(options.silent);
|
|
97
|
+
const interactive = silent ? false : (options.interactive ?? isInteractive());
|
|
98
|
+
const confirmImpl = options.prompts?.confirm ?? promptConfirm;
|
|
99
|
+
const textImpl = options.prompts?.text ?? promptText;
|
|
100
|
+
const selectImpl = options.prompts?.select ?? promptSelect;
|
|
101
|
+
// Validate --access / --password early before prompting or scanning
|
|
102
|
+
const prevalidatedAccess = normalizeAccess(options.access);
|
|
103
|
+
if (prevalidatedAccess === 'Protected' && options.password !== undefined && options.password.length < 8) {
|
|
104
|
+
throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
|
|
105
|
+
}
|
|
106
|
+
if (prevalidatedAccess === 'Protected' && !options.password && !interactive) {
|
|
107
|
+
throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
|
|
108
|
+
}
|
|
109
|
+
const targetDir = path.resolve(options.targetDir);
|
|
110
|
+
const folderDisplay = options.folderDisplay;
|
|
111
|
+
if (await hasProjectConfigInDir(targetDir)) {
|
|
112
|
+
throw new CliError(409, `${targetDir} already contains ${PROJECT_CONFIG_FILENAME}. Use \`cdpn push\` to update the existing Pen.`);
|
|
113
|
+
}
|
|
114
|
+
const scanned = await scanLocalFiles(targetDir);
|
|
115
|
+
if (scanned.size === 0) {
|
|
116
|
+
throw new CliError(400, `No ${PROJECT_CONFIG_FILENAME} found and no syncable files in ${targetDir}.\n` +
|
|
117
|
+
'Run `cdpn clone <url>` to clone an existing Pen or `cdpn new` to scaffold a brand-new Pen.');
|
|
118
|
+
}
|
|
119
|
+
const indexFile = scanned.get('/index.html');
|
|
120
|
+
// 1. Check for index.html before pushing a local demo for the first time
|
|
121
|
+
if (!indexFile) {
|
|
122
|
+
if (!silent) {
|
|
123
|
+
printMissingIndexHtmlWarning(targetDir, scanned.size);
|
|
124
|
+
}
|
|
125
|
+
if (!options.force) {
|
|
126
|
+
if (!interactive) {
|
|
127
|
+
throw new CliError(400, `No index.html found in ${targetDir}. Pass --force to push this folder without an index.html.`);
|
|
128
|
+
}
|
|
129
|
+
const ok = await confirmImpl('Are you sure you want to push this folder without an index.html?', false);
|
|
130
|
+
if (!ok) {
|
|
131
|
+
console.log('Aborted.');
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
// 2. Ask which account/profile to push to (only prompts if multiple keys exist in ~/.cdpn)
|
|
137
|
+
const auth = await resolveCommandAuth({
|
|
138
|
+
explicitProfile: options.explicitProfile,
|
|
139
|
+
promptMessage: 'Which CodePen account/profile would you like to push to?',
|
|
140
|
+
interactive,
|
|
141
|
+
env: options.env,
|
|
142
|
+
homeDir: options.homeDir,
|
|
143
|
+
selectProfile: selectImpl,
|
|
144
|
+
});
|
|
145
|
+
const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
|
|
146
|
+
// 3. Determine title (defaulting to index.html's <title> when present)
|
|
147
|
+
const htmlTitle = indexFile && !indexFile.isBinary && indexFile.textContent
|
|
148
|
+
? extractHtmlTitle(indexFile.textContent)
|
|
149
|
+
: null;
|
|
150
|
+
const fallbackTitle = path.basename(targetDir) || 'Untitled';
|
|
151
|
+
const defaultTitle = htmlTitle ?? fallbackTitle;
|
|
152
|
+
let title = options.title?.trim();
|
|
153
|
+
if (!title) {
|
|
154
|
+
if (interactive) {
|
|
155
|
+
title = (await textImpl('Pen title', defaultTitle)).trim() || defaultTitle;
|
|
156
|
+
}
|
|
157
|
+
else {
|
|
158
|
+
title = defaultTitle;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
// 4. Ask for visibility (Public by default, Private, Protected, or Collaborators)
|
|
162
|
+
const { access, password } = await resolveVisibilityAndPassword({
|
|
163
|
+
rawAccess: options.access,
|
|
164
|
+
rawPassword: options.password,
|
|
165
|
+
interactive,
|
|
166
|
+
prompts: options.prompts,
|
|
167
|
+
});
|
|
168
|
+
const textFiles = [];
|
|
169
|
+
const binaryFiles = [];
|
|
170
|
+
for (const [filePath, lf] of scanned) {
|
|
171
|
+
if (lf.isBinary && lf.buffer.length > 0) {
|
|
172
|
+
binaryFiles.push({ path: filePath, content: lf.buffer });
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
textFiles.push({ path: filePath, content: lf.textContent ?? '' });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
const shouldWait = options.wait !== false;
|
|
179
|
+
if (!silent) {
|
|
180
|
+
console.log(`\nCreating new Pen from ${textFiles.length + binaryFiles.length} local file(s)…`);
|
|
181
|
+
}
|
|
182
|
+
const created = await client.createPen({
|
|
183
|
+
...(title ? { title } : {}),
|
|
184
|
+
...(options.description ? { description: options.description } : {}),
|
|
185
|
+
...(options.tags && options.tags.length > 0 ? { tags: options.tags } : {}),
|
|
186
|
+
access,
|
|
187
|
+
...(password ? { password } : {}),
|
|
188
|
+
...(options.template ? { template: true } : {}),
|
|
189
|
+
files: textFiles,
|
|
190
|
+
wait: shouldWait ? 45 : 0,
|
|
191
|
+
}, binaryFiles);
|
|
192
|
+
let finalBuild = created.build ?? null;
|
|
193
|
+
if (finalBuild && shouldWait) {
|
|
194
|
+
finalBuild = await client.settleBuild(finalBuild);
|
|
195
|
+
if (!silent) {
|
|
196
|
+
printBuildSummary(finalBuild);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
await fs.mkdir(targetDir, { recursive: true });
|
|
200
|
+
const finalVersionId = finalBuild?.version_id ?? created.saved_version?.id ?? null;
|
|
201
|
+
const remoteFiles = finalVersionId
|
|
202
|
+
? (await client.getVersion(finalVersionId)).files ?? (await client.getPenFiles(created.id))
|
|
203
|
+
: await client.getPenFiles(created.id);
|
|
204
|
+
const materialized = await syncRemoteFilesToDisk({
|
|
205
|
+
client,
|
|
206
|
+
rootDir: targetDir,
|
|
207
|
+
remoteFiles,
|
|
208
|
+
pruneRemoved: false,
|
|
209
|
+
});
|
|
210
|
+
const config = {
|
|
211
|
+
url: created.urls.editor,
|
|
212
|
+
pen_id: created.id,
|
|
213
|
+
...(auth.profile ? { profile: auth.profile } : {}),
|
|
214
|
+
last_synced_version_id: finalVersionId,
|
|
215
|
+
editor: created.editor,
|
|
216
|
+
files: buildSyncedFileMap(remoteFiles, materialized.localSha256ByPath),
|
|
217
|
+
};
|
|
218
|
+
const configPath = await writeProjectConfig(targetDir, config);
|
|
219
|
+
if (finalBuild?.status === 'Failed') {
|
|
220
|
+
if (!silent) {
|
|
221
|
+
console.log(`\n${fmt.yellow('!')} Created Pen ${fmt.bold(created.title || 'Untitled')} ${fmt.dim(`(${created.id})`)}, but the initial build failed.`);
|
|
222
|
+
}
|
|
223
|
+
process.exitCode = 1;
|
|
224
|
+
}
|
|
225
|
+
else if (!silent) {
|
|
226
|
+
console.log(`\n${fmt.green('✓')} Created Pen ${fmt.bold(created.title || 'Untitled')} ${fmt.dim(`(${created.id})`)}`);
|
|
227
|
+
}
|
|
228
|
+
if (!silent) {
|
|
229
|
+
if (auth.profile) {
|
|
230
|
+
console.log(` Profile: ${fmt.cyan(auth.profile)}`);
|
|
231
|
+
}
|
|
232
|
+
console.log(` Visibility: ${created.access}`);
|
|
233
|
+
console.log(` Folder: ${fmt.cyan(folderDisplay)}`);
|
|
234
|
+
console.log(` Editor: ${fmt.cyan(created.urls.editor)}`);
|
|
235
|
+
console.log(` Preview: ${fmt.cyan(created.urls.preview)}`);
|
|
236
|
+
console.log(` Version: ${fmt.dim(shortId(finalVersionId))}`);
|
|
237
|
+
}
|
|
238
|
+
return {
|
|
239
|
+
pen: created,
|
|
240
|
+
versionId: finalVersionId,
|
|
241
|
+
build: finalBuild,
|
|
242
|
+
auth,
|
|
243
|
+
project: {
|
|
244
|
+
rootDir: targetDir,
|
|
245
|
+
configPath,
|
|
246
|
+
config,
|
|
247
|
+
},
|
|
248
|
+
};
|
|
249
|
+
}
|