codepen-demokit 0.0.0-stage → 1.1.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 +235 -2
- package/bin/cli.mjs +155 -0
- package/lib/blocks.mjs +1067 -0
- package/lib/build-json.mjs +507 -0
- package/lib/build-site.mjs +258 -0
- package/lib/config.mjs +254 -0
- package/lib/init.mjs +1084 -0
- package/lib/serve.mjs +507 -0
- package/lib/sync-codepen.mjs +1375 -0
- package/package.json +40 -4
- package/shell/index.html +69 -0
- package/shell/scripts.js +268 -0
- package/shell/styles.css +463 -0
- package/templates/AGENTS.md +77 -0
- package/templates/README.md +63 -0
- package/templates/config.json.example +10 -0
- package/templates/gitignore +27 -0
package/lib/init.mjs
ADDED
|
@@ -0,0 +1,1084 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import { existsSync } from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import readline from 'node:readline';
|
|
6
|
+
import readlinePromises from 'node:readline/promises';
|
|
7
|
+
import { PACKAGE_DIR } from './build-site.mjs';
|
|
8
|
+
import {
|
|
9
|
+
DEFAULT_SITE_CONFIG,
|
|
10
|
+
DEFAULT_VISIBILITY,
|
|
11
|
+
PROFILE_NAME_PATTERN,
|
|
12
|
+
VISIBILITY_OPTIONS,
|
|
13
|
+
} from './config.mjs';
|
|
14
|
+
import { locateCdpnBinary } from './sync-codepen.mjs';
|
|
15
|
+
|
|
16
|
+
const TEMPLATES_DIR = path.join(PACKAGE_DIR, 'templates');
|
|
17
|
+
const CONTROL_CHAR_PATTERN = /[\x00-\x1f\x7f]/;
|
|
18
|
+
|
|
19
|
+
const VISIBILITY_BY_LOWER = new Map(
|
|
20
|
+
VISIBILITY_OPTIONS.map((option) => [option.toLowerCase(), option]),
|
|
21
|
+
);
|
|
22
|
+
|
|
23
|
+
const VISIBILITY_DESCRIPTIONS = Object.freeze({
|
|
24
|
+
Private: 'unlisted; anyone with the link can view it',
|
|
25
|
+
Public: 'visible to everyone',
|
|
26
|
+
Protected: 'private and password-protected',
|
|
27
|
+
Collaborators: 'private; visible only to you and collaborators',
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const VISIBILITY_CHOICES = Object.freeze(
|
|
31
|
+
VISIBILITY_OPTIONS.map((option) => ({
|
|
32
|
+
value: option,
|
|
33
|
+
label: option,
|
|
34
|
+
description: VISIBILITY_DESCRIPTIONS[option] || '',
|
|
35
|
+
})),
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
function createFormatter(output = process.stdout) {
|
|
39
|
+
const colorsEnabled = () => {
|
|
40
|
+
if (process.env.NO_COLOR !== undefined && process.env.NO_COLOR !== '') {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
if (process.env.FORCE_COLOR !== undefined && process.env.FORCE_COLOR !== '0') {
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
return Boolean(output.isTTY);
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const wrap = (code, text) => {
|
|
50
|
+
if (!colorsEnabled()) return text;
|
|
51
|
+
return `\x1b[${code}m${text}\x1b[0m`;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
return {
|
|
55
|
+
bold: (s) => wrap('1', s),
|
|
56
|
+
dim: (s) => wrap('2', s),
|
|
57
|
+
red: (s) => wrap('31', s),
|
|
58
|
+
green: (s) => wrap('32', s),
|
|
59
|
+
yellow: (s) => wrap('33', s),
|
|
60
|
+
blue: (s) => wrap('34', s),
|
|
61
|
+
magenta: (s) => wrap('35', s),
|
|
62
|
+
cyan: (s) => wrap('36', s),
|
|
63
|
+
gray: (s) => wrap('90', s),
|
|
64
|
+
boldGreen: (s) => wrap('1;32', s),
|
|
65
|
+
boldYellow: (s) => wrap('1;33', s),
|
|
66
|
+
boldCyan: (s) => wrap('1;36', s),
|
|
67
|
+
boldMagenta: (s) => wrap('1;35', s),
|
|
68
|
+
boldRed: (s) => wrap('1;31', s),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function stripAnsi(text) {
|
|
73
|
+
return String(text).replace(/\x1b\[[0-9;]*m/g, '');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function countTerminalRows(lines, columns) {
|
|
77
|
+
const safeCols = Math.max(1, columns);
|
|
78
|
+
let total = 0;
|
|
79
|
+
for (const rawLine of lines) {
|
|
80
|
+
for (const subLine of rawLine.split('\n')) {
|
|
81
|
+
const visibleLength = stripAnsi(subLine).length;
|
|
82
|
+
total += visibleLength === 0 ? 1 : Math.ceil(visibleLength / safeCols);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return total;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export class InitCancelledError extends Error {
|
|
89
|
+
constructor() {
|
|
90
|
+
super('Init cancelled.');
|
|
91
|
+
this.name = 'InitCancelledError';
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function slugifyDirectoryName(name) {
|
|
96
|
+
const slug = String(name ?? '')
|
|
97
|
+
.normalize('NFKD')
|
|
98
|
+
.replace(/[\u0300-\u036f]/g, '')
|
|
99
|
+
.toLowerCase()
|
|
100
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
101
|
+
.replace(/^-+|-+$/g, '');
|
|
102
|
+
return slug || 'my-codepen-demos';
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function toValidPackageName(dirName) {
|
|
106
|
+
const cleaned = dirName
|
|
107
|
+
.toLowerCase()
|
|
108
|
+
.replace(/[^a-z0-9._-]+/g, '-')
|
|
109
|
+
.replace(/^[._-]+/, '')
|
|
110
|
+
.replace(/-+$/, '');
|
|
111
|
+
return cleaned || 'my-codepen-demos';
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function normalizeVisibility(rawInput) {
|
|
115
|
+
const trimmed = String(rawInput ?? '').trim();
|
|
116
|
+
if (!trimmed) return DEFAULT_VISIBILITY;
|
|
117
|
+
return VISIBILITY_BY_LOWER.get(trimmed.toLowerCase()) ?? null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function isWithinRoot(candidatePath, rootPath) {
|
|
121
|
+
return candidatePath === rootPath || candidatePath.startsWith(rootPath + path.sep);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function resolveTargetDirectory(rawInput, baseCwd) {
|
|
125
|
+
const trimmed = String(rawInput ?? '').trim();
|
|
126
|
+
if (!trimmed) {
|
|
127
|
+
return { ok: false, error: 'Directory cannot be empty.' };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (CONTROL_CHAR_PATTERN.test(trimmed) || trimmed.includes('\\')) {
|
|
131
|
+
return {
|
|
132
|
+
ok: false,
|
|
133
|
+
error: 'Directory contains invalid characters. Use a relative path with forward slashes.',
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (path.isAbsolute(trimmed)) {
|
|
138
|
+
return {
|
|
139
|
+
ok: false,
|
|
140
|
+
error: 'Please enter a relative directory path (e.g., "my-codepen-demos" or ".").',
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
let resolvedDir;
|
|
145
|
+
if (trimmed === '.' || trimmed === './') {
|
|
146
|
+
resolvedDir = baseCwd;
|
|
147
|
+
} else {
|
|
148
|
+
let normalized = trimmed;
|
|
149
|
+
while (normalized.startsWith('./')) {
|
|
150
|
+
normalized = normalized.slice(2);
|
|
151
|
+
}
|
|
152
|
+
normalized = normalized.replace(/\/+$/, '');
|
|
153
|
+
|
|
154
|
+
if (!normalized || normalized === '.') {
|
|
155
|
+
resolvedDir = baseCwd;
|
|
156
|
+
} else {
|
|
157
|
+
const segments = normalized.split('/').filter(Boolean);
|
|
158
|
+
for (const segment of segments) {
|
|
159
|
+
if (segment === '.' || segment === '..' || segment.startsWith('.')) {
|
|
160
|
+
return {
|
|
161
|
+
ok: false,
|
|
162
|
+
error: 'Directory cannot contain "..", ".", or hidden folder segments.',
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
resolvedDir = path.resolve(baseCwd, ...segments);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
if (!isWithinRoot(resolvedDir, baseCwd)) {
|
|
171
|
+
return {
|
|
172
|
+
ok: false,
|
|
173
|
+
error: 'Directory must resolve inside the current working directory.',
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const baseRealpath = await fs.realpath(baseCwd);
|
|
178
|
+
|
|
179
|
+
// Check nearest existing path to guard against symlinks or file collisions
|
|
180
|
+
let probe = resolvedDir;
|
|
181
|
+
while (true) {
|
|
182
|
+
try {
|
|
183
|
+
const stat = await fs.lstat(probe);
|
|
184
|
+
if (probe === resolvedDir) {
|
|
185
|
+
if (stat.isSymbolicLink()) {
|
|
186
|
+
return {
|
|
187
|
+
ok: false,
|
|
188
|
+
error: `"${trimmed}" is a symbolic link. Please choose a regular directory.`,
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
if (!stat.isDirectory()) {
|
|
192
|
+
return {
|
|
193
|
+
ok: false,
|
|
194
|
+
error: `"${trimmed}" already exists and is not a directory.`,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
} else if (!stat.isDirectory()) {
|
|
198
|
+
return {
|
|
199
|
+
ok: false,
|
|
200
|
+
error: `Cannot create "${trimmed}" because an ancestor path is a file.`,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const realProbe = await fs.realpath(probe);
|
|
205
|
+
if (!isWithinRoot(realProbe, baseRealpath)) {
|
|
206
|
+
return {
|
|
207
|
+
ok: false,
|
|
208
|
+
error: `"${trimmed}" resolves outside the current working directory.`,
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
break;
|
|
212
|
+
} catch (err) {
|
|
213
|
+
if (err && err.code === 'ENOENT') {
|
|
214
|
+
if (probe === baseCwd) break;
|
|
215
|
+
const parent = path.dirname(probe);
|
|
216
|
+
if (parent === probe) break;
|
|
217
|
+
probe = parent;
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
throw err;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
return {
|
|
225
|
+
ok: true,
|
|
226
|
+
resolvedDir,
|
|
227
|
+
isCurrentDir: resolvedDir === baseCwd,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function promptSelectInteractive({ question, options, defaultIndex, input, output, fmt }) {
|
|
232
|
+
readline.emitKeypressEvents(input);
|
|
233
|
+
|
|
234
|
+
let selectedIndex = defaultIndex;
|
|
235
|
+
let windowStart = 0;
|
|
236
|
+
let lastRenderedRows = 0;
|
|
237
|
+
let settled = false;
|
|
238
|
+
|
|
239
|
+
const getColumns = () => Math.max(20, output.columns || 80);
|
|
240
|
+
const getMaxVisible = () => {
|
|
241
|
+
const termRows = output.rows || 24;
|
|
242
|
+
const available = Math.max(3, termRows - 5);
|
|
243
|
+
return Math.min(options.length, available, 12);
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
const syncWindow = (maxVisible) => {
|
|
247
|
+
if (options.length <= maxVisible) {
|
|
248
|
+
windowStart = 0;
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
if (selectedIndex < windowStart) {
|
|
252
|
+
windowStart = selectedIndex;
|
|
253
|
+
} else if (selectedIndex >= windowStart + maxVisible) {
|
|
254
|
+
windowStart = selectedIndex - maxVisible + 1;
|
|
255
|
+
}
|
|
256
|
+
const maxStart = Math.max(0, options.length - maxVisible);
|
|
257
|
+
if (windowStart > maxStart) {
|
|
258
|
+
windowStart = maxStart;
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
const erasePrevious = () => {
|
|
263
|
+
if (lastRenderedRows <= 0) return '';
|
|
264
|
+
return `\x1b[${lastRenderedRows}A\r\x1b[J`;
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
const renderActive = (hideCursor) => {
|
|
268
|
+
const columns = getColumns();
|
|
269
|
+
const maxVisible = getMaxVisible();
|
|
270
|
+
syncWindow(maxVisible);
|
|
271
|
+
|
|
272
|
+
const lines = [
|
|
273
|
+
`${fmt.cyan('◆')} ${fmt.bold(question)} ${fmt.dim('(↑/↓, Enter)')}`,
|
|
274
|
+
];
|
|
275
|
+
|
|
276
|
+
if (windowStart > 0) {
|
|
277
|
+
lines.push(` ${fmt.dim(`↑ ${windowStart} more`)}`);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const windowEnd = Math.min(options.length, windowStart + maxVisible);
|
|
281
|
+
for (let i = windowStart; i < windowEnd; i++) {
|
|
282
|
+
const opt = options[i];
|
|
283
|
+
const isSelected = i === selectedIndex;
|
|
284
|
+
if (isSelected) {
|
|
285
|
+
const desc = opt.description ? ` ${fmt.cyan(`— ${opt.description}`)}` : '';
|
|
286
|
+
lines.push(` ${fmt.boldCyan('→')} ${fmt.boldCyan(opt.label)}${desc}`);
|
|
287
|
+
} else {
|
|
288
|
+
const desc = opt.description ? ` ${fmt.dim(`— ${opt.description}`)}` : '';
|
|
289
|
+
lines.push(` ${opt.label}${desc}`);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const hiddenBelow = options.length - windowEnd;
|
|
294
|
+
if (hiddenBelow > 0) {
|
|
295
|
+
lines.push(` ${fmt.dim(`↓ ${hiddenBelow} more`)}`);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const prefix = `${hideCursor ? '\x1b[?25l' : ''}${erasePrevious()}`;
|
|
299
|
+
output.write(`${prefix}${lines.join('\n')}\n`);
|
|
300
|
+
lastRenderedRows = countTerminalRows(lines, columns);
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
const renderFinal = (lines) => {
|
|
304
|
+
const prefix = erasePrevious();
|
|
305
|
+
output.write(`${prefix}${lines.join('\n')}\n\x1b[?25h`);
|
|
306
|
+
lastRenderedRows = 0;
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
const wasRaw = Boolean(input.isRaw);
|
|
310
|
+
input.setRawMode?.(true);
|
|
311
|
+
input.resume();
|
|
312
|
+
|
|
313
|
+
return new Promise((resolve, reject) => {
|
|
314
|
+
const cleanup = () => {
|
|
315
|
+
input.removeListener('keypress', onKeypress);
|
|
316
|
+
input.removeListener('end', onEnd);
|
|
317
|
+
output.removeListener('resize', onResize);
|
|
318
|
+
process.removeListener('SIGINT', onSigint);
|
|
319
|
+
try {
|
|
320
|
+
input.setRawMode?.(wasRaw);
|
|
321
|
+
} catch {
|
|
322
|
+
// Ignore if stream already closed
|
|
323
|
+
}
|
|
324
|
+
input.pause();
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
const cancel = () => {
|
|
328
|
+
if (settled) return;
|
|
329
|
+
settled = true;
|
|
330
|
+
cleanup();
|
|
331
|
+
renderFinal([
|
|
332
|
+
`${fmt.cyan('◆')} ${fmt.bold(question)}`,
|
|
333
|
+
` ${fmt.red('×')} ${fmt.dim('Cancelled')}`,
|
|
334
|
+
]);
|
|
335
|
+
reject(new InitCancelledError());
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
const confirm = () => {
|
|
339
|
+
if (settled) return;
|
|
340
|
+
settled = true;
|
|
341
|
+
cleanup();
|
|
342
|
+
const chosen = options[selectedIndex];
|
|
343
|
+
const desc = chosen.description ? ` ${fmt.dim(`— ${chosen.description}`)}` : '';
|
|
344
|
+
renderFinal([
|
|
345
|
+
`${fmt.cyan('◆')} ${fmt.bold(question)}`,
|
|
346
|
+
` ${fmt.boldGreen('→')} ${fmt.boldGreen(chosen.label)}${desc}`,
|
|
347
|
+
]);
|
|
348
|
+
resolve(chosen.value);
|
|
349
|
+
};
|
|
350
|
+
|
|
351
|
+
const onResize = () => {
|
|
352
|
+
if (settled) return;
|
|
353
|
+
renderActive(false);
|
|
354
|
+
};
|
|
355
|
+
|
|
356
|
+
const onSigint = () => {
|
|
357
|
+
cancel();
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
const onEnd = () => {
|
|
361
|
+
cancel();
|
|
362
|
+
};
|
|
363
|
+
|
|
364
|
+
const onKeypress = (str, key) => {
|
|
365
|
+
if (settled) return;
|
|
366
|
+
|
|
367
|
+
if (str === '\u0003' || (key?.ctrl && key.name === 'c') || key?.name === 'escape') {
|
|
368
|
+
cancel();
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
if (key?.name === 'return' || key?.name === 'enter') {
|
|
373
|
+
confirm();
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
if (key?.name === 'up' || (!key?.ctrl && !key?.meta && key?.name === 'k')) {
|
|
378
|
+
selectedIndex = (selectedIndex - 1 + options.length) % options.length;
|
|
379
|
+
renderActive(false);
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
if (key?.name === 'down' || (!key?.ctrl && !key?.meta && key?.name === 'j')) {
|
|
384
|
+
selectedIndex = (selectedIndex + 1) % options.length;
|
|
385
|
+
renderActive(false);
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
if (key?.name === 'home' || key?.name === 'pageup') {
|
|
390
|
+
if (selectedIndex !== 0) {
|
|
391
|
+
selectedIndex = 0;
|
|
392
|
+
renderActive(false);
|
|
393
|
+
}
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
if (key?.name === 'end' || key?.name === 'pagedown') {
|
|
398
|
+
if (selectedIndex !== options.length - 1) {
|
|
399
|
+
selectedIndex = options.length - 1;
|
|
400
|
+
renderActive(false);
|
|
401
|
+
}
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
if (str && !key?.ctrl && !key?.meta) {
|
|
406
|
+
if (/^[1-9]$/.test(str)) {
|
|
407
|
+
const idx = Number.parseInt(str, 10) - 1;
|
|
408
|
+
if (idx >= 0 && idx < options.length && idx !== selectedIndex) {
|
|
409
|
+
selectedIndex = idx;
|
|
410
|
+
renderActive(false);
|
|
411
|
+
}
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
const lower = str.toLowerCase();
|
|
416
|
+
const shortcutIdx = options.findIndex(
|
|
417
|
+
(opt) => opt.shortcut && opt.shortcut.toLowerCase() === lower,
|
|
418
|
+
);
|
|
419
|
+
if (shortcutIdx !== -1 && shortcutIdx !== selectedIndex) {
|
|
420
|
+
selectedIndex = shortcutIdx;
|
|
421
|
+
renderActive(false);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
};
|
|
425
|
+
|
|
426
|
+
input.on('keypress', onKeypress);
|
|
427
|
+
input.once('end', onEnd);
|
|
428
|
+
output.on('resize', onResize);
|
|
429
|
+
process.on('SIGINT', onSigint);
|
|
430
|
+
renderActive(true);
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
function createPrompter({
|
|
435
|
+
input = process.stdin,
|
|
436
|
+
output = process.stdout,
|
|
437
|
+
fmt = createFormatter(output),
|
|
438
|
+
term = process.env.TERM,
|
|
439
|
+
} = {}) {
|
|
440
|
+
const canUseInteractive =
|
|
441
|
+
Boolean(input.isTTY) &&
|
|
442
|
+
Boolean(output.isTTY) &&
|
|
443
|
+
typeof input.setRawMode === 'function' &&
|
|
444
|
+
term !== 'dumb';
|
|
445
|
+
|
|
446
|
+
let closed = false;
|
|
447
|
+
let activeRl = null;
|
|
448
|
+
|
|
449
|
+
const formatQuestionHeader = (question, defaultValue) => {
|
|
450
|
+
const hint = defaultValue ? ` ${fmt.dim(`(${defaultValue})`)}` : '';
|
|
451
|
+
return `${fmt.cyan('◆')} ${fmt.bold(question)}${hint}`;
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
if (canUseInteractive) {
|
|
455
|
+
const readLineInteractive = async (promptText) => {
|
|
456
|
+
const rl = readlinePromises.createInterface({ input, output });
|
|
457
|
+
activeRl = rl;
|
|
458
|
+
const abortController = new AbortController();
|
|
459
|
+
|
|
460
|
+
const onSigint = () => {
|
|
461
|
+
abortController.abort();
|
|
462
|
+
rl.close();
|
|
463
|
+
};
|
|
464
|
+
const onClose = () => {
|
|
465
|
+
abortController.abort();
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
rl.on('SIGINT', onSigint);
|
|
469
|
+
rl.once('close', onClose);
|
|
470
|
+
|
|
471
|
+
try {
|
|
472
|
+
return await rl.question(promptText, { signal: abortController.signal });
|
|
473
|
+
} catch (err) {
|
|
474
|
+
if (
|
|
475
|
+
abortController.signal.aborted ||
|
|
476
|
+
err?.name === 'AbortError' ||
|
|
477
|
+
err?.code === 'ABORT_ERR' ||
|
|
478
|
+
err?.code === 'ERR_USE_AFTER_CLOSE'
|
|
479
|
+
) {
|
|
480
|
+
output.write(`\r\x1b[K ${fmt.red('×')} ${fmt.dim('Cancelled')}\n`);
|
|
481
|
+
throw new InitCancelledError();
|
|
482
|
+
}
|
|
483
|
+
throw err;
|
|
484
|
+
} finally {
|
|
485
|
+
rl.off('SIGINT', onSigint);
|
|
486
|
+
rl.off('close', onClose);
|
|
487
|
+
if (activeRl === rl) {
|
|
488
|
+
activeRl = null;
|
|
489
|
+
}
|
|
490
|
+
rl.close();
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
|
|
494
|
+
return {
|
|
495
|
+
async askText({ question, defaultValue = '', validate }) {
|
|
496
|
+
output.write(`${formatQuestionHeader(question, defaultValue)}\n`);
|
|
497
|
+
const promptText = ` ${fmt.boldCyan('→')} `;
|
|
498
|
+
const columns = () => Math.max(20, output.columns || 80);
|
|
499
|
+
|
|
500
|
+
while (true) {
|
|
501
|
+
const raw = await readLineInteractive(promptText);
|
|
502
|
+
const result = await validate(raw);
|
|
503
|
+
if (!result.ok) {
|
|
504
|
+
output.write(` ${fmt.yellow(result.error)}\n`);
|
|
505
|
+
continue;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
const displayText = result.displayValue ?? String(result.value);
|
|
509
|
+
const enteredRows = countTerminalRows([` → ${raw}`], columns());
|
|
510
|
+
output.write(
|
|
511
|
+
`\x1b[${enteredRows}A\r\x1b[J ${fmt.boldGreen('→')} ${fmt.boldGreen(displayText)}\n`,
|
|
512
|
+
);
|
|
513
|
+
return result.value;
|
|
514
|
+
}
|
|
515
|
+
},
|
|
516
|
+
|
|
517
|
+
async select({ question, options, defaultIndex = 0 }) {
|
|
518
|
+
if (!Array.isArray(options) || options.length === 0) {
|
|
519
|
+
throw new Error('select requires at least one option.');
|
|
520
|
+
}
|
|
521
|
+
const clampedDefault = Math.min(Math.max(0, Math.trunc(defaultIndex)), options.length - 1);
|
|
522
|
+
return promptSelectInteractive({
|
|
523
|
+
question,
|
|
524
|
+
options,
|
|
525
|
+
defaultIndex: clampedDefault,
|
|
526
|
+
input,
|
|
527
|
+
output,
|
|
528
|
+
fmt,
|
|
529
|
+
});
|
|
530
|
+
},
|
|
531
|
+
|
|
532
|
+
close() {
|
|
533
|
+
if (closed) return;
|
|
534
|
+
closed = true;
|
|
535
|
+
if (activeRl) {
|
|
536
|
+
activeRl.close();
|
|
537
|
+
activeRl = null;
|
|
538
|
+
}
|
|
539
|
+
},
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// Non-interactive / piped / dumb terminal fallback: keep a single shared readline iterator
|
|
544
|
+
// so buffered lines from piped stdin are never dropped between prompts.
|
|
545
|
+
const rl = readlinePromises.createInterface({ input, crlfDelay: Infinity });
|
|
546
|
+
const iterator = rl[Symbol.asyncIterator]();
|
|
547
|
+
|
|
548
|
+
const readFallbackLine = async (promptText) => {
|
|
549
|
+
output.write(promptText);
|
|
550
|
+
const { value, done } = await iterator.next();
|
|
551
|
+
if (done) {
|
|
552
|
+
output.write('\n');
|
|
553
|
+
throw new InitCancelledError();
|
|
554
|
+
}
|
|
555
|
+
return value;
|
|
556
|
+
};
|
|
557
|
+
|
|
558
|
+
return {
|
|
559
|
+
async askText({ question, defaultValue = '', validate }) {
|
|
560
|
+
output.write(`${formatQuestionHeader(question, defaultValue)}\n`);
|
|
561
|
+
while (true) {
|
|
562
|
+
const raw = await readFallbackLine(` ${fmt.boldCyan('→')} `);
|
|
563
|
+
const result = await validate(raw);
|
|
564
|
+
if (!result.ok) {
|
|
565
|
+
output.write(`${raw}\n ${fmt.yellow(result.error)}\n`);
|
|
566
|
+
continue;
|
|
567
|
+
}
|
|
568
|
+
const displayText = result.displayValue ?? String(result.value);
|
|
569
|
+
output.write(`${fmt.boldGreen(displayText)}\n`);
|
|
570
|
+
return result.value;
|
|
571
|
+
}
|
|
572
|
+
},
|
|
573
|
+
|
|
574
|
+
async select({ question, options, defaultIndex = 0 }) {
|
|
575
|
+
if (!Array.isArray(options) || options.length === 0) {
|
|
576
|
+
throw new Error('select requires at least one option.');
|
|
577
|
+
}
|
|
578
|
+
const clampedDefault = Math.min(Math.max(0, Math.trunc(defaultIndex)), options.length - 1);
|
|
579
|
+
output.write(`${formatQuestionHeader(question)}\n`);
|
|
580
|
+
options.forEach((opt, idx) => {
|
|
581
|
+
const num = fmt.cyan(`${idx + 1})`);
|
|
582
|
+
const desc = opt.description ? ` ${fmt.dim(`— ${opt.description}`)}` : '';
|
|
583
|
+
output.write(` ${num} ${opt.label}${desc}\n`);
|
|
584
|
+
});
|
|
585
|
+
|
|
586
|
+
while (true) {
|
|
587
|
+
const raw = await readFallbackLine(
|
|
588
|
+
` ${fmt.dim(`Choose [1-${options.length}] (default ${clampedDefault + 1}):`)} `,
|
|
589
|
+
);
|
|
590
|
+
const trimmed = raw.trim();
|
|
591
|
+
output.write('\n');
|
|
592
|
+
|
|
593
|
+
let matched = null;
|
|
594
|
+
if (!trimmed) {
|
|
595
|
+
matched = options[clampedDefault];
|
|
596
|
+
} else {
|
|
597
|
+
const num = Number.parseInt(trimmed, 10);
|
|
598
|
+
if (!Number.isNaN(num) && num >= 1 && num <= options.length && String(num) === trimmed) {
|
|
599
|
+
matched = options[num - 1];
|
|
600
|
+
} else {
|
|
601
|
+
const lower = trimmed.toLowerCase();
|
|
602
|
+
matched =
|
|
603
|
+
options.find(
|
|
604
|
+
(opt) =>
|
|
605
|
+
opt.label.toLowerCase() === lower ||
|
|
606
|
+
String(opt.value).toLowerCase() === lower ||
|
|
607
|
+
(opt.shortcut && opt.shortcut.toLowerCase() === lower),
|
|
608
|
+
) ?? null;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
if (matched) {
|
|
613
|
+
const desc = matched.description ? ` ${fmt.dim(`— ${matched.description}`)}` : '';
|
|
614
|
+
output.write(` ${fmt.boldGreen('→')} ${fmt.boldGreen(matched.label)}${desc}\n`);
|
|
615
|
+
return matched.value;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
output.write(
|
|
619
|
+
` ${fmt.yellow(`Please choose a number between 1 and ${options.length} (or an option name).`)}\n`,
|
|
620
|
+
);
|
|
621
|
+
}
|
|
622
|
+
},
|
|
623
|
+
|
|
624
|
+
close() {
|
|
625
|
+
if (closed) return;
|
|
626
|
+
closed = true;
|
|
627
|
+
rl.close();
|
|
628
|
+
},
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
async function promptYesNo(prompter, question, defaultYes = true) {
|
|
633
|
+
const options = defaultYes
|
|
634
|
+
? [
|
|
635
|
+
{ value: true, label: 'Yes', shortcut: 'y' },
|
|
636
|
+
{ value: false, label: 'No', shortcut: 'n' },
|
|
637
|
+
]
|
|
638
|
+
: [
|
|
639
|
+
{ value: false, label: 'No', shortcut: 'n' },
|
|
640
|
+
{ value: true, label: 'Yes', shortcut: 'y' },
|
|
641
|
+
];
|
|
642
|
+
return prompter.select({ question, options, defaultIndex: 0 });
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
export function checkCodePenProfileStatus(username, projectDir = process.cwd()) {
|
|
646
|
+
const trimmed = String(username ?? '').trim();
|
|
647
|
+
if (!trimmed || !PROFILE_NAME_PATTERN.test(trimmed)) {
|
|
648
|
+
return { status: 'unknown', cdpnBin: null };
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
const located = locateCdpnBinary(projectDir);
|
|
652
|
+
if (!located) {
|
|
653
|
+
return { status: 'unknown', cdpnBin: null };
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
const res = spawnSync(
|
|
657
|
+
located.bin.command,
|
|
658
|
+
[...located.bin.prefixArgs, '--profile', trimmed, 'auth', 'status', '--offline', '--json'],
|
|
659
|
+
{
|
|
660
|
+
cwd: projectDir,
|
|
661
|
+
encoding: 'utf8',
|
|
662
|
+
shell: located.bin.shell,
|
|
663
|
+
},
|
|
664
|
+
);
|
|
665
|
+
|
|
666
|
+
if (res.error) {
|
|
667
|
+
return { status: 'unknown', cdpnBin: located.bin };
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
let parsed = null;
|
|
671
|
+
const rawStdout = (res.stdout || '').trim();
|
|
672
|
+
if (rawStdout) {
|
|
673
|
+
try {
|
|
674
|
+
parsed = JSON.parse(rawStdout);
|
|
675
|
+
} catch {
|
|
676
|
+
const firstBrace = rawStdout.indexOf('{');
|
|
677
|
+
if (firstBrace !== -1) {
|
|
678
|
+
try {
|
|
679
|
+
parsed = JSON.parse(rawStdout.slice(firstBrace));
|
|
680
|
+
} catch {
|
|
681
|
+
parsed = null;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
const statusCode = parsed?.status?.code ?? null;
|
|
688
|
+
if (res.status === 0 && statusCode === 200) {
|
|
689
|
+
return { status: 'configured', cdpnBin: located.bin };
|
|
690
|
+
}
|
|
691
|
+
if (statusCode === 404) {
|
|
692
|
+
return { status: 'missing', cdpnBin: located.bin };
|
|
693
|
+
}
|
|
694
|
+
return { status: 'unknown', cdpnBin: located.bin };
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
async function promptInitOptions({
|
|
698
|
+
cwd = process.cwd(),
|
|
699
|
+
output = process.stdout,
|
|
700
|
+
prompter,
|
|
701
|
+
fmt = createFormatter(output),
|
|
702
|
+
}) {
|
|
703
|
+
const baseCwd = path.resolve(cwd);
|
|
704
|
+
|
|
705
|
+
output.write('\n');
|
|
706
|
+
output.write(
|
|
707
|
+
`${fmt.boldGreen('✦')} ${fmt.bold('Welcome to')} ${fmt.boldCyan('codepen-demokit')}${fmt.bold('!')}\n`,
|
|
708
|
+
);
|
|
709
|
+
output.write(
|
|
710
|
+
` ${fmt.dim("Let's get your new self-contained web demos repository set up.")}\n`,
|
|
711
|
+
);
|
|
712
|
+
|
|
713
|
+
output.write('\n');
|
|
714
|
+
const projectName = await prompter.askText({
|
|
715
|
+
question: 'Project name',
|
|
716
|
+
defaultValue: DEFAULT_SITE_CONFIG.title,
|
|
717
|
+
validate(raw) {
|
|
718
|
+
const trimmed = raw.trim();
|
|
719
|
+
if (CONTROL_CHAR_PATTERN.test(trimmed)) {
|
|
720
|
+
return { ok: false, error: 'Project name contains invalid control characters.' };
|
|
721
|
+
}
|
|
722
|
+
const value = trimmed || DEFAULT_SITE_CONFIG.title;
|
|
723
|
+
return { ok: true, value, displayValue: value };
|
|
724
|
+
},
|
|
725
|
+
});
|
|
726
|
+
|
|
727
|
+
output.write('\n');
|
|
728
|
+
const defaultDir = slugifyDirectoryName(projectName);
|
|
729
|
+
const { resolvedDir: targetDir, isCurrentDir } = await prompter.askText({
|
|
730
|
+
question: 'Directory',
|
|
731
|
+
defaultValue: defaultDir,
|
|
732
|
+
async validate(raw) {
|
|
733
|
+
const candidate = raw.trim() || defaultDir;
|
|
734
|
+
const result = await resolveTargetDirectory(candidate, baseCwd);
|
|
735
|
+
if (!result.ok) {
|
|
736
|
+
return { ok: false, error: result.error };
|
|
737
|
+
}
|
|
738
|
+
return { ok: true, value: result, displayValue: candidate };
|
|
739
|
+
},
|
|
740
|
+
});
|
|
741
|
+
|
|
742
|
+
output.write('\n');
|
|
743
|
+
const setupCodePenNow = await promptYesNo(
|
|
744
|
+
prompter,
|
|
745
|
+
'Do you want to set up your CodePen details right now?',
|
|
746
|
+
true,
|
|
747
|
+
);
|
|
748
|
+
|
|
749
|
+
let codepenUser = '';
|
|
750
|
+
let defaultVisibility = DEFAULT_VISIBILITY;
|
|
751
|
+
|
|
752
|
+
if (setupCodePenNow) {
|
|
753
|
+
output.write('\n');
|
|
754
|
+
codepenUser = await prompter.askText({
|
|
755
|
+
question: 'CodePen username',
|
|
756
|
+
validate(raw) {
|
|
757
|
+
const trimmed = raw.trim();
|
|
758
|
+
if (!trimmed) {
|
|
759
|
+
return {
|
|
760
|
+
ok: false,
|
|
761
|
+
error: 'Please enter a CodePen username (letters, numbers, ".", "_", or "-").',
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
if (!PROFILE_NAME_PATTERN.test(trimmed)) {
|
|
765
|
+
return {
|
|
766
|
+
ok: false,
|
|
767
|
+
error: `Invalid CodePen username "${trimmed}". Use letters, numbers, ".", "_", or "-" (without "@").`,
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
return { ok: true, value: trimmed, displayValue: trimmed };
|
|
771
|
+
},
|
|
772
|
+
});
|
|
773
|
+
|
|
774
|
+
output.write('\n');
|
|
775
|
+
const defaultVisIdx = Math.max(
|
|
776
|
+
0,
|
|
777
|
+
VISIBILITY_CHOICES.findIndex((choice) => choice.value === DEFAULT_VISIBILITY),
|
|
778
|
+
);
|
|
779
|
+
defaultVisibility = await prompter.select({
|
|
780
|
+
question: 'Default visibility for new Pens',
|
|
781
|
+
options: VISIBILITY_CHOICES,
|
|
782
|
+
defaultIndex: defaultVisIdx,
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
return {
|
|
787
|
+
projectName,
|
|
788
|
+
targetDir,
|
|
789
|
+
isCurrentDir,
|
|
790
|
+
codepenUser,
|
|
791
|
+
defaultVisibility,
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
async function readFrameworkMeta() {
|
|
796
|
+
const pkgJsonPath = path.join(PACKAGE_DIR, 'package.json');
|
|
797
|
+
const pkg = JSON.parse(await fs.readFile(pkgJsonPath, 'utf8'));
|
|
798
|
+
return {
|
|
799
|
+
version: pkg.version || '1.0.0',
|
|
800
|
+
codepenCommanderRange: pkg.dependencies?.['codepen-commander'] || '^1.3.0',
|
|
801
|
+
};
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
async function writeIfMissing(destPath, content) {
|
|
805
|
+
if (existsSync(destPath)) {
|
|
806
|
+
return 'skipped';
|
|
807
|
+
}
|
|
808
|
+
await fs.mkdir(path.dirname(destPath), { recursive: true });
|
|
809
|
+
await fs.writeFile(destPath, content, 'utf8');
|
|
810
|
+
return 'created';
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
async function copyIfMissing(srcPath, destPath) {
|
|
814
|
+
if (existsSync(destPath)) {
|
|
815
|
+
return 'skipped';
|
|
816
|
+
}
|
|
817
|
+
await fs.mkdir(path.dirname(destPath), { recursive: true });
|
|
818
|
+
await fs.copyFile(srcPath, destPath);
|
|
819
|
+
return 'created';
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
function printNextSteps({
|
|
823
|
+
output = process.stdout,
|
|
824
|
+
cwd = process.cwd(),
|
|
825
|
+
targetDir,
|
|
826
|
+
codepenUser = '',
|
|
827
|
+
needsAuthLogin = true,
|
|
828
|
+
fmt = createFormatter(output),
|
|
829
|
+
}) {
|
|
830
|
+
const writeLine = (line = '') => output.write(`${line}\n`);
|
|
831
|
+
const relDir = path.relative(path.resolve(cwd), path.resolve(targetDir));
|
|
832
|
+
const steps = [];
|
|
833
|
+
if (relDir && relDir !== '.') {
|
|
834
|
+
steps.push(fmt.cyan(`cd ${relDir}`));
|
|
835
|
+
}
|
|
836
|
+
steps.push(fmt.cyan('npm install'));
|
|
837
|
+
if (codepenUser) {
|
|
838
|
+
if (needsAuthLogin) {
|
|
839
|
+
steps.push(fmt.cyan(`npx cdpn auth login ${codepenUser}`));
|
|
840
|
+
}
|
|
841
|
+
} else {
|
|
842
|
+
steps.push(
|
|
843
|
+
`Edit ${fmt.magenta('config.json')} to set your CodePen profile ${fmt.dim('("codepen.user")')}`,
|
|
844
|
+
);
|
|
845
|
+
steps.push(fmt.cyan('npx cdpn auth login <your-codepen-username>'));
|
|
846
|
+
}
|
|
847
|
+
steps.push(fmt.cyan('npm start'));
|
|
848
|
+
|
|
849
|
+
writeLine();
|
|
850
|
+
writeLine(fmt.boldYellow('Next steps:'));
|
|
851
|
+
steps.forEach((step, idx) => {
|
|
852
|
+
writeLine(` ${fmt.dim(`${idx + 1}.`)} ${step}`);
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
export async function scaffoldProject({
|
|
857
|
+
targetDir,
|
|
858
|
+
projectName = DEFAULT_SITE_CONFIG.title,
|
|
859
|
+
isCurrentDir = false,
|
|
860
|
+
codepenUser = '',
|
|
861
|
+
defaultVisibility = DEFAULT_VISIBILITY,
|
|
862
|
+
cwd = process.cwd(),
|
|
863
|
+
output = process.stdout,
|
|
864
|
+
showNextSteps = true,
|
|
865
|
+
needsAuthLogin = Boolean(codepenUser),
|
|
866
|
+
}) {
|
|
867
|
+
const fmt = createFormatter(output);
|
|
868
|
+
const resolvedDir = path.resolve(targetDir);
|
|
869
|
+
await fs.mkdir(resolvedDir, { recursive: true });
|
|
870
|
+
|
|
871
|
+
const { version, codepenCommanderRange } = await readFrameworkMeta();
|
|
872
|
+
const packageName = isCurrentDir
|
|
873
|
+
? toValidPackageName(slugifyDirectoryName(projectName))
|
|
874
|
+
: toValidPackageName(path.basename(resolvedDir));
|
|
875
|
+
const results = [];
|
|
876
|
+
|
|
877
|
+
const record = (relPath, status) => {
|
|
878
|
+
results.push({ path: relPath, status });
|
|
879
|
+
};
|
|
880
|
+
|
|
881
|
+
const consumerPackageJson = {
|
|
882
|
+
name: packageName,
|
|
883
|
+
version: '1.0.0',
|
|
884
|
+
private: true,
|
|
885
|
+
description: 'Self-contained web demos synced with CodePen.',
|
|
886
|
+
type: 'module',
|
|
887
|
+
scripts: {
|
|
888
|
+
start: 'codepen-demokit start',
|
|
889
|
+
dev: 'codepen-demokit start',
|
|
890
|
+
build: 'codepen-demokit build',
|
|
891
|
+
'build:watch': 'codepen-demokit build --watch',
|
|
892
|
+
'cdpn:sync': 'codepen-demokit cdpn sync',
|
|
893
|
+
'cdpn:pull': 'codepen-demokit cdpn pull',
|
|
894
|
+
'cdpn:push': 'codepen-demokit cdpn push',
|
|
895
|
+
'cdpn:delete': 'codepen-demokit cdpn delete',
|
|
896
|
+
'cdpn:clone': 'codepen-demokit cdpn clone',
|
|
897
|
+
'cdpn:new': 'codepen-demokit cdpn new',
|
|
898
|
+
cdpn: 'cdpn',
|
|
899
|
+
},
|
|
900
|
+
engines: {
|
|
901
|
+
node: '>=20',
|
|
902
|
+
},
|
|
903
|
+
devDependencies: {
|
|
904
|
+
'codepen-commander': codepenCommanderRange,
|
|
905
|
+
'codepen-demokit': `^${version}`,
|
|
906
|
+
},
|
|
907
|
+
};
|
|
908
|
+
|
|
909
|
+
record(
|
|
910
|
+
'package.json',
|
|
911
|
+
await writeIfMissing(
|
|
912
|
+
path.join(resolvedDir, 'package.json'),
|
|
913
|
+
`${JSON.stringify(consumerPackageJson, null, 2)}\n`,
|
|
914
|
+
),
|
|
915
|
+
);
|
|
916
|
+
|
|
917
|
+
// Copy template files (note: gitignore is named `gitignore` inside templates/ so npm pack always includes it!)
|
|
918
|
+
const templateCopies = [
|
|
919
|
+
['gitignore', '.gitignore'],
|
|
920
|
+
['config.json.example', 'config.json.example'],
|
|
921
|
+
];
|
|
922
|
+
|
|
923
|
+
for (const [srcName, destName] of templateCopies) {
|
|
924
|
+
const status = await copyIfMissing(
|
|
925
|
+
path.join(TEMPLATES_DIR, srcName),
|
|
926
|
+
path.join(resolvedDir, destName),
|
|
927
|
+
);
|
|
928
|
+
record(destName, status);
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
const consumerConfig = {
|
|
932
|
+
site: {
|
|
933
|
+
title: projectName,
|
|
934
|
+
subtitle: DEFAULT_SITE_CONFIG.subtitle,
|
|
935
|
+
},
|
|
936
|
+
codepen: {
|
|
937
|
+
user: codepenUser,
|
|
938
|
+
defaultVisibility,
|
|
939
|
+
},
|
|
940
|
+
};
|
|
941
|
+
|
|
942
|
+
record(
|
|
943
|
+
'config.json',
|
|
944
|
+
await writeIfMissing(
|
|
945
|
+
path.join(resolvedDir, 'config.json'),
|
|
946
|
+
`${JSON.stringify(consumerConfig, null, 2)}\n`,
|
|
947
|
+
),
|
|
948
|
+
);
|
|
949
|
+
|
|
950
|
+
record(
|
|
951
|
+
'AGENTS.md',
|
|
952
|
+
await copyIfMissing(
|
|
953
|
+
path.join(TEMPLATES_DIR, 'AGENTS.md'),
|
|
954
|
+
path.join(resolvedDir, 'AGENTS.md'),
|
|
955
|
+
),
|
|
956
|
+
);
|
|
957
|
+
|
|
958
|
+
const readmeTemplate = await fs.readFile(path.join(TEMPLATES_DIR, 'README.md'), 'utf8');
|
|
959
|
+
const renderedReadme = readmeTemplate.replace(/^# .+/, () => `# ${projectName}`);
|
|
960
|
+
record(
|
|
961
|
+
'README.md',
|
|
962
|
+
await writeIfMissing(path.join(resolvedDir, 'README.md'), renderedReadme),
|
|
963
|
+
);
|
|
964
|
+
|
|
965
|
+
record(
|
|
966
|
+
'src/.gitkeep',
|
|
967
|
+
await writeIfMissing(path.join(resolvedDir, 'src', '.gitkeep'), ''),
|
|
968
|
+
);
|
|
969
|
+
|
|
970
|
+
const writeLine = (line = '') => output.write(`${line}\n`);
|
|
971
|
+
|
|
972
|
+
writeLine();
|
|
973
|
+
writeLine(
|
|
974
|
+
`${fmt.boldGreen('✓')} ${fmt.bold('Initialized')} ${fmt.boldCyan('codepen-demokit')} ${fmt.bold('project in')} ${fmt.magenta(resolvedDir)}`,
|
|
975
|
+
);
|
|
976
|
+
writeLine();
|
|
977
|
+
for (const item of results) {
|
|
978
|
+
if (item.status === 'created') {
|
|
979
|
+
writeLine(` ${fmt.boldGreen('+')} ${fmt.green('[CREATED]')} ${item.path}`);
|
|
980
|
+
} else {
|
|
981
|
+
writeLine(` ${fmt.yellow('-')} ${fmt.dim('[SKIPPED]')} ${fmt.dim(item.path)}`);
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
if (showNextSteps) {
|
|
986
|
+
printNextSteps({ output, cwd, targetDir: resolvedDir, codepenUser, needsAuthLogin, fmt });
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
return {
|
|
990
|
+
targetDir: resolvedDir,
|
|
991
|
+
projectName,
|
|
992
|
+
codepenUser,
|
|
993
|
+
defaultVisibility,
|
|
994
|
+
results,
|
|
995
|
+
};
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
export async function initProject({
|
|
999
|
+
cwd = process.cwd(),
|
|
1000
|
+
input = process.stdin,
|
|
1001
|
+
output = process.stdout,
|
|
1002
|
+
} = {}) {
|
|
1003
|
+
const fmt = createFormatter(output);
|
|
1004
|
+
const prompter = createPrompter({ input, output, fmt });
|
|
1005
|
+
|
|
1006
|
+
try {
|
|
1007
|
+
const options = await promptInitOptions({ cwd, output, prompter, fmt });
|
|
1008
|
+
const scaffoldResult = await scaffoldProject({
|
|
1009
|
+
...options,
|
|
1010
|
+
cwd,
|
|
1011
|
+
output,
|
|
1012
|
+
showNextSteps: false,
|
|
1013
|
+
});
|
|
1014
|
+
|
|
1015
|
+
let needsAuthLogin = Boolean(options.codepenUser);
|
|
1016
|
+
if (options.codepenUser) {
|
|
1017
|
+
const { status, cdpnBin } = checkCodePenProfileStatus(
|
|
1018
|
+
options.codepenUser,
|
|
1019
|
+
scaffoldResult.targetDir,
|
|
1020
|
+
);
|
|
1021
|
+
|
|
1022
|
+
if (status === 'configured') {
|
|
1023
|
+
output.write(
|
|
1024
|
+
`\n${fmt.boldGreen('✓')} CodePen authentication for ${fmt.boldCyan(options.codepenUser)} is already set up.\n`,
|
|
1025
|
+
);
|
|
1026
|
+
needsAuthLogin = false;
|
|
1027
|
+
} else if (status === 'missing' && cdpnBin) {
|
|
1028
|
+
output.write(
|
|
1029
|
+
`\n${fmt.boldYellow('!')} It looks like you haven't authenticated with CodePen as ${fmt.boldCyan(options.codepenUser)} yet.\n\n`,
|
|
1030
|
+
);
|
|
1031
|
+
let shouldLogin = false;
|
|
1032
|
+
try {
|
|
1033
|
+
shouldLogin = await promptYesNo(
|
|
1034
|
+
prompter,
|
|
1035
|
+
'Would you like to set up CodePen authentication now?',
|
|
1036
|
+
true,
|
|
1037
|
+
);
|
|
1038
|
+
} catch (err) {
|
|
1039
|
+
if (err instanceof InitCancelledError) {
|
|
1040
|
+
shouldLogin = false;
|
|
1041
|
+
} else {
|
|
1042
|
+
throw err;
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
// Release stdin cleanly before handing terminal control to `cdpn auth login`
|
|
1047
|
+
prompter.close();
|
|
1048
|
+
|
|
1049
|
+
if (shouldLogin) {
|
|
1050
|
+
output.write('\n');
|
|
1051
|
+
const loginRes = spawnSync(
|
|
1052
|
+
cdpnBin.command,
|
|
1053
|
+
[...cdpnBin.prefixArgs, 'auth', 'login', options.codepenUser],
|
|
1054
|
+
{
|
|
1055
|
+
cwd: scaffoldResult.targetDir,
|
|
1056
|
+
stdio: 'inherit',
|
|
1057
|
+
shell: cdpnBin.shell,
|
|
1058
|
+
},
|
|
1059
|
+
);
|
|
1060
|
+
if (!loginRes.error && loginRes.status === 0) {
|
|
1061
|
+
needsAuthLogin = false;
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
prompter.close();
|
|
1068
|
+
printNextSteps({
|
|
1069
|
+
output,
|
|
1070
|
+
cwd,
|
|
1071
|
+
targetDir: scaffoldResult.targetDir,
|
|
1072
|
+
codepenUser: options.codepenUser,
|
|
1073
|
+
needsAuthLogin,
|
|
1074
|
+
fmt,
|
|
1075
|
+
});
|
|
1076
|
+
|
|
1077
|
+
return {
|
|
1078
|
+
...scaffoldResult,
|
|
1079
|
+
authConfigured: Boolean(options.codepenUser) && !needsAuthLogin,
|
|
1080
|
+
};
|
|
1081
|
+
} finally {
|
|
1082
|
+
prompter.close();
|
|
1083
|
+
}
|
|
1084
|
+
}
|