maisongr-sitemap 1.1.0 → 1.2.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 +39 -7
- package/dist/build/crawl.d.ts +32 -0
- package/dist/build/crawl.js +210 -0
- package/dist/build/detect.d.ts +6 -0
- package/dist/build/detect.js +9 -1
- package/dist/build/next-build.js +3 -3
- package/dist/build/next-routes.js +1 -1
- package/dist/build/scripts.js +2 -2
- package/dist/build/spa-routes.d.ts +20 -0
- package/dist/build/spa-routes.js +135 -0
- package/dist/build/static.d.ts +35 -3
- package/dist/build/static.js +110 -33
- package/dist/cli/main.d.ts +3 -0
- package/dist/cli/main.js +329 -117
- package/dist/cli/ui.d.ts +59 -0
- package/dist/cli/ui.js +87 -0
- package/dist/next.d.ts +2 -1
- package/dist/next.js +39 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -26,7 +26,7 @@ The page reads your colours, fonts and dark mode from your own stylesheets. The
|
|
|
26
26
|
|
|
27
27
|
| | **maisongr-sitemap** | next-sitemap | @astrojs/sitemap |
|
|
28
28
|
|---|---|---|---|
|
|
29
|
-
| Frameworks | Next.js, Astro, SvelteKit, Nuxt, Express, any `Request`/`Response` server, any static site | Next.js | Astro |
|
|
29
|
+
| Frameworks | Next.js, Astro, SvelteKit, Nuxt, Express, any `Request`/`Response` server, single-page apps, any static site, any language through `crawl` | Next.js | Astro |
|
|
30
30
|
| What a person sees at `/sitemap.xml` | A page in your site's design | Raw XML | XML styled with your own XSL |
|
|
31
31
|
| `lastmod` | The last commit that changed each page | Build time, by default | What you set |
|
|
32
32
|
| `hreflang` alternates | Read from your routes and i18n config | Configured | From its `i18n` option |
|
|
@@ -53,9 +53,11 @@ The page reads your colours, fonts and dark mode from your own stylesheets. The
|
|
|
53
53
|
| **Static builds**: Astro without an adapter, SvelteKit with `adapter-static`, `nuxt generate` | Static mode, run after your build |
|
|
54
54
|
| **Express**, Connect, Polka, `node:http` | `sitemap.js` beside the server's entry, themed from the frontend it serves (see [Express](#express-and-nodehttp)) |
|
|
55
55
|
| **Anything that speaks `Request` and `Response`**: Hono, Cloudflare Workers, Bun, Deno, React Router | The [handler](#any-other-server) itself |
|
|
56
|
-
| **
|
|
56
|
+
| **Single-page apps**: Vite (React, Vue, Solid, Svelte, Preact) and Create React App | Static mode after your build, with the pages read from your router (see [Single-page apps](#single-page-apps)) |
|
|
57
|
+
| **Any static site**: hand-written HTML, Eleventy, Hugo, Jekyll, any generator | [`static`](#static-sites) on the build output |
|
|
58
|
+
| **Any other language**: PHP (Laravel, WordPress, Symfony), Python, Ruby, Go, Java, .NET, a CMS | [`crawl`](#any-site-in-any-language) reads the running site |
|
|
57
59
|
|
|
58
|
-
Each one has been checked on a real production build: Next.js 15 and 16 (
|
|
60
|
+
Each one has been checked on a real production build: Next.js 15 and 16 (App Router, Pages Router and `cacheComponents`), Astro 7, SvelteKit 3, Nuxt 4 (with `@nuxtjs/i18n`), Express 5, Hono 4, React Router 8, a Vite React app, Eleventy 3, a hand-written HTML site and a server that renders each page on request. The handler also runs on Bun 1.4 and Deno 2.9.
|
|
59
61
|
|
|
60
62
|
## What `init` does
|
|
61
63
|
|
|
@@ -266,11 +268,40 @@ npx maisongr-sitemap static dist --site https://www.example.com
|
|
|
266
268
|
- `sitemap.xml`, styled with CSS, for crawlers;
|
|
267
269
|
- the designed page at `/sitemap/`, for people.
|
|
268
270
|
|
|
269
|
-
It reads the built HTML, so each page's language and `hreflang` links come from the pages themselves. It leaves out pages marked `noindex`, redirects, and sign-in and account pages. The theme comes from your stylesheets and the CSS your build inlined. For a static build of Astro, SvelteKit or Nuxt, `init` adds this step to the end of your `build` script.
|
|
271
|
+
It reads the built HTML, so each page's language and `hreflang` links come from the pages themselves. It leaves out pages marked `noindex`, redirects, and sign-in and account pages. The theme comes from your stylesheets and the CSS your build inlined, and the name from what your pages say (`og:site_name`, or the part their titles share). For a static build of Astro, SvelteKit or Nuxt, `init` adds this step to the end of your `build` script; for another generator with a `build` script, `init --site https://your.site` does the same.
|
|
270
272
|
|
|
271
|
-
|
|
273
|
+
- **Addresses** follow your links. A site that links to `/about.html` gets `/about.html` (plain Apache and nginx serve nothing at `/about`); one that links to `/about` gets `/about`. `--clean-urls` forces the second.
|
|
274
|
+
- **Dates.** Hand-written HTML that Git tracks is dated from Git, file by file. A build output Git ignores gets no `lastmod`: built files don't say when their content changed, and a build date would be false.
|
|
275
|
+
- `--add /press,/jobs` lists addresses no HTML file holds.
|
|
276
|
+
- With `--images`, each page's `og:image` and `<img>` sources go into an image sitemap. It's off by default, so icons and tracking pixels aren't listed unless you ask for them.
|
|
272
277
|
|
|
273
|
-
|
|
278
|
+
## Single-page apps
|
|
279
|
+
|
|
280
|
+
A Vite or Create React App build is one `index.html`; its pages live in your router. `init` reads them from the router's table and adds static mode to your `build` script:
|
|
281
|
+
|
|
282
|
+
```sh
|
|
283
|
+
npx maisongr-sitemap init --site https://www.example.com
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
It reads React Router, Vue Router, TanStack Router, Solid Router, Wouter, Preact Router and svelte-spa-router, in route objects (`{ path: "docs", children: [...] }`) and `<Route path>` elements, nested routes joined. Dynamic routes (`/blog/:slug`) and sign-in or account pages are left out and named; list a dynamic route's pages with `--add` in the build script.
|
|
287
|
+
|
|
288
|
+
Your host must serve `index.html` for paths it has no file for (the usual single-page app setting on Netlify, Vercel, Cloudflare Pages and the rest), so every listed page answers.
|
|
289
|
+
|
|
290
|
+
## Any site, in any language
|
|
291
|
+
|
|
292
|
+
For a site no file describes, PHP, Python, Ruby, Go, a CMS, `crawl` reads it the way a search engine does: from the home page, along its own links.
|
|
293
|
+
|
|
294
|
+
```sh
|
|
295
|
+
npx maisongr-sitemap crawl http://localhost:8000 --out public --site https://www.example.com
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
- `--out` is the folder your server serves files from (`public/` in Laravel and Symfony, the web root in WordPress). The files are the same as static mode's: `sitemap.xml` and the page at `/sitemap/`.
|
|
299
|
+
- `--site` is the public address, when you crawl a local or staging copy. Without it, the address crawled is the one listed.
|
|
300
|
+
- It follows `robots.txt`, `noindex` (in the page or its `X-Robots-Tag` header), `nofollow`, canonicals, redirects and `hreflang` alternates. It leaves out sign-in and account pages, and addresses with a query string, which search engines treat as copies.
|
|
301
|
+
- **Dates** come only from what each page states: `article:modified_time`, `dateModified` in its JSON-LD, or a `Last-Modified` header. A header that says "now" on every response is ignored.
|
|
302
|
+
- `--max 5000` stops after that many pages (default 10,000). It reads four pages at a time, gently.
|
|
303
|
+
|
|
304
|
+
Run it again whenever content changes, after a deploy or from a daily cron, so the list stays current. It needs Node 20.9 or later on the machine that runs it, not on your server.
|
|
274
305
|
|
|
275
306
|
## Telling search engines
|
|
276
307
|
|
|
@@ -292,7 +323,8 @@ With `--images`, each page's `og:image` and `<img>` sources go into an image sit
|
|
|
292
323
|
|
|
293
324
|
## Limits
|
|
294
325
|
|
|
295
|
-
- **Dynamic routes** are listed only when the route is given their values through `params`. The build report names every route that needs them.
|
|
326
|
+
- **Dynamic routes** are listed only when the route is given their values through `params`, or by the page's own `generateStaticParams` or `getStaticPaths`. The build report names every route that needs them.
|
|
327
|
+
- **`crawl` finds only what is linked.** A page nothing links to, or one reached only by a form or a script, isn't found. Link it, or add it to the site's navigation or footer.
|
|
296
328
|
- **The URL is the language code.** An Astro locale written as `{ path: "spanish", codes: ["es"] }` is listed with `hreflang="spanish"`. Pass `locales` to the route to correct it.
|
|
297
329
|
|
|
298
330
|
## Requirements
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { Entry, Theme } from "../types.js";
|
|
2
|
+
/**
|
|
3
|
+
* For a site no file describes (PHP, Python, Ruby, Go, a CMS…): reads it the
|
|
4
|
+
* way a search engine does, from the home page along its own links, and lists
|
|
5
|
+
* the pages a search engine would keep. It follows robots.txt, noindex (in the
|
|
6
|
+
* page or its X-Robots-Tag), nofollow, canonicals and redirects.
|
|
7
|
+
*/
|
|
8
|
+
export type CrawlOptions = {
|
|
9
|
+
/** The address the site is served at publicly, when the crawl reads another (http://localhost:8000). */
|
|
10
|
+
site?: string;
|
|
11
|
+
/** Stop after this many pages. Default 10,000. */
|
|
12
|
+
max?: number;
|
|
13
|
+
/** Requests at a time. Default 4, gentle on a small server. */
|
|
14
|
+
concurrency?: number;
|
|
15
|
+
images?: boolean;
|
|
16
|
+
fetch?: typeof fetch;
|
|
17
|
+
/** Called after each page is read, with the pages listed and the addresses seen so far. */
|
|
18
|
+
onPage?: (listed: number, seen: number) => void;
|
|
19
|
+
};
|
|
20
|
+
export type CrawlReport = {
|
|
21
|
+
entries: Entry[];
|
|
22
|
+
skipped: {
|
|
23
|
+
path: string;
|
|
24
|
+
reason: string;
|
|
25
|
+
}[];
|
|
26
|
+
theme: Theme;
|
|
27
|
+
capped: boolean;
|
|
28
|
+
queries: number;
|
|
29
|
+
};
|
|
30
|
+
/** robots.txt's rules for every crawler (User-agent: *), longest match wins, Allow over Disallow on a tie. */
|
|
31
|
+
export declare function robotsRules(text: string): (path: string) => boolean;
|
|
32
|
+
export declare function crawl(start: string, options?: CrawlOptions): Promise<CrawlReport>;
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { trimSlashes } from "../entries.js";
|
|
2
|
+
import { styleBlocks } from "./project.js";
|
|
3
|
+
import { privateOf } from "./route-rules.js";
|
|
4
|
+
import { attr, holds, pageFacts, themeOf } from "./static.js";
|
|
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
|
+
const AGENT = "maisongr-sitemap (+https://github.com/maison-gr/sitemap)";
|
|
7
|
+
const tags = (html, name) => [...html.matchAll(new RegExp(`<${name}\\b[^>]*>`, "gi"))].map((m) => m[0]);
|
|
8
|
+
const unescape = (s) => s.replace(/&/g, "&");
|
|
9
|
+
/** robots.txt's rules for every crawler (User-agent: *), longest match wins, Allow over Disallow on a tie. */
|
|
10
|
+
export function robotsRules(text) {
|
|
11
|
+
const rules = [];
|
|
12
|
+
let applies = false;
|
|
13
|
+
let inAgents = false;
|
|
14
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
15
|
+
const line = raw.split("#")[0];
|
|
16
|
+
const colon = line.indexOf(":");
|
|
17
|
+
if (colon < 0)
|
|
18
|
+
continue;
|
|
19
|
+
const [key, value] = [line.slice(0, colon).trim().toLowerCase(), line.slice(colon + 1).trim()];
|
|
20
|
+
if (key === "user-agent") {
|
|
21
|
+
if (!inAgents)
|
|
22
|
+
applies = false;
|
|
23
|
+
inAgents = true;
|
|
24
|
+
if (value === "*")
|
|
25
|
+
applies = true;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
inAgents = false;
|
|
29
|
+
if (applies && (key === "allow" || key === "disallow") && value)
|
|
30
|
+
rules.push({ allow: key === "allow", prefix: value.replace(/\*$/, "").replace(/\$$/, "") });
|
|
31
|
+
}
|
|
32
|
+
return (path) => {
|
|
33
|
+
let best;
|
|
34
|
+
for (const r of rules) {
|
|
35
|
+
if (!path.startsWith(r.prefix))
|
|
36
|
+
continue;
|
|
37
|
+
if (!best || r.prefix.length > best.prefix.length || (r.prefix.length === best.prefix.length && r.allow))
|
|
38
|
+
best = r;
|
|
39
|
+
}
|
|
40
|
+
return best ? best.allow : true;
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/** The date a page states for its last change, if it states one. */
|
|
44
|
+
function statedDate(html, lastModified) {
|
|
45
|
+
const meta = tags(html, "meta").find((t) => ["property", "name", "itemprop"].some((n) => /^(?:article:modified_time|og:updated_time|datemodified|last-modified)$/i.test(attr(t, n) ?? "")));
|
|
46
|
+
const ld = html.match(/"dateModified"\s*:\s*"([^"]+)"/)?.[1];
|
|
47
|
+
for (const value of [meta && attr(meta, "content"), ld]) {
|
|
48
|
+
if (value && !Number.isNaN(Date.parse(value)))
|
|
49
|
+
return value;
|
|
50
|
+
}
|
|
51
|
+
// A Last-Modified that is "now" is a dynamic page stamping every response, not a real date.
|
|
52
|
+
if (lastModified) {
|
|
53
|
+
const t = Date.parse(lastModified);
|
|
54
|
+
if (!Number.isNaN(t) && Date.now() - t > 5 * 60_000)
|
|
55
|
+
return new Date(t).toISOString();
|
|
56
|
+
}
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
/** url(...) in a stylesheet made absolute, so the page served from the site's root finds the same fonts. */
|
|
60
|
+
const absoluteUrls = (css, from, origin) => css.replace(/url\(([^)]*)\)/g, (whole, inner) => {
|
|
61
|
+
const href = inner.trim().replace(/^(["'])(.*)\1$/, "$2");
|
|
62
|
+
if (!href || href.startsWith("data:"))
|
|
63
|
+
return whole;
|
|
64
|
+
let url;
|
|
65
|
+
try {
|
|
66
|
+
url = new URL(href, from);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return whole;
|
|
70
|
+
}
|
|
71
|
+
return url.origin === origin ? `url("${url.pathname}")` : whole;
|
|
72
|
+
});
|
|
73
|
+
export async function crawl(start, options = {}) {
|
|
74
|
+
const get = options.fetch ?? fetch;
|
|
75
|
+
const startUrl = new URL(start);
|
|
76
|
+
const origin = startUrl.origin;
|
|
77
|
+
const base = trimSlashes(options.site ?? origin);
|
|
78
|
+
const publicOrigin = new URL(base).origin;
|
|
79
|
+
const max = options.max ?? 10_000;
|
|
80
|
+
const request = (url) => get(url, { redirect: "manual", headers: { "user-agent": AGENT, accept: "text/html,*/*;q=0.5" }, signal: AbortSignal.timeout(20_000) });
|
|
81
|
+
const robotsRes = await request(`${origin}/robots.txt`).catch(() => null);
|
|
82
|
+
const allowed = robotsRules(robotsRes?.ok ? await robotsRes.text() : "");
|
|
83
|
+
/** A link as a path on this site, or null when it leaves the site or isn't a page. */
|
|
84
|
+
const queries = new Set();
|
|
85
|
+
const pathOf = (href, from) => {
|
|
86
|
+
let url;
|
|
87
|
+
try {
|
|
88
|
+
url = new URL(unescape(href), from);
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
if (url.origin !== origin && url.origin !== publicOrigin)
|
|
94
|
+
return null;
|
|
95
|
+
if (!/^https?:$/.test(url.protocol) || NOT_PAGES.test(url.pathname))
|
|
96
|
+
return null;
|
|
97
|
+
if (url.search) {
|
|
98
|
+
queries.add(url.pathname + url.search);
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
return url.pathname;
|
|
102
|
+
};
|
|
103
|
+
const seen = new Set();
|
|
104
|
+
const queue = [];
|
|
105
|
+
const add = (path) => {
|
|
106
|
+
if (path === null || seen.has(path) || path === "/sitemap.xml" || path.startsWith("/sitemap/"))
|
|
107
|
+
return;
|
|
108
|
+
seen.add(path);
|
|
109
|
+
queue.push(path);
|
|
110
|
+
};
|
|
111
|
+
add(startUrl.pathname);
|
|
112
|
+
const entries = [];
|
|
113
|
+
const skipped = [];
|
|
114
|
+
const pages = [];
|
|
115
|
+
let home = "";
|
|
116
|
+
async function visit(path) {
|
|
117
|
+
if (!allowed(path))
|
|
118
|
+
return void skipped.push({ path, reason: "robots.txt disallows it" });
|
|
119
|
+
const privateSegment = privateOf(path.split("/").filter(Boolean));
|
|
120
|
+
if (privateSegment)
|
|
121
|
+
return void skipped.push({ path, reason: `private page (${privateSegment})` });
|
|
122
|
+
const res = await request(`${origin}${path}`).catch((error) => ({ error }));
|
|
123
|
+
if ("error" in res)
|
|
124
|
+
return void skipped.push({ path, reason: `could not be read (${res.error.message})` });
|
|
125
|
+
if (res.status >= 300 && res.status < 400) {
|
|
126
|
+
const to = res.headers.get("location");
|
|
127
|
+
const target = to ? pathOf(to, `${origin}${path}`) : null;
|
|
128
|
+
skipped.push({ path, reason: `redirects${target ? ` to ${target}` : ""}` });
|
|
129
|
+
return add(target);
|
|
130
|
+
}
|
|
131
|
+
if (res.status !== 200)
|
|
132
|
+
return void skipped.push({ path, reason: `answers ${res.status}` });
|
|
133
|
+
if (!/text\/html|application\/xhtml/i.test(res.headers.get("content-type") ?? ""))
|
|
134
|
+
return;
|
|
135
|
+
const html = await res.text();
|
|
136
|
+
if (path === startUrl.pathname)
|
|
137
|
+
home = html;
|
|
138
|
+
pages.push(html);
|
|
139
|
+
const robots = tags(html, "meta").find((t) => attr(t, "name")?.toLowerCase() === "robots");
|
|
140
|
+
const directives = `${attr(robots ?? "", "content") ?? ""},${res.headers.get("x-robots-tag") ?? ""}`;
|
|
141
|
+
if (!/nofollow/i.test(directives)) {
|
|
142
|
+
for (const a of tags(html, "a")) {
|
|
143
|
+
if (holds(a, "rel", "nofollow"))
|
|
144
|
+
continue;
|
|
145
|
+
const href = attr(a, "href");
|
|
146
|
+
if (href && !href.startsWith("#"))
|
|
147
|
+
add(pathOf(href, `${origin}${path}`));
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
// Language versions named only in hreflang are followed too, as search engines do.
|
|
151
|
+
for (const link of tags(html, "link").filter((t) => holds(t, "rel", "alternate") && attr(t, "hreflang"))) {
|
|
152
|
+
const href = attr(link, "href");
|
|
153
|
+
if (href)
|
|
154
|
+
add(pathOf(href, `${origin}${path}`));
|
|
155
|
+
}
|
|
156
|
+
if (/noindex/i.test(directives))
|
|
157
|
+
return void skipped.push({ path, reason: "noindex" });
|
|
158
|
+
// A page whose canonical is another address is a copy: the canonical one is listed instead.
|
|
159
|
+
const canonical = tags(html, "link").find((t) => holds(t, "rel", "canonical"));
|
|
160
|
+
const canonicalPath = canonical && attr(canonical, "href") ? pathOf(attr(canonical, "href"), `${origin}${path}`) : null;
|
|
161
|
+
if (canonicalPath !== null && canonicalPath !== path) {
|
|
162
|
+
skipped.push({ path, reason: `canonical is ${canonicalPath}` });
|
|
163
|
+
return add(canonicalPath);
|
|
164
|
+
}
|
|
165
|
+
const facts = pageFacts(html, `${base}${path}`, base, options.images);
|
|
166
|
+
if ("skip" in facts)
|
|
167
|
+
return void skipped.push({ path, reason: facts.skip });
|
|
168
|
+
// Alternates the page writes with the address the crawl reads are given the public one.
|
|
169
|
+
const alternates = facts.entry.alternates?.map((a) => (a.href.startsWith(origin) ? { ...a, href: `${base}${a.href.slice(origin.length)}` } : a));
|
|
170
|
+
const lastmod = statedDate(html, res.headers.get("last-modified"));
|
|
171
|
+
entries.push({ ...facts.entry, ...(alternates ? { alternates } : {}), ...(lastmod ? { lastmod } : {}) });
|
|
172
|
+
}
|
|
173
|
+
// A few requests at a time, as the queue grows.
|
|
174
|
+
let capped = false;
|
|
175
|
+
let next = 0;
|
|
176
|
+
async function worker() {
|
|
177
|
+
while (next < queue.length) {
|
|
178
|
+
if (entries.length >= max) {
|
|
179
|
+
capped = true;
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
await visit(queue[next++]);
|
|
183
|
+
options.onPage?.(entries.length, seen.size);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
// Workers stop when the queue is momentarily empty, so start more until nothing new is found.
|
|
187
|
+
while (next < queue.length && !capped)
|
|
188
|
+
await Promise.all(Array.from({ length: options.concurrency ?? 4 }, worker));
|
|
189
|
+
// The theme, from the home page's own stylesheets and <style> blocks.
|
|
190
|
+
const css = [];
|
|
191
|
+
for (const link of tags(home, "link").filter((t) => holds(t, "rel", "stylesheet"))) {
|
|
192
|
+
const href = attr(link, "href");
|
|
193
|
+
if (!href)
|
|
194
|
+
continue;
|
|
195
|
+
const url = new URL(unescape(href), `${origin}/`);
|
|
196
|
+
if (url.origin !== origin)
|
|
197
|
+
continue;
|
|
198
|
+
const res = await request(url.href).catch(() => null);
|
|
199
|
+
if (res?.ok)
|
|
200
|
+
css.push(absoluteUrls(await res.text(), url, origin));
|
|
201
|
+
}
|
|
202
|
+
css.push(absoluteUrls(styleBlocks(home), new URL(`${origin}/`), origin));
|
|
203
|
+
const iconTag = tags(home, "link").find((t) => holds(t, "rel", "icon"));
|
|
204
|
+
const iconHref = iconTag && attr(iconTag, "href");
|
|
205
|
+
const iconUrl = iconHref ? new URL(unescape(iconHref), `${origin}/`) : undefined;
|
|
206
|
+
const icon = iconUrl && iconUrl.origin === origin ? iconUrl.pathname : undefined;
|
|
207
|
+
entries.sort((a, b) => a.loc.localeCompare(b.loc));
|
|
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 };
|
|
210
|
+
}
|
package/dist/build/detect.d.ts
CHANGED
|
@@ -29,6 +29,12 @@ export type Detected = {
|
|
|
29
29
|
| {
|
|
30
30
|
kind: "node";
|
|
31
31
|
name: string;
|
|
32
|
+
}
|
|
33
|
+
/** A single-page app (Vite, Create React App): one index.html, its pages in a client-side router's table. */
|
|
34
|
+
| {
|
|
35
|
+
kind: "spa";
|
|
36
|
+
name: string;
|
|
37
|
+
outDir: string;
|
|
32
38
|
} | {
|
|
33
39
|
kind: "static";
|
|
34
40
|
outDir: string;
|
package/dist/build/detect.js
CHANGED
|
@@ -3,7 +3,8 @@ import { join } from "node:path";
|
|
|
3
3
|
/** Frameworks recognised but without their own adapter yet: they can use static mode on their build output. */
|
|
4
4
|
const LATER = [
|
|
5
5
|
["@remix-run/react", "Remix"],
|
|
6
|
-
|
|
6
|
+
// React Router's framework mode; the library alone is a single-page app's router.
|
|
7
|
+
["@react-router/dev", "React Router"],
|
|
7
8
|
["gatsby", "Gatsby"],
|
|
8
9
|
];
|
|
9
10
|
const BUILD_DIRS = ["out", "dist", "build", "_site", "public"];
|
|
@@ -61,6 +62,13 @@ export function detect(root) {
|
|
|
61
62
|
if (deps[name])
|
|
62
63
|
return { kind: "node", name: label };
|
|
63
64
|
}
|
|
65
|
+
if (deps.vite && existsSync(join(root, "index.html"))) {
|
|
66
|
+
const outDir = /\boutDir\s*:\s*["'`]([^"'`]+)["'`]/.exec(configOf(root, ["vite.config.ts", "vite.config.js", "vite.config.mts", "vite.config.mjs"])?.source ?? "")?.[1] ?? "dist";
|
|
67
|
+
const name = deps.vue ? "Vue" : deps["solid-js"] ? "Solid" : deps.svelte ? "Svelte" : deps.preact ? "Preact" : deps.react ? "React" : "Vite";
|
|
68
|
+
return { kind: "spa", name: `${name} (Vite)`, outDir };
|
|
69
|
+
}
|
|
70
|
+
if (deps["react-scripts"])
|
|
71
|
+
return { kind: "spa", name: "Create React App", outDir: "build" };
|
|
64
72
|
const outDir = BUILD_DIRS.find((d) => existsSync(join(root, d, "index.html")));
|
|
65
73
|
if (outDir)
|
|
66
74
|
return { kind: "static", outDir };
|
package/dist/build/next-build.js
CHANGED
|
@@ -127,8 +127,8 @@ export async function buildNext(root, detected, options = {}) {
|
|
|
127
127
|
writeParamsFile(root, appDir, fromPages);
|
|
128
128
|
return { ...report, needParams: report.needParams.filter((p) => !fromPages.some((r) => r.pattern === p)), fromPages: fromPages.map((r) => r.pattern) };
|
|
129
129
|
}
|
|
130
|
-
/** export function generateStaticParams
|
|
131
|
-
const STATIC_PARAMS = /\bexport\s+(?:async\s+)?(?:function\s+generateStaticParams\b|const\s+generateStaticParams\s
|
|
130
|
+
/** export function generateStaticParams (or the Pages Router's getStaticPaths), async or as a const. */
|
|
131
|
+
const STATIC_PARAMS = /\bexport\s+(?:async\s+)?(?:function\s+(?:generateStaticParams|getStaticPaths)\b|const\s+(?:generateStaticParams|getStaticPaths)\s*[:=])/;
|
|
132
132
|
/** The file beside the route that hands each dynamic page's generateStaticParams to the sitemap, rewritten on every build. */
|
|
133
133
|
export function paramsPathOf(root, appDir) {
|
|
134
134
|
const ts = existsSync(join(root, "tsconfig.json"));
|
|
@@ -141,7 +141,7 @@ function writeParamsFile(root, appDir, routes) {
|
|
|
141
141
|
const ts = file.endsWith(".ts");
|
|
142
142
|
const lines = routes.map((r) => {
|
|
143
143
|
const spec = toPosix(relative(dirname(file), join(root, r.page))).replace(/\.(tsx|ts|jsx|js)$/, "");
|
|
144
|
-
return ` ${literal(r.pattern)}: staticParams(() => import(${literal(spec.startsWith(".") ? spec : `./${spec}`)})),`;
|
|
144
|
+
return ` ${literal(r.pattern)}: staticParams(() => import(${literal(spec.startsWith(".") ? spec : `./${spec}`)}), ${literal(r.pattern)}),`;
|
|
145
145
|
});
|
|
146
146
|
mkdirSync(dirname(file), { recursive: true });
|
|
147
147
|
writeFileSync(file, `// Written by \`maisongr-sitemap build\` before each build: each dynamic page's own generateStaticParams,
|
|
@@ -74,7 +74,7 @@ export function pagesRoutes(root, pagesDir) {
|
|
|
74
74
|
else if (isNoindex(root, full))
|
|
75
75
|
skipped.push({ pattern, reason: "noindex" });
|
|
76
76
|
else
|
|
77
|
-
routes.push({ pattern, files: [toPosix(relative(root, full))] });
|
|
77
|
+
routes.push({ pattern, files: [toPosix(relative(root, full))], page: toPosix(relative(root, full)) });
|
|
78
78
|
}
|
|
79
79
|
}
|
|
80
80
|
if (existsSync(base))
|
package/dist/build/scripts.js
CHANGED
|
@@ -19,7 +19,7 @@ export function withBuildStep(scripts = {}, fallback = "next build") {
|
|
|
19
19
|
if (out.build?.includes(COMMAND))
|
|
20
20
|
return { scripts: out, note: "already runs before each build" };
|
|
21
21
|
out.build = out.build ? `${COMMAND} && ${out.build}` : `${COMMAND} && ${fallback}`;
|
|
22
|
-
return { scripts: out, note: `added to the "build" script
|
|
22
|
+
return { scripts: out, note: `added to the "build" script` };
|
|
23
23
|
}
|
|
24
24
|
/** For a static build: the sitemap is written into the output once the site's own build has finished. */
|
|
25
25
|
export function withStaticStep(scripts = {}, outDir, site, fallback) {
|
|
@@ -28,5 +28,5 @@ export function withStaticStep(scripts = {}, outDir, site, fallback) {
|
|
|
28
28
|
if (out.build?.includes("maisongr-sitemap static"))
|
|
29
29
|
return { scripts: out, note: "already runs after each build" };
|
|
30
30
|
out.build = `${out.build ?? fallback} && ${step}`;
|
|
31
|
-
return { scripts: out, note: `added to the end of the "build" script
|
|
31
|
+
return { scripts: out, note: `added to the end of the "build" script` };
|
|
32
32
|
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Client-side routers whose route tables live in code, which a single-page app's build output never shows. */
|
|
2
|
+
export declare const CLIENT_ROUTERS: string[];
|
|
3
|
+
export declare function clientRouter(root: string): string | undefined;
|
|
4
|
+
/**
|
|
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
|
|
7
|
+
* `<Route path="docs"><Route path="setup" /></Route>` both give /docs/setup.
|
|
8
|
+
* One pass that skips strings and comments, so it runs in linear time.
|
|
9
|
+
*/
|
|
10
|
+
export declare function routePaths(source: string): string[];
|
|
11
|
+
export type SpaRoutes = {
|
|
12
|
+
router: string;
|
|
13
|
+
paths: string[];
|
|
14
|
+
skipped: {
|
|
15
|
+
path: string;
|
|
16
|
+
reason: string;
|
|
17
|
+
}[];
|
|
18
|
+
};
|
|
19
|
+
/** The public pages a single-page app's router declares, from the files that import it. */
|
|
20
|
+
export declare function spaRoutes(root: string): SpaRoutes | null;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { readPackage } from "./detect.js";
|
|
2
|
+
import { sourceFiles } from "./project.js";
|
|
3
|
+
import { privateOf, read } from "./route-rules.js";
|
|
4
|
+
/** Client-side routers whose route tables live in code, which a single-page app's build output never shows. */
|
|
5
|
+
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
|
+
export function clientRouter(root) {
|
|
7
|
+
const pkg = readPackage(root);
|
|
8
|
+
const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
|
|
9
|
+
return CLIENT_ROUTERS.find((r) => deps[r]);
|
|
10
|
+
}
|
|
11
|
+
const join = (parent, path) => (path.startsWith("/") ? path : `${parent.replace(/\/$/, "")}/${path}`).replace(/\/{2,}/g, "/");
|
|
12
|
+
/**
|
|
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
|
|
15
|
+
* `<Route path="docs"><Route path="setup" /></Route>` both give /docs/setup.
|
|
16
|
+
* One pass that skips strings and comments, so it runs in linear time.
|
|
17
|
+
*/
|
|
18
|
+
export function routePaths(source) {
|
|
19
|
+
const stack = [];
|
|
20
|
+
const found = [];
|
|
21
|
+
const pathOfStack = () => stack.reduce((p, f) => (f.path === undefined ? p : join(p, f.path)), "/");
|
|
22
|
+
let i = 0;
|
|
23
|
+
const n = source.length;
|
|
24
|
+
const readString = () => {
|
|
25
|
+
const quote = source[i];
|
|
26
|
+
let out = "";
|
|
27
|
+
for (i++; i < n && source[i] !== quote; i++) {
|
|
28
|
+
if (source[i] === "\\")
|
|
29
|
+
i++;
|
|
30
|
+
else
|
|
31
|
+
out += source[i];
|
|
32
|
+
}
|
|
33
|
+
i++;
|
|
34
|
+
return out;
|
|
35
|
+
};
|
|
36
|
+
while (i < n) {
|
|
37
|
+
const c = source[i];
|
|
38
|
+
if (c === "/" && source[i + 1] === "/") {
|
|
39
|
+
const end = source.indexOf("\n", i);
|
|
40
|
+
i = end < 0 ? n : end;
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
if (c === "/" && source[i + 1] === "*") {
|
|
44
|
+
const end = source.indexOf("*/", i + 2);
|
|
45
|
+
i = end < 0 ? n : end + 2;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
49
|
+
readString();
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
// path: "x" in a route object, or path="x" on a <Route>.
|
|
53
|
+
if (c === "p" && source.startsWith("path", i) && !/[\w$]/.test(source[i - 1] ?? "") && !/[\w$]/.test(source[i + 4] ?? "")) {
|
|
54
|
+
let j = i + 4;
|
|
55
|
+
while (/\s/.test(source[j] ?? ""))
|
|
56
|
+
j++;
|
|
57
|
+
if (source[j] === ":" || source[j] === "=") {
|
|
58
|
+
j++;
|
|
59
|
+
while (/\s/.test(source[j] ?? "") || source[j] === "{")
|
|
60
|
+
j++;
|
|
61
|
+
if (source[j] === '"' || source[j] === "'" || source[j] === "`") {
|
|
62
|
+
i = j;
|
|
63
|
+
const value = readString();
|
|
64
|
+
const top = stack[stack.length - 1];
|
|
65
|
+
if (top && top.path === undefined && !value.includes("${")) {
|
|
66
|
+
top.path = value;
|
|
67
|
+
found.push(pathOfStack());
|
|
68
|
+
}
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
i += 4;
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (c === "<" && source.startsWith("<Route", i) && !/[\w$]/.test(source[i + 6] ?? "")) {
|
|
76
|
+
stack.push({ kind: "route", inTag: true });
|
|
77
|
+
i += 6;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (c === "<" && source.startsWith("</Route>", i)) {
|
|
81
|
+
while (stack.length && stack.pop().kind !== "route")
|
|
82
|
+
;
|
|
83
|
+
i += 8;
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
const top = stack[stack.length - 1];
|
|
87
|
+
if (c === ">" && top?.kind === "route" && top.inTag && source[i - 1] !== "=") {
|
|
88
|
+
if (source[i - 1] === "/")
|
|
89
|
+
stack.pop();
|
|
90
|
+
else
|
|
91
|
+
top.inTag = false;
|
|
92
|
+
i++;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (c === "{")
|
|
96
|
+
stack.push({ kind: "brace" });
|
|
97
|
+
else if (c === "}") {
|
|
98
|
+
while (stack.length && stack.pop().kind !== "brace")
|
|
99
|
+
;
|
|
100
|
+
}
|
|
101
|
+
i++;
|
|
102
|
+
}
|
|
103
|
+
return found;
|
|
104
|
+
}
|
|
105
|
+
/** The public pages a single-page app's router declares, from the files that import it. */
|
|
106
|
+
export function spaRoutes(root) {
|
|
107
|
+
const router = clientRouter(root);
|
|
108
|
+
if (!router)
|
|
109
|
+
return null;
|
|
110
|
+
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();
|
|
112
|
+
const skipped = [];
|
|
113
|
+
for (const file of files) {
|
|
114
|
+
const source = read(file);
|
|
115
|
+
if (!CLIENT_ROUTERS.some((r) => source.includes(`"${r}"`) || source.includes(`'${r}'`)))
|
|
116
|
+
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))
|
|
120
|
+
continue;
|
|
121
|
+
const segments = path.split("/").filter(Boolean);
|
|
122
|
+
const dynamic = segments.find((s) => /^[:$]|[*[(]/.test(s));
|
|
123
|
+
const privateSegment = privateOf(segments);
|
|
124
|
+
if (dynamic)
|
|
125
|
+
skipped.push({ path, reason: "dynamic: list its pages with --add" });
|
|
126
|
+
else if (privateSegment)
|
|
127
|
+
skipped.push({ path, reason: `private page (${privateSegment})` });
|
|
128
|
+
else if (segments[0] === "api")
|
|
129
|
+
skipped.push({ path, reason: "API" });
|
|
130
|
+
else
|
|
131
|
+
paths.add(path);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return { router, paths: [...paths].sort(), skipped };
|
|
135
|
+
}
|
package/dist/build/static.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Theme } from "../types.js";
|
|
1
|
+
import type { Entry, Theme } from "../types.js";
|
|
2
2
|
export type StaticReport = {
|
|
3
3
|
pages: number;
|
|
4
4
|
skipped: {
|
|
@@ -8,8 +8,40 @@ export type StaticReport = {
|
|
|
8
8
|
written: string[];
|
|
9
9
|
theme: Theme;
|
|
10
10
|
};
|
|
11
|
-
|
|
11
|
+
/** An attribute's value, in double, single or no quotes (minified HTML drops them): href=/about. */
|
|
12
|
+
export declare const attr: (tag: string, name: string) => string | undefined;
|
|
13
|
+
/** Whether an attribute holds this word among its words, as rel="alternate icon" holds icon. */
|
|
14
|
+
export declare const holds: (tag: string, name: string, word: string) => boolean;
|
|
15
|
+
/**
|
|
16
|
+
* The site's name: what its pages say it is (og:site_name, application-name),
|
|
17
|
+
* else the part their titles share ("About | Lumen" and "Menu | Lumen" give
|
|
18
|
+
* "Lumen"), else the first part of the home page's title.
|
|
19
|
+
*/
|
|
20
|
+
export declare function siteNameOf(pages: string[], home: string): string | undefined;
|
|
21
|
+
export type StaticOptions = {
|
|
12
22
|
name?: string;
|
|
13
23
|
credit?: boolean;
|
|
14
24
|
images?: boolean;
|
|
15
|
-
|
|
25
|
+
/** Addresses no HTML file holds: a single-page app's routes, and any given with --add. */
|
|
26
|
+
extra?: string[];
|
|
27
|
+
/** Force /about over /about.html, whatever the site's links do. */
|
|
28
|
+
cleanUrls?: boolean;
|
|
29
|
+
};
|
|
30
|
+
export declare function buildStatic(dir: string, site: string, options?: StaticOptions): StaticReport;
|
|
31
|
+
/** What one page says about itself: why it is left out, or its entry (language, alternates, images). */
|
|
32
|
+
export declare function pageFacts(html: string, loc: string, base: string, withImages?: boolean): {
|
|
33
|
+
skip: string;
|
|
34
|
+
} | {
|
|
35
|
+
entry: Entry;
|
|
36
|
+
};
|
|
37
|
+
/** The page's theme from the site's CSS: colour tokens light and dark, its @font-face fonts, name and icon. */
|
|
38
|
+
export declare function themeOf(site: {
|
|
39
|
+
css: string;
|
|
40
|
+
pages: string[];
|
|
41
|
+
home: string;
|
|
42
|
+
icon?: string;
|
|
43
|
+
name?: string;
|
|
44
|
+
base: string;
|
|
45
|
+
}): Theme;
|
|
46
|
+
/** 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[];
|