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