pinggy 0.6.7 → 0.6.9

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/dist/index.cjs CHANGED
@@ -237,6 +237,17 @@ function ensurePinggyLogDir() {
237
237
  function getTunnelLogDir() {
238
238
  return import_path2.default.join(getPinggyLogDir(), "tunnels");
239
239
  }
240
+ function getLibpinggyLogDir() {
241
+ return import_path2.default.join(getPinggyLogDir(), "libpinggy");
242
+ }
243
+ function ensureLibpinggyLogDir() {
244
+ const dir = getLibpinggyLogDir();
245
+ import_fs2.default.mkdirSync(dir, { recursive: true });
246
+ return dir;
247
+ }
248
+ function getLibpinggyLogPath() {
249
+ return import_path2.default.join(getLibpinggyLogDir(), "libpinggy.log");
250
+ }
240
251
  function getTunnelLogPath(tunnelId, origin, name) {
241
252
  const dir = getTunnelLogDir();
242
253
  if (name) {
@@ -556,6 +567,45 @@ var init_rotateLog = __esm({
556
567
  }
557
568
  });
558
569
 
570
+ // src/logger/nativeLog.ts
571
+ function sdkAddon() {
572
+ return import_pinggy2.Pinggy.addon;
573
+ }
574
+ function setNativeLogging(enabled, addon = sdkAddon()) {
575
+ if (!addon) {
576
+ if (!warned) {
577
+ warned = true;
578
+ logger.warn("libpinggy logging unavailable: the SDK does not expose its native addon");
579
+ }
580
+ return;
581
+ }
582
+ try {
583
+ if (enabled && !pathSet) {
584
+ ensureLibpinggyLogDir();
585
+ const logPath = getLibpinggyLogPath();
586
+ maybeRotate(logPath);
587
+ addon.setLogPath(logPath);
588
+ pathSet = true;
589
+ }
590
+ addon.setLogEnable(enabled);
591
+ } catch (err) {
592
+ logger.error("Failed to configure libpinggy logging", { error: err instanceof Error ? err.message : String(err) });
593
+ }
594
+ }
595
+ var import_pinggy2, pathSet, warned;
596
+ var init_nativeLog = __esm({
597
+ "src/logger/nativeLog.ts"() {
598
+ "use strict";
599
+ init_cjs_shims();
600
+ import_pinggy2 = require("@pinggy/pinggy");
601
+ init_logger();
602
+ init_configDir();
603
+ init_rotateLog();
604
+ pathSet = false;
605
+ warned = false;
606
+ }
607
+ });
608
+
559
609
  // src/types.ts
560
610
  function isErrorResponse(obj) {
561
611
  return typeof obj === "object" && obj !== null && "code" in obj && "message" in obj && typeof obj.message === "string" && Object.values(ErrorCode).includes(obj.code);
@@ -741,18 +791,19 @@ __export(TunnelManager_exports, {
741
791
  TunnelRebuildInProgressError: () => TunnelRebuildInProgressError
742
792
  });
743
793
  function mapToSdkLogLevel(level) {
744
- if (level === "debug") return import_pinggy2.LogLevel.DEBUG;
745
- if (level === "error") return import_pinggy2.LogLevel.ERROR;
746
- return import_pinggy2.LogLevel.INFO;
794
+ if (level === "debug") return import_pinggy3.LogLevel.DEBUG;
795
+ if (level === "error") return import_pinggy3.LogLevel.ERROR;
796
+ return import_pinggy3.LogLevel.INFO;
747
797
  }
748
- var import_pinggy2, import_node_path, import_node_worker_threads, import_node_url, __filename3, __dirname2, START_FAILED_MESSAGE, STATS_HISTORY_LIMIT, TunnelAlreadyRunningError, TunnelRebuildInProgressError, TunnelManager;
798
+ var import_pinggy3, import_node_path, import_node_worker_threads, import_node_url, __filename3, __dirname2, START_FAILED_MESSAGE, STATS_HISTORY_LIMIT, TunnelAlreadyRunningError, TunnelRebuildInProgressError, TunnelManager;
749
799
  var init_TunnelManager = __esm({
750
800
  "src/tunnel_manager/TunnelManager.ts"() {
751
801
  "use strict";
752
802
  init_cjs_shims();
753
- import_pinggy2 = require("@pinggy/pinggy");
803
+ import_pinggy3 = require("@pinggy/pinggy");
754
804
  init_logger();
755
805
  init_tunnelLogger();
806
+ init_nativeLog();
756
807
  init_rotateLog();
757
808
  init_types();
758
809
  import_node_path = __toESM(require("path"), 1);
@@ -852,14 +903,16 @@ var init_TunnelManager = __esm({
852
903
  const tunnelLogPath = getTunnelLogPath(params.tunnelid, params.origin, tunnelLogName);
853
904
  maybeRotate(tunnelLogPath);
854
905
  attachTunnelLogger(params.tunnelid, params.origin, tunnelLogName);
906
+ const loggingEnabled = isTunnelLoggingEnabled();
907
+ setNativeLogging(loggingEnabled);
855
908
  let instance;
856
909
  try {
857
910
  logger.debug("Creating tunnel instance with processed config", tunnelConfig);
858
- instance = await import_pinggy2.TunnelInstance.create(tunnelConfig, {
859
- enabled: true,
911
+ instance = await import_pinggy3.TunnelInstance.create(tunnelConfig, {
912
+ enabled: loggingEnabled,
860
913
  logLevel: mapToSdkLogLevel(getLogLevel()),
861
914
  logFilePath: tunnelLogPath,
862
- libpinggyLogPath: tunnelLogPath
915
+ libpinggyLogPath: null
863
916
  });
864
917
  } catch (e) {
865
918
  logger.error("Error creating tunnel instance:", e);
@@ -1052,17 +1105,17 @@ var init_TunnelManager = __esm({
1052
1105
  }
1053
1106
  }
1054
1107
  /**
1055
- * Re-apply the given log level to every live tunnel's worker JS logger.
1056
- * Native libpinggy level is fixed at worker init and cannot be re-pathed
1057
- * or re-levelled at runtime without restarting the tunnel.
1108
+ * Re-apply the given log level, and the tunnel-logging switch, to every live tunnel's worker
1109
+ * JS logger. libpinggy has no log level at runtime, only on or off (see nativeLog.ts).
1058
1110
  */
1059
1111
  applyLogLevelToActiveTunnels(level) {
1060
1112
  const sdkLevel = mapToSdkLogLevel(level);
1113
+ const loggingEnabled = isTunnelLoggingEnabled();
1061
1114
  for (const tunnel of this.tunnelsByTunnelId.values()) {
1062
1115
  if (tunnel.isStopped) continue;
1063
1116
  if (tunnel.lastError?.isFatal) continue;
1064
1117
  const logPath = getTunnelLogPath(tunnel.tunnelid, tunnel.origin, tunnel.tunnelName || tunnel.tunnelConfig?.name);
1065
- tunnel.instance.setDebugLogging(true, sdkLevel, logPath).catch((err) => {
1118
+ tunnel.instance.setDebugLogging(loggingEnabled, sdkLevel, logPath).catch((err) => {
1066
1119
  logger.error("Failed to apply log level to tunnel", { tunnelId: tunnel.tunnelid, error: err?.message ?? err });
1067
1120
  });
1068
1121
  }
@@ -2324,7 +2377,7 @@ function tunnelConfigToPinggyOptions(config) {
2324
2377
  const forwardingData = [];
2325
2378
  forwardingData.push({
2326
2379
  address: `${config.forwardedhost}:${config.localport}`,
2327
- type: config.type || import_pinggy3.TunnelType.Http
2380
+ type: config.type || import_pinggy4.TunnelType.Http
2328
2381
  // Default to HTTP for the primary forwarding entry
2329
2382
  });
2330
2383
  if (config.additionalForwarding && Array.isArray(config.additionalForwarding)) {
@@ -2334,7 +2387,7 @@ function tunnelConfigToPinggyOptions(config) {
2334
2387
  forwardingData.push({
2335
2388
  address: `${entry.localDomain}:${entry.localPort}`,
2336
2389
  listenAddress,
2337
- type: import_pinggy3.TunnelType.Http
2390
+ type: import_pinggy4.TunnelType.Http
2338
2391
  });
2339
2392
  }
2340
2393
  });
@@ -2372,7 +2425,7 @@ function pinggyOptionsToTunnelConfig(opts, configid, configName, localserverTls,
2372
2425
  const forwarding = primaryEntry ? String(primaryEntry.address) : String(opts.forwarding);
2373
2426
  const [parsedForwardedHost, portStr] = forwarding.split(":");
2374
2427
  const parsedLocalPort = parseInt(portStr, 10);
2375
- const tunnelType = primaryEntry?.type ?? import_pinggy3.TunnelType.Http;
2428
+ const tunnelType = primaryEntry?.type ?? import_pinggy4.TunnelType.Http;
2376
2429
  const additionalForwarding = additionalEntries.map((e) => {
2377
2430
  const [localDomain, localPortStr] = String(e.address).split(":");
2378
2431
  const [remoteDomain, remotePortStr] = String(e.listenAddress).split(":");
@@ -2420,12 +2473,12 @@ function pinggyOptionsToTunnelConfig(opts, configid, configName, localserverTls,
2420
2473
  serve: serve || ""
2421
2474
  };
2422
2475
  }
2423
- var import_pinggy3, import_zod, HeaderModificationSchema, AdditionalForwardingSchema, TunnelConfigSchema, StartSchema, StopSchema, GetSchema, RestartSchema, UpdateConfigSchema, ForwardingEntryV2Schema, OptionalSchema, TunnelConfigV1Schema, TUNNEL_CONFIG_V1_KEYS, StartV2Schema, UpdateConfigV2Schema;
2476
+ var import_pinggy4, import_zod, HeaderModificationSchema, AdditionalForwardingSchema, TunnelConfigSchema, StartSchema, StopSchema, GetSchema, RestartSchema, UpdateConfigSchema, ForwardingEntryV2Schema, OptionalSchema, TunnelConfigV1Schema, TUNNEL_CONFIG_V1_KEYS, StartV2Schema, UpdateConfigV2Schema;
2424
2477
  var init_remote_schema = __esm({
2425
2478
  "src/remote_management/remote_schema.ts"() {
2426
2479
  "use strict";
2427
2480
  init_cjs_shims();
2428
- import_pinggy3 = require("@pinggy/pinggy");
2481
+ import_pinggy4 = require("@pinggy/pinggy");
2429
2482
  import_zod = require("zod");
2430
2483
  init_util();
2431
2484
  HeaderModificationSchema = import_zod.z.object({
@@ -2468,11 +2521,11 @@ var init_remote_schema = __esm({
2468
2521
  token: import_zod.z.string(),
2469
2522
  tunnelTimeout: import_zod.z.number(),
2470
2523
  type: import_zod.z.enum([
2471
- import_pinggy3.TunnelType.Http,
2472
- import_pinggy3.TunnelType.Tcp,
2473
- import_pinggy3.TunnelType.Udp,
2474
- import_pinggy3.TunnelType.Tls,
2475
- import_pinggy3.TunnelType.TlsTcp
2524
+ import_pinggy4.TunnelType.Http,
2525
+ import_pinggy4.TunnelType.Tcp,
2526
+ import_pinggy4.TunnelType.Udp,
2527
+ import_pinggy4.TunnelType.Tls,
2528
+ import_pinggy4.TunnelType.TlsTcp
2476
2529
  ]),
2477
2530
  webdebuggerport: import_zod.z.number(),
2478
2531
  xff: import_zod.z.string(),
@@ -2506,7 +2559,7 @@ var init_remote_schema = __esm({
2506
2559
  ForwardingEntryV2Schema = import_zod.z.object({
2507
2560
  listenAddress: import_zod.z.string().optional(),
2508
2561
  address: import_zod.z.string(),
2509
- type: import_zod.z.enum([import_pinggy3.TunnelType.Http, import_pinggy3.TunnelType.Tcp, import_pinggy3.TunnelType.Udp, import_pinggy3.TunnelType.Tls, import_pinggy3.TunnelType.TlsTcp]).default(import_pinggy3.TunnelType.Http)
2562
+ type: import_zod.z.enum([import_pinggy4.TunnelType.Http, import_pinggy4.TunnelType.Tcp, import_pinggy4.TunnelType.Udp, import_pinggy4.TunnelType.Tls, import_pinggy4.TunnelType.TlsTcp]).default(import_pinggy4.TunnelType.Http)
2510
2563
  });
2511
2564
  OptionalSchema = import_zod.z.object({
2512
2565
  sniServerName: import_zod.z.string().optional(),
@@ -2550,7 +2603,7 @@ var init_remote_schema = __esm({
2550
2603
  httpsOnly: import_zod.z.boolean().optional(),
2551
2604
  originalRequestUrl: import_zod.z.boolean().optional(),
2552
2605
  allowPreflight: import_zod.z.boolean().optional(),
2553
- haProxy: import_zod.z.enum([import_pinggy3.HaProxyVersion.V1, import_pinggy3.HaProxyVersion.V2]).optional(),
2606
+ haProxy: import_zod.z.enum([import_pinggy4.HaProxyVersion.V1, import_pinggy4.HaProxyVersion.V2]).optional(),
2554
2607
  serve: import_zod.z.string().optional(),
2555
2608
  optional: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional()
2556
2609
  }).superRefine((config, ctx) => {
@@ -2559,11 +2612,11 @@ var init_remote_schema = __esm({
2559
2612
  }
2560
2613
  const entries = Array.isArray(config.forwarding) ? config.forwarding : [];
2561
2614
  const primaryType = entries.length > 0 ? entries[0].type : void 0;
2562
- if (primaryType !== import_pinggy3.TunnelType.Tcp) {
2615
+ if (primaryType !== import_pinggy4.TunnelType.Tcp) {
2563
2616
  ctx.addIssue({
2564
2617
  code: "custom",
2565
2618
  path: ["haProxy"],
2566
- message: `haProxy can only be used with "tcp" tunnels, but the first forwarding rule has type: ${primaryType ?? import_pinggy3.TunnelType.Http}`
2619
+ message: `haProxy can only be used with "tcp" tunnels, but the first forwarding rule has type: ${primaryType ?? import_pinggy4.TunnelType.Http}`
2567
2620
  });
2568
2621
  }
2569
2622
  });
@@ -3077,11 +3130,11 @@ var init_ipcClient = __esm({
3077
3130
  call(key, body, timeoutMs) {
3078
3131
  const spaceIdx = key.indexOf(" ");
3079
3132
  const method = key.slice(0, spaceIdx);
3080
- const path18 = key.slice(spaceIdx + 1);
3133
+ const path20 = key.slice(spaceIdx + 1);
3081
3134
  const payload = method === "GET" ? void 0 : JSON.stringify(body ?? {});
3082
- return this.request(method, path18, payload, timeoutMs);
3135
+ return this.request(method, path20, payload, timeoutMs);
3083
3136
  }
3084
- request(method, path18, body, timeoutMs) {
3137
+ request(method, path20, body, timeoutMs) {
3085
3138
  return new Promise((resolve, reject) => {
3086
3139
  const headers = {
3087
3140
  "X-Pinggy-Origin": this.origin
@@ -3094,7 +3147,7 @@ var init_ipcClient = __esm({
3094
3147
  {
3095
3148
  hostname: "127.0.0.1",
3096
3149
  port: this.port,
3097
- path: path18,
3150
+ path: path20,
3098
3151
  method,
3099
3152
  headers,
3100
3153
  timeout: timeoutMs ?? REQUEST_TIMEOUT_MS
@@ -3175,6 +3228,11 @@ function recordLatestVersion(version) {
3175
3228
  const changed = readUpdateState().latestVersion !== version;
3176
3229
  return writeUpdateState(changed ? { latestVersion: version, latestSeenEpochSeconds: nowEpochSeconds() } : { latestVersion: version });
3177
3230
  }
3231
+ function moveDeclinedInstallToVersion(execPath, newVersion) {
3232
+ if (readUpdateState().declinedInstallPath?.toLowerCase() === execPath.toLowerCase()) {
3233
+ writeUpdateState({ declinedInstallVersion: newVersion });
3234
+ }
3235
+ }
3178
3236
  var import_node_fs3, import_node_path2, NUMBER_FIELDS, STRING_FIELDS;
3179
3237
  var init_updateState = __esm({
3180
3238
  "src/update/updateState.ts"() {
@@ -3191,7 +3249,9 @@ var init_updateState = __esm({
3191
3249
  "latestSeenEpochSeconds",
3192
3250
  "lastCheckFailureNoticeEpochSeconds",
3193
3251
  "failedAttempts",
3194
- "deferredIpcVersion"
3252
+ "deferredIpcVersion",
3253
+ "cachedVersionSizeBytes",
3254
+ "cachedVersionModifiedMillis"
3195
3255
  ];
3196
3256
  STRING_FIELDS = [
3197
3257
  "latestVersion",
@@ -3201,7 +3261,11 @@ var init_updateState = __esm({
3201
3261
  "updatedFromVersion",
3202
3262
  "updatedToVersion",
3203
3263
  "failedVersion",
3204
- "deferredVersion"
3264
+ "deferredVersion",
3265
+ "declinedInstallPath",
3266
+ "declinedInstallVersion",
3267
+ "cachedVersionPath",
3268
+ "cachedVersion"
3205
3269
  ];
3206
3270
  }
3207
3271
  });
@@ -3404,7 +3468,7 @@ function createInstallProbe() {
3404
3468
  directoryIsWritable: () => canCreateFileNextTo(execPath)
3405
3469
  };
3406
3470
  }
3407
- var import_node_fs4, import_node_os, import_node_path3, InstallKind, NODE_MODULES_SEGMENT, WINDOWS_INSTALL_COMMAND, UNIX_INSTALL_COMMAND, NPM_INSTALL_COMMAND;
3471
+ var import_node_fs4, import_node_os, import_node_path3, InstallKind, NODE_MODULES_SEGMENT, WINDOWS_INSTALL_COMMAND, UNIX_INSTALL_COMMAND, NPM_INSTALL_COMMAND, NPM_UNINSTALL_COMMAND;
3408
3472
  var init_installKind = __esm({
3409
3473
  "src/update/installKind.ts"() {
3410
3474
  "use strict";
@@ -3426,6 +3490,7 @@ var init_installKind = __esm({
3426
3490
  WINDOWS_INSTALL_COMMAND = "irm https://pinggy.io/install.ps1 | iex";
3427
3491
  UNIX_INSTALL_COMMAND = "curl -fsSL https://pinggy.io/install.sh | sh";
3428
3492
  NPM_INSTALL_COMMAND = "npm i -g pinggy";
3493
+ NPM_UNINSTALL_COMMAND = "npm uninstall -g pinggy";
3429
3494
  }
3430
3495
  });
3431
3496
 
@@ -3465,18 +3530,33 @@ function isInstallerBinary(ctx) {
3465
3530
  return actual === expected;
3466
3531
  }
3467
3532
  function installerFix(platform3) {
3468
- const installCommand2 = platform3 === "win32" ? "irm https://pinggy.io/install.ps1 | iex" : "curl -fsSL https://pinggy.io/install.sh | sh";
3469
3533
  return [
3470
3534
  "pinggy can only run as a service when it is installed with the Pinggy installer.",
3471
3535
  "Install it, then run this command again:",
3472
- ` ${installCommand2}`,
3536
+ ` ${installCommandFor(platform3)}`,
3537
+ " pinggy daemon service-install"
3538
+ ].join("\n");
3539
+ }
3540
+ function npmInstallerFix(platform3) {
3541
+ return [
3542
+ "The npm version of pinggy cannot run as a service.",
3543
+ "Remove it, install pinggy with the Pinggy installer, then run this command again:",
3544
+ ` ${NPM_UNINSTALL_COMMAND}`,
3545
+ ` ${installCommandFor(platform3)}`,
3473
3546
  " pinggy daemon service-install"
3474
3547
  ].join("\n");
3475
3548
  }
3476
- function serviceInstallRefusal(ctx) {
3477
- if (!ctx.isPkg) return `The npm version of pinggy cannot run as a service.
3478
- ${installerFix(ctx.platform)}`;
3549
+ function installedCopyFix(installedPath) {
3550
+ return [
3551
+ "This pinggy is not the installed one. Run this command with the installed copy:",
3552
+ ` ${installedPath} daemon service-install`
3553
+ ].join("\n");
3554
+ }
3555
+ function serviceInstallRefusal(ctx, fileExists = import_node_fs5.default.existsSync) {
3556
+ if (!ctx.isPkg) return npmInstallerFix(ctx.platform);
3479
3557
  if (ctx.env[SERVICE_ANY_LOCATION_ENV] === "1" || isInstallerBinary(ctx)) return null;
3558
+ const installedPath = installerBinaryPath(ctx.platform, ctx.home, ctx.env);
3559
+ if (fileExists(installedPath)) return installedCopyFix(installedPath);
3480
3560
  return installerFix(ctx.platform);
3481
3561
  }
3482
3562
  function printInstalled() {
@@ -3835,6 +3915,67 @@ var init_serviceInstaller = __esm({
3835
3915
  }
3836
3916
  });
3837
3917
 
3918
+ // src/daemon/lifecycle/bootId.ts
3919
+ function readBootId(sources) {
3920
+ try {
3921
+ switch (sources.platform) {
3922
+ case "linux":
3923
+ return nonEmpty(sources.readFile(LINUX_BOOT_ID_PATH));
3924
+ case "darwin":
3925
+ return nonEmpty(sources.runCommand(MACOS_SYSCTL_PATH, ["-n", MACOS_BOOT_ID_KEY]));
3926
+ default:
3927
+ return null;
3928
+ }
3929
+ } catch {
3930
+ return null;
3931
+ }
3932
+ }
3933
+ function currentBootId() {
3934
+ if (cachedBootId === void 0) {
3935
+ cachedBootId = readBootId(machineBootIdSources);
3936
+ }
3937
+ return cachedBootId;
3938
+ }
3939
+ function startedInEarlierBoot(recordedBootId, startedAt, bootId = currentBootId()) {
3940
+ if (typeof recordedBootId === "string" && recordedBootId.length > 0 && bootId) {
3941
+ return recordedBootId !== bootId;
3942
+ }
3943
+ return startedBeforeBoot(startedAt);
3944
+ }
3945
+ function startedBeforeBoot(startedAt) {
3946
+ const startedAtMillis = Date.parse(startedAt);
3947
+ const bootMillis = Date.now() - import_node_os3.default.uptime() * 1e3;
3948
+ return Number.isNaN(startedAtMillis) || startedAtMillis < bootMillis - BOOT_TIME_TOLERANCE_MILLIS;
3949
+ }
3950
+ function nonEmpty(text) {
3951
+ const trimmed = text.trim();
3952
+ return trimmed.length > 0 ? trimmed : null;
3953
+ }
3954
+ var import_node_fs6, import_node_os3, import_node_child_process2, LINUX_BOOT_ID_PATH, MACOS_SYSCTL_PATH, MACOS_BOOT_ID_KEY, SYSCTL_TIMEOUT_MILLIS, BOOT_TIME_TOLERANCE_MILLIS, machineBootIdSources, cachedBootId;
3955
+ var init_bootId = __esm({
3956
+ "src/daemon/lifecycle/bootId.ts"() {
3957
+ "use strict";
3958
+ init_cjs_shims();
3959
+ import_node_fs6 = __toESM(require("fs"), 1);
3960
+ import_node_os3 = __toESM(require("os"), 1);
3961
+ import_node_child_process2 = require("child_process");
3962
+ LINUX_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id";
3963
+ MACOS_SYSCTL_PATH = "/usr/sbin/sysctl";
3964
+ MACOS_BOOT_ID_KEY = "kern.bootsessionuuid";
3965
+ SYSCTL_TIMEOUT_MILLIS = 2e3;
3966
+ BOOT_TIME_TOLERANCE_MILLIS = 6e4;
3967
+ machineBootIdSources = {
3968
+ platform: process.platform,
3969
+ readFile: (filePath) => import_node_fs6.default.readFileSync(filePath, "utf-8"),
3970
+ runCommand: (command, args) => (0, import_node_child_process2.execFileSync)(command, args, {
3971
+ encoding: "utf-8",
3972
+ stdio: ["ignore", "pipe", "ignore"],
3973
+ timeout: SYSCTL_TIMEOUT_MILLIS
3974
+ })
3975
+ };
3976
+ }
3977
+ });
3978
+
3838
3979
  // src/cli/options.ts
3839
3980
  var cliOptions;
3840
3981
  var init_options = __esm({
@@ -3961,6 +4102,7 @@ function printHelpMessage() {
3961
4102
  console.log(" pinggy attach <name|id> # Re-attach TUI to a running tunnel");
3962
4103
  console.log(" pinggy restart <name|id> # Restart a running tunnel (picks up latest log level)");
3963
4104
  console.log(" pinggy logs [-f] [<name|id>] # Show (or follow) tunnel or daemon logs");
4105
+ console.log(" pinggy logs [-f] libpinggy # Show (or follow) the native library log, shared by all tunnels");
3964
4106
  console.log(" pinggy log level [debug|info|error] # Get or set the log level");
3965
4107
  console.log(" pinggy log path [<name|id>] # Print log file path");
3966
4108
  console.log("\nBackground Mode:");
@@ -4012,7 +4154,7 @@ function shouldMergeReverseOrLocalFragment(current, next) {
4012
4154
  return false;
4013
4155
  }
4014
4156
  function preprocessWindowsArgs(args) {
4015
- if (os5.platform() !== "win32") {
4157
+ if (os6.platform() !== "win32") {
4016
4158
  return args;
4017
4159
  }
4018
4160
  ;
@@ -4049,13 +4191,13 @@ function parseCliArgs(options, overrideArgs) {
4049
4191
  hasAnyArgs
4050
4192
  };
4051
4193
  }
4052
- var import_util6, os5;
4194
+ var import_util6, os6;
4053
4195
  var init_parseArgs = __esm({
4054
4196
  "src/utils/parseArgs.ts"() {
4055
4197
  "use strict";
4056
4198
  init_cjs_shims();
4057
4199
  import_util6 = require("util");
4058
- os5 = __toESM(require("os"), 1);
4200
+ os6 = __toESM(require("os"), 1);
4059
4201
  }
4060
4202
  });
4061
4203
 
@@ -4217,7 +4359,7 @@ function assetNameFor(platform3, architecture) {
4217
4359
  }
4218
4360
  function realFreeBytes(directory) {
4219
4361
  try {
4220
- const stats = import_node_fs6.default.statfsSync(directory);
4362
+ const stats = import_node_fs7.default.statfsSync(directory);
4221
4363
  return Number(stats.bavail) * Number(stats.bsize);
4222
4364
  } catch {
4223
4365
  return null;
@@ -4299,7 +4441,7 @@ async function readExpectedHash(request2, releaseUrl, dependencies) {
4299
4441
  function writeFully(fileDescriptor, chunk) {
4300
4442
  let written = 0;
4301
4443
  while (written < chunk.length) {
4302
- written += import_node_fs6.default.writeSync(fileDescriptor, chunk, written);
4444
+ written += import_node_fs7.default.writeSync(fileDescriptor, chunk, written);
4303
4445
  }
4304
4446
  }
4305
4447
  function receiveBody(response2, fileDescriptor) {
@@ -4342,7 +4484,7 @@ function bodyFailure(error, running) {
4342
4484
  }
4343
4485
  async function receiveVerifiedFile(response2, request2, expectedHash, contentLength) {
4344
4486
  const { tempPath, runningVersion } = request2;
4345
- const fileDescriptor = import_node_fs6.default.openSync(tempPath, "w", EXECUTABLE_MODE2);
4487
+ const fileDescriptor = import_node_fs7.default.openSync(tempPath, "w", EXECUTABLE_MODE2);
4346
4488
  try {
4347
4489
  const body = await receiveBody(response2, fileDescriptor).catch((error) => {
4348
4490
  throw bodyFailure(error, runningVersion);
@@ -4353,10 +4495,10 @@ async function receiveVerifiedFile(response2, request2, expectedHash, contentLen
4353
4495
  if (body.sha256 !== expectedHash) {
4354
4496
  throw new UpdateError(UpdateErrorCode.Checksum, `The download failed its checksum. ${unchanged(runningVersion)}`);
4355
4497
  }
4356
- import_node_fs6.default.fsyncSync(fileDescriptor);
4357
- if (process.platform !== "win32") import_node_fs6.default.fchmodSync(fileDescriptor, EXECUTABLE_MODE2);
4498
+ import_node_fs7.default.fsyncSync(fileDescriptor);
4499
+ if (process.platform !== "win32") import_node_fs7.default.fchmodSync(fileDescriptor, EXECUTABLE_MODE2);
4358
4500
  } finally {
4359
- import_node_fs6.default.closeSync(fileDescriptor);
4501
+ import_node_fs7.default.closeSync(fileDescriptor);
4360
4502
  }
4361
4503
  }
4362
4504
  async function downloadAsset(request2, releaseUrl, expectedHash, dependencies) {
@@ -4390,7 +4532,7 @@ async function ensureBinaryRuns(request2, dependencies) {
4390
4532
  }
4391
4533
  }
4392
4534
  function removeQuietly(filePath) {
4393
- import_node_fs6.default.rmSync(filePath, { force: true });
4535
+ import_node_fs7.default.rmSync(filePath, { force: true });
4394
4536
  }
4395
4537
  async function downloadAndVerify(request2, dependencies = defaultDownloadDependencies) {
4396
4538
  const releaseUrl = `${getReleasesUrl()}/download/${request2.tag}`;
@@ -4403,14 +4545,14 @@ async function downloadAndVerify(request2, dependencies = defaultDownloadDepende
4403
4545
  throw error;
4404
4546
  }
4405
4547
  }
4406
- var import_node_crypto2, import_node_child_process2, import_node_fs6, import_node_path5, UpdateErrorCode, BAD_RELEASE_CODES, UpdateError, BINARY_RUN_TIMEOUT_MILLIS, DEVICE_TOKEN_ENV, VERSION_LINE, runPinggyBinary, ASSET_NAMES, MAX_REDIRECTS, IDLE_TIMEOUT_MILLIS, FREE_SPACE_MARGIN_BYTES, WINDOWS_FREE_SPACE_FACTOR, UNIX_FREE_SPACE_FACTOR, EXECUTABLE_MODE2, USER_AGENT2, SUMS_LINE, defaultDownloadDependencies;
4548
+ var import_node_crypto2, import_node_child_process3, import_node_fs7, import_node_path5, UpdateErrorCode, BAD_RELEASE_CODES, UpdateError, BINARY_RUN_TIMEOUT_MILLIS, DEVICE_TOKEN_ENV, VERSION_LINE, runPinggyBinary, ASSET_NAMES, MAX_REDIRECTS, IDLE_TIMEOUT_MILLIS, FREE_SPACE_MARGIN_BYTES, WINDOWS_FREE_SPACE_FACTOR, UNIX_FREE_SPACE_FACTOR, EXECUTABLE_MODE2, USER_AGENT2, SUMS_LINE, defaultDownloadDependencies;
4407
4549
  var init_binaryUpdater = __esm({
4408
4550
  "src/update/binaryUpdater.ts"() {
4409
4551
  "use strict";
4410
4552
  init_cjs_shims();
4411
4553
  import_node_crypto2 = __toESM(require("crypto"), 1);
4412
- import_node_child_process2 = require("child_process");
4413
- import_node_fs6 = __toESM(require("fs"), 1);
4554
+ import_node_child_process3 = require("child_process");
4555
+ import_node_fs7 = __toESM(require("fs"), 1);
4414
4556
  import_node_path5 = __toESM(require("path"), 1);
4415
4557
  init_latestRelease();
4416
4558
  init_util();
@@ -4444,7 +4586,7 @@ var init_binaryUpdater = __esm({
4444
4586
  DEVICE_TOKEN_ENV = "DEVICE_AGENT_TOKEN";
4445
4587
  VERSION_LINE = /^Pinggy CLI version: (\d+\.\d+\.\d+)\s*$/m;
4446
4588
  runPinggyBinary = (binaryPath, args) => new Promise((resolve, reject) => {
4447
- (0, import_node_child_process2.execFile)(binaryPath, args, pinggyBinaryRunOptions(), (error, stdout) => {
4589
+ (0, import_node_child_process3.execFile)(binaryPath, args, pinggyBinaryRunOptions(), (error, stdout) => {
4448
4590
  if (error) reject(error);
4449
4591
  else resolve(String(stdout));
4450
4592
  });
@@ -4603,12 +4745,12 @@ function removeStaleUpdateFiles(execPath = process.execPath, operations = realSt
4603
4745
  }
4604
4746
  }
4605
4747
  }
4606
- var import_node_fs7, import_node_path6, WINDOWS_PATH, BACKUP_MARKER, NEW_FILE_SUFFIX, OLD_FILE_SUFFIX, RETRYABLE_RENAME_CODES, RENAME_RETRY_INTERVAL_MILLIS, RENAME_RETRY_LIMIT_MILLIS, POST_SWAP_WAIT_MILLIS, INSTALL_COMMAND, realWindowsFileOperations, realStaleFileOperations;
4748
+ var import_node_fs8, import_node_path6, WINDOWS_PATH, BACKUP_MARKER, NEW_FILE_SUFFIX, OLD_FILE_SUFFIX, RETRYABLE_RENAME_CODES, RENAME_RETRY_INTERVAL_MILLIS, RENAME_RETRY_LIMIT_MILLIS, POST_SWAP_WAIT_MILLIS, INSTALL_COMMAND, realWindowsFileOperations, realStaleFileOperations;
4607
4749
  var init_windowsSwap = __esm({
4608
4750
  "src/update/windowsSwap.ts"() {
4609
4751
  "use strict";
4610
4752
  init_cjs_shims();
4611
- import_node_fs7 = __toESM(require("fs"), 1);
4753
+ import_node_fs8 = __toESM(require("fs"), 1);
4612
4754
  import_node_path6 = __toESM(require("path"), 1);
4613
4755
  init_daemonManager();
4614
4756
  init_binaryUpdater();
@@ -4623,9 +4765,9 @@ var init_windowsSwap = __esm({
4623
4765
  POST_SWAP_WAIT_MILLIS = 2e3;
4624
4766
  INSTALL_COMMAND = "irm https://pinggy.io/install.ps1 | iex";
4625
4767
  realWindowsFileOperations = {
4626
- exists: (filePath) => import_node_fs7.default.existsSync(filePath),
4627
- copyFile: (from, to) => import_node_fs7.default.copyFileSync(from, to),
4628
- rename: (from, to) => import_node_fs7.default.renameSync(from, to),
4768
+ exists: (filePath) => import_node_fs8.default.existsSync(filePath),
4769
+ copyFile: (from, to) => import_node_fs8.default.copyFileSync(from, to),
4770
+ rename: (from, to) => import_node_fs8.default.renameSync(from, to),
4629
4771
  // Synchronous, so no other JavaScript runs between the 2 renames of a swap.
4630
4772
  sleepMillis: (millis) => {
4631
4773
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, millis);
@@ -4633,8 +4775,8 @@ var init_windowsSwap = __esm({
4633
4775
  nowMillis: () => Date.now()
4634
4776
  };
4635
4777
  realStaleFileOperations = {
4636
- list: (directory) => import_node_fs7.default.readdirSync(directory),
4637
- remove: (filePath) => import_node_fs7.default.rmSync(filePath, { force: true }),
4778
+ list: (directory) => import_node_fs8.default.readdirSync(directory),
4779
+ remove: (filePath) => import_node_fs8.default.rmSync(filePath, { force: true }),
4638
4780
  isAlive: isProcessAlive
4639
4781
  };
4640
4782
  }
@@ -4657,7 +4799,7 @@ var init_updateMessages = __esm({
4657
4799
  // src/update/updateLock.ts
4658
4800
  function readLockPid(lockPath) {
4659
4801
  try {
4660
- const parsed = JSON.parse(import_node_fs8.default.readFileSync(lockPath, "utf-8"));
4802
+ const parsed = JSON.parse(import_node_fs9.default.readFileSync(lockPath, "utf-8"));
4661
4803
  return typeof parsed.pid === "number" && parsed.pid > 0 ? parsed.pid : null;
4662
4804
  } catch {
4663
4805
  return null;
@@ -4666,7 +4808,7 @@ function readLockPid(lockPath) {
4666
4808
  function lockState(lockPath) {
4667
4809
  let modifiedMillis;
4668
4810
  try {
4669
- modifiedMillis = import_node_fs8.default.statSync(lockPath).mtimeMs;
4811
+ modifiedMillis = import_node_fs9.default.statSync(lockPath).mtimeMs;
4670
4812
  } catch {
4671
4813
  return LockState.Absent;
4672
4814
  }
@@ -4679,9 +4821,9 @@ function lockContents() {
4679
4821
  }
4680
4822
  function createLock(lockPath) {
4681
4823
  try {
4682
- const fileDescriptor = import_node_fs8.default.openSync(lockPath, "wx");
4683
- import_node_fs8.default.writeSync(fileDescriptor, lockContents());
4684
- import_node_fs8.default.closeSync(fileDescriptor);
4824
+ const fileDescriptor = import_node_fs9.default.openSync(lockPath, "wx");
4825
+ import_node_fs9.default.writeSync(fileDescriptor, lockContents());
4826
+ import_node_fs9.default.closeSync(fileDescriptor);
4685
4827
  return true;
4686
4828
  } catch (error) {
4687
4829
  if (error.code === "EEXIST") return false;
@@ -4693,8 +4835,8 @@ function wait(millis) {
4693
4835
  }
4694
4836
  async function replaceStaleLock(lockPath) {
4695
4837
  const temporaryPath = `${lockPath}.${process.pid}`;
4696
- import_node_fs8.default.writeFileSync(temporaryPath, lockContents());
4697
- import_node_fs8.default.renameSync(temporaryPath, lockPath);
4838
+ import_node_fs9.default.writeFileSync(temporaryPath, lockContents());
4839
+ import_node_fs9.default.renameSync(temporaryPath, lockPath);
4698
4840
  await wait(REPLACEMENT_SETTLE_MILLIS);
4699
4841
  return readLockPid(lockPath) === process.pid;
4700
4842
  }
@@ -4718,14 +4860,14 @@ function isUpdateLockOurs() {
4718
4860
  return readLockPid(getUpdateLockPath()) === process.pid;
4719
4861
  }
4720
4862
  function releaseUpdateLock() {
4721
- if (isUpdateLockOurs()) import_node_fs8.default.rmSync(getUpdateLockPath(), { force: true });
4863
+ if (isUpdateLockOurs()) import_node_fs9.default.rmSync(getUpdateLockPath(), { force: true });
4722
4864
  }
4723
- var import_node_fs8, STALE_AFTER_MILLIS, REPLACEMENT_SETTLE_MILLIS, LockState;
4865
+ var import_node_fs9, STALE_AFTER_MILLIS, REPLACEMENT_SETTLE_MILLIS, LockState;
4724
4866
  var init_updateLock = __esm({
4725
4867
  "src/update/updateLock.ts"() {
4726
4868
  "use strict";
4727
4869
  init_cjs_shims();
4728
- import_node_fs8 = __toESM(require("fs"), 1);
4870
+ import_node_fs9 = __toESM(require("fs"), 1);
4729
4871
  init_daemonManager();
4730
4872
  init_configDir();
4731
4873
  STALE_AFTER_MILLIS = 30 * 60 * 1e3;
@@ -4753,8 +4895,11 @@ function isAutoUpdateOff(variables) {
4753
4895
  function isExplicitOrPrintOnly({ rawArgs, values, hasAnyArgs }) {
4754
4896
  return rawArgs[0] === UPDATE_SUBCOMMAND || !hasAnyArgs || Boolean(values.help) || Boolean(values.version);
4755
4897
  }
4898
+ function isUnderSudoOrInContainer(variables, fileExists) {
4899
+ return Boolean(variables[SUDO_UID_ENV]) || CONTAINER_MARKER_FILES.some(fileExists);
4900
+ }
4756
4901
  function isExcludedProcess(environment) {
4757
- return Boolean(environment.variables[SUDO_UID_ENV]) || CONTAINER_MARKER_FILES.some(environment.fileExists) || parseVersion(environment.runningVersion) === null || hasPathSegment(environment.scriptRealPath, NPX_SEGMENT);
4902
+ return isUnderSudoOrInContainer(environment.variables, environment.fileExists) || parseVersion(environment.runningVersion) === null || hasPathSegment(environment.scriptRealPath, NPX_SEGMENT);
4758
4903
  }
4759
4904
  function updatedNotice(state, running) {
4760
4905
  if (state.updatedToVersion !== running || !state.updatedFromVersion) return null;
@@ -4810,82 +4955,739 @@ function runGates(command, environment) {
4810
4955
  let detectedKind;
4811
4956
  const kind = () => detectedKind ?? (detectedKind = environment.detectKind());
4812
4957
  const state = environment.readState();
4813
- printPendingNotice(state, kind, environment);
4958
+ if (!command.installQuestionShown) printPendingNotice(state, kind, environment);
4814
4959
  const now = environment.nowEpochSeconds();
4815
4960
  if (!isDue(state.lastCheckEpochSeconds, CHECK_INTERVAL_SECONDS, now)) return;
4816
4961
  if (!isDue(state.lastAttemptEpochSeconds, ATTEMPT_INTERVAL_SECONDS, now)) return;
4817
4962
  if (kind() === InstallKind.DevCheckout || environment.isLockHeld()) return;
4818
4963
  if (environment.writeState({ lastAttemptEpochSeconds: now })) environment.spawnUpdater();
4819
4964
  }
4820
- function spawnUpdater(spawnProcess = import_node_child_process3.spawn) {
4821
- const child = spawnProcess(process.execPath, [process.argv[1], UPDATE_CHILD_FLAG], {
4822
- detached: true,
4823
- stdio: "ignore",
4824
- // On Windows a process holds its working directory open, so inheriting it would block deleting that folder.
4825
- cwd: import_node_os3.default.homedir(),
4826
- env: environmentWithoutDeviceToken(),
4827
- ...import_node_os3.default.platform() === "win32" ? { windowsHide: true } : {}
4828
- });
4829
- child.on("error", (error) => logger.debug("Could not start the updater", { error: errorMessage(error) }));
4830
- child.unref();
4965
+ function spawnUpdater(spawnProcess = import_node_child_process4.spawn) {
4966
+ const child = spawnProcess(process.execPath, [process.argv[1], UPDATE_CHILD_FLAG], {
4967
+ detached: true,
4968
+ stdio: "ignore",
4969
+ // On Windows a process holds its working directory open, so inheriting it would block deleting that folder.
4970
+ cwd: import_node_os4.default.homedir(),
4971
+ env: environmentWithoutDeviceToken(),
4972
+ ...import_node_os4.default.platform() === "win32" ? { windowsHide: true } : {}
4973
+ });
4974
+ child.on("error", (error) => logger.debug("Could not start the updater", { error: errorMessage(error) }));
4975
+ child.unref();
4976
+ }
4977
+ function realEnvironment() {
4978
+ const probe = createInstallProbe();
4979
+ return {
4980
+ variables: process.env,
4981
+ stdoutIsTerminal: process.stdout.isTTY === true,
4982
+ runningVersion: getVersion(),
4983
+ platform: probe.platform,
4984
+ scriptRealPath: probe.scriptRealPath,
4985
+ nowEpochSeconds,
4986
+ fileExists: (filePath) => import_node_fs10.default.existsSync(filePath),
4987
+ detectKind: () => backgroundInstallKind(detectInstallKind(probe), probe.execPath, probe.homeRealPath),
4988
+ readState: readUpdateState,
4989
+ writeState: writeUpdateState,
4990
+ isLockHeld: isUpdateLockHeld,
4991
+ liveDaemon: getDaemonInfo,
4992
+ print: (line) => printer_default.print(line),
4993
+ spawnUpdater: () => spawnUpdater()
4994
+ };
4995
+ }
4996
+ function startBackgroundUpdate(command, createEnvironment = realEnvironment) {
4997
+ try {
4998
+ runGates(command, createEnvironment());
4999
+ } catch (error) {
5000
+ logger.debug("Background update gate failed", { error: errorMessage(error) });
5001
+ }
5002
+ }
5003
+ var import_node_child_process4, import_node_fs10, import_node_os4, AUTO_UPDATE_ENV, OFF_VALUES, ON_VALUES, SUDO_UID_ENV, CONTAINER_MARKER_FILES, NPX_SEGMENT, UPDATE_SUBCOMMAND, UPDATE_CHILD_FLAG, SECONDS_PER_DAY, CHECK_INTERVAL_SECONDS, ATTEMPT_INTERVAL_SECONDS, COULD_NOT_UPDATE_AFTER_SECONDS, COULD_NOT_CHECK_AFTER_SECONDS;
5004
+ var init_backgroundUpdate = __esm({
5005
+ "src/update/backgroundUpdate.ts"() {
5006
+ "use strict";
5007
+ init_cjs_shims();
5008
+ import_node_child_process4 = require("child_process");
5009
+ import_node_fs10 = __toESM(require("fs"), 1);
5010
+ import_node_os4 = __toESM(require("os"), 1);
5011
+ init_daemonManager();
5012
+ init_logger();
5013
+ init_util();
5014
+ init_printer();
5015
+ init_binaryUpdater();
5016
+ init_installKind();
5017
+ init_latestRelease();
5018
+ init_updateMessages();
5019
+ init_updateLock();
5020
+ init_updateState();
5021
+ AUTO_UPDATE_ENV = "PINGGY_AUTO_UPDATE";
5022
+ OFF_VALUES = /* @__PURE__ */ new Set(["false", "0"]);
5023
+ ON_VALUES = /* @__PURE__ */ new Set(["true", "1"]);
5024
+ SUDO_UID_ENV = "SUDO_UID";
5025
+ CONTAINER_MARKER_FILES = ["/.dockerenv", "/run/.containerenv"];
5026
+ NPX_SEGMENT = "_npx";
5027
+ UPDATE_SUBCOMMAND = "update";
5028
+ UPDATE_CHILD_FLAG = "--_update-child";
5029
+ SECONDS_PER_DAY = 24 * 60 * 60;
5030
+ CHECK_INTERVAL_SECONDS = SECONDS_PER_DAY;
5031
+ ATTEMPT_INTERVAL_SECONDS = 60 * 60;
5032
+ COULD_NOT_UPDATE_AFTER_SECONDS = 7 * SECONDS_PER_DAY;
5033
+ COULD_NOT_CHECK_AFTER_SECONDS = 30 * SECONDS_PER_DAY;
5034
+ }
5035
+ });
5036
+
5037
+ // src/update/unixLinkSwap.ts
5038
+ function fsyncPath(target, flags) {
5039
+ const fileDescriptor = import_node_fs11.default.openSync(target, flags);
5040
+ try {
5041
+ import_node_fs11.default.fsyncSync(fileDescriptor);
5042
+ } finally {
5043
+ import_node_fs11.default.closeSync(fileDescriptor);
5044
+ }
5045
+ }
5046
+ function unixDownloadPath(layout) {
5047
+ return import_node_path7.default.posix.join(layout.versionsDirectory, `${DOWNLOAD_PREFIX}${process.pid}`);
5048
+ }
5049
+ function versionDirectory(layout, version) {
5050
+ return import_node_path7.default.posix.join(layout.versionsDirectory, version);
5051
+ }
5052
+ function versionBinaryPath(layout, version) {
5053
+ return import_node_path7.default.posix.join(versionDirectory(layout, version), BINARY_NAME);
5054
+ }
5055
+ function readLinkVersion(layout) {
5056
+ try {
5057
+ const version = import_node_path7.default.posix.basename(import_node_path7.default.posix.dirname(import_node_fs11.default.readlinkSync(layout.link)));
5058
+ return parseVersion(version) ? version : null;
5059
+ } catch {
5060
+ return null;
5061
+ }
5062
+ }
5063
+ function installedVersions(layout) {
5064
+ return import_node_fs11.default.readdirSync(layout.versionsDirectory).filter((name) => parseVersion(name) !== null);
5065
+ }
5066
+ function highestVersionBelow(layout, ceiling) {
5067
+ const lower = installedVersions(layout).filter((version) => isNewerVersion(ceiling, version));
5068
+ return lower.reduce((best, version) => best === null || isNewerVersion(version, best) ? version : best, null);
5069
+ }
5070
+ function moveLink(layout, version, environment) {
5071
+ import_node_fs11.default.mkdirSync(layout.binDirectory, { recursive: true });
5072
+ const temporaryLink = import_node_path7.default.posix.join(layout.binDirectory, `${LINK_TEMP_PREFIX}${process.pid}`);
5073
+ import_node_fs11.default.rmSync(temporaryLink, { force: true });
5074
+ import_node_fs11.default.symlinkSync(versionBinaryPath(layout, version), temporaryLink);
5075
+ import_node_fs11.default.renameSync(temporaryLink, layout.link);
5076
+ environment.fsyncDirectory(layout.binDirectory);
5077
+ }
5078
+ function convertPlainFile(layout, execPath, runningVersion, environment) {
5079
+ const temporaryPath = import_node_path7.default.posix.join(layout.versionsDirectory, `${CONVERT_PREFIX}${process.pid}`);
5080
+ import_node_fs11.default.copyFileSync(execPath, temporaryPath);
5081
+ import_node_fs11.default.chmodSync(temporaryPath, EXECUTABLE_MODE3);
5082
+ environment.fsyncFile(temporaryPath);
5083
+ import_node_fs11.default.mkdirSync(versionDirectory(layout, runningVersion), { recursive: true });
5084
+ import_node_fs11.default.renameSync(temporaryPath, versionBinaryPath(layout, runningVersion));
5085
+ environment.fsyncDirectory(versionDirectory(layout, runningVersion));
5086
+ }
5087
+ function isNamedByService(layout, version, environment) {
5088
+ return environment.serviceEntryText().includes(versionBinaryPath(layout, version));
5089
+ }
5090
+ function removeDeadProcessTemp(directory, prefix, environment) {
5091
+ for (const name of import_node_fs11.default.readdirSync(directory)) {
5092
+ const pidText = name.startsWith(prefix) ? name.slice(prefix.length) : "";
5093
+ if (/^\d+$/.test(pidText) && !environment.isAlive(Number(pidText))) {
5094
+ import_node_fs11.default.rmSync(import_node_path7.default.posix.join(directory, name), { force: true });
5095
+ }
5096
+ }
5097
+ }
5098
+ function removeStaleUnixFiles(layout, environment = realUnixSwapEnvironment) {
5099
+ const locations = [
5100
+ [layout.versionsDirectory, DOWNLOAD_PREFIX],
5101
+ [layout.versionsDirectory, CONVERT_PREFIX],
5102
+ [layout.binDirectory, LINK_TEMP_PREFIX]
5103
+ ];
5104
+ for (const [directory, prefix] of locations) {
5105
+ try {
5106
+ removeDeadProcessTemp(directory, prefix, environment);
5107
+ } catch {
5108
+ }
5109
+ }
5110
+ }
5111
+ function pruneVersions(layout, environment = realUnixSwapEnvironment) {
5112
+ removeStaleUnixFiles(layout, environment);
5113
+ const target = readLinkVersion(layout);
5114
+ if (target === null) return;
5115
+ const keep = /* @__PURE__ */ new Set([target, highestVersionBelow(layout, target), environment.daemonVersion()]);
5116
+ for (const version of installedVersions(layout)) {
5117
+ if (keep.has(version) || isNamedByService(layout, version, environment)) continue;
5118
+ import_node_fs11.default.rmSync(versionDirectory(layout, version), { recursive: true, force: true });
5119
+ }
5120
+ }
5121
+ function replaceFailure(layout, error, running) {
5122
+ return new UpdateError(
5123
+ UpdateErrorCode.RenameFailed,
5124
+ `Could not replace ${layout.link}: ${errorMessage(error)}. pinggy ${running} is unchanged.`
5125
+ );
5126
+ }
5127
+ function installVersion(request2, environment = realUnixSwapEnvironment) {
5128
+ const { layout, plainFileToConvert, runningVersion, newVersion } = request2;
5129
+ try {
5130
+ import_node_fs11.default.mkdirSync(layout.versionsDirectory, { recursive: true });
5131
+ if (plainFileToConvert !== null) convertPlainFile(layout, plainFileToConvert, runningVersion, environment);
5132
+ import_node_fs11.default.mkdirSync(versionDirectory(layout, newVersion), { recursive: true });
5133
+ import_node_fs11.default.renameSync(unixDownloadPath(layout), versionBinaryPath(layout, newVersion));
5134
+ environment.fsyncDirectory(versionDirectory(layout, newVersion));
5135
+ moveLink(layout, newVersion, environment);
5136
+ } catch (error) {
5137
+ throw replaceFailure(layout, error, runningVersion);
5138
+ }
5139
+ try {
5140
+ pruneVersions(layout, environment);
5141
+ } catch {
5142
+ }
5143
+ }
5144
+ function nothingToRollBack2() {
5145
+ return new UpdateError(UpdateErrorCode.NothingToRollBack, "No previous version to go back to.");
5146
+ }
5147
+ function previousVersion(layout, current) {
5148
+ try {
5149
+ const version = highestVersionBelow(layout, current);
5150
+ if (version !== null) return version;
5151
+ } catch {
5152
+ }
5153
+ throw nothingToRollBack2();
5154
+ }
5155
+ function rollbackUnixVersion(layout, environment = realUnixSwapEnvironment) {
5156
+ const current = readLinkVersion(layout);
5157
+ if (current === null) throw nothingToRollBack2();
5158
+ const previous = previousVersion(layout, current);
5159
+ try {
5160
+ moveLink(layout, previous, environment);
5161
+ } catch (error) {
5162
+ throw replaceFailure(layout, error, current);
5163
+ }
5164
+ writeUpdateState({ rolledBackFromVersion: current });
5165
+ if (environment.daemonVersion() !== current && !isNamedByService(layout, current, environment)) {
5166
+ import_node_fs11.default.rmSync(versionDirectory(layout, current), { recursive: true, force: true });
5167
+ }
5168
+ return { from: current, to: previous };
5169
+ }
5170
+ var import_node_fs11, import_node_path7, BINARY_NAME, DOWNLOAD_PREFIX, CONVERT_PREFIX, LINK_TEMP_PREFIX, EXECUTABLE_MODE3, realUnixSwapEnvironment;
5171
+ var init_unixLinkSwap = __esm({
5172
+ "src/update/unixLinkSwap.ts"() {
5173
+ "use strict";
5174
+ init_cjs_shims();
5175
+ import_node_fs11 = __toESM(require("fs"), 1);
5176
+ import_node_path7 = __toESM(require("path"), 1);
5177
+ init_daemonManager();
5178
+ init_serviceInstaller();
5179
+ init_binaryUpdater();
5180
+ init_latestRelease();
5181
+ init_updateState();
5182
+ init_util();
5183
+ BINARY_NAME = "pinggy";
5184
+ DOWNLOAD_PREFIX = "pinggy.download.";
5185
+ CONVERT_PREFIX = "pinggy.convert.";
5186
+ LINK_TEMP_PREFIX = "pinggy.link.";
5187
+ EXECUTABLE_MODE3 = 493;
5188
+ realUnixSwapEnvironment = {
5189
+ fsyncFile: (filePath) => fsyncPath(filePath, "r+"),
5190
+ fsyncDirectory: (directory) => fsyncPath(directory, "r"),
5191
+ daemonVersion: () => getDaemonInfo()?.cliVersion,
5192
+ serviceEntryText: readServiceEntryText,
5193
+ isAlive: isProcessAlive
5194
+ };
5195
+ }
5196
+ });
5197
+
5198
+ // src/install/pinggyOnPath.ts
5199
+ function pathModule(platform3) {
5200
+ return platform3 === "win32" ? import_node_path8.default.win32 : import_node_path8.default.posix;
5201
+ }
5202
+ function pathFolders(platform3, pathValue) {
5203
+ const separator = platform3 === "win32" ? ";" : ":";
5204
+ return pathValue.split(separator).filter((folder) => folder !== "" && folder !== CURRENT_FOLDER);
5205
+ }
5206
+ function windowsCommandNames(name, pathExtensions) {
5207
+ const extensions = (pathExtensions || DEFAULT_PATH_EXTENSIONS).split(";").filter(Boolean);
5208
+ return [...extensions, POWERSHELL_SCRIPT_EXTENSION].map((extension) => `${name}${extension.toLowerCase()}`);
5209
+ }
5210
+ function findOnPath(names, lookup) {
5211
+ const paths = pathModule(lookup.platform);
5212
+ for (const folder of pathFolders(lookup.platform, lookup.pathValue)) {
5213
+ for (const name of names) {
5214
+ const candidate = paths.join(folder, name);
5215
+ if (lookup.files.isExecutableFile(candidate)) return candidate;
5216
+ }
5217
+ }
5218
+ return null;
5219
+ }
5220
+ function npmCopyFor(commandPath, lookup) {
5221
+ if (lookup.platform === "win32") {
5222
+ const folder = import_node_path8.default.win32.dirname(commandPath);
5223
+ const packageFolder = import_node_path8.default.win32.join(folder, "node_modules", NPM_PACKAGE);
5224
+ const isPackage = lookup.files.isFile(import_node_path8.default.win32.join(packageFolder, "package.json"));
5225
+ return isPackage && !lookup.files.isLink(packageFolder) ? { prefix: folder, packageFolder } : null;
5226
+ }
5227
+ const realPath2 = lookup.files.realPath(commandPath);
5228
+ const segmentStart = realPath2?.indexOf(UNIX_NPM_SEGMENT) ?? -1;
5229
+ if (realPath2 === null || segmentStart < 0) return null;
5230
+ const prefix = realPath2.slice(0, segmentStart);
5231
+ return { prefix, packageFolder: import_node_path8.default.posix.join(prefix, "lib", "node_modules", NPM_PACKAGE) };
5232
+ }
5233
+ function findPinggyCommand(lookup) {
5234
+ const names = lookup.platform === "win32" ? windowsCommandNames(NPM_PACKAGE, lookup.pathExtensions) : [NPM_PACKAGE];
5235
+ const commandPath = findOnPath(names, lookup);
5236
+ if (commandPath === null) return null;
5237
+ return { commandPath, npm: npmCopyFor(commandPath, lookup) };
5238
+ }
5239
+ function isFile(filePath) {
5240
+ try {
5241
+ return import_node_fs12.default.statSync(filePath).isFile();
5242
+ } catch {
5243
+ return false;
5244
+ }
5245
+ }
5246
+ function realPathFileSystem(platform3) {
5247
+ return {
5248
+ isExecutableFile: (filePath) => {
5249
+ if (!isFile(filePath)) return false;
5250
+ if (platform3 === "win32") return true;
5251
+ try {
5252
+ import_node_fs12.default.accessSync(filePath, import_node_fs12.default.constants.X_OK);
5253
+ return true;
5254
+ } catch {
5255
+ return false;
5256
+ }
5257
+ },
5258
+ isFile,
5259
+ realPath: (filePath) => {
5260
+ try {
5261
+ return import_node_fs12.default.realpathSync(filePath);
5262
+ } catch {
5263
+ return null;
5264
+ }
5265
+ },
5266
+ isLink: (filePath) => {
5267
+ try {
5268
+ return import_node_fs12.default.lstatSync(filePath).isSymbolicLink();
5269
+ } catch {
5270
+ return false;
5271
+ }
5272
+ }
5273
+ };
5274
+ }
5275
+ function processPathLookup() {
5276
+ return {
5277
+ platform: process.platform,
5278
+ pathValue: process.env.PATH ?? process.env.Path ?? "",
5279
+ pathExtensions: process.env.PATHEXT,
5280
+ files: realPathFileSystem(process.platform)
5281
+ };
5282
+ }
5283
+ var import_node_fs12, import_node_path8, NPM_PACKAGE, UNIX_NPM_SEGMENT, DEFAULT_PATH_EXTENSIONS, POWERSHELL_SCRIPT_EXTENSION, CURRENT_FOLDER;
5284
+ var init_pinggyOnPath = __esm({
5285
+ "src/install/pinggyOnPath.ts"() {
5286
+ "use strict";
5287
+ init_cjs_shims();
5288
+ import_node_fs12 = __toESM(require("fs"), 1);
5289
+ import_node_path8 = __toESM(require("path"), 1);
5290
+ NPM_PACKAGE = "pinggy";
5291
+ UNIX_NPM_SEGMENT = `/lib/node_modules/${NPM_PACKAGE}/`;
5292
+ DEFAULT_PATH_EXTENSIONS = ".COM;.EXE;.BAT;.CMD";
5293
+ POWERSHELL_SCRIPT_EXTENSION = ".ps1";
5294
+ CURRENT_FOLDER = ".";
5295
+ }
5296
+ });
5297
+
5298
+ // src/install/selfInstall.ts
5299
+ function installPathFor(environment, home) {
5300
+ return installerBinaryPath(environment.platform, home, environment.variables);
5301
+ }
5302
+ function shown(filePath, environment, home) {
5303
+ if (environment.platform === "win32") return filePath;
5304
+ return filePath === home || filePath.startsWith(`${home}/`) ? `~${filePath.slice(home.length)}` : filePath;
5305
+ }
5306
+ function samePath(first, second, platform3) {
5307
+ return platform3 === "win32" ? first.toLowerCase() === second.toLowerCase() : first === second;
5308
+ }
5309
+ function wasDeclined(environment) {
5310
+ const state = environment.readState();
5311
+ return state.declinedInstallVersion === environment.runningVersion && state.declinedInstallPath !== void 0 && samePath(state.declinedInstallPath, environment.execPath, environment.platform);
5312
+ }
5313
+ function isPrintOnlyOrUpdate({ rawArgs, values }) {
5314
+ return rawArgs[0] === UPDATE_SUBCOMMAND2 || Boolean(values.help) || Boolean(values.version);
5315
+ }
5316
+ function passesGates(command, environment) {
5317
+ if (!environment.isPackaged || isPrintOnlyOrUpdate(command)) return false;
5318
+ if (!environment.stdinIsTerminal || !environment.stdoutIsTerminal) return false;
5319
+ if (isUnderSudoOrInContainer(environment.variables, environment.fileExists)) return false;
5320
+ if (parseVersion(environment.runningVersion) === null || environment.home === null) return false;
5321
+ if (environment.isInstalledCopy() || wasDeclined(environment)) return false;
5322
+ return !environment.isLockHeld();
5323
+ }
5324
+ async function decideOffer(environment, home) {
5325
+ const command = environment.findPinggyCommand();
5326
+ if (command?.npm) return { kind: "npm", npm: command.npm, npmVersion: environment.npmVersion(command.npm) };
5327
+ const installed = await environment.installedBinary(installPathFor(environment, home));
5328
+ return installed ? { kind: "replace", installedVersion: installed.version } : { kind: "install" };
5329
+ }
5330
+ function questionFor(offer, environment, home) {
5331
+ const running = environment.runningVersion;
5332
+ const installPath = shown(installPathFor(environment, home), environment, home);
5333
+ switch (offer.kind) {
5334
+ case "npm": {
5335
+ const npmCopy = offer.npmVersion ? `pinggy ${offer.npmVersion}` : "pinggy";
5336
+ return `${npmCopy} is installed with npm. Remove it, and install this pinggy, ${running}, to ${installPath}? [Y/n] `;
5337
+ }
5338
+ case "replace":
5339
+ if (offer.installedVersion === null) {
5340
+ return `${installPath} does not run. Replace it with this pinggy, ${running}? [Y/n] `;
5341
+ }
5342
+ return `pinggy ${offer.installedVersion} is installed in ${installPath}. Replace it with this pinggy, ${running}? [Y/n] `;
5343
+ case "install":
5344
+ return `Install this pinggy, ${running}, to ${installPath}? [Y/n] `;
5345
+ }
5346
+ }
5347
+ function rememberDecline(environment) {
5348
+ environment.writeState({ declinedInstallPath: environment.execPath, declinedInstallVersion: environment.runningVersion });
5349
+ }
5350
+ function npmUninstallCommand(npm) {
5351
+ return `npm uninstall -g --prefix ${npm.prefix} ${NPM_PACKAGE2}`;
5352
+ }
5353
+ function printNpmRemoval(result, npm, environment) {
5354
+ switch (result) {
5355
+ case NpmRemoval.Removed:
5356
+ environment.print("Removed npm's pinggy.");
5357
+ environment.print("Open a new terminal to use the installed pinggy.");
5358
+ return;
5359
+ case NpmRemoval.NotWritable:
5360
+ environment.print(`This user cannot change ${npm.prefix}. To remove npm's pinggy, run: sudo ${npmUninstallCommand(npm)}`);
5361
+ return;
5362
+ case NpmRemoval.NoNpm:
5363
+ environment.print(`npm is not on PATH. To remove npm's pinggy, run: ${npmUninstallCommand(npm)}`);
5364
+ return;
5365
+ case NpmRemoval.Failed:
5366
+ environment.print("Could not remove npm's pinggy. If pinggy is running, run: pinggy daemon stop");
5367
+ environment.print(`Then run: ${npmUninstallCommand(npm)}`);
5368
+ return;
5369
+ }
5370
+ }
5371
+ function warnIfShadowed(environment, home) {
5372
+ const found = environment.findPinggyCommand();
5373
+ if (found === null) return;
5374
+ let expectedFolder;
5375
+ if (environment.platform === "win32") {
5376
+ expectedFolder = import_node_path9.default.win32.dirname(installPathFor(environment, home));
5377
+ if (samePath(import_node_path9.default.win32.dirname(found.commandPath), expectedFolder, "win32")) return;
5378
+ } else {
5379
+ expectedFolder = import_node_path9.default.posix.join(home, LINK_DIRECTORY);
5380
+ const folders = pathFolders(environment.platform, environment.variables.PATH ?? "").map((folder2) => import_node_path9.default.posix.normalize(`${folder2}/`));
5381
+ if (!folders.includes(`${expectedFolder}/`)) return;
5382
+ if (found.commandPath === import_node_path9.default.posix.join(expectedFolder, NPM_PACKAGE2)) return;
5383
+ }
5384
+ const folder = shown(expectedFolder, environment, home);
5385
+ environment.print(`Another pinggy, ${shown(found.commandPath, environment, home)}, comes before ${folder} on PATH, so the pinggy command runs it.`);
5386
+ environment.print(`Remove it, or move ${folder} earlier in PATH.`);
5387
+ }
5388
+ async function installAfterYes(offer, environment, home) {
5389
+ if (!await environment.acquireLock()) {
5390
+ environment.print("Another pinggy is installing or updating. Skipped the install.");
5391
+ return;
5392
+ }
5393
+ try {
5394
+ if (!await environment.runInstaller()) {
5395
+ environment.print(`Could not install pinggy. To install it later, run: ${installCommandFor(environment.platform)}`);
5396
+ rememberDecline(environment);
5397
+ return;
5398
+ }
5399
+ environment.useInstalledBinaryForDaemon(installPathFor(environment, home));
5400
+ if (offer.kind === "npm") printNpmRemoval(await environment.removeNpmCopy(offer.npm), offer.npm, environment);
5401
+ warnIfShadowed(environment, home);
5402
+ } finally {
5403
+ environment.releaseLock();
5404
+ }
5405
+ }
5406
+ async function offerSelfInstall(command, createEnvironment = realEnvironment2) {
5407
+ let questionShown = false;
5408
+ try {
5409
+ const environment = createEnvironment();
5410
+ if (!passesGates(command, environment) || environment.home === null) return { questionShown };
5411
+ const home = environment.home;
5412
+ const offer = await decideOffer(environment, home);
5413
+ if (!environment.writeState({})) return { questionShown };
5414
+ questionShown = true;
5415
+ const answer = await environment.ask(questionFor(offer, environment, home));
5416
+ if (answer === SelfInstallAnswer.No) rememberDecline(environment);
5417
+ if (answer === SelfInstallAnswer.Yes) await installAfterYes(offer, environment, home);
5418
+ } catch (error) {
5419
+ logger.debug("Self-install check failed", { error: errorMessage(error) });
5420
+ }
5421
+ return { questionShown };
5422
+ }
5423
+ function existingFolder(folder) {
5424
+ if (!folder) return null;
5425
+ try {
5426
+ return import_node_fs13.default.statSync(folder).isDirectory() ? folder : null;
5427
+ } catch {
5428
+ return null;
5429
+ }
5430
+ }
5431
+ function installHome(platform3, variables) {
5432
+ if (platform3 === "win32") return existingFolder(variables.LOCALAPPDATA) ? import_node_os5.default.homedir() : null;
5433
+ return existingFolder(variables.HOME);
5434
+ }
5435
+ function isInstalledCopy(platform3, execPath, home, variables) {
5436
+ if (platform3 === "win32") {
5437
+ if (home === null) return false;
5438
+ const installFolder = import_node_path9.default.win32.dirname(installerBinaryPath(platform3, home, variables));
5439
+ return samePath(import_node_path9.default.win32.dirname(execPath), installFolder, platform3);
5440
+ }
5441
+ const kind = detectInstallKind(createInstallProbe());
5442
+ return kind === InstallKind.UnixLayout || kind === InstallKind.UnixPlainFile;
5443
+ }
5444
+ async function cachedBinaryVersion(binaryPath) {
5445
+ const stats = import_node_fs13.default.statSync(binaryPath);
5446
+ const state = readUpdateState();
5447
+ if (state.cachedVersionPath === binaryPath && state.cachedVersionSizeBytes === stats.size && state.cachedVersionModifiedMillis === stats.mtimeMs) {
5448
+ return state.cachedVersion || null;
5449
+ }
5450
+ let version = null;
5451
+ try {
5452
+ version = await readBinaryVersion(binaryPath, runForVersion);
5453
+ } catch (error) {
5454
+ logger.debug("The installed pinggy printed no version", { binaryPath, error: errorMessage(error) });
5455
+ }
5456
+ writeUpdateState({
5457
+ cachedVersionPath: binaryPath,
5458
+ cachedVersionSizeBytes: stats.size,
5459
+ cachedVersionModifiedMillis: stats.mtimeMs,
5460
+ cachedVersion: version ?? ""
5461
+ });
5462
+ return version;
5463
+ }
5464
+ async function realInstalledBinary(platform3, home, installPath) {
5465
+ if (platform3 !== "win32") {
5466
+ let isLink;
5467
+ try {
5468
+ isLink = import_node_fs13.default.lstatSync(installPath).isSymbolicLink();
5469
+ } catch {
5470
+ return null;
5471
+ }
5472
+ if (!import_node_fs13.default.existsSync(installPath)) return { path: installPath, version: null };
5473
+ const linkVersion = isLink ? readLinkVersion(unixLayoutPaths(home)) : null;
5474
+ if (linkVersion) return { path: installPath, version: linkVersion };
5475
+ } else if (!import_node_fs13.default.existsSync(installPath)) {
5476
+ return null;
5477
+ }
5478
+ return { path: installPath, version: await cachedBinaryVersion(installPath) };
5479
+ }
5480
+ function readNpmVersion(npm) {
5481
+ try {
5482
+ const parsed = JSON.parse(import_node_fs13.default.readFileSync(import_node_path9.default.join(npm.packageFolder, "package.json"), "utf-8"));
5483
+ return typeof parsed.version === "string" && parseVersion(parsed.version) ? parsed.version : null;
5484
+ } catch {
5485
+ return null;
5486
+ }
5487
+ }
5488
+ function askOnTerminal(question) {
5489
+ return new Promise((resolve) => {
5490
+ const readline = (0, import_node_readline.createInterface)({ input: process.stdin, output: process.stdout, terminal: true });
5491
+ let settled = false;
5492
+ const finish = (answer) => {
5493
+ if (settled) return;
5494
+ settled = true;
5495
+ readline.close();
5496
+ process.stdin.pause();
5497
+ resolve(answer);
5498
+ };
5499
+ readline.on("SIGINT", () => {
5500
+ readline.close();
5501
+ process.stdout.write("\n");
5502
+ process.exit(INTERRUPTED_EXIT_CODE);
5503
+ });
5504
+ readline.on("close", () => {
5505
+ if (!settled) process.stdout.write("\n");
5506
+ finish(SelfInstallAnswer.Closed);
5507
+ });
5508
+ readline.question(question, (text) => finish(NO_ANSWER.test(text) ? SelfInstallAnswer.No : SelfInstallAnswer.Yes));
5509
+ });
5510
+ }
5511
+ function waitForEnterToClose() {
5512
+ return new Promise((resolve) => {
5513
+ const readline = (0, import_node_readline.createInterface)({ input: process.stdin, output: process.stdout, terminal: true });
5514
+ readline.on("close", () => resolve());
5515
+ readline.on("SIGINT", () => readline.close());
5516
+ readline.question("Press Enter to close.", () => readline.close());
5517
+ });
5518
+ }
5519
+ function waitForExit(command, args, options) {
5520
+ return new Promise((resolve) => {
5521
+ const child = (0, import_node_child_process5.spawn)(command, args, options);
5522
+ child.on("error", (error) => {
5523
+ logger.debug("Could not start a process", { command, error: errorMessage(error) });
5524
+ resolve(null);
5525
+ });
5526
+ child.on("close", (code) => resolve(code));
5527
+ });
5528
+ }
5529
+ function binaryUrlFor(platform3, execPath) {
5530
+ return platform3 === "win32" ? (0, import_node_url2.pathToFileURL)(execPath).href : `file://${execPath}`;
5531
+ }
5532
+ function installerEnvironment(platform3, execPath) {
5533
+ const environment = {
5534
+ ...environmentWithoutDeviceToken(),
5535
+ PKG_EXECPATH: "",
5536
+ [BINARY_URL_ENV]: binaryUrlFor(platform3, execPath),
5537
+ [INSTALL_ONLY_ENV]: "1"
5538
+ };
5539
+ delete environment[VERSION_ENV];
5540
+ return environment;
5541
+ }
5542
+ function windowsPowerShell() {
5543
+ const systemRoot = process.env.SystemRoot;
5544
+ return systemRoot ? import_node_path9.default.win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe") : "powershell.exe";
5545
+ }
5546
+ async function runEmbeddedInstaller(platform3, execPath) {
5547
+ const scriptName = platform3 === "win32" ? "install.ps1" : "install.sh";
5548
+ const temporaryFolder = import_node_fs13.default.mkdtempSync(import_node_path9.default.join(import_node_os5.default.tmpdir(), "pinggy-install-"));
5549
+ try {
5550
+ const scriptPath = import_node_path9.default.join(temporaryFolder, scriptName);
5551
+ import_node_fs13.default.writeFileSync(scriptPath, import_node_fs13.default.readFileSync(import_node_path9.default.join(SCRIPTS_DIRECTORY, scriptName)), { mode: 384 });
5552
+ const options = { stdio: OUTPUT_ONLY, env: installerEnvironment(platform3, execPath) };
5553
+ if (platform3 !== "win32") return await waitForExit("/bin/sh", [scriptPath], options) === 0;
5554
+ const command = `iex ([IO.File]::ReadAllText('${scriptPath.replace(/'/g, "''")}'))`;
5555
+ const encoded = Buffer.from(command, "utf16le").toString("base64");
5556
+ return await waitForExit(windowsPowerShell(), ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], options) === 0;
5557
+ } catch (error) {
5558
+ logger.debug("The install script did not run", { error: errorMessage(error) });
5559
+ printer_default.error(`pinggy install: ${errorMessage(error)}`);
5560
+ return false;
5561
+ } finally {
5562
+ import_node_fs13.default.rmSync(temporaryFolder, { recursive: true, force: true });
5563
+ }
5564
+ }
5565
+ function canWrite(folder) {
5566
+ try {
5567
+ import_node_fs13.default.accessSync(folder, import_node_fs13.default.constants.W_OK);
5568
+ return true;
5569
+ } catch {
5570
+ return false;
5571
+ }
5572
+ }
5573
+ function findNpm(npm, lookup) {
5574
+ if (lookup.platform === "win32") {
5575
+ const onPath2 = findOnPath(["npm.cmd"], lookup);
5576
+ const inPrefix2 = import_node_path9.default.win32.join(npm.prefix, "npm.cmd");
5577
+ return onPath2 ?? (lookup.files.isFile(inPrefix2) ? inPrefix2 : null);
5578
+ }
5579
+ const onPath = findOnPath(["npm"], lookup);
5580
+ const inPrefix = import_node_path9.default.posix.join(npm.prefix, "bin", "npm");
5581
+ return onPath ?? (lookup.files.isExecutableFile(inPrefix) ? inPrefix : null);
5582
+ }
5583
+ async function removeNpmCopy(npm) {
5584
+ const lookup = processPathLookup();
5585
+ if (lookup.platform !== "win32") {
5586
+ const folders = [import_node_path9.default.posix.join(npm.prefix, "lib", "node_modules"), import_node_path9.default.posix.join(npm.prefix, "bin")];
5587
+ if (!folders.every(canWrite)) return NpmRemoval.NotWritable;
5588
+ }
5589
+ const npmPath = findNpm(npm, lookup);
5590
+ if (npmPath === null) return NpmRemoval.NoNpm;
5591
+ printer_default.print(`Running: ${npmUninstallCommand(npm)}`);
5592
+ const options = { stdio: OUTPUT_ONLY, env: environmentWithoutDeviceToken() };
5593
+ let exitCode;
5594
+ if (lookup.platform === "win32") {
5595
+ const commandLine = `""${npmPath}" uninstall -g --prefix "${npm.prefix}" ${NPM_PACKAGE2}"`;
5596
+ exitCode = await waitForExit(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", commandLine], {
5597
+ ...options,
5598
+ windowsVerbatimArguments: true
5599
+ });
5600
+ } else {
5601
+ exitCode = await waitForExit(npmPath, ["uninstall", "-g", "--prefix", npm.prefix, NPM_PACKAGE2], options);
5602
+ }
5603
+ return exitCode === 0 ? NpmRemoval.Removed : NpmRemoval.Failed;
4831
5604
  }
4832
- function realEnvironment() {
4833
- const probe = createInstallProbe();
5605
+ function realEnvironment2() {
5606
+ const platform3 = process.platform;
5607
+ const variables = process.env;
5608
+ const home = installHome(platform3, variables);
5609
+ const execPath = process.execPath;
4834
5610
  return {
4835
- variables: process.env,
5611
+ platform: platform3,
5612
+ variables,
5613
+ isPackaged: isPackagedBinary(),
5614
+ stdinIsTerminal: process.stdin.isTTY === true,
4836
5615
  stdoutIsTerminal: process.stdout.isTTY === true,
5616
+ execPath,
4837
5617
  runningVersion: getVersion(),
4838
- platform: probe.platform,
4839
- scriptRealPath: probe.scriptRealPath,
4840
- nowEpochSeconds,
4841
- fileExists: (filePath) => import_node_fs9.default.existsSync(filePath),
4842
- detectKind: () => backgroundInstallKind(detectInstallKind(probe), probe.execPath, probe.homeRealPath),
5618
+ home,
5619
+ fileExists: (filePath) => import_node_fs13.default.existsSync(filePath),
5620
+ isInstalledCopy: () => isInstalledCopy(platform3, execPath, home, variables),
5621
+ findPinggyCommand: () => findPinggyCommand(processPathLookup()),
5622
+ installedBinary: (installPath) => home === null ? Promise.resolve(null) : realInstalledBinary(platform3, home, installPath),
5623
+ npmVersion: readNpmVersion,
4843
5624
  readState: readUpdateState,
4844
5625
  writeState: writeUpdateState,
4845
5626
  isLockHeld: isUpdateLockHeld,
4846
- liveDaemon: getDaemonInfo,
4847
- print: (line) => printer_default.print(line),
4848
- spawnUpdater: () => spawnUpdater()
5627
+ acquireLock: acquireUpdateLock,
5628
+ releaseLock: releaseUpdateLock,
5629
+ ask: askOnTerminal,
5630
+ runInstaller: () => runEmbeddedInstaller(platform3, execPath),
5631
+ removeNpmCopy,
5632
+ useInstalledBinaryForDaemon: startDaemonFromInstalledBinary,
5633
+ print: (line) => printer_default.print(line)
4849
5634
  };
4850
5635
  }
4851
- function startBackgroundUpdate(command, createEnvironment = realEnvironment) {
4852
- try {
4853
- runGates(command, createEnvironment());
4854
- } catch (error) {
4855
- logger.debug("Background update gate failed", { error: errorMessage(error) });
4856
- }
4857
- }
4858
- var import_node_child_process3, import_node_fs9, import_node_os3, AUTO_UPDATE_ENV, OFF_VALUES, ON_VALUES, SUDO_UID_ENV, CONTAINER_MARKER_FILES, NPX_SEGMENT, UPDATE_SUBCOMMAND, UPDATE_CHILD_FLAG, SECONDS_PER_DAY, CHECK_INTERVAL_SECONDS, ATTEMPT_INTERVAL_SECONDS, COULD_NOT_UPDATE_AFTER_SECONDS, COULD_NOT_CHECK_AFTER_SECONDS;
4859
- var init_backgroundUpdate = __esm({
4860
- "src/update/backgroundUpdate.ts"() {
5636
+ var import_node_child_process5, import_node_fs13, import_node_os5, import_node_path9, import_node_readline, import_node_url2, UPDATE_SUBCOMMAND2, NPM_PACKAGE2, LINK_DIRECTORY, NO_ANSWER, INTERRUPTED_EXIT_CODE, VERSION_RUN_TIMEOUT_MILLIS, OUTPUT_ONLY, INSTALL_ONLY_ENV, BINARY_URL_ENV, VERSION_ENV, BUNDLE_DIRECTORY, SCRIPTS_DIRECTORY, SelfInstallAnswer, NpmRemoval, runForVersion;
5637
+ var init_selfInstall = __esm({
5638
+ "src/install/selfInstall.ts"() {
4861
5639
  "use strict";
4862
5640
  init_cjs_shims();
4863
- import_node_child_process3 = require("child_process");
4864
- import_node_fs9 = __toESM(require("fs"), 1);
4865
- import_node_os3 = __toESM(require("os"), 1);
5641
+ import_node_child_process5 = require("child_process");
5642
+ import_node_fs13 = __toESM(require("fs"), 1);
5643
+ import_node_os5 = __toESM(require("os"), 1);
5644
+ import_node_path9 = __toESM(require("path"), 1);
5645
+ import_node_readline = require("readline");
5646
+ import_node_url2 = require("url");
4866
5647
  init_daemonManager();
5648
+ init_serviceInstaller();
5649
+ init_nodePtyRuntime();
4867
5650
  init_logger();
4868
- init_util();
4869
- init_printer();
5651
+ init_backgroundUpdate();
4870
5652
  init_binaryUpdater();
4871
5653
  init_installKind();
4872
5654
  init_latestRelease();
4873
- init_updateMessages();
5655
+ init_unixLinkSwap();
4874
5656
  init_updateLock();
4875
5657
  init_updateState();
4876
- AUTO_UPDATE_ENV = "PINGGY_AUTO_UPDATE";
4877
- OFF_VALUES = /* @__PURE__ */ new Set(["false", "0"]);
4878
- ON_VALUES = /* @__PURE__ */ new Set(["true", "1"]);
4879
- SUDO_UID_ENV = "SUDO_UID";
4880
- CONTAINER_MARKER_FILES = ["/.dockerenv", "/run/.containerenv"];
4881
- NPX_SEGMENT = "_npx";
4882
- UPDATE_SUBCOMMAND = "update";
4883
- UPDATE_CHILD_FLAG = "--_update-child";
4884
- SECONDS_PER_DAY = 24 * 60 * 60;
4885
- CHECK_INTERVAL_SECONDS = SECONDS_PER_DAY;
4886
- ATTEMPT_INTERVAL_SECONDS = 60 * 60;
4887
- COULD_NOT_UPDATE_AFTER_SECONDS = 7 * SECONDS_PER_DAY;
4888
- COULD_NOT_CHECK_AFTER_SECONDS = 30 * SECONDS_PER_DAY;
5658
+ init_printer();
5659
+ init_util();
5660
+ init_pinggyOnPath();
5661
+ UPDATE_SUBCOMMAND2 = "update";
5662
+ NPM_PACKAGE2 = "pinggy";
5663
+ LINK_DIRECTORY = import_node_path9.default.posix.join(".local", "bin");
5664
+ NO_ANSWER = /^\s*n/i;
5665
+ INTERRUPTED_EXIT_CODE = 130;
5666
+ VERSION_RUN_TIMEOUT_MILLIS = 1e4;
5667
+ OUTPUT_ONLY = ["ignore", "inherit", "inherit"];
5668
+ INSTALL_ONLY_ENV = "PINGGY_INSTALL_ONLY";
5669
+ BINARY_URL_ENV = "PINGGY_BINARY_URL";
5670
+ VERSION_ENV = "PINGGY_VERSION";
5671
+ BUNDLE_DIRECTORY = import_node_path9.default.dirname((0, import_node_url2.fileURLToPath)(importMetaUrl));
5672
+ SCRIPTS_DIRECTORY = import_node_path9.default.join(BUNDLE_DIRECTORY, "..", "scripts", "install");
5673
+ SelfInstallAnswer = {
5674
+ Yes: "yes",
5675
+ No: "no",
5676
+ /** Ctrl+D: the input ended. Not a decision, so nothing is installed or remembered. */
5677
+ Closed: "closed"
5678
+ };
5679
+ NpmRemoval = {
5680
+ Removed: "removed",
5681
+ NotWritable: "not-writable",
5682
+ NoNpm: "no-npm",
5683
+ Failed: "failed"
5684
+ };
5685
+ runForVersion = (binaryPath, args) => new Promise((resolve, reject) => {
5686
+ (0, import_node_child_process5.execFile)(binaryPath, args, { ...pinggyBinaryRunOptions(), timeout: VERSION_RUN_TIMEOUT_MILLIS }, (error, stdout) => {
5687
+ if (error) reject(error);
5688
+ else resolve(String(stdout));
5689
+ });
5690
+ });
4889
5691
  }
4890
5692
  });
4891
5693
 
@@ -5841,10 +6643,10 @@ function parseExtendedOptions(options, config, localServerTls) {
5841
6643
  break;
5842
6644
  case "haproxy":
5843
6645
  case "haproxy:v1":
5844
- config.haProxy = import_pinggy4.HaProxyVersion.V1;
6646
+ config.haProxy = import_pinggy5.HaProxyVersion.V1;
5845
6647
  break;
5846
6648
  case "haproxy:v2":
5847
- config.haProxy = import_pinggy4.HaProxyVersion.V2;
6649
+ config.haProxy = import_pinggy5.HaProxyVersion.V2;
5848
6650
  break;
5849
6651
  default: {
5850
6652
  if (value && (value.startsWith("localServerTls") || value.startsWith("localservertls"))) {
@@ -5954,12 +6756,12 @@ function isValidIpV6Cidr(input) {
5954
6756
  }
5955
6757
  return false;
5956
6758
  }
5957
- var import_pinggy4, import_net;
6759
+ var import_pinggy5, import_net;
5958
6760
  var init_extendedOptions = __esm({
5959
6761
  "src/cli/extendedOptions.ts"() {
5960
6762
  "use strict";
5961
6763
  init_cjs_shims();
5962
- import_pinggy4 = require("@pinggy/pinggy");
6764
+ import_pinggy5 = require("@pinggy/pinggy");
5963
6765
  import_net = require("net");
5964
6766
  init_logger();
5965
6767
  init_printer();
@@ -5996,7 +6798,7 @@ function parseUserAndDomain(str) {
5996
6798
  const [user, domain] = str.split("@", 2);
5997
6799
  if (isValidServerAddress(domain)) {
5998
6800
  let processKeyword2 = function(keyword) {
5999
- if ([import_pinggy5.TunnelType.Http, import_pinggy5.TunnelType.Tcp, import_pinggy5.TunnelType.Tls, import_pinggy5.TunnelType.Udp, import_pinggy5.TunnelType.TlsTcp].includes(keyword)) {
6801
+ if ([import_pinggy6.TunnelType.Http, import_pinggy6.TunnelType.Tcp, import_pinggy6.TunnelType.Tls, import_pinggy6.TunnelType.Udp, import_pinggy6.TunnelType.TlsTcp].includes(keyword)) {
6000
6802
  type = keyword;
6001
6803
  } else if (keyword === "force") {
6002
6804
  forceFlag = true;
@@ -6084,7 +6886,7 @@ function parseUsers(positionalArgs, explicitToken) {
6084
6886
  }
6085
6887
  function parseType(finalConfig, values, inferredType) {
6086
6888
  const t = inferredType || values.type;
6087
- if (t === import_pinggy5.TunnelType.Http || t === import_pinggy5.TunnelType.Tcp || t === import_pinggy5.TunnelType.Tls || t === import_pinggy5.TunnelType.Udp || t === import_pinggy5.TunnelType.TlsTcp) {
6889
+ if (t === import_pinggy6.TunnelType.Http || t === import_pinggy6.TunnelType.Tcp || t === import_pinggy6.TunnelType.Tls || t === import_pinggy6.TunnelType.Udp || t === import_pinggy6.TunnelType.TlsTcp) {
6088
6890
  return t;
6089
6891
  }
6090
6892
  }
@@ -6182,7 +6984,7 @@ function parseAdditionalForwarding(forwarding) {
6182
6984
  }
6183
6985
  const firstPart = parsed[0];
6184
6986
  const [hostPart] = firstPart.split("@");
6185
- let protocol = import_pinggy5.TunnelType.Http;
6987
+ let protocol = import_pinggy6.TunnelType.Http;
6186
6988
  let remoteDomainRaw;
6187
6989
  let remotePort = 0;
6188
6990
  if (hostPart.includes("//")) {
@@ -6215,7 +7017,7 @@ function parseAdditionalForwarding(forwarding) {
6215
7017
  if (!isValidServerAddress(remoteDomainRaw)) {
6216
7018
  return new Error("invalid remote domain");
6217
7019
  }
6218
- protocol = import_pinggy5.TunnelType.Http;
7020
+ protocol = import_pinggy6.TunnelType.Http;
6219
7021
  remotePort = 0;
6220
7022
  }
6221
7023
  const localDomain = removeIPv6Brackets(parsed[2] || "localhost");
@@ -6245,7 +7047,7 @@ function parseReverseTunnelAddr(finalConfig, values, primaryType) {
6245
7047
  if (parsed instanceof Error) return parsed;
6246
7048
  forwardingData.push({
6247
7049
  address: `${parsed.localDomain}:${parsed.localPort}`,
6248
- type: primaryType || import_pinggy5.TunnelType.Http
7050
+ type: primaryType || import_pinggy6.TunnelType.Http
6249
7051
  });
6250
7052
  } else if (slicedForwarding.length === 4) {
6251
7053
  const parsed = parseAdditionalForwarding(forwarding);
@@ -6311,7 +7113,7 @@ function normalizeForwardingToArray(finalConfig, type) {
6311
7113
  if (typeof fwd !== "string") {
6312
7114
  return;
6313
7115
  }
6314
- finalConfig.forwarding = fwd.trim() === "" ? [] : [{ type: type || import_pinggy5.TunnelType.Http, address: fwd.trim() }];
7116
+ finalConfig.forwarding = fwd.trim() === "" ? [] : [{ type: type || import_pinggy6.TunnelType.Http, address: fwd.trim() }];
6315
7117
  }
6316
7118
  function parseArgs2(finalConfig, remainingPositionals) {
6317
7119
  let localserverTls = "";
@@ -6324,10 +7126,10 @@ function parseArgs2(finalConfig, remainingPositionals) {
6324
7126
  }
6325
7127
  function storeJson(config, saveconf) {
6326
7128
  if (saveconf) {
6327
- const path18 = saveconf;
7129
+ const path20 = saveconf;
6328
7130
  try {
6329
- import_fs7.default.writeFileSync(path18, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
6330
- logger.info(`Configuration saved to ${path18}`);
7131
+ import_fs7.default.writeFileSync(path20, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
7132
+ logger.info(`Configuration saved to ${path20}`);
6331
7133
  } catch (err) {
6332
7134
  const msg = err instanceof Error ? err.message : String(err);
6333
7135
  logger.error("Error loading configuration:", msg);
@@ -6380,11 +7182,11 @@ function validateHaProxy(finalConfig) {
6380
7182
  const forwarding = finalConfig.forwarding;
6381
7183
  const entries = Array.isArray(forwarding) ? forwarding : [];
6382
7184
  const primaryType = entries.length > 0 ? entries[0].type : void 0;
6383
- if (primaryType === import_pinggy5.TunnelType.Tcp) {
7185
+ if (primaryType === import_pinggy6.TunnelType.Tcp) {
6384
7186
  return null;
6385
7187
  }
6386
7188
  return new Error(
6387
- `HAProxy PROXY protocol (x:haproxy) can only be used with TCP tunnels, but this tunnel is "${primaryType ?? import_pinggy5.TunnelType.Http}". Make it a TCP tunnel (--type tcp, or the tcp@ server prefix) or drop x:haproxy.`
7189
+ `HAProxy PROXY protocol (x:haproxy) can only be used with TCP tunnels, but this tunnel is "${primaryType ?? import_pinggy6.TunnelType.Http}". Make it a TCP tunnel (--type tcp, or the tcp@ server prefix) or drop x:haproxy.`
6388
7190
  );
6389
7191
  }
6390
7192
  function buildFinalConfig(values, positionals, baseConfig) {
@@ -6458,7 +7260,7 @@ function buildFinalConfig(values, positionals, baseConfig) {
6458
7260
  storeJson(finalConfig, saveconf);
6459
7261
  return finalConfig;
6460
7262
  }
6461
- var import_pinggy5, import_fs7, import_path7, import_net2, domainRegex, KEYWORDS, VALID_PROTOCOLS;
7263
+ var import_pinggy6, import_fs7, import_path7, import_net2, domainRegex, KEYWORDS, VALID_PROTOCOLS;
6462
7264
  var init_buildConfig = __esm({
6463
7265
  "src/cli/buildConfig.ts"() {
6464
7266
  "use strict";
@@ -6467,21 +7269,21 @@ var init_buildConfig = __esm({
6467
7269
  init_extendedOptions();
6468
7270
  init_logger();
6469
7271
  init_util();
6470
- import_pinggy5 = require("@pinggy/pinggy");
7272
+ import_pinggy6 = require("@pinggy/pinggy");
6471
7273
  import_fs7 = __toESM(require("fs"), 1);
6472
7274
  import_path7 = __toESM(require("path"), 1);
6473
7275
  import_net2 = require("net");
6474
7276
  domainRegex = /^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
6475
7277
  KEYWORDS = /* @__PURE__ */ new Set([
6476
- import_pinggy5.TunnelType.Http,
6477
- import_pinggy5.TunnelType.Tcp,
6478
- import_pinggy5.TunnelType.Tls,
6479
- import_pinggy5.TunnelType.Udp,
6480
- import_pinggy5.TunnelType.TlsTcp,
7278
+ import_pinggy6.TunnelType.Http,
7279
+ import_pinggy6.TunnelType.Tcp,
7280
+ import_pinggy6.TunnelType.Tls,
7281
+ import_pinggy6.TunnelType.Udp,
7282
+ import_pinggy6.TunnelType.TlsTcp,
6481
7283
  "force",
6482
7284
  "qr"
6483
7285
  ]);
6484
- VALID_PROTOCOLS = [import_pinggy5.TunnelType.Http, import_pinggy5.TunnelType.Tcp, import_pinggy5.TunnelType.Udp, import_pinggy5.TunnelType.Tls, import_pinggy5.TunnelType.TlsTcp];
7286
+ VALID_PROTOCOLS = [import_pinggy6.TunnelType.Http, import_pinggy6.TunnelType.Tcp, import_pinggy6.TunnelType.Udp, import_pinggy6.TunnelType.Tls, import_pinggy6.TunnelType.TlsTcp];
6485
7287
  }
6486
7288
  });
6487
7289
 
@@ -8941,7 +9743,8 @@ function printLogHelp() {
8941
9743
  console.log(" level Print current log level");
8942
9744
  console.log(" level debug|info|error Set log level");
8943
9745
  console.log(" path Print daemon log path");
8944
- console.log(" path <name|id> Print tunnel log path\n");
9746
+ console.log(" path <name|id> Print tunnel log path");
9747
+ console.log(" path libpinggy Print the native library's log path (one file for all tunnels)\n");
8945
9748
  }
8946
9749
  function printConfigHelp() {
8947
9750
  console.log("\nUsage: pinggy config <command> [name] [options]\n");
@@ -8970,6 +9773,7 @@ function printDeviceHelp() {
8970
9773
  console.log(" background");
8971
9774
  console.log(" connect --token <TOKEN> Enrol with a token from the dashboard, then run the agent in the");
8972
9775
  console.log(" background. Without --token: start the enrolled device's agent again");
9776
+ console.log(" start Same as connect");
8973
9777
  console.log(" stop Stop the agent running in the background, until the daemon");
8974
9778
  console.log(" starts again");
8975
9779
  console.log(" status Show whether the agent runs, the enrolment, and the background agent");
@@ -8978,15 +9782,15 @@ function printDeviceHelp() {
8978
9782
  console.log("By default the agent runs in the daemon, and stays connected after this terminal closes.");
8979
9783
  console.log("Each time the daemon starts, it starts the agent again, until remove.\n");
8980
9784
  console.log("Options:");
8981
- console.log(" --foreground login and connect: run the agent in this terminal until Ctrl+C");
8982
- console.log(" -b login and connect: run the agent in the background. The default");
9785
+ console.log(" --foreground login, connect and start: run the agent in this terminal until Ctrl+C");
9786
+ console.log(" -b login, connect and start: run the agent in the background. The default");
8983
9787
  console.log(" --token <TOKEN> Device token from the dashboard");
8984
9788
  console.log(" --manage <HOST> Dashboard address. Default: dashboard.pinggy.io");
8985
9789
  console.log(" --name <NAME> login only: the device's name. Default: this machine's hostname");
8986
9790
  console.log(" -f remove only: remove without asking\n");
8987
9791
  console.log("Environment:");
8988
- console.log(" DEVICE_AGENT_TOKEN connect only: the device token, when --token is not given. With no");
8989
- console.log(" --manage, it dials dashboard.pinggy.io. Removed once read\n");
9792
+ console.log(" DEVICE_AGENT_TOKEN connect and start: the device token, when --token is not given.");
9793
+ console.log(" With no --manage, it dials dashboard.pinggy.io. Removed once read\n");
8990
9794
  }
8991
9795
  function printUpdateHelp() {
8992
9796
  console.log("\nUsage: pinggy update [--check | --rollback]\n");
@@ -9241,18 +10045,32 @@ function buildMetrics(readings) {
9241
10045
  collected_at: readings.collectedAtEpochSeconds
9242
10046
  };
9243
10047
  }
9244
- async function collectMetrics() {
9245
- const earlier = sumCpuTicks(import_os4.default.cpus());
10048
+ function ticksMovedForward(earlier, later) {
10049
+ return later.totalTicks > earlier.totalTicks && later.idleTicks >= earlier.idleTicks;
10050
+ }
10051
+ async function readCpuPercent(previousTicks, readCpus) {
10052
+ const currentTicks = sumCpuTicks(readCpus());
10053
+ if (previousTicks && ticksMovedForward(previousTicks, currentTicks)) {
10054
+ return { cpuPercent: cpuPercentBetween(previousTicks, currentTicks), endTicks: currentTicks };
10055
+ }
9246
10056
  await new Promise((resolve) => setTimeout(resolve, CPU_SAMPLE_WINDOW_MS));
9247
- const later = sumCpuTicks(import_os4.default.cpus());
9248
- return buildMetrics({
9249
- cpuPercent: cpuPercentBetween(earlier, later),
9250
- loadAverages: import_os4.default.loadavg(),
9251
- totalMemoryBytes: import_os4.default.totalmem(),
9252
- freeMemoryBytes: import_os4.default.freemem(),
9253
- uptimeSeconds: import_os4.default.uptime(),
9254
- collectedAtEpochSeconds: Math.floor(Date.now() / 1e3)
9255
- });
10057
+ const laterTicks = sumCpuTicks(readCpus());
10058
+ return { cpuPercent: cpuPercentBetween(currentTicks, laterTicks), endTicks: laterTicks };
10059
+ }
10060
+ function createMetricsCollector(readCpus = () => import_os4.default.cpus()) {
10061
+ let previousTicks = null;
10062
+ return async () => {
10063
+ const cpuReading = await readCpuPercent(previousTicks, readCpus);
10064
+ previousTicks = cpuReading.endTicks;
10065
+ return buildMetrics({
10066
+ cpuPercent: cpuReading.cpuPercent,
10067
+ loadAverages: import_os4.default.loadavg(),
10068
+ totalMemoryBytes: import_os4.default.totalmem(),
10069
+ freeMemoryBytes: import_os4.default.freemem(),
10070
+ uptimeSeconds: import_os4.default.uptime(),
10071
+ collectedAtEpochSeconds: Math.floor(Date.now() / 1e3)
10072
+ });
10073
+ };
9256
10074
  }
9257
10075
  var import_os4, CPU_SAMPLE_WINDOW_MS;
9258
10076
  var init_metrics = __esm({
@@ -9947,13 +10765,13 @@ function programName(rawName) {
9947
10765
  function displayCwd(rawCwd, resolvedHome) {
9948
10766
  const cwd = cleanText(rawCwd, Number.MAX_SAFE_INTEGER);
9949
10767
  if (cwd === null) return null;
9950
- let shown = cwd;
10768
+ let shown2 = cwd;
9951
10769
  if (resolvedHome && cwd === resolvedHome) {
9952
- shown = HOME_PREFIX;
10770
+ shown2 = HOME_PREFIX;
9953
10771
  } else if (resolvedHome && cwd.startsWith(resolvedHome + "/")) {
9954
- shown = HOME_PREFIX + cwd.slice(resolvedHome.length);
10772
+ shown2 = HOME_PREFIX + cwd.slice(resolvedHome.length);
9955
10773
  }
9956
- return truncate(shown, MAX_CWD_CHARACTERS);
10774
+ return truncate(shown2, MAX_CWD_CHARACTERS);
9957
10775
  }
9958
10776
  function resolvedHomeDirectory() {
9959
10777
  try {
@@ -11164,9 +11982,9 @@ function readShellEnvironment() {
11164
11982
  platform: process.platform,
11165
11983
  loginShell: process.env.SHELL,
11166
11984
  etcShells,
11167
- exists: (path18) => {
11985
+ exists: (path20) => {
11168
11986
  try {
11169
- return import_fs12.default.statSync(path18).isFile();
11987
+ return import_fs12.default.statSync(path20).isFile();
11170
11988
  } catch {
11171
11989
  return false;
11172
11990
  }
@@ -11234,7 +12052,7 @@ function readForegroundAgent() {
11234
12052
  if (record.pid === process.pid) {
11235
12053
  return null;
11236
12054
  }
11237
- if (startedBeforeBoot(record.started_at) || !isProcessAlive(record.pid)) {
12055
+ if (startedInEarlierBoot(record.boot_id, record.started_at) || !isProcessAlive(record.pid)) {
11238
12056
  logger.info("Stale device-agent.json found, cleaning up", { stalePid: record.pid });
11239
12057
  deleteRecordFile(filePath);
11240
12058
  return null;
@@ -11243,7 +12061,11 @@ function readForegroundAgent() {
11243
12061
  }
11244
12062
  function recordForegroundAgent(onRecordDeleted) {
11245
12063
  const filePath = getForegroundAgentPath();
11246
- const record = { pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() };
12064
+ const record = {
12065
+ pid: process.pid,
12066
+ started_at: (/* @__PURE__ */ new Date()).toISOString(),
12067
+ boot_id: currentBootId() ?? void 0
12068
+ };
11247
12069
  try {
11248
12070
  ensurePinggyConfigDir();
11249
12071
  import_fs13.default.writeFileSync(filePath, JSON.stringify(record, null, 2), "utf-8");
@@ -11310,6 +12132,7 @@ var init_foregroundAgent = __esm({
11310
12132
  import_fs13 = __toESM(require("fs"), 1);
11311
12133
  init_configDir();
11312
12134
  init_daemonManager();
12135
+ init_bootId();
11313
12136
  init_logger();
11314
12137
  init_util();
11315
12138
  init_printer();
@@ -11570,7 +12393,7 @@ function connectOnce(context) {
11570
12393
  sendFrame(event(CHANNEL_DEVICE, OP_INFO, collectSystemInfo()));
11571
12394
  stopMetrics = startMetricsReporting(
11572
12395
  welcome.stats_interval_seconds,
11573
- collectMetrics,
12396
+ createMetricsCollector(),
11574
12397
  (metrics) => sendFrame(event(CHANNEL_DEVICE, OP_METRICS, metrics))
11575
12398
  );
11576
12399
  stopTunnels = startTunnelReporting(
@@ -11788,8 +12611,8 @@ function buildDashboardHttpUrl(manage) {
11788
12611
  }
11789
12612
  function createDeviceLoginApi(manage, fetchImpl = fetch) {
11790
12613
  const baseUrl = buildDashboardHttpUrl(manage);
11791
- async function post(path18, body, schema) {
11792
- const response2 = await fetchImpl(`${baseUrl}/${path18}`, {
12614
+ async function post(path20, body, schema) {
12615
+ const response2 = await fetchImpl(`${baseUrl}/${path20}`, {
11793
12616
  method: "POST",
11794
12617
  headers: { "Content-Type": "application/json", Accept: "application/json" },
11795
12618
  body: JSON.stringify(body)
@@ -12301,7 +13124,7 @@ function describeDeviceState(reading, daemonFound, foreground) {
12301
13124
  return import_picocolors9.default.green("running, with --foreground in another terminal");
12302
13125
  }
12303
13126
  if (reading || !daemonFound) {
12304
- return `${import_picocolors9.default.red("stopped")}. To start it, run: pinggy device connect`;
13127
+ return `${import_picocolors9.default.red("stopped")}. To start it, run: pinggy device start or pinggy device connect`;
12305
13128
  }
12306
13129
  return import_picocolors9.default.gray("unknown, could not read the daemon");
12307
13130
  }
@@ -12417,7 +13240,8 @@ var init_backgroundAgent = __esm({
12417
13240
  MANAGE_COMMANDS = [
12418
13241
  ["pinggy device status", "Show this device, and whether its agent runs"],
12419
13242
  ["pinggy device stop", "Stop the agent until the daemon starts again. The device shows offline"],
12420
- ["pinggy device connect", "Start the agent again after a stop"],
13243
+ ["pinggy device start", "Start the agent again after a stop"],
13244
+ ["pinggy device connect", "Same as start"],
12421
13245
  ["pinggy device remove", "Stop the agent and forget this machine's credential"]
12422
13246
  ];
12423
13247
  verifyingReporter = {
@@ -12788,8 +13612,8 @@ function parseTunnelLogFilename(filename) {
12788
13612
  }
12789
13613
  function listTunnelLogFiles() {
12790
13614
  const logDir = getTunnelLogDir();
12791
- if (!import_node_fs10.default.existsSync(logDir)) return [];
12792
- return import_node_fs10.default.readdirSync(logDir).filter((f) => f.endsWith(".log") && !/\.log\.\d+$/.test(f));
13615
+ if (!import_node_fs14.default.existsSync(logDir)) return [];
13616
+ return import_node_fs14.default.readdirSync(logDir).filter((f) => f.endsWith(".log") && !/\.log\.\d+$/.test(f));
12793
13617
  }
12794
13618
  function newestLogFile(q) {
12795
13619
  const logDir = getTunnelLogDir();
@@ -12800,8 +13624,8 @@ function newestLogFile(q) {
12800
13624
  const nameMatch = parsed.name !== void 0 && parsed.name === q;
12801
13625
  const idMatch = parsed.tunnelId !== void 0 && (parsed.tunnelId === q || parsed.tunnelId.startsWith(q));
12802
13626
  if (nameMatch || idMatch) {
12803
- const filePath = import_node_path7.default.join(logDir, file);
12804
- matches.push({ ...parsed, path: filePath, mtime: import_node_fs10.default.statSync(filePath).mtimeMs });
13627
+ const filePath = import_node_path10.default.join(logDir, file);
13628
+ matches.push({ ...parsed, path: filePath, mtime: import_node_fs14.default.statSync(filePath).mtimeMs });
12805
13629
  }
12806
13630
  }
12807
13631
  if (matches.length === 0) return null;
@@ -12820,13 +13644,13 @@ function resolveStoppedLogPath(q) {
12820
13644
  }
12821
13645
  return { status: "not-found" };
12822
13646
  }
12823
- var import_node_fs10, import_node_path7, TUNNEL_ORIGINS, UUID_RE;
13647
+ var import_node_fs14, import_node_path10, TUNNEL_ORIGINS, UUID_RE;
12824
13648
  var init_logPaths = __esm({
12825
13649
  "src/daemon/logPaths.ts"() {
12826
13650
  "use strict";
12827
13651
  init_cjs_shims();
12828
- import_node_fs10 = __toESM(require("fs"), 1);
12829
- import_node_path7 = __toESM(require("path"), 1);
13652
+ import_node_fs14 = __toESM(require("fs"), 1);
13653
+ import_node_path10 = __toESM(require("path"), 1);
12830
13654
  init_configStore();
12831
13655
  init_configDir();
12832
13656
  TUNNEL_ORIGINS = ["app", "cli", "remote", "device"];
@@ -12835,21 +13659,28 @@ var init_logPaths = __esm({
12835
13659
  });
12836
13660
 
12837
13661
  // src/cli/subcommand/handlers/logLookup.ts
13662
+ function orLibpinggyLog(nameOrId, result) {
13663
+ if (nameOrId === LIBPINGGY_LOG_NAME && result.status === "not-found") {
13664
+ return { status: "libpinggy", path: getLibpinggyLogPath() };
13665
+ }
13666
+ return result;
13667
+ }
12838
13668
  function openLogLookup() {
12839
13669
  const client = new TunnelClient();
12840
13670
  if (!client.connectIfRunning()) {
12841
13671
  return {
12842
13672
  daemonLogPath: () => Promise.resolve(getDaemonLogPath()),
12843
- resolve: (nameOrId) => Promise.resolve(resolveStoppedLogPath(nameOrId)),
13673
+ resolve: (nameOrId) => Promise.resolve(orLibpinggyLog(nameOrId, resolveStoppedLogPath(nameOrId))),
12844
13674
  close: () => void 0
12845
13675
  };
12846
13676
  }
12847
13677
  return {
12848
13678
  daemonLogPath: async () => (await client.getLogPaths()).daemon,
12849
- resolve: (nameOrId) => client.resolveLogPath(nameOrId),
13679
+ resolve: async (nameOrId) => orLibpinggyLog(nameOrId, await client.resolveLogPath(nameOrId)),
12850
13680
  close: () => client.close()
12851
13681
  };
12852
13682
  }
13683
+ var LIBPINGGY_LOG_NAME;
12853
13684
  var init_logLookup = __esm({
12854
13685
  "src/cli/subcommand/handlers/logLookup.ts"() {
12855
13686
  "use strict";
@@ -12857,6 +13688,7 @@ var init_logLookup = __esm({
12857
13688
  init_tunnelClient();
12858
13689
  init_logPaths();
12859
13690
  init_configDir();
13691
+ LIBPINGGY_LOG_NAME = "libpinggy";
12860
13692
  }
12861
13693
  });
12862
13694
 
@@ -12899,7 +13731,7 @@ async function handleLogs(args, follow) {
12899
13731
  return;
12900
13732
  }
12901
13733
  client.close();
12902
- if (!filePath || !import_node_fs11.default.existsSync(filePath)) {
13734
+ if (!filePath || !import_node_fs15.default.existsSync(filePath)) {
12903
13735
  printer_default.error(`Log file not found: ${filePath}`);
12904
13736
  process.exit(1);
12905
13737
  }
@@ -12910,18 +13742,18 @@ async function handleLogs(args, follow) {
12910
13742
  }
12911
13743
  }
12912
13744
  function printTail(filePath, lines) {
12913
- const content = import_node_fs11.default.readFileSync(filePath, "utf-8");
13745
+ const content = import_node_fs15.default.readFileSync(filePath, "utf-8");
12914
13746
  const allLines = content.split("\n");
12915
13747
  const tail = allLines.slice(-lines).join("\n");
12916
13748
  process.stdout.write(tail);
12917
13749
  if (!tail.endsWith("\n")) process.stdout.write("\n");
12918
13750
  }
12919
13751
  async function followFile(filePath) {
12920
- if (import_node_fs11.default.existsSync(filePath)) printTail(filePath, 20);
12921
- let fileSize = import_node_fs11.default.existsSync(filePath) ? import_node_fs11.default.statSync(filePath).size : 0;
13752
+ if (import_node_fs15.default.existsSync(filePath)) printTail(filePath, 20);
13753
+ let fileSize = import_node_fs15.default.existsSync(filePath) ? import_node_fs15.default.statSync(filePath).size : 0;
12922
13754
  let watcher = null;
12923
13755
  const openStream = () => {
12924
- const stream = import_node_fs11.default.createReadStream(filePath, { start: fileSize, encoding: "utf-8" });
13756
+ const stream = import_node_fs15.default.createReadStream(filePath, { start: fileSize, encoding: "utf-8" });
12925
13757
  stream.on("data", (chunk) => {
12926
13758
  process.stdout.write(chunk);
12927
13759
  fileSize += Buffer.byteLength(chunk, "utf-8");
@@ -12929,9 +13761,9 @@ async function followFile(filePath) {
12929
13761
  stream.on("error", () => {
12930
13762
  });
12931
13763
  };
12932
- watcher = import_node_fs11.default.watch(filePath, { persistent: true }, (event2) => {
13764
+ watcher = import_node_fs15.default.watch(filePath, { persistent: true }, (event2) => {
12933
13765
  if (event2 === "change") {
12934
- const stat = import_node_fs11.default.existsSync(filePath) ? import_node_fs11.default.statSync(filePath) : null;
13766
+ const stat = import_node_fs15.default.existsSync(filePath) ? import_node_fs15.default.statSync(filePath) : null;
12935
13767
  if (!stat || stat.size < fileSize) {
12936
13768
  fileSize = 0;
12937
13769
  }
@@ -12945,12 +13777,12 @@ async function followFile(filePath) {
12945
13777
  });
12946
13778
  });
12947
13779
  }
12948
- var import_node_fs11;
13780
+ var import_node_fs15;
12949
13781
  var init_logsCommand = __esm({
12950
13782
  "src/cli/subcommand/handlers/logsCommand.ts"() {
12951
13783
  "use strict";
12952
13784
  init_cjs_shims();
12953
- import_node_fs11 = __toESM(require("fs"), 1);
13785
+ import_node_fs15 = __toESM(require("fs"), 1);
12954
13786
  init_logLookup();
12955
13787
  init_printer();
12956
13788
  init_util();
@@ -13036,6 +13868,7 @@ async function handleLogPath(args) {
13036
13868
  switch (result.status) {
13037
13869
  case "running":
13038
13870
  case "historical":
13871
+ case "libpinggy":
13039
13872
  printer_default.print(result.path);
13040
13873
  break;
13041
13874
  case "config-only":
@@ -13255,6 +14088,7 @@ async function handleDevice(args, background = machineBackgroundAgentDependencie
13255
14088
  exitUnlessOk(await handleDeviceLogin(values.manage, values.name, inBackground, background));
13256
14089
  return;
13257
14090
  case DeviceVerb.Connect:
14091
+ case DeviceVerb.Start:
13258
14092
  exitUnlessOk(await handleDeviceConnect(
13259
14093
  values.token,
13260
14094
  environmentToken,
@@ -13280,7 +14114,7 @@ async function handleDevice(args, background = machineBackgroundAgentDependencie
13280
14114
  printDeviceHelp();
13281
14115
  return;
13282
14116
  }
13283
- printer_default.error(`Unknown command "${verb}". Valid commands: login, connect, stop, status, remove.`);
14117
+ printer_default.error(`Unknown command "${verb}". Valid commands: login, connect, start, stop, status, remove.`);
13284
14118
  process.exit(1);
13285
14119
  }
13286
14120
  }
@@ -13379,6 +14213,7 @@ var init_deviceCommand = __esm({
13379
14213
  DeviceVerb = {
13380
14214
  Login: "login",
13381
14215
  Connect: "connect",
14216
+ Start: "start",
13382
14217
  Stop: "stop",
13383
14218
  Status: "status",
13384
14219
  Remove: "remove"
@@ -13387,167 +14222,6 @@ var init_deviceCommand = __esm({
13387
14222
  }
13388
14223
  });
13389
14224
 
13390
- // src/update/unixLinkSwap.ts
13391
- function fsyncPath(target, flags) {
13392
- const fileDescriptor = import_node_fs12.default.openSync(target, flags);
13393
- try {
13394
- import_node_fs12.default.fsyncSync(fileDescriptor);
13395
- } finally {
13396
- import_node_fs12.default.closeSync(fileDescriptor);
13397
- }
13398
- }
13399
- function unixDownloadPath(layout) {
13400
- return import_node_path8.default.posix.join(layout.versionsDirectory, `${DOWNLOAD_PREFIX}${process.pid}`);
13401
- }
13402
- function versionDirectory(layout, version) {
13403
- return import_node_path8.default.posix.join(layout.versionsDirectory, version);
13404
- }
13405
- function versionBinaryPath(layout, version) {
13406
- return import_node_path8.default.posix.join(versionDirectory(layout, version), BINARY_NAME);
13407
- }
13408
- function readLinkVersion(layout) {
13409
- try {
13410
- const version = import_node_path8.default.posix.basename(import_node_path8.default.posix.dirname(import_node_fs12.default.readlinkSync(layout.link)));
13411
- return parseVersion(version) ? version : null;
13412
- } catch {
13413
- return null;
13414
- }
13415
- }
13416
- function installedVersions(layout) {
13417
- return import_node_fs12.default.readdirSync(layout.versionsDirectory).filter((name) => parseVersion(name) !== null);
13418
- }
13419
- function highestVersionBelow(layout, ceiling) {
13420
- const lower = installedVersions(layout).filter((version) => isNewerVersion(ceiling, version));
13421
- return lower.reduce((best, version) => best === null || isNewerVersion(version, best) ? version : best, null);
13422
- }
13423
- function moveLink(layout, version, environment) {
13424
- import_node_fs12.default.mkdirSync(layout.binDirectory, { recursive: true });
13425
- const temporaryLink = import_node_path8.default.posix.join(layout.binDirectory, `${LINK_TEMP_PREFIX}${process.pid}`);
13426
- import_node_fs12.default.rmSync(temporaryLink, { force: true });
13427
- import_node_fs12.default.symlinkSync(versionBinaryPath(layout, version), temporaryLink);
13428
- import_node_fs12.default.renameSync(temporaryLink, layout.link);
13429
- environment.fsyncDirectory(layout.binDirectory);
13430
- }
13431
- function convertPlainFile(layout, execPath, runningVersion, environment) {
13432
- const temporaryPath = import_node_path8.default.posix.join(layout.versionsDirectory, `${CONVERT_PREFIX}${process.pid}`);
13433
- import_node_fs12.default.copyFileSync(execPath, temporaryPath);
13434
- import_node_fs12.default.chmodSync(temporaryPath, EXECUTABLE_MODE3);
13435
- environment.fsyncFile(temporaryPath);
13436
- import_node_fs12.default.mkdirSync(versionDirectory(layout, runningVersion), { recursive: true });
13437
- import_node_fs12.default.renameSync(temporaryPath, versionBinaryPath(layout, runningVersion));
13438
- environment.fsyncDirectory(versionDirectory(layout, runningVersion));
13439
- }
13440
- function isNamedByService(layout, version, environment) {
13441
- return environment.serviceEntryText().includes(versionBinaryPath(layout, version));
13442
- }
13443
- function removeDeadProcessTemp(directory, prefix, environment) {
13444
- for (const name of import_node_fs12.default.readdirSync(directory)) {
13445
- const pidText = name.startsWith(prefix) ? name.slice(prefix.length) : "";
13446
- if (/^\d+$/.test(pidText) && !environment.isAlive(Number(pidText))) {
13447
- import_node_fs12.default.rmSync(import_node_path8.default.posix.join(directory, name), { force: true });
13448
- }
13449
- }
13450
- }
13451
- function removeStaleUnixFiles(layout, environment = realUnixSwapEnvironment) {
13452
- const locations = [
13453
- [layout.versionsDirectory, DOWNLOAD_PREFIX],
13454
- [layout.versionsDirectory, CONVERT_PREFIX],
13455
- [layout.binDirectory, LINK_TEMP_PREFIX]
13456
- ];
13457
- for (const [directory, prefix] of locations) {
13458
- try {
13459
- removeDeadProcessTemp(directory, prefix, environment);
13460
- } catch {
13461
- }
13462
- }
13463
- }
13464
- function pruneVersions(layout, environment = realUnixSwapEnvironment) {
13465
- removeStaleUnixFiles(layout, environment);
13466
- const target = readLinkVersion(layout);
13467
- if (target === null) return;
13468
- const keep = /* @__PURE__ */ new Set([target, highestVersionBelow(layout, target), environment.daemonVersion()]);
13469
- for (const version of installedVersions(layout)) {
13470
- if (keep.has(version) || isNamedByService(layout, version, environment)) continue;
13471
- import_node_fs12.default.rmSync(versionDirectory(layout, version), { recursive: true, force: true });
13472
- }
13473
- }
13474
- function replaceFailure(layout, error, running) {
13475
- return new UpdateError(
13476
- UpdateErrorCode.RenameFailed,
13477
- `Could not replace ${layout.link}: ${errorMessage(error)}. pinggy ${running} is unchanged.`
13478
- );
13479
- }
13480
- function installVersion(request2, environment = realUnixSwapEnvironment) {
13481
- const { layout, plainFileToConvert, runningVersion, newVersion } = request2;
13482
- try {
13483
- import_node_fs12.default.mkdirSync(layout.versionsDirectory, { recursive: true });
13484
- if (plainFileToConvert !== null) convertPlainFile(layout, plainFileToConvert, runningVersion, environment);
13485
- import_node_fs12.default.mkdirSync(versionDirectory(layout, newVersion), { recursive: true });
13486
- import_node_fs12.default.renameSync(unixDownloadPath(layout), versionBinaryPath(layout, newVersion));
13487
- environment.fsyncDirectory(versionDirectory(layout, newVersion));
13488
- moveLink(layout, newVersion, environment);
13489
- } catch (error) {
13490
- throw replaceFailure(layout, error, runningVersion);
13491
- }
13492
- try {
13493
- pruneVersions(layout, environment);
13494
- } catch {
13495
- }
13496
- }
13497
- function nothingToRollBack2() {
13498
- return new UpdateError(UpdateErrorCode.NothingToRollBack, "No previous version to go back to.");
13499
- }
13500
- function previousVersion(layout, current) {
13501
- try {
13502
- const version = highestVersionBelow(layout, current);
13503
- if (version !== null) return version;
13504
- } catch {
13505
- }
13506
- throw nothingToRollBack2();
13507
- }
13508
- function rollbackUnixVersion(layout, environment = realUnixSwapEnvironment) {
13509
- const current = readLinkVersion(layout);
13510
- if (current === null) throw nothingToRollBack2();
13511
- const previous = previousVersion(layout, current);
13512
- try {
13513
- moveLink(layout, previous, environment);
13514
- } catch (error) {
13515
- throw replaceFailure(layout, error, current);
13516
- }
13517
- writeUpdateState({ rolledBackFromVersion: current });
13518
- if (environment.daemonVersion() !== current && !isNamedByService(layout, current, environment)) {
13519
- import_node_fs12.default.rmSync(versionDirectory(layout, current), { recursive: true, force: true });
13520
- }
13521
- return { from: current, to: previous };
13522
- }
13523
- var import_node_fs12, import_node_path8, BINARY_NAME, DOWNLOAD_PREFIX, CONVERT_PREFIX, LINK_TEMP_PREFIX, EXECUTABLE_MODE3, realUnixSwapEnvironment;
13524
- var init_unixLinkSwap = __esm({
13525
- "src/update/unixLinkSwap.ts"() {
13526
- "use strict";
13527
- init_cjs_shims();
13528
- import_node_fs12 = __toESM(require("fs"), 1);
13529
- import_node_path8 = __toESM(require("path"), 1);
13530
- init_daemonManager();
13531
- init_serviceInstaller();
13532
- init_binaryUpdater();
13533
- init_latestRelease();
13534
- init_updateState();
13535
- init_util();
13536
- BINARY_NAME = "pinggy";
13537
- DOWNLOAD_PREFIX = "pinggy.download.";
13538
- CONVERT_PREFIX = "pinggy.convert.";
13539
- LINK_TEMP_PREFIX = "pinggy.link.";
13540
- EXECUTABLE_MODE3 = 493;
13541
- realUnixSwapEnvironment = {
13542
- fsyncFile: (filePath) => fsyncPath(filePath, "r+"),
13543
- fsyncDirectory: (directory) => fsyncPath(directory, "r"),
13544
- daemonVersion: () => getDaemonInfo()?.cliVersion,
13545
- serviceEntryText: readServiceEntryText,
13546
- isAlive: isProcessAlive
13547
- };
13548
- }
13549
- });
13550
-
13551
14225
  // src/update/applyUpdate.ts
13552
14226
  function windowsUpdateTarget(execPath, runBinary) {
13553
14227
  return {
@@ -13555,11 +14229,14 @@ function windowsUpdateTarget(execPath, runBinary) {
13555
14229
  rollbackBinaryPath: () => windowsInstallPaths(execPath).livePath,
13556
14230
  installedVersion: (runningVersion) => runningVersion,
13557
14231
  prepareDownload: () => void 0,
13558
- install: ({ newVersion, runningVersion }) => swapWindowsBinary(
13559
- { execPath, downloadPath: windowsDownloadPath(execPath), newVersion, runningVersion },
13560
- realWindowsFileOperations,
13561
- runBinary
13562
- ),
14232
+ install: async ({ newVersion, runningVersion }) => {
14233
+ await swapWindowsBinary(
14234
+ { execPath, downloadPath: windowsDownloadPath(execPath), newVersion, runningVersion },
14235
+ realWindowsFileOperations,
14236
+ runBinary
14237
+ );
14238
+ moveDeclinedInstallToVersion(execPath, newVersion);
14239
+ },
13563
14240
  rollback: async (runningVersion) => {
13564
14241
  const result = await rollbackWindowsBinary(
13565
14242
  { execPath, runningVersion, latestVersion: readUpdateState().latestVersion },
@@ -13579,7 +14256,7 @@ function unixUpdateTarget(kind, probe) {
13579
14256
  rollbackBinaryPath: (version) => versionBinaryPath(layout, version),
13580
14257
  installedVersion: (runningVersion) => readLinkVersion(layout) ?? runningVersion,
13581
14258
  prepareDownload: () => {
13582
- import_node_fs13.default.mkdirSync(layout.versionsDirectory, { recursive: true });
14259
+ import_node_fs16.default.mkdirSync(layout.versionsDirectory, { recursive: true });
13583
14260
  },
13584
14261
  install: ({ newVersion, runningVersion }) => installVersion({
13585
14262
  layout,
@@ -13608,12 +14285,12 @@ function downloadRelease(target, tag, assetName, runningVersion, dependencies =
13608
14285
  target.prepareDownload();
13609
14286
  return downloadAndVerify({ tag, assetName, tempPath: target.downloadPath, runningVersion }, dependencies);
13610
14287
  }
13611
- var import_node_fs13;
14288
+ var import_node_fs16;
13612
14289
  var init_applyUpdate = __esm({
13613
14290
  "src/update/applyUpdate.ts"() {
13614
14291
  "use strict";
13615
14292
  init_cjs_shims();
13616
- import_node_fs13 = __toESM(require("fs"), 1);
14293
+ import_node_fs16 = __toESM(require("fs"), 1);
13617
14294
  init_binaryUpdater();
13618
14295
  init_installKind();
13619
14296
  init_unixLinkSwap();
@@ -14244,14 +14921,14 @@ function removeStaleFilesFor(platform3, homeRealPath) {
14244
14921
  }
14245
14922
  function writeLogLine(logPath, line) {
14246
14923
  try {
14247
- import_node_fs14.default.appendFileSync(logPath, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}${import_node_os4.default.EOL}`);
14924
+ import_node_fs17.default.appendFileSync(logPath, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}${import_node_os6.default.EOL}`);
14248
14925
  } catch {
14249
14926
  }
14250
14927
  }
14251
14928
  function startLogFile(logPath) {
14252
14929
  try {
14253
14930
  ensurePinggyLogDir();
14254
- import_node_fs14.default.writeFileSync(logPath, "");
14931
+ import_node_fs17.default.writeFileSync(logPath, "");
14255
14932
  } catch {
14256
14933
  }
14257
14934
  }
@@ -14289,13 +14966,13 @@ function createUpdateChildEnvironment() {
14289
14966
  exitProcess: () => process.exit(0)
14290
14967
  };
14291
14968
  }
14292
- var import_node_fs14, import_node_os4, TIME_LIMIT_MILLIS, CHECK_TIMEOUT_MILLIS2, CHECK_INTERVAL_SECONDS2, MAX_FAILED_ATTEMPTS, Outcome;
14969
+ var import_node_fs17, import_node_os6, TIME_LIMIT_MILLIS, CHECK_TIMEOUT_MILLIS2, CHECK_INTERVAL_SECONDS2, MAX_FAILED_ATTEMPTS, Outcome;
14293
14970
  var init_updateChild = __esm({
14294
14971
  "src/update/updateChild.ts"() {
14295
14972
  "use strict";
14296
14973
  init_cjs_shims();
14297
- import_node_fs14 = __toESM(require("fs"), 1);
14298
- import_node_os4 = __toESM(require("os"), 1);
14974
+ import_node_fs17 = __toESM(require("fs"), 1);
14975
+ import_node_os6 = __toESM(require("os"), 1);
14299
14976
  init_daemonManager();
14300
14977
  init_configDir();
14301
14978
  init_util();
@@ -14356,13 +15033,15 @@ async function main() {
14356
15033
  process.exit(0);
14357
15034
  }
14358
15035
  if (isPackagedBinary() && (0, import_os10.platform)() === "win32") removeStaleUpdateFiles();
14359
- startBackgroundUpdate({ rawArgs, values, hasAnyArgs });
15036
+ const { questionShown } = await offerSelfInstall({ rawArgs, values });
15037
+ startBackgroundUpdate({ rawArgs, values, hasAnyArgs, installQuestionShown: questionShown });
14360
15038
  if (isSubcommand(rawArgs)) {
14361
15039
  await handleSubcommand(rawArgs);
14362
15040
  return;
14363
15041
  }
14364
15042
  if (!hasAnyArgs || values.help) {
14365
15043
  printHelpMessage();
15044
+ if (questionShown && !hasAnyArgs && (0, import_os10.platform)() === "win32") await waitForEnterToClose();
14366
15045
  return;
14367
15046
  }
14368
15047
  if (values.version) {
@@ -14390,6 +15069,7 @@ var init_main = __esm({
14390
15069
  init_nodePtyRuntime();
14391
15070
  init_windowsSwap();
14392
15071
  init_backgroundUpdate();
15072
+ init_selfInstall();
14393
15073
  init_handler();
14394
15074
  import_url2 = require("url");
14395
15075
  import_process = require("process");
@@ -14446,13 +15126,13 @@ var init_wsProtocol = __esm({
14446
15126
 
14447
15127
  // src/daemon/lifecycle/stateStore.ts
14448
15128
  function getStatePath() {
14449
- return import_node_path9.default.join(getPinggyConfigDir(), STATE_FILENAME);
15129
+ return import_node_path11.default.join(getPinggyConfigDir(), STATE_FILENAME);
14450
15130
  }
14451
15131
  function loadDaemonState() {
14452
15132
  const statePath = getStatePath();
14453
15133
  try {
14454
- if (!import_node_fs15.default.existsSync(statePath)) return null;
14455
- const raw = import_node_fs15.default.readFileSync(statePath, "utf-8");
15134
+ if (!import_node_fs18.default.existsSync(statePath)) return null;
15135
+ const raw = import_node_fs18.default.readFileSync(statePath, "utf-8");
14456
15136
  const state = JSON.parse(raw);
14457
15137
  if (!Array.isArray(state.tunnels)) return null;
14458
15138
  return state;
@@ -14466,8 +15146,8 @@ function persistDaemonState(state) {
14466
15146
  const tmpPath = statePath + ".tmp";
14467
15147
  try {
14468
15148
  state.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
14469
- import_node_fs15.default.writeFileSync(tmpPath, JSON.stringify(state, null, 2), "utf-8");
14470
- import_node_fs15.default.renameSync(tmpPath, statePath);
15149
+ import_node_fs18.default.writeFileSync(tmpPath, JSON.stringify(state, null, 2), "utf-8");
15150
+ import_node_fs18.default.renameSync(tmpPath, statePath);
14471
15151
  } catch (err) {
14472
15152
  logger.error("Failed to persist daemon state", { error: errorMessage(err) });
14473
15153
  }
@@ -14475,8 +15155,8 @@ function persistDaemonState(state) {
14475
15155
  function clearDaemonState() {
14476
15156
  const statePath = getStatePath();
14477
15157
  try {
14478
- if (import_node_fs15.default.existsSync(statePath)) {
14479
- import_node_fs15.default.unlinkSync(statePath);
15158
+ if (import_node_fs18.default.existsSync(statePath)) {
15159
+ import_node_fs18.default.unlinkSync(statePath);
14480
15160
  }
14481
15161
  } catch {
14482
15162
  }
@@ -14488,13 +15168,13 @@ function addTunnelToState(state, tunnel) {
14488
15168
  function removeTunnelFromState(state, tunnelId) {
14489
15169
  state.tunnels = state.tunnels.filter((t) => t.tunnelId !== tunnelId);
14490
15170
  }
14491
- var import_node_fs15, import_node_path9, STATE_FILENAME;
15171
+ var import_node_fs18, import_node_path11, STATE_FILENAME;
14492
15172
  var init_stateStore = __esm({
14493
15173
  "src/daemon/lifecycle/stateStore.ts"() {
14494
15174
  "use strict";
14495
15175
  init_cjs_shims();
14496
- import_node_fs15 = __toESM(require("fs"), 1);
14497
- import_node_path9 = __toESM(require("path"), 1);
15176
+ import_node_fs18 = __toESM(require("fs"), 1);
15177
+ import_node_path11 = __toESM(require("path"), 1);
14498
15178
  init_configDir();
14499
15179
  init_logger();
14500
15180
  init_util();
@@ -14513,18 +15193,19 @@ function parseBody(method, body) {
14513
15193
  if (!body) return {};
14514
15194
  return JSON.parse(body);
14515
15195
  }
14516
- var import_node_http3, import_node_fs16, import_node_path10, import_ws4, IPCServer;
15196
+ var import_node_http3, import_node_fs19, import_node_path12, import_ws4, IPCServer;
14517
15197
  var init_ipcServer = __esm({
14518
15198
  "src/daemon/ipc/ipcServer.ts"() {
14519
15199
  "use strict";
14520
15200
  init_cjs_shims();
14521
15201
  import_node_http3 = __toESM(require("http"), 1);
14522
- import_node_fs16 = __toESM(require("fs"), 1);
14523
- import_node_path10 = __toESM(require("path"), 1);
15202
+ import_node_fs19 = __toESM(require("fs"), 1);
15203
+ import_node_path12 = __toESM(require("path"), 1);
14524
15204
  import_ws4 = require("ws");
14525
15205
  init_main();
14526
15206
  init_logger();
14527
15207
  init_tunnelLogger();
15208
+ init_nativeLog();
14528
15209
  init_configStore();
14529
15210
  init_configDir();
14530
15211
  init_logPaths();
@@ -14663,6 +15344,8 @@ var init_ipcServer = __esm({
14663
15344
  [Route.SetTunnelLogging]: (req) => {
14664
15345
  if (typeof req.enabled !== "boolean") throw new Error("Missing 'enabled' boolean");
14665
15346
  setTunnelLoggingEnabled(req.enabled);
15347
+ setNativeLogging(req.enabled);
15348
+ TunnelManager.getInstance().applyLogLevelToActiveTunnels(getLogLevel());
14666
15349
  return { enabled: isTunnelLoggingEnabled() };
14667
15350
  },
14668
15351
  [Route.GetLogPaths]: async () => {
@@ -14680,8 +15363,8 @@ var init_ipcServer = __esm({
14680
15363
  if (n) activeNames.add(n);
14681
15364
  }
14682
15365
  for (const file of files) {
14683
- const filePath = import_node_path10.default.join(logDir, file);
14684
- const stat = import_node_fs16.default.statSync(filePath);
15366
+ const filePath = import_node_path12.default.join(logDir, file);
15367
+ const stat = import_node_fs19.default.statSync(filePath);
14685
15368
  const parsed = parseTunnelLogFilename(file);
14686
15369
  if (!parsed) continue;
14687
15370
  const running = parsed.tunnelId ? activeIds.has(parsed.tunnelId) : parsed.name ? activeNames.has(parsed.name) : false;
@@ -15357,7 +16040,7 @@ var init_deviceAgentHost = __esm({
15357
16040
  // src/daemon/lifecycle/daemonLock.ts
15358
16041
  function readLock(lockPath) {
15359
16042
  try {
15360
- const record = JSON.parse(import_node_fs17.default.readFileSync(lockPath, "utf-8"));
16043
+ const record = JSON.parse(import_node_fs20.default.readFileSync(lockPath, "utf-8"));
15361
16044
  return Number.isInteger(record.pid) && record.pid > 0 ? record : null;
15362
16045
  } catch {
15363
16046
  return null;
@@ -15365,18 +16048,18 @@ function readLock(lockPath) {
15365
16048
  }
15366
16049
  function isUnreadableLockOld(lockPath) {
15367
16050
  try {
15368
- return Date.now() - import_node_fs17.default.statSync(lockPath).mtimeMs > UNREADABLE_LOCK_GRACE_MILLIS;
16051
+ return Date.now() - import_node_fs20.default.statSync(lockPath).mtimeMs > UNREADABLE_LOCK_GRACE_MILLIS;
15369
16052
  } catch {
15370
16053
  return true;
15371
16054
  }
15372
16055
  }
15373
16056
  function isStale(lockPath, holder) {
15374
16057
  if (!holder) return isUnreadableLockOld(lockPath);
15375
- return startedBeforeBoot(holder.started_at) || !isProcessAlive(holder.pid);
16058
+ return startedInEarlierBoot(holder.boot_id, holder.started_at) || !isProcessAlive(holder.pid);
15376
16059
  }
15377
16060
  function createLock2(lockPath, record) {
15378
16061
  try {
15379
- import_node_fs17.default.writeFileSync(lockPath, JSON.stringify(record), { encoding: "utf-8", flag: "wx" });
16062
+ import_node_fs20.default.writeFileSync(lockPath, JSON.stringify(record), { encoding: "utf-8", flag: "wx" });
15380
16063
  return true;
15381
16064
  } catch (err) {
15382
16065
  if (err.code === "EEXIST") return false;
@@ -15386,29 +16069,34 @@ function createLock2(lockPath, record) {
15386
16069
  function acquireDaemonLock() {
15387
16070
  ensurePinggyConfigDir();
15388
16071
  const lockPath = getDaemonLockPath();
15389
- const record = { pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() };
16072
+ const record = {
16073
+ pid: process.pid,
16074
+ started_at: (/* @__PURE__ */ new Date()).toISOString(),
16075
+ boot_id: currentBootId() ?? void 0
16076
+ };
15390
16077
  if (createLock2(lockPath, record)) return true;
15391
16078
  const holder = readLock(lockPath);
15392
16079
  if (holder?.pid === process.pid) return true;
15393
16080
  if (!isStale(lockPath, holder)) return false;
15394
16081
  logger.info("Stale daemon.lock found, replacing it", { stalePid: holder?.pid });
15395
- import_node_fs17.default.rmSync(lockPath, { force: true });
16082
+ import_node_fs20.default.rmSync(lockPath, { force: true });
15396
16083
  return createLock2(lockPath, record);
15397
16084
  }
15398
16085
  function releaseDaemonLock() {
15399
16086
  const lockPath = getDaemonLockPath();
15400
16087
  if (readLock(lockPath)?.pid === process.pid) {
15401
- import_node_fs17.default.rmSync(lockPath, { force: true });
16088
+ import_node_fs20.default.rmSync(lockPath, { force: true });
15402
16089
  }
15403
16090
  }
15404
- var import_node_fs17, UNREADABLE_LOCK_GRACE_MILLIS;
16091
+ var import_node_fs20, UNREADABLE_LOCK_GRACE_MILLIS;
15405
16092
  var init_daemonLock = __esm({
15406
16093
  "src/daemon/lifecycle/daemonLock.ts"() {
15407
16094
  "use strict";
15408
16095
  init_cjs_shims();
15409
- import_node_fs17 = __toESM(require("fs"), 1);
16096
+ import_node_fs20 = __toESM(require("fs"), 1);
15410
16097
  init_configDir();
15411
16098
  init_daemonManager();
16099
+ init_bootId();
15412
16100
  init_logger();
15413
16101
  UNREADABLE_LOCK_GRACE_MILLIS = 1e4;
15414
16102
  }
@@ -15436,14 +16124,14 @@ function writeDaemonInfo(info) {
15436
16124
  ensurePinggyConfigDir();
15437
16125
  const infoPath = getDaemonInfoPath();
15438
16126
  const tmpPath = infoPath + ".tmp";
15439
- import_node_fs18.default.writeFileSync(tmpPath, JSON.stringify(info, null, 2), "utf-8");
15440
- import_node_fs18.default.renameSync(tmpPath, infoPath);
16127
+ import_node_fs21.default.writeFileSync(tmpPath, JSON.stringify(info, null, 2), "utf-8");
16128
+ import_node_fs21.default.renameSync(tmpPath, infoPath);
15441
16129
  }
15442
16130
  function removeDaemonInfo() {
15443
16131
  try {
15444
16132
  const infoPath = getDaemonInfoPath();
15445
- const info = JSON.parse(import_node_fs18.default.readFileSync(infoPath, "utf-8"));
15446
- if (info.pid === process.pid) import_node_fs18.default.unlinkSync(infoPath);
16133
+ const info = JSON.parse(import_node_fs21.default.readFileSync(infoPath, "utf-8"));
16134
+ if (info.pid === process.pid) import_node_fs21.default.unlinkSync(infoPath);
15447
16135
  } catch {
15448
16136
  }
15449
16137
  }
@@ -15673,7 +16361,8 @@ async function runDaemonChild(opts = {}) {
15673
16361
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
15674
16362
  host: daemonHost,
15675
16363
  ipcVersion: IPC_VERSION,
15676
- cliVersion: getVersion()
16364
+ cliVersion: getVersion(),
16365
+ bootId: currentBootId() ?? void 0
15677
16366
  };
15678
16367
  writeDaemonInfo(info);
15679
16368
  logger.info("Daemon info written", info);
@@ -15711,12 +16400,12 @@ async function runDaemonChild(opts = {}) {
15711
16400
  throw err;
15712
16401
  }
15713
16402
  }
15714
- var import_node_fs18, daemonState, daemonHost, sessionTrackerRef;
16403
+ var import_node_fs21, daemonState, daemonHost, sessionTrackerRef;
15715
16404
  var init_daemonChild = __esm({
15716
16405
  "src/daemon/lifecycle/daemonChild.ts"() {
15717
16406
  "use strict";
15718
16407
  init_cjs_shims();
15719
- import_node_fs18 = __toESM(require("fs"), 1);
16408
+ import_node_fs21 = __toESM(require("fs"), 1);
15720
16409
  init_ipcServer();
15721
16410
  init_sessionTracker();
15722
16411
  init_stateStore();
@@ -15732,6 +16421,7 @@ var init_daemonChild = __esm({
15732
16421
  init_util();
15733
16422
  init_ipcRoutes();
15734
16423
  init_daemonLock();
16424
+ init_bootId();
15735
16425
  daemonState = { tunnels: [], lastUpdated: "" };
15736
16426
  daemonHost = DaemonHost.CLI;
15737
16427
  sessionTrackerRef = null;
@@ -15747,21 +16437,16 @@ function isProcessAlive(pid) {
15747
16437
  return err.code === "EPERM";
15748
16438
  }
15749
16439
  }
15750
- function startedBeforeBoot(startedAt) {
15751
- const startedAtMillis = Date.parse(startedAt);
15752
- const bootMillis = Date.now() - import_node_os5.default.uptime() * 1e3;
15753
- return Number.isNaN(startedAtMillis) || startedAtMillis < bootMillis - BOOT_TIME_TOLERANCE_MILLIS;
15754
- }
15755
16440
  function getDaemonInfo() {
15756
16441
  const infoPath = getDaemonInfoPath();
15757
- if (!import_node_fs19.default.existsSync(infoPath)) return null;
16442
+ if (!import_node_fs22.default.existsSync(infoPath)) return null;
15758
16443
  try {
15759
- const data = JSON.parse(import_node_fs19.default.readFileSync(infoPath, "utf-8"));
16444
+ const data = JSON.parse(import_node_fs22.default.readFileSync(infoPath, "utf-8"));
15760
16445
  if (!data.pid || !data.port) return null;
15761
- if (startedBeforeBoot(data.startedAt) || !isProcessAlive(data.pid)) {
16446
+ if (startedInEarlierBoot(data.bootId, data.startedAt) || !isProcessAlive(data.pid)) {
15762
16447
  logger.info("Stale daemon.json found, cleaning up", { stalePid: data.pid });
15763
16448
  try {
15764
- import_node_fs19.default.unlinkSync(infoPath);
16449
+ import_node_fs22.default.unlinkSync(infoPath);
15765
16450
  } catch {
15766
16451
  }
15767
16452
  return null;
@@ -15796,7 +16481,13 @@ function printDaemonVersionNoticeOnce(info, restartInstruction = serviceRestartI
15796
16481
  printer_default.print(`${runs} Run ${instruction} to start ${running}. This stops all running tunnels.`);
15797
16482
  }
15798
16483
  }
15799
- function getDaemonSpawnArgs(isPackaged = isPackagedBinary(), executableExists = import_node_fs19.default.existsSync(process.execPath), linkPath = unixLayoutPaths(import_node_os5.default.homedir()).link) {
16484
+ function startDaemonFromInstalledBinary(binaryPath) {
16485
+ installedBinaryForDaemon = binaryPath;
16486
+ }
16487
+ function getDaemonSpawnArgs(isPackaged = isPackagedBinary(), executableExists = import_node_fs22.default.existsSync(process.execPath), linkPath = unixLayoutPaths(import_node_os7.default.homedir()).link, installedBinary = installedBinaryForDaemon) {
16488
+ if (isPackaged && installedBinary) {
16489
+ return { command: installedBinary, args: ["--_daemon-child"], env: { ...process.env } };
16490
+ }
15800
16491
  if (isPackaged && !executableExists) {
15801
16492
  return { command: linkPath, args: ["--_daemon-child"], env: { ...process.env } };
15802
16493
  }
@@ -15816,11 +16507,11 @@ async function startDaemon() {
15816
16507
  let stderrOutput = "";
15817
16508
  let exited = false;
15818
16509
  let exitCode = null;
15819
- const child = (0, import_node_child_process4.spawn)(command, args, {
16510
+ const child = (0, import_node_child_process6.spawn)(command, args, {
15820
16511
  detached: true,
15821
16512
  stdio: ["ignore", "ignore", "pipe"],
15822
16513
  env,
15823
- ...import_node_os5.default.platform() === "win32" ? { windowsHide: true } : {}
16514
+ ...import_node_os7.default.platform() === "win32" ? { windowsHide: true } : {}
15824
16515
  });
15825
16516
  child.stderr?.on("data", (chunk) => {
15826
16517
  stderrOutput += chunk.toString("utf-8");
@@ -15940,7 +16631,7 @@ async function stopDaemon() {
15940
16631
  } catch (e) {
15941
16632
  return { ok: false, error: `Failed to reach daemon: ${errorMessage(e)}` };
15942
16633
  }
15943
- const exited = await waitForExit(info.pid, 5e3);
16634
+ const exited = await waitForExit2(info.pid, 5e3);
15944
16635
  if (!exited) {
15945
16636
  const detail = daemonErrors.length > 0 ? ` Daemon reported: ${daemonErrors.join("; ")}` : "";
15946
16637
  return { ok: false, error: `Daemon PID ${info.pid} did not exit within 5s.${detail}` };
@@ -15950,7 +16641,7 @@ async function stopDaemon() {
15950
16641
  }
15951
16642
  return { ok: true };
15952
16643
  }
15953
- async function waitForExit(pid, timeoutMs) {
16644
+ async function waitForExit2(pid, timeoutMs) {
15954
16645
  const deadline = Date.now() + timeoutMs;
15955
16646
  while (Date.now() < deadline) {
15956
16647
  if (!isProcessAlive(pid)) return true;
@@ -15958,14 +16649,14 @@ async function waitForExit(pid, timeoutMs) {
15958
16649
  }
15959
16650
  return !isProcessAlive(pid);
15960
16651
  }
15961
- var import_node_os5, import_node_fs19, import_node_child_process4, inProcessHandle, DAEMON_SPAWN_TIMEOUT_MS, DAEMON_POLL_INTERVAL_MS, SPAWN_FAILED_EXIT_CODE, DAEMON_STOP_INSTRUCTION, BOOT_TIME_TOLERANCE_MILLIS;
16652
+ var import_node_os7, import_node_fs22, import_node_child_process6, inProcessHandle, DAEMON_SPAWN_TIMEOUT_MS, DAEMON_POLL_INTERVAL_MS, SPAWN_FAILED_EXIT_CODE, DAEMON_STOP_INSTRUCTION, installedBinaryForDaemon;
15962
16653
  var init_daemonManager = __esm({
15963
16654
  "src/daemon/lifecycle/daemonManager.ts"() {
15964
16655
  "use strict";
15965
16656
  init_cjs_shims();
15966
- import_node_os5 = __toESM(require("os"), 1);
15967
- import_node_fs19 = __toESM(require("fs"), 1);
15968
- import_node_child_process4 = require("child_process");
16657
+ import_node_os7 = __toESM(require("os"), 1);
16658
+ import_node_fs22 = __toESM(require("fs"), 1);
16659
+ import_node_child_process6 = require("child_process");
15969
16660
  init_configDir();
15970
16661
  init_ipcRoutes();
15971
16662
  init_logger();
@@ -15976,12 +16667,13 @@ var init_daemonManager = __esm({
15976
16667
  init_serviceInstaller();
15977
16668
  init_nodePtyRuntime();
15978
16669
  init_installKind();
16670
+ init_bootId();
15979
16671
  inProcessHandle = null;
15980
16672
  DAEMON_SPAWN_TIMEOUT_MS = 8e3;
15981
16673
  DAEMON_POLL_INTERVAL_MS = 200;
15982
16674
  SPAWN_FAILED_EXIT_CODE = -1;
15983
16675
  DAEMON_STOP_INSTRUCTION = '"pinggy daemon stop"';
15984
- BOOT_TIME_TOLERANCE_MILLIS = 6e4;
16676
+ installedBinaryForDaemon = null;
15985
16677
  }
15986
16678
  });
15987
16679