@dogsbay/site-files 0.2.0-beta.146 → 0.2.0-beta.148

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,4 @@
1
+ /** The config error every caller reports as its own (`ConfigError`, `Error`): products.ts and version-menu.ts. */
2
+ export declare class ProductConfigError extends Error {
3
+ name: string;
4
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,4 @@
1
+ /** The config error every caller reports as its own (`ConfigError`, `Error`): products.ts and version-menu.ts. */
2
+ export class ProductConfigError extends Error {
3
+ name = "ProductConfigError";
4
+ }
@@ -28,15 +28,19 @@ function matcher(from) {
28
28
  // Tokens: a literal character, `*` (any characters) or `:name` (one segment). Matched by dynamic
29
29
  // programming over (token, position), O(tokens × length): a regex from a project's rule like
30
30
  // `/*a*a*a*a*b` backtracked exponentially, and a repo's _redirects could hang the build.
31
+ // The two special tokens are longer than one character, so no literal (one character) equals them:
32
+ // a literal `:` (not followed by a letter) stays a colon, not a placeholder
33
+ const ANY = "**any";
34
+ const SEGMENT = "**segment";
31
35
  const tokens = [];
32
36
  for (let i = 0; i < from.length;) {
33
37
  if (from[i] === "*") {
34
- if (tokens[tokens.length - 1] !== "*")
35
- tokens.push("*");
38
+ if (tokens[tokens.length - 1] !== ANY)
39
+ tokens.push(ANY);
36
40
  i++;
37
41
  }
38
42
  else if (from[i] === ":" && /[A-Za-z]/.test(from[i + 1] ?? "")) {
39
- tokens.push(":");
43
+ tokens.push(SEGMENT);
40
44
  i += 2;
41
45
  while (i < from.length && /\w/.test(from[i]))
42
46
  i++;
@@ -52,9 +56,9 @@ function matcher(from) {
52
56
  for (const t of tokens) {
53
57
  const cur = new Uint8Array(n + 1);
54
58
  for (let j = 0; j <= n; j++) {
55
- if (t === "*")
59
+ if (t === ANY)
56
60
  cur[j] = prev[j] || (j > 0 ? cur[j - 1] : 0);
57
- else if (t === ":")
61
+ else if (t === SEGMENT)
58
62
  cur[j] = j > 0 && path[j - 1] !== "/" ? prev[j - 1] || cur[j - 1] : 0;
59
63
  else
60
64
  cur[j] = j > 0 && path[j - 1] === t ? prev[j - 1] : 0;
package/dist/index.d.ts CHANGED
@@ -16,4 +16,6 @@ export * from "./namespaces.js";
16
16
  export * from "./mounts.js";
17
17
  export * from "./markdown-links.js";
18
18
  export * from "./products.js";
19
+ export * from "./version-menu.js";
20
+ export * from "./static-folder.js";
19
21
  export * from "./host-files.js";
package/dist/index.js CHANGED
@@ -16,4 +16,6 @@ export * from "./namespaces.js";
16
16
  export * from "./mounts.js";
17
17
  export * from "./markdown-links.js";
18
18
  export * from "./products.js";
19
+ export * from "./version-menu.js";
20
+ export * from "./static-folder.js";
19
21
  export * from "./host-files.js";
@@ -48,7 +48,9 @@ export declare function prefixSlug(prefix: readonly string[], slug: string): str
48
48
  * @param basePath `""` or `/<seg>` (the site's combined URL prefix), the
49
49
  * prefix the importer already wrote into each href.
50
50
  */
51
- export declare function prefixNavHrefs<T extends PrefixableNavItem>(items: readonly T[], prefix: readonly string[], basePath: string): T[];
51
+ export declare function prefixNavHrefs<T extends PrefixableNavItem>(items: readonly T[], prefix: readonly string[], basePath: string,
52
+ /** A file of `content.static` (a site path without the base path): its link is not this source's. */
53
+ isSiteFile?: (path: string) => boolean): T[];
52
54
  /**
53
55
  * The URL segments that name a product: every source's `name:` when namespaces are active,
54
56
  * else none. A root-relative link starting with one already names its product
@@ -68,6 +70,11 @@ export declare function namespaceNavGroup<T extends PrefixableNavItem>(ns: strin
68
70
  label: string;
69
71
  children: T[];
70
72
  } | undefined;
73
+ /**
74
+ * Whether a site path names a file of `content.static` (its paths as `/x`), as a host serves it:
75
+ * the path, percent-decoded, its folder's `index.html`, or the path with `.html`.
76
+ */
77
+ export declare function staticFileMatcher(files: ReadonlySet<string>): (path: string) => boolean;
71
78
  /**
72
79
  * Prefix INTERNAL-ABSOLUTE refs in a page tree with the source's URL
73
80
  * segments, matching the slug rewrite — so a versioned/localised page's
@@ -94,4 +101,6 @@ export declare function namespaceNavGroup<T extends PrefixableNavItem>(ns: strin
94
101
  * Used for a named source (`["api"]`) and, in the Astro pipeline, versioned
95
102
  * and localized ones too (`["api", "fr", "v2"]`).
96
103
  */
97
- export declare function rewriteContentRefs(tree: unknown, prefixSegs: readonly string[], globalPrefixes: ReadonlySet<string>): void;
104
+ export declare function rewriteContentRefs(tree: unknown, prefixSegs: readonly string[], globalPrefixes: ReadonlySet<string>,
105
+ /** A file of `content.static`, served as it is at the site root: a ref to it is not this source's. */
106
+ isSiteFile?: (path: string) => boolean): void;
@@ -60,7 +60,9 @@ export function prefixSlug(prefix, slug) {
60
60
  * @param basePath `""` or `/<seg>` (the site's combined URL prefix), the
61
61
  * prefix the importer already wrote into each href.
62
62
  */
63
- export function prefixNavHrefs(items, prefix, basePath) {
63
+ export function prefixNavHrefs(items, prefix, basePath,
64
+ /** A file of `content.static` (a site path without the base path): its link is not this source's. */
65
+ isSiteFile) {
64
66
  if (prefix.length === 0)
65
67
  return items.map((item) => ({ ...item }));
66
68
  const match = basePath ? `${basePath}/` : "/";
@@ -69,6 +71,8 @@ export function prefixNavHrefs(items, prefix, basePath) {
69
71
  return h;
70
72
  if (!h.startsWith(match))
71
73
  return h;
74
+ if (isSiteFile?.(`/${h.slice(match.length).split(/[#?]/)[0]}`))
75
+ return h;
72
76
  return `${match}${prefix.join("/")}/${h.slice(match.length)}`;
73
77
  };
74
78
  return items.map((item) => {
@@ -76,7 +80,7 @@ export function prefixNavHrefs(items, prefix, basePath) {
76
80
  if (item.href !== undefined)
77
81
  next.href = href(item.href);
78
82
  if (item.children && item.children.length > 0) {
79
- next.children = prefixNavHrefs(item.children, prefix, basePath);
83
+ next.children = prefixNavHrefs(item.children, prefix, basePath, isSiteFile);
80
84
  }
81
85
  return next;
82
86
  });
@@ -103,6 +107,23 @@ export function namespacePrefixes(sources) {
103
107
  export function namespaceNavGroup(ns, nav) {
104
108
  return ns === undefined ? undefined : { label: namespaceLabel(ns), children: nav };
105
109
  }
110
+ /**
111
+ * Whether a site path names a file of `content.static` (its paths as `/x`), as a host serves it:
112
+ * the path, percent-decoded, its folder's `index.html`, or the path with `.html`.
113
+ */
114
+ export function staticFileMatcher(files) {
115
+ return (path) => {
116
+ let p = path;
117
+ try {
118
+ p = decodeURIComponent(path);
119
+ }
120
+ catch {
121
+ /* not encoded */
122
+ }
123
+ const bare = p.replace(/\/+$/, "");
124
+ return files.has(p) || files.has(`${bare}/index.html`) || (!p.endsWith("/") && files.has(`${p}.html`));
125
+ };
126
+ }
106
127
  /**
107
128
  * Prefix INTERNAL-ABSOLUTE refs in a page tree with the source's URL
108
129
  * segments, matching the slug rewrite — so a versioned/localised page's
@@ -129,7 +150,9 @@ export function namespaceNavGroup(ns, nav) {
129
150
  * Used for a named source (`["api"]`) and, in the Astro pipeline, versioned
130
151
  * and localized ones too (`["api", "fr", "v2"]`).
131
152
  */
132
- export function rewriteContentRefs(tree, prefixSegs, globalPrefixes) {
153
+ export function rewriteContentRefs(tree, prefixSegs, globalPrefixes,
154
+ /** A file of `content.static`, served as it is at the site root: a ref to it is not this source's. */
155
+ isSiteFile) {
133
156
  if (prefixSegs.length === 0)
134
157
  return;
135
158
  const seg = prefixSegs.join("/");
@@ -151,6 +174,8 @@ export function rewriteContentRefs(tree, prefixSegs, globalPrefixes) {
151
174
  const firstSeg = u.slice(1).split(/[/#?]/)[0];
152
175
  if (globalPrefixes.has(firstSeg))
153
176
  return u;
177
+ if (isSiteFile?.(u.split(/[#?]/)[0]))
178
+ return u;
154
179
  return `/${seg}${u}`;
155
180
  };
156
181
  // Raw HTML: rewrite the VALUE of each href="..."/src="..." attribute.
@@ -26,6 +26,9 @@
26
26
  * before. Pure and Worker-safe.
27
27
  */
28
28
  import { type VersionSeo } from "./canonical.js";
29
+ import { ProductConfigError } from "./errors.js";
30
+ import { type VersionMenu } from "./version-menu.js";
31
+ export { ProductConfigError };
29
32
  /** A source, as far as the product model reads it. */
30
33
  export interface ProductSource {
31
34
  name?: string;
@@ -42,6 +45,8 @@ export interface ProductsContent {
42
45
  /** The site-wide list: the unnamed source's, and a product's without its own. */
43
46
  versions?: unknown;
44
47
  defaultVersion?: unknown;
48
+ /** The site's version menu extras (version-menu.ts): every product's unless it has its own. */
49
+ versionMenu?: unknown;
45
50
  locales?: ReadonlyArray<{
46
51
  id: string;
47
52
  }>;
@@ -59,6 +64,8 @@ export interface ProductVersion extends VersionSeo {
59
64
  hidden?: boolean;
60
65
  /** The version's own banner text, instead of the standard eol/prerelease/old-version one. */
61
66
  banner?: string;
67
+ /** "Version: <label>" above each page's title. */
68
+ badge?: boolean;
62
69
  }
63
70
  /** One product, checked. `name` is undefined for the unnamed source's bucket. */
64
71
  export interface Product {
@@ -67,6 +74,8 @@ export interface Product {
67
74
  /** Empty: unversioned (no version segment, no switcher). */
68
75
  versions: ProductVersion[];
69
76
  defaultVersion?: string;
77
+ /** Its version menu's links and limit: its own `versionMenu:`, else the site's. */
78
+ versionMenu?: VersionMenu;
70
79
  }
71
80
  /** Which build a page belongs to. A missing axis is undefined. */
72
81
  export interface UnitKey {
@@ -84,10 +93,8 @@ export interface ProductModel {
84
93
  /** Whether named sources carry their product segment in URLs: always, with a products: block (the unnamed source never does). */
85
94
  productAxis: boolean;
86
95
  defaultLocale?: string;
87
- }
88
- /** The config error every caller reports as its own (`ConfigError`, `Error`). */
89
- export declare class ProductConfigError extends Error {
90
- name: string;
96
+ /** The site's `content.versionMenu`, checked. */
97
+ versionMenu?: VersionMenu;
91
98
  }
92
99
  /**
93
100
  * Read and check `content.products`, with the sources and site-wide
@@ -159,6 +166,17 @@ export declare function unitOf(model: ProductModel, u: UnitKey): UnitInfo;
159
166
  * product whose default is served at its root (`path: ""`), or unversioned.
160
167
  */
161
168
  export declare function productRootRedirects(model: ProductModel): Array<[string, string]>;
169
+ /** Every unit's home (`/gizmo/latest/`), in unit order. */
170
+ export declare function unitHomes(model: ProductModel): string[];
171
+ /**
172
+ * Units with no home page (an imported version whose folder has no index: Tigera's Calico) would
173
+ * leave their home, and every switcher row and redirect pointing at it, a 404. Each such home
174
+ * forwards to the unit's first page in the nav (`navUrls`, depth-first), else its first page by
175
+ * path. Pages of a unit nested inside it (a version at a product's root holds the others'
176
+ * folders) are not its own. `/` is left to the site root's own rule. All paths are site paths
177
+ * with their trailing slash, without the base path.
178
+ */
179
+ export declare function homeForwards(homes: readonly string[], pageUrls: ReadonlySet<string>, navUrls?: readonly string[]): Array<[string, string]>;
162
180
  /**
163
181
  * Where the site root `/` goes on a site with products and no unnamed source
164
182
  * (which owns `/` when there is one): the first product's default home, in
@@ -179,6 +197,8 @@ export interface SwitcherRow {
179
197
  isDefault: boolean;
180
198
  eol?: boolean;
181
199
  prerelease?: boolean;
200
+ /** "Version: <label>" above each page's title. */
201
+ badge?: boolean;
182
202
  /** The version's page list (`<home>_dogsbay/pages.js`), read when the switcher is used. */
183
203
  pagesScript: string;
184
204
  }
@@ -267,3 +287,15 @@ export declare function toPagesScript(key: string, pages: readonly string[]): st
267
287
  * close a `<script>` or break the statement.
268
288
  */
269
289
  export declare function toScript(global: string, value: unknown): string;
290
+ /**
291
+ * A later selection added to a project's parsed config (`content` as written): its products and
292
+ * versions merged in, its sources appended. A product or version already there keeps its
293
+ * settings and default (the project's word wins); a source already there is not added twice.
294
+ * Site-wide `versions:` merge the same way. The result is checked by `productModel` (throws
295
+ * `ProductConfigError`), so a merge that would not build is refused here. The host writes YAML.
296
+ */
297
+ export declare function addToConfig<C extends ProductsContent & {
298
+ sources?: ProductSource[];
299
+ }>(content: C, addition: ProductsContent & {
300
+ sources?: ProductSource[];
301
+ }): C;
package/dist/products.js CHANGED
@@ -26,10 +26,9 @@
26
26
  * before. Pure and Worker-safe.
27
27
  */
28
28
  import { checkVersionsSeo } from "./canonical.js";
29
- /** The config error every caller reports as its own (`ConfigError`, `Error`). */
30
- export class ProductConfigError extends Error {
31
- name = "ProductConfigError";
32
- }
29
+ import { ProductConfigError } from "./errors.js";
30
+ import { readVersionBadge, readVersionMenu } from "./version-menu.js";
31
+ export { ProductConfigError };
33
32
  const NAME = /^[a-z0-9][a-z0-9-]*$/i;
34
33
  const ID = /^[a-z0-9][a-z0-9._-]*$/i;
35
34
  const fail = (msg) => {
@@ -76,6 +75,7 @@ function versionList(raw, at, quoted = false) {
76
75
  return fail(`${at}: "${id}".label must be text`);
77
76
  if (v.banner != null && typeof v.banner !== "string")
78
77
  return fail(`${at}: "${id}".banner must be text`);
78
+ const badge = readVersionBadge(v.badge, `${at}: "${id}"`);
79
79
  out.push({
80
80
  id,
81
81
  label: v.label == null ? id : String(v.label),
@@ -84,6 +84,7 @@ function versionList(raw, at, quoted = false) {
84
84
  ...(v.prerelease ? { prerelease: true } : {}),
85
85
  ...(v.hidden ? { hidden: true } : {}),
86
86
  ...(v.banner ? { banner: v.banner } : {}),
87
+ ...(badge ? { badge: true } : {}),
87
88
  ...(v.canonical !== undefined ? { canonical: v.canonical } : {}),
88
89
  ...(v.noindex !== undefined ? { noindex: v.noindex } : {}),
89
90
  ...(v.sitemap !== undefined ? { sitemap: v.sitemap } : {}),
@@ -165,12 +166,13 @@ export function productModel(content) {
165
166
  if (localeIds.size && !localeIds.has(l))
166
167
  fail(`locale "${l}" is not in content.locales (${[...localeIds].join(", ")})`);
167
168
  }
169
+ const siteMenu = readVersionMenu(content.versionMenu, "content.versionMenu");
168
170
  const siteVersions = versionList(content.versions, "content.versions");
169
171
  const siteDefault = siteVersions ? settle(siteVersions, content.defaultVersion, "content.versions", localeIds) : undefined;
170
172
  const products = [];
171
173
  const byName = new Map();
172
174
  if (sources.some((s) => s.name == null)) {
173
- const bucket = { label: "", versions: siteVersions ?? [], ...(siteDefault ? { defaultVersion: siteDefault } : {}) };
175
+ const bucket = { label: "", versions: siteVersions ?? [], ...(siteDefault ? { defaultVersion: siteDefault } : {}), ...(siteMenu ? { versionMenu: siteMenu } : {}) };
174
176
  products.push(bucket);
175
177
  byName.set(undefined, bucket);
176
178
  }
@@ -192,7 +194,8 @@ export function productModel(content) {
192
194
  if (!own && typeof p.defaultVersion === "number")
193
195
  idOf(p.defaultVersion, `${at}: defaultVersion`, true);
194
196
  const defaultVersion = own ? settle(own, p.defaultVersion, `${at}.versions`, localeIds, true) : siteDefault;
195
- const product = { name, label: p.label ?? name, versions, ...(defaultVersion ? { defaultVersion } : {}) };
197
+ const versionMenu = readVersionMenu(p.versionMenu, `${at}.versionMenu`) ?? siteMenu;
198
+ const product = { name, label: p.label ?? name, versions, ...(defaultVersion ? { defaultVersion } : {}), ...(versionMenu ? { versionMenu } : {}) };
196
199
  products.push(product);
197
200
  byName.set(name, product);
198
201
  }
@@ -253,6 +256,7 @@ export function productModel(content) {
253
256
  // move when a second product is added (the namespace rule drops it for a single named source).
254
257
  productAxis: true,
255
258
  ...(content.defaultLocale ? { defaultLocale: content.defaultLocale } : {}),
259
+ ...(siteMenu ? { versionMenu: siteMenu } : {}),
256
260
  };
257
261
  // Two units at one address would write over each other's pages and page list.
258
262
  const homes = new Map();
@@ -362,6 +366,32 @@ export function productRootRedirects(model) {
362
366
  }
363
367
  return out;
364
368
  }
369
+ /** Every unit's home (`/gizmo/latest/`), in unit order. */
370
+ export function unitHomes(model) {
371
+ return model.units.map((u) => homeOf(unitSegments(model, u)));
372
+ }
373
+ /**
374
+ * Units with no home page (an imported version whose folder has no index: Tigera's Calico) would
375
+ * leave their home, and every switcher row and redirect pointing at it, a 404. Each such home
376
+ * forwards to the unit's first page in the nav (`navUrls`, depth-first), else its first page by
377
+ * path. Pages of a unit nested inside it (a version at a product's root holds the others'
378
+ * folders) are not its own. `/` is left to the site root's own rule. All paths are site paths
379
+ * with their trailing slash, without the base path.
380
+ */
381
+ export function homeForwards(homes, pageUrls, navUrls = []) {
382
+ const out = [];
383
+ const sorted = [...pageUrls].sort();
384
+ for (const home of new Set(homes)) {
385
+ if (home === "/" || pageUrls.has(home))
386
+ continue;
387
+ const inner = homes.filter((h) => h !== home && h.startsWith(home));
388
+ const mine = (u) => u !== home && u.startsWith(home) && !inner.some((h) => u.startsWith(h));
389
+ const to = navUrls.find((u) => mine(u) && pageUrls.has(u)) ?? sorted.find(mine);
390
+ if (to)
391
+ out.push([home, to]);
392
+ }
393
+ return out;
394
+ }
365
395
  /**
366
396
  * Where the site root `/` goes on a site with products and no unnamed source
367
397
  * (which owns `/` when there is one): the first product's default home, in
@@ -392,7 +422,7 @@ export function switcher(model, product, locale) {
392
422
  if (!built.has(unitKeyString(u)))
393
423
  continue;
394
424
  const home = homeOf(unitSegments(model, u));
395
- rows.push({ id: v.id, label: v.label, home, isDefault: v.id === p.defaultVersion, ...(v.eol ? { eol: true } : {}), ...(v.prerelease ? { prerelease: true } : {}), pagesScript: pagesScriptOf(home) });
425
+ rows.push({ id: v.id, label: v.label, home, isDefault: v.id === p.defaultVersion, ...(v.eol ? { eol: true } : {}), ...(v.prerelease ? { prerelease: true } : {}), ...(v.badge ? { badge: true } : {}), pagesScript: pagesScriptOf(home) });
396
426
  }
397
427
  return rows;
398
428
  }
@@ -485,3 +515,81 @@ export function toScript(global, value) {
485
515
  const json = JSON.stringify(value).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
486
516
  return `window.${global}=${json};\n`;
487
517
  }
518
+ /** A source as a config writes it; compared by everything that says what it reads and where it goes. */
519
+ const sourceKey = (s) => JSON.stringify(["name", "version", "locale", "path", "git", "ref", "subdir", "from", "mount"].map((k) => s[k] ?? null));
520
+ /**
521
+ * A later selection added to a project's parsed config (`content` as written): its products and
522
+ * versions merged in, its sources appended. A product or version already there keeps its
523
+ * settings and default (the project's word wins); a source already there is not added twice.
524
+ * Site-wide `versions:` merge the same way. The result is checked by `productModel` (throws
525
+ * `ProductConfigError`), so a merge that would not build is refused here. The host writes YAML.
526
+ */
527
+ export function addToConfig(content, addition) {
528
+ // A version added to versions already there is not the default: the root ("" path) stays the
529
+ // default's, so an added one is served at its id (products) or without a path (site-wide)
530
+ const mergeVersions = (into, more, siteWide = false) => {
531
+ if (!more?.length)
532
+ return into;
533
+ const out = [...(into ?? [])];
534
+ const ids = new Set(out.map((v) => String(v.id)));
535
+ for (const v of more) {
536
+ const add = v;
537
+ if (ids.has(String(add.id)))
538
+ continue;
539
+ if (into?.length && add.path === "") {
540
+ const { path: _root, ...rest } = add;
541
+ out.push(siteWide ? rest : { ...rest, path: String(add.id) });
542
+ }
543
+ else
544
+ out.push(v);
545
+ }
546
+ return out;
547
+ };
548
+ const out = { ...content };
549
+ if (addition.products) {
550
+ const products = Object.assign(Object.create(null), content.products ?? {});
551
+ for (const [name, add] of Object.entries(addition.products)) {
552
+ const have = products[name];
553
+ if (!have) {
554
+ products[name] = add;
555
+ continue;
556
+ }
557
+ const versions = mergeVersions(have.versions, add.versions);
558
+ products[name] = {
559
+ ...add,
560
+ ...have,
561
+ ...(versions ? { versions } : {}),
562
+ ...(have.defaultVersion === undefined && add.defaultVersion !== undefined && !have.versions ? { defaultVersion: add.defaultVersion } : {}),
563
+ };
564
+ }
565
+ out.products = products;
566
+ }
567
+ if (addition.versions?.length && out.products && Object.keys(out.products).length) {
568
+ throw new Error("a config with a products: block takes versions per product, not site-wide versions:");
569
+ }
570
+ if (addition.products && Object.keys(addition.products).length && content.versions?.length) {
571
+ throw new Error("a config with site-wide versions: cannot take a products: block; import the first product as a product too");
572
+ }
573
+ const versions = mergeVersions(content.versions, addition.versions, true);
574
+ if (versions)
575
+ out.versions = versions;
576
+ if (content.defaultVersion === undefined && addition.defaultVersion !== undefined)
577
+ out.defaultVersion = addition.defaultVersion;
578
+ // Site-wide versions: productModel checks only a products: block, so check the rule the loader has
579
+ for (const v of (out.versions ?? [])) {
580
+ if (v.path === "" && v.id !== out.defaultVersion)
581
+ throw new Error(`version "${String(v.id)}" is served at the site's root, which only the default version "${String(out.defaultVersion)}" may be`);
582
+ }
583
+ const seen = new Set((content.sources ?? []).map((s) => sourceKey(s)));
584
+ const folders = new Map((content.sources ?? []).map((s) => [String(s.path), sourceKey(s)]));
585
+ const added = (addition.sources ?? []).filter((s) => !seen.has(sourceKey(s)));
586
+ for (const s of added) {
587
+ const path = s.path;
588
+ // Another source's folder: the host would write the addition's files over it
589
+ if (typeof path === "string" && folders.has(path))
590
+ throw new Error(`source path "${path}" is already another source's; import into another folder`);
591
+ }
592
+ out.sources = [...(content.sources ?? []), ...added];
593
+ productModel(out);
594
+ return out;
595
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * `content.static`: one folder served as it is at the site root (a Docusaurus `static/`:
3
+ * downloads, verification files, the host's own `_redirects`). The rules, agreed with the
4
+ * dogsbay-ssg team 2026-10-30 (plans/tigera-urls.md), decided once for both pipelines from the
5
+ * folder's file list; each host copies the files and reads the host files itself.
6
+ *
7
+ * - `_headers` / `_redirects` at its root are merged with the generated ones (`mergeHeaders` /
8
+ * `mergeRedirects`), never copied over them;
9
+ * - `robots.txt` replaces the generated one (warned about: no `Sitemap:`, no `Content-Signal`);
10
+ * - any other file at a path the build writes fails the build, naming both;
11
+ * - untrusted: passive files only, the rest left out and listed;
12
+ * - served under the base path: host-root files (robots.txt, the host files, verification
13
+ * pages) do nothing there, which is warned about.
14
+ *
15
+ * Pure and Worker-safe: paths in, decisions out.
16
+ */
17
+ /** Whether an untrusted build may serve `path` by its type alone (no HTML, scripts, CSS, XML or SVG). */
18
+ export declare function isPassiveStaticFile(path: string): boolean;
19
+ /**
20
+ * An SVG with nothing a browser runs or acts on when it is opened on its own (an `<img>` never runs
21
+ * anything; the risk is a reader opening the file). One linear pass over the markup, every tag and
22
+ * attribute parsed with its quotes, and anything it cannot read refused. Refused: a DOCTYPE or
23
+ * entity declaration, a processing instruction other than the XML declaration (`<?xml-stylesheet?>`
24
+ * applies an XSLT), a named reference other than XML's five, a non-ASCII or malformed name, an
25
+ * unquoted value, a denied element (script, animations, frames, embeds, form controls, meta, base,
26
+ * link) under any prefix, an `on…` attribute, a URL attribute (href, src, srcset, …) with a scheme
27
+ * other than http(s) or an embedded raster image (`<a>`: http(s) or `#` only), a `<use>` of
28
+ * another file, and `javascript:` / `vbscript:` anywhere. Kept: `<foreignObject>` labels, `&#xa;`
29
+ * line breaks and draw.io's https fallback link, which every draw.io diagram has. From dogsbay-ssg
30
+ * (2026-10-30), rewritten after a review found prefix, quote and entity bypasses.
31
+ */
32
+ export declare function passiveSvg(text: string): boolean;
33
+ /**
34
+ * `passiveSvg` over a file's bytes: decoded as strict UTF-8 first (invalid bytes refuse it), the
35
+ * way every host should call it.
36
+ */
37
+ export declare function passiveSvgBytes(bytes: Uint8Array): boolean;
38
+ /** The largest SVG whose text is checked; a larger one is left out. */
39
+ export declare const PASSIVE_SVG_MAX_BYTES: number;
40
+ export interface StaticFolderPlan {
41
+ /** Files to copy as they are (folder-relative, `/`-separated); `robots.txt` among them when present. */
42
+ copy: string[];
43
+ /** The folder's own `_headers` / `_redirects` (its root only): merged, not copied. */
44
+ headers?: string;
45
+ redirects?: string;
46
+ /** The folder has a `robots.txt` at its root: it replaces the generated one. */
47
+ robots: boolean;
48
+ /** Left out under `untrusted`: not passive. */
49
+ leftOut: string[];
50
+ /** Fatal: a file at a path the build writes. */
51
+ errors: string[];
52
+ warnings: string[];
53
+ }
54
+ /**
55
+ * Decide what a static folder serves. `writes(path)` names what the build itself writes at a
56
+ * folder-relative path (a page's `x/index.html`, `sitemap-index.xml`, …), else undefined.
57
+ * `basePath` is the docs base path (`""` at the host root).
58
+ */
59
+ export declare function staticFolderPlan(files: readonly string[], o: {
60
+ writes: (path: string) => string | undefined;
61
+ untrusted?: boolean;
62
+ basePath?: string;
63
+ label?: string;
64
+ /** An SVG's bytes (undefined: unreadable or over PASSIVE_SVG_MAX_BYTES), so an untrusted build keeps a passive one. */
65
+ readBytes?: (path: string) => Uint8Array | undefined;
66
+ }): StaticFolderPlan;
67
+ /** What a project's `robots.txt` replacing the generated one loses. */
68
+ export declare function staticRobotsWarnings(text: string, label?: string): string[];
@@ -0,0 +1,257 @@
1
+ /**
2
+ * `content.static`: one folder served as it is at the site root (a Docusaurus `static/`:
3
+ * downloads, verification files, the host's own `_redirects`). The rules, agreed with the
4
+ * dogsbay-ssg team 2026-10-30 (plans/tigera-urls.md), decided once for both pipelines from the
5
+ * folder's file list; each host copies the files and reads the host files itself.
6
+ *
7
+ * - `_headers` / `_redirects` at its root are merged with the generated ones (`mergeHeaders` /
8
+ * `mergeRedirects`), never copied over them;
9
+ * - `robots.txt` replaces the generated one (warned about: no `Sitemap:`, no `Content-Signal`);
10
+ * - any other file at a path the build writes fails the build, naming both;
11
+ * - untrusted: passive files only, the rest left out and listed;
12
+ * - served under the base path: host-root files (robots.txt, the host files, verification
13
+ * pages) do nothing there, which is warned about.
14
+ *
15
+ * Pure and Worker-safe: paths in, decisions out.
16
+ */
17
+ /**
18
+ * Files an untrusted build may serve from someone else's repo, by type: what a browser shows or
19
+ * downloads but does not run. The one list both pipelines use (dogsbay-ssg's and ours, merged
20
+ * 2026-10-30). Left out on purpose: HTML, scripts, CSS (it restyles pages and can leak data through
21
+ * selectors), XML (XHTML and XSLT run in it when it is opened on its own) and SVG, which is kept
22
+ * only when `passiveSvg` passes its text.
23
+ */
24
+ const PASSIVE = new Set([
25
+ "png", "jpg", "jpeg", "gif", "webp", "avif", "ico", "bmp", "tif", "tiff",
26
+ "woff", "woff2", "ttf", "otf", "eot",
27
+ "mp4", "webm", "ogv", "ogg", "oga", "mp3", "wav", "m4a", "flac",
28
+ "pdf", "txt", "md", "csv", "tsv", "json", "yaml", "yml", "toml",
29
+ "zip", "gz", "tgz", "tar", "bz2", "xz", "7z",
30
+ "epub", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "odt", "ods", "odp",
31
+ "sh", "ps1", "py", "conf", "ini", "env", "cfg", "pem", "crt", "pub", "asc", "sig", "sha256",
32
+ ]);
33
+ /** Whether an untrusted build may serve `path` by its type alone (no HTML, scripts, CSS, XML or SVG). */
34
+ export function isPassiveStaticFile(path) {
35
+ const name = path.slice(path.lastIndexOf("/") + 1);
36
+ const dot = name.lastIndexOf(".");
37
+ return dot > 0 && PASSIVE.has(name.slice(dot + 1).toLowerCase());
38
+ }
39
+ /** Elements an SVG opened on its own may not hold (their local name, whatever the prefix). */
40
+ const SVG_DENIED = new Set([
41
+ "script", "animate", "animatemotion", "animatetransform", "animatecolor", "set", "discard",
42
+ "iframe", "frame", "frameset", "embed", "object", "applet", "portal", "handler", "listener",
43
+ "form", "input", "button", "textarea", "select", "meta", "base", "link",
44
+ ]);
45
+ /** Attributes whose value is a URL (their local name). */
46
+ const SVG_URL_ATTRS = new Set(["href", "src", "srcset", "poster", "data", "action", "formaction", "base", "background", "codebase", "dynsrc", "lowsrc"]);
47
+ /** XML's own named references; any other (`&colon;`, which a DOCTYPE'd document may decode) is refused. */
48
+ const XML_ENTITIES = { lt: "<", gt: ">", amp: "&", quot: '"', apos: "'" };
49
+ /** A value as the browser reads it: references decoded, control characters and spaces gone. */
50
+ function svgValue(raw) {
51
+ let bad = false;
52
+ const decoded = raw.replace(/&(#x[0-9a-f]+|#\d+|[a-z][a-z0-9]*);?/gi, (_m, n) => {
53
+ if (n[0] !== "#") {
54
+ const named = XML_ENTITIES[n.toLowerCase()];
55
+ if (named === undefined)
56
+ bad = true;
57
+ return named ?? "";
58
+ }
59
+ const code = n[1] === "x" || n[1] === "X" ? parseInt(n.slice(2), 16) : parseInt(n.slice(1), 10);
60
+ return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : "";
61
+ });
62
+ return bad ? undefined : decoded.replace(/[\x00-\x20]+/g, "");
63
+ }
64
+ /**
65
+ * An SVG with nothing a browser runs or acts on when it is opened on its own (an `<img>` never runs
66
+ * anything; the risk is a reader opening the file). One linear pass over the markup, every tag and
67
+ * attribute parsed with its quotes, and anything it cannot read refused. Refused: a DOCTYPE or
68
+ * entity declaration, a processing instruction other than the XML declaration (`<?xml-stylesheet?>`
69
+ * applies an XSLT), a named reference other than XML's five, a non-ASCII or malformed name, an
70
+ * unquoted value, a denied element (script, animations, frames, embeds, form controls, meta, base,
71
+ * link) under any prefix, an `on…` attribute, a URL attribute (href, src, srcset, …) with a scheme
72
+ * other than http(s) or an embedded raster image (`<a>`: http(s) or `#` only), a `<use>` of
73
+ * another file, and `javascript:` / `vbscript:` anywhere. Kept: `<foreignObject>` labels, `&#xa;`
74
+ * line breaks and draw.io's https fallback link, which every draw.io diagram has. From dogsbay-ssg
75
+ * (2026-10-30), rewritten after a review found prefix, quote and entity bypasses.
76
+ */
77
+ export function passiveSvg(text) {
78
+ // Read as UTF-8 only: a browser decodes in the encoding the XML declaration names, and a 7-bit one
79
+ // (ISO-2022-JP) moves quotes out from under this reader. No escape byte, no character that came
80
+ // from invalid UTF-8, no BOM but UTF-8's at the start, no other encoding declared.
81
+ if (/[\x1b\ufffd\ufffe]/.test(text) || text.indexOf("\ufeff", 1) >= 0)
82
+ return false;
83
+ const decl = /^\ufeff?<\?xml[^?]*\?>/.exec(text)?.[0];
84
+ if (decl && /encoding\s*=/i.test(decl) && !/encoding\s*=\s*(["'])(utf-8|utf8|us-ascii)\1/i.test(decl))
85
+ return false;
86
+ // Anywhere in the text (a style, a CDATA script body): a script scheme, once references are read
87
+ const flat = svgValue(text);
88
+ if (flat === undefined || /(javascript|vbscript|livescript):/i.test(flat))
89
+ return false;
90
+ const NAME = /[A-Za-z_][A-Za-z0-9_.:-]*/y;
91
+ const SPACE = /[ \t\r\n]*/y;
92
+ const n = text.length;
93
+ let i = 0;
94
+ while (i < n) {
95
+ const lt = text.indexOf("<", i);
96
+ if (lt < 0)
97
+ break;
98
+ if (text.startsWith("<!--", lt)) {
99
+ const end = text.indexOf("-->", lt + 4);
100
+ if (end < 0)
101
+ return false;
102
+ i = end + 3;
103
+ continue;
104
+ }
105
+ if (text.startsWith("<![CDATA[", lt)) {
106
+ const end = text.indexOf("]]>", lt + 9);
107
+ if (end < 0)
108
+ return false;
109
+ i = end + 3;
110
+ continue;
111
+ }
112
+ if (text[lt + 1] === "?") {
113
+ const end = text.indexOf("?>", lt + 2);
114
+ if (end < 0 || !/^<\?xml[ \t\r\n]/.test(text.slice(lt, lt + 6)) || lt !== text.search(/\S/))
115
+ return false;
116
+ i = end + 2;
117
+ continue;
118
+ }
119
+ if (text[lt + 1] === "!")
120
+ return false; // DOCTYPE, ENTITY and anything else
121
+ let j = lt + 1;
122
+ if (text[j] === "/")
123
+ j++;
124
+ NAME.lastIndex = j;
125
+ const name = NAME.exec(text)?.[0];
126
+ if (!name)
127
+ return false;
128
+ j += name.length;
129
+ const local = name.slice(name.lastIndexOf(":") + 1).toLowerCase();
130
+ if (SVG_DENIED.has(local))
131
+ return false;
132
+ // Attributes, each quoted, until the tag ends
133
+ for (;;) {
134
+ SPACE.lastIndex = j;
135
+ j += SPACE.exec(text)[0].length;
136
+ if (text[j] === ">") {
137
+ j++;
138
+ break;
139
+ }
140
+ if (text[j] === "/" && text[j + 1] === ">") {
141
+ j += 2;
142
+ break;
143
+ }
144
+ NAME.lastIndex = j;
145
+ const attr = NAME.exec(text)?.[0];
146
+ if (!attr)
147
+ return false;
148
+ j += attr.length;
149
+ SPACE.lastIndex = j;
150
+ j += SPACE.exec(text)[0].length;
151
+ if (text[j] !== "=")
152
+ return false;
153
+ j++;
154
+ SPACE.lastIndex = j;
155
+ j += SPACE.exec(text)[0].length;
156
+ const q = text[j];
157
+ if (q !== '"' && q !== "'")
158
+ return false;
159
+ const close = text.indexOf(q, j + 1);
160
+ if (close < 0)
161
+ return false;
162
+ const raw = text.slice(j + 1, close);
163
+ j = close + 1;
164
+ const aLocal = attr.slice(attr.lastIndexOf(":") + 1).toLowerCase();
165
+ if (aLocal.startsWith("on"))
166
+ return false;
167
+ if (!SVG_URL_ATTRS.has(aLocal))
168
+ continue;
169
+ const value = svgValue(raw);
170
+ if (value === undefined)
171
+ return false;
172
+ if (local === "use" && aLocal === "href") {
173
+ if (!value.startsWith("#"))
174
+ return false;
175
+ }
176
+ else if (local === "a") {
177
+ if (!/^(https?:\/\/|#)/i.test(value))
178
+ return false;
179
+ }
180
+ else if (/^[a-z][a-z0-9+.-]*:/i.test(value) && !/^(https?:\/\/|data:image\/(png|jpe?g|gif|webp|avif)[;,])/i.test(value)) {
181
+ return false;
182
+ }
183
+ }
184
+ i = j;
185
+ }
186
+ return true;
187
+ }
188
+ /**
189
+ * `passiveSvg` over a file's bytes: decoded as strict UTF-8 first (invalid bytes refuse it), the
190
+ * way every host should call it.
191
+ */
192
+ export function passiveSvgBytes(bytes) {
193
+ let text;
194
+ try {
195
+ text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
196
+ }
197
+ catch {
198
+ return false;
199
+ }
200
+ return passiveSvg(text);
201
+ }
202
+ /** The largest SVG whose text is checked; a larger one is left out. */
203
+ export const PASSIVE_SVG_MAX_BYTES = 5 * 1024 * 1024;
204
+ /**
205
+ * Decide what a static folder serves. `writes(path)` names what the build itself writes at a
206
+ * folder-relative path (a page's `x/index.html`, `sitemap-index.xml`, …), else undefined.
207
+ * `basePath` is the docs base path (`""` at the host root).
208
+ */
209
+ export function staticFolderPlan(files, o) {
210
+ const label = o.label ?? "content.static";
211
+ const plan = { copy: [], robots: false, leftOut: [], errors: [], warnings: [] };
212
+ const hostRoot = [];
213
+ for (const file of [...files].sort()) {
214
+ if (file === "_headers" || file === "_redirects") {
215
+ plan[file === "_headers" ? "headers" : "redirects"] = file;
216
+ hostRoot.push(file);
217
+ continue;
218
+ }
219
+ const svgOk = () => {
220
+ const bytes = /\.svg$/i.test(file) ? o.readBytes?.(file) : undefined;
221
+ return bytes !== undefined && passiveSvgBytes(bytes);
222
+ };
223
+ if (o.untrusted && !isPassiveStaticFile(file) && !svgOk()) {
224
+ plan.leftOut.push(file);
225
+ continue;
226
+ }
227
+ if (file === "robots.txt") {
228
+ plan.robots = true;
229
+ hostRoot.push(file);
230
+ plan.copy.push(file);
231
+ continue;
232
+ }
233
+ const clash = o.writes(file);
234
+ if (clash) {
235
+ plan.errors.push(`${label}: ${file} is at a path the build writes (${clash}). Rename or remove one.`);
236
+ continue;
237
+ }
238
+ if (!file.includes("/") && /\.html?$/i.test(file))
239
+ hostRoot.push(file);
240
+ plan.copy.push(file);
241
+ }
242
+ if (plan.leftOut.length) {
243
+ plan.warnings.push(`${label}: ${plan.leftOut.length} file(s) left out, as the folder is untrusted (only passive files are served): ${plan.leftOut.slice(0, 5).join(", ")}${plan.leftOut.length > 5 ? ", …" : ""}`);
244
+ }
245
+ const base = (o.basePath ?? "").replace(/\/+$/, "");
246
+ if (base && hostRoot.length) {
247
+ plan.warnings.push(`${label}: ${hostRoot.join(", ")} only work at the host's root, and the folder is served under ${base}/`);
248
+ }
249
+ return plan;
250
+ }
251
+ /** What a project's `robots.txt` replacing the generated one loses. */
252
+ export function staticRobotsWarnings(text, label = "content.static") {
253
+ const out = [`${label}: its robots.txt replaces the generated one, so no Content-Signal line is added`];
254
+ if (!/^\s*sitemap\s*:/im.test(text))
255
+ out.push(`${label}: its robots.txt names no Sitemap:, so crawlers are not pointed at the site's sitemap`);
256
+ return out;
257
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The version menu's extras, read and checked once for the dogsbay CLI and
3
+ * dogsbay-ssg (agreed with the SSG team 2026-10-30, their rules as merged):
4
+ *
5
+ * content:
6
+ * versionMenu:
7
+ * links: [{ label: All versions, href: /archive/ }] # after the versions
8
+ * limit: 5 # the first 5, plus the page's own
9
+ * products:
10
+ * gizmo:
11
+ * versionMenu: {} # a product's own replaces the site's; {} turns it off
12
+ * versions:
13
+ * - { id: "2.0", badge: true } # "Version: 2.0" above the title
14
+ *
15
+ * Whether the menu shows is decided before `limit` (two or more versions that
16
+ * are not hidden), so it is on every version's pages or on none, and its links
17
+ * come only with it. Pure and Worker-safe. See plans/version-menu-extras.md.
18
+ */
19
+ /** A link after the versions: a site path or an http(s) address. */
20
+ export interface VersionMenuLink {
21
+ label: string;
22
+ href: string;
23
+ }
24
+ export interface VersionMenu {
25
+ /** After the versions, below a separator. Empty: none. */
26
+ links: VersionMenuLink[];
27
+ /** List the first `limit` versions, plus the page's own when it comes later. */
28
+ limit?: number;
29
+ }
30
+ /** Whether `href` is a link the version menu takes: a site path or an http(s) address. */
31
+ export declare function isVersionMenuHref(href: unknown): href is string;
32
+ /**
33
+ * Read and check a `versionMenu:` mapping (`at` names it in errors:
34
+ * `content.versionMenu`, `content.products.gizmo.versionMenu`). Undefined when
35
+ * it is not written. `{}` is a menu with no links and no limit: on a product,
36
+ * it turns the site's off.
37
+ */
38
+ export declare function readVersionMenu(raw: unknown, at: string): VersionMenu | undefined;
39
+ /** A version's `badge:`, checked as the other version flags: true or false, never a word. */
40
+ export declare function readVersionBadge(raw: unknown, at: string): boolean | undefined;
41
+ /**
42
+ * The menu's version rows under `limit`: the first `limit`, plus the current
43
+ * one when it comes later. Call only once the menu is shown (two or more rows).
44
+ */
45
+ export declare function limitVersionRows<T>(rows: readonly T[], limit: number | undefined, isCurrent: (row: T) => boolean): T[];
46
+ /**
47
+ * A menu link as a site that serves pages as folders (`/x/`) writes it: an
48
+ * http(s) address as it is; a site path with a leading `basePath` dropped (as
49
+ * for redirects), then under `basePath`, a page given its trailing slash and a
50
+ * file of a known type kept as written. `basePath` is `""` or `/docs`.
51
+ */
52
+ export declare function versionMenuHref(href: string, basePath?: string): string;
@@ -0,0 +1,112 @@
1
+ /**
2
+ * The version menu's extras, read and checked once for the dogsbay CLI and
3
+ * dogsbay-ssg (agreed with the SSG team 2026-10-30, their rules as merged):
4
+ *
5
+ * content:
6
+ * versionMenu:
7
+ * links: [{ label: All versions, href: /archive/ }] # after the versions
8
+ * limit: 5 # the first 5, plus the page's own
9
+ * products:
10
+ * gizmo:
11
+ * versionMenu: {} # a product's own replaces the site's; {} turns it off
12
+ * versions:
13
+ * - { id: "2.0", badge: true } # "Version: 2.0" above the title
14
+ *
15
+ * Whether the menu shows is decided before `limit` (two or more versions that
16
+ * are not hidden), so it is on every version's pages or on none, and its links
17
+ * come only with it. Pure and Worker-safe. See plans/version-menu-extras.md.
18
+ */
19
+ import { ProductConfigError } from "./errors.js";
20
+ /** `/` and then no second `/` or `\`; no whitespace, control characters or backslashes (a URL parser drops or reads them as slashes). */
21
+ const SITE_PATH = /^\/(?![/\\])[^\s\x00-\x1f\\]*$/;
22
+ const WEB = /^https?:\/\/\S+$/;
23
+ const fail = (msg) => {
24
+ throw new ProductConfigError(msg);
25
+ };
26
+ /** Whether `href` is a link the version menu takes: a site path or an http(s) address. */
27
+ export function isVersionMenuHref(href) {
28
+ return typeof href === "string" && (SITE_PATH.test(href) || WEB.test(href));
29
+ }
30
+ /**
31
+ * Read and check a `versionMenu:` mapping (`at` names it in errors:
32
+ * `content.versionMenu`, `content.products.gizmo.versionMenu`). Undefined when
33
+ * it is not written. `{}` is a menu with no links and no limit: on a product,
34
+ * it turns the site's off.
35
+ */
36
+ export function readVersionMenu(raw, at) {
37
+ if (raw === undefined)
38
+ return undefined;
39
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
40
+ return fail(`${at}: expected a mapping (links, limit)`);
41
+ const m = raw;
42
+ const links = [];
43
+ if (m.links != null) {
44
+ if (!Array.isArray(m.links))
45
+ fail(`${at}.links: expected a list of { label, href }`);
46
+ for (const [i, e] of m.links.entries()) {
47
+ const where = `${at}.links[${i}]`;
48
+ if (!e || typeof e !== "object" || Array.isArray(e))
49
+ fail(`${where}: expected a mapping { label, href }`);
50
+ const l = e;
51
+ if (typeof l.label !== "string" || !l.label.trim())
52
+ fail(`${where}: needs a label`);
53
+ if (!isVersionMenuHref(l.href))
54
+ fail(`${where}.href: a path from the site root (/archive/) or an http(s) address; got ${JSON.stringify(l.href ?? null)}`);
55
+ links.push({ label: l.label, href: l.href });
56
+ }
57
+ }
58
+ let limit;
59
+ if (m.limit != null) {
60
+ if (typeof m.limit !== "number" || !Number.isInteger(m.limit) || m.limit < 1)
61
+ fail(`${at}.limit: expected a whole number of 1 or more`);
62
+ limit = m.limit;
63
+ // The default version's pages would list only themselves: a menu with nothing to choose
64
+ if (limit === 1 && !links.length)
65
+ fail(`${at}.limit: 1 needs links`);
66
+ }
67
+ return { links, ...(limit !== undefined ? { limit } : {}) };
68
+ }
69
+ /** A version's `badge:`, checked as the other version flags: true or false, never a word. */
70
+ export function readVersionBadge(raw, at) {
71
+ if (raw == null)
72
+ return undefined;
73
+ if (typeof raw !== "boolean")
74
+ return fail(`${at}.badge must be true or false`);
75
+ return raw;
76
+ }
77
+ /**
78
+ * The menu's version rows under `limit`: the first `limit`, plus the current
79
+ * one when it comes later. Call only once the menu is shown (two or more rows).
80
+ */
81
+ export function limitVersionRows(rows, limit, isCurrent) {
82
+ if (limit === undefined || rows.length <= limit)
83
+ return [...rows];
84
+ const shown = rows.slice(0, limit);
85
+ const current = rows.slice(limit).find(isCurrent);
86
+ return current ? [...shown, current] : shown;
87
+ }
88
+ /** File types a site path is kept as written for: anything else is a page, so a version number (`/archive/v3.30`) is not an extension. */
89
+ const FILE_TYPES = new Set(["pdf", "html", "htm", "zip", "gz", "tgz", "tar", "xz", "bz2", "7z", "json", "xml", "txt", "csv", "tsv", "yaml", "yml", "md", "epub", "png", "jpg", "jpeg", "gif", "svg", "webp", "avif", "ico", "mp4", "webm", "mp3", "wav", "js", "mjs", "css", "wasm", "woff", "woff2", "ttf", "otf", "doc", "docx", "xls", "xlsx", "ppt", "pptx"]);
90
+ /**
91
+ * A menu link as a site that serves pages as folders (`/x/`) writes it: an
92
+ * http(s) address as it is; a site path with a leading `basePath` dropped (as
93
+ * for redirects), then under `basePath`, a page given its trailing slash and a
94
+ * file of a known type kept as written. `basePath` is `""` or `/docs`.
95
+ */
96
+ export function versionMenuHref(href, basePath = "") {
97
+ if (WEB.test(href))
98
+ return href;
99
+ const base = basePath.replace(/\/+$/, "");
100
+ const cut = href.search(/[?#]/);
101
+ let path = cut === -1 ? href : href.slice(0, cut);
102
+ const tail = cut === -1 ? "" : href.slice(cut);
103
+ if (base && (path === base || path.startsWith(`${base}/`)))
104
+ path = path.slice(base.length) || "/";
105
+ if (!path.endsWith("/")) {
106
+ const last = path.slice(path.lastIndexOf("/") + 1);
107
+ const ext = /\.([a-z0-9]+)$/i.exec(last)?.[1]?.toLowerCase();
108
+ if (!ext || !FILE_TYPES.has(ext))
109
+ path += "/";
110
+ }
111
+ return `${base}${path}${tail}`;
112
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dogsbay/site-files",
3
- "version": "0.2.0-beta.146",
3
+ "version": "0.2.0-beta.148",
4
4
  "description": "robots.txt, _headers, llms.txt, sitemaps, redirects and JSON-LD for docs sites; shared by the dogsbay Astro pipeline and dogsbay-ssg, Worker-safe",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",