@lwrjs/lwc-ssr 0.7.0-alpha.4 → 0.7.0-alpha.7

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.
@@ -24,20 +24,27 @@ var __toModule = (module2) => {
24
24
  // packages/@lwrjs/lwc-ssr/src/moduleProvider/index.ts
25
25
  __markAsModule(exports);
26
26
  __export(exports, {
27
+ createSsrBootstrapModule: () => createSsrBootstrapModule,
27
28
  default: () => moduleProvider_default
28
29
  });
29
- var import_diagnostics = __toModule(require("@lwrjs/diagnostics"));
30
30
  var import_shared_utils = __toModule(require("@lwrjs/shared-utils"));
31
- var import_utils = __toModule(require("./utils.cjs"));
32
31
  var import_identity = __toModule(require("../identity.cjs"));
33
- function getRootModuleSpecifier(ssrSpecifier) {
34
- const [, , namespace, name] = ssrSpecifier.split("/");
35
- return `${namespace}/${name}`;
32
+ function createSsrBootstrapModule(rootComponent) {
33
+ return [
34
+ "/* This module is generated and meant to be used in a Server context */",
35
+ 'import { renderComponent } from "@lwc/engine-server"',
36
+ `import Ctor from "${rootComponent}"`,
37
+ "try {",
38
+ ` const result = renderComponent("${(0, import_shared_utils.moduleSpecifierToKebabCase)(rootComponent)}", Ctor, globalThis.ssrProps);`,
39
+ " globalThis.ssrWorkerResult = { result };",
40
+ "} catch(err) {",
41
+ " globalThis.ssrWorkerResult = { error: err.toString() };",
42
+ `}`
43
+ ].join("\n");
36
44
  }
37
45
  var LwcSsrModuleProvider = class {
38
- constructor(appPluginConfig, {config, runtimeEnvironment: {hmrEnabled, lwrVersion}}) {
46
+ constructor(providerConfig, {runtimeEnvironment: {lwrVersion}}) {
39
47
  this.name = "ssr-module-provider";
40
- this.config = config;
41
48
  this.version = lwrVersion;
42
49
  }
43
50
  async getModuleEntry({specifier}) {
@@ -52,22 +59,12 @@ var LwcSsrModuleProvider = class {
52
59
  };
53
60
  }
54
61
  }
55
- async getModuleSource({
56
- specifier,
57
- namespace,
58
- name
59
- }) {
60
- if (!specifier.startsWith(import_identity.LWC_SSR_PREFIX)) {
61
- return;
62
- }
62
+ async getModule({specifier, namespace, name}) {
63
63
  const moduleEntry = await this.getModuleEntry({specifier});
64
64
  if (!moduleEntry) {
65
- throw (0, import_diagnostics.createSingleDiagnosticError)({
66
- description: import_diagnostics.descriptions.UNRESOLVABLE.MODULE(specifier)
67
- }, import_diagnostics.LwrUnresolvableError);
65
+ return;
68
66
  }
69
- const customElementModule = getRootModuleSpecifier(specifier);
70
- const originalSource = (0, import_utils.createSsrBootstrapModule)(customElementModule);
67
+ const originalSource = createSsrBootstrapModule(specifier.replace(import_identity.LWC_SSR_PREFIX, ""));
71
68
  return {
72
69
  id: moduleEntry.id,
73
70
  namespace,
@@ -76,18 +73,8 @@ var LwcSsrModuleProvider = class {
76
73
  specifier,
77
74
  moduleEntry,
78
75
  ownHash: (0, import_shared_utils.hashContent)(originalSource),
79
- originalSource
80
- };
81
- }
82
- async getModule(moduleId) {
83
- if (!moduleId.specifier.startsWith("@lwrjs/lwc-ssr/")) {
84
- return;
85
- }
86
- const moduleSource = await this.getModuleSource(moduleId);
87
- const compiledSource = moduleSource.originalSource;
88
- return {
89
- ...moduleSource,
90
- compiledSource
76
+ originalSource,
77
+ compiledSource: originalSource
91
78
  };
92
79
  }
93
80
  };
@@ -29,22 +29,29 @@ __export(exports, {
29
29
  var import_shared_utils = __toModule(require("@lwrjs/shared-utils"));
30
30
  var import_identity = __toModule(require("../identity.cjs"));
31
31
  var import_ssr_element = __toModule(require("./ssr-element.cjs"));
32
- function lwcSsrViewTranformer(options, lwrGlobalContext) {
33
- const {moduleBundler} = lwrGlobalContext;
32
+ function lwcSsrViewTranformer(options, {moduleBundler}) {
34
33
  return {
35
34
  name: "ssr-lwc-transformer",
36
- async link(stringBuilder, viewContext, viewMeta) {
35
+ async link(stringBuilder, viewContext, {customElements}) {
37
36
  if (viewContext.view.bootstrap?.experimentalSSR) {
38
- const {customElements} = viewMeta;
39
- for (const customElementRef of customElements) {
40
- if (customElementRef.location) {
41
- const {startOffset, endOffset} = customElementRef.location;
42
- const moduleSpecifier = (0, import_shared_utils.kebabcaseToCamelcase)(customElementRef.tagName);
43
- const ssrSpecifier = `${import_identity.LWC_SSR_PREFIX}${moduleSpecifier}`;
44
- const ssrResult = await (0, import_ssr_element.ssrElement)({specifier: ssrSpecifier}, moduleBundler, viewContext.runtimeEnvironment);
45
- stringBuilder.overwrite(startOffset, endOffset, ssrResult);
37
+ const ssrModules = [];
38
+ for (const {tagName, location, props = {}} of customElements) {
39
+ if (location) {
40
+ const {startOffset, endOffset} = location;
41
+ const moduleSpecifier = (0, import_shared_utils.kebabCaseToModuleSpecifer)(tagName);
42
+ ssrModules.push({
43
+ startOffset,
44
+ endOffset,
45
+ props,
46
+ specifier: `${import_identity.LWC_SSR_PREFIX}${moduleSpecifier}`
47
+ });
46
48
  }
47
49
  }
50
+ return Promise.all(ssrModules.map(({specifier, props, startOffset, endOffset}) => {
51
+ return (0, import_ssr_element.ssrElement)({specifier, props}, moduleBundler, viewContext.runtimeEnvironment).then((ssrResult) => {
52
+ stringBuilder.overwrite(startOffset, endOffset, ssrResult);
53
+ });
54
+ })).then(() => void 0);
48
55
  }
49
56
  }
50
57
  };
@@ -33,28 +33,32 @@ var bundleConfigOverrides = {
33
33
  lwc: "@lwc/engine-server"
34
34
  }
35
35
  };
36
- var WORKER_CONTEXT_PREPEND = `const { parentPort } = require('worker_threads')`;
37
- var WORKER_CONTEXT_APPEND = `parentPort.postMessage(globalThis.workerResult)`;
38
- function runCodeOnWorker(code) {
39
- const workerCode = [WORKER_CONTEXT_PREPEND, code, WORKER_CONTEXT_APPEND].join("\n");
40
- return new Promise((resolve, reject) => {
36
+ var WORKER_CONTEXT_PREPEND = `const { parentPort } = require('worker_threads');`;
37
+ var WORKER_CONTEXT_APPEND = `parentPort.postMessage(globalThis.ssrWorkerResult);`;
38
+ function runCodeOnWorker(code, props) {
39
+ const workerCode = [
40
+ WORKER_CONTEXT_PREPEND,
41
+ `globalThis.ssrProps = ${JSON.stringify(props)};`,
42
+ code,
43
+ WORKER_CONTEXT_APPEND
44
+ ].join("\n");
45
+ return new Promise((resolve) => {
41
46
  const worker = new import_worker_threads.Worker(workerCode, {eval: true});
42
47
  worker.on("message", resolve);
43
- worker.on("error", reject);
48
+ worker.on("error", ({message}) => resolve({error: `SSR worker exited with error: ${message}`}));
44
49
  worker.on("exit", (code2) => {
45
50
  if (code2 !== 0) {
46
- reject(new Error(`Worker stopped with exit code ${code2}`));
51
+ resolve({error: `SSR worker stopped with exit code: ${code2}`});
47
52
  }
48
53
  });
49
54
  });
50
55
  }
51
- async function ssrElement(options, moduleBundler, runtimeEnvironment) {
52
- const {specifier} = options;
53
- const bundleDef = await moduleBundler.getModuleBundle({specifier}, runtimeEnvironment, void 0, bundleConfigOverrides);
54
- const result = await runCodeOnWorker(bundleDef.code);
55
- if (result.error) {
56
- throw new Error(result.error);
56
+ async function ssrElement({specifier, props}, moduleBundler, runtimeEnvironment) {
57
+ const {code} = await moduleBundler.getModuleBundle({specifier}, runtimeEnvironment, void 0, bundleConfigOverrides);
58
+ const {result, error} = await runCodeOnWorker(code, props);
59
+ if (error) {
60
+ throw new Error(error);
57
61
  } else {
58
- return result.result;
62
+ return result;
59
63
  }
60
64
  }
@@ -1,11 +1,23 @@
1
- import { ModuleCompiled, ModuleEntry, ModuleProvider, ModuleSource, ProviderContext, AbstractModuleId, ProviderAppConfig } from '@lwrjs/types';
1
+ import { ModuleCompiled, ModuleEntry, ModuleProvider, ProviderContext, AbstractModuleId } from '@lwrjs/types';
2
+ /**
3
+ * This module provider generates code which server-side renders a given component.
4
+ * It handles module specifiers in the form: "@lwrjs/lwc-ssr/${component specifier}".
5
+ * eg: "@lwrjs/lwc-ssr/my/appRoot"
6
+ */
7
+ /**
8
+ * Create the virtual source for a module which server-side renders the given component.
9
+ * This code is meant to be executed on the server; it is run in a worker in "lwc-ssr/viewTransformer#ssr-element" during linking.
10
+ * The resulting SSRed string (or error) is stored in globalThis.ssrWorkerResult for the worker to pass back to the main thread.
11
+ * @param rootComponent - The specifier for the component to SSR
12
+ * @param globalThis.ssrProps - The properties to pass to the component, set in "lwc-ssr/viewTransformer#ssr-element"
13
+ * @returns the generated module source
14
+ */
15
+ export declare function createSsrBootstrapModule(rootComponent: string): string;
2
16
  export default class LwcSsrModuleProvider implements ModuleProvider {
3
17
  name: string;
4
18
  version: string;
5
- config: ProviderAppConfig;
6
- constructor(appPluginConfig: unknown, { config, runtimeEnvironment: { hmrEnabled, lwrVersion } }: ProviderContext);
19
+ constructor(providerConfig: unknown, { runtimeEnvironment: { lwrVersion } }: ProviderContext);
7
20
  getModuleEntry({ specifier }: AbstractModuleId): Promise<ModuleEntry | undefined>;
8
- getModuleSource<R extends AbstractModuleId>({ specifier, namespace, name, }: R): Promise<ModuleSource | undefined>;
9
- getModule(moduleId: AbstractModuleId): Promise<ModuleCompiled | undefined>;
21
+ getModule({ specifier, namespace, name }: AbstractModuleId): Promise<ModuleCompiled | undefined>;
10
22
  }
11
23
  //# sourceMappingURL=index.d.ts.map
@@ -1,15 +1,34 @@
1
- import { LwrUnresolvableError, createSingleDiagnosticError, descriptions } from '@lwrjs/diagnostics';
2
- import { hashContent } from '@lwrjs/shared-utils';
3
- import { createSsrBootstrapModule } from './utils.js';
1
+ import { hashContent, moduleSpecifierToKebabCase } from '@lwrjs/shared-utils';
4
2
  import { LWC_SSR_PREFIX } from '../identity.js';
5
- function getRootModuleSpecifier(ssrSpecifier) {
6
- const [, , namespace, name] = ssrSpecifier.split('/');
7
- return `${namespace}/${name}`;
3
+ /**
4
+ * This module provider generates code which server-side renders a given component.
5
+ * It handles module specifiers in the form: "@lwrjs/lwc-ssr/${component specifier}".
6
+ * eg: "@lwrjs/lwc-ssr/my/appRoot"
7
+ */
8
+ /**
9
+ * Create the virtual source for a module which server-side renders the given component.
10
+ * This code is meant to be executed on the server; it is run in a worker in "lwc-ssr/viewTransformer#ssr-element" during linking.
11
+ * The resulting SSRed string (or error) is stored in globalThis.ssrWorkerResult for the worker to pass back to the main thread.
12
+ * @param rootComponent - The specifier for the component to SSR
13
+ * @param globalThis.ssrProps - The properties to pass to the component, set in "lwc-ssr/viewTransformer#ssr-element"
14
+ * @returns the generated module source
15
+ */
16
+ export function createSsrBootstrapModule(rootComponent) {
17
+ return [
18
+ '/* This module is generated and meant to be used in a Server context */',
19
+ 'import { renderComponent } from "@lwc/engine-server"',
20
+ `import Ctor from "${rootComponent}"`,
21
+ 'try {',
22
+ ` const result = renderComponent("${moduleSpecifierToKebabCase(rootComponent)}", Ctor, globalThis.ssrProps);`,
23
+ ' globalThis.ssrWorkerResult = { result };',
24
+ '} catch(err) {',
25
+ ' globalThis.ssrWorkerResult = { error: err.toString() };',
26
+ `}`,
27
+ ].join('\n');
8
28
  }
9
29
  export default class LwcSsrModuleProvider {
10
- constructor(appPluginConfig, { config, runtimeEnvironment: { hmrEnabled, lwrVersion } }) {
30
+ constructor(providerConfig, { runtimeEnvironment: { lwrVersion } }) {
11
31
  this.name = 'ssr-module-provider';
12
- this.config = config;
13
32
  this.version = lwrVersion;
14
33
  }
15
34
  async getModuleEntry({ specifier }) {
@@ -24,19 +43,13 @@ export default class LwcSsrModuleProvider {
24
43
  };
25
44
  }
26
45
  }
27
- async getModuleSource({ specifier, namespace, name, }) {
28
- if (!specifier.startsWith(LWC_SSR_PREFIX)) {
29
- return;
30
- }
31
- // Fetch the Module Entry and corresponding route config object
46
+ async getModule({ specifier, namespace, name }) {
32
47
  const moduleEntry = await this.getModuleEntry({ specifier });
33
48
  if (!moduleEntry) {
34
- throw createSingleDiagnosticError({
35
- description: descriptions.UNRESOLVABLE.MODULE(specifier),
36
- }, LwrUnresolvableError);
49
+ return;
37
50
  }
38
- const customElementModule = getRootModuleSpecifier(specifier);
39
- const originalSource = createSsrBootstrapModule(customElementModule);
51
+ // Generate the module source which SSRs a lwc, and return the Module
52
+ const originalSource = createSsrBootstrapModule(specifier.replace(LWC_SSR_PREFIX, ''));
40
53
  return {
41
54
  id: moduleEntry.id,
42
55
  namespace,
@@ -46,18 +59,7 @@ export default class LwcSsrModuleProvider {
46
59
  moduleEntry,
47
60
  ownHash: hashContent(originalSource),
48
61
  originalSource,
49
- };
50
- }
51
- async getModule(moduleId) {
52
- if (!moduleId.specifier.startsWith('@lwrjs/lwc-ssr/')) {
53
- return;
54
- }
55
- // Get the source to compile
56
- const moduleSource = (await this.getModuleSource(moduleId));
57
- const compiledSource = moduleSource.originalSource;
58
- return {
59
- ...moduleSource,
60
- compiledSource,
62
+ compiledSource: originalSource,
61
63
  };
62
64
  }
63
65
  }
@@ -1,7 +1,23 @@
1
- import { ProviderContext, ViewTransformPlugin } from '@lwrjs/types';
1
+ import type { ProviderContext, ViewTransformPlugin } from '@lwrjs/types';
2
2
  interface SsrPluginOptions {
3
3
  shareWorker?: boolean;
4
4
  }
5
- export default function lwcSsrViewTranformer(options: SsrPluginOptions, lwrGlobalContext: ProviderContext): ViewTransformPlugin;
5
+ /**
6
+ * This is a view transformer run by the view registry during linking of a page document/route (configured in lwr.config.json[routes]).
7
+ * If the "experimentalSSR" bootstrap flag is on for the route, it will server-side render (SSR) each custom element found in the page HTML.
8
+ *
9
+ * SSR Flow:
10
+ * 1. There is a request to generate a view (ie: page document) via the UI middleware or static site generation
11
+ * 2. During view generation, the view registry runs all the registered view transformers (including this one)
12
+ * 3. This view transformer links the SSRed string for EVERY custom element (ie: root component) found in the page document:
13
+ * a) It requests a module which SSRs a given custom element, generated by "lwc-ssr/moduleProvider"
14
+ * b) A bundle is created for the generated SSR module (see "./ssr-element")
15
+ * c) The bundle code is run inside a worker (see "./ssr-element"), with properties stored in "globalThis.ssrProps"
16
+ * d) The generated SSR module (running the worker) passes the SSRed code string back to the main thread (ie: "globalThis.ssrWorkerResult")
17
+ * e) The SSRed string is used to overwrite/link each custom element (eg: "<c-app></c-app>") in the document (see "stringBuild.overwrite")
18
+ * 4. The view/page document now contains SSRed components, which will be sent to the client
19
+ * 5. During bootstrap on the client, the "lwr/initSsr" module will hydrate ALL the custom elements on the page
20
+ */
21
+ export default function lwcSsrViewTranformer(options: SsrPluginOptions, { moduleBundler }: ProviderContext): ViewTransformPlugin;
6
22
  export {};
7
23
  //# sourceMappingURL=index.d.ts.map
@@ -1,24 +1,45 @@
1
- import { kebabcaseToCamelcase } from '@lwrjs/shared-utils';
1
+ import { kebabCaseToModuleSpecifer } from '@lwrjs/shared-utils';
2
2
  import { LWC_SSR_PREFIX } from '../identity.js';
3
3
  import { ssrElement } from './ssr-element.js';
4
- export default function lwcSsrViewTranformer(options, lwrGlobalContext) {
5
- const { moduleBundler } = lwrGlobalContext;
4
+ /**
5
+ * This is a view transformer run by the view registry during linking of a page document/route (configured in lwr.config.json[routes]).
6
+ * If the "experimentalSSR" bootstrap flag is on for the route, it will server-side render (SSR) each custom element found in the page HTML.
7
+ *
8
+ * SSR Flow:
9
+ * 1. There is a request to generate a view (ie: page document) via the UI middleware or static site generation
10
+ * 2. During view generation, the view registry runs all the registered view transformers (including this one)
11
+ * 3. This view transformer links the SSRed string for EVERY custom element (ie: root component) found in the page document:
12
+ * a) It requests a module which SSRs a given custom element, generated by "lwc-ssr/moduleProvider"
13
+ * b) A bundle is created for the generated SSR module (see "./ssr-element")
14
+ * c) The bundle code is run inside a worker (see "./ssr-element"), with properties stored in "globalThis.ssrProps"
15
+ * d) The generated SSR module (running the worker) passes the SSRed code string back to the main thread (ie: "globalThis.ssrWorkerResult")
16
+ * e) The SSRed string is used to overwrite/link each custom element (eg: "<c-app></c-app>") in the document (see "stringBuild.overwrite")
17
+ * 4. The view/page document now contains SSRed components, which will be sent to the client
18
+ * 5. During bootstrap on the client, the "lwr/initSsr" module will hydrate ALL the custom elements on the page
19
+ */
20
+ export default function lwcSsrViewTranformer(options, { moduleBundler }) {
6
21
  return {
7
22
  name: 'ssr-lwc-transformer',
8
- async link(stringBuilder, viewContext, viewMeta) {
23
+ async link(stringBuilder, viewContext, { customElements }) {
9
24
  if (viewContext.view.bootstrap?.experimentalSSR) {
10
- const { customElements } = viewMeta;
11
- for (const customElementRef of customElements) {
12
- if (customElementRef.location) {
13
- const { startOffset, endOffset } = customElementRef.location;
14
- const moduleSpecifier = kebabcaseToCamelcase(customElementRef.tagName);
15
- const ssrSpecifier = `${LWC_SSR_PREFIX}${moduleSpecifier}`;
16
- // TODO: Paralelize this await
17
- // eslint-disable-next-line no-await-in-loop
18
- const ssrResult = await ssrElement({ specifier: ssrSpecifier }, moduleBundler, viewContext.runtimeEnvironment);
19
- stringBuilder.overwrite(startOffset, endOffset, ssrResult);
25
+ const ssrModules = [];
26
+ for (const { tagName, location, props = {} } of customElements) {
27
+ if (location) {
28
+ const { startOffset, endOffset } = location;
29
+ const moduleSpecifier = kebabCaseToModuleSpecifer(tagName);
30
+ ssrModules.push({
31
+ startOffset,
32
+ endOffset,
33
+ props,
34
+ specifier: `${LWC_SSR_PREFIX}${moduleSpecifier}`,
35
+ });
20
36
  }
21
37
  }
38
+ return Promise.all(ssrModules.map(({ specifier, props, startOffset, endOffset }) => {
39
+ return ssrElement({ specifier, props }, moduleBundler, viewContext.runtimeEnvironment).then((ssrResult) => {
40
+ stringBuilder.overwrite(startOffset, endOffset, ssrResult);
41
+ });
42
+ })).then(() => undefined); // we need to ultimately return "void" here, there is nothing to return
22
43
  }
23
44
  },
24
45
  };
@@ -1,3 +1,16 @@
1
- import { AbstractModuleId, ModuleBundler, RuntimeEnvironment } from '@lwrjs/types';
2
- export declare function ssrElement<ModuleId extends AbstractModuleId, RuntimeEnv extends RuntimeEnvironment>(options: ModuleId, moduleBundler: ModuleBundler, runtimeEnvironment: RuntimeEnv): Promise<string>;
1
+ import type { ModuleBundler, RuntimeEnvironment } from '@lwrjs/types';
2
+ /**
3
+ * Create a bundle for the given SSR module and run the code in a worker.
4
+ * @param moduleInfo - specifier: The ID of the module, generated by "lwc-ssr/moduleProvider", which SSRs a component
5
+ * props: A map of the key:value property pairs parsed from the custom element attributes (ie: all string values)
6
+ * @param moduleBundler
7
+ * @param runtimeEnvironment
8
+ * @returns a promise to the SSRed code string
9
+ */
10
+ export declare function ssrElement<RuntimeEnv extends RuntimeEnvironment>({ specifier, props }: {
11
+ specifier: string;
12
+ props: {
13
+ [name: string]: string;
14
+ };
15
+ }, moduleBundler: ModuleBundler, runtimeEnvironment: RuntimeEnv): Promise<string>;
3
16
  //# sourceMappingURL=ssr-element.d.ts.map
@@ -2,33 +2,54 @@ import { Worker } from 'worker_threads';
2
2
  const bundleConfigOverrides = {
3
3
  exclude: [],
4
4
  alias: {
5
- lwc: '@lwc/engine-server',
5
+ lwc: '@lwc/engine-server', // override the default "@lwc/engine-dom" package
6
6
  },
7
7
  };
8
- const WORKER_CONTEXT_PREPEND = `const { parentPort } = require('worker_threads')`;
9
- const WORKER_CONTEXT_APPEND = `parentPort.postMessage(globalThis.workerResult)`;
10
- function runCodeOnWorker(code) {
11
- const workerCode = [WORKER_CONTEXT_PREPEND, code, WORKER_CONTEXT_APPEND].join('\n');
12
- return new Promise((resolve, reject) => {
8
+ const WORKER_CONTEXT_PREPEND = `const { parentPort } = require('worker_threads');`;
9
+ const WORKER_CONTEXT_APPEND = `parentPort.postMessage(globalThis.ssrWorkerResult);`;
10
+ /**
11
+ * Run the SSR process in a worker, and return the results to the main thread.
12
+ * The "globalThis.ssrWorkerResult" is set in the SSR module generated in "lwc-ssr/moduleProvider"
13
+ * then the result is posted to the parentPort, and the Promise in the main thread resolves.
14
+ * The properties are stored in "globalThis.ssrProps" and used in the SSR module.
15
+ * @param code - A string bundle for a module which SSRs a root component
16
+ * @param props - A map of the key:value property pairs to pass to the root component
17
+ * @returns a promise to the SSRed code string, or an error message
18
+ */
19
+ function runCodeOnWorker(code, props) {
20
+ const workerCode = [
21
+ WORKER_CONTEXT_PREPEND,
22
+ `globalThis.ssrProps = ${JSON.stringify(props)};`,
23
+ code,
24
+ WORKER_CONTEXT_APPEND,
25
+ ].join('\n');
26
+ return new Promise((resolve) => {
13
27
  const worker = new Worker(workerCode, { eval: true });
14
28
  worker.on('message', resolve);
15
- worker.on('error', reject);
29
+ worker.on('error', ({ message }) => resolve({ error: `SSR worker exited with error: ${message}` }));
16
30
  worker.on('exit', (code) => {
17
31
  if (code !== 0) {
18
- reject(new Error(`Worker stopped with exit code ${code}`));
32
+ resolve({ error: `SSR worker stopped with exit code: ${code}` });
19
33
  }
20
34
  });
21
35
  });
22
36
  }
23
- export async function ssrElement(options, moduleBundler, runtimeEnvironment) {
24
- const { specifier } = options;
25
- const bundleDef = await moduleBundler.getModuleBundle({ specifier }, runtimeEnvironment, undefined, bundleConfigOverrides);
26
- const result = await runCodeOnWorker(bundleDef.code);
27
- if (result.error) {
28
- throw new Error(result.error);
37
+ /**
38
+ * Create a bundle for the given SSR module and run the code in a worker.
39
+ * @param moduleInfo - specifier: The ID of the module, generated by "lwc-ssr/moduleProvider", which SSRs a component
40
+ * props: A map of the key:value property pairs parsed from the custom element attributes (ie: all string values)
41
+ * @param moduleBundler
42
+ * @param runtimeEnvironment
43
+ * @returns a promise to the SSRed code string
44
+ */
45
+ export async function ssrElement({ specifier, props }, moduleBundler, runtimeEnvironment) {
46
+ const { code } = await moduleBundler.getModuleBundle({ specifier }, runtimeEnvironment, undefined, bundleConfigOverrides);
47
+ const { result, error } = await runCodeOnWorker(code, props);
48
+ if (error) {
49
+ throw new Error(error);
29
50
  }
30
51
  else {
31
- return result.result;
52
+ return result;
32
53
  }
33
54
  }
34
55
  //# sourceMappingURL=ssr-element.js.map
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
7
- "version": "0.7.0-alpha.4",
7
+ "version": "0.7.0-alpha.7",
8
8
  "homepage": "https://developer.salesforce.com/docs/platform/lwr/overview",
9
9
  "repository": {
10
10
  "type": "git",
@@ -33,14 +33,14 @@
33
33
  "build/**/*.d.ts"
34
34
  ],
35
35
  "dependencies": {
36
- "@lwrjs/diagnostics": "0.7.0-alpha.4",
37
- "@lwrjs/shared-utils": "0.7.0-alpha.4"
36
+ "@lwrjs/diagnostics": "0.7.0-alpha.7",
37
+ "@lwrjs/shared-utils": "0.7.0-alpha.7"
38
38
  },
39
39
  "devDependencies": {
40
- "@lwrjs/types": "0.7.0-alpha.4"
40
+ "@lwrjs/types": "0.7.0-alpha.7"
41
41
  },
42
42
  "engines": {
43
43
  "node": ">=14.15.4 <17"
44
44
  },
45
- "gitHead": "611f98b00c050ddb2f0aca529c5d9a0d6e55cc3d"
45
+ "gitHead": "37d42307c304716834ce39944d5677e95d04a63a"
46
46
  }
@@ -1,42 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getProtoOf = Object.getPrototypeOf;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
- var __markAsModule = (target) => __defProp(target, "__esModule", {value: true});
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, {get: all[name], enumerable: true});
11
- };
12
- var __exportStar = (target, module2, desc) => {
13
- if (module2 && typeof module2 === "object" || typeof module2 === "function") {
14
- for (let key of __getOwnPropNames(module2))
15
- if (!__hasOwnProp.call(target, key) && key !== "default")
16
- __defProp(target, key, {get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable});
17
- }
18
- return target;
19
- };
20
- var __toModule = (module2) => {
21
- return __exportStar(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? {get: () => module2.default, enumerable: true} : {value: module2, enumerable: true})), module2);
22
- };
23
-
24
- // packages/@lwrjs/lwc-ssr/src/moduleProvider/utils.ts
25
- __markAsModule(exports);
26
- __export(exports, {
27
- createSsrBootstrapModule: () => createSsrBootstrapModule
28
- });
29
- var import_shared_utils = __toModule(require("@lwrjs/shared-utils"));
30
- function createSsrBootstrapModule(rootComponent) {
31
- return [
32
- "/* This module is meant to be used in a Server context */",
33
- 'import { renderComponent } from "@lwc/engine-server"',
34
- `import Ctor from "${rootComponent}"`,
35
- "try {",
36
- ` const result = renderComponent("${(0, import_shared_utils.moduleSpecifierToKebabCase)(rootComponent)}", Ctor, {});`,
37
- " globalThis.workerResult = { result };",
38
- "} catch(err) {",
39
- " globalThis.workerResult = { error: err.toString() };",
40
- `}`
41
- ].join("\n");
42
- }
@@ -1,6 +0,0 @@
1
- /**
2
- * Create the virtual source for the application bootstrap module
3
- * @returns the generated source
4
- */
5
- export declare function createSsrBootstrapModule(rootComponent: string): string;
6
- //# sourceMappingURL=utils.d.ts.map
@@ -1,19 +0,0 @@
1
- import { moduleSpecifierToKebabCase } from '@lwrjs/shared-utils';
2
- /**
3
- * Create the virtual source for the application bootstrap module
4
- * @returns the generated source
5
- */
6
- export function createSsrBootstrapModule(rootComponent) {
7
- return [
8
- '/* This module is meant to be used in a Server context */',
9
- 'import { renderComponent } from "@lwc/engine-server"',
10
- `import Ctor from "${rootComponent}"`,
11
- 'try {',
12
- ` const result = renderComponent("${moduleSpecifierToKebabCase(rootComponent)}", Ctor, {});`,
13
- ' globalThis.workerResult = { result };',
14
- '} catch(err) {',
15
- ' globalThis.workerResult = { error: err.toString() };',
16
- `}`,
17
- ].join('\n');
18
- }
19
- //# sourceMappingURL=utils.js.map