@x-tech-laboratories/x-app 0.116.0 → 0.118.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +19 -6
  2. package/dist/agent/claude_stream.d.ts +22 -0
  3. package/dist/agent/claude_stream.js +85 -0
  4. package/dist/agent/git.d.ts +37 -0
  5. package/dist/agent/git.js +121 -0
  6. package/dist/agent/github.d.ts +81 -0
  7. package/dist/agent/github.js +185 -0
  8. package/dist/agent/programs.d.ts +17 -0
  9. package/dist/agent/programs.js +62 -0
  10. package/dist/agent/worktree_files.d.ts +20 -0
  11. package/dist/agent/worktree_files.js +69 -0
  12. package/dist/agent_transcript.d.ts +83 -0
  13. package/dist/agent_transcript.js +267 -0
  14. package/dist/app_android_key.d.ts +3 -0
  15. package/dist/app_android_key.js +34 -11
  16. package/dist/connection_protocol.d.ts +1 -0
  17. package/dist/connection_protocol.js +11 -0
  18. package/dist/diff_rows.d.ts +78 -0
  19. package/dist/diff_rows.js +158 -0
  20. package/dist/frontmatter.d.ts +10 -0
  21. package/dist/frontmatter.js +57 -0
  22. package/dist/frontmatter_folder.d.ts +24 -0
  23. package/dist/frontmatter_folder.js +54 -0
  24. package/dist/server/config.d.ts +2 -0
  25. package/dist/server/config.js +15 -1
  26. package/dist/server/github_webhook.d.ts +30 -0
  27. package/dist/server/github_webhook.js +146 -0
  28. package/dist/test_helpers.d.ts +7 -0
  29. package/dist/test_helpers.js +44 -0
  30. package/dist/web/react/accounts.js +2 -1
  31. package/dist/web/react/controls.d.ts +3 -2
  32. package/dist/web/react/controls.js +6 -4
  33. package/dist/web/react/copy_button.d.ts +11 -0
  34. package/dist/web/react/copy_button.js +44 -0
  35. package/dist/web/react/dialog.js +2 -2
  36. package/dist/web/react/diff.d.ts +26 -0
  37. package/dist/web/react/diff.js +79 -0
  38. package/dist/web/react/file_tree.d.ts +26 -0
  39. package/dist/web/react/file_tree.js +46 -0
  40. package/dist/web/react/local_mcp_settings.js +2 -1
  41. package/dist/web/react/transcript.d.ts +24 -0
  42. package/dist/web/react/transcript.js +100 -0
  43. package/package.json +5 -3
@@ -0,0 +1,57 @@
1
+ // Markdown files that start with YAML frontmatter between --- lines, such as agent definitions or notes: read into the
2
+ // frontmatter document and the body, the values read as text or lists whatever shape they were written in, and written
3
+ // back with the app's keys set or dropped while every other key and comment stays as it was. It runs alike in a page
4
+ // and in Node, on the `yaml` package, an optional peer the app installs.
5
+ // ── Imports ──────────────────────────────────────────────────────────────────
6
+ import { Document, parseDocument } from "yaml";
7
+ const frontmatter_pattern = /^---\r?\n(?:([\s\S]*?)\r?\n)?---[ \t]*(?:\r?\n|$)([\s\S]*)$/;
8
+ // ── Reading ──────────────────────────────────────────────────────────────────
9
+ // The file's frontmatter and body; throws in plain words when it has no frontmatter or it is not a set of keys.
10
+ export function parse_frontmatter(text) {
11
+ const match = frontmatter_pattern.exec(text);
12
+ if (!match)
13
+ throw new Error("it does not start with a frontmatter block between --- lines");
14
+ const frontmatter = parseDocument(match[1] ?? "");
15
+ if (frontmatter.errors.length)
16
+ throw new Error(`its frontmatter is not valid YAML: ${frontmatter.errors[0].message}`);
17
+ const values = frontmatter.toJS();
18
+ if (frontmatter.contents !== null && (typeof values !== "object" || values === null || Array.isArray(values)))
19
+ throw new Error("its frontmatter is not a set of keys");
20
+ return { frontmatter, body: match[2].trim() };
21
+ }
22
+ // The frontmatter's keys and values, an empty frontmatter as none.
23
+ export function frontmatter_values(file) {
24
+ return (file.frontmatter.toJS() ?? {});
25
+ }
26
+ // A value as text: a string, or a number written out; anything else as "".
27
+ export function frontmatter_text(value) {
28
+ return typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
29
+ }
30
+ // A value as a list of text, from a YAML list or a comma-separated line such as "Read, Grep, Bash".
31
+ export function frontmatter_list(value) {
32
+ if (Array.isArray(value))
33
+ return value.map(frontmatter_text).filter(Boolean);
34
+ return frontmatter_text(value)
35
+ .split(",")
36
+ .map((part) => part.trim())
37
+ .filter(Boolean);
38
+ }
39
+ // ── Writing ──────────────────────────────────────────────────────────────────
40
+ // Whether a value is left out of the frontmatter: undefined, null, "" or an empty list.
41
+ function is_empty(value) {
42
+ return value === undefined || value === null || value === "" || (Array.isArray(value) && value.length === 0);
43
+ }
44
+ // The file's text with the values given set, or dropped when empty, every other key and comment kept from `previous`.
45
+ export function write_frontmatter(values, body, previous = null) {
46
+ const document = previous ? previous.clone() : new Document({});
47
+ if (document.contents === null)
48
+ document.contents = document.createNode({});
49
+ for (const [key, value] of Object.entries(values)) {
50
+ if (is_empty(value))
51
+ document.delete(key);
52
+ else
53
+ document.set(key, value);
54
+ }
55
+ const trimmed = body.trim();
56
+ return `---\n${String(document).trimEnd()}\n---\n${trimmed ? `\n${trimmed}\n` : ""}`;
57
+ }
@@ -0,0 +1,24 @@
1
+ import { type FrontmatterFile } from "./frontmatter.ts";
2
+ export interface FrontmatterFolderOptions {
3
+ folder: string;
4
+ id_of_file: (name: string) => string | null;
5
+ file_of_id: (id: string) => string;
6
+ on_change?: () => void;
7
+ settle_in_milliseconds?: number;
8
+ }
9
+ export interface FrontmatterProblem {
10
+ file: string;
11
+ problem: string;
12
+ }
13
+ export interface FrontmatterFolder {
14
+ read_all: () => {
15
+ files: Map<string, FrontmatterFile>;
16
+ problems: FrontmatterProblem[];
17
+ };
18
+ write: (id: string, text: string) => void;
19
+ remove: (id: string) => void;
20
+ has: (id: string) => boolean;
21
+ path_of: (id: string) => string;
22
+ watch: () => () => void;
23
+ }
24
+ export declare function create_frontmatter_folder({ folder, id_of_file, file_of_id, on_change, settle_in_milliseconds }: FrontmatterFolderOptions): FrontmatterFolder;
@@ -0,0 +1,54 @@
1
+ // A folder of frontmatter files named by id, such as `stage-<id>.md`: every file read with a problem for each that does
2
+ // not parse, one written beside its old self and moved over it so a reader never sees half a file, removed, and the
3
+ // folder followed for changes made by other programs.
4
+ // ── Imports ──────────────────────────────────────────────────────────────────
5
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, watch, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { parse_frontmatter } from "./frontmatter.js";
8
+ // ── Folder ───────────────────────────────────────────────────────────────────
9
+ export function create_frontmatter_folder({ folder, id_of_file, file_of_id, on_change = () => undefined, settle_in_milliseconds = 300 }) {
10
+ const path_of = (id) => join(folder, file_of_id(id));
11
+ return {
12
+ path_of,
13
+ has: (id) => existsSync(path_of(id)),
14
+ read_all: () => {
15
+ const files = new Map();
16
+ const problems = [];
17
+ const names = existsSync(folder) ? readdirSync(folder).sort() : [];
18
+ for (const name of names) {
19
+ const id = id_of_file(name);
20
+ if (id === null)
21
+ continue;
22
+ try {
23
+ files.set(id, parse_frontmatter(readFileSync(join(folder, name), "utf8")));
24
+ }
25
+ catch (error) {
26
+ problems.push({ file: name, problem: error.message });
27
+ }
28
+ }
29
+ return { files, problems };
30
+ },
31
+ write: (id, text) => {
32
+ mkdirSync(folder, { recursive: true });
33
+ const target = path_of(id);
34
+ const temporary = `${target}.saving`;
35
+ writeFileSync(temporary, text);
36
+ renameSync(temporary, target);
37
+ },
38
+ remove: (id) => rmSync(path_of(id), { force: true }),
39
+ watch: () => {
40
+ mkdirSync(folder, { recursive: true });
41
+ let timer;
42
+ const watcher = watch(folder, (_event, name) => {
43
+ if (name !== null && id_of_file(String(name)) === null)
44
+ return;
45
+ clearTimeout(timer);
46
+ timer = setTimeout(on_change, settle_in_milliseconds);
47
+ });
48
+ return () => {
49
+ clearTimeout(timer);
50
+ watcher.close();
51
+ };
52
+ },
53
+ };
54
+ }
@@ -45,5 +45,7 @@ export declare function command_words(line: string, words_for?: SecretCommandWor
45
45
  export declare function secret_command_reader(words_for?: SecretCommandWords): SecretReader;
46
46
  export declare const read_secret_command: SecretReader;
47
47
  export declare function secret_from_command(command_line: string, read?: SecretReader, words_for?: SecretCommandWords): Promise<string>;
48
+ export declare function create_secret_file(path: string, bytes?: number): void;
49
+ export declare function has_secret_file(path: string): boolean;
48
50
  export declare function read_server_config<Name extends string = never>(spec: ServerConfigSpec<Name>): ServerConfig<Name>;
49
51
  export {};
@@ -4,7 +4,9 @@
4
4
  // the program and never holds the secret.
5
5
  // ── Imports ──────────────────────────────────────────────────────────────────
6
6
  import { execFile } from "node:child_process";
7
- import { readFileSync } from "node:fs";
7
+ import { randomBytes } from "node:crypto";
8
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
9
+ import { dirname } from "node:path";
8
10
  import { parseArgs } from "node:util";
9
11
  export class HelpRequested extends Error {
10
12
  usage;
@@ -104,6 +106,18 @@ export async function secret_from_command(command_line, read = read_secret_comma
104
106
  const words = command_words(command_line.trim(), words_for);
105
107
  return words.length === 0 ? "" : read(words);
106
108
  }
109
+ // A new random secret, such as a webhook's, written to a file only its owner may read, replacing any before it; the
110
+ // caller gives it out only when asked, through read_secret_file.
111
+ export function create_secret_file(path, bytes = 32) {
112
+ mkdirSync(dirname(path), { recursive: true });
113
+ writeFileSync(path, `${randomBytes(bytes).toString("hex")}\n`, { mode: 0o600 });
114
+ // A file that was there before keeps its old mode through writeFileSync, so it is tightened too.
115
+ chmodSync(path, 0o600);
116
+ }
117
+ // Whether the file holds a secret, without reading it out.
118
+ export function has_secret_file(path) {
119
+ return existsSync(path) && readFileSync(path, "utf8").trim() !== "";
120
+ }
107
121
  // ── Reading ──────────────────────────────────────────────────────────────────
108
122
  function capitals(name) {
109
123
  return name.replaceAll("-", "_").toUpperCase();
@@ -0,0 +1,30 @@
1
+ import type { IncomingHttpHeaders } from "node:http";
2
+ import { AddressLockout, type WebhookAnswer } from "./forge_webhook.ts";
3
+ export declare const github_target_events: readonly ["pull_request", "check_suite", "check_run", "status", "workflow_run", "issues", "issue_comment"];
4
+ export interface WebhookTargets {
5
+ repository: string;
6
+ pull_requests: number[];
7
+ branches: string[];
8
+ issues: number[];
9
+ }
10
+ export interface GitHubDelivery {
11
+ delivery_id: string;
12
+ event: string;
13
+ targets: WebhookTargets;
14
+ }
15
+ export interface GitHubReceiverOptions {
16
+ secret: () => string;
17
+ events?: readonly string[];
18
+ on_delivery: (delivery: GitHubDelivery) => void;
19
+ lockout?: AddressLockout;
20
+ remembered?: number;
21
+ unsigned_text?: string;
22
+ }
23
+ export declare function is_repository_name(name: string): boolean;
24
+ export declare function repository_of(payload: unknown): string | null;
25
+ export declare function delivery_id_of(header: unknown): string;
26
+ export declare function targets_of(event: string, payload: unknown): WebhookTargets | null;
27
+ export declare function read_targets(repository: string, stored: string): WebhookTargets;
28
+ export declare function read_public_url(typed: string): string;
29
+ export declare function payload_url_of(public_url: string, path: string): string;
30
+ export declare function create_github_receiver({ secret, events, on_delivery, lockout, remembered, unsigned_text }: GitHubReceiverOptions): (address: string, headers: IncomingHttpHeaders, body: Buffer) => WebhookAnswer;
@@ -0,0 +1,146 @@
1
+ // GitHub's webhooks on top of `forge_webhook`: a delivery counts only when signed with X-Hub-Signature-256 under the
2
+ // app's secret, never by a bearer token or another forge's header; an address that keeps failing waits; a delivery id
3
+ // seen before is answered without being passed on again; and of each delivery only the repository and the pull
4
+ // requests, branches and issues it names are kept, each checked for shape, for the app to look up for itself.
5
+ import { AddressLockout, is_signed, parse_payload } from "./forge_webhook.js";
6
+ // ── Shapes ───────────────────────────────────────────────────────────────────
7
+ // The events that name pull requests, branches or issues, for the app to tick on GitHub.
8
+ export const github_target_events = ["pull_request", "check_suite", "check_run", "status", "workflow_run", "issues", "issue_comment"];
9
+ const repository_pattern = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;
10
+ const branch_pattern = /^[A-Za-z0-9._/-]{1,255}$/;
11
+ const delivery_pattern = /^[A-Za-z0-9-]{1,100}$/;
12
+ const most_targets = 50;
13
+ function fields_of(value) {
14
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
15
+ }
16
+ function number_of(value) {
17
+ return typeof value === "number" && Number.isInteger(value) && value > 0 && value < 2 ** 31 ? value : null;
18
+ }
19
+ function branch_of(value) {
20
+ return typeof value === "string" && branch_pattern.test(value) && !value.includes("..") && !value.startsWith("-") ? value : null;
21
+ }
22
+ // The pull request numbers in a list such as check_suite.pull_requests, left out where they are not plain numbers.
23
+ function numbers_in(list) {
24
+ return (Array.isArray(list) ? list : []).map((entry) => number_of(fields_of(entry).number)).filter((number) => number !== null);
25
+ }
26
+ // Whether a name is a repository as owner/name.
27
+ export function is_repository_name(name) {
28
+ return repository_pattern.test(name);
29
+ }
30
+ // The repository a payload names as owner/name, or null when it names none that looks like one.
31
+ export function repository_of(payload) {
32
+ const name = fields_of(fields_of(payload).repository).full_name;
33
+ return typeof name === "string" && repository_pattern.test(name) ? name : null;
34
+ }
35
+ // The delivery id as GitHub sends it, or "" when it is missing or not an id.
36
+ export function delivery_id_of(header) {
37
+ return typeof header === "string" && delivery_pattern.test(header) ? header : "";
38
+ }
39
+ // The repository and the pull requests, branches and issues a delivery names, or null; nothing else in it is kept.
40
+ export function targets_of(event, payload) {
41
+ const repository = repository_of(payload);
42
+ if (repository === null)
43
+ return null;
44
+ const values = fields_of(payload);
45
+ const pull_requests = [];
46
+ const branches = [];
47
+ const issues = [];
48
+ if (event === "ping") {
49
+ // Only says the hook works.
50
+ }
51
+ else if (event === "pull_request") {
52
+ const pull = fields_of(values.pull_request);
53
+ const head = fields_of(pull.head);
54
+ pull_requests.push(number_of(pull.number) ?? number_of(values.number));
55
+ // A fork's branch is not one of the repository's own, so only a branch of the same repository counts.
56
+ if (fields_of(head.repo).full_name === repository)
57
+ branches.push(branch_of(head.ref));
58
+ }
59
+ else if (event === "check_suite" || event === "workflow_run") {
60
+ const suite = fields_of(values[event]);
61
+ branches.push(branch_of(suite.head_branch));
62
+ pull_requests.push(...numbers_in(suite.pull_requests));
63
+ }
64
+ else if (event === "check_run") {
65
+ const run = fields_of(values.check_run);
66
+ branches.push(branch_of(fields_of(run.check_suite).head_branch));
67
+ pull_requests.push(...numbers_in(run.pull_requests));
68
+ }
69
+ else if (event === "status") {
70
+ branches.push(...(Array.isArray(values.branches) ? values.branches : []).map((branch) => branch_of(fields_of(branch).name)));
71
+ }
72
+ else if (event === "issues" || event === "issue_comment") {
73
+ issues.push(number_of(fields_of(values.issue).number));
74
+ }
75
+ else
76
+ return null;
77
+ const kept = (list) => [...new Set(list.filter((value) => value !== null))].slice(0, most_targets);
78
+ return { repository, pull_requests: kept(pull_requests), branches: kept(branches), issues: kept(issues) };
79
+ }
80
+ // A delivery's targets as stored, each list left empty where the stored text is damaged.
81
+ export function read_targets(repository, stored) {
82
+ let fields = {};
83
+ try {
84
+ fields = fields_of(JSON.parse(stored));
85
+ }
86
+ catch {
87
+ fields = {};
88
+ }
89
+ const numbers = (value) => (Array.isArray(value) ? value.map(number_of).filter((number) => number !== null) : []);
90
+ const names = Array.isArray(fields.branches) ? fields.branches.map(branch_of).filter((branch) => branch !== null) : [];
91
+ return { repository, pull_requests: numbers(fields.pull_requests), branches: names, issues: numbers(fields.issues) };
92
+ }
93
+ // ── Addresses ────────────────────────────────────────────────────────────────
94
+ // A public address as saved: http or https with a host and maybe a path, no query, fragment or user; anything else throws.
95
+ export function read_public_url(typed) {
96
+ const trimmed = typed.trim().replace(/\/+$/, "");
97
+ if (trimmed === "")
98
+ return "";
99
+ let url;
100
+ try {
101
+ url = new URL(trimmed);
102
+ }
103
+ catch {
104
+ throw new Error("Give the address GitHub reaches this server at, such as https://example.org.");
105
+ }
106
+ if ((url.protocol !== "https:" && url.protocol !== "http:") || url.search || url.hash || url.username || url.password)
107
+ throw new Error("The address is http or https with a host and a path, and nothing more.");
108
+ return trimmed;
109
+ }
110
+ // The payload URL for a public address and the route's path, or "" when no address is given.
111
+ export function payload_url_of(public_url, path) {
112
+ const trimmed = public_url.trim().replace(/\/+$/, "");
113
+ return trimmed ? `${trimmed}${path}` : "";
114
+ }
115
+ // ── Receiving ────────────────────────────────────────────────────────────────
116
+ // Answers deliveries as `register_webhook_route`'s receive.
117
+ export function create_github_receiver({ secret, events = github_target_events, on_delivery, lockout = new AddressLockout(), remembered = 1000, unsigned_text = "The delivery is not signed with this server's webhook secret." }) {
118
+ // Delivery ids already taken, oldest first, so a replayed delivery is answered without being passed on again.
119
+ const seen = new Set();
120
+ return (address, headers, body) => {
121
+ if (lockout.is_locked(address))
122
+ return { status: 429, body: { message: "Too many deliveries were not signed; try again later." } };
123
+ const key = secret();
124
+ const signature = headers["x-hub-signature-256"];
125
+ if (key === "" || typeof signature !== "string" || !is_signed({ "x-hub-signature-256": signature }, body, key)) {
126
+ lockout.fail(address);
127
+ return { status: 401, body: { message: unsigned_text } };
128
+ }
129
+ lockout.succeed(address);
130
+ const header = headers["x-github-event"];
131
+ const event = typeof header === "string" ? header.toLowerCase() : "";
132
+ const targets = event === "ping" || events.includes(event) ? targets_of(event, parse_payload(body, headers["content-type"])) : null;
133
+ if (targets === null)
134
+ return { status: 204, body: { message: "" } };
135
+ const delivery_id = delivery_id_of(headers["x-github-delivery"]);
136
+ if (delivery_id && seen.has(delivery_id))
137
+ return { status: 200, body: { message: "Already received." } };
138
+ if (delivery_id) {
139
+ seen.add(delivery_id);
140
+ if (seen.size > remembered)
141
+ seen.delete(seen.values().next().value);
142
+ }
143
+ on_delivery({ delivery_id, event, targets });
144
+ return { status: 202, body: { message: event === "ping" ? "Pong." : "Received." } };
145
+ };
146
+ }
@@ -0,0 +1,7 @@
1
+ export declare function free_port(): Promise<number>;
2
+ export declare function temp_folder(name: string): string;
3
+ export declare function make_checkout(name?: string): string;
4
+ export declare function self_signed_certificate(): {
5
+ certificate_file: string;
6
+ key_file: string;
7
+ };
@@ -0,0 +1,44 @@
1
+ // Helpers an app's tests share when they reach servers and repositories for real, on this machine alone: a free port
2
+ // on the loopback address, throwaway folders, a git checkout with one commit, and a certificate that signs itself for
3
+ // localhost, as a home server's often does. The checkout needs git and the certificate openssl on the PATH.
4
+ // ── Imports ──────────────────────────────────────────────────────────────────
5
+ import { execFileSync } from "node:child_process";
6
+ import { mkdtempSync, writeFileSync } from "node:fs";
7
+ import { createServer } from "node:net";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ // ── Ports and folders ────────────────────────────────────────────────────────
11
+ // A port nothing listens on, found by asking for any port on the loopback address.
12
+ export function free_port() {
13
+ return new Promise((resolve, reject) => {
14
+ const probe = createServer();
15
+ probe.on("error", reject);
16
+ probe.listen(0, "127.0.0.1", () => {
17
+ const { port } = probe.address();
18
+ probe.close(() => resolve(port));
19
+ });
20
+ });
21
+ }
22
+ // A new empty folder under the system's temporary folder, its name starting with the one given.
23
+ export function temp_folder(name) {
24
+ return mkdtempSync(join(tmpdir(), `${name}-`));
25
+ }
26
+ // A throwaway git checkout on branch main with one commit holding a README, as a test's stand-in repository.
27
+ export function make_checkout(name = "checkout") {
28
+ const folder = temp_folder(name);
29
+ const git = (...args) => execFileSync("git", ["-c", "user.name=Test", "-c", "user.email=test@example.org", ...args], { cwd: folder, stdio: "ignore" });
30
+ git("init", "-q", "-b", "main");
31
+ writeFileSync(join(folder, "README.md"), "# Test\n");
32
+ git("add", ".");
33
+ git("commit", "-q", "-m", "chore: start");
34
+ return folder;
35
+ }
36
+ // ── Certificates ─────────────────────────────────────────────────────────────
37
+ // A certificate that signs itself for localhost and 127.0.0.1, valid for a month, and its key, in a folder of their own.
38
+ export function self_signed_certificate() {
39
+ const folder = temp_folder("certificate");
40
+ const certificate_file = join(folder, "server.pem");
41
+ const key_file = join(folder, "server.key");
42
+ execFileSync("openssl", ["req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes", "-keyout", key_file, "-out", certificate_file, "-days", "30", "-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1"], { stdio: "ignore" });
43
+ return { certificate_file, key_file };
44
+ }
@@ -14,6 +14,7 @@ import { Facts, FormRow, PageHeading, Section } from "./layout.js";
14
14
  import { Empty, Loaded, use_resource } from "./states.js";
15
15
  import { DataTable } from "./table.js";
16
16
  import { Age } from "./time.js";
17
+ import { CopyButton } from "./copy_button.js";
17
18
  import { toast } from "./toasts.js";
18
19
  const default_access_text = (access) => access === null ? "everything" : "limited";
19
20
  export function AccountView({ client, on_change, ...words }) {
@@ -311,7 +312,7 @@ function reset_totp(client, user, refresh) {
311
312
  // A secret the server hands out once, with a button to copy it.
312
313
  export function show_once(title, note, lines) {
313
314
  const text = lines.join("\n");
314
- open_dialog((close) => (_jsx(Dialog, { title: title, on_close: close, buttons: _jsxs(_Fragment, { children: [_jsx("button", { onClick: () => void navigator.clipboard?.writeText(text).then(() => toast("Copied.")), children: "Copy" }), _jsx("button", { className: "accent solid", onClick: close, children: "I have saved it" })] }), children: _jsxs("div", { children: [_jsx("p", { children: note }), _jsx("pre", { className: "output secret-once", children: text })] }) })));
315
+ open_dialog((close) => (_jsx(Dialog, { title: title, on_close: close, buttons: _jsxs(_Fragment, { children: [_jsx(CopyButton, { text: text }), _jsx("button", { className: "accent solid", onClick: close, children: "I have saved it" })] }), children: _jsxs("div", { children: [_jsx("p", { children: note }), _jsx("pre", { className: "output secret-once", children: text })] }) })));
315
316
  }
316
317
  // The server's words for a refusal, passing on anything else, such as a lapsed session.
317
318
  function refusal_of(error) {
@@ -46,8 +46,9 @@ interface SelectProps<Value extends string | number> {
46
46
  on_change: (value: Value) => void;
47
47
  bare?: boolean;
48
48
  id?: string;
49
+ disabled?: boolean;
49
50
  }
50
- export declare function Select<Value extends string | number>({ label, options, groups, value, on_change, bare, id }: SelectProps<Value>): import("react").JSX.Element;
51
+ export declare function Select<Value extends string | number>({ label, options, groups, value, on_change, bare, id, disabled }: SelectProps<Value>): import("react").JSX.Element;
51
52
  type CommitInputProps = Omit<InputHTMLAttributes<HTMLInputElement>, "value" | "defaultValue" | "onChange"> & {
52
53
  value: string | number;
53
54
  on_commit: (event: {
@@ -86,7 +87,7 @@ interface PathInputProps {
86
87
  label: string;
87
88
  value: string;
88
89
  on_change: (value: string) => void;
89
- pick: (current: string) => Promise<string | null>;
90
+ pick?: (current: string) => Promise<string | null>;
90
91
  placeholder?: string;
91
92
  disabled?: boolean;
92
93
  browse_label?: string;
@@ -106,14 +106,14 @@ export function SearchBox({ label, value, on_input, on_submit, on_paste, submit_
106
106
  return input;
107
107
  return (_jsxs("form", { className: "search-box", role: "search", onSubmit: (event) => { event.preventDefault(); submit(); }, children: [input, _jsx("button", { type: "submit", className: "accent solid", children: submit_label })] }));
108
108
  }
109
- export function Select({ label, options, groups = [], value, on_change, bare = false, id }) {
109
+ export function Select({ label, options, groups = [], value, on_change, bare = false, id, disabled = false }) {
110
110
  const shown_groups = groups.filter((group) => group.options.length > 0);
111
111
  const change = (event) => {
112
112
  const text = event.currentTarget.value;
113
113
  const every = [...options, ...shown_groups.flatMap((group) => group.options)];
114
114
  on_change((every.find(([option]) => String(option) === text)?.[0] ?? text));
115
115
  };
116
- const select = (_jsxs("select", { id: id, value: value, "aria-label": bare ? label : undefined, onChange: change, children: [options.map(([option, text]) => _jsx("option", { value: option, children: text }, option)), shown_groups.map((group) => (_jsx("optgroup", { label: group.label, children: group.options.map(([option, text]) => _jsx("option", { value: option, children: text }, option)) }, group.label)))] }));
116
+ const select = (_jsxs("select", { id: id, value: value, "aria-label": bare ? label : undefined, disabled: disabled, onChange: change, children: [options.map(([option, text]) => _jsx("option", { value: option, children: text }, option)), shown_groups.map((group) => (_jsx("optgroup", { label: group.label, children: group.options.map(([option, text]) => _jsx("option", { value: option, children: text }, option)) }, group.label)))] }));
117
117
  if (bare)
118
118
  return select;
119
119
  return (_jsxs("label", { className: "field", children: [_jsx("span", { className: "field-label", children: label }), select] }));
@@ -171,10 +171,12 @@ export function PeriodStepper({ label, period, value, on_change, now, locale })
171
171
  };
172
172
  return (_jsxs("div", { className: "stepper", role: "group", "aria-label": label, children: [_jsxs("div", { className: "date-time-inputs", children: [_jsx("button", { type: "button", "aria-label": `Previous ${period}`, onClick: () => shift(-1), children: "\u2039" }), _jsx("input", { type: is_daily ? "date" : "month", "aria-label": `Pick a ${period}`, value: value, onChange: (event) => pick(event.currentTarget.value) }), _jsx("button", { type: "button", "aria-label": `Next ${period}`, onClick: () => shift(1), children: "\u203A" })] }), _jsx("button", { type: "button", disabled: value === current, onClick: () => on_change(current), children: is_daily ? "Today" : "This month" }), _jsx("span", { className: "muted", children: is_daily ? relative_day_label(value, now, locale) : format_month(value, locale) })] }));
173
173
  }
174
- // A path typed by hand or picked through a Browse button.
174
+ // A path typed by hand or picked through a Browse button, when the app has a picker.
175
175
  export function PathInput({ label, value, on_change, pick, placeholder, disabled = false, browse_label = "Browse…" }) {
176
176
  const [picking, set_picking] = useState(false);
177
177
  async function browse() {
178
+ if (!pick)
179
+ return;
178
180
  set_picking(true);
179
181
  try {
180
182
  const chosen = await pick(value);
@@ -185,7 +187,7 @@ export function PathInput({ label, value, on_change, pick, placeholder, disabled
185
187
  set_picking(false);
186
188
  }
187
189
  }
188
- return (_jsxs("span", { className: "path-row", children: [_jsx("input", { type: "text", "aria-label": label, spellCheck: false, placeholder: placeholder, disabled: disabled, value: value, onChange: (event) => on_change(event.currentTarget.value) }), _jsx("button", { type: "button", disabled: disabled || picking, onClick: () => void browse(), children: browse_label })] }));
190
+ return (_jsxs("span", { className: "path-row", children: [_jsx("input", { type: "text", "aria-label": label, spellCheck: false, placeholder: placeholder, disabled: disabled, value: value, onChange: (event) => on_change(event.currentTarget.value) }), pick && _jsx("button", { type: "button", disabled: disabled || picking, onClick: () => void browse(), children: browse_label })] }));
189
191
  }
190
192
  // Swatches, a None choice, and the system colour chooser for any other colour.
191
193
  export function ColorPicker({ label, value, swatches, on_change, allow_none = true }) {
@@ -0,0 +1,11 @@
1
+ export declare function copy_text(text: string | (() => string | Promise<string>), copied_text?: string): Promise<boolean>;
2
+ interface CopyButtonProps {
3
+ text: string | (() => string | Promise<string>);
4
+ label?: string;
5
+ copied_text?: string;
6
+ class_name?: string;
7
+ title?: string;
8
+ disabled?: boolean;
9
+ }
10
+ export declare function CopyButton({ text, label, copied_text, class_name, title, disabled }: CopyButtonProps): import("react").JSX.Element;
11
+ export {};
@@ -0,0 +1,44 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ // Copying text to the clipboard with a "Copied." toast: `CopyButton` copies what it is given, or what a function gives
3
+ // back when pressed, such as a secret fetched only then, and `copy_text` does the same from anywhere; a page the browser
4
+ // will not let copy says so instead of failing quietly.
5
+ // ── Imports ──────────────────────────────────────────────────────────────────
6
+ import { useState } from "react";
7
+ import { describe_error } from "../errors.js";
8
+ import { toast } from "./toasts.js";
9
+ // ── Copying ──────────────────────────────────────────────────────────────────
10
+ // Copies the text and says so in a toast; false when the clipboard refused it or getting the text failed.
11
+ export async function copy_text(text, copied_text = "Copied.") {
12
+ let value;
13
+ try {
14
+ value = typeof text === "function" ? await text() : text;
15
+ }
16
+ catch (error) {
17
+ toast(describe_error(error), { tone: "bad" });
18
+ return false;
19
+ }
20
+ try {
21
+ if (!navigator.clipboard)
22
+ throw new Error("no clipboard");
23
+ await navigator.clipboard.writeText(value);
24
+ }
25
+ catch {
26
+ toast("Could not copy; select the text and copy it by hand.", { tone: "bad" });
27
+ return false;
28
+ }
29
+ toast(copied_text);
30
+ return true;
31
+ }
32
+ export function CopyButton({ text, label = "Copy", copied_text = "Copied.", class_name, title, disabled = false }) {
33
+ const [busy, set_busy] = useState(false);
34
+ async function copy() {
35
+ set_busy(true);
36
+ try {
37
+ await copy_text(text, copied_text);
38
+ }
39
+ finally {
40
+ set_busy(false);
41
+ }
42
+ }
43
+ return (_jsx("button", { type: "button", className: class_name, title: title, "aria-label": title, disabled: disabled || busy, onClick: () => void copy(), children: label }));
44
+ }
@@ -2,7 +2,7 @@ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-run
2
2
  // Modal dialogs on the native one: any body and buttons, one that asks before an action, and one that shows a long text.
3
3
  import { Fragment, useEffect, useId, useRef, useState } from "react";
4
4
  import { SettingRow } from "./layout.js";
5
- import { toast } from "./toasts.js";
5
+ import { CopyButton } from "./copy_button.js";
6
6
  // Shown while it is rendered: the page behind it is inert, focus stays inside, Escape calls on_close, and focus goes back to the opener after.
7
7
  export function Dialog({ title, subtitle, actions, on_close, buttons, form, wide = false, full = false, class_name, children }) {
8
8
  const dialog = useRef(null);
@@ -49,7 +49,7 @@ export function ConfirmDialog({ options, on_close }) {
49
49
  }
50
50
  // Shows a long text result, such as a preview, with a button to copy it.
51
51
  export function TextDialog({ title, text, on_close }) {
52
- return (_jsx(Dialog, { title: title, on_close: on_close, wide: true, buttons: _jsxs(_Fragment, { children: [_jsx("button", { onClick: () => void navigator.clipboard?.writeText(text).then(() => toast("Copied.")), children: "Copy" }), _jsx("button", { className: "accent solid", onClick: on_close, children: "Close" })] }), children: _jsx("pre", { className: "output", children: text }) }));
52
+ return (_jsx(Dialog, { title: title, on_close: on_close, wide: true, buttons: _jsxs(_Fragment, { children: [_jsx(CopyButton, { text: text }), _jsx("button", { className: "accent solid", onClick: on_close, children: "Close" })] }), children: _jsx("pre", { className: "output", children: text }) }));
53
53
  }
54
54
  let open = [];
55
55
  let next_id = 1;
@@ -0,0 +1,26 @@
1
+ import { type DiffFile, type DiffFileStatus } from "../../diff_rows.ts";
2
+ import type { Tone } from "./badges.tsx";
3
+ export declare const diff_status_words: Record<DiffFileStatus, [label: string, letter: string, tone: Tone]>;
4
+ export type DiffLayout = "split" | "unified";
5
+ export declare function DiffCounts({ additions, deletions }: {
6
+ additions: number;
7
+ deletions: number;
8
+ }): import("react").JSX.Element;
9
+ interface FileDiffProps {
10
+ file: DiffFile;
11
+ layout: DiffLayout;
12
+ no_lines_text?: string;
13
+ }
14
+ export declare function FileDiff({ file, layout, no_lines_text }: FileDiffProps): import("react").JSX.Element;
15
+ export declare function FileContent({ path, text }: {
16
+ path: string;
17
+ text: string;
18
+ }): import("react").JSX.Element;
19
+ interface EditDiffProps {
20
+ path?: string;
21
+ before: string;
22
+ after: string;
23
+ limit?: number;
24
+ }
25
+ export declare function EditDiff({ path, before, after, limit }: EditDiffProps): import("react").JSX.Element;
26
+ export {};