@mark1russell7/service 0.8.19 → 0.8.20

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 (331) hide show
  1. package/build/backoff.d.ts +44 -2
  2. package/build/{builder-zO48Vgoj.d.ts → builder.d.ts} +14 -101
  3. package/build/builder.js +499 -0
  4. package/build/builder.js.map +1 -0
  5. package/build/{call-context-DDhcVvn5.d.ts → call-context.d.ts} +3 -4
  6. package/build/channel.d.ts +1 -1
  7. package/build/{core-BSzt4RI2.d.ts → client/core.d.ts} +32 -61
  8. package/build/{machine-BhVeHr_m.js → client/core.js} +4 -153
  9. package/build/client/core.js.map +1 -0
  10. package/build/{dial-ChwIcvd4.d.ts → client/dial.d.ts} +3 -4
  11. package/build/client/dial.js +52 -0
  12. package/build/client/dial.js.map +1 -0
  13. package/build/client/machine.js +29 -0
  14. package/build/client/machine.js.map +1 -0
  15. package/build/client/meets.d.ts +35 -0
  16. package/build/client/meets.js +78 -0
  17. package/build/client/meets.js.map +1 -0
  18. package/build/clock.d.ts +1 -1
  19. package/build/conformance.d.ts +122 -0
  20. package/build/conformance.js +470 -0
  21. package/build/conformance.js.map +1 -0
  22. package/build/contract.d.ts +28 -0
  23. package/build/contract.js +184 -0
  24. package/build/contract.js.map +1 -0
  25. package/build/description.d.ts +161 -0
  26. package/build/description.js +11 -0
  27. package/build/description.js.map +1 -0
  28. package/build/drains.js +35 -0
  29. package/build/drains.js.map +1 -0
  30. package/build/events.d.ts +25 -0
  31. package/build/fakes.d.ts +43 -0
  32. package/build/fakes.js +93 -0
  33. package/build/fakes.js.map +1 -0
  34. package/build/grpc/client.d.ts +153 -0
  35. package/build/grpc/client.js +474 -0
  36. package/build/grpc/client.js.map +1 -0
  37. package/build/grpc/connection.d.ts +97 -0
  38. package/build/grpc/connection.js +59 -0
  39. package/build/grpc/connection.js.map +1 -0
  40. package/build/grpc/machine.d.ts +12 -0
  41. package/build/grpc/machine.js +149 -0
  42. package/build/grpc/machine.js.map +1 -0
  43. package/build/grpc/meets.d.ts +14 -0
  44. package/build/grpc/meets.js +105 -0
  45. package/build/grpc/meets.js.map +1 -0
  46. package/build/grpc/starting.d.ts +33 -0
  47. package/build/grpc/starting.js +89 -0
  48. package/build/grpc/starting.js.map +1 -0
  49. package/build/grpc.d.ts +9 -303
  50. package/build/grpc.js +7 -854
  51. package/build/health.d.ts +93 -0
  52. package/build/health.js +223 -0
  53. package/build/health.js.map +1 -0
  54. package/build/heartbeat.d.ts +1 -1
  55. package/build/host/discovery.d.ts +61 -0
  56. package/build/host/discovery.js +113 -0
  57. package/build/host/discovery.js.map +1 -0
  58. package/build/host/env.d.ts +14 -0
  59. package/build/host/env.js +57 -0
  60. package/build/host/env.js.map +1 -0
  61. package/build/host/fakes.d.ts +82 -0
  62. package/build/host/fakes.js +239 -0
  63. package/build/host/fakes.js.map +1 -0
  64. package/build/host/group.d.ts +142 -0
  65. package/build/host/group.js +517 -0
  66. package/build/host/group.js.map +1 -0
  67. package/build/host/install.d.ts +96 -0
  68. package/build/host/install.js +330 -0
  69. package/build/host/install.js.map +1 -0
  70. package/build/host/lock.d.ts +78 -0
  71. package/build/host/lock.js +190 -0
  72. package/build/host/lock.js.map +1 -0
  73. package/build/host/logs.d.ts +26 -0
  74. package/build/host/logs.js +48 -0
  75. package/build/host/logs.js.map +1 -0
  76. package/build/host/node.d.ts +14 -0
  77. package/build/host/node.js +309 -0
  78. package/build/host/node.js.map +1 -0
  79. package/build/{ports-B1ayTL-j.d.ts → host/ports.d.ts} +15 -16
  80. package/build/host/ports.js +17 -0
  81. package/build/host/ports.js.map +1 -0
  82. package/build/host/probes.d.ts +51 -0
  83. package/build/host/probes.js +139 -0
  84. package/build/host/probes.js.map +1 -0
  85. package/build/host/processes.d.ts +32 -0
  86. package/build/host/processes.js +63 -0
  87. package/build/host/processes.js.map +1 -0
  88. package/build/host/render.d.ts +84 -0
  89. package/build/host/render.js +235 -0
  90. package/build/host/render.js.map +1 -0
  91. package/build/host/watch.d.ts +90 -0
  92. package/build/host/watch.js +165 -0
  93. package/build/host/watch.js.map +1 -0
  94. package/build/host.d.ts +13 -671
  95. package/build/host.js +12 -2126
  96. package/build/http/answers.js +29 -0
  97. package/build/http/answers.js.map +1 -0
  98. package/build/http/fake-server.js +61 -0
  99. package/build/http/fake-server.js.map +1 -0
  100. package/build/http/outcome.d.ts +115 -0
  101. package/build/http/outcome.js +325 -0
  102. package/build/http/outcome.js.map +1 -0
  103. package/build/http/probes.d.ts +83 -0
  104. package/build/http/probes.js +232 -0
  105. package/build/http/probes.js.map +1 -0
  106. package/build/http/transport.d.ts +165 -0
  107. package/build/http/transport.js +517 -0
  108. package/build/http/transport.js.map +1 -0
  109. package/build/http-client/client.d.ts +121 -0
  110. package/build/http-client/client.js +330 -0
  111. package/build/http-client/client.js.map +1 -0
  112. package/build/http-client/connection.d.ts +78 -0
  113. package/build/http-client/connection.js +54 -0
  114. package/build/http-client/connection.js.map +1 -0
  115. package/build/http-client/machine.d.ts +14 -0
  116. package/build/http-client/machine.js +109 -0
  117. package/build/http-client/machine.js.map +1 -0
  118. package/build/http-client/meets.d.ts +11 -0
  119. package/build/http-client/meets.js +74 -0
  120. package/build/http-client/meets.js.map +1 -0
  121. package/build/http-client/session.d.ts +87 -0
  122. package/build/http-client/session.js +99 -0
  123. package/build/http-client/session.js.map +1 -0
  124. package/build/http-client/starting.d.ts +25 -0
  125. package/build/http-client/starting.js +65 -0
  126. package/build/http-client/starting.js.map +1 -0
  127. package/build/http-client.d.ts +9 -330
  128. package/build/http-client.js +8 -707
  129. package/build/http.d.ts +5 -353
  130. package/build/http.js +3 -1086
  131. package/build/identity.d.ts +16 -0
  132. package/build/identity.js +44 -0
  133. package/build/identity.js.map +1 -0
  134. package/build/index.d.ts +35 -412
  135. package/build/index.js +24 -3277
  136. package/build/knobs.d.ts +1 -0
  137. package/build/{knobs-BJcz6m01.js → knobs.js} +2 -34
  138. package/build/knobs.js.map +1 -0
  139. package/build/latch.d.ts +29 -0
  140. package/build/latch.js +122 -0
  141. package/build/latch.js.map +1 -0
  142. package/build/{rules-HyFCBStQ.d.ts → law.d.ts} +19 -37
  143. package/build/law.js +149 -0
  144. package/build/law.js.map +1 -0
  145. package/build/lifecycle.d.ts +144 -0
  146. package/build/lifecycle.js +411 -0
  147. package/build/lifecycle.js.map +1 -0
  148. package/build/limiter/machine.d.ts +40 -0
  149. package/build/limiter/machine.js +279 -0
  150. package/build/limiter/machine.js.map +1 -0
  151. package/build/{policy-CBcK2XGg.d.ts → limiter/policy.d.ts} +28 -29
  152. package/build/{policy-UYALkqVq.js → limiter/policy.js} +10 -9
  153. package/build/limiter/policy.js.map +1 -0
  154. package/build/{limiter-BNKnwzeY.d.ts → limiter/quota.d.ts} +32 -74
  155. package/build/{limiter-DrM0PQV9.js → limiter/quota.js} +3 -418
  156. package/build/limiter/quota.js.map +1 -0
  157. package/build/{store-DFwFKrsB.d.ts → limiter/store.d.ts} +10 -11
  158. package/build/limiter/store.js +145 -0
  159. package/build/limiter/store.js.map +1 -0
  160. package/build/limiter.d.ts +4 -3
  161. package/build/limiter.js +4 -2
  162. package/build/lint.d.ts +152 -0
  163. package/build/lint.js +576 -0
  164. package/build/lint.js.map +1 -0
  165. package/build/logger.d.ts +71 -0
  166. package/build/logger.js +183 -0
  167. package/build/logger.js.map +1 -0
  168. package/build/machines.d.ts +41 -0
  169. package/build/machines.js +451 -0
  170. package/build/machines.js.map +1 -0
  171. package/build/metrics.d.ts +53 -0
  172. package/build/metrics.js +111 -0
  173. package/build/metrics.js.map +1 -0
  174. package/build/mongodb/client.d.ts +131 -0
  175. package/build/mongodb/client.js +388 -0
  176. package/build/mongodb/client.js.map +1 -0
  177. package/build/mongodb/connection.d.ts +112 -0
  178. package/build/mongodb/connection.js +12 -0
  179. package/build/mongodb/connection.js.map +1 -0
  180. package/build/mongodb/machine.d.ts +14 -0
  181. package/build/mongodb/machine.js +122 -0
  182. package/build/mongodb/machine.js.map +1 -0
  183. package/build/mongodb/meets.d.ts +15 -0
  184. package/build/mongodb/meets.js +103 -0
  185. package/build/mongodb/meets.js.map +1 -0
  186. package/build/mongodb/starting.d.ts +29 -0
  187. package/build/mongodb/starting.js +77 -0
  188. package/build/mongodb/starting.js.map +1 -0
  189. package/build/mongodb.d.ts +8 -296
  190. package/build/mongodb.js +7 -682
  191. package/build/operation.d.ts +27 -0
  192. package/build/{operation-DF73RZOI.js → operation.js} +2 -2
  193. package/build/operation.js.map +1 -0
  194. package/build/otel.d.ts +2 -2
  195. package/build/pg/client.d.ts +96 -0
  196. package/build/pg/client.js +277 -0
  197. package/build/pg/client.js.map +1 -0
  198. package/build/pg/connection.d.ts +75 -0
  199. package/build/pg/connection.js +11 -0
  200. package/build/pg/connection.js.map +1 -0
  201. package/build/pg/machine.d.ts +13 -0
  202. package/build/pg/machine.js +111 -0
  203. package/build/pg/machine.js.map +1 -0
  204. package/build/pg/meets.d.ts +14 -0
  205. package/build/pg/meets.js +83 -0
  206. package/build/pg/meets.js.map +1 -0
  207. package/build/pg/starting.d.ts +26 -0
  208. package/build/pg/starting.js +62 -0
  209. package/build/pg/starting.js.map +1 -0
  210. package/build/pg.d.ts +8 -219
  211. package/build/pg.js +7 -525
  212. package/build/poller.d.ts +9 -0
  213. package/build/poller.js +152 -0
  214. package/build/poller.js.map +1 -0
  215. package/build/process.d.ts +114 -0
  216. package/build/process.js +170 -0
  217. package/build/process.js.map +1 -0
  218. package/build/profiles.d.ts +68 -0
  219. package/build/profiles.js +120 -0
  220. package/build/profiles.js.map +1 -0
  221. package/build/{queue-DXdw1vLO.d.ts → queue.d.ts} +16 -29
  222. package/build/queue.js +279 -0
  223. package/build/queue.js.map +1 -0
  224. package/build/rabbitmq/client.d.ts +144 -0
  225. package/build/rabbitmq/client.js +426 -0
  226. package/build/rabbitmq/client.js.map +1 -0
  227. package/build/rabbitmq/connection.d.ts +91 -0
  228. package/build/rabbitmq/connection.js +15 -0
  229. package/build/rabbitmq/connection.js.map +1 -0
  230. package/build/rabbitmq/machine.d.ts +13 -0
  231. package/build/rabbitmq/machine.js +159 -0
  232. package/build/rabbitmq/machine.js.map +1 -0
  233. package/build/rabbitmq/meets.d.ts +12 -0
  234. package/build/rabbitmq/meets.js +96 -0
  235. package/build/rabbitmq/meets.js.map +1 -0
  236. package/build/rabbitmq/starting.d.ts +27 -0
  237. package/build/rabbitmq/starting.js +67 -0
  238. package/build/rabbitmq/starting.js.map +1 -0
  239. package/build/rabbitmq.d.ts +8 -283
  240. package/build/rabbitmq.js +7 -742
  241. package/build/redis/client.d.ts +86 -0
  242. package/build/redis/client.js +285 -0
  243. package/build/redis/client.js.map +1 -0
  244. package/build/redis/connection.d.ts +57 -0
  245. package/build/redis/connection.js +11 -0
  246. package/build/redis/connection.js.map +1 -0
  247. package/build/redis/limiter.d.ts +43 -0
  248. package/build/redis/limiter.js +164 -0
  249. package/build/redis/limiter.js.map +1 -0
  250. package/build/redis/machine.d.ts +12 -0
  251. package/build/redis/machine.js +144 -0
  252. package/build/redis/machine.js.map +1 -0
  253. package/build/redis/meets.d.ts +11 -0
  254. package/build/redis/meets.js +75 -0
  255. package/build/redis/meets.js.map +1 -0
  256. package/build/redis/operations.d.ts +5 -0
  257. package/build/redis/operations.js +114 -0
  258. package/build/redis/operations.js.map +1 -0
  259. package/build/redis.d.ts +10 -207
  260. package/build/redis.js +9 -771
  261. package/build/requests.d.ts +66 -0
  262. package/build/requests.js +279 -0
  263. package/build/requests.js.map +1 -0
  264. package/build/retrier.d.ts +62 -0
  265. package/build/{retrier-Dnjhvxol.js → retrier.js} +2 -2
  266. package/build/retrier.js.map +1 -0
  267. package/build/routes.d.ts +35 -0
  268. package/build/routes.js +77 -0
  269. package/build/routes.js.map +1 -0
  270. package/build/rules.d.ts +19 -2
  271. package/build/stops.d.ts +51 -0
  272. package/build/stops.js +86 -0
  273. package/build/stops.js.map +1 -0
  274. package/build/testing.d.ts +8 -270
  275. package/build/testing.js +4 -1027
  276. package/build/testing.js.map +1 -1
  277. package/build/timing.d.ts +63 -0
  278. package/build/{timing-DZl36uXs.js → timing.js} +2 -2
  279. package/build/timing.js.map +1 -0
  280. package/build/units.d.ts +17 -0
  281. package/build/units.js +236 -0
  282. package/build/units.js.map +1 -0
  283. package/build/watchdog.d.ts +34 -0
  284. package/build/watchdog.js +53 -0
  285. package/build/watchdog.js.map +1 -0
  286. package/build/websocket/client.d.ts +136 -0
  287. package/build/websocket/client.js +422 -0
  288. package/build/websocket/client.js.map +1 -0
  289. package/build/websocket/connection.d.ts +83 -0
  290. package/build/websocket/connection.js +57 -0
  291. package/build/websocket/connection.js.map +1 -0
  292. package/build/websocket/machine.d.ts +12 -0
  293. package/build/websocket/machine.js +155 -0
  294. package/build/websocket/machine.js.map +1 -0
  295. package/build/websocket/meets.d.ts +14 -0
  296. package/build/websocket/meets.js +92 -0
  297. package/build/websocket/meets.js.map +1 -0
  298. package/build/websocket/starting.d.ts +25 -0
  299. package/build/websocket/starting.js +69 -0
  300. package/build/websocket/starting.js.map +1 -0
  301. package/build/websocket.d.ts +9 -264
  302. package/build/websocket.js +8 -774
  303. package/build/worker.d.ts +92 -0
  304. package/build/worker.js +153 -0
  305. package/build/worker.js.map +1 -0
  306. package/package.json +4 -3
  307. package/build/backoff-QTRGfkEK.d.ts +0 -45
  308. package/build/clock-DpVgpY4h.d.ts +0 -2
  309. package/build/grpc.js.map +0 -1
  310. package/build/host.js.map +0 -1
  311. package/build/http-client.js.map +0 -1
  312. package/build/http.js.map +0 -1
  313. package/build/index.js.map +0 -1
  314. package/build/knobs-BJcz6m01.js.map +0 -1
  315. package/build/lifecycle-D0J-zwZF.d.ts +0 -374
  316. package/build/limiter-DrM0PQV9.js.map +0 -1
  317. package/build/logger-B6drv9w0.d.ts +0 -488
  318. package/build/machine-BhVeHr_m.js.map +0 -1
  319. package/build/mongodb.js.map +0 -1
  320. package/build/operation-DF73RZOI.js.map +0 -1
  321. package/build/pg.js.map +0 -1
  322. package/build/policy-UYALkqVq.js.map +0 -1
  323. package/build/process-7R9M29wN.js +0 -437
  324. package/build/process-7R9M29wN.js.map +0 -1
  325. package/build/rabbitmq.js.map +0 -1
  326. package/build/redis.js.map +0 -1
  327. package/build/requests-DD2ALv0_.js +0 -583
  328. package/build/requests-DD2ALv0_.js.map +0 -1
  329. package/build/retrier-Dnjhvxol.js.map +0 -1
  330. package/build/timing-DZl36uXs.js.map +0 -1
  331. package/build/websocket.js.map +0 -1
@@ -0,0 +1,96 @@
1
+ import { DiscoveryRead } from "./discovery.js";
2
+ import { HostPorts } from "./ports.js";
3
+ import { ServiceSpec } from "./render.js";
4
+ /** A command record is one command that a service operation started, and its result. */
5
+ export interface CommandRecord {
6
+ readonly file: string;
7
+ readonly args: readonly string[];
8
+ readonly code: number;
9
+ readonly out: string;
10
+ }
11
+ /**
12
+ * A service outcome tells what a service operation did. An operation does not throw.
13
+ * - `done`: each command gave 0. `commands` and `files` tell what the operation did.
14
+ * - `failed`: a command gave a code that is not 0, or the file system failed. The problem tells which.
15
+ * - `refused`: the spec has problems, and the operation did nothing.
16
+ * - `unsupported`: the platform is not Windows or Linux, and the operation did nothing.
17
+ */
18
+ export type ServiceOutcome = {
19
+ readonly kind: "done";
20
+ readonly commands: readonly CommandRecord[];
21
+ readonly files: readonly string[];
22
+ } | {
23
+ readonly kind: "failed";
24
+ readonly commands: readonly CommandRecord[];
25
+ readonly problem: string;
26
+ } | {
27
+ readonly kind: "refused";
28
+ readonly problems: readonly string[];
29
+ } | {
30
+ readonly kind: "unsupported";
31
+ readonly platform: string;
32
+ };
33
+ /** A service status tells if the system has the service, its state, and the instance of the discovery file. */
34
+ export interface ServiceStatus {
35
+ /** This flag tells if the system has the task or the unit. */
36
+ readonly installed: boolean;
37
+ /**
38
+ * This text is the state that the system gives, for example `Running` or `Ready` from `schtasks`, or
39
+ * `active` or `inactive` from `systemctl`. It is `unknown` when the system gives no state.
40
+ */
41
+ readonly state: string;
42
+ /** This is the read of the discovery file, or null without a discovery path. */
43
+ readonly instance: DiscoveryRead | null;
44
+ /** These are the commands that the status started. */
45
+ readonly commands: readonly CommandRecord[];
46
+ }
47
+ /** These options go with an install. */
48
+ export interface InstallOptions {
49
+ /** True starts the service after the install. The default is true. */
50
+ readonly start?: boolean | undefined;
51
+ }
52
+ /** These options go with an operation that stops the instance: the discovery file that names it. */
53
+ export interface InstanceOptions {
54
+ /** This path is the discovery file of the instance. With it, the operation stops the process tree of a live instance. */
55
+ readonly discovery?: string | undefined;
56
+ }
57
+ /** These are the files of a service on this platform. */
58
+ export interface ServicePaths {
59
+ /** This path is the task file on Windows, or the unit on Linux. */
60
+ readonly unit: string;
61
+ /** This path is the timer of a daily job on Linux, or null. */
62
+ readonly timer: string | null;
63
+ }
64
+ /** This function gives the files of a service on the platform of the ports. */
65
+ export declare const servicePaths: (spec: ServiceSpec, ports: HostPorts) => ServicePaths;
66
+ /**
67
+ * This function installs a service of the user, and by default starts it. It does not throw.
68
+ * - On Windows, it writes the task file in UTF-16 to `stateDir`, and starts `schtasks /Create /XML <file> /F`, then `schtasks /Run`.
69
+ * - On Linux, it writes the unit (and the timer of a daily job), then starts `systemctl --user daemon-reload` and `enable`.
70
+ * For a spec in the background, it first starts `loginctl enable-linger` for the user.
71
+ * A second install replaces the first. Give it the ports of a test, thus no test installs a real task.
72
+ * On Windows, Task Scheduler refuses a spec in the background from a shell that is not elevated: the problem then tells so.
73
+ */
74
+ export declare const installService: (spec: ServiceSpec, ports: HostPorts, options?: InstallOptions) => Promise<ServiceOutcome>;
75
+ /**
76
+ * This function removes a service. It does not throw. On Windows, it ends the task and deletes it. On
77
+ * Linux, it disables and stops the unit, removes its files and reloads systemd. With a discovery file,
78
+ * it then stops the process tree of an instance that stays.
79
+ */
80
+ export declare const uninstallService: (spec: ServiceSpec, ports: HostPorts, options?: InstanceOptions) => Promise<ServiceOutcome>;
81
+ /** This function enables a service and starts it. It does not throw. On Windows, it enables the task and runs it. */
82
+ export declare const startService: (spec: ServiceSpec, ports: HostPorts) => Promise<ServiceOutcome>;
83
+ /**
84
+ * This function stops a service, and keeps it stopped until `startService`. It does not throw.
85
+ * - On Windows, it disables the task, thus its time trigger does not start it again, and ends the task.
86
+ * With a discovery file, it then stops the process tree of the instance. Windows has no signal that a child can catch.
87
+ * - On Linux, it disables the unit of a service at logon or at boot, or the timer of a daily job, and stops it.
88
+ * Thus the next login, the next boot or the next calendar time does not start it again. The stop sends SIGTERM,
89
+ * thus `run()` stops in its stages. A daily job that operates stops too.
90
+ */
91
+ export declare const stopService: (spec: ServiceSpec, ports: HostPorts, options?: InstanceOptions) => Promise<ServiceOutcome>;
92
+ /**
93
+ * This function gives the status of a service. It does not throw. A service that the system does not
94
+ * have gives `installed: false`. A malformed or stale discovery file gives its read, and not a throw.
95
+ */
96
+ export declare const serviceStatus: (spec: ServiceSpec, ports: HostPorts, options?: InstanceOptions) => Promise<ServiceStatus>;
@@ -0,0 +1,330 @@
1
+ import { readDiscovery } from "./discovery.js";
2
+ import { joinPath } from "./ports.js";
3
+ import { stopTree } from "./processes.js";
4
+ import { inBackground, renderSystemdTimer, renderSystemdUnit, renderTaskXml, runsUntilStop, serviceProblems, utf16le } from "./render.js";
5
+ // src/host/install.ts
6
+ /** This function gives the folder of the systemd user units: `$XDG_CONFIG_HOME/systemd/user`, or `~/.config/systemd/user`. */
7
+ const unitDir = (ports) => {
8
+ const config = ports.env["XDG_CONFIG_HOME"];
9
+ return joinPath("linux", config === void 0 || config === "" ? joinPath("linux", ports.homeDir, ".config") : config, "systemd", "user");
10
+ };
11
+ /** This function gives the files of a service on the platform of the ports. */
12
+ const servicePaths = (spec, ports) => {
13
+ if (ports.platform === "win32") return {
14
+ unit: joinPath("win32", spec.stateDir, `${spec.name}.task.xml`),
15
+ timer: null
16
+ };
17
+ const dir = unitDir(ports);
18
+ return {
19
+ unit: joinPath("linux", dir, `${spec.name}.service`),
20
+ timer: runsUntilStop(spec.start) ? null : joinPath("linux", dir, `${spec.name}.timer`)
21
+ };
22
+ };
23
+ /** This function gives the unit that `systemctl` enables: the timer of a daily job, or the service. */
24
+ const enabledUnit = (spec) => runsUntilStop(spec.start) ? `${spec.name}.service` : `${spec.name}.timer`;
25
+ /**
26
+ * This text goes with a failure of `schtasks` for a spec in the background. Task Scheduler refuses a boot trigger
27
+ * and an S4U logon from a shell that is not elevated: `Access is denied`, with the code 1 (Windows 11, 2026-11).
28
+ */
29
+ const ELEVATION = "Task Scheduler refuses a boot trigger and an S4U logon from a shell that is not elevated: start the same operation in a shell of an administrator";
30
+ /** This function gives the path of `conhost.exe` from `SystemRoot`. Without it, Task Scheduler expands `%SystemRoot%` at the start. */
31
+ const conhostPath = (ports) => joinPath("win32", ports.env["SystemRoot"] ?? "%SystemRoot%", "System32", "conhost.exe");
32
+ const runner = (ports) => {
33
+ const commands = [];
34
+ return {
35
+ commands,
36
+ async run(file, args) {
37
+ let record;
38
+ try {
39
+ const result = await ports.commands.run(file, args);
40
+ record = {
41
+ file,
42
+ args,
43
+ code: result.code,
44
+ out: result.out.trim()
45
+ };
46
+ } catch (error) {
47
+ record = {
48
+ file,
49
+ args,
50
+ code: 127,
51
+ out: error instanceof Error ? error.message : String(error)
52
+ };
53
+ }
54
+ commands.push(record);
55
+ ports.logger?.log(record.code === 0 ? "debug" : "warn", `${file} ${args.join(" ")} gave the code ${record.code}`, { ...record });
56
+ return record;
57
+ }
58
+ };
59
+ };
60
+ const failed = (commands, record, note) => ({
61
+ kind: "failed",
62
+ commands,
63
+ problem: `${record.file} ${record.args.join(" ")} gave the code ${record.code}${record.out === "" ? "" : `: ${record.out}`}${note === null ? "" : ` (${note})`}`
64
+ });
65
+ /** This function gives the note of a failed command: the elevation of Task Scheduler for a spec in the background, or null. */
66
+ const noteOf = (spec, ports, record) => ports.platform === "win32" && record.file === "schtasks" && inBackground(spec) ? ELEVATION : null;
67
+ const problemOf = (error) => error instanceof Error ? error.message : String(error);
68
+ /**
69
+ * This function runs the steps of an operation. It refuses a spec with problems and a platform that
70
+ * is not Windows or Linux, and it catches each failure of the file system.
71
+ */
72
+ const operate = async (spec, ports, steps) => {
73
+ const problems = serviceProblems(spec);
74
+ if (problems.length > 0) return {
75
+ kind: "refused",
76
+ problems
77
+ };
78
+ if (ports.platform !== "win32" && ports.platform !== "linux") return {
79
+ kind: "unsupported",
80
+ platform: ports.platform
81
+ };
82
+ const run = runner(ports);
83
+ const files = [];
84
+ try {
85
+ const failure = await steps(run, files);
86
+ if (failure !== null) return failed(run.commands, failure, noteOf(spec, ports, failure));
87
+ } catch (error) {
88
+ return {
89
+ kind: "failed",
90
+ commands: run.commands,
91
+ problem: `the file system failed: ${problemOf(error)}`
92
+ };
93
+ }
94
+ return {
95
+ kind: "done",
96
+ commands: run.commands,
97
+ files
98
+ };
99
+ };
100
+ /** This function gives the first record whose code is not 0, or null. */
101
+ const firstFailure = (...records) => records.find((record) => record.code !== 0) ?? null;
102
+ /**
103
+ * This function installs a service of the user, and by default starts it. It does not throw.
104
+ * - On Windows, it writes the task file in UTF-16 to `stateDir`, and starts `schtasks /Create /XML <file> /F`, then `schtasks /Run`.
105
+ * - On Linux, it writes the unit (and the timer of a daily job), then starts `systemctl --user daemon-reload` and `enable`.
106
+ * For a spec in the background, it first starts `loginctl enable-linger` for the user.
107
+ * A second install replaces the first. Give it the ports of a test, thus no test installs a real task.
108
+ * On Windows, Task Scheduler refuses a spec in the background from a shell that is not elevated: the problem then tells so.
109
+ */
110
+ const installService = (spec, ports, options = {}) => operate(spec, ports, async (run, files) => {
111
+ const start = options.start ?? true;
112
+ const paths = servicePaths(spec, ports);
113
+ if (ports.platform === "win32") {
114
+ await ports.files.write(paths.unit, utf16le(renderTaskXml(spec, {
115
+ user: ports.user(),
116
+ conhost: conhostPath(ports)
117
+ })));
118
+ files.push(paths.unit);
119
+ const created = await run.run("schtasks", [
120
+ "/Create",
121
+ "/TN",
122
+ spec.name,
123
+ "/XML",
124
+ paths.unit,
125
+ "/F"
126
+ ]);
127
+ if (created.code !== 0 || !start) return firstFailure(created);
128
+ return firstFailure(await run.run("schtasks", [
129
+ "/Run",
130
+ "/TN",
131
+ spec.name
132
+ ]));
133
+ }
134
+ await ports.files.write(paths.unit, renderSystemdUnit(spec));
135
+ files.push(paths.unit);
136
+ const timer = renderSystemdTimer(spec);
137
+ if (paths.timer !== null && timer !== null) {
138
+ await ports.files.write(paths.timer, timer);
139
+ files.push(paths.timer);
140
+ }
141
+ if (inBackground(spec)) {
142
+ const lingered = await run.run("loginctl", ["enable-linger"]);
143
+ if (lingered.code !== 0) return lingered;
144
+ }
145
+ const reloaded = await run.run("systemctl", ["--user", "daemon-reload"]);
146
+ if (reloaded.code !== 0) return reloaded;
147
+ return firstFailure(await run.run("systemctl", [
148
+ "--user",
149
+ "enable",
150
+ ...start ? ["--now"] : [],
151
+ enabledUnit(spec)
152
+ ]));
153
+ });
154
+ /** This function stops the instance of a discovery file, when it is alive and is the same process. */
155
+ const stopInstance = async (ports, options) => {
156
+ if (options.discovery === void 0) return;
157
+ const found = await readDiscovery(options.discovery, ports, { clean: true });
158
+ if (found.kind !== "running") return;
159
+ const stopped = await stopTree(found.record.pid, ports);
160
+ ports.logger?.log(stopped.kind === "failed" ? "warn" : "info", `the host stopped the instance ${found.record.pid}: ${stopped.kind}`, {
161
+ pid: found.record.pid,
162
+ outcome: stopped.kind
163
+ });
164
+ };
165
+ /**
166
+ * This function removes a service. It does not throw. On Windows, it ends the task and deletes it. On
167
+ * Linux, it disables and stops the unit, removes its files and reloads systemd. With a discovery file,
168
+ * it then stops the process tree of an instance that stays.
169
+ */
170
+ const uninstallService = (spec, ports, options = {}) => operate(spec, ports, async (run, files) => {
171
+ const paths = servicePaths(spec, ports);
172
+ let failure;
173
+ if (ports.platform === "win32") {
174
+ await run.run("schtasks", [
175
+ "/End",
176
+ "/TN",
177
+ spec.name
178
+ ]);
179
+ failure = firstFailure(await run.run("schtasks", [
180
+ "/Delete",
181
+ "/TN",
182
+ spec.name,
183
+ "/F"
184
+ ]));
185
+ await ports.files.remove(paths.unit);
186
+ } else {
187
+ failure = firstFailure(await run.run("systemctl", [
188
+ "--user",
189
+ "disable",
190
+ "--now",
191
+ enabledUnit(spec)
192
+ ]));
193
+ if (paths.timer !== null) await run.run("systemctl", [
194
+ "--user",
195
+ "stop",
196
+ `${spec.name}.service`
197
+ ]);
198
+ await ports.files.remove(paths.unit);
199
+ if (paths.timer !== null) await ports.files.remove(paths.timer);
200
+ await run.run("systemctl", ["--user", "daemon-reload"]);
201
+ }
202
+ files.push(paths.unit, ...paths.timer === null ? [] : [paths.timer]);
203
+ await stopInstance(ports, options);
204
+ return failure;
205
+ });
206
+ /** This function enables a service and starts it. It does not throw. On Windows, it enables the task and runs it. */
207
+ const startService = (spec, ports) => operate(spec, ports, async (run) => {
208
+ if (ports.platform === "win32") {
209
+ const enabled = await run.run("schtasks", [
210
+ "/Change",
211
+ "/TN",
212
+ spec.name,
213
+ "/ENABLE"
214
+ ]);
215
+ if (enabled.code !== 0) return enabled;
216
+ return firstFailure(await run.run("schtasks", [
217
+ "/Run",
218
+ "/TN",
219
+ spec.name
220
+ ]));
221
+ }
222
+ return firstFailure(await run.run("systemctl", [
223
+ "--user",
224
+ "enable",
225
+ "--now",
226
+ enabledUnit(spec)
227
+ ]));
228
+ });
229
+ /**
230
+ * This function stops a service, and keeps it stopped until `startService`. It does not throw.
231
+ * - On Windows, it disables the task, thus its time trigger does not start it again, and ends the task.
232
+ * With a discovery file, it then stops the process tree of the instance. Windows has no signal that a child can catch.
233
+ * - On Linux, it disables the unit of a service at logon or at boot, or the timer of a daily job, and stops it.
234
+ * Thus the next login, the next boot or the next calendar time does not start it again. The stop sends SIGTERM,
235
+ * thus `run()` stops in its stages. A daily job that operates stops too.
236
+ */
237
+ const stopService = (spec, ports, options = {}) => operate(spec, ports, async (run) => {
238
+ if (ports.platform === "win32") {
239
+ const disabled = await run.run("schtasks", [
240
+ "/Change",
241
+ "/TN",
242
+ spec.name,
243
+ "/DISABLE"
244
+ ]);
245
+ if (disabled.code !== 0) return disabled;
246
+ await run.run("schtasks", [
247
+ "/End",
248
+ "/TN",
249
+ spec.name
250
+ ]);
251
+ await stopInstance(ports, options);
252
+ return null;
253
+ }
254
+ const disabled = await run.run("systemctl", [
255
+ "--user",
256
+ "disable",
257
+ "--now",
258
+ enabledUnit(spec)
259
+ ]);
260
+ if (disabled.code !== 0 || runsUntilStop(spec.start)) return firstFailure(disabled);
261
+ return firstFailure(await run.run("systemctl", [
262
+ "--user",
263
+ "stop",
264
+ `${spec.name}.service`
265
+ ]));
266
+ });
267
+ /** This function gives the value of a line `Key: value` of the list of `schtasks /Query /FO LIST`. */
268
+ const listValue = (out, key) => {
269
+ for (const line of out.split(/\r?\n/)) {
270
+ const at = line.indexOf(":");
271
+ if (at > 0 && line.slice(0, at).trim() === key) return line.slice(at + 1).trim();
272
+ }
273
+ return null;
274
+ };
275
+ /**
276
+ * This function gives the status of a service. It does not throw. A service that the system does not
277
+ * have gives `installed: false`. A malformed or stale discovery file gives its read, and not a throw.
278
+ */
279
+ const serviceStatus = async (spec, ports, options = {}) => {
280
+ const run = runner(ports);
281
+ const instance = options.discovery === void 0 ? null : await readDiscovery(options.discovery, ports);
282
+ if (serviceProblems(spec).length > 0 || ports.platform !== "win32" && ports.platform !== "linux") return {
283
+ installed: false,
284
+ state: "unknown",
285
+ instance,
286
+ commands: run.commands
287
+ };
288
+ if (ports.platform === "win32") {
289
+ const query = await run.run("schtasks", [
290
+ "/Query",
291
+ "/TN",
292
+ spec.name,
293
+ "/V",
294
+ "/FO",
295
+ "LIST"
296
+ ]);
297
+ if (query.code !== 0) return {
298
+ installed: false,
299
+ state: "unknown",
300
+ instance,
301
+ commands: run.commands
302
+ };
303
+ return {
304
+ installed: true,
305
+ state: listValue(query.out, "Status") ?? "unknown",
306
+ instance,
307
+ commands: run.commands
308
+ };
309
+ }
310
+ let installed;
311
+ try {
312
+ installed = await ports.files.read(servicePaths(spec, ports).unit) !== null;
313
+ } catch {
314
+ installed = false;
315
+ }
316
+ const state = (await run.run("systemctl", [
317
+ "--user",
318
+ "is-active",
319
+ `${spec.name}.service`
320
+ ])).out.split(/\r?\n/)[0]?.trim() ?? "";
321
+ return {
322
+ installed,
323
+ state: state === "" ? "unknown" : state,
324
+ instance,
325
+ commands: run.commands
326
+ };
327
+ };
328
+ export { installService, servicePaths, serviceStatus, startService, stopService, uninstallService };
329
+
330
+ //# sourceMappingURL=install.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"install.js","names":[],"sources":["../../src/host/install.ts"],"sourcesContent":["import type { DiscoveryRead } from \"./discovery.ts\";\nimport { readDiscovery } from \"./discovery.ts\";\nimport type { HostPorts } from \"./ports.ts\";\nimport { joinPath } from \"./ports.ts\";\nimport { stopTree } from \"./processes.ts\";\nimport type { ServiceSpec } from \"./render.ts\";\nimport { inBackground, renderSystemdTimer, renderSystemdUnit, renderTaskXml, runsUntilStop, serviceProblems, utf16le } from \"./render.ts\";\n\n/** A command record is one command that a service operation started, and its result. */\nexport interface CommandRecord {\n readonly file: string;\n readonly args: readonly string[];\n readonly code: number;\n readonly out: string;\n}\n\n/**\n * A service outcome tells what a service operation did. An operation does not throw.\n * - `done`: each command gave 0. `commands` and `files` tell what the operation did.\n * - `failed`: a command gave a code that is not 0, or the file system failed. The problem tells which.\n * - `refused`: the spec has problems, and the operation did nothing.\n * - `unsupported`: the platform is not Windows or Linux, and the operation did nothing.\n */\nexport type ServiceOutcome =\n | { readonly kind: \"done\"; readonly commands: readonly CommandRecord[]; readonly files: readonly string[] }\n | { readonly kind: \"failed\"; readonly commands: readonly CommandRecord[]; readonly problem: string }\n | { readonly kind: \"refused\"; readonly problems: readonly string[] }\n | { readonly kind: \"unsupported\"; readonly platform: string };\n\n/** A service status tells if the system has the service, its state, and the instance of the discovery file. */\nexport interface ServiceStatus {\n /** This flag tells if the system has the task or the unit. */\n readonly installed: boolean;\n /**\n * This text is the state that the system gives, for example `Running` or `Ready` from `schtasks`, or\n * `active` or `inactive` from `systemctl`. It is `unknown` when the system gives no state.\n */\n readonly state: string;\n /** This is the read of the discovery file, or null without a discovery path. */\n readonly instance: DiscoveryRead | null;\n /** These are the commands that the status started. */\n readonly commands: readonly CommandRecord[];\n}\n\n/** These options go with an install. */\nexport interface InstallOptions {\n /** True starts the service after the install. The default is true. */\n readonly start?: boolean | undefined;\n}\n\n/** These options go with an operation that stops the instance: the discovery file that names it. */\nexport interface InstanceOptions {\n /** This path is the discovery file of the instance. With it, the operation stops the process tree of a live instance. */\n readonly discovery?: string | undefined;\n}\n\n/** These are the files of a service on this platform. */\nexport interface ServicePaths {\n /** This path is the task file on Windows, or the unit on Linux. */\n readonly unit: string;\n /** This path is the timer of a daily job on Linux, or null. */\n readonly timer: string | null;\n}\n\n/** This function gives the folder of the systemd user units: `$XDG_CONFIG_HOME/systemd/user`, or `~/.config/systemd/user`. */\nconst unitDir = (ports: HostPorts): string => {\n const config = ports.env[\"XDG_CONFIG_HOME\"];\n return joinPath(\"linux\", config === undefined || config === \"\" ? joinPath(\"linux\", ports.homeDir, \".config\") : config, \"systemd\", \"user\");\n};\n\n/** This function gives the files of a service on the platform of the ports. */\nexport const servicePaths = (spec: ServiceSpec, ports: HostPorts): ServicePaths => {\n if (ports.platform === \"win32\") return { unit: joinPath(\"win32\", spec.stateDir, `${spec.name}.task.xml`), timer: null };\n const dir = unitDir(ports);\n return { unit: joinPath(\"linux\", dir, `${spec.name}.service`), timer: runsUntilStop(spec.start) ? null : joinPath(\"linux\", dir, `${spec.name}.timer`) };\n};\n\n/** This function gives the unit that `systemctl` enables: the timer of a daily job, or the service. */\nconst enabledUnit = (spec: ServiceSpec): string => (runsUntilStop(spec.start) ? `${spec.name}.service` : `${spec.name}.timer`);\n\n/**\n * This text goes with a failure of `schtasks` for a spec in the background. Task Scheduler refuses a boot trigger\n * and an S4U logon from a shell that is not elevated: `Access is denied`, with the code 1 (Windows 11, 2026-11).\n */\nconst ELEVATION =\n \"Task Scheduler refuses a boot trigger and an S4U logon from a shell that is not elevated: start the same operation in a shell of an administrator\";\n\n/** This function gives the path of `conhost.exe` from `SystemRoot`. Without it, Task Scheduler expands `%SystemRoot%` at the start. */\nconst conhostPath = (ports: HostPorts): string => joinPath(\"win32\", ports.env[\"SystemRoot\"] ?? \"%SystemRoot%\", \"System32\", \"conhost.exe\");\n\n/** A runner starts commands, and keeps a record of each. */\ninterface Runner {\n readonly commands: CommandRecord[];\n run(file: string, args: readonly string[]): Promise<CommandRecord>;\n}\n\nconst runner = (ports: HostPorts): Runner => {\n const commands: CommandRecord[] = [];\n return {\n commands,\n async run(file, args) {\n let record: CommandRecord;\n try {\n const result = await ports.commands.run(file, args);\n record = { file, args, code: result.code, out: result.out.trim() };\n } catch (error) {\n record = { file, args, code: 127, out: error instanceof Error ? error.message : String(error) };\n }\n commands.push(record);\n ports.logger?.log(record.code === 0 ? \"debug\" : \"warn\", `${file} ${args.join(\" \")} gave the code ${record.code}`, { ...record });\n return record;\n },\n };\n};\n\nconst failed = (commands: readonly CommandRecord[], record: CommandRecord, note: string | null): ServiceOutcome => ({\n kind: \"failed\",\n commands,\n problem: `${record.file} ${record.args.join(\" \")} gave the code ${record.code}${record.out === \"\" ? \"\" : `: ${record.out}`}${note === null ? \"\" : ` (${note})`}`,\n});\n\n/** This function gives the note of a failed command: the elevation of Task Scheduler for a spec in the background, or null. */\nconst noteOf = (spec: ServiceSpec, ports: HostPorts, record: CommandRecord): string | null =>\n ports.platform === \"win32\" && record.file === \"schtasks\" && inBackground(spec) ? ELEVATION : null;\n\nconst problemOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n/**\n * This function runs the steps of an operation. It refuses a spec with problems and a platform that\n * is not Windows or Linux, and it catches each failure of the file system.\n */\nconst operate = async (\n spec: ServiceSpec,\n ports: HostPorts,\n steps: (run: Runner, files: string[]) => Promise<CommandRecord | null>,\n): Promise<ServiceOutcome> => {\n const problems = serviceProblems(spec);\n if (problems.length > 0) return { kind: \"refused\", problems };\n if (ports.platform !== \"win32\" && ports.platform !== \"linux\") return { kind: \"unsupported\", platform: ports.platform };\n const run = runner(ports);\n const files: string[] = [];\n try {\n const failure = await steps(run, files);\n if (failure !== null) return failed(run.commands, failure, noteOf(spec, ports, failure));\n } catch (error) {\n return { kind: \"failed\", commands: run.commands, problem: `the file system failed: ${problemOf(error)}` };\n }\n return { kind: \"done\", commands: run.commands, files };\n};\n\n/** This function gives the first record whose code is not 0, or null. */\nconst firstFailure = (...records: readonly CommandRecord[]): CommandRecord | null => records.find((record) => record.code !== 0) ?? null;\n\n/**\n * This function installs a service of the user, and by default starts it. It does not throw.\n * - On Windows, it writes the task file in UTF-16 to `stateDir`, and starts `schtasks /Create /XML <file> /F`, then `schtasks /Run`.\n * - On Linux, it writes the unit (and the timer of a daily job), then starts `systemctl --user daemon-reload` and `enable`.\n * For a spec in the background, it first starts `loginctl enable-linger` for the user.\n * A second install replaces the first. Give it the ports of a test, thus no test installs a real task.\n * On Windows, Task Scheduler refuses a spec in the background from a shell that is not elevated: the problem then tells so.\n */\nexport const installService = (spec: ServiceSpec, ports: HostPorts, options: InstallOptions = {}): Promise<ServiceOutcome> =>\n operate(spec, ports, async (run, files) => {\n const start = options.start ?? true;\n const paths = servicePaths(spec, ports);\n if (ports.platform === \"win32\") {\n await ports.files.write(paths.unit, utf16le(renderTaskXml(spec, { user: ports.user(), conhost: conhostPath(ports) })));\n files.push(paths.unit);\n const created = await run.run(\"schtasks\", [\"/Create\", \"/TN\", spec.name, \"/XML\", paths.unit, \"/F\"]);\n if (created.code !== 0 || !start) return firstFailure(created);\n return firstFailure(await run.run(\"schtasks\", [\"/Run\", \"/TN\", spec.name]));\n }\n await ports.files.write(paths.unit, renderSystemdUnit(spec));\n files.push(paths.unit);\n const timer = renderSystemdTimer(spec);\n if (paths.timer !== null && timer !== null) {\n await ports.files.write(paths.timer, timer);\n files.push(paths.timer);\n }\n if (inBackground(spec)) {\n // the linger starts the user manager at boot and keeps it after the logout. The removal keeps the linger, because other units can need it\n const lingered = await run.run(\"loginctl\", [\"enable-linger\"]);\n if (lingered.code !== 0) return lingered;\n }\n const reloaded = await run.run(\"systemctl\", [\"--user\", \"daemon-reload\"]);\n if (reloaded.code !== 0) return reloaded;\n return firstFailure(await run.run(\"systemctl\", [\"--user\", \"enable\", ...(start ? [\"--now\"] : []), enabledUnit(spec)]));\n });\n\n/** This function stops the instance of a discovery file, when it is alive and is the same process. */\nconst stopInstance = async (ports: HostPorts, options: InstanceOptions): Promise<void> => {\n if (options.discovery === undefined) return;\n const found = await readDiscovery(options.discovery, ports, { clean: true });\n if (found.kind !== \"running\") return;\n const stopped = await stopTree(found.record.pid, ports);\n ports.logger?.log(stopped.kind === \"failed\" ? \"warn\" : \"info\", `the host stopped the instance ${found.record.pid}: ${stopped.kind}`, {\n pid: found.record.pid,\n outcome: stopped.kind,\n });\n};\n\n/**\n * This function removes a service. It does not throw. On Windows, it ends the task and deletes it. On\n * Linux, it disables and stops the unit, removes its files and reloads systemd. With a discovery file,\n * it then stops the process tree of an instance that stays.\n */\nexport const uninstallService = (spec: ServiceSpec, ports: HostPorts, options: InstanceOptions = {}): Promise<ServiceOutcome> =>\n operate(spec, ports, async (run, files) => {\n const paths = servicePaths(spec, ports);\n let failure: CommandRecord | null;\n if (ports.platform === \"win32\") {\n // the end of a task that does not run gives a code that is not 0: it is not a failure of the removal\n await run.run(\"schtasks\", [\"/End\", \"/TN\", spec.name]);\n failure = firstFailure(await run.run(\"schtasks\", [\"/Delete\", \"/TN\", spec.name, \"/F\"]));\n await ports.files.remove(paths.unit);\n } else {\n failure = firstFailure(await run.run(\"systemctl\", [\"--user\", \"disable\", \"--now\", enabledUnit(spec)]));\n if (paths.timer !== null) await run.run(\"systemctl\", [\"--user\", \"stop\", `${spec.name}.service`]);\n await ports.files.remove(paths.unit);\n if (paths.timer !== null) await ports.files.remove(paths.timer);\n await run.run(\"systemctl\", [\"--user\", \"daemon-reload\"]);\n }\n files.push(paths.unit, ...(paths.timer === null ? [] : [paths.timer]));\n await stopInstance(ports, options);\n return failure;\n });\n\n/** This function enables a service and starts it. It does not throw. On Windows, it enables the task and runs it. */\nexport const startService = (spec: ServiceSpec, ports: HostPorts): Promise<ServiceOutcome> =>\n operate(spec, ports, async (run) => {\n if (ports.platform === \"win32\") {\n const enabled = await run.run(\"schtasks\", [\"/Change\", \"/TN\", spec.name, \"/ENABLE\"]);\n if (enabled.code !== 0) return enabled;\n return firstFailure(await run.run(\"schtasks\", [\"/Run\", \"/TN\", spec.name]));\n }\n // stopService disables the unit or its timer, thus the start enables it again\n return firstFailure(await run.run(\"systemctl\", [\"--user\", \"enable\", \"--now\", enabledUnit(spec)]));\n });\n\n/**\n * This function stops a service, and keeps it stopped until `startService`. It does not throw.\n * - On Windows, it disables the task, thus its time trigger does not start it again, and ends the task.\n * With a discovery file, it then stops the process tree of the instance. Windows has no signal that a child can catch.\n * - On Linux, it disables the unit of a service at logon or at boot, or the timer of a daily job, and stops it.\n * Thus the next login, the next boot or the next calendar time does not start it again. The stop sends SIGTERM,\n * thus `run()` stops in its stages. A daily job that operates stops too.\n */\nexport const stopService = (spec: ServiceSpec, ports: HostPorts, options: InstanceOptions = {}): Promise<ServiceOutcome> =>\n operate(spec, ports, async (run) => {\n if (ports.platform === \"win32\") {\n const disabled = await run.run(\"schtasks\", [\"/Change\", \"/TN\", spec.name, \"/DISABLE\"]);\n if (disabled.code !== 0) return disabled;\n await run.run(\"schtasks\", [\"/End\", \"/TN\", spec.name]);\n await stopInstance(ports, options);\n return null;\n }\n const disabled = await run.run(\"systemctl\", [\"--user\", \"disable\", \"--now\", enabledUnit(spec)]);\n if (disabled.code !== 0 || runsUntilStop(spec.start)) return firstFailure(disabled);\n return firstFailure(await run.run(\"systemctl\", [\"--user\", \"stop\", `${spec.name}.service`]));\n });\n\n/** This function gives the value of a line `Key: value` of the list of `schtasks /Query /FO LIST`. */\nconst listValue = (out: string, key: string): string | null => {\n for (const line of out.split(/\\r?\\n/)) {\n const at = line.indexOf(\":\");\n if (at > 0 && line.slice(0, at).trim() === key) return line.slice(at + 1).trim();\n }\n return null;\n};\n\n/**\n * This function gives the status of a service. It does not throw. A service that the system does not\n * have gives `installed: false`. A malformed or stale discovery file gives its read, and not a throw.\n */\nexport const serviceStatus = async (spec: ServiceSpec, ports: HostPorts, options: InstanceOptions = {}): Promise<ServiceStatus> => {\n const run = runner(ports);\n const instance = options.discovery === undefined ? null : await readDiscovery(options.discovery, ports);\n if (serviceProblems(spec).length > 0 || (ports.platform !== \"win32\" && ports.platform !== \"linux\"))\n return { installed: false, state: \"unknown\", instance, commands: run.commands };\n if (ports.platform === \"win32\") {\n const query = await run.run(\"schtasks\", [\"/Query\", \"/TN\", spec.name, \"/V\", \"/FO\", \"LIST\"]);\n if (query.code !== 0) return { installed: false, state: \"unknown\", instance, commands: run.commands };\n return { installed: true, state: listValue(query.out, \"Status\") ?? \"unknown\", instance, commands: run.commands };\n }\n let installed: boolean;\n try {\n installed = (await ports.files.read(servicePaths(spec, ports).unit)) !== null;\n } catch {\n installed = false;\n }\n const active = await run.run(\"systemctl\", [\"--user\", \"is-active\", `${spec.name}.service`]);\n const state = active.out.split(/\\r?\\n/)[0]?.trim() ?? \"\";\n return { installed, state: state === \"\" ? \"unknown\" : state, instance, commands: run.commands };\n};\n"],"mappings":";;;;;;AAiEA,MAAM,WAAW,UAA6B;CAC5C,MAAM,SAAS,MAAM,IAAI;CACzB,OAAO,SAAS,SAAS,WAAW,KAAA,KAAa,WAAW,KAAK,SAAS,SAAS,MAAM,SAAS,SAAS,IAAI,QAAQ,WAAW,MAAM;AAC1I;;AAGA,MAAa,gBAAgB,MAAmB,UAAmC;CACjF,IAAI,MAAM,aAAa,SAAS,OAAO;EAAE,MAAM,SAAS,SAAS,KAAK,UAAU,GAAG,KAAK,KAAK,UAAU;EAAG,OAAO;CAAK;CACtH,MAAM,MAAM,QAAQ,KAAK;CACzB,OAAO;EAAE,MAAM,SAAS,SAAS,KAAK,GAAG,KAAK,KAAK,SAAS;EAAG,OAAO,cAAc,KAAK,KAAK,IAAI,OAAO,SAAS,SAAS,KAAK,GAAG,KAAK,KA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GAAM;GAAM;GAAO;EAAM,CAAC;EACzF,IAAI,MAAM,SAAS,GAAG,OAAO;GAAE,WAAW;GAAO,OAAO;GAAW;GAAU,UAAU,IAAI;EAAS;EACpG,OAAO;GAAE,WAAW;GAAM,OAAO,UAAU,MAAM,KAAK,QAAQ,KAAK;GAAW;GAAU,UAAU,IAAI;EAAS;CACjH;CACA,IAAI;CACJ,IAAI;EACF,YAAa,MAAM,MAAM,MAAM,KAAK,aAAa,MAAM,KAAK,CAAC,CAAC,IAAI,MAAO;CAC3E,QAAQ;EACN,YAAY;CACd;CAEA,MAAM,SAAQ,MADO,IAAI,IAAI,aAAa;EAAC;EAAU;EAAa,GAAG,KAAK,KAAK;CAAS,CAAC,EAAA,CACpE,IAAI,MAAM,OAAO,CAAC,CAAC,EAAE,EAAE,KAAK,KAAK;CACtD,OAAO;EAAE;EAAW,OAAO,UAAU,KAAK,YAAY;EAAO;EAAU,UAAU,IAAI;CAAS;AAChG"}
@@ -0,0 +1,78 @@
1
+ import { HostPorts, ProcessMark } from "./ports.js";
2
+ /**
3
+ * A lock owner is the record in a lock file: the process that holds the lock. The record can also
4
+ * have the child process that it holds the lock for. The lock is held while one of the two is alive.
5
+ */
6
+ export interface LockOwner extends ProcessMark {
7
+ readonly child?: ProcessMark | undefined;
8
+ }
9
+ /** An instance lock is a lock that this process holds. */
10
+ export interface InstanceLock {
11
+ readonly path: string;
12
+ readonly owner: LockOwner;
13
+ /** This method writes a new child process in the record, or no child with null. */
14
+ update(child: ProcessMark | null): Promise<void>;
15
+ /** This method removes the lock file, when it still has the record of this lock. A second use does nothing. */
16
+ release(): Promise<void>;
17
+ }
18
+ /**
19
+ * A lock result tells what a try to take the lock found.
20
+ * - `acquired`: this process holds the lock. `recovered` tells why a stale lock went first, or it is null.
21
+ * - `held`: a live process holds the lock. Its owner is in the result.
22
+ * - `failed`: the lock did not come free, or the file system failed. The problem tells why.
23
+ */
24
+ export type LockResult = {
25
+ readonly kind: "acquired";
26
+ readonly lock: InstanceLock;
27
+ readonly recovered: string | null;
28
+ } | {
29
+ readonly kind: "held";
30
+ readonly owner: LockOwner;
31
+ } | {
32
+ readonly kind: "failed";
33
+ readonly problem: string;
34
+ };
35
+ /**
36
+ * A lock state is what an examination of a lock file found. An examination does not throw.
37
+ * - `free`: no file.
38
+ * - `held`: the record names a live process.
39
+ * - `stale`: the record names processes that stopped. The next take removes the file.
40
+ * - `malformed`: the file is not a record, or the read failed.
41
+ */
42
+ export type LockState = {
43
+ readonly kind: "free";
44
+ } | {
45
+ readonly kind: "held";
46
+ readonly owner: LockOwner;
47
+ } | {
48
+ readonly kind: "stale";
49
+ readonly owner: LockOwner;
50
+ readonly why: string;
51
+ } | {
52
+ readonly kind: "malformed";
53
+ readonly problem: string;
54
+ };
55
+ /** These options go with a take of the lock. */
56
+ export interface LockOptions {
57
+ /** This count is the number of reads of a malformed file before the take removes it. The default is 3. */
58
+ readonly tries?: number | undefined;
59
+ /** This time is the pause between two reads of a malformed file, in milliseconds. The default is 100. */
60
+ readonly pause?: number | undefined;
61
+ /** This child process goes in the record at the take. */
62
+ readonly child?: ProcessMark | undefined;
63
+ }
64
+ /** This function reads a lock owner from the text of a lock file, or gives null for a text that is not a record. */
65
+ export declare const parseLockOwner: (text: string) => LockOwner | null;
66
+ /** This function gives the text of a lock file for an owner. */
67
+ export declare const lockText: (owner: LockOwner) => string;
68
+ /** This function examines a lock file. It does not throw. */
69
+ export declare const inspectInstanceLock: (path: string, ports: HostPorts) => Promise<LockState>;
70
+ /**
71
+ * This function takes the lock of one instance: a lock file with the record of this process. Thus a
72
+ * second instance does not start. It does not throw.
73
+ * - A file whose owner and child stopped is stale: it goes, and the take tries again.
74
+ * - A malformed file can be the file of a take that writes at this time. The take reads it again after
75
+ * a pause, and after `tries` reads, it removes it.
76
+ * - A file whose owner or child is alive gives `held`.
77
+ */
78
+ export declare const acquireInstanceLock: (path: string, ports: HostPorts, options?: LockOptions) => Promise<LockResult>;