@se-studio/project-build 1.1.19 → 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.
@@ -0,0 +1,2309 @@
1
+ /**
2
+ * Marketing page allowlist and thin route generator.
3
+ *
4
+ * A URL is a Contentful slug unless it is the CMS catch-all, an article type,
5
+ * a person type under the people base, or a fixed misc route.
6
+ * `src/lib/marketing-routes.json` names the article bases and the person types.
7
+ * Extra `page.ts` / `page.tsx` files fail. Generated pages, flags, and the
8
+ * markdown rewrite module must match this file.
9
+ *
10
+ * @see docs/CUSTOMER_APP_SKELETON.md
11
+ */
12
+
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+
16
+ export const GENERATED_MARK =
17
+ '/** @generated by scripts/generate-marketing-routes.mjs — do not edit */';
18
+
19
+ const SEGMENT = /^[a-z0-9-]+$/;
20
+
21
+ /** Typed people live here, not under the people base, so the dynamic names do not collide. */
22
+ const PERSON_TYPE_ROOT = 'peopleType';
23
+
24
+ /** Boolean switches written to `src/generated/marketing-flags.ts`. */
25
+ export const MARKETING_FLAG_NAMES = [
26
+ 'enableArticleTypeIndex',
27
+ 'enableArticleTypeTagIndex',
28
+ 'enableTag',
29
+ 'enableTagsIndex',
30
+ 'enablePerson',
31
+ 'enablePeopleIndex',
32
+ 'enablePrimaryTagPartOfSlug',
33
+ ];
34
+
35
+ const FLAGS_REL = 'src/generated/marketing-flags.ts';
36
+ const SLUGS_REL = 'src/generated/marketing-slugs.ts';
37
+ const MARKDOWN_NEGOTIATION_REL = 'src/generated/markdown-negotiation.ts';
38
+
39
+ /**
40
+ * CMS section config. `peopleSlug` may be null. Distinct from hand-written
41
+ * `articleBases` / `personBases`.
42
+ *
43
+ * @param {unknown} config
44
+ */
45
+ export function isSectionConfig(config) {
46
+ return (
47
+ !!config &&
48
+ typeof config === 'object' &&
49
+ (Object.prototype.hasOwnProperty.call(config, 'peopleSlug') ||
50
+ Array.isArray(config.personTypes))
51
+ );
52
+ }
53
+
54
+ /**
55
+ * @param {Record<string, unknown>} config
56
+ */
57
+ export function sectionFlags(config) {
58
+ const people = typeof config.peopleSlug === 'string' && config.peopleSlug.length > 0;
59
+ const personTypes = Array.isArray(config.personTypes) && config.personTypes.length > 0;
60
+ const tags = typeof config.tagsSlug === 'string' && config.tagsSlug.length > 0;
61
+ const tagTypes = Array.isArray(config.tagTypes) && config.tagTypes.length > 0;
62
+ const articles = typeof config.articlesSlug === 'string';
63
+ const articleTypes = Array.isArray(config.articleTypes) && config.articleTypes.length > 0;
64
+ const tagInPath = config.tagInPath === true;
65
+ return {
66
+ enableArticleTypeIndex: articles || articleTypes,
67
+ enableArticleTypeTagIndex: tagInPath && (articles || articleTypes),
68
+ enableTag: tags || tagTypes,
69
+ enableTagsIndex: tags,
70
+ enablePerson: people || personTypes,
71
+ enablePeopleIndex: people,
72
+ enablePrimaryTagPartOfSlug: tagInPath,
73
+ };
74
+ }
75
+
76
+ /**
77
+ * @param {unknown} config
78
+ * @returns {Set<string>} route rests under `(cms-routes)/`, `''` is the home page
79
+ */
80
+ export function allowedRests(config) {
81
+ if (!config || typeof config !== 'object') {
82
+ throw new Error('marketing-routes.json must be an object');
83
+ }
84
+ /** @type {Set<string>} */
85
+ const allowed = new Set();
86
+ if (config.catchAll !== false) {
87
+ allowed.add('');
88
+ allowed.add('[level1]');
89
+ allowed.add('[level1]/[...slugs]');
90
+ }
91
+ if (config.pageTest === true) {
92
+ allowed.add('page-test/[...slugs]');
93
+ }
94
+ if (isSectionConfig(config)) {
95
+ addSectionRests(allowed, config);
96
+ return allowed;
97
+ }
98
+ if (config.tags === true) {
99
+ allowed.add('tags');
100
+ allowed.add('tags/[tag]');
101
+ }
102
+ const articles = Array.isArray(config.articleBases) ? config.articleBases : [];
103
+ for (const base of articles) {
104
+ const segment = requireSegment(base?.path, 'articleBases.path');
105
+ if (base.shape === 'dynamic') {
106
+ allowed.add(segment);
107
+ allowed.add(`${segment}/[articleType]`);
108
+ allowed.add(`${segment}/[articleType]/[...slugs]`);
109
+ if (base.tagInPath === true) {
110
+ allowed.add(`${segment}/[articleType]/[tag]`);
111
+ allowed.add(`${segment}/[articleType]/[tag]/[...slugs]`);
112
+ }
113
+ } else if (base.shape === 'fixed') {
114
+ allowed.add(segment);
115
+ allowed.add(`${segment}/[...slugs]`);
116
+ if (base.tagInPath === true) {
117
+ allowed.add(`${segment}/[tag]`);
118
+ allowed.add(`${segment}/[tag]/[...slugs]`);
119
+ }
120
+ } else {
121
+ throw new Error(`articleBases.shape for "${segment}" must be "fixed" or "dynamic"`);
122
+ }
123
+ }
124
+ const people = Array.isArray(config.personBases) ? config.personBases : [];
125
+ for (const base of people) {
126
+ const segment = requireSegment(base?.path, 'personBases.path');
127
+ if (base.index !== false) {
128
+ allowed.add(segment);
129
+ }
130
+ allowed.add(`${segment}/[person]`);
131
+ for (const type of personTypeNames(base)) {
132
+ allowed.add(`${segment}/${type}`);
133
+ allowed.add(`${segment}/${type}/[person]`);
134
+ }
135
+ }
136
+ if (people.length > 0) {
137
+ allowed.add(typedPersonRest());
138
+ }
139
+ return allowed;
140
+ }
141
+
142
+ /**
143
+ * @param {string} appRoot
144
+ */
145
+ export function readMarketingRoutes(appRoot) {
146
+ const configPath = path.join(appRoot, 'src/lib/marketing-routes.json');
147
+ if (!fs.existsSync(configPath)) {
148
+ return null;
149
+ }
150
+ return JSON.parse(fs.readFileSync(configPath, 'utf8'));
151
+ }
152
+
153
+ /**
154
+ * @param {string} appRoot
155
+ * @returns {{ pages: string[], outside: string[] }}
156
+ */
157
+ export function listMarketingPages(appRoot) {
158
+ /** @type {string[]} */
159
+ const pages = [];
160
+ /** @type {string[]} */
161
+ const outside = [];
162
+ const appDir = path.join(appRoot, 'src/app');
163
+ if (!fs.existsSync(appDir)) {
164
+ return { pages, outside };
165
+ }
166
+ walk(appDir, (file) => {
167
+ const base = path.basename(file);
168
+ if (base !== 'page.ts' && base !== 'page.tsx') {
169
+ return;
170
+ }
171
+ const rel = path.relative(appRoot, file).split(path.sep).join('/');
172
+ if (rel.includes('/(cms-dev)/') || rel.startsWith('src/app/(cms-dev)/')) {
173
+ return;
174
+ }
175
+ if (isPreviewPage(rel)) {
176
+ return;
177
+ }
178
+ const rest = routeRestFromRel(rel);
179
+ if (rest === null) {
180
+ outside.push(rel);
181
+ return;
182
+ }
183
+ pages.push(rest);
184
+ });
185
+ return { pages, outside };
186
+ }
187
+
188
+ /**
189
+ * URL rest under `(cms-routes)`. Route groups are not segments, including a
190
+ * group nested inside `(cms-routes)` such as `(with-chrome)`.
191
+ *
192
+ * @param {string} rel posix path from the app root
193
+ * @returns {string|null} `''` is the home page; null when this is not a cms page
194
+ */
195
+ export function routeRestFromRel(rel) {
196
+ const marker = '(cms-routes)/';
197
+ const idx = rel.indexOf(marker);
198
+ if (idx === -1) {
199
+ return null;
200
+ }
201
+ let rest = rel.slice(idx + marker.length).replace(/\/page\.tsx?$/, '');
202
+ if (rest === 'page.ts' || rest === 'page.tsx') {
203
+ rest = '';
204
+ }
205
+ return rest
206
+ .split('/')
207
+ .filter((segment) => segment.length > 0 && !isRouteGroup(segment))
208
+ .join('/');
209
+ }
210
+
211
+ /**
212
+ * @param {string} appRoot
213
+ */
214
+ export function checkMarketingRoutes(appRoot) {
215
+ let config;
216
+ try {
217
+ config = readMarketingRoutes(appRoot);
218
+ } catch (error) {
219
+ const message = error instanceof Error ? error.message : String(error);
220
+ return { ok: false, severity: 'error', detail: `marketing-routes.json: ${message}` };
221
+ }
222
+ if (!config) {
223
+ return {
224
+ ok: true,
225
+ severity: 'warn',
226
+ detail: 'no src/lib/marketing-routes.json — extra page check skipped',
227
+ };
228
+ }
229
+ let allowed;
230
+ try {
231
+ allowed = allowedRests(config);
232
+ } catch (error) {
233
+ const message = error instanceof Error ? error.message : String(error);
234
+ return { ok: false, severity: 'error', detail: message };
235
+ }
236
+ const found = listMarketingPages(appRoot);
237
+ const extras = found.pages.filter((rest) => !allowed.has(rest));
238
+ const drift = generatedDrift(appRoot, config);
239
+ /** @type {string[]} */
240
+ const problems = [
241
+ ...found.outside,
242
+ ...extras.map((rest) => `(cms-routes)/${rest ? `${rest}/` : ''}page`),
243
+ ...drift,
244
+ ...supportDrift(appRoot, config),
245
+ ...policyProblems(appRoot, allowed),
246
+ ...proxyMarkdownProblems(appRoot),
247
+ ];
248
+ if (problems.length > 0) {
249
+ return {
250
+ ok: false,
251
+ severity: 'error',
252
+ detail: `page files outside marketing-routes.json: ${problems.join('; ')}`,
253
+ };
254
+ }
255
+ return {
256
+ ok: true,
257
+ detail: `${found.pages.length} cms page files match marketing-routes.json`,
258
+ };
259
+ }
260
+
261
+ /**
262
+ * Thin CMS pages described by marketing-routes.json. Person types are named
263
+ * segments under the people base. `[level1]` stays a generic page.
264
+ *
265
+ * A `tagInPath` base also gets its `[tag]` index and detail files.
266
+ *
267
+ * @param {unknown} config
268
+ * @returns {Map<string, string>} rest → file contents
269
+ */
270
+ export function renderGeneratedRoutes(config) {
271
+ if (!config || typeof config !== 'object') {
272
+ throw new Error('marketing-routes.json must be an object');
273
+ }
274
+ /** @type {Map<string, string>} */
275
+ const files = new Map();
276
+ if (config.catchAll !== false) {
277
+ files.set('', homePage());
278
+ files.set('[level1]', levelPage());
279
+ files.set('[level1]/[...slugs]', levelSlugsPage());
280
+ }
281
+ if (isSectionConfig(config)) {
282
+ renderSectionRoutes(config, files);
283
+ return files;
284
+ }
285
+ if (config.tags === true) {
286
+ files.set('tags', tagsIndexPage());
287
+ files.set('tags/[tag]', tagPage());
288
+ }
289
+ const articles = Array.isArray(config.articleBases) ? config.articleBases : [];
290
+ for (const base of articles) {
291
+ const segment = requireSegment(base?.path, 'articleBases.path');
292
+ if (base.shape === 'fixed') {
293
+ files.set(segment, fixedArticleIndex(segment));
294
+ files.set(`${segment}/[...slugs]`, fixedArticleDetail(segment));
295
+ if (base.tagInPath === true) {
296
+ files.set(`${segment}/[tag]`, fixedArticleTag(segment));
297
+ files.set(`${segment}/[tag]/[...slugs]`, fixedArticleTagDetail(segment));
298
+ }
299
+ } else if (base.shape === 'dynamic') {
300
+ files.set(segment, dynamicArticleIndex(segment));
301
+ files.set(`${segment}/[articleType]`, dynamicArticleType(segment));
302
+ files.set(`${segment}/[articleType]/[...slugs]`, dynamicArticleDetail(segment));
303
+ if (base.tagInPath === true) {
304
+ files.set(`${segment}/[articleType]/[tag]`, dynamicArticleTag(segment));
305
+ files.set(
306
+ `${segment}/[articleType]/[tag]/[...slugs]`,
307
+ dynamicArticleTagDetail(segment),
308
+ );
309
+ }
310
+ } else {
311
+ throw new Error(`articleBases.shape for "${segment}" must be "fixed" or "dynamic"`);
312
+ }
313
+ }
314
+ const people = Array.isArray(config.personBases) ? config.personBases : [];
315
+ for (const base of people) {
316
+ const segment = requireSegment(base?.path, 'personBases.path');
317
+ if (base.index !== false) {
318
+ files.set(segment, peopleIndexPage(segment));
319
+ }
320
+ files.set(`${segment}/[person]`, untypedPersonPage(segment));
321
+ for (const type of personTypeNames(base)) {
322
+ files.set(`${segment}/${type}`, personTypeIndexPage(segment, type));
323
+ files.set(`${segment}/${type}/[person]`, personTypePersonPage(segment, type));
324
+ }
325
+ }
326
+ if (people.length > 0) {
327
+ files.set(typedPersonRest(), typedPersonPage());
328
+ }
329
+ return files;
330
+ }
331
+
332
+ /**
333
+ * `[tag]` segments are generated when `tagInPath` is set. Kept so callers
334
+ * that print skip notes stay quiet.
335
+ *
336
+ * @param {unknown} _config
337
+ * @returns {string[]}
338
+ */
339
+ export function tagRouteSkips(_config) {
340
+ return [];
341
+ }
342
+
343
+ /**
344
+ * @param {unknown} config
345
+ */
346
+ export function renderMarketingFlags(config) {
347
+ const derived = isSectionConfig(config) ? sectionFlags(config) : null;
348
+ const lines = MARKETING_FLAG_NAMES.map((name) => {
349
+ const value = derived ? derived[name] : config?.[name];
350
+ if (value === undefined) {
351
+ return `export const ${name} = false;`;
352
+ }
353
+ if (typeof value !== 'boolean') {
354
+ throw new Error(`${name} must be a boolean`);
355
+ }
356
+ return `export const ${name} = ${value};`;
357
+ });
358
+ return `${header()}\n${lines.join('\n')}\n`;
359
+ }
360
+
361
+ /**
362
+ * @param {unknown[]} values
363
+ */
364
+ function slugList(values) {
365
+ return values.length === 0
366
+ ? '[] as const'
367
+ : `[${values.map((value) => `'${value}'`).join(', ')}] as const`;
368
+ }
369
+
370
+ /**
371
+ * @param {Record<string, unknown>} config
372
+ * @returns {{ slug: string, indexPath: string, articlePath: string }[]}
373
+ */
374
+ function articleRouteRecords(config) {
375
+ const articles = typeof config.articlesSlug === 'string' ? config.articlesSlug : '';
376
+ const types = Array.isArray(config.articleTypes) ? config.articleTypes : [];
377
+ const tagInPath = config.tagInPath === true;
378
+ return types.map((type) => {
379
+ const route = articleTypeRoute(type, config);
380
+ if (tagInPath) {
381
+ const path = categoryPath(config)
382
+ ? `/${route.slug}/`
383
+ : `/${underPrefix(articles, route.slug)}/`;
384
+ return { slug: route.slug, indexPath: path, articlePath: path };
385
+ }
386
+ const indexPath = `/${underPrefix(articles, route.indexSlug)}/`;
387
+ const articlePath = `/${underPrefix(articles, route.slug)}/`;
388
+ return { slug: route.slug, indexPath, articlePath };
389
+ });
390
+ }
391
+
392
+ /**
393
+ * @param {Record<string, unknown>} config
394
+ */
395
+ export function renderMarketingSlugs(config) {
396
+ const people = typeof config.peopleSlug === 'string' ? config.peopleSlug : '';
397
+ const tags = typeof config.tagsSlug === 'string' ? config.tagsSlug : '';
398
+ const articles = typeof config.articlesSlug === 'string' ? config.articlesSlug : '';
399
+ const personTypes = Array.isArray(config.personTypes) ? config.personTypes : [];
400
+ const tagTypes = Array.isArray(config.tagTypes) ? config.tagTypes : [];
401
+ const articleTypes = Array.isArray(config.articleTypes) ? config.articleTypes : [];
402
+ const articleSlugs = articleTypes.map((type) => articleTypeRoute(type, config).slug);
403
+ const routes = articleRouteRecords(config);
404
+ const routeLiteral =
405
+ routes.length === 0
406
+ ? '[] as const'
407
+ : `[\n${routes
408
+ .map(
409
+ (route) =>
410
+ ` { slug: '${route.slug}', indexPath: '${route.indexPath}', articlePath: '${route.articlePath}' },`,
411
+ )
412
+ .join('\n')}\n] as const`;
413
+ const base = (slug) => (slug ? `'/${slug}'` : "''");
414
+ return `${header()}
415
+ export const PEOPLE_SLUG = '${people}';
416
+ export const PEOPLE_BASE = ${base(people)};
417
+ export const TAGS_SLUG = '${tags}';
418
+ export const TAGS_BASE = ${base(tags)};
419
+ export const ARTICLES_SLUG = '${articles}';
420
+ export const ARTICLES_BASE = ${base(articles)};
421
+ export const PERSON_TYPE_SLUGS = ${slugList(personTypes)};
422
+ export const TAG_TYPE_SLUGS = ${slugList(tagTypes)};
423
+ export const ARTICLE_TYPE_SLUGS = ${slugList(articleSlugs)};
424
+ export const ARTICLE_TYPE_ROUTES = ${routeLiteral};
425
+ `;
426
+ }
427
+
428
+ export function renderMarkdownNegotiation() {
429
+ return `${header()}
430
+ /**
431
+ * The only content rewrite. \`src/proxy.ts\` imports \`resolveMarkdownNegotiationPath\`
432
+ * from this module. Do not add a second Accept: text/markdown rewrite.
433
+ * Trailing-slash 308 and the Contentful preview \`redirect()\` are framework
434
+ * behaviour. CMS content redirects stay the map in \`redirects.ts\`.
435
+ */
436
+ export { resolveMarkdownNegotiationPath } from '@se-studio/core-ui';
437
+ `;
438
+ }
439
+
440
+ /**
441
+ * @param {string} appRoot
442
+ * @param {{ write?: boolean, force?: boolean }} [options]
443
+ */
444
+ export function syncGeneratedRoutes(appRoot, options = {}) {
445
+ const config = readMarketingRoutes(appRoot);
446
+ if (!config) {
447
+ throw new Error(`No src/lib/marketing-routes.json under ${appRoot}`);
448
+ }
449
+ const files = renderGeneratedRoutes(config);
450
+ /** @type {string[]} */
451
+ const wrote = [];
452
+ /** @type {string[]} */
453
+ const skipped = [];
454
+ for (const [rest, contents] of files) {
455
+ for (const rel of destinationsForRest(appRoot, rest)) {
456
+ const abs = path.join(appRoot, rel);
457
+ if (fs.existsSync(abs) && !options.force) {
458
+ skipped.push(rel);
459
+ continue;
460
+ }
461
+ if (options.write) {
462
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
463
+ fs.writeFileSync(abs, contents);
464
+ wrote.push(rel);
465
+ }
466
+ }
467
+ }
468
+ /** @type {[string, string][]} */
469
+ const support = [
470
+ [FLAGS_REL, renderMarketingFlags(config)],
471
+ [MARKDOWN_NEGOTIATION_REL, renderMarkdownNegotiation()],
472
+ ];
473
+ if (isSectionConfig(config)) {
474
+ support.push([SLUGS_REL, renderMarketingSlugs(config)]);
475
+ }
476
+ for (const [rel, contents] of support) {
477
+ const abs = path.join(appRoot, rel);
478
+ if (fs.existsSync(abs) && !options.force) {
479
+ skipped.push(rel);
480
+ continue;
481
+ }
482
+ if (options.write) {
483
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
484
+ fs.writeFileSync(abs, contents);
485
+ wrote.push(rel);
486
+ }
487
+ }
488
+ /** @type {string[]} */
489
+ const removed = [];
490
+ if (options.write && isSectionConfig(config)) {
491
+ const live = new Set(files.keys());
492
+ for (const file of listCmsPageFiles(appRoot)) {
493
+ if (live.has(file.rest)) {
494
+ continue;
495
+ }
496
+ const abs = path.join(appRoot, file.rel);
497
+ const current = fs.readFileSync(abs, 'utf8');
498
+ if (!current.startsWith(GENERATED_MARK)) {
499
+ continue;
500
+ }
501
+ fs.unlinkSync(abs);
502
+ removed.push(file.rel);
503
+ removeEmptyParents(path.dirname(abs), path.join(appRoot, 'src/app'));
504
+ }
505
+ }
506
+ return { wrote, skipped, removed, count: files.size, tagSkips: tagRouteSkips(config) };
507
+ }
508
+
509
+ /**
510
+ * @param {string} dir
511
+ * @param {string} stopAt
512
+ */
513
+ function removeEmptyParents(dir, stopAt) {
514
+ let current = dir;
515
+ while (current.startsWith(stopAt) && current !== stopAt) {
516
+ if (fs.readdirSync(current).length > 0) {
517
+ return;
518
+ }
519
+ fs.rmdirSync(current);
520
+ current = path.dirname(current);
521
+ }
522
+ }
523
+
524
+ /**
525
+ * @param {string} appRoot
526
+ * @param {unknown} config
527
+ * @returns {string[]}
528
+ */
529
+ function generatedDrift(appRoot, config) {
530
+ /** @type {string[]} */
531
+ const drift = [];
532
+ let files;
533
+ try {
534
+ files = renderGeneratedRoutes(config);
535
+ } catch {
536
+ return drift;
537
+ }
538
+ const requireComplete = fs.existsSync(path.join(appRoot, FLAGS_REL));
539
+ for (const [rest, expected] of files) {
540
+ const rels = existingPageRels(appRoot, rest);
541
+ if (rels.length === 0 && requireComplete) {
542
+ drift.push(`missing generated (cms-routes)/${rest ? `${rest}/` : ''}page.ts`);
543
+ continue;
544
+ }
545
+ for (const rel of rels) {
546
+ const current = fs.readFileSync(path.join(appRoot, rel), 'utf8');
547
+ if (!current.startsWith(GENERATED_MARK)) {
548
+ continue;
549
+ }
550
+ if (current !== expected) {
551
+ drift.push(`${rel} was edited after generation`);
552
+ }
553
+ }
554
+ }
555
+ return drift;
556
+ }
557
+
558
+ /**
559
+ * @param {string} appRoot
560
+ * @param {unknown} config
561
+ * @returns {string[]}
562
+ */
563
+ function supportDrift(appRoot, config) {
564
+ /** @type {string[]} */
565
+ const drift = [];
566
+ const flagsAbs = path.join(appRoot, FLAGS_REL);
567
+ const expectsFlags = MARKETING_FLAG_NAMES.some(
568
+ (name) => config && typeof config === 'object' && name in config,
569
+ );
570
+ if (isSectionConfig(config)) {
571
+ const slugsAbs = path.join(appRoot, SLUGS_REL);
572
+ const expectedSlugs = renderMarketingSlugs(config);
573
+ if (!fs.existsSync(slugsAbs)) {
574
+ drift.push(`${SLUGS_REL} is missing`);
575
+ } else if (fs.readFileSync(slugsAbs, 'utf8') !== expectedSlugs) {
576
+ drift.push(`${SLUGS_REL} was edited after generation`);
577
+ }
578
+ }
579
+ if (expectsFlags || fs.existsSync(flagsAbs)) {
580
+ const expected = renderMarketingFlags(config);
581
+ if (!fs.existsSync(flagsAbs)) {
582
+ drift.push(`${FLAGS_REL} is missing`);
583
+ } else if (fs.readFileSync(flagsAbs, 'utf8') !== expected) {
584
+ drift.push(`${FLAGS_REL} was edited after generation`);
585
+ }
586
+ }
587
+ const markdownAbs = path.join(appRoot, MARKDOWN_NEGOTIATION_REL);
588
+ if (fs.existsSync(flagsAbs) || fs.existsSync(markdownAbs)) {
589
+ const expected = renderMarkdownNegotiation();
590
+ if (!fs.existsSync(markdownAbs)) {
591
+ drift.push(`${MARKDOWN_NEGOTIATION_REL} is missing`);
592
+ } else if (fs.readFileSync(markdownAbs, 'utf8') !== expected) {
593
+ drift.push(`${MARKDOWN_NEGOTIATION_REL} was edited after generation`);
594
+ }
595
+ }
596
+ return drift;
597
+ }
598
+
599
+ /**
600
+ * Bracket CMS routes in route-build-policy.json must be the generated tree.
601
+ *
602
+ * @param {string} appRoot
603
+ * @param {Set<string>} allowed
604
+ * @returns {string[]}
605
+ */
606
+ function policyProblems(appRoot, allowed) {
607
+ const policyPath = path.join(appRoot, 'route-build-policy.json');
608
+ if (!fs.existsSync(policyPath)) {
609
+ return [];
610
+ }
611
+ let policy;
612
+ try {
613
+ policy = JSON.parse(fs.readFileSync(policyPath, 'utf8'));
614
+ } catch (error) {
615
+ const message = error instanceof Error ? error.message : String(error);
616
+ return [`route-build-policy.json: ${message}`];
617
+ }
618
+ const must = new Set(Array.isArray(policy.mustBeSsgOrStatic) ? policy.mustBeSsgOrStatic : []);
619
+ /** @type {string[]} */
620
+ const problems = [];
621
+ for (const rest of allowed) {
622
+ if (!rest.includes('[')) {
623
+ continue;
624
+ }
625
+ const route = `/${rest}`;
626
+ if (!must.has(route)) {
627
+ problems.push(`route-build-policy.json missing ${route}`);
628
+ }
629
+ }
630
+ for (const route of must) {
631
+ if (typeof route !== 'string' || !route.startsWith('/') || route.includes('.')) {
632
+ continue;
633
+ }
634
+ const rest = route.slice(1);
635
+ if (!allowed.has(rest)) {
636
+ problems.push(`route-build-policy.json lists ${route} outside marketing-routes.json`);
637
+ }
638
+ }
639
+ return problems;
640
+ }
641
+
642
+ /**
643
+ * @param {string} appRoot
644
+ * @returns {string[]}
645
+ */
646
+ function proxyMarkdownProblems(appRoot) {
647
+ const proxyPath = path.join(appRoot, 'src/proxy.ts');
648
+ if (!fs.existsSync(proxyPath)) {
649
+ return [];
650
+ }
651
+ const text = fs.readFileSync(proxyPath, 'utf8');
652
+ /** @type {string[]} */
653
+ const problems = [];
654
+ if (!text.includes("from '@/generated/markdown-negotiation'")) {
655
+ problems.push(
656
+ 'src/proxy.ts must import the markdown rewrite from @/generated/markdown-negotiation',
657
+ );
658
+ }
659
+ const coreImport = text.match(/import\s*\{[^}]*\}\s*from\s*'@se-studio\/core-ui'/);
660
+ if (coreImport?.[0]?.includes('resolveMarkdownNegotiationPath')) {
661
+ problems.push(
662
+ 'src/proxy.ts imports resolveMarkdownNegotiationPath from @se-studio/core-ui; use the generated module',
663
+ );
664
+ }
665
+ return problems;
666
+ }
667
+
668
+ /**
669
+ * @param {Set<string>} allowed
670
+ * @param {Record<string, unknown>} config
671
+ */
672
+ /**
673
+ * Category in the path, with no articles prefix. The article type slug is the
674
+ * public path (`resources/news`). Flat mode (Eagle) stays one segment.
675
+ *
676
+ * @param {Record<string, unknown>} config
677
+ */
678
+ function categoryPath(config) {
679
+ const articles = typeof config.articlesSlug === 'string' ? config.articlesSlug : '';
680
+ return config.tagInPath === true && articles.length === 0;
681
+ }
682
+
683
+ /**
684
+ * @param {unknown} type
685
+ * @param {Record<string, unknown>} [config]
686
+ * @returns {{ slug: string, indexSlug: string }}
687
+ */
688
+ function articleTypeRoute(type, config = {}) {
689
+ const category = categoryPath(config);
690
+ if (typeof type === 'string') {
691
+ const slug = category
692
+ ? requireRoutePath(type, 'articleTypes')
693
+ : requireSegment(type, 'articleTypes');
694
+ return { slug, indexSlug: slug };
695
+ }
696
+ const slug = category
697
+ ? requireRoutePath(type?.slug, 'articleTypes.slug')
698
+ : requireSegment(type?.slug, 'articleTypes.slug');
699
+ const rawIndex =
700
+ typeof type?.indexSlug === 'string' && type.indexSlug.length > 0 ? type.indexSlug : slug;
701
+ if (category && rawIndex !== slug) {
702
+ throw new Error(
703
+ `${slug} indexSlug must equal the article type slug when the category is in the path`,
704
+ );
705
+ }
706
+ return {
707
+ slug,
708
+ indexSlug: category ? slug : requireSegment(rawIndex, 'articleTypes.indexSlug'),
709
+ };
710
+ }
711
+
712
+ /**
713
+ * @param {string} prefix
714
+ * @param {string} segment
715
+ */
716
+ function underPrefix(prefix, segment) {
717
+ return prefix ? `${prefix}/${segment}` : segment;
718
+ }
719
+
720
+ function addSectionRests(allowed, config) {
721
+ const people = typeof config.peopleSlug === 'string' ? config.peopleSlug : '';
722
+ const tags = typeof config.tagsSlug === 'string' ? config.tagsSlug : '';
723
+ const articles = typeof config.articlesSlug === 'string' ? config.articlesSlug : '';
724
+ if (people) {
725
+ allowed.add(people);
726
+ allowed.add(`${people}/[person]`);
727
+ }
728
+ for (const type of config.personTypes ?? []) {
729
+ const segment = requireSegment(type, 'personTypes');
730
+ const rest = underPrefix(people, segment);
731
+ allowed.add(rest);
732
+ allowed.add(`${rest}/[person]`);
733
+ }
734
+ if (tags) {
735
+ allowed.add(tags);
736
+ allowed.add(`${tags}/[tag]`);
737
+ }
738
+ for (const type of config.tagTypes ?? []) {
739
+ const segment = requireSegment(type, 'tagTypes');
740
+ const rest = underPrefix(tags, segment);
741
+ allowed.add(rest);
742
+ allowed.add(`${rest}/[tag]`);
743
+ }
744
+ if (categoryPath(config)) {
745
+ for (const type of config.articleTypes ?? []) {
746
+ const route = articleTypeRoute(type, config);
747
+ allowed.add(route.slug);
748
+ allowed.add(`${route.slug}/[tag]`);
749
+ allowed.add(`${route.slug}/[tag]/[...slugs]`);
750
+ }
751
+ return;
752
+ }
753
+ if (config.tagInPath === true) {
754
+ if (!articles) {
755
+ throw new Error('tagInPath needs an articles custom type prefix');
756
+ }
757
+ allowed.add(articles);
758
+ allowed.add(`${articles}/[articleType]`);
759
+ allowed.add(`${articles}/[articleType]/[...slugs]`);
760
+ allowed.add(`${articles}/[articleType]/[tag]`);
761
+ allowed.add(`${articles}/[articleType]/[tag]/[...slugs]`);
762
+ return;
763
+ }
764
+ if (articles) {
765
+ allowed.add(articles);
766
+ }
767
+ for (const type of config.articleTypes ?? []) {
768
+ const route = articleTypeRoute(type, config);
769
+ const indexRest = underPrefix(articles, route.indexSlug);
770
+ const articleRest = underPrefix(articles, route.slug);
771
+ allowed.add(indexRest);
772
+ allowed.add(`${articleRest}/[article]`);
773
+ }
774
+ }
775
+
776
+ /**
777
+ * @param {Record<string, unknown>} config
778
+ * @param {Map<string, string>} files
779
+ */
780
+ function renderSectionRoutes(config, files) {
781
+ const people = typeof config.peopleSlug === 'string' ? config.peopleSlug : '';
782
+ const tags = typeof config.tagsSlug === 'string' ? config.tagsSlug : '';
783
+ const articles = typeof config.articlesSlug === 'string' ? config.articlesSlug : '';
784
+ if (people) {
785
+ const segment = requireSegment(people, 'peopleSlug');
786
+ files.set(segment, peopleIndexPage(segment));
787
+ files.set(`${segment}/[person]`, untypedPersonPage(segment));
788
+ }
789
+ for (const type of config.personTypes ?? []) {
790
+ const segment = requireSegment(type, 'personTypes');
791
+ const rest = underPrefix(people, segment);
792
+ files.set(rest, topPersonTypeIndex(rest, segment));
793
+ files.set(`${rest}/[person]`, topPersonTypePerson(rest, segment));
794
+ }
795
+ if (tags) {
796
+ const segment = requireSegment(tags, 'tagsSlug');
797
+ files.set(segment, sectionTagsIndex(segment));
798
+ files.set(`${segment}/[tag]`, sectionTagPage(segment));
799
+ }
800
+ for (const type of config.tagTypes ?? []) {
801
+ const segment = requireSegment(type, 'tagTypes');
802
+ const rest = underPrefix(tags, segment);
803
+ files.set(rest, tagTypeIndexPage(rest, segment));
804
+ files.set(`${rest}/[tag]`, tagTypeTagPage(rest));
805
+ }
806
+ if (categoryPath(config)) {
807
+ for (const type of config.articleTypes ?? []) {
808
+ const route = articleTypeRoute(type, config);
809
+ files.set(route.slug, concreteArticleTypeIndex(route.slug, route.slug));
810
+ files.set(`${route.slug}/[tag]`, fixedArticleTag(route.slug));
811
+ files.set(`${route.slug}/[tag]/[...slugs]`, fixedArticleTagDetail(route.slug));
812
+ }
813
+ return;
814
+ }
815
+ if (config.tagInPath === true) {
816
+ if (!articles) {
817
+ throw new Error('tagInPath needs an articles custom type prefix');
818
+ }
819
+ const segment = requireSegment(articles, 'articlesSlug');
820
+ files.set(segment, dynamicArticleIndex(segment));
821
+ files.set(`${segment}/[articleType]`, dynamicArticleType(segment));
822
+ files.set(`${segment}/[articleType]/[...slugs]`, dynamicArticleDetail(segment));
823
+ files.set(`${segment}/[articleType]/[tag]`, dynamicArticleTag(segment));
824
+ files.set(`${segment}/[articleType]/[tag]/[...slugs]`, dynamicArticleTagDetail(segment));
825
+ return;
826
+ }
827
+ if (articles) {
828
+ const segment = requireSegment(articles, 'articlesSlug');
829
+ files.set(segment, dynamicArticleIndex(segment));
830
+ }
831
+ for (const type of config.articleTypes ?? []) {
832
+ const route = articleTypeRoute(type, config);
833
+ const indexRest = underPrefix(articles, route.indexSlug);
834
+ const articleRest = underPrefix(articles, route.slug);
835
+ files.set(indexRest, concreteArticleTypeIndex(indexRest, route.slug));
836
+ files.set(`${articleRest}/[article]`, concreteArticlePage(articleRest, route.slug));
837
+ }
838
+ }
839
+
840
+ /**
841
+ * Person type index. `rest` may include a person custom-type prefix.
842
+ *
843
+ * @param {string} rest
844
+ * @param {string} type
845
+ */
846
+ function topPersonTypeIndex(rest, type) {
847
+ const props = `PageProps<'/${rest}'>`;
848
+ const routePath = `/${rest}/`;
849
+ const metadata = openFn('export async function generateMetadata', [
850
+ `_props: ${props}`,
851
+ 'parent: ResolvingMetadata',
852
+ ]);
853
+ const page = openFn('export default async function ', [`_props: ${props}`]);
854
+ return `${header()}import type { ResolvingMetadata } from 'next';
855
+ import { notFound } from 'next/navigation';
856
+ import { enablePerson } from '@/generated/marketing-flags';
857
+ import {
858
+ generatePersonTypeIndexMetadata,
859
+ generatePersonTypeIndexPage,
860
+ } from '@/lib/route-handlers';
861
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
862
+
863
+ const PERSON_TYPE = '${type}';
864
+ const PATH = '${routePath}';
865
+
866
+ export function generateStaticParams() {
867
+ return [];
868
+ }
869
+
870
+ ${metadata}
871
+ if (!enablePerson) {
872
+ return {};
873
+ }
874
+ return await generatePersonTypeIndexMetadata(PERSON_TYPE, PATH, DEFAULT_ROUTE_CONFIG, parent);
875
+ }
876
+
877
+ ${page}
878
+ if (!enablePerson) {
879
+ notFound();
880
+ }
881
+ return await generatePersonTypeIndexPage(PERSON_TYPE, PATH, DEFAULT_ROUTE_CONFIG);
882
+ }
883
+ `;
884
+ }
885
+
886
+ /**
887
+ * @param {string} rest
888
+ * @param {string} _type
889
+ */
890
+ function topPersonTypePerson(rest, _type) {
891
+ const props = `PageProps<'/${rest}/[person]'>`;
892
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
893
+ const metadata = openFn('export async function generateMetadata', [
894
+ `props: ${props}`,
895
+ 'parent: ResolvingMetadata',
896
+ ]);
897
+ const page = openFn('export default async function ', [`props: ${props}`]);
898
+ return `${header()}import type { ResolvingMetadata } from 'next';
899
+ import { notFound } from 'next/navigation';
900
+ import { enablePerson } from '@/generated/marketing-flags';
901
+ import { generatePersonMetadata, generatePersonPage } from '@/lib/route-handlers';
902
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
903
+
904
+ export function generateStaticParams() {
905
+ return [];
906
+ }
907
+
908
+ ${extract}
909
+ const params = await props.params;
910
+ const { person } = params;
911
+ return { person, path: \`/${rest}/\${person}/\` };
912
+ }
913
+
914
+ ${metadata}
915
+ if (!enablePerson) {
916
+ return {};
917
+ }
918
+ const { person, path } = await extractDetails(props);
919
+ return await generatePersonMetadata(person, path, DEFAULT_ROUTE_CONFIG, parent);
920
+ }
921
+
922
+ ${page}
923
+ if (!enablePerson) {
924
+ notFound();
925
+ }
926
+ const { person, path } = await extractDetails(props);
927
+ return await generatePersonPage(person, path, DEFAULT_ROUTE_CONFIG);
928
+ }
929
+ `;
930
+ }
931
+
932
+ /**
933
+ * @param {string} rest
934
+ * @param {string} type
935
+ */
936
+ function tagTypeIndexPage(rest, type) {
937
+ const props = `PageProps<'/${rest}'>`;
938
+ const routePath = `/${rest}/`;
939
+ const metadata = openFn('export async function generateMetadata', [
940
+ `_props: ${props}`,
941
+ 'parent: ResolvingMetadata',
942
+ ]);
943
+ const page = openFn('export default async function ', [`_props: ${props}`]);
944
+ return `${header()}import type { ResolvingMetadata } from 'next';
945
+ import { generateTagTypeMetadata, generateTagTypePage } from '@/lib/route-handlers';
946
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
947
+
948
+ const TAG_TYPE = '${type}';
949
+ const PATH = '${routePath}';
950
+
951
+ export function generateStaticParams() {
952
+ return [];
953
+ }
954
+
955
+ ${metadata}
956
+ return await generateTagTypeMetadata(TAG_TYPE, PATH, DEFAULT_ROUTE_CONFIG, parent);
957
+ }
958
+
959
+ ${page}
960
+ return await generateTagTypePage(TAG_TYPE, PATH, DEFAULT_ROUTE_CONFIG);
961
+ }
962
+ `;
963
+ }
964
+
965
+ /**
966
+ * Tag page under a tag type. The path is the route, not the tag calculator.
967
+ *
968
+ * @param {string} rest
969
+ */
970
+ function tagTypeTagPage(rest) {
971
+ const props = `PageProps<'/${rest}/[tag]'>`;
972
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
973
+ const metadata = openFn('export async function generateMetadata', [
974
+ `props: ${props}`,
975
+ 'parent: ResolvingMetadata',
976
+ ]);
977
+ const page = openFn('export default async function ', [`props: ${props}`]);
978
+ return `${header()}import type { ResolvingMetadata } from 'next';
979
+ import { generateTagMetadata, generateTagPage } from '@/lib/route-handlers';
980
+ import { TAG_LISTING_ROUTE_CONFIG } from '@/lib/routeConfig';
981
+
982
+ export function generateStaticParams() {
983
+ return [];
984
+ }
985
+
986
+ ${extract}
987
+ const params = await props.params;
988
+ const { tag } = params;
989
+ return { tagSlug: tag, path: \`/${rest}/\${tag}/\` };
990
+ }
991
+
992
+ ${metadata}
993
+ const { tagSlug, path } = await extractDetails(props);
994
+ return await generateTagMetadata(tagSlug, path, TAG_LISTING_ROUTE_CONFIG, parent);
995
+ }
996
+
997
+ ${page}
998
+ const { tagSlug, path } = await extractDetails(props);
999
+ return await generateTagPage(tagSlug, path, TAG_LISTING_ROUTE_CONFIG);
1000
+ }
1001
+ `;
1002
+ }
1003
+
1004
+ /**
1005
+ * Article type index. The handler is called with the type slug, not the index slug.
1006
+ *
1007
+ * @param {string} rest
1008
+ * @param {string} typeSlug
1009
+ */
1010
+ function concreteArticleTypeIndex(rest, typeSlug) {
1011
+ const props = `PageProps<'/${rest}'>`;
1012
+ const routePath = `/${rest}/`;
1013
+ const metadata = openFn('export async function generateMetadata', [
1014
+ `_props: ${props}`,
1015
+ 'parent: ResolvingMetadata',
1016
+ ]);
1017
+ const page = openFn('export default async function ', [`_props: ${props}`]);
1018
+ return `${header()}import type { ResolvingMetadata } from 'next';
1019
+ import { generateArticleTypeMetadata, generateArticleTypePage } from '@/lib/route-handlers';
1020
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1021
+
1022
+ const ARTICLE_TYPE = '${typeSlug}';
1023
+ const PATH = '${routePath}';
1024
+
1025
+ export function generateStaticParams() {
1026
+ return [];
1027
+ }
1028
+
1029
+ ${metadata}
1030
+ return await generateArticleTypeMetadata(ARTICLE_TYPE, PATH, DEFAULT_ROUTE_CONFIG, parent);
1031
+ }
1032
+
1033
+ ${page}
1034
+ return await generateArticleTypePage(ARTICLE_TYPE, PATH, DEFAULT_ROUTE_CONFIG);
1035
+ }
1036
+ `;
1037
+ }
1038
+
1039
+ /**
1040
+ * @param {string} rest directory of the article, without `[article]`
1041
+ * @param {string} typeSlug
1042
+ */
1043
+ function concreteArticlePage(rest, typeSlug) {
1044
+ const props = `PageProps<'/${rest}/[article]'>`;
1045
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
1046
+ const metadata = openFn('export async function generateMetadata', [
1047
+ `props: ${props}`,
1048
+ 'parent: ResolvingMetadata',
1049
+ ]);
1050
+ const page = openFn('export default async function ', [`props: ${props}`]);
1051
+ return `${header()}import type { ResolvingMetadata } from 'next';
1052
+ import { generateArticleMetadata, generateArticlePage } from '@/lib/route-handlers';
1053
+ import { ARTICLE_DETAIL_ROUTE_CONFIG } from '@/lib/routeConfig';
1054
+
1055
+ const ARTICLE_TYPE = '${typeSlug}';
1056
+
1057
+ export function generateStaticParams() {
1058
+ return [];
1059
+ }
1060
+
1061
+ ${extract}
1062
+ const params = await props.params;
1063
+ const { article } = params;
1064
+ return { articleSlug: article, path: \`/${rest}/\${article}/\` };
1065
+ }
1066
+
1067
+ ${metadata}
1068
+ const { articleSlug, path } = await extractDetails(props);
1069
+ return await generateArticleMetadata(
1070
+ ARTICLE_TYPE,
1071
+ articleSlug,
1072
+ path,
1073
+ ARTICLE_DETAIL_ROUTE_CONFIG,
1074
+ parent,
1075
+ );
1076
+ }
1077
+
1078
+ ${page}
1079
+ const { articleSlug, path } = await extractDetails(props);
1080
+ return await generateArticlePage(ARTICLE_TYPE, articleSlug, path, ARTICLE_DETAIL_ROUTE_CONFIG);
1081
+ }
1082
+ `;
1083
+ }
1084
+
1085
+ /**
1086
+ * @param {string} segment
1087
+ */
1088
+ function sectionTagsIndex(segment) {
1089
+ const props = `PageProps<'/${segment}'>`;
1090
+ const metadata = openFn('export function generateMetadata', [
1091
+ `_props: ${props}`,
1092
+ 'parent: ResolvingMetadata',
1093
+ ]);
1094
+ const page = openFn('export default function ', [`_props: ${props}`]);
1095
+ return `${header()}import type { ResolvingMetadata } from 'next';
1096
+ import { TAGS_BASE } from '@/lib/constants';
1097
+ import { generateTagsIndexMetadata, generateTagsIndexPage } from '@/lib/route-handlers';
1098
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1099
+
1100
+ export function generateStaticParams() {
1101
+ return [];
1102
+ }
1103
+
1104
+ ${metadata}
1105
+ return generateTagsIndexMetadata(TAGS_BASE, DEFAULT_ROUTE_CONFIG, parent);
1106
+ }
1107
+
1108
+ ${page}
1109
+ return generateTagsIndexPage(TAGS_BASE, DEFAULT_ROUTE_CONFIG);
1110
+ }
1111
+ `;
1112
+ }
1113
+
1114
+ /**
1115
+ * @param {string} segment
1116
+ */
1117
+ function sectionTagPage(segment) {
1118
+ const props = `PageProps<'/${segment}/[tag]'>`;
1119
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
1120
+ const metadata = openFn('export async function generateMetadata', [
1121
+ `props: ${props}`,
1122
+ 'parent: ResolvingMetadata',
1123
+ ]);
1124
+ const page = openFn('export default async function ', [`props: ${props}`]);
1125
+ return `${header()}import type { ResolvingMetadata } from 'next';
1126
+ import { converterContext } from '@/lib/converter-context';
1127
+ import { generateTagMetadata, generateTagPage } from '@/lib/route-handlers';
1128
+ import { TAG_LISTING_ROUTE_CONFIG } from '@/lib/routeConfig';
1129
+
1130
+ export function generateStaticParams() {
1131
+ return [];
1132
+ }
1133
+
1134
+ ${extract}
1135
+ const params = await props.params;
1136
+ const { tag } = params;
1137
+ return { tagSlug: tag, path: converterContext.urlCalculators.tag(tag) };
1138
+ }
1139
+
1140
+ ${metadata}
1141
+ const { tagSlug, path } = await extractDetails(props);
1142
+ return await generateTagMetadata(tagSlug, path, TAG_LISTING_ROUTE_CONFIG, parent);
1143
+ }
1144
+
1145
+ ${page}
1146
+ const { tagSlug, path } = await extractDetails(props);
1147
+ return await generateTagPage(tagSlug, path, TAG_LISTING_ROUTE_CONFIG);
1148
+ }
1149
+ `;
1150
+ }
1151
+
1152
+ /**
1153
+ * Named person types on a people base. An empty list writes no named folders.
1154
+ * Every people base also writes `[person]`. Typed people are one `peopleType/` tree.
1155
+ *
1156
+ * @param {unknown} base
1157
+ * @returns {string[]}
1158
+ */
1159
+ function personTypeNames(base) {
1160
+ if (!Array.isArray(base?.types)) {
1161
+ return [];
1162
+ }
1163
+ /** @type {Set<string>} */
1164
+ const seen = new Set();
1165
+ return base.types.map((type) => {
1166
+ const segment = requireSegment(type, 'personBases.types');
1167
+ if (seen.has(segment)) {
1168
+ throw new Error(`personBases.types lists "${segment}" twice`);
1169
+ }
1170
+ seen.add(segment);
1171
+ return segment;
1172
+ });
1173
+ }
1174
+
1175
+ /**
1176
+ * @param {string} segment
1177
+ */
1178
+ function isRouteGroup(segment) {
1179
+ return /^\([^)/]+\)$/.test(segment);
1180
+ }
1181
+
1182
+ /**
1183
+ * Prefix through `(cms-routes)/` and any route groups nested directly inside it.
1184
+ *
1185
+ * @param {string} rel
1186
+ * @returns {string|null}
1187
+ */
1188
+ function cmsPagePrefix(rel) {
1189
+ const marker = '(cms-routes)/';
1190
+ const idx = rel.indexOf(marker);
1191
+ if (idx === -1) {
1192
+ return null;
1193
+ }
1194
+ const groups = [];
1195
+ for (const segment of rel.slice(idx + marker.length).split('/')) {
1196
+ if (!isRouteGroup(segment)) {
1197
+ break;
1198
+ }
1199
+ groups.push(segment);
1200
+ }
1201
+ const nested = groups.length > 0 ? `${groups.join('/')}/` : '';
1202
+ return `${rel.slice(0, idx + marker.length)}${nested}`;
1203
+ }
1204
+
1205
+ /**
1206
+ * @param {string} appRoot
1207
+ * @returns {{ rel: string, rest: string }[]}
1208
+ */
1209
+ function listCmsPageFiles(appRoot) {
1210
+ /** @type {{ rel: string, rest: string }[]} */
1211
+ const files = [];
1212
+ const appDir = path.join(appRoot, 'src/app');
1213
+ if (!fs.existsSync(appDir)) {
1214
+ return files;
1215
+ }
1216
+ walk(appDir, (file) => {
1217
+ const base = path.basename(file);
1218
+ if (base !== 'page.ts' && base !== 'page.tsx') {
1219
+ return;
1220
+ }
1221
+ const rel = path.relative(appRoot, file).split(path.sep).join('/');
1222
+ if (rel.includes('/(cms-dev)/') || rel.startsWith('src/app/(cms-dev)/')) {
1223
+ return;
1224
+ }
1225
+ if (isPreviewPage(rel)) {
1226
+ return;
1227
+ }
1228
+ const rest = routeRestFromRel(rel);
1229
+ if (rest === null) {
1230
+ return;
1231
+ }
1232
+ files.push({ rel, rest });
1233
+ });
1234
+ return files;
1235
+ }
1236
+
1237
+ /**
1238
+ * @param {string} appRoot
1239
+ * @param {string} rest
1240
+ * @returns {string[]}
1241
+ */
1242
+ function existingPageRels(appRoot, rest) {
1243
+ return listCmsPageFiles(appRoot)
1244
+ .filter((file) => file.rest === rest)
1245
+ .map((file) => file.rel);
1246
+ }
1247
+
1248
+ /**
1249
+ * Trees that already serve CMS pages. A bare `src/app/(cms-routes)/` is not
1250
+ * added when the site uses `(default)` or an inner group: that file is a
1251
+ * second copy of the same URL.
1252
+ *
1253
+ * @param {string[]} prefixes
1254
+ */
1255
+ function preferExistingTrees(prefixes) {
1256
+ let next = prefixes;
1257
+ if (next.some((prefix) => prefix.includes('/(default)/'))) {
1258
+ next = next.filter(
1259
+ (prefix) => prefix.includes('/(default)/') || !prefix.startsWith('src/app/(cms-routes)/'),
1260
+ );
1261
+ }
1262
+ if (next.some((prefix) => prefix.startsWith('src/app/(cms-routes)/('))) {
1263
+ next = next.filter((prefix) => prefix !== 'src/app/(cms-routes)/');
1264
+ }
1265
+ return next;
1266
+ }
1267
+
1268
+ /**
1269
+ * @param {string} appRoot
1270
+ * @returns {string[]}
1271
+ */
1272
+ function writePrefixes(appRoot) {
1273
+ const fromPages = [
1274
+ ...new Set(listCmsPageFiles(appRoot).map((file) => cmsPagePrefix(file.rel)).filter(Boolean)),
1275
+ ];
1276
+ if (fromPages.length > 0) {
1277
+ return preferExistingTrees(fromPages);
1278
+ }
1279
+ const fromDirs = findCmsRouteDirs(appRoot).map((dir) => prefixFromCmsDir(appRoot, dir));
1280
+ if (fromDirs.length > 0) {
1281
+ return preferExistingTrees(fromDirs);
1282
+ }
1283
+ return ['src/app/(cms-routes)/'];
1284
+ }
1285
+
1286
+ /**
1287
+ * @param {string} appRoot
1288
+ * @returns {string[]} absolute directories
1289
+ */
1290
+ function findCmsRouteDirs(appRoot) {
1291
+ /** @type {string[]} */
1292
+ const found = [];
1293
+ const appDir = path.join(appRoot, 'src/app');
1294
+ if (!fs.existsSync(appDir)) {
1295
+ return found;
1296
+ }
1297
+ const visit = (dir) => {
1298
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
1299
+ if (!entry.isDirectory()) {
1300
+ continue;
1301
+ }
1302
+ const full = path.join(dir, entry.name);
1303
+ if (entry.name === '(cms-routes)') {
1304
+ found.push(full);
1305
+ continue;
1306
+ }
1307
+ visit(full);
1308
+ }
1309
+ };
1310
+ visit(appDir);
1311
+ return found;
1312
+ }
1313
+
1314
+ /**
1315
+ * @param {string} appRoot
1316
+ * @param {string} absDir
1317
+ */
1318
+ function prefixFromCmsDir(appRoot, absDir) {
1319
+ let rel = `${path.relative(appRoot, absDir).split(path.sep).join('/')}/`;
1320
+ const groups = fs
1321
+ .readdirSync(absDir, { withFileTypes: true })
1322
+ .filter((entry) => entry.isDirectory() && isRouteGroup(entry.name))
1323
+ .map((entry) => entry.name);
1324
+ if (groups.length === 1) {
1325
+ rel += `${groups[0]}/`;
1326
+ }
1327
+ return rel;
1328
+ }
1329
+
1330
+ /**
1331
+ * @param {string} prefix
1332
+ * @param {string} rest
1333
+ */
1334
+ function pageRel(prefix, rest) {
1335
+ return rest ? `${prefix}${rest}/page.ts` : `${prefix}page.ts`;
1336
+ }
1337
+
1338
+ /**
1339
+ * Path before `(cms-routes)/`, with route groups removed. `(default)`, a bare
1340
+ * `(cms-routes)`, and `(with-chrome)` share one slot. A locale prefix does not.
1341
+ *
1342
+ * @param {string} rel
1343
+ */
1344
+ function urlSlot(rel) {
1345
+ const marker = '(cms-routes)/';
1346
+ const idx = rel.indexOf(marker);
1347
+ const before = idx === -1 ? rel : rel.slice(0, idx);
1348
+ return `${before
1349
+ .split('/')
1350
+ .filter((segment) => segment.length > 0 && !isRouteGroup(segment))
1351
+ .join('/')}/`;
1352
+ }
1353
+
1354
+ /**
1355
+ * One destination per serving tree. An existing page covers its own URL slot
1356
+ * only, so a default-locale file does not skip `es-US`. A new sibling stays
1357
+ * next to an article file that already lives in that slot.
1358
+ *
1359
+ * @param {string} appRoot
1360
+ * @param {string} rest
1361
+ * @returns {string[]}
1362
+ */
1363
+ function destinationsForRest(appRoot, rest) {
1364
+ const existing = existingPageRels(appRoot, rest);
1365
+ /** @type {string[]} */
1366
+ const dest = [];
1367
+ const seen = new Set();
1368
+ for (const prefix of writePrefixes(appRoot)) {
1369
+ const slot = urlSlot(prefix);
1370
+ const onSlot = existing.filter((rel) => urlSlot(rel) === slot);
1371
+ const chosen =
1372
+ onSlot.length > 0
1373
+ ? onSlot
1374
+ : [pageRel(siblingPrefix(appRoot, rest, slot) ?? prefix, rest)];
1375
+ for (const rel of chosen) {
1376
+ if (seen.has(rel)) {
1377
+ continue;
1378
+ }
1379
+ seen.add(rel);
1380
+ dest.push(rel);
1381
+ }
1382
+ }
1383
+ return dest;
1384
+ }
1385
+
1386
+ /**
1387
+ * @param {string} appRoot
1388
+ * @param {string} rest
1389
+ * @param {string} slot
1390
+ * @returns {string|null}
1391
+ */
1392
+ function siblingPrefix(appRoot, rest, slot) {
1393
+ const base = rest.split('/')[0];
1394
+ if (!base) {
1395
+ return null;
1396
+ }
1397
+ const sibling = listCmsPageFiles(appRoot).find(
1398
+ (file) =>
1399
+ urlSlot(file.rel) === slot && (file.rest === base || file.rest.startsWith(`${base}/`)),
1400
+ );
1401
+ return sibling ? cmsPagePrefix(sibling.rel) : null;
1402
+ }
1403
+
1404
+ /**
1405
+ * @param {unknown} value
1406
+ * @param {string} label
1407
+ */
1408
+ function requireSegment(value, label) {
1409
+ if (typeof value !== 'string' || !SEGMENT.test(value)) {
1410
+ throw new Error(`${label} must be a single lowercase segment`);
1411
+ }
1412
+ return value;
1413
+ }
1414
+
1415
+ /**
1416
+ * @param {unknown} value
1417
+ * @param {string} label
1418
+ */
1419
+ function requireRoutePath(value, label) {
1420
+ if (typeof value !== 'string' || value.length === 0) {
1421
+ throw new Error(`${label} must be a path of lowercase segments`);
1422
+ }
1423
+ const parts = value.split('/');
1424
+ if (parts.some((part) => !SEGMENT.test(part))) {
1425
+ throw new Error(`${label} must be a path of lowercase segments`);
1426
+ }
1427
+ return value;
1428
+ }
1429
+
1430
+ /**
1431
+ * @param {string} dir
1432
+ * @param {(file: string) => void} visit
1433
+ */
1434
+ function walk(dir, visit) {
1435
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
1436
+ const full = path.join(dir, entry.name);
1437
+ if (entry.isDirectory()) {
1438
+ walk(full, visit);
1439
+ } else {
1440
+ visit(full);
1441
+ }
1442
+ }
1443
+ }
1444
+
1445
+ function header() {
1446
+ return `${GENERATED_MARK}\n`;
1447
+ }
1448
+
1449
+ function homePage() {
1450
+ return `${header()}import type { ResolvingMetadata } from 'next';
1451
+ import { generatePage, generatePageMetadata } from '@/lib/route-handlers';
1452
+ import { getPageRouteConfig } from '@/lib/routeConfig';
1453
+
1454
+ export function generateMetadata(_props: PageProps<'/'>, parent: ResolvingMetadata) {
1455
+ return generatePageMetadata('index', '/', getPageRouteConfig('index'), parent);
1456
+ }
1457
+
1458
+ export default function (_props: PageProps<'/'>) {
1459
+ return generatePage('index', '/', getPageRouteConfig('index'));
1460
+ }
1461
+ `;
1462
+ }
1463
+
1464
+ function levelPage() {
1465
+ const props = "PageProps<'/[level1]'>";
1466
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
1467
+ const metadata = openFn('export async function generateMetadata', [
1468
+ `props: ${props}`,
1469
+ 'parent: ResolvingMetadata',
1470
+ ]);
1471
+ const page = openFn('export default async function ', [`props: ${props}`]);
1472
+ return `${header()}import { joinCmsPathSegments } from '@se-studio/core-ui';
1473
+ import type { ResolvingMetadata } from 'next';
1474
+ import { notFound } from 'next/navigation';
1475
+ import { generatePage, generatePageMetadata } from '@/lib/route-handlers';
1476
+ import { getPageRouteConfig } from '@/lib/routeConfig';
1477
+
1478
+ export function generateStaticParams() {
1479
+ return [];
1480
+ }
1481
+
1482
+ ${extract}
1483
+ const params = await props.params;
1484
+ const slug = joinCmsPathSegments(params.level1);
1485
+ if (!slug) {
1486
+ notFound();
1487
+ }
1488
+ return { slug, path: \`/\${slug}/\` };
1489
+ }
1490
+
1491
+ ${metadata}
1492
+ const { slug, path } = await extractDetails(props);
1493
+ return generatePageMetadata(slug, path, getPageRouteConfig(slug), parent);
1494
+ }
1495
+
1496
+ ${page}
1497
+ const { slug, path } = await extractDetails(props);
1498
+ return generatePage(slug, path, getPageRouteConfig(slug));
1499
+ }
1500
+ `;
1501
+ }
1502
+
1503
+ function levelSlugsPage() {
1504
+ const props = "PageProps<'/[level1]/[...slugs]'>";
1505
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
1506
+ const metadata = openFn('export async function generateMetadata', [
1507
+ `props: ${props}`,
1508
+ 'parent: ResolvingMetadata',
1509
+ ]);
1510
+ const page = openFn('export default async function ', [`props: ${props}`]);
1511
+ return `${header()}import { joinCmsPathSegments } from '@se-studio/core-ui';
1512
+ import type { ResolvingMetadata } from 'next';
1513
+ import { notFound } from 'next/navigation';
1514
+ import { generatePage, generatePageMetadata } from '@/lib/route-handlers';
1515
+ import { getPageRouteConfig } from '@/lib/routeConfig';
1516
+
1517
+ export function generateStaticParams() {
1518
+ return [];
1519
+ }
1520
+
1521
+ ${extract}
1522
+ const params = await props.params;
1523
+ const slug = joinCmsPathSegments(params.level1, params.slugs);
1524
+ if (!slug) {
1525
+ notFound();
1526
+ }
1527
+ return { slug, path: \`/\${slug}/\` };
1528
+ }
1529
+
1530
+ ${metadata}
1531
+ const { slug, path } = await extractDetails(props);
1532
+ return generatePageMetadata(slug, path, getPageRouteConfig(slug), parent);
1533
+ }
1534
+
1535
+ ${page}
1536
+ const { slug, path } = await extractDetails(props);
1537
+ return generatePage(slug, path, getPageRouteConfig(slug));
1538
+ }
1539
+ `;
1540
+ }
1541
+
1542
+ function tagsIndexPage() {
1543
+ const props = "PageProps<'/tags'>";
1544
+ const metadata = openFn('export function generateMetadata', [
1545
+ `_props: ${props}`,
1546
+ 'parent: ResolvingMetadata',
1547
+ ]);
1548
+ const page = openFn('export default function ', [`_props: ${props}`]);
1549
+ return `${header()}import type { ResolvingMetadata } from 'next';
1550
+ import { TAGS_BASE } from '@/lib/constants';
1551
+ import { generateTagsIndexMetadata, generateTagsIndexPage } from '@/lib/route-handlers';
1552
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1553
+
1554
+ export function generateStaticParams() {
1555
+ return [];
1556
+ }
1557
+
1558
+ ${metadata}
1559
+ return generateTagsIndexMetadata(TAGS_BASE, DEFAULT_ROUTE_CONFIG, parent);
1560
+ }
1561
+
1562
+ ${page}
1563
+ return generateTagsIndexPage(TAGS_BASE, DEFAULT_ROUTE_CONFIG);
1564
+ }
1565
+ `;
1566
+ }
1567
+
1568
+ function tagPage() {
1569
+ const props = "PageProps<'/tags/[tag]'>";
1570
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
1571
+ const metadata = openFn('export async function generateMetadata', [
1572
+ `props: ${props}`,
1573
+ 'parent: ResolvingMetadata',
1574
+ ]);
1575
+ const page = openFn('export default async function ', [`props: ${props}`]);
1576
+ return `${header()}import type { ResolvingMetadata } from 'next';
1577
+ import { converterContext } from '@/lib/converter-context';
1578
+ import { generateTagMetadata, generateTagPage } from '@/lib/route-handlers';
1579
+ import { TAG_LISTING_ROUTE_CONFIG } from '@/lib/routeConfig';
1580
+
1581
+ export function generateStaticParams() {
1582
+ return [];
1583
+ }
1584
+
1585
+ ${extract}
1586
+ const params = await props.params;
1587
+ const { tag } = params;
1588
+ return { tagSlug: tag, path: converterContext.urlCalculators.tag(tag) };
1589
+ }
1590
+
1591
+ ${metadata}
1592
+ const { tagSlug, path } = await extractDetails(props);
1593
+ return await generateTagMetadata(tagSlug, path, TAG_LISTING_ROUTE_CONFIG, parent);
1594
+ }
1595
+
1596
+ ${page}
1597
+ const { tagSlug, path } = await extractDetails(props);
1598
+ return await generateTagPage(tagSlug, path, TAG_LISTING_ROUTE_CONFIG);
1599
+ }
1600
+ `;
1601
+ }
1602
+
1603
+ /**
1604
+ * @param {string} segment
1605
+ */
1606
+ function peopleIndexPage(segment) {
1607
+ const props = `PageProps<'/${segment}'>`;
1608
+ const metadata = openFn('export function generateMetadata', [
1609
+ `_props: ${props}`,
1610
+ 'parent: ResolvingMetadata',
1611
+ ]);
1612
+ const page = openFn('export default function ', [`_props: ${props}`]);
1613
+ const baseImport =
1614
+ segment === 'people'
1615
+ ? `import { PEOPLE_BASE } from '@/lib/constants';\n`
1616
+ : '';
1617
+ const baseExpr = segment === 'people' ? 'PEOPLE_BASE' : `'/${segment}'`;
1618
+ return `${header()}import type { ResolvingMetadata } from 'next';
1619
+ ${baseImport}import { generateTeamIndexMetadata, generateTeamIndexPage } from '@/lib/route-handlers';
1620
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1621
+
1622
+ export function generateStaticParams() {
1623
+ return [];
1624
+ }
1625
+
1626
+ ${metadata}
1627
+ return generateTeamIndexMetadata(${baseExpr}, DEFAULT_ROUTE_CONFIG, parent);
1628
+ }
1629
+
1630
+ ${page}
1631
+ return generateTeamIndexPage(${baseExpr}, DEFAULT_ROUTE_CONFIG);
1632
+ }
1633
+ `;
1634
+ }
1635
+
1636
+ /**
1637
+ * @param {string} base
1638
+ * @param {string} type
1639
+ */
1640
+ function personTypeIndexPage(base, type) {
1641
+ const props = `PageProps<'/${base}/${type}'>`;
1642
+ const routePath = `/${base}/${type}/`;
1643
+ const metadata = openFn('export async function generateMetadata', [
1644
+ `_props: ${props}`,
1645
+ 'parent: ResolvingMetadata',
1646
+ ]);
1647
+ const page = openFn('export default async function ', [`_props: ${props}`]);
1648
+ return `${header()}import type { ResolvingMetadata } from 'next';
1649
+ import { notFound } from 'next/navigation';
1650
+ import { enablePerson } from '@/generated/marketing-flags';
1651
+ import {
1652
+ generatePersonTypeIndexMetadata,
1653
+ generatePersonTypeIndexPage,
1654
+ } from '@/lib/route-handlers';
1655
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1656
+
1657
+ const PERSON_TYPE = '${type}';
1658
+ const PATH = '${routePath}';
1659
+
1660
+ export function generateStaticParams() {
1661
+ return [];
1662
+ }
1663
+
1664
+ ${metadata}
1665
+ if (!enablePerson) {
1666
+ return {};
1667
+ }
1668
+ return await generatePersonTypeIndexMetadata(PERSON_TYPE, PATH, DEFAULT_ROUTE_CONFIG, parent);
1669
+ }
1670
+
1671
+ ${page}
1672
+ if (!enablePerson) {
1673
+ notFound();
1674
+ }
1675
+ return await generatePersonTypeIndexPage(PERSON_TYPE, PATH, DEFAULT_ROUTE_CONFIG);
1676
+ }
1677
+ `;
1678
+ }
1679
+
1680
+ /**
1681
+ * @param {string} base
1682
+ * @param {string} type
1683
+ */
1684
+ function personTypePersonPage(base, type) {
1685
+ const props = `PageProps<'/${base}/${type}/[person]'>`;
1686
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
1687
+ const metadata = openFn('export async function generateMetadata', [
1688
+ `props: ${props}`,
1689
+ 'parent: ResolvingMetadata',
1690
+ ]);
1691
+ const page = openFn('export default async function ', [`props: ${props}`]);
1692
+ return `${header()}import type { ResolvingMetadata } from 'next';
1693
+ import { notFound } from 'next/navigation';
1694
+ import { enablePerson } from '@/generated/marketing-flags';
1695
+ import { generatePersonMetadata, generatePersonPage } from '@/lib/route-handlers';
1696
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1697
+
1698
+ export function generateStaticParams() {
1699
+ return [];
1700
+ }
1701
+
1702
+ ${extract}
1703
+ const params = await props.params;
1704
+ const { person } = params;
1705
+ return { person, path: \`/${base}/${type}/\${person}/\` };
1706
+ }
1707
+
1708
+ ${metadata}
1709
+ if (!enablePerson) {
1710
+ return {};
1711
+ }
1712
+ const { person, path } = await extractDetails(props);
1713
+ return await generatePersonMetadata(person, path, DEFAULT_ROUTE_CONFIG, parent);
1714
+ }
1715
+
1716
+ ${page}
1717
+ if (!enablePerson) {
1718
+ notFound();
1719
+ }
1720
+ const { person, path } = await extractDetails(props);
1721
+ return await generatePersonPage(person, path, DEFAULT_ROUTE_CONFIG);
1722
+ }
1723
+ `;
1724
+ }
1725
+
1726
+ /**
1727
+ * Person with no person type. Does not redirect to the typed URL.
1728
+ *
1729
+ * @param {string} segment
1730
+ */
1731
+ function untypedPersonPage(segment) {
1732
+ const props = `PageProps<'/${segment}/[person]'>`;
1733
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
1734
+ const metadata = openFn('export async function generateMetadata', [
1735
+ `props: ${props}`,
1736
+ 'parent: ResolvingMetadata',
1737
+ ]);
1738
+ const page = openFn('export default async function ', [`props: ${props}`]);
1739
+ return `${header()}import type { ResolvingMetadata } from 'next';
1740
+ import { notFound } from 'next/navigation';
1741
+ import { enablePerson } from '@/generated/marketing-flags';
1742
+ import { generatePersonMetadata, generatePersonPage } from '@/lib/route-handlers';
1743
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1744
+
1745
+ export function generateStaticParams() {
1746
+ return [];
1747
+ }
1748
+
1749
+ ${extract}
1750
+ const params = await props.params;
1751
+ const { person } = params;
1752
+ return { person, path: \`/${segment}/\${person}/\` };
1753
+ }
1754
+
1755
+ ${metadata}
1756
+ if (!enablePerson) {
1757
+ return {};
1758
+ }
1759
+ const { person, path } = await extractDetails(props);
1760
+ return await generatePersonMetadata(person, path, DEFAULT_ROUTE_CONFIG, parent);
1761
+ }
1762
+
1763
+ ${page}
1764
+ if (!enablePerson) {
1765
+ notFound();
1766
+ }
1767
+ const { person, path } = await extractDetails(props);
1768
+ return await generatePersonPage(person, path, DEFAULT_ROUTE_CONFIG);
1769
+ }
1770
+ `;
1771
+ }
1772
+
1773
+ /** @returns {string} */
1774
+ function typedPersonRest() {
1775
+ return `${PERSON_TYPE_ROOT}/[peopleType]/[person]`;
1776
+ }
1777
+
1778
+ /**
1779
+ * Person under a person type, at /peopleType/{peopleType}/{person}/.
1780
+ * Does not redirect to /people/{person}/.
1781
+ */
1782
+ function typedPersonPage() {
1783
+ const props = `PageProps<'/${PERSON_TYPE_ROOT}/[peopleType]/[person]'>`;
1784
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
1785
+ const metadata = openFn('export async function generateMetadata', [
1786
+ `props: ${props}`,
1787
+ 'parent: ResolvingMetadata',
1788
+ ]);
1789
+ const page = openFn('export default async function ', [`props: ${props}`]);
1790
+ return `${header()}import type { ResolvingMetadata } from 'next';
1791
+ import { notFound } from 'next/navigation';
1792
+ import { enablePerson } from '@/generated/marketing-flags';
1793
+ import { generatePersonMetadata, generatePersonPage } from '@/lib/route-handlers';
1794
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1795
+
1796
+ export function generateStaticParams() {
1797
+ return [];
1798
+ }
1799
+
1800
+ ${extract}
1801
+ const params = await props.params;
1802
+ const { person, peopleType } = params;
1803
+ return { person, path: \`/${PERSON_TYPE_ROOT}/\${peopleType}/\${person}/\` };
1804
+ }
1805
+
1806
+ ${metadata}
1807
+ if (!enablePerson) {
1808
+ return {};
1809
+ }
1810
+ const { person, path } = await extractDetails(props);
1811
+ return await generatePersonMetadata(person, path, DEFAULT_ROUTE_CONFIG, parent);
1812
+ }
1813
+
1814
+ ${page}
1815
+ if (!enablePerson) {
1816
+ notFound();
1817
+ }
1818
+ const { person, path } = await extractDetails(props);
1819
+ return await generatePersonPage(person, path, DEFAULT_ROUTE_CONFIG);
1820
+ }
1821
+ `;
1822
+ }
1823
+
1824
+ /**
1825
+ * Preview lives at the app root or under Brightlife's `(default)` group.
1826
+ *
1827
+ * @param {string} rel
1828
+ */
1829
+ function isPreviewPage(rel) {
1830
+ return (
1831
+ rel === 'src/app/preview/page.ts' ||
1832
+ rel === 'src/app/preview/page.tsx' ||
1833
+ rel === 'src/app/(default)/preview/page.ts' ||
1834
+ rel === 'src/app/(default)/preview/page.tsx'
1835
+ );
1836
+ }
1837
+
1838
+ /** example-empty Biome line width. Longer signatures are wrapped the same way. */
1839
+ const LINE_WIDTH = 100;
1840
+
1841
+ /**
1842
+ * Dynamic `articles` keeps `urlCalculators`, matching the hand-written pages.
1843
+ * Any other base uses the path of the file that was written. `article()`
1844
+ * inserts the primary tag (`other`) and prefixes `ARTICLES_BASE`.
1845
+ *
1846
+ * @param {string} segment
1847
+ */
1848
+ function usesArticleCalculator(segment) {
1849
+ return segment === 'articles';
1850
+ }
1851
+
1852
+ /**
1853
+ * @param {string} prefix text before `(`, including a trailing space for `function `
1854
+ * @param {string[]} params
1855
+ */
1856
+ function openFn(prefix, params) {
1857
+ const oneLine = `${prefix}(${params.join(', ')}) {`;
1858
+ if (oneLine.length <= LINE_WIDTH) {
1859
+ return oneLine;
1860
+ }
1861
+ const inner = params.map((param) => ` ${param},`).join('\n');
1862
+ return `${prefix}(\n${inner}\n) {`;
1863
+ }
1864
+
1865
+ /**
1866
+ * @param {string} segment
1867
+ */
1868
+ function fixedArticleIndex(segment) {
1869
+ const props = `PageProps<'/${segment}'>`;
1870
+ const metadata = openFn('export async function generateMetadata', [
1871
+ `_props: ${props}`,
1872
+ 'parent: ResolvingMetadata',
1873
+ ]);
1874
+ const page = openFn('export default async function ', [`_props: ${props}`]);
1875
+ return `${header()}import type { ResolvingMetadata } from 'next';
1876
+ import { generateArticleTypeMetadata, generateArticleTypePage } from '@/lib/route-handlers';
1877
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1878
+
1879
+ const ARTICLE_TYPE = '${segment}';
1880
+ const PATH = '/${segment}/';
1881
+
1882
+ export function generateStaticParams() {
1883
+ return [];
1884
+ }
1885
+
1886
+ ${metadata}
1887
+ return await generateArticleTypeMetadata(ARTICLE_TYPE, PATH, DEFAULT_ROUTE_CONFIG, parent);
1888
+ }
1889
+
1890
+ ${page}
1891
+ return await generateArticleTypePage(ARTICLE_TYPE, PATH, DEFAULT_ROUTE_CONFIG);
1892
+ }
1893
+ `;
1894
+ }
1895
+
1896
+ /**
1897
+ * @param {string} segment
1898
+ */
1899
+ function fixedArticleDetail(segment) {
1900
+ const props = `PageProps<'/${segment}/[...slugs]'>`;
1901
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
1902
+ const metadata = openFn('export async function generateMetadata', [
1903
+ `props: ${props}`,
1904
+ 'parent: ResolvingMetadata',
1905
+ ]);
1906
+ const page = openFn('export default async function ', [`props: ${props}`]);
1907
+ return `${header()}import { joinCmsPathSegments } from '@se-studio/core-ui';
1908
+ import type { ResolvingMetadata } from 'next';
1909
+ import { notFound } from 'next/navigation';
1910
+ import { generateArticleMetadata, generateArticlePage } from '@/lib/route-handlers';
1911
+ import { ARTICLE_DETAIL_ROUTE_CONFIG } from '@/lib/routeConfig';
1912
+
1913
+ const ARTICLE_TYPE = '${segment}';
1914
+
1915
+ export function generateStaticParams() {
1916
+ return [];
1917
+ }
1918
+
1919
+ ${extract}
1920
+ const params = await props.params;
1921
+ const articleSlug = joinCmsPathSegments(params.slugs);
1922
+ if (!articleSlug) {
1923
+ notFound();
1924
+ }
1925
+ return {
1926
+ articleSlug,
1927
+ path: \`/${segment}/\${articleSlug}/\`,
1928
+ };
1929
+ }
1930
+
1931
+ ${metadata}
1932
+ const { articleSlug, path } = await extractDetails(props);
1933
+ return await generateArticleMetadata(
1934
+ ARTICLE_TYPE,
1935
+ articleSlug,
1936
+ path,
1937
+ ARTICLE_DETAIL_ROUTE_CONFIG,
1938
+ parent,
1939
+ );
1940
+ }
1941
+
1942
+ ${page}
1943
+ const { articleSlug, path } = await extractDetails(props);
1944
+ return await generateArticlePage(ARTICLE_TYPE, articleSlug, path, ARTICLE_DETAIL_ROUTE_CONFIG);
1945
+ }
1946
+ `;
1947
+ }
1948
+
1949
+ /**
1950
+ * @param {string} segment
1951
+ */
1952
+ function dynamicArticleIndex(segment) {
1953
+ const props = `PageProps<'/${segment}'>`;
1954
+ const articles = usesArticleCalculator(segment);
1955
+ const importBase = articles
1956
+ ? `import { enableArticleTypeIndex } from '@/generated/marketing-flags';
1957
+ import { ARTICLES_BASE } from '@/lib/constants';`
1958
+ : `import { enableArticleTypeIndex } from '@/generated/marketing-flags';`;
1959
+ const baseDecl = articles ? '' : `const BASE = '/${segment}';\n\n`;
1960
+ const baseIdent = articles ? 'ARTICLES_BASE' : 'BASE';
1961
+ const metadata = openFn('export function generateMetadata', [
1962
+ `_props: ${props}`,
1963
+ 'parent: ResolvingMetadata',
1964
+ ]);
1965
+ const page = openFn('export default function ', [`_props: ${props}`]);
1966
+ return `${header()}import type { ResolvingMetadata } from 'next';
1967
+ import { notFound } from 'next/navigation';
1968
+ ${importBase}
1969
+ import {
1970
+ generateArticleTypesIndexMetadata,
1971
+ generateArticleTypesIndexPage,
1972
+ } from '@/lib/route-handlers';
1973
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1974
+
1975
+ ${baseDecl}export function generateStaticParams() {
1976
+ return [];
1977
+ }
1978
+
1979
+ ${metadata}
1980
+ if (!enableArticleTypeIndex) {
1981
+ notFound();
1982
+ }
1983
+ return generateArticleTypesIndexMetadata(${baseIdent}, DEFAULT_ROUTE_CONFIG, parent);
1984
+ }
1985
+
1986
+ ${page}
1987
+ if (!enableArticleTypeIndex) {
1988
+ notFound();
1989
+ }
1990
+ return generateArticleTypesIndexPage(${baseIdent}, DEFAULT_ROUTE_CONFIG);
1991
+ }
1992
+ `;
1993
+ }
1994
+
1995
+ /**
1996
+ * @param {string} segment
1997
+ */
1998
+ function dynamicArticleType(segment) {
1999
+ const props = `PageProps<'/${segment}/[articleType]'>`;
2000
+ const calculator = usesArticleCalculator(segment);
2001
+ const converterImport = calculator
2002
+ ? `import { converterContext } from '@/lib/converter-context';\n`
2003
+ : '';
2004
+ const pathExpr = calculator
2005
+ ? 'converterContext.urlCalculators.articleType(articleType)'
2006
+ : `\`/${segment}/\${articleType}/\``;
2007
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
2008
+ const metadata = openFn('export async function generateMetadata', [
2009
+ `props: ${props}`,
2010
+ 'parent: ResolvingMetadata',
2011
+ ]);
2012
+ const page = openFn('export default async function ', [`props: ${props}`]);
2013
+ return `${header()}import type { ResolvingMetadata } from 'next';
2014
+ ${converterImport}import { generateArticleTypeMetadata, generateArticleTypePage } from '@/lib/route-handlers';
2015
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
2016
+
2017
+ export function generateStaticParams() {
2018
+ return [];
2019
+ }
2020
+
2021
+ ${extract}
2022
+ const params = await props.params;
2023
+ const { articleType } = params;
2024
+ return { slug: articleType, path: ${pathExpr} };
2025
+ }
2026
+
2027
+ ${metadata}
2028
+ const { slug, path } = await extractDetails(props);
2029
+ return await generateArticleTypeMetadata(slug, path, DEFAULT_ROUTE_CONFIG, parent);
2030
+ }
2031
+
2032
+ ${page}
2033
+ const { slug, path } = await extractDetails(props);
2034
+ return await generateArticleTypePage(slug, path, DEFAULT_ROUTE_CONFIG);
2035
+ }
2036
+ `;
2037
+ }
2038
+
2039
+ /**
2040
+ * @param {string} segment
2041
+ */
2042
+ function dynamicArticleDetail(segment) {
2043
+ const props = `PageProps<'/${segment}/[articleType]/[...slugs]'>`;
2044
+ const calculator = usesArticleCalculator(segment);
2045
+ const converterImport = calculator
2046
+ ? `import { converterContext } from '@/lib/converter-context';\n`
2047
+ : '';
2048
+ const pathExpr = calculator
2049
+ ? 'converterContext.urlCalculators.article(articleType, articleSlug)'
2050
+ : `\`/${segment}/\${articleType}/\${articleSlug}/\``;
2051
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
2052
+ const metadata = openFn('export async function generateMetadata', [
2053
+ `props: ${props}`,
2054
+ 'parent: ResolvingMetadata',
2055
+ ]);
2056
+ const page = openFn('export default async function ', [`props: ${props}`]);
2057
+ return `${header()}import { joinCmsPathSegments } from '@se-studio/core-ui';
2058
+ import type { ResolvingMetadata } from 'next';
2059
+ import { notFound } from 'next/navigation';
2060
+ ${converterImport}import { generateArticleMetadata, generateArticlePage } from '@/lib/route-handlers';
2061
+ import { ARTICLE_DETAIL_ROUTE_CONFIG } from '@/lib/routeConfig';
2062
+
2063
+ export function generateStaticParams() {
2064
+ return [];
2065
+ }
2066
+
2067
+ ${extract}
2068
+ const params = await props.params;
2069
+ const articleType = joinCmsPathSegments(params.articleType);
2070
+ const articleSlug = joinCmsPathSegments(params.slugs);
2071
+ if (!(articleType && articleSlug)) {
2072
+ notFound();
2073
+ }
2074
+ return {
2075
+ articleType,
2076
+ articleSlug,
2077
+ path: ${pathExpr},
2078
+ };
2079
+ }
2080
+
2081
+ ${metadata}
2082
+ const { articleType, articleSlug, path } = await extractDetails(props);
2083
+ return await generateArticleMetadata(
2084
+ articleType,
2085
+ articleSlug,
2086
+ path,
2087
+ ARTICLE_DETAIL_ROUTE_CONFIG,
2088
+ parent,
2089
+ );
2090
+ }
2091
+
2092
+ ${page}
2093
+ const { articleType, articleSlug, path } = await extractDetails(props);
2094
+ return await generateArticlePage(articleType, articleSlug, path, ARTICLE_DETAIL_ROUTE_CONFIG);
2095
+ }
2096
+ `;
2097
+ }
2098
+
2099
+ /**
2100
+ * @param {string} segment
2101
+ */
2102
+ function fixedArticleTag(segment) {
2103
+ const props = `PageProps<'/${segment}/[tag]'>`;
2104
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
2105
+ const metadata = openFn('export async function generateMetadata', [
2106
+ `props: ${props}`,
2107
+ 'parent: ResolvingMetadata',
2108
+ ]);
2109
+ const page = openFn('export default async function ', [`props: ${props}`]);
2110
+ return `${header()}import type { ResolvingMetadata } from 'next';
2111
+ import {
2112
+ generateArticleTypeTagMetadata,
2113
+ generateArticleTypeTagPage,
2114
+ } from '@/lib/route-handlers';
2115
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
2116
+
2117
+ const ARTICLE_TYPE = '${segment}';
2118
+
2119
+ export function generateStaticParams() {
2120
+ return [];
2121
+ }
2122
+
2123
+ ${extract}
2124
+ const params = await props.params;
2125
+ const { tag } = params;
2126
+ return { tag, path: \`/${segment}/\${tag}/\` };
2127
+ }
2128
+
2129
+ ${metadata}
2130
+ const { tag, path } = await extractDetails(props);
2131
+ return await generateArticleTypeTagMetadata(ARTICLE_TYPE, tag, path, DEFAULT_ROUTE_CONFIG, parent);
2132
+ }
2133
+
2134
+ ${page}
2135
+ const { tag, path } = await extractDetails(props);
2136
+ return await generateArticleTypeTagPage(ARTICLE_TYPE, tag, path, DEFAULT_ROUTE_CONFIG);
2137
+ }
2138
+ `;
2139
+ }
2140
+
2141
+ /**
2142
+ * @param {string} segment
2143
+ */
2144
+ function fixedArticleTagDetail(segment) {
2145
+ const props = `PageProps<'/${segment}/[tag]/[...slugs]'>`;
2146
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
2147
+ const metadata = openFn('export async function generateMetadata', [
2148
+ `props: ${props}`,
2149
+ 'parent: ResolvingMetadata',
2150
+ ]);
2151
+ const page = openFn('export default async function ', [`props: ${props}`]);
2152
+ return `${header()}import { joinCmsPathSegments } from '@se-studio/core-ui';
2153
+ import type { ResolvingMetadata } from 'next';
2154
+ import { notFound } from 'next/navigation';
2155
+ import { generateArticleMetadata, generateArticlePage } from '@/lib/route-handlers';
2156
+ import { ARTICLE_DETAIL_ROUTE_CONFIG } from '@/lib/routeConfig';
2157
+
2158
+ const ARTICLE_TYPE = '${segment}';
2159
+
2160
+ export function generateStaticParams() {
2161
+ return [];
2162
+ }
2163
+
2164
+ ${extract}
2165
+ const params = await props.params;
2166
+ const tag = joinCmsPathSegments(params.tag);
2167
+ const articleSlug = joinCmsPathSegments(params.slugs);
2168
+ if (!(tag && articleSlug)) {
2169
+ notFound();
2170
+ }
2171
+ return {
2172
+ tag,
2173
+ articleSlug,
2174
+ path: \`/${segment}/\${tag}/\${articleSlug}/\`,
2175
+ };
2176
+ }
2177
+
2178
+ ${metadata}
2179
+ const { articleSlug, path } = await extractDetails(props);
2180
+ return await generateArticleMetadata(
2181
+ ARTICLE_TYPE,
2182
+ articleSlug,
2183
+ path,
2184
+ ARTICLE_DETAIL_ROUTE_CONFIG,
2185
+ parent,
2186
+ );
2187
+ }
2188
+
2189
+ ${page}
2190
+ const { articleSlug, path } = await extractDetails(props);
2191
+ return await generateArticlePage(ARTICLE_TYPE, articleSlug, path, ARTICLE_DETAIL_ROUTE_CONFIG);
2192
+ }
2193
+ `;
2194
+ }
2195
+
2196
+ /**
2197
+ * @param {string} segment
2198
+ */
2199
+ function dynamicArticleTag(segment) {
2200
+ const props = `PageProps<'/${segment}/[articleType]/[tag]'>`;
2201
+ const calculator = usesArticleCalculator(segment);
2202
+ const converterImport = calculator
2203
+ ? `import { converterContext } from '@/lib/converter-context';\n`
2204
+ : '';
2205
+ const pathExpr = calculator
2206
+ ? 'converterContext.urlCalculators.articleTypeTag(articleType, tag)'
2207
+ : `\`/${segment}/\${articleType}/\${tag}/\``;
2208
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
2209
+ const metadata = openFn('export async function generateMetadata', [
2210
+ `props: ${props}`,
2211
+ 'parent: ResolvingMetadata',
2212
+ ]);
2213
+ const page = openFn('export default async function ', [`props: ${props}`]);
2214
+ return `${header()}import type { ResolvingMetadata } from 'next';
2215
+ ${converterImport}import {
2216
+ generateArticleTypeTagMetadata,
2217
+ generateArticleTypeTagPage,
2218
+ } from '@/lib/route-handlers';
2219
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
2220
+
2221
+ export function generateStaticParams() {
2222
+ return [];
2223
+ }
2224
+
2225
+ ${extract}
2226
+ const params = await props.params;
2227
+ const { articleType, tag } = params;
2228
+ return { articleType, tag, path: ${pathExpr} };
2229
+ }
2230
+
2231
+ ${metadata}
2232
+ const { articleType, tag, path } = await extractDetails(props);
2233
+ return await generateArticleTypeTagMetadata(
2234
+ articleType,
2235
+ tag,
2236
+ path,
2237
+ DEFAULT_ROUTE_CONFIG,
2238
+ parent,
2239
+ );
2240
+ }
2241
+
2242
+ ${page}
2243
+ const { articleType, tag, path } = await extractDetails(props);
2244
+ return await generateArticleTypeTagPage(articleType, tag, path, DEFAULT_ROUTE_CONFIG);
2245
+ }
2246
+ `;
2247
+ }
2248
+
2249
+ /**
2250
+ * @param {string} segment
2251
+ */
2252
+ function dynamicArticleTagDetail(segment) {
2253
+ const props = `PageProps<'/${segment}/[articleType]/[tag]/[...slugs]'>`;
2254
+ const calculator = usesArticleCalculator(segment);
2255
+ const converterImport = calculator
2256
+ ? `import { converterContext } from '@/lib/converter-context';\n`
2257
+ : '';
2258
+ const pathExpr = calculator
2259
+ ? 'converterContext.urlCalculators.article(articleType, articleSlug, tag)'
2260
+ : `\`/${segment}/\${articleType}/\${tag}/\${articleSlug}/\``;
2261
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
2262
+ const metadata = openFn('export async function generateMetadata', [
2263
+ `props: ${props}`,
2264
+ 'parent: ResolvingMetadata',
2265
+ ]);
2266
+ const page = openFn('export default async function ', [`props: ${props}`]);
2267
+ return `${header()}import { joinCmsPathSegments } from '@se-studio/core-ui';
2268
+ import type { ResolvingMetadata } from 'next';
2269
+ import { notFound } from 'next/navigation';
2270
+ ${converterImport}import { generateArticleMetadata, generateArticlePage } from '@/lib/route-handlers';
2271
+ import { ARTICLE_DETAIL_ROUTE_CONFIG } from '@/lib/routeConfig';
2272
+
2273
+ export function generateStaticParams() {
2274
+ return [];
2275
+ }
2276
+
2277
+ ${extract}
2278
+ const params = await props.params;
2279
+ const articleType = joinCmsPathSegments(params.articleType);
2280
+ const tag = joinCmsPathSegments(params.tag);
2281
+ const articleSlug = joinCmsPathSegments(params.slugs);
2282
+ if (!(articleType && tag && articleSlug)) {
2283
+ notFound();
2284
+ }
2285
+ return {
2286
+ articleType,
2287
+ tag,
2288
+ articleSlug,
2289
+ path: ${pathExpr},
2290
+ };
2291
+ }
2292
+
2293
+ ${metadata}
2294
+ const { articleType, articleSlug, path } = await extractDetails(props);
2295
+ return await generateArticleMetadata(
2296
+ articleType,
2297
+ articleSlug,
2298
+ path,
2299
+ ARTICLE_DETAIL_ROUTE_CONFIG,
2300
+ parent,
2301
+ );
2302
+ }
2303
+
2304
+ ${page}
2305
+ const { articleType, articleSlug, path } = await extractDetails(props);
2306
+ return await generateArticlePage(articleType, articleSlug, path, ARTICLE_DETAIL_ROUTE_CONFIG);
2307
+ }
2308
+ `;
2309
+ }