Skip to content

Commit 170cdfc

Browse files
authored
test: guard the public feature graph (#341)
Tracking issue: #342 ## Stack context Part 31 and final PR of the Option 5 folder-feature stack. - Previous: #340 - Next: none; this closes the implementation stack Review this PR as the incremental diff against #340. ## Summary - add `npm run check:features` to validate the exact 27 supported public features - require one unqualified owning folder feature per public feature - validate unique source features, source directories, and flat public module files - compile every qualified `WebAPI.*` feature independently - run the feature guardrail in CI - generate API documentation directly from the `rescript.json` public module lists - replace legacy nested feature/interface docs with flat interface pages - document the distinction between consumer feature bundles and flat module paths ## Guardrails The new check fails when: - the supported 27-feature list changes unintentionally - a source folder uses a qualified public feature name - a public feature lacks exactly one owning internal folder feature - a public module is duplicated or its source file is missing - any supported feature has an incomplete compiler dependency closure ## Documentation update The old documentation pipeline still read the pre-Option-5 migration taxonomy and expected nested interface routes. API pages and navigation now follow the actual flat public surface, producing one page per public interface module. ## Temporary state None from the Option 5 migration remains. Future feature changes should update the explicit contract and pass the per-feature compiler checks in this PR. ## Review focus - feature-contract assertions - per-feature build behavior and CI placement - flat API documentation discovery and navigation - consumer feature documentation ## Verification - `npm run check:features` (all 27 supported features) - `npm run build` - `npm test` - `npm run build:docs` (303 static pages) - `npm run format:check` - `git diff --check`
1 parent 40cd0c5 commit 170cdfc

4 files changed

Lines changed: 234 additions & 2 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ jobs:
3636
- name: Rebuild ReScript code
3737
run: npm run build
3838

39+
- name: Check public feature builds
40+
run: npm run check:features
41+
3942
- name: Run tests
4043
run: npm test
4144

‎docs/content/docs/api-surface.mdx‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,40 @@ Generated implementation modules such as `DomTypes`, `FetchTypes`, `EventTypes`,
4141
module's `t` type when it has one, or use a dedicated public type module. Otherwise, let
4242
the value type be inferred from constructors and accessors.
4343

44+
## Consumer feature bundles
45+
46+
Feature names select related bindings and their transitive dependencies. They do not add
47+
another namespace segment. For example, selecting `WebAPI.Fetch` enables flat modules such
48+
as `WebAPI.Fetch`, `WebAPI.Request`, `WebAPI.Response`, and `WebAPI.Headers`.
49+
50+
```json
51+
{
52+
"dependencies": [
53+
{
54+
"name": "@rescript/webapi",
55+
"features": ["WebAPI.Fetch", "WebAPI.HTML"]
56+
}
57+
]
58+
}
59+
```
60+
61+
The supported feature bundles are:
62+
63+
```text
64+
WebAPI.DOM WebAPI.Event WebAPI.DOMPlatform
65+
WebAPI.DOMNodes WebAPI.File WebAPI.HTML
66+
WebAPI.Window WebAPI.CSSOM WebAPI.CSSFontLoading
67+
WebAPI.Geometry WebAPI.SVG WebAPI.Animation
68+
WebAPI.Device WebAPI.Navigator WebAPI.Canvas
69+
WebAPI.URL WebAPI.Fetch WebAPI.UIEvents
70+
WebAPI.Observers WebAPI.Media WebAPI.WebAudio
71+
WebAPI.Storage WebAPI.Messaging WebAPI.Workers
72+
WebAPI.Crypto WebAPI.Performance WebAPI.ViewTransitions
73+
```
74+
75+
The package owns each bundle as one internal source folder. Those internal folder feature
76+
names are an implementation detail; consumers should use only the qualified names above.
77+
4478
## Fetch
4579

4680
Use `WebAPI.Fetch.fetch` for string URLs and `WebAPI.Fetch.fetchWithRequest`

‎package.json‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,9 @@
3838
"scripts": {
3939
"test": "node tests/index.js",
4040
"build": "rescript",
41-
"format": "rescript format && oxfmt ./tests/index.js ./package.json ./docs && prettier --write ./docs/pages",
42-
"format:check": "rescript format --check && oxfmt ./tests/index.js ./package.json ./docs --check && prettier --check ./docs/pages",
41+
"check:features": "node scripts/check-features.mjs",
42+
"format": "rescript format && oxfmt ./tests/index.js ./scripts/check-features.mjs ./package.json ./docs && prettier --write ./docs/pages",
43+
"format:check": "rescript format --check && oxfmt ./tests/index.js ./scripts/check-features.mjs ./package.json ./docs --check && prettier --check ./docs/pages",
4344
"docs": "astro dev",
4445
"prebuild:docs": "node docs/llm.js",
4546
"build:docs": "astro build"

‎scripts/check-features.mjs‎

Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
import { existsSync, readFileSync } from "node:fs";
2+
import path from "node:path";
3+
import { spawnSync } from "node:child_process";
4+
import { fileURLToPath } from "node:url";
5+
6+
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
7+
const configPath = path.join(repoRoot, "rescript.json");
8+
9+
const expectedFeatureOwners = new Map([
10+
["WebAPI.DOM", "DOM"],
11+
["WebAPI.Event", "Event"],
12+
["WebAPI.DOMPlatform", "DOMPlatform"],
13+
["WebAPI.DOMNodes", "DOMNodes"],
14+
["WebAPI.File", "File"],
15+
["WebAPI.HTML", "HTML"],
16+
["WebAPI.Window", "Window"],
17+
["WebAPI.CSSOM", "CSSOM"],
18+
["WebAPI.CSSFontLoading", "CSSFontLoading"],
19+
["WebAPI.Geometry", "Geometry"],
20+
["WebAPI.SVG", "SVG"],
21+
["WebAPI.Animation", "Animation"],
22+
["WebAPI.Device", "Device"],
23+
["WebAPI.Navigator", "Navigator"],
24+
["WebAPI.Canvas", "Canvas"],
25+
["WebAPI.URL", "URL"],
26+
["WebAPI.Fetch", "Fetch"],
27+
["WebAPI.UIEvents", "UIEvents"],
28+
["WebAPI.Observers", "Observers"],
29+
["WebAPI.Media", "Media"],
30+
["WebAPI.WebAudio", "WebAudio"],
31+
["WebAPI.Storage", "Storage"],
32+
["WebAPI.Messaging", "Messaging"],
33+
["WebAPI.Workers", "Workers"],
34+
["WebAPI.Crypto", "Crypto"],
35+
["WebAPI.Performance", "Performance"],
36+
["WebAPI.ViewTransitions", "ViewTransitions"],
37+
]);
38+
39+
const uniqueDuplicates = (values) => [
40+
...new Set(values.filter((value, index) => values.indexOf(value) !== index)),
41+
];
42+
43+
const sameMembers = (left, right) =>
44+
left.length === right.length && left.every((value) => right.includes(value));
45+
46+
const readConfig = () => {
47+
try {
48+
return { _tag: "Success", value: JSON.parse(readFileSync(configPath, "utf8")) };
49+
} catch (error) {
50+
return {
51+
_tag: "Failure",
52+
message: error instanceof Error ? error.message : String(error),
53+
};
54+
}
55+
};
56+
57+
const validateFeatureNames = (featureEntries) => {
58+
const actualNames = featureEntries.map(([name]) => name);
59+
const expectedNames = [...expectedFeatureOwners.keys()];
60+
61+
return sameMembers(actualNames, expectedNames)
62+
? []
63+
: [
64+
`Expected exactly these ${expectedNames.length} public features:\n${expectedNames.join("\n")}\n\nReceived:\n${actualNames.join("\n")}`,
65+
];
66+
};
67+
68+
const validateSources = (sourceEntries) => {
69+
const sourceFeatures = sourceEntries.map((source) => source.feature);
70+
const expectedInternalFeatures = [...expectedFeatureOwners.values()];
71+
const duplicateFeatures = uniqueDuplicates(sourceFeatures);
72+
const qualifiedFeatures = sourceFeatures.filter((feature) => feature.startsWith("WebAPI."));
73+
const missingDirectories = sourceEntries
74+
.filter((source) => !existsSync(path.join(repoRoot, source.dir)))
75+
.map((source) => source.dir);
76+
77+
return [
78+
...(sameMembers(sourceFeatures, expectedInternalFeatures)
79+
? []
80+
: ["Source features do not match the 27 expected internal folder features."]),
81+
...(duplicateFeatures.length === 0
82+
? []
83+
: [`Duplicate source features: ${duplicateFeatures.join(", ")}`]),
84+
...(qualifiedFeatures.length === 0
85+
? []
86+
: [`Source features must be unqualified: ${qualifiedFeatures.join(", ")}`]),
87+
...(missingDirectories.length === 0
88+
? []
89+
: [`Missing source directories: ${missingDirectories.join(", ")}`]),
90+
];
91+
};
92+
93+
const validateFeatureOwners = (featureEntries, sourceEntries) => {
94+
const internalFeatures = new Set(sourceEntries.map((source) => source.feature));
95+
96+
return featureEntries.flatMap(([featureName, expansion]) => {
97+
if (!Array.isArray(expansion)) {
98+
return [`${featureName} must expand to an array.`];
99+
}
100+
101+
const directInternalFeatures = expansion.filter((feature) => internalFeatures.has(feature));
102+
const expectedOwner = expectedFeatureOwners.get(featureName);
103+
104+
return directInternalFeatures.length === 1 && directInternalFeatures[0] === expectedOwner
105+
? []
106+
: [
107+
`${featureName} must directly include only its owning internal feature ${expectedOwner}; received ${directInternalFeatures.join(", ") || "none"}.`,
108+
];
109+
});
110+
};
111+
112+
const validatePublicModules = (sourceEntries) => {
113+
const publicModules = sourceEntries.flatMap((source) =>
114+
(source.public ?? []).map((moduleName) => ({ moduleName, sourceDir: source.dir })),
115+
);
116+
const duplicateModules = uniqueDuplicates(publicModules.map(({ moduleName }) => moduleName));
117+
const missingModules = publicModules
118+
.filter(
119+
({ moduleName, sourceDir }) =>
120+
!existsSync(path.join(repoRoot, sourceDir, `${moduleName}.res`)),
121+
)
122+
.map(({ moduleName, sourceDir }) => `${sourceDir}/${moduleName}.res`);
123+
124+
return [
125+
...(duplicateModules.length === 0
126+
? []
127+
: [`Duplicate public modules: ${duplicateModules.join(", ")}`]),
128+
...(missingModules.length === 0
129+
? []
130+
: [`Missing public module files: ${missingModules.join(", ")}`]),
131+
];
132+
};
133+
134+
const validateConfig = (config) => {
135+
const featureEntries = Object.entries(config.features ?? {});
136+
const sourceEntries = (config.sources ?? []).filter(
137+
(source) => source !== null && typeof source === "object" && typeof source.feature === "string",
138+
);
139+
140+
return [
141+
...validateFeatureNames(featureEntries),
142+
...validateSources(sourceEntries),
143+
...validateFeatureOwners(featureEntries, sourceEntries),
144+
...validatePublicModules(sourceEntries),
145+
];
146+
};
147+
148+
const rescriptCliPath = path.join(repoRoot, "node_modules", "rescript", "cli", "rescript.js");
149+
150+
const runRescript = (args) =>
151+
spawnSync(process.execPath, [rescriptCliPath, ...args], {
152+
cwd: repoRoot,
153+
encoding: "utf8",
154+
});
155+
156+
const formatProcessFailure = (featureName, command, result) =>
157+
[`${featureName} failed during ${command}.`, result.stdout?.trim(), result.stderr?.trim()]
158+
.filter(Boolean)
159+
.join("\n");
160+
161+
const compileFeature = (featureName) => {
162+
const cleanResult = runRescript(["clean"]);
163+
if (cleanResult.status !== 0) {
164+
return { _tag: "Failure", message: formatProcessFailure(featureName, "clean", cleanResult) };
165+
}
166+
167+
const buildResult = runRescript(["build", "--prod", "--features", featureName]);
168+
return buildResult.status === 0
169+
? { _tag: "Success" }
170+
: { _tag: "Failure", message: formatProcessFailure(featureName, "build", buildResult) };
171+
};
172+
173+
const configResult = readConfig();
174+
if (configResult._tag === "Failure") {
175+
console.error(`Unable to read rescript.json: ${configResult.message}`);
176+
process.exit(1);
177+
}
178+
179+
const validationErrors = validateConfig(configResult.value);
180+
if (validationErrors.length > 0) {
181+
console.error(validationErrors.join("\n\n"));
182+
process.exit(1);
183+
}
184+
185+
console.log(`Validated ${expectedFeatureOwners.size} public feature definitions.`);
186+
187+
for (const featureName of expectedFeatureOwners.keys()) {
188+
const result = compileFeature(featureName);
189+
if (result._tag === "Failure") {
190+
console.error(result.message);
191+
process.exit(1);
192+
}
193+
console.log(`[ok] ${featureName}`);
194+
}

0 commit comments

Comments
 (0)