@x-tech-laboratories/x-app 0.127.0 → 0.129.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 CHANGED
@@ -283,6 +283,13 @@ An app whose work needs a computer, such as one that runs programs on checkouts,
283
283
  - **Sign-in from the config**: `admin_name` names the admin a bare hash in the accounts file signs in as, and
284
284
  `proxy_user_header` (with `trusted_proxies`, 127.0.0.1 and ::1 unless set) signs in whoever a reverse proxy on those
285
285
  addresses names; `define_app`'s `check_access` checks a user's access when an admin sets it, such as a list of grants.
286
+ - **Outside sites**: `outside: { hosts, headers }` names the sites the page reaches with `page().outside_fetch`, such
287
+ as a video site's API, which a browser's cross-origin rules would block: the desktop sends each request from its main
288
+ process with the answer streamed back, the server for a signed-in browser at `POST /api/outside`, and a phone with
289
+ Android's own HTTP (`app/outside_fetch`). Each host refuses any other host and sets `headers` last, such as an
290
+ `Origin` the site insists on, which a page cannot set itself.
291
+ - **A start page the user picks**: `render_app`'s `default_page_setting` names the setting holding the page an empty
292
+ route opens, such as `"stream.startup_page"`; `default_page` while it names none of the pages.
286
293
  - **Keys in a settings export**: `render_app`'s `exports_secrets: true` offers "Include keys and tokens" on exporting
287
294
  the settings, for an app whose settings hold other services' keys.
288
295
  - **Links to other apps**: `run_desktop`'s `external_schemes`, such as `["stremio:", "steam:"]`, opens those links in
@@ -800,7 +807,8 @@ it, MDX's own compiler reads the pages (with GitHub's tables and task lists), Sh
800
807
  Pagefind indexes the built pages for search. Each page is drawn to HTML at build time and picked up again in the browser,
801
808
  so it reads without JavaScript and its search, outline, menus and theme work with it.
802
809
 
803
- - **Pages**: `content/**/*.md(x)` with a `title` in the frontmatter, `index` files at their folder; `template: splash` makes a
810
+ - **Pages**: `content/**/*.md(x)` with a `title` in the frontmatter, `index` files at their folder, and a `README` at its
811
+ folder when the folder has no `index` (with both, the `README` is a page of its own); `template: splash` makes a
804
812
  landing page with a `hero` (title, tagline, image, actions); `sidebar.order`, `sidebar.label` and `sidebar.hidden` place a
805
813
  page; `toc: false` hides its outline. MDX imports `Card`, `CardGrid`, `LinkCard` and `Aside` from `web/react/site`, and the
806
814
  site's own React components.
@@ -820,9 +828,15 @@ so it reads without JavaScript and its search, outline, menus and theme work wit
820
828
  - **GitHub's own Markdown**: alerts such as `> [!TIP]` show as asides and raw HTML such as a table of pictures is
821
829
  kept, so a page reads the same on GitHub and on the site; a page with no `title` takes its opening `# heading`, which
822
830
  is then not drawn twice, so an MDX page can show a README with `import Readme from "../README.md"`; links that start at the root move under the base in Markdown and in a component's `href` or `src`.
823
- - **Diagrams**: a ```` ```mermaid ```` block, which GitHub draws too, is drawn with [Mermaid](https://mermaid.js.org/) in
824
- Halon's colours and drawn again when the scheme changes; the page shows its source until then, and without
825
- JavaScript. The browser loads mermaid only on a site with a diagram, which adds `mermaid` to its own dependencies.
831
+ - **Relative links and pictures, as on GitHub**: a link written relative to its page, such as `[Merge](../decisions/merge.md#why)`
832
+ or `[Decisions](../decisions/)`, goes to that page, or the folder's `index` or `README` page, keeping its anchor; a
833
+ picture or other file inside the content folder, such as `![Map](../diagrams/map.png)` or a linked `.drawio` or
834
+ `.pdf`, is served at its own path in `dev` and copied into `dist/` by `build`, and only files a page uses are copied. A
835
+ link to anything else, such as a source file outside the content folder, is left as written, and a link to a Markdown
836
+ file that is not there is too, named in a list at the end of the build rather than failing it, so archived pages
837
+ with links that were already dead on GitHub still build.
838
+ - **Diagrams**: images like any other. Draw them in [draw.io](https://www.drawio.com/), keep the `.drawio` source beside
839
+ its PNG export, in `public/` or beside the pages, and show the PNG; a ```` ```mermaid ```` block is only code.
826
840
  - **Pages beside a package**: the scan skips `node_modules`, `dist`, `public` and hidden folders, so a site can live in
827
841
  an app's `docs/` folder with a `package.json` of its own.
828
842
 
@@ -5,7 +5,7 @@ import { type Caller } from "../caller.ts";
5
5
  import { type CertificateMethods } from "../certificate_protocol.ts";
6
6
  import { type ConnectionMethods } from "../connection_protocol.ts";
7
7
  import { type Bridge } from "../electron/bridge.ts";
8
- import type { FetchMethod } from "../electron/fetch.ts";
8
+ import type { FetchMethod, StreamCancelMethod, StreamChunk, StreamStartMethod } from "../electron/fetch.ts";
9
9
  import { type EventsBridge } from "../electron/events.ts";
10
10
  import type { History } from "../history.ts";
11
11
  import type { ScopeSpec } from "../server/declared_tokens.ts";
@@ -16,6 +16,7 @@ import { type SyncedTable } from "../sync_engine.ts";
16
16
  import { type PeerListeningMethods, type SyncDeviceMethods, type SyncStatus } from "../sync_protocol.ts";
17
17
  import { type RemoteAccessMethods } from "../remote_access_protocol.ts";
18
18
  import type { SecurityHeadersOptions } from "../server/security_headers.ts";
19
+ import type { OutsideSites } from "./outside_fetch.ts";
19
20
  import { type DataChange, type DesktopMethods, type DesktopSettingSpec, type HostAbilityMethods } from "./protocol.ts";
20
21
  export type StoreMethod = (database: SqlDatabase, ...args: never[]) => unknown;
21
22
  export type KeptHistory = Pick<History<unknown>, "synced_table" | "install" | "forget_touched" | "record" | "prune"> & Partial<Pick<History<unknown>, "drop_triggers">>;
@@ -106,6 +107,7 @@ export interface AppOptions<Features extends readonly Feature[]> {
106
107
  limit_key?: string;
107
108
  };
108
109
  security_headers?: boolean | SecurityHeadersOptions;
110
+ outside?: OutsideSites;
109
111
  }
110
112
  export declare const base_setting_defaults: {
111
113
  history_days: number;
@@ -123,7 +125,12 @@ export type AppEvents = {
123
125
  event: string;
124
126
  data: unknown;
125
127
  };
128
+ outside_chunk: StreamChunk;
126
129
  };
130
+ export interface OutsideMethods {
131
+ outside_stream: StreamStartMethod;
132
+ outside_stream_cancel: StreamCancelMethod;
133
+ }
127
134
  export interface AppBridges<Methods extends Record<keyof Methods, (...args: never[]) => unknown>> {
128
135
  calls: Bridge<Methods>;
129
136
  device: Bridge<SyncDeviceMethods>;
@@ -139,6 +146,7 @@ export interface AppBridges<Methods extends Record<keyof Methods, (...args: neve
139
146
  fetch: Bridge<{
140
147
  http_fetch: FetchMethod;
141
148
  }>;
149
+ outside: Bridge<OutsideMethods>;
142
150
  host_tables: Readonly<Record<string, Bridge<Record<string, (...args: never[]) => unknown>>>>;
143
151
  }
144
152
  export declare function define_app<const Features extends readonly Feature[]>(options: AppOptions<Features>): {
@@ -191,6 +199,7 @@ export declare function define_app<const Features extends readonly Feature[]>(op
191
199
  limit_key?: string;
192
200
  };
193
201
  security_headers?: boolean | SecurityHeadersOptions;
202
+ outside?: OutsideSites;
194
203
  features: readonly Feature<Record<string, StoreMethod>>[];
195
204
  settings_store: SettingsStore;
196
205
  setting_defaults: Readonly<import("../settings.ts").Settings>;
@@ -267,6 +267,7 @@ export function define_app(options) {
267
267
  events: define_events(`${prefix}_events`),
268
268
  host: define_bridge(`${prefix}_host`, host_ability_method_names),
269
269
  fetch: define_bridge(`${prefix}_fetch`, ["http_fetch"]),
270
+ outside: define_bridge(`${prefix}_outside`, ["outside_stream", "outside_stream_cancel"]),
270
271
  // Letting other devices reach this computer's daemon, answered over its socket alone.
271
272
  remote_access: define_bridge(`${prefix}_remote`, remote_access_method_names),
272
273
  host_tables: Object.fromEntries(Object.entries(options.host_tables ?? {}).map(([name, table]) => [name, define_bridge(`${prefix}_${name}`, Object.keys(table.api))])),
@@ -24,7 +24,8 @@ import { peer_listening_method_names, sync_device_method_names } from "../sync_p
24
24
  import { route_of_link } from "./links.js";
25
25
  import { remote_access_method_names } from "../remote_access_protocol.js";
26
26
  import { file_response, register_file_scheme } from "../electron/file_protocol.js";
27
- import { create_main_fetch } from "../electron/fetch.js";
27
+ import { create_main_fetch, create_main_stream_fetch } from "../electron/fetch.js";
28
+ import { with_site_headers } from "./outside_fetch.js";
28
29
  import { no_server_text, server_headers, server_url } from "./server_fetch.js";
29
30
  import { folder_file_store } from "../node_file_store.js";
30
31
  import { read_plugin_file } from "../plugin_folder.js";
@@ -310,6 +311,12 @@ export function run_desktop(app, electron, options) {
310
311
  bridges.remote_access.handle(ipcMain, forwarded(remote_access_method_names, "remote"), handle_options);
311
312
  bridges.host.handle(ipcMain, forwarded(host_ability_method_names, "host"), handle_options);
312
313
  bridges.fetch.handle(ipcMain, { http_fetch }, handle_options);
314
+ // The app's outside sites, sent from here whichever host the window works on, each answer streamed to the windows.
315
+ const outside = app.outside;
316
+ if (outside) {
317
+ const stream = create_main_stream_fetch({ hosts: outside.hosts }, (chunk) => app.bridges.events.emit(windows(), "outside_chunk", chunk));
318
+ bridges.outside.handle(ipcMain, { outside_stream: (request) => stream.start({ ...request, headers: with_site_headers(request.headers, outside) }), outside_stream_cancel: stream.cancel }, handle_options);
319
+ }
313
320
  for (const [name, bridge] of Object.entries(bridges.host_tables))
314
321
  bridge.handle(ipcMain, forwarded(Object.keys(app.host_tables[name].api), name), handle_options);
315
322
  const desktop = {
@@ -0,0 +1,40 @@
1
+ import { type HeaderList } from "../electron/fetch.ts";
2
+ export interface OutsideSites {
3
+ hosts: readonly string[];
4
+ headers?: Readonly<Record<string, string>>;
5
+ }
6
+ export declare function with_site_headers(headers: HeaderList, sites: OutsideSites): HeaderList;
7
+ export interface OutsideRequest {
8
+ url: string;
9
+ method: string;
10
+ headers: HeaderList;
11
+ body?: string;
12
+ }
13
+ export declare const outside_route = "/outside";
14
+ export declare const outside_path = "api/outside";
15
+ export declare const status_header = "x-outside-status";
16
+ export declare const status_text_header = "x-outside-status-text";
17
+ export declare const headers_header = "x-outside-headers";
18
+ export declare const NULL_BODY_STATUSES: Set<number>;
19
+ export declare const DROPPED_HEADERS: Set<string>;
20
+ export declare function is_outside_request(value: unknown): value is OutsideRequest;
21
+ export declare function bytes_of_base64(text: string): Uint8Array<ArrayBuffer>;
22
+ export declare function base64_of_bytes(bytes: Uint8Array): string;
23
+ type Fetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
24
+ export declare function web_outside_fetch(post?: typeof fetch): Fetch;
25
+ export interface NativeHttp {
26
+ request(options: {
27
+ url: string;
28
+ method: string;
29
+ headers: Record<string, string>;
30
+ data?: string;
31
+ dataType?: "file";
32
+ responseType: "arraybuffer";
33
+ }): Promise<{
34
+ status: number;
35
+ headers: Record<string, string>;
36
+ data: unknown;
37
+ }>;
38
+ }
39
+ export declare function phone_outside_fetch(http: NativeHttp, sites: OutsideSites): Fetch;
40
+ export {};
@@ -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:";
@@ -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,7 +16,8 @@ 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 { has_mermaid, mdx_plugin } from "./markdown.js";
19
+ import { site_links } from "./links.js";
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";
22
23
  // ── The project ──────────────────────────────────────────────────────────────
@@ -106,8 +107,8 @@ export function page_data(project, plan, route, locale = route?.locale ?? root_l
106
107
  };
107
108
  }
108
109
  // ── Vite ─────────────────────────────────────────────────────────────────────
109
- // The entries Vite starts from: the page modules by content file, the browser's entry with the site's stylesheets (and
110
- // mermaid, when a page draws a diagram), and the server's; written only when they change, so the dev server does not
110
+ // The entries Vite starts from: the page modules by content file, the browser's entry with the site's stylesheets, and the
111
+ // server's; written only when they change, so the dev server does not
111
112
  // reload for nothing.
112
113
  export function write_entries(project, plan) {
113
114
  mkdirSync(project.work_folder, { recursive: true });
@@ -117,13 +118,9 @@ export function write_entries(project, plan) {
117
118
  };
118
119
  const page_lines = plan.pages.map((page) => ` ${JSON.stringify(page.id)}: () => import(${JSON.stringify(from_work(join(project.content_folder, page.id)))}),`);
119
120
  const css_lines = (project.config.css ?? []).map((sheet) => `import ${JSON.stringify(sheet.startsWith(".") ? from_work(resolve(project.root, sheet)) : sheet)};`);
120
- const draws_diagrams = plan.pages.some((page) => has_mermaid(readFileSync(join(project.content_folder, page.id), "utf8")));
121
- const start = draws_diagrams
122
- ? `import { mermaid_drawer } from "@x-tech-laboratories/x-app/web/site/mermaid";\nimport { pages } from "./pages.js";\n\nstart_site(pages, { draw_diagram: mermaid_drawer(() => import("mermaid")) });\n`
123
- : `import { pages } from "./pages.js";\n\nstart_site(pages);\n`;
124
121
  const files = {
125
122
  "pages.js": `export const pages = {\n${page_lines.join("\n")}\n};\n`,
126
- "client.js": `${css_lines.join("\n")}\nimport { start_site } from "@x-tech-laboratories/x-app/web/site/client";\n${start}`,
123
+ "client.js": `${css_lines.join("\n")}\nimport { start_site } from "@x-tech-laboratories/x-app/web/site/client";\nimport { pages } from "./pages.js";\n\nstart_site(pages);\n`,
127
124
  "server.js": `export { load_content, render_content, render_page } from "@x-tech-laboratories/x-app/web/site/server";\nexport { pages } from "./pages.js";\n`,
128
125
  ".gitignore": "*\n",
129
126
  };
@@ -133,13 +130,13 @@ export function write_entries(project, plan) {
133
130
  writeFileSync(file, text);
134
131
  }
135
132
  }
136
- function vite_config(project) {
133
+ function vite_config(project, links) {
137
134
  return {
138
135
  root: project.root,
139
136
  base: project.base,
140
137
  configFile: false,
141
138
  publicDir: resolve(project.root, project.config.public ?? "public"),
142
- plugins: [mdx_plugin(project.base)],
139
+ plugins: [mdx_plugin(project.base, links)],
143
140
  oxc: { jsx: { runtime: "automatic", importSource: "react" } },
144
141
  resolve: { dedupe: ["react", "react-dom"] },
145
142
  logLevel: "warn",
@@ -236,12 +233,13 @@ function write_file(file, content) {
236
233
  writeFileSync(file, content);
237
234
  }
238
235
  // ── Build ────────────────────────────────────────────────────────────────────
239
- export async function build_site(root, log = console.info) {
236
+ export async function build_site(root, log = console.info, warn = console.warn) {
240
237
  const project = await load_project(root);
241
238
  const plan = plan_site(project, project.config.last_updated === true);
242
239
  write_entries(project, plan);
243
240
  rmSync(project.out_folder, { recursive: true, force: true });
244
- const config = vite_config(project);
241
+ const links = site_links(project.content_folder, plan.pages);
242
+ const config = vite_config(project, links);
245
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.
246
244
  const quiet = { checks: { pluginTimings: false } };
247
245
  await build({ ...config, build: { outDir: project.out_folder, emptyOutDir: true, manifest: true, rolldownOptions: { ...quiet, input: join(project.work_folder, "client.js") } } });
@@ -258,6 +256,8 @@ export async function build_site(root, log = console.info) {
258
256
  mkdirSync(dirname(join(project.out_folder, address)), { recursive: true });
259
257
  copyFileSync(file, join(project.out_folder, address));
260
258
  }
259
+ for (const file of links.files)
260
+ write_file(join(project.out_folder, file), readFileSync(join(project.content_folder, file)));
261
261
  const map = sitemap(project, plan.routes);
262
262
  if (map)
263
263
  write_file(join(project.out_folder, "sitemap.xml"), map);
@@ -281,6 +281,10 @@ export async function build_site(root, log = console.info) {
281
281
  await pagefind.close();
282
282
  log(`Indexed ${added.page_count} pages for search.`);
283
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"));
284
288
  }
285
289
  // ── Dev server ───────────────────────────────────────────────────────────────
286
290
  function send(response, status, type, body) {
@@ -288,11 +292,14 @@ function send(response, status, type, body) {
288
292
  response.setHeader("Content-Type", type);
289
293
  response.end(body);
290
294
  }
291
- 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" };
292
296
  export async function serve_site(root, port) {
293
297
  const project = await load_project(root);
294
- write_entries(project, plan_site(project));
295
- 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" });
296
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>`;
297
304
  server.middlewares.use((request, response, next) => {
298
305
  void (async () => {
@@ -302,6 +309,9 @@ export async function serve_site(root, port) {
302
309
  const path = `/${address.slice(project.base.length)}`;
303
310
  const plan = plan_site(project);
304
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;
305
315
  const route = plan.routes.find((candidate) => candidate.path === path);
306
316
  const moved_to = project.config.redirects?.[path];
307
317
  if (!route && moved_to !== undefined) {
@@ -318,6 +328,8 @@ export async function serve_site(root, port) {
318
328
  const asset = plan.assets.get(path.slice(1));
319
329
  if (asset)
320
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))));
321
333
  const extra = ((await project.config.files?.()) ?? []).find((file) => `/${file.path}` === path);
322
334
  if (extra)
323
335
  return send(response, 200, content_types[extname(extra.path)] ?? "text/plain", extra.content);
@@ -327,6 +339,10 @@ export async function serve_site(root, port) {
327
339
  const entry = (await server.ssrLoadModule(join(project.work_folder, "server.js")));
328
340
  const locale = route?.locale ?? Object.keys(site_locales(project.config)).find((key) => key !== root_locale && path.startsWith(`/${key}/`));
329
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();
330
346
  send(response, route ? 200 : 404, "text/html", await server.transformIndexHtml(address, html));
331
347
  })().catch((error) => {
332
348
  if (error instanceof Error)
@@ -339,6 +355,6 @@ export async function serve_site(root, port) {
339
355
  }
340
356
  export async function preview_site(root, port) {
341
357
  const project = await load_project(root);
342
- 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" });
343
359
  server.printUrls();
344
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;
@@ -0,0 +1,55 @@
1
+ // Links a page writes relative to its own file, as on GitHub: a link to a Markdown file or to a folder becomes that
2
+ // page's address, and a picture or other file inside the content folder is served at its own path.
3
+ import { existsSync, statSync } from "node:fs";
4
+ import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
5
+ import { index_files, page_path } from "./model.js";
6
+ export function site_links(content_folder, pages) {
7
+ const indexes = index_files(pages.map((page) => page.id));
8
+ const links = { content_folder, pages: new Map(), folders: new Map(), files: new Set(), missing: new Set() };
9
+ for (const page of pages) {
10
+ const path = page_path(page.locale, page.slug);
11
+ links.pages.set(page.id, path);
12
+ if (indexes.has(page.id))
13
+ links.folders.set(page.id.slice(0, Math.max(page.id.lastIndexOf("/"), 0)), path);
14
+ }
15
+ return links;
16
+ }
17
+ // Folders that never hold pages or the files they show.
18
+ const skipped_folders = new Set(["node_modules", "dist", "public"]);
19
+ // A name the content scan skips: a package, build or public folder, or one that is hidden or starts with an underscore.
20
+ export function is_skipped(name) {
21
+ return skipped_folders.has(name) || name.startsWith(".") || name.startsWith("_");
22
+ }
23
+ // An address with a scheme, one from the site's root, or an anchor on the same page.
24
+ const not_relative = /^([a-z][a-z0-9+.-]*:|\/|#|\?)/i;
25
+ // Where a relative link from a file goes on the site, without the base: a page's address with the link's query and
26
+ // anchor kept, or a file's own path; anything else, such as a file outside the content folder, is left as written,
27
+ // and a link to a Markdown file that is not there is noted in `missing`.
28
+ export function site_link(links, source_file, href) {
29
+ if (href === "" || not_relative.test(href))
30
+ return href;
31
+ const [, path, rest] = /^([^?#]*)(.*)$/s.exec(href);
32
+ let decoded;
33
+ try {
34
+ decoded = decodeURIComponent(path);
35
+ }
36
+ catch {
37
+ return href;
38
+ }
39
+ const target = resolve(dirname(source_file), decoded);
40
+ const id = relative(links.content_folder, target).split(sep).join("/");
41
+ if (id === ".." || id.startsWith("../") || isAbsolute(id))
42
+ return href;
43
+ const page = links.pages.get(id) ?? links.folders.get(id);
44
+ if (page !== undefined)
45
+ return `${page}${rest}`;
46
+ if (/\.mdx?$/i.test(id)) {
47
+ if (!existsSync(target))
48
+ links.missing.add(`${relative(links.content_folder, source_file).split(sep).join("/")} links to ${href}, which is not a page of the site.`);
49
+ return href;
50
+ }
51
+ if (id === "" || id.split("/").some(is_skipped) || !existsSync(target) || !statSync(target).isFile())
52
+ return href;
53
+ links.files.add(id);
54
+ return `/${encodeURI(id)}${rest}`;
55
+ }
@@ -1,9 +1,10 @@
1
1
  import type { Root } from "hast";
2
2
  import type { Root as MarkdownRoot } from "mdast";
3
3
  import type { Plugin } from "vite";
4
- export declare function rehype_base_links(base: string): (tree: Root) => void;
4
+ import { type SiteLinks } from "./links.ts";
5
+ export declare function rehype_base_links(base: string, links?: SiteLinks): (tree: Root, file: {
6
+ path?: string;
7
+ }) => void;
5
8
  export declare function remark_github_alerts(): (tree: MarkdownRoot) => void;
6
9
  export declare function remark_drop_title_heading(): (tree: MarkdownRoot) => void;
7
- export declare function rehype_mermaid_blocks(): (tree: Root) => void;
8
- export declare function has_mermaid(text: string): boolean;
9
- export declare function mdx_plugin(base: string): Plugin;
10
+ export declare function mdx_plugin(base: string, links?: SiteLinks): Plugin;
@@ -1,6 +1,7 @@
1
1
  // How a site's Markdown and MDX become pages, on MDX's own compiler: GitHub's tables, task lists, autolinks, alerts
2
2
  // and raw HTML, frontmatter and a leading title heading kept out of the page, an id and an anchor link on every heading, code coloured by Shiki through Halon's
3
- // tokens, mermaid blocks kept for the page to draw, and links within the site moved under its base.
3
+ // tokens, relative links and pictures moved to where they are on the site, and links within the site moved under its base.
4
+ import { resolve } from "node:path";
4
5
  import mdx from "@mdx-js/rollup";
5
6
  import rehype_shiki from "@shikijs/rehype";
6
7
  import rehype_autolink_headings from "rehype-autolink-headings";
@@ -10,28 +11,30 @@ import remark_frontmatter from "remark-frontmatter";
10
11
  import remark_gfm from "remark-gfm";
11
12
  import { createCssVariablesTheme } from "shiki";
12
13
  import { visit } from "unist-util-visit";
14
+ import { site_link } from "./links.js";
13
15
  import { with_base } from "./model.js";
14
16
  // Colours each kind of code token with a --shiki-* variable that Halon's site sheet sets for the light and dark schemes.
15
17
  const halon_code_theme = createCssVariablesTheme({ name: "halon", variablePrefix: "--shiki-", fontStyle: true });
16
- // Puts the base in front of every link and picture that starts at the site's root, written in Markdown or as a
17
- // component's href or src.
18
- export function rehype_base_links(base) {
19
- return (tree) => {
20
- if (base === "/")
21
- return;
18
+ // Moves each link and picture a page writes relative to its own file to where it is on the site, when `links` knows the
19
+ // site's pages, and puts the base in front of every link and picture that starts at the site's root, written in
20
+ // Markdown or as a component's href or src.
21
+ export function rehype_base_links(base, links) {
22
+ return (tree, file) => {
23
+ const source = links && file.path ? resolve(file.path) : undefined;
24
+ const rewrite = (value) => with_base(base, links && source ? site_link(links, source, value) : value);
22
25
  visit(tree, (node) => {
23
26
  if (node.type === "element") {
24
27
  const element = node;
25
28
  for (const attribute of ["href", "src"]) {
26
29
  const value = element.properties[attribute];
27
30
  if (typeof value === "string")
28
- element.properties[attribute] = with_base(base, value);
31
+ element.properties[attribute] = rewrite(value);
29
32
  }
30
33
  }
31
34
  else if (node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement") {
32
35
  for (const attribute of node.attributes) {
33
36
  if (attribute.type === "mdxJsxAttribute" && (attribute.name === "href" || attribute.name === "src") && typeof attribute.value === "string") {
34
- attribute.value = with_base(base, attribute.value);
37
+ attribute.value = rewrite(attribute.value);
35
38
  }
36
39
  }
37
40
  }
@@ -76,27 +79,9 @@ export function remark_drop_title_heading() {
76
79
  tree.children.splice(index, 1);
77
80
  };
78
81
  }
79
- // A ```mermaid block kept as its source in a marked <pre>, which the page draws as a diagram and Shiki leaves alone.
80
- export function rehype_mermaid_blocks() {
81
- return (tree) => {
82
- visit(tree, "element", (node) => {
83
- const code = node.tagName === "pre" ? node.children.find((child) => child.type === "element" && child.tagName === "code") : undefined;
84
- const classes = code?.properties.className;
85
- if (!code || !Array.isArray(classes) || !classes.includes("language-mermaid"))
86
- return;
87
- const source = code.children.map((child) => (child.type === "text" ? child.value : "")).join("");
88
- node.properties = { dataMermaid: "" };
89
- node.children = [{ type: "text", value: source }];
90
- });
91
- };
92
- }
93
- // Whether a page's Markdown holds a ```mermaid block, so the site's browser entry loads mermaid.
94
- export function has_mermaid(text) {
95
- return /^[ \t]*(```|~~~)[ \t]*mermaid\b/m.test(text);
96
- }
97
82
  // MDX's own nodes, which raw HTML parsing must pass through untouched.
98
83
  const mdx_node_types = ["mdxFlowExpression", "mdxJsxFlowElement", "mdxJsxTextElement", "mdxTextExpression", "mdxjsEsm"];
99
- export function mdx_plugin(base) {
84
+ export function mdx_plugin(base, links) {
100
85
  return mdx({
101
86
  jsxImportSource: "react",
102
87
  remarkPlugins: [remark_frontmatter, remark_drop_title_heading, remark_gfm, remark_github_alerts],
@@ -104,9 +89,8 @@ export function mdx_plugin(base) {
104
89
  [rehype_raw, { passThrough: mdx_node_types }],
105
90
  rehype_slug,
106
91
  [rehype_autolink_headings, { behavior: "append", properties: { className: ["heading-anchor"], ariaHidden: "true", tabIndex: -1, dataPagefindIgnore: "" }, content: { type: "text", value: "#" } }],
107
- rehype_mermaid_blocks,
108
92
  [rehype_shiki, { theme: halon_code_theme, defaultLanguage: "text", fallbackLanguage: "text" }],
109
- [rehype_base_links, base],
93
+ [rehype_base_links, base, links],
110
94
  ],
111
95
  });
112
96
  }
@@ -92,7 +92,8 @@ export interface SourcePage {
92
92
  frontmatter: Frontmatter;
93
93
  last_updated?: string;
94
94
  }
95
- export declare function place_of_file(id: string, locale_keys: readonly string[]): {
95
+ export declare function index_files(ids: readonly string[]): Set<string>;
96
+ export declare function place_of_file(id: string, locale_keys: readonly string[], is_index?: boolean): {
96
97
  locale: string;
97
98
  slug: string;
98
99
  };
@@ -8,11 +8,20 @@ const english_root = { [root_locale]: { label: "English", lang: "en" } };
8
8
  export function site_locales(config) {
9
9
  return config.locales ?? english_root;
10
10
  }
11
- // The locale and slug a content file serves, from its path under the content folder.
12
- export function place_of_file(id, locale_keys) {
11
+ const index_name = /(^|\/)index\.mdx?$/;
12
+ const readme_name = /(^|\/)readme\.mdx?$/i;
13
+ // The content files that are their folder's own page: each index file, and a README in a folder with no index file.
14
+ export function index_files(ids) {
15
+ const folder_of = (id) => id.slice(0, id.lastIndexOf("/") + 1);
16
+ const with_index = new Set(ids.filter((id) => index_name.test(id)).map(folder_of));
17
+ return new Set(ids.filter((id) => index_name.test(id) || (readme_name.test(id) && !with_index.has(folder_of(id)))));
18
+ }
19
+ // The locale and slug a content file serves, from its path under the content folder; an index file, or a README that
20
+ // stands for one, serves its folder.
21
+ export function place_of_file(id, locale_keys, is_index = index_name.test(id)) {
13
22
  const parts = id.replace(/\.mdx?$/, "").split("/");
14
23
  const locale = parts.length > 1 && parts[0] !== root_locale && locale_keys.includes(parts[0]) ? parts.shift() : root_locale;
15
- if (parts.at(-1) === "index")
24
+ if (is_index)
16
25
  parts.pop();
17
26
  return { locale, slug: parts.join("/") };
18
27
  }
@@ -1,7 +1,8 @@
1
1
  // Whether the page is phone-sized, the width at which Halon draws widgets in their phone layouts.
2
2
  import { useEffect, useState } from "react";
3
3
  const phone_query = "(max-width: 640px)";
4
- const matches = (query) => typeof window.matchMedia === "function" && window.matchMedia(query).matches;
4
+ // False where there is no window, as when a site's pages are drawn to HTML at build time.
5
+ const matches = (query) => typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia(query).matches;
5
6
  // Whether a media query such as "(max-width: 700px)" matches, read again whenever it changes.
6
7
  export function use_media_query(query) {
7
8
  const [matched, set_matched] = useState(() => matches(query));
@@ -1,6 +1,5 @@
1
1
  import { type ComponentType, type ReactNode } from "react";
2
2
  import { type NavItem, type PageData } from "../../site/model.ts";
3
- import type { DiagramDrawer } from "../site/mermaid.ts";
4
3
  import { type SearchHit } from "./search_dialog.tsx";
5
4
  export type { PageData } from "../../site/model.ts";
6
5
  export declare function use_site_page(): PageData;
@@ -11,9 +10,8 @@ interface SitePageProps {
11
10
  page: PageData;
12
11
  Content: PageContent;
13
12
  search?: (query: string) => Promise<SearchHit[]>;
14
- draw_diagram?: DiagramDrawer;
15
13
  }
16
- export declare function SitePage({ page, Content, search, draw_diagram }: SitePageProps): import("react").JSX.Element;
14
+ export declare function SitePage({ page, Content, search }: SitePageProps): import("react").JSX.Element;
17
15
  export declare function SiteNav({ items, current }: {
18
16
  items: NavItem[];
19
17
  current: string;
@@ -2,7 +2,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  // A static site's page in the X-apps' frame: the Shell with the site's sidebar, search, links and language picker in
3
3
  // the top bar, the page's outline beside it, and edit, date and previous and next links at its foot. The pieces a page's
4
4
  // MDX can use, such as cards and asides, are here too.
5
- import { createContext, useContext, useEffect, useMemo, useState, useSyncExternalStore } from "react";
5
+ import { createContext, useContext, useMemo, useState } from "react";
6
6
  import { with_base } from "../../site/model.js";
7
7
  import { create_translator } from "../../i18n.js";
8
8
  import { theme_choice } from "../theme.js";
@@ -19,50 +19,7 @@ export function use_site_page() {
19
19
  throw new Error("Site content is drawn outside a SitePage.");
20
20
  return page;
21
21
  }
22
- // ── Diagrams ─────────────────────────────────────────────────────────────────
23
- const DiagramDrawing = createContext(null);
24
- // Whether the page shows its dark scheme: the theme picked, else the system's, followed as either changes.
25
- function use_dark_page() {
26
- return useSyncExternalStore((changed) => {
27
- const media = matchMedia("(prefers-color-scheme: dark)");
28
- const observer = new MutationObserver(changed);
29
- observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
30
- media.addEventListener("change", changed);
31
- return () => {
32
- observer.disconnect();
33
- media.removeEventListener("change", changed);
34
- };
35
- }, () => {
36
- const theme = document.documentElement.dataset.theme;
37
- return theme === undefined ? matchMedia("(prefers-color-scheme: dark)").matches : theme === "dark";
38
- }, () => false);
39
- }
40
- // A ```mermaid block: its source until the page has drawn it, then the diagram, drawn again when the scheme changes.
41
- function Diagram({ source }) {
42
- const draw = useContext(DiagramDrawing);
43
- const dark = use_dark_page();
44
- const [svg, set_svg] = useState(null);
45
- useEffect(() => {
46
- if (draw === null)
47
- return;
48
- let shown = true;
49
- draw(source, dark).then((drawn) => shown && set_svg(drawn), () => shown && set_svg(null));
50
- return () => {
51
- shown = false;
52
- };
53
- }, [draw, source, dark]);
54
- if (svg === null)
55
- return _jsx("pre", { className: "site-diagram-source", "data-pagefind-ignore": "", children: source });
56
- return _jsx("div", { className: "site-diagram", "data-pagefind-ignore": "", dangerouslySetInnerHTML: { __html: svg } });
57
- }
58
- // A Markdown <pre>: a diagram when the build marked it as mermaid, else code as it is.
59
- function SitePre({ "data-mermaid": mermaid, ...props }) {
60
- if (mermaid === undefined)
61
- return _jsx("pre", { ...props });
62
- return _jsx(Diagram, { source: typeof props.children === "string" ? props.children : String(props.children ?? "") });
63
- }
64
- const content_components = { pre: SitePre };
65
- export function SitePage({ page, Content, search, draw_diagram }) {
22
+ export function SitePage({ page, Content, search }) {
66
23
  const t = create_translator(page.ui);
67
24
  const theme = useMemo(() => theme_choice(page.site.theme_key), [page.site.theme_key]);
68
25
  const [is_searching, set_searching] = useState(false);
@@ -77,7 +34,7 @@ export function SitePage({ page, Content, search, draw_diagram }) {
77
34
  change_theme: t("change_theme"),
78
35
  };
79
36
  const tools = (_jsxs("div", { className: "site-tools", children: [search && page.site.search && _jsx(SearchButton, { label: t("search"), on_open: () => set_searching(true) }), _jsxs("div", { className: "site-tools-end", children: [_jsx(SocialLinks, { links: page.site.social }), _jsx(LanguagePicker, { page: page, label: t("language") })] })] }));
80
- return (_jsx(SiteData.Provider, { value: page, children: _jsxs(DiagramDrawing.Provider, { value: draw_diagram ?? null, children: [_jsx(Shell, { brand: page.site.title, brand_icon: page.site.logo_replaces_title ? undefined : page.site.logo, brand_logo: page.site.logo_replaces_title ? page.site.logo : undefined, brand_href: page.site.home, sidebar: _jsx(SiteNav, { items: page.nav, current: page.href }), theme: theme, tools: tools, labels: labels, view_key: page.href, children: page.template === "splash" ? _jsx(SplashLayout, { page: page, Content: Content, t: t }) : _jsx(DocLayout, { page: page, Content: Content, t: t }) }), is_searching && search && (_jsx(SearchDialog, { search: search, on_close: () => set_searching(false), labels: { title: t("search_title"), placeholder: t("search_placeholder"), no_results: t("search_no_results"), searching: t("search_searching") } }))] }) }));
37
+ return (_jsxs(SiteData.Provider, { value: page, children: [_jsx(Shell, { brand: page.site.title, brand_icon: page.site.logo_replaces_title ? undefined : page.site.logo, brand_logo: page.site.logo_replaces_title ? page.site.logo : undefined, brand_href: page.site.home, sidebar: _jsx(SiteNav, { items: page.nav, current: page.href }), theme: theme, tools: tools, labels: labels, view_key: page.href, children: page.template === "splash" ? _jsx(SplashLayout, { page: page, Content: Content, t: t }) : _jsx(DocLayout, { page: page, Content: Content, t: t }) }), is_searching && search && (_jsx(SearchDialog, { search: search, on_close: () => set_searching(false), labels: { title: t("search_title"), placeholder: t("search_placeholder"), no_results: t("search_no_results"), searching: t("search_searching") } }))] }));
81
38
  }
82
39
  // Search indexes only a page's own words, so the missing-page page and one shown in the default language for want of a
83
40
  // translation are left out.
@@ -87,11 +44,11 @@ function search_body(page) {
87
44
  function DocLayout({ page, Content, t }) {
88
45
  const has_outline = page.toc && page.headings.length > 0;
89
46
  const outline = [{ heading: t("on_this_page"), items: page.headings.map((heading) => ({ target: heading.id, label: heading.text, level: heading.level })) }];
90
- return (_jsxs("div", { className: has_outline ? "site-page with-outline" : "site-page", children: [_jsxs("div", { className: "site-main", children: [has_outline && (_jsxs("details", { className: "site-outline-narrow", children: [_jsx("summary", { children: t("on_this_page") }), _jsx(Outline, { groups: [{ items: outline[0].items }], label: t("on_this_page"), update_hash: true })] })), _jsxs("article", { className: "site-article", ...search_body(page), children: [_jsx("h1", { className: "site-title", children: page.title }), page.description && _jsx("p", { className: "site-lead", children: page.description }), page.fallback_language && _jsx("p", { className: "banner site-notice", children: t("not_translated", { language: page.fallback_language }) }), _jsx("div", { className: "markdown site-content", children: _jsx(Content, { components: content_components }) })] }), _jsx(PageFoot, { page: page, t: t })] }), has_outline && (_jsx("aside", { className: "site-outline", children: _jsx(Outline, { groups: outline, label: t("on_this_page"), update_hash: true }) }))] }));
47
+ return (_jsxs("div", { className: has_outline ? "site-page with-outline" : "site-page", children: [_jsxs("div", { className: "site-main", children: [has_outline && (_jsxs("details", { className: "site-outline-narrow", children: [_jsx("summary", { children: t("on_this_page") }), _jsx(Outline, { groups: [{ items: outline[0].items }], label: t("on_this_page"), update_hash: true })] })), _jsxs("article", { className: "site-article", ...search_body(page), children: [_jsx("h1", { className: "site-title", children: page.title }), page.description && _jsx("p", { className: "site-lead", children: page.description }), page.fallback_language && _jsx("p", { className: "banner site-notice", children: t("not_translated", { language: page.fallback_language }) }), _jsx("div", { className: "markdown site-content", children: _jsx(Content, {}) })] }), _jsx(PageFoot, { page: page, t: t })] }), has_outline && (_jsx("aside", { className: "site-outline", children: _jsx(Outline, { groups: outline, label: t("on_this_page"), update_hash: true }) }))] }));
91
48
  }
92
49
  function SplashLayout({ page, Content, t }) {
93
50
  const hero = page.hero ?? {};
94
- return (_jsx("div", { className: "site-page splash", children: _jsxs("div", { className: "site-main", children: [_jsxs("article", { className: "site-article", ...search_body(page), children: [_jsxs("header", { className: "site-hero", children: [_jsxs("div", { className: "site-hero-text", children: [_jsx("h1", { className: "site-title", children: hero.title ?? page.title }), (hero.tagline ?? page.description) && _jsx("p", { className: "site-hero-tagline", children: hero.tagline ?? page.description }), hero.actions && hero.actions.length > 0 && (_jsx("div", { className: "site-hero-actions", children: hero.actions.map((action) => (_jsx("a", { href: with_base(page.base, action.link), className: action_class(action.variant), children: action.text }, action.link))) }))] }), hero.image && _jsx("img", { className: "site-hero-image", src: hero.image, alt: "" })] }), page.fallback_language && _jsx("p", { className: "banner site-notice", children: t("not_translated", { language: page.fallback_language }) }), _jsx("div", { className: "markdown site-content", children: _jsx(Content, { components: content_components }) })] }), _jsx(PageFoot, { page: page, t: t })] }) }));
51
+ return (_jsx("div", { className: "site-page splash", children: _jsxs("div", { className: "site-main", children: [_jsxs("article", { className: "site-article", ...search_body(page), children: [_jsxs("header", { className: "site-hero", children: [_jsxs("div", { className: "site-hero-text", children: [_jsx("h1", { className: "site-title", children: hero.title ?? page.title }), (hero.tagline ?? page.description) && _jsx("p", { className: "site-hero-tagline", children: hero.tagline ?? page.description }), hero.actions && hero.actions.length > 0 && (_jsx("div", { className: "site-hero-actions", children: hero.actions.map((action) => (_jsx("a", { href: with_base(page.base, action.link), className: action_class(action.variant), children: action.text }, action.link))) }))] }), hero.image && _jsx("img", { className: "site-hero-image", src: hero.image, alt: "" })] }), page.fallback_language && _jsx("p", { className: "banner site-notice", children: t("not_translated", { language: page.fallback_language }) }), _jsx("div", { className: "markdown site-content", children: _jsx(Content, {}) })] }), _jsx(PageFoot, { page: page, t: t })] }) }));
95
52
  }
96
53
  function action_class(variant = "primary") {
97
54
  return variant === "primary" ? "button accent solid" : variant === "secondary" ? "button" : "button minimal";
@@ -1,6 +1,2 @@
1
- import type { DiagramDrawer } from "./mermaid.ts";
2
1
  import { type PageModules } from "./pages.ts";
3
- export interface SiteOptions {
4
- draw_diagram?: DiagramDrawer;
5
- }
6
- export declare function start_site(pages: PageModules, options?: SiteOptions): Promise<void>;
2
+ export declare function start_site(pages: PageModules): Promise<void>;
@@ -1,11 +1,11 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- // Picks up a page the build drew, so its search, outline, menus, theme and diagrams work in the browser.
2
+ // Picks up a page the build drew, so its search, outline, menus and theme work in the browser.
3
3
  import { hydrateRoot } from "react-dom/client";
4
4
  import { NotFound, SitePage } from "../react/site.js";
5
5
  import { pagefind_search } from "./pagefind.js";
6
6
  import { load_content } from "./pages.js";
7
- export async function start_site(pages, options = {}) {
7
+ export async function start_site(pages) {
8
8
  const page = JSON.parse(document.getElementById("x-site-page").textContent);
9
9
  const Content = (await load_content(pages, page.source)) ?? NotFound;
10
- hydrateRoot(document.getElementById("root"), _jsx(SitePage, { page: page, Content: Content, search: pagefind_search(page.base, page.ui.search_unavailable), draw_diagram: options.draw_diagram }));
10
+ hydrateRoot(document.getElementById("root"), _jsx(SitePage, { page: page, Content: Content, search: pagefind_search(page.base, page.ui.search_unavailable) }));
11
11
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x-tech-laboratories/x-app",
3
- "version": "0.127.0",
3
+ "version": "0.129.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": {
@@ -61,7 +61,6 @@
61
61
  "electron-builder": "^26.18.0",
62
62
  "electron-vite": "^6.0.0",
63
63
  "fastify": "^5.12.7",
64
- "mermaid": "^11.0.0",
65
64
  "nodemailer": "^10.3.1",
66
65
  "pagefind": "^1.6.0",
67
66
  "react": "^19",
@@ -138,9 +137,6 @@
138
137
  "fastify": {
139
138
  "optional": true
140
139
  },
141
- "mermaid": {
142
- "optional": true
143
- },
144
140
  "nodemailer": {
145
141
  "optional": true
146
142
  },
@@ -1,11 +0,0 @@
1
- export interface MermaidModule {
2
- initialize(config: Record<string, unknown>): void;
3
- render(id: string, text: string): Promise<{
4
- svg: string;
5
- }>;
6
- }
7
- export type DiagramDrawer = (source: string, dark: boolean) => Promise<string>;
8
- export declare function mermaid_theme(read: (token: string) => string, dark: boolean): Record<string, unknown>;
9
- export declare function mermaid_drawer(load: () => Promise<{
10
- default: MermaidModule;
11
- }>): DiagramDrawer;
@@ -1,65 +0,0 @@
1
- // Draws a site's ```mermaid blocks with mermaid, coloured by Halon's tokens for the scheme the page shows. The site's
2
- // browser entry hands in its own import of mermaid, so X-App never needs it and sites without diagrams never load it.
3
- // ── Colours ──────────────────────────────────────────────────────────────────
4
- // Mermaid's theme variables from the page's Halon tokens, as the current scheme sets them.
5
- export function mermaid_theme(read, dark) {
6
- const surface = read("--surface-default") || (dark ? "#16213a" : "#ffffff");
7
- const panel = read("--surface-secondary") || (dark ? "#060b14" : "#f1f5f9");
8
- const text = read("--text-body") || (dark ? "#e2e8f0" : "#1a1a2e");
9
- const muted = read("--text-secondary") || (dark ? "#cbd5e1" : "#475569");
10
- const border = read("--border-default") || (dark ? "#334155" : "#e2e8f0");
11
- return {
12
- darkMode: dark,
13
- background: surface,
14
- fontFamily: read("--font-family-interface") || "Noto Sans, sans-serif",
15
- fontSize: "14px",
16
- primaryColor: panel,
17
- primaryTextColor: text,
18
- primaryBorderColor: muted,
19
- secondaryColor: surface,
20
- tertiaryColor: panel,
21
- lineColor: muted,
22
- textColor: text,
23
- mainBkg: panel,
24
- nodeBorder: muted,
25
- clusterBkg: surface,
26
- clusterBorder: border,
27
- edgeLabelBackground: surface,
28
- noteBkgColor: panel,
29
- noteTextColor: text,
30
- noteBorderColor: border,
31
- actorBkg: panel,
32
- actorBorder: muted,
33
- actorTextColor: text,
34
- signalColor: text,
35
- signalTextColor: text,
36
- labelBoxBkgColor: panel,
37
- labelTextColor: text,
38
- };
39
- }
40
- // ── Drawing ──────────────────────────────────────────────────────────────────
41
- // A drawer that loads mermaid on its first diagram and sets its colours again whenever the scheme changes; diagrams
42
- // are drawn one at a time, since mermaid's settings are shared by every diagram.
43
- export function mermaid_drawer(load) {
44
- let loading = null;
45
- let scheme = null;
46
- let count = 0;
47
- let queue = Promise.resolve();
48
- const draw = async (source, dark) => {
49
- loading ??= load().then((module) => module.default);
50
- const mermaid = await loading;
51
- if (scheme !== dark) {
52
- const styles = getComputedStyle(document.documentElement);
53
- mermaid.initialize({ startOnLoad: false, securityLevel: "strict", theme: "base", themeVariables: mermaid_theme((token) => styles.getPropertyValue(token).trim(), dark) });
54
- scheme = dark;
55
- }
56
- count += 1;
57
- const { svg } = await mermaid.render(`site-diagram-${count}`, source);
58
- return svg;
59
- };
60
- return (source, dark) => {
61
- const next = queue.then(() => draw(source, dark));
62
- queue = next.catch(() => { });
63
- return next;
64
- };
65
- }