codepen-commander 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +104 -10
  2. package/api/client.js +129 -106
  3. package/cli.js +34 -29
  4. package/commands/auth/default.js +40 -0
  5. package/commands/auth/index.js +83 -0
  6. package/commands/auth/list.js +78 -0
  7. package/commands/auth/login.js +136 -0
  8. package/commands/auth/logout.js +186 -0
  9. package/commands/auth/status.js +212 -0
  10. package/commands/build.js +256 -0
  11. package/commands/clone.js +13 -581
  12. package/commands/delete.js +553 -37
  13. package/commands/deploy.js +164 -154
  14. package/commands/domains.js +83 -39
  15. package/commands/fork.js +13 -317
  16. package/commands/info.js +152 -0
  17. package/commands/init.js +375 -0
  18. package/commands/list.js +95 -78
  19. package/commands/new.js +155 -83
  20. package/commands/open.js +29 -19
  21. package/commands/privacy.js +52 -36
  22. package/commands/pull.js +123 -110
  23. package/commands/push.js +222 -365
  24. package/commands/restore.js +251 -0
  25. package/commands/rollback.js +141 -0
  26. package/commands/serve.js +119 -0
  27. package/commands/settings.js +126 -0
  28. package/commands/shell.js +305 -0
  29. package/commands/status.js +133 -39
  30. package/commands/sync.js +330 -0
  31. package/commands/undeploy.js +102 -0
  32. package/commands/unlink.js +191 -0
  33. package/commands/versions.js +100 -163
  34. package/config/auth.js +4 -374
  35. package/config/pen-blocks.js +166 -0
  36. package/config/project.js +179 -240
  37. package/config/user-store.js +364 -0
  38. package/constants.js +42 -0
  39. package/errors.js +17 -0
  40. package/package.json +1 -1
  41. package/shell/index.html +79 -0
  42. package/shell/scripts.js +276 -0
  43. package/shell/styles.css +492 -0
  44. package/site/blocks/classic.js +270 -0
  45. package/site/blocks/context.js +63 -0
  46. package/site/blocks/index.js +4 -0
  47. package/site/blocks/packages.js +242 -0
  48. package/site/blocks/unsupported-page.js +328 -0
  49. package/site/builder.js +475 -0
  50. package/site/detect.js +65 -0
  51. package/site/ignore-files.js +90 -0
  52. package/site/manifest.js +227 -0
  53. package/site/server.js +483 -0
  54. package/site/shell.js +363 -0
  55. package/sync/fs.js +19 -17
  56. package/sync/info.js +6 -81
  57. package/utils/browser.js +17 -10
  58. package/utils/cli-options.js +79 -0
  59. package/utils/codepen-url.js +183 -0
  60. package/utils/format.js +39 -30
  61. package/utils/fs-safe.js +95 -0
  62. package/utils/html.js +40 -1
  63. package/utils/json.js +4 -19
  64. package/utils/output.js +37 -0
  65. package/utils/package-paths.js +51 -0
  66. package/utils/prompts/index.js +5 -0
  67. package/utils/prompts/multi-select.js +185 -0
  68. package/utils/prompts/secret.js +65 -0
  69. package/utils/prompts/select.js +141 -0
  70. package/utils/prompts/text.js +99 -0
  71. package/utils/prompts/tty-list.js +165 -0
  72. package/utils/prompts/types.js +35 -0
  73. package/utils/strings.js +98 -0
  74. package/utils/watcher.js +82 -0
  75. package/{commands → workflows}/auth-context.js +13 -7
  76. package/workflows/batch-pens.js +1647 -0
  77. package/workflows/batch-target.js +184 -0
  78. package/workflows/classic-convert.js +241 -0
  79. package/workflows/clone-pen.js +381 -0
  80. package/workflows/create-pen.js +254 -0
  81. package/workflows/discover-pens.js +91 -0
  82. package/workflows/fork-pen.js +314 -0
  83. package/workflows/missing-pen.js +212 -0
  84. package/workflows/pull-pen.js +204 -0
  85. package/workflows/push-pen.js +318 -0
  86. package/{commands → workflows}/scaffold.js +4 -3
  87. package/workflows/sync-pen.js +227 -0
  88. package/{commands → workflows}/unowned-pen.js +16 -12
  89. package/commands/auth.js +0 -593
  90. package/commands/create-pen.js +0 -251
  91. package/commands/meta.js +0 -184
  92. package/utils/prompts.js +0 -316
  93. /package/{types.js → api/types.js} +0 -0
@@ -0,0 +1,270 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { CLASSIC_CONFIG_FILENAME, CODEPEN_DIR, PEN_HTML_SUFFIX, PROJECT_CONFIG_FILENAME, } from '../../constants.js';
4
+ import { isWithinRoot, readPartialUtf8, readSafeJsonObject, resolveSafeFile, } from '../../utils/fs-safe.js';
5
+ import { escapeHtml } from '../../utils/html.js';
6
+ import { hasControlChars, isPlainObject } from '../../utils/strings.js';
7
+ import { findPenContext } from './context.js';
8
+ import { applyPackagesBlock } from './packages.js';
9
+ const MAX_HTML_BYTES = 10 * 1024 * 1024;
10
+ const MAX_SCRIPT_SNIFF_BYTES = 64 * 1024;
11
+ const URL_SCHEME_PATTERN = /^[a-zA-Z][a-zA-Z0-9+.-]*:/;
12
+ const ALLOWED_SCRIPT_TYPES = new Set(['module', 'text/javascript']);
13
+ /**
14
+ * Reads the optional `head` HTML string from `<penDir>/.codepen/classic.config.json`.
15
+ */
16
+ export async function readClassicHeadMetadata(penDir, rootRealpath) {
17
+ const classicConfigPath = path.join(penDir, CODEPEN_DIR, CLASSIC_CONFIG_FILENAME);
18
+ const classicConfig = await readSafeJsonObject(classicConfigPath, rootRealpath);
19
+ if (!classicConfig || typeof classicConfig.head !== 'string')
20
+ return null;
21
+ const trimmed = classicConfig.head.trim();
22
+ return trimmed || null;
23
+ }
24
+ function resolveClassicAssetUrl(rawUrl, htmlRelDirPosix) {
25
+ if (typeof rawUrl !== 'string')
26
+ return null;
27
+ const trimmed = rawUrl.trim();
28
+ if (!trimmed || hasControlChars(trimmed))
29
+ return null;
30
+ // Allow external HTTP(S) and protocol-relative URLs untouched
31
+ if (trimmed.startsWith('https://') ||
32
+ trimmed.startsWith('http://') ||
33
+ trimmed.startsWith('//')) {
34
+ return { href: trimmed, localPenRelPosix: null };
35
+ }
36
+ // Reject any other explicit URL scheme (e.g. javascript:, data:, vbscript:, file:)
37
+ if (URL_SCHEME_PATTERN.test(trimmed)) {
38
+ return null;
39
+ }
40
+ const splitMatch = /^([^?#]*)(.*)$/.exec(trimmed);
41
+ const rawPath = splitMatch?.[1] ?? trimmed;
42
+ const suffix = splitMatch?.[2] ?? '';
43
+ // Pen-root-relative path (e.g. "/style.css", "/script.js"): rewrite relative to the HTML file
44
+ // so the demo works both at "/<group>/<demo>/" and when served directly as "/".
45
+ if (rawPath.startsWith('/')) {
46
+ const stripped = rawPath.replace(/^\/+/, '');
47
+ if (!stripped)
48
+ return null;
49
+ const normalizedTarget = path.posix.normalize(stripped);
50
+ if (!normalizedTarget ||
51
+ normalizedTarget === '.' ||
52
+ normalizedTarget === '..' ||
53
+ normalizedTarget.startsWith('../')) {
54
+ return null;
55
+ }
56
+ let relativeHref = path.posix.relative(htmlRelDirPosix, normalizedTarget);
57
+ if (!relativeHref)
58
+ return null;
59
+ if (!relativeHref.startsWith('./') && !relativeHref.startsWith('../')) {
60
+ relativeHref = `./${relativeHref}`;
61
+ }
62
+ return { href: `${relativeHref}${suffix}`, localPenRelPosix: normalizedTarget };
63
+ }
64
+ // Already a relative path (e.g. "./style.css", "script.js")
65
+ const normalizedTarget = path.posix.normalize(htmlRelDirPosix ? path.posix.join(htmlRelDirPosix, rawPath) : rawPath);
66
+ const localPenRelPosix = normalizedTarget &&
67
+ normalizedTarget !== '.' &&
68
+ normalizedTarget !== '..' &&
69
+ !normalizedTarget.startsWith('../')
70
+ ? normalizedTarget
71
+ : null;
72
+ return { href: trimmed, localPenRelPosix };
73
+ }
74
+ function looksLikeEsModule(source) {
75
+ for (const rawLine of source.split(/\r?\n/)) {
76
+ const line = rawLine.trimStart();
77
+ if (line.startsWith('import ') ||
78
+ line.startsWith('import{') ||
79
+ line.startsWith('import*') ||
80
+ line.startsWith("import'") ||
81
+ line.startsWith('import"') ||
82
+ line.startsWith('export ') ||
83
+ line.startsWith('export{') ||
84
+ line.startsWith('export*')) {
85
+ return true;
86
+ }
87
+ }
88
+ return false;
89
+ }
90
+ async function localScriptUsesEsm(localPenRelPosix, penDir, rootRealpath) {
91
+ if (!localPenRelPosix)
92
+ return false;
93
+ const segments = localPenRelPosix.split('/').filter(Boolean);
94
+ if (segments.length === 0)
95
+ return false;
96
+ for (const seg of segments) {
97
+ if (seg === '.' || seg === '..' || seg.startsWith('.'))
98
+ return false;
99
+ }
100
+ const candidatePath = path.resolve(penDir, ...segments);
101
+ if (!isWithinRoot(candidatePath, penDir))
102
+ return false;
103
+ const file = await resolveSafeFile(candidatePath, rootRealpath);
104
+ if (!file)
105
+ return false;
106
+ try {
107
+ const snippet = await readPartialUtf8(file.realPath, MAX_SCRIPT_SNIFF_BYTES);
108
+ return looksLikeEsModule(snippet);
109
+ }
110
+ catch {
111
+ return false;
112
+ }
113
+ }
114
+ function normalizeHtmlClasses(rawClasses) {
115
+ if (typeof rawClasses === 'string') {
116
+ return rawClasses.trim();
117
+ }
118
+ if (Array.isArray(rawClasses)) {
119
+ return rawClasses
120
+ .filter((item) => typeof item === 'string' && Boolean(item.trim()))
121
+ .map((item) => item.trim())
122
+ .join(' ');
123
+ }
124
+ return '';
125
+ }
126
+ /**
127
+ * Compiles a `.pen.html` body fragment into a complete HTML document using
128
+ * `.codepen/classic.config.json` and `.cdpn.json` title metadata. If the Pen also
129
+ * enables the `packages` block, the importmap transform is applied afterward.
130
+ */
131
+ export async function compileClassicPenHtml(options) {
132
+ const { penHtmlPath, penContext, rootRealpath } = options;
133
+ const penHtmlFile = await resolveSafeFile(penHtmlPath, rootRealpath);
134
+ if (!penHtmlFile || penHtmlFile.size > MAX_HTML_BYTES)
135
+ return null;
136
+ let bodyHtml;
137
+ try {
138
+ bodyHtml = await fs.readFile(penHtmlFile.realPath, 'utf8');
139
+ }
140
+ catch {
141
+ return null;
142
+ }
143
+ const classicConfig = (await readSafeJsonObject(path.join(penContext.penDir, CODEPEN_DIR, CLASSIC_CONFIG_FILENAME), rootRealpath)) ?? {};
144
+ const cdpnConfig = (await readSafeJsonObject(path.join(penContext.penDir, PROJECT_CONFIG_FILENAME), rootRealpath)) ?? {};
145
+ const infoObj = isPlainObject(cdpnConfig.info) ? cdpnConfig.info : null;
146
+ const title = typeof infoObj?.title === 'string' && infoObj.title.trim()
147
+ ? infoObj.title.trim()
148
+ : path.basename(penContext.penDir) || 'Pen';
149
+ const htmlClasses = normalizeHtmlClasses(classicConfig.htmlClasses);
150
+ // TODO(security): `classicConfig.head` and `bodyHtml` are raw HTML authored by the
151
+ // demo developer inside the local Pen folder (same trust boundary as `index.html`), so
152
+ // they are intentionally embedded unescaped while `title`, `htmlClasses`, and asset URLs
153
+ // are validated and HTML-escaped.
154
+ const headHtml = typeof classicConfig.head === 'string' ? classicConfig.head.trim() : '';
155
+ const relFromPen = path.relative(penContext.penDir, path.dirname(penHtmlFile.realPath));
156
+ const htmlRelDirPosix = relFromPen ? relFromPen.split(path.sep).join('/') : '';
157
+ const styleTags = [];
158
+ if (Array.isArray(classicConfig.styles)) {
159
+ for (const entry of classicConfig.styles) {
160
+ const rawHref = typeof entry === 'string'
161
+ ? entry
162
+ : isPlainObject(entry)
163
+ ? (entry.href ?? entry.url ?? entry.src)
164
+ : null;
165
+ const resolved = resolveClassicAssetUrl(rawHref, htmlRelDirPosix);
166
+ if (!resolved)
167
+ continue;
168
+ styleTags.push(`<link rel="stylesheet" href="${escapeHtml(resolved.href)}">`);
169
+ }
170
+ }
171
+ const scriptTags = [];
172
+ if (Array.isArray(classicConfig.scripts)) {
173
+ for (const entry of classicConfig.scripts) {
174
+ const rawSrc = typeof entry === 'string'
175
+ ? entry
176
+ : isPlainObject(entry)
177
+ ? (entry.src ?? entry.url)
178
+ : null;
179
+ const explicitType = isPlainObject(entry) && typeof entry.type === 'string'
180
+ ? entry.type.trim().toLowerCase()
181
+ : null;
182
+ const resolved = resolveClassicAssetUrl(rawSrc, htmlRelDirPosix);
183
+ if (!resolved)
184
+ continue;
185
+ let scriptType = explicitType && ALLOWED_SCRIPT_TYPES.has(explicitType) ? explicitType : null;
186
+ const pathWithoutQuery = (resolved.href.split(/[?#]/, 1)[0] ?? '').toLowerCase();
187
+ if (!scriptType && pathWithoutQuery.endsWith('.mjs')) {
188
+ scriptType = 'module';
189
+ }
190
+ if (!scriptType && penContext.hasPackages && resolved.localPenRelPosix) {
191
+ if (await localScriptUsesEsm(resolved.localPenRelPosix, penContext.penDir, rootRealpath)) {
192
+ scriptType = 'module';
193
+ }
194
+ }
195
+ const typeAttr = scriptType ? ` type="${escapeHtml(scriptType)}"` : '';
196
+ scriptTags.push(`<script${typeAttr} src="${escapeHtml(resolved.href)}"></script>`);
197
+ }
198
+ }
199
+ const htmlOpenTag = htmlClasses
200
+ ? `<html lang="en" class="${escapeHtml(htmlClasses)}">`
201
+ : '<html lang="en">';
202
+ const headLines = [
203
+ ' <meta charset="UTF-8">',
204
+ ` <title>${escapeHtml(title)}</title>`,
205
+ ];
206
+ if (headHtml) {
207
+ headLines.push(` ${headHtml}`);
208
+ }
209
+ for (const tag of styleTags) {
210
+ headLines.push(` ${tag}`);
211
+ }
212
+ const trimmedBody = bodyHtml.replace(/\r?\n$/, '');
213
+ const bodyLines = [];
214
+ if (trimmedBody) {
215
+ bodyLines.push(` ${trimmedBody}`);
216
+ }
217
+ for (const tag of scriptTags) {
218
+ bodyLines.push(` ${tag}`);
219
+ }
220
+ let html = [
221
+ '<!DOCTYPE html>',
222
+ htmlOpenTag,
223
+ '',
224
+ ' <head>',
225
+ ...headLines,
226
+ ' </head>',
227
+ '',
228
+ ' <body>',
229
+ ...bodyLines,
230
+ ' </body>',
231
+ '',
232
+ '</html>',
233
+ '',
234
+ ].join('\n');
235
+ if (penContext.hasPackages) {
236
+ html = await applyPackagesBlock({ html, penContext, rootRealpath });
237
+ }
238
+ return html;
239
+ }
240
+ /**
241
+ * When a requested `.html` file does not exist on disk, checks if the enclosing Pen
242
+ * enables the `classic` block and has a matching `.pen.html` source file. Returns the
243
+ * compiled HTML string or `null`.
244
+ */
245
+ export async function resolveVirtualClassicHtml(options) {
246
+ const { dirRealpath, requestedFilename, rootRealpath } = options;
247
+ if (typeof requestedFilename !== 'string' ||
248
+ !requestedFilename ||
249
+ requestedFilename.includes('\0') ||
250
+ requestedFilename.includes('\\') ||
251
+ requestedFilename.includes('/') ||
252
+ requestedFilename !== path.basename(requestedFilename) ||
253
+ requestedFilename.startsWith('.')) {
254
+ return null;
255
+ }
256
+ const lowerName = requestedFilename.toLowerCase();
257
+ if (!lowerName.endsWith('.html') || lowerName.endsWith(PEN_HTML_SUFFIX)) {
258
+ return null;
259
+ }
260
+ const penContext = await findPenContext(dirRealpath, rootRealpath);
261
+ if (!penContext?.hasClassic)
262
+ return null;
263
+ const penHtmlFilename = `${requestedFilename.slice(0, -'.html'.length)}${PEN_HTML_SUFFIX}`;
264
+ const penHtmlCandidate = path.join(dirRealpath, penHtmlFilename);
265
+ return compileClassicPenHtml({
266
+ penHtmlPath: penHtmlCandidate,
267
+ penContext,
268
+ rootRealpath,
269
+ });
270
+ }
@@ -0,0 +1,63 @@
1
+ import path from 'node:path';
2
+ import { normalizeBlockType } from '../../config/pen-blocks.js';
3
+ import { CODEPEN_DIR, PEN_CONFIG_FILENAME } from '../../constants.js';
4
+ import { isWithinRoot, readSafeJsonObject } from '../../utils/fs-safe.js';
5
+ import { compareNatural, isPlainObject } from '../../utils/strings.js';
6
+ const MAX_WALK_DEPTH = 16;
7
+ const SUPPORTED_BLOCK_TYPES = new Set(['validate', 'fingerprint', 'classic', 'packages']);
8
+ /**
9
+ * Inspects `<penDir>/.codepen/pen.config.json` and detects enabled supported blocks
10
+ * (`classic`, `packages`; `validate` and `fingerprint` are default no-ops) as well as
11
+ * any active unsupported blocks.
12
+ */
13
+ export async function readPenBlocks(penDir, rootRealpath) {
14
+ const configPath = path.join(penDir, CODEPEN_DIR, PEN_CONFIG_FILENAME);
15
+ const parsed = await readSafeJsonObject(configPath, rootRealpath);
16
+ if (!parsed || !isPlainObject(parsed.blocks))
17
+ return null;
18
+ const activeBlocks = new Set();
19
+ const unsupportedMap = new Map();
20
+ for (const [key, block] of Object.entries(parsed.blocks)) {
21
+ if (!isPlainObject(block))
22
+ continue;
23
+ if (block.disabled === true)
24
+ continue;
25
+ const rawName = typeof block.name === 'string' && block.name.trim() ? block.name.trim() : key;
26
+ const cleanedName = String(rawName).replace(/[\x00-\x1f\x7f]+/g, '').trim().slice(0, 128);
27
+ const blockType = normalizeBlockType(cleanedName);
28
+ if (!blockType)
29
+ continue;
30
+ activeBlocks.add(blockType);
31
+ if (!SUPPORTED_BLOCK_TYPES.has(blockType) && !unsupportedMap.has(blockType)) {
32
+ unsupportedMap.set(blockType, cleanedName);
33
+ }
34
+ }
35
+ const unsupportedBlocks = [...unsupportedMap.values()].sort(compareNatural);
36
+ return {
37
+ penDir,
38
+ hasClassic: activeBlocks.has('classic'),
39
+ hasPackages: activeBlocks.has('packages'),
40
+ unsupportedBlocks,
41
+ };
42
+ }
43
+ /**
44
+ * Walks upward from `targetDir` to `rootRealpath` (inclusive) to find the nearest
45
+ * enclosing Pen directory containing `.codepen/pen.config.json`.
46
+ */
47
+ export async function findPenContext(targetDir, rootRealpath) {
48
+ let currentDir = path.resolve(targetDir);
49
+ if (!isWithinRoot(currentDir, rootRealpath))
50
+ return null;
51
+ for (let depth = 0; depth <= MAX_WALK_DEPTH; depth++) {
52
+ const blocks = await readPenBlocks(currentDir, rootRealpath);
53
+ if (blocks)
54
+ return blocks;
55
+ if (currentDir === rootRealpath)
56
+ break;
57
+ const parent = path.dirname(currentDir);
58
+ if (parent === currentDir || !isWithinRoot(parent, rootRealpath))
59
+ break;
60
+ currentDir = parent;
61
+ }
62
+ return null;
63
+ }
@@ -0,0 +1,4 @@
1
+ export { findPenContext, readPenBlocks, } from './context.js';
2
+ export { compileClassicPenHtml, readClassicHeadMetadata, resolveVirtualClassicHtml, } from './classic.js';
3
+ export { applyPackagesBlock, resolveServedHtmlWithBlocks, } from './packages.js';
4
+ export { UNSUPPORTED_BLOCK_PAGE_CSP, renderUnsupportedBlocksPage, resolveUnsupportedBlocksPage, } from './unsupported-page.js';
@@ -0,0 +1,242 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { PEN_HTML_SUFFIX } from '../../constants.js';
4
+ import { readSafeJsonObject, resolveSafeFile } from '../../utils/fs-safe.js';
5
+ import { isPlainObject } from '../../utils/strings.js';
6
+ import { findPenContext } from './context.js';
7
+ const PACKAGE_JSON_FILENAME = 'package.json';
8
+ const MAX_HTML_BYTES = 10 * 1024 * 1024;
9
+ const ESM_SH_ORIGIN = 'https://esm.sh';
10
+ const NPM_PACKAGE_NAME_PATTERN = /^(?:@[a-zA-Z0-9~][a-zA-Z0-9._~-]*\/)?[a-zA-Z0-9~][a-zA-Z0-9._~-]*$/;
11
+ const SAFE_VERSION_PATTERN = /^[a-zA-Z0-9._^~*+-][a-zA-Z0-9._^~*+<>=| -]*$/;
12
+ function buildEsmShImports(dependencies) {
13
+ const imports = {};
14
+ if (!isPlainObject(dependencies))
15
+ return imports;
16
+ for (const [rawName, rawVersion] of Object.entries(dependencies)) {
17
+ if (typeof rawName !== 'string' || typeof rawVersion !== 'string')
18
+ continue;
19
+ const name = rawName.trim();
20
+ const version = rawVersion.trim();
21
+ if (!name || !version)
22
+ continue;
23
+ if (!NPM_PACKAGE_NAME_PATTERN.test(name) || name.includes('..'))
24
+ continue;
25
+ if (!SAFE_VERSION_PATTERN.test(version) || version.includes('..'))
26
+ continue;
27
+ const encodedVersion = version.replace(/ /g, '%20');
28
+ const baseUrlStr = `${ESM_SH_ORIGIN}/${name}@${encodedVersion}`;
29
+ let parsedUrl;
30
+ try {
31
+ parsedUrl = new URL(baseUrlStr);
32
+ }
33
+ catch {
34
+ continue;
35
+ }
36
+ if (parsedUrl.origin !== ESM_SH_ORIGIN ||
37
+ parsedUrl.search ||
38
+ parsedUrl.hash ||
39
+ parsedUrl.pathname.includes('..')) {
40
+ continue;
41
+ }
42
+ imports[name] = baseUrlStr;
43
+ imports[`${name}/`] = `${baseUrlStr}/`;
44
+ }
45
+ return imports;
46
+ }
47
+ function serializeImportMap(mapObj) {
48
+ // Escape `<` as `\u003c` so serialized JSON can never break out of `<script>`.
49
+ return JSON.stringify(mapObj, null, 2).replace(/</g, '\\u003c');
50
+ }
51
+ function findTagEnd(html, startIndex) {
52
+ let quote = null;
53
+ for (let i = startIndex; i < html.length; i++) {
54
+ const ch = html[i];
55
+ if (quote) {
56
+ if (ch === quote)
57
+ quote = null;
58
+ }
59
+ else if (ch === '"' || ch === "'") {
60
+ quote = ch;
61
+ }
62
+ else if (ch === '>') {
63
+ return i;
64
+ }
65
+ }
66
+ return -1;
67
+ }
68
+ function isTagNameBoundary(ch) {
69
+ return ch === undefined || ch === '>' || ch === '/' || /\s/.test(ch);
70
+ }
71
+ function getTagAttribute(attrText, targetName) {
72
+ const attrPattern = /([a-zA-Z_:][\w:.-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
73
+ const lowerTarget = targetName.toLowerCase();
74
+ for (const match of attrText.matchAll(attrPattern)) {
75
+ if (match[1]?.toLowerCase() === lowerTarget) {
76
+ return match[2] ?? match[3] ?? match[4] ?? '';
77
+ }
78
+ }
79
+ return null;
80
+ }
81
+ function findExistingImportMapScript(html) {
82
+ const lower = html.toLowerCase();
83
+ let i = 0;
84
+ while (i < html.length) {
85
+ const lt = html.indexOf('<', i);
86
+ if (lt === -1)
87
+ break;
88
+ if (html.startsWith('<!--', lt)) {
89
+ const endComment = html.indexOf('-->', lt + 4);
90
+ if (endComment === -1)
91
+ break;
92
+ i = endComment + 3;
93
+ continue;
94
+ }
95
+ if (lower.startsWith('<script', lt) && isTagNameBoundary(html[lt + 7])) {
96
+ const openEnd = findTagEnd(html, lt + 7);
97
+ if (openEnd === -1)
98
+ break;
99
+ const closeStart = lower.indexOf('</script', openEnd + 1);
100
+ if (closeStart === -1)
101
+ break;
102
+ const closeEnd = findTagEnd(html, closeStart + 8);
103
+ if (closeEnd === -1)
104
+ break;
105
+ const attrText = html.slice(lt + 7, openEnd);
106
+ const scriptType = getTagAttribute(attrText, 'type');
107
+ if (scriptType !== null && scriptType.trim().toLowerCase() === 'importmap') {
108
+ return {
109
+ contentStart: openEnd + 1,
110
+ contentEnd: closeStart,
111
+ };
112
+ }
113
+ i = closeEnd + 1;
114
+ continue;
115
+ }
116
+ i = lt + 1;
117
+ }
118
+ return null;
119
+ }
120
+ function findImportMapInsertionPoint(html) {
121
+ const lower = html.toLowerCase();
122
+ let i = 0;
123
+ let firstScriptStart = -1;
124
+ let afterHtmlOrDoctype = -1;
125
+ while (i < html.length) {
126
+ const lt = html.indexOf('<', i);
127
+ if (lt === -1)
128
+ break;
129
+ if (html.startsWith('<!--', lt)) {
130
+ const endComment = html.indexOf('-->', lt + 4);
131
+ if (endComment === -1)
132
+ break;
133
+ i = endComment + 3;
134
+ continue;
135
+ }
136
+ if (lower.startsWith('<head', lt) && isTagNameBoundary(html[lt + 5])) {
137
+ const openEnd = findTagEnd(html, lt + 5);
138
+ if (openEnd !== -1) {
139
+ return { index: openEnd + 1, leadingNewline: true };
140
+ }
141
+ break;
142
+ }
143
+ if (firstScriptStart === -1 &&
144
+ lower.startsWith('<script', lt) &&
145
+ isTagNameBoundary(html[lt + 7])) {
146
+ firstScriptStart = lt;
147
+ }
148
+ if (lower.startsWith('<!doctype', lt) && isTagNameBoundary(html[lt + 9])) {
149
+ const openEnd = findTagEnd(html, lt + 9);
150
+ if (openEnd !== -1) {
151
+ afterHtmlOrDoctype = openEnd + 1;
152
+ i = openEnd + 1;
153
+ continue;
154
+ }
155
+ }
156
+ if (lower.startsWith('<html', lt) && isTagNameBoundary(html[lt + 5])) {
157
+ const openEnd = findTagEnd(html, lt + 5);
158
+ if (openEnd !== -1) {
159
+ afterHtmlOrDoctype = openEnd + 1;
160
+ i = openEnd + 1;
161
+ continue;
162
+ }
163
+ }
164
+ i = lt + 1;
165
+ }
166
+ if (firstScriptStart !== -1) {
167
+ return { index: firstScriptStart, leadingNewline: false };
168
+ }
169
+ if (afterHtmlOrDoctype !== -1) {
170
+ return { index: afterHtmlOrDoctype, leadingNewline: true };
171
+ }
172
+ return { index: 0, leadingNewline: false };
173
+ }
174
+ /**
175
+ * Applies the CodePen `packages` block to an HTML document by reading `package.json`
176
+ * dependencies from the Pen root and injecting (or merging into an existing)
177
+ * `<script type="importmap">` targeting `https://esm.sh/`.
178
+ */
179
+ export async function applyPackagesBlock(options) {
180
+ const { html, penContext, rootRealpath } = options;
181
+ if (!penContext?.hasPackages)
182
+ return html;
183
+ const pkgJsonPath = path.join(penContext.penDir, PACKAGE_JSON_FILENAME);
184
+ const pkgJson = await readSafeJsonObject(pkgJsonPath, rootRealpath);
185
+ if (!pkgJson || !isPlainObject(pkgJson.dependencies))
186
+ return html;
187
+ const generatedImports = buildEsmShImports(pkgJson.dependencies);
188
+ if (Object.keys(generatedImports).length === 0)
189
+ return html;
190
+ const existingScript = findExistingImportMapScript(html);
191
+ if (existingScript) {
192
+ const rawExisting = html.slice(existingScript.contentStart, existingScript.contentEnd).trim();
193
+ try {
194
+ const parsedExisting = rawExisting ? JSON.parse(rawExisting) : {};
195
+ if (!isPlainObject(parsedExisting))
196
+ return html;
197
+ const userImports = isPlainObject(parsedExisting.imports) ? parsedExisting.imports : {};
198
+ const merged = {
199
+ ...parsedExisting,
200
+ imports: {
201
+ ...generatedImports,
202
+ ...userImports,
203
+ },
204
+ };
205
+ return (html.slice(0, existingScript.contentStart) +
206
+ `\n${serializeImportMap(merged)}\n` +
207
+ html.slice(existingScript.contentEnd));
208
+ }
209
+ catch {
210
+ return html;
211
+ }
212
+ }
213
+ const { index, leadingNewline } = findImportMapInsertionPoint(html);
214
+ const prefix = leadingNewline ? '\n' : '';
215
+ const importMapTag = `${prefix}<script type="importmap">\n${serializeImportMap({ imports: generatedImports })}\n</script>\n`;
216
+ return html.slice(0, index) + importMapTag + html.slice(index);
217
+ }
218
+ /**
219
+ * Applies active HTML blocks (currently `packages`) to an existing `.html` file on disk.
220
+ * Returns `{ transformed: true, html }` when a transform ran, or `{ transformed: false }`.
221
+ */
222
+ export async function resolveServedHtmlWithBlocks(options) {
223
+ const { filePath, rootRealpath } = options;
224
+ const lowerPath = filePath.toLowerCase();
225
+ if (!lowerPath.endsWith('.html') || lowerPath.endsWith(PEN_HTML_SUFFIX)) {
226
+ return { transformed: false };
227
+ }
228
+ const penContext = await findPenContext(path.dirname(filePath), rootRealpath);
229
+ if (!penContext?.hasPackages) {
230
+ return { transformed: false };
231
+ }
232
+ const safeFile = await resolveSafeFile(filePath, rootRealpath);
233
+ if (!safeFile || safeFile.size > MAX_HTML_BYTES) {
234
+ return { transformed: false };
235
+ }
236
+ const rawHtml = await fs.readFile(safeFile.realPath, 'utf8');
237
+ const html = await applyPackagesBlock({ html: rawHtml, penContext, rootRealpath });
238
+ if (html === rawHtml) {
239
+ return { transformed: false };
240
+ }
241
+ return { transformed: true, html };
242
+ }