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
|
@@ -0,0 +1,507 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import { watch } from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { readClassicHeadMetadata, readPenBlocks } from './blocks.mjs';
|
|
6
|
+
|
|
7
|
+
const MAX_SCAN_DEPTH = 4;
|
|
8
|
+
const MAX_HTML_HEAD_BYTES = 16 * 1024;
|
|
9
|
+
const MAX_CDPN_JSON_BYTES = 64 * 1024;
|
|
10
|
+
const MAX_DEMO_TAGS = 10;
|
|
11
|
+
const CDPN_JSON_FILENAME = '.cdpn.json';
|
|
12
|
+
|
|
13
|
+
const ACRONYMS = new Map([
|
|
14
|
+
['ai', 'AI'],
|
|
15
|
+
['api', 'API'],
|
|
16
|
+
['apis', 'APIs'],
|
|
17
|
+
['aria', 'ARIA'],
|
|
18
|
+
['cls', 'CLS'],
|
|
19
|
+
['css', 'CSS'],
|
|
20
|
+
['cwv', 'CWV'],
|
|
21
|
+
['dom', 'DOM'],
|
|
22
|
+
['html', 'HTML'],
|
|
23
|
+
['http', 'HTTP'],
|
|
24
|
+
['inp', 'INP'],
|
|
25
|
+
['js', 'JS'],
|
|
26
|
+
['json', 'JSON'],
|
|
27
|
+
['lcp', 'LCP'],
|
|
28
|
+
['mcp', 'MCP'],
|
|
29
|
+
['pwa', 'PWA'],
|
|
30
|
+
['svg', 'SVG'],
|
|
31
|
+
['ui', 'UI'],
|
|
32
|
+
['url', 'URL'],
|
|
33
|
+
['ux', 'UX'],
|
|
34
|
+
['wasm', 'WASM'],
|
|
35
|
+
['webgl', 'WebGL'],
|
|
36
|
+
['webgpu', 'WebGPU'],
|
|
37
|
+
['webmcp', 'WebMCP'],
|
|
38
|
+
]);
|
|
39
|
+
|
|
40
|
+
const MINOR_WORDS = new Set([
|
|
41
|
+
'a',
|
|
42
|
+
'an',
|
|
43
|
+
'and',
|
|
44
|
+
'as',
|
|
45
|
+
'at',
|
|
46
|
+
'by',
|
|
47
|
+
'for',
|
|
48
|
+
'from',
|
|
49
|
+
'in',
|
|
50
|
+
'of',
|
|
51
|
+
'on',
|
|
52
|
+
'or',
|
|
53
|
+
'the',
|
|
54
|
+
'to',
|
|
55
|
+
'with',
|
|
56
|
+
]);
|
|
57
|
+
|
|
58
|
+
const NAMED_HTML_ENTITIES = new Map([
|
|
59
|
+
['amp', '&'],
|
|
60
|
+
['apos', "'"],
|
|
61
|
+
['gt', '>'],
|
|
62
|
+
['lt', '<'],
|
|
63
|
+
['mdash', '—'],
|
|
64
|
+
['nbsp', ' '],
|
|
65
|
+
['ndash', '–'],
|
|
66
|
+
['quot', '"'],
|
|
67
|
+
]);
|
|
68
|
+
|
|
69
|
+
const utf8Decoder = new TextDecoder('utf-8');
|
|
70
|
+
|
|
71
|
+
function isWithinRoot(candidatePath, rootPath) {
|
|
72
|
+
return candidatePath === rootPath || candidatePath.startsWith(rootPath + path.sep);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function compareNatural(a, b) {
|
|
76
|
+
return a.localeCompare(b, 'en', { numeric: true, sensitivity: 'base' });
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function formatFolderTitle(folderName) {
|
|
80
|
+
const words = folderName.split(/[-_]+/).filter(Boolean);
|
|
81
|
+
return words
|
|
82
|
+
.map((word, index) => {
|
|
83
|
+
const lower = word.toLowerCase();
|
|
84
|
+
if (ACRONYMS.has(lower)) {
|
|
85
|
+
return ACRONYMS.get(lower);
|
|
86
|
+
}
|
|
87
|
+
if (index > 0 && index < words.length - 1 && MINOR_WORDS.has(lower)) {
|
|
88
|
+
return lower;
|
|
89
|
+
}
|
|
90
|
+
return word[0].toUpperCase() + word.slice(1);
|
|
91
|
+
})
|
|
92
|
+
.join(' ');
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function decodeHtmlEntities(input) {
|
|
96
|
+
return input.replace(/&(?:#(\d{1,7})|#x([0-9a-fA-F]{1,6})|([a-zA-Z]{2,10}));/g, (match, dec, hex, named) => {
|
|
97
|
+
if (dec || hex) {
|
|
98
|
+
const codePoint = Number.parseInt(dec ?? hex, dec ? 10 : 16);
|
|
99
|
+
if (Number.isInteger(codePoint) && codePoint >= 0 && codePoint <= 0x10ffff) {
|
|
100
|
+
return String.fromCodePoint(codePoint);
|
|
101
|
+
}
|
|
102
|
+
return match;
|
|
103
|
+
}
|
|
104
|
+
return NAMED_HTML_ENTITIES.get(named.toLowerCase()) ?? match;
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function normalizePlainText(value, maxLength) {
|
|
109
|
+
const cleaned = String(value).replace(/\s+/g, ' ').trim();
|
|
110
|
+
if (!cleaned) return null;
|
|
111
|
+
return cleaned.length > maxLength ? `${cleaned.slice(0, maxLength - 1)}…` : cleaned;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function normalizeText(value, maxLength) {
|
|
115
|
+
return normalizePlainText(decodeHtmlEntities(value), maxLength);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function extractTitle(headHtml) {
|
|
119
|
+
const match = /<title\b[^>]{0,200}>([\s\S]{0,500}?)<\/title>/i.exec(headHtml);
|
|
120
|
+
return match ? normalizeText(match[1], 160) : null;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function extractMetaDescription(headHtml) {
|
|
124
|
+
const metaTagPattern = /<meta\b[^>]{1,1000}>/gi;
|
|
125
|
+
const attrPattern = /([a-zA-Z_:][\w:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/g;
|
|
126
|
+
|
|
127
|
+
for (const tagMatch of headHtml.matchAll(metaTagPattern)) {
|
|
128
|
+
let metaName = null;
|
|
129
|
+
let metaContent = null;
|
|
130
|
+
|
|
131
|
+
for (const attrMatch of tagMatch[0].matchAll(attrPattern)) {
|
|
132
|
+
const key = attrMatch[1].toLowerCase();
|
|
133
|
+
const value = attrMatch[2] ?? attrMatch[3] ?? attrMatch[4] ?? '';
|
|
134
|
+
if (key === 'name') {
|
|
135
|
+
metaName = value.trim().toLowerCase();
|
|
136
|
+
} else if (key === 'content') {
|
|
137
|
+
metaContent = value;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
if (metaName === 'description' && metaContent !== null) {
|
|
142
|
+
return normalizeText(metaContent, 320);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function extractCdpnTags(rawTags) {
|
|
150
|
+
if (!Array.isArray(rawTags)) return [];
|
|
151
|
+
const seen = new Set();
|
|
152
|
+
const tags = [];
|
|
153
|
+
for (const rawTag of rawTags) {
|
|
154
|
+
if (typeof rawTag !== 'string') continue;
|
|
155
|
+
const normalized = normalizePlainText(rawTag, 48);
|
|
156
|
+
if (!normalized) continue;
|
|
157
|
+
const key = normalized.toLowerCase();
|
|
158
|
+
if (seen.has(key)) continue;
|
|
159
|
+
seen.add(key);
|
|
160
|
+
tags.push(normalized);
|
|
161
|
+
if (tags.length >= MAX_DEMO_TAGS) break;
|
|
162
|
+
}
|
|
163
|
+
return tags;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function sanitizeCodePenUrl(rawUrl) {
|
|
167
|
+
if (typeof rawUrl !== 'string') return null;
|
|
168
|
+
try {
|
|
169
|
+
const parsed = new URL(rawUrl.trim());
|
|
170
|
+
if (parsed.protocol !== 'https:') return null;
|
|
171
|
+
if (parsed.hostname !== 'codepen.io' && !parsed.hostname.endsWith('.codepen.io')) {
|
|
172
|
+
return null;
|
|
173
|
+
}
|
|
174
|
+
return parsed.href;
|
|
175
|
+
} catch {
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function readPartialUtf8(filePath, maxBytes) {
|
|
181
|
+
const handle = await fs.open(filePath, 'r');
|
|
182
|
+
try {
|
|
183
|
+
const buffer = Buffer.alloc(maxBytes);
|
|
184
|
+
const { bytesRead } = await handle.read(buffer, 0, maxBytes, 0);
|
|
185
|
+
return utf8Decoder.decode(buffer.subarray(0, bytesRead));
|
|
186
|
+
} finally {
|
|
187
|
+
await handle.close();
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async function resolveSafeRealFile(candidatePath, srcDir, srcRealpath) {
|
|
192
|
+
if (!isWithinRoot(candidatePath, srcDir)) return null;
|
|
193
|
+
let stat;
|
|
194
|
+
try {
|
|
195
|
+
stat = await fs.stat(candidatePath);
|
|
196
|
+
} catch {
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
if (!stat.isFile()) return null;
|
|
200
|
+
|
|
201
|
+
try {
|
|
202
|
+
const realPath = await fs.realpath(candidatePath);
|
|
203
|
+
if (!isWithinRoot(realPath, srcRealpath)) return null;
|
|
204
|
+
return { realPath, size: stat.size };
|
|
205
|
+
} catch {
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async function resolveSafeRealDir(candidatePath, srcDir, srcRealpath) {
|
|
211
|
+
if (!isWithinRoot(candidatePath, srcDir)) return null;
|
|
212
|
+
let stat;
|
|
213
|
+
try {
|
|
214
|
+
stat = await fs.stat(candidatePath);
|
|
215
|
+
} catch {
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
218
|
+
if (!stat.isDirectory()) return null;
|
|
219
|
+
|
|
220
|
+
try {
|
|
221
|
+
const realPath = await fs.realpath(candidatePath);
|
|
222
|
+
if (!isWithinRoot(realPath, srcRealpath)) return null;
|
|
223
|
+
return realPath;
|
|
224
|
+
} catch {
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function readDemoEntry(segments, demoRealpath, srcDir, srcRealpath) {
|
|
230
|
+
const demoDir = path.resolve(srcDir, ...segments);
|
|
231
|
+
const cdpnFile = await resolveSafeRealFile(
|
|
232
|
+
path.join(demoDir, CDPN_JSON_FILENAME),
|
|
233
|
+
srcDir,
|
|
234
|
+
srcRealpath,
|
|
235
|
+
);
|
|
236
|
+
const indexFile = await resolveSafeRealFile(path.join(demoDir, 'index.html'), srcDir, srcRealpath);
|
|
237
|
+
|
|
238
|
+
let classicIndexFile = null;
|
|
239
|
+
let hasUnsupportedBlocks = false;
|
|
240
|
+
if (!indexFile) {
|
|
241
|
+
const penBlocks = await readPenBlocks(demoRealpath, srcRealpath);
|
|
242
|
+
if (penBlocks?.unsupportedBlocks?.length > 0) {
|
|
243
|
+
hasUnsupportedBlocks = true;
|
|
244
|
+
} else if (penBlocks?.hasClassic) {
|
|
245
|
+
classicIndexFile = await resolveSafeRealFile(
|
|
246
|
+
path.join(demoDir, 'index.pen.html'),
|
|
247
|
+
srcDir,
|
|
248
|
+
srcRealpath,
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
if (!cdpnFile && !indexFile && !classicIndexFile && !hasUnsupportedBlocks) return null;
|
|
254
|
+
|
|
255
|
+
let htmlTitle = null;
|
|
256
|
+
let htmlDescription = null;
|
|
257
|
+
if (indexFile) {
|
|
258
|
+
try {
|
|
259
|
+
const headHtml = await readPartialUtf8(indexFile.realPath, MAX_HTML_HEAD_BYTES);
|
|
260
|
+
htmlTitle = extractTitle(headHtml);
|
|
261
|
+
htmlDescription = extractMetaDescription(headHtml);
|
|
262
|
+
} catch {
|
|
263
|
+
// Fall back to .cdpn.json or folder name when HTML metadata cannot be read
|
|
264
|
+
}
|
|
265
|
+
} else if (classicIndexFile) {
|
|
266
|
+
try {
|
|
267
|
+
const classicHead = await readClassicHeadMetadata(demoRealpath, srcRealpath);
|
|
268
|
+
if (classicHead) {
|
|
269
|
+
htmlTitle = extractTitle(classicHead);
|
|
270
|
+
htmlDescription = extractMetaDescription(classicHead);
|
|
271
|
+
}
|
|
272
|
+
} catch {
|
|
273
|
+
// Fall back to .cdpn.json or folder name when classic config metadata cannot be read
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
let codepenUrl = null;
|
|
278
|
+
let cdpnTitle = null;
|
|
279
|
+
let cdpnDescription = null;
|
|
280
|
+
let tags = [];
|
|
281
|
+
if (cdpnFile && cdpnFile.size <= MAX_CDPN_JSON_BYTES) {
|
|
282
|
+
try {
|
|
283
|
+
const rawJson = await fs.readFile(cdpnFile.realPath, 'utf8');
|
|
284
|
+
const parsed = JSON.parse(rawJson);
|
|
285
|
+
codepenUrl = sanitizeCodePenUrl(parsed?.url);
|
|
286
|
+
if (typeof parsed?.info?.title === 'string') {
|
|
287
|
+
cdpnTitle = normalizePlainText(parsed.info.title, 160);
|
|
288
|
+
}
|
|
289
|
+
if (typeof parsed?.info?.description === 'string') {
|
|
290
|
+
cdpnDescription = normalizePlainText(parsed.info.description, 320);
|
|
291
|
+
}
|
|
292
|
+
tags = extractCdpnTags(parsed?.info?.tags);
|
|
293
|
+
} catch {
|
|
294
|
+
codepenUrl = null;
|
|
295
|
+
tags = [];
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
return {
|
|
300
|
+
title: cdpnTitle ?? htmlTitle ?? formatFolderTitle(segments.at(-1)),
|
|
301
|
+
description: cdpnDescription ?? htmlDescription,
|
|
302
|
+
tags,
|
|
303
|
+
path: `${segments.join('/')}/`,
|
|
304
|
+
href: `./${segments.map(encodeURIComponent).join('/')}/`,
|
|
305
|
+
codepenUrl,
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
async function scanGroupNode(dirRealpath, segments, depth, visitedRealpaths, srcDir, srcRealpath) {
|
|
310
|
+
if (depth > MAX_SCAN_DEPTH) return { demos: [], groups: [] };
|
|
311
|
+
|
|
312
|
+
let entries;
|
|
313
|
+
try {
|
|
314
|
+
entries = await fs.readdir(dirRealpath, { withFileTypes: true });
|
|
315
|
+
} catch {
|
|
316
|
+
return { demos: [], groups: [] };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const demos = [];
|
|
320
|
+
const groups = [];
|
|
321
|
+
|
|
322
|
+
for (const entry of entries) {
|
|
323
|
+
if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
|
|
324
|
+
|
|
325
|
+
const childSegments = [...segments, entry.name];
|
|
326
|
+
const childCandidate = path.resolve(srcDir, ...childSegments);
|
|
327
|
+
const childRealDir = await resolveSafeRealDir(childCandidate, srcDir, srcRealpath);
|
|
328
|
+
if (!childRealDir || visitedRealpaths.has(childRealDir)) continue;
|
|
329
|
+
|
|
330
|
+
visitedRealpaths.add(childRealDir);
|
|
331
|
+
|
|
332
|
+
const demoEntry = await readDemoEntry(childSegments, childRealDir, srcDir, srcRealpath);
|
|
333
|
+
if (demoEntry) {
|
|
334
|
+
demos.push(demoEntry);
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const subNode = await scanGroupNode(childRealDir, childSegments, depth + 1, visitedRealpaths, srcDir, srcRealpath);
|
|
339
|
+
if (subNode.demos.length > 0 || subNode.groups.length > 0) {
|
|
340
|
+
groups.push({
|
|
341
|
+
id: childSegments.join('/'),
|
|
342
|
+
title: formatFolderTitle(entry.name),
|
|
343
|
+
demos: subNode.demos,
|
|
344
|
+
groups: subNode.groups,
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
return {
|
|
350
|
+
demos: demos.toSorted((a, b) => compareNatural(a.path, b.path)),
|
|
351
|
+
groups: groups.toSorted((a, b) => compareNatural(a.id, b.id)),
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
export async function scanDemos(projectDir = process.cwd()) {
|
|
356
|
+
const srcDir = path.resolve(projectDir, 'src');
|
|
357
|
+
let srcRealpath;
|
|
358
|
+
try {
|
|
359
|
+
srcRealpath = await fs.realpath(srcDir);
|
|
360
|
+
} catch {
|
|
361
|
+
throw new Error(`Directory "src/" not found in ${path.resolve(projectDir)}.`);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const visitedRealpaths = new Set([srcRealpath]);
|
|
365
|
+
const root = await scanGroupNode(srcRealpath, [], 0, visitedRealpaths, srcDir, srcRealpath);
|
|
366
|
+
return {
|
|
367
|
+
groups: root.groups,
|
|
368
|
+
standalone: root.demos,
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function countGroupDemos(groups) {
|
|
373
|
+
return groups.reduce(
|
|
374
|
+
(total, group) => total + group.demos.length + countGroupDemos(group.groups ?? []),
|
|
375
|
+
0,
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
export function countDemos(manifest) {
|
|
380
|
+
return (manifest.standalone?.length ?? 0) + countGroupDemos(manifest.groups ?? []);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export async function buildDemosJson({
|
|
384
|
+
projectDir = process.cwd(),
|
|
385
|
+
outputFile = path.resolve(projectDir, 'dist', 'demos.json'),
|
|
386
|
+
} = {}) {
|
|
387
|
+
const resolvedProjectDir = path.resolve(projectDir);
|
|
388
|
+
const resolvedOutputFile = path.resolve(outputFile);
|
|
389
|
+
if (!isWithinRoot(resolvedOutputFile, resolvedProjectDir)) {
|
|
390
|
+
throw new Error(`Refusing to write demos.json outside project directory: ${resolvedOutputFile}`);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
const manifest = await scanDemos(resolvedProjectDir);
|
|
394
|
+
const serialized = `${JSON.stringify(manifest, null, 2)}\n`;
|
|
395
|
+
const demoCount = countDemos(manifest);
|
|
396
|
+
|
|
397
|
+
let existing = null;
|
|
398
|
+
try {
|
|
399
|
+
existing = await fs.readFile(resolvedOutputFile, 'utf8');
|
|
400
|
+
} catch {
|
|
401
|
+
existing = null;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
if (existing === serialized) {
|
|
405
|
+
return { changed: false, demoCount, manifest, outputFile: resolvedOutputFile };
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const outputDir = path.dirname(resolvedOutputFile);
|
|
409
|
+
await fs.mkdir(outputDir, { recursive: true });
|
|
410
|
+
|
|
411
|
+
const tempOutputFile = path.join(
|
|
412
|
+
outputDir,
|
|
413
|
+
`.demos.json.${process.pid}.${randomBytes(4).toString('hex')}.tmp`,
|
|
414
|
+
);
|
|
415
|
+
try {
|
|
416
|
+
await fs.writeFile(tempOutputFile, serialized, 'utf8');
|
|
417
|
+
await fs.rename(tempOutputFile, resolvedOutputFile);
|
|
418
|
+
} catch (error) {
|
|
419
|
+
await fs.rm(tempOutputFile, { force: true }).catch(() => {});
|
|
420
|
+
throw error;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
return { changed: true, demoCount, manifest, outputFile: resolvedOutputFile };
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function shouldIgnoreWatchEvent(rawFilename) {
|
|
427
|
+
if (typeof rawFilename !== 'string' || !rawFilename) return false;
|
|
428
|
+
const normalized = rawFilename.split(path.sep).join('/');
|
|
429
|
+
if (
|
|
430
|
+
normalized === 'demos.json' ||
|
|
431
|
+
(normalized.startsWith('.demos.json.') && normalized.endsWith('.tmp'))
|
|
432
|
+
) {
|
|
433
|
+
return true;
|
|
434
|
+
}
|
|
435
|
+
const segments = normalized.split('/');
|
|
436
|
+
const base = segments.at(-1);
|
|
437
|
+
if (base === '.DS_Store') return true;
|
|
438
|
+
if (segments.includes('node_modules') || segments.includes('.git')) return true;
|
|
439
|
+
return false;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
export function watchDemos({
|
|
443
|
+
projectDir = process.cwd(),
|
|
444
|
+
outputFile = path.resolve(projectDir, 'dist', 'demos.json'),
|
|
445
|
+
debounceMs = 150,
|
|
446
|
+
onRebuild,
|
|
447
|
+
onError,
|
|
448
|
+
} = {}) {
|
|
449
|
+
const srcDir = path.resolve(projectDir, 'src');
|
|
450
|
+
let timer = null;
|
|
451
|
+
let isBuilding = false;
|
|
452
|
+
let pendingRebuild = false;
|
|
453
|
+
let closed = false;
|
|
454
|
+
|
|
455
|
+
async function runBuild() {
|
|
456
|
+
if (closed) return;
|
|
457
|
+
if (isBuilding) {
|
|
458
|
+
pendingRebuild = true;
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
isBuilding = true;
|
|
463
|
+
try {
|
|
464
|
+
const result = await buildDemosJson({ projectDir, outputFile });
|
|
465
|
+
if (result.changed) {
|
|
466
|
+
onRebuild?.(result);
|
|
467
|
+
}
|
|
468
|
+
} catch (error) {
|
|
469
|
+
onError?.(error);
|
|
470
|
+
} finally {
|
|
471
|
+
isBuilding = false;
|
|
472
|
+
if (pendingRebuild && !closed) {
|
|
473
|
+
pendingRebuild = false;
|
|
474
|
+
scheduleBuild();
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
function scheduleBuild() {
|
|
480
|
+
if (closed) return;
|
|
481
|
+
if (timer) clearTimeout(timer);
|
|
482
|
+
timer = setTimeout(() => {
|
|
483
|
+
timer = null;
|
|
484
|
+
void runBuild();
|
|
485
|
+
}, debounceMs);
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
const watcher = watch(srcDir, { recursive: true }, (_eventType, filename) => {
|
|
489
|
+
if (shouldIgnoreWatchEvent(filename)) return;
|
|
490
|
+
scheduleBuild();
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
watcher.on('error', (error) => {
|
|
494
|
+
onError?.(error);
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
return {
|
|
498
|
+
close() {
|
|
499
|
+
closed = true;
|
|
500
|
+
if (timer) {
|
|
501
|
+
clearTimeout(timer);
|
|
502
|
+
timer = null;
|
|
503
|
+
}
|
|
504
|
+
watcher.close();
|
|
505
|
+
},
|
|
506
|
+
};
|
|
507
|
+
}
|