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