@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 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAoBF,YAAY;AACZ,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEjD,cAAc;AACd,OAAO,EACL,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,sBAAsB,EACtB,KAAK,GAEN,MAAM,cAAc,CAAC;AAEtB,mDAAmD;AACnD,0DAA0D;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,gBAAgB,CAAC,aAAa,CAAC,CAAC;AAEhC,kBAAkB;AAClB,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,oBAAoB,GAErB,MAAM,kBAAkB,CAAC;AAE1B,qBAAqB;AACrB,OAAO,EACL,iBAAiB,GAGlB,MAAM,qBAAqB,CAAC;AAE7B,aAAa;AACb,OAAO,EACL,iBAAiB,EACjB,2BAA2B,EAC3B,sBAAsB,EACtB,mBAAmB,EACnB,qBAAqB,EACrB,0BAA0B,GAM3B,MAAM,cAAc,CAAC;AAEtB,0BAA0B;AAC1B,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,oCAAoC;AACpC,OAAO,EAAE,cAAc,EAA8B,MAAM,aAAa,CAAC;AAEzE,iDAAiD;AACjD,OAAO,EACL,WAAW,GAGZ,MAAM,mBAAmB,CAAC;AAE3B,kBAAkB;AAClB,OAAO,EACL,mBAAmB,EACnB,aAAa,GAGd,MAAM,kBAAkB,CAAC;AAE1B,uDAAuD;AACvD,OAAO,EACL,QAAQ,EACR,SAAS,GAGV,MAAM,UAAU,CAAC;AAElB,8DAA8D;AAC9D,OAAO,EACL,SAAS,EACT,eAAe,EACf,gBAAgB,GACjB,MAAM,4BAA4B,CAAC;AAEpC,0BAA0B;AAC1B,OAAO,EACL,kBAAkB,GAEnB,MAAM,iBAAiB,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.ssr.server\",\n \"title\": \"SSR Server Runtime\",\n \"category\": \"runtime\"\n}\n*/\n\n/**\n * @pithyjs/ssr/server - Server-side rendering exports\n *\n * Import from '@pithyjs/ssr/server' for server-side code.\n */\n\n// Types\nexport type {\n RenderResult,\n SSRContext,\n SSREnvironment,\n ShellOptions,\n HeadState,\n HeadConfig,\n SerializedState,\n SSGResult,\n} from '../shared/types.js';\n\n// Constants\nexport { SSR_VERSION } from '../shared/types.js';\n\n// Context API\nexport {\n createSSRContext,\n getSSRContext,\n runWithSSRContext,\n runWithSSRContextAsync,\n isSSR,\n type CreateSSRContextOptions,\n} from './context.js';\n\n// Initialize head API context getter (side effect)\n// This wires up the head() function to access SSR context\nimport { setContextGetter } from '../shared/head.js';\nimport { getSSRContext } from './context.js';\nsetContextGetter(getSSRContext);\n\n// Environment API\nexport {\n setupEnvironment,\n withEnvironment,\n withEnvironmentAsync,\n type SetupEnvironmentOptions,\n} from './environment.js';\n\n// Router Adapter API\nexport {\n SSRHistoryAdapter,\n type SSRHistoryAdapterOptions,\n type SSRRedirect,\n} from './router-adapter.js';\n\n// Loader API\nexport {\n executeSSRLoaders,\n extractLoadersFromRouteTree,\n createSSRLoaderContext,\n serializeLoaderData,\n deserializeLoaderData,\n generateCacheControlHeader,\n type SSRRouteSegment,\n type ExecuteLoadersOptions,\n type ExecuteLoadersResult,\n type SSRCacheHints,\n type SerializedLoaderData,\n} from './loaders.js';\n\n// HTML Shell API (Task 8)\nexport { htmlShell } from './html-shell.js';\n\n// Render API (Task 7 - Implemented)\nexport { renderToString, type RenderToStringOptions } from './render.js';\n\n// Route Render API (Task 12 - Full SSR pipeline)\nexport {\n renderRoute,\n type RenderRouteOptions,\n type RenderRouteResult,\n} from './render-route.js';\n\n// Worker Pool API\nexport {\n createSSRWorkerPool,\n SSRWorkerPool,\n type SSRWorkerPoolOptions,\n type WorkerRenderOptions,\n} from './worker-pool.js';\n\n// PithyApp API (Task 15 - Request → Response boundary)\nexport {\n PithyApp,\n createApp,\n type PithyAppOptions,\n type PithyMiddleware,\n} from './app.js';\n\n// Shell helpers (shared between SSR dev plugin and SSG build)\nexport {\n mergeHead,\n findOutletMatch,\n injectIntoOutlet,\n} from '../shared/shell-helpers.js';\n\n// SSG Build API (Task 10)\nexport {\n generateStaticSite,\n type GenerateStaticSiteOptions,\n} from '../build/ssg.js';\n"]}
@@ -0,0 +1,62 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.ssr.layout-taint",
4
+ "title": "Layout Taint (server-only)",
5
+ "category": "runtime",
6
+ "risk": "high"
7
+ }
8
+ */
9
+ /** Restores installed by {@link installLayoutTaint}, applied on teardown. */
10
+ type Restore = () => void;
11
+ /**
12
+ * Replace layout accessors on a happy-dom window with tainted (`NaN`) versions.
13
+ *
14
+ * @param window - The happy-dom window whose prototypes to patch.
15
+ * @returns A function restoring the original accessors.
16
+ */
17
+ /** @codexApi {"parent":"pithy.ssr.layout-taint","name":"installLayoutTaint","stability":"experimental","signature":"(window: unknown) => () => void"} */
18
+ export declare function installLayoutTaint(window: unknown): Restore;
19
+ /**
20
+ * Remove measurement-derived declarations from a rendered tree, **before** it is
21
+ * serialized.
22
+ *
23
+ * ## Why this operates on the DOM, not the HTML string
24
+ *
25
+ * An earlier version regex-matched `style="…"` in the serialized output. That
26
+ * cannot tell an element's style attribute from the same characters appearing
27
+ * anywhere else — inside an inline `<script>`, or in app-authored markup — and
28
+ * `renderToString()` accepts arbitrary application content, so the failure mode
29
+ * was silent output corruption. Walking real elements removes that whole class:
30
+ * a declaration is only ever dropped from an actual `CSSStyleDeclaration`.
31
+ *
32
+ * @param root - Container whose subtree to clean. The root itself is included.
33
+ * @param onDrop - Called with each dropped `prop: value`, so the caller can
34
+ * report it. Silence is the failure mode: a style vanishing without a trace is
35
+ * what makes a stray `NaN` hard to explain later.
36
+ */
37
+ /** @codexApi {"parent":"pithy.ssr.layout-taint","name":"stripTaintedStyles","stability":"experimental","signature":"(root: Element, onDrop?: (declaration: string) => void) => void"} */
38
+ export declare function stripTaintedStyles(root: Element, onDrop?: (declaration: string) => void): void;
39
+ /**
40
+ * Find zero-valued geometry in emitted HTML — the fingerprint of a measurement
41
+ * that escaped the taint.
42
+ *
43
+ * ## Why a detector and not a fix
44
+ *
45
+ * {@link installLayoutTaint} makes a measurement self-identifying, but a
46
+ * *comparison* can launder it back to a clean number: `publishHeaderOffset`
47
+ * reduces with `if (height > tallest)`, and `NaN > 0` is false, so `tallest`
48
+ * stays `0` and a perfectly ordinary `0px` is written. Nothing in the output
49
+ * distinguishes that from a legitimate zero, and comparison semantics cannot be
50
+ * changed — so the hole cannot be closed, only watched.
51
+ *
52
+ * This is deliberately a **heuristic**. It reports rather than throws, because a
53
+ * genuine zero is possible and failing a build on a guess is worse than the bug
54
+ * it guards.
55
+ *
56
+ * @param html - Serialized HTML for one page.
57
+ * @returns The suspicious declarations found, in document order.
58
+ */
59
+ /** @codexApi {"parent":"pithy.ssr.layout-taint","name":"findSuspiciousGeometry","stability":"experimental","signature":"(html: string) => string[]"} */
60
+ export declare function findSuspiciousGeometry(html: string): string[];
61
+ export {};
62
+ //# sourceMappingURL=layout-taint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"layout-taint.d.ts","sourceRoot":"","sources":["../../src/server/layout-taint.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AA0EF,6EAA6E;AAC7E,KAAK,OAAO,GAAG,MAAM,IAAI,CAAC;AA4B1B;;;;;GAKG;AACH,yJAAyJ;AACzJ,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,OAAO,GAAG,OAAO,CAoF3D;AAYD;;;;;;;;;;;;;;;;;GAiBG;AACH,yLAAyL;AACzL,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,OAAO,EACb,MAAM,CAAC,EAAE,CAAC,WAAW,EAAE,MAAM,KAAK,IAAI,GACrC,IAAI,CA0BN;AAmCD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wJAAwJ;AACxJ,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAa7D"}
@@ -0,0 +1,313 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.ssr.layout-taint",
4
+ "title": "Layout Taint (server-only)",
5
+ "category": "runtime",
6
+ "risk": "high"
7
+ }
8
+ */
9
+ /**
10
+ * Make unmeasurable layout *unmistakable*, so components never need to know
11
+ * they are being rendered on a server.
12
+ *
13
+ * ## The problem this replaces
14
+ *
15
+ * A server DOM has no layout engine, so `offsetWidth` and
16
+ * `getBoundingClientRect()` do not throw — they return **0**. Zero is a
17
+ * plausible answer, so a component writes it straight into an inline style and
18
+ * ships a broken value (`inline-size: 0px` on a tab indicator renders it
19
+ * invisible, and nothing re-runs to correct it).
20
+ *
21
+ * The only fixes available at the call site are guards, which means every author
22
+ * of every component has to know that static rendering exists.
23
+ *
24
+ * ## The idea
25
+ *
26
+ * Return `NaN` instead of `0`, and strip what it touches on the way out.
27
+ *
28
+ * `NaN` is the one value in JavaScript that **propagates through arithmetic**:
29
+ * `offsetLeft - clientWidth + offsetWidth` is `NaN` if any input is. So a
30
+ * measurement taints every value derived from it, however many steps later, with
31
+ * no tracking machinery. When such a value reaches the DOM it lands in the
32
+ * markup as the literal `NaN` — `inline-size: NaNpx` — which
33
+ * {@link stripTaintedStyles} then removes.
34
+ *
35
+ * The result is that a component measures freely, writes freely, and the
36
+ * measurement-derived writes simply never reach the output.
37
+ *
38
+ * ## What this does NOT change
39
+ *
40
+ * Only *layout* accessors are tainted. Reading a CSS **value** (a custom
41
+ * property, `direction`) is genuinely correct on the server, and stays correct.
42
+ *
43
+ * ## Known limits
44
+ *
45
+ * - **Comparisons against NaN are always false.** Code branching on
46
+ * `rect.height === 0` takes the other branch server-side. That path was
47
+ * already meaningless (it was comparing against a fabricated zero), but it is
48
+ * a behaviour change, not a no-op.
49
+ * - **A comparison can launder the taint.** `publishHeaderOffset` reduces with
50
+ * `if (height > tallest) tallest = height`; `NaN > 0` is false, so `tallest`
51
+ * stays `0` and a clean `0px` is written. Verified latent rather than live:
52
+ * that value lands on `documentElement`, and the static shell builds its own
53
+ * `<html>` element, so it is never serialized. It would become real if the
54
+ * shell ever emitted `documentElement`'s style, or if the same reduce-then-
55
+ * write shape appeared on an element inside the app container.
56
+ * - **A measurement coerced to a string before use** (`String(x)`, `toFixed`)
57
+ * still yields `"NaN"` and is still caught; one coerced with `|| 0` or
58
+ * `Number.isNaN` guards is not, by construction — that is the author opting
59
+ * out.
60
+ * - **Only inline styles are stripped.** A measurement written to an attribute
61
+ * or to `textContent` would render a literal `NaN`. No component does that
62
+ * today, but the strip would need extending if one did.
63
+ *
64
+ * @module server/layout-taint
65
+ */
66
+ /** Layout accessors: answered by a layout engine, absent on the server. */
67
+ const LAYOUT_NUMBER_PROPS = [
68
+ 'offsetWidth',
69
+ 'offsetHeight',
70
+ 'offsetTop',
71
+ 'offsetLeft',
72
+ 'clientWidth',
73
+ 'clientHeight',
74
+ 'clientTop',
75
+ 'clientLeft',
76
+ 'scrollWidth',
77
+ 'scrollHeight',
78
+ ];
79
+ /**
80
+ * A rect whose every field is tainted, and which is safe to coerce.
81
+ *
82
+ * Symbol keys answer `undefined` on purpose. A trap that returned `NaN` for
83
+ * *every* key handed back a number for `Symbol.toPrimitive`, so `${rect}` tried
84
+ * to call it: `TypeError: number NaN is not a function`. During SSR that throw
85
+ * is caught by the renderer and the component's subtree is dropped — the silent
86
+ * component loss this module exists to prevent, reintroduced for the stringify
87
+ * idiom. With symbols absent, coercion falls back to `toString`/`valueOf`, both
88
+ * of which are provided and both of which stay tainted.
89
+ */
90
+ function taintedRect() {
91
+ return new Proxy({}, {
92
+ get(_target, key) {
93
+ if (typeof key === 'symbol')
94
+ return undefined;
95
+ if (key === 'toJSON')
96
+ return () => ({});
97
+ if (key === 'toString')
98
+ return () => 'NaN';
99
+ if (key === 'valueOf')
100
+ return () => Number.NaN;
101
+ return Number.NaN;
102
+ },
103
+ });
104
+ }
105
+ /**
106
+ * Replace layout accessors on a happy-dom window with tainted (`NaN`) versions.
107
+ *
108
+ * @param window - The happy-dom window whose prototypes to patch.
109
+ * @returns A function restoring the original accessors.
110
+ */
111
+ /** @codexApi {"parent":"pithy.ssr.layout-taint","name":"installLayoutTaint","stability":"experimental","signature":"(window: unknown) => () => void"} */
112
+ export function installLayoutTaint(window) {
113
+ const w = window;
114
+ const restores = [];
115
+ const elementProto = w.Element?.prototype;
116
+ const htmlProto = w.HTMLElement?.prototype;
117
+ // `offsetParent === null` is the platform's own "this element has no box"
118
+ // signal — it is what a browser reports for a `display: none` subtree, and
119
+ // well-written components already branch on it to skip positioning. On a
120
+ // server *nothing* has a box, so answering `null` is not a trick: it is the
121
+ // truthful answer, and it routes components down the path they already have
122
+ // for the unrendered case.
123
+ if (htmlProto) {
124
+ const original = Object.getOwnPropertyDescriptor(htmlProto, 'offsetParent');
125
+ Object.defineProperty(htmlProto, 'offsetParent', {
126
+ configurable: true,
127
+ get: () => null,
128
+ });
129
+ restores.push(() => {
130
+ if (original)
131
+ Object.defineProperty(htmlProto, 'offsetParent', original);
132
+ else
133
+ delete htmlProto.offsetParent;
134
+ });
135
+ }
136
+ for (const prop of LAYOUT_NUMBER_PROPS) {
137
+ for (const proto of [htmlProto, elementProto]) {
138
+ if (!proto)
139
+ continue;
140
+ const original = Object.getOwnPropertyDescriptor(proto, prop);
141
+ if (!original)
142
+ continue;
143
+ Object.defineProperty(proto, prop, {
144
+ configurable: true,
145
+ get: () => Number.NaN,
146
+ });
147
+ restores.push(() => Object.defineProperty(proto, prop, original));
148
+ }
149
+ }
150
+ // `getBoundingClientRect()` always returns a rect, so every field of it is a
151
+ // measurement and the whole object is tainted.
152
+ const rectProto = elementProto;
153
+ if (rectProto && typeof rectProto.getBoundingClientRect === 'function') {
154
+ const original = rectProto.getBoundingClientRect;
155
+ rectProto.getBoundingClientRect = () => taintedRect();
156
+ restores.push(() => {
157
+ rectProto.getBoundingClientRect = original;
158
+ });
159
+ }
160
+ // `getClientRects()` answers a length of **0** — the truthful "no boxes" count
161
+ // and the second standard "am I rendered?" idiom after `offsetParent`, so
162
+ // `rects.length === 0` keeps working.
163
+ //
164
+ // Indexing still yields a tainted rect rather than `undefined`, which is
165
+ // deliberately inconsistent with that length. A browser really does return an
166
+ // empty list here, so `rects[0].width` throws there too — but a throw during
167
+ // SSR is caught by the renderer, which drops the component's whole subtree.
168
+ // Silent component loss is the exact failure this module exists to prevent, so
169
+ // an unguarded index degrades to `NaN` (and gets stripped) instead of taking
170
+ // the page down with it.
171
+ if (rectProto && typeof rectProto.getClientRects === 'function') {
172
+ const original = rectProto.getClientRects;
173
+ const emptyish = new Proxy({ length: 0 }, {
174
+ get(target, key) {
175
+ if (key === 'length')
176
+ return 0;
177
+ if (key === 'item')
178
+ return () => null;
179
+ if (key === Symbol.iterator)
180
+ return function* () { };
181
+ if (typeof key === 'string' && /^\d+$/.test(key))
182
+ return taintedRect();
183
+ return Reflect.get(target, key);
184
+ },
185
+ });
186
+ rectProto.getClientRects = () => emptyish;
187
+ restores.push(() => {
188
+ rectProto.getClientRects = original;
189
+ });
190
+ }
191
+ return () => {
192
+ for (const restore of restores)
193
+ restore();
194
+ };
195
+ }
196
+ /**
197
+ * Does this declaration value carry the taint?
198
+ *
199
+ * `NaN` inside a quoted string is a literal an author wrote (`content: "NaN"`),
200
+ * not a measurement, so it is left alone.
201
+ */
202
+ function isTaintedValue(value) {
203
+ return value.replace(/"[^"]*"|'[^']*'/g, '').includes('NaN');
204
+ }
205
+ /**
206
+ * Remove measurement-derived declarations from a rendered tree, **before** it is
207
+ * serialized.
208
+ *
209
+ * ## Why this operates on the DOM, not the HTML string
210
+ *
211
+ * An earlier version regex-matched `style="…"` in the serialized output. That
212
+ * cannot tell an element's style attribute from the same characters appearing
213
+ * anywhere else — inside an inline `<script>`, or in app-authored markup — and
214
+ * `renderToString()` accepts arbitrary application content, so the failure mode
215
+ * was silent output corruption. Walking real elements removes that whole class:
216
+ * a declaration is only ever dropped from an actual `CSSStyleDeclaration`.
217
+ *
218
+ * @param root - Container whose subtree to clean. The root itself is included.
219
+ * @param onDrop - Called with each dropped `prop: value`, so the caller can
220
+ * report it. Silence is the failure mode: a style vanishing without a trace is
221
+ * what makes a stray `NaN` hard to explain later.
222
+ */
223
+ /** @codexApi {"parent":"pithy.ssr.layout-taint","name":"stripTaintedStyles","stability":"experimental","signature":"(root: Element, onDrop?: (declaration: string) => void) => void"} */
224
+ export function stripTaintedStyles(root, onDrop) {
225
+ const scope = root.hasAttribute?.('style')
226
+ ? [root, ...Array.from(root.querySelectorAll('[style]'))]
227
+ : Array.from(root.querySelectorAll('[style]'));
228
+ for (const element of scope) {
229
+ const style = element.style;
230
+ if (!style)
231
+ continue;
232
+ // Snapshot first: removing a property mutates the live index.
233
+ const properties = [];
234
+ for (let i = 0; i < style.length; i += 1) {
235
+ const name = style.item(i);
236
+ if (name)
237
+ properties.push(name);
238
+ }
239
+ for (const name of properties) {
240
+ const value = style.getPropertyValue(name);
241
+ if (!isTaintedValue(value))
242
+ continue;
243
+ onDrop?.(`${name}: ${value.trim()}`);
244
+ style.removeProperty(name);
245
+ }
246
+ // happy-dom keeps an empty `style=""`; a browser-shaped tree would not.
247
+ if (style.length === 0)
248
+ element.removeAttribute('style');
249
+ }
250
+ }
251
+ /**
252
+ * Geometry properties whose value is almost always a measurement when written
253
+ * inline. A legitimate `inline-size: 0px` in *static* output is vanishingly
254
+ * rare; a laundered measurement is the likely explanation.
255
+ */
256
+ const GEOMETRY_PROPERTIES = [
257
+ 'inline-size',
258
+ 'block-size',
259
+ 'width',
260
+ 'height',
261
+ 'inset-inline-start',
262
+ 'inset-block-start',
263
+ '--app-header-offset',
264
+ ];
265
+ // `top` and `left` are deliberately absent. `style="top: 0; left: 0"` is the
266
+ // ordinary absolutely-positioned-overlay idiom, hand-written and legitimate, and
267
+ // it appears often enough that including it drowned the genuine laundered-`0px`
268
+ // hit this detector exists to surface.
269
+ /**
270
+ * `prop: 0px` / `prop: 0` / `transform: translateX(0px)` and friends.
271
+ *
272
+ * The property must start at a declaration boundary. Without that anchor,
273
+ * `width` matches inside `min-width: 0` — the standard flexbox idiom, written by
274
+ * hand and entirely legitimate — which the first real build promptly flagged.
275
+ */
276
+ const SUSPICIOUS_ZERO = new RegExp(`(?:^|;)\\s*(?:(?:${GEOMETRY_PROPERTIES.map(p => p.replace(/-/g, '\\-')).join('|')})\\s*:\\s*0(?:px)?\\s*(?=;|"|$)` +
277
+ `|transform\\s*:\\s*translate[XY]?\\(\\s*0(?:px)?\\s*(?:,\\s*0(?:px)?\\s*)?\\))`, 'g');
278
+ /**
279
+ * Find zero-valued geometry in emitted HTML — the fingerprint of a measurement
280
+ * that escaped the taint.
281
+ *
282
+ * ## Why a detector and not a fix
283
+ *
284
+ * {@link installLayoutTaint} makes a measurement self-identifying, but a
285
+ * *comparison* can launder it back to a clean number: `publishHeaderOffset`
286
+ * reduces with `if (height > tallest)`, and `NaN > 0` is false, so `tallest`
287
+ * stays `0` and a perfectly ordinary `0px` is written. Nothing in the output
288
+ * distinguishes that from a legitimate zero, and comparison semantics cannot be
289
+ * changed — so the hole cannot be closed, only watched.
290
+ *
291
+ * This is deliberately a **heuristic**. It reports rather than throws, because a
292
+ * genuine zero is possible and failing a build on a guess is worse than the bug
293
+ * it guards.
294
+ *
295
+ * @param html - Serialized HTML for one page.
296
+ * @returns The suspicious declarations found, in document order.
297
+ */
298
+ /** @codexApi {"parent":"pithy.ssr.layout-taint","name":"findSuspiciousGeometry","stability":"experimental","signature":"(html: string) => string[]"} */
299
+ export function findSuspiciousGeometry(html) {
300
+ const found = [];
301
+ for (const match of html.matchAll(/style="([^"]*)"/g)) {
302
+ const body = match[1];
303
+ if (!body)
304
+ continue;
305
+ for (const hit of body.matchAll(SUSPICIOUS_ZERO)) {
306
+ const declaration = hit[0].replace(/^[;\s]+/, '').trim();
307
+ if (declaration)
308
+ found.push(declaration);
309
+ }
310
+ }
311
+ return found;
312
+ }
313
+ //# sourceMappingURL=layout-taint.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"layout-taint.js","sourceRoot":"","sources":["../../src/server/layout-taint.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwDG;AAEH,2EAA2E;AAC3E,MAAM,mBAAmB,GAAG;IAC1B,aAAa;IACb,cAAc;IACd,WAAW;IACX,YAAY;IACZ,aAAa;I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BAAmB,GAAG;IAC1B,aAAa;IACb,YAAY;IACZ,OAAO;IACP,QAAQ;IACR,oBAAoB;IACpB,mBAAmB;IACnB,qBAAqB;CACtB,CAAC;AAEF,6EAA6E;AAC7E,iFAAiF;AACjF,gFAAgF;AAChF,uCAAuC;AAEvC;;;;;;GAMG;AACH,MAAM,eAAe,GAAG,IAAI,MAAM,CAChC,oBAAoB,mBAAmB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,iCAAiC;IACjH,gFAAgF,EAClF,GAAG,CACJ,CAAC;AAEF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wJAAwJ;AACxJ,MAAM,UAAU,sBAAsB,CAAC,IAAY;IACjD,MAAM,KAAK,GAAa,EAAE,CAAC;IAE3B,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,QAAQ,CAAC,kBAAkB,CAAC,EAAE,CAAC;QACtD,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QACtB,IAAI,CAAC,IAAI;YAAE,SAAS;QACpB,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC,EAAE,CAAC;YACjD,MAAM,WAAW,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;YACzD,IAAI,WAAW;gBAAE,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAC3C,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.ssr.layout-taint\",\n \"title\": \"Layout Taint (server-only)\",\n \"category\": \"runtime\",\n \"risk\": \"high\"\n}\n*/\n\n/**\n * Make unmeasurable layout *unmistakable*, so components never need to know\n * they are being rendered on a server.\n *\n * ## The problem this replaces\n *\n * A server DOM has no layout engine, so `offsetWidth` and\n * `getBoundingClientRect()` do not throw — they return **0**. Zero is a\n * plausible answer, so a component writes it straight into an inline style and\n * ships a broken value (`inline-size: 0px` on a tab indicator renders it\n * invisible, and nothing re-runs to correct it).\n *\n * The only fixes available at the call site are guards, which means every author\n * of every component has to know that static rendering exists.\n *\n * ## The idea\n *\n * Return `NaN` instead of `0`, and strip what it touches on the way out.\n *\n * `NaN` is the one value in JavaScript that **propagates through arithmetic**:\n * `offsetLeft - clientWidth + offsetWidth` is `NaN` if any input is. So a\n * measurement taints every value derived from it, however many steps later, with\n * no tracking machinery. When such a value reaches the DOM it lands in the\n * markup as the literal `NaN` — `inline-size: NaNpx` — which\n * {@link stripTaintedStyles} then removes.\n *\n * The result is that a component measures freely, writes freely, and the\n * measurement-derived writes simply never reach the output.\n *\n * ## What this does NOT change\n *\n * Only *layout* accessors are tainted. Reading a CSS **value** (a custom\n * property, `direction`) is genuinely correct on the server, and stays correct.\n *\n * ## Known limits\n *\n * - **Comparisons against NaN are always false.** Code branching on\n * `rect.height === 0` takes the other branch server-side. That path was\n * already meaningless (it was comparing against a fabricated zero), but it is\n * a behaviour change, not a no-op.\n * - **A comparison can launder the taint.** `publishHeaderOffset` reduces with\n * `if (height > tallest) tallest = height`; `NaN > 0` is false, so `tallest`\n * stays `0` and a clean `0px` is written. Verified latent rather than live:\n * that value lands on `documentElement`, and the static shell builds its own\n * `<html>` element, so it is never serialized. It would become real if the\n * shell ever emitted `documentElement`'s style, or if the same reduce-then-\n * write shape appeared on an element inside the app container.\n * - **A measurement coerced to a string before use** (`String(x)`, `toFixed`)\n * still yields `\"NaN\"` and is still caught; one coerced with `|| 0` or\n * `Number.isNaN` guards is not, by construction — that is the author opting\n * out.\n * - **Only inline styles are stripped.** A measurement written to an attribute\n * or to `textContent` would render a literal `NaN`. No component does that\n * today, but the strip would need extending if one did.\n *\n * @module server/layout-taint\n */\n\n/** Layout accessors: answered by a layout engine, absent on the server. */\nconst LAYOUT_NUMBER_PROPS = [\n 'offsetWidth',\n 'offsetHeight',\n 'offsetTop',\n 'offsetLeft',\n 'clientWidth',\n 'clientHeight',\n 'clientTop',\n 'clientLeft',\n 'scrollWidth',\n 'scrollHeight',\n] as const;\n\n/** Restores installed by {@link installLayoutTaint}, applied on teardown. */\ntype Restore = () => void;\n\n/**\n * A rect whose every field is tainted, and which is safe to coerce.\n *\n * Symbol keys answer `undefined` on purpose. A trap that returned `NaN` for\n * *every* key handed back a number for `Symbol.toPrimitive`, so `${rect}` tried\n * to call it: `TypeError: number NaN is not a function`. During SSR that throw\n * is caught by the renderer and the component's subtree is dropped — the silent\n * component loss this module exists to prevent, reintroduced for the stringify\n * idiom. With symbols absent, coercion falls back to `toString`/`valueOf`, both\n * of which are provided and both of which stay tainted.\n */\nfunction taintedRect(): object {\n return new Proxy(\n {},\n {\n get(_target, key) {\n if (typeof key === 'symbol') return undefined;\n if (key === 'toJSON') return () => ({});\n if (key === 'toString') return () => 'NaN';\n if (key === 'valueOf') return () => Number.NaN;\n return Number.NaN;\n },\n }\n );\n}\n\n/**\n * Replace layout accessors on a happy-dom window with tainted (`NaN`) versions.\n *\n * @param window - The happy-dom window whose prototypes to patch.\n * @returns A function restoring the original accessors.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.layout-taint\",\"name\":\"installLayoutTaint\",\"stability\":\"experimental\",\"signature\":\"(window: unknown) => () => void\"} */\nexport function installLayoutTaint(window: unknown): Restore {\n const w = window as Record<string, { prototype: object }>;\n const restores: Restore[] = [];\n\n const elementProto = w.Element?.prototype;\n const htmlProto = w.HTMLElement?.prototype;\n\n // `offsetParent === null` is the platform's own \"this element has no box\"\n // signal — it is what a browser reports for a `display: none` subtree, and\n // well-written components already branch on it to skip positioning. On a\n // server *nothing* has a box, so answering `null` is not a trick: it is the\n // truthful answer, and it routes components down the path they already have\n // for the unrendered case.\n if (htmlProto) {\n const original = Object.getOwnPropertyDescriptor(htmlProto, 'offsetParent');\n Object.defineProperty(htmlProto, 'offsetParent', {\n configurable: true,\n get: () => null,\n });\n restores.push(() => {\n if (original) Object.defineProperty(htmlProto, 'offsetParent', original);\n else delete (htmlProto as Record<string, unknown>).offsetParent;\n });\n }\n\n for (const prop of LAYOUT_NUMBER_PROPS) {\n for (const proto of [htmlProto, elementProto]) {\n if (!proto) continue;\n const original = Object.getOwnPropertyDescriptor(proto, prop);\n if (!original) continue;\n Object.defineProperty(proto, prop, {\n configurable: true,\n get: () => Number.NaN,\n });\n restores.push(() => Object.defineProperty(proto, prop, original));\n }\n }\n\n // `getBoundingClientRect()` always returns a rect, so every field of it is a\n // measurement and the whole object is tainted.\n const rectProto = elementProto as Record<string, unknown> | undefined;\n if (rectProto && typeof rectProto.getBoundingClientRect === 'function') {\n const original = rectProto.getBoundingClientRect;\n rectProto.getBoundingClientRect = () => taintedRect();\n restores.push(() => {\n rectProto.getBoundingClientRect = original;\n });\n }\n\n // `getClientRects()` answers a length of **0** — the truthful \"no boxes\" count\n // and the second standard \"am I rendered?\" idiom after `offsetParent`, so\n // `rects.length === 0` keeps working.\n //\n // Indexing still yields a tainted rect rather than `undefined`, which is\n // deliberately inconsistent with that length. A browser really does return an\n // empty list here, so `rects[0].width` throws there too — but a throw during\n // SSR is caught by the renderer, which drops the component's whole subtree.\n // Silent component loss is the exact failure this module exists to prevent, so\n // an unguarded index degrades to `NaN` (and gets stripped) instead of taking\n // the page down with it.\n if (rectProto && typeof rectProto.getClientRects === 'function') {\n const original = rectProto.getClientRects;\n const emptyish = new Proxy(\n { length: 0 },\n {\n get(target, key) {\n if (key === 'length') return 0;\n if (key === 'item') return () => null;\n if (key === Symbol.iterator) return function* () {};\n if (typeof key === 'string' && /^\\d+$/.test(key))\n return taintedRect();\n return Reflect.get(target, key);\n },\n }\n );\n rectProto.getClientRects = () => emptyish;\n restores.push(() => {\n rectProto.getClientRects = original;\n });\n }\n\n return () => {\n for (const restore of restores) restore();\n };\n}\n\n/**\n * Does this declaration value carry the taint?\n *\n * `NaN` inside a quoted string is a literal an author wrote (`content: \"NaN\"`),\n * not a measurement, so it is left alone.\n */\nfunction isTaintedValue(value: string): boolean {\n return value.replace(/\"[^\"]*\"|'[^']*'/g, '').includes('NaN');\n}\n\n/**\n * Remove measurement-derived declarations from a rendered tree, **before** it is\n * serialized.\n *\n * ## Why this operates on the DOM, not the HTML string\n *\n * An earlier version regex-matched `style=\"…\"` in the serialized output. That\n * cannot tell an element's style attribute from the same characters appearing\n * anywhere else — inside an inline `<script>`, or in app-authored markup — and\n * `renderToString()` accepts arbitrary application content, so the failure mode\n * was silent output corruption. Walking real elements removes that whole class:\n * a declaration is only ever dropped from an actual `CSSStyleDeclaration`.\n *\n * @param root - Container whose subtree to clean. The root itself is included.\n * @param onDrop - Called with each dropped `prop: value`, so the caller can\n * report it. Silence is the failure mode: a style vanishing without a trace is\n * what makes a stray `NaN` hard to explain later.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.layout-taint\",\"name\":\"stripTaintedStyles\",\"stability\":\"experimental\",\"signature\":\"(root: Element, onDrop?: (declaration: string) => void) => void\"} */\nexport function stripTaintedStyles(\n root: Element,\n onDrop?: (declaration: string) => void\n): void {\n const scope = root.hasAttribute?.('style')\n ? [root, ...Array.from(root.querySelectorAll('[style]'))]\n : Array.from(root.querySelectorAll('[style]'));\n\n for (const element of scope) {\n const style = (element as unknown as { style?: CSSStyleDeclaration }).style;\n if (!style) continue;\n\n // Snapshot first: removing a property mutates the live index.\n const properties: string[] = [];\n for (let i = 0; i < style.length; i += 1) {\n const name = style.item(i);\n if (name) properties.push(name);\n }\n\n for (const name of properties) {\n const value = style.getPropertyValue(name);\n if (!isTaintedValue(value)) continue;\n onDrop?.(`${name}: ${value.trim()}`);\n style.removeProperty(name);\n }\n\n // happy-dom keeps an empty `style=\"\"`; a browser-shaped tree would not.\n if (style.length === 0) element.removeAttribute('style');\n }\n}\n\n/**\n * Geometry properties whose value is almost always a measurement when written\n * inline. A legitimate `inline-size: 0px` in *static* output is vanishingly\n * rare; a laundered measurement is the likely explanation.\n */\nconst GEOMETRY_PROPERTIES = [\n 'inline-size',\n 'block-size',\n 'width',\n 'height',\n 'inset-inline-start',\n 'inset-block-start',\n '--app-header-offset',\n];\n\n// `top` and `left` are deliberately absent. `style=\"top: 0; left: 0\"` is the\n// ordinary absolutely-positioned-overlay idiom, hand-written and legitimate, and\n// it appears often enough that including it drowned the genuine laundered-`0px`\n// hit this detector exists to surface.\n\n/**\n * `prop: 0px` / `prop: 0` / `transform: translateX(0px)` and friends.\n *\n * The property must start at a declaration boundary. Without that anchor,\n * `width` matches inside `min-width: 0` — the standard flexbox idiom, written by\n * hand and entirely legitimate — which the first real build promptly flagged.\n */\nconst SUSPICIOUS_ZERO = new RegExp(\n `(?:^|;)\\\\s*(?:(?:${GEOMETRY_PROPERTIES.map(p => p.replace(/-/g, '\\\\-')).join('|')})\\\\s*:\\\\s*0(?:px)?\\\\s*(?=;|\"|$)` +\n `|transform\\\\s*:\\\\s*translate[XY]?\\\\(\\\\s*0(?:px)?\\\\s*(?:,\\\\s*0(?:px)?\\\\s*)?\\\\))`,\n 'g'\n);\n\n/**\n * Find zero-valued geometry in emitted HTML — the fingerprint of a measurement\n * that escaped the taint.\n *\n * ## Why a detector and not a fix\n *\n * {@link installLayoutTaint} makes a measurement self-identifying, but a\n * *comparison* can launder it back to a clean number: `publishHeaderOffset`\n * reduces with `if (height > tallest)`, and `NaN > 0` is false, so `tallest`\n * stays `0` and a perfectly ordinary `0px` is written. Nothing in the output\n * distinguishes that from a legitimate zero, and comparison semantics cannot be\n * changed — so the hole cannot be closed, only watched.\n *\n * This is deliberately a **heuristic**. It reports rather than throws, because a\n * genuine zero is possible and failing a build on a guess is worse than the bug\n * it guards.\n *\n * @param html - Serialized HTML for one page.\n * @returns The suspicious declarations found, in document order.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.layout-taint\",\"name\":\"findSuspiciousGeometry\",\"stability\":\"experimental\",\"signature\":\"(html: string) => string[]\"} */\nexport function findSuspiciousGeometry(html: string): string[] {\n const found: string[] = [];\n\n for (const match of html.matchAll(/style=\"([^\"]*)\"/g)) {\n const body = match[1];\n if (!body) continue;\n for (const hit of body.matchAll(SUSPICIOUS_ZERO)) {\n const declaration = hit[0].replace(/^[;\\s]+/, '').trim();\n if (declaration) found.push(declaration);\n }\n }\n\n return found;\n}\n"]}
@@ -0,0 +1,194 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.ssr.server.loaders",
4
+ "title": "SSR Loader Execution",
5
+ "category": "runtime"
6
+ }
7
+ */
8
+ /**
9
+ * @pithyjs/ssr - SSR Loader Execution
10
+ *
11
+ * Executes route loaders during server-side rendering and serializes
12
+ * loader data for client hydration.
13
+ */
14
+ import { type LoaderFunction, type LoaderContext, type RouteNode, type CacheOptions } from '@pithyjs/router';
15
+ export { serializeLoaderData, deserializeLoaderData, type SerializedLoaderData, } from './serialization.js';
16
+ /**
17
+ * Route segment with loader information for SSR execution
18
+ */
19
+ export interface SSRRouteSegment {
20
+ /** Unique route segment ID */
21
+ id: string;
22
+ /** Loader function (if present) */
23
+ loader?: LoaderFunction;
24
+ /** Cache options for this loader */
25
+ cacheOptions?: SSRLoaderCacheOptions;
26
+ }
27
+ /**
28
+ * Cache options for SSR loaders (extends router CacheOptions with HTTP-specific fields)
29
+ */
30
+ export interface SSRLoaderCacheOptions extends CacheOptions {
31
+ /** Whether response can be cached by CDN (public vs private) */
32
+ public?: boolean;
33
+ /** Stale-while-revalidate window in seconds (for HTTP header) */
34
+ swr?: number;
35
+ }
36
+ /**
37
+ * Options for SSR loader execution
38
+ */
39
+ export interface ExecuteLoadersOptions {
40
+ /** Route segments to execute loaders for */
41
+ segments: SSRRouteSegment[];
42
+ /** Route parameters */
43
+ params: Record<string, string>;
44
+ /** Query parameters */
45
+ query: Record<string, string>;
46
+ /** Timeout in milliseconds (default: 30000) */
47
+ timeout?: number;
48
+ /** Abort signal for cancellation */
49
+ signal?: AbortSignal;
50
+ /** Whether to continue on loader error (default: false) */
51
+ continueOnError?: boolean;
52
+ }
53
+ /**
54
+ * Result from executing a single loader
55
+ */
56
+ export interface SSRLoaderResult<T = unknown> {
57
+ /** Route segment ID */
58
+ id: string;
59
+ /** Whether loader succeeded */
60
+ success: boolean;
61
+ /** Loader data (if successful) */
62
+ data?: T;
63
+ /** Error (if failed) */
64
+ error?: SSRLoaderError;
65
+ /** Execution time in milliseconds */
66
+ timing: number;
67
+ /** Cache hints from loader config */
68
+ cacheHints?: SSRCacheHints;
69
+ }
70
+ /**
71
+ * Loader error details
72
+ */
73
+ export interface SSRLoaderError {
74
+ /** Error message */
75
+ message: string;
76
+ /** Error name/type */
77
+ name: string;
78
+ /** Stack trace (in development) */
79
+ stack?: string;
80
+ /** Whether this was a timeout */
81
+ isTimeout: boolean;
82
+ /** Whether this was an abort */
83
+ isAborted: boolean;
84
+ }
85
+ /**
86
+ * Cache hints for HTTP headers
87
+ */
88
+ export interface SSRCacheHints {
89
+ /** Cache-Control: public or private */
90
+ public: boolean;
91
+ /** Max-age in seconds */
92
+ maxAge: number;
93
+ /** Stale-while-revalidate in seconds */
94
+ swr?: number;
95
+ /** Whether to skip cache entirely */
96
+ noStore: boolean;
97
+ }
98
+ /**
99
+ * Result from executeSSRLoaders
100
+ */
101
+ export interface ExecuteLoadersResult {
102
+ /** All loader results */
103
+ results: SSRLoaderResult[];
104
+ /** Combined loader data (keyed by segment ID) */
105
+ loaderData: Record<string, unknown>;
106
+ /** Whether all loaders succeeded */
107
+ success: boolean;
108
+ /** First error encountered (if any) */
109
+ firstError?: SSRLoaderError;
110
+ /** Total execution time in milliseconds */
111
+ totalTiming: number;
112
+ /** Aggregated cache hints (most restrictive wins) */
113
+ cacheHints: SSRCacheHints;
114
+ }
115
+ /** @codexApi {"parent":"pithy.ssr.server.loaders","name":"executeSSRLoaders","stability":"stable","signature":"(options: ExecuteLoadersOptions) => Promise<ExecuteLoadersResult>"} */
116
+ /**
117
+ * Execute loaders for route segments during SSR
118
+ *
119
+ * Loaders are executed in sequence (parent to child) to allow parent
120
+ * loader data to potentially inform child loaders.
121
+ *
122
+ * @param options - Loader execution options
123
+ * @returns Result containing loader data and status
124
+ *
125
+ * @example
126
+ * ```ts
127
+ * const result = await executeSSRLoaders({
128
+ * segments: [
129
+ * { id: 'root', loader: rootLoader },
130
+ * { id: 'dashboard', loader: dashboardLoader }
131
+ * ],
132
+ * params: { id: '123' },
133
+ * query: { tab: 'settings' }
134
+ * });
135
+ *
136
+ * if (result.success) {
137
+ * console.log('All loaders succeeded:', result.loaderData);
138
+ * }
139
+ * ```
140
+ */
141
+ export declare function executeSSRLoaders(options: ExecuteLoadersOptions): Promise<ExecuteLoadersResult>;
142
+ /** @codexApi {"parent":"pithy.ssr.server.loaders","name":"createSSRLoaderContext","stability":"stable","signature":"(options: { params: Record<string, string>; query: Record<string, string>; signal?: AbortSignal }) => LoaderContext"} */
143
+ /**
144
+ * Create a LoaderContext for SSR execution
145
+ *
146
+ * @param options - Context options
147
+ * @returns LoaderContext compatible with router loaders
148
+ *
149
+ * @example
150
+ * ```ts
151
+ * const context = createSSRLoaderContext({
152
+ * params: { id: '123' },
153
+ * query: { filter: 'active' }
154
+ * });
155
+ * const data = await myLoader(context);
156
+ * ```
157
+ */
158
+ export declare function createSSRLoaderContext(options: {
159
+ params: Record<string, string>;
160
+ query: Record<string, string>;
161
+ signal?: AbortSignal;
162
+ }): LoaderContext;
163
+ /** @codexApi {"parent":"pithy.ssr.server.loaders","name":"generateCacheControlHeader","stability":"stable","signature":"(hints: SSRCacheHints) => string"} */
164
+ /**
165
+ * Generate Cache-Control header value from cache hints
166
+ *
167
+ * @param hints - Aggregated cache hints
168
+ * @returns Cache-Control header value
169
+ *
170
+ * @example
171
+ * ```ts
172
+ * const cacheControl = generateCacheControlHeader(result.cacheHints);
173
+ * res.setHeader('Cache-Control', cacheControl);
174
+ * ```
175
+ */
176
+ export declare function generateCacheControlHeader(hints: SSRCacheHints): string;
177
+ /** @codexApi {"parent":"pithy.ssr.server.loaders","name":"extractLoadersFromRouteTree","stability":"stable","signature":"(nodes: RouteNode[], matchedPath: string[]) => Promise<SSRRouteSegment[]>"} */
178
+ /**
179
+ * Extract loader segments from matched route nodes
180
+ *
181
+ * Handles both nested route trees AND flat manifests (where all routes are
182
+ * at the top level with full path patterns like `/dashboard/settings`).
183
+ *
184
+ * @param nodes - Route nodes (may be flat or nested)
185
+ * @param matchedPath - Matched path segments (e.g., ['dashboard', 'settings'])
186
+ * @returns Array of route segments with loaders (parent to child order)
187
+ *
188
+ * @example
189
+ * ```ts
190
+ * const segments = await extractLoadersFromRouteTree(routes, ['dashboard', 'settings']);
191
+ * ```
192
+ */
193
+ export declare function extractLoadersFromRouteTree(nodes: RouteNode[], matchedPath: string[]): Promise<SSRRouteSegment[]>;
194
+ //# sourceMappingURL=loaders.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loaders.d.ts","sourceRoot":"","sources":["../../src/server/loaders.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;GAKG;AAEH,OAAO,EAGL,KAAK,cAAc,EACnB,KAAK,aAAa,EAClB,KAAK,SAAS,EACd,KAAK,YAAY,EAClB,MAAM,iBAAiB,CAAC;AASzB,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,KAAK,oBAAoB,GAC1B,MAAM,oBAAoB,CAAC;AAM5B;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,8BAA8B;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,mCAAmC;IACnC,MAAM,CAAC,EAAE,cAAc,CAAC;IACxB,oCAAoC;IACpC,YAAY,CAAC,EAAE,qBAAqB,CAAC;CACtC;AAED;;GAEG;AACH,MAAM,WAAW,qBAAsB,SAAQ,YAAY;IACzD,gEAAgE;IAChE,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,iEAAiE;IACjE,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC,4CAA4C;IAC5C,QAA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