codepen-commander 1.3.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.
- package/README.md +103 -11
- package/api/client.js +129 -106
- package/cli.js +34 -29
- package/commands/auth/default.js +40 -0
- package/commands/auth/index.js +83 -0
- package/commands/auth/list.js +78 -0
- package/commands/auth/login.js +136 -0
- package/commands/auth/logout.js +186 -0
- package/commands/auth/status.js +212 -0
- package/commands/build.js +256 -0
- package/commands/clone.js +13 -581
- package/commands/delete.js +548 -80
- package/commands/deploy.js +164 -169
- package/commands/domains.js +83 -39
- package/commands/fork.js +13 -317
- package/commands/info.js +152 -0
- package/commands/init.js +375 -0
- package/commands/list.js +95 -78
- package/commands/new.js +155 -83
- package/commands/open.js +29 -19
- package/commands/privacy.js +52 -36
- package/commands/pull.js +123 -110
- package/commands/push.js +221 -376
- package/commands/restore.js +251 -0
- package/commands/rollback.js +141 -0
- package/commands/serve.js +119 -0
- package/commands/settings.js +126 -0
- package/commands/shell.js +305 -0
- package/commands/status.js +133 -39
- package/commands/sync.js +330 -0
- package/commands/undeploy.js +102 -0
- package/commands/unlink.js +191 -0
- package/commands/versions.js +100 -163
- package/config/auth.js +4 -374
- package/config/pen-blocks.js +166 -0
- package/config/project.js +103 -231
- package/config/user-store.js +364 -0
- package/constants.js +42 -0
- package/errors.js +17 -0
- package/package.json +1 -1
- package/shell/index.html +79 -0
- package/shell/scripts.js +276 -0
- package/shell/styles.css +492 -0
- package/site/blocks/classic.js +270 -0
- package/site/blocks/context.js +63 -0
- package/site/blocks/index.js +4 -0
- package/site/blocks/packages.js +242 -0
- package/site/blocks/unsupported-page.js +328 -0
- package/site/builder.js +475 -0
- package/site/detect.js +65 -0
- package/site/ignore-files.js +90 -0
- package/site/manifest.js +227 -0
- package/site/server.js +483 -0
- package/site/shell.js +363 -0
- package/sync/fs.js +19 -17
- package/sync/info.js +6 -81
- package/utils/browser.js +17 -10
- package/utils/cli-options.js +79 -0
- package/utils/codepen-url.js +183 -0
- package/utils/format.js +39 -30
- package/utils/fs-safe.js +95 -0
- package/utils/html.js +40 -1
- package/utils/json.js +4 -19
- package/utils/output.js +37 -0
- package/utils/package-paths.js +51 -0
- package/utils/prompts/index.js +5 -0
- package/utils/prompts/multi-select.js +185 -0
- package/utils/prompts/secret.js +65 -0
- package/utils/prompts/select.js +141 -0
- package/utils/prompts/text.js +99 -0
- package/utils/prompts/tty-list.js +165 -0
- package/utils/prompts/types.js +35 -0
- package/utils/strings.js +98 -0
- package/utils/watcher.js +82 -0
- package/{commands → workflows}/auth-context.js +13 -7
- package/workflows/batch-pens.js +1647 -0
- package/workflows/batch-target.js +184 -0
- package/workflows/classic-convert.js +241 -0
- package/workflows/clone-pen.js +381 -0
- package/{commands → workflows}/create-pen.js +59 -84
- package/workflows/discover-pens.js +91 -0
- package/workflows/fork-pen.js +314 -0
- package/workflows/missing-pen.js +212 -0
- package/workflows/pull-pen.js +204 -0
- package/workflows/push-pen.js +318 -0
- package/{commands → workflows}/scaffold.js +4 -3
- package/workflows/sync-pen.js +227 -0
- package/{commands → workflows}/unowned-pen.js +16 -12
- package/commands/auth.js +0 -593
- package/commands/meta.js +0 -184
- package/utils/prompts.js +0 -316
- /package/{types.js → api/types.js} +0 -0
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { MAX_PEN_TAGS, MAX_VERSION_LABEL_LENGTH, MIN_PROTECTED_PASSWORD_LENGTH, VALID_PEN_ACCESS_LOWER, } from '../constants.js';
|
|
2
|
+
import { CliError } from '../errors.js';
|
|
3
|
+
export function parseAccessValue(raw) {
|
|
4
|
+
const lower = raw.trim().toLowerCase();
|
|
5
|
+
if (!VALID_PEN_ACCESS_LOWER.has(lower)) {
|
|
6
|
+
return null;
|
|
7
|
+
}
|
|
8
|
+
return (lower[0].toUpperCase() + lower.slice(1));
|
|
9
|
+
}
|
|
10
|
+
export function normalizeAccess(raw) {
|
|
11
|
+
if (!raw)
|
|
12
|
+
return undefined;
|
|
13
|
+
const parsed = parseAccessValue(raw);
|
|
14
|
+
if (!parsed) {
|
|
15
|
+
throw new CliError(400, `Invalid access level "${raw}". Use: Public, Private, Protected, or Collaborators.`);
|
|
16
|
+
}
|
|
17
|
+
return parsed;
|
|
18
|
+
}
|
|
19
|
+
export function resolveAccessOrVisibility(rawAccess, rawVisibility) {
|
|
20
|
+
const access = normalizeAccess(rawAccess);
|
|
21
|
+
const visibility = normalizeAccess(rawVisibility);
|
|
22
|
+
if (access && visibility && access !== visibility) {
|
|
23
|
+
throw new CliError(400, `Conflicting --access ("${access}") and --visibility ("${visibility}") values.`);
|
|
24
|
+
}
|
|
25
|
+
return access ?? visibility;
|
|
26
|
+
}
|
|
27
|
+
export function parseTagsOption(raw) {
|
|
28
|
+
if (raw === undefined)
|
|
29
|
+
return undefined;
|
|
30
|
+
return raw
|
|
31
|
+
.split(',')
|
|
32
|
+
.map((t) => t.trim())
|
|
33
|
+
.filter(Boolean);
|
|
34
|
+
}
|
|
35
|
+
export function assertValidTagCount(tags, sourceHint = '') {
|
|
36
|
+
if (tags && tags.length > MAX_PEN_TAGS) {
|
|
37
|
+
const suffix = sourceHint ? ` (${sourceHint})` : '';
|
|
38
|
+
throw new CliError(400, `CodePen allows at most ${MAX_PEN_TAGS} tags per Pen (found ${tags.length}${suffix}).`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export function assertValidVersionLabel(label) {
|
|
42
|
+
if (label && label.length > MAX_VERSION_LABEL_LENGTH) {
|
|
43
|
+
throw new CliError(400, `Version label must be at most ${MAX_VERSION_LABEL_LENGTH} characters.`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export function assertValidProtectedPassword(access, password, interactive) {
|
|
47
|
+
if (access !== 'Protected')
|
|
48
|
+
return;
|
|
49
|
+
if (password !== undefined && password.length < MIN_PROTECTED_PASSWORD_LENGTH) {
|
|
50
|
+
throw new CliError(400, `Protected Pens require --password with at least ${MIN_PROTECTED_PASSWORD_LENGTH} characters.`);
|
|
51
|
+
}
|
|
52
|
+
if (!password && !interactive) {
|
|
53
|
+
throw new CliError(400, `Protected Pens require --password with at least ${MIN_PROTECTED_PASSWORD_LENGTH} characters.`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
export function parseBooleanOption(raw, flagName) {
|
|
57
|
+
const lower = raw.trim().toLowerCase();
|
|
58
|
+
if (lower === 'true' || lower === '1' || lower === 'yes' || lower === 'on')
|
|
59
|
+
return true;
|
|
60
|
+
if (lower === 'false' || lower === '0' || lower === 'no' || lower === 'off')
|
|
61
|
+
return false;
|
|
62
|
+
throw new CliError(400, `Invalid boolean value "${raw}" for ${flagName}. Use true or false.`);
|
|
63
|
+
}
|
|
64
|
+
export function parseTemplateCliFlag(rawTemplate, asTemplate) {
|
|
65
|
+
let parsedTemplate;
|
|
66
|
+
if (typeof rawTemplate === 'boolean') {
|
|
67
|
+
parsedTemplate = rawTemplate;
|
|
68
|
+
}
|
|
69
|
+
else if (typeof rawTemplate === 'string') {
|
|
70
|
+
parsedTemplate = parseBooleanOption(rawTemplate, '--template');
|
|
71
|
+
}
|
|
72
|
+
if (parsedTemplate !== undefined && asTemplate !== undefined && parsedTemplate !== asTemplate) {
|
|
73
|
+
throw new CliError(400, 'Cannot combine conflicting --template and --as-template flags.');
|
|
74
|
+
}
|
|
75
|
+
return parsedTemplate ?? asTemplate;
|
|
76
|
+
}
|
|
77
|
+
export function resolveInheritedJsonOption(options, command) {
|
|
78
|
+
return Boolean(options.json || command.parent?.opts().json);
|
|
79
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { CliError } from '../errors.js';
|
|
2
|
+
import { slugifyTitle } from './strings.js';
|
|
3
|
+
const PEN_ID_PATTERN = /^[A-Za-z0-9_-]{3,64}$/;
|
|
4
|
+
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
5
|
+
const PEN_VIEW_SEGMENTS = new Set(['pen', 'full', 'details', 'debug', 'live', 'embed']);
|
|
6
|
+
const CLASSIC_PEN_VIEW_SEGMENTS = new Set([...PEN_VIEW_SEGMENTS, 'editor']);
|
|
7
|
+
const RESERVED_CODEPEN_SEGMENTS = new Set([
|
|
8
|
+
'pen',
|
|
9
|
+
'editor',
|
|
10
|
+
'full',
|
|
11
|
+
'details',
|
|
12
|
+
'debug',
|
|
13
|
+
'live',
|
|
14
|
+
'embed',
|
|
15
|
+
'settings',
|
|
16
|
+
'trending',
|
|
17
|
+
'following',
|
|
18
|
+
'your-work',
|
|
19
|
+
'collections',
|
|
20
|
+
'project',
|
|
21
|
+
'projects',
|
|
22
|
+
'api',
|
|
23
|
+
]);
|
|
24
|
+
/**
|
|
25
|
+
* Extracts a Pen's cpid or hashid from a CodePen URL, when present in the URL path or host.
|
|
26
|
+
*/
|
|
27
|
+
export function extractPenIdFromUrl(rawUrl) {
|
|
28
|
+
let parsed;
|
|
29
|
+
try {
|
|
30
|
+
parsed = new URL(rawUrl.trim());
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
const host = parsed.hostname.toLowerCase();
|
|
36
|
+
if (host === 'codepen.io' || host === 'www.codepen.io') {
|
|
37
|
+
const segments = parsed.pathname.split('/').filter(Boolean);
|
|
38
|
+
if (segments.length < 2) {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
let idx = 0;
|
|
42
|
+
const isV2EditorPath = segments[0]?.toLowerCase() === 'editor';
|
|
43
|
+
const viewSegments = isV2EditorPath ? PEN_VIEW_SEGMENTS : CLASSIC_PEN_VIEW_SEGMENTS;
|
|
44
|
+
if (isV2EditorPath) {
|
|
45
|
+
idx++;
|
|
46
|
+
if (segments.length === 2 && segments[1] && UUID_PATTERN.test(segments[1])) {
|
|
47
|
+
return segments[1];
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (segments[idx]?.toLowerCase() === 'team') {
|
|
51
|
+
// Skip `team/<team-slug>`
|
|
52
|
+
idx += 2;
|
|
53
|
+
}
|
|
54
|
+
else if (segments[idx] && !viewSegments.has(segments[idx].toLowerCase())) {
|
|
55
|
+
// Skip `<username>`
|
|
56
|
+
idx += 1;
|
|
57
|
+
}
|
|
58
|
+
const view = segments[idx]?.toLowerCase();
|
|
59
|
+
if (!view || !viewSegments.has(view)) {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
idx++;
|
|
63
|
+
// Handle `/embed/preview/<id>`
|
|
64
|
+
if (view === 'embed' && segments[idx]?.toLowerCase() === 'preview') {
|
|
65
|
+
idx++;
|
|
66
|
+
}
|
|
67
|
+
const idCandidate = segments[idx]?.trim();
|
|
68
|
+
if (idCandidate && PEN_ID_PATTERN.test(idCandidate)) {
|
|
69
|
+
return idCandidate;
|
|
70
|
+
}
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
// Content or preview subdomains carrying a UUID cpid (e.g. `<cpid>.codepenusercontent.com`)
|
|
74
|
+
const firstLabel = host.split('.')[0];
|
|
75
|
+
if (firstLabel &&
|
|
76
|
+
UUID_PATTERN.test(firstLabel) &&
|
|
77
|
+
(host.endsWith('.codepen.dev') ||
|
|
78
|
+
host.endsWith('.codepen.app') ||
|
|
79
|
+
host.endsWith('.codepenusercontent.com'))) {
|
|
80
|
+
return firstLabel;
|
|
81
|
+
}
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Validates and normalizes a Pen identifier or CodePen URL passed by the user.
|
|
86
|
+
*/
|
|
87
|
+
export function normalizePenReference(rawInput) {
|
|
88
|
+
const trimmed = rawInput.trim();
|
|
89
|
+
if (!trimmed) {
|
|
90
|
+
throw new CliError(400, 'Pen URL or ID cannot be empty.');
|
|
91
|
+
}
|
|
92
|
+
if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) {
|
|
93
|
+
let parsed;
|
|
94
|
+
try {
|
|
95
|
+
parsed = new URL(trimmed);
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
throw new CliError(400, `Invalid URL: ${trimmed}`);
|
|
99
|
+
}
|
|
100
|
+
const host = parsed.hostname.toLowerCase();
|
|
101
|
+
const isCodePenHost = host === 'codepen.io' ||
|
|
102
|
+
host.endsWith('.codepen.io') ||
|
|
103
|
+
host.endsWith('.codepen.dev') ||
|
|
104
|
+
host.endsWith('.codepen.app') ||
|
|
105
|
+
host.endsWith('.codepenusercontent.com');
|
|
106
|
+
if (!isCodePenHost) {
|
|
107
|
+
throw new CliError(400, `Expected a CodePen URL (codepen.io / codepen.dev / codepen.app), got: ${host}`);
|
|
108
|
+
}
|
|
109
|
+
const extractedId = extractPenIdFromUrl(trimmed);
|
|
110
|
+
return {
|
|
111
|
+
apiIdentifier: extractedId ?? trimmed,
|
|
112
|
+
originalUrl: trimmed,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
// Raw cpid (UUID) or hashid
|
|
116
|
+
if (!PEN_ID_PATTERN.test(trimmed)) {
|
|
117
|
+
throw new CliError(400, `Invalid Pen ID: "${trimmed}". Provide a Pen URL, cpid, or hashid.`);
|
|
118
|
+
}
|
|
119
|
+
return { apiIdentifier: trimmed };
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Produces a safe default local folder name for a Pen based on its title or ID.
|
|
123
|
+
*/
|
|
124
|
+
export function suggestFolderName(pen) {
|
|
125
|
+
return slugifyTitle(pen.title) ?? pen.id.replace(/[^A-Za-z0-9_-]/g, '-');
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Extracts the CodePen username or team slug from a `codepen.io` URL, if present.
|
|
129
|
+
*/
|
|
130
|
+
export function extractCodePenOwnerFromUrl(rawUrl) {
|
|
131
|
+
let parsed;
|
|
132
|
+
try {
|
|
133
|
+
parsed = new URL(rawUrl.trim());
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
const host = parsed.hostname.toLowerCase();
|
|
139
|
+
if (host !== 'codepen.io' && host !== 'www.codepen.io') {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
const segments = parsed.pathname.split('/').filter(Boolean);
|
|
143
|
+
let idx = 0;
|
|
144
|
+
// CodePen 2.0 editor URLs place `/editor/` before the username/team slug
|
|
145
|
+
if (segments[idx]?.toLowerCase() === 'editor') {
|
|
146
|
+
idx++;
|
|
147
|
+
}
|
|
148
|
+
// Team URLs may include a `/team/` prefix before the team slug
|
|
149
|
+
if (segments[idx]?.toLowerCase() === 'team') {
|
|
150
|
+
idx++;
|
|
151
|
+
}
|
|
152
|
+
// Require at least `<owner>/<view-or-resource>` remaining (e.g. `bramus/pen/<id>`)
|
|
153
|
+
if (segments.length - idx < 2) {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
const candidate = segments[idx]?.trim();
|
|
157
|
+
if (!candidate || RESERVED_CODEPEN_SEGMENTS.has(candidate.toLowerCase())) {
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
if (/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(candidate)) {
|
|
161
|
+
return candidate;
|
|
162
|
+
}
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Validates that a URL is an HTTPS `codepen.io` (or `*.codepen.io`) URL safe for rendering in HTML.
|
|
167
|
+
*/
|
|
168
|
+
export function sanitizeCodePenUrl(rawUrl) {
|
|
169
|
+
if (typeof rawUrl !== 'string')
|
|
170
|
+
return null;
|
|
171
|
+
try {
|
|
172
|
+
const parsed = new URL(rawUrl.trim());
|
|
173
|
+
if (parsed.protocol !== 'https:')
|
|
174
|
+
return null;
|
|
175
|
+
if (parsed.hostname !== 'codepen.io' && !parsed.hostname.endsWith('.codepen.io')) {
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
return parsed.href;
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
}
|
package/utils/format.js
CHANGED
|
@@ -1,28 +1,37 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
1
|
+
import { defaultOutput } from './output.js';
|
|
2
|
+
export function createFormatter(output = process.stdout) {
|
|
3
|
+
const colorsEnabled = () => {
|
|
4
|
+
if (process.env.NO_COLOR !== undefined && process.env.NO_COLOR !== '') {
|
|
5
|
+
return false;
|
|
6
|
+
}
|
|
7
|
+
if (process.env.FORCE_COLOR !== undefined && process.env.FORCE_COLOR !== '0') {
|
|
8
|
+
return true;
|
|
9
|
+
}
|
|
10
|
+
return Boolean(output.isTTY);
|
|
11
|
+
};
|
|
12
|
+
const wrap = (code, text) => {
|
|
13
|
+
if (!colorsEnabled())
|
|
14
|
+
return text;
|
|
15
|
+
return `\x1b[${code}m${text}\x1b[0m`;
|
|
16
|
+
};
|
|
17
|
+
return {
|
|
18
|
+
bold: (s) => wrap('1', s),
|
|
19
|
+
dim: (s) => wrap('2', s),
|
|
20
|
+
red: (s) => wrap('31', s),
|
|
21
|
+
green: (s) => wrap('32', s),
|
|
22
|
+
yellow: (s) => wrap('33', s),
|
|
23
|
+
blue: (s) => wrap('34', s),
|
|
24
|
+
magenta: (s) => wrap('35', s),
|
|
25
|
+
cyan: (s) => wrap('36', s),
|
|
26
|
+
gray: (s) => wrap('90', s),
|
|
27
|
+
boldGreen: (s) => wrap('1;32', s),
|
|
28
|
+
boldYellow: (s) => wrap('1;33', s),
|
|
29
|
+
boldCyan: (s) => wrap('1;36', s),
|
|
30
|
+
boldMagenta: (s) => wrap('1;35', s),
|
|
31
|
+
boldRed: (s) => wrap('1;31', s),
|
|
32
|
+
};
|
|
14
33
|
}
|
|
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
|
-
};
|
|
34
|
+
export const fmt = createFormatter(process.stdout);
|
|
26
35
|
export function stripAnsi(text) {
|
|
27
36
|
return text.replace(/\x1b\[[0-9;]*m/g, '');
|
|
28
37
|
}
|
|
@@ -82,26 +91,26 @@ export function formatDiagnostic(diag) {
|
|
|
82
91
|
const block = diag.block_name ? ` ${fmt.dim(`[${diag.block_name}]`)}` : '';
|
|
83
92
|
return ` ${badge} ${loc}${diag.message}${block}`;
|
|
84
93
|
}
|
|
85
|
-
export function printBuildSummary(build) {
|
|
94
|
+
export function printBuildSummary(build, output = defaultOutput) {
|
|
86
95
|
const statusLabel = build.status === 'Success'
|
|
87
96
|
? fmt.green(build.status)
|
|
88
97
|
: build.status === 'Failed'
|
|
89
98
|
? fmt.red(build.status)
|
|
90
99
|
: fmt.yellow(build.status);
|
|
91
100
|
const roundsNote = build.rounds > 1 ? fmt.dim(` (${build.rounds} build rounds)`) : '';
|
|
92
|
-
|
|
101
|
+
output.log(`Build: ${statusLabel}${roundsNote}`);
|
|
93
102
|
if (build.applied_patches.length > 0) {
|
|
94
|
-
|
|
103
|
+
output.log(fmt.cyan(`Compiler applied ${build.applied_patches.length} patch(es):`));
|
|
95
104
|
for (const patch of build.applied_patches) {
|
|
96
105
|
const symbol = patch.type === 'create' ? '+' : patch.type === 'delete' ? '-' : '~';
|
|
97
|
-
|
|
106
|
+
output.log(` ${fmt.cyan(symbol)} ${patch.path} ${fmt.dim(`(${patch.type})`)}`);
|
|
98
107
|
}
|
|
99
108
|
}
|
|
100
109
|
const actionableDiags = build.diagnostics.filter((d) => d.type === 'Error' || d.type === 'Warning');
|
|
101
110
|
if (actionableDiags.length > 0) {
|
|
102
|
-
|
|
111
|
+
output.log('Diagnostics:');
|
|
103
112
|
for (const diag of actionableDiags) {
|
|
104
|
-
|
|
113
|
+
output.log(formatDiagnostic(diag));
|
|
105
114
|
}
|
|
106
115
|
}
|
|
107
116
|
}
|
package/utils/fs-safe.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { isPlainObject } from './strings.js';
|
|
4
|
+
const DEFAULT_MAX_JSON_BYTES = 256 * 1024;
|
|
5
|
+
const utf8Decoder = new TextDecoder('utf-8');
|
|
6
|
+
export function isWithinRoot(candidatePath, rootPath) {
|
|
7
|
+
return candidatePath === rootPath || candidatePath.startsWith(rootPath + path.sep);
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Safely verifies that `candidatePath` is a regular (non-symlink) file whose resolved
|
|
11
|
+
* and canonical paths both stay strictly inside `rootDir` / `rootRealpath`.
|
|
12
|
+
*/
|
|
13
|
+
export async function resolveSafeFile(candidatePath, rootRealpath, rootDir = rootRealpath) {
|
|
14
|
+
const resolved = path.resolve(candidatePath);
|
|
15
|
+
if (!isWithinRoot(resolved, rootDir))
|
|
16
|
+
return null;
|
|
17
|
+
let lstat;
|
|
18
|
+
try {
|
|
19
|
+
lstat = await fs.lstat(resolved);
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
if (lstat.isSymbolicLink() || !lstat.isFile())
|
|
25
|
+
return null;
|
|
26
|
+
try {
|
|
27
|
+
const realPath = await fs.realpath(resolved);
|
|
28
|
+
if (!isWithinRoot(realPath, rootRealpath))
|
|
29
|
+
return null;
|
|
30
|
+
return { realPath, size: lstat.size };
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Safely verifies that `candidatePath` is a regular (non-symlink) directory whose resolved
|
|
38
|
+
* and canonical paths both stay strictly inside `rootDir` / `rootRealpath`.
|
|
39
|
+
*/
|
|
40
|
+
export async function resolveSafeDir(candidatePath, rootRealpath, rootDir = rootRealpath) {
|
|
41
|
+
const resolved = path.resolve(candidatePath);
|
|
42
|
+
if (!isWithinRoot(resolved, rootDir))
|
|
43
|
+
return null;
|
|
44
|
+
let lstat;
|
|
45
|
+
try {
|
|
46
|
+
lstat = await fs.lstat(resolved);
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
if (lstat.isSymbolicLink() || !lstat.isDirectory())
|
|
52
|
+
return null;
|
|
53
|
+
try {
|
|
54
|
+
const realPath = await fs.realpath(resolved);
|
|
55
|
+
if (!isWithinRoot(realPath, rootRealpath))
|
|
56
|
+
return null;
|
|
57
|
+
return realPath;
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export async function readSafeJsonObject(filePath, rootRealpath, maxBytes = DEFAULT_MAX_JSON_BYTES) {
|
|
64
|
+
const file = await resolveSafeFile(filePath, rootRealpath);
|
|
65
|
+
if (!file || file.size > maxBytes)
|
|
66
|
+
return null;
|
|
67
|
+
try {
|
|
68
|
+
const raw = await fs.readFile(file.realPath, 'utf8');
|
|
69
|
+
const parsed = JSON.parse(raw);
|
|
70
|
+
return isPlainObject(parsed) ? parsed : null;
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
export async function readPartialUtf8(filePath, maxBytes) {
|
|
77
|
+
const handle = await fs.open(filePath, 'r');
|
|
78
|
+
try {
|
|
79
|
+
const buffer = Buffer.alloc(maxBytes);
|
|
80
|
+
const { bytesRead } = await handle.read(buffer, 0, maxBytes, 0);
|
|
81
|
+
return utf8Decoder.decode(buffer.subarray(0, bytesRead));
|
|
82
|
+
}
|
|
83
|
+
finally {
|
|
84
|
+
await handle.close();
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
export async function fileExistsRegular(filePath) {
|
|
88
|
+
try {
|
|
89
|
+
const stat = await fs.lstat(filePath);
|
|
90
|
+
return !stat.isSymbolicLink() && stat.isFile();
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
}
|
package/utils/html.js
CHANGED
|
@@ -10,7 +10,15 @@ const NAMED_ENTITIES = {
|
|
|
10
10
|
hellip: '…',
|
|
11
11
|
copy: '©',
|
|
12
12
|
};
|
|
13
|
-
function
|
|
13
|
+
export function escapeHtml(value) {
|
|
14
|
+
return String(value)
|
|
15
|
+
.replace(/&/g, '&')
|
|
16
|
+
.replace(/</g, '<')
|
|
17
|
+
.replace(/>/g, '>')
|
|
18
|
+
.replace(/"/g, '"')
|
|
19
|
+
.replace(/'/g, ''');
|
|
20
|
+
}
|
|
21
|
+
export function decodeHtmlEntities(input) {
|
|
14
22
|
return input.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);/g, (match, entity) => {
|
|
15
23
|
if (entity.startsWith('#x') || entity.startsWith('#X')) {
|
|
16
24
|
const codePoint = Number.parseInt(entity.slice(2), 16);
|
|
@@ -49,3 +57,34 @@ export function extractHtmlTitle(html) {
|
|
|
49
57
|
const decoded = decodeHtmlEntities(match[1]).replace(/\s+/g, ' ').trim();
|
|
50
58
|
return decoded || null;
|
|
51
59
|
}
|
|
60
|
+
/**
|
|
61
|
+
* Extracts and cleans the `<meta name="description" content="...">` value from HTML.
|
|
62
|
+
*/
|
|
63
|
+
export function extractMetaDescription(html, maxLength = 320) {
|
|
64
|
+
if (!html)
|
|
65
|
+
return null;
|
|
66
|
+
const withoutComments = html.replace(/<!--[\s\S]*?-->/g, '');
|
|
67
|
+
const metaTagPattern = /<meta\b[^>]{1,1000}>/gi;
|
|
68
|
+
const attrPattern = /([a-zA-Z_:][\w:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/g;
|
|
69
|
+
for (const tagMatch of withoutComments.matchAll(metaTagPattern)) {
|
|
70
|
+
let metaName = null;
|
|
71
|
+
let metaContent = null;
|
|
72
|
+
for (const attrMatch of tagMatch[0].matchAll(attrPattern)) {
|
|
73
|
+
const key = attrMatch[1]?.toLowerCase();
|
|
74
|
+
const value = attrMatch[2] ?? attrMatch[3] ?? attrMatch[4] ?? '';
|
|
75
|
+
if (key === 'name') {
|
|
76
|
+
metaName = value.trim().toLowerCase();
|
|
77
|
+
}
|
|
78
|
+
else if (key === 'content') {
|
|
79
|
+
metaContent = value;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (metaName === 'description' && metaContent !== null) {
|
|
83
|
+
const cleaned = decodeHtmlEntities(metaContent).replace(/\s+/g, ' ').trim();
|
|
84
|
+
if (!cleaned)
|
|
85
|
+
return null;
|
|
86
|
+
return cleaned.length > maxLength ? `${cleaned.slice(0, maxLength - 1)}…` : cleaned;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return null;
|
|
90
|
+
}
|
package/utils/json.js
CHANGED
|
@@ -1,23 +1,8 @@
|
|
|
1
1
|
import { CommanderError } from 'commander';
|
|
2
2
|
import { isCodePenApiError } from '../api/errors.js';
|
|
3
|
+
import { isCliError } from '../errors.js';
|
|
3
4
|
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
|
-
}
|
|
5
|
+
import { defaultOutput } from './output.js';
|
|
21
6
|
export function createJsonResponse(code, message, contents) {
|
|
22
7
|
return {
|
|
23
8
|
status: {
|
|
@@ -30,9 +15,9 @@ export function createJsonResponse(code, message, contents) {
|
|
|
30
15
|
export function formatJsonResponse(code, message, contents) {
|
|
31
16
|
return JSON.stringify(createJsonResponse(code, message, contents), null, 2);
|
|
32
17
|
}
|
|
33
|
-
export function printJsonResponse(code, message, contents) {
|
|
18
|
+
export function printJsonResponse(code, message, contents, output = defaultOutput) {
|
|
34
19
|
const envelope = createJsonResponse(code, message, contents);
|
|
35
|
-
|
|
20
|
+
output.log(JSON.stringify(envelope, null, 2));
|
|
36
21
|
return envelope;
|
|
37
22
|
}
|
|
38
23
|
/**
|
package/utils/output.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export const defaultOutput = {
|
|
2
|
+
log(message = '') {
|
|
3
|
+
console.log(message);
|
|
4
|
+
},
|
|
5
|
+
error(message = '') {
|
|
6
|
+
console.error(message);
|
|
7
|
+
},
|
|
8
|
+
write(chunk) {
|
|
9
|
+
process.stdout.write(chunk);
|
|
10
|
+
},
|
|
11
|
+
};
|
|
12
|
+
export function createSilentOutput() {
|
|
13
|
+
return {
|
|
14
|
+
log: () => { },
|
|
15
|
+
error: () => { },
|
|
16
|
+
write: () => { },
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export function createBufferedOutput() {
|
|
20
|
+
const stdoutLines = [];
|
|
21
|
+
const stderrLines = [];
|
|
22
|
+
return {
|
|
23
|
+
log(message = '') {
|
|
24
|
+
stdoutLines.push(message);
|
|
25
|
+
},
|
|
26
|
+
error(message = '') {
|
|
27
|
+
stderrLines.push(message);
|
|
28
|
+
},
|
|
29
|
+
write(chunk) {
|
|
30
|
+
stdoutLines.push(chunk);
|
|
31
|
+
},
|
|
32
|
+
stdoutLines,
|
|
33
|
+
stderrLines,
|
|
34
|
+
stdout: () => stdoutLines.join('\n'),
|
|
35
|
+
stderr: () => stderrLines.join('\n'),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import fsSync from 'node:fs';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { CliError } from '../errors.js';
|
|
6
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
7
|
+
const __dirname = path.dirname(__filename);
|
|
8
|
+
/**
|
|
9
|
+
* Candidate package root directories across:
|
|
10
|
+
* - published/compiled `dist/utils/package-paths.js` -> `dist`
|
|
11
|
+
* - local `src/utils/package-paths.ts` -> `<repo>`
|
|
12
|
+
* - test builds `.test-dist/src/utils/package-paths.js` -> `<repo>`
|
|
13
|
+
*/
|
|
14
|
+
function getPackageRootCandidates() {
|
|
15
|
+
return [
|
|
16
|
+
path.resolve(__dirname, '..'),
|
|
17
|
+
path.resolve(__dirname, '..', '..'),
|
|
18
|
+
path.resolve(__dirname, '..', '..', '..'),
|
|
19
|
+
];
|
|
20
|
+
}
|
|
21
|
+
export function readPackageVersion() {
|
|
22
|
+
for (const root of getPackageRootCandidates()) {
|
|
23
|
+
const candidate = path.join(root, 'package.json');
|
|
24
|
+
try {
|
|
25
|
+
const pkg = JSON.parse(fsSync.readFileSync(candidate, 'utf8'));
|
|
26
|
+
if (pkg.version && (!pkg.name || pkg.name === 'codepen-commander')) {
|
|
27
|
+
return pkg.version;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
// Try next candidate
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return '0.0.0';
|
|
35
|
+
}
|
|
36
|
+
export async function resolveBuiltinShellDir() {
|
|
37
|
+
for (const root of getPackageRootCandidates()) {
|
|
38
|
+
const candidate = path.join(root, 'shell');
|
|
39
|
+
try {
|
|
40
|
+
const stat = await fs.stat(path.join(candidate, 'index.html'));
|
|
41
|
+
if (stat.isFile()) {
|
|
42
|
+
const realpath = await fs.realpath(candidate);
|
|
43
|
+
return { dir: candidate, realpath };
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
// Try next candidate
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
throw new CliError(500, 'Built-in shell assets could not be located in the codepen-commander package.');
|
|
51
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { PromptCanceledError, isInteractive, isPromptCanceledError, } from './types.js';
|
|
2
|
+
export { promptText, promptTextWithIO, promptValidatedTextWithIO } from './text.js';
|
|
3
|
+
export { promptConfirm, promptConfirmWithIO, promptSelect, promptSelectWithIO, } from './select.js';
|
|
4
|
+
export { promptMultiSelect, promptMultiSelectWithIO } from './multi-select.js';
|
|
5
|
+
export { promptSecret } from './secret.js';
|