@nasebanal/cli 0.7.0 → 0.9.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
@@ -161,6 +161,37 @@ It is made to run on **every commit**:
161
161
  happen. `NB_SPECS_BASE_URL` points it at another host (local: `http://localhost:8792`).
162
162
  - In GitHub Actions the spec's id is written to `$GITHUB_OUTPUT` as `spec_id`.
163
163
 
164
+ ### Reading a version back (`nb specs pull`, `nb specs versions`)
165
+
166
+ A pipeline can work from the catalog's document instead of a copy kept in a repository (a
167
+ contract test with Specmatic against the API's provider side, a stub for a consumer, a client
168
+ generator):
169
+
170
+ ```bash
171
+ nb specs versions --name "Billing API" # versions newest first, each with its sha256
172
+ nb specs pull --name "Billing API" --spec-version 3 --out spec.yaml
173
+ nb specs pull --id kMsl4TXEMmeN --spec-version 3 --hash <sha256> --out spec.yaml # pinned: fails if it differs
174
+ nb specs pull --name "Billing API" > spec.yaml # latest; the document is all of stdout
175
+ ```
176
+
177
+ - **`--spec-version` is the catalog's version number** (1, 2, 3...: one per `nb specs push` that
178
+ changed the document). It is not the API's URL version (`v1`, `v2`, the label of a test result
179
+ in `nb assurance report upload --api-version`), not the document's own `info.version`, and not
180
+ the CLI's own `nb --version`.
181
+ Absent or `latest` is the newest; **pin a number in a pipeline**, `latest` moves.
182
+ - **The document comes back exactly as it was uploaded** (the bytes: a JSON document is not
183
+ parsed and re-printed), and its SHA-256 is checked against the `content_hash` the catalog keeps
184
+ for that version, so a document that did not arrive intact fails. `--hash <sha256>` pins what
185
+ the pipeline expects, so a version that was replaced, or a name that now points at another
186
+ spec, fails instead of testing the wrong thing. `nb specs versions` prints the hashes.
187
+ - A spec is named by `--id` (a rename cannot change it) or by `--name` (matched ignoring case).
188
+ `--org <id|personal>` / `$NB_SPECS_ORG` and `NB_SPECS_BASE_URL` work as for `push`. With `--out`
189
+ the details are printed as JSON; without it they go to stderr. In GitHub Actions `spec_id`,
190
+ `spec_version` and `spec_hash` are written to `$GITHUB_OUTPUT`.
191
+ - The catalog has no "released" mark yet: unlike the `@nasebanal/api-specs-*` packages, which
192
+ only advance once the provider has deployed, a pull of `latest` can return a version that
193
+ nothing implements. Pinning a version (and its hash) is the safe way to use it today.
194
+
164
195
  ## Installation
165
196
 
166
197
  The CLI installs the `nb` command. Node ≥ 20 is required.
package/dist/http.js CHANGED
@@ -45,7 +45,7 @@ export async function request(opts) {
45
45
  }
46
46
  const text = await res.text();
47
47
  let data = text;
48
- if (text) {
48
+ if (text && !(opts.raw && res.ok)) {
49
49
  try {
50
50
  data = JSON.parse(text);
51
51
  }
@@ -2,10 +2,12 @@
2
2
  * `nb specs` - the API catalog (your own OpenAPI documents) from the command line. Hand-written: the CLI's generated
3
3
  * command tree comes from the pinned contracts, and the catalog's is not among them.
4
4
  */
5
+ import { writeFileSync } from "node:fs";
5
6
  import { Command } from "commander";
6
7
  import { resolveAccessToken, resolveEnv } from "../config.js";
7
8
  import { exportGithubOutput, printJson } from "../output.js";
8
9
  import { detectCi } from "../reports/ci.js";
10
+ import { parseHash, parseVersion, pullSpec, specVersions } from "./pull.js";
9
11
  import { checkOrg, ciNote, pushSpec, specsBaseUrl } from "./push.js";
10
12
  export function buildPushCommand() {
11
13
  return new Command("push")
@@ -39,6 +41,66 @@ export function buildPushCommand() {
39
41
  process.stderr.write(`${opts.dryRun ? "(dry run) " : ""}✓ ${result.name} -> ${what}\n`);
40
42
  });
41
43
  }
44
+ async function connection(opts) {
45
+ const env = opts.env || resolveEnv();
46
+ const token = opts.token || (await resolveAccessToken());
47
+ return { baseUrl: specsBaseUrl(env), token, org: checkOrg(opts.org ?? process.env.NB_SPECS_ORG) };
48
+ }
49
+ export function buildPullCommand() {
50
+ return new Command("pull")
51
+ .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)")
52
+ .option("--id <id>", "the spec, by id (a rename cannot change it)")
53
+ .option("--name <name>", "the spec, by its name in the catalog (matched ignoring case)")
54
+ .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")
55
+ .option("--hash <sha256>", "the SHA-256 the document must have (as 'nb specs versions' prints it): the pull fails when it differs")
56
+ .option("--out <file>", "write the document here (default: to standard output, the details to standard error)")
57
+ .option("--org <id>", "the organization whose catalog it is (an id), or 'personal' (default; or $NB_SPECS_ORG)")
58
+ .action(async (_flags, command) => {
59
+ const opts = command.optsWithGlobals();
60
+ const result = await pullSpec({
61
+ conn: await connection(opts),
62
+ id: opts.id,
63
+ name: opts.name,
64
+ version: parseVersion(opts.specVersion),
65
+ hash: parseHash(opts.hash),
66
+ });
67
+ const { text, ...details } = result;
68
+ if (opts.out) {
69
+ try {
70
+ writeFileSync(opts.out, text);
71
+ }
72
+ catch (err) {
73
+ throw new Error(`--out: cannot write ${opts.out}: ${err.message}`);
74
+ }
75
+ printJson({ ...details, out: opts.out });
76
+ }
77
+ else {
78
+ process.stdout.write(text);
79
+ }
80
+ exportGithubOutput("spec_id", result.id);
81
+ exportGithubOutput("spec_version", String(result.version));
82
+ exportGithubOutput("spec_hash", result.content_hash);
83
+ process.stderr.write(`✓ ${result.name} v${result.version} (sha256 ${result.content_hash.slice(0, 12)}..., ${result.size_bytes} bytes)${opts.out ? ` -> ${opts.out}` : ""}\n`);
84
+ });
85
+ }
86
+ export function buildVersionsCommand() {
87
+ return new Command("versions")
88
+ .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)")
89
+ .option("--id <id>", "the spec, by id")
90
+ .option("--name <name>", "the spec, by its name in the catalog (matched ignoring case)")
91
+ .option("--org <id>", "the organization whose catalog it is (an id), or 'personal' (default; or $NB_SPECS_ORG)")
92
+ .action(async (_flags, command) => {
93
+ const opts = command.optsWithGlobals();
94
+ const result = await specVersions({ conn: await connection(opts), id: opts.id, name: opts.name });
95
+ printJson(result);
96
+ const latest = result.versions[0];
97
+ process.stderr.write(`✓ ${result.name}: ${result.versions.length} version${result.versions.length === 1 ? "" : "s"}${latest ? ` (latest v${latest.version})` : ""}\n`);
98
+ });
99
+ }
42
100
  export function buildSpecsCommand() {
43
- return new Command("specs").description("The API catalog: your own OpenAPI documents (NASEBANAL Evolution)").addCommand(buildPushCommand());
101
+ return new Command("specs")
102
+ .description("The API catalog: your own OpenAPI documents (NASEBANAL Evolution)")
103
+ .addCommand(buildPushCommand())
104
+ .addCommand(buildPullCommand())
105
+ .addCommand(buildVersionsCommand());
44
106
  }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * `nb specs pull` / `nb specs versions` - read a document back out of the API catalog (nb-specs-api), the other half of
3
+ * `nb specs push`: a pipeline asks the catalog for a given version of an API's document and works from that (a contract
4
+ * test with Specmatic, a client generator) instead of from a copy that lives in some repository.
5
+ *
6
+ * - a spec is named by `--id` (what a rename cannot change) or by `--name` (matched ignoring case, like push)
7
+ * - `--spec-version` is the catalog's version NUMBER (1, 2, 3...: one per `nb specs push` that changed the document),
8
+ * not the API's URL version (`v1`, `v2`) and not the document's own `info.version`; absent or `latest` = the newest
9
+ * - the document comes back exactly as it was uploaded (the bytes, not a re-serialised copy), and its SHA-256 is
10
+ * checked against the `content_hash` the catalog keeps for that version; `--hash` pins what a pipeline expects, so
11
+ * a version that was swapped, or a name that now points somewhere else, fails instead of testing the wrong thing
12
+ */
13
+ import { ApiError, request } from "../http.js";
14
+ import { envTokenHint } from "../output.js";
15
+ import { findSpec, hashText, headersOf, reasonOf } from "./push.js";
16
+ /** `--spec-version`: a positive whole number, or `latest` (or nothing) for the newest. Returns undefined for the newest. */
17
+ export function parseVersion(raw) {
18
+ const v = raw?.trim();
19
+ if (v === undefined || v === "" || v.toLowerCase() === "latest")
20
+ return undefined;
21
+ if (/^[1-9]\d{0,8}$/.test(v))
22
+ return Number(v);
23
+ throw new Error(`--spec-version '${raw}' must be a version number (1, 2, 3...) or 'latest'. It is the catalog's version, not the API's v1 / v2`);
24
+ }
25
+ /** `--hash`: 64 hex characters (case does not matter). Returns it lower-cased, or undefined when none was asked. */
26
+ export function parseHash(raw) {
27
+ const v = raw?.trim();
28
+ if (v === undefined || v === "")
29
+ return undefined;
30
+ if (/^[0-9a-fA-F]{64}$/.test(v))
31
+ return v.toLowerCase();
32
+ throw new Error(`--hash '${raw}' must be a SHA-256: 64 hexadecimal characters (the content_hash that 'nb specs versions' prints)`);
33
+ }
34
+ /** Whatever the catalog refuses comes back with its own reason, and the token hint on a 401, not a bare "403 Forbidden". */
35
+ async function refusal(what, run) {
36
+ try {
37
+ return await run();
38
+ }
39
+ catch (err) {
40
+ if (err instanceof ApiError) {
41
+ const hint = err.status === 401 ? envTokenHint() : null;
42
+ throw new Error(`The catalog refused ${what}: ${reasonOf(err)}${hint ? `\n${hint}` : ""}`);
43
+ }
44
+ throw err;
45
+ }
46
+ }
47
+ async function resolveSpec(conn, id, name) {
48
+ if (!id && !name?.trim())
49
+ throw new Error("Say which spec: --id <id> or --name <name> (the name is the spec's title in the catalog)");
50
+ const spec = await findSpec(conn, name?.trim() ?? "", id);
51
+ if (!spec) {
52
+ throw new Error(`No spec named '${name}' in the catalog (names match ignoring case; check --org: the catalog is per owner, and 'nb specs versions' needs the exact name or the id).`);
53
+ }
54
+ return spec;
55
+ }
56
+ async function listVersions(conn, spec) {
57
+ const res = await request({ ...headersOf(conn), method: "GET", path: `/api/v1/specs/${encodeURIComponent(spec.id)}/versions` });
58
+ return res.data.data.data;
59
+ }
60
+ /** The versions of a spec, newest first, each with the SHA-256 of its document (what `--hash` pins). */
61
+ export async function specVersions(p) {
62
+ return refusal("the request", async () => {
63
+ const spec = await resolveSpec(p.conn, p.id, p.name);
64
+ return { id: spec.id, name: spec.name, versions: await listVersions(p.conn, spec) };
65
+ });
66
+ }
67
+ /** A version's document exactly as uploaded, verified against the catalog's hash (and `--hash`). */
68
+ export async function pullSpec(p) {
69
+ return refusal("the request", async () => {
70
+ const spec = await resolveSpec(p.conn, p.id, p.name);
71
+ const versions = await listVersions(p.conn, spec);
72
+ if (versions.length === 0)
73
+ throw new Error(`Spec '${spec.name}' has no versions.`);
74
+ const picked = p.version === undefined ? versions[0] : versions.find((v) => v.version === p.version);
75
+ if (!picked) {
76
+ throw new Error(`Spec '${spec.name}' has no version ${p.version} (it has ${versions.map((v) => v.version).join(", ")}). The version is the catalog's number: 'nb specs versions' lists them.`);
77
+ }
78
+ const res = await request({
79
+ ...headersOf(p.conn),
80
+ method: "GET",
81
+ path: `/api/v1/specs/${encodeURIComponent(spec.id)}/versions/${picked.version}/content`,
82
+ raw: true,
83
+ });
84
+ const text = res.data;
85
+ const hash = hashText(text);
86
+ // The catalog keeps the hash of what it stored: a document that does not match it was damaged on the way.
87
+ if (picked.content_hash && hash !== picked.content_hash) {
88
+ throw new Error(`The document of '${spec.name}' v${picked.version} has SHA-256 ${hash}, not the ${picked.content_hash} the catalog lists for it: it did not arrive intact.`);
89
+ }
90
+ // And the one a pipeline pinned: the version, or what the name points at, is no longer what it expected.
91
+ if (p.hash && hash !== p.hash) {
92
+ throw new Error(`The document of '${spec.name}' v${picked.version} has SHA-256 ${hash}, not the ${p.hash} you pinned with --hash: the version was replaced, or the name now points at another spec.`);
93
+ }
94
+ return { id: spec.id, name: spec.name, version: picked.version, content_hash: hash, size_bytes: Buffer.byteLength(text, "utf8"), text };
95
+ });
96
+ }
@@ -73,16 +73,16 @@ export function specNameFor(text, file, asked) {
73
73
  throw new Error("The spec has no name: pass --name");
74
74
  return name.slice(0, 100);
75
75
  }
76
- function headersOf(conn) {
76
+ export function headersOf(conn) {
77
77
  return { baseUrl: conn.baseUrl, token: conn.token, headers: { "X-Active-Organization-Id": conn.org } };
78
78
  }
79
- function reasonOf(err) {
79
+ export function reasonOf(err) {
80
80
  if (err instanceof ApiError)
81
81
  return err.data?.error?.message ?? err.message;
82
82
  return err.message;
83
83
  }
84
84
  const codeOf = (err) => (err instanceof ApiError ? err.data?.error?.code : undefined);
85
- async function findSpec(conn, name, id) {
85
+ export async function findSpec(conn, name, id) {
86
86
  if (id) {
87
87
  try {
88
88
  const res = await request({ ...headersOf(conn), method: "GET", path: `/api/v1/specs/${encodeURIComponent(id)}` });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nasebanal/cli",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "gcloud-style command-line interface for NASEBANAL APIs, generated from nb-api-specs OpenAPI contracts.",
5
5
  "license": "MIT",
6
6
  "type": "module",