ferst-core 0.13.0 → 0.15.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.
package/content/blocks.ts CHANGED
@@ -262,19 +262,33 @@ export const payBlock = z.object({
262
262
  });
263
263
 
264
264
  /** Visitors book a time for one of the organisation's offers, from the Ferst Events and bookings
265
- * module ("Haircut", 30 minutes). The block names the offer; its name, length, who gives it and
266
- * its free times are the organisation's, read from the platform (lib/book), never written here.
267
- * A picked time is held for the visitor while they give their details, then booked; the visitor
268
- * is emailed. List what a site takes bookings for with `npx ferst-modules`. */
265
+ * module ("Haircut", 30 minutes). The block names the offer, a person or a place (everything they
266
+ * provide online, the visitor choosing which), or both (that offer with them only); one of the
267
+ * two is needed. Names, lengths, prices, who gives it and the free times are the organisation's,
268
+ * read from the platform (lib/book), never written here. A picked time is held for the visitor
269
+ * while they give their details, then booked; the visitor is emailed. List what a site takes
270
+ * bookings for, and who provides it, with `npx ferst-modules`. */
269
271
  export const bookBlock = z.object({
270
272
  type: z.literal('book'),
271
273
  enabled: z.boolean().default(true),
272
274
  /** The offer's id in the portal (e.g. `evs_8c1d…`). */
273
- service: z.string().min(1),
275
+ service: z.string().min(1).optional(),
276
+ /** A person's or a place's id in the portal (e.g. `evr_3f2a…`): what they provide online, booked with them. */
277
+ resource: z.string().min(1).optional(),
274
278
  /** One event of it (e.g. `eve_…`, the Christmas concert): only that event's dates. Left out: all of them. */
275
279
  event: z.string().min(1).optional(),
276
- /** Defaults to the offer's name. */
280
+ /** `button`: "Book now" for one date of a class or an event, with only the booker's details left
281
+ * (the maintainer, 2026-11-24). Its next date with places, or `date`. Left out: the calendar or list. */
282
+ look: z.enum(['button']).optional(),
283
+ /** With `look: button`: one date of a repeating event ('YYYY-MM-DDTHH:MM', London). Left out: the next with places. */
284
+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/).optional(),
285
+ /** A list of dates across chosen classes and events, in place of `service` (the maintainer, 2026-11-24:
286
+ * "a custom block where we pick what event types we want to group to display as a single list"):
287
+ * each an offer booked by places (all its events), or one event of it. */
288
+ list: z.array(z.object({ service: z.string().min(1), event: z.string().min(1).optional() })).min(1).max(20).optional(),
289
+ /** Defaults to the offer's name (or the person's or place's, when the block names them alone). */
277
290
  title: z.string().optional(),
291
+ /** Defaults to its description. */
278
292
  intro: z.string().optional(),
279
293
  /** Small print under the form (e.g. how to cancel). */
280
294
  note: z.string().optional(),
@@ -83,6 +83,25 @@ export const siteSettingsSchema = z.object({
83
83
  verification: verificationSchema,
84
84
  });
85
85
 
86
+ /** How the header logo sits: its size and whether it hangs below the bar. The defaults are
87
+ * the header every site had before these settings (a 56px logo inside the bar). */
88
+ export const logoHeaderSchema = z
89
+ .object({
90
+ /** The logo's height on a desktop at the top of the page: `standard` 56px, `large` about
91
+ * twice that (112px), `xl` about four times (216px). Tablets and phones take smaller steps. */
92
+ size: z.enum(['standard', 'large', 'xl']).default('standard'),
93
+ /** `inline` sits in the bar (a larger logo makes the bar taller, on desktops only).
94
+ * `overhang` pins the logo to the top of the bar and lets it hang below the bar over the
95
+ * top of the page, and the bar keeps its height. */
96
+ placement: z.enum(['inline', 'overhang']).default('inline'),
97
+ /** Overhang only: once the visitor scrolls, the logo tucks back into the bar at the
98
+ * small size, and grows again at the top. Off keeps it hanging while they read. */
99
+ shrinkOnScroll: z.boolean().default(true),
100
+ /** A soft shadow under the logo, so a dark round badge stands out from a dark header. */
101
+ shadow: z.boolean().default(false),
102
+ })
103
+ .default({});
104
+
86
105
  export const logoSettingsSchema = z.object({
87
106
  /** Primary/header logo — light theme variant. Optional (SiteHeader falls back to a wordmark). */
88
107
  primaryLogoLight: z.string().optional(),
@@ -103,6 +122,8 @@ export const logoSettingsSchema = z.object({
103
122
  url: z.string().default(''),
104
123
  })
105
124
  .default({}),
125
+ /** The header logo's size and placement (optional; the defaults change nothing). */
126
+ header: logoHeaderSchema,
106
127
  });
107
128
 
108
129
  export const navbarSettingsSchema = z.object({
@@ -195,6 +216,16 @@ export const themeSettingsSchema = z.object({
195
216
 
196
217
  export type SiteSettings = z.infer<typeof siteSettingsSchema>;
197
218
  export type LogoSettings = z.infer<typeof logoSettingsSchema>;
219
+ export type LogoHeader = z.infer<typeof logoHeaderSchema>;
220
+ /** One page's header logo in place of the site's (a preview or a test fixture). `width` and
221
+ * `height` are the image's own, so its box is reserved before it loads. */
222
+ export interface HeaderLogoOverride {
223
+ light: string;
224
+ dark?: string;
225
+ width?: number;
226
+ height?: number;
227
+ header?: z.input<typeof logoHeaderSchema>;
228
+ }
198
229
  export type NavbarSettings = z.infer<typeof navbarSettingsSchema>;
199
230
  export type FooterSettings = z.infer<typeof footerSettingsSchema>;
200
231
  export type ThemeSettings = z.infer<typeof themeSettingsSchema>;
package/integration.mjs CHANGED
@@ -1,249 +1,263 @@
1
- /**
2
- * ferst() — the Astro integration that makes a client site's ROUTING package-owned.
3
- *
4
- * A thin client adds `integrations: [ferst()]` to astro.config.mjs and carries
5
- * ZERO page files: the page catch-all (which also owns the home page), the
6
- * calendar route and the blog routes are injected from ferst-core. A routing fix
7
- * then ships as a package bump + rebuild — the same channel component fixes travel
8
- * through — instead of being hand-copied into every client repo.
9
- *
10
- * Irreducible caveat (Astro 5): content collections must be defined in the CONSUMER,
11
- * so the one-line `src/content/config.ts` re-export stays. "Zero page files" is
12
- * reachable; "zero files" is not. Explicit client `.astro` routes still win over
13
- * these injected ones, so a one-off hand-built page is always possible.
14
- *
15
- * The blog routes (posts index / individual post / tag pages) inject as a set:
16
- * the listing components (NewsList, PostsFilter) now live in core, so `/posts`,
17
- * `/posts/[...slug]` and `/posts/tag/[...tag]` all ship from the package. Turn
18
- * the whole capability off with `blog: false` (then a client wanting posts hand-
19
- * builds its own routes over `ferst-core/lib/posts`).
20
- *
21
- * @param {object} [options]
22
- * @param {boolean} [options.calendar=true] Inject the `/calendar` route.
23
- * @param {boolean} [options.blog=true] Inject the blog routes (`/posts`,
24
- * `/posts/[...slug]`, `/posts/tag/[...tag]`).
25
- * @param {boolean} [options.accessibility=true] Inject `/accessibility`, the accessibility statement
26
- * every footer links to (content/accessibility.ts). Skipped when the site has its own
27
- * `src/pages/accessibility.astro`.
28
- * @param {boolean} [options.cookiePolicy=true] Inject `/cookie-policy` (the page the cookie
29
- * banner links to), generated from the blocks the site uses. Skipped automatically when
30
- * the site has its own `src/pages/cookie-policy.astro`.
31
- * @param {boolean} [options.notFound=true] Inject the "page not found" page (`/404` →
32
- * `404.html`). Cloudflare Pages answers a missing address with it and a real 404 status;
33
- * without one it serves the home page with a 200 (a "soft 404"). Skipped automatically
34
- * when the site has its own `src/pages/404.astro` or `public/404.html`.
35
- * @param {boolean} [options.icons=true] The browser icon (lib/site-icon.mjs): `/favicon.ico` and
36
- * `/apple-touch-icon.png` in every build, from the icon set in the CMS, else a roughly
37
- * square logo, else the site's initial in its brand colour. A site's own files in
38
- * `public/` win.
39
- * @param {boolean} [options.seo=true] Search signals (lib/seo.mjs): `/robots.txt`, and once
40
- * `ferst-site.json` has a `siteUrl`, `/sitemap.xml`, a canonical address on every page,
41
- * structured data and link previews, and (with the blog) `/posts/rss.xml`. Every build's
42
- * internal links to a page point at its own address (`/about-us/`), not at a redirect.
43
- * A test copy (any branch but the production one) is marked noindex on every file. A
44
- * site's own `public/robots.txt` or `public/sitemap.xml` wins.
45
- * @returns {import('astro').AstroIntegration}
46
- */
47
- import { copyFileSync, createReadStream, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
48
- import { deploymentBranch } from './bin/cms-config.mjs';
49
- import { linksToPageAddresses, seoContext, withNoindexHeader } from './lib/seo.mjs';
50
- import { writeSiteIcons } from './lib/site-icon.mjs';
51
-
52
- /** Every page of a build (its .html files, at any depth), as file URLs. */
53
- function htmlFiles(dir) {
54
- return readdirSync(dir, { withFileTypes: true }).flatMap((entry) =>
55
- entry.isDirectory()
56
- ? htmlFiles(new URL(`${encodeURIComponent(entry.name)}/`, dir))
57
- : entry.name.endsWith('.html')
58
- ? [new URL(encodeURIComponent(entry.name), dir)]
59
- : [],
60
- );
61
- }
62
-
63
- /** The self-hosted fonts the engine's CSS requests (/fonts/*.woff2), shipped in the package. */
64
- const FONTS_DIR = new URL('./fonts/', import.meta.url);
65
- const FONT_URL = /^\/fonts\/([a-z0-9-]+\.woff2)(?:\?.*)?$/;
66
-
67
- /**
68
- * ferstFonts() — serves the engine's self-hosted fonts in `astro dev` and copies them into
69
- * every build's `/fonts/`. Included in ferst(); usable on its own (the showcase). A file
70
- * the site already has in its own `public/fonts/` is never overwritten.
71
- * @returns {import('astro').AstroIntegration}
72
- */
73
- export function ferstFonts() {
74
- return {
75
- name: 'ferst-fonts',
76
- hooks: {
77
- 'astro:server:setup': ({ server }) => {
78
- server.middlewares.use((req, res, next) => {
79
- const m = req.url && req.url.match(FONT_URL);
80
- if (!m) return next();
81
- const file = new URL(m[1], FONTS_DIR);
82
- if (!existsSync(file)) return next();
83
- res.setHeader('Content-Type', 'font/woff2');
84
- res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
85
- createReadStream(file).pipe(res);
86
- });
87
- },
88
- 'astro:build:done': async ({ dir }) => {
89
- const out = new URL('fonts/', dir);
90
- mkdirSync(out, { recursive: true });
91
- for (const name of readdirSync(FONTS_DIR)) {
92
- if (!name.endsWith('.woff2')) continue;
93
- const dest = new URL(name, out);
94
- if (!existsSync(dest)) copyFileSync(new URL(name, FONTS_DIR), dest);
95
- }
96
- },
97
- },
98
- };
99
- }
100
-
101
- /** The site's `ferst-site.json`, or null (no file, or not JSON). */
102
- function readSiteMeta(root) {
103
- if (!root) return null;
104
- try {
105
- return JSON.parse(readFileSync(new URL('ferst-site.json', root), 'utf8'));
106
- } catch {
107
- return null;
108
- }
109
- }
110
-
111
- /** Does the site ship this file in its own `public/`? (Its own file wins over ours.) */
112
- const hasPublicFile = (root, name) => Boolean(root) && existsSync(new URL(`public/${name}`, root));
113
-
114
- export default function ferst(options = {}) {
115
- const { calendar = true, blog = true, cookiePolicy = true, accessibility = true, notFound = true, icons = true, seo = true } = options;
116
- const fonts = ferstFonts().hooks;
117
- /** This build's search context, decided at setup and used again when the build is done. */
118
- let search = null;
119
- /** The site's folder, for the content and public files the build-done steps read. */
120
- let siteRoot = null;
121
- return {
122
- name: 'ferst',
123
- hooks: {
124
- 'astro:config:setup': ({ injectRoute, updateConfig, config }) => {
125
- siteRoot = config?.root ?? null;
126
- // Pages + home: the reserved `index` entry renders at `/`, every other
127
- // `pages` entry at its own slug (see lib/pages.ts `getSiteRoutes`).
128
- injectRoute({
129
- pattern: '/[...slug]',
130
- entrypoint: 'ferst-core/routes/[...slug].astro',
131
- });
132
- if (calendar) {
133
- injectRoute({
134
- pattern: '/calendar',
135
- entrypoint: 'ferst-core/routes/calendar/index.astro',
136
- });
137
- }
138
- if (blog) {
139
- // The posts capability: index, individual post, and tag pages. Reads
140
- // the `posts`/`tags`/`postsSettings` collections (content/collections.ts).
141
- injectRoute({
142
- pattern: '/posts',
143
- entrypoint: 'ferst-core/routes/posts/index.astro',
144
- });
145
- injectRoute({
146
- pattern: '/posts/[...slug]',
147
- entrypoint: 'ferst-core/routes/posts/[...slug].astro',
148
- });
149
- injectRoute({
150
- pattern: '/posts/tag/[...tag]',
151
- entrypoint: 'ferst-core/routes/posts/tag/[...tag].astro',
152
- });
153
- // Index pages 2+ (page 1 is /posts; tag pages paginate inside their own route).
154
- injectRoute({
155
- pattern: '/posts/page/[page]',
156
- entrypoint: 'ferst-core/routes/posts/page/[page].astro',
157
- });
158
- }
159
- // The cookie banner links here on every page, so it must always resolve. A site's
160
- // own hand-built page wins (Astro would otherwise see two routes for one path).
161
- const bespoke = config?.root && existsSync(new URL('src/pages/cookie-policy.astro', config.root));
162
- if (cookiePolicy && !bespoke) {
163
- injectRoute({
164
- pattern: '/cookie-policy',
165
- entrypoint: 'ferst-core/routes/cookie-policy.astro',
166
- });
167
- }
168
- // Every footer links to the accessibility statement. The site's own page wins.
169
- const ownStatement = config?.root && existsSync(new URL('src/pages/accessibility.astro', config.root));
170
- if (accessibility && !ownStatement) {
171
- injectRoute({ pattern: '/accessibility', entrypoint: 'ferst-core/routes/accessibility.astro' });
172
- }
173
- // A missing address must answer 404, not the home page (Cloudflare Pages serves the
174
- // home page with a 200 when a build has no 404.html). The site's own page wins.
175
- const ownNotFound = config?.root && existsSync(new URL('src/pages/404.astro', config.root));
176
- if (notFound && !ownNotFound && !hasPublicFile(config?.root, '404.html')) {
177
- injectRoute({ pattern: '/404', entrypoint: 'ferst-core/routes/404.astro' });
178
- }
179
- // Which optional routes this site has, for the pages that link to them (the sitemap,
180
- // the "page not found" page).
181
- updateConfig?.({
182
- vite: {
183
- define: {
184
- 'import.meta.env.FERST_ROUTES_BLOG': JSON.stringify(blog),
185
- 'import.meta.env.FERST_ROUTES_CALENDAR': JSON.stringify(calendar),
186
- 'import.meta.env.FERST_ROUTES_ACCESSIBILITY': JSON.stringify(accessibility),
187
- },
188
- },
189
- });
190
- // Search signals: the site's address and whether this deploy is the live site (the
191
- // production branch) or a test copy, the same rule the CMS uses for its git-proxy.
192
- if (seo) {
193
- const root = config?.root;
194
- search = seoContext({ siteMeta: readSiteMeta(root), branch: deploymentBranch(), env: process.env });
195
- updateConfig?.({
196
- ...(search.siteUrl && !config?.site ? { site: search.siteUrl } : {}),
197
- vite: {
198
- define: {
199
- 'import.meta.env.FERST_SITE_URL': JSON.stringify(search.siteUrl ?? ''),
200
- 'import.meta.env.FERST_SEO_PRODUCTION': JSON.stringify(search.production),
201
- },
202
- },
203
- });
204
- if (!hasPublicFile(root, 'robots.txt')) {
205
- injectRoute({ pattern: '/robots.txt', entrypoint: 'ferst-core/routes/robots.txt.ts' });
206
- }
207
- // A sitemap lists absolute addresses, so it needs the site's address.
208
- if (search.siteUrl && !hasPublicFile(root, 'sitemap.xml')) {
209
- injectRoute({ pattern: '/sitemap.xml', entrypoint: 'ferst-core/routes/sitemap.xml.ts' });
210
- }
211
- // The news feed lists absolute addresses too.
212
- if (search.siteUrl && blog) {
213
- injectRoute({ pattern: '/posts/rss.xml', entrypoint: 'ferst-core/routes/posts/rss.xml.ts' });
214
- }
215
- }
216
- },
217
- // The engine's self-hosted fonts: served in dev, copied into every build.
218
- 'astro:server:setup': fonts['astro:server:setup'],
219
- 'astro:build:done': async (ctx) => {
220
- await fonts['astro:build:done'](ctx);
221
- // Internal links point at each page's one address, never at a redirect (lib/seo.mjs).
222
- if (seo) {
223
- const isPage = (path) => {
224
- try {
225
- return existsSync(new URL(`.${path}index.html`, ctx.dir));
226
- } catch {
227
- return false;
228
- }
229
- };
230
- for (const file of htmlFiles(ctx.dir)) {
231
- const html = readFileSync(file, 'utf8');
232
- const linked = linksToPageAddresses(html, isPage);
233
- if (linked !== html) writeFileSync(file, linked);
234
- }
235
- }
236
- // A test copy is noindex on every file: pages, and the PDFs and images beside them.
237
- if (search && !search.production) {
238
- const file = new URL('_headers', ctx.dir);
239
- writeFileSync(file, withNoindexHeader(existsSync(file) ? readFileSync(file, 'utf8') : ''));
240
- }
241
- // The browser icon: /favicon.ico and /apple-touch-icon.png (sharp comes with Astro).
242
- if (icons && siteRoot) {
243
- const sharp = await import('sharp').then((m) => m.default ?? m).catch(() => null);
244
- await writeSiteIcons({ root: siteRoot, outDir: ctx.dir, sharp, warn: (m) => (ctx.logger ? ctx.logger.warn(m) : console.warn(m)) });
245
- }
246
- },
247
- },
248
- };
249
- }
1
+ /**
2
+ * ferst() — the Astro integration that makes a client site's ROUTING package-owned.
3
+ *
4
+ * A thin client adds `integrations: [ferst()]` to astro.config.mjs and carries
5
+ * ZERO page files: the page catch-all (which also owns the home page), the
6
+ * calendar route and the blog routes are injected from ferst-core. A routing fix
7
+ * then ships as a package bump + rebuild — the same channel component fixes travel
8
+ * through — instead of being hand-copied into every client repo.
9
+ *
10
+ * Irreducible caveat (Astro 5): content collections must be defined in the CONSUMER,
11
+ * so the one-line `src/content/config.ts` re-export stays. "Zero page files" is
12
+ * reachable; "zero files" is not. Explicit client `.astro` routes still win over
13
+ * these injected ones, so a one-off hand-built page is always possible.
14
+ *
15
+ * The blog routes (posts index / individual post / tag pages) inject as a set:
16
+ * the listing components (NewsList, PostsFilter) now live in core, so `/posts`,
17
+ * `/posts/[...slug]` and `/posts/tag/[...tag]` all ship from the package. Turn
18
+ * the whole capability off with `blog: false` (then a client wanting posts hand-
19
+ * builds its own routes over `ferst-core/lib/posts`).
20
+ *
21
+ * @param {object} [options]
22
+ * @param {boolean} [options.calendar=true] Inject the `/calendar` route.
23
+ * @param {boolean} [options.blog=true] Inject the blog routes (`/posts`,
24
+ * `/posts/[...slug]`, `/posts/tag/[...tag]`).
25
+ * @param {boolean} [options.accessibility=true] Inject `/accessibility`, the accessibility statement
26
+ * every footer links to (content/accessibility.ts). Skipped when the site has its own
27
+ * `src/pages/accessibility.astro`.
28
+ * @param {boolean} [options.cookiePolicy=true] Inject `/cookie-policy` (the page the cookie
29
+ * banner links to), generated from the blocks the site uses. Skipped automatically when
30
+ * the site has its own `src/pages/cookie-policy.astro`.
31
+ * @param {boolean} [options.notFound=true] Inject the "page not found" page (`/404` →
32
+ * `404.html`). Cloudflare Pages answers a missing address with it and a real 404 status;
33
+ * without one it serves the home page with a 200 (a "soft 404"). Skipped automatically
34
+ * when the site has its own `src/pages/404.astro` or `public/404.html`.
35
+ * @param {boolean} [options.icons=true] The browser icon (lib/site-icon.mjs): `/favicon.ico` and
36
+ * `/apple-touch-icon.png` in every build, from the icon set in the CMS, else a roughly
37
+ * square logo, else the site's initial in its brand colour. A site's own files in
38
+ * `public/` win.
39
+ * @param {boolean} [options.seo=true] Search signals (lib/seo.mjs): `/robots.txt`, and once
40
+ * `ferst-site.json` has a `siteUrl`, `/sitemap.xml`, a canonical address on every page,
41
+ * structured data and link previews, and (with the blog) `/posts/rss.xml`. Every build's
42
+ * internal links to a page point at its own address (`/about-us/`), not at a redirect.
43
+ * A test copy (any branch but the production one) is marked noindex on every file. A
44
+ * site's own `public/robots.txt` or `public/sitemap.xml` wins.
45
+ * @returns {import('astro').AstroIntegration}
46
+ */
47
+ import { copyFileSync, createReadStream, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
48
+ import { deploymentBranch } from './bin/cms-config.mjs';
49
+ import { linksToPageAddresses, seoContext, withNoindexHeader } from './lib/seo.mjs';
50
+ import { writeSiteIcons } from './lib/site-icon.mjs';
51
+ import { publicImageSize } from './lib/image-size.mjs';
52
+
53
+ /** Every page of a build (its .html files, at any depth), as file URLs. */
54
+ function htmlFiles(dir) {
55
+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) =>
56
+ entry.isDirectory()
57
+ ? htmlFiles(new URL(`${encodeURIComponent(entry.name)}/`, dir))
58
+ : entry.name.endsWith('.html')
59
+ ? [new URL(encodeURIComponent(entry.name), dir)]
60
+ : [],
61
+ );
62
+ }
63
+
64
+ /** The header logo's (logoSettings `primaryLogoLight`) own width and height, or null. */
65
+ function headerLogoSize(root) {
66
+ if (!root) return null;
67
+ try {
68
+ const logos = JSON.parse(readFileSync(new URL('src/content/logoSettings/index.json', root), 'utf8'));
69
+ return publicImageSize(root, logos.primaryLogoLight);
70
+ } catch {
71
+ return null;
72
+ }
73
+ }
74
+
75
+ /** The self-hosted fonts the engine's CSS requests (/fonts/*.woff2), shipped in the package. */
76
+ const FONTS_DIR = new URL('./fonts/', import.meta.url);
77
+ const FONT_URL = /^\/fonts\/([a-z0-9-]+\.woff2)(?:\?.*)?$/;
78
+
79
+ /**
80
+ * ferstFonts() — serves the engine's self-hosted fonts in `astro dev` and copies them into
81
+ * every build's `/fonts/`. Included in ferst(); usable on its own (the showcase). A file
82
+ * the site already has in its own `public/fonts/` is never overwritten.
83
+ * @returns {import('astro').AstroIntegration}
84
+ */
85
+ export function ferstFonts() {
86
+ return {
87
+ name: 'ferst-fonts',
88
+ hooks: {
89
+ 'astro:server:setup': ({ server }) => {
90
+ server.middlewares.use((req, res, next) => {
91
+ const m = req.url && req.url.match(FONT_URL);
92
+ if (!m) return next();
93
+ const file = new URL(m[1], FONTS_DIR);
94
+ if (!existsSync(file)) return next();
95
+ res.setHeader('Content-Type', 'font/woff2');
96
+ res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
97
+ createReadStream(file).pipe(res);
98
+ });
99
+ },
100
+ 'astro:build:done': async ({ dir }) => {
101
+ const out = new URL('fonts/', dir);
102
+ mkdirSync(out, { recursive: true });
103
+ for (const name of readdirSync(FONTS_DIR)) {
104
+ if (!name.endsWith('.woff2')) continue;
105
+ const dest = new URL(name, out);
106
+ if (!existsSync(dest)) copyFileSync(new URL(name, FONTS_DIR), dest);
107
+ }
108
+ },
109
+ },
110
+ };
111
+ }
112
+
113
+ /** The site's `ferst-site.json`, or null (no file, or not JSON). */
114
+ function readSiteMeta(root) {
115
+ if (!root) return null;
116
+ try {
117
+ return JSON.parse(readFileSync(new URL('ferst-site.json', root), 'utf8'));
118
+ } catch {
119
+ return null;
120
+ }
121
+ }
122
+
123
+ /** Does the site ship this file in its own `public/`? (Its own file wins over ours.) */
124
+ const hasPublicFile = (root, name) => Boolean(root) && existsSync(new URL(`public/${name}`, root));
125
+
126
+ export default function ferst(options = {}) {
127
+ const { calendar = true, blog = true, cookiePolicy = true, accessibility = true, notFound = true, icons = true, seo = true } = options;
128
+ const fonts = ferstFonts().hooks;
129
+ /** This build's search context, decided at setup and used again when the build is done. */
130
+ let search = null;
131
+ /** The site's folder, for the content and public files the build-done steps read. */
132
+ let siteRoot = null;
133
+ return {
134
+ name: 'ferst',
135
+ hooks: {
136
+ 'astro:config:setup': ({ injectRoute, updateConfig, config }) => {
137
+ siteRoot = config?.root ?? null;
138
+ // Pages + home: the reserved `index` entry renders at `/`, every other
139
+ // `pages` entry at its own slug (see lib/pages.ts `getSiteRoutes`).
140
+ injectRoute({
141
+ pattern: '/[...slug]',
142
+ entrypoint: 'ferst-core/routes/[...slug].astro',
143
+ });
144
+ if (calendar) {
145
+ injectRoute({
146
+ pattern: '/calendar',
147
+ entrypoint: 'ferst-core/routes/calendar/index.astro',
148
+ });
149
+ }
150
+ if (blog) {
151
+ // The posts capability: index, individual post, and tag pages. Reads
152
+ // the `posts`/`tags`/`postsSettings` collections (content/collections.ts).
153
+ injectRoute({
154
+ pattern: '/posts',
155
+ entrypoint: 'ferst-core/routes/posts/index.astro',
156
+ });
157
+ injectRoute({
158
+ pattern: '/posts/[...slug]',
159
+ entrypoint: 'ferst-core/routes/posts/[...slug].astro',
160
+ });
161
+ injectRoute({
162
+ pattern: '/posts/tag/[...tag]',
163
+ entrypoint: 'ferst-core/routes/posts/tag/[...tag].astro',
164
+ });
165
+ // Index pages 2+ (page 1 is /posts; tag pages paginate inside their own route).
166
+ injectRoute({
167
+ pattern: '/posts/page/[page]',
168
+ entrypoint: 'ferst-core/routes/posts/page/[page].astro',
169
+ });
170
+ }
171
+ // The cookie banner links here on every page, so it must always resolve. A site's
172
+ // own hand-built page wins (Astro would otherwise see two routes for one path).
173
+ const bespoke = config?.root && existsSync(new URL('src/pages/cookie-policy.astro', config.root));
174
+ if (cookiePolicy && !bespoke) {
175
+ injectRoute({
176
+ pattern: '/cookie-policy',
177
+ entrypoint: 'ferst-core/routes/cookie-policy.astro',
178
+ });
179
+ }
180
+ // Every footer links to the accessibility statement. The site's own page wins.
181
+ const ownStatement = config?.root && existsSync(new URL('src/pages/accessibility.astro', config.root));
182
+ if (accessibility && !ownStatement) {
183
+ injectRoute({ pattern: '/accessibility', entrypoint: 'ferst-core/routes/accessibility.astro' });
184
+ }
185
+ // A missing address must answer 404, not the home page (Cloudflare Pages serves the
186
+ // home page with a 200 when a build has no 404.html). The site's own page wins.
187
+ const ownNotFound = config?.root && existsSync(new URL('src/pages/404.astro', config.root));
188
+ if (notFound && !ownNotFound && !hasPublicFile(config?.root, '404.html')) {
189
+ injectRoute({ pattern: '/404', entrypoint: 'ferst-core/routes/404.astro' });
190
+ }
191
+ // Which optional routes this site has, for the pages that link to them (the sitemap,
192
+ // the "page not found" page).
193
+ updateConfig?.({
194
+ vite: {
195
+ define: {
196
+ 'import.meta.env.FERST_ROUTES_BLOG': JSON.stringify(blog),
197
+ 'import.meta.env.FERST_ROUTES_CALENDAR': JSON.stringify(calendar),
198
+ 'import.meta.env.FERST_ROUTES_ACCESSIBILITY': JSON.stringify(accessibility),
199
+ // The header logo's own width and height, so its box is reserved before it loads.
200
+ 'import.meta.env.FERST_LOGO_SIZE': JSON.stringify(headerLogoSize(config?.root)),
201
+ },
202
+ },
203
+ });
204
+ // Search signals: the site's address and whether this deploy is the live site (the
205
+ // production branch) or a test copy, the same rule the CMS uses for its git-proxy.
206
+ if (seo) {
207
+ const root = config?.root;
208
+ search = seoContext({ siteMeta: readSiteMeta(root), branch: deploymentBranch(), env: process.env });
209
+ updateConfig?.({
210
+ ...(search.siteUrl && !config?.site ? { site: search.siteUrl } : {}),
211
+ vite: {
212
+ define: {
213
+ 'import.meta.env.FERST_SITE_URL': JSON.stringify(search.siteUrl ?? ''),
214
+ 'import.meta.env.FERST_SEO_PRODUCTION': JSON.stringify(search.production),
215
+ },
216
+ },
217
+ });
218
+ if (!hasPublicFile(root, 'robots.txt')) {
219
+ injectRoute({ pattern: '/robots.txt', entrypoint: 'ferst-core/routes/robots.txt.ts' });
220
+ }
221
+ // A sitemap lists absolute addresses, so it needs the site's address.
222
+ if (search.siteUrl && !hasPublicFile(root, 'sitemap.xml')) {
223
+ injectRoute({ pattern: '/sitemap.xml', entrypoint: 'ferst-core/routes/sitemap.xml.ts' });
224
+ }
225
+ // The news feed lists absolute addresses too.
226
+ if (search.siteUrl && blog) {
227
+ injectRoute({ pattern: '/posts/rss.xml', entrypoint: 'ferst-core/routes/posts/rss.xml.ts' });
228
+ }
229
+ }
230
+ },
231
+ // The engine's self-hosted fonts: served in dev, copied into every build.
232
+ 'astro:server:setup': fonts['astro:server:setup'],
233
+ 'astro:build:done': async (ctx) => {
234
+ await fonts['astro:build:done'](ctx);
235
+ // Internal links point at each page's one address, never at a redirect (lib/seo.mjs).
236
+ if (seo) {
237
+ const isPage = (path) => {
238
+ try {
239
+ return existsSync(new URL(`.${path}index.html`, ctx.dir));
240
+ } catch {
241
+ return false;
242
+ }
243
+ };
244
+ for (const file of htmlFiles(ctx.dir)) {
245
+ const html = readFileSync(file, 'utf8');
246
+ const linked = linksToPageAddresses(html, isPage);
247
+ if (linked !== html) writeFileSync(file, linked);
248
+ }
249
+ }
250
+ // A test copy is noindex on every file: pages, and the PDFs and images beside them.
251
+ if (search && !search.production) {
252
+ const file = new URL('_headers', ctx.dir);
253
+ writeFileSync(file, withNoindexHeader(existsSync(file) ? readFileSync(file, 'utf8') : ''));
254
+ }
255
+ // The browser icon: /favicon.ico and /apple-touch-icon.png (sharp comes with Astro).
256
+ if (icons && siteRoot) {
257
+ const sharp = await import('sharp').then((m) => m.default ?? m).catch(() => null);
258
+ await writeSiteIcons({ root: siteRoot, outDir: ctx.dir, sharp, warn: (m) => (ctx.logger ? ctx.logger.warn(m) : console.warn(m)) });
259
+ }
260
+ },
261
+ },
262
+ };
263
+ }