@tokenoftrust/cli 7.4.1 → 7.4.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/cli",
3
- "version": "7.4.1",
3
+ "version": "7.4.2",
4
4
  "description": "Token of Trust developer CLI — clone a tenant store, run it locally with save→reload, and submit it for preview. Installs the `tot` command.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Token of Trust",
@@ -0,0 +1,261 @@
1
+ // @ts-check
2
+ /**
3
+ * Precedence between the routes a release GENERATES and the redirects its content DECLARES: a route
4
+ * the release generates wins over a declared redirect whose exact source is that route. The redirect
5
+ * is dropped from what the release publishes and reported as a non-blocking warning; it is never a
6
+ * reason to refuse a publish.
7
+ *
8
+ * A redirect declared for a URL that did not exist yet goes stale the day the content grows into it:
9
+ * a leftover `"blog/page/9": "blog"` does nothing while the blog has 8 pages, and would send the 9th
10
+ * page away the day one more post is written. Only EXACT sources yield; a `<dir>/*` rule is a
11
+ * deliberate statement about a whole family of URLs and keeps answering.
12
+ *
13
+ * Pure: callers pass the declaration files they read (`{path, json}`, the shape
14
+ * `declaredRedirectsFromContent` takes) and the route set they know, so the publish, the preview
15
+ * reconcile, the kit and `tot validate` apply one rule.
16
+ * `packages/cli/src/redirect-shadows.mjs` is a byte-identical copy (a test pins it).
17
+ */
18
+
19
+ /** The finding prefix the publish pipeline classifies as non-blocking (`finding-severity`). */
20
+ export const SHADOWED_REDIRECT_PREFIX = "REDIRECT";
21
+
22
+ /** The tenant-wide declaration, and a content collection's slug-rename map. */
23
+ const SITE_REDIRECTS_PATH = "content/redirects.json";
24
+ const COLLECTION_REDIRECTS_PATH = /^content\/([A-Za-z0-9][A-Za-z0-9_-]*)\/redirects\.json$/;
25
+
26
+ /** Posts per collection index page when a collection declares no valid `pageSize`. */
27
+ const DEFAULT_PAGE_SIZE = 12;
28
+
29
+ /**
30
+ * The form a route and a redirect source are compared in: root-absolute, no query or fragment, a
31
+ * trailing slash unless the last segment names a file. Null when `raw` is not a same-origin path.
32
+ * The same normalization the redirect contract applies to a declared source.
33
+ * @param {unknown} raw
34
+ * @returns {string | null}
35
+ */
36
+ export function routeKey(raw) {
37
+ if (typeof raw !== "string") return null;
38
+ const trimmed = raw.trim();
39
+ if (!trimmed.startsWith("/") || trimmed.startsWith("//") || trimmed.includes("*")) return null;
40
+ const path = trimmed.replace(/[?#].*$/, "");
41
+ if (path.includes("..") || path.includes("\\")) return null;
42
+ const collapsed = path.replace(/\/{2,}/g, "/");
43
+ if (collapsed === "/") return "/";
44
+ const segments = collapsed.split("/").filter(Boolean);
45
+ if ((segments[segments.length - 1] ?? "").includes(".")) return collapsed.replace(/\/$/, "");
46
+ return collapsed.endsWith("/") ? collapsed : `${collapsed}/`;
47
+ }
48
+
49
+ /**
50
+ * A matcher over a list of generated route paths, in any slash form.
51
+ * @param {Iterable<string>} paths
52
+ * @returns {(source: string) => boolean}
53
+ */
54
+ export function routeMatcher(paths) {
55
+ const keys = new Set();
56
+ for (const path of paths) {
57
+ const key = routeKey(path);
58
+ if (key) keys.add(key);
59
+ }
60
+ return (source) => keys.has(source);
61
+ }
62
+
63
+ /**
64
+ * @typedef {{file: string, key: string, value: unknown, source: string}} ShadowedRedirect
65
+ * `file` the declaration it came from, `key`/`value` the entry exactly as written, `source` the
66
+ * generated route it would have redirected.
67
+ */
68
+
69
+ /**
70
+ * Split declaration files into the entries that still apply and the ones a generated route shadows.
71
+ * The files come back with the shadowed entries removed and every other entry untouched, so the
72
+ * caller hands them to the redirect contract exactly as it would have handed the originals; a file
73
+ * that is not a key/value object passes through unchanged for the contract to refuse.
74
+ * @template {{path: string, json: unknown}} T
75
+ * @param {readonly T[]} declarations
76
+ * @param {(source: string) => boolean} isRoute called with a source in `routeKey` form
77
+ * @returns {{declarations: T[], shadowed: ShadowedRedirect[]}}
78
+ */
79
+ export function redirectsYieldingToRoutes(declarations, isRoute) {
80
+ /** @type {T[]} */
81
+ const kept = [];
82
+ /** @type {ShadowedRedirect[]} */
83
+ const shadowed = [];
84
+ for (const declaration of declarations ?? []) {
85
+ const collection = COLLECTION_REDIRECTS_PATH.exec(declaration?.path ?? "")?.[1];
86
+ const json = declaration?.json;
87
+ if ((declaration?.path !== SITE_REDIRECTS_PATH && !collection) ||
88
+ !json || typeof json !== "object" || Array.isArray(json)) {
89
+ kept.push(declaration);
90
+ continue;
91
+ }
92
+ /** @type {Record<string, unknown>} */
93
+ const rows = {};
94
+ for (const [key, value] of Object.entries(json)) {
95
+ const source = collection
96
+ ? (key ? routeKey(`/${collection}/${key}/`) : null)
97
+ : (key && !key.startsWith("/") ? routeKey(`/${key}`) : null);
98
+ if (source !== null && isRoute(source)) shadowed.push({ file: declaration.path, key, value, source });
99
+ else rows[key] = value;
100
+ }
101
+ kept.push({ ...declaration, json: rows });
102
+ }
103
+ return { declarations: kept, shadowed };
104
+ }
105
+
106
+ /** @param {number} n */
107
+ function ordinal(n) {
108
+ const tens = n % 100;
109
+ const suffix = tens >= 11 && tens <= 13 ? "th" : ({ 1: "st", 2: "nd", 3: "rd" })[n % 10] ?? "th";
110
+ return `${n}${suffix}`;
111
+ }
112
+
113
+ /** @param {string} collection */
114
+ function collectionName(collection) {
115
+ return collection === "blog" ? "The blog" : `The ${collection} collection`;
116
+ }
117
+
118
+ /**
119
+ * Why the content now generates `source`, as the start of a sentence.
120
+ * @param {string} source a route in `routeKey` form
121
+ */
122
+ export function generatedRouteReason(source) {
123
+ const parts = source.split("/").filter(Boolean);
124
+ const [collection, kind, value] = parts;
125
+ if (collection === "blog" || collection === "the-build") {
126
+ if (parts.length === 3 && kind === "page" && /^[1-9][0-9]*$/.test(value ?? "")) {
127
+ return `${collectionName(collection)} now has a ${ordinal(Number(value))} page`;
128
+ }
129
+ if (parts.length === 3 && (kind === "tag" || kind === "category" || kind === "author")) {
130
+ return `${collectionName(collection)} now has a page for the ${kind} "${value}"`;
131
+ }
132
+ if (parts.length === 2) {
133
+ return `${collection === "blog" ? "A blog post" : `A post in the ${collection} collection`} now lives at ${source}`;
134
+ }
135
+ }
136
+ return `A page now lives at ${source}`;
137
+ }
138
+
139
+ /**
140
+ * The plain-language warning for one shadowed redirect: the file, the exact entry, what now
141
+ * generates that page and why, and what to do.
142
+ * @param {ShadowedRedirect} entry
143
+ */
144
+ export function shadowedRedirectMessage(entry) {
145
+ return `Your ${entry.file} has an old redirect, ${JSON.stringify(entry.key)}: ${JSON.stringify(entry.value)}. ` +
146
+ `${generatedRouteReason(entry.source)}, and that redirect would send it away. ` +
147
+ "The page is served; delete the redirect entry to clear this warning.";
148
+ }
149
+
150
+ /** The warning as a publish finding: `REDIRECT: <message>`. @param {ShadowedRedirect} entry */
151
+ export function shadowedRedirectFinding(entry) {
152
+ return `${SHADOWED_REDIRECT_PREFIX}: ${shadowedRedirectMessage(entry)}`;
153
+ }
154
+
155
+ /**
156
+ * Is a post listed on the live site's index pages? A missing status is published; a scheduled post
157
+ * counts once its time has come.
158
+ * @param {any} post @param {number} now
159
+ */
160
+ function listable(post, now) {
161
+ const status = post?.status ?? "published";
162
+ if (status === "published") return true;
163
+ return status === "scheduled" && typeof post?.scheduledAt === "string" && Date.parse(post.scheduledAt) <= now;
164
+ }
165
+
166
+ /** @param {any} post @param {number} now */
167
+ function visible(post, now) {
168
+ return (post?.status ?? "published") === "unlisted" || listable(post, now);
169
+ }
170
+
171
+ /** @param {unknown} value */
172
+ function taxonomySlug(value) {
173
+ return typeof value === "string" ? value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") : "";
174
+ }
175
+
176
+ /**
177
+ * The routes a store's content generates at the default collection bases: each editorial page at
178
+ * its slug, each visible post, each tag and category archive of a listed post, and every index page
179
+ * of a collection. The publish judges against the routes it actually rendered; this is the same
180
+ * question asked of the content, so authoring tools can warn before a publish.
181
+ * @param {{pages?: {slug?: unknown}[], collections?: Record<string, {posts?: {slug: string, post: any}[], settings?: any}>, now?: number}} content
182
+ * @returns {Set<string>} routes in `routeKey` form
183
+ */
184
+ export function contentGeneratedRoutes({ pages = [], collections = {}, now = Date.now() }) {
185
+ const routes = new Set();
186
+ const add = (/** @type {string} */ path) => {
187
+ const key = routeKey(path);
188
+ if (key) routes.add(key);
189
+ };
190
+ for (const page of pages) if (typeof page?.slug === "string" && page.slug) add(`/${page.slug}`);
191
+ for (const [collection, { posts = [], settings } = {}] of Object.entries(collections)) {
192
+ const pageSize = Number.isInteger(settings?.pageSize) && settings.pageSize > 0 ? settings.pageSize : DEFAULT_PAGE_SIZE;
193
+ let listed = 0;
194
+ for (const { slug, post } of posts) {
195
+ if (visible(post, now)) add(`/${collection}/${slug}`);
196
+ if (!listable(post, now)) continue;
197
+ listed++;
198
+ for (const kind of /** @type {const} */ (["tags", "categories"])) {
199
+ for (const value of Array.isArray(post?.[kind]) ? post[kind] : []) {
200
+ const term = taxonomySlug(value);
201
+ if (term) add(`/${collection}/${kind === "tags" ? "tag" : "category"}/${term}`);
202
+ }
203
+ }
204
+ }
205
+ if (listed > 0) add(`/${collection}`);
206
+ for (let page = 2; page <= Math.ceil(listed / pageSize); page++) add(`/${collection}/page/${page}`);
207
+ }
208
+ return routes;
209
+ }
210
+
211
+ /** The collections whose posts the platform renders at their default base. */
212
+ const POST_COLLECTIONS = /^(blog|the-build)\/(?:posts\/([^/]+)\.json|settings\.json)$/;
213
+
214
+ /**
215
+ * Collects, file by file, what the shadowed-redirect check needs from a store's `content/` tree,
216
+ * keeping only the few fields it reads (a slug, a post's status and taxonomy, a page size), so a
217
+ * caller streaming a large tree never holds it. A file that does not parse is skipped: the content
218
+ * validators own that finding.
219
+ */
220
+ export function createRedirectShadowCollector() {
221
+ /** @type {{slug?: unknown}[]} */
222
+ const pages = [];
223
+ /** @type {Record<string, {posts: {slug: string, post: any}[], settings?: any}>} */
224
+ const collections = {};
225
+ /** @type {{path: string, json: unknown}[]} */
226
+ const declarations = [];
227
+ const collection = (/** @type {string} */ name) => (collections[name] ??= { posts: [] });
228
+ return {
229
+ /**
230
+ * @param {string} rel path under `content/`, e.g. `blog/posts/hello.json`
231
+ * @param {string} text
232
+ */
233
+ add(rel, text) {
234
+ const declaration = rel === "redirects.json" || COLLECTION_REDIRECTS_PATH.test(`content/${rel}`);
235
+ const html = /^pages-html\/(.+)\.html$/.exec(rel);
236
+ const post = POST_COLLECTIONS.exec(rel);
237
+ if (html) {
238
+ pages.push({ slug: html[1] });
239
+ return;
240
+ }
241
+ if (!declaration && !post && !/^pages\/[^/]+\.json$/.test(rel)) return;
242
+ let json;
243
+ try {
244
+ json = JSON.parse(text);
245
+ } catch {
246
+ return;
247
+ }
248
+ if (declaration) declarations.push({ path: `content/${rel}`, json });
249
+ else if (!post) pages.push({ slug: json?.slug });
250
+ else if (post[2] === undefined) collection(post[1] ?? "").settings = { pageSize: json?.pageSize };
251
+ else collection(post[1] ?? "").posts.push({ slug: post[2], post: {
252
+ status: json?.status, scheduledAt: json?.scheduledAt, tags: json?.tags, categories: json?.categories,
253
+ } });
254
+ },
255
+ /** The declared redirects the collected content shadows. @param {number} [now] */
256
+ shadowed(now = Date.now()) {
257
+ const routes = contentGeneratedRoutes({ pages, collections, now });
258
+ return redirectsYieldingToRoutes(declarations, (source) => routes.has(source)).shadowed;
259
+ },
260
+ };
261
+ }
package/src/validate.mjs CHANGED
@@ -16,7 +16,7 @@
16
16
  * point; `validateConfigShape` is exported for focused testing.
17
17
  */
18
18
  import { readFileSync, existsSync, readdirSync, statSync } from "node:fs";
19
- import { join, relative } from "node:path";
19
+ import { join, relative, sep } from "node:path";
20
20
  import { contrastRatio, declaredObligations, isRegulatedCompliance, validateDeclaredConfig } from "./declared-config.mjs";
21
21
  import {
22
22
  foreignTenantSegments,
@@ -24,6 +24,7 @@ import {
24
24
  workspacePathForTenantRelative,
25
25
  } from "./tot-repo-mappings.mjs";
26
26
  import { isForbiddenPublicPath, publicBinaryFindings } from "./public-binaries.mjs";
27
+ import { createRedirectShadowCollector, shadowedRedirectMessage } from "./redirect-shadows.mjs";
27
28
  import { pageSlugFindings } from "./page-slugs.mjs";
28
29
  import { ANALYTICS_DECLARATION_FILE, analyticsDeclarationFindings } from "./analytics-declaration.mjs";
29
30
  import { parseSku, skuCollisions, skuFindings } from "./sku.mjs";
@@ -1206,6 +1207,23 @@ function readJsonSafe(path) {
1206
1207
  return { value: null, error: /** @type {Error} */ (e).message };
1207
1208
  }
1208
1209
  }
1210
+ /**
1211
+ * Declared redirects a generated page shadows (the same rule the publish and the preview reconcile
1212
+ * apply), as warnings naming the file, the entry, why, and what to do.
1213
+ * @param {string} contentDir @param {(p: string) => string} rel
1214
+ */
1215
+ function shadowedRedirectFindings(contentDir, rel) {
1216
+ const collector = createRedirectShadowCollector();
1217
+ for (const p of walk(contentDir, (x) => x.endsWith(".json") || x.endsWith(".html"))) {
1218
+ const path = relative(contentDir, p).split(sep).join("/");
1219
+ if (!/^(redirects\.json|[^/]+\/redirects\.json|pages-html\/.+\.html|pages\/[^/]+\.json|(blog|the-build)\/(settings\.json|posts\/[^/]+\.json))$/.test(path)) continue;
1220
+ collector.add(path, readFileSync(p, "utf8"));
1221
+ }
1222
+ return collector.shadowed().map((entry) => mk(WARN, "redirect-shadowed",
1223
+ rel(join(contentDir, entry.file.slice("content/".length))), shadowedRedirectMessage(entry),
1224
+ `delete ${JSON.stringify(entry.key)} from ${entry.file}`));
1225
+ }
1226
+
1209
1227
  function walk(dir, pred) {
1210
1228
  const out = [];
1211
1229
  if (!existsSync(dir)) return out;
@@ -1441,6 +1459,10 @@ export function validateTenant(tenantDir, opts = {}) {
1441
1459
  // 3b. editorial page slugs — every page must be reachable at its slug on the hosted router.
1442
1460
  findings.push(...editorialSlugFindings(contentDir, pagesDir, rel));
1443
1461
 
1462
+ // 3c. a declared redirect whose source the content now generates a page for: the page is served
1463
+ // and the redirect yields, so this warns rather than refuses.
1464
+ findings.push(...shadowedRedirectFindings(contentDir, rel));
1465
+
1444
1466
  // 4. raw HTML documents — validate + portability + resolution
1445
1467
  const hasChrome = providesChrome(contentDir);
1446
1468
  const htmlFiles = walk(contentDir, (p) => p.endsWith(".html"));