@conloca/astro-cms 0.2.2 → 0.2.3

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.
@@ -6,68 +6,9 @@ import type { Connect } from 'vite';
6
6
  * contenteditable inside a clone of whatever element the host wraps
7
7
  * its page content in. This endpoint fetches the live HTML the dev
8
8
  * server serves at `?url=<route>`, locates the relevant wrappers
9
- * (prose content + code-block chrome), and returns them as JSON.
10
- *
11
- * Returned shape:
12
- *
13
- * {
14
- * content: { tagName, className } | null,
15
- * codeBlock: { tagName, className }[] | null,
16
- * }
17
- *
18
- * - `content` is the wrapper for prose (h1-h6, p, lists, etc.). The
19
- * editor wraps its contenteditable in a clone so the host's prose
20
- * CSS reaches via the cascade.
21
- * - `codeBlock` is the ORDERED chain of classed wrappers around the
22
- * host's `<pre>`, outermost first. For Starlight's expressive-code:
23
- * `[{ div, 'expressive-code' }, { figure, 'frame has-title …' }]`.
24
- * The editor's CodeMirror frame renders each link as a nested
25
- * element (outer→inner) so the host's code-block CSS reaches via
26
- * the cascade including descendant selectors (`.expressive-code
27
- * .frame .header`, etc.) — not just single-class targets.
28
- *
29
- * Discovery priorities (content):
30
- *
31
- * 1. `[data-conloca-content-root]` — explicit opt-in.
32
- * 2. The smallest classed wrapper inside `<main>` containing the
33
- * majority of prose tags.
34
- * 3. `<main>` itself.
35
- * 4. `null`.
36
- *
37
- * Discovery (codeBlock): walk up from a `<pre>` inside `<main>` and
38
- * collect classed ancestors between the content wrapper and `<pre>`,
39
- * preserving their nesting order. Returns null when no `<pre>` exists,
40
- * or when there are no classed wrappers between the prose wrapper and
41
- * the `<pre>`.
9
+ * (prose content + code-block chrome) with `findContentWrapper`, and
10
+ * returns them as JSON. An editor page without this endpoint runs the
11
+ * same function on the page its style probe loads.
42
12
  */
43
- export interface ContentWrapperInfo {
44
- /** Lower-case HTML tag name as it appeared in source, eg `'article'`. */
45
- tagName: string;
46
- /** Space-separated class list from the source element. Preserved
47
- * verbatim so Astro-scoped hashes (`astro-e3flfouy`) survive — host
48
- * scoped CSS only matches when those hashes are present on the
49
- * element. */
50
- className: string;
51
- }
52
- export interface DiscoveredWrappers {
53
- /** The element wrapping the page's prose content (h1-h6, p, etc.).
54
- * For Starlight: `.sl-markdown-content`. For Tailwind Typography:
55
- * `.prose`. Null when no prose wrapper exists on the page. */
56
- content: ContentWrapperInfo | null;
57
- /** Ordered chain of classed wrappers between the content wrapper
58
- * and the `<pre>`, outermost first. For Starlight:
59
- * `[{ div, 'expressive-code' }, { figure, 'frame has-title …' }]`.
60
- * Null when the page has no code blocks or no classed wrappers
61
- * between the prose wrapper and the `<pre>`. */
62
- codeBlock: ContentWrapperInfo[] | null;
63
- }
64
13
  export declare function createContentWrapperEndpoint(): Connect.NextHandleFunction;
65
- /**
66
- * Locate the host's content + code-block wrappers in raw HTML. Single-
67
- * pass regex walk with a stack so we can recover ancestor chains for
68
- * both prose tags and `<pre>` tags without a full DOM parser dep.
69
- *
70
- * Exported for unit testing.
71
- */
72
- export declare function findContentWrapper(html: string): DiscoveredWrappers;
73
14
  //# sourceMappingURL=content-wrapper-endpoint.d.ts.map
@@ -1 +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,OAAO,EAAE,MAAM,MAAM,CAAC;AAEpC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,OAAO,CAAC,kBAAkB,CA+BzE;AAuCD;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,kBAAkB,CAsEnE"}
1
+ {"version":3,"file":"content-wrapper-endpoint.d.ts","sourceRoot":"","sources":["../../../../src/site-styles/content-wrapper-endpoint.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAEpC;;;;;;;;;;GAUG;AACH,wBAAgB,4BAA4B,IAAI,OAAO,CAAC,kBAAkB,CA+BzE"}
@@ -1,3 +1,15 @@
1
+ import { findContentWrapper } from '@conloca/cms-spa/content-wrapper';
2
+ /**
3
+ * Per-route content-wrapper discovery endpoint.
4
+ *
5
+ * The editor mirrors the host's content surface by rendering its
6
+ * contenteditable inside a clone of whatever element the host wraps
7
+ * its page content in. This endpoint fetches the live HTML the dev
8
+ * server serves at `?url=<route>`, locates the relevant wrappers
9
+ * (prose content + code-block chrome) with `findContentWrapper`, and
10
+ * returns them as JSON. An editor page without this endpoint runs the
11
+ * same function on the page its style probe loads.
12
+ */
1
13
  export function createContentWrapperEndpoint() {
2
14
  return async (req, res, _next) => {
3
15
  try {
@@ -28,197 +40,4 @@ export function createContentWrapperEndpoint() {
28
40
  }
29
41
  };
30
42
  }
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
- for (const match of cleaned.matchAll(tagRe)) {
80
- const isClose = match[1] === '/';
81
- const tagName = match[2].toLowerCase();
82
- const attrBlob = match[3] ?? '';
83
- const explicitlySelfClosing = match[4] === '/';
84
- if (isClose) {
85
- for (let i = stack.length - 1; i >= 0; i--) {
86
- if (stack[i].tag === tagName) {
87
- stack.length = i;
88
- break;
89
- }
90
- }
91
- continue;
92
- }
93
- const attrs = parseAttributes(attrBlob);
94
- const className = attrs.class ?? '';
95
- const el = { tag: tagName, className, attrs };
96
- // Priority 1 (content only): explicit opt-in. Capture and keep
97
- // walking — we still need to discover the code-block wrapper.
98
- if (!explicit && 'data-conloca-content-root' in attrs) {
99
- explicit = { tagName, className };
100
- }
101
- if (!mainEl && tagName === 'main') {
102
- mainEl = el;
103
- }
104
- if (mainEl && PROSE_TAGS.has(tagName)) {
105
- const mainIdx = stack.indexOf(mainEl);
106
- if (mainIdx >= 0) {
107
- proseAncestorChains.push(stack.slice(mainIdx + 1));
108
- }
109
- }
110
- if (mainEl && tagName === CODE_BLOCK_ANCHOR) {
111
- const mainIdx = stack.indexOf(mainEl);
112
- if (mainIdx >= 0) {
113
- preAncestorChains.push(stack.slice(mainIdx + 1));
114
- }
115
- }
116
- const isVoid = VOID_TAGS.has(tagName);
117
- if (!isVoid && !explicitlySelfClosing) {
118
- stack.push(el);
119
- }
120
- }
121
- const content = resolveContentWrapper(explicit, mainEl, proseAncestorChains);
122
- const codeBlock = resolveCodeBlockWrapper(content, preAncestorChains);
123
- return { content, codeBlock };
124
- }
125
- /**
126
- * Pick the content wrapper from the walk's collected data.
127
- *
128
- * Priority: explicit opt-in > majority-prose-wrapper-inside-main >
129
- * `<main>` fallback > null.
130
- */
131
- function resolveContentWrapper(explicit, mainEl, proseAncestorChains) {
132
- if (explicit)
133
- return explicit;
134
- if (!mainEl)
135
- return null;
136
- if (proseAncestorChains.length === 0) {
137
- return { tagName: 'main', className: mainEl.className };
138
- }
139
- // Tally classed-ancestor occurrences across all prose chains.
140
- const scores = new Map();
141
- for (const chain of proseAncestorChains) {
142
- for (const ancestor of chain) {
143
- if (!ancestor.className)
144
- continue;
145
- scores.set(ancestor, (scores.get(ancestor) ?? 0) + 1);
146
- }
147
- }
148
- // Majority threshold rules out partial-coverage classed ancestors
149
- // (single Cards holding one of many prose blocks).
150
- const threshold = proseAncestorChains.length / 2;
151
- const candidates = [...scores.entries()].filter(([, count]) => count > threshold);
152
- if (candidates.length === 0) {
153
- return { tagName: 'main', className: mainEl.className };
154
- }
155
- // Tie-break by depth: the candidate that appears deepest in any
156
- // chain is the most specific (closest to the prose tags).
157
- const maxChainIndex = (el) => Math.max(...proseAncestorChains.map((c) => c.indexOf(el)));
158
- candidates.sort((a, b) => {
159
- if (b[1] !== a[1])
160
- return b[1] - a[1];
161
- return maxChainIndex(b[0]) - maxChainIndex(a[0]);
162
- });
163
- const winner = candidates[0][0];
164
- return { tagName: winner.tag, className: winner.className };
165
- }
166
- /**
167
- * Derive the code-block wrapper chain from a representative `<pre>`'s
168
- * ancestor chain. We strip everything at or above the content wrapper
169
- * (its styles are already handled by the content-wrapper mirror) and
170
- * return the remaining classed elements in nesting order, outermost
171
- * first.
172
- *
173
- * Returning a chain (instead of one collapsed element) preserves the
174
- * shape host CSS expects:
175
- *
176
- * - Single-class selectors (`.frame { ... }`) hit on whichever link
177
- * carries that class.
178
- * - Descendant selectors (`.expressive-code .frame { ... }`,
179
- * `.frame .header > .title`) hit because the editor's renderer
180
- * materialises the chain as nested elements with the host's
181
- * expected tag names.
182
- *
183
- * The editor's code-block frame component (`code-block-frame.tsx` in
184
- * `@conloca/mdx`) treats the LAST link as the "frame" element (where
185
- * figcaption/pre/copy children render) and wraps it with the earlier
186
- * links from inside out. This matches the host's authoring shape for
187
- * libraries like ExpressiveCode (`.expressive-code > figure.frame >
188
- * figcaption + pre + .copy`).
189
- */
190
- function resolveCodeBlockWrapper(content, preAncestorChains) {
191
- if (preAncestorChains.length === 0)
192
- return null;
193
- // Pick the first <pre>'s chain as representative. Code blocks on a
194
- // single page are uniformly wrapped, so chains are interchangeable.
195
- const chain = preAncestorChains[0];
196
- // Strip everything at-or-above the content wrapper; the rest is
197
- // code-block-specific chrome that this endpoint is responsible for.
198
- const contentIdx = content
199
- ? chain.findIndex((el) => el.tag === content.tagName && el.className === content.className)
200
- : -1;
201
- const codeBlockChain = chain.slice(contentIdx + 1);
202
- const classedAncestors = codeBlockChain.filter((el) => el.className);
203
- if (classedAncestors.length === 0)
204
- return null;
205
- return classedAncestors.map((el) => ({ tagName: el.tag, className: el.className }));
206
- }
207
- /**
208
- * Parse the attribute blob inside an opening tag. Handles `name="v"`,
209
- * `name='v'`, `name=v`, and boolean (no-value) attributes. Doesn't
210
- * handle entity decoding (`&amp;` → `&`) since the values we read
211
- * (tag name, class list, the marker attribute) don't carry entities
212
- * in practice.
213
- */
214
- function parseAttributes(s) {
215
- const out = {};
216
- const re = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+)))?/g;
217
- for (const match of s.matchAll(re)) {
218
- const name = match[1];
219
- const value = match[2] ?? match[3] ?? match[4] ?? '';
220
- out[name] = value;
221
- }
222
- return out;
223
- }
224
43
  //# sourceMappingURL=content-wrapper-endpoint.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"content-wrapper-endpoint.js","sourceRoot":"","sources":["../../../../src/site-styles/content-wrapper-endpoint.ts"],"names":[],"mappings":"AAkEA,MAAM,UAAU,4BAA4B;IAC1C,OAAO,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,EAAE;QAC/B,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,IAAI,EAAE,EAAE,kBAAkB,CAAC,CAAC;YAC1D,MAAM,QAAQ,GAAG,MAAM,CAAC,YAAY,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;YAChD,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACd,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC;gBACrB,GAAG,CAAC,SAAS,CAAC,cAAc,EAAE,YAAY,CAAC,CAAC;gBAC5C,GAAG,CAAC,GAAG,CAAC,uCAAuC,CAAC,CAAC;gBACjD,OAAO;YACT,CAAC;YAED,MAAM,IAAI,GAAG,GAAG,CAAC,OAAO,CAAC,IAAI,IAAI,gBAAgB,CAAC;YAClD,MAAM,QAAQ,GAAI,GAAG,CAAC,OAAO,CAAC,mBAAmB,CAAY,IAAI,MAAM,CAAC;YACxE,MAAM,OAAO,GAAG,GAAG,QAAQ,MAAM,IAAI,GAAG,QAAQ,EAAE,CAAC;YACnD,MAAM,IAAI,GAAG,MAAM,KAAK,CAAC,OAAO,EAAE;gBAChC,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,OAAO,CAAC,MAAM,EA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AC,OAAO,GAAG,EAAE,CAAC;YACb,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC;YACrB,GAAG,CAAC,SAAS,CAAC,cAAc,EAAE,YAAY,CAAC,CAAC;YAC5C,GAAG,CAAC,GAAG,CAAC,qCAAqC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACnG,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
package/node/index.ts CHANGED
@@ -1,3 +1,10 @@
1
+ // Pure HTML→wrapper-shape heuristic, for any build-time caller, so it runs
2
+ // the same find-wrapper implementation as the dev endpoint.
3
+ export {
4
+ type ContentWrapperInfo,
5
+ type DiscoveredWrappers,
6
+ findContentWrapper,
7
+ } from '@conloca/cms-spa/content-wrapper';
1
8
  // The MDX component registry scan, for any build-time caller, so it runs the
2
9
  // same discovery implementation as the dev endpoint.
3
10
  export { discoverMdxComponents, type MdxRegistryScanOptions, toPortableImports } from '../src/discovery/discover.js';
@@ -11,12 +18,5 @@ export {
11
18
  export { type HydrationDiscovery, scanForHydratableComponents } from '../src/lib/hydration-scanner.js';
12
19
  export { type ConlocaLocales, localesFromAstroI18n, localesFromStarlight } from '../src/locales-helpers.js';
13
20
  export { type ConlocaCMSOptions, conlocaCMS } from '../src/plugin-spa.js';
14
- // Pure HTML→wrapper-shape heuristic, for any build-time caller, so it runs
15
- // the same find-wrapper implementation as the dev endpoint.
16
- export {
17
- type ContentWrapperInfo,
18
- type DiscoveredWrappers,
19
- findContentWrapper,
20
- } from '../src/site-styles/content-wrapper-endpoint.js';
21
21
  // Sitemap entries for CMS pages, which a sitemap cannot find by itself when they render on demand.
22
22
  export { type AstroUrlSettings, type ConlocaSitemapOptions, conlocaSitemapOptions } from '../src/sitemap-options.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@conloca/astro-cms",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -92,9 +92,9 @@
92
92
  "!**/*.tsbuildinfo"
93
93
  ],
94
94
  "dependencies": {
95
- "@conloca/cms-spa": "0.2.2",
96
- "@conloca/content-api": "0.2.2",
97
- "@conloca/mdx": "0.2.2",
95
+ "@conloca/cms-spa": "0.2.3",
96
+ "@conloca/content-api": "0.2.3",
97
+ "@conloca/mdx": "0.2.3",
98
98
  "@puckeditor/core": "^0.23.0",
99
99
  "@tiptap/core": "^3.31.2",
100
100
  "@tiptap/pm": "^3.31.2",
@@ -137,11 +137,11 @@
137
137
  "@tiptap/extension-text-align": "3.31.2",
138
138
  "@tiptap/extension-underline": "3.31.2",
139
139
  "@tiptap/html": "3.31.2",
140
- "@ttsc/unplugin": "^0.30.4",
140
+ "@ttsc/unplugin": "^0.34.1",
141
141
  "@vitejs/plugin-react": "^5.2.0",
142
142
  "astro": "^7.3.1",
143
143
  "fast-check": "^4.9.0",
144
- "ttsc": "0.30.4",
144
+ "ttsc": "0.34.1",
145
145
  "typia": "^14.0.4",
146
146
  "vite": "^7.3.6"
147
147
  },
@@ -1,3 +1,4 @@
1
+ import { isAbsolute } from 'node:path';
1
2
  import { readEditorDataBindings } from '@conloca/content-api';
2
3
  import type { MdxRegistryScanOptions } from './discovery/discover.js';
3
4
  import type { EditorDataBindings, TemplateConfig } from './types.js';
@@ -6,23 +7,37 @@ import type { EditorDataBindings, TemplateConfig } from './types.js';
6
7
  * Env var through which `conlocaCMS` publishes the editor descriptors it
7
8
  * resolved during an Astro build, alongside `CONLOCA_CONTENT_ROOT`.
8
9
  *
9
- * The CMS resolves them once — the site's schemas module, the MDX registry
10
- * scan inputs, the page templates and the routing data bindings — so another
11
- * integration in the same build reads the SAME descriptors dev serves from
12
- * `schemasPath`, `/api/registry` and its UI config instead of taking those
13
- * options a second time.
10
+ * The CMS resolves them once — the site's schemas module, its editor-build
11
+ * options, the MDX registry scan inputs, the page templates and the routing
12
+ * data bindings — so another integration in the same build reads the SAME
13
+ * descriptors dev serves from `schemasPath`, `/api/registry` and its UI config
14
+ * instead of taking those options a second time.
14
15
  */
15
16
  export const EDITOR_DESCRIPTORS_ENV_VAR = 'CONLOCA_EDITOR_DESCRIPTORS';
16
17
 
17
18
  export interface EditorDescriptorChannel {
18
19
  /** Absolute path of the host's schemas module (the `schemasPath` option), when configured. */
19
20
  schemasPath?: string;
21
+ /**
22
+ * Absolute path of the puck config module (the `puckConfigPath` option).
23
+ * Optional only because an older `@conloca/astro-cms` wrote no such field;
24
+ * this version always publishes it.
25
+ */
26
+ puckConfigPath?: string;
27
+ /** Absolute paths of the `siteStyles` option, resolved against the Astro root, one entry per stylesheet. */
28
+ siteStyles?: string[];
29
+ /** Absolute paths of `editorStyles`, each resolved against the Astro root. */
30
+ editorStyles?: string[];
31
+ /** The `editorCSS` option, verbatim. */
32
+ editorCSS?: string;
20
33
  /** Resolved inputs for the MDX component registry scan (`mdxComponentFolders` + the MDX content root). */
21
34
  registry: MdxRegistryScanOptions;
22
35
  /** Page-creation templates (the `templates` option), when configured. */
23
36
  templates?: Record<string, TemplateConfig>;
24
37
  /** The routing data bindings each page's data context is built from, when the site has content routes. */
25
38
  dataBindings?: EditorDataBindings;
39
+ /** Absolute paths of every folder the content API writes to: the content root, the MDX pages root, the media folder. */
40
+ contentPaths?: string[];
26
41
  }
27
42
 
28
43
  /**
@@ -44,9 +59,14 @@ export function readEditorDescriptors(
44
59
  }
45
60
  if (typeof parsed !== 'object' || parsed === null) return undefined;
46
61
  const schemasPath = 'schemasPath' in parsed ? parsed.schemasPath : undefined;
62
+ const puckConfigPath = 'puckConfigPath' in parsed ? parsed.puckConfigPath : undefined;
63
+ const styleValue = 'siteStyles' in parsed ? parsed.siteStyles : undefined;
64
+ const editorStyleValue = 'editorStyles' in parsed ? parsed.editorStyles : undefined;
65
+ const editorCSS = 'editorCSS' in parsed ? parsed.editorCSS : undefined;
47
66
  const registry = 'registry' in parsed ? parsed.registry : undefined;
48
67
  const templateValue = 'templates' in parsed ? parsed.templates : undefined;
49
68
  const dataBindingValue = 'dataBindings' in parsed ? parsed.dataBindings : undefined;
69
+ const contentPathValue = 'contentPaths' in parsed ? parsed.contentPaths : undefined;
50
70
  if (typeof registry !== 'object' || registry === null) return undefined;
51
71
  const contentRoot = 'contentRoot' in registry ? registry.contentRoot : undefined;
52
72
  const componentFolders = 'componentFolders' in registry ? registry.componentFolders : undefined;
@@ -61,8 +81,25 @@ export function readEditorDescriptors(
61
81
  }
62
82
  const templates = readTemplates(templateValue);
63
83
  const dataBindings = readEditorDataBindings(dataBindingValue);
84
+ const siteStyles =
85
+ Array.isArray(styleValue) && styleValue.every((path): path is string => typeof path === 'string')
86
+ ? styleValue
87
+ : undefined;
88
+ const editorStyles =
89
+ Array.isArray(editorStyleValue) && editorStyleValue.every((path): path is string => typeof path === 'string')
90
+ ? editorStyleValue
91
+ : undefined;
92
+ const contentPaths =
93
+ Array.isArray(contentPathValue) &&
94
+ contentPathValue.every((path): path is string => typeof path === 'string' && isAbsolute(path))
95
+ ? contentPathValue
96
+ : undefined;
64
97
  return {
65
98
  ...(typeof schemasPath === 'string' ? { schemasPath } : {}),
99
+ ...(typeof puckConfigPath === 'string' ? { puckConfigPath } : {}),
100
+ ...(siteStyles === undefined ? {} : { siteStyles }),
101
+ ...(editorStyles === undefined ? {} : { editorStyles }),
102
+ ...(typeof editorCSS === 'string' ? { editorCSS } : {}),
66
103
  registry: {
67
104
  contentRoot,
68
105
  componentFolders,
@@ -71,6 +108,7 @@ export function readEditorDescriptors(
71
108
  },
72
109
  ...(templates === undefined ? {} : { templates }),
73
110
  ...(dataBindings === undefined ? {} : { dataBindings }),
111
+ ...(contentPaths === undefined ? {} : { contentPaths }),
74
112
  };
75
113
  }
76
114
 
package/src/plugin-spa.ts CHANGED
@@ -669,12 +669,39 @@ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
669
669
  // descriptors dev loads from `schemasPath`, `/api/registry` and
670
670
  // `virtual:conloca-config` instead of taking these options again.
671
671
  // schemasPath is absolutized because a reader may use it as an import
672
- // specifier.
672
+ // specifier. Readers inherit the puck config, the site and editor
673
+ // stylesheets, the editor CSS and the fragment preview route from here
674
+ // too, so the site writes each of them once. The stylesheets resolve
675
+ // against the Astro root, where the dev editor's Vite imports find
676
+ // them, so a build started from another folder (`astro build --root
677
+ // site`) still hands on the same files.
678
+ const configuredStyles = options.siteStyles;
679
+ const siteStyles = configuredStyles
680
+ ? (Array.isArray(configuredStyles) ? configuredStyles : [configuredStyles]).map((path) =>
681
+ resolve(fileURLToPath(config.root), path),
682
+ )
683
+ : undefined;
684
+ const configuredEditorStyles = options.editorStyles;
685
+ const editorStyles = configuredEditorStyles
686
+ ? (Array.isArray(configuredEditorStyles) ? configuredEditorStyles : [configuredEditorStyles]).map((path) =>
687
+ resolve(fileURLToPath(config.root), path),
688
+ )
689
+ : undefined;
673
690
  const editorDescriptors: EditorDescriptorChannel = {
674
691
  ...(options.schemasPath ? { schemasPath: resolve(options.schemasPath) } : {}),
692
+ puckConfigPath: resolve(options.puckConfigPath),
693
+ ...(siteStyles === undefined ? {} : { siteStyles }),
694
+ ...(editorStyles === undefined ? {} : { editorStyles }),
695
+ ...(options.editorCSS ? { editorCSS: options.editorCSS } : {}),
675
696
  registry: registryScan,
676
697
  ...(options.templates ? { templates: options.templates } : {}),
677
698
  ...(spaConfig.dataBindings ? { dataBindings: spaConfig.dataBindings } : {}),
699
+ // Every folder the content API writes to, resolved as it resolves them (the build's working directory).
700
+ contentPaths: [
701
+ resolve(options.contentRoot),
702
+ ...(resolvedMdxPages ? [resolve(resolvedMdxPages)] : []),
703
+ ...(options.assetsPath ? [resolve(options.assetsPath)] : []),
704
+ ],
678
705
  };
679
706
  process.env[EDITOR_DESCRIPTORS_ENV_VAR] = JSON.stringify(editorDescriptors);
680
707
 
@@ -913,17 +940,12 @@ initHydration(componentRegistry)
913
940
  }
914
941
  }
915
942
 
916
- // The sandbox frame document ContentSandbox loads for MDX previews.
917
- // Root-absolute by contract (SANDBOX_FRAME_PATH in @conloca/mdx) and
918
- // needed wherever the editor runs — anything that serves the editor
919
- // serves the same path. Injected outside the dev-only block: a
920
- // production editor build needs the frame too.
921
- //
922
- // On-demand by necessity — the response carries the sandbox CSP, which
923
- // a prerendered file cannot — so injecting it into a fully static site
924
- // fails that build with NoAdapterInstalled. Such a site has no runtime
925
- // editor to serve it to; dev serves it whatever the output mode.
926
- if (command === 'dev' || config.output !== 'static') {
943
+ // The sandbox frame document ContentSandbox loads for MDX previews in
944
+ // the dev editor. Root-absolute by contract (SANDBOX_FRAME_PATH in
945
+ // @conloca/mdx). On-demand by necessity — the response carries the
946
+ // sandbox CSP, which a prerendered file cannot. A built site never
947
+ // gets it: its editor page ships the frame as a static file.
948
+ if (command === 'dev') {
927
949
  injectRoute({
928
950
  pattern: '/api/v1/mdx/sandbox-frame',
929
951
  entrypoint: SANDBOX_FRAME_HANDLER_PATH,
@@ -1,4 +1,4 @@
1
- import { buildSandboxSrcdoc, SANDBOX_FRAME_CSP } from '@conloca/mdx/sandbox-frame';
1
+ import { buildSandboxSrcdoc, MDX_SANDBOX_FRAME_POLICY } from '@conloca/mdx/sandbox-frame';
2
2
  import type { APIRoute } from 'astro';
3
3
 
4
4
  /**
@@ -11,7 +11,8 @@ import type { APIRoute } from 'astro';
11
11
  * that serves the editor must serve this path too. astro-cms routes otherwise
12
12
  * live under the cmsRoute prefix, so without this route the frame 404s and
13
13
  * chips render the site's 404 page. Response headers are the frame's contract
14
- * (`SANDBOX_FRAME_CSP`); any other server of the frame must match them.
14
+ * (`MDX_SANDBOX_FRAME_POLICY`); any other server of the frame must match them,
15
+ * including the 403 for anything but an iframe load.
15
16
  *
16
17
  * No auth gate: the document is static boilerplate — content only ever enters
17
18
  * the frame via postMessage from the editor.
@@ -19,13 +20,23 @@ import type { APIRoute } from 'astro';
19
20
 
20
21
  export const prerender = false;
21
22
 
22
- export const GET: APIRoute = () =>
23
- new Response(buildSandboxSrcdoc(), {
23
+ /** The frame route's answer to a request with these headers. */
24
+ export function sandboxFrameResponse(request: Pick<Request, 'headers'>): Response {
25
+ if (request.headers.get('sec-fetch-dest') !== 'iframe') {
26
+ return new Response('The MDX preview frame loads only inside an editor frame.', {
27
+ status: 403,
28
+ headers: { 'cache-control': 'no-store' },
29
+ });
30
+ }
31
+ return new Response(buildSandboxSrcdoc(), {
24
32
  status: 200,
25
33
  headers: {
26
34
  'content-type': 'text/html; charset=utf-8',
27
- 'content-security-policy': `${SANDBOX_FRAME_CSP}; frame-ancestors 'self'`,
35
+ 'content-security-policy': MDX_SANDBOX_FRAME_POLICY,
28
36
  'x-content-type-options': 'nosniff',
29
37
  'cache-control': 'no-store',
30
38
  },
31
39
  });
40
+ }
41
+
42
+ export const GET: APIRoute = ({ request }) => sandboxFrameResponse(request);