@ecopages/lit 0.2.1 → 0.3.0

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,145 @@
1
+ import path from 'node:path';
2
+ import { ensureLitDomShim } from './dom-shim.js';
3
+ import { CUSTOM_ELEMENT_SSR_PRELOAD_CACHE_SCOPES, CustomElementScriptPreloader, } from '@ecopages/core/integration';
4
+ import { LIT_PLUGIN_NAME } from './lit.constants.js';
5
+ import { createCustomElementSsrPipelineImporter } from '@ecopages/core/integration';
6
+ import { LitStaticRenderWorkerClient } from './lit-static-render-worker-client.js';
7
+ /**
8
+ * Plugin-runtime-scoped Lit server render session.
9
+ *
10
+ * @remarks
11
+ * Owns worker lifecycle and SSR preload for Lit page routes during static export
12
+ * and runtime/dev requests. Injected into `LitRenderer` via a lazy accessor from
13
+ * `LitPlugin`; there is no process-global coordinator.
14
+ *
15
+ * Worker init identity is sticky for the first `{ configModulePath, runtimeOrigin }`.
16
+ * Later `ensureWorker` calls with the same identity are no-ops; a different identity
17
+ * recreates the worker so stale config/origin is never silently reused.
18
+ */
19
+ export class LitStaticRenderSession {
20
+ preloader;
21
+ createWorkerClient;
22
+ workerClient = null;
23
+ workerIdentity = null;
24
+ getInvalidationVersion;
25
+ workerInvalidationVersion = 0;
26
+ renderChain = Promise.resolve();
27
+ constructor(options) {
28
+ this.getInvalidationVersion = options.getInvalidationVersion ?? (() => 0);
29
+ this.preloader = new CustomElementScriptPreloader({
30
+ cacheScope: CUSTOM_ELEMENT_SSR_PRELOAD_CACHE_SCOPES.lit,
31
+ preloadScopes: options.preloadScopes,
32
+ logLabel: 'lit',
33
+ requireLazyScriptEntry: true,
34
+ resolveDependencyPath: options.resolveDependencyPath,
35
+ importServerModule: createCustomElementSsrPipelineImporter({
36
+ integration: options.integration,
37
+ processDependencies: options.processDependencies,
38
+ }),
39
+ });
40
+ this.createWorkerClient =
41
+ options.createWorkerClient ??
42
+ ((input) => new LitStaticRenderWorkerClient({
43
+ configModulePath: input.configModulePath,
44
+ runtimeOrigin: input.runtimeOrigin,
45
+ }));
46
+ }
47
+ /**
48
+ * Ensures the static render worker is running for the given identity.
49
+ *
50
+ * @remarks
51
+ * First successful start sticks that identity. Matching re-entry is a no-op.
52
+ * A different `configModulePath` or `runtimeOrigin` disposes and recreates.
53
+ */
54
+ async ensureWorker(input) {
55
+ if (this.workerClient &&
56
+ this.workerIdentity &&
57
+ this.workerIdentity.configModulePath === input.configModulePath &&
58
+ this.workerIdentity.runtimeOrigin === input.runtimeOrigin) {
59
+ return;
60
+ }
61
+ if (this.workerClient) {
62
+ await this.dispose();
63
+ }
64
+ this.workerIdentity = {
65
+ configModulePath: input.configModulePath,
66
+ runtimeOrigin: input.runtimeOrigin,
67
+ };
68
+ this.workerClient = this.createWorkerClient({
69
+ configModulePath: input.configModulePath,
70
+ runtimeOrigin: input.runtimeOrigin,
71
+ });
72
+ await this.workerClient.start();
73
+ this.workerInvalidationVersion = this.getInvalidationVersion();
74
+ }
75
+ async preloadStaticRoutes(context) {
76
+ await this.preloadLitRoutes(context);
77
+ }
78
+ async preloadSsrScripts(components) {
79
+ ensureLitDomShim();
80
+ await this.preloader.preloadSsrScripts(components);
81
+ }
82
+ collectSsrPreloadScripts(components) {
83
+ return this.preloader.collectSsrPreloadScripts(components);
84
+ }
85
+ async renderPageInWorker(input) {
86
+ if (!this.workerClient) {
87
+ throw new Error('Lit static render worker is not active');
88
+ }
89
+ const render = this.renderChain.then(async () => {
90
+ const version = this.getInvalidationVersion();
91
+ if (version !== this.workerInvalidationVersion && this.workerIdentity) {
92
+ const identity = this.workerIdentity;
93
+ await this.dispose();
94
+ await this.ensureWorker(identity);
95
+ }
96
+ if (!this.workerClient)
97
+ throw new Error('Lit static render worker is not active');
98
+ return this.workerClient.renderPage(input);
99
+ });
100
+ this.renderChain = render.then(() => undefined, () => undefined);
101
+ return render;
102
+ }
103
+ isExpectedSsrPreloadError(error) {
104
+ return this.preloader.isExpectedSsrPreloadError(error);
105
+ }
106
+ async dispose() {
107
+ await this.workerClient?.dispose();
108
+ this.workerClient = null;
109
+ this.workerIdentity = null;
110
+ }
111
+ async preloadLitRoutes(context) {
112
+ if (!context.routeRendererFactory) {
113
+ return;
114
+ }
115
+ const routes = await context.router.listStaticGenerationRoutes({ runtimeOrigin: context.baseUrl });
116
+ const components = [];
117
+ for (const route of routes) {
118
+ const filePath = route.templateRoute.filePath;
119
+ if (!this.isLitRoute(filePath, context.appConfig)) {
120
+ continue;
121
+ }
122
+ const pageRenderer = context.routeRendererFactory.getPageRenderer(filePath);
123
+ const pageModule = await pageRenderer.loadPageModule(filePath);
124
+ const page = pageModule.default;
125
+ if (page) {
126
+ components.push(page);
127
+ for (const layout of page.config?.layouts ?? []) {
128
+ components.push(layout);
129
+ }
130
+ for (const nestedComponent of page.config?.dependencies?.components ?? []) {
131
+ components.push(nestedComponent);
132
+ }
133
+ }
134
+ }
135
+ await this.preloadSsrScripts(components);
136
+ }
137
+ isLitRoute(filePath, appConfig) {
138
+ const litIntegration = appConfig.integrations.find((plugin) => plugin.name === LIT_PLUGIN_NAME);
139
+ if (!litIntegration) {
140
+ return false;
141
+ }
142
+ const normalizedPath = path.normalize(filePath);
143
+ return litIntegration.extensions.some((extension) => normalizedPath.endsWith(extension));
144
+ }
145
+ }
@@ -0,0 +1,26 @@
1
+ import type { PageParams, PageQuery } from '@ecopages/core';
2
+ import type { LitStaticRenderResult } from './lit-static-render-protocol.js';
3
+ export declare class LitStaticRenderWorkerClient {
4
+ private readonly configModulePath;
5
+ private readonly runtimeOrigin;
6
+ private worker;
7
+ private workerExitPromise;
8
+ private workerExitCode;
9
+ private readyPromise;
10
+ private pending;
11
+ private nextRenderId;
12
+ private shutdownHandler;
13
+ constructor({ configModulePath, runtimeOrigin }: {
14
+ configModulePath: string;
15
+ runtimeOrigin: string;
16
+ });
17
+ private rejectPending;
18
+ start(): Promise<void>;
19
+ renderPage(input: {
20
+ filePath: string;
21
+ params: PageParams;
22
+ query?: PageQuery;
23
+ }): Promise<LitStaticRenderResult>;
24
+ dispose(): Promise<void>;
25
+ }
26
+ export declare const litStaticRenderWorkerEntryPath: string;
@@ -0,0 +1,181 @@
1
+ import { Worker } from 'node:worker_threads';
2
+ import { fileURLToPath } from 'node:url';
3
+ const workerShutdownTimeoutMs = 30_000;
4
+ const workerExitTimeoutMs = 1_000;
5
+ export class LitStaticRenderWorkerClient {
6
+ configModulePath;
7
+ runtimeOrigin;
8
+ worker = null;
9
+ workerExitPromise = null;
10
+ workerExitCode = null;
11
+ readyPromise = null;
12
+ pending = new Map();
13
+ nextRenderId = 0;
14
+ shutdownHandler = null;
15
+ constructor({ configModulePath, runtimeOrigin }) {
16
+ this.configModulePath = configModulePath;
17
+ this.runtimeOrigin = runtimeOrigin;
18
+ }
19
+ rejectPending(error) {
20
+ for (const pending of this.pending.values()) {
21
+ pending.reject(error);
22
+ }
23
+ this.pending.clear();
24
+ }
25
+ async start() {
26
+ if (this.readyPromise) {
27
+ return this.readyPromise;
28
+ }
29
+ this.readyPromise = new Promise((resolveReady, rejectReady) => {
30
+ const worker = new Worker(new URL('./lit-static-render-worker.js', import.meta.url), {
31
+ execArgv: [...process.execArgv],
32
+ env: {
33
+ ...process.env,
34
+ ECOPAGES_LIT_STATIC_RENDER_WORKER: 'true',
35
+ },
36
+ });
37
+ this.worker = worker;
38
+ this.workerExitCode = null;
39
+ this.workerExitPromise = new Promise((resolveExit) => {
40
+ worker.once('exit', resolveExit);
41
+ });
42
+ worker.on('message', (message) => {
43
+ if (message.type === 'ready') {
44
+ resolveReady();
45
+ return;
46
+ }
47
+ if (message.type === 'shutdown-complete') {
48
+ this.shutdownHandler?.resolve();
49
+ this.shutdownHandler = null;
50
+ return;
51
+ }
52
+ if (message.type === 'error') {
53
+ if (message.id && this.pending.has(message.id)) {
54
+ const pending = this.pending.get(message.id);
55
+ this.pending.delete(message.id);
56
+ pending.reject(new Error(message.message));
57
+ return;
58
+ }
59
+ const error = new Error(message.message);
60
+ this.shutdownHandler?.reject(error);
61
+ this.shutdownHandler = null;
62
+ rejectReady(error);
63
+ return;
64
+ }
65
+ if (message.type === 'result') {
66
+ const pending = this.pending.get(message.id);
67
+ if (!pending) {
68
+ return;
69
+ }
70
+ this.pending.delete(message.id);
71
+ pending.resolve({
72
+ html: message.html,
73
+ cacheStrategy: message.cacheStrategy,
74
+ sourceDependencyPaths: message.sourceDependencyPaths,
75
+ metadata: message.metadata,
76
+ });
77
+ }
78
+ });
79
+ worker.on('error', (error) => {
80
+ rejectReady(error instanceof Error ? error : new Error(String(error)));
81
+ });
82
+ worker.on('exit', (code) => {
83
+ this.workerExitCode = code;
84
+ const exitError = new Error(code === 0
85
+ ? 'Lit static render worker exited'
86
+ : `Lit static render worker exited with code ${code}`);
87
+ this.rejectPending(exitError);
88
+ this.shutdownHandler?.reject(exitError);
89
+ this.shutdownHandler = null;
90
+ if (code !== 0) {
91
+ rejectReady(exitError);
92
+ }
93
+ });
94
+ const initMessage = {
95
+ type: 'init',
96
+ configModulePath: this.configModulePath,
97
+ runtimeOrigin: this.runtimeOrigin,
98
+ };
99
+ worker.postMessage(initMessage);
100
+ });
101
+ return this.readyPromise;
102
+ }
103
+ async renderPage(input) {
104
+ await this.start();
105
+ const worker = this.worker;
106
+ if (!worker) {
107
+ throw new Error('Lit static render worker is not available');
108
+ }
109
+ const id = String(++this.nextRenderId);
110
+ return new Promise((resolve, reject) => {
111
+ this.pending.set(id, { resolve, reject });
112
+ const renderMessage = {
113
+ type: 'render',
114
+ id,
115
+ filePath: input.filePath,
116
+ params: input.params,
117
+ query: input.query,
118
+ };
119
+ worker.postMessage(renderMessage);
120
+ });
121
+ }
122
+ async dispose() {
123
+ if (!this.worker) {
124
+ return;
125
+ }
126
+ this.rejectPending(new Error('Lit static render worker was disposed'));
127
+ const worker = this.worker;
128
+ const workerExit = this.workerExitPromise ?? Promise.resolve(this.workerExitCode ?? 0);
129
+ this.worker = null;
130
+ this.workerExitPromise = null;
131
+ this.readyPromise = null;
132
+ if (this.workerExitCode !== null) {
133
+ if (this.workerExitCode !== 0) {
134
+ throw new Error(`Lit static render worker exited with code ${this.workerExitCode}`);
135
+ }
136
+ return;
137
+ }
138
+ let shutdownTimeout;
139
+ const shutdownComplete = new Promise((resolve, reject) => {
140
+ shutdownTimeout = setTimeout(() => reject(new Error('Lit static render worker shutdown timed out')), workerShutdownTimeoutMs);
141
+ this.shutdownHandler = {
142
+ resolve: () => {
143
+ if (shutdownTimeout)
144
+ clearTimeout(shutdownTimeout);
145
+ resolve();
146
+ },
147
+ reject: (error) => {
148
+ if (shutdownTimeout)
149
+ clearTimeout(shutdownTimeout);
150
+ reject(error);
151
+ },
152
+ };
153
+ });
154
+ worker.postMessage({ type: 'shutdown' });
155
+ let shutdownError;
156
+ try {
157
+ await shutdownComplete;
158
+ }
159
+ catch (error) {
160
+ shutdownError = error instanceof Error ? error : new Error(String(error));
161
+ }
162
+ if (shutdownTimeout)
163
+ clearTimeout(shutdownTimeout);
164
+ const exitResult = await new Promise((resolve) => {
165
+ const exitTimeout = setTimeout(() => resolve({ timedOut: true }), workerExitTimeoutMs);
166
+ void workerExit.then((code) => {
167
+ clearTimeout(exitTimeout);
168
+ resolve({ code });
169
+ });
170
+ });
171
+ if ('timedOut' in exitResult) {
172
+ await worker.terminate();
173
+ }
174
+ else if (exitResult.code !== 0) {
175
+ shutdownError ??= new Error(`Lit static render worker exited with code ${exitResult.code}`);
176
+ }
177
+ if (shutdownError)
178
+ throw shutdownError;
179
+ }
180
+ }
181
+ 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,111 @@
1
+ import { parentPort } from 'node:worker_threads';
2
+ import { loadEcoPagesConfig } from '@ecopages/core/config';
3
+ import { setupAppRuntimeIntegrations, setupAppRuntimePlugins, teardownAppRuntimeIntegrations, } from '@ecopages/core/build';
4
+ import { installBuildQueue } from '@ecopages/core/build';
5
+ import { requireAppRuntime } from '@ecopages/core/integration';
6
+ import { RouteRendererFactory } from '@ecopages/core/integration';
7
+ import { toLitStaticRenderResult } from './lit-static-render-result.js';
8
+ import './dom-shim.js';
9
+ let appConfig = null;
10
+ let routeRendererFactory = null;
11
+ let activeRenders = 0;
12
+ let shutdownRequested = false;
13
+ let resolveRendersIdle;
14
+ /**
15
+ * Loads app config in the worker isolate and bootstraps rendering.
16
+ *
17
+ * @remarks
18
+ * Processor `.setup()` is skipped here because the main thread already prepared disk artifacts
19
+ * before the Lit worker started (`ECOPAGES_LIT_STATIC_RENDER_WORKER`). Integrations still need
20
+ * setup in this isolate before route renderers are created.
21
+ */
22
+ async function initializeWorker(configModulePath, runtimeOrigin) {
23
+ appConfig = await loadEcoPagesConfig({ configFile: configModulePath });
24
+ const runtime = requireAppRuntime(appConfig);
25
+ runtime.origin = runtimeOrigin;
26
+ await setupAppRuntimePlugins({
27
+ appConfig,
28
+ });
29
+ await setupAppRuntimeIntegrations({ appConfig });
30
+ installBuildQueue(appConfig);
31
+ routeRendererFactory = new RouteRendererFactory({
32
+ appConfig,
33
+ runtime,
34
+ });
35
+ }
36
+ async function renderPage(filePath, params, query) {
37
+ if (!routeRendererFactory) {
38
+ throw new Error('Lit static render worker is not initialized');
39
+ }
40
+ const result = await routeRendererFactory.getPageRenderer(filePath).execute({
41
+ file: filePath,
42
+ params,
43
+ query,
44
+ });
45
+ return toLitStaticRenderResult(result);
46
+ }
47
+ async function shutdownWorker() {
48
+ shutdownRequested = true;
49
+ if (activeRenders > 0) {
50
+ await new Promise((resolve) => {
51
+ resolveRendersIdle = resolve;
52
+ });
53
+ }
54
+ try {
55
+ if (appConfig) {
56
+ await teardownAppRuntimeIntegrations({ appConfig });
57
+ }
58
+ postMessage({ type: 'shutdown-complete' });
59
+ }
60
+ catch (error) {
61
+ const errorMessage = error instanceof Error ? error.message : String(error);
62
+ postMessage({ type: 'error', message: errorMessage });
63
+ }
64
+ finally {
65
+ parentPort?.close();
66
+ }
67
+ }
68
+ function postMessage(message) {
69
+ parentPort?.postMessage(message);
70
+ }
71
+ if (!parentPort) {
72
+ throw new Error('Lit static render worker must be started as a worker thread');
73
+ }
74
+ parentPort.on('message', async (message) => {
75
+ try {
76
+ if (message.type === 'init') {
77
+ await initializeWorker(message.configModulePath, message.runtimeOrigin);
78
+ postMessage({ type: 'ready' });
79
+ return;
80
+ }
81
+ if (message.type === 'shutdown') {
82
+ await shutdownWorker();
83
+ return;
84
+ }
85
+ if (message.type === 'render') {
86
+ if (shutdownRequested) {
87
+ throw new Error('Lit static render worker is shutting down');
88
+ }
89
+ activeRenders += 1;
90
+ try {
91
+ const result = await renderPage(message.filePath, message.params, message.query);
92
+ postMessage({ type: 'result', id: message.id, ...result });
93
+ }
94
+ finally {
95
+ activeRenders -= 1;
96
+ if (activeRenders === 0) {
97
+ resolveRendersIdle?.();
98
+ resolveRendersIdle = undefined;
99
+ }
100
+ }
101
+ }
102
+ }
103
+ catch (error) {
104
+ const errorMessage = error instanceof Error ? error.message : String(error);
105
+ if (message.type === 'render') {
106
+ postMessage({ type: 'error', id: message.id, message: errorMessage });
107
+ return;
108
+ }
109
+ postMessage({ type: 'error', message: errorMessage });
110
+ }
111
+ });
@@ -0,0 +1 @@
1
+ export declare const LIT_PLUGIN_NAME = "lit";
@@ -0,0 +1 @@
1
+ export const LIT_PLUGIN_NAME = 'lit';
@@ -3,8 +3,8 @@
3
3
  * @module
4
4
  */
5
5
  import './console.js';
6
- import { IntegrationPlugin, type IntegrationPluginConfig } from '@ecopages/core/plugins/integration-plugin';
7
- import { type AssetDefinition } from '@ecopages/core/services/asset-processing-service';
6
+ import { IntegrationPlugin, type IntegrationRendererBase, type IntegrationRuntimeContext, type IntegrationPluginConfig, type StaticExportContext, type StaticExportRelease } from '@ecopages/core/integration';
7
+ import { type AssetDefinition } from '@ecopages/core/integration';
8
8
  import { LitRenderer } from './lit-renderer.js';
9
9
  /**
10
10
  * The name of the Lit plugin
@@ -13,11 +13,44 @@ 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
- renderer: typeof LitRenderer;
23
+ renderer: new (options: import("@ecopages/core/integration").IntegrationRendererOptions) => import("@ecopages/core/integration").IntegrationRenderer<import("@ecopages/core").EcoPagesElement> & {
24
+ name: string;
25
+ };
26
+ private renderSession;
19
27
  constructor(options?: Omit<IntegrationPluginConfig, 'name'>);
28
+ /**
29
+ * Returns the global integration dependencies required in the browser.
30
+ *
31
+ * @remarks
32
+ * Injects Lit's hydration support script into the document head before any
33
+ * custom element connects. While `@lit-labs/ssr-client/lit-element-hydrate-support.js`
34
+ * can be resolved directly in modern Bun and Node environments, an inline self-contained
35
+ * script is currently emitted to ensure synchronous availability before custom-element
36
+ * registration without requiring an import map for `@lit-labs/ssr-client` subpath imports.
37
+ */
20
38
  getDependencies(): AssetDefinition[];
39
+ private createRenderSession;
40
+ createRenderer(base: IntegrationRendererBase): LitRenderer;
41
+ hmr(context: IntegrationRuntimeContext): void;
42
+ setup(context: IntegrationRuntimeContext): Promise<void>;
43
+ teardown(): Promise<void>;
44
+ /**
45
+ * Reconciles the render worker with the export origin and preloads Lit routes.
46
+ *
47
+ * @remarks
48
+ * `setup()` can start the session with the runtime origin before static export resolves its own base URL. The
49
+ * session reuses the worker when the identities match and restarts it when the export origin differs. The returned
50
+ * release stops the worker once the export ends, so an in-process export leaves no worker thread running. A later
51
+ * render in the same process falls back to rendering in-process.
52
+ */
53
+ staticExport(context: StaticExportContext): Promise<StaticExportRelease>;
21
54
  }
22
55
  /**
23
56
  * Factory function to create a Lit plugin instance