@gtkx/utils 2.0.0-beta.1 → 2.0.0-beta.10

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 (30) hide show
  1. package/README.md +43 -40
  2. package/dist/process/index.d.ts +3 -1
  3. package/dist/process/index.d.ts.map +1 -1
  4. package/dist/process/index.js +3 -1
  5. package/dist/process/index.js.map +1 -1
  6. package/dist/process/kill-marked-processes.d.ts +3 -2
  7. package/dist/process/kill-marked-processes.d.ts.map +1 -1
  8. package/dist/process/kill-marked-processes.js +39 -13
  9. package/dist/process/kill-marked-processes.js.map +1 -1
  10. package/dist/process/kill-process-group.d.ts +16 -0
  11. package/dist/process/kill-process-group.d.ts.map +1 -0
  12. package/dist/process/kill-process-group.js +70 -0
  13. package/dist/process/kill-process-group.js.map +1 -0
  14. package/dist/process/process-guard.js +192 -6
  15. package/dist/process/process-guard.js.map +1 -1
  16. package/dist/process/process-status.d.ts +5 -0
  17. package/dist/process/process-status.d.ts.map +1 -0
  18. package/dist/process/process-status.js +19 -0
  19. package/dist/process/process-status.js.map +1 -0
  20. package/dist/process/spawn-with-parent-death-signal.d.ts +7 -1
  21. package/dist/process/spawn-with-parent-death-signal.d.ts.map +1 -1
  22. package/dist/process/spawn-with-parent-death-signal.js +315 -8
  23. package/dist/process/spawn-with-parent-death-signal.js.map +1 -1
  24. package/package.json +4 -2
  25. package/src/process/index.ts +14 -1
  26. package/src/process/kill-marked-processes.ts +58 -13
  27. package/src/process/kill-process-group.ts +105 -0
  28. package/src/process/process-guard.ts +261 -6
  29. package/src/process/process-status.ts +25 -0
  30. package/src/process/spawn-with-parent-death-signal.ts +422 -11
package/README.md CHANGED
@@ -5,9 +5,9 @@
5
5
  <h1 align="center">GTKX</h1>
6
6
 
7
7
  <p align="center">
8
- The React framework for Linux, built on GTK.<br />
9
- Write native GTK4 desktop applications with React and TypeScript.
10
- Real GTK widgets, the GNOME stack, and standard web tooling.
8
+ The React framework for Linux.<br />
9
+ Write native GNOME applications with React and TypeScript.
10
+ Real Adwaita and GTK4 widgets with standard web tooling.
11
11
  </p>
12
12
 
13
13
  <p align="center">
@@ -38,11 +38,12 @@
38
38
 
39
39
  ## Demo
40
40
 
41
- The intrinsic elements in this snippet render GTK4 widgets, and ordinary React hooks and events drive them:
41
+ This app starts with an Adwaita application shell, renders native GTK4 widgets inside it, and uses ordinary React hooks and events:
42
42
 
43
43
  ```tsx
44
44
  import * as Gtk from "@gtkx/gi/gtk";
45
- import { GtkApplication, GtkApplicationWindow, GtkBox, GtkButton, GtkLabel } from "@gtkx/jsx/gtk";
45
+ import { AdwApplication, AdwApplicationWindow, AdwHeaderBar, AdwToolbarView } from "@gtkx/jsx/adw";
46
+ import { GtkBox, GtkButton, GtkLabel } from "@gtkx/jsx/gtk";
46
47
  import { createRoot, quit } from "@gtkx/react";
47
48
  import { useState } from "react";
48
49
 
@@ -50,38 +51,40 @@ const Counter = () => {
50
51
  const [count, setCount] = useState(0);
51
52
 
52
53
  return (
53
- <GtkApplicationWindow
54
+ <AdwApplicationWindow
54
55
  title="Hello GTKX"
55
56
  defaultWidth={400}
56
57
  defaultHeight={300}
57
58
  onCloseRequest={quit}
58
59
  >
59
- <GtkBox
60
- orientation={Gtk.Orientation.VERTICAL}
61
- spacing={20}
62
- marginTop={40}
63
- marginBottom={40}
64
- marginStart={40}
65
- marginEnd={40}
66
- valign={Gtk.Align.CENTER}
67
- halign={Gtk.Align.CENTER}
68
- >
69
- <GtkLabel cssClasses={["title-1"]}>Welcome to GTKX!</GtkLabel>
70
- <GtkLabel cssClasses={["title-2"]}>{`Count: ${count}`}</GtkLabel>
71
- <GtkButton
72
- label="Increment"
73
- onClicked={() => setCount((c) => c + 1)}
74
- cssClasses={["suggested-action", "pill"]}
75
- />
76
- </GtkBox>
77
- </GtkApplicationWindow>
60
+ <AdwToolbarView topBar={<AdwHeaderBar />}>
61
+ <GtkBox
62
+ orientation={Gtk.Orientation.VERTICAL}
63
+ spacing={20}
64
+ marginTop={40}
65
+ marginBottom={40}
66
+ marginStart={40}
67
+ marginEnd={40}
68
+ valign={Gtk.Align.CENTER}
69
+ halign={Gtk.Align.CENTER}
70
+ >
71
+ <GtkLabel cssClasses={["title-1"]}>Welcome to GTKX!</GtkLabel>
72
+ <GtkLabel cssClasses={["title-2"]}>{`Count: ${String(count)}`}</GtkLabel>
73
+ <GtkButton
74
+ label="Increment"
75
+ onClicked={() => setCount((c) => c + 1)}
76
+ cssClasses={["suggested-action", "pill"]}
77
+ />
78
+ </GtkBox>
79
+ </AdwToolbarView>
80
+ </AdwApplicationWindow>
78
81
  );
79
82
  };
80
83
 
81
84
  const App = () => (
82
- <GtkApplication>
85
+ <AdwApplication>
83
86
  <Counter />
84
- </GtkApplication>
87
+ </AdwApplication>
85
88
  );
86
89
 
87
90
  createRoot().render(<App />);
@@ -91,9 +94,9 @@ This is the [`hello-world`](https://github.com/gtkx-org/gtkx/tree/main/examples/
91
94
 
92
95
  ## Why GTKX
93
96
 
94
- ### A declarative layer for the GNOME stack
97
+ ### Adwaita-first application development
95
98
 
96
- GTK4 is mature, and GtkBuilder XML can lay out a static interface, but nothing re-renders that interface when your application state changes, and nothing hot-reloads it as you work. GTKX adds that missing layer, and the tooling around it, on top of the stack you already know:
99
+ GTKX uses Adwaita as the foundation for applications, windows, navigation, dialogs, and adaptive layouts, with the complete GTK4 toolkit underneath. It adds a declarative React layer and an integrated TypeScript toolchain to the GNOME platform:
97
100
 
98
101
  - a React reconciler that exposes every GObject as a JSX element,
99
102
  - a CLI for scaffolding, development, and production builds,
@@ -102,17 +105,17 @@ GTK4 is mature, and GtkBuilder XML can lay out a static interface, but nothing r
102
105
  - a Testing Library-style API for querying and driving your widgets in tests,
103
106
  - and a Model Context Protocol (MCP) server that exposes your live app to AI agents.
104
107
 
105
- ### The full GNOME API surface
108
+ ### Native GNOME widgets, without a compatibility layer
106
109
 
107
- React Native and similar frameworks hide the native toolkit so one API can run everywhere. GTKX exposes it: GTK4, Adwaita, and any other GObject-Introspection library on your system. Linux-only by design.
110
+ React Native and similar frameworks hide the native toolkit so one API can run everywhere. GTKX renders real Adwaita and GTK4 widgets and exposes any other GObject-Introspection library on your system. It is GNOME-native and Linux-only by design.
108
111
 
109
112
  ### Why Node.js, and why generated bindings
110
113
 
111
114
  GTKX runs on Node.js, which puts native modules, the npm ecosystem, and the tooling built for Node.js APIs within reach. GJS is GNOME's own runtime, built on SpiderMonkey rather than V8; node-gtk runs on Node.js but is lightly maintained, on the older nan/V8 ABI rather than N-API, and still centered on GTK3. The [Why GTKX guide](https://gtkx.dev/guide/why-gtkx) covers what running on Node.js means day to day.
112
115
 
113
- GTKX generates the TypeScript types and the native FFI calls from the same GObject-Introspection data, so the types cannot drift from the calls they back. Codegen covers the whole GTK4 and Adwaita surface.
116
+ GTKX generates the TypeScript types and native FFI calls from the same GObject-Introspection data, so the types cannot drift from the calls they back. `Adw-1` is the sole default GIR root; its GIR include pulls in `Gtk-4.0`, so codegen covers both complete API surfaces. Neither belongs in a GTKX 2 `libraries` list.
114
117
 
115
- At runtime, the native Rust core calls straight into the system GTK4, Adwaita, and GLib libraries through libffi, without loading libgirepository at all.
118
+ At runtime, the native Rust core calls straight into the system Adwaita, GTK4, and GLib libraries through libffi, without loading libgirepository at all.
116
119
 
117
120
  ## Quick start
118
121
 
@@ -121,10 +124,10 @@ GTKX is Linux-only and needs Node.js 26.7 or later. See [Requirements](#requirem
121
124
  Scaffold a new app with the `create-gtkx` initializer:
122
125
 
123
126
  ```sh
124
- npm create gtkx
127
+ npm create gtkx@beta
125
128
  ```
126
129
 
127
- The same command works with other package managers: `pnpm create gtkx` or `yarn create gtkx`.
130
+ The same command works with other package managers: `pnpm create gtkx@beta` or `yarn create gtkx@beta`.
128
131
 
129
132
  Then run your new app:
130
133
 
@@ -145,7 +148,7 @@ The documentation at **[gtkx.dev](https://gtkx.dev)** includes a step-by-step tu
145
148
 
146
149
  GTKX is Linux-only. You need:
147
150
 
148
- - Linux with the GTK4 (4.20 or later), Adwaita (1.8 or later), and GLib development libraries
151
+ - Linux with the Adwaita (1.8 or later), GTK4 (4.20 or later), and GLib development libraries
149
152
  - Node.js 26.7 or later
150
153
 
151
154
  The `@gtkx/native` addon ships prebuilt for x64 and arm64 glibc Linux; other targets need to build it from the GTKX repository, which requires a Rust toolchain.
@@ -154,10 +157,10 @@ The `@gtkx/native` addon ships prebuilt for x64 and arm64 glibc Linux; other tar
154
157
 
155
158
  Explore the [example apps](https://github.com/gtkx-org/gtkx/tree/main/examples):
156
159
 
157
- - [`hello-world`](https://github.com/gtkx-org/gtkx/tree/main/examples/hello-world): the counter above.
158
- - [`gtk-demo`](https://github.com/gtkx-org/gtkx/tree/main/examples/gtk-demo): a React port of the official GTK4 widget showcase, covering lists, dialogs, gestures, CSS, and OpenGL.
159
- - [`browser`](https://github.com/gtkx-org/gtkx/tree/main/examples/browser): a WebKitWebView-based web browser.
160
- - [`animations`](https://github.com/gtkx-org/gtkx/tree/main/examples/animations): a tour of `@gtkx/animated`, React Spring animations driven by the GTK frame clock.
160
+ - [`hello-world`](https://github.com/gtkx-org/gtkx/tree/main/examples/hello-world): the Adwaita counter above.
161
+ - [`gtk-demo`](https://github.com/gtkx-org/gtkx/tree/main/examples/gtk-demo): the official GTK4 widget showcase in an Adwaita application shell, covering lists, dialogs, gestures, CSS, and OpenGL.
162
+ - [`browser`](https://github.com/gtkx-org/gtkx/tree/main/examples/browser): an Adwaita browser built around `WebKitWebView`.
163
+ - [`animations`](https://github.com/gtkx-org/gtkx/tree/main/examples/animations): an Adwaita showcase for `@gtkx/animated`, with React Spring animations driven by the GTK frame clock.
161
164
  - [`navigation`](https://github.com/gtkx-org/gtkx/tree/main/examples/navigation): a tour of `@gtkx/navigation`, React Navigation's stack, tab, and drawer navigators rendered with libadwaita.
162
165
  - [`tutorial`](https://github.com/gtkx-org/gtkx/tree/main/examples/tutorial): the Tasks app the documentation builds.
163
166
 
@@ -1,5 +1,7 @@
1
1
  export { exitCodeForSignal } from "./exit-code-for-signal.ts";
2
2
  export { installGracefulShutdown } from "./install-graceful-shutdown.ts";
3
+ export { type CleanupDirectoryIdentity, cleanupDirectoryIdentity, killProcessGroup, type ProcessGroupIdentity, processGroupIdentity, removeCleanupDirectory, } from "./kill-process-group.ts";
4
+ export { isProcessAlive } from "./process-status.ts";
3
5
  export { resolveExecutable, tryResolveExecutable } from "./resolve-executable.ts";
4
- export { spawnWithParentDeathSignal } from "./spawn-with-parent-death-signal.ts";
6
+ export { spawnWithParentDeathSignal, spawnWithParentDeathSupervisor, watchParentProcess, } from "./spawn-with-parent-death-signal.ts";
5
7
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/process/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAClF,OAAO,EAAE,0BAA0B,EAAE,MAAM,qCAAqC,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/process/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,EACH,KAAK,wBAAwB,EAC7B,wBAAwB,EACxB,gBAAgB,EAChB,KAAK,oBAAoB,EACzB,oBAAoB,EACpB,sBAAsB,GACzB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAClF,OAAO,EACH,0BAA0B,EAC1B,8BAA8B,EAC9B,kBAAkB,GACrB,MAAM,qCAAqC,CAAC"}
@@ -1,5 +1,7 @@
1
1
  export { exitCodeForSignal } from "./exit-code-for-signal.js";
2
2
  export { installGracefulShutdown } from "./install-graceful-shutdown.js";
3
+ export { cleanupDirectoryIdentity, killProcessGroup, processGroupIdentity, removeCleanupDirectory, } from "./kill-process-group.js";
4
+ export { isProcessAlive } from "./process-status.js";
3
5
  export { resolveExecutable, tryResolveExecutable } from "./resolve-executable.js";
4
- export { spawnWithParentDeathSignal } from "./spawn-with-parent-death-signal.js";
6
+ export { spawnWithParentDeathSignal, spawnWithParentDeathSupervisor, watchParentProcess, } from "./spawn-with-parent-death-signal.js";
5
7
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/process/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAClF,OAAO,EAAE,0BAA0B,EAAE,MAAM,qCAAqC,CAAC","sourcesContent":["export { exitCodeForSignal } from \"./exit-code-for-signal.ts\";\nexport { installGracefulShutdown } from \"./install-graceful-shutdown.ts\";\nexport { resolveExecutable, tryResolveExecutable } from \"./resolve-executable.ts\";\nexport { spawnWithParentDeathSignal } from \"./spawn-with-parent-death-signal.ts\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/process/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,EAEH,wBAAwB,EACxB,gBAAgB,EAEhB,oBAAoB,EACpB,sBAAsB,GACzB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAClF,OAAO,EACH,0BAA0B,EAC1B,8BAA8B,EAC9B,kBAAkB,GACrB,MAAM,qCAAqC,CAAC","sourcesContent":["export { exitCodeForSignal } from \"./exit-code-for-signal.ts\";\nexport { installGracefulShutdown } from \"./install-graceful-shutdown.ts\";\nexport {\n type CleanupDirectoryIdentity,\n cleanupDirectoryIdentity,\n killProcessGroup,\n type ProcessGroupIdentity,\n processGroupIdentity,\n removeCleanupDirectory,\n} from \"./kill-process-group.ts\";\nexport { isProcessAlive } from \"./process-status.ts\";\nexport { resolveExecutable, tryResolveExecutable } from \"./resolve-executable.ts\";\nexport {\n spawnWithParentDeathSignal,\n spawnWithParentDeathSupervisor,\n watchParentProcess,\n} from \"./spawn-with-parent-death-signal.ts\";\n"]}
@@ -1,4 +1,5 @@
1
1
  declare const PROCESS_MARKER = "GTKX_PROCESS_GUARD";
2
- declare function killMarkedProcesses(prefix: string): void;
3
- export { PROCESS_MARKER, killMarkedProcesses };
2
+ declare const killMarkedProcesses: (marker: string) => void;
3
+ declare const killMarkedProcessRun: (runPrefix: string) => void;
4
+ export { PROCESS_MARKER, killMarkedProcessRun, killMarkedProcesses };
4
5
  //# sourceMappingURL=kill-marked-processes.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"kill-marked-processes.d.ts","sourceRoot":"","sources":["../../src/process/kill-marked-processes.ts"],"names":[],"mappings":"AAEA,QAAA,MAAM,cAAc,uBAAuB,CAAC;AA2B5C,iBAAS,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAYjD;AAED,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,CAAC"}
1
+ {"version":3,"file":"kill-marked-processes.d.ts","sourceRoot":"","sources":["../../src/process/kill-marked-processes.ts"],"names":[],"mappings":"AAWA,QAAA,MAAM,cAAc,uBAAuB,CAAC;AAmE5C,QAAA,MAAM,mBAAmB,GAAI,QAAQ,MAAM,KAAG,IAE7C,CAAC;AAEF,QAAA,MAAM,oBAAoB,GAAI,WAAW,MAAM,KAAG,IAIjD,CAAC;AAEF,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,CAAC"}
@@ -1,38 +1,64 @@
1
1
  import { readdirSync, readFileSync } from "node:fs";
2
+ import { readProcessStatFields } from "./process-status.js";
2
3
  const PROCESS_MARKER = "GTKX_PROCESS_GUARD";
3
4
  const MAX_KILL_PASSES = 8;
4
- const isMarked = (pid, prefix) => {
5
+ const JOB_ID_PATTERN = /^[0-9a-f]{8}$/;
6
+ const processIdentity = (pid) => {
7
+ const fields = readProcessStatFields(pid);
8
+ const sessionId = Number(fields?.[3]);
9
+ const startTime = fields?.[19];
10
+ return startTime !== undefined && Number.isSafeInteger(sessionId)
11
+ ? { pid, sessionId, startTime }
12
+ : undefined;
13
+ };
14
+ const isMarked = (pid, isMatch) => {
5
15
  try {
6
16
  return readFileSync(`/proc/${String(pid)}/environ`, "utf8")
7
17
  .split("\0")
8
- .some((assignment) => assignment.startsWith(prefix));
18
+ .some((assignment) => isMatch(assignment));
9
19
  }
10
20
  catch {
11
21
  return false;
12
22
  }
13
23
  };
14
- const markedPids = (prefix) => readdirSync("/proc")
24
+ const markedProcesses = (isMatch) => readdirSync("/proc")
15
25
  .map(Number)
16
26
  .filter((pid) => Number.isSafeInteger(pid) && pid > 1 && pid !== process.pid)
17
- .filter((pid) => isMarked(pid, prefix));
18
- const killPid = (pid) => {
27
+ .filter((pid) => isMarked(pid, isMatch))
28
+ .map((pid) => processIdentity(pid))
29
+ .filter((identity) => identity !== undefined);
30
+ const killProcess = (identity, isMatch) => {
31
+ if (!isMarked(identity.pid, isMatch)) {
32
+ return;
33
+ }
34
+ const current = processIdentity(identity.pid);
35
+ if (current?.sessionId !== identity.sessionId ||
36
+ current.startTime !== identity.startTime) {
37
+ return;
38
+ }
19
39
  try {
20
- process.kill(pid, "SIGKILL");
40
+ process.kill(identity.pid, "SIGKILL");
21
41
  }
22
42
  catch {
23
43
  return;
24
44
  }
25
45
  };
26
- function killMarkedProcesses(prefix) {
46
+ const killMatchingProcesses = (isMatch) => {
27
47
  for (let pass = 0; pass < MAX_KILL_PASSES; pass += 1) {
28
- const pids = markedPids(prefix);
29
- if (pids.length === 0) {
48
+ const processes = markedProcesses(isMatch);
49
+ if (processes.length === 0) {
30
50
  return;
31
51
  }
32
- for (const pid of pids) {
33
- killPid(pid);
52
+ for (const identity of processes) {
53
+ killProcess(identity, isMatch);
34
54
  }
35
55
  }
36
- }
37
- export { PROCESS_MARKER, killMarkedProcesses };
56
+ };
57
+ const killMarkedProcesses = (marker) => {
58
+ killMatchingProcesses((assignment) => assignment === marker);
59
+ };
60
+ const killMarkedProcessRun = (runPrefix) => {
61
+ killMatchingProcesses((assignment) => assignment.startsWith(runPrefix) && JOB_ID_PATTERN.test(assignment.slice(runPrefix.length)));
62
+ };
63
+ export { PROCESS_MARKER, killMarkedProcessRun, killMarkedProcesses };
38
64
  //# sourceMappingURL=kill-marked-processes.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"kill-marked-processes.js","sourceRoot":"","sources":["../../src/process/kill-marked-processes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAEpD,MAAM,cAAc,GAAG,oBAAoB,CAAC;AAC5C,MAAM,eAAe,GAAG,CAAC,CAAC;AAE1B,MAAM,QAAQ,GAAG,CAAC,GAAW,EAAE,MAAc,EAAW,EAAE;IACtD,IAAI,CAAC;QACD,OAAO,YAAY,CAAC,SAAS,MAAM,CAAC,GAAG,CAAC,UAAU,EAAE,MAAM,CAAC;aACtD,KAAK,CAAC,IAAI,CAAC;aACX,IAAI,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC;IAC7D,CAAC;IAAC,MAAM,CAAC;QACL,OAAO,KAAK,CAAC;IACjB,CAAC;AACL,CAAC,CAAC;AAEF,MAAM,UAAU,GAAG,CAAC,MAAc,EAAY,EAAE,CAC5C,WAAW,CAAC,OAAO,CAAC;KACf,GAAG,CAAC,MAAM,CAAC;KACX,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,KAAK,OAAO,CAAC,GAAG,CAAC;KAC5E,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC;AAEhD,MAAM,OAAO,GAAG,CAAC,GAAW,EAAQ,EAAE;IAClC,IAAI,CAAC;QACD,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;IACjC,CAAC;IAAC,MAAM,CAAC;QACL,OAAO;IACX,CAAC;AACL,CAAC,CAAC;AAEF,SAAS,mBAAmB,CAAC,MAAc;IACvC,KAAK,IAAI,IAAI,GAAG,CAAC,EAAE,IAAI,GAAG,eAAe,EAAE,IAAI,IAAI,CAAC,EAAE,CAAC;QACnD,MAAM,IAAI,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;QAEhC,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACpB,OAAO;QACX,CAAC;QAED,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;YACrB,OAAO,CAAC,GAAG,CAAC,CAAC;QACjB,CAAC;IACL,CAAC;AACL,CAAC;AAED,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,CAAC","sourcesContent":["import { readdirSync, readFileSync } from \"node:fs\";\n\nconst PROCESS_MARKER = \"GTKX_PROCESS_GUARD\";\nconst MAX_KILL_PASSES = 8;\n\nconst isMarked = (pid: number, prefix: string): boolean => {\n try {\n return readFileSync(`/proc/${String(pid)}/environ`, \"utf8\")\n .split(\"\\0\")\n .some((assignment) => assignment.startsWith(prefix));\n } catch {\n return false;\n }\n};\n\nconst markedPids = (prefix: string): number[] =>\n readdirSync(\"/proc\")\n .map(Number)\n .filter((pid) => Number.isSafeInteger(pid) && pid > 1 && pid !== process.pid)\n .filter((pid) => isMarked(pid, prefix));\n\nconst killPid = (pid: number): void => {\n try {\n process.kill(pid, \"SIGKILL\");\n } catch {\n return;\n }\n};\n\nfunction killMarkedProcesses(prefix: string): void {\n for (let pass = 0; pass < MAX_KILL_PASSES; pass += 1) {\n const pids = markedPids(prefix);\n\n if (pids.length === 0) {\n return;\n }\n\n for (const pid of pids) {\n killPid(pid);\n }\n }\n}\n\nexport { PROCESS_MARKER, killMarkedProcesses };\n"]}
1
+ {"version":3,"file":"kill-marked-processes.js","sourceRoot":"","sources":["../../src/process/kill-marked-processes.ts"],"names":[],"mappings":"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","sourcesContent":["import { readdirSync, readFileSync } from \"node:fs\";\nimport { readProcessStatFields } from \"./process-status.ts\";\n\ntype ProcessIdentity = {\n pid: number;\n sessionId: number;\n startTime: string;\n};\n\ntype MarkerMatcher = (assignment: string) => boolean;\n\nconst PROCESS_MARKER = \"GTKX_PROCESS_GUARD\";\nconst MAX_KILL_PASSES = 8;\nconst JOB_ID_PATTERN = /^[0-9a-f]{8}$/;\n\nconst processIdentity = (pid: number): ProcessIdentity | undefined => {\n const fields = readProcessStatFields(pid);\n const sessionId = Number(fields?.[3]);\n const startTime = fields?.[19];\n\n return startTime !== undefined && Number.isSafeInteger(sessionId)\n ? { pid, sessionId, startTime }\n : undefined;\n};\n\nconst isMarked = (pid: number, isMatch: MarkerMatcher): boolean => {\n try {\n return readFileSync(`/proc/${String(pid)}/environ`, \"utf8\")\n .split(\"\\0\")\n .some((assignment) => isMatch(assignment));\n } catch {\n return false;\n }\n};\n\nconst markedProcesses = (isMatch: MarkerMatcher): ProcessIdentity[] =>\n readdirSync(\"/proc\")\n .map(Number)\n .filter((pid) => Number.isSafeInteger(pid) && pid > 1 && pid !== process.pid)\n .filter((pid) => isMarked(pid, isMatch))\n .map((pid) => processIdentity(pid))\n .filter((identity): identity is ProcessIdentity => identity !== undefined);\n\nconst killProcess = (identity: ProcessIdentity, isMatch: MarkerMatcher): void => {\n if (!isMarked(identity.pid, isMatch)) {\n return;\n }\n\n const current = processIdentity(identity.pid);\n\n if (\n current?.sessionId !== identity.sessionId ||\n current.startTime !== identity.startTime\n ) {\n return;\n }\n\n try {\n process.kill(identity.pid, \"SIGKILL\");\n } catch {\n return;\n }\n};\n\nconst killMatchingProcesses = (isMatch: MarkerMatcher): void => {\n for (let pass = 0; pass < MAX_KILL_PASSES; pass += 1) {\n const processes = markedProcesses(isMatch);\n\n if (processes.length === 0) {\n return;\n }\n\n for (const identity of processes) {\n killProcess(identity, isMatch);\n }\n }\n};\n\nconst killMarkedProcesses = (marker: string): void => {\n killMatchingProcesses((assignment) => assignment === marker);\n};\n\nconst killMarkedProcessRun = (runPrefix: string): void => {\n killMatchingProcesses((assignment) =>\n assignment.startsWith(runPrefix) && JOB_ID_PATTERN.test(assignment.slice(runPrefix.length)),\n );\n};\n\nexport { PROCESS_MARKER, killMarkedProcessRun, killMarkedProcesses };\n"]}
@@ -0,0 +1,16 @@
1
+ type ProcessGroupIdentity = {
2
+ processGroupId: number;
3
+ leaderStartTime: string;
4
+ };
5
+ type CleanupDirectoryIdentity = {
6
+ path: string;
7
+ device: string;
8
+ inode: string;
9
+ userId: string;
10
+ };
11
+ declare const processGroupIdentity: (processGroupId: number) => ProcessGroupIdentity | undefined;
12
+ declare const killProcessGroup: (identity: ProcessGroupIdentity, signal?: NodeJS.Signals) => void;
13
+ declare const cleanupDirectoryIdentity: (path: string) => CleanupDirectoryIdentity | undefined;
14
+ declare const removeCleanupDirectory: (identity: CleanupDirectoryIdentity) => void;
15
+ export { type CleanupDirectoryIdentity, cleanupDirectoryIdentity, killProcessGroup, type ProcessGroupIdentity, processGroupIdentity, removeCleanupDirectory, };
16
+ //# sourceMappingURL=kill-process-group.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kill-process-group.d.ts","sourceRoot":"","sources":["../../src/process/kill-process-group.ts"],"names":[],"mappings":"AAIA,KAAK,oBAAoB,GAAG;IACxB,cAAc,EAAE,MAAM,CAAC;IACvB,eAAe,EAAE,MAAM,CAAC;CAC3B,CAAC;AAEF,KAAK,wBAAwB,GAAG;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CAClB,CAAC;AAIF,QAAA,MAAM,oBAAoB,GAAI,gBAAgB,MAAM,KAAG,oBAAoB,GAAG,SAkB7E,CAAC;AAQF,QAAA,MAAM,gBAAgB,GAAI,UAAU,oBAAoB,EAAE,SAAQ,MAAM,CAAC,OAAmB,KAAG,IAU9F,CAAC;AAEF,QAAA,MAAM,wBAAwB,GAAI,MAAM,MAAM,KAAG,wBAAwB,GAAG,SAqB3E,CAAC;AAEF,QAAA,MAAM,sBAAsB,GAAI,UAAU,wBAAwB,KAAG,IAgBpE,CAAC;AAEF,OAAO,EACH,KAAK,wBAAwB,EAC7B,wBAAwB,EACxB,gBAAgB,EAChB,KAAK,oBAAoB,EACzB,oBAAoB,EACpB,sBAAsB,GACzB,CAAC"}
@@ -0,0 +1,70 @@
1
+ import { lstatSync, rmSync } from "node:fs";
2
+ import { isAbsolute, resolve } from "node:path";
3
+ import { readProcessStatFields } from "./process-status.js";
4
+ const isProcessGroupId = (value) => Number.isSafeInteger(value) && value > 1;
5
+ const processGroupIdentity = (processGroupId) => {
6
+ if (!isProcessGroupId(processGroupId)) {
7
+ return undefined;
8
+ }
9
+ const fields = readProcessStatFields(processGroupId);
10
+ if (fields === undefined) {
11
+ return undefined;
12
+ }
13
+ const actualProcessGroupId = Number(fields[2]);
14
+ const sessionId = Number(fields[3]);
15
+ const leaderStartTime = fields[19];
16
+ return actualProcessGroupId === processGroupId && sessionId === processGroupId && leaderStartTime !== undefined
17
+ ? { processGroupId, leaderStartTime }
18
+ : undefined;
19
+ };
20
+ const isCurrentProcessGroup = (identity) => {
21
+ const current = processGroupIdentity(identity.processGroupId);
22
+ return current?.leaderStartTime === identity.leaderStartTime;
23
+ };
24
+ const killProcessGroup = (identity, signal = "SIGKILL") => {
25
+ if (!isCurrentProcessGroup(identity)) {
26
+ return;
27
+ }
28
+ try {
29
+ process.kill(-identity.processGroupId, signal);
30
+ }
31
+ catch {
32
+ return;
33
+ }
34
+ };
35
+ const cleanupDirectoryIdentity = (path) => {
36
+ const absolutePath = resolve(path);
37
+ if (absolutePath === "/" || !isAbsolute(path)) {
38
+ return undefined;
39
+ }
40
+ try {
41
+ const entry = lstatSync(absolutePath, { bigint: true });
42
+ return entry.isDirectory()
43
+ ? {
44
+ path: absolutePath,
45
+ device: entry.dev.toString(),
46
+ inode: entry.ino.toString(),
47
+ userId: entry.uid.toString(),
48
+ }
49
+ : undefined;
50
+ }
51
+ catch {
52
+ return undefined;
53
+ }
54
+ };
55
+ const removeCleanupDirectory = (identity) => {
56
+ const current = cleanupDirectoryIdentity(identity.path);
57
+ if (current?.device !== identity.device ||
58
+ current.inode !== identity.inode ||
59
+ current.userId !== identity.userId) {
60
+ return;
61
+ }
62
+ try {
63
+ rmSync(identity.path, { recursive: true, force: true });
64
+ }
65
+ catch {
66
+ return;
67
+ }
68
+ };
69
+ export { cleanupDirectoryIdentity, killProcessGroup, processGroupIdentity, removeCleanupDirectory, };
70
+ //# sourceMappingURL=kill-process-group.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kill-process-group.js","sourceRoot":"","sources":["../../src/process/kill-process-group.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAChD,OAAO,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAc5D,MAAM,gBAAgB,GAAG,CAAC,KAAa,EAAW,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,CAAC;AAE9F,MAAM,oBAAoB,GAAG,CAAC,cAAsB,EAAoC,EAAE;IACtF,IAAI,CAAC,gBAAgB,CAAC,cAAc,CAAC,EAAE,CAAC;QACpC,OAAO,SAAS,CAAC;IACrB,CAAC;IAED,MAAM,MAAM,GAAG,qBAAqB,CAAC,cAAc,CAAC,CAAC;IAErD,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QACvB,OAAO,SAAS,CAAC;IACrB,CAAC;IAED,MAAM,oBAAoB,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/C,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IACpC,MAAM,eAAe,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;IAEnC,OAAO,oBAAoB,KAAK,cAAc,IAAI,SAAS,KAAK,cAAc,IAAI,eAAe,KAAK,SAAS;QAC3G,CAAC,CAAC,EAAE,cAAc,EAAE,eAAe,EAAE;QACrC,CAAC,CAAC,SAAS,CAAC;AACpB,CAAC,CAAC;AAEF,MAAM,qBAAqB,GAAG,CAAC,QAA8B,EAAW,EAAE;IACtE,MAAM,OAAO,GAAG,oBAAoB,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;IAE9D,OAAO,OAAO,EAAE,eAAe,KAAK,QAAQ,CAAC,eAAe,CAAC;AACjE,CAAC,CAAC;AAEF,MAAM,gBAAgB,GAAG,CAAC,QAA8B,EAAE,SAAyB,SAAS,EAAQ,EAAE;IAClG,IAAI,CAAC,qBAAqB,CAAC,QAAQ,CAAC,EAAE,CAAC;QACnC,OAAO;IACX,CAAC;IAED,IAAI,CAAC;QACD,OAAO,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC,CAAC;IACnD,CAAC;IAAC,MAAM,CAAC;QACL,OAAO;IACX,CAAC;AACL,CAAC,CAAC;AAEF,MAAM,wBAAwB,GAAG,CAAC,IAAY,EAAwC,EAAE;IACpF,MAAM,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEnC,IAAI,YAAY,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QAC5C,OAAO,SAAS,CAAC;IACrB,CAAC;IAED,IAAI,CAAC;QACD,MAAM,KAAK,GAAG,SAAS,CAAC,YAAY,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QAExD,OAAO,KAAK,CAAC,WAAW,EAAE;YACtB,CAAC,CAAC;gBACM,IAAI,EAAE,YAAY;gBAClB,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE;gBAC5B,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE;gBAC3B,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE;aAC/B;YACL,CAAC,CAAC,SAAS,CAAC;IACpB,CAAC;IAAC,MAAM,CAAC;QACL,OAAO,SAAS,CAAC;IACrB,CAAC;AACL,CAAC,CAAC;AAEF,MAAM,sBAAsB,GAAG,CAAC,QAAkC,EAAQ,EAAE;IACxE,MAAM,OAAO,GAAG,wBAAwB,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAExD,IACI,OAAO,EAAE,MAAM,KAAK,QAAQ,CAAC,MAAM;QACnC,OAAO,CAAC,KAAK,KAAK,QAAQ,CAAC,KAAK;QAChC,OAAO,CAAC,MAAM,KAAK,QAAQ,CAAC,MAAM,EACpC,CAAC;QACC,OAAO;IACX,CAAC;IAED,IAAI,CAAC;QACD,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC5D,CAAC;IAAC,MAAM,CAAC;QACL,OAAO;IACX,CAAC;AACL,CAAC,CAAC;AAEF,OAAO,EAEH,wBAAwB,EACxB,gBAAgB,EAEhB,oBAAoB,EACpB,sBAAsB,GACzB,CAAC","sourcesContent":["import { lstatSync, rmSync } from \"node:fs\";\nimport { isAbsolute, resolve } from \"node:path\";\nimport { readProcessStatFields } from \"./process-status.ts\";\n\ntype ProcessGroupIdentity = {\n processGroupId: number;\n leaderStartTime: string;\n};\n\ntype CleanupDirectoryIdentity = {\n path: string;\n device: string;\n inode: string;\n userId: string;\n};\n\nconst isProcessGroupId = (value: number): boolean => Number.isSafeInteger(value) && value > 1;\n\nconst processGroupIdentity = (processGroupId: number): ProcessGroupIdentity | undefined => {\n if (!isProcessGroupId(processGroupId)) {\n return undefined;\n }\n\n const fields = readProcessStatFields(processGroupId);\n\n if (fields === undefined) {\n return undefined;\n }\n\n const actualProcessGroupId = Number(fields[2]);\n const sessionId = Number(fields[3]);\n const leaderStartTime = fields[19];\n\n return actualProcessGroupId === processGroupId && sessionId === processGroupId && leaderStartTime !== undefined\n ? { processGroupId, leaderStartTime }\n : undefined;\n};\n\nconst isCurrentProcessGroup = (identity: ProcessGroupIdentity): boolean => {\n const current = processGroupIdentity(identity.processGroupId);\n\n return current?.leaderStartTime === identity.leaderStartTime;\n};\n\nconst killProcessGroup = (identity: ProcessGroupIdentity, signal: NodeJS.Signals = \"SIGKILL\"): void => {\n if (!isCurrentProcessGroup(identity)) {\n return;\n }\n\n try {\n process.kill(-identity.processGroupId, signal);\n } catch {\n return;\n }\n};\n\nconst cleanupDirectoryIdentity = (path: string): CleanupDirectoryIdentity | undefined => {\n const absolutePath = resolve(path);\n\n if (absolutePath === \"/\" || !isAbsolute(path)) {\n return undefined;\n }\n\n try {\n const entry = lstatSync(absolutePath, { bigint: true });\n\n return entry.isDirectory()\n ? {\n path: absolutePath,\n device: entry.dev.toString(),\n inode: entry.ino.toString(),\n userId: entry.uid.toString(),\n }\n : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst removeCleanupDirectory = (identity: CleanupDirectoryIdentity): void => {\n const current = cleanupDirectoryIdentity(identity.path);\n\n if (\n current?.device !== identity.device ||\n current.inode !== identity.inode ||\n current.userId !== identity.userId\n ) {\n return;\n }\n\n try {\n rmSync(identity.path, { recursive: true, force: true });\n } catch {\n return;\n }\n};\n\nexport {\n type CleanupDirectoryIdentity,\n cleanupDirectoryIdentity,\n killProcessGroup,\n type ProcessGroupIdentity,\n processGroupIdentity,\n removeCleanupDirectory,\n};\n"]}
@@ -1,16 +1,202 @@
1
- import { killMarkedProcesses } from "./kill-marked-processes.js";
1
+ import { readFileSync } from "node:fs";
2
+ import { killMarkedProcesses, killMarkedProcessRun } from "./kill-marked-processes.js";
3
+ import { killProcessGroup, processGroupIdentity, removeCleanupDirectory, } from "./kill-process-group.js";
2
4
  const GUARD_PREFIX = process.argv[2] ?? "";
5
+ const PROCESS_WATCH_ARGUMENT = process.argv[3];
3
6
  const WATCHED_SIGNALS = ["SIGTERM", "SIGINT", "SIGHUP"];
4
- const sweep = () => {
7
+ const OWNER_POLL_INTERVAL_MS = 50;
8
+ const SUPERVISOR_EXIT_TIMEOUT_MS = 2000;
9
+ const state = {
10
+ bufferedCommands: "",
11
+ isSweeping: false,
12
+ jobs: new Map(),
13
+ };
14
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
15
+ const isProcessIdentity = (value) => isRecord(value) &&
16
+ typeof value.pid === "number" &&
17
+ Number.isSafeInteger(value.pid) &&
18
+ value.pid > 1 &&
19
+ typeof value.startTime === "string" &&
20
+ /^\d+$/.test(value.startTime);
21
+ const isProcessWatch = (value) => isRecord(value) && isProcessIdentity(value.owner) && isProcessIdentity(value.target);
22
+ const isProcessGroupIdentity = (value) => isRecord(value) &&
23
+ typeof value.processGroupId === "number" &&
24
+ Number.isSafeInteger(value.processGroupId) &&
25
+ value.processGroupId > 1 &&
26
+ typeof value.leaderStartTime === "string" &&
27
+ /^\d+$/.test(value.leaderStartTime);
28
+ const isCleanupDirectoryIdentity = (value) => isRecord(value) &&
29
+ typeof value.path === "string" &&
30
+ typeof value.device === "string" &&
31
+ typeof value.inode === "string" &&
32
+ typeof value.userId === "string";
33
+ const isGuardJob = (value) => isRecord(value) &&
34
+ typeof value.marker === "string" &&
35
+ isProcessGroupIdentity(value.processGroup) &&
36
+ Array.isArray(value.cleanupDirectories) &&
37
+ value.cleanupDirectories.every(isCleanupDirectoryIdentity) &&
38
+ (value.signal === "SIGKILL" || value.signal === "SIGCONT");
39
+ const parseProcessWatch = () => {
40
+ if (PROCESS_WATCH_ARGUMENT === undefined) {
41
+ return undefined;
42
+ }
43
+ try {
44
+ const value = JSON.parse(PROCESS_WATCH_ARGUMENT);
45
+ return isProcessWatch(value) ? value : undefined;
46
+ }
47
+ catch {
48
+ return undefined;
49
+ }
50
+ };
51
+ const currentProcessIdentity = (pid) => {
52
+ try {
53
+ const stat = readFileSync(`/proc/${String(pid)}/stat`, "utf8");
54
+ const fields = stat.slice(stat.lastIndexOf(") ") + 2).split(" ", 20);
55
+ const state = fields[0];
56
+ const startTime = fields[19];
57
+ return startTime !== undefined && state !== undefined && !["Z", "X", "x"].includes(state)
58
+ ? { pid, startTime }
59
+ : undefined;
60
+ }
61
+ catch {
62
+ return undefined;
63
+ }
64
+ };
65
+ const isCurrentProcess = (identity) => currentProcessIdentity(identity.pid)?.startTime === identity.startTime;
66
+ const killProcess = (identity) => {
67
+ if (!isCurrentProcess(identity)) {
68
+ return;
69
+ }
70
+ try {
71
+ process.kill(identity.pid, "SIGKILL");
72
+ }
73
+ catch {
74
+ return;
75
+ }
76
+ };
77
+ const applyCommand = (command) => {
78
+ const operation = command[0];
79
+ let value;
80
+ try {
81
+ value = JSON.parse(command.slice(1));
82
+ }
83
+ catch {
84
+ return;
85
+ }
86
+ if (!isGuardJob(value)) {
87
+ return;
88
+ }
89
+ if (operation === "+") {
90
+ state.jobs.set(value.marker, value);
91
+ }
92
+ else if (operation === "-") {
93
+ state.jobs.delete(value.marker);
94
+ }
95
+ };
96
+ const receiveCommands = (chunk) => {
97
+ state.bufferedCommands += chunk.toString();
98
+ const commands = state.bufferedCommands.split("\n");
99
+ state.bufferedCommands = commands.pop() ?? "";
100
+ for (const command of commands) {
101
+ applyCommand(command);
102
+ }
103
+ };
104
+ const killJobs = () => {
105
+ for (const job of state.jobs.values()) {
106
+ killProcessGroup(job.processGroup, job.signal);
107
+ if (job.signal === "SIGKILL") {
108
+ killMarkedProcesses(job.marker);
109
+ }
110
+ }
111
+ };
112
+ const removeCleanupDirectories = () => {
113
+ const cleanupDirectories = new Map();
114
+ for (const job of state.jobs.values()) {
115
+ for (const identity of job.cleanupDirectories) {
116
+ cleanupDirectories.set(`${identity.device}:${identity.inode}`, identity);
117
+ }
118
+ }
119
+ for (const identity of cleanupDirectories.values()) {
120
+ removeCleanupDirectory(identity);
121
+ }
122
+ };
123
+ const hasRunningSupervisor = () => {
124
+ for (const job of state.jobs.values()) {
125
+ if (job.signal !== "SIGCONT") {
126
+ continue;
127
+ }
128
+ const current = processGroupIdentity(job.processGroup.processGroupId);
129
+ if (current?.leaderStartTime === job.processGroup.leaderStartTime) {
130
+ return true;
131
+ }
132
+ }
133
+ return false;
134
+ };
135
+ const forceSupervisors = () => {
136
+ for (const job of state.jobs.values()) {
137
+ if (job.signal === "SIGCONT") {
138
+ killProcessGroup(job.processGroup);
139
+ }
140
+ }
141
+ };
142
+ const finishSweep = () => {
5
143
  if (GUARD_PREFIX.length > 0) {
6
- killMarkedProcesses(GUARD_PREFIX);
144
+ killMarkedProcessRun(GUARD_PREFIX);
7
145
  }
146
+ removeCleanupDirectories();
8
147
  process.exit(0);
9
148
  };
149
+ const awaitSupervisors = (deadline) => {
150
+ if (hasRunningSupervisor() && Date.now() < deadline) {
151
+ setTimeout(() => {
152
+ awaitSupervisors(deadline);
153
+ }, OWNER_POLL_INTERVAL_MS);
154
+ return;
155
+ }
156
+ forceSupervisors();
157
+ finishSweep();
158
+ };
159
+ const sweep = (target) => {
160
+ if (state.isSweeping) {
161
+ return;
162
+ }
163
+ state.isSweeping = true;
164
+ applyCommand(state.bufferedCommands);
165
+ if (target !== undefined) {
166
+ killProcess(target);
167
+ }
168
+ killJobs();
169
+ awaitSupervisors(Date.now() + SUPERVISOR_EXIT_TIMEOUT_MS);
170
+ };
171
+ const watch = parseProcessWatch();
172
+ const startOwnerPoll = () => {
173
+ if (watch === undefined) {
174
+ return;
175
+ }
176
+ const ownerPoll = setInterval(() => {
177
+ if (isCurrentProcess(watch.owner)) {
178
+ return;
179
+ }
180
+ clearInterval(ownerPoll);
181
+ sweep(watch.target);
182
+ }, OWNER_POLL_INTERVAL_MS);
183
+ if (!isCurrentProcess(watch.owner)) {
184
+ clearInterval(ownerPoll);
185
+ sweep(watch.target);
186
+ }
187
+ };
188
+ startOwnerPoll();
10
189
  process.stdin.resume();
11
- process.stdin.on("end", sweep);
12
- process.stdin.on("error", sweep);
190
+ process.stdin.on("data", receiveCommands);
191
+ process.stdin.on("end", () => {
192
+ sweep();
193
+ });
194
+ process.stdin.on("error", () => {
195
+ sweep();
196
+ });
13
197
  for (const signal of WATCHED_SIGNALS) {
14
- process.on(signal, sweep);
198
+ process.on(signal, () => {
199
+ sweep();
200
+ });
15
201
  }
16
202
  //# sourceMappingURL=process-guard.js.map