@gebit/stax-cli 0.0.0-stage → 1.2.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.
package/README.md CHANGED
@@ -1,3 +1,103 @@
1
- # Temporary Holding Version
1
+ # stax CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Scaffolds, extends and validates projects for the stax stack framework. Package [`@gebit/stax-cli`](https://www.npmjs.com/package/@gebit/stax-cli), binary `stax`. Requires Node.js 24 or later.
4
+
5
+ ```bash
6
+ npm install -g @gebit/stax-cli
7
+ ```
8
+
9
+ ## `stax init`
10
+
11
+ Generates a deploy wrapper and an empty stack list in a repository:
12
+
13
+ | File | Content |
14
+ |---|---|
15
+ | `.github/workflows/deploy.yml` | Manual `Deploy` workflow calling `a-wf-setup-ci.yml` and `a-wf-deploy-levels.yml` from `GEBITSolutions/stax@main` |
16
+ | `configs/default.yaml` | One commented `deployment` block listing every required deployment value with its GitHub variable (`deployment.project` live only when `--project` is given), `stacks: []`, commented examples and a `yaml-language-server` schema link for editor completion |
17
+
18
+ ```bash
19
+ stax init [directory] [--environment <github-environment>] [--project <name>] [--force]
20
+ ```
21
+
22
+ `stax init` needs no input and never prompts; both options are optional.
23
+
24
+ - `--environment`: default GitHub Environment preselected in the deploy form. Without it, the form has no preselection.
25
+ - `--project`: lowercase letters, digits and hyphens, starting with a letter. Saved as `deployment.project` in `configs/default.yaml`; without it, the GitHub variable `PROJECT` supplies the value.
26
+ - Deployment values are not asked for. The generated config lists all required ones in one block, each next to its GitHub variable. Set them at least as GitHub variables (repository or Environment); a value uncommented in the config overrides the variable.
27
+ - Existing files are never overwritten unless `--force` is given. Without it, nothing is written.
28
+
29
+ Nothing is deployed until `configs/default.yaml` has at least one stack; add one with `stax add`. Set the required Azure resource, DNS and state deployment values in YAML or the matching GitHub variables before deploying; see [deployment configuration](../docs/docs/configuration.md).
30
+
31
+ The generated caller includes `pages: write` and `id-token: write` for GitHub Pages stacks. Existing callers upgrading to the Pages-enabled framework must add `pages: write` to their existing workflow permissions so nested workflow validation succeeds. A Pages-only caller can use the setup workflow's `skip-azure-credentials-validation: true`; see the repository's dedicated `configs/stax-docs.yaml` and `.github/workflows/docs.yml` example.
32
+
33
+ ## `stax add`
34
+
35
+ Adds a stack to a deploy config in `configs/`:
36
+
37
+ ```bash
38
+ stax add [directory] [--config <name>] [--name <stack name>] [--type <type>] [--yes]
39
+ ```
40
+
41
+ - `--config`: `configs/<name>.yaml`, the name the Deploy workflow takes. Without it, the existing configs are offered. With `--yes`, `default` (or the only config) is used.
42
+ - `--name`: display name. The id is derived from it: lowercase letters and digits joined by dashes, plus six random digits, e.g. `Network Hub` → `network-hub-482913`. The id is only an identifier; nothing derives paths from it.
43
+ - `--type`: one of the stack types in the schema; offered as a list when missing.
44
+ - Fields the type requires are prompted for, with the schema example as default (`folder` defaults to the name's slug). `--yes` accepts the defaults.
45
+ - Every other field the type reads is added as a commented example with its description. Uncomment the ones you need.
46
+ - The stack is appended after the last stack; the rest of the file stays byte for byte. A stack that would make the config invalid (e.g. a second `github-pages-site-deploy` stack) is not written.
47
+ - Without a terminal, a missing value is an error.
48
+
49
+ The field list and examples come from the schema: each stack property lists the types that read it in `x-stax-types` (`"all"` for every type) and its example in `examples`.
50
+
51
+ ## `stax validate config`
52
+
53
+ Checks deploy configs against the schema in [`schema/deploy-config.schema.json`](../schema/deploy-config.schema.json) and against the rules the pipeline enforces.
54
+
55
+ ```bash
56
+ stax validate config # deploy configs directly in configs/
57
+ stax validate config -r # ... and in its subdirectories
58
+ stax validate config configs/prod.yaml
59
+ stax validate config other-dir -r --strict
60
+ ```
61
+
62
+ - `[path]` is a file or a directory; it defaults to `configs`. A named file is always validated. When scanning a directory, YAML files without `deployment`, `stacks`, `externalRepos` or `globals` (for example Helm values) are listed as skipped.
63
+ - Findings show `line:column`, severity and the field path, e.g. `stacks[1].type`.
64
+ - Exit code 1 when any file has errors; warnings only fail with `--strict`.
65
+ - `deployment` fields are optional in local validation because GitHub variables can supply them. Setup checks the required values after resolution. Unknown deployment keys fail validation because setup rejects them.
66
+
67
+ | Errors (the pipeline fails or silently skips the stack) | Warnings |
68
+ |---|---|
69
+ | Invalid YAML; wrong field types (e.g. `local_backend: "false"` instead of a boolean) | Fields the schema does not know (often typos such as `depend_on`) |
70
+ | Missing `id` or `type`; unknown `type`; more than one `github-pages-site-deploy` stack or `destroy` on it | `depends_on` or `stack.<id>.var.<key>` pointing to a stack in another config |
71
+ | Type-specific required fields: `folder` for `terraform`/`opentofu`/`function-build-deploy`, Packer `packer_directory`/`packer_version`, `s3-site-deploy` `location`, `script` `script`, `bizep` `template`, `function-build-deploy` `runtime` | `source_repo` alias not defined in this file (configs deployed together share `externalRepos`) |
72
+ | Packer paths that are absolute, contain `..`, backslashes, empty segments or control characters; non-exact `packer_version` | No stacks defined |
73
+ | Duplicate stack ids; malformed `stack.<id>.var.<key>` references | |
74
+ | Dependency cycles (including through `stack.<id>...` inputs); dependency chains deeper than 14 levels | |
75
+
76
+ ### `folder` is required
77
+
78
+ `terraform`, `opentofu` and `function-build-deploy` stacks must set `folder`: the stack directory below `stack_base_path` (default `terraform/stacks`) or below `functions/`. The pipeline no longer falls back to the stack id, and setup fails for a stack without `folder`. To migrate a stack that relied on the fallback, add `folder: <its id>`.
79
+
80
+ ## Development
81
+
82
+ ```bash
83
+ cd cli
84
+ npm ci
85
+ npm run typecheck
86
+ npm test # copies ../schema first
87
+ npm run build
88
+ npm run sync-schema && node src/cli.ts validate config ../path/to/configs # runs from source (Node 24 type stripping)
89
+ ```
90
+
91
+ ## Releasing
92
+
93
+ The CLI is released together with the reusable workflows, under the same version. [`release.yml`](../.github/workflows/release.yml) runs on every push to `main` and composes the `a-wf-release-*` phase workflows:
94
+
95
+ 1. `a-wf-release-version.yml` waits for approval and derives the next version from conventional commits.
96
+ 2. [`cli-pack.yml`](../.github/workflows/cli-pack.yml) sets the package version to that version, typechecks, tests, builds and packs the CLI.
97
+ 3. `a-wf-release-prepare.yml` commits the release changes, creates the tag and the pre-release, and attaches the packed tarball.
98
+ 4. `a-wf-release-approve.yml` waits for the second approval (`publish-release` environment).
99
+ 5. [`docs.yml`](../.github/workflows/docs.yml) deploys the documentation site; if it fails, nothing is published.
100
+ 6. `a-wf-release-publish.yml` publishes the release.
101
+ 7. [`cli-publish.yml`](../.github/workflows/cli-publish.yml) runs `npm publish` on the same tarball.
102
+
103
+ Publishing uses npm trusted publishing (OIDC): no npm token is stored, and npm attaches a provenance attestation. The `version` in `package.json` stays `0.0.0-development`; only published packages carry a real version.
package/dist/add.js ADDED
@@ -0,0 +1,147 @@
1
+ import { randomInt } from "node:crypto";
2
+ import { existsSync, readdirSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { isMap, isScalar, isSeq, parseDocument, stringify } from "yaml";
5
+ import { isRecord } from "./guards.js";
6
+ import { requiredStackFields, schema } from "./schema.js";
7
+ import { validateConfigText } from "./validate.js";
8
+ /** Item prefix for a new stacks list; matches the config written by stax init. */
9
+ const DEFAULT_ITEM_PREFIX = " - ";
10
+ /** The generated deploy workflow reads configs/<name>.yaml, so only .yaml files are selectable. */
11
+ export function listConfigs(configsDir) {
12
+ if (!existsSync(configsDir))
13
+ return [];
14
+ return readdirSync(configsDir, { withFileTypes: true })
15
+ .filter((entry) => entry.isFile() && entry.name.endsWith(".yaml"))
16
+ .map((entry) => ({ name: entry.name.slice(0, -".yaml".length), path: join(configsDir, entry.name) }))
17
+ .sort((a, b) => a.name.localeCompare(b.name));
18
+ }
19
+ /** Lowercase letters and digits joined by single dashes; accents are dropped, everything else separates. */
20
+ export function slugify(name) {
21
+ return name
22
+ .normalize("NFKD")
23
+ .replace(/[\u0300-\u036f]/g, "")
24
+ .toLowerCase()
25
+ .replace(/[^a-z0-9]+/g, "-")
26
+ .replace(/^-+|-+$/g, "");
27
+ }
28
+ /** `<slug>-<6 random digits>`, redrawn while the id is taken. */
29
+ export function generateStackId(slug, taken, random = () => randomInt(1_000_000)) {
30
+ for (let attempt = 0; attempt < 100; attempt += 1) {
31
+ const id = `${slug}-${String(random()).padStart(6, "0")}`;
32
+ if (!taken.has(id))
33
+ return id;
34
+ }
35
+ throw new Error(`no free stack id for "${slug}" after 100 attempts`);
36
+ }
37
+ /**
38
+ * The stack as YAML lines without list prefix: id, name, type and the required fields, then every other
39
+ * field the schema offers for the type as a commented example with its description.
40
+ */
41
+ export function renderStackLines(id, stack) {
42
+ const active = stringify({ id, name: stack.name, type: stack.type, ...stack.values }).trimEnd().split("\n");
43
+ const skipped = new Set(["id", "name", "type", ...Object.keys(stack.values)]);
44
+ const examples = Object.entries(schema.$defs.stack.properties)
45
+ .filter(([field, definition]) => {
46
+ const types = definition["x-stax-types"];
47
+ return !skipped.has(field) && (types === "all" || (types?.includes(stack.type) ?? false));
48
+ })
49
+ .map(([field, definition]) => ({
50
+ lines: stringify({ [field]: definition.examples?.[0] }).trimEnd().split("\n").map((line) => `# ${line}`),
51
+ description: definition.description,
52
+ }));
53
+ const width = Math.max(...examples.map(({ lines }) => lines[0]?.length ?? 0));
54
+ const commented = examples.flatMap(({ lines: [first = "", ...rest], description }) => [
55
+ description ? `${first.padEnd(width)} # ${description}` : first,
56
+ ...rest,
57
+ ]);
58
+ return [...active, ...commented];
59
+ }
60
+ /** Start of the line after the one containing `pos`; `pos` itself when it already starts a line. */
61
+ function lineStartAfter(text, pos) {
62
+ if (pos === 0 || text[pos - 1] === "\n")
63
+ return pos;
64
+ const newline = text.indexOf("\n", pos);
65
+ return newline === -1 ? text.length : newline + 1;
66
+ }
67
+ /** Where a new stack goes: after the last stack, keeping the rest of the file byte for byte. */
68
+ function findInsertionPoint(text) {
69
+ const doc = parseDocument(text);
70
+ const [error] = doc.errors;
71
+ if (error)
72
+ throw new Error(`invalid YAML: ${error.message.split("\n")[0]} (see stax validate config)`);
73
+ const data = doc.toJS();
74
+ const stacks = isRecord(data) && Array.isArray(data.stacks) ? data.stacks : [];
75
+ const takenIds = new Set(stacks.flatMap((stack) => (isRecord(stack) && typeof stack.id === "string" ? [stack.id] : [])));
76
+ const root = doc.contents;
77
+ if (root !== null && !isMap(root))
78
+ throw new Error("not a deploy config: the document must be a mapping");
79
+ const pair = root?.items.find((item) => isScalar(item.key) && item.key.value === "stacks");
80
+ if (!pair || !isScalar(pair.key)) {
81
+ const updated = `${text}${text === "" || text.endsWith("\n") ? "" : "\n"}stacks:\n`;
82
+ return { text: updated, at: updated.length, prefix: DEFAULT_ITEM_PREFIX, takenIds };
83
+ }
84
+ // Parsed nodes always carry source ranges.
85
+ const keyEnd = pair.key.range[1];
86
+ const value = pair.value;
87
+ if (value === null || (isScalar(value) && value.value === null)) {
88
+ return { text, at: lineStartAfter(text, keyEnd), prefix: DEFAULT_ITEM_PREFIX, takenIds };
89
+ }
90
+ if (!isSeq(value))
91
+ throw new Error("stacks must be a list");
92
+ const [start, end] = value.range;
93
+ if (value.flow) {
94
+ if (value.items.length > 0)
95
+ throw new Error("stacks is a [...] list with entries; rewrite it as a block list first");
96
+ let cut = start;
97
+ while (cut > 0 && text[cut - 1] === " ")
98
+ cut -= 1;
99
+ const updated = text.slice(0, cut) + text.slice(end);
100
+ return { text: updated, at: lineStartAfter(updated, cut), prefix: DEFAULT_ITEM_PREFIX, takenIds };
101
+ }
102
+ const last = value.items.at(-1);
103
+ if (!last || !("range" in last) || !last.range)
104
+ throw new Error("stacks list without entries");
105
+ const itemStart = last.range[0];
106
+ const linePrefix = text.slice(text.lastIndexOf("\n", itemStart - 1) + 1, itemStart);
107
+ const prefix = /^ *- +$/.test(linePrefix) ? linePrefix : DEFAULT_ITEM_PREFIX;
108
+ // Comment lines indented into the last stack (e.g. its commented example fields) stay with it.
109
+ let at = lineStartAfter(text, last.range[1]);
110
+ while (at < text.length) {
111
+ const newline = text.indexOf("\n", at);
112
+ const next = newline === -1 ? text.length : newline + 1;
113
+ const indent = /^( *)#/.exec(text.slice(at, next));
114
+ if ((indent?.[1]?.length ?? -1) < prefix.length)
115
+ break;
116
+ at = next;
117
+ }
118
+ return { text, at, prefix, takenIds };
119
+ }
120
+ /**
121
+ * Appends a stack to a deploy config. Fails when the new stack has a validation error, so a written
122
+ * config never gains one.
123
+ */
124
+ export function addStackToConfig(text, stack, random) {
125
+ const slug = slugify(stack.name);
126
+ if (slug === "")
127
+ throw new Error(`stack name "${stack.name}" needs at least one letter or digit`);
128
+ const missing = requiredStackFields(stack.type).filter((field) => !(field in stack.values));
129
+ if (missing.length > 0)
130
+ throw new Error(`a ${stack.type} stack needs ${missing.join(", ")}`);
131
+ const point = findInsertionPoint(text);
132
+ const id = generateStackId(slug, point.takenIds, random);
133
+ const indent = " ".repeat(point.prefix.length);
134
+ const block = renderStackLines(id, stack)
135
+ .map((line, index) => `${index === 0 ? point.prefix : indent}${line}\n`)
136
+ .join("");
137
+ const lead = point.at === point.text.length && point.text !== "" && !point.text.endsWith("\n") ? "\n" : "";
138
+ const before = point.text.slice(0, point.at) + lead;
139
+ const updated = before + block + point.text.slice(point.at);
140
+ const firstLine = before.split("\n").length;
141
+ const lastLine = firstLine + block.split("\n").length - 2;
142
+ const introduced = validateConfigText(updated).filter((finding) => finding.severity === "error" && finding.line >= firstLine && finding.line <= lastLine);
143
+ if (introduced.length > 0) {
144
+ throw new Error(`the new stack would be invalid:\n${introduced.map((finding) => ` ${finding.message}`).join("\n")}`);
145
+ }
146
+ return { id, text: updated };
147
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,187 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { join, relative, resolve } from "node:path";
5
+ import { input, select } from "@inquirer/prompts";
6
+ import { Command } from "commander";
7
+ import { addStackToConfig, listConfigs, slugify } from "./add.js";
8
+ import { schema, STACK_TYPES, requiredStackFields, stackFieldProblem } from "./schema.js";
9
+ import { DEPLOY_CONFIG_PATH, renderProject, validateEnvironment, validateProject } from "./templates.js";
10
+ import { collectConfigFiles, isDeployConfigText, validateConfigText } from "./validate.js";
11
+ import { writeProject } from "./write.js";
12
+ const { version } = createRequire(import.meta.url)("../package.json");
13
+ /**
14
+ * Command-line values win; missing values are prompted for on a terminal and are an
15
+ * error otherwise, so scripted runs never hang on a prompt.
16
+ */
17
+ async function resolveValue(question) {
18
+ const { given, validate, fallback } = question;
19
+ if (given !== undefined) {
20
+ const error = validate(given);
21
+ if (error)
22
+ throw new Error(error);
23
+ return given;
24
+ }
25
+ if (question.acceptFallback && fallback !== undefined)
26
+ return fallback;
27
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
28
+ throw new Error(`${question.missing} (no terminal to prompt on)`);
29
+ }
30
+ if (question.choices)
31
+ return select({ message: question.message, choices: question.choices, default: fallback });
32
+ return input({ message: question.message, default: fallback, validate: (value) => validate(value) ?? true });
33
+ }
34
+ const program = new Command()
35
+ .name("stax")
36
+ .description("Scaffold, extend and validate projects for the stax stack framework")
37
+ .version(version);
38
+ program
39
+ .command("init")
40
+ .description("Generate the deploy workflow and default deploy config in a repository")
41
+ .argument("[directory]", "repository root to write into", ".")
42
+ .option("-p, --project <name>", "optional deployment.project; otherwise the GitHub variable PROJECT supplies it")
43
+ .option("-e, --environment <name>", "optional default GitHub Environment of the deploy form")
44
+ .option("-f, --force", "overwrite existing files", false)
45
+ .action(async (directory, flags) => {
46
+ const problems = [
47
+ flags.project === undefined ? undefined : validateProject(flags.project),
48
+ flags.environment === undefined ? undefined : validateEnvironment(flags.environment),
49
+ ].filter((problem) => problem !== undefined);
50
+ if (problems.length > 0)
51
+ throw new Error(problems.join("\n"));
52
+ const { environment } = flags;
53
+ const root = resolve(directory);
54
+ const files = renderProject({ project: flags.project, environment });
55
+ await writeProject(root, files, flags.force);
56
+ for (const file of files)
57
+ console.log(`created ${file.path}`);
58
+ console.log(`
59
+ Next steps:
60
+ 1. Create the GitHub Environment${environment === undefined ? "(s) you deploy to" : ` "${environment}"`}. Set the required deployment values listed in
61
+ ${DEPLOY_CONFIG_PATH} as GitHub variables there or on the repository, plus the secrets your stacks need.
62
+ 2. Add stacks with: stax add
63
+ 3. Run the Deploy workflow with dry-run enabled.`);
64
+ });
65
+ program
66
+ .command("add")
67
+ .description("Add a stack to a deploy config; the other fields its type supports are added as commented examples")
68
+ .argument("[directory]", "repository root containing configs/", ".")
69
+ .option("-c, --config <name>", "deploy config: configs/<name>.yaml")
70
+ .option("-n, --name <name>", "stack name; the id is derived from it")
71
+ .option("-t, --type <type>", "stack type")
72
+ .option("-y, --yes", "accept the example values of required fields instead of prompting", false)
73
+ .action(async (directory, flags) => {
74
+ const configsDir = join(directory, "configs");
75
+ const configs = listConfigs(resolve(configsDir));
76
+ if (configs.length === 0)
77
+ throw new Error(`no deploy configs (.yaml) in ${configsDir}; run stax init first`);
78
+ const names = configs.map((config) => config.name);
79
+ const configName = await resolveValue({
80
+ given: flags.config,
81
+ message: "Deploy config:",
82
+ missing: "missing required option --config",
83
+ validate: (value) => names.includes(value) ? undefined : `unknown deploy config "${value}"; ${configsDir} has: ${names.join(", ")}`,
84
+ choices: names,
85
+ fallback: names.includes("default") ? "default" : names.length === 1 ? names[0] : undefined,
86
+ acceptFallback: flags.yes,
87
+ });
88
+ const name = await resolveValue({
89
+ given: flags.name,
90
+ message: "Stack name:",
91
+ missing: "missing required option --name",
92
+ validate: (value) => (slugify(value) === "" ? "the stack name needs at least one letter or digit" : undefined),
93
+ });
94
+ const type = await resolveValue({
95
+ given: flags.type,
96
+ message: "Stack type:",
97
+ missing: "missing required option --type",
98
+ validate: (value) => STACK_TYPES.includes(value) ? undefined : `unknown stack type "${value}"; expected one of: ${STACK_TYPES.join(", ")}`,
99
+ choices: STACK_TYPES,
100
+ });
101
+ const values = {};
102
+ for (const field of requiredStackFields(type)) {
103
+ const definition = schema.$defs.stack.properties[field];
104
+ const example = field === "folder" ? slugify(name) : definition?.examples?.[0];
105
+ const fallback = typeof example === "string" ? example : undefined;
106
+ values[field] = await resolveValue({
107
+ given: undefined,
108
+ message: definition?.description ? `${field} (${definition.description.replace(/\.$/, "")}):` : `${field}:`,
109
+ missing: `missing ${field} for the ${type} stack; pass --yes to accept "${fallback}"`,
110
+ validate: (value) => {
111
+ const problem = stackFieldProblem(field, value);
112
+ return problem && `${field}: ${problem}`;
113
+ },
114
+ choices: definition?.enum,
115
+ fallback,
116
+ acceptFallback: flags.yes,
117
+ });
118
+ }
119
+ const config = configs.find((candidate) => candidate.name === configName);
120
+ if (!config)
121
+ throw new Error(`unknown deploy config "${configName}"`);
122
+ const { id, text } = addStackToConfig(readFileSync(config.path, "utf8"), { name, type, values });
123
+ writeFileSync(config.path, text);
124
+ console.log(`added stack "${id}" (${type}) to ${join(configsDir, `${configName}.yaml`)}
125
+ Uncomment the example fields you need, then check the file with: stax validate config`);
126
+ });
127
+ program
128
+ .command("validate")
129
+ .description("Validate project files against the stax framework")
130
+ .command("config")
131
+ .description("Validate deploy configs: one file, or the deploy configs among the .yaml/.yml files in a directory (default: configs)")
132
+ .argument("[path]", "deploy config file or directory", "configs")
133
+ .option("-r, --recursive", "include subdirectories", false)
134
+ .option("--strict", "fail on warnings too", false)
135
+ .action((target, flags) => {
136
+ if (!existsSync(target))
137
+ throw new Error(`${target} does not exist`);
138
+ // A named file is always validated; directory scans skip other YAML (e.g. Helm values) next to the configs.
139
+ const scanning = statSync(target).isDirectory();
140
+ const files = collectConfigFiles(target, flags.recursive);
141
+ if (files.length === 0) {
142
+ throw new Error(`no .yaml/.yml files in ${target}${flags.recursive ? "" : " (use -r to include subdirectories)"}`);
143
+ }
144
+ let checked = 0;
145
+ let errors = 0;
146
+ let warnings = 0;
147
+ for (const file of files) {
148
+ const fromCwd = relative(process.cwd(), file);
149
+ const shown = fromCwd && !fromCwd.startsWith("..") ? fromCwd : file;
150
+ const text = readFileSync(file, "utf8");
151
+ if (scanning && !isDeployConfigText(text)) {
152
+ console.log(`${shown}: skipped (no stacks, externalRepos or globals)`);
153
+ continue;
154
+ }
155
+ checked += 1;
156
+ const findings = validateConfigText(text);
157
+ if (findings.length === 0) {
158
+ console.log(`${shown}: ok`);
159
+ continue;
160
+ }
161
+ console.log(shown);
162
+ for (const finding of findings) {
163
+ if (finding.severity === "error")
164
+ errors += 1;
165
+ else
166
+ warnings += 1;
167
+ console.log(` ${`${finding.line}:${finding.column}`.padEnd(8)}${finding.severity.padEnd(9)}${finding.message}`);
168
+ }
169
+ }
170
+ if (checked === 0)
171
+ throw new Error(`no deploy configs in ${target}`);
172
+ const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
173
+ const skipped = files.length - checked;
174
+ console.log(`\n${plural(checked, "file")} checked${skipped > 0 ? `, ${skipped} skipped` : ""}: ${plural(errors, "error")}, ${plural(warnings, "warning")}`);
175
+ if (errors > 0 || (flags.strict && warnings > 0))
176
+ process.exitCode = 1;
177
+ });
178
+ try {
179
+ await program.parseAsync();
180
+ }
181
+ catch (error) {
182
+ if (error instanceof Error && error.name === "ExitPromptError")
183
+ process.exit(130);
184
+ const message = error instanceof Error ? error.message : String(error);
185
+ console.error(`stax: ${message}`);
186
+ process.exit(1);
187
+ }
package/dist/guards.js ADDED
@@ -0,0 +1,4 @@
1
+ /** Narrows parsed YAML/JSON to a mapping; values stay unknown. */
2
+ export function isRecord(value) {
3
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4
+ }
package/dist/schema.js ADDED
@@ -0,0 +1,33 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { Ajv2020 } from "ajv/dist/2020.js";
3
+ export const schema = JSON.parse(readFileSync(new URL("../schema/deploy-config.schema.json", import.meta.url), "utf8"));
4
+ export const ajv = new Ajv2020({ allErrors: true, allowUnionTypes: true });
5
+ ajv.addKeyword({
6
+ keyword: "x-stax-types",
7
+ metaSchema: { anyOf: [{ const: "all" }, { type: "array", items: { type: "string" } }] },
8
+ });
9
+ export const validateDeployConfig = ajv.compile(schema);
10
+ export const STACK_TYPES = schema.$defs.stack.properties.type?.enum ?? [];
11
+ /** Fields the schema requires for `type`, besides id and type, in schema order. */
12
+ export function requiredStackFields(type) {
13
+ return schema.$defs.stack.allOf
14
+ .filter(({ if: condition }) => {
15
+ const { const: single, enum: anyOf } = condition.properties.type;
16
+ return single === type || (anyOf?.includes(type) ?? false);
17
+ })
18
+ .flatMap((rule) => rule.then.required);
19
+ }
20
+ /** Validates one value against a stack property's schema; returns the first problem. */
21
+ export function stackFieldProblem(field, value) {
22
+ const validate = ajv.getSchema(`${schema.$id}#/$defs/stack/properties/${field}`);
23
+ if (!validate)
24
+ throw new Error(`unknown stack field ${field}`);
25
+ if (validate(value))
26
+ return undefined;
27
+ const [error] = validate.errors ?? [];
28
+ const allowed = error?.keyword === "enum" ? error.params.allowedValues : undefined;
29
+ if (Array.isArray(allowed))
30
+ return `must be one of: ${allowed.join(", ")}`;
31
+ const [example] = schema.$defs.stack.properties[field]?.examples ?? [];
32
+ return `${error?.message ?? "invalid value"}${typeof example === "string" ? ` (e.g. ${example})` : ""}`;
33
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Reusable workflows the generated wrapper calls. Unpinned until stax publishes releases.
3
+ */
4
+ export const WORKFLOW_REPOSITORY = "GEBITSolutions/stax";
5
+ export const WORKFLOW_REF = "main";
6
+ export const DEPLOY_WORKFLOW_PATH = ".github/workflows/deploy.yml";
7
+ export const DEPLOY_CONFIG_PATH = "configs/default.yaml";
8
+ export const DEPLOY_CONFIG_SCHEMA_URL = "https://raw.githubusercontent.com/GEBITSolutions/stax/main/schema/deploy-config.schema.json";
9
+ const PROJECT_PATTERN = /^[a-z][a-z0-9-]*$/;
10
+ const ENVIRONMENT_PATTERN = /^[A-Za-z0-9._-]+$/;
11
+ /** Returns an error message, or undefined when the project name is valid. */
12
+ export function validateProject(value) {
13
+ if (PROJECT_PATTERN.test(value))
14
+ return undefined;
15
+ return `invalid project "${value}": use lowercase letters, digits and hyphens, starting with a letter`;
16
+ }
17
+ /** Returns an error message, or undefined when the environment name is valid. */
18
+ export function validateEnvironment(value) {
19
+ if (ENVIRONMENT_PATTERN.test(value))
20
+ return undefined;
21
+ return `invalid environment "${value}": use letters, digits, ".", "_" and "-"`;
22
+ }
23
+ /** Deployment values setup requires, with an example value; the GitHub variable is the uppercased field name. */
24
+ const REQUIRED_DEPLOYMENT_VALUES = {
25
+ "required": {
26
+ project: "my-project",
27
+ customer_id: "default",
28
+ stage: "dev",
29
+ cloud: "azure",
30
+ default_location: "northeurope",
31
+ public_cloud_flag: "true",
32
+ },
33
+ "required for azure": {
34
+ resource_group_name: "my-resource-group",
35
+ dns_zone_name: "example.com",
36
+ dns_zone_resource_group_name: "my-dns-resource-group",
37
+ state_storage_account_name: "mystatestorage",
38
+ state_container_name: "tfstate",
39
+ state_resource_group_name: "my-state-resource-group",
40
+ },
41
+ "required for aws": {
42
+ state_bucket_name: "my-state-bucket",
43
+ state_region: "eu-north-1",
44
+ },
45
+ };
46
+ /** Every line stays valid YAML when the whole block is uncommented at once. */
47
+ function renderDeploymentBlock(project) {
48
+ const rows = Object.entries(REQUIRED_DEPLOYMENT_VALUES).flatMap(([requirement, values]) => Object.entries(values).map(([field, example]) => {
49
+ const live = field === "project" && project !== undefined;
50
+ return {
51
+ prefix: live ? " " : " # ",
52
+ entry: live ? `project: "${project}"` : `${field}: ${example}`,
53
+ note: `${requirement}; GitHub variable ${field.toUpperCase()}`,
54
+ };
55
+ }));
56
+ const width = Math.max(...rows.map(({ prefix, entry }) => prefix.length + entry.length));
57
+ const lines = rows.map(({ prefix, entry, note }) => `${(prefix + entry).padEnd(width)} # ${note}`);
58
+ return [project === undefined ? "# deployment:" : "deployment:", ...lines].join("\n");
59
+ }
60
+ function renderDeployConfig({ project, environment }) {
61
+ return `# yaml-language-server: $schema=${DEPLOY_CONFIG_SCHEMA_URL}
62
+ # Deploy configuration read by the Deploy workflow (deploy-config input "default").
63
+ # Nothing is deployed until at least one stack is defined. Add one with: stax add
64
+ # Check the file with: stax validate config
65
+
66
+ # Deployment values: setup needs every value marked "required", plus those required for your cloud.
67
+ # Set each one at least as the GitHub variable named next to it, on the repository or the
68
+ # ${environment === undefined ? "GitHub Environment you deploy to" : `"${environment}" Environment`}. A value uncommented here overrides that variable for this config.
69
+ # Setup fails while a required value is missing.
70
+ ${renderDeploymentBlock(project)}
71
+
72
+ # Optional: repositories providing stack sources or config files.
73
+ # externalRepos:
74
+ # shared:
75
+ # - repoURL: "github.com/<org>/<repo>.git"
76
+ # targetRevision: main
77
+ # token: <SECRET_NAME> # GitHub secret holding a read token
78
+
79
+ # Optional: values readable by stacks as global.config.var.<key>.
80
+ # globals:
81
+ # owner: platform-team
82
+
83
+ stacks: []
84
+ # Example OpenTofu stack in terraform/stacks/network:
85
+ # - id: "network"
86
+ # name: "Network"
87
+ # type: "opentofu"
88
+ # folder: "network" # stack directory below stack_base_path
89
+ # opentofu_version: "1.8.1"
90
+ # location: "westeurope"
91
+ # stack_base_path: "terraform/stacks"
92
+ # depends_on: [] # stack ids deployed before this one
93
+ # input:
94
+ # - global.pipeline.var.project
95
+ # - global.pipeline.var.stage
96
+ `;
97
+ }
98
+ export function renderProject(values) {
99
+ const { environment } = values;
100
+ const workflowPrefix = `${WORKFLOW_REPOSITORY}/.github/workflows`;
101
+ const deployWorkflow = `name: Deploy
102
+
103
+ on:
104
+ workflow_dispatch:
105
+ inputs:
106
+ environment:
107
+ description: GitHub Environment to deploy to
108
+ type: environment
109
+ required: true
110
+ ${environment === undefined ? "" : ` default: "${environment}"\n`}\
111
+ stack-filter:
112
+ description: One or more stack ids, comma separated; empty selects all stacks
113
+ type: string
114
+ required: false
115
+ default: ""
116
+ deploy-config:
117
+ description: Deploy config in configs/ (file name without .yaml)
118
+ type: string
119
+ required: false
120
+ default: default
121
+ dry-run:
122
+ description: Dry run (plan only, no apply)
123
+ type: boolean
124
+ default: true
125
+ destroy:
126
+ description: Destroy infrastructure
127
+ type: boolean
128
+ default: false
129
+
130
+ permissions:
131
+ actions: read
132
+ contents: read
133
+ id-token: write
134
+ packages: write
135
+ pages: write
136
+
137
+ concurrency:
138
+ group: \${{ github.workflow }}-\${{ inputs.dry-run && github.sha || inputs.environment }}
139
+ cancel-in-progress: false
140
+
141
+ jobs:
142
+ setup:
143
+ name: Setup CI/CD
144
+ uses: ${workflowPrefix}/a-wf-setup-ci.yml@${WORKFLOW_REF}
145
+ secrets: inherit
146
+ with:
147
+ environment: \${{ inputs.environment }}
148
+ stack_filter: \${{ inputs.stack-filter }}
149
+ dry-run: \${{ inputs.dry-run }}
150
+ destroy: \${{ inputs.destroy }}
151
+ runs-on: \${{ vars.RUNNER || 'ubuntu-latest' }}
152
+ release_config_filepath: configs/\${{ inputs.deploy-config }}.yaml
153
+
154
+ deploy-levels:
155
+ name: Deploy Levels
156
+ needs: setup
157
+ uses: ${workflowPrefix}/a-wf-deploy-levels.yml@${WORKFLOW_REF}
158
+ secrets: inherit
159
+ with:
160
+ ci_config: \${{ needs.setup.outputs.ci-config }}
161
+ env: \${{ needs.setup.outputs.env }}
162
+ default_location: \${{ needs.setup.outputs.default-location }}
163
+ external_repos: \${{ needs.setup.outputs.external-repos }}
164
+ `;
165
+ return [
166
+ { path: DEPLOY_WORKFLOW_PATH, content: deployWorkflow },
167
+ { path: DEPLOY_CONFIG_PATH, content: renderDeployConfig(values) },
168
+ ];
169
+ }
@@ -0,0 +1,301 @@
1
+ import { readdirSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { isMap, isScalar, LineCounter, parseDocument } from "yaml";
4
+ import { isRecord } from "./guards.js";
5
+ import { schema, validateDeployConfig as validateSchema } from "./schema.js";
6
+ /** a-wf-deploy-levels runs dependency levels l0 to l13. */
7
+ const MAX_LEVELS = 14;
8
+ const KNOWN_KEYS = {
9
+ root: Object.keys(schema.properties),
10
+ stack: Object.keys(schema.$defs.stack.properties),
11
+ externalRepo: Object.keys(schema.$defs.externalRepo.properties),
12
+ };
13
+ /** Renders a document path the way users read it: stacks[1].depends_on[0]. */
14
+ function formatPath(path) {
15
+ return path
16
+ .map((segment, index) => (typeof segment === "number" ? `[${segment}]` : index === 0 ? segment : `.${segment}`))
17
+ .join("");
18
+ }
19
+ class Reporter {
20
+ findings = [];
21
+ seen = new Set();
22
+ doc;
23
+ lineCounter;
24
+ constructor(doc, lineCounter) {
25
+ this.doc = doc;
26
+ this.lineCounter = lineCounter;
27
+ }
28
+ add(severity, path, message) {
29
+ const text = path.length > 0 ? `${formatPath(path)}: ${message}` : message;
30
+ const dedupeKey = `${severity}|${text}`;
31
+ if (this.seen.has(dedupeKey))
32
+ return;
33
+ this.seen.add(dedupeKey);
34
+ const { line, col } = this.position(path);
35
+ this.findings.push({ severity, message: text, line, column: col });
36
+ }
37
+ /**
38
+ * Position of a field's key (paths ending in a field name) or of a list item, falling back to the
39
+ * nearest existing ancestor.
40
+ */
41
+ position(path) {
42
+ if (typeof path.at(-1) === "string") {
43
+ const parent = this.doc.getIn(path.slice(0, -1), true);
44
+ if (isMap(parent)) {
45
+ const pair = parent.items.find((item) => isScalar(item.key) && item.key.value === path.at(-1));
46
+ if (pair && isScalar(pair.key) && pair.key.range)
47
+ return this.lineCounter.linePos(pair.key.range[0]);
48
+ }
49
+ }
50
+ for (let depth = path.length; depth >= 0; depth -= 1) {
51
+ const node = depth === 0 ? this.doc.contents : this.doc.getIn(path.slice(0, depth), true);
52
+ if (node && typeof node === "object" && "range" in node && Array.isArray(node.range)) {
53
+ return this.lineCounter.linePos(node.range[0]);
54
+ }
55
+ }
56
+ return { line: 1, col: 1 };
57
+ }
58
+ }
59
+ function schemaMessage(error, path) {
60
+ switch (error.keyword) {
61
+ case "required":
62
+ return `missing required field "${String(error.params.missingProperty)}"`;
63
+ case "enum": {
64
+ const allowed = error.params.allowedValues.join(", ");
65
+ return path.at(-1) === "type" ? `unknown stack type; expected one of: ${allowed}` : `must be one of: ${allowed}`;
66
+ }
67
+ case "pattern":
68
+ return path.at(-1) === "packer_version"
69
+ ? "must be an exact numeric Major.Minor.Patch version"
70
+ : `must match ${String(error.params.pattern)}`;
71
+ default:
72
+ return error.message ?? error.keyword;
73
+ }
74
+ }
75
+ function checkSchema(data, report) {
76
+ if (validateSchema(data))
77
+ return;
78
+ for (const error of validateSchema.errors ?? []) {
79
+ // "if" errors only say a "then" branch failed; the branch's own error carries the detail.
80
+ if (error.keyword === "if")
81
+ continue;
82
+ const path = error.instancePath
83
+ .split("/")
84
+ .slice(1)
85
+ .map((segment) => (/^\d+$/.test(segment) ? Number(segment) : segment.replaceAll("~1", "/").replaceAll("~0", "~")));
86
+ report.add("error", path, schemaMessage(error, path));
87
+ }
88
+ }
89
+ function checkUnknownKeys(value, known, path, report) {
90
+ if (!isRecord(value))
91
+ return;
92
+ for (const key of Object.keys(value)) {
93
+ if (!known.includes(key))
94
+ report.add("warning", [...path, key], "unknown field");
95
+ }
96
+ }
97
+ /** Mirrors validateRelativePosixPath in gh-create-deploy-config (Packer paths). */
98
+ function packerPathProblem(value) {
99
+ if (/^[A-Za-z]:/.test(value) || value.startsWith("/"))
100
+ return "must be repository-relative";
101
+ if (/[\u0000-\u001f\u007f]/.test(value))
102
+ return "must not contain control characters";
103
+ if (value.includes("\\"))
104
+ return "must use POSIX separators";
105
+ const segments = value.split("/");
106
+ if (segments.includes(".."))
107
+ return 'must not contain a ".." segment';
108
+ if (segments.includes(""))
109
+ return "must not contain empty path segments";
110
+ return undefined;
111
+ }
112
+ /** Collects stack.<id>.var|secret.<key> references in an input value, like update_deploy_config. */
113
+ function collectStackReferences(value, path, out) {
114
+ if (typeof value === "string") {
115
+ if (value.startsWith("stack."))
116
+ out.push({ path, ref: value });
117
+ }
118
+ else if (Array.isArray(value)) {
119
+ value.forEach((item, index) => collectStackReferences(item, [...path, index], out));
120
+ }
121
+ else if (isRecord(value)) {
122
+ for (const [key, nested] of Object.entries(value))
123
+ collectStackReferences(nested, [...path, key], out);
124
+ }
125
+ }
126
+ function checkPipelineRules(data, report) {
127
+ const stacks = Array.isArray(data.stacks) ? data.stacks : [];
128
+ if (stacks.length === 0) {
129
+ report.add("warning", data.stacks === undefined ? [] : ["stacks"], "no stacks defined; nothing will be deployed");
130
+ return;
131
+ }
132
+ const aliases = isRecord(data.externalRepos) ? Object.keys(data.externalRepos) : [];
133
+ const firstIndexById = new Map();
134
+ stacks.forEach((stack, index) => {
135
+ if (!isRecord(stack) || typeof stack.id !== "string")
136
+ return;
137
+ if (firstIndexById.has(stack.id)) {
138
+ report.add("error", ["stacks", index, "id"], `duplicate stack id "${stack.id}"`);
139
+ }
140
+ else {
141
+ firstIndexById.set(stack.id, index);
142
+ }
143
+ });
144
+ const dependencies = new Map();
145
+ // Cross-config references are a normal multi-config pattern: report each referenced id once per file.
146
+ const externalDependsOn = new Map();
147
+ const externalReferences = new Map();
148
+ const noteExternal = (seen, id, path) => {
149
+ const entry = seen.get(id);
150
+ if (entry)
151
+ entry.count += 1;
152
+ else
153
+ seen.set(id, { path, count: 1 });
154
+ };
155
+ let pagesStackId;
156
+ stacks.forEach((stack, index) => {
157
+ if (!isRecord(stack) || typeof stack.id !== "string" || firstIndexById.get(stack.id) !== index)
158
+ return;
159
+ const deps = new Set();
160
+ dependencies.set(stack.id, deps);
161
+ // Pages stacks also accept a direct owner/repository (github-pages-config.mjs).
162
+ const directRepository = stack.type === "github-pages-site-deploy" && typeof stack.source_repo === "string" && stack.source_repo.includes("/");
163
+ if (typeof stack.source_repo === "string" && !directRepository && !aliases.includes(stack.source_repo)) {
164
+ // setup-ci merges externalRepos across all configs passed together, so the alias may live in another file.
165
+ const defined = aliases.length > 0 ? `this file defines: ${aliases.join(", ")}` : "this file defines no externalRepos";
166
+ report.add("warning", ["stacks", index, "source_repo"], `externalRepos alias "${stack.source_repo}" is not in this file (${defined}); unless another config deployed with this one defines it, the stack fails or uses the calling repository, depending on its type`);
167
+ }
168
+ if (stack.type === "packer") {
169
+ for (const field of ["packer_directory", "packer_template"]) {
170
+ const value = stack[field];
171
+ const problem = typeof value === "string" ? packerPathProblem(value) : undefined;
172
+ if (problem)
173
+ report.add("error", ["stacks", index, field], problem);
174
+ }
175
+ }
176
+ // Mirrors validateGitHubPagesConfig and github-pages-config.mjs.
177
+ if (stack.type === "github-pages-site-deploy") {
178
+ if (pagesStackId !== undefined) {
179
+ report.add("error", ["stacks", index, "type"], `more than one github-pages-site-deploy stack ("${pagesStackId}" and "${stack.id}")`);
180
+ }
181
+ pagesStackId ??= stack.id;
182
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(stack.id)) {
183
+ report.add("error", ["stacks", index, "id"], "a github-pages-site-deploy id may contain only letters, digits, dots, underscores and hyphens");
184
+ }
185
+ if (stack.destroy === true || stack.destroy === "true") {
186
+ report.add("error", ["stacks", index, "destroy"], "github-pages-site-deploy does not support destroy");
187
+ }
188
+ }
189
+ if (Array.isArray(stack.depends_on)) {
190
+ stack.depends_on.forEach((dependency, depIndex) => {
191
+ if (typeof dependency !== "string")
192
+ return;
193
+ if (firstIndexById.has(dependency)) {
194
+ deps.add(dependency);
195
+ }
196
+ else {
197
+ noteExternal(externalDependsOn, dependency, ["stacks", index, "depends_on", depIndex]);
198
+ }
199
+ });
200
+ }
201
+ const references = [];
202
+ collectStackReferences(stack.input, ["stacks", index, "input"], references);
203
+ for (const { path, ref } of references) {
204
+ const [, referencedId, kind, key] = ref.split(".");
205
+ if (ref.split(".").length !== 4 || (kind !== "var" && kind !== "secret") || !referencedId || !key) {
206
+ report.add("error", path, `invalid stack reference "${ref}"; expected stack.<id>.var.<key> or stack.<id>.secret.<key>`);
207
+ }
208
+ else if (firstIndexById.has(referencedId)) {
209
+ deps.add(referencedId);
210
+ }
211
+ else {
212
+ noteExternal(externalReferences, referencedId, path);
213
+ }
214
+ }
215
+ });
216
+ for (const [id, { path, count }] of externalDependsOn) {
217
+ const suffix = count === 1 ? "" : ` (${count} references)`;
218
+ report.add("warning", path, `"${id}" is not in this file${suffix}; the pipeline treats it as a dependency on another config and ignores it for ordering`);
219
+ }
220
+ for (const [id, { path, count }] of externalReferences) {
221
+ const suffix = count === 1 ? "" : ` (${count} references)`;
222
+ report.add("warning", path, `stack "${id}" is not in this file${suffix}; its values are read from stored outputs at runtime`);
223
+ }
224
+ // Level scheduling as in generate_layerdeployment: a stack runs one level after its last dependency.
225
+ const level = new Map();
226
+ let progressed = true;
227
+ while (progressed) {
228
+ progressed = false;
229
+ for (const [id, deps] of dependencies) {
230
+ if (level.has(id) || ![...deps].every((dep) => level.has(dep)))
231
+ continue;
232
+ level.set(id, deps.size === 0 ? 0 : Math.max(...[...deps].map((dep) => level.get(dep) ?? 0)) + 1);
233
+ progressed = true;
234
+ }
235
+ }
236
+ for (const [id, deps] of dependencies) {
237
+ const index = firstIndexById.get(id) ?? 0;
238
+ const stackLevel = level.get(id);
239
+ if (stackLevel === undefined) {
240
+ const unresolved = [...deps].filter((dep) => !level.has(dep));
241
+ report.add("error", ["stacks", index, "id"], `"${id}" cannot be scheduled: dependency cycle through ${unresolved.join(", ")}`);
242
+ }
243
+ else if (stackLevel >= MAX_LEVELS) {
244
+ report.add("error", ["stacks", index, "id"], `"${id}" needs dependency level l${stackLevel}; the pipeline runs at most ${MAX_LEVELS} levels (l0-l${MAX_LEVELS - 1})`);
245
+ }
246
+ }
247
+ }
248
+ /** Validates one deploy config. Findings are sorted by position. */
249
+ export function validateConfigText(text) {
250
+ const lineCounter = new LineCounter();
251
+ const doc = parseDocument(text, { lineCounter, prettyErrors: false });
252
+ const report = new Reporter(doc, lineCounter);
253
+ if (doc.errors.length > 0) {
254
+ return doc.errors.map((error) => {
255
+ const { line, col } = lineCounter.linePos(error.pos[0]);
256
+ return { severity: "error", message: `invalid YAML: ${error.message.split("\n")[0]}`, line, column: col };
257
+ });
258
+ }
259
+ const data = doc.toJS();
260
+ if (!isRecord(data)) {
261
+ report.add("error", [], "a deploy config must be a mapping with a stacks list");
262
+ return report.findings;
263
+ }
264
+ checkSchema(data, report);
265
+ checkUnknownKeys(data, KNOWN_KEYS.root, [], report);
266
+ if (isRecord(data.externalRepos)) {
267
+ for (const [alias, entries] of Object.entries(data.externalRepos)) {
268
+ if (Array.isArray(entries)) {
269
+ entries.forEach((entry, index) => checkUnknownKeys(entry, KNOWN_KEYS.externalRepo, ["externalRepos", alias, index], report));
270
+ }
271
+ }
272
+ }
273
+ if (Array.isArray(data.stacks)) {
274
+ data.stacks.forEach((stack, index) => checkUnknownKeys(stack, KNOWN_KEYS.stack, ["stacks", index], report));
275
+ }
276
+ checkPipelineRules(data, report);
277
+ return report.findings.sort((a, b) => a.line - b.line || a.column - b.column);
278
+ }
279
+ /**
280
+ * Whether a YAML file in a scanned directory is a deploy config: a mapping with at least one of the
281
+ * deploy-config top-level keys. Files that fail to parse count as deploy configs so the error is shown.
282
+ */
283
+ export function isDeployConfigText(text) {
284
+ const doc = parseDocument(text);
285
+ if (doc.errors.length > 0)
286
+ return true;
287
+ const data = doc.toJS();
288
+ return isRecord(data) && KNOWN_KEYS.root.some((key) => key in data);
289
+ }
290
+ /**
291
+ * YAML files to validate: `target` itself when it is a file, otherwise the .yaml/.yml files in the
292
+ * directory (and its subdirectories when `recursive`), sorted by path.
293
+ */
294
+ export function collectConfigFiles(target, recursive) {
295
+ if (statSync(target).isFile())
296
+ return [target];
297
+ return readdirSync(target, { recursive, withFileTypes: true })
298
+ .filter((entry) => entry.isFile() && /\.ya?ml$/.test(entry.name))
299
+ .map((entry) => join(entry.parentPath, entry.name))
300
+ .sort();
301
+ }
package/dist/write.js ADDED
@@ -0,0 +1,21 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdir, writeFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ /**
5
+ * Writes all files below `root`. Without `force`, nothing is written when any
6
+ * target already exists.
7
+ */
8
+ export async function writeProject(root, files, force) {
9
+ if (!force) {
10
+ const existing = files.filter((file) => existsSync(join(root, file.path))).map((file) => file.path);
11
+ if (existing.length > 0) {
12
+ throw new Error(`refusing to overwrite existing files (use --force): ${existing.join(", ")}`);
13
+ }
14
+ }
15
+ for (const file of files) {
16
+ const target = join(root, file.path);
17
+ await mkdir(dirname(target), { recursive: true });
18
+ // "wx" still guards against a file appearing between the check and the write.
19
+ await writeFile(target, file.content, { flag: force ? "w" : "wx" });
20
+ }
21
+ }
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@gebit/stax-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.2.0",
4
+ "description": "Scaffold, extend and validate projects for the stax stack framework",
5
+ "type": "module",
6
+ "license": "GPL-3.0-only",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/GEBITSolutions/stax.git",
10
+ "directory": "cli"
11
+ },
12
+ "homepage": "https://github.com/GEBITSolutions/stax/tree/main/cli#readme",
13
+ "bugs": "https://github.com/GEBITSolutions/stax/issues",
14
+ "keywords": [
15
+ "cli",
16
+ "github-actions",
17
+ "deployment",
18
+ "opentofu",
19
+ "terraform"
20
+ ],
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "bin": {
25
+ "stax": "dist/cli.js"
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "schema"
30
+ ],
31
+ "engines": {
32
+ "node": ">=24"
33
+ },
34
+ "scripts": {
35
+ "build": "tsc -p tsconfig.build.json",
36
+ "typecheck": "tsc --noEmit",
37
+ "test": "vitest run",
38
+ "sync-schema": "node -e \"require('node:fs').cpSync('../schema', 'schema', { recursive: true })\"",
39
+ "prebuild": "npm run sync-schema",
40
+ "pretest": "npm run sync-schema"
41
+ },
42
+ "dependencies": {
43
+ "@inquirer/prompts": "^8.7.3",
44
+ "ajv": "^8.20.0",
45
+ "commander": "^15.0.0",
46
+ "yaml": "^2.9.1"
47
+ },
48
+ "devDependencies": {
49
+ "@types/node": "^24.19.2",
50
+ "typescript": "^7.0.2",
51
+ "vitest": "^5.0.5"
52
+ }
53
+ }
@@ -0,0 +1,194 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://raw.githubusercontent.com/GEBITSolutions/stax/main/schema/deploy-config.schema.json",
4
+ "title": "stax deploy config",
5
+ "description": "Deploy configuration read by a-wf-setup-ci. Stacks are deployed in dependency levels.",
6
+ "type": "object",
7
+ "properties": {
8
+ "deployment": {
9
+ "description": "Deployment context from this selected YAML. Missing values come directly from GitHub variables; sibling configs are not loaded.",
10
+ "$ref": "#/$defs/deployment"
11
+ },
12
+ "externalRepos": {
13
+ "description": "Repositories providing stack sources or config files, by alias. Stacks reference an alias with source_repo. An empty list means none.",
14
+ "type": ["object", "array"],
15
+ "maxItems": 0,
16
+ "additionalProperties": {
17
+ "type": "array",
18
+ "minItems": 1,
19
+ "items": { "$ref": "#/$defs/externalRepo" }
20
+ }
21
+ },
22
+ "globals": {
23
+ "description": "Values readable by every stack in this file as global.config.var.<key>.",
24
+ "type": "object"
25
+ },
26
+ "stacks": {
27
+ "description": "Stacks deployed by this config.",
28
+ "type": "array",
29
+ "items": { "$ref": "#/$defs/stack" }
30
+ }
31
+ },
32
+ "$defs": {
33
+ "deploymentValue": { "type": ["string", "null"], "pattern": "^[^\\r\\n]*$" },
34
+ "deployment": {
35
+ "type": ["object", "null"],
36
+ "additionalProperties": false,
37
+ "properties": {
38
+ "project": { "description": "Project name; falls back to GitHub PROJECT.", "$ref": "#/$defs/deploymentValue" },
39
+ "customer_id": { "description": "Customer identifier; falls back to CUSTOMER_ID.", "$ref": "#/$defs/deploymentValue" },
40
+ "stage": { "description": "Deployment stage; falls back to STAGE.", "$ref": "#/$defs/deploymentValue" },
41
+ "cloud": { "description": "Azure or AWS, case-insensitive; falls back to CLOUD.", "type": ["string", "null"], "pattern": "^(?:[aA][zZ][uU][rR][eE]|[aA][wW][sS]|[^\\S\\r\\n]*)$" },
42
+ "default_location": { "description": "Cloud region; falls back to DEFAULT_LOCATION.", "$ref": "#/$defs/deploymentValue" },
43
+ "resource_group_name": { "description": "Azure resource group; falls back to RESOURCE_GROUP_NAME.", "$ref": "#/$defs/deploymentValue" },
44
+ "public_cloud_flag": { "description": "Public-cloud flag; falls back to PUBLIC_CLOUD_FLAG. An explicit false overrides GitHub.", "type": ["boolean", "string", "null"], "pattern": "^(?:true|false|[^\\S\\r\\n]*)$" },
45
+ "dns_zone_name": { "description": "DNS zone; falls back to DNS_ZONE_NAME.", "$ref": "#/$defs/deploymentValue" },
46
+ "dns_zone_resource_group_name": { "description": "Azure DNS resource group; falls back to DNS_ZONE_RESOURCE_GROUP_NAME.", "$ref": "#/$defs/deploymentValue" },
47
+ "state_storage_account_name": { "description": "Azure state account; falls back to STATE_STORAGE_ACCOUNT_NAME.", "$ref": "#/$defs/deploymentValue" },
48
+ "state_container_name": { "description": "Azure state container; falls back to STATE_CONTAINER_NAME.", "$ref": "#/$defs/deploymentValue" },
49
+ "state_resource_group_name": { "description": "Azure state resource group; falls back to STATE_RESOURCE_GROUP_NAME.", "$ref": "#/$defs/deploymentValue" },
50
+ "state_bucket_name": { "description": "AWS state bucket; falls back to STATE_BUCKET_NAME.", "$ref": "#/$defs/deploymentValue" },
51
+ "state_region": { "description": "AWS state region; falls back to STATE_REGION.", "$ref": "#/$defs/deploymentValue" }
52
+ }
53
+ },
54
+ "externalRepo": {
55
+ "type": "object",
56
+ "properties": {
57
+ "repoURL": { "description": "Git URL, e.g. github.com/<org>/<repo>.git.", "type": "string", "minLength": 1 },
58
+ "targetRevision": { "description": "Default branch, tag or commit.", "type": "string", "minLength": 1 },
59
+ "token": { "description": "Name of the GitHub secret holding a read token.", "type": "string", "minLength": 1 },
60
+ "use_app_token": { "description": "Use the GitHub App token; only works for repositories in the caller's org.", "type": "boolean" }
61
+ },
62
+ "required": ["repoURL", "targetRevision"]
63
+ },
64
+ "stringList": { "type": "array", "items": { "type": "string" } },
65
+ "relativePath": { "type": "string", "minLength": 1 },
66
+ "stack": {
67
+ "type": "object",
68
+ "properties": {
69
+ "id": { "description": "Unique stack id; other stacks reference it in depends_on and stack.<id>.var.<key> inputs.", "type": "string", "minLength": 1 },
70
+ "name": { "description": "Display name.", "type": "string" },
71
+ "type": {
72
+ "description": "Executor that deploys the stack.",
73
+ "enum": [
74
+ "terraform",
75
+ "opentofu",
76
+ "packer",
77
+ "docker-build-push",
78
+ "function-build-deploy",
79
+ "rpmbuild",
80
+ "swa-site-deploy",
81
+ "swa-docs-site-deploy",
82
+ "s3-site-deploy",
83
+ "script",
84
+ "bizep",
85
+ "github-pages-site-deploy"
86
+ ]
87
+ },
88
+ "if": { "description": "Deploy only when this JavaScript condition holds; {stage} and other pipeline values are substituted first.", "type": "string", "examples": ["'{stage}' == 'prod'"], "x-stax-types": "all" },
89
+ "depends_on": { "description": "Stack ids deployed before this one.", "$ref": "#/$defs/stringList", "examples": [[]], "x-stax-types": "all" },
90
+ "stack-groups": { "description": "Groups for selecting stacks in the deploy form.", "$ref": "#/$defs/stringList", "examples": [["core"]], "x-stax-types": "all" },
91
+ "runs-on": { "description": "Runner label.", "type": "string", "examples": ["ubuntu-24.04"], "x-stax-types": "all" },
92
+ "input": {
93
+ "description": "Inputs: reference strings (global.pipeline.var.<key>, stack.<id>.var.<key>, ...) or key/value maps.",
94
+ "type": "array",
95
+ "items": { "type": ["string", "object"] },
96
+ "examples": [["global.pipeline.var.stage"]],
97
+ "x-stax-types": ["terraform", "opentofu", "packer", "docker-build-push", "function-build-deploy", "swa-site-deploy", "swa-docs-site-deploy", "s3-site-deploy", "script", "bizep"]
98
+ },
99
+ "tf-vars": { "type": "object", "additionalProperties": { "type": "string" } },
100
+ "output-var": { "description": "Outputs exported as variables.", "$ref": "#/$defs/stringList", "examples": [["resource_group_name"]], "x-stax-types": ["terraform", "opentofu", "packer"] },
101
+ "output-secret": { "description": "Outputs exported as secrets.", "$ref": "#/$defs/stringList", "examples": [["admin_password"]], "x-stax-types": ["terraform", "opentofu"] },
102
+ "globals": { "description": "Extra values for input resolution.", "type": "object", "examples": [{ "site_name": "docs" }], "x-stax-types": ["swa-site-deploy", "swa-docs-site-deploy", "s3-site-deploy", "script", "bizep"] },
103
+ "location": { "description": "Cloud region.", "type": "string", "examples": ["westeurope"], "x-stax-types": ["terraform", "opentofu", "function-build-deploy", "s3-site-deploy"] },
104
+ "source_repo": {
105
+ "description": "externalRepos alias holding the stack source.",
106
+ "type": "string",
107
+ "examples": ["shared"],
108
+ "x-stax-types": ["terraform", "opentofu", "packer", "swa-site-deploy", "swa-docs-site-deploy", "s3-site-deploy", "script", "bizep", "github-pages-site-deploy"]
109
+ },
110
+ "source_version": {
111
+ "description": "Branch, tag or commit; overrides the alias targetRevision.",
112
+ "type": "string",
113
+ "examples": ["main"],
114
+ "x-stax-types": ["terraform", "opentofu", "packer", "swa-site-deploy", "swa-docs-site-deploy", "s3-site-deploy", "script", "bizep", "github-pages-site-deploy"]
115
+ },
116
+ "destroy": { "description": "Destroy the stack instead of deploying it.", "type": ["boolean", "string"], "examples": [false], "x-stax-types": ["terraform", "opentofu", "swa-site-deploy", "swa-docs-site-deploy"] },
117
+
118
+ "folder": {
119
+ "description": "Stack directory: below stack_base_path for terraform/opentofu, below functions/ for function-build-deploy.",
120
+ "$ref": "#/$defs/relativePath",
121
+ "examples": ["network"],
122
+ "x-stax-types": ["terraform", "opentofu", "function-build-deploy"]
123
+ },
124
+ "stack_base_path": { "description": "Defaults to terraform/stacks.", "type": "string", "examples": ["terraform/stacks"], "x-stax-types": ["terraform", "opentofu"] },
125
+ "cloud": { "description": "Defaults to the pipeline cloud, then azure.", "enum": ["azure", "aws"], "examples": ["azure"], "x-stax-types": ["terraform", "opentofu"] },
126
+ "terraform_version": { "type": "string", "examples": ["1.9.8"], "x-stax-types": ["terraform"] },
127
+ "opentofu_version": { "type": "string", "examples": ["1.8.1"], "x-stax-types": ["opentofu"] },
128
+ "local_backend": { "description": "Use local state instead of the remote backend.", "type": "boolean", "examples": [false], "x-stax-types": ["terraform", "opentofu"] },
129
+ "local_terraform_state": { "description": "Alias of local_backend.", "type": "boolean" },
130
+ "upload_plan_artifact": { "type": "boolean", "examples": [false], "x-stax-types": ["terraform", "opentofu"] },
131
+ "checkov_skip_checks": { "$ref": "#/$defs/stringList", "examples": [["CKV_AZURE_35"]], "x-stax-types": ["terraform", "opentofu"] },
132
+
133
+ "packer_directory": { "description": "Packer project path, relative to the source repository.", "$ref": "#/$defs/relativePath", "examples": ["packer/ubuntu"], "x-stax-types": ["packer"] },
134
+ "packer_template": { "description": "Template file or directory relative to packer_directory; defaults to '.'.", "$ref": "#/$defs/relativePath", "examples": ["azure.pkr.hcl"], "x-stax-types": ["packer"] },
135
+ "packer_version": { "description": "Exact Packer version.", "type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$", "examples": ["1.11.2"], "x-stax-types": ["packer"] },
136
+
137
+ "image_name": { "type": "string", "examples": ["my-app"], "x-stax-types": ["docker-build-push"] },
138
+ "dockerfile_folder": { "description": "Build context containing the Dockerfile.", "type": "string", "examples": ["docker/my-app"], "x-stax-types": ["docker-build-push"] },
139
+ "no_cache": { "type": "boolean", "examples": [false], "x-stax-types": ["docker-build-push"] },
140
+ "registry": { "type": "string", "examples": ["ghcr.io"], "x-stax-types": ["docker-build-push"] },
141
+ "registy": { "description": "Deprecated misspelling of registry; still read and wins over registry.", "type": "string" },
142
+ "input-gh-secrets": { "description": "Build secrets: secret id to GitHub secret name.", "type": "object", "additionalProperties": { "type": "string" }, "examples": [{ "npm_token": "NPM_TOKEN" }], "x-stax-types": ["docker-build-push"] },
143
+ "output-gh-vars": { "type": "object", "additionalProperties": { "type": "string" }, "examples": [{ "image": "IMAGE_REF" }], "x-stax-types": ["docker-build-push"] },
144
+
145
+ "runtime": { "enum": ["python", "node"], "examples": ["python"], "x-stax-types": ["function-build-deploy"] },
146
+ "version": { "description": "Runtime version for function-build-deploy.", "type": "string", "examples": ["3.12"], "x-stax-types": ["function-build-deploy"] },
147
+
148
+ "rpm_repo_baseurl": { "type": "string", "examples": ["https://rpm.example.com/repo"], "x-stax-types": ["rpmbuild"] },
149
+ "pulp_rpm_repository": { "type": "string", "examples": ["my-repo"], "x-stax-types": ["rpmbuild"] },
150
+ "rpm_gpg_name": { "type": "string", "examples": ["Release Signing Key"], "x-stax-types": ["rpmbuild"] },
151
+
152
+ "swa_source_type": { "description": "Static site source; defaults to mkdocs.", "type": "string", "examples": ["mkdocs"], "x-stax-types": ["swa-site-deploy", "swa-docs-site-deploy"] },
153
+ "site_source_type": { "description": "Static site source; defaults to mkdocs.", "enum": ["mkdocs", "zensical", "prebuilt"], "examples": ["mkdocs"], "x-stax-types": ["s3-site-deploy", "github-pages-site-deploy"] },
154
+ "site_url": { "description": "Public site URL.", "type": "string", "pattern": "^https?://", "examples": ["https://docs.example.com/"], "x-stax-types": ["github-pages-site-deploy"] },
155
+ "docs_path": { "description": "Docs directory; defaults to docs.", "$ref": "#/$defs/relativePath", "examples": ["docs"], "x-stax-types": ["swa-site-deploy", "swa-docs-site-deploy", "s3-site-deploy", "github-pages-site-deploy"] },
156
+ "site_source": { "description": "Alias of docs_path.", "type": "string" },
157
+ "app_location": { "description": "Site root containing the site config.", "type": "string", "examples": ["."], "x-stax-types": ["swa-site-deploy", "swa-docs-site-deploy", "s3-site-deploy", "github-pages-site-deploy"] },
158
+ "config_file": { "description": "staticwebapp.config.json path in the source repository.", "type": "string", "examples": ["staticwebapp.config.json"], "x-stax-types": ["swa-site-deploy", "swa-docs-site-deploy"] },
159
+ "config_file_location": { "description": "Directory holding staticwebapp.config.json.", "type": "string", "examples": ["site"], "x-stax-types": ["swa-site-deploy", "swa-docs-site-deploy"] },
160
+
161
+ "script": { "description": "Script path relative to the source checkout.", "type": "string", "minLength": 1, "examples": ["scripts/deploy.sh"], "x-stax-types": ["script"] },
162
+ "resource_prefix": { "type": "string", "examples": ["app"], "x-stax-types": ["script", "bizep"] },
163
+ "template": { "description": "Bicep template path for bizep stacks.", "type": "string", "minLength": 1, "examples": ["bicep/main.bicep"], "x-stax-types": ["bizep"] }
164
+ },
165
+ "required": ["id", "type"],
166
+ "allOf": [
167
+ {
168
+ "if": { "properties": { "type": { "enum": ["terraform", "opentofu", "function-build-deploy"] } }, "required": ["type"] },
169
+ "then": { "required": ["folder"] }
170
+ },
171
+ {
172
+ "if": { "properties": { "type": { "const": "packer" } }, "required": ["type"] },
173
+ "then": { "required": ["packer_directory", "packer_version"] }
174
+ },
175
+ {
176
+ "if": { "properties": { "type": { "const": "s3-site-deploy" } }, "required": ["type"] },
177
+ "then": { "required": ["location"] }
178
+ },
179
+ {
180
+ "if": { "properties": { "type": { "const": "script" } }, "required": ["type"] },
181
+ "then": { "required": ["script"] }
182
+ },
183
+ {
184
+ "if": { "properties": { "type": { "const": "bizep" } }, "required": ["type"] },
185
+ "then": { "required": ["template"] }
186
+ },
187
+ {
188
+ "if": { "properties": { "type": { "const": "function-build-deploy" } }, "required": ["type"] },
189
+ "then": { "required": ["runtime"] }
190
+ }
191
+ ]
192
+ }
193
+ }
194
+ }