evalctl 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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +149 -2
  3. package/dist/cli.d.ts +13 -0
  4. package/dist/cli.js +294 -0
  5. package/dist/client.d.ts +53 -0
  6. package/dist/client.js +269 -0
  7. package/dist/commands/auth.d.ts +6 -0
  8. package/dist/commands/auth.js +341 -0
  9. package/dist/commands/common.d.ts +17 -0
  10. package/dist/commands/common.js +53 -0
  11. package/dist/commands/export.d.ts +2 -0
  12. package/dist/commands/export.js +54 -0
  13. package/dist/commands/index.d.ts +3 -0
  14. package/dist/commands/index.js +10 -0
  15. package/dist/commands/info.d.ts +2 -0
  16. package/dist/commands/info.js +208 -0
  17. package/dist/commands/runs.d.ts +2 -0
  18. package/dist/commands/runs.js +325 -0
  19. package/dist/commands/scenarios.d.ts +2 -0
  20. package/dist/commands/scenarios.js +585 -0
  21. package/dist/commands/screens.d.ts +2 -0
  22. package/dist/commands/screens.js +139 -0
  23. package/dist/config.d.ts +52 -0
  24. package/dist/config.js +281 -0
  25. package/dist/context.d.ts +64 -0
  26. package/dist/context.js +1 -0
  27. package/dist/diff.d.ts +7 -0
  28. package/dist/diff.js +122 -0
  29. package/dist/errors.d.ts +22 -0
  30. package/dist/errors.js +35 -0
  31. package/dist/fsutil.d.ts +34 -0
  32. package/dist/fsutil.js +245 -0
  33. package/dist/index.d.ts +2 -0
  34. package/dist/index.js +18 -0
  35. package/dist/output.d.ts +38 -0
  36. package/dist/output.js +156 -0
  37. package/dist/prompt.d.ts +29 -0
  38. package/dist/prompt.js +195 -0
  39. package/dist/sidecar.d.ts +39 -0
  40. package/dist/sidecar.js +138 -0
  41. package/dist/state.d.ts +14 -0
  42. package/dist/state.js +48 -0
  43. package/dist/util.d.ts +21 -0
  44. package/dist/util.js +77 -0
  45. package/dist/version.d.ts +2 -0
  46. package/dist/version.js +12 -0
  47. package/dist/yaml-text.d.ts +15 -0
  48. package/dist/yaml-text.js +103 -0
  49. package/package.json +62 -4
@@ -0,0 +1,139 @@
1
+ import { basename, resolve } from "node:path";
2
+ import { CliError, EXIT_OK, EXIT_VALIDATION } from "../errors.js";
3
+ import { readUtf8File } from "../fsutil.js";
4
+ import { displayText, emitJson, errOut, formatTable, out, outRaw, printValidationIssues } from "../output.js";
5
+ import { asArray, isObject, stringList } from "../util.js";
6
+ import { authoringBody, confirmAction, isScreenName, MAX_SCREEN_BYTES, yes } from "./common.js";
7
+ const SCREENS = "/api/screens";
8
+ const SCREEN_MAX_CHARS = 60_000;
9
+ function screenName(value) {
10
+ if (!isScreenName(value)) {
11
+ throw new CliError(`Invalid screen filename ${JSON.stringify(value)}. Use 1–64 lowercase letters, digits or hyphens followed by .txt.`, {
12
+ exitCode: EXIT_VALIDATION,
13
+ });
14
+ }
15
+ return value;
16
+ }
17
+ function screenPath(name) {
18
+ return `${SCREENS}/${encodeURIComponent(name)}`;
19
+ }
20
+ async function list(ctx) {
21
+ const { body } = await ctx.client().request("GET", SCREENS);
22
+ if (ctx.global.json) {
23
+ emitJson(body);
24
+ }
25
+ else {
26
+ const rows = asArray(body["screens"]).filter(isObject).map((screen) => [
27
+ screen["name"], screen["origin"], screen["current_rev"], screen["size_bytes"],
28
+ stringList(screen["used_by"]).join(","), displayText(screen["sha256"]).slice(0, 12),
29
+ ]);
30
+ out(rows.length === 0 ? "No screens found." : formatTable(["NAME", "ORIGIN", "REV", "BYTES", "USED_BY", "SHA256"], rows));
31
+ }
32
+ return EXIT_OK;
33
+ }
34
+ async function show(ctx) {
35
+ const name = screenName(ctx.positionals[0]);
36
+ const { body } = await ctx.client().request("GET", screenPath(name));
37
+ if (ctx.global.json) {
38
+ emitJson(body);
39
+ }
40
+ else {
41
+ const usedBy = stringList(body["used_by"]);
42
+ const content = body["content"];
43
+ if (typeof content !== "string") {
44
+ throw new CliError(`The server response is missing content for screen '${name}'.`);
45
+ }
46
+ out(`Screen ${name} (${displayText(body["origin"])}, ${displayText(body["size_bytes"])} bytes, sha256=${displayText(body["sha256"])})`);
47
+ if (usedBy.length > 0) {
48
+ out(`Used by ${displayText(usedBy.join(", "))}`);
49
+ }
50
+ printValidationIssues(body);
51
+ out();
52
+ outRaw(content.endsWith("\n") ? content : content + "\n");
53
+ }
54
+ return EXIT_OK;
55
+ }
56
+ async function upload(ctx) {
57
+ const path = resolve(ctx.io.cwd, ctx.positionals[0] ?? "");
58
+ // The server's rule is about the screen's name, not the local file's: `--name notes.txt /tmp/capture.log` is fine.
59
+ const name = screenName(ctx.opt("name") ?? basename(path));
60
+ const content = readUtf8File(path, MAX_SCREEN_BYTES);
61
+ if (content.trim() === "" || Array.from(content).length > SCREEN_MAX_CHARS) {
62
+ throw new CliError(`A screen must contain text and be at most ${SCREEN_MAX_CHARS} characters.`, { exitCode: EXIT_VALIDATION });
63
+ }
64
+ // eslint-disable-next-line no-control-regex -- permit only the layout controls accepted by the server
65
+ if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/.test(content)) {
66
+ throw new CliError("The screen contains disallowed control characters.", { exitCode: EXIT_VALIDATION });
67
+ }
68
+ if (ctx.global.dryRun) {
69
+ const size = Buffer.byteLength(content, "utf8");
70
+ if (ctx.global.json) {
71
+ emitJson({ dry_run: true, name, size_bytes: size });
72
+ }
73
+ else {
74
+ out(`Dry run: would upload screen '${name}' (${size} bytes).`);
75
+ }
76
+ return EXIT_OK;
77
+ }
78
+ const { status, body } = await ctx.client().request("PUT", screenPath(name), {
79
+ jsonBody: authoringBody({ content }), allowStatuses: [422],
80
+ });
81
+ if (ctx.global.json) {
82
+ emitJson(body);
83
+ }
84
+ else {
85
+ printValidationIssues(body);
86
+ if (status === 422) {
87
+ if (body["message"]) {
88
+ errOut(displayText(body["message"]));
89
+ }
90
+ }
91
+ else {
92
+ const sha = displayText(body["sha256"]).slice(0, 12);
93
+ out(`Uploaded ${name} (rev ${displayText(body["current_rev"])}, ${displayText(body["size_bytes"])} bytes, sha256=${sha})`);
94
+ }
95
+ }
96
+ return status === 422 ? EXIT_VALIDATION : EXIT_OK;
97
+ }
98
+ async function remove(ctx) {
99
+ const name = screenName(ctx.positionals[0]);
100
+ if (ctx.global.dryRun) {
101
+ if (ctx.global.json) {
102
+ emitJson({ dry_run: true, name });
103
+ }
104
+ else {
105
+ out(`Dry run: would delete screen '${name}'.`);
106
+ }
107
+ return EXIT_OK;
108
+ }
109
+ await confirmAction(ctx, `Delete server screen '${name}'? [y/N]: `, `Aborted delete for screen ${name}.`);
110
+ const { body } = await ctx.client().request("DELETE", screenPath(name));
111
+ if (ctx.global.json) {
112
+ emitJson(body);
113
+ }
114
+ else {
115
+ out(`Deleted screen ${displayText(body["deleted"])}.`);
116
+ }
117
+ return EXIT_OK;
118
+ }
119
+ export const screenCommands = {
120
+ name: "screen",
121
+ summary: "Manage screen captures",
122
+ usage: "screen <list|show|upload|delete>",
123
+ subcommands: [
124
+ { name: "list", summary: "List Git and server screens", usage: "screen list", handler: list },
125
+ { name: "show", summary: "Show a screen's content", usage: "screen show <name>", positionals: { min: 1, max: 1 }, handler: show },
126
+ {
127
+ name: "upload",
128
+ summary: "Upload or update a server screen",
129
+ usage: "screen upload [--name NAME] <file>",
130
+ positionals: { min: 1, max: 1 },
131
+ options: { name: { type: "string", placeholder: "NAME", description: "Target screen file name" } },
132
+ handler: upload,
133
+ },
134
+ {
135
+ name: "delete", summary: "Delete an unused server screen", usage: "screen delete [--yes] <name>",
136
+ positionals: { min: 1, max: 1 }, options: { yes }, handler: remove,
137
+ },
138
+ ],
139
+ };
@@ -0,0 +1,52 @@
1
+ import { type JsonObject } from "./util.js";
2
+ export declare const ENV_SERVER = "EVALCTL_SERVER";
3
+ export declare const ENV_TOKEN = "EVALCTL_TOKEN";
4
+ export declare const ENV_CONFIG = "EVALCTL_CONFIG";
5
+ export declare const LOOPBACK_HOSTS: ReadonlySet<string>;
6
+ /** Config keys that belong to one login; they are dropped together on logout. */
7
+ export declare const TOKEN_CONFIG_KEYS: readonly ["token", "token_id", "scope", "abs_expires", "idle_seconds"];
8
+ export type ServerOrigin = readonly [scheme: string, host: string, port: number];
9
+ /**
10
+ * Validates and normalizes a server base URL: http(s) only, no credentials, query or fragment.
11
+ * A deliberate base path survives (`https://eval.example.com/sub/` becomes `https://eval.example.com/sub`); the trailing slash does not.
12
+ */
13
+ export declare function normalizeServerUrl(raw: string | null | undefined): string;
14
+ /** `[scheme, hostname, port]` with the default port filled in, for exact origin comparison; null when not an http(s) URL. */
15
+ export declare function serverOrigin(url: string): ServerOrigin | null;
16
+ export declare function sameServerOrigin(a: string, b: string): boolean;
17
+ /** True for plain `http:` to anything but loopback: credentials and tokens would cross the network in cleartext. */
18
+ export declare function isNonLoopbackHttp(url: string): boolean;
19
+ export interface PathContext {
20
+ env?: NodeJS.ProcessEnv;
21
+ platform?: NodeJS.Platform;
22
+ home?: string;
23
+ }
24
+ /** `--config`, then `EVALCTL_CONFIG`, then `$XDG_CONFIG_HOME/evalctl/config.json` (`%APPDATA%` on Windows). */
25
+ export declare function resolveConfigPath(cliConfig?: string | null, context?: PathContext): string;
26
+ /** Reads the config file; a missing file is an empty config, a symbolic link or a non-object is refused. */
27
+ export declare function loadConfig(path: string): JsonObject;
28
+ /** Writes the config atomically with mode 0600 in a 0700 directory. A password is never stored, whatever is passed in. */
29
+ export declare function saveConfig(path: string, data: Readonly<JsonObject>): void;
30
+ /** The config minus the keys of one login. */
31
+ export declare function withoutTokenFields(cfg: Readonly<JsonObject>): {
32
+ config: JsonObject;
33
+ removed: boolean;
34
+ };
35
+ export interface ConfigFileCheck {
36
+ exists: boolean;
37
+ ok: boolean;
38
+ detail: string;
39
+ /** Why it is not ok: `permissions` can be fixed with chmod, `unsafe` (a link, a directory, an unreadable path) cannot. */
40
+ problem?: "permissions" | "unsafe";
41
+ }
42
+ /** Looks at the config file's type and permissions without reading it. */
43
+ export declare function inspectConfigFile(path: string, platform?: NodeJS.Platform): ConfigFileCheck;
44
+ /** A sentence to show when the config file deserves attention, or null when there is nothing to say. */
45
+ export declare function configPermWarning(path: string, platform?: NodeJS.Platform): string | null;
46
+ /** `--server`, then `EVALCTL_SERVER`, then the saved server, normalized. */
47
+ export declare function resolveServer(flagServer: string | undefined, cfg: Readonly<JsonObject>, env?: NodeJS.ProcessEnv): string;
48
+ /**
49
+ * The Bearer token for `serverUrl`. `EVALCTL_TOKEN` wins when it is set, since the person chose it for this run.
50
+ * A saved token is only ever used for the origin it was issued by, so a `--server` override never leaks it elsewhere.
51
+ */
52
+ export declare function resolveToken(cfg: Readonly<JsonObject>, serverUrl: string, env?: NodeJS.ProcessEnv): string | null;
package/dist/config.js ADDED
@@ -0,0 +1,281 @@
1
+ import { closeSync, constants, fstatSync, openSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { CliError, EXIT_AUTH, EXIT_RUNTIME, EXIT_VALIDATION } from "./errors.js";
5
+ import { tryLstat, writeFileAtomic } from "./fsutil.js";
6
+ import { errorMessage, isObject, nonEmptyString } from "./util.js";
7
+ export const ENV_SERVER = "EVALCTL_SERVER";
8
+ export const ENV_TOKEN = "EVALCTL_TOKEN";
9
+ export const ENV_CONFIG = "EVALCTL_CONFIG";
10
+ export const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1"]);
11
+ /** Config keys that belong to one login; they are dropped together on logout. */
12
+ export const TOKEN_CONFIG_KEYS = ["token", "token_id", "scope", "abs_expires", "idle_seconds"];
13
+ /**
14
+ * Hides credentials a person may have typed into a URL before the URL is echoed in a message: in each word, everything
15
+ * in front of its last `@` goes (after a scheme, extra slashes or white space), whether or not a scheme was typed
16
+ * (`user:secret@host`, `https:///user:secret@host`). A path that happens to hold an `@` is hidden too, which is the safe side.
17
+ */
18
+ function redactUrl(raw) {
19
+ return raw.replace(/(^|[a-z][a-z0-9+.-]*:\/\/+|\/+|\s)[^\s?#]*@/gi, "$1***@");
20
+ }
21
+ /**
22
+ * Validates and normalizes a server base URL: http(s) only, no credentials, query or fragment.
23
+ * A deliberate base path survives (`https://eval.example.com/sub/` becomes `https://eval.example.com/sub`); the trailing slash does not.
24
+ */
25
+ export function normalizeServerUrl(raw) {
26
+ const text = typeof raw === "string" ? raw.trim() : "";
27
+ if (text === "") {
28
+ throw new CliError(`Server URL is not configured. Pass --server URL, set ${ENV_SERVER}, or run 'login'.`, {
29
+ exitCode: EXIT_AUTH,
30
+ });
31
+ }
32
+ const authority = /^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)/i.exec(text)?.[1] ?? "";
33
+ if (authority.includes("@") || /[?#]/.test(text)) {
34
+ throw new CliError("Server URL must not contain credentials, query parameters, or fragments", {
35
+ exitCode: EXIT_VALIDATION,
36
+ });
37
+ }
38
+ // The URL parser forgives `https:///host` and `http:host`; a typo in a server address should not be forgiven.
39
+ if (!/^https?:\/\/[^/?#]/i.test(text)) {
40
+ throw new CliError(`Invalid server URL ${JSON.stringify(redactUrl(text))}; expected http(s)://host[:port]`, {
41
+ exitCode: EXIT_VALIDATION,
42
+ });
43
+ }
44
+ let url;
45
+ try {
46
+ url = new URL(text);
47
+ }
48
+ catch {
49
+ throw new CliError(`Invalid server URL ${JSON.stringify(redactUrl(text))}; expected http(s)://host[:port]`, {
50
+ exitCode: EXIT_VALIDATION,
51
+ });
52
+ }
53
+ if ((url.protocol !== "http:" && url.protocol !== "https:") || url.hostname === "") {
54
+ throw new CliError(`Invalid server URL ${JSON.stringify(redactUrl(text))}; expected http(s)://host[:port]`, {
55
+ exitCode: EXIT_VALIDATION,
56
+ });
57
+ }
58
+ // The URL parser accepts `:0`, which nothing can listen on.
59
+ if (url.port !== "" && (Number(url.port) < 1 || Number(url.port) > 65535)) {
60
+ throw new CliError(`Invalid server URL ${JSON.stringify(redactUrl(text))}; the port must be between 1 and 65535`, {
61
+ exitCode: EXIT_VALIDATION,
62
+ });
63
+ }
64
+ const path = url.pathname.replace(/\/+$/, "");
65
+ return `${url.protocol}//${url.host}${path}`;
66
+ }
67
+ /** `[scheme, hostname, port]` with the default port filled in, for exact origin comparison; null when not an http(s) URL. */
68
+ export function serverOrigin(url) {
69
+ let parsed;
70
+ try {
71
+ parsed = new URL(url);
72
+ }
73
+ catch {
74
+ return null;
75
+ }
76
+ const scheme = parsed.protocol.replace(/:$/, "");
77
+ if ((scheme !== "http" && scheme !== "https") || parsed.hostname === "") {
78
+ return null;
79
+ }
80
+ const port = parsed.port === "" ? (scheme === "https" ? 443 : 80) : Number(parsed.port);
81
+ return [scheme, parsed.hostname.toLowerCase(), port];
82
+ }
83
+ export function sameServerOrigin(a, b) {
84
+ const left = serverOrigin(a);
85
+ const right = serverOrigin(b);
86
+ return left !== null && right !== null && left.every((part, index) => part === right[index]);
87
+ }
88
+ /** True for plain `http:` to anything but loopback: credentials and tokens would cross the network in cleartext. */
89
+ export function isNonLoopbackHttp(url) {
90
+ let parsed;
91
+ try {
92
+ parsed = new URL(url);
93
+ }
94
+ catch {
95
+ return false;
96
+ }
97
+ const host = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, "");
98
+ return parsed.protocol === "http:" && !LOOPBACK_HOSTS.has(host);
99
+ }
100
+ function expandHome(path, home) {
101
+ if (path === "~") {
102
+ return home;
103
+ }
104
+ return path.startsWith("~/") || path.startsWith("~\\") ? join(home, path.slice(2)) : path;
105
+ }
106
+ /** `--config`, then `EVALCTL_CONFIG`, then `$XDG_CONFIG_HOME/evalctl/config.json` (`%APPDATA%` on Windows). */
107
+ export function resolveConfigPath(cliConfig, context = {}) {
108
+ const env = context.env ?? process.env;
109
+ const platform = context.platform ?? process.platform;
110
+ const home = context.home ?? homedir();
111
+ if (cliConfig !== undefined && cliConfig !== null && cliConfig !== "") {
112
+ return expandHome(cliConfig, home);
113
+ }
114
+ const fromEnv = nonEmptyString(env[ENV_CONFIG]);
115
+ if (fromEnv !== undefined) {
116
+ return expandHome(fromEnv, home);
117
+ }
118
+ const base = platform === "win32"
119
+ ? (nonEmptyString(env["APPDATA"]) ?? join(home, ".config"))
120
+ : (nonEmptyString(env["XDG_CONFIG_HOME"]) ?? join(home, ".config"));
121
+ return join(base, "evalctl", "config.json");
122
+ }
123
+ /** The directory holding the config file must be a real directory: through a link, a token could be read from or written to anywhere. */
124
+ function refuseLinkedDirectory(path, action) {
125
+ const dir = dirname(path);
126
+ if (tryLstat(dir)?.isSymbolicLink() === true) {
127
+ throw new CliError(`Refusing to ${action} the config file through a symbolic link: ${dir}`, { exitCode: EXIT_RUNTIME });
128
+ }
129
+ }
130
+ /** Reads the config file; a missing file is an empty config, a symbolic link or a non-object is refused. */
131
+ export function loadConfig(path) {
132
+ let stats;
133
+ try {
134
+ refuseLinkedDirectory(path, "read");
135
+ stats = tryLstat(path);
136
+ }
137
+ catch (err) {
138
+ if (err instanceof CliError) {
139
+ throw err;
140
+ }
141
+ throw new CliError(`Could not read config file ${path}: ${errorMessage(err)}`, { exitCode: EXIT_RUNTIME });
142
+ }
143
+ if (stats === undefined) {
144
+ return {};
145
+ }
146
+ if (stats.isSymbolicLink()) {
147
+ throw new CliError(`Refusing to read config file through a symbolic link: ${path}`, { exitCode: EXIT_RUNTIME });
148
+ }
149
+ if (!stats.isFile()) {
150
+ throw new CliError(`Config path ${path} is not a regular file`, { exitCode: EXIT_RUNTIME });
151
+ }
152
+ let data;
153
+ try {
154
+ // Opened without following a link and judged by what was actually opened, so a swap after the checks above changes nothing.
155
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
156
+ try {
157
+ if (!fstatSync(fd).isFile()) {
158
+ throw new CliError(`Config path ${path} is not a regular file`, { exitCode: EXIT_RUNTIME });
159
+ }
160
+ const raw = readFileSync(fd, "utf8").replace(/^\uFEFF/, "");
161
+ data = raw.trim() === "" ? {} : JSON.parse(raw);
162
+ }
163
+ finally {
164
+ closeSync(fd);
165
+ }
166
+ }
167
+ catch (err) {
168
+ if (err instanceof CliError) {
169
+ throw err;
170
+ }
171
+ throw new CliError(`Could not read config file ${path}: ${errorMessage(err)}`, { exitCode: EXIT_RUNTIME });
172
+ }
173
+ if (!isObject(data)) {
174
+ throw new CliError(`Config file ${path} must hold a JSON object`, { exitCode: EXIT_RUNTIME });
175
+ }
176
+ return data;
177
+ }
178
+ /** Writes the config atomically with mode 0600 in a 0700 directory. A password is never stored, whatever is passed in. */
179
+ export function saveConfig(path, data) {
180
+ const clean = {};
181
+ for (const [key, value] of Object.entries(data)) {
182
+ if (key !== "password") {
183
+ clean[key] = value;
184
+ }
185
+ }
186
+ try {
187
+ refuseLinkedDirectory(path, "write");
188
+ }
189
+ catch (err) {
190
+ if (err instanceof CliError) {
191
+ throw err;
192
+ }
193
+ throw new CliError(`Could not save config file ${path}: ${errorMessage(err)}`, { exitCode: EXIT_RUNTIME });
194
+ }
195
+ writeFileAtomic(path, `${JSON.stringify(clean, null, 2)}\n`, {
196
+ fileMode: 0o600,
197
+ dirMode: 0o700,
198
+ refuseSymlink: true,
199
+ label: "config file",
200
+ });
201
+ }
202
+ /** The config minus the keys of one login. */
203
+ export function withoutTokenFields(cfg) {
204
+ const config = { ...cfg };
205
+ let removed = false;
206
+ for (const key of TOKEN_CONFIG_KEYS) {
207
+ if (key in config) {
208
+ removed = true;
209
+ }
210
+ delete config[key];
211
+ }
212
+ return { config, removed };
213
+ }
214
+ /** Looks at the config file's type and permissions without reading it. */
215
+ export function inspectConfigFile(path, platform = process.platform) {
216
+ let stats;
217
+ try {
218
+ const dir = dirname(path);
219
+ if (tryLstat(dir)?.isSymbolicLink() === true) {
220
+ return { exists: true, ok: false, problem: "unsafe", detail: `${dir} is a symbolic link; evalctl refuses to use it` };
221
+ }
222
+ stats = tryLstat(path);
223
+ }
224
+ catch (err) {
225
+ return { exists: true, ok: false, problem: "unsafe", detail: `Could not inspect ${path}: ${errorMessage(err)}` };
226
+ }
227
+ if (stats === undefined) {
228
+ return { exists: false, ok: true, detail: `No config file at ${path}` };
229
+ }
230
+ if (stats.isSymbolicLink()) {
231
+ return { exists: true, ok: false, problem: "unsafe", detail: `${path} is a symbolic link; evalctl refuses to use it` };
232
+ }
233
+ if (!stats.isFile()) {
234
+ return { exists: true, ok: false, problem: "unsafe", detail: `${path} is not a regular file` };
235
+ }
236
+ if (platform === "win32") {
237
+ return {
238
+ exists: true,
239
+ ok: true,
240
+ detail: `Windows ACLs apply, POSIX modes are not enforced; keep ${path} readable by your account only`,
241
+ };
242
+ }
243
+ const mode = stats.mode & 0o777;
244
+ const ok = (mode & 0o077) === 0;
245
+ return { exists: true, ok, ...(ok ? {} : { problem: "permissions" }), detail: `0${mode.toString(8)} (${path})` };
246
+ }
247
+ /** A sentence to show when the config file deserves attention, or null when there is nothing to say. */
248
+ export function configPermWarning(path, platform = process.platform) {
249
+ const check = inspectConfigFile(path, platform);
250
+ if (!check.exists) {
251
+ return null;
252
+ }
253
+ if (!check.ok) {
254
+ // A link or a directory is not fixed by chmod; say what is wrong and nothing else.
255
+ return check.problem === "permissions" ? `Config file permissions are too open: ${check.detail}; run chmod 600 on it` : check.detail;
256
+ }
257
+ return platform === "win32" ? check.detail : null;
258
+ }
259
+ /** `--server`, then `EVALCTL_SERVER`, then the saved server, normalized. */
260
+ export function resolveServer(flagServer, cfg, env = process.env) {
261
+ const raw = nonEmptyString(flagServer) ?? nonEmptyString(env[ENV_SERVER]) ?? nonEmptyString(cfg["server"]);
262
+ return normalizeServerUrl(raw);
263
+ }
264
+ /**
265
+ * The Bearer token for `serverUrl`. `EVALCTL_TOKEN` wins when it is set, since the person chose it for this run.
266
+ * A saved token is only ever used for the origin it was issued by, so a `--server` override never leaks it elsewhere.
267
+ */
268
+ export function resolveToken(cfg, serverUrl, env = process.env) {
269
+ if (serverOrigin(serverUrl) === null) {
270
+ return null;
271
+ }
272
+ const fromEnv = nonEmptyString(env[ENV_TOKEN]);
273
+ if (fromEnv !== undefined) {
274
+ return fromEnv;
275
+ }
276
+ const savedServer = nonEmptyString(cfg["server"]);
277
+ if (savedServer === undefined || !sameServerOrigin(serverUrl, savedServer)) {
278
+ return null;
279
+ }
280
+ return nonEmptyString(cfg["token"]) ?? null;
281
+ }
@@ -0,0 +1,64 @@
1
+ import type { ApiClient, ApiClientOptions } from "./client.js";
2
+ import type { InputStream } from "./prompt.js";
3
+ import type { JsonObject } from "./util.js";
4
+ export interface GlobalOptions {
5
+ server: string | undefined;
6
+ config: string | undefined;
7
+ json: boolean;
8
+ dryRun: boolean;
9
+ }
10
+ /** Everything a command reads from the machine it runs on; tests substitute each piece. */
11
+ export interface RuntimeIO {
12
+ stdin: InputStream;
13
+ /** Where prompts are written: stderr, so stdout stays clean for data. */
14
+ promptOutput: NodeJS.WritableStream;
15
+ env: NodeJS.ProcessEnv;
16
+ cwd: string;
17
+ platform: NodeJS.Platform;
18
+ hostname: () => string;
19
+ nodeVersion: string;
20
+ clientOptions?: ApiClientOptions;
21
+ }
22
+ export type OptionValue = string | boolean | readonly (string | boolean)[] | undefined;
23
+ export interface OptionSpec {
24
+ type: "boolean" | "string";
25
+ short?: string;
26
+ multiple?: boolean;
27
+ description: string;
28
+ /** Name of the value in help, e.g. `PATH`. */
29
+ placeholder?: string;
30
+ /** The only values accepted, checked for every string option that declares them; `--help` lists them. */
31
+ choices?: readonly string[];
32
+ /** What is used when the option is left out, as `--help` shows it. */
33
+ default?: string;
34
+ }
35
+ export interface CommandContext {
36
+ global: GlobalOptions;
37
+ values: Readonly<Record<string, OptionValue>>;
38
+ positionals: readonly string[];
39
+ io: RuntimeIO;
40
+ configPath: string;
41
+ /** The saved config, read on first use. Throws a `CliError` when the file cannot be used. */
42
+ config(): JsonObject;
43
+ /** A client for the resolved server and token, built on first use. */
44
+ client(): ApiClient;
45
+ flag(name: string): boolean;
46
+ opt(name: string): string | undefined;
47
+ optList(name: string): string[];
48
+ }
49
+ export type CommandHandler = (ctx: CommandContext) => Promise<number>;
50
+ export interface CommandSpec {
51
+ name: string;
52
+ summary: string;
53
+ /** Usage after the program name, e.g. `login [--email EMAIL]`. */
54
+ usage: string;
55
+ options?: Readonly<Record<string, OptionSpec>>;
56
+ /** Positional arguments after the command (and its subcommand): how few and how many. */
57
+ positionals?: {
58
+ min: number;
59
+ max: number;
60
+ };
61
+ /** A command with subcommands is only a namespace; each subcommand carries its own options and handler. */
62
+ subcommands?: readonly CommandSpec[];
63
+ handler?: CommandHandler;
64
+ }
@@ -0,0 +1 @@
1
+ export {};
package/dist/diff.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ /** Splits text into lines that keep their own line break, so a missing final newline stays visible. */
2
+ export declare function splitLinesKeepEnds(text: string): string[];
3
+ /**
4
+ * Unified diff of two line lists (each line with its own line break, see `splitLinesKeepEnds`),
5
+ * `context` unchanged lines around each change. Returns "" when the two are identical.
6
+ */
7
+ export declare function unifiedDiff(fromLines: readonly string[], toLines: readonly string[], fromLabel: string, toLabel: string, context?: number): string;
package/dist/diff.js ADDED
@@ -0,0 +1,122 @@
1
+ // A small line-based unified diff, so `diff --local` needs no external tool and prints the same shape on every platform.
2
+ // The LCS table costs rows x columns cells; beyond this the changed region is reported as one replacement.
3
+ const MAX_TABLE_CELLS = 4_000_000;
4
+ /** Splits text into lines that keep their own line break, so a missing final newline stays visible. */
5
+ export function splitLinesKeepEnds(text) {
6
+ const lines = text.match(/[^\n]*\n|[^\n]+$/g);
7
+ return lines === null ? [] : lines;
8
+ }
9
+ function diffOps(from, to) {
10
+ let start = 0;
11
+ while (start < from.length && start < to.length && from[start] === to[start]) {
12
+ start += 1;
13
+ }
14
+ let endFrom = from.length;
15
+ let endTo = to.length;
16
+ while (endFrom > start && endTo > start && from[endFrom - 1] === to[endTo - 1]) {
17
+ endFrom -= 1;
18
+ endTo -= 1;
19
+ }
20
+ const ops = from.slice(0, start).map((line) => ({ tag: "equal", line }));
21
+ const a = from.slice(start, endFrom);
22
+ const b = to.slice(start, endTo);
23
+ const cols = b.length + 1;
24
+ if ((a.length + 1) * cols > MAX_TABLE_CELLS) {
25
+ ops.push(...a.map((line) => ({ tag: "delete", line })), ...b.map((line) => ({ tag: "insert", line })));
26
+ }
27
+ else {
28
+ // table[i * cols + j] is the length of the longest common subsequence of a[i..] and b[j..].
29
+ const table = new Uint32Array((a.length + 1) * cols);
30
+ for (let i = a.length - 1; i >= 0; i -= 1) {
31
+ for (let j = b.length - 1; j >= 0; j -= 1) {
32
+ table[i * cols + j] =
33
+ a[i] === b[j]
34
+ ? (table[(i + 1) * cols + j + 1] ?? 0) + 1
35
+ : Math.max(table[(i + 1) * cols + j] ?? 0, table[i * cols + j + 1] ?? 0);
36
+ }
37
+ }
38
+ let i = 0;
39
+ let j = 0;
40
+ while (i < a.length && j < b.length) {
41
+ const lineA = a[i] ?? "";
42
+ if (lineA === b[j]) {
43
+ ops.push({ tag: "equal", line: lineA });
44
+ i += 1;
45
+ j += 1;
46
+ }
47
+ else if ((table[(i + 1) * cols + j] ?? 0) >= (table[i * cols + j + 1] ?? 0)) {
48
+ ops.push({ tag: "delete", line: lineA });
49
+ i += 1;
50
+ }
51
+ else {
52
+ ops.push({ tag: "insert", line: b[j] ?? "" });
53
+ j += 1;
54
+ }
55
+ }
56
+ for (; i < a.length; i += 1) {
57
+ ops.push({ tag: "delete", line: a[i] ?? "" });
58
+ }
59
+ for (; j < b.length; j += 1) {
60
+ ops.push({ tag: "insert", line: b[j] ?? "" });
61
+ }
62
+ }
63
+ ops.push(...from.slice(endFrom).map((line) => ({ tag: "equal", line })));
64
+ return ops;
65
+ }
66
+ function formatRange(start, length) {
67
+ const beginning = start + 1;
68
+ if (length === 1) {
69
+ return String(beginning);
70
+ }
71
+ return length === 0 ? `${beginning - 1},0` : `${beginning},${length}`;
72
+ }
73
+ function renderLine(prefix, line) {
74
+ return line.endsWith("\n") ? `${prefix}${line}` : `${prefix}${line}\n\\n`;
75
+ }
76
+ /**
77
+ * Unified diff of two line lists (each line with its own line break, see `splitLinesKeepEnds`),
78
+ * `context` unchanged lines around each change. Returns "" when the two are identical.
79
+ */
80
+ export function unifiedDiff(fromLines, toLines, fromLabel, toLabel, context = 3) {
81
+ const ops = diffOps(fromLines, toLines);
82
+ const changed = [];
83
+ ops.forEach((op, index) => {
84
+ if (op.tag !== "equal") {
85
+ changed.push(index);
86
+ }
87
+ });
88
+ const first = changed[0];
89
+ if (first === undefined) {
90
+ return "";
91
+ }
92
+ const groups = [];
93
+ let groupStart = first;
94
+ let groupEnd = first;
95
+ for (const index of changed.slice(1)) {
96
+ if (index - groupEnd - 1 > 2 * context) {
97
+ groups.push([groupStart, groupEnd]);
98
+ groupStart = index;
99
+ }
100
+ groupEnd = index;
101
+ }
102
+ groups.push([groupStart, groupEnd]);
103
+ let text = `--- ${fromLabel}\n+++ ${toLabel}\n`;
104
+ for (const [firstChange, lastChange] of groups) {
105
+ const begin = Math.max(0, firstChange - context);
106
+ const end = Math.min(ops.length, lastChange + context + 1);
107
+ let fromStart = 0;
108
+ let toStart = 0;
109
+ for (const op of ops.slice(0, begin)) {
110
+ fromStart += op.tag === "insert" ? 0 : 1;
111
+ toStart += op.tag === "delete" ? 0 : 1;
112
+ }
113
+ const slice = ops.slice(begin, end);
114
+ const fromLength = slice.filter((op) => op.tag !== "insert").length;
115
+ const toLength = slice.filter((op) => op.tag !== "delete").length;
116
+ text += `@@ -${formatRange(fromStart, fromLength)} +${formatRange(toStart, toLength)} @@\n`;
117
+ for (const op of slice) {
118
+ text += renderLine(op.tag === "equal" ? " " : op.tag === "delete" ? "-" : "+", op.line);
119
+ }
120
+ }
121
+ return text;
122
+ }