@screenreader-speech-capture/bridge 0.1.0-feat-expected-target-window.34 → 0.2.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/dist/cli.mjs +1244 -948
- package/dist/ui/adapter-node.js +1 -1
- package/dist/ui/client/ui/_app/immutable/assets/{4.DyY1vjRV.css → 4.DEk4yqpA.css} +1 -1
- package/dist/ui/client/ui/_app/immutable/assets/4.DEk4yqpA.css.br +0 -0
- package/dist/ui/client/ui/_app/immutable/assets/4.DEk4yqpA.css.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/{B1Ryegye.js → Bq3k_s8n.js} +1 -1
- package/dist/ui/client/ui/_app/immutable/chunks/Bq3k_s8n.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/Bq3k_s8n.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/{CMWEX9XL.js → CEGGem4o.js} +1 -1
- package/dist/ui/client/ui/_app/immutable/chunks/CEGGem4o.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/CEGGem4o.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/{tKonUL5Y.js → Cwz551Q0.js} +4 -3
- package/dist/ui/client/ui/_app/immutable/chunks/Cwz551Q0.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/Cwz551Q0.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/{4wvZDMeR.js → DJvJc_zO.js} +1 -1
- package/dist/ui/client/ui/_app/immutable/chunks/DJvJc_zO.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/DJvJc_zO.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/{CK3uUd4t.js → DU8ibkb0.js} +1 -1
- package/dist/ui/client/ui/_app/immutable/chunks/DU8ibkb0.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/DU8ibkb0.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/{BS7n1gMj.js → Dk73DTz3.js} +1 -1
- package/dist/ui/client/ui/_app/immutable/chunks/Dk73DTz3.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/Dk73DTz3.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/{DOY87jO2.js → DoG5cwE3.js} +1 -1
- package/dist/ui/client/ui/_app/immutable/chunks/DoG5cwE3.js.br +3 -0
- package/dist/ui/client/ui/_app/immutable/chunks/DoG5cwE3.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/hhZsYtkz.js +3 -0
- package/dist/ui/client/ui/_app/immutable/chunks/hhZsYtkz.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/hhZsYtkz.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/entry/app.Bic9wlww.js +2 -0
- package/dist/ui/client/ui/_app/immutable/entry/app.Bic9wlww.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/entry/app.Bic9wlww.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/0.IqK6bsxB.js +1 -0
- package/dist/ui/client/ui/_app/immutable/nodes/0.IqK6bsxB.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/0.IqK6bsxB.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/{3.WT26F_BF.js → 3.DYZ3H5TS.js} +1 -1
- package/dist/ui/client/ui/_app/immutable/nodes/3.DYZ3H5TS.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/3.DYZ3H5TS.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/4.Lwlmq1AY.js +180 -0
- package/dist/ui/client/ui/_app/immutable/nodes/4.Lwlmq1AY.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/4.Lwlmq1AY.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/{5.MzfJoePg.js → 5.rBMVkFpN.js} +5 -5
- package/dist/ui/client/ui/_app/immutable/nodes/5.rBMVkFpN.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/5.rBMVkFpN.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/6.nui9awM2.js +6 -0
- package/dist/ui/client/ui/_app/immutable/nodes/6.nui9awM2.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/6.nui9awM2.js.gz +0 -0
- package/dist/ui/client/ui/_app/version.json +1 -1
- package/dist/ui/client/ui/_app/version.json.br +0 -0
- package/dist/ui/client/ui/_app/version.json.gz +0 -0
- package/dist/ui/server/.vite/manifest.json +18 -29
- package/dist/ui/server/_app/immutable/assets/{_page.DyY1vjRV.css → _page.DEk4yqpA.css} +1 -1
- package/dist/ui/server/chunks/composition.js +60 -5
- package/dist/ui/server/chunks/composition.js.map +1 -1
- package/dist/ui/server/chunks/instance.js +3 -3
- package/dist/ui/server/chunks/internal.js +1 -1
- package/dist/ui/server/chunks/outlined-button.js +116 -0
- package/dist/ui/server/chunks/outlined-button.js.map +1 -0
- package/dist/ui/server/chunks/src.js +19 -13
- package/dist/ui/server/chunks/src.js.map +1 -1
- package/dist/ui/server/entries/hooks.server.js +3 -2
- package/dist/ui/server/entries/hooks.server.js.map +1 -1
- package/dist/ui/server/entries/pages/_layout.svelte.js +2 -3
- package/dist/ui/server/entries/pages/_layout.svelte.js.map +1 -1
- package/dist/ui/server/entries/pages/_page.svelte.js +0 -1
- package/dist/ui/server/entries/pages/_page.svelte.js.map +1 -1
- package/dist/ui/server/entries/pages/settings/_page.svelte.js +139 -13
- package/dist/ui/server/entries/pages/settings/_page.svelte.js.map +1 -1
- package/dist/ui/server/entries/pages/setup/_page.svelte.js +2 -3
- package/dist/ui/server/entries/pages/setup/_page.svelte.js.map +1 -1
- package/dist/ui/server/entries/pages/setup/instructions/_page.svelte.js +15 -10
- package/dist/ui/server/entries/pages/setup/instructions/_page.svelte.js.map +1 -1
- package/dist/ui/server/manifest-full.js +1 -1
- package/dist/ui/server/manifest.js +1 -1
- package/dist/ui/server/nodes/0.js +1 -1
- package/dist/ui/server/nodes/3.js +1 -1
- package/dist/ui/server/nodes/4.js +2 -2
- package/dist/ui/server/nodes/5.js +1 -1
- package/dist/ui/server/nodes/6.js +1 -1
- package/dist/ui/server/server.js +1 -1
- package/package.json +1 -1
- package/dist/ui/client/ui/_app/immutable/assets/4.DyY1vjRV.css.br +0 -0
- package/dist/ui/client/ui/_app/immutable/assets/4.DyY1vjRV.css.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/4wvZDMeR.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/4wvZDMeR.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/B1Ryegye.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/B1Ryegye.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/B1vArRqi.js +0 -3
- package/dist/ui/client/ui/_app/immutable/chunks/B1vArRqi.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/B1vArRqi.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/BS7n1gMj.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/BS7n1gMj.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/BnU72Mow.js +0 -2
- package/dist/ui/client/ui/_app/immutable/chunks/BnU72Mow.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/BnU72Mow.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/CK3uUd4t.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/CK3uUd4t.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/CMWEX9XL.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/CMWEX9XL.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/DOY87jO2.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/DOY87jO2.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/tKonUL5Y.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/chunks/tKonUL5Y.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/entry/app.C8tsut3X.js +0 -2
- package/dist/ui/client/ui/_app/immutable/entry/app.C8tsut3X.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/entry/app.C8tsut3X.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/0.3bVKqGbx.js +0 -1
- package/dist/ui/client/ui/_app/immutable/nodes/0.3bVKqGbx.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/0.3bVKqGbx.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/3.WT26F_BF.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/3.WT26F_BF.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/4.tiDJxi6M.js +0 -160
- package/dist/ui/client/ui/_app/immutable/nodes/4.tiDJxi6M.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/4.tiDJxi6M.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/5.MzfJoePg.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/5.MzfJoePg.js.gz +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/6.bNZhqiRK.js +0 -6
- package/dist/ui/client/ui/_app/immutable/nodes/6.bNZhqiRK.js.br +0 -0
- package/dist/ui/client/ui/_app/immutable/nodes/6.bNZhqiRK.js.gz +0 -0
- package/dist/ui/server/chunks/filled-button.js +0 -116
- package/dist/ui/server/chunks/filled-button.js.map +0 -1
- package/dist/ui/server/chunks/icon.js +0 -49
- package/dist/ui/server/chunks/icon.js.map +0 -1
package/dist/cli.mjs
CHANGED
|
@@ -1,27 +1,28 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
|
+
import { once, setMaxListeners } from "node:events";
|
|
3
4
|
import os, { hostname } from "node:os";
|
|
4
5
|
import http from "node:http";
|
|
5
6
|
import net from "node:net";
|
|
6
|
-
import { finished } from "node:stream";
|
|
7
|
+
import { finished, pipeline } from "node:stream";
|
|
7
8
|
import { setImmediate, setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
9
|
+
import fs, { existsSync, readFileSync } from "node:fs";
|
|
8
10
|
import { TextDecoder as TextDecoder$1, parseArgs } from "node:util";
|
|
9
|
-
import fs, { mkdir, readdir, rename, rm, writeFile } from "node:fs/promises";
|
|
11
|
+
import fs$1, { mkdir, readdir, rename, rm, writeFile } from "node:fs/promises";
|
|
10
12
|
import path from "node:path";
|
|
11
13
|
import { Worker } from "node:worker_threads";
|
|
12
|
-
import fs$1, { existsSync, readFileSync } from "node:fs";
|
|
13
14
|
import { execFile, spawn, spawnSync } from "node:child_process";
|
|
14
|
-
import { once } from "node:events";
|
|
15
15
|
import readline from "node:readline";
|
|
16
|
+
import { createInterface } from "node:readline/promises";
|
|
16
17
|
// package.json
|
|
17
|
-
var version = "0.
|
|
18
|
+
var version = "0.2.0";
|
|
18
19
|
// ../shared/src/api-version.ts
|
|
19
20
|
/**
|
|
20
21
|
* `<major>.<minor>` of the HTTP API. Minor versions only add things, with the exceptions in
|
|
21
22
|
* docs/usage/http-api.md#versioning. Within a major version the enums of the answers never grow
|
|
22
23
|
* (`openapi/freeze.test.ts`).
|
|
23
24
|
*/
|
|
24
|
-
const API_VERSION = "1.
|
|
25
|
+
const API_VERSION = "1.33";
|
|
25
26
|
/** Path prefix of every API route. */
|
|
26
27
|
const API_PREFIX = "/api/v1";
|
|
27
28
|
/**
|
|
@@ -742,7 +743,7 @@ function safeParse(schema, input, config$1) {
|
|
|
742
743
|
issues: dataset.issues
|
|
743
744
|
};
|
|
744
745
|
}
|
|
745
|
-
// ../shared/src/limits.ts
|
|
746
|
+
// ../shared/src/rules/limits.ts
|
|
746
747
|
/** Ranges of the speech endpoints. */
|
|
747
748
|
const API_LIMITS = {
|
|
748
749
|
/** `GET /speech?limit=`: the default and the most a caller may ask for. */
|
|
@@ -836,6 +837,22 @@ const isTrimmedLabel = (text, max) => {
|
|
|
836
837
|
const trimmed = text.trim();
|
|
837
838
|
return trimmed !== "" && trimmed.length <= max;
|
|
838
839
|
};
|
|
840
|
+
// ../shared/src/rules/vocabulary.ts
|
|
841
|
+
/** `log.level`, from the least to the most detail. */
|
|
842
|
+
const LOG_LEVELS = [
|
|
843
|
+
"error",
|
|
844
|
+
"warn",
|
|
845
|
+
"info",
|
|
846
|
+
"debug"
|
|
847
|
+
];
|
|
848
|
+
/** The buttons of a native click. */
|
|
849
|
+
const MOUSE_BUTTONS = [
|
|
850
|
+
"left",
|
|
851
|
+
"right",
|
|
852
|
+
"middle"
|
|
853
|
+
];
|
|
854
|
+
/** Whose browser a focus or a key press means. */
|
|
855
|
+
const FOCUS_TARGETS = ["mcp", "playwright"];
|
|
839
856
|
// ../shared/src/config.ts
|
|
840
857
|
/** A `TextDecoder` label other than UTF-16 (the framing splits the bytes on 0x0A first). */
|
|
841
858
|
function isSupportedEncoding(label) {
|
|
@@ -845,12 +862,6 @@ function isSupportedEncoding(label) {
|
|
|
845
862
|
return false;
|
|
846
863
|
}
|
|
847
864
|
}
|
|
848
|
-
const LOG_LEVELS = [
|
|
849
|
-
"error",
|
|
850
|
-
"warn",
|
|
851
|
-
"info",
|
|
852
|
-
"debug"
|
|
853
|
-
];
|
|
854
865
|
const range = ({ min, max }) => /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(min), /* @__PURE__ */ maxValue(max));
|
|
855
866
|
const port = range(CONFIG_LIMITS.port);
|
|
856
867
|
/** Port of a child service: `0` ("any free port") would leave the bridge no port to proxy to. */
|
|
@@ -927,14 +938,9 @@ CAPTURE.entries, `${CAPTURE.entries}`;
|
|
|
927
938
|
const ClickRequestSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ strictObject({
|
|
928
939
|
x: /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(-coordinate$1), /* @__PURE__ */ maxValue(coordinate$1), /* @__PURE__ */ description("Screen x in physical pixels."), /* @__PURE__ */ examples([640])),
|
|
929
940
|
y: /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(-coordinate$1), /* @__PURE__ */ maxValue(coordinate$1), /* @__PURE__ */ description("Screen y in physical pixels."), /* @__PURE__ */ examples([12])),
|
|
930
|
-
button: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ picklist(
|
|
931
|
-
"left",
|
|
932
|
-
"right",
|
|
933
|
-
"middle"
|
|
934
|
-
])), /* @__PURE__ */ description("Mouse button, `left` if omitted.")),
|
|
941
|
+
button: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ picklist(MOUSE_BUTTONS)), /* @__PURE__ */ description("Mouse button, `left` if omitted.")),
|
|
935
942
|
capture
|
|
936
943
|
}), /* @__PURE__ */ description("`POST /input/click`: a native mouse click at a screen point, to give a window the focus. Added in API 1.14."));
|
|
937
|
-
const FOCUS_TARGETS = ["mcp", "playwright"];
|
|
938
944
|
const KeysRequestSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ strictObject({
|
|
939
945
|
keys: /* @__PURE__ */ pipe(/* @__PURE__ */ union([/* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ nonEmpty()), /* @__PURE__ */ pipe(/* @__PURE__ */ array(/* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ nonEmpty())), /* @__PURE__ */ minLength(1), /* @__PURE__ */ maxLength(maxKeys$1))]), /* @__PURE__ */ description(`One chord (\`Insert+T\`) or a sequence of chords (\`["h", "h", "Insert+Down"]\`). Chords join modifiers (\`Control\`, \`Shift\`, \`Alt\`, \`Win\`, \`Insert\`, \`CapsLock\`) and one key with \`+\`. Names are case-insensitive (docs/usage/native-input.md#key-names); the numpad keys (\`numpad7\`, \`numpadEnter\`, …) since API 1.30. At most ${maxKeys$1} chords.`), /* @__PURE__ */ examples(["Insert+T"])),
|
|
940
946
|
delayMs: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(0), /* @__PURE__ */ maxValue(delayMs$1.max))), /* @__PURE__ */ description(`Pause between the chords of a sequence in milliseconds, ${delayMs$1.default} if omitted.`)),
|
|
@@ -945,7 +951,7 @@ const FocusRequestSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ strictObject({
|
|
|
945
951
|
target: /* @__PURE__ */ pipe(/* @__PURE__ */ picklist(FOCUS_TARGETS), /* @__PURE__ */ description("Whose browser: `mcp` (Playwright MCP) or `playwright` (the Playwright server, for tests).")),
|
|
946
952
|
title: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ minLength(1), /* @__PURE__ */ maxLength(API_LIMITS.input.focusTitleLength))), /* @__PURE__ */ description("Only a window whose title contains this text, for example a marker the caller put into `document.title`. Without it, the front-most window of the target."))
|
|
947
953
|
}), /* @__PURE__ */ description("`POST /input/focus`: bring a browser window the bridge started to the front. Added in API 1.21."));
|
|
948
|
-
// ../shared/src/key-chord.ts
|
|
954
|
+
// ../shared/src/rules/key-chord.ts
|
|
949
955
|
/**
|
|
950
956
|
* The key names of `POST /input/keys` (docs/usage/native-input.md#key-names). The bridge parses
|
|
951
957
|
* chords with this rule, and the CLI checks them before sending and lists the names in `--help`,
|
|
@@ -1045,38 +1051,12 @@ function parseKeyChord$1(chord) {
|
|
|
1045
1051
|
}
|
|
1046
1052
|
};
|
|
1047
1053
|
}
|
|
1048
|
-
// ../shared/src/
|
|
1054
|
+
// ../shared/src/rules/service-paths.ts
|
|
1049
1055
|
/** The Playwright server (`connectOptions.wsEndpoint`): `ws://<bridge>:5151/playwright`. */
|
|
1050
1056
|
const PLAYWRIGHT_PATH = "/playwright";
|
|
1051
1057
|
/** Playwright MCP (streamable HTTP): `http://<bridge>:5151/playwright-mcp`. */
|
|
1052
1058
|
const PLAYWRIGHT_MCP_PATH = "/playwright-mcp";
|
|
1053
|
-
// ../shared/src/
|
|
1054
|
-
const integer$1 = (min) => /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(min));
|
|
1055
|
-
const timestamp$1 = /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ isoTimestamp());
|
|
1056
|
-
const label = (text) => /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ check((text) => isTrimmedLabel(text, API_LIMITS.sessionLabelLength)), /* @__PURE__ */ description(`${text} Trimmed, must not be empty, at most ${API_LIMITS.sessionLabelLength} characters.`));
|
|
1057
|
-
const sessionEntries = {
|
|
1058
|
-
id: /* @__PURE__ */ pipe(integer$1(1), /* @__PURE__ */ description("Increasing, also across restarts (since API 1.29): the first session of a bridge run gets the run's start time in milliseconds, so an id is never given out twice.")),
|
|
1059
|
-
name: /* @__PURE__ */ string(),
|
|
1060
|
-
run: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), /* @__PURE__ */ description("Optional label that groups sessions.")),
|
|
1061
|
-
client: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), /* @__PURE__ */ description("Who started it: the `X-SR-Speech-Client` header, `null` if it wasn't sent. Added in API 1.10.")),
|
|
1062
|
-
startedAt: timestamp$1,
|
|
1063
|
-
endedAt: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(timestamp$1), /* @__PURE__ */ description("`null` while the session is current.")),
|
|
1064
|
-
startSeq: /* @__PURE__ */ pipe(integer$1(0), /* @__PURE__ */ description("The last `seq` given out before the session started: `since=startSeq` reads the session from its start. Added in API 1.9.")),
|
|
1065
|
-
firstSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$1(1)), /* @__PURE__ */ description("First entry still in the buffer, `null` if none.")),
|
|
1066
|
-
lastSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$1(1)), /* @__PURE__ */ description("Last entry still in the buffer, `null` if none.")),
|
|
1067
|
-
entries: /* @__PURE__ */ pipe(integer$1(0), /* @__PURE__ */ description("Entries of this session still in the buffer."))
|
|
1068
|
-
};
|
|
1069
|
-
const StartSessionRequestSchema = /* @__PURE__ */ strictObject({
|
|
1070
|
-
name: /* @__PURE__ */ pipe(label("For example the test title."), /* @__PURE__ */ examples(["checkout test"])),
|
|
1071
|
-
run: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ nullable(label("Optional label that groups sessions, for example one per test run."))), /* @__PURE__ */ examples(["nightly-42"]))
|
|
1072
|
-
});
|
|
1073
|
-
({ ...sessionEntries });
|
|
1074
|
-
/**
|
|
1075
|
-
* Request header naming the client (for example `host pid 1234`), so the bridge can tell when
|
|
1076
|
-
* one client ends or replaces another one's session. Optional. API 1.10.
|
|
1077
|
-
*/
|
|
1078
|
-
const CLIENT_HEADER = "x-sr-speech-client";
|
|
1079
|
-
// ../shared/src/text-match.ts
|
|
1059
|
+
// ../shared/src/rules/text-match.ts
|
|
1080
1060
|
/**
|
|
1081
1061
|
* The `normalize` rule of the HTTP API (docs/usage/http-api.md). The bridge applies it in
|
|
1082
1062
|
* `GET /speech/wait`, the client in its own waits, so both must use this one copy. It is the only
|
|
@@ -1104,6 +1084,32 @@ function createTextTest(match, normalize) {
|
|
|
1104
1084
|
if (needle === "") return void 0;
|
|
1105
1085
|
return (text) => prepare(text).includes(needle);
|
|
1106
1086
|
}
|
|
1087
|
+
// ../shared/src/session.ts
|
|
1088
|
+
const integer$1 = (min) => /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(min));
|
|
1089
|
+
const timestamp$1 = /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ isoTimestamp());
|
|
1090
|
+
const label = (text) => /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ check((text) => isTrimmedLabel(text, API_LIMITS.sessionLabelLength)), /* @__PURE__ */ description(`${text} Trimmed, must not be empty, at most ${API_LIMITS.sessionLabelLength} characters.`));
|
|
1091
|
+
const sessionEntries = {
|
|
1092
|
+
id: /* @__PURE__ */ pipe(integer$1(1), /* @__PURE__ */ description("Increasing, also across restarts (since API 1.29): the first session of a bridge run gets the run's start time in milliseconds, so an id is never given out twice.")),
|
|
1093
|
+
name: /* @__PURE__ */ string(),
|
|
1094
|
+
run: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), /* @__PURE__ */ description("Optional label that groups sessions.")),
|
|
1095
|
+
client: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), /* @__PURE__ */ description("Who started it: the `X-SR-Speech-Client` header, `null` if it wasn't sent. Added in API 1.10.")),
|
|
1096
|
+
startedAt: timestamp$1,
|
|
1097
|
+
endedAt: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(timestamp$1), /* @__PURE__ */ description("`null` while the session is current.")),
|
|
1098
|
+
startSeq: /* @__PURE__ */ pipe(integer$1(0), /* @__PURE__ */ description("The last `seq` given out before the session started: `since=startSeq` reads the session from its start. Added in API 1.9.")),
|
|
1099
|
+
firstSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$1(1)), /* @__PURE__ */ description("First entry still in the buffer, `null` if none.")),
|
|
1100
|
+
lastSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$1(1)), /* @__PURE__ */ description("Last entry still in the buffer, `null` if none.")),
|
|
1101
|
+
entries: /* @__PURE__ */ pipe(integer$1(0), /* @__PURE__ */ description("Entries of this session still in the buffer."))
|
|
1102
|
+
};
|
|
1103
|
+
const StartSessionRequestSchema = /* @__PURE__ */ strictObject({
|
|
1104
|
+
name: /* @__PURE__ */ pipe(label("For example the test title."), /* @__PURE__ */ examples(["checkout test"])),
|
|
1105
|
+
run: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ nullable(label("Optional label that groups sessions, for example one per test run."))), /* @__PURE__ */ examples(["nightly-42"]))
|
|
1106
|
+
});
|
|
1107
|
+
({ ...sessionEntries });
|
|
1108
|
+
/**
|
|
1109
|
+
* Request header naming the client (for example `host pid 1234`), so the bridge can tell when
|
|
1110
|
+
* one client ends or replaces another one's session. Optional. API 1.10.
|
|
1111
|
+
*/
|
|
1112
|
+
const CLIENT_HEADER = "x-sr-speech-client";
|
|
1107
1113
|
// ../shared/src/validate.ts
|
|
1108
1114
|
/**
|
|
1109
1115
|
* Checks `value` against `schema`. Unknown keys of an answer don't fail it and are left out of the
|
|
@@ -1123,6 +1129,108 @@ function checkDto(schema, value) {
|
|
|
1123
1129
|
message: issue.message
|
|
1124
1130
|
};
|
|
1125
1131
|
}
|
|
1132
|
+
// src/adapters/in/cli/lifecycle.ts
|
|
1133
|
+
const SHUTDOWN_TIMEOUT_MS = 1e4;
|
|
1134
|
+
/** Ctrl+C, `kill`, closing the console window, and Ctrl+Break on Windows. */
|
|
1135
|
+
function shutdownSignals(platform) {
|
|
1136
|
+
const signals = [
|
|
1137
|
+
"SIGINT",
|
|
1138
|
+
"SIGTERM",
|
|
1139
|
+
"SIGHUP"
|
|
1140
|
+
];
|
|
1141
|
+
if (platform === "win32") signals.push("SIGBREAK");
|
|
1142
|
+
return signals;
|
|
1143
|
+
}
|
|
1144
|
+
/** Resolves once everything written to `stream` so far is handed to the OS. */
|
|
1145
|
+
function drain(stream) {
|
|
1146
|
+
return new Promise((resolve) => stream.write("", () => resolve()));
|
|
1147
|
+
}
|
|
1148
|
+
/** Default `flush`: drains stdout and stderr. The log file is written synchronously. */
|
|
1149
|
+
async function flushConsole() {
|
|
1150
|
+
await Promise.all([drain(process.stdout), drain(process.stderr)]);
|
|
1151
|
+
}
|
|
1152
|
+
function describeError(error) {
|
|
1153
|
+
return error instanceof Error ? error.stack ?? String(error) : String(error);
|
|
1154
|
+
}
|
|
1155
|
+
/**
|
|
1156
|
+
* Starts the bridge with `start`, then stops it gracefully and exits the process
|
|
1157
|
+
* (docs/usage/operations.md#shutdown):
|
|
1158
|
+
*
|
|
1159
|
+
* - on a shutdown signal. A second signal exits at once.
|
|
1160
|
+
* - on an uncaught exception or unhandled rejection, which is logged with its stack. Exit code 1.
|
|
1161
|
+
* - if the shutdown takes longer than `timeoutMs`, it exits anyway with code 1.
|
|
1162
|
+
*
|
|
1163
|
+
* The exit code is 0 unless something failed. Console output is flushed before exiting.
|
|
1164
|
+
*
|
|
1165
|
+
* The signal handlers are installed before `start`, so a signal that arrives while the bridge
|
|
1166
|
+
* starts is not fatal: the bridge stops as soon as it has started. That signal also aborts the
|
|
1167
|
+
* `cancel` signal `start` gets, which ends a question on the console the start waits for.
|
|
1168
|
+
* Resolves once started; rejects like `start`.
|
|
1169
|
+
*/
|
|
1170
|
+
async function runUntilStopped(start, proc, options = {}) {
|
|
1171
|
+
const { timeoutMs = SHUTDOWN_TIMEOUT_MS, flush = flushConsole, onForcedExit } = options;
|
|
1172
|
+
let bridge = void 0;
|
|
1173
|
+
/** A signal that arrived before the bridge had started. */
|
|
1174
|
+
let early;
|
|
1175
|
+
let stopping = false;
|
|
1176
|
+
let exiting = false;
|
|
1177
|
+
let exitCode = 0;
|
|
1178
|
+
let watchdog;
|
|
1179
|
+
const cancelStart = new AbortController();
|
|
1180
|
+
/** Ends the child processes the graceful stop didn't get to. */
|
|
1181
|
+
const killLeftovers = () => {
|
|
1182
|
+
try {
|
|
1183
|
+
onForcedExit?.();
|
|
1184
|
+
} catch {}
|
|
1185
|
+
};
|
|
1186
|
+
const forceExit = (code) => {
|
|
1187
|
+
killLeftovers();
|
|
1188
|
+
proc.exit(code);
|
|
1189
|
+
};
|
|
1190
|
+
const exit = (code) => {
|
|
1191
|
+
if (exiting) return forceExit(code);
|
|
1192
|
+
exiting = true;
|
|
1193
|
+
flush().catch(() => void 0).then(() => {
|
|
1194
|
+
clearTimeout(watchdog);
|
|
1195
|
+
proc.exit(code);
|
|
1196
|
+
});
|
|
1197
|
+
};
|
|
1198
|
+
const shutdown = (running, reason) => {
|
|
1199
|
+
stopping = true;
|
|
1200
|
+
watchdog = setTimeout(() => {
|
|
1201
|
+
running.log.error(`shutdown did not finish within ${timeoutMs / 1e3} s, exiting`);
|
|
1202
|
+
exiting = true;
|
|
1203
|
+
forceExit(1);
|
|
1204
|
+
}, timeoutMs).unref();
|
|
1205
|
+
running.stop(reason).then(() => exit(exitCode), () => exit(1));
|
|
1206
|
+
};
|
|
1207
|
+
for (const signal of shutdownSignals(proc.platform)) proc.on(signal, () => {
|
|
1208
|
+
if (bridge === void 0) {
|
|
1209
|
+
if (early === void 0) {
|
|
1210
|
+
early = signal;
|
|
1211
|
+
cancelStart.abort();
|
|
1212
|
+
} else {
|
|
1213
|
+
killLeftovers();
|
|
1214
|
+
exit(1);
|
|
1215
|
+
}
|
|
1216
|
+
return;
|
|
1217
|
+
}
|
|
1218
|
+
if (!stopping) return shutdown(bridge, signal);
|
|
1219
|
+
bridge.log.warn(`${signal} again, exiting without waiting`);
|
|
1220
|
+
killLeftovers();
|
|
1221
|
+
exit(1);
|
|
1222
|
+
});
|
|
1223
|
+
bridge = await start(cancelStart.signal);
|
|
1224
|
+
const running = bridge;
|
|
1225
|
+
const crash = (what) => (error) => {
|
|
1226
|
+
running.log.error(`${what}: ${describeError(error)}`);
|
|
1227
|
+
exitCode = 1;
|
|
1228
|
+
if (!stopping) shutdown(running, "crash");
|
|
1229
|
+
};
|
|
1230
|
+
proc.on("uncaughtException", crash("uncaught exception"));
|
|
1231
|
+
proc.on("unhandledRejection", crash("unhandled rejection"));
|
|
1232
|
+
if (early !== void 0) shutdown(running, early);
|
|
1233
|
+
}
|
|
1126
1234
|
// src/domain/errors.ts
|
|
1127
1235
|
/** An expected error with a stable code, for example a bad request. */
|
|
1128
1236
|
var AppError = class extends Error {
|
|
@@ -1139,6 +1247,21 @@ var AppError = class extends Error {
|
|
|
1139
1247
|
function invalidField(field, message) {
|
|
1140
1248
|
return new AppError("INVALID_REQUEST", `${field}: ${message}`, { field });
|
|
1141
1249
|
}
|
|
1250
|
+
/**
|
|
1251
|
+
* A listener can't use its port: something else listens on it (`EADDRINUSE`), or the system
|
|
1252
|
+
* doesn't allow it (`EACCES`, for example a port in a Windows excluded port range). Startup may
|
|
1253
|
+
* ask for another TCP port then (docs/implementation/tcp-capture.md#listening-and-connections).
|
|
1254
|
+
*/
|
|
1255
|
+
var PortUnavailableError = class extends Error {
|
|
1256
|
+
port;
|
|
1257
|
+
reason;
|
|
1258
|
+
name = "PortUnavailableError";
|
|
1259
|
+
constructor(message, port, reason) {
|
|
1260
|
+
super(message);
|
|
1261
|
+
this.port = port;
|
|
1262
|
+
this.reason = reason;
|
|
1263
|
+
}
|
|
1264
|
+
};
|
|
1142
1265
|
// src/adapters/in/http/access.ts
|
|
1143
1266
|
/** Methods that don't change anything. Other methods with a foreign `Origin` are refused. */
|
|
1144
1267
|
const SAFE_METHODS = /* @__PURE__ */ new Set([
|
|
@@ -1184,7 +1307,11 @@ function ownNames(hostnames) {
|
|
|
1184
1307
|
return hostnames.flatMap((name) => [name, name.split(".")[0]]).filter((name) => name !== "");
|
|
1185
1308
|
}
|
|
1186
1309
|
// src/adapters/shared/net/listen.ts
|
|
1187
|
-
/**
|
|
1310
|
+
/**
|
|
1311
|
+
* Thrown when a listener can't start for another reason than its port being unavailable (for
|
|
1312
|
+
* example `EADDRNOTAVAIL`: an address this machine doesn't have). A port that is in use or not
|
|
1313
|
+
* allowed is a `PortUnavailableError`.
|
|
1314
|
+
*/
|
|
1188
1315
|
var ListenError = class extends Error {
|
|
1189
1316
|
code;
|
|
1190
1317
|
name = "ListenError";
|
|
@@ -1193,15 +1320,31 @@ var ListenError = class extends Error {
|
|
|
1193
1320
|
this.code = code;
|
|
1194
1321
|
}
|
|
1195
1322
|
};
|
|
1323
|
+
const UNAVAILABLE = {
|
|
1324
|
+
EADDRINUSE: {
|
|
1325
|
+
reason: "in-use",
|
|
1326
|
+
text: "the port is already in use (is another bridge running?)"
|
|
1327
|
+
},
|
|
1328
|
+
EACCES: {
|
|
1329
|
+
reason: "denied",
|
|
1330
|
+
text: "the system does not allow this port (on Windows it may be in an excluded port range: `netsh interface ipv4 show excludedportrange protocol=tcp`)"
|
|
1331
|
+
}
|
|
1332
|
+
};
|
|
1333
|
+
/** The error `listen` rejects with when `server` fails to listen on `host:port`. */
|
|
1334
|
+
function listenFailure(error, host, port) {
|
|
1335
|
+
const where = `Cannot listen on ${host}:${port}`;
|
|
1336
|
+
const unavailable = error.code === void 0 ? void 0 : UNAVAILABLE[error.code];
|
|
1337
|
+
if (unavailable !== void 0) return new PortUnavailableError(`${where}: ${unavailable.text}`, port, unavailable.reason);
|
|
1338
|
+
return new ListenError(`${where}: ${error.message}`, error.code);
|
|
1339
|
+
}
|
|
1196
1340
|
/**
|
|
1197
1341
|
* Starts `server` on `host:port` and resolves with the bound port (useful with port 0).
|
|
1198
|
-
* Rejects with a `ListenError` that says what went wrong, naming the
|
|
1342
|
+
* Rejects with a `PortUnavailableError` or a `ListenError` that says what went wrong, naming the
|
|
1343
|
+
* port.
|
|
1199
1344
|
*/
|
|
1200
1345
|
async function listen(server, host, port) {
|
|
1201
1346
|
await new Promise((resolve, reject) => {
|
|
1202
|
-
const onError = (error) =>
|
|
1203
|
-
reject(new ListenError(`Cannot listen on ${host}:${port}: ${error.code === "EADDRINUSE" ? "the port is already in use (is another bridge running?)" : error.message}`, error.code));
|
|
1204
|
-
};
|
|
1347
|
+
const onError = (error) => reject(listenFailure(error, host, port));
|
|
1205
1348
|
server.once("error", onError);
|
|
1206
1349
|
server.listen(port, host, () => {
|
|
1207
1350
|
server.off("error", onError);
|
|
@@ -1428,7 +1571,7 @@ var ServiceProxy = class {
|
|
|
1428
1571
|
for (const [name, value] of Object.entries(answer.headers)) if (!HOP_BY_HOP.has(name)) back[name] = value;
|
|
1429
1572
|
res.writeHead(answer.statusCode ?? 502, back);
|
|
1430
1573
|
res.flushHeaders();
|
|
1431
|
-
answer
|
|
1574
|
+
pipeline(answer, res, () => {});
|
|
1432
1575
|
});
|
|
1433
1576
|
upstream.on("error", (error) => {
|
|
1434
1577
|
if (res.headersSent) {
|
|
@@ -1577,8 +1720,8 @@ async function readJson(req) {
|
|
|
1577
1720
|
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1578
1721
|
/** The object schema of a field, behind `optional` or `nullable`; `undefined` for other types. */
|
|
1579
1722
|
function nestedSchema(entry) {
|
|
1580
|
-
if (
|
|
1581
|
-
return
|
|
1723
|
+
if (entry.entries) return { entries: entry.entries };
|
|
1724
|
+
return entry.wrapped && nestedSchema(entry.wrapped);
|
|
1582
1725
|
}
|
|
1583
1726
|
/** Rejects a field the schema doesn't have, naming it with its path (`capture.quietFor`). */
|
|
1584
1727
|
function checkFields(body, schema, path = "") {
|
|
@@ -1593,9 +1736,58 @@ function checkFields(body, schema, path = "") {
|
|
|
1593
1736
|
if (nested && isObject(value)) checkFields(value, nested, `${path}${name}.`);
|
|
1594
1737
|
}
|
|
1595
1738
|
}
|
|
1739
|
+
/** Whether `value` has the schema's type. An object's fields are not looked at. */
|
|
1740
|
+
function hasType(value, schema) {
|
|
1741
|
+
switch (schema.type) {
|
|
1742
|
+
case "string": return typeof value === "string";
|
|
1743
|
+
case "number": return Number.isFinite(value);
|
|
1744
|
+
case "picklist": return schema.options.includes(value);
|
|
1745
|
+
case "array": return Array.isArray(value) && value.every((item) => hasType(item, schema.item));
|
|
1746
|
+
case "union": return schema.options.some((option) => hasType(value, option));
|
|
1747
|
+
case "strict_object": return isObject(value);
|
|
1748
|
+
case "optional": return value === void 0 || hasType(value, schema.wrapped);
|
|
1749
|
+
case "nullable": return value === null || hasType(value, schema.wrapped);
|
|
1750
|
+
default: throw new Error(`request schema type ${schema.type} is not supported`);
|
|
1751
|
+
}
|
|
1752
|
+
}
|
|
1753
|
+
/** What the error says `value` must be, for a schema `hasType` supports. */
|
|
1754
|
+
function typeName(schema, value) {
|
|
1755
|
+
switch (schema.type) {
|
|
1756
|
+
case "optional": return typeName(schema.wrapped, value);
|
|
1757
|
+
case "nullable": return `${typeName(schema.wrapped, value)} or null`;
|
|
1758
|
+
case "union": return schema.options.map((option) => typeName(option, value)).join(" or ");
|
|
1759
|
+
case "array": return `an array of ${schema.item.type}s`;
|
|
1760
|
+
case "strict_object": return "an object";
|
|
1761
|
+
case "picklist": {
|
|
1762
|
+
if (typeof value !== "string") return "a string";
|
|
1763
|
+
const names = schema.options.map(String);
|
|
1764
|
+
return `${names.slice(0, -1).join(", ")} or ${names.at(-1)}`;
|
|
1765
|
+
}
|
|
1766
|
+
default: return `a ${schema.type}`;
|
|
1767
|
+
}
|
|
1768
|
+
}
|
|
1769
|
+
/** Rejects the first field, in the schema's order, that doesn't have its type. */
|
|
1770
|
+
function checkTypes(body, schema, path = "") {
|
|
1771
|
+
for (const [name, entry] of Object.entries(schema.entries)) {
|
|
1772
|
+
const value = body[name];
|
|
1773
|
+
if (!hasType(value, entry)) throw invalidField(`${path}${name}`, `must be ${typeName(entry, value)}`);
|
|
1774
|
+
const nested = nestedSchema(entry);
|
|
1775
|
+
if (nested && isObject(value)) checkTypes(value, nested, `${path}${name}.`);
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
/**
|
|
1779
|
+
* The body with its fields' types checked against `schema`. Only the types: ranges, lengths and
|
|
1780
|
+
* formats are use-case rules, applied by the application.
|
|
1781
|
+
*/
|
|
1782
|
+
function typedBody(schema, body) {
|
|
1783
|
+
if (!isObject(body)) throw invalidField("body", "must be a JSON object");
|
|
1784
|
+
checkTypes(body, schema);
|
|
1785
|
+
return body;
|
|
1786
|
+
}
|
|
1596
1787
|
/**
|
|
1597
1788
|
* The JSON body of a POST/PUT: checks the content type, reads it, and rejects anything but an
|
|
1598
|
-
* object with fields of `schema`. The fields' types are checked by the
|
|
1789
|
+
* object with fields of `schema`. The fields' types are checked by the route (`typedBody`), those
|
|
1790
|
+
* of `PUT /config` by the domain.
|
|
1599
1791
|
*/
|
|
1600
1792
|
async function jsonBody(req, schema) {
|
|
1601
1793
|
requireJson(req);
|
|
@@ -1620,52 +1812,6 @@ function requireNoBody(req) {
|
|
|
1620
1812
|
});
|
|
1621
1813
|
});
|
|
1622
1814
|
}
|
|
1623
|
-
/** `body[name]`, or `undefined` when the body isn't a JSON object. */
|
|
1624
|
-
function field(body, name) {
|
|
1625
|
-
return isObject(body) ? body[name] : void 0;
|
|
1626
|
-
}
|
|
1627
|
-
/** A required string field of a JSON body. */
|
|
1628
|
-
function stringField(body, name) {
|
|
1629
|
-
const value = field(body, name);
|
|
1630
|
-
if (typeof value !== "string") throw invalidField(name, "must be a string");
|
|
1631
|
-
return value;
|
|
1632
|
-
}
|
|
1633
|
-
/** An optional string field of a JSON body. */
|
|
1634
|
-
function optionalStringField(body, name) {
|
|
1635
|
-
const value = field(body, name);
|
|
1636
|
-
if (value !== void 0 && typeof value !== "string") throw invalidField(name, "must be a string");
|
|
1637
|
-
return value;
|
|
1638
|
-
}
|
|
1639
|
-
/** A required number field of a JSON body. Ranges are checked by the use case. */
|
|
1640
|
-
function numberField(body, name) {
|
|
1641
|
-
const value = field(body, name);
|
|
1642
|
-
if (typeof value !== "number" || !Number.isFinite(value)) throw invalidField(name, "must be a number");
|
|
1643
|
-
return value;
|
|
1644
|
-
}
|
|
1645
|
-
/** An optional number field of a JSON body. */
|
|
1646
|
-
function optionalNumberField(body, name) {
|
|
1647
|
-
return field(body, name) === void 0 ? void 0 : numberField(body, name);
|
|
1648
|
-
}
|
|
1649
|
-
/** An optional field of a JSON body that is a JSON object. */
|
|
1650
|
-
function optionalObjectField(body, name) {
|
|
1651
|
-
const value = field(body, name);
|
|
1652
|
-
if (value === void 0) return void 0;
|
|
1653
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) throw invalidField(name, "must be an object");
|
|
1654
|
-
return value;
|
|
1655
|
-
}
|
|
1656
|
-
/** A required field that is a string or an array of strings. */
|
|
1657
|
-
function keysField(body, name) {
|
|
1658
|
-
const value = field(body, name);
|
|
1659
|
-
if (typeof value === "string") return value;
|
|
1660
|
-
if (Array.isArray(value) && value.every((item) => typeof item === "string")) return value;
|
|
1661
|
-
throw invalidField(name, "must be a string or an array of strings");
|
|
1662
|
-
}
|
|
1663
|
-
/** An optional string field of a JSON body that may also be `null`. */
|
|
1664
|
-
function nullableStringField(body, name) {
|
|
1665
|
-
const value = field(body, name);
|
|
1666
|
-
if (value !== void 0 && value !== null && typeof value !== "string") throw invalidField(name, "must be a string or null");
|
|
1667
|
-
return value;
|
|
1668
|
-
}
|
|
1669
1815
|
/** The `X-SR-Speech-Client` header (`CLIENT_HEADER`), `null` if missing or empty. */
|
|
1670
1816
|
function clientHeader(req) {
|
|
1671
1817
|
const raw = req.headers[CLIENT_HEADER];
|
|
@@ -1853,32 +1999,6 @@ function hangUpSignal(req, res) {
|
|
|
1853
1999
|
return controller.signal;
|
|
1854
2000
|
}
|
|
1855
2001
|
// src/adapters/in/http/routes/input-routes.ts
|
|
1856
|
-
/** The `capture` object of an input request, `undefined` without one. */
|
|
1857
|
-
function captureField(body) {
|
|
1858
|
-
const capture = optionalObjectField(body, "capture");
|
|
1859
|
-
if (capture === void 0) return void 0;
|
|
1860
|
-
const ms = (name) => {
|
|
1861
|
-
try {
|
|
1862
|
-
return optionalNumberField(capture, name);
|
|
1863
|
-
} catch {
|
|
1864
|
-
throw invalidField(`capture.${name}`, "must be a number");
|
|
1865
|
-
}
|
|
1866
|
-
};
|
|
1867
|
-
return {
|
|
1868
|
-
quietForMs: ms("quietForMs"),
|
|
1869
|
-
firstWithinMs: ms("firstWithinMs"),
|
|
1870
|
-
timeoutMs: ms("timeoutMs"),
|
|
1871
|
-
settleMs: ms("settleMs")
|
|
1872
|
-
};
|
|
1873
|
-
}
|
|
1874
|
-
function toTarget(field, value) {
|
|
1875
|
-
if (value !== "mcp" && value !== "playwright") throw invalidField(field, "must be mcp or playwright");
|
|
1876
|
-
return value;
|
|
1877
|
-
}
|
|
1878
|
-
function targetField(body, name) {
|
|
1879
|
-
const value = optionalStringField(body, name);
|
|
1880
|
-
return value === void 0 ? void 0 : toTarget(name, value);
|
|
1881
|
-
}
|
|
1882
2002
|
/**
|
|
1883
2003
|
* Runs `task` and answers with `reply`. A client that hangs up first cancels the input that isn't
|
|
1884
2004
|
* sent yet (docs/usage/native-input.md#when-the-client-gives-up).
|
|
@@ -1911,10 +2031,7 @@ function answer(exchange, capture, send, record) {
|
|
|
1911
2031
|
function inputRoutes(router, deps) {
|
|
1912
2032
|
const { input, captures, focus, logger } = deps;
|
|
1913
2033
|
router.add("POST", "/input/focus", { body: FocusRequestSchema }, async ({ req, res, body }) => {
|
|
1914
|
-
const request =
|
|
1915
|
-
target: toTarget("target", stringField(body, "target")),
|
|
1916
|
-
title: optionalStringField(body, "title")
|
|
1917
|
-
};
|
|
2034
|
+
const request = typedBody(FocusRequestSchema, body);
|
|
1918
2035
|
await whileConnected({
|
|
1919
2036
|
req,
|
|
1920
2037
|
res,
|
|
@@ -1924,34 +2041,23 @@ function inputRoutes(router, deps) {
|
|
|
1924
2041
|
signal
|
|
1925
2042
|
}), (focused) => sendJson(res, 200, toFocusedWindowDto(focused)));
|
|
1926
2043
|
}).add("POST", "/input/click", { body: ClickRequestSchema }, async ({ req, res, body }) => {
|
|
1927
|
-
const
|
|
1928
|
-
if (button !== void 0 && button !== "left" && button !== "right" && button !== "middle") throw invalidField("button", "must be left, right or middle");
|
|
1929
|
-
const mouseButton = button;
|
|
1930
|
-
const request = {
|
|
1931
|
-
x: numberField(body, "x"),
|
|
1932
|
-
y: numberField(body, "y"),
|
|
1933
|
-
button: mouseButton
|
|
1934
|
-
};
|
|
2044
|
+
const { capture, ...request } = typedBody(ClickRequestSchema, body);
|
|
1935
2045
|
await answer({
|
|
1936
2046
|
req,
|
|
1937
2047
|
res,
|
|
1938
2048
|
logger
|
|
1939
|
-
},
|
|
2049
|
+
}, capture, (signal) => input.click(request, { signal }), (capture, signal) => captures.click({
|
|
1940
2050
|
...request,
|
|
1941
2051
|
capture,
|
|
1942
2052
|
signal
|
|
1943
2053
|
}));
|
|
1944
2054
|
}).add("POST", "/input/keys", { body: KeysRequestSchema }, async ({ req, res, body }) => {
|
|
1945
|
-
const request =
|
|
1946
|
-
keys: keysField(body, "keys"),
|
|
1947
|
-
delayMs: optionalNumberField(body, "delayMs"),
|
|
1948
|
-
expectedTarget: targetField(body, "expectedTarget")
|
|
1949
|
-
};
|
|
2055
|
+
const { capture, ...request } = typedBody(KeysRequestSchema, body);
|
|
1950
2056
|
await answer({
|
|
1951
2057
|
req,
|
|
1952
2058
|
res,
|
|
1953
2059
|
logger
|
|
1954
|
-
},
|
|
2060
|
+
}, capture, (signal) => input.pressKeys(request, { signal }), (capture, signal) => captures.pressKeys({
|
|
1955
2061
|
...request,
|
|
1956
2062
|
capture,
|
|
1957
2063
|
signal
|
|
@@ -1993,8 +2099,7 @@ function toSessionListDto({ sessions, currentId, outsideEntries }) {
|
|
|
1993
2099
|
/** `POST /sessions`, `POST /sessions/end`, `DELETE /sessions`, `GET /sessions` (docs/usage/http-api.md#endpoints). */
|
|
1994
2100
|
function sessionRoutes(router, { sessions }) {
|
|
1995
2101
|
router.add("POST", "/sessions", { body: StartSessionRequestSchema }, ({ req, res, body }) => {
|
|
1996
|
-
const name =
|
|
1997
|
-
const run = nullableStringField(body, "run");
|
|
2102
|
+
const { name, run } = typedBody(StartSessionRequestSchema, body);
|
|
1998
2103
|
const client = clientHeader(req);
|
|
1999
2104
|
sendJson(res, 201, toStartSessionResponseDto(sessions.start({
|
|
2000
2105
|
name,
|
|
@@ -2069,7 +2174,7 @@ function speechRoutes(router, deps) {
|
|
|
2069
2174
|
speech.clear(sessionParam(url));
|
|
2070
2175
|
sendNoContent(res);
|
|
2071
2176
|
}).add("POST", "/markers", { body: MarkerRequestSchema }, ({ res, body }) => {
|
|
2072
|
-
const label =
|
|
2177
|
+
const { label } = typedBody(MarkerRequestSchema, body);
|
|
2073
2178
|
sendJson(res, 201, toSpeechEntryDto(speech.addMarker(label)));
|
|
2074
2179
|
}).add("GET", "/markers/latest", { query: ["label", "session"] }, ({ res, url }) => {
|
|
2075
2180
|
const label = stringParam(url, "label");
|
|
@@ -2121,7 +2226,8 @@ function toServiceStatusDto(service) {
|
|
|
2121
2226
|
version: service.version,
|
|
2122
2227
|
port: service.port,
|
|
2123
2228
|
restarts: service.restarts,
|
|
2124
|
-
exitCode: service.exitCode
|
|
2229
|
+
exitCode: service.exitCode,
|
|
2230
|
+
lastError: service.lastError
|
|
2125
2231
|
};
|
|
2126
2232
|
}
|
|
2127
2233
|
function toInputAvailabilityDto(availability) {
|
|
@@ -2156,7 +2262,8 @@ function toStatusDto({ bridge, tcp, buffer, services, session, input }) {
|
|
|
2156
2262
|
id,
|
|
2157
2263
|
voice,
|
|
2158
2264
|
connectedAt: connectedAt.toISOString()
|
|
2159
|
-
}))
|
|
2265
|
+
})),
|
|
2266
|
+
lastSpeechAt: tcp.lastSpeechAt?.toISOString() ?? null
|
|
2160
2267
|
},
|
|
2161
2268
|
buffer: {
|
|
2162
2269
|
size: buffer.size,
|
|
@@ -2377,43 +2484,120 @@ function parseUrl(target) {
|
|
|
2377
2484
|
throw new AppError("INVALID_REQUEST", "The request URL is not valid");
|
|
2378
2485
|
}
|
|
2379
2486
|
}
|
|
2380
|
-
// src/adapters/in/
|
|
2381
|
-
|
|
2382
|
-
const
|
|
2383
|
-
|
|
2487
|
+
// src/adapters/in/http/ui-mount.ts
|
|
2488
|
+
/** The environment variable the UI's BFF reads the bridge's address from. */
|
|
2489
|
+
const BRIDGE_API_URL_ENV = "SR_BRIDGE_API_URL";
|
|
2490
|
+
/** The header adapter-node reads the request's protocol from (`PROTOCOL_HEADER`). */
|
|
2491
|
+
const PROTOCOL_HEADER = "x-sr-bridge-protocol";
|
|
2384
2492
|
/**
|
|
2385
|
-
*
|
|
2386
|
-
* (docs/
|
|
2387
|
-
*
|
|
2388
|
-
* decoded correctly.
|
|
2493
|
+
* The header that tells the UI its page is opened from the bridge's own machine, where the screen
|
|
2494
|
+
* reader would read the live log and feed it back (docs/usage/web-ui.md#accessibility-of-the-ui-itself).
|
|
2495
|
+
* Set (`1`) or removed on every request, so a client can't send it.
|
|
2389
2496
|
*/
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2497
|
+
const LOCAL_HEADER = "x-sr-bridge-local";
|
|
2498
|
+
/**
|
|
2499
|
+
* Where the UI's server code finds the bridge log (`packages/ui/src/lib/server/log.ts` reads it):
|
|
2500
|
+
* a `Symbol.for` key on `globalThis`, because the bridge and the UI don't import each other. Its
|
|
2501
|
+
* lines then get the `[web-ui]` prefix, go to the log file and never block on the console.
|
|
2502
|
+
*/
|
|
2503
|
+
const UI_LOGGER_KEY = Symbol.for("screenreader-speech-capture.ui-logger");
|
|
2504
|
+
/**
|
|
2505
|
+
* The UI shipped in `dir` (`handler.js` of the `adapter-node` build). `undefined` when there is
|
|
2506
|
+
* none: the bridge runs from source, or the package was built without the UI.
|
|
2507
|
+
*/
|
|
2508
|
+
function createUiMount(dir, logger) {
|
|
2509
|
+
const file = new URL("handler.js", dir);
|
|
2510
|
+
if (!existsSync(file)) {
|
|
2511
|
+
logger.debug(`no web UI at ${file.pathname}`);
|
|
2512
|
+
return;
|
|
2513
|
+
}
|
|
2514
|
+
let settle;
|
|
2515
|
+
const loaded = new Promise((resolve, reject) => {
|
|
2516
|
+
settle = {
|
|
2517
|
+
resolve,
|
|
2518
|
+
reject
|
|
2519
|
+
};
|
|
2520
|
+
});
|
|
2521
|
+
loaded.catch(() => void 0);
|
|
2522
|
+
return {
|
|
2523
|
+
handler: async (req, res) => {
|
|
2524
|
+
if (new URL(req.url ?? "/", "http://localhost").pathname === "/") {
|
|
2525
|
+
res.writeHead(302, { location: "/ui/" }).end();
|
|
2526
|
+
return;
|
|
2527
|
+
}
|
|
2528
|
+
let handler;
|
|
2529
|
+
try {
|
|
2530
|
+
handler = await loaded;
|
|
2531
|
+
} catch {
|
|
2532
|
+
throw new AppError("SERVICE_UNAVAILABLE", "The web UI failed to start");
|
|
2533
|
+
}
|
|
2534
|
+
req.headers[PROTOCOL_HEADER] = "http";
|
|
2535
|
+
if (isOwnAddress(req.socket?.remoteAddress)) req.headers[LOCAL_HEADER] = "1";
|
|
2536
|
+
else delete req.headers[LOCAL_HEADER];
|
|
2537
|
+
handler(req, res, () => {
|
|
2538
|
+
res.statusCode = 404;
|
|
2539
|
+
res.end();
|
|
2540
|
+
});
|
|
2541
|
+
},
|
|
2542
|
+
async mount(apiUrl) {
|
|
2543
|
+
try {
|
|
2544
|
+
process.env[BRIDGE_API_URL_ENV] = apiUrl;
|
|
2545
|
+
process.env.PROTOCOL_HEADER = PROTOCOL_HEADER;
|
|
2546
|
+
globalThis[UI_LOGGER_KEY] = logger;
|
|
2547
|
+
const module = await import(file.href);
|
|
2548
|
+
if (typeof module.handler !== "function") throw new Error("handler.js has no `handler`");
|
|
2549
|
+
settle.resolve(module.handler);
|
|
2550
|
+
logger.debug(`web UI loaded from ${file.pathname}`);
|
|
2551
|
+
} catch (error) {
|
|
2552
|
+
logger.error(`web UI failed to start: ${error instanceof Error ? error.message : String(error)}`);
|
|
2553
|
+
settle.reject(error);
|
|
2554
|
+
}
|
|
2555
|
+
}
|
|
2556
|
+
};
|
|
2557
|
+
}
|
|
2558
|
+
/**
|
|
2559
|
+
* Where the BFF reaches the bridge's HTTP API: over loopback, whatever address it listens on.
|
|
2560
|
+
*/
|
|
2561
|
+
function bridgeApiUrl(host, port) {
|
|
2562
|
+
return `http://${hostPort(host === "::" ? "::1" : isWildcard(host) ? "127.0.0.1" : host, port)}`;
|
|
2563
|
+
}
|
|
2564
|
+
// src/adapters/in/tcp/text-to-socket-parser.ts
|
|
2565
|
+
const LF = 10;
|
|
2566
|
+
const CR = 13;
|
|
2567
|
+
const HEADER = /^voice=(\S.*)$/;
|
|
2568
|
+
/**
|
|
2569
|
+
* Parser for the `text-to-socket` wire format
|
|
2570
|
+
* (docs/implementation/tcp-capture.md#framing-and-decoding), one instance per connection. Bytes are
|
|
2571
|
+
* split at `\n` *before* decoding, so a multi-byte character split across two TCP packets is
|
|
2572
|
+
* decoded correctly.
|
|
2573
|
+
*/
|
|
2574
|
+
var TextToSocketParser = class {
|
|
2575
|
+
maxLineBytes;
|
|
2576
|
+
events;
|
|
2577
|
+
decoder;
|
|
2578
|
+
pending = [];
|
|
2579
|
+
pendingBytes = 0;
|
|
2580
|
+
/** After a cut: drop bytes until the next `\n`. */
|
|
2581
|
+
discarding = false;
|
|
2582
|
+
firstLine = true;
|
|
2583
|
+
constructor(encoding, maxLineBytes, events) {
|
|
2584
|
+
this.maxLineBytes = maxLineBytes;
|
|
2585
|
+
this.events = events;
|
|
2586
|
+
this.decoder = new TextDecoder$1(encoding);
|
|
2587
|
+
}
|
|
2588
|
+
push(chunk) {
|
|
2589
|
+
let start = 0;
|
|
2590
|
+
while (start < chunk.length) {
|
|
2591
|
+
const newline = chunk.indexOf(LF, start);
|
|
2592
|
+
const end = newline === -1 ? chunk.length : newline;
|
|
2593
|
+
this.append(chunk.subarray(start, end));
|
|
2594
|
+
if (newline === -1) return;
|
|
2595
|
+
this.completeLine();
|
|
2596
|
+
start = newline + 1;
|
|
2597
|
+
}
|
|
2598
|
+
}
|
|
2599
|
+
/** The connection closed: text still in the buffer becomes a last line. */
|
|
2600
|
+
end() {
|
|
2417
2601
|
if (!this.discarding && this.pendingBytes > 0) this.emit();
|
|
2418
2602
|
this.pending = [];
|
|
2419
2603
|
this.pendingBytes = 0;
|
|
@@ -2569,42 +2753,62 @@ var FsConfigStore = class {
|
|
|
2569
2753
|
constructor(location) {
|
|
2570
2754
|
this.location = location;
|
|
2571
2755
|
}
|
|
2572
|
-
async load() {
|
|
2756
|
+
async load(onWarning) {
|
|
2573
2757
|
const text = await this.read(this.location);
|
|
2574
2758
|
if (text === void 0) return void 0;
|
|
2575
2759
|
try {
|
|
2576
2760
|
return parseJson(text);
|
|
2577
2761
|
} catch (error) {
|
|
2578
2762
|
const backup = await this.readBackup();
|
|
2579
|
-
if (backup !== void 0)
|
|
2580
|
-
|
|
2763
|
+
if (isBlank(text) && backup !== void 0) {
|
|
2764
|
+
onWarning?.(`The config file ${this.location} is empty: using the previous version, ${this.location}.bak`);
|
|
2765
|
+
return backup;
|
|
2766
|
+
}
|
|
2767
|
+
const hint = backup === void 0 ? "" : `. Fix it, or copy the previous version, ${this.location}.bak, over it`;
|
|
2768
|
+
throw new Error(`The config file ${this.location} is not valid JSON: ${error.message}${hint}`, { cause: error });
|
|
2581
2769
|
}
|
|
2582
2770
|
}
|
|
2583
2771
|
/**
|
|
2584
2772
|
* Writes a temporary file, flushes it to disk and renames it, so a crash never leaves half a
|
|
2585
|
-
* file. The previous file is kept
|
|
2773
|
+
* file. The previous file is kept (`keepPrevious`).
|
|
2586
2774
|
*/
|
|
2587
|
-
async save(file) {
|
|
2588
|
-
await fs.mkdir(path.dirname(this.location), { recursive: true });
|
|
2775
|
+
async save(file, onWarning) {
|
|
2776
|
+
await fs$1.mkdir(path.dirname(this.location), { recursive: true });
|
|
2589
2777
|
const temporary = `${this.location}.${process.pid}.tmp`;
|
|
2590
2778
|
try {
|
|
2591
|
-
const handle = await fs.open(temporary, "w");
|
|
2779
|
+
const handle = await fs$1.open(temporary, "w");
|
|
2592
2780
|
try {
|
|
2593
2781
|
await handle.writeFile(`${JSON.stringify(file, null, 2)}\n`, "utf8");
|
|
2594
2782
|
await handle.sync();
|
|
2595
2783
|
} finally {
|
|
2596
2784
|
await handle.close();
|
|
2597
2785
|
}
|
|
2598
|
-
|
|
2599
|
-
await fs.rename(temporary, this.location);
|
|
2786
|
+
await this.keepPrevious(onWarning);
|
|
2787
|
+
await fs$1.rename(temporary, this.location);
|
|
2600
2788
|
} catch (error) {
|
|
2601
|
-
await fs.rm(temporary, { force: true });
|
|
2789
|
+
await fs$1.rm(temporary, { force: true });
|
|
2602
2790
|
throw error;
|
|
2603
2791
|
}
|
|
2604
2792
|
}
|
|
2793
|
+
/**
|
|
2794
|
+
* Keeps the file a save is about to replace: one that parses as `config.json.bak`, for `load`
|
|
2795
|
+
* to fall back on, so a broken one never overwrites a good one. A broken one (edited while the
|
|
2796
|
+
* bridge ran) as `config.json.broken`. A blank one holds nothing to keep.
|
|
2797
|
+
*/
|
|
2798
|
+
async keepPrevious(onWarning) {
|
|
2799
|
+
const text = await this.read(this.location);
|
|
2800
|
+
if (text === void 0 || isBlank(text)) return;
|
|
2801
|
+
if (isJson(text)) {
|
|
2802
|
+
await fs$1.copyFile(this.location, `${this.location}.bak`);
|
|
2803
|
+
return;
|
|
2804
|
+
}
|
|
2805
|
+
const kept = `${this.location}.broken`;
|
|
2806
|
+
await fs$1.copyFile(this.location, kept);
|
|
2807
|
+
onWarning?.(`The config file ${this.location} was not valid JSON: kept as ${kept} before saving over it`);
|
|
2808
|
+
}
|
|
2605
2809
|
async read(file) {
|
|
2606
2810
|
try {
|
|
2607
|
-
return await fs.readFile(file, "utf8");
|
|
2811
|
+
return await fs$1.readFile(file, "utf8");
|
|
2608
2812
|
} catch (error) {
|
|
2609
2813
|
if (error.code === "ENOENT") return void 0;
|
|
2610
2814
|
throw new Error(`Cannot read the config file ${file}: ${error.message}`, { cause: error });
|
|
@@ -2618,21 +2822,133 @@ var FsConfigStore = class {
|
|
|
2618
2822
|
return;
|
|
2619
2823
|
}
|
|
2620
2824
|
}
|
|
2621
|
-
async isValid(file) {
|
|
2622
|
-
try {
|
|
2623
|
-
const text = await this.read(file);
|
|
2624
|
-
if (text === void 0) return false;
|
|
2625
|
-
parseJson(text);
|
|
2626
|
-
return true;
|
|
2627
|
-
} catch {
|
|
2628
|
-
return false;
|
|
2629
|
-
}
|
|
2630
|
-
}
|
|
2631
2825
|
};
|
|
2632
2826
|
/** `JSON.parse` that accepts a leading byte order mark (Notepad and PowerShell write one). */
|
|
2633
2827
|
function parseJson(text) {
|
|
2634
2828
|
return JSON.parse(text.replace(/^\uFEFF/, ""));
|
|
2635
2829
|
}
|
|
2830
|
+
function isJson(text) {
|
|
2831
|
+
try {
|
|
2832
|
+
parseJson(text);
|
|
2833
|
+
return true;
|
|
2834
|
+
} catch {
|
|
2835
|
+
return false;
|
|
2836
|
+
}
|
|
2837
|
+
}
|
|
2838
|
+
/** Empty, or only white space and NUL bytes: what a crash can leave of a file. */
|
|
2839
|
+
function isBlank(text) {
|
|
2840
|
+
return [...text].every((char) => char === "\0" || char.trim() === "");
|
|
2841
|
+
}
|
|
2842
|
+
// src/adapters/out/log/async-console.ts
|
|
2843
|
+
const MAX_PENDING_BYTES = 1048576;
|
|
2844
|
+
const FLUSH_TIMEOUT_MS = 1e3;
|
|
2845
|
+
/**
|
|
2846
|
+
* Hands text to `channel` without ever blocking. While the console is stuck, text piles up to
|
|
2847
|
+
* `maxPendingBytes`, then new lines are dropped (the log file keeps everything). When the console
|
|
2848
|
+
* takes text again, a line says how many were dropped.
|
|
2849
|
+
*/
|
|
2850
|
+
function createAsyncConsole(options) {
|
|
2851
|
+
const { channel, fallback, maxPendingBytes = MAX_PENDING_BYTES } = options;
|
|
2852
|
+
let pending = 0;
|
|
2853
|
+
let dropped = 0;
|
|
2854
|
+
let failed = false;
|
|
2855
|
+
let nextFlush = 0;
|
|
2856
|
+
const waiting = /* @__PURE__ */ new Map();
|
|
2857
|
+
channel.onMessage((message) => {
|
|
2858
|
+
if ("written" in message) {
|
|
2859
|
+
pending = Math.max(0, pending - message.written);
|
|
2860
|
+
return;
|
|
2861
|
+
}
|
|
2862
|
+
waiting.get(message.flushed)?.();
|
|
2863
|
+
});
|
|
2864
|
+
channel.onFailure(() => {
|
|
2865
|
+
failed = true;
|
|
2866
|
+
for (const done of waiting.values()) done();
|
|
2867
|
+
});
|
|
2868
|
+
return {
|
|
2869
|
+
write(text) {
|
|
2870
|
+
if (failed) return fallback(text);
|
|
2871
|
+
if (pending >= maxPendingBytes) {
|
|
2872
|
+
dropped += 1;
|
|
2873
|
+
return;
|
|
2874
|
+
}
|
|
2875
|
+
if (dropped > 0) {
|
|
2876
|
+
const notice = `console output was blocked, ${dropped} lines dropped (see the log file)\n`;
|
|
2877
|
+
dropped = 0;
|
|
2878
|
+
pending += Buffer.byteLength(notice);
|
|
2879
|
+
channel.post(notice);
|
|
2880
|
+
}
|
|
2881
|
+
pending += Buffer.byteLength(text);
|
|
2882
|
+
channel.post(text);
|
|
2883
|
+
},
|
|
2884
|
+
flush(timeoutMs = FLUSH_TIMEOUT_MS) {
|
|
2885
|
+
if (failed) return Promise.resolve();
|
|
2886
|
+
return new Promise((resolve) => {
|
|
2887
|
+
const id = nextFlush++;
|
|
2888
|
+
const finish = () => {
|
|
2889
|
+
clearTimeout(timer);
|
|
2890
|
+
waiting.delete(id);
|
|
2891
|
+
resolve();
|
|
2892
|
+
};
|
|
2893
|
+
const timer = setTimeout(finish, timeoutMs);
|
|
2894
|
+
waiting.set(id, finish);
|
|
2895
|
+
channel.requestFlush(id);
|
|
2896
|
+
});
|
|
2897
|
+
}
|
|
2898
|
+
};
|
|
2899
|
+
}
|
|
2900
|
+
const WORKER_SOURCE = `
|
|
2901
|
+
const { parentPort, workerData } = require('node:worker_threads');
|
|
2902
|
+
const tty = require('node:tty');
|
|
2903
|
+
const stream = new tty.WriteStream(workerData.fd);
|
|
2904
|
+
stream.on('error', () => {});
|
|
2905
|
+
parentPort.on('message', (message) => {
|
|
2906
|
+
if (message.flush !== undefined) {
|
|
2907
|
+
stream.write('', () => parentPort.postMessage({ flushed: message.flush }));
|
|
2908
|
+
return;
|
|
2909
|
+
}
|
|
2910
|
+
const bytes = Buffer.byteLength(message.text);
|
|
2911
|
+
stream.write(message.text, () => parentPort.postMessage({ written: bytes }));
|
|
2912
|
+
});
|
|
2913
|
+
`;
|
|
2914
|
+
function workerChannel(fd) {
|
|
2915
|
+
const worker = new Worker(WORKER_SOURCE, {
|
|
2916
|
+
eval: true,
|
|
2917
|
+
workerData: { fd }
|
|
2918
|
+
});
|
|
2919
|
+
worker.unref();
|
|
2920
|
+
return {
|
|
2921
|
+
post: (text) => worker.postMessage({ text }),
|
|
2922
|
+
requestFlush: (id) => worker.postMessage({ flush: id }),
|
|
2923
|
+
onMessage: (listener) => worker.on("message", listener),
|
|
2924
|
+
onFailure: (listener) => {
|
|
2925
|
+
worker.on("error", listener);
|
|
2926
|
+
worker.on("exit", listener);
|
|
2927
|
+
}
|
|
2928
|
+
};
|
|
2929
|
+
}
|
|
2930
|
+
let console_;
|
|
2931
|
+
/**
|
|
2932
|
+
* A writer for stdout that can't block the bridge, or `undefined` when stdout is not a terminal
|
|
2933
|
+
* (a pipe or file has no selection mode, and `process.stdout` is fine there).
|
|
2934
|
+
*/
|
|
2935
|
+
function terminalWriter(stream = process.stdout) {
|
|
2936
|
+
if (stream.isTTY !== true) return void 0;
|
|
2937
|
+
try {
|
|
2938
|
+
console_ ??= createAsyncConsole({
|
|
2939
|
+
channel: workerChannel(1),
|
|
2940
|
+
fallback: (text) => void stream.write(text)
|
|
2941
|
+
});
|
|
2942
|
+
} catch {
|
|
2943
|
+
return;
|
|
2944
|
+
}
|
|
2945
|
+
const writer = console_;
|
|
2946
|
+
return (text) => writer.write(text);
|
|
2947
|
+
}
|
|
2948
|
+
/** Waits (briefly) until the terminal writer has written everything. */
|
|
2949
|
+
function flushTerminal() {
|
|
2950
|
+
return console_?.flush() ?? Promise.resolve();
|
|
2951
|
+
}
|
|
2636
2952
|
// src/adapters/out/memory/in-process-event-bus.ts
|
|
2637
2953
|
/** Synchronous in-process event bus. A failing listener doesn't stop the others. */
|
|
2638
2954
|
var InProcessEventBus = class {
|
|
@@ -2714,37 +3030,217 @@ function defaultPlaywrightDir(platform = process.platform, env = process.env, ho
|
|
|
2714
3030
|
home
|
|
2715
3031
|
});
|
|
2716
3032
|
}
|
|
2717
|
-
// src/
|
|
2718
|
-
/**
|
|
2719
|
-
|
|
2720
|
-
|
|
2721
|
-
|
|
2722
|
-
|
|
2723
|
-
|
|
2724
|
-
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
}
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
3033
|
+
// src/adapters/out/process/process-tree.ts
|
|
3034
|
+
/** How long the process group gets after `SIGTERM` before `SIGKILL` (not on Windows). */
|
|
3035
|
+
const TERM_GRACE_MS = 3e3;
|
|
3036
|
+
/**
|
|
3037
|
+
* Spawn options for a child whose whole tree `killTree` can end. On POSIX the child leads its own
|
|
3038
|
+
* process group. On Windows that isn't needed (`taskkill /T` walks the tree), and `detached`
|
|
3039
|
+
* there would open a new console window.
|
|
3040
|
+
*/
|
|
3041
|
+
const treeSpawnOptions = {
|
|
3042
|
+
detached: process.platform !== "win32",
|
|
3043
|
+
windowsHide: true
|
|
3044
|
+
};
|
|
3045
|
+
function hasExited(child) {
|
|
3046
|
+
return child.exitCode !== null || child.signalCode !== null;
|
|
3047
|
+
}
|
|
3048
|
+
function killGroup(pid, signal) {
|
|
3049
|
+
try {
|
|
3050
|
+
process.kill(-pid, signal);
|
|
3051
|
+
} catch {}
|
|
3052
|
+
}
|
|
3053
|
+
/** Resolves after `ms`, or when `promise` settles, whichever comes first. */
|
|
3054
|
+
async function within(promise, ms) {
|
|
3055
|
+
let timer;
|
|
3056
|
+
await Promise.race([promise.catch(() => void 0), new Promise((resolve) => timer = setTimeout(resolve, ms))]);
|
|
3057
|
+
clearTimeout(timer);
|
|
3058
|
+
}
|
|
3059
|
+
const exec = (file, args, timeoutMs) => new Promise((resolve) => {
|
|
3060
|
+
execFile(file, [...args], {
|
|
3061
|
+
windowsHide: true,
|
|
3062
|
+
timeout: timeoutMs,
|
|
3063
|
+
killSignal: "SIGKILL"
|
|
3064
|
+
}, (error, stdout) => resolve({
|
|
3065
|
+
ok: error === null,
|
|
3066
|
+
stdout: String(stdout)
|
|
3067
|
+
}));
|
|
3068
|
+
});
|
|
3069
|
+
const TOOL_TIMEOUT_MS = 5e3;
|
|
3070
|
+
/** Trees that may still have processes, for `killAllTreesNow`. */
|
|
3071
|
+
const trees = /* @__PURE__ */ new Set();
|
|
3072
|
+
/**
|
|
3073
|
+
* Remembers a child spawned with `treeSpawnOptions`, so `killAllTreesNow` can end it when the
|
|
3074
|
+
* bridge has to exit without stopping gracefully. `killTree` forgets it; so does `releaseTree`.
|
|
3075
|
+
*/
|
|
3076
|
+
function trackTree(child) {
|
|
3077
|
+
trees.add(child);
|
|
3078
|
+
}
|
|
3079
|
+
/** Forgets a child that ended on its own and left nothing behind to kill. */
|
|
3080
|
+
function releaseTree(child) {
|
|
3081
|
+
trees.delete(child);
|
|
3082
|
+
}
|
|
3083
|
+
/**
|
|
3084
|
+
* Ends every tracked tree at once and synchronously, without waiting for anything. For a forced
|
|
3085
|
+
* exit (watchdog, second Ctrl+C), when the graceful `killTree` has no time left: exiting without
|
|
3086
|
+
* this leaves the browsers of the Playwright server behind.
|
|
3087
|
+
*/
|
|
3088
|
+
function killAllTreesNow(platform = process.platform) {
|
|
3089
|
+
for (const child of trees) {
|
|
3090
|
+
const { pid } = child;
|
|
3091
|
+
if (pid === void 0) continue;
|
|
3092
|
+
if (platform === "win32") spawnSync("taskkill", [
|
|
3093
|
+
"/T",
|
|
3094
|
+
"/F",
|
|
3095
|
+
"/PID",
|
|
3096
|
+
String(pid)
|
|
3097
|
+
], {
|
|
3098
|
+
windowsHide: true,
|
|
3099
|
+
stdio: "ignore",
|
|
3100
|
+
timeout: TOOL_TIMEOUT_MS
|
|
3101
|
+
});
|
|
3102
|
+
else killGroup(pid, "SIGKILL");
|
|
3103
|
+
}
|
|
3104
|
+
trees.clear();
|
|
3105
|
+
}
|
|
3106
|
+
/**
|
|
3107
|
+
* Kills `child` and every process it started (docs/usage/operations.md#shutdown). On Windows,
|
|
3108
|
+
* `taskkill /T /F` limited to a few seconds (killing a process there doesn't kill its children;
|
|
3109
|
+
* the orphans of a child that already died are not hunted down, see
|
|
3110
|
+
* docs/implementation/decisions.md#child-process-trees-are-killed-by-the-bridge-not-the-os).
|
|
3111
|
+
* Elsewhere `SIGTERM` to the process group, then `SIGKILL` to whatever is left. Resolves
|
|
3112
|
+
* once `child` has exited, or after a deadline if it can't be killed. Never rejects.
|
|
3113
|
+
* `child` must have been spawned with `treeSpawnOptions`.
|
|
3114
|
+
*/
|
|
3115
|
+
async function killTree(child, options = {}) {
|
|
3116
|
+
const { platform = process.platform, toolTimeoutMs = TOOL_TIMEOUT_MS } = options;
|
|
3117
|
+
const { exitTimeoutMs = TOOL_TIMEOUT_MS, exec: run = exec } = options;
|
|
3118
|
+
const { pid } = child;
|
|
3119
|
+
try {
|
|
3120
|
+
if (pid === void 0) return;
|
|
3121
|
+
const exited = hasExited(child) ? Promise.resolve() : once(child, "exit");
|
|
3122
|
+
if (platform === "win32") {
|
|
3123
|
+
if (!hasExited(child)) await run("taskkill", [
|
|
3124
|
+
"/T",
|
|
3125
|
+
"/F",
|
|
3126
|
+
"/PID",
|
|
3127
|
+
String(pid)
|
|
3128
|
+
], toolTimeoutMs);
|
|
3129
|
+
await within(exited, exitTimeoutMs);
|
|
3130
|
+
return;
|
|
3131
|
+
}
|
|
3132
|
+
killGroup(pid, "SIGTERM");
|
|
3133
|
+
await within(exited, TERM_GRACE_MS);
|
|
3134
|
+
killGroup(pid, "SIGKILL");
|
|
3135
|
+
await within(exited, exitTimeoutMs);
|
|
3136
|
+
} finally {
|
|
3137
|
+
trees.delete(child);
|
|
3138
|
+
}
|
|
3139
|
+
}
|
|
3140
|
+
/** Writes each line of the child's stdout as `info` and of its stderr as `warn`. */
|
|
3141
|
+
function pipeLines(child, output) {
|
|
3142
|
+
if (child.stdout) readline.createInterface({
|
|
3143
|
+
input: child.stdout,
|
|
3144
|
+
crlfDelay: Infinity
|
|
3145
|
+
}).on("line", (line) => output.info(line));
|
|
3146
|
+
if (child.stderr) readline.createInterface({
|
|
3147
|
+
input: child.stderr,
|
|
3148
|
+
crlfDelay: Infinity
|
|
3149
|
+
}).on("line", (line) => output.warn(line));
|
|
3150
|
+
}
|
|
3151
|
+
// src/application/shared/abort.ts
|
|
3152
|
+
/** The error an aborted signal ends a pending request with: its reason, if that is an error. */
|
|
3153
|
+
function abortReason(signal) {
|
|
3154
|
+
const reason = signal.reason;
|
|
3155
|
+
return reason instanceof Error ? reason : /* @__PURE__ */ new Error("The request was aborted");
|
|
3156
|
+
}
|
|
3157
|
+
/**
|
|
3158
|
+
* The reason of the bridge's shutdown signal, which pending requests (waits, captures, input) end
|
|
3159
|
+
* with.
|
|
3160
|
+
*/
|
|
3161
|
+
const shuttingDown = () => new AppError("SERVICE_UNAVAILABLE", "The bridge is shutting down");
|
|
3162
|
+
/**
|
|
3163
|
+
* The signal of one request: aborts with the reason of the first of `signals` that aborts, or at
|
|
3164
|
+
* once if one already has (then the first of them in the list). `undefined` ones are skipped.
|
|
3165
|
+
* `dispose` takes the listeners off them again: call it when the request ends, or a long-lived
|
|
3166
|
+
* signal such as the shutdown's keeps them. Not `AbortSignal.any`, which keeps memory for every
|
|
3167
|
+
* signal made of a long-lived one (docs/implementation/decisions.md#one-shutdown-signal).
|
|
3168
|
+
*/
|
|
3169
|
+
function linkSignals(...signals) {
|
|
3170
|
+
const controller = new AbortController();
|
|
3171
|
+
const removers = [];
|
|
3172
|
+
for (const source of signals) {
|
|
3173
|
+
if (source === void 0) continue;
|
|
3174
|
+
const abort = () => controller.abort(abortReason(source));
|
|
3175
|
+
if (source.aborted) {
|
|
3176
|
+
abort();
|
|
3177
|
+
break;
|
|
3178
|
+
}
|
|
3179
|
+
source.addEventListener("abort", abort, { once: true });
|
|
3180
|
+
removers.push(() => source.removeEventListener("abort", abort));
|
|
3181
|
+
}
|
|
3182
|
+
return {
|
|
3183
|
+
signal: controller.signal,
|
|
3184
|
+
dispose: () => {
|
|
3185
|
+
for (const remove of removers) remove();
|
|
3186
|
+
}
|
|
3187
|
+
};
|
|
3188
|
+
}
|
|
3189
|
+
// src/application/services/bridge-lifecycle-service.ts
|
|
3190
|
+
/**
|
|
3191
|
+
* The bridge's state from `starting` over `ready` to `stopping`, and the order of startup and
|
|
3192
|
+
* shutdown.
|
|
3193
|
+
*/
|
|
3194
|
+
var BridgeLifecycleService = class {
|
|
3195
|
+
deps;
|
|
3196
|
+
stopping;
|
|
3197
|
+
constructor(deps) {
|
|
3198
|
+
this.deps = deps;
|
|
3199
|
+
}
|
|
3200
|
+
async start() {
|
|
3201
|
+
const ports = await this.listen();
|
|
3202
|
+
await this.deps.httpListening(ports.http);
|
|
3203
|
+
this.deps.services.startEnabled().then(() => {
|
|
3204
|
+
if (this.stopping !== void 0) return;
|
|
3205
|
+
this.deps.state.setState("ready");
|
|
3206
|
+
this.deps.logger.info(this.deps.readyMessage(ports));
|
|
3207
|
+
});
|
|
3208
|
+
return ports;
|
|
3209
|
+
}
|
|
3210
|
+
stop(reason) {
|
|
3211
|
+
this.stopping ??= this.shutdown(reason);
|
|
3212
|
+
return this.stopping;
|
|
3213
|
+
}
|
|
3214
|
+
/** TCP first, so no speech is lost while the rest starts. It stops again if HTTP fails. */
|
|
3215
|
+
async listen() {
|
|
3216
|
+
const { tcp, http } = this.deps;
|
|
3217
|
+
const tcpPort = await tcp.start();
|
|
3218
|
+
try {
|
|
3219
|
+
return {
|
|
3220
|
+
tcp: tcpPort,
|
|
3221
|
+
http: await http.start()
|
|
3222
|
+
};
|
|
3223
|
+
} catch (error) {
|
|
3224
|
+
await tcp.stop();
|
|
3225
|
+
throw error;
|
|
3226
|
+
}
|
|
3227
|
+
}
|
|
3228
|
+
async shutdown(reason) {
|
|
3229
|
+
const { state, shutdown, tcp, http, services, logger } = this.deps;
|
|
3230
|
+
state.setState("stopping");
|
|
3231
|
+
logger.info(reason === void 0 ? "stopping" : `stopping (${reason})`);
|
|
3232
|
+
shutdown.abort(shuttingDown());
|
|
3233
|
+
const errors = [];
|
|
3234
|
+
for (const stop of [
|
|
3235
|
+
() => http.stop(),
|
|
3236
|
+
() => tcp.stop(),
|
|
3237
|
+
() => services.stopAll()
|
|
3238
|
+
]) try {
|
|
3239
|
+
await stop();
|
|
3240
|
+
} catch (error) {
|
|
3241
|
+
logger.error(`shutdown failed: ${String(error)}`);
|
|
3242
|
+
errors.push(error);
|
|
3243
|
+
}
|
|
2748
3244
|
if (errors.length === 1) throw errors[0];
|
|
2749
3245
|
if (errors.length > 1) throw new AggregateError(errors, "shutdown failed");
|
|
2750
3246
|
logger.info("stopped");
|
|
@@ -2869,12 +3365,14 @@ function mergePatch(base, patch) {
|
|
|
2869
3365
|
* Throws `INVALID_REQUEST` if two listeners of `config` would use the same port: the bridge's TCP
|
|
2870
3366
|
* and HTTP ports and the ports of the enabled child services. A port `0` (any free port) can't
|
|
2871
3367
|
* collide. Checked on the final configuration only: a patch alone doesn't know the other ports.
|
|
3368
|
+
* The error names `changed` if it is one of the two, else the later one.
|
|
2872
3369
|
*/
|
|
2873
|
-
function assertDistinctPorts(config) {
|
|
3370
|
+
function assertDistinctPorts(config, changed) {
|
|
2874
3371
|
const used = /* @__PURE__ */ new Map();
|
|
2875
3372
|
const listeners = [["tcp.port", config.tcp.port], ["http.port", config.http.port]];
|
|
2876
3373
|
if (config.playwright.enabled) listeners.push(["playwright.port", config.playwright.port]);
|
|
2877
3374
|
if (config.mcp.enabled) listeners.push(["mcp.port", config.mcp.port]);
|
|
3375
|
+
listeners.sort(([a], [b]) => Number(a === changed) - Number(b === changed));
|
|
2878
3376
|
for (const [field, value] of listeners) {
|
|
2879
3377
|
const other = used.get(value);
|
|
2880
3378
|
if (value !== 0 && other !== void 0) throw invalidField(field, `port ${value} is already used by ${other}`);
|
|
@@ -2938,7 +3436,8 @@ const same = (a, b) => show$1(a) === show$1(b);
|
|
|
2938
3436
|
/**
|
|
2939
3437
|
* The configuration (`GET` / `PUT /api/v1/config`). The configuration in use never changes while
|
|
2940
3438
|
* the bridge runs: an update is saved to the config file and takes effect on the next start
|
|
2941
|
-
* (docs/usage/configuration.md#changing-settings).
|
|
3439
|
+
* (docs/usage/configuration.md#changing-settings). The one exception is a TCP port chosen at
|
|
3440
|
+
* startup (`adopt`), before the API answers.
|
|
2942
3441
|
*/
|
|
2943
3442
|
var ConfigService = class {
|
|
2944
3443
|
deps;
|
|
@@ -2963,24 +3462,54 @@ var ConfigService = class {
|
|
|
2963
3462
|
return Object.fromEntries(this.deps.pinned ?? []);
|
|
2964
3463
|
}
|
|
2965
3464
|
update(patch) {
|
|
2966
|
-
|
|
3465
|
+
return this.enqueue(async () => {
|
|
3466
|
+
const changes = await this.save(patch);
|
|
3467
|
+
this.log(configFields(changes));
|
|
3468
|
+
return this.saved;
|
|
3469
|
+
});
|
|
3470
|
+
}
|
|
3471
|
+
check(patch) {
|
|
3472
|
+
this.validate(patch);
|
|
3473
|
+
}
|
|
3474
|
+
adopt(patch) {
|
|
3475
|
+
return this.enqueue(async () => {
|
|
3476
|
+
const changes = await this.save(patch);
|
|
3477
|
+
const before = configFields(this.active);
|
|
3478
|
+
this.active = mergeConfig(this.active, changes);
|
|
3479
|
+
for (const [field, value] of configFields(changes)) {
|
|
3480
|
+
if (same(value, before.get(field))) continue;
|
|
3481
|
+
this.deps.logger.info(`${field}: ${show$1(before.get(field))} → ${show$1(value)}, saved to ${this.deps.store.location}`);
|
|
3482
|
+
}
|
|
3483
|
+
return this.active;
|
|
3484
|
+
});
|
|
3485
|
+
}
|
|
3486
|
+
/** One at a time: a second update starts from the result of the first. */
|
|
3487
|
+
enqueue(run) {
|
|
3488
|
+
const result = this.queue.then(run);
|
|
2967
3489
|
this.queue = result.catch(() => void 0);
|
|
2968
3490
|
return result;
|
|
2969
3491
|
}
|
|
2970
|
-
|
|
3492
|
+
/** The valid changes of `patch`, and the saved configuration with them. Throws `AppError`. */
|
|
3493
|
+
validate(patch) {
|
|
2971
3494
|
const changes = validatePatch(patch);
|
|
2972
3495
|
const merged = mergeConfig(this.saved, changes);
|
|
2973
|
-
assertDistinctPorts(merged);
|
|
3496
|
+
assertDistinctPorts(merged, [...configFields(changes).keys()].find((field) => field.endsWith(".port")));
|
|
3497
|
+
return {
|
|
3498
|
+
changes,
|
|
3499
|
+
merged
|
|
3500
|
+
};
|
|
3501
|
+
}
|
|
3502
|
+
/** Validates `patch` and saves it. Resolves with its changes. */
|
|
3503
|
+
async save(patch) {
|
|
3504
|
+
const { changes, merged } = this.validate(patch);
|
|
2974
3505
|
const saved = configFields(this.file);
|
|
2975
|
-
|
|
2976
|
-
if ([...patched].some(([field, value]) => !same(saved.get(field), value))) {
|
|
3506
|
+
if ([...configFields(changes)].some(([field, value]) => !same(saved.get(field), value))) {
|
|
2977
3507
|
const file = mergePatch(this.file, changes);
|
|
2978
|
-
await this.deps.store.save(withUnknownSettings(file, this.deps.unknownSettings ?? {}));
|
|
3508
|
+
await this.deps.store.save(withUnknownSettings(file, this.deps.unknownSettings ?? {}), (warning) => this.deps.logger.warn(warning));
|
|
2979
3509
|
this.file = file;
|
|
2980
3510
|
}
|
|
2981
3511
|
this.saved = merged;
|
|
2982
|
-
|
|
2983
|
-
return merged;
|
|
3512
|
+
return changes;
|
|
2984
3513
|
}
|
|
2985
3514
|
log(patched) {
|
|
2986
3515
|
const { logger, pinned, store } = this.deps;
|
|
@@ -2995,14 +3524,6 @@ var ConfigService = class {
|
|
|
2995
3524
|
// src/application/ports/in/capture-input.ts
|
|
2996
3525
|
/** Defaults and ranges of the capture options, in milliseconds. */
|
|
2997
3526
|
const CAPTURE_LIMITS = API_LIMITS.capture;
|
|
2998
|
-
// src/application/shared/abort.ts
|
|
2999
|
-
/** The error an aborted signal ends a pending request with: its reason, if that is an error. */
|
|
3000
|
-
function abortReason(signal) {
|
|
3001
|
-
const reason = signal.reason;
|
|
3002
|
-
return reason instanceof Error ? reason : /* @__PURE__ */ new Error("The request was aborted");
|
|
3003
|
-
}
|
|
3004
|
-
/** What pending requests (waits, captures) end with when the bridge shuts down. */
|
|
3005
|
-
const shuttingDown = () => new AppError("SERVICE_UNAVAILABLE", "The bridge is shutting down");
|
|
3006
3527
|
// src/domain/seq-cursor.ts
|
|
3007
3528
|
/**
|
|
3008
3529
|
* A follower's position in the speech log. `SpeechLog` gives every entry the next `seq`, strictly
|
|
@@ -3150,8 +3671,6 @@ const toError = (error) => error instanceof Error ? error : new Error(String(err
|
|
|
3150
3671
|
*/
|
|
3151
3672
|
var InputCaptureService = class {
|
|
3152
3673
|
deps;
|
|
3153
|
-
pending = /* @__PURE__ */ new Set();
|
|
3154
|
-
closed = false;
|
|
3155
3674
|
constructor(deps) {
|
|
3156
3675
|
this.deps = deps;
|
|
3157
3676
|
}
|
|
@@ -3161,22 +3680,11 @@ var InputCaptureService = class {
|
|
|
3161
3680
|
pressKeys({ capture, signal, ...request }) {
|
|
3162
3681
|
return this.run(capture, signal, (hooks) => this.deps.input.pressKeys(request, hooks));
|
|
3163
3682
|
}
|
|
3164
|
-
/**
|
|
3165
|
-
* Rejects all pending captures, and every later one, with `SERVICE_UNAVAILABLE`. The `Shutdown`
|
|
3166
|
-
* lifecycle port: only the composition root calls it.
|
|
3167
|
-
*/
|
|
3168
|
-
shutdown() {
|
|
3169
|
-
this.closed = true;
|
|
3170
|
-
for (const stop of [...this.pending]) stop.abort(shuttingDown());
|
|
3171
|
-
}
|
|
3172
3683
|
async run(capture, signal, send) {
|
|
3173
|
-
|
|
3684
|
+
this.deps.shutdown.throwIfAborted();
|
|
3174
3685
|
const options = parseOptions(capture);
|
|
3175
3686
|
if (signal?.aborted) throw abortReason(signal);
|
|
3176
|
-
const stop =
|
|
3177
|
-
const onAbort = () => stop.abort(abortReason(signal));
|
|
3178
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
3179
|
-
this.pending.add(stop);
|
|
3687
|
+
const stop = linkSignals(this.deps.shutdown, signal);
|
|
3180
3688
|
try {
|
|
3181
3689
|
let startSeq = 0;
|
|
3182
3690
|
return {
|
|
@@ -3191,8 +3699,7 @@ var InputCaptureService = class {
|
|
|
3191
3699
|
...await this.record(startSeq, options, stop.signal)
|
|
3192
3700
|
};
|
|
3193
3701
|
} finally {
|
|
3194
|
-
|
|
3195
|
-
this.pending.delete(stop);
|
|
3702
|
+
stop.dispose();
|
|
3196
3703
|
}
|
|
3197
3704
|
}
|
|
3198
3705
|
/**
|
|
@@ -3369,11 +3876,6 @@ function parseKeyChord(chord) {
|
|
|
3369
3876
|
}
|
|
3370
3877
|
// src/application/services/native-input-service.ts
|
|
3371
3878
|
const { coordinate, delayMs, maxKeys } = API_LIMITS.input;
|
|
3372
|
-
const BUTTONS = [
|
|
3373
|
-
"left",
|
|
3374
|
-
"right",
|
|
3375
|
-
"middle"
|
|
3376
|
-
];
|
|
3377
3879
|
function checkCoordinate(field, value) {
|
|
3378
3880
|
if (!Number.isInteger(value) || Math.abs(value) > coordinate) throw invalidField(field, `must be an integer from -${coordinate} to ${coordinate}`);
|
|
3379
3881
|
}
|
|
@@ -3398,16 +3900,13 @@ function parseKeys(keys) {
|
|
|
3398
3900
|
var NativeInputService = class {
|
|
3399
3901
|
deps;
|
|
3400
3902
|
queue = Promise.resolve();
|
|
3401
|
-
/** One per queued or running request. */
|
|
3402
|
-
pending = /* @__PURE__ */ new Set();
|
|
3403
|
-
closed = false;
|
|
3404
3903
|
constructor(deps) {
|
|
3405
3904
|
this.deps = deps;
|
|
3406
3905
|
}
|
|
3407
3906
|
async click({ x, y, button = "left" }, hooks = {}) {
|
|
3408
3907
|
checkCoordinate("x", x);
|
|
3409
3908
|
checkCoordinate("y", y);
|
|
3410
|
-
if (!
|
|
3909
|
+
if (!MOUSE_BUTTONS.includes(button)) throw invalidField("button", "must be left, right or middle");
|
|
3411
3910
|
let sent = false;
|
|
3412
3911
|
return this.enqueue(async (signal) => {
|
|
3413
3912
|
await hooks.beforeInject?.();
|
|
@@ -3509,21 +4008,31 @@ var NativeInputService = class {
|
|
|
3509
4008
|
held.push(modifier);
|
|
3510
4009
|
}
|
|
3511
4010
|
await injector.keyTap(key);
|
|
3512
|
-
}
|
|
3513
|
-
|
|
4011
|
+
} catch (error) {
|
|
4012
|
+
await this.release(held);
|
|
4013
|
+
throw error;
|
|
3514
4014
|
}
|
|
3515
|
-
|
|
3516
|
-
|
|
3517
|
-
return this.enqueue(task, signal);
|
|
4015
|
+
const failed = await this.release(held);
|
|
4016
|
+
if (failed !== void 0) throw failed;
|
|
3518
4017
|
}
|
|
3519
4018
|
/**
|
|
3520
|
-
*
|
|
3521
|
-
*
|
|
3522
|
-
*
|
|
4019
|
+
* Releases the held keys, the last one first. Every one is tried even if another fails: a
|
|
4020
|
+
* modifier left down would change all later input on the desktop. Resolves with the first
|
|
4021
|
+
* failure, `undefined` if all were released.
|
|
3523
4022
|
*/
|
|
3524
|
-
|
|
3525
|
-
|
|
3526
|
-
for (const
|
|
4023
|
+
async release(held) {
|
|
4024
|
+
let first;
|
|
4025
|
+
for (const key of [...held].reverse()) try {
|
|
4026
|
+
await this.deps.injector.keyUp(key);
|
|
4027
|
+
} catch (error) {
|
|
4028
|
+
const failure = error instanceof Error ? error : new Error(String(error));
|
|
4029
|
+
this.deps.logger.error(`${key} could not be released, it may still be held down (${failure.message})`);
|
|
4030
|
+
first ??= failure;
|
|
4031
|
+
}
|
|
4032
|
+
return first;
|
|
4033
|
+
}
|
|
4034
|
+
exclusive(task, signal) {
|
|
4035
|
+
return this.enqueue(task, signal);
|
|
3527
4036
|
}
|
|
3528
4037
|
/**
|
|
3529
4038
|
* Runs `task` after the earlier ones; a failed task doesn't stop the later ones. `task` isn't
|
|
@@ -3531,12 +4040,7 @@ var NativeInputService = class {
|
|
|
3531
4040
|
* request leaves unsent, for the log.
|
|
3532
4041
|
*/
|
|
3533
4042
|
async enqueue(task, signal, unsent = () => void 0) {
|
|
3534
|
-
const stop =
|
|
3535
|
-
const onAbort = () => stop.abort(abortReason(signal));
|
|
3536
|
-
if (this.closed) stop.abort(shuttingDown());
|
|
3537
|
-
else if (signal?.aborted) onAbort();
|
|
3538
|
-
else signal?.addEventListener("abort", onAbort, { once: true });
|
|
3539
|
-
this.pending.add(stop);
|
|
4043
|
+
const stop = linkSignals(this.deps.shutdown, signal);
|
|
3540
4044
|
const run = this.queue.then(() => {
|
|
3541
4045
|
stop.signal.throwIfAborted();
|
|
3542
4046
|
return task(stop.signal);
|
|
@@ -3549,8 +4053,7 @@ var NativeInputService = class {
|
|
|
3549
4053
|
if (what !== void 0) this.deps.logger.warn(`${what} (${abortReason(stop.signal).message})`);
|
|
3550
4054
|
throw error;
|
|
3551
4055
|
} finally {
|
|
3552
|
-
|
|
3553
|
-
this.pending.delete(stop);
|
|
4056
|
+
stop.dispose();
|
|
3554
4057
|
}
|
|
3555
4058
|
}
|
|
3556
4059
|
};
|
|
@@ -3735,8 +4238,8 @@ function markerLabel(label) {
|
|
|
3735
4238
|
}
|
|
3736
4239
|
// src/application/services/status-service.ts
|
|
3737
4240
|
/**
|
|
3738
|
-
* `GET /api/v1/status`.
|
|
3739
|
-
* `BridgeStateControl`.
|
|
4241
|
+
* `GET /api/v1/status`. `BridgeLifecycleService` moves the state from `starting` to `ready` and
|
|
4242
|
+
* `stopping` through `BridgeStateControl`.
|
|
3740
4243
|
*/
|
|
3741
4244
|
var StatusService = class {
|
|
3742
4245
|
deps;
|
|
@@ -3765,7 +4268,8 @@ var StatusService = class {
|
|
|
3765
4268
|
host: listener?.host ?? tcp.host,
|
|
3766
4269
|
port: listener?.port ?? tcp.port,
|
|
3767
4270
|
encoding: listener?.encoding ?? tcp.encoding,
|
|
3768
|
-
connections
|
|
4271
|
+
connections,
|
|
4272
|
+
lastSpeechAt: log.lastSpeechAt ?? null
|
|
3769
4273
|
},
|
|
3770
4274
|
buffer: log.stats(),
|
|
3771
4275
|
services: Object.fromEntries(SERVICE_NAMES.map((name) => [name, supervisors[name].status()])),
|
|
@@ -3780,6 +4284,87 @@ var StatusService = class {
|
|
|
3780
4284
|
};
|
|
3781
4285
|
}
|
|
3782
4286
|
};
|
|
4287
|
+
// src/application/services/tcp-startup-service.ts
|
|
4288
|
+
const VOICE_DOCS = "docs/usage/vm-setup.md#more-voices--other-ports";
|
|
4289
|
+
const QUIT = /* @__PURE__ */ new Set([
|
|
4290
|
+
"",
|
|
4291
|
+
"q",
|
|
4292
|
+
"quit",
|
|
4293
|
+
"exit"
|
|
4294
|
+
]);
|
|
4295
|
+
/**
|
|
4296
|
+
* Starts the TCP listener on `tcp.port`. If that port is in use or not allowed, it asks the person
|
|
4297
|
+
* at the console for another one, checks it, listens on it and saves it to the config file. It
|
|
4298
|
+
* never picks a port by itself: the socket voice only sends to the port it is set up with
|
|
4299
|
+
* (docs/implementation/tcp-capture.md#listening-and-connections).
|
|
4300
|
+
*/
|
|
4301
|
+
var TcpStartupService = class {
|
|
4302
|
+
deps;
|
|
4303
|
+
constructor(deps) {
|
|
4304
|
+
this.deps = deps;
|
|
4305
|
+
}
|
|
4306
|
+
async start() {
|
|
4307
|
+
const { listener, config } = this.deps;
|
|
4308
|
+
const port = config.get().tcp.port;
|
|
4309
|
+
try {
|
|
4310
|
+
return await listener.start(port);
|
|
4311
|
+
} catch (error) {
|
|
4312
|
+
if (!(error instanceof PortUnavailableError) || port === 0) throw error;
|
|
4313
|
+
return this.choosePort(error);
|
|
4314
|
+
}
|
|
4315
|
+
}
|
|
4316
|
+
stop() {
|
|
4317
|
+
return this.deps.listener.stop();
|
|
4318
|
+
}
|
|
4319
|
+
async choosePort(failure) {
|
|
4320
|
+
const { pinnedBy, prompt, logger, configLocation } = this.deps;
|
|
4321
|
+
if (pinnedBy !== void 0) throw hinted(failure, `${pinnedBy} sets this port: choose a free one there`);
|
|
4322
|
+
const giveUp = hinted(failure, `Start with --tcp-port <port>, or set tcp.port in ${configLocation}`);
|
|
4323
|
+
if (prompt === void 0) throw giveUp;
|
|
4324
|
+
logger.warn(failure.message);
|
|
4325
|
+
for (;;) {
|
|
4326
|
+
const text = (await prompt.ask(`TCP port ${failure.port} can't be used. TCP port for the socket voice (Enter to quit): `))?.trim();
|
|
4327
|
+
if (text === void 0 || QUIT.has(text.toLowerCase())) throw giveUp;
|
|
4328
|
+
const port = await this.tryPort(text);
|
|
4329
|
+
if (port === void 0) continue;
|
|
4330
|
+
await this.save(port);
|
|
4331
|
+
logger.warn(`speech capture listens on port ${port} instead of ${failure.port}: point the socket voice to it (${VOICE_DOCS})`);
|
|
4332
|
+
return port;
|
|
4333
|
+
}
|
|
4334
|
+
}
|
|
4335
|
+
/** Listens on the port in `answer`, or warns why not and resolves with `undefined`. */
|
|
4336
|
+
async tryPort(answer) {
|
|
4337
|
+
const { listener, config, logger } = this.deps;
|
|
4338
|
+
if (!/^\d+$/.test(answer)) {
|
|
4339
|
+
logger.warn(`${JSON.stringify(answer)} is not a port number`);
|
|
4340
|
+
return;
|
|
4341
|
+
}
|
|
4342
|
+
const port = Number(answer);
|
|
4343
|
+
if (port === 0) {
|
|
4344
|
+
logger.warn("port 0 picks another port on every start, but the voice needs a fixed one");
|
|
4345
|
+
return;
|
|
4346
|
+
}
|
|
4347
|
+
try {
|
|
4348
|
+
config.check({ tcp: { port } });
|
|
4349
|
+
return await listener.start(port);
|
|
4350
|
+
} catch (error) {
|
|
4351
|
+
if (!(error instanceof AppError || error instanceof PortUnavailableError)) throw error;
|
|
4352
|
+
logger.warn(error.message);
|
|
4353
|
+
return;
|
|
4354
|
+
}
|
|
4355
|
+
}
|
|
4356
|
+
/** Saves `port` as `tcp.port`. The bridge uses it anyway if the file can't be written. */
|
|
4357
|
+
async save(port) {
|
|
4358
|
+
try {
|
|
4359
|
+
await this.deps.config.adopt({ tcp: { port } });
|
|
4360
|
+
} catch (error) {
|
|
4361
|
+
this.deps.logger.warn(`tcp.port ${port} could not be saved to ${this.deps.configLocation} (${error instanceof Error ? error.message : String(error)}): start with --tcp-port ${port} next time`);
|
|
4362
|
+
}
|
|
4363
|
+
}
|
|
4364
|
+
};
|
|
4365
|
+
function hinted(failure, hint) {
|
|
4366
|
+
return new PortUnavailableError(`${failure.message}. ${hint}`, failure.port, failure.reason);
|
|
4367
|
+
}
|
|
3783
4368
|
// src/application/services/transcript-service.ts
|
|
3784
4369
|
/** Logs each recorded speech line, and each session start and end, at `debug`. */
|
|
3785
4370
|
var TranscriptService = class {
|
|
@@ -3870,13 +4455,11 @@ var LastSeen = class {
|
|
|
3870
4455
|
*/
|
|
3871
4456
|
var WaitForSpeechService = class {
|
|
3872
4457
|
deps;
|
|
3873
|
-
pending = /* @__PURE__ */ new Set();
|
|
3874
|
-
closed = false;
|
|
3875
4458
|
constructor(deps) {
|
|
3876
4459
|
this.deps = deps;
|
|
3877
4460
|
}
|
|
3878
4461
|
async wait(options) {
|
|
3879
|
-
|
|
4462
|
+
this.deps.shutdown.throwIfAborted();
|
|
3880
4463
|
const { signal } = options;
|
|
3881
4464
|
const since = intOption("since", options.since, {
|
|
3882
4465
|
fallback: 0,
|
|
@@ -3895,18 +4478,18 @@ var WaitForSpeechService = class {
|
|
|
3895
4478
|
const seen = new LastSeen();
|
|
3896
4479
|
let done = false;
|
|
3897
4480
|
let stop;
|
|
4481
|
+
/** The client's signal and the shutdown's. */
|
|
4482
|
+
const ended = linkSignals(this.deps.shutdown, signal);
|
|
3898
4483
|
const finish = () => {
|
|
3899
4484
|
done = true;
|
|
3900
4485
|
stop?.();
|
|
3901
4486
|
timer.abort();
|
|
3902
|
-
|
|
3903
|
-
this.pending.delete(fail);
|
|
4487
|
+
ended.dispose();
|
|
3904
4488
|
};
|
|
3905
4489
|
const fail = (error) => {
|
|
3906
4490
|
finish();
|
|
3907
4491
|
reject(error);
|
|
3908
4492
|
};
|
|
3909
|
-
const onAbort = () => fail(abortReason(signal));
|
|
3910
4493
|
const timer = new AbortController();
|
|
3911
4494
|
const startTimer = () => {
|
|
3912
4495
|
if (done) return;
|
|
@@ -3919,8 +4502,7 @@ var WaitForSpeechService = class {
|
|
|
3919
4502
|
});
|
|
3920
4503
|
}, () => {});
|
|
3921
4504
|
};
|
|
3922
|
-
signal
|
|
3923
|
-
this.pending.add(fail);
|
|
4505
|
+
ended.signal.addEventListener("abort", () => fail(abortReason(ended.signal)), { once: true });
|
|
3924
4506
|
const failed = (error) => fail(error instanceof Error ? error : new Error(String(error)));
|
|
3925
4507
|
try {
|
|
3926
4508
|
stop = followLog(this.deps, {
|
|
@@ -3946,40 +4528,7 @@ var WaitForSpeechService = class {
|
|
|
3946
4528
|
}
|
|
3947
4529
|
});
|
|
3948
4530
|
}
|
|
3949
|
-
/**
|
|
3950
|
-
* Rejects all pending waits, and every later one, with `SERVICE_UNAVAILABLE`. The `Shutdown`
|
|
3951
|
-
* lifecycle port, not part of `WaitForSpeech`: only the composition root calls it.
|
|
3952
|
-
*/
|
|
3953
|
-
shutdown() {
|
|
3954
|
-
this.closed = true;
|
|
3955
|
-
for (const fail of [...this.pending]) fail(shuttingDown());
|
|
3956
|
-
}
|
|
3957
4531
|
};
|
|
3958
|
-
// src/composition/lifecycle.ts
|
|
3959
|
-
/**
|
|
3960
|
-
* Startup order (docs/usage/operations.md#startup): the TCP listener first, so no speech is lost
|
|
3961
|
-
* while the rest starts, then HTTP. A failure is logged, and the TCP listener stops if HTTP fails.
|
|
3962
|
-
*/
|
|
3963
|
-
async function startListeners(tcp, http, config, logger) {
|
|
3964
|
-
const failed = (error) => logger.error(error instanceof ListenError ? error.message : String(error));
|
|
3965
|
-
let tcpPort;
|
|
3966
|
-
try {
|
|
3967
|
-
tcpPort = await tcp.start(config.tcp);
|
|
3968
|
-
} catch (error) {
|
|
3969
|
-
failed(error);
|
|
3970
|
-
throw error;
|
|
3971
|
-
}
|
|
3972
|
-
try {
|
|
3973
|
-
return {
|
|
3974
|
-
tcp: tcpPort,
|
|
3975
|
-
http: await http.start(config.http)
|
|
3976
|
-
};
|
|
3977
|
-
} catch (error) {
|
|
3978
|
-
failed(error);
|
|
3979
|
-
await tcp.stop();
|
|
3980
|
-
throw error;
|
|
3981
|
-
}
|
|
3982
|
-
}
|
|
3983
4532
|
// src/composition/load-config.ts
|
|
3984
4533
|
/** A setting from flags, the environment or the config file is invalid. Nothing was started. */
|
|
3985
4534
|
var ConfigError = class extends Error {
|
|
@@ -3995,12 +4544,14 @@ function checked(patch, origin) {
|
|
|
3995
4544
|
}
|
|
3996
4545
|
/**
|
|
3997
4546
|
* Defaults, then the config file, then flags and environment variables. Settings of the file this
|
|
3998
|
-
* bridge doesn't know are left out of `config` and `file` and returned in `unknown`.
|
|
4547
|
+
* bridge doesn't know are left out of `config` and `file` and returned in `unknown`. The store's
|
|
4548
|
+
* `warnings` are returned too: there is no log yet, it is built from the result.
|
|
3999
4549
|
*/
|
|
4000
4550
|
async function loadConfig(store, overridesPatch, sourceOf) {
|
|
4001
4551
|
let saved;
|
|
4552
|
+
const warnings = [];
|
|
4002
4553
|
try {
|
|
4003
|
-
saved = await store.load();
|
|
4554
|
+
saved = await store.load((message) => warnings.push(message));
|
|
4004
4555
|
} catch (error) {
|
|
4005
4556
|
throw new ConfigError(error.message, { cause: error });
|
|
4006
4557
|
}
|
|
@@ -4018,7 +4569,8 @@ async function loadConfig(store, overridesPatch, sourceOf) {
|
|
|
4018
4569
|
file,
|
|
4019
4570
|
overrides,
|
|
4020
4571
|
unknown,
|
|
4021
|
-
ignored
|
|
4572
|
+
ignored,
|
|
4573
|
+
warnings
|
|
4022
4574
|
};
|
|
4023
4575
|
}
|
|
4024
4576
|
// src/composition/summary.ts
|
|
@@ -4550,116 +5102,6 @@ var BridgeLog = class {
|
|
|
4550
5102
|
}
|
|
4551
5103
|
}
|
|
4552
5104
|
};
|
|
4553
|
-
// src/adapters/out/log/async-console.ts
|
|
4554
|
-
const MAX_PENDING_BYTES = 1048576;
|
|
4555
|
-
const FLUSH_TIMEOUT_MS = 1e3;
|
|
4556
|
-
/**
|
|
4557
|
-
* Hands text to `channel` without ever blocking. While the console is stuck, text piles up to
|
|
4558
|
-
* `maxPendingBytes`, then new lines are dropped (the log file keeps everything). When the console
|
|
4559
|
-
* takes text again, a line says how many were dropped.
|
|
4560
|
-
*/
|
|
4561
|
-
function createAsyncConsole(options) {
|
|
4562
|
-
const { channel, fallback, maxPendingBytes = MAX_PENDING_BYTES } = options;
|
|
4563
|
-
let pending = 0;
|
|
4564
|
-
let dropped = 0;
|
|
4565
|
-
let failed = false;
|
|
4566
|
-
let nextFlush = 0;
|
|
4567
|
-
const waiting = /* @__PURE__ */ new Map();
|
|
4568
|
-
channel.onMessage((message) => {
|
|
4569
|
-
if ("written" in message) {
|
|
4570
|
-
pending = Math.max(0, pending - message.written);
|
|
4571
|
-
return;
|
|
4572
|
-
}
|
|
4573
|
-
waiting.get(message.flushed)?.();
|
|
4574
|
-
});
|
|
4575
|
-
channel.onFailure(() => {
|
|
4576
|
-
failed = true;
|
|
4577
|
-
for (const done of waiting.values()) done();
|
|
4578
|
-
});
|
|
4579
|
-
return {
|
|
4580
|
-
write(text) {
|
|
4581
|
-
if (failed) return fallback(text);
|
|
4582
|
-
if (pending >= maxPendingBytes) {
|
|
4583
|
-
dropped += 1;
|
|
4584
|
-
return;
|
|
4585
|
-
}
|
|
4586
|
-
if (dropped > 0) {
|
|
4587
|
-
const notice = `console output was blocked, ${dropped} lines dropped (see the log file)\n`;
|
|
4588
|
-
dropped = 0;
|
|
4589
|
-
pending += Buffer.byteLength(notice);
|
|
4590
|
-
channel.post(notice);
|
|
4591
|
-
}
|
|
4592
|
-
pending += Buffer.byteLength(text);
|
|
4593
|
-
channel.post(text);
|
|
4594
|
-
},
|
|
4595
|
-
flush(timeoutMs = FLUSH_TIMEOUT_MS) {
|
|
4596
|
-
if (failed) return Promise.resolve();
|
|
4597
|
-
return new Promise((resolve) => {
|
|
4598
|
-
const id = nextFlush++;
|
|
4599
|
-
const finish = () => {
|
|
4600
|
-
clearTimeout(timer);
|
|
4601
|
-
waiting.delete(id);
|
|
4602
|
-
resolve();
|
|
4603
|
-
};
|
|
4604
|
-
const timer = setTimeout(finish, timeoutMs);
|
|
4605
|
-
waiting.set(id, finish);
|
|
4606
|
-
channel.requestFlush(id);
|
|
4607
|
-
});
|
|
4608
|
-
}
|
|
4609
|
-
};
|
|
4610
|
-
}
|
|
4611
|
-
const WORKER_SOURCE = `
|
|
4612
|
-
const { parentPort, workerData } = require('node:worker_threads');
|
|
4613
|
-
const tty = require('node:tty');
|
|
4614
|
-
const stream = new tty.WriteStream(workerData.fd);
|
|
4615
|
-
stream.on('error', () => {});
|
|
4616
|
-
parentPort.on('message', (message) => {
|
|
4617
|
-
if (message.flush !== undefined) {
|
|
4618
|
-
stream.write('', () => parentPort.postMessage({ flushed: message.flush }));
|
|
4619
|
-
return;
|
|
4620
|
-
}
|
|
4621
|
-
const bytes = Buffer.byteLength(message.text);
|
|
4622
|
-
stream.write(message.text, () => parentPort.postMessage({ written: bytes }));
|
|
4623
|
-
});
|
|
4624
|
-
`;
|
|
4625
|
-
function workerChannel(fd) {
|
|
4626
|
-
const worker = new Worker(WORKER_SOURCE, {
|
|
4627
|
-
eval: true,
|
|
4628
|
-
workerData: { fd }
|
|
4629
|
-
});
|
|
4630
|
-
worker.unref();
|
|
4631
|
-
return {
|
|
4632
|
-
post: (text) => worker.postMessage({ text }),
|
|
4633
|
-
requestFlush: (id) => worker.postMessage({ flush: id }),
|
|
4634
|
-
onMessage: (listener) => worker.on("message", listener),
|
|
4635
|
-
onFailure: (listener) => {
|
|
4636
|
-
worker.on("error", listener);
|
|
4637
|
-
worker.on("exit", listener);
|
|
4638
|
-
}
|
|
4639
|
-
};
|
|
4640
|
-
}
|
|
4641
|
-
let console_;
|
|
4642
|
-
/**
|
|
4643
|
-
* A writer for stdout that can't block the bridge, or `undefined` when stdout is not a terminal
|
|
4644
|
-
* (a pipe or file has no selection mode, and `process.stdout` is fine there).
|
|
4645
|
-
*/
|
|
4646
|
-
function terminalWriter(stream = process.stdout) {
|
|
4647
|
-
if (stream.isTTY !== true) return void 0;
|
|
4648
|
-
try {
|
|
4649
|
-
console_ ??= createAsyncConsole({
|
|
4650
|
-
channel: workerChannel(1),
|
|
4651
|
-
fallback: (text) => void stream.write(text)
|
|
4652
|
-
});
|
|
4653
|
-
} catch {
|
|
4654
|
-
return;
|
|
4655
|
-
}
|
|
4656
|
-
const writer = console_;
|
|
4657
|
-
return (text) => writer.write(text);
|
|
4658
|
-
}
|
|
4659
|
-
/** Waits (briefly) until the terminal writer has written everything. */
|
|
4660
|
-
function flushTerminal() {
|
|
4661
|
-
return console_?.flush() ?? Promise.resolve();
|
|
4662
|
-
}
|
|
4663
5105
|
// src/adapters/out/log/console-sink.ts
|
|
4664
5106
|
/**
|
|
4665
5107
|
* Decides whether a console stream gets colours: `NO_COLOR` turns them off, `FORCE_COLOR`
|
|
@@ -4684,40 +5126,77 @@ function consoleSink(options = {}) {
|
|
|
4684
5126
|
/**
|
|
4685
5127
|
* Bridge log file (docs/usage/operations.md#logging): no colours, includes the speech channel.
|
|
4686
5128
|
* Writes synchronously so nothing is lost on a crash. Log volume is small.
|
|
5129
|
+
*
|
|
5130
|
+
* A failure doesn't end the file log. A line that can't be written is lost, and the next one tries
|
|
5131
|
+
* again. A file that can't be rotated keeps growing, and rotation is tried again later.
|
|
4687
5132
|
*/
|
|
4688
5133
|
function fileSink(file, options = {}) {
|
|
4689
5134
|
const { maxBytes = 10485760, keep = 5 } = options;
|
|
4690
|
-
const onError = options.onError ?? ((error) => process.stderr.write(`screenreader-speech-capture-bridge:
|
|
4691
|
-
|
|
4692
|
-
let
|
|
5135
|
+
const onError = options.onError ?? ((error) => process.stderr.write(`screenreader-speech-capture-bridge: ${error.message}\n`));
|
|
5136
|
+
/** `undefined`: unknown, the folder and the size are looked at again before the next write. */
|
|
5137
|
+
let size;
|
|
5138
|
+
let writeFailed = false;
|
|
5139
|
+
let rotateFailed = false;
|
|
5140
|
+
/** After a failed rotation: don't try again before the file has this size. */
|
|
5141
|
+
let rotateFrom = 0;
|
|
5142
|
+
const report = (what, error) => onError(new Error(`cannot ${what} the log file: ${error.message}`, { cause: error }));
|
|
5143
|
+
const failedWrite = (error) => {
|
|
5144
|
+
size = void 0;
|
|
5145
|
+
if (!writeFailed) report("write", error);
|
|
5146
|
+
writeFailed = true;
|
|
5147
|
+
};
|
|
5148
|
+
const open = () => {
|
|
5149
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
5150
|
+
return fs.existsSync(file) ? fs.statSync(file).size : 0;
|
|
5151
|
+
};
|
|
5152
|
+
/**
|
|
5153
|
+
* Moves the older files up only as far as the first free number, dropping the oldest when there
|
|
5154
|
+
* is none. So a rotation that fails and is tried again doesn't push out one more file each time.
|
|
5155
|
+
*/
|
|
5156
|
+
const rotate = () => {
|
|
5157
|
+
if (keep < 1) {
|
|
5158
|
+
fs.rmSync(file, { force: true });
|
|
5159
|
+
return;
|
|
5160
|
+
}
|
|
5161
|
+
let free = 1;
|
|
5162
|
+
while (free < keep && fs.existsSync(`${file}.${free}`)) free++;
|
|
5163
|
+
fs.rmSync(`${file}.${free}`, { force: true });
|
|
5164
|
+
for (let i = free - 1; i >= 1; i--) fs.renameSync(`${file}.${i}`, `${file}.${i + 1}`);
|
|
5165
|
+
fs.renameSync(file, `${file}.1`);
|
|
5166
|
+
};
|
|
5167
|
+
/** Rotates, and returns the size of the file to write to. */
|
|
5168
|
+
const tryRotate = (current) => {
|
|
5169
|
+
try {
|
|
5170
|
+
rotate();
|
|
5171
|
+
rotateFailed = false;
|
|
5172
|
+
rotateFrom = 0;
|
|
5173
|
+
return 0;
|
|
5174
|
+
} catch (error) {
|
|
5175
|
+
if (!rotateFailed) report("rotate", error);
|
|
5176
|
+
rotateFailed = true;
|
|
5177
|
+
rotateFrom = current + Math.ceil(maxBytes / 10);
|
|
5178
|
+
return current;
|
|
5179
|
+
}
|
|
5180
|
+
};
|
|
4693
5181
|
try {
|
|
4694
|
-
|
|
4695
|
-
size = fs$1.existsSync(file) ? fs$1.statSync(file).size : 0;
|
|
5182
|
+
size = open();
|
|
4696
5183
|
} catch (error) {
|
|
4697
|
-
|
|
4698
|
-
onError(error);
|
|
5184
|
+
failedWrite(error);
|
|
4699
5185
|
}
|
|
4700
|
-
const rotate = () => {
|
|
4701
|
-
fs$1.rmSync(`${file}.${keep}`, { force: true });
|
|
4702
|
-
for (let i = keep - 1; i >= 1; i--) if (fs$1.existsSync(`${file}.${i}`)) fs$1.renameSync(`${file}.${i}`, `${file}.${i + 1}`);
|
|
4703
|
-
if (keep >= 1) fs$1.renameSync(file, `${file}.1`);
|
|
4704
|
-
else fs$1.rmSync(file, { force: true });
|
|
4705
|
-
size = 0;
|
|
4706
|
-
};
|
|
4707
5186
|
return {
|
|
4708
5187
|
colour: false,
|
|
4709
5188
|
speech: true,
|
|
4710
5189
|
write(line) {
|
|
4711
|
-
if (failed) return;
|
|
4712
5190
|
const data = `${line}\n`;
|
|
4713
5191
|
const bytes = Buffer.byteLength(data);
|
|
4714
5192
|
try {
|
|
4715
|
-
|
|
4716
|
-
|
|
5193
|
+
size ??= open();
|
|
5194
|
+
if (size > 0 && size + bytes > maxBytes && size >= rotateFrom) size = tryRotate(size);
|
|
5195
|
+
fs.appendFileSync(file, data);
|
|
4717
5196
|
size += bytes;
|
|
5197
|
+
writeFailed = false;
|
|
4718
5198
|
} catch (error) {
|
|
4719
|
-
|
|
4720
|
-
onError(error);
|
|
5199
|
+
failedWrite(error);
|
|
4721
5200
|
}
|
|
4722
5201
|
}
|
|
4723
5202
|
};
|
|
@@ -4760,6 +5239,67 @@ function createLogging(config, options) {
|
|
|
4760
5239
|
log.always("bridge", startupMessage(config, options.version, options.configLocation, file));
|
|
4761
5240
|
return log;
|
|
4762
5241
|
}
|
|
5242
|
+
// src/adapters/out/terminal/terminal-prompt.ts
|
|
5243
|
+
/**
|
|
5244
|
+
* Driven adapter: asks a question on the console and reads one line. Ctrl+C, end of input (Ctrl+D,
|
|
5245
|
+
* Ctrl+Z on Windows) and the `signal` cancel it. It lets go of the input after each question, so
|
|
5246
|
+
* the process can still exit.
|
|
5247
|
+
*/
|
|
5248
|
+
var TerminalPrompt = class {
|
|
5249
|
+
options;
|
|
5250
|
+
constructor(options) {
|
|
5251
|
+
this.options = options;
|
|
5252
|
+
}
|
|
5253
|
+
async ask(question) {
|
|
5254
|
+
const { input, output, flush, terminal, signal } = this.options;
|
|
5255
|
+
if (signal?.aborted === true) return void 0;
|
|
5256
|
+
await flush().catch(() => void 0);
|
|
5257
|
+
const rl = createInterface({
|
|
5258
|
+
input,
|
|
5259
|
+
output,
|
|
5260
|
+
...terminal === void 0 ? {} : { terminal }
|
|
5261
|
+
});
|
|
5262
|
+
const abortQuestion = new AbortController();
|
|
5263
|
+
let settled = false;
|
|
5264
|
+
let cancel = () => void 0;
|
|
5265
|
+
const cancelled = new Promise((resolve) => {
|
|
5266
|
+
cancel = () => {
|
|
5267
|
+
if (settled) return;
|
|
5268
|
+
settled = true;
|
|
5269
|
+
output.write("\n");
|
|
5270
|
+
resolve(void 0);
|
|
5271
|
+
};
|
|
5272
|
+
});
|
|
5273
|
+
rl.once("SIGINT", cancel);
|
|
5274
|
+
rl.once("close", cancel);
|
|
5275
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
5276
|
+
try {
|
|
5277
|
+
const answer = rl.question(question, { signal: abortQuestion.signal }).then((line) => line.trim(), () => void 0);
|
|
5278
|
+
const result = await Promise.race([answer, cancelled]);
|
|
5279
|
+
settled = true;
|
|
5280
|
+
return result;
|
|
5281
|
+
} finally {
|
|
5282
|
+
signal?.removeEventListener("abort", cancel);
|
|
5283
|
+
abortQuestion.abort();
|
|
5284
|
+
rl.close();
|
|
5285
|
+
}
|
|
5286
|
+
}
|
|
5287
|
+
};
|
|
5288
|
+
// src/composition/prompt.ts
|
|
5289
|
+
/**
|
|
5290
|
+
* The console prompt, or `undefined` when nobody can answer: stdin or stdout is not a terminal
|
|
5291
|
+
* (a service, CI, a test, output piped to a file). `cancel` ends a pending question.
|
|
5292
|
+
*/
|
|
5293
|
+
function createOperatorPrompt(cancel) {
|
|
5294
|
+
if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) return void 0;
|
|
5295
|
+
return new TerminalPrompt({
|
|
5296
|
+
input: process.stdin,
|
|
5297
|
+
output: process.stdout,
|
|
5298
|
+
flush: flushTerminal,
|
|
5299
|
+
terminal: true,
|
|
5300
|
+
...cancel === void 0 ? {} : { signal: cancel }
|
|
5301
|
+
});
|
|
5302
|
+
}
|
|
4763
5303
|
// src/composition/pace.ts
|
|
4764
5304
|
/**
|
|
4765
5305
|
* A `pace` for a replay or a wait's look through the buffer (`FollowOptions`): lets other work
|
|
@@ -4783,151 +5323,33 @@ function proxyRoutes(services) {
|
|
|
4783
5323
|
target: () => services.reachability("playwright")
|
|
4784
5324
|
}, {
|
|
4785
5325
|
name: SERVICE_TITLES.mcp,
|
|
4786
|
-
path: PLAYWRIGHT_MCP_PATH,
|
|
4787
|
-
upstreamPath: "/mcp",
|
|
4788
|
-
scheme: "http",
|
|
4789
|
-
target: () => services.reachability("mcp")
|
|
4790
|
-
}];
|
|
4791
|
-
}
|
|
4792
|
-
// src/adapters/shared/net/port-probe.ts
|
|
4793
|
-
/** Where to probe a listener on a wildcard host: the loopback address of that family. */
|
|
4794
|
-
const WILDCARD_PROBE = {
|
|
4795
|
-
"0.0.0.0": "127.0.0.1",
|
|
4796
|
-
"::": "::1"
|
|
4797
|
-
};
|
|
4798
|
-
/** Whether something accepts connections on `host:port`, within `timeoutMs`. */
|
|
4799
|
-
function portOpen(host, port, timeoutMs = 1e3) {
|
|
4800
|
-
return new Promise((resolve) => {
|
|
4801
|
-
const socket = net.connect({
|
|
4802
|
-
host: WILDCARD_PROBE[host] ?? host,
|
|
4803
|
-
port
|
|
4804
|
-
});
|
|
4805
|
-
const done = (open) => {
|
|
4806
|
-
socket.destroy();
|
|
4807
|
-
resolve(open);
|
|
4808
|
-
};
|
|
4809
|
-
socket.setTimeout(timeoutMs, () => done(false));
|
|
4810
|
-
socket.once("connect", () => done(true));
|
|
4811
|
-
socket.once("error", () => done(false));
|
|
4812
|
-
});
|
|
4813
|
-
}
|
|
4814
|
-
// src/adapters/out/process/process-tree.ts
|
|
4815
|
-
/** How long the process group gets after `SIGTERM` before `SIGKILL` (not on Windows). */
|
|
4816
|
-
const TERM_GRACE_MS = 3e3;
|
|
4817
|
-
/**
|
|
4818
|
-
* Spawn options for a child whose whole tree `killTree` can end. On POSIX the child leads its own
|
|
4819
|
-
* process group. On Windows that isn't needed (`taskkill /T` walks the tree), and `detached`
|
|
4820
|
-
* there would open a new console window.
|
|
4821
|
-
*/
|
|
4822
|
-
const treeSpawnOptions = {
|
|
4823
|
-
detached: process.platform !== "win32",
|
|
4824
|
-
windowsHide: true
|
|
4825
|
-
};
|
|
4826
|
-
function hasExited(child) {
|
|
4827
|
-
return child.exitCode !== null || child.signalCode !== null;
|
|
4828
|
-
}
|
|
4829
|
-
function killGroup(pid, signal) {
|
|
4830
|
-
try {
|
|
4831
|
-
process.kill(-pid, signal);
|
|
4832
|
-
} catch {}
|
|
4833
|
-
}
|
|
4834
|
-
/** Resolves after `ms`, or when `promise` settles, whichever comes first. */
|
|
4835
|
-
async function within(promise, ms) {
|
|
4836
|
-
let timer;
|
|
4837
|
-
await Promise.race([promise.catch(() => void 0), new Promise((resolve) => timer = setTimeout(resolve, ms))]);
|
|
4838
|
-
clearTimeout(timer);
|
|
4839
|
-
}
|
|
4840
|
-
const exec = (file, args, timeoutMs) => new Promise((resolve) => {
|
|
4841
|
-
execFile(file, [...args], {
|
|
4842
|
-
windowsHide: true,
|
|
4843
|
-
timeout: timeoutMs,
|
|
4844
|
-
killSignal: "SIGKILL"
|
|
4845
|
-
}, (error, stdout) => resolve({
|
|
4846
|
-
ok: error === null,
|
|
4847
|
-
stdout: String(stdout)
|
|
4848
|
-
}));
|
|
4849
|
-
});
|
|
4850
|
-
const TOOL_TIMEOUT_MS = 5e3;
|
|
4851
|
-
/** Trees that may still have processes, for `killAllTreesNow`. */
|
|
4852
|
-
const trees = /* @__PURE__ */ new Set();
|
|
4853
|
-
/**
|
|
4854
|
-
* Remembers a child spawned with `treeSpawnOptions`, so `killAllTreesNow` can end it when the
|
|
4855
|
-
* bridge has to exit without stopping gracefully. `killTree` forgets it; so does `releaseTree`.
|
|
4856
|
-
*/
|
|
4857
|
-
function trackTree(child) {
|
|
4858
|
-
trees.add(child);
|
|
4859
|
-
}
|
|
4860
|
-
/** Forgets a child that ended on its own and left nothing behind to kill. */
|
|
4861
|
-
function releaseTree(child) {
|
|
4862
|
-
trees.delete(child);
|
|
4863
|
-
}
|
|
4864
|
-
/**
|
|
4865
|
-
* Ends every tracked tree at once and synchronously, without waiting for anything. For a forced
|
|
4866
|
-
* exit (watchdog, second Ctrl+C), when the graceful `killTree` has no time left: exiting without
|
|
4867
|
-
* this leaves the browsers of the Playwright server behind.
|
|
4868
|
-
*/
|
|
4869
|
-
function killAllTreesNow(platform = process.platform) {
|
|
4870
|
-
for (const child of trees) {
|
|
4871
|
-
const { pid } = child;
|
|
4872
|
-
if (pid === void 0) continue;
|
|
4873
|
-
if (platform === "win32") spawnSync("taskkill", [
|
|
4874
|
-
"/T",
|
|
4875
|
-
"/F",
|
|
4876
|
-
"/PID",
|
|
4877
|
-
String(pid)
|
|
4878
|
-
], {
|
|
4879
|
-
windowsHide: true,
|
|
4880
|
-
stdio: "ignore",
|
|
4881
|
-
timeout: TOOL_TIMEOUT_MS
|
|
4882
|
-
});
|
|
4883
|
-
else killGroup(pid, "SIGKILL");
|
|
4884
|
-
}
|
|
4885
|
-
trees.clear();
|
|
4886
|
-
}
|
|
4887
|
-
/**
|
|
4888
|
-
* Kills `child` and every process it started (docs/usage/operations.md#shutdown). On Windows,
|
|
4889
|
-
* `taskkill /T /F` limited to a few seconds (killing a process there doesn't kill its children;
|
|
4890
|
-
* the orphans of a child that already died are not hunted down, see
|
|
4891
|
-
* docs/implementation/decisions.md#child-process-trees-are-killed-by-the-bridge-not-the-os).
|
|
4892
|
-
* Elsewhere `SIGTERM` to the process group, then `SIGKILL` to whatever is left. Resolves
|
|
4893
|
-
* once `child` has exited, or after a deadline if it can't be killed. Never rejects.
|
|
4894
|
-
* `child` must have been spawned with `treeSpawnOptions`.
|
|
4895
|
-
*/
|
|
4896
|
-
async function killTree(child, options = {}) {
|
|
4897
|
-
const { platform = process.platform, toolTimeoutMs = TOOL_TIMEOUT_MS } = options;
|
|
4898
|
-
const { exitTimeoutMs = TOOL_TIMEOUT_MS, exec: run = exec } = options;
|
|
4899
|
-
const { pid } = child;
|
|
4900
|
-
try {
|
|
4901
|
-
if (pid === void 0) return;
|
|
4902
|
-
const exited = hasExited(child) ? Promise.resolve() : once(child, "exit");
|
|
4903
|
-
if (platform === "win32") {
|
|
4904
|
-
if (!hasExited(child)) await run("taskkill", [
|
|
4905
|
-
"/T",
|
|
4906
|
-
"/F",
|
|
4907
|
-
"/PID",
|
|
4908
|
-
String(pid)
|
|
4909
|
-
], toolTimeoutMs);
|
|
4910
|
-
await within(exited, exitTimeoutMs);
|
|
4911
|
-
return;
|
|
4912
|
-
}
|
|
4913
|
-
killGroup(pid, "SIGTERM");
|
|
4914
|
-
await within(exited, TERM_GRACE_MS);
|
|
4915
|
-
killGroup(pid, "SIGKILL");
|
|
4916
|
-
await within(exited, exitTimeoutMs);
|
|
4917
|
-
} finally {
|
|
4918
|
-
trees.delete(child);
|
|
4919
|
-
}
|
|
4920
|
-
}
|
|
4921
|
-
/** Writes each line of the child's stdout as `info` and of its stderr as `warn`. */
|
|
4922
|
-
function pipeLines(child, output) {
|
|
4923
|
-
if (child.stdout) readline.createInterface({
|
|
4924
|
-
input: child.stdout,
|
|
4925
|
-
crlfDelay: Infinity
|
|
4926
|
-
}).on("line", (line) => output.info(line));
|
|
4927
|
-
if (child.stderr) readline.createInterface({
|
|
4928
|
-
input: child.stderr,
|
|
4929
|
-
crlfDelay: Infinity
|
|
4930
|
-
}).on("line", (line) => output.warn(line));
|
|
5326
|
+
path: PLAYWRIGHT_MCP_PATH,
|
|
5327
|
+
upstreamPath: "/mcp",
|
|
5328
|
+
scheme: "http",
|
|
5329
|
+
target: () => services.reachability("mcp")
|
|
5330
|
+
}];
|
|
5331
|
+
}
|
|
5332
|
+
// src/adapters/shared/net/port-probe.ts
|
|
5333
|
+
/** Where to probe a listener on a wildcard host: the loopback address of that family. */
|
|
5334
|
+
const WILDCARD_PROBE = {
|
|
5335
|
+
"0.0.0.0": "127.0.0.1",
|
|
5336
|
+
"::": "::1"
|
|
5337
|
+
};
|
|
5338
|
+
/** Whether something accepts connections on `host:port`, within `timeoutMs`. */
|
|
5339
|
+
function portOpen(host, port, timeoutMs = 1e3) {
|
|
5340
|
+
return new Promise((resolve) => {
|
|
5341
|
+
const socket = net.connect({
|
|
5342
|
+
host: WILDCARD_PROBE[host] ?? host,
|
|
5343
|
+
port
|
|
5344
|
+
});
|
|
5345
|
+
const done = (open) => {
|
|
5346
|
+
socket.destroy();
|
|
5347
|
+
resolve(open);
|
|
5348
|
+
};
|
|
5349
|
+
socket.setTimeout(timeoutMs, () => done(false));
|
|
5350
|
+
socket.once("connect", () => done(true));
|
|
5351
|
+
socket.once("error", () => done(false));
|
|
5352
|
+
});
|
|
4931
5353
|
}
|
|
4932
5354
|
// src/adapters/out/process/child-process-supervisor.ts
|
|
4933
5355
|
/** How long the port may take to open after the start, before it counts as a crash. */
|
|
@@ -4945,6 +5367,7 @@ var ChildProcessSupervisor = class {
|
|
|
4945
5367
|
state = "stopped";
|
|
4946
5368
|
restarts = 0;
|
|
4947
5369
|
exitCode = null;
|
|
5370
|
+
lastError = null;
|
|
4948
5371
|
crashesInRow = 0;
|
|
4949
5372
|
child = null;
|
|
4950
5373
|
runningSince = null;
|
|
@@ -4969,7 +5392,8 @@ var ChildProcessSupervisor = class {
|
|
|
4969
5392
|
version,
|
|
4970
5393
|
port,
|
|
4971
5394
|
restarts: this.restarts,
|
|
4972
|
-
exitCode: this.exitCode
|
|
5395
|
+
exitCode: this.exitCode,
|
|
5396
|
+
lastError: this.lastError
|
|
4973
5397
|
};
|
|
4974
5398
|
}
|
|
4975
5399
|
start() {
|
|
@@ -4979,6 +5403,7 @@ var ChildProcessSupervisor = class {
|
|
|
4979
5403
|
this.restarts = 0;
|
|
4980
5404
|
this.crashesInRow = 0;
|
|
4981
5405
|
this.exitCode = null;
|
|
5406
|
+
this.lastError = null;
|
|
4982
5407
|
this.launch();
|
|
4983
5408
|
}
|
|
4984
5409
|
return settled;
|
|
@@ -5019,20 +5444,23 @@ var ChildProcessSupervisor = class {
|
|
|
5019
5444
|
this.setState("starting");
|
|
5020
5445
|
this.launchedAt = Date.now();
|
|
5021
5446
|
this.options.logger.info(`starting ${this.options.name} ${settings.version}`);
|
|
5447
|
+
const failed = (how, error) => {
|
|
5448
|
+
if (!current()) return;
|
|
5449
|
+
const cause = `${how}: ${error instanceof Error ? error.message : String(error)}`;
|
|
5450
|
+
this.options.logger.error(`${this.options.name} ${cause}`);
|
|
5451
|
+
this.crashed(null, "failed to start", cause);
|
|
5452
|
+
};
|
|
5022
5453
|
this.options.prepare(settings, abort.signal).then(async (command) => {
|
|
5023
5454
|
if (!current()) return;
|
|
5024
5455
|
if (await portOpen(settings.host, settings.port)) {
|
|
5025
5456
|
if (!current()) return;
|
|
5026
|
-
|
|
5027
|
-
this.
|
|
5457
|
+
const cause = `port ${settings.port} is already in use (a leftover process of an earlier run, or another program)`;
|
|
5458
|
+
this.options.logger.error(`${this.options.name}: ${cause}`);
|
|
5459
|
+
this.crashed(null, "could not start", cause);
|
|
5028
5460
|
return;
|
|
5029
5461
|
}
|
|
5030
5462
|
if (current()) this.spawn(command, settings, generation);
|
|
5031
|
-
}, (error) =>
|
|
5032
|
-
if (!current()) return;
|
|
5033
|
-
this.options.logger.error(`${this.options.name} could not be prepared: ${error instanceof Error ? error.message : String(error)}`);
|
|
5034
|
-
this.crashed(null, "failed to start");
|
|
5035
|
-
});
|
|
5463
|
+
}, (error) => failed("could not be prepared", error)).catch((error) => failed("could not be started", error));
|
|
5036
5464
|
}
|
|
5037
5465
|
spawn(command, settings, generation) {
|
|
5038
5466
|
const current = () => generation === this.generation;
|
|
@@ -5048,6 +5476,7 @@ var ChildProcessSupervisor = class {
|
|
|
5048
5476
|
trackTree(child);
|
|
5049
5477
|
pipeLines(child, this.options.output);
|
|
5050
5478
|
let exited = false;
|
|
5479
|
+
let cause;
|
|
5051
5480
|
const onExit = (code, signal) => {
|
|
5052
5481
|
if (exited) return;
|
|
5053
5482
|
exited = true;
|
|
@@ -5055,12 +5484,16 @@ var ChildProcessSupervisor = class {
|
|
|
5055
5484
|
this.child = null;
|
|
5056
5485
|
killTree(child);
|
|
5057
5486
|
const what = code !== null ? `exited with code ${code}` : signal !== null ? `was killed (${signal})` : "failed to start";
|
|
5058
|
-
this.crashed(code, what);
|
|
5487
|
+
this.crashed(code, what, cause);
|
|
5059
5488
|
};
|
|
5060
5489
|
child.once("exit", onExit);
|
|
5061
5490
|
child.once("error", (error) => {
|
|
5062
|
-
|
|
5063
|
-
|
|
5491
|
+
const failure = `could not be started: ${error.message}`;
|
|
5492
|
+
this.options.logger.error(`${this.options.name} ${failure}`);
|
|
5493
|
+
if (child.pid === void 0) {
|
|
5494
|
+
cause = failure;
|
|
5495
|
+
onExit(null, null);
|
|
5496
|
+
}
|
|
5064
5497
|
});
|
|
5065
5498
|
this.waitForPort(settings, generation, () => exited).then((open) => {
|
|
5066
5499
|
if (!current() || exited) return;
|
|
@@ -5070,7 +5503,8 @@ var ChildProcessSupervisor = class {
|
|
|
5070
5503
|
const seconds = ((Date.now() - this.launchedAt) / 1e3).toFixed(1);
|
|
5071
5504
|
this.options.logger.info(`${this.options.name} running (${seconds}s)`);
|
|
5072
5505
|
} else {
|
|
5073
|
-
|
|
5506
|
+
cause = `did not open port ${settings.port} in time`;
|
|
5507
|
+
this.options.logger.error(`${this.options.name} ${cause}, killing it`);
|
|
5074
5508
|
killTree(child);
|
|
5075
5509
|
}
|
|
5076
5510
|
});
|
|
@@ -5083,11 +5517,13 @@ var ChildProcessSupervisor = class {
|
|
|
5083
5517
|
}
|
|
5084
5518
|
return false;
|
|
5085
5519
|
}
|
|
5086
|
-
|
|
5520
|
+
/** `what` goes to the log, `cause` to the status. */
|
|
5521
|
+
crashed(code, what, cause = what) {
|
|
5087
5522
|
const { name, logger } = this.options;
|
|
5088
5523
|
const ranForMs = this.runningSince === null ? 0 : Date.now() - this.runningSince;
|
|
5089
5524
|
this.runningSince = null;
|
|
5090
5525
|
this.exitCode = code;
|
|
5526
|
+
this.lastError = cause;
|
|
5091
5527
|
const decision = nextAfterCrash(this.crashesInRow, ranForMs, this.options.policy);
|
|
5092
5528
|
this.crashesInRow = decision.crashesInRow;
|
|
5093
5529
|
if (decision.action === "fail") {
|
|
@@ -5411,87 +5847,6 @@ function createSupervisors(config, options, log) {
|
|
|
5411
5847
|
})
|
|
5412
5848
|
};
|
|
5413
5849
|
}
|
|
5414
|
-
// src/composition/ui.ts
|
|
5415
|
-
/** The environment variable the UI's BFF reads the bridge's address from. */
|
|
5416
|
-
const BRIDGE_API_URL_ENV = "SR_BRIDGE_API_URL";
|
|
5417
|
-
/** The header adapter-node reads the request's protocol from (`PROTOCOL_HEADER`). */
|
|
5418
|
-
const PROTOCOL_HEADER = "x-sr-bridge-protocol";
|
|
5419
|
-
/**
|
|
5420
|
-
* The header that tells the UI its page is opened from the bridge's own machine, where the screen
|
|
5421
|
-
* reader would read the live log and feed it back (docs/usage/web-ui.md#accessibility-of-the-ui-itself).
|
|
5422
|
-
* Set (`1`) or removed on every request, so a client can't send it.
|
|
5423
|
-
*/
|
|
5424
|
-
const LOCAL_HEADER = "x-sr-bridge-local";
|
|
5425
|
-
/**
|
|
5426
|
-
* Where the UI's server code finds the bridge log (`packages/ui/src/lib/server/log.ts` reads it):
|
|
5427
|
-
* a `Symbol.for` key on `globalThis`, because the bridge and the UI don't import each other. Its
|
|
5428
|
-
* lines then get the `[web-ui]` prefix, go to the log file and never block on the console.
|
|
5429
|
-
*/
|
|
5430
|
-
const UI_LOGGER_KEY = Symbol.for("screenreader-speech-capture.ui-logger");
|
|
5431
|
-
/**
|
|
5432
|
-
* The UI shipped in `dir` (`handler.js` of the `adapter-node` build). `undefined` when there is
|
|
5433
|
-
* none: the bridge runs from source, or the package was built without the UI.
|
|
5434
|
-
*/
|
|
5435
|
-
function createUiMount(dir, logger) {
|
|
5436
|
-
const file = new URL("handler.js", dir);
|
|
5437
|
-
if (!existsSync(file)) {
|
|
5438
|
-
logger.debug(`no web UI at ${file.pathname}`);
|
|
5439
|
-
return;
|
|
5440
|
-
}
|
|
5441
|
-
let settle;
|
|
5442
|
-
const loaded = new Promise((resolve, reject) => {
|
|
5443
|
-
settle = {
|
|
5444
|
-
resolve,
|
|
5445
|
-
reject
|
|
5446
|
-
};
|
|
5447
|
-
});
|
|
5448
|
-
loaded.catch(() => void 0);
|
|
5449
|
-
return {
|
|
5450
|
-
handler: async (req, res) => {
|
|
5451
|
-
if (new URL(req.url ?? "/", "http://localhost").pathname === "/") {
|
|
5452
|
-
res.writeHead(302, { location: "/ui/" }).end();
|
|
5453
|
-
return;
|
|
5454
|
-
}
|
|
5455
|
-
let handler;
|
|
5456
|
-
try {
|
|
5457
|
-
handler = await loaded;
|
|
5458
|
-
} catch {
|
|
5459
|
-
throw new AppError("SERVICE_UNAVAILABLE", "The web UI failed to start");
|
|
5460
|
-
}
|
|
5461
|
-
req.headers[PROTOCOL_HEADER] = "http";
|
|
5462
|
-
if (isOwnAddress(req.socket?.remoteAddress)) req.headers[LOCAL_HEADER] = "1";
|
|
5463
|
-
else delete req.headers[LOCAL_HEADER];
|
|
5464
|
-
handler(req, res, () => {
|
|
5465
|
-
res.statusCode = 404;
|
|
5466
|
-
res.end();
|
|
5467
|
-
});
|
|
5468
|
-
},
|
|
5469
|
-
async mount(apiUrl) {
|
|
5470
|
-
try {
|
|
5471
|
-
process.env[BRIDGE_API_URL_ENV] = apiUrl;
|
|
5472
|
-
process.env.PROTOCOL_HEADER = PROTOCOL_HEADER;
|
|
5473
|
-
globalThis[UI_LOGGER_KEY] = logger;
|
|
5474
|
-
const module = await import(file.href);
|
|
5475
|
-
if (typeof module.handler !== "function") throw new Error("handler.js has no `handler`");
|
|
5476
|
-
settle.resolve(module.handler);
|
|
5477
|
-
logger.debug(`web UI loaded from ${file.pathname}`);
|
|
5478
|
-
} catch (error) {
|
|
5479
|
-
logger.error(`web UI failed to start: ${error instanceof Error ? error.message : String(error)}`);
|
|
5480
|
-
settle.reject(error);
|
|
5481
|
-
}
|
|
5482
|
-
}
|
|
5483
|
-
};
|
|
5484
|
-
}
|
|
5485
|
-
/** The shipped UI: `ui/` next to the bundled `cli.mjs` (`dist/ui`). */
|
|
5486
|
-
function shippedUiDir() {
|
|
5487
|
-
return new URL("./ui/", import.meta.url);
|
|
5488
|
-
}
|
|
5489
|
-
/**
|
|
5490
|
-
* Where the BFF reaches the bridge's HTTP API: over loopback, whatever address it listens on.
|
|
5491
|
-
*/
|
|
5492
|
-
function bridgeApiUrl(host, port) {
|
|
5493
|
-
return `http://${hostPort(host === "::" ? "::1" : isWildcard(host) ? "127.0.0.1" : host, port)}`;
|
|
5494
|
-
}
|
|
5495
5850
|
// src/domain/capture.ts
|
|
5496
5851
|
/**
|
|
5497
5852
|
* What the capture adapters reported about their listener and connections, for the status. The
|
|
@@ -5855,7 +6210,26 @@ var SpeechLog = class {
|
|
|
5855
6210
|
}
|
|
5856
6211
|
};
|
|
5857
6212
|
// src/main.ts
|
|
6213
|
+
/** The web UI shipped with the package: `ui/` next to the bundled `cli.mjs` (`dist/ui`). */
|
|
6214
|
+
const SHIPPED_UI_DIR = new URL("./ui/", import.meta.url);
|
|
6215
|
+
/**
|
|
6216
|
+
* For an exit that can't wait for `stop()`: ends the child services' process trees at once,
|
|
6217
|
+
* synchronously (docs/usage/operations.md#shutdown).
|
|
6218
|
+
*/
|
|
6219
|
+
function killChildProcessesNow() {
|
|
6220
|
+
killAllTreesNow();
|
|
6221
|
+
}
|
|
6222
|
+
/** Writes out the console output that is still buffered, before the process exits. */
|
|
6223
|
+
async function flushOutput() {
|
|
6224
|
+
await flushTerminal();
|
|
6225
|
+
await flushConsole();
|
|
6226
|
+
}
|
|
5858
6227
|
const show = (value) => JSON.stringify(value);
|
|
6228
|
+
/** A busy port needs no stack: the message says what to do. Anything else is unexpected. */
|
|
6229
|
+
function describeStartFailure(error) {
|
|
6230
|
+
if (error instanceof ListenError || error instanceof PortUnavailableError) return error.message;
|
|
6231
|
+
return error instanceof Error ? error.stack ?? String(error) : String(error);
|
|
6232
|
+
}
|
|
5859
6233
|
/**
|
|
5860
6234
|
* Starts the bridge. An invalid setting rejects with a `ConfigError` before anything starts.
|
|
5861
6235
|
* Any other failure to start is written to the bridge log before the promise rejects, and so is
|
|
@@ -5866,7 +6240,7 @@ async function startBridge(options) {
|
|
|
5866
6240
|
const seams = options.testSeams ?? {};
|
|
5867
6241
|
const store = seams.configStore ?? new FsConfigStore(options.configFile ?? defaultConfigFile());
|
|
5868
6242
|
const sourceOf = (field) => options.overrideSources?.get(field) ?? "a flag or environment variable";
|
|
5869
|
-
const { config, file: savedFile, overrides, unknown: unknownSettings, ignored } = await loadConfig(store, options.overrides, sourceOf);
|
|
6243
|
+
const { config, file: savedFile, overrides, unknown: unknownSettings, ignored, warnings } = await loadConfig(store, options.overrides, sourceOf);
|
|
5870
6244
|
const log = createLogging(config, {
|
|
5871
6245
|
version,
|
|
5872
6246
|
configLocation: store.location,
|
|
@@ -5874,232 +6248,155 @@ async function startBridge(options) {
|
|
|
5874
6248
|
});
|
|
5875
6249
|
const bridgeLogger = log.for("bridge");
|
|
5876
6250
|
const configLogger = log.for("config");
|
|
6251
|
+
for (const warning of warnings) configLogger.warn(warning);
|
|
5877
6252
|
for (const name of ignored) configLogger.warn(`${name}: unknown setting in ${store.location}, ignored`);
|
|
5878
6253
|
for (const { field, file: saved, override } of overriddenFields(savedFile, overrides)) configLogger.warn(`${field}: the config file sets ${show(saved)}, but ${sourceOf(field)} sets ${show(override)}, which wins`);
|
|
5879
|
-
|
|
5880
|
-
|
|
5881
|
-
|
|
5882
|
-
|
|
5883
|
-
|
|
5884
|
-
|
|
5885
|
-
|
|
5886
|
-
|
|
5887
|
-
|
|
5888
|
-
|
|
5889
|
-
|
|
5890
|
-
|
|
5891
|
-
|
|
5892
|
-
|
|
5893
|
-
|
|
5894
|
-
|
|
5895
|
-
|
|
5896
|
-
|
|
5897
|
-
|
|
5898
|
-
|
|
5899
|
-
|
|
5900
|
-
|
|
5901
|
-
|
|
5902
|
-
|
|
5903
|
-
|
|
5904
|
-
|
|
5905
|
-
|
|
5906
|
-
|
|
5907
|
-
|
|
5908
|
-
injector
|
|
5909
|
-
windows
|
|
5910
|
-
|
|
5911
|
-
|
|
5912
|
-
|
|
5913
|
-
|
|
5914
|
-
|
|
5915
|
-
|
|
5916
|
-
|
|
5917
|
-
|
|
5918
|
-
|
|
5919
|
-
|
|
5920
|
-
|
|
5921
|
-
|
|
5922
|
-
|
|
5923
|
-
|
|
5924
|
-
|
|
5925
|
-
|
|
5926
|
-
|
|
5927
|
-
|
|
5928
|
-
|
|
5929
|
-
|
|
5930
|
-
|
|
5931
|
-
|
|
5932
|
-
|
|
5933
|
-
|
|
5934
|
-
|
|
5935
|
-
|
|
5936
|
-
|
|
5937
|
-
|
|
5938
|
-
|
|
5939
|
-
|
|
5940
|
-
|
|
5941
|
-
|
|
5942
|
-
|
|
5943
|
-
|
|
5944
|
-
|
|
5945
|
-
|
|
5946
|
-
|
|
5947
|
-
|
|
5948
|
-
|
|
5949
|
-
|
|
5950
|
-
|
|
5951
|
-
|
|
5952
|
-
|
|
5953
|
-
|
|
5954
|
-
|
|
5955
|
-
|
|
5956
|
-
|
|
5957
|
-
|
|
5958
|
-
|
|
5959
|
-
|
|
5960
|
-
|
|
5961
|
-
|
|
5962
|
-
|
|
5963
|
-
|
|
5964
|
-
|
|
5965
|
-
|
|
5966
|
-
|
|
5967
|
-
|
|
5968
|
-
|
|
5969
|
-
|
|
5970
|
-
|
|
5971
|
-
|
|
5972
|
-
|
|
5973
|
-
|
|
5974
|
-
|
|
6254
|
+
try {
|
|
6255
|
+
const clock = seams.clock ?? new SystemClock();
|
|
6256
|
+
const startedAt = clock.now();
|
|
6257
|
+
const speechLog = new SpeechLog(config.buffer.maxEntries, startedAt.getTime());
|
|
6258
|
+
const events = new InProcessEventBus((error) => bridgeLogger.error(`event listener failed: ${String(error)}`));
|
|
6259
|
+
new TranscriptService({
|
|
6260
|
+
events,
|
|
6261
|
+
transcript: log.for("speech-capture", { channel: "speech" })
|
|
6262
|
+
}).start();
|
|
6263
|
+
const speech = new SpeechService({
|
|
6264
|
+
log: speechLog,
|
|
6265
|
+
events,
|
|
6266
|
+
clock
|
|
6267
|
+
});
|
|
6268
|
+
const shutdown = new AbortController();
|
|
6269
|
+
setMaxListeners(0, shutdown.signal);
|
|
6270
|
+
const waits = new WaitForSpeechService({
|
|
6271
|
+
log: speechLog,
|
|
6272
|
+
events,
|
|
6273
|
+
clock,
|
|
6274
|
+
pace: () => yieldEvery(256),
|
|
6275
|
+
shutdown: shutdown.signal
|
|
6276
|
+
});
|
|
6277
|
+
const sessions = new SessionService({
|
|
6278
|
+
log: speechLog,
|
|
6279
|
+
events,
|
|
6280
|
+
clock,
|
|
6281
|
+
logger: log.for("bridge")
|
|
6282
|
+
});
|
|
6283
|
+
const injector = seams.inputInjector ?? await createInputInjector(log.for("native-input"));
|
|
6284
|
+
const windows = seams.windowSystem ?? await createWindowSystem(log.for("native-input"));
|
|
6285
|
+
const supervisors = createSupervisors(config, seams, log);
|
|
6286
|
+
const input = new NativeInputService({
|
|
6287
|
+
injector,
|
|
6288
|
+
windows,
|
|
6289
|
+
services: supervisors,
|
|
6290
|
+
clock,
|
|
6291
|
+
logger: log.for("native-input"),
|
|
6292
|
+
shutdown: shutdown.signal
|
|
6293
|
+
});
|
|
6294
|
+
const captures = new InputCaptureService({
|
|
6295
|
+
input,
|
|
6296
|
+
log: speechLog,
|
|
6297
|
+
events,
|
|
6298
|
+
clock,
|
|
6299
|
+
pace: () => yieldEvery(256),
|
|
6300
|
+
shutdown: shutdown.signal
|
|
6301
|
+
});
|
|
6302
|
+
const configService = new ConfigService({
|
|
6303
|
+
store,
|
|
6304
|
+
logger: configLogger,
|
|
6305
|
+
active: config,
|
|
6306
|
+
file: savedFile,
|
|
6307
|
+
unknownSettings,
|
|
6308
|
+
pinned: new Map([...configFields(overrides).keys()].map((field) => [field, sourceOf(field)]))
|
|
6309
|
+
});
|
|
6310
|
+
const focus = new WindowFocusService({
|
|
6311
|
+
windows,
|
|
6312
|
+
queue: input,
|
|
6313
|
+
services: supervisors,
|
|
6314
|
+
clock,
|
|
6315
|
+
logger: log.for("native-input")
|
|
6316
|
+
});
|
|
6317
|
+
const childServices = new ChildServicesService({
|
|
6318
|
+
supervisors,
|
|
6319
|
+
config: () => configService.get(),
|
|
6320
|
+
logger: bridgeLogger
|
|
6321
|
+
});
|
|
6322
|
+
const captureState = new CaptureState(() => clock.now());
|
|
6323
|
+
const tcp = new TcpListener(speech, captureState, log.for("speech-capture"));
|
|
6324
|
+
const prompt = seams.prompt === void 0 ? createOperatorPrompt(options.cancelStart) : seams.prompt;
|
|
6325
|
+
const tcpStartup = new TcpStartupService({
|
|
6326
|
+
listener: {
|
|
6327
|
+
start: (port) => tcp.start({
|
|
6328
|
+
...config.tcp,
|
|
6329
|
+
port
|
|
6330
|
+
}),
|
|
6331
|
+
stop: () => tcp.stop()
|
|
6332
|
+
},
|
|
6333
|
+
config: configService,
|
|
6334
|
+
...configFields(overrides).has("tcp.port") ? { pinnedBy: sourceOf("tcp.port") } : {},
|
|
6335
|
+
...prompt === null || prompt === void 0 ? {} : { prompt },
|
|
6336
|
+
configLocation: store.location,
|
|
6337
|
+
logger: configLogger
|
|
6338
|
+
});
|
|
6339
|
+
const status = new StatusService({
|
|
6340
|
+
capture: captureState,
|
|
6341
|
+
log: speechLog,
|
|
6342
|
+
supervisors,
|
|
6343
|
+
config: () => configService.get(),
|
|
6344
|
+
version,
|
|
6345
|
+
apiVersion: API_VERSION,
|
|
6346
|
+
startedAt,
|
|
6347
|
+
injector,
|
|
6348
|
+
windows
|
|
6349
|
+
});
|
|
6350
|
+
const ui = createUiMount(seams.uiDir ?? SHIPPED_UI_DIR, log.for("web-ui"));
|
|
6351
|
+
const http = new HttpServer({
|
|
6352
|
+
speech,
|
|
5975
6353
|
waits,
|
|
6354
|
+
status,
|
|
6355
|
+
config: configService,
|
|
6356
|
+
sessions,
|
|
6357
|
+
input,
|
|
5976
6358
|
captures,
|
|
5977
|
-
|
|
5978
|
-
|
|
5979
|
-
|
|
5980
|
-
|
|
5981
|
-
|
|
5982
|
-
|
|
5983
|
-
{ stop: () => childServices.stopAll() }
|
|
5984
|
-
],
|
|
5985
|
-
readyMessage: () => readySummary({
|
|
5986
|
-
config,
|
|
5987
|
-
ports,
|
|
5988
|
-
supervisors,
|
|
5989
|
-
webUi: ui !== void 0,
|
|
5990
|
-
nativeInput: injector.availability,
|
|
5991
|
-
tookMs: clock.now().getTime() - startedAt.getTime()
|
|
5992
|
-
}),
|
|
5993
|
-
logger: bridgeLogger
|
|
5994
|
-
});
|
|
5995
|
-
lifecycle.start();
|
|
5996
|
-
return {
|
|
5997
|
-
tcpPort: ports.tcp,
|
|
5998
|
-
httpPort: ports.http,
|
|
5999
|
-
speech,
|
|
6000
|
-
sessions,
|
|
6001
|
-
capture: captureState,
|
|
6002
|
-
log: bridgeLogger,
|
|
6003
|
-
stop: (reason) => lifecycle.stop(reason)
|
|
6004
|
-
};
|
|
6005
|
-
}
|
|
6006
|
-
// src/adapters/in/cli/lifecycle.ts
|
|
6007
|
-
const SHUTDOWN_TIMEOUT_MS = 1e4;
|
|
6008
|
-
/** Ctrl+C, `kill`, closing the console window, and Ctrl+Break on Windows. */
|
|
6009
|
-
function shutdownSignals(platform) {
|
|
6010
|
-
const signals = [
|
|
6011
|
-
"SIGINT",
|
|
6012
|
-
"SIGTERM",
|
|
6013
|
-
"SIGHUP"
|
|
6014
|
-
];
|
|
6015
|
-
if (platform === "win32") signals.push("SIGBREAK");
|
|
6016
|
-
return signals;
|
|
6017
|
-
}
|
|
6018
|
-
/** Resolves once everything written to `stream` so far is handed to the OS. */
|
|
6019
|
-
function drain(stream) {
|
|
6020
|
-
return new Promise((resolve) => stream.write("", () => resolve()));
|
|
6021
|
-
}
|
|
6022
|
-
/** Default `flush`: drains stdout and stderr. The log file is written synchronously. */
|
|
6023
|
-
async function flushConsole() {
|
|
6024
|
-
await Promise.all([drain(process.stdout), drain(process.stderr)]);
|
|
6025
|
-
}
|
|
6026
|
-
function describeError(error) {
|
|
6027
|
-
return error instanceof Error ? error.stack ?? String(error) : String(error);
|
|
6028
|
-
}
|
|
6029
|
-
/**
|
|
6030
|
-
* Starts the bridge with `start`, then stops it gracefully and exits the process
|
|
6031
|
-
* (docs/usage/operations.md#shutdown):
|
|
6032
|
-
*
|
|
6033
|
-
* - on a shutdown signal. A second signal exits at once.
|
|
6034
|
-
* - on an uncaught exception or unhandled rejection, which is logged with its stack. Exit code 1.
|
|
6035
|
-
* - if the shutdown takes longer than `timeoutMs`, it exits anyway with code 1.
|
|
6036
|
-
*
|
|
6037
|
-
* The exit code is 0 unless something failed. Console output is flushed before exiting.
|
|
6038
|
-
*
|
|
6039
|
-
* The signal handlers are installed before `start`, so a signal that arrives while the bridge
|
|
6040
|
-
* starts is not fatal: the bridge stops as soon as it has started. Resolves once started; rejects
|
|
6041
|
-
* like `start`.
|
|
6042
|
-
*/
|
|
6043
|
-
async function runUntilStopped(start, proc, options = {}) {
|
|
6044
|
-
const { timeoutMs = SHUTDOWN_TIMEOUT_MS, flush = flushConsole, onForcedExit } = options;
|
|
6045
|
-
let bridge = void 0;
|
|
6046
|
-
/** A signal that arrived before the bridge had started. */
|
|
6047
|
-
let early;
|
|
6048
|
-
let stopping = false;
|
|
6049
|
-
let exiting = false;
|
|
6050
|
-
let exitCode = 0;
|
|
6051
|
-
let watchdog;
|
|
6052
|
-
/** Ends the child processes the graceful stop didn't get to. */
|
|
6053
|
-
const killLeftovers = () => {
|
|
6054
|
-
try {
|
|
6055
|
-
onForcedExit?.();
|
|
6056
|
-
} catch {}
|
|
6057
|
-
};
|
|
6058
|
-
const forceExit = (code) => {
|
|
6059
|
-
killLeftovers();
|
|
6060
|
-
proc.exit(code);
|
|
6061
|
-
};
|
|
6062
|
-
const exit = (code) => {
|
|
6063
|
-
if (exiting) return forceExit(code);
|
|
6064
|
-
exiting = true;
|
|
6065
|
-
flush().catch(() => void 0).then(() => {
|
|
6066
|
-
clearTimeout(watchdog);
|
|
6067
|
-
proc.exit(code);
|
|
6359
|
+
focus,
|
|
6360
|
+
logger: log.for("http-api"),
|
|
6361
|
+
hostnames: [hostname()],
|
|
6362
|
+
proxies: proxyRoutes(childServices),
|
|
6363
|
+
...ui ? { ui: ui.handler } : {},
|
|
6364
|
+
...seams.ssePingMs === void 0 ? {} : { pingMs: seams.ssePingMs }
|
|
6068
6365
|
});
|
|
6069
|
-
|
|
6070
|
-
|
|
6071
|
-
|
|
6072
|
-
|
|
6073
|
-
|
|
6074
|
-
|
|
6075
|
-
|
|
6076
|
-
|
|
6077
|
-
|
|
6078
|
-
|
|
6079
|
-
|
|
6080
|
-
|
|
6081
|
-
|
|
6082
|
-
|
|
6083
|
-
|
|
6084
|
-
|
|
6085
|
-
|
|
6086
|
-
|
|
6087
|
-
|
|
6088
|
-
|
|
6089
|
-
|
|
6090
|
-
|
|
6091
|
-
|
|
6092
|
-
|
|
6093
|
-
|
|
6094
|
-
|
|
6095
|
-
|
|
6096
|
-
|
|
6097
|
-
|
|
6098
|
-
|
|
6099
|
-
}
|
|
6100
|
-
|
|
6101
|
-
|
|
6102
|
-
|
|
6366
|
+
const lifecycle = new BridgeLifecycleService({
|
|
6367
|
+
state: status,
|
|
6368
|
+
tcp: tcpStartup,
|
|
6369
|
+
http: {
|
|
6370
|
+
start: () => http.start(config.http),
|
|
6371
|
+
stop: () => http.stop()
|
|
6372
|
+
},
|
|
6373
|
+
httpListening: async (port) => ui?.mount(bridgeApiUrl(config.http.host, port)),
|
|
6374
|
+
services: childServices,
|
|
6375
|
+
shutdown,
|
|
6376
|
+
readyMessage: (ports) => readySummary({
|
|
6377
|
+
config: configService.get(),
|
|
6378
|
+
ports,
|
|
6379
|
+
supervisors,
|
|
6380
|
+
webUi: ui !== void 0,
|
|
6381
|
+
nativeInput: injector.availability,
|
|
6382
|
+
tookMs: clock.now().getTime() - startedAt.getTime()
|
|
6383
|
+
}),
|
|
6384
|
+
logger: bridgeLogger
|
|
6385
|
+
});
|
|
6386
|
+
const ports = await lifecycle.start();
|
|
6387
|
+
return {
|
|
6388
|
+
tcpPort: ports.tcp,
|
|
6389
|
+
httpPort: ports.http,
|
|
6390
|
+
speech,
|
|
6391
|
+
sessions,
|
|
6392
|
+
capture: captureState,
|
|
6393
|
+
log: bridgeLogger,
|
|
6394
|
+
stop: (reason) => lifecycle.stop(reason)
|
|
6395
|
+
};
|
|
6396
|
+
} catch (error) {
|
|
6397
|
+
bridgeLogger.error(describeStartFailure(error));
|
|
6398
|
+
throw error;
|
|
6399
|
+
}
|
|
6103
6400
|
}
|
|
6104
6401
|
// src/adapters/in/cli/options.ts
|
|
6105
6402
|
const SETTINGS = [
|
|
@@ -6343,22 +6640,21 @@ if (options.version) {
|
|
|
6343
6640
|
process.exit(0);
|
|
6344
6641
|
}
|
|
6345
6642
|
try {
|
|
6346
|
-
await runUntilStopped(() => startBridge({
|
|
6643
|
+
await runUntilStopped((cancelStart) => startBridge({
|
|
6347
6644
|
version,
|
|
6645
|
+
cancelStart,
|
|
6348
6646
|
overrides: options.overrides,
|
|
6349
6647
|
overrideSources: options.sources,
|
|
6350
6648
|
...options.configFile === void 0 ? {} : { configFile: options.configFile }
|
|
6351
6649
|
}), process, {
|
|
6352
|
-
onForcedExit:
|
|
6353
|
-
flush:
|
|
6354
|
-
await flushTerminal();
|
|
6355
|
-
await flushConsole();
|
|
6356
|
-
}
|
|
6650
|
+
onForcedExit: killChildProcessesNow,
|
|
6651
|
+
flush: flushOutput
|
|
6357
6652
|
});
|
|
6358
6653
|
} catch (error) {
|
|
6359
6654
|
if (error instanceof ConfigError) fail(error.message);
|
|
6360
|
-
|
|
6361
|
-
|
|
6655
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
6656
|
+
process.stderr.write(`screenreader-speech-capture-bridge: failed to start: ${reason}\n`);
|
|
6657
|
+
await flushOutput();
|
|
6362
6658
|
process.exit(1);
|
|
6363
6659
|
}
|
|
6364
6660
|
export {};
|