@ecopages/lit 0.2.0-beta.4 → 0.2.0-beta.40

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.
@@ -0,0 +1,109 @@
1
+ import { Worker } from 'node:worker_threads';
2
+ import { fileURLToPath } from 'node:url';
3
+ export class LitStaticRenderWorkerClient {
4
+ configModulePath;
5
+ runtimeOrigin;
6
+ worker = null;
7
+ readyPromise = null;
8
+ pending = new Map();
9
+ nextRenderId = 0;
10
+ constructor({ configModulePath, runtimeOrigin }) {
11
+ this.configModulePath = configModulePath;
12
+ this.runtimeOrigin = runtimeOrigin;
13
+ }
14
+ rejectPending(error) {
15
+ for (const pending of this.pending.values()) {
16
+ pending.reject(error);
17
+ }
18
+ this.pending.clear();
19
+ }
20
+ async start() {
21
+ if (this.readyPromise) {
22
+ return this.readyPromise;
23
+ }
24
+ this.readyPromise = new Promise((resolveReady, rejectReady) => {
25
+ const worker = new Worker(new URL('./lit-static-render-worker.js', import.meta.url), {
26
+ execArgv: [...process.execArgv],
27
+ env: {
28
+ ...process.env,
29
+ ECOPAGES_LIT_STATIC_RENDER_WORKER: 'true',
30
+ },
31
+ });
32
+ this.worker = worker;
33
+ worker.on('message', (message) => {
34
+ if (message.type === 'ready') {
35
+ resolveReady();
36
+ return;
37
+ }
38
+ if (message.type === 'error') {
39
+ if (message.id && this.pending.has(message.id)) {
40
+ const pending = this.pending.get(message.id);
41
+ this.pending.delete(message.id);
42
+ pending.reject(new Error(message.message));
43
+ return;
44
+ }
45
+ rejectReady(new Error(message.message));
46
+ return;
47
+ }
48
+ if (message.type === 'result') {
49
+ const pending = this.pending.get(message.id);
50
+ if (!pending) {
51
+ return;
52
+ }
53
+ this.pending.delete(message.id);
54
+ pending.resolve({ html: message.html, cacheStrategy: message.cacheStrategy });
55
+ }
56
+ });
57
+ worker.on('error', (error) => {
58
+ rejectReady(error instanceof Error ? error : new Error(String(error)));
59
+ });
60
+ worker.on('exit', (code) => {
61
+ const exitError = new Error(code === 0
62
+ ? 'Lit static render worker exited'
63
+ : `Lit static render worker exited with code ${code}`);
64
+ this.rejectPending(exitError);
65
+ if (code !== 0) {
66
+ rejectReady(exitError);
67
+ }
68
+ });
69
+ const initMessage = {
70
+ type: 'init',
71
+ configModulePath: this.configModulePath,
72
+ runtimeOrigin: this.runtimeOrigin,
73
+ };
74
+ worker.postMessage(initMessage);
75
+ });
76
+ return this.readyPromise;
77
+ }
78
+ async renderPage(input) {
79
+ await this.start();
80
+ const worker = this.worker;
81
+ if (!worker) {
82
+ throw new Error('Lit static render worker is not available');
83
+ }
84
+ const id = String(++this.nextRenderId);
85
+ return new Promise((resolve, reject) => {
86
+ this.pending.set(id, { resolve, reject });
87
+ const renderMessage = {
88
+ type: 'render',
89
+ id,
90
+ filePath: input.filePath,
91
+ params: input.params,
92
+ query: input.query,
93
+ };
94
+ worker.postMessage(renderMessage);
95
+ });
96
+ }
97
+ async dispose() {
98
+ if (!this.worker) {
99
+ return;
100
+ }
101
+ this.rejectPending(new Error('Lit static render worker was disposed'));
102
+ const worker = this.worker;
103
+ this.worker = null;
104
+ this.readyPromise = null;
105
+ worker.postMessage({ type: 'shutdown' });
106
+ await worker.terminate();
107
+ }
108
+ }
109
+ export const litStaticRenderWorkerEntryPath = fileURLToPath(new URL('./lit-static-render-worker.js', import.meta.url));
@@ -0,0 +1 @@
1
+ import './dom-shim.js';
@@ -0,0 +1,80 @@
1
+ import { parentPort } from 'node:worker_threads';
2
+ import { pathToFileURL } from 'node:url';
3
+ import { setupAppRuntimePlugins } from '@ecopages/core/build/build-adapter';
4
+ import { installBuildRuntime } from '@ecopages/core/build/build-runtime';
5
+ import { RouteRendererFactory } from '@ecopages/core/route-renderer/route-renderer';
6
+ import './dom-shim.js';
7
+ let appConfig = null;
8
+ let routeRendererFactory = null;
9
+ /**
10
+ * Loads app config in the worker isolate and bootstraps rendering.
11
+ *
12
+ * @remarks
13
+ * Processor `.setup()` is skipped here — the main thread already prepared disk artifacts
14
+ * before the Lit worker started (`ECOPAGES_LIT_STATIC_RENDER_WORKER`).
15
+ */
16
+ async function initializeWorker(configModulePath, runtimeOrigin) {
17
+ const configModule = await import(/* @vite-ignore */ pathToFileURL(configModulePath).href);
18
+ appConfig = (configModule.default ?? configModule);
19
+ await setupAppRuntimePlugins({
20
+ appConfig,
21
+ runtimeOrigin,
22
+ });
23
+ installBuildRuntime(appConfig);
24
+ routeRendererFactory = new RouteRendererFactory({
25
+ appConfig,
26
+ runtimeOrigin,
27
+ });
28
+ }
29
+ async function renderPage(filePath, params, query) {
30
+ if (!routeRendererFactory) {
31
+ throw new Error('Lit static render worker is not initialized');
32
+ }
33
+ const result = await routeRendererFactory.getPageRenderer(filePath).execute({
34
+ file: filePath,
35
+ params,
36
+ query,
37
+ });
38
+ const body = result.body;
39
+ if (typeof body === 'string') {
40
+ return { html: body, cacheStrategy: result.cacheStrategy };
41
+ }
42
+ if (Buffer.isBuffer(body)) {
43
+ return { html: body.toString('utf8'), cacheStrategy: result.cacheStrategy };
44
+ }
45
+ if (body instanceof ReadableStream) {
46
+ return { html: await new Response(body).text(), cacheStrategy: result.cacheStrategy };
47
+ }
48
+ throw new TypeError(`Unsupported Lit static render body type: ${typeof body}`);
49
+ }
50
+ function postMessage(message) {
51
+ parentPort?.postMessage(message);
52
+ }
53
+ if (!parentPort) {
54
+ throw new Error('Lit static render worker must be started as a worker thread');
55
+ }
56
+ parentPort.on('message', async (message) => {
57
+ try {
58
+ if (message.type === 'init') {
59
+ await initializeWorker(message.configModulePath, message.runtimeOrigin);
60
+ postMessage({ type: 'ready' });
61
+ return;
62
+ }
63
+ if (message.type === 'shutdown') {
64
+ process.exit(0);
65
+ return;
66
+ }
67
+ if (message.type === 'render') {
68
+ const result = await renderPage(message.filePath, message.params, message.query);
69
+ postMessage({ type: 'result', id: message.id, ...result });
70
+ }
71
+ }
72
+ catch (error) {
73
+ const errorMessage = error instanceof Error ? error.message : String(error);
74
+ if (message.type === 'render') {
75
+ postMessage({ type: 'error', id: message.id, message: errorMessage });
76
+ return;
77
+ }
78
+ postMessage({ type: 'error', message: errorMessage });
79
+ }
80
+ });
@@ -1,4 +1 @@
1
- const LIT_PLUGIN_NAME = "lit";
2
- export {
3
- LIT_PLUGIN_NAME
4
- };
1
+ export const LIT_PLUGIN_NAME = 'lit';
@@ -3,7 +3,7 @@
3
3
  * @module
4
4
  */
5
5
  import './console.js';
6
- import { IntegrationPlugin, type IntegrationPluginConfig } from '@ecopages/core/plugins/integration-plugin';
6
+ import { IntegrationPlugin, type IntegrationPluginConfig, type StaticExportContext } from '@ecopages/core/plugins/integration-plugin';
7
7
  import { type AssetDefinition } from '@ecopages/core/services/asset-processing-service';
8
8
  import { LitRenderer } from './lit-renderer.js';
9
9
  /**
@@ -13,11 +13,24 @@ export declare const PLUGIN_NAME = "lit";
13
13
  /**
14
14
  * The Lit plugin class
15
15
  * This plugin provides support for Lit components in Ecopages
16
+ *
17
+ * @remarks
18
+ * Owns the {@link LitStaticRenderSession} for worker SSR. Renderers receive a
19
+ * lazy `getRenderSession` accessor so construction before {@link setup} still
20
+ * observes the session once setup assigns it.
16
21
  */
17
22
  export declare class LitPlugin extends IntegrationPlugin {
18
23
  renderer: typeof LitRenderer;
24
+ private renderSession;
19
25
  constructor(options?: Omit<IntegrationPluginConfig, 'name'>);
20
26
  getDependencies(): AssetDefinition[];
27
+ private createRenderSession;
28
+ initializeRenderer(options?: {
29
+ rendererModules?: unknown;
30
+ }): LitRenderer;
31
+ setup(): Promise<void>;
32
+ teardown(): Promise<void>;
33
+ beforeStaticExport(context: StaticExportContext): Promise<void>;
21
34
  }
22
35
  /**
23
36
  * Factory function to create a Lit plugin instance
package/src/lit.plugin.js CHANGED
@@ -1,51 +1,116 @@
1
- import "./console.js";
2
- import { IntegrationPlugin } from "@ecopages/core/plugins/integration-plugin";
3
- import { AssetFactory } from "@ecopages/core/services/asset-processing-service";
4
- import { litElementHydrateScript } from "./lit-element-hydrate.js";
5
- import { LIT_PLUGIN_NAME } from "./lit.constants.js";
6
- import { LitRenderer } from "./lit-renderer.js";
7
- const PLUGIN_NAME = LIT_PLUGIN_NAME;
8
- class LitPlugin extends IntegrationPlugin {
9
- renderer = LitRenderer;
10
- constructor(options) {
11
- super({
12
- name: PLUGIN_NAME,
13
- extensions: [".lit.tsx"],
14
- staticBuildStep: "fetch",
15
- ...options
16
- });
17
- this.integrationDependencies.unshift(...this.getDependencies());
18
- }
19
- getDependencies() {
20
- return [
21
- /**
22
- * BUG ALERT
23
- * Due to an issue appeared in Bun 1.2.2, we need to use a workaround to import the hydrate script.
24
- * This is a temporary solution until the issue is resolved.
25
- * The litElementHydrateScript is the same file built on Bun 1.1.45.
26
- * https://github.com/oven-sh/bun/issues/17180
27
- *
28
- * AssetFactory.createNodeModuleScript({
29
- * position: 'head',
30
- * importPath: '@lit-labs/ssr-client/lit-element-hydrate-support.js'
31
- * })
32
- */
33
- AssetFactory.createInlineContentScript({
34
- position: "head",
35
- content: `(() => {${litElementHydrateScript}})();`,
36
- bundle: false,
37
- attributes: {
38
- "data-eco-script-id": "lit-hydrate-support"
1
+ /**
2
+ * This module contains the Lit plugin
3
+ * @module
4
+ */
5
+ import './console.js';
6
+ import { IntegrationPlugin, } from '@ecopages/core/plugins/integration-plugin';
7
+ import { isLitStaticRenderWorkerThread } from '@ecopages/core/build/lit-static-render-worker-context';
8
+ import path from 'node:path';
9
+ import { AssetFactory } from '@ecopages/core/services/asset-processing-service';
10
+ import { litElementHydrateScript } from './lit-element-hydrate.js';
11
+ import { LIT_PLUGIN_NAME } from './lit.constants.js';
12
+ import { LitRenderer } from './lit-renderer.js';
13
+ import { LitStaticRenderSession } from './lit-static-render-session.js';
14
+ /**
15
+ * The name of the Lit plugin
16
+ */
17
+ export const PLUGIN_NAME = LIT_PLUGIN_NAME;
18
+ /**
19
+ * The Lit plugin class
20
+ * This plugin provides support for Lit components in Ecopages
21
+ *
22
+ * @remarks
23
+ * Owns the {@link LitStaticRenderSession} for worker SSR. Renderers receive a
24
+ * lazy `getRenderSession` accessor so construction before {@link setup} still
25
+ * observes the session once setup assigns it.
26
+ */
27
+ export class LitPlugin extends IntegrationPlugin {
28
+ renderer = LitRenderer;
29
+ renderSession = null;
30
+ constructor(options) {
31
+ super({
32
+ name: PLUGIN_NAME,
33
+ extensions: ['.lit.tsx'],
34
+ ...options,
35
+ });
36
+ this.integrationDependencies.unshift(...this.getDependencies());
37
+ }
38
+ getDependencies() {
39
+ return [
40
+ /**
41
+ * BUG ALERT
42
+ * Due to an issue appeared in Bun 1.2.2, we need to use a workaround to import the hydrate script.
43
+ * This is a temporary solution until the issue is resolved.
44
+ * The litElementHydrateScript is the same file built on Bun 1.1.45.
45
+ * https://github.com/oven-sh/bun/issues/17180
46
+ *
47
+ * AssetFactory.createNodeModuleScript({
48
+ * position: 'head',
49
+ * importPath: '@lit-labs/ssr-client/lit-element-hydrate-support.js'
50
+ * })
51
+ */
52
+ AssetFactory.createInlineContentScript({
53
+ position: 'head',
54
+ content: `(() => {${litElementHydrateScript}})();`,
55
+ bundle: false,
56
+ attributes: {
57
+ 'data-eco-script-id': 'lit-hydrate-support',
58
+ },
59
+ }),
60
+ ];
61
+ }
62
+ createRenderSession() {
63
+ if (!this.appConfig || !this.assetProcessingService) {
64
+ throw new Error('Lit plugin must be initialized before starting the render worker');
39
65
  }
40
- })
41
- ];
42
- }
66
+ return new LitStaticRenderSession({
67
+ resolveDependencyPath: (componentDir, sourcePath) => path.join(componentDir, sourcePath),
68
+ processDependencies: this.assetProcessingService.processDependencies.bind(this.assetProcessingService),
69
+ preferSourceImports: typeof Bun !== 'undefined',
70
+ });
71
+ }
72
+ initializeRenderer(options) {
73
+ const renderer = new this.renderer({
74
+ ...this.createRendererOptions(options),
75
+ getRenderSession: () => this.renderSession ?? undefined,
76
+ });
77
+ return this.attachRendererRuntimeServices(renderer);
78
+ }
79
+ async setup() {
80
+ await super.setup();
81
+ if (!this.appConfig?.absolutePaths?.config) {
82
+ throw new Error('[ecopages][lit] Lit server rendering requires appConfig.absolutePaths.config');
83
+ }
84
+ if (isLitStaticRenderWorkerThread()) {
85
+ return;
86
+ }
87
+ this.renderSession = this.createRenderSession();
88
+ await this.renderSession.ensureWorker({
89
+ configModulePath: this.appConfig.absolutePaths.config,
90
+ runtimeOrigin: this.runtimeOrigin,
91
+ });
92
+ }
93
+ async teardown() {
94
+ await this.renderSession?.dispose();
95
+ this.renderSession = null;
96
+ await super.teardown();
97
+ }
98
+ async beforeStaticExport(context) {
99
+ if (!this.renderSession) {
100
+ this.renderSession = this.createRenderSession();
101
+ await this.renderSession.ensureWorker({
102
+ configModulePath: context.appConfig.absolutePaths.config,
103
+ runtimeOrigin: context.baseUrl,
104
+ });
105
+ }
106
+ await this.renderSession.preloadStaticRoutes(context);
107
+ }
43
108
  }
44
- function litPlugin(options) {
45
- return new LitPlugin(options);
109
+ /**
110
+ * Factory function to create a Lit plugin instance
111
+ * @param options Configuration options for the Lit plugin
112
+ * @returns A new LitPlugin instance
113
+ */
114
+ export function litPlugin(options) {
115
+ return new LitPlugin(options);
46
116
  }
47
- export {
48
- LitPlugin,
49
- PLUGIN_NAME,
50
- litPlugin
51
- };
@@ -1,13 +1,21 @@
1
- import { unsafeCSS } from "lit";
2
- const StyledMixin = (superClass, css = []) => {
3
- class StyledMixinClass extends superClass {
4
- static styles = [
5
- superClass.styles ?? [],
6
- ...css.map((styles) => unsafeCSS(styles))
7
- ];
8
- }
9
- return StyledMixinClass;
10
- };
11
- export {
12
- StyledMixin
1
+ /**
2
+ * This module contains StyledMixin
3
+ * It is used to add styles to a LitElement
4
+ * @module
5
+ */
6
+ import { unsafeCSS } from 'lit';
7
+ /**
8
+ * A mixin to add styles to a LitElement
9
+ * @param superClass - The class to mix into
10
+ * @param css - The styles to add
11
+ * @returns The class with the styles added
12
+ */
13
+ export const StyledMixin = (superClass, css = []) => {
14
+ class StyledMixinClass extends superClass {
15
+ static styles = [
16
+ superClass.styles ?? [],
17
+ ...css.map((styles) => unsafeCSS(styles)),
18
+ ];
19
+ }
20
+ return StyledMixinClass;
13
21
  };
@@ -1,52 +1,45 @@
1
- import { render } from "@lit-labs/ssr";
2
- import { html as staticHtml, unsafeStatic } from "lit/static-html.js";
3
- const LIT_HTML_TEMPLATE_SLOT_MARKER = "<--content-->";
4
- const LIT_COMPONENT_CHILDREN_SLOT_MARKER = "<!--eco-lit-component-children-->";
5
- const ESCAPED_COMPONENT_CHILDREN_SLOT_MARKER = "&lt;!--eco-lit-component-children--&gt;";
6
- const DOUBLE_ESCAPED_COMPONENT_CHILDREN_SLOT_MARKER = "&amp;lt;!--eco-lit-component-children--&amp;gt;";
1
+ import { render } from '@lit-labs/ssr';
2
+ import { html as staticHtml, unsafeStatic } from 'lit/static-html.js';
3
+ export const LIT_HTML_TEMPLATE_SLOT_MARKER = '<--content-->';
4
+ export const LIT_COMPONENT_CHILDREN_SLOT_MARKER = '<!--eco-lit-component-children-->';
5
+ const ESCAPED_COMPONENT_CHILDREN_SLOT_MARKER = '&lt;!--eco-lit-component-children--&gt;';
6
+ const DOUBLE_ESCAPED_COMPONENT_CHILDREN_SLOT_MARKER = '&amp;lt;!--eco-lit-component-children--&amp;gt;';
7
7
  const DUPLICATE_DECLARATIVE_SHADOW_ROOT_ATTRIBUTE = /\sshadowroot=(['"])(open|closed)\1(?=\sshadowrootmode=\1\2\1)/g;
8
- function normalizeLitHtml(markup) {
9
- return markup.replace(DUPLICATE_DECLARATIVE_SHADOW_ROOT_ATTRIBUTE, "");
8
+ export function normalizeLitHtml(markup) {
9
+ return markup.replace(DUPLICATE_DECLARATIVE_SHADOW_ROOT_ATTRIBUTE, '');
10
10
  }
11
- function injectLitRenderedChildren(template, renderedChildren) {
12
- for (const marker of [
13
- LIT_COMPONENT_CHILDREN_SLOT_MARKER,
14
- ESCAPED_COMPONENT_CHILDREN_SLOT_MARKER,
15
- DOUBLE_ESCAPED_COMPONENT_CHILDREN_SLOT_MARKER
16
- ]) {
17
- if (template.includes(marker)) {
18
- return template.split(marker).join(renderedChildren);
11
+ export function injectLitRenderedChildren(template, renderedChildren) {
12
+ for (const marker of [
13
+ LIT_COMPONENT_CHILDREN_SLOT_MARKER,
14
+ ESCAPED_COMPONENT_CHILDREN_SLOT_MARKER,
15
+ DOUBLE_ESCAPED_COMPONENT_CHILDREN_SLOT_MARKER,
16
+ ]) {
17
+ if (template.includes(marker)) {
18
+ return template.split(marker).join(renderedChildren);
19
+ }
19
20
  }
20
- }
21
- if (template.includes(LIT_HTML_TEMPLATE_SLOT_MARKER)) {
22
- return template.split(LIT_HTML_TEMPLATE_SLOT_MARKER).join(renderedChildren);
23
- }
24
- if (template.includes("</body>")) {
25
- return template.replace("</body>", `${renderedChildren}</body>`);
26
- }
27
- if (template.includes("</html>")) {
28
- return template.replace("</html>", `${renderedChildren}</html>`);
29
- }
30
- return `${template}${renderedChildren}`;
21
+ if (template.includes(LIT_HTML_TEMPLATE_SLOT_MARKER)) {
22
+ return template.split(LIT_HTML_TEMPLATE_SLOT_MARKER).join(renderedChildren);
23
+ }
24
+ if (template.includes('</body>')) {
25
+ return template.replace('</body>', `${renderedChildren}</body>`);
26
+ }
27
+ if (template.includes('</html>')) {
28
+ return template.replace('</html>', `${renderedChildren}</html>`);
29
+ }
30
+ return `${template}${renderedChildren}`;
31
31
  }
32
- async function renderLitValueToString(value) {
33
- if (typeof value === "string") {
34
- let renderedHtml2 = "";
35
- for (const chunk of render(staticHtml`${unsafeStatic(value)}`)) {
36
- renderedHtml2 += chunk;
32
+ export async function renderLitValueToString(value) {
33
+ if (typeof value === 'string') {
34
+ let renderedHtml = '';
35
+ for (const chunk of render(staticHtml `${unsafeStatic(value)}`)) {
36
+ renderedHtml += chunk;
37
+ }
38
+ return normalizeLitHtml(renderedHtml);
39
+ }
40
+ let renderedHtml = '';
41
+ for (const chunk of render(value)) {
42
+ renderedHtml += chunk;
37
43
  }
38
- return normalizeLitHtml(renderedHtml2);
39
- }
40
- let renderedHtml = "";
41
- for (const chunk of render(value)) {
42
- renderedHtml += chunk;
43
- }
44
- return normalizeLitHtml(renderedHtml);
44
+ return normalizeLitHtml(renderedHtml);
45
45
  }
46
- export {
47
- LIT_COMPONENT_CHILDREN_SLOT_MARKER,
48
- LIT_HTML_TEMPLATE_SLOT_MARKER,
49
- injectLitRenderedChildren,
50
- normalizeLitHtml,
51
- renderLitValueToString
52
- };