@jmanuelcorral/bond-app 0.1.6 → 0.2.1

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.
@@ -0,0 +1,861 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { execFile, execFileSync } from 'node:child_process';
5
+ import { promisify } from 'node:util';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ import type { CommandOutput } from './doctor.ts';
9
+ import { installWindowsTask, queryWindowsTask, startWindowsTask, stopWindowsTask, uninstallWindowsTask } from './service-windows.ts';
10
+
11
+ const execFileAsync = promisify(execFile);
12
+ const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
13
+
14
+ export const DEFAULT_SYSTEMD_UNIT = 'bond-app';
15
+ export const DEFAULT_LAUNCHD_LABEL = 'dev.bond-app.orchestrator';
16
+
17
+ export type ServiceAction = 'status' | 'install' | 'start' | 'stop' | 'restart' | 'uninstall';
18
+ export type ServiceManager = 'systemd' | 'launchd' | 'windows';
19
+
20
+ /**
21
+ * The bond-app the service starts must outlive this process: run from `npx` (its cache,
22
+ * `…/_npx/<hash>/…`, is cleared at any time), point at the global install `setup` has just
23
+ * made instead. Any other copy (global install, a checkout) is used as it is.
24
+ */
25
+ export function stableBinPath(current: string, npmGlobalRoot: () => string | null = defaultNpmGlobalRoot): string {
26
+ if (!/[\\/]_npx[\\/]/.test(current)) return current;
27
+ const root = npmGlobalRoot();
28
+ const global = root ? path.join(root, '@jmanuelcorral', 'bond-app', 'bin', 'bond-app.js') : null;
29
+ return global && fs.existsSync(global) ? global : current;
30
+ }
31
+
32
+ function defaultNpmGlobalRoot(): string | null {
33
+ try {
34
+ return execFileSync(process.platform === 'win32' ? 'npm.cmd' : 'npm', ['root', '-g'], { encoding: 'utf8', timeout: 15_000 }).trim() || null;
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
39
+
40
+ export interface ServiceDeps {
41
+ runCommand?: (cmd: string, args: string[], timeoutMs?: number) => Promise<CommandOutput>;
42
+ platform?: NodeJS.Platform;
43
+ homeDir?: string;
44
+ xdgConfigHome?: string;
45
+ nodePath?: string;
46
+ binPath?: string;
47
+ /** `npm root -g` (injectable): where the global bond-app lives when this copy is npx's. */
48
+ npmGlobalRoot?: () => string | null;
49
+ env?: NodeJS.ProcessEnv;
50
+ uid?: number;
51
+ }
52
+
53
+ export interface ServiceOptions {
54
+ port?: number;
55
+ host?: string;
56
+ dataDir?: string;
57
+ runnerImage?: string;
58
+ serviceName?: string;
59
+ deps?: ServiceDeps;
60
+ }
61
+
62
+ export interface ServiceStatusResult {
63
+ ok: boolean;
64
+ manager: ServiceManager;
65
+ supported: boolean;
66
+ available: boolean;
67
+ installed: boolean;
68
+ active: boolean;
69
+ enabled: boolean;
70
+ unitPath: string | null;
71
+ serviceName: string;
72
+ detail: string;
73
+ }
74
+
75
+ export interface ServiceActionResult {
76
+ ok: boolean;
77
+ action: ServiceAction;
78
+ manager: ServiceManager;
79
+ supported: boolean;
80
+ available: boolean;
81
+ installed: boolean;
82
+ active: boolean;
83
+ unitPath: string | null;
84
+ serviceName: string;
85
+ detail: string;
86
+ }
87
+
88
+ async function defaultRunCommand(cmd: string, args: string[], timeoutMs = 15_000): Promise<CommandOutput> {
89
+ try {
90
+ const { stdout, stderr } = await execFileAsync(cmd, args, {
91
+ encoding: 'utf8',
92
+ timeout: timeoutMs,
93
+ });
94
+ return { ok: true, stdout: stdout || '', stderr: stderr || '' };
95
+ } catch (err: unknown) {
96
+ const e = err as { stdout?: string; stderr?: string; message?: string };
97
+ return {
98
+ ok: false,
99
+ stdout: typeof e.stdout === 'string' ? e.stdout : '',
100
+ stderr: typeof e.stderr === 'string' ? e.stderr : '',
101
+ error: e.message || String(err),
102
+ };
103
+ }
104
+ }
105
+
106
+ function resolveManager(platform: NodeJS.Platform): ServiceManager {
107
+ if (platform === 'darwin') return 'launchd';
108
+ if (platform === 'win32') return 'windows';
109
+ return 'systemd';
110
+ }
111
+
112
+ function resolveServiceContext(options: ServiceOptions = {}) {
113
+ const deps = options.deps ?? {};
114
+ const env = deps.env ?? process.env;
115
+ const platform = deps.platform ?? process.platform;
116
+ const manager = resolveManager(platform);
117
+ const homeDir = deps.homeDir ?? os.homedir();
118
+ const xdgConfigHome =
119
+ deps.xdgConfigHome ??
120
+ (env.XDG_CONFIG_HOME && path.isAbsolute(env.XDG_CONFIG_HOME)
121
+ ? env.XDG_CONFIG_HOME
122
+ : path.join(homeDir, '.config'));
123
+
124
+ const port = options.port ?? parseInt(env.BOND_APP_PORT || '3000', 10);
125
+ const host = options.host ?? env.BOND_APP_HOST ?? '127.0.0.1';
126
+ const dataDir = path.resolve(options.dataDir ?? env.BOND_APP_DATA_DIR ?? path.join(homeDir, '.bond-app'));
127
+ const runnerImage = options.runnerImage ?? (env.RUNNER_IMAGE || undefined);
128
+ const nodePath = deps.nodePath ?? process.execPath;
129
+ const binPath = path.resolve(deps.binPath ?? stableBinPath(path.join(repoRoot, 'bin', 'bond-app.js'), deps.npmGlobalRoot));
130
+ const runCommand = deps.runCommand ?? defaultRunCommand;
131
+ const uid = deps.uid ?? (typeof process.getuid === 'function' ? process.getuid() : 501);
132
+
133
+ const rawName = options.serviceName?.trim();
134
+ const serviceName =
135
+ manager === 'launchd'
136
+ ? rawName || DEFAULT_LAUNCHD_LABEL
137
+ : (rawName || DEFAULT_SYSTEMD_UNIT).replace(/\.service$/, '');
138
+
139
+ const unitPath =
140
+ manager === 'systemd'
141
+ ? path.join(xdgConfigHome, 'systemd', 'user', `${serviceName}.service`)
142
+ : manager === 'launchd'
143
+ ? path.join(homeDir, 'Library', 'LaunchAgents', `${serviceName}.plist`)
144
+ : null;
145
+
146
+ return {
147
+ manager,
148
+ platform,
149
+ homeDir,
150
+ xdgConfigHome,
151
+ port,
152
+ host,
153
+ dataDir,
154
+ runnerImage,
155
+ nodePath,
156
+ binPath,
157
+ runCommand,
158
+ uid,
159
+ serviceName,
160
+ unitPath,
161
+ };
162
+ }
163
+
164
+ function quoteSystemdArg(value: string): string {
165
+ if (/[\s"'\\$`]/.test(value)) {
166
+ return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
167
+ }
168
+ return value;
169
+ }
170
+
171
+ function quoteSystemdEnv(key: string, value: string): string {
172
+ if (/[\s"'\\]/.test(value)) {
173
+ return `"${key}=${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
174
+ }
175
+ return `${key}=${value}`;
176
+ }
177
+
178
+ export function renderSystemdUnit(params: {
179
+ nodePath: string;
180
+ binPath: string;
181
+ port: number;
182
+ host?: string;
183
+ dataDir: string;
184
+ runnerImage?: string;
185
+ }): string {
186
+ const execParts = [
187
+ quoteSystemdArg(params.nodePath),
188
+ quoteSystemdArg(params.binPath),
189
+ 'start',
190
+ '--port',
191
+ String(params.port),
192
+ '--data-dir',
193
+ quoteSystemdArg(params.dataDir),
194
+ ];
195
+ if (params.host && params.host !== '127.0.0.1') {
196
+ execParts.push('--host', quoteSystemdArg(params.host));
197
+ }
198
+
199
+ const envLines = [`Environment=${quoteSystemdEnv('BOND_APP_DATA_DIR', params.dataDir)}`];
200
+ if (params.runnerImage) {
201
+ envLines.push(`Environment=${quoteSystemdEnv('RUNNER_IMAGE', params.runnerImage)}`);
202
+ }
203
+
204
+ const logPath = path.join(params.dataDir, 'orchestrator.log');
205
+
206
+ return [
207
+ '[Unit]',
208
+ 'Description=bond-app orchestrator',
209
+ 'After=network-online.target',
210
+ 'Wants=network-online.target',
211
+ '',
212
+ '[Service]',
213
+ 'Type=simple',
214
+ `ExecStart=${execParts.join(' ')}`,
215
+ 'Restart=on-failure',
216
+ 'RestartSec=3',
217
+ ...envLines,
218
+ `StandardOutput=append:${quoteSystemdArg(logPath)}`,
219
+ `StandardError=append:${quoteSystemdArg(logPath)}`,
220
+ '',
221
+ '[Install]',
222
+ 'WantedBy=default.target',
223
+ '',
224
+ ].join('\n');
225
+ }
226
+
227
+ function escapeXml(value: string): string {
228
+ return value
229
+ .replace(/&/g, '&amp;')
230
+ .replace(/</g, '&lt;')
231
+ .replace(/>/g, '&gt;')
232
+ .replace(/"/g, '&quot;')
233
+ .replace(/'/g, '&apos;');
234
+ }
235
+
236
+ export function renderLaunchdPlist(params: {
237
+ label: string;
238
+ nodePath: string;
239
+ binPath: string;
240
+ port: number;
241
+ host?: string;
242
+ dataDir: string;
243
+ runnerImage?: string;
244
+ }): string {
245
+ const args = [
246
+ params.nodePath,
247
+ params.binPath,
248
+ 'start',
249
+ '--port',
250
+ String(params.port),
251
+ '--data-dir',
252
+ params.dataDir,
253
+ ];
254
+ if (params.host && params.host !== '127.0.0.1') {
255
+ args.push('--host', params.host);
256
+ }
257
+
258
+ const envEntries = [` <key>BOND_APP_DATA_DIR</key>`, ` <string>${escapeXml(params.dataDir)}</string>`];
259
+ if (params.runnerImage) {
260
+ envEntries.push(` <key>RUNNER_IMAGE</key>`, ` <string>${escapeXml(params.runnerImage)}</string>`);
261
+ }
262
+
263
+ const logPath = path.join(params.dataDir, 'orchestrator.log');
264
+
265
+ return [
266
+ '<?xml version="1.0" encoding="UTF-8"?>',
267
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
268
+ '<plist version="1.0">',
269
+ '<dict>',
270
+ ' <key>Label</key>',
271
+ ` <string>${escapeXml(params.label)}</string>`,
272
+ ' <key>ProgramArguments</key>',
273
+ ' <array>',
274
+ ...args.map((a) => ` <string>${escapeXml(a)}</string>`),
275
+ ' </array>',
276
+ ' <key>RunAtLoad</key>',
277
+ ' <true/>',
278
+ ' <key>KeepAlive</key>',
279
+ ' <true/>',
280
+ ' <key>EnvironmentVariables</key>',
281
+ ' <dict>',
282
+ ...envEntries,
283
+ ' </dict>',
284
+ ' <key>StandardOutPath</key>',
285
+ ` <string>${escapeXml(logPath)}</string>`,
286
+ ' <key>StandardErrorPath</key>',
287
+ ` <string>${escapeXml(logPath)}</string>`,
288
+ '</dict>',
289
+ '</plist>',
290
+ '',
291
+ ].join('\n');
292
+ }
293
+
294
+ async function checkSystemdAvailable(
295
+ runCommand: (cmd: string, args: string[], timeoutMs?: number) => Promise<CommandOutput>
296
+ ): Promise<{ available: boolean; reason?: string }> {
297
+ const res = await runCommand('systemctl', ['--user', 'show-environment'], 5_000);
298
+ if (res.ok) return { available: true };
299
+ const reason = (res.stderr || res.error || 'systemctl --user unavailable').trim();
300
+ return { available: false, reason };
301
+ }
302
+
303
+ export async function getServiceStatus(options: ServiceOptions = {}): Promise<ServiceStatusResult> {
304
+ const ctx = resolveServiceContext(options);
305
+
306
+ if (ctx.manager === 'windows') {
307
+ return windowsStatus(ctx);
308
+ }
309
+
310
+ if (ctx.manager === 'systemd') {
311
+ const unitFile = `${ctx.serviceName}.service`;
312
+ const installed = Boolean(ctx.unitPath && fs.existsSync(ctx.unitPath));
313
+ const avail = await checkSystemdAvailable(ctx.runCommand);
314
+ if (!avail.available) {
315
+ return {
316
+ ok: true,
317
+ manager: 'systemd',
318
+ supported: true,
319
+ available: false,
320
+ installed,
321
+ active: false,
322
+ enabled: false,
323
+ unitPath: ctx.unitPath,
324
+ serviceName: ctx.serviceName,
325
+ detail: `systemd --user is not available (${avail.reason}); use 'bond-app start' in the foreground`,
326
+ };
327
+ }
328
+
329
+ const activeRes = await ctx.runCommand('systemctl', ['--user', 'is-active', unitFile], 5_000);
330
+ const active = activeRes.ok && activeRes.stdout.trim() === 'active';
331
+ const enabledRes = await ctx.runCommand('systemctl', ['--user', 'is-enabled', unitFile], 5_000);
332
+ const enabled = enabledRes.ok && enabledRes.stdout.trim() === 'enabled';
333
+
334
+ let detail = 'not installed';
335
+ if (installed && active) {
336
+ detail = `installed and active (${unitFile})`;
337
+ } else if (installed) {
338
+ detail = `installed but not active (${activeRes.stdout.trim() || 'inactive'})`;
339
+ } else if (active) {
340
+ detail = `active (${unitFile})`;
341
+ }
342
+
343
+ return {
344
+ ok: true,
345
+ manager: 'systemd',
346
+ supported: true,
347
+ available: true,
348
+ installed,
349
+ active,
350
+ enabled,
351
+ unitPath: ctx.unitPath,
352
+ serviceName: ctx.serviceName,
353
+ detail,
354
+ };
355
+ }
356
+
357
+ // launchd (macOS)
358
+ const installed = Boolean(ctx.unitPath && fs.existsSync(ctx.unitPath));
359
+ const domainTarget = `gui/${ctx.uid}/${ctx.serviceName}`;
360
+ const printRes = await ctx.runCommand('launchctl', ['print', domainTarget], 5_000);
361
+ const active = printRes.ok;
362
+
363
+ let detail = 'not installed';
364
+ if (installed && active) {
365
+ detail = `installed and active (${ctx.serviceName})`;
366
+ } else if (installed) {
367
+ detail = `installed but not active (${ctx.serviceName})`;
368
+ } else if (active) {
369
+ detail = `active (${ctx.serviceName})`;
370
+ }
371
+
372
+ return {
373
+ ok: true,
374
+ manager: 'launchd',
375
+ supported: true,
376
+ available: true,
377
+ installed,
378
+ active,
379
+ enabled: installed,
380
+ unitPath: ctx.unitPath,
381
+ serviceName: ctx.serviceName,
382
+ detail,
383
+ };
384
+ }
385
+
386
+ export async function installService(options: ServiceOptions = {}): Promise<ServiceActionResult> {
387
+ const ctx = resolveServiceContext(options);
388
+
389
+ if (ctx.manager === 'windows') {
390
+ return windowsAction('install', ctx);
391
+ }
392
+
393
+ if (ctx.manager === 'systemd') {
394
+ const avail = await checkSystemdAvailable(ctx.runCommand);
395
+ if (!avail.available) {
396
+ return {
397
+ ok: false,
398
+ action: 'install',
399
+ manager: 'systemd',
400
+ supported: true,
401
+ available: false,
402
+ installed: Boolean(ctx.unitPath && fs.existsSync(ctx.unitPath)),
403
+ active: false,
404
+ unitPath: ctx.unitPath,
405
+ serviceName: ctx.serviceName,
406
+ detail: `systemd --user is not available (${avail.reason}); running in foreground via 'bond-app start'`,
407
+ };
408
+ }
409
+
410
+ fs.mkdirSync(ctx.dataDir, { recursive: true, mode: 0o700 });
411
+ fs.mkdirSync(path.dirname(ctx.unitPath!), { recursive: true });
412
+
413
+ const unitContent = renderSystemdUnit({
414
+ nodePath: ctx.nodePath,
415
+ binPath: ctx.binPath,
416
+ port: ctx.port,
417
+ host: ctx.host,
418
+ dataDir: ctx.dataDir,
419
+ runnerImage: ctx.runnerImage,
420
+ });
421
+ fs.writeFileSync(ctx.unitPath!, unitContent, { encoding: 'utf8', mode: 0o644 });
422
+
423
+ const reloadRes = await ctx.runCommand('systemctl', ['--user', 'daemon-reload'], 10_000);
424
+ if (!reloadRes.ok) {
425
+ return {
426
+ ok: false,
427
+ action: 'install',
428
+ manager: 'systemd',
429
+ supported: true,
430
+ available: true,
431
+ installed: true,
432
+ active: false,
433
+ unitPath: ctx.unitPath,
434
+ serviceName: ctx.serviceName,
435
+ detail: `systemctl --user daemon-reload failed: ${(reloadRes.stderr || reloadRes.error || '').trim()}`,
436
+ };
437
+ }
438
+
439
+ const unitFile = `${ctx.serviceName}.service`;
440
+ const enableRes = await ctx.runCommand('systemctl', ['--user', 'enable', '--now', unitFile], 15_000);
441
+ if (!enableRes.ok) {
442
+ return {
443
+ ok: false,
444
+ action: 'install',
445
+ manager: 'systemd',
446
+ supported: true,
447
+ available: true,
448
+ installed: true,
449
+ active: false,
450
+ unitPath: ctx.unitPath,
451
+ serviceName: ctx.serviceName,
452
+ detail: `systemctl --user enable --now ${unitFile} failed: ${(enableRes.stderr || enableRes.error || '').trim()}`,
453
+ };
454
+ }
455
+
456
+ return {
457
+ ok: true,
458
+ action: 'install',
459
+ manager: 'systemd',
460
+ supported: true,
461
+ available: true,
462
+ installed: true,
463
+ active: true,
464
+ unitPath: ctx.unitPath,
465
+ serviceName: ctx.serviceName,
466
+ detail: `installed and started ${ctx.unitPath}`,
467
+ };
468
+ }
469
+
470
+ // launchd (macOS)
471
+ fs.mkdirSync(ctx.dataDir, { recursive: true, mode: 0o700 });
472
+ fs.mkdirSync(path.dirname(ctx.unitPath!), { recursive: true });
473
+
474
+ const plistContent = renderLaunchdPlist({
475
+ label: ctx.serviceName,
476
+ nodePath: ctx.nodePath,
477
+ binPath: ctx.binPath,
478
+ port: ctx.port,
479
+ host: ctx.host,
480
+ dataDir: ctx.dataDir,
481
+ runnerImage: ctx.runnerImage,
482
+ });
483
+ fs.writeFileSync(ctx.unitPath!, plistContent, { encoding: 'utf8', mode: 0o644 });
484
+
485
+ const domain = `gui/${ctx.uid}`;
486
+ await ctx.runCommand('launchctl', ['bootout', domain, ctx.unitPath!], 10_000);
487
+
488
+ const bootRes = await ctx.runCommand('launchctl', ['bootstrap', domain, ctx.unitPath!], 15_000);
489
+ if (!bootRes.ok) {
490
+ return {
491
+ ok: false,
492
+ action: 'install',
493
+ manager: 'launchd',
494
+ supported: true,
495
+ available: true,
496
+ installed: true,
497
+ active: false,
498
+ unitPath: ctx.unitPath,
499
+ serviceName: ctx.serviceName,
500
+ detail: `launchctl bootstrap ${domain} failed: ${(bootRes.stderr || bootRes.error || '').trim()}`,
501
+ };
502
+ }
503
+
504
+ return {
505
+ ok: true,
506
+ action: 'install',
507
+ manager: 'launchd',
508
+ supported: true,
509
+ available: true,
510
+ installed: true,
511
+ active: true,
512
+ unitPath: ctx.unitPath,
513
+ serviceName: ctx.serviceName,
514
+ detail: `installed and started ${ctx.unitPath}`,
515
+ };
516
+ }
517
+
518
+ export async function startService(options: ServiceOptions = {}): Promise<ServiceActionResult> {
519
+ const ctx = resolveServiceContext(options);
520
+
521
+ if (ctx.manager === 'windows') {
522
+ return windowsAction('start', ctx);
523
+ }
524
+
525
+ if (ctx.manager === 'systemd') {
526
+ const avail = await checkSystemdAvailable(ctx.runCommand);
527
+ if (!avail.available) {
528
+ return {
529
+ ok: false,
530
+ action: 'start',
531
+ manager: 'systemd',
532
+ supported: true,
533
+ available: false,
534
+ installed: Boolean(ctx.unitPath && fs.existsSync(ctx.unitPath)),
535
+ active: false,
536
+ unitPath: ctx.unitPath,
537
+ serviceName: ctx.serviceName,
538
+ detail: `systemd --user is not available (${avail.reason})`,
539
+ };
540
+ }
541
+ const unitFile = `${ctx.serviceName}.service`;
542
+ const res = await ctx.runCommand('systemctl', ['--user', 'start', unitFile], 15_000);
543
+ return {
544
+ ok: res.ok,
545
+ action: 'start',
546
+ manager: 'systemd',
547
+ supported: true,
548
+ available: true,
549
+ installed: Boolean(ctx.unitPath && fs.existsSync(ctx.unitPath)),
550
+ active: res.ok,
551
+ unitPath: ctx.unitPath,
552
+ serviceName: ctx.serviceName,
553
+ detail: res.ok ? `started ${unitFile}` : `systemctl --user start ${unitFile} failed: ${(res.stderr || res.error || '').trim()}`,
554
+ };
555
+ }
556
+
557
+ // launchd
558
+ const domain = `gui/${ctx.uid}`;
559
+ const target = `${domain}/${ctx.serviceName}`;
560
+ const kickRes = await ctx.runCommand('launchctl', ['kickstart', '-k', target], 15_000);
561
+ if (kickRes.ok) {
562
+ return {
563
+ ok: true,
564
+ action: 'start',
565
+ manager: 'launchd',
566
+ supported: true,
567
+ available: true,
568
+ installed: Boolean(ctx.unitPath && fs.existsSync(ctx.unitPath)),
569
+ active: true,
570
+ unitPath: ctx.unitPath,
571
+ serviceName: ctx.serviceName,
572
+ detail: `started ${ctx.serviceName}`,
573
+ };
574
+ }
575
+ if (ctx.unitPath && fs.existsSync(ctx.unitPath)) {
576
+ const bootRes = await ctx.runCommand('launchctl', ['bootstrap', domain, ctx.unitPath], 15_000);
577
+ return {
578
+ ok: bootRes.ok,
579
+ action: 'start',
580
+ manager: 'launchd',
581
+ supported: true,
582
+ available: true,
583
+ installed: true,
584
+ active: bootRes.ok,
585
+ unitPath: ctx.unitPath,
586
+ serviceName: ctx.serviceName,
587
+ detail: bootRes.ok
588
+ ? `started ${ctx.serviceName}`
589
+ : `launchctl bootstrap ${domain} failed: ${(bootRes.stderr || bootRes.error || '').trim()}`,
590
+ };
591
+ }
592
+ return {
593
+ ok: false,
594
+ action: 'start',
595
+ manager: 'launchd',
596
+ supported: true,
597
+ available: true,
598
+ installed: false,
599
+ active: false,
600
+ unitPath: ctx.unitPath,
601
+ serviceName: ctx.serviceName,
602
+ detail: `service ${ctx.serviceName} is not installed (run 'bond-app service install')`,
603
+ };
604
+ }
605
+
606
+ export async function stopService(options: ServiceOptions = {}): Promise<ServiceActionResult> {
607
+ const ctx = resolveServiceContext(options);
608
+
609
+ if (ctx.manager === 'windows') {
610
+ return windowsAction('stop', ctx);
611
+ }
612
+
613
+ if (ctx.manager === 'systemd') {
614
+ const avail = await checkSystemdAvailable(ctx.runCommand);
615
+ if (!avail.available) {
616
+ return {
617
+ ok: false,
618
+ action: 'stop',
619
+ manager: 'systemd',
620
+ supported: true,
621
+ available: false,
622
+ installed: Boolean(ctx.unitPath && fs.existsSync(ctx.unitPath)),
623
+ active: false,
624
+ unitPath: ctx.unitPath,
625
+ serviceName: ctx.serviceName,
626
+ detail: `systemd --user is not available (${avail.reason})`,
627
+ };
628
+ }
629
+ const unitFile = `${ctx.serviceName}.service`;
630
+ const res = await ctx.runCommand('systemctl', ['--user', 'stop', unitFile], 15_000);
631
+ return {
632
+ ok: res.ok,
633
+ action: 'stop',
634
+ manager: 'systemd',
635
+ supported: true,
636
+ available: true,
637
+ installed: Boolean(ctx.unitPath && fs.existsSync(ctx.unitPath)),
638
+ active: !res.ok,
639
+ unitPath: ctx.unitPath,
640
+ serviceName: ctx.serviceName,
641
+ detail: res.ok ? `stopped ${unitFile}` : `systemctl --user stop ${unitFile} failed: ${(res.stderr || res.error || '').trim()}`,
642
+ };
643
+ }
644
+
645
+ // launchd
646
+ const domain = `gui/${ctx.uid}`;
647
+ const res = await ctx.runCommand('launchctl', ['bootout', domain, ctx.unitPath!], 15_000);
648
+ return {
649
+ ok: res.ok,
650
+ action: 'stop',
651
+ manager: 'launchd',
652
+ supported: true,
653
+ available: true,
654
+ installed: Boolean(ctx.unitPath && fs.existsSync(ctx.unitPath)),
655
+ active: !res.ok,
656
+ unitPath: ctx.unitPath,
657
+ serviceName: ctx.serviceName,
658
+ detail: res.ok ? `stopped ${ctx.serviceName}` : `launchctl bootout ${domain} failed: ${(res.stderr || res.error || '').trim()}`,
659
+ };
660
+ }
661
+
662
+ export async function restartService(options: ServiceOptions = {}): Promise<ServiceActionResult> {
663
+ const ctx = resolveServiceContext(options);
664
+
665
+ if (ctx.manager === 'windows') {
666
+ return windowsAction('restart', ctx);
667
+ }
668
+
669
+ if (ctx.manager === 'systemd') {
670
+ const avail = await checkSystemdAvailable(ctx.runCommand);
671
+ if (!avail.available) {
672
+ return {
673
+ ok: false,
674
+ action: 'restart',
675
+ manager: 'systemd',
676
+ supported: true,
677
+ available: false,
678
+ installed: Boolean(ctx.unitPath && fs.existsSync(ctx.unitPath)),
679
+ active: false,
680
+ unitPath: ctx.unitPath,
681
+ serviceName: ctx.serviceName,
682
+ detail: `systemd --user is not available (${avail.reason})`,
683
+ };
684
+ }
685
+ const unitFile = `${ctx.serviceName}.service`;
686
+ const res = await ctx.runCommand('systemctl', ['--user', 'restart', unitFile], 15_000);
687
+ return {
688
+ ok: res.ok,
689
+ action: 'restart',
690
+ manager: 'systemd',
691
+ supported: true,
692
+ available: true,
693
+ installed: Boolean(ctx.unitPath && fs.existsSync(ctx.unitPath)),
694
+ active: res.ok,
695
+ unitPath: ctx.unitPath,
696
+ serviceName: ctx.serviceName,
697
+ detail: res.ok ? `restarted ${unitFile}` : `systemctl --user restart ${unitFile} failed: ${(res.stderr || res.error || '').trim()}`,
698
+ };
699
+ }
700
+
701
+ // launchd
702
+ const domain = `gui/${ctx.uid}`;
703
+ const target = `${domain}/${ctx.serviceName}`;
704
+ const kickRes = await ctx.runCommand('launchctl', ['kickstart', '-k', target], 15_000);
705
+ if (kickRes.ok) {
706
+ return {
707
+ ok: true,
708
+ action: 'restart',
709
+ manager: 'launchd',
710
+ supported: true,
711
+ available: true,
712
+ installed: Boolean(ctx.unitPath && fs.existsSync(ctx.unitPath)),
713
+ active: true,
714
+ unitPath: ctx.unitPath,
715
+ serviceName: ctx.serviceName,
716
+ detail: `restarted ${ctx.serviceName}`,
717
+ };
718
+ }
719
+ if (ctx.unitPath && fs.existsSync(ctx.unitPath)) {
720
+ const bootRes = await ctx.runCommand('launchctl', ['bootstrap', domain, ctx.unitPath], 15_000);
721
+ return {
722
+ ok: bootRes.ok,
723
+ action: 'restart',
724
+ manager: 'launchd',
725
+ supported: true,
726
+ available: true,
727
+ installed: true,
728
+ active: bootRes.ok,
729
+ unitPath: ctx.unitPath,
730
+ serviceName: ctx.serviceName,
731
+ detail: bootRes.ok
732
+ ? `restarted ${ctx.serviceName}`
733
+ : `launchctl bootstrap ${domain} failed: ${(bootRes.stderr || bootRes.error || '').trim()}`,
734
+ };
735
+ }
736
+ return {
737
+ ok: false,
738
+ action: 'restart',
739
+ manager: 'launchd',
740
+ supported: true,
741
+ available: true,
742
+ installed: false,
743
+ active: false,
744
+ unitPath: ctx.unitPath,
745
+ serviceName: ctx.serviceName,
746
+ detail: `service ${ctx.serviceName} is not installed (run 'bond-app service install')`,
747
+ };
748
+ }
749
+
750
+ export async function uninstallService(options: ServiceOptions = {}): Promise<ServiceActionResult> {
751
+ const ctx = resolveServiceContext(options);
752
+
753
+ if (ctx.manager === 'windows') {
754
+ return windowsAction('uninstall', ctx);
755
+ }
756
+
757
+ if (ctx.manager === 'systemd') {
758
+ const avail = await checkSystemdAvailable(ctx.runCommand);
759
+ const unitFile = `${ctx.serviceName}.service`;
760
+ if (avail.available) {
761
+ await ctx.runCommand('systemctl', ['--user', 'disable', '--now', unitFile], 15_000);
762
+ }
763
+ const existed = Boolean(ctx.unitPath && fs.existsSync(ctx.unitPath));
764
+ if (ctx.unitPath && existed) {
765
+ fs.rmSync(ctx.unitPath, { force: true });
766
+ }
767
+ if (avail.available) {
768
+ await ctx.runCommand('systemctl', ['--user', 'daemon-reload'], 10_000);
769
+ }
770
+ return {
771
+ ok: true,
772
+ action: 'uninstall',
773
+ manager: 'systemd',
774
+ supported: true,
775
+ available: avail.available,
776
+ installed: false,
777
+ active: false,
778
+ unitPath: ctx.unitPath,
779
+ serviceName: ctx.serviceName,
780
+ detail: existed ? `uninstalled ${ctx.unitPath}` : `${unitFile} was not installed`,
781
+ };
782
+ }
783
+
784
+ // launchd
785
+ const domain = `gui/${ctx.uid}`;
786
+ const existed = Boolean(ctx.unitPath && fs.existsSync(ctx.unitPath));
787
+ if (ctx.unitPath) {
788
+ await ctx.runCommand('launchctl', ['bootout', domain, ctx.unitPath], 15_000);
789
+ if (existed) {
790
+ fs.rmSync(ctx.unitPath, { force: true });
791
+ }
792
+ }
793
+ return {
794
+ ok: true,
795
+ action: 'uninstall',
796
+ manager: 'launchd',
797
+ supported: true,
798
+ available: true,
799
+ installed: false,
800
+ active: false,
801
+ unitPath: ctx.unitPath,
802
+ serviceName: ctx.serviceName,
803
+ detail: existed ? `uninstalled ${ctx.unitPath}` : `${ctx.serviceName} was not installed`,
804
+ };
805
+ }
806
+
807
+ // --- Windows (instalador P5): a scheduled task at logon (schtasks), via service-windows.ts. ---
808
+
809
+ type ServiceCtx = ReturnType<typeof resolveServiceContext>;
810
+
811
+ async function windowsStatus(ctx: ServiceCtx): Promise<ServiceStatusResult> {
812
+ const q = await queryWindowsTask({ taskName: ctx.serviceName, runCommand: ctx.runCommand });
813
+ return {
814
+ ok: true,
815
+ manager: 'windows',
816
+ supported: true,
817
+ available: true,
818
+ installed: q.installed,
819
+ active: q.running,
820
+ enabled: q.installed,
821
+ unitPath: null,
822
+ serviceName: ctx.serviceName,
823
+ detail: q.installed ? `scheduled task '${ctx.serviceName}' (${q.state ?? 'unknown'})` : `scheduled task '${ctx.serviceName}' not installed`,
824
+ };
825
+ }
826
+
827
+ async function windowsAction(action: ServiceAction, ctx: ServiceCtx): Promise<ServiceActionResult> {
828
+ const task = { taskName: ctx.serviceName, runCommand: ctx.runCommand };
829
+ let ok = true;
830
+ const details: string[] = [];
831
+ const step = (r: { ok: boolean; detail: string }) => { ok = ok && r.ok; details.push(r.detail); };
832
+ if (action === 'install') {
833
+ step(await installWindowsTask({ ...task, nodePath: ctx.nodePath, binPath: ctx.binPath, dataDir: ctx.dataDir, port: ctx.port, host: ctx.host }));
834
+ if (ok) step(await startWindowsTask(task));
835
+ } else if (action === 'start') {
836
+ step(await startWindowsTask(task));
837
+ } else if (action === 'stop') {
838
+ step(await stopWindowsTask(task));
839
+ } else if (action === 'restart') {
840
+ const stopped = await stopWindowsTask(task);
841
+ details.push(stopped.detail);
842
+ step(await startWindowsTask(task));
843
+ } else if (action === 'uninstall') {
844
+ const stopped = await stopWindowsTask(task);
845
+ details.push(stopped.detail);
846
+ step(await uninstallWindowsTask(task));
847
+ }
848
+ const q = await queryWindowsTask(task);
849
+ return {
850
+ ok,
851
+ action,
852
+ manager: 'windows',
853
+ supported: true,
854
+ available: true,
855
+ installed: q.installed,
856
+ active: q.running,
857
+ unitPath: null,
858
+ serviceName: ctx.serviceName,
859
+ detail: details.join('; '),
860
+ };
861
+ }