create-ailk 0.40.0 → 0.40.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.
@@ -8,6 +8,12 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
8
8
  import { tmpdir } from "node:os";
9
9
  import { join } from "node:path";
10
10
 
11
+ // #11456 D4 — the held hub value, `undefined` (no hub connection) unless a
12
+ // case sets one; the hub read itself is pinned in `hub-site-config.test.ts`.
13
+ const mockHeldHubSite = jest.fn((): unknown => undefined);
14
+ // eslint-disable-next-line no-restricted-syntax -- the held hub value stands in for the hub read, an HTTP boundary
15
+ jest.mock("../hub-site-config", () => ({ heldHubSite: () => mockHeldHubSite() }));
16
+
11
17
  import { readSiteContactLines } from "../site-contact-lines";
12
18
 
13
19
  let root: string;
@@ -210,3 +216,61 @@ describe("readSiteContactLines(locality) — the site's own locality line (#1055
210
216
  ]);
211
217
  });
212
218
  });
219
+
220
+ describe("readSiteContactLines on a hub-connected site (#11456 D4)", () => {
221
+ afterEach(() => mockHeldHubSite.mockReset().mockReturnValue(undefined));
222
+
223
+ it("takes the locality and email from the held hub identity, never the file's", () => {
224
+ writeSite(
225
+ [
226
+ "siteName: Acme",
227
+ "contactEmail: file@acme.test",
228
+ "siteIdentity:",
229
+ " kind: LocalBusiness",
230
+ " name: Acme",
231
+ " url: https://acme.test",
232
+ " telephone: '+14155550100'",
233
+ ...addressYaml(" ", "San Francisco", "CA"),
234
+ ].join("\n"),
235
+ );
236
+ mockHeldHubSite.mockReturnValue({
237
+ identity: {
238
+ kind: "Person",
239
+ name: "Hub Person",
240
+ url: "https://hub.example",
241
+ email: "hub@hub.example",
242
+ address: {
243
+ streetAddress: "1 Hub St",
244
+ addressLocality: "Hubton",
245
+ addressRegion: "HB",
246
+ postalCode: "00001",
247
+ addressCountry: "US",
248
+ },
249
+ },
250
+ seo: null,
251
+ });
252
+ expect(readSiteContactLines()).toEqual([
253
+ { label: "Hubton, HB" },
254
+ { label: "hub@hub.example", href: "mailto:hub@hub.example" },
255
+ ]);
256
+ });
257
+
258
+ it("a hub Organization identity has no locality line, whatever the file declares", () => {
259
+ writeSite(
260
+ [
261
+ "siteName: Acme",
262
+ "siteIdentity:",
263
+ " kind: LocalBusiness",
264
+ " name: Acme",
265
+ " url: https://acme.test",
266
+ " telephone: '+14155550100'",
267
+ ...addressYaml(" ", "San Francisco", "CA"),
268
+ ].join("\n"),
269
+ );
270
+ mockHeldHubSite.mockReturnValue({
271
+ identity: { kind: "Organization", name: "Hub Co", url: "https://hub.example" },
272
+ seo: null,
273
+ });
274
+ expect(readSiteContactLines()).toEqual([]);
275
+ });
276
+ });
@@ -24,9 +24,26 @@ jest.mock("node:fs", () => {
24
24
  });
25
25
 
26
26
  const mockGetContentAdapter = jest.fn<Pick<ContentAdapter, "listPages">, []>();
27
- jest.mock("@working-theory/page-renderer", () => ({
28
- ...jest.requireActual<PageRenderer>("@working-theory/page-renderer"),
29
- getContentAdapter: () => mockGetContentAdapter(),
27
+ // #11456 — the two registrations site-identity.ts makes, recorded per module
28
+ // registry (spies passing through to that registry's real renderer).
29
+ jest.mock("@working-theory/page-renderer", () => {
30
+ const actual = jest.requireActual<PageRenderer>("@working-theory/page-renderer");
31
+ return {
32
+ ...actual,
33
+ getContentAdapter: () => mockGetContentAdapter(),
34
+ setSiteIdentity: jest.fn(actual.setSiteIdentity),
35
+ setSiteIdentityReader: jest.fn(actual.setSiteIdentityReader),
36
+ };
37
+ });
38
+
39
+ // #11456 — the hub read's HTTP call; the rest of the client stays real.
40
+ const mockSiteConfigGet = jest.fn();
41
+ jest.mock("@working-theory/api-client", () => ({
42
+ ...jest.requireActual("@working-theory/api-client"),
43
+ siteConfig: { get: (...args: unknown[]) => mockSiteConfigGet(...args) },
44
+ }));
45
+ jest.mock("next/cache", () => ({
46
+ unstable_cache: (fn: () => Promise<unknown>) => fn,
30
47
  }));
31
48
 
32
49
  type Row = { type: string; slug: string; title: string; sections?: unknown[] };
@@ -143,6 +160,7 @@ describe("the featureList registration with no content directory (#10644 AC-2)",
143
160
 
144
161
  afterEach(() => {
145
162
  renderer?.setSiteFeatureListReader(undefined);
163
+ renderer?.setSiteIdentityReader(undefined);
146
164
  renderer?.setSiteIdentity(undefined);
147
165
  renderer = undefined;
148
166
  rmSync(root, { recursive: true, force: true });
@@ -193,4 +211,98 @@ describe("the featureList registration with no content directory (#10644 AC-2)",
193
211
  expect(appNode(result as Record<string, unknown>)).not.toHaveProperty("featureList");
194
212
  expect(mockGetContentAdapter).toHaveBeenCalledTimes(0);
195
213
  });
214
+
215
+ describe("the hub identity reader (#11456 D4, AC-2)", () => {
216
+ const HUB_IDENTITY = {
217
+ kind: "Organization",
218
+ name: "Hub Co",
219
+ // Another origin: no workspace value may move an `@id` (SEC-11456-6).
220
+ url: "https://elsewhere.example",
221
+ description: "The hub's description.",
222
+ sameAs: ["https://social.example/hub"],
223
+ };
224
+ const savedHub = {
225
+ key: process.env.AILK_SPOKE_KEY,
226
+ api: process.env.AILK_API_URL,
227
+ };
228
+
229
+ function hubConnect(): void {
230
+ process.env.CONTENT_ADAPTER = "database";
231
+ process.env.AILK_SPOKE_KEY = "ailk_spk_TESTKEYxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
232
+ process.env.AILK_API_URL = "https://hub.example";
233
+ }
234
+
235
+ /** The registrations the last `loadSiteIdentity()` made. */
236
+ const calls = (name: "setSiteIdentity" | "setSiteIdentityReader") =>
237
+ jest.mocked(loadedRenderer![name]).mock.calls;
238
+ let loadedRenderer: PageRenderer | undefined;
239
+ const load = (): PageRenderer => {
240
+ // The mocked renderer is one instance across registries: forget the
241
+ // registrations earlier loads made.
242
+ const shared = jest.requireMock<PageRenderer>("@working-theory/page-renderer");
243
+ jest.mocked(shared.setSiteIdentity).mockClear();
244
+ jest.mocked(shared.setSiteIdentityReader).mockClear();
245
+ return (loadedRenderer = loadSiteIdentity());
246
+ };
247
+
248
+ beforeEach(() => {
249
+ mockSiteConfigGet.mockReset();
250
+ mockSiteConfigGet.mockResolvedValue({ ok: true, body: { identity: HUB_IDENTITY, seo: null } });
251
+ });
252
+
253
+ afterEach(() => {
254
+ restore("AILK_SPOKE_KEY", savedHub.key);
255
+ restore("AILK_API_URL", savedHub.api);
256
+ });
257
+
258
+ it("hub-connected: registers a reader carrying the hub identity on the file's baseUrl; every @id stays on the file's origin", async () => {
259
+ hubConnect();
260
+ delete process.env.NEXT_PUBLIC_SITE_URL;
261
+ const renderer = load();
262
+
263
+ expect(calls("setSiteIdentityReader")).toHaveLength(1);
264
+ const reader = calls("setSiteIdentityReader")[0]![0] as () => Promise<unknown>;
265
+ await expect(reader()).resolves.toEqual({
266
+ siteName: "Hub Co",
267
+ baseUrl: ORIGIN,
268
+ identity: HUB_IDENTITY,
269
+ });
270
+
271
+ const result = (await renderer.pageToJsonLd(
272
+ { type: "AboutPage", slug: "about", title: "About" } as Parameters<PageRenderer["pageToJsonLd"]>[0],
273
+ "en",
274
+ )) as Record<string, unknown>;
275
+ const graph = (result["@graph"] ?? []) as Array<Record<string, unknown>>;
276
+ expect(graph.find((n) => n["@type"] === "Organization")).toMatchObject({
277
+ "@id": `${ORIGIN}/#organization`,
278
+ name: "Hub Co",
279
+ description: "The hub's description.",
280
+ sameAs: ["https://social.example/hub"],
281
+ });
282
+ const ids = graph.map((n) => n["@id"]).filter((id): id is string => typeof id === "string");
283
+ expect(ids.length).toBeGreaterThan(0);
284
+ for (const id of ids) expect(id.startsWith(`${ORIGIN}/`)).toBe(true);
285
+ expect(JSON.stringify(result)).not.toContain("elsewhere.example/#");
286
+ });
287
+
288
+ it("hub-connected with no hub identity row: the reader answers undefined, so the file registration composes", async () => {
289
+ hubConnect();
290
+ mockSiteConfigGet.mockResolvedValue({ ok: true, body: { identity: null, seo: null } });
291
+ load();
292
+ const reader = calls("setSiteIdentityReader")[0]![0] as () => Promise<unknown>;
293
+ await expect(reader()).resolves.toBeUndefined();
294
+ });
295
+
296
+ it.each([
297
+ ["no AILK_SPOKE_KEY", () => delete process.env.AILK_SPOKE_KEY],
298
+ ["CONTENT_ADAPTER unset", () => delete process.env.CONTENT_ADAPTER],
299
+ ])("not hub-connected (%s): registers no reader, and setSiteIdentity receives the file registration", (_label, unset) => {
300
+ hubConnect();
301
+ unset();
302
+ load();
303
+ expect(calls("setSiteIdentityReader")).toEqual([]);
304
+ expect(calls("setSiteIdentity")).toEqual([[readSiteIdentity(root)]]);
305
+ expect(mockSiteConfigGet).not.toHaveBeenCalled();
306
+ });
307
+ });
196
308
  });
@@ -0,0 +1,151 @@
1
+ /**
2
+ * The hub read of the site's identity and seo (#11456, spec
3
+ * docs/specs/11456-a-hub-connected-site-reads-spec.md D3).
4
+ *
5
+ * A HUB-CONNECTED site — `CONTENT_ADAPTER=database` (the switch
6
+ * `resolveBlogSource` uses, samhenry#687) AND a spoke key that would go on the
7
+ * wire (`sendsSpokeKey()`) — reads `GET /v1/content/site-config`, which
8
+ * answers its own workspace's rows. Any other site makes no call and keeps
9
+ * reading `content/_site.mdx`: without a key the route can only answer 401.
10
+ *
11
+ * Cached with Next's `unstable_cache` under `siteConfigTag()` for at most
12
+ * `HUB_SITE_REVALIDATE_SECONDS`. The `site-config` revalidate event an Admin
13
+ * save fires purges the tag (`app/api/revalidate/route.ts`); the expiry is the
14
+ * safety net for a spoke with no `revalidateUrl`. The key parts carry a
15
+ * digest of the spoke key — never the key — so two deployments with different
16
+ * keys sharing one data cache never share an entry (SEC-11456-2).
17
+ *
18
+ * Inside the cached callback a non-2xx, a throw, a read slower than
19
+ * `HUB_SITE_TIMEOUT_MS` or a body without the two keys THROWS, so nothing is
20
+ * written and Next keeps serving the last entry (`page-renderer`'s
21
+ * `api-source.ts` failure rule). Outside, a failure answers this instance's
22
+ * last good value, else `undefined` — so a hub outage never reaches a page.
23
+ * The timeout does not abort the request (`http.ts`'s `get` takes no signal).
24
+ *
25
+ * One read per request: `readHubSite` is wrapped in React's `cache()`, so
26
+ * the layout's metadata, its render and every page's JSON-LD share it.
27
+ *
28
+ * `site-brand.tsx`, `site-identity.ts`, `site-contact-email.ts` and
29
+ * `site-contact-lines.ts` import this module; it imports none of them.
30
+ */
31
+
32
+ import { createHash } from "node:crypto";
33
+
34
+ import { sendsSpokeKey, siteConfig } from "@working-theory/api-client";
35
+ import { resolvedAdapterKind } from "@working-theory/content-adapters";
36
+ import {
37
+ siteConfigTag,
38
+ siteWorkspaceSegment,
39
+ } from "@working-theory/page-renderer/edge";
40
+ import {
41
+ SEOSchema,
42
+ SiteIdentitySchema,
43
+ type SEO,
44
+ type SiteIdentity,
45
+ } from "@working-theory/site-config/schema";
46
+ import { cache } from "react";
47
+ import type { ZodType } from "zod";
48
+
49
+ /** The workspace's identity and seo rows as the site reads them; each `null` when absent or unreadable. */
50
+ export interface HubSite {
51
+ identity: SiteIdentity | null;
52
+ seo: SEO | null;
53
+ }
54
+
55
+ /** How long one hub read is served before it is read again. */
56
+ export const HUB_SITE_REVALIDATE_SECONDS = 300;
57
+ /** A read slower than this is a failed read. */
58
+ export const HUB_SITE_TIMEOUT_MS = 3_000;
59
+
60
+ /** Whether this site reads its identity from the hub. */
61
+ export function hubConnected(): boolean {
62
+ return resolvedAdapterKind() === "database" && sendsSpokeKey();
63
+ }
64
+
65
+ /** The last value `readHubSite` resolved on this instance. */
66
+ let held: HubSite | undefined;
67
+
68
+ function parsedOrNull<T>(schema: ZodType<T>, value: unknown): T | null {
69
+ const parsed = schema.safeParse(value);
70
+ return parsed.success ? parsed.data : null;
71
+ }
72
+
73
+ /** One hub read. Throws on any failure, so the cache writes nothing. */
74
+ async function fetchHubSite(): Promise<HubSite> {
75
+ let timer: ReturnType<typeof setTimeout> | undefined;
76
+ const timeout = new Promise<never>((_resolve, reject) => {
77
+ timer = setTimeout(
78
+ () => reject(new Error("hub site-config read timed out")),
79
+ HUB_SITE_TIMEOUT_MS,
80
+ );
81
+ timer.unref?.();
82
+ });
83
+ try {
84
+ const res = await Promise.race([siteConfig.get(), timeout]);
85
+ if (!res.ok) throw new Error(`hub site-config read answered ${res.status}`);
86
+ const body: unknown = res.body;
87
+ if (
88
+ typeof body !== "object" ||
89
+ body === null ||
90
+ !("identity" in body) ||
91
+ !("seo" in body)
92
+ ) {
93
+ throw new Error("hub site-config read answered no rows");
94
+ }
95
+ return {
96
+ identity: parsedOrNull(SiteIdentitySchema, body.identity),
97
+ seo: parsedOrNull(SEOSchema, body.seo),
98
+ };
99
+ } finally {
100
+ clearTimeout(timer);
101
+ }
102
+ }
103
+
104
+ /** The first 16 hex of the spoke key's SHA-256 — a cache-key part, never the key. */
105
+ function spokeKeyDigest(): string {
106
+ return createHash("sha256")
107
+ .update((process.env.AILK_SPOKE_KEY ?? "").trim(), "utf8")
108
+ .digest("hex")
109
+ .slice(0, 16);
110
+ }
111
+
112
+ /**
113
+ * The hub's identity and seo for this site, or `undefined` when the site is
114
+ * not hub-connected (no call made) or no read has ever succeeded here.
115
+ * Never rejects. Shared within one request (React `cache()`).
116
+ */
117
+ export const readHubSite = cache(async function readHubSite(): Promise<
118
+ HubSite | undefined
119
+ > {
120
+ if (!hubConnected()) return undefined;
121
+ try {
122
+ // Loaded only on the hub-connected path, so a site that is not one loads
123
+ // nothing it did not load before.
124
+ const { unstable_cache } = await import("next/cache");
125
+ const read = unstable_cache(
126
+ fetchHubSite,
127
+ ["ailk-hub-site-config", siteWorkspaceSegment(), spokeKeyDigest()],
128
+ { tags: [siteConfigTag()], revalidate: HUB_SITE_REVALIDATE_SECONDS },
129
+ );
130
+ held = await read();
131
+ } catch (err) {
132
+ console.warn(
133
+ `[hub-site-config] read failed (${err instanceof Error ? err.name : typeof err}); serving the last good value`,
134
+ );
135
+ }
136
+ return held;
137
+ });
138
+
139
+ /**
140
+ * The last value `readHubSite` resolved on this instance (synchronous), for
141
+ * the readers whose seam is synchronous — the contact email and contact
142
+ * lines. `undefined` on a cold instance's first render.
143
+ */
144
+ export function heldHubSite(): HubSite | undefined {
145
+ return hubConnected() ? held : undefined;
146
+ }
147
+
148
+ /** Test seam: forget the held value. */
149
+ export function __resetHubSiteForTests(): void {
150
+ held = undefined;
151
+ }
@@ -36,6 +36,25 @@ function escapeRegExp(segment: string): string {
36
36
  return segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
37
37
  }
38
38
 
39
+ /**
40
+ * The page's ancestors below the home as bare (locale-less) paths, nearest
41
+ * first — every parent the walk may ask about (`lib/served-pages.ts` matches
42
+ * them against the app's dynamic page routes, #11438). None for an absent or
43
+ * empty pathname.
44
+ */
45
+ export function ancestorPaths(
46
+ pathname: string | null | undefined,
47
+ locales: readonly string[],
48
+ ): string[] {
49
+ if (!pathname) return [];
50
+ const segments = barePath(pathname, locales).split("/").filter(Boolean);
51
+ const ancestors: string[] = [];
52
+ for (let depth = segments.length - 1; depth >= 1; depth--) {
53
+ ancestors.push(`/${segments.slice(0, depth).join("/")}`);
54
+ }
55
+ return ancestors;
56
+ }
57
+
39
58
  /**
40
59
  * The page's served parent as a bare (locale-less) path, nearest first, or
41
60
  * `null` when no ancestor below the home is served.
@@ -48,14 +67,7 @@ export function servedParent(input: {
48
67
  locales: readonly string[];
49
68
  served: (barePath: string) => boolean;
50
69
  }): string | null {
51
- const { pathname, locales, served } = input;
52
- if (!pathname) return null;
53
- const segments = barePath(pathname, locales).split("/").filter(Boolean);
54
- for (let depth = segments.length - 1; depth >= 1; depth--) {
55
- const parent = `/${segments.slice(0, depth).join("/")}`;
56
- if (served(parent)) return parent;
57
- }
58
- return null;
70
+ return ancestorPaths(input.pathname, input.locales).find((path) => input.served(path)) ?? null;
59
71
  }
60
72
 
61
73
  /** The arrow's server href: the served parent under the home's locale prefix, else `homePath`. */
@@ -104,20 +116,45 @@ export function navLabelsByPath(
104
116
  return labels;
105
117
  }
106
118
 
119
+ /** The separators a page title may join a trailing site name with. */
120
+ const SITE_NAME_SEPARATORS = [" — ", " | ", " - "] as const;
121
+
122
+ /**
123
+ * `title` without a trailing ` — <siteName>` / ` | <siteName>` /
124
+ * ` - <siteName>` (hub-built pages title themselves "About — Sam Henry").
125
+ * Only that exact trailing form is removed: the site name anywhere else, or
126
+ * a suffix that would leave nothing, is left alone.
127
+ */
128
+ function stripSiteNameSuffix(title: string, siteName: string | undefined): string {
129
+ const name = siteName?.trim();
130
+ if (!name) return title;
131
+ for (const separator of SITE_NAME_SEPARATORS) {
132
+ const suffix = `${separator}${name}`;
133
+ if (title.endsWith(suffix) && title.length > suffix.length) {
134
+ return title.slice(0, -suffix.length).trim() || title;
135
+ }
136
+ }
137
+ return title;
138
+ }
139
+
107
140
  /**
108
141
  * The name the arrow's label gives its destination ("Back to <name>"): the
109
- * parent's nav label, else its page title, else its last segment in words
110
- * (`/meet` → "Meet", `/case-studies` → "Case studies"), so the label always
111
- * names where the link goes.
142
+ * parent's nav label, else its page title with a trailing site-name suffix
143
+ * removed, else its last segment in words (`/meet` → "Meet",
144
+ * `/case-studies` → "Case studies"), so the label always names where the
145
+ * link goes.
112
146
  */
113
147
  export function backLinkName(
114
148
  parent: string,
115
149
  sources: {
116
150
  navLabels: ReadonlyMap<string, string>;
117
151
  titles: ReadonlyMap<string, string>;
152
+ siteName?: string;
118
153
  },
119
154
  ): string {
120
- const named = sources.navLabels.get(parent) || sources.titles.get(parent);
155
+ const title = sources.titles.get(parent);
156
+ const named =
157
+ sources.navLabels.get(parent) || (title ? stripSiteNameSuffix(title, sources.siteName) : "");
121
158
  if (named) return named;
122
159
  const words = (parent.split("/").pop() ?? "").replace(/-/g, " ");
123
160
  return words.charAt(0).toUpperCase() + words.slice(1);
@@ -8,20 +8,28 @@
8
8
  * (`app/sitemap.xml/route.ts`: `listPages` per type, `listedPath` over
9
9
  * the site's listing, docs rows and `ThankYouPage` left out). Title =
10
10
  * the page's frontmatter `title`.
11
- * 2. Every fixed, code-rendered route in the routes map (`ROUTES` rows with
12
- * no `:` segment and no `contentPath`) whose module's pages this site
13
- * carries (`lib/modules.generated.ts`) — `/meet` is one: its index is
14
- * code, its seeds are detail pages. No title.
15
- * A route with seed content counts only through source 1, so a scaffold
16
- * that dropped that surface's content never gets a link to a missing page.
17
- * The layout adds the nav and footer paths itself (every nav entry is a
18
- * route the site carries — `lib/nav-config.ts`).
11
+ * 2. Every page route the app builds (#11438) — its page files under
12
+ * `app/`, and Next's app-path routes manifest where those files are not
13
+ * deployed — whatever module or site file put it there. No title. A
14
+ * route with no dynamic segment is a served path in itself; one with a
15
+ * dynamic segment (`[slug]`) serves the candidates the caller asks about
16
+ * that it matches, so `/flows/<slug>` counts under its start page. An
17
+ * optional catch-all serves its own index only; a required catch-all,
18
+ * and a route of dynamic segments alone (the content catch-all), serve
19
+ * nothing.
20
+ * A route with seed content (a `ROUTES` row with a `contentPath`) counts only
21
+ * through source 1, so a scaffold that dropped that surface's content never
22
+ * gets a link to a missing page. The layout adds the nav and footer paths
23
+ * itself (every nav entry is a route the site carries — `lib/nav-config.ts`).
19
24
  *
20
25
  * Shared per server instance for 60 seconds per locale, and fail-safe: any
21
26
  * read that throws leaves that source out, so the arrow degrades toward the
22
27
  * home, never to an error.
23
28
  */
24
29
 
30
+ import { readdirSync, readFileSync } from "node:fs";
31
+ import { join } from "node:path";
32
+
25
33
  import { SCHEMA_ORG_TYPES } from "@working-theory/content-adapters";
26
34
  import type { SchemaOrgType } from "@working-theory/content-adapters";
27
35
  import { getContentAdapter, listedPath } from "@working-theory/page-renderer";
@@ -30,36 +38,120 @@ import { ROUTES } from "@working-theory/templates/routes";
30
38
  import { pagePathFor } from "../src/lib/routes";
31
39
 
32
40
  import { isDocsType } from "./docs-index";
33
- import {
34
- DOCS_BLOG_PAGES,
35
- MARKETING_PAGES,
36
- SCHEDULING_PAGES,
37
- } from "./modules.generated";
38
41
  import { SITE_LISTING } from "./site-listing";
39
42
 
40
43
  const TTL_MS = 60_000;
41
44
 
42
- /** The modules whose code-rendered pages a site may carry, by its generated flags. */
43
- const MODULE_PAGES: Readonly<Record<string, boolean>> = {
44
- marketing: MARKETING_PAGES,
45
- scheduling: SCHEDULING_PAGES,
46
- "docs-blog": DOCS_BLOG_PAGES,
47
- };
45
+ /** The app's locale segment, under which every site page route sits. */
46
+ const LOCALE_SEGMENT = "[locale]";
48
47
 
49
- const cache = new Map<
50
- string,
51
- { at: number; pages: Promise<ReadonlyMap<string, string>> }
52
- >();
48
+ const PAGE_FILE = /^page\.(?:tsx|ts|jsx|js|mdx)$/;
53
49
 
54
- async function readServedPages(
55
- locale: string,
56
- ): Promise<ReadonlyMap<string, string>> {
50
+ interface ServedSet {
51
+ /** Bare path → title for every served path. */
52
+ pages: ReadonlyMap<string, string>;
53
+ /** The built routes with a dynamic segment, as segments. */
54
+ dynamic: readonly (readonly string[])[];
55
+ }
56
+
57
+ const cache = new Map<string, { at: number; served: Promise<ServedSet> }>();
58
+
59
+ function isDynamic(segment: string): boolean {
60
+ return segment.startsWith("[") || segment.startsWith(":");
61
+ }
62
+
63
+ /** A route's shape: its segments, every dynamic one as `*`, whatever its name. */
64
+ function shape(segments: readonly string[]): string {
65
+ return segments.map((segment) => (isDynamic(segment) ? "*" : segment)).join("/");
66
+ }
67
+
68
+ /** The shapes of the routes whose pages render seed content. */
69
+ const CONTENT_SHAPES = new Set(
70
+ ROUTES.filter((row) => row.contentPath !== undefined).map((row) =>
71
+ shape(row.route.split("/").filter(Boolean)),
72
+ ),
73
+ );
74
+
75
+ /** Every page route under `dir`, from its page files, route groups dropped. */
76
+ function pageFileRoutes(dir: string, route = ""): string[] {
77
+ const routes: string[] = [];
78
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
79
+ if (entry.isFile() && PAGE_FILE.test(entry.name)) routes.push(route);
80
+ // `_private` folders and `@slot`s are not URL segments; a `(group)` adds none.
81
+ if (!entry.isDirectory() || /^[_@]/.test(entry.name)) continue;
82
+ const segment = /^\(.*\)$/.test(entry.name) ? "" : `/${entry.name}`;
83
+ routes.push(...pageFileRoutes(join(dir, entry.name), route + segment));
84
+ }
85
+ return routes;
86
+ }
87
+
88
+ /** Every page route in Next's app-path routes manifest (route handlers left out). */
89
+ function manifestRoutes(root: string): string[] {
90
+ const distDir = process.env.__NEXT_RELATIVE_DIST_DIR || ".next";
91
+ const manifest: unknown = JSON.parse(
92
+ readFileSync(join(root, distDir, "app-path-routes-manifest.json"), "utf8"),
93
+ );
94
+ if (typeof manifest !== "object" || manifest === null) return [];
95
+ return Object.entries(manifest)
96
+ .filter(([entry, route]) => entry.endsWith("/page") && typeof route === "string")
97
+ .map(([, route]) => route as string);
98
+ }
99
+
100
+ function readSafely(read: () => string[]): string[] {
101
+ try {
102
+ return read();
103
+ } catch {
104
+ return [];
105
+ }
106
+ }
107
+
108
+ /**
109
+ * The page routes the app builds, as locale-less segments: an optional
110
+ * catch-all's index kept, a required catch-all, a route of dynamic segments
111
+ * alone, the home and every seed-content route left out.
112
+ */
113
+ function builtRoutes(): string[][] {
114
+ const root = process.cwd();
115
+ const routes = new Set([
116
+ ...readSafely(() => pageFileRoutes(join(root, "app"))),
117
+ ...readSafely(() => manifestRoutes(root)),
118
+ ]);
119
+ if (routes.size === 0) {
120
+ // Neither the page files nor the manifest could be read: every code
121
+ // route's arrow falls through to home, so say so once per read.
122
+ console.warn("[served-pages] no page route of the app could be read; the back arrow sees content pages only");
123
+ }
124
+ const built: string[][] = [];
125
+ for (const route of routes) {
126
+ const segments = route.split("/").filter(Boolean);
127
+ // A `_private` segment is never a URL; the walk skips such folders, and
128
+ // the manifest's own entries (`/_not-found`) start with one too.
129
+ if (segments.some((segment) => segment.startsWith("_"))) continue;
130
+ if (segments[0] === LOCALE_SEGMENT) segments.shift();
131
+ if (segments[segments.length - 1]?.startsWith("[[...")) segments.pop();
132
+ if (segments.some((segment) => segment.startsWith("[..."))) continue;
133
+ if (segments.every(isDynamic)) continue;
134
+ if (CONTENT_SHAPES.has(shape(segments))) continue;
135
+ built.push(segments);
136
+ }
137
+ return built;
138
+ }
139
+
140
+ function matches(route: readonly string[], path: string): boolean {
141
+ const segments = path.split("/").filter(Boolean);
142
+ return (
143
+ segments.length === route.length &&
144
+ route.every((segment, i) => isDynamic(segment) || segment === segments[i])
145
+ );
146
+ }
147
+
148
+ async function readServedSet(locale: string): Promise<ServedSet> {
57
149
  const pages = new Map<string, string>();
150
+ const dynamic: string[][] = [];
58
151
 
59
- for (const row of ROUTES) {
60
- if (row.route.includes(":") || row.contentPath !== undefined) continue;
61
- if (MODULE_PAGES[row.module] !== true) continue;
62
- pages.set(row.route, "");
152
+ for (const route of builtRoutes()) {
153
+ if (route.some(isDynamic)) dynamic.push(route);
154
+ else pages.set(`/${route.join("/")}`, "");
63
155
  }
64
156
 
65
157
  try {
@@ -76,20 +168,33 @@ async function readServedPages(
76
168
  }
77
169
  }
78
170
  } catch {
79
- // No adapter: the code-rendered routes alone.
171
+ // No adapter: the built page routes alone.
80
172
  }
81
173
 
82
- return pages;
174
+ return { pages, dynamic };
83
175
  }
84
176
 
85
- /** Bare path → title ("" when the page has none) for every page served in `locale`. */
86
- export function servedPages(
177
+ /**
178
+ * Bare path → title ("" when the page has none) for every page served in
179
+ * `locale`, plus each of `candidates` (bare paths — the page's ancestors,
180
+ * `ancestorPaths`) that a built dynamic route serves.
181
+ */
182
+ export async function servedPages(
87
183
  locale: string,
184
+ candidates: readonly string[] = [],
88
185
  ): Promise<ReadonlyMap<string, string>> {
89
186
  const now = Date.now();
90
- const hit = cache.get(locale);
91
- if (hit && now - hit.at < TTL_MS) return hit.pages;
92
- const pages = readServedPages(locale);
93
- cache.set(locale, { at: now, pages });
94
- return pages;
187
+ let hit = cache.get(locale);
188
+ if (!hit || now - hit.at >= TTL_MS) {
189
+ hit = { at: now, served: readServedSet(locale) };
190
+ cache.set(locale, hit);
191
+ }
192
+ const { pages, dynamic } = await hit.served;
193
+ const matched = candidates.filter(
194
+ (path) => !pages.has(path) && dynamic.some((route) => matches(route, path)),
195
+ );
196
+ if (matched.length === 0) return pages;
197
+ const withMatched = new Map(pages);
198
+ for (const path of matched) withMatched.set(path, "");
199
+ return withMatched;
95
200
  }