@networkbase/cli 1.0.4 → 2.0.0-next.3
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 +60 -37
- package/bin/nb.mjs +69 -5390
- package/lib/api.mjs +163 -0
- package/lib/args.mjs +140 -0
- package/lib/commands/account.mjs +293 -0
- package/lib/commands/agent.mjs +169 -0
- package/lib/commands/ask.mjs +84 -0
- package/lib/commands/assignments.mjs +199 -0
- package/lib/commands/browse.mjs +140 -0
- package/lib/commands/docs.mjs +178 -0
- package/lib/commands/extras.mjs +114 -0
- package/lib/commands/files.mjs +425 -0
- package/lib/commands/inbox.mjs +98 -0
- package/lib/commands/link.mjs +85 -0
- package/lib/commands/mcp.mjs +149 -0
- package/lib/commands/misc.mjs +263 -0
- package/lib/commands/resolve.mjs +95 -0
- package/lib/commands/table.mjs +225 -0
- package/lib/commands/tasks.mjs +362 -0
- package/lib/commands/undo.mjs +52 -0
- package/lib/commands/watch.mjs +113 -0
- package/lib/commands/work.mjs +190 -0
- package/lib/config.mjs +203 -0
- package/lib/context.mjs +72 -0
- package/lib/errors.mjs +72 -0
- package/lib/keychain.mjs +59 -0
- package/lib/mcp/tools.mjs +336 -0
- package/lib/print/notices.mjs +48 -0
- package/lib/print/out.mjs +151 -0
- package/lib/print/remind.mjs +25 -0
- package/lib/print/style.mjs +110 -0
- package/lib/sync/diff.mjs +41 -0
- package/lib/sync/ignore.mjs +86 -0
- package/lib/sync/local.mjs +68 -0
- package/lib/sync/plan.mjs +94 -0
- package/lib/sync/queue.mjs +31 -0
- package/lib/sync/state.mjs +136 -0
- package/lib/sync/transfer.mjs +172 -0
- package/lib/tui/ask.mjs +124 -0
- package/lib/undo-log.mjs +34 -0
- package/package.json +13 -11
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// nb undo (report A2.9, §17.4): reverses a change made from this machine in the last 24 hours, if nothing has
|
|
2
|
+
// happened since that it would undo. The server keeps the rules; this only picks which change.
|
|
3
|
+
import { CliError } from "../errors.mjs";
|
|
4
|
+
import { safe } from "../print/style.mjs";
|
|
5
|
+
import { dropUndo, readUndoLog } from "../undo-log.mjs";
|
|
6
|
+
|
|
7
|
+
/** @typedef {import("../context.mjs").Context} Context */
|
|
8
|
+
|
|
9
|
+
const WHAT = /** @type {Record<string, string>} */ ({
|
|
10
|
+
"/api/v1/files/place": "push", "/api/v1/extension/fast-push": "push", "/api/v1/extension/create-task": "task created",
|
|
11
|
+
"/api/v1/extension/task-subtask": "subtask added", "/api/v1/extension/task-update": "task or subtask change", "/api/v1/extension/comments": "comment",
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
/** @param {Context} ctx */
|
|
15
|
+
export async function undo(ctx) {
|
|
16
|
+
const log = readUndoLog(ctx.env, ctx.profile.origin);
|
|
17
|
+
if (ctx.flags.list) {
|
|
18
|
+
return ctx.out.result("nb.undo.list/1", { changes: log.slice().reverse().map((e) => ({ token: e.token, at: new Date(e.at).toISOString(), what: WHAT[e.path] ?? e.path })) }, (d) =>
|
|
19
|
+
d.changes.length ? d.changes.map((c, i) => ` ${i === 0 ? ctx.out.c.brand(ctx.out.sym.brand) : " "} ${c.at.slice(11, 16)} ${c.what} ${ctx.out.c.muted(c.token.slice(0, 8))}`) : "Nothing to undo from the last 24 hours");
|
|
20
|
+
}
|
|
21
|
+
if (ctx.flags.session) {
|
|
22
|
+
// Everything this agent session did, newest first (report A7.7): `nb mcp` tags its changes with a session id.
|
|
23
|
+
const session = ctx.env.NB_AGENT_SESSION;
|
|
24
|
+
if (!session) throw new CliError("USAGE", "--session works inside an agent session (nb mcp)");
|
|
25
|
+
const mine = log.filter((e) => e.session === session).reverse();
|
|
26
|
+
if (!mine.length) throw new CliError("NOT_FOUND", "This agent session hasn't changed anything that can be undone");
|
|
27
|
+
/** @type {Array<{ token: string, ok: boolean, message: string }>} */
|
|
28
|
+
const results = [];
|
|
29
|
+
for (const e of mine) {
|
|
30
|
+
try {
|
|
31
|
+
const res = /** @type {any} */ (await ctx.api.post(`/api/v1/undo/${encodeURIComponent(e.token)}`, {}));
|
|
32
|
+
dropUndo(ctx.env, e.token);
|
|
33
|
+
results.push({ token: e.token, ok: true, message: String(res.result ?? res.undone) });
|
|
34
|
+
} catch (error) {
|
|
35
|
+
results.push({ token: e.token, ok: false, message: error instanceof Error ? error.message : String(error) });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
ctx.out.result("nb.undo.session/1", { results }, (d) => d.results.map((r) => `${r.ok ? ctx.out.c.success(ctx.out.sym.done) : ctx.out.c.warning(ctx.out.sym.warn)} ${safe(r.message)}`));
|
|
39
|
+
return results.every((r) => r.ok) ? 0 : 4;
|
|
40
|
+
}
|
|
41
|
+
const given = ctx.positionals[0];
|
|
42
|
+
const entry = given ? log.find((e) => e.token.startsWith(given)) ?? { token: given } : log.at(-1);
|
|
43
|
+
if (!entry) throw new CliError("NOT_FOUND", "Nothing to undo from the last 24 hours on this machine", { hint: "nb undo --list" });
|
|
44
|
+
try {
|
|
45
|
+
const res = /** @type {any} */ (await ctx.api.post(`/api/v1/undo/${encodeURIComponent(entry.token)}`, {}));
|
|
46
|
+
dropUndo(ctx.env, entry.token);
|
|
47
|
+
ctx.out.result("nb.undo/1", { token: entry.token, undone: res.undone, result: res.result }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Undid: ${safe(d.undone)} (${safe(d.result)})`);
|
|
48
|
+
} catch (error) {
|
|
49
|
+
if (error instanceof CliError && error.status === 410) dropUndo(ctx.env, entry.token);
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// nb watch (report A1.13, D2): in the foreground only, so you can see it and stop it with Ctrl+C. Pushes saves of
|
|
2
|
+
// files NetworkBase already tracks, as drafts, without linking each save to a task or moving its status. New files
|
|
3
|
+
// are pushed by naming them. Waits until an editor finishes saving (500 ms, plus 2 s quiet). It also pulls other
|
|
4
|
+
// people's new versions as they land (A1.13 item 5, long-poll /api/v1/events): pull never overwrites your edits, so
|
|
5
|
+
// a file you changed too gets a conflict copy. Its polling keeps this sign-in "active" in the app (presence, A11.4).
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
|
|
9
|
+
import { CliError, EXIT } from "../errors.mjs";
|
|
10
|
+
import { safe } from "../print/style.mjs";
|
|
11
|
+
import { toRemote } from "../sync/local.mjs";
|
|
12
|
+
import { readState } from "../sync/state.mjs";
|
|
13
|
+
import { toRelative } from "../sync/local.mjs";
|
|
14
|
+
import { pull, push } from "./files.mjs";
|
|
15
|
+
|
|
16
|
+
/** @typedef {import("../context.mjs").Context} Context */
|
|
17
|
+
|
|
18
|
+
const SETTLE_MS = 500;
|
|
19
|
+
const QUIET_MS = 2000;
|
|
20
|
+
const SKIP = /(^|\/)(\.networkbase|\.git|node_modules|\.tasks)(\/|$)|\.nbtmp-|\.swp$|~$|(^|\/)\.#|(^|\/)4913$/;
|
|
21
|
+
|
|
22
|
+
/** @param {Context} ctx */
|
|
23
|
+
export async function watch(ctx) {
|
|
24
|
+
const { root, project } = ctx.requireRoot();
|
|
25
|
+
if (ctx.out.json) throw new CliError("USAGE", "nb watch runs until you stop it, so it has no --json result");
|
|
26
|
+
/** @type {Map<string, number>} relative path → last event time */
|
|
27
|
+
const pending = new Map();
|
|
28
|
+
let busy = false;
|
|
29
|
+
let stopping = false;
|
|
30
|
+
|
|
31
|
+
ctx.out.note(`${ctx.out.c.brand(ctx.out.sym.brand)} Watching ${root} → ${safe(project.slug ?? project.workspaceId)}`);
|
|
32
|
+
ctx.out.note(ctx.out.c.muted(` Saves of tracked files are pushed as drafts${ctx.flags["no-pull"] ? "" : "; teammates' new versions are pulled"}. New files: nb push <file>. Ctrl+C to stop.`));
|
|
33
|
+
|
|
34
|
+
/** Files nb itself just wrote by pulling: their change events aren't your saves. */
|
|
35
|
+
const pulledAt = new Map();
|
|
36
|
+
const watcher = fs.watch(root, { recursive: true }, (_event, name) => {
|
|
37
|
+
if (!name) return;
|
|
38
|
+
const rel = String(name).split(path.sep).join("/");
|
|
39
|
+
if (SKIP.test(rel)) return;
|
|
40
|
+
if (Date.now() - (pulledAt.get(rel) ?? 0) < 5000) return;
|
|
41
|
+
pending.set(rel, Date.now());
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
// Live pull: wait for new versions from other people, then pull just those files.
|
|
45
|
+
const livePull = async () => {
|
|
46
|
+
let since = new Date().toISOString();
|
|
47
|
+
let backoff = 1000;
|
|
48
|
+
while (!stopping) {
|
|
49
|
+
try {
|
|
50
|
+
const res = /** @type {any} */ (await ctx.api.get("/api/v1/events", { query: { since, workspace: project.workspaceId, inbox: 0 }, timeoutMs: 40_000 }));
|
|
51
|
+
since = res.cursor;
|
|
52
|
+
backoff = 1000;
|
|
53
|
+
const theirs = [...new Set(res.files.filter((/** @type {any} */ f) => !f.mine).map((/** @type {any} */ f) => toRelative(project.remoteRoot, f.path)).filter(Boolean))];
|
|
54
|
+
if (!theirs.length || stopping) continue;
|
|
55
|
+
while (busy) await new Promise((r) => setTimeout(r, 200));
|
|
56
|
+
busy = true;
|
|
57
|
+
try {
|
|
58
|
+
for (const rel of theirs) pulledAt.set(rel, Date.now());
|
|
59
|
+
await pull(/** @type {Context} */ ({ ...ctx, cwd: root, positionals: theirs, flags: { ...ctx.flags } }));
|
|
60
|
+
for (const rel of theirs) pulledAt.set(rel, Date.now());
|
|
61
|
+
} finally {
|
|
62
|
+
busy = false;
|
|
63
|
+
}
|
|
64
|
+
} catch (error) {
|
|
65
|
+
if (error instanceof CliError && (error.code === "UNAUTHORIZED" || error.status === 403)) { ctx.out.warn(`Live pull stopped: ${error.message}`); return; }
|
|
66
|
+
await new Promise((r) => setTimeout(r, backoff));
|
|
67
|
+
backoff = Math.min(60_000, backoff * 2);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
if (!ctx.flags["no-pull"]) void livePull();
|
|
72
|
+
|
|
73
|
+
/** One batch: files whose last change is older than the quiet window. */
|
|
74
|
+
async function flush() {
|
|
75
|
+
if (busy || !pending.size) return;
|
|
76
|
+
const now = Date.now();
|
|
77
|
+
const ready = [...pending].filter(([, at]) => now - at >= QUIET_MS).map(([rel]) => rel);
|
|
78
|
+
if (!ready.length) return;
|
|
79
|
+
for (const rel of ready) pending.delete(rel);
|
|
80
|
+
const state = readState(root, project.workspaceId);
|
|
81
|
+
const tracked = ready.filter((rel) => state.files[toRemote(project.remoteRoot, rel)] && fs.existsSync(path.join(root, rel)));
|
|
82
|
+
if (!tracked.length) return;
|
|
83
|
+
busy = true;
|
|
84
|
+
const ctx2 = /** @type {Context} */ ({ ...ctx, cwd: root, positionals: tracked, flags: { ...ctx.flags, as: "draft", task: undefined, message: ctx.flags.message ?? "Saved from nb watch" } });
|
|
85
|
+
try {
|
|
86
|
+
await push(ctx2);
|
|
87
|
+
} catch (error) {
|
|
88
|
+
const e = error instanceof CliError ? error : null;
|
|
89
|
+
ctx.out.warn(`${e?.message ?? String(error)}${e?.hint ? ` — ${e.hint}` : ""}`);
|
|
90
|
+
} finally {
|
|
91
|
+
busy = false;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const timer = setInterval(() => void flush(), SETTLE_MS);
|
|
96
|
+
await new Promise((resolve) => {
|
|
97
|
+
const stop = async () => {
|
|
98
|
+
if (stopping) return;
|
|
99
|
+
stopping = true;
|
|
100
|
+
ctx.out.note(ctx.out.c.muted("Stopping after the current batch…"));
|
|
101
|
+
while (busy) await new Promise((r) => setTimeout(r, 100));
|
|
102
|
+
clearInterval(timer);
|
|
103
|
+
watcher.close();
|
|
104
|
+
resolve(undefined);
|
|
105
|
+
};
|
|
106
|
+
process.removeAllListeners("SIGINT");
|
|
107
|
+
process.once("SIGINT", stop);
|
|
108
|
+
process.once("SIGTERM", stop);
|
|
109
|
+
});
|
|
110
|
+
// A live-pull request may still be waiting on the server: don't let it hold the process open.
|
|
111
|
+
setTimeout(() => process.exit(process.exitCode ?? EXIT.ok), 200).unref();
|
|
112
|
+
return EXIT.ok;
|
|
113
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
// task edit|assign|delete|report, subtask edit|delete|move, comment list|resolve and line comments (report §17.4,
|
|
2
|
+
// §17.4.1, D10). Changes go through the same server rules as the app; agents' big ones wait for a yes there.
|
|
3
|
+
import crypto from "node:crypto";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
|
|
7
|
+
import { CliError, EXIT, usage } from "../errors.mjs";
|
|
8
|
+
import { safe } from "../print/style.mjs";
|
|
9
|
+
import { confirm } from "../tui/ask.mjs";
|
|
10
|
+
import { resolveTask, taskRef } from "./tasks.mjs";
|
|
11
|
+
|
|
12
|
+
/** @typedef {import("../context.mjs").Context} Context */
|
|
13
|
+
|
|
14
|
+
/** @param {Context} ctx @param {Record<string, unknown>} body */
|
|
15
|
+
const update = (ctx, body) => ctx.api.patch("/api/v1/extension/task-update", { projectId: ctx.requireWorkspace(), ...body });
|
|
16
|
+
|
|
17
|
+
/** @param {Context} ctx */
|
|
18
|
+
export async function taskEdit(ctx) {
|
|
19
|
+
const task = await resolveTask(ctx, taskRef(ctx, ctx.positionals[0]));
|
|
20
|
+
/** @type {Array<[string, string | null]>} */
|
|
21
|
+
const changes = [];
|
|
22
|
+
if (ctx.flags.title) changes.push(["title", String(ctx.flags.title)]);
|
|
23
|
+
if (ctx.flags.message !== undefined) changes.push(["description", String(ctx.flags.message)]);
|
|
24
|
+
if (ctx.flags.priority) {
|
|
25
|
+
if (!["low", "medium", "high", "urgent"].includes(ctx.flags.priority)) throw usage("--priority must be low, medium, high or urgent");
|
|
26
|
+
changes.push(["priority", ctx.flags.priority]);
|
|
27
|
+
}
|
|
28
|
+
if (ctx.flags.due) {
|
|
29
|
+
const due = String(ctx.flags.due);
|
|
30
|
+
if (due !== "none" && Number.isNaN(Date.parse(due))) throw usage("--due takes a date like 2026-11-14, or none");
|
|
31
|
+
changes.push(["dueDate", due === "none" ? null : new Date(due).toISOString()]);
|
|
32
|
+
}
|
|
33
|
+
if (!changes.length) throw usage("nb task edit <task> [--title text] [-m description] [--priority high] [--due 2026-11-14|none]");
|
|
34
|
+
for (const [field, value] of changes) await update(ctx, { kind: "edit", taskId: task.id, field, value });
|
|
35
|
+
ctx.out.result("nb.task.edit/1", { number: task.taskNumber, changed: changes.map(([f]) => f) }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Changed ${d.changed.join(", ")} on #${d.number}`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** @param {Context} ctx */
|
|
39
|
+
export async function taskAssign(ctx) {
|
|
40
|
+
const [ref, who] = ctx.positionals;
|
|
41
|
+
if (!ref || !who) throw usage("nb task assign <task> <@username|me|none>");
|
|
42
|
+
const task = await resolveTask(ctx, ref);
|
|
43
|
+
let assigneeId = null;
|
|
44
|
+
if (who === "me") assigneeId = /** @type {any} */ (await ctx.api.get("/api/v1/me")).user.id;
|
|
45
|
+
else if (who !== "none") {
|
|
46
|
+
const name = who.replace(/^@/, "").toLowerCase();
|
|
47
|
+
const { members } = /** @type {any} */ (await ctx.api.get(`/api/v1/workspaces/${encodeURIComponent(ctx.requireWorkspace())}/members`, { query: { q: name } }));
|
|
48
|
+
const hit = members.find((/** @type {any} */ m) => String(m.username ?? "").toLowerCase() === name);
|
|
49
|
+
if (!hit) throw new CliError("NOT_FOUND", `No member @${name} in this workspace`, { hint: "nb member list" });
|
|
50
|
+
assigneeId = hit.id;
|
|
51
|
+
}
|
|
52
|
+
await update(ctx, { kind: "assign", taskId: task.id, assigneeId });
|
|
53
|
+
ctx.out.result("nb.task.assign/1", { number: task.taskNumber, assignee: who === "none" ? null : who.replace(/^@/, "") }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} #${d.number} ${d.assignee ? `is assigned to ${d.assignee === "me" ? "you" : `@${safe(d.assignee)}`}` : "is unassigned"}`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** @param {Context} ctx */
|
|
57
|
+
export async function taskDelete(ctx) {
|
|
58
|
+
const task = await resolveTask(ctx, taskRef(ctx, ctx.positionals[0]));
|
|
59
|
+
if (!(await confirm(ctx, { key: "delete", question: `Delete #${task.taskNumber} ${task.title}? Its draft files move to a recovery folder.`, yesLabel: "Delete", defaultYes: false }))) return EXIT.cancelled;
|
|
60
|
+
await update(ctx, { kind: "delete", taskId: task.id });
|
|
61
|
+
ctx.out.result("nb.task.delete/1", { number: task.taskNumber }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Deleted #${d.number}`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** A report without finishing (report §18.2 "task_report"): what was done and the checks, as a comment. @param {Context} ctx */
|
|
65
|
+
export async function taskReport(ctx) {
|
|
66
|
+
const task = await resolveTask(ctx, taskRef(ctx, ctx.positionals[0]));
|
|
67
|
+
const summary = String(ctx.flags.message ?? "").trim();
|
|
68
|
+
if (!summary) throw usage('nb task report <task> -m "what was done" [--check "npm test=pass"]');
|
|
69
|
+
const checks = /** @type {string[]} */ (ctx.flags.check ?? []).map((c) => {
|
|
70
|
+
const [name, rest = "pass"] = c.split("=");
|
|
71
|
+
const [result, note] = rest.split(":");
|
|
72
|
+
return `- ${result === "fail" ? "✗" : "✓"} ${name}${note ? ` — ${note}` : ""}`;
|
|
73
|
+
});
|
|
74
|
+
const text = [`**Report** ${summary}`, ...(checks.length ? ["", ...checks] : [])].join("\n");
|
|
75
|
+
await ctx.api.post("/api/v1/extension/comments", { kind: "task", projectId: ctx.requireWorkspace(), taskId: task.id, text });
|
|
76
|
+
ctx.out.result("nb.task.report/1", { number: task.taskNumber, checks: checks.length }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Reported on #${d.number}${d.checks ? ` with ${d.checks} check${d.checks === 1 ? "" : "s"}` : ""}`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** @param {Context} ctx @param {string} n */
|
|
80
|
+
async function subtaskByNumber(ctx, n) {
|
|
81
|
+
const task = await resolveTask(ctx, taskRef(ctx, undefined));
|
|
82
|
+
const list = task.subtasks.map((/** @type {any} */ s, /** @type {number} */ i) => ({ ...s, n: s.index ?? i + 1 }));
|
|
83
|
+
const hit = list.find((/** @type {any} */ s) => String(s.n) === n.replace("#", "") || s.id === n);
|
|
84
|
+
if (!hit) throw usage(`#${task.taskNumber} has no subtask ${n}`, `nb subtask list --task ${task.taskNumber}`);
|
|
85
|
+
return { task, subtask: hit, count: list.length };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** @param {Context} ctx */
|
|
89
|
+
export async function subtaskEdit(ctx) {
|
|
90
|
+
const [n, ...words] = ctx.positionals;
|
|
91
|
+
if (!n || !words.length) throw usage('nb subtask edit <n> "<new title>" [--task 4]');
|
|
92
|
+
const { task, subtask } = await subtaskByNumber(ctx, n);
|
|
93
|
+
await update(ctx, { kind: "subtask_edit", taskId: task.id, subtaskId: subtask.id, title: words.join(" ") });
|
|
94
|
+
ctx.out.result("nb.subtask.edit/1", { number: task.taskNumber, n: subtask.n }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Renamed subtask ${d.n} on #${d.number}`);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** @param {Context} ctx */
|
|
98
|
+
export async function subtaskDelete(ctx) {
|
|
99
|
+
const n = ctx.positionals[0];
|
|
100
|
+
if (!n) throw usage("nb subtask delete <n> [--task 4]");
|
|
101
|
+
const { task, subtask } = await subtaskByNumber(ctx, n);
|
|
102
|
+
if (!(await confirm(ctx, { key: "delete", question: `Delete subtask ${subtask.n} "${subtask.title}" on #${task.taskNumber}?`, yesLabel: "Delete", defaultYes: false }))) return EXIT.cancelled;
|
|
103
|
+
await update(ctx, { kind: "subtask_delete", taskId: task.id, subtaskId: subtask.id });
|
|
104
|
+
ctx.out.result("nb.subtask.delete/1", { number: task.taskNumber, n: subtask.n }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Deleted subtask ${d.n} on #${d.number}`);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** @param {Context} ctx */
|
|
108
|
+
export async function subtaskMove(ctx) {
|
|
109
|
+
const [n, to] = ctx.positionals;
|
|
110
|
+
if (!n || !to || !/^\d+$/.test(to)) throw usage("nb subtask move <n> <new position, 1 = first> [--task 4]");
|
|
111
|
+
const { task, subtask, count } = await subtaskByNumber(ctx, n);
|
|
112
|
+
const position = Math.min(Math.max(Number(to), 1), count) - 1;
|
|
113
|
+
await update(ctx, { kind: "subtask_move", taskId: task.id, subtaskId: subtask.id, position });
|
|
114
|
+
ctx.out.result("nb.subtask.move/1", { number: task.taskNumber, from: subtask.n, to: position + 1 }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Subtask ${d.from} is now ${d.to} on #${d.number}`);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** "src/app.ts:12" or "src/app.ts:12-18" → path and lines. @param {string} spec */
|
|
118
|
+
function fileSpec(spec) {
|
|
119
|
+
const m = /^(.*?):(\d+)(?:-(\d+))?$/.exec(spec);
|
|
120
|
+
return m ? { path: `/${String(m[1]).replace(/^\/+/, "")}`, start: Number(m[2]), end: Number(m[3] ?? m[2]) } : { path: `/${spec.replace(/^\/+/, "")}`, start: null, end: null };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** @param {Context} ctx @param {string} remotePath */
|
|
124
|
+
async function fileNode(ctx, remotePath) {
|
|
125
|
+
const meta = /** @type {any} */ (await ctx.api.get("/api/v1/extension/file", { query: { projectId: ctx.requireWorkspace(), path: remotePath, transfer: "metadata" } }).catch((error) => {
|
|
126
|
+
if (error instanceof CliError && error.status === 404) throw new CliError("NOT_FOUND", `No file ${remotePath} in this workspace`);
|
|
127
|
+
throw error;
|
|
128
|
+
}));
|
|
129
|
+
return meta;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** @param {Context} ctx @param {string} nodeId */
|
|
133
|
+
async function fileThreads(ctx, nodeId) {
|
|
134
|
+
const { events } = /** @type {any} */ (await ctx.api.get("/api/v1/extension/comments", { query: { projectId: ctx.requireWorkspace(), nodeId } }));
|
|
135
|
+
/** @type {Map<string, any>} */
|
|
136
|
+
const threads = new Map();
|
|
137
|
+
for (const e of events) {
|
|
138
|
+
const m = e.metadata ?? {};
|
|
139
|
+
const id = m.threadId ?? e.id;
|
|
140
|
+
const t = threads.get(id) ?? { id, anchor: null, comments: [], resolved: false, sequence: 0 };
|
|
141
|
+
if (m.anchor) t.anchor = m.anchor;
|
|
142
|
+
if (typeof m.text === "string") t.comments.push({ by: e.name ?? null, text: m.text, at: e.createdAt });
|
|
143
|
+
if (typeof m.resolved === "boolean") t.resolved = m.resolved;
|
|
144
|
+
t.sequence = Math.max(t.sequence, Number(e.sequence ?? 0));
|
|
145
|
+
threads.set(id, t);
|
|
146
|
+
}
|
|
147
|
+
return [...threads.values()];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** @param {Context} ctx */
|
|
151
|
+
export async function commentList(ctx) {
|
|
152
|
+
if (ctx.flags.file) {
|
|
153
|
+
const spec = fileSpec(String(ctx.flags.file));
|
|
154
|
+
const node = await fileNode(ctx, spec.path);
|
|
155
|
+
const threads = await fileThreads(ctx, node.nodeId ?? node.id);
|
|
156
|
+
return ctx.out.result("nb.comment.list/1", { path: spec.path, threads }, (d) =>
|
|
157
|
+
d.threads.length ? d.threads.flatMap((t) => [`${t.resolved ? ctx.out.c.muted("resolved") : ctx.out.c.accent("open")} ${safe(d.path)}${t.anchor ? `:${t.anchor.startLine}${t.anchor.endLine !== t.anchor.startLine ? `-${t.anchor.endLine}` : ""}` : ""} ${ctx.out.c.muted(String(t.id).slice(0, 8))}`, ...t.comments.map((/** @type {any} */ c) => ` ${c.by ? `${safe(c.by)}: ` : ""}${safe(c.text)}`)]) : `No comments on ${safe(d.path)}`);
|
|
158
|
+
}
|
|
159
|
+
const task = await resolveTask(ctx, taskRef(ctx, undefined));
|
|
160
|
+
const comments = task.comments.map((/** @type {any} */ c) => ({ id: c.id, by: c.authorUsername ?? c.authorName ?? null, text: c.content, at: c.createdAt }));
|
|
161
|
+
ctx.out.result("nb.comment.list/1", { number: task.taskNumber, comments, untrusted: true }, (d) =>
|
|
162
|
+
d.comments.length ? d.comments.map((/** @type {any} */ c) => ` ${ctx.out.c.muted(String(c.at).slice(0, 16).replace("T", " "))} ${c.by ? `@${safe(c.by)}` : "someone"}: ${safe(c.text).replace(/\n/g, " ")}`) : `#${d.number} has no comments`);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** A comment on lines of a file (report D10): `nb comment add -m "…" --file src/app.ts:12-18`. @param {Context} ctx */
|
|
166
|
+
export async function commentOnFile(ctx) {
|
|
167
|
+
const spec = fileSpec(String(ctx.flags.file));
|
|
168
|
+
if (spec.start === null) throw usage("Say which lines: --file src/app.ts:12 or src/app.ts:12-18");
|
|
169
|
+
const text = String(ctx.flags.message ?? ctx.positionals.join(" ")).trim();
|
|
170
|
+
if (!text) throw usage('nb comment add -m "<text>" --file <path>:<line>');
|
|
171
|
+
const node = await fileNode(ctx, spec.path);
|
|
172
|
+
const local = ctx.root ? path.join(ctx.root, spec.path.slice(1)) : null;
|
|
173
|
+
const hash = node.contentHash ?? (local && fs.existsSync(local) ? crypto.createHash("sha256").update(fs.readFileSync(local)).digest("hex") : null);
|
|
174
|
+
if (!hash) throw new CliError("NOT_FOUND", "Couldn't tell which version of the file the lines are in", { hint: "nb pull, then try again" });
|
|
175
|
+
await ctx.api.post("/api/v1/extension/comments", { kind: "create", projectId: ctx.requireWorkspace(), nodeId: node.nodeId ?? node.id, text, anchor: { version: node.currentVersion, hash, startLine: spec.start, endLine: spec.end } });
|
|
176
|
+
ctx.out.result("nb.comment.add/1", { path: spec.path, lines: [spec.start, spec.end] }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Commented on ${safe(d.path)}:${d.lines[0]}${d.lines[1] !== d.lines[0] ? `-${d.lines[1]}` : ""}`);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** @param {Context} ctx */
|
|
180
|
+
export async function commentResolve(ctx) {
|
|
181
|
+
const id = ctx.positionals[0];
|
|
182
|
+
if (!id || !ctx.flags.file) throw usage("nb comment resolve <thread id> --file <path> [--reopen]");
|
|
183
|
+
const spec = fileSpec(String(ctx.flags.file));
|
|
184
|
+
const node = await fileNode(ctx, spec.path);
|
|
185
|
+
const thread = (await fileThreads(ctx, node.nodeId ?? node.id)).find((t) => String(t.id).startsWith(id));
|
|
186
|
+
if (!thread) throw new CliError("NOT_FOUND", `No comment thread ${id} on ${spec.path}`, { hint: `nb comment list --file ${spec.path.slice(1)}` });
|
|
187
|
+
const resolved = !ctx.flags.reopen;
|
|
188
|
+
await ctx.api.post("/api/v1/extension/comments", { kind: "resolve", projectId: ctx.requireWorkspace(), nodeId: node.nodeId ?? node.id, threadId: thread.id, expectedSequence: thread.sequence, resolved });
|
|
189
|
+
ctx.out.result("nb.comment.resolve/1", { thread: thread.id, resolved }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} ${d.resolved ? "Resolved" : "Reopened"} the thread`);
|
|
190
|
+
}
|
package/lib/config.mjs
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
// Where the CLI keeps things, and which setting wins (report A1.1, A1.2, A3.5, A3.8, A3.16, A4.3).
|
|
2
|
+
// ~/.networkbase/credentials.json tokens per profile, each bound to the server that issued it (0600)
|
|
3
|
+
// ~/.networkbase/config.json user settings
|
|
4
|
+
// <root>/.networkbase/config.json the folder's link: workspace id, slug, started task (never a server URL)
|
|
5
|
+
// <root>/.networkbase/state.json what was last synced (the base for three-way decisions)
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import os from "node:os";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import crypto from "node:crypto";
|
|
10
|
+
|
|
11
|
+
import { CliError } from "./errors.mjs";
|
|
12
|
+
import { readSecret, removeSecret, secureStore, storeSecret } from "./keychain.mjs";
|
|
13
|
+
|
|
14
|
+
export const DEFAULT_ORIGIN = "https://networkbase.in";
|
|
15
|
+
export const DIR_NAME = ".networkbase";
|
|
16
|
+
|
|
17
|
+
export const globalDir = (env = process.env) => path.join(env.NB_HOME || os.homedir(), DIR_NAME);
|
|
18
|
+
|
|
19
|
+
/** Write a file so readers see the old or the new content, never half (A1.9). @param {string} file @param {string | Uint8Array} data @param {number} [mode] */
|
|
20
|
+
export function writeAtomic(file, data, mode = 0o600) {
|
|
21
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
22
|
+
const tmp = `${file}.nbtmp-${crypto.randomBytes(4).toString("hex")}`;
|
|
23
|
+
const fd = fs.openSync(tmp, "w", mode);
|
|
24
|
+
try {
|
|
25
|
+
fs.writeSync(fd, typeof data === "string" ? Buffer.from(data) : data);
|
|
26
|
+
fs.fsyncSync(fd);
|
|
27
|
+
} finally {
|
|
28
|
+
fs.closeSync(fd);
|
|
29
|
+
}
|
|
30
|
+
renameRetry(tmp, file);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* fs.renameSync that waits out Windows' brief locks (antivirus, indexer, an open preview: EBUSY/EPERM/EACCES),
|
|
35
|
+
* up to ~1.5 s (A12.16). Elsewhere it's a plain rename.
|
|
36
|
+
* @param {string} from @param {string} to
|
|
37
|
+
*/
|
|
38
|
+
export function renameRetry(from, to) {
|
|
39
|
+
for (let attempt = 0; ; attempt++) {
|
|
40
|
+
try {
|
|
41
|
+
fs.renameSync(from, to);
|
|
42
|
+
return;
|
|
43
|
+
} catch (error) {
|
|
44
|
+
const code = /** @type {NodeJS.ErrnoException} */ (error).code;
|
|
45
|
+
if (process.platform !== "win32" || attempt >= 5 || !["EBUSY", "EPERM", "EACCES"].includes(String(code))) throw error;
|
|
46
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100 * (attempt + 1));
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** @param {string} file @returns {any} */
|
|
52
|
+
export function readJson(file) {
|
|
53
|
+
try {
|
|
54
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (/** @type {NodeJS.ErrnoException} */ (error).code === "ENOENT") return null;
|
|
57
|
+
throw new CliError("CORRUPT_STATE", `${file} can't be read`, { hint: "Run nb doctor --repair", cause: error });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** @param {string} origin */
|
|
62
|
+
export function normalizeOrigin(origin) {
|
|
63
|
+
let url;
|
|
64
|
+
try {
|
|
65
|
+
url = new URL(origin);
|
|
66
|
+
} catch {
|
|
67
|
+
throw new CliError("USAGE", `${origin} isn't a web address`);
|
|
68
|
+
}
|
|
69
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) {
|
|
70
|
+
throw new CliError("USAGE", `${origin} must use https (http only for localhost)`);
|
|
71
|
+
}
|
|
72
|
+
return url.origin;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* @typedef {{ origin: string, token: string, user?: { id: string, username?: string | null, email?: string | null } | null, savedAt?: string, source?: "file" | "env", storage?: "keychain" | "secret-service" | "dpapi" | "file", sealed?: string }} Profile
|
|
77
|
+
*/
|
|
78
|
+
|
|
79
|
+
/** Settings: flag > environment > project > user > default. @param {{ profile?: string }} [flags] @param {NodeJS.ProcessEnv} [env] @param {any} [project] */
|
|
80
|
+
export function resolveProfileName(flags = {}, env = process.env, project = null) {
|
|
81
|
+
return /** @type {string} */ (flags.profile || env.NB_PROFILE || /** @type {any} */ (project)?.profile || "default");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The keychain entry's name: one per profile and server. @param {string} name @param {string} origin */
|
|
85
|
+
const account = (name, origin) => `${name}@${new URL(origin).host}`;
|
|
86
|
+
|
|
87
|
+
/** @param {NodeJS.ProcessEnv} env */
|
|
88
|
+
function readCredentialFile(env) {
|
|
89
|
+
const raw = readJson(path.join(globalDir(env), "credentials.json"));
|
|
90
|
+
if (!raw) return { profiles: {} };
|
|
91
|
+
// 1.x stored one token with its server; it becomes the default profile, bound to that server.
|
|
92
|
+
if (!raw.profiles && typeof raw.token === "string") {
|
|
93
|
+
return { profiles: { default: { origin: normalizeOrigin(raw.apiUrl || DEFAULT_ORIGIN), token: raw.token, user: raw.user ?? null, savedAt: raw.savedAt } } };
|
|
94
|
+
}
|
|
95
|
+
return raw;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The token to use, and the only server it may be sent to (report A3.8, finding 28).
|
|
100
|
+
* @param {{ flags?: Record<string, any>, env?: NodeJS.ProcessEnv, project?: any }} [ctx]
|
|
101
|
+
* @returns {{ name: string, origin: string, token: string | null, profile: Profile | null }}
|
|
102
|
+
*/
|
|
103
|
+
export function currentProfile(ctx = {}) {
|
|
104
|
+
const env = ctx.env ?? process.env;
|
|
105
|
+
const flags = ctx.flags ?? {};
|
|
106
|
+
const name = resolveProfileName(flags, env, ctx.project);
|
|
107
|
+
const wanted = flags["api-url"] || env.NB_API_URL || env.NETWORKBASE_API_URL;
|
|
108
|
+
const envToken = env.NB_TOKEN || env.NETWORKBASE_TOKEN;
|
|
109
|
+
if (envToken) {
|
|
110
|
+
const origin = normalizeOrigin(wanted || DEFAULT_ORIGIN);
|
|
111
|
+
return { name, origin, token: envToken, profile: { origin, token: envToken, source: "env" } };
|
|
112
|
+
}
|
|
113
|
+
const saved = readCredentialFile(env).profiles?.[name] ?? null;
|
|
114
|
+
const origin = normalizeOrigin(wanted || saved?.origin || DEFAULT_ORIGIN);
|
|
115
|
+
// A token is only ever sent to the server that issued it.
|
|
116
|
+
if (saved && saved.origin === origin) {
|
|
117
|
+
const token = saved.storage && saved.storage !== "file" ? readSecret(saved.storage, account(name, origin), saved.sealed) : saved.token;
|
|
118
|
+
return { name, origin, token: token ?? null, profile: { ...saved, token: token ?? "", source: "file" } };
|
|
119
|
+
}
|
|
120
|
+
return { name, origin, token: null, profile: null };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** @param {string} name @param {Profile | null} profile @param {NodeJS.ProcessEnv} [env] */
|
|
124
|
+
export function saveProfile(name, profile, env = process.env) {
|
|
125
|
+
const file = path.join(globalDir(env), "credentials.json");
|
|
126
|
+
const data = readCredentialFile(env);
|
|
127
|
+
data.profiles = data.profiles ?? {};
|
|
128
|
+
const old = data.profiles[name];
|
|
129
|
+
if (old?.storage && old.storage !== "file") removeSecret(old.storage, account(name, old.origin));
|
|
130
|
+
if (profile) {
|
|
131
|
+
// The OS keychain when there is one (report A3.4); the file only holds which store and the user.
|
|
132
|
+
const store = secureStore(env);
|
|
133
|
+
let kept = /** @type {Profile} */ ({ ...profile, storage: "file" });
|
|
134
|
+
if (store) {
|
|
135
|
+
try {
|
|
136
|
+
const extra = storeSecret(store, account(name, profile.origin), profile.token);
|
|
137
|
+
kept = { ...profile, token: "", storage: store, ...extra };
|
|
138
|
+
} catch {
|
|
139
|
+
kept = { ...profile, storage: "file" };
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
data.profiles[name] = { ...kept, savedAt: new Date().toISOString() };
|
|
143
|
+
} else delete data.profiles[name];
|
|
144
|
+
writeAtomic(file, `${JSON.stringify(data, null, 2)}\n`, 0o600);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** All saved profiles (for `nb whoami --all`). @param {NodeJS.ProcessEnv} [env] */
|
|
148
|
+
export const listProfiles = (env = process.env) => /** @type {Record<string, Profile>} */ (readCredentialFile(env).profiles ?? {});
|
|
149
|
+
|
|
150
|
+
/** User settings in ~/.networkbase/config.json. @param {NodeJS.ProcessEnv} [env] */
|
|
151
|
+
export const readUserConfig = (env = process.env) => readJson(path.join(globalDir(env), "config.json")) ?? {};
|
|
152
|
+
/** @param {Record<string, unknown>} config @param {NodeJS.ProcessEnv} [env] */
|
|
153
|
+
export const writeUserConfig = (config, env = process.env) => writeAtomic(path.join(globalDir(env), "config.json"), `${JSON.stringify(config, null, 2)}\n`);
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* The linked folder above `cwd`, like git (A1.1 item 2). Stops at the filesystem root.
|
|
157
|
+
* @param {string} cwd
|
|
158
|
+
* @returns {string | null}
|
|
159
|
+
*/
|
|
160
|
+
export function findRoot(cwd) {
|
|
161
|
+
let dir = path.resolve(cwd);
|
|
162
|
+
for (;;) {
|
|
163
|
+
if (fs.existsSync(path.join(dir, DIR_NAME, "config.json"))) return dir;
|
|
164
|
+
const parent = path.dirname(dir);
|
|
165
|
+
if (parent === dir) return null;
|
|
166
|
+
dir = parent;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* @typedef {{ workspaceId: string, slug?: string | null, title?: string | null, remoteRoot: string, startedTask?: { id: string, number?: number | null, title?: string | null } | null, profile?: string | null, linkedAt?: string }} ProjectConfig
|
|
172
|
+
*/
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* The folder's link. 1.x configs (`projectId`, `apiUrl`) are read; their server URL is ignored, because a
|
|
176
|
+
* file inside a project must never decide where your token goes (A3.8).
|
|
177
|
+
* @param {string} root
|
|
178
|
+
* @param {(message: string) => void} [warn]
|
|
179
|
+
* @returns {ProjectConfig | null}
|
|
180
|
+
*/
|
|
181
|
+
export function readProjectConfig(root, warn) {
|
|
182
|
+
const raw = readJson(path.join(root, DIR_NAME, "config.json"));
|
|
183
|
+
if (!raw) return null;
|
|
184
|
+
if (raw.apiUrl && warn) warn(`Ignoring the server address in ${path.join(root, DIR_NAME, "config.json")}: a project file can't choose where your token is sent. Use --api-url or nb login.`);
|
|
185
|
+
return {
|
|
186
|
+
workspaceId: raw.workspaceId ?? raw.projectId,
|
|
187
|
+
slug: raw.slug ?? null,
|
|
188
|
+
title: raw.title ?? null,
|
|
189
|
+
remoteRoot: raw.remoteRoot ?? "/",
|
|
190
|
+
startedTask: raw.startedTask ?? null,
|
|
191
|
+
profile: raw.profile ?? null,
|
|
192
|
+
linkedAt: raw.linkedAt,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** @param {string} root @param {ProjectConfig} config */
|
|
197
|
+
export function writeProjectConfig(root, config) {
|
|
198
|
+
const dir = path.join(root, DIR_NAME);
|
|
199
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
200
|
+
// Never commit the link, tokens or sync state to the user's git repo (A1.2, finding 62).
|
|
201
|
+
if (!fs.existsSync(path.join(dir, ".gitignore"))) writeAtomic(path.join(dir, ".gitignore"), "*\n", 0o600);
|
|
202
|
+
writeAtomic(path.join(dir, "config.json"), `${JSON.stringify(config, null, 2)}\n`);
|
|
203
|
+
}
|
package/lib/context.mjs
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// What every command gets: output, flags, the linked folder, the signed-in profile and an API client.
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
|
|
6
|
+
import { createApi } from "./api.mjs";
|
|
7
|
+
import { currentProfile, findRoot, readProjectConfig } from "./config.mjs";
|
|
8
|
+
import { CliError } from "./errors.mjs";
|
|
9
|
+
import { createOutput } from "./print/out.mjs";
|
|
10
|
+
import { appendUndo } from "./undo-log.mjs";
|
|
11
|
+
|
|
12
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
13
|
+
const PACKAGE_JSON = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
14
|
+
/** The version comes from package.json only, so it can't drift (finding 92). */
|
|
15
|
+
export const VERSION = JSON.parse(fs.readFileSync(PACKAGE_JSON, "utf8")).version;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @param {{ flags: Record<string, any>, positionals: string[], cwd?: string, env?: NodeJS.ProcessEnv, fetchImpl?: typeof fetch, io?: Parameters<typeof createOutput>[1] }} input
|
|
19
|
+
*/
|
|
20
|
+
export function createContext({ flags, positionals, cwd = process.cwd(), env = process.env, fetchImpl, io }) {
|
|
21
|
+
const out = createOutput({ json: Boolean(flags.json || env.NB_JSON === "1"), quiet: Boolean(flags.quiet), plain: Boolean(flags.plain), verbose: Boolean(flags.verbose), fields: flags.fields ? String(flags.fields).split(",").map((f) => f.trim()).filter(Boolean) : null, pager: !flags["no-pager"] }, io);
|
|
22
|
+
const root = findRoot(cwd);
|
|
23
|
+
const project = root ? readProjectConfig(root, (m) => out.warn(m)) : null;
|
|
24
|
+
const profile = currentProfile({ flags, env, project });
|
|
25
|
+
const api = createApi({
|
|
26
|
+
origin: profile.origin,
|
|
27
|
+
token: profile.token,
|
|
28
|
+
version: VERSION,
|
|
29
|
+
fetchImpl,
|
|
30
|
+
confirmToken: typeof flags.confirm === "string" ? flags.confirm : null,
|
|
31
|
+
onUndo: (u) => appendUndo(env, { token: u.token, at: Date.now(), method: u.method, path: u.path, origin: profile.origin, session: env.NB_AGENT_SESSION ?? null }),
|
|
32
|
+
onRetry: ({ waitMs, reason }) => out.note(out.c.muted(`${reason}; retrying in ${Math.max(1, Math.round(waitMs / 1000))} s`)),
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
return {
|
|
36
|
+
out,
|
|
37
|
+
flags,
|
|
38
|
+
positionals,
|
|
39
|
+
cwd,
|
|
40
|
+
env,
|
|
41
|
+
root,
|
|
42
|
+
project,
|
|
43
|
+
profile,
|
|
44
|
+
api,
|
|
45
|
+
version: VERSION,
|
|
46
|
+
/** Workspace id from --workspace or the link; an error naming the fix otherwise. */
|
|
47
|
+
requireWorkspace() {
|
|
48
|
+
if (flags.workspace) return /** @type {string} */ (flags.workspace);
|
|
49
|
+
if (project?.workspaceId) return project.workspaceId;
|
|
50
|
+
// A default for scripts, CI and the hosted MCP server (an agent token's own workspace).
|
|
51
|
+
if (env.NB_WORKSPACE) return env.NB_WORKSPACE;
|
|
52
|
+
throw new CliError("NOT_LINKED", "This folder isn't linked to a workspace", { hint: "Run nb init <workspace>, or pass --workspace <slug>" });
|
|
53
|
+
},
|
|
54
|
+
/** --workspace takes a slug or title; the API needs the id, so it's looked up once before the command runs. */
|
|
55
|
+
async resolveWorkspace() {
|
|
56
|
+
const given = flags.workspace;
|
|
57
|
+
if (!given || UUID.test(given)) return;
|
|
58
|
+
const { workspaces } = /** @type {any} */ (await api.get("/api/v1/extension/workspaces"));
|
|
59
|
+
const want = String(given).toLowerCase();
|
|
60
|
+
const found = workspaces.find((/** @type {any} */ w) => String(w.slug).toLowerCase() === want) ?? workspaces.find((/** @type {any} */ w) => String(w.title).toLowerCase() === want);
|
|
61
|
+
if (!found) throw new CliError("WORKSPACE_NOT_FOUND", `No workspace ${given} in your list`, { hint: workspaces.length ? `Yours: ${workspaces.slice(0, 8).map((/** @type {any} */ w) => w.slug).join(", ")}` : "Create one at networkbase.in first" });
|
|
62
|
+
flags.workspace = found.id;
|
|
63
|
+
},
|
|
64
|
+
/** The linked folder; commands that sync files need one. */
|
|
65
|
+
requireRoot() {
|
|
66
|
+
if (!root || !project) throw new CliError("NOT_LINKED", "This folder isn't linked to a workspace", { hint: "Run nb init <workspace> here" });
|
|
67
|
+
return { root, project };
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** @typedef {ReturnType<typeof createContext>} Context */
|