repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(the-system): validate config and document names

e5754b968a7d2f9e076c1c291e321ea1fe068597

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (2)

extensions/the-system/__tests__/documents.test.ts

Modified
5 5 import { afterEach, describe, it } from "vitest";
6 6 import {
7 7 discoverProjectRoot,
8 + parseDocumentId,
9 + parseSystemConfig,
8 10 resolveGovernedPath,
9 11 SystemDocumentError,
12 + validateFilename,
10 13 } from "../documents.ts";
12 15 const temporary: string[] = [];
93 +describe("system config", () => {
94 + it("accepts only the exact versioned shape", () => {
95 + assert.deepEqual(parseSystemConfig('{"prefix":"PX","schemaVersion":1,"styleVersion":1}'), {
96 + prefix: "PX",
97 + schemaVersion: 1,
98 + styleVersion: 1,
99 + });
100 + });
102 + it.each([
103 + ["malformed JSON", "{"],
104 + ["unknown key", '{"prefix":"PX","schemaVersion":1,"styleVersion":1,"extra":true}'],
105 + ["missing key", '{"prefix":"PX","schemaVersion":1}'],
106 + ["short prefix", '{"prefix":"P","schemaVersion":1,"styleVersion":1}'],
107 + ["lowercase prefix", '{"prefix":"px","schemaVersion":1,"styleVersion":1}'],
108 + ["zero schema", '{"prefix":"PX","schemaVersion":0,"styleVersion":1}'],
109 + ["fractional style", '{"prefix":"PX","schemaVersion":1,"styleVersion":1.5}'],
110 + ])("rejects %s", (_name, source) =>
111 + assert.throws(() => parseSystemConfig(source), SystemDocumentError),
112 + );
113 +});
115 +describe("document IDs and filenames", () => {
116 + it.each([
117 + ["PX-SPEC-001", "spec", 1],
118 + ["PX-ROADMAP-999", "roadmap", 999],
119 + ["PX-PLAN-1000", "plan", 1000],
120 + ["PX-ISSUE-042", "issue", 42],
121 + ["PX-RESEARCH-007", "research", 7],
122 + ] as const)("parses %s", (id, type, sequence) => {
123 + assert.deepEqual(parseDocumentId(id, "PX"), { id, prefix: "PX", type, sequence });
124 + });
126 + it.each([
127 + "P-SPEC-001",
128 + "px-SPEC-001",
129 + "PX-spec-001",
130 + "PX-SPEC-01",
131 + "PX-SPEC-000",
132 + "PX-SPEC-0001",
133 + "PX-TEST-001",
134 + "PX-SPEC-001-slug",
135 + ])("rejects invalid ID %s", (id) =>
136 + assert.throws(() => parseDocumentId(id), /Invalid document ID/),
137 + );
139 + it("rejects a foreign configured prefix", () =>
140 + assert.throws(() => parseDocumentId("AB-SPEC-001", "PX"), /prefix PX/));
142 + it("accepts a matching type directory, ID, and slug", () => {
143 + assert.doesNotThrow(() =>
144 + validateFilename(
145 + "/project/.system/specs/PX-SPEC-001-login-flow.html",
146 + { id: "PX-SPEC-001", type: "spec" },
147 + "PX",
148 + ),
149 + );
150 + });
152 + it.each([
153 + "/project/.system/specs/PX-SPEC-002-login-flow.html",
154 + "/project/.system/specs/PX-SPEC-001-Login.html",
155 + "/project/.system/plans/PX-SPEC-001-login-flow.html",
156 + "/project/.system/specs/PX-SPEC-001-login_flow.html",
157 + ])("rejects mismatched filename %s", (filename) => {
158 + assert.throws(
159 + () => validateFilename(filename, { id: "PX-SPEC-001", type: "spec" }, "PX"),
160 + /Filename mismatch/,
161 + );
162 + });
163 +});

extensions/the-system/documents.ts

Modified
44 44 return target;
47 +export const DOCUMENT_TYPES = ["spec", "roadmap", "plan", "issue", "research"] as const;
48 +export type DocumentType = (typeof DOCUMENT_TYPES)[number];
49 +export type SystemConfig = Readonly<{ prefix: string; schemaVersion: number; styleVersion: number }>;
50 +export type ParsedDocumentId = Readonly<{
51 + id: string;
52 + prefix: string;
53 + type: DocumentType;
54 + sequence: number;
55 +}>;
56 +export type SpecMetadata = Readonly<{ id: string; type: "spec" }>;
57 +export type RoadmapMetadata = Readonly<{ id: string; type: "roadmap"; spec: string }>;
58 +export type PlanMetadata = Readonly<{
59 + id: string;
60 + type: "plan";
61 + spec: string;
62 + roadmap?: string;
63 + phase?: number;
64 +}>;
65 +export type IssueMetadata = Readonly<{
66 + id: string;
67 + type: "issue";
68 + status: "open" | "fixed";
69 + specs: readonly string[];
70 +}>;
71 +export type ResearchMetadata = Readonly<{
72 + id: string;
73 + type: "research";
74 + capturedAt: string;
75 + sources?: readonly string[];
76 +}>;
77 +export type DocumentMetadata =
78 + | SpecMetadata
79 + | RoadmapMetadata
80 + | PlanMetadata
81 + | IssueMetadata
82 + | ResearchMetadata;
84 +const PREFIX = /^[A-Z][A-Z0-9]{1,7}$/;
85 +const SLUG = "[a-z0-9]+(?:-[a-z0-9]+)*";
86 +const TYPE_BY_TOKEN = new Map(DOCUMENT_TYPES.map((type) => [type.toUpperCase(), type]));
87 +const DIRECTORY_BY_TYPE: Readonly<Record<DocumentType, string>> = {
88 + spec: "specs",
89 + roadmap: "roadmaps",
90 + plan: "plans",
91 + issue: "issues",
92 + research: "research",
93 +};
95 +const objectValue = (value: unknown, label: string): Record<string, unknown> => {
96 + if (typeof value !== "object" || value === null || Array.isArray(value)) {
97 + throw new SystemDocumentError("json.shape", `${label} must be a JSON object`);
98 + }
99 + return value as Record<string, unknown>;
101 +const exactKeys = (
102 + value: Record<string, unknown>,
103 + required: readonly string[],
104 + optional: readonly string[] = [],
105 +) => {
106 + const actual = Object.keys(value).sort();
107 + const allowed = new Set([...required, ...optional]);
108 + if (required.some((key) => !(key in value)) || actual.some((key) => !allowed.has(key))) {
109 + throw new SystemDocumentError(
110 + "json.keys",
111 + `Expected keys ${[...required, ...optional].sort().join(", ")}; received ${actual.join(", ")}`,
112 + );
115 +const positiveInteger = (value: unknown) =>
116 + typeof value === "number" && Number.isInteger(value) && value > 0;
118 +export function parseSystemConfig(source: string): SystemConfig {
119 + let parsed: unknown;
120 + try {
121 + parsed = JSON.parse(source);
122 + } catch {
123 + throw new SystemDocumentError("config.invalid-json", "Invalid config JSON");
125 + const value = objectValue(parsed, "Config");
126 + exactKeys(value, ["prefix", "schemaVersion", "styleVersion"]);
127 + if (typeof value.prefix !== "string" || !PREFIX.test(value.prefix)) {
128 + throw new SystemDocumentError("config.prefix", "Invalid project prefix");
130 + if (!positiveInteger(value.schemaVersion) || !positiveInteger(value.styleVersion)) {
131 + throw new SystemDocumentError(
132 + "config.version",
133 + "Schema and style versions must be positive integers",
134 + );
136 + return {
137 + prefix: value.prefix,
138 + schemaVersion: value.schemaVersion as number,
139 + styleVersion: value.styleVersion as number,
140 + };
143 +export function parseDocumentId(source: string, expectedPrefix?: string): ParsedDocumentId {
144 + const match = /^([A-Z][A-Z0-9]{1,7})-(SPEC|ROADMAP|PLAN|ISSUE|RESEARCH)-([0-9]{3,})$/.exec(
145 + source,
146 + );
147 + const sequence = match ? Number(match[3]) : 0;
148 + const canonical = sequence > 0 ? String(sequence).padStart(3, "0") : "";
149 + if (!match || match[3] !== canonical) {
150 + throw new SystemDocumentError("id.invalid", `Invalid document ID: ${source}`);
152 + if (expectedPrefix && match[1] !== expectedPrefix) {
153 + throw new SystemDocumentError(
154 + "id.prefix",
155 + `Document ID must use prefix ${expectedPrefix}: ${source}`,
156 + );
158 + return {
159 + id: source,
160 + prefix: match[1],
161 + type: TYPE_BY_TOKEN.get(match[2]) as DocumentType,
162 + sequence,
163 + };
166 +export function validateFilename(
167 + filename: string,
168 + metadata: DocumentMetadata,
169 + prefix: string,
170 +): void {
171 + const parsed = parseDocumentId(metadata.id, prefix);
172 + const expectedDirectory = DIRECTORY_BY_TYPE[metadata.type];
173 + const directory = path.basename(path.dirname(filename));
174 + const pattern = new RegExp(`^${metadata.id}-${SLUG}\\.html$`);
175 + if (
176 + parsed.type !== metadata.type ||
177 + directory !== expectedDirectory ||
178 + !pattern.test(path.basename(filename))
179 + ) {
180 + throw new SystemDocumentError(
181 + "document.filename",
182 + `Filename mismatch for ${metadata.id}: ${filename}`,
183 + );