@x-tech-laboratories/x-app 0.128.0 → 0.130.1

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 (71) hide show
  1. package/README.md +28 -4
  2. package/dist/agent/claude_stream.d.ts +1 -22
  3. package/dist/agent/claude_stream.js +2 -85
  4. package/dist/agent/client.d.ts +1 -35
  5. package/dist/agent/client.js +2 -169
  6. package/dist/agent/commands.d.ts +1 -22
  7. package/dist/agent/commands.js +2 -80
  8. package/dist/agent/desktop_notify.d.ts +1 -54
  9. package/dist/agent/desktop_notify.js +2 -229
  10. package/dist/agent/firefox_bookmarks.d.ts +1 -29
  11. package/dist/agent/firefox_bookmarks.js +2 -147
  12. package/dist/agent/git.d.ts +1 -37
  13. package/dist/agent/git.js +2 -121
  14. package/dist/agent/github.d.ts +1 -81
  15. package/dist/agent/github.js +2 -185
  16. package/dist/agent/inhibit.d.ts +1 -32
  17. package/dist/agent/inhibit.js +2 -141
  18. package/dist/agent/keys.d.ts +1 -26
  19. package/dist/agent/keys.js +2 -161
  20. package/dist/agent/local_socket.d.ts +1 -18
  21. package/dist/agent/local_socket.js +2 -106
  22. package/dist/agent/long_runs.d.ts +1 -45
  23. package/dist/agent/long_runs.js +2 -419
  24. package/dist/agent/programs.d.ts +1 -60
  25. package/dist/agent/programs.js +2 -237
  26. package/dist/agent/protocol.d.ts +1 -172
  27. package/dist/agent/protocol.js +2 -249
  28. package/dist/agent/scheduled_notices.d.ts +1 -21
  29. package/dist/agent/scheduled_notices.js +2 -38
  30. package/dist/agent/session.d.ts +1 -61
  31. package/dist/agent/session.js +2 -335
  32. package/dist/agent/ssh_config.d.ts +1 -12
  33. package/dist/agent/ssh_config.js +2 -72
  34. package/dist/agent/stalls.d.ts +1 -44
  35. package/dist/agent/stalls.js +2 -176
  36. package/dist/agent/tasks.d.ts +1 -17
  37. package/dist/agent/tasks.js +2 -15
  38. package/dist/agent/wake.d.ts +1 -14
  39. package/dist/agent/wake.js +2 -88
  40. package/dist/agent/worktree_files.d.ts +1 -20
  41. package/dist/agent/worktree_files.js +2 -69
  42. package/dist/app/define.d.ts +10 -1
  43. package/dist/app/define.js +1 -0
  44. package/dist/app/desktop.js +29 -9
  45. package/dist/app/outside_fetch.d.ts +40 -0
  46. package/dist/app/outside_fetch.js +94 -0
  47. package/dist/app/outside_route.d.ts +3 -0
  48. package/dist/app/outside_route.js +51 -0
  49. package/dist/app/preload.js +2 -0
  50. package/dist/app/protocol.d.ts +1 -0
  51. package/dist/app/server.js +3 -0
  52. package/dist/app/web/app_page.js +33 -4
  53. package/dist/app/web/hosts.d.ts +2 -2
  54. package/dist/app/web/hosts.js +12 -1
  55. package/dist/app/web/settings_page.d.ts +1 -0
  56. package/dist/config/capacitor.js +1 -1
  57. package/dist/daemon_link.d.ts +2 -1
  58. package/dist/daemon_link.js +4 -2
  59. package/dist/durations.d.ts +1 -15
  60. package/dist/durations.js +2 -52
  61. package/dist/site/build.d.ts +1 -1
  62. package/dist/site/build.js +28 -8
  63. package/dist/site/content.js +6 -8
  64. package/dist/site/links.d.ts +11 -0
  65. package/dist/site/links.js +55 -0
  66. package/dist/site/markdown.d.ts +5 -2
  67. package/dist/site/markdown.js +14 -11
  68. package/dist/site/model.d.ts +2 -1
  69. package/dist/site/model.js +12 -3
  70. package/dist/web/react/phone.js +2 -1
  71. package/package.json +5 -3
@@ -0,0 +1,94 @@
1
+ // The page's requests to the outside sites an app names, such as a video site's API, which a browser's cross-origin
2
+ // rules would block: the desktop app sends them from its main process, a browser through its server's signed-in route,
3
+ // and a phone with Android's own HTTP. Each host sets the site's own headers last, such as an Origin the site insists
4
+ // on, which a page cannot set itself.
5
+ // ── Imports ──────────────────────────────────────────────────────────────────
6
+ import { is_allowed_url } from "../electron/fetch.js";
7
+ // The page's headers with the sites' own set over them.
8
+ export function with_site_headers(headers, sites) {
9
+ const pinned = Object.entries(sites.headers ?? {});
10
+ const names = new Set(pinned.map(([name]) => name.toLowerCase()));
11
+ return [...headers.filter(([name]) => !names.has(name.toLowerCase())), ...pinned];
12
+ }
13
+ // The server's route under /api, and where a page posts to it.
14
+ export const outside_route = "/outside";
15
+ export const outside_path = "api/outside";
16
+ // The site's own status and headers travel in these, so they are never taken for the server's own.
17
+ export const status_header = "x-outside-status";
18
+ export const status_text_header = "x-outside-status-text";
19
+ export const headers_header = "x-outside-headers";
20
+ export const NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
21
+ // The body arrives unpacked, so the headers describing the packed body go.
22
+ export const DROPPED_HEADERS = new Set(["content-encoding", "content-length", "transfer-encoding", "connection"]);
23
+ export function is_outside_request(value) {
24
+ const request = value;
25
+ return (typeof request?.url === "string" &&
26
+ typeof request.method === "string" &&
27
+ Array.isArray(request.headers) &&
28
+ request.headers.every((pair) => Array.isArray(pair) && pair.length === 2 && pair.every((part) => typeof part === "string")) &&
29
+ (request.body === undefined || typeof request.body === "string"));
30
+ }
31
+ export function bytes_of_base64(text) {
32
+ const binary = atob(text);
33
+ const bytes = new Uint8Array(binary.length);
34
+ for (let index = 0; index < binary.length; index++)
35
+ bytes[index] = binary.charCodeAt(index);
36
+ return bytes;
37
+ }
38
+ export function base64_of_bytes(bytes) {
39
+ let binary = "";
40
+ for (let start = 0; start < bytes.length; start += 0x8000)
41
+ binary += String.fromCharCode(...bytes.subarray(start, start + 0x8000));
42
+ return btoa(binary);
43
+ }
44
+ // The parts of a request a host sends on, its body read into bytes.
45
+ async function read_request(input, init) {
46
+ const request = new Request(input, init);
47
+ const body = request.method === "GET" || request.method === "HEAD" ? undefined : new Uint8Array(await request.arrayBuffer());
48
+ return { request, headers: [...new Headers(request.headers).entries()], body };
49
+ }
50
+ // A browser's fetch of the sites, through its server's route with its own sign-in; the answer's body streams.
51
+ export function web_outside_fetch(post = (input, init) => fetch(input, init)) {
52
+ return async (input, init) => {
53
+ const { request, headers, body } = await read_request(input, init);
54
+ const envelope = { url: request.url, method: request.method, headers, ...(body ? { body: base64_of_bytes(body) } : {}) };
55
+ const response = await post(outside_path, {
56
+ method: "POST",
57
+ headers: { "content-type": "application/json" },
58
+ body: JSON.stringify(envelope),
59
+ signal: init?.signal ?? request.signal,
60
+ });
61
+ const status = response.headers.get(status_header);
62
+ if (status === null)
63
+ throw new TypeError((await response.text()) || `The server refused the request (${response.status}).`);
64
+ const site_status = Number(status);
65
+ return new Response(NULL_BODY_STATUSES.has(site_status) ? null : response.body, {
66
+ status: site_status,
67
+ statusText: decodeURIComponent(response.headers.get(status_text_header) ?? ""),
68
+ headers: JSON.parse(decodeURIComponent(response.headers.get(headers_header) ?? "%5B%5D")),
69
+ });
70
+ };
71
+ }
72
+ // A phone's fetch of the sites with Android's own HTTP, which no cross-origin rule stops; the answer comes whole.
73
+ export function phone_outside_fetch(http, sites) {
74
+ return async (input, init) => {
75
+ const { request, headers, body } = await read_request(input, init);
76
+ const url = request.url;
77
+ if (!is_allowed_url(url, { hosts: sites.hosts }))
78
+ throw new TypeError(`Fetching ${url} is not allowed.`);
79
+ const answer = await http.request({
80
+ url,
81
+ method: request.method,
82
+ headers: Object.fromEntries(with_site_headers(headers, sites)),
83
+ ...(body ? { data: base64_of_bytes(body), dataType: "file" } : {}),
84
+ responseType: "arraybuffer",
85
+ });
86
+ const bytes = NULL_BODY_STATUSES.has(answer.status) || request.method === "HEAD"
87
+ ? null
88
+ : typeof answer.data === "string"
89
+ ? bytes_of_base64(answer.data)
90
+ : new TextEncoder().encode(JSON.stringify(answer.data ?? null));
91
+ const answer_headers = Object.entries(answer.headers).filter(([name]) => !DROPPED_HEADERS.has(name.toLowerCase()));
92
+ return new Response(bytes, { status: answer.status, headers: answer_headers });
93
+ };
94
+ }
@@ -0,0 +1,3 @@
1
+ import type { FastifyInstance } from "fastify";
2
+ import { type OutsideSites } from "./outside_fetch.ts";
3
+ export declare function register_outside_route(api: FastifyInstance, sites: OutsideSites, send?: typeof fetch): void;
@@ -0,0 +1,51 @@
1
+ // POST /api/outside: a browser's request to the outside sites its app names, sent on by the server and streamed back.
2
+ // ── Imports ──────────────────────────────────────────────────────────────────
3
+ import { PassThrough, Readable } from "node:stream";
4
+ import { bytes_of_base64, DROPPED_HEADERS, headers_header, is_outside_request, NULL_BODY_STATUSES, outside_route, status_header, status_text_header, with_site_headers } from "./outside_fetch.js";
5
+ import { is_allowed_url } from "../electron/fetch.js";
6
+ // ── Server ───────────────────────────────────────────────────────────────────
7
+ // POST <prefix>/outside: sends the posted request on to the site and streams its answer back, its status and headers in
8
+ // the x-outside- headers; refuses any URL outside the sites.
9
+ export function register_outside_route(api, sites, send = fetch) {
10
+ api.post(outside_route, async (request, reply) => {
11
+ const outside = request.body;
12
+ if (!is_outside_request(outside))
13
+ return reply.code(400).type("text/plain").send("A request needs a url, a method and a list of headers.");
14
+ if (!is_allowed_url(outside.url, { hosts: sites.hosts }))
15
+ return reply.code(403).type("text/plain").send(`Fetching ${outside.url} is not allowed.`);
16
+ const controller = new AbortController();
17
+ request.raw.on("close", () => controller.abort());
18
+ let response;
19
+ try {
20
+ response = await send(outside.url, {
21
+ method: outside.method,
22
+ headers: with_site_headers(outside.headers, sites),
23
+ ...(outside.body === undefined ? {} : { body: bytes_of_base64(outside.body) }),
24
+ signal: controller.signal,
25
+ });
26
+ }
27
+ catch (error) {
28
+ return reply.code(502).type("text/plain").send(`Could not reach ${new URL(outside.url).host}: ${error instanceof Error ? error.message : String(error)}`);
29
+ }
30
+ const headers = [];
31
+ response.headers.forEach((value, name) => {
32
+ if (!DROPPED_HEADERS.has(name))
33
+ headers.push([name, value]);
34
+ });
35
+ reply
36
+ .header(status_header, String(response.status))
37
+ .header(status_text_header, encodeURIComponent(response.statusText))
38
+ .header(headers_header, encodeURIComponent(JSON.stringify(headers)))
39
+ .header("cache-control", "no-store")
40
+ .type("application/octet-stream");
41
+ const has_body = response.body !== null && !NULL_BODY_STATUSES.has(response.status) && outside.method !== "HEAD";
42
+ if (!has_body)
43
+ return reply.send("");
44
+ // The browser leaving mid-answer, such as a player dropping a segment, ends the answer quietly rather than as an error.
45
+ const body = Readable.fromWeb(response.body);
46
+ const answer = new PassThrough();
47
+ body.on("error", (error) => (controller.signal.aborted ? answer.end() : answer.destroy(error)));
48
+ body.pipe(answer);
49
+ return reply.send(answer);
50
+ });
51
+ }
@@ -12,6 +12,8 @@ export function run_preload(app, { contextBridge, ipcRenderer }) {
12
12
  bridges.remote_access.expose(contextBridge, ipcRenderer, { envelopes: true });
13
13
  bridges.host.expose(contextBridge, ipcRenderer, { envelopes: true });
14
14
  bridges.fetch.expose(contextBridge, ipcRenderer, { envelopes: true });
15
+ if (app.outside)
16
+ bridges.outside.expose(contextBridge, ipcRenderer, { envelopes: true });
15
17
  for (const bridge of Object.values(bridges.host_tables))
16
18
  bridge.expose(contextBridge, ipcRenderer, { envelopes: true });
17
19
  bridges.events.expose(contextBridge, ipcRenderer);
@@ -92,6 +92,7 @@ export interface PageApi<Methods extends Record<keyof Methods, (...args: never[]
92
92
  reread_abilities?: () => Promise<Pick<PageApi, "admin" | "tables">>;
93
93
  server_theme?: ServerTheme;
94
94
  fetch?: typeof fetch;
95
+ outside_fetch?: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
95
96
  file_src?: (name: string) => Promise<string>;
96
97
  plugin_base?: string;
97
98
  read_plugin_file?: (path: string) => Promise<string>;
@@ -27,6 +27,7 @@ import { EventStream } from "../server/events.js";
27
27
  import { register_mcp_route } from "../server/mcp.js";
28
28
  import { register_plugin_files } from "../server/plugin_files.js";
29
29
  import { register_synced_files } from "../server/synced_file_route.js";
30
+ import { register_outside_route } from "./outside_route.js";
30
31
  import { folder_file_store } from "../node_file_store.js";
31
32
  import { load_accounts } from "../server/passwords.js";
32
33
  import { BAD_JSON, register_error_replies, register_lenient_json_body, send_text } from "../server/replies.js";
@@ -278,6 +279,8 @@ export async function build_server(app, options) {
278
279
  register_host_tables(api, app, reach, services, changes);
279
280
  if (options.files)
280
281
  register_synced_files(api, options.files);
282
+ if (app.outside)
283
+ register_outside_route(api, app.outside);
281
284
  // A route table's calls are documented as the routes they run, the rest as the calls posted under /api.
282
285
  api.get("/openapi.json", async () => {
283
286
  const called = Object.fromEntries(Object.entries(documented).filter(([method]) => !route_calls.has(method)));
@@ -15,8 +15,9 @@ import { Shell, use_route } from "../../web/react/shell.js";
15
15
  import { SignInForm, use_account } from "../../web/react/sign_in.js";
16
16
  import { SyncButton } from "../../web/react/sync_settings.js";
17
17
  import { apply_theme_colors, local_theme_storage, pinned_theme_choice, read_server_theme, theme_choice } from "../../web/theme.js";
18
+ import { phone_outside_fetch } from "../outside_fetch.js";
18
19
  import { desktop_api, is_android, is_desktop, web_api } from "./hosts.js";
19
- import { calls, data_watch, page, set_page_api, set_page_reach, use_settings } from "./page.js";
20
+ import { calls, data_watch, page, set_page_api, set_page_reach, use_data, use_settings } from "./page.js";
20
21
  import { SettingsView } from "./settings_page.js";
21
22
  // ── Pages ────────────────────────────────────────────────────────────────────
22
23
  // Relative, so a server behind a proxy under a folder keeps it.
@@ -87,10 +88,29 @@ function use_theme(app) {
87
88
  }, [stored, theme, pinned]);
88
89
  return theme;
89
90
  }
91
+ // The page an empty route opens: the one the app's setting names, once read, or its default; null while still reading.
92
+ function use_default_page(pages) {
93
+ const key = pages.default_page_setting;
94
+ const chosen = use_data(async (api) => (key ? (await api.get_settings())[key] : null), [key]);
95
+ const fallback = pages.default_page ?? pages.pages[0]?.id ?? "settings";
96
+ if (!key)
97
+ return fallback;
98
+ if (chosen.status === "loading" && chosen.data === null)
99
+ return null;
100
+ return pages.pages.some((each) => each.id === chosen.data) ? String(chosen.data) : fallback;
101
+ }
90
102
  function Pages({ pages, account }) {
103
+ const default_page = use_default_page(pages);
104
+ const route = use_route();
105
+ // An empty route waits for the page the setting names, rather than showing another first.
106
+ if (default_page === null && route.parts.length === 0)
107
+ return null;
108
+ return _jsx(RoutedPages, { pages: pages, account: account, default_page: default_page ?? pages.default_page ?? pages.pages[0]?.id ?? "settings" });
109
+ }
110
+ function RoutedPages({ pages, account, default_page }) {
91
111
  const { app } = pages;
92
112
  const route = use_route();
93
- const [section = pages.default_page ?? pages.pages[0]?.id ?? "settings", ...rest] = route.parts;
113
+ const [section = default_page, ...rest] = route.parts;
94
114
  const shown = pages.pages.find((candidate) => candidate.id === section);
95
115
  const is_account = account !== null && section === "account";
96
116
  // A page with pages of its own shows the one the route names, or its first; with only one it is the page itself.
@@ -182,15 +202,24 @@ async function host_api(app, pages) {
182
202
  return desktop_api(app);
183
203
  if (is_android() && app.phone === "portal") {
184
204
  const [{ portal_api }, { App: CapacitorApp }] = await Promise.all([import("./portal.js"), import("@capacitor/app")]);
185
- return portal_api(app, { lifecycle: CapacitorApp, ...(pages.phone_notifications ? { notifications: await pages.phone_notifications() } : {}) });
205
+ const api = await portal_api(app, { lifecycle: CapacitorApp, ...(pages.phone_notifications ? { notifications: await pages.phone_notifications() } : {}) });
206
+ return { ...api, ...(await phone_outside(app)) };
186
207
  }
187
208
  const phone_services = pages.phone_services;
188
209
  if (is_android()) {
189
210
  const { android_api } = await import("./android.js");
190
- return android_api(app, phone_services ? { services: await phone_services() } : {});
211
+ const api = await android_api(app, phone_services ? { services: await phone_services() } : {});
212
+ return { ...api, ...(await phone_outside(app)) };
191
213
  }
192
214
  return web_api(app);
193
215
  }
216
+ // A phone reaches the app's outside sites with Android's own HTTP, whether it keeps its own copy or works elsewhere.
217
+ async function phone_outside(app) {
218
+ if (!app.outside)
219
+ return {};
220
+ const { CapacitorHttp } = await import("@capacitor/core");
221
+ return { outside_fetch: phone_outside_fetch(CapacitorHttp, app.outside) };
222
+ }
194
223
  // Starts the page on whichever host it runs: the desktop app, the phone app or a browser.
195
224
  export async function render_app(pages, root = document.getElementById("app")) {
196
225
  const api = await host_api(pages.app, pages);
@@ -2,7 +2,7 @@ import type { App } from "../define.ts";
2
2
  import { type HostAbilities, type PageApi } from "../protocol.ts";
3
3
  export declare function read_host_abilities(read: () => Promise<unknown>): Promise<HostAbilities>;
4
4
  export declare function host_tables_of(app: Pick<App, "bridges">, abilities: HostAbilities, client_of: (name: string) => unknown): NonNullable<PageApi["tables"]>;
5
- export declare function web_api(app: Pick<App, "bridges"> & Partial<Pick<App, "sync" | "synced_files">>): PageApi;
5
+ export declare function web_api(app: Pick<App, "bridges"> & Partial<Pick<App, "sync" | "synced_files" | "outside">>): PageApi;
6
6
  export declare function is_desktop(app: Pick<App, "bridges">): boolean;
7
- export declare function desktop_api(app: Pick<App, "bridges"> & Partial<Pick<App, "id" | "local_mcp" | "remote_access" | "synced_files">>): Promise<PageApi>;
7
+ export declare function desktop_api(app: Pick<App, "bridges"> & Partial<Pick<App, "id" | "local_mcp" | "remote_access" | "synced_files" | "outside">>): Promise<PageApi>;
8
8
  export declare function is_android(): boolean;
@@ -1,7 +1,8 @@
1
1
  // Where the page runs and how it reaches the data there: a browser posts every call to the server it was loaded from
2
2
  // and follows its event stream; the desktop app's preload has put the main process's calls on the window, which go to
3
3
  // this computer's daemon or to the server Settings → Connections chose.
4
- import { create_page_fetch } from "../../electron/fetch.js";
4
+ import { create_page_fetch, create_page_stream_fetch } from "../../electron/fetch.js";
5
+ import { web_outside_fetch } from "../outside_fetch.js";
5
6
  import { LOCAL_CONNECTION_ID } from "../../connection_protocol.js";
6
7
  import { LoginNeeded } from "../../web/states.js";
7
8
  import { data_change_of, desktop_plugin_base, file_scheme_of } from "../protocol.js";
@@ -110,6 +111,7 @@ export function web_api(app) {
110
111
  plugin_base: "api/plugins/",
111
112
  // The server's own routes, with the browser's sign-in.
112
113
  fetch: (input, init) => fetch(input, init),
114
+ ...(app.outside ? { outside_fetch: web_outside_fetch() } : {}),
113
115
  on_change: (listener) => {
114
116
  listeners.add(listener);
115
117
  return () => listeners.delete(listener);
@@ -159,10 +161,19 @@ export async function desktop_api(app) {
159
161
  read_plugin_file: (path) => desktop.read_plugin_file(path),
160
162
  // The routes of the server the window works on, sent on by the main process with this device's token.
161
163
  ...(exposed[bridges.fetch.api_name] ? { fetch: create_page_fetch((request) => exposed[bridges.fetch.api_name].http_fetch(request)) } : {}),
164
+ ...(app.outside && exposed[bridges.outside.api_name] ? { outside_fetch: desktop_outside_fetch(exposed[bridges.outside.api_name], events) } : {}),
162
165
  on_change: (listener) => events.on("changed", listener),
163
166
  on_event: (event, listener) => events.on("app_event", (sent) => sent.event === event && listener(sent.data)),
164
167
  };
165
168
  }
169
+ // The outside sites through the main process, the answer's body streaming in as its chunks land.
170
+ function desktop_outside_fetch(outside, events) {
171
+ return create_page_stream_fetch({
172
+ start: (request) => outside.outside_stream(request),
173
+ cancel: (stream_id) => outside.outside_stream_cancel(stream_id),
174
+ on_chunk: (handler) => events.on("outside_chunk", handler),
175
+ });
176
+ }
166
177
  // ── Phone ────────────────────────────────────────────────────────────────────
167
178
  // Capacitor's native shell names its platform on the window.
168
179
  export function is_android() {
@@ -45,6 +45,7 @@ export interface AppPages {
45
45
  settings_categories?: (props: PageSettingsProps) => SettingsCategory[];
46
46
  brand_icon?: string;
47
47
  default_page?: string;
48
+ default_page_setting?: string;
48
49
  use_chrome?: (parts: readonly string[]) => AppChrome;
49
50
  phone_services?: () => Promise<StartPhoneServices>;
50
51
  phone_notifications?: () => Promise<LocalNotificationsLike>;
@@ -7,7 +7,7 @@ import { join } from "node:path";
7
7
  // ── Stand-ins ────────────────────────────────────────────────────────────────
8
8
  // What the base app takes from each package, none of which a page off the phone ever calls.
9
9
  const stand_ins = {
10
- "@capacitor/core": `export function registerPlugin() { throw new Error("Capacitor is not installed in this app."); }\nexport const Capacitor = { getPlatform: () => "web", isNativePlatform: () => false };\n`,
10
+ "@capacitor/core": `export function registerPlugin() { throw new Error("Capacitor is not installed in this app."); }\nexport const Capacitor = { getPlatform: () => "web", isNativePlatform: () => false };\nexport const CapacitorHttp = { request() { throw new Error("Capacitor is not installed in this app."); } };\n`,
11
11
  "@capacitor/app": `export const App = { addListener: () => { throw new Error("Capacitor is not installed in this app."); } };\n`,
12
12
  };
13
13
  const prefix = "\0x-app-capacitor:";
@@ -4,9 +4,10 @@ export interface DaemonLinkOptions {
4
4
  connections: Pick<Connections, "current" | "subscribe">;
5
5
  socket_path: string;
6
6
  fetch?: typeof fetch;
7
+ local_ready?: () => Promise<unknown>;
7
8
  }
8
9
  export type DaemonLink = ReturnType<typeof create_daemon_link>;
9
- export declare function create_daemon_link({ connections, socket_path, fetch: given_fetch }: DaemonLinkOptions): {
10
+ export declare function create_daemon_link({ connections, socket_path, fetch: given_fetch, local_ready }: DaemonLinkOptions): {
10
11
  call: (path: string, args?: unknown[], headers?: Record<string, string>) => Promise<unknown>;
11
12
  follow_events: (path: string, on_event: (event: string, data: string) => void, options?: FollowOptions) => () => void;
12
13
  };
@@ -4,15 +4,17 @@
4
4
  // the user picks another.
5
5
  import { call_daemon, daemon_answer, follow_daemon_events, parse_event } from "./local_daemon.js";
6
6
  const no_daemon_text = "No daemon is chosen yet. Choose one under Settings → Connections.";
7
- export function create_daemon_link({ connections, socket_path, fetch: given_fetch }) {
7
+ export function create_daemon_link({ connections, socket_path, fetch: given_fetch, local_ready }) {
8
8
  const do_fetch = given_fetch ?? fetch;
9
9
  // Posts one call with its arguments as a JSON array and answers with what it returned; a refusal throws the daemon's words.
10
10
  async function call(path, args = [], headers = {}) {
11
11
  const daemon = connections.current();
12
12
  if (daemon === null)
13
13
  throw new Error(no_daemon_text);
14
- if (daemon.kind === "local")
14
+ if (daemon.kind === "local") {
15
+ await local_ready?.();
15
16
  return call_daemon(socket_path, path, args, headers);
17
+ }
16
18
  let response;
17
19
  try {
18
20
  response = await do_fetch(`${daemon.address}${path}`, {
@@ -1,15 +1 @@
1
- declare const unit_names: readonly [readonly ["months", 2592000], readonly ["weeks", 604800], readonly ["days", 86400], readonly ["hours", 3600], readonly ["minutes", 60], readonly ["seconds", 1]];
2
- export type DurationUnit = (typeof unit_names)[number][0];
3
- export interface DurationWording {
4
- separator?: string;
5
- largest_unit?: DurationUnit;
6
- }
7
- export declare function parse_duration(value: unknown, key: string): number;
8
- export declare function format_duration(seconds: number, wording?: DurationWording): string;
9
- export declare function format_age(seconds: number): string;
10
- export interface ClockOptions {
11
- empty?: string;
12
- hours?: "auto" | "always";
13
- }
14
- export declare function format_clock(milliseconds: number | null | undefined, options?: string | ClockOptions): string;
15
- export {};
1
+ export * from "@x-tech-laboratories/x-app-agent/durations";
package/dist/durations.js CHANGED
@@ -1,52 +1,2 @@
1
- // Reads durations such as "2h30m" from settings and writes them back in words, for the server and the agent alike.
2
- import parse from "parse-duration";
3
- // A month counts as 30 days.
4
- const unit_names = [["months", 2592000], ["weeks", 604800], ["days", 86400], ["hours", 3600], ["minutes", 60], ["seconds", 1]];
5
- const words = new Intl.DurationFormat("en", { style: "long" });
6
- // A duration in whole seconds; `key` names the setting in the error.
7
- export function parse_duration(value, key) {
8
- if (typeof value === "number" && Number.isFinite(value) && value >= 0)
9
- return Math.floor(value);
10
- const text = String(value).trim();
11
- // A bare number is seconds, where parse-duration would read milliseconds.
12
- const seconds = /^\d+$/.test(text) ? Number(text) : parse(text, "s");
13
- if (seconds === null || seconds === undefined || !Number.isFinite(seconds) || seconds < 0) {
14
- throw new Error(`\`${key}\` must be a duration such as "1w", "7d", "2h30m" or "60s", not ${JSON.stringify(value)}`);
15
- }
16
- return Math.floor(seconds);
17
- }
18
- // The two largest whole units, such as "1 day, 2 hours" or, with a space between, "1 week 2 days"; "less than a second" below one.
19
- export function format_duration(seconds, wording = {}) {
20
- if (seconds <= 0)
21
- return "0 seconds";
22
- if (seconds < 1)
23
- return "less than a second";
24
- const first_unit = unit_names.findIndex(([name]) => name === (wording.largest_unit ?? "months"));
25
- const parts = {};
26
- let remaining = Math.floor(seconds);
27
- for (const [name, size] of unit_names.slice(first_unit)) {
28
- if (Object.keys(parts).length === 2)
29
- break;
30
- if (remaining < size)
31
- continue;
32
- parts[name] = Math.floor(remaining / size);
33
- remaining %= size;
34
- }
35
- if (wording.separator === undefined)
36
- return words.format(parts);
37
- return Object.entries(parts).map(([name, count]) => words.format({ [name]: count })).join(wording.separator);
38
- }
39
- export function format_age(seconds) {
40
- return seconds < 0 ? "never" : `${format_duration(seconds)} ago`;
41
- }
42
- // A playing time as a clock, such as "3:07", or "1:02:03" from an hour; a string option is the empty text alone.
43
- export function format_clock(milliseconds, options = {}) {
44
- const { empty = "0:00", hours: show_hours = "auto" } = typeof options === "string" ? { empty: options } : options;
45
- if (milliseconds === null || milliseconds === undefined || !Number.isFinite(milliseconds))
46
- return empty;
47
- const total = Math.max(0, Math.round(milliseconds / 1000));
48
- const hours = Math.floor(total / 3600);
49
- const minutes = Math.floor((total % 3600) / 60);
50
- const seconds = String(total % 60).padStart(2, "0");
51
- return hours > 0 || show_hours === "always" ? `${hours}:${String(minutes).padStart(2, "0")}:${seconds}` : `${minutes}:${seconds}`;
52
- }
1
+ // Moved to @x-tech-laboratories/x-app-agent, which a host agent installs without the rest of X-App.
2
+ export * from "@x-tech-laboratories/x-app-agent/durations";
@@ -17,6 +17,6 @@ export declare function plan_site(project: SiteProject, with_dates?: boolean): S
17
17
  export declare function page_data(project: SiteProject, plan: SitePlan, route: Route | null, locale?: string): PageData;
18
18
  export declare function write_entries(project: SiteProject, plan: SitePlan): void;
19
19
  export declare function redirect_html(target: string): string;
20
- export declare function build_site(root: string, log?: (line: string) => void): Promise<void>;
20
+ export declare function build_site(root: string, log?: (line: string) => void, warn?: (line: string) => void): Promise<void>;
21
21
  export declare function serve_site(root: string, port: number): Promise<void>;
22
22
  export declare function preview_site(root: string, port: number): Promise<void>;
@@ -16,6 +16,7 @@ import { pathToFileURL } from "node:url";
16
16
  import { build, createServer, preview } from "vite";
17
17
  import { text_direction } from "../i18n.js";
18
18
  import { read_content } from "./content.js";
19
+ import { site_links } from "./links.js";
19
20
  import { mdx_plugin } from "./markdown.js";
20
21
  import { build_sidebar, extract_headings, neighbours, page_path, plan_routes, root_locale, site_locales, with_base, } from "./model.js";
21
22
  import { messages_for } from "./ui_strings.js";
@@ -129,13 +130,13 @@ export function write_entries(project, plan) {
129
130
  writeFileSync(file, text);
130
131
  }
131
132
  }
132
- function vite_config(project) {
133
+ function vite_config(project, links) {
133
134
  return {
134
135
  root: project.root,
135
136
  base: project.base,
136
137
  configFile: false,
137
138
  publicDir: resolve(project.root, project.config.public ?? "public"),
138
- plugins: [mdx_plugin(project.base)],
139
+ plugins: [mdx_plugin(project.base, links)],
139
140
  oxc: { jsx: { runtime: "automatic", importSource: "react" } },
140
141
  resolve: { dedupe: ["react", "react-dom"] },
141
142
  logLevel: "warn",
@@ -232,12 +233,13 @@ function write_file(file, content) {
232
233
  writeFileSync(file, content);
233
234
  }
234
235
  // ── Build ────────────────────────────────────────────────────────────────────
235
- export async function build_site(root, log = console.info) {
236
+ export async function build_site(root, log = console.info, warn = console.warn) {
236
237
  const project = await load_project(root);
237
238
  const plan = plan_site(project, project.config.last_updated === true);
238
239
  write_entries(project, plan);
239
240
  rmSync(project.out_folder, { recursive: true, force: true });
240
- const config = vite_config(project);
241
+ const links = site_links(project.content_folder, plan.pages);
242
+ const config = vite_config(project, links);
241
243
  // Rolldown's note on how long each plugin took is left out, as MDX's compiler is always most of a site's build.
242
244
  const quiet = { checks: { pluginTimings: false } };
243
245
  await build({ ...config, build: { outDir: project.out_folder, emptyOutDir: true, manifest: true, rolldownOptions: { ...quiet, input: join(project.work_folder, "client.js") } } });
@@ -254,6 +256,8 @@ export async function build_site(root, log = console.info) {
254
256
  mkdirSync(dirname(join(project.out_folder, address)), { recursive: true });
255
257
  copyFileSync(file, join(project.out_folder, address));
256
258
  }
259
+ for (const file of links.files)
260
+ write_file(join(project.out_folder, file), readFileSync(join(project.content_folder, file)));
257
261
  const map = sitemap(project, plan.routes);
258
262
  if (map)
259
263
  write_file(join(project.out_folder, "sitemap.xml"), map);
@@ -277,6 +281,10 @@ export async function build_site(root, log = console.info) {
277
281
  await pagefind.close();
278
282
  log(`Indexed ${added.page_count} pages for search.`);
279
283
  }
284
+ // A link to a Markdown file that is not there is left as written and named here, not failing the build, as an
285
+ // archived page may keep links that were dead on GitHub too.
286
+ if (links.missing.size > 0)
287
+ warn([`Links to Markdown files that are not pages, left as written (${links.missing.size}):`, ...[...links.missing].sort()].join("\n"));
280
288
  }
281
289
  // ── Dev server ───────────────────────────────────────────────────────────────
282
290
  function send(response, status, type, body) {
@@ -284,11 +292,14 @@ function send(response, status, type, body) {
284
292
  response.setHeader("Content-Type", type);
285
293
  response.end(body);
286
294
  }
287
- const content_types = { ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".json": "application/json", ".gif": "image/gif" };
295
+ const content_types = { ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".json": "application/json", ".gif": "image/gif", ".pdf": "application/pdf" };
288
296
  export async function serve_site(root, port) {
289
297
  const project = await load_project(root);
290
- write_entries(project, plan_site(project));
291
- const server = await createServer({ ...vite_config(project), appType: "custom", server: { port }, logLevel: "info" });
298
+ const first_plan = plan_site(project);
299
+ write_entries(project, first_plan);
300
+ // Kept up to date with the pages on each request, as Vite compiles a page only when it is first asked for or changes.
301
+ const links = site_links(project.content_folder, first_plan.pages);
302
+ const server = await createServer({ ...vite_config(project, links), appType: "custom", server: { port }, logLevel: "info" });
292
303
  const client_tag = `<script type="module" src="${with_base(project.base, `/${relative(project.root, join(project.work_folder, "client.js")).split(sep).join("/")}`)}"></script>`;
293
304
  server.middlewares.use((request, response, next) => {
294
305
  void (async () => {
@@ -298,6 +309,9 @@ export async function serve_site(root, port) {
298
309
  const path = `/${address.slice(project.base.length)}`;
299
310
  const plan = plan_site(project);
300
311
  write_entries(project, plan);
312
+ const placed = site_links(project.content_folder, plan.pages);
313
+ links.pages = placed.pages;
314
+ links.folders = placed.folders;
301
315
  const route = plan.routes.find((candidate) => candidate.path === path);
302
316
  const moved_to = project.config.redirects?.[path];
303
317
  if (!route && moved_to !== undefined) {
@@ -314,6 +328,8 @@ export async function serve_site(root, port) {
314
328
  const asset = plan.assets.get(path.slice(1));
315
329
  if (asset)
316
330
  return send(response, 200, content_types[extname(asset)] ?? "application/octet-stream", readFileSync(asset));
331
+ if (links.files.has(path.slice(1)))
332
+ return send(response, 200, content_types[extname(path).toLowerCase()] ?? "application/octet-stream", readFileSync(join(project.content_folder, path.slice(1))));
317
333
  const extra = ((await project.config.files?.()) ?? []).find((file) => `/${file.path}` === path);
318
334
  if (extra)
319
335
  return send(response, 200, content_types[extname(extra.path)] ?? "text/plain", extra.content);
@@ -323,6 +339,10 @@ export async function serve_site(root, port) {
323
339
  const entry = (await server.ssrLoadModule(join(project.work_folder, "server.js")));
324
340
  const locale = route?.locale ?? Object.keys(site_locales(project.config)).find((key) => key !== root_locale && path.startsWith(`/${key}/`));
325
341
  const html = await render_html(project, plan, entry, route ?? null, [client_tag], locale);
342
+ // Each link to a Markdown file that is not there, as the build names them at its end.
343
+ for (const line of links.missing)
344
+ server.config.logger.warn(line);
345
+ links.missing.clear();
326
346
  send(response, route ? 200 : 404, "text/html", await server.transformIndexHtml(address, html));
327
347
  })().catch((error) => {
328
348
  if (error instanceof Error)
@@ -335,6 +355,6 @@ export async function serve_site(root, port) {
335
355
  }
336
356
  export async function preview_site(root, port) {
337
357
  const project = await load_project(root);
338
- const server = await preview({ ...vite_config(project), build: { outDir: project.out_folder }, preview: { port }, logLevel: "info" });
358
+ const server = await preview({ ...vite_config(project, site_links(project.content_folder, [])), build: { outDir: project.out_folder }, preview: { port }, logLevel: "info" });
339
359
  server.printUrls();
340
360
  }
@@ -3,7 +3,8 @@ import { execFileSync } from "node:child_process";
3
3
  import { readdirSync, readFileSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { parse as parse_yaml } from "yaml";
6
- import { place_of_file } from "./model.js";
6
+ import { is_skipped } from "./links.js";
7
+ import { index_files, place_of_file } from "./model.js";
7
8
  // The YAML between the opening and closing --- lines, or nothing when the file has none.
8
9
  export function read_frontmatter(text) {
9
10
  const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
@@ -12,11 +13,6 @@ export function read_frontmatter(text) {
12
13
  const parsed = parse_yaml(match[1]);
13
14
  return parsed !== null && typeof parsed === "object" ? parsed : {};
14
15
  }
15
- // Folders that never hold pages, so a site can keep its package, build and public files beside its pages.
16
- const skipped_folders = new Set(["node_modules", "dist", "public"]);
17
- function is_skipped(name) {
18
- return skipped_folders.has(name) || name.startsWith(".") || name.startsWith("_");
19
- }
20
16
  // The text of the page's opening "# heading", after any frontmatter and imports, with its inline code marks dropped.
21
17
  export function title_heading(text) {
22
18
  const body = text.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, "");
@@ -61,12 +57,14 @@ function last_commit_dates(folder) {
61
57
  }
62
58
  export function read_content(folder, locale_keys, with_dates = false) {
63
59
  const dates = with_dates ? last_commit_dates(folder) : new Map();
64
- return list_content_files(folder).map((id) => {
60
+ const ids = list_content_files(folder);
61
+ const indexes = index_files(ids);
62
+ return ids.map((id) => {
65
63
  const text = readFileSync(join(folder, id), "utf8");
66
64
  const frontmatter = read_frontmatter(text);
67
65
  frontmatter.title ??= title_heading(text);
68
66
  if (typeof frontmatter.title !== "string")
69
67
  throw new Error(`${id} has no title in its frontmatter or a # heading.`);
70
- return { id, ...place_of_file(id, locale_keys), frontmatter, last_updated: dates.get(id) };
68
+ return { id, ...place_of_file(id, locale_keys, indexes.has(id)), frontmatter, last_updated: dates.get(id) };
71
69
  });
72
70
  }
@@ -0,0 +1,11 @@
1
+ import { type SourcePage } from "./model.ts";
2
+ export interface SiteLinks {
3
+ content_folder: string;
4
+ pages: Map<string, string>;
5
+ folders: Map<string, string>;
6
+ files: Set<string>;
7
+ missing: Set<string>;
8
+ }
9
+ export declare function site_links(content_folder: string, pages: readonly SourcePage[]): SiteLinks;
10
+ export declare function is_skipped(name: string): boolean;
11
+ export declare function site_link(links: SiteLinks, source_file: string, href: string): string;