@conloca/astro-cms 0.1.0

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.
@@ -0,0 +1,298 @@
1
+ ---
2
+ /**
3
+ * Page Handler Component
4
+ *
5
+ * This Astro component is injected via injectRoute() to handle content pages.
6
+ * It implements getStaticPaths() for static page generation and renders
7
+ * content using the Puck Render component with an optional Layout wrapper.
8
+ *
9
+ * MDX blocks are evaluated at build time and rendered as React components.
10
+ */
11
+
12
+ import { Render, resolveAllData } from '@measured/puck';
13
+ import type { ComponentType } from 'react';
14
+
15
+ // MDX evaluation imports
16
+ import { createContentAPI } from '@conloca/content-api/node';
17
+ import { evaluateMDXBlocks } from '@conloca/mdx/node';
18
+ import { createPageRendererWithBlocks } from '../components/RenderWithBlocks.js';
19
+
20
+ // Hydration support
21
+ import { hasHydratableComponents } from '../lib/hydration-utils.js';
22
+ import { RenderWithHydration } from '../components/RenderWithHydration.js';
23
+
24
+ // Virtual modules configured by the Vite plugin
25
+ import routingConfig from 'virtual:conloca-routing-config';
26
+ import Layout from 'virtual:conloca-layout';
27
+ import { getAllPages, getPage, getDataCollection, getPagesByPrefix, contentOptions } from 'virtual:conloca-page-api';
28
+ import puckConfig from 'virtual:conloca-puck-config';
29
+
30
+ // Route utilities for slug extraction
31
+ import { extractSlugFromPathname } from '../lib/route-utils.js';
32
+
33
+ import type { GetStaticPaths } from 'astro';
34
+ import type { DataCollectionEntry, DataContext, PageData, PageReference, ResolvedRoutingConfig } from '../types.js';
35
+
36
+ // Default to prerender: true for static site generation
37
+ export const prerender = true;
38
+
39
+ /**
40
+ * Generate static paths for all content pages.
41
+ *
42
+ * Iterates through all configured routes and their collections
43
+ * to discover pages and generate the params/props for each.
44
+ */
45
+ export const getStaticPaths: GetStaticPaths = async () => {
46
+ // Import config inside getStaticPaths to ensure it's available at build time
47
+ // (Astro hoists getStaticPaths and runs it before module initialization)
48
+ const config = routingConfig as ResolvedRoutingConfig;
49
+
50
+ const paths: {
51
+ params: { slug: string | undefined };
52
+ props: { routeName: string; collection: string; pathname: string };
53
+ }[] = [];
54
+
55
+ // Skip if routing is disabled
56
+ if (!config.enabled) {
57
+ return paths;
58
+ }
59
+
60
+ // For each configured route
61
+ for (const [routeName, routeConfig] of Object.entries(config.routes)) {
62
+ try {
63
+ // Get all pages from this route's collection
64
+ const pages = await getAllPages(routeConfig.collection);
65
+
66
+ for (const page of pages) {
67
+ // Convert pathname to slug params
68
+ // Pattern: /blog/[...slug] + pathname: /blog/post-1 = slug: 'post-1'
69
+ const slug = extractSlugFromPathname(page.pathname, routeConfig.pattern);
70
+
71
+ paths.push({
72
+ params: { slug },
73
+ props: {
74
+ routeName,
75
+ collection: routeConfig.collection,
76
+ pathname: page.pathname,
77
+ },
78
+ });
79
+ }
80
+ } catch (error) {
81
+ console.error(`[Conloca] Error loading pages for route '${routeName}':`, error);
82
+ }
83
+ }
84
+
85
+ return paths;
86
+ };
87
+
88
+ // Props passed from getStaticPaths
89
+ interface Props {
90
+ routeName: string;
91
+ collection: string;
92
+ pathname: string;
93
+ }
94
+
95
+ const { routeName, collection, pathname } = Astro.props as Props;
96
+
97
+ // Cast routing config for component body
98
+ const config = routingConfig as ResolvedRoutingConfig;
99
+
100
+ // Load page data
101
+ let page: PageData | undefined;
102
+ let loadError: Error | undefined;
103
+
104
+ try {
105
+ page = await getPage(pathname, collection);
106
+
107
+ // Enrich with route information
108
+ if (page && config.routes[routeName]) {
109
+ const routeConfig = config.routes[routeName];
110
+ page.route = {
111
+ name: routeName,
112
+ pattern: routeConfig.pattern,
113
+ meta: routeConfig.meta,
114
+ };
115
+ }
116
+ } catch (error) {
117
+ loadError = error as Error;
118
+
119
+ // Handle 404 based on fallback configuration
120
+ if ((error as { code?: string }).code === 'PAGE_NOT_FOUND') {
121
+ if (config.fallback === 'passthrough') {
122
+ // Let Astro continue to next route
123
+ return Astro.redirect('/404', 307);
124
+ }
125
+ // Return 404 response
126
+ return new Response('Page not found', { status: 404 });
127
+ }
128
+
129
+ // Re-throw other errors
130
+ throw error;
131
+ }
132
+
133
+ // Build metadata with collection data for resolvers
134
+ let dataContext: DataContext | undefined;
135
+
136
+ const routeConfig = config.routes[routeName];
137
+ const hasCollections = routeConfig?.dataBindings?.collections?.length;
138
+ const hasPages = routeConfig?.dataBindings?.pages?.prefix;
139
+
140
+ if (hasCollections || hasPages) {
141
+ const collections: Record<string, DataCollectionEntry[]> = {};
142
+ let pages: PageReference[] | undefined;
143
+
144
+ // Fetch collections
145
+ if (hasCollections) {
146
+ for (const collectionName of routeConfig.dataBindings.collections) {
147
+ try {
148
+ const locale = routeConfig.dataBindings.locale ?? contentOptions.locale;
149
+ collections[collectionName] = await getDataCollection(collectionName, locale);
150
+ } catch (error) {
151
+ console.error(`[Conloca] Failed to fetch collection '${collectionName}':`, error);
152
+ collections[collectionName] = [];
153
+ }
154
+ }
155
+ }
156
+
157
+ // Fetch pages by prefix
158
+ if (hasPages) {
159
+ try {
160
+ const pagesConfig = routeConfig.dataBindings.pages;
161
+ pages = await getPagesByPrefix(pagesConfig.prefix, {
162
+ sort: pagesConfig.sort,
163
+ limit: pagesConfig.limit,
164
+ });
165
+ } catch (error) {
166
+ console.error(`[Conloca] Failed to fetch pages with prefix '${routeConfig.dataBindings.pages.prefix}':`, error);
167
+ pages = [];
168
+ }
169
+ }
170
+
171
+ dataContext = {
172
+ collections,
173
+ pages,
174
+ locale: routeConfig.dataBindings.locale ?? contentOptions.locale,
175
+ siteName: contentOptions.siteName,
176
+ };
177
+ }
178
+
179
+ // Handle missing puckData gracefully
180
+ const hasPuckData = page?.puckData && Object.keys(page.puckData).length > 0;
181
+
182
+ // Resolve component data if we have bindings
183
+ let resolvedPuckData = page?.puckData;
184
+
185
+ if (hasPuckData && page && dataContext) {
186
+ try {
187
+ resolvedPuckData = await resolveAllData(page.puckData, puckConfig, {
188
+ metadata: dataContext,
189
+ });
190
+ } catch (error) {
191
+ console.error('[Conloca] resolveAllData failed:', error);
192
+ // Fall back to original puckData if resolution fails
193
+ }
194
+ }
195
+
196
+ // Check if page has hydratable components (for conditional script injection)
197
+ const needsHydration = hasPuckData && resolvedPuckData && hasHydratableComponents(resolvedPuckData, puckConfig);
198
+
199
+ // Create PageRenderer with MDX blocks support
200
+ // This evaluates all MDX blocks at build time and creates a renderer with them baked in
201
+ let PageRenderer: ComponentType | undefined;
202
+
203
+ if (hasPuckData && page && resolvedPuckData) {
204
+ try {
205
+ // Create ContentAPI for MDX evaluation using options from virtual module
206
+ const contentApi = await createContentAPI({
207
+ contentRoot: contentOptions.contentRoot,
208
+ canvasDir: contentOptions.canvasDir,
209
+ });
210
+
211
+ // Evaluate MDX blocks - converts MDX content to React components
212
+ const mdxComponents = await evaluateMDXBlocks(contentApi, contentOptions.locale);
213
+
214
+ // Create renderer with MDX components baked in via closure
215
+ PageRenderer = createPageRendererWithBlocks(puckConfig, resolvedPuckData, mdxComponents);
216
+ } catch (error) {
217
+ // If MDX evaluation fails, log and fall back to plain Render
218
+ console.error('[Conloca] MDX evaluation failed, falling back to plain render:', error);
219
+ PageRenderer = undefined;
220
+ }
221
+ }
222
+ ---
223
+
224
+ {Layout && page ? (
225
+ <Layout title={page.title ?? 'Page'} description={page.description}>
226
+ {hasPuckData && PageRenderer ? (
227
+ <PageRenderer />
228
+ ) : hasPuckData && resolvedPuckData ? (
229
+ needsHydration ? (
230
+ <RenderWithHydration config={puckConfig} data={resolvedPuckData} />
231
+ ) : (
232
+ <Render config={puckConfig} data={resolvedPuckData} />
233
+ )
234
+ ) : (
235
+ <div class="conloca-empty-page">
236
+ <p>This page has no content yet.</p>
237
+ </div>
238
+ )}
239
+ </Layout>
240
+ ) : page ? (
241
+ <html lang="en">
242
+ <head>
243
+ <meta charset="UTF-8" />
244
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
245
+ <title>{page.title || 'Untitled'}</title>
246
+ {page.description && <meta name="description" content={page.description} />}
247
+ {needsHydration && <script>import 'virtual:conloca-hydration-entry'</script>}
248
+ </head>
249
+ <body>
250
+ {hasPuckData && PageRenderer ? (
251
+ <PageRenderer />
252
+ ) : hasPuckData && resolvedPuckData ? (
253
+ needsHydration ? (
254
+ <RenderWithHydration config={puckConfig} data={resolvedPuckData} />
255
+ ) : (
256
+ <Render config={puckConfig} data={resolvedPuckData} />
257
+ )
258
+ ) : (
259
+ <div class="conloca-empty-page">
260
+ <p>This page has no content yet.</p>
261
+ </div>
262
+ )}
263
+ </body>
264
+ </html>
265
+ ) : (
266
+ <html lang="en">
267
+ <head>
268
+ <meta charset="UTF-8" />
269
+ <title>Error</title>
270
+ </head>
271
+ <body>
272
+ <div class="conloca-error">
273
+ <h1>Error Loading Page</h1>
274
+ <p>{loadError?.message || 'An unknown error occurred.'}</p>
275
+ </div>
276
+ </body>
277
+ </html>
278
+ )}
279
+
280
+ {/* Hydration script - conditionally loaded only on pages with hydratable components */}
281
+ {Layout && needsHydration && <script>import 'virtual:conloca-hydration-entry'</script>}
282
+
283
+ <style>
284
+ .conloca-empty-page {
285
+ padding: 2rem;
286
+ text-align: center;
287
+ color: #666;
288
+ }
289
+
290
+ .conloca-error {
291
+ padding: 2rem;
292
+ text-align: center;
293
+ }
294
+
295
+ .conloca-error h1 {
296
+ color: #c00;
297
+ }
298
+ </style>
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Type declarations for Conloca virtual modules.
3
+ *
4
+ * These modules are generated at build/dev time by the Vite plugin
5
+ * and provide routing configuration, layout components, page API,
6
+ * and Puck config to page handlers.
7
+ */
8
+
9
+ import type { Config } from '@measured/puck';
10
+
11
+ import type { LayoutProps, PageData, PageReference, ResolvedRoutingConfig } from './types.js';
12
+
13
+ /**
14
+ * Virtual module: virtual:conloca-routing-config
15
+ *
16
+ * Provides resolved routing configuration to page handlers.
17
+ * All defaults are applied before this module is generated.
18
+ */
19
+ declare module 'virtual:conloca-routing-config' {
20
+ const config: ResolvedRoutingConfig;
21
+ export default config;
22
+ }
23
+
24
+ /**
25
+ * Virtual module: virtual:conloca-layout
26
+ *
27
+ * Provides the layout component for content pages.
28
+ * Returns undefined if no layout is configured.
29
+ *
30
+ * Currently uses the first route's layout - multi-layout support
31
+ * is planned for future versions.
32
+ */
33
+ declare module 'virtual:conloca-layout' {
34
+ type LayoutComponent = ((props: LayoutProps) => unknown) | undefined;
35
+
36
+ const Layout: LayoutComponent;
37
+ export default Layout;
38
+ }
39
+
40
+ /**
41
+ * Virtual module: virtual:conloca-page-api
42
+ *
43
+ * Provides page loading functions wrapping ContentAPI.
44
+ * Used by page-handler.astro for:
45
+ * - getStaticPaths(): getAllPages()
46
+ * - Page rendering: getPage()
47
+ * - 404 checks: pageExists()
48
+ * - MDX evaluation: contentOptions
49
+ */
50
+ declare module 'virtual:conloca-page-api' {
51
+ /**
52
+ * Content configuration options for ContentAPI initialization.
53
+ * Useful for creating additional ContentAPI instances (e.g., for MDX evaluation).
54
+ */
55
+ export const contentOptions: {
56
+ /** Path to content directory */
57
+ contentRoot: string;
58
+ /** Path to canvas/puck directory */
59
+ canvasDir: string;
60
+ /** Site name for content resolution */
61
+ siteName: string;
62
+ /** Default locale for content resolution */
63
+ locale: string;
64
+ };
65
+
66
+ /**
67
+ * Get all pages for static path generation.
68
+ * @param collection - Optional collection filter (defaults to all collections)
69
+ * @returns Array of page references with id, pathname, title, collection
70
+ */
71
+ export function getAllPages(collection?: string): Promise<PageReference[]>;
72
+
73
+ /**
74
+ * Load full page data for rendering.
75
+ * @param pathname - URL pathname (e.g., '/about')
76
+ * @param collection - Optional collection to search in
77
+ * @returns Full page data including puckData for rendering
78
+ * @throws Error with code 'PAGE_NOT_FOUND' if page doesn't exist
79
+ */
80
+ export function getPage(pathname: string, collection?: string): Promise<PageData>;
81
+
82
+ /**
83
+ * Check if a page exists without loading full data.
84
+ * @param pathname - URL pathname
85
+ * @param collection - Optional collection filter
86
+ * @returns true if page exists, false otherwise
87
+ */
88
+ export function pageExists(pathname: string, collection?: string): Promise<boolean>;
89
+
90
+ /**
91
+ * Get all entries from a data collection.
92
+ *
93
+ * Fetches all entries from a data collection and returns them as
94
+ * simplified DataCollectionEntry objects for use in Puck component resolvers.
95
+ *
96
+ * @param collection - Data collection name
97
+ * @param locale - Optional locale override (defaults to configured locale)
98
+ * @returns Array of DataCollectionEntry objects with id, name, data, and meta
99
+ */
100
+ export function getDataCollection(
101
+ collection: string,
102
+ locale?: string,
103
+ ): Promise<import('./types').DataCollectionEntry[]>;
104
+
105
+ /**
106
+ * Get pages matching a path prefix.
107
+ *
108
+ * Filters all pages by pathname prefix and returns them sorted.
109
+ * Excludes the listing page itself (exact prefix match).
110
+ *
111
+ * @param prefix - Path prefix to match (e.g., '/blog/')
112
+ * @param options - Optional sort and limit settings
113
+ * @returns Array of PageReference objects with meta and timestamps
114
+ *
115
+ * @example Get latest 10 blog posts
116
+ * ```typescript
117
+ * const posts = await getPagesByPrefix('/blog/', {
118
+ * sort: 'date-desc',
119
+ * limit: 10,
120
+ * });
121
+ * ```
122
+ */
123
+ export function getPagesByPrefix(
124
+ prefix: string,
125
+ options?: {
126
+ sort?: 'date-desc' | 'date-asc' | 'title';
127
+ limit?: number;
128
+ },
129
+ ): Promise<PageReference[]>;
130
+ }
131
+
132
+ /**
133
+ * Virtual module: virtual:conloca-puck-config
134
+ *
135
+ * Provides Puck configuration for static page rendering.
136
+ *
137
+ * This is separate from the HMR-enabled puck-entry.js used by
138
+ * the CMS SPA. It's a simple re-export without React refresh
139
+ * preamble since it's used for SSG builds.
140
+ */
141
+ declare module 'virtual:conloca-puck-config' {
142
+ const config: Config;
143
+ export default config;
144
+ }