inlaycms 0.2.0 → 0.3.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.
Files changed (121) hide show
  1. package/README.md +330 -1
  2. package/assets/admin/admin.css +1 -1
  3. package/assets/admin/admin.js +1 -1
  4. package/assets/admin/editor.js +59 -44
  5. package/dist/adapters/admin/screens/redirects.js +12 -3
  6. package/dist/adapters/admin/views/layout.js +27 -7
  7. package/dist/adapters/cli/remote.js +9 -1
  8. package/dist/adapters/mcp/tools/redirects.js +16 -2
  9. package/dist/adapters/site/assets.d.ts +11 -0
  10. package/dist/adapters/site/assets.js +71 -0
  11. package/dist/adapters/site/cache.d.ts +2 -1
  12. package/dist/adapters/site/cache.js +6 -1
  13. package/dist/adapters/site/context.d.ts +6 -0
  14. package/dist/adapters/site/context.js +38 -13
  15. package/dist/adapters/site/head.d.ts +30 -7
  16. package/dist/adapters/site/head.js +145 -20
  17. package/dist/adapters/site/headers.d.ts +5 -0
  18. package/dist/adapters/site/headers.js +31 -0
  19. package/dist/adapters/site/plugin.d.ts +2 -0
  20. package/dist/adapters/site/plugin.js +32 -9
  21. package/dist/adapters/site/public.js +7 -24
  22. package/dist/adapters/site/render.d.ts +5 -0
  23. package/dist/adapters/site/render.js +23 -8
  24. package/dist/adapters/site/routes.d.ts +6 -0
  25. package/dist/adapters/site/routes.js +8 -3
  26. package/dist/adapters/site/seo.d.ts +20 -0
  27. package/dist/adapters/site/seo.js +45 -0
  28. package/dist/adapters/site/sitemap.d.ts +1 -1
  29. package/dist/adapters/site/sitemap.js +1 -1
  30. package/dist/config.js +3 -2
  31. package/dist/core/agent/format.js +1 -1
  32. package/dist/core/agent/schema.js +3 -0
  33. package/dist/core/boot.js +7 -0
  34. package/dist/core/check.js +6 -1
  35. package/dist/core/content/dry-run.d.ts +7 -6
  36. package/dist/core/content/dry-run.js +8 -8
  37. package/dist/core/content/publish.d.ts +1 -1
  38. package/dist/core/content/publish.js +5 -3
  39. package/dist/core/content/read.d.ts +3 -0
  40. package/dist/core/content/reader.js +3 -2
  41. package/dist/core/content/refs.js +1 -1
  42. package/dist/core/content/search.js +2 -2
  43. package/dist/core/content/shipped-images.d.ts +32 -0
  44. package/dist/core/content/shipped-images.js +62 -0
  45. package/dist/core/content/shipped-input.d.ts +9 -3
  46. package/dist/core/content/shipped-input.js +165 -28
  47. package/dist/core/content/shipped.js +8 -3
  48. package/dist/core/content/validate.js +7 -1
  49. package/dist/core/core.d.ts +5 -1
  50. package/dist/core/core.js +5 -4
  51. package/dist/core/db/connection.d.ts +6 -0
  52. package/dist/core/db/connection.js +13 -1
  53. package/dist/core/db/migrate.js +2 -0
  54. package/dist/core/db/migrations/0007_published_at.d.ts +3 -0
  55. package/dist/core/db/migrations/0007_published_at.js +16 -0
  56. package/dist/core/db/schema.d.ts +1 -0
  57. package/dist/core/export/export.js +3 -1
  58. package/dist/core/export/format.d.ts +8 -1
  59. package/dist/core/export/format.js +3 -2
  60. package/dist/core/export/read.js +7 -0
  61. package/dist/core/export/stage.d.ts +1 -1
  62. package/dist/core/export/stage.js +24 -1
  63. package/dist/core/fields/builtins.d.ts +28 -0
  64. package/dist/core/fields/builtins.js +103 -11
  65. package/dist/core/fields/define.d.ts +6 -0
  66. package/dist/core/fields/widgets.d.ts +7 -0
  67. package/dist/core/fields/widgets.js +76 -28
  68. package/dist/core/messages/en.d.ts +70 -6
  69. package/dist/core/messages/en.js +70 -6
  70. package/dist/core/redirects/collapse.d.ts +17 -1
  71. package/dist/core/redirects/collapse.js +19 -3
  72. package/dist/core/redirects/redirects.d.ts +13 -12
  73. package/dist/core/redirects/redirects.js +141 -53
  74. package/dist/core/redirects/rule.d.ts +25 -0
  75. package/dist/core/redirects/rule.js +55 -0
  76. package/dist/core/registry/define.d.ts +40 -0
  77. package/dist/core/registry/define.js +3 -0
  78. package/dist/core/registry/registry.d.ts +21 -0
  79. package/dist/core/registry/registry.js +114 -6
  80. package/dist/core/registry/render.d.ts +37 -1
  81. package/dist/core/registry/route.d.ts +4 -0
  82. package/dist/core/release/bundle.js +30 -5
  83. package/dist/core/release/manifest.d.ts +14 -0
  84. package/dist/core/release/manifest.js +42 -17
  85. package/dist/core/release/markdown-file.d.ts +21 -0
  86. package/dist/core/release/markdown-file.js +172 -0
  87. package/dist/core/release/pack.js +2 -2
  88. package/dist/core/release/read.js +4 -1
  89. package/dist/core/release/site-dir.d.ts +4 -0
  90. package/dist/core/release/site-dir.js +8 -0
  91. package/dist/core/report.d.ts +8 -2
  92. package/dist/core/richtext/html.d.ts +3 -1
  93. package/dist/core/richtext/html.js +16 -4
  94. package/dist/core/richtext/inline.d.ts +22 -0
  95. package/dist/core/richtext/inline.js +33 -0
  96. package/dist/core/richtext/markdown.d.ts +16 -1
  97. package/dist/core/richtext/markdown.js +137 -14
  98. package/dist/core/richtext/schema.d.ts +16 -4
  99. package/dist/core/richtext/schema.js +71 -1
  100. package/dist/core/site/live.d.ts +1 -0
  101. package/dist/core/site/live.js +1 -0
  102. package/dist/core/site/paths.d.ts +6 -0
  103. package/dist/core/site/paths.js +13 -0
  104. package/dist/core/site/resolve.d.ts +1 -1
  105. package/dist/core/site/resolve.js +119 -30
  106. package/dist/core/site/sitemap.d.ts +1 -1
  107. package/dist/core/site/sitemap.js +4 -0
  108. package/dist/core/types.d.ts +28 -3
  109. package/dist/host/app.d.ts +5 -0
  110. package/dist/host/app.js +8 -0
  111. package/dist/host/dev.js +3 -7
  112. package/dist/host/diff.d.ts +19 -1
  113. package/dist/host/diff.js +32 -2
  114. package/dist/index.d.ts +2 -2
  115. package/dist/markdown-modules.d.ts +8 -0
  116. package/dist/markdown-modules.js +1 -0
  117. package/dist/site.d.ts +8 -3
  118. package/dist/site.js +6 -0
  119. package/dist/testing.d.ts +22 -0
  120. package/dist/testing.js +155 -0
  121. package/package.json +6 -1
@@ -1,40 +1,165 @@
1
+ import { InlayError } from '../../core/errors.js';
2
+ import { isSafeUrl } from '../../core/fields/define.js';
1
3
  import { encodePath } from '../../core/site/paths.js';
2
4
  import { escapeHtml, raw } from '../../jsx/html.js';
3
- const RASTER = /^image\/(jpeg|png|webp|gif|avif|tiff)$/;
5
+ export const NO_HEAD = { meta: [], links: [], jsonLd: [] };
6
+ const SCRIPT_UNSAFE = {
7
+ '<': '\\u003c',
8
+ '>': '\\u003e',
9
+ '&': '\\u0026',
10
+ '\u2028': '\\u2028',
11
+ '\u2029': '\\u2029',
12
+ };
13
+ /** `value` as JSON that can't end its `<script>` or open an HTML comment in it. */
14
+ function scriptJson(value) {
15
+ const json = JSON.stringify(value);
16
+ if (json === undefined)
17
+ throw new InlayError('config', 'config.headJsonLd');
18
+ return json.replace(/[<>&\u2028\u2029]/g, (c) => SCRIPT_UNSAFE[c]);
19
+ }
20
+ const LINK_ATTRS = ['rel', 'hreflang', 'type', 'sizes', 'media', 'as', 'crossorigin', 'href'];
21
+ /** The `ctx.head` of one render, and what it collected. */
22
+ export function createHeadCollector() {
23
+ const head = { meta: [], links: [], jsonLd: [] };
24
+ const api = {
25
+ jsonLd(value) {
26
+ head.jsonLd.push(scriptJson(value));
27
+ },
28
+ meta(attrs) {
29
+ const tag = 'property' in attrs
30
+ ? { attr: 'property', key: String(attrs.property) }
31
+ : { attr: 'name', key: String(attrs.name) };
32
+ head.meta.push({ ...tag, content: String(attrs.content) });
33
+ },
34
+ link(attrs) {
35
+ const href = String(attrs.href);
36
+ if (!isSafeUrl(href))
37
+ throw new InlayError('config', 'config.headHref', { href });
38
+ const link = { rel: String(attrs.rel), href };
39
+ for (const k of LINK_ATTRS) {
40
+ const v = attrs[k];
41
+ if (v !== undefined && v !== null)
42
+ link[k] = String(v);
43
+ }
44
+ head.links.push(link);
45
+ },
46
+ };
47
+ return { api, collected: () => ({ meta: [...head.meta], links: [...head.links], jsonLd: [...head.jsonLd] }) };
48
+ }
4
49
  function absolute(baseUrl, path) {
5
50
  const [p = '', query] = path.split('?');
6
51
  return `${baseUrl}${p === '/' ? '/' : encodePath(p)}${query === undefined ? '' : `?${query}`}`;
7
52
  }
8
- export function buildHead(input) {
9
- const title = input.seo?.title || input.title;
10
- const description = input.seo?.description || '';
11
- const e = escapeHtml;
53
+ const meta = (attr, key, content) => ({ tag: 'meta', attr, key, content });
54
+ /** Inlay's own tags for the page, before any Twitter tags. */
55
+ function inlayTags(input) {
12
56
  const url = input.canonical === null ? null : absolute(input.baseUrl, input.canonical);
13
- const tags = [`<title>${e(title)}</title>`];
14
- if (description)
15
- tags.push(`<meta name="description" content="${e(description)}">`);
57
+ const tags = [{ tag: 'title', text: input.title }];
58
+ if (input.description)
59
+ tags.push(meta('name', 'description', input.description));
16
60
  if (url !== null)
17
- tags.push(`<link rel="canonical" href="${e(url)}">`);
61
+ tags.push({ tag: 'link', attrs: { rel: 'canonical', href: url } });
18
62
  if (input.alternates.length >= 2) {
19
63
  for (const a of input.alternates) {
20
- tags.push(`<link rel="alternate" hreflang="${e(a.locale)}" href="${e(absolute(input.baseUrl, a.path))}">`);
64
+ tags.push({ tag: 'link', attrs: { rel: 'alternate', hreflang: a.locale, href: absolute(input.baseUrl, a.path) } });
21
65
  }
22
66
  const def = input.alternates.find((a) => a.locale === input.defaultLocale);
23
67
  if (def)
24
- tags.push(`<link rel="alternate" hreflang="x-default" href="${e(absolute(input.baseUrl, def.path))}">`);
68
+ tags.push({ tag: 'link', attrs: { rel: 'alternate', hreflang: 'x-default', href: absolute(input.baseUrl, def.path) } });
25
69
  }
26
- tags.push(`<meta property="og:type" content="website">`);
27
- tags.push(`<meta property="og:title" content="${e(title)}">`);
28
- if (description)
29
- tags.push(`<meta property="og:description" content="${e(description)}">`);
70
+ tags.push(meta('property', 'og:type', input.ogType));
71
+ tags.push(meta('property', 'og:title', input.title));
72
+ if (input.description)
73
+ tags.push(meta('property', 'og:description', input.description));
30
74
  if (url !== null)
31
- tags.push(`<meta property="og:url" content="${e(url)}">`);
32
- if (input.image && RASTER.test(input.image.mime)) {
33
- tags.push(`<meta property="og:image" content="${e(`${input.baseUrl}/media/${encodeURIComponent(input.image.id)}/1280.jpeg`)}">`);
75
+ tags.push(meta('property', 'og:url', url));
76
+ if (input.image)
77
+ tags.push(meta('property', 'og:image', input.image));
78
+ if (input.article) {
79
+ if (input.article.publishedTime !== null)
80
+ tags.push(meta('property', 'article:published_time', input.article.publishedTime));
81
+ tags.push(meta('property', 'article:modified_time', input.article.modifiedTime));
34
82
  }
35
83
  if (input.preview || url === null)
36
- tags.push(`<meta name="robots" content="noindex">`);
37
- return raw(tags.join(''));
84
+ tags.push(meta('name', 'robots', 'noindex'));
85
+ return tags;
86
+ }
87
+ const linkKey = (attrs) => JSON.stringify([attrs.rel?.toLowerCase() ?? '', attrs.hreflang ?? null]);
88
+ /** The collected tags merged into Inlay's: Inlay's surviving tags, then the template's metas, links and JSON-LD. */
89
+ function merge(inlay, collected, preview) {
90
+ const metas = new Map();
91
+ for (const m of collected.meta) {
92
+ if (preview && m.key.toLowerCase() === 'robots')
93
+ continue;
94
+ metas.set(m.key, meta(m.attr, m.key, m.content));
95
+ }
96
+ const inlayLinks = new Set(inlay.flatMap((t) => (t.tag === 'link' ? [linkKey(t.attrs)] : [])));
97
+ const links = new Map();
98
+ for (const l of collected.links) {
99
+ const attrs = {};
100
+ for (const k of LINK_ATTRS) {
101
+ const v = l[k];
102
+ if (v !== undefined)
103
+ attrs[k] = v;
104
+ }
105
+ const key = linkKey(attrs);
106
+ if (inlayLinks.has(key))
107
+ links.set(key, { tag: 'link', attrs });
108
+ else {
109
+ const exact = JSON.stringify(Object.entries(attrs));
110
+ if (!links.has(exact))
111
+ links.set(exact, { tag: 'link', attrs });
112
+ }
113
+ }
114
+ const replacedLinks = new Set([...links.keys()].filter((k) => inlayLinks.has(k)));
115
+ const kept = inlay.filter((t) => {
116
+ if (t.tag === 'meta')
117
+ return !metas.has(t.key);
118
+ if (t.tag === 'link')
119
+ return !replacedLinks.has(linkKey(t.attrs));
120
+ return true;
121
+ });
122
+ const scripts = collected.jsonLd.map((json) => ({ tag: 'script', json }));
123
+ return { inlay: kept, template: [...metas.values(), ...links.values(), ...scripts] };
124
+ }
125
+ /**
126
+ * Inlay's tags with Twitter tags mirroring the final `og:*` values (Inlay's or the template's) before Inlay's
127
+ * `robots` (or at the end), then the template's tags. A `twitter:*` key the template set is left to it.
128
+ */
129
+ function withTwitter({ inlay, template }) {
130
+ const all = [...inlay, ...template];
131
+ const has = (key) => all.some((t) => t.tag === 'meta' && t.key === key);
132
+ const og = (key) => {
133
+ const found = all.find((t) => t.tag === 'meta' && t.key === key);
134
+ return found?.tag === 'meta' ? found.content : null;
135
+ };
136
+ const twitter = [meta('name', 'twitter:card', og('og:image') === null ? 'summary' : 'summary_large_image')];
137
+ for (const key of ['title', 'description', 'image']) {
138
+ const content = og(`og:${key}`);
139
+ if (content !== null)
140
+ twitter.push(meta('name', `twitter:${key}`, content));
141
+ }
142
+ const mirrored = twitter.filter((t) => t.tag === 'meta' && !has(t.key));
143
+ const robots = inlay.findIndex((t) => t.tag === 'meta' && t.key === 'robots');
144
+ const at = robots < 0 ? inlay.length : robots;
145
+ return [...inlay.slice(0, at), ...mirrored, ...inlay.slice(at), ...template];
146
+ }
147
+ function serialize(tag) {
148
+ const e = escapeHtml;
149
+ switch (tag.tag) {
150
+ case 'title':
151
+ return `<title>${e(tag.text)}</title>`;
152
+ case 'meta':
153
+ return `<meta ${tag.attr}="${e(tag.key)}" content="${e(tag.content)}">`;
154
+ case 'link':
155
+ return `<link${Object.entries(tag.attrs).map(([k, v]) => ` ${k}="${e(v)}"`).join('')}>`;
156
+ case 'script':
157
+ return `<script type="application/ld+json">${tag.json}</script>`;
158
+ }
159
+ }
160
+ export function buildHead(input) {
161
+ const tags = merge(inlayTags(input), input.collected ?? NO_HEAD, input.preview);
162
+ return raw(withTwitter(tags).map(serialize).join(''));
38
163
  }
39
164
  export function injectHead(html, head) {
40
165
  const i = html.search(/<\/head>/i);
@@ -0,0 +1,5 @@
1
+ import type { FastifyInstance } from 'fastify';
2
+ /** The headers for a site at `baseUrl`: the defaults (HSTS only over https) with the site's own laid over them. */
3
+ export declare function siteHeaders(baseUrl: string, own: Readonly<Record<string, string | false>>): Record<string, string>;
4
+ /** Adds `headers` to every response that doesn't set them itself, so the admin's and a route's own headers win. */
5
+ export declare function registerSiteHeaders(app: FastifyInstance, headers: Readonly<Record<string, string>>): void;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * What every response gets unless it sets the header itself: no MIME sniffing, no full URLs leaked to other sites,
3
+ * and no framing by other sites. A site can't be given a whole CSP without knowing its templates, so the default
4
+ * one only says who may frame it.
5
+ */
6
+ const DEFAULTS = {
7
+ 'x-content-type-options': 'nosniff',
8
+ 'referrer-policy': 'strict-origin-when-cross-origin',
9
+ 'content-security-policy': "frame-ancestors 'self'",
10
+ };
11
+ /** One year, without `includeSubDomains`, so other hosts under the same domain are left alone. */
12
+ const HSTS = 'max-age=31536000';
13
+ /** The headers for a site at `baseUrl`: the defaults (HSTS only over https) with the site's own laid over them. */
14
+ export function siteHeaders(baseUrl, own) {
15
+ const headers = { ...DEFAULTS };
16
+ if (baseUrl.startsWith('https:'))
17
+ headers['strict-transport-security'] = HSTS;
18
+ for (const [name, value] of Object.entries(own))
19
+ headers[name.toLowerCase()] = value;
20
+ return Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] !== false));
21
+ }
22
+ /** Adds `headers` to every response that doesn't set them itself, so the admin's and a route's own headers win. */
23
+ export function registerSiteHeaders(app, headers) {
24
+ const entries = Object.entries(headers);
25
+ app.addHook('onSend', async (_request, reply, payload) => {
26
+ for (const [name, value] of entries)
27
+ if (!reply.hasHeader(name))
28
+ reply.header(name, value);
29
+ return payload;
30
+ });
31
+ }
@@ -37,6 +37,8 @@ export interface InlayOptions {
37
37
  publicMaxAge?: number;
38
38
  /** Secret values by name, such as API tokens. Routes see only the ones their site declares in `secrets`. */
39
39
  secrets?: Record<string, string>;
40
+ /** What routes get as `ctx.fetch`; the global `fetch` by default. */
41
+ fetch?: typeof fetch;
40
42
  /** `'apply'` (the default) applies the site's shipped content at boot; `'none'` leaves content to release activation. */
41
43
  content?: 'apply' | 'none';
42
44
  /**
@@ -3,9 +3,11 @@ import fp from 'fastify-plugin';
3
3
  import { DEFAULT_KEEP, SCHEDULE_INTERVAL_MS } from '../../core/backup/schedule.js';
4
4
  import { bootInlay } from '../../core/boot.js';
5
5
  import { readOnlyCore } from '../../core/core.js';
6
+ import { dataVersion } from '../../core/db/connection.js';
6
7
  import { InlayError } from '../../core/errors.js';
7
8
  import { DEFAULT_MAX_BYTES, DEFAULT_UPLOAD_TYPES } from '../../core/media/detect.js';
8
9
  import { t } from '../../core/messages/index.js';
10
+ import { externalTarget } from '../../core/redirects/rule.js';
9
11
  import { buildRegistry } from '../../core/registry/registry.js';
10
12
  import { encodePath, normalizePath, splitLocale } from '../../core/site/paths.js';
11
13
  import { loadAdminAssets } from '../admin/assets.js';
@@ -18,8 +20,10 @@ import { fetchRemoteFile } from '../mcp/fetch-url.js';
18
20
  import { registerMcpRoute } from '../mcp/route.js';
19
21
  import { createInlayMcpHandler } from '../mcp/server.js';
20
22
  import { sendWebResponse, toWebRequest } from '../web.js';
23
+ import { publicAssets } from './assets.js';
21
24
  import { cacheControl, etagMatches, PageCache, response } from './cache.js';
22
25
  import { createRenderContext } from './context.js';
26
+ import { registerSiteHeaders, siteHeaders } from './headers.js';
23
27
  import { startBackupSchedule } from './backup-schedule.js';
24
28
  import { isLockedRequest, registerSiteLockGate, registerUnlockRoute } from './lock.js';
25
29
  import { registerMediaRoutes } from './media-routes.js';
@@ -77,6 +81,7 @@ function createApi(core, cache, service, opts) {
77
81
  page: 1,
78
82
  baseUrl,
79
83
  alternates: [],
84
+ assets: opts.assets,
80
85
  });
81
86
  const api = {
82
87
  core,
@@ -114,13 +119,13 @@ function createApi(core, cache, service, opts) {
114
119
  function registerSiteRoutes(app, core, cache, opts) {
115
120
  const { registry } = core;
116
121
  const { notFound } = registry.site;
117
- const { baseUrl, cdn } = opts;
122
+ const { baseUrl, cdn, assets } = opts;
118
123
  const banner = opts.release === undefined ? {} : { release: opts.release };
119
124
  async function notFoundPage(locale, state) {
120
125
  if (notFound !== null) {
121
126
  const doc = await core.liveSingleton(notFound, locale, { state });
122
127
  if (doc)
123
- return renderPage(core, doc, { state, page: 1, baseUrl, ...banner });
128
+ return renderPage(core, doc, { state, page: 1, baseUrl, assets, ...banner });
124
129
  }
125
130
  return catalogPage('site.notFound.title', 'site.notFound');
126
131
  }
@@ -188,11 +193,16 @@ function registerSiteRoutes(app, core, cache, opts) {
188
193
  return send(request, reply, hit, true);
189
194
  const generation = cache?.generation ?? 0;
190
195
  const match = await core.resolvePath(path, { state });
191
- if (match.kind === 'redirect' && match.location.startsWith('/') && !match.location.startsWith('//')) {
192
- return reply.redirect(`${match.location}${search}`, match.status);
196
+ if (match.kind === 'redirect') {
197
+ if (match.external === true && externalTarget(match.location) === match.location) {
198
+ return reply.redirect(match.location, match.status);
199
+ }
200
+ if (match.external !== true && match.location.startsWith('/') && !match.location.startsWith('//')) {
201
+ return reply.redirect(`${match.location}${search}`, match.status);
202
+ }
193
203
  }
194
204
  if (match.kind === 'page') {
195
- const html = await renderPage(core, match.document, { state, page: pageNumber, baseUrl, ...banner });
205
+ const html = await renderPage(core, match.document, { state, page: pageNumber, baseUrl, assets, ...banner });
196
206
  if (preview)
197
207
  return sendPreview(reply, 200, html);
198
208
  const res = response(200, html, HTML);
@@ -341,10 +351,11 @@ const plugin = async (app, opts) => {
341
351
  }
342
352
  const core = opts.readOnly ? readOnlyCore(booted.core) : booted.core;
343
353
  for (const warning of report.warnings)
344
- app.log.warn({ document: warning.document }, warning.message);
354
+ app.log.warn('document' in warning ? { document: warning.document } : { redirect: warning.redirect }, warning.message);
345
355
  for (const warning of report.shipped.warnings ?? [])
346
356
  app.log.warn(warning.message);
347
357
  const now = opts.now ?? (() => new Date());
358
+ registerSiteHeaders(app, siteHeaders(baseUrl, registry.site.headers));
348
359
  const lockOptions = { db, service: auth, secret, baseUrl, now, publicPaths };
349
360
  registerSiteLockGate(app, { ...lockOptions, ...(opts.preview === 'forced' && opts.release && { release: opts.release.id }) });
350
361
  registerUnlockRoute(app, { ...lockOptions, rateLimit: opts.rateLimit !== false });
@@ -363,14 +374,25 @@ const plugin = async (app, opts) => {
363
374
  await schedule?.stop();
364
375
  await db.destroy();
365
376
  });
366
- const cache = opts.cache === false ? undefined : new PageCache(opts.cache?.maxEntries ?? 500);
377
+ const siteAssets = publicAssets(opts.publicDir ?? null);
378
+ // A commit from another connection (the other worker during a `serve` swap, a second `inlaycms dev`) changes
379
+ // data_version; this connection's own writes don't, and the live ones among them clear the cache below.
380
+ let seen = dataVersion(db);
381
+ const changedElsewhere = () => {
382
+ const version = dataVersion(db);
383
+ if (version === seen)
384
+ return false;
385
+ seen = version;
386
+ return true;
387
+ };
388
+ const cache = opts.cache === false ? undefined : new PageCache(opts.cache?.maxEntries ?? 500, changedElsewhere);
367
389
  if (cache) {
368
390
  const stop = core.onLiveChange(() => cache.clear());
369
391
  app.addHook('onClose', async () => stop());
370
392
  }
371
393
  if (baseUrl.startsWith('https:') && !app.initialConfig.https)
372
394
  warnWithoutTrustProxy(app, baseUrl);
373
- app.decorate('inlay', createApi(core, cache, auth, { baseUrl, secret, now, host: opts.host ?? null }));
395
+ app.decorate('inlay', createApi(core, cache, auth, { baseUrl, secret, now, host: opts.host ?? null, assets: siteAssets }));
374
396
  registerAuthHandler(app, { service: auth, baseUrl });
375
397
  if (opts.readOnly)
376
398
  refuseWrites(app);
@@ -419,12 +441,13 @@ const plugin = async (app, opts) => {
419
441
  registerMediaRoutes(app, core);
420
442
  if (opts.publicDir !== undefined)
421
443
  registerPublicRoutes(app, { dir: opts.publicDir, maxAge: opts.publicMaxAge ?? 3600 });
422
- registerReleaseRoutes(app, { core, registry, baseUrl, secrets: opts.secrets ?? {}, log: app.log });
444
+ registerReleaseRoutes(app, { core, registry, baseUrl, assets: siteAssets, secrets: opts.secrets ?? {}, fetch: opts.fetch ?? ((input, init) => globalThis.fetch(input, init)), log: app.log, preview: opts.preview === 'forced' });
423
445
  registerPreviewRoutes(app, { secret, baseUrl, now });
424
446
  registerSiteRoutes(app, core, cache, {
425
447
  baseUrl,
426
448
  secret,
427
449
  now,
450
+ assets: siteAssets,
428
451
  ...(opts.cdn && { cdn: opts.cdn }),
429
452
  ...(opts.noSite && { noSite: opts.noSite }),
430
453
  ...(opts.preview && { preview: opts.preview }),
@@ -1,6 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { lstat, readFile, realpath } from 'node:fs/promises';
3
- import { extname, resolve, sep } from 'node:path';
3
+ import { extname, sep } from 'node:path';
4
+ import { ASSET_VERSION_LENGTH, locate } from './assets.js';
4
5
  import { etagMatches } from './cache.js';
5
6
  import { catalogPage } from './render.js';
6
7
  const TYPES = {
@@ -25,27 +26,6 @@ const TYPES = {
25
26
  '.pdf': 'application/pdf',
26
27
  '.map': 'application/json; charset=utf-8',
27
28
  };
28
- const ENCODED = /%2e|%2f|%5c/i;
29
- /** The absolute path under `dir` that the raw wildcard names, or null when it is empty, tricky or outside `dir`. */
30
- function locate(dir, rawPath) {
31
- if (rawPath === '' || ENCODED.test(rawPath) || rawPath.includes('\\'))
32
- return null;
33
- let decoded;
34
- try {
35
- decoded = decodeURIComponent(rawPath);
36
- }
37
- catch {
38
- return null;
39
- }
40
- if (decoded.includes('\\') || decoded.includes('\0'))
41
- return null;
42
- const segments = decoded.split('/');
43
- if (segments.some((s) => s === '' || s.startsWith('.')))
44
- return null;
45
- const root = resolve(dir);
46
- const file = resolve(root, ...segments);
47
- return file.startsWith(root + sep) ? file : null;
48
- }
49
29
  /** Serves the files under `opts.dir` at `/public/*`, GET and HEAD, never anything outside it. */
50
30
  export function registerPublicRoutes(app, opts) {
51
31
  app.route({
@@ -72,8 +52,11 @@ export function registerPublicRoutes(app, opts) {
72
52
  catch {
73
53
  return missing();
74
54
  }
75
- const etag = `"${createHash('sha256').update(bytes).digest('hex').slice(0, 32)}"`;
76
- reply.header('cache-control', `public, max-age=${opts.maxAge}`).header('etag', etag);
55
+ const hex = createHash('sha256').update(bytes).digest('hex');
56
+ const etag = `"${hex.slice(0, 32)}"`;
57
+ const version = new URLSearchParams(q === -1 ? '' : rawUrl.slice(q + 1)).get('v');
58
+ const cacheControl = version === hex.slice(0, ASSET_VERSION_LENGTH) ? 'public, max-age=31536000, immutable' : `public, max-age=${opts.maxAge}`;
59
+ reply.header('cache-control', cacheControl).header('etag', etag);
77
60
  if (etagMatches(request.headers['if-none-match'], etag))
78
61
  return reply.code(304).send();
79
62
  const ext = extname(file).toLowerCase();
@@ -3,6 +3,7 @@ import { type MessageId } from '../../core/messages/index.js';
3
3
  import type { TemplateDef } from '../../core/registry/define.js';
4
4
  import type { ContentIssue, DocumentData, LiveDocument, LiveState } from '../../core/types.js';
5
5
  import { type SafeHtml } from '../../jsx/html.js';
6
+ import type { PublicAssets } from './assets.js';
6
7
  export declare const PREVIEW_EXIT_PATH = "/_inlay/preview/exit";
7
8
  /** A page Inlay renders itself (in the catalog's language), with `body` (Inlay-built HTML) under its `title` heading. */
8
9
  export declare function inlayPage(title: string, body: SafeHtml): string;
@@ -18,6 +19,7 @@ export declare function renderPage(core: Core, doc: LiveDocument, opts: {
18
19
  page: number;
19
20
  baseUrl: string;
20
21
  release?: string;
22
+ assets?: PublicAssets;
21
23
  }): Promise<string>;
22
24
  export type PaneResult = {
23
25
  ok: true;
@@ -42,4 +44,7 @@ export declare function renderTemplateData(core: Core, template: TemplateDef, da
42
44
  locale: string;
43
45
  path: string;
44
46
  baseUrl: string;
47
+ canonical?: string | null;
48
+ assets?: PublicAssets;
49
+ preview?: boolean;
45
50
  }): Promise<string>;
@@ -5,6 +5,7 @@ import { t } from '../../core/messages/index.js';
5
5
  import { escapeHtml, raw, renderToString, toHtml } from '../../jsx/html.js';
6
6
  import { createRenderContext } from './context.js';
7
7
  import { buildHead, injectHead } from './head.js';
8
+ import { isHomePath, mediaShareImage, pageTitle, resolveSeoDefaults } from './seo.js';
8
9
  const DOCTYPE = /^\s*<!doctype\s/i;
9
10
  const BODY = /<body\b[^>]*>/i;
10
11
  export const PREVIEW_EXIT_PATH = '/_inlay/preview/exit';
@@ -105,6 +106,7 @@ async function renderTemplate(core, doc, opts, internal = {}) {
105
106
  page: opts.page,
106
107
  baseUrl: opts.baseUrl,
107
108
  alternates,
109
+ ...(opts.assets && { assets: opts.assets }),
108
110
  });
109
111
  await ctx.preload([doc]);
110
112
  const page = {
@@ -114,21 +116,28 @@ async function renderTemplate(core, doc, opts, internal = {}) {
114
116
  contentLocale: doc.contentLocale,
115
117
  fallback: doc.fallback,
116
118
  path: doc.path ?? '',
119
+ publishedAt: doc.publishedAt,
117
120
  page: opts.page,
118
121
  };
119
122
  const html = await renderBody(template, doc.data, page, ctx, internal);
120
123
  const seo = seoValue(template.fields, doc.data.fields);
124
+ const defaults = await resolveSeoDefaults(core.registry, ctx, opts.baseUrl);
121
125
  const own = doc.path;
122
126
  const base = doc.fallback ? (alternates.find((a) => a.locale === core.registry.defaultLocale)?.path ?? own) : own;
127
+ const ogType = template.ogType ?? 'website';
123
128
  const head = buildHead({
124
- title: doc.title,
125
- seo,
129
+ title: pageTitle(doc.title, seo?.title, defaults.titleTemplate, isHomePath(core.registry, doc.path)),
130
+ description: seo?.description || defaults.description || null,
131
+ image: mediaShareImage(ctx.image(seo?.image), opts.baseUrl) ?? defaults.image,
132
+ ogType,
133
+ // publishedAt comes with part 3 (content model): read doc.publishedAt here once LiveDocument has it.
134
+ article: ogType === 'article' ? { publishedTime: doc.publishedAt, modifiedTime: doc.updatedAt } : null,
126
135
  canonical: own === null || base === null ? null : opts.page > 1 ? `${base}?page=${opts.page}` : base,
127
136
  alternates: doc.fallback ? [] : alternates.filter((a) => !a.fallback),
128
137
  defaultLocale: core.registry.defaultLocale,
129
- image: ctx.image(seo?.image),
130
138
  baseUrl: opts.baseUrl,
131
139
  preview: opts.state === 'preview',
140
+ collected: ctx.headTags(),
132
141
  });
133
142
  let out = injectHead(html, head);
134
143
  if (internal.pane && doc.path !== null) {
@@ -152,6 +161,7 @@ export async function renderTemplateData(core, template, data, opts) {
152
161
  page: 1,
153
162
  baseUrl: opts.baseUrl,
154
163
  alternates: [],
164
+ ...(opts.assets && { assets: opts.assets }),
155
165
  });
156
166
  await ctx.preloadData(template, data);
157
167
  const field = data.fields.title;
@@ -163,19 +173,24 @@ export async function renderTemplateData(core, template, data, opts) {
163
173
  contentLocale: opts.locale,
164
174
  fallback: false,
165
175
  path: opts.path,
176
+ publishedAt: null,
166
177
  page: 1,
167
178
  };
168
179
  const html = await renderBody(template, data, page, ctx, {});
169
180
  const seo = seoValue(template.fields, data.fields);
181
+ const defaults = await resolveSeoDefaults(core.registry, ctx, opts.baseUrl);
170
182
  const head = buildHead({
171
- title,
172
- seo,
173
- canonical: null,
183
+ title: pageTitle(title, seo?.title, defaults.titleTemplate, false),
184
+ description: seo?.description || defaults.description || null,
185
+ image: mediaShareImage(ctx.image(seo?.image), opts.baseUrl) ?? defaults.image,
186
+ ogType: template.ogType ?? 'website',
187
+ article: null,
188
+ canonical: opts.canonical ?? null,
174
189
  alternates: [],
175
190
  defaultLocale: core.registry.defaultLocale,
176
- image: ctx.image(seo?.image),
177
191
  baseUrl: opts.baseUrl,
178
- preview: false,
192
+ preview: opts.preview === true,
193
+ collected: ctx.headTags(),
179
194
  });
180
195
  return withDoctype(injectHead(html, head));
181
196
  }
@@ -1,12 +1,18 @@
1
1
  import type { FastifyBaseLogger, FastifyInstance } from 'fastify';
2
2
  import type { Core } from '../../core/core.js';
3
3
  import type { Registry } from '../../core/registry/registry.js';
4
+ import { type PublicAssets } from './assets.js';
4
5
  export interface ReleaseRouteOptions {
5
6
  core: Core;
6
7
  registry: Registry;
7
8
  baseUrl: string;
9
+ assets?: PublicAssets;
10
+ /** The site is a staged release's forced preview: its renders stay noindex, with no canonical. */
11
+ preview?: boolean;
8
12
  /** Host-supplied secret values; a route sees only the ones its site declares. */
9
13
  secrets: Readonly<Record<string, string>>;
14
+ /** What a route gets as `ctx.fetch`. */
15
+ fetch: typeof fetch;
10
16
  log: FastifyBaseLogger;
11
17
  }
12
18
  /**
@@ -1,6 +1,8 @@
1
1
  import { normalizeContent } from '../../core/content/schema.js';
2
2
  import { readData } from '../../core/content/reader.js';
3
3
  import { t } from '../../core/messages/index.js';
4
+ import { encodePath } from '../../core/site/paths.js';
5
+ import { publicAssets } from './assets.js';
4
6
  import { queryApi } from './context.js';
5
7
  import { catalogPage, renderTemplateData } from './render.js';
6
8
  const BODY_LIMIT = 1024 * 1024;
@@ -59,6 +61,7 @@ function send(reply, res) {
59
61
  */
60
62
  export function registerReleaseRoutes(app, opts) {
61
63
  const { core, registry, baseUrl, log } = opts;
64
+ const assets = opts.assets ?? publicAssets(null);
62
65
  const routes = registry.site.routes;
63
66
  if (routes.length === 0)
64
67
  return;
@@ -105,17 +108,19 @@ export function registerReleaseRoutes(app, opts) {
105
108
  locale,
106
109
  };
107
110
  const ctx = {
108
- query: queryApi(core, { locale, baseUrl }),
111
+ query: queryApi(core, { locale, baseUrl, assets }),
109
112
  async render(template, data = {}, o = {}) {
110
113
  const read = templateRegistry(registry, template);
111
114
  const doc = readData(read, template.name, normalizeContent(read, template.name, data), { fill: true }).data;
112
- const html = await renderTemplateData(core, template, doc, { locale, path: route.path, baseUrl });
115
+ const canonical = route.sitemap === true && request.url.split('?')[0] === encodePath(route.path) ? route.path : null;
116
+ const html = await renderTemplateData(core, template, doc, { locale, path: route.path, baseUrl, canonical, assets, preview: opts.preview === true });
113
117
  return { status: o.status ?? 200, headers: { 'content-type': HTML }, body: html };
114
118
  },
115
- fetch: (input, init) => globalThis.fetch(input, init),
119
+ fetch: opts.fetch,
116
120
  secrets,
117
121
  redirect: (location, status = 303) => ({ status, headers: { location } }),
118
122
  baseUrl,
123
+ asset: (path) => assets.url(path),
119
124
  locale,
120
125
  };
121
126
  return send(reply, await route.handler(req, ctx));
@@ -0,0 +1,20 @@
1
+ import type { RenderContext, ResolvedImage } from '../../core/registry/render.js';
2
+ import type { Registry } from '../../core/registry/registry.js';
3
+ /** The site's effective search and sharing defaults for one render. */
4
+ export interface SeoDefaults {
5
+ titleTemplate: string | null;
6
+ description: string | null;
7
+ /** Absolute URL of the default share image. */
8
+ image: string | null;
9
+ }
10
+ /** The 1280px JPEG variant of a raster `image`, as an absolute URL; `null` for none or a non-raster one. */
11
+ export declare function mediaShareImage(image: ResolvedImage | null, baseUrl: string): string | null;
12
+ /**
13
+ * Each default from the `f.seoDefaults()` global (read through `ctx`, so preview and its per-render cache apply)
14
+ * when filled in, then from the site's code, then `null`.
15
+ */
16
+ export declare function resolveSeoDefaults(registry: Registry, ctx: RenderContext, baseUrl: string): Promise<SeoDefaults>;
17
+ /** `seoTitle` exactly when set; else `fallback`, through `titleTemplate` unless on the home page. */
18
+ export declare function pageTitle(fallback: string, seoTitle: string | undefined, titleTemplate: string | null, home: boolean): string;
19
+ /** Whether `path` is the home page: `/` or a locale root such as `/es`. */
20
+ export declare function isHomePath(registry: Registry, path: string | null): boolean;
@@ -0,0 +1,45 @@
1
+ import { isTitleTemplate } from '../../core/fields/builtins.js';
2
+ const RASTER = /^image\/(jpeg|png|webp|gif|avif|tiff)$/;
3
+ const filled = (v) => typeof v === 'string' && v !== '';
4
+ /** The 1280px JPEG variant of a raster `image`, as an absolute URL; `null` for none or a non-raster one. */
5
+ export function mediaShareImage(image, baseUrl) {
6
+ if (!image || !RASTER.test(image.mime))
7
+ return null;
8
+ return `${baseUrl}/media/${encodeURIComponent(image.id)}/1280.jpeg`;
9
+ }
10
+ /**
11
+ * Each default from the `f.seoDefaults()` global (read through `ctx`, so preview and its per-render cache apply)
12
+ * when filled in, then from the site's code, then `null`.
13
+ */
14
+ export async function resolveSeoDefaults(registry, ctx, baseUrl) {
15
+ let stored = {};
16
+ if (registry.seoDefaults) {
17
+ const fields = (await ctx.global(registry.seoDefaults.global));
18
+ const value = fields?.[registry.seoDefaults.field];
19
+ if (value && typeof value === 'object')
20
+ stored = value;
21
+ }
22
+ const code = registry.site.seo;
23
+ const titleTemplate = filled(stored.titleTemplate) && isTitleTemplate(stored.titleTemplate) ? stored.titleTemplate : null;
24
+ const description = filled(stored.description) ? stored.description : null;
25
+ const image = mediaShareImage(ctx.image(stored.image), baseUrl);
26
+ return {
27
+ titleTemplate: titleTemplate ?? code.titleTemplate ?? null,
28
+ description: description ?? (filled(code.description) ? code.description : null),
29
+ image: image ?? (code.image ? `${baseUrl}${ctx.asset(code.image)}` : null),
30
+ };
31
+ }
32
+ /** `seoTitle` exactly when set; else `fallback`, through `titleTemplate` unless on the home page. */
33
+ export function pageTitle(fallback, seoTitle, titleTemplate, home) {
34
+ if (seoTitle)
35
+ return seoTitle;
36
+ if (titleTemplate === null || home)
37
+ return fallback;
38
+ return titleTemplate.replace('%s', () => fallback);
39
+ }
40
+ /** Whether `path` is the home page: `/` or a locale root such as `/es`. */
41
+ export function isHomePath(registry, path) {
42
+ if (path === null)
43
+ return false;
44
+ return path === '/' || registry.locales.some((locale) => path === `/${locale}`);
45
+ }