codepen-commander 0.0.0-stage → 1.0.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bramus Van Damme
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,180 @@
1
- # Temporary Holding Version
1
+ # `cdpn` — CodePen Commander
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Sync local folders with [CodePen 2.0](https://codepen.io) Pens using the [CodePen API v2](https://blog.codepen.io/docs/api/api-v2/).
4
+
5
+ - Clone Pens (text & binary files) to a local folder and pull remote updates
6
+ - Track diffs between local files and the online saved head
7
+ - Push additions, edits, and deletions as a single version — waiting for builds and syncing compiler patches back locally
8
+ - Deploy, undeploy, manage custom domains, browse versions & roll back, inspect/edit metadata & settings
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ npm install -g codepen-commander
14
+ ```
15
+
16
+ Requires Node.js 20 or newer.
17
+
18
+ ## Authentication & Profiles
19
+
20
+ Generate personal (`cp_user_…`) and/or team (`cp_team_…`) API keys at [codepen.io/settings/api](https://codepen.io/settings/api), or run:
21
+
22
+ ```bash
23
+ cdpn auth login # Add a profile (e.g. bramus)
24
+ cdpn auth login username # Add another profile (e.g. a team account)
25
+ ```
26
+
27
+ `cdpn` stores named profiles in **`~/.cdpn`** (with strict `0600` owner-only permissions):
28
+
29
+ ```json
30
+ {
31
+ "default": "bramus",
32
+ "profiles": {
33
+ "bramus": "cp_user_...",
34
+ "username": "cp_team_..."
35
+ }
36
+ }
37
+ ```
38
+
39
+ When running commands, `cdpn` resolves credentials in this order:
40
+
41
+ 1. An explicit `--profile <name>` flag (e.g. `cdpn list --profile username`)
42
+ 2. The `CODEPEN_API_KEY` environment variable (useful in CI)
43
+ 3. The `"profile"` stored in the Pen folder’s `.cdpn.json`
44
+ 4. Your sole profile in `~/.cdpn`, a stored profile matching the Pen owner (automatically selected by `cdpn clone <url>`), or—when multiple profiles exist and none matches—an interactive prompt
45
+
46
+ Check your authentication status or list profiles at any time:
47
+
48
+ ```bash
49
+ cdpn auth status
50
+ cdpn auth list
51
+ ```
52
+
53
+ ## Quick Start
54
+
55
+ ```bash
56
+ # 1. Authenticate (add one or more profiles)
57
+ cdpn auth login bramus
58
+ cdpn auth login username
59
+
60
+ # 2. Clone an existing Pen into a local folder (automatically uses "username" when stored)
61
+ cdpn clone https://codepen.io/username/pen/abcde my-pen
62
+ cd my-pen
63
+
64
+ # 3. Edit files locally, then check differences (automatically uses "username")
65
+ cdpn status
66
+
67
+ # 4. Push local changes (additions, edits, and deletions) to CodePen
68
+ cdpn push -m "Tweak layout and styles"
69
+
70
+ # 5. Push and deploy live to CodePen Hosting
71
+ cdpn deploy
72
+ ```
73
+
74
+ ## Sync Metadata (`.cdpn.json`)
75
+
76
+ Every synced Pen folder contains a `.cdpn.json` file at its root:
77
+
78
+ ```json
79
+ {
80
+ "url": "https://codepen.io/username/pen/abcde",
81
+ "pen_id": "01a08738-73f0-7847-b6a8-5789d289c158",
82
+ "profile": "username",
83
+ "last_synced_version_id": "01a08738-73f0-7848-b8bf-e8e7e91b1ae2"
84
+ }
85
+ ```
86
+
87
+ > **Why `.cdpn.json` instead of `.codepen`?**
88
+ > CodePen 2.0 Pens already contain a `.codepen/` directory (housing `.codepen/pen.config.json`). Using `.cdpn.json` avoids filesystem collisions while allowing `.codepen/pen.config.json` to sync cleanly with CodePen.
89
+
90
+ You can also add an optional `.cdpnignore` file in a Pen folder to exclude extra local files from syncing (`.cdpn.json`, `.cdpnignore`, `.git`, `node_modules`, and `.DS_Store` are ignored automatically).
91
+
92
+ ## Scaffolding & Templates (`cdpn new`)
93
+
94
+ `cdpn new [folder]` is dedicated to scaffolding a brand-new CodePen 2.0 Pen from a CodePen Template into a new or empty local folder (for pushing an existing local demo folder, run `cdpn push` inside that folder instead).
95
+
96
+ CodePen stores your reusable scaffolds as **Templates** (any Pen marked with `template: true` on CodePen or via `cdpn info --template true` / `cdpn new --as-template`), alongside CodePen's built-in 2.0 starter. When you run `cdpn new` interactively, it fetches your account's Templates from CodePen and lets you pick one (or use CodePen's default starter):
97
+
98
+ ```bash
99
+ cdpn new my-demo # Interactive picker (your CodePen Templates + CodePen default starter)
100
+ cdpn new my-demo --template "CSS Demo Base" # Scaffold from a CodePen Template by title, ID, or URL
101
+ cdpn new my-starter --as-template # Create a new reusable Template on CodePen
102
+ ```
103
+
104
+ To fork one of your own 2.0 Pens into a new local folder, use `cdpn fork`:
105
+
106
+ ```bash
107
+ cdpn fork https://codepen.io/username/pen/abcde # Prompts for target folder (or auto-generates one)
108
+ cdpn fork https://codepen.io/username/pen/abcde my-fork # Forks directly into ./my-fork
109
+ ```
110
+
111
+ > **Note:** CodePen API v2 keys can only access and fork Pens owned by the key's account (other users' Pens return `404`, even when public). When you run `cdpn fork` or `cdpn clone` on another user's Pen URL interactively, `cdpn` offers to open the Pen in your browser so you can fork it on `codepen.io` and paste your forked URL back to clone immediately.
112
+
113
+ ## Commands
114
+
115
+ All commands accept the global `--profile <name>` flag to override the active profile. Every data/state command also accepts `--json` (everything except interactive-only `cdpn auth login` and browser-opening `cdpn open`).
116
+
117
+ | Command | Description |
118
+ | --- | --- |
119
+ | `cdpn auth status [--offline] [--json]` | Show loaded API keys/profiles (`CODEPEN_API_KEY` & `~/.cdpn`) and verify them |
120
+ | `cdpn auth login [profile] [--default] [--no-open]` | Open CodePen API settings, verify key, and save a profile to `~/.cdpn` or print shell export lines |
121
+ | `cdpn auth list [--json]` | List stored profiles in `~/.cdpn` (alias: `cdpn auth ls`) |
122
+ | `cdpn auth default [profile] [--json]` | Set the default profile in `~/.cdpn` |
123
+ | `cdpn auth logout [profile] [--all] [--json]` | Remove a specific profile or delete `~/.cdpn` completely |
124
+ | `cdpn new [folder] [--template <id\|url\|title>] [--as-template] [--json]` | Scaffold a brand-new 2.0 Pen from a CodePen Template (or CodePen default starter) into a new or empty folder |
125
+ | `cdpn fork <url> [folder] [--title ...] [--access ...] [--json]` | Fork one of your own 2.0 Pens into a local folder (for other users' Pens, offers to open in browser to fork and clone back) |
126
+ | `cdpn clone <url> [folder] [--force] [--json]` | Clone a CodePen Pen into a local folder (auto-matches stored profile by URL owner; offers browser fork-and-clone fallback for unowned Pens) |
127
+ | `cdpn pull [--force] [--json]` | Pull latest remote changes into an existing cloned folder (requires `.cdpn.json`) |
128
+ | `cdpn status [--json]` | Show active profile, file diffs (added/modified/deleted), remote head, build & deployment status |
129
+ | `cdpn push [-m <label>] [--force] [--dry-run] [--no-wait] [--json]` | Push local changes (text & binary + deletions), or push an unlinked local demo folder as a new Pen (checks `index.html`, asks account, title, and visibility) |
130
+ | `cdpn deploy [--no-push] [--version <id>] [--force] [--json]` | Push local changes (creating a Pen first if unlinked) and deploy to CodePen Hosting |
131
+ | `cdpn undeploy [--yes] [--json]` | Take down the live deployment (Pen & versions remain intact) |
132
+ | `cdpn domains [list] [--json]` | Show the default deployed URL, custom domains, verification status, and required DNS records |
133
+ | `cdpn domains add <host> [--json]` | Attach a custom domain to the Pen's deployment |
134
+ | `cdpn domains delete <host> [--yes] [--json]` | Delete a custom domain (aliases: `cdpn domains del`, `cdpn domains rm`) |
135
+ | `cdpn open [--preview \| --deploy]` | Open the Pen's editor, preview, or deployed URL in your browser (prompts to choose when multiple domains exist; `--live` is an alias for `--deploy`) |
136
+ | `cdpn list [--search ...] [--templates] [--deployed] [--editor V2\|Classic] [--json]` | List and search your Pens (or Templates) on CodePen (alias: `cdpn ls`) |
137
+ | `cdpn versions [--limit <n>] [--json]` | List saved versions with build status, labels, and markers (`head`, `local`, `deployed`) |
138
+ | `cdpn rollback [version-id] [-m <label>] [--yes] [--json]` | Restore an older saved version to head and sync files locally |
139
+ | `cdpn privacy [level] [--password <pw>] [--show] [--json]` | View or update Pen privacy (`Public`, `Private`, `Protected`, `Collaborators`; alias: `cdpn access`; requires `.cdpn.json` in current folder) |
140
+ | `cdpn delete [--yes] [--json]` | Delete the online Pen on CodePen (moves to Deleted Items for 3 days) and remove `.cdpn.json` while keeping local files untouched (aliases: `cdpn del`, `cdpn rm`) |
141
+ | `cdpn info [--title ...] [--tags ...] [--access ...] [--template true\|false] [--json]` | View or update Pen metadata |
142
+ | `cdpn settings [--auto-deploy ...] [--indent-with ...] [--json]` | View or update Pen editor & deployment settings |
143
+
144
+ ## JSON Output (`--json`)
145
+
146
+ When `--json` is passed, `cdpn` runs non-interactively, suppresses human-readable progress output, and prints a single JSON envelope to `stdout` (even on errors):
147
+
148
+ ```json
149
+ {
150
+ "status": {
151
+ "code": 200,
152
+ "message": "Up to date with CodePen (3 file(s))."
153
+ },
154
+ "contents": {
155
+ "...": "raw command data"
156
+ }
157
+ }
158
+ ```
159
+
160
+ - `status.code` uses HTTP-style status codes (`200` OK, `201` Created, `400` Bad Request / missing required flag such as `--yes`, `401` Unauthorized, `403` Forbidden, `404` Not Found, `409` Conflict, `422` Build Failed, `429` Rate Limited, `500` Internal Error).
161
+ - `status.message` is a plain, human-readable summary string (ANSI-free).
162
+ - `contents` holds the structured payload for tools to consume (or error metadata / `null` on failure).
163
+ - Non-`2xx` outcomes exit with a non-zero exit code (`1`).
164
+
165
+ ## Development & Publishing
166
+
167
+ Source files live in `./src` and compile into `./dist`. Only the contents of `./dist` are published to npm (with paths in `dist/package.json` rewritten cleanly to package root):
168
+
169
+ ```bash
170
+ npm run build # Compiles src/ -> dist/ and prepares dist/package.json, README.md, LICENSE
171
+ npm test # Builds and runs the full test suite
172
+ npm run typecheck # Runs strict TypeScript checks across src/ and test/
173
+ npm run pub # Builds and publishes ./dist to npm
174
+ ```
175
+
176
+ Running `npm publish` directly from the repository root is intentionally blocked via `prepublishOnly` so you never accidentally publish `./src` or a nested `./dist` folder.
177
+
178
+ ## License
179
+
180
+ MIT
package/api/client.js ADDED
@@ -0,0 +1,364 @@
1
+ import path from 'node:path';
2
+ import { extractPenIdFromUrl } from '../config/project.js';
3
+ import { CodePenApiError } from './errors.js';
4
+ export const DEFAULT_API_BASE_URL = 'https://api.codepen.io';
5
+ /** Conservative threshold (12 MB) under CodePen's 16 MB JSON body limit before switching to multipart. */
6
+ const JSON_BODY_LIMIT_BYTES = 12 * 1024 * 1024;
7
+ /** CodePen's documented max multipart request size (120 MB). */
8
+ export const MAX_MULTIPART_BYTES = 120 * 1024 * 1024;
9
+ /** CodePen's documented max single file size (30 MB). */
10
+ export const MAX_FILE_BYTES = 30 * 1024 * 1024;
11
+ function isLocalLoopbackHost(hostname) {
12
+ return hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '[::1]';
13
+ }
14
+ function validateApiBaseUrl(rawUrl) {
15
+ let parsed;
16
+ try {
17
+ parsed = new URL(rawUrl);
18
+ }
19
+ catch {
20
+ throw new Error(`Invalid API base URL: ${rawUrl}`);
21
+ }
22
+ if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && isLocalLoopbackHost(parsed.hostname))) {
23
+ throw new Error(`Refusing non-HTTPS API base URL: ${rawUrl}`);
24
+ }
25
+ return parsed;
26
+ }
27
+ export function parseLinkHeader(header) {
28
+ const links = {};
29
+ if (!header)
30
+ return links;
31
+ for (const part of header.split(',')) {
32
+ const match = part.trim().match(/^<([^>]+)>;\s*rel="(next|prev|first|last)"$/);
33
+ if (match?.[1] && match[2]) {
34
+ const rel = match[2];
35
+ links[rel] = match[1];
36
+ }
37
+ }
38
+ return links;
39
+ }
40
+ export function encodePenId(penIdOrUrl) {
41
+ const trimmed = penIdOrUrl.trim();
42
+ const extracted = extractPenIdFromUrl(trimmed);
43
+ return encodeURIComponent(extracted ?? trimmed);
44
+ }
45
+ export class CodePenClient {
46
+ apiKey;
47
+ baseUrl;
48
+ fetchImpl;
49
+ constructor(options) {
50
+ if (!options.apiKey || !options.apiKey.trim()) {
51
+ throw new Error('A CodePen API key is required.');
52
+ }
53
+ this.apiKey = options.apiKey.trim();
54
+ this.baseUrl = validateApiBaseUrl(options.baseUrl ?? DEFAULT_API_BASE_URL);
55
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
56
+ }
57
+ buildUrl(endpointPath, query) {
58
+ const url = new URL(endpointPath, this.baseUrl);
59
+ if (query) {
60
+ for (const [key, value] of Object.entries(query)) {
61
+ if (value !== undefined) {
62
+ url.searchParams.set(key, String(value));
63
+ }
64
+ }
65
+ }
66
+ return url.toString();
67
+ }
68
+ async requestRaw(method, endpointOrUrl, options = {}) {
69
+ let targetUrl;
70
+ if (endpointOrUrl.startsWith('http://') || endpointOrUrl.startsWith('https://')) {
71
+ const parsed = new URL(endpointOrUrl);
72
+ if (parsed.origin !== this.baseUrl.origin) {
73
+ throw new Error(`Refusing to send API credentials to unexpected origin: ${parsed.origin}`);
74
+ }
75
+ targetUrl = parsed.toString();
76
+ }
77
+ else {
78
+ targetUrl = this.buildUrl(endpointOrUrl, options.query);
79
+ }
80
+ const headers = {
81
+ Authorization: `Bearer ${this.apiKey}`,
82
+ Accept: 'application/json',
83
+ };
84
+ let body;
85
+ if (options.formData !== undefined) {
86
+ body = options.formData;
87
+ }
88
+ else if (options.json !== undefined) {
89
+ headers['Content-Type'] = 'application/json';
90
+ body = JSON.stringify(options.json);
91
+ }
92
+ const response = await this.fetchImpl(targetUrl, {
93
+ method,
94
+ headers,
95
+ body,
96
+ });
97
+ if (!response.ok) {
98
+ let parsedBody = {};
99
+ try {
100
+ const text = await response.text();
101
+ if (text) {
102
+ parsedBody = JSON.parse(text);
103
+ }
104
+ }
105
+ catch {
106
+ // Non-JSON error body; keep fallback status message
107
+ }
108
+ throw new CodePenApiError(response.status, parsedBody);
109
+ }
110
+ return response;
111
+ }
112
+ async requestJson(method, endpointOrUrl, options = {}) {
113
+ const response = await this.requestRaw(method, endpointOrUrl, options);
114
+ return (await response.json());
115
+ }
116
+ /**
117
+ * Verifies that the configured API key is accepted by CodePen API v2.
118
+ * CodePen API v2 does not expose a `/me` endpoint; listing 1 Pen validates auth
119
+ * and optionally lets callers inspect a sample Pen URL to suggest a profile name.
120
+ */
121
+ async verifyAuth() {
122
+ const response = await this.requestRaw('GET', '/v2/pens', { query: { per_page: 1 } });
123
+ try {
124
+ const items = (await response.json());
125
+ if (Array.isArray(items) && items.length > 0 && items[0] && typeof items[0] === 'object') {
126
+ return items[0];
127
+ }
128
+ }
129
+ catch {
130
+ // Ignore empty or non-JSON bodies; 2xx status already verified the key
131
+ }
132
+ return null;
133
+ }
134
+ async listPens(params = {}) {
135
+ const response = await this.requestRaw('GET', '/v2/pens', {
136
+ query: {
137
+ page: params.page,
138
+ per_page: params.per_page,
139
+ sort: params.sort,
140
+ direction: params.direction,
141
+ access: params.access,
142
+ deployed: params.deployed,
143
+ template: params.template,
144
+ forks: params.forks,
145
+ editor: params.editor,
146
+ tags: params.tags,
147
+ search_term: params.search_term,
148
+ untitled: params.untitled,
149
+ block: params.block,
150
+ cursor: params.cursor,
151
+ },
152
+ });
153
+ const items = (await response.json());
154
+ const links = parseLinkHeader(response.headers.get('link'));
155
+ return { items, links };
156
+ }
157
+ async listPensPageByUrl(nextUrl) {
158
+ const response = await this.requestRaw('GET', nextUrl);
159
+ const items = (await response.json());
160
+ const links = parseLinkHeader(response.headers.get('link'));
161
+ return { items, links };
162
+ }
163
+ async getPen(penIdOrUrl) {
164
+ return this.requestJson('GET', `/v2/pens/${encodePenId(penIdOrUrl)}`);
165
+ }
166
+ async createPen(payload = {}, binaryFiles = []) {
167
+ const jsonString = JSON.stringify(payload);
168
+ const useMultipart = binaryFiles.length > 0 || Buffer.byteLength(jsonString, 'utf8') > JSON_BODY_LIMIT_BYTES;
169
+ if (!useMultipart) {
170
+ return this.requestJson('POST', '/v2/pens', { json: payload });
171
+ }
172
+ const form = new FormData();
173
+ const { wait, ...penBody } = payload;
174
+ form.append('pen', JSON.stringify(penBody));
175
+ let totalBytes = Buffer.byteLength(jsonString, 'utf8');
176
+ for (const part of binaryFiles) {
177
+ if (part.content.length === 0) {
178
+ throw new Error(`Empty binary upload part is not allowed for ${part.path}; send empty files as text.`);
179
+ }
180
+ if (part.content.length > MAX_FILE_BYTES) {
181
+ throw new Error(`File ${part.path} exceeds CodePen's 30 MB per-file limit.`);
182
+ }
183
+ totalBytes += part.content.length;
184
+ if (totalBytes > MAX_MULTIPART_BYTES) {
185
+ throw new Error(`Upload exceeds CodePen's 120 MB multipart request limit.`);
186
+ }
187
+ const normalizedPath = part.path.startsWith('/') ? part.path : `/${part.path}`;
188
+ const filename = path.posix.basename(normalizedPath);
189
+ form.append(normalizedPath, new Blob([new Uint8Array(part.content)], { type: 'application/octet-stream' }), filename);
190
+ }
191
+ return this.requestJson('POST', '/v2/pens', {
192
+ query: wait !== undefined ? { wait } : undefined,
193
+ formData: form,
194
+ });
195
+ }
196
+ async forkPen(penIdOrUrl, payload = {}) {
197
+ return this.requestJson('POST', `/v2/pens/${encodePenId(penIdOrUrl)}/fork`, {
198
+ json: payload,
199
+ });
200
+ }
201
+ async updatePen(penId, payload) {
202
+ return this.requestJson('PATCH', `/v2/pens/${encodePenId(penId)}`, { json: payload });
203
+ }
204
+ async deletePen(penId) {
205
+ await this.requestRaw('DELETE', `/v2/pens/${encodePenId(penId)}`);
206
+ }
207
+ async updateSettings(penId, payload) {
208
+ return this.requestJson('PATCH', `/v2/pens/${encodePenId(penId)}/settings`, {
209
+ json: payload,
210
+ });
211
+ }
212
+ async getPenFiles(penId) {
213
+ return this.requestJson('GET', `/v2/pens/${encodePenId(penId)}/files`);
214
+ }
215
+ async writePenFiles(penId, request, binaryFiles = []) {
216
+ const jsonString = JSON.stringify(request);
217
+ const useMultipart = binaryFiles.length > 0 || Buffer.byteLength(jsonString, 'utf8') > JSON_BODY_LIMIT_BYTES;
218
+ if (!useMultipart) {
219
+ return this.requestJson('PUT', `/v2/pens/${encodePenId(penId)}/files`, {
220
+ json: request,
221
+ });
222
+ }
223
+ const form = new FormData();
224
+ const { wait, dry_run, expected_version_id, ...changesRest } = request;
225
+ const changesBody = {
226
+ ...changesRest,
227
+ ...(expected_version_id ? { expected_version_id } : {}),
228
+ };
229
+ form.append('changes', JSON.stringify(changesBody));
230
+ if (expected_version_id) {
231
+ form.append('expected_version_id', expected_version_id);
232
+ }
233
+ let totalBytes = Buffer.byteLength(JSON.stringify(changesBody), 'utf8');
234
+ for (const part of binaryFiles) {
235
+ if (part.content.length === 0) {
236
+ throw new Error(`Empty binary upload part is not allowed for ${part.path}; send empty files as text.`);
237
+ }
238
+ if (part.content.length > MAX_FILE_BYTES) {
239
+ throw new Error(`File ${part.path} exceeds CodePen's 30 MB per-file limit.`);
240
+ }
241
+ totalBytes += part.content.length;
242
+ if (totalBytes > MAX_MULTIPART_BYTES) {
243
+ throw new Error(`Upload exceeds CodePen's 120 MB multipart request limit.`);
244
+ }
245
+ const normalizedPath = part.path.startsWith('/') ? part.path : `/${part.path}`;
246
+ const filename = path.posix.basename(normalizedPath);
247
+ form.append(normalizedPath, new Blob([new Uint8Array(part.content)], { type: 'application/octet-stream' }), filename);
248
+ }
249
+ return this.requestJson('PUT', `/v2/pens/${encodePenId(penId)}/files`, {
250
+ query: {
251
+ wait,
252
+ dry_run,
253
+ },
254
+ formData: form,
255
+ });
256
+ }
257
+ /**
258
+ * Downloads raw file bytes from a signed CodePen `download_url`.
259
+ * Intentionally sends NO Authorization header (signed URLs are self-authenticating).
260
+ */
261
+ async downloadFile(downloadUrl) {
262
+ let parsed;
263
+ try {
264
+ parsed = new URL(downloadUrl);
265
+ }
266
+ catch {
267
+ throw new Error(`Invalid download URL: ${downloadUrl}`);
268
+ }
269
+ const isAllowedLocalMock = this.baseUrl.protocol === 'http:' &&
270
+ isLocalLoopbackHost(this.baseUrl.hostname) &&
271
+ parsed.origin === this.baseUrl.origin;
272
+ if (parsed.protocol !== 'https:' && !isAllowedLocalMock) {
273
+ throw new Error(`Refusing to download file over insecure protocol: ${parsed.protocol}`);
274
+ }
275
+ const response = await this.fetchImpl(parsed.toString(), {
276
+ method: 'GET',
277
+ });
278
+ if (!response.ok) {
279
+ let parsedBody = {};
280
+ try {
281
+ const text = await response.text();
282
+ if (text) {
283
+ parsedBody = JSON.parse(text);
284
+ }
285
+ }
286
+ catch {
287
+ // Ignore non-JSON error
288
+ }
289
+ throw new CodePenApiError(response.status, parsedBody);
290
+ }
291
+ const arrayBuffer = await response.arrayBuffer();
292
+ return Buffer.from(arrayBuffer);
293
+ }
294
+ async getVersion(versionId) {
295
+ return this.requestJson('GET', `/v2/versions/${encodeURIComponent(versionId)}`);
296
+ }
297
+ async listVersions(penId, params = {}) {
298
+ const response = await this.requestRaw('GET', `/v2/pens/${encodePenId(penId)}/versions`, {
299
+ query: {
300
+ page: params.page,
301
+ per_page: params.per_page,
302
+ sort: params.sort,
303
+ direction: params.direction,
304
+ },
305
+ });
306
+ const items = (await response.json());
307
+ const links = parseLinkHeader(response.headers.get('link'));
308
+ return { items, links };
309
+ }
310
+ async restoreVersion(penId, versionId, label) {
311
+ return this.requestJson('POST', `/v2/pens/${encodePenId(penId)}/versions/${encodeURIComponent(versionId)}/restore`, {
312
+ query: label ? { label } : undefined,
313
+ });
314
+ }
315
+ async getBuild(buildId, wait) {
316
+ return this.requestJson('GET', `/v2/builds/${encodeURIComponent(buildId)}`, {
317
+ query: wait !== undefined ? { wait } : undefined,
318
+ });
319
+ }
320
+ /**
321
+ * Polls a CodePen build until it settles (`Success`, `Failed`, or `Canceled` with no `next_id`).
322
+ * Follows `next_id` automatically when the compiler applies patches and queues a follow-up build.
323
+ */
324
+ async settleBuild(initialBuild, options = {}) {
325
+ const pollIntervalMs = options.pollIntervalMs ?? 2000;
326
+ const maxPollTimeMs = options.maxPollTimeMs ?? 5 * 60 * 1000;
327
+ const started = Date.now();
328
+ let current = initialBuild;
329
+ options.onUpdate?.(current);
330
+ for (;;) {
331
+ const isRunning = current.status === 'Queued' || current.status === 'Running';
332
+ const nextId = current.status === 'Canceled' ? current.next_id : null;
333
+ if (!isRunning && !nextId) {
334
+ return current;
335
+ }
336
+ if (Date.now() - started > maxPollTimeMs) {
337
+ throw new Error(`Timed out waiting for build ${current.id} to settle (last status: ${current.status}).`);
338
+ }
339
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
340
+ const targetBuildId = nextId ?? current.id;
341
+ current = await this.getBuild(targetBuildId);
342
+ options.onUpdate?.(current);
343
+ }
344
+ }
345
+ async deployPen(penId, versionId) {
346
+ return this.requestJson('PUT', `/v2/pens/${encodePenId(penId)}/deployment`, {
347
+ json: versionId ? { version_id: versionId } : {},
348
+ });
349
+ }
350
+ async undeployPen(penId) {
351
+ await this.requestRaw('DELETE', `/v2/pens/${encodePenId(penId)}/deployment`);
352
+ }
353
+ async listDomains(penId) {
354
+ return this.requestJson('GET', `/v2/pens/${encodePenId(penId)}/domains`);
355
+ }
356
+ async addDomain(penId, host) {
357
+ return this.requestJson('POST', `/v2/pens/${encodePenId(penId)}/domains`, {
358
+ json: { host },
359
+ });
360
+ }
361
+ async removeDomain(penId, host) {
362
+ return this.requestJson('DELETE', `/v2/pens/${encodePenId(penId)}/domains/${encodeURIComponent(host)}`);
363
+ }
364
+ }
package/api/errors.js ADDED
@@ -0,0 +1,49 @@
1
+ export class CodePenApiError extends Error {
2
+ status;
3
+ code;
4
+ expectedVersionId;
5
+ currentVersionId;
6
+ buildId;
7
+ field;
8
+ details;
9
+ limit;
10
+ retryAfterSeconds;
11
+ resetAt;
12
+ constructor(status, body) {
13
+ const message = body.message || body.error || `CodePen API returned HTTP ${status}`;
14
+ super(message);
15
+ this.name = 'CodePenApiError';
16
+ this.status = status;
17
+ this.code = body.code || (status === 404 ? 'NOT_FOUND' : 'UNKNOWN');
18
+ this.expectedVersionId = body.expected_version_id;
19
+ this.currentVersionId = body.current_version_id;
20
+ this.buildId = body.build_id;
21
+ this.field = body.field;
22
+ this.details = body.details;
23
+ this.limit = body.limit;
24
+ this.retryAfterSeconds = body.retry_after_seconds;
25
+ this.resetAt = body.reset_at;
26
+ }
27
+ formatForUser() {
28
+ const lines = [`API Error (${this.status} ${this.code}): ${this.message}`];
29
+ if (this.code === 'UNAUTHENTICATED') {
30
+ lines.push('Check your API key with `cdpn auth status` or run `cdpn auth login`.');
31
+ }
32
+ else if (this.code === 'CONFLICT') {
33
+ if (this.currentVersionId && this.expectedVersionId) {
34
+ lines.push(`Expected version ${this.expectedVersionId}, but remote head is ${this.currentVersionId}.`);
35
+ }
36
+ lines.push('Run `cdpn status` to inspect differences, `cdpn pull` to sync, or `cdpn push --force` to overwrite.');
37
+ }
38
+ else if (this.code === 'RATE_LIMITED') {
39
+ if (typeof this.retryAfterSeconds === 'number') {
40
+ const mins = Math.ceil(this.retryAfterSeconds / 60);
41
+ lines.push(`Retry after ~${mins} minute(s)${this.resetAt ? ` (resets at ${this.resetAt})` : ''}.`);
42
+ }
43
+ }
44
+ return lines.join('\n');
45
+ }
46
+ }
47
+ export function isCodePenApiError(error) {
48
+ return error instanceof CodePenApiError;
49
+ }