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 +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 +371 -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
package/sync/fs.js
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { MAX_FILE_BYTES } from '../api/client.js';
|
|
5
|
+
import { PROJECT_CONFIG_FILENAME } from '../config/project.js';
|
|
6
|
+
export const IGNORE_FILENAME = '.cdpnignore';
|
|
7
|
+
const BUILTIN_IGNORED_SEGMENTS = new Set([
|
|
8
|
+
PROJECT_CONFIG_FILENAME,
|
|
9
|
+
IGNORE_FILENAME,
|
|
10
|
+
'.git',
|
|
11
|
+
'.svn',
|
|
12
|
+
'.hg',
|
|
13
|
+
'node_modules',
|
|
14
|
+
'.DS_Store',
|
|
15
|
+
'Thumbs.db',
|
|
16
|
+
'desktop.ini',
|
|
17
|
+
]);
|
|
18
|
+
export function sha256Hex(content) {
|
|
19
|
+
return crypto.createHash('sha256').update(content).digest('hex');
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Determines whether a Buffer should be treated as binary.
|
|
23
|
+
* Checks for NUL bytes and validates strict UTF-8 decoding.
|
|
24
|
+
*/
|
|
25
|
+
export function isBinaryBuffer(buffer) {
|
|
26
|
+
if (buffer.length === 0)
|
|
27
|
+
return false;
|
|
28
|
+
const sampleLength = Math.min(buffer.length, 8192);
|
|
29
|
+
for (let i = 0; i < sampleLength; i++) {
|
|
30
|
+
if (buffer[i] === 0)
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
try {
|
|
34
|
+
new TextDecoder('utf-8', { fatal: true }).decode(buffer);
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Validates and normalizes a CodePen file path into a safe leading-slash POSIX path (e.g. `/src/app.js`).
|
|
43
|
+
* Rejects path traversal segments, backslashes, NUL bytes, Windows drive letters, and reserved CLI files.
|
|
44
|
+
*/
|
|
45
|
+
export function normalizePenPath(rawPath) {
|
|
46
|
+
if (typeof rawPath !== 'string' || rawPath.length === 0) {
|
|
47
|
+
throw new Error('File path cannot be empty.');
|
|
48
|
+
}
|
|
49
|
+
if (rawPath.includes('\0') || /[\x00-\x1f\x7f]/.test(rawPath)) {
|
|
50
|
+
throw new Error(`Invalid control character in file path: ${JSON.stringify(rawPath)}`);
|
|
51
|
+
}
|
|
52
|
+
if (rawPath.includes('\\')) {
|
|
53
|
+
throw new Error(`Backslashes are not allowed in Pen file paths: ${rawPath}`);
|
|
54
|
+
}
|
|
55
|
+
if (/^[A-Za-z]:/.test(rawPath)) {
|
|
56
|
+
throw new Error(`Drive-letter paths are not allowed: ${rawPath}`);
|
|
57
|
+
}
|
|
58
|
+
const trimmed = rawPath.replace(/^\/+/, '');
|
|
59
|
+
if (!trimmed) {
|
|
60
|
+
throw new Error(`Invalid empty Pen file path: ${rawPath}`);
|
|
61
|
+
}
|
|
62
|
+
const segments = trimmed.split('/');
|
|
63
|
+
for (const seg of segments) {
|
|
64
|
+
if (!seg || seg === '.' || seg === '..') {
|
|
65
|
+
throw new Error(`Unsafe path segment in Pen file path: ${rawPath}`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const normalized = `/${segments.join('/')}`;
|
|
69
|
+
if (segments[0] === PROJECT_CONFIG_FILENAME || segments[0] === '.git') {
|
|
70
|
+
throw new Error(`Refusing to touch reserved path: ${normalized}`);
|
|
71
|
+
}
|
|
72
|
+
return normalized;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Safely resolves a CodePen file path inside `rootDir` and enforces strict directory boundary containment.
|
|
76
|
+
*/
|
|
77
|
+
export function resolveSafeLocalPath(rootDir, penPath) {
|
|
78
|
+
const normalizedPenPath = normalizePenPath(penPath);
|
|
79
|
+
const resolvedRoot = path.resolve(rootDir);
|
|
80
|
+
const relative = normalizedPenPath.slice(1).split('/').join(path.sep);
|
|
81
|
+
const resolvedTarget = path.resolve(resolvedRoot, relative);
|
|
82
|
+
if (!resolvedTarget.startsWith(resolvedRoot + path.sep)) {
|
|
83
|
+
throw new Error(`Path escapes project root boundary: ${penPath}`);
|
|
84
|
+
}
|
|
85
|
+
return resolvedTarget;
|
|
86
|
+
}
|
|
87
|
+
function escapeRegex(str) {
|
|
88
|
+
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
89
|
+
}
|
|
90
|
+
function compileIgnorePattern(pattern) {
|
|
91
|
+
const trimmed = pattern.trim();
|
|
92
|
+
if (!trimmed || trimmed.startsWith('#'))
|
|
93
|
+
return null;
|
|
94
|
+
const normalized = trimmed.replace(/^\/+/, '').replace(/\/+$/, '');
|
|
95
|
+
if (!normalized)
|
|
96
|
+
return null;
|
|
97
|
+
const hasSlash = normalized.includes('/');
|
|
98
|
+
const regexBody = normalized
|
|
99
|
+
.split('**')
|
|
100
|
+
.map((part) => part.split('*').map(escapeRegex).join('[^/]*'))
|
|
101
|
+
.join('.*');
|
|
102
|
+
if (hasSlash) {
|
|
103
|
+
return new RegExp(`^/${regexBody}(?:/.*)?$`);
|
|
104
|
+
}
|
|
105
|
+
return new RegExp(`(?:^|/)${regexBody}(?:/.*)?$`);
|
|
106
|
+
}
|
|
107
|
+
export async function loadIgnoreMatchers(rootDir) {
|
|
108
|
+
const ignorePath = path.join(path.resolve(rootDir), IGNORE_FILENAME);
|
|
109
|
+
try {
|
|
110
|
+
const raw = await fs.readFile(ignorePath, 'utf8');
|
|
111
|
+
const matchers = [];
|
|
112
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
113
|
+
const compiled = compileIgnorePattern(line);
|
|
114
|
+
if (compiled)
|
|
115
|
+
matchers.push(compiled);
|
|
116
|
+
}
|
|
117
|
+
return matchers;
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
if (error.code === 'ENOENT') {
|
|
121
|
+
return [];
|
|
122
|
+
}
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
export function isIgnoredPath(penPath, customMatchers) {
|
|
127
|
+
const segments = penPath.replace(/^\/+/, '').split('/');
|
|
128
|
+
for (const seg of segments) {
|
|
129
|
+
if (BUILTIN_IGNORED_SEGMENTS.has(seg)) {
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return customMatchers.some((regex) => regex.test(penPath));
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Recursively scans a local Pen directory and returns all non-ignored regular files.
|
|
137
|
+
* Symlinks are intentionally skipped to prevent reading files outside the Pen directory.
|
|
138
|
+
*/
|
|
139
|
+
export async function scanLocalFiles(rootDir) {
|
|
140
|
+
const resolvedRoot = path.resolve(rootDir);
|
|
141
|
+
const customMatchers = await loadIgnoreMatchers(resolvedRoot);
|
|
142
|
+
const results = new Map();
|
|
143
|
+
async function walk(currentDir, relativePrefix) {
|
|
144
|
+
const entries = await fs.readdir(currentDir, { withFileTypes: true });
|
|
145
|
+
for (const entry of entries) {
|
|
146
|
+
if (BUILTIN_IGNORED_SEGMENTS.has(entry.name)) {
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
const penPath = relativePrefix ? `${relativePrefix}/${entry.name}` : `/${entry.name}`;
|
|
150
|
+
if (isIgnoredPath(penPath, customMatchers)) {
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
const fullPath = path.join(currentDir, entry.name);
|
|
154
|
+
if (!fullPath.startsWith(resolvedRoot + path.sep)) {
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
const stat = await fs.lstat(fullPath);
|
|
158
|
+
if (stat.isSymbolicLink()) {
|
|
159
|
+
// Skip symlinks so files outside the Pen folder are never leaked/uploaded
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
if (stat.isDirectory()) {
|
|
163
|
+
await walk(fullPath, penPath);
|
|
164
|
+
}
|
|
165
|
+
else if (stat.isFile()) {
|
|
166
|
+
if (stat.size > MAX_FILE_BYTES) {
|
|
167
|
+
throw new Error(`Local file ${penPath} is ${Math.round(stat.size / (1024 * 1024))} MB, exceeding CodePen's 30 MB per-file limit.`);
|
|
168
|
+
}
|
|
169
|
+
const buffer = await fs.readFile(fullPath);
|
|
170
|
+
const binary = isBinaryBuffer(buffer);
|
|
171
|
+
results.set(penPath, {
|
|
172
|
+
path: penPath,
|
|
173
|
+
absolutePath: fullPath,
|
|
174
|
+
buffer,
|
|
175
|
+
isBinary: binary,
|
|
176
|
+
sha256: sha256Hex(buffer),
|
|
177
|
+
textContent: binary ? null : buffer.toString('utf8'),
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
await walk(resolvedRoot, '');
|
|
183
|
+
return results;
|
|
184
|
+
}
|
|
185
|
+
async function assertNoSymlinksInRelativePath(rootDir, penPath) {
|
|
186
|
+
const resolvedRoot = path.resolve(rootDir);
|
|
187
|
+
const segments = normalizePenPath(penPath).slice(1).split('/');
|
|
188
|
+
let current = resolvedRoot;
|
|
189
|
+
for (const segment of segments) {
|
|
190
|
+
current = path.join(current, segment);
|
|
191
|
+
try {
|
|
192
|
+
const stat = await fs.lstat(current);
|
|
193
|
+
if (stat.isSymbolicLink()) {
|
|
194
|
+
throw new Error(`Refusing to write through symlink at ${penPath}`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
if (error.code === 'ENOENT') {
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
throw error;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
export async function writeLocalFile(rootDir, penPath, content) {
|
|
206
|
+
const targetPath = resolveSafeLocalPath(rootDir, penPath);
|
|
207
|
+
await assertNoSymlinksInRelativePath(rootDir, penPath);
|
|
208
|
+
await fs.mkdir(path.dirname(targetPath), { recursive: true });
|
|
209
|
+
await fs.writeFile(targetPath, content);
|
|
210
|
+
return targetPath;
|
|
211
|
+
}
|
|
212
|
+
export async function deleteLocalFile(rootDir, penPath) {
|
|
213
|
+
const targetPath = resolveSafeLocalPath(rootDir, penPath);
|
|
214
|
+
await assertNoSymlinksInRelativePath(rootDir, penPath);
|
|
215
|
+
try {
|
|
216
|
+
await fs.unlink(targetPath);
|
|
217
|
+
}
|
|
218
|
+
catch (error) {
|
|
219
|
+
if (error.code !== 'ENOENT') {
|
|
220
|
+
throw error;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
await pruneEmptyDirs(rootDir, path.dirname(targetPath));
|
|
224
|
+
}
|
|
225
|
+
export async function pruneEmptyDirs(rootDir, startDir) {
|
|
226
|
+
const resolvedRoot = path.resolve(rootDir);
|
|
227
|
+
let current = path.resolve(startDir);
|
|
228
|
+
while (current !== resolvedRoot && current.startsWith(resolvedRoot + path.sep)) {
|
|
229
|
+
try {
|
|
230
|
+
const entries = await fs.readdir(current);
|
|
231
|
+
if (entries.length > 0) {
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
await fs.rmdir(current);
|
|
235
|
+
current = path.dirname(current);
|
|
236
|
+
}
|
|
237
|
+
catch {
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
export async function isDirectoryNonEmpty(dirPath) {
|
|
243
|
+
try {
|
|
244
|
+
const entries = await fs.readdir(dirPath);
|
|
245
|
+
return entries.length > 0;
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
if (error.code === 'ENOENT') {
|
|
249
|
+
return false;
|
|
250
|
+
}
|
|
251
|
+
throw error;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { deleteLocalFile, normalizePenPath, sha256Hex, writeLocalFile, } from './fs.js';
|
|
4
|
+
export async function syncRemoteFilesToDisk(options) {
|
|
5
|
+
const { client, rootDir, remoteFiles, existingLocalPaths, pruneRemoved = false } = options;
|
|
6
|
+
const resolvedRoot = path.resolve(rootDir);
|
|
7
|
+
await fs.mkdir(resolvedRoot, { recursive: true });
|
|
8
|
+
const writtenPaths = [];
|
|
9
|
+
const deletedPaths = [];
|
|
10
|
+
const localSha256ByPath = new Map();
|
|
11
|
+
const remotePathSet = new Set();
|
|
12
|
+
for (const file of remoteFiles) {
|
|
13
|
+
const normalizedPath = normalizePenPath(file.path);
|
|
14
|
+
remotePathSet.add(normalizedPath);
|
|
15
|
+
let buffer;
|
|
16
|
+
if (!file.is_binary && file.content !== null) {
|
|
17
|
+
buffer = Buffer.from(file.content, 'utf8');
|
|
18
|
+
}
|
|
19
|
+
else if (file.download_url) {
|
|
20
|
+
buffer = await client.downloadFile(file.download_url);
|
|
21
|
+
}
|
|
22
|
+
else {
|
|
23
|
+
throw new Error(`Remote file ${normalizedPath} has neither text content nor a download_url.`);
|
|
24
|
+
}
|
|
25
|
+
await writeLocalFile(resolvedRoot, normalizedPath, buffer);
|
|
26
|
+
localSha256ByPath.set(normalizedPath, sha256Hex(buffer));
|
|
27
|
+
writtenPaths.push(normalizedPath);
|
|
28
|
+
}
|
|
29
|
+
if (pruneRemoved && existingLocalPaths) {
|
|
30
|
+
for (const localPath of existingLocalPaths) {
|
|
31
|
+
if (!remotePathSet.has(localPath)) {
|
|
32
|
+
await deleteLocalFile(resolvedRoot, localPath);
|
|
33
|
+
deletedPaths.push(localPath);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
writtenPaths.sort();
|
|
38
|
+
deletedPaths.sort();
|
|
39
|
+
return { writtenPaths, deletedPaths, localSha256ByPath };
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Applies compiler patches returned from a CodePen build back onto the local folder
|
|
43
|
+
* so the working copy stays strictly in sync with the converged remote head.
|
|
44
|
+
*/
|
|
45
|
+
export async function applyCompilerPatchesToDisk(options) {
|
|
46
|
+
const { client, rootDir, patches, convergedFiles } = options;
|
|
47
|
+
const touched = [];
|
|
48
|
+
const convergedByPath = new Map();
|
|
49
|
+
if (convergedFiles) {
|
|
50
|
+
for (const f of convergedFiles) {
|
|
51
|
+
convergedByPath.set(normalizePenPath(f.path), f);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
for (const patch of patches) {
|
|
55
|
+
const normalizedPath = normalizePenPath(patch.path);
|
|
56
|
+
if (patch.type === 'delete') {
|
|
57
|
+
await deleteLocalFile(rootDir, normalizedPath);
|
|
58
|
+
touched.push(normalizedPath);
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
const converged = convergedByPath.get(normalizedPath);
|
|
62
|
+
if (converged) {
|
|
63
|
+
if (!converged.is_binary && converged.content !== null) {
|
|
64
|
+
await writeLocalFile(rootDir, normalizedPath, converged.content);
|
|
65
|
+
touched.push(normalizedPath);
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (converged.download_url) {
|
|
69
|
+
const bytes = await client.downloadFile(converged.download_url);
|
|
70
|
+
await writeLocalFile(rootDir, normalizedPath, bytes);
|
|
71
|
+
touched.push(normalizedPath);
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (patch.content !== null) {
|
|
76
|
+
await writeLocalFile(rootDir, normalizedPath, patch.content);
|
|
77
|
+
touched.push(normalizedPath);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return touched;
|
|
81
|
+
}
|
package/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/utils/browser.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
/**
|
|
3
|
+
* Validates that a URL is a clean HTTPS URL with no control characters.
|
|
4
|
+
*/
|
|
5
|
+
export function validateBrowserUrl(rawUrl) {
|
|
6
|
+
if (/[\x00-\x1f\x7f]/.test(rawUrl)) {
|
|
7
|
+
throw new Error('URL contains invalid control characters.');
|
|
8
|
+
}
|
|
9
|
+
let parsed;
|
|
10
|
+
try {
|
|
11
|
+
parsed = new URL(rawUrl);
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
throw new Error(`Invalid URL: ${rawUrl}`);
|
|
15
|
+
}
|
|
16
|
+
if (parsed.protocol !== 'https:') {
|
|
17
|
+
throw new Error(`Refusing to open non-HTTPS URL in browser: ${parsed.protocol}`);
|
|
18
|
+
}
|
|
19
|
+
return parsed.toString();
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Opens an HTTPS URL in the user's default browser without invoking a shell.
|
|
23
|
+
* Returns `true` if the launcher succeeded, or `false` if unavailable (e.g. headless/SSH).
|
|
24
|
+
*/
|
|
25
|
+
export async function openBrowser(rawUrl) {
|
|
26
|
+
const safeUrl = validateBrowserUrl(rawUrl);
|
|
27
|
+
let command;
|
|
28
|
+
let args;
|
|
29
|
+
if (process.platform === 'darwin') {
|
|
30
|
+
command = 'open';
|
|
31
|
+
args = [safeUrl];
|
|
32
|
+
}
|
|
33
|
+
else if (process.platform === 'win32') {
|
|
34
|
+
command = 'rundll32';
|
|
35
|
+
args = ['url.dll,FileProtocolHandler', safeUrl];
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
command = 'xdg-open';
|
|
39
|
+
args = [safeUrl];
|
|
40
|
+
}
|
|
41
|
+
return new Promise((resolve) => {
|
|
42
|
+
const child = execFile(command, args, { shell: false, timeout: 10_000 }, (error) => {
|
|
43
|
+
resolve(!error);
|
|
44
|
+
});
|
|
45
|
+
child.unref();
|
|
46
|
+
});
|
|
47
|
+
}
|
package/utils/format.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
function colorsEnabled() {
|
|
2
|
+
if (process.env.NO_COLOR !== undefined && process.env.NO_COLOR !== '') {
|
|
3
|
+
return false;
|
|
4
|
+
}
|
|
5
|
+
if (process.env.FORCE_COLOR !== undefined && process.env.FORCE_COLOR !== '0') {
|
|
6
|
+
return true;
|
|
7
|
+
}
|
|
8
|
+
return Boolean(process.stdout.isTTY);
|
|
9
|
+
}
|
|
10
|
+
function wrap(code, text) {
|
|
11
|
+
if (!colorsEnabled())
|
|
12
|
+
return text;
|
|
13
|
+
return `\x1b[${code}m${text}\x1b[0m`;
|
|
14
|
+
}
|
|
15
|
+
export const fmt = {
|
|
16
|
+
bold: (s) => wrap('1', s),
|
|
17
|
+
dim: (s) => wrap('2', s),
|
|
18
|
+
red: (s) => wrap('31', s),
|
|
19
|
+
green: (s) => wrap('32', s),
|
|
20
|
+
yellow: (s) => wrap('33', s),
|
|
21
|
+
blue: (s) => wrap('34', s),
|
|
22
|
+
magenta: (s) => wrap('35', s),
|
|
23
|
+
cyan: (s) => wrap('36', s),
|
|
24
|
+
gray: (s) => wrap('90', s),
|
|
25
|
+
};
|
|
26
|
+
export function stripAnsi(text) {
|
|
27
|
+
return text.replace(/\x1b\[[0-9;]*m/g, '');
|
|
28
|
+
}
|
|
29
|
+
export function formatBytes(bytes) {
|
|
30
|
+
if (bytes < 1024)
|
|
31
|
+
return `${bytes} B`;
|
|
32
|
+
if (bytes < 1024 * 1024)
|
|
33
|
+
return `${(bytes / 1024).toFixed(1)} KB`;
|
|
34
|
+
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
|
|
35
|
+
}
|
|
36
|
+
export function formatDate(iso) {
|
|
37
|
+
const date = new Date(iso);
|
|
38
|
+
if (Number.isNaN(date.getTime()))
|
|
39
|
+
return iso;
|
|
40
|
+
return date.toISOString().replace('T', ' ').replace(/\.\d+Z$/, ' UTC');
|
|
41
|
+
}
|
|
42
|
+
export function shortId(id) {
|
|
43
|
+
if (!id)
|
|
44
|
+
return 'none';
|
|
45
|
+
return id.length > 14 ? `${id.slice(0, 8)}…${id.slice(-4)}` : id;
|
|
46
|
+
}
|
|
47
|
+
export function formatTable(headers, rows) {
|
|
48
|
+
const widths = headers.map((h, i) => {
|
|
49
|
+
let max = stripAnsi(h).length;
|
|
50
|
+
for (const row of rows) {
|
|
51
|
+
const cell = row[i] ?? '';
|
|
52
|
+
max = Math.max(max, stripAnsi(cell).length);
|
|
53
|
+
}
|
|
54
|
+
return max;
|
|
55
|
+
});
|
|
56
|
+
const pad = (text, width) => {
|
|
57
|
+
const visible = stripAnsi(text).length;
|
|
58
|
+
return text + ' '.repeat(Math.max(0, width - visible));
|
|
59
|
+
};
|
|
60
|
+
const lines = [];
|
|
61
|
+
lines.push(headers.map((h, i) => fmt.bold(pad(h, widths[i]))).join(' '));
|
|
62
|
+
lines.push(widths.map((w) => fmt.dim('─'.repeat(w))).join(' '));
|
|
63
|
+
for (const row of rows) {
|
|
64
|
+
lines.push(headers.map((_, i) => pad(row[i] ?? '', widths[i])).join(' '));
|
|
65
|
+
}
|
|
66
|
+
return lines.join('\n');
|
|
67
|
+
}
|
|
68
|
+
export function formatDiagnostic(diag) {
|
|
69
|
+
const badge = diag.type === 'Error'
|
|
70
|
+
? fmt.red('ERROR')
|
|
71
|
+
: diag.type === 'Warning'
|
|
72
|
+
? fmt.yellow('WARN ')
|
|
73
|
+
: fmt.cyan(diag.type.toUpperCase());
|
|
74
|
+
let loc = '';
|
|
75
|
+
if (diag.path) {
|
|
76
|
+
loc = diag.path;
|
|
77
|
+
if (diag.range?.start) {
|
|
78
|
+
loc += `:${diag.range.start.line}:${diag.range.start.column}`;
|
|
79
|
+
}
|
|
80
|
+
loc = `${fmt.dim(loc)} `;
|
|
81
|
+
}
|
|
82
|
+
const block = diag.block_name ? ` ${fmt.dim(`[${diag.block_name}]`)}` : '';
|
|
83
|
+
return ` ${badge} ${loc}${diag.message}${block}`;
|
|
84
|
+
}
|
|
85
|
+
export function printBuildSummary(build) {
|
|
86
|
+
const statusLabel = build.status === 'Success'
|
|
87
|
+
? fmt.green(build.status)
|
|
88
|
+
: build.status === 'Failed'
|
|
89
|
+
? fmt.red(build.status)
|
|
90
|
+
: fmt.yellow(build.status);
|
|
91
|
+
const roundsNote = build.rounds > 1 ? fmt.dim(` (${build.rounds} build rounds)`) : '';
|
|
92
|
+
console.log(`Build: ${statusLabel}${roundsNote}`);
|
|
93
|
+
if (build.applied_patches.length > 0) {
|
|
94
|
+
console.log(fmt.cyan(`Compiler applied ${build.applied_patches.length} patch(es):`));
|
|
95
|
+
for (const patch of build.applied_patches) {
|
|
96
|
+
const symbol = patch.type === 'create' ? '+' : patch.type === 'delete' ? '-' : '~';
|
|
97
|
+
console.log(` ${fmt.cyan(symbol)} ${patch.path} ${fmt.dim(`(${patch.type})`)}`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const actionableDiags = build.diagnostics.filter((d) => d.type === 'Error' || d.type === 'Warning');
|
|
101
|
+
if (actionableDiags.length > 0) {
|
|
102
|
+
console.log('Diagnostics:');
|
|
103
|
+
for (const diag of actionableDiags) {
|
|
104
|
+
console.log(formatDiagnostic(diag));
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
package/utils/html.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
const NAMED_ENTITIES = {
|
|
2
|
+
amp: '&',
|
|
3
|
+
lt: '<',
|
|
4
|
+
gt: '>',
|
|
5
|
+
quot: '"',
|
|
6
|
+
apos: "'",
|
|
7
|
+
nbsp: ' ',
|
|
8
|
+
ndash: '–',
|
|
9
|
+
mdash: '—',
|
|
10
|
+
hellip: '…',
|
|
11
|
+
copy: '©',
|
|
12
|
+
};
|
|
13
|
+
function decodeHtmlEntities(input) {
|
|
14
|
+
return input.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);/g, (match, entity) => {
|
|
15
|
+
if (entity.startsWith('#x') || entity.startsWith('#X')) {
|
|
16
|
+
const codePoint = Number.parseInt(entity.slice(2), 16);
|
|
17
|
+
if (isValidCodePoint(codePoint)) {
|
|
18
|
+
return String.fromCodePoint(codePoint);
|
|
19
|
+
}
|
|
20
|
+
return match;
|
|
21
|
+
}
|
|
22
|
+
if (entity.startsWith('#')) {
|
|
23
|
+
const codePoint = Number.parseInt(entity.slice(1), 10);
|
|
24
|
+
if (isValidCodePoint(codePoint)) {
|
|
25
|
+
return String.fromCodePoint(codePoint);
|
|
26
|
+
}
|
|
27
|
+
return match;
|
|
28
|
+
}
|
|
29
|
+
const named = NAMED_ENTITIES[entity.toLowerCase()];
|
|
30
|
+
return named ?? match;
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
function isValidCodePoint(cp) {
|
|
34
|
+
return Number.isInteger(cp) && cp >= 0 && cp <= 0x10ffff && !(cp >= 0xd800 && cp <= 0xdfff);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Extracts and cleans the text inside an HTML document's `<title>` tag,
|
|
38
|
+
* ignoring HTML comments and decoding common HTML entities.
|
|
39
|
+
*/
|
|
40
|
+
export function extractHtmlTitle(html) {
|
|
41
|
+
if (!html)
|
|
42
|
+
return null;
|
|
43
|
+
// Strip HTML comments so commented-out <title> tags are ignored
|
|
44
|
+
const withoutComments = html.replace(/<!--[\s\S]*?-->/g, '');
|
|
45
|
+
const match = withoutComments.match(/<title(?:\s[^>]*)?>([\s\S]*?)<\/title>/i);
|
|
46
|
+
if (!match?.[1]) {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
const decoded = decodeHtmlEntities(match[1]).replace(/\s+/g, ' ').trim();
|
|
50
|
+
return decoded || null;
|
|
51
|
+
}
|
package/utils/json.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { CommanderError } from 'commander';
|
|
2
|
+
import { isCodePenApiError } from '../api/errors.js';
|
|
3
|
+
import { stripAnsi } from './format.js';
|
|
4
|
+
/**
|
|
5
|
+
* Structured CLI error carrying an HTTP-modeled status code and optional structured contents
|
|
6
|
+
* for `--json` output while remaining a standard `Error` for human-readable terminal output.
|
|
7
|
+
*/
|
|
8
|
+
export class CliError extends Error {
|
|
9
|
+
statusCode;
|
|
10
|
+
contents;
|
|
11
|
+
constructor(statusCode, message, contents = null) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = 'CliError';
|
|
14
|
+
this.statusCode = statusCode;
|
|
15
|
+
this.contents = contents;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function isCliError(error) {
|
|
19
|
+
return error instanceof CliError;
|
|
20
|
+
}
|
|
21
|
+
export function createJsonResponse(code, message, contents) {
|
|
22
|
+
return {
|
|
23
|
+
status: {
|
|
24
|
+
code,
|
|
25
|
+
message: stripAnsi(message),
|
|
26
|
+
},
|
|
27
|
+
contents,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
export function formatJsonResponse(code, message, contents) {
|
|
31
|
+
return JSON.stringify(createJsonResponse(code, message, contents), null, 2);
|
|
32
|
+
}
|
|
33
|
+
export function printJsonResponse(code, message, contents) {
|
|
34
|
+
const envelope = createJsonResponse(code, message, contents);
|
|
35
|
+
console.log(JSON.stringify(envelope, null, 2));
|
|
36
|
+
return envelope;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Checks whether `--json` was passed in the CLI argument vector (stopping at `--`).
|
|
40
|
+
*/
|
|
41
|
+
export function wantsJsonOutput(argv) {
|
|
42
|
+
for (let i = 2; i < argv.length; i++) {
|
|
43
|
+
const arg = argv[i];
|
|
44
|
+
if (arg === '--')
|
|
45
|
+
break;
|
|
46
|
+
if (arg === '--json')
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
function inferHttpStatusCode(error) {
|
|
52
|
+
const errno = error.code;
|
|
53
|
+
if (errno === 'ENOENT')
|
|
54
|
+
return 404;
|
|
55
|
+
if (errno === 'EACCES' || errno === 'EPERM')
|
|
56
|
+
return 403;
|
|
57
|
+
if (errno === 'EEXIST')
|
|
58
|
+
return 409;
|
|
59
|
+
if (errno === 'ETIMEDOUT')
|
|
60
|
+
return 504;
|
|
61
|
+
if (errno === 'ECONNREFUSED' || errno === 'ENOTFOUND' || errno === 'EAI_AGAIN' || errno === 'ECONNRESET') {
|
|
62
|
+
return 502;
|
|
63
|
+
}
|
|
64
|
+
const msg = error.message;
|
|
65
|
+
if (/no codepen api key found|not authenticated|unauthenticated/i.test(msg))
|
|
66
|
+
return 401;
|
|
67
|
+
if (/classic pen.*read-only|cannot (fork|clone) .+ via codepen api/i.test(msg))
|
|
68
|
+
return 403;
|
|
69
|
+
if (/not found|no \.cdpn\.json found|no profiles found|no saved versions|no codepen template found/i.test(msg)) {
|
|
70
|
+
return 404;
|
|
71
|
+
}
|
|
72
|
+
if (/already exists|is not empty|moved ahead|local changes detected|already contains|multiple codepen templates match/i.test(msg)) {
|
|
73
|
+
return 409;
|
|
74
|
+
}
|
|
75
|
+
if (/build failed/i.test(msg))
|
|
76
|
+
return 422;
|
|
77
|
+
if (/invalid |cannot combine|must be |requires? |missing |specify |refusing to |at most |expected a codepen url|cannot be empty|not deployed yet|only supported for|only works/i.test(msg)) {
|
|
78
|
+
return 400;
|
|
79
|
+
}
|
|
80
|
+
return 500;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Converts any thrown error into a consistent `{ status: { code, message }, contents }` envelope.
|
|
84
|
+
*/
|
|
85
|
+
export function errorToJsonEnvelope(error) {
|
|
86
|
+
if (isCodePenApiError(error)) {
|
|
87
|
+
const code = Number.isInteger(error.status) && error.status >= 100 && error.status <= 599
|
|
88
|
+
? error.status
|
|
89
|
+
: 502;
|
|
90
|
+
const details = {
|
|
91
|
+
error_code: error.code,
|
|
92
|
+
};
|
|
93
|
+
if (error.expectedVersionId !== undefined)
|
|
94
|
+
details.expected_version_id = error.expectedVersionId;
|
|
95
|
+
if (error.currentVersionId !== undefined)
|
|
96
|
+
details.current_version_id = error.currentVersionId;
|
|
97
|
+
if (error.buildId !== undefined)
|
|
98
|
+
details.build_id = error.buildId;
|
|
99
|
+
if (error.field !== undefined)
|
|
100
|
+
details.field = error.field;
|
|
101
|
+
if (error.details !== undefined)
|
|
102
|
+
details.details = error.details;
|
|
103
|
+
if (error.limit !== undefined)
|
|
104
|
+
details.limit = error.limit;
|
|
105
|
+
if (error.retryAfterSeconds !== undefined)
|
|
106
|
+
details.retry_after_seconds = error.retryAfterSeconds;
|
|
107
|
+
if (error.resetAt !== undefined)
|
|
108
|
+
details.reset_at = error.resetAt;
|
|
109
|
+
return createJsonResponse(code, error.message, details);
|
|
110
|
+
}
|
|
111
|
+
if (isCliError(error)) {
|
|
112
|
+
return createJsonResponse(error.statusCode, error.message, error.contents);
|
|
113
|
+
}
|
|
114
|
+
if (error instanceof CommanderError) {
|
|
115
|
+
const cleanMessage = error.message.replace(/^error:\s*/i, '').trim() || error.message;
|
|
116
|
+
return createJsonResponse(400, cleanMessage, { error_code: error.code });
|
|
117
|
+
}
|
|
118
|
+
if (error instanceof Error) {
|
|
119
|
+
return createJsonResponse(inferHttpStatusCode(error), error.message, null);
|
|
120
|
+
}
|
|
121
|
+
return createJsonResponse(500, String(error), null);
|
|
122
|
+
}
|