texlite 0.16.0 → 0.17.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/DESIGN.md +87 -5
- package/OPERATIONS.md +27 -0
- package/dist/client/assets/AdminUsers-5cAOkdRO.js +1 -0
- package/dist/client/assets/CitationLibraryDialog-G2kKkA2f.js +1 -0
- package/dist/client/assets/Dashboard-BJDFbzQa.js +5 -0
- package/dist/client/assets/GitDialog-BEtLh2S_.js +3 -0
- package/dist/client/assets/GitHubAccountDialog-D2kdCzOs.js +1 -0
- package/dist/client/assets/{HistoryDialog-DWYErBwj.js → HistoryDialog-BwxDdj-j.js} +3 -3
- package/dist/client/assets/LatexEditor-sMjmvA6V.js +141 -0
- package/dist/client/assets/{PdfPreview-BjghzUb1.js → PdfPreview-z5KnowpL.js} +1 -1
- package/dist/client/assets/ProjectIconPickerDialog-DNV7M7vH.js +1 -0
- package/dist/client/assets/ProjectSettings-Mf8zDGRu.js +1 -0
- package/dist/client/assets/ProjectWorkspace-BJFxjMCn.js +32 -0
- package/dist/client/assets/QuickOpenDialog-C758pouQ.js +1 -0
- package/dist/client/assets/{SelectionHistoryDialog-CR5c3I8k.js → SelectionHistoryDialog-p8L2n4RS.js} +2 -2
- package/dist/client/assets/SystemMetricsDialog-DDiSuglF.js +1 -0
- package/dist/client/assets/TagManagementDialog-BTVERmQS.js +1 -0
- package/dist/client/assets/WordCountDialog-B6RvAI6V.js +1 -0
- package/dist/client/assets/check-Hlb-tLSh.js +1 -0
- package/dist/client/assets/chevron-up-D0psXvTv.js +1 -0
- package/dist/client/assets/chktex-ZnIx425m.js +3 -0
- package/dist/client/assets/clock-3-C71NmJZI.js +1 -0
- package/dist/client/assets/{editor-CLY5CgkY.js → editor-_i6aPXT4.js} +1 -1
- package/dist/client/assets/eye-swovgNYS.js +1 -0
- package/dist/client/assets/github-y6i0qxSV.js +1 -0
- package/dist/client/assets/{hard-drive-Ctj3K_zx.js → hard-drive-BqcHPdoY.js} +1 -1
- package/dist/client/assets/index-7WrjzKvC.js +5 -0
- package/dist/client/assets/index-C5T8_lAl.js +1 -0
- package/dist/client/assets/index-DF5cor0N.js +10 -0
- package/dist/client/assets/index-Do5FsFqg.js +1 -0
- package/dist/client/assets/index-Y-wXUwwe.css +1 -0
- package/dist/client/assets/{minimize-2-BiVyoWZA.js → minimize-2-CK7jUy7-.js} +1 -1
- package/dist/client/assets/{minus-Bl8l4LXq.js → minus-B2sswwWT.js} +1 -1
- package/dist/client/assets/{plus-CCxK-HNt.js → plus-Co7iyp5m.js} +1 -1
- package/dist/client/assets/{refresh-cw-BE8IbaHI.js → refresh-cw-BHVcjInn.js} +1 -1
- package/dist/client/assets/{search-CPbhRWQE.js → search-Tpi6WAga.js} +1 -1
- package/dist/client/assets/{sigma-LxGD9tK2.js → sigma-DoHJQYf7.js} +1 -1
- package/dist/client/assets/spellCheck-BSbFJY9f.js +1 -0
- package/dist/client/assets/{tags-DuN89PsZ.js → tags-BHDlIcSb.js} +1 -1
- package/dist/client/assets/{type-BiettCiY.js → type-C-6Jq_0r.js} +1 -1
- package/dist/client/index.html +15 -3
- package/dist/server/app.js +6 -1
- package/dist/server/cgroups.js +35 -0
- package/dist/server/compilerVersions.js +46 -0
- package/dist/server/config.js +8 -0
- package/dist/server/cpuMetrics.js +122 -0
- package/dist/server/db.js +13 -0
- package/dist/server/environment.js +11 -0
- package/dist/server/i18n.js +0 -2
- package/dist/server/resourceMetrics.js +214 -0
- package/dist/server/routes/projectFiles.js +1 -59
- package/dist/server/routes/system.js +32 -1
- package/dist/server/systemMemory.js +51 -0
- package/dist/server/updates.js +116 -0
- package/dist/shared/compilerVersions.js +11 -0
- package/dist/shared/resourceMetrics.js +1 -0
- package/dist/shared/updates.js +5 -0
- package/package.json +3 -1
- package/texlite.config.example.json +3 -0
- package/dist/client/assets/AdminUsers-Dyapv-3c.js +0 -1
- package/dist/client/assets/CitationLibraryDialog-CU7Q7r0Z.js +0 -1
- package/dist/client/assets/Dashboard-DsdhFENx.js +0 -2
- package/dist/client/assets/GitDialog-CZpnKw-J.js +0 -3
- package/dist/client/assets/GitHubAccountDialog-CZ8O_PjD.js +0 -1
- package/dist/client/assets/LatexEditor-CssVgypt.js +0 -141
- package/dist/client/assets/ProjectIconPickerDialog-CqRmgFBM.js +0 -1
- package/dist/client/assets/ProjectNavigationDialogs-BZxI3PJO.js +0 -1
- package/dist/client/assets/ProjectSettings-CZE_xDKn.js +0 -1
- package/dist/client/assets/ProjectWorkspace-CAX3qEYr.js +0 -32
- package/dist/client/assets/SystemMetricsDialog-DDpFwgXh.js +0 -1
- package/dist/client/assets/TagManagementDialog-CXLA9h_j.js +0 -1
- package/dist/client/assets/WordCountDialog-DUyR24vv.js +0 -1
- package/dist/client/assets/check-CwBYzomT.js +0 -1
- package/dist/client/assets/chevron-up-D5lCNKlk.js +0 -1
- package/dist/client/assets/chktex-CRkLYKcV.js +0 -3
- package/dist/client/assets/external-link-C9Td1CCj.js +0 -1
- package/dist/client/assets/github-D-JDXb-w.js +0 -1
- package/dist/client/assets/index-9hnQ8Q9x.js +0 -5
- package/dist/client/assets/index-C0qg2Ylw.css +0 -1
- package/dist/client/assets/index-DkpU9Fgs.js +0 -10
- package/dist/client/assets/index-_eYe7K9T.js +0 -1
- package/dist/client/assets/spellCheck-hpm8qZTr.js +0 -1
- package/dist/client/assets/x-C_3swJOC.js +0 -1
- package/dist/server/projectSearch.js +0 -113
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as w,A as L}from"./index-DF5cor0N.js";import{s as y,c as S}from"./ProjectWorkspace-BJFxjMCn.js";import"./react-CltQJflK.js";import"./index-C5T8_lAl.js";import"./check-Hlb-tLSh.js";import"./index-Do5FsFqg.js";import"./chevron-up-D0psXvTv.js";import"./refresh-cw-BHVcjInn.js";const k=5,f=new Map,C=12,x=S();let E=0;class p extends Error{constructor(){super("A newer writing check replaced this request."),this.name="HarperLintSupersededError"}}function I(e){return e instanceof p}function $(e){const t=[0];let r=0;for(const n of e)r+=n.length,t.push(r);return t}function d(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort((t,r)=>t.localeCompare(r)).join("\0")}async function v(e,t,r,n){try{return(await w(`/api/projects/${e}/spellcheck`,{method:"POST",body:JSON.stringify({path:t,source:r,clientId:x,sequence:n})})).lints}catch(o){throw o instanceof L&&o.code==="SPELLCHECK_SUPERSEDED"?new p:o}}function A(e,t,r){if(!t.problem)return null;const n={from:t.start,to:t.end},o={from:r[t.start]??-1,to:r[t.end]??-1},i=c=>c.from>=0&&c.to>c.from&&c.to<=e.length,a=c=>i(c)&&e.slice(c.from,c.to)===t.problem;return a(o)?o:a(n)?n:null}function H(e,t,r){const n=A(e,t,r);if(!n)return null;const{from:o,to:i}=n,a=e.slice(o,i);if(!a.trim()||!/[A-Za-z]/.test(a)||t.kind==="Formatting")return null;const c=t.kind==="Spelling"||t.kind==="Typo"?"spelling":"grammar",u=t.suggestions.filter((m,s,l)=>s<k&&l.indexOf(m)===s);return{from:o,to:i,word:a,kind:c,message:t.message,suggestions:u}}function h(e,t){let r=2166136261;for(let n=0;n<t.length;n+=1)r^=t.charCodeAt(n),r=Math.imul(r,16777619);return`${e}\0${t.length}:${r>>>0}`}function g(e,t,r){const n=h(e,t),o=f.get(n);return!o||o.path!==e||o.source!==t||o.dictionary!==r?null:(f.delete(n),f.set(n,o),o.issues)}function R(e,t,r,n){const o=h(e,t);for(f.set(o,{path:e,source:t,dictionary:r,issues:n});f.size>C;){const i=f.keys().next().value;if(i===void 0)break;f.delete(i)}}async function b(e,t,r,n="main.tex"){const o=d(t),i=g(n,e,o);if(i)return i;const a=$(e),c=new Set(t.map(s=>s.trim().toLocaleLowerCase("en-US")).filter(Boolean)),u=new Set,m=r.map(s=>H(e,s,a)).filter(s=>!!s).filter(s=>s.kind!=="spelling"||!c.has(s.word.trim().toLocaleLowerCase("en-US"))).filter(s=>{const l=`${s.from}:${s.to}:${s.kind}`;return u.has(l)?!1:(u.add(l),!0)}).sort((s,l)=>s.from-l.from||s.to-l.to);return R(n,e,o,m),m}async function P(e,t,r,n){const o=d(n),i=g(t,r,o);if(i)return i;const a=await v(e,t,r,++E);return b(r,n,a,t)}function N(e,t,r,n=[]){return y(t)?P(e,t,r,n):Promise.resolve([])}export{p as HarperLintSupersededError,I as isHarperLintSupersededError,N as lintLatex,b as mapLatexLints};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as a}from"./index-
|
|
1
|
+
import{c as a}from"./index-DF5cor0N.js";const e=a("Tags",[["path",{d:"m15 5 6.3 6.3a2.4 2.4 0 0 1 0 3.4L17 19",key:"1cbfv1"}],["path",{d:"M9.586 5.586A2 2 0 0 0 8.172 5H3a1 1 0 0 0-1 1v5.172a2 2 0 0 0 .586 1.414L8.29 18.29a2.426 2.426 0 0 0 3.42 0l3.58-3.58a2.426 2.426 0 0 0 0-3.42z",key:"135mg7"}],["circle",{cx:"6.5",cy:"9.5",r:".5",fill:"currentColor",key:"5pm5xn"}]]);export{e as T};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as e}from"./index-
|
|
1
|
+
import{c as e}from"./index-DF5cor0N.js";const n=e("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);export{n as T};
|
package/dist/client/index.html
CHANGED
|
@@ -3,9 +3,21 @@
|
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="UTF-8" />
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
|
-
<meta name="color-scheme" content="light" />
|
|
6
|
+
<meta name="color-scheme" content="light dark" />
|
|
7
7
|
<base href="/" />
|
|
8
8
|
<meta name="texlite-base-path" content="/" />
|
|
9
|
+
<script>
|
|
10
|
+
// Apply the browser preference before styles paint; keep this key in
|
|
11
|
+
// sync with scopedStorageKey("texlite-theme") in theme.ts.
|
|
12
|
+
try {
|
|
13
|
+
const base = document.querySelector('meta[name="texlite-base-path"]').content;
|
|
14
|
+
const key = base === "/" ? "texlite-theme" : `texlite-theme:base=${encodeURIComponent(base)}`;
|
|
15
|
+
const preference = localStorage.getItem(key);
|
|
16
|
+
const dark = preference === "dark" || (preference === "system" && typeof matchMedia === "function" && matchMedia("(prefers-color-scheme: dark)").matches);
|
|
17
|
+
document.documentElement.dataset.theme = dark ? "dark" : "light";
|
|
18
|
+
} catch { document.documentElement.dataset.theme = "light"; }
|
|
19
|
+
document.documentElement.style.colorScheme = document.documentElement.dataset.theme;
|
|
20
|
+
</script>
|
|
9
21
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
|
10
22
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
|
11
23
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500;600&family=IBM+Plex+Mono:wght@400;500;600&family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&family=Source+Code+Pro:wght@400;500;600&display=swap" />
|
|
@@ -13,9 +25,9 @@
|
|
|
13
25
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fontsource/iosevka@5.2.5/600.css" />
|
|
14
26
|
<link rel="icon" type="image/svg+xml" href="texlite-icon.svg" />
|
|
15
27
|
<title>TexLite</title>
|
|
16
|
-
<script type="module" crossorigin src="./assets/index-
|
|
28
|
+
<script type="module" crossorigin src="./assets/index-DF5cor0N.js"></script>
|
|
17
29
|
<link rel="modulepreload" crossorigin href="./assets/react-CltQJflK.js">
|
|
18
|
-
<link rel="stylesheet" crossorigin href="./assets/index-
|
|
30
|
+
<link rel="stylesheet" crossorigin href="./assets/index-Y-wXUwwe.css">
|
|
19
31
|
</head>
|
|
20
32
|
<body>
|
|
21
33
|
<div id="root"></div>
|
package/dist/server/app.js
CHANGED
|
@@ -21,6 +21,7 @@ import { HistoryRetentionScheduler } from "./historyRetention.js";
|
|
|
21
21
|
import { EditHistoryRetry } from "./editHistoryRetry.js";
|
|
22
22
|
import { ProjectOutlineService } from "./projectOutline.js";
|
|
23
23
|
import { MetricRegistry } from "./metrics.js";
|
|
24
|
+
import { UpdateChecker } from "./updates.js";
|
|
24
25
|
import { apiError, HttpError } from "./http.js";
|
|
25
26
|
import { registerCompileRoutes } from "./routes/compile.js";
|
|
26
27
|
import { registerAuthRoutes } from "./routes/auth.js";
|
|
@@ -74,6 +75,9 @@ export async function buildApp(config, db, options = {}) {
|
|
|
74
75
|
logger: options.logger ?? true,
|
|
75
76
|
bodyLimit: Math.max(12 * 1024 * 1024, config.maxUploadBytes + 1024 * 1024)
|
|
76
77
|
});
|
|
78
|
+
const updates = new UpdateChecker(db, { enabled: config.updatesEnabled, fetch: options.updateFetch });
|
|
79
|
+
app.addHook("onListen", async () => { updates.start(); });
|
|
80
|
+
app.addHook("onClose", async () => { await updates.dispose(); });
|
|
77
81
|
const queue = new CompileQueue(config.maxCompileJobs);
|
|
78
82
|
const compileCoordinator = new ProjectCompileCoordinator(queue);
|
|
79
83
|
const metrics = new MetricRegistry(200);
|
|
@@ -257,7 +261,8 @@ export async function buildApp(config, db, options = {}) {
|
|
|
257
261
|
latexCompletions,
|
|
258
262
|
projectOutlines,
|
|
259
263
|
metrics,
|
|
260
|
-
eventLoopDelay
|
|
264
|
+
eventLoopDelay,
|
|
265
|
+
updates
|
|
261
266
|
});
|
|
262
267
|
registerCollaborationRoutes(routes, { db, collaboration, metrics });
|
|
263
268
|
registerAuthRoutes(routes, { config, db, loginLimiter });
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
/** Resolve the current process's controller in both private and host cgroup namespaces. */
|
|
3
|
+
export function cgroupPaths(groups, mounts, controller) {
|
|
4
|
+
const memberships = groups.split("\n").flatMap((line) => {
|
|
5
|
+
const match = line.match(/^\d+:([^:]*):(\/.*)$/);
|
|
6
|
+
return match && (!match[1] || match[1].split(",").includes(controller))
|
|
7
|
+
? [{ group: path.posix.normalize(match[2]), v2: !match[1] }] : [];
|
|
8
|
+
});
|
|
9
|
+
const paths = [];
|
|
10
|
+
const unescape = (value) => value.replace(/\\([0-7]{3})/g, (_, octal) => String.fromCharCode(parseInt(octal, 8)));
|
|
11
|
+
for (const line of mounts.split("\n")) {
|
|
12
|
+
const [left, right] = line.split(" - ");
|
|
13
|
+
if (!right)
|
|
14
|
+
continue;
|
|
15
|
+
const fields = left.split(" ");
|
|
16
|
+
const [kind, , options = ""] = right.split(" ");
|
|
17
|
+
if (kind !== "cgroup2" && !(kind === "cgroup" && options.split(",").includes(controller)))
|
|
18
|
+
continue;
|
|
19
|
+
if (!fields[3] || !fields[4])
|
|
20
|
+
continue;
|
|
21
|
+
const root = unescape(fields[3]);
|
|
22
|
+
const mountPoint = unescape(fields[4]);
|
|
23
|
+
for (const membership of memberships.filter((entry) => entry.v2 === (kind === "cgroup2"))) {
|
|
24
|
+
const relative = path.posix.relative(root, membership.group);
|
|
25
|
+
if (relative === ".." || relative.startsWith("../"))
|
|
26
|
+
continue;
|
|
27
|
+
paths.push({ directory: path.posix.join(mountPoint, relative), mountPoint, v2: membership.v2 });
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return paths.length ? paths : [
|
|
31
|
+
{ directory: "/sys/fs/cgroup", mountPoint: "/sys/fs/cgroup", v2: true },
|
|
32
|
+
{ directory: `/sys/fs/cgroup/${controller}`, mountPoint: `/sys/fs/cgroup/${controller}`, v2: false },
|
|
33
|
+
...(controller === "memory" ? [] : [{ directory: "/sys/fs/cgroup/cpu,cpuacct", mountPoint: "/sys/fs/cgroup/cpu,cpuacct", v2: false }])
|
|
34
|
+
];
|
|
35
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { COMPILER_VERSION_TOOLS } from "../shared/compilerVersions.js";
|
|
2
|
+
const cacheDurationMs = 60_000;
|
|
3
|
+
/** Shared across users, refreshed on demand only. Never expose probe errors or paths. */
|
|
4
|
+
export class CompilerVersionService {
|
|
5
|
+
probe;
|
|
6
|
+
now;
|
|
7
|
+
cached = null;
|
|
8
|
+
expiresAt = 0;
|
|
9
|
+
pending = null;
|
|
10
|
+
constructor(probe, now = Date.now) {
|
|
11
|
+
this.probe = probe;
|
|
12
|
+
this.now = now;
|
|
13
|
+
}
|
|
14
|
+
getVersions() {
|
|
15
|
+
if (this.cached && this.now() < this.expiresAt)
|
|
16
|
+
return Promise.resolve(this.cached);
|
|
17
|
+
if (this.pending)
|
|
18
|
+
return this.pending;
|
|
19
|
+
this.pending = this.load().then((result) => {
|
|
20
|
+
this.cached = result;
|
|
21
|
+
this.expiresAt = this.now() + cacheDurationMs;
|
|
22
|
+
return result;
|
|
23
|
+
}).finally(() => { this.pending = null; });
|
|
24
|
+
return this.pending;
|
|
25
|
+
}
|
|
26
|
+
async load() {
|
|
27
|
+
const tools = await this.probe().catch(() => []);
|
|
28
|
+
const banners = new Map(tools.map((tool) => [tool.id, tool.status === "installed" ? tool.version : null]));
|
|
29
|
+
// Some distribution packages omit tlmgr. Engine banners still identify TeX Live.
|
|
30
|
+
const texlive = ["texlive", "pdflatex", "xelatex", "lualatex"]
|
|
31
|
+
.map((id) => banners.get(id)?.match(/\bTeX Live\b.*?\b(20\d{2})\b/i)?.[1])
|
|
32
|
+
.find(Boolean) ?? null;
|
|
33
|
+
return { tools: COMPILER_VERSION_TOOLS.map(({ id }) => ({
|
|
34
|
+
id, version: id === "texlive" ? texlive : softwareVersion(banners.get(id))
|
|
35
|
+
})) };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function softwareVersion(banner) {
|
|
39
|
+
if (!banner)
|
|
40
|
+
return null;
|
|
41
|
+
// Keep meaningful suffixes (BibTeX 0.99d, LuaHBTeX 1.21.0, pdfTeX 3.1415-2.6-1.40).
|
|
42
|
+
const numericVersion = "v?(\\d+(?:\\.\\d+)+(?:-\\d+(?:\\.\\d+)*)*[a-z]?)";
|
|
43
|
+
return banner.match(new RegExp(`\\bversion\\s*:?\\s*${numericVersion}`, "i"))?.[1]
|
|
44
|
+
?? banner.match(new RegExp(`\\b${numericVersion}`, "i"))?.[1]
|
|
45
|
+
?? null;
|
|
46
|
+
}
|
package/dist/server/config.js
CHANGED
|
@@ -7,6 +7,7 @@ export const PDF_LOADING_STRATEGIES = ["auto", "full", "range"];
|
|
|
7
7
|
/** Effective values used when the corresponding file/env setting is omitted. */
|
|
8
8
|
export const CONFIG_DEFAULTS = {
|
|
9
9
|
siteName: "TexLite",
|
|
10
|
+
updatesEnabled: true,
|
|
10
11
|
adminEmail: "",
|
|
11
12
|
host: "127.0.0.1",
|
|
12
13
|
port: 3000,
|
|
@@ -80,6 +81,7 @@ export function loadConfig(configPathOverride) {
|
|
|
80
81
|
const config = {
|
|
81
82
|
configPath,
|
|
82
83
|
siteName: stringSetting("siteName", process.env.TEXLITE_SITE_NAME, fileConfig.siteName, CONFIG_DEFAULTS.siteName, { min: 1, max: 120 }),
|
|
84
|
+
updatesEnabled: fileConfig.updates?.enabled ?? CONFIG_DEFAULTS.updatesEnabled,
|
|
83
85
|
adminEmail: stringSetting("adminEmail", process.env.TEXLITE_ADMIN_EMAIL, fileConfig.adminEmail, CONFIG_DEFAULTS.adminEmail, { min: 0, max: 320 }),
|
|
84
86
|
host: stringSetting("server.host", process.env.TEXLITE_HOST, fileConfig.server?.host, CONFIG_DEFAULTS.host, { min: 1, max: 255 }),
|
|
85
87
|
port: integerSetting("server.port", process.env.TEXLITE_PORT, fileConfig.server?.port, CONFIG_DEFAULTS.port, CONFIG_LIMITS.port),
|
|
@@ -122,6 +124,8 @@ export function loadBasePath(configPathOverride) {
|
|
|
122
124
|
}
|
|
123
125
|
/** Validate an already materialized configuration (useful for startup/tests). */
|
|
124
126
|
export function validateConfig(config) {
|
|
127
|
+
if (typeof config.updatesEnabled !== "boolean")
|
|
128
|
+
throw configurationError("updates.enabled", "must be true or false");
|
|
125
129
|
if (!config.dataDir || path.parse(config.dataDir).root === config.dataDir) {
|
|
126
130
|
throw configurationError("storage.dataDir", "must be a non-root directory where TexLite can store data");
|
|
127
131
|
}
|
|
@@ -188,6 +192,10 @@ function readConfigFile(configPath) {
|
|
|
188
192
|
}
|
|
189
193
|
}
|
|
190
194
|
function validateFileConfig(config) {
|
|
195
|
+
const updates = optionalSection(config.updates, "updates");
|
|
196
|
+
if (updates && Object.prototype.hasOwnProperty.call(updates, "enabled") && typeof updates.enabled !== "boolean") {
|
|
197
|
+
throw configurationError("updates.enabled", "must be true or false");
|
|
198
|
+
}
|
|
191
199
|
optionalString(config.siteName, "siteName", { min: 1, max: 120 });
|
|
192
200
|
optionalString(config.adminEmail, "adminEmail", { min: 0, max: 320 });
|
|
193
201
|
optionalInteger(config.sessionDays, "sessionDays", CONFIG_LIMITS.sessionDays);
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { performance } from "node:perf_hooks";
|
|
5
|
+
import { cgroupPaths } from "./cgroups.js";
|
|
6
|
+
/** Counters, not load averages or lifetime-average ps percentages. */
|
|
7
|
+
export async function collectCpuSnapshot(scope, tex, platform = process.platform, read = (file) => readFile(file, "utf8")) {
|
|
8
|
+
try {
|
|
9
|
+
const cpus = os.cpus();
|
|
10
|
+
if (!cpus.length)
|
|
11
|
+
return null;
|
|
12
|
+
const optional = (file) => read(file).catch(() => null);
|
|
13
|
+
let hostTotal = cpus.reduce((sum, cpu) => sum + Object.values(cpu.times).reduce((sum, time) => sum + time, 0), 0);
|
|
14
|
+
let hostIdle = cpus.reduce((sum, cpu) => sum + cpu.times.idle, 0);
|
|
15
|
+
let linuxTicks = null;
|
|
16
|
+
let capacityCores = cpus.length;
|
|
17
|
+
let containerUsageUs = null;
|
|
18
|
+
if (platform === "linux") {
|
|
19
|
+
const stat = await read("/proc/stat");
|
|
20
|
+
const values = stat.match(/^cpu[ \t]+([\d \t]+)$/m)?.[1].trim().split(/\s+/).map(Number);
|
|
21
|
+
if (!values || values.length < 4)
|
|
22
|
+
return null;
|
|
23
|
+
// guest/guest_nice are already included in user/nice; don't add them twice.
|
|
24
|
+
hostTotal = values.slice(0, 8).reduce((sum, value) => sum + value, 0);
|
|
25
|
+
hostIdle = values[3] + (values[4] ?? 0); // Idle and I/O wait are not executing work.
|
|
26
|
+
linuxTicks = hostTotal;
|
|
27
|
+
if (scope === "container") {
|
|
28
|
+
const [groups, mounts] = await Promise.all([optional("/proc/self/cgroup"), optional("/proc/self/mountinfo")]);
|
|
29
|
+
capacityCores = Math.min(cpus.length, os.availableParallelism());
|
|
30
|
+
for (const entry of cgroupPaths(groups ?? "", mounts ?? "", "cpuacct")) {
|
|
31
|
+
const usage = await optional(`${entry.directory}/${entry.v2 ? "cpu.stat" : "cpuacct.usage"}`);
|
|
32
|
+
const value = entry.v2 ? usage?.match(/^usage_usec\s+(\d+)$/m)?.[1] : usage?.trim();
|
|
33
|
+
if (value && /^\d+$/.test(value)) {
|
|
34
|
+
containerUsageUs = Number(value) / (entry.v2 ? 1 : 1_000);
|
|
35
|
+
break;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (containerUsageUs === null)
|
|
39
|
+
return null;
|
|
40
|
+
for (const entry of cgroupPaths(groups ?? "", mounts ?? "", "cpu")) {
|
|
41
|
+
for (let current = entry.directory;; current = path.posix.dirname(current)) {
|
|
42
|
+
let quota;
|
|
43
|
+
let period;
|
|
44
|
+
if (entry.v2) {
|
|
45
|
+
const fields = (await optional(`${current}/cpu.max`))?.trim().split(/\s+/);
|
|
46
|
+
quota = Number(fields?.[0]);
|
|
47
|
+
period = Number(fields?.[1]);
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
const fields = await Promise.all([optional(`${current}/cpu.cfs_quota_us`), optional(`${current}/cpu.cfs_period_us`)]);
|
|
51
|
+
quota = Number(fields[0]);
|
|
52
|
+
period = Number(fields[1]);
|
|
53
|
+
}
|
|
54
|
+
if (Number.isFinite(quota) && quota > 0 && period > 0)
|
|
55
|
+
capacityCores = Math.min(capacityCores, quota / period);
|
|
56
|
+
if (current === entry.mountPoint || current === "/")
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
else if (scope === "container")
|
|
63
|
+
return null;
|
|
64
|
+
const service = process.cpuUsage();
|
|
65
|
+
return { scope, at: performance.now(), hostCores: cpus.length, capacityCores, hostTotal, hostIdle, linuxTicks,
|
|
66
|
+
containerUsageUs, serviceUs: service.user + service.system, tex };
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** One baseline per server, shared by administrators; idle gaps start a fresh window. */
|
|
73
|
+
export class CpuMetrics {
|
|
74
|
+
previous = null;
|
|
75
|
+
update(current, scope) {
|
|
76
|
+
const empty = (status) => ({ scope, status, texlitePercent: null, otherPercent: null, idlePercent: null });
|
|
77
|
+
const previous = this.previous;
|
|
78
|
+
this.previous = current;
|
|
79
|
+
if (!current || current.tex === null)
|
|
80
|
+
return empty("unavailable");
|
|
81
|
+
const elapsed = previous ? current.at - previous.at : 0;
|
|
82
|
+
if (!previous || previous.tex === null || elapsed < 500 || elapsed > 15_000 || current.scope !== previous.scope
|
|
83
|
+
|| current.capacityCores !== previous.capacityCores || current.hostCores !== previous.hostCores)
|
|
84
|
+
return empty("warming");
|
|
85
|
+
const hostDelta = current.hostTotal - previous.hostTotal;
|
|
86
|
+
const idleDelta = current.hostIdle - previous.hostIdle;
|
|
87
|
+
const serviceDelta = current.serviceUs - previous.serviceUs;
|
|
88
|
+
if (hostDelta <= 0 || idleDelta < 0 || serviceDelta < 0 || current.capacityCores <= 0)
|
|
89
|
+
return empty("unavailable");
|
|
90
|
+
const oldProcesses = new Map(previous.tex.map((process) => [`${process.pid}:${process.started}`, process.time]));
|
|
91
|
+
let texDelta = 0;
|
|
92
|
+
for (const process of current.tex) {
|
|
93
|
+
const delta = process.time - (oldProcesses.get(`${process.pid}:${process.started}`) ?? 0);
|
|
94
|
+
if (delta < 0 || !Number.isFinite(delta))
|
|
95
|
+
return empty("unavailable");
|
|
96
|
+
texDelta += delta;
|
|
97
|
+
}
|
|
98
|
+
const capacityUs = elapsed * 1_000 * current.capacityCores;
|
|
99
|
+
let texPercent;
|
|
100
|
+
if (current.linuxTicks !== null && previous.linuxTicks !== null) {
|
|
101
|
+
const ticks = current.linuxTicks - previous.linuxTicks;
|
|
102
|
+
if (ticks <= 0)
|
|
103
|
+
return empty("unavailable");
|
|
104
|
+
texPercent = texDelta / ticks * current.hostCores / current.capacityCores * 100;
|
|
105
|
+
}
|
|
106
|
+
else
|
|
107
|
+
texPercent = texDelta / capacityUs * 100;
|
|
108
|
+
let busy = (hostDelta - idleDelta) / hostDelta * 100;
|
|
109
|
+
if (scope === "container") {
|
|
110
|
+
if (current.containerUsageUs === null || previous.containerUsageUs === null || current.containerUsageUs < previous.containerUsageUs)
|
|
111
|
+
return empty("unavailable");
|
|
112
|
+
busy = (current.containerUsageUs - previous.containerUsageUs) / capacityUs * 100;
|
|
113
|
+
}
|
|
114
|
+
busy = Math.max(0, Math.min(100, busy));
|
|
115
|
+
// Partition integer tenths before formatting; independently rounded shares
|
|
116
|
+
// can otherwise add up to 100.1% at half-way boundaries.
|
|
117
|
+
const busyTenths = Math.round(busy * 10);
|
|
118
|
+
const texliteTenths = Math.min(busyTenths, Math.round(Math.min(busy, texPercent + serviceDelta / capacityUs * 100) * 10));
|
|
119
|
+
return { scope, status: "ready", texlitePercent: texliteTenths / 10,
|
|
120
|
+
idlePercent: (1_000 - busyTenths) / 10, otherPercent: (busyTenths - texliteTenths) / 10 };
|
|
121
|
+
}
|
|
122
|
+
}
|
package/dist/server/db.js
CHANGED
|
@@ -27,6 +27,19 @@ const databaseMigrations = [
|
|
|
27
27
|
if (missingColumn(db, "comments", "resolved_at")) {
|
|
28
28
|
db.exec("ALTER TABLE comments ADD COLUMN resolved_at TEXT");
|
|
29
29
|
}
|
|
30
|
+
} },
|
|
31
|
+
{ version: 5, name: "add_update_notifications", apply: (db) => {
|
|
32
|
+
db.exec(`
|
|
33
|
+
CREATE TABLE IF NOT EXISTS update_check_cache (
|
|
34
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
35
|
+
latest_version TEXT,
|
|
36
|
+
next_check_at INTEGER NOT NULL
|
|
37
|
+
);
|
|
38
|
+
CREATE TABLE IF NOT EXISTS dismissed_updates (
|
|
39
|
+
user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
|
40
|
+
version TEXT NOT NULL
|
|
41
|
+
);
|
|
42
|
+
`);
|
|
30
43
|
} }
|
|
31
44
|
];
|
|
32
45
|
function migrateGitHubTokensToUsers(db) {
|
|
@@ -2,6 +2,7 @@ import { spawn } from "node:child_process";
|
|
|
2
2
|
import { LATEX_ENGINES } from "./config.js";
|
|
3
3
|
import { httpError } from "./http.js";
|
|
4
4
|
import { detachedProcessGroup, killProcessGroup } from "./processTree.js";
|
|
5
|
+
import { COMPILER_VERSION_TOOLS } from "../shared/compilerVersions.js";
|
|
5
6
|
export const MIN_NODE_MAJOR = 24;
|
|
6
7
|
const commandProbeTimeoutMs = 10_000;
|
|
7
8
|
const maxCommandOutputBytes = 64 * 1024;
|
|
@@ -13,6 +14,16 @@ const maxCommandOutputBytes = 64 * 1024;
|
|
|
13
14
|
export async function inspectHostEnvironment(config) {
|
|
14
15
|
return Promise.all(hostToolDefinitions(config).map((tool) => inspectTool(tool)));
|
|
15
16
|
}
|
|
17
|
+
/** Read-only, bounded version checks; missing tools never become requirements. */
|
|
18
|
+
export async function inspectCompilerEnvironment(config) {
|
|
19
|
+
return Promise.all(COMPILER_VERSION_TOOLS.map(({ id, name }) => inspectTool({
|
|
20
|
+
id, name,
|
|
21
|
+
command: id === "texlive" ? "tlmgr" : id === "latexmk" ? config.latexmk : id,
|
|
22
|
+
requirement: "optional", purpose: "Compiler environment version",
|
|
23
|
+
versionArgs: id === "texcount" ? ["-version"] : ["--version"],
|
|
24
|
+
timeoutMs: 3_000
|
|
25
|
+
})));
|
|
26
|
+
}
|
|
16
27
|
/**
|
|
17
28
|
* Probe the default commands on PATH without loading a TexLite configuration.
|
|
18
29
|
* This supports pre-installation checks through `texlite requirements`.
|
package/dist/server/i18n.js
CHANGED
|
@@ -91,7 +91,6 @@ const enMessages = {
|
|
|
91
91
|
REPLY_NOT_FOUND: "The reply does not exist.",
|
|
92
92
|
REQUEST_INVALID: "The request is invalid.",
|
|
93
93
|
RESERVED_PATH: "This path is reserved by TexLite.",
|
|
94
|
-
SEARCH_QUERY_INVALID: "The search or replacement text is invalid.",
|
|
95
94
|
SELF_DELETE_FORBIDDEN: "You cannot delete the currently signed-in administrator.",
|
|
96
95
|
SELF_RESTRICT_FORBIDDEN: "You cannot disable or demote the currently signed-in administrator.",
|
|
97
96
|
SERVER_ERROR: "The server could not complete the request.",
|
|
@@ -230,7 +229,6 @@ const zhMessages = {
|
|
|
230
229
|
REPLY_NOT_FOUND: "回复不存在。",
|
|
231
230
|
REQUEST_INVALID: "请求格式无效。",
|
|
232
231
|
RESERVED_PATH: "此路径由 TexLite 保留。",
|
|
233
|
-
SEARCH_QUERY_INVALID: "搜索或替换内容格式不正确。",
|
|
234
232
|
SELF_DELETE_FORBIDDEN: "不能删除当前登录的管理员。",
|
|
235
233
|
SELF_RESTRICT_FORBIDDEN: "不能禁用当前登录的管理员或降低其角色权限。",
|
|
236
234
|
SERVER_ERROR: "服务器内部错误",
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
import { collectSystemMemory } from "./systemMemory.js";
|
|
5
|
+
import { collectCpuSnapshot, CpuMetrics } from "./cpuMetrics.js";
|
|
6
|
+
const exec = promisify(execFile);
|
|
7
|
+
const commandOptions = { timeout: 3_000, maxBuffer: 4 * 1024 * 1024, windowsHide: true, env: { ...process.env, LC_ALL: "C" } };
|
|
8
|
+
const texTools = new Set([
|
|
9
|
+
"tex", "latex", "pdftex", "pdflatex", "xetex", "xelatex", "luatex", "lualatex", "luahbtex", "luahblatex",
|
|
10
|
+
"pdfetex", "etex", "elatex", "euptex", "uptex", "uplatex", "ptex", "platex", "tectonic",
|
|
11
|
+
"latexmk", "bibtex", "bibtex8", "bibtexu", "biber", "makeindex", "xindy", "texindy", "makeglossaries",
|
|
12
|
+
"dvipdfm", "dvipdfmx", "xdvipdfmx", "dvips", "texcount", "chktex", "harper-cli"
|
|
13
|
+
]);
|
|
14
|
+
const texScripts = new Set(["latexmk", "biber", "makeglossaries", "texcount", "texindy", "xindy"]);
|
|
15
|
+
const unavailable = () => ({ rssBytes: null, processCount: null });
|
|
16
|
+
const processAccess = {
|
|
17
|
+
read: (file) => readFile(file, "utf8"),
|
|
18
|
+
directories: () => readdir("/proc"),
|
|
19
|
+
command: async (file, args) => (await exec(file, args, commandOptions)).stdout
|
|
20
|
+
};
|
|
21
|
+
function executableName(value) {
|
|
22
|
+
return value.replaceAll("\\", "/").split("/").at(-1).toLowerCase().replace(/\.(?:exe|pl)$/i, "").replace(/^miktex-/, "");
|
|
23
|
+
}
|
|
24
|
+
function isPerl(name) {
|
|
25
|
+
return /^perl(?:\d+(?:\.\d+)*)?$/.test(executableName(name));
|
|
26
|
+
}
|
|
27
|
+
/** Includes Harper CLI writing checks; match tool names, not arbitrary arguments or every Perl process. */
|
|
28
|
+
export function isTexProcess(process) {
|
|
29
|
+
if (texTools.has(executableName(process.name)))
|
|
30
|
+
return true;
|
|
31
|
+
if (!isPerl(process.name) || !process.argv)
|
|
32
|
+
return false;
|
|
33
|
+
const args = process.argv.slice(1);
|
|
34
|
+
for (let index = 0; index < args.length; index++) {
|
|
35
|
+
const arg = args[index];
|
|
36
|
+
if (arg === "--")
|
|
37
|
+
return texScripts.has(executableName(args[index + 1] ?? ""));
|
|
38
|
+
if (arg === "-e" || arg === "-E" || /^-[eE]/.test(arg))
|
|
39
|
+
return false;
|
|
40
|
+
if (["-I", "-M", "-m"].includes(arg)) {
|
|
41
|
+
index++;
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (arg.startsWith("-"))
|
|
45
|
+
continue;
|
|
46
|
+
return texScripts.has(executableName(arg));
|
|
47
|
+
}
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
/** A failed RSS read must not look like a successfully measured zero. */
|
|
51
|
+
export function sumTexMemory(processes) {
|
|
52
|
+
const selected = new Map(processes.filter(isTexProcess).map((process) => [process.pid, process]));
|
|
53
|
+
let rssBytes = 0;
|
|
54
|
+
for (const process of selected.values()) {
|
|
55
|
+
if (process.rssBytes === null || !Number.isFinite(process.rssBytes) || process.rssBytes < 0)
|
|
56
|
+
return unavailable();
|
|
57
|
+
rssBytes += process.rssBytes;
|
|
58
|
+
}
|
|
59
|
+
return { rssBytes, processCount: selected.size };
|
|
60
|
+
}
|
|
61
|
+
// Handle quoted script paths when available; Linux uses lossless NUL-separated argv.
|
|
62
|
+
function commandArguments(command) {
|
|
63
|
+
return (command.match(/"[^"]*"|'[^']*'|\S+/g) ?? []).map((part) => /^(["']).*\1$/.test(part) ? part.slice(1, -1) : part);
|
|
64
|
+
}
|
|
65
|
+
export function parsePosixProcesses(output) {
|
|
66
|
+
return output.trim().split("\n").filter(Boolean).map((line) => {
|
|
67
|
+
const match = line.match(/^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/);
|
|
68
|
+
if (!match)
|
|
69
|
+
throw new Error("Invalid ps memory sample");
|
|
70
|
+
const timing = match[3].match(/^(\S+)\s+((?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s+\w+\s+\d+\s+[\d:]+\s+\d{4})\s+(.+)$/);
|
|
71
|
+
return { pid: Number(match[1]), rssBytes: Number(match[2]) * 1024, name: timing?.[3] ?? match[3],
|
|
72
|
+
...(timing ? { cpuTime: parseCpuTime(timing[1]), started: timing[2] } : {}) };
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
/** BSD ps CPU time: [[days-]hours:]minutes:seconds[.fraction]. */
|
|
76
|
+
export function parseCpuTime(value) {
|
|
77
|
+
const match = value.match(/^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+(?:\.\d+)?)$/);
|
|
78
|
+
if (!match)
|
|
79
|
+
throw new Error("Invalid process CPU time");
|
|
80
|
+
return ((Number(match[1] ?? 0) * 86_400) + Number(match[2] ?? 0) * 3_600 + Number(match[3]) * 60 + Number(match[4])) * 1_000_000;
|
|
81
|
+
}
|
|
82
|
+
export function parseLinuxProcessCpu(stat) {
|
|
83
|
+
// comm can contain spaces and parentheses. The final ')' ends that field.
|
|
84
|
+
const closing = stat.lastIndexOf(")");
|
|
85
|
+
if (closing < 0)
|
|
86
|
+
throw new Error("Invalid process stat");
|
|
87
|
+
const fields = stat.slice(closing + 1).trim().split(/\s+/);
|
|
88
|
+
if (![fields[11], fields[12], fields[19]].every((field) => /^\d+$/.test(field ?? "")))
|
|
89
|
+
throw new Error("Invalid process CPU counters");
|
|
90
|
+
return { cpuTime: Number(fields[11]) + Number(fields[12]), started: fields[19] };
|
|
91
|
+
}
|
|
92
|
+
export function parseWindowsProcesses(output) {
|
|
93
|
+
const decoded = JSON.parse(output.replace(/^\uFEFF/, ""));
|
|
94
|
+
if (decoded === null)
|
|
95
|
+
return [];
|
|
96
|
+
const entries = Array.isArray(decoded) ? decoded : [decoded];
|
|
97
|
+
return entries.map((value) => {
|
|
98
|
+
if (!value || typeof value !== "object")
|
|
99
|
+
throw new Error("Invalid CIM memory sample");
|
|
100
|
+
const entry = value;
|
|
101
|
+
if (typeof entry.Name !== "string" || !Number.isInteger(entry.ProcessId))
|
|
102
|
+
throw new Error("Invalid CIM process");
|
|
103
|
+
const rss = entry.WorkingSetSize === null || entry.WorkingSetSize === undefined ? null : Number(entry.WorkingSetSize);
|
|
104
|
+
return {
|
|
105
|
+
pid: entry.ProcessId, name: entry.Name,
|
|
106
|
+
rssBytes: rss, argv: typeof entry.CommandLine === "string" ? commandArguments(entry.CommandLine) : undefined,
|
|
107
|
+
...(entry.UserModeTime !== null && entry.UserModeTime !== undefined && entry.KernelModeTime !== null && entry.KernelModeTime !== undefined && typeof entry.CreationDate === "string"
|
|
108
|
+
? { cpuTime: (Number(entry.UserModeTime) + Number(entry.KernelModeTime)) / 10, started: entry.CreationDate } : {})
|
|
109
|
+
};
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
async function linuxProcesses(io) {
|
|
113
|
+
const ids = (await io.directories()).filter((name) => /^\d+$/.test(name));
|
|
114
|
+
const result = [];
|
|
115
|
+
let cursor = 0;
|
|
116
|
+
// Bound open file descriptors even on hosts running many unrelated processes.
|
|
117
|
+
await Promise.all(Array.from({ length: Math.min(16, ids.length) }, async () => {
|
|
118
|
+
while (cursor < ids.length) {
|
|
119
|
+
const pid = Number(ids[cursor++]);
|
|
120
|
+
try {
|
|
121
|
+
const status = await io.read(`/proc/${pid}/status`);
|
|
122
|
+
if (/^State:\s+Z/m.test(status))
|
|
123
|
+
continue;
|
|
124
|
+
const name = status.match(/^Name:\s+(.+)$/m)?.[1]?.trim();
|
|
125
|
+
if (!name || (!texTools.has(executableName(name)) && !isPerl(name)))
|
|
126
|
+
continue;
|
|
127
|
+
const rss = status.match(/^VmRSS:\s+(\d+)\s+kB$/m);
|
|
128
|
+
const argv = isPerl(name) ? (await io.read(`/proc/${pid}/cmdline`)).split("\0").filter(Boolean) : undefined;
|
|
129
|
+
// A missing CPU counter must not discard an otherwise valid memory reading.
|
|
130
|
+
const cpu = await io.read(`/proc/${pid}/stat`).then(parseLinuxProcessCpu).catch(() => ({}));
|
|
131
|
+
result.push({ pid, name, rssBytes: rss ? Number(rss[1]) * 1024 : null, argv, ...cpu });
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
// Exiting processes and processes hidden by OS permissions are outside this visible sample.
|
|
135
|
+
if (!["ENOENT", "ESRCH", "EACCES", "EPERM"].includes(error.code ?? ""))
|
|
136
|
+
throw error;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}));
|
|
140
|
+
return result;
|
|
141
|
+
}
|
|
142
|
+
async function macProcesses(io) {
|
|
143
|
+
const stdout = await io.command("ps", ["-ww", "-axo", "pid=,rss=,time=,lstart=,comm="]);
|
|
144
|
+
const result = parsePosixProcesses(stdout);
|
|
145
|
+
const interpreters = result.filter((process) => isPerl(process.name));
|
|
146
|
+
if (interpreters.length) {
|
|
147
|
+
const commands = await io.command("ps", ["-ww", "-p", interpreters.map((process) => process.pid).join(","), "-o", "pid=,args="])
|
|
148
|
+
.catch((error) => {
|
|
149
|
+
// ps exits 1 if all requested processes disappeared between the two samples.
|
|
150
|
+
if (error.code === 1)
|
|
151
|
+
return "";
|
|
152
|
+
throw error;
|
|
153
|
+
});
|
|
154
|
+
const argsByPid = new Map(commands.trim().split("\n").flatMap((line) => {
|
|
155
|
+
const match = line.match(/^\s*(\d+)\s+(.+)$/);
|
|
156
|
+
return match ? [[Number(match[1]), commandArguments(match[2])]] : [];
|
|
157
|
+
}));
|
|
158
|
+
for (const process of interpreters)
|
|
159
|
+
process.argv = argsByPid.get(process.pid);
|
|
160
|
+
}
|
|
161
|
+
return result;
|
|
162
|
+
}
|
|
163
|
+
export async function collectTexResources(platform = process.platform, io = processAccess) {
|
|
164
|
+
try {
|
|
165
|
+
let processes;
|
|
166
|
+
if (platform === "linux")
|
|
167
|
+
processes = await linuxProcesses(io);
|
|
168
|
+
else if (platform === "darwin")
|
|
169
|
+
processes = await macProcesses(io);
|
|
170
|
+
else if (platform === "win32") {
|
|
171
|
+
const stdout = await io.command("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command",
|
|
172
|
+
"Get-CimInstance Win32_Process -ErrorAction Stop | Select-Object ProcessId,Name,WorkingSetSize,CommandLine,UserModeTime,KernelModeTime,CreationDate | ConvertTo-Json -Compress"]);
|
|
173
|
+
processes = parseWindowsProcesses(stdout);
|
|
174
|
+
}
|
|
175
|
+
else
|
|
176
|
+
return { memory: unavailable(), cpu: null };
|
|
177
|
+
const selected = processes.filter(isTexProcess);
|
|
178
|
+
const validCpu = selected.every((process) => process.cpuTime !== undefined && Number.isFinite(process.cpuTime) && process.cpuTime >= 0 && process.started !== undefined);
|
|
179
|
+
return { memory: sumTexMemory(selected), cpu: validCpu ? selected.map((process) => ({ pid: process.pid, started: process.started, time: process.cpuTime })) : null };
|
|
180
|
+
}
|
|
181
|
+
catch { /* Optional monitoring must never interrupt application operations. */ }
|
|
182
|
+
return { memory: unavailable(), cpu: null };
|
|
183
|
+
}
|
|
184
|
+
export async function collectTexMemory(platform = process.platform, io = processAccess) {
|
|
185
|
+
return (await collectTexResources(platform, io)).memory;
|
|
186
|
+
}
|
|
187
|
+
async function collectResources(cpu) {
|
|
188
|
+
const [systemMemory, tex] = await Promise.all([collectSystemMemory(), collectTexResources()]);
|
|
189
|
+
const cpuSnapshot = await collectCpuSnapshot(systemMemory.scope, tex.cpu);
|
|
190
|
+
return { systemMemory, texMemory: tex.memory, cpu: cpu.update(cpuSnapshot, systemMemory.scope) };
|
|
191
|
+
}
|
|
192
|
+
/** On-demand only: no timers or process scans while nobody is viewing System status. */
|
|
193
|
+
export class ResourceMetrics {
|
|
194
|
+
now;
|
|
195
|
+
cached = null;
|
|
196
|
+
pending = null;
|
|
197
|
+
collect;
|
|
198
|
+
constructor(collect, now = Date.now) {
|
|
199
|
+
this.now = now;
|
|
200
|
+
const cpu = new CpuMetrics();
|
|
201
|
+
this.collect = collect ?? (() => collectResources(cpu));
|
|
202
|
+
}
|
|
203
|
+
sample() {
|
|
204
|
+
if (this.cached && this.now() - this.cached.at < 2_000)
|
|
205
|
+
return Promise.resolve(this.cached.value);
|
|
206
|
+
if (this.pending)
|
|
207
|
+
return this.pending;
|
|
208
|
+
this.pending = this.collect().then((value) => {
|
|
209
|
+
this.cached = { at: this.now(), value };
|
|
210
|
+
return value;
|
|
211
|
+
}).finally(() => { this.pending = null; });
|
|
212
|
+
return this.pending;
|
|
213
|
+
}
|
|
214
|
+
}
|