@conloca/astro-cms 0.1.14 → 0.1.16

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 (164) hide show
  1. package/README.md +65 -5
  2. package/dist/collections-Bd7EME4b.mjs +129 -0
  3. package/dist/collections-Bd7EME4b.mjs.map +1 -0
  4. package/dist/collections.d.mts +3 -3
  5. package/dist/collections.d.mts.map +1 -1
  6. package/dist/collections.mjs +2 -56
  7. package/dist/components.d.mts +6 -31
  8. package/dist/components.d.mts.map +1 -1
  9. package/dist/components.mjs +100 -45
  10. package/dist/components.mjs.map +1 -1
  11. package/dist/hydration.d.mts +2 -2
  12. package/dist/hydration.mjs +2 -3
  13. package/dist/index.d.mts +12 -88
  14. package/dist/index.d.mts.map +1 -1
  15. package/dist/index.mjs +19 -797
  16. package/dist/index.mjs.map +1 -1
  17. package/dist/internal/acorn-default.mjs +29 -0
  18. package/dist/{cms-handler.d.mts → internal/cms-handler.d.mts} +0 -1
  19. package/dist/internal/cms-handler.d.mts.map +1 -0
  20. package/dist/{cms-handler.mjs → internal/cms-handler.mjs} +57 -8
  21. package/dist/internal/cms-handler.mjs.map +1 -0
  22. package/dist/internal/page-handler.astro +541 -0
  23. package/dist/lib/hydration-script.d.mts +1 -2
  24. package/dist/lib/hydration-script.d.mts.map +1 -1
  25. package/dist/lib/hydration-script.mjs +1 -2
  26. package/dist/lib/hydration-script.mjs.map +1 -1
  27. package/dist/locales-helpers-BvYYqnJ5.d.mts +64 -0
  28. package/dist/locales-helpers-BvYYqnJ5.d.mts.map +1 -0
  29. package/dist/locales-helpers-qiwh7nxS.mjs +54 -0
  30. package/dist/locales-helpers-qiwh7nxS.mjs.map +1 -0
  31. package/dist/node/content.d.mts +18 -0
  32. package/dist/node/content.d.mts.map +1 -0
  33. package/dist/node/content.d.ts +3 -0
  34. package/dist/node/content.d.ts.map +1 -0
  35. package/dist/node/content.js +2 -0
  36. package/dist/node/content.mjs +2 -0
  37. package/dist/node/index.d.mts +200 -0
  38. package/dist/node/index.d.mts.map +1 -0
  39. package/dist/node/index.d.ts +4 -0
  40. package/dist/node/index.d.ts.map +1 -0
  41. package/dist/node/index.js +3 -0
  42. package/dist/node/index.mjs +2513 -0
  43. package/dist/node/index.mjs.map +1 -0
  44. package/dist/{serialize-props-DqfDQeFl.mjs → serialize-props-BHoNpzH6.mjs} +4 -5
  45. package/dist/{serialize-props-DqfDQeFl.mjs.map → serialize-props-BHoNpzH6.mjs.map} +1 -1
  46. package/dist/src/cms-handler.d.ts +19 -0
  47. package/dist/src/cms-handler.d.ts.map +1 -0
  48. package/dist/src/cms-handler.js +366 -0
  49. package/dist/src/collections.d.ts +32 -0
  50. package/dist/src/collections.d.ts.map +1 -0
  51. package/dist/src/collections.js +50 -0
  52. package/dist/src/components/HydrationWrapper.d.ts +18 -0
  53. package/dist/src/components/HydrationWrapper.d.ts.map +1 -0
  54. package/dist/src/components/HydrationWrapper.js +21 -0
  55. package/dist/src/components/RenderWithBlocks.d.ts +23 -0
  56. package/dist/src/components/RenderWithBlocks.d.ts.map +1 -0
  57. package/dist/src/components/RenderWithBlocks.js +129 -0
  58. package/dist/src/components/RenderWithHydration.d.ts +17 -0
  59. package/dist/src/components/RenderWithHydration.d.ts.map +1 -0
  60. package/dist/src/components/RenderWithHydration.js +36 -0
  61. package/dist/src/components.d.ts +4 -0
  62. package/dist/src/components.d.ts.map +1 -0
  63. package/dist/src/components.js +3 -0
  64. package/dist/src/discovery/astro-frontmatter.d.ts +18 -0
  65. package/dist/src/discovery/astro-frontmatter.d.ts.map +1 -0
  66. package/dist/src/discovery/astro-frontmatter.js +24 -0
  67. package/dist/src/discovery/extract-props-ts.d.ts +41 -0
  68. package/dist/src/discovery/extract-props-ts.d.ts.map +1 -0
  69. package/dist/src/discovery/extract-props-ts.js +231 -0
  70. package/dist/src/discovery/merge-registry.d.ts +58 -0
  71. package/dist/src/discovery/merge-registry.d.ts.map +1 -0
  72. package/dist/src/discovery/merge-registry.js +332 -0
  73. package/dist/src/discovery/registry-endpoint.d.ts +42 -0
  74. package/dist/src/discovery/registry-endpoint.d.ts.map +1 -0
  75. package/dist/src/discovery/registry-endpoint.js +81 -0
  76. package/dist/src/discovery/scan-components.d.ts +98 -0
  77. package/dist/src/discovery/scan-components.d.ts.map +1 -0
  78. package/dist/src/discovery/scan-components.js +399 -0
  79. package/dist/src/discovery/scan-mdx.d.ts +63 -0
  80. package/dist/src/discovery/scan-mdx.d.ts.map +1 -0
  81. package/dist/src/discovery/scan-mdx.js +112 -0
  82. package/dist/src/discovery/scan-overrides.d.ts +71 -0
  83. package/dist/src/discovery/scan-overrides.d.ts.map +1 -0
  84. package/dist/src/discovery/scan-overrides.js +33 -0
  85. package/dist/src/hydration.d.ts +4 -0
  86. package/dist/src/hydration.d.ts.map +1 -0
  87. package/dist/src/hydration.js +4 -0
  88. package/dist/src/index.d.ts +11 -0
  89. package/dist/src/index.d.ts.map +1 -0
  90. package/dist/src/index.js +25 -0
  91. package/dist/src/lib/hydration-scanner.d.ts +47 -0
  92. package/dist/src/lib/hydration-scanner.d.ts.map +1 -0
  93. package/dist/src/lib/hydration-scanner.js +135 -0
  94. package/dist/src/lib/hydration-script.d.ts +28 -0
  95. package/dist/src/lib/hydration-script.d.ts.map +1 -0
  96. package/dist/src/lib/hydration-script.js +88 -0
  97. package/dist/src/lib/hydration-utils.d.ts +51 -0
  98. package/dist/src/lib/hydration-utils.d.ts.map +1 -0
  99. package/dist/src/lib/hydration-utils.js +83 -0
  100. package/dist/src/lib/page-api.d.ts +77 -0
  101. package/dist/src/lib/page-api.d.ts.map +1 -0
  102. package/dist/src/lib/page-api.js +121 -0
  103. package/dist/src/lib/route-utils.d.ts +41 -0
  104. package/dist/src/lib/route-utils.d.ts.map +1 -0
  105. package/dist/src/lib/route-utils.js +78 -0
  106. package/dist/src/lib/routing-config.d.ts +32 -0
  107. package/dist/src/lib/routing-config.d.ts.map +1 -0
  108. package/dist/src/lib/routing-config.js +93 -0
  109. package/dist/src/lib/serialize-props.d.ts +6 -0
  110. package/dist/src/lib/serialize-props.d.ts.map +1 -0
  111. package/dist/src/lib/serialize-props.js +7 -0
  112. package/dist/src/lib/virtual-module-generators.d.ts +57 -0
  113. package/dist/src/lib/virtual-module-generators.d.ts.map +1 -0
  114. package/dist/src/lib/virtual-module-generators.js +263 -0
  115. package/dist/src/lib/withHydration.d.ts +51 -0
  116. package/dist/src/lib/withHydration.d.ts.map +1 -0
  117. package/dist/src/lib/withHydration.js +49 -0
  118. package/dist/src/loader.d.ts +14 -0
  119. package/dist/src/loader.d.ts.map +1 -0
  120. package/dist/src/loader.js +89 -0
  121. package/dist/src/locales-helpers.d.ts +61 -0
  122. package/dist/src/locales-helpers.d.ts.map +1 -0
  123. package/dist/src/locales-helpers.js +49 -0
  124. package/dist/src/mime-types.d.ts +3 -0
  125. package/dist/src/mime-types.d.ts.map +1 -0
  126. package/dist/src/mime-types.js +19 -0
  127. package/dist/src/path-validation.d.ts +8 -0
  128. package/dist/src/path-validation.d.ts.map +1 -0
  129. package/dist/src/path-validation.js +12 -0
  130. package/dist/src/plugin-spa.d.ts +164 -0
  131. package/dist/src/plugin-spa.d.ts.map +1 -0
  132. package/dist/src/plugin-spa.js +972 -0
  133. package/dist/src/safe-json-stringify.d.ts +13 -0
  134. package/dist/src/safe-json-stringify.d.ts.map +1 -0
  135. package/dist/src/safe-json-stringify.js +6 -0
  136. package/dist/src/site-styles/content-wrapper-endpoint.d.ts +76 -0
  137. package/dist/src/site-styles/content-wrapper-endpoint.d.ts.map +1 -0
  138. package/dist/src/site-styles/content-wrapper-endpoint.js +227 -0
  139. package/dist/src/site-styles/render-endpoint.d.ts +55 -0
  140. package/dist/src/site-styles/render-endpoint.d.ts.map +1 -0
  141. package/dist/src/site-styles/render-endpoint.js +263 -0
  142. package/dist/src/site-styles/styles-endpoint.d.ts +61 -0
  143. package/dist/src/site-styles/styles-endpoint.d.ts.map +1 -0
  144. package/dist/src/site-styles/styles-endpoint.js +158 -0
  145. package/dist/src/types.d.ts +627 -0
  146. package/dist/src/types.d.ts.map +1 -0
  147. package/dist/src/types.js +1 -0
  148. package/dist/{types-Bsd_qENn.d.mts → types-CS9neadI.d.mts} +193 -3
  149. package/dist/types-CS9neadI.d.mts.map +1 -0
  150. package/dist/virtual-modules.d.ts +155 -0
  151. package/dist/{withHydration-692fMySA.mjs → withHydration-C256ox_6.mjs} +6 -2
  152. package/dist/withHydration-C256ox_6.mjs.map +1 -0
  153. package/dist/{withHydration-BGgQDE-H.d.mts → withHydration-DkKpkmzJ.d.mts} +5 -2
  154. package/dist/withHydration-DkKpkmzJ.d.mts.map +1 -0
  155. package/package.json +106 -40
  156. package/dist/cms-handler.d.mts.map +0 -1
  157. package/dist/cms-handler.mjs.map +0 -1
  158. package/dist/collections.mjs.map +0 -1
  159. package/dist/handlers/page-handler.astro +0 -299
  160. package/dist/loader-W3i9kf3p.mjs +0 -61
  161. package/dist/loader-W3i9kf3p.mjs.map +0 -1
  162. package/dist/types-Bsd_qENn.d.mts.map +0 -1
  163. package/dist/withHydration-692fMySA.mjs.map +0 -1
  164. package/dist/withHydration-BGgQDE-H.d.mts.map +0 -1
@@ -0,0 +1,13 @@
1
+ /**
2
+ * JSON.stringify replacement that escapes characters dangerous in HTML script contexts.
3
+ *
4
+ * When embedding JSON in `<script>` tags, characters like `<`, `>`, `&`, and `'` can break
5
+ * out of the script context (e.g., `</script>` closes the tag prematurely). This function
6
+ * replaces those characters with their Unicode escape equivalents, which are valid in both
7
+ * JSON and JavaScript string contexts.
8
+ *
9
+ * @see https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html
10
+ */
11
+ export declare function safeJsonStringify(data: Record<string, unknown> | unknown[] | string | number | boolean | null): string;
12
+ export declare function safeJsonStringify(data: unknown): string | undefined;
13
+ //# sourceMappingURL=safe-json-stringify.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"safe-json-stringify.d.ts","sourceRoot":"","sources":["../../src/safe-json-stringify.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,EAAE,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,GAAG,MAAM,CAAC;AACxH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAAC"}
@@ -0,0 +1,6 @@
1
+ export function safeJsonStringify(data) {
2
+ const json = JSON.stringify(data);
3
+ if (json === undefined)
4
+ return undefined;
5
+ return json.replace(/[<>&']/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`);
6
+ }
@@ -0,0 +1,76 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ /** Connect-compatible middleware handler — see render-endpoint.ts. */
3
+ type NextHandleFunction = (req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => void) => void;
4
+ /**
5
+ * Per-route content-wrapper discovery endpoint.
6
+ *
7
+ * The editor mirrors the host's content surface by rendering its
8
+ * contenteditable inside a clone of whatever element the host wraps
9
+ * its page content in. This endpoint fetches the live HTML the dev
10
+ * server serves at `?url=<route>`, locates the relevant wrappers
11
+ * (prose content + code-block chrome), and returns them as JSON.
12
+ *
13
+ * Returned shape:
14
+ *
15
+ * {
16
+ * content: { tagName, className } | null,
17
+ * codeBlock: { tagName, className }[] | null,
18
+ * }
19
+ *
20
+ * - `content` is the wrapper for prose (h1-h6, p, lists, etc.). The
21
+ * editor wraps its contenteditable in a clone so the host's prose
22
+ * CSS reaches via the cascade.
23
+ * - `codeBlock` is the ORDERED chain of classed wrappers around the
24
+ * host's `<pre>`, outermost first. For Starlight's expressive-code:
25
+ * `[{ div, 'expressive-code' }, { figure, 'frame has-title …' }]`.
26
+ * The editor's CodeMirror frame renders each link as a nested
27
+ * element (outer→inner) so the host's code-block CSS reaches via
28
+ * the cascade including descendant selectors (`.expressive-code
29
+ * .frame .header`, etc.) — not just single-class targets.
30
+ *
31
+ * Discovery priorities (content):
32
+ *
33
+ * 1. `[data-conloca-content-root]` — explicit opt-in.
34
+ * 2. The smallest classed wrapper inside `<main>` containing the
35
+ * majority of prose tags.
36
+ * 3. `<main>` itself.
37
+ * 4. `null`.
38
+ *
39
+ * Discovery (codeBlock): walk up from a `<pre>` inside `<main>` and
40
+ * collect classed ancestors between the content wrapper and `<pre>`,
41
+ * preserving their nesting order. Returns null when no `<pre>` exists,
42
+ * or when there are no classed wrappers between the prose wrapper and
43
+ * the `<pre>`.
44
+ */
45
+ export interface ContentWrapperInfo {
46
+ /** Lower-case HTML tag name as it appeared in source, eg `'article'`. */
47
+ tagName: string;
48
+ /** Space-separated class list from the source element. Preserved
49
+ * verbatim so Astro-scoped hashes (`astro-e3flfouy`) survive — host
50
+ * scoped CSS only matches when those hashes are present on the
51
+ * element. */
52
+ className: string;
53
+ }
54
+ export interface DiscoveredWrappers {
55
+ /** The element wrapping the page's prose content (h1-h6, p, etc.).
56
+ * For Starlight: `.sl-markdown-content`. For Tailwind Typography:
57
+ * `.prose`. Null when no prose wrapper exists on the page. */
58
+ content: ContentWrapperInfo | null;
59
+ /** Ordered chain of classed wrappers between the content wrapper
60
+ * and the `<pre>`, outermost first. For Starlight:
61
+ * `[{ div, 'expressive-code' }, { figure, 'frame has-title …' }]`.
62
+ * Null when the page has no code blocks or no classed wrappers
63
+ * between the prose wrapper and the `<pre>`. */
64
+ codeBlock: ContentWrapperInfo[] | null;
65
+ }
66
+ export declare function createContentWrapperEndpoint(): NextHandleFunction;
67
+ /**
68
+ * Locate the host's content + code-block wrappers in raw HTML. Single-
69
+ * pass regex walk with a stack so we can recover ancestor chains for
70
+ * both prose tags and `<pre>` tags without a full DOM parser dep.
71
+ *
72
+ * Exported for unit testing.
73
+ */
74
+ export declare function findContentWrapper(html: string): DiscoveredWrappers;
75
+ export {};
76
+ //# sourceMappingURL=content-wrapper-endpoint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"content-wrapper-endpoint.d.ts","sourceRoot":"","sources":["../../../src/site-styles/content-wrapper-endpoint.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAEjE,sEAAsE;AACtE,KAAK,kBAAkB,GAAG,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,cAAc,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,EAAE,OAAO,KAAK,IAAI,KAAK,IAAI,CAAC;AAE7G;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,MAAM,WAAW,kBAAkB;IACjC,yEAAyE;IACzE,OAAO,EAAE,MAAM,CAAC;IAChB;;;kBAGc;IACd,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,kBAAkB;IACjC;;kEAE8D;IAC9D,OAAO,EAAE,kBAAkB,GAAG,IAAI,CAAC;IACnC;;;;oDAIgD;IAChD,SAAS,EAAE,kBAAkB,EAAE,GAAG,IAAI,CAAC;CACxC;AAED,wBAAgB,4BAA4B,IAAI,kBAAkB,CA+BjE;AAuCD;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,kBAAkB,CAwEnE"}
@@ -0,0 +1,227 @@
1
+ export function createContentWrapperEndpoint() {
2
+ return async (req, res, _next) => {
3
+ try {
4
+ const parsed = new URL(req.url ?? '', 'http://localhost');
5
+ const routeUrl = parsed.searchParams.get('url');
6
+ if (!routeUrl) {
7
+ res.statusCode = 400;
8
+ res.setHeader('content-type', 'text/plain');
9
+ res.end('Missing required query parameter: url');
10
+ return;
11
+ }
12
+ const host = req.headers.host ?? 'localhost:4321';
13
+ const protocol = req.headers['x-forwarded-proto'] ?? 'http';
14
+ const liveUrl = `${protocol}://${host}${routeUrl}`;
15
+ const html = await fetch(liveUrl, {
16
+ headers: req.headers.cookie ? { cookie: req.headers.cookie } : undefined,
17
+ }).then((r) => r.text());
18
+ const wrappers = findContentWrapper(html);
19
+ res.statusCode = 200;
20
+ res.setHeader('content-type', 'application/json; charset=utf-8');
21
+ res.setHeader('cache-control', 'no-store');
22
+ res.end(JSON.stringify(wrappers));
23
+ }
24
+ catch (err) {
25
+ res.statusCode = 500;
26
+ res.setHeader('content-type', 'text/plain');
27
+ res.end(`Content-wrapper discovery failed: ${err instanceof Error ? err.message : String(err)}`);
28
+ }
29
+ };
30
+ }
31
+ /** Tags whose presence signals "this element holds prose content."
32
+ * We walk up from the first such element we find inside `<main>` to
33
+ * locate the wrapper. Headings + paragraphs cover every prose-styling
34
+ * convention we've seen — every CSS framework scopes typography
35
+ * through descendant selectors on `h1`–`h6` and `p`. */
36
+ const PROSE_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p']);
37
+ /** Tag that anchors code-block wrapper discovery. The host's code-
38
+ * block library (Starlight's expressive-code, Tailwind's `pre`
39
+ * styling, etc.) always renders a `<pre>` containing the code,
40
+ * often wrapped in additional classed elements. */
41
+ const CODE_BLOCK_ANCHOR = 'pre';
42
+ /** HTML5 void elements — never push onto the open-tag stack since they
43
+ * have no closing tag. */
44
+ const VOID_TAGS = new Set([
45
+ 'area',
46
+ 'base',
47
+ 'br',
48
+ 'col',
49
+ 'embed',
50
+ 'hr',
51
+ 'img',
52
+ 'input',
53
+ 'link',
54
+ 'meta',
55
+ 'source',
56
+ 'track',
57
+ 'wbr',
58
+ ]);
59
+ /**
60
+ * Locate the host's content + code-block wrappers in raw HTML. Single-
61
+ * pass regex walk with a stack so we can recover ancestor chains for
62
+ * both prose tags and `<pre>` tags without a full DOM parser dep.
63
+ *
64
+ * Exported for unit testing.
65
+ */
66
+ export function findContentWrapper(html) {
67
+ // Strip comments and scripts so opening-tag-shaped strings inside
68
+ // them don't pollute the walk.
69
+ const cleaned = html
70
+ .replace(/<!--[\s\S]*?-->/g, '')
71
+ .replace(/<script[\s\S]*?<\/script>/gi, '')
72
+ .replace(/<style[\s\S]*?<\/style>/gi, '');
73
+ const tagRe = /<(\/?)([a-zA-Z][a-zA-Z0-9-]*)((?:\s+[^>]*)?)\s*(\/?)>/g;
74
+ const stack = [];
75
+ let explicit = null;
76
+ let mainEl = null;
77
+ const proseAncestorChains = [];
78
+ const preAncestorChains = [];
79
+ let match;
80
+ // biome-ignore lint/suspicious/noAssignInExpressions: regex exec iterator
81
+ while ((match = tagRe.exec(cleaned)) !== null) {
82
+ const isClose = match[1] === '/';
83
+ const tagName = match[2].toLowerCase();
84
+ const attrBlob = match[3] ?? '';
85
+ const explicitlySelfClosing = match[4] === '/';
86
+ if (isClose) {
87
+ for (let i = stack.length - 1; i >= 0; i--) {
88
+ if (stack[i].tag === tagName) {
89
+ stack.length = i;
90
+ break;
91
+ }
92
+ }
93
+ continue;
94
+ }
95
+ const attrs = parseAttributes(attrBlob);
96
+ const className = attrs.class ?? '';
97
+ const el = { tag: tagName, className, attrs };
98
+ // Priority 1 (content only): explicit opt-in. Capture and keep
99
+ // walking — we still need to discover the code-block wrapper.
100
+ if (!explicit && 'data-conloca-content-root' in attrs) {
101
+ explicit = { tagName, className };
102
+ }
103
+ if (!mainEl && tagName === 'main') {
104
+ mainEl = el;
105
+ }
106
+ if (mainEl && PROSE_TAGS.has(tagName)) {
107
+ const mainIdx = stack.indexOf(mainEl);
108
+ if (mainIdx >= 0) {
109
+ proseAncestorChains.push(stack.slice(mainIdx + 1));
110
+ }
111
+ }
112
+ if (mainEl && tagName === CODE_BLOCK_ANCHOR) {
113
+ const mainIdx = stack.indexOf(mainEl);
114
+ if (mainIdx >= 0) {
115
+ preAncestorChains.push(stack.slice(mainIdx + 1));
116
+ }
117
+ }
118
+ const isVoid = VOID_TAGS.has(tagName);
119
+ if (!isVoid && !explicitlySelfClosing) {
120
+ stack.push(el);
121
+ }
122
+ }
123
+ const content = resolveContentWrapper(explicit, mainEl, proseAncestorChains);
124
+ const codeBlock = resolveCodeBlockWrapper(content, preAncestorChains);
125
+ return { content, codeBlock };
126
+ }
127
+ /**
128
+ * Pick the content wrapper from the walk's collected data.
129
+ *
130
+ * Priority: explicit opt-in > majority-prose-wrapper-inside-main >
131
+ * `<main>` fallback > null.
132
+ */
133
+ function resolveContentWrapper(explicit, mainEl, proseAncestorChains) {
134
+ if (explicit)
135
+ return explicit;
136
+ if (!mainEl)
137
+ return null;
138
+ if (proseAncestorChains.length === 0) {
139
+ return { tagName: 'main', className: mainEl.className };
140
+ }
141
+ // Tally classed-ancestor occurrences across all prose chains.
142
+ const scores = new Map();
143
+ for (const chain of proseAncestorChains) {
144
+ for (const ancestor of chain) {
145
+ if (!ancestor.className)
146
+ continue;
147
+ scores.set(ancestor, (scores.get(ancestor) ?? 0) + 1);
148
+ }
149
+ }
150
+ // Majority threshold rules out partial-coverage classed ancestors
151
+ // (single Cards holding one of many prose blocks).
152
+ const threshold = proseAncestorChains.length / 2;
153
+ const candidates = [...scores.entries()].filter(([, count]) => count > threshold);
154
+ if (candidates.length === 0) {
155
+ return { tagName: 'main', className: mainEl.className };
156
+ }
157
+ // Tie-break by depth: the candidate that appears deepest in any
158
+ // chain is the most specific (closest to the prose tags).
159
+ const maxChainIndex = (el) => Math.max(...proseAncestorChains.map((c) => c.indexOf(el)));
160
+ candidates.sort((a, b) => {
161
+ if (b[1] !== a[1])
162
+ return b[1] - a[1];
163
+ return maxChainIndex(b[0]) - maxChainIndex(a[0]);
164
+ });
165
+ const winner = candidates[0][0];
166
+ return { tagName: winner.tag, className: winner.className };
167
+ }
168
+ /**
169
+ * Derive the code-block wrapper chain from a representative `<pre>`'s
170
+ * ancestor chain. We strip everything at or above the content wrapper
171
+ * (its styles are already handled by the content-wrapper mirror) and
172
+ * return the remaining classed elements in nesting order, outermost
173
+ * first.
174
+ *
175
+ * Returning a chain (instead of one collapsed element) preserves the
176
+ * shape host CSS expects:
177
+ *
178
+ * - Single-class selectors (`.frame { ... }`) hit on whichever link
179
+ * carries that class.
180
+ * - Descendant selectors (`.expressive-code .frame { ... }`,
181
+ * `.frame .header > .title`) hit because the editor's renderer
182
+ * materialises the chain as nested elements with the host's
183
+ * expected tag names.
184
+ *
185
+ * The editor's code-block frame component (`code-block-frame.tsx` in
186
+ * `@conloca/mdx`) treats the LAST link as the "frame" element (where
187
+ * figcaption/pre/copy children render) and wraps it with the earlier
188
+ * links from inside out. This matches the host's authoring shape for
189
+ * libraries like ExpressiveCode (`.expressive-code > figure.frame >
190
+ * figcaption + pre + .copy`).
191
+ */
192
+ function resolveCodeBlockWrapper(content, preAncestorChains) {
193
+ if (preAncestorChains.length === 0)
194
+ return null;
195
+ // Pick the first <pre>'s chain as representative. Code blocks on a
196
+ // single page are uniformly wrapped, so chains are interchangeable.
197
+ const chain = preAncestorChains[0];
198
+ // Strip everything at-or-above the content wrapper; the rest is
199
+ // code-block-specific chrome that this endpoint is responsible for.
200
+ const contentIdx = content
201
+ ? chain.findIndex((el) => el.tag === content.tagName && el.className === content.className)
202
+ : -1;
203
+ const codeBlockChain = chain.slice(contentIdx + 1);
204
+ const classedAncestors = codeBlockChain.filter((el) => el.className);
205
+ if (classedAncestors.length === 0)
206
+ return null;
207
+ return classedAncestors.map((el) => ({ tagName: el.tag, className: el.className }));
208
+ }
209
+ /**
210
+ * Parse the attribute blob inside an opening tag. Handles `name="v"`,
211
+ * `name='v'`, `name=v`, and boolean (no-value) attributes. Doesn't
212
+ * handle entity decoding (`&amp;` → `&`) since the values we read
213
+ * (tag name, class list, the marker attribute) don't carry entities
214
+ * in practice.
215
+ */
216
+ function parseAttributes(s) {
217
+ const out = {};
218
+ const re = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+)))?/g;
219
+ let m;
220
+ // biome-ignore lint/suspicious/noAssignInExpressions: regex exec iterator
221
+ while ((m = re.exec(s)) !== null) {
222
+ const name = m[1];
223
+ const value = m[2] ?? m[3] ?? m[4] ?? '';
224
+ out[name] = value;
225
+ }
226
+ return out;
227
+ }
@@ -0,0 +1,55 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ /** Connect-compatible middleware handler. Avoids importing Vite's Connect
3
+ * namespace so dual peer-hash installs of the same Vite version can't
4
+ * produce cross-package `ViteDevServer` identity errors under tsc. */
5
+ type NextHandleFunction = (req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => void) => void;
6
+ /** Minimal surface used by the render tree — only ssrLoadModule. */
7
+ interface SsrModuleLoader {
8
+ ssrLoadModule(url: string): Promise<Record<string, unknown>>;
9
+ }
10
+ /**
11
+ * Vite middleware that renders an MDX JSX subtree to HTML on demand.
12
+ *
13
+ * Container components (CardGrid, Tabs, …) have JSX children that on
14
+ * the published page render as direct DOM children of the parent —
15
+ * positional CSS (`:nth-child` colour cycling on Card grids, CSS-grid
16
+ * placement) depends on that DOM shape. Per-block isolated rendering
17
+ * breaks both: each child gets its own wrapper, and the parent's only
18
+ * direct child is a slot marker.
19
+ *
20
+ * This endpoint renders a recursive tree: each node provides its
21
+ * component name + source + props, optionally with its own `children`
22
+ * tree. The server renders leaves first and assembles parents by
23
+ * passing rendered children HTML as the parent's default slot, so the
24
+ * final markup matches what Astro would emit for the same MDX
25
+ * source — same DOM, same CSS context.
26
+ *
27
+ * Request shape (JSON body):
28
+ * {
29
+ * tree: {
30
+ * component: string,
31
+ * source: string,
32
+ * defaultExport?: boolean,
33
+ * props?: Record<string, unknown>,
34
+ * slotId: string,
35
+ * children?: RenderTreeNode[]
36
+ * },
37
+ * documentIndex?: number // wraps top-level output to fix
38
+ * // sibling-position CSS for root-level
39
+ * // blocks (see phantom-sibling fix).
40
+ * }
41
+ *
42
+ * Legacy shape (kept for backward compatibility):
43
+ * { component, source, defaultExport?, props?, documentIndex? }
44
+ *
45
+ * For each node, the rendered slot content is either:
46
+ * - The concatenated HTML of recursively-rendered children, if any.
47
+ * - `<conloca-slot data-slot-id="<id>"></conloca-slot>` placeholder
48
+ * otherwise (the SPA portals a Lexical editor into it).
49
+ *
50
+ * Returns 200 with `Content-Type: text/html` on success; 4xx with a
51
+ * plain-text error otherwise.
52
+ */
53
+ export declare function createRenderEndpoint(server: SsrModuleLoader, getAllowedSources: () => Promise<Set<string>>): NextHandleFunction;
54
+ export {};
55
+ //# sourceMappingURL=render-endpoint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-endpoint.d.ts","sourceRoot":"","sources":["../../../src/site-styles/render-endpoint.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAGjE;;sEAEsE;AACtE,KAAK,kBAAkB,GAAG,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,cAAc,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,EAAE,OAAO,KAAK,IAAI,KAAK,IAAI,CAAC;AAE7G,oEAAoE;AACpE,UAAU,eAAe;IACvB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CAC9D;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,eAAe,EACvB,iBAAiB,EAAE,MAAM,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,GAC5C,kBAAkB,CA4FpB"}
@@ -0,0 +1,263 @@
1
+ import { experimental_AstroContainer } from 'astro/container';
2
+ /**
3
+ * Vite middleware that renders an MDX JSX subtree to HTML on demand.
4
+ *
5
+ * Container components (CardGrid, Tabs, …) have JSX children that on
6
+ * the published page render as direct DOM children of the parent —
7
+ * positional CSS (`:nth-child` colour cycling on Card grids, CSS-grid
8
+ * placement) depends on that DOM shape. Per-block isolated rendering
9
+ * breaks both: each child gets its own wrapper, and the parent's only
10
+ * direct child is a slot marker.
11
+ *
12
+ * This endpoint renders a recursive tree: each node provides its
13
+ * component name + source + props, optionally with its own `children`
14
+ * tree. The server renders leaves first and assembles parents by
15
+ * passing rendered children HTML as the parent's default slot, so the
16
+ * final markup matches what Astro would emit for the same MDX
17
+ * source — same DOM, same CSS context.
18
+ *
19
+ * Request shape (JSON body):
20
+ * {
21
+ * tree: {
22
+ * component: string,
23
+ * source: string,
24
+ * defaultExport?: boolean,
25
+ * props?: Record<string, unknown>,
26
+ * slotId: string,
27
+ * children?: RenderTreeNode[]
28
+ * },
29
+ * documentIndex?: number // wraps top-level output to fix
30
+ * // sibling-position CSS for root-level
31
+ * // blocks (see phantom-sibling fix).
32
+ * }
33
+ *
34
+ * Legacy shape (kept for backward compatibility):
35
+ * { component, source, defaultExport?, props?, documentIndex? }
36
+ *
37
+ * For each node, the rendered slot content is either:
38
+ * - The concatenated HTML of recursively-rendered children, if any.
39
+ * - `<conloca-slot data-slot-id="<id>"></conloca-slot>` placeholder
40
+ * otherwise (the SPA portals a Lexical editor into it).
41
+ *
42
+ * Returns 200 with `Content-Type: text/html` on success; 4xx with a
43
+ * plain-text error otherwise.
44
+ */
45
+ export function createRenderEndpoint(server, getAllowedSources) {
46
+ let containerPromise = null;
47
+ const getContainer = () => {
48
+ if (!containerPromise)
49
+ containerPromise = experimental_AstroContainer.create();
50
+ return containerPromise;
51
+ };
52
+ return async (req, res, _next) => {
53
+ if (req.method !== 'POST') {
54
+ res.statusCode = 405;
55
+ res.setHeader('content-type', 'text/plain');
56
+ res.end('Method not allowed');
57
+ return;
58
+ }
59
+ try {
60
+ const body = (await readJson(req));
61
+ // Normalize: accept either { tree } or the legacy flat shape.
62
+ const tree = body.tree ?? {
63
+ component: body.component ?? '',
64
+ source: body.source ?? '',
65
+ defaultExport: body.defaultExport,
66
+ props: body.props,
67
+ slotId: 'root',
68
+ };
69
+ if (!tree.component || !tree.source) {
70
+ res.statusCode = 400;
71
+ res.setHeader('content-type', 'text/plain');
72
+ res.end('Missing required fields: tree.component, tree.source');
73
+ return;
74
+ }
75
+ // Allowlist check. `source` flows into `server.ssrLoadModule`,
76
+ // which will load and execute ANY file Vite can resolve — so
77
+ // accepting arbitrary strings here would let any localhost POST
78
+ // (eg from a malicious tab visited during `bun dev`) run any
79
+ // JS file on the developer's machine. The registry already knows
80
+ // every legal component source; reject anything outside it.
81
+ const allowed = await getAllowedSources();
82
+ const disallowed = collectDisallowedSources(tree, allowed);
83
+ if (disallowed.length > 0) {
84
+ res.statusCode = 400;
85
+ res.setHeader('content-type', 'text/plain');
86
+ res.end(`source not in registry: ${disallowed.join(', ')}`);
87
+ return;
88
+ }
89
+ const container = await getContainer();
90
+ // Even the top-level render is wrapped: a hard failure here would
91
+ // 500 the whole response and leave the editor with no usable
92
+ // HTML to portal a body editor into. The stub keeps the surface
93
+ // editable so the author can fix the broken prop in place.
94
+ let rendered;
95
+ try {
96
+ rendered = await renderTree(tree, container, server);
97
+ }
98
+ catch (err) {
99
+ console.warn(`[conloca:render] <${tree.component}> failed:`, err instanceof Error ? err.message : err);
100
+ rendered = renderErrorStub(tree, err);
101
+ }
102
+ // Wrap top-level output in a host-marker parent (`.sl-markdown-content`)
103
+ // with `(documentIndex - 1)` hidden phantom siblings so root-level
104
+ // components match the live page's `:nth-child(N)` position. See
105
+ // earlier commit for the rationale (Starlight Card cycle).
106
+ //
107
+ // Inline (text-kind) requests skip the wrapper entirely: the
108
+ // rendered HTML is destined for inline text flow (eg an Icon's
109
+ // `<svg>` inside a paragraph), where a block wrapper would force
110
+ // a line break and phantom siblings make no sense (the node
111
+ // isn't a root flow child).
112
+ let html;
113
+ if (body.inline) {
114
+ html = rendered;
115
+ }
116
+ else {
117
+ const documentIndex = body.documentIndex;
118
+ const phantomCount = typeof documentIndex === 'number' && documentIndex > 0 ? documentIndex - 1 : 0;
119
+ const phantoms = phantomCount > 0 ? '<span hidden aria-hidden="true"></span>'.repeat(phantomCount) : '';
120
+ html = `<div class="sl-markdown-content">${phantoms}${rendered}</div>`;
121
+ }
122
+ res.statusCode = 200;
123
+ res.setHeader('content-type', 'text/html; charset=utf-8');
124
+ res.setHeader('cache-control', 'no-store');
125
+ res.end(html);
126
+ }
127
+ catch (err) {
128
+ res.statusCode = 500;
129
+ res.setHeader('content-type', 'text/plain');
130
+ res.end(`Render failed: ${err instanceof Error ? err.message : String(err)}`);
131
+ }
132
+ };
133
+ }
134
+ async function renderTree(node, container, server) {
135
+ const module = (await server.ssrLoadModule(node.source));
136
+ const exportKey = node.defaultExport ? 'default' : node.component;
137
+ const factory = module[exportKey];
138
+ if (typeof factory !== 'function') {
139
+ throw new Error(`Component '${node.component}' not found at '${node.source}' (export '${exportKey}')`);
140
+ }
141
+ // Slot content priority:
142
+ // 1. `children` (recursive tree) — pure-JSX container case.
143
+ // 2. `bodyHtml` — raw HTML emitted as-is, no
144
+ // conloca-slot wrapper. For
145
+ // components whose Astro
146
+ // implementation validates the
147
+ // slot's element type.
148
+ // 3. `<conloca-slot data-slot-id>{body}</conloca-slot>`
149
+ // — default path for everything
150
+ // else. The slot marker is the
151
+ // portal target; `body` is the
152
+ // static text fallback shown
153
+ // when no portal is mounted.
154
+ let slotContent;
155
+ if (node.children && node.children.length > 0) {
156
+ // Per-child error isolation: one broken `<Card>` no longer blanks
157
+ // its sibling Cards. A failure to render any specific child
158
+ // becomes an inline error stub (carrying that child's slot id so
159
+ // the body editor still portals into it), and the parent goes on
160
+ // to render with the stub HTML in that child's position.
161
+ const renderedChildren = await Promise.all(node.children.map(async (child) => {
162
+ try {
163
+ return await renderTree(child, container, server);
164
+ }
165
+ catch (err) {
166
+ // Log to the dev console so the failure isn't entirely
167
+ // invisible — the inline stub is the author's surface, but
168
+ // a dev tailing the terminal still wants the stack trace.
169
+ console.warn(`[conloca:render] <${child.component}> failed:`, err instanceof Error ? err.message : err);
170
+ return renderErrorStub(child, err);
171
+ }
172
+ }));
173
+ slotContent = renderedChildren.join('');
174
+ }
175
+ else if (node.bodyHtml) {
176
+ slotContent = node.bodyHtml;
177
+ }
178
+ else {
179
+ const fallback = node.body ?? '';
180
+ slotContent = `<conloca-slot data-slot-id="${escapeHtml(node.slotId)}">${fallback}</conloca-slot>`;
181
+ }
182
+ // Named slots (Astro's `<Fragment slot="header">` pattern) are
183
+ // passed alongside `default`. The client extracts them from mdast
184
+ // and ships each as an HTML string keyed by slot name.
185
+ const slots = { default: slotContent, ...(node.namedSlots ?? {}) };
186
+ return container.renderToString(factory, {
187
+ props: node.props,
188
+ slots,
189
+ // Frameworks (Starlight, others) read content via `Astro.locals.t(...)`
190
+ // set by their middleware. The bare container has none, so we
191
+ // pass a fallback: strip namespace, capitalize the leaf
192
+ // ('asides.note' → 'Note'). Real titles/body come from props.
193
+ locals: { t: defaultI18nFallback },
194
+ });
195
+ }
196
+ /**
197
+ * Build a self-contained, editable error stub for one render failure.
198
+ *
199
+ * Three jobs:
200
+ * 1. Surface the error inline so the author sees *exactly* which
201
+ * component blew up and why, right where it sits in the document.
202
+ * No console-spelunking required.
203
+ * 2. Keep the slot id intact so GenericBlock's portal-discovery loop
204
+ * (`querySelectorAll('conloca-slot[data-slot-id]')`) still finds a
205
+ * mount point inside the stub. The body editor mounts as normal;
206
+ * the author can edit the children even though the parent
207
+ * component's own render failed — typically that's enough to fix
208
+ * whatever the validator was upset about.
209
+ * 3. Stay structurally innocuous. A `<div>` wrapper renders cleanly
210
+ * inside any parent slot that accepts arbitrary HTML, and a
211
+ * data-attribute on the wrapper lets host CSS style it however
212
+ * they like (yellow background, red border, whatever).
213
+ *
214
+ * Note: if the parent component itself has a strict-slot validator
215
+ * (eg `<Tabs>` rejects non-TabItem children), the stub will fail the
216
+ * parent's render too — but the recursion at the parent level then
217
+ * catches THAT failure and emits its own stub one level up. The
218
+ * worst case bubbles all the way to the top-level wrap in the
219
+ * endpoint handler. Errors never escape as 500s.
220
+ */
221
+ function renderErrorStub(node, err) {
222
+ const message = err instanceof Error ? err.message : String(err);
223
+ const name = node.component || 'unknown';
224
+ return (`<div class="conloca-render-error" data-component="${escapeHtml(name)}" data-slot-id="${escapeHtml(node.slotId)}" role="alert">` +
225
+ `<div class="conloca-render-error__label">&lt;${escapeHtml(name)}&gt; failed to render: ${escapeHtml(message)}</div>` +
226
+ `<conloca-slot data-slot-id="${escapeHtml(node.slotId)}"></conloca-slot>` +
227
+ '</div>');
228
+ }
229
+ function collectDisallowedSources(node, allowed) {
230
+ const bad = [];
231
+ if (!allowed.has(node.source))
232
+ bad.push(node.source);
233
+ if (node.children) {
234
+ for (const child of node.children)
235
+ bad.push(...collectDisallowedSources(child, allowed));
236
+ }
237
+ return bad;
238
+ }
239
+ function escapeHtml(s) {
240
+ return s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
241
+ }
242
+ function defaultI18nFallback(key) {
243
+ const leaf = key.split('.').pop() ?? key;
244
+ return leaf.charAt(0).toUpperCase() + leaf.slice(1);
245
+ }
246
+ async function readJson(req) {
247
+ return new Promise((resolve, reject) => {
248
+ let raw = '';
249
+ req.setEncoding('utf8');
250
+ req.on('data', (chunk) => {
251
+ raw += chunk;
252
+ });
253
+ req.on('end', () => {
254
+ try {
255
+ resolve(raw ? JSON.parse(raw) : {});
256
+ }
257
+ catch (err) {
258
+ reject(err instanceof Error ? err : new Error('Invalid JSON'));
259
+ }
260
+ });
261
+ req.on('error', reject);
262
+ });
263
+ }