@edena-solutions/cli 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +101 -2
- package/dist/src/args.js +56 -0
- package/dist/src/cli.js +164 -0
- package/dist/src/commands/api.js +55 -0
- package/dist/src/commands/auth.js +115 -0
- package/dist/src/commands/docs.js +92 -0
- package/dist/src/commands/listen.js +155 -0
- package/dist/src/commands/logs.js +49 -0
- package/dist/src/commands/open.js +43 -0
- package/dist/src/commands/operation.js +216 -0
- package/dist/src/commands/skill.js +66 -0
- package/dist/src/config.js +105 -0
- package/dist/src/errors.js +53 -0
- package/dist/src/http.js +83 -0
- package/dist/src/output.js +83 -0
- package/dist/src/reference.js +181 -0
- package/dist/src/schema.js +213 -0
- package/dist/src/sse.js +98 -0
- package/dist/src/version.js +14 -0
- package/package.json +44 -4
- package/skill/SKILL.md +60 -0
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** Exit codes, so a script or an agent can tell what went wrong without reading the message. */
|
|
2
|
+
export const EXIT = {
|
|
3
|
+
ok: 0,
|
|
4
|
+
failure: 1,
|
|
5
|
+
usage: 2,
|
|
6
|
+
auth: 3,
|
|
7
|
+
notFound: 4,
|
|
8
|
+
conflict: 5,
|
|
9
|
+
rateLimited: 6,
|
|
10
|
+
};
|
|
11
|
+
/** A mistake in how the command was called: what is wrong, and how to call it. */
|
|
12
|
+
export class UsageError extends Error {
|
|
13
|
+
hint;
|
|
14
|
+
exitCode = EXIT.usage;
|
|
15
|
+
constructor(message, hint) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.hint = hint;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** No key to call the API with: nobody signed in, and no `EDENA_API_KEY`. */
|
|
21
|
+
export class NotSignedInError extends Error {
|
|
22
|
+
hint;
|
|
23
|
+
exitCode = EXIT.auth;
|
|
24
|
+
constructor(hint = "Run edena login, or set EDENA_API_KEY.") {
|
|
25
|
+
super("Not signed in.");
|
|
26
|
+
this.hint = hint;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** An error the API answered, with its stable `key` and the `requestId` to quote when asking for help. */
|
|
30
|
+
export class ApiError extends Error {
|
|
31
|
+
status;
|
|
32
|
+
key;
|
|
33
|
+
requestId;
|
|
34
|
+
details;
|
|
35
|
+
constructor(status, key, message, requestId, details) {
|
|
36
|
+
super(message);
|
|
37
|
+
this.status = status;
|
|
38
|
+
this.key = key;
|
|
39
|
+
this.requestId = requestId;
|
|
40
|
+
this.details = details;
|
|
41
|
+
}
|
|
42
|
+
get exitCode() {
|
|
43
|
+
if (this.status === 401 || this.status === 403)
|
|
44
|
+
return EXIT.auth;
|
|
45
|
+
if (this.status === 404)
|
|
46
|
+
return EXIT.notFound;
|
|
47
|
+
if (this.status === 409 || this.status === 422)
|
|
48
|
+
return EXIT.conflict;
|
|
49
|
+
if (this.status === 429)
|
|
50
|
+
return EXIT.rateLimited;
|
|
51
|
+
return EXIT.failure;
|
|
52
|
+
}
|
|
53
|
+
}
|
package/dist/src/http.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { ApiError } from "./errors.js";
|
|
3
|
+
import { VERSION } from "./version.js";
|
|
4
|
+
const WRITES = new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
5
|
+
const RETRIES = 3;
|
|
6
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
7
|
+
/** What the API answers on a 429 or a 5xx: worth retrying, waiting longer each time. */
|
|
8
|
+
const retryable = (status) => status === 429 || status >= 500;
|
|
9
|
+
/**
|
|
10
|
+
* Calls the API: the key, an `Idempotency-Key` on writes, retries on 429, 5xx and dropped
|
|
11
|
+
* connections with exponential backoff, and every error as an {@link ApiError} with its stable key.
|
|
12
|
+
*/
|
|
13
|
+
export async function apiRequest(options) {
|
|
14
|
+
const url = new URL(`${options.apiUrl}${options.path}`);
|
|
15
|
+
for (const [name, value] of Object.entries(options.query ?? {})) {
|
|
16
|
+
if (value === undefined)
|
|
17
|
+
continue;
|
|
18
|
+
for (const item of Array.isArray(value) ? value : [value])
|
|
19
|
+
url.searchParams.append(name, item);
|
|
20
|
+
}
|
|
21
|
+
const headers = {
|
|
22
|
+
...options.headers,
|
|
23
|
+
Accept: "application/json",
|
|
24
|
+
"User-Agent": `edena-cli/${VERSION} (node ${process.version}; ${process.platform})`,
|
|
25
|
+
};
|
|
26
|
+
if (options.apiKey)
|
|
27
|
+
headers.Authorization = `Bearer ${options.apiKey}`;
|
|
28
|
+
if (WRITES.has(options.method))
|
|
29
|
+
headers["Idempotency-Key"] = options.idempotencyKey ?? randomUUID();
|
|
30
|
+
if (options.body !== undefined)
|
|
31
|
+
headers["Content-Type"] = "application/json";
|
|
32
|
+
const body = options.body === undefined ? undefined : JSON.stringify(options.body);
|
|
33
|
+
for (let attempt = 0;; attempt++) {
|
|
34
|
+
let response;
|
|
35
|
+
try {
|
|
36
|
+
response = await fetch(url, { method: options.method, headers, body });
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
if (attempt < RETRIES) {
|
|
40
|
+
await sleep(backoff(attempt));
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
throw new ApiError(0, "cli.network_error", `Could not reach ${options.apiUrl}: ${error.message}`, null, null);
|
|
44
|
+
}
|
|
45
|
+
if (retryable(response.status) && attempt < RETRIES) {
|
|
46
|
+
await sleep(backoff(attempt, response.headers.get("retry-after")));
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
return read(response);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function backoff(attempt, retryAfter) {
|
|
53
|
+
const seconds = retryAfter ? Number(retryAfter) : Number.NaN;
|
|
54
|
+
if (Number.isFinite(seconds) && seconds > 0)
|
|
55
|
+
return Math.min(seconds, 30) * 1000;
|
|
56
|
+
return 500 * 2 ** attempt + Math.floor(Math.random() * 250);
|
|
57
|
+
}
|
|
58
|
+
async function read(response) {
|
|
59
|
+
const requestId = response.headers.get("x-request-id");
|
|
60
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
61
|
+
if (!response.ok) {
|
|
62
|
+
const text = await response.text();
|
|
63
|
+
let parsed = {};
|
|
64
|
+
try {
|
|
65
|
+
parsed = JSON.parse(text);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
// Not the API's error body: a proxy, a gateway. The status says enough.
|
|
69
|
+
}
|
|
70
|
+
const message = Array.isArray(parsed.message) ? parsed.message.join("; ") : (parsed.message ?? (text || response.statusText));
|
|
71
|
+
throw new ApiError(response.status, parsed.key ?? `http.${response.status}`, message, parsed.requestId ?? requestId, parsed.details ?? null);
|
|
72
|
+
}
|
|
73
|
+
if (response.status === 204)
|
|
74
|
+
return { kind: "empty", status: response.status, requestId };
|
|
75
|
+
if (contentType.includes("application/json")) {
|
|
76
|
+
const text = await response.text();
|
|
77
|
+
return { kind: "json", status: response.status, data: text ? JSON.parse(text) : null, requestId };
|
|
78
|
+
}
|
|
79
|
+
const data = Buffer.from(await response.arrayBuffer());
|
|
80
|
+
if (data.length === 0)
|
|
81
|
+
return { kind: "empty", status: response.status, requestId };
|
|
82
|
+
return { kind: "file", status: response.status, data, contentType, requestId };
|
|
83
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { ApiError, NotSignedInError, UsageError } from "./errors.js";
|
|
2
|
+
/** JSON when asked for, or when the output goes to another program (an agent, a pipe). */
|
|
3
|
+
export function wantsJson(json) {
|
|
4
|
+
return json || !process.stdout.isTTY;
|
|
5
|
+
}
|
|
6
|
+
const color = (code) => (text) => process.stdout.isTTY && !process.env.NO_COLOR ? `\u001b[${code}m${text}\u001b[0m` : text;
|
|
7
|
+
export const dim = color(2);
|
|
8
|
+
export const bold = color(1);
|
|
9
|
+
export const red = (text) => (process.stderr.isTTY && !process.env.NO_COLOR ? `\u001b[31m${text}\u001b[0m` : text);
|
|
10
|
+
export function printJson(value) {
|
|
11
|
+
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
|
|
12
|
+
}
|
|
13
|
+
/** Columns worth reading first in a table, when a row has them. */
|
|
14
|
+
const PREFERRED = ["id", "name", "surname1", "title", "email", "status", "role", "date", "total", "amount", "createdAt"];
|
|
15
|
+
const MAX_COLUMNS = 6;
|
|
16
|
+
/** An answer for a person: a table for a list, field by field for a record. */
|
|
17
|
+
export function printHuman(value) {
|
|
18
|
+
if (value === null || value === undefined)
|
|
19
|
+
return;
|
|
20
|
+
const rows = Array.isArray(value) ? value : isPage(value) ? value.data : null;
|
|
21
|
+
if (rows) {
|
|
22
|
+
printTable(rows);
|
|
23
|
+
if (isPage(value))
|
|
24
|
+
process.stdout.write(dim(`page ${value.meta.page} of ${value.meta.pages} · ${value.meta.total} in total\n`));
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
if (typeof value === "object") {
|
|
28
|
+
const entries = Object.entries(value);
|
|
29
|
+
const width = Math.max(...entries.map(([key]) => key.length), 0);
|
|
30
|
+
for (const [key, field] of entries)
|
|
31
|
+
process.stdout.write(`${dim(key.padEnd(width))} ${cell(field, 120)}\n`);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
process.stdout.write(`${String(value)}\n`);
|
|
35
|
+
}
|
|
36
|
+
function isPage(value) {
|
|
37
|
+
return (typeof value === "object" &&
|
|
38
|
+
value !== null &&
|
|
39
|
+
Array.isArray(value.data) &&
|
|
40
|
+
typeof value.meta?.total === "number");
|
|
41
|
+
}
|
|
42
|
+
function printTable(rows) {
|
|
43
|
+
if (rows.length === 0) {
|
|
44
|
+
process.stdout.write(dim("Nothing.\n"));
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const objects = rows.filter((row) => typeof row === "object" && row !== null);
|
|
48
|
+
if (objects.length === 0) {
|
|
49
|
+
for (const row of rows)
|
|
50
|
+
process.stdout.write(`${String(row)}\n`);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
const scalar = (key) => objects.some((row) => row[key] !== null && row[key] !== undefined && typeof row[key] !== "object");
|
|
54
|
+
const keys = [...new Set(objects.flatMap((row) => Object.keys(row)))].filter(scalar);
|
|
55
|
+
const columns = [...PREFERRED.filter((key) => keys.includes(key)), ...keys.filter((key) => !PREFERRED.includes(key))].slice(0, MAX_COLUMNS);
|
|
56
|
+
const limit = Math.max(12, Math.floor((process.stdout.columns ?? 120) / columns.length) - 2);
|
|
57
|
+
const cells = objects.map((row) => columns.map((key) => cell(row[key], limit)));
|
|
58
|
+
const widths = columns.map((key, index) => Math.max(key.length, ...cells.map((row) => row[index].length)));
|
|
59
|
+
process.stdout.write(`${bold(columns.map((key, index) => key.padEnd(widths[index])).join(" "))}\n`);
|
|
60
|
+
for (const row of cells)
|
|
61
|
+
process.stdout.write(`${row.map((text, index) => text.padEnd(widths[index])).join(" ")}\n`);
|
|
62
|
+
}
|
|
63
|
+
function cell(value, limit) {
|
|
64
|
+
const text = value === null || value === undefined ? "—" : typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
65
|
+
return text.length > limit ? `${text.slice(0, limit - 1)}…` : text;
|
|
66
|
+
}
|
|
67
|
+
/** An error for whoever reads it: the message, and for the API's errors their key and request id. */
|
|
68
|
+
export function printError(error, json) {
|
|
69
|
+
if (wantsJson(json) && error instanceof ApiError) {
|
|
70
|
+
process.stderr.write(`${JSON.stringify({ error: { status: error.status, key: error.key, message: error.message, requestId: error.requestId, details: error.details } })}\n`);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (error instanceof ApiError) {
|
|
74
|
+
process.stderr.write(`${red("Error")} ${error.message} (${error.key}${error.status ? `, ${error.status}` : ""})\n`);
|
|
75
|
+
if (error.requestId)
|
|
76
|
+
process.stderr.write(`Request id: ${error.requestId}\n`);
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
80
|
+
process.stderr.write(`${red("Error")} ${message}\n`);
|
|
81
|
+
if ((error instanceof UsageError || error instanceof NotSignedInError) && error.hint)
|
|
82
|
+
process.stderr.write(`${error.hint}\n`);
|
|
83
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { cacheDir } from "./config.js";
|
|
4
|
+
import { VERSION } from "./version.js";
|
|
5
|
+
const METHODS = ["get", "post", "put", "patch", "delete"];
|
|
6
|
+
/** The reference changes only with a deploy of the API; a day is fresh enough, and `docs refresh` forces it. */
|
|
7
|
+
const MAX_AGE_MS = 24 * 60 * 60 * 1000;
|
|
8
|
+
/** `García` → `garcia`: search ignores case and accents, as the console's does. */
|
|
9
|
+
export function fold(text) {
|
|
10
|
+
return text.normalize("NFD").replace(/\p{Diacritic}/gu, "").toLowerCase();
|
|
11
|
+
}
|
|
12
|
+
/** The API's operations as commands, and the ways to find one. */
|
|
13
|
+
export class Reference {
|
|
14
|
+
document;
|
|
15
|
+
operations = [];
|
|
16
|
+
groups = new Map();
|
|
17
|
+
byCommand = new Map();
|
|
18
|
+
byId = new Map();
|
|
19
|
+
constructor(document) {
|
|
20
|
+
this.document = document;
|
|
21
|
+
const tags = new Map((document.tags ?? []).map((tag) => [tag.name, tag]));
|
|
22
|
+
for (const [path, item] of Object.entries(document.paths)) {
|
|
23
|
+
for (const method of METHODS) {
|
|
24
|
+
const raw = item[method];
|
|
25
|
+
if (!raw?.operationId || !raw["x-cli"])
|
|
26
|
+
continue;
|
|
27
|
+
const tag = raw.tags?.[0] ?? "";
|
|
28
|
+
const [group = "", action = ""] = raw["x-cli"].split(" ");
|
|
29
|
+
const operation = {
|
|
30
|
+
id: raw.operationId,
|
|
31
|
+
method: method.toUpperCase(),
|
|
32
|
+
path,
|
|
33
|
+
tag,
|
|
34
|
+
category: tags.get(tag)?.["x-displayName"] ?? tag,
|
|
35
|
+
summary: (raw.summary ?? "").trim(),
|
|
36
|
+
command: raw["x-cli"],
|
|
37
|
+
group,
|
|
38
|
+
action,
|
|
39
|
+
parameters: raw.parameters ?? [],
|
|
40
|
+
requestBody: raw.requestBody,
|
|
41
|
+
responses: raw.responses ?? {},
|
|
42
|
+
};
|
|
43
|
+
this.operations.push(operation);
|
|
44
|
+
this.byCommand.set(operation.command, operation);
|
|
45
|
+
this.byId.set(operation.id, operation);
|
|
46
|
+
let entry = this.groups.get(group);
|
|
47
|
+
if (!entry) {
|
|
48
|
+
entry = { name: group, category: operation.category, description: tags.get(tag)?.description ?? "", operations: [] };
|
|
49
|
+
this.groups.set(group, entry);
|
|
50
|
+
}
|
|
51
|
+
entry.operations.push(operation);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
for (const entry of this.groups.values())
|
|
55
|
+
entry.operations.sort((a, b) => a.action.localeCompare(b.action));
|
|
56
|
+
}
|
|
57
|
+
/** By its command (`students list`) or its operation id (`clients_list`). */
|
|
58
|
+
find(name) {
|
|
59
|
+
return this.byCommand.get(name.trim().replace(/\s+/g, " ")) ?? this.byId.get(name.trim()) ?? null;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* What a query finds, best first: the operations matching the most words, a word in the command or
|
|
63
|
+
* the summary counting more than one in the path. Words like "the" or "without" are left out and
|
|
64
|
+
* plurals match their singular, since an agent searches with what the person said.
|
|
65
|
+
*/
|
|
66
|
+
search(query, limit = 20) {
|
|
67
|
+
const words = fold(query)
|
|
68
|
+
.split(/[^a-z0-9-]+/)
|
|
69
|
+
.filter((word) => word.length > 1 && !STOP_WORDS.has(word))
|
|
70
|
+
.map(stem);
|
|
71
|
+
if (words.length === 0)
|
|
72
|
+
return [];
|
|
73
|
+
const needed = Math.max(1, Math.ceil(words.length / 2));
|
|
74
|
+
const scored = [];
|
|
75
|
+
for (const operation of this.operations) {
|
|
76
|
+
const fields = {
|
|
77
|
+
command: stems(operation.command),
|
|
78
|
+
summary: stems(operation.summary),
|
|
79
|
+
category: stems(`${operation.category} ${this.groups.get(operation.group)?.description ?? ""}`),
|
|
80
|
+
other: stems(`${operation.id} ${operation.path} ${operation.method}`),
|
|
81
|
+
};
|
|
82
|
+
const commandWords = new Set(fields.command.split(" "));
|
|
83
|
+
let matched = 0;
|
|
84
|
+
let score = 0;
|
|
85
|
+
for (const word of words) {
|
|
86
|
+
const hit = (commandWords.has(word) ? 3 : 0) +
|
|
87
|
+
(fields.command.includes(word) ? 4 : 0) +
|
|
88
|
+
(fields.summary.includes(word) ? 3 : 0) +
|
|
89
|
+
(fields.category.includes(word) ? 2 : 0) +
|
|
90
|
+
(fields.other.includes(word) ? 1 : 0);
|
|
91
|
+
if (hit > 0)
|
|
92
|
+
matched++;
|
|
93
|
+
score += hit;
|
|
94
|
+
}
|
|
95
|
+
if (matched >= needed)
|
|
96
|
+
scored.push({ operation, matched, score });
|
|
97
|
+
}
|
|
98
|
+
return scored
|
|
99
|
+
.sort((a, b) => b.matched - a.matched ||
|
|
100
|
+
Number(isDeprecated(a.operation)) - Number(isDeprecated(b.operation)) ||
|
|
101
|
+
b.score - a.score ||
|
|
102
|
+
a.operation.command.split(/[ -]/).length - b.operation.command.split(/[ -]/).length ||
|
|
103
|
+
a.operation.command.localeCompare(b.operation.command))
|
|
104
|
+
.slice(0, limit)
|
|
105
|
+
.map((entry) => entry.operation);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/** Kept for old apps: listed after what replaces it. */
|
|
109
|
+
const isDeprecated = (operation) => operation.summary.startsWith("Deprecated");
|
|
110
|
+
/** Words that say nothing about which operation is meant. */
|
|
111
|
+
const STOP_WORDS = new Set([
|
|
112
|
+
"a", "an", "the", "of", "for", "to", "in", "on", "at", "by", "with", "without", "and", "or", "not", "no",
|
|
113
|
+
"my", "our", "their", "all", "any", "every", "that", "which", "who", "is", "are", "have", "has", "how", "many", "much",
|
|
114
|
+
]);
|
|
115
|
+
/** A text as the stems of its words, so `families` finds `family` and the other way round. */
|
|
116
|
+
function stems(text) {
|
|
117
|
+
return fold(text.replace(/([a-z0-9])([A-Z])/g, "$1 $2"))
|
|
118
|
+
.split(/[^a-z0-9]+/)
|
|
119
|
+
.filter(Boolean)
|
|
120
|
+
.map(stem)
|
|
121
|
+
.join(" ");
|
|
122
|
+
}
|
|
123
|
+
/** `students` → `student`, `classes` → `class`: a plural finds its singular, and the other way round. */
|
|
124
|
+
function stem(word) {
|
|
125
|
+
if (word.length > 4 && word.endsWith("ies"))
|
|
126
|
+
return `${word.slice(0, -3)}y`;
|
|
127
|
+
if (word.length > 4 && /(ss|sh|ch|x)es$/.test(word))
|
|
128
|
+
return word.slice(0, -2);
|
|
129
|
+
if (word.length > 3 && word.endsWith("s") && !word.endsWith("ss"))
|
|
130
|
+
return word.slice(0, -1);
|
|
131
|
+
return word;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* The API reference, from the cache when it is fresh, else from `GET /openapi.json` (public, no key
|
|
135
|
+
* needed), asking with the cached ETag so an unchanged one costs nothing. Offline, a stale copy still
|
|
136
|
+
* serves; `EDENA_REFERENCE_FILE` reads one from disk instead.
|
|
137
|
+
*/
|
|
138
|
+
export async function loadReference(apiUrl, options = {}) {
|
|
139
|
+
if (process.env.EDENA_REFERENCE_FILE) {
|
|
140
|
+
return new Reference(JSON.parse(await readFile(process.env.EDENA_REFERENCE_FILE, "utf8")));
|
|
141
|
+
}
|
|
142
|
+
const dir = cacheDir();
|
|
143
|
+
const file = join(dir, "openapi.json");
|
|
144
|
+
const metaFile = join(dir, "openapi.meta.json");
|
|
145
|
+
const cached = await readCache(file, metaFile, apiUrl);
|
|
146
|
+
if (cached && !options.refresh && Date.now() - cached.mtime < MAX_AGE_MS)
|
|
147
|
+
return new Reference(cached.document);
|
|
148
|
+
try {
|
|
149
|
+
const response = await fetch(`${apiUrl}/openapi.json?lang=en`, {
|
|
150
|
+
headers: { Accept: "application/json", "User-Agent": `edena-cli/${VERSION}`, ...(cached?.meta.etag && { "If-None-Match": cached.meta.etag }) },
|
|
151
|
+
});
|
|
152
|
+
if (response.status === 304 && cached) {
|
|
153
|
+
await writeFile(file, JSON.stringify(cached.document));
|
|
154
|
+
return new Reference(cached.document);
|
|
155
|
+
}
|
|
156
|
+
if (!response.ok)
|
|
157
|
+
throw new Error(`HTTP ${response.status}`);
|
|
158
|
+
const document = (await response.json());
|
|
159
|
+
await mkdir(dir, { recursive: true });
|
|
160
|
+
await writeFile(file, JSON.stringify(document));
|
|
161
|
+
await writeFile(metaFile, JSON.stringify({ etag: response.headers.get("etag"), apiUrl }));
|
|
162
|
+
return new Reference(document);
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
if (cached)
|
|
166
|
+
return new Reference(cached.document);
|
|
167
|
+
throw new Error(`Could not load the API reference from ${apiUrl}: ${error.message}`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
async function readCache(file, metaFile, apiUrl) {
|
|
171
|
+
try {
|
|
172
|
+
const meta = JSON.parse(await readFile(metaFile, "utf8"));
|
|
173
|
+
if (meta.apiUrl !== apiUrl)
|
|
174
|
+
return null;
|
|
175
|
+
const [raw, info] = await Promise.all([readFile(file, "utf8"), stat(file)]);
|
|
176
|
+
return { document: JSON.parse(raw), meta, mtime: info.mtimeMs };
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
const MAX_INLINE_DEPTH = 3;
|
|
2
|
+
/** Enough for any category; past it the rest are named so the reader knows they exist. */
|
|
3
|
+
const MAX_TYPES = 150;
|
|
4
|
+
/** Covered by the rules every prompt states, so not repeated under each write. */
|
|
5
|
+
const RULE_HEADERS = new Set(["idempotency-key"]);
|
|
6
|
+
/** `#/components/schemas/Client` → `Client`. */
|
|
7
|
+
export function refName(schema) {
|
|
8
|
+
return schema?.$ref ? (schema.$ref.split("/").pop() ?? null) : null;
|
|
9
|
+
}
|
|
10
|
+
/** The named schemas an operation reaches, rendered once each as TypeScript. */
|
|
11
|
+
export class TypeCollector {
|
|
12
|
+
document;
|
|
13
|
+
exported;
|
|
14
|
+
order = [];
|
|
15
|
+
seen = new Set();
|
|
16
|
+
constructor(document, exported = false) {
|
|
17
|
+
this.document = document;
|
|
18
|
+
this.exported = exported;
|
|
19
|
+
}
|
|
20
|
+
add(name) {
|
|
21
|
+
if (this.seen.has(name))
|
|
22
|
+
return;
|
|
23
|
+
this.seen.add(name);
|
|
24
|
+
this.order.push(name);
|
|
25
|
+
}
|
|
26
|
+
/** A schema as a TypeScript type, naming every reference it meets. */
|
|
27
|
+
ts(schema, depth = 0) {
|
|
28
|
+
const name = refName(schema);
|
|
29
|
+
if (name) {
|
|
30
|
+
this.add(name);
|
|
31
|
+
return name;
|
|
32
|
+
}
|
|
33
|
+
return this.bare(schema, depth) + (schema.nullable ? " | null" : "");
|
|
34
|
+
}
|
|
35
|
+
bare(schema, depth) {
|
|
36
|
+
if (schema.allOf?.length)
|
|
37
|
+
return schema.allOf.map((part) => this.ts(part, depth)).join(" & ");
|
|
38
|
+
const union = schema.oneOf ?? schema.anyOf;
|
|
39
|
+
if (union?.length)
|
|
40
|
+
return union.map((part) => this.ts(part, depth)).join(" | ");
|
|
41
|
+
if (schema.enum?.length)
|
|
42
|
+
return schema.enum.map((value) => JSON.stringify(value)).join(" | ");
|
|
43
|
+
switch (schema.type) {
|
|
44
|
+
case "string":
|
|
45
|
+
return schema.format === "binary" ? "Blob" : "string";
|
|
46
|
+
case "integer":
|
|
47
|
+
case "number":
|
|
48
|
+
return "number";
|
|
49
|
+
case "boolean":
|
|
50
|
+
return "boolean";
|
|
51
|
+
case "array": {
|
|
52
|
+
const item = this.ts(schema.items ?? {}, depth);
|
|
53
|
+
return /[|& ]/.test(item) ? `Array<${item}>` : `${item}[]`;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (schema.properties && depth < MAX_INLINE_DEPTH) {
|
|
57
|
+
const required = new Set(schema.required ?? []);
|
|
58
|
+
const fields = Object.entries(schema.properties).map(([key, property]) => `${key}${required.has(key) ? "" : "?"}: ${this.ts(property, depth + 1)}`);
|
|
59
|
+
return `{ ${fields.join("; ")} }`;
|
|
60
|
+
}
|
|
61
|
+
if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
|
|
62
|
+
return `Record<string, ${this.ts(schema.additionalProperties, depth + 1)}>`;
|
|
63
|
+
}
|
|
64
|
+
return schema.type === "object" || schema.additionalProperties ? "Record<string, unknown>" : "unknown";
|
|
65
|
+
}
|
|
66
|
+
/** Every type collected, in the order met; rendering one may meet more, so it runs to the end. */
|
|
67
|
+
render() {
|
|
68
|
+
const blocks = [];
|
|
69
|
+
for (let index = 0; index < this.order.length && blocks.length < MAX_TYPES; index++) {
|
|
70
|
+
blocks.push(this.block(this.order[index]));
|
|
71
|
+
}
|
|
72
|
+
return { blocks, omitted: this.order.slice(blocks.length) };
|
|
73
|
+
}
|
|
74
|
+
block(name) {
|
|
75
|
+
const schema = this.document.components?.schemas?.[name] ?? {};
|
|
76
|
+
const doc = schema.description ? `/** ${oneLine(schema.description)} */\n` : "";
|
|
77
|
+
const keyword = this.exported ? "export " : "";
|
|
78
|
+
if (!schema.properties)
|
|
79
|
+
return `${doc}${keyword}type ${name} = ${this.bare(schema, 0)};`;
|
|
80
|
+
const required = new Set(schema.required ?? []);
|
|
81
|
+
const fields = Object.entries(schema.properties).map(([key, property]) => {
|
|
82
|
+
const note = propertyNote(property);
|
|
83
|
+
const comment = note ? ` /** ${note} */\n` : "";
|
|
84
|
+
return `${comment} ${key}${required.has(key) ? "" : "?"}: ${this.ts(property, 1)};`;
|
|
85
|
+
});
|
|
86
|
+
return `${doc}${keyword}interface ${name} {\n${fields.join("\n")}\n}`;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/** What a field's type does not say: its description and its constraints. */
|
|
90
|
+
function propertyNote(schema) {
|
|
91
|
+
const constraints = [
|
|
92
|
+
schema.format && schema.format !== "binary" ? schema.format : null,
|
|
93
|
+
schema.minLength !== undefined ? `min ${schema.minLength}` : null,
|
|
94
|
+
schema.maxLength !== undefined ? `max ${schema.maxLength}` : null,
|
|
95
|
+
schema.minimum !== undefined ? `>= ${schema.minimum}` : null,
|
|
96
|
+
schema.maximum !== undefined ? `<= ${schema.maximum}` : null,
|
|
97
|
+
].filter(Boolean);
|
|
98
|
+
const description = schema.description ? oneLine(schema.description) : "";
|
|
99
|
+
if (constraints.length === 0)
|
|
100
|
+
return description;
|
|
101
|
+
return description ? `${description} (${constraints.join(", ")})` : constraints.join(", ");
|
|
102
|
+
}
|
|
103
|
+
export function oneLine(text) {
|
|
104
|
+
return text.replace(/\s+/g, " ").replace(/\*\//g, "*\\/").trim();
|
|
105
|
+
}
|
|
106
|
+
/** The parameters an operation takes, by where they go; the idempotency header is the CLI's own. */
|
|
107
|
+
export function parametersOf(operation) {
|
|
108
|
+
const visible = (parameter) => !(parameter.in === "header" && RULE_HEADERS.has(parameter.name.toLowerCase()));
|
|
109
|
+
return {
|
|
110
|
+
path: operation.parameters.filter((parameter) => parameter.in === "path"),
|
|
111
|
+
query: operation.parameters.filter((parameter) => parameter.in === "query"),
|
|
112
|
+
headers: operation.parameters.filter((parameter) => parameter.in === "header" && visible(parameter)),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/** The JSON body an operation takes, when it takes one. */
|
|
116
|
+
export function bodySchemaOf(operation) {
|
|
117
|
+
const content = operation.requestBody?.content;
|
|
118
|
+
if (!content)
|
|
119
|
+
return null;
|
|
120
|
+
const [mediaType, media] = Object.entries(content)[0] ?? [];
|
|
121
|
+
if (!mediaType || !media?.schema)
|
|
122
|
+
return null;
|
|
123
|
+
return { schema: media.schema, required: Boolean(operation.requestBody?.required), mediaType };
|
|
124
|
+
}
|
|
125
|
+
/** The schema a `$ref` points to; any other is answered as it is. */
|
|
126
|
+
export function resolve(document, schema) {
|
|
127
|
+
if (!schema)
|
|
128
|
+
return {};
|
|
129
|
+
const name = refName(schema);
|
|
130
|
+
return name ? (document.components?.schemas?.[name] ?? {}) : schema;
|
|
131
|
+
}
|
|
132
|
+
/** One operation, as a section of a prompt or of `docs show`. */
|
|
133
|
+
export function operationMarkdown(operation, types) {
|
|
134
|
+
const { path, query, headers } = parametersOf(operation);
|
|
135
|
+
const lines = [`### ${operation.method} ${operation.path}`, "", `\`edena ${operation.command}\` (\`${operation.id}\`): ${operation.summary}`, ""];
|
|
136
|
+
for (const [label, group] of [
|
|
137
|
+
["Path parameters", path],
|
|
138
|
+
["Query parameters", query],
|
|
139
|
+
["Headers", headers],
|
|
140
|
+
]) {
|
|
141
|
+
if (group.length === 0)
|
|
142
|
+
continue;
|
|
143
|
+
lines.push(`${label}:`);
|
|
144
|
+
for (const parameter of group) {
|
|
145
|
+
const type = parameter.schema ? types.ts(parameter.schema) : "string";
|
|
146
|
+
const description = parameter.description ? `: ${oneLine(parameter.description)}` : "";
|
|
147
|
+
lines.push(`- \`${parameter.name}\` (\`${type}\`${parameter.required ? ", required" : ""})${description}`);
|
|
148
|
+
}
|
|
149
|
+
lines.push("");
|
|
150
|
+
}
|
|
151
|
+
const body = bodySchemaOf(operation);
|
|
152
|
+
if (body) {
|
|
153
|
+
const media = body.mediaType === "application/json" ? "" : `, ${body.mediaType}`;
|
|
154
|
+
lines.push(`Body${media}${body.required ? ", required" : ""}: \`${types.ts(body.schema)}\``, "");
|
|
155
|
+
}
|
|
156
|
+
const responses = Object.entries(operation.responses);
|
|
157
|
+
for (const [status, response] of responses.filter(([code]) => code.startsWith("2"))) {
|
|
158
|
+
const json = response.content?.["application/json"]?.schema;
|
|
159
|
+
const other = response.content ? Object.keys(response.content)[0] : undefined;
|
|
160
|
+
lines.push(`Response ${status}: ${json ? `\`${types.ts(json)}\`` : other ? `file (${other})` : "no body"}`);
|
|
161
|
+
}
|
|
162
|
+
const errors = responses.filter(([code]) => !code.startsWith("2")).map(([code]) => code);
|
|
163
|
+
if (errors.length > 0)
|
|
164
|
+
lines.push(`Errors: ${errors.join(", ")} (\`ErrorResponse\`)`);
|
|
165
|
+
lines.push("");
|
|
166
|
+
return lines;
|
|
167
|
+
}
|
|
168
|
+
const RULES = (apiUrl) => [
|
|
169
|
+
`Base URL: \`${apiUrl}\`.`,
|
|
170
|
+
"Authentication: header `Authorization: Bearer <key>`, with the key in the `EDENA_API_KEY` environment variable. Never put it in code that runs in a browser: a key sent from a web page answers 403 `auth.api_key_in_browser`. When an app acts on behalf of its users, request end-user tokens (`POST /end-user-tokens`) from your server.",
|
|
171
|
+
"Writes (POST, PUT, PATCH, DELETE): send the `Idempotency-Key` header with a UUID per operation and reuse it when retrying; for 24 hours the same key answers what it answered the first time.",
|
|
172
|
+
"Errors: every one answers `ErrorResponse`. Decide on `key`, which is stable, never on `message`, and log `requestId`. A 400 names the fields that failed in `details.fields`.",
|
|
173
|
+
"Limit: 300 requests per minute per key; past that the API answers 429. Retry with exponential backoff, as for a 5xx.",
|
|
174
|
+
"Paginated lists take `page` and `pageSize` and answer `{ data, meta: { total, page, pageSize, pages } }`.",
|
|
175
|
+
"To learn about changes without polling, use webhooks (set up in the developer console) or `GET /webhook-events`.",
|
|
176
|
+
];
|
|
177
|
+
const DELIVER = [
|
|
178
|
+
"One function per operation, named after its `operationId` in camelCase, taking its path parameters, query parameters and body, and returning the response with its type.",
|
|
179
|
+
"The types of the “Types” section, as they are.",
|
|
180
|
+
"A shared function for every request: authentication, `Idempotency-Key` on writes, retries on 429 and 5xx, and a typed error with `statusCode`, `key` and `requestId`.",
|
|
181
|
+
"An example of each function in use.",
|
|
182
|
+
"Write it in my project's language and style; if there is none, in TypeScript.",
|
|
183
|
+
];
|
|
184
|
+
/**
|
|
185
|
+
* A prompt for a coding agent to implement a whole category: how the API works, every operation, and
|
|
186
|
+
* every type they use, once. The same one the console's «Copy prompt» writes, in English.
|
|
187
|
+
*/
|
|
188
|
+
export function categoryPrompt(document, group, apiUrl) {
|
|
189
|
+
const types = new TypeCollector(document);
|
|
190
|
+
const sections = group.operations.flatMap((operation) => operationMarkdown(operation, types));
|
|
191
|
+
if (document.components?.schemas?.ErrorResponse)
|
|
192
|
+
types.add("ErrorResponse");
|
|
193
|
+
const lines = [
|
|
194
|
+
`# Implement the integration with “${group.category}” of the Edena API`,
|
|
195
|
+
"",
|
|
196
|
+
"You are a senior developer. Implement in my project the integration with every operation of this category of the Edena API, the management platform for schools. Use only what this document describes: do not invent endpoints, fields or values. If something is unclear, ask me before assuming it.",
|
|
197
|
+
"",
|
|
198
|
+
"## How the API works",
|
|
199
|
+
"",
|
|
200
|
+
...RULES(apiUrl).map((rule) => `- ${rule}`),
|
|
201
|
+
"",
|
|
202
|
+
];
|
|
203
|
+
if (group.description)
|
|
204
|
+
lines.push(`## The category: ${group.category}`, "", group.description, "");
|
|
205
|
+
lines.push(`## Operations (${group.operations.length})`, "", ...sections);
|
|
206
|
+
const { blocks, omitted } = types.render();
|
|
207
|
+
if (blocks.length > 0)
|
|
208
|
+
lines.push("## Types", "", "```ts", blocks.join("\n\n"), "```", "");
|
|
209
|
+
if (omitted.length > 0)
|
|
210
|
+
lines.push(`Other types they refer to, left out for length: ${omitted.join(", ")}.`, "");
|
|
211
|
+
lines.push("## What to deliver", "", ...DELIVER.map((item) => `- ${item}`));
|
|
212
|
+
return `${lines.join("\n").trimEnd()}\n`;
|
|
213
|
+
}
|