@ecopages/lit 0.2.0-alpha.8 → 0.2.1

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/CHANGELOG.md CHANGED
@@ -4,21 +4,16 @@ All notable changes to `@ecopages/lit` are documented here.
4
4
 
5
5
  > **Note:** Changelog tracking begins at version `0.2.0`. Changes prior to this release are not recorded here but are available in the git history.
6
6
 
7
- ## [UNRELEASED] — TBD
8
-
9
- ### Features
10
-
11
- - Aligned Lit with the unified orchestration pipeline and the shared lazy dependency and global injector flow.
7
+ ## [0.2.1] — 2026-04-16
12
8
 
13
9
  ### Bug Fixes
14
10
 
15
- - Prevented the shared Lit hydrate-support bootstrap from re-running on every browser-router navigation.
16
- - Routed Lit renderer output through Lit's static SSR template pipeline so registered custom elements render declarative shadow DOM during SSR instead of staying as bare host tags.
11
+ - Fixed Lit document-shell composition, declarative shadow DOM SSR, nested child serialization, lazy preload handling, explicit render paths, and mixed-renderer boundary resolution.
17
12
 
18
- ### Refactoring
13
+ ### Documentation
19
14
 
20
- - Cleaned up ambient module declarations.
15
+ - Updated the README to document `.lit.tsx` route ownership, standalone setup, and mixed-renderer Lit boundary handling.
21
16
 
22
17
  ### Tests
23
18
 
24
- - Updated integration coverage for the orchestration pipeline and Node and esbuild compatibility.
19
+ - Updated integration coverage for explicit boundary composition and Node and esbuild compatibility.
package/README.md CHANGED
@@ -1,8 +1,6 @@
1
1
  # @ecopages/lit
2
2
 
3
- Integration plugin for [Lit](https://lit.dev/) web components in Ecopages.
4
-
5
- This integration is optimized for use alongside `@ecopages/kitajs` (or another HTML JSX engine), allowing you to author your pages in Kitajs JSX templates while embedding interactive Lit components where needed.
3
+ Integration plugin for [Lit](https://lit.dev/) in Ecopages. Use it when Lit should own `.lit.tsx` routes or when another integration needs Lit to render nested custom-element boundaries.
6
4
 
7
5
  ## Installation
8
6
 
@@ -12,7 +10,21 @@ bunx jsr add @ecopages/lit
12
10
 
13
11
  ## Usage
14
12
 
15
- It is recommended to use `@ecopages/lit` in conjunction with `@ecopages/kitajs`. Configure your project to include both integrations in your `eco.config.ts`:
13
+ Register `litPlugin()` in your `eco.config.ts`.
14
+
15
+ ```ts
16
+ import { ConfigBuilder } from '@ecopages/core/config-builder';
17
+ import { litPlugin } from '@ecopages/lit';
18
+
19
+ const config = await new ConfigBuilder()
20
+ .setBaseUrl(import.meta.env.ECOPAGES_BASE_URL)
21
+ .setIntegrations([litPlugin()])
22
+ .build();
23
+
24
+ export default config;
25
+ ```
26
+
27
+ Lit also works well alongside an HTML-first renderer such as `@ecopages/kitajs` when you want Lit to own only the nested custom elements:
16
28
 
17
29
  ```ts
18
30
  import { ConfigBuilder } from '@ecopages/core/config-builder';
@@ -27,4 +39,14 @@ const config = await new ConfigBuilder()
27
39
  export default config;
28
40
  ```
29
41
 
30
- This setup enables server-rendered KitaJS pages that embed and hydrate Lit custom elements on the client.
42
+ This setup lets Kita own the page shell while Lit owns the nested Lit component boundaries.
43
+
44
+ ## What This Integration Owns
45
+
46
+ - `.lit.tsx` route files.
47
+ - Nested Lit component boundaries rendered inside pages owned by other integrations.
48
+ - The Lit hydration support script required for SSR custom elements and declarative shadow DOM.
49
+
50
+ ## Mixed Rendering
51
+
52
+ When a non-Lit render pass enters a Lit-owned component boundary, Ecopages hands that boundary to the Lit renderer. That keeps Lit SSR in charge of custom elements, declarative shadow DOM, and Lit-managed child content.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/lit",
3
- "version": "0.2.0-alpha.8",
3
+ "version": "0.2.1",
4
4
  "description": "Ecopages lit integration",
5
5
  "keywords": [
6
6
  "ecopages",
@@ -31,7 +31,7 @@
31
31
  "directory": "packages/integrations/lit"
32
32
  },
33
33
  "peerDependencies": {
34
- "@ecopages/core": "0.2.0-alpha.8",
34
+ "@ecopages/core": "0.2.1",
35
35
  "@lit-labs/ssr": "^3.3.0",
36
36
  "@lit-labs/ssr-client": "^1.1.7",
37
37
  "lit": "^3.2.1"
@@ -3,20 +3,37 @@
3
3
  * @module
4
4
  */
5
5
  import type { ComponentRenderInput, ComponentRenderResult, EcoComponent, EcoPagesElement, IntegrationRendererRenderOptions, RouteRendererBody } from '@ecopages/core';
6
+ import '@lit-labs/ssr/lib/install-global-dom-shim.js';
6
7
  import { IntegrationRenderer, type RenderToResponseContext } from '@ecopages/core/route-renderer/integration-renderer';
7
8
  /**
8
9
  * A renderer for the Lit integration.
9
10
  */
10
11
  export declare class LitRenderer extends IntegrationRenderer<EcoPagesElement> {
11
12
  name: string;
13
+ private resolveQueuedBoundaryChildren;
14
+ private resolveQueuedBoundaryHtml;
15
+ private normalizeDeclarativeShadowRootMarkup;
12
16
  private createRenderableMarkup;
17
+ protected shouldRenderPageComponent(): boolean;
13
18
  private renderMarkupToString;
19
+ private renderValueToString;
20
+ private isLitManagedComponent;
21
+ private injectRenderedChildren;
22
+ private renderHtmlTemplate;
14
23
  /**
15
24
  * Renders a Lit component boundary for component-level orchestration.
16
25
  *
26
+ * SSR-eligible lazy scripts are preloaded first so custom elements registered
27
+ * by the component can render their server markup even when the Lit renderer is
28
+ * entered through cross-integration boundary handoff.
29
+ *
17
30
  * Includes component-scoped dependency assets when declared.
18
31
  */
19
32
  renderComponent(input: ComponentRenderInput): Promise<ComponentRenderResult>;
33
+ protected createComponentBoundaryRuntime(options: {
34
+ boundaryInput: ComponentRenderInput;
35
+ rendererCache: Map<string, IntegrationRenderer<any>>;
36
+ }): import("@ecopages/core").ComponentBoundaryRuntime;
20
37
  private readonly ssrLazyPreloader;
21
38
  /**
22
39
  * Detects preload failures that are expected for browser-only modules.
@@ -1,43 +1,167 @@
1
+ import "@lit-labs/ssr/lib/install-global-dom-shim.js";
1
2
  import { IntegrationRenderer } from "@ecopages/core/route-renderer/integration-renderer";
2
3
  import { render } from "@lit-labs/ssr";
3
- import { RenderResultReadable } from "@lit-labs/ssr/lib/render-result-readable.js";
4
4
  import { html as staticHtml, unsafeStatic } from "lit/static-html.js";
5
5
  import { LitSsrLazyPreloader } from "./lit-ssr-lazy-preloader.js";
6
6
  import { PLUGIN_NAME } from "./lit.plugin.js";
7
+ const HTML_TEMPLATE_SLOT_MARKER = "<--content-->";
8
+ const COMPONENT_CHILDREN_SLOT_MARKER = "<!--eco-lit-component-children-->";
9
+ const ESCAPED_COMPONENT_CHILDREN_SLOT_MARKER = "&lt;!--eco-lit-component-children--&gt;";
10
+ const DOUBLE_ESCAPED_COMPONENT_CHILDREN_SLOT_MARKER = "&amp;lt;!--eco-lit-component-children--&amp;gt;";
11
+ const DUPLICATE_DECLARATIVE_SHADOW_ROOT_ATTRIBUTE = /\sshadowroot=(['"])(open|closed)\1(?=\sshadowrootmode=\1\2\1)/g;
7
12
  class LitRenderer extends IntegrationRenderer {
8
13
  name = PLUGIN_NAME;
14
+ async resolveQueuedBoundaryChildren(children, queuedResolutionsByToken, resolveToken) {
15
+ if (children === void 0) {
16
+ return void 0;
17
+ }
18
+ let renderedChildren = typeof children === "string" ? children : await this.renderValueToString(children);
19
+ renderedChildren = await this.resolveQueuedBoundaryTokens(
20
+ renderedChildren,
21
+ queuedResolutionsByToken,
22
+ resolveToken
23
+ );
24
+ return renderedChildren;
25
+ }
26
+ async resolveQueuedBoundaryHtml(html, runtimeContext) {
27
+ const queuedBoundaryResolution = await this.resolveRendererOwnedQueuedBoundaryHtml({
28
+ html,
29
+ runtimeContext,
30
+ queueLabel: "Lit",
31
+ renderQueuedChildren: async (children, _runtimeContext, queuedResolutionsByToken, resolveToken) => {
32
+ const renderedChildren = await this.resolveQueuedBoundaryChildren(
33
+ children,
34
+ queuedResolutionsByToken,
35
+ resolveToken
36
+ );
37
+ return {
38
+ assets: [],
39
+ html: renderedChildren
40
+ };
41
+ }
42
+ });
43
+ return {
44
+ html: queuedBoundaryResolution.html,
45
+ assets: queuedBoundaryResolution.assets.length > 0 ? queuedBoundaryResolution.assets : void 0
46
+ };
47
+ }
48
+ normalizeDeclarativeShadowRootMarkup(markup) {
49
+ return markup.replace(DUPLICATE_DECLARATIVE_SHADOW_ROOT_ATTRIBUTE, "");
50
+ }
9
51
  createRenderableMarkup(markup) {
10
52
  return staticHtml`${unsafeStatic(markup)}`;
11
53
  }
54
+ shouldRenderPageComponent() {
55
+ return false;
56
+ }
12
57
  async renderMarkupToString(markup) {
13
58
  let renderedHtml = "";
14
59
  for (const chunk of render(this.createRenderableMarkup(markup))) {
15
60
  renderedHtml += chunk;
16
61
  }
17
- return renderedHtml;
62
+ return this.normalizeDeclarativeShadowRootMarkup(renderedHtml);
63
+ }
64
+ async renderValueToString(value) {
65
+ if (typeof value === "string") {
66
+ return await this.renderMarkupToString(value);
67
+ }
68
+ let renderedHtml = "";
69
+ for (const chunk of render(value)) {
70
+ renderedHtml += chunk;
71
+ }
72
+ return this.normalizeDeclarativeShadowRootMarkup(renderedHtml);
73
+ }
74
+ isLitManagedComponent(component) {
75
+ return component?.config?.integration === this.name || component?.config?.__eco?.integration === this.name;
76
+ }
77
+ injectRenderedChildren(template, renderedChildren) {
78
+ for (const marker of [
79
+ COMPONENT_CHILDREN_SLOT_MARKER,
80
+ ESCAPED_COMPONENT_CHILDREN_SLOT_MARKER,
81
+ DOUBLE_ESCAPED_COMPONENT_CHILDREN_SLOT_MARKER
82
+ ]) {
83
+ if (template.includes(marker)) {
84
+ return template.split(marker).join(renderedChildren);
85
+ }
86
+ }
87
+ if (template.includes(HTML_TEMPLATE_SLOT_MARKER)) {
88
+ return template.split(HTML_TEMPLATE_SLOT_MARKER).join(renderedChildren);
89
+ }
90
+ if (template.includes("</body>")) {
91
+ return template.replace("</body>", `${renderedChildren}</body>`);
92
+ }
93
+ if (template.includes("</html>")) {
94
+ return template.replace("</html>", `${renderedChildren}</html>`);
95
+ }
96
+ return `${template}${renderedChildren}`;
97
+ }
98
+ async renderHtmlTemplate(options) {
99
+ if (!options.isLitManagedHtmlTemplate) {
100
+ return String(
101
+ await options.HtmlTemplate({
102
+ metadata: options.metadata,
103
+ children: options.renderedChildren,
104
+ pageProps: options.pageProps
105
+ })
106
+ );
107
+ }
108
+ const template = await options.HtmlTemplate({
109
+ metadata: options.metadata,
110
+ children: HTML_TEMPLATE_SLOT_MARKER,
111
+ pageProps: options.pageProps
112
+ });
113
+ return this.injectRenderedChildren(String(template), options.renderedChildren);
18
114
  }
19
115
  /**
20
116
  * Renders a Lit component boundary for component-level orchestration.
21
117
  *
118
+ * SSR-eligible lazy scripts are preloaded first so custom elements registered
119
+ * by the component can render their server markup even when the Lit renderer is
120
+ * entered through cross-integration boundary handoff.
121
+ *
22
122
  * Includes component-scoped dependency assets when declared.
23
123
  */
24
124
  async renderComponent(input) {
125
+ await this.preloadSsrLazyScripts([input.component]);
25
126
  const component = input.component;
26
- const props = input.children === void 0 ? input.props : { ...input.props, children: input.children };
127
+ let renderedChildren;
128
+ if (input.children !== void 0) {
129
+ renderedChildren = typeof input.children === "string" ? input.children : await this.renderValueToString(input.children);
130
+ }
131
+ let props = input.props;
132
+ if (renderedChildren !== void 0) {
133
+ props = {
134
+ ...input.props,
135
+ children: COMPONENT_CHILDREN_SLOT_MARKER
136
+ };
137
+ }
27
138
  const content = await component(props);
28
- const markup = String(content);
29
- const html = await this.renderMarkupToString(markup);
139
+ const renderedHtml = await this.renderValueToString(content);
140
+ const html = renderedChildren === void 0 ? renderedHtml : this.injectRenderedChildren(renderedHtml, renderedChildren);
141
+ const queuedBoundaryResolution = await this.resolveQueuedBoundaryHtml(
142
+ html,
143
+ this.getQueuedBoundaryRuntime(input)
144
+ );
30
145
  const hasDependencies = Boolean(input.component.config?.dependencies);
31
146
  const canResolveAssets = typeof this.assetProcessingService?.processDependencies === "function";
32
147
  const assets = hasDependencies && canResolveAssets ? await this.processComponentDependencies([input.component]) : void 0;
33
148
  return {
34
- html,
149
+ html: queuedBoundaryResolution.html,
35
150
  canAttachAttributes: true,
36
- rootTag: this.getRootTagName(markup),
151
+ rootTag: this.getRootTagName(queuedBoundaryResolution.html),
37
152
  integrationName: this.name,
38
- assets
153
+ assets: this.htmlTransformer.dedupeProcessedAssets([
154
+ ...assets ?? [],
155
+ ...queuedBoundaryResolution.assets ?? []
156
+ ])
39
157
  };
40
158
  }
159
+ createComponentBoundaryRuntime(options) {
160
+ return this.createQueuedBoundaryRuntime({
161
+ boundaryInput: options.boundaryInput,
162
+ rendererCache: options.rendererCache
163
+ });
164
+ }
41
165
  ssrLazyPreloader = new LitSsrLazyPreloader({
42
166
  resolveDependencyPath: this.resolveDependencyPath.bind(this),
43
167
  processDependencies: this.assetProcessingService?.processDependencies?.bind(this.assetProcessingService)
@@ -88,74 +212,68 @@ class LitRenderer extends IntegrationRenderer {
88
212
  }) {
89
213
  try {
90
214
  await this.preloadSsrLazyScripts([Page, Layout]);
91
- const pageContent = await Page({ params, query, ...props, locals });
92
- const children = Layout ? await Layout(
93
- {
94
- children: pageContent,
95
- locals
96
- }
97
- ) : pageContent;
98
- const template = await HtmlTemplate({
215
+ return await this.renderPageWithDocumentShell({
216
+ page: {
217
+ component: Page,
218
+ props: {
219
+ params,
220
+ query,
221
+ ...props,
222
+ locals
223
+ }
224
+ },
225
+ layout: Layout ? {
226
+ component: Layout,
227
+ props: locals ? { locals } : {}
228
+ } : void 0,
229
+ htmlTemplate: HtmlTemplate,
99
230
  metadata,
100
- children: "<--content-->",
101
- pageProps: props || {}
231
+ pageProps: props || {},
232
+ transformDocumentHtml: (html) => this.normalizeDeclarativeShadowRootMarkup(html)
102
233
  });
103
- const [templateStart, templateEnd] = template.split("<--content-->");
104
- const DOC_TYPE = this.DOC_TYPE;
105
- function* streamBody() {
106
- yield DOC_TYPE;
107
- yield templateStart;
108
- yield* render(staticHtml`${unsafeStatic(children)}`);
109
- yield templateEnd;
110
- }
111
- return new RenderResultReadable(streamBody());
112
234
  } catch (error) {
113
235
  throw this.createRenderError("Error rendering page", error);
114
236
  }
115
237
  }
116
238
  async renderToResponse(view, props, ctx) {
117
239
  try {
118
- const viewConfig = view.config;
119
- const Layout = viewConfig?.layout;
120
- await this.preloadSsrLazyScripts([view, Layout]);
121
- const viewFn = view;
122
- const pageContent = await viewFn(props);
123
240
  if (ctx.partial) {
124
- function* streamBody2() {
125
- yield* render(staticHtml`${unsafeStatic(pageContent)}`);
126
- }
127
- const readable = new RenderResultReadable(streamBody2());
128
- return this.createHtmlResponse(readable, ctx);
241
+ return this.renderPartialViewResponse({
242
+ view,
243
+ props,
244
+ ctx,
245
+ transformHtml: (html) => this.normalizeDeclarativeShadowRootMarkup(html)
246
+ });
129
247
  }
130
- const DOC_TYPE = this.DOC_TYPE;
131
- const children = Layout ? await Layout({ children: pageContent }) : pageContent;
248
+ const viewConfig = view.config;
249
+ const Layout = viewConfig?.layout;
132
250
  const HtmlTemplate = await this.getHtmlTemplate();
133
- const metadata = view.metadata ? await view.metadata({
134
- params: {},
135
- query: {},
136
- props,
137
- appConfig: this.appConfig
138
- }) : this.appConfig.defaultMetadata;
251
+ const metadata = await this.resolveViewMetadata(view, props);
252
+ await this.preloadSsrLazyScripts([view, Layout]);
139
253
  await this.prepareViewDependencies(view, Layout);
140
- const template = await HtmlTemplate({
141
- metadata,
142
- children: "<--content-->",
143
- pageProps: props
254
+ const pageRender = await this.renderComponentBoundary({
255
+ component: view,
256
+ props: props ?? {}
144
257
  });
145
- const [templateStart, templateEnd] = template.split("<--content-->");
146
- function* streamBody() {
147
- yield DOC_TYPE;
148
- yield templateStart;
149
- yield* render(staticHtml`${unsafeStatic(children)}`);
150
- yield templateEnd;
151
- }
152
- const stream = new RenderResultReadable(streamBody());
153
- const transformedResponse = await this.htmlTransformer.transform(
154
- new Response(stream, {
155
- headers: { "Content-Type": "text/html" }
156
- })
157
- );
158
- return this.createHtmlResponse(transformedResponse.body, ctx);
258
+ const layoutRender = Layout ? await this.renderComponentBoundary({
259
+ component: Layout,
260
+ props: {},
261
+ children: pageRender.html
262
+ }) : void 0;
263
+ const documentRender = await this.renderComponentBoundary({
264
+ component: HtmlTemplate,
265
+ props: {
266
+ metadata,
267
+ pageProps: props ?? {}
268
+ },
269
+ children: layoutRender?.html ?? pageRender.html
270
+ });
271
+ this.appendProcessedDependencies(pageRender.assets, layoutRender?.assets, documentRender.assets);
272
+ const body = await this.finalizeResolvedHtml({
273
+ html: `${this.DOC_TYPE}${this.normalizeDeclarativeShadowRootMarkup(documentRender.html)}`,
274
+ partial: false
275
+ });
276
+ return this.createHtmlResponse(body, ctx);
159
277
  } catch (error) {
160
278
  throw this.createRenderError("Error rendering view", error);
161
279
  }
@@ -6,6 +6,7 @@ type ProcessDependencies = (dependencies: AssetDefinition[], integrationName: st
6
6
  export interface LitSsrLazyPreloaderOptions {
7
7
  resolveDependencyPath: (componentDir: string, sourcePath: string) => string;
8
8
  processDependencies?: ProcessDependencies;
9
+ preferSourceImports?: boolean;
9
10
  }
10
11
  /**
11
12
  * Encapsulates SSR lazy script preload behavior for Lit components.
@@ -17,10 +18,11 @@ export interface LitSsrLazyPreloaderOptions {
17
18
  export declare class LitSsrLazyPreloader {
18
19
  private readonly resolveDependencyPath;
19
20
  private readonly processDependencies?;
21
+ private readonly preferSourceImports;
20
22
  private readonly ssrPreloadedScripts;
21
23
  private readonly ssrPreloadFailedScripts;
22
24
  private readonly ssrPreloadEntrypointCache;
23
- constructor({ resolveDependencyPath, processDependencies }: LitSsrLazyPreloaderOptions);
25
+ constructor({ resolveDependencyPath, processDependencies, preferSourceImports }: LitSsrLazyPreloaderOptions);
24
26
  /**
25
27
  * Detects preload failures that are expected for browser-only modules.
26
28
  */
@@ -4,12 +4,14 @@ import { pathToFileURL } from "node:url";
4
4
  class LitSsrLazyPreloader {
5
5
  resolveDependencyPath;
6
6
  processDependencies;
7
+ preferSourceImports;
7
8
  ssrPreloadedScripts = /* @__PURE__ */ new Set();
8
9
  ssrPreloadFailedScripts = /* @__PURE__ */ new Set();
9
10
  ssrPreloadEntrypointCache = /* @__PURE__ */ new Map();
10
- constructor({ resolveDependencyPath, processDependencies }) {
11
+ constructor({ resolveDependencyPath, processDependencies, preferSourceImports }) {
11
12
  this.resolveDependencyPath = resolveDependencyPath;
12
13
  this.processDependencies = processDependencies;
14
+ this.preferSourceImports = preferSourceImports ?? typeof Bun !== "undefined";
13
15
  }
14
16
  /**
15
17
  * Detects preload failures that are expected for browser-only modules.
@@ -87,7 +89,10 @@ class LitSsrLazyPreloader {
87
89
  return;
88
90
  }
89
91
  try {
90
- await import(pathToFileURL(preloadEntrypoint).href);
92
+ await import(
93
+ /* @vite-ignore */
94
+ pathToFileURL(preloadEntrypoint).href
95
+ );
91
96
  this.ssrPreloadedScripts.add(scriptPath);
92
97
  } catch (error) {
93
98
  this.ssrPreloadFailedScripts.add(scriptPath);
@@ -112,7 +117,12 @@ class LitSsrLazyPreloader {
112
117
  if (cachedEntrypoint) {
113
118
  return cachedEntrypoint;
114
119
  }
120
+ if (this.preferSourceImports) {
121
+ this.ssrPreloadEntrypointCache.set(scriptPath, scriptPath);
122
+ return scriptPath;
123
+ }
115
124
  if (!this.processDependencies) {
125
+ this.ssrPreloadEntrypointCache.set(scriptPath, scriptPath);
116
126
  return scriptPath;
117
127
  }
118
128
  try {
@@ -140,6 +150,7 @@ class LitSsrLazyPreloader {
140
150
  if (process.env.ECOPAGES_DEBUG === "true") {
141
151
  console.warn(`[ecopages][lit] Failed to resolve SSR preload entrypoint for: ${scriptPath}`, error);
142
152
  }
153
+ this.ssrPreloadEntrypointCache.set(scriptPath, scriptPath);
143
154
  return scriptPath;
144
155
  }
145
156
  }
@@ -2,8 +2,7 @@
2
2
  * This module contains the Lit plugin
3
3
  * @module
4
4
  */
5
- import '@lit-labs/ssr/lib/install-global-dom-shim.js';
6
- import './console';
5
+ import './console.js';
7
6
  import { IntegrationPlugin, type IntegrationPluginConfig } from '@ecopages/core/plugins/integration-plugin';
8
7
  import { type AssetDefinition } from '@ecopages/core/services/asset-processing-service';
9
8
  import { LitRenderer } from './lit-renderer.js';
package/src/lit.plugin.js CHANGED
@@ -1,5 +1,4 @@
1
- import "@lit-labs/ssr/lib/install-global-dom-shim.js";
2
- import "./console";
1
+ import "./console.js";
3
2
  import { IntegrationPlugin } from "@ecopages/core/plugins/integration-plugin";
4
3
  import { AssetFactory } from "@ecopages/core/services/asset-processing-service";
5
4
  import { litElementHydrateScript } from "./lit-element-hydrate.js";
package/src/console.ts DELETED
@@ -1,19 +0,0 @@
1
- const originalConsoleWarn = console.warn;
2
-
3
- /**
4
- * Suppresses the warning about CustomElementRegistry already being defined in ssr-dom-shim by lit
5
- * https://github.com/lit/lit/blob/bd881370b83d366f7654dd510731242a68949a20/packages/labs/ssr-dom-shim/src/index.ts#L140
6
- * Complete Error Log:
7
- * 'CustomElementRegistry' already has "lit-counter" defined. This may have been caused by live reload or hot module replacement in which case it can be safely ignored.
8
- * Make sure to test your application with a production build as repeat registrations will throw in production.
9
- */
10
- console.warn = (...messages: any[]) => {
11
- if (
12
- messages.some(
13
- (message) => typeof message === 'string' && message.includes("'CustomElementRegistry' already has"),
14
- )
15
- ) {
16
- return;
17
- }
18
- originalConsoleWarn.apply(console, messages);
19
- };
@@ -1,2 +0,0 @@
1
- export const litElementHydrateScript =
2
- 'var k=globalThis,y=k.trustedTypes,p=y?y.createPolicy("lit-html",{createHTML:(q)=>q}):void 0;var P=`lit$${Math.random().toFixed(9).slice(2)}$`,v="?"+P,Kq=`<${v}>`,x=document,C=()=>x.createComment(""),S=(q)=>q===null||typeof q!="object"&&typeof q!="function",L=Array.isArray,h=(q)=>L(q)||typeof q?.[Symbol.iterator]=="function";var U=/<(?:(!--|\\/[^a-zA-Z])|(\\/?[a-zA-Z][^>\\s]*)|(\\/?$))/g,m=/-->/g,a=/>/g,$=/>|[ \\t\\n\\f\\r](?:([^\\s"\'>=\\/]+)([ \\t\\n\\f\\r]*=[ \\t\\n\\f\\r]*(?:[^ \\t\\n\\f\\r"\'\\`<>=]|("|\')|))|$)/g,c=/\'/g,l=/"/g,r=/^(?:script|style|textarea|title)$/i,M=(q)=>(D,...F)=>({_$litType$:q,strings:D,values:F}),Aq=M(1),Pq=M(2),Vq=M(3),V=Symbol.for("lit-noChange"),B=Symbol.for("lit-nothing"),n=new WeakMap,w=x.createTreeWalker(x,129);function o(q,D){if(!L(q)||!q.hasOwnProperty("raw"))throw Error("invalid template strings array");return p!==void 0?p.createHTML(D):D}var e=(q,D)=>{let F=q.length-1,J=[],G,O=D===2?"<svg>":D===3?"<math>":"",K=U;for(let W=0;W<F;W++){let Q=q[W],Y,X,b=-1,A=0;while(A<Q.length&&(K.lastIndex=A,X=K.exec(Q),X!==null))A=K.lastIndex,K===U?X[1]==="!--"?K=m:X[1]!==void 0?K=a:X[2]!==void 0?(r.test(X[2])&&(G=RegExp("</"+X[2],"g")),K=$):X[3]!==void 0&&(K=$):K===$?X[0]===">"?(K=G??U,b=-1):X[1]===void 0?b=-2:(b=K.lastIndex-X[2].length,Y=X[1],K=X[3]===void 0?$:X[3]===\'"\'?l:c):K===l||K===c?K=$:K===m||K===a?K=U:(K=$,G=void 0);const _=K===$&&q[W+1].startsWith("/>")?" ":"";O+=K===U?Q+Kq:b>=0?(J.push(Y),Q.slice(0,b)+"$lit$"+Q.slice(b)+P+_):Q+P+(b===-2?W:_)}return[o(q,O+(q[F]||"<?>")+(D===2?"</svg>":D===3?"</math>":"")),J]};class g{constructor({strings:q,_$litType$:D},F){let J;this.parts=[];let G=0,O=0,K=q.length-1,W=this.parts,[Q,Y]=e(q,D);if(this.el=g.createElement(Q,F),w.currentNode=this.el.content,D===2||D===3){const X=this.el.content.firstChild;X.replaceWith(...X.childNodes)}while((J=w.nextNode())!==null&&W.length<K){if(J.nodeType===1){if(J.hasAttributes())for(const X of J.getAttributeNames())if(X.endsWith("$lit$")){const b=Y[O++],A=J.getAttribute(X).split(P),_=/([.?@])?(.*)/.exec(b);W.push({type:1,index:G,name:_[2],strings:A,ctor:_[1]==="."?R:_[1]==="?"?E:_[1]==="@"?d:I}),J.removeAttribute(X)}else X.startsWith(P)&&(W.push({type:6,index:G}),J.removeAttribute(X));if(r.test(J.tagName)){const X=J.textContent.split(P),b=X.length-1;if(b>0){J.textContent=y?y.emptyScript:"";for(let A=0;A<b;A++)J.append(X[A],C()),w.nextNode(),W.push({type:2,index:++G});J.append(X[b],C())}}}else if(J.nodeType===8)if(J.data===v)W.push({type:2,index:G});else{let X=-1;while((X=J.data.indexOf(P,X+1))!==-1)W.push({type:7,index:G}),X+=P.length-1}G++}}static createElement(q,D){const F=x.createElement("template");return F.innerHTML=q,F}}function z(q,D,F=q,J){if(D===V)return D;let G=J!==void 0?F._$Co?.[J]:F._$Cl,O=S(D)?void 0:D._$litDirective$;return G?.constructor!==O&&(G?._$AO?.(!1),O===void 0?G=void 0:(G=new O(q),G._$AT(q,F,J)),J!==void 0?(F._$Co??=[])[J]=G:F._$Cl=G),G!==void 0&&(D=z(q,G._$AS(q,D.values),G,J)),D}class j{constructor(q,D){this._$AV=[],this._$AN=void 0,this._$AD=q,this._$AM=D}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(q){const{el:{content:D},parts:F}=this._$AD,J=(q?.creationScope??x).importNode(D,!0);w.currentNode=J;let G=w.nextNode(),O=0,K=0,W=F[0];while(W!==void 0){if(O===W.index){let Q;W.type===2?Q=new H(G,G.nextSibling,this,q):W.type===1?Q=new W.ctor(G,W.name,W.strings,this,q):W.type===6&&(Q=new f(G,this,q)),this._$AV.push(Q),W=F[++K]}O!==W?.index&&(G=w.nextNode(),O++)}return w.currentNode=x,J}p(q){let D=0;for(const F of this._$AV)F!==void 0&&(F.strings!==void 0?(F._$AI(q,F,D),D+=F.strings.length-2):F._$AI(q[D])),D++}}class H{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(q,D,F,J){this.type=2,this._$AH=B,this._$AN=void 0,this._$AA=q,this._$AB=D,this._$AM=F,this.options=J,this._$Cv=J?.isConnected??!0}get parentNode(){let q=this._$AA.parentNode,D=this._$AM;return D!==void 0&&q?.nodeType===11&&(q=D.parentNode),q}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(q,D=this){q=z(this,q,D),S(q)?q===B||q==null||q===""?(this._$AH!==B&&this._$AR(),this._$AH=B):q!==this._$AH&&q!==V&&this._(q):q._$litType$!==void 0?this.$(q):q.nodeType!==void 0?this.T(q):h(q)?this.k(q):this._(q)}O(q){return this._$AA.parentNode.insertBefore(q,this._$AB)}T(q){this._$AH!==q&&(this._$AR(),this._$AH=this.O(q))}_(q){this._$AH!==B&&S(this._$AH)?this._$AA.nextSibling.data=q:this.T(x.createTextNode(q)),this._$AH=q}$(q){const{values:D,_$litType$:F}=q,J=typeof F=="number"?this._$AC(q):(F.el===void 0&&(F.el=g.createElement(o(F.h,F.h[0]),this.options)),F);if(this._$AH?._$AD===J)this._$AH.p(D);else{const G=new j(J,this),O=G.u(this.options);G.p(D),this.T(O),this._$AH=G}}_$AC(q){let D=n.get(q.strings);return D===void 0&&n.set(q.strings,D=new g(q)),D}k(q){L(this._$AH)||(this._$AH=[],this._$AR());let D=this._$AH,F,J=0;for(const G of q)J===D.length?D.push(F=new H(this.O(C()),this.O(C()),this,this.options)):F=D[J],F._$AI(G),J++;J<D.length&&(this._$AR(F&&F._$AB.nextSibling,J),D.length=J)}_$AR(q=this._$AA.nextSibling,D){for(this._$AP?.(!1,!0,D);q&&q!==this._$AB;){const F=q.nextSibling;q.remove(),q=F}}setConnected(q){this._$AM===void 0&&(this._$Cv=q,this._$AP?.(q))}}class I{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(q,D,F,J,G){this.type=1,this._$AH=B,this._$AN=void 0,this.element=q,this.name=D,this._$AM=J,this.options=G,F.length>2||F[0]!==""||F[1]!==""?(this._$AH=Array(F.length-1).fill(new String),this.strings=F):this._$AH=B}_$AI(q,D=this,F,J){let G=this.strings,O=!1;if(G===void 0)q=z(this,q,D,0),O=!S(q)||q!==this._$AH&&q!==V,O&&(this._$AH=q);else{let K=q,W,Q;for(q=G[0],W=0;W<G.length-1;W++)Q=z(this,K[F+W],D,W),Q===V&&(Q=this._$AH[W]),O||=!S(Q)||Q!==this._$AH[W],Q===B?q=B:q!==B&&(q+=(Q??"")+G[W+1]),this._$AH[W]=Q}O&&!J&&this.j(q)}j(q){q===B?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,q??"")}}class R extends I{constructor(){super(...arguments),this.type=3}j(q){this.element[this.name]=q===B?void 0:q}}class E extends I{constructor(){super(...arguments),this.type=4}j(q){this.element.toggleAttribute(this.name,!!q&&q!==B)}}class d extends I{constructor(q,D,F,J,G){super(q,D,F,J,G),this.type=5}_$AI(q,D=this){if((q=z(this,q,D,0)??B)===V)return;const F=this._$AH,J=q===B&&F!==B||q.capture!==F.capture||q.once!==F.once||q.passive!==F.passive,G=q!==B&&(F===B||J);J&&this.element.removeEventListener(this.name,this,F),G&&this.element.addEventListener(this.name,this,q),this._$AH=q}handleEvent(q){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,q):this._$AH.handleEvent(q)}}class f{constructor(q,D,F){this.element=q,this.type=6,this._$AN=void 0,this._$AM=D,this.options=F}get _$AU(){return this._$AM._$AU}_$AI(q){z(this,q)}}var Z={M:"$lit$",P,A:v,C:1,L:e,R:j,D:h,V:z,I:H,H:I,N:E,U:d,B:R,F:f},Oq=k.litHtmlPolyfillSupport;Oq?.(g,H),(k.litHtmlVersions??=[]).push("3.2.1");var i=(q,D,F)=>{let J=F?.renderBefore??D,G=J._$litPart$;if(G===void 0){const O=F?.renderBefore??null;J._$litPart$=G=new H(D.insertBefore(C(),O),O,void 0,F??{})}return G._$AI(q),G};var u=null,s={boundAttributeSuffix:Z.M,marker:Z.P,markerMatch:Z.A,HTML_RESULT:Z.C,getTemplateHtml:Z.L,overrideDirectiveResolve:(q,D)=>class extends q{_$AS(F,J){return D(this,J)}},patchDirectiveResolve:(q,D)=>{if(q.prototype._$AS!==D){u??=q.prototype._$AS.name;for(let F=q.prototype;F!==Object.prototype;F=Object.getPrototypeOf(F))if(F.hasOwnProperty(u))return void(F[u]=D);throw Error("Internal error: It is possible that both dev mode and production mode Lit was mixed together during SSR. Please comment on the issue: https://github.com/lit/lit/issues/4527")}},setDirectiveClass(q,D){q._$litDirective$=D},getAttributePartCommittedValue:(q,D,F)=>{let J=V;return q.j=(G)=>J=G,q._$AI(D,q,F),J},connectedDisconnectable:(q)=>({...q,_$AU:!0}),resolveDirective:Z.V,AttributePart:Z.H,PropertyPart:Z.B,BooleanAttributePart:Z.N,EventPart:Z.U,ElementPart:Z.F,TemplateInstance:Z.R,isIterable:Z.D,ChildPart:Z.I};var T={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6};var t=(q)=>q===null||typeof q!="object"&&typeof q!="function";var qq=(q,D)=>D===void 0?q?._$litType$!==void 0:q?._$litType$===D,Dq=(q)=>q?._$litType$?.h!=null;var Fq=(q)=>q.strings===void 0;var{TemplateInstance:Qq,isIterable:Wq,resolveDirective:Gq,ChildPart:N,ElementPart:Xq}=s,Jq=(q,D,F={})=>{if(D._$litPart$!==void 0)throw Error("container already contains a live render");let J,G,O,K=[],W=document.createTreeWalker(D,NodeFilter.SHOW_COMMENT),Q;while((Q=W.nextNode())!==null){const Y=Q.data;if(Y.startsWith("lit-part")){if(K.length===0&&J!==void 0)throw Error(`There must be only one root part per container. Found a part marker (${Q}) when we already have a root part marker (${G})`);O=Yq(q,Q,K,F),J===void 0&&(J=O),G??=Q}else if(Y.startsWith("lit-node"))Zq(Q,K,F);else if(Y.startsWith("/lit-part")){if(K.length===1&&O!==J)throw Error("internal error");O=Bq(Q,O,K)}}if(J===void 0){const Y=D instanceof ShadowRoot?"{container.host.localName}\'s shadow root":D instanceof DocumentFragment?"DocumentFragment":D.localName;console.error(`There should be exactly one root part in a render container, but we didn\'t find any in ${Y}.`)}D._$litPart$=J},Yq=(q,D,F,J)=>{let G,O;if(F.length===0)O=new N(D,null,void 0,J),G=q;else{const K=F[F.length-1];if(K.type==="template-instance")O=new N(D,null,K.instance,J),K.instance._$AV.push(O),G=K.result.values[K.instancePartIndex++],K.templatePartIndex++;else if(K.type==="iterable"){O=new N(D,null,K.part,J);const W=K.iterator.next();if(W.done)throw G=void 0,K.done=!0,Error("Unhandled shorter than expected iterable");G=W.value,K.part._$AH.push(O)}else O=new N(D,null,K.part,J)}if(G=Gq(O,G),G===V)F.push({part:O,type:"leaf"});else if(t(G))F.push({part:O,type:"leaf"}),O._$AH=G;else if(qq(G)){if(Dq(G))throw Error("compiled templates are not supported");const K="lit-part "+bq(G);if(D.data!==K)throw Error("Hydration value mismatch: Unexpected TemplateResult rendered to part");{const W=N.prototype._$AC(G),Q=new Qq(W,O);F.push({type:"template-instance",instance:Q,part:O,templatePartIndex:0,instancePartIndex:0,result:G}),O._$AH=Q}}else Wq(G)?(F.push({part:O,type:"iterable",value:G,iterator:G[Symbol.iterator](),done:!1}),O._$AH=[]):(F.push({part:O,type:"leaf"}),O._$AH=G??"");return O},Bq=(q,D,F)=>{if(D===void 0)throw Error("unbalanced part marker");D._$AB=q;const J=F.pop();if(J.type==="iterable"&&!J.iterator.next().done)throw Error("unexpected longer than expected iterable");if(F.length>0)return F[F.length-1].part},Zq=(q,D,F)=>{const J=/lit-node (\\d+)/.exec(q.data),G=Number.parseInt(J[1]),O=q.nextElementSibling;if(O===null)throw Error("could not find node for attribute parts");O.removeAttribute("defer-hydration");const K=D[D.length-1];if(K.type!=="template-instance")throw Error("Hydration value mismatch: Primitive found where TemplateResult expected. This usually occurs due to conditional rendering that resulted in a different value or template being rendered between the server and client.");{const W=K.instance;for(;;){const Q=W._$AD.parts[K.templatePartIndex];if(Q===void 0||Q.type!==T.ATTRIBUTE&&Q.type!==T.ELEMENT||Q.index!==G)break;if(Q.type===T.ATTRIBUTE){const Y=new Q.ctor(O,Q.name,Q.strings,K.instance,F),X=Fq(Y)?K.result.values[K.instancePartIndex]:K.result.values,b=!(Y.type===T.EVENT||Y.type===T.PROPERTY);Y._$AI(X,Y,K.instancePartIndex,b),K.instancePartIndex+=Q.strings.length-1,W._$AV.push(Y)}else{const Y=new Xq(O,K.instance,F);Gq(Y,K.result.values[K.instancePartIndex++]),W._$AV.push(Y)}K.templatePartIndex++}}},bq=(q)=>{const D=new Uint32Array(2).fill(5381);for(const J of q.strings)for(let G=0;G<J.length;G++)D[G%2]=33*D[G%2]^J.charCodeAt(G);const F=String.fromCharCode(...new Uint8Array(D.buffer));return btoa(F)};globalThis.litElementHydrateSupport=({LitElement:q})=>{const D=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(q),"observedAttributes").get;Object.defineProperty(q,"observedAttributes",{get(){return[...D.call(this),"defer-hydration"]}});const F=q.prototype.attributeChangedCallback;q.prototype.attributeChangedCallback=function(K,W,Q){K==="defer-hydration"&&Q===null&&J.call(this),F.call(this,K,W,Q)};const J=q.prototype.connectedCallback;q.prototype.connectedCallback=function(){this.hasAttribute("defer-hydration")||J.call(this)};const G=q.prototype.createRenderRoot;q.prototype.createRenderRoot=function(){return this.shadowRoot?(this._$AG=!0,this.shadowRoot):G.call(this)};const O=Object.getPrototypeOf(q.prototype).update;q.prototype.update=function(K){const W=this.render();if(O.call(this,K),this._$AG){this._$AG=!1;for(let Q=0;Q<this.attributes.length;Q++){const Y=this.attributes[Q];if(Y.name.startsWith("hydrate-internals-")){const X=Y.name.slice(18);this.removeAttribute(X),this.removeAttribute(Y.name)}}Jq(W,this.renderRoot,this.renderOptions)}else i(W,this.renderRoot,this.renderOptions)}};';
@@ -1,223 +0,0 @@
1
- /**
2
- * This module contains the Lit renderer
3
- * @module
4
- */
5
-
6
- import type {
7
- ComponentRenderInput,
8
- ComponentRenderResult,
9
- EcoComponent,
10
- EcoPagesElement,
11
- IntegrationRendererRenderOptions,
12
- PageMetadataProps,
13
- RouteRendererBody,
14
- } from '@ecopages/core';
15
- import { IntegrationRenderer, type RenderToResponseContext } from '@ecopages/core/route-renderer/integration-renderer';
16
- import { render } from '@lit-labs/ssr';
17
- import { RenderResultReadable } from '@lit-labs/ssr/lib/render-result-readable.js';
18
- import { html as staticHtml, unsafeStatic } from 'lit/static-html.js';
19
- import { LitSsrLazyPreloader } from './lit-ssr-lazy-preloader.ts';
20
- import { PLUGIN_NAME } from './lit.plugin.ts';
21
-
22
- /**
23
- * A renderer for the Lit integration.
24
- */
25
- export class LitRenderer extends IntegrationRenderer<EcoPagesElement> {
26
- override name = PLUGIN_NAME;
27
-
28
- private createRenderableMarkup(markup: string) {
29
- return staticHtml`${unsafeStatic(markup)}`;
30
- }
31
-
32
- private async renderMarkupToString(markup: string): Promise<string> {
33
- let renderedHtml = '';
34
- for (const chunk of render(this.createRenderableMarkup(markup))) {
35
- renderedHtml += chunk;
36
- }
37
- return renderedHtml;
38
- }
39
-
40
- /**
41
- * Renders a Lit component boundary for component-level orchestration.
42
- *
43
- * Includes component-scoped dependency assets when declared.
44
- */
45
- override async renderComponent(input: ComponentRenderInput): Promise<ComponentRenderResult> {
46
- const component = input.component as (
47
- props: Record<string, unknown>,
48
- ) => Promise<EcoPagesElement> | EcoPagesElement;
49
- const props = input.children === undefined ? input.props : { ...input.props, children: input.children };
50
- const content = await component(props);
51
- const markup = String(content);
52
- const html = await this.renderMarkupToString(markup);
53
- const hasDependencies = Boolean(input.component.config?.dependencies);
54
- const canResolveAssets = typeof this.assetProcessingService?.processDependencies === 'function';
55
- const assets =
56
- hasDependencies && canResolveAssets
57
- ? await this.processComponentDependencies([input.component])
58
- : undefined;
59
-
60
- return {
61
- html,
62
- canAttachAttributes: true,
63
- rootTag: this.getRootTagName(markup),
64
- integrationName: this.name,
65
- assets,
66
- };
67
- }
68
-
69
- private readonly ssrLazyPreloader = new LitSsrLazyPreloader({
70
- resolveDependencyPath: this.resolveDependencyPath.bind(this),
71
- processDependencies: this.assetProcessingService?.processDependencies?.bind(this.assetProcessingService),
72
- });
73
-
74
- /**
75
- * Detects preload failures that are expected for browser-only modules.
76
- *
77
- * These errors are treated as non-fatal during SSR preload because some
78
- * lazy client scripts intentionally depend on browser globals.
79
- */
80
- protected isExpectedSsrPreloadError(error: unknown): boolean {
81
- return this.ssrLazyPreloader.isExpectedSsrPreloadError(error);
82
- }
83
-
84
- /**
85
- * Collects lazy script file paths eligible for SSR preloading.
86
- *
87
- * Only per-entry lazy script dependencies with `ssr: true` are collected.
88
- * File-backed entries are required (`src` must be present);
89
- * inline content lazy entries are intentionally skipped.
90
- */
91
- protected collectSsrPreloadScripts(components: Array<EcoComponent | undefined>): string[] {
92
- return this.ssrLazyPreloader.collectSsrPreloadScripts(components);
93
- }
94
-
95
- /**
96
- * Preloads SSR-eligible lazy scripts to register custom elements before render.
97
- */
98
- protected async preloadSsrLazyScripts(components: Array<EcoComponent | undefined>): Promise<void> {
99
- await this.ssrLazyPreloader.preloadSsrLazyScripts(components);
100
- }
101
-
102
- /**
103
- * Resolves the concrete JS entrypoint used for SSR preloading.
104
- *
105
- * Scripts are passed through the asset pipeline so preload imports can use
106
- * the same processed output shape as runtime dependencies.
107
- */
108
- protected async resolveSsrPreloadEntrypoint(scriptPath: string): Promise<string | null> {
109
- return this.ssrLazyPreloader.resolveSsrPreloadEntrypoint(scriptPath);
110
- }
111
-
112
- async render({
113
- params,
114
- query,
115
- props,
116
- locals,
117
- metadata,
118
- Page,
119
- Layout,
120
- HtmlTemplate,
121
- }: IntegrationRendererRenderOptions): Promise<RouteRendererBody> {
122
- try {
123
- await this.preloadSsrLazyScripts([Page, Layout]);
124
-
125
- const pageContent = await Page({ params, query, ...props, locals });
126
- const children = Layout
127
- ? await (Layout as (props: { children: EcoPagesElement } & Record<string, unknown>) => EcoPagesElement)(
128
- {
129
- children: pageContent,
130
- locals,
131
- },
132
- )
133
- : pageContent;
134
-
135
- const template = (await HtmlTemplate({
136
- metadata,
137
- children: '<--content-->',
138
- pageProps: props || {},
139
- })) as string;
140
-
141
- const [templateStart, templateEnd] = template.split('<--content-->');
142
-
143
- const DOC_TYPE = this.DOC_TYPE;
144
-
145
- function* streamBody() {
146
- yield DOC_TYPE;
147
- yield templateStart;
148
- yield* render(staticHtml`${unsafeStatic(children)}`);
149
- yield templateEnd;
150
- }
151
-
152
- return new RenderResultReadable(streamBody());
153
- } catch (error) {
154
- throw this.createRenderError('Error rendering page', error);
155
- }
156
- }
157
-
158
- async renderToResponse<P = Record<string, unknown>>(
159
- view: EcoComponent<P>,
160
- props: P,
161
- ctx: RenderToResponseContext,
162
- ): Promise<Response> {
163
- try {
164
- const viewConfig = view.config;
165
- const Layout = viewConfig?.layout as
166
- | ((props: { children: EcoPagesElement } & Record<string, unknown>) => EcoPagesElement)
167
- | undefined;
168
-
169
- await this.preloadSsrLazyScripts([view as unknown as EcoComponent, Layout as unknown as EcoComponent]);
170
-
171
- const viewFn = view as (props: P) => Promise<EcoPagesElement>;
172
- const pageContent = await viewFn(props);
173
-
174
- if (ctx.partial) {
175
- function* streamBody() {
176
- yield* render(staticHtml`${unsafeStatic(pageContent)}`);
177
- }
178
- const readable = new RenderResultReadable(streamBody());
179
- return this.createHtmlResponse(readable as unknown as BodyInit, ctx);
180
- }
181
-
182
- const DOC_TYPE = this.DOC_TYPE;
183
- const children = Layout ? await Layout({ children: pageContent }) : pageContent;
184
-
185
- const HtmlTemplate = await this.getHtmlTemplate();
186
- const metadata: PageMetadataProps = view.metadata
187
- ? await view.metadata({
188
- params: {},
189
- query: {},
190
- props: props as Record<string, unknown>,
191
- appConfig: this.appConfig,
192
- })
193
- : this.appConfig.defaultMetadata;
194
-
195
- await this.prepareViewDependencies(view, Layout as EcoComponent | undefined);
196
-
197
- const template = (await HtmlTemplate({
198
- metadata,
199
- children: '<--content-->',
200
- pageProps: props as Record<string, unknown>,
201
- })) as string;
202
-
203
- const [templateStart, templateEnd] = template.split('<--content-->');
204
-
205
- function* streamBody() {
206
- yield DOC_TYPE;
207
- yield templateStart;
208
- yield* render(staticHtml`${unsafeStatic(children)}`);
209
- yield templateEnd;
210
- }
211
- const stream = new RenderResultReadable(streamBody());
212
- const transformedResponse = await this.htmlTransformer.transform(
213
- new Response(stream as any, {
214
- headers: { 'Content-Type': 'text/html' },
215
- }),
216
- );
217
-
218
- return this.createHtmlResponse(transformedResponse.body as BodyInit, ctx);
219
- } catch (error) {
220
- throw this.createRenderError('Error rendering view', error);
221
- }
222
- }
223
- }
@@ -1,202 +0,0 @@
1
- import type { EcoComponent, EcoComponentConfig } from '@ecopages/core';
2
- import { AssetFactory } from '@ecopages/core/services/asset-processing-service';
3
- import type { AssetDefinition } from '@ecopages/core/services/asset-processing-service';
4
- import path from 'node:path';
5
- import { pathToFileURL } from 'node:url';
6
-
7
- type ProcessDependencies = (
8
- dependencies: AssetDefinition[],
9
- integrationName: string,
10
- ) => Promise<Array<{ filepath?: string }>>;
11
-
12
- export interface LitSsrLazyPreloaderOptions {
13
- resolveDependencyPath: (componentDir: string, sourcePath: string) => string;
14
- processDependencies?: ProcessDependencies;
15
- }
16
-
17
- /**
18
- * Encapsulates SSR lazy script preload behavior for Lit components.
19
- *
20
- * Collects `dependencies.scripts` lazy entries with `ssr: true`, resolves the
21
- * processed entrypoint through the asset pipeline, and imports the module so
22
- * custom elements are registered before SSR rendering.
23
- */
24
- export class LitSsrLazyPreloader {
25
- private readonly resolveDependencyPath: (componentDir: string, sourcePath: string) => string;
26
- private readonly processDependencies?: ProcessDependencies;
27
- private readonly ssrPreloadedScripts = new Set<string>();
28
- private readonly ssrPreloadFailedScripts = new Set<string>();
29
- private readonly ssrPreloadEntrypointCache = new Map<string, string>();
30
-
31
- constructor({ resolveDependencyPath, processDependencies }: LitSsrLazyPreloaderOptions) {
32
- this.resolveDependencyPath = resolveDependencyPath;
33
- this.processDependencies = processDependencies;
34
- }
35
-
36
- /**
37
- * Detects preload failures that are expected for browser-only modules.
38
- */
39
- isExpectedSsrPreloadError(error: unknown): boolean {
40
- const errorMessage = error instanceof Error ? error.message : String(error);
41
- const errorCode =
42
- typeof error === 'object' && error !== null && 'code' in error
43
- ? String((error as { code?: unknown }).code ?? '')
44
- : '';
45
-
46
- if (errorCode === 'ERR_UNKNOWN_FILE_EXTENSION') {
47
- return true;
48
- }
49
-
50
- return (
51
- errorMessage.includes(`reading 'Element'`) ||
52
- errorMessage.includes('window is not defined') ||
53
- errorMessage.includes('document is not defined') ||
54
- errorMessage.includes('navigator is not defined')
55
- );
56
- }
57
-
58
- /**
59
- * Collects lazy script file paths eligible for SSR preloading.
60
- */
61
- collectSsrPreloadScripts(components: Array<EcoComponent | undefined>): string[] {
62
- const scriptPaths = new Set<string>();
63
- const visitedConfigs = new Set<EcoComponentConfig>();
64
-
65
- const collect = (component?: EcoComponent) => {
66
- const config = component?.config;
67
- if (!config || visitedConfigs.has(config)) {
68
- return;
69
- }
70
-
71
- visitedConfigs.add(config);
72
-
73
- const scriptEntries = config.dependencies?.scripts ?? [];
74
- const componentFile = config.__eco?.file;
75
-
76
- if (componentFile) {
77
- const componentDir = path.dirname(componentFile);
78
- for (const script of scriptEntries) {
79
- if (typeof script === 'string') {
80
- continue;
81
- }
82
-
83
- if (!script.lazy || script.ssr !== true) {
84
- continue;
85
- }
86
-
87
- if (!script.src) {
88
- continue;
89
- }
90
-
91
- scriptPaths.add(this.resolveDependencyPath(componentDir, script.src));
92
- }
93
- }
94
-
95
- if (config.layout) {
96
- collect(config.layout);
97
- }
98
-
99
- for (const nestedComponent of config.dependencies?.components || []) {
100
- collect(nestedComponent);
101
- }
102
- };
103
-
104
- for (const component of components) {
105
- collect(component);
106
- }
107
-
108
- return Array.from(scriptPaths);
109
- }
110
-
111
- /**
112
- * Preloads SSR-eligible lazy scripts to register custom elements before render.
113
- */
114
- async preloadSsrLazyScripts(components: Array<EcoComponent | undefined>): Promise<void> {
115
- const scripts = this.collectSsrPreloadScripts(components);
116
- if (scripts.length === 0) {
117
- return;
118
- }
119
-
120
- await Promise.all(
121
- scripts
122
- .filter((scriptPath) => {
123
- if (this.ssrPreloadedScripts.has(scriptPath)) {
124
- return false;
125
- }
126
- if (this.ssrPreloadFailedScripts.has(scriptPath)) {
127
- return false;
128
- }
129
- return true;
130
- })
131
- .map(async (scriptPath) => {
132
- const preloadEntrypoint = await this.resolveSsrPreloadEntrypoint(scriptPath);
133
- if (!preloadEntrypoint) {
134
- this.ssrPreloadFailedScripts.add(scriptPath);
135
- return;
136
- }
137
-
138
- try {
139
- await import(pathToFileURL(preloadEntrypoint).href);
140
- this.ssrPreloadedScripts.add(scriptPath);
141
- } catch (error) {
142
- this.ssrPreloadFailedScripts.add(scriptPath);
143
-
144
- if (this.isExpectedSsrPreloadError(error)) {
145
- if (process.env.ECOPAGES_DEBUG === 'true') {
146
- console.warn(
147
- `[ecopages][lit] Skipping SSR preload for browser-only lazy script: ${scriptPath}`,
148
- );
149
- }
150
- return;
151
- }
152
-
153
- console.warn(`[ecopages][lit] Failed to preload lazy SSR script: ${scriptPath}`, error);
154
- }
155
- }),
156
- );
157
- }
158
-
159
- /**
160
- * Resolves the concrete JS entrypoint used for SSR preloading.
161
- */
162
- async resolveSsrPreloadEntrypoint(scriptPath: string): Promise<string | null> {
163
- const cachedEntrypoint = this.ssrPreloadEntrypointCache.get(scriptPath);
164
- if (cachedEntrypoint) {
165
- return cachedEntrypoint;
166
- }
167
-
168
- if (!this.processDependencies) {
169
- return scriptPath;
170
- }
171
-
172
- try {
173
- const processed = await this.processDependencies(
174
- [
175
- AssetFactory.createInlineFileScript({
176
- filepath: scriptPath,
177
- position: 'head',
178
- bundle: true,
179
- attributes: {
180
- type: 'module',
181
- defer: '',
182
- },
183
- }),
184
- ],
185
- `lit-ssr-preload:${scriptPath}`,
186
- );
187
-
188
- const entrypoint = processed[0]?.filepath;
189
- if (!entrypoint) {
190
- return scriptPath;
191
- }
192
-
193
- this.ssrPreloadEntrypointCache.set(scriptPath, entrypoint);
194
- return entrypoint;
195
- } catch (error) {
196
- if (process.env.ECOPAGES_DEBUG === 'true') {
197
- console.warn(`[ecopages][lit] Failed to resolve SSR preload entrypoint for: ${scriptPath}`, error);
198
- }
199
- return scriptPath;
200
- }
201
- }
202
- }
package/src/lit.plugin.ts DELETED
@@ -1,69 +0,0 @@
1
- /**
2
- * This module contains the Lit plugin
3
- * @module
4
- */
5
-
6
- import '@lit-labs/ssr/lib/install-global-dom-shim.js';
7
- import './console';
8
- import { IntegrationPlugin, type IntegrationPluginConfig } from '@ecopages/core/plugins/integration-plugin';
9
- import { type AssetDefinition, AssetFactory } from '@ecopages/core/services/asset-processing-service';
10
- import { litElementHydrateScript } from './lit-element-hydrate.ts';
11
- import { LitRenderer } from './lit-renderer.ts';
12
-
13
- /**
14
- * The name of the Lit plugin
15
- */
16
- export const PLUGIN_NAME = 'lit';
17
-
18
- /**
19
- * The Lit plugin class
20
- * This plugin provides support for Lit components in Ecopages
21
- */
22
- export class LitPlugin extends IntegrationPlugin {
23
- renderer = LitRenderer;
24
-
25
- constructor(options?: Omit<IntegrationPluginConfig, 'name'>) {
26
- super({
27
- name: PLUGIN_NAME,
28
- extensions: ['.lit.tsx'],
29
- staticBuildStep: 'fetch',
30
- ...options,
31
- });
32
-
33
- this.integrationDependencies.unshift(...this.getDependencies());
34
- }
35
-
36
- getDependencies(): AssetDefinition[] {
37
- return [
38
- /**
39
- * BUG ALERT
40
- * Due to an issue appeared in Bun 1.2.2, we need to use a workaround to import the hydrate script.
41
- * This is a temporary solution until the issue is resolved.
42
- * The litElementHydrateScript is the same file built on Bun 1.1.45.
43
- * https://github.com/oven-sh/bun/issues/17180
44
- *
45
- * AssetFactory.createNodeModuleScript({
46
- * position: 'head',
47
- * importPath: '@lit-labs/ssr-client/lit-element-hydrate-support.js'
48
- * })
49
- */
50
- AssetFactory.createInlineContentScript({
51
- position: 'head',
52
- content: litElementHydrateScript,
53
- bundle: false,
54
- attributes: {
55
- 'data-eco-script-id': 'lit-hydrate-support',
56
- },
57
- }),
58
- ];
59
- }
60
- }
61
-
62
- /**
63
- * Factory function to create a Lit plugin instance
64
- * @param options Configuration options for the Lit plugin
65
- * @returns A new LitPlugin instance
66
- */
67
- export function litPlugin(options?: Omit<IntegrationPluginConfig, 'name'>): LitPlugin {
68
- return new LitPlugin(options);
69
- }
@@ -1,27 +0,0 @@
1
- /**
2
- * This module contains StyledMixin
3
- * It is used to add styles to a LitElement
4
- * @module
5
- */
6
- import { type LitElement, unsafeCSS } from 'lit';
7
-
8
- type Constructor<T> = new (...args: any[]) => T;
9
-
10
- /**
11
- * A mixin to add styles to a LitElement
12
- * @param superClass - The class to mix into
13
- * @param css - The styles to add
14
- * @returns The class with the styles added
15
- */
16
- export const StyledMixin = <T extends Constructor<LitElement>>(
17
- superClass: T,
18
- css: string[] = [],
19
- ): Constructor<LitElement> & T => {
20
- class StyledMixinClass extends superClass {
21
- static styles = [
22
- (superClass as unknown as typeof LitElement).styles ?? [],
23
- ...css.map((styles) => unsafeCSS(styles)),
24
- ];
25
- }
26
- return StyledMixinClass as Constructor<LitElement> & T;
27
- };