@nasebanal/cli 0.12.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,7 +168,6 @@ 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 } : {}),
195
173
  ...(opts.specHash ? { spec_hash: opts.specHash } : {}),
@@ -227,123 +205,30 @@ export function parseReport(opts) {
227
205
  },
228
206
  };
229
207
  }
230
- /** Find the project by name, or create it (unless told not to). Returns its id. */
231
- export async function ensureProject(conn, name, repo, create, spec) {
232
- const find = async () => {
233
- const res = await request({ ...conn, method: "GET", path: "/api/v1/projects", query: { name } });
234
- const list = res.data.data.data;
235
- const hit = list[0];
236
- return hit ? { id: hit.id, created: false, repo: hit.repo, spec: { id: hit.spec_id ?? null, environment: hit.spec_environment ?? null } } : null;
237
- };
238
- const existing = await find();
239
- if (existing)
240
- return existing;
241
- if (!create) {
242
- throw new Error(`No project named '${name}' (create it first, or drop --no-create-project).`);
243
- }
244
- try {
245
- const res = await request({
246
- ...conn,
247
- method: "POST",
248
- path: "/api/v1/projects",
249
- // A new project is born linked: nothing to compare, nothing to patch afterwards.
250
- body: { name, ...(repo ? { repo } : {}), ...(spec ? { spec_id: spec.id, ...(spec.environment ? { spec_environment: spec.environment } : {}) } : {}) },
251
- });
252
- return { id: res.data.data.id, created: true, repo, spec: spec ? { id: spec.id, environment: spec.environment ?? null } : undefined, specLinked: !!spec };
253
- }
254
- catch (err) {
255
- // Another job of the same pipeline created it between our lookup and our create.
256
- if (err instanceof ApiError && err.status === 409) {
257
- const raced = await find();
258
- if (raced)
259
- return raced;
260
- }
261
- throw err;
262
- }
263
- }
264
- /**
265
- * The repository the CI reports is the project's repository: the latest sender wins, whether the old value was typed in
266
- * or came from an earlier upload. (To follow another repository, use another project.) Only a difference is written.
267
- */
268
- async function syncRepo(conn, project, repo) {
269
- let current = project.repo;
270
- if (current === undefined) {
271
- const res = await request({ ...conn, method: "GET", path: `/api/v1/projects/${encodeURIComponent(project.id)}` });
272
- current = res.data.data.repo ?? null;
273
- }
274
- if (current === repo)
275
- return { changed: false, was: current };
276
- await request({ ...conn, method: "PATCH", path: `/api/v1/projects/${encodeURIComponent(project.id)}`, body: { repo } });
277
- return { changed: true, was: current ?? null };
278
- }
279
- /**
280
- * Bring the project's link to the catalog in line with what the CI says. Only what differs is written, so a pipeline that
281
- * runs on every commit leaves the project untouched once it is linked. Pointing at another spec clears the environment
282
- * unless one is given too (the API's rule: the old environment belonged to the old spec).
283
- */
284
- async function syncSpecLink(conn, project, spec) {
285
- const want = spec.environment ?? null;
286
- if (project.specLinked)
287
- return { id: spec.id, environment: want, changed: true, was: null };
288
- let current = project.spec;
289
- if (!current) {
290
- const res = await request({ ...conn, method: "GET", path: `/api/v1/projects/${encodeURIComponent(project.id)}` });
291
- const row = res.data.data;
292
- current = { id: row.spec_id ?? null, environment: row.spec_environment ?? null };
293
- }
294
- const sameId = current.id === spec.id;
295
- const patch = {};
296
- if (!sameId)
297
- patch.spec_id = spec.id;
298
- if (spec.environment !== undefined && (!sameId || current.environment !== want))
299
- patch.spec_environment = spec.environment;
300
- if (Object.keys(patch).length === 0)
301
- return { id: spec.id, environment: current.environment, changed: false, was: current.id };
302
- await request({ ...conn, method: "PATCH", path: `/api/v1/projects/${encodeURIComponent(project.id)}`, body: patch });
303
- return { id: spec.id, environment: spec.environment ?? (sameId ? current.environment : null), changed: true, was: current.id };
304
- }
305
208
  export async function uploadReport(p) {
306
- const project = p.projectId ? { id: p.projectId, created: false } : await ensureProject(p.conn, p.project, p.repo, p.createProject, p.spec);
307
209
  let res;
308
210
  try {
309
211
  res = await request({
310
212
  ...p.conn,
311
213
  method: "POST",
312
- path: `/api/v1/projects/${encodeURIComponent(project.id)}/results`,
214
+ path: `/api/v1/specs/${encodeURIComponent(p.specId)}/results`,
313
215
  body: p.payload,
314
216
  });
315
217
  }
316
218
  catch (err) {
317
- // A pinned id that is not found (or not yours) is a wrong id, not a project to create.
318
- if (p.projectId && err instanceof ApiError && err.status === 404) {
319
- 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}`);
320
227
  }
321
228
  throw err;
322
229
  }
323
230
  const data = res.data.data;
324
- const done = { project_id: project.id, project_created: project.created, ...data };
325
- if (p.repo) {
326
- try {
327
- const synced = await syncRepo(p.conn, project, p.repo);
328
- if (synced.changed)
329
- done.repo_changed_from = synced.was;
330
- }
331
- catch (err) {
332
- const detail = err instanceof ApiError ? (err.data?.error?.message ?? err.message) : err.message;
333
- throw new Error(`The result was reported, but the project's repository could not be updated: ${detail}`);
334
- }
335
- }
336
- if (p.spec) {
337
- // The result is in; a link that fails now leaves it as it is and says so.
338
- try {
339
- done.spec = await syncSpecLink(p.conn, project, p.spec);
340
- }
341
- catch (err) {
342
- const detail = err instanceof ApiError ? (err.data?.error?.message ?? err.message) : err.message;
343
- throw new Error(`The result was reported, but the project could not be linked to the catalog: ${detail}`);
344
- }
345
- }
346
- return done;
231
+ return { spec_id: p.specId, repository_id: p.payload.repository_id, ...data };
347
232
  }
348
233
  function fail(message) {
349
234
  throw new Error(message);
@@ -355,9 +240,8 @@ function statsFileIn(dir) {
355
240
  fail(`No *_stats.csv file in ${dir}`);
356
241
  return join(dir, files.sort()[files.length - 1]);
357
242
  }
358
- /** At most this many components per result (the API's limit) and this many characters in a name. */
359
- const MAX_COMPONENTS = 20;
360
- const MAX_COMPONENT_LENGTH = 100;
243
+ /** The longest `--label` the API takes. */
244
+ const MAX_LABEL_LENGTH = 100;
361
245
  /** The `--label`: trimmed, not empty, within the API's limit. */
362
246
  function checkLabel(raw) {
363
247
  if (raw === undefined)
@@ -365,8 +249,8 @@ function checkLabel(raw) {
365
249
  const label = raw.trim();
366
250
  if (label === "")
367
251
  fail("--label must not be empty");
368
- if (label.length > MAX_COMPONENT_LENGTH)
369
- 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`);
370
254
  return label;
371
255
  }
372
256
  /** The `--tool-version`: trimmed, not empty, within the API's limit. */
@@ -398,24 +282,6 @@ function hashOfContractFile(file) {
398
282
  return fail(String(err.message).replace(/^--file:/, "--contract-file:"));
399
283
  }
400
284
  }
401
- /** The `--component` names: trimmed, no empty one, no two alike ignoring case, within the API's limits. */
402
- function checkComponents(raw) {
403
- if (raw === undefined)
404
- return undefined;
405
- const out = [];
406
- for (const value of raw) {
407
- const name = value.trim();
408
- if (name === "")
409
- fail("--component must not be empty");
410
- if (name.length > MAX_COMPONENT_LENGTH)
411
- fail(`--component must be ${MAX_COMPONENT_LENGTH} characters or fewer: ${name.slice(0, 20)}…`);
412
- if (!out.some((o) => o.toLowerCase() === name.toLowerCase()))
413
- out.push(name);
414
- }
415
- if (out.length > MAX_COMPONENTS)
416
- fail(`At most ${MAX_COMPONENTS} --component values`);
417
- return out;
418
- }
419
285
  function resolveFormat(opts, file) {
420
286
  if (opts.format !== undefined) {
421
287
  if (opts.format !== "junit" && opts.format !== "locust")
@@ -451,7 +317,7 @@ export async function uploadAttachment(conn, ids, a) {
451
317
  await request({
452
318
  ...conn,
453
319
  method: "PUT",
454
- 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`,
455
321
  query: { name: a.name },
456
322
  rawBody: a.bytes,
457
323
  contentType: a.name.endsWith(".zip") ? "application/zip" : "application/octet-stream",
@@ -462,32 +328,54 @@ export async function uploadAttachment(conn, ids, a) {
462
328
  throw new Error(`The result was reported, but the attached report was not kept: ${detail}`);
463
329
  }
464
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
+ }
465
354
  export function buildReportUploadCommand() {
466
355
  return new Command("upload")
467
- .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")
468
357
  .option("--file <path>", "the report file (JUnit XML, or Locust *_stats.csv)")
469
358
  .option("--dir <dir>", "a Locust output directory (uses its *_stats.csv)")
470
359
  .option("--coverage-report <path>", "specmatic: its report (the HTML or a JSON copy); adds the API coverage as the coverage_pct metric")
471
360
  .option("--format <format>", "junit | locust (default: from the file name)")
472
361
  .option("--kind <kind>", `what the suite proves: ${SUITE_KINDS.join(" | ")} (locust: load)`)
473
362
  .option("--tool <label>", "the producing tool, a free label, e.g. vitest, pytest, playwright, specmatic, zap, trivy (locust: locust)")
474
- .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])
475
- .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")
476
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")
477
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")
478
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")
479
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])
480
- .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")
481
- .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)")
482
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")
483
- .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")
484
- .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")
485
- .option("--spec-name <name>", "with --spec-file: the spec's name in the catalog (default: the document's info.title)")
486
- .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")
487
- .option("--spec-org <id>", "with --spec-file: the organization whose catalog it is (an id), or 'personal' (default; or $NB_SPECS_ORG)")
488
- .option("--spec-environment <name>", "which environment of that API the project covers (production, staging, ...); needs --spec-id")
489
- .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")
490
- .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")
491
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")
492
380
  .option("--provider <provider>", `the CI provider: ${RUN_PROVIDERS.join(" | ")} (CI: detected)`)
493
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)")
@@ -497,7 +385,6 @@ export function buildReportUploadCommand() {
497
385
  .option("--ci-url <url>", "link to the CI run (CI: detected)")
498
386
  .option("--status <status>", "passed | failed; default is derived from the report")
499
387
  .option("--max-fail-ratio <ratio>", "locust: allowed failure ratio 0..1 (default: $LOCUST_MAX_FAIL_RATIO or 0)")
500
- .option("--no-create-project", "fail instead of creating the project when it does not exist")
501
388
  .option("--dry-run", "print what would be sent and exit without calling the API")
502
389
  .action(async (_flags, command) => {
503
390
  const opts = command.optsWithGlobals();
@@ -518,16 +405,16 @@ export function buildReportUploadCommand() {
518
405
  const maxFailRatio = Number(ratioRaw);
519
406
  if (!Number.isFinite(maxFailRatio) || maxFailRatio < 0 || maxFailRatio > 1)
520
407
  fail("--max-fail-ratio must be a number between 0 and 1");
521
- // 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.
522
- const versionRaw = opts.apiVersion ?? (process.env.NB_API_VERSION || undefined);
523
- 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
+ }
524
412
  if (opts.specHash !== undefined && opts.contractFile !== undefined)
525
413
  fail("--spec-hash and --contract-file are exclusive: one gives the hash, the other a file to take it from");
526
414
  const parsed = parseReport({
527
415
  format,
528
416
  kind,
529
417
  tool: checkedTool,
530
- components: checkComponents(opts.component),
531
418
  label: checkLabel(opts.label),
532
419
  toolVersion: checkToolVersion(opts.toolVersion),
533
420
  specHash: opts.contractFile !== undefined ? hashOfContractFile(opts.contractFile) : checkSpecHash(opts.specHash),
@@ -544,8 +431,6 @@ export function buildReportUploadCommand() {
544
431
  parsed.suite.metrics = { ...parsed.suite.metrics, coverage_pct: cov.coverage_pct };
545
432
  parsed.note += `, API coverage ${cov.coverage_pct}% (${cov.covered}/${cov.total} operations)`;
546
433
  }
547
- if (apiVersion !== undefined)
548
- parsed.suite.api_version = apiVersion;
549
434
  if (opts.metric !== undefined && opts.metric.length > 0) {
550
435
  const extra = parseMetrics(opts.metric);
551
436
  const merged = { ...parsed.suite.metrics, ...extra };
@@ -557,23 +442,18 @@ export function buildReportUploadCommand() {
557
442
  const ci = detectCi(process.env);
558
443
  const runKey = opts.runKey ?? ci.runKey ?? fail("Cannot determine the run key; pass --run-key");
559
444
  const attachment = opts.attach !== undefined ? prepareAttachment(opts.attach) : undefined;
560
- if (opts.specId !== undefined && opts.specFile !== undefined)
561
- fail("--spec-id and --spec-file are exclusive: one names a spec of the catalog, the other registers a file");
562
- if (opts.specEnvironment !== undefined && opts.specId === undefined && opts.specFile === undefined)
563
- fail("--spec-environment needs --spec-id or --spec-file");
564
- for (const [flag, value] of [["--spec-name", opts.specName], ["--spec-group", opts.specGroup], ["--spec-org", opts.specOrg]]) {
565
- if (value !== undefined && opts.specFile === undefined)
566
- 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)`);
567
454
  }
568
- const specEnvironment = opts.specEnvironment !== undefined ? checkSpecEnvironment(opts.specEnvironment) : undefined;
569
- let spec = opts.specId !== undefined ? { id: checkSpecId(opts.specId), ...(specEnvironment !== undefined ? { environment: specEnvironment } : {}) } : undefined;
570
- // The file is read and its name settled before anything is sent, so a bad path fails the command while nothing has happened yet.
571
- const specText = opts.specFile !== undefined ? readSpecFile(opts.specFile) : undefined;
572
- const specOrg = opts.specFile !== undefined ? checkOrg(opts.specOrg ?? process.env.NB_SPECS_ORG) : undefined;
573
- const projectId = checkProjectId(opts.projectId ?? process.env.NB_ASSURANCE_PROJECT_ID);
574
- const project = opts.project ?? ci.project ?? projectId ?? fail("Cannot determine the project name; pass --project <name> or --project-id <id>");
575
- if (projectId && opts.project)
576
- 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);
577
457
  const commit = opts.commit ?? ci.commitSha;
578
458
  const branch = opts.branch ?? ci.branch;
579
459
  const ciUrl = opts.ciUrl ?? ci.ciUrl;
@@ -582,7 +462,8 @@ export function buildReportUploadCommand() {
582
462
  const reportPath = opts.reportPath !== undefined ? checkReportPath(opts.reportPath) : readReportPath(file, commit);
583
463
  if (reportPath)
584
464
  parsed.suite.report_path = reportPath;
585
- const payload = {
465
+ const buildPayload = (repositoryId) => ({
466
+ repository_id: repositoryId,
586
467
  run: {
587
468
  key: runKey,
588
469
  ...(commit ? { commit_sha: commit } : {}),
@@ -592,63 +473,50 @@ export function buildReportUploadCommand() {
592
473
  ...(repoUrl ? { repo_url: repoUrl } : {}),
593
474
  },
594
475
  suite: parsed.suite,
595
- };
596
- 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 } } : {};
597
480
  if (opts.dryRun) {
598
- 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
+ }
599
493
  process.stderr.write(`(dry run) ${basename(dirname(file)) || "."}/${basename(file)}: ${parsed.note}\n`);
600
494
  return;
601
495
  }
602
- const env = opts.env || resolveEnv();
603
496
  const override = process.env.NB_BASE_URL?.replace(/\/$/, "");
604
497
  const baseUrl = override ?? resolveBaseUrl(loadSpec("assurance.yaml").servers, env);
605
- const token = opts.token || (await resolveAccessToken());
606
- // The catalog comes first: the project is tied to the spec it returns. It must not cost the result: a failure here is
607
- // kept, the result is reported without the link, and the command says so at the end.
608
- let pushed;
609
- let specError;
610
- if (opts.specFile !== undefined && specOrg !== undefined) {
611
- try {
612
- pushed = await pushSpec({
613
- conn: { baseUrl: specsBaseUrl(env), token, org: specOrg },
614
- file: opts.specFile,
615
- name: opts.specName,
616
- group: opts.specGroup,
617
- note: ciNote(ci, commit),
618
- });
619
- spec = { id: pushed.id, ...(specEnvironment !== undefined ? { environment: specEnvironment } : {}) };
620
- }
621
- catch (err) {
622
- specError = err;
623
- }
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`);
624
511
  }
625
- const result = await uploadReport({
626
- conn: { baseUrl, token },
627
- project,
628
- projectId,
629
- repo,
630
- createProject: opts.createProject,
631
- payload,
632
- spec,
633
- });
634
- if (attachment)
635
- await uploadAttachment({ baseUrl, token }, result, attachment);
636
- printJson({ ...result, ...(attachment ? { attachment: { name: attachment.name, size_bytes: attachment.bytes.length } } : {}), ...(pushed ? { catalog: pushed } : {}) });
637
- exportGithubOutput("project_id", result.project_id);
638
- if (pushed)
639
- exportGithubOutput("spec_id", pushed.id);
640
- process.stderr.write(`✓ ${kind}/${checkedTool} ${payload.suite.status}: ${parsed.note} -> project '${project}' (id ${result.project_id})` +
641
- `${result.project_created ? " (created)" : ""}, run '${runKey}'${result.replaced ? " (replaced)" : ""}` +
642
- `${attachment ? `, attached ${attachment.name} (${(attachment.bytes.length / 1024).toFixed(0)} KiB)` : ""}` +
643
- `${pushed ? `, spec ${pushed.name} v${pushed.version} (${pushed.action.replace("_", " ")})` : ""}` +
644
- `${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`);
645
- if (result.repo_changed_from !== undefined) {
646
- 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(","));
647
515
  }
648
- if (!projectId) {
649
- 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);
650
519
  }
651
- if (specError)
652
- 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);
653
521
  });
654
522
  }