@okhay-p/mivra 0.1.5 → 0.1.7
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/README.md +1 -0
- package/THIRD_PARTY_NOTICES.md +250 -0
- package/dist/{chunk-ODFBAPPH.js → chunk-M62PZTK3.js} +125 -6
- package/dist/chunk-M62PZTK3.js.map +7 -0
- package/dist/{chunk-KE5ZEREE.js → chunk-T5WM74CI.js} +2 -1
- package/dist/chunk-TKDX5OCX.js +2555 -0
- package/dist/chunk-TKDX5OCX.js.map +7 -0
- package/dist/{chunk-KUKQU7EQ.js → chunk-VHOVRHI3.js} +38 -10
- package/dist/{chunk-KUKQU7EQ.js.map → chunk-VHOVRHI3.js.map} +2 -2
- package/dist/cli.js +1099 -53
- package/dist/cli.js.map +4 -4
- package/dist/{client-5YDLS4KV.js → client-76YUHG4T.js} +2 -2
- package/dist/exercise-child.js +37 -0
- package/dist/exercise-child.js.map +7 -0
- package/dist/extract-child.js +2 -2
- package/dist/python-child.js +51 -0
- package/dist/python-child.js.map +7 -0
- package/dist/{start-2RXX57ZZ.js → start-GVAACONX.js} +5809 -2377
- package/dist/start-GVAACONX.js.map +7 -0
- package/drizzle/0019_public_doctor_faustus.sql +1 -0
- package/drizzle/0020_early_wolfpack.sql +3 -0
- package/drizzle/0021_strange_gamma_corps.sql +2 -0
- package/drizzle/0022_fast_forgotten_one.sql +28 -0
- package/drizzle/0023_low_wiccan.sql +17 -0
- package/drizzle/0024_windy_annihilus.sql +1 -0
- package/drizzle/0025_brief_rictor.sql +6 -0
- package/drizzle/0026_greedy_sally_floyd.sql +1 -0
- package/drizzle/0027_regular_calypso.sql +41 -0
- package/drizzle/0028_lazy_agent_zero.sql +17 -0
- package/drizzle/meta/0019_snapshot.json +2288 -0
- package/drizzle/meta/0020_snapshot.json +2297 -0
- package/drizzle/meta/0021_snapshot.json +2313 -0
- package/drizzle/meta/0022_snapshot.json +2529 -0
- package/drizzle/meta/0023_snapshot.json +2654 -0
- package/drizzle/meta/0024_snapshot.json +2662 -0
- package/drizzle/meta/0025_snapshot.json +2707 -0
- package/drizzle/meta/0026_snapshot.json +2714 -0
- package/drizzle/meta/0027_snapshot.json +2816 -0
- package/drizzle/meta/0028_snapshot.json +2940 -0
- package/drizzle/meta/_journal.json +70 -0
- package/package.json +6 -1
- package/web/assets/emscripten-module-uFzwHH0Y.wasm +0 -0
- package/web/assets/emscripten-module.browser-D72eEgXo.js +1 -0
- package/web/assets/exercise-workers/exercise.worker-LCHlYekD.js +265 -0
- package/web/assets/exercise-workers/python-exercise.worker-DeTriNjh.js +236 -0
- package/web/assets/ffi-4V2b7xu3.js +1 -0
- package/web/assets/index-CQjNLnxP.js +540 -0
- package/web/assets/index-DpV5il_3.css +1 -0
- package/web/assets/module-ES6BEMUI-B2wjplZC.js +1 -0
- package/web/assets/notes-graph.worker-Dqb5HK34.js +1 -0
- package/web/assets/render.worker-OksjuBjV.js +537 -0
- package/web/index.html +2 -2
- package/dist/chunk-ODFBAPPH.js.map +0 -7
- package/dist/chunk-YACRW47X.js +0 -1203
- package/dist/chunk-YACRW47X.js.map +0 -7
- package/dist/start-2RXX57ZZ.js.map +0 -7
- package/web/assets/index-DJ2D5ZXo.css +0 -1
- package/web/assets/index-DcYzUL1W.js +0 -413
- package/web/assets/notes-graph.worker-DaVQvftJ.js +0 -1
- package/web/assets/render.worker-BAfybD27.js +0 -416
- /package/dist/{chunk-KE5ZEREE.js.map → chunk-T5WM74CI.js.map} +0 -0
- /package/dist/{client-5YDLS4KV.js.map → client-76YUHG4T.js.map} +0 -0
package/dist/cli.js
CHANGED
|
@@ -5,26 +5,41 @@ import {
|
|
|
5
5
|
ChatGptError,
|
|
6
6
|
PROVIDER_ENV,
|
|
7
7
|
PROVIDER_LABELS,
|
|
8
|
+
ServerToken,
|
|
8
9
|
TOKEN_FILE,
|
|
9
10
|
chatGptFileStore,
|
|
10
11
|
createChatGptSession,
|
|
11
12
|
createCredentialStore,
|
|
12
|
-
|
|
13
|
-
|
|
13
|
+
loadOrCreateToken,
|
|
14
|
+
providerIds,
|
|
15
|
+
readRemoteServer,
|
|
16
|
+
removeRemoteServer,
|
|
17
|
+
saveRemoteServer
|
|
18
|
+
} from "./chunk-VHOVRHI3.js";
|
|
14
19
|
import {
|
|
20
|
+
CourseView,
|
|
21
|
+
MAX_CASE_OUTPUT_CHARS,
|
|
22
|
+
MAX_MILESTONE_STDERR_CHARS,
|
|
15
23
|
MAX_NOTE_CHARS,
|
|
24
|
+
MAX_REVIEW_FILES,
|
|
25
|
+
MAX_REVIEW_FILE_CHARS,
|
|
26
|
+
MAX_REVIEW_PATH_CHARS,
|
|
27
|
+
MAX_REVIEW_TOTAL_CHARS,
|
|
16
28
|
MAX_VAULT_BYTES,
|
|
17
29
|
MAX_VAULT_FILES,
|
|
30
|
+
MilestoneCases,
|
|
31
|
+
MilestoneCheckResult,
|
|
18
32
|
VaultImportResult,
|
|
19
|
-
VaultImportView
|
|
20
|
-
|
|
33
|
+
VaultImportView,
|
|
34
|
+
normaliseOutput
|
|
35
|
+
} from "./chunk-TKDX5OCX.js";
|
|
21
36
|
import "./chunk-PZ5AY32C.js";
|
|
22
37
|
|
|
23
38
|
// src/cli.ts
|
|
24
39
|
import { spawn as spawn2 } from "node:child_process";
|
|
25
40
|
import { createInterface as createInterface2 } from "node:readline";
|
|
26
|
-
import { closeSync as closeSync2, existsSync as existsSync2, mkdirSync as
|
|
27
|
-
import { join as
|
|
41
|
+
import { closeSync as closeSync2, existsSync as existsSync2, mkdirSync as mkdirSync3, openSync as openSync2, readFileSync as readFileSync5 } from "node:fs";
|
|
42
|
+
import { join as join9 } from "node:path";
|
|
28
43
|
import { fileURLToPath } from "node:url";
|
|
29
44
|
|
|
30
45
|
// ../server/src/config.ts
|
|
@@ -63,6 +78,21 @@ Commands:
|
|
|
63
78
|
auth logout chatgpt Sign out of ChatGPT
|
|
64
79
|
import obsidian <folder> Import an Obsidian vault's notes into a running Mivra; run it again to re-import
|
|
65
80
|
--name <name> Name the import (default: the folder's name)
|
|
81
|
+
link <course> Link this folder to a project course, in .mivra.json (no secrets; safe to commit)
|
|
82
|
+
--run <command> How to run your program, e.g. "./build/mycc {input}": {input} becomes the path to a
|
|
83
|
+
file holding a case's input, which also comes on stdin. Runs without a shell
|
|
84
|
+
--run-output <command> For cases that run your program's output (e.g. assembly): {output} is its path
|
|
85
|
+
link --server <url> Use the Mivra at this address (on another computer) for link and check. Asks for its
|
|
86
|
+
token (or pipe it in) and saves both in the data dir, never in .mivra.json
|
|
87
|
+
link --local Go back to the Mivra running on this computer
|
|
88
|
+
token Print this Mivra's token, for \`mivra link --server\` on another computer
|
|
89
|
+
check Run your program on the current milestone's cases and record the result in Mivra
|
|
90
|
+
--timeout <seconds> Time limit for each run (default: 10)
|
|
91
|
+
--dry-run List exactly what would be sent for review, without running or sending anything
|
|
92
|
+
--approve Approve the commands in .mivra.json for this folder without asking. Check runs only
|
|
93
|
+
commands you approved here: \`mivra link\` approves the ones it writes, and a
|
|
94
|
+
.mivra.json that's new here or changed (from a clone or a pull) needs approving again
|
|
95
|
+
--watch Watch the project folder and re-run check when files change
|
|
66
96
|
uninstall Stop Mivra and ask whether to delete its data, before you remove the package
|
|
67
97
|
--delete-data Delete the data without asking
|
|
68
98
|
--keep-data Keep the data without asking
|
|
@@ -71,6 +101,18 @@ Providers: ${providerIds.join(", ")}
|
|
|
71
101
|
Data lives in ~/.mivra, or MIVRA_DATA_DIR.`;
|
|
72
102
|
var UsageError = class extends Error {
|
|
73
103
|
};
|
|
104
|
+
function serverUrl(input) {
|
|
105
|
+
let url;
|
|
106
|
+
try {
|
|
107
|
+
url = new URL(input.trim());
|
|
108
|
+
} catch {
|
|
109
|
+
throw new UsageError(`--server needs an address such as https://mivra.example.ts.net, not "${input}".`);
|
|
110
|
+
}
|
|
111
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") throw new UsageError("--server needs an http:// or https:// address.");
|
|
112
|
+
if (url.username || url.password) throw new UsageError("Leave the user name and password out of --server: Mivra asks for its token separately.");
|
|
113
|
+
if (url.pathname !== "/" && url.pathname !== "" || url.search || url.hash) throw new UsageError(`--server takes the address Mivra opens at, without a path: ${url.origin}`);
|
|
114
|
+
return url.origin;
|
|
115
|
+
}
|
|
74
116
|
var provider = (value) => {
|
|
75
117
|
if (!value) throw new UsageError(`Name a provider: ${providerIds.join(", ")}.`);
|
|
76
118
|
if (!providerIds.includes(value)) throw new UsageError(`Unknown provider "${value}". Use one of: ${providerIds.join(", ")}.`);
|
|
@@ -86,6 +128,14 @@ function parseCommand(argv) {
|
|
|
86
128
|
options: {
|
|
87
129
|
port: { type: "string" },
|
|
88
130
|
name: { type: "string" },
|
|
131
|
+
run: { type: "string" },
|
|
132
|
+
"run-output": { type: "string" },
|
|
133
|
+
server: { type: "string" },
|
|
134
|
+
local: { type: "boolean", default: false },
|
|
135
|
+
timeout: { type: "string" },
|
|
136
|
+
"dry-run": { type: "boolean", default: false },
|
|
137
|
+
approve: { type: "boolean", default: false },
|
|
138
|
+
watch: { type: "boolean", default: false },
|
|
89
139
|
detach: { type: "boolean", default: false },
|
|
90
140
|
open: { type: "boolean", default: true },
|
|
91
141
|
check: { type: "boolean", default: true },
|
|
@@ -144,6 +194,35 @@ function parseCommand(argv) {
|
|
|
144
194
|
if (!arg) throw new UsageError("Give the vault's folder: `mivra import obsidian <folder>`.");
|
|
145
195
|
tooMany(3);
|
|
146
196
|
return { name: "import-obsidian", folder: arg, ...values.name === void 0 ? {} : { importName: values.name } };
|
|
197
|
+
case "link": {
|
|
198
|
+
tooMany(2);
|
|
199
|
+
const runOutput = values["run-output"]?.trim();
|
|
200
|
+
const server2 = values.server === void 0 ? void 0 : serverUrl(values.server);
|
|
201
|
+
if (server2 && values.local) throw new UsageError("Use --server or --local, not both.");
|
|
202
|
+
if (!sub) {
|
|
203
|
+
if (server2 || values.local) {
|
|
204
|
+
if (values.run !== void 0 || runOutput) throw new UsageError('Give the course\'s id with --run: `mivra link <course> --run "<command>"`.');
|
|
205
|
+
return { name: "link", ...server2 ? { server: server2 } : {}, local: values.local };
|
|
206
|
+
}
|
|
207
|
+
throw new UsageError('Give the course\'s id, as the milestone in Mivra shows it: `mivra link <course> --run "<command>"`.');
|
|
208
|
+
}
|
|
209
|
+
if (!values.run?.trim()) throw new UsageError('Say how to run your program with --run, e.g. `mivra link <course> --run "./build/mycc {input}"`.');
|
|
210
|
+
return { name: "link", course: sub, run: values.run.trim(), ...runOutput ? { runOutput } : {}, ...server2 ? { server: server2 } : {}, local: values.local };
|
|
211
|
+
}
|
|
212
|
+
case "token":
|
|
213
|
+
tooMany(1);
|
|
214
|
+
return { name: "token" };
|
|
215
|
+
case "check": {
|
|
216
|
+
tooMany(1);
|
|
217
|
+
let timeoutS = 10;
|
|
218
|
+
if (values.timeout !== void 0) {
|
|
219
|
+
timeoutS = Number(values.timeout);
|
|
220
|
+
if (!Number.isFinite(timeoutS) || timeoutS < 1 || timeoutS > 600) throw new UsageError(`--timeout needs a number of seconds from 1 to 600, not "${values.timeout}".`);
|
|
221
|
+
}
|
|
222
|
+
if (values.approve && values["dry-run"]) throw new UsageError("Use --approve or --dry-run, not both: a dry run runs nothing.");
|
|
223
|
+
if (values.watch && values["dry-run"]) throw new UsageError("Use --watch or --dry-run, not both: a dry run runs once and runs nothing.");
|
|
224
|
+
return { name: "check", timeoutS, dryRun: values["dry-run"], approve: values.approve, watch: values.watch };
|
|
225
|
+
}
|
|
147
226
|
case "uninstall":
|
|
148
227
|
tooMany(1);
|
|
149
228
|
if (values["delete-data"] && values["keep-data"]) throw new UsageError("Use --delete-data or --keep-data, not both.");
|
|
@@ -288,7 +367,7 @@ async function readSecret(prompt, input = process.stdin, output = process.stderr
|
|
|
288
367
|
input.setRawMode(true);
|
|
289
368
|
input.resume();
|
|
290
369
|
input.setEncoding("utf8");
|
|
291
|
-
return new Promise((
|
|
370
|
+
return new Promise((resolve3, reject) => {
|
|
292
371
|
let value = "";
|
|
293
372
|
const done = (error) => {
|
|
294
373
|
input.setRawMode(false);
|
|
@@ -296,7 +375,7 @@ async function readSecret(prompt, input = process.stdin, output = process.stderr
|
|
|
296
375
|
input.off("data", onData);
|
|
297
376
|
output.write("\n");
|
|
298
377
|
if (error) reject(error);
|
|
299
|
-
else
|
|
378
|
+
else resolve3(value.trim());
|
|
300
379
|
};
|
|
301
380
|
const onData = (chunk) => {
|
|
302
381
|
for (const char of chunk) {
|
|
@@ -312,27 +391,977 @@ async function readSecret(prompt, input = process.stdin, output = process.stderr
|
|
|
312
391
|
async function confirm(question, input = process.stdin, output = process.stderr) {
|
|
313
392
|
output.write(question);
|
|
314
393
|
const lines = createInterface({ input, terminal: false });
|
|
315
|
-
const answer = await new Promise((
|
|
316
|
-
lines.once("line",
|
|
317
|
-
lines.once("close", () =>
|
|
394
|
+
const answer = await new Promise((resolve3) => {
|
|
395
|
+
lines.once("line", resolve3);
|
|
396
|
+
lines.once("close", () => resolve3(""));
|
|
318
397
|
});
|
|
319
398
|
lines.close();
|
|
320
399
|
input.pause();
|
|
321
400
|
if (!input.isTTY) output.write("\n");
|
|
322
401
|
return /^(y|yes)$/i.test(answer.trim());
|
|
323
402
|
}
|
|
403
|
+
var canAsk = (streams = process) => Boolean(streams.stdin.isTTY && streams.stdout.isTTY && streams.stderr.isTTY);
|
|
324
404
|
|
|
325
|
-
// src/
|
|
326
|
-
import {
|
|
405
|
+
// src/project.ts
|
|
406
|
+
import { mkdtempSync, readFileSync as readFileSync3, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "node:fs";
|
|
407
|
+
import { tmpdir } from "node:os";
|
|
408
|
+
import { dirname, join as join6, resolve } from "node:path";
|
|
409
|
+
import { z as z3 } from "zod";
|
|
410
|
+
|
|
411
|
+
// src/approval.ts
|
|
412
|
+
import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, realpathSync, renameSync as renameSync2, rmSync as rmSync2, writeFileSync } from "node:fs";
|
|
327
413
|
import { join as join3 } from "node:path";
|
|
414
|
+
import { z as z2 } from "zod";
|
|
415
|
+
var APPROVALS_FILE = "approved-commands.json";
|
|
416
|
+
var Record = z2.object({ course: z2.string(), run: z2.string(), runOutput: z2.string().optional(), approvedAt: z2.string() });
|
|
417
|
+
var File = z2.object({ checkouts: z2.record(z2.string(), Record) });
|
|
418
|
+
var checkoutKey = (dir) => realpathSync(dir);
|
|
419
|
+
function read(dataDir) {
|
|
420
|
+
try {
|
|
421
|
+
const parsed = File.safeParse(JSON.parse(readFileSync2(join3(dataDir, APPROVALS_FILE), "utf8")));
|
|
422
|
+
if (parsed.success) return parsed.data;
|
|
423
|
+
} catch {
|
|
424
|
+
}
|
|
425
|
+
return { checkouts: {} };
|
|
426
|
+
}
|
|
427
|
+
function isApproved(dataDir, dir, wanted) {
|
|
428
|
+
const record = read(dataDir).checkouts[checkoutKey(dir)];
|
|
429
|
+
return record !== void 0 && record.course === wanted.course && record.run === wanted.run && record.runOutput === wanted.runOutput;
|
|
430
|
+
}
|
|
431
|
+
function approve(dataDir, dir, approved) {
|
|
432
|
+
const file = read(dataDir);
|
|
433
|
+
file.checkouts[checkoutKey(dir)] = {
|
|
434
|
+
course: approved.course,
|
|
435
|
+
run: approved.run,
|
|
436
|
+
...approved.runOutput !== void 0 ? { runOutput: approved.runOutput } : {},
|
|
437
|
+
approvedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
438
|
+
};
|
|
439
|
+
mkdirSync2(dataDir, { recursive: true });
|
|
440
|
+
const path = join3(dataDir, APPROVALS_FILE);
|
|
441
|
+
const temp = `${path}.${process.pid}.${Date.now()}.tmp`;
|
|
442
|
+
try {
|
|
443
|
+
writeFileSync(temp, `${JSON.stringify(file, null, 2)}
|
|
444
|
+
`, { mode: 384 });
|
|
445
|
+
renameSync2(temp, path);
|
|
446
|
+
} catch (error) {
|
|
447
|
+
rmSync2(temp, { force: true });
|
|
448
|
+
throw error;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
var shown = (text) => (
|
|
452
|
+
// eslint-disable-next-line no-control-regex
|
|
453
|
+
text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`)
|
|
454
|
+
);
|
|
455
|
+
|
|
456
|
+
// src/repo-files.ts
|
|
457
|
+
import { execFile } from "node:child_process";
|
|
458
|
+
import { lstat, readFile, realpath } from "node:fs/promises";
|
|
459
|
+
import { basename, isAbsolute, join as join4, relative, sep } from "node:path";
|
|
460
|
+
var LOCKFILES = /* @__PURE__ */ new Set(["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock", "cargo.lock", "poetry.lock", "pipfile.lock", "uv.lock", "composer.lock", "gemfile.lock", "go.sum", "flake.lock", "mix.lock", "pubspec.lock", "podfile.lock", "packages.lock.json"]);
|
|
461
|
+
var SECRET_DIRS = /* @__PURE__ */ new Set([".ssh", ".aws", ".gnupg", ".azure", ".kube", ".docker", "secrets", ".secrets"]);
|
|
462
|
+
var SECRET_NAMES = /* @__PURE__ */ new Set([
|
|
463
|
+
".npmrc",
|
|
464
|
+
".pypirc",
|
|
465
|
+
".netrc",
|
|
466
|
+
"_netrc",
|
|
467
|
+
".git-credentials",
|
|
468
|
+
".htpasswd",
|
|
469
|
+
".pgpass",
|
|
470
|
+
".dockercfg",
|
|
471
|
+
"credentials",
|
|
472
|
+
"authorized_keys",
|
|
473
|
+
"known_hosts",
|
|
474
|
+
"terraform.tfvars"
|
|
475
|
+
]);
|
|
476
|
+
var SECRET_PATTERNS = [
|
|
477
|
+
/^\.env($|[-_.])/,
|
|
478
|
+
// .env, .env.local, .env-production, .env_prod, .env.example: all of them
|
|
479
|
+
/\.env$/,
|
|
480
|
+
// prod.env
|
|
481
|
+
/^\.?envrc$/,
|
|
482
|
+
/\.(pem|key|p8|p12|pfx|jks|keystore|ppk|asc|gpg|kdbx|tfstate|tfvars|secret|secrets)$/,
|
|
483
|
+
/\.tfstate\.backup$/,
|
|
484
|
+
/^id_(rsa|dsa|ecdsa|ed25519)(_sk)?$/,
|
|
485
|
+
/credential/,
|
|
486
|
+
/^secrets?\./,
|
|
487
|
+
/^service[-_]?account.*\.json$/,
|
|
488
|
+
/^client_secret.*\.json$/,
|
|
489
|
+
// Tokens, keys and passwords kept in data files (not source files: a lexer's token.c is code, not a secret).
|
|
490
|
+
/(^|[-_.])(api[-_]?keys?|keys?|(access|auth|api|bearer|refresh|github|slack|bot)[-_]?tokens?|passwords?|passwd|secrets?)([-_.][^/]*)?\.(json|ya?ml|toml|ini|cfg|conf|txt|properties|xml)$/
|
|
491
|
+
];
|
|
492
|
+
var KEY_DIRS = /* @__PURE__ */ new Set(["keys", ".keys", "apikeys", "api-keys", "api_keys"]);
|
|
493
|
+
var DATA_FILE = /(^[^.]+$)|\.(json|ya?ml|toml|ini|cfg|conf|txt|properties|xml|env)$/;
|
|
494
|
+
var PRIVATE_KEY = /-----BEGIN ([A-Z0-9]+ )*PRIVATE KEY( BLOCK)?-----/;
|
|
495
|
+
function looksSecret(path) {
|
|
496
|
+
const parts = path.split(/[\\/]/).map((p) => p.toLowerCase());
|
|
497
|
+
const secretName = (name2) => SECRET_NAMES.has(name2) || SECRET_PATTERNS.some((pattern) => pattern.test(name2));
|
|
498
|
+
if (parts.slice(0, -1).some((dir) => SECRET_DIRS.has(dir) || secretName(dir))) return true;
|
|
499
|
+
const name = parts.at(-1) ?? "";
|
|
500
|
+
if (parts.slice(0, -1).some((dir) => KEY_DIRS.has(dir)) && DATA_FILE.test(name)) return true;
|
|
501
|
+
return secretName(name);
|
|
502
|
+
}
|
|
503
|
+
function git(cwd, args) {
|
|
504
|
+
return new Promise((resolve3, reject) => {
|
|
505
|
+
execFile(
|
|
506
|
+
"git",
|
|
507
|
+
["-c", "core.quotepath=off", ...args],
|
|
508
|
+
{ cwd, maxBuffer: 64 * 1024 * 1024, windowsHide: true, encoding: "utf8" },
|
|
509
|
+
(error, stdout) => error ? reject(error) : resolve3(stdout)
|
|
510
|
+
);
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
var splitZ = (text) => text.split("\0").filter((p) => p !== "");
|
|
514
|
+
var toSlash = (path) => path.split(sep).join("/");
|
|
515
|
+
async function changedPaths(root2, since) {
|
|
516
|
+
const untracked = splitZ(await git(root2, ["ls-files", "-z", "--others", "--exclude-standard"]));
|
|
517
|
+
if (since && /^[0-9a-f]{40}([0-9a-f]{24})?$/.test(since)) {
|
|
518
|
+
const known = await git(root2, ["cat-file", "-e", `${since}^{commit}`]).then(
|
|
519
|
+
() => true,
|
|
520
|
+
() => false
|
|
521
|
+
);
|
|
522
|
+
if (known) {
|
|
523
|
+
const fields = splitZ(await git(root2, ["diff", "--name-status", "-z", "--no-renames", "--relative", since, "--", "."]));
|
|
524
|
+
const paths = [];
|
|
525
|
+
const deleted = [];
|
|
526
|
+
for (let i = 0; i + 1 < fields.length; i += 2) {
|
|
527
|
+
(fields[i] === "D" ? deleted : paths).push(fields[i + 1]);
|
|
528
|
+
}
|
|
529
|
+
return { paths: [.../* @__PURE__ */ new Set([...paths, ...untracked])], deleted, sinceUsed: true };
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
const tracked = splitZ(await git(root2, ["ls-files", "-z", "--cached"]));
|
|
533
|
+
return { paths: [.../* @__PURE__ */ new Set([...tracked, ...untracked])], deleted: [], sinceUsed: false };
|
|
534
|
+
}
|
|
535
|
+
async function readCandidate(root2, realRoot, path) {
|
|
536
|
+
if (looksSecret(path)) return { ok: false, reason: "secret" };
|
|
537
|
+
if (LOCKFILES.has(basename(path).toLowerCase())) return { ok: false, reason: "lockfile" };
|
|
538
|
+
if (path.length > MAX_REVIEW_PATH_CHARS) return { ok: false, reason: "too_large" };
|
|
539
|
+
const full = join4(root2, path);
|
|
540
|
+
let info;
|
|
541
|
+
try {
|
|
542
|
+
info = await lstat(full);
|
|
543
|
+
} catch {
|
|
544
|
+
return { ok: false, reason: "gone" };
|
|
545
|
+
}
|
|
546
|
+
if (!info.isFile()) return { ok: false, reason: "not_a_file" };
|
|
547
|
+
const real = await realpath(full).catch(() => void 0);
|
|
548
|
+
const rel = real === void 0 ? void 0 : relative(realRoot, real);
|
|
549
|
+
if (rel === void 0 || rel === "" || rel.startsWith("..") || isAbsolute(rel)) return { ok: false, reason: "not_a_file" };
|
|
550
|
+
if (info.size > MAX_REVIEW_FILE_CHARS * 4) return { ok: false, reason: "too_large" };
|
|
551
|
+
const bytes = await readFile(full).catch(() => void 0);
|
|
552
|
+
if (!bytes) return { ok: false, reason: "gone" };
|
|
553
|
+
if (bytes.subarray(0, 8e3).includes(0)) return { ok: false, reason: "binary" };
|
|
554
|
+
const content = bytes.toString("utf8");
|
|
555
|
+
if (PRIVATE_KEY.test(content)) return { ok: false, reason: "secret" };
|
|
556
|
+
if (content.length > MAX_REVIEW_FILE_CHARS) return { ok: false, reason: "too_large" };
|
|
557
|
+
return { ok: true, content };
|
|
558
|
+
}
|
|
559
|
+
async function collectChanges(root2, since) {
|
|
560
|
+
try {
|
|
561
|
+
if ((await git(root2, ["rev-parse", "--is-inside-work-tree"])).trim() !== "true") throw new Error("not a work tree");
|
|
562
|
+
} catch {
|
|
563
|
+
return {
|
|
564
|
+
source: "none",
|
|
565
|
+
note: "This folder isn't in a git repository (or git isn't installed), so Mivra can't tell which files to send for review, or which are ignored. Run `git init` here.",
|
|
566
|
+
sinceUsed: false,
|
|
567
|
+
files: [],
|
|
568
|
+
skipped: [],
|
|
569
|
+
deleted: []
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
const commit = (await git(root2, ["rev-parse", "--verify", "-q", "HEAD"]).catch(() => "")).trim();
|
|
573
|
+
const { paths, deleted, sinceUsed } = await changedPaths(root2, since);
|
|
574
|
+
const realRoot = await realpath(root2);
|
|
575
|
+
const files = [];
|
|
576
|
+
const skipped = [];
|
|
577
|
+
let total = 0;
|
|
578
|
+
for (const path of paths.map(toSlash).sort()) {
|
|
579
|
+
const read2 = await readCandidate(root2, realRoot, path);
|
|
580
|
+
if (!read2.ok) {
|
|
581
|
+
if (read2.reason !== "gone") skipped.push({ path, reason: read2.reason });
|
|
582
|
+
continue;
|
|
583
|
+
}
|
|
584
|
+
if (files.length >= MAX_REVIEW_FILES || total + read2.content.length > MAX_REVIEW_TOTAL_CHARS) {
|
|
585
|
+
skipped.push({ path, reason: "size_cap" });
|
|
586
|
+
continue;
|
|
587
|
+
}
|
|
588
|
+
total += read2.content.length;
|
|
589
|
+
files.push({ path, content: read2.content });
|
|
590
|
+
}
|
|
591
|
+
return {
|
|
592
|
+
source: "git",
|
|
593
|
+
.../^[0-9a-f]{40}([0-9a-f]{24})?$/.test(commit) ? { commit } : {},
|
|
594
|
+
sinceUsed,
|
|
595
|
+
files,
|
|
596
|
+
skipped,
|
|
597
|
+
deleted: deleted.map(toSlash).filter((p) => !looksSecret(p) && p.length <= MAX_REVIEW_PATH_CHARS).slice(0, 1e3)
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
var SENDABLE = /* @__PURE__ */ new Set(["binary", "too_large", "size_cap", "lockfile"]);
|
|
601
|
+
function changesToSend(changes) {
|
|
602
|
+
return {
|
|
603
|
+
source: changes.source,
|
|
604
|
+
...changes.commit ? { commit: changes.commit } : {},
|
|
605
|
+
files: changes.files,
|
|
606
|
+
skipped: changes.skipped.filter((s) => SENDABLE.has(s.reason)).slice(0, 1e3),
|
|
607
|
+
deleted: changes.deleted
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// src/run-command.ts
|
|
612
|
+
import { spawn as nodeSpawn, spawnSync } from "node:child_process";
|
|
613
|
+
import crossSpawn from "cross-spawn";
|
|
614
|
+
var CommandError = class extends Error {
|
|
615
|
+
};
|
|
616
|
+
var SHELL_OPERATORS = /* @__PURE__ */ new Set(["|", "&", ";", "<", ">", "(", ")", "$", "`"]);
|
|
617
|
+
function splitCommand(command, platform = process.platform) {
|
|
618
|
+
const windows = platform === "win32";
|
|
619
|
+
const args = [];
|
|
620
|
+
let current;
|
|
621
|
+
let quote;
|
|
622
|
+
for (let i = 0; i < command.length; i++) {
|
|
623
|
+
const c = command[i];
|
|
624
|
+
if (quote === "'") {
|
|
625
|
+
if (c === "'") quote = void 0;
|
|
626
|
+
else current = (current ?? "") + c;
|
|
627
|
+
} else if (quote === '"') {
|
|
628
|
+
if (c === '"') quote = void 0;
|
|
629
|
+
else if (!windows && c === "\\" && i + 1 < command.length && '"\\$`'.includes(command[i + 1])) current = (current ?? "") + command[++i];
|
|
630
|
+
else current = (current ?? "") + c;
|
|
631
|
+
} else if (/\s/.test(c)) {
|
|
632
|
+
if (current !== void 0) args.push(current);
|
|
633
|
+
current = void 0;
|
|
634
|
+
} else if (c === "'" || c === '"') {
|
|
635
|
+
quote = c;
|
|
636
|
+
current ??= "";
|
|
637
|
+
} else if (!windows && c === "\\") {
|
|
638
|
+
if (i + 1 >= command.length) throw new CommandError("The command ends with a backslash.");
|
|
639
|
+
current = (current ?? "") + command[++i];
|
|
640
|
+
} else if (SHELL_OPERATORS.has(c)) {
|
|
641
|
+
throw new CommandError(
|
|
642
|
+
`Mivra runs the command directly, without a shell, so "${c}" can't be used unquoted. Put pipes, redirects or several steps in a script and run that, e.g. ./check.sh {input}.`
|
|
643
|
+
);
|
|
644
|
+
} else current = (current ?? "") + c;
|
|
645
|
+
}
|
|
646
|
+
if (quote) throw new CommandError(`The command has an unclosed ${quote === '"' ? "double" : "single"} quote.`);
|
|
647
|
+
if (current !== void 0) args.push(current);
|
|
648
|
+
if (args.length === 0) throw new CommandError("The command is empty.");
|
|
649
|
+
return args;
|
|
650
|
+
}
|
|
651
|
+
function fillPlaceholders(args, paths) {
|
|
652
|
+
return args.map((arg) => arg.replaceAll("{input}", paths.input ?? "{input}").replaceAll("{output}", paths.output ?? "{output}"));
|
|
653
|
+
}
|
|
654
|
+
var STDERR_KEEP_CHARS = 2e3;
|
|
655
|
+
var DRAIN_MS = 500;
|
|
656
|
+
var KILL_WAIT_MS = 2e3;
|
|
657
|
+
function windowsKillScript(pid, since) {
|
|
658
|
+
return [
|
|
659
|
+
`$since = [datetime]::Parse('${since.toISOString()}').ToUniversalTime().AddSeconds(-1)`,
|
|
660
|
+
"$all = @(Get-CimInstance Win32_Process | Where-Object { $_.CreationDate -and $_.CreationDate.ToUniversalTime() -ge $since })",
|
|
661
|
+
`$ids = @(${pid})`,
|
|
662
|
+
"$queue = [System.Collections.Generic.Queue[int]]::new(); $queue.Enqueue(" + pid + ")",
|
|
663
|
+
"while ($queue.Count -gt 0) { $p = $queue.Dequeue(); foreach ($c in $all) { if ($c.ParentProcessId -eq $p -and $ids -notcontains $c.ProcessId) { $ids += $c.ProcessId; $queue.Enqueue($c.ProcessId) } } }",
|
|
664
|
+
"foreach ($i in $ids) { if ($i -eq " + pid + " -or ($all | Where-Object ProcessId -eq $i)) { Stop-Process -Id $i -Force -ErrorAction SilentlyContinue } }"
|
|
665
|
+
].join("; ");
|
|
666
|
+
}
|
|
667
|
+
function killTree(child, startedAt) {
|
|
668
|
+
if (child.pid === void 0) return;
|
|
669
|
+
if (process.platform === "win32") {
|
|
670
|
+
const ps = spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", windowsKillScript(child.pid, startedAt)], { stdio: "ignore", windowsHide: true, timeout: 15e3 });
|
|
671
|
+
if (ps.error || ps.status !== 0) spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
try {
|
|
675
|
+
process.kill(-child.pid, "SIGKILL");
|
|
676
|
+
} catch {
|
|
677
|
+
child.kill("SIGKILL");
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
var active;
|
|
681
|
+
var stopCurrent = () => active && killTree(active.child, active.startedAt);
|
|
682
|
+
function runProgram(args, { cwd, stdin, limits, env = process.env }) {
|
|
683
|
+
return new Promise((resolve3) => {
|
|
684
|
+
const [file, ...rest] = args;
|
|
685
|
+
let child;
|
|
686
|
+
const startedAt = /* @__PURE__ */ new Date();
|
|
687
|
+
try {
|
|
688
|
+
const spawn3 = process.platform === "win32" ? crossSpawn : nodeSpawn;
|
|
689
|
+
child = spawn3(file, rest, { cwd, env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, detached: process.platform !== "win32" });
|
|
690
|
+
} catch (error2) {
|
|
691
|
+
return resolve3({ stdout: "", stderr: "", exitCode: null, error: "start_failed", startError: error2.message });
|
|
692
|
+
}
|
|
693
|
+
active = { child, startedAt };
|
|
694
|
+
const stdout = [];
|
|
695
|
+
let stderr = "";
|
|
696
|
+
let bytes = 0;
|
|
697
|
+
let error;
|
|
698
|
+
let startError;
|
|
699
|
+
let exitCode = null;
|
|
700
|
+
let settled = false;
|
|
701
|
+
const timers = [];
|
|
702
|
+
const finish = () => {
|
|
703
|
+
if (settled) return;
|
|
704
|
+
settled = true;
|
|
705
|
+
for (const timer of timers) clearTimeout(timer);
|
|
706
|
+
if (active?.child === child) active = void 0;
|
|
707
|
+
killTree(child, startedAt);
|
|
708
|
+
child.stdout?.destroy();
|
|
709
|
+
child.stderr?.destroy();
|
|
710
|
+
resolve3({ stdout: Buffer.concat(stdout).toString("utf8"), stderr: stderr.slice(-STDERR_KEEP_CHARS), exitCode: error ? null : exitCode, ...error ? { error } : {}, ...startError ? { startError } : {} });
|
|
711
|
+
};
|
|
712
|
+
const stop2 = (reason) => {
|
|
713
|
+
if (error || settled) return;
|
|
714
|
+
error = reason;
|
|
715
|
+
killTree(child, startedAt);
|
|
716
|
+
timers.push(setTimeout(finish, KILL_WAIT_MS));
|
|
717
|
+
};
|
|
718
|
+
const count = (chunk) => {
|
|
719
|
+
bytes += chunk.length;
|
|
720
|
+
if (bytes > limits.maxOutputBytes) stop2("output_limit");
|
|
721
|
+
return bytes <= limits.maxOutputBytes;
|
|
722
|
+
};
|
|
723
|
+
child.stdout.on("data", (chunk) => {
|
|
724
|
+
if (count(chunk)) stdout.push(chunk);
|
|
725
|
+
});
|
|
726
|
+
child.stderr.setEncoding("utf8");
|
|
727
|
+
child.stderr.on("data", (chunk) => {
|
|
728
|
+
if (count(Buffer.from(chunk))) stderr = (stderr + chunk).slice(-STDERR_KEEP_CHARS * 2);
|
|
729
|
+
});
|
|
730
|
+
child.once("error", (e) => {
|
|
731
|
+
startError = e.message;
|
|
732
|
+
error ??= "start_failed";
|
|
733
|
+
finish();
|
|
734
|
+
});
|
|
735
|
+
child.once("exit", (code) => {
|
|
736
|
+
exitCode = code;
|
|
737
|
+
timers.push(setTimeout(finish, DRAIN_MS));
|
|
738
|
+
});
|
|
739
|
+
child.once("close", finish);
|
|
740
|
+
timers.push(setTimeout(() => stop2("timeout"), limits.timeoutMs));
|
|
741
|
+
child.stdin.on("error", () => {
|
|
742
|
+
});
|
|
743
|
+
child.stdin.end(stdin);
|
|
744
|
+
});
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
// src/watch.ts
|
|
748
|
+
import { lstatSync, readdirSync, watch } from "node:fs";
|
|
749
|
+
import { join as join5, relative as relative2 } from "node:path";
|
|
750
|
+
var IGNORED_DIRS = /* @__PURE__ */ new Set([
|
|
751
|
+
".git",
|
|
752
|
+
"node_modules",
|
|
753
|
+
"dist",
|
|
754
|
+
"build",
|
|
755
|
+
"target",
|
|
756
|
+
"out",
|
|
757
|
+
".next",
|
|
758
|
+
".nuxt",
|
|
759
|
+
".cache",
|
|
760
|
+
".turbo",
|
|
761
|
+
"__pycache__",
|
|
762
|
+
".pytest_cache",
|
|
763
|
+
".mypy_cache",
|
|
764
|
+
".venv",
|
|
765
|
+
"venv",
|
|
766
|
+
"coverage"
|
|
767
|
+
]);
|
|
768
|
+
var MAX_WATCHED_DIRS = 2e3;
|
|
769
|
+
function isIgnoredEntry(name) {
|
|
770
|
+
if (!name) return false;
|
|
771
|
+
if (IGNORED_DIRS.has(name)) return true;
|
|
772
|
+
if (name === ".DS_Store" || name.endsWith("~") || name.endsWith(".swp") || name.endsWith(".swo") || name.endsWith(".tmp")) return true;
|
|
773
|
+
if (name.startsWith("#") && name.endsWith("#")) return true;
|
|
774
|
+
return false;
|
|
775
|
+
}
|
|
776
|
+
function isIgnoredPath(relativePath) {
|
|
777
|
+
if (!relativePath || relativePath === ".") return false;
|
|
778
|
+
return relativePath.split(/[/\\]+/).some((segment) => segment !== "" && isIgnoredEntry(segment));
|
|
779
|
+
}
|
|
780
|
+
function watchDirectory(root2, onChange, { maxDirs = MAX_WATCHED_DIRS, onWarning } = {}) {
|
|
781
|
+
const watchers = /* @__PURE__ */ new Map();
|
|
782
|
+
let closed = false;
|
|
783
|
+
let warnedLimit = false;
|
|
784
|
+
let warnedError = false;
|
|
785
|
+
const warnLimit = () => {
|
|
786
|
+
if (warnedLimit) return;
|
|
787
|
+
warnedLimit = true;
|
|
788
|
+
onWarning?.(`Watch limit reached (${maxDirs} directories); changes in deeper folders may not trigger automatic re-runs.`);
|
|
789
|
+
};
|
|
790
|
+
const warnError = () => {
|
|
791
|
+
if (warnedError) return;
|
|
792
|
+
warnedError = true;
|
|
793
|
+
onWarning?.(`Couldn't watch all directories in ${root2}; some file changes may not trigger automatic re-runs.`);
|
|
794
|
+
};
|
|
795
|
+
const removeDir = (dir) => {
|
|
796
|
+
const existing = watchers.get(dir);
|
|
797
|
+
if (!existing) return;
|
|
798
|
+
watchers.delete(dir);
|
|
799
|
+
try {
|
|
800
|
+
existing.close();
|
|
801
|
+
} catch {
|
|
802
|
+
}
|
|
803
|
+
};
|
|
804
|
+
const addDir = (dir) => {
|
|
805
|
+
if (closed || watchers.has(dir)) return;
|
|
806
|
+
if (watchers.size >= maxDirs) {
|
|
807
|
+
warnLimit();
|
|
808
|
+
return;
|
|
809
|
+
}
|
|
810
|
+
let watcher;
|
|
811
|
+
try {
|
|
812
|
+
watcher = watch(dir, { persistent: true }, (_event, filename) => {
|
|
813
|
+
if (closed) return;
|
|
814
|
+
if (typeof filename === "string" && filename.length > 0) {
|
|
815
|
+
if (isIgnoredEntry(filename)) return;
|
|
816
|
+
const full = join5(dir, filename);
|
|
817
|
+
const rel2 = relative2(root2, full);
|
|
818
|
+
if (isIgnoredPath(rel2)) return;
|
|
819
|
+
try {
|
|
820
|
+
const stat = lstatSync(full);
|
|
821
|
+
if (!stat.isSymbolicLink() && stat.isDirectory()) addTree(full);
|
|
822
|
+
} catch {
|
|
823
|
+
removeDir(full);
|
|
824
|
+
}
|
|
825
|
+
onChange(rel2);
|
|
826
|
+
return;
|
|
827
|
+
}
|
|
828
|
+
const rel = relative2(root2, dir);
|
|
829
|
+
if (!isIgnoredPath(rel)) onChange(rel || ".");
|
|
830
|
+
});
|
|
831
|
+
} catch {
|
|
832
|
+
warnError();
|
|
833
|
+
return;
|
|
834
|
+
}
|
|
835
|
+
watcher.on("error", () => removeDir(dir));
|
|
836
|
+
watchers.set(dir, watcher);
|
|
837
|
+
};
|
|
838
|
+
const addTree = (dir) => {
|
|
839
|
+
if (closed) return;
|
|
840
|
+
if (watchers.size >= maxDirs) {
|
|
841
|
+
warnLimit();
|
|
842
|
+
return;
|
|
843
|
+
}
|
|
844
|
+
addDir(dir);
|
|
845
|
+
let entries;
|
|
846
|
+
try {
|
|
847
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
848
|
+
} catch {
|
|
849
|
+
return;
|
|
850
|
+
}
|
|
851
|
+
for (const entry of entries) {
|
|
852
|
+
if (closed) return;
|
|
853
|
+
if (entry.isSymbolicLink() || !entry.isDirectory()) continue;
|
|
854
|
+
if (isIgnoredEntry(entry.name)) continue;
|
|
855
|
+
if (watchers.size >= maxDirs) {
|
|
856
|
+
warnLimit();
|
|
857
|
+
return;
|
|
858
|
+
}
|
|
859
|
+
addTree(join5(dir, entry.name));
|
|
860
|
+
}
|
|
861
|
+
};
|
|
862
|
+
addTree(root2);
|
|
863
|
+
return {
|
|
864
|
+
close() {
|
|
865
|
+
closed = true;
|
|
866
|
+
for (const watcher of watchers.values()) {
|
|
867
|
+
try {
|
|
868
|
+
watcher.close();
|
|
869
|
+
} catch {
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
watchers.clear();
|
|
873
|
+
}
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
function createWatchScheduler({
|
|
877
|
+
debounceMs,
|
|
878
|
+
run
|
|
879
|
+
}) {
|
|
880
|
+
let running2 = false;
|
|
881
|
+
let pending = false;
|
|
882
|
+
let stopped = false;
|
|
883
|
+
let timer;
|
|
884
|
+
let inFlight;
|
|
885
|
+
const schedule = () => {
|
|
886
|
+
if (stopped) return;
|
|
887
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
888
|
+
timer = setTimeout(() => {
|
|
889
|
+
timer = void 0;
|
|
890
|
+
void execute();
|
|
891
|
+
}, debounceMs);
|
|
892
|
+
};
|
|
893
|
+
const execute = async () => {
|
|
894
|
+
if (stopped || running2) return;
|
|
895
|
+
running2 = true;
|
|
896
|
+
pending = false;
|
|
897
|
+
const current = (async () => {
|
|
898
|
+
try {
|
|
899
|
+
await run();
|
|
900
|
+
} finally {
|
|
901
|
+
running2 = false;
|
|
902
|
+
if (!stopped && pending) {
|
|
903
|
+
pending = false;
|
|
904
|
+
schedule();
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
})();
|
|
908
|
+
inFlight = current;
|
|
909
|
+
await current;
|
|
910
|
+
if (inFlight === current) inFlight = void 0;
|
|
911
|
+
};
|
|
912
|
+
return {
|
|
913
|
+
trigger() {
|
|
914
|
+
if (stopped) return;
|
|
915
|
+
if (running2) {
|
|
916
|
+
pending = true;
|
|
917
|
+
return;
|
|
918
|
+
}
|
|
919
|
+
schedule();
|
|
920
|
+
},
|
|
921
|
+
async runNow() {
|
|
922
|
+
if (stopped) return;
|
|
923
|
+
if (timer !== void 0) {
|
|
924
|
+
clearTimeout(timer);
|
|
925
|
+
timer = void 0;
|
|
926
|
+
}
|
|
927
|
+
if (running2) {
|
|
928
|
+
pending = true;
|
|
929
|
+
await inFlight;
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
await execute();
|
|
933
|
+
},
|
|
934
|
+
stop() {
|
|
935
|
+
stopped = true;
|
|
936
|
+
pending = false;
|
|
937
|
+
if (timer !== void 0) {
|
|
938
|
+
clearTimeout(timer);
|
|
939
|
+
timer = void 0;
|
|
940
|
+
}
|
|
941
|
+
},
|
|
942
|
+
async waitForIdle() {
|
|
943
|
+
await inFlight;
|
|
944
|
+
}
|
|
945
|
+
};
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
// src/project.ts
|
|
949
|
+
var LINK_FILE = ".mivra.json";
|
|
950
|
+
var LinkFile = z3.object({
|
|
951
|
+
course: z3.string().min(1),
|
|
952
|
+
/** The learner's command, e.g. `./build/mycc {input}`. */
|
|
953
|
+
run: z3.string().min(1),
|
|
954
|
+
/** For cases that run the program's output (e.g. generated assembly): a command with `{output}`. */
|
|
955
|
+
runOutput: z3.string().min(1).optional()
|
|
956
|
+
});
|
|
957
|
+
var MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
|
|
958
|
+
var ProjectError = class extends Error {
|
|
959
|
+
};
|
|
960
|
+
async function server(dataDir) {
|
|
961
|
+
const remote = readRemoteServer(dataDir);
|
|
962
|
+
if (remote) return { ...remote, remote: true };
|
|
963
|
+
const local = await running(dataDir);
|
|
964
|
+
if (!local) throw new ProjectError("Mivra isn't running. Start it with `mivra start --detach`, then try again.");
|
|
965
|
+
try {
|
|
966
|
+
return { url: local.url, token: readFileSync3(join6(dataDir, TOKEN_FILE), "utf8").trim(), remote: false };
|
|
967
|
+
} catch {
|
|
968
|
+
throw new ProjectError(`Couldn't read Mivra's API token from ${join6(dataDir, TOKEN_FILE)}.`);
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
function client({ url, token, remote }) {
|
|
972
|
+
const headers = { authorization: `Bearer ${token}`, "content-type": "application/json" };
|
|
973
|
+
const relink = `Get its token from Settings \u2192 Connect a CLI, or \`mivra token\` where it runs, and run \`mivra link --server ${url}\` again.`;
|
|
974
|
+
return async (path, init = {}, timeoutMs = 3e4, abortSignal) => {
|
|
975
|
+
let res;
|
|
976
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
977
|
+
const signal = abortSignal ? AbortSignal.any([timeout, abortSignal]) : timeout;
|
|
978
|
+
try {
|
|
979
|
+
res = await fetch(`${url}/api${path}`, { ...init, headers, redirect: "manual", signal });
|
|
980
|
+
} catch (error) {
|
|
981
|
+
if (abortSignal?.aborted) throw error;
|
|
982
|
+
throw new ProjectError(remote ? `Couldn't reach Mivra at ${url}. Check it's running and that this computer can reach it.` : `Couldn't reach Mivra at ${url}.`);
|
|
983
|
+
}
|
|
984
|
+
if (res.ok) return res.json();
|
|
985
|
+
if (res.status >= 300 && res.status < 400) throw redirected(url, res);
|
|
986
|
+
const message = (await res.json().catch(() => ({}))).error;
|
|
987
|
+
if (remote && res.status === 401) throw new ProjectError(`Mivra at ${url} didn't accept the token. ${relink}`);
|
|
988
|
+
if (remote && res.status === 403 && message === "Host not allowed") throw hostRefused(url);
|
|
989
|
+
throw new ProjectError(typeof message === "string" ? message : `Mivra answered ${res.status}.`);
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
async function connect(dataDir) {
|
|
993
|
+
const found = await server(dataDir);
|
|
994
|
+
return { url: found.url, remote: found.remote, call: client(found) };
|
|
995
|
+
}
|
|
996
|
+
var hostRefused = (url) => new ProjectError(`Mivra at ${url} doesn't accept requests for ${new URL(url).hostname}. Add it to MIVRA_ALLOWED_HOSTS where Mivra runs, and restart it.`);
|
|
997
|
+
var redirected = (url, res) => {
|
|
998
|
+
const location = res.headers.get("location");
|
|
999
|
+
return new ProjectError(`${url} redirects${location ? ` to ${location}` : ""}, which Mivra doesn't follow. Use Mivra's own address: \`mivra link --server <url>\`.`);
|
|
1000
|
+
};
|
|
1001
|
+
async function isMivra(url) {
|
|
1002
|
+
let res;
|
|
1003
|
+
try {
|
|
1004
|
+
res = await fetch(`${url}/api/health`, { redirect: "manual", signal: AbortSignal.timeout(1e4) });
|
|
1005
|
+
} catch {
|
|
1006
|
+
return false;
|
|
1007
|
+
}
|
|
1008
|
+
if (res.status >= 300 && res.status < 400) throw redirected(url, res);
|
|
1009
|
+
const body = await res.json().catch(() => ({}));
|
|
1010
|
+
if (res.status === 403 && body.error === "Host not allowed") throw hostRefused(url);
|
|
1011
|
+
return res.ok && body.ok === true;
|
|
1012
|
+
}
|
|
1013
|
+
async function connectRemote(url, dataDir, readToken, io) {
|
|
1014
|
+
if (!await isMivra(url)) throw new ProjectError(`There's no Mivra answering at ${url}. Check the address, and that Mivra is running there.`);
|
|
1015
|
+
let input;
|
|
1016
|
+
try {
|
|
1017
|
+
input = await readToken();
|
|
1018
|
+
} catch (error) {
|
|
1019
|
+
throw new ProjectError(error.message);
|
|
1020
|
+
}
|
|
1021
|
+
const token = ServerToken.safeParse(input);
|
|
1022
|
+
if (!token.success) throw new ProjectError(input ? token.error.issues[0].message : "No token given.");
|
|
1023
|
+
await client({ url, token: token.data, remote: true })("/settings/tasks");
|
|
1024
|
+
saveRemoteServer(dataDir, { url, token: token.data });
|
|
1025
|
+
io.out(`Connected to Mivra at ${url}. Its address and token are saved in ${join6(dataDir, CREDENTIALS_FILE)}, not in .mivra.json.`);
|
|
1026
|
+
const { hostname, protocol } = new URL(url);
|
|
1027
|
+
if (protocol === "http:" && !["localhost", "127.0.0.1", "[::1]"].includes(hostname)) {
|
|
1028
|
+
io.err("The token goes over plain HTTP to that address. That's only safe on a network that encrypts traffic itself, such as a tailnet.");
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
function checkCommand(command, where) {
|
|
1032
|
+
try {
|
|
1033
|
+
splitCommand(command);
|
|
1034
|
+
} catch (error) {
|
|
1035
|
+
if (error instanceof CommandError) throw new ProjectError(`${where}: ${error.message}`);
|
|
1036
|
+
throw error;
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
function failed(error, io) {
|
|
1040
|
+
if (error instanceof ProjectError) io.err(error.message);
|
|
1041
|
+
else if (error instanceof z3.ZodError) io.err("Mivra answered with something this `mivra` doesn't understand. Update it to the same version as the running Mivra.");
|
|
1042
|
+
else throw error;
|
|
1043
|
+
return 1;
|
|
1044
|
+
}
|
|
1045
|
+
async function link({ course, run, runOutput, server: url, local }, { dataDir, cwd, readToken }, io) {
|
|
1046
|
+
try {
|
|
1047
|
+
if (run !== void 0) checkCommand(run, "--run");
|
|
1048
|
+
if (runOutput !== void 0) {
|
|
1049
|
+
checkCommand(runOutput, "--run-output");
|
|
1050
|
+
if (!runOutput.includes("{output}")) throw new ProjectError(`--run-output needs {output} where the path to your program's output goes, e.g. "./run-asm.sh {output}".`);
|
|
1051
|
+
}
|
|
1052
|
+
if (local) io.out(removeRemoteServer(dataDir) ? "Forgot the remote Mivra: link and check use the one running on this computer again." : "Link and check already use the Mivra running on this computer.");
|
|
1053
|
+
if (url) await connectRemote(url, dataDir, readToken, io);
|
|
1054
|
+
if (course === void 0 || run === void 0) return 0;
|
|
1055
|
+
const { call, url: at, remote } = await connect(dataDir);
|
|
1056
|
+
const found = CourseView.parse(await call(`/courses/${encodeURIComponent(course)}`));
|
|
1057
|
+
if (found.kind !== "project") throw new ProjectError(`"${found.goal}" isn't a project course, so there's nothing to check from a repository.`);
|
|
1058
|
+
const path = join6(cwd, LINK_FILE);
|
|
1059
|
+
const file = { course: found.id, run, ...runOutput ? { runOutput } : {} };
|
|
1060
|
+
writeFileSync2(path, `${JSON.stringify(file, null, 2)}
|
|
1061
|
+
`);
|
|
1062
|
+
approve(dataDir, cwd, file);
|
|
1063
|
+
io.out(`Linked this folder to "${found.goal}"${remote ? ` on Mivra at ${at}` : ""} in ${path}. It holds no secrets, so you can commit it: a checkout it's cloned into asks before \`mivra check\` runs its commands.`);
|
|
1064
|
+
io.out(`Mivra will run: ${run}${run.includes("{input}") ? "" : " (each case's input comes on stdin; add {input} to get it as a file path too)"}`);
|
|
1065
|
+
io.out("Run `mivra check` here to check the current milestone.");
|
|
1066
|
+
return 0;
|
|
1067
|
+
} catch (error) {
|
|
1068
|
+
return failed(error, io);
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
function findLink(cwd) {
|
|
1072
|
+
let dir = resolve(cwd);
|
|
1073
|
+
for (; ; ) {
|
|
1074
|
+
const path = join6(dir, LINK_FILE);
|
|
1075
|
+
let text;
|
|
1076
|
+
try {
|
|
1077
|
+
text = readFileSync3(path, "utf8");
|
|
1078
|
+
} catch {
|
|
1079
|
+
}
|
|
1080
|
+
if (text !== void 0) {
|
|
1081
|
+
let parsed;
|
|
1082
|
+
try {
|
|
1083
|
+
parsed = LinkFile.safeParse(JSON.parse(text));
|
|
1084
|
+
} catch {
|
|
1085
|
+
throw new ProjectError(`${path} isn't valid JSON. Run \`mivra link\` again to rewrite it.`);
|
|
1086
|
+
}
|
|
1087
|
+
if (!parsed.success) throw new ProjectError(`${path} needs "course" and "run". Run \`mivra link\` again to rewrite it.`);
|
|
1088
|
+
return { path, file: parsed.data };
|
|
1089
|
+
}
|
|
1090
|
+
const parent = dirname(dir);
|
|
1091
|
+
if (parent === dir) throw new ProjectError(`No ${LINK_FILE} here or above. Link this folder to a project course first: \`mivra link <course> --run "<command>"\`.`);
|
|
1092
|
+
dir = parent;
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
async function ensureApproved({ path, file }, { dataDir, approveNow, ask }, io) {
|
|
1096
|
+
const root2 = dirname(path);
|
|
1097
|
+
if (isApproved(dataDir, root2, file)) return;
|
|
1098
|
+
if (!approveNow) {
|
|
1099
|
+
io.err(`${path} asks to run commands you haven't approved for this folder (it's new here, or its course or commands changed since you last approved them):`);
|
|
1100
|
+
io.err(` course: ${shown(file.course)}`);
|
|
1101
|
+
io.err(` run: ${shown(file.run)}`);
|
|
1102
|
+
if (file.runOutput !== void 0) io.err(` run-output: ${shown(file.runOutput)}`);
|
|
1103
|
+
io.err(`They'd run from ${root2} with your permissions. Only approve them if you trust them.`);
|
|
1104
|
+
if (!ask) throw new ProjectError("Nothing was run. To approve these commands for this folder, run `mivra check --approve`, or rewrite them with `mivra link`.");
|
|
1105
|
+
if (!await ask("Run them now, and approve them for this folder? [y/N] ")) throw new ProjectError("Nothing was run.");
|
|
1106
|
+
}
|
|
1107
|
+
approve(dataDir, root2, file);
|
|
1108
|
+
io.err(`Approved these commands for ${root2}. Mivra asks again if .mivra.json changes them.`);
|
|
1109
|
+
}
|
|
1110
|
+
function caseResult(run) {
|
|
1111
|
+
const stdout = normaliseOutput(run.stdout);
|
|
1112
|
+
const stderr = run.stderr.slice(-MAX_MILESTONE_STDERR_CHARS);
|
|
1113
|
+
return {
|
|
1114
|
+
stdout: stdout.slice(0, MAX_CASE_OUTPUT_CHARS),
|
|
1115
|
+
...stdout.length > MAX_CASE_OUTPUT_CHARS ? { truncated: true } : {},
|
|
1116
|
+
...stderr ? { stderr } : {},
|
|
1117
|
+
exitCode: run.exitCode,
|
|
1118
|
+
...run.error ? { error: run.error } : {}
|
|
1119
|
+
};
|
|
1120
|
+
}
|
|
1121
|
+
async function runCase(link2, testCase, { cwd, limits }) {
|
|
1122
|
+
const dir = mkdtempSync(join6(tmpdir(), "mivra-check-"));
|
|
1123
|
+
try {
|
|
1124
|
+
const input = join6(dir, "input");
|
|
1125
|
+
writeFileSync2(input, testCase.input);
|
|
1126
|
+
const first = await runProgram(fillPlaceholders(splitCommand(link2.run), { input }), { cwd, stdin: testCase.input, limits });
|
|
1127
|
+
if (testCase.compare !== "run_output" || first.error || first.exitCode !== 0) return { result: caseResult(first), startError: first.startError };
|
|
1128
|
+
if (!link2.runOutput) return { result: { stdout: "", exitCode: null, error: "no_run_output_command" } };
|
|
1129
|
+
const output = join6(dir, "output");
|
|
1130
|
+
writeFileSync2(output, first.stdout);
|
|
1131
|
+
const second = await runProgram(fillPlaceholders(splitCommand(link2.runOutput), { input, output }), { cwd, stdin: "", limits });
|
|
1132
|
+
return { result: caseResult(second), startError: second.startError };
|
|
1133
|
+
} finally {
|
|
1134
|
+
rmSync3(dir, { recursive: true, force: true });
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
var ERROR_TEXT = {
|
|
1138
|
+
timeout: "stopped: it took longer than the time limit",
|
|
1139
|
+
output_limit: "stopped: it printed more than the output limit",
|
|
1140
|
+
start_failed: "couldn't start",
|
|
1141
|
+
no_run_output_command: 'this case runs your program\'s output: set a command for that with `mivra link <course> --run "\u2026" --run-output "\u2026 {output}"`'
|
|
1142
|
+
};
|
|
1143
|
+
var excerpt = (text, lines = 8) => {
|
|
1144
|
+
const all = text.split("\n");
|
|
1145
|
+
const shown2 = all.slice(0, lines).map((line) => ` ${line}`);
|
|
1146
|
+
return [...shown2, ...all.length > lines ? [` \u2026 (${all.length - lines} more lines)`] : []].join("\n");
|
|
1147
|
+
};
|
|
1148
|
+
var CHECK_TIMEOUT_MS = 5 * 6e4;
|
|
1149
|
+
var kb = (chars) => `${(chars / 1024).toFixed(1)} KB`;
|
|
1150
|
+
var SKIP_TEXT = {
|
|
1151
|
+
secret: "looks like it holds a secret: never sent, not even its name",
|
|
1152
|
+
not_a_file: "a link or folder: never followed",
|
|
1153
|
+
binary: "binary",
|
|
1154
|
+
too_large: "too large to review",
|
|
1155
|
+
size_cap: "over the size Mivra sends for one check",
|
|
1156
|
+
lockfile: "a lockfile"
|
|
1157
|
+
};
|
|
1158
|
+
function describeChanges(changes, io, { full }) {
|
|
1159
|
+
if (changes.source === "none") {
|
|
1160
|
+
io.out(changes.note ?? "No files to send.");
|
|
1161
|
+
return;
|
|
1162
|
+
}
|
|
1163
|
+
const total = changes.files.reduce((sum, f) => sum + f.content.length, 0);
|
|
1164
|
+
const what = changes.sinceUsed ? "changed since the last passed milestone" : "in the repository (no earlier passed milestone to compare with)";
|
|
1165
|
+
if (!full) {
|
|
1166
|
+
io.out(`Sending ${changes.files.length} ${changes.files.length === 1 ? "file" : "files"} (${kb(total)}) ${what} for review${changes.skipped.length ? `, leaving out ${changes.skipped.length}` : ""}. See them with \`mivra check --dry-run\`.`);
|
|
1167
|
+
return;
|
|
1168
|
+
}
|
|
1169
|
+
io.out(changes.files.length === 0 ? `No files ${what} to send.` : `Files ${what} that would be sent for review (${changes.files.length}, ${kb(total)}):`);
|
|
1170
|
+
for (const file of changes.files) io.out(` ${file.path} (${kb(file.content.length)})`);
|
|
1171
|
+
if (changes.skipped.length > 0) {
|
|
1172
|
+
io.out("Not sent:");
|
|
1173
|
+
for (const skip of changes.skipped) io.out(` ${skip.path} (${SKIP_TEXT[skip.reason]})`);
|
|
1174
|
+
}
|
|
1175
|
+
if (changes.deleted.length > 0) io.out(`Named as deleted: ${changes.deleted.join(", ")}`);
|
|
1176
|
+
if (changes.commit) io.out(`Commit: ${changes.commit}`);
|
|
1177
|
+
}
|
|
1178
|
+
var CRITERIA = [
|
|
1179
|
+
["noHardCodedOutputs", "Computes its output"],
|
|
1180
|
+
["concept", "Shows the milestone's concept"],
|
|
1181
|
+
["quality", "Code quality"]
|
|
1182
|
+
];
|
|
1183
|
+
function showReview(review, io) {
|
|
1184
|
+
if (review.status === "skipped") {
|
|
1185
|
+
io.out(review.reason === "tests_failed" ? "Review: not yet, since the tests must pass first." : "Review: nothing was sent to review, so the milestone can't pass yet.");
|
|
1186
|
+
return;
|
|
1187
|
+
}
|
|
1188
|
+
if (review.status === "failed") {
|
|
1189
|
+
io.out(`Review: it didn't finish (${review.error}). Run mivra check again.`);
|
|
1190
|
+
return;
|
|
1191
|
+
}
|
|
1192
|
+
const { review: verdict } = review;
|
|
1193
|
+
io.out(`Review (judged by a model, ${verdict.model}): ${verdict.approved ? "approved" : "changes requested"}`);
|
|
1194
|
+
for (const [key, label] of CRITERIA) io.out(` ${verdict[key].passed ? "pass" : "FAIL"} ${label}: ${verdict[key].note}`);
|
|
1195
|
+
io.out(` ${verdict.summary}`);
|
|
1196
|
+
for (const suggestion of verdict.suggestions) io.out(` - ${suggestion}`);
|
|
1197
|
+
if (!verdict.approved) io.out(" You can dispute the verdict from the milestone in Mivra.");
|
|
1198
|
+
}
|
|
1199
|
+
var WATCH_DEBOUNCE_MS = 500;
|
|
1200
|
+
async function runSingleCheck(found, { timeoutS, dryRun, dataDir, signal }, io) {
|
|
1201
|
+
const root2 = dirname(found.path);
|
|
1202
|
+
const { call, url, remote } = await connect(dataDir);
|
|
1203
|
+
if (signal?.aborted) return 0;
|
|
1204
|
+
if (remote) io.out(`Checking against Mivra at ${url}; your program runs here.`);
|
|
1205
|
+
const milestone = MilestoneCases.parse(await call(`/courses/${encodeURIComponent(found.file.course)}/milestone`, {}, 3e4, signal));
|
|
1206
|
+
if (signal?.aborted) return 0;
|
|
1207
|
+
const count = milestone.checkType === "review" ? "checked by review" : `${milestone.cases.length} ${milestone.cases.length === 1 ? "case" : "cases"}`;
|
|
1208
|
+
io.out(`Milestone ${milestone.position}: ${milestone.title} (${count})`);
|
|
1209
|
+
const changes = await collectChanges(root2, milestone.since);
|
|
1210
|
+
if (signal?.aborted) return 0;
|
|
1211
|
+
if (dryRun) {
|
|
1212
|
+
if (milestone.cases.length > 0) io.out(`A check would run your command on ${milestone.cases.length} ${milestone.cases.length === 1 ? "case" : "cases"} and send what it printed.`);
|
|
1213
|
+
describeChanges(changes, io, { full: true });
|
|
1214
|
+
io.out("Nothing was run or sent.");
|
|
1215
|
+
return 0;
|
|
1216
|
+
}
|
|
1217
|
+
const limits = { timeoutMs: timeoutS * 1e3, maxOutputBytes: MAX_OUTPUT_BYTES };
|
|
1218
|
+
const results = [];
|
|
1219
|
+
for (const testCase of milestone.cases) {
|
|
1220
|
+
if (signal?.aborted) return 0;
|
|
1221
|
+
const { result, startError } = await runCase(found.file, testCase, { cwd: root2, limits });
|
|
1222
|
+
if (signal?.aborted) return 0;
|
|
1223
|
+
results.push(result);
|
|
1224
|
+
if (startError) {
|
|
1225
|
+
io.err(`Couldn't run your command (${startError}). Check the commands in ${found.path}; they run from ${root2}.`);
|
|
1226
|
+
return 1;
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
describeChanges(changes, io, { full: false });
|
|
1230
|
+
const body = { results, revision: milestone.revision, ...changesToSend(changes) };
|
|
1231
|
+
const graded = MilestoneCheckResult.parse(
|
|
1232
|
+
await call(`/artifacts/${encodeURIComponent(milestone.artifactId)}/checks`, { method: "POST", body: JSON.stringify(body) }, CHECK_TIMEOUT_MS, signal)
|
|
1233
|
+
);
|
|
1234
|
+
if (signal?.aborted) return 0;
|
|
1235
|
+
milestone.cases.forEach((testCase, i) => {
|
|
1236
|
+
const passed2 = graded.grade.cases[i]?.passed ?? false;
|
|
1237
|
+
io.out(` ${passed2 ? "pass" : "FAIL"} ${testCase.name}`);
|
|
1238
|
+
if (passed2) return;
|
|
1239
|
+
const result = results[i];
|
|
1240
|
+
if (result.error) io.out(` ${ERROR_TEXT[result.error]}`);
|
|
1241
|
+
else {
|
|
1242
|
+
if (result.exitCode !== 0) io.out(` exited with code ${result.exitCode}`);
|
|
1243
|
+
io.out(` expected:
|
|
1244
|
+
${excerpt(graded.expected[i] ?? "")}`);
|
|
1245
|
+
io.out(` got:${result.stdout ? `
|
|
1246
|
+
${excerpt(result.stdout)}` : " (nothing)"}${result.truncated ? "\n \u2026 (cut short)" : ""}`);
|
|
1247
|
+
}
|
|
1248
|
+
if (result.stderr) io.out(` stderr:
|
|
1249
|
+
${excerpt(result.stderr, 4)}`);
|
|
1250
|
+
});
|
|
1251
|
+
const { passed, total } = graded.grade;
|
|
1252
|
+
if (total > 0) io.out(passed === total ? `All ${total} cases passed.` : `${passed} of ${total} cases passed.`);
|
|
1253
|
+
showReview(graded.review, io);
|
|
1254
|
+
io.out(graded.passed ? "Milestone passed. Recorded in Mivra." : "Not passed yet. Recorded in Mivra.");
|
|
1255
|
+
return graded.passed ? 0 : 1;
|
|
1256
|
+
}
|
|
1257
|
+
async function check({ timeoutS, dryRun = false, approve: approveNow = false, watch: watch2 = false }, { dataDir, cwd, ask, watchDebounceMs = WATCH_DEBOUNCE_MS, signal }, io) {
|
|
1258
|
+
if (!watch2) {
|
|
1259
|
+
const onInterrupt = () => {
|
|
1260
|
+
stopCurrent();
|
|
1261
|
+
process.exit(130);
|
|
1262
|
+
};
|
|
1263
|
+
process.once("SIGINT", onInterrupt);
|
|
1264
|
+
try {
|
|
1265
|
+
const found = findLink(cwd);
|
|
1266
|
+
checkCommand(found.file.run, `"run" in ${found.path}`);
|
|
1267
|
+
if (found.file.runOutput) checkCommand(found.file.runOutput, `"runOutput" in ${found.path}`);
|
|
1268
|
+
if (!dryRun) await ensureApproved(found, { dataDir, approveNow, ask }, io);
|
|
1269
|
+
return await runSingleCheck(found, { timeoutS, dryRun, dataDir, signal }, io);
|
|
1270
|
+
} catch (error) {
|
|
1271
|
+
return failed(error, io);
|
|
1272
|
+
} finally {
|
|
1273
|
+
process.removeListener("SIGINT", onInterrupt);
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
let initialFound;
|
|
1277
|
+
try {
|
|
1278
|
+
initialFound = findLink(cwd);
|
|
1279
|
+
checkCommand(initialFound.file.run, `"run" in ${initialFound.path}`);
|
|
1280
|
+
if (initialFound.file.runOutput) checkCommand(initialFound.file.runOutput, `"runOutput" in ${initialFound.path}`);
|
|
1281
|
+
await ensureApproved(initialFound, { dataDir, approveNow, ask }, io);
|
|
1282
|
+
} catch (error) {
|
|
1283
|
+
return failed(error, io);
|
|
1284
|
+
}
|
|
1285
|
+
const root2 = dirname(initialFound.path);
|
|
1286
|
+
const controller = new AbortController();
|
|
1287
|
+
let watcher;
|
|
1288
|
+
let stopping = false;
|
|
1289
|
+
let finishWatch;
|
|
1290
|
+
const done = new Promise((resolve3) => {
|
|
1291
|
+
finishWatch = resolve3;
|
|
1292
|
+
});
|
|
1293
|
+
let firstRun = true;
|
|
1294
|
+
const scheduler = createWatchScheduler({
|
|
1295
|
+
debounceMs: watchDebounceMs,
|
|
1296
|
+
run: async () => {
|
|
1297
|
+
if (stopping) return;
|
|
1298
|
+
const isInitial = firstRun;
|
|
1299
|
+
firstRun = false;
|
|
1300
|
+
try {
|
|
1301
|
+
let current = initialFound;
|
|
1302
|
+
if (!isInitial) {
|
|
1303
|
+
io.out("\nChanges detected \u2014 re-running check\u2026");
|
|
1304
|
+
current = findLink(root2);
|
|
1305
|
+
if (dirname(current.path) !== root2) {
|
|
1306
|
+
throw new ProjectError(`${initialFound.path} is no longer there. Run \`mivra link\` again.`);
|
|
1307
|
+
}
|
|
1308
|
+
checkCommand(current.file.run, `"run" in ${current.path}`);
|
|
1309
|
+
if (current.file.runOutput) checkCommand(current.file.runOutput, `"runOutput" in ${current.path}`);
|
|
1310
|
+
await ensureApproved(current, { dataDir, approveNow: false }, io);
|
|
1311
|
+
}
|
|
1312
|
+
await runSingleCheck(current, { timeoutS, dryRun: false, dataDir, signal: controller.signal }, io);
|
|
1313
|
+
} catch (error) {
|
|
1314
|
+
if (!stopping && !controller.signal.aborted) failed(error, io);
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
});
|
|
1318
|
+
const shutdown = () => {
|
|
1319
|
+
if (stopping) return;
|
|
1320
|
+
stopping = true;
|
|
1321
|
+
scheduler.stop();
|
|
1322
|
+
watcher?.close();
|
|
1323
|
+
watcher = void 0;
|
|
1324
|
+
controller.abort();
|
|
1325
|
+
stopCurrent();
|
|
1326
|
+
finishWatch?.();
|
|
1327
|
+
};
|
|
1328
|
+
process.once("SIGINT", shutdown);
|
|
1329
|
+
process.once("SIGTERM", shutdown);
|
|
1330
|
+
if (signal) {
|
|
1331
|
+
if (signal.aborted) shutdown();
|
|
1332
|
+
else signal.addEventListener("abort", shutdown, { once: true });
|
|
1333
|
+
}
|
|
1334
|
+
try {
|
|
1335
|
+
if (!stopping) {
|
|
1336
|
+
watcher = watchDirectory(root2, () => scheduler.trigger(), { onWarning: (message) => io.err(message) });
|
|
1337
|
+
}
|
|
1338
|
+
await scheduler.runNow();
|
|
1339
|
+
if (!stopping) {
|
|
1340
|
+
io.out(`
|
|
1341
|
+
Watching ${root2} for changes\u2026 Press Ctrl+C to stop.`);
|
|
1342
|
+
await done;
|
|
1343
|
+
}
|
|
1344
|
+
return 0;
|
|
1345
|
+
} finally {
|
|
1346
|
+
shutdown();
|
|
1347
|
+
await scheduler.waitForIdle();
|
|
1348
|
+
process.removeListener("SIGINT", shutdown);
|
|
1349
|
+
process.removeListener("SIGTERM", shutdown);
|
|
1350
|
+
signal?.removeEventListener("abort", shutdown);
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
// src/uninstall.ts
|
|
1355
|
+
import { existsSync, readdirSync as readdirSync2, rmSync as rmSync4, rmdirSync } from "node:fs";
|
|
1356
|
+
import { join as join7 } from "node:path";
|
|
328
1357
|
var PACKAGE = "@okhay-p/mivra";
|
|
329
|
-
var DATA_FILES = ["mivra.db", "mivra.db-wal", "mivra.db-shm", "mivra.db-journal", CREDENTIALS_FILE, CHATGPT_FILE, TOKEN_FILE, STATE_FILE, LOG_FILE];
|
|
1358
|
+
var DATA_FILES = ["mivra.db", "mivra.db-wal", "mivra.db-shm", "mivra.db-journal", CREDENTIALS_FILE, CHATGPT_FILE, TOKEN_FILE, STATE_FILE, LOG_FILE, APPROVALS_FILE];
|
|
330
1359
|
var BACKUPS_DIR = "backups";
|
|
331
1360
|
var GENERATED_BACKUP = /^mivra-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z\.db$/;
|
|
332
1361
|
function mivraFiles(dataDir) {
|
|
333
|
-
const files = DATA_FILES.filter((name) => existsSync(
|
|
1362
|
+
const files = DATA_FILES.filter((name) => existsSync(join7(dataDir, name)));
|
|
334
1363
|
try {
|
|
335
|
-
for (const name of
|
|
1364
|
+
for (const name of readdirSync2(join7(dataDir, BACKUPS_DIR))) if (GENERATED_BACKUP.test(name)) files.push(join7(BACKUPS_DIR, name));
|
|
336
1365
|
} catch {
|
|
337
1366
|
}
|
|
338
1367
|
return files;
|
|
@@ -370,14 +1399,14 @@ async function deleteDataIn(dataDir, entries, err2) {
|
|
|
370
1399
|
} catch {
|
|
371
1400
|
}
|
|
372
1401
|
try {
|
|
373
|
-
for (const name of entries)
|
|
1402
|
+
for (const name of entries) rmSync4(join7(dataDir, name), { force: true });
|
|
374
1403
|
} catch (error) {
|
|
375
1404
|
err2(`Couldn't delete everything in ${dataDir}: ${error.message}`);
|
|
376
1405
|
return false;
|
|
377
1406
|
}
|
|
378
|
-
for (const dir of [
|
|
1407
|
+
for (const dir of [join7(dataDir, BACKUPS_DIR), dataDir]) {
|
|
379
1408
|
try {
|
|
380
|
-
if (
|
|
1409
|
+
if (readdirSync2(dir).length === 0) rmdirSync(dir);
|
|
381
1410
|
} catch {
|
|
382
1411
|
}
|
|
383
1412
|
}
|
|
@@ -385,8 +1414,8 @@ async function deleteDataIn(dataDir, entries, err2) {
|
|
|
385
1414
|
}
|
|
386
1415
|
|
|
387
1416
|
// src/vault.ts
|
|
388
|
-
import { readFileSync as
|
|
389
|
-
import { basename, join as
|
|
1417
|
+
import { readFileSync as readFileSync4, readdirSync as readdirSync3, statSync } from "node:fs";
|
|
1418
|
+
import { basename as basename2, join as join8, relative as relative3, resolve as resolve2, sep as sep2 } from "node:path";
|
|
390
1419
|
var VaultReadError = class extends Error {
|
|
391
1420
|
};
|
|
392
1421
|
function readVault(root2) {
|
|
@@ -403,13 +1432,13 @@ function readVault(root2) {
|
|
|
403
1432
|
let bytes = 0;
|
|
404
1433
|
while (folders.length > 0) {
|
|
405
1434
|
const folder = folders.pop();
|
|
406
|
-
for (const entry of
|
|
1435
|
+
for (const entry of readdirSync3(folder, { withFileTypes: true })) {
|
|
407
1436
|
if (entry.name.startsWith(".") || entry.isSymbolicLink()) continue;
|
|
408
|
-
const full =
|
|
1437
|
+
const full = join8(folder, entry.name);
|
|
409
1438
|
if (entry.isDirectory()) folders.push(full);
|
|
410
1439
|
else if (entry.isFile() && /\.md$/i.test(entry.name)) {
|
|
411
1440
|
if (files.length >= MAX_VAULT_FILES) throw new VaultReadError(`The vault has more than ${MAX_VAULT_FILES} notes, more than one import can take.`);
|
|
412
|
-
const path =
|
|
1441
|
+
const path = relative3(root2, full).split(sep2).join("/");
|
|
413
1442
|
const size = statSync(full).size;
|
|
414
1443
|
if (size > MAX_NOTE_CHARS * 4) {
|
|
415
1444
|
tooLong.push(path);
|
|
@@ -417,7 +1446,7 @@ function readVault(root2) {
|
|
|
417
1446
|
}
|
|
418
1447
|
bytes += size;
|
|
419
1448
|
if (bytes > MAX_VAULT_BYTES) throw new VaultReadError(`The vault's notes come to more than ${MAX_VAULT_BYTES / (1024 * 1024)} MB, more than one import can take.`);
|
|
420
|
-
const text =
|
|
1449
|
+
const text = readFileSync4(full, "utf8");
|
|
421
1450
|
if (text.length > MAX_NOTE_CHARS) tooLong.push(path);
|
|
422
1451
|
else files.push({ path, text });
|
|
423
1452
|
}
|
|
@@ -428,7 +1457,7 @@ function readVault(root2) {
|
|
|
428
1457
|
}
|
|
429
1458
|
var plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
430
1459
|
async function importObsidian(folder, name, dataDir, io) {
|
|
431
|
-
const root2 =
|
|
1460
|
+
const root2 = resolve2(folder);
|
|
432
1461
|
let vault;
|
|
433
1462
|
try {
|
|
434
1463
|
vault = readVault(root2);
|
|
@@ -437,25 +1466,25 @@ async function importObsidian(folder, name, dataDir, io) {
|
|
|
437
1466
|
io.err(error.message);
|
|
438
1467
|
return 1;
|
|
439
1468
|
}
|
|
440
|
-
const importName = (name ??
|
|
1469
|
+
const importName = (name ?? basename2(root2)).trim();
|
|
441
1470
|
if (vault.files.length === 0) {
|
|
442
1471
|
io.err(`No Markdown notes found in ${root2}.`);
|
|
443
1472
|
return 1;
|
|
444
1473
|
}
|
|
445
|
-
const
|
|
446
|
-
if (!
|
|
1474
|
+
const server2 = await running(dataDir);
|
|
1475
|
+
if (!server2) {
|
|
447
1476
|
io.err("Mivra isn't running. Start it with `mivra start --detach`, then import again.");
|
|
448
1477
|
return 1;
|
|
449
1478
|
}
|
|
450
1479
|
let token;
|
|
451
1480
|
try {
|
|
452
|
-
token =
|
|
1481
|
+
token = readFileSync4(join8(dataDir, TOKEN_FILE), "utf8").trim();
|
|
453
1482
|
} catch {
|
|
454
|
-
io.err(`Couldn't read Mivra's API token from ${
|
|
1483
|
+
io.err(`Couldn't read Mivra's API token from ${join8(dataDir, TOKEN_FILE)}.`);
|
|
455
1484
|
return 1;
|
|
456
1485
|
}
|
|
457
1486
|
const headers = { authorization: `Bearer ${token}`, "content-type": "application/json" };
|
|
458
|
-
const listed = await fetch(`${
|
|
1487
|
+
const listed = await fetch(`${server2.url}/api/imports`, { headers });
|
|
459
1488
|
if (!listed.ok) {
|
|
460
1489
|
io.err(`Mivra refused to list imports (${listed.status}).`);
|
|
461
1490
|
return 1;
|
|
@@ -466,7 +1495,7 @@ async function importObsidian(folder, name, dataDir, io) {
|
|
|
466
1495
|
io.err(`The vault's notes come to more than ${MAX_VAULT_BYTES / (1024 * 1024)} MB, more than one import can take.`);
|
|
467
1496
|
return 1;
|
|
468
1497
|
}
|
|
469
|
-
const res = await fetch(existing ? `${
|
|
1498
|
+
const res = await fetch(existing ? `${server2.url}/api/imports/${existing.id}/files` : `${server2.url}/api/imports`, {
|
|
470
1499
|
method: existing ? "PUT" : "POST",
|
|
471
1500
|
headers,
|
|
472
1501
|
body
|
|
@@ -490,9 +1519,9 @@ async function importObsidian(folder, name, dataDir, io) {
|
|
|
490
1519
|
// src/cli.ts
|
|
491
1520
|
var root = fileURLToPath(new URL("..", import.meta.url));
|
|
492
1521
|
var firstExisting = (...paths) => paths.find((p) => existsSync2(p)) ?? paths[0];
|
|
493
|
-
var webDist = () => firstExisting(
|
|
494
|
-
var migrations = () => firstExisting(
|
|
495
|
-
var version = () => JSON.parse(
|
|
1522
|
+
var webDist = () => firstExisting(join9(root, "web"), join9(root, "../web/dist"));
|
|
1523
|
+
var migrations = () => firstExisting(join9(root, "drizzle"), join9(root, "../server/drizzle"));
|
|
1524
|
+
var version = () => JSON.parse(readFileSync5(join9(root, "package.json"), "utf8")).version;
|
|
496
1525
|
var out = (message) => process.stdout.write(`${message}
|
|
497
1526
|
`);
|
|
498
1527
|
var err = (message) => process.stderr.write(`${message}
|
|
@@ -542,6 +1571,18 @@ ${USAGE}`);
|
|
|
542
1571
|
return authLogout(config);
|
|
543
1572
|
case "import-obsidian":
|
|
544
1573
|
return importObsidian(command.folder, command.importName, config.dataDir, { out, err });
|
|
1574
|
+
case "link":
|
|
1575
|
+
return link(command, { dataDir: config.dataDir, cwd: process.cwd(), readToken: () => readSecret("Paste the Mivra token (hidden): ") }, { out, err });
|
|
1576
|
+
case "token":
|
|
1577
|
+
return printToken(config.dataDir);
|
|
1578
|
+
case "check":
|
|
1579
|
+
return check(
|
|
1580
|
+
command,
|
|
1581
|
+
// Asks only at a terminal, where the question and commands (on stderr) are seen; piped, redirected or in a
|
|
1582
|
+
// script, unapproved commands are refused instead.
|
|
1583
|
+
{ dataDir: config.dataDir, cwd: process.cwd(), ...canAsk() ? { ask: (question) => confirm(question) } : {} },
|
|
1584
|
+
{ out, err }
|
|
1585
|
+
);
|
|
545
1586
|
case "uninstall":
|
|
546
1587
|
return uninstall({ dataDir: config.dataDir, deleteData: command.deleteData, stop: () => stop(config.dataDir), confirm, out, err });
|
|
547
1588
|
}
|
|
@@ -569,14 +1610,14 @@ async function startForeground(command, base, env) {
|
|
|
569
1610
|
}
|
|
570
1611
|
claimed = claim(config.dataDir);
|
|
571
1612
|
if (!claimed.ok) {
|
|
572
|
-
err(`Another Mivra (process ${claimed.holder.pid}) holds ${
|
|
1613
|
+
err(`Another Mivra (process ${claimed.holder.pid}) holds ${join9(config.dataDir, STATE_FILE)} but doesn't answer. If it isn't running, delete that file.`);
|
|
573
1614
|
return 1;
|
|
574
1615
|
}
|
|
575
1616
|
}
|
|
576
|
-
const [{ PortInUseError, startServer }, { NewerDatabaseError }] = await Promise.all([import("./start-
|
|
577
|
-
let
|
|
1617
|
+
const [{ PortInUseError, startServer }, { NewerDatabaseError }] = await Promise.all([import("./start-GVAACONX.js"), import("./client-76YUHG4T.js")]);
|
|
1618
|
+
let server2;
|
|
578
1619
|
try {
|
|
579
|
-
|
|
1620
|
+
server2 = await startServer({ config, env, webDist: webDist(), migrationsFolder: migrations(), portFallback: true, log: err });
|
|
580
1621
|
} catch (error) {
|
|
581
1622
|
clearState(config.dataDir, process.pid);
|
|
582
1623
|
if (error instanceof PortInUseError) {
|
|
@@ -604,24 +1645,24 @@ ${error.message}`);
|
|
|
604
1645
|
process.exit(0);
|
|
605
1646
|
};
|
|
606
1647
|
setTimeout(exit, 5e3).unref();
|
|
607
|
-
void
|
|
1648
|
+
void server2.close().then(exit, exit);
|
|
608
1649
|
};
|
|
609
1650
|
process.once("SIGINT", shutdown);
|
|
610
1651
|
process.once("SIGTERM", shutdown);
|
|
611
1652
|
process.once("SIGHUP", shutdown);
|
|
612
|
-
writeState(config.dataDir, { pid: process.pid, port:
|
|
613
|
-
if (
|
|
614
|
-
out(`Mivra is running at ${
|
|
1653
|
+
writeState(config.dataDir, { pid: process.pid, port: server2.port, url: server2.url, startedAt: readState(config.dataDir)?.startedAt ?? (/* @__PURE__ */ new Date()).toISOString() });
|
|
1654
|
+
if (server2.port !== config.port) err(`Port ${config.port} is in use, so Mivra is on ${server2.port}.`);
|
|
1655
|
+
out(`Mivra is running at ${server2.url}`);
|
|
615
1656
|
out(env.MIVRA_DETACHED === "1" ? `Data: ${config.dataDir}` : `Data: ${config.dataDir}. Press Ctrl+C to stop.`);
|
|
616
|
-
if (command.open) openBrowser(
|
|
1657
|
+
if (command.open) openBrowser(server2.url);
|
|
617
1658
|
return new Promise(() => {
|
|
618
1659
|
});
|
|
619
1660
|
}
|
|
620
1661
|
var DETACH_TIMEOUT_MS = 6e4;
|
|
621
1662
|
async function startDetached(command, config, env) {
|
|
622
1663
|
if (await alreadyRunning(config.dataDir, command.open)) return 0;
|
|
623
|
-
const logPath =
|
|
624
|
-
|
|
1664
|
+
const logPath = join9(config.dataDir, LOG_FILE);
|
|
1665
|
+
mkdirSync3(config.dataDir, { recursive: true });
|
|
625
1666
|
const log = openSync2(logPath, "a", 384);
|
|
626
1667
|
const args = [...process.execArgv, process.argv[1], "start", "--no-open", ...command.port === void 0 ? [] : ["--port", String(command.port)]];
|
|
627
1668
|
const child = spawn2(process.execPath, args, {
|
|
@@ -662,7 +1703,7 @@ ${tail(logPath)}`);
|
|
|
662
1703
|
}
|
|
663
1704
|
function tail(path, lines = 20) {
|
|
664
1705
|
try {
|
|
665
|
-
return
|
|
1706
|
+
return readFileSync5(path, "utf8").trimEnd().split("\n").slice(-lines).join("\n");
|
|
666
1707
|
} catch {
|
|
667
1708
|
return "(no log)";
|
|
668
1709
|
}
|
|
@@ -680,7 +1721,7 @@ async function stop(dataDir) {
|
|
|
680
1721
|
return 1;
|
|
681
1722
|
}
|
|
682
1723
|
if (!await running(dataDir)) {
|
|
683
|
-
err(`Process ${state.pid} is recorded as Mivra but nothing answers at ${state.url}, so it was left alone. If Mivra isn't running, delete ${
|
|
1724
|
+
err(`Process ${state.pid} is recorded as Mivra but nothing answers at ${state.url}, so it was left alone. If Mivra isn't running, delete ${join9(dataDir, "mivra.pid")}.`);
|
|
684
1725
|
return 1;
|
|
685
1726
|
}
|
|
686
1727
|
process.kill(state.pid, "SIGTERM");
|
|
@@ -695,7 +1736,7 @@ async function stop(dataDir) {
|
|
|
695
1736
|
return 0;
|
|
696
1737
|
}
|
|
697
1738
|
var fromEnvMessage = (provider2) => `${PROVIDER_ENV[provider2]} is set in this environment, and it takes precedence over a saved key. Change or unset it instead.`;
|
|
698
|
-
async function authSet(provider2,
|
|
1739
|
+
async function authSet(provider2, check2, config, env) {
|
|
699
1740
|
const credentials = createCredentialStore({ dataDir: config.dataDir, env });
|
|
700
1741
|
if (env[PROVIDER_ENV[provider2]]?.trim()) {
|
|
701
1742
|
err(fromEnvMessage(provider2));
|
|
@@ -714,8 +1755,8 @@ async function authSet(provider2, check, config, env) {
|
|
|
714
1755
|
return 1;
|
|
715
1756
|
}
|
|
716
1757
|
credentials.set(provider2, key.data);
|
|
717
|
-
out(`Saved the ${PROVIDER_LABELS[provider2]} key to ${
|
|
718
|
-
if (!
|
|
1758
|
+
out(`Saved the ${PROVIDER_LABELS[provider2]} key to ${join9(config.dataDir, CREDENTIALS_FILE)}. A running Mivra uses it from the next reply.`);
|
|
1759
|
+
if (!check2) return 0;
|
|
719
1760
|
const baseUrl = provider2 === "anthropic" ? env.ANTHROPIC_BASE_URL : provider2 === "openai" ? env.OPENAI_BASE_URL : void 0;
|
|
720
1761
|
const { checkProviderKey } = await import("./key-check-WJ4CVZV5.js");
|
|
721
1762
|
const result = await checkProviderKey(provider2, key.data, { baseUrl });
|
|
@@ -763,7 +1804,7 @@ async function authLogin(newAccount, open, config) {
|
|
|
763
1804
|
err(result.notice ?? "Sign-in didn't finish.");
|
|
764
1805
|
return 1;
|
|
765
1806
|
}
|
|
766
|
-
out(`Signed in to ChatGPT${result.email ? ` as ${result.email}` : ""}, saved in ${
|
|
1807
|
+
out(`Signed in to ChatGPT${result.email ? ` as ${result.email}` : ""}, saved in ${join9(config.dataDir, CHATGPT_FILE)}. A running Mivra uses it from the next reply.`);
|
|
767
1808
|
return 0;
|
|
768
1809
|
}
|
|
769
1810
|
async function authLogout(config) {
|
|
@@ -776,6 +1817,11 @@ async function authLogout(config) {
|
|
|
776
1817
|
out(revoked ? "Signed out of ChatGPT." : "Signed out of ChatGPT here, but ChatGPT didn't confirm it. To be sure, disconnect Mivra in ChatGPT's settings.");
|
|
777
1818
|
return 0;
|
|
778
1819
|
}
|
|
1820
|
+
function printToken(dataDir) {
|
|
1821
|
+
err(`Mivra's token, from ${join9(dataDir, TOKEN_FILE)}. On the other computer, run \`mivra link --server <this Mivra's address>\` and paste it there. Anyone with it can use this Mivra, so keep it private.`);
|
|
1822
|
+
out(loadOrCreateToken(dataDir));
|
|
1823
|
+
return 0;
|
|
1824
|
+
}
|
|
779
1825
|
function authRemove(provider2, config, env) {
|
|
780
1826
|
const removed = createCredentialStore({ dataDir: config.dataDir, env }).remove(provider2);
|
|
781
1827
|
if (removed === "env") {
|