@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
package/README.md CHANGED
@@ -34,12 +34,19 @@ exceptions:
34
34
  guards run only with `database`.
35
35
  - `steps.add` runs more (`name`, `run`, optionally `title`, `quick`, `after`, `limitSeconds`); `steps.skip` leaves a step out,
36
36
  always with a `reason`.
37
+ - `quick.limitSeconds` is the budget of `suwgate check --quick` (default 20): the quick gate fails above it. A machine that is slow
38
+ across the board overrides it with `SUWGATE_QUICK_LIMIT=<seconds>`.
37
39
  - `exceptions` let one target through one guard, always with a `reason`; `suwgate check` counts them in its report, and an
38
40
  exception that no longer matches anything fails the gate until it is deleted.
41
+ - `guards.skip` turns one whole guard off, always with a `reason`: a repository guard, or a .NET guard (`architecture/*`,
42
+ `database/*`), which `SuwgateGuards.VerifyAll` then does not run and the `dotnet-test` step does not ask evidence for. A
43
+ library, for example: `guards: { skip: [{ guard: architecture/endpoints, reason: a library has no server }] }`.
39
44
  - The schema is in the package, `schema/suwgate.schema.json`. VS Code checks the file as you type with
40
45
  `"yaml.schemas": { "./node_modules/@maniumek/suwgate/schema/suwgate.schema.json": "suwgate.yml" }` in `.vscode/settings.json`.
41
- - `settings` configure a guard by its id, for example `dependency-direction: { applications: [Myapp.*] }` or
42
- `agents-file: { acronyms: [NUGET] }`; the schema of each guard's settings is in its source, and `suwgate check` validates them.
46
+ - `settings` configure a guard by its id, for example `dependency-direction: { applications: [Myapp.*] }`,
47
+ `agents-file: { acronyms: [NUGET] }` or `docs-paths: { ignore: [Myapp.Web/node_modules/], skip: [docs/notes/**] }` (`ignore`: names the
48
+ docs may mention that are not paths here; `skip`: documents, by glob, that docs-paths does not read at all); the schema of each
49
+ guard's settings is in its source, and `suwgate check` validates them.
43
50
 
44
51
  ## Hooks
45
52
 
@@ -85,10 +92,10 @@ Each step looks where its profile lives (`directories`) and passes with nothing
85
92
 
86
93
  | Profile | Steps |
87
94
  | :--------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
88
- | `web`, `library` | `pnpm-install` (only without `node_modules`), `typecheck` (every `tsconfig*.json` but `tsconfig.build.json`), `lint`, `unit-tests` (the Vitest project `unit` when the config names one), `format`, `knip` |
89
- | `web` | `e2e`: `playwright test -c e2e/playwright.config.ts`, after the build, the database and the .NET tests |
95
+ | `web`, `library` | `pnpm-install` (only without `node_modules`), `typecheck` (every `tsconfig*.json` but `tsconfig.build.json`, with `tsc --showConfig`), `lint` (with `eslint --print-config`), `unit-tests` (the Vitest project `unit` when the config names one; 0 tests fail), `format`, `knip` |
96
+ | `web` | `e2e`: `playwright test -c e2e/playwright.config.ts`, after the build, the database and the .NET tests; with a `dev` section, first the checkout's variables (`suwgate dev checkout-env`) and a fresh, empty `E2E_DATABASE` (`dev db up`, then drop and create it); Playwright's `webServer` starts and stops the server and the web app |
90
97
  | `library` | `stories` (with `.storybook/`), `publint`, `attw`, `consumer-app` (packs the library into a copy of `gate/consumer/app`, builds it, runs `gate/consumer/playwright.config.ts`), `visual` (`visual/playwright.config.ts` in the Playwright image of the installed `@playwright/test`), `changeset` |
91
- | `dotnet` | `dotnet-build`, `dotnet-format`, `dotnet-test` (`--quick`: only the test projects that use `Suwgate.Architecture` or `Suwgate.Database`) |
98
+ | `dotnet` | `dotnet-build`, `dotnet-format`, `dotnet-test` (fails on 0 tests and unless every .NET guard of the profiles ran; with a `dev` section, under the checkout's variables, so two worktrees never share a test database; `--quick`: only the test projects that use `Suwgate.Architecture` or `Suwgate.Database`); every .NET step leaves no idle MSBuild worker or build server behind |
92
99
  | `dotnet`, `web` | with `contract/openapi.json`: `api-contract` (the contract and `src/api/openapi.d.ts` of the web app regenerated from the server's project, the one that references `Microsoft.Extensions.ApiDescription.Server`), `api-version` (oasdiff against master; a break needs a new major version in `contract/package.json`), `contract-pins` (every test tagged `contract <name>@<version>` names a version) |
93
100
  | `database` | `database-up`: `docker compose --profile db up -d --wait db`, not in CI |
94
101
  | every repository | `compose` (with a compose file), `criteria`, `shellcheck`, `gitleaks` |
@@ -117,25 +124,81 @@ adds the repository's own (`{ "kinds": [{ "kind", "paths", "how" }] }`, optional
117
124
 
118
125
  The configs of the tools the steps run extend suwgate's, so an application keeps only its own paths:
119
126
 
120
- | Tool | The application's file |
121
- | :--------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
122
- | Prettier | `.prettierrc.json`: `"@maniumek/suwgate/prettier"` (with a plugin: spread it in `prettier.config.js`) |
123
- | TypeScript | `{ "extends": "@maniumek/suwgate/tsconfig/browser", "include": ["src"] }`; `tsconfig/node` for the configs, scripts and tests run by Node; `tsconfig/strict` for the options alone |
124
- | knip | `knip.config.ts`: `export { default } from "@maniumek/suwgate/knip"`, or `knip({ entry: [...] })`; it ignores the tools the steps run and the generated API types, and reads the steps' Playwright configs |
125
- | Vitest | `unitTests({ environment: "jsdom" })` and `storyTests({ plugin, provider })` from `@maniumek/suwgate/vitest`: the projects `unit` and `stories` the steps run |
126
- | Playwright | `defineConfig(e2eTests({ use: { baseURL }, webServer }))` or `defineConfig(visualTests())` from `@maniumek/suwgate/playwright` |
127
+ | Tool | The application's file |
128
+ | :--------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
129
+ | Prettier | `.prettierrc.json`: `"@maniumek/suwgate/prettier"` (with a plugin: spread it in `prettier.config.js`) |
130
+ | TypeScript | `{ "extends": "@maniumek/suwgate/tsconfig/browser", "include": ["src"] }`; `tsconfig/node` for the configs, scripts and tests run by Node; `tsconfig/strict` for the options alone |
131
+ | knip | `knip.config.ts`: `export { default } from "@maniumek/suwgate/knip"`, or `knip({ entry: [...] })`; it ignores the tools the steps run and the generated API types, and reads the steps' Playwright configs |
132
+ | Vitest | `unitTests({ environment: "jsdom" })` and `storyTests({ plugin, provider })` from `@maniumek/suwgate/vitest`: the projects `unit` and `stories` the steps run |
133
+ | Playwright | `defineConfig(e2eTests({ use: { baseURL }, webServer }))` or `defineConfig(visualTests())` from `@maniumek/suwgate/playwright` |
134
+ | ESLint | `app({ root, features, shared, sharedImports, storage })` from `@maniumek/suwgate/eslint`: a feature imports itself and the shared folders, a shared folder only itself and what `sharedImports` allows it (`[["design", "api"]]`: design may import api) |
135
+
136
+ ### What the config files must say
137
+
138
+ `required-files` asks for the files; `config-contents` checks that they say what the gate relies on, each where its profile lives
139
+ (`directories`), and only when the profile is on and the file is there:
140
+
141
+ | File | Profile | Must contain |
142
+ | :---------------------------------------------------------------------------- | :--------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |
143
+ | `global.json` | `dotnet` | an exact `sdk.version` (`10.0.100`), a `sdk.rollForward` other than `major` and `latestMajor`, `test.runner` `Microsoft.Testing.Platform` |
144
+ | `.editorconfig` (the root's, then the dotnet directory's) | `dotnet` | `max_line_length = 140` for `*.cs`, `*.csproj`, `*.props` and `*.targets`: CSharpier's width; a `.csharpierrc*` anywhere must go, it would win over it |
145
+ | `Directory.Packages.props` | `dotnet` | `<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>` |
146
+ | `tsconfig*.json` (not `tsconfig.build.json`, which the typecheck step skips) | `web`, `library` | `extends` `@maniumek/suwgate/tsconfig/...`, directly or through another tsconfig of the repository |
147
+ | `eslint.config.js`, `knip.config.ts`, the Vitest config | `web`, `library` | an import of `@maniumek/suwgate/eslint`, `/knip`, `/vitest` |
148
+ | `.prettierrc.json` or `prettier.config.js` | `web`, `library` | exactly `"@maniumek/suwgate/prettier"`, or an import of it |
149
+ | `e2e/playwright.config.ts`, `visual/playwright.config.ts` | `web`, `library` | an import of `@maniumek/suwgate/playwright` |
150
+ | `package.json` that installs suwgate (the root or a web or library directory) | every | `@maniumek/suwgate` at an exact version: no `^`, `~`, range or tag |
151
+ | `pnpm-workspace.yaml` (web, library, and where suwgate is installed) | every | no `minimumReleaseAge` of 0 (pnpm waits 1440 minutes by default); `minimumReleaseAgeExclude` is fine |
152
+ | `.vscode/settings.json` | every | `yaml.schemas` mapping `./node_modules/@maniumek/suwgate/schema/suwgate.schema.json` (or under a profile's directory) to `suwgate.yml` |
153
+ | `.github/workflows/*.yml` | every | a job with `uses: Manomenu/suwgate/.github/workflows/gate.yml@<full 40-character commit sha>` |
154
+
155
+ `required-files` also asks the `dotnet` profile for exactly one `*.slnx` in its directory, and for `Directory.Build.rsp`
156
+ (`-nodeReuse:false`, so no idle MSBuild worker stays behind).
127
157
 
128
158
  ### The .NET guards
129
159
 
130
- In the xUnit tests of a .NET application:
160
+ One xUnit test in the gate's test project runs every guard of the `dotnet` and `database` profiles:
131
161
 
132
162
  ```csharp
133
- [Fact]
134
- public void Every_interface_has_two_implementations() =>
135
- Guards.Verify(InterfacesHaveTwoImplementations.Of(typeof(ServerApp).Assembly));
163
+ public sealed class GuardTests
164
+ {
165
+ [Fact]
166
+ public void Every_guard_of_suwgate_passes() =>
167
+ SuwgateGuards.VerifyAll(
168
+ new GuardInputs { Production = [typeof(ServerApp).Assembly], Tests = [typeof(GuardTests).Assembly], Server = typeof(ServerApp) },
169
+ new DatabaseProfile()
170
+ );
171
+ }
136
172
  ```
137
173
 
138
- `Guards.Verify` reads the exceptions of that guard from the nearest `suwgate.yml` above the test's output folder.
174
+ `VerifyAll` reads the nearest `suwgate.yml` above the test's output folder (profiles, `guards.skip`, exceptions, settings), finds
175
+ the solution, `layers.json`, the sources and the migrations itself, and takes from the test only what it cannot find
176
+ ([dotnet/Suwgate.Architecture/README.md](dotnet/Suwgate.Architecture/README.md) lists the inputs).
177
+
178
+ ### What the gate proves ran
179
+
180
+ A check counts only when the tool shows it ran, not because a file or a line of text is there:
181
+
182
+ - The .NET guards: `dotnet-test` points `SUWGATE_EVIDENCE` at a fresh folder of this gate run, and every guard that runs (through
183
+ `VerifyAll` or `Guards.Verify`) writes its id and outcome there. The step fails unless every guard of the profiles that
184
+ `guards.skip` does not name is in it, so a deleted guard test, a `[Fact(Skip = …)]` or a filtered-out one fails the gate.
185
+ - Zero tests fail: `unit-tests`, `stories` (Vitest, its JSON report), `e2e` (Playwright, its JSON report) and `dotnet-test`
186
+ (`--zero-tests-policy strict` of Microsoft.Testing.Platform, and xUnit's XML report) fail when the tool ran no test, also when
187
+ every test was skipped. A repository with truly no tests for a profile skips the step in `suwgate.yml` with a reason.
188
+ - `typecheck` reads `tsc --showConfig` of every tsconfig it checks: the strict options of the suwgate preset must be in effect, so
189
+ an override that turns one off fails, naming the option.
190
+ - `lint` reads `eslint --print-config` of a source file of `src/`: `suwgate/no-comments` and `boundaries/dependencies` must be
191
+ errors there.
192
+ - `criteria-ran`, after the test steps: every acceptance criterion of a living spec (`docs/visual/spec/`) that a test names
193
+ (`[Trait("criterion", "<id>")]`, a title or story name `"<id>: …"`) must have a test naming it that ran and passed in this run,
194
+ by the reports of xUnit, Vitest and Playwright. A criterion named only by tests of a step `steps.skip` names is not checked.
195
+ - The kits are wired, not only installed: `suwbackkit-wiring` (dotnet) asks a web server that references `Suwbackkit.Server` to
196
+ call `AddServerDefaults` and `MapServerDefaults`; `suwfrontkit-wiring` (web, library) asks an app whose `package.json` depends
197
+ on `@maniumek/suwfrontkit` to load `@maniumek/suwfrontkit/theme.css` from the main module of its `index.html`, or from a
198
+ stylesheet that module imports. Both read the sources: the evidence (a run hitting `/health`, a built stylesheet with the
199
+ kit's tokens) needs a running server or a production build, which the gate does not have in every repository.
200
+ - The reports live in a temporary folder of the run (`SUWGATE_RUN`), deleted when `suwgate check` ends. `dotnet-test` asks xUnit
201
+ for its XML report (`--report-xunit-xml`), so every .NET test project tests with xUnit v3.
139
202
 
140
203
  `suwgate dev db|logs|smoke|server|tmux|checkout-env` runs the local stack of the template (database, logs, smoke test, server, tmux
141
204
  session, worktree databases) from a `dev` section of `suwgate.yml`: [docs/dev.md](docs/dev.md).
package/dist/cli.js CHANGED
@@ -7,7 +7,7 @@ import { loadConfig } from "./gate/config.js";
7
7
  import { PROFILES } from "./gate/contract.js";
8
8
  import { repositoryRoot } from "./gate/repository.js";
9
9
  import { guards } from "./guards/index.js";
10
- import { stepsFor } from "./profiles/index.js";
10
+ import { dotnetGuards, stepsFor, verdict } from "./profiles/index.js";
11
11
  import { guardEdit } from "./session/guardEdit.js";
12
12
  import { preCommit, runTool } from "./session/preCommit.js";
13
13
  import { stop } from "./session/stop.js";
@@ -23,9 +23,12 @@ const USAGE = `usage: suwgate check [--quick] [--verbose] | suwgate hook <guard-
23
23
  suwgate hook pre-commit git pre-commit hook: gitleaks on the staged changes, then the quick gate
24
24
  suwgate dev <db|logs|smoke|server|tmux|checkout-env>
25
25
  the local stack of the repository (the dev section of suwgate.yml); suwgate dev --help
26
+ suwgate verdict <tests|guards|tsconfig|eslint> ...
27
+ what the steps call after their tool: did tests run, did the .NET guards run (evidence),
28
+ are the strict compiler options and the eslint rules in effect
26
29
  Every step has a ceiling (SUWGATE_STEP_LIMIT seconds overrides them all). A step whose tool is missing is SKIP,
27
30
  and a SKIP fails the gate when CI is set. Exit code: 0 green, 1 red, 2 a usage or suwgate.yml problem.`;
28
- const catalog = { guards, stepsFor };
31
+ const catalog = { guards, dotnetGuards, stepsFor };
29
32
  function version() {
30
33
  const manifest = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
31
34
  return manifest.version;
@@ -48,6 +51,12 @@ function readInput() {
48
51
  async function main(argv) {
49
52
  if (argv[0] === "dev")
50
53
  return dev(argv.slice(1));
54
+ if (argv[0] === "verdict") {
55
+ const result = verdict(argv.slice(1));
56
+ if (result.text !== "")
57
+ console.error(result.text);
58
+ return result.exitCode;
59
+ }
51
60
  const { values, positionals } = parseArgs({
52
61
  args: [...argv],
53
62
  allowPositionals: true,
@@ -10,6 +10,7 @@ export interface StrictOptions {
10
10
  export interface AppOptions extends StrictOptions {
11
11
  features: readonly string[];
12
12
  shared?: readonly string[];
13
+ sharedImports?: readonly (readonly [from: string, to: string])[];
13
14
  storage?: readonly string[];
14
15
  }
15
16
  export declare const plugin: ESLint.Plugin;
@@ -10,7 +10,7 @@ const CODE = ["**/*.{ts,tsx,js,jsx,mjs,cjs,mts,cts}"];
10
10
  const SOURCES = ["src/**/*.{ts,tsx}"];
11
11
  const BROWSER_STORAGE = ["localStorage", "sessionStorage", "indexedDB"];
12
12
  const BROWSER_STORAGE_FIX = "Keep the state on the server, in the address or in React; browser storage is allowed only in the files that storage of app() names in eslint.config.js.";
13
- const BOUNDARIES_FIX = "A feature of src/ imports only itself and the shared folders, a shared folder only itself, a file directly in src/ anything; a new folder of src/ goes into features or shared of app() in eslint.config.js.";
13
+ const BOUNDARIES_FIX = "A feature of src/ imports only itself and the shared folders, a shared folder only itself (and the shared folders sharedImports of app() lets it), a file directly in src/ anything; a new folder of src/ goes into features or shared of app() in eslint.config.js.";
14
14
  export const plugin = {
15
15
  meta: { name: "@maniumek/suwgate" },
16
16
  rules: { "no-comments": noComments },
@@ -67,6 +67,10 @@ function featureBoundaries(options) {
67
67
  allow: { to: [{ file: { categories: "entry" } }, { element: { types: { anyOf: ["feature", "shared"] } } }] },
68
68
  },
69
69
  { from: { element: { type: "feature" } }, allow: { to: { element: { type: "shared" } } } },
70
+ ...(options.sharedImports ?? []).map(([from, to]) => ({
71
+ from: { element: { type: "shared", path: `src/${from}/**` } },
72
+ allow: { to: { element: { type: "shared", path: `src/${to}/**` } } },
73
+ })),
70
74
  ],
71
75
  },
72
76
  ],
@@ -1,3 +1,6 @@
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import path from "node:path";
1
4
  import { loadConfig } from "./config.js";
2
5
  import { plan } from "./plan.js";
3
6
  import { report } from "./report.js";
@@ -34,13 +37,18 @@ export async function check(options) {
34
37
  changed: () => (changed ??= changedFiles(root)),
35
38
  });
36
39
  const began = performance.now();
37
- const results = await runSteps(steps, { ...options.env, SUWGATE_ROOT: root, SUWGATE_QUICK: options.quick ? "1" : "" }, typeof stepLimit === "number" ? stepLimit : null);
40
+ const run = mkdtempSync(path.join(tmpdir(), "suwgate-run-"));
41
+ const results = await runSteps(steps, { ...options.env, SUWGATE_ROOT: root, SUWGATE_QUICK: options.quick ? "1" : "", SUWGATE_RUN: run }, typeof stepLimit === "number" ? stepLimit : null).finally(() => rmSync(run, { recursive: true, force: true }));
38
42
  const totalSeconds = Math.round((performance.now() - began) / 1000);
39
43
  const { text, passed } = report({
40
44
  results,
41
45
  command,
42
46
  totalSeconds,
43
- quickLimit: options.quick ? (typeof quickLimit === "number" ? quickLimit : DEFAULT_QUICK_LIMIT_SECONDS) : null,
47
+ quickLimit: options.quick
48
+ ? typeof quickLimit === "number"
49
+ ? quickLimit
50
+ : (loaded.config.quickLimitSeconds ?? DEFAULT_QUICK_LIMIT_SECONDS)
51
+ : null,
44
52
  ci: (options.env["CI"] ?? "") !== "",
45
53
  exceptions: loaded.config.exceptions.length,
46
54
  verbose: options.verbose,
@@ -1,4 +1,4 @@
1
- import { type Guard, type GuardException, type Profile, type Step } from "./contract.ts";
1
+ import { type DotnetGuard, type Guard, type GuardException, type Profile, type Step } from "./contract.ts";
2
2
  export declare const CONFIG_FILE = "suwgate.yml";
3
3
  interface AddedStep {
4
4
  name: string;
@@ -12,16 +12,23 @@ interface SkippedStep {
12
12
  step: string;
13
13
  reason: string;
14
14
  }
15
+ interface SkippedGuard {
16
+ guard: string;
17
+ reason: string;
18
+ }
15
19
  export interface Config {
16
20
  profiles: Profile[];
17
21
  directories: Partial<Record<Profile, string>>;
18
22
  add: AddedStep[];
19
23
  skip: SkippedStep[];
24
+ skippedGuards: SkippedGuard[];
20
25
  exceptions: GuardException[];
21
26
  settings: Record<string, unknown>;
27
+ quickLimitSeconds?: number;
22
28
  }
23
29
  export interface Catalog {
24
30
  guards: readonly Guard[];
31
+ dotnetGuards: readonly DotnetGuard[];
25
32
  stepsFor(profiles: readonly Profile[]): readonly Step[];
26
33
  }
27
34
  export type Loaded = {
@@ -35,7 +35,8 @@ function describe(error) {
35
35
  switch (error.keyword) {
36
36
  case "required": {
37
37
  const missing = String(params["missingProperty"]);
38
- const fix = missing === "reason" ? `: every ${parts[0] === "exceptions" ? "exception" : "skipped step"} says why (reason: <why>)` : "";
38
+ const what = parts[0] === "exceptions" ? "exception" : parts[0] === "guards" ? "skipped guard" : "skipped step";
39
+ const fix = missing === "reason" ? `: every ${what} says why (reason: <why>)` : "";
39
40
  return `${where} has no "${missing}"${fix}`;
40
41
  }
41
42
  case "additionalProperties":
@@ -104,9 +105,36 @@ function checkSteps(raw, catalog, problem) {
104
105
  }
105
106
  });
106
107
  }
108
+ function profilesOf(id, catalog) {
109
+ const dotnet = catalog.dotnetGuards.find((guard) => guard.id === id);
110
+ if (dotnet !== undefined)
111
+ return [dotnet.profile];
112
+ return catalog.guards.find((guard) => guard.id === id)?.profiles ?? null;
113
+ }
114
+ function checkSkippedGuards(raw, catalog, problem) {
115
+ const skipped = (raw.guards?.skip ?? []).map((entry) => entry.guard);
116
+ (raw.guards?.skip ?? []).forEach((entry, index) => {
117
+ const where = ["guards", "skip", index, "guard"];
118
+ const profiles = profilesOf(entry.guard, catalog);
119
+ if (profiles === null) {
120
+ const known = [...catalog.guards.map((guard) => guard.id), ...catalog.dotnetGuards.map((guard) => guard.id)];
121
+ problem(where, `no guard "${entry.guard}": the guards are ${known.join(", ")}`);
122
+ }
123
+ else if (profiles !== "every" && !profiles.some((profile) => raw.profiles.includes(profile))) {
124
+ problem(where, `"${entry.guard}" runs only for ${profiles.join(", ")}, which this repository does not have: delete the entry`);
125
+ }
126
+ if (skipped.indexOf(entry.guard) !== index)
127
+ problem(where, `"${entry.guard}" is skipped twice: keep one entry`);
128
+ });
129
+ (raw.exceptions ?? []).forEach((exception, index) => {
130
+ if (skipped.includes(exception.guard)) {
131
+ problem(["exceptions", index], `"${exception.guard}" is skipped in guards.skip, so this exception is never checked: delete it, or the skip`);
132
+ }
133
+ });
134
+ }
107
135
  function checkSettings(raw, catalog, problem) {
108
136
  for (const [id, value] of Object.entries(raw.settings ?? {})) {
109
- const guard = catalog.guards.find((candidate) => candidate.id === id);
137
+ const guard = catalog.guards.find((candidate) => candidate.id === id) ?? catalog.dotnetGuards.find((candidate) => candidate.id === id);
110
138
  if (guard?.settingsSchema === undefined) {
111
139
  problem(["settings", id], guard === undefined ? `no guard "${id}"` : `the guard "${id}" takes no settings`);
112
140
  continue;
@@ -147,6 +175,7 @@ export function parseConfig(text, catalog) {
147
175
  checkDirectories(data, problem);
148
176
  checkExceptions(data, catalog, problem);
149
177
  checkSteps(data, catalog, problem);
178
+ checkSkippedGuards(data, catalog, problem);
150
179
  checkSettings(data, catalog, problem);
151
180
  if (problems.length > 0)
152
181
  return { problems };
@@ -156,8 +185,10 @@ export function parseConfig(text, catalog) {
156
185
  directories: data.directories ?? {},
157
186
  add: data.steps?.add ?? [],
158
187
  skip: data.steps?.skip ?? [],
188
+ skippedGuards: data.guards?.skip ?? [],
159
189
  exceptions: data.exceptions ?? [],
160
190
  settings: data.settings ?? {},
191
+ ...(data.quick?.limitSeconds === undefined ? {} : { quickLimitSeconds: data.quick.limitSeconds }),
161
192
  },
162
193
  };
163
194
  }
@@ -19,6 +19,11 @@ export interface GuardContext {
19
19
  settings: unknown;
20
20
  read(file: string): string;
21
21
  }
22
+ export interface DotnetGuard {
23
+ id: string;
24
+ profile: Profile;
25
+ settingsSchema?: object;
26
+ }
22
27
  export interface Guard {
23
28
  id: string;
24
29
  description: string;
@@ -33,6 +38,8 @@ export interface StepContext {
33
38
  quick: boolean;
34
39
  profiles: readonly Profile[];
35
40
  directories: Readonly<Partial<Record<Profile, string>>>;
41
+ skippedSteps: readonly string[];
42
+ skippedGuards: readonly string[];
36
43
  changed(): readonly string[];
37
44
  }
38
45
  export interface Skip {
package/dist/gate/plan.js CHANGED
@@ -32,11 +32,14 @@ function chosenRun(step, quick) {
32
32
  return step.quick;
33
33
  }
34
34
  function guardsStep(input) {
35
+ const skipped = input.config.skippedGuards.map((entry) => entry.guard);
35
36
  const active = input.catalog.guards.filter((guard) => (guard.profiles === "every" || guard.profiles.some((profile) => input.config.profiles.includes(profile))) &&
36
- (!input.quick || guard.quick !== false));
37
+ (!input.quick || guard.quick !== false) &&
38
+ !skipped.includes(guard.id));
39
+ const skippedHere = input.catalog.guards.filter((guard) => skipped.includes(guard.id)).length;
37
40
  return {
38
41
  id: GUARDS_STEP,
39
- title: `repository guards (${active.length})`,
42
+ title: `repository guards (${active.length}${skippedHere === 0 ? "" : `, ${skippedHere} skipped in suwgate.yml`})`,
40
43
  after: [],
41
44
  limitSeconds: DEFAULT_LIMIT_SECONDS,
42
45
  inline: async () => {
@@ -65,6 +68,8 @@ export function plan(input) {
65
68
  quick: input.quick,
66
69
  profiles: input.config.profiles,
67
70
  directories: input.config.directories,
71
+ skippedSteps: input.config.skip.map((skipped) => skipped.step),
72
+ skippedGuards: input.config.skippedGuards.map((skipped) => skipped.guard),
68
73
  changed: input.changed,
69
74
  };
70
75
  const line = typeof run === "string" ? run : run(context);
@@ -41,7 +41,7 @@ export function report(input) {
41
41
  }
42
42
  if (input.quickLimit !== null && input.totalSeconds > input.quickLimit) {
43
43
  failed = true;
44
- rows.push(row("FAIL", input.totalSeconds, `the quick gate is over its budget of ${input.quickLimit}s: move the slow step to the full gate or speed it up; a machine that is slow across the board runs with SUWGATE_QUICK_LIMIT=<seconds>`));
44
+ rows.push(row("FAIL", input.totalSeconds, `the quick gate is over its budget of ${input.quickLimit}s: move the slow step to the full gate or speed it up; a repository whose quick gate is rightly longer sets quick.limitSeconds in suwgate.yml, and a machine that is slow across the board runs with SUWGATE_QUICK_LIMIT=<seconds>`));
45
45
  }
46
46
  const extras = [
47
47
  `${input.exceptions} exception${input.exceptions === 1 ? "" : "s"} in suwgate.yml`,
@@ -1,2 +1,3 @@
1
1
  import type { Guard } from "../../gate/contract.ts";
2
+ export declare const GENERATED_API_TYPES = "src/api/openapi.d.ts";
2
3
  export declare const commentsEslint: Guard;
@@ -13,6 +13,7 @@ import { pathToFileURL } from "node:url";
13
13
  import { isScanned } from "./scan.js";
14
14
  const RULE = "suwgate/no-comments";
15
15
  const CODE = /\.(ts|tsx|js|jsx|mjs|cjs|mts|cts)$/;
16
+ export const GENERATED_API_TYPES = "src/api/openapi.d.ts";
16
17
  const LINTED_PROFILES = ["web", "library"];
17
18
  const USE_THE_PRESET = `extend strict() or app() of @maniumek/suwgate/eslint in eslint.config.js, or switch ${RULE} on as an error for every TypeScript and JavaScript file`;
18
19
  function lintedDirectories(context) {
@@ -53,7 +54,8 @@ function findingOf(file, verdict) {
53
54
  return [];
54
55
  }
55
56
  async function findingsIn(context, directory) {
56
- const files = context.files.filter((file) => CODE.test(file) && isScanned(file) && inDirectory(file, directory));
57
+ const generated = context.profiles.includes("web") ? path.posix.join(context.directories.web ?? ".", GENERATED_API_TYPES) : null;
58
+ const files = context.files.filter((file) => CODE.test(file) && isScanned(file) && inDirectory(file, directory) && file !== generated);
57
59
  if (files.length === 0)
58
60
  return [];
59
61
  const cwd = path.join(context.root, directory);
@@ -75,7 +77,7 @@ async function findingsIn(context, directory) {
75
77
  }
76
78
  export const commentsEslint = {
77
79
  id: "comments-eslint",
78
- description: `ESLint lints every TypeScript and JavaScript file and refuses its comments with ${RULE} as an error`,
80
+ description: `ESLint lints every TypeScript and JavaScript file but the web app's generated API types and refuses its comments with ${RULE} as an error`,
79
81
  profiles: LINTED_PROFILES,
80
82
  check: async (context) => (await Promise.all(lintedDirectories(context).map((directory) => findingsIn(context, directory)))).flat(),
81
83
  };
@@ -1,4 +1,5 @@
1
1
  import { appsettingsBound } from "./appsettingsBound.js";
2
2
  import { bannedNugetPackages } from "./bannedNugetPackages.js";
3
+ import { suwbackkitWiring } from "./suwbackkitWiring.js";
3
4
  import { unusedNugetVersions } from "./unusedNugetVersions.js";
4
- export const dotnetGuards = [bannedNugetPackages, unusedNugetVersions, appsettingsBound];
5
+ export const dotnetGuards = [bannedNugetPackages, unusedNugetVersions, appsettingsBound, suwbackkitWiring];
@@ -0,0 +1,2 @@
1
+ import type { Guard } from "../../gate/contract.ts";
2
+ export declare const suwbackkitWiring: Guard;
@@ -0,0 +1,31 @@
1
+ import path from "node:path";
2
+ import { dotnetFiles } from "./msbuild.js";
3
+ const PROJECT = /\.csproj$/;
4
+ const CSHARP = /\.cs$/;
5
+ const WEB_SDK = /<Project\b[^>]*\bSdk\s*=\s*"Microsoft\.NET\.Sdk\.Web"/;
6
+ const KIT_REFERENCE = /<(?:PackageReference\b[^>]*\bInclude\s*=\s*"Suwbackkit\.Server"|ProjectReference\b[^>]*\bInclude\s*=\s*"[^"]*Suwbackkit\.Server\.csproj")/;
7
+ const CALLS = [
8
+ { method: "AddServerDefaults", pattern: /\.AddServerDefaults\s*(?:<[^>]*>)?\s*\(/, on: "the builder (builder.AddServerDefaults())" },
9
+ { method: "MapServerDefaults", pattern: /\.MapServerDefaults\s*\(/, on: "the app (app.MapServerDefaults())" },
10
+ ];
11
+ function findingsOf(context, project) {
12
+ const folder = path.posix.dirname(project);
13
+ const sources = dotnetFiles(context, CSHARP)
14
+ .filter((file) => folder === "." || file.startsWith(`${folder}/`))
15
+ .map((file) => context.read(file));
16
+ return CALLS.filter((call) => !sources.some((text) => call.pattern.test(text))).map((call) => ({
17
+ target: project,
18
+ message: `the server references Suwbackkit.Server but never calls ${call.method}: call it on ${call.on} where the server is built, so it gets the kit's logging, problem details, OpenAPI and the /health and /alive checks`,
19
+ }));
20
+ }
21
+ export const suwbackkitWiring = {
22
+ id: "suwbackkit-wiring",
23
+ description: "A web server that references Suwbackkit.Server calls AddServerDefaults and MapServerDefaults, so the kit is wired, not only installed",
24
+ profiles: ["dotnet"],
25
+ check: (context) => dotnetFiles(context, PROJECT)
26
+ .filter((project) => {
27
+ const text = context.read(project);
28
+ return WEB_SDK.test(text) && KIT_REFERENCE.test(text);
29
+ })
30
+ .flatMap((project) => findingsOf(context, project)),
31
+ };
@@ -0,0 +1,3 @@
1
+ import type { Guard } from "../../gate/contract.ts";
2
+ export declare function appliesToEvery(glob: string, extension: string): boolean;
3
+ export declare const configContents: Guard;