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.
@@ -0,0 +1,164 @@
1
+ import { CodePenClient } from '../api/client.js';
2
+ import { requireProject } from '../config/project.js';
3
+ import { fmt, formatDate, shortId } from '../utils/format.js';
4
+ import { CliError, printJsonResponse } from '../utils/json.js';
5
+ import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
6
+ const VALID_ACCESS = new Set(['public', 'private', 'protected', 'collaborators']);
7
+ function parseBooleanOption(raw, flagName) {
8
+ const lower = raw.trim().toLowerCase();
9
+ if (lower === 'true' || lower === '1' || lower === 'yes' || lower === 'on')
10
+ return true;
11
+ if (lower === 'false' || lower === '0' || lower === 'no' || lower === 'off')
12
+ return false;
13
+ throw new CliError(400, `Invalid boolean value "${raw}" for ${flagName}. Use true or false.`);
14
+ }
15
+ function renderPenInfo(pen, profile) {
16
+ console.log(`${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)}`);
17
+ if (profile) {
18
+ console.log(`Profile: ${fmt.cyan(profile)}`);
19
+ }
20
+ if (pen.description) {
21
+ console.log(`Description: ${pen.description}`);
22
+ }
23
+ console.log(`Editor: ${pen.editor}`);
24
+ console.log(`Access: ${pen.access}${pen.template ? fmt.dim(' · Template') : ''}`);
25
+ console.log(`Tags: ${pen.tags.length > 0 ? pen.tags.join(', ') : fmt.dim('none')}`);
26
+ console.log(`Stats: ${pen.views_count} views · ${pen.loves_count} loves`);
27
+ console.log(`Editor URL: ${fmt.cyan(pen.urls.editor)}`);
28
+ console.log(`Preview URL: ${fmt.cyan(pen.urls.preview)}`);
29
+ if (pen.deployment) {
30
+ console.log(`Deployed: ${fmt.cyan(pen.deployment.url)} ${fmt.dim(`(v ${shortId(pen.deployment.version_id)})`)}`);
31
+ if (pen.deployment.custom_domains.length > 0) {
32
+ console.log(`Domains: ${pen.deployment.custom_domains.join(', ')}`);
33
+ }
34
+ }
35
+ else {
36
+ console.log(`Deployed: ${fmt.dim('not deployed')}`);
37
+ }
38
+ console.log(`Created: ${fmt.dim(formatDate(pen.created_at))}`);
39
+ console.log(`Updated: ${fmt.dim(formatDate(pen.updated_at))}`);
40
+ }
41
+ function renderPenSettings(settings) {
42
+ const boolText = (b) => (b ? fmt.green('true') : fmt.dim('false'));
43
+ console.log(`auto_deploy: ${boolText(settings.auto_deploy)}`);
44
+ console.log(`auto_run: ${boolText(settings.auto_run)}`);
45
+ console.log(`auto_save: ${boolText(settings.auto_save)}`);
46
+ console.log(`indent_with: ${fmt.cyan(settings.indent_with)}`);
47
+ console.log(`tab_size: ${fmt.cyan(String(settings.tab_size))}`);
48
+ }
49
+ export function registerMetaCommands(program) {
50
+ program
51
+ .command('info')
52
+ .description('Show or update Pen metadata (title, description, tags, access, template)')
53
+ .option('-t, --title <title>', 'Update Pen title')
54
+ .option('-d, --description <text>', 'Update Pen description')
55
+ .option('--tags <tags>', 'Replace tags with comma-separated list (pass "" to clear)')
56
+ .option('--access <level>', 'Update access: Public, Private, Protected, or Collaborators')
57
+ .option('--password <password>', 'Set/replace password (min 8 chars; for Protected Pens)')
58
+ .option('--template <bool>', 'Set template flag (true/false)')
59
+ .option('--json', 'Output Pen metadata as JSON')
60
+ .action(async (options, command) => {
61
+ const project = await requireProject();
62
+ const auth = await resolveCommandAuth({
63
+ explicitProfile: getGlobalProfileOption(command),
64
+ project,
65
+ interactive: options.json ? false : undefined,
66
+ persistProfileToProject: !options.json,
67
+ });
68
+ const client = new CodePenClient({ apiKey: auth.apiKey });
69
+ const patch = {};
70
+ if (options.title !== undefined)
71
+ patch.title = options.title;
72
+ if (options.description !== undefined)
73
+ patch.description = options.description;
74
+ if (options.tags !== undefined) {
75
+ patch.tags = options.tags
76
+ .split(',')
77
+ .map((t) => t.trim())
78
+ .filter(Boolean);
79
+ }
80
+ if (options.access !== undefined) {
81
+ const lower = options.access.trim().toLowerCase();
82
+ if (!VALID_ACCESS.has(lower)) {
83
+ throw new CliError(400, `Invalid --access "${options.access}". Use: Public, Private, Protected, or Collaborators.`);
84
+ }
85
+ patch.access = (lower[0].toUpperCase() + lower.slice(1));
86
+ }
87
+ if (options.password !== undefined) {
88
+ if (options.password.length < 8) {
89
+ throw new CliError(400, 'Password must be at least 8 characters.');
90
+ }
91
+ patch.password = options.password;
92
+ }
93
+ if (options.template !== undefined) {
94
+ patch.template = parseBooleanOption(options.template, '--template');
95
+ }
96
+ const hasUpdates = Object.keys(patch).length > 0;
97
+ const pen = hasUpdates
98
+ ? await client.updatePen(project.config.pen_id, patch)
99
+ : await client.getPen(project.config.pen_id);
100
+ if (options.json) {
101
+ printJsonResponse(200, hasUpdates ? 'Updated Pen metadata.' : 'Fetched Pen metadata.', pen);
102
+ return;
103
+ }
104
+ if (hasUpdates) {
105
+ console.log(`${fmt.green('✓')} Updated Pen metadata.\n`);
106
+ }
107
+ renderPenInfo(pen, auth.profile);
108
+ });
109
+ program
110
+ .command('settings')
111
+ .description('View or update Pen editor & deploy settings')
112
+ .option('--auto-deploy <bool>', 'Auto-deploy on save (true/false)')
113
+ .option('--auto-run <bool>', 'Auto-run preview (true/false)')
114
+ .option('--auto-save <bool>', 'Auto-save in editor (true/false)')
115
+ .option('--indent-with <mode>', 'Indentation style: tabs or spaces')
116
+ .option('--tab-size <n>', 'Tab size (integer between 1 and 6)')
117
+ .option('--json', 'Output settings as JSON')
118
+ .action(async (options, command) => {
119
+ const project = await requireProject();
120
+ const auth = await resolveCommandAuth({
121
+ explicitProfile: getGlobalProfileOption(command),
122
+ project,
123
+ interactive: options.json ? false : undefined,
124
+ persistProfileToProject: !options.json,
125
+ });
126
+ const client = new CodePenClient({ apiKey: auth.apiKey });
127
+ const patch = {};
128
+ if (options.autoDeploy !== undefined) {
129
+ patch.auto_deploy = parseBooleanOption(options.autoDeploy, '--auto-deploy');
130
+ }
131
+ if (options.autoRun !== undefined) {
132
+ patch.auto_run = parseBooleanOption(options.autoRun, '--auto-run');
133
+ }
134
+ if (options.autoSave !== undefined) {
135
+ patch.auto_save = parseBooleanOption(options.autoSave, '--auto-save');
136
+ }
137
+ if (options.indentWith !== undefined) {
138
+ const lower = options.indentWith.trim().toLowerCase();
139
+ if (lower !== 'tabs' && lower !== 'spaces') {
140
+ throw new CliError(400, 'Invalid --indent-with value. Use "tabs" or "spaces".');
141
+ }
142
+ patch.indent_with = lower;
143
+ }
144
+ if (options.tabSize !== undefined) {
145
+ const parsed = Number.parseInt(options.tabSize, 10);
146
+ if (Number.isNaN(parsed) || parsed < 1 || parsed > 6) {
147
+ throw new CliError(400, '--tab-size must be an integer between 1 and 6.');
148
+ }
149
+ patch.tab_size = parsed;
150
+ }
151
+ const hasUpdates = Object.keys(patch).length > 0;
152
+ const settings = hasUpdates
153
+ ? await client.updateSettings(project.config.pen_id, patch)
154
+ : (await client.getPen(project.config.pen_id)).settings;
155
+ if (options.json) {
156
+ printJsonResponse(200, hasUpdates ? 'Updated Pen settings.' : 'Fetched Pen settings.', settings);
157
+ return;
158
+ }
159
+ if (hasUpdates) {
160
+ console.log(`${fmt.green('✓')} Updated Pen settings.\n`);
161
+ }
162
+ renderPenSettings(settings);
163
+ });
164
+ }
@@ -0,0 +1,294 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { CodePenClient } from '../api/client.js';
4
+ import { buildSyncedFileMap, slugifyTitle, writeProjectConfig, } from '../config/project.js';
5
+ import { isDirectoryNonEmpty } from '../sync/fs.js';
6
+ import { syncRemoteFilesToDisk } from '../sync/materialize.js';
7
+ import { fmt, formatDate, printBuildSummary, shortId } from '../utils/format.js';
8
+ import { CliError, printJsonResponse } from '../utils/json.js';
9
+ import { isInteractive, promptSecret, promptSelect, promptText, } from '../utils/prompts.js';
10
+ import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
11
+ import { normalizeAccess, resolveVisibilityAndPassword } from './create-pen.js';
12
+ import { assertEmptyTargetDirectory, fetchPenFilesAsUploadPayload, listAccountTemplates, resolveTemplatePen, } from './scaffold.js';
13
+ const NEW_NON_EMPTY_HINT = 'To push an existing local demo folder to CodePen, run `cdpn push` inside that folder, or pass a new folder name (e.g. `cdpn new my-pen`).';
14
+ /**
15
+ * Scaffolds a brand-new CodePen 2.0 Pen strictly from CodePen's built-in default starter
16
+ * or one of your CodePen Templates, and materializes it into a new/empty local folder
17
+ * linked with `.cdpn.json`.
18
+ */
19
+ export async function scaffoldNewPen(options = {}) {
20
+ const cwd = path.resolve(options.cwd ?? process.cwd());
21
+ const jsonMode = Boolean(options.json);
22
+ const interactive = (options.interactive ?? isInteractive()) && !jsonMode;
23
+ const textImpl = options.prompts?.text ?? promptText;
24
+ const selectImpl = options.prompts?.select ?? promptSelect;
25
+ const secretImpl = options.prompts?.secret ?? promptSecret;
26
+ if (options.tags && options.tags.length > 5) {
27
+ throw new CliError(400, 'CodePen allows at most 5 tags per Pen.');
28
+ }
29
+ // Pre-validate --access and --password before hitting the network
30
+ const prevalidatedAccess = normalizeAccess(options.access);
31
+ if (prevalidatedAccess === 'Protected' && options.password !== undefined && options.password.length < 8) {
32
+ throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
33
+ }
34
+ if (prevalidatedAccess === 'Protected' && !options.password && !interactive) {
35
+ throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
36
+ }
37
+ // If the user passed an explicit folder argument, validate immediately that it is empty/new
38
+ let targetDir = null;
39
+ let folderDisplay = options.folderArg?.trim() || '';
40
+ if (folderDisplay) {
41
+ targetDir = path.resolve(cwd, folderDisplay);
42
+ await assertEmptyTargetDirectory(targetDir, folderDisplay, {
43
+ commandName: 'new',
44
+ nonEmptyHint: NEW_NON_EMPTY_HINT,
45
+ });
46
+ }
47
+ const urlHint = options.template && /^https?:\/\//i.test(options.template.trim())
48
+ ? options.template.trim()
49
+ : undefined;
50
+ // 1. Resolve CodePen account/profile (prompts only if multiple profiles exist in ~/.cdpn)
51
+ const auth = await resolveCommandAuth({
52
+ explicitProfile: options.explicitProfile,
53
+ urlHint,
54
+ promptMessage: 'Which CodePen account/profile would you like to scaffold under?',
55
+ interactive,
56
+ env: options.env,
57
+ homeDir: options.homeDir,
58
+ selectProfile: selectImpl,
59
+ });
60
+ const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
61
+ // 2. Select CodePen Template (or CodePen's built-in default starter)
62
+ let selected;
63
+ if (options.template !== undefined) {
64
+ const tplPen = await resolveTemplatePen(client, options.template);
65
+ selected = {
66
+ kind: 'template',
67
+ pen: tplPen,
68
+ label: `CodePen template: ${tplPen.title || 'Untitled'} (${tplPen.id})`,
69
+ };
70
+ }
71
+ else if (interactive) {
72
+ console.log(fmt.dim('Fetching your CodePen templates…'));
73
+ const templates = await listAccountTemplates(client, 25);
74
+ if (templates.length === 0) {
75
+ console.log(fmt.dim('No custom CodePen templates found — using CodePen’s default 2.0 starter.\n' +
76
+ 'Tip: Mark any Pen as a template on CodePen (or run `cdpn info --template true`) to choose it here.'));
77
+ selected = { kind: 'default-starter', label: 'CodePen default starter' };
78
+ }
79
+ else {
80
+ const choices = [
81
+ {
82
+ value: 'default-starter',
83
+ label: 'CodePen default starter',
84
+ description: 'CodePen’s built-in 2.0 starter files',
85
+ },
86
+ ...templates.map((tpl) => ({
87
+ value: `template:${tpl.id}`,
88
+ label: tpl.title || 'Untitled',
89
+ description: `${tpl.editor} template · updated ${formatDate(tpl.updated_at)}`,
90
+ })),
91
+ ];
92
+ const chosen = await selectImpl('Choose a template:', choices, 0);
93
+ if (chosen === 'default-starter') {
94
+ selected = { kind: 'default-starter', label: 'CodePen default starter' };
95
+ }
96
+ else {
97
+ const tplId = chosen.slice('template:'.length);
98
+ const tplPen = templates.find((t) => t.id === tplId);
99
+ selected = {
100
+ kind: 'template',
101
+ pen: tplPen,
102
+ label: `CodePen template: ${tplPen.title || 'Untitled'} (${tplPen.id})`,
103
+ };
104
+ }
105
+ }
106
+ }
107
+ else {
108
+ selected = { kind: 'default-starter', label: 'CodePen default starter' };
109
+ }
110
+ // 3. Determine Pen title
111
+ const cwdIsEmpty = !(await isDirectoryNonEmpty(cwd));
112
+ const defaultTitle = targetDir && folderDisplay !== '.'
113
+ ? path.basename(targetDir) || 'Untitled'
114
+ : cwdIsEmpty
115
+ ? path.basename(cwd) || 'Untitled'
116
+ : 'Untitled';
117
+ let title = options.title?.trim();
118
+ if (!title) {
119
+ if (interactive) {
120
+ title = (await textImpl('Pen title', defaultTitle)).trim() || defaultTitle;
121
+ }
122
+ else {
123
+ title = defaultTitle;
124
+ }
125
+ }
126
+ // 4. Determine visibility (Public default, Private, Protected, Collaborators)
127
+ const { access, password } = await resolveVisibilityAndPassword({
128
+ rawAccess: options.access,
129
+ rawPassword: options.password,
130
+ interactive,
131
+ prompts: {
132
+ select: selectImpl,
133
+ secret: secretImpl,
134
+ },
135
+ });
136
+ // 5. Resolve & validate target folder (if omitted on CLI) BEFORE creating the Pen on CodePen
137
+ if (!targetDir) {
138
+ const defaultFolder = cwdIsEmpty ? '.' : (slugifyTitle(title) ?? 'new-pen');
139
+ if (interactive) {
140
+ const chosenFolder = (await textImpl('Local folder to scaffold into', defaultFolder)).trim();
141
+ folderDisplay = chosenFolder || defaultFolder;
142
+ }
143
+ else {
144
+ folderDisplay = defaultFolder;
145
+ }
146
+ targetDir = path.resolve(cwd, folderDisplay);
147
+ await assertEmptyTargetDirectory(targetDir, folderDisplay, {
148
+ commandName: 'new',
149
+ nonEmptyHint: NEW_NON_EMPTY_HINT,
150
+ });
151
+ }
152
+ // 6. Fetch template files (if using a custom CodePen Template) and create Pen
153
+ const shouldWait = options.wait !== false;
154
+ let textFiles;
155
+ let binaryFiles = [];
156
+ if (selected.kind === 'template') {
157
+ if (!jsonMode) {
158
+ console.log(fmt.dim(`\nReading template files from ${selected.pen.title || 'Untitled'} (${selected.pen.id})…`));
159
+ }
160
+ const payload = await fetchPenFilesAsUploadPayload(client, selected.pen.id);
161
+ if (payload.textFiles.length > 0 || payload.binaryFiles.length > 0) {
162
+ textFiles = payload.textFiles;
163
+ binaryFiles = payload.binaryFiles;
164
+ }
165
+ }
166
+ if (!jsonMode) {
167
+ console.log(selected.kind === 'default-starter'
168
+ ? '\nCreating new CodePen 2.0 Pen with CodePen default starter files…'
169
+ : `\nCreating new CodePen 2.0 Pen from ${selected.label}…`);
170
+ }
171
+ const created = await client.createPen({
172
+ ...(title ? { title } : {}),
173
+ ...(options.description ? { description: options.description } : {}),
174
+ ...(options.tags && options.tags.length > 0 ? { tags: options.tags } : {}),
175
+ access,
176
+ ...(password ? { password } : {}),
177
+ ...(options.asTemplate ? { template: true } : {}),
178
+ ...(textFiles !== undefined ? { files: textFiles } : {}),
179
+ wait: shouldWait ? 45 : 0,
180
+ }, binaryFiles);
181
+ let finalBuild = created.build ?? null;
182
+ if (finalBuild && shouldWait) {
183
+ finalBuild = await client.settleBuild(finalBuild);
184
+ if (!jsonMode) {
185
+ printBuildSummary(finalBuild);
186
+ }
187
+ }
188
+ await fs.mkdir(targetDir, { recursive: true });
189
+ const finalVersionId = finalBuild?.version_id ?? created.saved_version?.id ?? null;
190
+ const remoteFiles = finalVersionId
191
+ ? (await client.getVersion(finalVersionId)).files ?? (await client.getPenFiles(created.id))
192
+ : await client.getPenFiles(created.id);
193
+ const materialized = await syncRemoteFilesToDisk({
194
+ client,
195
+ rootDir: targetDir,
196
+ remoteFiles,
197
+ pruneRemoved: false,
198
+ });
199
+ const config = {
200
+ url: created.urls.editor,
201
+ pen_id: created.id,
202
+ ...(auth.profile ? { profile: auth.profile } : {}),
203
+ last_synced_version_id: finalVersionId,
204
+ editor: created.editor,
205
+ files: buildSyncedFileMap(remoteFiles, materialized.localSha256ByPath),
206
+ };
207
+ const configPath = await writeProjectConfig(targetDir, config);
208
+ const buildFailed = finalBuild?.status === 'Failed';
209
+ if (buildFailed) {
210
+ process.exitCode = 1;
211
+ }
212
+ if (jsonMode) {
213
+ const code = buildFailed ? 422 : 201;
214
+ const message = buildFailed
215
+ ? `Scaffolded Pen ${created.title || 'Untitled'}, but the initial build failed.`
216
+ : `Scaffolded Pen ${created.title || 'Untitled'} into ${folderDisplay}.`;
217
+ printJsonResponse(code, message, {
218
+ pen: created,
219
+ template: selected.label,
220
+ profile: auth.profile,
221
+ folder: folderDisplay,
222
+ root_dir: targetDir,
223
+ config_path: configPath,
224
+ version_id: finalVersionId,
225
+ build: finalBuild,
226
+ written_paths: materialized.writtenPaths,
227
+ });
228
+ }
229
+ else {
230
+ if (buildFailed) {
231
+ console.log(`\n${fmt.yellow('!')} Scaffolded Pen ${fmt.bold(created.title || 'Untitled')} ${fmt.dim(`(${created.id})`)}, but the initial build failed.`);
232
+ }
233
+ else {
234
+ console.log(`\n${fmt.green('✓')} Scaffolded Pen ${fmt.bold(created.title || 'Untitled')} ${fmt.dim(`(${created.id})`)}`);
235
+ }
236
+ console.log(` Template: ${selected.label}`);
237
+ if (auth.profile) {
238
+ console.log(` Profile: ${fmt.cyan(auth.profile)}`);
239
+ }
240
+ console.log(` Visibility: ${created.access}${created.template ? fmt.dim(' · Template') : ''}`);
241
+ console.log(` Folder: ${fmt.cyan(folderDisplay)}`);
242
+ console.log(` Files: ${materialized.writtenPaths.length} written`);
243
+ console.log(` Editor: ${fmt.cyan(created.urls.editor)}`);
244
+ console.log(` Preview: ${fmt.cyan(created.urls.preview)}`);
245
+ console.log(` Version: ${fmt.dim(shortId(finalVersionId))}`);
246
+ }
247
+ return {
248
+ pen: created,
249
+ versionId: finalVersionId,
250
+ build: finalBuild,
251
+ auth,
252
+ project: {
253
+ rootDir: targetDir,
254
+ configPath,
255
+ config,
256
+ },
257
+ templateLabel: selected.label,
258
+ };
259
+ }
260
+ export function registerNewCommand(program) {
261
+ program
262
+ .command('new [folder]')
263
+ .description('Scaffold a brand-new CodePen 2.0 Pen from a CodePen Template into a new or empty folder')
264
+ .option('-t, --title <title>', 'Title for the new Pen')
265
+ .option('-d, --description <text>', 'Description for the new Pen')
266
+ .option('--tags <tags>', 'Comma-separated tags (up to 5)')
267
+ .option('--access <level>', 'Privacy: Public, Private, Protected, or Collaborators')
268
+ .option('--password <password>', 'Password (min 8 chars; required with --access Protected)')
269
+ .option('--template <id-or-name>', 'Scaffold from one of your CodePen Templates (ID, URL, or title)')
270
+ .option('--as-template', 'Mark the newly created Pen as a Template on CodePen')
271
+ .option('--no-wait', 'Return as soon as files are saved without waiting for the build')
272
+ .option('--json', 'Output scaffolded Pen result as JSON')
273
+ .action(async (folderArg, options, command) => {
274
+ const tags = options.tags
275
+ ? options.tags
276
+ .split(',')
277
+ .map((t) => t.trim())
278
+ .filter(Boolean)
279
+ : undefined;
280
+ await scaffoldNewPen({
281
+ folderArg,
282
+ explicitProfile: getGlobalProfileOption(command),
283
+ title: options.title,
284
+ description: options.description,
285
+ tags,
286
+ access: options.access,
287
+ password: options.password,
288
+ template: options.template,
289
+ asTemplate: options.asTemplate,
290
+ wait: options.wait,
291
+ json: options.json,
292
+ });
293
+ });
294
+ }
@@ -0,0 +1,174 @@
1
+ import { CodePenClient } from '../api/client.js';
2
+ import { requireProject } from '../config/project.js';
3
+ import { openBrowser } from '../utils/browser.js';
4
+ import { fmt } from '../utils/format.js';
5
+ import { isInteractive, promptSelect } from '../utils/prompts.js';
6
+ import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
7
+ function normalizeDeployedHostToUrl(rawHostOrUrl) {
8
+ const trimmed = rawHostOrUrl.trim();
9
+ if (!trimmed)
10
+ return null;
11
+ const candidate = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
12
+ try {
13
+ const parsed = new URL(candidate);
14
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
15
+ return null;
16
+ }
17
+ const httpsUrl = new URL(`https://${parsed.host}${parsed.pathname}`);
18
+ return {
19
+ url: httpsUrl.toString(),
20
+ host: httpsUrl.host.toLowerCase(),
21
+ };
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ }
27
+ /**
28
+ * Builds the deduplicated list of deployed URLs for a Pen:
29
+ * its default CodePen deployment URL first, followed by any configured custom domains.
30
+ */
31
+ export function buildDeployedDomainChoices(deployment, domains = []) {
32
+ const choices = [];
33
+ const seenHosts = new Set();
34
+ const defaultNormalized = normalizeDeployedHostToUrl(deployment.url);
35
+ if (defaultNormalized) {
36
+ seenHosts.add(defaultNormalized.host);
37
+ choices.push({
38
+ url: deployment.url,
39
+ host: defaultNormalized.host,
40
+ isDefault: true,
41
+ description: 'default',
42
+ });
43
+ }
44
+ else {
45
+ choices.push({
46
+ url: deployment.url,
47
+ host: deployment.url.toLowerCase(),
48
+ isDefault: true,
49
+ description: 'default',
50
+ });
51
+ }
52
+ const statusByHost = new Map();
53
+ for (const domain of domains) {
54
+ const normalized = normalizeDeployedHostToUrl(domain.host);
55
+ if (normalized) {
56
+ statusByHost.set(normalized.host, domain.status);
57
+ }
58
+ }
59
+ const candidateHosts = [
60
+ ...deployment.custom_domains,
61
+ ...domains.map((d) => d.host),
62
+ ];
63
+ for (const rawHost of candidateHosts) {
64
+ const normalized = normalizeDeployedHostToUrl(rawHost);
65
+ if (!normalized || seenHosts.has(normalized.host)) {
66
+ continue;
67
+ }
68
+ seenHosts.add(normalized.host);
69
+ const status = statusByHost.get(normalized.host);
70
+ choices.push({
71
+ url: normalized.url,
72
+ host: normalized.host,
73
+ isDefault: false,
74
+ description: status ? `custom domain · ${status}` : 'custom domain',
75
+ });
76
+ }
77
+ return choices;
78
+ }
79
+ export async function openPenCommand(options = {}) {
80
+ const openDeployed = Boolean(options.deploy || options.live);
81
+ if (options.preview && openDeployed) {
82
+ throw new Error('Specify at most one of --preview or --deploy / --live.');
83
+ }
84
+ const cwd = options.cwd ?? process.cwd();
85
+ const interactive = options.interactive ?? isInteractive();
86
+ const selectImpl = options.select ?? promptSelect;
87
+ const openBrowserImpl = options.openBrowserImpl ?? openBrowser;
88
+ const project = await requireProject(cwd);
89
+ const auth = await resolveCommandAuth({
90
+ explicitProfile: options.explicitProfile,
91
+ project,
92
+ interactive,
93
+ env: options.env,
94
+ homeDir: options.homeDir,
95
+ });
96
+ const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
97
+ let pen;
98
+ let domains = [];
99
+ if (openDeployed) {
100
+ [pen, domains] = await Promise.all([
101
+ client.getPen(project.config.pen_id),
102
+ client.listDomains(project.config.pen_id).catch(() => []),
103
+ ]);
104
+ }
105
+ else {
106
+ pen = await client.getPen(project.config.pen_id);
107
+ }
108
+ let targetUrl;
109
+ let label;
110
+ if (openDeployed) {
111
+ if (!pen.deployment) {
112
+ throw new Error('This Pen is not deployed yet. Run `cdpn deploy` first.');
113
+ }
114
+ const choices = buildDeployedDomainChoices(pen.deployment, domains);
115
+ if (choices.length > 1) {
116
+ if (interactive) {
117
+ targetUrl = await selectImpl('This Pen is deployed to multiple domains. Which URL would you like to open?', choices.map((choice) => ({
118
+ value: choice.url,
119
+ label: choice.url,
120
+ description: choice.description,
121
+ })), 0);
122
+ }
123
+ else {
124
+ targetUrl = choices[0].url;
125
+ const otherUrls = choices
126
+ .slice(1)
127
+ .map((c) => c.url)
128
+ .join(', ');
129
+ console.log(fmt.dim(`Deployed to multiple domains; opening default URL (other domains: ${otherUrls}).`));
130
+ }
131
+ }
132
+ else {
133
+ targetUrl = choices[0].url;
134
+ }
135
+ label = 'deployed site';
136
+ }
137
+ else if (options.preview) {
138
+ targetUrl = pen.urls.preview;
139
+ label = 'preview';
140
+ }
141
+ else {
142
+ targetUrl = pen.urls.editor || project.config.url;
143
+ label = 'editor';
144
+ }
145
+ console.log(`Opening ${label}: ${fmt.cyan(targetUrl)}`);
146
+ const launched = await openBrowserImpl(targetUrl);
147
+ if (!launched) {
148
+ console.log(fmt.yellow('Could not launch browser automatically. Open the URL above manually.'));
149
+ }
150
+ return {
151
+ url: targetUrl,
152
+ label,
153
+ launched,
154
+ pen,
155
+ project,
156
+ auth,
157
+ };
158
+ }
159
+ export function registerOpenCommand(program) {
160
+ program
161
+ .command('open')
162
+ .description('Open the Pen in your browser (editor by default, or --preview / --deploy)')
163
+ .option('-p, --preview', 'Open the saved head preview URL')
164
+ .option('-d, --deploy', 'Open the deployed URL (prompts to choose when multiple domains exist)')
165
+ .option('-l, --live', 'Alias for --deploy')
166
+ .action(async (options, command) => {
167
+ await openPenCommand({
168
+ preview: options.preview,
169
+ deploy: options.deploy,
170
+ live: options.live,
171
+ explicitProfile: getGlobalProfileOption(command),
172
+ });
173
+ });
174
+ }