@nasebanal/cli 0.11.0 → 0.13.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 +271 -73
- package/dist/apis.js +2 -1
- package/dist/index.js +12 -3
- package/dist/reports/monitors.js +57 -0
- package/dist/reports/upload.js +137 -245
- package/dist/spec/build.js +61 -7
- package/dist/specs/apiVersion.js +38 -0
- package/dist/specs/command.js +210 -13
- package/dist/specs/docs.js +73 -0
- package/dist/specs/pull.js +18 -13
- package/dist/specs/push.js +170 -16
- package/dist/specs/resolve.js +182 -0
- package/dist/specs/servers.js +88 -0
- package/dist/specs/settings.js +48 -0
- package/package.json +1 -1
- package/specs/account.yaml +90 -1
- package/specs/assurance.yaml +240 -1215
- package/specs/specs.yaml +1574 -0
- package/specs/target.yaml +2 -2
package/dist/specs/push.js
CHANGED
|
@@ -3,12 +3,24 @@
|
|
|
3
3
|
* wants it: no group has to exist, nothing is uploaded when the file is already the latest version, and running it on
|
|
4
4
|
* every commit is safe.
|
|
5
5
|
*
|
|
6
|
-
* - the spec is found by
|
|
6
|
+
* - the spec is found by its key (or by `--id`): its group, its repository row, its API VERSION and its name; new -> created with
|
|
7
|
+
* its first revision (and the group, the repository and the spec are all made on the first run), known -> a new revision. The
|
|
8
|
+
* API version is what the document's `info.version` gives (1.8.0 -> v1; see apiVersion.ts), or `--api-version`: a document of
|
|
9
|
+
* another major makes (first-run semantics) the NEW spec for that API version and never touches the other one. The same name
|
|
10
|
+
* may exist in other groups (an environment each) and at other API versions; a group left out means "the specs in no group",
|
|
11
|
+
* not any group, and a name that exists only in groups is an error that lists them instead of silently making a second spec
|
|
7
12
|
* - the document's SHA-256 is compared with the latest version's `content_hash` BEFORE anything is sent: the same
|
|
8
13
|
* bytes mean "unchanged", and the 2 MiB stay where they are. (The server refuses an identical upload with
|
|
9
14
|
* 409 UNCHANGED too; that is treated as "unchanged", for two jobs racing.)
|
|
10
|
-
* - a group is optional: `--group <name>`
|
|
11
|
-
* exists is never moved by a push (moving is the catalog's job).
|
|
15
|
+
* - a group is optional: `--group <name>` is part of the key (the spec is looked up in that group) and files a NEW spec there
|
|
16
|
+
* (the group is made when missing); a spec that already exists is never moved by a push (moving is the catalog's job).
|
|
17
|
+
* - `--server-url <url>` replaces the document's top-level `servers` before it is sent (see servers.ts): one OpenAPI file in the
|
|
18
|
+
* repository, one URL per environment.
|
|
19
|
+
* - a repository is optional too: `--repository-id <id>` (or `$NB_REPOSITORY_ID`) ties the spec to that repository, and
|
|
20
|
+
* `--repository <name> [--component <name>]` (the key of a repository is provider + name + component; no component = the
|
|
21
|
+
* repository as a whole) registers the repository first (an idempotent upsert) and uses the id it returns. A NEW spec
|
|
22
|
+
* is created tied to it; an existing spec with no repository is tied to it; one tied to ANOTHER repository is left
|
|
23
|
+
* where it is and the result says so (a push never moves a spec).
|
|
12
24
|
*/
|
|
13
25
|
import { createHash } from "node:crypto";
|
|
14
26
|
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
@@ -16,9 +28,12 @@ import { basename, extname } from "node:path";
|
|
|
16
28
|
import { parse } from "yaml";
|
|
17
29
|
import { ApiError, request } from "../http.js";
|
|
18
30
|
import { envTokenHint } from "../output.js";
|
|
31
|
+
import { apiVersionOf, checkApiVersion, sameApiVersion } from "./apiVersion.js";
|
|
32
|
+
import { checkServerUrl, setServers } from "./servers.js";
|
|
19
33
|
/** The catalog takes documents up to this size (2 MiB); the CLI refuses a larger one before sending anything. */
|
|
20
34
|
export const MAX_SPEC_BYTES = 2 * 1024 * 1024;
|
|
21
35
|
const MAX_NOTE = 500;
|
|
36
|
+
export const REPOSITORY_PROVIDERS = ["github", "gitlab", "bitbucket", "other"];
|
|
22
37
|
/** The catalog's host for the active environment (`NB_SPECS_BASE_URL` overrides; the CLI ships no spec for this API). */
|
|
23
38
|
export function specsBaseUrl(env) {
|
|
24
39
|
const override = process.env.NB_SPECS_BASE_URL?.replace(/\/$/, "");
|
|
@@ -82,7 +97,56 @@ export function reasonOf(err) {
|
|
|
82
97
|
return err.message;
|
|
83
98
|
}
|
|
84
99
|
const codeOf = (err) => (err instanceof ApiError ? err.data?.error?.code : undefined);
|
|
85
|
-
|
|
100
|
+
/** `--provider`: one of the four the catalog knows. */
|
|
101
|
+
export function checkProvider(raw) {
|
|
102
|
+
const v = (raw?.trim() || "github").toLowerCase();
|
|
103
|
+
if (REPOSITORY_PROVIDERS.includes(v))
|
|
104
|
+
return v;
|
|
105
|
+
throw new Error(`--provider '${raw}' must be one of: ${REPOSITORY_PROVIDERS.join(", ")}`);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Register a repository by provider and name and answer with it; the same pair always answers the same id, so it is safe
|
|
109
|
+
* on every run. `created` says whether this call made it (201) or it was already there (200). Never overwrites what is set.
|
|
110
|
+
*/
|
|
111
|
+
export async function upsertRepository(conn, provider, name, component = "", attachments) {
|
|
112
|
+
try {
|
|
113
|
+
const res = await request({ ...headersOf(conn), method: "PUT", path: "/api/v1/repositories", body: { provider, name, ...(component ? { component } : {}), ...(attachments !== undefined ? { attachments_enabled: attachments } : {}) } });
|
|
114
|
+
return { ...res.data.data, created: res.status === 201 };
|
|
115
|
+
}
|
|
116
|
+
catch (err) {
|
|
117
|
+
if (err instanceof ApiError)
|
|
118
|
+
throw new Error(`The catalog refused the repository: ${reasonOf(err)}`);
|
|
119
|
+
throw err;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/** A repository by provider and name without registering it (for a dry run); null when it is not registered. */
|
|
123
|
+
export async function findRepository(conn, provider, name, component = "") {
|
|
124
|
+
const res = await request({ ...headersOf(conn), method: "GET", path: "/api/v1/repositories" });
|
|
125
|
+
const list = res.data.data.data;
|
|
126
|
+
return list.find((r) => r.provider === provider && r.name.toLowerCase() === name.toLowerCase() && (r.component ?? "").toLowerCase() === component.toLowerCase()) ?? null;
|
|
127
|
+
}
|
|
128
|
+
/** The id of the repository a push should tie to: the id given, or the one `--repository` names (registered unless a dry run). */
|
|
129
|
+
async function repositoryIdFor(p) {
|
|
130
|
+
if (p.repositoryId)
|
|
131
|
+
return p.repositoryId;
|
|
132
|
+
if (!p.repository)
|
|
133
|
+
return null;
|
|
134
|
+
const provider = p.provider ?? "github";
|
|
135
|
+
if (p.dryRun)
|
|
136
|
+
return (await findRepository(p.conn, provider, p.repository, p.component))?.id ?? "(new)";
|
|
137
|
+
return (await upsertRepository(p.conn, provider, p.repository, p.component)).id;
|
|
138
|
+
}
|
|
139
|
+
/** Several specs carry this name (under different repositories) and no repository says which: nothing is picked silently. */
|
|
140
|
+
export class AmbiguousSpecError extends Error {
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* A spec by name, or by id. The same name may exist under different repositories, so a name is looked up inside the repository
|
|
144
|
+
* asked for (`scope.repositoryId`): that row's specs only (a spec with no repository is not adopted by a push that names one).
|
|
145
|
+
* With no repository asked, a spec with no repository wins; otherwise the name must match exactly one spec, or the error names
|
|
146
|
+
* the repositories that hold it and asks for --repository or --id. `scope.apiVersion` is part of the key: only the specs of that API
|
|
147
|
+
* version are looked at, so a name that exists at another API version is not a match (the push then makes the new spec).
|
|
148
|
+
*/
|
|
149
|
+
export async function findSpec(conn, name, id, scope) {
|
|
86
150
|
if (id) {
|
|
87
151
|
try {
|
|
88
152
|
const res = await request({ ...headersOf(conn), method: "GET", path: `/api/v1/specs/${encodeURIComponent(id)}` });
|
|
@@ -96,7 +160,43 @@ export async function findSpec(conn, name, id) {
|
|
|
96
160
|
}
|
|
97
161
|
const res = await request({ ...headersOf(conn), method: "GET", path: "/api/v1/specs" });
|
|
98
162
|
const list = res.data.data.data;
|
|
99
|
-
|
|
163
|
+
const named = list.filter((s) => s.name.toLowerCase() === name.toLowerCase() && (scope?.apiVersion === undefined || sameApiVersion(s.api_version ?? "v1", scope.apiVersion)));
|
|
164
|
+
const grouped = scope?.groupId !== undefined;
|
|
165
|
+
const pool = !grouped ? named : scope.groupId === "(new)" ? [] : named.filter((s) => (s.group_id ?? null) === scope.groupId);
|
|
166
|
+
let found;
|
|
167
|
+
if (scope?.repositoryId) {
|
|
168
|
+
found = scope.repositoryId === "(new)" ? null : (pool.find((s) => s.repository_id === scope.repositoryId) ?? null);
|
|
169
|
+
}
|
|
170
|
+
else if (pool.length <= 1) {
|
|
171
|
+
found = pool[0] ?? null;
|
|
172
|
+
}
|
|
173
|
+
else {
|
|
174
|
+
const without = pool.filter((s) => !s.repository_id);
|
|
175
|
+
if (without.length > 0)
|
|
176
|
+
found = without[0];
|
|
177
|
+
else {
|
|
178
|
+
const rows = await repositoriesOf(conn);
|
|
179
|
+
const groups = (await request({ ...headersOf(conn), method: "GET", path: "/api/v1/groups" })).data.data.data;
|
|
180
|
+
const where = pool.map((s) => {
|
|
181
|
+
const r = rows.find((x) => x.id === s.repository_id);
|
|
182
|
+
const g = s.group_id ? `group '${groups.find((x) => x.id === s.group_id)?.name ?? s.group_id}'` : "no group";
|
|
183
|
+
return `${g} / ${r ? `${r.provider} ${r.name}${r.component ? ` / ${r.component}` : ""}` : `repository ${s.repository_id}`}`;
|
|
184
|
+
});
|
|
185
|
+
throw new AmbiguousSpecError(`More than one spec is named '${name}' (${where.join("; ")}): say which with --group, --repository [--component], or --id.`);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (found || !grouped || scope.groupExplicit)
|
|
189
|
+
return found;
|
|
190
|
+
// No group was named and the name is not among the specs in no group: if it exists in groups, say so rather than make a second spec.
|
|
191
|
+
const others = scope?.repositoryId && scope.repositoryId !== "(new)" ? named.filter((s) => s.repository_id === scope.repositoryId) : scope?.repositoryId ? [] : named;
|
|
192
|
+
if (others.length === 0)
|
|
193
|
+
return null;
|
|
194
|
+
const groups = (await request({ ...headersOf(conn), method: "GET", path: "/api/v1/groups" })).data.data.data;
|
|
195
|
+
const where = others.map((s) => (s.group_id ? `group '${groups.find((g) => g.id === s.group_id)?.name ?? s.group_id}'` : "no group"));
|
|
196
|
+
throw new AmbiguousSpecError(`A spec named '${name}' exists in ${[...new Set(where)].join(", ")}, but not in the specs with no group: pass --group <name> (the group is part of the spec's key; leaving it out means no group) or --id.`);
|
|
197
|
+
}
|
|
198
|
+
async function repositoriesOf(conn) {
|
|
199
|
+
return (await request({ ...headersOf(conn), method: "GET", path: "/api/v1/repositories" })).data.data.data;
|
|
100
200
|
}
|
|
101
201
|
/** The id of the owner's group of that name, made when there is none. Refuses (with the catalog's reason) at the limit. */
|
|
102
202
|
async function groupIdFor(conn, name, create) {
|
|
@@ -127,13 +227,54 @@ export async function pushSpec(p) {
|
|
|
127
227
|
}
|
|
128
228
|
}
|
|
129
229
|
async function pushSpecInner(p) {
|
|
130
|
-
|
|
230
|
+
let text = readSpecFile(p.file);
|
|
231
|
+
let serverUrl;
|
|
232
|
+
let serversEdit;
|
|
233
|
+
if (p.serverUrl !== undefined) {
|
|
234
|
+
serverUrl = checkServerUrl(p.serverUrl);
|
|
235
|
+
const edited = setServers(text, serverUrl);
|
|
236
|
+
text = edited.text;
|
|
237
|
+
serversEdit = edited.method;
|
|
238
|
+
}
|
|
131
239
|
const hash = hashText(text);
|
|
240
|
+
const served = serverUrl ? { server_url: serverUrl, servers_edit: serversEdit } : {};
|
|
132
241
|
const name = specNameFor(text, p.file, p.name);
|
|
133
242
|
const note = p.note !== undefined ? p.note.trim().slice(0, MAX_NOTE) || undefined : undefined;
|
|
243
|
+
// The API version is part of the key: asked for, else the document's own (info.version). A push by id needs neither: the spec has one.
|
|
244
|
+
const explicitVersion = p.apiVersion !== undefined ? checkApiVersion(p.apiVersion) : undefined;
|
|
245
|
+
const apiVersion = explicitVersion ?? apiVersionOf(text) ?? undefined;
|
|
246
|
+
if (!p.id && apiVersion === undefined) {
|
|
247
|
+
throw new Error(`The document's info.version gives no API version (a major such as 1.8.0 -> v1): say which with --api-version <v1|v2|...>, or push to a spec by --id`);
|
|
248
|
+
}
|
|
134
249
|
if (p.rename && !p.id)
|
|
135
250
|
throw new Error("--rename needs --id: without an id the spec is found by its name, so there is nothing to rename");
|
|
136
|
-
|
|
251
|
+
if (p.repositoryId && p.repository)
|
|
252
|
+
throw new Error("--repository-id and --repository name the same thing: pass one");
|
|
253
|
+
const wanted = await repositoryIdFor(p);
|
|
254
|
+
// The group is part of the key: looked up (not made) now, made only when a new spec is created below.
|
|
255
|
+
const lookedUpGroup = p.id ? undefined : p.group ? ((await groupIdFor(p.conn, p.group, false)) ?? "(new)") : null;
|
|
256
|
+
const scope = { repositoryId: wanted, ...(apiVersion !== undefined ? { apiVersion } : {}), ...(lookedUpGroup !== undefined ? { groupId: lookedUpGroup, groupExplicit: !!p.group } : {}) };
|
|
257
|
+
let existing = await findSpec(p.conn, name, p.id, scope);
|
|
258
|
+
let repositoryId = existing?.repository_id ?? null;
|
|
259
|
+
let repositoryKept;
|
|
260
|
+
if (existing && wanted && wanted !== "(new)") {
|
|
261
|
+
if (repositoryId === null) {
|
|
262
|
+
// A spec with no repository is tied to it; one tied to another is not moved.
|
|
263
|
+
if (!p.dryRun) {
|
|
264
|
+
try {
|
|
265
|
+
await request({ ...headersOf(p.conn), method: "PATCH", path: `/api/v1/specs/${encodeURIComponent(existing.id)}`, body: { repository_id: wanted } });
|
|
266
|
+
}
|
|
267
|
+
catch (err) {
|
|
268
|
+
throw new Error(`The catalog refused the repository link: ${reasonOf(err)}`);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
repositoryId = wanted;
|
|
272
|
+
}
|
|
273
|
+
else if (repositoryId !== wanted) {
|
|
274
|
+
repositoryKept = repositoryId;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
const linked = { repository_id: repositoryId, ...(repositoryKept ? { repository_kept: repositoryKept } : {}), ...served };
|
|
137
278
|
// A rename only on request: a spec named by hand in the catalog is not renamed back to the title on every push.
|
|
138
279
|
let renamedFrom;
|
|
139
280
|
if (existing && p.rename && existing.name !== name) {
|
|
@@ -154,10 +295,10 @@ async function pushSpecInner(p) {
|
|
|
154
295
|
const versions = await request({ ...headersOf(p.conn), method: "GET", path: `/api/v1/specs/${encodeURIComponent(existing.id)}/versions` });
|
|
155
296
|
const latest = versions.data.data.data[0];
|
|
156
297
|
if (latest?.content_hash === hash) {
|
|
157
|
-
return { id: existing.id, name: existing.name, version: latest.version, group_id: existing.group_id, action: "unchanged", content_hash: hash, ...renamed };
|
|
298
|
+
return { id: existing.id, name: existing.name, version: latest.version, api_version: existing.api_version ?? apiVersion ?? "v1", group_id: existing.group_id, action: "unchanged", content_hash: hash, ...linked, ...renamed };
|
|
158
299
|
}
|
|
159
300
|
if (p.dryRun)
|
|
160
|
-
return { id: existing.id, name: existing.name, version: existing.latest_version + 1, group_id: existing.group_id, action: "new_version", content_hash: hash, ...renamed };
|
|
301
|
+
return { id: existing.id, name: existing.name, version: existing.latest_version + 1, api_version: existing.api_version ?? apiVersion ?? "v1", group_id: existing.group_id, action: "new_version", content_hash: hash, ...linked, ...renamed };
|
|
161
302
|
try {
|
|
162
303
|
const res = await request({
|
|
163
304
|
...headersOf(p.conn),
|
|
@@ -166,19 +307,22 @@ async function pushSpecInner(p) {
|
|
|
166
307
|
body: { content: text, ...(note ? { note } : {}) },
|
|
167
308
|
});
|
|
168
309
|
const version = res.data.data.version;
|
|
169
|
-
return { id: existing.id, name: existing.name, version, group_id: existing.group_id, action: "new_version", content_hash: hash, ...renamed };
|
|
310
|
+
return { id: existing.id, name: existing.name, version, api_version: existing.api_version ?? apiVersion ?? "v1", group_id: existing.group_id, action: "new_version", content_hash: hash, ...linked, ...renamed };
|
|
170
311
|
}
|
|
171
312
|
catch (err) {
|
|
172
313
|
// Another job pushed the same document between our comparison and our upload: the catalog says so, and that is the goal.
|
|
173
314
|
if (codeOf(err) === "UNCHANGED")
|
|
174
|
-
return { id: existing.id, name: existing.name, version: existing.latest_version, group_id: existing.group_id, action: "unchanged", content_hash: hash, ...renamed };
|
|
175
|
-
|
|
315
|
+
return { id: existing.id, name: existing.name, version: existing.latest_version, api_version: existing.api_version ?? apiVersion ?? "v1", group_id: existing.group_id, action: "unchanged", content_hash: hash, ...linked, ...renamed };
|
|
316
|
+
if (codeOf(err) === "API_VERSION_MISMATCH") {
|
|
317
|
+
throw new Error(`This document belongs to another API version than '${existing.name}' (${existing.api_version ?? "?"}): the catalog keeps one spec per API version. Push it without --id, so the spec for its own API version is found or made. (${reasonOf(err)})`);
|
|
318
|
+
}
|
|
319
|
+
throw new Error(`The catalog refused the new revision: ${reasonOf(err)}`);
|
|
176
320
|
}
|
|
177
321
|
}
|
|
178
322
|
// A new spec. The group is by name and made on the way; none asked = in no group.
|
|
179
323
|
if (p.dryRun) {
|
|
180
324
|
const gid = p.group ? await groupIdFor(p.conn, p.group, false) : null;
|
|
181
|
-
return { id: "(new)", name, version: 1, group_id: gid, action: "created", content_hash: hash };
|
|
325
|
+
return { id: "(new)", name, version: 1, api_version: apiVersion ?? "v1", group_id: gid, action: "created", content_hash: hash, repository_id: wanted, ...served };
|
|
182
326
|
}
|
|
183
327
|
let groupId = null;
|
|
184
328
|
try {
|
|
@@ -188,18 +332,28 @@ async function pushSpecInner(p) {
|
|
|
188
332
|
...headersOf(p.conn),
|
|
189
333
|
method: "POST",
|
|
190
334
|
path: "/api/v1/specs",
|
|
191
|
-
body: {
|
|
335
|
+
body: {
|
|
336
|
+
name,
|
|
337
|
+
content: text,
|
|
338
|
+
...(groupId ? { group_id: groupId } : {}),
|
|
339
|
+
...(explicitVersion ? { api_version: explicitVersion } : {}),
|
|
340
|
+
...(wanted && wanted !== "(new)" ? { repository_id: wanted } : {}),
|
|
341
|
+
...(p.description ? { description: p.description } : {}),
|
|
342
|
+
},
|
|
192
343
|
});
|
|
193
344
|
const created = res.data.data;
|
|
194
|
-
return { id: created.id, name: created.name, version: 1, group_id: created.group_id ?? null, action: "created", content_hash: hash };
|
|
345
|
+
return { id: created.id, name: created.name, version: 1, api_version: created.api_version ?? apiVersion ?? "v1", group_id: created.group_id ?? null, action: "created", content_hash: hash, repository_id: created.repository_id ?? null, ...served };
|
|
195
346
|
}
|
|
196
347
|
catch (err) {
|
|
197
348
|
if (codeOf(err) === "NAME_TAKEN") {
|
|
198
349
|
// Two jobs creating the same spec: the loser pushes to the winner's.
|
|
199
|
-
const raced = await findSpec(p.conn, name);
|
|
350
|
+
const raced = await findSpec(p.conn, name, undefined, { ...scope, groupId: groupId ?? scope.groupId, groupExplicit: true });
|
|
200
351
|
if (raced)
|
|
201
352
|
return pushSpecInner({ ...p, id: raced.id });
|
|
202
353
|
}
|
|
354
|
+
if (codeOf(err) === "API_VERSION_REQUIRED") {
|
|
355
|
+
throw new Error(`The catalog could not tell this document's API version (its info.version has no major): pass --api-version <v1|v2|...>. (${reasonOf(err)})`);
|
|
356
|
+
}
|
|
203
357
|
throw new Error(`The catalog refused the spec: ${reasonOf(err)}`);
|
|
204
358
|
}
|
|
205
359
|
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which spec (and so which repository row) a CI step is about - the one name resolution every assurance command shares
|
|
3
|
+
* (results and external monitoring work on a SPEC that has a repository; the model is in
|
|
4
|
+
* docs/decisions/2026-11-09-repository-as-parent-of-specs.md of nb-apps, "Amendment 2").
|
|
5
|
+
*
|
|
6
|
+
* Two ways to say it, never mixed:
|
|
7
|
+
* - by id: `--spec-id <id>`
|
|
8
|
+
* - by names: `--repository <name> [--component <name>] [--group <name>] [--api-version <v>] --spec <name>` (provider defaults to
|
|
9
|
+
* github). The key of a spec is its group, its repository row (provider, name, component), its API VERSION (v1, v2) and its
|
|
10
|
+
* name: the same name may exist in other groups (an environment each), under other repositories and at other API versions.
|
|
11
|
+
* The component is optional: none = the repository as a whole. The group is optional too, and NOT a wildcard: none = the specs
|
|
12
|
+
* that are in no group. The API version is the one deliberate exception to "left out means none": left out, it is the API
|
|
13
|
+
* version of the one spec the rest of the key matches (and when the rest matches specs of several API versions the error
|
|
14
|
+
* lists them and asks for --api-version). On a miss the error lists where the name does exist and asks for --group /
|
|
15
|
+
* --repository / --component / --api-version / --spec-id.
|
|
16
|
+
*
|
|
17
|
+
* Nothing is ever created here (a result does not register a spec or a repository: that is `nb specs ...`). A spec with no
|
|
18
|
+
* repository is refused, because a result or a monitor is reported against the repository the spec is tied to.
|
|
19
|
+
*/
|
|
20
|
+
import { ApiError, request } from "../http.js";
|
|
21
|
+
import { checkApiVersion, sameApiVersion } from "./apiVersion.js";
|
|
22
|
+
import { checkProvider, headersOf, reasonOf } from "./push.js";
|
|
23
|
+
const label = (r) => `${r.provider} ${r.name}${r.component ? ` / ${r.component}` : ""}`;
|
|
24
|
+
async function get(conn, path) {
|
|
25
|
+
try {
|
|
26
|
+
return (await request({ ...headersOf(conn), method: "GET", path })).data.data;
|
|
27
|
+
}
|
|
28
|
+
catch (err) {
|
|
29
|
+
if (err instanceof ApiError && err.status === 404)
|
|
30
|
+
throw err;
|
|
31
|
+
if (err instanceof ApiError)
|
|
32
|
+
throw new Error(`The catalog refused the request: ${reasonOf(err)}`);
|
|
33
|
+
throw err;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const noRepository = (s) => new Error(`The spec '${s.name}' is tied to no repository: a result or a monitor is reported against the repository a spec is tied to. Tie it first (Spec Management on the screen, or 'nb specs specs update ${s.id} --data '{"repository_id":"<id>"}'').`);
|
|
37
|
+
async function groupsOf(conn) {
|
|
38
|
+
return (await get(conn, "/api/v1/groups")).data;
|
|
39
|
+
}
|
|
40
|
+
/** Where a spec reads in an error: `group 'prod' / github acme/api / web / v2`. */
|
|
41
|
+
function whereOf(s, groups, repositories) {
|
|
42
|
+
const g = s.group_id ? `group '${groups.find((x) => x.id === s.group_id)?.name ?? s.group_id}'` : "no group";
|
|
43
|
+
const r = s.repository_id ? (repositories.find((x) => x.id === s.repository_id) ? label(repositories.find((x) => x.id === s.repository_id)) : `repository ${s.repository_id}`) : "no repository";
|
|
44
|
+
return `${g} / ${r} / ${s.api_version ?? "v1"}`;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* A spec by its key, without requiring a repository (a spec description document or a pull works on a spec with none): `--spec-id`,
|
|
48
|
+
* or `--spec <name>` with the optional `--repository` [`--component`] `--provider` and `--group`. Whatever is not given is "none":
|
|
49
|
+
* no repository = a spec tied to no repository, no group = a spec in no group. Nothing is created.
|
|
50
|
+
*/
|
|
51
|
+
export async function locateSpec(conn, ref) {
|
|
52
|
+
const byId = ref.specId?.trim() || undefined;
|
|
53
|
+
const specName = ref.spec?.trim() || undefined;
|
|
54
|
+
const repositoryName = ref.repository?.trim() || undefined;
|
|
55
|
+
const groupName = ref.group?.trim() || undefined;
|
|
56
|
+
const component = ref.component?.trim() ?? "";
|
|
57
|
+
const apiVersion = ref.apiVersion?.trim() ? checkApiVersion(ref.apiVersion) : undefined;
|
|
58
|
+
if (byId && (repositoryName || specName || component || groupName || apiVersion)) {
|
|
59
|
+
throw new Error("--spec-id names the spec by itself: do not combine it with --repository, --component, --group, --api-version or --spec");
|
|
60
|
+
}
|
|
61
|
+
if (!byId && !specName)
|
|
62
|
+
throw new Error("Say which spec: --spec-id <id>, or --spec <name> [--repository <name> [--component <name>]] [--group <name>] [--api-version <v>]");
|
|
63
|
+
if (!byId && !repositoryName && (component !== "" || ref.provider))
|
|
64
|
+
throw new Error("--component and --provider need --repository");
|
|
65
|
+
if (byId) {
|
|
66
|
+
let spec;
|
|
67
|
+
try {
|
|
68
|
+
spec = await get(conn, `/api/v1/specs/${encodeURIComponent(byId)}`);
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
if (err instanceof ApiError)
|
|
72
|
+
throw new Error(`No spec with id '${byId}' in the catalog (check --spec-id, and --org: the catalog is per owner).`);
|
|
73
|
+
throw err;
|
|
74
|
+
}
|
|
75
|
+
return { spec, repository: await repositoryOfSpec(conn, spec) };
|
|
76
|
+
}
|
|
77
|
+
if (repositoryName)
|
|
78
|
+
checkProvider(ref.provider); // refused before anything is sent
|
|
79
|
+
// The groups are read only when one is named (to turn its name into an id); an error reads them best-effort, to name them.
|
|
80
|
+
const groups = groupName ? await groupsOf(conn) : [];
|
|
81
|
+
let groupId = null;
|
|
82
|
+
if (groupName) {
|
|
83
|
+
const g = groups.find((x) => x.name.toLowerCase() === groupName.toLowerCase());
|
|
84
|
+
if (!g)
|
|
85
|
+
throw new Error(`No group named '${groupName}' in the catalog${groups.length > 0 ? ` (groups: ${groups.map((x) => x.name).join(", ")})` : ""}.`);
|
|
86
|
+
groupId = g.id;
|
|
87
|
+
}
|
|
88
|
+
const repositories = (await get(conn, "/api/v1/repositories")).data;
|
|
89
|
+
let repository = null;
|
|
90
|
+
if (repositoryName) {
|
|
91
|
+
const provider = checkProvider(ref.provider);
|
|
92
|
+
repository = repositories.find((r) => r.provider === provider && r.name.toLowerCase() === repositoryName.toLowerCase() && (r.component ?? "").toLowerCase() === component.toLowerCase()) ?? null;
|
|
93
|
+
if (!repository) {
|
|
94
|
+
throw new Error(`No repository ${label({ provider, name: repositoryName, component })} in the catalog (nothing is created here: 'nb specs repositories upsert'; check --provider and --component, which are part of the key).`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const specs = (await get(conn, "/api/v1/specs")).data;
|
|
98
|
+
const named = specs.filter((s) => s.name.toLowerCase() === specName.toLowerCase());
|
|
99
|
+
if (named.length === 0)
|
|
100
|
+
throw new Error(`No spec named '${specName}' in the catalog (nothing is created here: 'nb specs specs push').`);
|
|
101
|
+
const here = named.filter((s) => (s.group_id ?? null) === groupId && (s.repository_id ?? null) === (repository?.id ?? null));
|
|
102
|
+
// The API version is part of the key; left out, it is the one the rest of the key leaves (several: the error lists them).
|
|
103
|
+
const hits = apiVersion === undefined ? here : here.filter((s) => sameApiVersion(s.api_version ?? "v1", apiVersion));
|
|
104
|
+
if (hits.length > 1) {
|
|
105
|
+
throw new Error(`'${specName}' exists at more than one API version in ${groupName ? `group '${groupName}'` : "no group"} / ${repository ? label(repository) : "no repository"}: ${hits.map((s) => s.api_version ?? "v1").join(", ")}. ` +
|
|
106
|
+
"Say which with --api-version (the API version is part of the spec's key; unlike the group and the component, leaving it out is not 'none').");
|
|
107
|
+
}
|
|
108
|
+
const hit = hits[0];
|
|
109
|
+
if (!hit) {
|
|
110
|
+
const asked = `${groupName ? `group '${groupName}'` : "no group"} / ${repository ? label(repository) : "no repository"}${apiVersion ? ` / ${apiVersion}` : ""}`;
|
|
111
|
+
const known = groups.length > 0 ? groups : await groupsOf(conn).catch(() => []);
|
|
112
|
+
throw new Error(`No spec named '${specName}' in ${asked}. The name exists in: ${named.map((s) => whereOf(s, known, repositories)).join("; ")}. ` +
|
|
113
|
+
"Say which with --group, --repository (and --component), --api-version, or use --spec-id (a group or repository you leave out means none, not any).");
|
|
114
|
+
}
|
|
115
|
+
return { spec: hit, repository };
|
|
116
|
+
}
|
|
117
|
+
async function repositoryOfSpec(conn, spec) {
|
|
118
|
+
if (!spec.repository_id)
|
|
119
|
+
return null;
|
|
120
|
+
try {
|
|
121
|
+
return await get(conn, `/api/v1/repositories/${encodeURIComponent(spec.repository_id)}`);
|
|
122
|
+
}
|
|
123
|
+
catch (err) {
|
|
124
|
+
if (err instanceof ApiError)
|
|
125
|
+
throw new Error(`The spec '${spec.name}' points at repository '${spec.repository_id}', which the catalog does not have.`);
|
|
126
|
+
throw err;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
export async function resolveSpec(conn, ref) {
|
|
130
|
+
const byId = ref.specId?.trim() || undefined;
|
|
131
|
+
const repositoryName = ref.repository?.trim() || undefined;
|
|
132
|
+
const specName = ref.spec?.trim() || undefined;
|
|
133
|
+
const groupName = ref.group?.trim() || undefined;
|
|
134
|
+
const component = ref.component?.trim() ?? "";
|
|
135
|
+
const apiVersionAsked = !!ref.apiVersion?.trim();
|
|
136
|
+
if (byId && (repositoryName || specName || component || groupName || apiVersionAsked)) {
|
|
137
|
+
throw new Error("--spec-id names the spec by itself: do not combine it with --repository, --component, --group, --api-version or --spec");
|
|
138
|
+
}
|
|
139
|
+
if (!byId && !repositoryName && !specName && component === "" && !groupName && !apiVersionAsked) {
|
|
140
|
+
throw new Error("Say which spec: --spec-id <id>, or --repository <name> [--component <name>] [--group <name>] [--api-version <v>] --spec <name>");
|
|
141
|
+
}
|
|
142
|
+
if (!byId && !repositoryName)
|
|
143
|
+
throw new Error("--repository is required with --spec (--component is optional: none = the repository as a whole; --group too: none = no group)");
|
|
144
|
+
if (!byId && !specName)
|
|
145
|
+
throw new Error("--spec is required with --repository");
|
|
146
|
+
const { spec, repository } = await locateSpec(conn, ref);
|
|
147
|
+
if (!repository)
|
|
148
|
+
throw noRepository(spec);
|
|
149
|
+
return { spec_id: spec.id, spec_name: spec.name, repository_id: repository.id, repository };
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Every spec tied to one repository row AND one API version, whatever its group (`--all-specs`: a result that belongs to the source,
|
|
153
|
+
* such as a unit test run, is recorded for each environment's spec of that repository at that API version: a `release/v1` branch
|
|
154
|
+
* does not feed the v2 specs). Names only: `--repository` [`--component`] [`--provider`] [`--api-version`]. Without `--api-version`
|
|
155
|
+
* it is the API version the repository row has, when it has one; with specs of several, the error lists them and asks.
|
|
156
|
+
*/
|
|
157
|
+
export async function resolveRepositorySpecs(conn, ref) {
|
|
158
|
+
const repositoryName = ref.repository?.trim();
|
|
159
|
+
if (!repositoryName)
|
|
160
|
+
throw new Error("--all-specs needs --repository <name> [--component <name>]");
|
|
161
|
+
const component = ref.component?.trim() ?? "";
|
|
162
|
+
const provider = checkProvider(ref.provider);
|
|
163
|
+
const repositories = (await get(conn, "/api/v1/repositories")).data;
|
|
164
|
+
const repository = repositories.find((r) => r.provider === provider && r.name.toLowerCase() === repositoryName.toLowerCase() && (r.component ?? "").toLowerCase() === component.toLowerCase());
|
|
165
|
+
if (!repository)
|
|
166
|
+
throw new Error(`No repository ${label({ provider, name: repositoryName, component })} in the catalog (nothing is created here: 'nb specs repositories upsert').`);
|
|
167
|
+
const all = (await get(conn, "/api/v1/specs")).data.filter((s) => s.repository_id === repository.id);
|
|
168
|
+
if (all.length === 0)
|
|
169
|
+
throw new Error(`No spec is tied to ${label(repository)}: register one ('nb specs specs push --repository ...') before reporting results.`);
|
|
170
|
+
const versions = [...new Set(all.map((s) => (s.api_version ?? "v1").toLowerCase()))].sort();
|
|
171
|
+
const asked = ref.apiVersion?.trim() ? checkApiVersion(ref.apiVersion) : undefined;
|
|
172
|
+
if (asked === undefined && versions.length > 1) {
|
|
173
|
+
throw new Error(`${label(repository)} has specs at several API versions (${versions.join(", ")}): say which one gets the result with --api-version (a release branch feeds its own API version only).`);
|
|
174
|
+
}
|
|
175
|
+
const specs = asked === undefined ? all : all.filter((s) => sameApiVersion(s.api_version ?? "v1", asked));
|
|
176
|
+
if (specs.length === 0)
|
|
177
|
+
throw new Error(`No spec of ${label(repository)} is at API version '${asked}' (it has: ${versions.join(", ")}).`);
|
|
178
|
+
const groups = await groupsOf(conn).catch(() => []);
|
|
179
|
+
return [...specs]
|
|
180
|
+
.sort((a, b) => (groups.find((g) => g.id === a.group_id)?.name ?? "").localeCompare(groups.find((g) => g.id === b.group_id)?.name ?? "") || a.name.localeCompare(b.name))
|
|
181
|
+
.map((s) => ({ spec_id: s.id, spec_name: s.name, repository_id: repository.id, repository }));
|
|
182
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `nb specs specs push --server-url <url>`: the document a pipeline keeps in its repository is ONE file per API; what differs
|
|
3
|
+
* between environments is where the API is served, which is the document's top-level `servers`. The push replaces `servers`
|
|
4
|
+
* with `[{ url }]` just before it sends the document, so each environment's spec (a spec per environment, filed in a group)
|
|
5
|
+
* carries its own URL. The catalog's contract hash ignores `servers`, so this does not change the contract's identity.
|
|
6
|
+
*
|
|
7
|
+
* How the document is edited:
|
|
8
|
+
* - JSON input: parsed, `servers` set, written back as JSON (2-space indent).
|
|
9
|
+
* - YAML input: a TEXT edit of the top-level `servers` block (or one inserted before `paths:`), so comments and the order of
|
|
10
|
+
* everything else stay as they are. The result is parsed and compared with the original (everything but `servers` must be
|
|
11
|
+
* identical); if the edit cannot be proven safe the document is re-serialised instead (comments are lost) and the method
|
|
12
|
+
* says so.
|
|
13
|
+
*/
|
|
14
|
+
import { parse, stringify } from "yaml";
|
|
15
|
+
/** `--server-url`: an absolute http(s) URL (no trailing slash needed). */
|
|
16
|
+
export function checkServerUrl(raw) {
|
|
17
|
+
const v = raw.trim();
|
|
18
|
+
let url;
|
|
19
|
+
try {
|
|
20
|
+
url = new URL(v);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
throw new Error(`--server-url '${raw}' is not a URL (e.g. https://api.example.com/v1)`);
|
|
24
|
+
}
|
|
25
|
+
if (url.protocol !== "https:" && url.protocol !== "http:")
|
|
26
|
+
throw new Error(`--server-url must be an http(s) URL, got '${raw}'`);
|
|
27
|
+
return v;
|
|
28
|
+
}
|
|
29
|
+
const withoutServers = (doc) => {
|
|
30
|
+
const { servers: _servers, ...rest } = (doc ?? {});
|
|
31
|
+
void _servers;
|
|
32
|
+
return JSON.stringify(rest);
|
|
33
|
+
};
|
|
34
|
+
/** Set the document's top-level `servers` to `[{ url }]`. */
|
|
35
|
+
export function setServers(text, url) {
|
|
36
|
+
const trimmed = text.trimStart();
|
|
37
|
+
if (trimmed.startsWith("{")) {
|
|
38
|
+
let doc;
|
|
39
|
+
try {
|
|
40
|
+
doc = JSON.parse(text);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
throw new Error("--server-url: the file looks like JSON but does not parse");
|
|
44
|
+
}
|
|
45
|
+
return { text: `${JSON.stringify({ ...doc, servers: [{ url }] }, null, 2)}\n`, method: "json" };
|
|
46
|
+
}
|
|
47
|
+
let original;
|
|
48
|
+
try {
|
|
49
|
+
original = parse(text);
|
|
50
|
+
}
|
|
51
|
+
catch (err) {
|
|
52
|
+
throw new Error(`--server-url: the file is not valid YAML or JSON: ${err.message}`);
|
|
53
|
+
}
|
|
54
|
+
if (original === null || typeof original !== "object" || Array.isArray(original))
|
|
55
|
+
throw new Error("--server-url: the document is not an OpenAPI object");
|
|
56
|
+
const block = `servers:\n - url: ${JSON.stringify(url)}`;
|
|
57
|
+
const lines = text.split("\n");
|
|
58
|
+
const isTopKey = (l) => /^[^\s#\-][^\n]*$/.test(l) && !/^---\s*$/.test(l) && !/^\.\.\.\s*$/.test(l);
|
|
59
|
+
const start = lines.findIndex((l) => /^servers\s*:/.test(l));
|
|
60
|
+
let edited = null;
|
|
61
|
+
if (start >= 0) {
|
|
62
|
+
let end = start + 1;
|
|
63
|
+
// The block runs to the next top-level key; comment lines and blank lines after the last item stay with what follows it.
|
|
64
|
+
while (end < lines.length && !isTopKey(lines[end]))
|
|
65
|
+
end++;
|
|
66
|
+
let tail = end;
|
|
67
|
+
while (tail > start + 1 && (lines[tail - 1].trim() === "" || lines[tail - 1].trimStart().startsWith("#")))
|
|
68
|
+
tail--;
|
|
69
|
+
edited = [...lines.slice(0, start), ...block.split("\n"), ...lines.slice(tail)].join("\n");
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
const paths = lines.findIndex((l) => /^paths\s*:/.test(l));
|
|
73
|
+
if (paths >= 0)
|
|
74
|
+
edited = [...lines.slice(0, paths), ...block.split("\n"), ...lines.slice(paths)].join("\n");
|
|
75
|
+
else
|
|
76
|
+
edited = `${text.endsWith("\n") ? text : `${text}\n`}${block}\n`;
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
const after = parse(edited);
|
|
80
|
+
const ok = JSON.stringify(after?.servers) === JSON.stringify([{ url }]) && withoutServers(after) === withoutServers(original);
|
|
81
|
+
if (ok)
|
|
82
|
+
return { text: edited, method: "text" };
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
/* fall through to re-serialising */
|
|
86
|
+
}
|
|
87
|
+
return { text: stringify({ ...original, servers: [{ url }] }), method: "reserialised" };
|
|
88
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `nb specs specs settings <id>` - a spec's public settings (since 2026-11-10 these are columns of the spec, not of its
|
|
3
|
+
* repository): the quality badge, who may read the report, and the button that issues new public links. One `PATCH /specs/{id}`
|
|
4
|
+
* with only the fields asked for. The Evolution screen's Spec detail has the same fields (public badge and report with their
|
|
5
|
+
* links). Whether a result may carry the original report (`attachments_enabled`) is the REPOSITORY's: `nb specs repositories
|
|
6
|
+
* upsert|update --attachments`. There is no API version rule any more: a spec has ONE API version (v1, v2), so a result needs none.
|
|
7
|
+
*/
|
|
8
|
+
import { ApiError, request } from "../http.js";
|
|
9
|
+
import { headersOf, reasonOf } from "./push.js";
|
|
10
|
+
export const REPORT_ACCESS = ["hidden", "login", "public"];
|
|
11
|
+
/** `on|off` (also true/false, yes/no, 1/0) as a boolean; anything else is a mistake worth saying so. */
|
|
12
|
+
export function onOff(flag, raw) {
|
|
13
|
+
const v = raw.trim().toLowerCase();
|
|
14
|
+
if (["on", "true", "yes", "1"].includes(v))
|
|
15
|
+
return true;
|
|
16
|
+
if (["off", "false", "no", "0"].includes(v))
|
|
17
|
+
return false;
|
|
18
|
+
throw new Error(`${flag} '${raw}' must be on or off`);
|
|
19
|
+
}
|
|
20
|
+
/** The flags of `settings` as the PATCH body; at least one is required (a PATCH that changes nothing is a mistake). */
|
|
21
|
+
export function parseSettingsFlags(o) {
|
|
22
|
+
const patch = {};
|
|
23
|
+
if (o.publicBadge !== undefined)
|
|
24
|
+
patch.public_badge = onOff("--public-badge", o.publicBadge);
|
|
25
|
+
if (o.reportAccess !== undefined) {
|
|
26
|
+
const v = o.reportAccess.trim().toLowerCase();
|
|
27
|
+
if (!REPORT_ACCESS.includes(v))
|
|
28
|
+
throw new Error(`--report-access '${o.reportAccess}' must be one of: ${REPORT_ACCESS.join(", ")}`);
|
|
29
|
+
patch.report_access = v;
|
|
30
|
+
}
|
|
31
|
+
if (o.rotateQualityPublicId)
|
|
32
|
+
patch.rotate_quality_public_id = true;
|
|
33
|
+
if (Object.keys(patch).length === 0) {
|
|
34
|
+
throw new Error("Nothing to change: pass at least one of --public-badge, --report-access, --rotate-quality-public-id");
|
|
35
|
+
}
|
|
36
|
+
return patch;
|
|
37
|
+
}
|
|
38
|
+
export async function updateSpecSettings(conn, id, patch) {
|
|
39
|
+
try {
|
|
40
|
+
const res = await request({ ...headersOf(conn), method: "PATCH", path: `/api/v1/specs/${encodeURIComponent(id)}`, body: patch });
|
|
41
|
+
return res.data.data;
|
|
42
|
+
}
|
|
43
|
+
catch (err) {
|
|
44
|
+
if (err instanceof ApiError)
|
|
45
|
+
throw new Error(`The catalog refused the settings: ${reasonOf(err)}`);
|
|
46
|
+
throw err;
|
|
47
|
+
}
|
|
48
|
+
}
|