@maniumek/suwgate 0.2.0 → 0.4.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 (62) hide show
  1. package/README.md +132 -24
  2. package/dist/cli.js +49 -5
  3. package/dist/dev/db.d.ts +1 -1
  4. package/dist/dev/db.js +25 -0
  5. package/dist/dev/logs.js +9 -1
  6. package/dist/dev/settings.d.ts +2 -0
  7. package/dist/dev/settings.js +5 -2
  8. package/dist/eslint/index.js +4 -1
  9. package/dist/gate/check.d.ts +10 -0
  10. package/dist/gate/check.js +94 -18
  11. package/dist/gate/config.d.ts +19 -1
  12. package/dist/gate/config.js +119 -4
  13. package/dist/gate/contract.d.ts +13 -0
  14. package/dist/gate/guardsStep.d.ts +3 -1
  15. package/dist/gate/guardsStep.js +14 -3
  16. package/dist/gate/plan.d.ts +20 -1
  17. package/dist/gate/plan.js +92 -20
  18. package/dist/gate/report.d.ts +1 -0
  19. package/dist/gate/report.js +12 -3
  20. package/dist/gate/repository.d.ts +1 -0
  21. package/dist/gate/repository.js +8 -0
  22. package/dist/gate/runner.js +18 -3
  23. package/dist/guards/comments/hash.js +22 -1
  24. package/dist/guards/dotnet/appsettingsBound.js +29 -2
  25. package/dist/guards/dotnet/index.js +2 -1
  26. package/dist/guards/dotnet/suwbackkitWiring.d.ts +2 -0
  27. package/dist/guards/dotnet/suwbackkitWiring.js +31 -0
  28. package/dist/guards/repository/imagePins.js +1 -1
  29. package/dist/guards/repository/index.js +2 -0
  30. package/dist/guards/repository/justModules.js +28 -10
  31. package/dist/guards/repository/noRawColors.js +1 -1
  32. package/dist/guards/repository/scriptsCalled.js +38 -11
  33. package/dist/guards/repository/suwfrontkitWiring.d.ts +2 -0
  34. package/dist/guards/repository/suwfrontkitWiring.js +52 -0
  35. package/dist/profiles/contract.js +81 -38
  36. package/dist/profiles/criteria.d.ts +1 -0
  37. package/dist/profiles/criteria.js +1 -1
  38. package/dist/profiles/criteriaRan.d.ts +22 -0
  39. package/dist/profiles/criteriaRan.js +152 -0
  40. package/dist/profiles/database.js +11 -4
  41. package/dist/profiles/dotnet.d.ts +2 -0
  42. package/dist/profiles/dotnet.js +39 -6
  43. package/dist/profiles/dotnetGuards.d.ts +3 -0
  44. package/dist/profiles/dotnetGuards.js +54 -0
  45. package/dist/profiles/everyRepository.js +2 -0
  46. package/dist/profiles/index.d.ts +2 -0
  47. package/dist/profiles/index.js +2 -0
  48. package/dist/profiles/library.js +12 -7
  49. package/dist/profiles/node.js +21 -7
  50. package/dist/profiles/presets/knip.d.ts +1 -0
  51. package/dist/profiles/presets/knip.js +4 -2
  52. package/dist/profiles/presets/playwright.d.ts +3 -1
  53. package/dist/profiles/presets/playwright.js +7 -1
  54. package/dist/profiles/reports.d.ts +35 -0
  55. package/dist/profiles/reports.js +60 -0
  56. package/dist/profiles/shell.d.ts +6 -0
  57. package/dist/profiles/shell.js +39 -4
  58. package/dist/profiles/verdict.d.ts +9 -0
  59. package/dist/profiles/verdict.js +124 -0
  60. package/dist/profiles/web.js +25 -6
  61. package/package.json +2 -2
  62. package/schema/suwgate.schema.json +82 -4
@@ -0,0 +1,152 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { CRITERIA_FILE, criteriaConfig } from "./criteria.js";
5
+ import { excludedTraits } from "./dotnet.js";
6
+ import { readRun } from "./reports.js";
7
+ import { quoted, read, tracked, verdictCommand } from "./shell.js";
8
+ const REPORTED = {
9
+ "test (xunit)": { step: "dotnet-test", format: "xunit" },
10
+ "web test (vitest)": { step: "unit-tests", format: "vitest" },
11
+ "unit test (vitest)": { step: "unit-tests", format: "vitest" },
12
+ "story test (vitest, Chromium)": { step: "stories", format: "vitest" },
13
+ "e2e test (playwright)": { step: "e2e", format: "playwright" },
14
+ "visual test (playwright)": { step: "visual", format: "playwright" },
15
+ "consumer test (playwright)": { step: "consumer-app", format: "playwright" },
16
+ };
17
+ const REPORT_FILE = { vitest: "vitest.json", playwright: "playwright.json", xunit: "results" };
18
+ const ACCEPTANCE = /data-role="acceptance"[\s\S]*?(?=data-role="|$)/g;
19
+ const CODE = /<code>([A-Za-z][\w.]*(?:-[\w.]+)*-\d+)<\/code>/g;
20
+ export function criterionIds(spec) {
21
+ return [...new Set([...spec.matchAll(ACCEPTANCE)].flatMap((section) => [...section[0].matchAll(CODE)].map((code) => code[1] ?? "")))];
22
+ }
23
+ export function names(text, id, format) {
24
+ if (format === "xunit")
25
+ return new RegExp(`Trait\\(\\s*"criterion"\\s*,\\s*"${id.replace(/[.]/g, "\\.")}"\\s*\\)`).test(text);
26
+ return ['"', "'", "`"].some((quote) => text.includes(`${quote}${id}:`));
27
+ }
28
+ const ATTRIBUTE = /^\s*\[/;
29
+ const TYPE = /\b(class|record|struct)\s+\w+/;
30
+ function attributesAround(lines, index) {
31
+ let first = index;
32
+ while (first > 0 && ATTRIBUTE.test(lines[first - 1] ?? ""))
33
+ first--;
34
+ let last = index;
35
+ while (last + 1 < lines.length && ATTRIBUTE.test(lines[last + 1] ?? ""))
36
+ last++;
37
+ return lines.slice(first, last + 1).join("\n");
38
+ }
39
+ function escaped(text) {
40
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
41
+ }
42
+ function hasTrait(attributes, trait) {
43
+ const [name = "", value = ""] = trait.split("=");
44
+ return new RegExp(`Trait\\(\\s*"${escaped(name)}"\\s*,\\s*"${escaped(value)}"\\s*\\)`).test(attributes);
45
+ }
46
+ function typeAttributes(lines, index) {
47
+ const typeLine = lines.slice(0, index).findLastIndex((line) => TYPE.test(line));
48
+ return typeLine > 0 && ATTRIBUTE.test(lines[typeLine - 1] ?? "") ? attributesAround(lines, typeLine - 1) : "";
49
+ }
50
+ function outsideTheGate(text, id, traits) {
51
+ if (traits.length === 0)
52
+ return false;
53
+ const lines = text.split("\n");
54
+ const naming = lines.flatMap((line, index) => (names(line, id, "xunit") ? [index] : []));
55
+ return (naming.length > 0 &&
56
+ naming.every((index) => {
57
+ const attributes = `${attributesAround(lines, index)}\n${typeAttributes(lines, index)}`;
58
+ return traits.some((trait) => hasTrait(attributes, trait));
59
+ }));
60
+ }
61
+ function proven(passed, id) {
62
+ return passed.some((title) => title.startsWith(`${id}:`) || title.includes(` ${id}:`));
63
+ }
64
+ function listed(root, patterns) {
65
+ if (patterns.length === 0)
66
+ return [];
67
+ try {
68
+ return execFileSync("git", ["ls-files", "--cached", "--others", "--exclude-standard", "-z", "--", ...patterns.map((p) => `:(glob)${p}`)], {
69
+ cwd: root,
70
+ encoding: "utf8",
71
+ stdio: ["ignore", "pipe", "ignore"],
72
+ })
73
+ .split("\0")
74
+ .filter((file) => file !== "");
75
+ }
76
+ catch {
77
+ return [];
78
+ }
79
+ }
80
+ export function criteriaRan(input) {
81
+ const ids = [...new Set(input.specs.flatMap((spec) => criterionIds(readFileSync(path.join(input.root, spec), "utf8"))))];
82
+ const runs = new Map(input.sources.map((source) => [
83
+ source.step,
84
+ source.skipped === undefined ? readRun(source.format, path.join(input.run, source.report)) : null,
85
+ ]));
86
+ const texts = input.sources.map((source) => ({
87
+ source,
88
+ files: listed(input.root, source.patterns).map((file) => ({ file, text: readFileSync(path.join(input.root, file), "utf8") })),
89
+ }));
90
+ return ids.flatMap((id) => {
91
+ const naming = texts.flatMap(({ source, files }) => files
92
+ .filter((file) => names(file.text, id, source.format))
93
+ .map((file) => ({ source, file: file.file, outside: outsideTheGate(file.text, id, source.excludeTraits ?? []) })));
94
+ const checked = naming.filter((entry) => entry.source.skipped === undefined);
95
+ if (checked.length === 0)
96
+ return [];
97
+ if (checked.every((entry) => entry.outside)) {
98
+ const traits = [...new Set(checked.flatMap((entry) => entry.source.excludeTraits ?? []))].join(", ");
99
+ return [
100
+ `${id}: named only by tests outside the gate (${traits}, excludeTraits of dotnet-test in suwgate.yml): ${checked.map((entry) => entry.file).join(", ")}. The gate never runs them, so nothing in it proves the criterion: add a test the gate runs that names it, with a stand-in for the outside service (a fake model or server), and keep the outside test for the real one`,
101
+ ];
102
+ }
103
+ if (checked.some((entry) => proven(runs.get(entry.source.step)?.passed ?? [], id)))
104
+ return [];
105
+ const unreported = [...new Set(checked.filter((entry) => runs.get(entry.source.step) === null).map((entry) => entry.source.step))];
106
+ const why = unreported.length > 0 ? `${unreported.join(", ")} wrote no report` : "skipped, filtered out, or failed";
107
+ return [
108
+ `${id}: named by ${checked.map((entry) => `${entry.file} (${entry.source.step})`).join(", ")}, but no test naming it ran and passed in this gate run (${why}): make that test run and pass, or skip its step in suwgate.yml (steps.skip) with a reason`,
109
+ ];
110
+ });
111
+ }
112
+ function specsFolder(context) {
113
+ const text = read({ ...context, cwd: context.root }, CRITERIA_FILE);
114
+ try {
115
+ const parsed = text === null ? {} : JSON.parse(text);
116
+ return typeof parsed.specs === "string" ? parsed.specs : "docs/visual/spec";
117
+ }
118
+ catch {
119
+ return "docs/visual/spec";
120
+ }
121
+ }
122
+ export function criteriaRanInput(context) {
123
+ const root = { ...context, cwd: context.root };
124
+ const specs = tracked(root, [`${specsFolder(context)}/*.html`]);
125
+ if (specs.length === 0)
126
+ return null;
127
+ const sources = criteriaConfig(context, {}).kinds.flatMap((kind) => {
128
+ const reported = REPORTED[kind.kind];
129
+ if (reported === undefined)
130
+ return [];
131
+ return [
132
+ {
133
+ ...reported,
134
+ report: path.posix.join(reported.step, REPORT_FILE[reported.format]),
135
+ patterns: kind.paths,
136
+ ...(context.skippedSteps.includes(reported.step) ? { skipped: "skipped in suwgate.yml" } : {}),
137
+ ...(reported.format === "xunit" && excludedTraits(context).length > 0 ? { excludeTraits: excludedTraits(context) } : {}),
138
+ },
139
+ ];
140
+ });
141
+ return { root: context.root, specs, sources };
142
+ }
143
+ export const criteriaRanStep = {
144
+ id: "criteria-ran",
145
+ title: "every acceptance criterion a test names ran and passed in this gate run (the test tools' reports)",
146
+ after: ["unit-tests", "stories", "e2e", "visual", "consumer-app", "dotnet-test"],
147
+ run: (context) => {
148
+ const input = criteriaRanInput(context);
149
+ return input === null ? null : verdictCommand(`criteria "\${SUWGATE_RUN:-/no-run-folder}" ${quoted(JSON.stringify(input))}`);
150
+ },
151
+ limitSeconds: 60,
152
+ };
@@ -1,23 +1,30 @@
1
- import { has, script } from "./shell.js";
1
+ import { databaseUpCommand, has, script, suwgate } from "./shell.js";
2
2
  export const DATABASE_UP = "database-up";
3
3
  const COMPOSE_FILES = ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"];
4
+ const IN_CI = 'if [ -n "${CI:-}" ]; then echo "CI: the workflow starts the database (database: true of the reusable gate workflow)"; exit 0; fi';
4
5
  const UP = script([
5
- 'if [ -n "${CI:-}" ]; then echo "CI: the workflow starts the database (database: true of the reusable gate workflow)"; exit 0; fi',
6
+ IN_CI,
6
7
  "docker compose --profile db up -d --wait db >/dev/null 2>&1 || {",
7
8
  ' echo "postgres did not start — see: docker compose --profile db logs db" >&2',
8
9
  " exit 1",
9
10
  "}",
10
11
  ]);
12
+ const OWN_UP = script([IN_CI, `${suwgate("dev db up")} >/dev/null`]);
13
+ function databaseUp(context) {
14
+ if (databaseUpCommand(context) !== null)
15
+ return OWN_UP;
16
+ return composeFile(context) ? UP : null;
17
+ }
11
18
  export function composeFile(context) {
12
19
  return COMPOSE_FILES.some((file) => has(context, file));
13
20
  }
14
21
  export const databaseSteps = [
15
22
  {
16
23
  id: DATABASE_UP,
17
- title: "the local database for the tests (docker compose --profile db up --wait db; in CI the workflow starts it)",
24
+ title: "the local database for the tests (docker compose --profile db up --wait db, or dev.database.up of suwgate.yml; in CI the workflow starts it)",
18
25
  profile: "database",
19
26
  needs: ["docker"],
20
- run: (context) => (composeFile(context) ? UP : null),
27
+ run: databaseUp,
21
28
  limitSeconds: 120,
22
29
  },
23
30
  ];
@@ -2,6 +2,8 @@ import type { Step, StepContext } from "../gate/contract.ts";
2
2
  export declare const NO_IDLE_BUILD_PROCESSES = "export MSBUILDDISABLENODEREUSE=1 DOTNET_CLI_USE_MSBUILD_SERVER=0";
3
3
  export declare const DOTNET_BUILD = "dotnet-build";
4
4
  export declare const DOTNET_TEST = "dotnet-test";
5
+ export declare function excludedTraits(context: StepContext): string[];
5
6
  export declare function inCheckoutEnv(context: StepContext, command: string): string;
6
7
  export declare function guardTests(context: StepContext): string | null;
8
+ export declare function witnessed(context: StepContext, tests: string): string;
7
9
  export declare const dotnetSteps: readonly Step[];
@@ -1,14 +1,36 @@
1
1
  import { DATABASE_UP } from "./database.js";
2
- import { CHECKOUT_ENV, changedIn, hasDevSection, quoted, read, tracked, withChanged } from "./shell.js";
2
+ import { requiredGuards } from "./dotnetGuards.js";
3
+ import { CHECKOUT_ENV, changedIn, hasDevSection, quoted, read, runDirectory, settingsOf, tracked, verdictCommand, withChanged, } from "./shell.js";
3
4
  const DOTNET_INPUT = /\.(cs|csproj|props|targets|slnx|sln|rsp)$|(^|\/)(\.editorconfig|BannedSymbols\.txt|global\.json|packages\.lock\.json|nuget\.config)$/;
4
5
  const GUARD_PACKAGE = /<(PackageReference|ProjectReference)\b[^>]*(?:Include|Update)="[^"]*Suwgate\.(Architecture|Database)\b/;
5
6
  const TEST_PROJECT = /<PackageReference\b[^>]*Include="xunit\.v3"|<IsTestProject>true<\/IsTestProject>/;
6
7
  export const NO_IDLE_BUILD_PROCESSES = "export MSBUILDDISABLENODEREUSE=1 DOTNET_CLI_USE_MSBUILD_SERVER=0";
7
8
  const BUILD = `${NO_IDLE_BUILD_PROCESSES} && dotnet build --nologo -v quiet`;
8
- const TEST = "dotnet test --no-build --no-progress";
9
+ const TEST_OPTIONS = '--no-build --no-progress --zero-tests-policy strict --report-xunit-xml --results-directory "$run/results"';
9
10
  const FORMAT = `${NO_IDLE_BUILD_PROCESSES} && dotnet tool restore >/dev/null`;
10
11
  export const DOTNET_BUILD = "dotnet-build";
11
12
  export const DOTNET_TEST = "dotnet-test";
13
+ const TRAIT = "^[^=\\s]+=[^=\\s]+$";
14
+ const DOTNET_TEST_SETTINGS = {
15
+ type: "object",
16
+ additionalProperties: false,
17
+ properties: {
18
+ excludeTraits: {
19
+ description: "Traits (name=value) of the tests outside the gate, e.g. live=true for tests that call a real model: dotnet-test leaves them out (--filter-not-trait), and criteria-ran says so when a criterion is named only by them.",
20
+ type: "array",
21
+ minItems: 1,
22
+ uniqueItems: true,
23
+ items: { type: "string", pattern: TRAIT },
24
+ },
25
+ },
26
+ };
27
+ export function excludedTraits(context) {
28
+ return settingsOf(context, DOTNET_TEST).excludeTraits ?? [];
29
+ }
30
+ function testOptions(context) {
31
+ const traits = excludedTraits(context);
32
+ return traits.length === 0 ? TEST_OPTIONS : `${TEST_OPTIONS} --filter-not-trait ${traits.map(quoted).join(" ")}`;
33
+ }
12
34
  function dotnetChanged(context) {
13
35
  return changedIn(context, DOTNET_INPUT).length > 0;
14
36
  }
@@ -26,7 +48,16 @@ export function guardTests(context) {
26
48
  });
27
49
  if (projects.length === 0)
28
50
  return null;
29
- return projects.map((project) => `dotnet test --project ${quoted(project)} --no-build --no-progress`).join(" && ");
51
+ return projects.map((project) => `dotnet test --project ${quoted(project)} ${testOptions(context)}`).join(" && ");
52
+ }
53
+ export function witnessed(context, tests) {
54
+ return [
55
+ runDirectory(DOTNET_TEST),
56
+ 'export SUWGATE_EVIDENCE="$run/evidence"',
57
+ tests,
58
+ verdictCommand(`tests xunit "$run/results" ${quoted("dotnet test")}`),
59
+ `{ [ $# -gt 0 ] || ${verdictCommand(`guards "$run/evidence" ${requiredGuards(context).map(quoted).join(" ")}`)}; }`,
60
+ ].join(" && ");
30
61
  }
31
62
  export const dotnetSteps = [
32
63
  {
@@ -52,15 +83,17 @@ export const dotnetSteps = [
52
83
  },
53
84
  {
54
85
  id: DOTNET_TEST,
55
- title: "tests (dotnet test, xUnit v3, with the checkout's databases when suwgate.yml has dev; --quick: the projects that test with Suwgate.Architecture or Suwgate.Database)",
86
+ title: "tests (dotnet test, xUnit v3, with the checkout's databases when suwgate.yml has dev; fails on 0 tests run and, without arguments, unless every .NET guard of the profiles ran; --quick: the projects that test with Suwgate.Architecture or Suwgate.Database)",
56
87
  profile: "dotnet",
57
88
  needs: ["dotnet"],
58
89
  after: [DOTNET_BUILD, DATABASE_UP],
59
- run: (context) => inCheckoutEnv(context, TEST),
90
+ run: (context) => inCheckoutEnv(context, witnessed(context, `dotnet test ${testOptions(context)} "$@"`)),
60
91
  quick: (context) => {
61
92
  const command = guardTests(context);
62
- return command === null ? null : inCheckoutEnv(context, command);
93
+ return command === null ? null : inCheckoutEnv(context, witnessed(context, command));
63
94
  },
95
+ args: "dotnet test, xUnit v3 on Microsoft.Testing.Platform",
96
+ settingsSchema: DOTNET_TEST_SETTINGS,
64
97
  limitSeconds: 600,
65
98
  },
66
99
  ];
@@ -0,0 +1,3 @@
1
+ import type { DotnetGuard, StepContext } from "../gate/contract.ts";
2
+ export declare const dotnetGuards: readonly DotnetGuard[];
3
+ export declare function requiredGuards(context: StepContext): string[];
@@ -0,0 +1,54 @@
1
+ const ARCHITECTURE = [
2
+ "layers",
3
+ "endpoints",
4
+ "project-references",
5
+ "every-project-guarded",
6
+ "interfaces-have-two-implementations",
7
+ "nothing-obsolete",
8
+ "no-unused-types",
9
+ "forbidden-type-names",
10
+ "unique-type-names",
11
+ "one-type-per-file",
12
+ "no-escape-hatches",
13
+ "no-fixture-in-field",
14
+ "build-settings",
15
+ ];
16
+ const ARCHITECTURE_SETTINGS = {
17
+ "no-escape-hatches": {
18
+ type: "object",
19
+ additionalProperties: false,
20
+ properties: {
21
+ nullForgivingInTests: {
22
+ type: "boolean",
23
+ description: "Allow the null-forgiving ! in the sources of test projects (folders ending in .Tests); dynamic stays banned there.",
24
+ },
25
+ },
26
+ },
27
+ };
28
+ export const dotnetGuards = [
29
+ ...ARCHITECTURE.map((name) => ({
30
+ id: `architecture/${name}`,
31
+ profile: "dotnet",
32
+ ...(ARCHITECTURE_SETTINGS[name] === undefined ? {} : { settingsSchema: ARCHITECTURE_SETTINGS[name] }),
33
+ })),
34
+ {
35
+ id: "database/migration-script-names",
36
+ profile: "database",
37
+ settingsSchema: {
38
+ type: "object",
39
+ additionalProperties: false,
40
+ properties: {
41
+ directory: {
42
+ type: "string",
43
+ pattern: "^[^/\\\\][^\\\\]*$",
44
+ description: "The folder of the NNNN_what_it_does.sql scripts, when it is not the one Migrations/up folder.",
45
+ },
46
+ },
47
+ },
48
+ },
49
+ ];
50
+ export function requiredGuards(context) {
51
+ return dotnetGuards
52
+ .filter((guard) => context.profiles.includes(guard.profile) && !context.skippedGuards.includes(guard.id))
53
+ .map((guard) => guard.id);
54
+ }
@@ -1,4 +1,5 @@
1
1
  import { criteriaStep } from "./criteria.js";
2
+ import { criteriaRanStep } from "./criteriaRan.js";
2
3
  import { composeFile } from "./database.js";
3
4
  import { withChanged } from "./shell.js";
4
5
  const SHELL_SCRIPT = /\.sh$|^\.githooks\/[^/]+$/;
@@ -11,6 +12,7 @@ export const everyRepositorySteps = [
11
12
  limitSeconds: 120,
12
13
  },
13
14
  criteriaStep,
15
+ criteriaRanStep,
14
16
  {
15
17
  id: "shellcheck",
16
18
  title: "shell scripts (shellcheck)",
@@ -1,2 +1,4 @@
1
1
  import { type Profile, type Step } from "../gate/contract.ts";
2
+ export { dotnetGuards } from "./dotnetGuards.ts";
3
+ export { verdict } from "./verdict.ts";
2
4
  export declare function stepsFor(profiles: readonly Profile[]): Step[];
@@ -6,6 +6,8 @@ import { everyRepositorySteps } from "./everyRepository.js";
6
6
  import { librarySteps } from "./library.js";
7
7
  import { nodeSteps } from "./node.js";
8
8
  import { webSteps } from "./web.js";
9
+ export { dotnetGuards } from "./dotnetGuards.js";
10
+ export { verdict } from "./verdict.js";
9
11
  const BY_PROFILE = {
10
12
  web: [...nodeSteps("web"), ...webSteps, ...contractSteps],
11
13
  library: [...nodeSteps("library"), ...librarySteps],
@@ -1,5 +1,5 @@
1
1
  import { PNPM_INSTALL } from "./node.js";
2
- import { has, quoted, read, script } from "./shell.js";
2
+ import { countedPlaywright, countedVitest, has, quoted, read, runDirectory, script, verdictCommand } from "./shell.js";
3
3
  const CHANGESET = script([
4
4
  'base=""',
5
5
  "if git rev-parse --verify -q origin/master >/dev/null; then base=origin/master; elif git rev-parse --verify -q master >/dev/null; then base=master; fi",
@@ -24,11 +24,11 @@ function consumerAppCommand(build) {
24
24
  `cp -r ${CONSUMER}/app "$work/app"`,
25
25
  `(cd "$work/app" && pnpm add "$tarball" --silent && ${build})`,
26
26
  `port="$(node -e 'const server = require("node:net").createServer().listen(0, "127.0.0.1", () => { console.log(server.address().port); server.close(); });')"`,
27
- `CONSUMER_APP="$work/app" CONSUMER_PORT="$port" pnpm exec playwright test -c ${CONSUMER}/playwright.config.ts`,
27
+ countedPlaywright("consumer-app", `CONSUMER_APP="$work/app" CONSUMER_PORT="$port" pnpm exec playwright test -c ${CONSUMER}/playwright.config.ts`).join(" && "),
28
28
  ]);
29
29
  }
30
30
  function stories(context) {
31
- return has(context, STORYBOOK) ? "pnpm exec vitest run --project stories" : null;
31
+ return has(context, STORYBOOK) ? countedVitest("stories", "pnpm exec vitest run --project stories") : null;
32
32
  }
33
33
  function playwrightVersion(context) {
34
34
  const manifest = read(context, "node_modules/@playwright/test/package.json");
@@ -44,10 +44,12 @@ export function visual(context) {
44
44
  if (version === null) {
45
45
  return `echo "${VISUAL_CONFIG} runs in the Playwright image of the installed @playwright/test, which is not installed: pnpm add -D @playwright/test" >&2; exit 1`;
46
46
  }
47
- return script([
47
+ return [
48
48
  "pnpm exec storybook build --quiet -o storybook-static >/dev/null",
49
- `docker run --rm --init --ipc=host --security-opt label=disable -v "$PWD:/work" -w /work -e CI mcr.microsoft.com/playwright:v${version}-noble node_modules/.bin/playwright test -c ${VISUAL_CONFIG}`,
50
- ]);
49
+ runDirectory("visual"),
50
+ `docker run --rm --init --ipc=host --security-opt label=disable -v "$PWD:/work" -v "$run:/suwgate-run" -w /work -e CI -e PLAYWRIGHT_JSON_OUTPUT_FILE=/suwgate-run/playwright.json mcr.microsoft.com/playwright:v${version}-noble node_modules/.bin/playwright test -c ${VISUAL_CONFIG} --reporter=line,json "$@"`,
51
+ verdictCommand(`tests playwright "$run/playwright.json" ${quoted("playwright (visual)")}`),
52
+ ].join(" && ");
51
53
  }
52
54
  const NOT_A_MODULE = /\.(css|json)$/;
53
55
  function targets(entry) {
@@ -77,11 +79,12 @@ const after = [PNPM_INSTALL];
77
79
  export const librarySteps = [
78
80
  {
79
81
  id: "stories",
80
- title: "stories as tests with axe (vitest project stories, Chromium)",
82
+ title: "stories as tests with axe (vitest project stories, Chromium; 0 tests run fails)",
81
83
  profile: "library",
82
84
  needs: ["pnpm"],
83
85
  after,
84
86
  run: stories,
87
+ args: "vitest run --project stories",
85
88
  limitSeconds: 600,
86
89
  },
87
90
  {
@@ -109,6 +112,7 @@ export const librarySteps = [
109
112
  needs: ["pnpm", "node"],
110
113
  after: ["attw"],
111
114
  run: consumerApp,
115
+ args: "playwright test",
112
116
  limitSeconds: 900,
113
117
  },
114
118
  {
@@ -118,6 +122,7 @@ export const librarySteps = [
118
122
  needs: ["pnpm", "docker"],
119
123
  after,
120
124
  run: visual,
125
+ args: "playwright test, in the Playwright image",
121
126
  limitSeconds: 900,
122
127
  },
123
128
  {
@@ -1,8 +1,10 @@
1
- import { changedIn, filesIn, has, read, withChanged } from "./shell.js";
1
+ import { changedIn, countedVitest, filesIn, has, quoted, read, tracked, verdictCommand, withChanged } from "./shell.js";
2
2
  const CODE = /\.(ts|tsx|js|jsx|mjs|cjs|mts|cts)$/;
3
3
  const TSCONFIG = /^tsconfig(\..+)?\.json$/;
4
4
  const VITEST_CONFIG = /^vitest\.config\.(ts|mts|js|mjs)$/;
5
5
  const UNIT_PROJECT = /\bname:\s*["'`]unit["'`]|\bunitTests\(/;
6
+ const NOT_A_SOURCE = /\.(test|stories|e2e|visual|spec)\.[cm]?[jt]sx?$|\.d\.ts$/;
7
+ const ENFORCED_RULES = ["suwgate/no-comments", "boundaries/dependencies"];
6
8
  export const PNPM_INSTALL = "pnpm-install";
7
9
  function install(context) {
8
10
  return has(context, "node_modules") ? null : "pnpm install --frozen-lockfile --silent";
@@ -10,11 +12,22 @@ function install(context) {
10
12
  export function typecheck(context) {
11
13
  const configs = filesIn(context, TSCONFIG).filter((file) => file !== "tsconfig.build.json");
12
14
  const ordered = [...configs.filter((file) => file === "tsconfig.json"), ...configs.filter((file) => file !== "tsconfig.json")];
13
- return (ordered.length === 0 ? ["tsconfig.json"] : ordered).map((file) => `pnpm exec tsc --noEmit -p ${file}`).join(" && ");
15
+ return (ordered.length === 0 ? ["tsconfig.json"] : ordered)
16
+ .map((file) => `pnpm exec tsc --noEmit -p ${file} && pnpm exec tsc --showConfig -p ${file} | ${verdictCommand(`tsconfig ${quoted(file)}`)}`)
17
+ .join(" && ");
18
+ }
19
+ function lint(context) {
20
+ const source = tracked(context, ["src/*.ts", "src/*.tsx"]).find((file) => !NOT_A_SOURCE.test(file));
21
+ const rules = source === undefined
22
+ ? []
23
+ : [
24
+ `pnpm exec eslint --print-config ${quoted(source)} | ${verdictCommand(`eslint ${quoted(source)} ${ENFORCED_RULES.join(" ")}`)}`,
25
+ ];
26
+ return [...rules, "pnpm exec eslint . --max-warnings 0"].join(" && ");
14
27
  }
15
28
  export function unitTests(context) {
16
29
  const named = filesIn(context, VITEST_CONFIG).some((file) => UNIT_PROJECT.test(read(context, file) ?? ""));
17
- return named ? "pnpm exec vitest run --project unit" : "pnpm exec vitest run";
30
+ return countedVitest("unit-tests", named ? "pnpm exec vitest run --project unit" : "pnpm exec vitest run");
18
31
  }
19
32
  export function nodeSteps(profile) {
20
33
  const after = [PNPM_INSTALL];
@@ -30,7 +43,7 @@ export function nodeSteps(profile) {
30
43
  },
31
44
  {
32
45
  id: "typecheck",
33
- title: "typecheck (tsc, every tsconfig*.json but the build one)",
46
+ title: "typecheck (tsc, every tsconfig*.json but the build one; tsc --showConfig keeps the strict options of the preset on)",
34
47
  profile,
35
48
  needs: ["pnpm"],
36
49
  after,
@@ -40,21 +53,22 @@ export function nodeSteps(profile) {
40
53
  },
41
54
  {
42
55
  id: "lint",
43
- title: "lint (eslint)",
56
+ title: "lint (eslint; eslint --print-config of a source file keeps no-comments and boundaries at error)",
44
57
  profile,
45
58
  needs: ["pnpm"],
46
59
  after,
47
- run: "pnpm exec eslint . --max-warnings 0",
60
+ run: lint,
48
61
  quick: (context) => withChanged(context, CODE, "pnpm exec eslint --no-warn-ignored --max-warnings 0"),
49
62
  limitSeconds: 300,
50
63
  },
51
64
  {
52
65
  id: "unit-tests",
53
- title: "unit tests (vitest, the project unit when the config has several)",
66
+ title: "unit tests (vitest, the project unit when the config has several; 0 tests run fails)",
54
67
  profile,
55
68
  needs: ["pnpm"],
56
69
  after,
57
70
  run: unitTests,
71
+ args: "vitest run",
58
72
  limitSeconds: 300,
59
73
  },
60
74
  {
@@ -1,5 +1,6 @@
1
1
  export interface KnipConfig {
2
2
  ignore?: string[];
3
+ ignoreIssues?: Record<string, string[]>;
3
4
  ignoreDependencies?: string[];
4
5
  playwright?: {
5
6
  config?: string[];
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
- const STEP_TOOLS = ["publint", "@arethetypeswrong/cli", "openapi-typescript"];
3
+ const STEP_TOOLS = ["prettier", "publint", "@arethetypeswrong/cli", "openapi-typescript"];
4
+ const GENERATED_ISSUES = ["files", "exports", "nsExports", "types", "nsTypes", "enumMembers", "namespaceMembers", "duplicates"];
4
5
  const GENERATED = ["src/api/openapi.d.ts"];
5
6
  const PLAYWRIGHT_CONFIGS = ["e2e/playwright.config.ts", "visual/playwright.config.ts", "gate/consumer/playwright.config.ts"];
6
7
  function dependencies(directory) {
@@ -21,7 +22,8 @@ export function knip(config = {}, directory = process.cwd()) {
21
22
  const playwrightConfigs = [...PLAYWRIGHT_CONFIGS.filter(present), ...(config.playwright?.config ?? [])];
22
23
  return {
23
24
  ...config,
24
- ignore: [...GENERATED.filter(present), ...(config.ignore ?? [])],
25
+ ignore: [...(config.ignore ?? [])],
26
+ ignoreIssues: { ...Object.fromEntries(GENERATED.filter(present).map((file) => [file, GENERATED_ISSUES])), ...config.ignoreIssues },
25
27
  ignoreDependencies: [...STEP_TOOLS.filter((tool) => installed.includes(tool)), ...(config.ignoreDependencies ?? [])],
26
28
  ...(playwrightConfigs.length === 0 ? {} : { playwright: { ...config.playwright, config: playwrightConfigs } }),
27
29
  };
@@ -2,8 +2,10 @@ interface Use {
2
2
  baseURL?: string;
3
3
  [key: string]: unknown;
4
4
  }
5
+ type ReporterDescription = readonly [string] | readonly [string, unknown];
5
6
  interface PlaywrightConfig {
6
7
  use?: Use;
8
+ reporter?: string | readonly ReporterDescription[];
7
9
  [key: string]: unknown;
8
10
  }
9
11
  export declare function e2eTests<Config extends PlaywrightConfig>(config: Config): {
@@ -12,7 +14,6 @@ export declare function e2eTests<Config extends PlaywrightConfig>(config: Config
12
14
  workers: number;
13
15
  retries: number;
14
16
  failOnFlakyTests: boolean;
15
- reporter: "list";
16
17
  timeout: number;
17
18
  projects: {
18
19
  name: string;
@@ -25,6 +26,7 @@ export declare function e2eTests<Config extends PlaywrightConfig>(config: Config
25
26
  };
26
27
  }[];
27
28
  } & Config & {
29
+ reporter: ReporterDescription[];
28
30
  use: {
29
31
  baseURL?: string;
30
32
  locale: string;
@@ -1,4 +1,10 @@
1
1
  const ci = () => Boolean(process.env["CI"]);
2
+ const GATE_REPORT = "PLAYWRIGHT_JSON_OUTPUT_FILE";
3
+ function withGateReport(reporter) {
4
+ const listed = typeof reporter === "string" ? reporter.split(",").map((name) => [name.trim()]) : [...reporter];
5
+ const wanted = (process.env[GATE_REPORT] ?? "") !== "" && !listed.some(([name]) => name === "json");
6
+ return wanted ? [...listed, ["json"]] : listed;
7
+ }
2
8
  export function e2eTests(config) {
3
9
  return {
4
10
  testDir: "../src",
@@ -6,10 +12,10 @@ export function e2eTests(config) {
6
12
  workers: 1,
7
13
  retries: ci() ? 1 : 0,
8
14
  failOnFlakyTests: ci(),
9
- reporter: "list",
10
15
  timeout: 60_000,
11
16
  projects: [{ name: "chromium", use: { browserName: "chromium", viewport: { width: 1440, height: 900 } } }],
12
17
  ...config,
18
+ reporter: withGateReport(config.reporter ?? "list"),
13
19
  use: { locale: "en-US", trace: "retain-on-failure", screenshot: "only-on-failure", ...config.use },
14
20
  };
15
21
  }
@@ -0,0 +1,35 @@
1
+ export type ReportFormat = "vitest" | "playwright" | "xunit";
2
+ export interface TestRun {
3
+ executed: number;
4
+ passed: string[];
5
+ }
6
+ interface VitestAssertion {
7
+ fullName?: string;
8
+ status?: string;
9
+ }
10
+ interface VitestReport {
11
+ testResults?: {
12
+ assertionResults?: VitestAssertion[];
13
+ }[];
14
+ }
15
+ interface PlaywrightSpec {
16
+ title?: string;
17
+ tests?: {
18
+ status?: string;
19
+ }[];
20
+ }
21
+ interface PlaywrightSuite {
22
+ title?: string;
23
+ file?: string;
24
+ specs?: PlaywrightSpec[];
25
+ suites?: PlaywrightSuite[];
26
+ }
27
+ interface PlaywrightReport {
28
+ suites?: PlaywrightSuite[];
29
+ }
30
+ export declare function vitestRun(report: VitestReport): TestRun;
31
+ export declare function playwrightRun(report: PlaywrightReport): TestRun;
32
+ export declare function xunitRun(xml: string): TestRun;
33
+ export declare function files(location: string, extension: string): string[];
34
+ export declare function readRun(format: ReportFormat, location: string): TestRun | null;
35
+ export {};