@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
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Edena Software S.L.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,102 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Edena CLI
|
|
2
|
+
|
|
3
|
+
`edena` runs every operation of the [Edena API](https://api.edena.es/openapi.json) as a command, for people and for coding agents (Claude Code, Codex, Gemini CLI).
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install -g @edena-solutions/cli
|
|
7
|
+
edena login
|
|
8
|
+
edena students list --status active
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Requires Node.js 20 or later. No runtime dependencies.
|
|
12
|
+
|
|
13
|
+
## Sign in
|
|
14
|
+
|
|
15
|
+
`edena login` prints a link and a code, and opens the browser. In the Edena console, an Admin Developer checks the code and approves it, choosing where the CLI works (the organization's sandbox, recommended, or its real data) and the role of its key. The terminal then receives an API key of its own, named after the machine, which shows up in the console's Keys and can be revoked there.
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
edena whoami # the organization and key in use
|
|
19
|
+
edena profiles # every organization this terminal is signed in to
|
|
20
|
+
edena use my-school-sandbox # switch: a profile is named after its organization's slug
|
|
21
|
+
edena logout # revoke this terminal's key and forget it
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Signing in to the sandbox and to the real data gives two profiles (`my-school-sandbox` and `my-school`); `edena use` or `--profile` picks one.
|
|
25
|
+
|
|
26
|
+
`EDENA_API_KEY` overrides the session (CI, scripts). `EDENA_API_URL` points the CLI at another API, such as `http://localhost:8080` while developing Edena itself.
|
|
27
|
+
|
|
28
|
+
## Commands
|
|
29
|
+
|
|
30
|
+
Every API operation is `edena <category> <action>`, named after the reference: `edena students list`, `edena invoices get <id>`, `edena clocking void-break <id> <breakId>`. The commands come from the API's public reference (cached for a day), so new endpoints appear without updating the CLI.
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
edena categories # every category
|
|
34
|
+
edena students # its actions
|
|
35
|
+
edena students list --help # arguments, flags, body fields and answer
|
|
36
|
+
edena docs search "unpaid invoices" # find a command in plain words
|
|
37
|
+
edena docs show students create # one operation with all its types
|
|
38
|
+
|
|
39
|
+
edena students get 0190f3a2-… # path parameters in order
|
|
40
|
+
edena students list --status active --all # query flags; --all follows every page
|
|
41
|
+
edena students create --name Ana --surname1 Pérez # a flag per body field
|
|
42
|
+
edena students create --data @student.json # or the whole body (also --data '<json>' or --data -)
|
|
43
|
+
edena invoices pdf <id> --output invoice.pdf # files
|
|
44
|
+
edena api GET /clients --query status=active # any request
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Output is a table in a terminal and JSON when piped or with `--json`. Writes ask for confirmation; without a terminal (an agent, a script) they need `--yes`. Every write carries an `Idempotency-Key`, reused on retries, and 429 and 5xx answers are retried with backoff.
|
|
48
|
+
|
|
49
|
+
Exit codes: `0` done, `1` failed, `2` called wrong, `3` not signed in or not allowed, `4` not found, `5` conflict, `6` rate limited. Errors carry the API's stable `key` and its `requestId`.
|
|
50
|
+
|
|
51
|
+
## Developing locally
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
edena listen --forward-to http://localhost:3000/webhooks # events as they happen, to your local server
|
|
55
|
+
edena listen --events "client.*,invoice.updated" --since 1h # some types, replaying the last hour first
|
|
56
|
+
edena trigger client.updated # resend the latest real one to that server
|
|
57
|
+
edena trigger --event 019a8c5e-… # or a given event
|
|
58
|
+
edena logs --mine # the API's requests as they happen
|
|
59
|
+
edena open webhooks # the console, in the browser
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
`listen` needs no public address: it follows `GET /webhook-events/stream` and posts each event to your server exactly as an endpoint receives it, the same body and the same `Edena-Signature`, signed with a secret of this machine (`edena listen --print-secret`). Verify it in your server as you would an endpoint's. It reconnects on its own and resumes from the last event.
|
|
63
|
+
|
|
64
|
+
## Building with the API
|
|
65
|
+
|
|
66
|
+
```sh
|
|
67
|
+
edena prompt invoices > invoices.md # a full spec of a category, for a coding agent
|
|
68
|
+
edena types invoices students > src/edena.types.ts
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Coding agents
|
|
72
|
+
|
|
73
|
+
```sh
|
|
74
|
+
edena skill install # Claude Code, Codex and Gemini CLI found on this machine
|
|
75
|
+
edena skill install --agent claude # or one of them; --project writes it in the current project
|
|
76
|
+
edena skill show # the skill itself
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
The skill ([`skill/SKILL.md`](skill/SKILL.md), in the open Agent Skills format) teaches the agent to check the session, find commands with `docs search` instead of guessing, run them with `--json`, ask before any write, and integrate the API with `prompt` and `types`. Then ask in your own words: "how many active students have no payer?".
|
|
80
|
+
|
|
81
|
+
## Development
|
|
82
|
+
|
|
83
|
+
```sh
|
|
84
|
+
npm install
|
|
85
|
+
npm test # builds, then runs the unit tests and an end-to-end run against a fake API
|
|
86
|
+
node dist/src/cli.js --help
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`EDENA_REFERENCE_FILE=path/to/openapi.json` reads the reference from disk; `EDENA_CONFIG_DIR` and `EDENA_CACHE_DIR` move the config and the cache.
|
|
90
|
+
|
|
91
|
+
## Releasing
|
|
92
|
+
|
|
93
|
+
1. `npm version patch` (or `minor`, `major`, `prerelease --preid beta`): bumps `package.json` and tags `vX.Y.Z`.
|
|
94
|
+
2. `git push --follow-tags`.
|
|
95
|
+
3. Publish a GitHub release from the tag (`gh release create vX.Y.Z --generate-notes`).
|
|
96
|
+
|
|
97
|
+
The **Publish to npm** workflow then tests and publishes it with npm's trusted publishing and provenance; a pre-release goes out under the `next` tag. CI runs the tests on every push and pull request.
|
|
98
|
+
|
|
99
|
+
## License
|
|
100
|
+
|
|
101
|
+
[MIT](LICENSE)
|
|
2
102
|
|
|
3
|
-
This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
|
package/dist/src/args.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** Flags that never take a value, so `--json students` does not swallow the word after it. */
|
|
2
|
+
const BOOLEAN_FLAGS = new Set(["json", "yes", "all", "help", "refresh", "project", "version", "noBrowser", "printSecret", "mine"]);
|
|
3
|
+
const SHORT = { y: "yes", h: "help", v: "version" };
|
|
4
|
+
/** `--page-size` and `--pageSize` are the same flag: the API names it in camelCase. */
|
|
5
|
+
export function flagName(raw) {
|
|
6
|
+
return raw.replace(/-([a-z0-9])/g, (_, letter) => letter.toUpperCase());
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* `edena students get 0190… --status active --tag a --tag b --json` → positionals and flags. A flag
|
|
10
|
+
* takes the next word as its value unless that is another flag; `--name=value` works too, and `--`
|
|
11
|
+
* ends the flags.
|
|
12
|
+
*/
|
|
13
|
+
export function parseArgs(argv) {
|
|
14
|
+
const positionals = [];
|
|
15
|
+
const flags = new Map();
|
|
16
|
+
const add = (name, value) => flags.set(name, [...(flags.get(name) ?? []), value]);
|
|
17
|
+
for (let index = 0; index < argv.length; index++) {
|
|
18
|
+
const token = argv[index];
|
|
19
|
+
if (token === "--") {
|
|
20
|
+
positionals.push(...argv.slice(index + 1));
|
|
21
|
+
break;
|
|
22
|
+
}
|
|
23
|
+
if (/^-[a-z]$/i.test(token)) {
|
|
24
|
+
add(SHORT[token.slice(1)] ?? token.slice(1), "true");
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
if (!token.startsWith("--")) {
|
|
28
|
+
positionals.push(token);
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
const body = token.slice(2);
|
|
32
|
+
const equals = body.indexOf("=");
|
|
33
|
+
if (equals >= 0) {
|
|
34
|
+
add(flagName(body.slice(0, equals)), body.slice(equals + 1));
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
const name = flagName(body);
|
|
38
|
+
const next = argv[index + 1];
|
|
39
|
+
if (BOOLEAN_FLAGS.has(name) || next === undefined || next.startsWith("--")) {
|
|
40
|
+
add(name, "true");
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
add(name, next);
|
|
44
|
+
index++;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return { positionals, flags };
|
|
48
|
+
}
|
|
49
|
+
export function flag(args, name) {
|
|
50
|
+
const values = args.flags.get(name);
|
|
51
|
+
return values?.[values.length - 1];
|
|
52
|
+
}
|
|
53
|
+
export function hasFlag(args, name) {
|
|
54
|
+
const value = flag(args, name);
|
|
55
|
+
return value !== undefined && value !== "false";
|
|
56
|
+
}
|
package/dist/src/cli.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { flag, hasFlag, parseArgs } from "./args.js";
|
|
3
|
+
import { api } from "./commands/api.js";
|
|
4
|
+
import { login, logout, profiles, use, whoami } from "./commands/auth.js";
|
|
5
|
+
import { categories, docsRefresh, docsSearch, docsShow, prompt, types } from "./commands/docs.js";
|
|
6
|
+
import { listen, trigger } from "./commands/listen.js";
|
|
7
|
+
import { logs } from "./commands/logs.js";
|
|
8
|
+
import { groupHelp, operationHelp, runOperation } from "./commands/operation.js";
|
|
9
|
+
import { open } from "./commands/open.js";
|
|
10
|
+
import { skillInstall, skillShow, skillUninstall } from "./commands/skill.js";
|
|
11
|
+
import { resolveSession } from "./config.js";
|
|
12
|
+
import { EXIT, UsageError } from "./errors.js";
|
|
13
|
+
import { bold, dim, printError } from "./output.js";
|
|
14
|
+
import { loadReference } from "./reference.js";
|
|
15
|
+
import { VERSION } from "./version.js";
|
|
16
|
+
const HELP = `${bold("edena")}: Edena's command line, for people and for coding agents.
|
|
17
|
+
|
|
18
|
+
${bold("Usage")}
|
|
19
|
+
edena <category> <action> [arguments] [flags] every operation of the API
|
|
20
|
+
edena students list --status active
|
|
21
|
+
edena invoices get <id> --json
|
|
22
|
+
|
|
23
|
+
${bold("Find a command")}
|
|
24
|
+
edena docs search "<words>" the commands that match
|
|
25
|
+
edena categories every category
|
|
26
|
+
edena <category> its actions
|
|
27
|
+
edena <category> <action> --help what it takes and answers
|
|
28
|
+
edena docs show <category> <action> with its types
|
|
29
|
+
|
|
30
|
+
${bold("Session")}
|
|
31
|
+
edena login sign in from the browser (the sandbox, or real data)
|
|
32
|
+
edena whoami the organization and key in use
|
|
33
|
+
edena profiles / use <profile> switch organization
|
|
34
|
+
edena logout revoke this terminal's key
|
|
35
|
+
|
|
36
|
+
${bold("Build with the API")}
|
|
37
|
+
edena prompt <category> a prompt for a coding agent to implement it
|
|
38
|
+
edena types <category>... its TypeScript types
|
|
39
|
+
edena api <METHOD> </path> any request
|
|
40
|
+
|
|
41
|
+
${bold("Develop locally")}
|
|
42
|
+
edena listen --forward-to http://localhost:3000/webhooks
|
|
43
|
+
events as they happen, signed as webhooks are
|
|
44
|
+
edena trigger client.updated send one to that local server again
|
|
45
|
+
edena logs [--mine] the API's requests as they happen
|
|
46
|
+
edena open [section] the developer console in the browser
|
|
47
|
+
|
|
48
|
+
${bold("Coding agents")}
|
|
49
|
+
edena skill install teach Claude Code, Codex and Gemini CLI to use it
|
|
50
|
+
|
|
51
|
+
${bold("Flags")}
|
|
52
|
+
--json JSON output (the default when the output goes to another program)
|
|
53
|
+
--yes run a write without asking (agents need it; ask the person first)
|
|
54
|
+
--all every page of a list
|
|
55
|
+
--profile the organization to use (EDENA_PROFILE)
|
|
56
|
+
EDENA_API_KEY and EDENA_API_URL override the session and the API's address.
|
|
57
|
+
`;
|
|
58
|
+
async function main(argv) {
|
|
59
|
+
const args = parseArgs(argv);
|
|
60
|
+
const [command, sub] = args.positionals;
|
|
61
|
+
if (hasFlag(args, "version") || command === "version") {
|
|
62
|
+
process.stdout.write(`${VERSION}\n`);
|
|
63
|
+
return EXIT.ok;
|
|
64
|
+
}
|
|
65
|
+
if (!command || command === "help") {
|
|
66
|
+
process.stdout.write(HELP);
|
|
67
|
+
return EXIT.ok;
|
|
68
|
+
}
|
|
69
|
+
switch (command) {
|
|
70
|
+
case "login":
|
|
71
|
+
return login(args);
|
|
72
|
+
case "logout":
|
|
73
|
+
return logout(args);
|
|
74
|
+
case "whoami":
|
|
75
|
+
return whoami(args);
|
|
76
|
+
case "profiles":
|
|
77
|
+
return profiles(args);
|
|
78
|
+
case "use":
|
|
79
|
+
return use(args);
|
|
80
|
+
case "api":
|
|
81
|
+
return api(args);
|
|
82
|
+
case "listen":
|
|
83
|
+
return listen(args);
|
|
84
|
+
case "trigger":
|
|
85
|
+
return trigger(args);
|
|
86
|
+
case "logs":
|
|
87
|
+
return logs(args);
|
|
88
|
+
case "open":
|
|
89
|
+
return open(args);
|
|
90
|
+
case "skill":
|
|
91
|
+
if (sub === "install")
|
|
92
|
+
return skillInstall(args);
|
|
93
|
+
if (sub === "uninstall")
|
|
94
|
+
return skillUninstall(args);
|
|
95
|
+
if (sub === "show")
|
|
96
|
+
return skillShow();
|
|
97
|
+
throw new UsageError("Usage: edena skill install|uninstall|show [--agent claude|codex|gemini|all] [--project]");
|
|
98
|
+
}
|
|
99
|
+
if (command === "docs" && sub === "refresh")
|
|
100
|
+
return docsRefresh(args);
|
|
101
|
+
const session = await resolveSession(flag(args, "profile"));
|
|
102
|
+
const reference = await loadReference(session.apiUrl);
|
|
103
|
+
switch (command) {
|
|
104
|
+
case "docs":
|
|
105
|
+
if (sub === "search")
|
|
106
|
+
return docsSearch(reference, args);
|
|
107
|
+
if (sub === "show")
|
|
108
|
+
return docsShow(reference, args, session.apiUrl);
|
|
109
|
+
throw new UsageError('Usage: edena docs search "<words>" | docs show <category> <action> | docs refresh');
|
|
110
|
+
case "categories":
|
|
111
|
+
return categories(reference, args);
|
|
112
|
+
case "prompt":
|
|
113
|
+
return prompt(reference, args, session.apiUrl);
|
|
114
|
+
case "types":
|
|
115
|
+
return types(reference, args);
|
|
116
|
+
}
|
|
117
|
+
return runCommand(reference, args);
|
|
118
|
+
}
|
|
119
|
+
/** `edena <category> <action>`: one of the API's operations, from the reference. */
|
|
120
|
+
async function runCommand(reference, args) {
|
|
121
|
+
const [name, action] = args.positionals;
|
|
122
|
+
const group = reference.groups.get(name);
|
|
123
|
+
if (!group) {
|
|
124
|
+
const similar = [...reference.groups.keys()].filter((group) => distance(group, name) <= 2).map((group) => `edena ${group}`);
|
|
125
|
+
const close = similar.length > 0 ? similar : reference.search(name, 3).map((operation) => `edena ${operation.command}`);
|
|
126
|
+
throw new UsageError(`Unknown command “${name}”.`, close.length > 0 ? `Did you mean: ${close.join(", ")}?` : "Run edena categories, or edena docs search.");
|
|
127
|
+
}
|
|
128
|
+
if (!action) {
|
|
129
|
+
process.stdout.write(groupHelp(group));
|
|
130
|
+
return EXIT.ok;
|
|
131
|
+
}
|
|
132
|
+
const operation = reference.find(`${name} ${action}`);
|
|
133
|
+
if (!operation)
|
|
134
|
+
throw new UsageError(`“${name}” has no action “${action}”.`, `Its actions: ${group.operations.map((entry) => entry.action).join(", ")}.`);
|
|
135
|
+
if (hasFlag(args, "help")) {
|
|
136
|
+
process.stdout.write(operationHelp(reference, operation));
|
|
137
|
+
return EXIT.ok;
|
|
138
|
+
}
|
|
139
|
+
return runOperation(reference, operation, args);
|
|
140
|
+
}
|
|
141
|
+
/** Edits between two words, for “did you mean” on a mistyped category. */
|
|
142
|
+
function distance(a, b) {
|
|
143
|
+
const row = Array.from({ length: b.length + 1 }, (_, index) => index);
|
|
144
|
+
for (let i = 1; i <= a.length; i++) {
|
|
145
|
+
let previous = row[0];
|
|
146
|
+
row[0] = i;
|
|
147
|
+
for (let j = 1; j <= b.length; j++) {
|
|
148
|
+
const current = row[j];
|
|
149
|
+
row[j] = Math.min(current + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
150
|
+
previous = current;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return row[b.length];
|
|
154
|
+
}
|
|
155
|
+
main(process.argv.slice(2)).then((code) => {
|
|
156
|
+
process.exitCode = code;
|
|
157
|
+
}, (error) => {
|
|
158
|
+
const args = parseArgs(process.argv.slice(2));
|
|
159
|
+
printError(error, hasFlag(args, "json"));
|
|
160
|
+
const exitCode = error.exitCode;
|
|
161
|
+
process.exitCode = typeof exitCode === "number" ? exitCode : EXIT.failure;
|
|
162
|
+
if (process.env.EDENA_DEBUG && error instanceof Error)
|
|
163
|
+
process.stderr.write(`${dim(error.stack ?? "")}\n`);
|
|
164
|
+
});
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { createInterface } from "node:readline/promises";
|
|
3
|
+
import { flag, hasFlag } from "../args.js";
|
|
4
|
+
import { resolveSession } from "../config.js";
|
|
5
|
+
import { EXIT, NotSignedInError, UsageError } from "../errors.js";
|
|
6
|
+
import { apiRequest } from "../http.js";
|
|
7
|
+
import { printHuman, printJson, wantsJson } from "../output.js";
|
|
8
|
+
const METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
|
|
9
|
+
/**
|
|
10
|
+
* `edena api GET /clients --query status=active`: any request, for what a generated command does not
|
|
11
|
+
* cover the way you want. A write asks first, as any command does.
|
|
12
|
+
*/
|
|
13
|
+
export async function api(args) {
|
|
14
|
+
const [, rawMethod, path] = args.positionals;
|
|
15
|
+
const method = rawMethod?.toUpperCase();
|
|
16
|
+
if (!method || !METHODS.has(method) || !path?.startsWith("/")) {
|
|
17
|
+
throw new UsageError("Usage: edena api <METHOD> </path> [--query name=value]... [--data '<json>' | @file | -]");
|
|
18
|
+
}
|
|
19
|
+
const session = await resolveSession(flag(args, "profile"));
|
|
20
|
+
if (!session.apiKey)
|
|
21
|
+
throw new NotSignedInError();
|
|
22
|
+
if (method !== "GET" && !hasFlag(args, "yes")) {
|
|
23
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
24
|
+
throw new UsageError(`${method} ${path} changes data.`, "Run it again with --yes once it is confirmed.");
|
|
25
|
+
}
|
|
26
|
+
const readline = createInterface({ input: process.stdin, output: process.stdout });
|
|
27
|
+
const answer = await readline.question(`${method} ${path}. Go ahead? [y/N] `);
|
|
28
|
+
readline.close();
|
|
29
|
+
if (!/^y(es)?$/i.test(answer.trim())) {
|
|
30
|
+
process.stderr.write("Nothing was changed.\n");
|
|
31
|
+
return EXIT.ok;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const query = {};
|
|
35
|
+
for (const pair of args.flags.get("query") ?? []) {
|
|
36
|
+
const equals = pair.indexOf("=");
|
|
37
|
+
if (equals < 1)
|
|
38
|
+
throw new UsageError(`--query takes name=value, not “${pair}”.`);
|
|
39
|
+
const name = pair.slice(0, equals);
|
|
40
|
+
query[name] = [...(query[name] ?? []), pair.slice(equals + 1)];
|
|
41
|
+
}
|
|
42
|
+
const raw = flag(args, "data");
|
|
43
|
+
const body = raw === undefined ? undefined : JSON.parse(raw.startsWith("@") ? await readFile(raw.slice(1), "utf8") : raw);
|
|
44
|
+
const response = await apiRequest({ apiUrl: session.apiUrl, apiKey: session.apiKey, method: method, path, query, body });
|
|
45
|
+
if (response.kind === "json") {
|
|
46
|
+
if (wantsJson(hasFlag(args, "json")))
|
|
47
|
+
printJson(response.data);
|
|
48
|
+
else
|
|
49
|
+
printHuman(response.data);
|
|
50
|
+
}
|
|
51
|
+
else if (response.kind === "file") {
|
|
52
|
+
process.stdout.write(response.data);
|
|
53
|
+
}
|
|
54
|
+
return EXIT.ok;
|
|
55
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { hostname } from "node:os";
|
|
2
|
+
import { flag, hasFlag } from "../args.js";
|
|
3
|
+
import { DEFAULT_API_URL, readConfig, removeProfile, resolveSession, saveProfile, useProfile } from "../config.js";
|
|
4
|
+
import { ApiError, EXIT, NotSignedInError, UsageError } from "../errors.js";
|
|
5
|
+
import { apiRequest } from "../http.js";
|
|
6
|
+
import { bold, dim, printHuman, printJson, wantsJson } from "../output.js";
|
|
7
|
+
import { VERSION } from "../version.js";
|
|
8
|
+
import { openUrl } from "./open.js";
|
|
9
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
10
|
+
/**
|
|
11
|
+
* Signs in the way a TV signs in to a streaming service: the terminal asks the API for a sign-in, the
|
|
12
|
+
* person approves it in the console (choosing the sandbox or the real data, and the role), and the
|
|
13
|
+
* terminal receives an API key of its own. Nothing is copied by hand.
|
|
14
|
+
*/
|
|
15
|
+
export async function login(args) {
|
|
16
|
+
const apiUrl = (flag(args, "apiUrl") ?? process.env.EDENA_API_URL ?? DEFAULT_API_URL).replace(/\/$/, "");
|
|
17
|
+
const json = wantsJson(hasFlag(args, "json"));
|
|
18
|
+
const call = (path, body) => apiRequest({ apiUrl, apiKey: null, method: "POST", path, body }).then((response) => (response.kind === "json" ? response.data : null));
|
|
19
|
+
const started = await call("/cli/sessions", { client: hostname().slice(0, 60), platform: process.platform, version: VERSION });
|
|
20
|
+
if (!started)
|
|
21
|
+
throw new Error("The API did not start the sign-in.");
|
|
22
|
+
process.stderr.write(`\nOpen this page to sign in, and check that it shows the code ${bold(started.userCode)}:\n\n ${started.verificationUrl}\n\n`);
|
|
23
|
+
if (!hasFlag(args, "noBrowser") && process.stdout.isTTY)
|
|
24
|
+
openUrl(started.verificationUrl);
|
|
25
|
+
process.stderr.write(dim("Waiting for you to approve it in the console…\n"));
|
|
26
|
+
const deadline = Date.now() + started.expiresIn * 1000;
|
|
27
|
+
while (Date.now() < deadline) {
|
|
28
|
+
await sleep(started.interval * 1000);
|
|
29
|
+
let poll;
|
|
30
|
+
try {
|
|
31
|
+
poll = await call("/cli/sessions/token", { deviceCode: started.deviceCode });
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
if (error instanceof ApiError && error.key === "cli.session_denied") {
|
|
35
|
+
process.stderr.write("The sign-in was denied in the console.\n");
|
|
36
|
+
return EXIT.auth;
|
|
37
|
+
}
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
if (!poll || poll.status === "pending")
|
|
41
|
+
continue;
|
|
42
|
+
const profile = { apiUrl, organization: poll.organization, key: poll.key };
|
|
43
|
+
await saveProfile(poll.organization.slug, profile, poll.apiKey);
|
|
44
|
+
if (json)
|
|
45
|
+
printJson({ signedIn: true, profile: poll.organization.slug, ...profile });
|
|
46
|
+
else
|
|
47
|
+
process.stdout.write(`Signed in to ${bold(poll.organization.name)} (${poll.organization.environment}) with the key “${poll.key.name}”.\n` +
|
|
48
|
+
dim(`Commands now run there. Try: edena students list\n`));
|
|
49
|
+
return EXIT.ok;
|
|
50
|
+
}
|
|
51
|
+
process.stderr.write("The sign-in ran out. Run edena login again.\n");
|
|
52
|
+
return EXIT.auth;
|
|
53
|
+
}
|
|
54
|
+
/** Revokes the key this terminal holds and forgets it: signing out for good, not just locally. */
|
|
55
|
+
export async function logout(args) {
|
|
56
|
+
const session = await resolveSession(flag(args, "profile"));
|
|
57
|
+
if (!session.profileName || !session.apiKey)
|
|
58
|
+
throw new NotSignedInError("Run edena login.");
|
|
59
|
+
try {
|
|
60
|
+
await apiRequest({ apiUrl: session.apiUrl, apiKey: session.apiKey, method: "POST", path: "/cli/logout" });
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
// A key revoked already, from the console: there is nothing left to revoke, only to forget.
|
|
64
|
+
if (!(error instanceof ApiError && error.status === 401))
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
await removeProfile(session.profileName);
|
|
68
|
+
process.stdout.write(`Signed out of ${session.profile?.organization.name ?? session.profileName}; its key is revoked.\n`);
|
|
69
|
+
return EXIT.ok;
|
|
70
|
+
}
|
|
71
|
+
/** Who the CLI is signed in as, from the API itself. */
|
|
72
|
+
export async function whoami(args) {
|
|
73
|
+
const session = await resolveSession(flag(args, "profile"));
|
|
74
|
+
if (!session.apiKey)
|
|
75
|
+
throw new NotSignedInError();
|
|
76
|
+
const response = await apiRequest({ apiUrl: session.apiUrl, apiKey: session.apiKey, method: "GET", path: "/cli/whoami" });
|
|
77
|
+
const data = response.kind === "json" ? response.data : null;
|
|
78
|
+
if (wantsJson(hasFlag(args, "json")))
|
|
79
|
+
printJson({ profile: session.profileName, apiUrl: session.apiUrl, ...data });
|
|
80
|
+
else
|
|
81
|
+
printHuman(data);
|
|
82
|
+
return EXIT.ok;
|
|
83
|
+
}
|
|
84
|
+
/** The organizations this terminal is signed in to, the current one marked. */
|
|
85
|
+
export async function profiles(args) {
|
|
86
|
+
const config = await readConfig();
|
|
87
|
+
const list = Object.entries(config.profiles).map(([name, profile]) => ({
|
|
88
|
+
profile: name,
|
|
89
|
+
current: name === config.current,
|
|
90
|
+
organization: profile.organization.name,
|
|
91
|
+
environment: profile.organization.environment,
|
|
92
|
+
key: profile.key.name,
|
|
93
|
+
apiUrl: profile.apiUrl,
|
|
94
|
+
}));
|
|
95
|
+
if (wantsJson(hasFlag(args, "json")))
|
|
96
|
+
printJson(list);
|
|
97
|
+
else if (list.length === 0)
|
|
98
|
+
process.stdout.write("Not signed in anywhere. Run edena login.\n");
|
|
99
|
+
else
|
|
100
|
+
for (const entry of list)
|
|
101
|
+
process.stdout.write(`${entry.current ? "*" : " "} ${bold(entry.profile)} ${entry.organization} (${entry.environment}) ${dim(entry.key)}\n`);
|
|
102
|
+
return EXIT.ok;
|
|
103
|
+
}
|
|
104
|
+
/** Makes another signed-in organization the one commands run in. */
|
|
105
|
+
export async function use(args) {
|
|
106
|
+
const name = args.positionals[1];
|
|
107
|
+
const config = await readConfig();
|
|
108
|
+
if (!name || !config.profiles[name]) {
|
|
109
|
+
throw new UsageError(name ? `Not signed in to “${name}”.` : "Which profile?", `Profiles: ${Object.keys(config.profiles).join(", ") || "none"}. Run edena profiles.`);
|
|
110
|
+
}
|
|
111
|
+
await useProfile(name);
|
|
112
|
+
const profile = config.profiles[name];
|
|
113
|
+
process.stdout.write(`Commands now run in ${profile?.organization.name} (${profile?.organization.environment}).\n`);
|
|
114
|
+
return EXIT.ok;
|
|
115
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { flag, hasFlag } from "../args.js";
|
|
2
|
+
import { resolveSession } from "../config.js";
|
|
3
|
+
import { EXIT, UsageError } from "../errors.js";
|
|
4
|
+
import { bold, dim, printJson, wantsJson } from "../output.js";
|
|
5
|
+
import { loadReference } from "../reference.js";
|
|
6
|
+
import { TypeCollector, categoryPrompt, operationMarkdown } from "../schema.js";
|
|
7
|
+
/** `edena docs search "unpaid invoices"`: the commands that match, best first. */
|
|
8
|
+
export function docsSearch(reference, args) {
|
|
9
|
+
const query = args.positionals.slice(2).join(" ");
|
|
10
|
+
if (!query)
|
|
11
|
+
throw new UsageError("What should it look for?", 'Usage: edena docs search "<words>"');
|
|
12
|
+
const results = reference.search(query, Number(flag(args, "limit") ?? 20));
|
|
13
|
+
if (wantsJson(hasFlag(args, "json"))) {
|
|
14
|
+
printJson(results.map((operation) => ({ command: `edena ${operation.command}`, method: operation.method, path: operation.path, summary: operation.summary, category: operation.category, operationId: operation.id })));
|
|
15
|
+
return EXIT.ok;
|
|
16
|
+
}
|
|
17
|
+
if (results.length === 0) {
|
|
18
|
+
process.stdout.write(`Nothing matches “${query}”. Try other words, or edena categories.\n`);
|
|
19
|
+
return EXIT.notFound;
|
|
20
|
+
}
|
|
21
|
+
const width = Math.max(...results.map((operation) => operation.command.length));
|
|
22
|
+
for (const operation of results)
|
|
23
|
+
process.stdout.write(`${bold(operation.command.padEnd(width))} ${operation.summary}\n${" ".repeat(width + 2)}${dim(`${operation.method} ${operation.path}`)}\n`);
|
|
24
|
+
return EXIT.ok;
|
|
25
|
+
}
|
|
26
|
+
/** `edena docs show students list`: everything about one operation, its types included. */
|
|
27
|
+
export function docsShow(reference, args, apiUrl) {
|
|
28
|
+
const name = args.positionals.slice(2).join(" ");
|
|
29
|
+
const operation = reference.find(name);
|
|
30
|
+
if (!operation)
|
|
31
|
+
throw new UsageError(`No operation “${name}”.`, `Find it with edena docs search "${name}".`);
|
|
32
|
+
const types = new TypeCollector(reference.document);
|
|
33
|
+
const section = operationMarkdown(operation, types);
|
|
34
|
+
if (reference.document.components?.schemas?.ErrorResponse)
|
|
35
|
+
types.add("ErrorResponse");
|
|
36
|
+
const { blocks } = types.render();
|
|
37
|
+
if (wantsJson(hasFlag(args, "json"))) {
|
|
38
|
+
printJson({ command: `edena ${operation.command}`, operationId: operation.id, method: operation.method, path: operation.path, url: `${apiUrl}${operation.path}`, summary: operation.summary, category: operation.category, markdown: section.join("\n"), types: blocks.join("\n\n") });
|
|
39
|
+
return EXIT.ok;
|
|
40
|
+
}
|
|
41
|
+
process.stdout.write(`${section.join("\n")}\n\`\`\`ts\n${blocks.join("\n\n")}\n\`\`\`\n`);
|
|
42
|
+
return EXIT.ok;
|
|
43
|
+
}
|
|
44
|
+
/** `edena categories`: every category of the API, as the first word of its commands. */
|
|
45
|
+
export function categories(reference, args) {
|
|
46
|
+
const groups = [...reference.groups.values()].sort((a, b) => a.name.localeCompare(b.name));
|
|
47
|
+
if (wantsJson(hasFlag(args, "json"))) {
|
|
48
|
+
printJson(groups.map((group) => ({ command: `edena ${group.name}`, category: group.category, description: group.description, operations: group.operations.length })));
|
|
49
|
+
return EXIT.ok;
|
|
50
|
+
}
|
|
51
|
+
const width = Math.max(...groups.map((group) => group.name.length));
|
|
52
|
+
for (const group of groups)
|
|
53
|
+
process.stdout.write(`${bold(group.name.padEnd(width))} ${group.description}\n`);
|
|
54
|
+
process.stdout.write(dim(`\n${groups.length} categories. Run edena <category> for its actions.\n`));
|
|
55
|
+
return EXIT.ok;
|
|
56
|
+
}
|
|
57
|
+
/** `edena prompt invoices`: a prompt for a coding agent to implement the whole category. */
|
|
58
|
+
export function prompt(reference, args, apiUrl) {
|
|
59
|
+
const name = args.positionals[1];
|
|
60
|
+
const group = name ? reference.groups.get(name) : undefined;
|
|
61
|
+
if (!group)
|
|
62
|
+
throw new UsageError(name ? `No category “${name}”.` : "Which category?", "Usage: edena prompt <category>. See edena categories.");
|
|
63
|
+
process.stdout.write(categoryPrompt(reference.document, group, apiUrl));
|
|
64
|
+
return EXIT.ok;
|
|
65
|
+
}
|
|
66
|
+
/** `edena types invoices students`: the TypeScript types those categories use, ready to save in a project. */
|
|
67
|
+
export function types(reference, args) {
|
|
68
|
+
const names = args.positionals.slice(1);
|
|
69
|
+
if (names.length === 0 && !hasFlag(args, "all"))
|
|
70
|
+
throw new UsageError("Which categories?", "Usage: edena types <category>... or edena types --all");
|
|
71
|
+
const groups = names.length > 0 ? names.map((name) => reference.groups.get(name) ?? fail(name)) : [...reference.groups.values()];
|
|
72
|
+
const collector = new TypeCollector(reference.document, true);
|
|
73
|
+
for (const group of groups) {
|
|
74
|
+
for (const operation of group.operations)
|
|
75
|
+
operationMarkdown(operation, collector);
|
|
76
|
+
}
|
|
77
|
+
if (reference.document.components?.schemas?.ErrorResponse)
|
|
78
|
+
collector.add("ErrorResponse");
|
|
79
|
+
const { blocks } = collector.render();
|
|
80
|
+
process.stdout.write(`// Edena API types for ${groups.map((group) => group.name).join(", ")}. Generated by edena types.\n\n${blocks.join("\n\n")}\n`);
|
|
81
|
+
return EXIT.ok;
|
|
82
|
+
}
|
|
83
|
+
function fail(name) {
|
|
84
|
+
throw new UsageError(`No category “${name}”.`, "See edena categories.");
|
|
85
|
+
}
|
|
86
|
+
/** `edena docs refresh`: fetches the reference again, now. */
|
|
87
|
+
export async function docsRefresh(args) {
|
|
88
|
+
const session = await resolveSession(flag(args, "profile"));
|
|
89
|
+
const reference = await loadReference(session.apiUrl, { refresh: true });
|
|
90
|
+
process.stdout.write(`The reference is up to date: ${reference.operations.length} operations in ${reference.groups.size} categories.\n`);
|
|
91
|
+
return EXIT.ok;
|
|
92
|
+
}
|