@jive-sh/skill-sync 0.1.2-latest-linux-arm64 → 0.1.2

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/README.md ADDED
@@ -0,0 +1,29 @@
1
+ # @jive-sh/skill-sync
2
+
3
+ Keeps one skills directory identical across every machine you work on.
4
+
5
+ A daemon watches the directory and syncs it through a Cloudflare Worker: file index in D1, contents in
6
+ R2 addressed by hash. `skill-sync login` opens `skill-sync.jive.sh` in your browser, where you verify
7
+ with your passkey (from any passkey manager, such as Google Password Manager); the service then hands the
8
+ CLI a per-machine token. The CLI never handles the passkey.
9
+
10
+ ```
11
+ skill-sync login verify with your passkey in the browser and store this machine's token
12
+ skill-sync status what this machine syncs, and whether it can reach the service
13
+ skill-sync sync run one cycle now
14
+ skill-sync logout revoke this machine's token
15
+ ```
16
+
17
+ The daemon registers itself to start at login when the package is installed.
18
+
19
+ ## Conflicts
20
+
21
+ Every write is a compare-and-swap on the file's current hash, so a change made on two machines at once
22
+ is refused rather than silently overwritten. The losing side keeps its version beside the incoming one
23
+ as `<file>.local`, logs it, and raises a desktop notification. Nothing is ever lost to a race.
24
+
25
+ ## Configuration
26
+
27
+ `~/.jive/skill-sync.json` holds the endpoint, the machine name and the directory to sync — all detected
28
+ on first run. `~/.skill-sync-token.json` holds the token alone, at mode 0600, written by `skill-sync
29
+ login` rather than by hand.
package/bin/skill-sync ADDED
@@ -0,0 +1,568 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ import { spawnSync } from "node:child_process";
4
+ import {
5
+ chmodSync,
6
+ copyFileSync,
7
+ existsSync,
8
+ linkSync,
9
+ mkdirSync,
10
+ readdirSync,
11
+ readFileSync,
12
+ renameSync,
13
+ rmSync,
14
+ writeFileSync,
15
+ } from "node:fs";
16
+ import { createHash } from "node:crypto";
17
+ import { homedir } from "node:os";
18
+ import { basename, dirname, join } from "node:path";
19
+ import { fileURLToPath } from "node:url";
20
+
21
+ const PLATFORM_MAP = {
22
+ "darwin-arm64": "darwin-arm64",
23
+ "darwin-x64": "darwin-x64",
24
+ "linux-arm64": "linux-arm64",
25
+ "linux-x64": "linux-x64",
26
+ "win32-x64": "windows-x64"
27
+ };
28
+ const PLATFORM_PACKAGES = {
29
+ "darwin-arm64": "@jive-sh/skill-sync-darwin-arm64",
30
+ "darwin-x64": "@jive-sh/skill-sync-darwin-x64",
31
+ "linux-arm64": "@jive-sh/skill-sync-linux-arm64",
32
+ "linux-x64": "@jive-sh/skill-sync-linux-x64",
33
+ "windows-x64": "@jive-sh/skill-sync-windows-x64"
34
+ };
35
+ const PLATFORM_BINARIES = {
36
+ "darwin-arm64": "multi-call-binary",
37
+ "darwin-x64": "multi-call-binary",
38
+ "linux-arm64": "multi-call-binary",
39
+ "linux-x64": "multi-call-binary",
40
+ "windows-x64": "multi-call-binary.exe"
41
+ };
42
+ const COMMANDS = [
43
+ "skill-sync",
44
+ "skill-sync-daemon"
45
+ ];
46
+ const PACKAGE_NAME = "@jive-sh/skill-sync";
47
+ // Every src/daemons/ entry. The build refuses to produce a package where this disagrees with the files,
48
+ // so it needs no checking here.
49
+ const DAEMONS = [
50
+ "skill-sync-daemon"
51
+ ];
52
+ const DAEMON_ID_PREFIX = "jive-daemon";
53
+ const DAEMON_HOME_DIR = ".jive";
54
+ const DAEMON_REGISTRY_SUBDIR = "daemons";
55
+ const DAEMON_LOG_SUBDIR = "logs";
56
+ const REPAIR_ONLY_FLAG = "--repair-only";
57
+ const BIN_DIR = "bin";
58
+ const INSTALL_SCRIPT = "install.js";
59
+ // Root install.js repairs command targets; bin launchers repair and then execute.
60
+ const IS_INSTALL_SCRIPT = false;
61
+ const WINDOWS_EXECUTABLE_SUFFIX = ".exe";
62
+ const INSTALLED_JSON = "installed.json";
63
+
64
+ const require = createRequire(import.meta.url);
65
+ const launcherPath = fileURLToPath(import.meta.url);
66
+ const launcherDir = dirname(launcherPath);
67
+ const packageDir = IS_INSTALL_SCRIPT ? launcherDir : dirname(launcherDir);
68
+ const commandTargetDir = join(packageDir, BIN_DIR);
69
+ const rootInstallScriptPath = join(packageDir, INSTALL_SCRIPT);
70
+
71
+ function fail(message) {
72
+ console.error(message);
73
+ process.exit(1);
74
+ }
75
+
76
+ function currentPlatformKey() {
77
+ const platformKey = PLATFORM_MAP[`${process.platform}-${process.arch}`];
78
+ if (!platformKey) {
79
+ fail(`Unsupported platform: ${process.platform}-${process.arch}`);
80
+ }
81
+ return platformKey;
82
+ }
83
+
84
+ function currentPlatformPackageName() {
85
+ const platformKey = currentPlatformKey();
86
+ const packageName = PLATFORM_PACKAGES[platformKey];
87
+ if (!packageName) {
88
+ fail(`No platform package is configured for ${platformKey}`);
89
+ }
90
+ return packageName;
91
+ }
92
+
93
+ /**
94
+ * When a Jive library contains any number of CLIs (entrypoints or agents), then the base package
95
+ * will have an optional dependency for each possible architecture, with those platform-specific
96
+ * packages containing a platform build of the CLI.
97
+ * @returns the path to the platform binary and the exact version of the platform package.
98
+ */
99
+ function currentPlatformPackage() {
100
+ const platformKey = currentPlatformKey();
101
+ const binaryFile = PLATFORM_BINARIES[platformKey];
102
+ if (!binaryFile) {
103
+ fail(`No platform binary is configured for ${platformKey}`);
104
+ }
105
+
106
+ const packageName = currentPlatformPackageName();
107
+ try {
108
+ const packageJsonPath = require.resolve(`${packageName}/package.json`);
109
+ const packageDir = dirname(packageJsonPath);
110
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
111
+ return {
112
+ binaryPath: join(packageDir, binaryFile),
113
+ version: packageJson.version,
114
+ };
115
+ } catch (error) {
116
+ fail(`Could not resolve optional platform package ${packageName}. Reinstall dependencies for ${process.platform}-${process.arch}.`);
117
+ }
118
+ }
119
+
120
+ function commandTargetPath(command) {
121
+ const suffix = process.platform === "win32" ? WINDOWS_EXECUTABLE_SUFFIX : "";
122
+ return join(commandTargetDir, `${command}${suffix}`);
123
+ }
124
+
125
+ function installedJsonPath() {
126
+ return join(commandTargetDir, INSTALLED_JSON);
127
+ }
128
+
129
+ function windowsTargetsAreCurrent(version) {
130
+ if (process.platform !== "win32") return false;
131
+ if (!COMMANDS.every((command) => existsSync(commandTargetPath(command)))) return false;
132
+
133
+ try {
134
+ const installed = JSON.parse(readFileSync(installedJsonPath(), "utf-8"));
135
+ return installed.version === version;
136
+ } catch {
137
+ return false;
138
+ }
139
+ }
140
+
141
+ function linkOrCopyFirstExecutable(sourcePath, targetPath) {
142
+ mkdirSync(dirname(targetPath), { recursive: true });
143
+ const tempPath = `${targetPath}.${process.pid}.${Date.now()}.tmp${process.platform === "win32" ? WINDOWS_EXECUTABLE_SUFFIX : ""}`;
144
+ rmSync(tempPath, { force: true });
145
+
146
+ try {
147
+ try {
148
+ linkSync(sourcePath, tempPath);
149
+ } catch {
150
+ copyFileSync(sourcePath, tempPath);
151
+ }
152
+
153
+ chmodSync(tempPath, 0o755);
154
+ rmSync(targetPath, { force: true });
155
+ renameSync(tempPath, targetPath);
156
+ } finally {
157
+ rmSync(tempPath, { force: true });
158
+ }
159
+ }
160
+
161
+ function hardLinkCommandTarget(sourcePath, targetPath) {
162
+ if (sourcePath === targetPath) return;
163
+
164
+ const tempPath = `${targetPath}.${process.pid}.${Date.now()}.tmp${process.platform === "win32" ? WINDOWS_EXECUTABLE_SUFFIX : ""}`;
165
+ rmSync(tempPath, { force: true });
166
+
167
+ try {
168
+ linkSync(sourcePath, tempPath);
169
+ chmodSync(tempPath, 0o755);
170
+ rmSync(targetPath, { force: true });
171
+ renameSync(tempPath, targetPath);
172
+ } finally {
173
+ rmSync(tempPath, { force: true });
174
+ }
175
+ }
176
+
177
+ function repairCommandTargets() {
178
+ const platformPackage = currentPlatformPackage();
179
+
180
+ if (windowsTargetsAreCurrent(platformPackage.version)) {
181
+ return;
182
+ }
183
+
184
+ const firstTargetPath = commandTargetPath(COMMANDS[0]);
185
+ linkOrCopyFirstExecutable(platformPackage.binaryPath, firstTargetPath);
186
+
187
+ for (const command of COMMANDS.slice(1)) {
188
+ hardLinkCommandTarget(firstTargetPath, commandTargetPath(command));
189
+ }
190
+
191
+ if (process.platform === "win32") {
192
+ writeFileSync(installedJsonPath(), `${JSON.stringify({ version: platformPackage.version }, null, 2)}\n`);
193
+ }
194
+ }
195
+
196
+ function runExecutable(executablePath) {
197
+ const result = spawnSync(executablePath, process.argv.slice(2), { stdio: "inherit" });
198
+
199
+ if (result.error) {
200
+ fail(result.error.message);
201
+ }
202
+ if (result.status !== 0) {
203
+ process.exit(result.status ?? 1);
204
+ }
205
+ }
206
+
207
+ function removeInstallScript() {
208
+ try {
209
+ rmSync(rootInstallScriptPath, { force: true });
210
+ // TODO: should we also remove the postinstall script line from package.json?
211
+ } catch {
212
+ // Cleanup is best-effort; failing to remove install.js should not fail package installation.
213
+ }
214
+ }
215
+
216
+ /* ------------------------------------------------------------------ daemon registration ---------- */
217
+
218
+ /**
219
+ * Registering a package's daemons with the operating system so they start at login.
220
+ *
221
+ * At login, not at boot: a daemon here acts for one user, with access to that user's keychain, SSH agent
222
+ * and home directory, and a system-wide service would have none of those. On Windows that is a scheduled
223
+ * task rather than a service for the same reason — a service runs in session 0, isolated from the desktop
224
+ * the user is actually logged into.
225
+ *
226
+ * This runs in the installer, which is plain JavaScript, because it has to run on a machine that has only
227
+ * just received the package. The daemon binary cannot register itself: nothing has started it yet.
228
+ */
229
+
230
+ function jiveHome() {
231
+ return join(homedir(), DAEMON_HOME_DIR);
232
+ }
233
+
234
+ function registryDir() {
235
+ return join(jiveHome(), DAEMON_REGISTRY_SUBDIR);
236
+ }
237
+
238
+ function logDir() {
239
+ return join(jiveHome(), DAEMON_LOG_SUBDIR);
240
+ }
241
+
242
+ function recordPath(id) {
243
+ return join(registryDir(), `${id}.json`);
244
+ }
245
+
246
+ /**
247
+ * The tree this copy of the package was installed into, which is where its daemons should work.
248
+ *
249
+ * Derived from the path rather than from INIT_CWD, which npm sets and Bun does not, and which answers the
250
+ * wrong question anyway: where the install was *typed*, not what it installed into. Walking out of the
251
+ * enclosing node_modules answers it for a project install and a global one alike, and a package with no
252
+ * node_modules above it — one built and installed in place — is its own root.
253
+ */
254
+ function installRoot() {
255
+ let dir = packageDir;
256
+ while (true) {
257
+ if (basename(dir) === "node_modules") return dirname(dir);
258
+ const parent = dirname(dir);
259
+ if (parent === dir) return packageDir;
260
+ dir = parent;
261
+ }
262
+ }
263
+
264
+ /**
265
+ * The id a registration is replaced at: the package's name, the daemon's name, and a digest of the
266
+ * directory this copy of the package was installed into.
267
+ *
268
+ * **Where the package is installed is what decides how many of its daemons exist.** Reinstalling or
269
+ * upgrading the same copy keeps the id, so the registration is replaced; a second copy installed somewhere
270
+ * else gets its own id, so each project that installs its own copy gets its own daemon and a globally
271
+ * installed copy gets exactly one.
272
+ *
273
+ * An earlier version had each daemon declare `local` or `global` in the manifest instead. That was a
274
+ * second source of truth that contradicted the real one: a `global` daemon installed into two projects
275
+ * registered once, pointing at whichever installed last, so uninstalling the second took the first
276
+ * project's daemon away — the very failure `local` existed to prevent.
277
+ */
278
+ /** One id segment: dots separate segments, so a dot inside a name cannot be left as one. */
279
+ function idSegment(value) {
280
+ return value.replace(/[^A-Za-z0-9-]+/g, "-");
281
+ }
282
+
283
+ /**
284
+ * Scope and name get a segment each, and an unscoped package gets "_" where its scope would be.
285
+ *
286
+ * Joining them with a dash instead would not be reversible: `@ozyman42/ozy-cli` and a package actually
287
+ * named `ozyman42-ozy-cli` would produce the same text. "_" is safe as the marker because npm forbids a
288
+ * scope or name from starting with it, so no real scope can collide with it.
289
+ */
290
+ function packageSegments() {
291
+ if (!PACKAGE_NAME.startsWith("@")) return ["_", idSegment(PACKAGE_NAME)];
292
+ const separator = PACKAGE_NAME.indexOf("/");
293
+ return [
294
+ idSegment(PACKAGE_NAME.slice(1, separator)),
295
+ idSegment(PACKAGE_NAME.slice(separator + 1)),
296
+ ];
297
+ }
298
+
299
+ function daemonId(name) {
300
+ const [scope, packageName] = packageSegments();
301
+ const installDigest = createHash("sha256").update(packageDir).digest("hex").slice(0, 10);
302
+ return `${DAEMON_ID_PREFIX}.${scope}.${packageName}.${idSegment(name)}.${installDigest}`;
303
+ }
304
+
305
+ function run(argv, allowFailure) {
306
+ const result = spawnSync(argv[0], argv.slice(1), { stdio: ["ignore", "ignore", "pipe"] });
307
+ if (result.error || result.status !== 0) {
308
+ if (!allowFailure) {
309
+ const detail = result.error ? result.error.message : String(result.stderr || "").trim();
310
+ console.error(` ${argv.join(" ")} failed: ${detail}`);
311
+ }
312
+ return false;
313
+ }
314
+ return true;
315
+ }
316
+
317
+ function xmlEscape(value) {
318
+ return String(value)
319
+ .split("&").join("&amp;")
320
+ .split("<").join("&lt;")
321
+ .split(">").join("&gt;");
322
+ }
323
+
324
+ /**
325
+ * launchd. KeepAlive on SuccessfulExit=false restarts a daemon that crashes but respects one that exits
326
+ * zero, which is how a daemon that has removed its own registration stays stopped.
327
+ */
328
+ function registerLaunchd(id, name, executable, workingDirectory, logPath) {
329
+ // The id verbatim, rather than a reverse-DNS label: one string names this daemon on every platform.
330
+ const label = id;
331
+ const agentsDir = join(homedir(), "Library", "LaunchAgents");
332
+ const plistPath = join(agentsDir, `${label}.plist`);
333
+ const domain = `gui/${process.getuid()}`;
334
+ const unregister = ["launchctl", "bootout", `${domain}/${label}`];
335
+
336
+ mkdirSync(agentsDir, { recursive: true });
337
+ writeFileSync(plistPath, [
338
+ '<?xml version="1.0" encoding="UTF-8"?>',
339
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
340
+ '<plist version="1.0">',
341
+ "<dict>",
342
+ ` <key>Label</key><string>${xmlEscape(label)}</string>`,
343
+ ` <key>ProgramArguments</key><array><string>${xmlEscape(executable)}</string></array>`,
344
+ ` <key>WorkingDirectory</key><string>${xmlEscape(workingDirectory)}</string>`,
345
+ " <key>RunAtLoad</key><true/>",
346
+ " <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>",
347
+ ` <key>StandardOutPath</key><string>${xmlEscape(logPath)}</string>`,
348
+ ` <key>StandardErrorPath</key><string>${xmlEscape(logPath)}</string>`,
349
+ " <key>ProcessType</key><string>Background</string>",
350
+ "</dict>",
351
+ "</plist>",
352
+ "",
353
+ ].join("\n"));
354
+
355
+ // Booting out first: bootstrap refuses a label that is already loaded, and a reinstall is the common case.
356
+ run(unregister, true);
357
+ const started = run(["launchctl", "bootstrap", domain, plistPath], false);
358
+ return { kind: "launchd", unit: label, files: [plistPath], unregister, started };
359
+ }
360
+
361
+ /** systemd user units. `--user` rather than system units, for the same reason launchd gets a LaunchAgent. */
362
+ function registerSystemd(id, name, executable, workingDirectory, logPath) {
363
+ const unit = `${id}.service`;
364
+ const unitDir = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "systemd", "user");
365
+ const unitPath = join(unitDir, unit);
366
+ const unregister = ["systemctl", "--user", "disable", "--now", unit];
367
+
368
+ mkdirSync(unitDir, { recursive: true });
369
+ writeFileSync(unitPath, [
370
+ "[Unit]",
371
+ `Description=Jive daemon ${name} for ${PACKAGE_NAME}`,
372
+ "",
373
+ "[Service]",
374
+ "Type=simple",
375
+ `ExecStart=${executable}`,
376
+ `WorkingDirectory=${workingDirectory}`,
377
+ "Restart=on-failure",
378
+ "RestartSec=5",
379
+ "",
380
+ "[Install]",
381
+ "WantedBy=default.target",
382
+ "",
383
+ ].join("\n"));
384
+
385
+ run(["systemctl", "--user", "daemon-reload"], true);
386
+ const started = run(["systemctl", "--user", "enable", "--now", unit], false);
387
+ return { kind: "systemd", unit, files: [unitPath], unregister, started };
388
+ }
389
+
390
+ /**
391
+ * Windows Task Scheduler, through a .cmd shim.
392
+ *
393
+ * The shim exists because schtasks can set neither a working directory nor environment variables, and it
394
+ * also supplies the restart-on-crash behaviour the other two platforms get from their service manager: an
395
+ * ONLOGON task starts its program once and does not watch it. The loop mirrors launchd's KeepAlive, so a
396
+ * daemon that exits zero after removing itself is not restarted.
397
+ */
398
+ function registerScheduledTask(id, name, executable, workingDirectory, logPath) {
399
+ const taskName = id;
400
+ const shimPath = join(registryDir(), `${id}.cmd`);
401
+ const unregister = ["schtasks", "/Delete", "/F", "/TN", taskName];
402
+
403
+ writeFileSync(shimPath, [
404
+ "@echo off",
405
+ `cd /d "${workingDirectory}"`,
406
+ ":jive_loop",
407
+ `"${executable}" >> "${logPath}" 2>&1`,
408
+ "if %ERRORLEVEL% EQU 0 goto :eof",
409
+ "timeout /t 5 /nobreak > nul",
410
+ "goto jive_loop",
411
+ "",
412
+ ].join("\r\n"));
413
+
414
+ const started = run([
415
+ "schtasks", "/Create", "/F",
416
+ "/SC", "ONLOGON",
417
+ "/TN", taskName,
418
+ "/TR", `"${shimPath}"`,
419
+ "/RL", "LIMITED",
420
+ ], false);
421
+ return { kind: "scheduled-task", unit: taskName, files: [shimPath], unregister, started };
422
+ }
423
+
424
+ const DAEMON_REGISTRARS = {
425
+ darwin: registerLaunchd,
426
+ linux: registerSystemd,
427
+ win32: registerScheduledTask,
428
+ };
429
+
430
+ function readRecord(path) {
431
+ try {
432
+ return JSON.parse(readFileSync(path, "utf-8"));
433
+ } catch {
434
+ return undefined;
435
+ }
436
+ }
437
+
438
+ function removeRegistration(record, reason) {
439
+ console.log(`Removing daemon ${record.id} (${reason})`);
440
+ if (Array.isArray(record.unregister) && record.unregister.length > 0) {
441
+ run(record.unregister, true);
442
+ }
443
+ for (const file of record.files || []) {
444
+ rmSync(file, { force: true });
445
+ }
446
+ }
447
+
448
+ /**
449
+ * Drops this package's registrations that should no longer exist.
450
+ *
451
+ * Three cases, all of which would otherwise leave the operating system starting a missing or unwanted
452
+ * executable at every login: a daemon this version of the package no longer has, a copy of the package
453
+ * whose directory is gone, and a registration of this very copy under an id we no longer use — which is
454
+ * what makes a change to the id scheme replace its registrations instead of doubling them.
455
+ *
456
+ * Only this package's own registrations are considered, by name, so another package's daemon is never
457
+ * touched; and only this copy's, except where the copy itself has been deleted.
458
+ */
459
+ function pruneRemovedDaemons(currentIds) {
460
+ let entries;
461
+ try {
462
+ entries = readdirSync(registryDir());
463
+ } catch {
464
+ return;
465
+ }
466
+
467
+ for (const entry of entries) {
468
+ if (!entry.endsWith(".json")) continue;
469
+ const path = join(registryDir(), entry);
470
+ const record = readRecord(path);
471
+ if (!record || record.packageName !== PACKAGE_NAME) continue;
472
+
473
+ const reason =
474
+ !DAEMONS.includes(record.name) ? `no longer part of ${PACKAGE_NAME}`
475
+ : !existsSync(record.packageDir) ? `${record.packageDir} is gone`
476
+ : record.packageDir === packageDir && !currentIds.includes(record.id) ? "superseded by a new id"
477
+ : undefined;
478
+ if (reason === undefined) continue;
479
+
480
+ removeRegistration(record, reason);
481
+ rmSync(path, { force: true });
482
+ }
483
+ }
484
+
485
+ function registerDaemons() {
486
+ // Two reasons not to register. The caller asked for repair alone — the local deploy does, because its
487
+ // install exists so the launcher can resolve a platform package, not because anyone chose to install
488
+ // that copy. Or this is a build agent, which installs a package to run one command and is then
489
+ // discarded: registering something to start at a login that will never happen is pure noise, and in a
490
+ // container it fails outright.
491
+ const skip = IS_INSTALL_SCRIPT && process.argv.includes(REPAIR_ONLY_FLAG) ? `${REPAIR_ONLY_FLAG} was passed`
492
+ : process.env.CI ? "CI is set"
493
+ : undefined;
494
+ const names = skip === undefined ? DAEMONS : [];
495
+
496
+ // Pruning first, and with no current ids when skipping: declining to run daemons here has to also take
497
+ // away any this copy registered earlier, or one such install would leave them starting at every login
498
+ // forever. Before the early return below, too — a version that drops its last daemon still has to take
499
+ // the previous version's registration away, and the record carries everything undoing it needs.
500
+ pruneRemovedDaemons(names.map(daemonId));
501
+ if (skip !== undefined) {
502
+ if (DAEMONS.length > 0) console.log(`${skip} — not registering ${DAEMONS.join(", ")}`);
503
+ return;
504
+ }
505
+ if (names.length === 0) return;
506
+
507
+ const registrar = DAEMON_REGISTRARS[process.platform];
508
+ if (!registrar) {
509
+ console.log(`No daemon support for ${process.platform} — ${names.join(", ")} will not start automatically`);
510
+ return;
511
+ }
512
+
513
+ mkdirSync(registryDir(), { recursive: true });
514
+ mkdirSync(logDir(), { recursive: true });
515
+
516
+ for (const name of names) {
517
+ const id = daemonId(name);
518
+ const path = recordPath(id);
519
+ const previous = readRecord(path);
520
+ const workingDirectory = installRoot();
521
+ const executable = commandTargetPath(name);
522
+ const logPath = join(logDir(), `${id}.log`);
523
+
524
+ console.log(
525
+ `${previous ? "Replacing existing" : "Creating"} daemon ${id}`
526
+ + ` (${name} from ${PACKAGE_NAME}) in ${workingDirectory}`,
527
+ );
528
+
529
+ // The record goes down before the unit is loaded, because loading it starts the daemon, and the first
530
+ // thing the daemon does is read this file to find out how it was registered.
531
+ const pending = {
532
+ id,
533
+ name,
534
+ packageName: PACKAGE_NAME,
535
+ packageDir,
536
+ workingDirectory,
537
+ executable,
538
+ registeredAt: new Date().toISOString(),
539
+ files: [path],
540
+ unregister: previous && previous.unregister ? previous.unregister : [],
541
+ };
542
+ writeFileSync(path, `${JSON.stringify(pending, null, 2)}\n`);
543
+
544
+ const outcome = registrar(id, name, executable, workingDirectory, logPath);
545
+ // kind and unit are recorded for the sake of reading a daemon's status later: they are what a listing
546
+ // command has to ask the platform about, and only the installer knows which registrar ran.
547
+ writeFileSync(path, `${JSON.stringify({
548
+ ...pending,
549
+ kind: outcome.kind,
550
+ unit: outcome.unit,
551
+ logPath,
552
+ files: [...outcome.files, path],
553
+ unregister: outcome.unregister,
554
+ }, null, 2)}\n`);
555
+
556
+ if (!outcome.started) {
557
+ console.error(` ${id} is registered but could not be started; it will start at your next login`);
558
+ }
559
+ }
560
+ }
561
+
562
+ repairCommandTargets();
563
+ registerDaemons();
564
+ removeInstallScript();
565
+ if (!IS_INSTALL_SCRIPT) {
566
+ const commandName = basename(launcherPath);
567
+ runExecutable(commandTargetPath(commandName));
568
+ }