maisongr-sitemap 1.3.0 → 1.4.1

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.
@@ -6,15 +6,30 @@ import { join, sep } from "node:path";
6
6
  * private; "accounting-services" is not.
7
7
  */
8
8
  export const PRIVATE_WORDS = new Set([
9
- "login", "logout", "signin", "signout", "signup", "register", "auth", "oauth", "sso", "callback",
10
- "account", "accounts", "dashboard", "settings", "admin", "checkout", "cart", "billing", "onboarding",
11
- "password", "verify", "confirm", "confirmation", "recovery", "unsubscribe", "invite", "invitation", "api",
9
+ "login", "logout", "signin", "signout", "signup", "auth", "oauth", "sso",
10
+ "account", "accounts", "dashboard", "settings", "admin", "checkout", "billing", "onboarding",
11
+ "password", "unsubscribe", "invitation", "api",
12
12
  ]);
13
+ /**
14
+ * Words that name an account step only on their own (/register, /verify) or
15
+ * beside an account word (verify-email, order-confirmation): in a guide's name
16
+ * they are content ("recovery-strategies", "register-your-well").
17
+ */
18
+ const STEP_WORDS = new Set(["register", "verify", "verification", "confirm", "confirmation", "recovery", "recover", "invite", "callback", "cart"]);
19
+ const ACCOUNT_WORDS = new Set(["email", "mail", "phone", "password", "account", "code", "token", "otp", "link", "magic", "order", "payment", "subscription", "identity"]);
20
+ function isPrivateName(segment) {
21
+ const words = segment.toLowerCase().split(/[-_.]/).filter(Boolean);
22
+ if (words.some((w) => PRIVATE_WORDS.has(w)))
23
+ return true;
24
+ if (!words.some((w) => STEP_WORDS.has(w)))
25
+ return false;
26
+ return words.every((w) => STEP_WORDS.has(w)) || words.some((w) => ACCOUNT_WORDS.has(w));
27
+ }
13
28
  /** Written as two words: sign-in, sign-up, sign-out, log-in, log-out. */
14
29
  const SPLIT_WORDS = /(^|-)(sign|log)-(in|up|out)(-|$)/;
15
30
  /** Developer and test pages: dev-reset, debug, test-email, internal… */
16
31
  const TOOL_SEGMENT = /^(dev|debug|test|internal|sandbox)(-|$)/;
17
- const isPrivate = (segment) => !/^[[(]/.test(segment) && (SPLIT_WORDS.test(segment) || TOOL_SEGMENT.test(segment) || segment.split(/[-_.]/).some((w) => PRIVATE_WORDS.has(w)));
32
+ const isPrivate = (segment) => !/^[[(]/.test(segment) && (SPLIT_WORDS.test(segment) || TOOL_SEGMENT.test(segment) || isPrivateName(segment));
18
33
  export const privateOf = (segments) => segments.find(isPrivate);
19
34
  /**
20
35
  * robots: { index: false }, robots: "noindex", a noindex meta tag, or a
@@ -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,8 +22,11 @@ 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;
29
32
  /** The page's language. Default the one the home page declares in <html lang>. */
@@ -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");
package/dist/cli/main.js CHANGED
@@ -103,7 +103,7 @@ function printReport(r, pages = true) {
103
103
  if (r.missedFonts.length)
104
104
  u.warn(`Fonts not brought in: ${r.missedFonts.join(", ")}`, "system fonts are used instead");
105
105
  if (r.fromPages?.length) {
106
- 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`);
107
107
  u.list(r.fromPages.map((path) => ({ path })));
108
108
  }
109
109
  if (r.skipped.length) {
@@ -112,7 +112,7 @@ function printReport(r, pages = true) {
112
112
  }
113
113
  if (r.needParams.length) {
114
114
  u.heading("Needs values", r.needParams.length);
115
- 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`);
116
116
  u.list(r.needParams.map((path) => ({ path })));
117
117
  }
118
118
  }
@@ -399,7 +399,7 @@ async function build() {
399
399
  u.warn(`maisongr-sitemap: ${REBUILT}`, REBUILT_NOTE);
400
400
  u.ok(`maisongr-sitemap: ${plural(report.routes, "page")}, ${report.dated} dated`, `→ ${rel(report.manifestPath)}`);
401
401
  if (report.needParams.length)
402
- 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`);
403
403
  }
404
404
  function runStatic() {
405
405
  const dir = args[1];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "maisongr-sitemap",
3
- "version": "1.3.0",
3
+ "version": "1.4.1",
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)",