@pisapp/ssr-render 0.0.0-stage → 7.0.0-dev.20261028-114206

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/Dockerfile ADDED
@@ -0,0 +1,28 @@
1
+ # @pisapp/ssr-render docker image (works with docker and podman).
2
+ #
3
+ # Installs the published package from npm, so build this image after the
4
+ # version you pin is released. For a pre-release image, pack the workspace
5
+ # tarball and replace the npm install line with a COPY + npm install of it.
6
+ #
7
+ # Build: docker build -t pis-ssr-render .
8
+ # Run: docker run --rm -p 4181:4181 \
9
+ # -e PIS_RENDER_TOKEN=<shared-secret> \
10
+ # -e PIS_API_BASE_URL=https://external.productinformation.abb.com/PisWebApi \
11
+ # -e PIS_API_TOKEN=<api-token> \
12
+ # pis-ssr-render
13
+ FROM node:22-alpine
14
+
15
+ ENV NODE_ENV=production
16
+ WORKDIR /app
17
+
18
+ # Pin the major in production; the exact core version is reported as
19
+ # coreVersion on GET /health.
20
+ RUN npm install --omit=dev @pisapp/ssr-render@7
21
+
22
+ ENV PORT=4181
23
+ EXPOSE 4181
24
+
25
+ HEALTHCHECK --interval=30s --timeout=3s --start-period=5s \
26
+ CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||4181)+'/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
27
+
28
+ CMD ["pis-ssr-render"]
package/LICENSE ADDED
@@ -0,0 +1,36 @@
1
+ PRODUCT INFORMATION SERVICES (PIS) PROPRIETARY SOFTWARE LICENSE
2
+
3
+ Copyright (c) 2026 ABB Asea Brown Boveri Ltd. All rights reserved.
4
+
5
+ The Product Information Services (PIS) software package and its documentation
6
+ (the "Software") are proprietary and confidential property of ABB Asea Brown
7
+ Boveri Ltd ("ABB") and its licensors. The Software is closed source. No source
8
+ code rights are granted under this license.
9
+
10
+ An "Authorized User" is a person or organization that has completed the
11
+ applicable ABB onboarding process and is expressly authorized to use PIS under
12
+ a valid written agreement with ABB (the "Applicable Agreement"). Subject to
13
+ the Applicable Agreement, ABB grants each Authorized User a limited,
14
+ non-exclusive, non-transferable, non-sublicensable license to install and use
15
+ the Software solely to develop, test, and run applications that access PIS
16
+ services for the purposes authorized by the Applicable Agreement.
17
+
18
+ Except to the extent that mandatory law does not allow a restriction, you may
19
+ not copy, modify, adapt, distribute, publish, disclose, sublicense, rent, lease,
20
+ sell, or otherwise make the Software available to any unauthorized person or
21
+ third party. You may not remove or alter proprietary notices, derive source
22
+ code from the Software, or reverse engineer, decompile, or disassemble the
23
+ Software except as expressly permitted by mandatory law.
24
+
25
+ ABB and its licensors retain all right, title, and interest in and to the
26
+ Software. No rights are granted by implication. If you are not an Authorized
27
+ User, no license to use the Software is granted. Your right to use the Software
28
+ ends immediately when the Applicable Agreement ends or your authorization is
29
+ withdrawn.
30
+
31
+ Third-party components included with the Software remain subject to their
32
+ applicable license terms identified in THIRD-PARTY-NOTICES.txt.
33
+
34
+ The Applicable Agreement controls if it conflicts with this license. The
35
+ Software is provided subject to the warranties, limitations of liability,
36
+ confidentiality obligations, and other terms in the Applicable Agreement.
package/README.md CHANGED
@@ -1,3 +1,175 @@
1
- # Temporary Holding Version
1
+ # @pisapp/ssr-render
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Self-contained PIS product-details render service: fully server-rendered,
4
+ SEO-ready details-view HTML fragments for backends that cannot run a
5
+ JavaScript renderer - .NET, PHP, Java, or any HTTP client. One dependency
6
+ (`@pisapp/core`), one file, run it with Node or docker/podman.
7
+
8
+ Why: the details endpoint returns only the first page of data (relationships,
9
+ variants), so a fully working page needs (a) crawlable content in the initial
10
+ HTML, (b) the initial data embedded so the first render is instant, and (c) an
11
+ interactive client that lazy-loads the rest. This service produces exactly
12
+ that trio; your app embeds the fragment and, optionally, exposes a short-lived
13
+ public-data token so the lazy loads run live from the browser.
14
+
15
+ ## Quick start (Node)
16
+
17
+ ```bash
18
+ npm install @pisapp/ssr-render
19
+ PIS_RENDER_TOKEN=myservice \
20
+ PIS_API_BASE_URL=https://external.productinformation.abb.com/PisWebApi \
21
+ PIS_API_TOKEN=<api-token> \
22
+ npx pis-ssr-render
23
+ # [pis-ssr-render] listening on http://127.0.0.1:4181
24
+ ```
25
+
26
+ ## Quick start (docker / podman)
27
+
28
+ ```bash
29
+ docker build -t pis-ssr-render node_modules/@pisapp/ssr-render/
30
+ docker run --rm -p 4181:4181 \
31
+ -e PIS_RENDER_TOKEN=myservice \
32
+ -e PIS_API_BASE_URL=https://external.productinformation.abb.com/PisWebApi \
33
+ -e PIS_API_TOKEN=<api-token> \
34
+ pis-ssr-render
35
+ ```
36
+
37
+ `podman` takes the same commands. The image installs the package from npm and
38
+ carries a `HEALTHCHECK` against `GET /health`. The core version is reported as
39
+ `coreVersion` on `GET /health`.
40
+
41
+ ## Environment
42
+
43
+ | Variable | Purpose | Default |
44
+ | -------------------------- | -------------------------------------------------- | --------------------------- |
45
+ | `PORT` | listen port | `4181` |
46
+ | `PIS_RENDER_TOKEN` | bearer token callers must present | (unset = auth always fails) |
47
+ | `PIS_RENDER_AUTH=off` | disable caller auth (local dev only) | - |
48
+ | `PIS_API_BASE_URL` | PIS Web API base URL (service-fetch mode) | - |
49
+ | `PIS_API_TOKEN` | PIS Web API access token (service-fetch mode) | - |
50
+ | `PIS_ALLOW_TOKEN_EXPOSURE` | permit per-request `exposeAccessToken` (see below) | off |
51
+ | `PIS_STYLES_BASE` | stylesheet base URL | version-pinned jsDelivr |
52
+ | `PIS_CLIENT_SCRIPT_URL` | `pis-csp.js` URL | version-pinned jsDelivr |
53
+
54
+ ## The render request
55
+
56
+ `POST /render/products/details` with `Authorization: Bearer <PIS_RENDER_TOKEN>`:
57
+
58
+ ```json
59
+ {
60
+ "productId": "2CSF202201R5400",
61
+ "appSettings": { "appCode": "YOUR_APP_CODE", "langCode": "en" },
62
+
63
+ "composition": ["header", "gallery", "data"],
64
+ "template": "<div class='row'><pis-products-details-data instance-id='p'></pis-products-details-data></div>",
65
+
66
+ "payload": { "detail": { "...": "your /v2/Products/Detail response" }, "translations": [] },
67
+ "baseUrl": "https://your-gateway/PisWebApi",
68
+
69
+ "theme": "theme-abb",
70
+ "structuredData": true,
71
+ "layout": { "headerHtml": "...", "footerHtml": "...", "headExtra": "..." },
72
+ "mode": "fragment",
73
+ "cacheSeconds": 3600,
74
+
75
+ "exposeAccessToken": true,
76
+ "accessToken": "<short-lived public-data token>"
77
+ }
78
+ ```
79
+
80
+ Pick ONE of `composition` / `template` (default: `header, gallery, data`).
81
+
82
+ - **`composition`** - the canonical assembly inside the standard
83
+ `pis-products-instance` / router-view wrapper.
84
+ - **`template`** - YOUR partial markup (a .NET partial view, a PHP fragment).
85
+ The renderer keeps your chrome byte-for-byte and injects each
86
+ `pis-products-details-*` component's rendered internals, preserving the
87
+ tags' attributes and your static slotted children; unknown `pis-*` tags
88
+ pass through as shells.
89
+
90
+ Pick ONE data flow:
91
+
92
+ - **Service fetch** (default) - set `PIS_API_BASE_URL` + `PIS_API_TOKEN`; the
93
+ service fetches per render with its own `User-Agent` (trusted
94
+ `X-Forwarded-For` may be passed per request via `fetch.headers`).
95
+ - **Caller payload** - your backend already fetched
96
+ `/v2/Products/Detail` + `/v2/Translations` (for page metadata or caching);
97
+ pass the FULL, unmodified responses as `payload`. The service never touches
98
+ the PIS Web API; set `baseUrl` to the endpoint your page's live requests
99
+ should use (typically your gateway).
100
+
101
+ ## The response
102
+
103
+ `text/html; charset=utf-8` (or JSON with `Accept: application/json` /
104
+ `"format": "json"` - the raw render result: `html`, `head`, `cssImports`,
105
+ `embeddedPayload`, `found`). The fragment contains, in order: your layout
106
+ chrome, theme stylesheet links (theme first, then `pis.css` and `fonts.css`),
107
+ optional schema.org JSON-LD, the
108
+ SSR-Embedded Initial Data payloads, the server-rendered markup, and in
109
+ `fragment` mode the version-pinned `pis-csp.js` plus the one-shot bootstrap.
110
+ `mode: "seo-only"` omits the scripts. `Cache-Control` caps at one hour
111
+ (`cacheSeconds`, per the caching guidance).
112
+
113
+ ## Token exposure (live lazy loads)
114
+
115
+ Relationship pagination, sparse variants-table groups, and autocomplete fetch
116
+ live from the browser - the standard PIS web-components flow - and therefore
117
+ need an access token in the page. Enable it with `PIS_ALLOW_TOKEN_EXPOSURE=1`
118
+ on the service AND `exposeAccessToken: true` + `accessToken` per request; the
119
+ token then rides in the bootstrap and responses are marked
120
+ `Cache-Control: private`. Only short-lived PUBLIC-data application tokens
121
+ may reach the browser; internal-data tokens must stay server-side behind your
122
+ BFF/gateway.
123
+
124
+ ## Runtime templates
125
+
126
+ Customize any `*Template` mount point through the `templates` request field
127
+ (dotted paths into the components tree):
128
+
129
+ ```json
130
+ {
131
+ "templates": {
132
+ "details.actions.actionTemplate": "<button class=\"btn\" :data-product-id=\"item.productId\">Add {{ item.productId }}</button>",
133
+ "details.gallery.imageOverlayTemplate": {
134
+ "source": "container.innerHTML = '<b>' + ctx.item.productId + '</b>';"
135
+ }
136
+ }
137
+ }
138
+ ```
139
+
140
+ - **Strings** are legacy Vue templates: compiled for the server render and
141
+ embedded for the client - the CLIENT build must be the compiler-enabled
142
+ `pis.js` (the service rejects strings when its client script is
143
+ `pis-csp.js`; `seo-only` mode is exempt).
144
+ - **`{ source }`** values are render-function bodies, gated by
145
+ `PIS_ALLOW_TEMPLATE_FUNCTIONS=1` (trusted callers: the source executes
146
+ server- and client-side). The server renders them through an
147
+ innerHTML-capturing shim; the bootstrap rebuilds the functions before
148
+ `init()`.
149
+
150
+ ## Events, commands, and the full init configuration
151
+
152
+ Every serializable `init()` option from the render request (`appSettings`,
153
+ `components`, `allowMobileView`, `baseUrl`, the opt-in token) is
154
+ embedded in the fragment's bootstrap, so the client upgrade re-renders with
155
+ the same configuration as the server render. Functions cannot cross JSON -
156
+ define `window.pisSsrRenderReady(instance, options)` in your page before the
157
+ fragment's scripts to attach event listeners (`instance.on(...)`) and set
158
+ option functions (`commandInterceptor`, `onUserAction`, `errorInterceptor`);
159
+ the hook runs right before `init()`. `dataInterceptor` is not a request
160
+ field: enrich the payload in your backend instead (the hook covers any
161
+ client-side enrichment of lazy loads). Full walkthrough with .NET/PHP
162
+ examples on the documentation site (Headless Details Rendering).
163
+
164
+ ## Embedding examples
165
+
166
+ See the documentation site page (Headless Details Rendering, served under
167
+ `https://<docs-host>/pisdocs/current/components/common/headless-rendering`) for
168
+ the full .NET and PHP embedding walkthroughs, the Angular/Next.js/Nuxt SSR
169
+ alternatives, and the underlying `@pisapp/core/server` API used by framework
170
+ consumers.
171
+
172
+ ## How it works
173
+
174
+ The service is one file (`server.mjs`) plus the bin launcher; rendering is
175
+ delegated to `@pisapp/core/server` (`renderProductDetails`).
@@ -0,0 +1,43 @@
1
+ THIRD-PARTY NOTICES
2
+
3
+ Product Information Services (PIS) packages may include or depend on the
4
+ third-party software listed below. The applicable third-party license terms
5
+ apply to that software.
6
+
7
+ Bootstrap 5.3.2
8
+ Copyright (c) 2011-2023 The Bootstrap Authors
9
+
10
+ vue-virtual-scroller 2.0.1
11
+ Copyright (c) 2020 guillaume.b.chau@gmail.com
12
+
13
+ Vue 3.5.40
14
+ Copyright (c) 2018-present, Yuxi (Evan) You
15
+
16
+ vue3-runtime-template 1.0.2
17
+ Copyright (c) 2018 Alex Jover
18
+
19
+ The components listed above are licensed under the MIT License:
20
+
21
+ MIT License
22
+
23
+ Permission is hereby granted, free of charge, to any person obtaining a copy
24
+ of this software and associated documentation files (the "Software"), to deal
25
+ in the Software without restriction, including without limitation the rights
26
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
27
+ copies of the Software, and to permit persons to whom the Software is
28
+ furnished to do so, subject to the following conditions:
29
+
30
+ The above copyright notice and this permission notice shall be included in all
31
+ copies or substantial portions of the Software.
32
+
33
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
34
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
35
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
36
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
37
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
38
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
39
+ SOFTWARE.
40
+
41
+ ABBvoice font assets are proprietary ABB assets. They are not redistributed in
42
+ these npm packages. PIS CSS references the ABB-hosted font service at:
43
+ https://external.productinformation.abb.com/PisApp/current/fonts/
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ // @pisapp/ssr-render launcher: starts the render service from environment
3
+ // variables (see the package README / server.mjs header for the full list).
4
+
5
+ import { createRenderService } from '../server.mjs';
6
+
7
+ const PORT = Number(process.env.PORT ?? 4181);
8
+
9
+ createRenderService().listen(PORT, () => {
10
+ console.log(`[pis-ssr-render] listening on http://127.0.0.1:${PORT}`);
11
+ });
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@pisapp/ssr-render",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "7.0.0-dev.20261028-114206",
4
+ "license": "SEE LICENSE IN LICENSE",
5
+ "author": "ABB Asea Brown Boveri Ltd",
6
+ "description": "Self-contained PIS details-view render service (plan/25, decisions.md D10): serves fully server-rendered product details HTML fragments to any backend (.NET, PHP, ...) through @pisapp/core/server - composition or consumer-template mode, caller payloads or service-side fetches, opt-in token exposure for live lazy loads, one-file Node or docker/podman deployment.",
7
+ "type": "module",
8
+ "bin": {
9
+ "pis-ssr-render": "./bin/pis-ssr-render.mjs"
10
+ },
11
+ "main": "./server.mjs",
12
+ "exports": {
13
+ ".": {
14
+ "import": "./server.mjs"
15
+ },
16
+ "./package.json": "./package.json"
17
+ },
18
+ "files": [
19
+ "server.mjs",
20
+ "bin",
21
+ "Dockerfile",
22
+ "README.md",
23
+ "LICENSE",
24
+ "THIRD-PARTY-NOTICES.txt"
25
+ ],
26
+ "dependencies": {
27
+ "@pisapp/core": "7.0.0-dev.20261028-114206"
28
+ },
29
+ "devDependencies": {
30
+ "vitest": "^4.1.11"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "engines": {
36
+ "node": ">=22"
37
+ },
38
+ "pisRelease": {
39
+ "version": "7.0.0-dev.20261028-114206",
40
+ "channel": "dev",
41
+ "commit": "cb4e027d70a09e071fd486e7b5dd70f2bea567a6"
42
+ },
43
+ "scripts": {
44
+ "start": "node bin/pis-ssr-render.mjs",
45
+ "build": "node --check server.mjs && node --check bin/pis-ssr-render.mjs && echo ssr-render sources parse",
46
+ "lint": "eslint . --max-warnings 0",
47
+ "lint:fix": "eslint . --fix",
48
+ "test": "vitest run"
49
+ }
6
50
  }
package/server.mjs ADDED
@@ -0,0 +1,522 @@
1
+ #!/usr/bin/env node
2
+ // @pisapp/ssr-render - the self-contained headless PIS details render
3
+ // service (plan/25, decisions.md D10). Run it with Node or docker/podman and
4
+ // call it from any backend (.NET, PHP, Java, ...).
5
+ //
6
+ // Renders fully server-rendered product details HTML through the
7
+ // @pisapp/core/server surface. One POST per product page; the response is a
8
+ // complete, embeddable HTML fragment: layout chrome, theme stylesheets, the
9
+ // SSR-Embedded Initial Data payloads, the server-rendered pis-* markup, and
10
+ // (in "fragment" mode) the pis-csp.js client upgrade. Two data flows:
11
+ //
12
+ // - Service-fetch (default): the service holds the PIS Web API credentials
13
+ // (PIS_API_BASE_URL + PIS_API_TOKEN) and fetches per render.
14
+ // - Caller-payload: your backend fetches /v2/Products/Detail itself (for
15
+ // page metadata, caching, or template composition) and passes the full,
16
+ // unmodified responses as `payload` - the service then never touches the
17
+ // PIS Web API.
18
+ //
19
+ // Composition: pass `composition` for the canonical assembly, or `template`
20
+ // with your own partial markup (a .NET partial view, a PHP fragment) - the
21
+ // renderer keeps your chrome byte-for-byte and injects each
22
+ // pis-products-details-* component's rendered internals.
23
+ //
24
+ // Security model:
25
+ // - Callers authenticate with a shared bearer token (PIS_RENDER_TOKEN).
26
+ // Set PIS_RENDER_AUTH=off only for local development.
27
+ // - The service-side PIS Web API credentials never appear in responses.
28
+ // - Opt-in token exposure: lazy loads (relationship pagination, sparse
29
+ // variants-table groups, autocomplete) fetch live from the browser, and
30
+ // that standard flow needs an access token in the page. Enable it with
31
+ // PIS_ALLOW_TOKEN_EXPOSURE=1 on the service AND `exposeAccessToken: true`
32
+ // + `accessToken` per request; the token rides in the bootstrap, and
33
+ // responses are marked Cache-Control: private. Per decision D2 this must
34
+ // be a short-lived PUBLIC-data application token - internal-data tokens
35
+ // must never reach the browser.
36
+ // - Server fetches set their own User-Agent; an X-Forwarded-For may be
37
+ // supplied per request ONLY by the trusted caller (request.fetch.headers)
38
+ // and must be derived from a connection the caller trusts.
39
+ //
40
+ // Environment:
41
+ // PORT listen port (default 4181)
42
+ // PIS_RENDER_TOKEN required bearer token for callers
43
+ // PIS_RENDER_AUTH=off disable auth (local dev only)
44
+ // PIS_API_BASE_URL PIS Web API base URL (service-fetch mode)
45
+ // PIS_API_TOKEN PIS Web API access token (service-fetch mode)
46
+ // PIS_ALLOW_TOKEN_EXPOSURE set to 1/true to permit exposeAccessToken
47
+ // PIS_ALLOW_TEMPLATE_FUNCTIONS set to 1/true to permit { source } template dialect
48
+ // PIS_STYLES_BASE stylesheet base URL (default: version-pinned jsDelivr)
49
+ // PIS_CLIENT_SCRIPT_URL pis-csp.js URL (default: version-pinned jsDelivr)
50
+
51
+ import { CORE_VERSION, renderProductDetails } from '@pisapp/core/server';
52
+ import { createServer } from 'node:http';
53
+
54
+ const PORT = Number(process.env.PORT ?? 4181);
55
+ const AUTH_TOKEN = process.env.PIS_RENDER_TOKEN;
56
+ const AUTH_DISABLED = process.env.PIS_RENDER_AUTH === 'off';
57
+ const API_BASE_URL = process.env.PIS_API_BASE_URL;
58
+ const API_TOKEN = process.env.PIS_API_TOKEN;
59
+ const ALLOW_TOKEN_EXPOSURE = ['1', 'true'].includes(
60
+ String(process.env.PIS_ALLOW_TOKEN_EXPOSURE ?? '').toLowerCase(),
61
+ );
62
+ const ALLOW_TEMPLATE_FUNCTIONS = ['1', 'true'].includes(
63
+ String(process.env.PIS_ALLOW_TEMPLATE_FUNCTIONS ?? '').toLowerCase(),
64
+ );
65
+ const STYLES_BASE =
66
+ process.env.PIS_STYLES_BASE ?? `https://cdn.jsdelivr.net/npm/@pisapp/core@${CORE_VERSION}/styles`;
67
+ const CLIENT_SCRIPT_URL =
68
+ process.env.PIS_CLIENT_SCRIPT_URL ??
69
+ `https://cdn.jsdelivr.net/npm/@pisapp/core@${CORE_VERSION}/pis-csp.js`;
70
+
71
+ /** Docs guidance: server-side detail caches live at most one hour. */
72
+ const MAX_CACHE_SECONDS = 3600;
73
+ const MAX_BODY_BYTES = 512 * 1024;
74
+
75
+ function stripHtmlUnsafeKeys(options) {
76
+ if (!options || typeof options !== 'object') return {};
77
+ const { baseUrl, accessToken, httpInterceptor, commandInterceptor, ...rest } = options;
78
+ void baseUrl;
79
+ void accessToken;
80
+ void httpInterceptor;
81
+ void commandInterceptor;
82
+ return rest;
83
+ }
84
+
85
+ function escapeJsonForInline(value) {
86
+ return JSON.stringify(value ?? null).replace(/</g, '\\u003c');
87
+ }
88
+
89
+ /** Escapes a caller value for interpolation into a double-quoted HTML attribute. */
90
+ function escapeHtmlAttribute(value) {
91
+ return String(value).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
92
+ }
93
+
94
+ /**
95
+ * Runtime template request field (plan/25 follow-up):
96
+ * `{ "details.actions.actionTemplate": "<template>" | { "source": "..." } }`.
97
+ *
98
+ * - STRING values are legacy Vue template strings: the server render compiles
99
+ * them (vue3-runtime-template in the core server chunk) and they ride in
100
+ * the bootstrap verbatim - the CLIENT upgrade needs the compiler-enabled
101
+ * pis.js build to compile them again (validated below).
102
+ * - `{ source }` values are render-FUNCTION sources (`(container, ctx) =>
103
+ * ...` bodies): gated by PIS_ALLOW_TEMPLATE_FUNCTIONS=1. The server
104
+ * executes them through MountPoint's innerHTML-capture shim; the bootstrap
105
+ * reconstructs real functions with `new Function` before init.
106
+ *
107
+ * Returns the merged server components tree, the client components tree
108
+ * (function sources as `__pisTemplateSource` markers for the bootstrap to
109
+ * hydrate), and dialect flags.
110
+ */
111
+ function mergeRuntimeTemplates(components, templates) {
112
+ const server = structuredClone(components ?? {});
113
+ const client = structuredClone(components ?? {});
114
+ const dialects = { strings: false, sources: false };
115
+
116
+ for (const [path, value] of Object.entries(templates ?? {})) {
117
+ const segments = path.split('.');
118
+ if (segments.length === 0 || segments.some((s) => !/^[A-Za-z0-9_-]+$/.test(s))) {
119
+ return { error: `invalid template path "${path}"` };
120
+ }
121
+
122
+ const setDeep = (tree, leafValue) => {
123
+ let node = tree;
124
+ for (const segment of segments.slice(0, -1)) {
125
+ if (typeof node[segment] !== 'object' || node[segment] === null) node[segment] = {};
126
+ node = node[segment];
127
+ }
128
+ node[segments[segments.length - 1]] = leafValue;
129
+ };
130
+
131
+ if (typeof value === 'string') {
132
+ if (value.length === 0) return { error: `empty template value at "${path}"` };
133
+ dialects.strings = true;
134
+ // Server: the core renderer compiles *Template strings natively.
135
+ setDeep(server, value);
136
+ // Client: strings ride verbatim (compiled by the pis.js runtime).
137
+ setDeep(client, value);
138
+ continue;
139
+ }
140
+
141
+ if (value && typeof value === 'object' && typeof value.source === 'string') {
142
+ if (value.source.length === 0) return { error: `empty template source at "${path}"` };
143
+ dialects.sources = true;
144
+ // Server: a real function; MountPoint captures its output without a DOM.
145
+ setDeep(server, compileTemplateSource(value.source, path));
146
+ // Client: a marker the bootstrap converts back into a function.
147
+ setDeep(client, { __pisTemplateSource: value.source });
148
+ continue;
149
+ }
150
+
151
+ return { error: `template value at "${path}" must be a string or { source: string }` };
152
+ }
153
+
154
+ return { server, client, dialects };
155
+ }
156
+
157
+ function compileTemplateSource(source, path) {
158
+ try {
159
+ return new Function('container', 'ctx', source);
160
+ } catch (error) {
161
+ throw new Error(`template source at "${path}" does not evaluate: ${error.message}`, {
162
+ cause: error,
163
+ });
164
+ }
165
+ }
166
+
167
+ /**
168
+ * The client upgrade bootstrap. pis-csp.js auto-registers every domain and
169
+ * exposes window.PIS; this one-shot interceptor then hydrates from the
170
+ * embedded payloads exactly like the documented recipe. The SERIALIZABLE init
171
+ * configuration from the render request (appSettings, components,
172
+ * allowMobileView, baseUrl, and the opt-in token) is embedded verbatim so the
173
+ * client re-render uses the same configuration as the server render.
174
+ *
175
+ * Functions cannot cross the JSON boundary, so the page may define
176
+ * `window.pisSsrRenderReady(instance, options)` BEFORE this script runs: the
177
+ * hook receives the instance and the assembled options object prior to
178
+ * init() and can attach event listeners (instance.on(...)) and set option
179
+ * functions (commandInterceptor, onUserAction, errorInterceptor,
180
+ * dataInterceptor). dataInterceptor is intentionally NOT a request field:
181
+ * with caller payloads, data enrichment belongs in the backend that fetched
182
+ * the response; the hook still covers client-side enrichment of lazy loads.
183
+ */
184
+ function clientBootstrapScript(instanceId, baseUrl, appSettings, accessToken, clientConfig) {
185
+ const { components, allowMobileView } = clientConfig ?? {};
186
+ return [
187
+ '<script>',
188
+ '(function () {',
189
+ ' var detailScript = document.getElementById("pis-detail-payload");',
190
+ ' var productId = detailScript ? detailScript.getAttribute("data-product-id") : "";',
191
+ ' var take = function (id) { var el = document.getElementById(id); var json = el && el.textContent; if (el) el.remove(); try { return json ? JSON.parse(json) : undefined; } catch (e) { return undefined; } };',
192
+ ' var detail = take("pis-detail-payload");',
193
+ ' var translations = take("pis-translations-payload");',
194
+ ` var instanceId = ${JSON.stringify(instanceId)};`,
195
+ ' if (!detail || !window.PIS) return;',
196
+ ' var instance = window.PIS.Products.getInstance(instanceId);',
197
+ ' var options = {',
198
+ ` baseUrl: ${JSON.stringify(baseUrl)},`,
199
+ ...(accessToken
200
+ ? [` accessToken: ${JSON.stringify(accessToken).replace(/</g, '\\u003c')},`]
201
+ : []),
202
+ ` appSettings: ${escapeJsonForInline(appSettings)},`,
203
+ ...(components !== undefined ? [` components: ${escapeJsonForInline(components)},`] : []),
204
+ ...(allowMobileView !== undefined
205
+ ? [` allowMobileView: ${JSON.stringify(allowMobileView)},`]
206
+ : []),
207
+ ' cacheTranslations: false,',
208
+ ' httpInterceptor: function (request) {',
209
+ " if (request.url === '/v2/Products/Detail' && detail) { var d = detail; detail = undefined; return d; }",
210
+ " if (request.url === '/v2/Translations' && translations) { var t = translations; translations = undefined; return t; }",
211
+ ' }',
212
+ ' };',
213
+ // Runtime templates: reconstruct render functions from their embedded
214
+ // sources (the { source } dialect) so the client upgrade uses the same
215
+ // templates the server rendered with. String templates ride as strings
216
+ // and are compiled by the compiler-enabled pis.js build.
217
+ ' var hydrateTemplates = function (node) {',
218
+ ' if (Array.isArray(node)) { node.forEach(hydrateTemplates); return; }',
219
+ ' if (node && typeof node === "object") {',
220
+ ' for (var key in node) {',
221
+ ' var value = node[key];',
222
+ ' if (value && typeof value === "object" && typeof value.__pisTemplateSource === "string") {',
223
+ ' node[key] = new Function("container", "ctx", value.__pisTemplateSource);',
224
+ ' } else { hydrateTemplates(value); }',
225
+ ' }',
226
+ ' }',
227
+ ' };',
228
+ ' hydrateTemplates(options.components);',
229
+ ' if (typeof window.pisSsrRenderReady === "function") {',
230
+ ' try { window.pisSsrRenderReady(instance, options); } catch (error) {',
231
+ ' console.error("[pis-ssr-render] pisSsrRenderReady hook failed", error);',
232
+ ' }',
233
+ ' }',
234
+ ' instance.init(options, { view: "detail", detail: { productId: productId } }).catch(function (error) {',
235
+ ' console.error("[pis-ssr-render] client initialization failed", error);',
236
+ ' });',
237
+ '})();',
238
+ '</script>',
239
+ ].join('\n');
240
+ }
241
+
242
+ async function readJsonBody(request) {
243
+ const chunks = [];
244
+ let size = 0;
245
+ for await (const chunk of request) {
246
+ chunks.push(chunk);
247
+ size += chunk.length;
248
+ if (size > MAX_BODY_BYTES) throw new Error('Request body too large.');
249
+ }
250
+ const body = Buffer.concat(chunks).toString('utf8');
251
+ return body ? JSON.parse(body) : {};
252
+ }
253
+
254
+ function sendJson(response, status, payload, extraHeaders = {}) {
255
+ response.writeHead(status, {
256
+ 'Content-Type': 'application/json; charset=utf-8',
257
+ ...extraHeaders,
258
+ });
259
+ response.end(JSON.stringify(payload));
260
+ }
261
+
262
+ export function createRenderService(config = {}) {
263
+ const authToken = config.renderToken ?? AUTH_TOKEN;
264
+ const authDisabled = config.authDisabled ?? AUTH_DISABLED;
265
+ const allowTokenExposure = config.allowTokenExposure ?? ALLOW_TOKEN_EXPOSURE;
266
+ const allowTemplateFunctions = config.allowTemplateFunctions ?? ALLOW_TEMPLATE_FUNCTIONS;
267
+ const apiBaseUrl = config.apiBaseUrl ?? API_BASE_URL;
268
+ const apiToken = config.apiToken ?? API_TOKEN;
269
+ const stylesBase = config.stylesBase ?? STYLES_BASE;
270
+ const clientScriptUrl = config.clientScriptUrl ?? CLIENT_SCRIPT_URL;
271
+
272
+ return createServer(async (request, response) => {
273
+ try {
274
+ if (request.method === 'GET' && (request.url === '/' || request.url === '/health')) {
275
+ sendJson(response, 200, {
276
+ status: 'ok',
277
+ service: '@pisapp/ssr-render',
278
+ coreVersion: CORE_VERSION,
279
+ });
280
+ return;
281
+ }
282
+
283
+ if (request.method !== 'POST' || request.url !== '/render/products/details') {
284
+ sendJson(response, 404, { message: `No route for ${request.method} ${request.url}` });
285
+ return;
286
+ }
287
+
288
+ if (!authDisabled) {
289
+ const authorization = request.headers.authorization ?? '';
290
+ if (!authToken || authorization !== `Bearer ${authToken}`) {
291
+ response.writeHead(401, {
292
+ 'Content-Type': 'application/json',
293
+ 'WWW-Authenticate': 'Bearer',
294
+ });
295
+ response.end(JSON.stringify({ message: 'Missing or invalid bearer token.' }));
296
+ return;
297
+ }
298
+ }
299
+
300
+ const body = await readJsonBody(request);
301
+ const { productId } = body;
302
+ if (typeof productId !== 'string' || productId.length === 0) {
303
+ sendJson(response, 400, { message: 'Body requires a non-empty string "productId".' });
304
+ return;
305
+ }
306
+
307
+ // Caller-supplied payload (your backend fetched the detail response
308
+ // itself): full, unmodified API responses per the interceptor contract.
309
+ const payload =
310
+ body.payload && typeof body.payload === 'object' && body.payload !== null
311
+ ? body.payload
312
+ : undefined;
313
+ if (payload && typeof payload.detail !== 'object' && payload.detail !== undefined) {
314
+ sendJson(response, 400, { message: 'payload.detail must be the detail response object.' });
315
+ return;
316
+ }
317
+
318
+ // Template mode: your partial markup; mutually exclusive with composition.
319
+ const template =
320
+ typeof body.template === 'string' && body.template.length > 0 ? body.template : undefined;
321
+
322
+ // Token exposure: double opt-in (service env + per request), public-data
323
+ // tokens only (decision D2).
324
+ let exposedAccessToken;
325
+ if (body.exposeAccessToken === true) {
326
+ if (!allowTokenExposure) {
327
+ sendJson(response, 403, {
328
+ message:
329
+ 'Token exposure is disabled on this service. Set PIS_ALLOW_TOKEN_EXPOSURE=1 and only expose short-lived public-data tokens.',
330
+ });
331
+ return;
332
+ }
333
+ if (typeof body.accessToken === 'string' && body.accessToken.length > 0) {
334
+ exposedAccessToken = body.accessToken;
335
+ }
336
+ }
337
+
338
+ const needsServiceFetch = !payload?.detail || !payload?.translations;
339
+ if (needsServiceFetch && (!apiBaseUrl || !apiToken)) {
340
+ sendJson(response, 500, {
341
+ message:
342
+ 'Service misconfigured: set PIS_API_BASE_URL and PIS_API_TOKEN, or supply payload.detail and payload.translations.',
343
+ });
344
+ return;
345
+ }
346
+
347
+ // In full-payload mode nothing is fetched server-side; the baseUrl only
348
+ // has to be valid. It still rides in the bootstrap so live lazy loads
349
+ // (token exposure) hit the right endpoint - typically your gateway.
350
+ const callerBaseUrl =
351
+ typeof body.baseUrl === 'string' && body.baseUrl.length > 0 ? body.baseUrl : undefined;
352
+ const effectiveBaseUrl = apiBaseUrl ?? callerBaseUrl ?? 'https://pis.invalid';
353
+
354
+ // Serializable init configuration carried through to the client
355
+ // bootstrap so the upgrade re-renders with the SAME configuration as
356
+ // the server render. Option FUNCTIONS (commandInterceptor,
357
+ // dataInterceptor, onUserAction, errorInterceptor, event handlers)
358
+ // cannot cross JSON; the page wires them through the
359
+ // window.pisSsrRenderReady hook instead.
360
+ const clientComponents = stripHtmlUnsafeKeys(body.components);
361
+
362
+ // Runtime templates: merge the dotted-path request field into the
363
+ // components tree (server values for the render, markers/values for
364
+ // the client bootstrap).
365
+ const merged = mergeRuntimeTemplates(clientComponents, body.templates);
366
+ if (merged.error) {
367
+ sendJson(response, 400, { message: merged.error });
368
+ return;
369
+ }
370
+ if (merged.dialects.sources && !allowTemplateFunctions) {
371
+ sendJson(response, 403, {
372
+ message:
373
+ 'Function-source templates are disabled on this service. Set PIS_ALLOW_TEMPLATE_FUNCTIONS=1 (trusted callers only: the sources execute server- and client-side).',
374
+ });
375
+ return;
376
+ }
377
+ if (
378
+ merged.dialects.strings &&
379
+ body.mode !== 'seo-only' &&
380
+ /pis-csp\.js(\?|$)/.test(clientScriptUrl)
381
+ ) {
382
+ sendJson(response, 400, {
383
+ message:
384
+ 'String templates need the compiler-enabled client build: point PIS_CLIENT_SCRIPT_URL at pis.js (Scenario D; requires CSP unsafe-eval), or use { source } function templates.',
385
+ });
386
+ return;
387
+ }
388
+ const serverComponents = merged.server;
389
+ const clientConfig = {
390
+ components:
391
+ body.components || body.templates ? merged.client : stripHtmlUnsafeKeys(body.components),
392
+ allowMobileView: body.allowMobileView === true ? true : undefined,
393
+ };
394
+
395
+ // The service-side API credentials and interceptors stay service-owned;
396
+ // caller options are limited to the safe surface.
397
+ const result = await renderProductDetails({
398
+ productId,
399
+ cid: typeof body.cid === 'string' ? body.cid : undefined,
400
+ instanceId: typeof body.instanceId === 'string' ? body.instanceId : undefined,
401
+ composition: Array.isArray(body.composition) ? body.composition : undefined,
402
+ template,
403
+ payload,
404
+ theme: typeof body.theme === 'string' ? body.theme : undefined,
405
+ structuredData: body.structuredData === true,
406
+ fetch: {
407
+ headers:
408
+ body.fetch && typeof body.fetch.headers === 'object' && body.fetch.headers !== null
409
+ ? body.fetch.headers
410
+ : undefined,
411
+ },
412
+ options: {
413
+ baseUrl: effectiveBaseUrl,
414
+ accessToken: apiToken,
415
+ appSettings:
416
+ body.appSettings && typeof body.appSettings === 'object'
417
+ ? body.appSettings
418
+ : { appCode: '9AAG6689', langCode: 'en' },
419
+ components: serverComponents,
420
+ cacheTranslations: false,
421
+ },
422
+ });
423
+
424
+ const cacheSeconds = Math.max(
425
+ 0,
426
+ Math.min(
427
+ Number.isFinite(body.cacheSeconds) ? body.cacheSeconds : MAX_CACHE_SECONDS,
428
+ MAX_CACHE_SECONDS,
429
+ ),
430
+ );
431
+ // A fragment carrying an exposed token must never sit in a shared cache.
432
+ const cacheVisibility = exposedAccessToken ? 'private' : 'public';
433
+ const cacheControl =
434
+ cacheSeconds > 0 ? `${cacheVisibility}, max-age=${cacheSeconds}` : 'no-store';
435
+ const wantsJson =
436
+ request.headers.accept?.includes('application/json') || body.format === 'json';
437
+
438
+ if (wantsJson) {
439
+ sendJson(response, 200, result, { 'Cache-Control': cacheControl });
440
+ return;
441
+ }
442
+
443
+ const fragment = buildFragment(body, result, body.mode, {
444
+ stylesBase,
445
+ clientScriptUrl,
446
+ apiBaseUrl: effectiveBaseUrl,
447
+ exposedAccessToken,
448
+ clientConfig,
449
+ });
450
+ response.writeHead(200, {
451
+ 'Content-Type': 'text/html; charset=utf-8',
452
+ 'Cache-Control': cacheControl,
453
+ 'X-Pis-Found': String(result.found),
454
+ });
455
+ response.end(fragment);
456
+ } catch (error) {
457
+ if (error instanceof SyntaxError) {
458
+ sendJson(response, 400, { message: 'Invalid JSON body.' });
459
+ return;
460
+ }
461
+ console.error('[pis-ssr-render] render failed', error);
462
+ sendJson(response, 502, {
463
+ message: 'Render failed.',
464
+ detail: error instanceof Error ? error.message : String(error),
465
+ });
466
+ }
467
+ });
468
+ }
469
+
470
+ function buildFragment(
471
+ request,
472
+ result,
473
+ mode,
474
+ { stylesBase, clientScriptUrl, apiBaseUrl, exposedAccessToken, clientConfig },
475
+ ) {
476
+ const { layout = {} } = request;
477
+ const styles = result.cssImports
478
+ .map((specifier) => specifier.replace('@pisapp/core/styles/', ''))
479
+ .map((file) => `<link rel="stylesheet" href="${stylesBase}/${file}">`)
480
+ .join('\n');
481
+
482
+ const parts = [];
483
+ if (layout.headerHtml) parts.push(layout.headerHtml);
484
+ if (layout.headExtra) parts.push(layout.headExtra);
485
+ parts.push(styles);
486
+ if (result.head.jsonLd) {
487
+ parts.push(
488
+ `<script type="application/ld+json">${escapeJsonForInline(result.head.jsonLd)}</script>`,
489
+ );
490
+ }
491
+ parts.push(
492
+ `<script id="pis-detail-payload" type="application/json" data-product-id="${escapeHtmlAttribute(request.productId)}">${result.embeddedPayload.detailJson}</script>`,
493
+ );
494
+ parts.push(
495
+ `<script id="pis-translations-payload" type="application/json">${result.embeddedPayload.translationsJson}</script>`,
496
+ );
497
+ parts.push(result.html);
498
+ if (layout.footerHtml) parts.push(layout.footerHtml);
499
+
500
+ if (mode !== 'seo-only') {
501
+ parts.push(`<script src="${clientScriptUrl}"></script>`);
502
+ parts.push(
503
+ clientBootstrapScript(
504
+ result.instanceId,
505
+ apiBaseUrl,
506
+ request.appSettings,
507
+ exposedAccessToken,
508
+ clientConfig,
509
+ ),
510
+ );
511
+ }
512
+
513
+ return parts.join('\n');
514
+ }
515
+
516
+ const isMain = process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href;
517
+
518
+ if (isMain) {
519
+ createRenderService().listen(PORT, () => {
520
+ console.log(`[pis-ssr-render] listening on http://127.0.0.1:${PORT} (core ${CORE_VERSION})`);
521
+ });
522
+ }