mdorigin 0.6.0 → 0.7.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/README.md CHANGED
@@ -27,6 +27,12 @@ That means `mdorigin` should own content semantics, while page rendering remains
27
27
 
28
28
  ## Install
29
29
 
30
+ Use a patched Node.js release: 22.23.4+, 24.22.1+, or 26.12.1+ within
31
+ their supported even-numbered major lines. These are the minimum versions
32
+ for the October 21, 2026 security release, not a guarantee against future issues.
33
+ Development and CI use Node 24.22.1 from `.nvmrc` (`nvm install && nvm use`).
34
+ An npm install does not upgrade the Node executable on your deployment host.
35
+
30
36
  ```bash
31
37
  npm install -g mdorigin
32
38
  ```
@@ -1,9 +1,10 @@
1
1
  import type { ResolvedSiteConfig } from './site-config.js';
2
- import type { SearchApi } from '../search.js';
2
+ import type { SearchApi, SearchHit } from '../search.js';
3
3
  export interface ApiRouteOptions {
4
4
  searchApi?: SearchApi;
5
5
  siteConfig: ResolvedSiteConfig;
6
6
  requestUrl?: string;
7
+ resolveCitation?: (hit: SearchHit) => Promise<string | undefined>;
7
8
  }
8
9
  export interface ApiRouteResponse {
9
10
  status: number;
package/dist/core/api.js CHANGED
@@ -25,7 +25,7 @@ export async function handleApiRoute(pathname, searchParams, options) {
25
25
  topK,
26
26
  metadata,
27
27
  count: hits.length,
28
- hits: hits.map(serializeSearchHit),
28
+ hits: await Promise.all(hits.map(async (hit) => serializeSearchHit(hit, await options.resolveCitation?.(hit)))),
29
29
  });
30
30
  }
31
31
  return null;
@@ -102,6 +102,10 @@ function buildOpenApiDocument(options) {
102
102
  docId: { type: 'string' },
103
103
  relativePath: { type: 'string' },
104
104
  canonicalUrl: { type: 'string' },
105
+ citationUrl: {
106
+ type: 'string',
107
+ description: 'A rendered heading URL when a source-offset mapping is available; canonicalUrl stays page-level.',
108
+ },
105
109
  title: { type: 'string' },
106
110
  summary: { type: 'string' },
107
111
  score: { type: 'number' },
@@ -165,11 +169,12 @@ function readSearchMetadataFilters(searchParams) {
165
169
  }
166
170
  return Object.keys(metadata).length > 0 ? metadata : undefined;
167
171
  }
168
- function serializeSearchHit(hit) {
172
+ function serializeSearchHit(hit, citationUrl) {
169
173
  return {
170
174
  docId: hit.docId,
171
175
  relativePath: hit.relativePath,
172
176
  canonicalUrl: hit.canonicalUrl,
177
+ ...(citationUrl ? { citationUrl } : {}),
173
178
  title: hit.title,
174
179
  summary: hit.summary,
175
180
  metadata: hit.metadata,
@@ -1,2 +1,4 @@
1
1
  export declare const DIRECTORY_INDEX_FILENAMES: readonly ["index.md", "README.md", "SKILL.md"];
2
2
  export declare function getDirectoryIndexCandidates(directoryPath: string): string[];
3
+ /** Match request routing's index.md > README.md > SKILL.md preference. */
4
+ export declare function isCanonicalContentSource(contentPath: string, availablePaths: ReadonlySet<string>): boolean;
@@ -7,3 +7,9 @@ export const DIRECTORY_INDEX_FILENAMES = [
7
7
  export function getDirectoryIndexCandidates(directoryPath) {
8
8
  return DIRECTORY_INDEX_FILENAMES.map((filename) => directoryPath === '' ? filename : path.posix.join(directoryPath, filename));
9
9
  }
10
+ /** Match request routing's index.md > README.md > SKILL.md preference. */
11
+ export function isCanonicalContentSource(contentPath, availablePaths) {
12
+ const directory = path.posix.dirname(contentPath);
13
+ const candidates = getDirectoryIndexCandidates(directory === '.' ? '' : directory);
14
+ return !candidates.includes(contentPath) || candidates.find((candidate) => availablePaths.has(candidate)) === contentPath;
15
+ }
@@ -38,6 +38,7 @@ export interface PageRenderModel {
38
38
  bodyHtml: string;
39
39
  summary?: string;
40
40
  date?: string;
41
+ updated?: string;
41
42
  showSummary: boolean;
42
43
  showDate: boolean;
43
44
  topNav: SiteNavItem[];
@@ -53,6 +54,8 @@ export interface PageRenderModel {
53
54
  listingRequestPath: string;
54
55
  listingInitialPostCount: number;
55
56
  listingLoadMoreStep: number;
57
+ listingPage?: number;
58
+ listingPageCount?: number;
56
59
  searchEnabled: boolean;
57
60
  }
58
61
  export interface RenderHookContext {
@@ -1,8 +1,14 @@
1
1
  import type { ContentEntry } from './content-store.js';
2
+ import { type PageRobots } from './seo.js';
2
3
  export interface ParsedDocumentMeta {
3
4
  title?: string;
4
5
  name?: string;
5
6
  date?: string;
7
+ updated?: string;
8
+ author?: string | string[];
9
+ robots?: PageRobots;
10
+ /** Independent of external search indexing; false excludes this document from site search. */
11
+ search?: boolean;
6
12
  summary?: string;
7
13
  description?: string;
8
14
  draft?: boolean;
@@ -36,6 +42,13 @@ export interface ParsedDocumentLite {
36
42
  export interface ParsedDocument extends ParsedDocumentLite {
37
43
  html: string;
38
44
  }
45
+ export interface MarkdownHeading {
46
+ id: string;
47
+ text: string;
48
+ depth: number;
49
+ /** Offset in the exact Markdown string passed to the renderer. */
50
+ charStart: number;
51
+ }
39
52
  export declare function getDocumentTitle(meta: ParsedDocumentMeta, body: string, fallback: string): string;
40
53
  export declare function getDocumentSummary(meta: ParsedDocumentMeta, body: string): string | undefined;
41
54
  export declare function parseMarkdownDocument(sourcePath: string, markdown: string): Promise<ParsedDocument>;
@@ -49,6 +62,10 @@ export declare function parseDocumentMeta(sourcePath: string, markdown: string):
49
62
  */
50
63
  export declare function parseEntryDocumentMeta(entry: ContentEntry): ParsedDocumentLite;
51
64
  export declare function renderMarkdown(markdown: string): Promise<string>;
65
+ export declare function renderMarkdownWithHeadings(markdown: string): Promise<{
66
+ html: string;
67
+ headings: MarkdownHeading[];
68
+ }>;
52
69
  export declare function rewriteMarkdownLinksInHtml(html: string): string;
53
70
  export declare function stripManagedIndexBlock(markdown: string): string;
54
71
  export declare function stripMachineOnlyMarkdownComments(markdown: string): string;
@@ -1,9 +1,11 @@
1
1
  import matter from 'gray-matter';
2
+ import yaml from 'js-yaml';
2
3
  import { remark } from 'remark';
3
4
  import remarkGfm from 'remark-gfm';
4
5
  import remarkRehype from 'remark-rehype';
5
6
  import rehypeRaw from 'rehype-raw';
6
7
  import rehypeStringify from 'rehype-stringify';
8
+ import { normalizeContentDate, normalizePageRobots } from './seo.js';
7
9
  export function getDocumentTitle(meta, body, fallback) {
8
10
  return (firstNonEmptyString(meta.title, meta.name) ??
9
11
  extractFirstHeading(body) ??
@@ -24,7 +26,11 @@ export async function parseMarkdownDocument(sourcePath, markdown) {
24
26
  };
25
27
  }
26
28
  export function parseDocumentMeta(sourcePath, markdown) {
27
- const parsed = matter(markdown);
29
+ const parsed = matter(markdown, {
30
+ engines: {
31
+ yaml: (source) => yaml.safeLoad(source, { schema: FRONTMATTER_SCHEMA }),
32
+ },
33
+ });
28
34
  return {
29
35
  sourcePath,
30
36
  body: parsed.content,
@@ -49,13 +55,64 @@ export function parseEntryDocumentMeta(entry) {
49
55
  return parsed;
50
56
  }
51
57
  export async function renderMarkdown(markdown) {
58
+ return (await renderMarkdownWithHeadings(markdown)).html;
59
+ }
60
+ export async function renderMarkdownWithHeadings(markdown) {
61
+ const headings = [];
52
62
  const output = await remark()
53
63
  .use(remarkGfm)
54
64
  .use(remarkRehype, { allowDangerousHtml: true })
55
65
  .use(rehypeRaw)
66
+ .use(() => (tree) => assignHeadingIds(tree, headings))
56
67
  .use(rehypeStringify, { allowDangerousHtml: true })
57
68
  .process(markdown);
58
- return String(output);
69
+ return { html: String(output), headings };
70
+ }
71
+ function assignHeadingIds(root, headings) {
72
+ const reserved = new Set();
73
+ const seen = new Set();
74
+ const visit = (node, callback) => {
75
+ callback(node);
76
+ for (const child of node.children ?? [])
77
+ visit(child, callback);
78
+ };
79
+ visit(root, (node) => {
80
+ if (typeof node.properties?.id === 'string')
81
+ reserved.add(node.properties.id);
82
+ });
83
+ const unique = (base) => {
84
+ let id = base;
85
+ let suffix = 0;
86
+ while (reserved.has(id))
87
+ id = `${base}-${++suffix}`;
88
+ reserved.add(id);
89
+ return id;
90
+ };
91
+ const text = (node) => node.type === 'comment' ? '' :
92
+ node.value ?? (node.tagName === 'img' ? String(node.properties?.alt ?? '') : (node.children ?? []).map(text).join(''));
93
+ visit(root, (node) => {
94
+ let id = typeof node.properties?.id === 'string' ? node.properties.id : undefined;
95
+ if (id !== undefined) {
96
+ if (seen.has(id)) {
97
+ id = unique(id);
98
+ node.properties.id = id;
99
+ }
100
+ seen.add(id);
101
+ }
102
+ if (!/^h[1-6]$/.test(node.tagName ?? ''))
103
+ return;
104
+ const label = text(node);
105
+ if (!id) {
106
+ const slug = label.normalize('NFKC').toLowerCase().trim()
107
+ .replace(/\s+/g, '-').replace(/[^\p{L}\p{N}\p{M}_-]/gu, '') || 'section';
108
+ id = unique(slug);
109
+ node.properties = { ...node.properties, id };
110
+ }
111
+ const offset = node.position?.start?.offset;
112
+ if (typeof offset === 'number') {
113
+ headings.push({ id, text: label, depth: Number(node.tagName[1]), charStart: offset });
114
+ }
115
+ });
59
116
  }
60
117
  export function rewriteMarkdownLinksInHtml(html) {
61
118
  return html.replaceAll(/(<a\b[^>]*?\shref=")([^"]+)(")/g, (_match, prefix, href, suffix) => `${prefix}${rewriteMarkdownHref(href)}${suffix}`);
@@ -143,6 +200,18 @@ function extractManagedIndexDetail(lines) {
143
200
  }
144
201
  return undefined;
145
202
  }
203
+ // Preserve YAML timestamp spelling until our calendar/timezone validator runs.
204
+ // The default YAML Date constructor silently rolls e.g. February 30 into March.
205
+ const RAW_TIMESTAMP = new yaml.Type('tag:yaml.org,2002:timestamp', {
206
+ kind: 'scalar',
207
+ resolve: (value) => /^\d{4}-\d{1,2}-\d{1,2}(?:$|[Tt\s])/.test(value),
208
+ construct: (value) => value,
209
+ });
210
+ const FRONTMATTER_SCHEMA = new yaml.Schema({
211
+ include: [yaml.DEFAULT_SAFE_SCHEMA],
212
+ implicit: [RAW_TIMESTAMP],
213
+ explicit: [RAW_TIMESTAMP],
214
+ });
146
215
  function normalizeMeta(data) {
147
216
  const meta = { ...data };
148
217
  if (typeof data.title === 'string') {
@@ -151,12 +220,24 @@ function normalizeMeta(data) {
151
220
  if (typeof data.name === 'string') {
152
221
  meta.name = data.name;
153
222
  }
154
- if (typeof data.date === 'string') {
155
- meta.date = data.date;
156
- }
157
- if (data.date instanceof Date && !Number.isNaN(data.date.getTime())) {
158
- meta.date = data.date.toISOString().slice(0, 10);
159
- }
223
+ for (const key of ['date', 'updated']) {
224
+ const normalized = normalizeContentDate(data[key]);
225
+ if (normalized === undefined)
226
+ delete meta[key];
227
+ else
228
+ meta[key] = normalized;
229
+ }
230
+ meta.robots = normalizePageRobots(data.robots);
231
+ if (data.noindex === true)
232
+ meta.robots = { ...meta.robots, index: false };
233
+ if (typeof data.author === 'string' && data.author.trim())
234
+ meta.author = data.author.trim();
235
+ else if (Array.isArray(data.author))
236
+ meta.author = data.author.filter((author) => typeof author === 'string' && author.trim().length > 0).map((author) => author.trim());
237
+ else
238
+ delete meta.author;
239
+ if (typeof data.search !== 'boolean')
240
+ delete meta.search;
160
241
  if (typeof data.summary === 'string') {
161
242
  meta.summary = data.summary;
162
243
  }
@@ -1,9 +1,11 @@
1
1
  import path from 'node:path';
2
2
  import { isIgnoredContentName } from './content-store.js';
3
3
  import { inferDirectoryContentType, resolveContentType, } from './content-type.js';
4
- import { getDirectoryIndexCandidates } from './directory-index.js';
4
+ import { getDirectoryIndexCandidates, isCanonicalContentSource } from './directory-index.js';
5
5
  import { extractManagedIndexEntries, getDocumentSummary, getDocumentTitle as getParsedDocumentTitle, parseEntryDocumentMeta, parseMarkdownDocument, stripManagedIndexBlock, stripManagedIndexLinks, stripMachineOnlyMarkdownComments, } from './markdown.js';
6
6
  import { ensureTrailingSlash, trimLeadingSlash } from './site-url.js';
7
+ import { buildPageStructuredData, serializePageRobots } from './seo.js';
8
+ import { resolveSearchCitation } from './search-citations.js';
7
9
  import { applyIndexTransforms, renderFooterOverride, renderHeaderOverride, renderPageWithPlugins, transformHtmlWithPlugins, } from './extensions.js';
8
10
  import { handleApiRoute } from './api.js';
9
11
  import { matchRequestLocale, normalizeRequestPath, resolveRequest } from './router.js';
@@ -53,10 +55,35 @@ async function handleSiteRequestWithoutLocaleDetection(store, pathname, options)
53
55
  searchApi: options.searchApi,
54
56
  siteConfig: options.siteConfig,
55
57
  requestUrl: options.requestUrl,
58
+ resolveCitation: (hit) => resolveSearchCitation(store, hit, options.draftMode),
56
59
  });
57
60
  if (apiRoute !== null) {
58
61
  return apiRoute;
59
62
  }
63
+ if (pathname === '/robots.txt') {
64
+ const custom = await store.get('robots.txt');
65
+ if (custom !== null)
66
+ return serveAsset(custom);
67
+ const rules = options.siteConfig.robots?.rules ?? [];
68
+ const lines = rules.flatMap((rule) => [
69
+ `User-agent: ${rule.userAgent}`,
70
+ ...(rule.allow ?? []).map((href) => `Allow: ${href}`),
71
+ ...(rule.disallow ?? []).map((href) => `Disallow: ${href}`),
72
+ '',
73
+ ]);
74
+ if (options.siteConfig.siteUrl)
75
+ lines.push(`Sitemap: ${options.siteConfig.siteUrl}/sitemap.xml`);
76
+ if (lines.length > 0) {
77
+ return { status: 200, headers: { 'content-type': 'text/plain; charset=utf-8' }, body: `${lines.join('\n')}\n` };
78
+ }
79
+ }
80
+ if (pathname === '/llms.txt') {
81
+ const custom = await store.get('llms.txt');
82
+ if (custom !== null)
83
+ return serveAsset(custom);
84
+ if (options.siteConfig.llmsTxt)
85
+ return renderLlmsDirectory(store, options);
86
+ }
60
87
  if (pathname === '/sitemap.xml') {
61
88
  return renderSitemap(store, options);
62
89
  }
@@ -122,6 +149,7 @@ async function handleSiteRequestWithoutLocaleDetection(store, pathname, options)
122
149
  status: 200,
123
150
  headers: withVaryAcceptIfNeeded({
124
151
  'content-type': entry.mediaType,
152
+ ...getContentResponseHeaders(resolved.sourcePath, parsed.meta, options.siteConfig),
125
153
  }, negotiatedMarkdown),
126
154
  body: entry.text,
127
155
  };
@@ -161,6 +189,7 @@ async function handleSiteRequestWithoutLocaleDetection(store, pathname, options)
161
189
  requestLocale,
162
190
  draftMode: options.draftMode,
163
191
  varyOnAccept: shouldVaryOnAccept(resolved),
192
+ searchParams: options.searchParams,
164
193
  });
165
194
  }
166
195
  function getListingFragmentRequest(searchParams) {
@@ -194,6 +223,58 @@ function normalizePositiveInteger(value) {
194
223
  * into site-root-relative paths; the host itself is never emitted.
195
224
  */
196
225
  const SOCIAL_IMAGE_RESOLUTION_BASE = 'http://mdorigin.local';
226
+ function getContentResponseHeaders(sourcePath, meta, config, canonicalPath = getCanonicalHtmlPathForContentPath(sourcePath)) {
227
+ const headers = {};
228
+ const robots = serializePageRobots(meta.robots);
229
+ if (robots)
230
+ headers['x-robots-tag'] = robots;
231
+ const canonicalUrl = config.siteUrl
232
+ ? new URL(`${config.siteUrl}${canonicalPath}`).href
233
+ : encodeURI(canonicalPath);
234
+ const links = [`<${canonicalUrl}>; rel="canonical"`];
235
+ if (config.llmsTxt)
236
+ links.push('</llms.txt>; rel="describedby"; type="text/plain"');
237
+ headers.link = links.join(', ');
238
+ return headers;
239
+ }
240
+ async function renderLlmsDirectory(store, options) {
241
+ const entries = await collectSitemapEntries(store, '', { ...options, draftMode: 'exclude' });
242
+ const singleLine = (value) => value.replace(/[\r\n]/g, ' ').replace(/([\\[\]])/g, '\\$1').slice(0, 1000);
243
+ const lines = [
244
+ `# ${singleLine(options.siteConfig.siteTitle)}`,
245
+ '',
246
+ ...(options.siteConfig.siteDescription ? [`> ${singleLine(options.siteConfig.siteDescription)}`, ''] : []),
247
+ 'Read pages as Markdown using the links below, or send Accept: text/markdown to their canonical HTML URLs.',
248
+ '',
249
+ '## Search',
250
+ '',
251
+ ...(options.searchApi ? ['- [Search API](/api/search): GET with a required q parameter.'] : []),
252
+ '- [OpenAPI](/api/openapi.json)',
253
+ ];
254
+ // A small discovery directory, never a full-content dump. Stable order and budget.
255
+ let section = '';
256
+ for (const entry of entries.slice(0, 200)) {
257
+ const locale = matchRequestLocale(entry.path, options.siteConfig.locales);
258
+ const prefix = locale?.pathPrefix ?? '';
259
+ const relative = entry.path.slice(prefix.length).replace(/^\//, '');
260
+ const group = `${locale?.code ?? options.siteConfig.locale ?? 'en'} / ${relative.split('/')[0] || 'Home'}`;
261
+ const encodedPath = entry.sourcePath.split('/').map(encodeURIComponent).join('/');
262
+ const href = `${options.siteConfig.siteUrl ?? ''}/${encodedPath}`;
263
+ const additions = [
264
+ ...(group === section ? [] : ['', `## ${singleLine(group)}`, '']),
265
+ `- [${singleLine(entry.title)}](<${href.replaceAll('>', '%3E').replaceAll('<', '%3C')}>)`,
266
+ ];
267
+ if (new TextEncoder().encode(`${[...lines, ...additions].join('\n')}\n`).byteLength > 32_000)
268
+ break;
269
+ section = group;
270
+ lines.push(...additions);
271
+ }
272
+ return {
273
+ status: 200,
274
+ headers: { 'content-type': 'text/plain; charset=utf-8' },
275
+ body: `${lines.join('\n')}\n`,
276
+ };
277
+ }
197
278
  function resolvePageSocialImage(href, requestPath) {
198
279
  if (!href) {
199
280
  return undefined;
@@ -222,10 +303,9 @@ function buildPageRenderModel(options) {
222
303
  title: getDocumentTitle(options.parsed),
223
304
  meta: options.parsed.meta,
224
305
  bodyHtml: options.renderedBodyHtml,
225
- summary: options.siteConfig.showSummary === false
226
- ? undefined
227
- : getDocumentSummary(options.parsed.meta, options.parsed.body),
228
- date: options.siteConfig.showDate === false ? undefined : options.parsed.meta.date,
306
+ summary: getDocumentSummary(options.parsed.meta, options.parsed.body),
307
+ date: options.parsed.meta.date,
308
+ updated: options.parsed.meta.updated,
229
309
  showSummary: options.siteConfig.showSummary,
230
310
  showDate: options.siteConfig.showDate,
231
311
  topNav: options.topNav,
@@ -250,7 +330,6 @@ async function renderStructuredPage(options) {
250
330
  const messages = getEffectiveLocaleMessages(options.siteConfig, localeConfig);
251
331
  const htmlLang = getFrontmatterLocale(options.parsed.meta) ?? localeCode;
252
332
  const languages = await buildLanguageOptions(options.store, { sourcePath: options.sourcePath }, localeConfig, options.siteConfig, options.draftMode);
253
- const hreflangAlternates = buildHreflangAlternates(languages, options.siteConfig);
254
333
  const searchLocaleFilter = buildSearchLocaleFilter(options.siteConfig, localeConfig);
255
334
  const page = buildPageRenderModel({
256
335
  resolvedRequestPath: options.requestPath,
@@ -267,6 +346,25 @@ async function renderStructuredPage(options) {
267
346
  listingEntries: options.listingEntries,
268
347
  searchEnabled: options.searchEnabled,
269
348
  });
349
+ const rawPage = options.searchParams?.get('page') ?? '1';
350
+ const pageNumber = /^[1-9]\d*$/.test(rawPage) ? Number(rawPage) : NaN;
351
+ const pageSize = Math.max(1, page.listingInitialPostCount);
352
+ const articleCount = page.listingEntries.filter((entry) => entry.kind === 'article').length;
353
+ const pageCount = Math.max(1, Math.ceil(articleCount / pageSize));
354
+ if (!Number.isSafeInteger(pageNumber) || pageNumber > pageCount)
355
+ return notFound();
356
+ // Translated catalogs can differ in length and ordering; later pages are not
357
+ // verified language equivalents, even when both locales have that page number.
358
+ const hreflangAlternates = pageNumber === 1
359
+ ? buildHreflangAlternates(languages, options.siteConfig)
360
+ : [];
361
+ page.listingPage = pageNumber;
362
+ page.listingPageCount = pageCount;
363
+ page.listingRequestPath = page.canonicalPath ?? options.requestPath;
364
+ if (pageNumber > 1) {
365
+ page.canonicalPath = `${page.canonicalPath}?page=${pageNumber}`;
366
+ page.title = `${page.title} — ${formatSiteMessage(messages['listing.pageLabel'], { page: String(pageNumber) })}`;
367
+ }
270
368
  const renderContext = {
271
369
  page,
272
370
  siteConfig: options.siteConfig,
@@ -291,6 +389,21 @@ async function renderStructuredPage(options) {
291
389
  body: currentPage.bodyHtml,
292
390
  summary: currentPage.summary,
293
391
  date: currentPage.date,
392
+ robots: serializePageRobots(currentPage.meta.robots),
393
+ discoveryPath: options.siteConfig.llmsTxt ? '/llms.txt' : undefined,
394
+ structuredData: options.siteConfig.structuredData ? buildPageStructuredData({
395
+ title: currentPage.title,
396
+ description: currentPage.summary ?? currentPage.siteDescription,
397
+ url: currentPage.siteUrl && currentPage.canonicalPath
398
+ ? `${currentPage.siteUrl}${currentPage.canonicalPath}` : undefined,
399
+ siteTitle: currentPage.siteTitle,
400
+ siteUrl: currentPage.siteUrl,
401
+ locale: htmlLang,
402
+ type: currentPage.meta.type,
403
+ date: currentPage.date,
404
+ updated: currentPage.updated,
405
+ author: currentPage.meta.author,
406
+ }) : undefined,
294
407
  showSummary: currentPage.showSummary,
295
408
  showDate: currentPage.showDate,
296
409
  topNav: currentPage.topNav,
@@ -306,6 +419,8 @@ async function renderStructuredPage(options) {
306
419
  listingRequestPath: currentPage.listingRequestPath,
307
420
  listingInitialPostCount: currentPage.listingInitialPostCount,
308
421
  listingLoadMoreStep: currentPage.listingLoadMoreStep,
422
+ listingPage: currentPage.listingPage,
423
+ listingPageCount: currentPage.listingPageCount,
309
424
  searchEnabled: currentPage.searchEnabled,
310
425
  languages: currentPage.languages,
311
426
  hreflangAlternates,
@@ -322,6 +437,7 @@ async function renderStructuredPage(options) {
322
437
  status: 200,
323
438
  headers: withVaryAcceptIfNeeded({
324
439
  'content-type': 'text/html; charset=utf-8',
440
+ ...getContentResponseHeaders(options.sourcePath, options.parsed.meta, options.siteConfig, page.canonicalPath),
325
441
  }, options.varyOnAccept ?? false),
326
442
  body: finalHtml,
327
443
  };
@@ -334,6 +450,7 @@ function renderListingPostsFragment(entries, request) {
334
450
  status: 200,
335
451
  headers: {
336
452
  'content-type': 'application/json; charset=utf-8',
453
+ 'x-robots-tag': 'noindex',
337
454
  },
338
455
  body: JSON.stringify({
339
456
  itemsHtml: renderListingArticleItems(visibleArticles),
@@ -801,6 +918,7 @@ async function collectSitemapEntries(store, directoryPath, options) {
801
918
  return [];
802
919
  }
803
920
  const sitemapEntries = [];
921
+ const availablePaths = new Set(entries.map((entry) => entry.path));
804
922
  for (const entry of entries) {
805
923
  if (entry.kind === 'directory') {
806
924
  sitemapEntries.push(...(await collectSitemapEntries(store, entry.path, options)));
@@ -814,12 +932,16 @@ async function collectSitemapEntries(store, directoryPath, options) {
814
932
  continue;
815
933
  }
816
934
  const parsed = parseEntryDocumentMeta(document);
817
- if (parsed.meta.draft === true && options.draftMode === 'exclude') {
935
+ if ((parsed.meta.draft === true && options.draftMode === 'exclude') || parsed.meta.robots?.index === false) {
818
936
  continue;
819
937
  }
938
+ if (!isCanonicalContentSource(entry.path, availablePaths))
939
+ continue;
820
940
  sitemapEntries.push({
821
941
  path: getCanonicalHtmlPathForContentPath(entry.path),
822
- lastmod: parsed.meta.date,
942
+ sourcePath: entry.path,
943
+ title: getDocumentTitle(parsed),
944
+ lastmod: parsed.meta.updated ?? parsed.meta.date,
823
945
  });
824
946
  }
825
947
  sitemapEntries.sort((left, right) => left.path.localeCompare(right.path));
@@ -846,6 +968,7 @@ async function collectRssFeedItems(store, directoryPath, options, excludedDirect
846
968
  }
847
969
  const feedItems = [];
848
970
  const directoryShape = inspectDirectoryShapeEntries(entries);
971
+ const availablePaths = new Set(entries.map((entry) => entry.path));
849
972
  for (const entry of entries) {
850
973
  if (entry.kind === 'directory') {
851
974
  if (excludedDirectories.has(entry.path)) {
@@ -862,9 +985,11 @@ async function collectRssFeedItems(store, directoryPath, options, excludedDirect
862
985
  continue;
863
986
  }
864
987
  const parsed = parseEntryDocumentMeta(document);
865
- if (parsed.meta.draft === true && options.draftMode === 'exclude') {
988
+ if ((parsed.meta.draft === true && options.draftMode === 'exclude') || parsed.meta.robots?.index === false) {
866
989
  continue;
867
990
  }
991
+ if (!isCanonicalContentSource(entry.path, availablePaths))
992
+ continue;
868
993
  const pubDate = parseFeedDate(parsed.meta.date);
869
994
  if (pubDate === null) {
870
995
  continue;
@@ -1037,6 +1162,7 @@ async function tryRenderAlternateDirectoryIndex(store, requestPath, options) {
1037
1162
  // a raw markdown variant through Accept negotiation; the HTML variant
1038
1163
  // must therefore declare Vary: Accept like every other negotiated route.
1039
1164
  varyOnAccept: true,
1165
+ searchParams: options.searchParams,
1040
1166
  });
1041
1167
  }
1042
1168
  return null;
@@ -1065,6 +1191,7 @@ async function tryServeAlternateDirectoryMarkdown(store, resolved, options, nego
1065
1191
  status: 200,
1066
1192
  headers: withVaryAcceptIfNeeded({
1067
1193
  'content-type': entry.mediaType,
1194
+ ...getContentResponseHeaders(candidatePath, parsed.meta, options.siteConfig),
1068
1195
  }, true),
1069
1196
  body: entry.text,
1070
1197
  };
@@ -0,0 +1,10 @@
1
+ import { type ContentStore } from './content-store.js';
2
+ import type { SearchHit } from '../search.js';
3
+ export declare function getSearchableMarkdownBody(body: string): string;
4
+ export declare function getSearchContentRevision(content: string): Promise<string>;
5
+ /**
6
+ * indexbind 0.6.x calls these fields charStart/charEnd, but uses UTF-8 byte
7
+ * offsets into the transformed search content, not JS string or raw-file offsets.
8
+ * Never guess a fragment from headingPath or publish a stale/ambiguous mapping.
9
+ */
10
+ export declare function resolveSearchCitation(store: ContentStore, hit: SearchHit, draftMode: 'include' | 'exclude'): Promise<string | undefined>;
@@ -0,0 +1,65 @@
1
+ import { normalizeContentPath } from './content-store.js';
2
+ import { isCanonicalContentSource } from './directory-index.js';
3
+ import { parseEntryDocumentMeta, renderMarkdownWithHeadings, stripManagedIndexBlock, stripMachineOnlyMarkdownComments } from './markdown.js';
4
+ export function getSearchableMarkdownBody(body) {
5
+ return stripMachineOnlyMarkdownComments(stripManagedIndexBlock(body)).trim();
6
+ }
7
+ export async function getSearchContentRevision(content) {
8
+ const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(content));
9
+ return Array.from(new Uint8Array(hash), (byte) => byte.toString(16).padStart(2, '0')).join('');
10
+ }
11
+ const citationCache = new WeakMap();
12
+ /**
13
+ * indexbind 0.6.x calls these fields charStart/charEnd, but uses UTF-8 byte
14
+ * offsets into the transformed search content, not JS string or raw-file offsets.
15
+ * Never guess a fragment from headingPath or publish a stale/ambiguous mapping.
16
+ */
17
+ export async function resolveSearchCitation(store, hit, draftMode) {
18
+ if (!hit.canonicalUrl || typeof hit.metadata.contentRevision !== 'string')
19
+ return undefined;
20
+ const sourcePath = normalizeContentPath(hit.relativePath);
21
+ if (sourcePath === null || !sourcePath.endsWith('.md'))
22
+ return undefined;
23
+ const entry = await store.get(sourcePath);
24
+ if (!entry || entry.kind !== 'text' || entry.text === undefined)
25
+ return undefined;
26
+ const directoryPath = sourcePath.includes('/') ? sourcePath.slice(0, sourcePath.lastIndexOf('/')) : '';
27
+ const entries = await store.listDirectory(directoryPath);
28
+ if (!isCanonicalContentSource(sourcePath, new Set(entries?.map((item) => item.path))))
29
+ return undefined;
30
+ const parsed = parseEntryDocumentMeta(entry);
31
+ if (parsed.meta.draft && draftMode === 'exclude')
32
+ return undefined;
33
+ let pending = citationCache.get(entry);
34
+ if (!pending) {
35
+ pending = (async () => {
36
+ const content = getSearchableMarkdownBody(parsed.body);
37
+ const { headings } = await renderMarkdownWithHeadings(content);
38
+ return {
39
+ content,
40
+ revision: await getSearchContentRevision(content),
41
+ headings: headings.map((heading) => ({
42
+ id: heading.id,
43
+ byteStart: new TextEncoder().encode(content.slice(0, heading.charStart)).byteLength,
44
+ })),
45
+ };
46
+ })();
47
+ citationCache.set(entry, pending);
48
+ }
49
+ const current = await pending;
50
+ if (current.revision !== hit.metadata.contentRevision)
51
+ return undefined;
52
+ // Upstream may locate repeated blocks with string.find(first occurrence).
53
+ // Only emit precise references when the excerpt's first block is unambiguous.
54
+ const prefix = Array.from(hit.bestMatch.excerpt.split(/\n\s*\n/)[0] ?? '').slice(0, 120).join('');
55
+ if (!prefix)
56
+ return undefined;
57
+ const start = current.content.indexOf(prefix);
58
+ if (start < 0 || current.content.indexOf(prefix, start + 1) >= 0)
59
+ return undefined;
60
+ const byteStart = new TextEncoder().encode(current.content.slice(0, start)).byteLength;
61
+ if (byteStart !== hit.bestMatch.charStart)
62
+ return undefined;
63
+ const heading = current.headings.filter((item) => item.byteStart <= byteStart).at(-1);
64
+ return heading ? `${hit.canonicalUrl.split('#')[0]}#${encodeURIComponent(heading.id)}` : undefined;
65
+ }
@@ -0,0 +1,33 @@
1
+ /** Validated, representation-independent indexing and preview directives. */
2
+ export interface PageRobots {
3
+ index?: boolean;
4
+ follow?: boolean;
5
+ maxSnippet?: number;
6
+ maxImagePreview?: 'none' | 'standard' | 'large';
7
+ maxVideoPreview?: number;
8
+ }
9
+ export interface RobotsRule {
10
+ userAgent: string;
11
+ allow?: string[];
12
+ disallow?: string[];
13
+ }
14
+ export interface SiteRobots {
15
+ rules: RobotsRule[];
16
+ }
17
+ export declare function normalizePageRobots(value: unknown): PageRobots | undefined;
18
+ export declare function serializePageRobots(robots: PageRobots | undefined): string | undefined;
19
+ /** Only ISO calendar dates or timestamps with an explicit timezone are accepted. */
20
+ export declare function normalizeContentDate(value: unknown): string | undefined;
21
+ export declare function normalizeSiteRobots(value: unknown): SiteRobots | undefined;
22
+ export declare function buildPageStructuredData(input: {
23
+ title: string;
24
+ description?: string;
25
+ url?: string;
26
+ siteTitle: string;
27
+ siteUrl?: string;
28
+ locale: string;
29
+ type?: string;
30
+ date?: string;
31
+ updated?: string;
32
+ author?: string | string[];
33
+ }): Record<string, unknown>;
@@ -0,0 +1,116 @@
1
+ export function normalizePageRobots(value) {
2
+ const result = {};
3
+ if (typeof value === 'string') {
4
+ for (const directive of value.toLowerCase().split(',').map((item) => item.trim())) {
5
+ if (directive === 'noindex' || directive === 'none')
6
+ result.index = false;
7
+ if (directive === 'nofollow' || directive === 'none')
8
+ result.follow = false;
9
+ if (directive === 'index' || directive === 'all')
10
+ result.index = true;
11
+ if (directive === 'follow' || directive === 'all')
12
+ result.follow = true;
13
+ const [key, raw] = directive.split(':').map((item) => item.trim());
14
+ if (key === 'max-snippet' && /^-?\d+$/.test(raw ?? ''))
15
+ result.maxSnippet = Number(raw);
16
+ if (key === 'max-video-preview' && /^-?\d+$/.test(raw ?? ''))
17
+ result.maxVideoPreview = Number(raw);
18
+ if (key === 'max-image-preview' && ['none', 'standard', 'large'].includes(raw)) {
19
+ result.maxImagePreview = raw;
20
+ }
21
+ }
22
+ }
23
+ else if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
24
+ const input = value;
25
+ if (typeof input.index === 'boolean')
26
+ result.index = input.index;
27
+ if (typeof input.follow === 'boolean')
28
+ result.follow = input.follow;
29
+ if (typeof input.maxSnippet === 'number')
30
+ result.maxSnippet = input.maxSnippet;
31
+ if (typeof input.maxVideoPreview === 'number')
32
+ result.maxVideoPreview = input.maxVideoPreview;
33
+ if (['none', 'standard', 'large'].includes(String(input.maxImagePreview))) {
34
+ result.maxImagePreview = input.maxImagePreview;
35
+ }
36
+ }
37
+ for (const key of ['maxSnippet', 'maxVideoPreview']) {
38
+ if (!Number.isSafeInteger(result[key]) || result[key] < -1)
39
+ delete result[key];
40
+ }
41
+ return Object.keys(result).length > 0 ? result : undefined;
42
+ }
43
+ export function serializePageRobots(robots) {
44
+ if (!robots)
45
+ return undefined;
46
+ const parts = [];
47
+ if (robots.index !== undefined)
48
+ parts.push(robots.index ? 'index' : 'noindex');
49
+ if (robots.follow !== undefined)
50
+ parts.push(robots.follow ? 'follow' : 'nofollow');
51
+ if (robots.maxSnippet !== undefined)
52
+ parts.push(`max-snippet:${robots.maxSnippet}`);
53
+ if (robots.maxImagePreview !== undefined)
54
+ parts.push(`max-image-preview:${robots.maxImagePreview}`);
55
+ if (robots.maxVideoPreview !== undefined)
56
+ parts.push(`max-video-preview:${robots.maxVideoPreview}`);
57
+ return parts.length > 0 ? parts.join(', ') : undefined;
58
+ }
59
+ /** Only ISO calendar dates or timestamps with an explicit timezone are accepted. */
60
+ export function normalizeContentDate(value) {
61
+ if (value instanceof Date) {
62
+ if (Number.isNaN(value.getTime()))
63
+ return undefined;
64
+ const iso = value.toISOString();
65
+ return iso.endsWith('T00:00:00.000Z') ? iso.slice(0, 10) : iso;
66
+ }
67
+ if (typeof value !== 'string')
68
+ return undefined;
69
+ const match = /^(\d{4})-(\d{2})-(\d{2})(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2}))?$/.exec(value);
70
+ if (!match)
71
+ return undefined;
72
+ const day = new Date(`${match[1]}-${match[2]}-${match[3]}T00:00:00Z`);
73
+ if (Number.isNaN(day.getTime()) || day.toISOString().slice(0, 10) !== value.slice(0, 10))
74
+ return undefined;
75
+ const timestamp = Date.parse(value);
76
+ if (!Number.isFinite(timestamp))
77
+ return undefined;
78
+ return value.length === 10 ? value : new Date(timestamp).toISOString();
79
+ }
80
+ export function normalizeSiteRobots(value) {
81
+ if (!value || typeof value !== 'object' || !('rules' in value) || !Array.isArray(value.rules)) {
82
+ return undefined;
83
+ }
84
+ const line = (item) => typeof item === 'string' && item.length > 0 && !/[\r\n\u0000]/.test(item);
85
+ const rules = [];
86
+ for (const rule of value.rules) {
87
+ if (!rule || typeof rule !== 'object' || !line(rule.userAgent))
88
+ continue;
89
+ rules.push({
90
+ userAgent: rule.userAgent,
91
+ allow: Array.isArray(rule.allow) ? rule.allow.filter(line) : [],
92
+ disallow: Array.isArray(rule.disallow) ? rule.disallow.filter(line) : [],
93
+ });
94
+ }
95
+ return { rules };
96
+ }
97
+ export function buildPageStructuredData(input) {
98
+ const authors = typeof input.author === 'string' ? [input.author] : input.author ?? [];
99
+ return {
100
+ '@context': 'https://schema.org',
101
+ '@type': input.type === 'post' ? 'BlogPosting' : 'WebPage',
102
+ name: input.title,
103
+ ...(input.type === 'post' ? { headline: input.title } : {}),
104
+ ...(input.description ? { description: input.description } : {}),
105
+ ...(input.url ? { url: input.url, '@id': input.url } : {}),
106
+ inLanguage: input.locale,
107
+ ...(input.date ? { datePublished: input.date } : {}),
108
+ ...(input.updated ? { dateModified: input.updated } : {}),
109
+ ...(authors.length ? { author: authors.map((name) => ({ '@type': 'Person', name })) } : {}),
110
+ isPartOf: {
111
+ '@type': 'WebSite',
112
+ name: input.siteTitle,
113
+ ...(input.siteUrl ? { url: `${input.siteUrl}/` } : {}),
114
+ },
115
+ };
116
+ }
@@ -1,5 +1,6 @@
1
1
  import type { ContentStore } from './content-store.js';
2
2
  import type { MdoPlugin } from './extensions.js';
3
+ import { type SiteRobots } from './seo.js';
3
4
  import { type SiteMessages } from '../i18n/messages.js';
4
5
  export interface SiteNavItem {
5
6
  label: string;
@@ -85,6 +86,11 @@ export interface SiteConfig {
85
86
  socialImage?: string;
86
87
  logo?: SiteLogo;
87
88
  showDate?: boolean;
89
+ /** Explicit crawler rules; an existing robots.txt always wins. */
90
+ robots?: SiteRobots;
91
+ /** Optional agent directory; an existing llms.txt always wins. */
92
+ llmsTxt?: boolean;
93
+ structuredData?: boolean;
88
94
  showSummary?: boolean;
89
95
  stylesheet?: string;
90
96
  topNav?: SiteNavItem[];
@@ -113,6 +119,9 @@ export interface ResolvedSiteConfig {
113
119
  socialImage?: string;
114
120
  logo?: SiteLogo;
115
121
  showDate: boolean;
122
+ robots?: SiteRobots;
123
+ llmsTxt?: boolean;
124
+ structuredData?: boolean;
116
125
  showSummary: boolean;
117
126
  topNav: SiteNavItem[];
118
127
  footerNav: SiteNavItem[];
@@ -4,6 +4,7 @@ import { pathToFileURL } from 'node:url';
4
4
  import { tsImport } from 'tsx/esm/api';
5
5
  import { getDirectoryIndexCandidates } from './directory-index.js';
6
6
  import { parseEntryDocumentMeta } from './markdown.js';
7
+ import { normalizeSiteRobots } from './seo.js';
7
8
  import { DEFAULT_SITE_LOCALE, validateSiteMessages, } from '../i18n/messages.js';
8
9
  export async function loadSiteConfig(options = {}) {
9
10
  return (await loadUserSiteConfig(options)).siteConfig;
@@ -41,6 +42,9 @@ export async function loadUserSiteConfig(options = {}) {
41
42
  siteUrl: normalizeSiteUrl(parsedConfig.siteUrl),
42
43
  favicon: normalizeSiteHref(parsedConfig.favicon),
43
44
  socialImage: normalizeSiteHref(parsedConfig.socialImage),
45
+ robots: normalizeSiteRobots(parsedConfig.robots),
46
+ llmsTxt: parsedConfig.llmsTxt === true,
47
+ structuredData: parsedConfig.structuredData === true,
44
48
  logo: normalizeLogo(parsedConfig.logo),
45
49
  showDate: parsedConfig.showDate ?? true,
46
50
  showSummary: parsedConfig.showSummary ?? true,
@@ -15,6 +15,9 @@ export interface RenderDocumentOptions {
15
15
  body: string;
16
16
  summary?: string;
17
17
  date?: string;
18
+ robots?: string;
19
+ discoveryPath?: string;
20
+ structuredData?: Record<string, unknown>;
18
21
  showSummary?: boolean;
19
22
  showDate?: boolean;
20
23
  topNav?: SiteNavItem[];
@@ -30,6 +33,8 @@ export interface RenderDocumentOptions {
30
33
  listingRequestPath?: string;
31
34
  listingInitialPostCount?: number;
32
35
  listingLoadMoreStep?: number;
36
+ listingPage?: number;
37
+ listingPageCount?: number;
33
38
  searchEnabled?: boolean;
34
39
  /** Language switcher entries; rendered in the header when more than one is present. */
35
40
  languages?: PageLanguage[];
@@ -9,8 +9,8 @@ export function renderDocument(options) {
9
9
  ? escapeHtml(options.siteDescription)
10
10
  : undefined;
11
11
  const socialDescription = options.summary ?? options.siteDescription;
12
- const summaryMeta = options.summary
13
- ? `<meta name="description" content="${escapeHtml(options.summary)}">`
12
+ const summaryMeta = socialDescription
13
+ ? `<meta name="description" content="${escapeHtml(socialDescription)}">`
14
14
  : '';
15
15
  const canonicalUrl = options.siteUrl && options.canonicalPath
16
16
  ? `${options.siteUrl}${options.canonicalPath}`
@@ -132,6 +132,8 @@ export function renderDocument(options) {
132
132
  requestPath: options.listingRequestPath ?? '/',
133
133
  initialPostCount: options.listingInitialPostCount ?? 10,
134
134
  loadMoreStep: options.listingLoadMoreStep ?? 10,
135
+ page: options.listingPage ?? 1,
136
+ pageCount: options.listingPageCount ?? 1,
135
137
  }, messages)
136
138
  : options.body;
137
139
  const searchScript = options.searchEnabled
@@ -149,6 +151,9 @@ export function renderDocument(options) {
149
151
  '<meta name="viewport" content="width=device-width, initial-scale=1">',
150
152
  `<title>${title} | ${siteTitle}</title>`,
151
153
  summaryMeta,
154
+ options.robots ? `<meta name="robots" content="${escapeHtml(options.robots)}">` : '',
155
+ options.discoveryPath ? `<link rel="describedby" type="text/plain" href="${escapeHtml(options.discoveryPath)}">` : '',
156
+ options.structuredData ? `<script type="application/ld+json">${JSON.stringify(options.structuredData).replaceAll('<', '\\u003c').replaceAll('\u2028', '\\u2028').replaceAll('\u2029', '\\u2029')}</script>` : '',
152
157
  canonicalMeta,
153
158
  faviconMeta,
154
159
  socialMeta,
@@ -215,8 +220,11 @@ function renderListingArticle(body, entries, options, messages) {
215
220
  const directories = entries.filter((entry) => entry.kind === 'directory');
216
221
  const articles = entries.filter((entry) => entry.kind === 'article');
217
222
  const initialPostCount = Math.max(1, options.initialPostCount);
218
- const visibleArticles = articles.slice(0, initialPostCount);
219
- const shouldLoadMore = articles.length > visibleArticles.length;
223
+ const offset = (options.page - 1) * initialPostCount;
224
+ const visibleArticles = articles.slice(offset, offset + initialPostCount);
225
+ const nextOffset = offset + visibleArticles.length;
226
+ const shouldLoadMore = articles.length > nextOffset;
227
+ const pageHref = (page) => escapeHtml(page === 1 ? options.requestPath : `${options.requestPath}?page=${page}`);
220
228
  return [
221
229
  `<div class="catalog-page__body">${body}</div>`,
222
230
  `<section class="catalog-page" aria-label="${escapeHtml(messages['listing.ariaLabel'])}">`,
@@ -224,12 +232,19 @@ function renderListingArticle(body, entries, options, messages) {
224
232
  articles.length > 0
225
233
  ? renderListingArticles(visibleArticles, {
226
234
  requestPath: options.requestPath,
227
- nextOffset: visibleArticles.length,
235
+ nextOffset,
228
236
  loadMoreStep: options.loadMoreStep,
229
237
  hasMore: shouldLoadMore,
230
238
  }, messages)
231
239
  : '',
232
240
  '</section>',
241
+ options.pageCount > 1 ? [
242
+ '<nav class="catalog-pagination">',
243
+ options.page > 1 ? `<a rel="prev" href="${pageHref(options.page - 1)}">${escapeHtml(messages['listing.previousPage'])}</a>` : '',
244
+ ' ',
245
+ options.page < options.pageCount ? `<a rel="next" href="${pageHref(options.page + 1)}">${escapeHtml(messages['listing.nextPage'])}</a>` : '',
246
+ '</nav>',
247
+ ].join('') : '',
233
248
  shouldLoadMore ? renderListingLoadMoreScript(messages) : '',
234
249
  ].join('');
235
250
  }
@@ -384,7 +399,7 @@ function renderSearchScript(messages, localeFilter) {
384
399
  ' return;',
385
400
  ' }',
386
401
  ' results.innerHTML = hits.map((hit) => {',
387
- ' const href = escapeHtmlForScript(hit.canonicalUrl || hit.docId || "#");',
402
+ ' const href = escapeHtmlForScript(hit.citationUrl || hit.canonicalUrl || hit.docId || "#");',
388
403
  ' const title = escapeHtmlForScript(hit.title || hit.relativePath || M.untitled);',
389
404
  ' const summary = typeof hit.summary === "string" ? `<span class="site-search__item-summary">${escapeHtmlForScript(hit.summary)}</span>` : "";',
390
405
  ' const excerpt = hit.bestMatch && typeof hit.bestMatch.excerpt === "string" ? `<span class="site-search__item-excerpt">${escapeHtmlForScript(hit.bestMatch.excerpt)}</span>` : "";',
@@ -20,6 +20,9 @@ export interface SiteMessages {
20
20
  'listing.loading': string;
21
21
  'listing.ariaLabel': string;
22
22
  'listing.emptyDirectory': string;
23
+ 'listing.pageLabel': string;
24
+ 'listing.previousPage': string;
25
+ 'listing.nextPage': string;
23
26
  'error.notFoundTitle': string;
24
27
  'error.notFoundBody': string;
25
28
  }
@@ -25,6 +25,9 @@ const enMessages = {
25
25
  'listing.loading': 'Loading...',
26
26
  'listing.ariaLabel': 'Content listing',
27
27
  'listing.emptyDirectory': 'This directory is empty.',
28
+ 'listing.pageLabel': 'Page {page}',
29
+ 'listing.previousPage': 'Previous page',
30
+ 'listing.nextPage': 'Next page',
28
31
  'error.notFoundTitle': 'Not Found',
29
32
  'error.notFoundBody': 'No page was published at <code>{path}</code>.',
30
33
  };
@@ -50,6 +53,9 @@ const zhCnMessages = {
50
53
  'listing.loading': '加载中...',
51
54
  'listing.ariaLabel': '内容列表',
52
55
  'listing.emptyDirectory': '此目录为空。',
56
+ 'listing.pageLabel': '第 {page} 页',
57
+ 'listing.previousPage': '上一页',
58
+ 'listing.nextPage': '下一页',
53
59
  'error.notFoundTitle': '未找到',
54
60
  'error.notFoundBody': '没有页面发布在 <code>{path}</code>。',
55
61
  };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export { defineConfig, type SiteConfig, type UserSiteConfig, type SiteNavItem, type SiteLogo, type SiteSocialLink, type EditLinkConfig, } from './core/site-config.js';
2
2
  export type { MdoPlugin, PageRenderModel, RenderHookContext, IndexTransformContext, } from './core/extensions.js';
3
3
  export type { ParsedDocumentMeta } from './core/markdown.js';
4
+ export type { PageRobots, SiteRobots, RobotsRule } from './core/seo.js';
package/dist/search.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { mkdir, readdir, readFile, realpath, stat, writeFile, } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { inferDirectoryContentType } from './core/content-type.js';
4
- import { getDirectoryIndexCandidates } from './core/directory-index.js';
5
- import { getDocumentSummary, getDocumentTitle, parseMarkdownDocument, stripMachineOnlyMarkdownComments, stripManagedIndexBlock, } from './core/markdown.js';
4
+ import { getDirectoryIndexCandidates, isCanonicalContentSource } from './core/directory-index.js';
5
+ import { getDocumentSummary, getDocumentTitle, parseMarkdownDocument, } from './core/markdown.js';
6
+ import { getSearchableMarkdownBody, getSearchContentRevision } from './core/search-citations.js';
6
7
  import { isIgnoredContentName } from './core/content-store.js';
7
8
  import { ensureTrailingSlash, trimLeadingSlash } from './core/site-url.js';
8
9
  const OVERVIEW_CONTENT_FILENAMES = new Set(['readme.md', 'index.md', 'skill.md']);
@@ -93,16 +94,20 @@ export function createSearchApiFromExternalBundle(bundleEntries, loadResponse, d
93
94
  async function collectSearchDocuments(rootDir, siteConfig, options) {
94
95
  const searchDocuments = await listSearchDocuments(rootDir);
95
96
  const documents = [];
97
+ const availablePaths = new Set(searchDocuments.map((document) => document.relativePath));
96
98
  for (const document of searchDocuments) {
99
+ if (!isCanonicalContentSource(document.relativePath, availablePaths))
100
+ continue;
97
101
  const markdown = await readFile(document.absolutePath, 'utf8');
98
102
  const parsed = await parseMarkdownDocument(document.relativePath, markdown);
99
- if (parsed.meta.draft === true && options.draftMode === 'exclude') {
103
+ if ((parsed.meta.draft === true && options.draftMode === 'exclude') || parsed.meta.search === false) {
100
104
  continue;
101
105
  }
102
106
  const canonicalPath = getCanonicalHtmlPathForContentPath(document.relativePath);
103
107
  const absoluteCanonicalUrl = siteConfig.siteUrl
104
108
  ? new URL(trimLeadingSlash(canonicalPath), ensureTrailingSlash(siteConfig.siteUrl)).toString()
105
109
  : canonicalPath;
110
+ const content = getSearchableMarkdownBody(parsed.body);
106
111
  documents.push({
107
112
  docId: canonicalPath,
108
113
  sourcePath: document.absolutePath,
@@ -110,15 +115,15 @@ async function collectSearchDocuments(rootDir, siteConfig, options) {
110
115
  canonicalUrl: absoluteCanonicalUrl,
111
116
  title: getDocumentTitle(parsed.meta, parsed.body, fallbackTitleFromRelativePath(document.relativePath)),
112
117
  summary: getDocumentSummary(parsed.meta, parsed.body),
113
- content: buildSearchableMarkdownBody(parsed.body),
114
- metadata: buildSearchMetadata(document.relativePath, canonicalPath, parsed.meta, siteConfig),
118
+ content,
119
+ metadata: {
120
+ ...buildSearchMetadata(document.relativePath, canonicalPath, parsed.meta, siteConfig),
121
+ contentRevision: await getSearchContentRevision(content),
122
+ },
115
123
  });
116
124
  }
117
125
  return documents;
118
126
  }
119
- function buildSearchableMarkdownBody(markdownBody) {
120
- return stripMachineOnlyMarkdownComments(stripManagedIndexBlock(markdownBody)).trim();
121
- }
122
127
  async function listSearchDocuments(rootDir) {
123
128
  const results = [];
124
129
  await walkDirectory(rootDir, '', new Set(), results);
@@ -241,6 +246,10 @@ function buildSearchMetadata(relativePath, canonicalPath, meta, siteConfig) {
241
246
  if (typeof meta.date === 'string') {
242
247
  metadata.date = meta.date;
243
248
  }
249
+ if (meta.updated)
250
+ metadata.updated = meta.updated;
251
+ if (meta.author)
252
+ metadata.author = meta.author;
244
253
  if (typeof meta.order === 'number') {
245
254
  metadata.order = meta.order;
246
255
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mdorigin",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
5
  "description": "Markdown-first publishing for humans and agents.",
6
6
  "repository": {
@@ -62,10 +62,11 @@
62
62
  "access": "public"
63
63
  },
64
64
  "engines": {
65
- "node": ">=20"
65
+ "node": ">=22.23.4 <23 || >=24.22.1 <25 || >=26.12.1 <27"
66
66
  },
67
67
  "dependencies": {
68
68
  "gray-matter": "^4.0.3",
69
+ "js-yaml": "^3.15.2",
69
70
  "rehype-raw": "^7.0.0",
70
71
  "rehype-stringify": "^10.0.1",
71
72
  "remark": "^15.0.1",
@@ -75,6 +76,7 @@
75
76
  },
76
77
  "devDependencies": {
77
78
  "@types/node": "^24.5.2",
79
+ "@types/js-yaml": "^3.12.10",
78
80
  "typescript": "^5.9.2"
79
81
  },
80
82
  "optionalDependencies": {