@maniumek/suwgate 0.0.0-stage → 0.1.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 (165) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +149 -2
  3. package/dist/cli.d.ts +2 -0
  4. package/dist/cli.js +97 -0
  5. package/dist/dev/checkoutEnv.d.ts +20 -0
  6. package/dist/dev/checkoutEnv.js +101 -0
  7. package/dist/dev/db.d.ts +25 -0
  8. package/dist/dev/db.js +103 -0
  9. package/dist/dev/index.d.ts +16 -0
  10. package/dist/dev/index.js +108 -0
  11. package/dist/dev/logs.d.ts +15 -0
  12. package/dist/dev/logs.js +127 -0
  13. package/dist/dev/process.d.ts +24 -0
  14. package/dist/dev/process.js +34 -0
  15. package/dist/dev/server.d.ts +8 -0
  16. package/dist/dev/server.js +61 -0
  17. package/dist/dev/settings.d.ts +46 -0
  18. package/dist/dev/settings.js +160 -0
  19. package/dist/dev/smoke.d.ts +15 -0
  20. package/dist/dev/smoke.js +50 -0
  21. package/dist/dev/testing.d.ts +19 -0
  22. package/dist/dev/testing.js +18 -0
  23. package/dist/dev/tmux.d.ts +24 -0
  24. package/dist/dev/tmux.js +121 -0
  25. package/dist/eslint/index.d.ts +17 -0
  26. package/dist/eslint/index.js +91 -0
  27. package/dist/eslint/noComments.d.ts +2 -0
  28. package/dist/eslint/noComments.js +27 -0
  29. package/dist/gate/check.d.ts +13 -0
  30. package/dist/gate/check.js +49 -0
  31. package/dist/gate/config.d.ts +34 -0
  32. package/dist/gate/config.js +170 -0
  33. package/dist/gate/contract.d.ts +51 -0
  34. package/dist/gate/contract.js +1 -0
  35. package/dist/gate/guardsStep.d.ts +14 -0
  36. package/dist/gate/guardsStep.js +53 -0
  37. package/dist/gate/plan.d.ts +29 -0
  38. package/dist/gate/plan.js +86 -0
  39. package/dist/gate/report.d.ts +15 -0
  40. package/dist/gate/report.js +65 -0
  41. package/dist/gate/repository.d.ts +3 -0
  42. package/dist/gate/repository.js +37 -0
  43. package/dist/gate/runner.d.ts +10 -0
  44. package/dist/gate/runner.js +75 -0
  45. package/dist/guards/comments/csharp.d.ts +3 -0
  46. package/dist/guards/comments/csharp.js +163 -0
  47. package/dist/guards/comments/css.d.ts +3 -0
  48. package/dist/guards/comments/css.js +11 -0
  49. package/dist/guards/comments/eslint.d.ts +2 -0
  50. package/dist/guards/comments/eslint.js +81 -0
  51. package/dist/guards/comments/hash.d.ts +3 -0
  52. package/dist/guards/comments/hash.js +72 -0
  53. package/dist/guards/comments/index.d.ts +2 -0
  54. package/dist/guards/comments/index.js +18 -0
  55. package/dist/guards/comments/json.d.ts +3 -0
  56. package/dist/guards/comments/json.js +13 -0
  57. package/dist/guards/comments/markup.d.ts +3 -0
  58. package/dist/guards/comments/markup.js +14 -0
  59. package/dist/guards/comments/scan.d.ts +19 -0
  60. package/dist/guards/comments/scan.js +84 -0
  61. package/dist/guards/comments/sql.d.ts +3 -0
  62. package/dist/guards/comments/sql.js +11 -0
  63. package/dist/guards/comments/switches.d.ts +3 -0
  64. package/dist/guards/comments/switches.js +30 -0
  65. package/dist/guards/criteria/criteriaKinds.d.ts +2 -0
  66. package/dist/guards/criteria/criteriaKinds.js +45 -0
  67. package/dist/guards/criteria/index.d.ts +2 -0
  68. package/dist/guards/criteria/index.js +2 -0
  69. package/dist/guards/database/connectionHost.d.ts +2 -0
  70. package/dist/guards/database/connectionHost.js +30 -0
  71. package/dist/guards/database/index.d.ts +2 -0
  72. package/dist/guards/database/index.js +3 -0
  73. package/dist/guards/database/migrationsUnchanged.d.ts +2 -0
  74. package/dist/guards/database/migrationsUnchanged.js +56 -0
  75. package/dist/guards/dotnet/appsettingsBound.d.ts +2 -0
  76. package/dist/guards/dotnet/appsettingsBound.js +43 -0
  77. package/dist/guards/dotnet/bannedNugetPackages.d.ts +2 -0
  78. package/dist/guards/dotnet/bannedNugetPackages.js +51 -0
  79. package/dist/guards/dotnet/index.d.ts +2 -0
  80. package/dist/guards/dotnet/index.js +4 -0
  81. package/dist/guards/dotnet/msbuild.d.ts +5 -0
  82. package/dist/guards/dotnet/msbuild.js +17 -0
  83. package/dist/guards/dotnet/testContext.d.ts +2 -0
  84. package/dist/guards/dotnet/testContext.js +12 -0
  85. package/dist/guards/dotnet/unusedNugetVersions.d.ts +2 -0
  86. package/dist/guards/dotnet/unusedNugetVersions.js +21 -0
  87. package/dist/guards/index.d.ts +2 -0
  88. package/dist/guards/index.js +6 -0
  89. package/dist/guards/repository/agentsFile.d.ts +3 -0
  90. package/dist/guards/repository/agentsFile.js +56 -0
  91. package/dist/guards/repository/bannedNpmPackages.d.ts +2 -0
  92. package/dist/guards/repository/bannedNpmPackages.js +43 -0
  93. package/dist/guards/repository/composePorts.d.ts +6 -0
  94. package/dist/guards/repository/composePorts.js +57 -0
  95. package/dist/guards/repository/dependencyDirection.d.ts +2 -0
  96. package/dist/guards/repository/dependencyDirection.js +87 -0
  97. package/dist/guards/repository/docsPaths.d.ts +2 -0
  98. package/dist/guards/repository/docsPaths.js +54 -0
  99. package/dist/guards/repository/forbiddenNames.d.ts +4 -0
  100. package/dist/guards/repository/forbiddenNames.js +69 -0
  101. package/dist/guards/repository/hooks.d.ts +3 -0
  102. package/dist/guards/repository/hooks.js +86 -0
  103. package/dist/guards/repository/imagePins.d.ts +3 -0
  104. package/dist/guards/repository/imagePins.js +68 -0
  105. package/dist/guards/repository/index.d.ts +2 -0
  106. package/dist/guards/repository/index.js +32 -0
  107. package/dist/guards/repository/justModules.d.ts +2 -0
  108. package/dist/guards/repository/justModules.js +36 -0
  109. package/dist/guards/repository/noRawColors.d.ts +2 -0
  110. package/dist/guards/repository/noRawColors.js +29 -0
  111. package/dist/guards/repository/packageManifests.d.ts +13 -0
  112. package/dist/guards/repository/packageManifests.js +26 -0
  113. package/dist/guards/repository/repositoryLayout.d.ts +3 -0
  114. package/dist/guards/repository/repositoryLayout.js +75 -0
  115. package/dist/guards/repository/requiredFiles.d.ts +6 -0
  116. package/dist/guards/repository/requiredFiles.js +78 -0
  117. package/dist/guards/repository/scriptsCalled.d.ts +3 -0
  118. package/dist/guards/repository/scriptsCalled.js +39 -0
  119. package/dist/guards/repository/scriptsHelp.d.ts +2 -0
  120. package/dist/guards/repository/scriptsHelp.js +37 -0
  121. package/dist/guards/repository/testRepository.d.ts +4 -0
  122. package/dist/guards/repository/testRepository.js +39 -0
  123. package/dist/guards/repository/text.d.ts +20 -0
  124. package/dist/guards/repository/text.js +33 -0
  125. package/dist/guards/repository/vsCodeSettings.d.ts +3 -0
  126. package/dist/guards/repository/vsCodeSettings.js +49 -0
  127. package/dist/profiles/contract.d.ts +5 -0
  128. package/dist/profiles/contract.js +124 -0
  129. package/dist/profiles/criteria.d.ts +25 -0
  130. package/dist/profiles/criteria.js +162 -0
  131. package/dist/profiles/database.d.ts +4 -0
  132. package/dist/profiles/database.js +23 -0
  133. package/dist/profiles/dotnet.d.ts +5 -0
  134. package/dist/profiles/dotnet.js +56 -0
  135. package/dist/profiles/everyRepository.d.ts +2 -0
  136. package/dist/profiles/everyRepository.js +32 -0
  137. package/dist/profiles/index.d.ts +2 -0
  138. package/dist/profiles/index.js +21 -0
  139. package/dist/profiles/library.d.ts +7 -0
  140. package/dist/profiles/library.js +132 -0
  141. package/dist/profiles/node.d.ts +5 -0
  142. package/dist/profiles/node.js +79 -0
  143. package/dist/profiles/presets/knip.d.ts +11 -0
  144. package/dist/profiles/presets/knip.js +29 -0
  145. package/dist/profiles/presets/playwright.d.ts +68 -0
  146. package/dist/profiles/presets/playwright.js +37 -0
  147. package/dist/profiles/presets/prettier.d.ts +12 -0
  148. package/dist/profiles/presets/prettier.js +7 -0
  149. package/dist/profiles/presets/tsconfig/browser.json +11 -0
  150. package/dist/profiles/presets/tsconfig/node.json +8 -0
  151. package/dist/profiles/presets/tsconfig/strict.json +17 -0
  152. package/dist/profiles/presets/vitest.d.ts +36 -0
  153. package/dist/profiles/presets/vitest.js +16 -0
  154. package/dist/profiles/shell.d.ts +10 -0
  155. package/dist/profiles/shell.js +62 -0
  156. package/dist/profiles/web.d.ts +2 -0
  157. package/dist/profiles/web.js +17 -0
  158. package/dist/session/guardEdit.d.ts +19 -0
  159. package/dist/session/guardEdit.js +96 -0
  160. package/dist/session/preCommit.d.ts +16 -0
  161. package/dist/session/preCommit.js +33 -0
  162. package/dist/session/stop.d.ts +8 -0
  163. package/dist/session/stop.js +39 -0
  164. package/package.json +97 -3
  165. package/schema/suwgate.schema.json +196 -0
@@ -0,0 +1,19 @@
1
+ import type { Exec, ExecOptions, Io } from "./process.ts";
2
+ import { type DevSettings } from "./settings.ts";
3
+ export declare function settingsOf(raw?: unknown, directories?: Record<string, unknown>): DevSettings;
4
+ export interface Call {
5
+ argv: readonly string[];
6
+ options: ExecOptions | undefined;
7
+ }
8
+ export declare function fakeExec(answer?: (argv: readonly string[]) => {
9
+ status?: number;
10
+ stdout?: string;
11
+ }): {
12
+ exec: Exec;
13
+ calls: Call[];
14
+ };
15
+ export declare function recordingIo(): {
16
+ io: Io;
17
+ out: string[];
18
+ err: string[];
19
+ };
@@ -0,0 +1,18 @@
1
+ import { resolveSettings } from "./settings.js";
2
+ export function settingsOf(raw = { name: "myapp" }, directories = { dotnet: "Myapp.Server", web: "Myapp.Web" }) {
3
+ return resolveSettings(raw, directories, "/repo");
4
+ }
5
+ export function fakeExec(answer = () => ({})) {
6
+ const calls = [];
7
+ const exec = (argv, options) => {
8
+ calls.push({ argv, options });
9
+ const { status = 0, stdout = "" } = answer(argv);
10
+ return Promise.resolve({ status, stdout });
11
+ };
12
+ return { exec, calls };
13
+ }
14
+ export function recordingIo() {
15
+ const out = [];
16
+ const err = [];
17
+ return { io: { out: (text) => out.push(text), err: (text) => err.push(text) }, out, err };
18
+ }
@@ -0,0 +1,24 @@
1
+ import { type Exec, type Io } from "./process.ts";
2
+ import { type DevSettings } from "./settings.ts";
3
+ export declare const TMUX_USAGE = "usage: suwgate dev tmux start [--restart] | suwgate dev tmux stop\nThe local stack in one tmux session, <dev.name>-dev:\n left: a shell in the repository\n right: the server under dotnet watch (+ the database of the compose file) / the web app under pnpm dev, with hot reload\nThe session is reused when it exists; --restart kills it (and everything running in it) first; stop kills it and stops there.\nIn a tmux pane the client is switched, not nested; any other terminal attaches where it was called.\nTMUX_DEV_NO_ATTACH=1 builds the session and stops there (used to inspect the layout).";
4
+ export type TmuxCommand = {
5
+ kind: "start";
6
+ restart: boolean;
7
+ } | {
8
+ kind: "stop";
9
+ };
10
+ export declare function parseTmux(args: readonly string[]): TmuxCommand;
11
+ export declare function sessionName(settings: DevSettings): string;
12
+ export declare function paneCommands(settings: DevSettings, self: string): {
13
+ server: string;
14
+ web: string;
15
+ };
16
+ export interface TmuxEnvironment {
17
+ settings: DevSettings;
18
+ exec: Exec;
19
+ io: Io;
20
+ env: Readonly<Record<string, string | undefined>>;
21
+ self: string;
22
+ }
23
+ export declare function buildSession(environment: TmuxEnvironment): Promise<void>;
24
+ export declare function runTmux(command: TmuxCommand, environment: TmuxEnvironment): Promise<number>;
@@ -0,0 +1,121 @@
1
+ import { UsageError, Failure, quoted } from "./process.js";
2
+ import { needServerProject, needWebDirectory } from "./settings.js";
3
+ export const TMUX_USAGE = `usage: suwgate dev tmux start [--restart] | suwgate dev tmux stop
4
+ The local stack in one tmux session, <dev.name>-dev:
5
+ left: a shell in the repository
6
+ right: the server under dotnet watch (+ the database of the compose file) / the web app under pnpm dev, with hot reload
7
+ The session is reused when it exists; --restart kills it (and everything running in it) first; stop kills it and stops there.
8
+ In a tmux pane the client is switched, not nested; any other terminal attaches where it was called.
9
+ TMUX_DEV_NO_ATTACH=1 builds the session and stops there (used to inspect the layout).`;
10
+ const SESSION_WIDTH = 220;
11
+ const SESSION_HEIGHT = 50;
12
+ export function parseTmux(args) {
13
+ const [command, ...rest] = args;
14
+ if (command === "start" && rest.length === 0)
15
+ return { kind: "start", restart: false };
16
+ if (command === "start" && rest.length === 1 && rest[0] === "--restart")
17
+ return { kind: "start", restart: true };
18
+ if (command === "stop" && rest.length === 0)
19
+ return { kind: "stop" };
20
+ throw new UsageError(TMUX_USAGE);
21
+ }
22
+ export function sessionName(settings) {
23
+ return `${settings.name}-dev`;
24
+ }
25
+ export function paneCommands(settings, self) {
26
+ return {
27
+ server: `${self} dev db up && ${self} dev server`,
28
+ web: `cd ${quoted(needWebDirectory(settings))} && { [ -d node_modules ] || pnpm install; } && pnpm dev`,
29
+ };
30
+ }
31
+ async function tmux(environment, args, capture = false) {
32
+ const result = await environment.exec(["tmux", ...args], { cwd: environment.settings.root, capture, quiet: !capture });
33
+ return { status: result.status, stdout: result.stdout.trim() };
34
+ }
35
+ async function inTmuxPane(environment) {
36
+ if ((environment.env["TMUX"] ?? "") === "")
37
+ return false;
38
+ const panes = await tmux(environment, ["list-panes", "-a", "-F", "#{pane_tty}"], true);
39
+ const here = await environment.exec(["tty"], { capture: true });
40
+ if (here.status !== 0)
41
+ return false;
42
+ return panes.stdout.split("\n").includes(here.stdout.trim());
43
+ }
44
+ async function running(environment) {
45
+ return (await tmux(environment, ["has-session", "-t", `=${sessionName(environment.settings)}`])).status === 0;
46
+ }
47
+ async function insideSession(environment) {
48
+ if (!(await inTmuxPane(environment)))
49
+ return false;
50
+ return (await tmux(environment, ["display-message", "-p", "#S"], true)).stdout === sessionName(environment.settings);
51
+ }
52
+ async function attach(environment) {
53
+ if (environment.env["TMUX_DEV_NO_ATTACH"] === "1")
54
+ return;
55
+ const session = sessionName(environment.settings);
56
+ if (await inTmuxPane(environment)) {
57
+ await environment.exec(["tmux", "switch-client", "-t", session]);
58
+ }
59
+ else {
60
+ await environment.exec(["env", "-u", "TMUX", "tmux", "attach-session", "-t", session]);
61
+ }
62
+ }
63
+ export async function buildSession(environment) {
64
+ const { settings } = environment;
65
+ needServerProject(settings);
66
+ const session = sessionName(settings);
67
+ const root = settings.root;
68
+ const commands = paneCommands(settings, environment.self);
69
+ const pane = async (args) => (await tmux(environment, args, true)).stdout;
70
+ const shell = await pane([
71
+ "new-session",
72
+ "-d",
73
+ "-s",
74
+ session,
75
+ "-c",
76
+ root,
77
+ "-x",
78
+ String(SESSION_WIDTH),
79
+ "-y",
80
+ String(SESSION_HEIGHT),
81
+ "-P",
82
+ "-F",
83
+ "#{pane_id}",
84
+ ]);
85
+ const server = await pane(["split-window", "-h", "-t", shell, "-c", root, "-P", "-F", "#{pane_id}"]);
86
+ const web = await pane(["split-window", "-v", "-t", server, "-c", root, "-P", "-F", "#{pane_id}"]);
87
+ await tmux(environment, ["set-option", "-t", session, "pane-border-status", "top"]);
88
+ await tmux(environment, ["select-pane", "-t", shell, "-T", "shell"]);
89
+ await tmux(environment, ["select-pane", "-t", server, "-T", `server: (${settings.ports.server})`]);
90
+ await tmux(environment, ["select-pane", "-t", web, "-T", `web: (${settings.ports.web})`]);
91
+ await tmux(environment, ["send-keys", "-t", server, commands.server, "Enter"]);
92
+ await tmux(environment, ["send-keys", "-t", web, commands.web, "Enter"]);
93
+ await tmux(environment, ["select-pane", "-t", shell]);
94
+ }
95
+ export async function runTmux(command, environment) {
96
+ const { io, settings } = environment;
97
+ const session = sessionName(settings);
98
+ if ((await environment.exec(["tmux", "-V"], { capture: true })).status !== 0) {
99
+ throw new Failure("tmux is not installed. Install it: sudo dnf install tmux");
100
+ }
101
+ if (command.kind === "stop") {
102
+ if (!(await running(environment))) {
103
+ io.out(`No ${session} session is running.`);
104
+ return 0;
105
+ }
106
+ if (!(await insideSession(environment)))
107
+ io.out(`Stopping the ${session} session.`);
108
+ await tmux(environment, ["kill-session", "-t", `=${session}`]);
109
+ return 0;
110
+ }
111
+ if (command.restart && (await running(environment))) {
112
+ if (await insideSession(environment)) {
113
+ throw new Failure(`Run --restart from outside the ${session} session: killing it would end this shell before the new one starts.`);
114
+ }
115
+ await tmux(environment, ["kill-session", "-t", `=${session}`]);
116
+ }
117
+ if (!(await running(environment)))
118
+ await buildSession(environment);
119
+ await attach(environment);
120
+ return 0;
121
+ }
@@ -0,0 +1,17 @@
1
+ import type { ESLint, Linter } from "eslint";
2
+ import { noComments } from "./noComments.ts";
3
+ export { noComments };
4
+ export interface StrictOptions {
5
+ root: string;
6
+ projects?: readonly string[];
7
+ ignores?: readonly string[];
8
+ untyped?: readonly string[];
9
+ }
10
+ export interface AppOptions extends StrictOptions {
11
+ features: readonly string[];
12
+ shared?: readonly string[];
13
+ storage?: readonly string[];
14
+ }
15
+ export declare const plugin: ESLint.Plugin;
16
+ export declare function strict(options: StrictOptions): Linter.Config[];
17
+ export declare function app(options: AppOptions): Linter.Config[];
@@ -0,0 +1,91 @@
1
+ import path from "node:path";
2
+ import js from "@eslint/js";
3
+ import { defineConfig, globalIgnores } from "eslint/config";
4
+ import boundaries from "eslint-plugin-boundaries";
5
+ import tseslint from "typescript-eslint";
6
+ import { noComments } from "./noComments.js";
7
+ export { noComments };
8
+ const BOUNDARIES_PLUGIN = boundaries;
9
+ const CODE = ["**/*.{ts,tsx,js,jsx,mjs,cjs,mts,cts}"];
10
+ const SOURCES = ["src/**/*.{ts,tsx}"];
11
+ const BROWSER_STORAGE = ["localStorage", "sessionStorage", "indexedDB"];
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.";
14
+ export const plugin = {
15
+ meta: { name: "@maniumek/suwgate" },
16
+ rules: { "no-comments": noComments },
17
+ };
18
+ export function strict(options) {
19
+ return defineConfig(globalIgnores(["dist", ".artifacts", ...(options.ignores ?? [])]), js.configs.recommended, tseslint.configs.strictTypeChecked, tseslint.configs.stylisticTypeChecked, {
20
+ linterOptions: { noInlineConfig: true },
21
+ languageOptions: {
22
+ parserOptions: { project: [...(options.projects ?? ["./tsconfig.json"])], tsconfigRootDir: options.root },
23
+ },
24
+ rules: {
25
+ "@typescript-eslint/restrict-template-expressions": ["error", { allowNumber: true }],
26
+ "@typescript-eslint/no-confusing-void-expression": ["error", { ignoreArrowShorthand: true }],
27
+ "@typescript-eslint/no-unused-vars": ["error", { ignoreRestSiblings: true }],
28
+ },
29
+ }, {
30
+ files: CODE,
31
+ plugins: { suwgate: plugin },
32
+ rules: { "suwgate/no-comments": "error" },
33
+ }, {
34
+ files: ["eslint.config.js", ...(options.untyped ?? [])],
35
+ extends: [tseslint.configs.disableTypeChecked],
36
+ });
37
+ }
38
+ function featureBoundaries(options) {
39
+ const shared = options.shared ?? [];
40
+ return {
41
+ files: SOURCES,
42
+ plugins: { boundaries: BOUNDARIES_PLUGIN },
43
+ settings: {
44
+ "boundaries/root-path": options.root,
45
+ "import/resolver": {
46
+ typescript: { project: (options.projects ?? ["./tsconfig.json"]).map((project) => path.resolve(options.root, project)) },
47
+ node: { extensions: [".ts", ".tsx"] },
48
+ },
49
+ "boundaries/elements": [
50
+ ...shared.map((name) => ({ type: "shared", pattern: `src/${name}` })),
51
+ ...options.features.map((name) => ({ type: "feature", pattern: `src/${name}` })),
52
+ ],
53
+ "boundaries/files": [{ category: "entry", pattern: "src/*.{ts,tsx}" }],
54
+ },
55
+ rules: {
56
+ "boundaries/no-unknown-files": ["error"],
57
+ "boundaries/dependencies": [
58
+ "error",
59
+ {
60
+ default: "disallow",
61
+ message: BOUNDARIES_FIX,
62
+ policies: [
63
+ { allow: { to: { module: { origin: "external" } } } },
64
+ { allow: { dependency: { relationship: { to: "internal" } } } },
65
+ {
66
+ from: { file: { categories: "entry" } },
67
+ allow: { to: [{ file: { categories: "entry" } }, { element: { types: { anyOf: ["feature", "shared"] } } }] },
68
+ },
69
+ { from: { element: { type: "feature" } }, allow: { to: { element: { type: "shared" } } } },
70
+ ],
71
+ },
72
+ ],
73
+ },
74
+ };
75
+ }
76
+ function browserStorageBan(options) {
77
+ return {
78
+ files: SOURCES,
79
+ ignores: [...(options.storage ?? [])],
80
+ rules: {
81
+ "no-restricted-globals": ["error", ...BROWSER_STORAGE.map((name) => ({ name, message: BROWSER_STORAGE_FIX }))],
82
+ "no-restricted-properties": [
83
+ "error",
84
+ ...["window", "globalThis"].flatMap((object) => BROWSER_STORAGE.map((property) => ({ object, property, message: BROWSER_STORAGE_FIX }))),
85
+ ],
86
+ },
87
+ };
88
+ }
89
+ export function app(options) {
90
+ return [...strict(options), featureBoundaries(options), browserStorageBan(options)];
91
+ }
@@ -0,0 +1,2 @@
1
+ import type { Rule } from "eslint";
2
+ export declare const noComments: Rule.RuleModule;
@@ -0,0 +1,27 @@
1
+ const TOOL_DIRECTIVES = [/^ @ts-expect-error \S/, /^ @vitest-environment [\w-]+$/];
2
+ const CRITERION_MARKER = /^ AC-[a-z0-9]+(-[a-z0-9]+)*-[0-9]+$/;
3
+ export const noComments = {
4
+ meta: {
5
+ type: "problem",
6
+ schema: [],
7
+ docs: { description: 'Refuse every comment but the tool directives listed in AGENTS.md, "No comments"' },
8
+ messages: {
9
+ comment: 'Delete the comment; rename or split the code so it explains itself; put lasting knowledge in a test, the README, docs/ or AGENTS.md (the only comments allowed are the tool directives listed in AGENTS.md, "No comments").',
10
+ },
11
+ },
12
+ create(context) {
13
+ const readsCriterionMarkers = context.filename.endsWith("eslint.config.js");
14
+ return {
15
+ Program() {
16
+ for (const comment of context.sourceCode.getAllComments()) {
17
+ const allowed = comment.type === "Shebang" ||
18
+ TOOL_DIRECTIVES.some((directive) => directive.test(comment.value)) ||
19
+ (readsCriterionMarkers && CRITERION_MARKER.test(comment.value));
20
+ if (!allowed && comment.loc) {
21
+ context.report({ loc: comment.loc, messageId: "comment" });
22
+ }
23
+ }
24
+ },
25
+ };
26
+ },
27
+ };
@@ -0,0 +1,13 @@
1
+ import { type Catalog } from "./config.ts";
2
+ export interface CheckOptions {
3
+ cwd: string;
4
+ quick: boolean;
5
+ verbose: boolean;
6
+ env: NodeJS.ProcessEnv;
7
+ catalog: Catalog;
8
+ }
9
+ export interface CheckResult {
10
+ exitCode: number;
11
+ text: string;
12
+ }
13
+ export declare function check(options: CheckOptions): Promise<CheckResult>;
@@ -0,0 +1,49 @@
1
+ import { loadConfig } from "./config.js";
2
+ import { plan } from "./plan.js";
3
+ import { report } from "./report.js";
4
+ import { changedFiles, repositoryFiles, repositoryRoot } from "./repository.js";
5
+ import { runSteps } from "./runner.js";
6
+ const DEFAULT_QUICK_LIMIT_SECONDS = 20;
7
+ function seconds(env, name) {
8
+ const value = env[name];
9
+ if (value === undefined || value === "")
10
+ return null;
11
+ return /^\d+$/.test(value) && Number(value) > 0 ? Number(value) : `${name} must be a whole number of seconds, not '${value}'`;
12
+ }
13
+ export async function check(options) {
14
+ const command = `suwgate check${options.quick ? " --quick" : ""}`;
15
+ const root = repositoryRoot(options.cwd);
16
+ if (root === null)
17
+ return { exitCode: 2, text: `${command}: ${options.cwd} is not inside a git repository` };
18
+ const quickLimit = seconds(options.env, "SUWGATE_QUICK_LIMIT");
19
+ const stepLimit = seconds(options.env, "SUWGATE_STEP_LIMIT");
20
+ for (const limit of [quickLimit, stepLimit]) {
21
+ if (typeof limit === "string")
22
+ return { exitCode: 2, text: `${command}: ${limit}` };
23
+ }
24
+ const loaded = loadConfig(root, options.catalog);
25
+ if ("problems" in loaded)
26
+ return { exitCode: 2, text: [`${command}: suwgate.yml is not valid:`, ...loaded.problems.map((line) => ` ${line}`)].join("\n") };
27
+ let changed;
28
+ const steps = plan({
29
+ root,
30
+ quick: options.quick,
31
+ config: loaded.config,
32
+ catalog: options.catalog,
33
+ files: repositoryFiles(root),
34
+ changed: () => (changed ??= changedFiles(root)),
35
+ });
36
+ 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);
38
+ const totalSeconds = Math.round((performance.now() - began) / 1000);
39
+ const { text, passed } = report({
40
+ results,
41
+ command,
42
+ totalSeconds,
43
+ quickLimit: options.quick ? (typeof quickLimit === "number" ? quickLimit : DEFAULT_QUICK_LIMIT_SECONDS) : null,
44
+ ci: (options.env["CI"] ?? "") !== "",
45
+ exceptions: loaded.config.exceptions.length,
46
+ verbose: options.verbose,
47
+ });
48
+ return { exitCode: passed ? 0 : 1, text };
49
+ }
@@ -0,0 +1,34 @@
1
+ import { type Guard, type GuardException, type Profile, type Step } from "./contract.ts";
2
+ export declare const CONFIG_FILE = "suwgate.yml";
3
+ interface AddedStep {
4
+ name: string;
5
+ run: string;
6
+ title?: string;
7
+ quick?: boolean;
8
+ after?: string[];
9
+ limitSeconds?: number;
10
+ }
11
+ interface SkippedStep {
12
+ step: string;
13
+ reason: string;
14
+ }
15
+ export interface Config {
16
+ profiles: Profile[];
17
+ directories: Partial<Record<Profile, string>>;
18
+ add: AddedStep[];
19
+ skip: SkippedStep[];
20
+ exceptions: GuardException[];
21
+ settings: Record<string, unknown>;
22
+ }
23
+ export interface Catalog {
24
+ guards: readonly Guard[];
25
+ stepsFor(profiles: readonly Profile[]): readonly Step[];
26
+ }
27
+ export type Loaded = {
28
+ config: Config;
29
+ } | {
30
+ problems: string[];
31
+ };
32
+ export declare function parseConfig(text: string, catalog: Catalog): Loaded;
33
+ export declare function loadConfig(root: string, catalog: Catalog): Loaded;
34
+ export {};
@@ -0,0 +1,170 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { Ajv2020 } from "ajv/dist/2020.js";
4
+ import { isNode, LineCounter, parseDocument } from "yaml";
5
+ import { PROFILES } from "./contract.js";
6
+ export const CONFIG_FILE = "suwgate.yml";
7
+ const SCHEMA_FILE = new URL("../../schema/suwgate.schema.json", import.meta.url);
8
+ const DOTNET_GUARD_PREFIXES = { "architecture/": "dotnet", "database/": "database" };
9
+ const ajv = new Ajv2020({ allErrors: true, strict: true });
10
+ const validateFile = ajv.compile(JSON.parse(readFileSync(SCHEMA_FILE, "utf8")));
11
+ function segments(pointer) {
12
+ return pointer
13
+ .split("/")
14
+ .slice(1)
15
+ .map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"))
16
+ .map((part) => (/^\d+$/.test(part) ? Number(part) : part));
17
+ }
18
+ function shownPath(parts) {
19
+ return parts.reduce((shown, part) => (typeof part === "number" ? `${shown}[${part}]` : shown === "" ? part : `${shown}.${part}`), "");
20
+ }
21
+ function locate(document, lineCounter, parts) {
22
+ for (let length = parts.length; length >= 0; length--) {
23
+ const node = length === 0 ? document.contents : document.getIn(parts.slice(0, length), true);
24
+ if (isNode(node) && node.range !== undefined && node.range !== null) {
25
+ const { line, col } = lineCounter.linePos(node.range[0]);
26
+ return `${CONFIG_FILE}:${line}:${col}`;
27
+ }
28
+ }
29
+ return CONFIG_FILE;
30
+ }
31
+ function describe(error) {
32
+ const parts = segments(error.instancePath);
33
+ const where = parts.length === 0 ? "the file" : shownPath(parts);
34
+ const params = error.params;
35
+ switch (error.keyword) {
36
+ case "required": {
37
+ const missing = String(params["missingProperty"]);
38
+ const fix = missing === "reason" ? `: every ${parts[0] === "exceptions" ? "exception" : "skipped step"} says why (reason: <why>)` : "";
39
+ return `${where} has no "${missing}"${fix}`;
40
+ }
41
+ case "additionalProperties":
42
+ return `${where} has an unknown key "${String(params["additionalProperty"])}": check its spelling against the schema`;
43
+ case "propertyNames":
44
+ return `${where} has a key that is not allowed: ${String(params["propertyName"])}`;
45
+ case "enum":
46
+ return `${where} must be one of ${JSON.stringify(params["allowedValues"])}`;
47
+ case "pattern":
48
+ return parts.at(-1) === "reason"
49
+ ? `${where} is empty: say why, in a sentence a reviewer can judge`
50
+ : `${where} ${error.message ?? "is not valid"}`;
51
+ default:
52
+ return `${where} ${error.message ?? "is not valid"}`;
53
+ }
54
+ }
55
+ function relevant(errors) {
56
+ return errors.filter((error) => error.keyword !== "if" && !(error.keyword === "enum" && errors.some((other) => other.keyword === "propertyNames")));
57
+ }
58
+ function guardProfile(id, guards) {
59
+ if (Object.keys(DOTNET_GUARD_PREFIXES).some((prefix) => id.startsWith(prefix)))
60
+ return "dotnet-guard";
61
+ return guards.find((guard) => guard.id === id)?.profiles ?? null;
62
+ }
63
+ function checkExceptions(raw, catalog, problem) {
64
+ const seen = new Set();
65
+ (raw.exceptions ?? []).forEach((exception, index) => {
66
+ const where = ["exceptions", index];
67
+ const profiles = guardProfile(exception.guard, catalog.guards);
68
+ if (profiles === null) {
69
+ problem(where, `no guard "${exception.guard}": the guards are ${catalog.guards.map((guard) => guard.id).join(", ")} (and architecture/*, database/* of the .NET packages)`);
70
+ }
71
+ else if (profiles === "dotnet-guard") {
72
+ const prefix = Object.keys(DOTNET_GUARD_PREFIXES).find((candidate) => exception.guard.startsWith(candidate)) ?? "";
73
+ const needed = DOTNET_GUARD_PREFIXES[prefix];
74
+ if (needed !== undefined && !raw.profiles.includes(needed)) {
75
+ problem(where, `"${exception.guard}" is a guard of the ${needed} profile, which this repository does not have: delete the exception`);
76
+ }
77
+ }
78
+ else if (profiles !== "every" && !profiles.some((profile) => raw.profiles.includes(profile))) {
79
+ problem(where, `"${exception.guard}" runs only for ${profiles.join(", ")}, which this repository does not have: delete the exception`);
80
+ }
81
+ const key = `${exception.guard}\u0000${exception.target}`;
82
+ if (seen.has(key))
83
+ problem(where, `the same exception (${exception.guard}, ${exception.target}) is listed twice: keep one`);
84
+ seen.add(key);
85
+ });
86
+ }
87
+ function checkSteps(raw, catalog, problem) {
88
+ const known = catalog.stepsFor(raw.profiles).map((step) => step.id);
89
+ const added = (raw.steps?.add ?? []).map((step) => step.name);
90
+ (raw.steps?.add ?? []).forEach((step, index) => {
91
+ if (known.includes(step.name))
92
+ problem(["steps", "add", index, "name"], `the profiles already have a step "${step.name}": pick another name, or skip theirs`);
93
+ if (added.indexOf(step.name) !== index)
94
+ problem(["steps", "add", index, "name"], `"${step.name}" is added twice`);
95
+ (step.after ?? []).forEach((after, at) => {
96
+ if (!known.includes(after) && !added.includes(after)) {
97
+ problem(["steps", "add", index, "after", at], `no step "${after}": the steps are ${[...known, ...added].join(", ")}`);
98
+ }
99
+ });
100
+ });
101
+ (raw.steps?.skip ?? []).forEach((skipped, index) => {
102
+ if (!known.includes(skipped.step)) {
103
+ problem(["steps", "skip", index, "step"], `the profiles ${raw.profiles.join(", ")} have no step "${skipped.step}": their steps are ${known.join(", ")}`);
104
+ }
105
+ });
106
+ }
107
+ function checkSettings(raw, catalog, problem) {
108
+ for (const [id, value] of Object.entries(raw.settings ?? {})) {
109
+ const guard = catalog.guards.find((candidate) => candidate.id === id);
110
+ if (guard?.settingsSchema === undefined) {
111
+ problem(["settings", id], guard === undefined ? `no guard "${id}"` : `the guard "${id}" takes no settings`);
112
+ continue;
113
+ }
114
+ const validate = ajv.compile(guard.settingsSchema);
115
+ if (!validate(value)) {
116
+ for (const error of relevant(validate.errors ?? [])) {
117
+ const inner = segments(error.instancePath);
118
+ problem(["settings", id, ...inner], describe({ ...error, instancePath: `/settings/${id}${error.instancePath}` }));
119
+ }
120
+ }
121
+ }
122
+ }
123
+ function checkDirectories(raw, problem) {
124
+ for (const profile of Object.keys(raw.directories ?? {})) {
125
+ if (!raw.profiles.includes(profile))
126
+ problem(["directories", profile], `"${profile}" is not one of this repository's profiles`);
127
+ }
128
+ }
129
+ export function parseConfig(text, catalog) {
130
+ const lineCounter = new LineCounter();
131
+ const document = parseDocument(text, { lineCounter, prettyErrors: true, uniqueKeys: true });
132
+ if (document.errors.length > 0) {
133
+ return {
134
+ problems: document.errors.map((error) => `${CONFIG_FILE}:${error.linePos?.[0].line ?? 1}:${error.linePos?.[0].col ?? 1}: ${(error.message.split("\n")[0] ?? "").replace(/ at line \d+, column \d+:?$/, "")}`),
135
+ };
136
+ }
137
+ const data = document.toJS();
138
+ if (!validateFile(data)) {
139
+ return {
140
+ problems: relevant(validateFile.errors ?? []).map((error) => `${locate(document, lineCounter, segments(error.instancePath))}: ${describe(error)}`),
141
+ };
142
+ }
143
+ const problems = [];
144
+ const problem = (parts, text) => {
145
+ problems.push(`${locate(document, lineCounter, parts)}: ${shownPath(parts)}: ${text}`);
146
+ };
147
+ checkDirectories(data, problem);
148
+ checkExceptions(data, catalog, problem);
149
+ checkSteps(data, catalog, problem);
150
+ checkSettings(data, catalog, problem);
151
+ if (problems.length > 0)
152
+ return { problems };
153
+ return {
154
+ config: {
155
+ profiles: PROFILES.filter((profile) => data.profiles.includes(profile)),
156
+ directories: data.directories ?? {},
157
+ add: data.steps?.add ?? [],
158
+ skip: data.steps?.skip ?? [],
159
+ exceptions: data.exceptions ?? [],
160
+ settings: data.settings ?? {},
161
+ },
162
+ };
163
+ }
164
+ export function loadConfig(root, catalog) {
165
+ const file = path.join(root, CONFIG_FILE);
166
+ if (!existsSync(file)) {
167
+ return { problems: [`no ${CONFIG_FILE} in ${root}: create it with at least \`profiles: [<${PROFILES.join(" | ")}>]\``] };
168
+ }
169
+ return parseConfig(readFileSync(file, "utf8"), catalog);
170
+ }
@@ -0,0 +1,51 @@
1
+ export declare const PROFILES: readonly ["web", "library", "dotnet", "database"];
2
+ export type Profile = (typeof PROFILES)[number];
3
+ export interface Finding {
4
+ target: string;
5
+ message: string;
6
+ line?: number;
7
+ }
8
+ export interface GuardException {
9
+ guard: string;
10
+ target: string;
11
+ reason: string;
12
+ }
13
+ export interface GuardContext {
14
+ root: string;
15
+ files: readonly string[];
16
+ profiles: readonly Profile[];
17
+ directories: Readonly<Partial<Record<Profile, string>>>;
18
+ exceptions: readonly GuardException[];
19
+ settings: unknown;
20
+ read(file: string): string;
21
+ }
22
+ export interface Guard {
23
+ id: string;
24
+ description: string;
25
+ profiles: readonly Profile[] | "every";
26
+ quick?: boolean;
27
+ settingsSchema?: object;
28
+ check(context: GuardContext): readonly Finding[] | Promise<readonly Finding[]>;
29
+ }
30
+ export interface StepContext {
31
+ root: string;
32
+ cwd: string;
33
+ quick: boolean;
34
+ profiles: readonly Profile[];
35
+ directories: Readonly<Partial<Record<Profile, string>>>;
36
+ changed(): readonly string[];
37
+ }
38
+ export interface Skip {
39
+ skip: string;
40
+ }
41
+ export type Run = string | ((context: StepContext) => string | null | Skip);
42
+ export interface Step {
43
+ id: string;
44
+ title: string;
45
+ run: Run;
46
+ quick?: Run | true;
47
+ profile?: Profile;
48
+ needs?: readonly string[];
49
+ after?: readonly string[];
50
+ limitSeconds?: number;
51
+ }
@@ -0,0 +1 @@
1
+ export const PROFILES = ["web", "library", "dotnet", "database"];
@@ -0,0 +1,14 @@
1
+ import { type Config } from "./config.ts";
2
+ import type { Guard } from "./contract.ts";
3
+ interface GuardsSummary {
4
+ passed: boolean;
5
+ log: string;
6
+ }
7
+ interface GuardsInput {
8
+ root: string;
9
+ guards: readonly Guard[];
10
+ files: readonly string[];
11
+ config: Config;
12
+ }
13
+ export declare function runGuards(input: GuardsInput): Promise<GuardsSummary>;
14
+ export {};