@conloca/astro-cms 0.2.0 → 0.2.2

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 (98) hide show
  1. package/README.md +23 -20
  2. package/dist/internal/page-handler.astro +8 -2
  3. package/dist/ts/node/content.d.ts +1 -2
  4. package/dist/ts/node/content.d.ts.map +1 -1
  5. package/dist/ts/node/content.js +1 -1
  6. package/dist/ts/node/content.js.map +1 -1
  7. package/dist/ts/src/checks.d.ts +3 -3
  8. package/dist/ts/src/checks.d.ts.map +1 -1
  9. package/dist/ts/src/checks.js +3 -3
  10. package/dist/ts/src/checks.js.map +1 -1
  11. package/dist/ts/src/cms-handler.js +2 -1
  12. package/dist/ts/src/cms-handler.js.map +1 -1
  13. package/dist/ts/src/collections.d.ts +35 -56
  14. package/dist/ts/src/collections.d.ts.map +1 -1
  15. package/dist/ts/src/collections.js +77 -74
  16. package/dist/ts/src/collections.js.map +1 -1
  17. package/dist/ts/src/entries.d.ts +44 -0
  18. package/dist/ts/src/entries.d.ts.map +1 -0
  19. package/dist/ts/src/entries.js +48 -0
  20. package/dist/ts/src/entries.js.map +1 -0
  21. package/dist/ts/src/handlers/collection-content-api.d.ts.map +1 -1
  22. package/dist/ts/src/handlers/collection-content-api.js +7 -2
  23. package/dist/ts/src/handlers/collection-content-api.js.map +1 -1
  24. package/dist/ts/src/handlers/collection-names.d.ts +9 -0
  25. package/dist/ts/src/handlers/collection-names.d.ts.map +1 -0
  26. package/dist/ts/src/handlers/collection-names.js +9 -0
  27. package/dist/ts/src/handlers/collection-names.js.map +1 -0
  28. package/dist/ts/src/handlers/page-render-core.d.ts +31 -12
  29. package/dist/ts/src/handlers/page-render-core.d.ts.map +1 -1
  30. package/dist/ts/src/handlers/page-render-core.js +38 -17
  31. package/dist/ts/src/handlers/page-render-core.js.map +1 -1
  32. package/dist/ts/src/index.d.ts +2 -2
  33. package/dist/ts/src/index.d.ts.map +1 -1
  34. package/dist/ts/src/index.js +1 -3
  35. package/dist/ts/src/index.js.map +1 -1
  36. package/dist/ts/src/internal/collection-parsers.d.ts +26 -0
  37. package/dist/ts/src/internal/collection-parsers.d.ts.map +1 -0
  38. package/dist/ts/src/internal/collection-parsers.js +34 -0
  39. package/dist/ts/src/internal/collection-parsers.js.map +1 -0
  40. package/dist/ts/src/internal/entry-issues.d.ts +8 -0
  41. package/dist/ts/src/internal/entry-issues.d.ts.map +1 -0
  42. package/dist/ts/src/internal/entry-issues.js +19 -0
  43. package/dist/ts/src/internal/entry-issues.js.map +1 -0
  44. package/dist/ts/src/internal/entry-validation.d.ts +93 -0
  45. package/dist/ts/src/internal/entry-validation.d.ts.map +1 -0
  46. package/dist/ts/src/internal/entry-validation.js +228 -0
  47. package/dist/ts/src/internal/entry-validation.js.map +1 -0
  48. package/dist/ts/src/lib/content-config-guard.d.ts +2 -0
  49. package/dist/ts/src/lib/content-config-guard.d.ts.map +1 -1
  50. package/dist/ts/src/lib/content-config-guard.js +5 -1
  51. package/dist/ts/src/lib/content-config-guard.js.map +1 -1
  52. package/dist/ts/src/lib/virtual-module-generators.d.ts +13 -0
  53. package/dist/ts/src/lib/virtual-module-generators.d.ts.map +1 -1
  54. package/dist/ts/src/lib/virtual-module-generators.js +18 -0
  55. package/dist/ts/src/lib/virtual-module-generators.js.map +1 -1
  56. package/dist/ts/src/loader.d.ts +9 -12
  57. package/dist/ts/src/loader.d.ts.map +1 -1
  58. package/dist/ts/src/loader.js +19 -16
  59. package/dist/ts/src/loader.js.map +1 -1
  60. package/dist/ts/src/page-schemas.d.ts +1 -1
  61. package/dist/ts/src/page-schemas.d.ts.map +1 -1
  62. package/dist/ts/src/page-schemas.js +1 -1
  63. package/dist/ts/src/page-schemas.js.map +1 -1
  64. package/dist/ts/src/plugin-spa.d.ts +12 -0
  65. package/dist/ts/src/plugin-spa.d.ts.map +1 -1
  66. package/dist/ts/src/plugin-spa.js +33 -6
  67. package/dist/ts/src/plugin-spa.js.map +1 -1
  68. package/dist/ts/src/tiptap-html-static.d.ts +13 -12
  69. package/dist/ts/src/tiptap-html-static.d.ts.map +1 -1
  70. package/dist/ts/src/tiptap-html-static.js +104 -54
  71. package/dist/ts/src/tiptap-html-static.js.map +1 -1
  72. package/dist/virtual-modules.d.ts +14 -0
  73. package/node/content.ts +10 -1
  74. package/package.json +15 -10
  75. package/src/checks.ts +3 -2
  76. package/src/cms-handler.ts +2 -1
  77. package/src/collections.ts +119 -79
  78. package/src/entries.ts +111 -0
  79. package/src/handlers/collection-content-api.ts +7 -2
  80. package/src/handlers/collection-names.ts +8 -0
  81. package/src/handlers/page-handler.astro +8 -2
  82. package/src/handlers/page-render-core.ts +65 -17
  83. package/src/index.ts +6 -7
  84. package/src/internal/collection-parsers.ts +51 -0
  85. package/src/internal/entry-issues.ts +23 -0
  86. package/src/internal/entry-validation.ts +305 -0
  87. package/src/lib/content-config-guard.ts +8 -3
  88. package/src/lib/virtual-module-generators.ts +20 -0
  89. package/src/loader.ts +33 -17
  90. package/src/page-schemas.ts +4 -0
  91. package/src/plugin-spa.ts +49 -10
  92. package/src/tiptap-html-static.ts +114 -64
  93. package/src/virtual-modules.d.ts +14 -0
  94. package/dist/ts/src/internal/page-collection-schema.d.ts +0 -44
  95. package/dist/ts/src/internal/page-collection-schema.d.ts.map +0 -1
  96. package/dist/ts/src/internal/page-collection-schema.js +0 -152
  97. package/dist/ts/src/internal/page-collection-schema.js.map +0 -1
  98. package/src/internal/page-collection-schema.ts +0 -210
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@conloca/astro-cms",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -92,14 +92,16 @@
92
92
  "!**/*.tsbuildinfo"
93
93
  ],
94
94
  "dependencies": {
95
- "@conloca/cms-spa": "0.2.0",
96
- "@conloca/content-api": "0.2.0",
97
- "@conloca/mdx": "0.2.0",
95
+ "@conloca/cms-spa": "0.2.2",
96
+ "@conloca/content-api": "0.2.2",
97
+ "@conloca/mdx": "0.2.2",
98
98
  "@puckeditor/core": "^0.23.0",
99
- "@tiptap/static-renderer": "3.31.2",
99
+ "@tiptap/core": "^3.31.2",
100
+ "@tiptap/pm": "^3.31.2",
100
101
  "acorn": "^8.18.0",
101
102
  "clsx": "^2.1.1",
102
103
  "fast-glob": "^3.3.3",
104
+ "linkedom": "^0.18.13",
103
105
  "mdast-util-from-markdown": "^2.0.3",
104
106
  "mdast-util-mdx": "^3.0.0",
105
107
  "micromark-extension-mdxjs": "^3.0.0",
@@ -112,13 +114,12 @@
112
114
  "astro": "^7.3.1",
113
115
  "react": "^19.0.0",
114
116
  "react-dom": "^19.0.0",
115
- "vite": "^7.0.0 || ^8.0.0",
116
- "zod": "^4.5.4"
117
+ "vite": "^7.0.0 || ^8.0.0"
117
118
  },
118
119
  "devDependencies": {
119
120
  "@astrojs/check": "^0.9.10",
120
121
  "@astrojs/sitemap": "^3.7.3",
121
- "@happy-dom/global-registrator": "20.13.2",
122
+ "@happy-dom/global-registrator": "21.0.4",
122
123
  "@tiptap/extension-blockquote": "3.31.2",
123
124
  "@tiptap/extension-bold": "3.31.2",
124
125
  "@tiptap/extension-code": "3.31.2",
@@ -136,8 +137,12 @@
136
137
  "@tiptap/extension-text-align": "3.31.2",
137
138
  "@tiptap/extension-underline": "3.31.2",
138
139
  "@tiptap/html": "3.31.2",
140
+ "@ttsc/unplugin": "^0.30.4",
139
141
  "@vitejs/plugin-react": "^5.2.0",
140
142
  "astro": "^7.3.1",
143
+ "fast-check": "^4.9.0",
144
+ "ttsc": "0.30.4",
145
+ "typia": "^14.0.4",
141
146
  "vite": "^7.3.6"
142
147
  },
143
148
  "nx": {
@@ -212,9 +217,9 @@
212
217
  "{workspaceRoot}/example/website-with-cms/src/**/*"
213
218
  ],
214
219
  "options": {
215
- "command": "bun --conditions=production test",
220
+ "command": "bun test --timeout=0 --conditions=production --preload=./test-native-preload.ts",
216
221
  "cwd": "{projectRoot}",
217
- "timeoutMs": 120000,
222
+ "idleTimeoutMs": 180000,
218
223
  "killAfterMs": 10000
219
224
  }
220
225
  },
package/src/checks.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * Pure project-health helpers shared with external tooling (the conloca CLI's
3
- * doctor command). This entry must stay a leaf: node:fs and node:path only,
4
- * so importing it never pulls in the astro integration graph.
3
+ * doctor and page create commands). This entry must stay a leaf: node:fs and
4
+ * node:path only, so importing it never pulls in the astro integration graph.
5
5
  */
6
6
  export {
7
7
  CONTENT_CONFIG_SNIPPET,
8
8
  type ContentConfigProblem,
9
+ findContentConfig,
9
10
  findContentConfigProblem,
10
11
  } from './lib/content-config-guard.js';
@@ -229,7 +229,8 @@ async function handleContentApi(request: Request, cfResult: CFAccessResult): Pro
229
229
  // Create the Hono router with assets and content root for git operations
230
230
  const assetsPath = import.meta.env.CONLOCA_ASSETS_PATH || '';
231
231
  const app = createContentAPIRouter(contentApi, {
232
- ...(assetsPath && { assetsPath }),
232
+ // The editor stores image links under assetRefBase, so the usage lookup must search for that.
233
+ ...(assetsPath && { assetsPath, assetRefBase: spaConfig.assetRefBase }),
233
234
  contentRoot,
234
235
  });
235
236
 
@@ -1,15 +1,52 @@
1
1
  import { defineCollection } from 'astro:content';
2
- import type { DataSchemas, PageSchemas } from '@conloca/cms-spa/page-schema-define';
2
+ import type { DataSchemas, HostSchema, PageSchemas } from '@conloca/cms-spa/page-schema-define';
3
3
  import { createContentAPI } from '@conloca/content-api/reader';
4
- import { dataMetaSchema, fragmentMetaSchema, pageMetaSchema } from '@conloca/content-api/schemas';
5
- import { z } from 'zod';
6
- import { ALL_FRAGMENTS_COLLECTION } from './handlers/page-render-core.js';
4
+ import { parseLooseDataMeta } from '@conloca/content-api/schemas';
5
+ import type { Loader } from 'astro/loaders';
6
+ import { ALL_FRAGMENTS_COLLECTION } from './handlers/collection-names.js';
7
7
  import { declareConlocaCollection, withDeclarationCheck } from './internal/declared-collections.js';
8
- import { buildPageCollectionSchema, hostFieldsFromPageSchemas } from './internal/page-collection-schema.js';
8
+ import {
9
+ createDataEntryParser,
10
+ createPageEntryParser,
11
+ type EntryParser,
12
+ parseFragmentEntry,
13
+ } from './internal/entry-validation.js';
9
14
  import { conlocaLoader } from './loader.js';
10
15
 
16
+ export {
17
+ type CollectionEntryLike,
18
+ type ConlocaDataEntry,
19
+ type ConlocaFragmentEntry,
20
+ type ConlocaPageEntry,
21
+ conlocaDataEntries,
22
+ conlocaFragmentEntries,
23
+ conlocaPageEntries,
24
+ type TypedCollectionEntry,
25
+ } from './entries.js';
26
+ export type { EntryParser };
11
27
  export { ALL_FRAGMENTS_COLLECTION };
12
28
 
29
+ /**
30
+ * How every collection below is declared: a loader and NO `schema`.
31
+ *
32
+ * Astro's `schema` option only accepts Zod; it is optional, and without it
33
+ * `parseData` stores the loader's data unchanged. Validation therefore runs in
34
+ * the loader, before `store.set`, with the generated Typia validators for the
35
+ * collection (see `internal/entry-validation.ts`) — a stored entry that fails
36
+ * them still fails the build. Entry typing comes from the typed accessors
37
+ * (`conlocaPageEntries` / `conlocaDataEntries` / `conlocaFragmentEntries`),
38
+ * because Astro infers `getCollection` types from a Zod schema only.
39
+ */
40
+ function conlocaCollection(loader: Loader, parseEntry: EntryParser<Record<string, unknown>>) {
41
+ const defined = defineCollection({ loader });
42
+ entryParsersByCollection.set(defined, parseEntry);
43
+ return defined;
44
+ }
45
+
46
+ // The entry parser each Conloca-built collection's loader validates with, so a
47
+ // test (or a host) can run exactly the build's validation without a content root.
48
+ const entryParsersByCollection = new WeakMap<object, EntryParser<Record<string, unknown>>>();
49
+
13
50
  /**
14
51
  * Options for createConlocaCollections().
15
52
  */
@@ -23,8 +60,8 @@ export interface CreateConlocaCollectionsOptions {
23
60
  site?: string;
24
61
  /**
25
62
  * The same `pageSchemas` object the editor loads. Host meta fields are
26
- * validated on every page collection at build time (made optional, because
27
- * the editor scopes a descriptor to a prefix while Astro validates the
63
+ * validated on every page collection at build time (optional, because
64
+ * the editor scopes a descriptor to a prefix while Astro builds the
28
65
  * whole pile). Pass the object itself — not a hand-copied field list — so
29
66
  * the form and the build cannot drift. Listing types come from augmenting
30
67
  * `HostPageMeta`, not from Astro `entry.data`.
@@ -44,10 +81,8 @@ export interface ConlocaCollectionsResult {
44
81
 
45
82
  /**
46
83
  * @deprecated Declare collections explicitly with {@link conlocaPages},
47
- * {@link conlocaData} and {@link conlocaFragments} — they keep the entry
48
- * types Astro's generated `getCollection` needs, and undeclared content
49
- * fails the build instead of silently not building. This wrapper still
50
- * works but returns untyped entries.
84
+ * {@link conlocaData} and {@link conlocaFragments} — undeclared content fails
85
+ * the build instead of silently not building. This wrapper still works.
51
86
  *
52
87
  * Creates Astro Content Collections by discovering from indexed content.
53
88
  * Uses content-api to find collections that have content.
@@ -56,7 +91,7 @@ export interface ConlocaCollectionsResult {
56
91
  * ```typescript
57
92
  * // src/content.config.ts
58
93
  * import { createConlocaCollections } from '@conloca/astro-cms/node/content';
59
- * import { pageSchemas } from './page-schemas';
94
+ * import { pageSchemas } from './page-schemas.js';
60
95
  *
61
96
  * export const { collections } = await createConlocaCollections({ pageSchemas });
62
97
  * ```
@@ -73,37 +108,32 @@ export async function createConlocaCollections(
73
108
  const api = await createContentAPI({ contentRoot });
74
109
  const collections: Record<string, ReturnType<typeof defineCollection>> = {};
75
110
 
76
- collections[ALL_FRAGMENTS_COLLECTION] = defineCollection({
77
- loader: conlocaLoader({ contentRoot, site, kind: 'fragment' }),
78
- schema: fragmentMetaSchema.loose(),
79
- });
111
+ collections[ALL_FRAGMENTS_COLLECTION] = conlocaCollection(
112
+ conlocaLoader({ contentRoot, site, kind: 'fragment', parseEntry: parseFragmentEntry }),
113
+ parseFragmentEntry,
114
+ );
80
115
 
81
116
  for (const name of api.fragments.collections) {
82
- collections[name] = defineCollection({
83
- loader: conlocaLoader({ collection: name, contentRoot, site, kind: 'fragment' }),
84
- schema: fragmentMetaSchema.loose(),
85
- });
117
+ collections[name] = conlocaCollection(
118
+ conlocaLoader({ collection: name, contentRoot, site, kind: 'fragment', parseEntry: parseFragmentEntry }),
119
+ parseFragmentEntry,
120
+ );
86
121
  }
87
122
 
88
123
  for (const name of api.data.collections) {
89
- collections[name] = defineCollection({
90
- loader: conlocaLoader({ collection: name, contentRoot, site, kind: 'data' }),
91
- schema: dataMetaSchema.loose(),
92
- });
124
+ collections[name] = conlocaCollection(
125
+ conlocaLoader({ collection: name, contentRoot, site, kind: 'data', parseEntry: parseLooseDataMeta }),
126
+ parseLooseDataMeta,
127
+ );
93
128
  }
94
129
 
95
- const hostFields = pageSchemas ? hostFieldsFromPageSchemas(pageSchemas) : undefined;
96
- const pageSchema =
97
- hostFields && Object.keys(hostFields.shape).length > 0
98
- ? buildPageCollectionSchema(hostFields)
99
- : pageMetaSchema.loose();
100
-
130
+ const parsePage = createPageEntryParser(pageSchemas);
101
131
  const siteCollections = api.getSite(site)?.collections ?? new Set<string>();
102
132
  for (const name of siteCollections) {
103
- collections[name] = defineCollection({
104
- loader: conlocaLoader({ collection: name, contentRoot, site, kind: 'page' }),
105
- schema: pageSchema,
106
- });
133
+ collections[name] = conlocaCollection(
134
+ conlocaLoader({ collection: name, contentRoot, site, kind: 'page', parseEntry: parsePage }),
135
+ parsePage,
136
+ );
107
137
  }
108
138
 
109
139
  return { collections };
@@ -144,26 +174,35 @@ export function pageSchemasOf(collection: object): PageSchemas | undefined {
144
174
  }
145
175
 
146
176
  /**
147
- * One typed Astro collection for Conloca pages — the explicit,
148
- * Starlight-shaped declaration:
177
+ * The entry parser a Conloca-built collection's loader validates every entry
178
+ * with before storing it, or undefined for any other collection.
179
+ */
180
+ export function entryParserOf(collection: object): EntryParser<Record<string, unknown>> | undefined {
181
+ return entryParsersByCollection.get(collection);
182
+ }
183
+
184
+ /**
185
+ * One Astro collection for Conloca pages — the explicit, Starlight-shaped
186
+ * declaration:
149
187
  *
150
188
  * ```ts
151
189
  * export const collections = { pages: conlocaPages({ pageSchemas }) };
152
190
  * ```
153
191
  *
154
- * Entry data is typed as {@link ConlocaPageEntry}; `getCollection('pages')`
155
- * carries pathname/title/dates and the host's declared meta fields.
192
+ * Every page is validated as {@link ConlocaPageEntry} while it loads; read it
193
+ * typed with `conlocaPageEntries(await getCollection('pages'), pageSchemas)`.
156
194
  */
157
195
  export function conlocaPages(options: ConlocaPagesOptions = {}) {
158
196
  const { contentRoot = defaultContentRoot(), site = 'default', collection = 'pages', pageSchemas } = options;
159
197
  declareConlocaCollection('page', collection);
160
- const defined = defineCollection({
161
- loader: withDeclarationCheck(conlocaLoader({ collection, contentRoot, site, kind: 'page' }), {
198
+ const parseEntry = createPageEntryParser(pageSchemas);
199
+ const defined = conlocaCollection(
200
+ withDeclarationCheck(conlocaLoader({ collection, contentRoot, site, kind: 'page', parseEntry }), {
162
201
  contentRoot,
163
202
  site,
164
203
  }),
165
- schema: buildPageCollectionSchema(pageSchemas ? hostFieldsFromPageSchemas(pageSchemas) : z.object({})),
166
- });
204
+ parseEntry,
205
+ );
167
206
  if (pageSchemas) pageSchemasByCollection.set(defined, pageSchemas);
168
207
  return defined;
169
208
  }
@@ -184,69 +223,70 @@ export interface ConlocaDataOptions<DS extends DataSchemas> {
184
223
 
185
224
  /**
186
225
  * Deliberate asymmetry with pages: a data schema is validated AS GIVEN —
187
- * requiredness preserved, no rewrite guard — because the site owns it whole
188
- * for exactly one collection, unlike host page fields folded into the shared
189
- * pages schema. The flip side, accepted for now: a .transform or .default in
190
- * a dataSchema runs at build time but not in the editor form, so the two can
191
- * diverge.
226
+ * requiredness preserved — because the site owns it whole for exactly one
227
+ * collection, unlike host page fields checked across the shared pages pile.
192
228
  */
193
- function conlocaDataCollection<T extends z.ZodObject<z.ZodRawShape>>(
194
- name: string,
195
- payload: T,
196
- contentRoot: string,
197
- site: string,
198
- ) {
199
- return defineCollection({
200
- loader: withDeclarationCheck(conlocaLoader({ collection: name, contentRoot, site, kind: 'data' }), {
229
+ function conlocaDataCollection(name: string, payload: HostSchema, contentRoot: string, site: string) {
230
+ const parseEntry = createDataEntryParser(payload);
231
+ return conlocaCollection(
232
+ withDeclarationCheck(conlocaLoader({ collection: name, contentRoot, site, kind: 'data', parseEntry }), {
201
233
  contentRoot,
202
234
  site,
203
235
  }),
204
- // Base meta plus this collection's payload under `data`. `data` stays
205
- // optional: an entry saved before any payload exists is not an error.
206
- schema: z.looseObject({ ...dataMetaSchema.shape, data: payload.optional() }),
207
- });
236
+ parseEntry,
237
+ );
208
238
  }
209
239
 
210
240
  /**
211
- * Typed Astro collections for Conloca data, one per `dataSchemas` key:
241
+ * Astro collections for Conloca data, one per `dataSchemas` key:
212
242
  *
213
243
  * ```ts
214
244
  * export const collections = { ...conlocaData({ dataSchemas }) };
215
245
  * ```
216
246
  *
217
- * `getCollection('testimonials')` entries carry `data` typed by that key's
218
- * schema, and a stored entry that fails its schema fails the build instead
219
- * of rendering blank.
247
+ * A stored entry whose payload fails its schema fails the build instead of
248
+ * rendering blank. Read entries typed by that key's schema with
249
+ * `conlocaDataEntries(dataSchemas, 'testimonials', await getCollection('testimonials'))`.
220
250
  */
221
251
  export function conlocaData<DS extends DataSchemas>(options: ConlocaDataOptions<DS>) {
222
252
  const { dataSchemas, contentRoot = defaultContentRoot(), site = 'default' } = options;
223
- const entries = Object.entries(dataSchemas).map(([name, payload]) => {
253
+ const collections: Record<string, ReturnType<typeof conlocaDataCollection>> = {};
254
+ for (const [name, payload] of Object.entries(dataSchemas)) {
224
255
  declareConlocaCollection('data', name);
225
- return [name, conlocaDataCollection(name, payload, contentRoot, site)] as const;
226
- });
227
- // Object.fromEntries erases per-key types; the assertion restores exactly
228
- // what the loop built — one collection per dataSchemas key.
229
- return Object.fromEntries(entries) as { [K in keyof DS]: ReturnType<typeof conlocaDataCollection<DS[K]>> };
256
+ collections[name] = conlocaDataCollection(name, payload, contentRoot, site);
257
+ }
258
+ // The loop built exactly one collection per dataSchemas key; the record type
259
+ // keeps those keys for the content.config `collections` export.
260
+ return collections as { [K in keyof DS]: ReturnType<typeof conlocaDataCollection> };
230
261
  }
231
262
 
263
+ /**
264
+ * The folder the editor saves every new fragment to (content/fragments/fragments/).
265
+ * Every conlocaFragments call declares it, so a fragment made in the editor
266
+ * never fails the build of a site whose config does not name that folder.
267
+ */
268
+ const EDITOR_FRAGMENT_FOLDER = 'fragments';
269
+
232
270
  /**
233
271
  * The fragments aggregate (always) plus one collection per named fragment
234
272
  * folder: `...conlocaFragments('general')`. No arguments declares only the
235
- * aggregate the render pipeline reads. There are no per-call options:
236
- * contentRoot comes from conlocaCMS()'s contentRoot (via
237
- * CONLOCA_CONTENT_ROOT) and the site is always 'default'.
273
+ * aggregate the render pipeline reads. Every form also declares the folder
274
+ * the editor saves new fragments to, without returning a collection for it.
275
+ * There are no per-call options: contentRoot comes from conlocaCMS()'s
276
+ * contentRoot (via CONLOCA_CONTENT_ROOT) and the site is always 'default'.
238
277
  */
239
278
  export function conlocaFragments<const N extends readonly string[]>(...names: N) {
240
279
  const contentRoot = defaultContentRoot();
241
280
  const site = 'default';
281
+ declareConlocaCollection('fragment', EDITOR_FRAGMENT_FOLDER);
242
282
  const fragmentCollection = (collection?: string) =>
243
- defineCollection({
244
- loader: withDeclarationCheck(conlocaLoader({ collection, contentRoot, site, kind: 'fragment' }), {
245
- contentRoot,
246
- site,
247
- }),
248
- schema: fragmentMetaSchema.loose(),
249
- });
283
+ conlocaCollection(
284
+ withDeclarationCheck(
285
+ conlocaLoader({ collection, contentRoot, site, kind: 'fragment', parseEntry: parseFragmentEntry }),
286
+ { contentRoot, site },
287
+ ),
288
+ parseFragmentEntry,
289
+ );
250
290
  const named = Object.fromEntries(
251
291
  names.map((name) => {
252
292
  declareConlocaCollection('fragment', name);
package/src/entries.ts ADDED
@@ -0,0 +1,111 @@
1
+ import type { DataSchemas, HostSchemaType, PageSchemas } from '@conloca/cms-spa/page-schema-define';
2
+ import { describeEntryIssues } from './internal/entry-issues.js';
3
+ import {
4
+ type ConlocaDataEntry,
5
+ type ConlocaFragmentEntry,
6
+ type ConlocaPageEntry,
7
+ createDataEntryParser,
8
+ createPageEntryParser,
9
+ type EntryParser,
10
+ parseFragmentEntry,
11
+ } from './internal/entry-validation.js';
12
+
13
+ /**
14
+ * Typed reads of Conloca collections.
15
+ *
16
+ * Astro types `getCollection()` entries from a collection's Zod `schema`; the
17
+ * Conloca factories declare none (the loader validates with generated Typia
18
+ * validators instead), so Astro's own entry type for them is `any`. These
19
+ * accessors take what `getCollection()` returned and hand back entries typed
20
+ * by the same declarations the build validated with — re-running those
21
+ * validators, so the type is earned at runtime rather than asserted:
22
+ *
23
+ * ```ts
24
+ * import { getCollection } from 'astro:content';
25
+ * import { conlocaPageEntries } from '@conloca/astro-cms/collections';
26
+ * import { pageSchemas } from '../page-schemas';
27
+ *
28
+ * const pages = conlocaPageEntries(await getCollection('pages'), pageSchemas);
29
+ * pages[0].data.title; // string
30
+ * ```
31
+ *
32
+ * They take the entries rather than calling `getCollection` themselves so they
33
+ * stay importable (and testable) outside Astro's virtual modules.
34
+ *
35
+ * Each call re-validates every entry it is given; call once per collection
36
+ * read (e.g. in `getStaticPaths` or once per page) rather than per access.
37
+ */
38
+
39
+ /** The fields every Astro collection entry carries besides `data`. */
40
+ export interface CollectionEntryLike {
41
+ id: string;
42
+ data: unknown;
43
+ }
44
+
45
+ /** An Astro collection entry with `data` replaced by its validated, typed form. */
46
+ export type TypedCollectionEntry<E extends CollectionEntryLike, T> = Omit<E, 'data'> & { data: T };
47
+
48
+ // Parsers fold descriptors and compare generated schemas once per registry, not
49
+ // once per read: the registries are module constants in a site's config.
50
+ const pageParsers = new WeakMap<PageSchemas, EntryParser<ConlocaPageEntry>>();
51
+ const dataParsers = new WeakMap<object, EntryParser<ConlocaDataEntry<object>>>();
52
+ const corePageParser = createPageEntryParser();
53
+
54
+ function isRecord(value: unknown): value is Record<string, unknown> {
55
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
56
+ }
57
+
58
+ function typedEntries<E extends CollectionEntryLike, T>(
59
+ entries: readonly E[],
60
+ parse: EntryParser<T>,
61
+ collection: string,
62
+ ): TypedCollectionEntry<E, T>[] {
63
+ return entries.map((entry) => {
64
+ if (!isRecord(entry.data)) {
65
+ throw new Error(`[conloca] ${collection} entry "${entry.id}" has no data record`);
66
+ }
67
+ const result = parse(entry.data);
68
+ if (!result.success) {
69
+ throw new Error(describeEntryIssues(result.issues, { collection, id: entry.id }));
70
+ }
71
+ return { ...entry, data: result.data };
72
+ });
73
+ }
74
+
75
+ /** `getCollection('pages')` entries, validated and typed as {@link ConlocaPageEntry}. */
76
+ export function conlocaPageEntries<E extends CollectionEntryLike>(
77
+ entries: readonly E[],
78
+ pageSchemas?: PageSchemas,
79
+ ): TypedCollectionEntry<E, ConlocaPageEntry>[] {
80
+ let parse = corePageParser;
81
+ if (pageSchemas) {
82
+ parse = pageParsers.get(pageSchemas) ?? createPageEntryParser(pageSchemas);
83
+ pageParsers.set(pageSchemas, parse);
84
+ }
85
+ return typedEntries(entries, parse, 'pages');
86
+ }
87
+
88
+ /** A `conlocaData` collection's entries, with `data` validated and typed by that key's host schema. */
89
+ export function conlocaDataEntries<E extends CollectionEntryLike, DS extends DataSchemas, K extends keyof DS & string>(
90
+ dataSchemas: DS,
91
+ collection: K,
92
+ entries: readonly E[],
93
+ ): TypedCollectionEntry<E, ConlocaDataEntry<HostSchemaType<DS[K]>>>[] {
94
+ const payload: DataSchemas[string] | undefined = dataSchemas[collection];
95
+ if (!payload) throw new Error(`[conloca] dataSchemas declares no collection "${collection}"`);
96
+ const parse = dataParsers.get(payload) ?? createDataEntryParser(payload);
97
+ dataParsers.set(payload, parse);
98
+ // `payload` is `dataSchemas[collection]`, so its generated validator checks
99
+ // exactly `HostSchemaType<DS[K]>`; TypeScript cannot follow an indexed
100
+ // generic through the registry lookup, so the parser is re-typed here.
101
+ return typedEntries(entries, parse as EntryParser<ConlocaDataEntry<HostSchemaType<DS[K]>>>, collection);
102
+ }
103
+
104
+ /** Fragment collection entries, validated and typed as {@link ConlocaFragmentEntry}. */
105
+ export function conlocaFragmentEntries<E extends CollectionEntryLike>(
106
+ entries: readonly E[],
107
+ ): TypedCollectionEntry<E, ConlocaFragmentEntry>[] {
108
+ return typedEntries(entries, parseFragmentEntry, 'fragments');
109
+ }
110
+
111
+ export type { ConlocaDataEntry, ConlocaFragmentEntry, ConlocaPageEntry };
@@ -35,7 +35,8 @@ import type {
35
35
  UpdateResult,
36
36
  } from '@conloca/content-api';
37
37
  import type { ResolvedRoutingConfig } from '../types.js';
38
- import { ALL_FRAGMENTS_COLLECTION } from './page-render-core.js';
38
+ import { ALL_FRAGMENTS_COLLECTION } from './collection-names.js';
39
+ import { rememberBuiltRecord } from './page-render-core.js';
39
40
 
40
41
  interface CollectionEntry {
41
42
  data: Record<string, unknown>;
@@ -126,7 +127,11 @@ export async function createCollectionBackedContentAPI(opts: CollectionBackedCon
126
127
  if (locale === undefined) continue;
127
128
  const { version, content } = splitRecord(record);
128
129
  locales[locale] = version;
129
- entries.set(`${id} ${locale}`, { ...identity, localized: { ...version, content } });
130
+ const entry: LocalizedEntry = { ...identity, localized: { ...version, content } };
131
+ // The record is the build's parse output; a reader source hands it
132
+ // out as is instead of parsing what was reconstructed from it.
133
+ rememberBuiltRecord(entry, record);
134
+ entries.set(`${id} ${locale}`, entry);
130
135
  }
131
136
  manifests.push({ ...identity, locales });
132
137
  }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Synthetic collection every discovered fragment lands in (the loader flattens
3
+ * all fragment collections into one). A leaf module on purpose: the render core
4
+ * must stay free of the `astro:content` that `collections.ts` pulls in, and the
5
+ * content config that `collections.ts` runs in must not load the render core's
6
+ * Puck and React graph just to name a collection. Both re-export it.
7
+ */
8
+ export const ALL_FRAGMENTS_COLLECTION = '__conloca_fragments';
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  import { getCollection } from 'astro:content';
13
+ import { loadContentSchemas } from 'virtual:conloca-content-schemas';
13
14
  import Layout from 'virtual:conloca-layout';
14
15
  import puckConfig from 'virtual:conloca-puck-config';
15
16
  import routingConfig from 'virtual:conloca-routing-config';
@@ -37,6 +38,7 @@ import {
37
38
  pageNotFoundResponse,
38
39
  resolvePuckData,
39
40
  } from '../ts/src/handlers/page-render-core.js';
41
+ import { previewEntryParsers } from '../ts/src/internal/collection-parsers.js';
40
42
 
41
43
  // prerender is controlled by injectRoute({ prerender }) in plugin-spa.ts
42
44
  // Do not hardcode here — it overrides the route-level config
@@ -148,11 +150,15 @@ if (!routeName || !collection || !pathname) {
148
150
 
149
151
  // Content-access seam. A caller can install a ContentAPI on
150
152
  // `Astro.locals.contentApi`; when present we read through it, so the page shows
151
- // what that reader serves. Absent — the normal render — we read Astro content
153
+ // what that reader serves, parsed with each collection's entry parser as the build
154
+ // parses its entries. Absent — the normal render — we read Astro content
152
155
  // collections, byte-for-byte identically to before the extraction.
153
156
  const previewContentApi = (Astro.locals as { contentApi?: ContentAPI }).contentApi;
154
157
  const source: PageContentSource = previewContentApi
155
- ? createReaderContentSource(previewContentApi, config.locale)
158
+ ? createReaderContentSource(previewContentApi, {
159
+ renderLocale: config.locale,
160
+ parsers: previewEntryParsers(config, await loadContentSchemas()),
161
+ })
156
162
  : createCollectionContentSource({
157
163
  getCollection: (name) => getCollection(name as never) as Promise<{ data: unknown }[]>,
158
164
  isDev: import.meta.env.DEV,