@nasebanal/cli 0.13.0 → 0.15.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
@@ -211,6 +211,20 @@ field). `nb specs specs push` takes the API version from the document: the major
211
211
  - a breaking change is a new major (`2.0.0`): the same push makes the **v2 spec** and leaves v1 untouched; pushing a document of
212
212
  another major to a spec by `--id` is refused (`API_VERSION_MISMATCH`: register it as its own spec).
213
213
 
214
+ **A CI that names the API once: `--follow-version`.** The versions of one API are a family: each later version names the API's first
215
+ spec (its initial version) as `initial_spec_id`. Give the id of that FIRST spec and never change it:
216
+
217
+ ```bash
218
+ nb specs specs push --file openapi.yaml --id <the API's first spec> --follow-version --server-url "$API_URL"
219
+ ```
220
+
221
+ The document goes to the spec of ITS API version of that API (found by the API version, whichever spec of the family the id names).
222
+ When the API does not have that version yet the spec is made (named as the first spec is; the catalog keeps the family's group and
223
+ repository), so a new major (`2.0.0`) needs no change of the id. API versions are registered **in order**: the next one after the
224
+ highest the API has (v1, v2, then v3). A version that skips (v1, then v3) fails with the version that is next, and nothing is
225
+ registered (`--dry-run` says the same without writing): register a placeholder of the missing version first, then the real document
226
+ is a new revision of that spec afterwards. Needs `@nasebanal/api-specs-specs` 1.5.0 (`initial_spec_id`) on the catalog side.
227
+
214
228
  To maintain several API versions, keep each one on a **branch** of the repository with its own OpenAPI file, and let the same CI
215
229
  job push and report from whichever branch it runs on:
216
230
 
@@ -618,12 +632,41 @@ Overridable env vars: `NB_AUTH0_DOMAIN`, `NB_AUTH0_AUDIENCE`,
618
632
  | Option | Description |
619
633
  |--------|-------------|
620
634
  | `--env <production\|local>` | Target environment; picks the matching `servers` entry from the spec. Also `NB_ENV`. |
635
+ | `NB_<API>_BASE_URL` | The host of ONE API instead of its spec's `servers` entry (origin only; the spec's path is appended): `NB_ASSURANCE_BASE_URL=http://localhost:8791`, `NB_SPECS_BASE_URL=http://localhost:8792`, and `NB_ACCOUNT_BASE_URL` / `NB_RECORD_BASE_URL` / `NB_TARGET_BASE_URL`. `<API>` is the command group, as in `NB_<API>_ORG`. The shared `NB_BASE_URL` (one host for every API) still works but is **deprecated** and says so on stderr: pointing it at one local Worker sent every other command there too. |
621
636
  | `--token <token>` | Override stored credentials with a PAT for one invocation. |
622
637
  | `-V, --version` | Print the CLI version. |
623
638
 
624
639
  The active environment defaults to `production`; `--env local` targets the
625
640
  `wrangler dev` servers declared in each spec.
626
641
 
642
+ ## Other NASEBANAL tools (`nb secrets`, `nb quickstarts`)
643
+
644
+ `nb <name> ...` runs the program `nb-<name>` found on your `PATH`, the way `git` and `kubectl` run their extensions. NASEBANAL's other tools keep their own repositories, install and releases, and do not need Node or this package; `nb` only finds them and hands over.
645
+
646
+ ```bash
647
+ # install a tool once, from its own repository (each has a `--install` that links it into ~/.local/bin)
648
+ git clone https://github.com/nasebanal/nb-secrets.git && nb-secrets/bin/nb-secrets --install
649
+
650
+ nb secrets list ~/.secrets/deploy.env.age # = nb-secrets list ...
651
+ nb secrets -h # the tool's own usage
652
+ nb -h # lists the installed tools, and where to get the ones that are not
653
+ ```
654
+
655
+ | Tool | What it is |
656
+ |---|---|
657
+ | [`nb-secrets`](https://github.com/nasebanal/nb-secrets) | Secrets in passphrase-encrypted files, handed to a command only when you type the passphrase |
658
+ | [`nb-quickstarts`](https://github.com/nasebanal/nb-quickstarts) | Docker and Makefile quickstarts for infrastructure and testing tools |
659
+
660
+ How it behaves:
661
+
662
+ - **A built-in command always wins.** A program called `nb-auth` on `PATH` cannot take over `nb auth`; the generated API groups are protected the same way. Only the first word after `nb` is looked at (`nb secrets ...`, not `nb --env local secrets ...`).
663
+ - **Nothing is run to build the list.** `nb -h` must stay fast and must not execute whatever is called `nb-*` on your `PATH`, so a tool's one-line description is **read** from the first comment line after its shebang: `# nb-<name> - <what it does>`. A program that is not a script is listed by name only.
664
+ - **A tool is started only when you type its name**, directly (never through a shell), with your terminal, environment and exit status passed through, and `NB_PLUGIN_NAME="nb <name>"` set so it can print its usage the way it was called. Ctrl-C is left to the tool (a passphrase prompt, for example).
665
+ - **A published tool that is not installed** gets a message with its repository instead of "unknown command".
666
+ - Names are plain lowercase (`[a-z][a-z0-9-]*`); the first match on `PATH` wins; macOS and Linux only. Anything named `nb-<name>` and executable on your `PATH` runs with your rights, as with any command, so keep `PATH` to directories you trust.
667
+
668
+ To make your own: an executable `nb-<name>` on `PATH` whose second line is `# nb-<name> - <one line>`.
669
+
627
670
  ## Adding a New API
628
671
 
629
672
  1. Publish/own its spec in `nb-api-specs` (it ships as `@nasebanal/api-specs-<api>`).
package/dist/auth.js CHANGED
@@ -9,7 +9,11 @@
9
9
  */
10
10
  import { Command } from "commander";
11
11
  import { createInterface } from "node:readline";
12
- import { loadConfig, saveConfig, resolveToken, resolveEnv, configFilePath } from "./config.js";
12
+ import { loadConfig, saveConfig, resolveToken, resolveEnv, configFilePath, peekBaseUrlOverride } from "./config.js";
13
+ import { API_CATALOG } from "./apis.js";
14
+ import { resolveBaseUrl } from "./http.js";
15
+ import { loadSpec } from "./spec/loader.js";
16
+ import { specsBaseUrl } from "./specs/push.js";
13
17
  import { login } from "./oauth.js";
14
18
  import { envTokenHint } from "./output.js";
15
19
  function readSecretLine(promptText) {
@@ -90,8 +94,19 @@ export function buildAuthCommand() {
90
94
  ? "stored PAT"
91
95
  : "none";
92
96
  const masked = token ? `${token.slice(0, 10)}…${token.slice(-4)}` : "(not set)";
93
- process.stdout.write(`Environment: ${resolveEnv(config)}\n`);
97
+ const env = resolveEnv(config);
98
+ process.stdout.write(`Environment: ${env}\n`);
99
+ process.stdout.write(`Targets (the host each command calls; a NB_<API>_BASE_URL wins over the environment):\n`);
100
+ for (const line of targetLines(env))
101
+ process.stdout.write(` ${line}\n`);
94
102
  process.stdout.write(`Token: ${masked} [source: ${source}]\n`);
103
+ // The stored `nb auth login` session is shown whether or not it is the credential in use: NB_TOKEN beats it, and a
104
+ // status that hid it would make "am I logged in, and as whom" unanswerable exactly when the two disagree.
105
+ if (config.auth) {
106
+ const who = loginIdentity(config.auth.id_token) ?? "(not readable)";
107
+ const note = source === "OAuth login" ? "in use; from the login, not checked with the server" : "stored, NOT in use: another credential wins";
108
+ process.stdout.write(`Login: ${who} [${note}]\n`);
109
+ }
95
110
  if (config.auth?.expires_at) {
96
111
  const expired = config.auth.expires_at <= Date.now();
97
112
  process.stdout.write(`Expires: ${new Date(config.auth.expires_at).toLocaleString()}` +
@@ -101,3 +116,61 @@ export function buildAuthCommand() {
101
116
  });
102
117
  return auth;
103
118
  }
119
+ /**
120
+ * The word the reader is looking for, next to the URL, decided by the host itself: `*.nasebanal.com` is production, `localhost` /
121
+ * `127.0.0.1` is local, anything else (a stub, a self-hosted copy) is `other`, never claimed to be production.
122
+ */
123
+ export function hostKind(url) {
124
+ let host;
125
+ try {
126
+ host = new URL(url).hostname.toLowerCase();
127
+ }
128
+ catch {
129
+ return "other";
130
+ }
131
+ if (host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1")
132
+ return "local";
133
+ if (host === "nasebanal.com" || host.endsWith(".nasebanal.com"))
134
+ return "production";
135
+ return "other";
136
+ }
137
+ /**
138
+ * What `nb auth status` says about where the commands go: per API, the host the next command would call and whether that is
139
+ * local or production, plus which variable put it there when one did (the environment alone does not tell, because a
140
+ * NB_<API>_BASE_URL beats it).
141
+ */
142
+ export function targetLines(env) {
143
+ const width = Math.max(...API_CATALOG.map((a) => a.name.length));
144
+ return API_CATALOG.map((api) => {
145
+ // `nb specs` verbs read the catalog's host (NB_SPECS_BASE_URL only); every other group resolves from its spec's `servers`.
146
+ const peek = peekBaseUrlOverride(api.name);
147
+ const via = api.name === "specs"
148
+ ? process.env.NB_SPECS_BASE_URL?.trim()
149
+ ? { url: specsBaseUrl(env), variable: "NB_SPECS_BASE_URL" }
150
+ : undefined
151
+ : peek;
152
+ const url = api.name === "specs" ? specsBaseUrl(env) : (peek?.url ?? resolveBaseUrl(loadSpec(api.spec).servers, env));
153
+ return `${api.name.padEnd(width)} ${url} [${hostKind(url)}${via ? `, from ${via.variable}` : ""}]`;
154
+ });
155
+ }
156
+ /**
157
+ * Who a `nb auth login` was done as, `Name <email>`, read from the ID token that login stored (the payload is plain base64url JSON).
158
+ * For display only: nothing is authorized on it (the servers verify the access token's signature). null when there is no ID token
159
+ * or it cannot be read.
160
+ */
161
+ export function loginIdentity(idToken) {
162
+ const payload = idToken?.split(".")[1];
163
+ if (!payload)
164
+ return null;
165
+ try {
166
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
167
+ const email = typeof claims.email === "string" ? claims.email : "";
168
+ const name = typeof claims.name === "string" ? claims.name : typeof claims.nickname === "string" ? claims.nickname : "";
169
+ if (name && email)
170
+ return `${name} <${email}>`;
171
+ return email || name || null;
172
+ }
173
+ catch {
174
+ return null;
175
+ }
176
+ }
package/dist/config.js CHANGED
@@ -95,3 +95,33 @@ export function resolveEnv(config = loadConfig()) {
95
95
  export function configFilePath() {
96
96
  return configPath();
97
97
  }
98
+ let warnedSharedBaseUrl = false;
99
+ /**
100
+ * The host a command group talks to when the environment names one, or undefined (then the spec's own `servers` entry for the
101
+ * active environment is used). `NB_<API>_BASE_URL` is that API's alone (`NB_ASSURANCE_BASE_URL`, `NB_RECORD_BASE_URL`, ...: the
102
+ * API is the command group's name, as in `NB_<API>_ORG`). The older `NB_BASE_URL` is still read as a fallback, but it applies
103
+ * to EVERY API at once (pointing it at one local Worker sends `nb record` there too), so it is deprecated and says so, once, on stderr.
104
+ * Origin only: the spec's path is appended. A trailing slash is dropped; an empty value counts as unset.
105
+ */
106
+ export function baseUrlOverride(apiName) {
107
+ const found = peekBaseUrlOverride(apiName);
108
+ if (found?.variable === "NB_BASE_URL" && !warnedSharedBaseUrl) {
109
+ warnedSharedBaseUrl = true;
110
+ process.stderr.write(`nb: NB_BASE_URL applies to every API and is deprecated; set NB_${apiName.toUpperCase()}_BASE_URL (the host of the ${apiName} API) instead.\n`);
111
+ }
112
+ return found?.url;
113
+ }
114
+ /** The same lookup without the deprecation notice, and with the variable that supplied the host (for `nb auth status`). */
115
+ export function peekBaseUrlOverride(apiName) {
116
+ const clean = (v) => v?.trim().replace(/\/$/, "") || undefined;
117
+ const ownName = `NB_${apiName.toUpperCase()}_BASE_URL`;
118
+ const own = clean(process.env[ownName]);
119
+ if (own)
120
+ return { url: own, variable: ownName };
121
+ const shared = clean(process.env.NB_BASE_URL);
122
+ return shared ? { url: shared, variable: "NB_BASE_URL" } : undefined;
123
+ }
124
+ /** Tests: forget that the deprecation was already said. */
125
+ export function resetBaseUrlWarning() {
126
+ warnedSharedBaseUrl = false;
127
+ }
package/dist/index.js CHANGED
@@ -17,6 +17,7 @@ import { buildReportUploadCommand } from "./reports/upload.js";
17
17
  import { attachMonitorSpecOptions } from "./reports/monitors.js";
18
18
  import { attachSpecsCommands, buildSpecsCommand } from "./specs/command.js";
19
19
  import { buildUpgradeCommand, startUpdateNotifier } from "./update.js";
20
+ import { findPlugins, missingMessage, pluginCall, pluginHelp, runPlugin } from "./plugins.js";
20
21
  // Single source of truth for the version: package.json (dist/ and src/ both sit
21
22
  // next to it). A hard-coded string here drifts from the release tag.
22
23
  const { version } = createRequire(import.meta.url)("../package.json");
@@ -62,7 +63,22 @@ for (const api of API_CATALOG) {
62
63
  attachSpecsCommands(group);
63
64
  program.addCommand(group);
64
65
  }
66
+ // External tools (`nb secrets` runs `nb-secrets` from PATH). A built-in command, a generated API group included, always
67
+ // wins over a tool of the same name; `nb -h` lists what is installed (read from the scripts, nothing is run).
68
+ const reserved = new Set(["help", ...program.commands.flatMap((c) => [c.name(), ...c.aliases()])]);
69
+ program.addHelpText("after", () => pluginHelp(findPlugins(process.env.PATH, reserved)));
65
70
  async function main() {
71
+ const call = pluginCall(process.argv, process.env.PATH, reserved);
72
+ if (call) {
73
+ if ("missing" in call) {
74
+ process.stderr.write(`${missingMessage(call.missing)}\n`);
75
+ process.exitCode = 1;
76
+ }
77
+ else {
78
+ process.exitCode = await runPlugin(call.plugin, call.args);
79
+ }
80
+ return;
81
+ }
66
82
  const notifier = startUpdateNotifier(version, process.argv);
67
83
  try {
68
84
  await program.parseAsync(process.argv);
@@ -0,0 +1,176 @@
1
+ /**
2
+ * External tools: `nb <name> ...` runs the program `nb-<name>` found on PATH, the way `git` and `kubectl` do.
3
+ *
4
+ * Independent NASEBANAL tools (`nb-secrets`, `nb-quickstarts`) keep their own repositories, their own install and
5
+ * their own release; they do not need Node or this package. `nb` only finds them and hands over, so `nb secrets -h`
6
+ * shows the tool's own usage, and `nb -h` lists what is installed.
7
+ *
8
+ * Decisions that matter:
9
+ * - A built-in command always wins over a tool of the same name, so a tool cannot take over `nb auth`.
10
+ * - Nothing is executed to build the list (`nb -h` must be fast and must not run whatever happens to be called `nb-*`
11
+ * on PATH): the one-line description is READ from the first comment line of the script, `# nb-<name> - <what it does>`.
12
+ * A program that is not a script has a name and no description.
13
+ * - The program is started directly, never through a shell, and only when the user types its name.
14
+ * - macOS and Linux (executable bit, `:` in PATH). On Windows no tool is found.
15
+ */
16
+ import { spawn } from "node:child_process";
17
+ import { accessSync, closeSync, constants, openSync, readdirSync, readSync, statSync } from "node:fs";
18
+ import { delimiter, join } from "node:path";
19
+ import { constants as osConstants } from "node:os";
20
+ /** Tools NASEBANAL publishes, so `nb -h` and a mistyped call can say where to get one that is not installed. */
21
+ export const KNOWN_TOOLS = {
22
+ secrets: { repo: "https://github.com/nasebanal/nb-secrets" },
23
+ quickstarts: { repo: "https://github.com/nasebanal/nb-quickstarts" },
24
+ };
25
+ const NAME = /^[a-z][a-z0-9-]{0,30}$/;
26
+ const DESCRIPTION_MAX = 100;
27
+ /** Whether `name` could be a tool name: plain lowercase, so nothing like `../x` ever reaches the file system. */
28
+ export function isPluginName(name) {
29
+ return NAME.test(name);
30
+ }
31
+ /** The one-line description in the first comment line after the shebang (`# nb-secrets - keep secrets ...`), or "". */
32
+ export function describePlugin(file, name) {
33
+ let head = "";
34
+ try {
35
+ const fd = openSync(file, "r");
36
+ try {
37
+ const buf = Buffer.alloc(2048);
38
+ const n = readSync(fd, buf, 0, buf.length, 0);
39
+ head = buf.subarray(0, n).toString("utf8");
40
+ }
41
+ finally {
42
+ closeSync(fd);
43
+ }
44
+ }
45
+ catch {
46
+ return "";
47
+ }
48
+ if (!head.startsWith("#!"))
49
+ return ""; // a binary (or anything that is not a script) gives no description
50
+ for (const line of head.split("\n").slice(1)) {
51
+ if (!line.startsWith("#"))
52
+ return "";
53
+ const text = line.replace(/^#\s?/, "").trim();
54
+ if (text === "")
55
+ continue;
56
+ const m = /^nb-([a-z0-9-]+)\s+-\s+(.+)$/.exec(text);
57
+ // The first non-empty comment line is the description, or there is none: do not dig for one.
58
+ return m && m[1] === name ? m[2].slice(0, DESCRIPTION_MAX) : "";
59
+ }
60
+ return "";
61
+ }
62
+ function isExecutableFile(file) {
63
+ try {
64
+ if (!statSync(file).isFile())
65
+ return false; // follows a symlink
66
+ accessSync(file, constants.X_OK);
67
+ return true;
68
+ }
69
+ catch {
70
+ return false;
71
+ }
72
+ }
73
+ /**
74
+ * Every `nb-<name>` on PATH, by name. The first directory on PATH wins, a name that is not plain or that a built-in
75
+ * command already uses is skipped, and a file that is not executable is not a tool.
76
+ */
77
+ export function findPlugins(pathEnv, reserved) {
78
+ if (process.platform === "win32" || !pathEnv)
79
+ return [];
80
+ const found = new Map();
81
+ for (const dir of pathEnv.split(delimiter)) {
82
+ if (!dir)
83
+ continue;
84
+ let entries;
85
+ try {
86
+ entries = readdirSync(dir);
87
+ }
88
+ catch {
89
+ continue;
90
+ }
91
+ for (const entry of entries) {
92
+ if (!entry.startsWith("nb-"))
93
+ continue;
94
+ const name = entry.slice(3);
95
+ if (!isPluginName(name) || reserved.has(name) || found.has(name))
96
+ continue;
97
+ const file = join(dir, entry);
98
+ if (!isExecutableFile(file))
99
+ continue;
100
+ found.set(name, { name, file, description: describePlugin(file, name) });
101
+ }
102
+ }
103
+ return [...found.values()].sort((a, b) => a.name.localeCompare(b.name));
104
+ }
105
+ /**
106
+ * What `nb <name> ...` should do with the command line, or undefined to let the CLI handle it as usual.
107
+ * Only the first word after `nb` is looked at: `nb secrets run ...` is a tool call, `nb --env local secrets` is not.
108
+ */
109
+ export function pluginCall(argv, pathEnv, reserved) {
110
+ const name = argv[2];
111
+ if (!name || !isPluginName(name) || reserved.has(name))
112
+ return undefined;
113
+ const plugin = findPlugins(pathEnv, reserved).find((p) => p.name === name);
114
+ if (plugin)
115
+ return { plugin, args: argv.slice(3) };
116
+ return name in KNOWN_TOOLS ? { missing: name } : undefined;
117
+ }
118
+ /** The "Tools" part of `nb -h`: what is installed with its description, and where to get the published tools that are not. */
119
+ export function pluginHelp(plugins) {
120
+ const lines = [""];
121
+ if (plugins.length > 0) {
122
+ lines.push("Tools (programs named nb-<name> on your PATH):");
123
+ const width = Math.max(...plugins.map((p) => p.name.length)) + 2;
124
+ for (const p of plugins)
125
+ lines.push(` ${p.name.padEnd(width)}${p.description}`.trimEnd());
126
+ lines.push("Run `nb <tool> -h` for a tool's own usage.");
127
+ }
128
+ const absent = Object.entries(KNOWN_TOOLS).filter(([name]) => !plugins.some((p) => p.name === name));
129
+ if (absent.length > 0) {
130
+ if (plugins.length > 0)
131
+ lines.push("");
132
+ lines.push("Other NASEBANAL tools (not installed; `nb <tool>` runs them once they are on your PATH):");
133
+ const width = Math.max(...absent.map(([name]) => name.length)) + 2;
134
+ for (const [name, t] of absent)
135
+ lines.push(` ${name.padEnd(width)}${t.repo}`);
136
+ }
137
+ return lines.join("\n") + "\n";
138
+ }
139
+ /** What `nb <name>` says when the tool is published but not on PATH. */
140
+ export function missingMessage(name) {
141
+ return (`nb: '${name}' is not installed. It is a separate tool, run by \`nb ${name}\` as \`nb-${name}\` from your PATH.\n` +
142
+ `Get it from ${KNOWN_TOOLS[name].repo}`);
143
+ }
144
+ /**
145
+ * Run the tool with the arguments after its name, the terminal and the environment as they are (plus
146
+ * `NB_PLUGIN_NAME=nb <name>`, so a tool can print its usage the way it was called). Resolves to the exit status.
147
+ */
148
+ export function runPlugin(plugin, args) {
149
+ return new Promise((resolve) => {
150
+ const child = spawn(plugin.file, args, {
151
+ stdio: "inherit",
152
+ env: { ...process.env, NB_PLUGIN_NAME: `nb ${plugin.name}` },
153
+ });
154
+ // Ctrl-C reaches the whole foreground group: the tool decides what to do with it (a passphrase prompt, say), and
155
+ // `nb` waits for it instead of leaving first. A terminate request is passed on.
156
+ const ignoreInterrupt = () => undefined;
157
+ const forwardTerminate = () => child.kill("SIGTERM");
158
+ process.on("SIGINT", ignoreInterrupt);
159
+ process.on("SIGTERM", forwardTerminate);
160
+ const done = (status) => {
161
+ process.off("SIGINT", ignoreInterrupt);
162
+ process.off("SIGTERM", forwardTerminate);
163
+ resolve(status);
164
+ };
165
+ child.on("error", (err) => {
166
+ process.stderr.write(`nb: cannot run ${plugin.file}: ${err.message}\n`);
167
+ done(126);
168
+ });
169
+ child.on("close", (code, signal) => {
170
+ if (code !== null)
171
+ return done(code);
172
+ const sig = signal ? osConstants.signals[signal] : undefined;
173
+ done(sig ? 128 + sig : 1);
174
+ });
175
+ });
176
+ }
@@ -17,7 +17,7 @@
17
17
  import { Command, Option } from "commander";
18
18
  import { existsSync, lstatSync, readFileSync, readdirSync } from "node:fs";
19
19
  import { basename, dirname, join } from "node:path";
20
- import { resolveAccessToken, resolveEnv } from "../config.js";
20
+ import { baseUrlOverride, resolveAccessToken, resolveEnv } from "../config.js";
21
21
  import { request, resolveBaseUrl, ApiError } from "../http.js";
22
22
  import { loadSpec } from "../spec/loader.js";
23
23
  import { exportGithubOutput, printJson } from "../output.js";
@@ -493,8 +493,7 @@ export function buildReportUploadCommand() {
493
493
  process.stderr.write(`(dry run) ${basename(dirname(file)) || "."}/${basename(file)}: ${parsed.note}\n`);
494
494
  return;
495
495
  }
496
- const override = process.env.NB_BASE_URL?.replace(/\/$/, "");
497
- const baseUrl = override ?? resolveBaseUrl(loadSpec("assurance.yaml").servers, env);
496
+ const baseUrl = baseUrlOverride("assurance") ?? resolveBaseUrl(loadSpec("assurance.yaml").servers, env);
498
497
  // Assurance and the catalog act for the same owner: the organization goes to both (personal is the default and sent as is).
499
498
  const orgHeaders = org === "personal" ? undefined : { "X-Active-Organization-Id": org };
500
499
  const hits = opts.allSpecs ? await resolveRepositorySpecs(specsConn, ref) : [await resolveSpec(specsConn, ref)];
@@ -31,7 +31,7 @@ import { Command } from "commander";
31
31
  import { readFileSync } from "node:fs";
32
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) {
@@ -151,11 +151,10 @@ function attachLeaf(parent, name, pathTemplate, method, op, servers, parameters,
151
151
  const opts = command.optsWithGlobals();
152
152
  const env = opts.env || resolveEnv();
153
153
  const token = opts.token || (await resolveAccessToken());
154
- // 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
155
155
  // path is still appended). Used by the CDD contract test to point the CLI at
156
- // a Specmatic stub, and available for advanced/self-hosted setups.
157
- const override = process.env.NB_BASE_URL?.replace(/\/$/, "");
158
- 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);
159
158
  let realPath = pathTemplate;
160
159
  params.forEach((p, i) => {
161
160
  realPath = realPath.replace(`{${p}}`, encodeURIComponent(positionals[i]));
@@ -22,6 +22,7 @@ export function buildPushCommand() {
22
22
  .requiredOption("--file <path>", "the OpenAPI document (YAML or JSON, up to 2 MiB)")
23
23
  .option("--name <name>", "the spec's name in the catalog (default: the document's info.title, then the file's name)")
24
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")
25
26
  .option("--rename", "with --id: also rename the spec to --name (default: the document's info.title) when it is called something else")
26
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")
27
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")
@@ -50,6 +51,7 @@ export function buildPushCommand() {
50
51
  note: opts.note ?? ciNote(ci, undefined),
51
52
  id: opts.id,
52
53
  rename: opts.rename,
54
+ followVersion: opts.followVersion,
53
55
  // A name asked for wins over the id the pipeline's variable carries.
54
56
  repositoryId: opts.repository ? undefined : (opts.repositoryId ?? (process.env.NB_REPOSITORY_ID?.trim() || undefined)),
55
57
  repository: opts.repository,
@@ -226,7 +226,64 @@ export async function pushSpec(p) {
226
226
  throw err;
227
227
  }
228
228
  }
229
+ /** The number in an API version ("v2" -> 2), or null when it is not of that form (a calendar version). */
230
+ function versionNumber(v) {
231
+ const m = /^[vV](\d{1,3})$/.exec(v.trim());
232
+ return m ? Number.parseInt(m[1], 10) : null;
233
+ }
234
+ /**
235
+ * `--follow-version`: the spec of the document's API version in the family of the spec `p.id` names (its initial version, or any spec of the
236
+ * API: the family is found from it). Found: the push goes to that spec. Not there: it is made after the highest version the API has, with
237
+ * `initial_spec_id`, named as the initial spec is (the catalog keeps the group and the repository of the family); a version that is not the
238
+ * next one is refused here as the catalog refuses it (INITIAL_VERSION_NOT_NEXT), which is also what a dry run says.
239
+ */
240
+ async function pushFollowingVersion(p) {
241
+ if (!p.id)
242
+ throw new Error("--follow-version needs --id: the id of the API's first spec");
243
+ let text = readSpecFile(p.file);
244
+ const explicitVersion = p.apiVersion !== undefined ? checkApiVersion(p.apiVersion) : undefined;
245
+ const apiVersion = explicitVersion ?? apiVersionOf(text) ?? undefined;
246
+ if (apiVersion === undefined) {
247
+ throw new Error("--follow-version needs the document's API version (a major such as 2.0.0 -> v2): say which with --api-version <v1|v2|...>");
248
+ }
249
+ const given = (await findSpec(p.conn, "", p.id));
250
+ const initialId = given.initial_spec_id ?? given.id;
251
+ const res = await request({ ...headersOf(p.conn), method: "GET", path: "/api/v1/specs" });
252
+ const family = res.data.data.data.filter((s) => s.id === initialId || s.initial_spec_id === initialId);
253
+ const initial = family.find((s) => s.id === initialId) ?? given;
254
+ const found = family.find((s) => sameApiVersion(s.api_version ?? "v1", apiVersion));
255
+ if (found)
256
+ return pushSpecInner({ ...p, followVersion: false, id: found.id });
257
+ // Not there yet: it must be the next one after the highest the API has.
258
+ const numbers = family.map((s) => versionNumber(s.api_version ?? "v1")).filter((n) => n !== null);
259
+ const wanted = versionNumber(apiVersion);
260
+ if (wanted !== null && numbers.length > 0 && wanted !== Math.max(...numbers) + 1) {
261
+ throw new Error(`The next API version of '${initial.name}' is v${Math.max(...numbers) + 1}, not ${apiVersion}: register the versions in order (a placeholder document will do for one that is not ready). Nothing was registered.`);
262
+ }
263
+ if (p.serverUrl !== undefined)
264
+ text = setServers(text, checkServerUrl(p.serverUrl)).text;
265
+ const hash = hashText(text);
266
+ const served = p.serverUrl ? { server_url: checkServerUrl(p.serverUrl) } : {};
267
+ if (p.dryRun) {
268
+ return { id: "(new)", name: initial.name, version: 1, api_version: apiVersion, group_id: initial.group_id, action: "created", content_hash: hash, repository_id: initial.repository_id ?? null, ...served };
269
+ }
270
+ try {
271
+ const created = await request({
272
+ ...headersOf(p.conn),
273
+ method: "POST",
274
+ path: "/api/v1/specs",
275
+ body: { name: initial.name, content: text, initial_spec_id: initialId, ...(explicitVersion ? { api_version: explicitVersion } : {}), ...(p.description ? { description: p.description } : {}) },
276
+ });
277
+ const row = created.data.data;
278
+ return { id: row.id, name: row.name, version: 1, api_version: row.api_version ?? apiVersion, group_id: row.group_id ?? null, action: "created", content_hash: hash, repository_id: row.repository_id ?? null, ...served };
279
+ }
280
+ catch (err) {
281
+ throw new Error(`The catalog refused the spec: ${reasonOf(err)}`);
282
+ }
283
+ }
229
284
  async function pushSpecInner(p) {
285
+ if (p.followVersion)
286
+ return pushFollowingVersion(p);
230
287
  let text = readSpecFile(p.file);
231
288
  let serverUrl;
232
289
  let serversEdit;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nasebanal/cli",
3
- "version": "0.13.0",
3
+ "version": "0.15.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",