codepen-commander 1.3.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.
- package/README.md +103 -11
- package/api/client.js +129 -106
- package/cli.js +34 -29
- package/commands/auth/default.js +40 -0
- package/commands/auth/index.js +83 -0
- package/commands/auth/list.js +78 -0
- package/commands/auth/login.js +136 -0
- package/commands/auth/logout.js +186 -0
- package/commands/auth/status.js +212 -0
- package/commands/build.js +256 -0
- package/commands/clone.js +13 -581
- package/commands/delete.js +548 -80
- package/commands/deploy.js +164 -169
- package/commands/domains.js +83 -39
- package/commands/fork.js +13 -317
- package/commands/info.js +152 -0
- package/commands/init.js +375 -0
- package/commands/list.js +95 -78
- package/commands/new.js +155 -83
- package/commands/open.js +29 -19
- package/commands/privacy.js +52 -36
- package/commands/pull.js +123 -110
- package/commands/push.js +221 -376
- package/commands/restore.js +251 -0
- package/commands/rollback.js +141 -0
- package/commands/serve.js +119 -0
- package/commands/settings.js +126 -0
- package/commands/shell.js +305 -0
- package/commands/status.js +133 -39
- package/commands/sync.js +330 -0
- package/commands/undeploy.js +102 -0
- package/commands/unlink.js +191 -0
- package/commands/versions.js +100 -163
- package/config/auth.js +4 -374
- package/config/pen-blocks.js +166 -0
- package/config/project.js +103 -231
- package/config/user-store.js +364 -0
- package/constants.js +42 -0
- package/errors.js +17 -0
- package/package.json +1 -1
- package/shell/index.html +79 -0
- package/shell/scripts.js +276 -0
- package/shell/styles.css +492 -0
- package/site/blocks/classic.js +270 -0
- package/site/blocks/context.js +63 -0
- package/site/blocks/index.js +4 -0
- package/site/blocks/packages.js +242 -0
- package/site/blocks/unsupported-page.js +328 -0
- package/site/builder.js +475 -0
- package/site/detect.js +65 -0
- package/site/ignore-files.js +90 -0
- package/site/manifest.js +227 -0
- package/site/server.js +483 -0
- package/site/shell.js +363 -0
- package/sync/fs.js +19 -17
- package/sync/info.js +6 -81
- package/utils/browser.js +17 -10
- package/utils/cli-options.js +79 -0
- package/utils/codepen-url.js +183 -0
- package/utils/format.js +39 -30
- package/utils/fs-safe.js +95 -0
- package/utils/html.js +40 -1
- package/utils/json.js +4 -19
- package/utils/output.js +37 -0
- package/utils/package-paths.js +51 -0
- package/utils/prompts/index.js +5 -0
- package/utils/prompts/multi-select.js +185 -0
- package/utils/prompts/secret.js +65 -0
- package/utils/prompts/select.js +141 -0
- package/utils/prompts/text.js +99 -0
- package/utils/prompts/tty-list.js +165 -0
- package/utils/prompts/types.js +35 -0
- package/utils/strings.js +98 -0
- package/utils/watcher.js +82 -0
- package/{commands → workflows}/auth-context.js +13 -7
- package/workflows/batch-pens.js +1647 -0
- package/workflows/batch-target.js +184 -0
- package/workflows/classic-convert.js +241 -0
- package/workflows/clone-pen.js +381 -0
- package/{commands → workflows}/create-pen.js +59 -84
- package/workflows/discover-pens.js +91 -0
- package/workflows/fork-pen.js +314 -0
- package/workflows/missing-pen.js +212 -0
- package/workflows/pull-pen.js +204 -0
- package/workflows/push-pen.js +318 -0
- package/{commands → workflows}/scaffold.js +4 -3
- package/workflows/sync-pen.js +227 -0
- package/{commands → workflows}/unowned-pen.js +16 -12
- package/commands/auth.js +0 -593
- package/commands/meta.js +0 -184
- package/utils/prompts.js +0 -316
- /package/{types.js → api/types.js} +0 -0
package/site/server.js
ADDED
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
import http, {} from 'node:http';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { PEN_HTML_SUFFIX, PROJECT_CONFIG_FILENAME } from '../constants.js';
|
|
5
|
+
import { CliError } from '../errors.js';
|
|
6
|
+
import { isWithinRoot, resolveSafeDir, resolveSafeFile } from '../utils/fs-safe.js';
|
|
7
|
+
import { resolveServedHtmlWithBlocks, resolveUnsupportedBlocksPage, resolveVirtualClassicHtml, } from './blocks/index.js';
|
|
8
|
+
import { classifyDirectoryMode, inspectTargetDirectory, } from './detect.js';
|
|
9
|
+
import { countDemos, createInMemoryManifestWatcher, } from './manifest.js';
|
|
10
|
+
import { renderShellIndexHtml, resolveActiveShell, resolveShellAssetForRequest, resolveSiteMetadata, } from './shell.js';
|
|
11
|
+
export const SERVE_HOST = '127.0.0.1';
|
|
12
|
+
export const DEFAULT_SERVE_PORT = 3000;
|
|
13
|
+
export const MIME_TYPES = {
|
|
14
|
+
'.avif': 'image/avif',
|
|
15
|
+
'.css': 'text/css; charset=utf-8',
|
|
16
|
+
'.gif': 'image/gif',
|
|
17
|
+
'.html': 'text/html; charset=utf-8',
|
|
18
|
+
'.ico': 'image/x-icon',
|
|
19
|
+
'.jpeg': 'image/jpeg',
|
|
20
|
+
'.jpg': 'image/jpeg',
|
|
21
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
22
|
+
'.json': 'application/json; charset=utf-8',
|
|
23
|
+
'.md': 'text/markdown; charset=utf-8',
|
|
24
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
25
|
+
'.mp3': 'audio/mpeg',
|
|
26
|
+
'.mp4': 'video/mp4',
|
|
27
|
+
'.ogg': 'audio/ogg',
|
|
28
|
+
'.png': 'image/png',
|
|
29
|
+
'.svg': 'image/svg+xml',
|
|
30
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
31
|
+
'.vtt': 'text/vtt; charset=utf-8',
|
|
32
|
+
'.wasm': 'application/wasm',
|
|
33
|
+
'.wav': 'audio/wav',
|
|
34
|
+
'.webm': 'video/webm',
|
|
35
|
+
'.webp': 'image/webp',
|
|
36
|
+
'.woff': 'font/woff',
|
|
37
|
+
'.woff2': 'font/woff2',
|
|
38
|
+
'.xml': 'application/xml; charset=utf-8',
|
|
39
|
+
};
|
|
40
|
+
// TODO(security): Permissions-Policy and Content-Security-Policy are intentionally
|
|
41
|
+
// omitted on user demo routes served by this localhost-only dev server so users
|
|
42
|
+
// are free to author demos using inline scripts/styles, import maps, third-party
|
|
43
|
+
// CDNs, frameworks, or experimental browser APIs (sensors, media, fullscreen).
|
|
44
|
+
const BASE_SECURITY_HEADERS = {
|
|
45
|
+
'Cache-Control': 'no-store',
|
|
46
|
+
'Referrer-Policy': 'no-referrer',
|
|
47
|
+
'X-Content-Type-Options': 'nosniff',
|
|
48
|
+
'X-Frame-Options': 'SAMEORIGIN',
|
|
49
|
+
};
|
|
50
|
+
const BUILTIN_SHELL_SECURITY_HEADERS = {
|
|
51
|
+
...BASE_SECURITY_HEADERS,
|
|
52
|
+
'Permissions-Policy': 'camera=(), microphone=(), geolocation=()',
|
|
53
|
+
'Content-Security-Policy': "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; media-src 'self' blob:; font-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'",
|
|
54
|
+
};
|
|
55
|
+
// TODO(security): Custom user shells (exported and edited locally by the user) omit
|
|
56
|
+
// strict script-src/style-src CSP on localhost so users can freely add inline styles,
|
|
57
|
+
// external fonts, or custom scripts, while retaining nosniff, SAMEORIGIN, and Permissions-Policy.
|
|
58
|
+
const CUSTOM_SHELL_SECURITY_HEADERS = {
|
|
59
|
+
...BASE_SECURITY_HEADERS,
|
|
60
|
+
'Permissions-Policy': 'camera=(), microphone=(), geolocation=()',
|
|
61
|
+
};
|
|
62
|
+
export function parseServePort(rawPort, allowZero = false) {
|
|
63
|
+
if (rawPort === undefined || rawPort === '')
|
|
64
|
+
return DEFAULT_SERVE_PORT;
|
|
65
|
+
const parsed = typeof rawPort === 'number' ? rawPort : Number.parseInt(String(rawPort), 10);
|
|
66
|
+
const minPort = allowZero ? 0 : 1;
|
|
67
|
+
if (!Number.isInteger(parsed) ||
|
|
68
|
+
parsed < minPort ||
|
|
69
|
+
parsed > 65535 ||
|
|
70
|
+
String(parsed) !== String(rawPort).trim()) {
|
|
71
|
+
throw new CliError(400, `Invalid port value: ${String(rawPort)} (expected an integer between 1 and 65535).`);
|
|
72
|
+
}
|
|
73
|
+
return parsed;
|
|
74
|
+
}
|
|
75
|
+
function sendBuffer(req, res, statusCode, content, contentType, headers) {
|
|
76
|
+
res.writeHead(statusCode, {
|
|
77
|
+
...headers,
|
|
78
|
+
'Content-Type': contentType,
|
|
79
|
+
'Content-Length': content.byteLength,
|
|
80
|
+
});
|
|
81
|
+
if (req.method === 'HEAD') {
|
|
82
|
+
res.end();
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
res.end(content);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function sendError(res, statusCode, message, extraHeaders = {}) {
|
|
89
|
+
const body = `${statusCode} ${message}\n`;
|
|
90
|
+
res.writeHead(statusCode, {
|
|
91
|
+
...BUILTIN_SHELL_SECURITY_HEADERS,
|
|
92
|
+
...extraHeaders,
|
|
93
|
+
'Content-Type': 'text/plain; charset=utf-8',
|
|
94
|
+
'Content-Length': Buffer.byteLength(body),
|
|
95
|
+
});
|
|
96
|
+
res.end(body);
|
|
97
|
+
}
|
|
98
|
+
async function hasEnclosingCdpnJson(dirRealpath, rootRealpath) {
|
|
99
|
+
let current = path.resolve(dirRealpath);
|
|
100
|
+
while (current !== rootRealpath && isWithinRoot(current, rootRealpath)) {
|
|
101
|
+
const cdpnFile = await resolveSafeFile(path.join(current, PROJECT_CONFIG_FILENAME), rootRealpath);
|
|
102
|
+
if (cdpnFile) {
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
const parent = path.dirname(current);
|
|
106
|
+
if (parent === current)
|
|
107
|
+
break;
|
|
108
|
+
current = parent;
|
|
109
|
+
}
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
async function resolveUnsupportedOrClassicHtml(options) {
|
|
113
|
+
const { dirRealpath, requestedFilename, rootRealpath, isCollectionRoot, includeClassicVirtual = true, } = options;
|
|
114
|
+
const unsupportedPage = await resolveUnsupportedBlocksPage({
|
|
115
|
+
dirRealpath,
|
|
116
|
+
rootRealpath,
|
|
117
|
+
isRootServe: isCollectionRoot,
|
|
118
|
+
});
|
|
119
|
+
if (unsupportedPage) {
|
|
120
|
+
return {
|
|
121
|
+
status: 501,
|
|
122
|
+
errorHtml: unsupportedPage.html,
|
|
123
|
+
csp: unsupportedPage.csp,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
if (includeClassicVirtual) {
|
|
127
|
+
const virtualHtml = await resolveVirtualClassicHtml({
|
|
128
|
+
dirRealpath,
|
|
129
|
+
requestedFilename,
|
|
130
|
+
rootRealpath,
|
|
131
|
+
});
|
|
132
|
+
if (virtualHtml !== null) {
|
|
133
|
+
return { status: 200, virtualHtml, contentType: MIME_TYPES['.html'] };
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
async function resolveSafePath(rawPathname, rootDir, rootRealpath, isCollectionRoot) {
|
|
139
|
+
let decodedPath;
|
|
140
|
+
try {
|
|
141
|
+
decodedPath = decodeURIComponent(rawPathname);
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
return { status: 400, message: 'Bad Request' };
|
|
145
|
+
}
|
|
146
|
+
if (decodedPath.includes('\0') || decodedPath.includes('\\')) {
|
|
147
|
+
return { status: 400, message: 'Bad Request' };
|
|
148
|
+
}
|
|
149
|
+
const segments = decodedPath.split('/').filter(Boolean);
|
|
150
|
+
for (const segment of segments) {
|
|
151
|
+
if (segment === '.' || segment === '..' || segment.startsWith('.')) {
|
|
152
|
+
return { status: 403, message: 'Forbidden' };
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
const resolvedPath = path.resolve(rootDir, ...segments);
|
|
156
|
+
if (!isWithinRoot(resolvedPath, rootDir)) {
|
|
157
|
+
return { status: 403, message: 'Forbidden' };
|
|
158
|
+
}
|
|
159
|
+
let lstat;
|
|
160
|
+
try {
|
|
161
|
+
lstat = await fs.lstat(resolvedPath);
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
const canResolvePenBlocks = !isCollectionRoot || segments.length >= 2;
|
|
165
|
+
if (canResolvePenBlocks && !decodedPath.endsWith('/') && segments.length > 0) {
|
|
166
|
+
const requestedFilename = segments.at(-1);
|
|
167
|
+
const lowerFilename = requestedFilename.toLowerCase();
|
|
168
|
+
if (lowerFilename.endsWith('.html') && !lowerFilename.endsWith(PEN_HTML_SUFFIX)) {
|
|
169
|
+
const realParentDir = await resolveSafeDir(path.dirname(resolvedPath), rootRealpath, rootDir);
|
|
170
|
+
if (realParentDir) {
|
|
171
|
+
if (isCollectionRoot &&
|
|
172
|
+
!(await hasEnclosingCdpnJson(realParentDir, rootRealpath))) {
|
|
173
|
+
return { status: 404, message: 'Not Found' };
|
|
174
|
+
}
|
|
175
|
+
try {
|
|
176
|
+
const fallback = await resolveUnsupportedOrClassicHtml({
|
|
177
|
+
dirRealpath: realParentDir,
|
|
178
|
+
requestedFilename,
|
|
179
|
+
rootRealpath,
|
|
180
|
+
isCollectionRoot,
|
|
181
|
+
});
|
|
182
|
+
if (fallback)
|
|
183
|
+
return fallback;
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
// Fall through to 404
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return { status: 404, message: 'Not Found' };
|
|
192
|
+
}
|
|
193
|
+
if (lstat.isSymbolicLink()) {
|
|
194
|
+
return { status: 403, message: 'Forbidden' };
|
|
195
|
+
}
|
|
196
|
+
if (lstat.isDirectory()) {
|
|
197
|
+
let realDirPath;
|
|
198
|
+
try {
|
|
199
|
+
realDirPath = await fs.realpath(resolvedPath);
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
return { status: 404, message: 'Not Found' };
|
|
203
|
+
}
|
|
204
|
+
if (!isWithinRoot(realDirPath, rootRealpath)) {
|
|
205
|
+
return { status: 403, message: 'Forbidden' };
|
|
206
|
+
}
|
|
207
|
+
// In collection mode, never serve subdirectories that do not have an enclosing `.cdpn.json`
|
|
208
|
+
if (isCollectionRoot &&
|
|
209
|
+
segments.length > 0 &&
|
|
210
|
+
!(await hasEnclosingCdpnJson(realDirPath, rootRealpath))) {
|
|
211
|
+
return { status: 404, message: 'Not Found' };
|
|
212
|
+
}
|
|
213
|
+
if (!decodedPath.endsWith('/')) {
|
|
214
|
+
const normalizedRedirect = `/${segments.map(encodeURIComponent).join('/')}/`;
|
|
215
|
+
return { status: 301, redirect: normalizedRedirect };
|
|
216
|
+
}
|
|
217
|
+
const canResolvePenBlocks = !isCollectionRoot || segments.length > 0;
|
|
218
|
+
if (canResolvePenBlocks) {
|
|
219
|
+
const unsupported = await resolveUnsupportedOrClassicHtml({
|
|
220
|
+
dirRealpath: realDirPath,
|
|
221
|
+
requestedFilename: 'index.html',
|
|
222
|
+
rootRealpath,
|
|
223
|
+
isCollectionRoot,
|
|
224
|
+
includeClassicVirtual: false,
|
|
225
|
+
});
|
|
226
|
+
if (unsupported)
|
|
227
|
+
return unsupported;
|
|
228
|
+
}
|
|
229
|
+
const indexPath = path.join(resolvedPath, 'index.html');
|
|
230
|
+
try {
|
|
231
|
+
const indexStat = await fs.lstat(indexPath);
|
|
232
|
+
if (indexStat.isSymbolicLink() || !indexStat.isFile()) {
|
|
233
|
+
return { status: 404, message: 'Not Found' };
|
|
234
|
+
}
|
|
235
|
+
const realIndexPath = await fs.realpath(indexPath);
|
|
236
|
+
if (!isWithinRoot(realIndexPath, rootRealpath)) {
|
|
237
|
+
return { status: 403, message: 'Forbidden' };
|
|
238
|
+
}
|
|
239
|
+
return { status: 200, filePath: realIndexPath, size: indexStat.size };
|
|
240
|
+
}
|
|
241
|
+
catch {
|
|
242
|
+
if (canResolvePenBlocks) {
|
|
243
|
+
try {
|
|
244
|
+
const virtualHtml = await resolveVirtualClassicHtml({
|
|
245
|
+
dirRealpath: realDirPath,
|
|
246
|
+
requestedFilename: 'index.html',
|
|
247
|
+
rootRealpath,
|
|
248
|
+
});
|
|
249
|
+
if (virtualHtml !== null) {
|
|
250
|
+
return { status: 200, virtualHtml, contentType: MIME_TYPES['.html'] };
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
// Fall through to 404
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return { status: 404, message: 'Not Found' };
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
if (!lstat.isFile()) {
|
|
261
|
+
return { status: 404, message: 'Not Found' };
|
|
262
|
+
}
|
|
263
|
+
const realFilePath = await fs.realpath(resolvedPath);
|
|
264
|
+
if (!isWithinRoot(realFilePath, rootRealpath)) {
|
|
265
|
+
return { status: 403, message: 'Forbidden' };
|
|
266
|
+
}
|
|
267
|
+
// In collection mode, files inside subdirectories are only served when enclosed by a `.cdpn.json` demo
|
|
268
|
+
if (isCollectionRoot &&
|
|
269
|
+
segments.length >= 2 &&
|
|
270
|
+
!(await hasEnclosingCdpnJson(path.dirname(realFilePath), rootRealpath))) {
|
|
271
|
+
return { status: 404, message: 'Not Found' };
|
|
272
|
+
}
|
|
273
|
+
const lowerFilePath = realFilePath.toLowerCase();
|
|
274
|
+
if ((!isCollectionRoot || segments.length >= 2) &&
|
|
275
|
+
lowerFilePath.endsWith('.html') &&
|
|
276
|
+
!lowerFilePath.endsWith(PEN_HTML_SUFFIX)) {
|
|
277
|
+
const unsupported = await resolveUnsupportedOrClassicHtml({
|
|
278
|
+
dirRealpath: path.dirname(realFilePath),
|
|
279
|
+
requestedFilename: path.basename(realFilePath),
|
|
280
|
+
rootRealpath,
|
|
281
|
+
isCollectionRoot,
|
|
282
|
+
includeClassicVirtual: false,
|
|
283
|
+
});
|
|
284
|
+
if (unsupported)
|
|
285
|
+
return unsupported;
|
|
286
|
+
}
|
|
287
|
+
return { status: 200, filePath: realFilePath, size: lstat.size };
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Starts the local localhost-only (`127.0.0.1`) HTTP server for either a single Pen
|
|
291
|
+
* (`.cdpn.json`) or a multi-Pen collection directory with in-memory `demos.json`.
|
|
292
|
+
*/
|
|
293
|
+
export async function startDevServer(options = {}) {
|
|
294
|
+
const baseCwd = path.resolve(options.cwd ?? process.cwd());
|
|
295
|
+
const resolvedTarget = path.resolve(baseCwd, options.targetDir ?? '.');
|
|
296
|
+
let stat;
|
|
297
|
+
try {
|
|
298
|
+
stat = await fs.stat(resolvedTarget);
|
|
299
|
+
}
|
|
300
|
+
catch (error) {
|
|
301
|
+
if (error.code === 'ENOENT') {
|
|
302
|
+
throw new CliError(404, `Directory not found: ${resolvedTarget}`);
|
|
303
|
+
}
|
|
304
|
+
throw error;
|
|
305
|
+
}
|
|
306
|
+
if (!stat.isDirectory()) {
|
|
307
|
+
throw new CliError(400, `Not a directory: ${resolvedTarget}`);
|
|
308
|
+
}
|
|
309
|
+
const port = parseServePort(options.port, Boolean(options.allowEphemeralPort));
|
|
310
|
+
const inspection = await inspectTargetDirectory(resolvedTarget);
|
|
311
|
+
const mode = classifyDirectoryMode(inspection);
|
|
312
|
+
let manifestWatcher = null;
|
|
313
|
+
let initialDemoCount = 0;
|
|
314
|
+
if (mode === 'collection') {
|
|
315
|
+
manifestWatcher = await createInMemoryManifestWatcher({
|
|
316
|
+
rootDir: inspection.rootRealpath,
|
|
317
|
+
onUpdate({ demoCount }) {
|
|
318
|
+
options.onManifestUpdate?.(demoCount);
|
|
319
|
+
},
|
|
320
|
+
onError(error) {
|
|
321
|
+
options.onWatchError?.(error);
|
|
322
|
+
},
|
|
323
|
+
});
|
|
324
|
+
initialDemoCount = countDemos(manifestWatcher.getManifest());
|
|
325
|
+
}
|
|
326
|
+
let activeShell = null;
|
|
327
|
+
if (mode === 'collection') {
|
|
328
|
+
activeShell = await resolveActiveShell({
|
|
329
|
+
explicitShell: options.explicitShell,
|
|
330
|
+
cwd: baseCwd,
|
|
331
|
+
homeDir: options.homeDir,
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
else if (options.explicitShell !== undefined) {
|
|
335
|
+
// Still validate explicit --shell early so typos aren't silently swallowed
|
|
336
|
+
await resolveActiveShell({
|
|
337
|
+
explicitShell: options.explicitShell,
|
|
338
|
+
cwd: baseCwd,
|
|
339
|
+
homeDir: options.homeDir,
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
const siteMeta = resolveSiteMetadata(inspection.rootRealpath, options.site);
|
|
343
|
+
const isCollectionRoot = mode === 'collection';
|
|
344
|
+
const handleRequest = async (req, res) => {
|
|
345
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
346
|
+
sendError(res, 405, 'Method Not Allowed', { Allow: 'GET, HEAD' });
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
let requestUrl;
|
|
350
|
+
try {
|
|
351
|
+
requestUrl = new URL(req.url ?? '/', `http://${SERVE_HOST}:${port || DEFAULT_SERVE_PORT}`);
|
|
352
|
+
}
|
|
353
|
+
catch {
|
|
354
|
+
sendError(res, 400, 'Bad Request');
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
const result = await resolveSafePath(requestUrl.pathname, inspection.rootDir, inspection.rootRealpath, isCollectionRoot);
|
|
358
|
+
if (result.status === 301) {
|
|
359
|
+
res.writeHead(301, {
|
|
360
|
+
...BASE_SECURITY_HEADERS,
|
|
361
|
+
Location: result.redirect,
|
|
362
|
+
});
|
|
363
|
+
res.end();
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
// Serve in-memory demos.json at /demos.json in collection mode if not present on disk
|
|
367
|
+
if (result.status === 404 &&
|
|
368
|
+
isCollectionRoot &&
|
|
369
|
+
manifestWatcher &&
|
|
370
|
+
requestUrl.pathname === '/demos.json') {
|
|
371
|
+
sendBuffer(req, res, 200, Buffer.from(manifestWatcher.getSerialized(), 'utf8'), 'application/json; charset=utf-8', BUILTIN_SHELL_SECURITY_HEADERS);
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
// Fall back to active shell assets in collection mode whenever a root asset is not on disk
|
|
375
|
+
if (result.status === 404 && isCollectionRoot && activeShell) {
|
|
376
|
+
const shellAsset = await resolveShellAssetForRequest(requestUrl.pathname, activeShell);
|
|
377
|
+
if (shellAsset) {
|
|
378
|
+
const ext = path.extname(shellAsset.filePath).toLowerCase();
|
|
379
|
+
const contentType = MIME_TYPES[ext] ?? 'application/octet-stream';
|
|
380
|
+
const securityHeaders = shellAsset.fromBuiltin
|
|
381
|
+
? BUILTIN_SHELL_SECURITY_HEADERS
|
|
382
|
+
: CUSTOM_SHELL_SECURITY_HEADERS;
|
|
383
|
+
try {
|
|
384
|
+
let content;
|
|
385
|
+
if (shellAsset.isIndexHtml) {
|
|
386
|
+
const templateHtml = await fs.readFile(shellAsset.filePath, 'utf8');
|
|
387
|
+
content = Buffer.from(renderShellIndexHtml(templateHtml, siteMeta, { includeMissingDemoWarning: true }), 'utf8');
|
|
388
|
+
}
|
|
389
|
+
else {
|
|
390
|
+
content = await fs.readFile(shellAsset.filePath);
|
|
391
|
+
}
|
|
392
|
+
sendBuffer(req, res, 200, content, contentType, securityHeaders);
|
|
393
|
+
}
|
|
394
|
+
catch {
|
|
395
|
+
sendError(res, 500, 'Internal Server Error');
|
|
396
|
+
}
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
if (result.status === 501) {
|
|
401
|
+
sendBuffer(req, res, 501, Buffer.from(result.errorHtml, 'utf8'), MIME_TYPES['.html'], {
|
|
402
|
+
...BASE_SECURITY_HEADERS,
|
|
403
|
+
'Content-Security-Policy': result.csp,
|
|
404
|
+
});
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
if (result.status === 200 && 'virtualHtml' in result) {
|
|
408
|
+
sendBuffer(req, res, 200, Buffer.from(result.virtualHtml, 'utf8'), result.contentType, BASE_SECURITY_HEADERS);
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
if (result.status !== 200) {
|
|
412
|
+
sendError(res, result.status, result.message);
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
const ext = path.extname(result.filePath).toLowerCase();
|
|
416
|
+
const contentType = MIME_TYPES[ext] ?? 'application/octet-stream';
|
|
417
|
+
try {
|
|
418
|
+
let content;
|
|
419
|
+
if (ext === '.html' &&
|
|
420
|
+
(!isCollectionRoot || path.dirname(result.filePath) !== inspection.rootRealpath)) {
|
|
421
|
+
const blockResult = await resolveServedHtmlWithBlocks({
|
|
422
|
+
filePath: result.filePath,
|
|
423
|
+
rootRealpath: inspection.rootRealpath,
|
|
424
|
+
});
|
|
425
|
+
content = blockResult.transformed
|
|
426
|
+
? Buffer.from(blockResult.html, 'utf8')
|
|
427
|
+
: await fs.readFile(result.filePath);
|
|
428
|
+
}
|
|
429
|
+
else {
|
|
430
|
+
content = await fs.readFile(result.filePath);
|
|
431
|
+
}
|
|
432
|
+
sendBuffer(req, res, 200, content, contentType, BASE_SECURITY_HEADERS);
|
|
433
|
+
}
|
|
434
|
+
catch {
|
|
435
|
+
sendError(res, 500, 'Internal Server Error');
|
|
436
|
+
}
|
|
437
|
+
};
|
|
438
|
+
const server = http.createServer((req, res) => {
|
|
439
|
+
void handleRequest(req, res).catch(() => {
|
|
440
|
+
if (!res.headersSent) {
|
|
441
|
+
sendError(res, 500, 'Internal Server Error');
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
});
|
|
445
|
+
try {
|
|
446
|
+
await new Promise((resolve, reject) => {
|
|
447
|
+
server.once('error', reject);
|
|
448
|
+
server.listen(port, SERVE_HOST, () => {
|
|
449
|
+
server.off('error', reject);
|
|
450
|
+
resolve();
|
|
451
|
+
});
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
catch (error) {
|
|
455
|
+
manifestWatcher?.close();
|
|
456
|
+
throw error;
|
|
457
|
+
}
|
|
458
|
+
const address = server.address();
|
|
459
|
+
const boundPort = typeof address === 'object' && address ? address.port : port;
|
|
460
|
+
const url = `http://${SERVE_HOST}:${boundPort}`;
|
|
461
|
+
let closed = false;
|
|
462
|
+
const close = async () => {
|
|
463
|
+
if (closed)
|
|
464
|
+
return;
|
|
465
|
+
closed = true;
|
|
466
|
+
manifestWatcher?.close();
|
|
467
|
+
server.closeAllConnections?.();
|
|
468
|
+
await new Promise((resolve) => {
|
|
469
|
+
server.close(() => resolve());
|
|
470
|
+
});
|
|
471
|
+
};
|
|
472
|
+
return {
|
|
473
|
+
server,
|
|
474
|
+
url,
|
|
475
|
+
port: boundPort,
|
|
476
|
+
host: SERVE_HOST,
|
|
477
|
+
mode,
|
|
478
|
+
inspection,
|
|
479
|
+
demoCount: initialDemoCount,
|
|
480
|
+
shell: activeShell,
|
|
481
|
+
close,
|
|
482
|
+
};
|
|
483
|
+
}
|