@wirecat/cli-base 0.107.0 → 0.109.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 +110 -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 +12 -4
  6. package/dist/codegen/index.js +11 -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 +57 -1
  19. package/dist/codegen/pipeline.js +214 -6
  20. package/dist/codegen/skill.d.ts +35 -0
  21. package/dist/codegen/skill.js +171 -0
  22. package/dist/codegen/swagger.d.ts +7 -0
  23. package/dist/codegen/swagger.js +39 -0
  24. package/dist/credentials.d.ts +2 -2
  25. package/dist/credentials.js +17 -3
  26. package/dist/dev/conformance.d.ts +0 -2
  27. package/dist/dev/conformance.js +3 -9
  28. package/dist/dev/main.js +5 -1
  29. package/dist/dev/ready.d.ts +30 -0
  30. package/dist/dev/ready.js +310 -0
  31. package/dist/dev/slow-tests.d.ts +1 -0
  32. package/dist/http/fetch.js +21 -1
  33. package/dist/standards/audit.js +2 -1
  34. package/dist/standards/errors.js +6 -0
  35. package/dist/standards/index.d.ts +1 -0
  36. package/dist/standards/index.js +1 -0
  37. package/dist/standards/monthly.d.ts +5 -0
  38. package/dist/standards/monthly.js +12 -0
  39. package/docs/standards/ci.md +4 -2
  40. package/docs/standards/kit-surface.md +166 -0
  41. package/docs/standards/layout.md +1 -1
  42. package/docs/standards/new-cli.md +18 -7
  43. package/package.json +11 -1
@@ -1,6 +1,7 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import { dirname, extname, join } from "node:path";
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { dirname, extname, join, posix } 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;
129
+ }),
130
+ };
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;
24
188
  }),
25
189
  };
26
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));
@@ -188,5 +382,19 @@ export const writeArtifacts = (artifacts, options) => {
188
382
  mkdirSync(dirname(target), { recursive: true });
189
383
  writeFileSync(target, content);
190
384
  }
385
+ const generated = new Set(artifacts.map((artifact) => posix.normalize(artifact.path)));
386
+ for (const owned of options.owns ?? []) {
387
+ const folder = posix.normalize(owned).replace(/\/+$/, "");
388
+ if (!existsSync(join(options.root, folder)))
389
+ continue;
390
+ for (const entry of readdirSync(join(options.root, folder), { withFileTypes: true })) {
391
+ const path = posix.join(folder, entry.name);
392
+ if (!entry.isFile() || generated.has(path))
393
+ continue;
394
+ stale.push(path);
395
+ if (!options.check)
396
+ rmSync(join(options.root, path));
397
+ }
398
+ }
191
399
  return stale;
192
400
  };
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The API part of a CLI's agent skill: `references/api.md`, a short index, and `references/api/api-<group>.md`, one
3
+ * file per first tag of the operations, so an agent loads only the group it needs (`<cli> skill show api-<group>`). Each command,
4
+ * its usage, arguments and flags come from the built program's command tree, as `--help` prints them; the manifest
5
+ * adds only what the API says: the HTTP call, the effect, sign-in scopes, permission keys and paging.
6
+ */
7
+ import type { CommandInfo } from "../commands/registry.js";
8
+ import type { ManifestOperation } from "./manifest.js";
9
+ import type { GeneratedArtifact } from "./model.js";
10
+ export interface ApiSkillOptions {
11
+ /** The command word `skill show` runs under: `notion`. */
12
+ cli: string;
13
+ /** The skill's folder, beside its SKILL.md: `skills/notion-cli`. */
14
+ folder: string;
15
+ /**
16
+ * The files already in that folder, relative to it, as `skillFiles` lists them: `skill show` finds a part by its
17
+ * base name, so a hand-written `api-pages.md` elsewhere would hide the generated one.
18
+ */
19
+ files: readonly string[];
20
+ /** The service, for the headings: `Notion`. */
21
+ service: string;
22
+ operations: readonly ManifestOperation[];
23
+ /** The SKILL.md beside these files, as text: an agent reaches them only through its link to `references/api.md`. */
24
+ skill: string;
25
+ /** `describeProgram(createProgram())`: the generated commands carry `api_operation`. */
26
+ commands: readonly CommandInfo[];
27
+ banner: string;
28
+ }
29
+ export declare const API_SKILL_INDEX = "references/api.md";
30
+ export declare const API_SKILL_GROUPS = "references/api";
31
+ /**
32
+ * Throws `CodegenError` when an operation has no command or a generated command names no operation: a flag is
33
+ * never taken from anywhere but the command tree. Sorted, and with no version or date, so `generate:check` holds.
34
+ */
35
+ export declare const apiSkillFiles: (options: ApiSkillOptions) => GeneratedArtifact[];
@@ -0,0 +1,171 @@
1
+ import { flatten } from "../commands/registry.js";
2
+ import { kebab } from "./names.js";
3
+ import { CodegenError } from "./pipeline.js";
4
+ export const API_SKILL_INDEX = "references/api.md";
5
+ export const API_SKILL_GROUPS = "references/api";
6
+ const firstLine = (value) => (value ?? "").split(/\r\n|[\r\n\u2028\u2029]/)[0]?.trim() ?? "";
7
+ /**
8
+ * Vendor text becomes instructions an agent follows: its first line only, HTML and every Markdown mark escaped, and
9
+ * always after a label, so no heading, list, fence or link can start it.
10
+ */
11
+ const text = (value) => firstLine(value)
12
+ .replaceAll("&", "&amp;")
13
+ .replaceAll("<", "&lt;")
14
+ .replaceAll(">", "&gt;")
15
+ .replace(/[\\`*_[\]~|]/g, "\\$&");
16
+ /** A code span; in a table cell `|` still ends the cell, so it is escaped there. */
17
+ const code = (value, cell = false) => {
18
+ const plain = value.replace(/[\r\n\u2028\u2029]+/g, " ").replaceAll("`", "'");
19
+ return `\`${cell ? plain.replaceAll("|", "\\|") : plain}\``;
20
+ };
21
+ const pages = (pagination) => {
22
+ const sent = (parameter) => `${code(parameter.name)} (${parameter.in})`;
23
+ const limit = "limit" in pagination && pagination.limit ? `; page size in ${sent(pagination.limit)}` : "";
24
+ const items = pagination.items ? `; items in ${code(pagination.items)}` : "";
25
+ const total = "total" in pagination && pagination.total ? `; the count of all in ${code(pagination.total)}` : "";
26
+ switch (pagination.style) {
27
+ case "cursor": {
28
+ const more = pagination.hasMore ? `; ${code(pagination.hasMore)} is false on the last page` : "";
29
+ return `cursor: send ${sent(pagination.cursor)}, read the next one from ${code(pagination.next)}${items}${more}${limit}`;
30
+ }
31
+ case "offset":
32
+ return `offset: send ${sent(pagination.offset)}, raised by the items read so far${items}${total}${limit}`;
33
+ case "page":
34
+ return `page number: send ${sent(pagination.page)}, one more for each page${items}${total}${limit}`;
35
+ case "link":
36
+ return `the answer's ${code(pagination.next)} is the next page's address${items}`;
37
+ }
38
+ };
39
+ const flagRow = (option) => `| ${code(option.flags, true)} | ${option.mandatory ? "yes" : "no"} | ${text(option.description)} |`;
40
+ const section = (operation, command) => {
41
+ const call = operation.binding.kind === "http" ? `${operation.binding.method} ${operation.binding.path}` : operation.binding.name;
42
+ const scopes = (operation.security ?? []).map((requirement) => Object.entries(requirement)
43
+ .map(([scheme, list]) => (list.length > 0 ? `${scheme} (${list.join(", ")})` : scheme))
44
+ .join(" and "));
45
+ const lines = [
46
+ `## ${code(command.usage)}`,
47
+ "",
48
+ `- What: ${text(operation.summary ?? command.summary ?? command.description) || operation.id}`,
49
+ `- Call: ${code(call)}, effect: ${operation.effect}${operation.deprecated ? ", deprecated" : ""}`,
50
+ ];
51
+ if (scopes.length > 0)
52
+ lines.push(`- Sign-in: ${scopes.map(text).join("; or ")}`);
53
+ if (operation.permissions && operation.permissions.length > 0)
54
+ lines.push(`- Permission keys: ${operation.permissions.map((permission) => code(permission.key)).join(", ")}`);
55
+ if (operation.pagination)
56
+ lines.push(`- Pages: ${pages(operation.pagination)}`);
57
+ if (operation.request?.schema)
58
+ lines.push(`- Body: ${code(operation.request.schema)}${operation.request.required ? ", required" : ""}`);
59
+ if (command.arguments.length > 0) {
60
+ lines.push("", "| Argument | Required | What |", "|---|---|---|");
61
+ for (const argument of command.arguments)
62
+ lines.push(`| ${code(argument.name, true)} | ${argument.required ? "yes" : "no"} | ${text(argument.description)} |`);
63
+ }
64
+ if (command.options.length > 0) {
65
+ lines.push("", "| Flag | Required | What |", "|---|---|---|");
66
+ for (const option of command.options)
67
+ lines.push(flagRow(option));
68
+ }
69
+ return [...lines, ""];
70
+ };
71
+ /**
72
+ * Throws `CodegenError` when an operation has no command or a generated command names no operation: a flag is
73
+ * never taken from anywhere but the command tree. Sorted, and with no version or date, so `generate:check` holds.
74
+ */
75
+ export const apiSkillFiles = (options) => {
76
+ const generated = flatten(options.commands).filter((command) => command.origin === "generated" && command.api_operation);
77
+ const byOperation = new Map();
78
+ const problems = [];
79
+ for (const command of generated) {
80
+ const id = command.api_operation ?? "";
81
+ const earlier = byOperation.get(id);
82
+ if (earlier)
83
+ problems.push(`${earlier.path.join(" ")} and ${command.path.join(" ")} both name operation ${id}`);
84
+ byOperation.set(id, command);
85
+ }
86
+ const ids = new Set(options.operations.map((operation) => operation.id));
87
+ const linked = /\]\(\s*(\.\/)?references\/api\.md(#[^)]*)?\s*\)/.test(options.skill.replace(/<!--[\s\S]*?-->/g, ""));
88
+ const hidden = options.files.filter((file) => {
89
+ const base = file.split("/").at(-1)?.replace(/\.md$/, "") ?? "";
90
+ const ours = file === API_SKILL_INDEX || file.startsWith(`${API_SKILL_GROUPS}/`);
91
+ return !ours && file.endsWith(".md") && (base === "api" || base.startsWith("api-"));
92
+ });
93
+ if (!linked)
94
+ problems.push(`SKILL.md does not link ${API_SKILL_INDEX}`);
95
+ for (const file of hidden)
96
+ problems.push(`${file} would hide a generated part of the same name in skill show`);
97
+ for (const operation of options.operations)
98
+ if (!byOperation.has(operation.id))
99
+ problems.push(`operation ${operation.id} has no command in the program`);
100
+ for (const command of generated)
101
+ if (!ids.has(command.api_operation ?? ""))
102
+ problems.push(`${command.path.join(" ")} names operation ${command.api_operation}, not in the manifest`);
103
+ const groups = new Map();
104
+ for (const operation of options.operations) {
105
+ const tag = operation.tags[0] ?? "untagged";
106
+ const name = kebab(tag);
107
+ const group = groups.get(name);
108
+ if (!name)
109
+ problems.push(`tag "${tag}" of ${operation.id} has no Latin letter or digit for a file name`);
110
+ else if (group && group.tag !== tag)
111
+ problems.push(`tags "${group.tag}" and "${tag}" both make the file api-${name}.md`);
112
+ else if (group)
113
+ group.operations.push(operation);
114
+ else
115
+ groups.set(name, { tag, operations: [operation] });
116
+ }
117
+ if (problems.length > 0)
118
+ throw new CodegenError(problems);
119
+ const parentPaths = new Set(generated.map((command) => command.path.slice(0, -1).join(" ")));
120
+ const parents = flatten(options.commands).filter((command) => parentPaths.has(command.path.join(" ")));
121
+ const names = [...groups.keys()].sort();
122
+ const commandOf = (operation) => byOperation.get(operation.id);
123
+ const program = options.cli;
124
+ const index = [
125
+ `<!-- ${options.banner} -->`,
126
+ "",
127
+ `# ${text(options.service)} API`,
128
+ "",
129
+ `Every operation of the ${text(options.service)} API this CLI offers is a command of its own. Read only the group`,
130
+ `you need: ${code(`${program} skill show api-<group>`)} prints it, as does the file \`api/api-<group>.md\` beside`,
131
+ "this one. Each command lists its usage and flags as `--help` prints them.",
132
+ "",
133
+ "Effects: `read` changes nothing; `write` changes the service; `destructive` deletes or overwrites there.",
134
+ "",
135
+ ];
136
+ for (const parent of parents) {
137
+ if (parent.options.length === 0)
138
+ continue;
139
+ index.push(`Options of ${code(parent.usage)} for every command under it:`, "", "| Flag | Required | What |");
140
+ index.push("|---|---|---|");
141
+ for (const option of parent.options)
142
+ index.push(flagRow(option));
143
+ index.push("");
144
+ }
145
+ index.push("| Group | Read with | Commands | read | write | destructive |", "|---|---|---|---|---|---|");
146
+ for (const name of names) {
147
+ const { tag, operations } = groups.get(name);
148
+ const count = (effect) => operations.filter((operation) => operation.effect === effect).length;
149
+ index.push(`| ${text(tag)} | ${code(`${program} skill show api-${name}`, true)} | ${operations.length} | ${count("read")} | ` +
150
+ `${count("write")} | ${count("destructive")} |`);
151
+ }
152
+ const files = names.map((name) => {
153
+ const { tag, operations } = groups.get(name);
154
+ const usage = (operation) => commandOf(operation).usage;
155
+ // Code-unit order: a locale's collation would differ between machines and fail generate:check.
156
+ const sorted = [...operations].sort((one, other) => usage(one) < usage(other) ? -1 : usage(one) > usage(other) ? 1 : 0);
157
+ return {
158
+ path: `${options.folder}/${API_SKILL_GROUPS}/api-${name}.md`,
159
+ content: [
160
+ `<!-- ${options.banner} -->`,
161
+ "",
162
+ `# ${text(options.service)} API: ${text(tag)}`,
163
+ "",
164
+ ...sorted.flatMap((operation) => section(operation, commandOf(operation))),
165
+ ]
166
+ .join("\n")
167
+ .replace(/\n+$/, "\n"),
168
+ };
169
+ });
170
+ return [{ path: `${options.folder}/${API_SKILL_INDEX}`, content: `${index.join("\n")}\n` }, ...files];
171
+ };
@@ -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)