maisongr-sitemap 1.2.0 → 1.4.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
@@ -125,6 +125,7 @@ Astro, SvelteKit and Nuxt routes call `createSitemap` from `maisongr-sitemap` wi
125
125
  | `revalidate` | Seconds the list is kept before `params` and `entries` run again. Default 3600. A failed load is not kept. To list new content at once, call the handler's `invalidate()` when it is published. |
126
126
  | `theme` | Override any detected colour, font, name or icon. |
127
127
  | `credit` | The "Sitemap by Maison GR" footer line. Default `true`. |
128
+ | `lang` | The language of the page people see: `"en"` or `"fr"`. Default the site's own default language, so a French-first site gets « Plan du site ». Any other language gets English. Static mode and `crawl` take the home page's `<html lang>`, or `--lang`. |
128
129
 
129
130
  A `lastmod` can be a `YYYY-MM-DD` string, an ISO timestamp, a `Date` or milliseconds. One that isn't a real date is left out, because an invalid date makes Search Console reject the whole file.
130
131
 
@@ -305,8 +306,22 @@ Run it again whenever content changes, after a deploy or from a daily cron, so t
305
306
 
306
307
  ## Telling search engines
307
308
 
308
- - **robots.txt.** Crawlers find a sitemap through a `Sitemap:` line in `robots.txt`. `init` tells you when the line is missing, without editing the file.
309
- - **Search Console and Bing Webmaster Tools.** Submit `https://your.site/sitemap.xml` once in each.
309
+ - **`connect`** sets up the rest, in the folder your site serves:
310
+
311
+ ```sh
312
+ npx maisongr-sitemap connect --site https://www.example.com --google google1234abcd5678ef90.html --bing <code> --indexnow
313
+ ```
314
+
315
+ - **robots.txt:** creates it, or adds the `Sitemap:` line it lacks, after asking. `--yes` answers for you (in CI, without it, nothing is written). A robots.txt your code writes (`app/robots.ts`) or that names another sitemap is left alone, with what to change.
316
+ - **Verification files:** `--google` writes the HTML file Google Search Console gives you, `--bing` the `BingSiteAuth.xml` Bing Webmaster Tools gives you, `--indexnow` an IndexNow key file (with a new key if you give none). A file already there with other content is never replaced.
317
+ - **Search Console and Bing Webmaster Tools.** Submit `https://your.site/sitemap.xml` once in each, choosing the HTML file method to verify.
318
+ - **llms.txt**, the short Markdown file AI assistants read ([llmstxt.org](https://llmstxt.org)):
319
+
320
+ ```sh
321
+ npx maisongr-sitemap llms --site https://www.example.com --from http://localhost:3000
322
+ ```
323
+
324
+ It reads the sitemap, keeps one version of each page (the one its `x-default` names), and lists each with the title and meta description the page itself gives, by section, under what the home page says the site is. So it says only what your site says. `--from` reads a running or staging copy; without it, the live site. `--stdout` prints it, `--max` caps the pages (default 200). An `llms.txt` you wrote by hand is never replaced. Run it again when content changes.
310
325
  - **IndexNow.** Bing, Yandex, Seznam, Naver and the other participating engines take a list of changed addresses directly. After a deploy:
311
326
 
312
327
  ```sh
@@ -0,0 +1,29 @@
1
+ /**
2
+ * What `connect` writes so search engines find the sitemap and trust the
3
+ * site: the Sitemap line in robots.txt, and the files Google, Bing and
4
+ * IndexNow fetch to check the site is yours. Pure: the CLI decides where,
5
+ * and asks before it changes anything.
6
+ */
7
+ /** robots.txt with the sitemap named: a new one, or the existing one with the line added at its end. */
8
+ export declare function robotsWithSitemap(current: string | null, site: string): {
9
+ text: string;
10
+ change: "created" | "added" | "none";
11
+ };
12
+ /** The sitemap robots.txt already names, when it names another address than this one. */
13
+ export declare function otherSitemap(current: string, site: string): string | undefined;
14
+ /** Google's HTML file: google1234abcd.html, holding its own name. Accepts the token, the file name, or the meta tag's content. */
15
+ export declare function googleFile(token: string): {
16
+ name: string;
17
+ body: string;
18
+ } | null;
19
+ /** Bing's BingSiteAuth.xml, holding the code from Bing Webmaster Tools. */
20
+ export declare function bingFile(token: string): {
21
+ name: string;
22
+ body: string;
23
+ } | null;
24
+ /** The IndexNow key file: <key>.txt, holding the key. A new key is 32 hex characters, as Bing makes them. */
25
+ export declare function indexNowFile(key?: string): {
26
+ name: string;
27
+ body: string;
28
+ key: string;
29
+ } | null;
@@ -0,0 +1,43 @@
1
+ import { randomBytes } from "node:crypto";
2
+ /**
3
+ * What `connect` writes so search engines find the sitemap and trust the
4
+ * site: the Sitemap line in robots.txt, and the files Google, Bing and
5
+ * IndexNow fetch to check the site is yours. Pure: the CLI decides where,
6
+ * and asks before it changes anything.
7
+ */
8
+ /** robots.txt with the sitemap named: a new one, or the existing one with the line added at its end. */
9
+ export function robotsWithSitemap(current, site) {
10
+ const line = `Sitemap: ${site}/sitemap.xml`;
11
+ if (current === null)
12
+ return { text: `User-agent: *\nAllow: /\n\n${line}\n`, change: "created" };
13
+ if (/^\s*sitemap\s*:/im.test(current))
14
+ return { text: current, change: "none" };
15
+ const eol = current.includes("\r\n") ? "\r\n" : "\n";
16
+ const body = current.replace(/\s+$/, "");
17
+ return { text: `${body}${body ? `${eol}${eol}` : ""}${line}${eol}`, change: "added" };
18
+ }
19
+ /** The sitemap robots.txt already names, when it names another address than this one. */
20
+ export function otherSitemap(current, site) {
21
+ const named = [...current.matchAll(/^\s*sitemap\s*:\s*(\S+)/gim)].map((m) => m[1]);
22
+ return named.length && !named.includes(`${site}/sitemap.xml`) ? named[0] : undefined;
23
+ }
24
+ /** Google's HTML file: google1234abcd.html, holding its own name. Accepts the token, the file name, or the meta tag's content. */
25
+ export function googleFile(token) {
26
+ const id = token.trim().replace(/^google-site-verification:\s*/i, "").replace(/\.html$/i, "");
27
+ if (!/^google[0-9a-f]{8,32}$/i.test(id))
28
+ return null;
29
+ return { name: `${id}.html`, body: `google-site-verification: ${id}.html` };
30
+ }
31
+ /** Bing's BingSiteAuth.xml, holding the code from Bing Webmaster Tools. */
32
+ export function bingFile(token) {
33
+ const code = token.trim();
34
+ if (!/^[0-9A-F]{32}$/i.test(code))
35
+ return null;
36
+ return { name: "BingSiteAuth.xml", body: `<?xml version="1.0"?>\n<users>\n\t<user>${code.toUpperCase()}</user>\n</users>\n` };
37
+ }
38
+ /** The IndexNow key file: <key>.txt, holding the key. A new key is 32 hex characters, as Bing makes them. */
39
+ export function indexNowFile(key = randomBytes(16).toString("hex")) {
40
+ if (!/^[a-zA-Z0-9-]{8,128}$/.test(key))
41
+ return null;
42
+ return { name: `${key}.txt`, body: key, key };
43
+ }
@@ -26,6 +26,7 @@ export type CrawlReport = {
26
26
  theme: Theme;
27
27
  capped: boolean;
28
28
  queries: number;
29
+ lang?: string;
29
30
  };
30
31
  /** robots.txt's rules for every crawler (User-agent: *), longest match wins, Allow over Disallow on a tie. */
31
32
  export declare function robotsRules(text: string): (path: string) => boolean;
@@ -1,7 +1,7 @@
1
1
  import { trimSlashes } from "../entries.js";
2
2
  import { styleBlocks } from "./project.js";
3
3
  import { privateOf } from "./route-rules.js";
4
- import { attr, holds, pageFacts, themeOf } from "./static.js";
4
+ import { attr, holds, htmlLang, pageFacts, themeOf } from "./static.js";
5
5
  const NOT_PAGES = /\.(?:pdf|jpe?g|png|gif|webp|avif|svg|ico|bmp|css|js|mjs|json|xml|txt|csv|zip|gz|rar|7z|mp4|webm|mov|mp3|wav|ogg|woff2?|ttf|otf|eot|map|docx?|xlsx?|pptx?)$/i;
6
6
  const AGENT = "maisongr-sitemap (+https://github.com/maison-gr/sitemap)";
7
7
  const tags = (html, name) => [...html.matchAll(new RegExp(`<${name}\\b[^>]*>`, "gi"))].map((m) => m[0]);
@@ -206,5 +206,5 @@ export async function crawl(start, options = {}) {
206
206
  const icon = iconUrl && iconUrl.origin === origin ? iconUrl.pathname : undefined;
207
207
  entries.sort((a, b) => a.loc.localeCompare(b.loc));
208
208
  skipped.sort((a, b) => a.path.localeCompare(b.path));
209
- return { entries, skipped, theme: themeOf({ css: css.join("\n"), pages, home, icon, base }), capped, queries: queries.size };
209
+ return { entries, skipped, theme: themeOf({ css: css.join("\n"), pages, home, icon, base }), capped, queries: queries.size, lang: htmlLang(home) };
210
210
  }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * llms.txt (llmstxt.org): a short Markdown file that says what the site is and
3
+ * links its key pages, for AI assistants. Written from the sitemap and the
4
+ * pages' own titles and descriptions, so it says only what the site says, and
5
+ * a run after each content change keeps it current.
6
+ */
7
+ export declare const LLMS_MARK = "<!-- Written by maisongr-sitemap llms from the sitemap and each page's own title and description. Run it again to update. -->";
8
+ /**
9
+ * The addresses of a urlset, one version per page: where a page lists
10
+ * x-default, only that version is kept, so a site in ten languages is listed
11
+ * once, in the language its x-default names.
12
+ */
13
+ export declare function onePerPage(xml: string): string[];
14
+ export type PageInfo = {
15
+ url: string;
16
+ title: string;
17
+ description?: string;
18
+ };
19
+ /** A page's title (without the site name after its separator) and meta description. */
20
+ export declare function pageInfo(html: string, url: string, siteName?: string): PageInfo;
21
+ /** The file itself: the site's name, what its home page says it is, and its pages by section. */
22
+ export declare function llmsText(site: {
23
+ name: string;
24
+ description?: string;
25
+ pages: PageInfo[];
26
+ }): string;
@@ -0,0 +1,68 @@
1
+ import { attr } from "./static.js";
2
+ /**
3
+ * llms.txt (llmstxt.org): a short Markdown file that says what the site is and
4
+ * links its key pages, for AI assistants. Written from the sitemap and the
5
+ * pages' own titles and descriptions, so it says only what the site says, and
6
+ * a run after each content change keeps it current.
7
+ */
8
+ export const LLMS_MARK = "<!-- Written by maisongr-sitemap llms from the sitemap and each page's own title and description. Run it again to update. -->";
9
+ const NAMED = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
10
+ /** HTML's entities as text: &amp;, &#39; and &#x27; alike. */
11
+ const unescape = (s) => s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (whole, code) => code[0] === "#" ? String.fromCodePoint(code[1].toLowerCase() === "x" ? parseInt(code.slice(2), 16) : Number(code.slice(1))) : (NAMED[code.toLowerCase()] ?? whole));
12
+ /**
13
+ * The addresses of a urlset, one version per page: where a page lists
14
+ * x-default, only that version is kept, so a site in ten languages is listed
15
+ * once, in the language its x-default names.
16
+ */
17
+ export function onePerPage(xml) {
18
+ const out = [];
19
+ for (const m of xml.matchAll(/<url>([\s\S]*?)<\/url>/g)) {
20
+ const loc = m[1].match(/<loc>([^<]+)<\/loc>/)?.[1];
21
+ if (!loc)
22
+ continue;
23
+ const xDefault = m[1].match(/hreflang="x-default"\s+href="([^"]+)"/)?.[1];
24
+ const url = unescape(loc.trim());
25
+ if (!xDefault || unescape(xDefault) === url)
26
+ out.push(url);
27
+ }
28
+ return [...new Set(out)];
29
+ }
30
+ /** A page's title (without the site name after its separator) and meta description. */
31
+ export function pageInfo(html, url, siteName) {
32
+ const raw = unescape(html.match(/<title[^>]*>([^<]*)<\/title>/i)?.[1]?.trim() ?? "");
33
+ // The site's name, before or after the page's own ("Maison GR — Services", "Services | Maison GR"), says nothing here.
34
+ const parts = raw.split(/\s+[|·—–-]\s+/);
35
+ const own = parts.length > 1 && siteName ? parts.filter((p, i) => !(p === siteName && (i === 0 || i === parts.length - 1))) : parts;
36
+ const title = own.join(" · ") || raw || new URL(url).pathname;
37
+ const meta = [...html.matchAll(/<meta\b[^>]*>/gi)].map((t) => t[0]).find((t) => attr(t, "name")?.toLowerCase() === "description");
38
+ const description = meta ? unescape(attr(meta, "content") ?? "").trim() : "";
39
+ return { url, title, ...(description ? { description } : {}) };
40
+ }
41
+ /** Groups pages by their first path segment, the home page's section first. */
42
+ function sections(pages) {
43
+ const by = new Map();
44
+ for (const p of pages) {
45
+ const parts = new URL(p.url).pathname.split("/").filter(Boolean);
46
+ // A language prefix (/fr, /en-CA) is not a section.
47
+ if (parts[0] && /^[a-z]{2}(-[A-Za-z]{2,4})?$/.test(parts[0]))
48
+ parts.shift();
49
+ const key = parts.length > 1 ? parts[0] : "";
50
+ by.set(key, [...(by.get(key) ?? []), p]);
51
+ }
52
+ return [...by].sort(([a], [b]) => (a === "" ? -1 : b === "" ? 1 : a.localeCompare(b)));
53
+ }
54
+ const title = (key) => (key ? decodeURIComponent(key).replace(/[-_]+/g, " ").replace(/^./, (c) => c.toUpperCase()) : "Pages");
55
+ /** The file itself: the site's name, what its home page says it is, and its pages by section. */
56
+ export function llmsText(site) {
57
+ const lines = [`# ${site.name}`, ""];
58
+ if (site.description)
59
+ lines.push(`> ${site.description.replace(/\s+/g, " ")}`, "");
60
+ for (const [key, pages] of sections(site.pages)) {
61
+ lines.push(`## ${title(key)}`, "");
62
+ for (const p of pages)
63
+ lines.push(`- [${p.title.replace(/[[\]]/g, "")}](${p.url})${p.description ? `: ${p.description.replace(/\s+/g, " ")}` : ""}`);
64
+ lines.push("");
65
+ }
66
+ lines.push(LLMS_MARK, "");
67
+ return lines.join("\n");
68
+ }
@@ -67,17 +67,24 @@ export function emptyPageReason(file) {
67
67
  return "not-found page";
68
68
  return null;
69
69
  }
70
+ /**
71
+ * Whether a file always says noindex. One that also says index: true chooses
72
+ * per page (shouldIndex ? { index: true } : { index: false }), so its pages
73
+ * are listed, and the page decides for each one.
74
+ */
75
+ const INDEXABLE = /index\s*:\s*true/;
76
+ const saysNoindex = (src) => NOINDEX.test(src) && !INDEXABLE.test(src);
70
77
  /** A page or layout is noindex when it says so, or calls a local helper named for hiding that does. */
71
78
  export function isNoindex(root, file) {
72
79
  const src = read(file);
73
- if (NOINDEX.test(src))
80
+ if (saysNoindex(src))
74
81
  return true;
75
82
  for (const m of src.matchAll(/import\s*\{([^}]+)\}\s*from\s*["']([^"']+)["']/g)) {
76
83
  const names = m[1].split(",").map((n) => n.trim().split(/\s+as\s+/)[0]);
77
84
  if (!names.some((n) => HIDING_HELPER.test(n)))
78
85
  continue;
79
86
  const target = moduleFile(root, file, m[2]);
80
- if (target && NOINDEX.test(read(target)))
87
+ if (target && saysNoindex(read(target)))
81
88
  return true;
82
89
  }
83
90
  return false;
@@ -1,20 +1,39 @@
1
1
  /** Client-side routers whose route tables live in code, which a single-page app's build output never shows. */
2
2
  export declare const CLIENT_ROUTERS: string[];
3
3
  export declare function clientRouter(root: string): string | undefined;
4
+ /** A route as its file declares it: its full path, and what it renders when that can be read. */
5
+ export type DeclaredRoute = {
6
+ path: string;
7
+ /** The component it renders (<Services />, Component: Services), to find the file it comes from. */
8
+ element?: string;
9
+ /** A file it loads itself (lazy: () => import("./x"), component: () => import("./x.vue")). */
10
+ importPath?: string;
11
+ /** It only sends the visitor elsewhere (<Navigate>, redirect:). */
12
+ redirect?: boolean;
13
+ };
4
14
  /**
5
- * Every route path a file declares, joined to the paths of the routes it is
6
- * nested in: `{ path: "docs", children: [{ path: "setup" }] }` and
15
+ * Every route a file declares, joined to the paths of the routes it is nested
16
+ * in: `{ path: "docs", children: [{ path: "setup" }] }` and
7
17
  * `<Route path="docs"><Route path="setup" /></Route>` both give /docs/setup.
8
18
  * One pass that skips strings and comments, so it runs in linear time.
9
19
  */
10
- export declare function routePaths(source: string): string[];
20
+ export declare function routesIn(source: string): DeclaredRoute[];
21
+ /** Every route path a file declares (see routesIn). */
22
+ export declare const routePaths: (source: string) => string[];
11
23
  export type SpaRoutes = {
12
24
  router: string;
13
- paths: string[];
25
+ paths: {
26
+ path: string;
27
+ lastmod?: string;
28
+ }[];
14
29
  skipped: {
15
30
  path: string;
16
31
  reason: string;
17
32
  }[];
18
33
  };
19
- /** The public pages a single-page app's router declares, from the files that import it. */
34
+ /**
35
+ * The public pages a single-page app's router declares, from the files that
36
+ * import it. Each is dated from Git by the file of the component it renders,
37
+ * when that can be found: the page changes when that file does.
38
+ */
20
39
  export declare function spaRoutes(root: string): SpaRoutes | null;
@@ -1,6 +1,9 @@
1
+ import { existsSync, statSync } from "node:fs";
2
+ import { dirname, join as joinFile, relative } from "node:path";
1
3
  import { readPackage } from "./detect.js";
4
+ import { gitDates } from "./git-dates.js";
2
5
  import { sourceFiles } from "./project.js";
3
- import { privateOf, read } from "./route-rules.js";
6
+ import { privateOf, read, toPosix } from "./route-rules.js";
4
7
  /** Client-side routers whose route tables live in code, which a single-page app's build output never shows. */
5
8
  export const CLIENT_ROUTERS = ["react-router", "react-router-dom", "vue-router", "@tanstack/react-router", "@tanstack/vue-router", "@tanstack/solid-router", "@solidjs/router", "wouter", "preact-router", "svelte-spa-router"];
6
9
  export function clientRouter(root) {
@@ -9,16 +12,29 @@ export function clientRouter(root) {
9
12
  return CLIENT_ROUTERS.find((r) => deps[r]);
10
13
  }
11
14
  const join = (parent, path) => (path.startsWith("/") ? path : `${parent.replace(/\/$/, "")}/${path}`).replace(/\/{2,}/g, "/");
15
+ /** What a route renders, from its own tag or object, before any nested children. */
16
+ function renderedBy(own) {
17
+ const head = own.split(/\bchildren\s*[:=]/)[0];
18
+ const element = head.match(/\belement\s*[=:]\s*\{?\s*<\s*([A-Z][\w.]*)/)?.[1] ?? head.match(/\b[Cc]omponent\s*[:=]\s*\{?\s*([A-Z][\w$]*)/)?.[1];
19
+ const importPath = head.match(/\b(?:lazy|component|Component)\s*:\s*(?:async\s*)?\(\s*\)\s*=>\s*import\(\s*["'`]([^"'`]+)/)?.[1];
20
+ const redirect = element === "Navigate" || element === "Redirect" || /\bredirect\s*:/.test(head);
21
+ return { ...(element && !redirect ? { element } : {}), ...(importPath ? { importPath } : {}), ...(redirect ? { redirect } : {}) };
22
+ }
12
23
  /**
13
- * Every route path a file declares, joined to the paths of the routes it is
14
- * nested in: `{ path: "docs", children: [{ path: "setup" }] }` and
24
+ * Every route a file declares, joined to the paths of the routes it is nested
25
+ * in: `{ path: "docs", children: [{ path: "setup" }] }` and
15
26
  * `<Route path="docs"><Route path="setup" /></Route>` both give /docs/setup.
16
27
  * One pass that skips strings and comments, so it runs in linear time.
17
28
  */
18
- export function routePaths(source) {
29
+ export function routesIn(source) {
19
30
  const stack = [];
20
31
  const found = [];
21
32
  const pathOfStack = () => stack.reduce((p, f) => (f.path === undefined ? p : join(p, f.path)), "/");
33
+ /** A frame ends: what its route renders is read from the frame's own text. */
34
+ const close = (frame, end) => {
35
+ if (frame?.route)
36
+ Object.assign(frame.route, renderedBy(source.slice(frame.start, end)));
37
+ };
22
38
  let i = 0;
23
39
  const n = source.length;
24
40
  const readString = () => {
@@ -64,7 +80,8 @@ export function routePaths(source) {
64
80
  const top = stack[stack.length - 1];
65
81
  if (top && top.path === undefined && !value.includes("${")) {
66
82
  top.path = value;
67
- found.push(pathOfStack());
83
+ top.route = { path: pathOfStack() };
84
+ found.push(top.route);
68
85
  }
69
86
  continue;
70
87
  }
@@ -73,7 +90,7 @@ export function routePaths(source) {
73
90
  continue;
74
91
  }
75
92
  if (c === "<" && source.startsWith("<Route", i) && !/[\w$]/.test(source[i + 6] ?? "")) {
76
- stack.push({ kind: "route", inTag: true });
93
+ stack.push({ kind: "route", start: i, inTag: true });
77
94
  i += 6;
78
95
  continue;
79
96
  }
@@ -85,6 +102,7 @@ export function routePaths(source) {
85
102
  }
86
103
  const top = stack[stack.length - 1];
87
104
  if (c === ">" && top?.kind === "route" && top.inTag && source[i - 1] !== "=") {
105
+ close(top, i);
88
106
  if (source[i - 1] === "/")
89
107
  stack.pop();
90
108
  else
@@ -93,43 +111,93 @@ export function routePaths(source) {
93
111
  continue;
94
112
  }
95
113
  if (c === "{")
96
- stack.push({ kind: "brace" });
114
+ stack.push({ kind: "brace", start: i });
97
115
  else if (c === "}") {
98
- while (stack.length && stack.pop().kind !== "brace")
99
- ;
116
+ while (stack.length) {
117
+ const frame = stack.pop();
118
+ if (frame.kind === "brace") {
119
+ close(frame, i);
120
+ break;
121
+ }
122
+ }
100
123
  }
101
124
  i++;
102
125
  }
103
126
  return found;
104
127
  }
105
- /** The public pages a single-page app's router declares, from the files that import it. */
128
+ /** Every route path a file declares (see routesIn). */
129
+ export const routePaths = (source) => routesIn(source).map((r) => r.path);
130
+ /** The src/ folder a file sits in, where "@/" points. */
131
+ function srcOf(file) {
132
+ const at = file.replace(/\\/g, "/").lastIndexOf("/src/");
133
+ return at < 0 ? dirname(file) : file.slice(0, at + 4);
134
+ }
135
+ /** The file an import names, relative to the file that imports it, or through "@/" or "~/". */
136
+ function resolveImport(from, spec) {
137
+ const local = spec.startsWith(".");
138
+ if (!local && !spec.startsWith("@/") && !spec.startsWith("~/"))
139
+ return undefined;
140
+ const base = local ? joinFile(dirname(from), spec) : joinFile(srcOf(from), spec.slice(2));
141
+ for (const ext of ["", ".tsx", ".ts", ".jsx", ".js", ".vue", ".svelte", "/index.tsx", "/index.ts", "/index.jsx", "/index.js"]) {
142
+ const file = base + ext;
143
+ if (existsSync(file) && statSync(file).isFile())
144
+ return file;
145
+ }
146
+ return undefined;
147
+ }
148
+ /** The file a component comes from: import X from "…", import { X } from "…", or X = lazy(() => import("…")). */
149
+ function componentFile(file, source, name) {
150
+ // Every character that means something in a pattern escaped, whatever the name holds.
151
+ const id = name.split(".")[0].replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
152
+ const spec = source.match(new RegExp(`import\\s+${id}\\s+from\\s*["'\`]([^"'\`]+)`))?.[1] ??
153
+ source.match(new RegExp(`import\\s*\\{[^}]*\\b${id}\\b[^}]*\\}\\s*from\\s*["'\`]([^"'\`]+)`))?.[1] ??
154
+ source.match(new RegExp(`\\b${id}\\s*=\\s*(?:React\\.)?lazy\\(\\s*\\(\\s*\\)\\s*=>\\s*import\\(\\s*["'\`]([^"'\`]+)`))?.[1];
155
+ return spec ? resolveImport(file, spec) : undefined;
156
+ }
157
+ /**
158
+ * The public pages a single-page app's router declares, from the files that
159
+ * import it. Each is dated from Git by the file of the component it renders,
160
+ * when that can be found: the page changes when that file does.
161
+ */
106
162
  export function spaRoutes(root) {
107
163
  const router = clientRouter(root);
108
164
  if (!router)
109
165
  return null;
110
166
  const files = sourceFiles(root).filter((f) => /\.(?:[cm]?[jt]sx?|vue|svelte)$/.test(f) && !/[\\/](?:test|tests|__tests__)[\\/]/.test(f) && !/\.(?:test|spec)\./.test(f));
111
- const paths = new Set();
167
+ const pages = new Map();
112
168
  const skipped = [];
113
169
  for (const file of files) {
114
170
  const source = read(file);
115
171
  if (!CLIENT_ROUTERS.some((r) => source.includes(`"${r}"`) || source.includes(`'${r}'`)))
116
172
  continue;
117
- for (const raw of routePaths(source)) {
118
- const path = raw === "/" ? "/" : raw.replace(/\/$/, "");
119
- if (paths.has(path) || skipped.some((s) => s.path === path))
173
+ for (const route of routesIn(source)) {
174
+ const path = route.path === "/" ? "/" : route.path.replace(/\/$/, "");
175
+ if (pages.has(path) || skipped.some((s) => s.path === path))
120
176
  continue;
121
177
  const segments = path.split("/").filter(Boolean);
178
+ const last = segments[segments.length - 1] ?? "";
122
179
  const dynamic = segments.find((s) => /^[:$]|[*[(]/.test(s));
123
180
  const privateSegment = privateOf(segments);
124
- if (dynamic)
181
+ // "*" (React Router), "/:pathMatch(.*)*" (Vue Router): the page for addresses that exist nowhere.
182
+ if (last === "*" || last === "**" || /^:\w*\(\.\*\)\*?$/.test(last))
183
+ skipped.push({ path, reason: "not-found page" });
184
+ else if (route.redirect)
185
+ skipped.push({ path, reason: "redirect" });
186
+ else if (dynamic)
125
187
  skipped.push({ path, reason: "dynamic: list its pages with --add" });
126
188
  else if (privateSegment)
127
189
  skipped.push({ path, reason: `private page (${privateSegment})` });
128
190
  else if (segments[0] === "api")
129
191
  skipped.push({ path, reason: "API" });
130
192
  else
131
- paths.add(path);
193
+ pages.set(path, (route.importPath && resolveImport(file, route.importPath)) || (route.element && componentFile(file, source, route.element)) || undefined);
132
194
  }
133
195
  }
134
- return { router, paths: [...paths].sort(), skipped };
196
+ const rel = (f) => toPosix(relative(root, f));
197
+ const dated = gitDates(root, [...new Set([...pages.values()].filter((f) => !!f))].map(rel));
198
+ const paths = [...pages].map(([path, file]) => {
199
+ const lastmod = file ? dated.get(rel(file)) : undefined;
200
+ return { path, ...(lastmod ? { lastmod } : {}) };
201
+ });
202
+ return { router, paths: paths.sort((a, b) => a.path.localeCompare(b.path)), skipped };
135
203
  }
@@ -22,10 +22,15 @@ export type StaticOptions = {
22
22
  name?: string;
23
23
  credit?: boolean;
24
24
  images?: boolean;
25
- /** Addresses no HTML file holds: a single-page app's routes, and any given with --add. */
26
- extra?: string[];
25
+ /** Addresses no HTML file holds: a single-page app's routes (dated by their component's file), and any given with --add. */
26
+ extra?: (string | {
27
+ path: string;
28
+ lastmod?: string;
29
+ })[];
27
30
  /** Force /about over /about.html, whatever the site's links do. */
28
31
  cleanUrls?: boolean;
32
+ /** The page's language. Default the one the home page declares in <html lang>. */
33
+ lang?: string;
29
34
  };
30
35
  export declare function buildStatic(dir: string, site: string, options?: StaticOptions): StaticReport;
31
36
  /** What one page says about itself: why it is left out, or its entry (language, alternates, images). */
@@ -44,4 +49,9 @@ export declare function themeOf(site: {
44
49
  base: string;
45
50
  }): Theme;
46
51
  /** sitemap.xml (styled by sitemap.css) for crawlers, and the designed page at /sitemap/ for people. */
47
- export declare function writeSitemapFiles(dir: string, entries: Entry[], theme: Theme, credit?: boolean): string[];
52
+ /** The language a page declares: <html lang="fr-CA">. */
53
+ export declare const htmlLang: (html: string) => string | undefined;
54
+ export declare function writeSitemapFiles(dir: string, entries: Entry[], theme: Theme, page?: {
55
+ credit?: boolean;
56
+ lang?: string;
57
+ }): string[];
@@ -140,11 +140,18 @@ export function buildStatic(dir, site, options = {}) {
140
140
  const lastmod = dates.get(relative(dir, file).split(sep).join("/"));
141
141
  entries.push({ ...facts.entry, ...(lastmod ? { lastmod } : {}) });
142
142
  }
143
- for (const raw of options.extra ?? []) {
143
+ for (const item of options.extra ?? []) {
144
+ const { path: raw, lastmod } = typeof item === "string" ? { path: item, lastmod: undefined } : item;
144
145
  const path = raw.startsWith("/") ? raw : `/${raw}`;
145
146
  const loc = `${base}${path}`;
146
- if (!entries.some((e) => e.loc === loc || e.loc === `${loc}/`))
147
- entries.push({ loc });
147
+ const known = entries.find((e) => e.loc === loc || e.loc === `${loc}/`);
148
+ // A prerendered page in the build output has no Git date; the route's component file has one.
149
+ if (known) {
150
+ if (!known.lastmod && lastmod)
151
+ known.lastmod = lastmod;
152
+ }
153
+ else
154
+ entries.push({ loc, ...(lastmod ? { lastmod } : {}) });
148
155
  }
149
156
  entries.sort((a, b) => a.loc.localeCompare(b.loc));
150
157
  const home = files.find((f) => relative(dir, f) === "index.html");
@@ -156,7 +163,7 @@ export function buildStatic(dir, site, options = {}) {
156
163
  ].join("\n");
157
164
  const icon = ["favicon.svg", "icon.svg", "favicon.png", "favicon.ico"].find((n) => files.some((f) => relative(dir, f) === n));
158
165
  const theme = themeOf({ css, pages: [...sources.values()], home: homeHtml, icon: icon && `/${icon}`, name: options.name, base });
159
- return { pages: entries.length, skipped, written: writeSitemapFiles(dir, entries, theme, options.credit), theme };
166
+ return { pages: entries.length, skipped, written: writeSitemapFiles(dir, entries, theme, { credit: options.credit, lang: options.lang ?? htmlLang(homeHtml) }), theme };
160
167
  }
161
168
  /** What one page says about itself: why it is left out, or its entry (language, alternates, images). */
162
169
  export function pageFacts(html, loc, base, withImages = false) {
@@ -186,12 +193,14 @@ export function themeOf(site) {
186
193
  };
187
194
  }
188
195
  /** sitemap.xml (styled by sitemap.css) for crawlers, and the designed page at /sitemap/ for people. */
189
- export function writeSitemapFiles(dir, entries, theme, credit) {
196
+ /** The language a page declares: <html lang="fr-CA">. */
197
+ export const htmlLang = (html) => attr(html.match(/<html\b[^>]*>/i)?.[0] ?? "", "lang");
198
+ export function writeSitemapFiles(dir, entries, theme, page = {}) {
190
199
  mkdirSync(join(dir, "sitemap"), { recursive: true });
191
200
  const written = [
192
201
  ["sitemap.xml", urlsetXml(entries, "/sitemap.css")],
193
202
  ["sitemap.css", xmlCss(theme)],
194
- ["sitemap/index.html", urlsetPage(entries, theme, { credit, assets: { css: "/sitemap/page.css", js: "/sitemap/page.js" } })],
203
+ ["sitemap/index.html", urlsetPage(entries, theme, { ...page, assets: { css: "/sitemap/page.css", js: "/sitemap/page.js" } })],
195
204
  ["sitemap/page.css", pageCss(theme)],
196
205
  ["sitemap/page.js", PAGE_JS],
197
206
  ];
@@ -4,6 +4,8 @@ export type Io = {
4
4
  err: (s: string) => void;
5
5
  style?: Style;
6
6
  errStyle?: Style;
7
+ /** A yes/no question to the person at the terminal. Without one (CI, a pipe), every answer is no. */
8
+ ask?: (question: string) => Promise<boolean>;
7
9
  };
8
10
  /** Runs one command in `cwd` and returns the exit code. */
9
11
  export declare function main(argv: string[], cwd: string, streams?: Io): Promise<number>;
package/dist/cli/main.js CHANGED
@@ -3,12 +3,14 @@ import { dirname, join, relative } from "node:path";
3
3
  import { detect, readPackage } from "../build/detect.js";
4
4
  import { buildFramework, configuredSite } from "../build/framework-build.js";
5
5
  import { buildNext, usesCacheComponents } from "../build/next-build.js";
6
- import { buildNode, nodePaths } from "../build/node-build.js";
6
+ import { bingFile, googleFile, indexNowFile, otherSitemap, robotsWithSitemap } from "../build/connect.js";
7
+ import { LLMS_MARK, llmsText, onePerPage, pageInfo } from "../build/llms.js";
8
+ import { buildNode, clientOf, nodePaths, servedDirs } from "../build/node-build.js";
7
9
  import { findSite, sourceFiles } from "../build/project.js";
8
10
  import { COMMAND, withBuildStep, withStaticStep } from "../build/scripts.js";
9
11
  import { spaRoutes } from "../build/spa-routes.js";
10
12
  import { crawl } from "../build/crawl.js";
11
- import { buildStatic, writeSitemapFiles } from "../build/static.js";
13
+ import { buildStatic, siteNameOf, writeSitemapFiles } from "../build/static.js";
12
14
  import { trimSlashes } from "../entries.js";
13
15
  import { changedSince, readSitemap, submit, validKey } from "../indexnow.js";
14
16
  import { existingRoutes, LABEL, nodeModuleSource, RIVALS, routePath, routeSource, STATIC_OUT } from "./routes.js";
@@ -28,7 +30,11 @@ const HELP = `
28
30
  maisongr-sitemap crawl <url> --out <dir> [--site <url>] [--max <pages>]
29
31
  Any site (PHP, Python, Ruby, a CMS), read as a search engine reads it
30
32
 
31
- After a deploy
33
+ Search engines
34
+ maisongr-sitemap connect [--google <file>] [--bing <code>] [--indexnow [key]] [--yes]
35
+ robots.txt naming the sitemap (asks first), and the files that verify the site
36
+ maisongr-sitemap llms [--from <url>] [--out <dir>] [--stdout]
37
+ llms.txt for AI assistants, from the sitemap and each page's own words
32
38
  maisongr-sitemap indexnow --site <url> --key <key>
33
39
  Tell Bing and the other IndexNow engines which pages changed
34
40
  --since <YYYY-MM-DD> --all --dry-run --wait [s] --sitemap <file|url>
@@ -36,6 +42,7 @@ const HELP = `
36
42
  Options
37
43
  --site <url> the address the site is served at --offline don't download fonts
38
44
  --images list each page's images --no-credit leave out the footer credit
45
+ --lang <code> the page's language: en or fr (static, crawl; default the site's)
39
46
  --no-color plain text (also NO_COLOR=1) --version --help
40
47
 
41
48
  Docs: https://github.com/maison-gr/sitemap
@@ -43,6 +50,19 @@ const HELP = `
43
50
  /** The package's own version, from the package.json beside dist/ (or src/). */
44
51
  const version = () => JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
45
52
  const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
53
+ /** Asks on the terminal; anywhere else, says no without waiting. */
54
+ async function askTerminal(question) {
55
+ if (!process.stdin.isTTY)
56
+ return false;
57
+ const { createInterface } = await import("node:readline/promises");
58
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
59
+ try {
60
+ return /^y(es)?$/i.test((await rl.question(` ${question} [y/N] `)).trim());
61
+ }
62
+ finally {
63
+ rl.close();
64
+ }
65
+ }
46
66
  /** A message for the person at the terminal; the command stops and exits with 1. */
47
67
  class Exit extends Error {
48
68
  }
@@ -50,6 +70,7 @@ class Exit extends Error {
50
70
  let args = [];
51
71
  let root = "";
52
72
  let u;
73
+ let ask = async () => false;
53
74
  const flag = (name) => args.includes(`--${name}`);
54
75
  const value = (name) => {
55
76
  const i = args.indexOf(`--${name}`);
@@ -82,7 +103,7 @@ function printReport(r, pages = true) {
82
103
  if (r.missedFonts.length)
83
104
  u.warn(`Fonts not brought in: ${r.missedFonts.join(", ")}`, "system fonts are used instead");
84
105
  if (r.fromPages?.length) {
85
- u.ok(`${plural(r.fromPages.length, "dynamic route")} listed from their own static params`);
106
+ u.ok(`${plural(r.fromPages.length, "dynamic route")} listed from ${r.fromPages.length === 1 ? "its" : "their"} own static params`);
86
107
  u.list(r.fromPages.map((path) => ({ path })));
87
108
  }
88
109
  if (r.skipped.length) {
@@ -91,7 +112,7 @@ function printReport(r, pages = true) {
91
112
  }
92
113
  if (r.needParams.length) {
93
114
  u.heading("Needs values", r.needParams.length);
94
- u.warn(`${plural(r.needParams.length, "dynamic route")} not listed yet`, "give their values in the route file's params");
115
+ u.warn(`${plural(r.needParams.length, "dynamic route")} not listed yet`, `give ${r.needParams.length === 1 ? "its" : "their"} values in the route file's params`);
95
116
  u.list(r.needParams.map((path) => ({ path })));
96
117
  }
97
118
  }
@@ -303,6 +324,7 @@ function whatElse() {
303
324
  u.heading("You can also");
304
325
  if (rebuilds)
305
326
  u.next(u.code("npx maisongr-sitemap build"), "re-read pages, dates and theme now; your build already runs it");
327
+ u.next(u.code("npx maisongr-sitemap connect"), "robots.txt, and the files Google, Bing and IndexNow check");
306
328
  u.next(u.code("npx maisongr-sitemap indexnow --site <url> --key <key>"), "after a deploy, tell Bing and the other IndexNow engines what changed");
307
329
  u.next(u.code("npx maisongr-sitemap --help"), "every command and option");
308
330
  u.next(u.code("https://github.com/maison-gr/sitemap#readme"), "the full guide");
@@ -377,7 +399,7 @@ async function build() {
377
399
  u.warn(`maisongr-sitemap: ${REBUILT}`, REBUILT_NOTE);
378
400
  u.ok(`maisongr-sitemap: ${plural(report.routes, "page")}, ${report.dated} dated`, `→ ${rel(report.manifestPath)}`);
379
401
  if (report.needParams.length)
380
- u.warn(`${plural(report.needParams.length, "dynamic route")} not listed yet: ${report.needParams.join(", ")}`, "give their values in params");
402
+ u.warn(`${plural(report.needParams.length, "dynamic route")} not listed yet: ${report.needParams.join(", ")}`, `give ${report.needParams.length === 1 ? "its" : "their"} values in params`);
381
403
  }
382
404
  function runStatic() {
383
405
  const dir = args[1];
@@ -389,7 +411,7 @@ function runStatic() {
389
411
  // A single-page app's pages are in its router's table, not in the build output.
390
412
  const routes = spaRoutes(root);
391
413
  const added = (value("add") ?? "").split(",").map((p) => p.trim()).filter(Boolean);
392
- const report = buildStatic(join(root, dir), site, { credit: !flag("no-credit"), images: flag("images"), cleanUrls: flag("clean-urls"), extra: [...(routes?.paths ?? []), ...added] });
414
+ const report = buildStatic(join(root, dir), site, { credit: !flag("no-credit"), images: flag("images"), cleanUrls: flag("clean-urls"), lang: value("lang"), extra: [...(routes?.paths ?? []), ...added] });
393
415
  u.heading("Found");
394
416
  u.ok(`${plural(report.pages, "page")}`, routes ? `${routes.router} routes included` : undefined);
395
417
  u.ok(`Theme: ${report.theme.name}`, `${report.theme.dark ? "light and dark" : "light only, as the site"} · fonts: ${report.theme.fonts.map((f) => f.family).join(", ") || "system"}`);
@@ -422,7 +444,7 @@ async function runCrawl() {
422
444
  u.endProgress();
423
445
  if (!report.entries.length)
424
446
  fail(`No page could be listed from ${start}.\nIs the site running, and is its home page public? Open it in a browser to check.`);
425
- const written = writeSitemapFiles(join(root, out), report.entries, report.theme, !flag("no-credit"));
447
+ const written = writeSitemapFiles(join(root, out), report.entries, report.theme, { credit: !flag("no-credit"), lang: value("lang") ?? report.lang });
426
448
  const dated = report.entries.filter((e) => e.lastmod).length;
427
449
  u.heading("Found");
428
450
  u.ok(plural(report.entries.length, "page"), `${dated} with a date the page states`);
@@ -442,6 +464,221 @@ async function runCrawl() {
442
464
  u.next("Run it again after content changes", "a deploy step or a daily cron, so the list stays current");
443
465
  u.next(`Open ${u.code(`${site ? trimSlashes(site) : new URL(start).origin}/sitemap/`)}`, "the page; /sitemap.xml is styled with CSS for browsers that open it");
444
466
  }
467
+ /** Files that answer /robots.txt from code, which connect can only advise on. */
468
+ const ROBOTS_ROUTES = ["app/robots.ts", "app/robots.js", "src/app/robots.ts", "src/app/robots.js", "src/pages/robots.txt.ts", "src/pages/robots.txt.js", "src/routes/robots.txt/+server.ts", "src/routes/robots.txt/+server.js", "server/routes/robots.txt.ts"];
469
+ /** The folder the site serves files from at its root, where robots.txt and the verification files go. */
470
+ function publicDirOf(found) {
471
+ const given = value("public");
472
+ if (given)
473
+ return given;
474
+ if (found.kind === "sveltekit")
475
+ return "static";
476
+ if (found.kind === "next" || found.kind === "astro" || found.kind === "nuxt" || found.kind === "spa")
477
+ return "public";
478
+ if (found.kind === "node") {
479
+ const client = clientOf(root, servedDirs(root, sourceFiles(root)));
480
+ return client ? rel(client.publicDir) : existsSync(join(root, "public")) ? "public" : undefined;
481
+ }
482
+ if (found.kind === "static" && found.outDir === ".")
483
+ return ".";
484
+ return undefined;
485
+ }
486
+ /** Writes a file the site serves, unless one with other content is already there. */
487
+ function placeFile(dir, name, body, what) {
488
+ const file = join(root, dir, name);
489
+ const shown = `${dir === "." ? "" : `${dir}/`}${name}`;
490
+ mkdirSync(dirname(file), { recursive: true });
491
+ try {
492
+ // "wx": created only if it isn't there, in one step, so nothing can appear between a check and the write.
493
+ writeFileSync(file, body, { flag: "wx" });
494
+ return u.ok(shown, what);
495
+ }
496
+ catch (error) {
497
+ if (error.code !== "EEXIST")
498
+ throw error;
499
+ }
500
+ if (readFileSync(file, "utf8").trim() === body.trim())
501
+ return u.ok(shown, `${what}: already there`);
502
+ u.warn(`${shown} is already there, with other content`, "kept as it is; remove it first to replace it");
503
+ }
504
+ /** A file's text, or null when there is none: one read, no separate check that could go stale. */
505
+ function readOrNull(file) {
506
+ try {
507
+ return readFileSync(file, "utf8");
508
+ }
509
+ catch (error) {
510
+ if (error.code === "ENOENT")
511
+ return null;
512
+ throw error;
513
+ }
514
+ }
515
+ /**
516
+ * What search engines need besides the sitemap: robots.txt naming it, and the
517
+ * files Google, Bing and IndexNow fetch to check the site is yours. It asks
518
+ * before changing robots.txt, and never replaces a file it did not write.
519
+ */
520
+ async function runConnect() {
521
+ const found = detect(root);
522
+ const site = value("site") ?? process.env.SITEMAP_SITE_URL ?? findSite(sourceFiles(root));
523
+ if (!site || !/^https?:\/\//.test(site))
524
+ fail("Give the address the site is served at.\n npx maisongr-sitemap connect --site https://your.site");
525
+ const base = trimSlashes(site);
526
+ const publicDir = publicDirOf(found);
527
+ if (!publicDir)
528
+ fail("Name the folder your site serves files from at its root.\n npx maisongr-sitemap connect --public public --site https://your.site");
529
+ if (!existsSync(join(root, publicDir)))
530
+ fail(`${publicDir} does not exist.\nGive the folder your site serves files from at its root with --public.`);
531
+ u.subject(`Connecting ${base} to search engines`);
532
+ u.heading("robots.txt");
533
+ const route = ROBOTS_ROUTES.find((f) => existsSync(join(root, f)));
534
+ const served = found.kind === "node" ? sourceFiles(root).find((f) => /\.(?:get|use|all)\s*\(\s*["'`]\/robots\.txt/.test(readFileSync(f, "utf8"))) : undefined;
535
+ const code = route ? join(root, route) : served;
536
+ if (code) {
537
+ const src = readFileSync(code, "utf8");
538
+ if (/sitemap\.xml/.test(src))
539
+ u.ok(`${rel(code)} names a sitemap`, "check it is " + `${base}/sitemap.xml`);
540
+ else
541
+ u.warn(`${rel(code)} writes robots.txt and does not name the sitemap`, `add "Sitemap: ${base}/sitemap.xml"${route ? " (the `sitemap` field)" : ""}`);
542
+ }
543
+ else {
544
+ const file = join(root, publicDir, "robots.txt");
545
+ const current = readOrNull(file);
546
+ const other = current && otherSitemap(current, base);
547
+ const next = robotsWithSitemap(current, base);
548
+ if (other)
549
+ u.warn(`robots.txt names ${other}`, `not ${base}/sitemap.xml: change that line yourself if this one replaces it`);
550
+ else if (next.change === "none")
551
+ u.ok("robots.txt names the sitemap");
552
+ else {
553
+ const what = next.change === "created" ? `Create ${rel(file)}, allowing every crawler and naming the sitemap?` : `Add "Sitemap: ${base}/sitemap.xml" to ${rel(file)}?`;
554
+ if (flag("yes") || (await ask(what))) {
555
+ // A new one is created only if none appeared while the question was open.
556
+ writeFileSync(file, next.text, { flag: next.change === "created" ? "wx" : "w" });
557
+ u.ok(rel(file), next.change === "created" ? "created, naming the sitemap" : "the Sitemap line added at its end");
558
+ }
559
+ else
560
+ u.warn(next.change === "created" ? `No robots.txt` : `${rel(file)} does not name the sitemap`, `left as it is; run again with --yes to ${next.change === "created" ? "create it" : "add the line"}`);
561
+ }
562
+ }
563
+ u.heading("Verification files");
564
+ const google = value("google");
565
+ const bing = value("bing");
566
+ if (google) {
567
+ const f = googleFile(google);
568
+ if (!f)
569
+ fail(`--google takes the file Google gives you, such as google1234abcd5678ef90.html.`);
570
+ placeFile(publicDir, f.name, f.body, "Google Search Console's file");
571
+ }
572
+ if (bing) {
573
+ const f = bingFile(bing);
574
+ if (!f)
575
+ fail(`--bing takes the 32-character code from Bing Webmaster Tools' BingSiteAuth.xml.`);
576
+ placeFile(publicDir, f.name, f.body, "Bing Webmaster Tools' file");
577
+ }
578
+ let key;
579
+ if (flag("indexnow")) {
580
+ const given = value("indexnow");
581
+ const f = indexNowFile(given && !given.startsWith("--") ? given : undefined);
582
+ if (!f)
583
+ fail("--indexnow takes a key of 8 to 128 letters, digits or dashes, or none to make one.");
584
+ key = f.key;
585
+ placeFile(publicDir, f.name, f.body, "the IndexNow key");
586
+ }
587
+ if (!google && !bing && !flag("indexnow"))
588
+ u.text(u.paint("None asked for: add --google <file>, --bing <code> or --indexnow.", "dim"));
589
+ u.heading("Next");
590
+ u.next(`Deploy, then submit ${u.code(`${base}/sitemap.xml`)} in Google Search Console`, "https://search.google.com/search-console");
591
+ u.next("And in Bing Webmaster Tools", "https://www.bing.com/webmasters");
592
+ if (google || bing)
593
+ u.next("Choose the HTML file method there to verify the site", "the file is served from your own domain once deployed");
594
+ if (key)
595
+ u.next(`After each deploy: ${u.code(`npx maisongr-sitemap indexnow --site ${base} --key ${key}`)}`, "keep the key: it's in the file's name");
596
+ }
597
+ /**
598
+ * llms.txt from the sitemap: one version of each page, with the title and
599
+ * description the page itself gives. Reads the site at --from (a local or
600
+ * staging copy) or at its address, and writes where the site serves files.
601
+ */
602
+ async function runLlms() {
603
+ const found = detect(root);
604
+ const site = value("site") ?? process.env.SITEMAP_SITE_URL ?? findSite(sourceFiles(root));
605
+ if (!site || !/^https?:\/\//.test(site))
606
+ fail("Give the address the site is served at.\n npx maisongr-sitemap llms --site https://your.site");
607
+ const base = trimSlashes(site);
608
+ const from = trimSlashes(value("from") ?? base);
609
+ if (!/^https?:\/\//.test(from))
610
+ fail("--from takes the address to read the site at, such as http://localhost:3000.");
611
+ const toStdout = flag("stdout");
612
+ const out = value("out") ?? publicDirOf(found);
613
+ if (!toStdout && !out)
614
+ fail("Name the folder your site serves files from at its root.\n npx maisongr-sitemap llms --out public --site https://your.site");
615
+ const max = value("max") ? Number(value("max")) : 200;
616
+ if (!(max > 0))
617
+ fail("--max takes a number of pages: --max 100");
618
+ const local = (url) => {
619
+ const u = new URL(url);
620
+ return `${from}${u.pathname}${u.search}`;
621
+ };
622
+ const getText = async (url) => {
623
+ const res = await fetch(url, { headers: { "user-agent": "maisongr-sitemap llms (+https://github.com/maison-gr/sitemap)" }, signal: AbortSignal.timeout(20_000) });
624
+ if (!res.ok)
625
+ throw new Error(`${url} answered ${res.status}`);
626
+ return res.text();
627
+ };
628
+ if (!toStdout)
629
+ u.subject(`Reading ${from}/sitemap.xml`);
630
+ let first;
631
+ try {
632
+ first = await getText(`${from}/sitemap.xml`);
633
+ }
634
+ catch (error) {
635
+ return fail(`${error.message.startsWith("http") ? error.message : `${from}/sitemap.xml could not be read`}.\nDeploy first, or read a running copy with --from http://localhost:3000.`);
636
+ }
637
+ const parts = readSitemap(first).parts;
638
+ const xmls = [first, ...(await Promise.all(parts.map((p) => getText(local(p)))))];
639
+ const urls = [...new Set(xmls.flatMap(onePerPage))].sort((a, b) => new URL(a).pathname.split("/").length - new URL(b).pathname.split("/").length || a.localeCompare(b)).slice(0, max);
640
+ if (!urls.length)
641
+ fail(`${from}/sitemap.xml lists no page yet.`);
642
+ // Each page as the site serves it, read a few at a time.
643
+ const html = new Map();
644
+ let next = 0;
645
+ let done = 0;
646
+ await Promise.all(Array.from({ length: 4 }, async () => {
647
+ while (next < urls.length) {
648
+ const url = urls[next++];
649
+ html.set(url, await getText(local(url)).catch(() => ""));
650
+ if (!toStdout)
651
+ u.progress(`Reading… ${++done} of ${urls.length} pages`);
652
+ }
653
+ }));
654
+ u.endProgress();
655
+ const home = html.get(urls.find((url) => new URL(url).pathname.split("/").filter(Boolean).length === 0) ?? urls[0]) ?? "";
656
+ const name = value("name") ?? siteNameOf([...html.values()].filter(Boolean), home) ?? new URL(base).hostname;
657
+ const ordered = urls.map((url) => pageInfo(html.get(url) ?? "", url, name));
658
+ const description = home ? pageInfo(home, base, name).description : undefined;
659
+ const text = llmsText({ name, description, pages: ordered });
660
+ if (toStdout)
661
+ return void u.line(text.trimEnd());
662
+ u.heading("Found");
663
+ u.ok(`${plural(ordered.length, "page")}`, urls.length === max ? `the first ${max}, nearest the home page first; raise --max for more` : "one version of each");
664
+ u.ok(`Name: ${name}`, description ? "description from the home page" : undefined);
665
+ if (!description)
666
+ u.warn("The home page has no meta description", "llms.txt starts with it; add one to say what the site is");
667
+ const missing = ordered.filter((p) => !p.description).length;
668
+ if (missing)
669
+ u.warn(`${plural(missing, "page")} without a meta description`, "listed by title alone");
670
+ const file = join(root, out, "llms.txt");
671
+ u.heading("Wrote");
672
+ const current = readOrNull(file);
673
+ if (current !== null && !current.includes(LLMS_MARK)) {
674
+ u.warn(`${rel(file)} is already there, written by hand`, "kept as it is: --stdout prints this one to compare or copy");
675
+ }
676
+ else {
677
+ // Created only if none appeared meanwhile; replaced only when the one there is this tool's.
678
+ writeFileSync(file, text, { flag: current === null ? "wx" : "w" });
679
+ u.ok(rel(file), "run it again after content changes, or in your build");
680
+ }
681
+ }
445
682
  /** Reads a sitemap from a built file or the live site, following an index into its parts, as a crawler would. */
446
683
  async function sitemapUrls(source) {
447
684
  const read = async (where) => {
@@ -521,9 +758,10 @@ async function runIndexNow() {
521
758
  fail("IndexNow did not accept every batch.\nThe reason for each is above.");
522
759
  }
523
760
  /** Runs one command in `cwd` and returns the exit code. */
524
- export async function main(argv, cwd, streams = { out: (s) => process.stdout.write(s), err: (s) => process.stderr.write(s), style: styleFor(process.stdout), errStyle: styleFor(process.stderr) }) {
761
+ export async function main(argv, cwd, streams = { out: (s) => process.stdout.write(s), err: (s) => process.stderr.write(s), style: styleFor(process.stdout), errStyle: styleFor(process.stderr), ask: askTerminal }) {
525
762
  args = argv;
526
763
  root = cwd;
764
+ ask = streams.ask ?? (async () => false);
527
765
  const plain = { color: false, unicode: true };
528
766
  const noColor = args.includes("--no-color");
529
767
  const style = noColor ? { ...(streams.style ?? plain), color: false } : (streams.style ?? plain);
@@ -536,11 +774,12 @@ export async function main(argv, cwd, streams = { out: (s) => process.stdout.wri
536
774
  else if (command === undefined || command === "help" || command === "--help" || command === "-h")
537
775
  u.line(HELP);
538
776
  else if (COMMANDS[command]) {
539
- // build runs inside every build and CI log: its one or two lines stand alone.
540
- if (command !== "build")
777
+ // build runs inside every build log, and --stdout prints a file: neither gets a title or a Done line.
778
+ const bare = command === "build" || args.includes("--stdout");
779
+ if (!bare)
541
780
  u.title(version(), command);
542
781
  await COMMANDS[command]();
543
- if (command !== "build")
782
+ if (!bare)
544
783
  u.done(Date.now() - started);
545
784
  }
546
785
  else {
@@ -563,7 +802,7 @@ export async function main(argv, cwd, streams = { out: (s) => process.stdout.wri
563
802
  return 1;
564
803
  }
565
804
  }
566
- const COMMANDS = { init, build, static: runStatic, crawl: runCrawl, indexnow: runIndexNow };
805
+ const COMMANDS = { init, build, static: runStatic, crawl: runCrawl, connect: runConnect, llms: runLlms, indexnow: runIndexNow };
567
806
  /** How many letters apart two words are, for "did you mean". */
568
807
  function distance(a, b) {
569
808
  const row = Array.from({ length: b.length + 1 }, (_, i) => i);
package/dist/handler.d.ts CHANGED
@@ -40,6 +40,8 @@ export type SitemapOptions = {
40
40
  };
41
41
  /** The "Sitemap by Maison GR" footer line. Default true. */
42
42
  credit?: boolean;
43
+ /** The language of the page people see: "en" or "fr". Default the site's own default language, else English. */
44
+ lang?: string;
43
45
  };
44
46
  /** An address given through `entries`, its date in any form `DateLike` takes. */
45
47
  export type EntryInput = Omit<Entry, "lastmod"> & {
package/dist/handler.js CHANGED
@@ -43,7 +43,7 @@ export function createSitemap(options = {}) {
43
43
  const ttl = (options.revalidate ?? 3600) * 1000;
44
44
  const trailingSlash = options.trailingSlash ?? manifest.trailingSlash;
45
45
  const basePath = trimSlashes(options.basePath ?? manifest.basePath ?? "") || undefined;
46
- const page = { credit: options.credit, home: basePath || "/" };
46
+ const page = { credit: options.credit, home: basePath || "/", lang: options.lang ?? manifest.locales?.default };
47
47
  let cache;
48
48
  /** The last list that loaded, served when a later load fails: a 5xx on a sitemap costs crawl trust for every address in it. */
49
49
  let lastGood;
package/dist/page.d.ts CHANGED
@@ -9,6 +9,8 @@ export type PageOptions = {
9
9
  };
10
10
  /** Where the site's name links to. Default "/"; the basePath for a site mounted under one. */
11
11
  home?: string;
12
+ /** The page's own language: its labels, and <html lang>. Default English; "fr" for French. */
13
+ lang?: string;
12
14
  };
13
15
  export declare function urlsetPage(entries: Entry[], theme: Theme, options?: PageOptions): string;
14
16
  export declare function indexPage(parts: {
@@ -21,4 +23,4 @@ export declare function indexPage(parts: {
21
23
  export declare const xmlCss: (theme: Theme) => string;
22
24
  export declare function pageCss(theme: Theme): string;
23
25
  /** Served as ?asset=page.js. Filters by path and language; keeps the count live. */
24
- export declare const PAGE_JS = "(function () {\n var q = document.getElementById(\"q\");\n if (!q) return;\n var rows = [].slice.call(document.querySelectorAll(\".row[data-u]\"));\n var groups = [].slice.call(document.querySelectorAll(\".group\"));\n var chips = [].slice.call(document.querySelectorAll(\".chip\"));\n var tally = document.getElementById(\"tally\");\n var empty = document.getElementById(\"empty\");\n var lang = \"\";\n function apply() {\n var term = q.value.trim().toLowerCase(), shown = 0;\n rows.forEach(function (r) {\n var ok = (!term || r.getAttribute(\"data-u\").indexOf(term) !== -1) && (!lang || r.getAttribute(\"data-l\") === lang);\n r.hidden = !ok;\n if (ok) shown++;\n });\n groups.forEach(function (g) { g.hidden = !g.querySelector(\".row:not([hidden])\"); });\n tally.textContent = term || lang ? shown + \" of \" + rows.length + \" pages\" : \"\";\n empty.hidden = shown !== 0;\n }\n q.addEventListener(\"input\", apply);\n chips.forEach(function (chip) {\n chip.addEventListener(\"click\", function () {\n lang = chip.getAttribute(\"data-f\");\n chips.forEach(function (c) { c.setAttribute(\"aria-pressed\", c === chip ? \"true\" : \"false\"); });\n apply();\n });\n });\n})();\n";
26
+ export declare const PAGE_JS = "(function () {\n var q = document.getElementById(\"q\");\n if (!q) return;\n var rows = [].slice.call(document.querySelectorAll(\".row[data-u]\"));\n var groups = [].slice.call(document.querySelectorAll(\".group\"));\n var chips = [].slice.call(document.querySelectorAll(\".chip\"));\n var tally = document.getElementById(\"tally\");\n var empty = document.getElementById(\"empty\");\n var lang = \"\";\n function apply() {\n var term = q.value.trim().toLowerCase(), shown = 0;\n rows.forEach(function (r) {\n var ok = (!term || r.getAttribute(\"data-u\").indexOf(term) !== -1) && (!lang || r.getAttribute(\"data-l\") === lang);\n r.hidden = !ok;\n if (ok) shown++;\n });\n groups.forEach(function (g) { g.hidden = !g.querySelector(\".row:not([hidden])\"); });\n tally.textContent = term || lang ? (tally.getAttribute(\"data-t\") || \"{shown} of {total} pages\").replace(\"{shown}\", shown).replace(\"{total}\", rows.length) : \"\";\n empty.hidden = shown !== 0;\n }\n q.addEventListener(\"input\", apply);\n chips.forEach(function (chip) {\n chip.addEventListener(\"click\", function () {\n lang = chip.getAttribute(\"data-f\");\n chips.forEach(function (c) { c.setAttribute(\"aria-pressed\", c === chip ? \"true\" : \"false\"); });\n apply();\n });\n });\n})();\n";
package/dist/page.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { stringsFor } from "./strings.js";
1
2
  /*
2
3
  * The sitemap as a person sees it: the same addresses the XML lists, set in
3
4
  * the site's own colours and type, grouped by section, with a filter. No
@@ -41,11 +42,12 @@ function sectionsOf(entries) {
41
42
  sections.delete("");
42
43
  return sections;
43
44
  }
44
- const titleOf = (section) => (section ? `/${decodeURIComponent(section)}/` : "Pages");
45
+ const titleOf = (section, t) => (section ? `/${decodeURIComponent(section)}/` : t.pagesSection);
45
46
  function shell(theme, title, body, options) {
46
47
  const assets = options.assets ?? ASSETS;
48
+ const t = stringsFor(options.lang);
47
49
  return `<!doctype html>
48
- <html lang="en">
50
+ <html lang="${esc(t.lang)}">
49
51
  <head>
50
52
  <meta charset="utf-8">
51
53
  <meta name="viewport" content="width=device-width, initial-scale=1">
@@ -60,13 +62,14 @@ ${theme.fonts.flatMap((f) => f.files.slice(0, 1)).map((file) => `<link rel="prel
60
62
  <main class="page">
61
63
  <a class="brand" href="${esc(options.home ?? "/")}">${esc(theme.name)}</a>
62
64
  ${body}
63
- <footer class="foot"><span>Search engines read the XML version of this list.</span>${options.credit !== false ? `<span>Sitemap by <a href="https://www.maisongr.com" rel="noopener">Maison GR</a></span>` : ""}</footer>
65
+ <footer class="foot"><span>${esc(t.footer)}</span>${options.credit !== false ? `<span>${esc(t.credit)} <a href="https://www.maisongr.com" rel="noopener">Maison GR</a></span>` : ""}</footer>
64
66
  </main>
65
67
  <script src="${esc(assets.js)}" defer></script>
66
68
  </body>
67
69
  </html>`;
68
70
  }
69
71
  export function urlsetPage(entries, theme, options = {}) {
72
+ const t = stringsFor(options.lang);
70
73
  const langs = [...new Set(entries.map((e) => e.lang).filter((l) => !!l))];
71
74
  const width = String(entries.length).length < 2 ? 2 : String(entries.length).length;
72
75
  const sections = sectionsOf(entries);
@@ -82,44 +85,45 @@ export function urlsetPage(entries, theme, options = {}) {
82
85
  </li>`;
83
86
  })
84
87
  .join("\n");
85
- return `<section class="group" id="${id}" aria-labelledby="${id}-h"><header class="group-head"><h2 id="${id}-h">${esc(titleOf(key))}</h2><span class="count">${rows.length}</span></header>
88
+ return `<section class="group" id="${id}" aria-labelledby="${id}-h"><header class="group-head"><h2 id="${id}-h">${esc(titleOf(key, t))}</h2><span class="count">${rows.length}</span></header>
86
89
  <ol class="rows">
87
90
  ${items}
88
91
  </ol></section>`;
89
92
  });
90
93
  const counts = langs.map((l) => `<span><b>${entries.filter((e) => e.lang === l).length}</b> ${esc(l.toUpperCase())}</span>`).join("");
91
94
  const chips = langs.length > 1
92
- ? `<div class="chips" role="group" aria-label="Language"><button type="button" class="chip" data-f="" aria-pressed="true">All</button>${langs.map((l) => `<button type="button" class="chip" data-f="${esc(l)}" aria-pressed="false">${esc(l.toUpperCase())}</button>`).join("")}</div>`
95
+ ? `<div class="chips" role="group" aria-label="${esc(t.languageGroup)}"><button type="button" class="chip" data-f="" aria-pressed="true">${esc(t.all)}</button>${langs.map((l) => `<button type="button" class="chip" data-f="${esc(l)}" aria-pressed="false">${esc(l.toUpperCase())}</button>`).join("")}</div>`
93
96
  : "";
94
- const heading = `<p class="eyebrow">Sitemap</p>
95
- <h1>Every page on ${esc(theme.name)}<span class="mark">.</span></h1>`;
97
+ const heading = `<p class="eyebrow">${esc(t.title)}</p>
98
+ <h1>${esc(t.heading(theme.name))}<span class="mark">.</span></h1>`;
96
99
  if (!entries.length) {
97
- return shell(theme, "Sitemap", `${heading}\n<p class="empty">No pages are listed yet. They appear here, and in the XML, once the site publishes them.</p>`, options);
100
+ return shell(theme, t.title, `${heading}\n<p class="empty">${esc(t.empty)}</p>`, options);
98
101
  }
99
102
  const body = `${heading}
100
- <p class="facts"><span><b>${entries.length}</b> ${entries.length === 1 ? "page" : "pages"}</span>${counts}</p>
103
+ <p class="facts"><span><b>${entries.length}</b> ${esc(t.pages(entries.length))}</span>${counts}</p>
101
104
  <div class="tools">
102
- <input id="q" class="search" type="search" placeholder="Filter by path" aria-label="Filter pages by path" autocomplete="off" spellcheck="false">
105
+ <input id="q" class="search" type="search" placeholder="${esc(t.filterPlaceholder)}" aria-label="${esc(t.filterLabel)}" autocomplete="off" spellcheck="false">
103
106
  ${chips}
104
- <p class="tally" id="tally" aria-live="polite"></p>
107
+ <p class="tally" id="tally" aria-live="polite" data-t="${esc(t.tally)}"></p>
105
108
  </div>
106
- ${sections.size > 1 && sections.size <= 12 ? `<nav class="jump" aria-label="Sections">${[...sections].map(([key, rows], i) => `<a href="#s-${i}">${esc(titleOf(key))} <span>${rows.length}</span></a>`).join("")}</nav>` : ""}
109
+ ${sections.size > 1 && sections.size <= 12 ? `<nav class="jump" aria-label="${esc(t.sectionsNav)}">${[...sections].map(([key, rows], i) => `<a href="#s-${i}">${esc(titleOf(key, t))} <span>${rows.length}</span></a>`).join("")}</nav>` : ""}
107
110
  ${groups.join("\n")}
108
- <p class="empty" id="empty" hidden>No page matches this filter.</p>`;
109
- return shell(theme, "Sitemap", body, options);
111
+ <p class="empty" id="empty" hidden>${esc(t.noMatch)}</p>`;
112
+ return shell(theme, t.title, body, options);
110
113
  }
111
114
  export function indexPage(parts, theme, options = {}) {
115
+ const t = stringsFor(options.lang);
112
116
  const total = parts.reduce((s, p) => s + p.count, 0);
113
117
  const rows = parts
114
118
  .map((p, i) => `<li class="row"><span class="num">${pad(i + 1, 2)}</span><a class="url" href="${esc(pathOf(p.loc))}">${esc(p.label ?? pathOf(p.loc))}</a><span class="lang">${p.count}</span><span class="date">${p.lastmod ? esc(p.lastmod) : ""}</span></li>`)
115
119
  .join("\n");
116
- const body = `<p class="eyebrow">Sitemap index</p>
117
- <h1>Every page on ${esc(theme.name)}<span class="mark">.</span></h1>
118
- <p class="facts"><span><b>${total}</b> pages</span><span><b>${parts.length}</b> files</span></p>
119
- <section class="group" aria-labelledby="parts-h"><header class="group-head"><h2 id="parts-h">Files</h2><span class="count">${parts.length}</span></header><ol class="rows">
120
+ const body = `<p class="eyebrow">${esc(t.indexTitle)}</p>
121
+ <h1>${esc(t.heading(theme.name))}<span class="mark">.</span></h1>
122
+ <p class="facts"><span><b>${total}</b> ${esc(t.pages(total))}</span><span><b>${parts.length}</b> ${esc(t.files(parts.length))}</span></p>
123
+ <section class="group" aria-labelledby="parts-h"><header class="group-head"><h2 id="parts-h">${esc(t.filesSection)}</h2><span class="count">${parts.length}</span></header><ol class="rows">
120
124
  ${rows}
121
125
  </ol></section>`;
122
- return shell(theme, "Sitemap index", body, options);
126
+ return shell(theme, t.indexTitle, body, options);
123
127
  }
124
128
  /** The XML styled with CSS, for browsers that open the sitemap without sending Sec-Fetch-Dest. */
125
129
  export const xmlCss = (theme) => `urlset,sitemapindex{display:block;max-width:68rem;margin:0 auto;padding:3rem 1rem;background:${theme.light.background};color:${theme.light.foreground};font:15px/1.6 ui-sans-serif,system-ui,sans-serif}
@@ -207,7 +211,7 @@ export const PAGE_JS = `(function () {
207
211
  if (ok) shown++;
208
212
  });
209
213
  groups.forEach(function (g) { g.hidden = !g.querySelector(".row:not([hidden])"); });
210
- tally.textContent = term || lang ? shown + " of " + rows.length + " pages" : "";
214
+ tally.textContent = term || lang ? (tally.getAttribute("data-t") || "{shown} of {total} pages").replace("{shown}", shown).replace("{total}", rows.length) : "";
211
215
  empty.hidden = shown !== 0;
212
216
  }
213
217
  q.addEventListener("input", apply);
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The page's words, in the site's own language. English and French for now;
3
+ * any other language gets English. A language is chosen by its primary code,
4
+ * so "fr-CA" and "fr" both get French.
5
+ */
6
+ export type Strings = {
7
+ lang: string;
8
+ title: string;
9
+ indexTitle: string;
10
+ heading: (name: string) => string;
11
+ pages: (n: number) => string;
12
+ files: (n: number) => string;
13
+ pagesSection: string;
14
+ filesSection: string;
15
+ filterPlaceholder: string;
16
+ filterLabel: string;
17
+ languageGroup: string;
18
+ all: string;
19
+ sectionsNav: string;
20
+ noMatch: string;
21
+ empty: string;
22
+ footer: string;
23
+ credit: string;
24
+ /** For the filter's live count: {shown} and {total} are filled in by the page's script. */
25
+ tally: string;
26
+ };
27
+ export declare function stringsFor(lang: string | undefined): Strings;
@@ -0,0 +1,46 @@
1
+ const en = {
2
+ lang: "en",
3
+ title: "Sitemap",
4
+ indexTitle: "Sitemap index",
5
+ heading: (name) => `Every page on ${name}`,
6
+ pages: (n) => (n === 1 ? "page" : "pages"),
7
+ files: (n) => (n === 1 ? "file" : "files"),
8
+ pagesSection: "Pages",
9
+ filesSection: "Files",
10
+ filterPlaceholder: "Filter by path",
11
+ filterLabel: "Filter pages by path",
12
+ languageGroup: "Language",
13
+ all: "All",
14
+ sectionsNav: "Sections",
15
+ noMatch: "No page matches this filter.",
16
+ empty: "No pages are listed yet. They appear here, and in the XML, once the site publishes them.",
17
+ footer: "Search engines read the XML version of this list.",
18
+ credit: "Sitemap by",
19
+ tally: "{shown} of {total} pages",
20
+ };
21
+ const fr = {
22
+ lang: "fr",
23
+ title: "Plan du site",
24
+ indexTitle: "Index du plan du site",
25
+ // "d’Atelier", "d’Orbit", but "de Maison GR": de elides before a vowel.
26
+ heading: (name) => `Toutes les pages ${/^[aeiouyàâäéèêëîïôöùûüæœ]/i.test(name) ? "d’" : "de "}${name}`,
27
+ // French takes the singular for 0 and 1.
28
+ pages: (n) => (n < 2 ? "page" : "pages"),
29
+ files: (n) => (n < 2 ? "fichier" : "fichiers"),
30
+ pagesSection: "Pages",
31
+ filesSection: "Fichiers",
32
+ filterPlaceholder: "Filtrer par adresse",
33
+ filterLabel: "Filtrer les pages par adresse",
34
+ languageGroup: "Langue",
35
+ all: "Toutes",
36
+ sectionsNav: "Sections",
37
+ noMatch: "Aucune page ne correspond à ce filtre.",
38
+ empty: "Aucune page n’est encore listée. Elles apparaîtront ici, et dans le XML, dès que le site les publiera.",
39
+ footer: "Les moteurs de recherche lisent la version XML de cette liste.",
40
+ credit: "Plan du site par",
41
+ tally: "{shown} sur {total} pages",
42
+ };
43
+ const LANGUAGES = { en, fr };
44
+ export function stringsFor(lang) {
45
+ return LANGUAGES[(lang ?? "en").toLowerCase().split(/[-_]/)[0]] ?? en;
46
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "maisongr-sitemap",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "description": "One sitemap, two readers: the XML search engines need, and a page in your site's own design for people. Detects your stack, finds your pages, dates them from Git.",
5
5
  "license": "MIT",
6
6
  "author": "Maison GR (https://www.maisongr.com)",