@ecopages/lit 0.2.0-beta.30 → 0.2.0-beta.32

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.
@@ -1,113 +1,109 @@
1
- import { Worker } from "node:worker_threads";
2
- import { fileURLToPath } from "node:url";
3
- class LitStaticRenderWorkerClient {
4
- configModulePath;
5
- runtimeOrigin;
6
- worker = null;
7
- readyPromise = null;
8
- pending = /* @__PURE__ */ 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);
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;
17
13
  }
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"
14
+ rejectPending(error) {
15
+ for (const pending of this.pending.values()) {
16
+ pending.reject(error);
30
17
  }
31
- });
32
- this.worker = worker;
33
- worker.on("message", (message) => {
34
- if (message.type === "ready") {
35
- resolveReady();
36
- return;
18
+ this.pending.clear();
19
+ }
20
+ async start() {
21
+ if (this.readyPromise) {
22
+ return this.readyPromise;
37
23
  }
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;
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');
47
83
  }
48
- if (message.type === "result") {
49
- const pending = this.pending.get(message.id);
50
- if (!pending) {
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) {
51
99
  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(
62
- code === 0 ? "Lit static render worker exited" : `Lit static render worker exited with code ${code}`
63
- );
64
- this.rejectPending(exitError);
65
- if (code !== 0) {
66
- rejectReady(exitError);
67
100
  }
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;
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();
100
107
  }
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
108
  }
109
- const litStaticRenderWorkerEntryPath = fileURLToPath(new URL("./lit-static-render-worker.js", import.meta.url));
110
- export {
111
- LitStaticRenderWorkerClient,
112
- litStaticRenderWorkerEntryPath
113
- };
109
+ export const litStaticRenderWorkerEntryPath = fileURLToPath(new URL('./lit-static-render-worker.js', import.meta.url));
@@ -1,75 +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";
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
7
  let appConfig = null;
8
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
+ */
9
16
  async function initializeWorker(configModulePath, runtimeOrigin) {
10
- const configModule = await import(
11
- /* @vite-ignore */
12
- pathToFileURL(configModulePath).href
13
- );
14
- appConfig = configModule.default ?? configModule;
15
- await setupAppRuntimePlugins({
16
- appConfig,
17
- runtimeOrigin
18
- });
19
- installBuildRuntime(appConfig);
20
- routeRendererFactory = new RouteRendererFactory({
21
- appConfig,
22
- runtimeOrigin
23
- });
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
+ });
24
28
  }
25
29
  async function renderPage(filePath, params, query) {
26
- if (!routeRendererFactory) {
27
- throw new Error("Lit static render worker is not initialized");
28
- }
29
- const result = await routeRendererFactory.getPageRenderer(filePath).execute({
30
- file: filePath,
31
- params,
32
- query
33
- });
34
- const body = result.body;
35
- if (typeof body === "string") {
36
- return { html: body, cacheStrategy: result.cacheStrategy };
37
- }
38
- if (Buffer.isBuffer(body)) {
39
- return { html: body.toString("utf8"), cacheStrategy: result.cacheStrategy };
40
- }
41
- if (body instanceof ReadableStream) {
42
- return { html: await new Response(body).text(), cacheStrategy: result.cacheStrategy };
43
- }
44
- throw new TypeError(`Unsupported Lit static render body type: ${typeof body}`);
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}`);
45
49
  }
46
50
  function postMessage(message) {
47
- parentPort?.postMessage(message);
51
+ parentPort?.postMessage(message);
48
52
  }
49
53
  if (!parentPort) {
50
- throw new Error("Lit static render worker must be started as a worker thread");
54
+ throw new Error('Lit static render worker must be started as a worker thread');
51
55
  }
52
- parentPort.on("message", async (message) => {
53
- try {
54
- if (message.type === "init") {
55
- await initializeWorker(message.configModulePath, message.runtimeOrigin);
56
- postMessage({ type: "ready" });
57
- return;
58
- }
59
- if (message.type === "shutdown") {
60
- process.exit(0);
61
- return;
62
- }
63
- if (message.type === "render") {
64
- const result = await renderPage(message.filePath, message.params, message.query);
65
- postMessage({ type: "result", id: message.id, ...result });
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
+ }
66
71
  }
67
- } catch (error) {
68
- const errorMessage = error instanceof Error ? error.message : String(error);
69
- if (message.type === "render") {
70
- postMessage({ type: "error", id: message.id, message: errorMessage });
71
- return;
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 });
72
79
  }
73
- postMessage({ type: "error", message: errorMessage });
74
- }
75
80
  });
@@ -1,4 +1 @@
1
- const LIT_PLUGIN_NAME = "lit";
2
- export {
3
- LIT_PLUGIN_NAME
4
- };
1
+ export const LIT_PLUGIN_NAME = 'lit';
package/src/lit.plugin.js CHANGED
@@ -1,102 +1,116 @@
1
- import "./console.js";
2
- import {
3
- IntegrationPlugin
4
- } from "@ecopages/core/plugins/integration-plugin";
5
- import { isLitStaticRenderWorkerThread } from "@ecopages/core/build/lit-static-render-worker-context";
6
- import path from "node:path";
7
- import { AssetFactory } from "@ecopages/core/services/asset-processing-service";
8
- import { litElementHydrateScript } from "./lit-element-hydrate.js";
9
- import { LIT_PLUGIN_NAME } from "./lit.constants.js";
10
- import { LitRenderer } from "./lit-renderer.js";
11
- import { LitStaticRenderSession } from "./lit-static-render-session.js";
12
- const PLUGIN_NAME = LIT_PLUGIN_NAME;
13
- class LitPlugin extends IntegrationPlugin {
14
- renderer = LitRenderer;
15
- renderSession = null;
16
- constructor(options) {
17
- super({
18
- name: PLUGIN_NAME,
19
- extensions: [".lit.tsx"],
20
- ...options
21
- });
22
- this.integrationDependencies.unshift(...this.getDependencies());
23
- }
24
- getDependencies() {
25
- return [
26
- /**
27
- * BUG ALERT
28
- * Due to an issue appeared in Bun 1.2.2, we need to use a workaround to import the hydrate script.
29
- * This is a temporary solution until the issue is resolved.
30
- * The litElementHydrateScript is the same file built on Bun 1.1.45.
31
- * https://github.com/oven-sh/bun/issues/17180
32
- *
33
- * AssetFactory.createNodeModuleScript({
34
- * position: 'head',
35
- * importPath: '@lit-labs/ssr-client/lit-element-hydrate-support.js'
36
- * })
37
- */
38
- AssetFactory.createInlineContentScript({
39
- position: "head",
40
- content: `(() => {${litElementHydrateScript}})();`,
41
- bundle: false,
42
- attributes: {
43
- "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');
44
65
  }
45
- })
46
- ];
47
- }
48
- createRenderSession() {
49
- if (!this.appConfig || !this.assetProcessingService) {
50
- throw new Error("Lit plugin must be initialized before starting the render worker");
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);
51
78
  }
52
- return new LitStaticRenderSession({
53
- resolveDependencyPath: (componentDir, sourcePath) => path.join(componentDir, sourcePath),
54
- processDependencies: this.assetProcessingService.processDependencies.bind(this.assetProcessingService),
55
- preferSourceImports: typeof Bun !== "undefined"
56
- });
57
- }
58
- initializeRenderer(options) {
59
- const renderer = new this.renderer({
60
- ...this.createRendererOptions(options),
61
- getRenderSession: () => this.renderSession ?? void 0
62
- });
63
- return this.attachRendererRuntimeServices(renderer);
64
- }
65
- async setup() {
66
- await super.setup();
67
- if (!this.appConfig?.absolutePaths?.config) {
68
- throw new Error("[ecopages][lit] Lit server rendering requires appConfig.absolutePaths.config");
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
+ });
69
92
  }
70
- if (isLitStaticRenderWorkerThread()) {
71
- return;
93
+ async teardown() {
94
+ await this.renderSession?.dispose();
95
+ this.renderSession = null;
96
+ await super.teardown();
72
97
  }
73
- this.renderSession = this.createRenderSession();
74
- await this.renderSession.ensureWorker({
75
- configModulePath: this.appConfig.absolutePaths.config,
76
- runtimeOrigin: this.runtimeOrigin
77
- });
78
- }
79
- async teardown() {
80
- await this.renderSession?.dispose();
81
- this.renderSession = null;
82
- await super.teardown();
83
- }
84
- async beforeStaticExport(context) {
85
- if (!this.renderSession) {
86
- this.renderSession = this.createRenderSession();
87
- await this.renderSession.ensureWorker({
88
- configModulePath: context.appConfig.absolutePaths.config,
89
- runtimeOrigin: context.baseUrl
90
- });
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);
91
107
  }
92
- await this.renderSession.preloadStaticRoutes(context);
93
- }
94
108
  }
95
- function litPlugin(options) {
96
- 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);
97
116
  }
98
- export {
99
- LitPlugin,
100
- PLUGIN_NAME,
101
- litPlugin
102
- };
@@ -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
  };