@pithyjs/ssr 0.0.0-stage → 0.1.2-beta.10
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/LICENSE +21 -0
- package/README.md +100 -2
- package/bin/pithy-ssg.mjs +23 -0
- package/dist/browser.d.ts +38 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +40 -0
- package/dist/browser.js.map +1 -0
- package/dist/build/cli-args.d.ts +104 -0
- package/dist/build/cli-args.d.ts.map +1 -0
- package/dist/build/cli-args.js +88 -0
- package/dist/build/cli-args.js.map +1 -0
- package/dist/build/cli-exit.d.ts +95 -0
- package/dist/build/cli-exit.d.ts.map +1 -0
- package/dist/build/cli-exit.js +237 -0
- package/dist/build/cli-exit.js.map +1 -0
- package/dist/build/cli.d.ts +11 -0
- package/dist/build/cli.d.ts.map +1 -0
- package/dist/build/cli.js +93 -0
- package/dist/build/cli.js.map +1 -0
- package/dist/build/collect-css.d.ts +168 -0
- package/dist/build/collect-css.d.ts.map +1 -0
- package/dist/build/collect-css.js +479 -0
- package/dist/build/collect-css.js.map +1 -0
- package/dist/build/css-live-props.d.ts +89 -0
- package/dist/build/css-live-props.d.ts.map +1 -0
- package/dist/build/css-live-props.js +704 -0
- package/dist/build/css-live-props.js.map +1 -0
- package/dist/build/css-purge.d.ts +153 -0
- package/dist/build/css-purge.d.ts.map +1 -0
- package/dist/build/css-purge.js +463 -0
- package/dist/build/css-purge.js.map +1 -0
- package/dist/build/index.d.ts +24 -0
- package/dist/build/index.d.ts.map +1 -0
- package/dist/build/index.js +31 -0
- package/dist/build/index.js.map +1 -0
- package/dist/build/not-found.d.ts +94 -0
- package/dist/build/not-found.d.ts.map +1 -0
- package/dist/build/not-found.js +99 -0
- package/dist/build/not-found.js.map +1 -0
- package/dist/build/relative-links.d.ts +31 -0
- package/dist/build/relative-links.d.ts.map +1 -0
- package/dist/build/relative-links.js +79 -0
- package/dist/build/relative-links.js.map +1 -0
- package/dist/build/shell-head.d.ts +68 -0
- package/dist/build/shell-head.d.ts.map +1 -0
- package/dist/build/shell-head.js +236 -0
- package/dist/build/shell-head.js.map +1 -0
- package/dist/build/sprite-ssg.d.ts +61 -0
- package/dist/build/sprite-ssg.d.ts.map +1 -0
- package/dist/build/sprite-ssg.js +114 -0
- package/dist/build/sprite-ssg.js.map +1 -0
- package/dist/build/ssg.d.ts +117 -0
- package/dist/build/ssg.d.ts.map +1 -0
- package/dist/build/ssg.js +404 -0
- package/dist/build/ssg.js.map +1 -0
- package/dist/build/vite-ssg.d.ts +396 -0
- package/dist/build/vite-ssg.d.ts.map +1 -0
- package/dist/build/vite-ssg.js +1130 -0
- package/dist/build/vite-ssg.js.map +1 -0
- package/dist/client/bootstrap.d.ts +51 -0
- package/dist/client/bootstrap.d.ts.map +1 -0
- package/dist/client/bootstrap.js +121 -0
- package/dist/client/bootstrap.js.map +1 -0
- package/dist/client/hydrate.d.ts +60 -0
- package/dist/client/hydrate.d.ts.map +1 -0
- package/dist/client/hydrate.js +168 -0
- package/dist/client/hydrate.js.map +1 -0
- package/dist/client/index.d.ts +21 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +16 -0
- package/dist/client/index.js.map +1 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +31 -0
- package/dist/index.js.map +1 -0
- package/dist/server/app.d.ts +166 -0
- package/dist/server/app.d.ts.map +1 -0
- package/dist/server/app.js +200 -0
- package/dist/server/app.js.map +1 -0
- package/dist/server/context.d.ts +238 -0
- package/dist/server/context.d.ts.map +1 -0
- package/dist/server/context.js +371 -0
- package/dist/server/context.js.map +1 -0
- package/dist/server/environment.d.ts +88 -0
- package/dist/server/environment.d.ts.map +1 -0
- package/dist/server/environment.js +261 -0
- package/dist/server/environment.js.map +1 -0
- package/dist/server/html-shell.d.ts +41 -0
- package/dist/server/html-shell.d.ts.map +1 -0
- package/dist/server/html-shell.js +208 -0
- package/dist/server/html-shell.js.map +1 -0
- package/dist/server/index.d.ts +26 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +37 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/layout-taint.d.ts +62 -0
- package/dist/server/layout-taint.d.ts.map +1 -0
- package/dist/server/layout-taint.js +313 -0
- package/dist/server/layout-taint.js.map +1 -0
- package/dist/server/loaders.d.ts +194 -0
- package/dist/server/loaders.d.ts.map +1 -0
- package/dist/server/loaders.js +479 -0
- package/dist/server/loaders.js.map +1 -0
- package/dist/server/render-route.d.ts +102 -0
- package/dist/server/render-route.d.ts.map +1 -0
- package/dist/server/render-route.js +182 -0
- package/dist/server/render-route.js.map +1 -0
- package/dist/server/render.d.ts +80 -0
- package/dist/server/render.d.ts.map +1 -0
- package/dist/server/render.js +256 -0
- package/dist/server/render.js.map +1 -0
- package/dist/server/router-adapter.d.ts +134 -0
- package/dist/server/router-adapter.d.ts.map +1 -0
- package/dist/server/router-adapter.js +225 -0
- package/dist/server/router-adapter.js.map +1 -0
- package/dist/server/serialization.d.ts +54 -0
- package/dist/server/serialization.d.ts.map +1 -0
- package/dist/server/serialization.js +287 -0
- package/dist/server/serialization.js.map +1 -0
- package/dist/server/ssr-worker.d.ts +18 -0
- package/dist/server/ssr-worker.d.ts.map +1 -0
- package/dist/server/ssr-worker.js +118 -0
- package/dist/server/ssr-worker.js.map +1 -0
- package/dist/server/utils.d.ts +11 -0
- package/dist/server/utils.d.ts.map +1 -0
- package/dist/server/utils.js +14 -0
- package/dist/server/utils.js.map +1 -0
- package/dist/server/worker-pool.d.ts +153 -0
- package/dist/server/worker-pool.d.ts.map +1 -0
- package/dist/server/worker-pool.js +451 -0
- package/dist/server/worker-pool.js.map +1 -0
- package/dist/server/worker-protocol.d.ts +61 -0
- package/dist/server/worker-protocol.d.ts.map +1 -0
- package/dist/server/worker-protocol.js +9 -0
- package/dist/server/worker-protocol.js.map +1 -0
- package/dist/shared/css-purge.d.ts +71 -0
- package/dist/shared/css-purge.d.ts.map +1 -0
- package/dist/shared/css-purge.js +177 -0
- package/dist/shared/css-purge.js.map +1 -0
- package/dist/shared/entry-path.d.ts +41 -0
- package/dist/shared/entry-path.d.ts.map +1 -0
- package/dist/shared/entry-path.js +87 -0
- package/dist/shared/entry-path.js.map +1 -0
- package/dist/shared/head.d.ts +87 -0
- package/dist/shared/head.d.ts.map +1 -0
- package/dist/shared/head.js +412 -0
- package/dist/shared/head.js.map +1 -0
- package/dist/shared/shell-helpers.d.ts +69 -0
- package/dist/shared/shell-helpers.d.ts.map +1 -0
- package/dist/shared/shell-helpers.js +160 -0
- package/dist/shared/shell-helpers.js.map +1 -0
- package/dist/shared/types.d.ts +332 -0
- package/dist/shared/types.d.ts.map +1 -0
- package/dist/shared/types.js +27 -0
- package/dist/shared/types.js.map +1 -0
- package/package.json +84 -3
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
/** @codex
|
|
2
|
+
{
|
|
3
|
+
"id": "pithy.ssr.server.environment",
|
|
4
|
+
"title": "SSR DOM Environment",
|
|
5
|
+
"category": "runtime"
|
|
6
|
+
}
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* @pithyjs/ssr - SSR DOM Environment
|
|
10
|
+
*
|
|
11
|
+
* Sets up a lightweight DOM environment using happy-dom for server-side rendering.
|
|
12
|
+
* Provides global DOM APIs (document, window, etc.) that PithyJS components need.
|
|
13
|
+
*/
|
|
14
|
+
import { createRequire } from 'module';
|
|
15
|
+
import { installLayoutTaint } from './layout-taint.js';
|
|
16
|
+
// Create ESM-compatible require function
|
|
17
|
+
const require = createRequire(import.meta.url);
|
|
18
|
+
/** Undo for the layout-taint patch, applied when the environment is torn down. */
|
|
19
|
+
let restoreLayoutTaint = null;
|
|
20
|
+
// =============================================================================
|
|
21
|
+
// Global State Tracking
|
|
22
|
+
// =============================================================================
|
|
23
|
+
/**
|
|
24
|
+
* Track which globals we've set, so we only clean up what we added.
|
|
25
|
+
* This prevents accidentally removing globals that existed before setup.
|
|
26
|
+
*/
|
|
27
|
+
const originalGlobals = new Map();
|
|
28
|
+
let isEnvironmentActive = false;
|
|
29
|
+
// =============================================================================
|
|
30
|
+
// Implementation
|
|
31
|
+
// =============================================================================
|
|
32
|
+
/** @codexApi {"parent":"pithy.ssr.server.environment","name":"setupEnvironment","stability":"stable","signature":"(options?: SetupEnvironmentOptions) => SSREnvironment"} */
|
|
33
|
+
/**
|
|
34
|
+
* Set up SSR DOM environment with happy-dom
|
|
35
|
+
*
|
|
36
|
+
* Creates a lightweight DOM environment for server-side rendering.
|
|
37
|
+
* PithyJS components can use standard DOM APIs during SSR.
|
|
38
|
+
*
|
|
39
|
+
* @param options - Optional configuration
|
|
40
|
+
* @returns Environment with cleanup function and DOM references
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```ts
|
|
44
|
+
* const env = setupEnvironment();
|
|
45
|
+
* try {
|
|
46
|
+
* // Render components - document, window, etc. are now available
|
|
47
|
+
* const html = document.getElementById('app')?.innerHTML;
|
|
48
|
+
* } finally {
|
|
49
|
+
* env.cleanup();
|
|
50
|
+
* }
|
|
51
|
+
* ```
|
|
52
|
+
*
|
|
53
|
+
* @throws Error if environment is already active (prevents nested setup)
|
|
54
|
+
*/
|
|
55
|
+
export function setupEnvironment(options) {
|
|
56
|
+
if (isEnvironmentActive) {
|
|
57
|
+
throw new Error('SSR environment is already active. Call cleanup() before setting up a new environment. ' +
|
|
58
|
+
'For concurrent rendering, use separate worker threads.');
|
|
59
|
+
}
|
|
60
|
+
// Dynamically import happy-dom to avoid bundling issues
|
|
61
|
+
// and to provide a clear error if not installed.
|
|
62
|
+
// Using createRequire for ESM compatibility (require is not available in ESM by default)
|
|
63
|
+
let Window;
|
|
64
|
+
try {
|
|
65
|
+
const happyDom = require('happy-dom');
|
|
66
|
+
Window = happyDom.Window;
|
|
67
|
+
}
|
|
68
|
+
catch (err) {
|
|
69
|
+
// happy-dom is ESM-only, so an old Node fails here with ERR_REQUIRE_ESM.
|
|
70
|
+
throw new Error(err.code === 'MODULE_NOT_FOUND'
|
|
71
|
+
? 'happy-dom is required for SSR but not installed. ' +
|
|
72
|
+
'Install it with: pnpm add happy-dom'
|
|
73
|
+
: `happy-dom could not be loaded: ${err.message}`);
|
|
74
|
+
}
|
|
75
|
+
const url = options?.url ?? 'http://localhost';
|
|
76
|
+
const window = new Window({ url });
|
|
77
|
+
const document = window.document;
|
|
78
|
+
// Create app container if needed
|
|
79
|
+
const appId = options?.appId ?? 'app';
|
|
80
|
+
if (!document.getElementById(appId)) {
|
|
81
|
+
const appDiv = document.createElement('div');
|
|
82
|
+
appDiv.id = appId;
|
|
83
|
+
document.body.appendChild(appDiv);
|
|
84
|
+
}
|
|
85
|
+
// Store original values before overwriting
|
|
86
|
+
const globalsToSet = [
|
|
87
|
+
'window',
|
|
88
|
+
'document',
|
|
89
|
+
'HTMLElement',
|
|
90
|
+
'HTMLDivElement',
|
|
91
|
+
'HTMLSpanElement',
|
|
92
|
+
'HTMLInputElement',
|
|
93
|
+
'HTMLButtonElement',
|
|
94
|
+
'HTMLAnchorElement',
|
|
95
|
+
'HTMLFormElement',
|
|
96
|
+
'HTMLSelectElement',
|
|
97
|
+
'HTMLTextAreaElement',
|
|
98
|
+
'HTMLTemplateElement',
|
|
99
|
+
'HTMLImageElement',
|
|
100
|
+
'HTMLLabelElement',
|
|
101
|
+
'HTMLUListElement',
|
|
102
|
+
'HTMLLIElement',
|
|
103
|
+
'HTMLParagraphElement',
|
|
104
|
+
'HTMLHeadingElement',
|
|
105
|
+
'Element',
|
|
106
|
+
'Node',
|
|
107
|
+
'Text',
|
|
108
|
+
'Comment',
|
|
109
|
+
'DocumentFragment',
|
|
110
|
+
'Event',
|
|
111
|
+
'CustomEvent',
|
|
112
|
+
'MutationObserver',
|
|
113
|
+
'IntersectionObserver',
|
|
114
|
+
// Symmetric with the two observers above, and inert on the server: nothing
|
|
115
|
+
// is ever laid out, so a ResizeObserver is constructed and simply never
|
|
116
|
+
// fires. Omitting it made a bare `new ResizeObserver(...)` throw, which the
|
|
117
|
+
// renderer swallows into a dropped subtree — the same allowlist gap that
|
|
118
|
+
// `getComputedStyle` had (BACKLOG #33).
|
|
119
|
+
'ResizeObserver',
|
|
120
|
+
'NodeFilter',
|
|
121
|
+
'TreeWalker',
|
|
122
|
+
'Range',
|
|
123
|
+
'DOMParser',
|
|
124
|
+
'XMLSerializer',
|
|
125
|
+
'requestAnimationFrame',
|
|
126
|
+
'cancelAnimationFrame',
|
|
127
|
+
// Value reads (custom properties, direction) resolve correctly on the server
|
|
128
|
+
// DOM, so components get real answers instead of guesses. Layout measurement
|
|
129
|
+
// is handled separately by `installLayoutTaint` — happy-dom lays nothing
|
|
130
|
+
// out, so measurements answer NaN and are stripped before serialization.
|
|
131
|
+
'getComputedStyle',
|
|
132
|
+
'matchMedia',
|
|
133
|
+
];
|
|
134
|
+
// Save originals and set new values
|
|
135
|
+
for (const key of globalsToSet) {
|
|
136
|
+
if (key in globalThis) {
|
|
137
|
+
originalGlobals.set(key, globalThis[key]);
|
|
138
|
+
}
|
|
139
|
+
globalThis[key] =
|
|
140
|
+
window[key];
|
|
141
|
+
}
|
|
142
|
+
isEnvironmentActive = true;
|
|
143
|
+
// Set the global SSR mode flag so core binding functions can detect SSR
|
|
144
|
+
// and evaluate directives synchronously without reactive effects.
|
|
145
|
+
// Preserve any pre-existing value to stay consistent with the save/restore
|
|
146
|
+
// pattern used for all other globals in this module.
|
|
147
|
+
if ('__PITHY_SSR__' in globalThis) {
|
|
148
|
+
originalGlobals.set('__PITHY_SSR__', globalThis.__PITHY_SSR__);
|
|
149
|
+
}
|
|
150
|
+
globalThis.__PITHY_SSR__ = true;
|
|
151
|
+
// Layout accessors answer NaN rather than a fabricated 0, so any style a
|
|
152
|
+
// component derives from a measurement is self-identifying and gets stripped
|
|
153
|
+
// on the way out. This is what lets components measure freely without knowing
|
|
154
|
+
// they are on a server. See `layout-taint.ts`.
|
|
155
|
+
restoreLayoutTaint = installLayoutTaint(window);
|
|
156
|
+
// Create cleanup function
|
|
157
|
+
const cleanup = () => {
|
|
158
|
+
if (!isEnvironmentActive) {
|
|
159
|
+
return; // Already cleaned up
|
|
160
|
+
}
|
|
161
|
+
// Un-taint the layout accessors before the window goes away.
|
|
162
|
+
restoreLayoutTaint?.();
|
|
163
|
+
restoreLayoutTaint = null;
|
|
164
|
+
// Restore or delete globals
|
|
165
|
+
for (const key of globalsToSet) {
|
|
166
|
+
if (originalGlobals.has(key)) {
|
|
167
|
+
globalThis[key] = originalGlobals.get(key);
|
|
168
|
+
}
|
|
169
|
+
else {
|
|
170
|
+
delete globalThis[key];
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
// Restore or clear the global SSR mode flag (before clearing the map)
|
|
174
|
+
if (originalGlobals.has('__PITHY_SSR__')) {
|
|
175
|
+
globalThis.__PITHY_SSR__ =
|
|
176
|
+
originalGlobals.get('__PITHY_SSR__');
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
delete globalThis.__PITHY_SSR__;
|
|
180
|
+
}
|
|
181
|
+
originalGlobals.clear();
|
|
182
|
+
isEnvironmentActive = false;
|
|
183
|
+
// Close happy-dom window to release resources
|
|
184
|
+
try {
|
|
185
|
+
window.close();
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
// Ignore close errors
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
return {
|
|
192
|
+
cleanup,
|
|
193
|
+
window: window,
|
|
194
|
+
document: document,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
/** @codexApi {"parent":"pithy.ssr.server.environment","name":"isEnvironmentSetup","stability":"stable","signature":"() => boolean"} */
|
|
198
|
+
/**
|
|
199
|
+
* Check if SSR environment is currently active
|
|
200
|
+
*
|
|
201
|
+
* @returns True if setupEnvironment() has been called without cleanup()
|
|
202
|
+
*/
|
|
203
|
+
export function isEnvironmentSetup() {
|
|
204
|
+
return isEnvironmentActive;
|
|
205
|
+
}
|
|
206
|
+
/** @codexApi {"parent":"pithy.ssr.server.environment","name":"withEnvironment","stability":"stable","signature":"<T>(fn: (env: SSREnvironment) => T) => T"} */
|
|
207
|
+
/**
|
|
208
|
+
* Execute a function with SSR environment, ensuring cleanup
|
|
209
|
+
*
|
|
210
|
+
* Convenience wrapper that sets up the environment, runs the function,
|
|
211
|
+
* and cleans up automatically (even if the function throws).
|
|
212
|
+
*
|
|
213
|
+
* @param fn - Function to execute with the environment
|
|
214
|
+
* @returns The function's return value
|
|
215
|
+
*
|
|
216
|
+
* @example
|
|
217
|
+
* ```ts
|
|
218
|
+
* const html = withEnvironment((env) => {
|
|
219
|
+
* // env.document, env.window available
|
|
220
|
+
* renderComponent(App);
|
|
221
|
+
* return env.document.getElementById('app')?.innerHTML ?? '';
|
|
222
|
+
* });
|
|
223
|
+
* ```
|
|
224
|
+
*/
|
|
225
|
+
export function withEnvironment(fn) {
|
|
226
|
+
const env = setupEnvironment();
|
|
227
|
+
try {
|
|
228
|
+
return fn(env);
|
|
229
|
+
}
|
|
230
|
+
finally {
|
|
231
|
+
env.cleanup();
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
/** @codexApi {"parent":"pithy.ssr.server.environment","name":"withEnvironmentAsync","stability":"stable","signature":"<T>(fn: (env: SSREnvironment) => Promise<T>) => Promise<T>"} */
|
|
235
|
+
/**
|
|
236
|
+
* Execute an async function with SSR environment, ensuring cleanup
|
|
237
|
+
*
|
|
238
|
+
* Same as withEnvironment but for async functions.
|
|
239
|
+
*
|
|
240
|
+
* @param fn - Async function to execute with the environment
|
|
241
|
+
* @returns Promise resolving to the function's return value
|
|
242
|
+
*
|
|
243
|
+
* @example
|
|
244
|
+
* ```ts
|
|
245
|
+
* const html = await withEnvironmentAsync(async (env) => {
|
|
246
|
+
* await loadData();
|
|
247
|
+
* renderComponent(App);
|
|
248
|
+
* return env.document.getElementById('app')?.innerHTML ?? '';
|
|
249
|
+
* });
|
|
250
|
+
* ```
|
|
251
|
+
*/
|
|
252
|
+
export async function withEnvironmentAsync(fn) {
|
|
253
|
+
const env = setupEnvironment();
|
|
254
|
+
try {
|
|
255
|
+
return await fn(env);
|
|
256
|
+
}
|
|
257
|
+
finally {
|
|
258
|
+
env.cleanup();
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
//# sourceMappingURL=environment.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"environment.js","sourceRoot":"","sources":["../../src/server/environment.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;GAKG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AAEvC,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAEvD,yCAAyC;AACzC,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAE/C,kFAAkF;AAClF,IAAI,kBAAkB,GAAwB,IAAI,CAAC;AA+CnD,gFAAgF;AAChF,wBAAwB;AACxB,gFAAgF;AAEhF;;;GAGG;AACH,MAAM,eAAe,GAAG,IAAI,GAAG,EAAmB,CAAC;AACnD,IAAI,mBAAmB,GAAG,KAAK,CAAC;AAEhC,gFAAgF;AAChF,iBAAiB;AACjB,gFAAgF;AAEhF,6KAA6K;AAC7K;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,UAAU,gBAAgB,CAC9B,OAAiC;IAEjC,IAAI,mBAAmB,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CACb,yFAAyF;YACvF,wDAAwD,CAC3D,CAAC;IACJ,CAAC;IAED,wDAAwD;IACxD,iDAAiD;IACjD,yFAAyF;IACzF,IAAI,MAA0D,CAAC;IAC/D,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;QACtC,MAAM,GAAG,QAAQ,CAAC,MAAM,CAAC;IAC3B,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,yEAAyE;QACzE,MAAM,IAAI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sourcesContent":["/** @codex\n{\n \"id\": \"pithy.ssr.server.environment\",\n \"title\": \"SSR DOM Environment\",\n \"category\": \"runtime\"\n}\n*/\n\n/**\n * @pithyjs/ssr - SSR DOM Environment\n *\n * Sets up a lightweight DOM environment using happy-dom for server-side rendering.\n * Provides global DOM APIs (document, window, etc.) that PithyJS components need.\n */\n\nimport { createRequire } from 'module';\nimport type { SSREnvironment } from '../shared/types.js';\nimport { installLayoutTaint } from './layout-taint.js';\n\n// Create ESM-compatible require function\nconst require = createRequire(import.meta.url);\n\n/** Undo for the layout-taint patch, applied when the environment is torn down. */\nlet restoreLayoutTaint: (() => void) | null = null;\n\n// =============================================================================\n// Types for happy-dom (avoids requiring the full types at compile time)\n// =============================================================================\n\ninterface HappyDOMWindow {\n document: Document;\n HTMLElement: typeof HTMLElement;\n HTMLDivElement: typeof HTMLDivElement;\n HTMLSpanElement: typeof HTMLSpanElement;\n HTMLInputElement: typeof HTMLInputElement;\n HTMLButtonElement: typeof HTMLButtonElement;\n HTMLAnchorElement: typeof HTMLAnchorElement;\n HTMLFormElement: typeof HTMLFormElement;\n HTMLSelectElement: typeof HTMLSelectElement;\n HTMLTextAreaElement: typeof HTMLTextAreaElement;\n HTMLTemplateElement: typeof HTMLTemplateElement;\n HTMLImageElement: typeof HTMLImageElement;\n HTMLLabelElement: typeof HTMLLabelElement;\n HTMLUListElement: typeof HTMLUListElement;\n HTMLLIElement: typeof HTMLLIElement;\n HTMLParagraphElement: typeof HTMLParagraphElement;\n HTMLHeadingElement: typeof HTMLHeadingElement;\n Element: typeof Element;\n Node: typeof Node;\n Text: typeof Text;\n Comment: typeof Comment;\n DocumentFragment: typeof DocumentFragment;\n Event: typeof Event;\n CustomEvent: typeof CustomEvent;\n MutationObserver: typeof MutationObserver;\n IntersectionObserver: typeof IntersectionObserver;\n NodeFilter: typeof NodeFilter;\n TreeWalker: typeof TreeWalker;\n Range: typeof Range;\n DOMParser: typeof DOMParser;\n XMLSerializer: typeof XMLSerializer;\n requestAnimationFrame: typeof requestAnimationFrame;\n cancelAnimationFrame: typeof cancelAnimationFrame;\n setTimeout: typeof setTimeout;\n clearTimeout: typeof clearTimeout;\n setInterval: typeof setInterval;\n clearInterval: typeof clearInterval;\n close: () => void;\n}\n\n// =============================================================================\n// Global State Tracking\n// =============================================================================\n\n/**\n * Track which globals we've set, so we only clean up what we added.\n * This prevents accidentally removing globals that existed before setup.\n */\nconst originalGlobals = new Map<string, unknown>();\nlet isEnvironmentActive = false;\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.environment\",\"name\":\"setupEnvironment\",\"stability\":\"stable\",\"signature\":\"(options?: SetupEnvironmentOptions) => SSREnvironment\"} */\n/**\n * Set up SSR DOM environment with happy-dom\n *\n * Creates a lightweight DOM environment for server-side rendering.\n * PithyJS components can use standard DOM APIs during SSR.\n *\n * @param options - Optional configuration\n * @returns Environment with cleanup function and DOM references\n *\n * @example\n * ```ts\n * const env = setupEnvironment();\n * try {\n * // Render components - document, window, etc. are now available\n * const html = document.getElementById('app')?.innerHTML;\n * } finally {\n * env.cleanup();\n * }\n * ```\n *\n * @throws Error if environment is already active (prevents nested setup)\n */\nexport function setupEnvironment(\n options?: SetupEnvironmentOptions\n): SSREnvironment {\n if (isEnvironmentActive) {\n throw new Error(\n 'SSR environment is already active. Call cleanup() before setting up a new environment. ' +\n 'For concurrent rendering, use separate worker threads.'\n );\n }\n\n // Dynamically import happy-dom to avoid bundling issues\n // and to provide a clear error if not installed.\n // Using createRequire for ESM compatibility (require is not available in ESM by default)\n let Window: new (options?: { url?: string }) => HappyDOMWindow;\n try {\n const happyDom = require('happy-dom');\n Window = happyDom.Window;\n } catch (err) {\n // happy-dom is ESM-only, so an old Node fails here with ERR_REQUIRE_ESM.\n throw new Error(\n (err as { code?: string }).code === 'MODULE_NOT_FOUND'\n ? 'happy-dom is required for SSR but not installed. ' +\n 'Install it with: pnpm add happy-dom'\n : `happy-dom could not be loaded: ${(err as Error).message}`\n );\n }\n\n const url = options?.url ?? 'http://localhost';\n const window = new Window({ url }) as HappyDOMWindow;\n const document = window.document;\n\n // Create app container if needed\n const appId = options?.appId ?? 'app';\n if (!document.getElementById(appId)) {\n const appDiv = document.createElement('div');\n appDiv.id = appId;\n document.body.appendChild(appDiv);\n }\n\n // Store original values before overwriting\n const globalsToSet: Array<keyof typeof globalThis> = [\n 'window',\n 'document',\n 'HTMLElement',\n 'HTMLDivElement',\n 'HTMLSpanElement',\n 'HTMLInputElement',\n 'HTMLButtonElement',\n 'HTMLAnchorElement',\n 'HTMLFormElement',\n 'HTMLSelectElement',\n 'HTMLTextAreaElement',\n 'HTMLTemplateElement',\n 'HTMLImageElement',\n 'HTMLLabelElement',\n 'HTMLUListElement',\n 'HTMLLIElement',\n 'HTMLParagraphElement',\n 'HTMLHeadingElement',\n 'Element',\n 'Node',\n 'Text',\n 'Comment',\n 'DocumentFragment',\n 'Event',\n 'CustomEvent',\n 'MutationObserver',\n 'IntersectionObserver',\n // Symmetric with the two observers above, and inert on the server: nothing\n // is ever laid out, so a ResizeObserver is constructed and simply never\n // fires. Omitting it made a bare `new ResizeObserver(...)` throw, which the\n // renderer swallows into a dropped subtree — the same allowlist gap that\n // `getComputedStyle` had (BACKLOG #33).\n 'ResizeObserver',\n 'NodeFilter',\n 'TreeWalker',\n 'Range',\n 'DOMParser',\n 'XMLSerializer',\n 'requestAnimationFrame',\n 'cancelAnimationFrame',\n // Value reads (custom properties, direction) resolve correctly on the server\n // DOM, so components get real answers instead of guesses. Layout measurement\n // is handled separately by `installLayoutTaint` — happy-dom lays nothing\n // out, so measurements answer NaN and are stripped before serialization.\n 'getComputedStyle',\n 'matchMedia',\n ];\n\n // Save originals and set new values\n for (const key of globalsToSet) {\n if (key in globalThis) {\n originalGlobals.set(key, (globalThis as Record<string, unknown>)[key]);\n }\n (globalThis as Record<string, unknown>)[key] =\n window[key as keyof HappyDOMWindow];\n }\n\n isEnvironmentActive = true;\n\n // Set the global SSR mode flag so core binding functions can detect SSR\n // and evaluate directives synchronously without reactive effects.\n // Preserve any pre-existing value to stay consistent with the save/restore\n // pattern used for all other globals in this module.\n if ('__PITHY_SSR__' in globalThis) {\n originalGlobals.set(\n '__PITHY_SSR__',\n (globalThis as Record<string, unknown>).__PITHY_SSR__\n );\n }\n (globalThis as Record<string, unknown>).__PITHY_SSR__ = true;\n\n // Layout accessors answer NaN rather than a fabricated 0, so any style a\n // component derives from a measurement is self-identifying and gets stripped\n // on the way out. This is what lets components measure freely without knowing\n // they are on a server. See `layout-taint.ts`.\n restoreLayoutTaint = installLayoutTaint(window);\n\n // Create cleanup function\n const cleanup = (): void => {\n if (!isEnvironmentActive) {\n return; // Already cleaned up\n }\n\n // Un-taint the layout accessors before the window goes away.\n restoreLayoutTaint?.();\n restoreLayoutTaint = null;\n\n // Restore or delete globals\n for (const key of globalsToSet) {\n if (originalGlobals.has(key)) {\n (globalThis as Record<string, unknown>)[key] = originalGlobals.get(key);\n } else {\n delete (globalThis as Record<string, unknown>)[key];\n }\n }\n\n // Restore or clear the global SSR mode flag (before clearing the map)\n if (originalGlobals.has('__PITHY_SSR__')) {\n (globalThis as Record<string, unknown>).__PITHY_SSR__ =\n originalGlobals.get('__PITHY_SSR__');\n } else {\n delete (globalThis as Record<string, unknown>).__PITHY_SSR__;\n }\n\n originalGlobals.clear();\n isEnvironmentActive = false;\n\n // Close happy-dom window to release resources\n try {\n window.close();\n } catch {\n // Ignore close errors\n }\n };\n\n return {\n cleanup,\n window: window as unknown as Window,\n document: document as unknown as Document,\n };\n}\n\n/**\n * Options for setupEnvironment\n */\nexport interface SetupEnvironmentOptions {\n /** Base URL for the document (default: 'http://localhost') */\n url?: string;\n /** ID for the app container element (default: 'app') */\n appId?: string;\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.environment\",\"name\":\"isEnvironmentSetup\",\"stability\":\"stable\",\"signature\":\"() => boolean\"} */\n/**\n * Check if SSR environment is currently active\n *\n * @returns True if setupEnvironment() has been called without cleanup()\n */\nexport function isEnvironmentSetup(): boolean {\n return isEnvironmentActive;\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.environment\",\"name\":\"withEnvironment\",\"stability\":\"stable\",\"signature\":\"<T>(fn: (env: SSREnvironment) => T) => T\"} */\n/**\n * Execute a function with SSR environment, ensuring cleanup\n *\n * Convenience wrapper that sets up the environment, runs the function,\n * and cleans up automatically (even if the function throws).\n *\n * @param fn - Function to execute with the environment\n * @returns The function's return value\n *\n * @example\n * ```ts\n * const html = withEnvironment((env) => {\n * // env.document, env.window available\n * renderComponent(App);\n * return env.document.getElementById('app')?.innerHTML ?? '';\n * });\n * ```\n */\nexport function withEnvironment<T>(fn: (env: SSREnvironment) => T): T {\n const env = setupEnvironment();\n try {\n return fn(env);\n } finally {\n env.cleanup();\n }\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.environment\",\"name\":\"withEnvironmentAsync\",\"stability\":\"stable\",\"signature\":\"<T>(fn: (env: SSREnvironment) => Promise<T>) => Promise<T>\"} */\n/**\n * Execute an async function with SSR environment, ensuring cleanup\n *\n * Same as withEnvironment but for async functions.\n *\n * @param fn - Async function to execute with the environment\n * @returns Promise resolving to the function's return value\n *\n * @example\n * ```ts\n * const html = await withEnvironmentAsync(async (env) => {\n * await loadData();\n * renderComponent(App);\n * return env.document.getElementById('app')?.innerHTML ?? '';\n * });\n * ```\n */\nexport async function withEnvironmentAsync<T>(\n fn: (env: SSREnvironment) => Promise<T>\n): Promise<T> {\n const env = setupEnvironment();\n try {\n return await fn(env);\n } finally {\n env.cleanup();\n }\n}\n"]}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** @codex
|
|
2
|
+
{
|
|
3
|
+
"id": "pithy.ssr.server.html-shell",
|
|
4
|
+
"title": "HTML Shell Generator",
|
|
5
|
+
"category": "runtime"
|
|
6
|
+
}
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* @pithyjs/ssr - HTML Shell Generator
|
|
10
|
+
*
|
|
11
|
+
* Generates complete HTML documents from SSR output.
|
|
12
|
+
* Combines rendered HTML, head state, serialized state, scripts, and styles
|
|
13
|
+
* into a valid HTML5 document ready for browser delivery.
|
|
14
|
+
*/
|
|
15
|
+
import { type ShellOptions } from '../shared/types.js';
|
|
16
|
+
/** @codexApi {"parent":"pithy.ssr.server.html-shell","name":"htmlShell","stability":"stable","signature":"(options: ShellOptions) => string"} */
|
|
17
|
+
/**
|
|
18
|
+
* Generate complete HTML document
|
|
19
|
+
*
|
|
20
|
+
* Creates a valid HTML5 document by combining:
|
|
21
|
+
* - DOCTYPE declaration
|
|
22
|
+
* - HTML element with lang attribute
|
|
23
|
+
* - Head section with meta tags, stylesheets, preloads, and critical CSS
|
|
24
|
+
* - Body section with rendered content, state, and scripts
|
|
25
|
+
*
|
|
26
|
+
* @param options - Shell generation options
|
|
27
|
+
* @returns Complete HTML document string
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```ts
|
|
31
|
+
* const html = htmlShell({
|
|
32
|
+
* html: result.html,
|
|
33
|
+
* head: result.head,
|
|
34
|
+
* state: result.state,
|
|
35
|
+
* scripts: ['/entry-client.js'],
|
|
36
|
+
* styles: ['/styles.css'],
|
|
37
|
+
* });
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
export declare function htmlShell(options: ShellOptions): string;
|
|
41
|
+
//# sourceMappingURL=html-shell.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"html-shell.d.ts","sourceRoot":"","sources":["../../src/server/html-shell.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;;GAMG;AAEH,OAAO,EAGL,KAAK,YAAY,EAElB,MAAM,oBAAoB,CAAC;AAqH5B,iJAAiJ;AACjJ;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,SAAS,CAAC,OAAO,EAAE,YAAY,GAAG,MAAM,CA+FvD"}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
/** @codex
|
|
2
|
+
{
|
|
3
|
+
"id": "pithy.ssr.server.html-shell",
|
|
4
|
+
"title": "HTML Shell Generator",
|
|
5
|
+
"category": "runtime"
|
|
6
|
+
}
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* @pithyjs/ssr - HTML Shell Generator
|
|
10
|
+
*
|
|
11
|
+
* Generates complete HTML documents from SSR output.
|
|
12
|
+
* Combines rendered HTML, head state, serialized state, scripts, and styles
|
|
13
|
+
* into a valid HTML5 document ready for browser delivery.
|
|
14
|
+
*/
|
|
15
|
+
import { STATE_VAR_NAME, DEFAULT_APP_ID, } from '../shared/types.js';
|
|
16
|
+
import { renderHead, renderHtmlAttrs } from '../shared/head.js';
|
|
17
|
+
import { escapeHtml } from '@pithyjs/shared';
|
|
18
|
+
import { isDev } from './utils.js';
|
|
19
|
+
// =============================================================================
|
|
20
|
+
// Helper Functions
|
|
21
|
+
// =============================================================================
|
|
22
|
+
/**
|
|
23
|
+
* Render attributes object to HTML attribute string
|
|
24
|
+
*/
|
|
25
|
+
function renderAttrs(attrs) {
|
|
26
|
+
return Object.entries(attrs)
|
|
27
|
+
.map(([key, value]) => `${escapeHtml(key)}="${escapeHtml(value)}"`)
|
|
28
|
+
.join(' ');
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Render a preload link tag
|
|
32
|
+
*/
|
|
33
|
+
function renderPreloadTag(preload) {
|
|
34
|
+
const attrs = ['rel="preload"'];
|
|
35
|
+
attrs.push(`href="${escapeHtml(preload.href)}"`);
|
|
36
|
+
attrs.push(`as="${escapeHtml(preload.as)}"`);
|
|
37
|
+
if (preload.type) {
|
|
38
|
+
attrs.push(`type="${escapeHtml(preload.type)}"`);
|
|
39
|
+
}
|
|
40
|
+
if (preload.crossorigin) {
|
|
41
|
+
attrs.push(`crossorigin="${escapeHtml(preload.crossorigin)}"`);
|
|
42
|
+
}
|
|
43
|
+
return `<link ${attrs.join(' ')}>`;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Render a stylesheet link tag
|
|
47
|
+
*/
|
|
48
|
+
function renderStylesheetTag(href) {
|
|
49
|
+
return `<link rel="stylesheet" href="${escapeHtml(href)}">`;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Render a module script tag
|
|
53
|
+
*/
|
|
54
|
+
function renderScriptTag(src) {
|
|
55
|
+
return `<script type="module" src="${escapeHtml(src)}"></script>`;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Serialize state to JSON and escape for embedding in HTML
|
|
59
|
+
*
|
|
60
|
+
* Escapes:
|
|
61
|
+
* - </script to prevent XSS attacks where state contains malicious closing script tags
|
|
62
|
+
* - U+2028 (Line Separator) and U+2029 (Paragraph Separator) which are valid in JSON
|
|
63
|
+
* but act as line terminators in JavaScript, causing syntax errors in inline scripts
|
|
64
|
+
*
|
|
65
|
+
* Handles circular references gracefully by replacing them with null to prevent
|
|
66
|
+
* crashes during SSR. A warning is logged in development mode when this occurs.
|
|
67
|
+
*/
|
|
68
|
+
function serializeState(state) {
|
|
69
|
+
let json;
|
|
70
|
+
let hadCycle = false;
|
|
71
|
+
try {
|
|
72
|
+
// First, try plain JSON serialization. This correctly handles repeated
|
|
73
|
+
// (non-circular) references but will throw on true cycles.
|
|
74
|
+
json = JSON.stringify(state);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
// Fallback: break circular references by replacing them with null.
|
|
78
|
+
// NOTE: This simple approach may also null repeated (non-circular) references
|
|
79
|
+
// if they appear alongside true cycles. A more sophisticated ancestry-based
|
|
80
|
+
// approach could preserve repeated refs, but adds complexity for a rare case.
|
|
81
|
+
hadCycle = true;
|
|
82
|
+
const seen = new WeakSet();
|
|
83
|
+
json = JSON.stringify(state, (_key, value) => {
|
|
84
|
+
if (typeof value === 'object' && value !== null) {
|
|
85
|
+
if (seen.has(value)) {
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
seen.add(value);
|
|
89
|
+
}
|
|
90
|
+
return value;
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
if (hadCycle && isDev()) {
|
|
94
|
+
console.warn('[SSR] Circular reference detected in state serialization. ' +
|
|
95
|
+
'The circular value has been replaced with null. ' +
|
|
96
|
+
'Consider restructuring your loader data to avoid circular references.');
|
|
97
|
+
}
|
|
98
|
+
return json
|
|
99
|
+
.replace(/<\/script/gi, '<\\/script')
|
|
100
|
+
.replace(/\u2028/g, '\\u2028')
|
|
101
|
+
.replace(/\u2029/g, '\\u2029');
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Escape CSS content for safe embedding in <style> tags
|
|
105
|
+
*
|
|
106
|
+
* Escapes </style to prevent XSS attacks where CSS contains
|
|
107
|
+
* malicious closing style tags that could break out and inject scripts.
|
|
108
|
+
*/
|
|
109
|
+
function escapeCssContent(css) {
|
|
110
|
+
// Escape </style to prevent breaking out of the style tag
|
|
111
|
+
return css.replace(/<\/style/gi, '<\\/style');
|
|
112
|
+
}
|
|
113
|
+
// =============================================================================
|
|
114
|
+
// Main Implementation
|
|
115
|
+
// =============================================================================
|
|
116
|
+
/** @codexApi {"parent":"pithy.ssr.server.html-shell","name":"htmlShell","stability":"stable","signature":"(options: ShellOptions) => string"} */
|
|
117
|
+
/**
|
|
118
|
+
* Generate complete HTML document
|
|
119
|
+
*
|
|
120
|
+
* Creates a valid HTML5 document by combining:
|
|
121
|
+
* - DOCTYPE declaration
|
|
122
|
+
* - HTML element with lang attribute
|
|
123
|
+
* - Head section with meta tags, stylesheets, preloads, and critical CSS
|
|
124
|
+
* - Body section with rendered content, state, and scripts
|
|
125
|
+
*
|
|
126
|
+
* @param options - Shell generation options
|
|
127
|
+
* @returns Complete HTML document string
|
|
128
|
+
*
|
|
129
|
+
* @example
|
|
130
|
+
* ```ts
|
|
131
|
+
* const html = htmlShell({
|
|
132
|
+
* html: result.html,
|
|
133
|
+
* head: result.head,
|
|
134
|
+
* state: result.state,
|
|
135
|
+
* scripts: ['/entry-client.js'],
|
|
136
|
+
* styles: ['/styles.css'],
|
|
137
|
+
* });
|
|
138
|
+
* ```
|
|
139
|
+
*/
|
|
140
|
+
export function htmlShell(options) {
|
|
141
|
+
const { html, head, state, scripts = [], styles = [], lang, bodyAttrs = {}, appId = DEFAULT_APP_ID, criticalCss, preloads = [], } = options;
|
|
142
|
+
// Build HTML attributes
|
|
143
|
+
// Priority: direct lang option > head.htmlAttrs.lang > default 'en'
|
|
144
|
+
const htmlAttrs = { ...head.htmlAttrs };
|
|
145
|
+
if (lang) {
|
|
146
|
+
htmlAttrs.lang = lang;
|
|
147
|
+
}
|
|
148
|
+
else if (!htmlAttrs.lang) {
|
|
149
|
+
htmlAttrs.lang = 'en';
|
|
150
|
+
}
|
|
151
|
+
const htmlAttrsStr = renderHtmlAttrs({ ...head, htmlAttrs });
|
|
152
|
+
// Build body attributes (merge head.bodyAttrs with options.bodyAttrs)
|
|
153
|
+
const mergedBodyAttrs = { ...head.bodyAttrs, ...bodyAttrs };
|
|
154
|
+
const bodyAttrsStr = Object.keys(mergedBodyAttrs).length > 0
|
|
155
|
+
? ' ' + renderAttrs(mergedBodyAttrs)
|
|
156
|
+
: '';
|
|
157
|
+
// Build head content
|
|
158
|
+
const headParts = [];
|
|
159
|
+
// Essential meta tags first
|
|
160
|
+
headParts.push(' <meta charset="UTF-8">');
|
|
161
|
+
headParts.push(' <meta name="viewport" content="width=device-width, initial-scale=1.0">');
|
|
162
|
+
// Preload hints (early in head for faster resource discovery)
|
|
163
|
+
for (const preload of preloads) {
|
|
164
|
+
headParts.push(' ' + renderPreloadTag(preload));
|
|
165
|
+
}
|
|
166
|
+
// Stylesheets
|
|
167
|
+
for (const style of styles) {
|
|
168
|
+
headParts.push(' ' + renderStylesheetTag(style));
|
|
169
|
+
}
|
|
170
|
+
// Critical CSS (inline) - escaped to prevent XSS via </style> injection
|
|
171
|
+
if (criticalCss) {
|
|
172
|
+
headParts.push(` <style>${escapeCssContent(criticalCss)}</style>`);
|
|
173
|
+
}
|
|
174
|
+
// Head state (title, meta, link, script from head() calls)
|
|
175
|
+
const headStateHtml = renderHead(head);
|
|
176
|
+
if (headStateHtml) {
|
|
177
|
+
// Indent each line for consistent formatting
|
|
178
|
+
const indentedHead = headStateHtml
|
|
179
|
+
.split('\n')
|
|
180
|
+
.map(line => (line.trim() ? ' ' + line : line))
|
|
181
|
+
.join('\n');
|
|
182
|
+
headParts.push(indentedHead);
|
|
183
|
+
}
|
|
184
|
+
// Build body content
|
|
185
|
+
const bodyParts = [];
|
|
186
|
+
// App container with rendered HTML
|
|
187
|
+
bodyParts.push(` <div id="${escapeHtml(appId)}">${html}</div>`);
|
|
188
|
+
// State serialization script (omitted in static/no-JS mode when state is undefined)
|
|
189
|
+
if (state !== undefined) {
|
|
190
|
+
const stateScript = serializeState(state);
|
|
191
|
+
bodyParts.push(` <script>window.${STATE_VAR_NAME} = ${stateScript};</script>`);
|
|
192
|
+
}
|
|
193
|
+
// Entry scripts (after state so they can access it)
|
|
194
|
+
for (const script of scripts) {
|
|
195
|
+
bodyParts.push(' ' + renderScriptTag(script));
|
|
196
|
+
}
|
|
197
|
+
// Assemble final HTML document
|
|
198
|
+
return `<!DOCTYPE html>
|
|
199
|
+
<html ${htmlAttrsStr}>
|
|
200
|
+
<head>
|
|
201
|
+
${headParts.join('\n')}
|
|
202
|
+
</head>
|
|
203
|
+
<body${bodyAttrsStr}>
|
|
204
|
+
${bodyParts.join('\n')}
|
|
205
|
+
</body>
|
|
206
|
+
</html>`;
|
|
207
|
+
}
|
|
208
|
+
//# sourceMappingURL=html-shell.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"html-shell.js","sourceRoot":"","sources":["../../src/server/html-shell.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;;GAMG;AAEH,OAAO,EACL,cAAc,EACd,cAAc,GAGf,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,UAAU,EAAE,eAAe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AAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,SAAS,CAAC,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC;IACjD,CAAC;IAED,+BAA+B;IAC/B,OAAO;QACD,YAAY;;EAElB,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;;OAEf,YAAY;EACjB,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;;QAEd,CAAC;AACT,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.ssr.server.html-shell\",\n \"title\": \"HTML Shell Generator\",\n \"category\": \"runtime\"\n}\n*/\n\n/**\n * @pithyjs/ssr - HTML Shell Generator\n *\n * Generates complete HTML documents from SSR output.\n * Combines rendered HTML, head state, serialized state, scripts, and styles\n * into a valid HTML5 document ready for browser delivery.\n */\n\nimport {\n STATE_VAR_NAME,\n DEFAULT_APP_ID,\n type ShellOptions,\n type PreloadHint,\n} from '../shared/types.js';\nimport { renderHead, renderHtmlAttrs } from '../shared/head.js';\nimport { escapeHtml } from '@pithyjs/shared';\nimport { isDev } from './utils.js';\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Render attributes object to HTML attribute string\n */\nfunction renderAttrs(attrs: Record<string, string>): string {\n return Object.entries(attrs)\n .map(([key, value]) => `${escapeHtml(key)}=\"${escapeHtml(value)}\"`)\n .join(' ');\n}\n\n/**\n * Render a preload link tag\n */\nfunction renderPreloadTag(preload: PreloadHint): string {\n const attrs: string[] = ['rel=\"preload\"'];\n attrs.push(`href=\"${escapeHtml(preload.href)}\"`);\n attrs.push(`as=\"${escapeHtml(preload.as)}\"`);\n\n if (preload.type) {\n attrs.push(`type=\"${escapeHtml(preload.type)}\"`);\n }\n if (preload.crossorigin) {\n attrs.push(`crossorigin=\"${escapeHtml(preload.crossorigin)}\"`);\n }\n\n return `<link ${attrs.join(' ')}>`;\n}\n\n/**\n * Render a stylesheet link tag\n */\nfunction renderStylesheetTag(href: string): string {\n return `<link rel=\"stylesheet\" href=\"${escapeHtml(href)}\">`;\n}\n\n/**\n * Render a module script tag\n */\nfunction renderScriptTag(src: string): string {\n return `<script type=\"module\" src=\"${escapeHtml(src)}\"></script>`;\n}\n\n/**\n * Serialize state to JSON and escape for embedding in HTML\n *\n * Escapes:\n * - </script to prevent XSS attacks where state contains malicious closing script tags\n * - U+2028 (Line Separator) and U+2029 (Paragraph Separator) which are valid in JSON\n * but act as line terminators in JavaScript, causing syntax errors in inline scripts\n *\n * Handles circular references gracefully by replacing them with null to prevent\n * crashes during SSR. A warning is logged in development mode when this occurs.\n */\nfunction serializeState(state: unknown): string {\n let json: string;\n let hadCycle = false;\n\n try {\n // First, try plain JSON serialization. This correctly handles repeated\n // (non-circular) references but will throw on true cycles.\n json = JSON.stringify(state);\n } catch {\n // Fallback: break circular references by replacing them with null.\n // NOTE: This simple approach may also null repeated (non-circular) references\n // if they appear alongside true cycles. A more sophisticated ancestry-based\n // approach could preserve repeated refs, but adds complexity for a rare case.\n hadCycle = true;\n const seen = new WeakSet<object>();\n\n json = JSON.stringify(state, (_key, value) => {\n if (typeof value === 'object' && value !== null) {\n if (seen.has(value)) {\n return null;\n }\n seen.add(value);\n }\n return value;\n });\n }\n\n if (hadCycle && isDev()) {\n console.warn(\n '[SSR] Circular reference detected in state serialization. ' +\n 'The circular value has been replaced with null. ' +\n 'Consider restructuring your loader data to avoid circular references.'\n );\n }\n\n return json\n .replace(/<\\/script/gi, '<\\\\/script')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029');\n}\n\n/**\n * Escape CSS content for safe embedding in <style> tags\n *\n * Escapes </style to prevent XSS attacks where CSS contains\n * malicious closing style tags that could break out and inject scripts.\n */\nfunction escapeCssContent(css: string): string {\n // Escape </style to prevent breaking out of the style tag\n return css.replace(/<\\/style/gi, '<\\\\/style');\n}\n\n// =============================================================================\n// Main Implementation\n// =============================================================================\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.html-shell\",\"name\":\"htmlShell\",\"stability\":\"stable\",\"signature\":\"(options: ShellOptions) => string\"} */\n/**\n * Generate complete HTML document\n *\n * Creates a valid HTML5 document by combining:\n * - DOCTYPE declaration\n * - HTML element with lang attribute\n * - Head section with meta tags, stylesheets, preloads, and critical CSS\n * - Body section with rendered content, state, and scripts\n *\n * @param options - Shell generation options\n * @returns Complete HTML document string\n *\n * @example\n * ```ts\n * const html = htmlShell({\n * html: result.html,\n * head: result.head,\n * state: result.state,\n * scripts: ['/entry-client.js'],\n * styles: ['/styles.css'],\n * });\n * ```\n */\nexport function htmlShell(options: ShellOptions): string {\n const {\n html,\n head,\n state,\n scripts = [],\n styles = [],\n lang,\n bodyAttrs = {},\n appId = DEFAULT_APP_ID,\n criticalCss,\n preloads = [],\n } = options;\n\n // Build HTML attributes\n // Priority: direct lang option > head.htmlAttrs.lang > default 'en'\n const htmlAttrs = { ...head.htmlAttrs };\n if (lang) {\n htmlAttrs.lang = lang;\n } else if (!htmlAttrs.lang) {\n htmlAttrs.lang = 'en';\n }\n const htmlAttrsStr = renderHtmlAttrs({ ...head, htmlAttrs });\n\n // Build body attributes (merge head.bodyAttrs with options.bodyAttrs)\n const mergedBodyAttrs = { ...head.bodyAttrs, ...bodyAttrs };\n const bodyAttrsStr =\n Object.keys(mergedBodyAttrs).length > 0\n ? ' ' + renderAttrs(mergedBodyAttrs)\n : '';\n\n // Build head content\n const headParts: string[] = [];\n\n // Essential meta tags first\n headParts.push(' <meta charset=\"UTF-8\">');\n headParts.push(\n ' <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">'\n );\n\n // Preload hints (early in head for faster resource discovery)\n for (const preload of preloads) {\n headParts.push(' ' + renderPreloadTag(preload));\n }\n\n // Stylesheets\n for (const style of styles) {\n headParts.push(' ' + renderStylesheetTag(style));\n }\n\n // Critical CSS (inline) - escaped to prevent XSS via </style> injection\n if (criticalCss) {\n headParts.push(` <style>${escapeCssContent(criticalCss)}</style>`);\n }\n\n // Head state (title, meta, link, script from head() calls)\n const headStateHtml = renderHead(head);\n if (headStateHtml) {\n // Indent each line for consistent formatting\n const indentedHead = headStateHtml\n .split('\\n')\n .map(line => (line.trim() ? ' ' + line : line))\n .join('\\n');\n headParts.push(indentedHead);\n }\n\n // Build body content\n const bodyParts: string[] = [];\n\n // App container with rendered HTML\n bodyParts.push(` <div id=\"${escapeHtml(appId)}\">${html}</div>`);\n\n // State serialization script (omitted in static/no-JS mode when state is undefined)\n if (state !== undefined) {\n const stateScript = serializeState(state);\n bodyParts.push(\n ` <script>window.${STATE_VAR_NAME} = ${stateScript};</script>`\n );\n }\n\n // Entry scripts (after state so they can access it)\n for (const script of scripts) {\n bodyParts.push(' ' + renderScriptTag(script));\n }\n\n // Assemble final HTML document\n return `<!DOCTYPE html>\n<html ${htmlAttrsStr}>\n<head>\n${headParts.join('\\n')}\n</head>\n<body${bodyAttrsStr}>\n${bodyParts.join('\\n')}\n</body>\n</html>`;\n}\n"]}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** @codex
|
|
2
|
+
{
|
|
3
|
+
"id": "pithy.ssr.server",
|
|
4
|
+
"title": "SSR Server Runtime",
|
|
5
|
+
"category": "runtime"
|
|
6
|
+
}
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* @pithyjs/ssr/server - Server-side rendering exports
|
|
10
|
+
*
|
|
11
|
+
* Import from '@pithyjs/ssr/server' for server-side code.
|
|
12
|
+
*/
|
|
13
|
+
export type { RenderResult, SSRContext, SSREnvironment, ShellOptions, HeadState, HeadConfig, SerializedState, SSGResult, } from '../shared/types.js';
|
|
14
|
+
export { SSR_VERSION } from '../shared/types.js';
|
|
15
|
+
export { createSSRContext, getSSRContext, runWithSSRContext, runWithSSRContextAsync, isSSR, type CreateSSRContextOptions, } from './context.js';
|
|
16
|
+
export { setupEnvironment, withEnvironment, withEnvironmentAsync, type SetupEnvironmentOptions, } from './environment.js';
|
|
17
|
+
export { SSRHistoryAdapter, type SSRHistoryAdapterOptions, type SSRRedirect, } from './router-adapter.js';
|
|
18
|
+
export { executeSSRLoaders, extractLoadersFromRouteTree, createSSRLoaderContext, serializeLoaderData, deserializeLoaderData, generateCacheControlHeader, type SSRRouteSegment, type ExecuteLoadersOptions, type ExecuteLoadersResult, type SSRCacheHints, type SerializedLoaderData, } from './loaders.js';
|
|
19
|
+
export { htmlShell } from './html-shell.js';
|
|
20
|
+
export { renderToString, type RenderToStringOptions } from './render.js';
|
|
21
|
+
export { renderRoute, type RenderRouteOptions, type RenderRouteResult, } from './render-route.js';
|
|
22
|
+
export { createSSRWorkerPool, SSRWorkerPool, type SSRWorkerPoolOptions, type WorkerRenderOptions, } from './worker-pool.js';
|
|
23
|
+
export { PithyApp, createApp, type PithyAppOptions, type PithyMiddleware, } from './app.js';
|
|
24
|
+
export { mergeHead, findOutletMatch, injectIntoOutlet, } from '../shared/shell-helpers.js';
|
|
25
|
+
export { generateStaticSite, type GenerateStaticSiteOptions, } from '../build/ssg.js';
|
|
26
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;GAIG;AAGH,YAAY,EACV,YAAY,EACZ,UAAU,EACV,cAAc,EACd,YAAY,EACZ,SAAS,EACT,UAAU,EACV,eAAe,EACf,SAAS,GACV,MAAM,oBAAoB,CAAC;AAG5B,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAGjD,OAAO,EACL,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,sBAAsB,EACtB,KAAK,EACL,KAAK,uBAAuB,GAC7B,MAAM,cAAc,CAAC;AAStB,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,oBAAoB,EACpB,KAAK,uBAAuB,GAC7B,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EACL,iBAAiB,EACjB,KAAK,wBAAwB,EAC7B,KAAK,WAAW,GACjB,MAAM,qBAAqB,CAAC;AAG7B,OAAO,EACL,iBAAiB,EACjB,2BAA2B,EAC3B,sBAAsB,EACtB,mBAAmB,EACnB,qBAAqB,EACrB,0BAA0B,EAC1B,KAAK,eAAe,EACpB,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EACzB,KAAK,aAAa,EAClB,KAAK,oBAAoB,GAC1B,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAG5C,OAAO,EAAE,cAAc,EAAE,KAAK,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAGzE,OAAO,EACL,WAAW,EACX,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,GACvB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EACL,mBAAmB,EACnB,aAAa,EACb,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,GACzB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EACL,QAAQ,EACR,SAAS,EACT,KAAK,eAAe,EACpB,KAAK,eAAe,GACrB,MAAM,UAAU,CAAC;AAGlB,OAAO,EACL,SAAS,EACT,eAAe,EACf,gBAAgB,GACjB,MAAM,4BAA4B,CAAC;AAGpC,OAAO,EACL,kBAAkB,EAClB,KAAK,yBAAyB,GAC/B,MAAM,iBAAiB,CAAC"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** @codex
|
|
2
|
+
{
|
|
3
|
+
"id": "pithy.ssr.server",
|
|
4
|
+
"title": "SSR Server Runtime",
|
|
5
|
+
"category": "runtime"
|
|
6
|
+
}
|
|
7
|
+
*/
|
|
8
|
+
// Constants
|
|
9
|
+
export { SSR_VERSION } from '../shared/types.js';
|
|
10
|
+
// Context API
|
|
11
|
+
export { createSSRContext, getSSRContext, runWithSSRContext, runWithSSRContextAsync, isSSR, } from './context.js';
|
|
12
|
+
// Initialize head API context getter (side effect)
|
|
13
|
+
// This wires up the head() function to access SSR context
|
|
14
|
+
import { setContextGetter } from '../shared/head.js';
|
|
15
|
+
import { getSSRContext } from './context.js';
|
|
16
|
+
setContextGetter(getSSRContext);
|
|
17
|
+
// Environment API
|
|
18
|
+
export { setupEnvironment, withEnvironment, withEnvironmentAsync, } from './environment.js';
|
|
19
|
+
// Router Adapter API
|
|
20
|
+
export { SSRHistoryAdapter, } from './router-adapter.js';
|
|
21
|
+
// Loader API
|
|
22
|
+
export { executeSSRLoaders, extractLoadersFromRouteTree, createSSRLoaderContext, serializeLoaderData, deserializeLoaderData, generateCacheControlHeader, } from './loaders.js';
|
|
23
|
+
// HTML Shell API (Task 8)
|
|
24
|
+
export { htmlShell } from './html-shell.js';
|
|
25
|
+
// Render API (Task 7 - Implemented)
|
|
26
|
+
export { renderToString } from './render.js';
|
|
27
|
+
// Route Render API (Task 12 - Full SSR pipeline)
|
|
28
|
+
export { renderRoute, } from './render-route.js';
|
|
29
|
+
// Worker Pool API
|
|
30
|
+
export { createSSRWorkerPool, SSRWorkerPool, } from './worker-pool.js';
|
|
31
|
+
// PithyApp API (Task 15 - Request → Response boundary)
|
|
32
|
+
export { PithyApp, createApp, } from './app.js';
|
|
33
|
+
// Shell helpers (shared between SSR dev plugin and SSG build)
|
|
34
|
+
export { mergeHead, findOutletMatch, injectIntoOutlet, } from '../shared/shell-helpers.js';
|
|
35
|
+
// SSG Build API (Task 10)
|
|
36
|
+
export { generateStaticSite, } from '../build/ssg.js';
|
|
37
|
+
//# sourceMappingURL=index.js.map
|