@writedocs/generator 0.15.0 → 0.17.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.
Files changed (38) hide show
  1. package/astro.config.mjs +8 -2
  2. package/package.json +1 -1
  3. package/packages/components/src/components/CodeGroup.astro +6 -6
  4. package/src/cli/build.js +39 -4
  5. package/src/cli/dev.js +16 -0
  6. package/src/cli/rewrite-redirect-pages.js +8 -6
  7. package/src/cli/run-pagefind.js +24 -11
  8. package/src/cli/write-mcp-files.js +4 -1
  9. package/src/cli/write-redirects-file.js +9 -4
  10. package/src/content.config.ts +21 -1
  11. package/src/layout/BaseLayout.astro +38 -49
  12. package/src/layout/components/LockMark.astro +28 -0
  13. package/src/layout/components/MobileMenu.astro +13 -5
  14. package/src/layout/components/Sidebar.astro +3 -2
  15. package/src/layout/components/TopBar.astro +17 -4
  16. package/src/lib/appearance.js +64 -0
  17. package/src/lib/asset-dimensions.js +2 -1
  18. package/src/lib/bom.js +20 -0
  19. package/src/lib/config-file.js +21 -8
  20. package/src/lib/config-schema.js +55 -10
  21. package/src/lib/config-schema.ts +78 -18
  22. package/src/lib/config.ts +23 -11
  23. package/src/lib/content-check.js +54 -4
  24. package/src/lib/content-store-prune.js +44 -0
  25. package/src/lib/json-schema-descriptions.js +7 -2
  26. package/src/lib/llms-index.ts +5 -0
  27. package/src/lib/mcp-index.ts +5 -1
  28. package/src/lib/mintlify-convert.js +11 -1
  29. package/src/lib/pages.js +5 -3
  30. package/src/lib/protected-sections.js +238 -0
  31. package/src/lib/wdignore-cases.json +9 -2
  32. package/src/lib/wdignore.js +5 -0
  33. package/src/lib/writedocs-legacy-convert.js +1 -1
  34. package/src/pages/[...slug].astro +53 -14
  35. package/src/pages/llms-full.txt.ts +10 -3
  36. package/src/pages/llms.txt.ts +4 -4
  37. package/src/pages/og/[...slug].png.ts +11 -2
  38. package/writedocs.schema.json +478 -70
package/src/lib/config.ts CHANGED
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import { EXCLUDED_TOP_LEVEL_DIRS, navPageId, draftsIncluded, findDraftPages, fileIdForPath } from './pages.js';
4
4
  import { withoutDrafts } from './drafts.js';
5
5
  import { isHidden } from './hidden-sections.js';
6
+ import { accessOf, isLocked } from './protected-sections.js';
6
7
  import { itemPage, childLevel, equivalentItem, resolveLandings as resolveLandingsJs } from './item-pages.js';
7
8
  import matter from 'gray-matter';
8
9
  import { writedocsTempDir } from './writedocs-temp-dir.js';
@@ -850,6 +851,7 @@ export function landingSelectors(landing: Landing, hrefForSlug: (slug: string) =
850
851
  href: 'href' in child ? child.href : hrefForSlug(firstSlugOf(child as Container) ?? 'index'),
851
852
  active: false,
852
853
  dropdown: dropdownMenuOf(child as Container, hrefForSlug),
854
+ ...(isLocked(child) ? { locked: true } : {}),
853
855
  };
854
856
  }),
855
857
  });
@@ -883,24 +885,28 @@ export function resolveGlobalDropdowns(navigation: NavigationConfig): DropdownIt
883
885
  * (returns null, with nothing that tries the next one), which is a real
884
886
  * case now that any container - not just a nested dropdown - can be a
885
887
  * bare external link (e.g. a `tabs` array whose first entry is
886
- * `{ tab: "Status", href: "..." }`). */
887
- function firstSlugAmong(items: Container[]): string | null {
888
+ * `{ tab: "Status", href: "..." }`).
889
+ * `publicOnly` (the site's `/`): protected items are skipped too
890
+ * (lib/protected-sections.js) - an option's own link still leads into its
891
+ * protected children, the way choosing it in a menu would. */
892
+ function firstSlugAmong(items: Container[], publicOnly = false): string | null {
888
893
  for (const item of items) {
889
894
  // A hidden item is reached only by its address - never by default.
890
895
  if (isHidden(item)) continue;
891
- const slug = firstSlugOf(item);
896
+ if (publicOnly && accessOf(item)) continue;
897
+ const slug = firstSlugOf(item, publicOnly);
892
898
  if (slug !== null) return slug;
893
899
  }
894
900
  return null;
895
901
  }
896
902
 
897
- export function firstSlugOf(node: Container): string | null {
903
+ export function firstSlugOf(node: Container, publicOnly = false): string | null {
898
904
  // An item with a `page` of its own opens there (lib/item-pages.js).
899
905
  const own = itemPage(node);
900
906
  if (own !== null) return own;
901
907
  if ('pages' in node) return flattenNav(node.pages)[0]?.slug ?? null;
902
908
  if ('href' in node) return null;
903
- if ('tabs' in node) return firstSlugAmong(node.tabs);
909
+ if ('tabs' in node) return firstSlugAmong(node.tabs, publicOnly);
904
910
  if ('versions' in node) {
905
911
  // Try the `default`-tagged version(s) first (matching the old
906
912
  // "preferred" pick), then fall through to the rest in order - same
@@ -908,11 +914,11 @@ export function firstSlugOf(node: Container): string | null {
908
914
  // extra preference pass in front of it.
909
915
  const defaults = node.versions.filter((v) => v.default);
910
916
  const rest = node.versions.filter((v) => !v.default);
911
- return firstSlugAmong([...defaults, ...rest]);
917
+ return firstSlugAmong([...defaults, ...rest], publicOnly);
912
918
  }
913
- if ('languages' in node) return firstSlugAmong(node.languages);
914
- if ('dropdowns' in node) return firstSlugAmong(node.dropdowns);
915
- if ('products' in node) return firstSlugAmong(node.products);
919
+ if ('languages' in node) return firstSlugAmong(node.languages, publicOnly);
920
+ if ('dropdowns' in node) return firstSlugAmong(node.dropdowns, publicOnly);
921
+ if ('products' in node) return firstSlugAmong(node.products, publicOnly);
916
922
  return null;
917
923
  }
918
924
 
@@ -985,10 +991,11 @@ export function equivalentPageIn(
985
991
  * the navigation happens to be a page literally named "index" (the
986
992
  * usual "docs/index.mdx is the homepage" convention). Mirrors
987
993
  * firstSlugOf()'s per-container descent, plus the flat-array root case
988
- * firstSlugOf() alone can't handle since a bare array isn't a Container. */
994
+ * firstSlugOf() alone can't handle since a bare array isn't a Container.
995
+ * Never a page in a hidden or a protected item. */
989
996
  export function firstSlugOfNavigation(navigation: NavigationConfig): string | null {
990
997
  if (Array.isArray(navigation)) return flattenNav(navigation)[0]?.slug ?? null;
991
- return firstSlugOf(navigation as Container);
998
+ return firstSlugOf(navigation as Container, true);
992
999
  }
993
1000
 
994
1001
  /** Whether `slug` is reachable anywhere underneath a container, however
@@ -1048,6 +1055,9 @@ export interface SelectorOption {
1048
1055
  // On an entry with a `submenu`: the entry's own `page`, if it has one -
1049
1056
  // clicking the entry opens it. Without one, clicking opens the flyout.
1050
1057
  pageHref?: string;
1058
+ // A protected item with `lock: true` (lib/protected-sections.js): a
1059
+ // padlock beside its name, wherever it's listed (LockMark.astro).
1060
+ locked?: boolean;
1051
1061
  }
1052
1062
 
1053
1063
  export interface Selector {
@@ -1086,6 +1096,7 @@ function dropdownMenuOf(
1086
1096
  icon: iconOf(d),
1087
1097
  href: 'href' in d ? d.href : hrefForSlug(firstSlugOf(d) ?? 'index'),
1088
1098
  active,
1099
+ ...(isLocked(d) ? { locked: true } : {}),
1089
1100
  };
1090
1101
  if (depth === 1 && 'dropdowns' in d) {
1091
1102
  const submenu = dropdownMenuOf(d, hrefForSlug, active ? below : [], depth + 1);
@@ -1143,6 +1154,7 @@ export function buildSelectors(
1143
1154
  href: 'href' in item ? item.href : hrefForSlug(targetSlug),
1144
1155
  active: isActive,
1145
1156
  dropdown: dropdownMenuOf(item, hrefForSlug, isActive ? path.slice(segIndex + 1) : []),
1157
+ ...(isLocked(item) ? { locked: true } : {}),
1146
1158
  };
1147
1159
  }),
1148
1160
  };
@@ -31,12 +31,15 @@ import path from 'node:path';
31
31
  import matter from 'gray-matter';
32
32
  import { visit } from 'unist-util-visit';
33
33
  import { findAllPages, fileIdForPath, titleFromPath, navPageId } from './pages.js';
34
+ import { projectIgnore } from './project-ignore.js';
34
35
  import { iconExists } from '../../packages/components/src/lib/icons.js';
35
36
  import { findUnknownComponents } from './mdx-unknown-components.js';
36
37
  import { findInteractiveComponents, simplifiedBuiltinMessage } from './mdx-inline-react.js';
37
38
  import { pageFrontmatterSchema, createJsonLocator } from './config-schema.js';
38
39
  import { parseOpenApiRef } from './openapi-ref.js';
40
+ import { readText } from './config-file.js';
39
41
  import { collectOpenApiGroups, operationKeys } from './openapi-spec.js';
42
+ import { usesAccess, accessOf, firstAccessPath, ACCESS_NEEDS_PLATFORM } from './protected-sections.js';
40
43
 
41
44
  /** An issue: { file, line?, message, suggestion? } - `file` relative to the
42
45
  * content directory, POSIX slashes. */
@@ -70,7 +73,9 @@ async function parseMdx(text) {
70
73
  }
71
74
 
72
75
  async function checkPage(contentDir, rel, errors, warnings, openapiRefs) {
73
- const raw = fs.readFileSync(path.join(contentDir, rel), 'utf-8').replace(/\r\n/g, '\n');
76
+ // Without a byte order mark, so the frontmatter's line numbers below are
77
+ // the same as in the same file without one (lib/bom.js).
78
+ const raw = readText(path.join(contentDir, rel)).replace(/\r\n/g, '\n');
74
79
  let parsed;
75
80
  try {
76
81
  // An options object bypasses gray-matter's cache, which keeps an empty
@@ -381,6 +386,22 @@ async function checkOpenApi(contentDir, config, locate, openapiRefs, errors, war
381
386
  * null when it isn't valid JSON (then only the pages themselves are
382
387
  * checked). Returns { pages, errors, warnings }.
383
388
  */
389
+ /** The file a navigation id names (`<id>.mdx`, `<id>.md`, or the same as a
390
+ * folder's index), when it exists but the project's ignore rules
391
+ * (projectIgnore() - the default exclusions and `.wdignore`) leave it out.
392
+ * Its project-relative path, or null. */
393
+ function ignoredPageFile(contentDir, id) {
394
+ const rules = projectIgnore(contentDir);
395
+ for (const rel of [`${id}.mdx`, `${id}.md`, `${id}/index.mdx`, `${id}/index.md`]) {
396
+ let isFile = false;
397
+ try {
398
+ isFile = fs.statSync(path.join(contentDir, rel)).isFile();
399
+ } catch {}
400
+ if (isFile && rules.ignores(rel)) return rel;
401
+ }
402
+ return null;
403
+ }
404
+
384
405
  export async function checkContent(contentDir, configText) {
385
406
  const errors = [];
386
407
  const warnings = [];
@@ -405,6 +426,21 @@ export async function checkContent(contentDir, configText) {
405
426
  for (const ref of navigationReferences(config.navigation)) {
406
427
  // "guides/index" and "guides" both name guides/index.mdx (navPageId()).
407
428
  if (ids.has(navPageId(ref.id))) continue;
429
+ // The file is there but an ignore rule leaves it out - README.md is a
430
+ // default exclusion (lib/wdignore.js), and a Mintlify project may list
431
+ // its README. "Create README.mdx" would send the author in circles.
432
+ const ignoredFile = ignoredPageFile(contentDir, ref.id);
433
+ if (ignoredFile) {
434
+ errors.push(
435
+ issue(
436
+ 'writedocs.json',
437
+ locate(ref.path)?.line,
438
+ `The navigation lists page "${ref.id}", but ${ignoredFile} is left out of the site by the ignore rules.`,
439
+ `Rename the file, or bring it back with a line "!${ignoredFile}" at the end of .wdignore.`
440
+ )
441
+ );
442
+ continue;
443
+ }
408
444
  errors.push(
409
445
  issue(
410
446
  'writedocs.json',
@@ -416,15 +452,29 @@ export async function checkContent(contentDir, configText) {
416
452
  }
417
453
  // Every top-level item hidden, and no home page: `/` never redirects into a
418
454
  // hidden item (lib/hidden-sections.js), so the site's address has nothing.
455
+ // Nor into a protected one (lib/protected-sections.js).
419
456
  const nav = config.navigation;
420
457
  const topKey = nav && !Array.isArray(nav) ? ['tabs', 'versions', 'languages', 'dropdowns', 'products'].find((k) => Array.isArray(nav[k])) : null;
421
- if (topKey && nav[topKey].length && nav[topKey].every((item) => item?.hidden === true || 'href' in (item ?? {})) && !ids.has('index')) {
458
+ if (topKey && nav[topKey].length && nav[topKey].every((item) => item?.hidden === true || accessOf(item) || 'href' in (item ?? {})) && !ids.has('index')) {
459
+ const anyProtected = nav[topKey].some((item) => accessOf(item));
422
460
  warnings.push(
423
461
  issue(
424
462
  'writedocs.json',
425
463
  locate(['navigation', topKey])?.line,
426
- `Every item in navigation.${topKey} is hidden and there's no home page - the site's own address (/) shows "not found".`,
427
- 'Add an index.mdx at the project root for a home page, or leave one item not hidden.'
464
+ `Every item in navigation.${topKey} is hidden${anyProtected ? ' or protected' : ''} and there's no home page - the site's own address (/) shows "not found".`,
465
+ `Add an index.mdx at the project root for a home page, or leave one item not hidden${anyProtected ? ' and not protected' : ''}.`
466
+ )
467
+ );
468
+ }
469
+ // `access` is the WriteDocs platform's to enforce - anywhere else the
470
+ // pages are public (lib/protected-sections.js).
471
+ if (usesAccess(nav)) {
472
+ warnings.push(
473
+ issue(
474
+ 'writedocs.json',
475
+ locate(firstAccessPath(nav))?.line,
476
+ ACCESS_NEEDS_PLATFORM,
477
+ 'Publish the site on WriteDocs, where each access rule is set up - or, on another host, put a login in front of these pages (on Cloudflare, Cloudflare Access).'
428
478
  )
429
479
  );
430
480
  }
@@ -0,0 +1,44 @@
1
+ // Which entries of Astro's content store point at a file that's no longer
2
+ // one of the project's pages - so the content loaders (src/content.config.ts)
3
+ // can delete them before each sync.
4
+ //
5
+ // Why: Astro's glob() loader keeps a page's stored entry when one with the
6
+ // same id has the same digest - a hash of the file's text, not of where it
7
+ // is (astro/dist/content/loaders/glob.js, syncData()). A page with a `slug`
8
+ // in its frontmatter takes that slug as its id, so a page moved to another
9
+ // folder keeps its id and its text, and the store keeps its old `filePath`.
10
+ // The store is saved between runs (writedocsTempDir()'s cache/), so from
11
+ // then on:
12
+ // - `writedocs build` fails: content-modules.mjs, which Astro writes from
13
+ // the stored entries, imports the page from where it was;
14
+ // - `writedocs dev` fails on every page: writedocs reads a page's file id
15
+ // from its `filePath` (fileIdForEntry() in lib/config.ts), and the
16
+ // navigation names the page where it is now.
17
+ // Deleting the entry makes glob() read the page again, from its new path. A
18
+ // page without `slug` takes its id from its path, so moving it already
19
+ // makes a new entry - deleting is harmless there too.
20
+ //
21
+ // Plain JavaScript, so scripts/content-store-prune.test.js can run it.
22
+ import path from 'node:path';
23
+
24
+ // Windows paths aren't case-sensitive, and the same folder can reach here
25
+ // spelled two ways (lib/canonical-path.js).
26
+ const key = (p) => {
27
+ const resolved = path.resolve(p);
28
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
29
+ };
30
+
31
+ /** The ids of the stored entries whose file isn't one of `files`.
32
+ * `entries`: the store's [id, entry] pairs - an entry's `filePath` is
33
+ * relative to `root`, Astro's project root. `files`: the absolute paths of
34
+ * the pages the loader is about to sync. An entry with no `filePath` isn't
35
+ * a file's, and is left alone. */
36
+ export function staleEntryIds(entries, root, files) {
37
+ const current = new Set(files.map(key));
38
+ const stale = [];
39
+ for (const [id, entry] of entries) {
40
+ if (typeof entry?.filePath !== 'string' || entry.filePath === '') continue;
41
+ if (!current.has(key(path.resolve(root, entry.filePath)))) stale.push(id);
42
+ }
43
+ return stale;
44
+ }
@@ -45,7 +45,9 @@ const CONTAINERS = {
45
45
 
46
46
  const HIDDEN = {
47
47
  hidden: 'Reachable only by its address: no tab, switcher or menu lists it, and inside it this level isn\'t shown. Its pages search only among themselves.',
48
- searchPublic: 'For a hidden item: its search also finds the site\'s public pages.',
48
+ searchPublic: 'For a hidden or protected item: its search also finds the site\'s public pages.',
49
+ access: 'The name of an access rule on the WriteDocs platform (lowercase letters, numbers and hyphens, up to 40): every page under this item is served only to readers the rule lets in. Only the platform protects them - on any other host they\'re public.',
50
+ lock: 'For a protected item (with `access`): a padlock next to its name, wherever it\'s listed.',
49
51
  page: 'A page of its own - an overview - that choosing this item opens, in place of its first page. Shown inside the item; in a sidebar too, it opens there.',
50
52
  };
51
53
 
@@ -125,7 +127,10 @@ export const DESCRIPTIONS = {
125
127
  'styles.navbar.dark.accent': 'Color of the underline under the active tab in the topbar, in dark mode.',
126
128
  'styles.background': 'Background color of the site, and an optional background image.',
127
129
  'styles.background.colors': 'Background colors.',
128
- 'styles.background.colors.light': 'Background color in light mode. Default "#ffffff".',
130
+ 'styles.appearance': 'Light and dark mode: which one pages open in, and whether readers can switch.',
131
+ 'styles.appearance.default': 'The mode pages open in: "system" follows the reader\'s device setting; "light" or "dark" always starts there. Default "system". A reader who picks a mode with the theme toggle keeps their choice.',
132
+ 'styles.appearance.strict': 'Hide the theme toggle, so every reader sees the `default` mode and can\'t switch. Default false.',
133
+ 'styles.background.colors.light':'Background color in light mode. Default "#ffffff".',
129
134
  'styles.background.colors.dark': 'Background color in dark mode. Default "#0b1120".',
130
135
  'styles.background.images': 'Background images, shown behind the content and sidebar.',
131
136
  'styles.background.images.light': 'Background image in light mode.',
@@ -9,6 +9,7 @@ import path from 'node:path';
9
9
  import { loadDocsConfig, normalizeEntryId, findAllPages, resolveSiteRoot, fileIdForEntry, contextMenuOptions } from './config';
10
10
  import { buildLlmsTree, renderLlmsFiles } from './llms.js';
11
11
  import { navigationPageOrder } from './pages.js';
12
+ import { protectedPages } from './protected-sections.js';
12
13
  import { writedocsTempDir } from './writedocs-temp-dir.js';
13
14
 
14
15
  type DocsEntry = CollectionEntry<'pages'> | CollectionEntry<'generatedDocs'>;
@@ -55,11 +56,15 @@ export async function llmsIndexFiles(): Promise<Map<string, string> | null> {
55
56
  const entries: DocsEntry[] = [...pagesEntries, ...generatedDocsEntries];
56
57
 
57
58
  const pages = new Map<string, { title: string; href: string; description?: string; slug: string }>();
59
+ // Protected pages (lib/protected-sections.js) are for the readers their
60
+ // access rule lets in - never listed in a public file.
61
+ const protectedRules = protectedPages(config.navigation);
58
62
  for (const entry of entries) {
59
63
  // A page that opted out of search-engine indexing (`seo.noindex`, also
60
64
  // left out of sitemap.xml) is left out here too, and a frontmatter `url`
61
65
  // page (Mintlify's external link) has no content of its own.
62
66
  if (entry.data.seo?.noindex || entry.data.url) continue;
67
+ if (protectedRules.has(fileIdForEntry(contentDir, packageRoot, entry))) continue;
63
68
  const slug = normalizeEntryId(entry.id);
64
69
  // The .md route when it exists ([...slug].md.ts - unless `contextMenu` is off,
65
70
  // and never for an OpenAPI page, which renders from the spec), else the
@@ -19,6 +19,7 @@ import {
19
19
  } from './config';
20
20
  import { pageMarkdown } from './openapi-markdown';
21
21
  import { orderByNavigation } from './llms.js';
22
+ import { protectedPages } from './protected-sections.js';
22
23
  import { writedocsTempDir } from './writedocs-temp-dir.js';
23
24
 
24
25
  type DocsEntry = CollectionEntry<'pages'> | CollectionEntry<'generatedDocs'>;
@@ -71,10 +72,13 @@ export async function mcpIndex(): Promise<McpIndex> {
71
72
  return place;
72
73
  };
73
74
 
75
+ const protectedRules = protectedPages(config.navigation);
74
76
  const docs = entries
75
77
  // Same pages llms.txt lists: not `noindex`, not a frontmatter `url`
76
- // (an external link, with no content of its own).
78
+ // (an external link, with no content of its own), not protected
79
+ // (lib/protected-sections.js).
77
80
  .filter((entry) => !entry.data.seo?.noindex && !entry.data.url)
81
+ .filter((entry) => !protectedRules.has(fileIdForEntry(contentDir, packageRoot, entry)))
78
82
  .map((entry) => {
79
83
  const slug = normalizeEntryId(entry.id);
80
84
  const fileId = fileIdForEntry(contentDir, packageRoot, entry);
@@ -418,6 +418,17 @@ export function convertMintlifyConfig(docs) {
418
418
  if (Object.keys(background).length) styles.background = background;
419
419
  if (bg.decoration) notes.add('background.decoration', ['background', 'decoration'], `\`background.decoration\` ("${bg.decoration}") isn't supported - dropped.`);
420
420
  }
421
+ // `appearance` is the same shape in writedocs, under `styles`.
422
+ if (docs.appearance && typeof docs.appearance === 'object') {
423
+ const appearance = {};
424
+ const mode = docs.appearance.default;
425
+ if (['system', 'light', 'dark'].includes(mode)) appearance.default = mode;
426
+ else if (mode !== undefined) {
427
+ notes.add('appearance.default', ['appearance', 'default'], `\`appearance.default: ${JSON.stringify(mode)}\` isn't "system", "light" or "dark" - dropped, so pages follow the reader's device setting.`);
428
+ }
429
+ if (typeof docs.appearance.strict === 'boolean') appearance.strict = docs.appearance.strict;
430
+ if (Object.keys(appearance).length) styles.appearance = appearance;
431
+ }
421
432
  if (Object.keys(styles).length) out.styles = styles;
422
433
 
423
434
  // navigation (also collects topbar links from `global`)
@@ -576,7 +587,6 @@ export function convertMintlifyConfig(docs) {
576
587
 
577
588
  // Settings with no equivalent at all
578
589
  const unsupported = {
579
- appearance: 'Light/dark mode defaults (`appearance`) aren\'t configurable - readers choose with the theme toggle.',
580
590
  interaction: '`interaction` settings aren\'t supported.',
581
591
  thumbnails: 'Social thumbnails (`thumbnails`) aren\'t generated - set `seo.ogImage` for a social preview image.',
582
592
  metadata: '`metadata` (last-modified timestamps) isn\'t supported.',
package/src/lib/pages.js CHANGED
@@ -5,7 +5,7 @@
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import matter from 'gray-matter';
8
- import { readConfigText } from './config-file.js';
8
+ import { readConfigText, readText } from './config-file.js';
9
9
  import { oncePerBuild } from './build-memo.js';
10
10
  import { projectIgnore } from './project-ignore.js';
11
11
 
@@ -41,7 +41,7 @@ export function titleFromPath(filePath) {
41
41
  function readIgnoreFile(contentDir) {
42
42
  let text;
43
43
  try {
44
- text = fs.readFileSync(path.join(contentDir, '.mintignore'), 'utf-8');
44
+ text = readText(path.join(contentDir, '.mintignore'));
45
45
  } catch {
46
46
  return () => false;
47
47
  }
@@ -184,7 +184,9 @@ function scanAllPages(contentDir) {
184
184
  if (ignored(rel, false) || rules.ignores(rel)) continue;
185
185
  let raw;
186
186
  try {
187
- raw = fs.readFileSync(abs, 'utf-8');
187
+ // Without its byte order mark: the `^---` below has to see the
188
+ // frontmatter of a page saved by a Windows editor (lib/bom.js).
189
+ raw = readText(abs);
188
190
  } catch {
189
191
  continue;
190
192
  }
@@ -0,0 +1,238 @@
1
+ // Protected navigation items (`"access": "<rule>"` on a tab, product,
2
+ // version, language or dropdown): every page under the item is served only
3
+ // to the readers its access rule lets in. The rule itself - a password or a
4
+ // list of emails - lives on the WriteDocs platform, never in the project:
5
+ // writedocs.json only names it. The innermost item's rule wins.
6
+ //
7
+ // What the build does with a protected page:
8
+ //
9
+ // - It's left out of everything public that lists pages or carries their
10
+ // text: sitemap.xml (astro.config.mjs), llms.txt and its child files
11
+ // (lib/llms-index.ts), llms-full.txt and mcp-index.json - and it gets
12
+ // `noindex` ([...slug].astro).
13
+ // - `/` never redirects into a protected item (firstSlugOf() in
14
+ // lib/config.ts), and a folder address leads to a public page when the
15
+ // folder has one; a folder with only protected pages under it redirects
16
+ // to one of them, and that redirect is protected too ([...slug].astro).
17
+ // - Its search is its own, like a hidden item's (lib/hidden-sections.js):
18
+ // searchSpaceOf() below gives it a space per rule, and the public search
19
+ // never finds it.
20
+ // - The build writes dist/.writedocs/access.json (accessMap() below): for
21
+ // each rule, every served path it protects. The platform reads it when it
22
+ // publishes and serves those paths only behind the rule's sign-in; the
23
+ // file itself is never served.
24
+ //
25
+ // Protection isn't visual: whether the item shows in the menus is `hidden`'s
26
+ // to say, and `lock` adds a padlock where it shows. Without the platform -
27
+ // a build hosted anywhere else - nothing is protected; `writedocs build`
28
+ // and `validate` say so (ACCESS_NEEDS_PLATFORM).
29
+ //
30
+ // Plain JavaScript, for scripts/protected-sections.test.js and the CLI.
31
+ import { CHILD_KINDS, itemPage } from './item-pages.js';
32
+ import { navPageId } from './pages.js';
33
+ import { isHidden, spaceOf } from './hidden-sections.js';
34
+
35
+ /** What `writedocs build` and `writedocs validate` say when a project uses
36
+ * `access`. */
37
+ export const ACCESS_NEEDS_PLATFORM = 'access needs the WriteDocs platform; on your own host these pages are public.';
38
+
39
+ /** What `writedocs dev` says when a project uses `access`. */
40
+ export const ACCESS_IN_DEV = 'access: nothing is protected in writedocs dev - every page opens without signing in.';
41
+
42
+ /** The access.json format's version - see docs/dev/docs/protected-sections.mdx. */
43
+ export const ACCESS_MAP_VERSION = 1;
44
+
45
+ /** Where the map goes, from the root of dist/ - outside the site's own
46
+ * folder with a `basePath`: the platform reserves /.writedocs/ and never
47
+ * serves it. */
48
+ export const ACCESS_MAP_FILE = '.writedocs/access.json';
49
+
50
+ /** A navigation item's access rule, or null. */
51
+ export function accessOf(item) {
52
+ return item && typeof item === 'object' && typeof item.access === 'string' ? item.access : null;
53
+ }
54
+
55
+ /** Whether a padlock shows on the item where it's listed. */
56
+ export function isLocked(item) {
57
+ return Boolean(accessOf(item) && item.lock === true);
58
+ }
59
+
60
+ /** The rule on a section's path - its innermost protected item's - or null. */
61
+ export function ruleOf(path = []) {
62
+ let rule = null;
63
+ for (const segment of path) rule = accessOf(segment.items[segment.index]) ?? rule;
64
+ return rule;
65
+ }
66
+
67
+ /** Each item of the navigation, with the rule that applies to it (its own or
68
+ * the closest one above it) - `global.dropdowns` aren't walked: the
69
+ * validator refuses `access` there. */
70
+ function walkItems(navigation, visit) {
71
+ const walk = (node, rule) => {
72
+ if (!node || typeof node !== 'object') return;
73
+ for (const [key] of CHILD_KINDS) {
74
+ if (!Array.isArray(node[key])) continue;
75
+ for (const item of node[key]) {
76
+ const inner = accessOf(item) ?? rule;
77
+ visit(item, inner);
78
+ walk(item, inner);
79
+ }
80
+ }
81
+ };
82
+ if (navigation && !Array.isArray(navigation)) walk(navigation, null);
83
+ }
84
+
85
+ /** Whether any item of the navigation names an access rule. */
86
+ export function usesAccess(navigation) {
87
+ let found = false;
88
+ walkItems(navigation, (item) => {
89
+ if (accessOf(item)) found = true;
90
+ });
91
+ return found;
92
+ }
93
+
94
+ /** The JSON path of the first `access` in the navigation - for a warning's
95
+ * line in writedocs.json - or null. */
96
+ export function firstAccessPath(navigation) {
97
+ const find = (node, path) => {
98
+ if (!node || typeof node !== 'object') return null;
99
+ for (const [key] of CHILD_KINDS) {
100
+ if (!Array.isArray(node[key])) continue;
101
+ for (let i = 0; i < node[key].length; i++) {
102
+ const itemPath = [...path, key, i];
103
+ if (accessOf(node[key][i])) return [...itemPath, 'access'];
104
+ const inner = find(node[key][i], itemPath);
105
+ if (inner) return inner;
106
+ }
107
+ }
108
+ return null;
109
+ };
110
+ return navigation && !Array.isArray(navigation) ? find(navigation, ['navigation']) : null;
111
+ }
112
+
113
+ /** The access rules the navigation names, in order, without repeats. */
114
+ export function accessRules(navigation) {
115
+ const rules = new Set();
116
+ walkItems(navigation, (item) => {
117
+ const rule = accessOf(item);
118
+ if (rule) rules.add(rule);
119
+ });
120
+ return [...rules];
121
+ }
122
+
123
+ /** Every protected page - Map<page id, rule> - by the id writedocs.json
124
+ * names it with (fileIdForEntry() in lib/config.ts): the pages in a
125
+ * protected item's sidebar, however deep, and its own `page`. A page listed
126
+ * under two items keeps the first rule found; a page under any rule is
127
+ * protected, wherever else it's listed. */
128
+ export function protectedPages(navigation) {
129
+ const pages = new Map();
130
+ const add = (id, rule) => {
131
+ const key = navPageId(id);
132
+ if (!pages.has(key)) pages.set(key, rule);
133
+ };
134
+ const collect = (list, rule) => {
135
+ for (const entry of list) {
136
+ if (typeof entry === 'string') add(entry, rule);
137
+ else if (entry && typeof entry === 'object' && !('href' in entry)) {
138
+ if (typeof entry.page === 'string') add(entry.page, rule);
139
+ if (Array.isArray(entry.pages)) collect(entry.pages, rule);
140
+ }
141
+ }
142
+ };
143
+ walkItems(navigation, (item, rule) => {
144
+ if (!rule) return;
145
+ const own = itemPage(item);
146
+ if (own !== null) add(own, rule);
147
+ if (Array.isArray(item.pages)) collect(item.pages, rule);
148
+ });
149
+ return pages;
150
+ }
151
+
152
+ /** The search space of a section - `{ id, searchPublic }` - or null for the
153
+ * public pages. Under a rule: one space per rule, `access.<rule>`, and,
154
+ * when the section is also inside a hidden item, one per hidden item in
155
+ * the rule, `access.<rule>.<hidden space id>` - so a hidden part keeps
156
+ * its search to itself (lib/hidden-sections.js), and a reader signed in to
157
+ * a rule never gets another rule's pages from a search. Without a rule,
158
+ * the hidden item's space, as before. `searchPublic` is the innermost
159
+ * hidden or protected item's. A "." can't be in a rule's name or a hidden
160
+ * space's id, so no two spaces share an id. `rule` defaults to the path's
161
+ * (ruleOf()); a page's own rule can be passed in. */
162
+ export function searchSpaceOf(path = [], rule = ruleOf(path)) {
163
+ const hidden = spaceOf(path);
164
+ if (!rule) return hidden;
165
+ let searchPublic = false;
166
+ for (const segment of path) {
167
+ const item = segment.items[segment.index];
168
+ if (isHidden(item) || accessOf(item)) searchPublic = item.searchPublic === true;
169
+ }
170
+ return { id: hidden ? `access.${rule}.${hidden.id}` : `access.${rule}`, searchPublic };
171
+ }
172
+
173
+ /** The rule whose pages a search space holds, or null for a public or
174
+ * hidden one. */
175
+ export function ruleOfSpace(spaceId) {
176
+ const match = /^access\.([a-z0-9-]+)(?:\.|$)/.exec(spaceId);
177
+ return match ? match[1] : null;
178
+ }
179
+
180
+ /**
181
+ * The map the platform protects a site by - what goes in
182
+ * dist/.writedocs/access.json:
183
+ *
184
+ * { "version": 1, "basePath": "/docs", "rules": { "<rule>": { "paths": [...], "prefixes": [...] } } }
185
+ *
186
+ * `paths` are exact paths as the serving sees them (the basePath in front);
187
+ * `prefixes` are folders (ending in "/") whose every file is the rule's.
188
+ * Built from:
189
+ * - `rules`: every rule writedocs.json names (accessRules()) - each one is
190
+ * in the map, even with nothing to protect (every page under it a draft),
191
+ * so the platform can tell the author a rule isn't set up;
192
+ * - `routes`: the protected addresses the build rendered, `{ slug, rule }`
193
+ * - pages, and the folder redirects that lead only to protected pages
194
+ * ([...slug].astro writes the list); slug "index" is the site's root;
195
+ * - `exists(relPath)`: whether the site folder has a file, for the copies
196
+ * made from a page - its Markdown (`<slug>.md`) and its link-preview
197
+ * image (`og/<slug>.png`);
198
+ * - `spaces`: the search spaces the build indexed (run-pagefind.js).
199
+ * Each page is listed with and without its trailing slash and as its
200
+ * index.html - every way a static host answers for it. Sorted, so the same
201
+ * site gives the same file.
202
+ */
203
+ export function accessMap({ rules: named = [], routes, spaces = [], exists = () => false, basePath = '' }) {
204
+ const rules = new Map();
205
+ const ruleEntry = (rule) => {
206
+ if (!rules.has(rule)) rules.set(rule, { paths: new Set(), prefixes: new Set() });
207
+ return rules.get(rule);
208
+ };
209
+ const at = (address) => `${basePath}${address}`;
210
+ named.forEach(ruleEntry);
211
+ for (const { slug, rule } of routes) {
212
+ const entry = ruleEntry(rule);
213
+ if (slug === 'index') {
214
+ entry.paths.add(at('/'));
215
+ if (basePath) entry.paths.add(basePath);
216
+ entry.paths.add(at('/index.html'));
217
+ } else {
218
+ entry.paths.add(at(`/${slug}/`));
219
+ entry.paths.add(at(`/${slug}`));
220
+ entry.paths.add(at(`/${slug}/index.html`));
221
+ }
222
+ for (const copy of [`${slug}.md`, `og/${slug}.png`]) {
223
+ if (exists(copy)) entry.paths.add(at(`/${copy}`));
224
+ }
225
+ }
226
+ for (const space of spaces) {
227
+ const rule = ruleOfSpace(space);
228
+ if (rule) ruleEntry(rule).prefixes.add(at(`/pagefind-spaces/${space}/`));
229
+ }
230
+ const sorted = [...rules.keys()].sort();
231
+ return {
232
+ version: ACCESS_MAP_VERSION,
233
+ basePath,
234
+ rules: Object.fromEntries(
235
+ sorted.map((rule) => [rule, { paths: [...rules.get(rule).paths].sort(), prefixes: [...rules.get(rule).prefixes].sort() }])
236
+ ),
237
+ };
238
+ }
@@ -34,6 +34,11 @@
34
34
  { "path": "bun.lock", "ignored": true },
35
35
  { "path": "composer.json", "ignored": true },
36
36
  { "path": "composer.lock", "ignored": true },
37
+ { "path": "README.md", "ignored": true },
38
+ { "path": "readme.md", "ignored": true },
39
+ { "path": "docs/Readme.MD", "ignored": true },
40
+ { "path": "docs/README.mdx", "ignored": false },
41
+ { "path": "docs/readme-first.md", "ignored": false },
37
42
  { "path": "node_modules/pkg/index.js", "ignored": true },
38
43
  { "path": "node_modules", "directory": true, "ignored": true },
39
44
  { "path": "examples/app/node_modules/x/a.json", "ignored": true },
@@ -138,7 +143,7 @@
138
143
  },
139
144
  {
140
145
  "name": "default exclusions brought back with !",
141
- "wdignore": "!.well-known/\n!examples/package.json\n!*.sql\n!examples/dist/\n",
146
+ "wdignore": "!.well-known/\n!examples/package.json\n!*.sql\n!examples/dist/\n!docs/README.md\n",
142
147
  "paths": [
143
148
  { "path": ".well-known/security.txt", "ignored": false },
144
149
  { "path": ".well-known", "directory": true, "ignored": false },
@@ -151,7 +156,9 @@
151
156
  { "path": "data/app.db", "ignored": true },
152
157
  { "path": "examples/dist/bundle.zip", "ignored": false },
153
158
  { "path": "dist/bundle.zip", "ignored": true },
154
- { "path": "other/dist/bundle.zip", "ignored": true }
159
+ { "path": "other/dist/bundle.zip", "ignored": true },
160
+ { "path": "docs/README.md", "ignored": false },
161
+ { "path": "README.md", "ignored": true }
155
162
  ]
156
163
  },
157
164
  {