@wirecat/cli-base 0.96.0 → 0.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -8,6 +8,21 @@ Versions before 0.8.0 are in the [git tags](https://github.com/WireCatLabs/cli-b
8
8
  Every entry says what changed as a caller sees it, why, and what to watch for — the rules are
9
9
  [`docs/dev/CONVENTIONS.md`](docs/dev/CONVENTIONS.md#the-changelog).
10
10
 
11
+ ## 0.97.0 — 11.11.2026
12
+
13
+ ### Added
14
+
15
+ - **One shape for a list or a search in a TypeScript API, and a lint rule for it.** The handbook's new
16
+ [WC-OUT-25](docs/standards/output.md#wc-out-25--return-a-list-or-a-search-from-a-typescript-api-as-a-listresult)
17
+ says a list or search returns `{ items, hasMore, nextOffset?, nextCursor?, total? }`, the new `ListResult<T>` type
18
+ in `@wirecat/cli-base/standards`; `--json` keeps the envelope of WC-OUT-4. Until now cli-core's services answered
19
+ `{items, hasMore}`, `{items, has_more}`, `{hits, has_more}` or a bare array. `cli-dev lint` gets the rule
20
+ `result-shape`: it reads the `.d.ts` files that `package.json` publishes and names each page that keeps `hits`,
21
+ `has_more`, `limit_reached`, `next_offset` or `nextPage`, and each paged list or search that returns an array or
22
+ takes a page number. To watch for: the rule checks only built types, so run it after `tsc`; with none built, or
23
+ none published, it is skipped with a note. Today's violations go in `lint/baseline/result-shape.json` with
24
+ `--write-baseline`.
25
+
11
26
  ## 0.96.0 — 11.11.2026
12
27
 
13
28
  ### Changed — may break callers
@@ -4,6 +4,7 @@ import { summaryOf } from "../commands/registry.js";
4
4
  import { type LintRule, type Override } from "../standards/lint.js";
5
5
  import type { Vocabulary } from "../standards/vocabulary.js";
6
6
  import { type NetworkContext } from "./network.js";
7
+ import { type Declarations } from "./result-shape.js";
7
8
  export interface Violation {
8
9
  rule: string;
9
10
  /** What the baseline and overrides name: `chats list`, `chats show <chat>`, `chats list --limit`, `--until`. */
@@ -29,6 +30,8 @@ export interface LintContext {
29
30
  runLog?: RunLogProbe;
30
31
  /** The CLI's own source and declared hosts, for `raw-network` and `undeclared-host`; absent, both find nothing. */
31
32
  network?: NetworkContext;
33
+ /** The package's published `.d.ts` files, for `result-shape`; absent, it finds nothing. */
34
+ declarations?: Declarations;
32
35
  }
33
36
  export interface RunLogProbe {
34
37
  kept: boolean;
package/dist/dev/lint.js CHANGED
@@ -10,6 +10,7 @@ import { isContentKey, logAttributesJsonSchema, logRecordSchema } from "../stand
10
10
  import { itemEnvelopeSchema, jsonlEndSchema, jsonlItemSchema, listEnvelopeSchema } from "../standards/output.js";
11
11
  import { jsonSchemaOf, SNAKE_CASE } from "../standards/registry.js";
12
12
  import { rawNetwork, undeclaredHosts } from "./network.js";
13
+ import { resultShape } from "./result-shape.js";
13
14
  const SUMMARY_LIMIT = 80;
14
15
  const EXAMPLES_MIN = 1;
15
16
  const EXAMPLES_MAX = 3;
@@ -430,6 +431,7 @@ const CHECKS = {
430
431
  },
431
432
  "raw-network": (_document, _vocabulary, context) => (context.network ? rawNetwork(context.network) : []),
432
433
  "undeclared-host": (_document, _vocabulary, context) => (context.network ? undeclaredHosts(context.network) : []),
434
+ "result-shape": (_document, _vocabulary, context) => (context.declarations ? resultShape(context.declarations) : []),
433
435
  };
434
436
  export const lintRuleIds = () => Object.keys(CHECKS);
435
437
  /** Every violation, one per rule and target, sorted. Generated commands keep the names of the API they mirror. */
package/dist/dev/main.js CHANGED
@@ -27,6 +27,7 @@ import { changelogChange, landChange, landFold, newestTag, processShell, restore
27
27
  import { baselineOf, judge, lintCommands, RUN_LOG_COMMANDS, walk } from "./lint.js";
28
28
  import { readSources } from "./network.js";
29
29
  import { nextVersion } from "./next-version.js";
30
+ import { readDeclarations } from "./result-shape.js";
30
31
  import { slowTests } from "./slow-tests.js";
31
32
  import { matrixPage, matrixRows, parseArgvLog } from "./test-matrix.js";
32
33
  import { binNameWarnings, describeWarnings, hostsWarnings, WCAT_RULES } from "./wcat-lint.js";
@@ -458,11 +459,13 @@ const lintRun = (args, io) => {
458
459
  }
459
460
  const paths = new Set(walk(parsed.document.commands).map((command) => command.path.join(" ")));
460
461
  const hasRuns = RUN_LOG_COMMANDS.every((path) => paths.has(path));
462
+ const declarations = readDeclarations(io.cwd);
461
463
  const violations = lintCommands(parsed.document, VOCABULARY, LINT_RULES, {
462
464
  raw,
463
465
  schemas: schemas,
464
466
  ...(values.cli && hasRuns ? { runLog: probeRunLog(io.cwd, values.cli) } : {}),
465
467
  network: networkContext(io.cwd),
468
+ declarations,
466
469
  });
467
470
  const severity = new Map(LINT_RULES.map((rule) => [rule.id, rule.severity]));
468
471
  if (values["write-baseline"]) {
@@ -504,6 +507,10 @@ const lintRun = (args, io) => {
504
507
  io.err(`warning ${line}`);
505
508
  if (!existsSync(join(io.cwd, MANIFEST_FILE)))
506
509
  io.err(`undeclared-host: skipped, no ${MANIFEST_FILE}`);
510
+ if (declarations.files.length === 0)
511
+ io.err(declarations.missing.length === 0
512
+ ? "result-shape: skipped, package.json publishes no types"
513
+ : "result-shape: skipped, the types package.json publishes are not built");
507
514
  return report(io, problems, "lint: ok");
508
515
  };
509
516
  const shippedManifest = (cwd) => {
@@ -0,0 +1,19 @@
1
+ import type { SourceFile } from "./network.js";
2
+ /** The `.d.ts` files a package publishes, followed from its `exports`; `missing` are declared but not built. */
3
+ export interface Declarations {
4
+ files: readonly SourceFile[];
5
+ missing: readonly string[];
6
+ }
7
+ /** Every declaration file reachable from the package's `types` entries, by their relative imports. */
8
+ export declare const readDeclarations: (cwd: string) => Declarations;
9
+ export interface ShapeFinding {
10
+ target: string;
11
+ message: string;
12
+ }
13
+ /**
14
+ * Findings in one declaration file; targets name the declaration, `AttachmentsService.list`. `pagingTypes` gains the
15
+ * file's own types that declare a limit or an offset.
16
+ */
17
+ export declare const shapeFindings: (text: string, pagingTypes?: Set<string>) => ShapeFinding[];
18
+ /** Nothing built at all is a skip the lint reports, not a violation: a test run that did not build reads no types. */
19
+ export declare const resultShape: ({ files, missing }: Declarations) => ShapeFinding[];
@@ -0,0 +1,263 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, join, relative } from "node:path";
3
+ const typesIn = (value, key) => {
4
+ if (typeof value === "string")
5
+ return key === "types" || key === "typings" ? [value] : [];
6
+ if (Array.isArray(value))
7
+ return value.flatMap((one) => typesIn(one));
8
+ if (typeof value === "object" && value !== null)
9
+ return Object.entries(value).flatMap(([at, one]) => typesIn(one, at));
10
+ return [];
11
+ };
12
+ const RELATIVE_MODULE = /(?:\bfrom\s*|\bimport\s*\(\s*)["'](\.{1,2}\/[^"']+)["']/g;
13
+ const declarationOf = (dir, specifier) => {
14
+ const base = join(dir, specifier);
15
+ const candidates = /\.[cm]?js$/.test(base)
16
+ ? [base.replace(/\.(c|m)?js$/, ".d.$1ts")]
17
+ : [`${base}.d.ts`, join(base, "index.d.ts")];
18
+ return candidates.find((path) => existsSync(path));
19
+ };
20
+ /** Every declaration file reachable from the package's `types` entries, by their relative imports. */
21
+ export const readDeclarations = (cwd) => {
22
+ const manifest = join(cwd, "package.json");
23
+ if (!existsSync(manifest))
24
+ return { files: [], missing: [] };
25
+ const pkg = JSON.parse(readFileSync(manifest, "utf8"));
26
+ const entries = [
27
+ ...new Set(typesIn({ types: pkg.types, typings: pkg.typings, exports: pkg.exports }).filter((path) => !path.includes("*"))),
28
+ ];
29
+ const missing = entries.filter((path) => !existsSync(join(cwd, path)));
30
+ const read = new Map();
31
+ const queue = entries.map((path) => join(cwd, path)).filter((path) => existsSync(path));
32
+ for (let file = queue.shift(); file !== undefined; file = queue.shift()) {
33
+ if (read.has(file))
34
+ continue;
35
+ const text = readFileSync(file, "utf8");
36
+ read.set(file, text);
37
+ for (const [, specifier] of text.matchAll(RELATIVE_MODULE)) {
38
+ const next = declarationOf(dirname(file), specifier);
39
+ if (next !== undefined && !read.has(next))
40
+ queue.push(next);
41
+ }
42
+ }
43
+ const files = [...read]
44
+ .map(([path, text]) => ({ path: relative(cwd, path).split("\\").join("/"), text }))
45
+ .sort((a, b) => (a.path < b.path ? -1 : 1));
46
+ return { files, missing };
47
+ };
48
+ const STRINGS_AND_COMMENTS = /\/\/[^\n]*|\/\*[\s\S]*?\*\/|"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`/g;
49
+ const OPEN = "([{<";
50
+ const CLOSE = ")]}>";
51
+ /** Brackets of every kind count, and the `>` of `=>` closes nothing. */
52
+ const depthStep = (text, at) => {
53
+ const char = text[at];
54
+ if (char === ">" && text[at - 1] === "=")
55
+ return 0;
56
+ return OPEN.includes(char) ? 1 : CLOSE.includes(char) ? -1 : 0;
57
+ };
58
+ /** The index just past the bracket that closes the one at `from`. */
59
+ const closing = (text, from) => {
60
+ let depth = 0;
61
+ for (let at = from; at < text.length; at += 1) {
62
+ depth += depthStep(text, at);
63
+ if (depth === 0)
64
+ return at + 1;
65
+ }
66
+ return text.length;
67
+ };
68
+ const splitTop = (text, separators) => {
69
+ const parts = [];
70
+ let depth = 0;
71
+ let start = 0;
72
+ for (let at = 0; at < text.length; at += 1) {
73
+ depth += depthStep(text, at);
74
+ if (depth === 0 && separators.includes(text[at])) {
75
+ parts.push(text.slice(start, at));
76
+ start = at + 1;
77
+ }
78
+ }
79
+ return [...parts, text.slice(start)].map((part) => part.trim()).filter((part) => part !== "");
80
+ };
81
+ const objectsIn = (type) => {
82
+ const found = [];
83
+ for (let at = 0; at < type.length; at += 1)
84
+ if (type[at] === "{") {
85
+ const end = closing(type, at);
86
+ found.push(type.slice(at + 1, end - 1));
87
+ at = end - 1;
88
+ }
89
+ return found;
90
+ };
91
+ const skipGenerics = (text) => (text.startsWith("<") ? text.slice(closing(text, 0)).trimStart() : text);
92
+ /** `(a: A) => R` as its parameters and `R`; undefined for any other type. */
93
+ const arrowOf = (type) => {
94
+ const rest = skipGenerics(type);
95
+ if (!rest.startsWith("("))
96
+ return undefined;
97
+ const end = closing(rest, 0);
98
+ const after = rest.slice(end).trimStart();
99
+ return after.startsWith("=>") ? { params: rest.slice(1, end - 1), returns: after.slice(2).trim() } : undefined;
100
+ };
101
+ const memberOf = (raw) => {
102
+ const text = raw.replace(/^(?:(?:readonly|static|public|protected|private|abstract|declare|get|set)\s+)+/, "");
103
+ const name = text.match(/^[\w$]+\??/)?.[0];
104
+ if (name === undefined)
105
+ return undefined;
106
+ const rest = skipGenerics(text.slice(name.length).trimStart());
107
+ const bare = name.replace(/\?$/, "");
108
+ if (rest.startsWith("(")) {
109
+ const end = closing(rest, 0);
110
+ return { name: bare, params: rest.slice(1, end - 1), type: rest.slice(end).trim().replace(/^:/, "").trim() };
111
+ }
112
+ if (!rest.startsWith(":"))
113
+ return undefined;
114
+ const type = rest.slice(1).trim();
115
+ const arrow = arrowOf(type);
116
+ return arrow ? { name: bare, params: arrow.params, type: arrow.returns } : { name: bare, type };
117
+ };
118
+ const unwrapPromise = (type) => {
119
+ const inner = type.match(/^Promise\s*</);
120
+ return inner && closing(type, inner[0].length - 1) === type.length ? type.slice(inner[0].length, -1).trim() : type;
121
+ };
122
+ const isArray = (type) => {
123
+ const bare = type.trim().replace(/^readonly\s+/, "");
124
+ if (splitTop(bare, "|&").length !== 1)
125
+ return false;
126
+ if (/^(?:Readonly)?Array\s*</.test(bare))
127
+ return closing(bare, bare.indexOf("<")) === bare.length;
128
+ return bare.endsWith("[]");
129
+ };
130
+ const LISTY_NAME = /^(?:list|search|find)(?:[A-Z]|$)|[a-z](?:List|Search)$/;
131
+ const PAGE_NUMBER = /\bpage\??\s*:\s*number\b/;
132
+ /** A list or search that takes a limit, an offset or a page pages; one that takes none may return everything. */
133
+ const isPaged = ({ name, params = "" }, pagingTypes) => LISTY_NAME.test(name) &&
134
+ (/\b(?:limit|offset|page)\b/.test(params) || [...params.matchAll(/[\w$]+/g)].some(([word]) => pagingTypes.has(word)));
135
+ const PAGING_KEYS = new Set([
136
+ "hasMore",
137
+ "has_more",
138
+ "limit_reached",
139
+ "limitReached",
140
+ "nextOffset",
141
+ "next_offset",
142
+ "nextPage",
143
+ "next_page",
144
+ ]);
145
+ /** A declaration or member named like a page of a list or a search. */
146
+ const RESULT_NAME = /^(?:list|search|history)(?:[A-Z]|$)|(?:Found|Page|Results?|List|Hits)$/;
147
+ const renameOf = ({ name, type }) => {
148
+ if (name === "has_more" || name === "limit_reached" || name === "limitReached")
149
+ return "hasMore";
150
+ if (name === "next_offset")
151
+ return "nextOffset";
152
+ if (name === "nextPage" || name === "next_page")
153
+ return /\bstring\b/.test(type) ? "nextCursor" : "nextOffset";
154
+ return undefined;
155
+ };
156
+ /** `inherits`: an interface that extends another may get `items` and `hasMore` from it. */
157
+ const pageFixes = (members, label, inherits) => {
158
+ const props = members.filter((member) => member.params === undefined);
159
+ const names = new Set(props.map((member) => member.name));
160
+ const lists = props.filter((member) => isArray(member.type));
161
+ const paged = lists.length > 0 && props.some((member) => PAGING_KEYS.has(member.name));
162
+ if (!paged || !RESULT_NAME.test(label.split(".").at(-1) ?? ""))
163
+ return [];
164
+ return [
165
+ ...(names.has("items") || inherits
166
+ ? []
167
+ : [`name the rows \`items\` (now ${lists.map((member) => member.name).join(", ")})`]),
168
+ ...props.flatMap((member) => {
169
+ const now = renameOf(member);
170
+ return now ? [`rename \`${member.name}\` to \`${now}\``] : [];
171
+ }),
172
+ ...([...names].some((name) => renameOf({ name, type: "" }) === "hasMore") || names.has("hasMore") || inherits
173
+ ? []
174
+ : ["add `hasMore`"]),
175
+ ];
176
+ };
177
+ const STANDARD = "return ListResult<T> from @wirecat/cli-base/standards (WC-OUT-25)";
178
+ const visitObject = (body, label, scan, inherits = false) => {
179
+ const members = splitTop(body, ";,").flatMap((raw) => memberOf(raw) ?? []);
180
+ if (!label.includes(".") && members.some(({ name }) => name === "limit" || name === "offset"))
181
+ scan.pagingTypes.add(label);
182
+ const fixes = pageFixes(members, label, inherits);
183
+ if (fixes.length > 0)
184
+ scan.found.push({ target: label, message: `${fixes.join("; ")}: ${STANDARD}` });
185
+ for (const member of members)
186
+ visitMember(member, `${label}.${member.name}`, scan);
187
+ };
188
+ const visitMember = (member, label, scan) => {
189
+ if (member.params !== undefined && isPaged(member, scan.pagingTypes)) {
190
+ const fixes = [
191
+ ...(isArray(unwrapPromise(member.type)) ? ["returns a bare array"] : []),
192
+ ...(PAGE_NUMBER.test(member.params) ? ["takes a page number; take `offset` and `limit`"] : []),
193
+ ];
194
+ if (fixes.length > 0)
195
+ scan.found.push({ target: label, message: `${fixes.join("; ")}: ${STANDARD}` });
196
+ }
197
+ for (const body of objectsIn(member.type))
198
+ visitObject(body, label, scan);
199
+ };
200
+ const DECLARATION = /\b(interface|class|type|function|const|let|var)\s+([\w$]+)/g;
201
+ const statementEnd = (text, from) => {
202
+ let depth = 0;
203
+ for (let at = from; at < text.length; at += 1) {
204
+ depth += depthStep(text, at);
205
+ if (depth < 0 || (depth === 0 && text[at] === ";"))
206
+ return at;
207
+ }
208
+ return text.length;
209
+ };
210
+ /**
211
+ * Findings in one declaration file; targets name the declaration, `AttachmentsService.list`. `pagingTypes` gains the
212
+ * file's own types that declare a limit or an offset.
213
+ */
214
+ export const shapeFindings = (text, pagingTypes = new Set()) => {
215
+ const code = text.replace(STRINGS_AND_COMMENTS, (match) => (match.startsWith("/") ? " " : '""'));
216
+ const scan = { found: [], pagingTypes };
217
+ let done = 0;
218
+ for (const match of code.matchAll(DECLARATION)) {
219
+ if (match.index < done)
220
+ continue;
221
+ const [whole, keyword, name] = match;
222
+ const start = match.index + whole.length;
223
+ if (keyword === "interface" || keyword === "class") {
224
+ const head = code.slice(start).match(/^\s*/)?.[0].length ?? 0;
225
+ const afterGenerics = code[start + head] === "<" ? closing(code, start + head) : start + head;
226
+ const open = code.indexOf("{", afterGenerics);
227
+ if (open < 0)
228
+ continue;
229
+ done = closing(code, open);
230
+ const inherits = /\b(?:extends|implements)\b/.test(code.slice(afterGenerics, open));
231
+ visitObject(code.slice(open + 1, done - 1), name, scan, inherits);
232
+ continue;
233
+ }
234
+ done = statementEnd(code, start);
235
+ const rest = code.slice(start, done);
236
+ if (keyword === "type") {
237
+ const type = skipGenerics(rest.trimStart()).replace(/^=/, "").trim();
238
+ const arrow = arrowOf(type);
239
+ visitMember(arrow ? { name, params: arrow.params, type: arrow.returns } : { name, type }, name, scan);
240
+ }
241
+ else {
242
+ const member = memberOf(`${name}${rest}`);
243
+ if (member)
244
+ visitMember(member, name, scan);
245
+ }
246
+ }
247
+ return scan.found;
248
+ };
249
+ /** Nothing built at all is a skip the lint reports, not a violation: a test run that did not build reads no types. */
250
+ export const resultShape = ({ files, missing }) => {
251
+ if (files.length === 0)
252
+ return [];
253
+ const pagingTypes = new Set();
254
+ for (const { text } of files)
255
+ shapeFindings(text, pagingTypes);
256
+ return [
257
+ ...missing.map((path) => ({
258
+ target: `${path}: not built`,
259
+ message: "package.json declares these types, but the file does not exist: build them before cli-dev lint",
260
+ })),
261
+ ...files.flatMap(({ path, text }) => shapeFindings(text, pagingTypes).map((finding) => ({ ...finding, target: `${path}: ${finding.target}` }))),
262
+ ];
263
+ };
@@ -1,6 +1,6 @@
1
1
  export { EFFECT_LEVELS, type EffectLevel, type Effects, effectsSchema, writes } from "./effects.js";
2
2
  export { BASE_REASONS, COMMON_DETAILS, CRASH_CODE, CRASH_REASON, defineReasons, type ErrorObject, type ErrorReason, errorObjectSchema, } from "./errors.js";
3
3
  export { defineLogEvents, isContentKey, LOG_ATTRIBUTE_KEYS, LOG_EVENTS, LOG_SEVERITIES, type LogEvent, type LogRecord, type LogSeverity, logAttributesJsonSchema, logEventProblems, logRecordSchema, traceIdOf, } from "./log.js";
4
- export { COMPACT_FLAG, clockMeta, type Issue, type ItemEnvelope, isoTime, issueSchema, itemEnvelopeSchema, jsonlEndSchema, jsonlItemSchema, jsonlOf, type ListEnvelope, listEnvelopeSchema, localTime, MAX_NEXT_STEPS, type Meta, type Missing, metaSchema, missingSchema, type NextStep, nextStepSchema, type Page, pageSchema, type Ranking, rankingSchema, reference, type Total, totalSchema, } from "./output.js";
4
+ export { COMPACT_FLAG, clockMeta, type Issue, type ItemEnvelope, isoTime, issueSchema, itemEnvelopeSchema, jsonlEndSchema, jsonlItemSchema, jsonlOf, type ListEnvelope, type ListResult, listEnvelopeSchema, localTime, MAX_NEXT_STEPS, type Meta, type Missing, metaSchema, missingSchema, type NextStep, nextStepSchema, type Page, pageSchema, type Ranking, rankingSchema, reference, type Total, totalSchema, } from "./output.js";
5
5
  export { fill, jsonSchemaOf, RegistryError } from "./registry.js";
6
6
  export { defineSteps, SAME_COMMAND, STEPS, type StepDefinition, type StepInput, type StepTarget, stepOf, } from "./steps.js";
@@ -4,7 +4,7 @@ declare const lintRuleSchema: v.StrictObjectSchema<{
4
4
  readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a lower-case word, words joined by -">]>;
5
5
  readonly severity: v.PicklistSchema<readonly ["high", "medium", "low"], undefined>;
6
6
  /** What the rule looks at; a violation's target names one of these. */
7
- readonly scope: v.PicklistSchema<["command", "group", "argument", "option", "flag", "key", "source"], undefined>;
7
+ readonly scope: v.PicklistSchema<["command", "group", "argument", "option", "flag", "key", "source", "type"], undefined>;
8
8
  readonly summary: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "must not be empty">]>;
9
9
  }, undefined>;
10
10
  export type LintRule = v.InferOutput<typeof lintRuleSchema>;
@@ -5,7 +5,7 @@ const lintRuleSchema = v.strictObject({
5
5
  id: word,
6
6
  severity: v.picklist(LINT_SEVERITIES),
7
7
  /** What the rule looks at; a violation's target names one of these. */
8
- scope: v.picklist(["command", "group", "argument", "option", "flag", "key", "source"]),
8
+ scope: v.picklist(["command", "group", "argument", "option", "flag", "key", "source", "type"]),
9
9
  summary: text,
10
10
  });
11
11
  export const defineLintRules = (input) => parseRegistry("lint rules", v.array(lintRuleSchema), input, (rules) => duplicates(rules.map((rule) => rule.id)).map((id) => `"${id}" is listed twice`));
@@ -128,6 +128,12 @@ export const LINT_RULES = defineLintRules([
128
128
  scope: "source",
129
129
  summary: "every `http(s)://` host in the CLI's own source is in the manifest's `network.hosts`",
130
130
  },
131
+ {
132
+ id: "result-shape",
133
+ severity: "medium",
134
+ scope: "type",
135
+ summary: "a list or search in the published TypeScript API returns `{ items, hasMore, nextOffset?, total? }`: no bare array, no `hits` or `has_more`",
136
+ },
131
137
  ]);
132
138
  /** `lint/baseline/<rule-id>.json`: today's violations of one rule, by target. It may only shrink. */
133
139
  export const baselineSchema = v.array(text);
@@ -63,6 +63,18 @@ export declare const pageSchema: v.VariantSchema<"mode", [v.StrictObjectSchema<{
63
63
  }, undefined>, undefined>;
64
64
  }, undefined>], undefined>;
65
65
  export type Total = v.InferOutput<typeof totalSchema>;
66
+ /**
67
+ * A list or search returned by a TypeScript API (WC-OUT-25). It pages by `offset` and `limit`; a source with its own
68
+ * position gives `nextCursor` instead. `--json` prints it as the list envelope, in snake_case.
69
+ */
70
+ export interface ListResult<T> {
71
+ items: T[];
72
+ hasMore: boolean;
73
+ /** The `offset` that reads the next page; absent on the last one. */
74
+ nextOffset?: number;
75
+ nextCursor?: string;
76
+ total?: Total;
77
+ }
66
78
  /** A source that failed or was skipped: the answer holds what the others gave. */
67
79
  export declare const issueSchema: v.StrictObjectSchema<{
68
80
  readonly code: v.PicklistSchema<readonly ["validation_error", "configuration_error", "authentication_error", "permission_error", "not_found", "confirmation_required", "rate_limited", "timeout", "network_error", "provider_error", "provider_unavailable", "invalid_response", "outcome_unknown", "conflict", "cancelled"], undefined>;
@@ -30,7 +30,7 @@ the four steps that need a person. A new CLI is ready for its first release when
30
30
  | [Toolchain](toolchain.md) | `TOOL` | 20 | TypeScript, Biome, grit plugins, size caps, import cycles, spelling, Markdown, Go |
31
31
  | [Layout](layout.md) | `LAY` | 10 | Repository layout, entry points, exports, file size, one job per file, splitting a unit, the bundled bin |
32
32
  | [Commands](commands.md) | `CMD` | 32 | Paths, vocabulary, flags, arguments, effects, lifetime, query, help, external references, joining `wcat`, settings in the config file, refs, network hosts |
33
- | [Output](output.md) | `OUT` | 24 | Data on stdout only, envelopes, errors, exit codes, partial answers, projection |
33
+ | [Output](output.md) | `OUT` | 25 | Data on stdout only, envelopes, errors, exit codes, partial answers, projection, list results in a TypeScript API |
34
34
  | [MCP](mcp.md) | `MCP` | 13 | The MCP tools, how they come from commands, what each permission shows |
35
35
  | [Accounts](accounts.md) | `ACCT` | 13 | The explicit profile, reads across accounts, scope flags, linked identities, sign-in commands, memo's account groups |
36
36
  | [Permissions](permissions.md) | `PERM` | 23 | Levels, keys, defaults, hard limits, the write guard and its journal, handing the keys to cli-core |
@@ -309,6 +309,46 @@ Three things follow from it:
309
309
  - **Exceptions:** MCP tools answer JSON.
310
310
  - **Applies to:** CLIs that run on cli-core's `run()`. **Since:** cli-base 0.74.0. **Rulings:** NEED-2131.
311
311
 
312
+ ## TypeScript API
313
+
314
+ ### WC-OUT-25 · Return a list or a search from a TypeScript API as a `ListResult`
315
+
316
+ - **Why:** a caller that pages one service pages all of them the same way, and a command prints any of them as the
317
+ list envelope with no renaming of its own.
318
+ - **Enforced by:** `result-shape`.
319
+ - **Example:** `ListResult<T>` from `@wirecat/cli-base/standards` is `{ items, hasMore, nextOffset?, nextCursor?,
320
+ total? }`. A search takes `offset` and `limit`:
321
+
322
+ ```ts
323
+ const page = await notes.search("invoice", { offset: 40, limit: 20 })
324
+ // { items: [ … ], hasMore: true, nextOffset: 60, total: { value: 312, relation: "eq" } }
325
+ ```
326
+
327
+ `nextOffset` is absent on the last page. A source with its own position, such as a message history or a provider's
328
+ page token, gives `nextCursor` instead. `total` is the `Total` of
329
+ [WC-OUT-5](#wc-out-5--say-in-page-how-the-source-pages). Other facts about the run sit beside these keys, in
330
+ camelCase: `meaningSkipped`, `accounts`. In `--json` the same result is the list envelope of
331
+ [WC-OUT-4](#wc-out-4--answer-every-json-request-with-one-envelope-a-list-or-one-thing), in snake_case: `hasMore` is
332
+ `page.has_more`, a command paged by `--page` reads `offset = (page - 1) × limit` and answers `next_page`, and
333
+ `nextCursor` is `page.next_cursor`. A failure throws a `CliError`, which prints as the error object of
334
+ [WC-OUT-14](#wc-out-14--print-a-failure-in-machine-mode-as-one-json-object-on-stderr-with-stdout-empty); a result
335
+ never carries an `error` key. A paged list is never a bare array, never takes a page number, and its keys are never
336
+ `hits`, `has_more`, `limit_reached` or `next_offset`.
337
+ - **Exceptions:** a list that takes no limit and returns everything it has, such as the folders of an account, may
338
+ return an array. A type that describes the `--json` answer itself keeps the envelope's snake_case keys. A page as a
339
+ provider hands it to a source adapter, such as a CRM's `nextPage` token, keeps the provider's paging: an entry in
340
+ `lint/overrides.json` says so.
341
+ - **Applies to:** packages whose TypeScript API other packages import: cli-core today. **Since:** cli-base 0.97.0.
342
+ **Rulings:** NEED-2561.
343
+
344
+ `result-shape` reads the `.d.ts` files a package publishes: every `types` entry in `package.json`, and what they
345
+ import. It checks a declaration or member named like a page (`list…`, `search…`, `history…`, or a name ending in
346
+ `Found`, `Page`, `Result`, `Results`, `List` or `Hits`) that holds an array and a paging key. It also checks a
347
+ function or method named like a list or a search (`list…`, `search…`, `find…`, `…List`, `…Search`) that takes a
348
+ `limit`, an `offset`, a page, or a type that declares a `limit` or an `offset`: it must not return an array or take a
349
+ page number. A list named otherwise, such as `memories()`, is not seen. A package that publishes no types, or has not
350
+ built them, is skipped, and the lint says so. A declared file that is missing while others are built is a violation.
351
+
312
352
  ## Sources
313
353
 
314
354
  These documents explain the rules on this page in more detail. Where one of them disagrees with this page, this page
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-base",
3
- "version": "0.96.0",
3
+ "version": "0.97.0",
4
4
  "description": "The parts every command line tool needs: output modes, terminal rendering, error model, exit codes, credentials, clocks",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",