@stencil/dev-server 5.0.0-alpha.3 → 5.0.0-alpha.31

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 ADDED
@@ -0,0 +1,105 @@
1
+ # @stencil/dev-server
2
+
3
+ Development server for Stencil with DOM-based Hot Module Replacement (HMR).
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install --save-dev @stencil/dev-server @stencil/core
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ The dev server is configured via `stencil.config.ts` and started automatically with `stencil build --dev --watch --serve`.
14
+
15
+ ```ts
16
+ // stencil.config.ts
17
+ import { Config } from '@stencil/core';
18
+
19
+ export const config: Config = {
20
+ devServer: {
21
+ port: 3333,
22
+ openBrowser: true,
23
+ reloadStrategy: 'pageReload', // or 'hmr'
24
+ },
25
+ outputTargets: [{ type: 'www' }],
26
+ };
27
+ ```
28
+
29
+ ```bash
30
+ npx stencil build --dev --watch --serve
31
+ ```
32
+
33
+ ## Programmatic API
34
+
35
+ ### `start(config, logger, watcher?)` — start the dev server
36
+
37
+ ```ts
38
+ import { start } from '@stencil/dev-server';
39
+ import { createNodeLogger } from '@stencil/core/sys/node';
40
+
41
+ const server = await start(
42
+ {
43
+ root: './www', // directory to serve
44
+ port: 3333,
45
+ openBrowser: true,
46
+ reloadStrategy: 'hmr', // 'hmr' | 'pageReload' | null
47
+ },
48
+ createNodeLogger(),
49
+ );
50
+
51
+ console.log(`Listening at ${server.browserUrl}`);
52
+
53
+ // Shut down when done
54
+ await server.close();
55
+ ```
56
+
57
+ ### With a Stencil compiler watcher (full HMR)
58
+
59
+ Pass a `CompilerWatcher` to connect build output to the dev server — file changes trigger HMR or a page reload automatically.
60
+
61
+ ```ts
62
+ import * as coreCompiler from '@stencil/core/compiler';
63
+ import { start } from '@stencil/dev-server';
64
+ import { createNodeLogger, createNodeSys } from '@stencil/core/sys/node';
65
+
66
+ const logger = createNodeLogger();
67
+ const sys = createNodeSys();
68
+
69
+ const { config } = await coreCompiler.loadConfig({
70
+ configPath: './stencil.config.ts',
71
+ logger,
72
+ sys,
73
+ });
74
+
75
+ const compiler = await coreCompiler.createCompiler(config);
76
+ const watcher = await compiler.createWatcher();
77
+
78
+ const server = await start(
79
+ { root: './www', port: 3333, reloadStrategy: 'hmr' },
80
+ logger,
81
+ watcher,
82
+ );
83
+
84
+ // Start watching — builds trigger HMR updates in the browser
85
+ await watcher.start();
86
+
87
+ // To shut down:
88
+ // await watcher.close();
89
+ // await server.close();
90
+ ```
91
+
92
+ The returned `DevServer` exposes `address`, `browserUrl`, `protocol`, `port`, `root`, and `close()`.
93
+
94
+ #### Key config options
95
+
96
+ | Option | Default | Description |
97
+ |---|---|---|
98
+ | `root` | `'.'` | Directory to serve files from |
99
+ | `port` | `3333` | Port to listen on |
100
+ | `address` | `'0.0.0.0'` | Network interface to bind |
101
+ | `reloadStrategy` | `'hmr'` | `'hmr'`, `'pageReload'`, or `null` to disable |
102
+ | `openBrowser` | `false` | Open browser on start |
103
+ | `https` | — | `{ cert, key }` to enable HTTPS |
104
+ | `worker` | `true` | Fork server into a child process (disable for debugging) |
105
+ | `ssr` | `false` | Server-side render each page on request (dev only - you must have a `ssr` output target setup) |
@@ -1,5 +1,4 @@
1
1
  import { CompilerBuildResults, Diagnostic, HmrStyleUpdate, HotModuleReplacement, PrintLine } from "@stencil/core/compiler";
2
-
3
2
  //#region src/client/types.d.ts
4
3
  interface DevClientWindow extends Window {
5
4
  's-dev-server'?: boolean;
@@ -16,7 +16,7 @@ const NORMAL_CLOSURE_CODE = 1e3;
16
16
  const REQUEST_BUILD_RESULTS_INTERVAL_MS = 500;
17
17
  //#endregion
18
18
  //#region src/client/error.css?inline
19
- var error_default = "#dev-server-modal * {\n box-sizing: border-box !important;\n}\n\n#dev-server-modal {\n -webkit-font-smoothing: antialiased;\n text-rendering: optimizelegibility;\n text-size-adjust: none;\n word-wrap: break-word;\n user-select: auto;\n display: block;\n z-index: 99999 !important;\n -webkit-overflow-scrolling: touch !important;\n direction: ltr !important;\n background: #000000a8 !important;\n width: 100% !important;\n height: 100% !important;\n margin: 0 !important;\n padding: 0 !important;\n font-family: -apple-system, Roboto, BlinkMacSystemFont, Segoe UI, Helvetica Neue, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol !important;\n font-size: 14px !important;\n line-height: 1.5 !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n overflow-y: auto !important;\n}\n\n#dev-server-modal-inner {\n color: #333 !important;\n background-color: #fff !important;\n border-radius: 8px !important;\n max-width: 80vw !important;\n margin: 30px auto !important;\n padding: 25px !important;\n position: relative !important;\n box-shadow: 0 10px 40px #00000080 !important;\n}\n\n.dev-server-diagnostic {\n border: 1px solid #ddd !important;\n border-radius: 3px !important;\n margin: 20px !important;\n}\n\n.dev-server-diagnostic-masthead {\n padding: 8px 12px 12px !important;\n}\n\n.dev-server-diagnostic-title {\n color: #222 !important;\n margin: 0 !important;\n font-weight: bold !important;\n}\n\n.dev-server-diagnostic-message {\n color: #555 !important;\n margin-top: 4px !important;\n}\n\n.dev-server-diagnostic-file {\n border-top: 1px solid #ddd !important;\n position: relative !important;\n}\n\n.dev-server-diagnostic-file-header {\n color: #555 !important;\n background-color: #f9f9f9 !important;\n border-bottom: 1px solid #ddd !important;\n border-top-left-radius: 2px !important;\n border-top-right-radius: 2px !important;\n padding: 5px 10px !important;\n font-family: Consolas, Liberation Mono, Menlo, Courier, monospace !important;\n font-size: 12px !important;\n display: block !important;\n}\n\na.dev-server-diagnostic-file-header {\n color: #00e !important;\n text-decoration: underline !important;\n}\n\na.dev-server-diagnostic-file-header:hover {\n background-color: #f4f4f4 !important;\n text-decoration: none !important;\n}\n\n.dev-server-diagnostic-file-name {\n font-weight: bold !important;\n}\n\n.dev-server-diagnostic-blob {\n border-bottom-right-radius: 3px !important;\n border-bottom-left-radius: 3px !important;\n overflow: auto hidden !important;\n}\n\n.dev-server-diagnostic-table {\n -moz-tab-size: 2;\n tab-size: 2;\n border-spacing: 0 !important;\n border-collapse: collapse !important;\n border-style: none !important;\n border-width: 0 !important;\n margin: 0 !important;\n padding: 0 !important;\n}\n\n.dev-server-diagnostic-table td, .dev-server-diagnostic-table th {\n border-style: none !important;\n border-width: 0 !important;\n padding: 0 !important;\n}\n\ntd.dev-server-diagnostic-blob-num {\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n color: #0000004d !important;\n text-align: right !important;\n white-space: nowrap !important;\n vertical-align: top !important;\n border: 0 solid #eee !important;\n border-right-width: 1px !important;\n width: 1% !important;\n min-width: 50px !important;\n padding-left: 10px !important;\n padding-right: 10px !important;\n font-family: Consolas, Liberation Mono, Menlo, Courier, monospace !important;\n font-size: 12px !important;\n line-height: 20px !important;\n}\n\ntd.dev-server-diagnostic-blob-num:before {\n content: attr(data-line-number) !important;\n}\n\n.dev-server-diagnostic-error-line td.dev-server-diagnostic-blob-num {\n background-color: #fdd !important;\n border-color: #ffc9c9 !important;\n}\n\n.dev-server-diagnostic-error-line td.dev-server-diagnostic-blob-code {\n z-index: -1;\n background: #ffdddd40 !important;\n}\n\n.dev-server-diagnostic-open-in-editor td.dev-server-diagnostic-blob-num:hover {\n cursor: pointer;\n font-weight: bold;\n background-color: #ffffe3 !important;\n}\n\n.dev-server-diagnostic-open-in-editor.dev-server-diagnostic-error-line td.dev-server-diagnostic-blob-num:hover {\n background-color: #ffdada !important;\n}\n\ntd.dev-server-diagnostic-blob-code {\n vertical-align: top !important;\n color: #333 !important;\n word-wrap: normal !important;\n white-space: pre !important;\n padding-left: 10px !important;\n padding-right: 10px !important;\n font-family: Consolas, Liberation Mono, Menlo, Courier, monospace !important;\n font-size: 12px !important;\n line-height: 20px !important;\n position: relative !important;\n overflow: visible !important;\n}\n\ntd.dev-server-diagnostic-blob-code:before {\n content: \"\" !important;\n}\n\n.dev-server-diagnostic-error-chr {\n position: relative !important;\n}\n\n.dev-server-diagnostic-error-chr:before {\n z-index: -1;\n content: \"\" !important;\n background-color: #fdd !important;\n width: 8px !important;\n height: 20px !important;\n position: absolute !important;\n top: -3px !important;\n left: 0 !important;\n}\n\n.hljs-comment, .hljs-meta {\n color: #969896;\n}\n\n.hljs-string, .hljs-variable, .hljs-template-variable, .hljs-strong, .hljs-emphasis, .hljs-quote {\n color: #df5000;\n}\n\n.hljs-keyword, .hljs-selector-tag, .hljs-type {\n color: #a71d5d;\n}\n\n.hljs-literal, .hljs-symbol, .hljs-bullet, .hljs-attribute {\n color: #0086b3;\n}\n\n.hljs-section, .hljs-name {\n color: #63a35c;\n}\n\n.hljs-tag {\n color: #333;\n}\n\n.hljs-title, .hljs-attr, .hljs-selector-id, .hljs-selector-class, .hljs-selector-attr, .hljs-selector-pseudo {\n color: #795da3;\n}\n\n.hljs-addition {\n color: #55a532;\n background-color: #eaffea;\n}\n\n.hljs-deletion {\n color: #bd2c00;\n background-color: #ffecec;\n}\n\n.hljs-link {\n text-decoration: underline;\n}\n\n.dev-server-error-badge {\n z-index: 99998 !important;\n color: #fff !important;\n cursor: pointer !important;\n background: #f55 !important;\n border: none !important;\n border-radius: 8px !important;\n align-items: center !important;\n gap: 8px !important;\n padding: 10px 16px !important;\n font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, sans-serif !important;\n font-size: 14px !important;\n font-weight: 600 !important;\n transition: transform .2s, box-shadow .2s !important;\n display: flex !important;\n position: fixed !important;\n bottom: 20px !important;\n left: 20px !important;\n box-shadow: 0 4px 12px #0000004d !important;\n}\n\n.dev-server-error-badge:hover {\n transform: translateY(-2px) !important;\n box-shadow: 0 6px 16px #0006 !important;\n}\n\n.error-badge-icon {\n color: #f55 !important;\n background: #fff !important;\n border-radius: 50% !important;\n justify-content: center !important;\n align-items: center !important;\n width: 20px !important;\n height: 20px !important;\n font-size: 14px !important;\n font-weight: bold !important;\n display: flex !important;\n}\n\n.error-badge-count {\n font-size: 14px !important;\n font-weight: 600 !important;\n}\n";
19
+ var error_default = "#dev-server-modal * {\n box-sizing: border-box !important;\n}\n\n#dev-server-modal {\n -webkit-font-smoothing: antialiased;\n text-rendering: optimizelegibility;\n text-size-adjust: none;\n word-wrap: break-word;\n user-select: auto;\n display: block;\n z-index: 99999 !important;\n -webkit-overflow-scrolling: touch !important;\n direction: ltr !important;\n background: #000000a8 !important;\n width: 100% !important;\n height: 100% !important;\n margin: 0 !important;\n padding: 0 !important;\n font-family: -apple-system, Roboto, BlinkMacSystemFont, Segoe UI, Helvetica Neue, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol !important;\n font-size: 14px !important;\n line-height: 1.5 !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n overflow-y: auto !important;\n}\n\n#dev-server-modal-inner {\n color: #333 !important;\n background-color: #fff !important;\n border-radius: 8px !important;\n max-width: 80vw !important;\n margin: 30px auto !important;\n padding: 25px !important;\n position: relative !important;\n box-shadow: 0 10px 40px #00000080 !important;\n}\n\n.dev-server-diagnostic {\n border: 1px solid #ddd !important;\n border-radius: 3px !important;\n margin: 20px !important;\n}\n\n.dev-server-diagnostic-masthead {\n padding: 8px 12px 12px !important;\n}\n\n.dev-server-diagnostic-title {\n color: #222 !important;\n margin: 0 !important;\n font-weight: bold !important;\n}\n\n.dev-server-diagnostic-message {\n color: #555 !important;\n margin-top: 4px !important;\n}\n\n.dev-server-diagnostic-file {\n border-top: 1px solid #ddd !important;\n position: relative !important;\n}\n\n.dev-server-diagnostic-file-header {\n color: #555 !important;\n background-color: #f9f9f9 !important;\n border-bottom: 1px solid #ddd !important;\n border-top-left-radius: 2px !important;\n border-top-right-radius: 2px !important;\n padding: 5px 10px !important;\n font-family: Consolas, Liberation Mono, Menlo, Courier, monospace !important;\n font-size: 12px !important;\n display: block !important;\n}\n\na.dev-server-diagnostic-file-header {\n color: #00e !important;\n text-decoration: underline !important;\n}\n\na.dev-server-diagnostic-file-header:hover {\n background-color: #f4f4f4 !important;\n text-decoration: none !important;\n}\n\n.dev-server-diagnostic-file-name {\n font-weight: bold !important;\n}\n\n.dev-server-diagnostic-blob {\n border-bottom-right-radius: 3px !important;\n border-bottom-left-radius: 3px !important;\n overflow: auto hidden !important;\n}\n\n.dev-server-diagnostic-table {\n -moz-tab-size: 2;\n tab-size: 2;\n border-spacing: 0 !important;\n border-collapse: collapse !important;\n border-style: none !important;\n border-width: 0 !important;\n margin: 0 !important;\n padding: 0 !important;\n}\n\n.dev-server-diagnostic-table td, .dev-server-diagnostic-table th {\n border-style: none !important;\n border-width: 0 !important;\n padding: 0 !important;\n}\n\ntd.dev-server-diagnostic-blob-num {\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n color: #0000004d !important;\n text-align: right !important;\n white-space: nowrap !important;\n vertical-align: top !important;\n border: 0 solid #eee !important;\n border-right-width: 1px !important;\n width: 1% !important;\n min-width: 50px !important;\n padding-left: 10px !important;\n padding-right: 10px !important;\n font-family: Consolas, Liberation Mono, Menlo, Courier, monospace !important;\n font-size: 12px !important;\n line-height: 20px !important;\n}\n\ntd.dev-server-diagnostic-blob-num:before {\n content: attr(data-line-number) !important;\n}\n\n.dev-server-diagnostic-error-line td.dev-server-diagnostic-blob-num {\n background-color: #fdd !important;\n border-color: #ffc9c9 !important;\n}\n\n.dev-server-diagnostic-error-line td.dev-server-diagnostic-blob-code {\n background: #ffdddd40 !important;\n}\n\n.dev-server-diagnostic-open-in-editor td.dev-server-diagnostic-blob-num:hover {\n cursor: pointer;\n font-weight: bold;\n background-color: #ffffe3 !important;\n}\n\n.dev-server-diagnostic-open-in-editor.dev-server-diagnostic-error-line td.dev-server-diagnostic-blob-num:hover {\n background-color: #ffdada !important;\n}\n\ntd.dev-server-diagnostic-blob-code {\n vertical-align: top !important;\n color: #333 !important;\n word-wrap: normal !important;\n white-space: pre !important;\n padding-left: 10px !important;\n padding-right: 10px !important;\n font-family: Consolas, Liberation Mono, Menlo, Courier, monospace !important;\n font-size: 12px !important;\n line-height: 20px !important;\n position: relative !important;\n overflow: visible !important;\n}\n\ntd.dev-server-diagnostic-blob-code:before {\n content: \"\" !important;\n}\n\n.dev-server-diagnostic-error-chr {\n position: relative !important;\n}\n\n.dev-server-diagnostic-error-chr:before {\n z-index: -1;\n content: \"\" !important;\n background-color: #fdd !important;\n width: 8px !important;\n height: 20px !important;\n position: absolute !important;\n top: -3px !important;\n left: 0 !important;\n}\n\n.hljs-comment, .hljs-meta {\n color: #969896;\n}\n\n.hljs-string, .hljs-variable, .hljs-template-variable, .hljs-strong, .hljs-emphasis, .hljs-quote {\n color: #df5000;\n}\n\n.hljs-keyword, .hljs-selector-tag, .hljs-type {\n color: #a71d5d;\n}\n\n.hljs-literal, .hljs-symbol, .hljs-bullet, .hljs-attribute {\n color: #0086b3;\n}\n\n.hljs-section, .hljs-name {\n color: #63a35c;\n}\n\n.hljs-tag {\n color: #333;\n}\n\n.hljs-title, .hljs-attr, .hljs-selector-id, .hljs-selector-class, .hljs-selector-attr, .hljs-selector-pseudo {\n color: #795da3;\n}\n\n.hljs-addition {\n color: #55a532;\n background-color: #eaffea;\n}\n\n.hljs-deletion {\n color: #bd2c00;\n background-color: #ffecec;\n}\n\n.hljs-link {\n text-decoration: underline;\n}\n\n.dev-server-error-badge {\n z-index: 99998 !important;\n color: #fff !important;\n cursor: pointer !important;\n background: #f55 !important;\n border: none !important;\n border-radius: 8px !important;\n align-items: center !important;\n gap: 8px !important;\n padding: 10px 16px !important;\n font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, sans-serif !important;\n font-size: 14px !important;\n font-weight: 600 !important;\n transition: transform .2s, box-shadow .2s !important;\n display: flex !important;\n position: fixed !important;\n bottom: 20px !important;\n left: 20px !important;\n box-shadow: 0 4px 12px #0000004d !important;\n}\n\n.dev-server-error-badge:hover {\n transform: translateY(-2px) !important;\n box-shadow: 0 6px 16px #0006 !important;\n}\n\n.error-badge-icon {\n color: #f55 !important;\n background: #fff !important;\n border-radius: 50% !important;\n justify-content: center !important;\n align-items: center !important;\n width: 20px !important;\n height: 20px !important;\n font-size: 14px !important;\n font-weight: bold !important;\n display: flex !important;\n}\n\n.error-badge-count {\n font-size: 14px !important;\n font-weight: 600 !important;\n}\n";
20
20
  //#endregion
21
21
  //#region src/client/error.ts
22
22
  let errorCount = 0;
@@ -396,9 +396,7 @@ const hmrStyleSheetImages = (cssImageProps, styleSheet, versionId, imageFileName
396
396
  case CSSRule.STYLE_RULE:
397
397
  hmrStyleSheetRuleImages(cssImageProps, cssRule, versionId, imageFileNames);
398
398
  break;
399
- case CSSRule.MEDIA_RULE:
400
- hmrStyleSheetImages(cssImageProps, cssRule, versionId, imageFileNames);
401
- break;
399
+ case CSSRule.MEDIA_RULE: hmrStyleSheetImages(cssImageProps, cssRule, versionId, imageFileNames);
402
400
  }
403
401
  }
404
402
  } catch (e) {
@@ -507,6 +505,7 @@ const hmrInlineStylesTraverse = (elm, versionId, trackers) => {
507
505
  if (hasShadowRoot(elm)) hmrInlineStylesTraverse(elm.shadowRoot, versionId, trackers);
508
506
  if (elm.children) for (let i = 0; i < elm.children.length; i++) hmrInlineStylesTraverse(elm.children[i], versionId, trackers);
509
507
  };
508
+ const SLOT_FB_CSS = "slot-fb{display:contents}slot-fb[hidden]{display:none}";
510
509
  /**
511
510
  * Update or remove a style element based on the HMR update.
512
511
  * @param elm - the style element to update
@@ -517,7 +516,8 @@ const hmrInlineStylesTraverse = (elm, versionId, trackers) => {
517
516
  const hmrStyleElement = (elm, versionId, stylesUpdated) => {
518
517
  if (elm.getAttribute(STYLE_ID_ATTR) === stylesUpdated.styleId) {
519
518
  if (stylesUpdated.styleText) {
520
- elm.innerHTML = stylesUpdated.styleText.replace(/\\n/g, "\n");
519
+ const slotFbSuffix = elm.hasAttribute("data-slot-fb") ? SLOT_FB_CSS : "";
520
+ elm.innerHTML = stylesUpdated.styleText.replace(/\\n/g, "\n") + slotFbSuffix;
521
521
  elm.setAttribute("data-hmr", versionId);
522
522
  } else elm.remove();
523
523
  return true;
@@ -926,15 +926,17 @@ const appUpdate = (win, config, buildResults) => {
926
926
  win["s-build-id"] = buildResults.buildId;
927
927
  clearAppErrorModal({ window: win });
928
928
  if (buildResults.hasError) {
929
+ const hasEditors = Array.isArray(config.editors) && config.editors.length > 0;
929
930
  const errorResults = appError({
930
931
  window: win,
931
932
  buildResults,
932
- openInEditor: Array.isArray(config.editors) && config.editors.length > 0 ? (data) => {
933
- const url = `${OPEN_IN_EDITOR_URL}?${new URLSearchParams({
933
+ openInEditor: hasEditors ? (data) => {
934
+ const params = new URLSearchParams({
934
935
  file: data.file,
935
936
  line: String(data.line),
936
937
  column: String(data.column)
937
- }).toString()}`;
938
+ });
939
+ const url = `${OPEN_IN_EDITOR_URL}?${params.toString()}`;
938
940
  win.fetch(url).catch((err) => {
939
941
  console.error("Failed to open in editor:", err);
940
942
  });
package/dist/index.d.mts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { CompilerBuildResults, CompilerRequestResponse, CompilerWatcher, DevServer, DevServerConfig, DevServerConfig as DevServerConfig$1, Logger, StencilDevServerConfig } from "@stencil/core/compiler";
2
-
3
2
  //#region src/server/types.d.ts
4
3
  /**
5
4
  * Internal dev server message protocol for communication between
package/dist/index.mjs CHANGED
@@ -510,6 +510,118 @@ function getEditors() {
510
510
  ]);
511
511
  }
512
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. 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;
527
+ if (filterDirPath) {
528
+ const normalized = path.normalize(filterDirPath);
529
+ components = components.filter((c) => path.normalize(path.dirname(c.sourceFilePath)) === normalized);
530
+ }
531
+ const title = filterDirPath ? `${namespace} / ${path.basename(filterDirPath)}` : namespace;
532
+ const loaderUrl = getLoaderUrl(buildResults);
533
+ const globalCssUrls = getGlobalCssUrls(buildResults);
534
+ 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>`];
535
+ return `<!DOCTYPE html>
536
+ <html lang="en">
537
+ <head>
538
+ <meta charset="UTF-8">
539
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
540
+ <title>${title} — Stencil Dev</title>
541
+ <style>
542
+ *, *::before, *::after { box-sizing: border-box; }
543
+ body { font-family: system-ui, sans-serif; margin: 0; padding: 2rem; }
544
+ h1 { font-size: 1rem; font-weight: 500; margin: 0 0 2rem; color: color-mix(in oklab, CanvasText 90%, Canvas 10%); }
545
+ .component { border: 1px solid color-mix(in oklab, CanvasText 20%, Canvas 80%); border-radius: 6px; margin-bottom: 1.5rem; overflow: hidden; }
546
+ .component-header { padding: 0.5rem 1rem; background: color-mix(in oklab, CanvasText 5%, Canvas 95%); font-family: monospace; font-size: 0.875rem; }
547
+ .component-description { margin: 0; padding: 0.75rem 1rem 0; font-size: 0.875rem; color: color-mix(in oklab, CanvasText 70%, Canvas 30%); }
548
+ .component-preview { padding: 1.5rem; }
549
+ .component-preview + .component-preview { border-top: 1px dashed color-mix(in oklab, CanvasText 20%, Canvas 80%); }
550
+ .preview-note { margin: 0.75rem 0 0; font-size: 0.8125rem; color: color-mix(in oklab, CanvasText 50%, Canvas 50%); }
551
+ .preview-note code { font-size: 0.8125rem; }
552
+ </style>
553
+ ${[loaderUrl ? ` <script type="module" src="${loaderUrl}"><\/script>` : "", ...globalCssUrls.map((url) => ` <link rel="stylesheet" href="${url}">`)].filter(Boolean).join("\n")}
554
+ </head>
555
+ <body>
556
+ <h1>${title}</h1>
557
+ ${sections.join("\n")}
558
+ </body>
559
+ </html>`;
560
+ };
561
+ const renderComponentSection = (component) => {
562
+ const snippets = getUsageSnippets(component);
563
+ const previews = snippets.length > 0 ? snippets.map((html) => ` <div class="component-preview">\n ${html}\n </div>`).join("\n") : ` <div class="component-preview">
564
+ <${component.tagName}></${component.tagName}>
565
+ <p class="preview-note">No demos found - add usage examples to <code>usage/*.md</code> (fenced &#96;&#96;&#96;html&#96;&#96;&#96; blocks) to customize this preview.</p>
566
+ </div>`;
567
+ const description = component.docs.text.trim() ? `\n <p class="component-description">${escapeHtml(component.docs.text.trim())}</p>` : "";
568
+ return ` <div class="component">
569
+ <div class="component-header">&lt;${component.tagName}&gt;</div>${description}
570
+ ${previews}
571
+ </div>`;
572
+ };
573
+ const escapeHtml = (unsafe) => unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
574
+ const getUsageSnippets = (component) => {
575
+ const usageDir = path.join(path.dirname(component.sourceFilePath), "usage");
576
+ try {
577
+ const files = fs.readdirSync(usageDir).filter((f) => f.toLowerCase().endsWith(".md"));
578
+ const snippets = [];
579
+ for (const file of files.sort()) {
580
+ const content = fs.readFileSync(path.join(usageDir, file), "utf-8");
581
+ for (const match of content.matchAll(/```html\n([\s\S]*?)```/g)) snippets.push(match[1].trim());
582
+ }
583
+ return snippets;
584
+ } catch {
585
+ return [];
586
+ }
587
+ };
588
+ /**
589
+ * Convert an absolute output file path to a server-relative URL.
590
+ * @param absPath The absolute file path.
591
+ * @param rootDir The root directory to which the path should be relative.
592
+ * @returns A server-relative URL.
593
+ */
594
+ const toServePath = (absPath, rootDir) => "/" + path.relative(rootDir, absPath).split(path.sep).join("/");
595
+ /**
596
+ * Derive the loader script URL from build outputs.
597
+ * Prefers loader-bundle (always built in dev); falls back to standalone auto-loader if present.
598
+ * @param buildResults The compiler build results containing output file information.
599
+ * @returns A server-relative URL to a loader script, or null if not found.
600
+ */
601
+ const getLoaderUrl = ({ outputs, fsNamespace, rootDir }) => {
602
+ const distLazy = outputs.find((o) => o.type === "dist-lazy");
603
+ if (distLazy) {
604
+ const file = distLazy.files.find((f) => f.endsWith(`/${fsNamespace}.js`));
605
+ if (file) return toServePath(file, rootDir);
606
+ }
607
+ const standalone = outputs.find((o) => o.type === "standalone");
608
+ if (standalone) {
609
+ const file = standalone.files.find((f) => /\/loader\.js$/.test(f));
610
+ if (file) return toServePath(file, rootDir);
611
+ }
612
+ return null;
613
+ };
614
+ /**
615
+ * Collect server-relative URLs for all global-style CSS outputs.
616
+ * @param buildResults The compiler build results containing output file information.
617
+ * @returns An array of server-relative URLs to global-style CSS files.
618
+ */
619
+ const getGlobalCssUrls = ({ outputs, rootDir }) => {
620
+ const globalStyle = outputs.find((o) => o.type === "global-style");
621
+ if (!globalStyle) return [];
622
+ return globalStyle.files.filter((f) => f.endsWith(".css") && !f.endsWith(".css.map")).map((f) => toServePath(f, rootDir));
623
+ };
624
+ //#endregion
513
625
  //#region src/server/ssr.ts
514
626
  /**
515
627
  * SSR (Server-Side Rendering) request handling.
@@ -519,10 +631,10 @@ async function ssrPageRequest(devServerConfig, serverCtx, req, res) {
519
631
  try {
520
632
  let status = 500;
521
633
  let content = "";
522
- const { hydrateApp, srcIndexHtml, diagnostics } = await setupHydrateApp(devServerConfig, serverCtx);
634
+ const { ssrApp, srcIndexHtml, diagnostics } = await setupHydrateApp(devServerConfig, serverCtx);
523
635
  if (!diagnostics.some((diagnostic) => diagnostic.level === "error")) try {
524
636
  const opts = getSsrHydrateOptions(devServerConfig, serverCtx, req.url);
525
- const ssrResults = await hydrateApp.renderToString(srcIndexHtml, opts);
637
+ const ssrResults = await ssrApp.renderToString(srcIndexHtml, opts);
526
638
  diagnostics.push(...ssrResults.diagnostics);
527
639
  status = ssrResults.httpStatus ?? 500;
528
640
  content = ssrResults.html ?? "";
@@ -549,11 +661,11 @@ async function ssrStaticDataRequest(devServerConfig, serverCtx, req, res) {
549
661
  try {
550
662
  const data = {};
551
663
  let httpCache = false;
552
- const { hydrateApp, srcIndexHtml, diagnostics } = await setupHydrateApp(devServerConfig, serverCtx);
664
+ const { ssrApp, srcIndexHtml, diagnostics } = await setupHydrateApp(devServerConfig, serverCtx);
553
665
  if (!diagnostics.some((diagnostic) => diagnostic.level === "error")) try {
554
666
  const { ssrPath, hasQueryString } = getSsrStaticDataPath(req);
555
667
  const opts = getSsrHydrateOptions(devServerConfig, serverCtx, new URL(ssrPath, req.url));
556
- const ssrResults = await hydrateApp.renderToString(srcIndexHtml, opts);
668
+ const ssrResults = await ssrApp.renderToString(srcIndexHtml, opts);
557
669
  diagnostics.push(...ssrResults.diagnostics);
558
670
  ssrResults.staticData.forEach((s) => {
559
671
  if (s.type === "application/json") data[s.id] = JSON.parse(s.content);
@@ -580,18 +692,18 @@ async function ssrStaticDataRequest(devServerConfig, serverCtx, req, res) {
580
692
  }
581
693
  async function setupHydrateApp(devServerConfig, serverCtx) {
582
694
  let srcIndexHtml = null;
583
- let hydrateApp = null;
695
+ let ssrApp = null;
584
696
  const buildResults = await serverCtx.getBuildResults();
585
697
  const diagnostics = [];
586
698
  if (serverCtx.prerenderConfig == null && isString(devServerConfig.prerenderConfig)) try {
587
- const prerenderConfigResults = (await import("@stencil/core/compiler")).nodeRequire(devServerConfig.prerenderConfig);
699
+ const prerenderConfigResults = await (await import("@stencil/core/compiler")).nodeRequire(devServerConfig.prerenderConfig);
588
700
  diagnostics.push(...prerenderConfigResults.diagnostics);
589
701
  if (prerenderConfigResults.module?.config) serverCtx.prerenderConfig = prerenderConfigResults.module.config;
590
702
  } catch (e) {
591
703
  catchError(diagnostics, e);
592
704
  }
593
- if (!isString(buildResults.hydrateAppFilePath)) diagnostics.push({
594
- messageText: "Missing hydrateAppFilePath",
705
+ if (!isString(buildResults.ssrAppFilePath)) diagnostics.push({
706
+ messageText: "Missing ssrAppFilePath",
595
707
  level: "error",
596
708
  type: "ssr",
597
709
  lines: []
@@ -611,19 +723,19 @@ async function setupHydrateApp(devServerConfig, serverCtx) {
611
723
  type: "ssr"
612
724
  });
613
725
  else {
614
- const hydrateAppFilePath = path.resolve(buildResults.hydrateAppFilePath);
726
+ const ssrAppFilePath = path.resolve(buildResults.ssrAppFilePath);
615
727
  try {
616
- const hydrateUrl = pathToFileURL(hydrateAppFilePath);
728
+ const hydrateUrl = pathToFileURL(ssrAppFilePath);
617
729
  hydrateUrl.search = `?t=${Date.now()}`;
618
730
  const hydrateModule = await import(hydrateUrl.href);
619
- hydrateApp = hydrateModule.default || hydrateModule;
731
+ ssrApp = hydrateModule.default || hydrateModule;
620
732
  } catch (e) {
621
733
  catchError(diagnostics, e);
622
734
  }
623
735
  }
624
736
  }
625
737
  return {
626
- hydrateApp,
738
+ ssrApp,
627
739
  srcIndexHtml,
628
740
  diagnostics
629
741
  };
@@ -643,14 +755,14 @@ function getSsrHydrateOptions(devServerConfig, serverCtx, url) {
643
755
  prettyHtml: true
644
756
  };
645
757
  const prerenderConfig = serverCtx?.prerenderConfig;
646
- if (isFunction(prerenderConfig?.hydrateOptions)) {
647
- const userOpts = prerenderConfig.hydrateOptions(url);
758
+ if (isFunction(prerenderConfig?.prerenderOptions)) {
759
+ const userOpts = prerenderConfig.prerenderOptions(url);
648
760
  if (userOpts) Object.assign(opts, userOpts);
649
761
  }
650
762
  if (isFunction(serverCtx.sys.applyPrerenderGlobalPatch)) {
651
- const orgBeforeHydrate = opts.beforeHydrate;
763
+ const orgBeforeHydrate = opts.beforeSsr;
652
764
  const applyPatch = serverCtx.sys.applyPrerenderGlobalPatch;
653
- opts.beforeHydrate = (document) => {
765
+ opts.beforeSsr = (document) => {
654
766
  const devServerHostUrl = new URL(devServerConfig.browserUrl).origin;
655
767
  applyPatch({
656
768
  devServerHostUrl,
@@ -871,7 +983,8 @@ function updateStyleUrls(url, oldCss) {
871
983
  return newCss;
872
984
  }
873
985
  function appendDevServerClientScript(devServerConfig, req, content) {
874
- return appendDevServerClientIframe(content, `<iframe title="Stencil Dev Server Connector ${VERSION} &#9889;" src="${getDevServerClientUrl(devServerConfig, req.headers?.["x-forwarded-host"] ?? req.host, req.headers?.["x-forwarded-proto"])}" style="display:block;width:0;height:0;border:0;visibility:hidden" aria-hidden="true"></iframe>`);
986
+ const devServerClientUrl = getDevServerClientUrl(devServerConfig, req.headers?.["x-forwarded-host"] ?? req.host, req.headers?.["x-forwarded-proto"]);
987
+ return appendDevServerClientIframe(content, `<iframe title="Stencil Dev Server Connector ${VERSION} &#9889;" src="${devServerClientUrl}" style="display:block;width:0;height:0;border:0;visibility:hidden" aria-hidden="true"></iframe>`);
875
988
  }
876
989
  function appendDevServerClientIframe(content, iframe) {
877
990
  if (content.includes("</body>")) return content.replace("</body>", `${iframe}</body>`);
@@ -884,7 +997,7 @@ async function serveDevClient(devServerConfig, serverCtx, req, res) {
884
997
  if (isDevServerClient(req.pathname)) return serveDevClientScript(devServerConfig, serverCtx, req, res);
885
998
  if (isInitialDevServerLoad(req.pathname)) req.filePath = path.join(devServerConfig.devServerDir, "templates", "initial-load.html");
886
999
  else {
887
- const subPath = req.pathname.replace(DEV_SERVER_URL + "/", "");
1000
+ const subPath = req.pathname.replace("/~dev-server/", "");
888
1001
  if (subPath.startsWith("client/")) req.filePath = path.join(devServerConfig.devServerDir, subPath);
889
1002
  else req.filePath = path.join(devServerConfig.devServerDir, "static", subPath);
890
1003
  }
@@ -948,6 +1061,13 @@ async function serveDirectoryIndex(devServerConfig, serverCtx, req, res) {
948
1061
  if (!req.pathname.endsWith("/")) return serverCtx.serve302(req, res, req.pathname + "/");
949
1062
  try {
950
1063
  const dirFilePaths = await serverCtx.sys.readDir(req.filePath);
1064
+ if (dirFilePaths.some((f) => f.endsWith(".tsx")) && !await hasNestedHtmlFile(serverCtx.sys, dirFilePaths)) return serveDevPreview(devServerConfig, serverCtx, req, res, req.filePath);
1065
+ if (req.pathname === "/" || req.pathname === devServerConfig.basePath) {
1066
+ const srcPath = path.join(req.filePath, "src");
1067
+ try {
1068
+ if ((await serverCtx.sys.stat(srcPath)).isDirectory) return serverCtx.serve302(req, res, "/src/");
1069
+ } catch {}
1070
+ }
951
1071
  try {
952
1072
  if (serverCtx.dirTemplate == null) {
953
1073
  const dirTemplatePath = path.join(devServerConfig.devServerDir, "templates", "directory-index.html");
@@ -969,6 +1089,39 @@ async function serveDirectoryIndex(devServerConfig, serverCtx, req, res) {
969
1089
  return serverCtx.serve404(req, res, "serveDirectoryIndex");
970
1090
  }
971
1091
  }
1092
+ /**
1093
+ * Recursively checks a directory (and its subdirectories) for any .html/.htm file.
1094
+ * Used to decide whether the auto-generated component preview should be shown, or
1095
+ * the default file-listing view (since a nested html file likely means a custom
1096
+ * preview/demo page already exists somewhere in the tree).
1097
+ * @param sys The dev server's compiler system, used to read directories and stat files.
1098
+ * @param dirFilePaths The full paths of entries in the directory to check.
1099
+ * @returns true if an html file exists at this level or in any subdirectory.
1100
+ */
1101
+ async function hasNestedHtmlFile(sys, dirFilePaths) {
1102
+ const subDirPaths = [];
1103
+ for (const filePath of dirFilePaths) {
1104
+ if (filePath.endsWith(".html") || filePath.endsWith(".htm")) return true;
1105
+ if ((await sys.stat(filePath)).isDirectory) subDirPaths.push(filePath);
1106
+ }
1107
+ for (const subDirPath of subDirPaths) if (await hasNestedHtmlFile(sys, await sys.readDir(subDirPath))) return true;
1108
+ return false;
1109
+ }
1110
+ async function serveDevPreview(devServerConfig, serverCtx, req, res, filterDirPath) {
1111
+ try {
1112
+ const buildResults = await serverCtx.getBuildResults();
1113
+ const html = appendDevServerClientScript(devServerConfig, req, generateDevPreview(buildResults, filterDirPath));
1114
+ const buf = Buffer.from(html, "utf-8");
1115
+ serverCtx.logRequest(req, 200);
1116
+ res.writeHead(200, responseHeaders({
1117
+ "content-type": "text/html;charset=utf-8",
1118
+ "content-length": buf.byteLength
1119
+ }));
1120
+ res.end(buf);
1121
+ } catch (e) {
1122
+ serverCtx.serve500(req, res, e, "serveDevPreview");
1123
+ }
1124
+ }
972
1125
  async function getDirectoryFiles(sys, baseUrl, dirItemNames) {
973
1126
  const items = await getDirectoryItems(sys, baseUrl, dirItemNames);
974
1127
  if (baseUrl.pathname !== "/") items.unshift({
@@ -1178,7 +1331,8 @@ function initServerProcess(sendMsg) {
1178
1331
  * @returns Function to send messages from main to worker process
1179
1332
  */
1180
1333
  function initServerProcessWorkerProxy(sendToMain) {
1181
- let serverProcess = fork(path.join(import.meta.dirname, "worker-thread.js"), [], {
1334
+ const workerPath = path.join(import.meta.dirname, "worker-thread.js");
1335
+ const forkOpts = {
1182
1336
  execArgv: process.execArgv.filter((v) => !/^--(debug|inspect)/.test(v)),
1183
1337
  env: process.env,
1184
1338
  cwd: process.cwd(),
@@ -1188,7 +1342,8 @@ function initServerProcessWorkerProxy(sendToMain) {
1188
1342
  "pipe",
1189
1343
  "ipc"
1190
1344
  ]
1191
- });
1345
+ };
1346
+ let serverProcess = fork(workerPath, [], forkOpts);
1192
1347
  /**
1193
1348
  * Send a message from main to the worker process
1194
1349
  *
@@ -1339,27 +1494,33 @@ function startServer(devServerConfig, logger, watcher, initServerProcessFn, reso
1339
1494
  resolve(devServer);
1340
1495
  };
1341
1496
  const requestLog = (msg) => {
1342
- if (devServerConfig.logRequests && msg.requestLog) if (msg.requestLog.status >= 500) logger.info(logger.red(`${msg.requestLog.method} ${msg.requestLog.url} (${msg.requestLog.status})`));
1343
- else if (msg.requestLog.status >= 400) logger.info(logger.dim(logger.red(`${msg.requestLog.method} ${msg.requestLog.url} (${msg.requestLog.status})`)));
1344
- else if (msg.requestLog.status >= 300) logger.info(logger.dim(logger.magenta(`${msg.requestLog.method} ${msg.requestLog.url} (${msg.requestLog.status})`)));
1345
- else logger.info(logger.dim(`${logger.cyan(msg.requestLog.method)} ${msg.requestLog.url}`));
1497
+ if (devServerConfig.logRequests && msg.requestLog) {
1498
+ if (msg.requestLog.status >= 500) logger.info(logger.red(`${msg.requestLog.method} ${msg.requestLog.url} (${msg.requestLog.status})`));
1499
+ else if (msg.requestLog.status >= 400) logger.info(logger.dim(logger.red(`${msg.requestLog.method} ${msg.requestLog.url} (${msg.requestLog.status})`)));
1500
+ else if (msg.requestLog.status >= 300) logger.info(logger.dim(logger.magenta(`${msg.requestLog.method} ${msg.requestLog.url} (${msg.requestLog.status})`)));
1501
+ else logger.info(logger.dim(`${logger.cyan(msg.requestLog.method)} ${msg.requestLog.url}`));
1502
+ }
1346
1503
  };
1347
1504
  const serverError = async (msg) => {
1348
- if (msg.error) if (hasStarted) logger.error(msg.error.message + " " + msg.error.stack);
1349
- else {
1350
- await close();
1351
- reject(msg.error.message);
1505
+ if (msg.error) {
1506
+ if (hasStarted) logger.error(msg.error.message + " " + msg.error.stack);
1507
+ else {
1508
+ await close();
1509
+ reject(msg.error.message);
1510
+ }
1352
1511
  }
1353
1512
  };
1354
1513
  const requestBuildResults = () => {
1355
- if (sendToServer) if (lastBuildResults != null) {
1356
- const msg = {
1357
- buildResults: { ...lastBuildResults },
1358
- isActivelyBuilding
1359
- };
1360
- delete msg.buildResults.hmr;
1361
- sendToServer(msg);
1362
- } else sendToServer({ isActivelyBuilding: true });
1514
+ if (sendToServer) {
1515
+ if (lastBuildResults != null) {
1516
+ const msg = {
1517
+ buildResults: { ...lastBuildResults },
1518
+ isActivelyBuilding
1519
+ };
1520
+ delete msg.buildResults.hmr;
1521
+ sendToServer(msg);
1522
+ } else sendToServer({ isActivelyBuilding: true });
1523
+ }
1363
1524
  };
1364
1525
  const compilerRequest = async (compilerRequestPath) => {
1365
1526
  if (watcher?.request && sendToServer) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stencil/dev-server",
3
- "version": "5.0.0-alpha.3",
3
+ "version": "5.0.0-alpha.31",
4
4
  "description": "Development server for Stencil with DOM-based HMR",
5
5
  "keywords": [
6
6
  "dev server",
@@ -35,21 +35,21 @@
35
35
  }
36
36
  },
37
37
  "dependencies": {
38
- "launch-editor": "^2.9.1",
38
+ "launch-editor": "^2.14.1",
39
39
  "open": "^11.0.0",
40
- "ws": "^8.0.0"
40
+ "ws": "^8.21.3"
41
41
  },
42
42
  "devDependencies": {
43
- "@tsdown/css": "^0.21.6",
44
- "@types/ws": "^8.0.0",
45
- "tsdown": "^0.21.6",
46
- "typescript": "~6.0.2",
47
- "vitest": "^4.1.1",
48
- "vitest-environment-stencil": "^1.10.0",
49
- "@stencil/core": "5.0.0-alpha.3"
43
+ "@tsdown/css": "^0.22.14",
44
+ "@types/ws": "^8.18.1",
45
+ "tsdown": "^0.22.14",
46
+ "typescript": ">5.0.0 <7.0.0",
47
+ "vitest": "^4.1.10",
48
+ "vitest-environment-stencil": "^1.14.0",
49
+ "@stencil/core": "5.0.0-alpha.31"
50
50
  },
51
51
  "peerDependencies": {
52
- "@stencil/core": "^5.0.0-0"
52
+ "@stencil/core": "^5.0.0 || 5.0.0-alpha.31"
53
53
  },
54
54
  "volta": {
55
55
  "extends": "../../package.json"
File without changes