@x-tech-laboratories/x-app 0.128.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,8 +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`.
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.
823
838
  - **Diagrams**: images like any other. Draw them in [draw.io](https://www.drawio.com/), keep the `.drawio` source beside
824
- its PNG export in `public/`, and show the PNG; a ```` ```mermaid ```` block is only code.
839
+ its PNG export, in `public/` or beside the pages, and show the PNG; a ```` ```mermaid ```` block is only code.
825
840
  - **Pages beside a package**: the scan skips `node_modules`, `dist`, `public` and hidden folders, so a site can live in
826
841
  an app's `docs/` folder with a `package.json` of its own.
827
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,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;
@@ -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,7 +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 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, 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
  }
@@ -78,7 +81,7 @@ export function remark_drop_title_heading() {
78
81
  }
79
82
  // MDX's own nodes, which raw HTML parsing must pass through untouched.
80
83
  const mdx_node_types = ["mdxFlowExpression", "mdxJsxFlowElement", "mdxJsxTextElement", "mdxTextExpression", "mdxjsEsm"];
81
- export function mdx_plugin(base) {
84
+ export function mdx_plugin(base, links) {
82
85
  return mdx({
83
86
  jsxImportSource: "react",
84
87
  remarkPlugins: [remark_frontmatter, remark_drop_title_heading, remark_gfm, remark_github_alerts],
@@ -87,7 +90,7 @@ export function mdx_plugin(base) {
87
90
  rehype_slug,
88
91
  [rehype_autolink_headings, { behavior: "append", properties: { className: ["heading-anchor"], ariaHidden: "true", tabIndex: -1, dataPagefindIgnore: "" }, content: { type: "text", value: "#" } }],
89
92
  [rehype_shiki, { theme: halon_code_theme, defaultLanguage: "text", fallbackLanguage: "text" }],
90
- [rehype_base_links, base],
93
+ [rehype_base_links, base, links],
91
94
  ],
92
95
  });
93
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));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x-tech-laboratories/x-app",
3
- "version": "0.128.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": {