@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.
@@ -1,17 +1,20 @@
1
1
  /**
2
2
  * `nb assurance report upload` - read a test report on the CI runner, reduce it
3
- * to the normalised summary, and report it to a NASEBANAL Assurance project.
3
+ * to the normalised summary, and report it to a NASEBANAL Assurance SPEC (the spec of the API catalog, with the repository
4
+ * it is tied to: `nb specs specs push`, `nb specs repositories upsert`). The spec is named by id (`--spec-id`, $NB_SPEC_ID) or
5
+ * by names (`--repository`, optional `--component` / `--group` / `--api-version`, `--spec`), see `resolveSpec`; nothing is registered
6
+ * by a report. A result has no API version of its own: it belongs to the spec it is reported to (one spec per API version).
4
7
  *
5
8
  * The same command runs in a pipeline and on a laptop (nb-quickstarts' `make
6
- * <tool>:report-upload` calls it): it takes its run key, commit, branch and
7
- * project from the CI environment when there is one, and authenticates with
9
+ * <tool>:report-upload` calls it): it takes its run key, commit and branch
10
+ * from the CI environment when there is one, and authenticates with
8
11
  * `NB_TOKEN` (a PAT or service-account token) so no browser is needed.
9
12
  *
10
13
  * The parsing happens here, not on the server: the server stays small, parsers
11
14
  * are testable offline, and what is uploaded is a few hundred bytes of summary
12
15
  * instead of a megabyte of report.
13
16
  */
14
- import { Command } from "commander";
17
+ import { Command, Option } from "commander";
15
18
  import { existsSync, lstatSync, readFileSync, readdirSync } from "node:fs";
16
19
  import { basename, dirname, join } from "node:path";
17
20
  import { resolveAccessToken, resolveEnv } from "../config.js";
@@ -23,35 +26,20 @@ import { parseJunit } from "./junit.js";
23
26
  import { summariseLocust } from "./locust.js";
24
27
  import { parseSpecmaticCoverage } from "./specmatic.js";
25
28
  import { MAX_ATTACHMENT_BYTES, zipDirectory } from "./zip.js";
26
- import { checkOrg, ciNote, pushSpec, readSpecFile, specNameFor, hashText, specsBaseUrl } from "../specs/push.js";
29
+ import { checkOrg, hashText, readSpecFile, specsBaseUrl } from "../specs/push.js";
30
+ import { resolveRepositorySpecs, resolveSpec } from "../specs/resolve.js";
27
31
  export const SUITE_KINDS = ["unit", "e2e", "load", "contract", "security"];
28
32
  export const RUN_PROVIDERS = ["github", "gitlab", "other"];
29
- /** What the API's ids look like (12 letters and digits); anything else is a typo, not a project. */
30
- const PROJECT_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
31
- /** A spec's id in the API catalog (nb-specs-api): letters, digits, `_` and `-`, up to 64. */
33
+ /** What the API's ids look like (12 letters and digits); anything else is a typo, not a spec. */
32
34
  const SPEC_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
33
- const MAX_SPEC_ENVIRONMENT = 40;
34
- /** `--spec-id`: trimmed; it is never looked up here (the catalog is another service; a typo shows as "no spec" in the project). */
35
+ /** `--spec-id` / `NB_SPEC_ID`: trimmed; empty is none. */
35
36
  export function checkSpecId(raw) {
36
- const v = raw.trim();
37
- if (!SPEC_ID_PATTERN.test(v))
38
- throw new Error(`--spec-id '${raw}' is not a catalog spec id (letters, digits, '-' and '_', up to 64)`);
39
- return v;
40
- }
41
- /** `--spec-environment`: which environment of the API the project covers (production, staging, ...). */
42
- export function checkSpecEnvironment(raw) {
43
- const v = raw.trim();
44
- if (v === "" || v.length > MAX_SPEC_ENVIRONMENT)
45
- throw new Error(`--spec-environment must be 1 to ${MAX_SPEC_ENVIRONMENT} characters`);
46
- return v;
47
- }
48
- /** `--project-id` / `NB_ASSURANCE_PROJECT_ID`: trimmed; empty is none. */
49
- export function checkProjectId(raw) {
50
37
  const v = raw?.trim();
51
38
  if (!v)
52
39
  return undefined;
53
- if (!PROJECT_ID_PATTERN.test(v))
54
- throw new Error(`--project-id '${raw}' is not a project id (letters, digits, '-' and '_'): copy it from the project's page or from a previous upload's output`);
40
+ if (!SPEC_ID_PATTERN.test(v)) {
41
+ throw new Error(`--spec-id '${raw}' is not a spec id (letters, digits, '-' and '_'): it is the id of the spec in the catalog (Spec Management, or \`nb specs specs list\`)`);
42
+ }
55
43
  return v;
56
44
  }
57
45
  export function checkProvider(raw) {
@@ -107,8 +95,6 @@ export function checkSuite(kind, tool, format) {
107
95
  throw new Error("Only locust reports are read as CSV");
108
96
  return name;
109
97
  }
110
- /** The same label rule as the API (`utils/apiVersion.ts` in nb-assurance-api): checked here so a typo fails before anything is sent. */
111
- const API_VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/;
112
98
  const METRIC_KEY = /^[a-z][a-z0-9_]{0,39}$/;
113
99
  const MAX_METRICS = 20;
114
100
  /** `--metric high=0 --metric medium=3`: extra numbers for the suite (the API keeps at most 20). */
@@ -128,13 +114,6 @@ export function parseMetrics(pairs) {
128
114
  throw new Error(`At most ${MAX_METRICS} --metric values per suite`);
129
115
  return out;
130
116
  }
131
- export function checkApiVersion(label) {
132
- const v = label.trim();
133
- if (!API_VERSION_PATTERN.test(v)) {
134
- throw new Error(`--api-version / NB_API_VERSION '${label}' is not a version label: use letters, digits, '.', '_' and '-' (up to 32), e.g. v1 or 2026-10`);
135
- }
136
- return v;
137
- }
138
117
  const MAX_FAILURES = 20;
139
118
  /** Per-test cases: the API accepts this many (MAX_CASES), each message up to 2000 characters. */
140
119
  export const MAX_CASES = 5000;
@@ -189,9 +168,9 @@ export function parseReport(opts) {
189
168
  const base = {
190
169
  kind: opts.kind,
191
170
  tool: opts.tool,
192
- ...(opts.components && opts.components.length > 0 ? { components: opts.components } : {}),
193
171
  ...(opts.label ? { label: opts.label } : {}),
194
172
  ...(opts.toolVersion ? { tool_version: opts.toolVersion } : {}),
173
+ ...(opts.specHash ? { spec_hash: opts.specHash } : {}),
195
174
  };
196
175
  if (opts.format === "junit") {
197
176
  const j = parseJunit(text);
@@ -226,123 +205,30 @@ export function parseReport(opts) {
226
205
  },
227
206
  };
228
207
  }
229
- /** Find the project by name, or create it (unless told not to). Returns its id. */
230
- export async function ensureProject(conn, name, repo, create, spec) {
231
- const find = async () => {
232
- const res = await request({ ...conn, method: "GET", path: "/api/v1/projects", query: { name } });
233
- const list = res.data.data.data;
234
- const hit = list[0];
235
- return hit ? { id: hit.id, created: false, repo: hit.repo, spec: { id: hit.spec_id ?? null, environment: hit.spec_environment ?? null } } : null;
236
- };
237
- const existing = await find();
238
- if (existing)
239
- return existing;
240
- if (!create) {
241
- throw new Error(`No project named '${name}' (create it first, or drop --no-create-project).`);
242
- }
243
- try {
244
- const res = await request({
245
- ...conn,
246
- method: "POST",
247
- path: "/api/v1/projects",
248
- // A new project is born linked: nothing to compare, nothing to patch afterwards.
249
- body: { name, ...(repo ? { repo } : {}), ...(spec ? { spec_id: spec.id, ...(spec.environment ? { spec_environment: spec.environment } : {}) } : {}) },
250
- });
251
- return { id: res.data.data.id, created: true, repo, spec: spec ? { id: spec.id, environment: spec.environment ?? null } : undefined, specLinked: !!spec };
252
- }
253
- catch (err) {
254
- // Another job of the same pipeline created it between our lookup and our create.
255
- if (err instanceof ApiError && err.status === 409) {
256
- const raced = await find();
257
- if (raced)
258
- return raced;
259
- }
260
- throw err;
261
- }
262
- }
263
- /**
264
- * The repository the CI reports is the project's repository: the latest sender wins, whether the old value was typed in
265
- * or came from an earlier upload. (To follow another repository, use another project.) Only a difference is written.
266
- */
267
- async function syncRepo(conn, project, repo) {
268
- let current = project.repo;
269
- if (current === undefined) {
270
- const res = await request({ ...conn, method: "GET", path: `/api/v1/projects/${encodeURIComponent(project.id)}` });
271
- current = res.data.data.repo ?? null;
272
- }
273
- if (current === repo)
274
- return { changed: false, was: current };
275
- await request({ ...conn, method: "PATCH", path: `/api/v1/projects/${encodeURIComponent(project.id)}`, body: { repo } });
276
- return { changed: true, was: current ?? null };
277
- }
278
- /**
279
- * Bring the project's link to the catalog in line with what the CI says. Only what differs is written, so a pipeline that
280
- * runs on every commit leaves the project untouched once it is linked. Pointing at another spec clears the environment
281
- * unless one is given too (the API's rule: the old environment belonged to the old spec).
282
- */
283
- async function syncSpecLink(conn, project, spec) {
284
- const want = spec.environment ?? null;
285
- if (project.specLinked)
286
- return { id: spec.id, environment: want, changed: true, was: null };
287
- let current = project.spec;
288
- if (!current) {
289
- const res = await request({ ...conn, method: "GET", path: `/api/v1/projects/${encodeURIComponent(project.id)}` });
290
- const row = res.data.data;
291
- current = { id: row.spec_id ?? null, environment: row.spec_environment ?? null };
292
- }
293
- const sameId = current.id === spec.id;
294
- const patch = {};
295
- if (!sameId)
296
- patch.spec_id = spec.id;
297
- if (spec.environment !== undefined && (!sameId || current.environment !== want))
298
- patch.spec_environment = spec.environment;
299
- if (Object.keys(patch).length === 0)
300
- return { id: spec.id, environment: current.environment, changed: false, was: current.id };
301
- await request({ ...conn, method: "PATCH", path: `/api/v1/projects/${encodeURIComponent(project.id)}`, body: patch });
302
- return { id: spec.id, environment: spec.environment ?? (sameId ? current.environment : null), changed: true, was: current.id };
303
- }
304
208
  export async function uploadReport(p) {
305
- const project = p.projectId ? { id: p.projectId, created: false } : await ensureProject(p.conn, p.project, p.repo, p.createProject, p.spec);
306
209
  let res;
307
210
  try {
308
211
  res = await request({
309
212
  ...p.conn,
310
213
  method: "POST",
311
- path: `/api/v1/projects/${encodeURIComponent(project.id)}/results`,
214
+ path: `/api/v1/specs/${encodeURIComponent(p.specId)}/results`,
312
215
  body: p.payload,
313
216
  });
314
217
  }
315
218
  catch (err) {
316
- // A pinned id that is not found (or not yours) is a wrong id, not a project to create.
317
- if (p.projectId && err instanceof ApiError && err.status === 404) {
318
- throw new Error(`No project with id '${p.projectId}' (check --project-id / NB_ASSURANCE_PROJECT_ID, and --env).`);
219
+ // Assurance answers 404 for an id that is held by another namespace; a typo is the likelier cause.
220
+ if (err instanceof ApiError && err.status === 404) {
221
+ throw new Error(`No spec with id '${p.specId}' for this account (check --spec-id / NB_SPEC_ID, --org and --env). The id is the spec's id in the catalog.`);
222
+ }
223
+ // The pair of spec and repository is checked by Assurance against the catalog: say what it refused.
224
+ if (err instanceof ApiError && err.status === 422) {
225
+ const e = err.data?.error;
226
+ throw new Error(`Assurance refused the result${e?.code ? ` (${e.code})` : ""}: ${e?.message ?? err.message}`);
319
227
  }
320
228
  throw err;
321
229
  }
322
230
  const data = res.data.data;
323
- const done = { project_id: project.id, project_created: project.created, ...data };
324
- if (p.repo) {
325
- try {
326
- const synced = await syncRepo(p.conn, project, p.repo);
327
- if (synced.changed)
328
- done.repo_changed_from = synced.was;
329
- }
330
- catch (err) {
331
- const detail = err instanceof ApiError ? (err.data?.error?.message ?? err.message) : err.message;
332
- throw new Error(`The result was reported, but the project's repository could not be updated: ${detail}`);
333
- }
334
- }
335
- if (p.spec) {
336
- // The result is in; a link that fails now leaves it as it is and says so.
337
- try {
338
- done.spec = await syncSpecLink(p.conn, project, p.spec);
339
- }
340
- catch (err) {
341
- const detail = err instanceof ApiError ? (err.data?.error?.message ?? err.message) : err.message;
342
- throw new Error(`The result was reported, but the project could not be linked to the catalog: ${detail}`);
343
- }
344
- }
345
- return done;
231
+ return { spec_id: p.specId, repository_id: p.payload.repository_id, ...data };
346
232
  }
347
233
  function fail(message) {
348
234
  throw new Error(message);
@@ -354,9 +240,8 @@ function statsFileIn(dir) {
354
240
  fail(`No *_stats.csv file in ${dir}`);
355
241
  return join(dir, files.sort()[files.length - 1]);
356
242
  }
357
- /** At most this many components per result (the API's limit) and this many characters in a name. */
358
- const MAX_COMPONENTS = 20;
359
- const MAX_COMPONENT_LENGTH = 100;
243
+ /** The longest `--label` the API takes. */
244
+ const MAX_LABEL_LENGTH = 100;
360
245
  /** The `--label`: trimmed, not empty, within the API's limit. */
361
246
  function checkLabel(raw) {
362
247
  if (raw === undefined)
@@ -364,8 +249,8 @@ function checkLabel(raw) {
364
249
  const label = raw.trim();
365
250
  if (label === "")
366
251
  fail("--label must not be empty");
367
- if (label.length > MAX_COMPONENT_LENGTH)
368
- fail(`--label must be ${MAX_COMPONENT_LENGTH} characters or fewer`);
252
+ if (label.length > MAX_LABEL_LENGTH)
253
+ fail(`--label must be ${MAX_LABEL_LENGTH} characters or fewer`);
369
254
  return label;
370
255
  }
371
256
  /** The `--tool-version`: trimmed, not empty, within the API's limit. */
@@ -379,23 +264,23 @@ function checkToolVersion(raw) {
379
264
  fail("--tool-version must be 50 characters or fewer");
380
265
  return version;
381
266
  }
382
- /** The `--component` names: trimmed, no empty one, no two alike ignoring case, within the API's limits. */
383
- function checkComponents(raw) {
267
+ /** The `--spec-hash`: a SHA-256 in hex (what `nb specs versions` prints), lower-cased because the API takes lowercase only. */
268
+ function checkSpecHash(raw) {
384
269
  if (raw === undefined)
385
270
  return undefined;
386
- const out = [];
387
- for (const value of raw) {
388
- const name = value.trim();
389
- if (name === "")
390
- fail("--component must not be empty");
391
- if (name.length > MAX_COMPONENT_LENGTH)
392
- fail(`--component must be ${MAX_COMPONENT_LENGTH} characters or fewer: ${name.slice(0, 20)}…`);
393
- if (!out.some((o) => o.toLowerCase() === name.toLowerCase()))
394
- out.push(name);
271
+ const hash = raw.trim().toLowerCase();
272
+ if (!/^[0-9a-f]{64}$/.test(hash))
273
+ fail("--spec-hash must be a SHA-256 in hex (64 characters), e.g. the sha256 `nb specs versions` prints");
274
+ return hash;
275
+ }
276
+ /** The `--contract-file`: the hash the catalog would keep as `content_hash` for this document (SHA-256 of its text). */
277
+ function hashOfContractFile(file) {
278
+ try {
279
+ return hashText(readSpecFile(file));
280
+ }
281
+ catch (err) {
282
+ return fail(String(err.message).replace(/^--file:/, "--contract-file:"));
395
283
  }
396
- if (out.length > MAX_COMPONENTS)
397
- fail(`At most ${MAX_COMPONENTS} --component values`);
398
- return out;
399
284
  }
400
285
  function resolveFormat(opts, file) {
401
286
  if (opts.format !== undefined) {
@@ -432,7 +317,7 @@ export async function uploadAttachment(conn, ids, a) {
432
317
  await request({
433
318
  ...conn,
434
319
  method: "PUT",
435
- path: `/api/v1/projects/${encodeURIComponent(ids.project_id)}/runs/${encodeURIComponent(ids.run_id)}/suites/${encodeURIComponent(ids.suite_id)}/attachment`,
320
+ path: `/api/v1/specs/${encodeURIComponent(ids.spec_id)}/runs/${encodeURIComponent(ids.run_id)}/suites/${encodeURIComponent(ids.suite_id)}/attachment`,
436
321
  query: { name: a.name },
437
322
  rawBody: a.bytes,
438
323
  contentType: a.name.endsWith(".zip") ? "application/zip" : "application/octet-stream",
@@ -443,30 +328,54 @@ export async function uploadAttachment(conn, ids, a) {
443
328
  throw new Error(`The result was reported, but the attached report was not kept: ${detail}`);
444
329
  }
445
330
  }
331
+ /**
332
+ * The spec a command is about, from its options: `--spec-id` (default $NB_SPEC_ID) OR `--repository` [`--component`] `--spec`
333
+ * (a name asked for on the command line wins over the id the pipeline's variable carries). The retired `NB_REPOSITORY_ID` /
334
+ * `--repository-id` are refused with the way to the new ones, for this release.
335
+ */
336
+ export function specRefOf(opts, env = process.env) {
337
+ if (opts.repositoryId !== undefined)
338
+ fail("--repository-id is retired: a result is reported to a SPEC now. Use --spec-id <id> (or $NB_SPEC_ID), or --repository <owner/name> [--component <name>] [--group <name>] --spec <name>");
339
+ const byNames = [opts.repository, opts.spec, opts.component, opts.group, opts.apiVersion].some((v) => v !== undefined && v.trim() !== "");
340
+ if (opts.specId !== undefined && byNames)
341
+ fail("--spec-id names the spec by itself: do not combine it with --repository, --component, --group, --api-version or --spec");
342
+ if (opts.repositoryProvider !== undefined && !opts.repository)
343
+ fail("--repository-provider needs --repository");
344
+ if (byNames)
345
+ return { repository: opts.repository, component: opts.component, group: opts.group, apiVersion: opts.apiVersion, spec: opts.spec, provider: opts.repositoryProvider };
346
+ const specId = checkSpecId(opts.specId ?? env.NB_SPEC_ID);
347
+ if (specId)
348
+ return { specId };
349
+ if (env.NB_REPOSITORY_ID?.trim()) {
350
+ fail("NB_REPOSITORY_ID is retired: a result is now reported to a SPEC. Set NB_SPEC_ID (the spec's id in the catalog), or pass --repository <owner/name> [--component <name>] --spec <name>");
351
+ }
352
+ return fail("Say which spec: --spec-id <id> (or set NB_SPEC_ID), or --repository <owner/name> [--component <name>] [--group <name>] [--api-version <v>] --spec <name>. The spec must be tied to a repository (Spec Management on the screen, or `nb specs specs push`)");
353
+ }
446
354
  export function buildReportUploadCommand() {
447
355
  return new Command("upload")
448
- .description("Report a test result file (JUnit XML or Locust CSV) to an Assurance project")
356
+ .description("Report a test result file (JUnit XML or Locust CSV) to an Assurance spec: by its id (--spec-id, or $NB_SPEC_ID), or by names (--repository, optional --component and --group, --spec, and --api-version when the name exists at several API versions). The spec must be tied to a repository; nothing is registered by a report")
449
357
  .option("--file <path>", "the report file (JUnit XML, or Locust *_stats.csv)")
450
358
  .option("--dir <dir>", "a Locust output directory (uses its *_stats.csv)")
451
359
  .option("--coverage-report <path>", "specmatic: its report (the HTML or a JSON copy); adds the API coverage as the coverage_pct metric")
452
360
  .option("--format <format>", "junit | locust (default: from the file name)")
453
361
  .option("--kind <kind>", `what the suite proves: ${SUITE_KINDS.join(" | ")} (locust: load)`)
454
362
  .option("--tool <label>", "the producing tool, a free label, e.g. vitest, pytest, playwright, specmatic, zap, trivy (locust: locust)")
455
- .option("--component <name>", "a component the result is for (e.g. frontend, backend), repeatable when it covers several (e.g. an end-to-end test: --component frontend --component backend); new names are created in the project; leave it out for the component `default`", (v, all = []) => [...all, v])
456
- .option("--label <name>", "tells apart results that are otherwise the same, such as two scans of one tool on the same components (e.g. --label baseline, --label full-scan); part of the result's identity, so the same label again replaces the result; optional")
363
+ .option("--label <name>", "tells apart results that are otherwise the same, such as two scans of one tool of the same spec (e.g. --label baseline, --label full-scan); part of the result's identity, so the same label again replaces the result; optional")
457
364
  .option("--tool-version <version>", "the version of the tool that produced the report (e.g. 9.1.0): informational, shown next to the tool, handy when a tool's new version changes its layout; optional")
365
+ .option("--spec-hash <sha256>", "the SHA-256 of the API contract this result was produced against (64 hex characters; the sha256 `nb specs versions` prints for a catalog version): Evolution compares it with the catalog's versions and tells whether the result was produced with the current contract, an older one or an unknown one. Informational, not part of the result's identity; a report sent again replaces it. Exclusive with --contract-file")
366
+ .option("--contract-file <path>", "the contract document the result was produced against (e.g. node_modules/@nasebanal/api-specs-<api>/spec.yaml): its SHA-256 is sent as --spec-hash would, the same hash the catalog keeps for that document. Exclusive with --spec-hash")
458
367
  .option("--metric <key=value>", "an extra number for the suite, repeatable (e.g. --metric high=0 --metric medium=3; for security: critical, high, medium, low, info)", (v, all = []) => [...all, v])
459
- .option("--api-version <label>", "the API version the result is for (e.g. v1, v2), part of the result's identity next to its kind and components; leave it out for results that hold for every version, such as unit tests. Default: the NB_API_VERSION environment variable (set it once per CI job or branch). A project can require a version for some kinds of result, and then refuses one without it")
460
- .option("--project <name>", "project name (CI: the repository); found, or created if missing")
368
+ .option("--api-version <v>", "by names: the API version (v1, v2) of the spec, part of the spec's key (a new major API version is a new spec). It selects the spec; a result has no API version of its own. Left out, it is the API version of the one spec the rest of the key matches (several: the error lists them). With --all-specs: only the specs at this API version get the result (a release branch feeds its own API version)")
461
369
  .option("--attach <path>", "keep the tool's own report with the result: a file as it is, or a folder as a zip (up to 20 MiB). The server only stores it and offers it for download; nothing opens it. Nothing is attached unless you pass this, so check the report holds no secrets")
462
- .option("--spec-id <id>", "tie the project to this API of the catalog (the spec's id in Assurance / Specs): set when it differs, so a pipeline that runs on every commit leaves it alone once it is linked. A new project is created already linked. The id is not looked up here")
463
- .option("--spec-file <path>", "register this OpenAPI file in the API catalog first (a new spec, or a new version when its content changed; nothing is uploaded when it is already the latest) and tie the project to it: the whole chain in one command. Needs the catalog (Evolution) access of the account. Exclusive with --spec-id")
464
- .option("--spec-name <name>", "with --spec-file: the spec's name in the catalog (default: the document's info.title)")
465
- .option("--spec-group <name>", "with --spec-file: file a NEW spec in this group (made when missing); default none. An existing spec is never moved")
466
- .option("--spec-org <id>", "with --spec-file: the organization whose catalog it is (an id), or 'personal' (default; or $NB_SPECS_ORG)")
467
- .option("--spec-environment <name>", "which environment of that API the project covers (production, staging, ...); needs --spec-id")
468
- .option("--project-id <id>", "send to this project by id (or $NB_ASSURANCE_PROJECT_ID): no lookup by name and nothing is created, so a rename never moves the results; recommended for a pipeline once the project exists")
469
- .option("--repo <repo>", "repository recorded on the project; the latest sender wins (CI: detected)")
370
+ .option("--spec-id <id>", "the spec to report to, by its id in the catalog (default: $NB_SPEC_ID). Keep the id in the pipeline's variable: a rename of the spec or its repository never moves the results. Exclusive with --repository / --component / --spec")
371
+ .option("--repository <owner/name>", "by names: the repository the spec is tied to (owner/name for a git host). Needs --spec; --component is optional (none = the repository as a whole). The three are checked against each other: the spec must be tied to exactly that repository row. Nothing is created")
372
+ .option("--component <name>", "by names: the component part of the repository's key (the owner's own name for a part of it, e.g. account-api, web); optional, none = the repository as a whole")
373
+ .option("--group <name>", "by names: the group the spec is filed in (an environment, say: the same spec name may exist in several groups); optional, none = the specs in no group (not any group). On a miss the error lists where the name is")
374
+ .option("--spec <name>", "by names: the spec's name in the catalog. Needs --repository")
375
+ .option("--all-specs", "by names, instead of --spec: send the result to EVERY spec tied to that repository row at one API version, whatever its group (a result that belongs to the source, not to an environment: --kind unit or security). A repository row with specs of several API versions needs --api-version (a release branch feeds its own API version only). One line per spec")
376
+ .addOption(new Option("--repository-id <id>", "retired: use --spec-id").hideHelp())
377
+ .option("--repository-provider <provider>", "with --repository: github | gitlab | bitbucket | other (default: github)")
378
+ .option("--org <id>", "the organization whose specs these are (an id), or 'personal' (default; or $NB_SPECS_ORG): sent to the catalog and to Assurance as X-Active-Organization-Id")
470
379
  .option("--repo-url <url>", "the repository's web address on its host, e.g. https://gitlab.example.com/group/app (CI: detected); lets Evolution link to the report on a self-hosted GitLab / GitHub Enterprise")
471
380
  .option("--provider <provider>", `the CI provider: ${RUN_PROVIDERS.join(" | ")} (CI: detected)`)
472
381
  .option("--report-path <path>", "the report file's path in the repository, relative to its root (default: detected, and only for a file committed at the reported commit)")
@@ -476,7 +385,6 @@ export function buildReportUploadCommand() {
476
385
  .option("--ci-url <url>", "link to the CI run (CI: detected)")
477
386
  .option("--status <status>", "passed | failed; default is derived from the report")
478
387
  .option("--max-fail-ratio <ratio>", "locust: allowed failure ratio 0..1 (default: $LOCUST_MAX_FAIL_RATIO or 0)")
479
- .option("--no-create-project", "fail instead of creating the project when it does not exist")
480
388
  .option("--dry-run", "print what would be sent and exit without calling the API")
481
389
  .action(async (_flags, command) => {
482
390
  const opts = command.optsWithGlobals();
@@ -497,16 +405,19 @@ export function buildReportUploadCommand() {
497
405
  const maxFailRatio = Number(ratioRaw);
498
406
  if (!Number.isFinite(maxFailRatio) || maxFailRatio < 0 || maxFailRatio > 1)
499
407
  fail("--max-fail-ratio must be a number between 0 and 1");
500
- // The flag wins; NB_API_VERSION (a CI variable) is the default, and an empty one (a CI that declares it but does not set it) is none.
501
- const versionRaw = opts.apiVersion ?? (process.env.NB_API_VERSION || undefined);
502
- const apiVersion = versionRaw === undefined ? undefined : checkApiVersion(versionRaw);
408
+ // NB_API_VERSION retired with the result's own api_version: the API version is the spec's now. A CI that still sets it keeps working.
409
+ if (process.env.NB_API_VERSION?.trim()) {
410
+ process.stderr.write("! NB_API_VERSION is retired and ignored: a result has no API version of its own, it belongs to the spec it is reported to (a new major API version is a new spec). Use --api-version <v> only to SELECT a spec by names\n");
411
+ }
412
+ if (opts.specHash !== undefined && opts.contractFile !== undefined)
413
+ fail("--spec-hash and --contract-file are exclusive: one gives the hash, the other a file to take it from");
503
414
  const parsed = parseReport({
504
415
  format,
505
416
  kind,
506
417
  tool: checkedTool,
507
- components: checkComponents(opts.component),
508
418
  label: checkLabel(opts.label),
509
419
  toolVersion: checkToolVersion(opts.toolVersion),
420
+ specHash: opts.contractFile !== undefined ? hashOfContractFile(opts.contractFile) : checkSpecHash(opts.specHash),
510
421
  status: opts.status,
511
422
  maxFailRatio,
512
423
  file,
@@ -520,8 +431,6 @@ export function buildReportUploadCommand() {
520
431
  parsed.suite.metrics = { ...parsed.suite.metrics, coverage_pct: cov.coverage_pct };
521
432
  parsed.note += `, API coverage ${cov.coverage_pct}% (${cov.covered}/${cov.total} operations)`;
522
433
  }
523
- if (apiVersion !== undefined)
524
- parsed.suite.api_version = apiVersion;
525
434
  if (opts.metric !== undefined && opts.metric.length > 0) {
526
435
  const extra = parseMetrics(opts.metric);
527
436
  const merged = { ...parsed.suite.metrics, ...extra };
@@ -533,23 +442,18 @@ export function buildReportUploadCommand() {
533
442
  const ci = detectCi(process.env);
534
443
  const runKey = opts.runKey ?? ci.runKey ?? fail("Cannot determine the run key; pass --run-key");
535
444
  const attachment = opts.attach !== undefined ? prepareAttachment(opts.attach) : undefined;
536
- if (opts.specId !== undefined && opts.specFile !== undefined)
537
- fail("--spec-id and --spec-file are exclusive: one names a spec of the catalog, the other registers a file");
538
- if (opts.specEnvironment !== undefined && opts.specId === undefined && opts.specFile === undefined)
539
- fail("--spec-environment needs --spec-id or --spec-file");
540
- for (const [flag, value] of [["--spec-name", opts.specName], ["--spec-group", opts.specGroup], ["--spec-org", opts.specOrg]]) {
541
- if (value !== undefined && opts.specFile === undefined)
542
- fail(`${flag} needs --spec-file`);
445
+ // Which spec the result is for is settled before anything is sent: an id, or names the catalog turns into one (or, with
446
+ // --all-specs, every spec of one repository row: only for results that belong to the source).
447
+ if (opts.allSpecs) {
448
+ if (!opts.repository)
449
+ fail("--all-specs needs --repository <owner/name> [--component <name>]: the specs tied to that repository row get the result");
450
+ if (opts.spec !== undefined || opts.specId !== undefined || opts.group !== undefined)
451
+ fail("--all-specs sends the result to every spec of that repository at one API version: do not combine it with --spec-id, --spec or --group");
452
+ if (kind !== "unit" && kind !== "security")
453
+ fail(`--all-specs is for results that belong to the source (--kind unit or security), not --kind ${kind}: a ${kind} result is about one deployed environment, so name its spec (--spec-id, or --spec with --group)`);
543
454
  }
544
- const specEnvironment = opts.specEnvironment !== undefined ? checkSpecEnvironment(opts.specEnvironment) : undefined;
545
- let spec = opts.specId !== undefined ? { id: checkSpecId(opts.specId), ...(specEnvironment !== undefined ? { environment: specEnvironment } : {}) } : undefined;
546
- // The file is read and its name settled before anything is sent, so a bad path fails the command while nothing has happened yet.
547
- const specText = opts.specFile !== undefined ? readSpecFile(opts.specFile) : undefined;
548
- const specOrg = opts.specFile !== undefined ? checkOrg(opts.specOrg ?? process.env.NB_SPECS_ORG) : undefined;
549
- const projectId = checkProjectId(opts.projectId ?? process.env.NB_ASSURANCE_PROJECT_ID);
550
- const project = opts.project ?? ci.project ?? projectId ?? fail("Cannot determine the project name; pass --project <name> or --project-id <id>");
551
- if (projectId && opts.project)
552
- process.stderr.write("--project is ignored: --project-id decides where the result goes\n");
455
+ const ref = opts.allSpecs ? { repository: opts.repository, component: opts.component, apiVersion: opts.apiVersion, provider: opts.repositoryProvider } : specRefOf(opts);
456
+ const org = checkOrg(opts.org ?? process.env.NB_SPECS_ORG);
553
457
  const commit = opts.commit ?? ci.commitSha;
554
458
  const branch = opts.branch ?? ci.branch;
555
459
  const ciUrl = opts.ciUrl ?? ci.ciUrl;
@@ -558,7 +462,8 @@ export function buildReportUploadCommand() {
558
462
  const reportPath = opts.reportPath !== undefined ? checkReportPath(opts.reportPath) : readReportPath(file, commit);
559
463
  if (reportPath)
560
464
  parsed.suite.report_path = reportPath;
561
- const payload = {
465
+ const buildPayload = (repositoryId) => ({
466
+ repository_id: repositoryId,
562
467
  run: {
563
468
  key: runKey,
564
469
  ...(commit ? { commit_sha: commit } : {}),
@@ -568,63 +473,50 @@ export function buildReportUploadCommand() {
568
473
  ...(repoUrl ? { repo_url: repoUrl } : {}),
569
474
  },
570
475
  suite: parsed.suite,
571
- };
572
- const repo = opts.repo ?? ci.repo;
476
+ });
477
+ const env = opts.env || resolveEnv();
478
+ const specsConn = { baseUrl: specsBaseUrl(env), token: opts.token || (await resolveAccessToken()), org };
479
+ const attachmentNote = attachment ? { attachment: { name: attachment.name, size_bytes: attachment.bytes.length } } : {};
573
480
  if (opts.dryRun) {
574
- printJson({ project, ...(projectId ? { project_id: projectId } : {}), repo, payload, ...(spec ? { spec } : {}), ...(specText !== undefined && opts.specFile !== undefined ? { spec_file: { file: opts.specFile, name: specNameFor(specText, opts.specFile, opts.specName), content_hash: hashText(specText), ...(opts.specGroup ? { group: opts.specGroup } : {}) } } : {}), ...(attachment ? { attachment: { name: attachment.name, size_bytes: attachment.bytes.length } } : {}) });
481
+ // Nothing is written. By names the catalog is only read (to say which spec and repository they mean); by id nothing is called.
482
+ if (opts.allSpecs) {
483
+ const hits = await resolveRepositorySpecs(specsConn, ref);
484
+ printJson({ specs: hits.map((h) => ({ id: h.spec_id, name: h.spec_name })), repository: hits[0].repository, payload: buildPayload(hits[0].repository_id), ...attachmentNote });
485
+ }
486
+ else if (ref.specId !== undefined) {
487
+ printJson({ spec_id: ref.specId, repository_id: "(from the catalog when sent)", payload: buildPayload("(from the catalog when sent)"), ...attachmentNote });
488
+ }
489
+ else {
490
+ const hit = await resolveSpec(specsConn, ref);
491
+ printJson({ spec: { id: hit.spec_id, name: hit.spec_name }, repository: hit.repository, payload: buildPayload(hit.repository_id), ...attachmentNote });
492
+ }
575
493
  process.stderr.write(`(dry run) ${basename(dirname(file)) || "."}/${basename(file)}: ${parsed.note}\n`);
576
494
  return;
577
495
  }
578
- const env = opts.env || resolveEnv();
579
496
  const override = process.env.NB_BASE_URL?.replace(/\/$/, "");
580
497
  const baseUrl = override ?? resolveBaseUrl(loadSpec("assurance.yaml").servers, env);
581
- const token = opts.token || (await resolveAccessToken());
582
- // The catalog comes first: the project is tied to the spec it returns. It must not cost the result: a failure here is
583
- // kept, the result is reported without the link, and the command says so at the end.
584
- let pushed;
585
- let specError;
586
- if (opts.specFile !== undefined && specOrg !== undefined) {
587
- try {
588
- pushed = await pushSpec({
589
- conn: { baseUrl: specsBaseUrl(env), token, org: specOrg },
590
- file: opts.specFile,
591
- name: opts.specName,
592
- group: opts.specGroup,
593
- note: ciNote(ci, commit),
594
- });
595
- spec = { id: pushed.id, ...(specEnvironment !== undefined ? { environment: specEnvironment } : {}) };
596
- }
597
- catch (err) {
598
- specError = err;
599
- }
498
+ // Assurance and the catalog act for the same owner: the organization goes to both (personal is the default and sent as is).
499
+ const orgHeaders = org === "personal" ? undefined : { "X-Active-Organization-Id": org };
500
+ const hits = opts.allSpecs ? await resolveRepositorySpecs(specsConn, ref) : [await resolveSpec(specsConn, ref)];
501
+ const conn = { baseUrl, token: specsConn.token, ...(orgHeaders ? { headers: orgHeaders } : {}) };
502
+ const results = [];
503
+ for (const hit of hits) {
504
+ const label = `${hit.spec_name} (${hit.repository.provider} ${hit.repository.name}${hit.repository.component ? ` / ${hit.repository.component}` : ""}), id ${hit.spec_id}`;
505
+ const result = await uploadReport({ conn, specId: hit.spec_id, payload: buildPayload(hit.repository_id) });
506
+ if (attachment)
507
+ await uploadAttachment(conn, result, attachment);
508
+ results.push(result);
509
+ process.stderr.write(`✓ ${kind}/${checkedTool} ${parsed.suite.status}: ${parsed.note} -> spec ${label}, run '${runKey}'${result.replaced ? " (replaced)" : ""}` +
510
+ `${attachment ? `, attached ${attachment.name} (${(attachment.bytes.length / 1024).toFixed(0)} KiB)` : ""}\n`);
600
511
  }
601
- const result = await uploadReport({
602
- conn: { baseUrl, token },
603
- project,
604
- projectId,
605
- repo,
606
- createProject: opts.createProject,
607
- payload,
608
- spec,
609
- });
610
- if (attachment)
611
- await uploadAttachment({ baseUrl, token }, result, attachment);
612
- printJson({ ...result, ...(attachment ? { attachment: { name: attachment.name, size_bytes: attachment.bytes.length } } : {}), ...(pushed ? { catalog: pushed } : {}) });
613
- exportGithubOutput("project_id", result.project_id);
614
- if (pushed)
615
- exportGithubOutput("spec_id", pushed.id);
616
- process.stderr.write(`✓ ${kind}/${checkedTool} ${payload.suite.status}: ${parsed.note} -> project '${project}' (id ${result.project_id})` +
617
- `${result.project_created ? " (created)" : ""}, run '${runKey}'${result.replaced ? " (replaced)" : ""}` +
618
- `${attachment ? `, attached ${attachment.name} (${(attachment.bytes.length / 1024).toFixed(0)} KiB)` : ""}` +
619
- `${pushed ? `, spec ${pushed.name} v${pushed.version} (${pushed.action.replace("_", " ")})` : ""}` +
620
- `${result.spec ? `, catalog ${result.spec.id}${result.spec.environment ? ` (${result.spec.environment})` : ""} ${result.spec.changed ? (result.spec.was ? `(changed from ${result.spec.was})` : "(linked)") : "(already linked)"}` : ""}\n`);
621
- if (result.repo_changed_from !== undefined) {
622
- process.stderr.write(` Repository of the project set to ${repo} (was ${result.repo_changed_from ?? "not set"}); the latest sender wins\n`);
512
+ if (opts.allSpecs) {
513
+ printJson({ results, ...attachmentNote });
514
+ exportGithubOutput("spec_ids", results.map((x) => x.spec_id).join(","));
623
515
  }
624
- if (!projectId) {
625
- process.stderr.write(` Pin it so a rename or a typo cannot send results elsewhere: --project-id ${result.project_id} (or NB_ASSURANCE_PROJECT_ID=${result.project_id})\n`);
516
+ else {
517
+ printJson({ ...results[0], ...attachmentNote });
518
+ exportGithubOutput("spec_id", results[0].spec_id);
626
519
  }
627
- if (specError)
628
- throw new Error(`The result was reported, but the spec could not be registered in the catalog (the project is not tied to it): ${specError.message}`);
520
+ exportGithubOutput("repository_id", results[0].repository_id);
629
521
  });
630
522
  }