pi-webapp 0.1.57 → 0.1.58-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/bin/launcher-diagnostics.mjs +179 -0
  2. package/bin/launcher-logs.mjs +145 -0
  3. package/bin/pi-webapp.mjs +183 -39
  4. package/dist/extension.js +71 -71
  5. package/dist/hosted-recovery.js +2 -2
  6. package/dist/hosted-worker.js +2 -2
  7. package/docs/desktop.md +16 -5
  8. package/package.json +3 -2
  9. package/web/dist/.vite/manifest.json +80 -64
  10. package/web/dist/assets/{MarkdownText-Ca6_qCyr.js → MarkdownText-BmWua1fx.js} +11 -11
  11. package/web/dist/assets/WorkspacePanel.module-q1UBTZQr.js +2 -0
  12. package/web/dist/assets/app-Bl_vjH4f.js +53 -0
  13. package/web/dist/assets/app.css +1 -1
  14. package/web/dist/assets/app.js +4 -4
  15. package/web/dist/assets/{code-editor-B5kVAtku.js → code-editor-bWuZTiS2.js} +4 -4
  16. package/web/dist/assets/{icons-D8yiYkWB.js → code-file-types-BZAEsqNG.js} +3 -3
  17. package/web/dist/assets/{dist-CWWynAS-.js → dist-B8Mp_VTU.js} +2 -2
  18. package/web/dist/assets/{dist-o-4nubru.js → dist-BD_2QeWa.js} +2 -2
  19. package/web/dist/assets/{dist-Im2q9dJ0.js → dist-C2WSXtwq.js} +2 -2
  20. package/web/dist/assets/{dist-BRYLL4VU.js → dist-C7kRRV1b.js} +2 -2
  21. package/web/dist/assets/{dist-CaNhruaD.js → dist-CCfANS3F.js} +2 -2
  22. package/web/dist/assets/{dist-BFhI7cEI.js → dist-CP5SBgQB.js} +2 -2
  23. package/web/dist/assets/{dist-DAlictfL.js → dist-CmPE8_f_.js} +2 -2
  24. package/web/dist/assets/{dist-CszBAiM6.js → dist-D-nx7RRS.js} +2 -2
  25. package/web/dist/assets/{dist-BYJ4SXpR.js → dist-DFTCmV51.js} +2 -2
  26. package/web/dist/assets/{dist-CsFhAvz7.js → dist-Dr0qO3Zr.js} +2 -2
  27. package/web/dist/assets/{dist-CqXTRhJp.js → dist-Nlb4zANG.js} +2 -2
  28. package/web/dist/assets/{graphql-Cz1_wnUp.js → graphql-B5jxVvgN.js} +2 -2
  29. package/web/dist/assets/{http-CTlzQwRP.js → http-C6M1fy61.js} +2 -2
  30. package/web/dist/assets/{php-BHNgHgMp.js → php-B61pLHqK.js} +2 -2
  31. package/web/dist/assets/{plugin-D1z0mcl1.js → plugin-CE1WaS8V.js} +4 -4
  32. package/web/dist/assets/plugin-CsVaeNQM.js +6 -0
  33. package/web/dist/assets/plugin-Cyidq4oP.js +2 -0
  34. package/web/dist/assets/plugin-Gwwlx9MU.js +4 -0
  35. package/web/dist/assets/plugin.css +1 -1
  36. package/web/dist/assets/plugin2.css +1 -1
  37. package/web/dist/assets/plugin3.css +1 -0
  38. package/web/dist/assets/{rst-BdGjFUxD.js → rst-950N-2sy.js} +2 -2
  39. package/web/dist/assets/{ruby-D7-ny0V-.js → ruby-Qm2HAXfx.js} +2 -2
  40. package/web/dist/assets/{svelte-DoD3sicb.js → svelte-CoZSSs0h.js} +2 -2
  41. package/web/dist/assets/{vue-BYLUelN7.js → vue-as6FrWIW.js} +2 -2
  42. package/web/dist/assets/WorkspacePanel.module-V6gI-nG1.js +0 -2
  43. package/web/dist/assets/app-CIlV3hYO.js +0 -49
  44. package/web/dist/assets/plugin-CZx51rmJ.js +0 -6
  45. package/web/dist/assets/plugin-CvqNiFRV.js +0 -4
@@ -0,0 +1,179 @@
1
+ import { constants } from "node:fs";
2
+ import { access, lstat, stat } from "node:fs/promises";
3
+ import { get } from "node:http";
4
+ import { createServer } from "node:net";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { parseVersion } from "../desktop/release-version.mjs";
7
+
8
+ const loopback = "127.0.0.1";
9
+ const healthTimeoutMs = 1000;
10
+ const maxHealthBytes = 16 * 1024;
11
+ const minimumNode = [22, 19, 0]; // package.json engines.node
12
+ const minimumPi = [0, 87, 1]; // launcher Pi admission floor
13
+
14
+ function validPid(pid) {
15
+ return Number.isInteger(pid) && pid > 0 && pid <= 0x7fffffff;
16
+ }
17
+
18
+ function isAlive(pid) {
19
+ if (!validPid(pid)) return false;
20
+ try { process.kill(pid, 0); return true; }
21
+ catch (error) { return error?.code === "EPERM"; }
22
+ }
23
+
24
+ function validHost(host) {
25
+ return host === loopback || host === "0.0.0.0";
26
+ }
27
+
28
+ function safeVersion(value) {
29
+ try { parseVersion(value); return value; }
30
+ catch { return null; }
31
+ }
32
+
33
+ function localAddress(value) {
34
+ if (typeof value !== "string") return null;
35
+ try {
36
+ const url = new URL(value);
37
+ if (url.protocol === "http:" && url.hostname === loopback && !url.username && !url.password && url.port !== "0") return url;
38
+ } catch { /* Malformed or absent address. */ }
39
+ return null;
40
+ }
41
+
42
+ async function probeHealth(url) {
43
+ const token = url.hash.slice(1);
44
+ if (!/^[A-Za-z0-9_-]{1,256}$/.test(token)) return null;
45
+ try {
46
+ // Use the authenticated readiness route used by desktop. Connect directly
47
+ // to loopback (no shared agent, proxy, redirects, or saved path/query).
48
+ const response = await new Promise((resolveResponse, reject) => {
49
+ get({ hostname: loopback, port: url.port || 80, path: "/api/update/version", agent: false,
50
+ headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(healthTimeoutMs) }, resolveResponse)
51
+ .on("error", reject);
52
+ });
53
+ if (response.statusCode !== 200) {
54
+ response.destroy();
55
+ return null;
56
+ }
57
+ // The request deadline also covers a stalled response body.
58
+ const chunks = [];
59
+ let bytes = 0;
60
+ for await (const chunk of response) {
61
+ bytes += chunk.length;
62
+ if (bytes > maxHealthBytes) return null;
63
+ chunks.push(chunk);
64
+ }
65
+ return safeVersion(JSON.parse(Buffer.concat(chunks).toString("utf8"))?.current);
66
+ } catch { return null; }
67
+ }
68
+
69
+ /** Print one JSON object. Accepts raw state, null, or the launcher's starting sentinel. */
70
+ export async function showStatus({ state, cliVersion }) {
71
+ const pid = validPid(state?.pid) ? state.pid : null;
72
+ const stopped = state == null || (pid !== null && !isAlive(pid));
73
+ const starting = !stopped && state.starting === true;
74
+ const address = !stopped && !starting ? localAddress(state.url) : null;
75
+ const current = address && pid !== null ? await probeHealth(address) : null;
76
+ console.log(JSON.stringify({
77
+ status: stopped ? "stopped" : starting ? "starting" : current ? "healthy" : "unhealthy",
78
+ pid: stopped ? null : pid,
79
+ piPid: !stopped && validPid(state.piPid) ? state.piPid : null,
80
+ listenHost: !stopped && validHost(state.listenHost) ? state.listenHost : address ? loopback : null,
81
+ port: address ? Number(address.port || 80) : null,
82
+ runningVersion: stopped ? null : current ?? safeVersion(state.version),
83
+ cliVersion,
84
+ url: address ? `${address.origin}/` : null,
85
+ }));
86
+ }
87
+
88
+ function doctorArgs(args) {
89
+ let host, port;
90
+ for (let i = 0; i < args.length; i++) {
91
+ const match = /^(--host|--port)(?:=(.*))?$/.exec(args[i]);
92
+ if (!match) throw new Error("用法:pi-webapp doctor [--port <1–65535>] [--host <127.0.0.1|0.0.0.0>]");
93
+ const value = match[2] ?? args[++i];
94
+ if (match[1] === "--host") {
95
+ if (host !== undefined) throw new Error("--host 只能指定一次");
96
+ if (!validHost(value)) throw new Error("--host 必须是 127.0.0.1 或 0.0.0.0");
97
+ host = value;
98
+ } else {
99
+ if (port !== undefined) throw new Error("--port 只能指定一次");
100
+ if (!/^\d+$/.test(value ?? "") || Number(value) < 1 || Number(value) > 65535) throw new Error("--port 必须是 1–65535 之间的整数");
101
+ port = Number(value);
102
+ }
103
+ }
104
+ return { host: host ?? loopback, port };
105
+ }
106
+
107
+ function versionCheck(version, minimum) {
108
+ const match = typeof version === "string" && /^v?(\d+)\.(\d+)\.(\d+)/.exec(version.trim());
109
+ const parts = match ? match.slice(1).map(Number) : [];
110
+ if (parts.length !== 3 || !parts.every(Number.isSafeInteger)) return [false, `版本无效(需要 ${minimum.join(".")} 或更新版本)`];
111
+ const difference = parts.map((part, i) => part - minimum[i]).find(value => value !== 0) ?? 0;
112
+ return [difference >= 0, `${parts.join(".")}(需要 ${minimum.join(".")} 或更新版本)`];
113
+ }
114
+
115
+ async function directoryCheck(path) {
116
+ const target = resolve(path);
117
+ let dir = target;
118
+ try {
119
+ for (;;) {
120
+ const entry = await lstat(dir).catch(error => {
121
+ if (error?.code === "ENOENT") return null;
122
+ throw error;
123
+ });
124
+ if (entry) {
125
+ const info = entry.isSymbolicLink() ? await stat(dir) : entry;
126
+ if (!info.isDirectory()) return [false, `${dir} 不是目录`];
127
+ await access(dir, constants.R_OK | constants.W_OK | constants.X_OK);
128
+ return [true, dir === target ? `${dir} 可读写` : `${target} 不存在;上级目录 ${dir} 可读写`];
129
+ }
130
+ const parent = dirname(dir);
131
+ if (parent === dir) return [false, `${target} 无法访问`];
132
+ dir = parent;
133
+ }
134
+ } catch (error) { return [false, `${dir} 无法访问(${error?.code ?? "未知错误"})`]; }
135
+ }
136
+
137
+ function bindPort(host, port) {
138
+ return new Promise((resolveCheck, reject) => {
139
+ const server = createServer(socket => socket.destroy());
140
+ server.once("error", reject);
141
+ server.listen({ host, port, exclusive: true }, () => server.close(error => error ? reject(error) : resolveCheck()));
142
+ });
143
+ }
144
+
145
+ /** Print checks and return whether they all passed. Invalid arguments throw. */
146
+ export async function showDoctor({ args = [], readState, agentDir, probePi }) {
147
+ const { host, port } = doctorArgs(args);
148
+ let allGood = true;
149
+ function report(name, ok, detail) {
150
+ allGood &&= ok;
151
+ console.log(`[${ok ? "OK" : "FAIL"}] ${name}: ${detail}`);
152
+ }
153
+
154
+ report("Node.js", ...versionCheck(process.versions.node, minimumNode));
155
+ try {
156
+ const version = await probePi();
157
+ if (version == null) report("Pi", false, "未找到 Pi");
158
+ else report("Pi", ...versionCheck(version, minimumPi));
159
+ } catch { report("Pi", false, "无法运行 Pi --version"); }
160
+
161
+ report("Agent directory", ...await directoryCheck(agentDir));
162
+ report("Launcher directory", ...await directoryCheck(join(agentDir, "pi-web")));
163
+
164
+ try {
165
+ const state = await readState();
166
+ if (state == null) report("Launcher state", true, "没有状态文件");
167
+ else if (!validPid(state.pid)) report("Launcher state", false, "状态文件中的 PID 无效");
168
+ else if (!isAlive(state.pid)) report("Launcher state", false, `状态文件已过期:PID ${state.pid} 未运行`);
169
+ else report("Launcher state", true, `PID ${state.pid} 正在运行`);
170
+ } catch { report("Launcher state", false, "无法读取状态文件"); }
171
+
172
+ if (port !== undefined) {
173
+ try {
174
+ await bindPort(host, port);
175
+ report("Port", true, `${host}:${port} 可绑定`);
176
+ } catch (error) { report("Port", false, `${host}:${port} 无法绑定(${error?.code ?? "未知错误"})`); }
177
+ }
178
+ return allGood;
179
+ }
@@ -0,0 +1,145 @@
1
+ import { open } from "node:fs/promises";
2
+ import { setTimeout as delay } from "node:timers/promises";
3
+
4
+ const BLOCK_SIZE = 64 * 1024;
5
+ const BYTE_LIMIT = 4 * 1024 * 1024;
6
+ const LF = 0x0a;
7
+
8
+ function parseArgs(args) {
9
+ let tail;
10
+ let follow = false;
11
+ for (let i = 0; i < args.length; i++) {
12
+ const arg = args[i];
13
+ if (arg === "--follow") follow = true;
14
+ else if (arg === "--tail" || arg.startsWith("--tail=")) {
15
+ if (tail !== undefined) throw new Error("--tail can only be specified once");
16
+ const value = arg === "--tail" ? args[++i] : arg.slice("--tail=".length);
17
+ if (value === undefined || !/^\d+$/.test(value) || !Number.isSafeInteger(Number(value))) {
18
+ throw new Error("--tail requires a non-negative integer");
19
+ }
20
+ tail = Number(value);
21
+ } else throw new Error(`Unknown logs option: ${arg}`);
22
+ }
23
+ return { tail: tail ?? 100, follow };
24
+ }
25
+
26
+ function redact(text) {
27
+ return text
28
+ .replace(/(\/#)[^\s"'<>\\)\]},]+/g, "$1[REDACTED]")
29
+ .replace(/(\b(?:proxy-)?authorization["']?[ \t]*[:=][ \t]*["']?(?:(?:bearer|basic|token)[ \t]+)?|\bbearer[ \t]+)[A-Za-z0-9._~+/%=-]+/gi, "$1[REDACTED]")
30
+ .replace(/(\b(?:PI_WEBAPP_RESTART_TOKEN|(?:x[-_])?(?:pi[-_]?web[-_]?(?:app[-_]?)?)?(?:auth[-_]?|access[-_]?)?token)["']?[ \t]*[:=][ \t]*["']?)[A-Za-z0-9._~+/%=-]+/gi, "$1[REDACTED]");
31
+ }
32
+
33
+ async function print(bytes) {
34
+ if (!bytes.length) return;
35
+ await new Promise((resolve, reject) => {
36
+ process.stdout.write(redact(bytes.toString("utf8")), error => error ? reject(error) : resolve());
37
+ });
38
+ }
39
+
40
+ async function readTail(file, size, lines, follow) {
41
+ const empty = Buffer.alloc(0);
42
+ if (!lines) {
43
+ // An append may finish a line that --tail 0 explicitly excluded.
44
+ if (!follow || !size) return { bytes: empty, discard: false };
45
+ const last = Buffer.alloc(1);
46
+ const { bytesRead } = await file.read(last, 0, 1, size - 1);
47
+ return { bytes: empty, discard: bytesRead === 1 && last[0] !== LF };
48
+ }
49
+
50
+ const floor = Math.max(0, size - BYTE_LIMIT);
51
+ const chunks = [];
52
+ let end = size;
53
+ while (end > floor) {
54
+ const start = Math.max(floor, end - BLOCK_SIZE);
55
+ const chunk = Buffer.allocUnsafe(end - start);
56
+ const { bytesRead } = await file.read(chunk, 0, chunk.length, start);
57
+ if (bytesRead !== chunk.length) throw new Error("Launcher log changed while reading; please retry");
58
+ // Ignore the final LF: it terminates a line, rather than starting an empty one.
59
+ let index = chunk.length - (end === size ? 2 : 1);
60
+ while (index >= 0) {
61
+ const newline = chunk.lastIndexOf(LF, index);
62
+ if (newline < 0) break;
63
+ if (--lines === 0) {
64
+ chunks.push(chunk.subarray(newline + 1));
65
+ return { bytes: Buffer.concat(chunks.reverse()), discard: false };
66
+ }
67
+ index = newline - 1;
68
+ }
69
+ chunks.push(chunk);
70
+ end = start;
71
+ }
72
+
73
+ const bytes = Buffer.concat(chunks.reverse());
74
+ if (!floor) return { bytes, discard: false };
75
+ // Never emit a clipped first line: its credential prefix may be missing.
76
+ console.error("Launcher log tail limited to the last 4 MiB");
77
+ const newline = bytes.indexOf(LF);
78
+ return newline < 0 ? { bytes: empty, discard: true } : { bytes: bytes.subarray(newline + 1), discard: false };
79
+ }
80
+
81
+ async function followLog(file, offset, { bytes, discard }) {
82
+ let pending = [];
83
+ let pendingSize = 0;
84
+ const resetLine = () => {
85
+ pending = [];
86
+ pendingSize = 0;
87
+ discard = false;
88
+ };
89
+ const accept = async (chunk) => {
90
+ const first = chunk.indexOf(LF);
91
+ if (first >= 0) {
92
+ const end = chunk.lastIndexOf(LF) + 1;
93
+ if (!discard && pendingSize + first + 1 <= BYTE_LIMIT) {
94
+ const head = pending.length ? Buffer.concat([...pending, chunk.subarray(0, first + 1)]) : chunk.subarray(0, first + 1);
95
+ await print(head);
96
+ }
97
+ await print(chunk.subarray(first + 1, end));
98
+ resetLine();
99
+ chunk = chunk.subarray(end);
100
+ }
101
+ if (!discard && chunk.length) {
102
+ // Wait for the line to finish so split UTF-8 or credentials stay together.
103
+ pendingSize += chunk.length;
104
+ if (pendingSize < BYTE_LIMIT) pending.push(Buffer.from(chunk));
105
+ else {
106
+ resetLine();
107
+ discard = true;
108
+ }
109
+ }
110
+ };
111
+
112
+ await accept(bytes);
113
+ const buffer = Buffer.allocUnsafe(BLOCK_SIZE);
114
+ for (;;) {
115
+ const { size } = await file.stat();
116
+ if (size < offset) {
117
+ offset = 0;
118
+ resetLine();
119
+ }
120
+ if (size > offset) {
121
+ const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.length, size - offset), offset);
122
+ if (bytesRead) {
123
+ offset += bytesRead;
124
+ await accept(buffer.subarray(0, bytesRead));
125
+ continue;
126
+ }
127
+ }
128
+ await delay(100);
129
+ }
130
+ }
131
+
132
+ /** Read the existing launcher log. Pass the CLI arguments after `logs`. */
133
+ export async function showLogs(logPath, args = []) {
134
+ const { tail, follow } = parseArgs(args);
135
+ const file = await open(logPath, "r");
136
+ try {
137
+ const stat = await file.stat();
138
+ if (!stat.isFile()) throw new Error("Launcher log is not a regular file");
139
+ const initial = await readTail(file, stat.size, tail, follow);
140
+ if (follow) await followLog(file, stat.size, initial);
141
+ else await print(initial.bytes);
142
+ } finally {
143
+ await file.close();
144
+ }
145
+ }