@dogsbay/site-files 0.2.0-beta.144 → 0.2.0-beta.145

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.
package/dist/index.d.ts CHANGED
@@ -15,3 +15,4 @@ export * from "./translations.js";
15
15
  export * from "./namespaces.js";
16
16
  export * from "./mounts.js";
17
17
  export * from "./markdown-links.js";
18
+ export * from "./products.js";
package/dist/index.js CHANGED
@@ -15,3 +15,4 @@ export * from "./translations.js";
15
15
  export * from "./namespaces.js";
16
16
  export * from "./mounts.js";
17
17
  export * from "./markdown-links.js";
18
+ export * from "./products.js";
@@ -0,0 +1,269 @@
1
+ /**
2
+ * Versions per product (`content.products:`): one site holding several
3
+ * products, each with its own version list, default, labels and banners.
4
+ * The dogsbay CLI and dogsbay-ssg read the config through `productModel` and
5
+ * answer every per-unit and site-wide question from it, so the two refuse
6
+ * the same configs and agree on every URL, switcher row and data file.
7
+ * Design: plans/product-versions.md (agreed with the SSG team 2026-10-29).
8
+ *
9
+ * content:
10
+ * products:
11
+ * calico:
12
+ * label: Calico Open Source
13
+ * defaultVersion: "3.32"
14
+ * versions:
15
+ * - { id: next, prerelease: true }
16
+ * - { id: "3.32", path: latest } # served at /calico/latest/
17
+ * - { id: "3.31", eol: true }
18
+ * calico-cloud: { label: Calico Cloud } # unversioned: /calico-cloud/
19
+ * sources:
20
+ * - { ref: calico/3.32, subdir: content, name: calico, version: "3.32" }
21
+ *
22
+ * A unit is (product, locale, version): one build. A version's `id` is the
23
+ * key everywhere (sources, branches, data files, switcher); `path` is only
24
+ * its URL segment (left out: the id; `""`: none). Without a `products:`
25
+ * block `productModel` returns undefined and a config means what it did
26
+ * before. Pure and Worker-safe.
27
+ */
28
+ import { type VersionSeo } from "./canonical.js";
29
+ /** A source, as far as the product model reads it. */
30
+ export interface ProductSource {
31
+ name?: string;
32
+ version?: string | number;
33
+ locale?: string;
34
+ mount?: string;
35
+ /** Shown in error messages (`path`, `ref`, …). */
36
+ path?: string;
37
+ }
38
+ /** `content`, as far as the product model reads it (the parsed config, unchecked). */
39
+ export interface ProductsContent {
40
+ products?: unknown;
41
+ sources?: readonly ProductSource[];
42
+ /** The site-wide list: the unnamed source's, and a product's without its own. */
43
+ versions?: unknown;
44
+ defaultVersion?: unknown;
45
+ locales?: ReadonlyArray<{
46
+ id: string;
47
+ }>;
48
+ defaultLocale?: string;
49
+ }
50
+ /** One version of a product, checked. */
51
+ export interface ProductVersion extends VersionSeo {
52
+ id: string;
53
+ label: string;
54
+ /** The URL segment: the id unless `path:` says otherwise; `""` is none. */
55
+ path: string;
56
+ eol?: boolean;
57
+ prerelease?: boolean;
58
+ /** Served, but left out of the switcher (a version an alias row stands for). */
59
+ hidden?: boolean;
60
+ /** The version's own banner text, instead of the standard eol/prerelease/old-version one. */
61
+ banner?: string;
62
+ }
63
+ /** One product, checked. `name` is undefined for the unnamed source's bucket. */
64
+ export interface Product {
65
+ name?: string;
66
+ label: string;
67
+ /** Empty: unversioned (no version segment, no switcher). */
68
+ versions: ProductVersion[];
69
+ defaultVersion?: string;
70
+ }
71
+ /** Which build a page belongs to. A missing axis is undefined. */
72
+ export interface UnitKey {
73
+ product?: string;
74
+ locale?: string;
75
+ version?: string;
76
+ }
77
+ export interface ProductModel {
78
+ /** In config order; the unnamed bucket, when any source is unnamed, comes first without a `name`. */
79
+ products: Product[];
80
+ /** The units the sources build, in source order (mounts join theirs, adding none). */
81
+ units: UnitKey[];
82
+ /** Whether a locale segment is in URLs (two or more effective locales). */
83
+ localeAxis: boolean;
84
+ /** Whether named sources carry their product segment in URLs: always, with a products: block (the unnamed source never does). */
85
+ productAxis: boolean;
86
+ 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;
91
+ }
92
+ /**
93
+ * Read and check `content.products`, with the sources and site-wide
94
+ * versions it depends on. Undefined when the config has no `products:`
95
+ * block (the caller keeps its own rules). Throws `ProductConfigError`:
96
+ *
97
+ * - every named source names a product in the block (a typo stops the build);
98
+ * - a version's `path` is not another version's id or path, nor a locale code;
99
+ * - `defaultVersion` is in the product's own list and not a prerelease;
100
+ * - a source's version is in its product's list; an unversioned product's sources have none;
101
+ * - a mounted source joins a unit some unmounted source builds: its product's
102
+ * (by `name:`), or the unnamed source's.
103
+ */
104
+ export declare function productModel(content: ProductsContent): ProductModel | undefined;
105
+ /**
106
+ * The unit a source of the config builds (or, for a mounted source, joins):
107
+ * its product, its version (the product's default when it names none) and
108
+ * its locale when the locale axis is on. The model has checked them.
109
+ */
110
+ export declare function sourceUnit(model: ProductModel, s: ProductSource, defaultLocale?: string | undefined): UnitKey;
111
+ /** A unit as one string (`calico/_/3.32`): `_` for a missing axis. Also the data files' path. */
112
+ export declare function unitKeyString(u: UnitKey): string;
113
+ /** The product a unit belongs to (the unnamed bucket for `product: undefined`). */
114
+ export declare function productOf(model: ProductModel, product: string | undefined): Product;
115
+ /** The version a banner points readers to: the product's default, in the unit's locale when built there. */
116
+ export interface BannerTarget {
117
+ id: string;
118
+ label: string;
119
+ home: string;
120
+ }
121
+ /**
122
+ * The banner a unit's pages carry: its own `banner:` text, else a standard kind
123
+ * the tool words (in its own locale). `latest` is the default version to point
124
+ * at; left out on the default version itself.
125
+ */
126
+ export type UnitBanner = ({
127
+ kind: "custom";
128
+ text: string;
129
+ } | {
130
+ kind: "eol" | "prerelease" | "old";
131
+ }) & {
132
+ latest?: BannerTarget;
133
+ };
134
+ /** Everything a unit's build needs to know about itself, without another unit. */
135
+ export interface UnitInfo extends UnitKey {
136
+ /** URL segments under the site's base path: `["calico", "latest"]`. */
137
+ segments: string[];
138
+ /** `/calico/latest/` (under the base path); `/` for a unit with no segment. */
139
+ home: string;
140
+ /** Its version's settings (undefined when unversioned). */
141
+ versionDef?: ProductVersion;
142
+ /** The product's default version (or unversioned): its pages are their own canonical, and it is the product's home. */
143
+ isDefault: boolean;
144
+ /** The unit holding the canonical of this unit's pages, when it is not itself: same product and locale, default version. */
145
+ canonicalUnit?: UnitKey;
146
+ banner?: UnitBanner;
147
+ /** The unit's page list, written by its own build inside its folder: `<home>_dogsbay/pages.js`. */
148
+ pagesScript: string;
149
+ /** The unit's manifest file name (no extension): `_dogsbay/units/<dataKey>.json`. */
150
+ dataKey: string;
151
+ }
152
+ /** The URL segments of a unit, in the CLI's order: product, locale, version path. */
153
+ export declare function unitSegments(model: ProductModel, u: UnitKey): string[];
154
+ /** The answers for one unit. */
155
+ export declare function unitOf(model: ProductModel, u: UnitKey): UnitInfo;
156
+ /**
157
+ * Forwards from a product's root (in each locale) to its default version's
158
+ * home, `[from, to]` site paths: `/gizmo/` → `/gizmo/latest/`. None for a
159
+ * product whose default is served at its root (`path: ""`), or unversioned.
160
+ */
161
+ export declare function productRootRedirects(model: ProductModel): Array<[string, string]>;
162
+ /**
163
+ * Where the site root `/` goes on a site with products and no unnamed source
164
+ * (which owns `/` when there is one): the first product's default home, in
165
+ * the block's order and the default locale. Undefined when `/` is a page.
166
+ */
167
+ export declare function siteRootTarget(model: ProductModel): string | undefined;
168
+ /** The default version of a unit's product, or undefined when it has none (or no such product). */
169
+ export declare function productDefault(model: ProductModel, product: string | undefined): {
170
+ defaultVersion?: string;
171
+ versions: ProductVersion[];
172
+ } | undefined;
173
+ /** One row of a product's version switcher. */
174
+ export interface SwitcherRow {
175
+ id: string;
176
+ label: string;
177
+ /** The version's home: where the row goes when the page is not in it. */
178
+ home: string;
179
+ isDefault: boolean;
180
+ eol?: boolean;
181
+ prerelease?: boolean;
182
+ /** The version's page list (`<home>_dogsbay/pages.js`), read when the switcher is used. */
183
+ pagesScript: string;
184
+ }
185
+ /**
186
+ * The version switcher of a product in one locale: every version it has in
187
+ * that locale, in config order, `hidden` ones left out. Empty for an
188
+ * unversioned product. The same rows on every page of the product.
189
+ */
190
+ export declare function switcher(model: ProductModel, product: string | undefined, locale?: string): SwitcherRow[];
191
+ /** One entry of the product switcher. */
192
+ export interface ProductEntry {
193
+ name: string;
194
+ label: string;
195
+ /** The product's home: its default version's, in the locale when it has it. */
196
+ home: string;
197
+ }
198
+ /** The product switcher: every named product that builds something, in config order. */
199
+ export declare function productSwitcher(model: ProductModel, locale?: string): ProductEntry[];
200
+ /**
201
+ * Where switching to another version takes a reader on `slug` (the page's
202
+ * path inside its unit, `""` for the home): the same page when the target's
203
+ * page list has it, else the target's home (`""`). Without the list (no
204
+ * JavaScript), the home.
205
+ */
206
+ export declare function switchTarget(slug: string, targetPages?: ReadonlySet<string>): string;
207
+ /** What each unit's build writes for the site-wide files (`_dogsbay/units/<dataKey>.json`). */
208
+ export interface UnitManifest {
209
+ schemaVersion: 1;
210
+ product: string | null;
211
+ locale: string | null;
212
+ version: string | null;
213
+ /** Page paths inside the unit (`""` is its home). */
214
+ pages: string[];
215
+ /** Absolute URLs the unit lists in the sitemap. */
216
+ sitemap: string[];
217
+ /** Site paths, `[from, to, status]`. */
218
+ redirects: Array<[string, string, number]>;
219
+ llms?: {
220
+ title: string;
221
+ href: string;
222
+ };
223
+ facets?: Record<string, unknown>;
224
+ }
225
+ /** A unit's manifest from its build's results. */
226
+ export declare function unitManifest(u: UnitKey, m: Omit<UnitManifest, "schemaVersion" | "product" | "locale" | "version">): UnitManifest;
227
+ /** The switcher data every page loads (`_dogsbay/versions.js` / `.json`). */
228
+ export interface VersionsData {
229
+ schemaVersion: 1;
230
+ /** Per product (key `_` for the unnamed source) and locale (`_` without a locale axis): its rows. */
231
+ switchers: Record<string, Record<string, SwitcherRow[]>>;
232
+ /** Per locale (`_` without a locale axis): the product switcher. */
233
+ products: Record<string, ProductEntry[]>;
234
+ }
235
+ /** The site-wide files, from the model and the units' manifests alone. */
236
+ export interface SiteFiles {
237
+ /** Written as `/_dogsbay/versions.js`. Page lists are not here: each unit's build writes its own (`pagesScript`). */
238
+ versions: VersionsData;
239
+ /** Every unit's sitemap URLs, in unit order (for `buildSitemaps`). */
240
+ sitemap: string[];
241
+ /** Every unit's redirects, in unit order (for `resolveRedirects` / `renderRedirectsFile`). */
242
+ redirects: Array<[string, string, number]>;
243
+ /** Every unit's llms.txt entry, for the root llms.txt. */
244
+ llms: Array<{
245
+ title: string;
246
+ href: string;
247
+ }>;
248
+ /** Units the config builds with no manifest yet (not yet built): the caller decides whether that fails. */
249
+ missing: string[];
250
+ }
251
+ /**
252
+ * The site-wide files. Manifests of units the model does not build are
253
+ * refused (a stale `_dogsbay/units/` file would otherwise list a version
254
+ * that no longer exists).
255
+ */
256
+ export declare function siteFiles(model: ProductModel, manifests: readonly UnitManifest[]): SiteFiles;
257
+ /**
258
+ * A unit's page list as the script its build writes at `<home>_dogsbay/pages.js`:
259
+ * it adds the list under `key` (the unit's home) to `window.__DOGSBAY_PAGES__`,
260
+ * so a page that has loaded several units' lists keeps them all.
261
+ */
262
+ export declare function toPagesScript(key: string, pages: readonly string[]): string;
263
+ /**
264
+ * A value as a classic script assigning a global (`window.__DOGSBAY_VERSIONS__=…;`),
265
+ * for a page that must also work from `file://`, where it cannot fetch JSON.
266
+ * `<` and the JavaScript line separators are escaped, so the text cannot
267
+ * close a `<script>` or break the statement.
268
+ */
269
+ export declare function toScript(global: string, value: unknown): string;
@@ -0,0 +1,487 @@
1
+ /**
2
+ * Versions per product (`content.products:`): one site holding several
3
+ * products, each with its own version list, default, labels and banners.
4
+ * The dogsbay CLI and dogsbay-ssg read the config through `productModel` and
5
+ * answer every per-unit and site-wide question from it, so the two refuse
6
+ * the same configs and agree on every URL, switcher row and data file.
7
+ * Design: plans/product-versions.md (agreed with the SSG team 2026-10-29).
8
+ *
9
+ * content:
10
+ * products:
11
+ * calico:
12
+ * label: Calico Open Source
13
+ * defaultVersion: "3.32"
14
+ * versions:
15
+ * - { id: next, prerelease: true }
16
+ * - { id: "3.32", path: latest } # served at /calico/latest/
17
+ * - { id: "3.31", eol: true }
18
+ * calico-cloud: { label: Calico Cloud } # unversioned: /calico-cloud/
19
+ * sources:
20
+ * - { ref: calico/3.32, subdir: content, name: calico, version: "3.32" }
21
+ *
22
+ * A unit is (product, locale, version): one build. A version's `id` is the
23
+ * key everywhere (sources, branches, data files, switcher); `path` is only
24
+ * its URL segment (left out: the id; `""`: none). Without a `products:`
25
+ * block `productModel` returns undefined and a config means what it did
26
+ * before. Pure and Worker-safe.
27
+ */
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
+ }
33
+ const NAME = /^[a-z0-9][a-z0-9-]*$/i;
34
+ const ID = /^[a-z0-9][a-z0-9._-]*$/i;
35
+ const fail = (msg) => {
36
+ throw new ProductConfigError(msg);
37
+ };
38
+ /**
39
+ * An id as text. YAML reads an unquoted `1.0` as the number 1 and `2.10` as
40
+ * 2.1, so the written id is lost: only whole numbers are taken unquoted.
41
+ */
42
+ const idOf = (v, at, quoted = false) => {
43
+ if (v == null)
44
+ return undefined;
45
+ // Inside a products: block every id is quoted text: a parsed number cannot tell 1.0 from 1,
46
+ // and the block is new, so both pipelines can refuse it from the value alone.
47
+ if (quoted && typeof v === "number")
48
+ return fail(`${at}: ${v} is a number; write ids as quoted text ("${v}"), since YAML reads 1.0 as 1`);
49
+ if (typeof v === "number" && !Number.isInteger(v))
50
+ return fail(`${at}: ${v} is read as a number, which drops trailing zeros (1.0 → 1); quote it: "${v}"`);
51
+ if (typeof v !== "string" && typeof v !== "number")
52
+ return fail(`${at}: ${JSON.stringify(v)} must be text`);
53
+ return String(v);
54
+ };
55
+ function versionList(raw, at, quoted = false) {
56
+ if (raw == null)
57
+ return undefined;
58
+ if (!Array.isArray(raw) || raw.length === 0)
59
+ return fail(`${at} must be a non-empty list of versions`);
60
+ const out = [];
61
+ for (const [i, e] of raw.entries()) {
62
+ if (!e || typeof e !== "object" || Array.isArray(e))
63
+ return fail(`${at}[${i}] must be a mapping with an id`);
64
+ const v = e;
65
+ const id = idOf(v.id, `${at}[${i}].id`, quoted);
66
+ if (!id || !ID.test(id))
67
+ return fail(`${at}[${i}]: id ${JSON.stringify(id ?? null)} must be one URL segment of letters, digits, dots, dashes and underscores`);
68
+ const path = v.path == null ? id : idOf(v.path, `${at}: "${id}".path`, quoted);
69
+ if (path !== "" && !ID.test(path))
70
+ return fail(`${at}: "${id}".path ${JSON.stringify(path)} must be "" or one URL segment of letters, digits, dots, dashes and underscores`);
71
+ for (const flag of ["eol", "prerelease", "hidden"]) {
72
+ if (v[flag] != null && typeof v[flag] !== "boolean")
73
+ return fail(`${at}: "${id}".${flag} must be true or false`);
74
+ }
75
+ if (v.label != null && (typeof v.label !== "string" || !v.label.trim()) && typeof v.label !== "number")
76
+ return fail(`${at}: "${id}".label must be text`);
77
+ if (v.banner != null && typeof v.banner !== "string")
78
+ return fail(`${at}: "${id}".banner must be text`);
79
+ out.push({
80
+ id,
81
+ label: v.label == null ? id : String(v.label),
82
+ path,
83
+ ...(v.eol ? { eol: true } : {}),
84
+ ...(v.prerelease ? { prerelease: true } : {}),
85
+ ...(v.hidden ? { hidden: true } : {}),
86
+ ...(v.banner ? { banner: v.banner } : {}),
87
+ ...(v.canonical !== undefined ? { canonical: v.canonical } : {}),
88
+ ...(v.noindex !== undefined ? { noindex: v.noindex } : {}),
89
+ ...(v.sitemap !== undefined ? { sitemap: v.sitemap } : {}),
90
+ });
91
+ }
92
+ return out;
93
+ }
94
+ /**
95
+ * The default version: as given (in the list, not a prerelease), else the
96
+ * first that is not a prerelease. Then every path check that needs it.
97
+ */
98
+ function settle(versions, rawDefault, at, localeIds, quoted = false) {
99
+ const ids = new Set();
100
+ const paths = new Map();
101
+ for (const v of versions) {
102
+ if (ids.has(v.id))
103
+ fail(`${at}: version "${v.id}" is listed twice`);
104
+ ids.add(v.id);
105
+ }
106
+ for (const v of versions) {
107
+ const other = paths.get(v.path);
108
+ if (other !== undefined)
109
+ fail(`${at}: versions "${other}" and "${v.id}" are both served at ${v.path ? `"${v.path}"` : "the product's root (path: \"\")"}`);
110
+ paths.set(v.path, v.id);
111
+ if (v.path !== v.id && ids.has(v.path))
112
+ fail(`${at}: "${v.id}".path "${v.path}" is another version's id`);
113
+ if (localeIds.has(v.path))
114
+ fail(`${at}: "${v.id}".path "${v.path}" is a locale code`);
115
+ }
116
+ const given = idOf(rawDefault, `${at}: defaultVersion`, quoted);
117
+ const dv = given ?? versions.find((v) => !v.prerelease)?.id;
118
+ if (dv === undefined)
119
+ return fail(`${at}: every version is a prerelease; set defaultVersion to the one readers land on`);
120
+ const entry = versions.find((v) => v.id === dv);
121
+ if (!entry)
122
+ return fail(`${at}: defaultVersion "${dv}" is not in its versions (${versions.map((v) => v.id).join(", ")})`);
123
+ if (entry.prerelease)
124
+ fail(`${at}: defaultVersion "${dv}" is a prerelease`);
125
+ for (const v of versions)
126
+ if (v.path === "" && v.id !== dv)
127
+ fail(`${at}: "${v.id}".path: "" is only allowed on the defaultVersion`);
128
+ const seo = checkVersionsSeo(versions, dv);
129
+ if (seo)
130
+ fail(`${at}: ${seo}`);
131
+ return dv;
132
+ }
133
+ /**
134
+ * Read and check `content.products`, with the sources and site-wide
135
+ * versions it depends on. Undefined when the config has no `products:`
136
+ * block (the caller keeps its own rules). Throws `ProductConfigError`:
137
+ *
138
+ * - every named source names a product in the block (a typo stops the build);
139
+ * - a version's `path` is not another version's id or path, nor a locale code;
140
+ * - `defaultVersion` is in the product's own list and not a prerelease;
141
+ * - a source's version is in its product's list; an unversioned product's sources have none;
142
+ * - a mounted source joins a unit some unmounted source builds: its product's
143
+ * (by `name:`), or the unnamed source's.
144
+ */
145
+ export function productModel(content) {
146
+ if (content.products == null)
147
+ return undefined;
148
+ const raw = content.products;
149
+ if (typeof raw !== "object" || Array.isArray(raw))
150
+ return fail("content.products must be a mapping of product name to its settings");
151
+ const sources = content.sources ?? [];
152
+ const localeIds = new Set();
153
+ for (const l of content.locales ?? []) {
154
+ const id = String(l?.id);
155
+ if (!ID.test(id))
156
+ fail(`content.locales: ${JSON.stringify(l?.id)} must be one URL segment of letters, digits, dots, dashes and underscores`);
157
+ localeIds.add(id);
158
+ }
159
+ // Locale codes are URL segments. With content.locales declared, every code used must be one of them.
160
+ for (const l of [content.defaultLocale, ...sources.map((s) => s.locale)]) {
161
+ if (l == null)
162
+ continue;
163
+ if (typeof l !== "string" || !ID.test(l))
164
+ fail(`locale ${JSON.stringify(l)} must be one URL segment of letters, digits, dots, dashes and underscores`);
165
+ if (localeIds.size && !localeIds.has(l))
166
+ fail(`locale "${l}" is not in content.locales (${[...localeIds].join(", ")})`);
167
+ }
168
+ const siteVersions = versionList(content.versions, "content.versions");
169
+ const siteDefault = siteVersions ? settle(siteVersions, content.defaultVersion, "content.versions", localeIds) : undefined;
170
+ const products = [];
171
+ const byName = new Map();
172
+ if (sources.some((s) => s.name == null)) {
173
+ const bucket = { label: "", versions: siteVersions ?? [], ...(siteDefault ? { defaultVersion: siteDefault } : {}) };
174
+ products.push(bucket);
175
+ byName.set(undefined, bucket);
176
+ }
177
+ for (const [name, settings] of Object.entries(raw)) {
178
+ const at = `content.products.${name}`;
179
+ if (!NAME.test(name))
180
+ fail(`${at}: a product name must be one URL segment of letters, digits and dashes`);
181
+ if (localeIds.has(name))
182
+ fail(`${at}: "${name}" is a locale code`);
183
+ const p = (settings ?? {});
184
+ if (typeof p !== "object" || Array.isArray(p))
185
+ fail(`${at} must be a mapping (label, defaultVersion, versions)`);
186
+ if (p.label != null && (typeof p.label !== "string" || !p.label.trim()))
187
+ fail(`${at}.label must be text`);
188
+ const own = versionList(p.versions, `${at}.versions`, true);
189
+ if (!own && p.defaultVersion != null)
190
+ fail(`${at}: defaultVersion without versions`);
191
+ const versions = own ?? siteVersions ?? [];
192
+ if (!own && typeof p.defaultVersion === "number")
193
+ idOf(p.defaultVersion, `${at}: defaultVersion`, true);
194
+ const defaultVersion = own ? settle(own, p.defaultVersion, `${at}.versions`, localeIds, true) : siteDefault;
195
+ const product = { name, label: p.label ?? name, versions, ...(defaultVersion ? { defaultVersion } : {}) };
196
+ products.push(product);
197
+ byName.set(name, product);
198
+ }
199
+ // The unnamed source's version paths share the URL level of product names.
200
+ const bucket = byName.get(undefined);
201
+ for (const v of bucket?.versions ?? []) {
202
+ if (byName.has(v.path))
203
+ fail(`content.versions: "${v.id}".path "${v.path}" is a product name, so both are served at /${v.path}/`);
204
+ }
205
+ const effectiveLocales = new Set(sources.map((s) => s.locale ?? content.defaultLocale).filter((l) => l != null));
206
+ const localeAxis = effectiveLocales.size >= 2;
207
+ const units = [];
208
+ const built = new Set();
209
+ const unitOfSource = (s) => {
210
+ const where = `content.sources (${s.path ?? s.name ?? "unnamed"})`;
211
+ const product = byName.get(s.name);
212
+ if (!product)
213
+ return fail(`${where}: name "${s.name}" is not a product in content.products (${[...byName.keys()].filter(Boolean).join(", ")})`);
214
+ if (s.mount !== undefined && (typeof s.mount !== "string" || !s.mount))
215
+ fail(`${where}: mount must be a path inside the unit`);
216
+ const given = idOf(s.version, `${where}: version`, s.name != null);
217
+ let version;
218
+ if (product.versions.length === 0) {
219
+ if (given !== undefined)
220
+ fail(`${where}: version "${given}", but ${s.name ? `product "${s.name}"` : "the site"} has no versions`);
221
+ }
222
+ else {
223
+ version = given ?? product.defaultVersion;
224
+ if (!product.versions.some((v) => v.id === version))
225
+ fail(`${where}: version "${version}" is not one of ${s.name ? `product "${s.name}"'s` : "content.versions'"} ids (${product.versions.map((v) => v.id).join(", ")})`);
226
+ }
227
+ const locale = localeAxis ? (s.locale ?? content.defaultLocale) : undefined;
228
+ return { ...(s.name != null ? { product: s.name } : {}), ...(locale ? { locale } : {}), ...(version ? { version } : {}) };
229
+ };
230
+ for (const s of sources) {
231
+ if (s.mount !== undefined)
232
+ continue;
233
+ const u = unitOfSource(s);
234
+ const k = unitKeyString(u);
235
+ if (!built.has(k)) {
236
+ built.add(k);
237
+ units.push(u);
238
+ }
239
+ }
240
+ for (const s of sources) {
241
+ if (s.mount === undefined)
242
+ continue;
243
+ const u = unitOfSource(s);
244
+ if (!built.has(unitKeyString(u))) {
245
+ fail(`content.sources (${s.path ?? s.mount}): mount "${s.mount}" joins ${describeUnit(u)}, which no other source builds${s.name ? "" : " (a mount inside a product's version takes that product's name:)"}`);
246
+ }
247
+ }
248
+ const model = {
249
+ products,
250
+ units,
251
+ localeAxis,
252
+ // A products: block always gives named sources their product segment, so a site's URLs do not
253
+ // move when a second product is added (the namespace rule drops it for a single named source).
254
+ productAxis: true,
255
+ ...(content.defaultLocale ? { defaultLocale: content.defaultLocale } : {}),
256
+ };
257
+ // Two units at one address would write over each other's pages and page list.
258
+ const homes = new Map();
259
+ for (const u of units) {
260
+ const home = homeOf(unitSegments(model, u));
261
+ const other = homes.get(home);
262
+ if (other)
263
+ fail(`${describeUnit(other)} and ${describeUnit(u)} are both served at ${home}`);
264
+ homes.set(home, u);
265
+ }
266
+ return model;
267
+ }
268
+ /**
269
+ * The unit a source of the config builds (or, for a mounted source, joins):
270
+ * its product, its version (the product's default when it names none) and
271
+ * its locale when the locale axis is on. The model has checked them.
272
+ */
273
+ export function sourceUnit(model, s, defaultLocale = model.defaultLocale) {
274
+ const product = productOf(model, s.name);
275
+ const version = product.versions.length ? (s.version != null ? String(s.version) : product.defaultVersion) : undefined;
276
+ const locale = model.localeAxis ? (s.locale ?? defaultLocale) : undefined;
277
+ return { ...(s.name != null ? { product: s.name } : {}), ...(locale ? { locale } : {}), ...(version ? { version } : {}) };
278
+ }
279
+ /** A unit as one string (`calico/_/3.32`): `_` for a missing axis. Also the data files' path. */
280
+ export function unitKeyString(u) {
281
+ return `${u.product ?? "_"}/${u.locale ?? "_"}/${u.version ?? "_"}`;
282
+ }
283
+ function describeUnit(u) {
284
+ const parts = [u.product ? `product "${u.product}"` : "the unnamed source", u.locale ? `locale "${u.locale}"` : "", u.version ? `version "${u.version}"` : ""];
285
+ return parts.filter(Boolean).join(", ");
286
+ }
287
+ /** The product a unit belongs to (the unnamed bucket for `product: undefined`). */
288
+ export function productOf(model, product) {
289
+ const p = model.products.find((x) => x.name === product);
290
+ if (!p)
291
+ throw new ProductConfigError(`no product "${product ?? "(unnamed)"}"`);
292
+ return p;
293
+ }
294
+ /** The URL segments of a unit, in the CLI's order: product, locale, version path. */
295
+ export function unitSegments(model, u) {
296
+ const product = productOf(model, u.product);
297
+ const path = u.version === undefined ? "" : product.versions.find((v) => v.id === u.version)?.path ?? u.version;
298
+ return [model.productAxis ? u.product : undefined, model.localeAxis ? u.locale : undefined, path || undefined].filter((s) => !!s);
299
+ }
300
+ const homeOf = (segments) => (segments.length ? `/${segments.join("/")}/` : "/");
301
+ const pagesScriptOf = (home) => `${home}_dogsbay/pages.js`;
302
+ /** The built unit of a product's default version: in `locale` when it has one, else the default locale's, else any. */
303
+ function defaultUnitOf(model, p, locale) {
304
+ const units = model.units.filter((u) => u.product === p.name && u.version === p.defaultVersion);
305
+ return units.find((u) => u.locale === locale) ?? units.find((u) => u.locale === model.defaultLocale) ?? units[0];
306
+ }
307
+ /** The answers for one unit. */
308
+ export function unitOf(model, u) {
309
+ const product = productOf(model, u.product);
310
+ const versionDef = u.version === undefined ? undefined : product.versions.find((v) => v.id === u.version);
311
+ if (u.version !== undefined && !versionDef)
312
+ throw new ProductConfigError(`${describeUnit(u)}: not a version of this product`);
313
+ const segments = unitSegments(model, u);
314
+ const isDefault = !versionDef || versionDef.id === product.defaultVersion;
315
+ const kind = versionDef?.banner
316
+ ? { kind: "custom", text: versionDef.banner }
317
+ : versionDef?.eol
318
+ ? { kind: "eol" }
319
+ : versionDef?.prerelease
320
+ ? { kind: "prerelease" }
321
+ : versionDef && !isDefault
322
+ ? { kind: "old" }
323
+ : undefined;
324
+ const target = kind && !isDefault ? defaultUnitOf(model, product, u.locale) : undefined;
325
+ const targetDef = target && product.versions.find((v) => v.id === target.version);
326
+ const banner = kind && (targetDef ? { ...kind, latest: { id: targetDef.id, label: targetDef.label, home: homeOf(unitSegments(model, target)) } } : kind);
327
+ const home = homeOf(segments);
328
+ // The default version in the same locale, when the config builds it; else the page is its own canonical.
329
+ const sameLocaleDefault = { ...u, version: product.defaultVersion };
330
+ const canonicalUnit = !isDefault && versionDef?.canonical !== "self" && model.units.some((x) => unitKeyString(x) === unitKeyString(sameLocaleDefault)) ? sameLocaleDefault : undefined;
331
+ return {
332
+ ...u,
333
+ segments,
334
+ home,
335
+ ...(versionDef ? { versionDef } : {}),
336
+ isDefault,
337
+ ...(canonicalUnit ? { canonicalUnit } : {}),
338
+ ...(banner ? { banner } : {}),
339
+ pagesScript: pagesScriptOf(home),
340
+ dataKey: unitKeyString(u),
341
+ };
342
+ }
343
+ /**
344
+ * Forwards from a product's root (in each locale) to its default version's
345
+ * home, `[from, to]` site paths: `/gizmo/` → `/gizmo/latest/`. None for a
346
+ * product whose default is served at its root (`path: ""`), or unversioned.
347
+ */
348
+ export function productRootRedirects(model) {
349
+ const out = [];
350
+ for (const p of model.products) {
351
+ if (!p.versions.length)
352
+ continue;
353
+ for (const u of model.units) {
354
+ if (u.product !== p.name || u.version !== p.defaultVersion)
355
+ continue;
356
+ const segments = unitSegments(model, u);
357
+ const root = homeOf(unitSegments(model, { ...u, version: undefined }));
358
+ const home = homeOf(segments);
359
+ if (root !== home && root !== "/")
360
+ out.push([root, home]);
361
+ }
362
+ }
363
+ return out;
364
+ }
365
+ /**
366
+ * Where the site root `/` goes on a site with products and no unnamed source
367
+ * (which owns `/` when there is one): the first product's default home, in
368
+ * the block's order and the default locale. Undefined when `/` is a page.
369
+ */
370
+ export function siteRootTarget(model) {
371
+ if (model.units.some((u) => u.product === undefined))
372
+ return undefined;
373
+ return productSwitcher(model, model.defaultLocale)[0]?.home;
374
+ }
375
+ /** The default version of a unit's product, or undefined when it has none (or no such product). */
376
+ export function productDefault(model, product) {
377
+ return model.products.find((x) => x.name === product);
378
+ }
379
+ /**
380
+ * The version switcher of a product in one locale: every version it has in
381
+ * that locale, in config order, `hidden` ones left out. Empty for an
382
+ * unversioned product. The same rows on every page of the product.
383
+ */
384
+ export function switcher(model, product, locale) {
385
+ const p = productOf(model, product);
386
+ const built = new Set(model.units.map(unitKeyString));
387
+ const rows = [];
388
+ for (const v of p.versions) {
389
+ if (v.hidden)
390
+ continue;
391
+ const u = { ...(product ? { product } : {}), ...(model.localeAxis && locale ? { locale } : {}), version: v.id };
392
+ if (!built.has(unitKeyString(u)))
393
+ continue;
394
+ 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) });
396
+ }
397
+ return rows;
398
+ }
399
+ /** The product switcher: every named product that builds something, in config order. */
400
+ export function productSwitcher(model, locale) {
401
+ const out = [];
402
+ for (const p of model.products) {
403
+ if (!p.name)
404
+ continue;
405
+ const units = model.units.filter((u) => u.product === p.name);
406
+ if (!units.length)
407
+ continue;
408
+ const at = (l) => units.find((u) => u.locale === l && u.version === p.defaultVersion);
409
+ const unit = at(model.localeAxis ? locale : undefined) ?? at(model.defaultLocale) ?? units.find((u) => u.version === p.defaultVersion) ?? units[0];
410
+ out.push({ name: p.name, label: p.label, home: homeOf(unitSegments(model, unit)) });
411
+ }
412
+ return out;
413
+ }
414
+ /**
415
+ * Where switching to another version takes a reader on `slug` (the page's
416
+ * path inside its unit, `""` for the home): the same page when the target's
417
+ * page list has it, else the target's home (`""`). Without the list (no
418
+ * JavaScript), the home.
419
+ */
420
+ export function switchTarget(slug, targetPages) {
421
+ return targetPages?.has(slug) ? slug : "";
422
+ }
423
+ /** A unit's manifest from its build's results. */
424
+ export function unitManifest(u, m) {
425
+ return { schemaVersion: 1, product: u.product ?? null, locale: u.locale ?? null, version: u.version ?? null, ...m };
426
+ }
427
+ /**
428
+ * The site-wide files. Manifests of units the model does not build are
429
+ * refused (a stale `_dogsbay/units/` file would otherwise list a version
430
+ * that no longer exists).
431
+ */
432
+ export function siteFiles(model, manifests) {
433
+ const byKey = new Map();
434
+ for (const m of manifests) {
435
+ const k = unitKeyString({ product: m.product ?? undefined, locale: m.locale ?? undefined, version: m.version ?? undefined });
436
+ if (!model.units.some((u) => unitKeyString(u) === k))
437
+ throw new ProductConfigError(`a manifest for ${k}, which the config does not build`);
438
+ if (byKey.has(k))
439
+ throw new ProductConfigError(`two manifests for ${k}`);
440
+ byKey.set(k, m);
441
+ }
442
+ const locales = model.localeAxis ? [...new Set(model.units.map((u) => u.locale))] : [undefined];
443
+ const switchers = Object.create(null);
444
+ for (const p of model.products) {
445
+ if (!p.versions.length)
446
+ continue;
447
+ const perLocale = Object.create(null);
448
+ for (const l of locales) {
449
+ const rows = switcher(model, p.name, l);
450
+ if (rows.length)
451
+ perLocale[l ?? "_"] = rows;
452
+ }
453
+ switchers[p.name ?? "_"] = perLocale;
454
+ }
455
+ const products = Object.create(null);
456
+ for (const l of locales)
457
+ products[l ?? "_"] = productSwitcher(model, l);
458
+ const ordered = model.units.map((u) => byKey.get(unitKeyString(u))).filter((m) => !!m);
459
+ return {
460
+ versions: { schemaVersion: 1, switchers, products },
461
+ sitemap: ordered.flatMap((m) => m.sitemap),
462
+ redirects: ordered.flatMap((m) => m.redirects),
463
+ llms: ordered.flatMap((m) => (m.llms ? [m.llms] : [])),
464
+ missing: model.units.map(unitKeyString).filter((k) => !byKey.has(k)),
465
+ };
466
+ }
467
+ /**
468
+ * A unit's page list as the script its build writes at `<home>_dogsbay/pages.js`:
469
+ * it adds the list under `key` (the unit's home) to `window.__DOGSBAY_PAGES__`,
470
+ * so a page that has loaded several units' lists keeps them all.
471
+ */
472
+ export function toPagesScript(key, pages) {
473
+ const json = (v) => JSON.stringify(v).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
474
+ return `(window.__DOGSBAY_PAGES__=window.__DOGSBAY_PAGES__||{})[${json(key)}]=${json(pages)};\n`;
475
+ }
476
+ /**
477
+ * A value as a classic script assigning a global (`window.__DOGSBAY_VERSIONS__=…;`),
478
+ * for a page that must also work from `file://`, where it cannot fetch JSON.
479
+ * `<` and the JavaScript line separators are escaped, so the text cannot
480
+ * close a `<script>` or break the statement.
481
+ */
482
+ export function toScript(global, value) {
483
+ if (!/^__DOGSBAY_[A-Z_]+__$/.test(global))
484
+ throw new Error(`toScript: global must look like __DOGSBAY_NAME__; got ${JSON.stringify(global)}`);
485
+ const json = JSON.stringify(value).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
486
+ return `window.${global}=${json};\n`;
487
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dogsbay/site-files",
3
- "version": "0.2.0-beta.144",
3
+ "version": "0.2.0-beta.145",
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",
@@ -17,6 +17,7 @@
17
17
  ],
18
18
  "devDependencies": {
19
19
  "@types/node": "^22.20.1",
20
+ "yaml": "^2.9.0",
20
21
  "typescript": "^5.9.3",
21
22
  "vitest": "^4.1.10"
22
23
  },