@wirecat/cli-base 0.106.0 → 0.108.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.
Files changed (43) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/README.md +2 -1
  3. package/dist/codegen/fake.d.ts +64 -0
  4. package/dist/codegen/fake.js +341 -0
  5. package/dist/codegen/index.d.ts +11 -4
  6. package/dist/codegen/index.js +10 -3
  7. package/dist/codegen/manifest.d.ts +4 -1
  8. package/dist/codegen/manifest.js +69 -2
  9. package/dist/codegen/merge.d.ts +37 -0
  10. package/dist/codegen/merge.js +257 -0
  11. package/dist/codegen/model.d.ts +94 -0
  12. package/dist/codegen/openapi.d.ts +5 -1
  13. package/dist/codegen/openapi.js +102 -10
  14. package/dist/codegen/pagination.d.ts +14 -0
  15. package/dist/codegen/pagination.js +129 -0
  16. package/dist/codegen/patch.d.ts +28 -0
  17. package/dist/codegen/patch.js +75 -0
  18. package/dist/codegen/pipeline.d.ts +52 -1
  19. package/dist/codegen/pipeline.js +198 -4
  20. package/dist/codegen/swagger.d.ts +7 -0
  21. package/dist/codegen/swagger.js +39 -0
  22. package/dist/credentials.d.ts +2 -2
  23. package/dist/credentials.js +17 -3
  24. package/dist/dev/conformance.d.ts +0 -2
  25. package/dist/dev/conformance.js +3 -9
  26. package/dist/dev/main.js +11 -3
  27. package/dist/dev/ready.d.ts +30 -0
  28. package/dist/dev/ready.js +249 -0
  29. package/dist/dev/slow-tests.d.ts +6 -1
  30. package/dist/dev/slow-tests.js +14 -2
  31. package/dist/http/fetch.js +21 -1
  32. package/dist/standards/audit.js +2 -1
  33. package/dist/standards/errors.js +6 -0
  34. package/dist/standards/index.d.ts +1 -0
  35. package/dist/standards/index.js +1 -0
  36. package/dist/standards/monthly.d.ts +5 -0
  37. package/dist/standards/monthly.js +12 -0
  38. package/docs/standards/README.md +1 -1
  39. package/docs/standards/ci.md +4 -2
  40. package/docs/standards/kit-surface.md +138 -0
  41. package/docs/standards/new-cli.md +14 -7
  42. package/docs/standards/testing.md +22 -1
  43. package/package.json +11 -1
@@ -1,6 +1,7 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { dirname, extname, join } from "node:path";
3
3
  import { identifier, kebab } from "./names.js";
4
+ import { answerPaths, detectPagination, requestParameters } from "./pagination.js";
4
5
  export class CodegenError extends Error {
5
6
  problems;
6
7
  constructor(problems) {
@@ -9,6 +10,108 @@ export class CodegenError extends Error {
9
10
  this.name = "CodegenError";
10
11
  }
11
12
  }
13
+ /**
14
+ * A POST to these paths only reads, as HubSpot's and Notion's search and query do. Opt-in through `readingPosts`: a
15
+ * wrong guess turns a write into a read (a `/database/query` that runs any SQL).
16
+ */
17
+ const READING_POST = /[/:](search|query)$/i;
18
+ export const READING_POST_REASON = "a POST to a …/search or …/query path only reads (readingPosts rule)";
19
+ const applyReadingPosts = (model) => ({
20
+ ...model,
21
+ operations: model.operations.map((operation) => operation.binding.kind === "http" &&
22
+ operation.binding.method === "POST" &&
23
+ READING_POST.test(operation.binding.path)
24
+ ? { ...operation, effect: "read", effectReason: READING_POST_REASON }
25
+ : operation),
26
+ });
27
+ const COMMAND = /^[a-z0-9]+(-[a-z0-9]+)*$/;
28
+ const VERSION = /^(v\d+(\.\d+)*|\d{4}-\d{2}(-[a-z]+)?)$/i;
29
+ const isParameter = (segment) => segment.startsWith("{");
30
+ /** `contacts-list`, `contacts-get`, `contacts-create`, `contacts-batch-archive`: segments, then what the method does. */
31
+ const commandFromPath = (operation, all, names) => {
32
+ if (operation.binding.kind !== "http")
33
+ return kebab(operation.id);
34
+ const { method, path } = operation.binding;
35
+ const parts = path.split("/").filter(Boolean);
36
+ const words = parts
37
+ .filter((segment) => !isParameter(segment) && !VERSION.test(segment))
38
+ .map((segment) => names.segments && Object.hasOwn(names.segments, segment) ? names.segments[segment] : kebab(segment))
39
+ .filter(Boolean);
40
+ const onItem = isParameter(parts.at(-1) ?? "");
41
+ // A POST to a path that also lists or holds items creates one; to any other path it is the action the path names.
42
+ const collection = all.some((other) => other.binding.kind === "http" &&
43
+ ((other.binding.method === "GET" && other.binding.path === path) ||
44
+ (other.binding.path.startsWith(`${path}/{`) && !other.binding.path.slice(path.length + 1).includes("/"))));
45
+ const verb = {
46
+ GET: onItem ? "get" : "list",
47
+ HEAD: "head",
48
+ DELETE: "delete",
49
+ PATCH: "update",
50
+ PUT: onItem || collection ? "replace" : "",
51
+ POST: onItem ? "update" : collection ? "create" : "",
52
+ }[method];
53
+ return [...words, verb].filter(Boolean).join("-");
54
+ };
55
+ export const applyNames = (model, names) => {
56
+ const known = new Set(model.operations.map((operation) => operation.id));
57
+ const segments = new Set(model.operations.flatMap((operation) => operation.binding.kind === "http" ? operation.binding.path.split("/") : []));
58
+ const problems = [
59
+ ...Object.keys(names.commands ?? {}).flatMap((id) => known.has(id) ? [] : [`names: "${id}" matches no operation`]),
60
+ ...Object.keys(names.segments ?? {}).flatMap((segment) => segments.has(segment) ? [] : [`names: segment "${segment}" is in no path`]),
61
+ ];
62
+ const operations = model.operations.map((operation) => {
63
+ const own = names.commands && Object.hasOwn(names.commands, operation.id) ? names.commands[operation.id] : undefined;
64
+ const command = own ?? (names.fromPath ? commandFromPath(operation, model.operations, names) : undefined);
65
+ if (command === undefined)
66
+ return operation;
67
+ // An empty or malformed name would otherwise fall back to the id, the name `names` exists to avoid.
68
+ if (!COMMAND.test(command)) {
69
+ const where = operation.binding.kind === "http" ? ` (${operation.binding.method} ${operation.binding.path})` : "";
70
+ problems.push(`names: operation "${operation.id}"${where} gets "${command}", not a kebab-case command; map it in commands`);
71
+ }
72
+ return { ...operation, command };
73
+ });
74
+ if (problems.length > 0)
75
+ throw new CodegenError(problems);
76
+ return { ...model, operations };
77
+ };
78
+ /** Each read's pagination, detected unless an override set it, or said with `null` that the read does not page. */
79
+ export const applyPagination = (model, overrides, detect) => {
80
+ const schemas = new Map(model.schemas.map((schema) => [schema.id, schema]));
81
+ const problems = [];
82
+ const operations = model.operations.map((operation) => {
83
+ const override = overrides[operation.id];
84
+ if (override?.pagination === null)
85
+ return operation;
86
+ if (override?.pagination) {
87
+ const at = `override "${operation.id}": pagination`;
88
+ if (operation.effect !== "read")
89
+ problems.push(`${at} on an operation that is not a read`);
90
+ const request = requestParameters(operation, schemas);
91
+ const answer = answerPaths(operation, schemas);
92
+ const { style: _, ...fields } = override.pagination;
93
+ for (const [field, value] of Object.entries(fields)) {
94
+ if (typeof value === "string") {
95
+ // An answer without a schema has nothing to check the path against.
96
+ if (answer.size > 0 && !answer.has(value))
97
+ problems.push(`${at} reads ${field} from "${value}", which the answer lacks`);
98
+ continue;
99
+ }
100
+ const parameter = value;
101
+ if (!parameter || typeof parameter !== "object" || typeof parameter.name !== "string")
102
+ problems.push(`${at}: ${field} must name a parameter`);
103
+ else if (!request.some((one) => one.in === parameter.in && one.name === parameter.name))
104
+ problems.push(`${at} names ${parameter.in} "${parameter.name}", which the operation does not take`);
105
+ }
106
+ return { ...operation, pagination: override.pagination, paginationSource: `override: ${override.reason}` };
107
+ }
108
+ const found = detect ? detectPagination(operation, schemas) : undefined;
109
+ return found ? { ...operation, pagination: found, paginationSource: "detected" } : operation;
110
+ });
111
+ if (problems.length > 0)
112
+ throw new CodegenError(problems);
113
+ return { ...model, operations };
114
+ };
12
115
  export const applyOverrides = (model, overrides) => {
13
116
  const known = new Set(model.operations.map((operation) => operation.id));
14
117
  const stale = Object.keys(overrides).filter((id) => !known.has(id));
@@ -20,10 +123,87 @@ export const applyOverrides = (model, overrides) => {
20
123
  ...model,
21
124
  operations: model.operations.map((operation) => {
22
125
  const override = overrides[operation.id];
23
- return override?.effect ? { ...operation, effect: override.effect } : operation;
126
+ return override?.effect
127
+ ? { ...operation, effect: override.effect, effectReason: `override: ${override.reason}` }
128
+ : operation;
24
129
  }),
25
130
  };
26
131
  };
132
+ /** The top-level property names a body may carry, through references, inheritance, unions and subtypes. */
133
+ const bodyFields = (node, schemas, seen = new Set()) => {
134
+ switch (node.type) {
135
+ case "ref": {
136
+ const target = schemas.get(node.ref);
137
+ if (!target || seen.has(node.ref))
138
+ return [];
139
+ const inner = new Set([...seen, node.ref]);
140
+ const subtypes = Object.values(target.discriminator?.mapping ?? {}).flatMap((id) => bodyFields({ type: "ref", ref: id }, schemas, inner));
141
+ return [...bodyFields(target.schema, schemas, inner), ...subtypes];
142
+ }
143
+ case "object":
144
+ return Object.keys(node.properties);
145
+ case "union":
146
+ case "allOf":
147
+ return node.of.flatMap((member) => bodyFields(member, schemas, seen));
148
+ default:
149
+ return [];
150
+ }
151
+ };
152
+ export const applyPermissionRule = (model, rule) => {
153
+ const known = new Set(model.operations.map((operation) => operation.id));
154
+ const stale = (rule.shares ?? []).filter((id) => !known.has(id));
155
+ if (stale.length > 0)
156
+ throw new CodegenError(stale.map((id) => `shares: "${id}" matches no operation`));
157
+ const flags = rule.deletingFlags ?? [];
158
+ const schemas = new Map(model.schemas.map((schema) => [schema.id, schema]));
159
+ const fields = new Map(model.operations.map((operation) => [
160
+ operation.id,
161
+ new Set(operation.requestBody?.schema ? bodyFields(operation.requestBody.schema, schemas) : []),
162
+ ]));
163
+ const fieldsOf = (operation) => fields.get(operation.id) ?? new Set();
164
+ const unused = flags.filter((flag) => !model.operations.some((operation) => fieldsOf(operation).has(flag) ||
165
+ operation.parameters.some((parameter) => parameter.in === "query" && parameter.name === flag)));
166
+ if (unused.length > 0)
167
+ throw new CodegenError(unused.map((flag) => `deletingFlags: "${flag}" is in no request body or query`));
168
+ return {
169
+ ...model,
170
+ operations: model.operations.map((operation) => {
171
+ const group = typeof rule.group === "string" ? rule.group : rule.group(operation);
172
+ const permissions = [];
173
+ if (rule.shares?.includes(operation.id))
174
+ permissions.push({ key: `${group}.share` });
175
+ if (operation.effect === "destructive")
176
+ permissions.push({ key: `${group}.delete` });
177
+ else {
178
+ const body = flags.filter((flag) => fieldsOf(operation).has(flag));
179
+ const query = flags.filter((flag) => operation.parameters.some((parameter) => parameter.in === "query" && parameter.name === flag));
180
+ if (body.length > 0 || query.length > 0)
181
+ permissions.push({
182
+ key: `${group}.delete`,
183
+ ...(body.length > 0 ? { body } : {}),
184
+ ...(query.length > 0 ? { query } : {}),
185
+ });
186
+ }
187
+ return permissions.length > 0 ? { ...operation, permissions } : operation;
188
+ }),
189
+ };
190
+ };
191
+ const applyAuth = (model, auth) => {
192
+ const names = new Set(Object.keys(auth.securitySchemes));
193
+ const unknown = [...new Set(auth.security.flatMap(Object.keys))].filter((name) => !names.has(name));
194
+ if (unknown.length > 0)
195
+ throw new CodegenError(unknown.map((name) => `auth: security names "${name}", which securitySchemes lacks`));
196
+ return {
197
+ ...model,
198
+ securitySchemes: auth.securitySchemes,
199
+ security: auth.security,
200
+ securityReason: auth.reason,
201
+ // A requirement naming the source's own schemes is replaced; `[]`, "no sign-in", stays.
202
+ operations: model.operations.map(({ security, ...operation }) => security?.every((requirement) => Object.keys(requirement).every((name) => names.has(name)))
203
+ ? { ...operation, security }
204
+ : operation),
205
+ };
206
+ };
27
207
  const bindingKey = (operation) => operation.binding.kind === "http"
28
208
  ? `${operation.binding.method} ${operation.binding.path}`
29
209
  : `rpc ${operation.binding.name}`;
@@ -90,8 +270,12 @@ export const validateModel = (model) => {
90
270
  for (const id of duplicates(model.schemas.map((schema) => schema.id))) {
91
271
  problems.push(`two schemas share the id "${id}"`);
92
272
  }
93
- for (const command of duplicates(model.operations.map((operation) => kebab(operation.id)))) {
94
- problems.push(`two operations both become the command "${command}"`);
273
+ const commandOf = (operation) => operation.command ?? kebab(operation.id);
274
+ for (const command of duplicates(model.operations.map(commandOf))) {
275
+ const ids = model.operations
276
+ .filter((operation) => commandOf(operation) === command)
277
+ .map((operation) => operation.id);
278
+ problems.push(`two operations both become the command "${command}": ${ids.join(", ")}`);
95
279
  }
96
280
  for (const name of duplicates(model.schemas.map((schema) => identifier(schema.id)))) {
97
281
  problems.push(`two schemas both become the name "${name}"`);
@@ -154,6 +338,11 @@ export const validateModel = (model) => {
154
338
  unresolved(`operation "${operation.id}" request`, operation.requestBody?.schema);
155
339
  unresolved(`operation "${operation.id}" response`, operation.response?.schema);
156
340
  }
341
+ const schemes = new Set(Object.keys(model.securitySchemes ?? {}));
342
+ const named = [model.security ?? [], ...model.operations.map((operation) => operation.security ?? [])];
343
+ for (const name of new Set(named.flat().flatMap(Object.keys)))
344
+ if (!schemes.has(name))
345
+ problems.push(`security names "${name}", which securitySchemes lacks`);
157
346
  problems.push(...mergeCycles(model));
158
347
  if (problems.length > 0)
159
348
  throw new CodegenError(problems);
@@ -164,7 +353,12 @@ const commentFor = (path, lines) => {
164
353
  return `${lines.map((line) => `// ${line}`).join("\n")}\n\n`;
165
354
  };
166
355
  export const generate = (model, generators, options) => {
167
- const prepared = applyOverrides(model, options.overrides ?? {});
356
+ const overridden = applyOverrides(options.readingPosts ? applyReadingPosts(model) : model, options.overrides ?? {});
357
+ const paged = applyPagination(overridden, options.overrides ?? {}, options.pagination === true);
358
+ const named = options.names ? applyNames(paged, options.names) : paged;
359
+ const authed = options.auth ? applyAuth(named, options.auth) : named;
360
+ // After the overrides: an operation an override calls destructive is a delete too.
361
+ const prepared = options.permissions ? applyPermissionRule(authed, options.permissions) : authed;
168
362
  validateModel(prepared);
169
363
  const artifacts = generators.flatMap((generator) => generator(prepared));
170
364
  const clashing = duplicates(artifacts.map((artifact) => artifact.path));
@@ -0,0 +1,7 @@
1
+ type Json = Record<string, unknown>;
2
+ /**
3
+ * An OpenAPI 3 document, from an OpenAPI 3 document (returned as it is), a Swagger 2.0 one, or a Swagger 1.2 resource
4
+ * listing with its API declarations keyed by the listing's `apis[].path` (each served at `basePath` + that path).
5
+ */
6
+ export declare const upgradeToOpenApi3: (document: unknown, declarations?: Readonly<Record<string, unknown>>) => Promise<Json>;
7
+ export {};
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Swagger 1.2 and 2.0 → OpenAPI 3, so `adaptOpenApi` reads one format. Build-time only: the two converters are
3
+ * optional peer dependencies, loaded on first use, and a CLI that converts installs them as dev dependencies.
4
+ */
5
+ import { isObject, OpenApiError } from "./openapi.js";
6
+ const load = async (name, use) => {
7
+ try {
8
+ return (await import(name));
9
+ }
10
+ catch (error) {
11
+ const { code, message } = error;
12
+ if (code !== "ERR_MODULE_NOT_FOUND" || !message?.includes(`'${name}'`))
13
+ throw error;
14
+ throw new OpenApiError([`${use} needs ${name}: add it to the CLI's devDependencies`]);
15
+ }
16
+ };
17
+ /**
18
+ * An OpenAPI 3 document, from an OpenAPI 3 document (returned as it is), a Swagger 2.0 one, or a Swagger 1.2 resource
19
+ * listing with its API declarations keyed by the listing's `apis[].path` (each served at `basePath` + that path).
20
+ */
21
+ export const upgradeToOpenApi3 = async (document, declarations) => {
22
+ if (!isObject(document))
23
+ throw new OpenApiError(["not an OpenAPI or Swagger document"]);
24
+ if (typeof document.openapi === "string" && document.openapi.startsWith("3."))
25
+ return document;
26
+ let swagger2 = document;
27
+ if (typeof document.swaggerVersion === "string" && document.swaggerVersion.startsWith("1.")) {
28
+ if (!declarations)
29
+ throw new OpenApiError(["a Swagger 1.x resource listing needs its API declarations"]);
30
+ const converter = await load("swagger-converter", "Swagger 1.x");
31
+ swagger2 = converter.default.convert(document, declarations);
32
+ }
33
+ else if (document.swagger !== "2.0") {
34
+ throw new OpenApiError(["not an OpenAPI 3, Swagger 2.0 or Swagger 1.x document"]);
35
+ }
36
+ const { upgrade } = await load("@scalar/openapi-upgrader", "Swagger");
37
+ // The upgrader changes the document it is given, which is the caller's own for Swagger 2.0.
38
+ return upgrade(structuredClone(swagger2), "3.0");
39
+ };
@@ -49,8 +49,8 @@ export interface WriteOptions {
49
49
  * Environment first, then the OS keyring, then a file. In `auto`, a file that holds the account is read before the
50
50
  * keyring and keeps its refreshes, so a locked keyring is not tried again for it; a sign-in moves it back.
51
51
  *
52
- * `auto` does not probe whether a keyring exists: it attempts the operation, and on failure warns
53
- * once per run and falls through. A probe would touch the user's keychain for nothing and could still
52
+ * `auto` does not probe whether a keyring exists: it attempts the operation, and on a failed write or removal warns
53
+ * once per run and falls through. A failed read with no file entry throws `keyring.unreachable`. A probe would touch the user's keychain for nothing and could still
54
54
  * succeed where the real operation fails.
55
55
  */
56
56
  export declare class Credentials {
@@ -21,8 +21,8 @@ const warnedRuns = new WeakSet();
21
21
  * Environment first, then the OS keyring, then a file. In `auto`, a file that holds the account is read before the
22
22
  * keyring and keeps its refreshes, so a locked keyring is not tried again for it; a sign-in moves it back.
23
23
  *
24
- * `auto` does not probe whether a keyring exists: it attempts the operation, and on failure warns
25
- * once per run and falls through. A probe would touch the user's keychain for nothing and could still
24
+ * `auto` does not probe whether a keyring exists: it attempts the operation, and on a failed write or removal warns
25
+ * once per run and falls through. A failed read with no file entry throws `keyring.unreachable`. A probe would touch the user's keychain for nothing and could still
26
26
  * succeed where the real operation fails.
27
27
  */
28
28
  export class Credentials {
@@ -57,7 +57,14 @@ export class Credentials {
57
57
  return { secret: fromFile, source: "file" };
58
58
  if (this.#storage !== "file") {
59
59
  const temporary = this.#temporaryService;
60
- const fromKeyring = this.#tryKeyring(() => (temporary && this.#keyring.get(temporary, account)) || this.#keyring.get(this.#service, account));
60
+ let fromKeyring;
61
+ try {
62
+ fromKeyring = (temporary && this.#keyring.get(temporary, account)) || this.#keyring.get(this.#service, account);
63
+ }
64
+ catch (error) {
65
+ // Answering "not signed in" here sends the owner to sign in again while the entry sits in the keyring.
66
+ throw this.#unreachable(account, error);
67
+ }
61
68
  if (fromKeyring)
62
69
  return { secret: fromKeyring, source: "keyring" };
63
70
  }
@@ -146,6 +153,13 @@ export class Credentials {
146
153
  #writeFile(store) {
147
154
  writeSecurely(this.#path(), `${JSON.stringify(store, null, 2)}\n`, 0o600);
148
155
  }
156
+ #unreachable(account, error) {
157
+ const where = this.#storage === "keyring" ? "" : `, and ${this.#path()} holds no sign-in for ${account}`;
158
+ return new CliError("configuration_error", `the OS keyring did not answer (${error instanceof Error ? error.message : String(error)})${where}. ` +
159
+ "On Linux a restarted session bus is a known cause: log out and back in, or set " +
160
+ "DBUS_SESSION_BUS_ADDRESS=unix:path=$XDG_RUNTIME_DIR/bus. On a machine with no keyring, sign in with file " +
161
+ "storage.", { reason: "keyring.unreachable" });
162
+ }
149
163
  #tryKeyring(operation) {
150
164
  if (this.#storage === "keyring")
151
165
  return operation();
@@ -44,8 +44,6 @@ export declare const environmentProblems: (shell: Shell, slug: string) => {
44
44
  problems: string[];
45
45
  skipped?: string;
46
46
  };
47
- /** The WC-CI-9 table of taken monthly minutes, as `HH:MM → repository`. */
48
- export declare const takenMinutes: (ciPage: string) => Map<string, string>;
49
47
  export declare const cronProblems: (workflow: string | undefined, repo: string, taken: Map<string, string>) => string[];
50
48
  export declare const parityProblems: (cli: string, ownGroups: unknown) => string[];
51
49
  export declare const CONFORMANCE_USAGE = " release-pr --base <commit> --body <file>\n a pull request that changes package.json's version since --base\n needs a non-empty \"## Conformance\" section in its description\n live record --script <path> [--file <path>]\n appends \"<version> <commit> <date> <script> <tree>\" to docs/dev/live-checks.txt\n after a live check passed; <tree> hashes the committed src/,\n package.json and lockfile, which must be committed\n live check [--version <x.y.z>] [--file <path>]\n fails unless that version has a record and src/, package.json\n and the lockfile are the ones it hashed; needs no commit object,\n so a squash-merged release branch passes\n repo-check --cli <name> [--groups <file>]\n main's ruleset and its required checks, the npm environment\n limited to main (through gh; skipped without a login or network),\n monthly.yml's cron minute against WC-CI-9's list, and the CLI in\n a parity group (cli-base's, or --groups', config/parity-groups.json)";
@@ -1,10 +1,10 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { appendFileSync, existsSync, readFileSync } from "node:fs";
3
- import { dirname, join, resolve } from "node:path";
4
- import { fileURLToPath } from "node:url";
3
+ import { join, resolve } from "node:path";
5
4
  import { parseArgs } from "node:util";
6
5
  import { packageVersion } from "../release/index.js";
7
6
  import { defineParityGroups, PARITY_GROUPS } from "../standards/audit.js";
7
+ import { takenMinutes } from "../standards/monthly.js";
8
8
  import { PROGRAM_PREFIX } from "../wcat/names.js";
9
9
  import { processShell } from "./land.js";
10
10
  import { binNames } from "./wcat-lint.js";
@@ -248,11 +248,6 @@ export const environmentProblems = (shell, slug) => {
248
248
  ? { problems: [] }
249
249
  : { problems: [`the npm environment deploys from ${names.join(", ") || "no branch"}, not only main: ${limit}`] };
250
250
  };
251
- /** The WC-CI-9 table of taken monthly minutes, as `HH:MM → repository`. */
252
- export const takenMinutes = (ciPage) => new Map([...ciPage.matchAll(/^\s*\|\s*(\d\d:\d\d)\s*\|\s*([\w.-]+)\s*\|\s*$/gm)].map(([, time, repo]) => [
253
- time,
254
- repo,
255
- ]));
256
251
  export const cronProblems = (workflow, repo, taken) => {
257
252
  if (workflow === undefined)
258
253
  return [".github/workflows/monthly.yml is missing (WC-CI-9)"];
@@ -274,7 +269,6 @@ export const parityProblems = (cli, ownGroups) => {
274
269
  ? []
275
270
  : [`${cli} is in no parity group: add it to cli-base's PARITY_GROUPS (new-cli.md, step 4)`];
276
271
  };
277
- const ciPagePath = () => join(dirname(fileURLToPath(import.meta.url)), "../../docs/standards/ci.md");
278
272
  const repoCheck = (args, io, shell) => {
279
273
  const { values } = parseArgs({
280
274
  args,
@@ -303,7 +297,7 @@ const repoCheck = (args, io, shell) => {
303
297
  const problems = [
304
298
  ...ruleset.problems,
305
299
  ...environment.problems,
306
- ...cronProblems(read(".github/workflows/monthly.yml"), slug.split("/")[1] ?? "", takenMinutes(readFileSync(ciPagePath(), "utf8"))),
300
+ ...cronProblems(read(".github/workflows/monthly.yml"), slug.split("/")[1] ?? "", takenMinutes()),
307
301
  ...parityProblems(values.cli, groups === undefined ? undefined : JSON.parse(groups)),
308
302
  ];
309
303
  for (const problem of problems)
package/dist/dev/main.js CHANGED
@@ -29,13 +29,15 @@ import { changelogChange, landChange, landFold, newestTag, processShell, restore
29
29
  import { baselineOf, judge, lintCommands, misfiled, RUN_LOG_COMMANDS, walk } from "./lint.js";
30
30
  import { readSources } from "./network.js";
31
31
  import { nextVersion } from "./next-version.js";
32
+ import { READY_USAGE, ready } from "./ready.js";
32
33
  import { readDeclarations } from "./result-shape.js";
33
34
  import { slowTests } from "./slow-tests.js";
34
35
  import { matrixPage, matrixRows, parseArgvLog } from "./test-matrix.js";
35
36
  import { binNameWarnings, describeWarnings, hostsWarnings, WCAT_RULES } from "./wcat-lint.js";
36
37
  const USAGE = `usage: cli-dev <command> [options]
37
38
 
38
- slow-tests [report] [count] the slowest tests and files (report: coverage/tests.json, count: 20)
39
+ slow-tests [report] [count] the slowest tests and files (report: coverage/tests.json, count: 20);
40
+ warns on stderr about each test over 3 s, and still exits 0
39
41
  next-version <wanted> <latest> <versions-json>
40
42
  the version bin/release publishes, given npm's answers
41
43
  version [--sync] [--file <path>] package.json's version against src/version.ts
@@ -104,7 +106,8 @@ const USAGE = `usage: cli-dev <command> [options]
104
106
  --harmless names a third-party file whose import.meta or
105
107
  __dirname was read and found harmless. Fails when a bundled
106
108
  module would look for a file or package in the wrong place
107
- ${CONFORMANCE_USAGE}`;
109
+ ${CONFORMANCE_USAGE}
110
+ ${READY_USAGE}`;
108
111
  const load = async (cwd, path) => (await import(pathToFileURL(isAbsolute(path) ? path : join(cwd, path)).href));
109
112
  const report = (io, problems, ok) => {
110
113
  for (const problem of problems)
@@ -914,7 +917,10 @@ export const main = async (argv, io) => {
914
917
  case "slow-tests": {
915
918
  const [file = "coverage/tests.json", count = "20"] = args;
916
919
  const parsed = JSON.parse(readFileSync(join(io.cwd, file), "utf8"));
917
- io.out(slowTests(parsed, io.cwd, Number(count)));
920
+ const { out, warning } = slowTests(parsed, io.cwd, Number(count));
921
+ io.out(out);
922
+ if (warning)
923
+ io.err(warning);
918
924
  return 0;
919
925
  }
920
926
  case "next-version": {
@@ -953,6 +959,8 @@ export const main = async (argv, io) => {
953
959
  return audit(args, io);
954
960
  case "bundle":
955
961
  return bundleCommand(args, io);
962
+ case "ready":
963
+ return ready(args, io, processShell(io.cwd));
956
964
  case "adopt": {
957
965
  const { values, positionals } = parseArgs({
958
966
  args,
@@ -0,0 +1,30 @@
1
+ import type { Shell } from "./land.js";
2
+ interface DevIo {
3
+ cwd: string;
4
+ out: (text: string) => void;
5
+ err: (text: string) => void;
6
+ }
7
+ export type ReadyStatus = "verified" | "partially" | "not verified" | "unsupported";
8
+ export interface ReadyRow {
9
+ id: string;
10
+ title: string;
11
+ status: ReadyStatus;
12
+ /** A passing script, a test file that runs a contract, a live-check record's line; why a row is not verified. */
13
+ evidence: string[];
14
+ /** The one thing to do for this row, when it is not verified. */
15
+ fix?: string;
16
+ }
17
+ export interface ReadyReport {
18
+ category?: string;
19
+ rows: ReadyRow[];
20
+ /** The fix of the first row that is not verified, or nothing when every row is verified or unsupported. */
21
+ next?: string;
22
+ }
23
+ export declare const designCategory: (design: string) => string | undefined;
24
+ /** Where `ready` asks vitest for its JSON report; `coverage/` is git-ignored in every CLI. */
25
+ export declare const READY_TESTS = "coverage/ready-tests.json";
26
+ export declare const readyReport: (io: DevIo, shell: Shell) => ReadyReport;
27
+ export declare const readyText: (report: ReadyReport) => string;
28
+ export declare const ready: (args: string[], io: DevIo, shell: Shell) => number;
29
+ export declare const READY_USAGE = " ready [--json] runs the CLI's checks in order (typecheck and lint, tests and its\n category's cli-core contracts, the family audit, docs:check,\n generate:check, smoke, security:no-leak,\n deps:check) and reads the live-check record; prints each row as\n verified, partially, not verified or unsupported with its evidence,\n and the one next step; exits 1 until every row is verified or\n unsupported";
30
+ export {};