@dbx-tools/cli-service 0.9.167 → 0.9.173

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/package.json CHANGED
@@ -23,9 +23,9 @@
23
23
  "typescript": "^5.9.3"
24
24
  },
25
25
  "dependencies": {
26
- "@dbx-tools/cli-args": "^0.9.167",
27
- "@dbx-tools/core": "^0.9.167",
28
- "@dbx-tools/shared-core": "^0.9.167",
26
+ "@dbx-tools/cli-args": "^0.9.173",
27
+ "@dbx-tools/core": "^0.9.173",
28
+ "@dbx-tools/shared-core": "^0.9.173",
29
29
  "bun": "1.4.2",
30
30
  "commander": "^15.0.0",
31
31
  "systray2": "^2.1.4",
@@ -45,7 +45,7 @@
45
45
  "./package.json": "./package.json"
46
46
  }
47
47
  },
48
- "version": "0.9.167",
48
+ "version": "0.9.173",
49
49
  "types": "./lib/index.d.ts",
50
50
  "dbxToolsConfig": {
51
51
  "tags": [
package/src/_config.ts CHANGED
@@ -1,17 +1,28 @@
1
1
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
2
  import { dirname } from "node:path";
3
3
 
4
+ import { z } from "zod";
4
5
  import { CliServiceDefinitionSchema, type CliServiceDefinition } from "./definition.ts";
5
6
 
6
- export async function readServiceDefinition(path: string): Promise<CliServiceDefinition> {
7
- return CliServiceDefinitionSchema.parse(JSON.parse(await readFile(path, "utf8")));
7
+ const InstalledCliServiceDefinitionSchema = CliServiceDefinitionSchema.unwrap().extend({
8
+ hostExecutable: z
9
+ .string()
10
+ .min(1)
11
+ .optional()
12
+ .describe("Installed service host executable. Absent on legacy installations."),
13
+ }).readonly();
14
+
15
+ export type InstalledCliServiceDefinition = z.infer<typeof InstalledCliServiceDefinitionSchema>;
16
+
17
+ export async function readServiceDefinition(path: string): Promise<InstalledCliServiceDefinition> {
18
+ return InstalledCliServiceDefinitionSchema.parse(JSON.parse(await readFile(path, "utf8")));
8
19
  }
9
20
 
10
21
  export async function writeServiceDefinition(
11
22
  path: string,
12
- definition: CliServiceDefinition,
23
+ definition: CliServiceDefinition & { readonly hostExecutable: string },
13
24
  ): Promise<void> {
14
- const parsed = CliServiceDefinitionSchema.parse(definition);
25
+ const parsed = InstalledCliServiceDefinitionSchema.parse(definition);
15
26
  await mkdir(dirname(path), { recursive: true });
16
27
  const temporary = `${path}.${process.pid}.tmp`;
17
28
  await writeFile(temporary, `${JSON.stringify(parsed, null, 2)}\n`, {
package/src/_host.ts CHANGED
@@ -34,6 +34,15 @@ interface ActionMenuItem extends MenuItem {
34
34
  readonly click?: () => void;
35
35
  }
36
36
 
37
+ type ServiceTray = Pick<SysTrayType, "ready" | "onClick" | "onError" | "onExit"> & {
38
+ readonly process?: ChildProcess | null;
39
+ };
40
+
41
+ interface CliServiceHostDependencies {
42
+ readonly createTray?: () => ServiceTray;
43
+ readonly listenForControl?: typeof listenForServiceControl;
44
+ }
45
+
37
46
  function systrayConstructor(): typeof SysTrayType {
38
47
  const loaded: unknown = systrayModule.default;
39
48
  if (typeof loaded === "function") return loaded as typeof SysTrayType;
@@ -43,46 +52,47 @@ function systrayConstructor(): typeof SysTrayType {
43
52
  throw new TypeError("systray2 did not provide a constructor");
44
53
  }
45
54
 
46
- class CliServiceHost {
55
+ export class CliServiceHost {
47
56
  private readonly definition: CliServiceDefinition;
48
57
  private readonly paths: ServicePaths;
49
58
  private readonly requestStop: () => void;
50
- private tray?: SysTrayType;
59
+ private readonly createServiceTray: () => ServiceTray;
60
+ private readonly listenForControl: typeof listenForServiceControl;
61
+ private tray?: ServiceTray;
51
62
  private service?: ChildProcess;
52
63
  private control?: Awaited<ReturnType<typeof listenForServiceControl>>;
53
64
  private stopping = false;
54
65
 
55
- constructor(definition: CliServiceDefinition, paths: ServicePaths, requestStop: () => void) {
66
+ constructor(
67
+ definition: CliServiceDefinition,
68
+ paths: ServicePaths,
69
+ requestStop: () => void,
70
+ dependencies: CliServiceHostDependencies = {},
71
+ ) {
56
72
  this.definition = definition;
57
73
  this.paths = paths;
58
74
  this.requestStop = requestStop;
75
+ this.createServiceTray = dependencies.createTray ?? (() => this.createTray());
76
+ this.listenForControl = dependencies.listenForControl ?? listenForServiceControl;
59
77
  }
60
78
 
61
79
  async start(): Promise<void> {
62
80
  await mkdir(this.paths.directory, { recursive: true });
63
- this.service = this.definition.command
64
- ? this.startProcess(this.definition.command, true)
65
- : undefined;
66
- this.tray = this.createTray();
67
- await this.tray.ready();
68
- this.tray.onError((error) => {
69
- void logError(this.paths.hostLog, error);
70
- this.requestStop();
71
- });
72
- this.tray.onExit((code, signal) => {
73
- if (this.stopping) return;
74
- void logMessage(this.paths.hostLog, `system tray exited (${signal ?? String(code)})`);
75
- this.requestStop();
76
- });
77
- await this.tray.onClick((action) => {
78
- const item = action.item as ActionMenuItem;
79
- item.click?.();
80
- });
81
- this.control = await listenForServiceControl(
82
- this.paths.controlAddress,
83
- () => this.status(),
84
- this.requestStop,
85
- );
81
+ try {
82
+ this.control = await this.listenForControl(
83
+ this.paths.controlAddress,
84
+ () => this.status(),
85
+ this.requestStop,
86
+ );
87
+ this.service = this.definition.command
88
+ ? this.startProcess(this.definition.command, true)
89
+ : undefined;
90
+ this.tray = this.createServiceTray();
91
+ void this.initializeTray(this.tray);
92
+ } catch (error) {
93
+ await this.stop();
94
+ throw error;
95
+ }
86
96
  }
87
97
 
88
98
  async stop(): Promise<void> {
@@ -93,9 +103,7 @@ class CliServiceHost {
93
103
  this.control = undefined;
94
104
  }
95
105
  if (this.tray) {
96
- if (this.tray.process.exitCode === null && this.tray.process.signalCode === null) {
97
- await this.tray.kill(false);
98
- }
106
+ await stopTray(this.tray);
99
107
  this.tray = undefined;
100
108
  }
101
109
  if (this.service) {
@@ -112,6 +120,30 @@ class CliServiceHost {
112
120
  };
113
121
  }
114
122
 
123
+ private async initializeTray(tray: ServiceTray): Promise<void> {
124
+ try {
125
+ await tray.ready();
126
+ if (this.stopping || this.tray !== tray) return;
127
+ tray.onError((error) => {
128
+ void logError(this.paths.hostLog, error);
129
+ });
130
+ tray.onExit((code, signal) => {
131
+ if (this.tray === tray) this.tray = undefined;
132
+ if (this.stopping) return;
133
+ void logMessage(this.paths.hostLog, `system tray exited (${signal ?? String(code)})`);
134
+ });
135
+ await tray.onClick((action) => {
136
+ const item = action.item as ActionMenuItem;
137
+ item.click?.();
138
+ });
139
+ } catch (error) {
140
+ await logError(this.paths.hostLog, error);
141
+ if (this.tray !== tray) return;
142
+ await stopTray(tray);
143
+ this.tray = undefined;
144
+ }
145
+ }
146
+
115
147
  private startProcess(command: CliServiceCommand, managed: boolean): ChildProcess {
116
148
  if (!command.executable) {
117
149
  throw new Error("installed service commands require an executable");
@@ -237,6 +269,11 @@ async function stopProcess(child: ChildProcess): Promise<void> {
237
269
  }
238
270
  }
239
271
 
272
+ async function stopTray(tray: ServiceTray): Promise<void> {
273
+ const child = tray.process;
274
+ if (child) await stopProcess(child);
275
+ }
276
+
240
277
  async function logError(path: string, error: unknown): Promise<void> {
241
278
  await logMessage(path, error instanceof Error ? (error.stack ?? error.message) : String(error));
242
279
  }
package/src/_paths.ts CHANGED
@@ -9,6 +9,7 @@ export interface ServiceRuntimeContext {
9
9
  readonly environment: Readonly<NodeJS.ProcessEnv>;
10
10
  readonly homeDirectory: string;
11
11
  readonly temporaryDirectory: string;
12
+ readonly userId?: number;
12
13
  }
13
14
 
14
15
  export interface ServicePaths {
@@ -26,6 +27,7 @@ export function defaultRuntimeContext(): ServiceRuntimeContext {
26
27
  environment: process.env,
27
28
  homeDirectory: homedir(),
28
29
  temporaryDirectory: tmpdir(),
30
+ userId: process.getuid?.(),
29
31
  };
30
32
  }
31
33
 
package/src/_runtime.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
2
- import { join } from "node:path";
2
+ import { join, resolve } from "node:path";
3
3
 
4
- import { spawn } from "@dbx-tools/core";
4
+ import { spawn, withFileLock } from "@dbx-tools/core";
5
5
  import { log, isRecord } from "@dbx-tools/shared-core";
6
6
 
7
7
  const logger = log.logger("cli:service");
@@ -15,40 +15,64 @@ export async function installServiceRuntime(
15
15
  directory: string,
16
16
  dependencies: Readonly<Record<string, string>>,
17
17
  ): Promise<void> {
18
- const packages = Object.keys(dependencies);
19
- await mkdir(directory, { recursive: true });
20
- const manifestPath = join(directory, "package.json");
21
- const current = await readOptionalRecord(manifestPath);
22
- await writeFile(
23
- manifestPath,
24
- `${JSON.stringify(
25
- {
26
- ...current,
27
- name: "@dbx-tools/service-runtime",
28
- private: true,
29
- dependencies: {
30
- ...stringRecord(current.dependencies),
31
- ...dependencies,
18
+ const runtimeDirectory = resolve(directory);
19
+ if (await serviceRuntimeSatisfied(runtimeDirectory, dependencies)) return;
20
+ await withFileLock(["cli-service-runtime", runtimeDirectory], async () => {
21
+ if (await serviceRuntimeSatisfied(runtimeDirectory, dependencies)) return;
22
+ await mkdir(runtimeDirectory, { recursive: true });
23
+ const packages = Object.keys(dependencies);
24
+ const manifestPath = join(runtimeDirectory, "package.json");
25
+ const current = await readOptionalRecord(manifestPath);
26
+ await writeFile(
27
+ manifestPath,
28
+ `${JSON.stringify(
29
+ {
30
+ ...current,
31
+ name: "@dbx-tools/service-runtime",
32
+ private: true,
33
+ dependencies: {
34
+ ...stringRecord(current.dependencies),
35
+ ...dependencies,
36
+ },
32
37
  },
33
- },
34
- null,
35
- 2,
36
- )}\n`,
37
- "utf8",
38
- );
39
- if (packages.length > 0) {
40
- logger.info("installing service runtime packages", { directory, packages });
41
- }
42
- await spawn(bunExecutable, ["install", "--production", "--cwd", directory], {
43
- check: true,
44
- cwd: directory,
45
- stdin: "ignore",
46
- stdout: "capture",
47
- stderr: "capture",
38
+ null,
39
+ 2,
40
+ )}\n`,
41
+ "utf8",
42
+ );
43
+ if (packages.length > 0) {
44
+ logger.info("installing service runtime packages", { directory: runtimeDirectory, packages });
45
+ }
46
+ await spawn(bunExecutable, ["install", "--production", "--cwd", runtimeDirectory], {
47
+ check: true,
48
+ cwd: runtimeDirectory,
49
+ stdin: "ignore",
50
+ stdout: "capture",
51
+ stderr: "capture",
52
+ });
53
+ if (packages.length > 0) {
54
+ logger.info("service runtime packages installed", {
55
+ directory: runtimeDirectory,
56
+ packages,
57
+ });
58
+ }
48
59
  });
49
- if (packages.length > 0) {
50
- logger.info("service runtime packages installed", { directory, packages });
60
+ }
61
+
62
+ async function serviceRuntimeSatisfied(
63
+ directory: string,
64
+ dependencies: Readonly<Record<string, string>>,
65
+ ): Promise<boolean> {
66
+ const manifest = await readOptionalRecord(join(directory, "package.json"));
67
+ const declared = stringRecord(manifest.dependencies);
68
+ for (const [name, version] of Object.entries(dependencies)) {
69
+ if (declared[name] !== version) return false;
70
+ const installed = await readOptionalRecord(
71
+ join(directory, "node_modules", ...name.split("/"), "package.json"),
72
+ );
73
+ if (installed.version !== version) return false;
51
74
  }
75
+ return true;
52
76
  }
53
77
 
54
78
  /** Create a clean uv environment and install the primary and companion Python packages. */
package/src/_startup.ts CHANGED
@@ -1,9 +1,16 @@
1
+ import { spawn as spawnChild, type ChildProcess } from "node:child_process";
1
2
  import { mkdir, rm, writeFile } from "node:fs/promises";
2
3
  import { dirname } from "node:path";
3
4
 
5
+ import { spawn } from "@dbx-tools/core";
6
+ import { sleep } from "@dbx-tools/shared-core";
7
+
4
8
  import type { ServicePaths, ServiceRuntimeContext } from "./_paths.ts";
5
9
  import type { CliServiceDefinition } from "./definition.ts";
6
10
 
11
+ const LAUNCH_AGENT_STATE_TIMEOUT_MILLISECONDS = 10_000;
12
+ const LAUNCH_AGENT_POLL_INTERVAL_MILLISECONDS = 100;
13
+
7
14
  export interface ServiceLaunch {
8
15
  readonly executable: string;
9
16
  readonly arguments: readonly string[];
@@ -26,9 +33,48 @@ export async function installStartup(
26
33
  encoding: "utf8",
27
34
  mode: runtime.platform === "win32" ? undefined : 0o644,
28
35
  });
36
+ if (runtime.platform === "darwin") {
37
+ await unloadLaunchAgent(definition, runtime);
38
+ await runLaunchctl(["enable", launchAgentTarget(definition, runtime)], runtime, true);
39
+ }
40
+ }
41
+
42
+ export async function startStartup(
43
+ definition: CliServiceDefinition,
44
+ paths: ServicePaths,
45
+ runtime: ServiceRuntimeContext,
46
+ launch: ServiceLaunch,
47
+ ): Promise<ChildProcess | undefined> {
48
+ if (runtime.platform === "darwin") {
49
+ const target = launchAgentTarget(definition, runtime);
50
+ if (await launchAgentLoaded(definition, runtime)) {
51
+ await runLaunchctl(["kickstart", "-k", target], runtime, true);
52
+ } else {
53
+ await runLaunchctl(["bootstrap", launchAgentDomain(runtime), paths.startupFile], runtime, true);
54
+ }
55
+ return undefined;
56
+ }
57
+ const child = spawnChild(launch.executable, launch.arguments, {
58
+ detached: true,
59
+ stdio: "ignore",
60
+ });
61
+ child.unref();
62
+ return child;
63
+ }
64
+
65
+ export async function stopStartup(
66
+ definition: CliServiceDefinition,
67
+ runtime: ServiceRuntimeContext,
68
+ ): Promise<void> {
69
+ if (runtime.platform === "darwin") await unloadLaunchAgent(definition, runtime);
29
70
  }
30
71
 
31
- export async function removeStartup(paths: ServicePaths): Promise<void> {
72
+ export async function removeStartup(
73
+ definition: CliServiceDefinition,
74
+ paths: ServicePaths,
75
+ runtime: ServiceRuntimeContext,
76
+ ): Promise<void> {
77
+ await stopStartup(definition, runtime);
32
78
  await rm(paths.startupFile, { force: true });
33
79
  }
34
80
 
@@ -77,6 +123,67 @@ export function renderWindowsStartup(launch: ServiceLaunch): string {
77
123
  return `@echo off\r\nstart "" /b ${command}\r\n`;
78
124
  }
79
125
 
126
+ async function unloadLaunchAgent(
127
+ definition: CliServiceDefinition,
128
+ runtime: ServiceRuntimeContext,
129
+ ): Promise<void> {
130
+ if (!(await launchAgentLoaded(definition, runtime))) return;
131
+ await runLaunchctl(["bootout", launchAgentTarget(definition, runtime)], runtime, true);
132
+ await waitForLaunchAgentState(definition, runtime, false);
133
+ }
134
+
135
+ async function waitForLaunchAgentState(
136
+ definition: CliServiceDefinition,
137
+ runtime: ServiceRuntimeContext,
138
+ loaded: boolean,
139
+ ): Promise<void> {
140
+ const deadline = Date.now() + LAUNCH_AGENT_STATE_TIMEOUT_MILLISECONDS;
141
+ while (Date.now() < deadline) {
142
+ if ((await launchAgentLoaded(definition, runtime)) === loaded) return;
143
+ await sleep(LAUNCH_AGENT_POLL_INTERVAL_MILLISECONDS);
144
+ }
145
+ throw new Error(`${definition.name} LaunchAgent did not ${loaded ? "load" : "unload"}`);
146
+ }
147
+
148
+ async function launchAgentLoaded(
149
+ definition: CliServiceDefinition,
150
+ runtime: ServiceRuntimeContext,
151
+ ): Promise<boolean> {
152
+ const result = await runLaunchctl(
153
+ ["print", launchAgentTarget(definition, runtime)],
154
+ runtime,
155
+ false,
156
+ );
157
+ return result.exitCode === 0;
158
+ }
159
+
160
+ function launchAgentDomain(runtime: ServiceRuntimeContext): string {
161
+ const userId = runtime.userId;
162
+ if (userId === undefined) throw new Error("macOS service installation requires a user ID");
163
+ return `gui/${userId}`;
164
+ }
165
+
166
+ function launchAgentTarget(
167
+ definition: CliServiceDefinition,
168
+ runtime: ServiceRuntimeContext,
169
+ ): string {
170
+ return `${launchAgentDomain(runtime)}/${definition.id}`;
171
+ }
172
+
173
+ function runLaunchctl(
174
+ arguments_: readonly string[],
175
+ runtime: ServiceRuntimeContext,
176
+ check: boolean,
177
+ ) {
178
+ return spawn("launchctl", [...arguments_], {
179
+ check,
180
+ env: runtime.environment,
181
+ stdin: "ignore",
182
+ stdout: "capture",
183
+ stderr: "capture",
184
+ });
185
+ }
186
+
80
187
  function escapeDesktopValue(value: string): string {
81
188
  return value.replaceAll("\\", "\\\\").replaceAll("\n", "\\n");
82
189
  }