@dbx-tools/cli-service 0.9.214 → 0.11.3

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/src/_host.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { spawn, type ChildProcess } from "node:child_process";
1
+ import type { ChildProcess } from "node:child_process";
2
2
  import { closeSync, openSync } from "node:fs";
3
3
  import { appendFile, mkdir } from "node:fs/promises";
4
4
  import { dirname, join } from "node:path";
5
5
 
6
6
  import { parseArgv } from "@dbx-tools/cli-args";
7
- import { shutdownProcessTree } from "@dbx-tools/core";
7
+ import { spawn, shutdownProcessTree, type ChildProcessResult } from "@dbx-tools/core";
8
8
  import { boundedRetryDelay } from "@dbx-tools/shared-core";
9
9
  import * as systrayModule from "systray2";
10
10
  import type SysTrayType from "systray2";
@@ -77,10 +77,10 @@ export class CliServiceHost {
77
77
  private readonly listenForControl: typeof listenForServiceControl;
78
78
  private readonly restartBackoff: ServiceRestartBackoff;
79
79
  private tray?: ServiceTray;
80
- private auth?: ChildProcess;
80
+ private auth?: ChildProcessResult;
81
81
  private authRestartTimer?: ReturnType<typeof setTimeout>;
82
82
  private authRestartAttempt = 0;
83
- private service?: ChildProcess;
83
+ private service?: ChildProcessResult;
84
84
  private restartTimer?: ReturnType<typeof setTimeout>;
85
85
  private restartAttempt = 0;
86
86
  private control?: Awaited<ReturnType<typeof listenForServiceControl>>;
@@ -155,12 +155,12 @@ export class CliServiceHost {
155
155
  private startAuthPreflight(command: CliServiceCommand): void {
156
156
  const child = this.startProcess(command);
157
157
  this.auth = child;
158
- child.once("error", () => {
158
+ void child.once("error", () => {
159
159
  if (this.auth !== child) return;
160
160
  this.auth = undefined;
161
161
  this.requestStop();
162
162
  });
163
- child.once("exit", (code, signal) => {
163
+ void child.once("exit", (code, signal) => {
164
164
  if (this.stopping || this.auth !== child) return;
165
165
  this.auth = undefined;
166
166
  if (code === 0) {
@@ -232,12 +232,12 @@ export class CliServiceHost {
232
232
  const child = this.startProcess(command);
233
233
  this.service = child;
234
234
  // A spawn failure (missing or non-executable binary) will not fix itself.
235
- child.once("error", () => {
235
+ void child.once("error", () => {
236
236
  if (this.service !== child) return;
237
237
  this.service = undefined;
238
238
  this.requestStop();
239
239
  });
240
- child.once("exit", (code, signal) => {
240
+ void child.once("exit", (code, signal) => {
241
241
  if (this.stopping || this.service !== child) return;
242
242
  this.service = undefined;
243
243
  this.scheduleServiceRestart(command, Date.now() - startedAt, signal ?? String(code));
@@ -269,7 +269,7 @@ export class CliServiceHost {
269
269
  }, delay);
270
270
  }
271
271
 
272
- private startProcess(command: CliServiceCommand): ChildProcess {
272
+ private startProcess(command: CliServiceCommand): ChildProcessResult {
273
273
  if (!command.executable) {
274
274
  throw new Error("installed service commands require an executable");
275
275
  }
@@ -277,10 +277,12 @@ export class CliServiceHost {
277
277
  const child = spawn(command.executable, command.arguments ?? [], {
278
278
  cwd: command.cwd,
279
279
  env: { ...process.env, ...command.environment },
280
- stdio: ["ignore", logDescriptor, logDescriptor],
280
+ stdin: "ignore",
281
+ stdout: logDescriptor,
282
+ stderr: logDescriptor,
281
283
  });
282
284
  closeSync(logDescriptor);
283
- child.once("error", (error) => {
285
+ void child.once("error", (error) => {
284
286
  void logError(this.paths.hostLog, error);
285
287
  });
286
288
  return child;
@@ -374,8 +376,8 @@ async function runCliServiceHost(configFile: string): Promise<void> {
374
376
  }
375
377
  }
376
378
 
377
- async function stopProcess(child: ChildProcess): Promise<void> {
378
- await shutdownProcessTree(child, {
379
+ async function stopProcess(child: ChildProcessResult): Promise<void> {
380
+ await child.shutdown({
379
381
  terminateTimeout: CHILD_TERMINATE_TIMEOUT_MILLISECONDS,
380
382
  killTimeout: CHILD_KILL_TIMEOUT_MILLISECONDS,
381
383
  });
@@ -383,7 +385,12 @@ async function stopProcess(child: ChildProcess): Promise<void> {
383
385
 
384
386
  async function stopTray(tray: ServiceTray): Promise<void> {
385
387
  const child = tray.process;
386
- if (child) await stopProcess(child);
388
+ if (child) {
389
+ await shutdownProcessTree(child, {
390
+ terminateTimeout: CHILD_TERMINATE_TIMEOUT_MILLISECONDS,
391
+ killTimeout: CHILD_KILL_TIMEOUT_MILLISECONDS,
392
+ });
393
+ }
387
394
  }
388
395
 
389
396
  async function logError(path: string, error: unknown): Promise<void> {
package/src/_package.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { existsSync, readFileSync } from "node:fs";
1
+ import { existsSync } from "node:fs";
2
2
  import { createRequire } from "node:module";
3
3
  import { dirname, isAbsolute, join, resolve } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
 
6
- import { projectUtils } from "@dbx-tools/core";
6
+ import { projectUtils, readJsonFileSync } from "@dbx-tools/core";
7
7
  import { isRecord } from "@dbx-tools/shared-core";
8
8
 
9
9
  export interface ServicePackage {
@@ -170,7 +170,7 @@ function resolveBin(directory: string, value: unknown, name?: string): string {
170
170
  }
171
171
 
172
172
  function readRecord(path: string): Record<string, unknown> {
173
- const value: unknown = JSON.parse(readFileSync(path, "utf8"));
173
+ const value = readJsonFileSync(path);
174
174
  if (!isRecord(value)) throw new Error(`package manifest is not an object: ${path}`);
175
175
  return value;
176
176
  }
package/src/_runtime.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
1
+ import { mkdir, rm } from "node:fs/promises";
2
2
  import { join, resolve } from "node:path";
3
3
 
4
- import { spawn, withFileLock } from "@dbx-tools/core";
4
+ import { readJsonFile, spawn, withFileLock, writeJsonFile } from "@dbx-tools/core";
5
5
  import { log, isRecord } from "@dbx-tools/shared-core";
6
6
 
7
7
  const logger = log.logger("cli:service");
@@ -37,25 +37,17 @@ export async function installServiceRuntime(
37
37
  const current = await readOptionalRecord(manifestPath);
38
38
  const previousOwners = ownerRecords(current[SERVICE_OWNERS_FIELD]);
39
39
  const owners = { ...previousOwners, [owner]: { ...dependencies } };
40
- await writeFile(
41
- manifestPath,
42
- `${JSON.stringify(
43
- {
44
- ...current,
45
- name: "@dbx-tools/service-runtime",
46
- private: true,
47
- dependencies: {
48
- ...unownedDependencies(stringRecord(current.dependencies), previousOwners),
49
- ...Object.assign({}, ...Object.values(owners)),
50
- ...dependencies,
51
- },
52
- [SERVICE_OWNERS_FIELD]: owners,
53
- },
54
- null,
55
- 2,
56
- )}\n`,
57
- "utf8",
58
- );
40
+ await writeJsonFile(manifestPath, {
41
+ ...current,
42
+ name: "@dbx-tools/service-runtime",
43
+ private: true,
44
+ dependencies: {
45
+ ...unownedDependencies(stringRecord(current.dependencies), previousOwners),
46
+ ...Object.assign({}, ...Object.values(owners)),
47
+ ...dependencies,
48
+ },
49
+ [SERVICE_OWNERS_FIELD]: owners,
50
+ });
59
51
  if (packages.length > 0) {
60
52
  logger.info("installing service runtime packages", { directory: runtimeDirectory, packages });
61
53
  }
@@ -148,7 +140,7 @@ export async function installServicePythonPackage(
148
140
 
149
141
  async function readOptionalRecord(path: string): Promise<Record<string, unknown>> {
150
142
  try {
151
- const value: unknown = JSON.parse(await readFile(path, "utf8"));
143
+ const value = await readJsonFile(path);
152
144
  if (!isRecord(value)) throw new Error(`JSON file is not an object: ${path}`);
153
145
  return value;
154
146
  } catch (error) {
package/src/_startup.ts CHANGED
@@ -1,9 +1,8 @@
1
- import { spawn as spawnChild, type ChildProcess } from "node:child_process";
2
1
  import { mkdir, rm, writeFile } from "node:fs/promises";
3
2
  import { dirname } from "node:path";
4
3
 
5
- import { spawn } from "@dbx-tools/core";
6
- import { sleep } from "@dbx-tools/shared-core";
4
+ import { spawn, type ChildProcessResult } from "@dbx-tools/core";
5
+ import { escapeHtml, sleep } from "@dbx-tools/shared-core";
7
6
 
8
7
  import type { ServicePaths, ServiceRuntimeContext } from "./_paths.ts";
9
8
  import type { CliServiceDefinition } from "./definition.ts";
@@ -17,6 +16,11 @@ export interface ServiceLaunch {
17
16
  readonly arguments: readonly string[];
18
17
  }
19
18
 
19
+ /** Live process started directly on platforms without a native service manager. */
20
+ export interface StartedStartup {
21
+ readonly child?: ChildProcessResult;
22
+ }
23
+
20
24
  export async function installStartup(
21
25
  definition: CliServiceDefinition,
22
26
  paths: ServicePaths,
@@ -45,7 +49,7 @@ export async function startStartup(
45
49
  paths: ServicePaths,
46
50
  runtime: ServiceRuntimeContext,
47
51
  launch: ServiceLaunch,
48
- ): Promise<ChildProcess | undefined> {
52
+ ): Promise<StartedStartup> {
49
53
  if (runtime.platform === "darwin") {
50
54
  const target = launchAgentTarget(definition, runtime);
51
55
  if (await launchAgentLoaded(definition, runtime)) {
@@ -57,14 +61,17 @@ export async function startStartup(
57
61
  true,
58
62
  );
59
63
  }
60
- return undefined;
64
+ return {};
61
65
  }
62
- const child = spawnChild(launch.executable, launch.arguments, {
66
+ const child = spawn(launch.executable, launch.arguments, {
63
67
  detached: true,
64
- stdio: "ignore",
68
+ forwardTerminationSignals: false,
69
+ stdin: "ignore",
70
+ stdout: "ignore",
71
+ stderr: "ignore",
65
72
  });
66
73
  child.unref();
67
- return child;
74
+ return { child };
68
75
  }
69
76
 
70
77
  export async function stopStartup(
@@ -85,7 +92,7 @@ export async function removeStartup(
85
92
 
86
93
  export function renderLaunchAgent(definition: CliServiceDefinition, launch: ServiceLaunch): string {
87
94
  const argumentsXml = [launch.executable, ...launch.arguments]
88
- .map((argument) => ` <string>${escapeXml(argument)}</string>`)
95
+ .map((argument) => ` <string>${escapeHtml(argument)}</string>`)
89
96
  .join("\n");
90
97
  return [
91
98
  '<?xml version="1.0" encoding="UTF-8"?>',
@@ -93,7 +100,7 @@ export function renderLaunchAgent(definition: CliServiceDefinition, launch: Serv
93
100
  '<plist version="1.0">',
94
101
  " <dict>",
95
102
  " <key>Label</key>",
96
- ` <string>${escapeXml(definition.id)}</string>`,
103
+ ` <string>${escapeHtml(definition.id)}</string>`,
97
104
  " <key>ProgramArguments</key>",
98
105
  " <array>",
99
106
  argumentsXml,
@@ -195,15 +202,6 @@ function escapeDesktopValue(value: string): string {
195
202
  return value.replaceAll("\\", "\\\\").replaceAll("\n", "\\n");
196
203
  }
197
204
 
198
- function escapeXml(value: string): string {
199
- return value
200
- .replaceAll("&", "&amp;")
201
- .replaceAll("<", "&lt;")
202
- .replaceAll(">", "&gt;")
203
- .replaceAll('"', "&quot;")
204
- .replaceAll("'", "&apos;");
205
- }
206
-
207
205
  function quoteDesktopArgument(value: string): string {
208
206
  return `"${value
209
207
  .replaceAll("\\", "\\\\")
package/src/cli.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  * @module
8
8
  */
9
9
 
10
- import { addArgs, parseArgs } from "@dbx-tools/cli-args";
10
+ import { addArgs, parseArgs, type CliObjectSchema } from "@dbx-tools/cli-args";
11
11
  import { spawn } from "@dbx-tools/core";
12
12
  import { Command } from "commander";
13
13
 
@@ -121,6 +121,25 @@ export function buildServiceCommand(
121
121
  return command;
122
122
  }
123
123
 
124
+ /** Build a service command whose install action accepts an owning option schema. */
125
+ export function buildConfiguredServiceCommand<TSchema extends CliObjectSchema>(
126
+ schema: TSchema,
127
+ source: (
128
+ options: ReturnType<TSchema["parse"]>,
129
+ serviceOptions?: CliServiceInstallOptions,
130
+ ) => CliServiceDefinition,
131
+ dependencies: CliServiceCliDependencies = DEFAULT_DEPENDENCIES,
132
+ ): Command {
133
+ let install!: Command;
134
+ const command = buildServiceCommand(
135
+ (serviceOptions) => source(parseArgs(install, schema), serviceOptions),
136
+ dependencies,
137
+ );
138
+ install = command.commands.find((child) => child.name() === "install")!;
139
+ addArgs(install, schema);
140
+ return command;
141
+ }
142
+
124
143
  function resolveDefinition(
125
144
  source: CliServiceDefinitionSource,
126
145
  ): (options?: CliServiceInstallOptions) => CliServiceDefinition {
package/src/service.ts CHANGED
@@ -283,7 +283,7 @@ export class CliService implements CliServiceLifecycle {
283
283
  this.binaryContext(this.binaryName(installedDefinition, "service")).path,
284
284
  paths.configFile,
285
285
  );
286
- const child = await startStartup(installedDefinition, paths, this.runtime, launch);
286
+ const { child } = await startStartup(installedDefinition, paths, this.runtime, launch);
287
287
  const started = waitForState(
288
288
  async () => (await requestServiceControl(paths.controlAddress, "status")) !== undefined,
289
289
  true,
@@ -297,8 +297,8 @@ export class CliService implements CliServiceLifecycle {
297
297
  await Promise.race([
298
298
  started,
299
299
  new Promise<never>((_resolve, reject) => {
300
- child.once("error", reject);
301
- child.once("exit", (code, signal) => {
300
+ void child.once("error", reject);
301
+ void child.once("exit", (code, signal) => {
302
302
  reject(
303
303
  new Error(
304
304
  `${this.definition.name} host exited before startup (${signal ?? String(code)})`,