@x-tech-laboratories/x-app 0.119.0 → 0.121.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -2
- package/dist/app/daemon.d.ts +7 -1
- package/dist/app/daemon.js +76 -8
- package/dist/app/define.d.ts +22 -1
- package/dist/app/define.js +34 -1
- package/dist/app/desktop.d.ts +13 -0
- package/dist/app/desktop.js +35 -3
- package/dist/app/host_tables.d.ts +20 -0
- package/dist/app/host_tables.js +91 -0
- package/dist/app/preload.js +5 -0
- package/dist/app/protocol.d.ts +29 -1
- package/dist/app/protocol.js +8 -1
- package/dist/app/remote_access.d.ts +17 -0
- package/dist/app/remote_access.js +85 -0
- package/dist/app/server.d.ts +12 -4
- package/dist/app/server.js +63 -14
- package/dist/app/services.d.ts +15 -0
- package/dist/app/web/android.d.ts +1 -1
- package/dist/app/web/android.js +9 -0
- package/dist/app/web/app_page.js +43 -6
- package/dist/app/web/hosts.d.ts +4 -2
- package/dist/app/web/hosts.js +33 -0
- package/dist/app/web/page.d.ts +3 -0
- package/dist/app/web/page.js +24 -4
- package/dist/app/web/portal.d.ts +14 -0
- package/dist/app/web/portal.js +115 -0
- package/dist/app/web/settings_page.d.ts +5 -1
- package/dist/app/web/settings_page.js +25 -6
- package/dist/change_checks.js +1 -1
- package/dist/github_targets.d.ts +12 -0
- package/dist/github_targets.js +90 -0
- package/dist/remote_access_protocol.d.ts +26 -0
- package/dist/remote_access_protocol.js +33 -0
- package/dist/server/github_webhook.d.ts +2 -12
- package/dist/server/github_webhook.js +2 -87
- package/dist/sql.d.ts +5 -0
- package/dist/sql.js +21 -0
- package/dist/web/react/remote_access_settings.d.ts +5 -0
- package/dist/web/react/remote_access_settings.js +55 -0
- package/dist/web/remote_daemon.d.ts +26 -0
- package/dist/web/remote_daemon.js +105 -0
- package/package.json +1 -1
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// "Let other devices connect" for a desktop daemon's own calls: its network address, off unless turned on, behind the
|
|
2
|
+
// sign-in, so a phone, a browser or another computer's desktop app can work on this computer, such as on files only it
|
|
3
|
+
// holds. It is apart from sync's own listening, which lets paired devices sync with it.
|
|
4
|
+
// Off, on every network, at the port given, such as the app's web server's, over plain http.
|
|
5
|
+
export function remote_access_defaults(port) {
|
|
6
|
+
return { enabled: false, host: "0.0.0.0", port, certificate_file: "", key_file: "" };
|
|
7
|
+
}
|
|
8
|
+
const host_pattern = /^[A-Za-z0-9.:[\]_-]+$/;
|
|
9
|
+
// Settings saved on the computer, each default where it is missing or damaged.
|
|
10
|
+
export function read_remote_access(saved, default_port) {
|
|
11
|
+
const defaults = remote_access_defaults(default_port);
|
|
12
|
+
const fields = (saved ?? {});
|
|
13
|
+
const port = Number(fields.port);
|
|
14
|
+
const text = (value) => (typeof value === "string" ? value.trim() : "");
|
|
15
|
+
return {
|
|
16
|
+
enabled: fields.enabled === true,
|
|
17
|
+
host: typeof fields.host === "string" && host_pattern.test(fields.host.trim()) ? fields.host.trim() : defaults.host,
|
|
18
|
+
port: Number.isInteger(port) && port > 0 && port < 65536 ? port : defaults.port,
|
|
19
|
+
certificate_file: text(fields.certificate_file),
|
|
20
|
+
key_file: text(fields.key_file),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
// Why the settings cannot be used as they are, or "" when they can.
|
|
24
|
+
export function remote_access_problem(settings, admins) {
|
|
25
|
+
if (!settings.enabled)
|
|
26
|
+
return "";
|
|
27
|
+
if (admins.length === 0)
|
|
28
|
+
return "Add an admin first, so a device has someone to sign in as.";
|
|
29
|
+
if ((settings.certificate_file === "") !== (settings.key_file === ""))
|
|
30
|
+
return "Give both the certificate and its key, or neither.";
|
|
31
|
+
return "";
|
|
32
|
+
}
|
|
33
|
+
export const remote_access_method_names = ["get_remote_access", "set_remote_access", "set_remote_admin", "remove_remote_admin"];
|
|
@@ -1,12 +1,7 @@
|
|
|
1
1
|
import type { IncomingHttpHeaders } from "node:http";
|
|
2
2
|
import { AddressLockout, type WebhookAnswer } from "./forge_webhook.ts";
|
|
3
|
-
export
|
|
4
|
-
|
|
5
|
-
repository: string;
|
|
6
|
-
pull_requests: number[];
|
|
7
|
-
branches: string[];
|
|
8
|
-
issues: number[];
|
|
9
|
-
}
|
|
3
|
+
export { github_target_events, is_repository_name, repository_of, delivery_id_of, targets_of, read_targets, type WebhookTargets } from "../github_targets.ts";
|
|
4
|
+
import type { WebhookTargets } from "../github_targets.ts";
|
|
10
5
|
export interface GitHubDelivery {
|
|
11
6
|
delivery_id: string;
|
|
12
7
|
event: string;
|
|
@@ -20,11 +15,6 @@ export interface GitHubReceiverOptions {
|
|
|
20
15
|
remembered?: number;
|
|
21
16
|
unsigned_text?: string;
|
|
22
17
|
}
|
|
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
18
|
export declare function read_public_url(typed: string): string;
|
|
29
19
|
export declare function payload_url_of(public_url: string, path: string): string;
|
|
30
20
|
export declare function create_github_receiver({ secret, events, on_delivery, lockout, remembered, unsigned_text }: GitHubReceiverOptions): (address: string, headers: IncomingHttpHeaders, body: Buffer) => WebhookAnswer;
|
|
@@ -2,94 +2,9 @@
|
|
|
2
2
|
// app's secret, never by a bearer token or another forge's header; an address that keeps failing waits; a delivery id
|
|
3
3
|
// seen before is answered without being passed on again; and of each delivery only the repository and the pull
|
|
4
4
|
// requests, branches and issues it names are kept, each checked for shape, for the app to look up for itself.
|
|
5
|
+
import { delivery_id_of, github_target_events, targets_of } from "../github_targets.js";
|
|
5
6
|
import { AddressLockout, is_signed, parse_payload } from "./forge_webhook.js";
|
|
6
|
-
|
|
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
|
-
}
|
|
7
|
+
export { github_target_events, is_repository_name, repository_of, delivery_id_of, targets_of, read_targets } from "../github_targets.js";
|
|
93
8
|
// ── Addresses ────────────────────────────────────────────────────────────────
|
|
94
9
|
// A public address as saved: http or https with a host and maybe a path, no query, fragment or user; anything else throws.
|
|
95
10
|
export function read_public_url(typed) {
|
package/dist/sql.d.ts
CHANGED
|
@@ -20,3 +20,8 @@ export interface MigrateOptions {
|
|
|
20
20
|
owner?: string;
|
|
21
21
|
}
|
|
22
22
|
export declare function migrate(database: SqlDatabase, steps: readonly MigrationStep[], options?: MigrateOptions): void;
|
|
23
|
+
export declare const tidy_every_ms: number;
|
|
24
|
+
export interface TidyOptions {
|
|
25
|
+
free_share?: number;
|
|
26
|
+
}
|
|
27
|
+
export declare function tidy_database(database: SqlDatabase, options?: TidyOptions): boolean;
|
package/dist/sql.js
CHANGED
|
@@ -38,3 +38,24 @@ export function migrate(database, steps, options = {}) {
|
|
|
38
38
|
});
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
|
+
// ── Upkeep ───────────────────────────────────────────────────────────────────
|
|
42
|
+
// How often an app keeps its open database tidy.
|
|
43
|
+
export const tidy_every_ms = 24 * 60 * 60 * 1000;
|
|
44
|
+
// Refreshes the query planner's statistics, and rewrites the file without its empty pages once enough of it is empty;
|
|
45
|
+
// says whether it rewrote it. A rewrite held up by another connection's write is left for next time.
|
|
46
|
+
export function tidy_database(database, options = {}) {
|
|
47
|
+
database.exec("PRAGMA optimize");
|
|
48
|
+
const { page_count } = database.prepare("PRAGMA page_count").get();
|
|
49
|
+
const { freelist_count } = database.prepare("PRAGMA freelist_count").get();
|
|
50
|
+
if (page_count === 0 || freelist_count / page_count < (options.free_share ?? 0.1))
|
|
51
|
+
return false;
|
|
52
|
+
try {
|
|
53
|
+
database.exec("VACUUM");
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
// The rewrite passes through the write-ahead log, which is emptied so it does not keep the old size on disk.
|
|
59
|
+
database.exec("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
// "Let other devices connect": whether this computer's daemon listens on the network, where, over https or not, and
|
|
3
|
+
// the admins a phone, a browser or another computer signs in as, for Settings on the desktop.
|
|
4
|
+
// ── Imports ──────────────────────────────────────────────────────────────────
|
|
5
|
+
import { useEffect, useState } from "react";
|
|
6
|
+
import { StatusPill } from "./badges.js";
|
|
7
|
+
import { Switch } from "./controls.js";
|
|
8
|
+
import { confirm_dialog } from "./dialog.js";
|
|
9
|
+
import { SettingRow } from "./layout.js";
|
|
10
|
+
import { attempt_value as attempt, show_error } from "./toasts.js";
|
|
11
|
+
// What other devices can do once signed in, for the switch's hint.
|
|
12
|
+
const default_reach = "Phones, browsers and other computers sign in as an admin below and work on this computer's data with its rights.";
|
|
13
|
+
// ── Section ──────────────────────────────────────────────────────────────────
|
|
14
|
+
export function RemoteAccessSettings({ remote, reach = default_reach }) {
|
|
15
|
+
const [status, set_status] = useState(null);
|
|
16
|
+
const [draft, set_draft] = useState(null);
|
|
17
|
+
const [name, set_name] = useState("");
|
|
18
|
+
const [password, set_password] = useState("");
|
|
19
|
+
useEffect(() => {
|
|
20
|
+
void remote.get_remote_access().then((found) => {
|
|
21
|
+
set_status(found);
|
|
22
|
+
set_draft(found.settings);
|
|
23
|
+
}, show_error);
|
|
24
|
+
}, [remote]);
|
|
25
|
+
if (!status || !draft)
|
|
26
|
+
return null;
|
|
27
|
+
async function save(next) {
|
|
28
|
+
const saved = await attempt(() => remote.set_remote_access(next));
|
|
29
|
+
if (saved) {
|
|
30
|
+
set_status(saved);
|
|
31
|
+
set_draft(saved.settings);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
async function add_admin() {
|
|
35
|
+
const saved = await attempt(() => remote.set_remote_admin(name, password), `${name.trim()} can sign in from other devices.`);
|
|
36
|
+
if (!saved)
|
|
37
|
+
return;
|
|
38
|
+
set_status(saved);
|
|
39
|
+
set_name("");
|
|
40
|
+
set_password("");
|
|
41
|
+
}
|
|
42
|
+
function remove_admin(admin) {
|
|
43
|
+
confirm_dialog({
|
|
44
|
+
title: `Remove ${admin}?`,
|
|
45
|
+
message: "Devices signed in as them can no longer reach this computer.",
|
|
46
|
+
confirm_label: "Remove",
|
|
47
|
+
danger: true,
|
|
48
|
+
run: async () => void (await attempt(() => remote.remove_remote_admin(admin)).then((saved) => saved && set_status(saved))),
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
const field = (key, label, hint, placeholder = "") => (_jsx(SettingRow, { label: label, hint: hint, as_label: true, children: _jsx("input", { type: "text", spellCheck: false, placeholder: placeholder, value: draft[key], onChange: (event) => set_draft({ ...draft, [key]: event.currentTarget.value }) }) }));
|
|
52
|
+
const is_changed = JSON.stringify(draft) !== JSON.stringify(status.settings);
|
|
53
|
+
const state = status.listening ? _jsx(StatusPill, { tone: "good", label: `Listening on ${status.listening}` }) : status.problem ? _jsx(StatusPill, { tone: "bad", label: status.problem }) : _jsx(StatusPill, { label: "Off" });
|
|
54
|
+
return (_jsxs(_Fragment, { children: [_jsx(SettingRow, { label: "Let other devices connect", hint: `${reach} Use https, a VPN or a reverse proxy; plain http sends passwords and tokens as they are.`, as_label: true, children: _jsx(Switch, { label: "Let other devices connect", checked: status.settings.enabled, on_change: (on) => void save({ ...draft, enabled: on }) }) }), _jsx(SettingRow, { label: "State", children: state }), field("host", "Address", "Where to listen: 0.0.0.0 for every network, or one address such as a VPN's.", "0.0.0.0"), _jsx(SettingRow, { label: "Port", as_label: true, children: _jsx("input", { type: "number", min: 1, max: 65535, value: draft.port, onChange: (event) => set_draft({ ...draft, port: Number(event.currentTarget.value) }) }) }), field("certificate_file", "Certificate file", "The https certificate, as a PEM file; empty for plain http.", "/path/to/cert.pem"), field("key_file", "Key file", "The certificate's private key, as a PEM file.", "/path/to/key.pem"), _jsx(SettingRow, { label: "Save", hint: "Listens again with these settings.", children: _jsx("button", { type: "button", disabled: !is_changed, onClick: () => void save(draft), children: "Save" }) }), status.admins.map((admin) => (_jsx(SettingRow, { label: admin, hint: "An admin who may sign in from other devices", children: _jsx("button", { type: "button", className: "danger", onClick: () => remove_admin(admin), children: "Remove" }) }, admin))), _jsxs("form", { onSubmit: (event) => { event.preventDefault(); void add_admin(); }, children: [_jsx(SettingRow, { label: "Admin name", hint: "Signing in again with a new password changes it.", as_label: true, children: _jsx("input", { type: "text", autoCapitalize: "none", spellCheck: false, autoComplete: "off", value: name, onChange: (event) => set_name(event.currentTarget.value) }) }), _jsx(SettingRow, { label: "Password", hint: "At least 10 characters.", as_label: true, children: _jsx("input", { type: "password", autoComplete: "new-password", value: password, onChange: (event) => set_password(event.currentTarget.value) }) }), _jsx(SettingRow, { label: "Add an admin", children: _jsx("button", { type: "submit", disabled: name.trim() === "" || password === "", children: "Add Admin" }) })] })] }));
|
|
55
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export type RemoteRemoteClient<Methods> = {
|
|
2
|
+
[Name in keyof Methods]: Methods[Name] extends (...args: infer Args) => infer Result ? (...args: Args) => Promise<Awaited<Result>> : never;
|
|
3
|
+
};
|
|
4
|
+
export type RemoteClient<Methods> = {
|
|
5
|
+
[Name in keyof Methods]: Methods[Name] extends (...args: infer Args) => infer Result ? (...args: Args) => Promise<Awaited<Result>> : never;
|
|
6
|
+
};
|
|
7
|
+
export interface RemoteDaemon {
|
|
8
|
+
address: string;
|
|
9
|
+
token: string;
|
|
10
|
+
}
|
|
11
|
+
export interface RemoteLink {
|
|
12
|
+
daemon: () => RemoteDaemon | null;
|
|
13
|
+
client_id: () => string;
|
|
14
|
+
fetch?: typeof fetch;
|
|
15
|
+
}
|
|
16
|
+
export declare function call_remote(link: RemoteLink, path: string, args: unknown[]): Promise<unknown>;
|
|
17
|
+
export declare function remote_table<Methods extends Record<keyof Methods, (...args: never[]) => unknown>>(link: RemoteLink, prefix: string): RemoteClient<Methods>;
|
|
18
|
+
export interface FollowRemoteOptions {
|
|
19
|
+
retry_ms?: number;
|
|
20
|
+
on_connect?: () => void;
|
|
21
|
+
}
|
|
22
|
+
export declare function parse_remote_event(block: string): {
|
|
23
|
+
event: string;
|
|
24
|
+
data: string;
|
|
25
|
+
} | null;
|
|
26
|
+
export declare function follow_remote(link: RemoteLink, on_event: (event: string, data: string) => void, options?: FollowRemoteOptions): () => void;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// A page's calls to a daemon or server on another computer, made from the page itself with this device's token, as a
|
|
2
|
+
// phone that keeps no data makes them: each call posted under its table's path, and the host's events followed over a
|
|
3
|
+
// stream read by hand, since EventSource sends no token.
|
|
4
|
+
// ── Imports ──────────────────────────────────────────────────────────────────
|
|
5
|
+
import { LoginNeeded } from "./states.js";
|
|
6
|
+
const no_daemon_text = "No daemon is chosen yet. Add one under Settings → Connections.";
|
|
7
|
+
// One call to the daemon, its arguments as a JSON list; a refusal throws the daemon's words.
|
|
8
|
+
export async function call_remote(link, path, args) {
|
|
9
|
+
const daemon = link.daemon();
|
|
10
|
+
if (daemon === null)
|
|
11
|
+
throw new Error(no_daemon_text);
|
|
12
|
+
let response;
|
|
13
|
+
try {
|
|
14
|
+
response = await (link.fetch ?? fetch)(`${daemon.address}${path}`, {
|
|
15
|
+
method: "POST",
|
|
16
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${daemon.token}`, "x-client-id": link.client_id() },
|
|
17
|
+
body: JSON.stringify(args),
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
throw new Error(`The daemon at ${daemon.address} did not answer.`);
|
|
22
|
+
}
|
|
23
|
+
const text = await response.text();
|
|
24
|
+
if (response.status === 401)
|
|
25
|
+
throw new LoginNeeded("This device's sign-in was refused; add the daemon again under Settings → Connections.");
|
|
26
|
+
if (!response.ok)
|
|
27
|
+
throw new Error(error_text(text) || `The daemon answered ${response.status}.`);
|
|
28
|
+
return text === "" ? undefined : JSON.parse(text);
|
|
29
|
+
}
|
|
30
|
+
// The words of a refusal, sent as JSON with an error or message, or as plain text.
|
|
31
|
+
function error_text(text) {
|
|
32
|
+
try {
|
|
33
|
+
const parsed = JSON.parse(text);
|
|
34
|
+
return String(parsed.error ?? parsed.message ?? text);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return text;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
// Every call of a table by name, posted under its path, such as "/api/runner/"; the daemon refuses names it lacks.
|
|
41
|
+
export function remote_table(link, prefix) {
|
|
42
|
+
return new Proxy({}, {
|
|
43
|
+
get: (_target, name) => (typeof name === "string" && name !== "then" ? (...args) => call_remote(link, `${prefix}${name}`, args) : undefined),
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
// One server-sent event's name and data, or null for a comment or keep-alive.
|
|
47
|
+
export function parse_remote_event(block) {
|
|
48
|
+
let event = "message";
|
|
49
|
+
const data = [];
|
|
50
|
+
for (const line of block.split("\n")) {
|
|
51
|
+
if (line.startsWith("event:"))
|
|
52
|
+
event = line.slice(6).trim();
|
|
53
|
+
else if (line.startsWith("data:"))
|
|
54
|
+
data.push(line.slice(5).replace(/^ /, ""));
|
|
55
|
+
}
|
|
56
|
+
return data.length ? { event, data: data.join("\n") } : null;
|
|
57
|
+
}
|
|
58
|
+
// Follows the daemon's change events with the token, reconnecting whenever the stream ends; returns how to stop.
|
|
59
|
+
export function follow_remote(link, on_event, options = {}) {
|
|
60
|
+
const retry_ms = options.retry_ms ?? 5000;
|
|
61
|
+
let stopped = false;
|
|
62
|
+
let retry;
|
|
63
|
+
let stream = null;
|
|
64
|
+
async function read() {
|
|
65
|
+
const daemon = link.daemon();
|
|
66
|
+
if (daemon === null)
|
|
67
|
+
return;
|
|
68
|
+
stream = new AbortController();
|
|
69
|
+
const response = await (link.fetch ?? fetch)(`${daemon.address}/api/events`, { headers: { accept: "text/event-stream", authorization: `Bearer ${daemon.token}` }, signal: stream.signal });
|
|
70
|
+
if (!response.ok || !response.body)
|
|
71
|
+
return void (await response.body?.cancel());
|
|
72
|
+
options.on_connect?.();
|
|
73
|
+
const reader = response.body.getReader();
|
|
74
|
+
const decoder = new TextDecoder();
|
|
75
|
+
let buffer = "";
|
|
76
|
+
for (;;) {
|
|
77
|
+
const { value, done } = await reader.read();
|
|
78
|
+
if (done)
|
|
79
|
+
return;
|
|
80
|
+
buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n");
|
|
81
|
+
let cut;
|
|
82
|
+
while ((cut = buffer.indexOf("\n\n")) >= 0) {
|
|
83
|
+
const parsed = parse_remote_event(buffer.slice(0, cut));
|
|
84
|
+
buffer = buffer.slice(cut + 2);
|
|
85
|
+
if (parsed)
|
|
86
|
+
on_event(parsed.event, parsed.data);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function open() {
|
|
91
|
+
void read()
|
|
92
|
+
.catch(() => undefined)
|
|
93
|
+
.finally(() => {
|
|
94
|
+
stream = null;
|
|
95
|
+
if (!stopped)
|
|
96
|
+
retry = setTimeout(open, retry_ms);
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
open();
|
|
100
|
+
return () => {
|
|
101
|
+
stopped = true;
|
|
102
|
+
clearTimeout(retry);
|
|
103
|
+
stream?.abort();
|
|
104
|
+
};
|
|
105
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@x-tech-laboratories/x-app",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.121.0",
|
|
4
4
|
"description": "Code the X-apps share: agents and their long runs, passwords and sign-in, the Fastify server pieces, durations, and the web page's helpers and widgets",
|
|
5
5
|
"license": "GPL-3.0-or-later",
|
|
6
6
|
"repository": {
|