@maniumek/suwgate 0.1.1 → 0.3.0

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.
Files changed (54) hide show
  1. package/README.md +80 -17
  2. package/dist/cli.js +11 -2
  3. package/dist/eslint/index.d.ts +1 -0
  4. package/dist/eslint/index.js +5 -1
  5. package/dist/gate/check.js +10 -2
  6. package/dist/gate/config.d.ts +8 -1
  7. package/dist/gate/config.js +33 -2
  8. package/dist/gate/contract.d.ts +7 -0
  9. package/dist/gate/plan.js +7 -2
  10. package/dist/gate/report.js +1 -1
  11. package/dist/guards/comments/eslint.d.ts +1 -0
  12. package/dist/guards/comments/eslint.js +4 -2
  13. package/dist/guards/dotnet/index.js +2 -1
  14. package/dist/guards/dotnet/suwbackkitWiring.d.ts +2 -0
  15. package/dist/guards/dotnet/suwbackkitWiring.js +31 -0
  16. package/dist/guards/repository/configContents.d.ts +3 -0
  17. package/dist/guards/repository/configContents.js +330 -0
  18. package/dist/guards/repository/docsPaths.d.ts +2 -0
  19. package/dist/guards/repository/docsPaths.js +30 -6
  20. package/dist/guards/repository/forbiddenNames.js +5 -2
  21. package/dist/guards/repository/index.js +4 -0
  22. package/dist/guards/repository/noRawColors.js +3 -2
  23. package/dist/guards/repository/repositoryLayout.js +20 -2
  24. package/dist/guards/repository/requiredFiles.js +37 -8
  25. package/dist/guards/repository/suwfrontkitWiring.d.ts +2 -0
  26. package/dist/guards/repository/suwfrontkitWiring.js +52 -0
  27. package/dist/guards/repository/text.d.ts +1 -0
  28. package/dist/guards/repository/text.js +38 -0
  29. package/dist/guards/repository/vsCodeSettings.js +1 -1
  30. package/dist/profiles/contract.d.ts +1 -0
  31. package/dist/profiles/contract.js +6 -5
  32. package/dist/profiles/criteria.d.ts +1 -0
  33. package/dist/profiles/criteria.js +1 -1
  34. package/dist/profiles/criteriaRan.d.ts +21 -0
  35. package/dist/profiles/criteriaRan.js +109 -0
  36. package/dist/profiles/database.js +2 -2
  37. package/dist/profiles/dotnet.d.ts +3 -0
  38. package/dist/profiles/dotnet.js +30 -10
  39. package/dist/profiles/dotnetGuards.d.ts +3 -0
  40. package/dist/profiles/dotnetGuards.js +38 -0
  41. package/dist/profiles/everyRepository.js +2 -0
  42. package/dist/profiles/index.d.ts +2 -0
  43. package/dist/profiles/index.js +2 -0
  44. package/dist/profiles/library.js +9 -7
  45. package/dist/profiles/node.js +20 -7
  46. package/dist/profiles/reports.d.ts +35 -0
  47. package/dist/profiles/reports.js +60 -0
  48. package/dist/profiles/shell.d.ts +7 -0
  49. package/dist/profiles/shell.js +37 -0
  50. package/dist/profiles/verdict.d.ts +9 -0
  51. package/dist/profiles/verdict.js +120 -0
  52. package/dist/profiles/web.js +19 -3
  53. package/package.json +2 -2
  54. package/schema/suwgate.schema.json +32 -1
@@ -0,0 +1,330 @@
1
+ import path from "node:path";
2
+ import { parse as parseYaml } from "yaml";
3
+ import { npmDependencies } from "./packageManifests.js";
4
+ import { baseName, inProfileDirectory, isRecord, lineAt, numberedLines, parseJson, parseJsonc } from "./text.js";
5
+ const SUWGATE = "@maniumek/suwgate";
6
+ const NODE_PROFILES = ["web", "library"];
7
+ const EXACT_VERSION = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
8
+ const ROLL_FORWARD_ALLOWED = ["patch", "feature", "minor", "latestPatch", "latestFeature", "latestMinor", "disable"];
9
+ const ROLL_FORWARD_MAJOR = ["major", "latestMajor"];
10
+ const TEST_RUNNER = "Microsoft.Testing.Platform";
11
+ const LINE_LENGTH = "140";
12
+ const CSHARPIER_FILES = [".cs", ".csproj", ".props", ".targets"];
13
+ const CSHARPIER_CONFIGS = [".csharpierrc", ".csharpierrc.json", ".csharpierrc.yaml", ".csharpierrc.yml"];
14
+ const TSCONFIG = /^tsconfig(\..+)?\.json$/;
15
+ const ESLINT_CONFIGS = ["eslint.config.js", "eslint.config.mjs", "eslint.config.ts", "eslint.config.mts"];
16
+ const VITEST_CONFIGS = ["vitest.config.ts", "vitest.config.mts", "vitest.config.js", "vitest.config.mjs"];
17
+ const PLAYWRIGHT_CONFIGS = [
18
+ ["web", "e2e/playwright.config.ts"],
19
+ ["library", "visual/playwright.config.ts"],
20
+ ];
21
+ const SCHEMA_PATH = `node_modules/${SUWGATE}/schema/suwgate.schema.json`;
22
+ const WORKFLOW = /^\.github\/workflows\/[^/]+\.ya?ml$/;
23
+ const GATE_CALL = /^\s*(?:-\s+)?uses:\s*["']?manomenu\/suwgate\/\.github\/workflows\/gate\.ya?ml@([^\s"'#]+)/i;
24
+ const FULL_SHA = /^[0-9a-f]{40}$/;
25
+ const GATE_USES = "uses: Manomenu/suwgate/.github/workflows/gate.yml@<full 40-character commit sha>";
26
+ function directoryOf(context, profile) {
27
+ return (context.directories[profile] ?? "").replace(/\/+$/, "");
28
+ }
29
+ function joined(directory, file) {
30
+ return directory === "" ? file : `${directory}/${file}`;
31
+ }
32
+ function present(context, file) {
33
+ return context.files.includes(file);
34
+ }
35
+ function nodeDirectories(context) {
36
+ return [...new Set(NODE_PROFILES.filter((profile) => context.profiles.includes(profile)).map((p) => directoryOf(context, p)))];
37
+ }
38
+ function imports(text, module) {
39
+ const escaped = module.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
40
+ return new RegExp(`(?:\\bfrom\\s*|\\bimport\\s*\\(\\s*|\\bimport\\s+|\\brequire\\s*\\(\\s*)["']${escaped}["']`).test(text);
41
+ }
42
+ function globalJson(context) {
43
+ const file = inProfileDirectory(context.directories, "dotnet", "global.json");
44
+ if (!present(context, file))
45
+ return [];
46
+ const parsed = parseJsonc(context.read(file));
47
+ if (!isRecord(parsed))
48
+ return [{ target: file, message: "not valid JSON: fix the file so the dotnet CLI can read it" }];
49
+ const sdk = isRecord(parsed["sdk"]) ? parsed["sdk"] : {};
50
+ const test = isRecord(parsed["test"]) ? parsed["test"] : {};
51
+ const version = sdk["version"];
52
+ const rollForward = sdk["rollForward"];
53
+ const allowed = ROLL_FORWARD_ALLOWED.join(", ");
54
+ const findings = [];
55
+ if (typeof version !== "string" || !EXACT_VERSION.test(version)) {
56
+ findings.push(`sdk.version is ${JSON.stringify(version ?? null)}: set the exact SDK version, such as "10.0.100" (major.minor.patch, no wildcard or range), so every machine and CI build with the same SDK`);
57
+ }
58
+ if (typeof rollForward !== "string") {
59
+ findings.push(`sdk.rollForward is not set: set it, for example "latestFeature" (allowed: ${allowed}), so it is written down how far the SDK may move`);
60
+ }
61
+ else if (ROLL_FORWARD_MAJOR.includes(rollForward)) {
62
+ findings.push(`sdk.rollForward is "${rollForward}", which lets a new major SDK build the code with other analyzers and defaults: set it to one of ${allowed}`);
63
+ }
64
+ else if (!ROLL_FORWARD_ALLOWED.includes(rollForward)) {
65
+ findings.push(`sdk.rollForward "${rollForward}" is not a value .NET knows: set it to one of ${allowed}`);
66
+ }
67
+ if (test["runner"] !== TEST_RUNNER) {
68
+ findings.push(`test.runner is ${JSON.stringify(test["runner"] ?? null)}: set "test": { "runner": "${TEST_RUNNER}" }, the runner the dotnet-test step's dotnet test options are written for`);
69
+ }
70
+ return findings.map((message) => ({ target: file, message }));
71
+ }
72
+ function expandBraces(glob) {
73
+ const match = /\{([^{}]*)\}/.exec(glob);
74
+ if (match?.[1]?.includes(",") !== true)
75
+ return [glob];
76
+ const before = glob.slice(0, match.index);
77
+ const after = glob.slice(match.index + match[0].length);
78
+ return match[1].split(",").flatMap((option) => expandBraces(`${before}${option}${after}`));
79
+ }
80
+ function globPattern(glob) {
81
+ const source = glob
82
+ .replace(/[.+^${}()|\\]/g, "\\$&")
83
+ .replaceAll("**", "\u0000")
84
+ .replaceAll("*", "[^/]*")
85
+ .replaceAll("?", "[^/]")
86
+ .replaceAll("[!", "[^")
87
+ .replaceAll("\u0000", ".*");
88
+ return new RegExp(`^${source}$`);
89
+ }
90
+ export function appliesToEvery(glob, extension) {
91
+ return !glob.includes("/") && expandBraces(glob).some((single) => globPattern(single).test(`Any${extension}`));
92
+ }
93
+ function editorConfig(text) {
94
+ let glob = null;
95
+ let root = false;
96
+ const widths = [];
97
+ for (const { text: line } of numberedLines(text)) {
98
+ const trimmed = line.trim();
99
+ const header = /^\[(.*)\]$/.exec(trimmed);
100
+ const property = /^([^=#;]+?)\s*=\s*(.*)$/.exec(trimmed);
101
+ const key = property?.[1]?.toLowerCase();
102
+ const value = property?.[2]?.trim() ?? "";
103
+ if (header)
104
+ glob = header[1] ?? "";
105
+ else if (glob === null && key === "root")
106
+ root = value.toLowerCase() === "true";
107
+ else if (glob !== null && key === "max_line_length")
108
+ widths.push({ glob, width: value });
109
+ }
110
+ return { root, widths };
111
+ }
112
+ function widthFor(configs, extension) {
113
+ let width;
114
+ for (const config of configs) {
115
+ if (config.root)
116
+ width = undefined;
117
+ for (const section of config.widths)
118
+ if (appliesToEvery(section.glob, extension))
119
+ width = section.width;
120
+ }
121
+ return width;
122
+ }
123
+ function lineLength(context) {
124
+ const chain = [...new Set([".editorconfig", joined(directoryOf(context, "dotnet"), ".editorconfig")])].filter((file) => present(context, file));
125
+ const nearest = chain.at(-1);
126
+ if (nearest === undefined)
127
+ return [];
128
+ const configs = chain.map((file) => editorConfig(context.read(file)));
129
+ const wrong = CSHARPIER_FILES.map((extension) => ({ extension, width: widthFor(configs, extension) })).filter(({ width }) => width !== LINE_LENGTH);
130
+ if (wrong.length === 0)
131
+ return [];
132
+ const now = wrong.map(({ extension, width }) => `*${extension}: ${width ?? "not set"}`).join(", ");
133
+ return [
134
+ {
135
+ target: nearest,
136
+ message: `max_line_length is not ${LINE_LENGTH} for every file CSharpier formats (${now}): set max_line_length = ${LINE_LENGTH} in a section such as [*.{cs,csproj,props,targets}], the width CSharpier reads from .editorconfig`,
137
+ },
138
+ ];
139
+ }
140
+ function csharpierConfigs(context) {
141
+ return context.files
142
+ .filter((file) => CSHARPIER_CONFIGS.includes(baseName(file)))
143
+ .map((file) => ({
144
+ target: file,
145
+ message: `delete it: CSharpier takes a .csharpierrc over .editorconfig, and the width is max_line_length = ${LINE_LENGTH} in .editorconfig`,
146
+ }));
147
+ }
148
+ function centralPackages(context) {
149
+ const file = inProfileDirectory(context.directories, "dotnet", "Directory.Packages.props");
150
+ if (!present(context, file))
151
+ return [];
152
+ if (/<ManagePackageVersionsCentrally>\s*true\s*<\/ManagePackageVersionsCentrally>/i.test(context.read(file)))
153
+ return [];
154
+ return [
155
+ {
156
+ target: file,
157
+ message: "add <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally> to a PropertyGroup, so the versions in this file are the only ones and no project pins its own",
158
+ },
159
+ ];
160
+ }
161
+ function extendsSuwgate(context, file, seen) {
162
+ if (seen.has(file) || !present(context, file))
163
+ return false;
164
+ seen.add(file);
165
+ const parsed = parseJsonc(context.read(file));
166
+ const value = isRecord(parsed) ? parsed["extends"] : undefined;
167
+ const bases = (Array.isArray(value) ? value : [value]).filter((base) => typeof base === "string");
168
+ return bases.some((base) => {
169
+ if (base.startsWith(`${SUWGATE}/tsconfig/`))
170
+ return true;
171
+ if (!base.startsWith("."))
172
+ return false;
173
+ const resolved = path.posix.normalize(path.posix.join(path.posix.dirname(file), base));
174
+ return extendsSuwgate(context, resolved.endsWith(".json") ? resolved : `${resolved}.json`, seen);
175
+ });
176
+ }
177
+ function tsconfigs(context, directory) {
178
+ return context.files
179
+ .filter((file) => path.posix.dirname(file) === (directory === "" ? "." : directory))
180
+ .filter((file) => TSCONFIG.test(baseName(file)) && baseName(file) !== "tsconfig.build.json")
181
+ .filter((file) => !extendsSuwgate(context, file, new Set()))
182
+ .map((file) => ({
183
+ target: file,
184
+ message: `extends no ${SUWGATE}/tsconfig preset: set "extends": "${SUWGATE}/tsconfig/browser" (app code) or "${SUWGATE}/tsconfig/node" (configs, scripts, Node tests), directly or through another tsconfig of the repository that does`,
185
+ }));
186
+ }
187
+ function importing(context, file, module, fix) {
188
+ if (!present(context, file) || imports(context.read(file), module))
189
+ return [];
190
+ return [{ target: file, message: `does not import ${module}: ${fix}` }];
191
+ }
192
+ function prettier(context, directory) {
193
+ const json = joined(directory, ".prettierrc.json");
194
+ const preset = `${SUWGATE}/prettier`;
195
+ const findings = importing(context, joined(directory, "prettier.config.js"), preset, `spread the preset: import preset from "${preset}"; export default { ...preset, plugins: [...] }`);
196
+ if (present(context, json) && parseJson(context.read(json)) !== preset) {
197
+ findings.push({
198
+ target: json,
199
+ message: `does not use the preset: make the whole file "${preset}" (with a plugin, spread the preset in prettier.config.js instead)`,
200
+ });
201
+ }
202
+ return findings;
203
+ }
204
+ function nodeTools(context, directory) {
205
+ const eslint = ESLINT_CONFIGS.map((file) => joined(directory, file)).find((file) => present(context, file));
206
+ const vitest = VITEST_CONFIGS.map((file) => joined(directory, file)).filter((file) => present(context, file));
207
+ return [
208
+ ...tsconfigs(context, directory),
209
+ ...(eslint === undefined
210
+ ? []
211
+ : importing(context, eslint, `${SUWGATE}/eslint`, `build the config from strict() or app() of ${SUWGATE}/eslint`)),
212
+ ...prettier(context, directory),
213
+ ...importing(context, joined(directory, "knip.config.ts"), `${SUWGATE}/knip`, `export { default } from "${SUWGATE}/knip", or build it with knip({ entry: [...] }) from there`),
214
+ ...vitest.flatMap((file) => importing(context, file, `${SUWGATE}/vitest`, `build the projects with unitTests() or storyTests() of ${SUWGATE}/vitest, the projects unit and stories the steps run`)),
215
+ ];
216
+ }
217
+ function playwright(context) {
218
+ return PLAYWRIGHT_CONFIGS.filter(([profile]) => context.profiles.includes(profile)).flatMap(([profile, config]) => importing(context, joined(directoryOf(context, profile), config), `${SUWGATE}/playwright`, `build it with defineConfig(e2eTests({ ... })) or defineConfig(visualTests()) of ${SUWGATE}/playwright`));
219
+ }
220
+ function installDirectories(context) {
221
+ const candidates = new Set(["package.json", ...nodeDirectories(context).map((directory) => joined(directory, "package.json"))]);
222
+ const installs = new Map();
223
+ for (const dependency of npmDependencies(context)) {
224
+ if (dependency.name !== SUWGATE || !candidates.has(dependency.manifest))
225
+ continue;
226
+ const findings = EXACT_VERSION.test(dependency.version)
227
+ ? []
228
+ : [
229
+ {
230
+ target: dependency.manifest,
231
+ line: dependency.line,
232
+ message: `${SUWGATE} is "${dependency.version}": pin it to an exact version, such as "0.1.2" (no ^, ~, range or tag), so the gate changes only when the repository updates it`,
233
+ },
234
+ ];
235
+ installs.set(path.posix.dirname(dependency.manifest).replace(/^\.$/, ""), findings);
236
+ }
237
+ return installs;
238
+ }
239
+ function releaseAge(context, directories) {
240
+ return [...new Set(directories)]
241
+ .map((directory) => joined(directory, "pnpm-workspace.yaml"))
242
+ .filter((file) => present(context, file))
243
+ .flatMap((file) => {
244
+ const text = context.read(file);
245
+ let parsed;
246
+ try {
247
+ parsed = parseYaml(text);
248
+ }
249
+ catch {
250
+ return [{ target: file, message: "not valid YAML: fix the file so pnpm can read it" }];
251
+ }
252
+ if (!isRecord(parsed) || !("minimumReleaseAge" in parsed))
253
+ return [];
254
+ const age = parsed["minimumReleaseAge"];
255
+ if (typeof age === "number" && age > 0)
256
+ return [];
257
+ return [
258
+ {
259
+ target: file,
260
+ line: lineAt(text, Math.max(0, text.indexOf("minimumReleaseAge:"))),
261
+ message: `minimumReleaseAge is ${JSON.stringify(age)}, so pnpm installs a release minutes after it is published: delete the line (pnpm waits 1440 minutes by default) or set more minutes, and put a package needed sooner into minimumReleaseAgeExclude`,
262
+ },
263
+ ];
264
+ });
265
+ }
266
+ function schemaMapped(schemas, directories) {
267
+ const accepted = new Set(directories.flatMap((directory) => [joined(directory, SCHEMA_PATH), `./${joined(directory, SCHEMA_PATH)}`]));
268
+ return Object.entries(schemas).some(([schema, targets]) => accepted.has(schema) && (Array.isArray(targets) ? targets : [targets]).includes("suwgate.yml"));
269
+ }
270
+ function yamlSchemas(context, installs) {
271
+ const file = ".vscode/settings.json";
272
+ if (!present(context, file))
273
+ return [];
274
+ const settings = parseJson(context.read(file));
275
+ if (!isRecord(settings))
276
+ return [];
277
+ const schemas = isRecord(settings["yaml.schemas"]) ? settings["yaml.schemas"] : {};
278
+ const profileDirectories = Object.values(context.directories).map((directory) => directory.replace(/\/+$/, ""));
279
+ if (schemaMapped(schemas, ["", ...installs, ...profileDirectories]))
280
+ return [];
281
+ const schema = `./${joined(installs[0] ?? "", SCHEMA_PATH)}`;
282
+ return [
283
+ {
284
+ target: file,
285
+ message: `yaml.schemas does not map suwgate's schema to suwgate.yml: add "yaml.schemas": { "${schema}": "suwgate.yml" }, so VS Code checks suwgate.yml as you type`,
286
+ },
287
+ ];
288
+ }
289
+ function gateWorkflow(context) {
290
+ const workflows = context.files.filter((file) => WORKFLOW.test(file));
291
+ if (workflows.length === 0)
292
+ return [];
293
+ const calls = workflows.flatMap((file) => numberedLines(context.read(file)).flatMap(({ line, text }) => {
294
+ const ref = GATE_CALL.exec(text)?.[1];
295
+ return ref === undefined ? [] : [{ file, line, ref }];
296
+ }));
297
+ if (calls.length === 0) {
298
+ return [
299
+ {
300
+ target: ".github/workflows",
301
+ message: `no job calls suwgate's gate: add a job with ${GATE_USES}, so CI runs the same gate as suwgate check`,
302
+ },
303
+ ];
304
+ }
305
+ return calls
306
+ .filter(({ ref }) => !FULL_SHA.test(ref))
307
+ .map(({ file, line, ref }) => ({
308
+ target: file,
309
+ line,
310
+ message: `the gate is called at ${ref}, which can move: pin it by the commit, ${GATE_USES}`,
311
+ }));
312
+ }
313
+ export const configContents = {
314
+ id: "config-contents",
315
+ description: "The config files suwgate relies on say what it needs: the SDK and test runner, the C# line width, the tool presets, an exact suwgate version, pnpm's release age, the schema in VS Code and the pinned gate workflow",
316
+ profiles: "every",
317
+ check(context) {
318
+ const dotnet = context.profiles.includes("dotnet");
319
+ const installs = installDirectories(context);
320
+ return [
321
+ ...(dotnet ? [...globalJson(context), ...lineLength(context), ...csharpierConfigs(context), ...centralPackages(context)] : []),
322
+ ...nodeDirectories(context).flatMap((directory) => nodeTools(context, directory)),
323
+ ...playwright(context),
324
+ ...[...installs.values()].flat(),
325
+ ...releaseAge(context, [...nodeDirectories(context), ...installs.keys()]),
326
+ ...yamlSchemas(context, [...installs.keys()]),
327
+ ...gateWorkflow(context),
328
+ ];
329
+ },
330
+ };
@@ -1,2 +1,4 @@
1
1
  import type { Guard } from "../../gate/contract.ts";
2
+ export declare const DOTNET_GUARD_IDS: string[];
3
+ export declare function isPath(mention: string): boolean;
2
4
  export declare const docsPaths: Guard;
@@ -4,8 +4,24 @@ const MENTION = /`([\w.\-/@]+)`|\]\(([\w.\-/]+)(?:#[\w-]*)?\)/g;
4
4
  const FILE_NAME = /[\w-]\.(cs|csproj|css|json|md|props|sh|slnx|sql|ts|tsx|txt|yaml|yml)$/;
5
5
  const NOT_IN_THE_REPOSITORY = ["CLAUDE.local.md", "dist/"];
6
6
  const NOT_READ = ["docs/visual/**", ".changeset/**"];
7
- function isPath(mention) {
8
- return !/^(https?:|\/|@|~)/.test(mention) && (mention.includes("/") || FILE_NAME.test(mention));
7
+ export const DOTNET_GUARD_IDS = [
8
+ "architecture/build-settings",
9
+ "architecture/endpoints",
10
+ "architecture/every-project-guarded",
11
+ "architecture/forbidden-type-names",
12
+ "architecture/interfaces-have-two-implementations",
13
+ "architecture/layers",
14
+ "architecture/no-escape-hatches",
15
+ "architecture/no-fixture-in-field",
16
+ "architecture/no-unused-types",
17
+ "architecture/nothing-obsolete",
18
+ "architecture/one-type-per-file",
19
+ "architecture/project-references",
20
+ "architecture/unique-type-names",
21
+ "database/migration-script-names",
22
+ ];
23
+ export function isPath(mention) {
24
+ return !/^(https?:|\/|@|~)/.test(mention) && (mention.includes("/") || FILE_NAME.test(mention)) && !DOTNET_GUARD_IDS.includes(mention);
9
25
  }
10
26
  function existsLoosely(mention, files) {
11
27
  const name = mention.replace(/^(\.\.?\/)+/, "");
@@ -34,21 +50,29 @@ function stale(document, text, files, ignored) {
34
50
  {
35
51
  target: document,
36
52
  line: lineAt(text, match.index),
37
- message: `${mention} is not a path in this repository: fix the path, or say what the code does instead of where it is (a name meant to be outside the repository, or a pattern of names, goes into settings.docs-paths.ignore; a folder there ends with /)`,
53
+ message: `${mention} is not a path in this repository: fix the path, or say what the code does instead of where it is (a name meant to be outside the repository, or a pattern of names, goes into settings.docs-paths.ignore, a folder there ends with /; a whole document that is not about this repository goes into settings.docs-paths.skip as a glob)`,
38
54
  },
39
55
  ];
40
56
  });
41
57
  }
42
58
  export const docsPaths = {
43
59
  id: "docs-paths",
44
- description: "Every file and folder the Markdown docs name, in backticks or as a link, exists in the repository",
60
+ description: "Every file and folder the Markdown docs name, in backticks or as a link, exists in the repository (a .NET guard id is not a path)",
45
61
  profiles: "every",
46
- settingsSchema: { type: "object", additionalProperties: false, properties: { ignore: stringList } },
62
+ settingsSchema: {
63
+ type: "object",
64
+ additionalProperties: false,
65
+ properties: {
66
+ ignore: { ...stringList, description: "Names the docs may mention that are not paths here; a folder ends with /." },
67
+ skip: { ...stringList, description: "Globs of documents not read at all, such as docs/notes/**." },
68
+ },
69
+ },
47
70
  check(context) {
48
71
  const settings = (context.settings ?? {});
49
72
  const ignored = [...NOT_IN_THE_REPOSITORY, ...(settings.ignore ?? [])];
73
+ const notRead = [...NOT_READ, ...(settings.skip ?? [])];
50
74
  return context.files
51
- .filter((file) => file.endsWith(".md") && baseName(file) !== "CHANGELOG.md" && !matchesAny(file, NOT_READ))
75
+ .filter((file) => file.endsWith(".md") && baseName(file) !== "CHANGELOG.md" && !matchesAny(file, notRead))
52
76
  .flatMap((document) => stale(document, context.read(document), context.files, ignored));
53
77
  },
54
78
  };
@@ -1,7 +1,6 @@
1
1
  import { PROFILES } from "../../gate/contract.js";
2
2
  import { matchesAny, stringList } from "./text.js";
3
3
  const EVERY_REPOSITORY = [
4
- "base",
5
4
  "common",
6
5
  "core",
7
6
  "helper",
@@ -22,6 +21,7 @@ export const FORBIDDEN_BY_PROFILE = {
22
21
  dotnet: ["application", "controllers", "domain", "dtos", "infrastructure", "interfaces", "models", "repositories", "services"],
23
22
  database: [],
24
23
  };
24
+ const FOLDERS_ONLY = ["base"];
25
25
  const NOT_READ = ["docs/visual/**"];
26
26
  function words(name) {
27
27
  return name
@@ -51,7 +51,10 @@ export const forbiddenNames = {
51
51
  check(context) {
52
52
  const settings = (context.settings ?? {});
53
53
  const vague = [...EVERY_REPOSITORY, ...(settings.words ?? []).map((word) => word.toLowerCase())];
54
- const byKind = PROFILES.filter((profile) => context.profiles.includes(profile)).flatMap((profile) => FORBIDDEN_BY_PROFILE[profile]);
54
+ const byKind = [
55
+ ...FOLDERS_ONLY,
56
+ ...PROFILES.filter((profile) => context.profiles.includes(profile)).flatMap((profile) => FORBIDDEN_BY_PROFILE[profile]),
57
+ ];
55
58
  const ignored = [...NOT_READ, ...(settings.ignore ?? [])];
56
59
  return namedPaths(context.files.filter((file) => !matchesAny(file, ignored))).flatMap(({ named, isFolderOrProject }) => {
57
60
  const name = named.split("/").at(-1) ?? named;
@@ -1,6 +1,7 @@
1
1
  import { agentsFile } from "./agentsFile.js";
2
2
  import { bannedNpmPackages } from "./bannedNpmPackages.js";
3
3
  import { composePorts } from "./composePorts.js";
4
+ import { configContents } from "./configContents.js";
4
5
  import { dependencyDirection } from "./dependencyDirection.js";
5
6
  import { docsPaths } from "./docsPaths.js";
6
7
  import { forbiddenNames } from "./forbiddenNames.js";
@@ -12,9 +13,11 @@ import { repositoryLayout } from "./repositoryLayout.js";
12
13
  import { requiredFiles } from "./requiredFiles.js";
13
14
  import { scriptsCalled } from "./scriptsCalled.js";
14
15
  import { scriptsHelp } from "./scriptsHelp.js";
16
+ import { suwfrontkitWiring } from "./suwfrontkitWiring.js";
15
17
  import { vsCodeSettings } from "./vsCodeSettings.js";
16
18
  export const repositoryGuards = [
17
19
  requiredFiles,
20
+ configContents,
18
21
  agentsFile,
19
22
  docsPaths,
20
23
  forbiddenNames,
@@ -29,4 +32,5 @@ export const repositoryGuards = [
29
32
  noRawColors,
30
33
  dependencyDirection,
31
34
  hooks,
35
+ suwfrontkitWiring,
32
36
  ];
@@ -1,9 +1,10 @@
1
1
  import { inProfileDirectory, numberedLines, stringList } from "./text.js";
2
2
  const RAW_COLOR = /#[0-9a-fA-F]{3,8}\b|\b(rgb|rgba|hsl|hsla|oklch|oklab)\(|\[#/;
3
3
  const CODE_FILE = /\.(ts|tsx|js|jsx)$/;
4
+ const TEST_FILE = /\.(test|spec|e2e)\.(ts|tsx|js|jsx)$/;
4
5
  export const noRawColors = {
5
6
  id: "no-raw-colors",
6
- description: "Components use the theme's tokens, never a colour value of their own; it reads the src/ folder of a web app, and the folders settings name",
7
+ description: "Components use the theme's tokens, never a colour value of their own; it reads the src/ folder of a web app, and the folders settings name, but not the tests",
7
8
  profiles: ["web", "library"],
8
9
  settingsSchema: {
9
10
  type: "object",
@@ -17,7 +18,7 @@ export const noRawColors = {
17
18
  const defaults = context.profiles.includes("web") ? [inProfileDirectory(context.directories, "web", "src/")] : [];
18
19
  const folders = (settings.folders ?? defaults).map((folder) => `${folder.replace(/\/+$/, "")}/`);
19
20
  return context.files
20
- .filter((file) => CODE_FILE.test(file) && folders.some((folder) => file.startsWith(folder)))
21
+ .filter((file) => CODE_FILE.test(file) && !TEST_FILE.test(file) && folders.some((folder) => file.startsWith(folder)))
21
22
  .flatMap((file) => numberedLines(context.read(file))
22
23
  .filter(({ text }) => RAW_COLOR.test(text))
23
24
  .map(({ line }) => ({
@@ -5,8 +5,26 @@ import { numberedLines } from "./text.js";
5
5
  const MAP = "docs/architecture.md";
6
6
  export const MAX_MAP_LINE_LENGTH = 300;
7
7
  const MAP_ENTRY = /^- `([^`]+)`/;
8
+ const MAP_HEADING = "## The map";
9
+ function mapSection(text) {
10
+ const lines = numberedLines(text);
11
+ const start = lines.findIndex(({ text: line }) => line.trim() === MAP_HEADING);
12
+ if (start === -1)
13
+ return null;
14
+ const end = lines.findIndex(({ text: line }, index) => index > start && /^#{1,2} /.test(line));
15
+ return lines.slice(start + 1, end === -1 ? undefined : end);
16
+ }
8
17
  function mapFindings(context) {
9
- const entries = numberedLines(context.read(MAP)).filter(({ text }) => MAP_ENTRY.test(text));
18
+ const section = mapSection(context.read(MAP));
19
+ if (section === null) {
20
+ return [
21
+ {
22
+ target: MAP,
23
+ message: `no "${MAP_HEADING}" section: add it, with one line per top-level folder (- \`folder/\` — what it holds)`,
24
+ },
25
+ ];
26
+ }
27
+ const entries = section.filter(({ text }) => MAP_ENTRY.test(text));
10
28
  const folders = new Set(context.files.filter((file) => file.includes("/")).map((file) => file.split("/")[0] ?? ""));
11
29
  const described = new Map(entries.map(({ line, text }) => [(MAP_ENTRY.exec(text)?.[1] ?? "").split("/")[0] ?? "", line]));
12
30
  const missing = [...folders]
@@ -63,7 +81,7 @@ function notExecutable(root) {
63
81
  }
64
82
  export const repositoryLayout = {
65
83
  id: "repository-layout",
66
- description: "Every top-level folder has a short line in the map of docs/architecture.md, no two files differ only in letter case, and every shell script is executable in git",
84
+ description: "Every top-level folder has a short line in the map (the section ## The map) of docs/architecture.md, no two files differ only in letter case, and every shell script is executable in git",
67
85
  profiles: "every",
68
86
  check(context) {
69
87
  return [
@@ -1,5 +1,6 @@
1
+ import path from "node:path";
1
2
  import { PROFILES } from "../../gate/contract.js";
2
- import { inProfileDirectory, stringList } from "./text.js";
3
+ import { baseName, inProfileDirectory, stringList } from "./text.js";
3
4
  export const EVERY_REPOSITORY = {
4
5
  "suwgate.yml": "the repository's gate: its profiles, the steps it adds or skips, and the exceptions with their reasons",
5
6
  "README.md": "what the project is and how to use it, for people",
@@ -37,6 +38,7 @@ export const REQUIRED_BY_PROFILE = {
37
38
  "nuget.config": "the package sources, so a restore never reaches an unexpected feed",
38
39
  "Directory.Build.props": "the build settings of every project (warnings as errors, analyzers, nullable, lock files)",
39
40
  "Directory.Packages.props": "the one place that pins the version of every NuGet package",
41
+ "Directory.Build.rsp": "the MSBuild switches of every build, -nodeReuse:false among them, so no idle MSBuild worker stays behind",
40
42
  ".config/dotnet-tools.json": "the .NET tools at pinned versions, such as CSharpier for the format step",
41
43
  "layers.json": "the layers of the server and which project may reference which, read by Suwgate.Architecture",
42
44
  },
@@ -69,18 +71,45 @@ function required(context, settings) {
69
71
  }
70
72
  return files;
71
73
  }
74
+ function solutionFindings(context) {
75
+ if (!context.profiles.includes("dotnet"))
76
+ return [];
77
+ const directory = (context.directories.dotnet ?? "").replace(/\/+$/, "");
78
+ const inDirectory = context.files.filter((file) => path.posix.dirname(file) === (directory === "" ? "." : directory));
79
+ const solutions = inDirectory.filter((file) => file.endsWith(".slnx"));
80
+ const target = inProfileDirectory(context.directories, "dotnet", "*.slnx");
81
+ if (solutions.length === 1)
82
+ return [];
83
+ if (solutions.length === 0) {
84
+ return [
85
+ {
86
+ target,
87
+ message: "missing: the one solution file that dotnet build and dotnet test find in the dotnet profile's directory. Add it with dotnet new sln --format slnx (an old .sln: dotnet sln migrate, then delete the .sln), or add an exception with the reason it does not apply",
88
+ },
89
+ ];
90
+ }
91
+ return [
92
+ {
93
+ target,
94
+ message: `${solutions.length} solution files (${solutions.map(baseName).join(", ")}): keep one, because dotnet build and dotnet test refuse to choose between them`,
95
+ },
96
+ ];
97
+ }
72
98
  export const requiredFiles = {
73
99
  id: "required-files",
74
- description: "Every file a repository of these profiles needs is there (the gate, the agent rules, the editor and git settings, the hooks, each profile's tool configs)",
100
+ description: "Every file a repository of these profiles needs is there (the gate, the agent rules, the editor and git settings, the hooks, each profile's tool configs, one .slnx for .NET)",
75
101
  profiles: "every",
76
102
  settingsSchema: { type: "object", additionalProperties: false, properties: { files: stringList } },
77
103
  check(context) {
78
104
  const present = new Set(context.files);
79
- return [...required(context, (context.settings ?? {}))]
80
- .filter(([file]) => !isPresent(file, present))
81
- .map(([file, purpose]) => ({
82
- target: file,
83
- message: `missing: ${purpose}, or add an exception with the reason it does not apply`,
84
- }));
105
+ return [
106
+ ...[...required(context, (context.settings ?? {}))]
107
+ .filter(([file]) => !isPresent(file, present))
108
+ .map(([file, purpose]) => ({
109
+ target: file,
110
+ message: `missing: ${purpose}, or add an exception with the reason it does not apply`,
111
+ })),
112
+ ...solutionFindings(context),
113
+ ];
85
114
  },
86
115
  };
@@ -0,0 +1,2 @@
1
+ import type { Guard } from "../../gate/contract.ts";
2
+ export declare const suwfrontkitWiring: Guard;
@@ -0,0 +1,52 @@
1
+ import path from "node:path";
2
+ import { npmDependencies } from "./packageManifests.js";
3
+ const KIT = "@maniumek/suwfrontkit";
4
+ const THEME = `${KIT}/theme.css`;
5
+ const PROFILES = ["web", "library"];
6
+ const MAIN_SCRIPT = /<script\b[^>]*\btype\s*=\s*["']module["'][^>]*\bsrc\s*=\s*["']\/?([^"']+)["']/;
7
+ const CSS_IMPORT = /\bimport\s+["'](\.{1,2}\/[^"']+\.css)["']/g;
8
+ function importsTheme(text) {
9
+ const escaped = THEME.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
10
+ return new RegExp(`(?:\\bimport\\s+|@import\\s+(?:url\\()?)["']${escaped}["']`).test(text);
11
+ }
12
+ function present(context, file) {
13
+ return context.files.includes(file);
14
+ }
15
+ function findingsIn(context, directory) {
16
+ const joined = (file) => (directory === "" ? file : path.posix.join(directory, file));
17
+ const html = joined("index.html");
18
+ if (!present(context, html))
19
+ return [];
20
+ const main = MAIN_SCRIPT.exec(context.read(html))?.[1];
21
+ if (main === undefined)
22
+ return [];
23
+ const module = joined(main);
24
+ if (!present(context, module))
25
+ return [];
26
+ const text = context.read(module);
27
+ const stylesheets = [...text.matchAll(CSS_IMPORT)].map((match) => path.posix.join(path.posix.dirname(module), match[1] ?? ""));
28
+ if (importsTheme(text) || stylesheets.some((sheet) => present(context, sheet) && importsTheme(context.read(sheet))))
29
+ return [];
30
+ return [
31
+ {
32
+ target: module,
33
+ message: `the app depends on ${KIT} but neither its main module nor a stylesheet it imports loads the kit's theme: add @import "${THEME}"; at the top of the entry stylesheet (or import "${THEME}" in ${path.posix.basename(module)}), so the kit's components get their tokens`,
34
+ },
35
+ ];
36
+ }
37
+ export const suwfrontkitWiring = {
38
+ id: "suwfrontkit-wiring",
39
+ description: `A web app (an index.html with a module script) that depends on ${KIT} loads ${THEME} from its main module or a stylesheet that module imports`,
40
+ profiles: PROFILES,
41
+ check(context) {
42
+ const directories = [
43
+ ...new Set(PROFILES.filter((profile) => context.profiles.includes(profile)).map((profile) => context.directories[profile] ?? "")),
44
+ ];
45
+ const manifests = new Set(npmDependencies(context)
46
+ .filter((dependency) => dependency.name === KIT)
47
+ .map((dependency) => dependency.manifest));
48
+ return directories
49
+ .filter((directory) => manifests.has(directory === "" ? "package.json" : `${directory}/package.json`))
50
+ .flatMap((directory) => findingsIn(context, directory));
51
+ },
52
+ };
@@ -18,3 +18,4 @@ export declare const stringList: {
18
18
  readonly minLength: 1;
19
19
  };
20
20
  };
21
+ export declare function parseJsonc(text: string): unknown;