@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.
Files changed (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -2
  3. package/bin/pithy-ssg.mjs +23 -0
  4. package/dist/browser.d.ts +38 -0
  5. package/dist/browser.d.ts.map +1 -0
  6. package/dist/browser.js +40 -0
  7. package/dist/browser.js.map +1 -0
  8. package/dist/build/cli-args.d.ts +104 -0
  9. package/dist/build/cli-args.d.ts.map +1 -0
  10. package/dist/build/cli-args.js +88 -0
  11. package/dist/build/cli-args.js.map +1 -0
  12. package/dist/build/cli-exit.d.ts +95 -0
  13. package/dist/build/cli-exit.d.ts.map +1 -0
  14. package/dist/build/cli-exit.js +237 -0
  15. package/dist/build/cli-exit.js.map +1 -0
  16. package/dist/build/cli.d.ts +11 -0
  17. package/dist/build/cli.d.ts.map +1 -0
  18. package/dist/build/cli.js +93 -0
  19. package/dist/build/cli.js.map +1 -0
  20. package/dist/build/collect-css.d.ts +168 -0
  21. package/dist/build/collect-css.d.ts.map +1 -0
  22. package/dist/build/collect-css.js +479 -0
  23. package/dist/build/collect-css.js.map +1 -0
  24. package/dist/build/css-live-props.d.ts +89 -0
  25. package/dist/build/css-live-props.d.ts.map +1 -0
  26. package/dist/build/css-live-props.js +704 -0
  27. package/dist/build/css-live-props.js.map +1 -0
  28. package/dist/build/css-purge.d.ts +153 -0
  29. package/dist/build/css-purge.d.ts.map +1 -0
  30. package/dist/build/css-purge.js +463 -0
  31. package/dist/build/css-purge.js.map +1 -0
  32. package/dist/build/index.d.ts +24 -0
  33. package/dist/build/index.d.ts.map +1 -0
  34. package/dist/build/index.js +31 -0
  35. package/dist/build/index.js.map +1 -0
  36. package/dist/build/not-found.d.ts +94 -0
  37. package/dist/build/not-found.d.ts.map +1 -0
  38. package/dist/build/not-found.js +99 -0
  39. package/dist/build/not-found.js.map +1 -0
  40. package/dist/build/relative-links.d.ts +31 -0
  41. package/dist/build/relative-links.d.ts.map +1 -0
  42. package/dist/build/relative-links.js +79 -0
  43. package/dist/build/relative-links.js.map +1 -0
  44. package/dist/build/shell-head.d.ts +68 -0
  45. package/dist/build/shell-head.d.ts.map +1 -0
  46. package/dist/build/shell-head.js +236 -0
  47. package/dist/build/shell-head.js.map +1 -0
  48. package/dist/build/sprite-ssg.d.ts +61 -0
  49. package/dist/build/sprite-ssg.d.ts.map +1 -0
  50. package/dist/build/sprite-ssg.js +114 -0
  51. package/dist/build/sprite-ssg.js.map +1 -0
  52. package/dist/build/ssg.d.ts +117 -0
  53. package/dist/build/ssg.d.ts.map +1 -0
  54. package/dist/build/ssg.js +404 -0
  55. package/dist/build/ssg.js.map +1 -0
  56. package/dist/build/vite-ssg.d.ts +396 -0
  57. package/dist/build/vite-ssg.d.ts.map +1 -0
  58. package/dist/build/vite-ssg.js +1130 -0
  59. package/dist/build/vite-ssg.js.map +1 -0
  60. package/dist/client/bootstrap.d.ts +51 -0
  61. package/dist/client/bootstrap.d.ts.map +1 -0
  62. package/dist/client/bootstrap.js +121 -0
  63. package/dist/client/bootstrap.js.map +1 -0
  64. package/dist/client/hydrate.d.ts +60 -0
  65. package/dist/client/hydrate.d.ts.map +1 -0
  66. package/dist/client/hydrate.js +168 -0
  67. package/dist/client/hydrate.js.map +1 -0
  68. package/dist/client/index.d.ts +21 -0
  69. package/dist/client/index.d.ts.map +1 -0
  70. package/dist/client/index.js +16 -0
  71. package/dist/client/index.js.map +1 -0
  72. package/dist/index.d.ts +32 -0
  73. package/dist/index.d.ts.map +1 -0
  74. package/dist/index.js +31 -0
  75. package/dist/index.js.map +1 -0
  76. package/dist/server/app.d.ts +166 -0
  77. package/dist/server/app.d.ts.map +1 -0
  78. package/dist/server/app.js +200 -0
  79. package/dist/server/app.js.map +1 -0
  80. package/dist/server/context.d.ts +238 -0
  81. package/dist/server/context.d.ts.map +1 -0
  82. package/dist/server/context.js +371 -0
  83. package/dist/server/context.js.map +1 -0
  84. package/dist/server/environment.d.ts +88 -0
  85. package/dist/server/environment.d.ts.map +1 -0
  86. package/dist/server/environment.js +261 -0
  87. package/dist/server/environment.js.map +1 -0
  88. package/dist/server/html-shell.d.ts +41 -0
  89. package/dist/server/html-shell.d.ts.map +1 -0
  90. package/dist/server/html-shell.js +208 -0
  91. package/dist/server/html-shell.js.map +1 -0
  92. package/dist/server/index.d.ts +26 -0
  93. package/dist/server/index.d.ts.map +1 -0
  94. package/dist/server/index.js +37 -0
  95. package/dist/server/index.js.map +1 -0
  96. package/dist/server/layout-taint.d.ts +62 -0
  97. package/dist/server/layout-taint.d.ts.map +1 -0
  98. package/dist/server/layout-taint.js +313 -0
  99. package/dist/server/layout-taint.js.map +1 -0
  100. package/dist/server/loaders.d.ts +194 -0
  101. package/dist/server/loaders.d.ts.map +1 -0
  102. package/dist/server/loaders.js +479 -0
  103. package/dist/server/loaders.js.map +1 -0
  104. package/dist/server/render-route.d.ts +102 -0
  105. package/dist/server/render-route.d.ts.map +1 -0
  106. package/dist/server/render-route.js +182 -0
  107. package/dist/server/render-route.js.map +1 -0
  108. package/dist/server/render.d.ts +80 -0
  109. package/dist/server/render.d.ts.map +1 -0
  110. package/dist/server/render.js +256 -0
  111. package/dist/server/render.js.map +1 -0
  112. package/dist/server/router-adapter.d.ts +134 -0
  113. package/dist/server/router-adapter.d.ts.map +1 -0
  114. package/dist/server/router-adapter.js +225 -0
  115. package/dist/server/router-adapter.js.map +1 -0
  116. package/dist/server/serialization.d.ts +54 -0
  117. package/dist/server/serialization.d.ts.map +1 -0
  118. package/dist/server/serialization.js +287 -0
  119. package/dist/server/serialization.js.map +1 -0
  120. package/dist/server/ssr-worker.d.ts +18 -0
  121. package/dist/server/ssr-worker.d.ts.map +1 -0
  122. package/dist/server/ssr-worker.js +118 -0
  123. package/dist/server/ssr-worker.js.map +1 -0
  124. package/dist/server/utils.d.ts +11 -0
  125. package/dist/server/utils.d.ts.map +1 -0
  126. package/dist/server/utils.js +14 -0
  127. package/dist/server/utils.js.map +1 -0
  128. package/dist/server/worker-pool.d.ts +153 -0
  129. package/dist/server/worker-pool.d.ts.map +1 -0
  130. package/dist/server/worker-pool.js +451 -0
  131. package/dist/server/worker-pool.js.map +1 -0
  132. package/dist/server/worker-protocol.d.ts +61 -0
  133. package/dist/server/worker-protocol.d.ts.map +1 -0
  134. package/dist/server/worker-protocol.js +9 -0
  135. package/dist/server/worker-protocol.js.map +1 -0
  136. package/dist/shared/css-purge.d.ts +71 -0
  137. package/dist/shared/css-purge.d.ts.map +1 -0
  138. package/dist/shared/css-purge.js +177 -0
  139. package/dist/shared/css-purge.js.map +1 -0
  140. package/dist/shared/entry-path.d.ts +41 -0
  141. package/dist/shared/entry-path.d.ts.map +1 -0
  142. package/dist/shared/entry-path.js +87 -0
  143. package/dist/shared/entry-path.js.map +1 -0
  144. package/dist/shared/head.d.ts +87 -0
  145. package/dist/shared/head.d.ts.map +1 -0
  146. package/dist/shared/head.js +412 -0
  147. package/dist/shared/head.js.map +1 -0
  148. package/dist/shared/shell-helpers.d.ts +69 -0
  149. package/dist/shared/shell-helpers.d.ts.map +1 -0
  150. package/dist/shared/shell-helpers.js +160 -0
  151. package/dist/shared/shell-helpers.js.map +1 -0
  152. package/dist/shared/types.d.ts +332 -0
  153. package/dist/shared/types.d.ts.map +1 -0
  154. package/dist/shared/types.js +27 -0
  155. package/dist/shared/types.js.map +1 -0
  156. package/package.json +84 -3
@@ -0,0 +1,371 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.ssr.server.context",
4
+ "title": "SSR Context & Request Isolation",
5
+ "category": "runtime"
6
+ }
7
+ */
8
+ /**
9
+ * @pithyjs/ssr - SSR Context & Request Isolation
10
+ *
11
+ * Provides per-request context isolation using AsyncLocalStorage.
12
+ * This ensures concurrent SSR requests don't interfere with each other.
13
+ */
14
+ import { AsyncLocalStorage } from 'node:async_hooks';
15
+ import { createEmptyHeadState } from '../index.js';
16
+ // =============================================================================
17
+ // AsyncLocalStorage Instance
18
+ // =============================================================================
19
+ /**
20
+ * AsyncLocalStorage instance for SSR context isolation.
21
+ * Each SSR request runs in its own async context with isolated state.
22
+ */
23
+ const ssrContextStorage = new AsyncLocalStorage();
24
+ /**
25
+ * AsyncLocalStorage instance for component context isolation.
26
+ * This isolates the component context (passed to renderToString) per request,
27
+ * preventing data leakage between concurrent renders.
28
+ *
29
+ * @see Task 14 in docs/ssr/progress-tracker.md
30
+ */
31
+ const componentContextStorage = new AsyncLocalStorage();
32
+ // =============================================================================
33
+ // Global Getter Bridge (Installed Once at Module Init)
34
+ // =============================================================================
35
+ /**
36
+ * Install a stable global getter that @pithyjs/core can use to access the component context.
37
+ * This is installed ONCE at module initialization time to avoid race conditions.
38
+ * The getter delegates to AsyncLocalStorage, which provides proper isolation.
39
+ *
40
+ * This approach avoids the race condition that would occur if we installed/removed
41
+ * the getter per-request (overlapping requests could delete each other's getters).
42
+ */
43
+ function installGlobalComponentContextGetter() {
44
+ // Only install if not already present (idempotent)
45
+ if (typeof globalThis.__getComponentContext !==
46
+ 'function') {
47
+ globalThis.__getComponentContext = () => {
48
+ return componentContextStorage.getStore();
49
+ };
50
+ }
51
+ }
52
+ // Install the getter immediately when this module is loaded
53
+ installGlobalComponentContextGetter();
54
+ /** @codexApi {"parent":"pithy.ssr.server.context","name":"createSSRContext","stability":"stable","signature":"(options: CreateSSRContextOptions) => SSRContext"} */
55
+ /**
56
+ * Create a new SSR context for a request
57
+ *
58
+ * @param options - Context creation options
59
+ * @returns A new SSR context instance
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * const context = createSSRContext({
64
+ * url: '/dashboard',
65
+ * params: { id: '123' },
66
+ * query: { tab: 'settings' }
67
+ * });
68
+ * ```
69
+ */
70
+ export function createSSRContext(options) {
71
+ const { url, params = {}, query = {}, loaderData = {}, head, status = 200, } = options;
72
+ // Parse query from URL if not provided
73
+ let queryParams = query;
74
+ if (Object.keys(query).length === 0 && url.includes('?')) {
75
+ const urlObj = new URL(url, 'http://localhost');
76
+ queryParams = Object.fromEntries(urlObj.searchParams.entries());
77
+ }
78
+ // Create empty head state and merge with any provided values
79
+ const headState = {
80
+ ...createEmptyHeadState(),
81
+ ...head,
82
+ };
83
+ return {
84
+ url,
85
+ params,
86
+ query: queryParams,
87
+ head: headState,
88
+ loaderData,
89
+ isSSR: true,
90
+ status,
91
+ redirectTo: undefined,
92
+ };
93
+ }
94
+ // =============================================================================
95
+ // Context Access
96
+ // =============================================================================
97
+ /** @codexApi {"parent":"pithy.ssr.server.context","name":"getSSRContext","stability":"stable","signature":"() => SSRContext | undefined"} */
98
+ /**
99
+ * Get the current SSR context
100
+ *
101
+ * Returns undefined when called outside of an SSR render.
102
+ * Use this to access the current request's context during component rendering.
103
+ *
104
+ * @returns The current SSR context or undefined
105
+ *
106
+ * @example
107
+ * ```ts
108
+ * function MyComponent() {
109
+ * const ctx = getSSRContext();
110
+ * if (ctx) {
111
+ * // Running in SSR mode
112
+ * console.log('Rendering URL:', ctx.url);
113
+ * }
114
+ * }
115
+ * ```
116
+ */
117
+ export function getSSRContext() {
118
+ return ssrContextStorage.getStore();
119
+ }
120
+ /** @codexApi {"parent":"pithy.ssr.server.context","name":"requireSSRContext","stability":"stable","signature":"() => SSRContext"} */
121
+ /**
122
+ * Get the current SSR context or throw if not in SSR
123
+ *
124
+ * Use this when you need the context and it would be an error
125
+ * to call outside SSR (e.g., in head() function).
126
+ *
127
+ * @returns The current SSR context
128
+ * @throws Error if called outside SSR render
129
+ *
130
+ * @example
131
+ * ```ts
132
+ * function head(config: HeadConfig) {
133
+ * const ctx = requireSSRContext();
134
+ * // Merge config into ctx.head...
135
+ * }
136
+ * ```
137
+ */
138
+ export function requireSSRContext() {
139
+ const ctx = ssrContextStorage.getStore();
140
+ if (!ctx) {
141
+ throw new Error('SSR context not found. This function must be called within runWithSSRContext().');
142
+ }
143
+ return ctx;
144
+ }
145
+ // =============================================================================
146
+ // Context Execution
147
+ // =============================================================================
148
+ /** @codexApi {"parent":"pithy.ssr.server.context","name":"runWithSSRContext","stability":"stable","signature":"<T>(context: SSRContext, fn: () => T) => T"} */
149
+ /**
150
+ * Execute a function with SSR context
151
+ *
152
+ * All code executed within the callback has access to the SSR context
153
+ * via getSSRContext(). This uses AsyncLocalStorage for isolation,
154
+ * so concurrent requests don't interfere with each other.
155
+ *
156
+ * @param context - The SSR context for this request
157
+ * @param fn - The function to execute with context
158
+ * @returns The return value of the function
159
+ *
160
+ * @example
161
+ * ```ts
162
+ * const result = runWithSSRContext(context, () => {
163
+ * // head() calls here will use this context
164
+ * return renderComponent(App);
165
+ * });
166
+ * ```
167
+ */
168
+ export function runWithSSRContext(context, fn) {
169
+ return ssrContextStorage.run(context, fn);
170
+ }
171
+ /** @codexApi {"parent":"pithy.ssr.server.context","name":"runWithSSRContextAsync","stability":"stable","signature":"<T>(context: SSRContext, fn: () => Promise<T>) => Promise<T>"} */
172
+ /**
173
+ * Execute an async function with SSR context
174
+ *
175
+ * Same as runWithSSRContext but for async functions.
176
+ * The context is preserved across await boundaries.
177
+ *
178
+ * @param context - The SSR context for this request
179
+ * @param fn - The async function to execute with context
180
+ * @returns A promise resolving to the function's return value
181
+ *
182
+ * @example
183
+ * ```ts
184
+ * const result = await runWithSSRContextAsync(context, async () => {
185
+ * await executeLoaders();
186
+ * return renderComponent(App);
187
+ * });
188
+ * ```
189
+ */
190
+ export async function runWithSSRContextAsync(context, fn) {
191
+ return ssrContextStorage.run(context, fn);
192
+ }
193
+ // =============================================================================
194
+ // Context Utilities
195
+ // =============================================================================
196
+ /** @codexApi {"parent":"pithy.ssr.server.context","name":"isSSR","stability":"stable","signature":"() => boolean"} */
197
+ /**
198
+ * Check if currently running in SSR mode
199
+ *
200
+ * @returns True if within an SSR render context
201
+ *
202
+ * @example
203
+ * ```ts
204
+ * if (isSSR()) {
205
+ * // Skip client-only code
206
+ * }
207
+ * ```
208
+ */
209
+ export function isSSR() {
210
+ return ssrContextStorage.getStore() !== undefined;
211
+ }
212
+ /** @codexApi {"parent":"pithy.ssr.server.context","name":"updateSSRContext","stability":"stable","signature":"(updates: Partial<Omit<SSRContext, 'isSSR'>>) => void"} */
213
+ /**
214
+ * Update the current SSR context
215
+ *
216
+ * Allows modifying the context during rendering (e.g., setting redirectTo, status).
217
+ *
218
+ * @param updates - Partial context updates to apply
219
+ * @throws Error if called outside SSR render
220
+ *
221
+ * @example
222
+ * ```ts
223
+ * updateSSRContext({ status: 404 });
224
+ * updateSSRContext({ redirectTo: '/login' });
225
+ * ```
226
+ */
227
+ export function updateSSRContext(updates) {
228
+ const ctx = requireSSRContext();
229
+ Object.assign(ctx, updates);
230
+ }
231
+ /** @codexApi {"parent":"pithy.ssr.server.context","name":"setLoaderData","stability":"stable","signature":"(key: string, data: unknown) => void"} */
232
+ /**
233
+ * Set loader data for a route segment
234
+ *
235
+ * @param key - Route segment ID or key
236
+ * @param data - Loader data to store
237
+ * @throws Error if called outside SSR render
238
+ *
239
+ * @example
240
+ * ```ts
241
+ * setLoaderData('dashboard', { user: userData, stats: dashboardStats });
242
+ * ```
243
+ */
244
+ export function setLoaderData(key, data) {
245
+ const ctx = requireSSRContext();
246
+ ctx.loaderData[key] = data;
247
+ }
248
+ /** @codexApi {"parent":"pithy.ssr.server.context","name":"getLoaderData","stability":"stable","signature":"<T>(key: string) => T | undefined"} */
249
+ /**
250
+ * Get loader data for a route segment
251
+ *
252
+ * @param key - Route segment ID or key
253
+ * @returns The loader data or undefined
254
+ *
255
+ * @example
256
+ * ```ts
257
+ * const data = getLoaderData<DashboardData>('dashboard');
258
+ * ```
259
+ */
260
+ export function getLoaderData(key) {
261
+ const ctx = getSSRContext();
262
+ if (!ctx)
263
+ return undefined;
264
+ return ctx.loaderData[key];
265
+ }
266
+ /** @codexApi {"parent":"pithy.ssr.server.context","name":"setRedirect","stability":"stable","signature":"(url: string, status?: number) => void"} */
267
+ /**
268
+ * Set a redirect response
269
+ *
270
+ * @param url - URL to redirect to
271
+ * @param status - HTTP status code (default: 302)
272
+ * @throws Error if called outside SSR render
273
+ *
274
+ * @example
275
+ * ```ts
276
+ * setRedirect('/login', 302);
277
+ * ```
278
+ */
279
+ export function setRedirect(url, status = 302) {
280
+ const ctx = requireSSRContext();
281
+ ctx.redirectTo = url;
282
+ ctx.status = status;
283
+ }
284
+ /** @codexApi {"parent":"pithy.ssr.server.context","name":"setStatus","stability":"stable","signature":"(status: number) => void"} */
285
+ /**
286
+ * Set HTTP status code
287
+ *
288
+ * @param status - HTTP status code
289
+ * @throws Error if called outside SSR render
290
+ *
291
+ * @example
292
+ * ```ts
293
+ * setStatus(404);
294
+ * ```
295
+ */
296
+ export function setStatus(status) {
297
+ const ctx = requireSSRContext();
298
+ ctx.status = status;
299
+ }
300
+ // =============================================================================
301
+ // onDestroy Callback Isolation (Internal)
302
+ // =============================================================================
303
+ /**
304
+ * AsyncLocalStorage for onDestroy callback isolation.
305
+ * Prevents concurrent SSR requests from interleaving onDestroy() callbacks
306
+ * into the wrong component/request.
307
+ */
308
+ const destroyCallbacksStorage = new AsyncLocalStorage();
309
+ /**
310
+ * Install global getter/setter bridge for @pithyjs/core's onDestroy module.
311
+ * Same pattern as __getComponentContext — installed once, delegates to AsyncLocalStorage.
312
+ */
313
+ function installGlobalDestroyCallbacksHooks() {
314
+ if (typeof globalThis
315
+ .__pithyGetDestroyCallbacks !== 'function') {
316
+ globalThis.__pithyGetDestroyCallbacks = () => {
317
+ return destroyCallbacksStorage.getStore()?.callbacks;
318
+ };
319
+ }
320
+ if (typeof globalThis
321
+ .__pithySetDestroyCallbacks !== 'function') {
322
+ globalThis.__pithySetDestroyCallbacks = (cbs) => {
323
+ const store = destroyCallbacksStorage.getStore();
324
+ if (store)
325
+ store.callbacks = cbs;
326
+ };
327
+ }
328
+ }
329
+ installGlobalDestroyCallbacksHooks();
330
+ /**
331
+ * @internal
332
+ * Execute a function with isolated onDestroy callback storage.
333
+ * Used by renderToString to prevent callback interleaving between concurrent requests.
334
+ */
335
+ export function runWithDestroyCallbacks(fn) {
336
+ return destroyCallbacksStorage.run({ callbacks: [] }, fn);
337
+ }
338
+ // =============================================================================
339
+ // Component Context Isolation (Internal)
340
+ // =============================================================================
341
+ /**
342
+ * @internal
343
+ * Get the current component context
344
+ *
345
+ * Used internally by renderToString. Not exported as public API.
346
+ * Access from @pithyjs/core is via the __getComponentContext global getter.
347
+ */
348
+ export function getComponentContext() {
349
+ return componentContextStorage.getStore();
350
+ }
351
+ /**
352
+ * @internal
353
+ * Execute a function with component context
354
+ *
355
+ * Used internally by renderToString to wrap rendering with isolated context.
356
+ * Not exported as public API - users pass context via renderToString options.
357
+ */
358
+ export function runWithComponentContext(context, fn) {
359
+ return componentContextStorage.run(context, fn);
360
+ }
361
+ /**
362
+ * @internal
363
+ * Execute an async function with component context
364
+ *
365
+ * Used internally. Context is preserved across await boundaries.
366
+ * Not exported as public API.
367
+ */
368
+ export async function runWithComponentContextAsync(context, fn) {
369
+ return componentContextStorage.run(context, fn);
370
+ }
371
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/server/context.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;GAKG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErD,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnD,gFAAgF;AAChF,6BAA6B;AAC7B,gFAAgF;AAEhF;;;GAGG;AACH,MAAM,iBAAiB,GAAG,IAAI,iBAAiB,EAAc,CAAC;AAE9D;;;;;;GAMG;AACH,MAAM,uBAAuB,GAAG,IAAI,iBAAiB,EAElD,CAAC;AAEJ,gFAAgF;AAChF,uDAAuD;AACvD,gFAAgF;AAEhF;;;;;;;GAOG;AACH,SAAS,mCAAmC;IAC1C,mDAAmD;IACnD,IACE,OAAQ,UAAsC,CAAC,qBAAqB;QACpE,UAAU,EACV,CAAC;QACA,UAAsC,CAAC,qBAAqB,GAAG,GAAG,EAAE;YACnE,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,CAAC;AAErC;;;;GAIG;AACH,MAAM,UAAU,uBAAuB,CAAI,EAAW;IACpD,OAAO,uBAAuB,CAAC,GAAG,CAAC,EAAE,SAAS,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;AAC5D,CAAC;AAED,gFAAgF;AAChF,yCAAyC;AACzC,gFAAgF;AAEhF;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB;IACjC,OAAO,uBAAuB,CAAC,QAAQ,EAAE,CAAC;AAC5C,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,uBAAuB,CACrC,OAAgC,EAChC,EAAW;IAEX,OAAO,uBAAuB,CAAC,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;AAClD,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,4BAA4B,CAChD,OAAgC,EAChC,EAAoB;IAEpB,OAAO,uBAAuB,CAAC,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;AAClD,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.ssr.server.context\",\n \"title\": \"SSR Context & Request Isolation\",\n \"category\": \"runtime\"\n}\n*/\n\n/**\n * @pithyjs/ssr - SSR Context & Request Isolation\n *\n * Provides per-request context isolation using AsyncLocalStorage.\n * This ensures concurrent SSR requests don't interfere with each other.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type { SSRContext, HeadState } from '../shared/types.js';\nimport { createEmptyHeadState } from '../index.js';\n\n// =============================================================================\n// AsyncLocalStorage Instance\n// =============================================================================\n\n/**\n * AsyncLocalStorage instance for SSR context isolation.\n * Each SSR request runs in its own async context with isolated state.\n */\nconst ssrContextStorage = new AsyncLocalStorage<SSRContext>();\n\n/**\n * AsyncLocalStorage instance for component context isolation.\n * This isolates the component context (passed to renderToString) per request,\n * preventing data leakage between concurrent renders.\n *\n * @see Task 14 in docs/ssr/progress-tracker.md\n */\nconst componentContextStorage = new AsyncLocalStorage<\n Record<string, unknown>\n>();\n\n// =============================================================================\n// Global Getter Bridge (Installed Once at Module Init)\n// =============================================================================\n\n/**\n * Install a stable global getter that @pithyjs/core can use to access the component context.\n * This is installed ONCE at module initialization time to avoid race conditions.\n * The getter delegates to AsyncLocalStorage, which provides proper isolation.\n *\n * This approach avoids the race condition that would occur if we installed/removed\n * the getter per-request (overlapping requests could delete each other's getters).\n */\nfunction installGlobalComponentContextGetter(): void {\n // Only install if not already present (idempotent)\n if (\n typeof (globalThis as Record<string, unknown>).__getComponentContext !==\n 'function'\n ) {\n (globalThis as Record<string, unknown>).__getComponentContext = () => {\n return componentContextStorage.getStore();\n };\n }\n}\n\n// Install the getter immediately when this module is loaded\ninstallGlobalComponentContextGetter();\n\n// =============================================================================\n// Context Creation\n// =============================================================================\n\n/**\n * Options for creating SSR context\n */\nexport interface CreateSSRContextOptions {\n /** URL being rendered */\n url: string;\n /** Route parameters (parsed from URL) */\n params?: Record<string, string>;\n /** Query parameters (parsed from URL) */\n query?: Record<string, string>;\n /** Initial loader data (if pre-populated) */\n loaderData?: Record<string, unknown>;\n /** Initial head state */\n head?: Partial<HeadState>;\n /** Initial HTTP status code */\n status?: number;\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.context\",\"name\":\"createSSRContext\",\"stability\":\"stable\",\"signature\":\"(options: CreateSSRContextOptions) => SSRContext\"} */\n/**\n * Create a new SSR context for a request\n *\n * @param options - Context creation options\n * @returns A new SSR context instance\n *\n * @example\n * ```ts\n * const context = createSSRContext({\n * url: '/dashboard',\n * params: { id: '123' },\n * query: { tab: 'settings' }\n * });\n * ```\n */\nexport function createSSRContext(options: CreateSSRContextOptions): SSRContext {\n const {\n url,\n params = {},\n query = {},\n loaderData = {},\n head,\n status = 200,\n } = options;\n\n // Parse query from URL if not provided\n let queryParams = query;\n if (Object.keys(query).length === 0 && url.includes('?')) {\n const urlObj = new URL(url, 'http://localhost');\n queryParams = Object.fromEntries(urlObj.searchParams.entries());\n }\n\n // Create empty head state and merge with any provided values\n const headState: HeadState = {\n ...createEmptyHeadState(),\n ...head,\n };\n\n return {\n url,\n params,\n query: queryParams,\n head: headState,\n loaderData,\n isSSR: true,\n status,\n redirectTo: undefined,\n };\n}\n\n// =============================================================================\n// Context Access\n// =============================================================================\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.context\",\"name\":\"getSSRContext\",\"stability\":\"stable\",\"signature\":\"() => SSRContext | undefined\"} */\n/**\n * Get the current SSR context\n *\n * Returns undefined when called outside of an SSR render.\n * Use this to access the current request's context during component rendering.\n *\n * @returns The current SSR context or undefined\n *\n * @example\n * ```ts\n * function MyComponent() {\n * const ctx = getSSRContext();\n * if (ctx) {\n * // Running in SSR mode\n * console.log('Rendering URL:', ctx.url);\n * }\n * }\n * ```\n */\nexport function getSSRContext(): SSRContext | undefined {\n return ssrContextStorage.getStore();\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.context\",\"name\":\"requireSSRContext\",\"stability\":\"stable\",\"signature\":\"() => SSRContext\"} */\n/**\n * Get the current SSR context or throw if not in SSR\n *\n * Use this when you need the context and it would be an error\n * to call outside SSR (e.g., in head() function).\n *\n * @returns The current SSR context\n * @throws Error if called outside SSR render\n *\n * @example\n * ```ts\n * function head(config: HeadConfig) {\n * const ctx = requireSSRContext();\n * // Merge config into ctx.head...\n * }\n * ```\n */\nexport function requireSSRContext(): SSRContext {\n const ctx = ssrContextStorage.getStore();\n if (!ctx) {\n throw new Error(\n 'SSR context not found. This function must be called within runWithSSRContext().'\n );\n }\n return ctx;\n}\n\n// =============================================================================\n// Context Execution\n// =============================================================================\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.context\",\"name\":\"runWithSSRContext\",\"stability\":\"stable\",\"signature\":\"<T>(context: SSRContext, fn: () => T) => T\"} */\n/**\n * Execute a function with SSR context\n *\n * All code executed within the callback has access to the SSR context\n * via getSSRContext(). This uses AsyncLocalStorage for isolation,\n * so concurrent requests don't interfere with each other.\n *\n * @param context - The SSR context for this request\n * @param fn - The function to execute with context\n * @returns The return value of the function\n *\n * @example\n * ```ts\n * const result = runWithSSRContext(context, () => {\n * // head() calls here will use this context\n * return renderComponent(App);\n * });\n * ```\n */\nexport function runWithSSRContext<T>(context: SSRContext, fn: () => T): T {\n return ssrContextStorage.run(context, fn);\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.context\",\"name\":\"runWithSSRContextAsync\",\"stability\":\"stable\",\"signature\":\"<T>(context: SSRContext, fn: () => Promise<T>) => Promise<T>\"} */\n/**\n * Execute an async function with SSR context\n *\n * Same as runWithSSRContext but for async functions.\n * The context is preserved across await boundaries.\n *\n * @param context - The SSR context for this request\n * @param fn - The async function to execute with context\n * @returns A promise resolving to the function's return value\n *\n * @example\n * ```ts\n * const result = await runWithSSRContextAsync(context, async () => {\n * await executeLoaders();\n * return renderComponent(App);\n * });\n * ```\n */\nexport async function runWithSSRContextAsync<T>(\n context: SSRContext,\n fn: () => Promise<T>\n): Promise<T> {\n return ssrContextStorage.run(context, fn);\n}\n\n// =============================================================================\n// Context Utilities\n// =============================================================================\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.context\",\"name\":\"isSSR\",\"stability\":\"stable\",\"signature\":\"() => boolean\"} */\n/**\n * Check if currently running in SSR mode\n *\n * @returns True if within an SSR render context\n *\n * @example\n * ```ts\n * if (isSSR()) {\n * // Skip client-only code\n * }\n * ```\n */\nexport function isSSR(): boolean {\n return ssrContextStorage.getStore() !== undefined;\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.context\",\"name\":\"updateSSRContext\",\"stability\":\"stable\",\"signature\":\"(updates: Partial<Omit<SSRContext, 'isSSR'>>) => void\"} */\n/**\n * Update the current SSR context\n *\n * Allows modifying the context during rendering (e.g., setting redirectTo, status).\n *\n * @param updates - Partial context updates to apply\n * @throws Error if called outside SSR render\n *\n * @example\n * ```ts\n * updateSSRContext({ status: 404 });\n * updateSSRContext({ redirectTo: '/login' });\n * ```\n */\nexport function updateSSRContext(\n updates: Partial<Omit<SSRContext, 'isSSR'>>\n): void {\n const ctx = requireSSRContext();\n Object.assign(ctx, updates);\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.context\",\"name\":\"setLoaderData\",\"stability\":\"stable\",\"signature\":\"(key: string, data: unknown) => void\"} */\n/**\n * Set loader data for a route segment\n *\n * @param key - Route segment ID or key\n * @param data - Loader data to store\n * @throws Error if called outside SSR render\n *\n * @example\n * ```ts\n * setLoaderData('dashboard', { user: userData, stats: dashboardStats });\n * ```\n */\nexport function setLoaderData(key: string, data: unknown): void {\n const ctx = requireSSRContext();\n ctx.loaderData[key] = data;\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.context\",\"name\":\"getLoaderData\",\"stability\":\"stable\",\"signature\":\"<T>(key: string) => T | undefined\"} */\n/**\n * Get loader data for a route segment\n *\n * @param key - Route segment ID or key\n * @returns The loader data or undefined\n *\n * @example\n * ```ts\n * const data = getLoaderData<DashboardData>('dashboard');\n * ```\n */\nexport function getLoaderData<T>(key: string): T | undefined {\n const ctx = getSSRContext();\n if (!ctx) return undefined;\n return ctx.loaderData[key] as T | undefined;\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.context\",\"name\":\"setRedirect\",\"stability\":\"stable\",\"signature\":\"(url: string, status?: number) => void\"} */\n/**\n * Set a redirect response\n *\n * @param url - URL to redirect to\n * @param status - HTTP status code (default: 302)\n * @throws Error if called outside SSR render\n *\n * @example\n * ```ts\n * setRedirect('/login', 302);\n * ```\n */\nexport function setRedirect(url: string, status: number = 302): void {\n const ctx = requireSSRContext();\n ctx.redirectTo = url;\n ctx.status = status;\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.context\",\"name\":\"setStatus\",\"stability\":\"stable\",\"signature\":\"(status: number) => void\"} */\n/**\n * Set HTTP status code\n *\n * @param status - HTTP status code\n * @throws Error if called outside SSR render\n *\n * @example\n * ```ts\n * setStatus(404);\n * ```\n */\nexport function setStatus(status: number): void {\n const ctx = requireSSRContext();\n ctx.status = status;\n}\n\n// =============================================================================\n// onDestroy Callback Isolation (Internal)\n// =============================================================================\n\n/**\n * AsyncLocalStorage for onDestroy callback isolation.\n * Prevents concurrent SSR requests from interleaving onDestroy() callbacks\n * into the wrong component/request.\n */\nconst destroyCallbacksStorage = new AsyncLocalStorage<{\n callbacks: (() => void)[];\n}>();\n\n/**\n * Install global getter/setter bridge for @pithyjs/core's onDestroy module.\n * Same pattern as __getComponentContext — installed once, delegates to AsyncLocalStorage.\n */\nfunction installGlobalDestroyCallbacksHooks(): void {\n if (\n typeof (globalThis as Record<string, unknown>)\n .__pithyGetDestroyCallbacks !== 'function'\n ) {\n (globalThis as Record<string, unknown>).__pithyGetDestroyCallbacks = () => {\n return destroyCallbacksStorage.getStore()?.callbacks;\n };\n }\n if (\n typeof (globalThis as Record<string, unknown>)\n .__pithySetDestroyCallbacks !== 'function'\n ) {\n (globalThis as Record<string, unknown>).__pithySetDestroyCallbacks = (\n cbs: (() => void)[]\n ) => {\n const store = destroyCallbacksStorage.getStore();\n if (store) store.callbacks = cbs;\n };\n }\n}\n\ninstallGlobalDestroyCallbacksHooks();\n\n/**\n * @internal\n * Execute a function with isolated onDestroy callback storage.\n * Used by renderToString to prevent callback interleaving between concurrent requests.\n */\nexport function runWithDestroyCallbacks<T>(fn: () => T): T {\n return destroyCallbacksStorage.run({ callbacks: [] }, fn);\n}\n\n// =============================================================================\n// Component Context Isolation (Internal)\n// =============================================================================\n\n/**\n * @internal\n * Get the current component context\n *\n * Used internally by renderToString. Not exported as public API.\n * Access from @pithyjs/core is via the __getComponentContext global getter.\n */\nexport function getComponentContext(): Record<string, unknown> | undefined {\n return componentContextStorage.getStore();\n}\n\n/**\n * @internal\n * Execute a function with component context\n *\n * Used internally by renderToString to wrap rendering with isolated context.\n * Not exported as public API - users pass context via renderToString options.\n */\nexport function runWithComponentContext<T>(\n context: Record<string, unknown>,\n fn: () => T\n): T {\n return componentContextStorage.run(context, fn);\n}\n\n/**\n * @internal\n * Execute an async function with component context\n *\n * Used internally. Context is preserved across await boundaries.\n * Not exported as public API.\n */\nexport async function runWithComponentContextAsync<T>(\n context: Record<string, unknown>,\n fn: () => Promise<T>\n): Promise<T> {\n return componentContextStorage.run(context, fn);\n}\n"]}
@@ -0,0 +1,88 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.ssr.server.environment",
4
+ "title": "SSR DOM Environment",
5
+ "category": "runtime"
6
+ }
7
+ */
8
+ import type { SSREnvironment } from '../shared/types.js';
9
+ /** @codexApi {"parent":"pithy.ssr.server.environment","name":"setupEnvironment","stability":"stable","signature":"(options?: SetupEnvironmentOptions) => SSREnvironment"} */
10
+ /**
11
+ * Set up SSR DOM environment with happy-dom
12
+ *
13
+ * Creates a lightweight DOM environment for server-side rendering.
14
+ * PithyJS components can use standard DOM APIs during SSR.
15
+ *
16
+ * @param options - Optional configuration
17
+ * @returns Environment with cleanup function and DOM references
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * const env = setupEnvironment();
22
+ * try {
23
+ * // Render components - document, window, etc. are now available
24
+ * const html = document.getElementById('app')?.innerHTML;
25
+ * } finally {
26
+ * env.cleanup();
27
+ * }
28
+ * ```
29
+ *
30
+ * @throws Error if environment is already active (prevents nested setup)
31
+ */
32
+ export declare function setupEnvironment(options?: SetupEnvironmentOptions): SSREnvironment;
33
+ /**
34
+ * Options for setupEnvironment
35
+ */
36
+ export interface SetupEnvironmentOptions {
37
+ /** Base URL for the document (default: 'http://localhost') */
38
+ url?: string;
39
+ /** ID for the app container element (default: 'app') */
40
+ appId?: string;
41
+ }
42
+ /** @codexApi {"parent":"pithy.ssr.server.environment","name":"isEnvironmentSetup","stability":"stable","signature":"() => boolean"} */
43
+ /**
44
+ * Check if SSR environment is currently active
45
+ *
46
+ * @returns True if setupEnvironment() has been called without cleanup()
47
+ */
48
+ export declare function isEnvironmentSetup(): boolean;
49
+ /** @codexApi {"parent":"pithy.ssr.server.environment","name":"withEnvironment","stability":"stable","signature":"<T>(fn: (env: SSREnvironment) => T) => T"} */
50
+ /**
51
+ * Execute a function with SSR environment, ensuring cleanup
52
+ *
53
+ * Convenience wrapper that sets up the environment, runs the function,
54
+ * and cleans up automatically (even if the function throws).
55
+ *
56
+ * @param fn - Function to execute with the environment
57
+ * @returns The function's return value
58
+ *
59
+ * @example
60
+ * ```ts
61
+ * const html = withEnvironment((env) => {
62
+ * // env.document, env.window available
63
+ * renderComponent(App);
64
+ * return env.document.getElementById('app')?.innerHTML ?? '';
65
+ * });
66
+ * ```
67
+ */
68
+ export declare function withEnvironment<T>(fn: (env: SSREnvironment) => T): T;
69
+ /** @codexApi {"parent":"pithy.ssr.server.environment","name":"withEnvironmentAsync","stability":"stable","signature":"<T>(fn: (env: SSREnvironment) => Promise<T>) => Promise<T>"} */
70
+ /**
71
+ * Execute an async function with SSR environment, ensuring cleanup
72
+ *
73
+ * Same as withEnvironment but for async functions.
74
+ *
75
+ * @param fn - Async function to execute with the environment
76
+ * @returns Promise resolving to the function's return value
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * const html = await withEnvironmentAsync(async (env) => {
81
+ * await loadData();
82
+ * renderComponent(App);
83
+ * return env.document.getElementById('app')?.innerHTML ?? '';
84
+ * });
85
+ * ```
86
+ */
87
+ export declare function withEnvironmentAsync<T>(fn: (env: SSREnvironment) => Promise<T>): Promise<T>;
88
+ //# sourceMappingURL=environment.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"environment.d.ts","sourceRoot":"","sources":["../../src/server/environment.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAUF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAqEzD,6KAA6K;AAC7K;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,gBAAgB,CAC9B,OAAO,CAAC,EAAE,uBAAuB,GAChC,cAAc,CA+JhB;AAED;;GAEG;AACH,MAAM,WAAW,uBAAuB;IACtC,8DAA8D;IAC9D,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,wDAAwD;IACxD,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,uIAAuI;AACvI;;;;GAIG;AACH,wBAAgB,kBAAkB,IAAI,OAAO,CAE5C;AAED,+JAA+J;AAC/J;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,eAAe,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,GAAG,EAAE,cAAc,KAAK,CAAC,GAAG,CAAC,CAOpE;AAED,sLAAsL;AACtL;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,oBAAoB,CAAC,CAAC,EAC1C,EAAE,EAAE,CAAC,GAAG,EAAE,cAAc,KAAK,OAAO,CAAC,CAAC,CAAC,GACtC,OAAO,CAAC,CAAC,CAAC,CAOZ"}