codepen-commander 1.3.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 (92) hide show
  1. package/README.md +103 -11
  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 +548 -80
  13. package/commands/deploy.js +164 -169
  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 +221 -376
  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 +103 -231
  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/{commands → workflows}/create-pen.js +59 -84
  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/meta.js +0 -184
  91. package/utils/prompts.js +0 -316
  92. /package/{types.js → api/types.js} +0 -0
@@ -0,0 +1,91 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { readProjectConfigFile } from '../config/project.js';
4
+ import { PROJECT_CONFIG_FILENAME } from '../constants.js';
5
+ import { isBuiltCollectionOutputDir } from '../site/manifest.js';
6
+ import { isIgnoredPath, loadIgnoreMatchers } from '../sync/fs.js';
7
+ import { resolveSafeDir, resolveSafeFile } from '../utils/fs-safe.js';
8
+ import { compareNatural } from '../utils/strings.js';
9
+ const DEFAULT_MAX_DISCOVERY_DEPTH = 6;
10
+ async function scanDirectoryTree(dirRealpath, segments, depth, maxDepth, visitedRealpaths, rootDir, rootRealpath, ignoreMatchers, results) {
11
+ if (depth > maxDepth)
12
+ return;
13
+ let entries;
14
+ try {
15
+ entries = await fs.readdir(dirRealpath, { withFileTypes: true });
16
+ }
17
+ catch {
18
+ return;
19
+ }
20
+ for (const entry of entries) {
21
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') {
22
+ continue;
23
+ }
24
+ const childSegments = [...segments, entry.name];
25
+ const relPosix = `/${childSegments.join('/')}`;
26
+ if (ignoreMatchers.length > 0 && isIgnoredPath(relPosix, ignoreMatchers)) {
27
+ continue;
28
+ }
29
+ const childCandidate = path.resolve(rootDir, ...childSegments);
30
+ const childRealDir = await resolveSafeDir(childCandidate, rootRealpath, rootDir);
31
+ if (!childRealDir || visitedRealpaths.has(childRealDir)) {
32
+ continue;
33
+ }
34
+ visitedRealpaths.add(childRealDir);
35
+ if (await isBuiltCollectionOutputDir(childRealDir, rootRealpath)) {
36
+ continue;
37
+ }
38
+ const configCandidate = path.join(childRealDir, PROJECT_CONFIG_FILENAME);
39
+ const configFile = await resolveSafeFile(configCandidate, rootRealpath, rootRealpath);
40
+ if (configFile) {
41
+ const relPath = childSegments.join('/');
42
+ try {
43
+ const parsed = await readProjectConfigFile(childRealDir);
44
+ results.push({
45
+ relPath,
46
+ rootDir: childRealDir,
47
+ configPath: configFile.realPath,
48
+ parsed,
49
+ });
50
+ }
51
+ catch (error) {
52
+ results.push({
53
+ relPath,
54
+ rootDir: childRealDir,
55
+ configPath: configFile.realPath,
56
+ parseError: error instanceof Error ? error.message : String(error),
57
+ });
58
+ }
59
+ // Treat a Pen folder as a leaf — never descend inside it.
60
+ continue;
61
+ }
62
+ await scanDirectoryTree(childRealDir, childSegments, depth + 1, maxDepth, visitedRealpaths, rootDir, rootRealpath, ignoreMatchers, results);
63
+ }
64
+ }
65
+ /**
66
+ * Recursively walks subdirectories beneath `rootDir` to discover all folders containing
67
+ * a `.cdpn.json` file (both linked Pens and unlinked info-only Pens).
68
+ *
69
+ * Security & traversal guarantees:
70
+ * - Enforces `isWithinRoot` and `fs.realpath()` containment; never follows symlinks.
71
+ * - Skips hidden directories (`.git`, `.codepen`, etc.), `node_modules`, `.cdpnignore`d paths,
72
+ * and previously built static collection outputs.
73
+ * - Treats each discovered Pen directory as a leaf (does not descend inside a Pen).
74
+ * - Returns Pens sorted deterministically by relative path.
75
+ */
76
+ export async function discoverPenDirectories(rootDir, options = {}) {
77
+ const resolvedRoot = path.resolve(rootDir);
78
+ let rootRealpath;
79
+ try {
80
+ rootRealpath = await fs.realpath(resolvedRoot);
81
+ }
82
+ catch {
83
+ return [];
84
+ }
85
+ const maxDepth = options.maxDepth ?? DEFAULT_MAX_DISCOVERY_DEPTH;
86
+ const ignoreMatchers = await loadIgnoreMatchers(rootRealpath);
87
+ const visitedRealpaths = new Set([rootRealpath]);
88
+ const results = [];
89
+ await scanDirectoryTree(rootRealpath, [], 0, maxDepth, visitedRealpaths, resolvedRoot, rootRealpath, ignoreMatchers, results);
90
+ return results.sort((a, b) => compareNatural(a.relPath, b.relPath));
91
+ }
@@ -0,0 +1,314 @@
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, writeProjectConfig, } from '../config/project.js';
6
+ import { MIN_PROTECTED_PASSWORD_LENGTH } from '../constants.js';
7
+ import { CliError } from '../errors.js';
8
+ import { isDirectoryNonEmpty } from '../sync/fs.js';
9
+ import { buildPenInfoConfigFields } from '../sync/info.js';
10
+ import { syncRemoteFilesToDisk } from '../sync/materialize.js';
11
+ import { assertValidProtectedPassword, assertValidTagCount, resolveAccessOrVisibility, } from '../utils/cli-options.js';
12
+ import { normalizePenReference, suggestFolderName } from '../utils/codepen-url.js';
13
+ import { fmt, printBuildSummary, 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 { slugifyTitle } from '../utils/strings.js';
18
+ import { resolveCommandAuth } from './auth-context.js';
19
+ import { clonePenWorkflow } from './clone-pen.js';
20
+ import { assertEmptyTargetDirectory } from './scaffold.js';
21
+ import { findUnmatchedStoredOwner, handlePenNotFoundOnFetch, handleUnownedPenAccess, } from './unowned-pen.js';
22
+ const FORK_NON_EMPTY_HINT = 'Choose a different target folder (e.g. `cdpn fork <url> my-fork`) or remove existing files first.';
23
+ async function isPathOccupied(candidatePath) {
24
+ try {
25
+ const stat = await fs.lstat(candidatePath);
26
+ if (!stat.isDirectory())
27
+ return true;
28
+ }
29
+ catch (error) {
30
+ if (error.code === 'ENOENT') {
31
+ return false;
32
+ }
33
+ throw error;
34
+ }
35
+ return (await hasProjectConfigInDir(candidatePath)) || (await isDirectoryNonEmpty(candidatePath));
36
+ }
37
+ /**
38
+ * Generates an available default folder name for a forked Pen, automatically appending
39
+ * `-fork` (or `-fork-2`, etc.) if the original Pen's folder name is already occupied.
40
+ */
41
+ async function suggestAvailableForkFolder(cwd, baseName) {
42
+ if (!(await isPathOccupied(path.resolve(cwd, baseName)))) {
43
+ return baseName;
44
+ }
45
+ const withFork = `${baseName}-fork`;
46
+ if (!(await isPathOccupied(path.resolve(cwd, withFork)))) {
47
+ return withFork;
48
+ }
49
+ for (let i = 2; i <= 100; i++) {
50
+ const candidate = `${baseName}-fork-${i}`;
51
+ if (!(await isPathOccupied(path.resolve(cwd, candidate)))) {
52
+ return candidate;
53
+ }
54
+ }
55
+ return `${baseName}-fork-${Date.now()}`;
56
+ }
57
+ /**
58
+ * Forks an existing CodePen Pen via `POST /v2/pens/{id}/fork` and downloads the new fork
59
+ * into a local folder linked with `.cdpn.json`.
60
+ */
61
+ export async function forkPenWorkflow(options) {
62
+ const output = options.output ?? defaultOutput;
63
+ const cwd = path.resolve(options.cwd ?? process.cwd());
64
+ const jsonMode = Boolean(options.json);
65
+ const interactive = (options.interactive ?? isInteractive()) && !jsonMode;
66
+ const textImpl = options.prompts?.text ?? promptText;
67
+ const confirmImpl = options.prompts?.confirm ?? promptConfirm;
68
+ const selectImpl = options.prompts?.select ?? promptSelect;
69
+ const secretImpl = options.prompts?.secret ?? promptSecret;
70
+ const { apiIdentifier, originalUrl } = normalizePenReference(options.urlArg);
71
+ assertValidTagCount(options.tags);
72
+ const explicitAccess = resolveAccessOrVisibility(options.access, options.visibility);
73
+ assertValidProtectedPassword(explicitAccess, options.password, interactive);
74
+ // If target folder was passed explicitly, validate before hitting the network
75
+ let targetDir = null;
76
+ let folderDisplay = options.folderArg?.trim() || '';
77
+ if (folderDisplay) {
78
+ targetDir = path.resolve(cwd, folderDisplay);
79
+ if (!options.allowOverwrite) {
80
+ await assertEmptyTargetDirectory(targetDir, folderDisplay, {
81
+ commandName: 'fork',
82
+ nonEmptyHint: FORK_NON_EMPTY_HINT,
83
+ });
84
+ }
85
+ }
86
+ const clonePastedForkUrl = async (pastedUrl) => {
87
+ const cloned = await clonePenWorkflow({
88
+ urlArg: pastedUrl,
89
+ folderArg: options.folderArg,
90
+ cwd,
91
+ output,
92
+ baseUrl: options.baseUrl,
93
+ interactive,
94
+ env: options.env,
95
+ homeDir: options.homeDir,
96
+ openBrowser: options.openBrowser,
97
+ allowBrowserFallback: false,
98
+ prompts: {
99
+ text: textImpl,
100
+ confirm: confirmImpl,
101
+ select: selectImpl,
102
+ secret: secretImpl,
103
+ },
104
+ });
105
+ if (!cloned || !cloned.project) {
106
+ return null;
107
+ }
108
+ return {
109
+ sourcePen: null,
110
+ pen: cloned.pen,
111
+ versionId: cloned.pen.saved_version?.id ?? null,
112
+ build: null,
113
+ writtenPaths: cloned.writtenPaths,
114
+ auth: cloned.auth,
115
+ project: cloned.project,
116
+ forkedInBrowser: true,
117
+ };
118
+ };
119
+ if (!options.resolvedAuth && !options.sourcePen) {
120
+ const unmatched = await findUnmatchedStoredOwner({
121
+ originalUrl,
122
+ explicitProfile: options.explicitProfile,
123
+ env: options.env,
124
+ homeDir: options.homeDir,
125
+ });
126
+ if (unmatched && originalUrl) {
127
+ const pastedUrl = await handleUnownedPenAccess({
128
+ action: 'fork',
129
+ penUrl: originalUrl,
130
+ urlOwner: unmatched.urlOwner,
131
+ availableProfiles: unmatched.availableProfiles,
132
+ interactive,
133
+ allowBrowserFallback: options.allowBrowserFallback,
134
+ output,
135
+ confirmImpl,
136
+ textImpl,
137
+ openBrowserImpl: options.openBrowser,
138
+ });
139
+ if (!pastedUrl) {
140
+ return null;
141
+ }
142
+ return clonePastedForkUrl(pastedUrl);
143
+ }
144
+ }
145
+ const auth = options.resolvedAuth ??
146
+ (await resolveCommandAuth({
147
+ explicitProfile: options.explicitProfile,
148
+ urlHint: originalUrl ?? options.urlArg,
149
+ promptMessage: 'Which CodePen profile should be used to fork this Pen?',
150
+ interactive,
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
+ let sourcePen;
158
+ if (options.sourcePen) {
159
+ sourcePen = options.sourcePen;
160
+ }
161
+ else {
162
+ if (!jsonMode) {
163
+ output.log(`Fetching Pen ${fmt.cyan(apiIdentifier)}…`);
164
+ }
165
+ try {
166
+ sourcePen = await client.getPen(apiIdentifier);
167
+ }
168
+ catch (error) {
169
+ if (error instanceof CodePenApiError && error.status === 404) {
170
+ const pastedUrl = await handlePenNotFoundOnFetch({
171
+ action: 'fork',
172
+ apiIdentifier,
173
+ originalUrl,
174
+ auth,
175
+ client,
176
+ interactive,
177
+ allowBrowserFallback: options.allowBrowserFallback,
178
+ output,
179
+ confirmImpl,
180
+ textImpl,
181
+ openBrowserImpl: options.openBrowser,
182
+ });
183
+ if (!pastedUrl) {
184
+ return null;
185
+ }
186
+ return clonePastedForkUrl(pastedUrl);
187
+ }
188
+ throw error;
189
+ }
190
+ }
191
+ // CodePen API requires a password when forking a Protected Pen (unless access is overridden)
192
+ const effectiveAccess = explicitAccess ?? sourcePen.access;
193
+ let password = options.password;
194
+ if (effectiveAccess === 'Protected' &&
195
+ (!password || password.length < MIN_PROTECTED_PASSWORD_LENGTH)) {
196
+ if (!interactive) {
197
+ throw new CliError(400, `Forking a Protected Pen requires --password with at least ${MIN_PROTECTED_PASSWORD_LENGTH} characters (or pass --access Public/Private).`);
198
+ }
199
+ for (;;) {
200
+ password = await secretImpl(`Password for Protected fork (min ${MIN_PROTECTED_PASSWORD_LENGTH} characters)`);
201
+ if (password.length >= MIN_PROTECTED_PASSWORD_LENGTH)
202
+ break;
203
+ output.log(fmt.yellow(`Password must be at least ${MIN_PROTECTED_PASSWORD_LENGTH} characters.`));
204
+ }
205
+ }
206
+ const title = options.title?.trim() || undefined;
207
+ // Determine target folder if omitted (asked interactively or generated cleanly) BEFORE calling fork
208
+ if (!targetDir) {
209
+ const baseName = (title ? slugifyTitle(title) : null) ?? suggestFolderName(sourcePen);
210
+ const defaultFolder = await suggestAvailableForkFolder(cwd, baseName);
211
+ if (interactive) {
212
+ const chosen = (await textImpl('Target folder', defaultFolder)).trim();
213
+ folderDisplay = chosen || defaultFolder;
214
+ }
215
+ else {
216
+ folderDisplay = defaultFolder;
217
+ }
218
+ targetDir = path.resolve(cwd, folderDisplay);
219
+ await assertEmptyTargetDirectory(targetDir, folderDisplay, {
220
+ commandName: 'fork',
221
+ nonEmptyHint: FORK_NON_EMPTY_HINT,
222
+ });
223
+ }
224
+ const shouldWait = options.wait !== false;
225
+ if (!jsonMode) {
226
+ output.log(`\nForking ${fmt.bold(sourcePen.title || 'Untitled')} ${fmt.dim(`(${sourcePen.id})`)}…`);
227
+ }
228
+ const forked = await client.forkPen(sourcePen.id, {
229
+ ...(title ? { title } : {}),
230
+ ...(options.description ? { description: options.description } : {}),
231
+ ...(options.tags && options.tags.length > 0 ? { tags: options.tags } : {}),
232
+ ...(explicitAccess ? { access: explicitAccess } : {}),
233
+ ...(effectiveAccess === 'Protected' && password ? { password } : {}),
234
+ wait: shouldWait ? 45 : 0,
235
+ });
236
+ let finalBuild = forked.build ?? null;
237
+ if (finalBuild && shouldWait) {
238
+ finalBuild = await client.settleBuild(finalBuild);
239
+ if (!jsonMode) {
240
+ printBuildSummary(finalBuild, output);
241
+ }
242
+ }
243
+ await fs.mkdir(targetDir, { recursive: true });
244
+ const finalVersionId = finalBuild?.version_id ?? forked.saved_version?.id ?? null;
245
+ const remoteFiles = finalVersionId
246
+ ? (await client.getVersion(finalVersionId)).files ?? (await client.getPenFiles(forked.id))
247
+ : await client.getPenFiles(forked.id);
248
+ const materialized = await syncRemoteFilesToDisk({
249
+ client,
250
+ rootDir: targetDir,
251
+ remoteFiles,
252
+ pruneRemoved: false,
253
+ });
254
+ const config = {
255
+ url: forked.urls.editor,
256
+ pen_id: forked.id,
257
+ ...(auth.profile ? { profile: auth.profile } : {}),
258
+ last_synced_version_id: finalVersionId,
259
+ editor: forked.editor,
260
+ ...buildPenInfoConfigFields(forked),
261
+ files: buildSyncedFileMap(remoteFiles, materialized.localSha256ByPath),
262
+ };
263
+ const configPath = await writeProjectConfig(targetDir, config);
264
+ const buildFailed = finalBuild?.status === 'Failed';
265
+ if (jsonMode) {
266
+ const code = buildFailed ? 422 : 201;
267
+ const message = buildFailed
268
+ ? `Forked ${forked.title || 'Untitled'}, but the initial build failed.`
269
+ : `Forked ${forked.title || 'Untitled'} into ${folderDisplay}.`;
270
+ printJsonResponse(code, message, {
271
+ pen: forked,
272
+ source_pen: sourcePen,
273
+ profile: auth.profile,
274
+ folder: folderDisplay,
275
+ root_dir: targetDir,
276
+ config_path: configPath,
277
+ version_id: finalVersionId,
278
+ build: finalBuild,
279
+ written_paths: materialized.writtenPaths,
280
+ }, output);
281
+ }
282
+ else {
283
+ if (buildFailed) {
284
+ output.log(`\n${fmt.yellow('!')} Forked ${fmt.bold(forked.title || 'Untitled')} ${fmt.dim(`(${forked.id})`)}, but the initial build failed.`);
285
+ }
286
+ else {
287
+ output.log(`\n${fmt.green('✓')} Forked ${fmt.bold(forked.title || 'Untitled')} ${fmt.dim(`(${forked.id})`)}`);
288
+ }
289
+ output.log(` From: ${fmt.dim(sourcePen.urls.editor)}`);
290
+ if (auth.profile) {
291
+ output.log(` Profile: ${fmt.cyan(auth.profile)}`);
292
+ }
293
+ output.log(` Visibility: ${forked.access}`);
294
+ output.log(` Folder: ${fmt.cyan(folderDisplay)}`);
295
+ output.log(` Files: ${materialized.writtenPaths.length} downloaded`);
296
+ output.log(` Editor: ${fmt.cyan(forked.urls.editor)}`);
297
+ output.log(` Preview: ${fmt.cyan(forked.urls.preview)}`);
298
+ output.log(` Version: ${fmt.dim(shortId(finalVersionId))}`);
299
+ }
300
+ return {
301
+ sourcePen,
302
+ pen: forked,
303
+ versionId: finalVersionId,
304
+ build: finalBuild,
305
+ writtenPaths: materialized.writtenPaths,
306
+ auth,
307
+ project: {
308
+ rootDir: targetDir,
309
+ configPath,
310
+ config,
311
+ },
312
+ ...(buildFailed ? { exitCode: 1 } : {}),
313
+ };
314
+ }
@@ -0,0 +1,212 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { CodePenApiError, isCodePenApiError } from '../api/errors.js';
4
+ import { normalizePartialPenInfo, writeUnlinkedProjectInfo, } from '../config/project.js';
5
+ import { CODEPEN_DELETED_ITEMS_URL, CODEPEN_DIR, PROJECT_CONFIG_FILENAME } from '../constants.js';
6
+ import { CliError } from '../errors.js';
7
+ import { extractPenIdFromUrl } from '../utils/codepen-url.js';
8
+ import { fmt, formatDate } from '../utils/format.js';
9
+ import { isWithinRoot } from '../utils/fs-safe.js';
10
+ import { defaultOutput } from '../utils/output.js';
11
+ import { promptConfirm, promptSelect, } from '../utils/prompts/index.js';
12
+ export { CODEPEN_DELETED_ITEMS_URL };
13
+ export function isRemotePenNotFoundError(error) {
14
+ return isCodePenApiError(error) && error.status === 404;
15
+ }
16
+ /**
17
+ * Clears all online-link fields (`url`, `pen_id`, `profile`, `last_synced_version_id`,
18
+ * `last_synced_info_hash`, `editor`, `files`) from `.cdpn.json`, leaving an unlinked
19
+ * info-only `.cdpn.json` so the demo stays recognized locally and can be re-pushed as a new Pen.
20
+ */
21
+ export async function unlinkLinkedProject(project, fallbackTitle) {
22
+ const info = normalizePartialPenInfo(project.config.info ?? {});
23
+ if (!info.title && fallbackTitle?.trim()) {
24
+ info.title = fallbackTitle.trim();
25
+ }
26
+ const configPath = await writeUnlinkedProjectInfo(project.rootDir, info);
27
+ return { configPath, info };
28
+ }
29
+ /**
30
+ * Safely removes `<rootDir>/.codepen/` if it is a regular directory strictly within `rootDir`.
31
+ * Never follows symlinks. Returns `true` if `.codepen/` existed and was removed.
32
+ */
33
+ export async function removeCodepenDirSafe(rootDir) {
34
+ const resolvedRoot = await fs.realpath(rootDir);
35
+ const codepenDir = path.join(resolvedRoot, CODEPEN_DIR);
36
+ let stat;
37
+ try {
38
+ stat = await fs.lstat(codepenDir);
39
+ }
40
+ catch (error) {
41
+ if (error.code === 'ENOENT') {
42
+ return false;
43
+ }
44
+ throw error;
45
+ }
46
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
47
+ return false;
48
+ }
49
+ const realCodepenDir = await fs.realpath(codepenDir);
50
+ if (!isWithinRoot(realCodepenDir, resolvedRoot) || realCodepenDir === resolvedRoot) {
51
+ return false;
52
+ }
53
+ await fs.rm(realCodepenDir, { recursive: true, force: true });
54
+ return true;
55
+ }
56
+ /**
57
+ * Checks CodePen's Trash (`GET /v2/trash`) for the Pen referenced by `project`.
58
+ * Gracefully returns `null` if not found or if the trash endpoint is unavailable.
59
+ */
60
+ export async function findProjectPenInTrash(client, project) {
61
+ const ids = [project.config.pen_id];
62
+ const urlPenId = extractPenIdFromUrl(project.config.url);
63
+ if (urlPenId && !ids.includes(urlPenId)) {
64
+ ids.push(urlPenId);
65
+ }
66
+ try {
67
+ return await client.findTrashedPen(ids);
68
+ }
69
+ catch {
70
+ return null;
71
+ }
72
+ }
73
+ /**
74
+ * Handles a `404 NOT_FOUND` error for a locally linked Pen across `cdpn` commands:
75
+ *
76
+ * - First checks CodePen's Deleted Items (`GET /v2/trash`).
77
+ * - If found in Trash interactively, offers a choice menu:
78
+ * 1. Recover the Pen from Trash (`POST /v2/pens/{id}/restore`) and continue
79
+ * 2. Delete the Pen permanently (`DELETE /v2/trash/pens/{id}`) and unlink `.cdpn.json`
80
+ * 3. Unlink the local copy from the Pen (clear remote link fields in `.cdpn.json`)
81
+ * 4. Do nothing (exit)
82
+ * - If not found in Trash interactively, informs the user the Pen no longer exists on CodePen
83
+ * and offers to unlink `.cdpn.json`.
84
+ * - In non-interactive or `--json` mode, throws a structured `CliError(404)` with helpful guidance.
85
+ */
86
+ export async function handleMissingRemotePen(options) {
87
+ const { client, project, auth, commandName, interactive } = options;
88
+ const output = options.output ?? defaultOutput;
89
+ const selectImpl = options.prompts?.select ?? promptSelect;
90
+ const confirmImpl = options.prompts?.confirm ?? promptConfirm;
91
+ const trashItem = await findProjectPenInTrash(client, project);
92
+ const displayTitle = trashItem?.title || project.config.info?.title || 'Untitled';
93
+ const activeProfile = auth?.profile ?? project.config.profile ?? null;
94
+ if (trashItem) {
95
+ if (!interactive) {
96
+ throw new CliError(404, `Pen "${displayTitle}" (${project.config.pen_id}) is currently in CodePen’s Deleted Items (Trash; expires ${formatDate(trashItem.expires_at)}).\n` +
97
+ `Run \`cdpn restore\` to restore it on CodePen, run \`cdpn ${commandName}\` interactively to manage it, or restore it at ${CODEPEN_DELETED_ITEMS_URL}.`, {
98
+ pen_id: project.config.pen_id,
99
+ url: project.config.url,
100
+ profile: activeProfile,
101
+ in_trash: true,
102
+ trash_item: trashItem,
103
+ restore_url: CODEPEN_DELETED_ITEMS_URL,
104
+ });
105
+ }
106
+ output.log('');
107
+ output.log(`${fmt.boldYellow('!')} Pen ${fmt.bold(displayTitle)} ${fmt.dim(`(${project.config.pen_id})`)} was deleted on CodePen and is currently in ${fmt.bold('Deleted Items (Trash)')}.`);
108
+ output.log(` ${fmt.dim('Deleted:')} ${formatDate(trashItem.deleted_at)} ${fmt.dim('·')} ${fmt.dim('Expires:')} ${fmt.yellow(formatDate(trashItem.expires_at))}`);
109
+ output.log(` ${fmt.dim('URL:')} ${fmt.cyan(project.config.url)}`);
110
+ output.log('');
111
+ const choice = await selectImpl('What would you like to do?', [
112
+ {
113
+ value: 'recover',
114
+ label: 'Restore the Pen from Trash',
115
+ description: `restore it on CodePen and continue \`cdpn ${commandName}\``,
116
+ },
117
+ {
118
+ value: 'purge',
119
+ label: 'Delete the Pen permanently',
120
+ description: `purge from CodePen Trash and unlink ${PROJECT_CONFIG_FILENAME}`,
121
+ },
122
+ {
123
+ value: 'unlink',
124
+ label: 'Unlink local copy from this Pen',
125
+ description: `clear remote link in ${PROJECT_CONFIG_FILENAME} so you can re-push as a new Pen`,
126
+ },
127
+ {
128
+ value: 'cancel',
129
+ label: 'Do nothing (exit)',
130
+ description: `leave Trash and ${PROJECT_CONFIG_FILENAME} untouched`,
131
+ },
132
+ ], 0);
133
+ if (choice === 'recover') {
134
+ const pen = await client.restorePen(trashItem.item_id);
135
+ output.log(`\n${fmt.boldGreen('✓')} Restored ${fmt.bold(pen.title || displayTitle)} ${fmt.dim(`(${pen.id})`)} from CodePen Trash.\n`);
136
+ return { action: 'recovered', pen, trashItem };
137
+ }
138
+ if (choice === 'purge') {
139
+ const confirmed = await confirmImpl(`Permanently delete "${displayTitle}" (${trashItem.item_id}) from CodePen Trash? This cannot be undone.`, false);
140
+ if (!confirmed) {
141
+ output.log(fmt.dim('Aborted.'));
142
+ return { action: 'canceled', trashItem };
143
+ }
144
+ await client.purgeTrashedPen(trashItem.item_id);
145
+ const { info: unlinkedInfo } = await unlinkLinkedProject(project, trashItem.title);
146
+ output.log(`\n${fmt.boldGreen('✓')} Permanently deleted ${fmt.bold(displayTitle)} ${fmt.dim(`(${trashItem.item_id})`)} from CodePen Trash.`);
147
+ output.log(` ${fmt.dim('Unlinked:')} ${fmt.cyan(PROJECT_CONFIG_FILENAME)} ${fmt.dim('(cleared remote link; Pen info & local files kept untouched)')}`);
148
+ output.log(` ${fmt.dim('Tip:')} Run \`cdpn push\` anytime to publish this folder as a new Pen on CodePen.`);
149
+ return { action: 'purged', trashItem, unlinkedInfo };
150
+ }
151
+ if (choice === 'unlink') {
152
+ const { info: unlinkedInfo } = await unlinkLinkedProject(project, trashItem.title);
153
+ output.log(`\n${fmt.boldGreen('✓')} Unlinked local folder from Pen ${fmt.dim(`(${project.config.pen_id})`)}.`);
154
+ output.log(` ${fmt.dim('Updated:')} ${fmt.cyan(PROJECT_CONFIG_FILENAME)} ${fmt.dim('(cleared remote link; Pen info & local files kept untouched)')}`);
155
+ output.log(` ${fmt.dim('Note:')} The deleted Pen remains in CodePen Trash until ${formatDate(trashItem.expires_at)} (${CODEPEN_DELETED_ITEMS_URL}).`);
156
+ output.log(` ${fmt.dim('Tip:')} Run \`cdpn push\` anytime to publish this folder as a new Pen on CodePen.`);
157
+ return { action: 'unlinked', trashItem, unlinkedInfo };
158
+ }
159
+ output.log(fmt.dim('No changes made.'));
160
+ return { action: 'canceled', trashItem };
161
+ }
162
+ // Not found on CodePen and not in Trash
163
+ if (!interactive) {
164
+ const profileHint = activeProfile ? ` (active profile: ${activeProfile})` : '';
165
+ throw new CliError(404, `Pen "${displayTitle}" (${project.config.pen_id}) no longer exists on CodePen.\n` +
166
+ `It may have been permanently deleted, or belongs to a different account/profile${profileHint}.\n` +
167
+ `Run \`cdpn ${commandName}\` interactively to unlink ${PROJECT_CONFIG_FILENAME}, \`cdpn unlink --yes\` to clear the remote link, or pass --profile <name> if another profile owns it.`, {
168
+ pen_id: project.config.pen_id,
169
+ url: project.config.url,
170
+ profile: activeProfile,
171
+ in_trash: false,
172
+ });
173
+ }
174
+ output.log('');
175
+ output.log(`${fmt.boldYellow('!')} Pen ${fmt.bold(displayTitle)} ${fmt.dim(`(${project.config.pen_id})`)} no longer exists on CodePen (and is not in Deleted Items).`);
176
+ output.log(fmt.dim(' It may have been permanently deleted on CodePen, or belongs to a different account/profile.'));
177
+ output.log(` ${fmt.dim('URL:')} ${fmt.cyan(project.config.url)}`);
178
+ if (activeProfile) {
179
+ output.log(` ${fmt.dim('Profile:')} ${fmt.cyan(activeProfile)}`);
180
+ }
181
+ output.log('');
182
+ const shouldUnlink = await confirmImpl(`Unlink this local folder from the missing Pen (clears remote link in ${PROJECT_CONFIG_FILENAME}, keeps Pen info & local files)?`, true);
183
+ if (!shouldUnlink) {
184
+ output.log(fmt.dim(`Kept ${PROJECT_CONFIG_FILENAME} unchanged. Tip: if another profile owns this Pen, re-run with --profile <name>.`));
185
+ return { action: 'canceled', trashItem: null };
186
+ }
187
+ const { info: unlinkedInfo } = await unlinkLinkedProject(project);
188
+ output.log(`\n${fmt.boldGreen('✓')} Unlinked local folder from missing Pen ${fmt.dim(`(${project.config.pen_id})`)}.`);
189
+ output.log(` ${fmt.dim('Updated:')} ${fmt.cyan(PROJECT_CONFIG_FILENAME)} ${fmt.dim('(cleared remote link; Pen info & local files kept untouched)')}`);
190
+ output.log(` ${fmt.dim('Tip:')} Run \`cdpn push\` anytime to publish this folder as a new Pen on CodePen.`);
191
+ return { action: 'unlinked', trashItem: null, unlinkedInfo };
192
+ }
193
+ /**
194
+ * Fetches the remote Pen for a linked `.cdpn.json` project, automatically invoking
195
+ * `handleMissingRemotePen` if CodePen returns `404 NOT_FOUND`.
196
+ */
197
+ export async function fetchLinkedPenOrHandleMissing(options) {
198
+ try {
199
+ const pen = await options.client.getPen(options.project.config.pen_id);
200
+ return { found: true, pen, recoveredFromTrash: false };
201
+ }
202
+ catch (error) {
203
+ if (!isRemotePenNotFoundError(error)) {
204
+ throw error;
205
+ }
206
+ const resolution = await handleMissingRemotePen(options);
207
+ if (resolution.action === 'recovered') {
208
+ return { found: true, pen: resolution.pen, recoveredFromTrash: true };
209
+ }
210
+ return { found: false, resolution };
211
+ }
212
+ }