@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,108 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { askOnTerminal, DB_USAGE, parseDb, runDb } from "./db.js";
3
+ import { CHECKOUT_ENV_USAGE, runCheckoutEnv } from "./checkoutEnv.js";
4
+ import { LOGS_USAGE, parseLogs, runLogs } from "./logs.js";
5
+ import { exec, Failure, UsageError } from "./process.js";
6
+ import { runServer, SERVER_USAGE } from "./server.js";
7
+ import { loadSettings } from "./settings.js";
8
+ import { parseSmoke, realFetch, runSmoke, SMOKE_USAGE } from "./smoke.js";
9
+ import { parseTmux, runTmux, TMUX_USAGE } from "./tmux.js";
10
+ export const DEV_USAGE = `usage: suwgate dev <db|logs|smoke|server|tmux|checkout-env> [arguments] (every one takes --help)
11
+ The dev scripts of the template as commands, configured by the dev section of suwgate.yml:
12
+ db the local PostgreSQL of the compose file: up | down | reset | psql | logs | status
13
+ logs why did it fail? the last warnings and errors of the server's JSON log
14
+ smoke read-only requests against a running stack
15
+ server the server under dotnet watch, restarted when it exits
16
+ tmux the whole local stack in one tmux session: start [--restart] | stop
17
+ checkout-env eval "$(suwgate dev checkout-env)": own test databases and e2e ports for a linked worktree`;
18
+ const USAGES = {
19
+ db: DB_USAGE,
20
+ logs: LOGS_USAGE,
21
+ smoke: SMOKE_USAGE,
22
+ server: SERVER_USAGE,
23
+ tmux: TMUX_USAGE,
24
+ "checkout-env": CHECKOUT_ENV_USAGE,
25
+ };
26
+ function repositoryRootOf(cwd) {
27
+ try {
28
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
29
+ }
30
+ catch {
31
+ return cwd;
32
+ }
33
+ }
34
+ function realEnvironment() {
35
+ return {
36
+ cwd: process.cwd(),
37
+ env: process.env,
38
+ io: { out: (text) => console.log(text), err: (text) => console.error(text) },
39
+ exec,
40
+ fetch: realFetch,
41
+ self: `${JSON.stringify(process.execPath)} ${JSON.stringify(process.argv[1] ?? "suwgate")}`,
42
+ interactive: process.stdin.isTTY,
43
+ ask: askOnTerminal,
44
+ loadSettings: (cwd) => loadSettings(repositoryRootOf(cwd)),
45
+ };
46
+ }
47
+ async function dispatch(command, args, environment) {
48
+ const { io } = environment;
49
+ const settings = () => environment.loadSettings(environment.cwd);
50
+ switch (command) {
51
+ case "db": {
52
+ const parsed = parseDb(args);
53
+ return runDb(parsed, {
54
+ settings: settings(),
55
+ exec: environment.exec,
56
+ io,
57
+ interactive: environment.interactive,
58
+ ask: environment.ask,
59
+ });
60
+ }
61
+ case "logs":
62
+ return runLogs(parseLogs(args), settings(), environment.exec, io, environment.cwd);
63
+ case "smoke":
64
+ return runSmoke(parseSmoke(args), settings(), environment.fetch, io);
65
+ case "server":
66
+ return runServer(args, settings(), io);
67
+ case "tmux":
68
+ return runTmux(parseTmux(args), {
69
+ settings: settings(),
70
+ exec: environment.exec,
71
+ io,
72
+ env: environment.env,
73
+ self: environment.self,
74
+ });
75
+ default:
76
+ return runCheckoutEnv(args, settings(), environment.env, io);
77
+ }
78
+ }
79
+ export async function dev(argv, environment = realEnvironment()) {
80
+ const [command, ...args] = argv;
81
+ if (command === undefined || command === "--help") {
82
+ environment.io.out(DEV_USAGE);
83
+ return command === undefined ? 2 : 0;
84
+ }
85
+ const usage = USAGES[command];
86
+ if (usage === undefined) {
87
+ environment.io.err(`suwgate dev: no command "${command}"\n${DEV_USAGE}`);
88
+ return 2;
89
+ }
90
+ if (args[0] === "--help") {
91
+ environment.io.out(usage);
92
+ return 0;
93
+ }
94
+ try {
95
+ return await dispatch(command, args, environment);
96
+ }
97
+ catch (error) {
98
+ if (error instanceof UsageError) {
99
+ environment.io.err(error.message);
100
+ return 2;
101
+ }
102
+ if (error instanceof Failure) {
103
+ environment.io.err(error.message);
104
+ return error.exitCode;
105
+ }
106
+ throw error;
107
+ }
108
+ }
@@ -0,0 +1,15 @@
1
+ import { type Exec, type Io } from "./process.ts";
2
+ import type { DevSettings } from "./settings.ts";
3
+ export declare const LOGS_USAGE = "usage: suwgate dev logs [--all] [--trace <id>] [--compose] [-n N] [--file <path>]\nWhy did it fail? One command, short output, from the server's JSON log lines.\n (no option) the last warnings and errors of the newest log in the folder of dev.server.logFile\n --all every level\n --trace <id> every line of one request: the traceId of an error response (32 hex digits or the W3C form)\n --compose read the compose server (docker compose logs) instead of a file\n -n 50 the last 50 lines (default 20)\n --file <path> a specific log file\nOne line each: time level category trace=... message, and for an exception its type and first line.\nThe logs are written by the server of `suwgate dev server` and by the browser tests of the repository.";
4
+ export interface LogsCommand {
5
+ all: boolean;
6
+ trace: string;
7
+ compose: boolean;
8
+ count: number;
9
+ file: string;
10
+ }
11
+ export declare function parseLogs(args: readonly string[]): LogsCommand;
12
+ export declare function formatLine(line: string, command: Pick<LogsCommand, "all" | "trace">): string | null;
13
+ export declare function formatLog(content: string, command: LogsCommand): string[];
14
+ export declare function newestLog(directory: string): string | null;
15
+ export declare function runLogs(command: LogsCommand, settings: DevSettings, exec: Exec, io: Io, cwd: string): Promise<number>;
@@ -0,0 +1,127 @@
1
+ import { readdirSync, readFileSync, statSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import { composeBase } from "./db.js";
5
+ import { Failure, UsageError } from "./process.js";
6
+ export const LOGS_USAGE = `usage: suwgate dev logs [--all] [--trace <id>] [--compose] [-n N] [--file <path>]
7
+ Why did it fail? One command, short output, from the server's JSON log lines.
8
+ (no option) the last warnings and errors of the newest log in the folder of dev.server.logFile
9
+ --all every level
10
+ --trace <id> every line of one request: the traceId of an error response (32 hex digits or the W3C form)
11
+ --compose read the compose server (docker compose logs) instead of a file
12
+ -n 50 the last 50 lines (default 20)
13
+ --file <path> a specific log file
14
+ One line each: time level category trace=... message, and for an exception its type and first line.
15
+ The logs are written by the server of \`suwgate dev server\` and by the browser tests of the repository.`;
16
+ const SHOWN_LEVELS = ["Warning", "Error", "Critical"];
17
+ const MESSAGE_LIMIT = 300;
18
+ const EXCEPTION_LIMIT = 200;
19
+ const LEVEL_WIDTH = 11;
20
+ export function parseLogs(args) {
21
+ let values;
22
+ try {
23
+ ({ values } = parseArgs({
24
+ args: [...args],
25
+ strict: true,
26
+ options: {
27
+ all: { type: "boolean" },
28
+ trace: { type: "string" },
29
+ compose: { type: "boolean" },
30
+ n: { type: "string", short: "n" },
31
+ file: { type: "string" },
32
+ },
33
+ }));
34
+ }
35
+ catch (error) {
36
+ throw new UsageError(`${error instanceof Error ? error.message : String(error)}\n${LOGS_USAGE}`);
37
+ }
38
+ const count = values.n === undefined ? 20 : Number(values.n);
39
+ if (!Number.isInteger(count) || count < 1)
40
+ throw new UsageError(`-n needs a positive number, got "${values.n}"`);
41
+ const traceText = values.trace;
42
+ let trace = "";
43
+ if (traceText !== undefined) {
44
+ const match = /[0-9a-f]{32}/i.exec(traceText);
45
+ if (match === null)
46
+ throw new UsageError("that is not a traceId (32 hex digits, or 00-<32 hex>-<16 hex>-<2 hex>)");
47
+ trace = match[0].toLowerCase();
48
+ }
49
+ return {
50
+ all: values.all === true || trace !== "",
51
+ trace,
52
+ compose: values.compose === true,
53
+ count,
54
+ file: values.file ?? "",
55
+ };
56
+ }
57
+ function field(record, name) {
58
+ const value = record[name];
59
+ return typeof value === "string" ? value : "";
60
+ }
61
+ function oneLine(value) {
62
+ return value.replace(/\s*[\r\n]+\s*/g, " ");
63
+ }
64
+ export function formatLine(line, command) {
65
+ if (!line.startsWith("{"))
66
+ return null;
67
+ let record;
68
+ try {
69
+ record = JSON.parse(line);
70
+ }
71
+ catch {
72
+ return null;
73
+ }
74
+ const level = field(record, "LogLevel");
75
+ if (command.trace !== "" && !line.includes(command.trace))
76
+ return null;
77
+ if (!command.all && !SHOWN_LEVELS.includes(level))
78
+ return null;
79
+ const traceId = field(record, "TraceId");
80
+ const exception = field(record, "Exception").split(/[\r\n]/, 1)[0] ?? "";
81
+ const shownException = exception === "" ? "" : ` | ${exception.slice(0, EXCEPTION_LIMIT)}`;
82
+ const shownTrace = traceId === "" ? "" : ` trace=${traceId}`;
83
+ const message = oneLine(field(record, "Message")).slice(0, MESSAGE_LIMIT);
84
+ return `${field(record, "Timestamp")} ${level.padEnd(LEVEL_WIDTH)} ${field(record, "Category")}${shownTrace} ${message}${shownException}`;
85
+ }
86
+ export function formatLog(content, command) {
87
+ const shown = content.split("\n").flatMap((line) => formatLine(line, command) ?? []);
88
+ return shown.slice(-command.count);
89
+ }
90
+ export function newestLog(directory) {
91
+ let names;
92
+ try {
93
+ names = readdirSync(directory).filter((name) => name.endsWith(".jsonl"));
94
+ }
95
+ catch {
96
+ return null;
97
+ }
98
+ const files = names.map((name) => ({ file: path.join(directory, name), time: statSync(path.join(directory, name)).mtimeMs }));
99
+ return files.sort((left, right) => right.time - left.time)[0]?.file ?? null;
100
+ }
101
+ export async function runLogs(command, settings, exec, io, cwd) {
102
+ let sourceName;
103
+ let content;
104
+ if (command.compose) {
105
+ const service = settings.compose.serverService;
106
+ sourceName = `docker compose logs ${service}`;
107
+ const result = await exec([...composeBase(settings), "logs", "--no-log-prefix", "--no-color", service], { capture: true });
108
+ content = result.stdout;
109
+ }
110
+ else {
111
+ const file = command.file === "" ? newestLog(path.dirname(path.join(settings.root, settings.logFile))) : path.resolve(cwd, command.file);
112
+ if (file === null) {
113
+ throw new Failure("suwgate dev logs: no log file yet. Start the server with `suwgate dev tmux start` (or `suwgate dev server`), or run the browser tests (they write the logs), or read the container stack with --compose.");
114
+ }
115
+ try {
116
+ content = readFileSync(file, "utf8");
117
+ }
118
+ catch {
119
+ throw new Failure(`suwgate dev logs: cannot read ${file}`);
120
+ }
121
+ sourceName = path.relative(settings.root, file);
122
+ }
123
+ io.out(`# ${sourceName}`);
124
+ for (const line of formatLog(content, command))
125
+ io.out(line);
126
+ return 0;
127
+ }
@@ -0,0 +1,24 @@
1
+ export declare class UsageError extends Error {
2
+ }
3
+ export declare class Failure extends Error {
4
+ readonly exitCode: number;
5
+ constructor(message: string, exitCode?: number);
6
+ }
7
+ export interface ExecOptions {
8
+ cwd?: string;
9
+ env?: Readonly<Record<string, string | undefined>>;
10
+ capture?: boolean;
11
+ quiet?: boolean;
12
+ }
13
+ interface ExecResult {
14
+ status: number;
15
+ stdout: string;
16
+ }
17
+ export type Exec = (argv: readonly string[], options?: ExecOptions) => Promise<ExecResult>;
18
+ export interface Io {
19
+ out(text: string): void;
20
+ err(text: string): void;
21
+ }
22
+ export declare function quoted(argument: string): string;
23
+ export declare const exec: Exec;
24
+ export {};
@@ -0,0 +1,34 @@
1
+ import { spawn } from "node:child_process";
2
+ export class UsageError extends Error {
3
+ }
4
+ export class Failure extends Error {
5
+ exitCode;
6
+ constructor(message, exitCode = 1) {
7
+ super(message);
8
+ this.exitCode = exitCode;
9
+ }
10
+ }
11
+ export function quoted(argument) {
12
+ return `'${argument.replaceAll("'", `'"'"'`)}'`;
13
+ }
14
+ export const exec = (argv, options = {}) => new Promise((resolve) => {
15
+ const [program = "", ...args] = argv;
16
+ const stdio = options.capture === true
17
+ ? ["inherit", "pipe", "inherit"]
18
+ : options.quiet === true
19
+ ? ["inherit", "ignore", "ignore"]
20
+ : "inherit";
21
+ const child = spawn(program, args, {
22
+ cwd: options.cwd ?? process.cwd(),
23
+ env: { ...process.env, ...options.env },
24
+ stdio: stdio,
25
+ });
26
+ let stdout = "";
27
+ child.stdout?.setEncoding("utf8").on("data", (chunk) => (stdout += chunk));
28
+ child.on("error", (error) => {
29
+ resolve({ status: 127, stdout: `${program}: ${error.message}` });
30
+ });
31
+ child.on("close", (status) => {
32
+ resolve({ status: status ?? 1, stdout });
33
+ });
34
+ });
@@ -0,0 +1,8 @@
1
+ import { type Io } from "./process.ts";
2
+ import { type DevSettings } from "./settings.ts";
3
+ export declare const SERVER_USAGE = "usage: suwgate dev server [dotnet run arguments]\nThe server under `dotnet watch`, rebuilt on every change, with the settings of the gitignored .env of the repository root.\n`suwgate dev tmux start` runs it in its pane after `suwgate dev db up`. An edit hot reload cannot apply restarts the app\nwithout asking, and when dotnet watch itself exits it is started again after a pause that grows while it keeps failing fast\n(Ctrl+C stops it). Its JSON log is also written to dev.server.logFile, which `suwgate dev logs` reads.\nEvery argument goes to `dotnet run`.";
4
+ export declare const MAX_PAUSE_SECONDS = 60;
5
+ export declare function serverScript(project: string): string;
6
+ export declare function nextPause(previous: number, ranSeconds: number): number;
7
+ export declare function serverArgv(settings: DevSettings, args: readonly string[]): string[];
8
+ export declare function runServer(args: readonly string[], settings: DevSettings, io: Io): Promise<number>;
@@ -0,0 +1,61 @@
1
+ import { spawn } from "node:child_process";
2
+ import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { quoted } from "./process.js";
5
+ import { needServerProject } from "./settings.js";
6
+ export const SERVER_USAGE = `usage: suwgate dev server [dotnet run arguments]
7
+ The server under \`dotnet watch\`, rebuilt on every change, with the settings of the gitignored .env of the repository root.
8
+ \`suwgate dev tmux start\` runs it in its pane after \`suwgate dev db up\`. An edit hot reload cannot apply restarts the app
9
+ without asking, and when dotnet watch itself exits it is started again after a pause that grows while it keeps failing fast
10
+ (Ctrl+C stops it). Its JSON log is also written to dev.server.logFile, which \`suwgate dev logs\` reads.
11
+ Every argument goes to \`dotnet run\`.`;
12
+ const QUICK_FAILURE_SECONDS = 60;
13
+ export const MAX_PAUSE_SECONDS = 60;
14
+ const INTERRUPTED = 130;
15
+ export function serverScript(project) {
16
+ return `set -a; if [ -f .env ]; then source .env; fi; set +a; exec dotnet watch --non-interactive --quiet --project ${quoted(project)} run "$@" 2>&1`;
17
+ }
18
+ export function nextPause(previous, ranSeconds) {
19
+ return ranSeconds >= QUICK_FAILURE_SECONDS ? 2 : Math.min(previous * 2, MAX_PAUSE_SECONDS);
20
+ }
21
+ export function serverArgv(settings, args) {
22
+ return ["bash", "-c", serverScript(needServerProject(settings)), "suwgate-dev-server", ...args];
23
+ }
24
+ function runOnce(argv, settings, log, stopping) {
25
+ return new Promise((resolve) => {
26
+ const [program = "", ...args] = argv;
27
+ const child = spawn(program, args, { cwd: settings.root, stdio: ["inherit", "pipe", "inherit"] });
28
+ const forward = () => {
29
+ stopping.requested = true;
30
+ child.kill("SIGTERM");
31
+ };
32
+ process.once("SIGINT", forward);
33
+ process.once("SIGTERM", forward);
34
+ child.stdout.on("data", (chunk) => {
35
+ process.stdout.write(chunk);
36
+ appendFileSync(log, chunk);
37
+ });
38
+ child.on("close", (status) => {
39
+ process.removeListener("SIGINT", forward);
40
+ process.removeListener("SIGTERM", forward);
41
+ resolve(status ?? 1);
42
+ });
43
+ });
44
+ }
45
+ export async function runServer(args, settings, io) {
46
+ const argv = serverArgv(settings, args);
47
+ const log = path.join(settings.root, settings.logFile);
48
+ mkdirSync(path.dirname(log), { recursive: true });
49
+ writeFileSync(log, "");
50
+ const stopping = { requested: false };
51
+ let pause = 1;
52
+ for (;;) {
53
+ const started = Date.now();
54
+ const status = await runOnce(argv, settings, log, stopping);
55
+ if (stopping.requested)
56
+ return INTERRUPTED;
57
+ pause = nextPause(pause, (Date.now() - started) / 1000);
58
+ io.err(`suwgate dev server: dotnet watch exited with code ${status}; starting it again in ${pause}s (Ctrl+C stops)`);
59
+ await new Promise((resolve) => setTimeout(resolve, pause * 1000));
60
+ }
61
+ }
@@ -0,0 +1,46 @@
1
+ export interface SmokeCheck {
2
+ path: string;
3
+ expect: string;
4
+ hint: string;
5
+ }
6
+ export interface DevSettings {
7
+ root: string;
8
+ name: string;
9
+ ports: {
10
+ server: number;
11
+ web: number;
12
+ e2eServer: number;
13
+ e2eWeb: number;
14
+ database: number;
15
+ stack: number;
16
+ };
17
+ compose: {
18
+ file: string;
19
+ profile: string;
20
+ databaseService: string;
21
+ serverService: string;
22
+ extraServices: string[];
23
+ };
24
+ database: {
25
+ user: string;
26
+ password: string;
27
+ name: string;
28
+ };
29
+ serverProject: string | null;
30
+ webDirectory: string | null;
31
+ logFile: string;
32
+ smokeChecks: SmokeCheck[];
33
+ }
34
+ export declare const BASE_PORTS: {
35
+ readonly server: 6300;
36
+ readonly web: 3300;
37
+ readonly e2eServer: 6301;
38
+ readonly e2eWeb: 3301;
39
+ readonly database: 5533;
40
+ readonly stack: 8190;
41
+ };
42
+ export declare const DEFAULT_SMOKE_CHECKS: readonly SmokeCheck[];
43
+ export declare function resolveSettings(raw: unknown, directories: Readonly<Record<string, unknown>>, root: string): DevSettings;
44
+ export declare function loadSettings(root: string): DevSettings;
45
+ export declare function needServerProject(settings: DevSettings): string;
46
+ export declare function needWebDirectory(settings: DevSettings): string;
@@ -0,0 +1,160 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { parse } from "yaml";
4
+ import { Failure } from "./process.js";
5
+ export const BASE_PORTS = { server: 6300, web: 3300, e2eServer: 6301, e2eWeb: 3301, database: 5533, stack: 8190 };
6
+ export const DEFAULT_SMOKE_CHECKS = [
7
+ { path: "/healthz", expect: "^ok", hint: "nginx in the web container does not answer: docker compose ps, docker compose logs web." },
8
+ {
9
+ path: "/api/health",
10
+ expect: '"status":"ok"',
11
+ hint: "the page reaches nginx but not a healthy server with its database: docker compose logs server, check ConnectionStrings__Default.",
12
+ },
13
+ ];
14
+ const NAME = /^[a-z][a-z0-9-]*$/;
15
+ const ROOT_KEYS = ["name", "portOffset", "ports", "compose", "database", "server", "smoke"];
16
+ const PORT_KEYS = Object.keys(BASE_PORTS);
17
+ const COMPOSE_KEYS = ["file", "profile", "databaseService", "serverService", "extraServices"];
18
+ const DATABASE_KEYS = ["user", "password", "name"];
19
+ const SERVER_KEYS = ["project", "logFile"];
20
+ const SMOKE_KEYS = ["checks"];
21
+ const CHECK_KEYS = ["path", "expect", "hint"];
22
+ const PORT_RANGE = { min: 1, max: 65535 };
23
+ function section(value, where, keys, problems) {
24
+ if (value === undefined)
25
+ return {};
26
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
27
+ problems.push(`${where} must be a mapping`);
28
+ return {};
29
+ }
30
+ const record = value;
31
+ for (const key of Object.keys(record)) {
32
+ if (!keys.includes(key))
33
+ problems.push(`${where}.${key} is not a setting of suwgate dev: the settings are ${keys.join(", ")}`);
34
+ }
35
+ return record;
36
+ }
37
+ function text(record, key, where, fallback, problems) {
38
+ const value = record[key];
39
+ if (value === undefined)
40
+ return fallback;
41
+ if (typeof value === "string" && value.trim() !== "")
42
+ return value;
43
+ problems.push(`${where}.${key} must be a non-empty string`);
44
+ return fallback;
45
+ }
46
+ function whole(record, key, where, fallback, problems) {
47
+ const value = record[key];
48
+ if (value === undefined)
49
+ return fallback;
50
+ if (typeof value === "number" && Number.isInteger(value))
51
+ return value;
52
+ problems.push(`${where}.${key} must be an integer`);
53
+ return fallback;
54
+ }
55
+ function list(record, key, where, problems) {
56
+ const value = record[key];
57
+ if (value === undefined)
58
+ return [];
59
+ if (Array.isArray(value) && value.every((item) => typeof item === "string" && item !== ""))
60
+ return value;
61
+ problems.push(`${where}.${key} must be a list of names`);
62
+ return [];
63
+ }
64
+ function smokeChecks(raw, problems) {
65
+ const smoke = section(raw, "dev.smoke", SMOKE_KEYS, problems);
66
+ const checks = smoke["checks"];
67
+ if (checks === undefined)
68
+ return [...DEFAULT_SMOKE_CHECKS];
69
+ if (!Array.isArray(checks) || checks.length === 0) {
70
+ problems.push("dev.smoke.checks must be a non-empty list of {path, expect, hint}");
71
+ return [];
72
+ }
73
+ return checks.map((check, index) => {
74
+ const where = `dev.smoke.checks[${index}]`;
75
+ const record = section(check, where, CHECK_KEYS, problems);
76
+ const expect = text(record, "expect", where, "", problems);
77
+ try {
78
+ new RegExp(expect, "m");
79
+ }
80
+ catch {
81
+ problems.push(`${where}.expect is not a regular expression: ${expect}`);
82
+ }
83
+ const checkPath = text(record, "path", where, "", problems);
84
+ if (!checkPath.startsWith("/"))
85
+ problems.push(`${where}.path must start with /`);
86
+ return { path: checkPath, expect, hint: text(record, "hint", where, "", problems) };
87
+ });
88
+ }
89
+ export function resolveSettings(raw, directories, root) {
90
+ if (raw === undefined) {
91
+ throw new Failure("suwgate.yml has no dev section: add `dev:` with at least `name: <short lower-case name of the app>` (see docs/dev.md)", 2);
92
+ }
93
+ const problems = [];
94
+ const top = section(raw, "dev", ROOT_KEYS, problems);
95
+ const name = text(top, "name", "dev", "", problems);
96
+ if (top["name"] === undefined)
97
+ problems.push("dev.name is missing: the short lower-case name of the app (it names the tmux session and the database)");
98
+ else if (!NAME.test(name))
99
+ problems.push(`dev.name "${name}" must be lower-case letters, digits and dashes, starting with a letter`);
100
+ const offset = whole(top, "portOffset", "dev", 0, problems);
101
+ const portsRaw = section(top["ports"], "dev.ports", PORT_KEYS, problems);
102
+ const ports = Object.fromEntries(Object.entries(BASE_PORTS).map(([key, base]) => [key, whole(portsRaw, key, "dev.ports", base + offset, problems)]));
103
+ for (const [key, port] of Object.entries(ports)) {
104
+ if (port < PORT_RANGE.min || port > PORT_RANGE.max) {
105
+ problems.push(`port ${key} is ${port}, outside ${PORT_RANGE.min}-${PORT_RANGE.max}: lower dev.portOffset or set dev.ports.${key}`);
106
+ }
107
+ }
108
+ const composeRaw = section(top["compose"], "dev.compose", COMPOSE_KEYS, problems);
109
+ const databaseRaw = section(top["database"], "dev.database", DATABASE_KEYS, problems);
110
+ const user = text(databaseRaw, "user", "dev.database", name, problems);
111
+ const serverRaw = section(top["server"], "dev.server", SERVER_KEYS, problems);
112
+ const settings = {
113
+ root,
114
+ name,
115
+ ports,
116
+ compose: {
117
+ file: text(composeRaw, "file", "dev.compose", "compose.yaml", problems),
118
+ profile: text(composeRaw, "profile", "dev.compose", "db", problems),
119
+ databaseService: text(composeRaw, "databaseService", "dev.compose", "db", problems),
120
+ serverService: text(composeRaw, "serverService", "dev.compose", "server", problems),
121
+ extraServices: list(composeRaw, "extraServices", "dev.compose", problems),
122
+ },
123
+ database: {
124
+ user,
125
+ password: text(databaseRaw, "password", "dev.database", user, problems),
126
+ name: text(databaseRaw, "name", "dev.database", name, problems),
127
+ },
128
+ serverProject: typeof serverRaw["project"] === "string" ? serverRaw["project"] : stringOrNull(directories["dotnet"]),
129
+ webDirectory: stringOrNull(directories["web"]),
130
+ logFile: text(serverRaw, "logFile", "dev.server", ".artifacts/logs/server.jsonl", problems),
131
+ smokeChecks: smokeChecks(top["smoke"], problems),
132
+ };
133
+ if (problems.length > 0) {
134
+ throw new Failure(`suwgate.yml: ${problems.join("\n suwgate.yml: ")}`, 2);
135
+ }
136
+ return settings;
137
+ }
138
+ function stringOrNull(value) {
139
+ return typeof value === "string" ? value : null;
140
+ }
141
+ export function loadSettings(root) {
142
+ const file = path.join(root, "suwgate.yml");
143
+ if (!existsSync(file))
144
+ throw new Failure(`no suwgate.yml in ${root}: suwgate dev reads its settings from the dev section there`, 2);
145
+ const data = (parse(readFileSync(file, "utf8")) ?? {});
146
+ const directories = typeof data["directories"] === "object" && data["directories"] !== null ? data["directories"] : {};
147
+ return resolveSettings(data["dev"], directories, root);
148
+ }
149
+ export function needServerProject(settings) {
150
+ if (settings.serverProject === null) {
151
+ throw new Failure("no server project: set directories.dotnet (or dev.server.project) in suwgate.yml to the folder of the server's .csproj", 2);
152
+ }
153
+ return settings.serverProject;
154
+ }
155
+ export function needWebDirectory(settings) {
156
+ if (settings.webDirectory === null) {
157
+ throw new Failure("no web app folder: set directories.web in suwgate.yml to the folder of the web app's package.json", 2);
158
+ }
159
+ return settings.webDirectory;
160
+ }
@@ -0,0 +1,15 @@
1
+ import { type Io } from "./process.ts";
2
+ import type { DevSettings, SmokeCheck } from "./settings.ts";
3
+ export declare const SMOKE_USAGE = "usage: suwgate dev smoke [<base-url>] e.g. suwgate dev smoke http://127.0.0.1:8190\nSmoke test of a running stack. Read-only requests through the web's nginx, the way traffic arrives: the page answers, and\nthe server behind it answers with its database. The base url defaults to the stack's web port (dev.ports.stack);\nthe requests are dev.smoke.checks (default: /healthz and /api/health). Prints what failed and what to look at;\nthe exit code is non-zero on any failure.";
4
+ export type Fetch = (url: string) => Promise<{
5
+ status: number;
6
+ body: string;
7
+ }>;
8
+ export interface SmokeCommand {
9
+ baseUrl: string | null;
10
+ }
11
+ export declare function parseSmoke(args: readonly string[]): SmokeCommand;
12
+ export declare function baseUrlOf(settings: DevSettings, command: SmokeCommand): string;
13
+ export declare const realFetch: Fetch;
14
+ export declare function checkOne(base: string, check: SmokeCheck, fetcher: Fetch): Promise<string | null>;
15
+ export declare function runSmoke(command: SmokeCommand, settings: DevSettings, fetcher: Fetch, io: Io): Promise<number>;
@@ -0,0 +1,50 @@
1
+ import { UsageError } from "./process.js";
2
+ export const SMOKE_USAGE = `usage: suwgate dev smoke [<base-url>] e.g. suwgate dev smoke http://127.0.0.1:8190
3
+ Smoke test of a running stack. Read-only requests through the web's nginx, the way traffic arrives: the page answers, and
4
+ the server behind it answers with its database. The base url defaults to the stack's web port (dev.ports.stack);
5
+ the requests are dev.smoke.checks (default: /healthz and /api/health). Prints what failed and what to look at;
6
+ the exit code is non-zero on any failure.`;
7
+ const TIMEOUT_MS = 10_000;
8
+ export function parseSmoke(args) {
9
+ const [first, ...rest] = args;
10
+ if (rest.length > 0 || first?.startsWith("-") === true)
11
+ throw new UsageError(SMOKE_USAGE);
12
+ return { baseUrl: first ?? null };
13
+ }
14
+ export function baseUrlOf(settings, command) {
15
+ return (command.baseUrl ?? `http://127.0.0.1:${settings.ports.stack}`).replace(/\/+$/, "");
16
+ }
17
+ export const realFetch = async (url) => {
18
+ const response = await fetch(url, { signal: AbortSignal.timeout(TIMEOUT_MS) });
19
+ return { status: response.status, body: await response.text() };
20
+ };
21
+ export async function checkOne(base, check, fetcher) {
22
+ let status;
23
+ let body = "";
24
+ try {
25
+ const response = await fetcher(`${base}${check.path}`);
26
+ status = String(response.status);
27
+ body = response.body;
28
+ }
29
+ catch {
30
+ status = "unreachable";
31
+ }
32
+ if (status === "200" && new RegExp(check.expect, "m").test(body))
33
+ return null;
34
+ return `${base}${check.path}: got status '${status}', expected 200 with '${check.expect}' in the body. ${check.hint}`;
35
+ }
36
+ export async function runSmoke(command, settings, fetcher, io) {
37
+ const base = baseUrlOf(settings, command);
38
+ let failed = false;
39
+ for (const check of settings.smokeChecks) {
40
+ const failure = await checkOne(base, check, fetcher);
41
+ if (failure === null) {
42
+ io.out(`ok ${check.path}`);
43
+ }
44
+ else {
45
+ io.err(`FAIL ${failure}`);
46
+ failed = true;
47
+ }
48
+ }
49
+ return failed ? 1 : 0;
50
+ }