@maniumek/suwgate 0.3.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 (47) hide show
  1. package/README.md +92 -20
  2. package/dist/cli.js +38 -3
  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 +91 -19
  11. package/dist/gate/config.d.ts +12 -0
  12. package/dist/gate/config.js +87 -2
  13. package/dist/gate/contract.d.ts +6 -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 +89 -22
  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/repository/imagePins.js +1 -1
  26. package/dist/guards/repository/justModules.js +28 -10
  27. package/dist/guards/repository/noRawColors.js +1 -1
  28. package/dist/guards/repository/scriptsCalled.js +38 -11
  29. package/dist/profiles/contract.js +81 -38
  30. package/dist/profiles/criteriaRan.d.ts +1 -0
  31. package/dist/profiles/criteriaRan.js +44 -1
  32. package/dist/profiles/database.js +11 -4
  33. package/dist/profiles/dotnet.d.ts +1 -0
  34. package/dist/profiles/dotnet.js +28 -5
  35. package/dist/profiles/dotnetGuards.js +17 -1
  36. package/dist/profiles/library.js +4 -1
  37. package/dist/profiles/node.js +1 -0
  38. package/dist/profiles/presets/knip.d.ts +1 -0
  39. package/dist/profiles/presets/knip.js +4 -2
  40. package/dist/profiles/presets/playwright.d.ts +3 -1
  41. package/dist/profiles/presets/playwright.js +7 -1
  42. package/dist/profiles/shell.d.ts +3 -1
  43. package/dist/profiles/shell.js +22 -7
  44. package/dist/profiles/verdict.js +6 -2
  45. package/dist/profiles/web.js +24 -5
  46. package/package.json +1 -1
  47. package/schema/suwgate.schema.json +62 -3
@@ -1,31 +1,49 @@
1
1
  import { baseName } from "./text.js";
2
- const MOD_LINE = /^mod\??\s+([\w-]+)\s*$/gm;
2
+ const MOD_LINE = /^mod\??\s+([\w-]+)(?:\s+(['"])([^'"]+)\2)?\s*$/gm;
3
+ const SOURCES_IN_A_FOLDER = ["mod.just", "justfile", ".justfile"];
3
4
  function moduleName(file) {
4
5
  return file.endsWith("/mod.just") ? (file.split("/")[0] ?? "") : baseName(file).replace(/\.just$/, "");
5
6
  }
7
+ function normalized(file) {
8
+ return file.replace(/^\.\//, "").replace(/\/+$/, "");
9
+ }
10
+ function sourceOf(mod, files) {
11
+ if (mod.path === undefined)
12
+ return files.find((file) => file === `${mod.name}.just` || file === `${mod.name}/mod.just`);
13
+ const path = normalized(mod.path);
14
+ return files.includes(path) ? path : SOURCES_IN_A_FOLDER.map((name) => `${path}/${name}`).find((file) => files.includes(file));
15
+ }
6
16
  export const justModules = {
7
17
  id: "just-modules",
8
- description: "Every just module is <name>.just beside the justfile or <folder>/mod.just, and the justfile names each one with mod <name>",
18
+ description: "Every just module is <name>.just beside the justfile, <folder>/mod.just, or the file a mod line names by its path (mod <name> '<path>'), and the justfile names each one",
9
19
  profiles: "every",
10
20
  check(context) {
11
21
  const modules = context.files.filter((file) => file.endsWith(".just"));
12
- const named = context.files.includes("justfile")
13
- ? [...context.read("justfile").matchAll(MOD_LINE)].map((match) => match[1] ?? "")
22
+ const mods = context.files.includes("justfile")
23
+ ? [...context.read("justfile").matchAll(MOD_LINE)].map((match) => ({
24
+ name: match[1] ?? "",
25
+ ...(match[3] === undefined ? {} : { path: match[3] }),
26
+ }))
14
27
  : [];
28
+ const byPath = mods.filter((mod) => mod.path !== undefined).flatMap((mod) => sourceOf(mod, context.files) ?? []);
29
+ const named = mods.filter((mod) => mod.path === undefined).map((mod) => mod.name);
15
30
  const misplaced = modules
31
+ .filter((file) => !byPath.includes(file))
16
32
  .filter((file) => file.includes("/") && (baseName(file) !== "mod.just" || file.split("/").length !== 2))
17
33
  .map((file) => ({
18
34
  target: file,
19
- message: "just finds a module only as <name>.just beside the justfile or as <folder>/mod.just: move it there",
35
+ message: "just finds a module by its name only as <name>.just beside the justfile or as <folder>/mod.just: move it there, or name its path in the mod line (mod <name> '<path>')",
20
36
  }));
21
- const missing = named
22
- .filter((name) => !modules.includes(`${name}.just`) && !modules.includes(`${name}/mod.just`))
23
- .map((name) => ({
37
+ const missing = mods
38
+ .filter((mod) => sourceOf(mod, context.files) === undefined)
39
+ .map((mod) => ({
24
40
  target: "justfile",
25
- message: `mod ${name} has no ${name}.just or ${name}/mod.just: add the module, or delete the mod line`,
41
+ message: mod.path === undefined
42
+ ? `mod ${mod.name} has no ${mod.name}.just or ${mod.name}/mod.just: add the module, or delete the mod line`
43
+ : `mod ${mod.name} names ${mod.path}, which is not a module file here: fix the path, or delete the mod line`,
26
44
  }));
27
45
  const orphans = modules
28
- .filter((file) => !named.includes(moduleName(file)))
46
+ .filter((file) => !byPath.includes(file) && !named.includes(moduleName(file)))
29
47
  .filter((file) => !misplaced.some((finding) => finding.target === file))
30
48
  .map((file) => ({
31
49
  target: file,
@@ -1,5 +1,5 @@
1
1
  import { inProfileDirectory, numberedLines, stringList } from "./text.js";
2
- const RAW_COLOR = /#[0-9a-fA-F]{3,8}\b|\b(rgb|rgba|hsl|hsla|oklch|oklab)\(|\[#/;
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
4
  const TEST_FILE = /\.(test|spec|e2e)\.(ts|tsx|js|jsx)$/;
5
5
  export const noRawColors = {
@@ -1,12 +1,7 @@
1
- import { baseName } from "./text.js";
2
- const CALLER_FILES = new Set([
3
- "justfile",
4
- "package.json",
5
- "suwgate.yml",
6
- ".claude/settings.json",
7
- ".vscode/tasks.json",
8
- ".template.config/template.json",
9
- ]);
1
+ import { parse } from "yaml";
2
+ import { baseName, isRecord } from "./text.js";
3
+ const CONFIG_FILE = "suwgate.yml";
4
+ const CALLER_FILES = new Set(["justfile", "package.json", ".claude/settings.json", ".vscode/tasks.json", ".template.config/template.json"]);
10
5
  export function isScript(file) {
11
6
  return file.endsWith(".sh") || /(^|\/)scripts\/(.+\/)?[^/]+\.(ts|js|mjs|py|ps1)$/.test(file);
12
7
  }
@@ -18,16 +13,48 @@ function isCaller(file) {
18
13
  /\.(sh|just|csproj|proj|props|targets)$/.test(name) ||
19
14
  /^Dockerfile|\.Dockerfile$/.test(name) ||
20
15
  /^(docker-)?compose(\.[\w-]+)?\.ya?ml$/.test(name) ||
16
+ file === "hooks/hooks.json" ||
17
+ file.endsWith("/hooks/hooks.json") ||
21
18
  file.startsWith(".githooks/") ||
22
19
  file.startsWith(".github/workflows/") ||
23
20
  file.startsWith(".github/actions/"));
24
21
  }
22
+ function strings(value) {
23
+ if (typeof value === "string")
24
+ return [value];
25
+ if (Array.isArray(value))
26
+ return value.flatMap(strings);
27
+ return isRecord(value) ? Object.values(value).flatMap(strings) : [];
28
+ }
29
+ function commandsOfConfig(context) {
30
+ let parsed;
31
+ try {
32
+ parsed = parse(context.read(CONFIG_FILE));
33
+ }
34
+ catch {
35
+ return "";
36
+ }
37
+ if (!isRecord(parsed))
38
+ return "";
39
+ const steps = isRecord(parsed["steps"]) ? parsed["steps"] : {};
40
+ const added = Array.isArray(steps["add"]) ? steps["add"] : [];
41
+ return [
42
+ ...added.flatMap((step) => (isRecord(step) ? strings(step["run"]) : [])),
43
+ ...strings(steps["configure"]),
44
+ ...strings(parsed["env"]),
45
+ ...strings(parsed["dev"]),
46
+ ].join("\n");
47
+ }
48
+ function callersOf(context) {
49
+ const callers = context.files.filter(isCaller).map((file) => ({ file, text: context.read(file) }));
50
+ return context.files.includes(CONFIG_FILE) ? [...callers, { file: CONFIG_FILE, text: commandsOfConfig(context) }] : callers;
51
+ }
25
52
  export const scriptsCalled = {
26
53
  id: "scripts-called",
27
- description: "Every script (*.sh, and the files of a scripts/ folder) is called by a recipe, another script, a hook, the workflow or suwgate.yml",
54
+ description: "Every script (*.sh, and the files of a scripts/ folder) is called by a recipe, another script, a hook (also a Claude Code plugin's hooks/hooks.json), the workflow or a command of suwgate.yml (steps.add run, steps.configure, env, dev)",
28
55
  profiles: "every",
29
56
  check(context) {
30
- const callers = context.files.filter(isCaller).map((file) => ({ file, text: context.read(file) }));
57
+ const callers = callersOf(context);
31
58
  return context.files
32
59
  .filter(isScript)
33
60
  .filter((script) => !callers.some((caller) => caller.file !== script && caller.text.includes(baseName(script))))
@@ -2,9 +2,36 @@ import { existsSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { DOTNET_TEST, NO_IDLE_BUILD_PROCESSES } from "./dotnet.js";
4
4
  import { PNPM_INSTALL } from "./node.js";
5
- import { has, quoted, read, script, tracked } from "./shell.js";
6
- const CONTRACT = "contract/openapi.json";
7
- const CONTRACT_VERSION = "contract/package.json";
5
+ import { has, quoted, read, script, settingsOf, tracked } from "./shell.js";
6
+ const DEFAULT_CONTRACT = "contract/openapi.json";
7
+ const API_VERSION_STEP = "api-version";
8
+ const CONTRACT_SETTINGS = {
9
+ type: "object",
10
+ additionalProperties: false,
11
+ properties: {
12
+ contract: {
13
+ description: "Where the API contract is, relative to the dotnet directory (default contract/openapi.json); api-version compares the same file, and reads its version from the package.json beside it.",
14
+ type: "string",
15
+ pattern: "^[A-Za-z0-9._-][A-Za-z0-9._/-]*\\.json$",
16
+ },
17
+ },
18
+ };
19
+ const VERSION_SETTINGS = {
20
+ type: "object",
21
+ additionalProperties: false,
22
+ properties: {
23
+ breaking: {
24
+ description: "major (default): a breaking change of the contract needs a new major version in the package.json beside it; never: every breaking change fails, whatever the version.",
25
+ enum: ["major", "never"],
26
+ },
27
+ },
28
+ };
29
+ function contractOf(context) {
30
+ return settingsOf(context, API_CONTRACT).contract ?? DEFAULT_CONTRACT;
31
+ }
32
+ function versionFileOf(contract) {
33
+ return path.posix.join(path.posix.dirname(contract), "package.json");
34
+ }
8
35
  export const API_TYPES = "src/api/openapi.d.ts";
9
36
  export const API_CONTRACT = "api-contract";
10
37
  const GENERATOR = "Microsoft.Extensions.ApiDescription.Server";
@@ -22,14 +49,15 @@ function webApp(context) {
22
49
  return existsSync(path.join(directory, API_TYPES)) ? directory : null;
23
50
  }
24
51
  export function apiContract(context) {
25
- if (!has(context, CONTRACT))
52
+ const contract = contractOf(context);
53
+ if (!has(context, contract))
26
54
  return null;
27
55
  const servers = tracked(context, ["*.csproj"]).filter((project) => (read(context, project) ?? "").includes(GENERATOR));
28
56
  const [server, ...others] = servers;
29
57
  if (server === undefined)
30
- return fail(`${CONTRACT} is there, but no project writes it: reference ${GENERATOR} in the server's project`);
58
+ return fail(`${contract} is there, but no project writes it: reference ${GENERATOR} in the server's project`);
31
59
  if (others.length > 0)
32
- return fail(`${CONTRACT} has more than one project that could write it (${servers.join(", ")}): keep ${GENERATOR} in the server's project only`);
60
+ return fail(`${contract} has more than one project that could write it (${servers.join(", ")}): keep ${GENERATOR} in the server's project only`);
33
61
  const name = path.basename(server, ".csproj");
34
62
  const document = `"$work"/${quoted(`${name}.json`)}`;
35
63
  const web = webApp(context);
@@ -41,7 +69,7 @@ export function apiContract(context) {
41
69
  `rm -f ${quoted(path.join(path.dirname(server), "obj", `${name}.OpenApiFiles.cache`))}`,
42
70
  `dotnet build ${quoted(server)} --nologo -v quiet -p:OpenApiGenerateDocumentsOnBuild=true -p:OpenApiDocumentsDirectory="$work" >"$work/build.log" || { cat "$work/build.log" >&2; exit 1; }`,
43
71
  "stale=()",
44
- `diff -q ${document} ${CONTRACT} >/dev/null 2>&1 || stale+=(${quoted(path.relative(context.root, path.join(context.cwd, CONTRACT)))})`,
72
+ `diff -q ${document} ${contract} >/dev/null 2>&1 || stale+=(${quoted(path.relative(context.root, path.join(context.cwd, contract)))})`,
45
73
  ...(web === null
46
74
  ? []
47
75
  : [
@@ -53,33 +81,44 @@ export function apiContract(context) {
53
81
  `echo "API contract${web === null ? "" : " and types"} up to date"`,
54
82
  ]);
55
83
  }
56
- const API_VERSION = script([
57
- 'if ! git rev-parse --verify -q master >/dev/null && ! git rev-parse --verify -q origin/master >/dev/null; then echo "no master yet: nothing to compare the contract with"; exit 0; fi',
58
- "if git show-ref --verify --quiet refs/heads/master; then base=master; else base=origin/master; fi",
59
- 'work="$(mktemp -d)"',
60
- "trap 'rm -rf \"$work\"' EXIT",
61
- `if ! git show "$base:./${CONTRACT}" >"$work/base.json" 2>/dev/null; then echo "no ${CONTRACT} on $base yet; nothing to compare against."; exit 0; fi`,
62
- `if git diff --quiet --no-index "$work/base.json" ${CONTRACT} 2>/dev/null; then echo "API contract unchanged since $base"; exit 0; fi`,
63
- `if ! oasdiff breaking "$work/base.json" ${CONTRACT} >"$work/load.log" 2>&1; then cat "$work/load.log" >&2; echo "oasdiff could not compare the documents (see above); is ${CONTRACT} valid JSON? Regenerate it (just api-types)" >&2; exit 1; fi`,
64
- `version_of() { node -e 'let text = ""; process.stdin.on("data", (chunk) => (text += chunk)).on("end", () => console.log(JSON.parse(text).version));'; }`,
65
- `now="$(version_of <${CONTRACT_VERSION})"`,
66
- `was="$(git show "$base:./${CONTRACT_VERSION}" 2>/dev/null | version_of 2>/dev/null || true)"`,
67
- `version_is_higher() { [ "$1" != "$2" ] && [ "$(printf '%s\\n%s\\n' "$1" "$2" | sort -V | tail -n 1)" = "$1" ]; }`,
68
- `if oasdiff breaking "$work/base.json" ${CONTRACT} --fail-on ERR; then`,
69
- ' if [ -n "$was" ] && ! version_is_higher "$now" "$was"; then',
70
- ` echo "the API contract changed since $base, but ${CONTRACT_VERSION} still says $now. Raise its minor version (a compatible change), so a consumer can pin the new one." >&2`,
71
- " exit 1",
72
- " fi",
73
- ' echo "API contract changed since $base, compatibly (nothing breaks a consumer), as version $now"',
74
- "else",
75
- ' if [ -n "$was" ] && [ "${now%%.*}" -gt "${was%%.*}" ]; then',
76
- ' echo "API contract breaks consumers since $base (see above), as the new major version $now: every consumer moves to it on purpose."',
77
- " exit 0",
78
- " fi",
79
- ` echo "the API contract breaks consumers (see above). Keep the old shape and add the new one beside it, or, agreed with every consumer, raise the major version in ${CONTRACT_VERSION}." >&2`,
80
- " exit 1",
81
- "fi",
82
- ]);
84
+ function apiVersionScript(contract, breaking) {
85
+ const versionFile = versionFileOf(contract);
86
+ const breakingAllowed = breaking === "never"
87
+ ? [
88
+ ` echo "the API contract breaks consumers (see above), and this repository allows no break (api-version breaking: never in suwgate.yml): keep the old shape and add the new one beside it." >&2`,
89
+ " exit 1",
90
+ ]
91
+ : [
92
+ ' if [ -n "$was" ] && [ "${now%%.*}" -gt "${was%%.*}" ]; then',
93
+ ' echo "API contract breaks consumers since $base (see above), as the new major version $now: every consumer moves to it on purpose."',
94
+ " exit 0",
95
+ " fi",
96
+ ` echo "the API contract breaks consumers (see above). Keep the old shape and add the new one beside it, or, agreed with every consumer, raise the major version in ${versionFile}." >&2`,
97
+ " exit 1",
98
+ ];
99
+ return script([
100
+ 'if ! git rev-parse --verify -q master >/dev/null && ! git rev-parse --verify -q origin/master >/dev/null; then echo "no master yet: nothing to compare the contract with"; exit 0; fi',
101
+ "if git show-ref --verify --quiet refs/heads/master; then base=master; else base=origin/master; fi",
102
+ 'work="$(mktemp -d)"',
103
+ "trap 'rm -rf \"$work\"' EXIT",
104
+ `if ! git show "$base:./${contract}" >"$work/base.json" 2>/dev/null; then echo "no ${contract} on $base yet; nothing to compare against."; exit 0; fi`,
105
+ `if git diff --quiet --no-index "$work/base.json" ${contract} 2>/dev/null; then echo "API contract unchanged since $base"; exit 0; fi`,
106
+ `if ! oasdiff breaking "$work/base.json" ${contract} >"$work/load.log" 2>&1; then cat "$work/load.log" >&2; echo "oasdiff could not compare the documents (see above); is ${contract} valid JSON? Regenerate it (just api-types)" >&2; exit 1; fi`,
107
+ `version_of() { node -e 'let text = ""; process.stdin.on("data", (chunk) => (text += chunk)).on("end", () => console.log(JSON.parse(text).version));'; }`,
108
+ `now="$(version_of <${versionFile} 2>/dev/null || true)"`,
109
+ `was="$(git show "$base:./${versionFile}" 2>/dev/null | version_of 2>/dev/null || true)"`,
110
+ `version_is_higher() { [ "$1" != "$2" ] && [ "$(printf '%s\\n%s\\n' "$1" "$2" | sort -V | tail -n 1)" = "$1" ]; }`,
111
+ `if oasdiff breaking "$work/base.json" ${contract} --fail-on ERR; then`,
112
+ ' if [ -n "$was" ] && ! version_is_higher "$now" "$was"; then',
113
+ ` echo "the API contract changed since $base, but ${versionFile} still says $now. Raise its minor version (a compatible change), so a consumer can pin the new one." >&2`,
114
+ " exit 1",
115
+ " fi",
116
+ ' echo "API contract changed since $base, compatibly (nothing breaks a consumer), as version $now"',
117
+ "else",
118
+ ...breakingAllowed,
119
+ "fi",
120
+ ]);
121
+ }
83
122
  function pins(context) {
84
123
  return tracked({ ...context, cwd: context.root }, TAGGED).flatMap((file) => (read({ ...context, cwd: context.root }, file) ?? "").split("\n").flatMap((line, index) => {
85
124
  const tag = TRAIT_TAG.exec(line)?.[1] ?? TITLE_TAG.exec(line)?.[1];
@@ -100,20 +139,24 @@ export function contractPins(context) {
100
139
  export const contractSteps = [
101
140
  {
102
141
  id: API_CONTRACT,
103
- title: `the API contract and the web app's types up to date with the server (${CONTRACT}, ${API_TYPES}, openapi-typescript)`,
142
+ title: `the API contract and the web app's types up to date with the server (${DEFAULT_CONTRACT} or settings.contract, ${API_TYPES}, openapi-typescript)`,
104
143
  profile: "dotnet",
105
144
  needs: ["dotnet"],
106
145
  after: [DOTNET_TEST, PNPM_INSTALL],
107
146
  run: apiContract,
147
+ settingsSchema: CONTRACT_SETTINGS,
108
148
  limitSeconds: 300,
109
149
  },
110
150
  {
111
- id: "api-version",
112
- title: `the API contract's version right for what changed since master (${CONTRACT_VERSION}, oasdiff breaking)`,
151
+ id: API_VERSION_STEP,
152
+ title: "the API contract's version right for what changed since master (the package.json beside the contract, oasdiff breaking)",
113
153
  profile: "dotnet",
114
154
  needs: ["oasdiff", "node"],
115
155
  after: [API_CONTRACT],
116
- run: (context) => (has(context, CONTRACT) ? API_VERSION : null),
156
+ run: (context) => has(context, contractOf(context))
157
+ ? apiVersionScript(contractOf(context), settingsOf(context, API_VERSION_STEP).breaking ?? "major")
158
+ : null,
159
+ settingsSchema: VERSION_SETTINGS,
117
160
  limitSeconds: 60,
118
161
  },
119
162
  {
@@ -6,6 +6,7 @@ interface TestSource {
6
6
  report: string;
7
7
  patterns: string[];
8
8
  skipped?: string;
9
+ excludeTraits?: string[];
9
10
  }
10
11
  export interface CriteriaRanInput {
11
12
  root: string;
@@ -2,6 +2,7 @@ import { execFileSync } from "node:child_process";
2
2
  import { readFileSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { CRITERIA_FILE, criteriaConfig } from "./criteria.js";
5
+ import { excludedTraits } from "./dotnet.js";
5
6
  import { readRun } from "./reports.js";
6
7
  import { quoted, read, tracked, verdictCommand } from "./shell.js";
7
8
  const REPORTED = {
@@ -24,6 +25,39 @@ export function names(text, id, format) {
24
25
  return new RegExp(`Trait\\(\\s*"criterion"\\s*,\\s*"${id.replace(/[.]/g, "\\.")}"\\s*\\)`).test(text);
25
26
  return ['"', "'", "`"].some((quote) => text.includes(`${quote}${id}:`));
26
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
+ }
27
61
  function proven(passed, id) {
28
62
  return passed.some((title) => title.startsWith(`${id}:`) || title.includes(` ${id}:`));
29
63
  }
@@ -54,10 +88,18 @@ export function criteriaRan(input) {
54
88
  files: listed(input.root, source.patterns).map((file) => ({ file, text: readFileSync(path.join(input.root, file), "utf8") })),
55
89
  }));
56
90
  return ids.flatMap((id) => {
57
- const naming = texts.flatMap(({ source, files }) => files.filter((file) => names(file.text, id, source.format)).map((file) => ({ source, file: file.file })));
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 ?? []) })));
58
94
  const checked = naming.filter((entry) => entry.source.skipped === undefined);
59
95
  if (checked.length === 0)
60
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
+ }
61
103
  if (checked.some((entry) => proven(runs.get(entry.source.step)?.passed ?? [], id)))
62
104
  return [];
63
105
  const unreported = [...new Set(checked.filter((entry) => runs.get(entry.source.step) === null).map((entry) => entry.source.step))];
@@ -92,6 +134,7 @@ export function criteriaRanInput(context) {
92
134
  report: path.posix.join(reported.step, REPORT_FILE[reported.format]),
93
135
  patterns: kind.paths,
94
136
  ...(context.skippedSteps.includes(reported.step) ? { skipped: "skipped in suwgate.yml" } : {}),
137
+ ...(reported.format === "xunit" && excludedTraits(context).length > 0 ? { excludeTraits: excludedTraits(context) } : {}),
95
138
  },
96
139
  ];
97
140
  });
@@ -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,7 @@ 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;
7
8
  export declare function witnessed(context: StepContext, tests: string): string;
@@ -1,6 +1,6 @@
1
1
  import { DATABASE_UP } from "./database.js";
2
2
  import { requiredGuards } from "./dotnetGuards.js";
3
- import { CHECKOUT_ENV, changedIn, hasDevSection, quoted, read, runDirectory, tracked, verdictCommand, withChanged } from "./shell.js";
3
+ import { CHECKOUT_ENV, changedIn, hasDevSection, quoted, read, runDirectory, settingsOf, tracked, verdictCommand, withChanged, } from "./shell.js";
4
4
  const DOTNET_INPUT = /\.(cs|csproj|props|targets|slnx|sln|rsp)$|(^|\/)(\.editorconfig|BannedSymbols\.txt|global\.json|packages\.lock\.json|nuget\.config)$/;
5
5
  const GUARD_PACKAGE = /<(PackageReference|ProjectReference)\b[^>]*(?:Include|Update)="[^"]*Suwgate\.(Architecture|Database)\b/;
6
6
  const TEST_PROJECT = /<PackageReference\b[^>]*Include="xunit\.v3"|<IsTestProject>true<\/IsTestProject>/;
@@ -10,6 +10,27 @@ const TEST_OPTIONS = '--no-build --no-progress --zero-tests-policy strict --repo
10
10
  const FORMAT = `${NO_IDLE_BUILD_PROCESSES} && dotnet tool restore >/dev/null`;
11
11
  export const DOTNET_BUILD = "dotnet-build";
12
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
+ }
13
34
  function dotnetChanged(context) {
14
35
  return changedIn(context, DOTNET_INPUT).length > 0;
15
36
  }
@@ -27,7 +48,7 @@ export function guardTests(context) {
27
48
  });
28
49
  if (projects.length === 0)
29
50
  return null;
30
- return projects.map((project) => `dotnet test --project ${quoted(project)} ${TEST_OPTIONS}`).join(" && ");
51
+ return projects.map((project) => `dotnet test --project ${quoted(project)} ${testOptions(context)}`).join(" && ");
31
52
  }
32
53
  export function witnessed(context, tests) {
33
54
  return [
@@ -35,7 +56,7 @@ export function witnessed(context, tests) {
35
56
  'export SUWGATE_EVIDENCE="$run/evidence"',
36
57
  tests,
37
58
  verdictCommand(`tests xunit "$run/results" ${quoted("dotnet test")}`),
38
- verdictCommand(`guards "$run/evidence" ${requiredGuards(context).map(quoted).join(" ")}`),
59
+ `{ [ $# -gt 0 ] || ${verdictCommand(`guards "$run/evidence" ${requiredGuards(context).map(quoted).join(" ")}`)}; }`,
39
60
  ].join(" && ");
40
61
  }
41
62
  export const dotnetSteps = [
@@ -62,15 +83,17 @@ export const dotnetSteps = [
62
83
  },
63
84
  {
64
85
  id: DOTNET_TEST,
65
- title: "tests (dotnet test, xUnit v3, with the checkout's databases when suwgate.yml has dev; fails on 0 tests run and unless every .NET guard of the profiles ran; --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)",
66
87
  profile: "dotnet",
67
88
  needs: ["dotnet"],
68
89
  after: [DOTNET_BUILD, DATABASE_UP],
69
- run: (context) => inCheckoutEnv(context, witnessed(context, `dotnet test ${TEST_OPTIONS}`)),
90
+ run: (context) => inCheckoutEnv(context, witnessed(context, `dotnet test ${testOptions(context)} "$@"`)),
70
91
  quick: (context) => {
71
92
  const command = guardTests(context);
72
93
  return command === null ? null : inCheckoutEnv(context, witnessed(context, command));
73
94
  },
95
+ args: "dotnet test, xUnit v3 on Microsoft.Testing.Platform",
96
+ settingsSchema: DOTNET_TEST_SETTINGS,
74
97
  limitSeconds: 600,
75
98
  },
76
99
  ];
@@ -13,8 +13,24 @@ const ARCHITECTURE = [
13
13
  "no-fixture-in-field",
14
14
  "build-settings",
15
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
+ };
16
28
  export const dotnetGuards = [
17
- ...ARCHITECTURE.map((name) => ({ id: `architecture/${name}`, profile: "dotnet" })),
29
+ ...ARCHITECTURE.map((name) => ({
30
+ id: `architecture/${name}`,
31
+ profile: "dotnet",
32
+ ...(ARCHITECTURE_SETTINGS[name] === undefined ? {} : { settingsSchema: ARCHITECTURE_SETTINGS[name] }),
33
+ })),
18
34
  {
19
35
  id: "database/migration-script-names",
20
36
  profile: "database",
@@ -47,7 +47,7 @@ export function visual(context) {
47
47
  return [
48
48
  "pnpm exec storybook build --quiet -o storybook-static >/dev/null",
49
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`,
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
51
  verdictCommand(`tests playwright "$run/playwright.json" ${quoted("playwright (visual)")}`),
52
52
  ].join(" && ");
53
53
  }
@@ -84,6 +84,7 @@ export const librarySteps = [
84
84
  needs: ["pnpm"],
85
85
  after,
86
86
  run: stories,
87
+ args: "vitest run --project stories",
87
88
  limitSeconds: 600,
88
89
  },
89
90
  {
@@ -111,6 +112,7 @@ export const librarySteps = [
111
112
  needs: ["pnpm", "node"],
112
113
  after: ["attw"],
113
114
  run: consumerApp,
115
+ args: "playwright test",
114
116
  limitSeconds: 900,
115
117
  },
116
118
  {
@@ -120,6 +122,7 @@ export const librarySteps = [
120
122
  needs: ["pnpm", "docker"],
121
123
  after,
122
124
  run: visual,
125
+ args: "playwright test, in the Playwright image",
123
126
  limitSeconds: 900,
124
127
  },
125
128
  {
@@ -68,6 +68,7 @@ export function nodeSteps(profile) {
68
68
  needs: ["pnpm"],
69
69
  after,
70
70
  run: unitTests,
71
+ args: "vitest run",
71
72
  limitSeconds: 300,
72
73
  },
73
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;