@hop-top/kit 0.5.0-alpha.6 → 0.5.0-alpha.8
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 +52 -0
- package/LICENSE-cobra.txt +174 -0
- package/NOTICE +15 -0
- package/README.md +3 -3
- package/dist/alias-D9_qFlyP.d.ts +174 -0
- package/dist/alias.d.ts +1 -1
- package/dist/alias.js +10 -2
- package/dist/chunk-263IZ6Z6.js +915 -0
- package/dist/{chunk-S45UHXQF.js → chunk-BLS2OBIQ.js} +106 -25
- package/dist/{chunk-7FDIN5KE.js → chunk-GHPJJV5L.js} +8 -4
- package/dist/chunk-JKMQSAJP.js +174 -0
- package/dist/chunk-JZ22ZUFA.js +1131 -0
- package/dist/{chunk-GAZPYCQD.js → chunk-NLMS7HGP.js} +93 -35
- package/dist/chunk-QQQYCWSC.js +240 -0
- package/dist/chunk-XJTRY453.js +868 -0
- package/dist/cli.js +6 -4
- package/dist/completion-csVun6SP.d.ts +112 -0
- package/dist/completion-values-By-mnjNt.d.ts +142 -0
- package/dist/completion-values.d.ts +1 -0
- package/dist/completion-values.js +29 -0
- package/dist/completion.d.ts +2 -1
- package/dist/completion.js +23 -2
- package/dist/compliance-AxFf-uMy.d.ts +60 -0
- package/dist/compliance.d.ts +1 -0
- package/dist/compliance.js +17 -0
- package/dist/config-CaK60ByQ.d.ts +241 -0
- package/dist/config.d.ts +1 -1
- package/dist/config.js +4 -2
- package/dist/index.d.ts +7 -5
- package/dist/index.js +26 -18
- package/dist/log-CkaxMX3U.d.ts +115 -0
- package/dist/log.d.ts +1 -1
- package/dist/log.js +2 -2
- package/dist/toolspec-UrWnoJ3Y.d.ts +336 -0
- package/dist/toolspec.d.ts +2 -1
- package/dist/toolspec.js +27 -2
- package/package.json +19 -3
- package/src/alias.conformance.test.ts +250 -0
- package/src/alias.test.ts +206 -2
- package/src/alias.ts +196 -21
- package/src/cli.ts +5 -0
- package/src/completion-scripts.ts +16 -0
- package/src/completion-values.test.ts +70 -10
- package/src/completion-values.ts +170 -66
- package/src/completion.conformance.test.ts +297 -0
- package/src/completion.test.ts +256 -145
- package/src/completion.ts +767 -121
- package/src/config-merge.test.ts +425 -0
- package/src/config.test.ts +41 -0
- package/src/config.ts +265 -18
- package/src/index.test.ts +2 -1
- package/src/index.ts +5 -1
- package/src/log.test.ts +270 -1
- package/src/log.ts +172 -44
- package/src/published-types.test.ts +18 -0
- package/src/toolspec-internal.ts +197 -0
- package/src/toolspec-manifest.test.ts +82 -0
- package/src/toolspec-manifest.ts +404 -0
- package/src/toolspec-spec-schemas.ts +12 -0
- package/src/toolspec-spec.test.ts +273 -0
- package/src/toolspec-spec.ts +458 -0
- package/src/toolspec.from-command.test.ts +216 -0
- package/src/toolspec.ts +159 -0
- package/test/toolspec/fixture.ts +73 -0
- package/dist/alias-BOj0-VAr.d.ts +0 -88
- package/dist/chunk-6RFRV4VP.js +0 -128
- package/dist/chunk-IQXEISMC.js +0 -142
- package/dist/chunk-W7ERKNSQ.js +0 -171
- package/dist/completion-CVnPcWMZ.d.ts +0 -32
- package/dist/config-Bm9fBXch.d.ts +0 -134
- package/dist/log-uKjHsK-c.d.ts +0 -62
- package/dist/toolspec-DPBr18Ub.d.ts +0 -106
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Internal helpers shared by the toolspec modules. Not re-exported
|
|
3
|
+
* from the package's `toolspec` entry.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type {
|
|
7
|
+
Command as CommanderCommand,
|
|
8
|
+
Option as CommanderOption,
|
|
9
|
+
} from "commander";
|
|
10
|
+
|
|
11
|
+
export type Annotations = Record<string, string>;
|
|
12
|
+
|
|
13
|
+
export function annotationsOf(cmd: CommanderCommand): Annotations {
|
|
14
|
+
return (cmd as { annotations?: Annotations }).annotations ?? {};
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function splitCSV(s: string | undefined): string[] | undefined {
|
|
18
|
+
if (!s) return undefined;
|
|
19
|
+
const out = s.split(",").map((p) => p.trim()).filter((p) => p !== "");
|
|
20
|
+
return out.length > 0 ? out : undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// --- commander facts ---
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Whether cmd has an action handler (cobra Runnable). commander 15
|
|
27
|
+
* exposes no public accessor, so this reads the private field.
|
|
28
|
+
*/
|
|
29
|
+
export function isRunnable(cmd: CommanderCommand): boolean {
|
|
30
|
+
return (cmd as unknown as { _actionHandler?: unknown })._actionHandler != null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Hidden per the parent's help (public API; no private _hidden read). */
|
|
34
|
+
export function isHidden(cmd: CommanderCommand, parent: CommanderCommand): boolean {
|
|
35
|
+
return !parent.createHelp().visibleCommands(parent).includes(cmd);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const BUILTIN_NAMES = new Set([
|
|
39
|
+
"help",
|
|
40
|
+
"completion",
|
|
41
|
+
"man",
|
|
42
|
+
"__complete",
|
|
43
|
+
"__completeNoDesc",
|
|
44
|
+
]);
|
|
45
|
+
|
|
46
|
+
export function isBuiltin(cmd: CommanderCommand, parent: CommanderCommand): boolean {
|
|
47
|
+
return BUILTIN_NAMES.has(cmd.name()) || parent.name() === "completion";
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function byName(a: { name(): string }, b: { name(): string }): number {
|
|
51
|
+
const x = a.name();
|
|
52
|
+
const y = b.name();
|
|
53
|
+
return x < y ? -1 : x > y ? 1 : 0;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// --- Go encoding/json byte parity ---
|
|
57
|
+
|
|
58
|
+
/** Go's json string escaping (HTML-safe, U+2028/2029 escaped). */
|
|
59
|
+
export function goQuote(s: string): string {
|
|
60
|
+
return JSON.stringify(s)
|
|
61
|
+
.replace(/</g, "\\u003c")
|
|
62
|
+
.replace(/>/g, "\\u003e")
|
|
63
|
+
.replace(/&/g, "\\u0026")
|
|
64
|
+
.replace(/\u2028/g, "\\u2028")
|
|
65
|
+
.replace(/\u2029/g, "\\u2029");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Re-emit raw JSON text the way Go's Encoder.SetIndent("", " ")
|
|
70
|
+
* does for an embedded RawJSON: tokens verbatim (numbers keep their
|
|
71
|
+
* spelling), insignificant whitespace dropped, strings HTML-escaped,
|
|
72
|
+
* structure re-indented at the given depth. Throws on invalid JSON,
|
|
73
|
+
* as Go's encoder errors.
|
|
74
|
+
*/
|
|
75
|
+
export function reindentRaw(raw: string, depth: number): string {
|
|
76
|
+
JSON.parse(raw); // validity gate
|
|
77
|
+
let out = "";
|
|
78
|
+
let level = depth;
|
|
79
|
+
let needIndent = false;
|
|
80
|
+
const nl = (lvl: number) => "\n" + " ".repeat(lvl);
|
|
81
|
+
for (let i = 0; i < raw.length; i++) {
|
|
82
|
+
const c = raw[i];
|
|
83
|
+
if (c === " " || c === "\t" || c === "\n" || c === "\r") continue;
|
|
84
|
+
if (needIndent && c !== "]" && c !== "}") {
|
|
85
|
+
out += nl(level);
|
|
86
|
+
needIndent = false;
|
|
87
|
+
}
|
|
88
|
+
if (c === '"') {
|
|
89
|
+
let j = i + 1;
|
|
90
|
+
while (raw[j] !== '"') j += raw[j] === "\\" ? 2 : 1;
|
|
91
|
+
out += goQuote(JSON.parse(raw.slice(i, j + 1)) as string);
|
|
92
|
+
i = j;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
switch (c) {
|
|
96
|
+
case "{":
|
|
97
|
+
case "[":
|
|
98
|
+
out += c;
|
|
99
|
+
level++;
|
|
100
|
+
needIndent = true;
|
|
101
|
+
break;
|
|
102
|
+
case "}":
|
|
103
|
+
case "]":
|
|
104
|
+
level--;
|
|
105
|
+
if (needIndent) needIndent = false;
|
|
106
|
+
else out += nl(level);
|
|
107
|
+
out += c;
|
|
108
|
+
break;
|
|
109
|
+
case ",":
|
|
110
|
+
out += c + nl(level);
|
|
111
|
+
break;
|
|
112
|
+
case ":":
|
|
113
|
+
out += ": ";
|
|
114
|
+
break;
|
|
115
|
+
default:
|
|
116
|
+
out += c;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return out;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Go encoding/json (Encoder.SetIndent("", " ")) bytes for v; keys in rawKeys hold raw JSON text. */
|
|
123
|
+
export function encodeGoJSON(v: unknown, depth: number, rawKeys: Set<string>, key?: string): string {
|
|
124
|
+
if (key !== undefined && rawKeys.has(key) && typeof v === "string") {
|
|
125
|
+
return reindentRaw(v, depth);
|
|
126
|
+
}
|
|
127
|
+
if (typeof v === "string") return goQuote(v);
|
|
128
|
+
if (typeof v === "boolean" || typeof v === "number") return JSON.stringify(v);
|
|
129
|
+
if (Array.isArray(v)) {
|
|
130
|
+
if (v.length === 0) return "[]";
|
|
131
|
+
const pad = " ".repeat(depth + 1);
|
|
132
|
+
const items = v.map((x) => pad + encodeGoJSON(x, depth + 1, rawKeys));
|
|
133
|
+
return "[\n" + items.join(",\n") + "\n" + " ".repeat(depth) + "]";
|
|
134
|
+
}
|
|
135
|
+
if (v && typeof v === "object") {
|
|
136
|
+
const entries = Object.entries(v).filter(([, x]) => x !== undefined);
|
|
137
|
+
if (entries.length === 0) return "{}";
|
|
138
|
+
const pad = " ".repeat(depth + 1);
|
|
139
|
+
const items = entries.map(
|
|
140
|
+
([k, x]) => pad + goQuote(k) + ": " + encodeGoJSON(x, depth + 1, rawKeys, k),
|
|
141
|
+
);
|
|
142
|
+
return "{\n" + items.join(",\n") + "\n" + " ".repeat(depth) + "}";
|
|
143
|
+
}
|
|
144
|
+
return "null";
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Visit every command below program depth-first, children in name
|
|
149
|
+
* order (cobra's default sorting), with its Go-style path (root name
|
|
150
|
+
* first) and whether it is reserved: its depth-1 verb is in
|
|
151
|
+
* `reserved`, or it or an ancestor carries kit/reserved=true.
|
|
152
|
+
*/
|
|
153
|
+
export function walkCommands(
|
|
154
|
+
program: CommanderCommand,
|
|
155
|
+
reserved: Iterable<string> | undefined,
|
|
156
|
+
visit: (
|
|
157
|
+
cmd: CommanderCommand,
|
|
158
|
+
parent: CommanderCommand,
|
|
159
|
+
path: string[],
|
|
160
|
+
reserved: boolean,
|
|
161
|
+
) => void,
|
|
162
|
+
): void {
|
|
163
|
+
const reservedSet = new Set(reserved ?? []);
|
|
164
|
+
const walk = (
|
|
165
|
+
cmd: CommanderCommand,
|
|
166
|
+
parent: CommanderCommand,
|
|
167
|
+
path: string[],
|
|
168
|
+
depthOne: string,
|
|
169
|
+
reservedTree: boolean,
|
|
170
|
+
): void => {
|
|
171
|
+
const inReserved = reservedTree || annotationsOf(cmd)["kit/reserved"] === "true";
|
|
172
|
+
visit(cmd, parent, path, inReserved || reservedSet.has(depthOne));
|
|
173
|
+
for (const child of [...cmd.commands].sort(byName)) {
|
|
174
|
+
if (child.name() === "") continue;
|
|
175
|
+
walk(child, cmd, [...path, child.name()], depthOne, inReserved);
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
for (const child of [...program.commands].sort(byName)) {
|
|
179
|
+
if (child.name() === "") continue;
|
|
180
|
+
walk(child, program, [program.name(), child.name()], child.name(), false);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* pflag type names for options whose commander shape cannot say
|
|
186
|
+
* (commander has no typed options), e.g. a float --min.
|
|
187
|
+
*/
|
|
188
|
+
export const pflagTypes = new WeakMap<CommanderOption, string>();
|
|
189
|
+
|
|
190
|
+
/** Go fmt "%.0f": round half to even. */
|
|
191
|
+
export function goFormat0(x: number): string {
|
|
192
|
+
const floor = Math.floor(x);
|
|
193
|
+
const diff = x - floor;
|
|
194
|
+
let r = diff > 0.5 ? floor + 1 : diff < 0.5 ? floor : floor % 2 === 0 ? floor : floor + 1;
|
|
195
|
+
if (Object.is(r, -0)) r = 0;
|
|
196
|
+
return String(r);
|
|
197
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import * as fs from "fs";
|
|
3
|
+
import * as path from "path";
|
|
4
|
+
import { Command } from "commander";
|
|
5
|
+
import { FIXTURES, fixtureProgram } from "../test/toolspec/fixture";
|
|
6
|
+
import {
|
|
7
|
+
buildManifest,
|
|
8
|
+
LATEST_SCHEMA_VERSION,
|
|
9
|
+
negotiateSchemaVersion,
|
|
10
|
+
renderManifestJSON,
|
|
11
|
+
SCHEMA_VERSION_ENV,
|
|
12
|
+
} from "./toolspec";
|
|
13
|
+
|
|
14
|
+
describe("buildManifest cross-language fixture", () => {
|
|
15
|
+
for (const [file, includeDeprecated] of [
|
|
16
|
+
["toolspec-manifest.json", false],
|
|
17
|
+
["toolspec-manifest.include-deprecated.json", true],
|
|
18
|
+
] as const) {
|
|
19
|
+
it(`matches the Go bytes in ${file}`, () => {
|
|
20
|
+
const { program, tree } = fixtureProgram();
|
|
21
|
+
const manifest = buildManifest(program, "1.1", {
|
|
22
|
+
includeDeprecated,
|
|
23
|
+
reserved: tree.reserved,
|
|
24
|
+
});
|
|
25
|
+
const want = fs.readFileSync(path.join(FIXTURES, file), "utf-8");
|
|
26
|
+
expect(renderManifestJSON(manifest)).toBe(want);
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
it("throws on a malformed output schema, as Go's encoder does", () => {
|
|
31
|
+
const program = new Command("t");
|
|
32
|
+
const c = program.command("x").action(() => {});
|
|
33
|
+
(c as Command & { annotations?: Record<string, string> }).annotations = {
|
|
34
|
+
"kit/output-schema": "{not json",
|
|
35
|
+
};
|
|
36
|
+
expect(() => renderManifestJSON(buildManifest(program, "1.1"))).toThrow();
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it("emits an empty commands array for a bare program", () => {
|
|
40
|
+
const out = renderManifestJSON(buildManifest(new Command("t"), "1.0"));
|
|
41
|
+
expect(out).toBe(
|
|
42
|
+
'{\n "tool": "t",\n "version": "",\n "schema_version": "1.0",\n "commands": []\n}\n',
|
|
43
|
+
);
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
describe("negotiateSchemaVersion", () => {
|
|
48
|
+
const cases: Array<[string, string, string]> = [
|
|
49
|
+
["1.0", "", "1.0"],
|
|
50
|
+
["1.0", "1.0", "1.0"],
|
|
51
|
+
["1.0", "1.1", "1.1"],
|
|
52
|
+
["1.0", "2.0", "1.1"],
|
|
53
|
+
["1.0", "1.9", "1.1"],
|
|
54
|
+
["1.0", "0.9", "1.0"],
|
|
55
|
+
["1.0", "garbage", "1.0"],
|
|
56
|
+
["1.0", "1", "1.0"],
|
|
57
|
+
["1.0", "1.1x", "1.0"],
|
|
58
|
+
["1.0", "+1.1", "1.0"],
|
|
59
|
+
["1.0", "1.x", "1.0"],
|
|
60
|
+
["1.0", "1.1.0", "1.0"],
|
|
61
|
+
["1.0", " 1.1 ", "1.1"],
|
|
62
|
+
["1.1", "", "1.1"],
|
|
63
|
+
["1.1", "1.0", "1.1"],
|
|
64
|
+
["1.1", "1.1", "1.1"],
|
|
65
|
+
["1.1", "2.0", "1.1"],
|
|
66
|
+
["1.1", "junk", "1.1"],
|
|
67
|
+
["2.0", "1.1", "2.0"],
|
|
68
|
+
["2.0", "3.0", "2.0"],
|
|
69
|
+
["v1", "1.1", "v1"],
|
|
70
|
+
["", "1.1", ""],
|
|
71
|
+
];
|
|
72
|
+
for (const [declared, requested, want] of cases) {
|
|
73
|
+
it(`${JSON.stringify(declared)} + ${JSON.stringify(requested)} -> ${want}`, () => {
|
|
74
|
+
expect(negotiateSchemaVersion(declared, requested)).toBe(want);
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
it("pins the env name and latest version", () => {
|
|
79
|
+
expect(LATEST_SCHEMA_VERSION).toBe("1.1");
|
|
80
|
+
expect(SCHEMA_VERSION_ENV).toBe("KIT_TOOLSPEC_SCHEMA");
|
|
81
|
+
});
|
|
82
|
+
});
|
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Port of Go's `toolspec.Manifest` and `BuildManifest`
|
|
3
|
+
* (go/ai/toolspec/spec.go, go/ai/toolspec/cli/spec_command.go): the
|
|
4
|
+
* flat, snake_case capability manifest a `<tool> spec` command emits,
|
|
5
|
+
* projected from a commander tree carrying kit/* annotations.
|
|
6
|
+
*
|
|
7
|
+
* Byte parity with Go is pinned by
|
|
8
|
+
* sdk/tests/cross-lang/fixtures/toolspec-manifest*.json.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type {
|
|
12
|
+
Command as CommanderCommand,
|
|
13
|
+
Option as CommanderOption,
|
|
14
|
+
} from "commander";
|
|
15
|
+
import {
|
|
16
|
+
annotationsOf,
|
|
17
|
+
encodeGoJSON,
|
|
18
|
+
isBuiltin,
|
|
19
|
+
isHidden,
|
|
20
|
+
isRunnable,
|
|
21
|
+
pflagTypes,
|
|
22
|
+
splitCSV,
|
|
23
|
+
walkCommands,
|
|
24
|
+
type Annotations,
|
|
25
|
+
} from "./toolspec-internal.js";
|
|
26
|
+
|
|
27
|
+
/** Env var a harness sets to request a manifest schema version. */
|
|
28
|
+
export const SCHEMA_VERSION_ENV = "KIT_TOOLSPEC_SCHEMA";
|
|
29
|
+
/** Newest manifest schema version kit emits. */
|
|
30
|
+
export const LATEST_SCHEMA_VERSION = "1.1";
|
|
31
|
+
const KNOWN_SCHEMA_VERSIONS = ["1.0", LATEST_SCHEMA_VERSION];
|
|
32
|
+
|
|
33
|
+
/** Value side_effect / idempotent carry when nothing was declared. */
|
|
34
|
+
export const SIDE_EFFECT_UNKNOWN = "unknown";
|
|
35
|
+
export const IDEMPOTENT_UNKNOWN = "unknown";
|
|
36
|
+
|
|
37
|
+
export interface ManifestArg {
|
|
38
|
+
name: string;
|
|
39
|
+
required?: boolean;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface ManifestFlag {
|
|
43
|
+
name: string;
|
|
44
|
+
short?: string;
|
|
45
|
+
type?: string;
|
|
46
|
+
description?: string;
|
|
47
|
+
default?: string;
|
|
48
|
+
since_version?: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface ManifestExample {
|
|
52
|
+
title: string;
|
|
53
|
+
command: string;
|
|
54
|
+
output?: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface ManifestNextStep {
|
|
58
|
+
when?: string;
|
|
59
|
+
suggest: string;
|
|
60
|
+
reason?: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** One invocable command. Field order is the Go struct order. */
|
|
64
|
+
export interface ManifestCommand {
|
|
65
|
+
path: string[];
|
|
66
|
+
short: string;
|
|
67
|
+
side_effect: string;
|
|
68
|
+
idempotent: string;
|
|
69
|
+
args?: ManifestArg[];
|
|
70
|
+
flags?: ManifestFlag[];
|
|
71
|
+
exit_codes?: string[];
|
|
72
|
+
deprecated?: boolean;
|
|
73
|
+
deprecated_since?: string;
|
|
74
|
+
removal_target?: string;
|
|
75
|
+
since_version?: string;
|
|
76
|
+
long?: string;
|
|
77
|
+
retryable: boolean;
|
|
78
|
+
/** Raw JSON Schema text, embedded verbatim (Go RawJSON). */
|
|
79
|
+
output_schema?: string;
|
|
80
|
+
output_schema_version?: string;
|
|
81
|
+
examples?: ManifestExample[];
|
|
82
|
+
next_steps?: ManifestNextStep[];
|
|
83
|
+
top_level_verb?: boolean;
|
|
84
|
+
hierarchical?: boolean;
|
|
85
|
+
passthrough?: boolean;
|
|
86
|
+
destructive_token_required?: boolean;
|
|
87
|
+
dry_run_supported: boolean;
|
|
88
|
+
dry_run_rationale?: string;
|
|
89
|
+
reserved?: boolean;
|
|
90
|
+
hidden?: boolean;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface Manifest {
|
|
94
|
+
tool: string;
|
|
95
|
+
version: string;
|
|
96
|
+
schema_version: string;
|
|
97
|
+
commands: ManifestCommand[];
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export interface BuildManifestOptions {
|
|
101
|
+
/** Include deprecated commands (Go --include-deprecated). */
|
|
102
|
+
includeDeprecated?: boolean;
|
|
103
|
+
/** Depth-1 verbs the tool reserves (Go Root.IsReserved). */
|
|
104
|
+
reserved?: Iterable<string>;
|
|
105
|
+
/**
|
|
106
|
+
* The command being executed, if any. It gets the -h/--help flag
|
|
107
|
+
* cobra adds to the executing command, as a live Go run lists.
|
|
108
|
+
*/
|
|
109
|
+
invokedCommand?: CommanderCommand;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// --- Schema negotiation ---
|
|
113
|
+
|
|
114
|
+
function parseSchemaVersion(s: string): [number, number] | undefined {
|
|
115
|
+
const t = s.trim();
|
|
116
|
+
const dot = t.indexOf(".");
|
|
117
|
+
if (dot < 0) return undefined;
|
|
118
|
+
const parts = [t.slice(0, dot), t.slice(dot + 1)];
|
|
119
|
+
const out: number[] = [];
|
|
120
|
+
for (const p of parts) {
|
|
121
|
+
if (!/^[0-9]+$/.test(p)) return undefined;
|
|
122
|
+
const n = Number(p);
|
|
123
|
+
if (!Number.isSafeInteger(n)) return undefined;
|
|
124
|
+
out.push(n);
|
|
125
|
+
}
|
|
126
|
+
return [out[0], out[1]];
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function after(a: [number, number], b: [number, number]): boolean {
|
|
130
|
+
return a[0] !== b[0] ? a[0] > b[0] : a[1] > b[1];
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Resolve the emitted schema_version (Go NegotiateSchemaVersion):
|
|
135
|
+
* declared is a floor; a well-formed request raises it to the highest
|
|
136
|
+
* known version not above the request; nothing is ever refused.
|
|
137
|
+
*/
|
|
138
|
+
export function negotiateSchemaVersion(
|
|
139
|
+
declared: string,
|
|
140
|
+
requested: string,
|
|
141
|
+
): string {
|
|
142
|
+
const floor = parseSchemaVersion(declared);
|
|
143
|
+
if (!floor) return declared;
|
|
144
|
+
const ceiling = parseSchemaVersion(requested);
|
|
145
|
+
if (!ceiling) return declared;
|
|
146
|
+
let resolved = declared;
|
|
147
|
+
let best = floor;
|
|
148
|
+
for (const v of KNOWN_SCHEMA_VERSIONS) {
|
|
149
|
+
const known = parseSchemaVersion(v)!;
|
|
150
|
+
if (after(known, best) && !after(known, ceiling)) {
|
|
151
|
+
resolved = v;
|
|
152
|
+
best = known;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return resolved;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// --- Annotation reading (Go cmdreflect / cmdmeta) ---
|
|
159
|
+
|
|
160
|
+
function flagSince(ann: Annotations): Map<string, string> {
|
|
161
|
+
const out = new Map<string, string>();
|
|
162
|
+
for (const entry of (ann["kit/flag-since"] ?? "").split(",")) {
|
|
163
|
+
const e = entry.trim();
|
|
164
|
+
const eq = e.indexOf("=");
|
|
165
|
+
if (eq < 0) continue;
|
|
166
|
+
out.set(e.slice(0, eq).trim(), e.slice(eq + 1).trim());
|
|
167
|
+
}
|
|
168
|
+
return out;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Go's json decoding matches keys exactly first, then case-insensitively. */
|
|
172
|
+
function fieldOf(rec: Record<string, unknown>, name: string): unknown {
|
|
173
|
+
if (name in rec) return rec[name];
|
|
174
|
+
const k = Object.keys(rec).find((x) => x.toLowerCase() === name);
|
|
175
|
+
return k === undefined ? undefined : rec[k];
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Decode a JSON list annotation; absent or malformed yields undefined. */
|
|
179
|
+
function decodeList<T>(
|
|
180
|
+
raw: string | undefined,
|
|
181
|
+
fields: { name: string; required: boolean }[],
|
|
182
|
+
): T[] | undefined {
|
|
183
|
+
if (!raw) return undefined;
|
|
184
|
+
let parsed: unknown;
|
|
185
|
+
try {
|
|
186
|
+
parsed = JSON.parse(raw);
|
|
187
|
+
} catch {
|
|
188
|
+
return undefined;
|
|
189
|
+
}
|
|
190
|
+
if (parsed === null) return [];
|
|
191
|
+
if (!Array.isArray(parsed)) return undefined;
|
|
192
|
+
const out: T[] = [];
|
|
193
|
+
for (const item of parsed) {
|
|
194
|
+
if (item === null) {
|
|
195
|
+
out.push(Object.fromEntries(fields.filter((f) => f.required).map((f) => [f.name, ""])) as T);
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
if (typeof item !== "object" || Array.isArray(item)) return undefined;
|
|
199
|
+
const rec: Record<string, string> = {};
|
|
200
|
+
for (const f of fields) {
|
|
201
|
+
const v = fieldOf(item as Record<string, unknown>, f.name);
|
|
202
|
+
if (v === undefined || v === null) {
|
|
203
|
+
if (f.required) rec[f.name] = "";
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
if (typeof v !== "string") return undefined;
|
|
207
|
+
if (v !== "" || f.required) rec[f.name] = v;
|
|
208
|
+
}
|
|
209
|
+
out.push(rec as T);
|
|
210
|
+
}
|
|
211
|
+
return out;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const DRY_RUN_SIDE_EFFECTS = new Set([
|
|
215
|
+
"write",
|
|
216
|
+
"write-local",
|
|
217
|
+
"write-shared",
|
|
218
|
+
"destructive",
|
|
219
|
+
"destructive-local",
|
|
220
|
+
"destructive-shared",
|
|
221
|
+
]);
|
|
222
|
+
|
|
223
|
+
function dryRunSupported(ann: Annotations): boolean {
|
|
224
|
+
switch (ann["kit/dry-run"]) {
|
|
225
|
+
case "opted-out":
|
|
226
|
+
return false;
|
|
227
|
+
case "supported":
|
|
228
|
+
return true;
|
|
229
|
+
}
|
|
230
|
+
return DRY_RUN_SIDE_EFFECTS.has(ann["kit/side-effect"] ?? "");
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Map a commander option onto pflag's Type() and DefValue spelling,
|
|
235
|
+
* which is what the Go manifest carries.
|
|
236
|
+
*/
|
|
237
|
+
function flagTypeAndDefault(opt: CommanderOption): [string, string] {
|
|
238
|
+
const def = opt.defaultValue;
|
|
239
|
+
const declared = pflagTypes.get(opt);
|
|
240
|
+
if (declared) return [declared, def === undefined ? "" : String(def)];
|
|
241
|
+
if (opt.isBoolean()) return ["bool", def === undefined ? "false" : String(def)];
|
|
242
|
+
if (opt.variadic) {
|
|
243
|
+
const items = def === undefined ? [] : Array.isArray(def) ? def : [def];
|
|
244
|
+
return ["stringSlice", `[${items.map(String).join(",")}]`];
|
|
245
|
+
}
|
|
246
|
+
return ["string", def === undefined ? "" : String(def)];
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function manifestFlags(
|
|
250
|
+
cmd: CommanderCommand,
|
|
251
|
+
ann: Annotations,
|
|
252
|
+
withHelp: boolean,
|
|
253
|
+
): ManifestFlag[] | undefined {
|
|
254
|
+
const since = flagSince(ann);
|
|
255
|
+
const visible = (cmd.options as readonly CommanderOption[]).filter((o) => !o.hidden);
|
|
256
|
+
const flags: ManifestFlag[] = [];
|
|
257
|
+
for (const o of visible) {
|
|
258
|
+
const name = (o.long ?? o.short ?? "").replace(/^-+/, "");
|
|
259
|
+
if (name === "") continue;
|
|
260
|
+
const [type, def] = flagTypeAndDefault(o);
|
|
261
|
+
const f: ManifestFlag = { name };
|
|
262
|
+
if (o.long && o.short) f.short = o.short.replace(/^-/, "");
|
|
263
|
+
f.type = type;
|
|
264
|
+
if (o.description) f.description = o.description;
|
|
265
|
+
if (def !== "") f.default = def;
|
|
266
|
+
const sv = since.get(name);
|
|
267
|
+
if (sv) f.since_version = sv;
|
|
268
|
+
flags.push(f);
|
|
269
|
+
}
|
|
270
|
+
// cobra adds -h/--help to the command it executes (and only that
|
|
271
|
+
// one) before its RunE runs, so a live Go spec lists it there.
|
|
272
|
+
if (withHelp && !flags.some((f) => f.name === "help")) {
|
|
273
|
+
const help: ManifestFlag = { name: "help" };
|
|
274
|
+
if (!flags.some((f) => f.short === "h")) help.short = "h";
|
|
275
|
+
help.type = "bool";
|
|
276
|
+
help.description = `help for ${cmd.name()}`;
|
|
277
|
+
help.default = "false";
|
|
278
|
+
flags.push(help);
|
|
279
|
+
}
|
|
280
|
+
flags.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
281
|
+
return flags.length > 0 ? flags : undefined;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function manifestArgs(cmd: CommanderCommand, ann: Annotations): ManifestArg[] | undefined {
|
|
285
|
+
const declared = splitCSV(ann["kit/args"]);
|
|
286
|
+
const args: ManifestArg[] = declared
|
|
287
|
+
? declared.map((n) =>
|
|
288
|
+
n.endsWith("?") ? { name: n.slice(0, -1) } : { name: n, required: true },
|
|
289
|
+
)
|
|
290
|
+
: cmd.registeredArguments.map((a) =>
|
|
291
|
+
a.required ? { name: a.name(), required: true } : { name: a.name() },
|
|
292
|
+
);
|
|
293
|
+
return args.length > 0 ? args : undefined;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function manifestCommand(
|
|
297
|
+
cmd: CommanderCommand,
|
|
298
|
+
path: string[],
|
|
299
|
+
hidden: boolean,
|
|
300
|
+
reserved: boolean,
|
|
301
|
+
invoked: boolean,
|
|
302
|
+
): ManifestCommand {
|
|
303
|
+
const ann = annotationsOf(cmd);
|
|
304
|
+
// commander's summary() is the one-liner when set; description()
|
|
305
|
+
// then holds the long text (cobra Short / Long).
|
|
306
|
+
const summary = cmd.summary();
|
|
307
|
+
const short = summary || cmd.description();
|
|
308
|
+
const long = summary ? cmd.description() : "";
|
|
309
|
+
|
|
310
|
+
// Keys are inserted in Go struct order; the encoder keeps it.
|
|
311
|
+
const out = {
|
|
312
|
+
path,
|
|
313
|
+
short,
|
|
314
|
+
side_effect: ann["kit/side-effect"] || SIDE_EFFECT_UNKNOWN,
|
|
315
|
+
idempotent: ann["kit/idempotent"] || IDEMPOTENT_UNKNOWN,
|
|
316
|
+
} as ManifestCommand;
|
|
317
|
+
|
|
318
|
+
const args = manifestArgs(cmd, ann);
|
|
319
|
+
if (args) out.args = args;
|
|
320
|
+
const flags = manifestFlags(cmd, ann, invoked);
|
|
321
|
+
if (flags) out.flags = flags;
|
|
322
|
+
const exitCodes = splitCSV(ann["kit/exit-codes"]);
|
|
323
|
+
if (exitCodes) out.exit_codes = exitCodes;
|
|
324
|
+
|
|
325
|
+
const deprecatedSince = ann["kit/deprecated-since"] ?? "";
|
|
326
|
+
const removalTarget = ann["kit/removal-target"] ?? "";
|
|
327
|
+
if (deprecatedSince || removalTarget) out.deprecated = true;
|
|
328
|
+
if (deprecatedSince) out.deprecated_since = deprecatedSince;
|
|
329
|
+
if (removalTarget) out.removal_target = removalTarget;
|
|
330
|
+
if (ann["kit/since"]) out.since_version = ann["kit/since"];
|
|
331
|
+
|
|
332
|
+
if (long) out.long = long;
|
|
333
|
+
out.retryable = ann["kit/retryable"] === "true";
|
|
334
|
+
const schema = ann["kit/output-schema"];
|
|
335
|
+
if (schema) {
|
|
336
|
+
out.output_schema = schema;
|
|
337
|
+
if (ann["kit/output-schema-version"]) {
|
|
338
|
+
out.output_schema_version = ann["kit/output-schema-version"];
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
const examples = decodeList<ManifestExample>(ann["kit/examples"], [
|
|
342
|
+
{ name: "title", required: true },
|
|
343
|
+
{ name: "command", required: true },
|
|
344
|
+
{ name: "output", required: false },
|
|
345
|
+
]);
|
|
346
|
+
if (examples && examples.length > 0) out.examples = examples;
|
|
347
|
+
const nextSteps = decodeList<ManifestNextStep>(ann["kit/next-steps"], [
|
|
348
|
+
{ name: "when", required: false },
|
|
349
|
+
{ name: "suggest", required: true },
|
|
350
|
+
{ name: "reason", required: false },
|
|
351
|
+
]);
|
|
352
|
+
if (nextSteps && nextSteps.length > 0) out.next_steps = nextSteps;
|
|
353
|
+
|
|
354
|
+
if (ann["kit/top-level-verb"] === "true") out.top_level_verb = true;
|
|
355
|
+
if (ann["kit/hierarchical"] === "true") out.hierarchical = true;
|
|
356
|
+
if (ann["kit/passthrough"] === "true") out.passthrough = true;
|
|
357
|
+
const token = ann["kit/destructive-token"];
|
|
358
|
+
if (token === "required" || token === "true") out.destructive_token_required = true;
|
|
359
|
+
out.dry_run_supported = dryRunSupported(ann);
|
|
360
|
+
if (ann["kit/dry-run-rationale"]) out.dry_run_rationale = ann["kit/dry-run-rationale"];
|
|
361
|
+
if (reserved) out.reserved = true;
|
|
362
|
+
if (hidden) out.hidden = true;
|
|
363
|
+
return out;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Project a commander tree into the Go-shaped Manifest (Go
|
|
368
|
+
* BuildManifest). Lists every runnable command except framework
|
|
369
|
+
* builtins (help, completion, man) and, unless includeDeprecated,
|
|
370
|
+
* deprecated ones; hidden and reserved commands stay listed and say
|
|
371
|
+
* so. Children are visited in name order and flags sorted by name,
|
|
372
|
+
* as cobra and pflag do by default.
|
|
373
|
+
*/
|
|
374
|
+
export function buildManifest(
|
|
375
|
+
program: CommanderCommand,
|
|
376
|
+
schemaVersion: string,
|
|
377
|
+
opts: BuildManifestOptions = {},
|
|
378
|
+
): Manifest {
|
|
379
|
+
const m: Manifest = {
|
|
380
|
+
tool: program.name(),
|
|
381
|
+
version: program.version() ?? "",
|
|
382
|
+
schema_version: schemaVersion,
|
|
383
|
+
commands: [],
|
|
384
|
+
};
|
|
385
|
+
walkCommands(program, opts.reserved, (cmd, parent, path, reserved) => {
|
|
386
|
+
const ann = annotationsOf(cmd);
|
|
387
|
+
const deprecated = !!(ann["kit/deprecated-since"] || ann["kit/removal-target"]);
|
|
388
|
+
if (!isRunnable(cmd) || isBuiltin(cmd, parent)) return;
|
|
389
|
+
if (deprecated && !opts.includeDeprecated) return;
|
|
390
|
+
m.commands.push(
|
|
391
|
+
manifestCommand(cmd, path, isHidden(cmd, parent), reserved, cmd === opts.invokedCommand),
|
|
392
|
+
);
|
|
393
|
+
});
|
|
394
|
+
return m;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* Render a Manifest exactly as Go's `output.Render(w, "json", m)`:
|
|
399
|
+
* two-space indent, HTML-escaped strings, trailing newline, fields
|
|
400
|
+
* in Go struct order with omitempty applied.
|
|
401
|
+
*/
|
|
402
|
+
export function renderManifestJSON(m: Manifest): string {
|
|
403
|
+
return encodeGoJSON(m, 0, new Set(["output_schema"])) + "\n";
|
|
404
|
+
}
|