@gracile/engine 0.9.0-next.3 → 0.9.0-next.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/plugin.d.ts.map +1 -1
  2. package/dist/plugin.js +42 -254
  3. package/dist/render/light-dom.d.ts +2 -0
  4. package/dist/render/light-dom.d.ts.map +1 -0
  5. package/dist/render/light-dom.js +31 -0
  6. package/dist/render/route-template-pipeline.d.ts +64 -0
  7. package/dist/render/route-template-pipeline.d.ts.map +1 -0
  8. package/dist/render/route-template-pipeline.js +144 -0
  9. package/dist/render/route-template.d.ts +4 -3
  10. package/dist/render/route-template.d.ts.map +1 -1
  11. package/dist/render/route-template.js +17 -88
  12. package/dist/routes/collect.d.ts +4 -0
  13. package/dist/routes/collect.d.ts.map +1 -1
  14. package/dist/routes/collect.js +2 -1
  15. package/dist/routes/match.d.ts +26 -0
  16. package/dist/routes/match.d.ts.map +1 -1
  17. package/dist/routes/match.js +4 -2
  18. package/dist/routes/render.d.ts.map +1 -1
  19. package/dist/routes/render.js +1 -0
  20. package/dist/server/request-pipeline.d.ts +109 -0
  21. package/dist/server/request-pipeline.d.ts.map +1 -0
  22. package/dist/server/request-pipeline.js +198 -0
  23. package/dist/server/request.d.ts +3 -16
  24. package/dist/server/request.d.ts.map +1 -1
  25. package/dist/server/request.js +56 -169
  26. package/dist/test/init.d.ts +2 -0
  27. package/dist/test/init.d.ts.map +1 -0
  28. package/dist/test/init.js +7 -0
  29. package/dist/user-config.d.ts +35 -0
  30. package/dist/user-config.d.ts.map +1 -1
  31. package/dist/vite/plugin-client-build.d.ts +16 -0
  32. package/dist/vite/plugin-client-build.d.ts.map +1 -0
  33. package/dist/vite/plugin-client-build.js +49 -0
  34. package/dist/vite/plugin-serve.d.ts +18 -0
  35. package/dist/vite/plugin-serve.d.ts.map +1 -0
  36. package/dist/vite/plugin-serve.js +62 -0
  37. package/dist/vite/plugin-server-build.d.ts +33 -0
  38. package/dist/vite/plugin-server-build.d.ts.map +1 -0
  39. package/dist/vite/plugin-server-build.js +157 -0
  40. package/dist/vite/plugin-shared-state.d.ts +31 -0
  41. package/dist/vite/plugin-shared-state.d.ts.map +1 -0
  42. package/dist/vite/plugin-shared-state.js +22 -0
  43. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAQtD;;;;;;;;;;;;;;;;GAgBG;AAIH,eAAO,MAAM,OAAO,GAAI,SAAS,aAAa,KAAG,GAAG,EAqUnD,CAAC;AAEF,YAAY,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC"}
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AActD;;;;;;;;;;;;;;;;GAgBG;AAIH,eAAO,MAAM,OAAO,GAAI,SAAS,aAAa,KAAG,GAAG,EAiEnD,CAAC;AAEF,YAAY,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC"}
package/dist/plugin.js CHANGED
@@ -1,17 +1,12 @@
1
- import { join } from 'node:path';
2
- import { rename, rm } from 'node:fs/promises';
3
1
  import { createLogger } from '@gracile/internal-utils/logger/helpers';
4
- import { getVersion } from '@gracile/internal-utils/version';
5
- // import { betterErrors } from '@gracile-labs/better-errors/plugin';
6
- import c from 'picocolors';
7
- import { build, createServer } from 'vite';
8
- import {} from './routes/render.js';
9
- import { createDevelopmentHandler } from './dev/development.js';
10
- import { nodeAdapter } from './server/adapters/node.js';
11
- import { buildRoutes } from './vite/build-routes.js';
2
+ import { getPluginContext, } from '@gracile/internal-utils/plugin-context';
12
3
  import { htmlRoutesLoader } from './vite/html-routes.js';
13
- import { virtualRoutes, virtualRoutesClient } from './vite/virtual-routes.js';
14
4
  import { hmrSsrReload } from './vite/hmr.js';
5
+ import { virtualRoutesClient } from './vite/virtual-routes.js';
6
+ import { createPluginSharedState } from './vite/plugin-shared-state.js';
7
+ import { gracileServePlugin } from './vite/plugin-serve.js';
8
+ import { gracileClientBuildPlugin } from './vite/plugin-client-build.js';
9
+ import { gracileCollectClientAssetsPlugin, gracileServerBuildPlugin, } from './vite/plugin-server-build.js';
15
10
  let isClientBuilt = false;
16
11
  /**
17
12
  * The main Vite plugin for loading the Gracile framework.
@@ -35,262 +30,55 @@ let isClientBuilt = false;
35
30
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
36
31
  export const gracile = (config) => {
37
32
  const logger = createLogger();
38
- const outputMode = config?.output || 'static';
39
- const clientAssets = {};
40
- const routes = new Map();
41
- let renderedRoutes = null;
42
- let root = null;
43
- const gracileConfig = config || {};
33
+ const state = createPluginSharedState(config);
44
34
  // HACK: Prevent duplicate client build for the SSR build step in server mode.
45
35
  // TODO: Move to the new, clean, environments builders API.
46
36
  if (isClientBuilt)
47
37
  return [];
48
38
  isClientBuilt = true;
49
39
  const virtualRoutesForClient = virtualRoutesClient({
50
- mode: outputMode,
51
- routes,
52
- // NOTE: This will be a dedicated setting when it will not be experimental
53
- // anymore.
54
- gracileConfig,
55
- // enabled: gracileConfig?.pages?.premises?.expose || false,
40
+ mode: state.outputMode,
41
+ routes: state.routes,
42
+ gracileConfig: state.gracileConfig,
56
43
  });
44
+ let sharedPluginContext;
57
45
  return [
58
- // betterErrors({
59
- // overlayImportPath: '@gracile/gracile/_internals/vite-custom-overlay',
60
- // }),
61
- // {
62
- // name: 'gracile-routes-codegen',
63
- // // watchChange(change) {
64
- // // console.log({ change });
65
- // // },
66
- // resolveId(id) {
67
- // const virtualModuleId = 'gracile:route';
68
- // const resolvedVirtualModuleId = `\0${virtualModuleId}`;
69
- // if (id === virtualModuleId) {
70
- // return resolvedVirtualModuleId;
71
- // }
72
- // return null;
73
- // },
74
- // load(id) {
75
- // const virtualModuleId = 'gracile:route';
76
- // const resolvedVirtualModuleId = `\0${virtualModuleId}`;
77
- // if (id === resolvedVirtualModuleId) {
78
- // return `
79
- // export function route(input){
80
- // return input;
81
- // }`;
82
- // }
83
- // return null;
84
- // },
85
- // },
86
- hmrSsrReload(),
46
+ // MARK: 1. Plugin context setup
87
47
  {
88
- name: 'vite-plugin-gracile-serve-middleware',
89
- apply: 'serve',
90
- config(_, environment) {
91
- if (environment.isPreview)
92
- return null;
93
- return {
94
- // NOTE: Supresses message: `Could not auto-determine entry point from rollupOptions or html files…`
95
- // FIXME: It's not working when reloading the Vite config.
96
- // Is user config, putting `optimizeDeps: { include: [] }` solve this.
97
- optimizeDeps: { include: [] },
98
- // NOTE: Useful? It breaks preview (expected)
99
- appType: 'custom',
100
- // resolve: {
101
- // conditions: ['development'],
102
- // },
103
- };
48
+ name: 'vite-plugin-gracile-context',
49
+ config(viteConfig) {
50
+ sharedPluginContext = getPluginContext(viteConfig);
51
+ state.gracileConfig.litSsr ??= { renderInfo: {} };
52
+ state.gracileConfig.litSsr.renderInfo =
53
+ sharedPluginContext.litSsrRenderInfo;
104
54
  },
105
- async configureServer(server) {
106
- // HACK: We know we are in dev here, this will prevent incorrect
107
- // vite.config hot reloading. Will be removed when adopting env. API.
55
+ },
56
+ // MARK: 2. HMR SSR reload
57
+ hmrSsrReload(),
58
+ // MARK: 3. Dev serve middleware
59
+ gracileServePlugin({
60
+ state,
61
+ config,
62
+ logger,
63
+ resetClientBuiltFlag: () => {
108
64
  isClientBuilt = false;
109
- // Infos
110
- // // NOTE: Beware import.meta.resolve is only compatible
111
- // // with v20.6.0 (without cli flag)and upward
112
- // // Not working with StackBlitz ATM?
113
- // const mainPjson = import.meta
114
- // .resolve('@gracile/gracile')
115
- // // NOTE: Weirdly, it will assume that it's `dist/**.js`,
116
- // // even after fiddling with pjson exports.
117
- // .replace('/dist/index.js', '/package.json');
118
- // const { version } = JSON.parse(
119
- // await readFile(new URL(mainPjson), 'utf-8'),
120
- // ) as {
121
- // version: number;
122
- // };
123
- const version = getVersion();
124
- logger.info(`${c.cyan(c.italic(c.underline('🧚 Gracile')))}` +
125
- ` ${c.dim(`~`)} ${c.green(`v${version ?? 'X'}`)}`);
126
- // ---
127
- const { handler } = await createDevelopmentHandler({
128
- routes,
129
- vite: server,
130
- gracileConfig,
131
- });
132
- logger.info(c.dim('Vite development server is starting…'), {
133
- timestamp: true,
134
- });
135
- server.watcher.on('ready', () => {
136
- setTimeout(() => {
137
- logger.info('');
138
- logger.info(c.green('Watching for file changes…'), {
139
- timestamp: true,
140
- });
141
- logger.info('');
142
- // NOTE: We want it to show after the Vite intro stuff
143
- }, 100);
144
- });
145
- return () => {
146
- server.middlewares.use((request, response, next) => {
147
- const locals = config?.dev?.locals?.({ nodeRequest: request });
148
- Promise.resolve(nodeAdapter(handler, { logger })(request, response, locals)).catch((error) => next(error));
149
- });
150
- };
151
65
  },
152
- },
66
+ }),
67
+ // MARK: 4. Client virtual routes
153
68
  virtualRoutesForClient,
69
+ // MARK: 5. HTML routes loader
154
70
  htmlRoutesLoader(),
155
- {
156
- name: 'vite-plugin-gracile-build',
157
- apply: 'build',
158
- async config(viteConfig) {
159
- const viteServerForClientHtmlBuild = await createServer({
160
- // configFile: false,
161
- root: viteConfig.root || process.cwd(),
162
- server: { middlewareMode: true },
163
- // NOTE: Stub. KEEP IT!
164
- optimizeDeps: { include: [] },
165
- plugins: [virtualRoutesForClient],
166
- });
167
- const htmlPages = await buildRoutes({
168
- viteServerForBuild: viteServerForClientHtmlBuild,
169
- root: viteConfig.root || process.cwd(),
170
- gracileConfig,
171
- serverMode: outputMode === 'server',
172
- routes,
173
- });
174
- renderedRoutes = htmlPages.renderedRoutes;
175
- await viteServerForClientHtmlBuild.close();
176
- return {
177
- build: {
178
- // ssrManifest: true,
179
- rollupOptions: {
180
- input: htmlPages.inputList,
181
- plugins: [htmlPages.plugin],
182
- },
183
- outDir: join(viteConfig.build?.outDir || 'dist', outputMode === 'server' ? 'client' : ''),
184
- },
185
- };
186
- },
187
- },
188
- {
189
- name: 'vite-plugin-gracile-collect-client-assets-for-server',
190
- writeBundle(_, bundle) {
191
- if (outputMode === 'static')
192
- return;
193
- for (const file of Object.values(bundle))
194
- if (file.type === 'asset' && file.name)
195
- clientAssets[file.name] = file.fileName;
196
- },
197
- },
198
- {
199
- name: 'vite-plugin-gracile-server-build',
200
- apply: 'build',
201
- config(viteConfig) {
202
- root = viteConfig.root || null;
203
- },
204
- async closeBundle() {
205
- if (outputMode === 'static' || !routes || !renderedRoutes)
206
- return;
207
- await build({
208
- root: root || process.cwd(),
209
- ssr: { external: ['@gracile/gracile'] },
210
- build: {
211
- target: 'esnext',
212
- ssr: true,
213
- // ssrManifest: true,
214
- copyPublicDir: false,
215
- outDir: 'dist/server',
216
- ssrEmitAssets: true,
217
- cssMinify: true,
218
- cssCodeSplit: true,
219
- rollupOptions: {
220
- input: 'entrypoint.js',
221
- // external: ['@gracile/gracile'],
222
- // FIXME: ~~MUST import css from client somewhere.~~
223
- // ~~Hack could be using dynamic imports on client, so asset is picked up~~
224
- output: {
225
- entryFileNames: '[name].js',
226
- // assetFileNames: 'assets/[name].[ext]',
227
- // NOTE: Useful for, e.g., link tag with `?url`
228
- assetFileNames: (chunkInfo) => {
229
- if (chunkInfo.name) {
230
- const fileName = clientAssets[chunkInfo.name];
231
- if (fileName)
232
- return fileName;
233
- // NOTE: When not imported at all from client
234
- return `assets/${chunkInfo.name.replace(/\.(.*)$/, '')}-[hash].[ext]`;
235
- }
236
- // throw new Error(`Not a client asset`);
237
- return 'assets/[name]-[hash].[ext]';
238
- },
239
- chunkFileNames: 'chunk/[name].js',
240
- },
241
- },
242
- },
243
- plugins: [
244
- virtualRoutesForClient,
245
- virtualRoutes({ routes, renderedRoutes }),
246
- {
247
- name: 'vite-plugin-gracile-entry',
248
- resolveId(id) {
249
- if (id === 'entrypoint.js') {
250
- return id;
251
- }
252
- return null;
253
- },
254
- load(id) {
255
- if (id === 'entrypoint.js' && routes && renderedRoutes) {
256
- return `
257
- import { routeAssets, routeImports, routes } from 'gracile:routes';
258
- import { createGracileHandler } from '@gracile/gracile/_internals/server-runtime';
259
- import { createLogger } from '@gracile/gracile/_internals/logger';
260
-
261
- createLogger();
262
-
263
- export const handler = createGracileHandler({
264
- root: process.cwd(),
265
- routes,
266
- routeImports,
267
- routeAssets,
268
- serverMode: true,
269
- gracileConfig: ${JSON.stringify(gracileConfig, null, 2)}
270
- });
271
- `;
272
- }
273
- return null;
274
- },
275
- },
276
- {
277
- name: 'gracile-move-server-assets',
278
- async writeBundle(_, bundle) {
279
- const cwd = root || process.cwd();
280
- await Promise.all(Object.entries(bundle).map(async ([file]) => {
281
- if (file.startsWith('assets/') === false)
282
- return;
283
- await rename(join(cwd, `/dist/server/${file}`), join(cwd, `/dist/client/${file}`));
284
- }));
285
- // NOTE: Disabled for now, because it conflict with test's folder comparer
286
- await rm(join(cwd, `/dist/server/assets`), {
287
- recursive: true,
288
- }).catch(() => null);
289
- },
290
- },
291
- ],
292
- });
293
- },
294
- },
71
+ // MARK: 6. Client build
72
+ gracileClientBuildPlugin({
73
+ state,
74
+ virtualRoutesForClient,
75
+ }),
76
+ // MARK: 7. Collect client assets for server
77
+ gracileCollectClientAssetsPlugin({ state }),
78
+ // MARK: 8. Server build (nested)
79
+ gracileServerBuildPlugin({
80
+ state,
81
+ virtualRoutesForClient,
82
+ }),
295
83
  ];
296
84
  };
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=light-dom.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"light-dom.d.ts","sourceRoot":"","sources":["../../src/render/light-dom.ts"],"names":[],"mappings":"AAsCA,OAAO,EAAE,CAAC"}
@@ -0,0 +1,31 @@
1
+ // import { LitElementRenderer } from '@lit-labs/ssr/lib/lit-element-renderer.js';
2
+ // import type { ThunkedRenderResult } from '@lit-labs/ssr/lib/render-result.js';
3
+ // export class LightDomLitElementRenderer extends LitElementRenderer {
4
+ // static override matchesClass(ctor: typeof HTMLElement) {
5
+ // // return (ctor as any)._$lightDom === true;
6
+ // return true;
7
+ // }
8
+ // // eslint-disable-next-line class-methods-use-this
9
+ // override renderShadow(): ThunkedRenderResult {
10
+ // return;
11
+ // // return []; // ← no <template shadowrootmode> emitted
12
+ // // return [];
13
+ // }
14
+ // override renderLight(renderInfo) {
15
+ // // Emit the render() output as direct light-DOM children
16
+ // // yield* super.renderShadow(renderInfo);
17
+ // // return super.renderLight(renderInfo);
18
+ // const result = this.element.render();
19
+ // console.log({ result });
20
+ // // return renderInfo.render(result);
21
+ // return ['<div>Light DOM content</div>'];
22
+ // // yield* renderInfo.render(result);
23
+ // }
24
+ // // override *renderLight(renderInfo) {
25
+ // // const result = this.element.render();
26
+ // // yield* renderInfo.render(result);
27
+ // // }
28
+ // }
29
+ // // NOTE: On server, Lit SSR doesn't seems to care at all about CE ctors.
30
+ // // customElements.define('app-shell', new Object() as typeof HTMLElement);
31
+ export {};
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Pure, testable pipeline steps extracted from the route template renderer.
3
+ *
4
+ * Each function here is a focused stage of the document post-processing
5
+ * lifecycle. They are composed by `renderRouteTemplate` in
6
+ * `./route-template.ts`.
7
+ *
8
+ * @internal
9
+ */
10
+ import { Readable } from 'node:stream';
11
+ import type { RenderInfo } from '@lit-labs/ssr';
12
+ export declare const REGEX_TAG_SCRIPT: RegExp;
13
+ export declare const REGEX_TAG_LINK: RegExp;
14
+ /**
15
+ * Concatenate multiple `Readable` streams into a single async iterable.
16
+ */
17
+ export declare function concatStreams(...readables: Readable[]): AsyncGenerator<any, void, unknown>;
18
+ /**
19
+ * Merge user-provided `RenderInfo` with the default `LitElementRenderer`.
20
+ * Always appends `LitElementRenderer` to whatever the user supplied.
21
+ */
22
+ export declare function mergeRenderInfo(renderInfo: Partial<RenderInfo> | undefined): Partial<RenderInfo>;
23
+ /**
24
+ * Inject sibling page assets into the rendered document HTML.
25
+ *
26
+ * Inserts the `PAGE_ASSETS_MARKER` before `</head>`, then replaces it
27
+ * with concrete `<script>` / `<link>` tags for each asset path.
28
+ *
29
+ * @param documentHtml The rendered document string.
30
+ * @param pageAssets Array of asset file paths (e.g. `['src/pages/about.css']`).
31
+ * @returns The document with asset tags injected (or unchanged if no assets).
32
+ */
33
+ export declare function injectSiblingAssets(documentHtml: string, pageAssets: string[]): string;
34
+ /**
35
+ * Prepend `<!doctype html>` if the document doesn't already start with one.
36
+ *
37
+ * @param documentHtml The rendered document string.
38
+ * @returns The document guaranteed to start with a doctype declaration.
39
+ */
40
+ export declare function ensureDoctype(documentHtml: string): string;
41
+ /**
42
+ * The HMR error overlay script injected in dev mode.
43
+ * Returns the raw HTML string for the `<script>` tag.
44
+ */
45
+ export declare function developmentOverlaySnippet(): string;
46
+ /**
47
+ * Inject the dev overlay script right after `<head>`.
48
+ * Only applied when `mode === 'dev'`.
49
+ *
50
+ * @param documentHtml The rendered document string.
51
+ * @returns The document with the overlay injected.
52
+ */
53
+ export declare function injectDevelopmentOverlay(documentHtml: string): string;
54
+ /**
55
+ * For server-output builds: strip dev-time `<script type="module">` and
56
+ * `<link rel="stylesheet">` tags, then inject the production asset string
57
+ * before `</head>`.
58
+ *
59
+ * @param documentHtml The rendered document string.
60
+ * @param routeAssetsHtml The production asset tags to inject.
61
+ * @returns The document with dev assets stripped and production assets injected.
62
+ */
63
+ export declare function injectServerAssets(documentHtml: string, routeAssetsHtml: string): string;
64
+ //# sourceMappingURL=route-template-pipeline.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-template-pipeline.d.ts","sourceRoot":"","sources":["../../src/render/route-template-pipeline.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAIvC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAMhD,eAAO,MAAM,gBAAgB,QACkC,CAAC;AAEhE,eAAO,MAAM,cAAc,QAA2B,CAAC;AAIvD;;GAEG;AACH,wBAAuB,aAAa,CAAC,GAAG,SAAS,EAAE,QAAQ,EAAE,sCAM5D;AAID;;;GAGG;AACH,wBAAgB,eAAe,CAC9B,UAAU,EAAE,OAAO,CAAC,UAAU,CAAC,GAAG,SAAS,GACzC,OAAO,CAAC,UAAU,CAAC,CAQrB;AASD;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,CAClC,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM,EAAE,GAClB,MAAM,CA2BR;AAID;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAO1D;AAID;;;GAGG;AACH,wBAAgB,yBAAyB,IAAI,MAAM,CAalD;AAED;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAKrE;AAID;;;;;;;;GAQG;AACH,wBAAgB,kBAAkB,CACjC,YAAY,EAAE,MAAM,EACpB,eAAe,EAAE,MAAM,GACrB,MAAM,CAWR"}
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Pure, testable pipeline steps extracted from the route template renderer.
3
+ *
4
+ * Each function here is a focused stage of the document post-processing
5
+ * lifecycle. They are composed by `renderRouteTemplate` in
6
+ * `./route-template.ts`.
7
+ *
8
+ * @internal
9
+ */
10
+ import { Readable } from 'node:stream';
11
+ import { html } from '@gracile/internal-utils/dummy-literals';
12
+ import { LitElementRenderer } from '@lit-labs/ssr/lib/lit-element-renderer.js';
13
+ import { PAGE_ASSETS_MARKER } from './markers.js';
14
+ // ── Regexes (re-exported for testability) ────────────────────────────
15
+ export const REGEX_TAG_SCRIPT = /\s?<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script\s*>\s?/gi;
16
+ export const REGEX_TAG_LINK = /\s?<link\b[^>]*?>\s?/gi;
17
+ // ── Helpers ──────────────────────────────────────────────────────────
18
+ /**
19
+ * Concatenate multiple `Readable` streams into a single async iterable.
20
+ */
21
+ export async function* concatStreams(...readables) {
22
+ for (const readable of readables) {
23
+ for await (const chunk of readable) {
24
+ yield chunk;
25
+ }
26
+ }
27
+ }
28
+ // ── 1. Merge render info ─────────────────────────────────────────────
29
+ /**
30
+ * Merge user-provided `RenderInfo` with the default `LitElementRenderer`.
31
+ * Always appends `LitElementRenderer` to whatever the user supplied.
32
+ */
33
+ export function mergeRenderInfo(renderInfo) {
34
+ return {
35
+ ...renderInfo,
36
+ elementRenderers: [
37
+ ...(renderInfo?.elementRenderers || []),
38
+ LitElementRenderer,
39
+ ],
40
+ };
41
+ }
42
+ // ── 2. Inject sibling page assets ───────────────────────────────────
43
+ /** Regex matching JS/TS asset extensions. */
44
+ const REGEX_SCRIPT_EXT = /\.(js|ts|jsx|tsx)$/;
45
+ /** Regex matching CSS-like asset extensions. */
46
+ const REGEX_STYLE_EXT = /\.(css|scss|sass|less|styl|stylus)$/;
47
+ /**
48
+ * Inject sibling page assets into the rendered document HTML.
49
+ *
50
+ * Inserts the `PAGE_ASSETS_MARKER` before `</head>`, then replaces it
51
+ * with concrete `<script>` / `<link>` tags for each asset path.
52
+ *
53
+ * @param documentHtml The rendered document string.
54
+ * @param pageAssets Array of asset file paths (e.g. `['src/pages/about.css']`).
55
+ * @returns The document with asset tags injected (or unchanged if no assets).
56
+ */
57
+ export function injectSiblingAssets(documentHtml, pageAssets) {
58
+ return documentHtml
59
+ .replace('</head>', `\n${PAGE_ASSETS_MARKER}</head>`)
60
+ .replace(PAGE_ASSETS_MARKER, pageAssets.length > 0
61
+ ? html `<!-- PAGE ASSETS -->` +
62
+ `${pageAssets
63
+ .map((path) => {
64
+ if (REGEX_SCRIPT_EXT.test(path)) {
65
+ // prettier-ignore
66
+ return html ` <script type="module" src="/${path}"></script>`;
67
+ }
68
+ if (REGEX_STYLE_EXT.test(path)) {
69
+ // prettier-ignore
70
+ return html ` <link rel="stylesheet" href="/${path}" />`;
71
+ }
72
+ // NOTE: Never called (filtered upstream in `collectRoutes`)
73
+ return null;
74
+ })
75
+ .join('\n')}` +
76
+ `<!-- /PAGE ASSETS -->\n `
77
+ : '');
78
+ }
79
+ // ── 3. Ensure doctype ────────────────────────────────────────────────
80
+ /**
81
+ * Prepend `<!doctype html>` if the document doesn't already start with one.
82
+ *
83
+ * @param documentHtml The rendered document string.
84
+ * @returns The document guaranteed to start with a doctype declaration.
85
+ */
86
+ export function ensureDoctype(documentHtml) {
87
+ if (documentHtml.trimStart().toLocaleLowerCase().startsWith('<!doctype') ===
88
+ false)
89
+ return `<!doctype html>\n${documentHtml}`;
90
+ return documentHtml;
91
+ }
92
+ // ── 4. Inject dev overlay ────────────────────────────────────────────
93
+ /**
94
+ * The HMR error overlay script injected in dev mode.
95
+ * Returns the raw HTML string for the `<script>` tag.
96
+ */
97
+ export function developmentOverlaySnippet() {
98
+ return html `
99
+ <script type="module">
100
+ if (import.meta.hot) {
101
+ import.meta.hot.on('gracile:ssr-error', (error) => {
102
+ console.error(error.message);
103
+ });
104
+ import.meta.hot.on('error', (payload) => {
105
+ console.error(payload.err.message);
106
+ });
107
+ }
108
+ </script>
109
+ `;
110
+ }
111
+ /**
112
+ * Inject the dev overlay script right after `<head>`.
113
+ * Only applied when `mode === 'dev'`.
114
+ *
115
+ * @param documentHtml The rendered document string.
116
+ * @returns The document with the overlay injected.
117
+ */
118
+ export function injectDevelopmentOverlay(documentHtml) {
119
+ return documentHtml.replace('<head>', `<head>\n${developmentOverlaySnippet()}`);
120
+ }
121
+ // ── 5. Inject server runtime assets ─────────────────────────────────
122
+ /**
123
+ * For server-output builds: strip dev-time `<script type="module">` and
124
+ * `<link rel="stylesheet">` tags, then inject the production asset string
125
+ * before `</head>`.
126
+ *
127
+ * @param documentHtml The rendered document string.
128
+ * @param routeAssetsHtml The production asset tags to inject.
129
+ * @returns The document with dev assets stripped and production assets injected.
130
+ */
131
+ export function injectServerAssets(documentHtml, routeAssetsHtml) {
132
+ return documentHtml
133
+ .replaceAll(REGEX_TAG_SCRIPT, (s) => {
134
+ if (s.includes(`type="module"`))
135
+ return '';
136
+ return s;
137
+ })
138
+ .replaceAll(REGEX_TAG_LINK, (s) => {
139
+ if (s.includes(`rel="stylesheet"`))
140
+ return '';
141
+ return s;
142
+ })
143
+ .replace('</head>', `${routeAssetsHtml}\n</head>`);
144
+ }
@@ -1,10 +1,10 @@
1
1
  import { Readable } from 'node:stream';
2
+ import { type RenderInfo } from '@lit-labs/ssr';
2
3
  import type { ViteDevServer } from 'vite';
3
4
  import type { RouteInfos } from '../routes/match.js';
4
5
  import type * as R from '../routes/route.js';
5
- export declare const REGEX_TAG_SCRIPT: RegExp;
6
- export declare const REGEX_TAG_LINK: RegExp;
7
- export declare function renderRouteTemplate({ url, vite, mode, routeInfos, routeAssets, serverMode, docOnly, }: {
6
+ export { REGEX_TAG_SCRIPT, REGEX_TAG_LINK } from './route-template-pipeline.js';
7
+ export declare function renderRouteTemplate({ url, vite, mode, routeInfos, routeAssets, serverMode, docOnly, renderInfo, }: {
8
8
  url: string;
9
9
  vite?: ViteDevServer | undefined;
10
10
  mode: 'dev' | 'build';
@@ -13,6 +13,7 @@ export declare function renderRouteTemplate({ url, vite, mode, routeInfos, route
13
13
  root: string;
14
14
  serverMode?: boolean | undefined;
15
15
  docOnly?: boolean | undefined;
16
+ renderInfo?: Partial<RenderInfo> | undefined;
16
17
  }): Promise<{
17
18
  output: null | Readable;
18
19
  document: null | string;
@@ -1 +1 @@
1
- {"version":3,"file":"route-template.d.ts","sourceRoot":"","sources":["../../src/render/route-template.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAOvC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,MAAM,CAAC;AAO1C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,KAAK,KAAK,CAAC,MAAM,oBAAoB,CAAC;AAY7C,eAAO,MAAM,gBAAgB,QACkC,CAAC;AAEhE,eAAO,MAAM,cAAc,QAA2B,CAAC;AAEvD,wBAAsB,mBAAmB,CAAC,EACzC,GAAG,EACH,IAAI,EACJ,IAAI,EACJ,UAAU,EACV,WAAW,EACX,UAAU,EACV,OAAO,GACP,EAAE;IACF,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,CAAC,EAAE,aAAa,GAAG,SAAS,CAAC;IACjC,IAAI,EAAE,KAAK,GAAG,OAAO,CAAC;IACtB,UAAU,EAAE,UAAU,CAAC;IACvB,WAAW,CAAC,EAAE,CAAC,CAAC,YAAY,GAAG,SAAS,CAAC;IACzC,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IACjC,OAAO,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;CAC9B,GAAG,OAAO,CAAC;IAAE,MAAM,EAAE,IAAI,GAAG,QAAQ,CAAC;IAAC,QAAQ,EAAE,IAAI,GAAG,MAAM,CAAA;CAAE,CAAC,CA8NhE"}
1
+ {"version":3,"file":"route-template.d.ts","sourceRoot":"","sources":["../../src/render/route-template.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAIvC,OAAO,EAA0B,KAAK,UAAU,EAAE,MAAM,eAAe,CAAC;AAExE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,MAAM,CAAC;AAO1C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,KAAK,KAAK,CAAC,MAAM,oBAAoB,CAAC;AAa7C,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAEhF,wBAAsB,mBAAmB,CAAC,EACzC,GAAG,EACH,IAAI,EACJ,IAAI,EACJ,UAAU,EACV,WAAW,EACX,UAAU,EACV,OAAO,EACP,UAAU,GACV,EAAE;IACF,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,CAAC,EAAE,aAAa,GAAG,SAAS,CAAC;IACjC,IAAI,EAAE,KAAK,GAAG,OAAO,CAAC;IACtB,UAAU,EAAE,UAAU,CAAC;IACvB,WAAW,CAAC,EAAE,CAAC,CAAC,YAAY,GAAG,SAAS,CAAC;IACzC,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IACjC,OAAO,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAC9B,UAAU,CAAC,EAAE,OAAO,CAAC,UAAU,CAAC,GAAG,SAAS,CAAC;CAC7C,GAAG,OAAO,CAAC;IAAE,MAAM,EAAE,IAAI,GAAG,QAAQ,CAAC;IAAC,QAAQ,EAAE,IAAI,GAAG,MAAM,CAAA;CAAE,CAAC,CAwJhE"}