codepen-demokit 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/README.md +229 -2
- package/bin/cli.mjs +154 -0
- package/lib/build-json.mjs +439 -0
- package/lib/build-site.mjs +193 -0
- package/lib/config.mjs +245 -0
- package/lib/init.mjs +651 -0
- package/lib/serve.mjs +369 -0
- package/lib/sync-codepen.mjs +1326 -0
- package/package.json +35 -4
- package/shell/index.html +48 -0
- package/shell/scripts.js +201 -0
- package/shell/styles.css +299 -0
- package/templates/AGENTS.md +76 -0
- package/templates/README.md +62 -0
- package/templates/config.json.example +10 -0
- package/templates/gitignore +27 -0
|
@@ -0,0 +1,1326 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import {
|
|
7
|
+
PROFILE_NAME_PATTERN,
|
|
8
|
+
loadCodePenConfig,
|
|
9
|
+
loadCodePenProfile,
|
|
10
|
+
} from './config.mjs';
|
|
11
|
+
|
|
12
|
+
const CONFIG_FILENAME = '.cdpn.json';
|
|
13
|
+
const IGNORE_FILENAME = '.cdpnignore';
|
|
14
|
+
const MAX_SCAN_DEPTH = 4;
|
|
15
|
+
const BUILTIN_IGNORED_SEGMENTS = new Set([
|
|
16
|
+
CONFIG_FILENAME,
|
|
17
|
+
IGNORE_FILENAME,
|
|
18
|
+
'.git',
|
|
19
|
+
'.svn',
|
|
20
|
+
'.hg',
|
|
21
|
+
'node_modules',
|
|
22
|
+
'.DS_Store',
|
|
23
|
+
'Thumbs.db',
|
|
24
|
+
'desktop.ini',
|
|
25
|
+
]);
|
|
26
|
+
|
|
27
|
+
const require = createRequire(import.meta.url);
|
|
28
|
+
|
|
29
|
+
function usage() {
|
|
30
|
+
console.error(
|
|
31
|
+
'Usage:\n' +
|
|
32
|
+
' codepen-demokit cdpn <push|pull|sync|delete> [folder-in-src] [--dry-run] [--force]\n' +
|
|
33
|
+
' codepen-demokit cdpn clone [options] <url> [folder]'
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function isSemverAtLeast(version, minVersion) {
|
|
38
|
+
const parse = (raw) => {
|
|
39
|
+
const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(raw ?? '').trim());
|
|
40
|
+
return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
|
|
41
|
+
};
|
|
42
|
+
const current = parse(version);
|
|
43
|
+
const minimum = parse(minVersion);
|
|
44
|
+
if (!current || !minimum) return true;
|
|
45
|
+
for (let i = 0; i < 3; i++) {
|
|
46
|
+
if (current[i] !== minimum[i]) return current[i] > minimum[i];
|
|
47
|
+
}
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function parseArgs(argv) {
|
|
52
|
+
let mode = null;
|
|
53
|
+
let targetFolder = null;
|
|
54
|
+
let dryRun = false;
|
|
55
|
+
let force = false;
|
|
56
|
+
|
|
57
|
+
for (const arg of argv) {
|
|
58
|
+
if (arg === '--dry-run') {
|
|
59
|
+
dryRun = true;
|
|
60
|
+
} else if (arg === '--force' || arg === '-f') {
|
|
61
|
+
force = true;
|
|
62
|
+
} else if (arg === '-h' || arg === '--help') {
|
|
63
|
+
usage();
|
|
64
|
+
process.exit(0);
|
|
65
|
+
} else if (arg.startsWith('-')) {
|
|
66
|
+
console.error(`Error: Unknown option '${arg}'.`);
|
|
67
|
+
usage();
|
|
68
|
+
process.exit(1);
|
|
69
|
+
} else if (!mode) {
|
|
70
|
+
if (arg === 'push' || arg === 'pull' || arg === 'sync' || arg === 'delete') {
|
|
71
|
+
mode = arg;
|
|
72
|
+
} else {
|
|
73
|
+
console.error(
|
|
74
|
+
`Error: Unknown mode '${arg}' (expected 'push', 'pull', 'sync', 'delete', or 'clone').`
|
|
75
|
+
);
|
|
76
|
+
usage();
|
|
77
|
+
process.exit(1);
|
|
78
|
+
}
|
|
79
|
+
} else {
|
|
80
|
+
if (targetFolder !== null) {
|
|
81
|
+
console.error(
|
|
82
|
+
`Error: Multiple target folders specified ('${targetFolder}' and '${arg}').`
|
|
83
|
+
);
|
|
84
|
+
usage();
|
|
85
|
+
process.exit(1);
|
|
86
|
+
}
|
|
87
|
+
targetFolder = arg;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (!mode) {
|
|
92
|
+
console.error(
|
|
93
|
+
"Error: Missing mode (expected 'push', 'pull', 'sync', 'delete', or 'clone')."
|
|
94
|
+
);
|
|
95
|
+
usage();
|
|
96
|
+
process.exit(1);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (force && mode !== 'pull') {
|
|
100
|
+
console.error("Error: --force is only supported with 'pull'.");
|
|
101
|
+
usage();
|
|
102
|
+
process.exit(1);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return { mode, targetFolder, dryRun, force };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function spawnCdpn(cdpn, args, cwd) {
|
|
109
|
+
return spawnSync(cdpn.command, [...cdpn.prefixArgs, ...args], {
|
|
110
|
+
cwd,
|
|
111
|
+
encoding: 'utf8',
|
|
112
|
+
shell: cdpn.shell,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function findCodePenCommanderCli(projectDir) {
|
|
117
|
+
// 1. Prefer consumer project's own installed codepen-commander (supports npm/pnpm/yarn upgrades)
|
|
118
|
+
const projectPkgPath = path.join(projectDir, 'package.json');
|
|
119
|
+
if (fs.existsSync(projectPkgPath)) {
|
|
120
|
+
try {
|
|
121
|
+
const projectRequire = createRequire(projectPkgPath);
|
|
122
|
+
const pkgPath = projectRequire.resolve('codepen-commander/package.json');
|
|
123
|
+
const cliPath = path.join(path.dirname(pkgPath), 'cli.js');
|
|
124
|
+
if (fs.existsSync(cliPath)) {
|
|
125
|
+
return { cliPath, source: 'project node_modules' };
|
|
126
|
+
}
|
|
127
|
+
} catch {
|
|
128
|
+
// Fall through to bundled dependency
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// 2. Fallback: bundled dependency of codepen-demokit (e.g. during `npx codepen-demokit init` before `npm install`)
|
|
133
|
+
try {
|
|
134
|
+
const pkgPath = require.resolve('codepen-commander/package.json');
|
|
135
|
+
const cliPath = path.join(path.dirname(pkgPath), 'cli.js');
|
|
136
|
+
if (fs.existsSync(cliPath)) {
|
|
137
|
+
return { cliPath, source: 'codepen-commander' };
|
|
138
|
+
}
|
|
139
|
+
} catch {
|
|
140
|
+
// Fall through to PATH
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function locateCdpnBinary(projectDir = process.cwd()) {
|
|
147
|
+
const resolved = findCodePenCommanderCli(projectDir);
|
|
148
|
+
const cdpn = resolved
|
|
149
|
+
? {
|
|
150
|
+
command: process.execPath,
|
|
151
|
+
prefixArgs: [resolved.cliPath],
|
|
152
|
+
shell: false,
|
|
153
|
+
}
|
|
154
|
+
: {
|
|
155
|
+
command: 'cdpn',
|
|
156
|
+
prefixArgs: [],
|
|
157
|
+
// On Windows, a globally installed `cdpn` is a `.cmd` shim on PATH, which
|
|
158
|
+
// throws EINVAL on Node >= 20.12.2 when spawned with `shell: false`.
|
|
159
|
+
// All arguments passed to `cdpn` are hardcoded literals or strictly allow-listed.
|
|
160
|
+
shell: process.platform === 'win32',
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
const check = spawnCdpn(cdpn, ['--version'], projectDir);
|
|
164
|
+
if (check.error || check.status !== 0) {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
return {
|
|
169
|
+
bin: cdpn,
|
|
170
|
+
source: resolved ? resolved.source : 'PATH',
|
|
171
|
+
version: (check.stdout || '').trim() || 'unknown',
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function resolveCdpnBinary(projectDir) {
|
|
176
|
+
const located = locateCdpnBinary(projectDir);
|
|
177
|
+
if (!located) {
|
|
178
|
+
console.error(
|
|
179
|
+
"Error: 'cdpn' (CodePen Commander) is required but was not found or failed to run."
|
|
180
|
+
);
|
|
181
|
+
console.error('Run `npm install` to install project dependencies.');
|
|
182
|
+
process.exit(1);
|
|
183
|
+
}
|
|
184
|
+
return located;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function runCdpnJson(cdpnBin, args, cwd) {
|
|
188
|
+
const result = spawnCdpn(cdpnBin, args, cwd);
|
|
189
|
+
|
|
190
|
+
if (result.error) {
|
|
191
|
+
return {
|
|
192
|
+
ok: false,
|
|
193
|
+
exitCode: 1,
|
|
194
|
+
json: null,
|
|
195
|
+
errorMessage: result.error.message,
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const rawStdout = (result.stdout || '').trim();
|
|
200
|
+
const rawStderr = (result.stderr || '').trim();
|
|
201
|
+
let parsed = null;
|
|
202
|
+
|
|
203
|
+
if (rawStdout) {
|
|
204
|
+
try {
|
|
205
|
+
parsed = JSON.parse(rawStdout);
|
|
206
|
+
} catch {
|
|
207
|
+
const firstBrace = rawStdout.indexOf('{');
|
|
208
|
+
if (firstBrace !== -1) {
|
|
209
|
+
try {
|
|
210
|
+
parsed = JSON.parse(rawStdout.slice(firstBrace));
|
|
211
|
+
} catch {
|
|
212
|
+
parsed = null;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const statusCode = parsed?.status?.code ?? null;
|
|
219
|
+
const ok =
|
|
220
|
+
result.status === 0 &&
|
|
221
|
+
parsed !== null &&
|
|
222
|
+
typeof statusCode === 'number' &&
|
|
223
|
+
statusCode >= 200 &&
|
|
224
|
+
statusCode < 300;
|
|
225
|
+
|
|
226
|
+
return {
|
|
227
|
+
ok,
|
|
228
|
+
exitCode: result.status ?? 1,
|
|
229
|
+
json: parsed,
|
|
230
|
+
errorMessage:
|
|
231
|
+
parsed?.status?.message ||
|
|
232
|
+
rawStderr ||
|
|
233
|
+
rawStdout ||
|
|
234
|
+
`cdpn exited with code ${result.status ?? 1}`,
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function verifyProfileAuth(cdpnBin, requiredProfile, projectDir) {
|
|
239
|
+
const res = runCdpnJson(cdpnBin, ['auth', 'status', '--json'], projectDir);
|
|
240
|
+
if (!res.json) {
|
|
241
|
+
console.error(`Error: Failed to check cdpn auth status: ${res.errorMessage}`);
|
|
242
|
+
process.exit(1);
|
|
243
|
+
}
|
|
244
|
+
const profiles = Array.isArray(res.json.contents?.profiles)
|
|
245
|
+
? res.json.contents.profiles
|
|
246
|
+
: [];
|
|
247
|
+
const targetProfile = profiles.find((p) => p?.name === requiredProfile);
|
|
248
|
+
|
|
249
|
+
if (!targetProfile) {
|
|
250
|
+
console.error(
|
|
251
|
+
`Error: CodePen profile "${requiredProfile}" is not configured in cdpn.`
|
|
252
|
+
);
|
|
253
|
+
if (profiles.length > 0) {
|
|
254
|
+
const names = profiles.map((p) => p.name).filter(Boolean).join(', ');
|
|
255
|
+
console.error(` Configured profiles: ${names}`);
|
|
256
|
+
}
|
|
257
|
+
console.error(` Run: npx cdpn auth login ${requiredProfile}`);
|
|
258
|
+
process.exit(1);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
if (targetProfile.verified !== true) {
|
|
262
|
+
console.error(
|
|
263
|
+
`Error: CodePen profile "${requiredProfile}" failed authentication verification.`
|
|
264
|
+
);
|
|
265
|
+
if (targetProfile.verification_error) {
|
|
266
|
+
console.error(` Detail: ${targetProfile.verification_error}`);
|
|
267
|
+
}
|
|
268
|
+
console.error(` Re-authenticate with: npx cdpn auth login ${requiredProfile}`);
|
|
269
|
+
process.exit(1);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
return {
|
|
273
|
+
name: targetProfile.name,
|
|
274
|
+
keyType: targetProfile.key_type || 'unknown',
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function resolveTargetDir(resolvedDemosDir, targetFolder) {
|
|
279
|
+
if (!targetFolder) {
|
|
280
|
+
return { absDir: resolvedDemosDir, segments: [], relPrefix: null };
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
if (
|
|
284
|
+
targetFolder.includes('\0') ||
|
|
285
|
+
targetFolder.includes('\\') ||
|
|
286
|
+
path.isAbsolute(targetFolder)
|
|
287
|
+
) {
|
|
288
|
+
console.error(
|
|
289
|
+
`Error: Invalid folder "${targetFolder}": pass a relative folder path inside src/.`
|
|
290
|
+
);
|
|
291
|
+
process.exit(1);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
const trimmed = targetFolder.replace(/\/+$/, '');
|
|
295
|
+
if (!trimmed) {
|
|
296
|
+
return { absDir: resolvedDemosDir, segments: [], relPrefix: null };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const segments = trimmed.split('/').filter(Boolean);
|
|
300
|
+
for (const segment of segments) {
|
|
301
|
+
if (segment === '.' || segment === '..' || segment.startsWith('.')) {
|
|
302
|
+
console.error(
|
|
303
|
+
`Error: Invalid folder "${targetFolder}": path traversal and hidden folders are not allowed.`
|
|
304
|
+
);
|
|
305
|
+
process.exit(1);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const candidateDir = path.resolve(resolvedDemosDir, ...segments);
|
|
310
|
+
if (!candidateDir.startsWith(resolvedDemosDir + path.sep)) {
|
|
311
|
+
console.error(
|
|
312
|
+
`Error: Invalid folder "${targetFolder}": must resolve within src/.`
|
|
313
|
+
);
|
|
314
|
+
process.exit(1);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
let stat;
|
|
318
|
+
try {
|
|
319
|
+
stat = fs.lstatSync(candidateDir);
|
|
320
|
+
} catch {
|
|
321
|
+
console.error(`Error: Folder "src/${segments.join('/')}" does not exist.`);
|
|
322
|
+
process.exit(1);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
326
|
+
console.error(
|
|
327
|
+
`Error: "src/${segments.join('/')}" is not a regular directory.`
|
|
328
|
+
);
|
|
329
|
+
process.exit(1);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const realTargetDir = fs.realpathSync(candidateDir);
|
|
333
|
+
if (!realTargetDir.startsWith(resolvedDemosDir + path.sep)) {
|
|
334
|
+
console.error(
|
|
335
|
+
`Error: Invalid folder "${targetFolder}": resolves outside src/.`
|
|
336
|
+
);
|
|
337
|
+
process.exit(1);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
return {
|
|
341
|
+
absDir: realTargetDir,
|
|
342
|
+
segments,
|
|
343
|
+
relPrefix: segments.join('/'),
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function discoverDemoDirs(demosDir, targetFolder = null) {
|
|
348
|
+
if (!fs.existsSync(demosDir)) {
|
|
349
|
+
console.error(`Error: src directory not found at ${demosDir}.`);
|
|
350
|
+
process.exit(1);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const resolvedDemosDir = fs.realpathSync(path.resolve(demosDir));
|
|
354
|
+
const target = resolveTargetDir(resolvedDemosDir, targetFolder);
|
|
355
|
+
const demos = [];
|
|
356
|
+
|
|
357
|
+
function inspectFolderForDemo(dirPath, segments) {
|
|
358
|
+
const indexPath = path.join(dirPath, 'index.html');
|
|
359
|
+
const configPath = path.join(dirPath, CONFIG_FILENAME);
|
|
360
|
+
const hasIndex =
|
|
361
|
+
fs.existsSync(indexPath) && fs.lstatSync(indexPath).isFile();
|
|
362
|
+
const hasConfig =
|
|
363
|
+
fs.existsSync(configPath) && fs.lstatSync(configPath).isFile();
|
|
364
|
+
|
|
365
|
+
if (!hasIndex && !hasConfig) return null;
|
|
366
|
+
|
|
367
|
+
return {
|
|
368
|
+
relPath: segments.join('/'),
|
|
369
|
+
absPath: dirPath,
|
|
370
|
+
hasIndex,
|
|
371
|
+
hasConfig,
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function walk(currentDir, segments, depth) {
|
|
376
|
+
if (depth > MAX_SCAN_DEPTH) return;
|
|
377
|
+
|
|
378
|
+
for (const entry of fs.readdirSync(currentDir, { withFileTypes: true })) {
|
|
379
|
+
if (!entry.isDirectory()) continue;
|
|
380
|
+
if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
|
|
381
|
+
|
|
382
|
+
const childPath = path.resolve(currentDir, entry.name);
|
|
383
|
+
if (!childPath.startsWith(resolvedDemosDir + path.sep)) continue;
|
|
384
|
+
if (fs.lstatSync(childPath).isSymbolicLink()) continue;
|
|
385
|
+
|
|
386
|
+
const childSegments = [...segments, entry.name];
|
|
387
|
+
const demo = inspectFolderForDemo(childPath, childSegments);
|
|
388
|
+
if (demo) {
|
|
389
|
+
demos.push(demo);
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
walk(childPath, childSegments, depth + 1);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
if (target.segments.length > 0) {
|
|
398
|
+
const directDemo = inspectFolderForDemo(target.absDir, target.segments);
|
|
399
|
+
if (directDemo) {
|
|
400
|
+
demos.push(directDemo);
|
|
401
|
+
} else {
|
|
402
|
+
walk(target.absDir, target.segments, target.segments.length + 1);
|
|
403
|
+
}
|
|
404
|
+
} else {
|
|
405
|
+
walk(resolvedDemosDir, [], 1);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
demos.sort((a, b) =>
|
|
409
|
+
a.relPath.localeCompare(b.relPath, 'en', {
|
|
410
|
+
numeric: true,
|
|
411
|
+
sensitivity: 'base',
|
|
412
|
+
})
|
|
413
|
+
);
|
|
414
|
+
return { demos, scope: target.relPrefix };
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function escapeRegex(str) {
|
|
418
|
+
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function loadIgnoreMatchers(rootDir) {
|
|
422
|
+
const ignorePath = path.join(rootDir, IGNORE_FILENAME);
|
|
423
|
+
if (!fs.existsSync(ignorePath)) return [];
|
|
424
|
+
const raw = fs.readFileSync(ignorePath, 'utf8');
|
|
425
|
+
const matchers = [];
|
|
426
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
427
|
+
const trimmed = line.trim();
|
|
428
|
+
if (!trimmed || trimmed.startsWith('#')) continue;
|
|
429
|
+
const normalized = trimmed.replace(/^\/+/, '').replace(/\/+$/, '');
|
|
430
|
+
if (!normalized) continue;
|
|
431
|
+
const hasSlash = normalized.includes('/');
|
|
432
|
+
const regexBody = normalized
|
|
433
|
+
.split('**')
|
|
434
|
+
.map((part) => part.split('*').map(escapeRegex).join('[^/]*'))
|
|
435
|
+
.join('.*');
|
|
436
|
+
matchers.push(
|
|
437
|
+
hasSlash
|
|
438
|
+
? new RegExp(`^/${regexBody}(?:/.*)?$`)
|
|
439
|
+
: new RegExp(`(?:^|/)${regexBody}(?:/.*)?$`)
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
return matchers;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function scanLocalFileHashes(rootDir) {
|
|
446
|
+
const resolvedRoot = path.resolve(rootDir);
|
|
447
|
+
const customMatchers = loadIgnoreMatchers(resolvedRoot);
|
|
448
|
+
const hashes = new Map();
|
|
449
|
+
|
|
450
|
+
function walk(currentDir, relativePrefix) {
|
|
451
|
+
for (const entry of fs.readdirSync(currentDir, { withFileTypes: true })) {
|
|
452
|
+
if (BUILTIN_IGNORED_SEGMENTS.has(entry.name)) continue;
|
|
453
|
+
const penPath = relativePrefix
|
|
454
|
+
? `${relativePrefix}/${entry.name}`
|
|
455
|
+
: `/${entry.name}`;
|
|
456
|
+
if (customMatchers.some((re) => re.test(penPath))) continue;
|
|
457
|
+
|
|
458
|
+
const fullPath = path.resolve(currentDir, entry.name);
|
|
459
|
+
if (!fullPath.startsWith(resolvedRoot + path.sep)) continue;
|
|
460
|
+
|
|
461
|
+
const stat = fs.lstatSync(fullPath);
|
|
462
|
+
if (stat.isSymbolicLink()) continue;
|
|
463
|
+
|
|
464
|
+
if (stat.isDirectory()) {
|
|
465
|
+
walk(fullPath, penPath);
|
|
466
|
+
} else if (stat.isFile()) {
|
|
467
|
+
const buf = fs.readFileSync(fullPath);
|
|
468
|
+
const sha256 = crypto.createHash('sha256').update(buf).digest('hex');
|
|
469
|
+
hashes.set(penPath, sha256);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
walk(resolvedRoot, '');
|
|
475
|
+
return hashes;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
function detectLocalChanges(demoDir, baselineFiles) {
|
|
479
|
+
if (!baselineFiles || typeof baselineFiles !== 'object' || Array.isArray(baselineFiles)) {
|
|
480
|
+
return {
|
|
481
|
+
knownBaseline: false,
|
|
482
|
+
hasChanges: null,
|
|
483
|
+
added: [],
|
|
484
|
+
modified: [],
|
|
485
|
+
deleted: [],
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
const localHashes = scanLocalFileHashes(demoDir);
|
|
490
|
+
const added = [];
|
|
491
|
+
const modified = [];
|
|
492
|
+
const deleted = [];
|
|
493
|
+
|
|
494
|
+
for (const [filePath, sha256] of localHashes) {
|
|
495
|
+
const base = baselineFiles[filePath];
|
|
496
|
+
if (!base) {
|
|
497
|
+
added.push(filePath);
|
|
498
|
+
} else if (base.local_sha256 !== sha256) {
|
|
499
|
+
modified.push(filePath);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
for (const filePath of Object.keys(baselineFiles)) {
|
|
504
|
+
if (!localHashes.has(filePath)) {
|
|
505
|
+
deleted.push(filePath);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
added.sort();
|
|
510
|
+
modified.sort();
|
|
511
|
+
deleted.sort();
|
|
512
|
+
|
|
513
|
+
return {
|
|
514
|
+
knownBaseline: true,
|
|
515
|
+
hasChanges: added.length + modified.length + deleted.length > 0,
|
|
516
|
+
added,
|
|
517
|
+
modified,
|
|
518
|
+
deleted,
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
function extractHtmlTitle(demoDir) {
|
|
523
|
+
const indexPath = path.join(demoDir, 'index.html');
|
|
524
|
+
if (!fs.existsSync(indexPath)) return null;
|
|
525
|
+
const html = fs.readFileSync(indexPath, 'utf8');
|
|
526
|
+
const match = html.match(/<title\b[^>]{0,200}>([\s\S]{0,500}?)<\/title>/i);
|
|
527
|
+
return match ? match[1].replace(/\s+/g, ' ').trim() : null;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function shortId(id) {
|
|
531
|
+
if (!id) return 'none';
|
|
532
|
+
return id.length > 12 ? `${id.slice(0, 8)}…` : id;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
function formatChangesList(changes, indent = ' ') {
|
|
536
|
+
const lines = [];
|
|
537
|
+
for (const p of changes.added || []) lines.push(`${indent}+ ${p}`);
|
|
538
|
+
for (const p of changes.modified || []) lines.push(`${indent}~ ${p}`);
|
|
539
|
+
for (const p of changes.deleted || []) lines.push(`${indent}- ${p}`);
|
|
540
|
+
return lines;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
function readAndValidateConfig(demo, requiredProfile) {
|
|
544
|
+
let config;
|
|
545
|
+
try {
|
|
546
|
+
config = JSON.parse(
|
|
547
|
+
fs.readFileSync(path.join(demo.absPath, CONFIG_FILENAME), 'utf8')
|
|
548
|
+
);
|
|
549
|
+
} catch (err) {
|
|
550
|
+
return {
|
|
551
|
+
ok: false,
|
|
552
|
+
message: `Failed to read ${CONFIG_FILENAME}: ${err.message}`,
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
if (!config || typeof config !== 'object' || Array.isArray(config)) {
|
|
557
|
+
return {
|
|
558
|
+
ok: false,
|
|
559
|
+
message: `Invalid ${CONFIG_FILENAME}: expected a JSON object.`,
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
// Unlinked info-only `.cdpn.json` (e.g. retained after `cdpn delete --keep-info`)
|
|
564
|
+
if (
|
|
565
|
+
config.pen_id === undefined &&
|
|
566
|
+
config.url === undefined &&
|
|
567
|
+
config.info !== undefined
|
|
568
|
+
) {
|
|
569
|
+
return { ok: true, linked: false, config };
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
if (config.profile && config.profile !== requiredProfile) {
|
|
573
|
+
return {
|
|
574
|
+
ok: false,
|
|
575
|
+
message: `${CONFIG_FILENAME} is linked to profile "${config.profile}" instead of "${requiredProfile}".`,
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
return { ok: true, linked: true, config };
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
function inspectDemo(cdpnBin, demo, requiredProfile) {
|
|
583
|
+
if (!demo.hasConfig) {
|
|
584
|
+
return {
|
|
585
|
+
state: 'unlinked',
|
|
586
|
+
title: extractHtmlTitle(demo.absPath) || path.basename(demo.absPath),
|
|
587
|
+
hasRetainedInfo: false,
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
const configRes = readAndValidateConfig(demo, requiredProfile);
|
|
592
|
+
if (!configRes.ok) {
|
|
593
|
+
return {
|
|
594
|
+
state: 'error',
|
|
595
|
+
message: configRes.message,
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
const { config, linked } = configRes;
|
|
599
|
+
|
|
600
|
+
if (!linked) {
|
|
601
|
+
return {
|
|
602
|
+
state: 'unlinked',
|
|
603
|
+
title:
|
|
604
|
+
(typeof config.info?.title === 'string' && config.info.title.trim()) ||
|
|
605
|
+
extractHtmlTitle(demo.absPath) ||
|
|
606
|
+
path.basename(demo.absPath),
|
|
607
|
+
hasRetainedInfo: true,
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
const statusRes = runCdpnJson(
|
|
612
|
+
cdpnBin,
|
|
613
|
+
['--profile', requiredProfile, 'status', '--json'],
|
|
614
|
+
demo.absPath
|
|
615
|
+
);
|
|
616
|
+
|
|
617
|
+
if (!statusRes.ok) {
|
|
618
|
+
return {
|
|
619
|
+
state: 'error',
|
|
620
|
+
message: `cdpn status failed: ${statusRes.errorMessage}`,
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
const data = statusRes.json.contents;
|
|
625
|
+
const remoteAhead = Boolean(data.remote_ahead);
|
|
626
|
+
const diffChanges = data.changes || { added: [], modified: [], deleted: [] };
|
|
627
|
+
const diffCount =
|
|
628
|
+
(diffChanges.added?.length || 0) +
|
|
629
|
+
(diffChanges.modified?.length || 0) +
|
|
630
|
+
(diffChanges.deleted?.length || 0);
|
|
631
|
+
const infoChanges = Array.isArray(data.info_changes) ? data.info_changes : [];
|
|
632
|
+
const infoCount = infoChanges.length;
|
|
633
|
+
const localInfoChanged = Boolean(data.info_local_changed) && infoCount > 0;
|
|
634
|
+
const remoteInfoChanged = Boolean(data.info_remote_changed) && infoCount > 0;
|
|
635
|
+
const localBaseline = detectLocalChanges(demo.absPath, config.files);
|
|
636
|
+
const localFilesEdited = localBaseline.knownBaseline
|
|
637
|
+
? localBaseline.hasChanges
|
|
638
|
+
: diffCount > 0;
|
|
639
|
+
|
|
640
|
+
const localChanged =
|
|
641
|
+
(!remoteAhead && diffCount > 0) ||
|
|
642
|
+
(remoteAhead && localFilesEdited && diffCount > 0) ||
|
|
643
|
+
localInfoChanged;
|
|
644
|
+
const remoteChanged = remoteAhead || remoteInfoChanged;
|
|
645
|
+
|
|
646
|
+
let state;
|
|
647
|
+
if (!localChanged && !remoteChanged) {
|
|
648
|
+
state = 'up-to-date';
|
|
649
|
+
} else if (localChanged && !remoteChanged) {
|
|
650
|
+
state = 'local-ahead';
|
|
651
|
+
} else if (!localChanged && remoteChanged) {
|
|
652
|
+
state =
|
|
653
|
+
diffCount === 0 && !remoteInfoChanged
|
|
654
|
+
? 'remote-metadata-ahead'
|
|
655
|
+
: 'remote-ahead';
|
|
656
|
+
} else {
|
|
657
|
+
state = 'conflict';
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
return {
|
|
661
|
+
state,
|
|
662
|
+
config,
|
|
663
|
+
status: data,
|
|
664
|
+
diffChanges,
|
|
665
|
+
diffCount,
|
|
666
|
+
infoChanges,
|
|
667
|
+
infoCount,
|
|
668
|
+
localBaseline,
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
function hasHelpFlag(argv) {
|
|
673
|
+
for (const arg of argv) {
|
|
674
|
+
if (arg === '--') break;
|
|
675
|
+
if (arg === '-h' || arg === '--help') return true;
|
|
676
|
+
}
|
|
677
|
+
return false;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
function normalizeCloneFolderArg(rawFolder, demosRealpath) {
|
|
681
|
+
if (
|
|
682
|
+
rawFolder.includes('\0') ||
|
|
683
|
+
rawFolder.includes('\\') ||
|
|
684
|
+
path.isAbsolute(rawFolder)
|
|
685
|
+
) {
|
|
686
|
+
console.error(
|
|
687
|
+
`Error: Invalid folder "${rawFolder}": pass a relative folder path inside src/.`
|
|
688
|
+
);
|
|
689
|
+
process.exit(1);
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
let normalized = rawFolder;
|
|
693
|
+
while (normalized.startsWith('./')) {
|
|
694
|
+
normalized = normalized.slice(2);
|
|
695
|
+
}
|
|
696
|
+
if (normalized === 'src' || normalized === 'src/') {
|
|
697
|
+
console.error(
|
|
698
|
+
`Error: Invalid folder "${rawFolder}": specify a demo subfolder inside src/ (e.g., "my-demo" or "group/my-demo").`
|
|
699
|
+
);
|
|
700
|
+
process.exit(1);
|
|
701
|
+
}
|
|
702
|
+
if (normalized.startsWith('src/')) {
|
|
703
|
+
normalized = normalized.slice(4);
|
|
704
|
+
}
|
|
705
|
+
normalized = normalized.replace(/\/+$/, '');
|
|
706
|
+
|
|
707
|
+
if (!normalized || normalized === '.') {
|
|
708
|
+
console.error(
|
|
709
|
+
`Error: Invalid folder "${rawFolder}": specify a demo subfolder inside src/ (e.g., "my-demo" or "group/my-demo").`
|
|
710
|
+
);
|
|
711
|
+
process.exit(1);
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
const segments = normalized.split('/').filter(Boolean);
|
|
715
|
+
for (const segment of segments) {
|
|
716
|
+
if (segment === '.' || segment === '..' || segment.startsWith('.')) {
|
|
717
|
+
console.error(
|
|
718
|
+
`Error: Invalid folder "${rawFolder}": path traversal and hidden folders are not allowed.`
|
|
719
|
+
);
|
|
720
|
+
process.exit(1);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
const candidateDir = path.resolve(demosRealpath, ...segments);
|
|
725
|
+
if (!candidateDir.startsWith(demosRealpath + path.sep)) {
|
|
726
|
+
console.error(
|
|
727
|
+
`Error: Invalid folder "${rawFolder}": must resolve within src/.`
|
|
728
|
+
);
|
|
729
|
+
process.exit(1);
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
// Ensure no existing path component inside src/ is a symlink escaping src/
|
|
733
|
+
let probe = candidateDir;
|
|
734
|
+
while (probe !== demosRealpath) {
|
|
735
|
+
if (fs.existsSync(probe)) {
|
|
736
|
+
const stat = fs.lstatSync(probe);
|
|
737
|
+
if (stat.isSymbolicLink()) {
|
|
738
|
+
console.error(
|
|
739
|
+
`Error: Invalid folder "${rawFolder}": symbolic links are not allowed.`
|
|
740
|
+
);
|
|
741
|
+
process.exit(1);
|
|
742
|
+
}
|
|
743
|
+
const realProbe = fs.realpathSync(probe);
|
|
744
|
+
if (!realProbe.startsWith(demosRealpath + path.sep)) {
|
|
745
|
+
console.error(
|
|
746
|
+
`Error: Invalid folder "${rawFolder}": resolves outside src/.`
|
|
747
|
+
);
|
|
748
|
+
process.exit(1);
|
|
749
|
+
}
|
|
750
|
+
break;
|
|
751
|
+
}
|
|
752
|
+
const parent = path.dirname(probe);
|
|
753
|
+
if (parent === probe) break;
|
|
754
|
+
probe = parent;
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
return segments.join('/');
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
function parseCloneArgs(argv, demosRealpath) {
|
|
761
|
+
let explicitProfile = null;
|
|
762
|
+
let afterDoubleDash = false;
|
|
763
|
+
let positionalCount = 0;
|
|
764
|
+
const forwardedArgs = [];
|
|
765
|
+
|
|
766
|
+
for (let i = 0; i < argv.length; i++) {
|
|
767
|
+
const arg = argv[i];
|
|
768
|
+
|
|
769
|
+
if (!afterDoubleDash && arg === '--') {
|
|
770
|
+
afterDoubleDash = true;
|
|
771
|
+
forwardedArgs.push(arg);
|
|
772
|
+
continue;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
if (!afterDoubleDash && arg === '--profile') {
|
|
776
|
+
const next = argv[i + 1];
|
|
777
|
+
if (!next || next.startsWith('-')) {
|
|
778
|
+
console.error("Error: Missing value for '--profile'.");
|
|
779
|
+
process.exit(1);
|
|
780
|
+
}
|
|
781
|
+
const trimmed = next.trim();
|
|
782
|
+
if (!PROFILE_NAME_PATTERN.test(trimmed)) {
|
|
783
|
+
console.error(`Error: Invalid '--profile' value "${next}".`);
|
|
784
|
+
process.exit(1);
|
|
785
|
+
}
|
|
786
|
+
explicitProfile = trimmed;
|
|
787
|
+
i++;
|
|
788
|
+
continue;
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
if (!afterDoubleDash && arg.startsWith('--profile=')) {
|
|
792
|
+
const trimmed = arg.slice('--profile='.length).trim();
|
|
793
|
+
if (!trimmed || !PROFILE_NAME_PATTERN.test(trimmed)) {
|
|
794
|
+
console.error(`Error: Invalid '--profile' value "${trimmed}".`);
|
|
795
|
+
process.exit(1);
|
|
796
|
+
}
|
|
797
|
+
explicitProfile = trimmed;
|
|
798
|
+
continue;
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
if (!afterDoubleDash && arg.startsWith('-')) {
|
|
802
|
+
forwardedArgs.push(arg);
|
|
803
|
+
continue;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
// Positional args: 0 = <url>, 1 = [folder]
|
|
807
|
+
if (positionalCount === 1) {
|
|
808
|
+
forwardedArgs.push(normalizeCloneFolderArg(arg, demosRealpath));
|
|
809
|
+
} else {
|
|
810
|
+
forwardedArgs.push(arg);
|
|
811
|
+
}
|
|
812
|
+
positionalCount++;
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
return { explicitProfile, forwardedArgs };
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
export function runCodePenClone(argv, { projectDir = process.cwd() } = {}) {
|
|
819
|
+
const resolvedProjectDir = path.resolve(projectDir);
|
|
820
|
+
const { bin: cdpnBin } = resolveCdpnBinary(resolvedProjectDir);
|
|
821
|
+
|
|
822
|
+
if (hasHelpFlag(argv)) {
|
|
823
|
+
const helpRes = spawnSync(
|
|
824
|
+
cdpnBin.command,
|
|
825
|
+
[...cdpnBin.prefixArgs, 'clone', '--help'],
|
|
826
|
+
{
|
|
827
|
+
cwd: resolvedProjectDir,
|
|
828
|
+
stdio: 'inherit',
|
|
829
|
+
shell: cdpnBin.shell,
|
|
830
|
+
}
|
|
831
|
+
);
|
|
832
|
+
if (helpRes.error) {
|
|
833
|
+
console.error(`Error: Failed to run cdpn clone: ${helpRes.error.message}`);
|
|
834
|
+
process.exit(1);
|
|
835
|
+
}
|
|
836
|
+
if ((helpRes.status ?? 0) !== 0) {
|
|
837
|
+
process.exit(helpRes.status ?? 1);
|
|
838
|
+
}
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
const projectRealpath = fs.realpathSync(resolvedProjectDir);
|
|
843
|
+
const demosDir = path.resolve(resolvedProjectDir, 'src');
|
|
844
|
+
if (!fs.existsSync(demosDir)) {
|
|
845
|
+
fs.mkdirSync(demosDir, { recursive: true });
|
|
846
|
+
} else {
|
|
847
|
+
const srcStat = fs.lstatSync(demosDir);
|
|
848
|
+
if (srcStat.isSymbolicLink() || !srcStat.isDirectory()) {
|
|
849
|
+
console.error(`Error: "src" at ${demosDir} is not a regular directory.`);
|
|
850
|
+
process.exit(1);
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
const demosRealpath = fs.realpathSync(demosDir);
|
|
855
|
+
if (!demosRealpath.startsWith(projectRealpath + path.sep)) {
|
|
856
|
+
console.error(`Error: "src/" resolves outside ${resolvedProjectDir}.`);
|
|
857
|
+
process.exit(1);
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
const { explicitProfile, forwardedArgs } = parseCloneArgs(argv, demosRealpath);
|
|
861
|
+
|
|
862
|
+
let profileToUse = explicitProfile;
|
|
863
|
+
if (!profileToUse) {
|
|
864
|
+
const profileRes = loadCodePenProfile(resolvedProjectDir);
|
|
865
|
+
if (!profileRes.ok) {
|
|
866
|
+
for (const line of profileRes.warnings) {
|
|
867
|
+
console.warn(line);
|
|
868
|
+
}
|
|
869
|
+
process.exit(1);
|
|
870
|
+
}
|
|
871
|
+
profileToUse = profileRes.profile;
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
const finalArgs = [
|
|
875
|
+
...(profileToUse ? ['--profile', profileToUse] : []),
|
|
876
|
+
'clone',
|
|
877
|
+
...forwardedArgs,
|
|
878
|
+
];
|
|
879
|
+
|
|
880
|
+
if (cdpnBin.shell && finalArgs.some((arg) => /[&|<>^%!"`\r\n]/.test(arg))) {
|
|
881
|
+
console.error(
|
|
882
|
+
'Error: Refusing to pass shell metacharacters to global cdpn wrapper on Windows. Run `npm install` to use the local codepen-commander package.'
|
|
883
|
+
);
|
|
884
|
+
process.exit(1);
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
const result = spawnSync(cdpnBin.command, [...cdpnBin.prefixArgs, ...finalArgs], {
|
|
888
|
+
cwd: demosRealpath,
|
|
889
|
+
stdio: 'inherit',
|
|
890
|
+
shell: cdpnBin.shell,
|
|
891
|
+
});
|
|
892
|
+
|
|
893
|
+
if (result.error) {
|
|
894
|
+
console.error(`Error: Failed to run cdpn clone: ${result.error.message}`);
|
|
895
|
+
process.exit(1);
|
|
896
|
+
}
|
|
897
|
+
if (result.signal) {
|
|
898
|
+
process.exit(result.signal === 'SIGINT' ? 130 : 1);
|
|
899
|
+
}
|
|
900
|
+
if ((result.status ?? 0) !== 0) {
|
|
901
|
+
process.exit(result.status ?? 1);
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
export function runCodePenSync(argv, { projectDir = process.cwd() } = {}) {
|
|
906
|
+
if (argv[0] === 'clone') {
|
|
907
|
+
return runCodePenClone(argv.slice(1), { projectDir });
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
const resolvedProjectDir = path.resolve(projectDir);
|
|
911
|
+
const demosDir = path.resolve(resolvedProjectDir, 'src');
|
|
912
|
+
|
|
913
|
+
const { mode, targetFolder, dryRun, force } = parseArgs(argv);
|
|
914
|
+
|
|
915
|
+
const codepenConfig = loadCodePenConfig(resolvedProjectDir);
|
|
916
|
+
if (!codepenConfig.ok) {
|
|
917
|
+
for (const line of codepenConfig.warnings) {
|
|
918
|
+
console.warn(line);
|
|
919
|
+
}
|
|
920
|
+
process.exit(1);
|
|
921
|
+
}
|
|
922
|
+
const { requiredProfile, defaultNewAccess } = codepenConfig;
|
|
923
|
+
|
|
924
|
+
const { demos, scope } = discoverDemoDirs(demosDir, targetFolder);
|
|
925
|
+
const prefix = dryRun ? '[DRY RUN] ' : '';
|
|
926
|
+
const scopeNote = scope ? `, scope: src/${scope}` : '';
|
|
927
|
+
const forceNote = force ? ', force: true' : '';
|
|
928
|
+
|
|
929
|
+
console.log(
|
|
930
|
+
`${prefix}CodePen Demo Sync (mode: ${mode}${scopeNote}, profile: ${requiredProfile}, default visibility: ${defaultNewAccess}${forceNote})`
|
|
931
|
+
);
|
|
932
|
+
|
|
933
|
+
// 1. Check cdpn is installed
|
|
934
|
+
const { bin: cdpnBin, source: cdpnSource, version: cdpnVersion } =
|
|
935
|
+
resolveCdpnBinary(resolvedProjectDir);
|
|
936
|
+
console.log(` ✓ cdpn ${cdpnVersion} available (${cdpnSource})`);
|
|
937
|
+
|
|
938
|
+
if (mode === 'delete' && !isSemverAtLeast(cdpnVersion, '1.3.0')) {
|
|
939
|
+
console.error(
|
|
940
|
+
`Error: 'delete' requires codepen-commander >= 1.3.0 for --keep-info (found ${cdpnVersion}).`
|
|
941
|
+
);
|
|
942
|
+
console.error('Run `npm install` to update codepen-commander.');
|
|
943
|
+
process.exit(1);
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
// 2. Check profile authentication via `cdpn auth status --json`
|
|
947
|
+
const auth = verifyProfileAuth(cdpnBin, requiredProfile, resolvedProjectDir);
|
|
948
|
+
console.log(` ✓ Authenticated profile "${auth.name}" (${auth.keyType} key)`);
|
|
949
|
+
|
|
950
|
+
// 3. Report discovered demos
|
|
951
|
+
const scopeSummary = scope
|
|
952
|
+
? `under ./src/${scope}`
|
|
953
|
+
: '(excluding ./src/index.html)';
|
|
954
|
+
console.log(` ✓ Found ${demos.length} demo folder(s) ${scopeSummary}\n`);
|
|
955
|
+
|
|
956
|
+
const summary = {
|
|
957
|
+
created: [],
|
|
958
|
+
pushed: [],
|
|
959
|
+
pulled: [],
|
|
960
|
+
deleted: [],
|
|
961
|
+
upToDate: [],
|
|
962
|
+
skipped: [],
|
|
963
|
+
conflicts: [],
|
|
964
|
+
errors: [],
|
|
965
|
+
};
|
|
966
|
+
|
|
967
|
+
for (const demo of demos) {
|
|
968
|
+
// --- DELETE (delete every linked demo on CodePen while keeping info in .cdpn.json) ---
|
|
969
|
+
if (mode === 'delete') {
|
|
970
|
+
if (!demo.hasConfig) {
|
|
971
|
+
console.log(
|
|
972
|
+
`- [SKIP] ${demo.relPath} — unlinked (no ${CONFIG_FILENAME}); nothing to delete`
|
|
973
|
+
);
|
|
974
|
+
summary.skipped.push(demo.relPath);
|
|
975
|
+
continue;
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
const configRes = readAndValidateConfig(demo, requiredProfile);
|
|
979
|
+
if (!configRes.ok) {
|
|
980
|
+
console.log(`✗ [ERROR] ${demo.relPath}`);
|
|
981
|
+
console.log(` ${configRes.message}`);
|
|
982
|
+
summary.errors.push({ demo: demo.relPath, message: configRes.message });
|
|
983
|
+
continue;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
if (!configRes.linked) {
|
|
987
|
+
console.log(
|
|
988
|
+
`- [SKIP] ${demo.relPath} — already unlinked (info-only ${CONFIG_FILENAME}); nothing to delete`
|
|
989
|
+
);
|
|
990
|
+
summary.skipped.push(demo.relPath);
|
|
991
|
+
continue;
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
const { config } = configRes;
|
|
995
|
+
const deleteArgs = [
|
|
996
|
+
'--profile',
|
|
997
|
+
requiredProfile,
|
|
998
|
+
'delete',
|
|
999
|
+
'--keep-info',
|
|
1000
|
+
'--yes',
|
|
1001
|
+
'--json',
|
|
1002
|
+
];
|
|
1003
|
+
|
|
1004
|
+
if (dryRun) {
|
|
1005
|
+
console.log(
|
|
1006
|
+
`× [WOULD DELETE] ${demo.relPath} (${config.url || config.pen_id}) — retaining info in ${CONFIG_FILENAME}`
|
|
1007
|
+
);
|
|
1008
|
+
console.log(` Would run: cdpn ${deleteArgs.join(' ')}`);
|
|
1009
|
+
summary.deleted.push(demo.relPath);
|
|
1010
|
+
continue;
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
console.log(
|
|
1014
|
+
`× [DELETING] ${demo.relPath} (${config.url || config.pen_id})…`
|
|
1015
|
+
);
|
|
1016
|
+
const res = runCdpnJson(cdpnBin, deleteArgs, demo.absPath);
|
|
1017
|
+
if (!res.ok) {
|
|
1018
|
+
console.log(` ✗ Delete failed: ${res.errorMessage}`);
|
|
1019
|
+
summary.errors.push({ demo: demo.relPath, message: res.errorMessage });
|
|
1020
|
+
continue;
|
|
1021
|
+
}
|
|
1022
|
+
const penTitle = res.json?.contents?.title || path.basename(demo.absPath);
|
|
1023
|
+
const penId = res.json?.contents?.pen_id || config.pen_id;
|
|
1024
|
+
console.log(
|
|
1025
|
+
` ✓ Deleted "${penTitle}" (${shortId(penId)}) on CodePen (retained info in ${CONFIG_FILENAME})`
|
|
1026
|
+
);
|
|
1027
|
+
summary.deleted.push(demo.relPath);
|
|
1028
|
+
continue;
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
// --- FORCE PULL (pull every linked demo unconditionally to refresh files & .cdpn.json) ---
|
|
1032
|
+
if (mode === 'pull' && force) {
|
|
1033
|
+
if (!demo.hasConfig) {
|
|
1034
|
+
console.log(
|
|
1035
|
+
`- [SKIP] ${demo.relPath} — unlinked (no ${CONFIG_FILENAME}); nothing to pull`
|
|
1036
|
+
);
|
|
1037
|
+
summary.skipped.push(demo.relPath);
|
|
1038
|
+
continue;
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
const configRes = readAndValidateConfig(demo, requiredProfile);
|
|
1042
|
+
if (!configRes.ok) {
|
|
1043
|
+
console.log(`✗ [ERROR] ${demo.relPath}`);
|
|
1044
|
+
console.log(` ${configRes.message}`);
|
|
1045
|
+
summary.errors.push({ demo: demo.relPath, message: configRes.message });
|
|
1046
|
+
continue;
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
if (!configRes.linked) {
|
|
1050
|
+
console.log(
|
|
1051
|
+
`- [SKIP] ${demo.relPath} — unlinked (info-only ${CONFIG_FILENAME}); nothing to pull`
|
|
1052
|
+
);
|
|
1053
|
+
summary.skipped.push(demo.relPath);
|
|
1054
|
+
continue;
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
const { config } = configRes;
|
|
1058
|
+
const pullArgs = ['--profile', requiredProfile, 'pull', '--force', '--json'];
|
|
1059
|
+
|
|
1060
|
+
if (dryRun) {
|
|
1061
|
+
console.log(
|
|
1062
|
+
`↓ [WOULD FORCE PULL] ${demo.relPath} (${config.url || config.pen_id})`
|
|
1063
|
+
);
|
|
1064
|
+
console.log(` Would run: cdpn ${pullArgs.join(' ')}`);
|
|
1065
|
+
summary.pulled.push(demo.relPath);
|
|
1066
|
+
continue;
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
console.log(
|
|
1070
|
+
`↓ [FORCE PULLING] ${demo.relPath} (${shortId(config.last_synced_version_id)})…`
|
|
1071
|
+
);
|
|
1072
|
+
const res = runCdpnJson(cdpnBin, pullArgs, demo.absPath);
|
|
1073
|
+
if (!res.ok) {
|
|
1074
|
+
console.log(` ✗ Pull failed: ${res.errorMessage}`);
|
|
1075
|
+
summary.errors.push({ demo: demo.relPath, message: res.errorMessage });
|
|
1076
|
+
continue;
|
|
1077
|
+
}
|
|
1078
|
+
const written = res.json?.contents?.written_paths?.length ?? 0;
|
|
1079
|
+
const deleted = res.json?.contents?.deleted_paths?.length ?? 0;
|
|
1080
|
+
console.log(
|
|
1081
|
+
` ✓ Pulled (version ${shortId(res.json?.contents?.version_id)}, updated ${written}, removed ${deleted})`
|
|
1082
|
+
);
|
|
1083
|
+
summary.pulled.push(demo.relPath);
|
|
1084
|
+
continue;
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
const info = inspectDemo(cdpnBin, demo, requiredProfile);
|
|
1088
|
+
|
|
1089
|
+
if (info.state === 'error') {
|
|
1090
|
+
console.log(`✗ [ERROR] ${demo.relPath}`);
|
|
1091
|
+
console.log(` ${info.message}`);
|
|
1092
|
+
summary.errors.push({ demo: demo.relPath, message: info.message });
|
|
1093
|
+
continue;
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
// --- UNLINKED (no .cdpn.json or info-only .cdpn.json) ---
|
|
1097
|
+
if (info.state === 'unlinked') {
|
|
1098
|
+
if (mode === 'pull') {
|
|
1099
|
+
const reason = info.hasRetainedInfo
|
|
1100
|
+
? `info-only ${CONFIG_FILENAME}`
|
|
1101
|
+
: `no ${CONFIG_FILENAME}`;
|
|
1102
|
+
console.log(
|
|
1103
|
+
`- [SKIP] ${demo.relPath} — unlinked (${reason}); nothing to pull`
|
|
1104
|
+
);
|
|
1105
|
+
summary.skipped.push(demo.relPath);
|
|
1106
|
+
continue;
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
const pushArgs = [
|
|
1110
|
+
'--profile',
|
|
1111
|
+
requiredProfile,
|
|
1112
|
+
'push',
|
|
1113
|
+
'--access',
|
|
1114
|
+
defaultNewAccess,
|
|
1115
|
+
'--json',
|
|
1116
|
+
];
|
|
1117
|
+
|
|
1118
|
+
if (dryRun) {
|
|
1119
|
+
console.log(
|
|
1120
|
+
`+ [WOULD CREATE] ${demo.relPath} — new ${defaultNewAccess} Pen "${info.title}" under "${requiredProfile}"`
|
|
1121
|
+
);
|
|
1122
|
+
console.log(` Would run: cdpn ${pushArgs.join(' ')}`);
|
|
1123
|
+
summary.created.push(demo.relPath);
|
|
1124
|
+
continue;
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
console.log(
|
|
1128
|
+
`+ [CREATING] ${demo.relPath} — creating new ${defaultNewAccess} Pen "${info.title}"…`
|
|
1129
|
+
);
|
|
1130
|
+
const res = runCdpnJson(cdpnBin, pushArgs, demo.absPath);
|
|
1131
|
+
if (!res.ok) {
|
|
1132
|
+
console.log(` ✗ Failed: ${res.errorMessage}`);
|
|
1133
|
+
summary.errors.push({ demo: demo.relPath, message: res.errorMessage });
|
|
1134
|
+
continue;
|
|
1135
|
+
}
|
|
1136
|
+
const pen = res.json?.contents?.pen;
|
|
1137
|
+
console.log(
|
|
1138
|
+
` ✓ Created ${pen?.access || defaultNewAccess} Pen: ${pen?.urls?.editor || pen?.id || 'ok'}`
|
|
1139
|
+
);
|
|
1140
|
+
summary.created.push(demo.relPath);
|
|
1141
|
+
continue;
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
// --- UP TO DATE ---
|
|
1145
|
+
if (info.state === 'up-to-date') {
|
|
1146
|
+
console.log(`✓ [UP TO DATE] ${demo.relPath}`);
|
|
1147
|
+
summary.upToDate.push(demo.relPath);
|
|
1148
|
+
continue;
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
// --- CONFLICT (both local changes and remote changes) ---
|
|
1152
|
+
if (info.state === 'conflict') {
|
|
1153
|
+
const { status, localBaseline, diffChanges, infoChanges } = info;
|
|
1154
|
+
console.log(`! [CONFLICT] ${demo.relPath}`);
|
|
1155
|
+
console.log(` Pen: ${status.url || status.pen_id}`);
|
|
1156
|
+
console.log(
|
|
1157
|
+
` Synced version: ${shortId(status.local_version_id)} -> Remote head: ${shortId(status.remote_version_id)}`
|
|
1158
|
+
);
|
|
1159
|
+
if (localBaseline.knownBaseline && localBaseline.hasChanges) {
|
|
1160
|
+
console.log(' Local file changes since last sync:');
|
|
1161
|
+
for (const line of formatChangesList(localBaseline, ' ')) {
|
|
1162
|
+
console.log(line);
|
|
1163
|
+
}
|
|
1164
|
+
} else if (!localBaseline.knownBaseline) {
|
|
1165
|
+
console.log(
|
|
1166
|
+
` Local baseline missing in ${CONFIG_FILENAME}; cannot rule out local edits.`
|
|
1167
|
+
);
|
|
1168
|
+
}
|
|
1169
|
+
if (info.diffCount > 0) {
|
|
1170
|
+
console.log(' File differences vs remote head:');
|
|
1171
|
+
for (const line of formatChangesList(diffChanges, ' ')) {
|
|
1172
|
+
console.log(line);
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
if (infoChanges.length > 0) {
|
|
1176
|
+
const fields = infoChanges.map((c) => c.field).join(', ');
|
|
1177
|
+
console.log(` Pen info differences: ${fields}`);
|
|
1178
|
+
}
|
|
1179
|
+
console.log(
|
|
1180
|
+
` Resolve manually in src/${demo.relPath}: run \`npx cdpn --profile ${requiredProfile} status\`, then \`push --force\` or \`pull --force\`.`
|
|
1181
|
+
);
|
|
1182
|
+
summary.conflicts.push({
|
|
1183
|
+
demo: demo.relPath,
|
|
1184
|
+
url: status.url || status.pen_id,
|
|
1185
|
+
});
|
|
1186
|
+
continue;
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
// --- LOCAL AHEAD (only local changed) ---
|
|
1190
|
+
if (info.state === 'local-ahead') {
|
|
1191
|
+
const changeSummary = [
|
|
1192
|
+
info.diffCount > 0 ? `${info.diffCount} file(s)` : null,
|
|
1193
|
+
info.infoCount > 0
|
|
1194
|
+
? `info: ${info.infoChanges.map((c) => c.field).join(', ')}`
|
|
1195
|
+
: null,
|
|
1196
|
+
]
|
|
1197
|
+
.filter(Boolean)
|
|
1198
|
+
.join(', ');
|
|
1199
|
+
|
|
1200
|
+
if (mode === 'pull') {
|
|
1201
|
+
console.log(
|
|
1202
|
+
`- [SKIP] ${demo.relPath} — local has unpushed changes (${changeSummary}) and remote has no new changes; run \`npm run cdpn:push\` or \`npm run cdpn:sync\``
|
|
1203
|
+
);
|
|
1204
|
+
summary.skipped.push(demo.relPath);
|
|
1205
|
+
continue;
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
const pushArgs = ['--profile', requiredProfile, 'push', '--json'];
|
|
1209
|
+
if (dryRun) {
|
|
1210
|
+
console.log(`↑ [WOULD PUSH] ${demo.relPath} (${changeSummary})`);
|
|
1211
|
+
for (const line of formatChangesList(info.diffChanges)) {
|
|
1212
|
+
console.log(line);
|
|
1213
|
+
}
|
|
1214
|
+
console.log(` Would run: cdpn ${pushArgs.join(' ')}`);
|
|
1215
|
+
summary.pushed.push(demo.relPath);
|
|
1216
|
+
continue;
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
console.log(`↑ [PUSHING] ${demo.relPath} (${changeSummary})…`);
|
|
1220
|
+
for (const line of formatChangesList(info.diffChanges)) {
|
|
1221
|
+
console.log(line);
|
|
1222
|
+
}
|
|
1223
|
+
const res = runCdpnJson(cdpnBin, pushArgs, demo.absPath);
|
|
1224
|
+
if (!res.ok) {
|
|
1225
|
+
console.log(` ✗ Push failed: ${res.errorMessage}`);
|
|
1226
|
+
summary.errors.push({ demo: demo.relPath, message: res.errorMessage });
|
|
1227
|
+
continue;
|
|
1228
|
+
}
|
|
1229
|
+
console.log(
|
|
1230
|
+
` ✓ Pushed (version ${shortId(res.json?.contents?.version_id)})`
|
|
1231
|
+
);
|
|
1232
|
+
summary.pushed.push(demo.relPath);
|
|
1233
|
+
continue;
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
// --- REMOTE AHEAD or REMOTE METADATA AHEAD (only remote changed) ---
|
|
1237
|
+
if (info.state === 'remote-ahead' || info.state === 'remote-metadata-ahead') {
|
|
1238
|
+
const remoteSummary =
|
|
1239
|
+
[
|
|
1240
|
+
info.diffCount > 0 ? `${info.diffCount} file diff(s)` : null,
|
|
1241
|
+
info.infoCount > 0
|
|
1242
|
+
? `info: ${info.infoChanges.map((c) => c.field).join(', ')}`
|
|
1243
|
+
: null,
|
|
1244
|
+
]
|
|
1245
|
+
.filter(Boolean)
|
|
1246
|
+
.join(', ') || 'metadata behind';
|
|
1247
|
+
|
|
1248
|
+
if (mode === 'push') {
|
|
1249
|
+
console.log(
|
|
1250
|
+
`- [SKIP] ${demo.relPath} — remote is ahead (${remoteSummary}); run \`npm run cdpn:pull\` or \`npm run cdpn:sync\``
|
|
1251
|
+
);
|
|
1252
|
+
summary.skipped.push(demo.relPath);
|
|
1253
|
+
continue;
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
const pullArgs =
|
|
1257
|
+
info.state === 'remote-metadata-ahead'
|
|
1258
|
+
? ['--profile', requiredProfile, 'pull', '--force', '--json']
|
|
1259
|
+
: ['--profile', requiredProfile, 'pull', '--json'];
|
|
1260
|
+
|
|
1261
|
+
if (dryRun) {
|
|
1262
|
+
console.log(
|
|
1263
|
+
`↓ [WOULD PULL] ${demo.relPath} (${shortId(info.status.local_version_id)} -> ${shortId(info.status.remote_version_id)}, ${remoteSummary})`
|
|
1264
|
+
);
|
|
1265
|
+
for (const line of formatChangesList(info.diffChanges)) {
|
|
1266
|
+
console.log(line);
|
|
1267
|
+
}
|
|
1268
|
+
console.log(` Would run: cdpn ${pullArgs.join(' ')}`);
|
|
1269
|
+
summary.pulled.push(demo.relPath);
|
|
1270
|
+
continue;
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
console.log(
|
|
1274
|
+
`↓ [PULLING] ${demo.relPath} (${shortId(info.status.local_version_id)} -> ${shortId(info.status.remote_version_id)}, ${remoteSummary})…`
|
|
1275
|
+
);
|
|
1276
|
+
const res = runCdpnJson(cdpnBin, pullArgs, demo.absPath);
|
|
1277
|
+
if (!res.ok) {
|
|
1278
|
+
console.log(` ✗ Pull failed: ${res.errorMessage}`);
|
|
1279
|
+
summary.errors.push({ demo: demo.relPath, message: res.errorMessage });
|
|
1280
|
+
continue;
|
|
1281
|
+
}
|
|
1282
|
+
const written = res.json?.contents?.written_paths?.length ?? 0;
|
|
1283
|
+
const deleted = res.json?.contents?.deleted_paths?.length ?? 0;
|
|
1284
|
+
console.log(
|
|
1285
|
+
` ✓ Pulled (version ${shortId(res.json?.contents?.version_id)}, updated ${written}, removed ${deleted})`
|
|
1286
|
+
);
|
|
1287
|
+
summary.pulled.push(demo.relPath);
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
// Final Summary
|
|
1292
|
+
console.log(`\n${prefix}Summary (${mode}):`);
|
|
1293
|
+
console.log(` Created: ${summary.created.length}`);
|
|
1294
|
+
console.log(` Pushed: ${summary.pushed.length}`);
|
|
1295
|
+
console.log(` Pulled: ${summary.pulled.length}`);
|
|
1296
|
+
console.log(` Deleted: ${summary.deleted.length}`);
|
|
1297
|
+
console.log(` Up to date: ${summary.upToDate.length}`);
|
|
1298
|
+
console.log(` Skipped: ${summary.skipped.length}`);
|
|
1299
|
+
console.log(` Conflicts: ${summary.conflicts.length}`);
|
|
1300
|
+
console.log(` Errors: ${summary.errors.length}`);
|
|
1301
|
+
|
|
1302
|
+
if (!dryRun && summary.deleted.length > 0) {
|
|
1303
|
+
console.log(
|
|
1304
|
+
'\nDeleted Pens move to CodePen Deleted Items (restorable for 3 days):'
|
|
1305
|
+
);
|
|
1306
|
+
console.log(' https://codepen.io/your-work?item_type=DELETED_ITEMS');
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
if (summary.conflicts.length > 0) {
|
|
1310
|
+
console.log('\nConflicts requiring manual resolution:');
|
|
1311
|
+
for (const c of summary.conflicts) {
|
|
1312
|
+
console.log(` - src/${c.demo} (${c.url})`);
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
if (summary.errors.length > 0) {
|
|
1317
|
+
console.log('\nErrors:');
|
|
1318
|
+
for (const e of summary.errors) {
|
|
1319
|
+
console.log(` - src/${e.demo}: ${e.message}`);
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1323
|
+
if (summary.errors.length > 0 || (!dryRun && summary.conflicts.length > 0)) {
|
|
1324
|
+
process.exit(1);
|
|
1325
|
+
}
|
|
1326
|
+
}
|