@nasebanal/cli 0.12.0 → 0.14.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.
@@ -29,9 +29,9 @@
29
29
  */
30
30
  import { Command } from "commander";
31
31
  import { readFileSync } from "node:fs";
32
- import { loadSpec } from "./loader.js";
32
+ import { loadSpec, } from "./loader.js";
33
33
  import { resolveBaseUrl, request } from "../http.js";
34
- import { resolveAccessToken, resolveEnv } from "../config.js";
34
+ import { baseUrlOverride, resolveAccessToken, resolveEnv } from "../config.js";
35
35
  import { printJson } from "../output.js";
36
36
  const METHODS = ["get", "post", "put", "patch", "delete"];
37
37
  function stripBasePath(path) {
@@ -81,6 +81,38 @@ function group(parent, name) {
81
81
  parent.addCommand(cmd);
82
82
  return cmd;
83
83
  }
84
+ /** The parameters of an operation as the spec means them: the path's shared ones and its own, `$ref`s resolved, own wins. */
85
+ function resolveParameters(spec, shared, own) {
86
+ const out = new Map();
87
+ for (const raw of [...(shared ?? []), ...(own ?? [])]) {
88
+ let p;
89
+ if ("$ref" in raw) {
90
+ const name = raw.$ref.replace(/^#\/components\/parameters\//, "");
91
+ p = spec.components?.parameters?.[name];
92
+ }
93
+ else {
94
+ p = raw;
95
+ }
96
+ if (p)
97
+ out.set(`${p.in}:${p.name.toLowerCase()}`, p);
98
+ }
99
+ return [...out.values()];
100
+ }
101
+ /**
102
+ * The `--flag` a header parameter becomes. The active organization (`X-Active-Organization-Id`) is `--org`, the same flag
103
+ * the hand-written `nb specs` verbs take; any other header is its name without the `X-` prefix, in kebab case.
104
+ */
105
+ export function headerFlag(header) {
106
+ if (header.toLowerCase() === "x-active-organization-id")
107
+ return "org";
108
+ return header.toLowerCase().replace(/^x-/, "");
109
+ }
110
+ /** `personal`, or an organization's id: the only two values the active-organization header takes. */
111
+ function checkOrgValue(raw) {
112
+ if (raw === "personal" || /^[1-9]\d{0,17}$/.test(raw))
113
+ return raw;
114
+ throw new Error(`--org '${raw}' must be 'personal' or an organization id (a number)`);
115
+ }
84
116
  function readData(value) {
85
117
  const raw = value.startsWith("@") ? readFileSync(value.slice(1), "utf8") : value;
86
118
  try {
@@ -90,16 +122,24 @@ function readData(value) {
90
122
  throw new Error(`--data must be valid JSON (or @file containing JSON); got: ${value}`);
91
123
  }
92
124
  }
93
- function attachLeaf(parent, name, pathTemplate, method, op, servers) {
125
+ function attachLeaf(parent, name, pathTemplate, method, op, servers, parameters, apiName) {
94
126
  const leaf = new Command(name);
95
127
  leaf.description(op.summary || `${method.toUpperCase()} ${pathTemplate}`);
96
128
  const params = pathParams(pathTemplate);
97
129
  for (const p of params)
98
130
  leaf.argument(`<${p}>`, `path parameter: ${p}`);
99
- const queryParams = (op.parameters ?? []).filter((p) => p.in === "query");
131
+ const queryParams = parameters.filter((p) => p.in === "query");
100
132
  for (const q of queryParams) {
101
133
  leaf.option(`--${q.name} <value>`, q.description || `query parameter: ${q.name}`);
102
134
  }
135
+ // A header the API wants on the call (the catalog's active organization). A required one has a default, so the
136
+ // command works without the flag; the active organization also reads $NB_<API>_ORG (NB_SPECS_ORG for `nb specs`).
137
+ const headerParams = parameters.filter((p) => p.in === "header" && p.name.toLowerCase() !== "authorization");
138
+ for (const h of headerParams) {
139
+ const flag = headerFlag(h.name);
140
+ const envName = flag === "org" ? `NB_${apiName.toUpperCase()}_ORG` : undefined;
141
+ leaf.option(`--${flag} <value>`, `${h.name} header${flag === "org" ? ": an organization id, or 'personal'" : ""}${h.required ? " (default: personal)" : ""}${envName ? ` (or $${envName})` : ""}`);
142
+ }
103
143
  const acceptsBody = method !== "get" && method !== "delete";
104
144
  if (acceptsBody || op.requestBody) {
105
145
  leaf.option("--data <json>", "request body as JSON (or @file to read from a file)");
@@ -111,11 +151,10 @@ function attachLeaf(parent, name, pathTemplate, method, op, servers) {
111
151
  const opts = command.optsWithGlobals();
112
152
  const env = opts.env || resolveEnv();
113
153
  const token = opts.token || (await resolveAccessToken());
114
- // NB_BASE_URL overrides server resolution entirely (origin only — the spec
154
+ // NB_<API>_BASE_URL overrides server resolution for this API entirely (origin only — the spec
115
155
  // path is still appended). Used by the CDD contract test to point the CLI at
116
- // a Specmatic stub, and available for advanced/self-hosted setups.
117
- const override = process.env.NB_BASE_URL?.replace(/\/$/, "");
118
- const baseUrl = override ?? resolveBaseUrl(servers, env);
156
+ // a Specmatic stub, and available for local / self-hosted setups. The shared NB_BASE_URL still works but is deprecated.
157
+ const baseUrl = baseUrlOverride(apiName) ?? resolveBaseUrl(servers, env);
119
158
  let realPath = pathTemplate;
120
159
  params.forEach((p, i) => {
121
160
  realPath = realPath.replace(`{${p}}`, encodeURIComponent(positionals[i]));
@@ -124,7 +163,15 @@ function attachLeaf(parent, name, pathTemplate, method, op, servers) {
124
163
  for (const q of queryParams)
125
164
  query[q.name] = opts[q.name];
126
165
  const body = opts.data !== undefined ? readData(opts.data) : undefined;
127
- const res = await request({ baseUrl, path: realPath, method, query, body, token });
166
+ const headers = {};
167
+ for (const h of headerParams) {
168
+ const flag = headerFlag(h.name);
169
+ const fromEnv = flag === "org" ? process.env[`NB_${apiName.toUpperCase()}_ORG`]?.trim() || undefined : undefined;
170
+ const value = opts[flag] ?? fromEnv ?? (h.required && flag === "org" ? "personal" : undefined);
171
+ if (value !== undefined)
172
+ headers[h.name] = flag === "org" ? checkOrgValue(value) : value;
173
+ }
174
+ const res = await request({ baseUrl, path: realPath, method, query, body, token, headers });
128
175
  printJson(res.data);
129
176
  });
130
177
  parent.addCommand(leaf);
@@ -141,7 +188,13 @@ export function buildApiCommand(api) {
141
188
  const op = item[method];
142
189
  if (!op)
143
190
  continue;
144
- const entry = { chain: commandChain(method, path), path, method, op };
191
+ const entry = {
192
+ chain: commandChain(method, path),
193
+ path,
194
+ method,
195
+ op,
196
+ parameters: resolveParameters(spec, item.parameters, op.parameters),
197
+ };
145
198
  const key = entry.chain.join(" ");
146
199
  const existing = byChain.get(key);
147
200
  if (!existing || pathParams(path).length > pathParams(existing.path).length) {
@@ -174,12 +227,12 @@ export function buildApiCommand(api) {
174
227
  byChain.delete(entry.chain.join(" "));
175
228
  byChain.set(key, { ...entry, chain: renamed });
176
229
  }
177
- for (const { chain, path, method, op } of byChain.values()) {
230
+ for (const { chain, path, method, op, parameters } of byChain.values()) {
178
231
  const leafName = chain[chain.length - 1];
179
232
  let parent = root;
180
233
  for (const segment of chain.slice(0, -1))
181
234
  parent = group(parent, segment);
182
- attachLeaf(parent, leafName, path, method, op, spec.servers);
235
+ attachLeaf(parent, leafName, path, method, op, spec.servers, parameters, api.name);
183
236
  }
184
237
  return root;
185
238
  }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The API version of a spec (`v1`, `v2`): a property of the SPEC, not of a revision. A new major API version is a new spec; inside
3
+ * a spec the numbered history is the REVISION (what the catalog calls `version`, and this CLI calls a revision).
4
+ *
5
+ * The same derivation as nb-specs-api's `apiVersionOf`, so `nb specs specs push` knows before sending which spec a document
6
+ * belongs to: the document's `info.version`, trimmed, must match `^[vV]?(\d{1,3})(\.\d+){0,2}([-+][0-9A-Za-z.+-]*)?$`, and the
7
+ * API version is `v<major>` with leading zeros dropped. `1.8.0` -> `v1`, `v2.0` -> `v2`, `1.0.0-rc.1` -> `v1`, `007.1` -> `v7`;
8
+ * `2023-01`, `2023.1`, `latest` and `1.x` have no major (they need `--api-version`).
9
+ */
10
+ import { parse } from "yaml";
11
+ const MAJOR = /^[vV]?(\d{1,3})(\.\d+){0,2}([-+][0-9A-Za-z.+-]*)?$/;
12
+ /** The API version an `info.version` gives, or null when it has no major. */
13
+ export function apiVersionFromInfoVersion(infoVersion) {
14
+ const m = MAJOR.exec(infoVersion.trim());
15
+ return m ? `v${Number(m[1])}` : null;
16
+ }
17
+ /** The API version a document's `info.version` gives, or null (not parseable, no `info.version`, or no major in it). */
18
+ export function apiVersionOf(text) {
19
+ try {
20
+ const doc = parse(text);
21
+ const v = doc?.info?.version;
22
+ // YAML reads `version: 1.0` as the number 1: the text the author wrote is what the server reads, so a number is its plain text.
23
+ return typeof v === "string" || typeof v === "number" ? apiVersionFromInfoVersion(String(v)) : null;
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ const LABEL = /^[A-Za-z0-9._-]{1,32}$/;
30
+ /** `--api-version`: the same label rule as the catalog (letters, digits, '.', '_', '-', up to 32). Returned trimmed. */
31
+ export function checkApiVersion(raw) {
32
+ const v = raw.trim();
33
+ if (!LABEL.test(v))
34
+ throw new Error(`--api-version '${raw}' must be a version label: letters, digits, '.', '_' and '-' (up to 32), e.g. v1 or v2`);
35
+ return v;
36
+ }
37
+ /** Whether two API versions are the same one (the catalog compares them ignoring case). */
38
+ export const sameApiVersion = (a, b) => (a ?? "").toLowerCase() === (b ?? "").toLowerCase();
@@ -1,24 +1,38 @@
1
1
  /**
2
- * `nb specs` - the API catalog (your own OpenAPI documents) from the command line. Hand-written: the CLI's generated
3
- * command tree comes from the pinned contracts, and the catalog's is not among them.
2
+ * `nb specs` - repositories and the API catalog (your own OpenAPI documents). The tree is generated from the contract like
3
+ * every other group (`nb specs specs list`, `nb specs repositories get <id>`, `nb specs groups ...`); the verbs a pipeline
4
+ * wants and the contract cannot express are hand-written and attached to it by `attachSpecsCommands`: `specs push`,
5
+ * `specs pull`, `specs settings` and `repositories upsert`. Each sub-menu of the Evolution screen API management has one resource:
6
+ * Repository Management = `nb specs repositories` (provider, name, component and the one repository setting, `--attachments`),
7
+ * Spec Management = `nb specs specs` (the spec, its description document `docs push|pull|delete`, and, since 2026-11-10, its public badge and report with their links). The key of a spec is its group, its repository row, its API version (v1, v2: a new major version is a new spec) and its name (an environment is a group); the numbered history inside a spec is its revisions. The old direct form (`nb specs push|pull|versions`) stays as hidden aliases.
4
8
  */
5
- import { writeFileSync } from "node:fs";
9
+ import { readFileSync, writeFileSync } from "node:fs";
6
10
  import { Command } from "commander";
7
11
  import { resolveAccessToken, resolveEnv } from "../config.js";
8
12
  import { exportGithubOutput, printJson } from "../output.js";
9
13
  import { detectCi } from "../reports/ci.js";
14
+ import { docsDelete, docsPull, docsPush } from "./docs.js";
10
15
  import { parseHash, parseVersion, pullSpec, specVersions } from "./pull.js";
11
- import { checkOrg, ciNote, pushSpec, specsBaseUrl } from "./push.js";
16
+ import { checkServerUrl } from "./servers.js";
17
+ import { checkOrg, checkProvider, ciNote, pushSpec, specsBaseUrl, upsertRepository } from "./push.js";
18
+ import { onOff, parseSettingsFlags, updateSpecSettings } from "./settings.js";
12
19
  export function buildPushCommand() {
13
20
  return new Command("push")
14
- .description("Register an OpenAPI file in the API catalog: a new spec, or a new version when its content changed. Safe to run on every commit: a file that is already the latest version uploads nothing")
21
+ .description("Register an OpenAPI file in the API catalog: a new spec, or a new revision when its content changed. Safe to run on every commit: a file that is already the latest revision uploads nothing")
15
22
  .requiredOption("--file <path>", "the OpenAPI document (YAML or JSON, up to 2 MiB)")
16
23
  .option("--name <name>", "the spec's name in the catalog (default: the document's info.title, then the file's name)")
17
24
  .option("--id <id>", "push to this spec by id: a rename cannot make a second one")
25
+ .option("--follow-version", "with --id: the id names the FIRST spec of an API (its initial version); the document goes to the spec of ITS API version of that API, found by the API version, and that spec is made when the API does not have it yet (a new major needs no change of the id). API versions are registered in order: the next one after the highest the API has, otherwise nothing is registered and the push fails")
18
26
  .option("--rename", "with --id: also rename the spec to --name (default: the document's info.title) when it is called something else")
19
- .option("--group <name>", "file a NEW spec in this group (made when missing); default none. An existing spec is never moved by a push")
27
+ .option("--group <name>", "the spec's group, part of its key (the same name may exist in other groups: an environment each): the spec is looked up in this group, and a NEW one is filed there (the group is made when missing). Default: no group, which does not mean any group: a name that exists only in groups is an error that lists them. An existing spec is never moved by a push")
28
+ .option("--api-version <v>", "the spec's API version (v1, v2), part of its key: a new major API version is a new spec. Default: what the document's info.version gives (1.8.0 -> v1, v2.0 -> v2); needed when it gives none (2023-01, latest). A document of another major than an existing spec of that name makes the NEW spec for its API version and leaves the other alone")
29
+ .option("--server-url <url>", "replace the document's top-level `servers` with this one URL before sending (the environment's URL): one OpenAPI file in the repository, one spec per environment. A YAML file is edited as text (comments and order kept) when that can be proven safe, otherwise written again; the contract hash ignores `servers`, so the contract's identity does not change")
20
30
  .option("--description <text>", "a new spec's description")
21
- .option("--note <text>", "what changed, shown in the version list (default: the commit, branch and CI run)")
31
+ .option("--note <text>", "what changed, shown in the revision list (default: the commit, branch and CI run)")
32
+ .option("--repository-id <id>", "tie the spec to this repository (the id `nb specs repositories upsert` printed; default: $NB_REPOSITORY_ID). A new spec is created tied to it; a spec with no repository is tied to it; one tied to another repository is left there")
33
+ .option("--repository <name>", "tie the spec to the repository of this name (owner/name): it is registered first, idempotently, and its id used. Instead of --repository-id")
34
+ .option("--provider <provider>", "with --repository: github | gitlab | bitbucket | other (default: github)")
35
+ .option("--component <name>", "with --repository: the part of the repository the spec belongs to (account-api, web...); part of the repository's key. Default: none = the repository as a whole")
22
36
  .option("--org <id>", "the organization whose catalog it is (an id), or 'personal' (default; or $NB_SPECS_ORG)")
23
37
  .option("--dry-run", "read the catalog and say what would happen; write nothing")
24
38
  .action(async (_flags, command) => {
@@ -31,18 +45,41 @@ export function buildPushCommand() {
31
45
  file: opts.file,
32
46
  name: opts.name,
33
47
  group: opts.group,
48
+ apiVersion: opts.apiVersion,
49
+ serverUrl: opts.serverUrl !== undefined ? checkServerUrl(opts.serverUrl) : undefined,
34
50
  description: opts.description,
35
51
  note: opts.note ?? ciNote(ci, undefined),
36
52
  id: opts.id,
37
53
  rename: opts.rename,
54
+ followVersion: opts.followVersion,
55
+ // A name asked for wins over the id the pipeline's variable carries.
56
+ repositoryId: opts.repository ? undefined : (opts.repositoryId ?? (process.env.NB_REPOSITORY_ID?.trim() || undefined)),
57
+ repository: opts.repository,
58
+ provider: opts.repository ? checkProvider(opts.provider) : undefined,
59
+ component: opts.repository ? opts.component?.trim() || undefined : undefined,
38
60
  dryRun: opts.dryRun,
39
61
  });
40
62
  printJson(result);
41
63
  exportGithubOutput("spec_id", result.id);
42
- const what = { created: "created (v1)", new_version: `new version v${result.version}`, unchanged: `unchanged (already v${result.version}: nothing uploaded)` }[result.action];
64
+ if (result.repository_id && result.repository_id !== "(new)")
65
+ exportGithubOutput("repository_id", result.repository_id);
66
+ if (result.repository_kept) {
67
+ process.stderr.write(`! ${result.name} is tied to another repository (${result.repository_kept}); a push never moves a spec, so it was left there\n`);
68
+ }
69
+ if (result.servers_edit === "reserialised")
70
+ process.stderr.write("! --server-url: the YAML file was written again (its comments are not kept in what was pushed); the file on disk is unchanged\n");
71
+ const what = { created: `created (${result.api_version}, rev ${result.version})`, new_version: `new revision ${result.version} of ${result.api_version}`, unchanged: `unchanged (already rev ${result.version} of ${result.api_version}: nothing uploaded)` }[result.action];
43
72
  process.stderr.write(`${opts.dryRun ? "(dry run) " : ""}✓ ${result.renamed_from ? `${result.renamed_from} renamed to ` : ""}${result.name} -> ${what}\n`);
44
73
  });
45
74
  }
75
+ /** The group / repository / API version part of a spec's key, from the options (all absent = the name alone, as before). */
76
+ function whereOf(opts) {
77
+ if (opts.repository === undefined && opts.group === undefined && opts.component === undefined && opts.provider === undefined && opts.apiVersion === undefined)
78
+ return undefined;
79
+ if (opts.repository === undefined && (opts.component !== undefined || opts.provider !== undefined))
80
+ throw new Error("--component and --provider need --repository");
81
+ return { group: opts.group, repository: opts.repository, component: opts.component, apiVersion: opts.apiVersion, provider: opts.repository ? checkProvider(opts.provider) : undefined };
82
+ }
46
83
  async function connection(opts) {
47
84
  const env = opts.env || resolveEnv();
48
85
  const token = opts.token || (await resolveAccessToken());
@@ -53,7 +90,12 @@ export function buildPullCommand() {
53
90
  .description("Read a version of a spec's document out of the API catalog, exactly as it was uploaded, and check its SHA-256. For a pipeline that works from the catalog's document (a contract test, a client generator)")
54
91
  .option("--id <id>", "the spec, by id (a rename cannot change it)")
55
92
  .option("--name <name>", "the spec, by its name in the catalog (matched ignoring case)")
56
- .option("--spec-version <n|latest>", "the catalog's version number (1, 2, 3...), not the API's v1 / v2 and not the CLI's own --version. Default: latest. Pin a number in a pipeline: 'latest' moves")
93
+ .option("--group <name>", "with --name: the group the spec is in (part of its key); none = no group")
94
+ .option("--api-version <v>", "with --name: the spec's API version (v1, v2), part of its key; left out = the API version of the one spec the rest of the key matches (several: the error lists them)")
95
+ .option("--repository <owner/name>", "with --name: the repository the spec is tied to (part of its key); none = a spec tied to no repository")
96
+ .option("--component <name>", "with --repository: the component part of its key (none = the repository as a whole)")
97
+ .option("--provider <provider>", "with --repository: github | gitlab | bitbucket | other (default: github)")
98
+ .option("--spec-version <n|latest>", "the catalog's revision number (1, 2, 3...), not the API's v1 / v2 and not the CLI's own --version. Default: latest. Pin a number in a pipeline: 'latest' moves")
57
99
  .option("--hash <sha256>", "the SHA-256 the document must have (as 'nb specs versions' prints it): the pull fails when it differs")
58
100
  .option("--out <file>", "write the document here (default: to standard output, the details to standard error)")
59
101
  .option("--org <id>", "the organization whose catalog it is (an id), or 'personal' (default; or $NB_SPECS_ORG)")
@@ -63,6 +105,7 @@ export function buildPullCommand() {
63
105
  conn: await connection(opts),
64
106
  id: opts.id,
65
107
  name: opts.name,
108
+ where: whereOf(opts),
66
109
  version: parseVersion(opts.specVersion),
67
110
  hash: parseHash(opts.hash),
68
111
  });
@@ -82,23 +125,179 @@ export function buildPullCommand() {
82
125
  exportGithubOutput("spec_id", result.id);
83
126
  exportGithubOutput("spec_version", String(result.version));
84
127
  exportGithubOutput("spec_hash", result.content_hash);
85
- process.stderr.write(`✓ ${result.name} v${result.version} (sha256 ${result.content_hash.slice(0, 12)}..., ${result.size_bytes} bytes)${opts.out ? ` -> ${opts.out}` : ""}\n`);
128
+ process.stderr.write(`✓ ${result.name} rev ${result.version} (sha256 ${result.content_hash.slice(0, 12)}..., ${result.size_bytes} bytes)${opts.out ? ` -> ${opts.out}` : ""}\n`);
86
129
  });
87
130
  }
88
131
  export function buildVersionsCommand() {
89
132
  return new Command("versions")
90
- .description("List the versions of a spec in the API catalog, newest first, each with the SHA-256 of its document (what 'nb specs pull --hash' pins)")
133
+ .description("List the revisions of a spec in the API catalog, newest first, each with the SHA-256 of its document (what 'nb specs pull --hash' pins)")
91
134
  .option("--id <id>", "the spec, by id")
92
135
  .option("--name <name>", "the spec, by its name in the catalog (matched ignoring case)")
136
+ .option("--group <name>", "with --name: the group the spec is in (part of its key); none = no group")
137
+ .option("--api-version <v>", "with --name: the spec's API version (v1, v2), part of its key; left out = the API version of the one spec the rest of the key matches (several: the error lists them)")
138
+ .option("--repository <owner/name>", "with --name: the repository the spec is tied to (part of its key); none = a spec tied to no repository")
139
+ .option("--component <name>", "with --repository: the component part of its key (none = the repository as a whole)")
140
+ .option("--provider <provider>", "with --repository: github | gitlab | bitbucket | other (default: github)")
93
141
  .option("--org <id>", "the organization whose catalog it is (an id), or 'personal' (default; or $NB_SPECS_ORG)")
94
142
  .action(async (_flags, command) => {
95
143
  const opts = command.optsWithGlobals();
96
- const result = await specVersions({ conn: await connection(opts), id: opts.id, name: opts.name });
144
+ const result = await specVersions({ conn: await connection(opts), id: opts.id, name: opts.name, where: whereOf(opts) });
97
145
  printJson(result);
98
146
  const latest = result.versions[0];
99
- process.stderr.write(`✓ ${result.name}: ${result.versions.length} version${result.versions.length === 1 ? "" : "s"}${latest ? ` (latest v${latest.version})` : ""}\n`);
147
+ process.stderr.write(`✓ ${result.name}: ${result.versions.length} revision${result.versions.length === 1 ? "" : "s"}${latest ? ` (latest rev ${latest.version})` : ""}\n`);
100
148
  });
101
149
  }
150
+ /** The spec a `docs` verb is about: `--spec-id` (default $NB_SPEC_ID), or `--spec` with the optional repository / component / group. */
151
+ function docsRefOf(opts) {
152
+ const byNames = [opts.spec, opts.repository, opts.component, opts.group, opts.apiVersion].some((v) => v !== undefined && v.trim() !== "");
153
+ if (opts.specId !== undefined && byNames)
154
+ throw new Error("--spec-id names the spec by itself: do not combine it with --spec, --repository, --component, --group or --api-version");
155
+ if (byNames)
156
+ return { spec: opts.spec, repository: opts.repository, component: opts.component, group: opts.group, apiVersion: opts.apiVersion, provider: opts.provider };
157
+ const specId = (opts.specId ?? process.env.NB_SPEC_ID)?.trim();
158
+ if (specId)
159
+ return { specId };
160
+ throw new Error("Say which spec: --spec-id <id> (or set NB_SPEC_ID), or --spec <name> [--repository <name> [--component <name>]] [--group <name>]");
161
+ }
162
+ function withSpecOptions(cmd) {
163
+ return cmd
164
+ .option("--spec-id <id>", "the spec, by its id in the catalog (default: $NB_SPEC_ID). Exclusive with the names below")
165
+ .option("--spec <name>", "by names: the spec's name")
166
+ .option("--repository <owner/name>", "by names: the repository the spec is tied to; none = a spec tied to no repository")
167
+ .option("--component <name>", "by names, with --repository: the component part of its key (none = the repository as a whole)")
168
+ .option("--group <name>", "by names: the group the spec is filed in; none = a spec in no group (not any group)")
169
+ .option("--api-version <v>", "by names: the spec's API version (v1, v2), part of its key; left out = the API version of the one spec the rest of the key matches (several: the error lists them)")
170
+ .option("--provider <provider>", "with --repository: github | gitlab | bitbucket | other (default: github)")
171
+ .option("--org <id>", "the organization whose catalog it is (an id), or 'personal' (default; or $NB_SPECS_ORG)");
172
+ }
173
+ export function buildDocsCommand() {
174
+ const docs = new Command("docs").description("The spec's description document: ONE Markdown file per spec (up to 200 KiB), shown rendered in the catalog, like a developer portal's overview page");
175
+ docs.addCommand(withSpecOptions(new Command("push").description("Upload a Markdown file as the spec's description document (replaces the one it has)").requiredOption("--file <path>", "the Markdown file (up to 200 KiB, UTF-8)")).action(async (_flags, command) => {
176
+ const opts = command.optsWithGlobals();
177
+ const ref = docsRefOf({ ...opts, provider: opts.repository ? checkProvider(opts.provider) : undefined });
178
+ const result = await docsPush({ conn: await connection(opts), ref, file: opts.file });
179
+ printJson(result);
180
+ exportGithubOutput("spec_id", result.spec_id);
181
+ process.stderr.write(`✓ ${result.spec_name}: description document ${result.created ? "added" : "replaced"} (${result.size_bytes} bytes)\n`);
182
+ }));
183
+ docs.addCommand(withSpecOptions(new Command("pull").description("Print the spec's description document (or write it with --out)").option("--out <file>", "write the document here (default: standard output)")).action(async (_flags, command) => {
184
+ const opts = command.optsWithGlobals();
185
+ const ref = docsRefOf({ ...opts, provider: opts.repository ? checkProvider(opts.provider) : undefined });
186
+ const result = await docsPull({ conn: await connection(opts), ref });
187
+ if (opts.out) {
188
+ try {
189
+ writeFileSync(opts.out, result.text);
190
+ }
191
+ catch (err) {
192
+ throw new Error(`--out: cannot write ${opts.out}: ${err.message}`);
193
+ }
194
+ printJson({ spec_id: result.spec_id, spec_name: result.spec_name, out: opts.out });
195
+ }
196
+ else {
197
+ process.stdout.write(result.text);
198
+ }
199
+ process.stderr.write(`✓ ${result.spec_name}: description document (${Buffer.byteLength(result.text, "utf8")} bytes)${opts.out ? ` -> ${opts.out}` : ""}\n`);
200
+ }));
201
+ docs.addCommand(withSpecOptions(new Command("delete").description("Remove the spec's description document (safe when there is none)")).action(async (_flags, command) => {
202
+ const opts = command.optsWithGlobals();
203
+ const ref = docsRefOf({ ...opts, provider: opts.repository ? checkProvider(opts.provider) : undefined });
204
+ const result = await docsDelete({ conn: await connection(opts), ref });
205
+ printJson(result);
206
+ process.stderr.write(`✓ ${result.spec_name}: description document removed\n`);
207
+ }));
208
+ return docs;
209
+ }
210
+ export function buildUpsertCommand() {
211
+ return new Command("upsert")
212
+ .description("Register a repository by provider and name and print it, with the id the catalog issued for it. Safe to repeat: the same repository always answers the same id (and nothing set on a screen is overwritten). Run it once by hand, then give the id to the pipeline as NB_REPOSITORY_ID")
213
+ .requiredOption("--name <name>", "the repository: owner/name for github, gitlab and bitbucket; any text for 'other' (a delivery that is not in git)")
214
+ .option("--provider <provider>", "github | gitlab | bitbucket | other (default: github)")
215
+ .option("--component <name>", "the part of the repository (account-api, web...), at most 100 characters; with the provider and the name it is the key, and one id says which repository AND which component. Default: none = the repository as a whole")
216
+ .option("--attachments <on|off>", "a result of this repository may carry the original test report (kept in R2); applied only when this call registers the repository, an existing one is left as it is (change it with `repositories update --attachments`)")
217
+ .option("--org <id>", "the organization whose catalog it is (an id), or 'personal' (default; or $NB_SPECS_ORG)")
218
+ .action(async (_flags, command) => {
219
+ const opts = command.optsWithGlobals();
220
+ const attachments = opts.attachments === undefined ? undefined : onOff("--attachments", opts.attachments);
221
+ const repo = await upsertRepository(await connection(opts), checkProvider(opts.provider), opts.name.trim(), opts.component?.trim() ?? "", attachments);
222
+ const { created, ...row } = repo;
223
+ printJson(row);
224
+ exportGithubOutput("repository_id", repo.id);
225
+ process.stderr.write(`✓ ${repo.provider} ${repo.name}${repo.component ? ` / ${repo.component}` : ""} -> ${repo.id} (${created ? "registered" : "already registered"})\n`);
226
+ });
227
+ }
228
+ export function buildSettingsCommand() {
229
+ return new Command("settings")
230
+ .description("Change a spec's public settings (the Spec screen's public badge and report with their links), and print the spec. Only the flags you pass change; the rest is left as it is. Attachments are the repository's: `nb specs repositories update --attachments`")
231
+ .argument("<id>", "the spec's id")
232
+ .option("--public-badge <on|off>", "the quality badge is readable without a login while it is on")
233
+ .option("--report-access <hidden|login|public>", "who may read the quality report: nobody, anyone signed in with the link, or anyone with the link")
234
+ .option("--rotate-quality-public-id", "issue a new token for the public badge and report links: every old link stops working")
235
+ .option("--org <id>", "the organization whose catalog it is (an id), or 'personal' (default; or $NB_SPECS_ORG)")
236
+ .action(async (id, _flags, command) => {
237
+ const opts = command.optsWithGlobals();
238
+ const patch = parseSettingsFlags(opts);
239
+ const spec = await updateSpecSettings(await connection(opts), id, patch);
240
+ printJson(spec);
241
+ process.stderr.write(`✓ ${spec.name}: ${Object.keys(patch).join(", ")} updated\n`);
242
+ });
243
+ }
244
+ /**
245
+ * The generated `repositories update` takes the whole body as `--data`; this adds `--attachments <on|off>` to it (the repository's
246
+ * one setting) and puts `attachments_enabled` into the body just before the generated action sends it. Without the flag the body
247
+ * is sent as it is.
248
+ */
249
+ export function attachRepositoryAttachments(repositories) {
250
+ const leaf = repositories.commands.find((c) => c.name() === "update");
251
+ if (!leaf)
252
+ return;
253
+ leaf.option("--attachments <on|off>", "a result of this repository may carry the original test report (kept in R2); merged into --data as attachments_enabled");
254
+ leaf.hook("preAction", (thisCommand) => {
255
+ const opts = thisCommand.optsWithGlobals();
256
+ if (opts.attachments === undefined)
257
+ return;
258
+ const attachments = onOff("--attachments", opts.attachments);
259
+ let body = {};
260
+ if (opts.data !== undefined) {
261
+ const raw = opts.data.startsWith("@") ? readFileSync(opts.data.slice(1), "utf8") : opts.data;
262
+ try {
263
+ const parsed = JSON.parse(raw);
264
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
265
+ throw new Error("not an object");
266
+ body = parsed;
267
+ }
268
+ catch {
269
+ throw new Error(`--data must be a JSON object (or @file containing one); got: ${opts.data}`);
270
+ }
271
+ }
272
+ thisCommand.setOptionValue("data", JSON.stringify({ ...body, attachments_enabled: attachments }));
273
+ });
274
+ }
275
+ /** The hand-written verbs on the generated `specs` group, in the same `<resource> <verb>` shape as the rest of the tree. */
276
+ export function attachSpecsCommands(group) {
277
+ const child = (name) => {
278
+ const existing = group.commands.find((c) => c.name() === name);
279
+ if (existing)
280
+ return existing;
281
+ const made = new Command(name).description(`${name} commands`);
282
+ group.addCommand(made);
283
+ return made;
284
+ };
285
+ const specsResource = child("specs");
286
+ // The contract's docs routes generate a `docs` leaf (a JSON body for PUT): the description document is Markdown, so the hand-written
287
+ // `docs push|pull|delete` group takes its place.
288
+ const generated = specsResource.commands.findIndex((c) => c.name() === "docs");
289
+ if (generated >= 0)
290
+ specsResource.commands.splice(generated, 1);
291
+ specsResource.addCommand(buildPushCommand()).addCommand(buildPullCommand()).addCommand(buildSettingsCommand()).addCommand(buildDocsCommand());
292
+ child("repositories").addCommand(buildUpsertCommand());
293
+ attachRepositoryAttachments(child("repositories"));
294
+ // The old direct form (`nb specs push`) keeps working for pipelines already written that way; it is not advertised.
295
+ group.addCommand(buildPushCommand(), { hidden: true });
296
+ group.addCommand(buildPullCommand(), { hidden: true });
297
+ group.addCommand(buildVersionsCommand(), { hidden: true });
298
+ return group;
299
+ }
300
+ /** The old standalone `nb specs push|pull|versions` group, as it was before the tree was generated (the tests drive it). */
102
301
  export function buildSpecsCommand() {
103
302
  return new Command("specs")
104
303
  .description("The API catalog: your own OpenAPI documents (NASEBANAL Evolution)")
@@ -0,0 +1,73 @@
1
+ /**
2
+ * `nb specs specs docs push|pull|delete`: the description document of a spec (Kong Dev Portal style): ONE Markdown file per spec,
3
+ * shown rendered in the catalog beside the API reference. The catalog keeps it as text (`PUT|GET|DELETE /specs/{id}/docs`, at most
4
+ * 200 KiB of UTF-8). The spec is named like everywhere else: `--spec-id`, or `--spec <name>` with the optional `--repository`
5
+ * [`--component`] and `--group` (what is left out means none: a spec in no group, tied to no repository).
6
+ */
7
+ import { readFileSync, statSync, existsSync } from "node:fs";
8
+ import { ApiError, request } from "../http.js";
9
+ import { envTokenHint } from "../output.js";
10
+ import { headersOf, reasonOf } from "./push.js";
11
+ import { locateSpec } from "./resolve.js";
12
+ /** The catalog takes a description document up to this size (200 KiB); the CLI refuses a larger one before sending anything. */
13
+ export const MAX_DOCS_BYTES = 200 * 1024;
14
+ /** The Markdown file: it must exist, be a file, be non-empty, at most 200 KiB, valid text (no NUL byte). */
15
+ export function readDocsFile(file) {
16
+ if (!existsSync(file))
17
+ throw new Error(`--file: not found: ${file}`);
18
+ const stat = statSync(file);
19
+ if (!stat.isFile())
20
+ throw new Error(`--file: ${file} is not a file`);
21
+ if (stat.size === 0)
22
+ throw new Error(`--file: ${file} is empty`);
23
+ if (stat.size > MAX_DOCS_BYTES)
24
+ throw new Error(`--file: ${file} is ${(stat.size / 1024).toFixed(0)} KiB, more than the ${MAX_DOCS_BYTES / 1024} KiB the catalog takes for a description document`);
25
+ const bytes = readFileSync(file);
26
+ if (bytes.includes(0))
27
+ throw new Error(`--file: ${file} is not a text file (it contains a NUL byte): a description document is Markdown`);
28
+ return { text: bytes.toString("utf8"), bytes };
29
+ }
30
+ async function catalog(what, run) {
31
+ try {
32
+ return await run();
33
+ }
34
+ catch (err) {
35
+ if (err instanceof ApiError) {
36
+ const hint = err.status === 401 ? envTokenHint() : null;
37
+ const reason = err.status === 413 ? `the document is larger than ${MAX_DOCS_BYTES / 1024} KiB` : err.status === 415 ? "the catalog takes Markdown only (text/markdown)" : reasonOf(err);
38
+ throw new Error(`The catalog refused ${what}: ${reason}${hint ? `\n${hint}` : ""}`);
39
+ }
40
+ throw err;
41
+ }
42
+ }
43
+ const pathOf = (id) => `/api/v1/specs/${encodeURIComponent(id)}/docs`;
44
+ export async function docsPush(p) {
45
+ const { bytes } = readDocsFile(p.file);
46
+ return catalog("the description document", async () => {
47
+ const { spec } = await locateSpec(p.conn, p.ref);
48
+ const res = await request({ ...headersOf(p.conn), method: "PUT", path: pathOf(spec.id), rawBody: new Uint8Array(bytes), contentType: "text/markdown; charset=utf-8" });
49
+ const data = res.data.data;
50
+ return { spec_id: spec.id, spec_name: spec.name, size_bytes: data?.size_bytes ?? bytes.length, updated_at: data?.updated_at, created: res.status === 201 };
51
+ });
52
+ }
53
+ export async function docsPull(p) {
54
+ return catalog("the request", async () => {
55
+ const { spec } = await locateSpec(p.conn, p.ref);
56
+ try {
57
+ const res = await request({ ...headersOf(p.conn), method: "GET", path: pathOf(spec.id), headers: { ...headersOf(p.conn).headers, Accept: "text/markdown" }, raw: true });
58
+ return { spec_id: spec.id, spec_name: spec.name, text: res.data };
59
+ }
60
+ catch (err) {
61
+ if (err instanceof ApiError && err.status === 404)
62
+ throw new Error(`The spec '${spec.name}' has no description document (push one with 'nb specs specs docs push --file README.md').`);
63
+ throw err;
64
+ }
65
+ });
66
+ }
67
+ export async function docsDelete(p) {
68
+ return catalog("the request", async () => {
69
+ const { spec } = await locateSpec(p.conn, p.ref);
70
+ await request({ ...headersOf(p.conn), method: "DELETE", path: pathOf(spec.id) });
71
+ return { spec_id: spec.id, spec_name: spec.name };
72
+ });
73
+ }