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/blocks.mjs
ADDED
|
@@ -0,0 +1,1067 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { escapeHtml } from './config.mjs';
|
|
5
|
+
|
|
6
|
+
export const PEN_HTML_SUFFIX = '.pen.html';
|
|
7
|
+
|
|
8
|
+
const CODEPEN_DIR = '.codepen';
|
|
9
|
+
const PEN_CONFIG_FILENAME = 'pen.config.json';
|
|
10
|
+
const CLASSIC_CONFIG_FILENAME = 'classic.config.json';
|
|
11
|
+
const CDPN_JSON_FILENAME = '.cdpn.json';
|
|
12
|
+
const PACKAGE_JSON_FILENAME = 'package.json';
|
|
13
|
+
|
|
14
|
+
const MAX_CONFIG_BYTES = 256 * 1024;
|
|
15
|
+
const MAX_HTML_BYTES = 10 * 1024 * 1024;
|
|
16
|
+
const MAX_SCRIPT_SNIFF_BYTES = 64 * 1024;
|
|
17
|
+
const MAX_WALK_DEPTH = 16;
|
|
18
|
+
|
|
19
|
+
const ESM_SH_ORIGIN = 'https://esm.sh';
|
|
20
|
+
const CONTROL_CHAR_PATTERN = /[\x00-\x1f\x7f]/;
|
|
21
|
+
const URL_SCHEME_PATTERN = /^[a-zA-Z][a-zA-Z0-9+.-]*:/;
|
|
22
|
+
const NPM_PACKAGE_NAME_PATTERN =
|
|
23
|
+
/^(?:@[a-zA-Z0-9~][a-zA-Z0-9._~-]*\/)?[a-zA-Z0-9~][a-zA-Z0-9._~-]*$/;
|
|
24
|
+
const SAFE_VERSION_PATTERN = /^[a-zA-Z0-9._^~*+-][a-zA-Z0-9._^~*+<>=| -]*$/;
|
|
25
|
+
const ALLOWED_SCRIPT_TYPES = new Set(['module', 'text/javascript']);
|
|
26
|
+
const SUPPORTED_BLOCK_TYPES = new Set(['validate', 'fingerprint', 'classic', 'packages']);
|
|
27
|
+
|
|
28
|
+
const utf8Decoder = new TextDecoder('utf-8');
|
|
29
|
+
|
|
30
|
+
function isWithinRoot(candidatePath, rootPath) {
|
|
31
|
+
return candidatePath === rootPath || candidatePath.startsWith(rootPath + path.sep);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function isPlainObject(value) {
|
|
35
|
+
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function resolveSafeFile(candidatePath, rootRealpath) {
|
|
39
|
+
const resolved = path.resolve(candidatePath);
|
|
40
|
+
if (!isWithinRoot(resolved, rootRealpath)) return null;
|
|
41
|
+
|
|
42
|
+
let lstat;
|
|
43
|
+
try {
|
|
44
|
+
lstat = await fs.lstat(resolved);
|
|
45
|
+
} catch {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
if (lstat.isSymbolicLink() || !lstat.isFile()) return null;
|
|
49
|
+
|
|
50
|
+
try {
|
|
51
|
+
const realPath = await fs.realpath(resolved);
|
|
52
|
+
if (!isWithinRoot(realPath, rootRealpath)) return null;
|
|
53
|
+
return { realPath, size: lstat.size };
|
|
54
|
+
} catch {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function readSafeJsonObject(filePath, rootRealpath, maxBytes = MAX_CONFIG_BYTES) {
|
|
60
|
+
const file = await resolveSafeFile(filePath, rootRealpath);
|
|
61
|
+
if (!file || file.size > maxBytes) return null;
|
|
62
|
+
|
|
63
|
+
try {
|
|
64
|
+
const raw = await fs.readFile(file.realPath, 'utf8');
|
|
65
|
+
const parsed = JSON.parse(raw);
|
|
66
|
+
return isPlainObject(parsed) ? parsed : null;
|
|
67
|
+
} catch {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function readPartialUtf8(filePath, maxBytes) {
|
|
73
|
+
const handle = await fs.open(filePath, 'r');
|
|
74
|
+
try {
|
|
75
|
+
const buffer = Buffer.alloc(maxBytes);
|
|
76
|
+
const { bytesRead } = await handle.read(buffer, 0, maxBytes, 0);
|
|
77
|
+
return utf8Decoder.decode(buffer.subarray(0, bytesRead));
|
|
78
|
+
} finally {
|
|
79
|
+
await handle.close();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function normalizeBlockType(rawName) {
|
|
84
|
+
return String(rawName).trim().toLowerCase().replace(/-\d+$/, '');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Inspects `<penDir>/.codepen/pen.config.json` and detects enabled supported blocks
|
|
89
|
+
* (`classic`, `packages`; `validate` and `fingerprint` are default no-ops) as well as
|
|
90
|
+
* any active unsupported blocks.
|
|
91
|
+
*/
|
|
92
|
+
export async function readPenBlocks(penDir, rootRealpath) {
|
|
93
|
+
const configPath = path.join(penDir, CODEPEN_DIR, PEN_CONFIG_FILENAME);
|
|
94
|
+
const parsed = await readSafeJsonObject(configPath, rootRealpath);
|
|
95
|
+
if (!parsed || !isPlainObject(parsed.blocks)) return null;
|
|
96
|
+
|
|
97
|
+
const activeBlocks = new Set();
|
|
98
|
+
const unsupportedMap = new Map();
|
|
99
|
+
|
|
100
|
+
for (const [key, block] of Object.entries(parsed.blocks)) {
|
|
101
|
+
if (!isPlainObject(block)) continue;
|
|
102
|
+
if (block.disabled === true) continue;
|
|
103
|
+
|
|
104
|
+
const rawName =
|
|
105
|
+
typeof block.name === 'string' && block.name.trim() ? block.name.trim() : key;
|
|
106
|
+
const cleanedName = String(rawName).replace(/[\x00-\x1f\x7f]+/g, '').trim().slice(0, 128);
|
|
107
|
+
const blockType = normalizeBlockType(cleanedName);
|
|
108
|
+
if (!blockType) continue;
|
|
109
|
+
|
|
110
|
+
activeBlocks.add(blockType);
|
|
111
|
+
if (!SUPPORTED_BLOCK_TYPES.has(blockType) && !unsupportedMap.has(blockType)) {
|
|
112
|
+
unsupportedMap.set(blockType, cleanedName);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const unsupportedBlocks = [...unsupportedMap.values()].sort((a, b) =>
|
|
117
|
+
a.localeCompare(b, 'en', { numeric: true, sensitivity: 'base' }),
|
|
118
|
+
);
|
|
119
|
+
|
|
120
|
+
return {
|
|
121
|
+
penDir,
|
|
122
|
+
hasClassic: activeBlocks.has('classic'),
|
|
123
|
+
hasPackages: activeBlocks.has('packages'),
|
|
124
|
+
unsupportedBlocks,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Walks upward from `targetDir` to `rootRealpath` (inclusive) to find the nearest
|
|
130
|
+
* enclosing Pen directory containing `.codepen/pen.config.json`.
|
|
131
|
+
*/
|
|
132
|
+
export async function findPenContext(targetDir, rootRealpath) {
|
|
133
|
+
let currentDir = path.resolve(targetDir);
|
|
134
|
+
if (!isWithinRoot(currentDir, rootRealpath)) return null;
|
|
135
|
+
|
|
136
|
+
for (let depth = 0; depth <= MAX_WALK_DEPTH; depth++) {
|
|
137
|
+
const blocks = await readPenBlocks(currentDir, rootRealpath);
|
|
138
|
+
if (blocks) return blocks;
|
|
139
|
+
|
|
140
|
+
if (currentDir === rootRealpath) break;
|
|
141
|
+
const parent = path.dirname(currentDir);
|
|
142
|
+
if (parent === currentDir || !isWithinRoot(parent, rootRealpath)) break;
|
|
143
|
+
currentDir = parent;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Reads the optional `head` HTML string from `<penDir>/.codepen/classic.config.json`.
|
|
151
|
+
*/
|
|
152
|
+
export async function readClassicHeadMetadata(penDir, rootRealpath) {
|
|
153
|
+
const classicConfigPath = path.join(penDir, CODEPEN_DIR, CLASSIC_CONFIG_FILENAME);
|
|
154
|
+
const classicConfig = await readSafeJsonObject(classicConfigPath, rootRealpath);
|
|
155
|
+
if (!classicConfig || typeof classicConfig.head !== 'string') return null;
|
|
156
|
+
const trimmed = classicConfig.head.trim();
|
|
157
|
+
return trimmed || null;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function resolveClassicAssetUrl(rawUrl, htmlRelDirPosix) {
|
|
161
|
+
if (typeof rawUrl !== 'string') return null;
|
|
162
|
+
const trimmed = rawUrl.trim();
|
|
163
|
+
if (!trimmed || CONTROL_CHAR_PATTERN.test(trimmed)) return null;
|
|
164
|
+
|
|
165
|
+
// Allow external HTTP(S) and protocol-relative URLs untouched
|
|
166
|
+
if (
|
|
167
|
+
trimmed.startsWith('https://') ||
|
|
168
|
+
trimmed.startsWith('http://') ||
|
|
169
|
+
trimmed.startsWith('//')
|
|
170
|
+
) {
|
|
171
|
+
return { href: trimmed, localPenRelPosix: null };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Reject any other explicit URL scheme (e.g. javascript:, data:, vbscript:, file:)
|
|
175
|
+
if (URL_SCHEME_PATTERN.test(trimmed)) {
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const splitMatch = /^([^?#]*)(.*)$/.exec(trimmed);
|
|
180
|
+
const rawPath = splitMatch ? splitMatch[1] : trimmed;
|
|
181
|
+
const suffix = splitMatch ? splitMatch[2] : '';
|
|
182
|
+
|
|
183
|
+
// Pen-root-relative path (e.g. "/style.css", "/script.js"): rewrite relative to the HTML file
|
|
184
|
+
// so the demo works both at "/<group>/<demo>/" and when served directly as "/".
|
|
185
|
+
if (rawPath.startsWith('/')) {
|
|
186
|
+
const stripped = rawPath.replace(/^\/+/, '');
|
|
187
|
+
if (!stripped) return null;
|
|
188
|
+
const normalizedTarget = path.posix.normalize(stripped);
|
|
189
|
+
if (
|
|
190
|
+
!normalizedTarget ||
|
|
191
|
+
normalizedTarget === '.' ||
|
|
192
|
+
normalizedTarget === '..' ||
|
|
193
|
+
normalizedTarget.startsWith('../')
|
|
194
|
+
) {
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
let relativeHref = path.posix.relative(htmlRelDirPosix, normalizedTarget);
|
|
199
|
+
if (!relativeHref) return null;
|
|
200
|
+
if (!relativeHref.startsWith('./') && !relativeHref.startsWith('../')) {
|
|
201
|
+
relativeHref = `./${relativeHref}`;
|
|
202
|
+
}
|
|
203
|
+
return { href: `${relativeHref}${suffix}`, localPenRelPosix: normalizedTarget };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Already a relative path (e.g. "./style.css", "script.js")
|
|
207
|
+
const normalizedTarget = path.posix.normalize(
|
|
208
|
+
htmlRelDirPosix ? path.posix.join(htmlRelDirPosix, rawPath) : rawPath,
|
|
209
|
+
);
|
|
210
|
+
const localPenRelPosix =
|
|
211
|
+
normalizedTarget &&
|
|
212
|
+
normalizedTarget !== '.' &&
|
|
213
|
+
normalizedTarget !== '..' &&
|
|
214
|
+
!normalizedTarget.startsWith('../')
|
|
215
|
+
? normalizedTarget
|
|
216
|
+
: null;
|
|
217
|
+
|
|
218
|
+
return { href: trimmed, localPenRelPosix };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function looksLikeEsModule(source) {
|
|
222
|
+
for (const rawLine of source.split(/\r?\n/)) {
|
|
223
|
+
const line = rawLine.trimStart();
|
|
224
|
+
if (
|
|
225
|
+
line.startsWith('import ') ||
|
|
226
|
+
line.startsWith('import{') ||
|
|
227
|
+
line.startsWith('import*') ||
|
|
228
|
+
line.startsWith("import'") ||
|
|
229
|
+
line.startsWith('import"') ||
|
|
230
|
+
line.startsWith('export ') ||
|
|
231
|
+
line.startsWith('export{') ||
|
|
232
|
+
line.startsWith('export*')
|
|
233
|
+
) {
|
|
234
|
+
return true;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return false;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function localScriptUsesEsm(localPenRelPosix, penDir, rootRealpath) {
|
|
241
|
+
if (!localPenRelPosix) return false;
|
|
242
|
+
const segments = localPenRelPosix.split('/').filter(Boolean);
|
|
243
|
+
if (segments.length === 0) return false;
|
|
244
|
+
for (const seg of segments) {
|
|
245
|
+
if (seg === '.' || seg === '..' || seg.startsWith('.')) return false;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const candidatePath = path.resolve(penDir, ...segments);
|
|
249
|
+
if (!isWithinRoot(candidatePath, penDir)) return false;
|
|
250
|
+
|
|
251
|
+
const file = await resolveSafeFile(candidatePath, rootRealpath);
|
|
252
|
+
if (!file) return false;
|
|
253
|
+
|
|
254
|
+
try {
|
|
255
|
+
const snippet = await readPartialUtf8(file.realPath, MAX_SCRIPT_SNIFF_BYTES);
|
|
256
|
+
return looksLikeEsModule(snippet);
|
|
257
|
+
} catch {
|
|
258
|
+
return false;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function normalizeHtmlClasses(rawClasses) {
|
|
263
|
+
if (typeof rawClasses === 'string') {
|
|
264
|
+
return rawClasses.trim();
|
|
265
|
+
}
|
|
266
|
+
if (Array.isArray(rawClasses)) {
|
|
267
|
+
return rawClasses
|
|
268
|
+
.filter((item) => typeof item === 'string' && item.trim())
|
|
269
|
+
.map((item) => item.trim())
|
|
270
|
+
.join(' ');
|
|
271
|
+
}
|
|
272
|
+
return '';
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Compiles a `.pen.html` body fragment into a complete HTML document using
|
|
277
|
+
* `.codepen/classic.config.json` and `.cdpn.json` title metadata. If the Pen also
|
|
278
|
+
* enables the `packages` block, the importmap transform is applied afterward.
|
|
279
|
+
*/
|
|
280
|
+
export async function compileClassicPenHtml({ penHtmlPath, penContext, rootRealpath }) {
|
|
281
|
+
const penHtmlFile = await resolveSafeFile(penHtmlPath, rootRealpath);
|
|
282
|
+
if (!penHtmlFile || penHtmlFile.size > MAX_HTML_BYTES) return null;
|
|
283
|
+
|
|
284
|
+
let bodyHtml;
|
|
285
|
+
try {
|
|
286
|
+
bodyHtml = await fs.readFile(penHtmlFile.realPath, 'utf8');
|
|
287
|
+
} catch {
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const classicConfig =
|
|
292
|
+
(await readSafeJsonObject(
|
|
293
|
+
path.join(penContext.penDir, CODEPEN_DIR, CLASSIC_CONFIG_FILENAME),
|
|
294
|
+
rootRealpath,
|
|
295
|
+
)) ?? {};
|
|
296
|
+
const cdpnConfig =
|
|
297
|
+
(await readSafeJsonObject(
|
|
298
|
+
path.join(penContext.penDir, CDPN_JSON_FILENAME),
|
|
299
|
+
rootRealpath,
|
|
300
|
+
)) ?? {};
|
|
301
|
+
|
|
302
|
+
const title =
|
|
303
|
+
typeof cdpnConfig?.info?.title === 'string' && cdpnConfig.info.title.trim()
|
|
304
|
+
? cdpnConfig.info.title.trim()
|
|
305
|
+
: path.basename(penContext.penDir) || 'Pen';
|
|
306
|
+
|
|
307
|
+
const htmlClasses = normalizeHtmlClasses(classicConfig.htmlClasses);
|
|
308
|
+
// TODO(security): `classicConfig.head` and `bodyHtml` are raw HTML authored by the
|
|
309
|
+
// demo developer in local `src/` (same trust boundary as `src/*/index.html`), so they
|
|
310
|
+
// are intentionally embedded unescaped while `title`, `htmlClasses`, and asset URLs
|
|
311
|
+
// are validated and HTML-escaped.
|
|
312
|
+
const headHtml = typeof classicConfig.head === 'string' ? classicConfig.head.trim() : '';
|
|
313
|
+
|
|
314
|
+
const relFromPen = path.relative(penContext.penDir, path.dirname(penHtmlFile.realPath));
|
|
315
|
+
const htmlRelDirPosix = relFromPen ? relFromPen.split(path.sep).join('/') : '';
|
|
316
|
+
|
|
317
|
+
const styleTags = [];
|
|
318
|
+
if (Array.isArray(classicConfig.styles)) {
|
|
319
|
+
for (const entry of classicConfig.styles) {
|
|
320
|
+
const rawHref =
|
|
321
|
+
typeof entry === 'string'
|
|
322
|
+
? entry
|
|
323
|
+
: isPlainObject(entry)
|
|
324
|
+
? (entry.href ?? entry.url ?? entry.src)
|
|
325
|
+
: null;
|
|
326
|
+
const resolved = resolveClassicAssetUrl(rawHref, htmlRelDirPosix);
|
|
327
|
+
if (!resolved) continue;
|
|
328
|
+
styleTags.push(`<link rel="stylesheet" href="${escapeHtml(resolved.href)}">`);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const scriptTags = [];
|
|
333
|
+
if (Array.isArray(classicConfig.scripts)) {
|
|
334
|
+
for (const entry of classicConfig.scripts) {
|
|
335
|
+
const rawSrc =
|
|
336
|
+
typeof entry === 'string'
|
|
337
|
+
? entry
|
|
338
|
+
: isPlainObject(entry)
|
|
339
|
+
? (entry.src ?? entry.url)
|
|
340
|
+
: null;
|
|
341
|
+
const explicitType =
|
|
342
|
+
isPlainObject(entry) && typeof entry.type === 'string'
|
|
343
|
+
? entry.type.trim().toLowerCase()
|
|
344
|
+
: null;
|
|
345
|
+
|
|
346
|
+
const resolved = resolveClassicAssetUrl(rawSrc, htmlRelDirPosix);
|
|
347
|
+
if (!resolved) continue;
|
|
348
|
+
|
|
349
|
+
let scriptType =
|
|
350
|
+
explicitType && ALLOWED_SCRIPT_TYPES.has(explicitType) ? explicitType : null;
|
|
351
|
+
const pathWithoutQuery = resolved.href.split(/[?#]/, 1)[0].toLowerCase();
|
|
352
|
+
if (!scriptType && pathWithoutQuery.endsWith('.mjs')) {
|
|
353
|
+
scriptType = 'module';
|
|
354
|
+
}
|
|
355
|
+
if (!scriptType && penContext.hasPackages && resolved.localPenRelPosix) {
|
|
356
|
+
if (await localScriptUsesEsm(resolved.localPenRelPosix, penContext.penDir, rootRealpath)) {
|
|
357
|
+
scriptType = 'module';
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const typeAttr = scriptType ? ` type="${escapeHtml(scriptType)}"` : '';
|
|
362
|
+
scriptTags.push(`<script${typeAttr} src="${escapeHtml(resolved.href)}"></script>`);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
const htmlOpenTag = htmlClasses
|
|
367
|
+
? `<html lang="en" class="${escapeHtml(htmlClasses)}">`
|
|
368
|
+
: '<html lang="en">';
|
|
369
|
+
|
|
370
|
+
const headLines = [
|
|
371
|
+
' <meta charset="UTF-8">',
|
|
372
|
+
` <title>${escapeHtml(title)}</title>`,
|
|
373
|
+
];
|
|
374
|
+
if (headHtml) {
|
|
375
|
+
headLines.push(` ${headHtml}`);
|
|
376
|
+
}
|
|
377
|
+
for (const tag of styleTags) {
|
|
378
|
+
headLines.push(` ${tag}`);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const trimmedBody = bodyHtml.replace(/\r?\n$/, '');
|
|
382
|
+
const bodyLines = [];
|
|
383
|
+
if (trimmedBody) {
|
|
384
|
+
bodyLines.push(` ${trimmedBody}`);
|
|
385
|
+
}
|
|
386
|
+
for (const tag of scriptTags) {
|
|
387
|
+
bodyLines.push(` ${tag}`);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
let html = [
|
|
391
|
+
'<!DOCTYPE html>',
|
|
392
|
+
htmlOpenTag,
|
|
393
|
+
'',
|
|
394
|
+
' <head>',
|
|
395
|
+
...headLines,
|
|
396
|
+
' </head>',
|
|
397
|
+
'',
|
|
398
|
+
' <body>',
|
|
399
|
+
...bodyLines,
|
|
400
|
+
' </body>',
|
|
401
|
+
'',
|
|
402
|
+
'</html>',
|
|
403
|
+
'',
|
|
404
|
+
].join('\n');
|
|
405
|
+
|
|
406
|
+
if (penContext.hasPackages) {
|
|
407
|
+
html = await applyPackagesBlock({ html, penContext, rootRealpath });
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
return html;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
function buildEsmShImports(dependencies) {
|
|
414
|
+
const imports = {};
|
|
415
|
+
if (!isPlainObject(dependencies)) return imports;
|
|
416
|
+
|
|
417
|
+
for (const [rawName, rawVersion] of Object.entries(dependencies)) {
|
|
418
|
+
if (typeof rawName !== 'string' || typeof rawVersion !== 'string') continue;
|
|
419
|
+
const name = rawName.trim();
|
|
420
|
+
const version = rawVersion.trim();
|
|
421
|
+
if (!name || !version) continue;
|
|
422
|
+
if (!NPM_PACKAGE_NAME_PATTERN.test(name) || name.includes('..')) continue;
|
|
423
|
+
if (!SAFE_VERSION_PATTERN.test(version) || version.includes('..')) continue;
|
|
424
|
+
|
|
425
|
+
const encodedVersion = version.replace(/ /g, '%20');
|
|
426
|
+
const baseUrlStr = `${ESM_SH_ORIGIN}/${name}@${encodedVersion}`;
|
|
427
|
+
let parsedUrl;
|
|
428
|
+
try {
|
|
429
|
+
parsedUrl = new URL(baseUrlStr);
|
|
430
|
+
} catch {
|
|
431
|
+
continue;
|
|
432
|
+
}
|
|
433
|
+
if (
|
|
434
|
+
parsedUrl.origin !== ESM_SH_ORIGIN ||
|
|
435
|
+
parsedUrl.search ||
|
|
436
|
+
parsedUrl.hash ||
|
|
437
|
+
parsedUrl.pathname.includes('..')
|
|
438
|
+
) {
|
|
439
|
+
continue;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
imports[name] = baseUrlStr;
|
|
443
|
+
imports[`${name}/`] = `${baseUrlStr}/`;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
return imports;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function serializeImportMap(mapObj) {
|
|
450
|
+
// Escape `<` as `\u003c` so serialized JSON can never break out of `<script>`.
|
|
451
|
+
return JSON.stringify(mapObj, null, 2).replace(/</g, '\\u003c');
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function findTagEnd(html, startIndex) {
|
|
455
|
+
let quote = null;
|
|
456
|
+
for (let i = startIndex; i < html.length; i++) {
|
|
457
|
+
const ch = html[i];
|
|
458
|
+
if (quote) {
|
|
459
|
+
if (ch === quote) quote = null;
|
|
460
|
+
} else if (ch === '"' || ch === "'") {
|
|
461
|
+
quote = ch;
|
|
462
|
+
} else if (ch === '>') {
|
|
463
|
+
return i;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
return -1;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function isTagNameBoundary(ch) {
|
|
470
|
+
return ch === undefined || ch === '>' || ch === '/' || /\s/.test(ch);
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function getTagAttribute(attrText, targetName) {
|
|
474
|
+
const attrPattern =
|
|
475
|
+
/([a-zA-Z_:][\w:.-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
|
|
476
|
+
const lowerTarget = targetName.toLowerCase();
|
|
477
|
+
|
|
478
|
+
for (const match of attrText.matchAll(attrPattern)) {
|
|
479
|
+
if (match[1].toLowerCase() === lowerTarget) {
|
|
480
|
+
return match[2] ?? match[3] ?? match[4] ?? '';
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
return null;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
function findExistingImportMapScript(html) {
|
|
487
|
+
const lower = html.toLowerCase();
|
|
488
|
+
let i = 0;
|
|
489
|
+
|
|
490
|
+
while (i < html.length) {
|
|
491
|
+
const lt = html.indexOf('<', i);
|
|
492
|
+
if (lt === -1) break;
|
|
493
|
+
|
|
494
|
+
if (html.startsWith('<!--', lt)) {
|
|
495
|
+
const endComment = html.indexOf('-->', lt + 4);
|
|
496
|
+
if (endComment === -1) break;
|
|
497
|
+
i = endComment + 3;
|
|
498
|
+
continue;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
if (lower.startsWith('<script', lt) && isTagNameBoundary(html[lt + 7])) {
|
|
502
|
+
const openEnd = findTagEnd(html, lt + 7);
|
|
503
|
+
if (openEnd === -1) break;
|
|
504
|
+
|
|
505
|
+
const closeStart = lower.indexOf('</script', openEnd + 1);
|
|
506
|
+
if (closeStart === -1) break;
|
|
507
|
+
const closeEnd = findTagEnd(html, closeStart + 8);
|
|
508
|
+
if (closeEnd === -1) break;
|
|
509
|
+
|
|
510
|
+
const attrText = html.slice(lt + 7, openEnd);
|
|
511
|
+
const scriptType = getTagAttribute(attrText, 'type');
|
|
512
|
+
if (scriptType !== null && scriptType.trim().toLowerCase() === 'importmap') {
|
|
513
|
+
return {
|
|
514
|
+
contentStart: openEnd + 1,
|
|
515
|
+
contentEnd: closeStart,
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
i = closeEnd + 1;
|
|
520
|
+
continue;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
i = lt + 1;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
return null;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function findImportMapInsertionPoint(html) {
|
|
530
|
+
const lower = html.toLowerCase();
|
|
531
|
+
let i = 0;
|
|
532
|
+
let firstScriptStart = -1;
|
|
533
|
+
let afterHtmlOrDoctype = -1;
|
|
534
|
+
|
|
535
|
+
while (i < html.length) {
|
|
536
|
+
const lt = html.indexOf('<', i);
|
|
537
|
+
if (lt === -1) break;
|
|
538
|
+
|
|
539
|
+
if (html.startsWith('<!--', lt)) {
|
|
540
|
+
const endComment = html.indexOf('-->', lt + 4);
|
|
541
|
+
if (endComment === -1) break;
|
|
542
|
+
i = endComment + 3;
|
|
543
|
+
continue;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
if (lower.startsWith('<head', lt) && isTagNameBoundary(html[lt + 5])) {
|
|
547
|
+
const openEnd = findTagEnd(html, lt + 5);
|
|
548
|
+
if (openEnd !== -1) {
|
|
549
|
+
return { index: openEnd + 1, leadingNewline: true };
|
|
550
|
+
}
|
|
551
|
+
break;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
if (
|
|
555
|
+
firstScriptStart === -1 &&
|
|
556
|
+
lower.startsWith('<script', lt) &&
|
|
557
|
+
isTagNameBoundary(html[lt + 7])
|
|
558
|
+
) {
|
|
559
|
+
firstScriptStart = lt;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
if (lower.startsWith('<!doctype', lt) && isTagNameBoundary(html[lt + 9])) {
|
|
563
|
+
const openEnd = findTagEnd(html, lt + 9);
|
|
564
|
+
if (openEnd !== -1) {
|
|
565
|
+
afterHtmlOrDoctype = openEnd + 1;
|
|
566
|
+
i = openEnd + 1;
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
if (lower.startsWith('<html', lt) && isTagNameBoundary(html[lt + 5])) {
|
|
572
|
+
const openEnd = findTagEnd(html, lt + 5);
|
|
573
|
+
if (openEnd !== -1) {
|
|
574
|
+
afterHtmlOrDoctype = openEnd + 1;
|
|
575
|
+
i = openEnd + 1;
|
|
576
|
+
continue;
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
i = lt + 1;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
if (firstScriptStart !== -1) {
|
|
584
|
+
return { index: firstScriptStart, leadingNewline: false };
|
|
585
|
+
}
|
|
586
|
+
if (afterHtmlOrDoctype !== -1) {
|
|
587
|
+
return { index: afterHtmlOrDoctype, leadingNewline: true };
|
|
588
|
+
}
|
|
589
|
+
return { index: 0, leadingNewline: false };
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* Applies the CodePen `packages` block to an HTML document by reading `package.json`
|
|
594
|
+
* dependencies from the Pen root and injecting (or merging into an existing)
|
|
595
|
+
* `<script type="importmap">` targeting `https://esm.sh/`.
|
|
596
|
+
*/
|
|
597
|
+
export async function applyPackagesBlock({ html, penContext, rootRealpath }) {
|
|
598
|
+
if (!penContext?.hasPackages) return html;
|
|
599
|
+
|
|
600
|
+
const pkgJsonPath = path.join(penContext.penDir, PACKAGE_JSON_FILENAME);
|
|
601
|
+
const pkgJson = await readSafeJsonObject(pkgJsonPath, rootRealpath);
|
|
602
|
+
if (!pkgJson || !isPlainObject(pkgJson.dependencies)) return html;
|
|
603
|
+
|
|
604
|
+
const generatedImports = buildEsmShImports(pkgJson.dependencies);
|
|
605
|
+
if (Object.keys(generatedImports).length === 0) return html;
|
|
606
|
+
|
|
607
|
+
const existingScript = findExistingImportMapScript(html);
|
|
608
|
+
if (existingScript) {
|
|
609
|
+
const rawExisting = html.slice(existingScript.contentStart, existingScript.contentEnd).trim();
|
|
610
|
+
try {
|
|
611
|
+
const parsedExisting = rawExisting ? JSON.parse(rawExisting) : {};
|
|
612
|
+
if (!isPlainObject(parsedExisting)) return html;
|
|
613
|
+
|
|
614
|
+
const userImports = isPlainObject(parsedExisting.imports) ? parsedExisting.imports : {};
|
|
615
|
+
const merged = {
|
|
616
|
+
...parsedExisting,
|
|
617
|
+
imports: {
|
|
618
|
+
...generatedImports,
|
|
619
|
+
...userImports,
|
|
620
|
+
},
|
|
621
|
+
};
|
|
622
|
+
|
|
623
|
+
return (
|
|
624
|
+
html.slice(0, existingScript.contentStart) +
|
|
625
|
+
`\n${serializeImportMap(merged)}\n` +
|
|
626
|
+
html.slice(existingScript.contentEnd)
|
|
627
|
+
);
|
|
628
|
+
} catch {
|
|
629
|
+
return html;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
const { index, leadingNewline } = findImportMapInsertionPoint(html);
|
|
634
|
+
const prefix = leadingNewline ? '\n' : '';
|
|
635
|
+
const importMapTag = `${prefix}<script type="importmap">\n${serializeImportMap({ imports: generatedImports })}\n</script>\n`;
|
|
636
|
+
|
|
637
|
+
return html.slice(0, index) + importMapTag + html.slice(index);
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* When a requested `.html` file does not exist on disk, checks if the enclosing Pen
|
|
642
|
+
* enables the `classic` block and has a matching `.pen.html` source file. Returns the
|
|
643
|
+
* compiled HTML string or `null`.
|
|
644
|
+
*/
|
|
645
|
+
export async function resolveVirtualClassicHtml({
|
|
646
|
+
dirRealpath,
|
|
647
|
+
requestedFilename,
|
|
648
|
+
rootRealpath,
|
|
649
|
+
}) {
|
|
650
|
+
if (
|
|
651
|
+
typeof requestedFilename !== 'string' ||
|
|
652
|
+
!requestedFilename ||
|
|
653
|
+
requestedFilename.includes('\0') ||
|
|
654
|
+
requestedFilename.includes('\\') ||
|
|
655
|
+
requestedFilename.includes('/') ||
|
|
656
|
+
requestedFilename !== path.basename(requestedFilename) ||
|
|
657
|
+
requestedFilename.startsWith('.')
|
|
658
|
+
) {
|
|
659
|
+
return null;
|
|
660
|
+
}
|
|
661
|
+
const lowerName = requestedFilename.toLowerCase();
|
|
662
|
+
if (!lowerName.endsWith('.html') || lowerName.endsWith(PEN_HTML_SUFFIX)) {
|
|
663
|
+
return null;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
const penContext = await findPenContext(dirRealpath, rootRealpath);
|
|
667
|
+
if (!penContext?.hasClassic) return null;
|
|
668
|
+
|
|
669
|
+
const penHtmlFilename = `${requestedFilename.slice(0, -'.html'.length)}${PEN_HTML_SUFFIX}`;
|
|
670
|
+
const penHtmlCandidate = path.join(dirRealpath, penHtmlFilename);
|
|
671
|
+
|
|
672
|
+
return compileClassicPenHtml({
|
|
673
|
+
penHtmlPath: penHtmlCandidate,
|
|
674
|
+
penContext,
|
|
675
|
+
rootRealpath,
|
|
676
|
+
});
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
/**
|
|
680
|
+
* Applies active HTML blocks (currently `packages`) to an existing `.html` file on disk.
|
|
681
|
+
* Returns `{ transformed: true, html }` when a transform ran, or `{ transformed: false }`.
|
|
682
|
+
*/
|
|
683
|
+
export async function resolveServedHtmlWithBlocks({ filePath, rootRealpath }) {
|
|
684
|
+
const lowerPath = filePath.toLowerCase();
|
|
685
|
+
if (!lowerPath.endsWith('.html') || lowerPath.endsWith(PEN_HTML_SUFFIX)) {
|
|
686
|
+
return { transformed: false };
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
const penContext = await findPenContext(path.dirname(filePath), rootRealpath);
|
|
690
|
+
if (!penContext?.hasPackages) {
|
|
691
|
+
return { transformed: false };
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
const safeFile = await resolveSafeFile(filePath, rootRealpath);
|
|
695
|
+
if (!safeFile || safeFile.size > MAX_HTML_BYTES) {
|
|
696
|
+
return { transformed: false };
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
const rawHtml = await fs.readFile(safeFile.realPath, 'utf8');
|
|
700
|
+
const html = await applyPackagesBlock({ html: rawHtml, penContext, rootRealpath });
|
|
701
|
+
if (html === rawHtml) {
|
|
702
|
+
return { transformed: false };
|
|
703
|
+
}
|
|
704
|
+
return { transformed: true, html };
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
function sanitizeCodePenUrl(rawUrl) {
|
|
708
|
+
if (typeof rawUrl !== 'string') return null;
|
|
709
|
+
try {
|
|
710
|
+
const parsed = new URL(rawUrl.trim());
|
|
711
|
+
if (parsed.protocol !== 'https:') return null;
|
|
712
|
+
if (parsed.hostname !== 'codepen.io' && !parsed.hostname.endsWith('.codepen.io')) {
|
|
713
|
+
return null;
|
|
714
|
+
}
|
|
715
|
+
return parsed.href;
|
|
716
|
+
} catch {
|
|
717
|
+
return null;
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
const UNSUPPORTED_BLOCK_PAGE_STYLE = `
|
|
722
|
+
@layer reset, base, components;
|
|
723
|
+
|
|
724
|
+
:root {
|
|
725
|
+
color-scheme: light dark;
|
|
726
|
+
|
|
727
|
+
--surface-page: light-dark(oklch(98.5% 0.004 250), oklch(15% 0.012 260));
|
|
728
|
+
--surface-card: light-dark(oklch(100% 0 0), oklch(20% 0.014 260));
|
|
729
|
+
--surface-code: light-dark(oklch(94.5% 0.008 255), oklch(25% 0.016 260));
|
|
730
|
+
|
|
731
|
+
--text-primary: light-dark(oklch(20% 0.015 260), oklch(94% 0.008 250));
|
|
732
|
+
--text-muted: light-dark(oklch(46% 0.016 260), oklch(72% 0.014 255));
|
|
733
|
+
--text-subtle: light-dark(oklch(56% 0.014 260), oklch(62% 0.014 255));
|
|
734
|
+
|
|
735
|
+
--border-subtle: light-dark(oklch(88% 0.01 255), oklch(30% 0.018 260));
|
|
736
|
+
|
|
737
|
+
--accent: light-dark(oklch(48% 0.2 260), oklch(75% 0.15 250));
|
|
738
|
+
--accent-fg: light-dark(oklch(99% 0 0), oklch(15% 0.015 260));
|
|
739
|
+
|
|
740
|
+
--radius-card: 0.875rem;
|
|
741
|
+
--radius-code: 0.375rem;
|
|
742
|
+
accent-color: var(--accent);
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
@layer reset {
|
|
746
|
+
html,
|
|
747
|
+
body,
|
|
748
|
+
main,
|
|
749
|
+
article,
|
|
750
|
+
header,
|
|
751
|
+
footer,
|
|
752
|
+
div,
|
|
753
|
+
ul,
|
|
754
|
+
li {
|
|
755
|
+
box-sizing: border-box;
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
body,
|
|
759
|
+
h1,
|
|
760
|
+
p,
|
|
761
|
+
ul {
|
|
762
|
+
margin: 0;
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
@layer base {
|
|
767
|
+
body {
|
|
768
|
+
min-block-size: 100dvb;
|
|
769
|
+
display: grid;
|
|
770
|
+
place-items: center;
|
|
771
|
+
padding: clamp(1.5rem, 5vw, 3rem) clamp(1.25rem, 4vw, 2rem);
|
|
772
|
+
background-color: var(--surface-page);
|
|
773
|
+
color: var(--text-primary);
|
|
774
|
+
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
|
775
|
+
line-height: 1.55;
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
h1 {
|
|
779
|
+
font-size: clamp(1.4rem, 3vw, 1.75rem);
|
|
780
|
+
line-height: 1.25;
|
|
781
|
+
letter-spacing: -0.02em;
|
|
782
|
+
text-wrap: balance;
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
p {
|
|
786
|
+
text-wrap: pretty;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
a:focus-visible {
|
|
790
|
+
outline: 2px solid var(--accent);
|
|
791
|
+
outline-offset: 3px;
|
|
792
|
+
border-radius: 0.25rem;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
code {
|
|
796
|
+
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
|
797
|
+
font-size: 0.875em;
|
|
798
|
+
padding-block: 0.125em;
|
|
799
|
+
padding-inline: 0.4em;
|
|
800
|
+
border-radius: var(--radius-code);
|
|
801
|
+
background-color: var(--surface-code);
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
@layer components {
|
|
806
|
+
.error-card {
|
|
807
|
+
inline-size: min(100%, 38rem);
|
|
808
|
+
display: grid;
|
|
809
|
+
gap: 1.15rem;
|
|
810
|
+
padding: clamp(1.5rem, 4vw, 2.25rem);
|
|
811
|
+
background-color: var(--surface-card);
|
|
812
|
+
border: 1px solid var(--border-subtle);
|
|
813
|
+
border-radius: var(--radius-card);
|
|
814
|
+
corner-shape: squircle;
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
.error-header {
|
|
818
|
+
display: grid;
|
|
819
|
+
gap: 0.45rem;
|
|
820
|
+
justify-items: start;
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
.demo-path {
|
|
824
|
+
padding: 0;
|
|
825
|
+
background: none;
|
|
826
|
+
color: var(--text-subtle);
|
|
827
|
+
font-size: 0.8rem;
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
.error-body {
|
|
831
|
+
display: grid;
|
|
832
|
+
gap: 1.25rem;
|
|
833
|
+
color: var(--text-muted);
|
|
834
|
+
font-size: 0.95rem;
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
.block-list {
|
|
838
|
+
display: flex;
|
|
839
|
+
flex-wrap: wrap;
|
|
840
|
+
gap: 0.45rem;
|
|
841
|
+
list-style: none;
|
|
842
|
+
padding: 0;
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
.block-list code {
|
|
846
|
+
color: var(--text-primary);
|
|
847
|
+
font-weight: 500;
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
.error-illustration {
|
|
851
|
+
display: block;
|
|
852
|
+
inline-size: 7rem;
|
|
853
|
+
block-size: 7rem;
|
|
854
|
+
margin-block: 0.5rem;
|
|
855
|
+
margin-inline: auto;
|
|
856
|
+
color: light-dark(#000, var(--text-primary));
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
.error-actions {
|
|
860
|
+
display: flex;
|
|
861
|
+
flex-wrap: wrap;
|
|
862
|
+
align-items: center;
|
|
863
|
+
justify-content: space-between;
|
|
864
|
+
gap: 0.65rem;
|
|
865
|
+
padding-block-start: 1rem;
|
|
866
|
+
border-block-start: 1px solid color-mix(in oklch, var(--border-subtle) 70%, transparent);
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
.btn {
|
|
870
|
+
display: inline-flex;
|
|
871
|
+
align-items: center;
|
|
872
|
+
justify-content: center;
|
|
873
|
+
gap: 0.45em;
|
|
874
|
+
padding-block: 0.55em;
|
|
875
|
+
padding-inline: 0.95em;
|
|
876
|
+
border-radius: var(--radius-code);
|
|
877
|
+
border: 1px solid transparent;
|
|
878
|
+
font-size: 0.875rem;
|
|
879
|
+
font-weight: 500;
|
|
880
|
+
line-height: 1.3;
|
|
881
|
+
text-decoration: none;
|
|
882
|
+
white-space: nowrap;
|
|
883
|
+
transition: background-color 150ms ease, border-color 150ms ease, color 150ms ease;
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
.btn-primary {
|
|
887
|
+
background-color: var(--accent);
|
|
888
|
+
color: var(--accent-fg);
|
|
889
|
+
|
|
890
|
+
&:hover {
|
|
891
|
+
background-color: color-mix(in oklch, var(--accent) 88%, var(--text-primary));
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
.btn-secondary {
|
|
896
|
+
border-color: var(--border-subtle);
|
|
897
|
+
background-color: var(--surface-page);
|
|
898
|
+
color: var(--text-primary);
|
|
899
|
+
|
|
900
|
+
&:hover {
|
|
901
|
+
border-color: color-mix(in oklch, var(--accent) 60%, var(--border-subtle));
|
|
902
|
+
color: var(--accent);
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
.btn-codepen {
|
|
907
|
+
margin-inline-start: auto;
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
.btn-icon {
|
|
911
|
+
flex-shrink: 0;
|
|
912
|
+
inline-size: 0.95rem;
|
|
913
|
+
block-size: 0.95rem;
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
@media (prefers-reduced-motion: reduce) {
|
|
917
|
+
.btn {
|
|
918
|
+
transition: none;
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
`;
|
|
923
|
+
|
|
924
|
+
const UNSUPPORTED_BLOCK_PAGE_STYLE_HASH = createHash('sha256')
|
|
925
|
+
.update(UNSUPPORTED_BLOCK_PAGE_STYLE, 'utf8')
|
|
926
|
+
.digest('base64');
|
|
927
|
+
|
|
928
|
+
export const UNSUPPORTED_BLOCK_PAGE_CSP =
|
|
929
|
+
`default-src 'none'; style-src 'sha256-${UNSUPPORTED_BLOCK_PAGE_STYLE_HASH}'; img-src 'none'; script-src 'none'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'`;
|
|
930
|
+
|
|
931
|
+
const UNSUPPORTED_BLOCK_EMOJI_SVG = `<svg class="error-illustration" viewBox="0 0 120 120" fill="none" stroke="currentColor" stroke-width="6.5" stroke-linecap="butt" stroke-linejoin="miter" aria-hidden="true">
|
|
932
|
+
<circle cx="60" cy="60" r="52" />
|
|
933
|
+
<line x1="33.5" y1="37.5" x2="50.5" y2="54.5" />
|
|
934
|
+
<line x1="50.5" y1="37.5" x2="33.5" y2="54.5" />
|
|
935
|
+
<line x1="69.5" y1="37.5" x2="86.5" y2="54.5" />
|
|
936
|
+
<line x1="86.5" y1="37.5" x2="69.5" y2="54.5" />
|
|
937
|
+
<line x1="32" y1="72" x2="88" y2="72" />
|
|
938
|
+
<path d="M 58 72 V 83 A 11 11 0 0 0 80 83 V 72" />
|
|
939
|
+
<line x1="69" y1="72" x2="69" y2="84" />
|
|
940
|
+
</svg>`;
|
|
941
|
+
|
|
942
|
+
/**
|
|
943
|
+
* Renders a self-contained HTML error page explaining which CodePen block(s) in
|
|
944
|
+
* `.codepen/pen.config.json` are not supported, with links back to the homepage
|
|
945
|
+
* and/or to open the demo on CodePen.
|
|
946
|
+
*/
|
|
947
|
+
export async function renderUnsupportedBlocksPage({
|
|
948
|
+
penContext,
|
|
949
|
+
rootRealpath,
|
|
950
|
+
demoRelPath = null,
|
|
951
|
+
homeHref = null,
|
|
952
|
+
}) {
|
|
953
|
+
const cdpnConfig =
|
|
954
|
+
(await readSafeJsonObject(
|
|
955
|
+
path.join(penContext.penDir, CDPN_JSON_FILENAME),
|
|
956
|
+
rootRealpath,
|
|
957
|
+
)) ?? {};
|
|
958
|
+
|
|
959
|
+
const codepenUrl = sanitizeCodePenUrl(cdpnConfig?.url);
|
|
960
|
+
|
|
961
|
+
const blocks = penContext.unsupportedBlocks;
|
|
962
|
+
const isPlural = blocks.length > 1;
|
|
963
|
+
const headingText = isPlural ? 'Unsupported CodePen Blocks' : 'Unsupported CodePen Block';
|
|
964
|
+
const displayPath = demoRelPath ?? `${path.basename(penContext.penDir)}/`;
|
|
965
|
+
|
|
966
|
+
const blockItemsHtml = blocks
|
|
967
|
+
.map((name) => `<li><code>${escapeHtml(name)}</code></li>`)
|
|
968
|
+
.join('');
|
|
969
|
+
|
|
970
|
+
const explanationHtml = isPlural
|
|
971
|
+
? `<p>This demo uses blocks configured in <code>.codepen/pen.config.json</code> that are not supported by <code>codepen-demokit</code>:</p>
|
|
972
|
+
<ul class="block-list" aria-label="Unsupported blocks">${blockItemsHtml}</ul>`
|
|
973
|
+
: `<p>This demo uses the <code>${escapeHtml(blocks[0])}</code> block in <code>.codepen/pen.config.json</code>, which is not supported by <code>codepen-demokit</code>.</p>`;
|
|
974
|
+
|
|
975
|
+
const actions = [];
|
|
976
|
+
if (homeHref) {
|
|
977
|
+
const homeBtnClass = codepenUrl ? 'btn btn-secondary' : 'btn btn-primary';
|
|
978
|
+
actions.push(
|
|
979
|
+
`<a class="${homeBtnClass}" href="${escapeHtml(homeHref)}">
|
|
980
|
+
<svg class="btn-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
981
|
+
<path d="M10.5 3.5 6 8l4.5 4.5" />
|
|
982
|
+
</svg>
|
|
983
|
+
<span>Back to Homepage</span>
|
|
984
|
+
</a>`,
|
|
985
|
+
);
|
|
986
|
+
}
|
|
987
|
+
if (codepenUrl) {
|
|
988
|
+
actions.push(
|
|
989
|
+
`<a class="btn btn-primary btn-codepen" href="${escapeHtml(codepenUrl)}" target="_blank" rel="noopener noreferrer">
|
|
990
|
+
<svg class="btn-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
991
|
+
<polygon points="8,1.5 14.5,5.5 8,9.5 1.5,5.5" />
|
|
992
|
+
<polygon points="8,6.5 14.5,10.5 8,14.5 1.5,10.5" />
|
|
993
|
+
<line x1="1.5" y1="5.5" x2="1.5" y2="10.5" />
|
|
994
|
+
<line x1="14.5" y1="5.5" x2="14.5" y2="10.5" />
|
|
995
|
+
<line x1="8" y1="1.5" x2="8" y2="6.5" />
|
|
996
|
+
<line x1="8" y1="9.5" x2="8" y2="14.5" />
|
|
997
|
+
</svg>
|
|
998
|
+
<span>Open on CodePen</span>
|
|
999
|
+
</a>`,
|
|
1000
|
+
);
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
const actionsHtml =
|
|
1004
|
+
actions.length > 0
|
|
1005
|
+
? `\n <footer class="error-actions">\n ${actions.join('\n ')}\n </footer>`
|
|
1006
|
+
: '';
|
|
1007
|
+
|
|
1008
|
+
const html = `<!DOCTYPE html>
|
|
1009
|
+
<html lang="en">
|
|
1010
|
+
<head>
|
|
1011
|
+
<meta charset="utf-8">
|
|
1012
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1013
|
+
<meta name="color-scheme" content="light dark">
|
|
1014
|
+
<title>${escapeHtml(headingText)}</title>
|
|
1015
|
+
<style>${UNSUPPORTED_BLOCK_PAGE_STYLE}</style>
|
|
1016
|
+
</head>
|
|
1017
|
+
<body>
|
|
1018
|
+
<main>
|
|
1019
|
+
<article class="error-card">
|
|
1020
|
+
<header class="error-header">
|
|
1021
|
+
<code class="demo-path">${escapeHtml(displayPath)}</code>
|
|
1022
|
+
<h1>${escapeHtml(headingText)}</h1>
|
|
1023
|
+
</header>
|
|
1024
|
+
<div class="error-body">
|
|
1025
|
+
${explanationHtml}
|
|
1026
|
+
${UNSUPPORTED_BLOCK_EMOJI_SVG}
|
|
1027
|
+
</div>${actionsHtml}
|
|
1028
|
+
</article>
|
|
1029
|
+
</main>
|
|
1030
|
+
</body>
|
|
1031
|
+
</html>
|
|
1032
|
+
`;
|
|
1033
|
+
|
|
1034
|
+
return { html, csp: UNSUPPORTED_BLOCK_PAGE_CSP };
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
/**
|
|
1038
|
+
* Checks whether `dirRealpath` belongs to a Pen with unsupported active blocks and,
|
|
1039
|
+
* if so, returns `{ html, csp }` for the error page.
|
|
1040
|
+
*/
|
|
1041
|
+
export async function resolveUnsupportedBlocksPage({
|
|
1042
|
+
dirRealpath,
|
|
1043
|
+
rootRealpath,
|
|
1044
|
+
isRootServe = true,
|
|
1045
|
+
}) {
|
|
1046
|
+
const penContext = await findPenContext(dirRealpath, rootRealpath);
|
|
1047
|
+
if (!penContext || penContext.unsupportedBlocks.length === 0) {
|
|
1048
|
+
return null;
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
const relDir = path.relative(rootRealpath, dirRealpath);
|
|
1052
|
+
const dirSegments = relDir ? relDir.split(path.sep).filter(Boolean) : [];
|
|
1053
|
+
const homeHref = isRootServe && dirSegments.length > 0 ? '../'.repeat(dirSegments.length) : null;
|
|
1054
|
+
|
|
1055
|
+
const relPen = path.relative(rootRealpath, penContext.penDir);
|
|
1056
|
+
const penSegments = relPen ? relPen.split(path.sep).filter(Boolean) : [];
|
|
1057
|
+
const demoRelPath =
|
|
1058
|
+
penSegments.length > 0 ? `${penSegments.join('/')}/` : `${path.basename(penContext.penDir)}/`;
|
|
1059
|
+
|
|
1060
|
+
return renderUnsupportedBlocksPage({
|
|
1061
|
+
penContext,
|
|
1062
|
+
rootRealpath,
|
|
1063
|
+
demoRelPath,
|
|
1064
|
+
homeHref,
|
|
1065
|
+
});
|
|
1066
|
+
}
|
|
1067
|
+
|