@stencil/dev-server 5.0.0-next.0 → 5.0.0-rc.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 +105 -0
- package/dist/client/index.d.ts +9 -3
- package/dist/client/index.js +152 -84
- package/dist/connector.html +27 -20
- package/dist/index.d.mts +0 -3
- package/dist/index.mjs +348 -51
- package/dist/templates/directory-index.html +16 -6
- package/dist/templates/initial-load.html +142 -132
- package/dist/worker-thread.js +17 -15
- package/package.json +25 -19
- package/templates/directory-index.html +16 -6
- package/templates/initial-load.html +142 -132
- /package/{LICENSE.md → LICENSE} +0 -0
package/dist/index.mjs
CHANGED
|
@@ -5,9 +5,9 @@ import * as net from "node:net";
|
|
|
5
5
|
import { WebSocketServer } from "ws";
|
|
6
6
|
import * as fs from "node:fs";
|
|
7
7
|
import { inspect } from "node:util";
|
|
8
|
+
import { pathToFileURL } from "node:url";
|
|
8
9
|
import * as zlib from "node:zlib";
|
|
9
10
|
import { fork } from "node:child_process";
|
|
10
|
-
|
|
11
11
|
//#region src/server/utils.ts
|
|
12
12
|
const DEV_SERVER_URL = "/~dev-server";
|
|
13
13
|
const DEV_MODULE_URL = "/~dev-module";
|
|
@@ -22,6 +22,13 @@ const DEFAULT_HEADERS = {
|
|
|
22
22
|
"access-control-allow-origin": "*",
|
|
23
23
|
"access-control-expose-headers": "*"
|
|
24
24
|
};
|
|
25
|
+
/**
|
|
26
|
+
* Build response headers with optional HTTP caching.
|
|
27
|
+
*
|
|
28
|
+
* @param headers - custom headers to merge with defaults
|
|
29
|
+
* @param httpCache - whether to enable HTTP caching
|
|
30
|
+
* @returns the combined response headers
|
|
31
|
+
*/
|
|
25
32
|
function responseHeaders(headers, httpCache = false) {
|
|
26
33
|
const result = {
|
|
27
34
|
...DEFAULT_HEADERS,
|
|
@@ -34,6 +41,16 @@ function responseHeaders(headers, httpCache = false) {
|
|
|
34
41
|
}
|
|
35
42
|
return result;
|
|
36
43
|
}
|
|
44
|
+
/**
|
|
45
|
+
* Build a browser URL from components.
|
|
46
|
+
*
|
|
47
|
+
* @param protocol - the URL protocol (http or https)
|
|
48
|
+
* @param address - the server address
|
|
49
|
+
* @param port - the server port
|
|
50
|
+
* @param basePath - the base path
|
|
51
|
+
* @param pathname - the URL pathname
|
|
52
|
+
* @returns the complete browser URL
|
|
53
|
+
*/
|
|
37
54
|
function getBrowserUrl(protocol, address, port, basePath, pathname) {
|
|
38
55
|
address = address === "0.0.0.0" ? "localhost" : address;
|
|
39
56
|
const portSuffix = !port || port === 80 || port === 443 ? "" : ":" + port;
|
|
@@ -43,6 +60,14 @@ function getBrowserUrl(protocol, address, port, basePath, pathname) {
|
|
|
43
60
|
protocol = protocol.replace(/:/g, "");
|
|
44
61
|
return `${protocol}://${address}${portSuffix}${path}`;
|
|
45
62
|
}
|
|
63
|
+
/**
|
|
64
|
+
* Get the URL for the dev server client script.
|
|
65
|
+
*
|
|
66
|
+
* @param devServerConfig - the dev server configuration
|
|
67
|
+
* @param host - optional host override
|
|
68
|
+
* @param protocol - optional protocol override
|
|
69
|
+
* @returns the dev server client URL
|
|
70
|
+
*/
|
|
46
71
|
function getDevServerClientUrl(devServerConfig, host, protocol) {
|
|
47
72
|
let address = devServerConfig.address;
|
|
48
73
|
let port = devServerConfig.port;
|
|
@@ -86,16 +111,34 @@ const CONTENT_TYPES = {
|
|
|
86
111
|
ts: "text/typescript",
|
|
87
112
|
tsx: "text/typescript-jsx"
|
|
88
113
|
};
|
|
114
|
+
/**
|
|
115
|
+
* Get the content type for a file based on its extension.
|
|
116
|
+
*
|
|
117
|
+
* @param filePath - the file path to check
|
|
118
|
+
* @returns the MIME content type
|
|
119
|
+
*/
|
|
89
120
|
function getContentType(filePath) {
|
|
90
121
|
const last = filePath.replace(/^.*[/\\]/, "").toLowerCase();
|
|
91
122
|
const ext = last.replace(/^.*\./, "").toLowerCase();
|
|
92
123
|
const hasPath = last.length < filePath.length;
|
|
93
124
|
return (ext.length < last.length - 1 || !hasPath) && CONTENT_TYPES[ext] || "application/octet-stream";
|
|
94
125
|
}
|
|
126
|
+
/**
|
|
127
|
+
* Check if a file is an HTML file.
|
|
128
|
+
*
|
|
129
|
+
* @param filePath - the file path to check
|
|
130
|
+
* @returns true if the file is HTML
|
|
131
|
+
*/
|
|
95
132
|
function isHtmlFile(filePath) {
|
|
96
133
|
const lower = filePath.toLowerCase().trim();
|
|
97
134
|
return lower.endsWith(".html") || lower.endsWith(".htm");
|
|
98
135
|
}
|
|
136
|
+
/**
|
|
137
|
+
* Check if a file is a CSS file.
|
|
138
|
+
*
|
|
139
|
+
* @param filePath - the file path to check
|
|
140
|
+
* @returns true if the file is CSS
|
|
141
|
+
*/
|
|
99
142
|
function isCssFile(filePath) {
|
|
100
143
|
return filePath.toLowerCase().trim().endsWith(".css");
|
|
101
144
|
}
|
|
@@ -113,18 +156,42 @@ const TXT_EXT = [
|
|
|
113
156
|
"md",
|
|
114
157
|
"txt"
|
|
115
158
|
];
|
|
159
|
+
/**
|
|
160
|
+
* Check if a file is simple text (CSS, HTML, JS, JSON, etc.).
|
|
161
|
+
*
|
|
162
|
+
* @param filePath - the file path to check
|
|
163
|
+
* @returns true if the file is a simple text format
|
|
164
|
+
*/
|
|
116
165
|
function isSimpleText(filePath) {
|
|
117
166
|
const ext = filePath.toLowerCase().trim().split(".").pop();
|
|
118
167
|
return ext ? TXT_EXT.includes(ext) : false;
|
|
119
168
|
}
|
|
169
|
+
/**
|
|
170
|
+
* Check if a pathname has no file extension.
|
|
171
|
+
*
|
|
172
|
+
* @param pathname - the URL pathname to check
|
|
173
|
+
* @returns true if the path has no extension
|
|
174
|
+
*/
|
|
120
175
|
function isExtensionLessPath(pathname) {
|
|
121
176
|
const parts = pathname.split("/");
|
|
122
177
|
return !parts[parts.length - 1].includes(".");
|
|
123
178
|
}
|
|
179
|
+
/**
|
|
180
|
+
* Check if a pathname is for SSR static data (page.state.json).
|
|
181
|
+
*
|
|
182
|
+
* @param pathname - the URL pathname to check
|
|
183
|
+
* @returns true if the path is for SSR static data
|
|
184
|
+
*/
|
|
124
185
|
function isSsrStaticDataPath(pathname) {
|
|
125
186
|
const parts = pathname.split("/");
|
|
126
187
|
return parts[parts.length - 1].split("?")[0] === "page.state.json";
|
|
127
188
|
}
|
|
189
|
+
/**
|
|
190
|
+
* Extract SSR static data path information from an HTTP request.
|
|
191
|
+
*
|
|
192
|
+
* @param req - the HTTP request object
|
|
193
|
+
* @returns an object containing ssrPath, fileName, and hasQueryString
|
|
194
|
+
*/
|
|
128
195
|
function getSsrStaticDataPath(req) {
|
|
129
196
|
const parts = req.url.href.split("/");
|
|
130
197
|
const fileNameParts = parts[parts.length - 1].split("?");
|
|
@@ -139,21 +206,58 @@ function getSsrStaticDataPath(req) {
|
|
|
139
206
|
hasQueryString: typeof fileNameParts[1] === "string" && fileNameParts[1].length > 0
|
|
140
207
|
};
|
|
141
208
|
}
|
|
209
|
+
/**
|
|
210
|
+
* Check if a pathname is for the dev client.
|
|
211
|
+
*
|
|
212
|
+
* @param pathname - the URL pathname to check
|
|
213
|
+
* @returns true if the path is for the dev client
|
|
214
|
+
*/
|
|
142
215
|
function isDevClient(pathname) {
|
|
143
216
|
return pathname.startsWith(DEV_SERVER_URL);
|
|
144
217
|
}
|
|
218
|
+
/**
|
|
219
|
+
* Check if a pathname is for a dev module.
|
|
220
|
+
*
|
|
221
|
+
* @param pathname - the URL pathname to check
|
|
222
|
+
* @returns true if the path is for a dev module
|
|
223
|
+
*/
|
|
145
224
|
function isDevModule(pathname) {
|
|
146
225
|
return pathname.includes(DEV_MODULE_URL);
|
|
147
226
|
}
|
|
227
|
+
/**
|
|
228
|
+
* Check if a pathname is for the open-in-editor endpoint.
|
|
229
|
+
*
|
|
230
|
+
* @param pathname - the URL pathname to check
|
|
231
|
+
* @returns true if the path is for opening in editor
|
|
232
|
+
*/
|
|
148
233
|
function isOpenInEditor(pathname) {
|
|
149
234
|
return pathname === OPEN_IN_EDITOR_URL;
|
|
150
235
|
}
|
|
236
|
+
/**
|
|
237
|
+
* Check if a pathname is for the initial dev server load.
|
|
238
|
+
*
|
|
239
|
+
* @param pathname - the URL pathname to check
|
|
240
|
+
* @returns true if the path is for initial dev server load
|
|
241
|
+
*/
|
|
151
242
|
function isInitialDevServerLoad(pathname) {
|
|
152
243
|
return pathname === DEV_SERVER_INIT_URL;
|
|
153
244
|
}
|
|
245
|
+
/**
|
|
246
|
+
* Check if a pathname is for the dev server client script.
|
|
247
|
+
*
|
|
248
|
+
* @param pathname - the URL pathname to check
|
|
249
|
+
* @returns true if the path is for the dev server client
|
|
250
|
+
*/
|
|
154
251
|
function isDevServerClient(pathname) {
|
|
155
252
|
return pathname === DEV_SERVER_URL;
|
|
156
253
|
}
|
|
254
|
+
/**
|
|
255
|
+
* Check if a response should be gzip compressed.
|
|
256
|
+
*
|
|
257
|
+
* @param devServerConfig - the dev server configuration
|
|
258
|
+
* @param req - the HTTP request object
|
|
259
|
+
* @returns true if the response should be compressed
|
|
260
|
+
*/
|
|
157
261
|
function shouldCompress(devServerConfig, req) {
|
|
158
262
|
if (!devServerConfig.gzip) return false;
|
|
159
263
|
if (req.method !== "GET") return false;
|
|
@@ -163,6 +267,9 @@ function shouldCompress(devServerConfig, req) {
|
|
|
163
267
|
}
|
|
164
268
|
/**
|
|
165
269
|
* Normalize a file path to use forward slashes and remove redundant slashes.
|
|
270
|
+
*
|
|
271
|
+
* @param path - the file path to normalize
|
|
272
|
+
* @returns the normalized path
|
|
166
273
|
*/
|
|
167
274
|
function normalizePath(path) {
|
|
168
275
|
let normalized = path.replace(/\\/g, "/");
|
|
@@ -170,7 +277,6 @@ function normalizePath(path) {
|
|
|
170
277
|
if (path.startsWith("\\\\")) normalized = "/" + normalized;
|
|
171
278
|
return normalized;
|
|
172
279
|
}
|
|
173
|
-
|
|
174
280
|
//#endregion
|
|
175
281
|
//#region src/server/context.ts
|
|
176
282
|
/**
|
|
@@ -277,9 +383,12 @@ function createServerContext(sys, sendMsg, devServerConfig, buildResultsResolves
|
|
|
277
383
|
};
|
|
278
384
|
return serverCtx;
|
|
279
385
|
}
|
|
280
|
-
|
|
281
386
|
//#endregion
|
|
282
387
|
//#region src/server/editor.ts
|
|
388
|
+
/**
|
|
389
|
+
* Editor integration using launch-editor.
|
|
390
|
+
* Consolidated from open-in-browser.ts, open-in-editor.ts, and open-in-editor-api.ts.
|
|
391
|
+
*/
|
|
283
392
|
async function openInBrowser(opts) {
|
|
284
393
|
const { default: open } = await import("open");
|
|
285
394
|
await open(opts.url);
|
|
@@ -291,7 +400,7 @@ async function loadLaunchEditor() {
|
|
|
291
400
|
try {
|
|
292
401
|
const mod = await import("launch-editor");
|
|
293
402
|
launchEditor = mod.default || mod;
|
|
294
|
-
} catch
|
|
403
|
+
} catch {
|
|
295
404
|
console.warn("launch-editor package is not available. Open in editor functionality will be disabled.");
|
|
296
405
|
launchEditor = null;
|
|
297
406
|
}
|
|
@@ -400,7 +509,120 @@ function getEditors() {
|
|
|
400
509
|
}
|
|
401
510
|
]);
|
|
402
511
|
}
|
|
403
|
-
|
|
512
|
+
//#endregion
|
|
513
|
+
//#region src/server/dev-preview.ts
|
|
514
|
+
/**
|
|
515
|
+
* Generate a virtual HTML page for the dev server when no index.html is present.
|
|
516
|
+
*
|
|
517
|
+
* Renders all discovered components, including CSS-only components. For each component, usage markdown files
|
|
518
|
+
* (src/components/my-cmp/usage/*.md) are scanned for ```html``` code blocks, which
|
|
519
|
+
* are used as preview snippets. Falls back to a bare tag if none are found.
|
|
520
|
+
* @param buildResults The compiler build results containing component metadata and output file information.
|
|
521
|
+
* @param filterDirPath Optional directory path to filter components by (e.g. when visiting /src/my-component/).
|
|
522
|
+
* @returns A string of HTML to be served as the dev preview page.
|
|
523
|
+
*/
|
|
524
|
+
const generateDevPreview = (buildResults, filterDirPath) => {
|
|
525
|
+
const { namespace } = buildResults;
|
|
526
|
+
let components = [...buildResults.components, ...buildResults.cssOnlyComponents ?? []];
|
|
527
|
+
if (filterDirPath) components = components.filter((c) => isComponentInDir(c, filterDirPath));
|
|
528
|
+
const title = filterDirPath ? `${namespace} / ${path.basename(filterDirPath)}` : namespace;
|
|
529
|
+
const loaderUrl = getLoaderUrl(buildResults);
|
|
530
|
+
const globalCssUrls = getGlobalCssUrls(buildResults);
|
|
531
|
+
const sections = components.length > 0 ? components.map((c) => renderComponentSection(c)) : [` <p style="color:color-mix(in oklab,CanvasText 50%,Canvas 50%)">No Stencil components found in this directory.</p>`];
|
|
532
|
+
return `<!DOCTYPE html>
|
|
533
|
+
<html lang="en">
|
|
534
|
+
<head>
|
|
535
|
+
<meta charset="UTF-8">
|
|
536
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
537
|
+
<title>${title} — Stencil Dev</title>
|
|
538
|
+
<style>
|
|
539
|
+
*, *::before, *::after { box-sizing: border-box; }
|
|
540
|
+
body { font-family: system-ui, sans-serif; margin: 0; padding: 2rem; }
|
|
541
|
+
h1 { font-size: 1rem; font-weight: 500; margin: 0 0 2rem; color: color-mix(in oklab, CanvasText 90%, Canvas 10%); }
|
|
542
|
+
.component { border: 1px solid color-mix(in oklab, CanvasText 20%, Canvas 80%); border-radius: 6px; margin-bottom: 1.5rem; overflow: hidden; }
|
|
543
|
+
.component-header { padding: 0.5rem 1rem; background: color-mix(in oklab, CanvasText 5%, Canvas 95%); font-family: monospace; font-size: 0.875rem; }
|
|
544
|
+
.component-description { margin: 0; padding: 0.75rem 1rem 0; font-size: 0.875rem; color: color-mix(in oklab, CanvasText 70%, Canvas 30%); }
|
|
545
|
+
.component-preview { padding: 1.5rem; }
|
|
546
|
+
.component-preview + .component-preview { border-top: 1px dashed color-mix(in oklab, CanvasText 20%, Canvas 80%); }
|
|
547
|
+
.preview-note { margin: 0.75rem 0 0; font-size: 0.8125rem; color: color-mix(in oklab, CanvasText 50%, Canvas 50%); }
|
|
548
|
+
.preview-note code { font-size: 0.8125rem; }
|
|
549
|
+
</style>
|
|
550
|
+
${[loaderUrl ? ` <script type="module" src="${loaderUrl}"><\/script>` : "", ...globalCssUrls.map((url) => ` <link rel="stylesheet" href="${url}">`)].filter(Boolean).join("\n")}
|
|
551
|
+
</head>
|
|
552
|
+
<body>
|
|
553
|
+
<h1>${title}</h1>
|
|
554
|
+
${sections.join("\n")}
|
|
555
|
+
</body>
|
|
556
|
+
</html>`;
|
|
557
|
+
};
|
|
558
|
+
/**
|
|
559
|
+
* Whether a component's source file lives directly in the given directory.
|
|
560
|
+
* @param component The component metadata.
|
|
561
|
+
* @param dirPath The directory path to check against.
|
|
562
|
+
* @returns true if the component's source file is in `dirPath`.
|
|
563
|
+
*/
|
|
564
|
+
const isComponentInDir = (component, dirPath) => path.normalize(path.dirname(component.sourceFilePath)) === path.normalize(dirPath);
|
|
565
|
+
const renderComponentSection = (component) => {
|
|
566
|
+
const snippets = getUsageSnippets(component);
|
|
567
|
+
const previews = snippets.length > 0 ? snippets.map((html) => ` <div class="component-preview">\n ${html}\n </div>`).join("\n") : ` <div class="component-preview">
|
|
568
|
+
<${component.tagName}></${component.tagName}>
|
|
569
|
+
<p class="preview-note">No demos found - add usage examples to <code>usage/*.md</code> (fenced ```html``` blocks) to customize this preview.</p>
|
|
570
|
+
</div>`;
|
|
571
|
+
const description = component.docs.text.trim() ? `\n <p class="component-description">${escapeHtml(component.docs.text.trim())}</p>` : "";
|
|
572
|
+
return ` <div class="component">
|
|
573
|
+
<div class="component-header"><${component.tagName}></div>${description}
|
|
574
|
+
${previews}
|
|
575
|
+
</div>`;
|
|
576
|
+
};
|
|
577
|
+
const escapeHtml = (unsafe) => unsafe.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
578
|
+
const getUsageSnippets = (component) => {
|
|
579
|
+
const usageDir = path.join(path.dirname(component.sourceFilePath), "usage");
|
|
580
|
+
try {
|
|
581
|
+
const files = fs.readdirSync(usageDir).filter((f) => f.toLowerCase().endsWith(".md"));
|
|
582
|
+
const snippets = [];
|
|
583
|
+
for (const file of files.sort()) {
|
|
584
|
+
const content = fs.readFileSync(path.join(usageDir, file), "utf-8");
|
|
585
|
+
for (const match of content.matchAll(/```html\n([\s\S]*?)```/g)) snippets.push(match[1].trim());
|
|
586
|
+
}
|
|
587
|
+
return snippets;
|
|
588
|
+
} catch {
|
|
589
|
+
return [];
|
|
590
|
+
}
|
|
591
|
+
};
|
|
592
|
+
/**
|
|
593
|
+
* Convert an absolute output file path to a server-relative URL.
|
|
594
|
+
* @param absPath The absolute file path.
|
|
595
|
+
* @param rootDir The root directory to which the path should be relative.
|
|
596
|
+
* @returns A server-relative URL.
|
|
597
|
+
*/
|
|
598
|
+
const toServePath = (absPath, rootDir) => "/" + path.relative(rootDir, absPath).split(path.sep).join("/");
|
|
599
|
+
/**
|
|
600
|
+
* Derive the loader script URL from build outputs.
|
|
601
|
+
* Prefers loader-bundle (always built in dev); falls back to standalone auto-loader if present.
|
|
602
|
+
* @param buildResults The compiler build results containing output file information.
|
|
603
|
+
* @returns A server-relative URL to a loader script, or null if not found.
|
|
604
|
+
*/
|
|
605
|
+
const getLoaderUrl = ({ outputs, fsNamespace, rootDir }) => {
|
|
606
|
+
const distLazy = outputs.find((o) => o.type === "dist-lazy");
|
|
607
|
+
if (distLazy) {
|
|
608
|
+
const file = distLazy.files.find((f) => f.endsWith(`/${fsNamespace}.js`));
|
|
609
|
+
if (file) return toServePath(file, rootDir);
|
|
610
|
+
}
|
|
611
|
+
const standalone = outputs.find((o) => o.type === "standalone");
|
|
612
|
+
if (standalone) {
|
|
613
|
+
const file = standalone.files.find((f) => /\/loader\.js$/.test(f));
|
|
614
|
+
if (file) return toServePath(file, rootDir);
|
|
615
|
+
}
|
|
616
|
+
return null;
|
|
617
|
+
};
|
|
618
|
+
/**
|
|
619
|
+
* Collect server-relative URLs for all global-style CSS outputs, in the same order their
|
|
620
|
+
* output targets are declared in config - cascade order is meaningful when more than one
|
|
621
|
+
* `global-style` output target is configured.
|
|
622
|
+
* @param buildResults The compiler build results containing output file information.
|
|
623
|
+
* @returns An array of server-relative URLs to global-style CSS files.
|
|
624
|
+
*/
|
|
625
|
+
const getGlobalCssUrls = ({ globalStyleFiles, rootDir }) => globalStyleFiles.map((f) => toServePath(f, rootDir));
|
|
404
626
|
//#endregion
|
|
405
627
|
//#region src/server/ssr.ts
|
|
406
628
|
/**
|
|
@@ -411,10 +633,10 @@ async function ssrPageRequest(devServerConfig, serverCtx, req, res) {
|
|
|
411
633
|
try {
|
|
412
634
|
let status = 500;
|
|
413
635
|
let content = "";
|
|
414
|
-
const {
|
|
636
|
+
const { ssrApp, srcIndexHtml, diagnostics } = await setupHydrateApp(devServerConfig, serverCtx);
|
|
415
637
|
if (!diagnostics.some((diagnostic) => diagnostic.level === "error")) try {
|
|
416
638
|
const opts = getSsrHydrateOptions(devServerConfig, serverCtx, req.url);
|
|
417
|
-
const ssrResults = await
|
|
639
|
+
const ssrResults = await ssrApp.renderToString(srcIndexHtml, opts);
|
|
418
640
|
diagnostics.push(...ssrResults.diagnostics);
|
|
419
641
|
status = ssrResults.httpStatus ?? 500;
|
|
420
642
|
content = ssrResults.html ?? "";
|
|
@@ -441,11 +663,11 @@ async function ssrStaticDataRequest(devServerConfig, serverCtx, req, res) {
|
|
|
441
663
|
try {
|
|
442
664
|
const data = {};
|
|
443
665
|
let httpCache = false;
|
|
444
|
-
const {
|
|
666
|
+
const { ssrApp, srcIndexHtml, diagnostics } = await setupHydrateApp(devServerConfig, serverCtx);
|
|
445
667
|
if (!diagnostics.some((diagnostic) => diagnostic.level === "error")) try {
|
|
446
668
|
const { ssrPath, hasQueryString } = getSsrStaticDataPath(req);
|
|
447
669
|
const opts = getSsrHydrateOptions(devServerConfig, serverCtx, new URL(ssrPath, req.url));
|
|
448
|
-
const ssrResults = await
|
|
670
|
+
const ssrResults = await ssrApp.renderToString(srcIndexHtml, opts);
|
|
449
671
|
diagnostics.push(...ssrResults.diagnostics);
|
|
450
672
|
ssrResults.staticData.forEach((s) => {
|
|
451
673
|
if (s.type === "application/json") data[s.id] = JSON.parse(s.content);
|
|
@@ -472,18 +694,18 @@ async function ssrStaticDataRequest(devServerConfig, serverCtx, req, res) {
|
|
|
472
694
|
}
|
|
473
695
|
async function setupHydrateApp(devServerConfig, serverCtx) {
|
|
474
696
|
let srcIndexHtml = null;
|
|
475
|
-
let
|
|
697
|
+
let ssrApp = null;
|
|
476
698
|
const buildResults = await serverCtx.getBuildResults();
|
|
477
699
|
const diagnostics = [];
|
|
478
700
|
if (serverCtx.prerenderConfig == null && isString(devServerConfig.prerenderConfig)) try {
|
|
479
|
-
const prerenderConfigResults = (await import("@stencil/core/compiler")).nodeRequire(devServerConfig.prerenderConfig);
|
|
701
|
+
const prerenderConfigResults = await (await import("@stencil/core/compiler")).nodeRequire(devServerConfig.prerenderConfig);
|
|
480
702
|
diagnostics.push(...prerenderConfigResults.diagnostics);
|
|
481
703
|
if (prerenderConfigResults.module?.config) serverCtx.prerenderConfig = prerenderConfigResults.module.config;
|
|
482
704
|
} catch (e) {
|
|
483
705
|
catchError(diagnostics, e);
|
|
484
706
|
}
|
|
485
|
-
if (!isString(buildResults.
|
|
486
|
-
messageText: "Missing
|
|
707
|
+
if (!isString(buildResults.ssrAppFilePath)) diagnostics.push({
|
|
708
|
+
messageText: "Missing ssrAppFilePath",
|
|
487
709
|
level: "error",
|
|
488
710
|
type: "ssr",
|
|
489
711
|
lines: []
|
|
@@ -503,17 +725,19 @@ async function setupHydrateApp(devServerConfig, serverCtx) {
|
|
|
503
725
|
type: "ssr"
|
|
504
726
|
});
|
|
505
727
|
else {
|
|
506
|
-
const
|
|
728
|
+
const ssrAppFilePath = path.resolve(buildResults.ssrAppFilePath);
|
|
507
729
|
try {
|
|
508
|
-
const
|
|
509
|
-
|
|
730
|
+
const hydrateUrl = pathToFileURL(ssrAppFilePath);
|
|
731
|
+
hydrateUrl.search = `?t=${Date.now()}`;
|
|
732
|
+
const hydrateModule = await import(hydrateUrl.href);
|
|
733
|
+
ssrApp = hydrateModule.default || hydrateModule;
|
|
510
734
|
} catch (e) {
|
|
511
735
|
catchError(diagnostics, e);
|
|
512
736
|
}
|
|
513
737
|
}
|
|
514
738
|
}
|
|
515
739
|
return {
|
|
516
|
-
|
|
740
|
+
ssrApp,
|
|
517
741
|
srcIndexHtml,
|
|
518
742
|
diagnostics
|
|
519
743
|
};
|
|
@@ -533,14 +757,14 @@ function getSsrHydrateOptions(devServerConfig, serverCtx, url) {
|
|
|
533
757
|
prettyHtml: true
|
|
534
758
|
};
|
|
535
759
|
const prerenderConfig = serverCtx?.prerenderConfig;
|
|
536
|
-
if (isFunction(prerenderConfig?.
|
|
537
|
-
const userOpts = prerenderConfig.
|
|
760
|
+
if (isFunction(prerenderConfig?.prerenderOptions)) {
|
|
761
|
+
const userOpts = prerenderConfig.prerenderOptions(url);
|
|
538
762
|
if (userOpts) Object.assign(opts, userOpts);
|
|
539
763
|
}
|
|
540
764
|
if (isFunction(serverCtx.sys.applyPrerenderGlobalPatch)) {
|
|
541
|
-
const orgBeforeHydrate = opts.
|
|
765
|
+
const orgBeforeHydrate = opts.beforeSsr;
|
|
542
766
|
const applyPatch = serverCtx.sys.applyPrerenderGlobalPatch;
|
|
543
|
-
opts.
|
|
767
|
+
opts.beforeSsr = (document) => {
|
|
544
768
|
const devServerHostUrl = new URL(devServerConfig.browserUrl).origin;
|
|
545
769
|
applyPatch({
|
|
546
770
|
devServerHostUrl,
|
|
@@ -591,7 +815,6 @@ function isString(val) {
|
|
|
591
815
|
function isFunction(val) {
|
|
592
816
|
return typeof val === "function";
|
|
593
817
|
}
|
|
594
|
-
|
|
595
818
|
//#endregion
|
|
596
819
|
//#region src/server/handlers.ts
|
|
597
820
|
/**
|
|
@@ -606,7 +829,7 @@ function createRequestHandler(devServerConfig, serverCtx) {
|
|
|
606
829
|
if (!userHandlerLoaded && typeof devServerConfig.requestListenerPath === "string") {
|
|
607
830
|
userHandlerLoaded = true;
|
|
608
831
|
try {
|
|
609
|
-
const userModule = await import(devServerConfig.requestListenerPath);
|
|
832
|
+
const userModule = await import(pathToFileURL(devServerConfig.requestListenerPath).href);
|
|
610
833
|
userRequestHandler = userModule.default || userModule;
|
|
611
834
|
} catch (e) {
|
|
612
835
|
console.error("Failed to load user request handler:", e);
|
|
@@ -762,11 +985,14 @@ function updateStyleUrls(url, oldCss) {
|
|
|
762
985
|
return newCss;
|
|
763
986
|
}
|
|
764
987
|
function appendDevServerClientScript(devServerConfig, req, content) {
|
|
765
|
-
|
|
988
|
+
const devServerClientUrl = getDevServerClientUrl(devServerConfig, req.headers?.["x-forwarded-host"] ?? req.host, req.headers?.["x-forwarded-proto"]);
|
|
989
|
+
return appendDevServerClientIframe(content, `<iframe title="Stencil Dev Server Connector ${VERSION} ⚡" src="${devServerClientUrl}" style="display:block;width:0;height:0;border:0;visibility:hidden" aria-hidden="true"></iframe>`);
|
|
766
990
|
}
|
|
767
991
|
function appendDevServerClientIframe(content, iframe) {
|
|
768
|
-
|
|
769
|
-
if (
|
|
992
|
+
const bodyIndex = content.lastIndexOf("</body>");
|
|
993
|
+
if (bodyIndex !== -1) return content.slice(0, bodyIndex) + iframe + content.slice(bodyIndex);
|
|
994
|
+
const htmlIndex = content.lastIndexOf("</html>");
|
|
995
|
+
if (htmlIndex !== -1) return content.slice(0, htmlIndex) + iframe + content.slice(htmlIndex);
|
|
770
996
|
return `${content}${iframe}`;
|
|
771
997
|
}
|
|
772
998
|
async function serveDevClient(devServerConfig, serverCtx, req, res) {
|
|
@@ -775,7 +1001,7 @@ async function serveDevClient(devServerConfig, serverCtx, req, res) {
|
|
|
775
1001
|
if (isDevServerClient(req.pathname)) return serveDevClientScript(devServerConfig, serverCtx, req, res);
|
|
776
1002
|
if (isInitialDevServerLoad(req.pathname)) req.filePath = path.join(devServerConfig.devServerDir, "templates", "initial-load.html");
|
|
777
1003
|
else {
|
|
778
|
-
const subPath = req.pathname.replace(
|
|
1004
|
+
const subPath = req.pathname.replace("/~dev-server/", "");
|
|
779
1005
|
if (subPath.startsWith("client/")) req.filePath = path.join(devServerConfig.devServerDir, subPath);
|
|
780
1006
|
else req.filePath = path.join(devServerConfig.devServerDir, "static", subPath);
|
|
781
1007
|
}
|
|
@@ -839,6 +1065,13 @@ async function serveDirectoryIndex(devServerConfig, serverCtx, req, res) {
|
|
|
839
1065
|
if (!req.pathname.endsWith("/")) return serverCtx.serve302(req, res, req.pathname + "/");
|
|
840
1066
|
try {
|
|
841
1067
|
const dirFilePaths = await serverCtx.sys.readDir(req.filePath);
|
|
1068
|
+
if ((dirFilePaths.some((f) => f.endsWith(".tsx")) || await hasCssOnlyComponent(serverCtx, dirFilePaths, req.filePath)) && !await hasNestedHtmlFile(serverCtx.sys, dirFilePaths)) return serveDevPreview(devServerConfig, serverCtx, req, res, req.filePath);
|
|
1069
|
+
if (req.pathname === "/" || req.pathname === devServerConfig.basePath) {
|
|
1070
|
+
const srcPath = path.join(req.filePath, "src");
|
|
1071
|
+
try {
|
|
1072
|
+
if ((await serverCtx.sys.stat(srcPath)).isDirectory) return serverCtx.serve302(req, res, "/src/");
|
|
1073
|
+
} catch {}
|
|
1074
|
+
}
|
|
842
1075
|
try {
|
|
843
1076
|
if (serverCtx.dirTemplate == null) {
|
|
844
1077
|
const dirTemplatePath = path.join(devServerConfig.devServerDir, "templates", "directory-index.html");
|
|
@@ -860,6 +1093,53 @@ async function serveDirectoryIndex(devServerConfig, serverCtx, req, res) {
|
|
|
860
1093
|
return serverCtx.serve404(req, res, "serveDirectoryIndex");
|
|
861
1094
|
}
|
|
862
1095
|
}
|
|
1096
|
+
const STYLE_FILE_RE = /\.(css|scss|sass|less|styl|stylus|pcss)$/i;
|
|
1097
|
+
/**
|
|
1098
|
+
* Checks whether a directory directly contains a CSS-only component's source file. Only asks the
|
|
1099
|
+
* compiler for build results when the directory has a style file, to keep plain listings cheap.
|
|
1100
|
+
* @param serverCtx The dev server context, used to fetch the latest build results.
|
|
1101
|
+
* @param dirFilePaths The full paths of entries in the directory to check.
|
|
1102
|
+
* @param dirPath The directory being served.
|
|
1103
|
+
* @returns true if a CSS-only component is defined in this directory.
|
|
1104
|
+
*/
|
|
1105
|
+
async function hasCssOnlyComponent(serverCtx, dirFilePaths, dirPath) {
|
|
1106
|
+
if (!dirFilePaths.some((f) => STYLE_FILE_RE.test(f))) return false;
|
|
1107
|
+
const { cssOnlyComponents = [] } = await serverCtx.getBuildResults();
|
|
1108
|
+
return cssOnlyComponents.some((c) => isComponentInDir(c, dirPath));
|
|
1109
|
+
}
|
|
1110
|
+
/**
|
|
1111
|
+
* Recursively checks a directory (and its subdirectories) for any .html/.htm file.
|
|
1112
|
+
* Used to decide whether the auto-generated component preview should be shown, or
|
|
1113
|
+
* the default file-listing view (since a nested html file likely means a custom
|
|
1114
|
+
* preview/demo page already exists somewhere in the tree).
|
|
1115
|
+
* @param sys The dev server's compiler system, used to read directories and stat files.
|
|
1116
|
+
* @param dirFilePaths The full paths of entries in the directory to check.
|
|
1117
|
+
* @returns true if an html file exists at this level or in any subdirectory.
|
|
1118
|
+
*/
|
|
1119
|
+
async function hasNestedHtmlFile(sys, dirFilePaths) {
|
|
1120
|
+
const subDirPaths = [];
|
|
1121
|
+
for (const filePath of dirFilePaths) {
|
|
1122
|
+
if (filePath.endsWith(".html") || filePath.endsWith(".htm")) return true;
|
|
1123
|
+
if ((await sys.stat(filePath)).isDirectory) subDirPaths.push(filePath);
|
|
1124
|
+
}
|
|
1125
|
+
for (const subDirPath of subDirPaths) if (await hasNestedHtmlFile(sys, await sys.readDir(subDirPath))) return true;
|
|
1126
|
+
return false;
|
|
1127
|
+
}
|
|
1128
|
+
async function serveDevPreview(devServerConfig, serverCtx, req, res, filterDirPath) {
|
|
1129
|
+
try {
|
|
1130
|
+
const buildResults = await serverCtx.getBuildResults();
|
|
1131
|
+
const html = appendDevServerClientScript(devServerConfig, req, generateDevPreview(buildResults, filterDirPath));
|
|
1132
|
+
const buf = Buffer.from(html, "utf-8");
|
|
1133
|
+
serverCtx.logRequest(req, 200);
|
|
1134
|
+
res.writeHead(200, responseHeaders({
|
|
1135
|
+
"content-type": "text/html;charset=utf-8",
|
|
1136
|
+
"content-length": buf.byteLength
|
|
1137
|
+
}));
|
|
1138
|
+
res.end(buf);
|
|
1139
|
+
} catch (e) {
|
|
1140
|
+
serverCtx.serve500(req, res, e, "serveDevPreview");
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
863
1143
|
async function getDirectoryFiles(sys, baseUrl, dirItemNames) {
|
|
864
1144
|
const items = await getDirectoryItems(sys, baseUrl, dirItemNames);
|
|
865
1145
|
if (baseUrl.pathname !== "/") items.unshift({
|
|
@@ -898,7 +1178,6 @@ function getDirectoryNav(pathName) {
|
|
|
898
1178
|
return `<a href="${url}">${index === 0 ? "~" : dir}</a>`;
|
|
899
1179
|
}).join("<span>/</span>") + "<span>/</span>";
|
|
900
1180
|
}
|
|
901
|
-
|
|
902
1181
|
//#endregion
|
|
903
1182
|
//#region src/server/server.ts
|
|
904
1183
|
/**
|
|
@@ -1056,7 +1335,6 @@ function initServerProcess(sendMsg) {
|
|
|
1056
1335
|
};
|
|
1057
1336
|
return receiveMessageFromMain;
|
|
1058
1337
|
}
|
|
1059
|
-
|
|
1060
1338
|
//#endregion
|
|
1061
1339
|
//#region src/server/worker-main.ts
|
|
1062
1340
|
/**
|
|
@@ -1071,7 +1349,8 @@ function initServerProcess(sendMsg) {
|
|
|
1071
1349
|
* @returns Function to send messages from main to worker process
|
|
1072
1350
|
*/
|
|
1073
1351
|
function initServerProcessWorkerProxy(sendToMain) {
|
|
1074
|
-
|
|
1352
|
+
const workerPath = path.join(import.meta.dirname, "worker-thread.js");
|
|
1353
|
+
const forkOpts = {
|
|
1075
1354
|
execArgv: process.execArgv.filter((v) => !/^--(debug|inspect)/.test(v)),
|
|
1076
1355
|
env: process.env,
|
|
1077
1356
|
cwd: process.cwd(),
|
|
@@ -1081,9 +1360,12 @@ function initServerProcessWorkerProxy(sendToMain) {
|
|
|
1081
1360
|
"pipe",
|
|
1082
1361
|
"ipc"
|
|
1083
1362
|
]
|
|
1084
|
-
}
|
|
1363
|
+
};
|
|
1364
|
+
let serverProcess = fork(workerPath, [], forkOpts);
|
|
1085
1365
|
/**
|
|
1086
1366
|
* Send a message from main to the worker process
|
|
1367
|
+
*
|
|
1368
|
+
* @param msg - the message to send to the worker
|
|
1087
1369
|
*/
|
|
1088
1370
|
const receiveFromMain = (msg) => {
|
|
1089
1371
|
if (serverProcess && serverProcess.connected) serverProcess.send(msg);
|
|
@@ -1126,15 +1408,15 @@ function initServerProcessWorkerProxy(sendToMain) {
|
|
|
1126
1408
|
});
|
|
1127
1409
|
return receiveFromMain;
|
|
1128
1410
|
}
|
|
1129
|
-
|
|
1130
1411
|
//#endregion
|
|
1131
1412
|
//#region src/server/index.ts
|
|
1132
1413
|
/**
|
|
1133
|
-
*
|
|
1414
|
+
* Stencil Dev Server
|
|
1134
1415
|
*
|
|
1135
1416
|
* A modern development server for Stencil with DOM-based HMR.
|
|
1136
1417
|
* Designed for lazy-loading component architectures where module graphs
|
|
1137
1418
|
* are discovered at runtime from the DOM.
|
|
1419
|
+
* @module @stencil/dev-server
|
|
1138
1420
|
*/
|
|
1139
1421
|
/**
|
|
1140
1422
|
* Start the Stencil development server.
|
|
@@ -1161,6 +1443,16 @@ function start(stencilDevServerConfig, logger, watcher) {
|
|
|
1161
1443
|
}
|
|
1162
1444
|
});
|
|
1163
1445
|
}
|
|
1446
|
+
/**
|
|
1447
|
+
* Internal function to start the dev server.
|
|
1448
|
+
*
|
|
1449
|
+
* @param devServerConfig - configuration for the dev server
|
|
1450
|
+
* @param logger - logger instance for output
|
|
1451
|
+
* @param watcher - optional compiler watcher for build events
|
|
1452
|
+
* @param initServerProcessFn - function to initialize the server process
|
|
1453
|
+
* @param resolve - promise resolve callback
|
|
1454
|
+
* @param reject - promise reject callback
|
|
1455
|
+
*/
|
|
1164
1456
|
function startServer(devServerConfig, logger, watcher, initServerProcessFn, resolve, reject) {
|
|
1165
1457
|
const timespan = logger.createTimeSpan("starting dev server", true);
|
|
1166
1458
|
const startupTimeout = logger.getLevel() !== "debug" || devServerConfig.startupTimeout !== 0 ? setTimeout(() => {
|
|
@@ -1220,27 +1512,33 @@ function startServer(devServerConfig, logger, watcher, initServerProcessFn, reso
|
|
|
1220
1512
|
resolve(devServer);
|
|
1221
1513
|
};
|
|
1222
1514
|
const requestLog = (msg) => {
|
|
1223
|
-
if (devServerConfig.logRequests && msg.requestLog)
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1515
|
+
if (devServerConfig.logRequests && msg.requestLog) {
|
|
1516
|
+
if (msg.requestLog.status >= 500) logger.info(logger.red(`${msg.requestLog.method} ${msg.requestLog.url} (${msg.requestLog.status})`));
|
|
1517
|
+
else if (msg.requestLog.status >= 400) logger.info(logger.dim(logger.red(`${msg.requestLog.method} ${msg.requestLog.url} (${msg.requestLog.status})`)));
|
|
1518
|
+
else if (msg.requestLog.status >= 300) logger.info(logger.dim(logger.magenta(`${msg.requestLog.method} ${msg.requestLog.url} (${msg.requestLog.status})`)));
|
|
1519
|
+
else logger.info(logger.dim(`${logger.cyan(msg.requestLog.method)} ${msg.requestLog.url}`));
|
|
1520
|
+
}
|
|
1227
1521
|
};
|
|
1228
1522
|
const serverError = async (msg) => {
|
|
1229
|
-
if (msg.error)
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1523
|
+
if (msg.error) {
|
|
1524
|
+
if (hasStarted) logger.error(msg.error.message + " " + msg.error.stack);
|
|
1525
|
+
else {
|
|
1526
|
+
await close();
|
|
1527
|
+
reject(msg.error.message);
|
|
1528
|
+
}
|
|
1233
1529
|
}
|
|
1234
1530
|
};
|
|
1235
1531
|
const requestBuildResults = () => {
|
|
1236
|
-
if (sendToServer)
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1532
|
+
if (sendToServer) {
|
|
1533
|
+
if (lastBuildResults != null) {
|
|
1534
|
+
const msg = {
|
|
1535
|
+
buildResults: { ...lastBuildResults },
|
|
1536
|
+
isActivelyBuilding
|
|
1537
|
+
};
|
|
1538
|
+
delete msg.buildResults.hmr;
|
|
1539
|
+
sendToServer(msg);
|
|
1540
|
+
} else sendToServer({ isActivelyBuilding: true });
|
|
1541
|
+
}
|
|
1244
1542
|
};
|
|
1245
1543
|
const compilerRequest = async (compilerRequestPath) => {
|
|
1246
1544
|
if (watcher?.request && sendToServer) {
|
|
@@ -1272,6 +1570,5 @@ function startServer(devServerConfig, logger, watcher, initServerProcessFn, reso
|
|
|
1272
1570
|
reject(e);
|
|
1273
1571
|
}
|
|
1274
1572
|
}
|
|
1275
|
-
|
|
1276
1573
|
//#endregion
|
|
1277
|
-
export { initServerProcess, start };
|
|
1574
|
+
export { initServerProcess, start };
|