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
@@ -1,174 +1,111 @@
1
1
  import { CodePenClient } from '../api/client.js';
2
- import { buildSyncedFileMap, requireProject, writeProjectConfig } from '../config/project.js';
3
- import { scanLocalFiles } from '../sync/fs.js';
4
- import { buildPenInfoConfigFields } from '../sync/info.js';
5
- import { syncRemoteFilesToDisk } from '../sync/materialize.js';
6
- import { fmt, formatDate, formatTable, shortId } from '../utils/format.js';
7
- import { CliError, printJsonResponse } from '../utils/json.js';
8
- import { isInteractive, promptConfirm, promptSelect } from '../utils/prompts.js';
9
- import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
10
- export function registerVersionCommands(program) {
2
+ import { requireProject } from '../config/project.js';
3
+ import { CliError } from '../errors.js';
4
+ import { fmt, formatDate, formatTable } from '../utils/format.js';
5
+ import { printJsonResponse } from '../utils/json.js';
6
+ import { defaultOutput } from '../utils/output.js';
7
+ import { isInteractive } from '../utils/prompts/index.js';
8
+ import { getGlobalProfileOption, resolveCommandAuth } from '../workflows/auth-context.js';
9
+ import { fetchLinkedPenOrHandleMissing } from '../workflows/missing-pen.js';
10
+ export async function runVersionsCommand(options = {}) {
11
+ const output = options.output ?? defaultOutput;
12
+ const limit = typeof options.limit === 'number'
13
+ ? options.limit
14
+ : Number.parseInt(options.limit ?? '15', 10);
15
+ if (!Number.isInteger(limit) || limit < 1) {
16
+ throw new CliError(400, '--limit must be a positive integer.');
17
+ }
18
+ const interactive = !options.json && (options.interactive ?? isInteractive());
19
+ const project = await requireProject(options.cwd ?? process.cwd());
20
+ const auth = await resolveCommandAuth({
21
+ explicitProfile: options.explicitProfile,
22
+ project,
23
+ interactive,
24
+ persistProfileToProject: !options.json,
25
+ output,
26
+ env: options.env,
27
+ homeDir: options.homeDir,
28
+ selectProfile: options.selectProfile,
29
+ });
30
+ const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
31
+ const penLookup = await fetchLinkedPenOrHandleMissing({
32
+ client,
33
+ project,
34
+ auth,
35
+ commandName: 'versions',
36
+ interactive,
37
+ json: options.json,
38
+ output,
39
+ prompts: options.prompts,
40
+ });
41
+ if (!penLookup.found) {
42
+ return null;
43
+ }
44
+ const pen = penLookup.pen;
45
+ const versionsPage = await client.listVersions(project.config.pen_id, {
46
+ per_page: Math.min(limit, 100),
47
+ sort: 'created',
48
+ direction: 'desc',
49
+ });
50
+ if (pen.editor === 'Classic') {
51
+ if (options.json) {
52
+ printJsonResponse(200, 'Classic Pens do not have saved versions in CodePen API v2.', [], output);
53
+ }
54
+ else {
55
+ output.log(fmt.yellow('Classic Pens do not have saved versions in CodePen API v2.'));
56
+ }
57
+ return { versions: [], isClassic: true };
58
+ }
59
+ const versions = versionsPage.items.slice(0, limit);
60
+ if (options.json) {
61
+ const message = versions.length === 0
62
+ ? 'No saved versions found.'
63
+ : `Found ${versions.length} saved version(s).`;
64
+ printJsonResponse(200, message, versions, output);
65
+ return { versions, isClassic: false };
66
+ }
67
+ if (versions.length === 0) {
68
+ output.log(fmt.dim('No saved versions found.'));
69
+ return { versions, isClassic: false };
70
+ }
71
+ const headId = pen.saved_version?.id ?? null;
72
+ const syncedId = project.config.last_synced_version_id;
73
+ const rows = versions.map((v) => {
74
+ const status = v.build?.status ?? '—';
75
+ const coloredStatus = status === 'Success'
76
+ ? fmt.green(status)
77
+ : status === 'Failed'
78
+ ? fmt.red(status)
79
+ : fmt.yellow(status);
80
+ const markers = [];
81
+ if (v.id === headId)
82
+ markers.push(fmt.cyan('head'));
83
+ if (v.id === syncedId)
84
+ markers.push(fmt.green('local'));
85
+ if (v.deployed)
86
+ markers.push(fmt.magenta('deployed'));
87
+ return [
88
+ v.id,
89
+ coloredStatus,
90
+ v.label ? v.label : fmt.dim('—'),
91
+ markers.length > 0 ? markers.join(', ') : fmt.dim('—'),
92
+ fmt.dim(formatDate(v.created_at)),
93
+ ];
94
+ });
95
+ output.log(formatTable(['Version ID', 'Build', 'Label', 'Markers', 'Created'], rows));
96
+ return { versions, isClassic: false };
97
+ }
98
+ export function registerVersionsCommand(program) {
11
99
  program
12
100
  .command('versions')
13
101
  .description('List saved versions of this Pen')
14
102
  .option('-n, --limit <count>', 'Maximum number of versions to show', '15')
15
103
  .option('--json', 'Output versions as JSON')
16
104
  .action(async (options, command) => {
17
- const limit = Number.parseInt(options.limit ?? '15', 10);
18
- if (Number.isNaN(limit) || limit < 1) {
19
- throw new CliError(400, '--limit must be a positive integer.');
20
- }
21
- const project = await requireProject();
22
- const auth = await resolveCommandAuth({
23
- explicitProfile: getGlobalProfileOption(command),
24
- project,
25
- interactive: options.json ? false : undefined,
26
- persistProfileToProject: !options.json,
27
- });
28
- const client = new CodePenClient({ apiKey: auth.apiKey });
29
- const [pen, versionsPage] = await Promise.all([
30
- client.getPen(project.config.pen_id),
31
- client.listVersions(project.config.pen_id, {
32
- per_page: Math.min(limit, 100),
33
- sort: 'created',
34
- direction: 'desc',
35
- }),
36
- ]);
37
- if (pen.editor === 'Classic') {
38
- if (options.json) {
39
- printJsonResponse(200, 'Classic Pens do not have saved versions in CodePen API v2.', []);
40
- }
41
- else {
42
- console.log(fmt.yellow('Classic Pens do not have saved versions in CodePen API v2.'));
43
- }
44
- return;
45
- }
46
- const versions = versionsPage.items.slice(0, limit);
47
- if (options.json) {
48
- const message = versions.length === 0
49
- ? 'No saved versions found.'
50
- : `Found ${versions.length} saved version(s).`;
51
- printJsonResponse(200, message, versions);
52
- return;
53
- }
54
- if (versions.length === 0) {
55
- console.log(fmt.dim('No saved versions found.'));
56
- return;
57
- }
58
- const headId = pen.saved_version?.id ?? null;
59
- const syncedId = project.config.last_synced_version_id;
60
- const rows = versions.map((v) => {
61
- const status = v.build?.status ?? '—';
62
- const coloredStatus = status === 'Success'
63
- ? fmt.green(status)
64
- : status === 'Failed'
65
- ? fmt.red(status)
66
- : fmt.yellow(status);
67
- const markers = [];
68
- if (v.id === headId)
69
- markers.push(fmt.cyan('head'));
70
- if (v.id === syncedId)
71
- markers.push(fmt.green('local'));
72
- if (v.deployed)
73
- markers.push(fmt.magenta('deployed'));
74
- return [
75
- v.id,
76
- coloredStatus,
77
- v.label ? v.label : fmt.dim('—'),
78
- markers.length > 0 ? markers.join(', ') : fmt.dim('—'),
79
- fmt.dim(formatDate(v.created_at)),
80
- ];
81
- });
82
- console.log(formatTable(['Version ID', 'Build', 'Label', 'Markers', 'Created'], rows));
83
- });
84
- program
85
- .command('rollback [version-id]')
86
- .description('Restore an older saved version to head and sync files locally')
87
- .option('-m, --label <label>', 'Optional label for the restored version (max 80 chars)')
88
- .option('-y, --yes', 'Skip confirmation prompt')
89
- .option('--json', 'Output rollback result as JSON')
90
- .action(async (versionIdArg, options, command) => {
91
- if (options.label && options.label.length > 80) {
92
- throw new CliError(400, 'Version label must be at most 80 characters.');
93
- }
94
- const interactive = isInteractive() && !options.json;
95
- const project = await requireProject();
96
- const auth = await resolveCommandAuth({
105
+ await runVersionsCommand({
106
+ limit: options.limit,
107
+ json: options.json,
97
108
  explicitProfile: getGlobalProfileOption(command),
98
- project,
99
- interactive,
100
- persistProfileToProject: !options.json,
101
109
  });
102
- const client = new CodePenClient({ apiKey: auth.apiKey });
103
- let targetVersionId = versionIdArg?.trim();
104
- if (!targetVersionId) {
105
- if (!interactive) {
106
- throw new CliError(400, 'Missing <version-id>. Run `cdpn versions` to list available version IDs.');
107
- }
108
- const page = await client.listVersions(project.config.pen_id, {
109
- per_page: 10,
110
- sort: 'created',
111
- direction: 'desc',
112
- });
113
- if (page.items.length === 0) {
114
- throw new CliError(404, 'No saved versions available to restore.');
115
- }
116
- targetVersionId = await promptSelect('Select a version to restore to head:', page.items.map((v) => ({
117
- value: v.id,
118
- label: `${shortId(v.id)}${v.label ? ` — ${v.label}` : ''}`,
119
- description: `${v.build?.status ?? 'Unknown'} · ${formatDate(v.created_at)}${v.deployed ? ' · deployed' : ''}`,
120
- })), 0);
121
- }
122
- if (!options.yes) {
123
- if (!interactive) {
124
- throw new CliError(400, 'Refusing to rollback in non-interactive mode without --yes.');
125
- }
126
- const ok = await promptConfirm(`Restore version ${fmt.cyan(targetVersionId)} as the new head and overwrite local files?`, false);
127
- if (!ok) {
128
- console.log('Aborted.');
129
- return;
130
- }
131
- }
132
- if (!options.json) {
133
- console.log(`Restoring version ${fmt.cyan(shortId(targetVersionId))}…`);
134
- }
135
- const updatedPen = await client.restoreVersion(project.config.pen_id, targetVersionId, options.label);
136
- const newHeadId = updatedPen.saved_version?.id ?? null;
137
- const [localFiles, remoteFiles] = await Promise.all([
138
- scanLocalFiles(project.rootDir),
139
- client.getPenFiles(updatedPen.id),
140
- ]);
141
- const materialized = await syncRemoteFilesToDisk({
142
- client,
143
- rootDir: project.rootDir,
144
- remoteFiles,
145
- existingLocalPaths: localFiles.keys(),
146
- pruneRemoved: true,
147
- });
148
- await writeProjectConfig(project.rootDir, {
149
- url: project.config.url || updatedPen.urls.editor,
150
- pen_id: updatedPen.id,
151
- ...(project.config.profile ? { profile: project.config.profile } : {}),
152
- last_synced_version_id: newHeadId,
153
- editor: updatedPen.editor,
154
- ...buildPenInfoConfigFields(updatedPen),
155
- files: buildSyncedFileMap(remoteFiles, materialized.localSha256ByPath),
156
- });
157
- if (options.json) {
158
- printJsonResponse(200, `Restored version ${targetVersionId} to head.`, {
159
- pen: updatedPen,
160
- profile: auth.profile ?? project.config.profile ?? null,
161
- restored_version_id: targetVersionId,
162
- new_version_id: newHeadId,
163
- written_paths: materialized.writtenPaths,
164
- deleted_paths: materialized.deletedPaths,
165
- });
166
- return;
167
- }
168
- console.log(`\n${fmt.green('✓')} Restored version ${fmt.dim(shortId(targetVersionId))} → new head ${fmt.dim(shortId(newHeadId))}`);
169
- console.log(` Synced ${materialized.writtenPaths.length} file(s)` +
170
- (materialized.deletedPaths.length > 0
171
- ? `, removed ${materialized.deletedPaths.length} file(s)`
172
- : ''));
173
110
  });
174
111
  }
package/config/auth.js CHANGED
@@ -1,15 +1,14 @@
1
- import fs from 'node:fs/promises';
2
1
  import os from 'node:os';
3
2
  import path from 'node:path';
4
- import { CliError } from '../utils/json.js';
5
- import { extractCodePenOwnerFromUrl } from './project.js';
6
- export const CODEPEN_API_SETTINGS_URL = 'https://codepen.io/settings/api';
3
+ import { CODEPEN_API_SETTINGS_URL } from '../constants.js';
4
+ import { CliError } from '../errors.js';
5
+ import { extractCodePenOwnerFromUrl } from '../utils/codepen-url.js';
6
+ export { CODEPEN_API_SETTINGS_URL };
7
7
  export const API_KEY_ENV_VAR = 'CODEPEN_API_KEY';
8
8
  export const API_KEY_FILENAME = '.cdpn';
9
9
  export const DEFAULT_PROFILE_NAME = 'default';
10
10
  const FORBIDDEN_PROFILE_NAMES = new Set(['__proto__', 'constructor', 'prototype']);
11
11
  const PROFILE_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
12
- const SINGLE_KEY_FIELDS = ['api_key', 'apiKey', 'key', 'token'];
13
12
  export function getApiKeyFilePath(homeDir) {
14
13
  return path.join(homeDir ?? os.homedir(), API_KEY_FILENAME);
15
14
  }
@@ -56,296 +55,6 @@ export function maskApiKey(apiKey) {
56
55
  }
57
56
  return `••••••••${suffix}`;
58
57
  }
59
- function extractKeyFromValue(value) {
60
- if (typeof value === 'string') {
61
- const trimmed = value.trim();
62
- return trimmed || null;
63
- }
64
- if (value && typeof value === 'object' && !Array.isArray(value)) {
65
- const obj = value;
66
- for (const field of SINGLE_KEY_FIELDS) {
67
- const candidate = obj[field];
68
- if (typeof candidate === 'string' && candidate.trim()) {
69
- return candidate.trim();
70
- }
71
- }
72
- }
73
- return null;
74
- }
75
- function createEmptyStore() {
76
- return {
77
- defaultProfile: null,
78
- profiles: Object.create(null),
79
- };
80
- }
81
- /**
82
- * Parses `~/.cdpn` content into a normalized multi-profile `AuthStore`.
83
- *
84
- * Supported formats:
85
- * - Multi-profile JSON (canonical format written by `cdpn auth login`):
86
- * `{ "default": "bramus", "profiles": { "bramus": "cp_user_...", "username": "cp_team_..." } }`
87
- * - Flat JSON map of profile names to API keys:
88
- * `{ "bramus": "cp_user_...", "username": "cp_team_..." }`
89
- * - Single-key JSON (`{ "api_key": "..." }`, `{ "key": "..." }`, `{ "token": "..." }`)
90
- * - Plain raw key (`cp_user_...`) or env assignment (`export CODEPEN_API_KEY="..."`)
91
- */
92
- export function parseAuthStoreContent(raw) {
93
- const trimmed = raw.trim();
94
- if (!trimmed) {
95
- return createEmptyStore();
96
- }
97
- if (trimmed.startsWith('{')) {
98
- try {
99
- const parsed = JSON.parse(trimmed);
100
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
101
- return createEmptyStore();
102
- }
103
- const record = parsed;
104
- const profiles = Object.create(null);
105
- // Format 1: { "default": "...", "profiles": { "bramus": "cp_user_...", ... } }
106
- if (record.profiles && typeof record.profiles === 'object' && !Array.isArray(record.profiles)) {
107
- for (const [name, entry] of Object.entries(record.profiles)) {
108
- if (!isValidProfileName(name))
109
- continue;
110
- const key = extractKeyFromValue(entry);
111
- if (key) {
112
- profiles[name.trim()] = key;
113
- }
114
- }
115
- const profileNames = Object.keys(profiles);
116
- const rawDefault = typeof record.default === 'string'
117
- ? record.default.trim()
118
- : typeof record.defaultProfile === 'string'
119
- ? record.defaultProfile.trim()
120
- : typeof record.default_profile === 'string'
121
- ? record.default_profile.trim()
122
- : '';
123
- const defaultProfile = rawDefault && Object.hasOwn(profiles, rawDefault)
124
- ? rawDefault
125
- : (profileNames[0] ?? null);
126
- return { defaultProfile, profiles };
127
- }
128
- // Format 2: Single-key JSON ({ "api_key": "..." })
129
- for (const field of SINGLE_KEY_FIELDS) {
130
- const value = record[field];
131
- if (typeof value === 'string' && value.trim()) {
132
- profiles[DEFAULT_PROFILE_NAME] = value.trim();
133
- return { defaultProfile: DEFAULT_PROFILE_NAME, profiles };
134
- }
135
- }
136
- // Format 3: Flat map JSON ({ "bramus": "cp_user_...", "username": "cp_team_..." })
137
- const metaKeys = new Set(['default', 'defaultProfile', 'default_profile']);
138
- for (const [name, entry] of Object.entries(record)) {
139
- if (metaKeys.has(name) || !isValidProfileName(name))
140
- continue;
141
- const key = extractKeyFromValue(entry);
142
- if (key) {
143
- profiles[name.trim()] = key;
144
- }
145
- }
146
- const profileNames = Object.keys(profiles);
147
- if (profileNames.length > 0) {
148
- const rawDefault = typeof record.default === 'string' ? record.default.trim() : '';
149
- const defaultProfile = rawDefault && Object.hasOwn(profiles, rawDefault)
150
- ? rawDefault
151
- : (profileNames[0] ?? null);
152
- return { defaultProfile, profiles };
153
- }
154
- return createEmptyStore();
155
- }
156
- catch {
157
- return createEmptyStore();
158
- }
159
- }
160
- // Format 4: Plain key or env assignment line
161
- for (const line of trimmed.split(/\r?\n/)) {
162
- const cleanLine = line.trim();
163
- if (!cleanLine || cleanLine.startsWith('#'))
164
- continue;
165
- const envMatch = cleanLine.match(/^(?:export\s+)?CODEPEN_API_KEY\s*=\s*(.+)$/);
166
- const key = envMatch?.[1]
167
- ? envMatch[1].trim().replace(/^['"]|['"]$/g, '').trim()
168
- : cleanLine.replace(/^['"]|['"]$/g, '').trim();
169
- if (key) {
170
- const profiles = Object.create(null);
171
- profiles[DEFAULT_PROFILE_NAME] = key;
172
- return { defaultProfile: DEFAULT_PROFILE_NAME, profiles };
173
- }
174
- }
175
- return createEmptyStore();
176
- }
177
- /**
178
- * Extracts the default (or sole) API key from `~/.cdpn` content.
179
- */
180
- export function parseKeyFileContent(raw) {
181
- const store = parseAuthStoreContent(raw);
182
- if (store.defaultProfile && Object.hasOwn(store.profiles, store.defaultProfile)) {
183
- return store.profiles[store.defaultProfile] ?? null;
184
- }
185
- const first = Object.keys(store.profiles)[0];
186
- return first ? (store.profiles[first] ?? null) : null;
187
- }
188
- export async function readAuthStore(options = {}) {
189
- const filePath = getApiKeyFilePath(options.homeDir);
190
- try {
191
- const stat = await fs.lstat(filePath);
192
- if (!stat.isFile()) {
193
- return {
194
- store: createEmptyStore(),
195
- filePath,
196
- exists: false,
197
- insecurePermissions: false,
198
- };
199
- }
200
- const content = await fs.readFile(filePath, 'utf8');
201
- const insecurePermissions = process.platform !== 'win32' && (stat.mode & 0o077) !== 0;
202
- return {
203
- store: parseAuthStoreContent(content),
204
- filePath,
205
- exists: true,
206
- insecurePermissions,
207
- };
208
- }
209
- catch (error) {
210
- if (error.code === 'ENOENT') {
211
- return {
212
- store: createEmptyStore(),
213
- filePath,
214
- exists: false,
215
- insecurePermissions: false,
216
- };
217
- }
218
- throw error;
219
- }
220
- }
221
- export async function readApiKeyFile(options = {}) {
222
- const result = await readAuthStore(options);
223
- const { store } = result;
224
- const activeProfile = store.defaultProfile ?? Object.keys(store.profiles)[0] ?? null;
225
- const apiKey = activeProfile && Object.hasOwn(store.profiles, activeProfile)
226
- ? (store.profiles[activeProfile] ?? null)
227
- : null;
228
- return {
229
- apiKey,
230
- filePath: result.filePath,
231
- exists: result.exists,
232
- insecurePermissions: result.insecurePermissions,
233
- };
234
- }
235
- /**
236
- * Writes the multi-profile store to `~/.cdpn` with strict owner-only (`0o600`) file permissions.
237
- */
238
- export async function writeAuthStore(store, options = {}) {
239
- const filePath = getApiKeyFilePath(options.homeDir);
240
- const sortedProfiles = {};
241
- for (const name of Object.keys(store.profiles).sort((a, b) => a.localeCompare(b))) {
242
- const validName = validateProfileName(name);
243
- const key = store.profiles[name]?.trim();
244
- if (key) {
245
- sortedProfiles[validName] = key;
246
- }
247
- }
248
- const names = Object.keys(sortedProfiles);
249
- const resolvedDefault = store.defaultProfile && Object.hasOwn(sortedProfiles, store.defaultProfile)
250
- ? store.defaultProfile
251
- : (names[0] ?? null);
252
- const payload = {
253
- ...(resolvedDefault ? { default: resolvedDefault } : {}),
254
- profiles: sortedProfiles,
255
- };
256
- await fs.writeFile(filePath, `${JSON.stringify(payload, null, 2)}\n`, {
257
- encoding: 'utf8',
258
- mode: 0o600,
259
- });
260
- if (process.platform !== 'win32') {
261
- await fs.chmod(filePath, 0o600);
262
- }
263
- return filePath;
264
- }
265
- /**
266
- * Adds or updates a named profile inside `~/.cdpn` (creating the file with `0o600` permissions).
267
- */
268
- export async function saveProfileToFile(profileName, apiKey, options = {}) {
269
- const validProfile = validateProfileName(profileName);
270
- const trimmedKey = apiKey.trim();
271
- if (!trimmedKey) {
272
- throw new CliError(400, 'Cannot save an empty API key.');
273
- }
274
- const { store } = await readAuthStore({ homeDir: options.homeDir });
275
- store.profiles[validProfile] = trimmedKey;
276
- const hasValidDefault = Boolean(store.defaultProfile && Object.hasOwn(store.profiles, store.defaultProfile));
277
- if (options.setAsDefault || !hasValidDefault) {
278
- store.defaultProfile = validProfile;
279
- }
280
- const filePath = await writeAuthStore(store, { homeDir: options.homeDir });
281
- return {
282
- filePath,
283
- profile: validProfile,
284
- isDefault: store.defaultProfile === validProfile,
285
- };
286
- }
287
- /**
288
- * Persists an API key to `~/.cdpn` under `options.profile` (default `"default"`) with `0o600` permissions.
289
- */
290
- export async function saveApiKeyToFile(apiKey, options = {}) {
291
- const result = await saveProfileToFile(options.profile ?? DEFAULT_PROFILE_NAME, apiKey, options);
292
- return result.filePath;
293
- }
294
- export async function setDefaultProfile(profileName, options = {}) {
295
- const validProfile = validateProfileName(profileName);
296
- const { store } = await readAuthStore(options);
297
- if (!Object.hasOwn(store.profiles, validProfile)) {
298
- const available = Object.keys(store.profiles);
299
- const hint = available.length > 0
300
- ? ` Available profiles: ${available.join(', ')}.`
301
- : ` Run \`cdpn auth login --profile ${validProfile}\` first.`;
302
- throw new CliError(404, `Profile "${validProfile}" not found in ~/${API_KEY_FILENAME}.${hint}`, {
303
- requested_profile: validProfile,
304
- available_profiles: available,
305
- });
306
- }
307
- store.defaultProfile = validProfile;
308
- return writeAuthStore(store, options);
309
- }
310
- export async function removeProfileFromFile(profileName, options = {}) {
311
- const validProfile = validateProfileName(profileName);
312
- const { store, exists } = await readAuthStore(options);
313
- if (!exists || !Object.hasOwn(store.profiles, validProfile)) {
314
- return {
315
- removed: false,
316
- remainingProfiles: Object.keys(store.profiles),
317
- newDefault: store.defaultProfile,
318
- };
319
- }
320
- delete store.profiles[validProfile];
321
- const remaining = Object.keys(store.profiles).sort((a, b) => a.localeCompare(b));
322
- if (remaining.length === 0) {
323
- await removeApiKeyFile(options);
324
- return { removed: true, remainingProfiles: [], newDefault: null };
325
- }
326
- if (store.defaultProfile === validProfile) {
327
- store.defaultProfile = remaining[0] ?? null;
328
- }
329
- await writeAuthStore(store, options);
330
- return {
331
- removed: true,
332
- remainingProfiles: remaining,
333
- newDefault: store.defaultProfile,
334
- };
335
- }
336
- export async function removeApiKeyFile(options = {}) {
337
- const filePath = getApiKeyFilePath(options.homeDir);
338
- try {
339
- await fs.unlink(filePath);
340
- return true;
341
- }
342
- catch (error) {
343
- if (error.code === 'ENOENT') {
344
- return false;
345
- }
346
- throw error;
347
- }
348
- }
349
58
  /**
350
59
  * Matches a CodePen URL's owner segment (user or team slug) against stored profile names.
351
60
  */
@@ -361,85 +70,6 @@ export function findMatchingProfile(availableProfiles, urlHint) {
361
70
  const lower = owner.toLowerCase();
362
71
  return availableProfiles.find((p) => p.toLowerCase() === lower) ?? null;
363
72
  }
364
- /**
365
- * Resolves CodePen API credentials non-interactively.
366
- *
367
- * Precedence:
368
- * 1. Explicit `options.profile` from `~/.cdpn` (returns `null` if that profile does not exist).
369
- * 2. `CODEPEN_API_KEY` environment variable.
370
- * 3. Default (or sole) profile in `~/.cdpn`.
371
- */
372
- export async function resolveAuth(options = {}) {
373
- const env = options.env ?? process.env;
374
- const envKey = env[API_KEY_ENV_VAR]?.trim() || '';
375
- const { store, filePath, insecurePermissions } = await readAuthStore({
376
- homeDir: options.homeDir,
377
- });
378
- const availableProfiles = Object.keys(store.profiles).sort((a, b) => a.localeCompare(b));
379
- const hasEnv = Boolean(envKey);
380
- const hasFile = availableProfiles.length > 0;
381
- if (options.profile !== undefined) {
382
- const requestedProfile = validateProfileName(options.profile);
383
- if (Object.hasOwn(store.profiles, requestedProfile)) {
384
- return {
385
- apiKey: store.profiles[requestedProfile],
386
- source: 'file',
387
- profile: requestedProfile,
388
- filePath,
389
- hasEnv,
390
- hasFile,
391
- availableProfiles,
392
- defaultProfile: store.defaultProfile,
393
- insecureFilePermissions: insecurePermissions,
394
- };
395
- }
396
- return null;
397
- }
398
- if (hasEnv) {
399
- return {
400
- apiKey: envKey,
401
- source: 'env',
402
- profile: null,
403
- filePath,
404
- hasEnv,
405
- hasFile,
406
- availableProfiles,
407
- defaultProfile: store.defaultProfile,
408
- insecureFilePermissions: insecurePermissions,
409
- };
410
- }
411
- if (hasFile) {
412
- const chosen = store.defaultProfile && Object.hasOwn(store.profiles, store.defaultProfile)
413
- ? store.defaultProfile
414
- : availableProfiles[0];
415
- return {
416
- apiKey: store.profiles[chosen],
417
- source: 'file',
418
- profile: chosen,
419
- filePath,
420
- hasEnv,
421
- hasFile,
422
- availableProfiles,
423
- defaultProfile: store.defaultProfile,
424
- insecureFilePermissions: insecurePermissions,
425
- };
426
- }
427
- return null;
428
- }
429
- export async function requireAuth(options = {}) {
430
- const auth = await resolveAuth(options);
431
- if (!auth) {
432
- if (options.profile) {
433
- const { store } = await readAuthStore({ homeDir: options.homeDir });
434
- const available = Object.keys(store.profiles).sort((a, b) => a.localeCompare(b));
435
- const availableNote = available.length > 0 ? ` Available profiles: ${available.join(', ')}.` : '';
436
- throw new CliError(404, `Profile "${options.profile}" not found in ~/${API_KEY_FILENAME}.${availableNote}\n` +
437
- `Run \`cdpn auth login --profile ${options.profile}\` to add it.`, { requested_profile: options.profile, available_profiles: available });
438
- }
439
- throw new CliError(401, `No CodePen API key found. Run \`cdpn auth login\` or set the ${API_KEY_ENV_VAR} environment variable.`);
440
- }
441
- return auth;
442
- }
443
73
  export function getShellExportSnippets(apiKey, shellPath = process.env.SHELL ?? '') {
444
74
  const escapedPosix = apiKey.replaceAll("'", "'\\''");
445
75
  const all = [