@lwrjs/lwc-ssr 0.7.0-alpha.7 → 0.7.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.
package/README.md ADDED
@@ -0,0 +1,130 @@
1
+ # Server-side rendering (SSR) in LWR
2
+
3
+ ## Overview
4
+
5
+ ### What is SSR?
6
+
7
+ [Lightning Web Components (LWC)](https://lwc.dev/) is a framework for creating client-side applications. However, these components can also be rendered as an HTML string on the **server**. LWR sends these strings to the client, where they can be ["hydrated"](#client-hydration) to create an interactive web app.
8
+
9
+ ### Why use SSR?
10
+
11
+ With SSR, the browser does not need to wait for all the JavaScript to download and execute before displaying component markup. This results in faster time-to-content, especially on slower devices or internet connections. It also makes the content accessible to search engine crawlers, improving SEO.
12
+
13
+ That said, SSR is best used for apps where time-to-content is important, such as B2C websites. The benefits of SSR should be weighed against the costs: higher server load, increased build & deployment complexity, developing server-compatible component code.
14
+
15
+ ## Using SSR with LWR
16
+
17
+ Learn how to use SSR in your LWR apps.
18
+
19
+ ### Turn on SSR
20
+
21
+ SSR is activated on a per-route basis by changing `bootstrap.experimentalSSR` to `true`:
22
+
23
+ ```json
24
+ // my-app/lwr.config.json
25
+ {
26
+ "routes": [
27
+ {
28
+ "id": "ssr-page",
29
+ // parameterized path
30
+ "path": "/category/:category",
31
+ // content template
32
+ "contentTemplate": "$contentDir/page.html",
33
+ "bootstrap": {
34
+ // turn on SSR for the page here
35
+ "experimentalSSR": true
36
+ }
37
+ }
38
+ ]
39
+ }
40
+ ```
41
+
42
+ ### Building SSR pages
43
+
44
+ When a route with `experimentalSSR` is requested, LWR will use [LWC'S `renderComponent()` function](https://rfcs.lwc.dev/rfcs/lwc/0112-server-engine) to SSR each root component on the page. This is done whether the page is generated at runtime, or pre-built using `generateStaticSite()`.
45
+
46
+ > A "root component" is any lwc in an app route's [content template, layout template](https://github.com/salesforce/lwr-recipes/tree/main/packages/templating#templates), or [`rootComponent` configuration](https://github.com/salesforce/lwr-recipes/blob/main/doc/config.md#routes).
47
+
48
+ LWR will automatically pass any root component attributes from a [template](https://github.com/salesforce/lwr-recipes/tree/main/packages/templating#templates) as [public properties](https://developer.salesforce.com/docs/component-library/documentation/en/lwc/reactivity_public) during SSR. For example, `my/root` will receive `{ limit: '10' }`.
49
+
50
+ ```html
51
+ <!-- my-app/src/content/page.html -->
52
+ <section>
53
+ <!-- "limit" is a template attribute property -->
54
+ <my-root limit="10"></my-root>
55
+ </section>
56
+ ```
57
+
58
+ #### Limitations
59
+
60
+ There are restrictions on component code for it to successfully render on the server. The `renderComponent()` function executes the [`constructor` and `connectedCallback`](https://developer.salesforce.com/docs/component-library/documentation/en/lwc/reference_lifecycle_hooks) of each component. These functions must be free of browser-specific code, such as DOM manipulation, eventing, and fetching data.
61
+
62
+ Because of this, the [`@lwrjs/router`](https://github.com/salesforce/lwr-recipes/blob/main/doc/navigation.md) is not supported with SSR.
63
+
64
+ ### Preloading data during SSR
65
+
66
+ Many components depend on external data. LWR provides a `getProps()` hook for developers to fetch that data on the server. LWR passes the data to the component during SSR as [properties](<(https://developer.salesforce.com/docs/component-library/documentation/en/lwc/reactivity_public)>).
67
+
68
+ > **Important**: This hook is **only** run for root components.
69
+
70
+ The `getProps()` hook is exported as a function from a root component module:
71
+
72
+ ```ts
73
+ // my-app/src/modules/my/root/root.ts
74
+ import { LightningElement, api } from 'lwc';
75
+ import type { PropsRequestContext, PropsResponse } from '@lwrjs/types';
76
+
77
+ export default class MyRoot extends LightningElement {
78
+ @api data: SomeDataType[] = [];
79
+ }
80
+
81
+ export async function getProps(context: PropsRequestContext): Promise<PropsResponse> {
82
+ // "/category/books" => context.params = { category: 'books' }
83
+ const category = context.params.category;
84
+ // page.html template => context.props = { limit: '10' }
85
+ const num = context.props.limit || '25';
86
+ const res = await context.fetch(`https://www.some-api.com/${category}?lang=${context.locale}&num=${num}`);
87
+ const data = await res.json();
88
+ return {
89
+ props: {
90
+ // will be passed to the root component as props
91
+ data,
92
+ ...context.props, // pass the template props through, if desired
93
+ },
94
+ };
95
+ }
96
+ ```
97
+
98
+ ```ts
99
+ type GetPropsHook = (context: PropsRequestContext) => Promise<PropsResponse>;
100
+
101
+ interface PropsRequestContext {
102
+ // existing props from template attributes
103
+ props: Json;
104
+ // values from a parameterized route defined in lwr.config.json
105
+ params: { [key: string]: string };
106
+ // search parameters from the request URL
107
+ query: { [key: string]: string };
108
+ // locale string for the request, eg: 'en-US'
109
+ locale: string;
110
+ // server-friendly fetch() function for accessing data
111
+ fetch: Function;
112
+ }
113
+
114
+ interface PropsResponse {
115
+ // serializable props for the root component
116
+ props: Json;
117
+ }
118
+
119
+ type Json = undefined | null | boolean | number | string | Json[] | { [prop: string]: Json };
120
+ ```
121
+
122
+ Notes:
123
+
124
+ - The `getProps()` hook can choose to merge the properties from `PropsRequestContext.props` into its return object, or it can ignore/discard them.
125
+ - The author of `getProps()` is responsible for validating the `params` and `query` from `PropsRequestContext` before using them.
126
+ - The **same** `props` returned by `getProps()` are passed to the component during server rendering **and** client hydration.
127
+
128
+ ### Client hydration
129
+
130
+ When SSRed component HTML reaches the browser, each root component is automatically hydrated. LWR uses the [LWC `hydrateComponent()` API](https://rfcs.lwc.dev/rfcs/lwc/0117-ssr-rehydration) to do so. Hydrating a component starts its component lifecycle and makes it interactive.
@@ -8,6 +8,14 @@ var __export = (target, all) => {
8
8
  // packages/@lwrjs/lwc-ssr/src/identity.ts
9
9
  __markAsModule(exports);
10
10
  __export(exports, {
11
- LWC_SSR_PREFIX: () => LWC_SSR_PREFIX
11
+ LWC_SSR_PREFIX: () => LWC_SSR_PREFIX,
12
+ SSR_PROPS_ATTR: () => SSR_PROPS_ATTR,
13
+ SSR_PROPS_KEY: () => SSR_PROPS_KEY,
14
+ getPropsId: () => getPropsId
12
15
  });
13
16
  var LWC_SSR_PREFIX = "@lwrjs/lwc-ssr/";
17
+ var SSR_PROPS_ATTR = "data-lwr-props-id";
18
+ var SSR_PROPS_KEY = "ssrProps";
19
+ function getPropsId() {
20
+ return `lwcprops${Math.floor(Math.random() * 65536).toString(16)}`;
21
+ }
@@ -29,18 +29,30 @@ __export(exports, {
29
29
  });
30
30
  var import_shared_utils = __toModule(require("@lwrjs/shared-utils"));
31
31
  var import_identity = __toModule(require("../identity.cjs"));
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");
32
+ function createSsrBootstrapModule(rootSpecifier) {
33
+ return `
34
+ import { renderComponent } from '@lwc/engine-server';
35
+ import Ctor, * as rootComponent from '${rootSpecifier}';
36
+
37
+ (async () => {
38
+ try {
39
+ let props = globalThis.context.props;
40
+ if (rootComponent.getProps) {
41
+ const data = await rootComponent.getProps({
42
+ props,
43
+ params: globalThis.context.params,
44
+ query: globalThis.context.query,
45
+ locale: globalThis.context.locale,
46
+ fetch: globalThis.fetch,
47
+ });
48
+ props = data.props; // overwrite public props
49
+ }
50
+ const result = renderComponent('${(0, import_shared_utils.moduleSpecifierToKebabCase)(rootSpecifier)}', Ctor, props || {});
51
+ globalThis.postMessage({ result, props });
52
+ } catch(e) {
53
+ globalThis.postMessage({ error: e });
54
+ }
55
+ })()`;
44
56
  }
45
57
  var LwcSsrModuleProvider = class {
46
58
  constructor(providerConfig, {runtimeEnvironment: {lwrVersion}}) {
@@ -0,0 +1,88 @@
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/viewTransformer/amd-utils.ts
25
+ __markAsModule(exports);
26
+ __export(exports, {
27
+ default: () => getCode
28
+ });
29
+ var import_loader = __toModule(require("@lwrjs/loader"));
30
+ var import_shared_utils = __toModule(require("@lwrjs/shared-utils"));
31
+ async function readableToString(readable) {
32
+ let result = "";
33
+ for await (const chunk of readable) {
34
+ result += chunk;
35
+ }
36
+ return result;
37
+ }
38
+ var loaderShimSource;
39
+ async function getLoaderShim(runtimeEnvironment) {
40
+ if (loaderShimSource !== void 0) {
41
+ return loaderShimSource;
42
+ }
43
+ const amdloaderShimService = new import_loader.default({}, {
44
+ runtimeEnvironment,
45
+ resourceRegistry: {resolveResourceUri: () => "NOT IMPLEMENTED"}
46
+ });
47
+ const specifier = (0, import_shared_utils.getFeatureFlags)().LEGACY_LOADER ? "lwr-loader-shim-legacy.bundle.js" : "lwr-loader-shim.bundle.js";
48
+ const resource = await amdloaderShimService.getResource({specifier}, runtimeEnvironment);
49
+ if (resource) {
50
+ const {stream} = resource;
51
+ if (stream) {
52
+ loaderShimSource = await readableToString(stream);
53
+ return loaderShimSource;
54
+ }
55
+ }
56
+ }
57
+ function getLwrConfig(bundleSpecifier, lwrVersion) {
58
+ return Object.assign({}, {
59
+ autoBoot: true,
60
+ bootstrapModule: `${bundleSpecifier}/v/${lwrVersion}`,
61
+ disableInitDefer: true,
62
+ endpoints: {
63
+ uris: {mapping: "/1/mapping/amd/1/l/en-US/mp/"}
64
+ },
65
+ rootComponents: [`${bundleSpecifier.split("@lwrjs/lwc-ssr/")[1]}/v/${lwrVersion}`]
66
+ }, (0, import_shared_utils.getFeatureFlags)().LEGACY_LOADER ? {
67
+ baseUrl: "ssr"
68
+ } : {
69
+ baseUrl: "/",
70
+ imports: {
71
+ "any/thing.js": ["any/thing"]
72
+ }
73
+ });
74
+ }
75
+ function lwcDefineOverride(lwcSpecifier) {
76
+ return `LWR.define("${lwcSpecifier}", ["${lwcSpecifier.replace("lwc", "@lwc/engine-server")}"], function(lwcEngine) { return lwcEngine; });`;
77
+ }
78
+ var GLOBALTHIS_LWR = `globalThis.LWR = globalThis.LWR || {};`;
79
+ async function getCode(runtimeEnvironment, lwrVersion, lwcSpecifier, bundleSpecifier) {
80
+ const loaderShimSource2 = await getLoaderShim(runtimeEnvironment);
81
+ const lwrConfigString = JSON.stringify(getLwrConfig(bundleSpecifier, lwrVersion));
82
+ return [
83
+ GLOBALTHIS_LWR,
84
+ `Object.assign(globalThis.LWR, ${lwrConfigString});`,
85
+ loaderShimSource2 ? loaderShimSource2 : "",
86
+ lwcSpecifier ? lwcDefineOverride(lwcSpecifier) : ""
87
+ ];
88
+ }
@@ -33,9 +33,12 @@ function lwcSsrViewTranformer(options, {moduleBundler}) {
33
33
  return {
34
34
  name: "ssr-lwc-transformer",
35
35
  async link(stringBuilder, viewContext, {customElements}) {
36
+ if (process.env.LOCKER === "true") {
37
+ return;
38
+ }
36
39
  if (viewContext.view.bootstrap?.experimentalSSR) {
37
40
  const ssrModules = [];
38
- for (const {tagName, location, props = {}} of customElements) {
41
+ for (const {tagName, location, props} of customElements) {
39
42
  if (location) {
40
43
  const {startOffset, endOffset} = location;
41
44
  const moduleSpecifier = (0, import_shared_utils.kebabCaseToModuleSpecifer)(tagName);
@@ -43,15 +46,26 @@ function lwcSsrViewTranformer(options, {moduleBundler}) {
43
46
  startOffset,
44
47
  endOffset,
45
48
  props,
49
+ tagName,
46
50
  specifier: `${import_identity.LWC_SSR_PREFIX}${moduleSpecifier}`
47
51
  });
48
52
  }
49
53
  }
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);
54
+ const ssrProps = {};
55
+ await Promise.all(ssrModules.map(({specifier, tagName, props, startOffset, endOffset}) => {
56
+ return (0, import_ssr_element.ssrElement)({specifier, props}, moduleBundler, viewContext).then(({html, props: props2}) => {
57
+ if (props2) {
58
+ const propsId = (0, import_identity.getPropsId)();
59
+ ssrProps[propsId] = props2;
60
+ const [, remain] = html.split(`<${tagName}`);
61
+ html = [`<${tagName}`, ` ${import_identity.SSR_PROPS_ATTR}="${propsId}"`, remain].join("");
62
+ }
63
+ stringBuilder.overwrite(startOffset, endOffset, html);
53
64
  });
54
- })).then(() => void 0);
65
+ }));
66
+ if (Object.keys(ssrProps).length) {
67
+ stringBuilder.prependLeft(ssrModules[0].startOffset, `<script type="application/javascript">globalThis.LWR = globalThis.LWR || {};globalThis.LWR.${import_identity.SSR_PROPS_KEY} = ${JSON.stringify(ssrProps)};</script>`);
68
+ }
55
69
  }
56
70
  }
57
71
  };
@@ -0,0 +1,52 @@
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/viewTransformer/sandbox.ts
25
+ __markAsModule(exports);
26
+ __export(exports, {
27
+ default: () => runCode
28
+ });
29
+ var import_worker_threads = __toModule(require("worker_threads"));
30
+ var HEADER = "/* This module is generated and meant to be used in a Server context */";
31
+ var WORKER_CODE_SANDBOX_APIS = [
32
+ `const { parentPort, workerData } = require('worker_threads');`,
33
+ `globalThis.context = workerData;`,
34
+ `globalThis.fetch = require('node-fetch');`,
35
+ `globalThis.postMessage = (...args) => parentPort.postMessage(...args);`
36
+ ];
37
+ function runCodeOnWorker(codes, workerData) {
38
+ const workerCode = [HEADER, ...WORKER_CODE_SANDBOX_APIS, ...codes].join("\n");
39
+ return new Promise((resolve) => {
40
+ const worker = new import_worker_threads.Worker(workerCode, {eval: true, workerData});
41
+ worker.on("message", resolve);
42
+ worker.on("error", ({message}) => resolve({error: `SSR worker exited with error: ${message}`}));
43
+ worker.on("exit", (code) => {
44
+ if (code !== 0) {
45
+ resolve({error: `SSR worker stopped with exit code: ${code}`});
46
+ }
47
+ });
48
+ });
49
+ }
50
+ function runCode(codes, context) {
51
+ return runCodeOnWorker(codes, context);
52
+ }
@@ -26,39 +26,34 @@ __markAsModule(exports);
26
26
  __export(exports, {
27
27
  ssrElement: () => ssrElement
28
28
  });
29
- var import_worker_threads = __toModule(require("worker_threads"));
29
+ var import_amd_utils = __toModule(require("./amd-utils.cjs"));
30
+ var import_sandbox = __toModule(require("./sandbox.cjs"));
30
31
  var bundleConfigOverrides = {
31
32
  exclude: [],
32
33
  alias: {
33
34
  lwc: "@lwc/engine-server"
34
35
  }
35
36
  };
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)};`,
37
+ async function ssrElement({specifier, props: templateProps}, moduleBundler, {runtimeEnvironment, runtimeParams}) {
38
+ const {
39
+ bundleRecord,
42
40
  code,
43
- WORKER_CONTEXT_APPEND
44
- ].join("\n");
45
- return new Promise((resolve) => {
46
- const worker = new import_worker_threads.Worker(workerCode, {eval: true});
47
- worker.on("message", resolve);
48
- worker.on("error", ({message}) => resolve({error: `SSR worker exited with error: ${message}`}));
49
- worker.on("exit", (code2) => {
50
- if (code2 !== 0) {
51
- resolve({error: `SSR worker stopped with exit code: ${code2}`});
52
- }
53
- });
54
- });
55
- }
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);
41
+ specifier: bundleSpecifier,
42
+ version
43
+ } = await moduleBundler.getModuleBundle({specifier}, {...runtimeEnvironment, bundle: false}, void 0, bundleConfigOverrides);
44
+ const context = {
45
+ props: templateProps,
46
+ params: runtimeParams.params || {},
47
+ query: runtimeParams.query || {},
48
+ locale: runtimeParams.locale || runtimeEnvironment.defaultLocale
49
+ };
50
+ const {error, result, props} = runtimeEnvironment.format === "amd" ? await (0, import_sandbox.default)([
51
+ ...await (0, import_amd_utils.default)(runtimeEnvironment, version.replace(/\./g, "_"), bundleRecord.includedModules.find((m) => m.startsWith("lwc/v")), bundleSpecifier),
52
+ code
53
+ ], context) : await (0, import_sandbox.default)([code], context);
59
54
  if (error) {
60
55
  throw new Error(error);
61
56
  } else {
62
- return result;
57
+ return {html: result, props};
63
58
  }
64
59
  }
@@ -1,2 +1,5 @@
1
1
  export declare const LWC_SSR_PREFIX = "@lwrjs/lwc-ssr/";
2
+ export declare const SSR_PROPS_ATTR = "data-lwr-props-id";
3
+ export declare const SSR_PROPS_KEY = "ssrProps";
4
+ export declare function getPropsId(): string;
2
5
  //# sourceMappingURL=identity.d.ts.map
@@ -1,2 +1,7 @@
1
1
  export const LWC_SSR_PREFIX = '@lwrjs/lwc-ssr/';
2
+ export const SSR_PROPS_ATTR = 'data-lwr-props-id';
3
+ export const SSR_PROPS_KEY = 'ssrProps';
4
+ export function getPropsId() {
5
+ return `lwcprops${Math.floor(Math.random() * 0x10000).toString(16)}`;
6
+ }
2
7
  //# sourceMappingURL=identity.js.map
@@ -6,13 +6,13 @@ import { ModuleCompiled, ModuleEntry, ModuleProvider, ProviderContext, AbstractM
6
6
  */
7
7
  /**
8
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"
9
+ * This code is meant to be executed in a worker on the server; it is run from "lwc-ssr/viewTransformer#ssr-element" during linking.
10
+ * The result is posted to the parentPort and the Promise in the main thread resolves.
11
+ * If available, getProps() is called on the root component to mutate context.props
12
+ * @param rootSpecifier - The specifier for the component to SSR
13
13
  * @returns the generated module source
14
14
  */
15
- export declare function createSsrBootstrapModule(rootComponent: string): string;
15
+ export declare function createSsrBootstrapModule(rootSpecifier: string): string;
16
16
  export default class LwcSsrModuleProvider implements ModuleProvider {
17
17
  name: string;
18
18
  version: string;
@@ -7,24 +7,36 @@ import { LWC_SSR_PREFIX } from '../identity.js';
7
7
  */
8
8
  /**
9
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"
10
+ * This code is meant to be executed in a worker on the server; it is run from "lwc-ssr/viewTransformer#ssr-element" during linking.
11
+ * The result is posted to the parentPort and the Promise in the main thread resolves.
12
+ * If available, getProps() is called on the root component to mutate context.props
13
+ * @param rootSpecifier - The specifier for the component to SSR
14
14
  * @returns the generated module source
15
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');
16
+ export function createSsrBootstrapModule(rootSpecifier) {
17
+ return `
18
+ import { renderComponent } from '@lwc/engine-server';
19
+ import Ctor, * as rootComponent from '${rootSpecifier}';
20
+
21
+ (async () => {
22
+ try {
23
+ let props = globalThis.context.props;
24
+ if (rootComponent.getProps) {
25
+ const data = await rootComponent.getProps({
26
+ props,
27
+ params: globalThis.context.params,
28
+ query: globalThis.context.query,
29
+ locale: globalThis.context.locale,
30
+ fetch: globalThis.fetch,
31
+ });
32
+ props = data.props; // overwrite public props
33
+ }
34
+ const result = renderComponent('${moduleSpecifierToKebabCase(rootSpecifier)}', Ctor, props || {});
35
+ globalThis.postMessage({ result, props });
36
+ } catch(e) {
37
+ globalThis.postMessage({ error: e });
38
+ }
39
+ })()`;
28
40
  }
29
41
  export default class LwcSsrModuleProvider {
30
42
  constructor(providerConfig, { runtimeEnvironment: { lwrVersion } }) {
@@ -0,0 +1,3 @@
1
+ import { RuntimeEnvironment } from '@lwrjs/types';
2
+ export default function getCode(runtimeEnvironment: RuntimeEnvironment, lwrVersion: string, lwcSpecifier: string | undefined, bundleSpecifier: string): Promise<string[]>;
3
+ //# sourceMappingURL=amd-utils.d.ts.map
@@ -0,0 +1,70 @@
1
+ import AmdLoaderShimService from '@lwrjs/loader';
2
+ import { getFeatureFlags } from '@lwrjs/shared-utils';
3
+ async function readableToString(readable) {
4
+ let result = '';
5
+ for await (const chunk of readable) {
6
+ result += chunk;
7
+ }
8
+ return result;
9
+ }
10
+ let loaderShimSource;
11
+ async function getLoaderShim(runtimeEnvironment) {
12
+ if (loaderShimSource !== undefined) {
13
+ return loaderShimSource;
14
+ }
15
+ const amdloaderShimService = new AmdLoaderShimService({}, {
16
+ runtimeEnvironment,
17
+ resourceRegistry: { resolveResourceUri: () => 'NOT IMPLEMENTED' },
18
+ });
19
+ const specifier = getFeatureFlags().LEGACY_LOADER
20
+ ? 'lwr-loader-shim-legacy.bundle.js'
21
+ : 'lwr-loader-shim.bundle.js';
22
+ const resource = await amdloaderShimService.getResource({ specifier }, runtimeEnvironment);
23
+ if (resource) {
24
+ const { stream } = resource;
25
+ if (stream) {
26
+ loaderShimSource = await readableToString(stream);
27
+ return loaderShimSource;
28
+ }
29
+ }
30
+ }
31
+ function getLwrConfig(bundleSpecifier, lwrVersion) {
32
+ // This is the minimum LWR config required for the loader to be created and mountApp to succeed
33
+ return Object.assign({}, {
34
+ autoBoot: true,
35
+ bootstrapModule: `${bundleSpecifier}/v/${lwrVersion}`,
36
+ disableInitDefer: true,
37
+ endpoints: {
38
+ uris: { mapping: '/1/mapping/amd/1/l/en-US/mp/' },
39
+ },
40
+ rootComponents: [`${bundleSpecifier.split('@lwrjs/lwc-ssr/')[1]}/v/${lwrVersion}`],
41
+ }, getFeatureFlags().LEGACY_LOADER
42
+ ? {
43
+ baseUrl: 'ssr',
44
+ }
45
+ : {
46
+ baseUrl: '/',
47
+ imports: {
48
+ 'any/thing.js': ['any/thing'],
49
+ },
50
+ });
51
+ }
52
+ // lwc/v/2_13_0 -> @lwc/engine-server/v/2_13_0
53
+ function lwcDefineOverride(lwcSpecifier) {
54
+ return `LWR.define("${lwcSpecifier}", ["${lwcSpecifier.replace('lwc', '@lwc/engine-server')}"], function(lwcEngine) { return lwcEngine; });`;
55
+ }
56
+ const GLOBALTHIS_LWR = `globalThis.LWR = globalThis.LWR || {};`;
57
+ export default async function getCode(runtimeEnvironment, lwrVersion, lwcSpecifier, bundleSpecifier) {
58
+ const loaderShimSource = await getLoaderShim(runtimeEnvironment);
59
+ const lwrConfigString = JSON.stringify(getLwrConfig(bundleSpecifier, lwrVersion));
60
+ // Order matters:
61
+ // 1. "globalThis.LWR" must be defined prior to executing the shim and loader
62
+ // 2. the lwc module override needs to be defined before lwc is [re]defined in the custom element code (first define wins)
63
+ return [
64
+ GLOBALTHIS_LWR,
65
+ `Object.assign(globalThis.LWR, ${lwrConfigString});`,
66
+ loaderShimSource ? loaderShimSource : '',
67
+ lwcSpecifier ? lwcDefineOverride(lwcSpecifier) : '',
68
+ ];
69
+ }
70
+ //# sourceMappingURL=amd-utils.js.map
@@ -12,9 +12,11 @@ interface SsrPluginOptions {
12
12
  * 3. This view transformer links the SSRed string for EVERY custom element (ie: root component) found in the page document:
13
13
  * a) It requests a module which SSRs a given custom element, generated by "lwc-ssr/moduleProvider"
14
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")
15
+ * c) The bundle code is run inside a worker (see "./ssr-element"), with context stored in "workerData"
16
+ * d) RootComponent.getProps() is run to preload data, if available
17
+ * e) The generated SSR module (running the worker) passes the SSRed code string back to the main thread
18
+ * f) The SSRed string is used to overwrite/link each custom element (eg: "<c-app></c-app>") in the document (see "stringBuilder.overwrite")
19
+ * g) A script containing all the serialized properties is added for hydration
18
20
  * 4. The view/page document now contains SSRed components, which will be sent to the client
19
21
  * 5. During bootstrap on the client, the "lwr/initSsr" module will hydrate ALL the custom elements on the page
20
22
  */
@@ -1,5 +1,5 @@
1
1
  import { kebabCaseToModuleSpecifer } from '@lwrjs/shared-utils';
2
- import { LWC_SSR_PREFIX } from '../identity.js';
2
+ import { LWC_SSR_PREFIX, SSR_PROPS_ATTR, SSR_PROPS_KEY, getPropsId } from '../identity.js';
3
3
  import { ssrElement } from './ssr-element.js';
4
4
  /**
5
5
  * This is a view transformer run by the view registry during linking of a page document/route (configured in lwr.config.json[routes]).
@@ -11,9 +11,11 @@ import { ssrElement } from './ssr-element.js';
11
11
  * 3. This view transformer links the SSRed string for EVERY custom element (ie: root component) found in the page document:
12
12
  * a) It requests a module which SSRs a given custom element, generated by "lwc-ssr/moduleProvider"
13
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")
14
+ * c) The bundle code is run inside a worker (see "./ssr-element"), with context stored in "workerData"
15
+ * d) RootComponent.getProps() is run to preload data, if available
16
+ * e) The generated SSR module (running the worker) passes the SSRed code string back to the main thread
17
+ * f) The SSRed string is used to overwrite/link each custom element (eg: "<c-app></c-app>") in the document (see "stringBuilder.overwrite")
18
+ * g) A script containing all the serialized properties is added for hydration
17
19
  * 4. The view/page document now contains SSRed components, which will be sent to the client
18
20
  * 5. During bootstrap on the client, the "lwr/initSsr" module will hydrate ALL the custom elements on the page
19
21
  */
@@ -21,9 +23,15 @@ export default function lwcSsrViewTranformer(options, { moduleBundler }) {
21
23
  return {
22
24
  name: 'ssr-lwc-transformer',
23
25
  async link(stringBuilder, viewContext, { customElements }) {
26
+ // SSR currently does not support locker because the module constructor returns undefined
27
+ // and the call to renderComponent would fail
28
+ if (process.env.LOCKER === 'true') {
29
+ return;
30
+ }
24
31
  if (viewContext.view.bootstrap?.experimentalSSR) {
32
+ // Gather all the SSRable custom elements (ie: root components) into 1 list
25
33
  const ssrModules = [];
26
- for (const { tagName, location, props = {} } of customElements) {
34
+ for (const { tagName, location, props } of customElements) {
27
35
  if (location) {
28
36
  const { startOffset, endOffset } = location;
29
37
  const moduleSpecifier = kebabCaseToModuleSpecifer(tagName);
@@ -31,15 +39,32 @@ export default function lwcSsrViewTranformer(options, { moduleBundler }) {
31
39
  startOffset,
32
40
  endOffset,
33
41
  props,
42
+ tagName,
34
43
  specifier: `${LWC_SSR_PREFIX}${moduleSpecifier}`,
35
44
  });
36
45
  }
37
46
  }
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);
47
+ // SSR and gather the properties for each eligible custom element, in parallel
48
+ const ssrProps = {};
49
+ await Promise.all(ssrModules.map(({ specifier, tagName, props, startOffset, endOffset }) => {
50
+ return ssrElement({ specifier, props }, moduleBundler, viewContext).then(({ html, props }) => {
51
+ if (props) {
52
+ // Add the props id to the HTML for the custom element
53
+ // eg: <some-cmp> -> <some-cmp data-lwr-props-id="1234">
54
+ const propsId = getPropsId();
55
+ ssrProps[propsId] = props;
56
+ const [, remain] = html.split(`<${tagName}`);
57
+ html = [`<${tagName}`, ` ${SSR_PROPS_ATTR}="${propsId}"`, remain].join('');
58
+ }
59
+ // Overwrite the custom element with the SSRed component string
60
+ stringBuilder.overwrite(startOffset, endOffset, html);
41
61
  });
42
- })).then(() => undefined); // we need to ultimately return "void" here, there is nothing to return
62
+ }));
63
+ if (Object.keys(ssrProps).length) {
64
+ // Serialize all root component properties into a single script for the page
65
+ // Append the script before the custom elements; it MUST appear before the AMD shim to avoid timing issues
66
+ stringBuilder.prependLeft(ssrModules[0].startOffset, `<script type="application/javascript">globalThis.LWR = globalThis.LWR || {};globalThis.LWR.${SSR_PROPS_KEY} = ${JSON.stringify(ssrProps)};</script>`);
67
+ }
43
68
  }
44
69
  },
45
70
  };
@@ -0,0 +1,9 @@
1
+ import { Json, PropsRequestContext } from '@lwrjs/types';
2
+ interface SandboxResults {
3
+ result?: string;
4
+ error?: string;
5
+ props?: Json;
6
+ }
7
+ export default function runCode(codes: string[], context: Partial<PropsRequestContext>): Promise<SandboxResults>;
8
+ export {};
9
+ //# sourceMappingURL=sandbox.d.ts.map
@@ -0,0 +1,41 @@
1
+ import { Worker } from 'worker_threads';
2
+ const HEADER = '/* This module is generated and meant to be used in a Server context */';
3
+ /**
4
+ * Sandbox APIs
5
+ * @param globalThis.context
6
+ * context such as props, params, and locale for executing SSR
7
+ *
8
+ * @param globalThis.fetch
9
+ * fetch function for external data fetching
10
+ *
11
+ * @param globalThis.postMessage
12
+ * postbacks from sandbox to main thread
13
+ */
14
+ const WORKER_CODE_SANDBOX_APIS = [
15
+ `const { parentPort, workerData } = require('worker_threads');`,
16
+ `globalThis.context = workerData;`,
17
+ `globalThis.fetch = require('node-fetch');`,
18
+ `globalThis.postMessage = (...args) => parentPort.postMessage(...args);`,
19
+ ];
20
+ /**
21
+ * Run the SSR module code in a worker, and return the results to the main thread.
22
+ * @param codes - Code strings which SSR a root component
23
+ * @returns a promise to the SSRed code string, or an error message
24
+ */
25
+ function runCodeOnWorker(codes, workerData) {
26
+ const workerCode = [HEADER, ...WORKER_CODE_SANDBOX_APIS, ...codes].join('\n');
27
+ return new Promise((resolve) => {
28
+ const worker = new Worker(workerCode, { eval: true, workerData });
29
+ worker.on('message', resolve);
30
+ worker.on('error', ({ message }) => resolve({ error: `SSR worker exited with error: ${message}` }));
31
+ worker.on('exit', (code) => {
32
+ if (code !== 0) {
33
+ resolve({ error: `SSR worker stopped with exit code: ${code}` });
34
+ }
35
+ });
36
+ });
37
+ }
38
+ export default function runCode(codes, context) {
39
+ return runCodeOnWorker(codes, context);
40
+ }
41
+ //# sourceMappingURL=sandbox.js.map
@@ -1,16 +1,17 @@
1
- import type { ModuleBundler, RuntimeEnvironment } from '@lwrjs/types';
1
+ import type { Json, ModuleBundler, ViewTranformPluginContext } from '@lwrjs/types';
2
2
  /**
3
- * Create a bundle for the given SSR module and run the code in a worker.
3
+ * Create a bundle for the given SSR module and run the code in a sandbox.
4
4
  * @param moduleInfo - specifier: The ID of the module, generated by "lwc-ssr/moduleProvider", which SSRs a component
5
5
  * props: A map of the key:value property pairs parsed from the custom element attributes (ie: all string values)
6
6
  * @param moduleBundler
7
7
  * @param runtimeEnvironment
8
8
  * @returns a promise to the SSRed code string
9
9
  */
10
- export declare function ssrElement<RuntimeEnv extends RuntimeEnvironment>({ specifier, props }: {
10
+ export declare function ssrElement({ specifier, props: templateProps }: {
11
11
  specifier: string;
12
- props: {
13
- [name: string]: string;
14
- };
15
- }, moduleBundler: ModuleBundler, runtimeEnvironment: RuntimeEnv): Promise<string>;
12
+ props: Json;
13
+ }, moduleBundler: ModuleBundler, { runtimeEnvironment, runtimeParams }: ViewTranformPluginContext): Promise<{
14
+ html: string;
15
+ props: Json;
16
+ }>;
16
17
  //# sourceMappingURL=ssr-element.d.ts.map
@@ -1,55 +1,44 @@
1
- import { Worker } from 'worker_threads';
1
+ import getCode from './amd-utils.js';
2
+ import runCode from './sandbox.js';
2
3
  const bundleConfigOverrides = {
3
4
  exclude: [],
4
5
  alias: {
5
6
  lwc: '@lwc/engine-server', // override the default "@lwc/engine-dom" package
6
7
  },
7
8
  };
8
- const WORKER_CONTEXT_PREPEND = `const { parentPort } = require('worker_threads');`;
9
- const WORKER_CONTEXT_APPEND = `parentPort.postMessage(globalThis.ssrWorkerResult);`;
10
9
  /**
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) => {
27
- const worker = new Worker(workerCode, { eval: true });
28
- worker.on('message', resolve);
29
- worker.on('error', ({ message }) => resolve({ error: `SSR worker exited with error: ${message}` }));
30
- worker.on('exit', (code) => {
31
- if (code !== 0) {
32
- resolve({ error: `SSR worker stopped with exit code: ${code}` });
33
- }
34
- });
35
- });
36
- }
37
- /**
38
- * Create a bundle for the given SSR module and run the code in a worker.
10
+ * Create a bundle for the given SSR module and run the code in a sandbox.
39
11
  * @param moduleInfo - specifier: The ID of the module, generated by "lwc-ssr/moduleProvider", which SSRs a component
40
12
  * props: A map of the key:value property pairs parsed from the custom element attributes (ie: all string values)
41
13
  * @param moduleBundler
42
14
  * @param runtimeEnvironment
43
15
  * @returns a promise to the SSRed code string
44
16
  */
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);
17
+ export async function ssrElement({ specifier, props: templateProps }, moduleBundler, { runtimeEnvironment, runtimeParams }) {
18
+ const { bundleRecord, code, specifier: bundleSpecifier, version, } = await moduleBundler.getModuleBundle({ specifier },
19
+ // Ensure the bundle flag is always off,
20
+ // otherwise TOO much gets bundled in the module registry
21
+ // in ESM, resulting lwc clashes/duplication
22
+ { ...runtimeEnvironment, bundle: false }, undefined, bundleConfigOverrides);
23
+ // Gather context to send into the SSR sandbox
24
+ const context = {
25
+ props: templateProps,
26
+ params: runtimeParams.params || {},
27
+ query: runtimeParams.query || {},
28
+ locale: runtimeParams.locale || runtimeEnvironment.defaultLocale,
29
+ };
30
+ // Get the SSR string and properties bag
31
+ const { error, result, props } = runtimeEnvironment.format === 'amd'
32
+ ? await runCode([
33
+ ...(await getCode(runtimeEnvironment, version.replace(/\./g, '_'), bundleRecord.includedModules.find((m) => m.startsWith('lwc/v')), bundleSpecifier)),
34
+ code,
35
+ ], context)
36
+ : await runCode([code], context);
48
37
  if (error) {
49
38
  throw new Error(error);
50
39
  }
51
40
  else {
52
- return result;
41
+ return { html: result, props };
53
42
  }
54
43
  }
55
44
  //# 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.7",
7
+ "version": "0.7.0",
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.7",
37
- "@lwrjs/shared-utils": "0.7.0-alpha.7"
36
+ "@lwrjs/diagnostics": "0.7.0",
37
+ "@lwrjs/shared-utils": "0.7.0"
38
38
  },
39
39
  "devDependencies": {
40
- "@lwrjs/types": "0.7.0-alpha.7"
40
+ "@lwrjs/types": "0.7.0"
41
41
  },
42
42
  "engines": {
43
- "node": ">=14.15.4 <17"
43
+ "node": ">=14.15.4 <19"
44
44
  },
45
- "gitHead": "37d42307c304716834ce39944d5677e95d04a63a"
45
+ "gitHead": "c6dcb52144a8da80170e30d49a87e29d2da30f9b"
46
46
  }