pinggy 0.6.9 → 0.6.11

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
@@ -3130,11 +3130,11 @@ var init_ipcClient = __esm({
3130
3130
  call(key, body, timeoutMs) {
3131
3131
  const spaceIdx = key.indexOf(" ");
3132
3132
  const method = key.slice(0, spaceIdx);
3133
- const path20 = key.slice(spaceIdx + 1);
3133
+ const path23 = key.slice(spaceIdx + 1);
3134
3134
  const payload = method === "GET" ? void 0 : JSON.stringify(body ?? {});
3135
- return this.request(method, path20, payload, timeoutMs);
3135
+ return this.request(method, path23, payload, timeoutMs);
3136
3136
  }
3137
- request(method, path20, body, timeoutMs) {
3137
+ request(method, path23, body, timeoutMs) {
3138
3138
  return new Promise((resolve, reject) => {
3139
3139
  const headers = {
3140
3140
  "X-Pinggy-Origin": this.origin
@@ -3147,10 +3147,14 @@ var init_ipcClient = __esm({
3147
3147
  {
3148
3148
  hostname: "127.0.0.1",
3149
3149
  port: this.port,
3150
- path: path20,
3150
+ path: path23,
3151
3151
  method,
3152
3152
  headers,
3153
- timeout: timeoutMs ?? REQUEST_TIMEOUT_MS
3153
+ timeout: timeoutMs ?? REQUEST_TIMEOUT_MS,
3154
+ // A new connection per request. The shared agent keeps a socket for reuse, and the
3155
+ // daemon closes an idle one after 5 s, which is also the heartbeat interval: a ping
3156
+ // written to a socket the daemon is closing fails with ECONNRESET.
3157
+ agent: false
3154
3158
  },
3155
3159
  (res) => {
3156
3160
  const chunks = [];
@@ -3494,7 +3498,7 @@ var init_installKind = __esm({
3494
3498
  }
3495
3499
  });
3496
3500
 
3497
- // src/daemon/lifecycle/serviceInstaller.ts
3501
+ // src/daemon/lifecycle/servicePaths.ts
3498
3502
  function installerBinaryPath(platform3, home, env) {
3499
3503
  if (platform3 === "win32") {
3500
3504
  const localAppData = env.LOCALAPPDATA || import_node_path4.default.win32.join(home, "AppData", "Local");
@@ -3502,6 +3506,29 @@ function installerBinaryPath(platform3, home, env) {
3502
3506
  }
3503
3507
  return import_node_path4.default.posix.join(home, ".pinggy", "bin", "pinggy");
3504
3508
  }
3509
+ function systemdServicePath(home) {
3510
+ return import_node_path4.default.posix.join(home, ".config", "systemd", "user", `${SYSTEMD_SERVICE_NAME}.service`);
3511
+ }
3512
+ function launchdPlistPath(home) {
3513
+ return import_node_path4.default.posix.join(home, "Library", "LaunchAgents", `${SERVICE_LABEL}.plist`);
3514
+ }
3515
+ function autostartFilePath(platform3, home) {
3516
+ if (platform3 === "linux") return systemdServicePath(home);
3517
+ if (platform3 === "darwin") return launchdPlistPath(home);
3518
+ return null;
3519
+ }
3520
+ var import_node_path4, SERVICE_LABEL, SYSTEMD_SERVICE_NAME;
3521
+ var init_servicePaths = __esm({
3522
+ "src/daemon/lifecycle/servicePaths.ts"() {
3523
+ "use strict";
3524
+ init_cjs_shims();
3525
+ import_node_path4 = __toESM(require("path"), 1);
3526
+ SERVICE_LABEL = "io.pinggy.agent";
3527
+ SYSTEMD_SERVICE_NAME = "pinggy";
3528
+ }
3529
+ });
3530
+
3531
+ // src/daemon/lifecycle/serviceInstaller.ts
3505
3532
  function realPath(p) {
3506
3533
  try {
3507
3534
  return import_node_fs5.default.realpathSync(p);
@@ -3573,8 +3600,7 @@ function toolError(err) {
3573
3600
  return stderr ? stderr.replace(/^ERROR:\s*/i, "") : errorMessage(err);
3574
3601
  }
3575
3602
  function getSystemdServicePath() {
3576
- const dir = import_node_path4.default.join(import_node_os2.default.homedir(), ".config", "systemd", "user");
3577
- return import_node_path4.default.join(dir, `${SYSTEMD_SERVICE_NAME}.service`);
3603
+ return systemdServicePath(import_node_os2.default.homedir());
3578
3604
  }
3579
3605
  function generateSystemdUnit(program) {
3580
3606
  const execStart = `${program} --_daemon-child`;
@@ -3595,7 +3621,7 @@ WantedBy=default.target
3595
3621
  }
3596
3622
  function installSystemd(program) {
3597
3623
  const servicePath = getSystemdServicePath();
3598
- const dir = import_node_path4.default.dirname(servicePath);
3624
+ const dir = import_node_path5.default.dirname(servicePath);
3599
3625
  import_node_fs5.default.mkdirSync(dir, { recursive: true });
3600
3626
  import_node_fs5.default.writeFileSync(servicePath, generateSystemdUnit(program), "utf-8");
3601
3627
  (0, import_node_child_process.execSync)("systemctl --user daemon-reload", QUIET);
@@ -3643,7 +3669,7 @@ function uninstallSystemd() {
3643
3669
  }
3644
3670
  }
3645
3671
  function getLaunchdPlistPath() {
3646
- return import_node_path4.default.join(import_node_os2.default.homedir(), "Library", "LaunchAgents", `${SERVICE_LABEL}.plist`);
3672
+ return launchdPlistPath(import_node_os2.default.homedir());
3647
3673
  }
3648
3674
  function generateLaunchdPlist(program) {
3649
3675
  const allArgs = [program, "--_daemon-child"];
@@ -3669,7 +3695,7 @@ ${programArgs}
3669
3695
  }
3670
3696
  function installLaunchd(program) {
3671
3697
  const plistPath = getLaunchdPlistPath();
3672
- const dir = import_node_path4.default.dirname(plistPath);
3698
+ const dir = import_node_path5.default.dirname(plistPath);
3673
3699
  import_node_fs5.default.mkdirSync(dir, { recursive: true });
3674
3700
  import_node_fs5.default.writeFileSync(plistPath, generateLaunchdPlist(program), "utf-8");
3675
3701
  const uid = process.getuid?.() ?? 501;
@@ -3756,7 +3782,7 @@ function generateTaskXml(program, userId) {
3756
3782
  }
3757
3783
  function createWindowsTask(program) {
3758
3784
  const xml = generateTaskXml(program, getWindowsUserId());
3759
- const tmpPath = import_node_path4.default.join(import_node_os2.default.tmpdir(), `${WINDOWS_TASK_NAME}.xml`);
3785
+ const tmpPath = import_node_path5.default.join(import_node_os2.default.tmpdir(), `${WINDOWS_TASK_NAME}.xml`);
3760
3786
  import_node_fs5.default.writeFileSync(tmpPath, "\uFEFF" + xml, "utf16le");
3761
3787
  try {
3762
3788
  (0, import_node_child_process.execFileSync)("schtasks", ["/Create", "/TN", WINDOWS_TASK_NAME, "/XML", tmpPath, "/F"], QUIET);
@@ -3892,22 +3918,22 @@ async function uninstallService() {
3892
3918
  process.exit(1);
3893
3919
  }
3894
3920
  }
3895
- var import_node_os2, import_node_fs5, import_node_path4, import_node_child_process, SERVICE_LABEL, SYSTEMD_SERVICE_NAME, SERVICE_ANY_LOCATION_ENV, QUIET, WINDOWS_TASK_NAME, SERVICE_QUERY_TIMEOUT_MILLIS;
3921
+ var import_node_os2, import_node_fs5, import_node_path5, import_node_child_process, SERVICE_ANY_LOCATION_ENV, QUIET, WINDOWS_TASK_NAME, SERVICE_QUERY_TIMEOUT_MILLIS;
3896
3922
  var init_serviceInstaller = __esm({
3897
3923
  "src/daemon/lifecycle/serviceInstaller.ts"() {
3898
3924
  "use strict";
3899
3925
  init_cjs_shims();
3900
3926
  import_node_os2 = __toESM(require("os"), 1);
3901
3927
  import_node_fs5 = __toESM(require("fs"), 1);
3902
- import_node_path4 = __toESM(require("path"), 1);
3928
+ import_node_path5 = __toESM(require("path"), 1);
3903
3929
  import_node_child_process = require("child_process");
3904
3930
  init_logger();
3905
3931
  init_printer();
3906
3932
  init_util();
3907
3933
  init_daemonManager();
3908
3934
  init_installKind();
3909
- SERVICE_LABEL = "io.pinggy.agent";
3910
- SYSTEMD_SERVICE_NAME = "pinggy";
3935
+ init_servicePaths();
3936
+ init_servicePaths();
3911
3937
  SERVICE_ANY_LOCATION_ENV = "PINGGY_SERVICE_ANY_LOCATION";
3912
3938
  QUIET = { stdio: ["ignore", "ignore", "pipe"] };
3913
3939
  WINDOWS_TASK_NAME = "PinggyDaemon";
@@ -4028,6 +4054,8 @@ var init_options = __esm({
4028
4054
  all: { type: "boolean", description: "Start all auto-start tunnels" },
4029
4055
  // `pinggy device login` and `connect` only. Their agent runs in the daemon unless this is set.
4030
4056
  foreground: { type: "boolean", description: "Run the device agent in this terminal", hidden: true },
4057
+ // `pinggy device login`, `connect` and `start` only: on or off, the answer to the file access question.
4058
+ files: { type: "string", description: "Allow file access from the dashboard: on or off", hidden: true },
4031
4059
  // `pinggy update` only.
4032
4060
  check: { type: "boolean", description: "Print the latest version and change nothing", hidden: true },
4033
4061
  rollback: { type: "boolean", description: "Go back to the previous version", hidden: true },
@@ -4469,7 +4497,7 @@ function noDiskSpace(running) {
4469
4497
  }
4470
4498
  function ensureFreeSpace(request2, contentLength, dependencies) {
4471
4499
  const factor = request2.assetName.endsWith(".exe") ? WINDOWS_FREE_SPACE_FACTOR : UNIX_FREE_SPACE_FACTOR;
4472
- const freeBytes = dependencies.freeBytes(import_node_path5.default.dirname(request2.tempPath));
4500
+ const freeBytes = dependencies.freeBytes(import_node_path6.default.dirname(request2.tempPath));
4473
4501
  if (freeBytes !== null && freeBytes < contentLength * factor + FREE_SPACE_MARGIN_BYTES) {
4474
4502
  throw noDiskSpace(request2.runningVersion);
4475
4503
  }
@@ -4545,7 +4573,7 @@ async function downloadAndVerify(request2, dependencies = defaultDownloadDepende
4545
4573
  throw error;
4546
4574
  }
4547
4575
  }
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;
4576
+ var import_node_crypto2, import_node_child_process3, import_node_fs7, import_node_path6, 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;
4549
4577
  var init_binaryUpdater = __esm({
4550
4578
  "src/update/binaryUpdater.ts"() {
4551
4579
  "use strict";
@@ -4553,7 +4581,7 @@ var init_binaryUpdater = __esm({
4553
4581
  import_node_crypto2 = __toESM(require("crypto"), 1);
4554
4582
  import_node_child_process3 = require("child_process");
4555
4583
  import_node_fs7 = __toESM(require("fs"), 1);
4556
- import_node_path5 = __toESM(require("path"), 1);
4584
+ import_node_path6 = __toESM(require("path"), 1);
4557
4585
  init_latestRelease();
4558
4586
  init_util();
4559
4587
  UpdateErrorCode = {
@@ -4745,17 +4773,17 @@ function removeStaleUpdateFiles(execPath = process.execPath, operations = realSt
4745
4773
  }
4746
4774
  }
4747
4775
  }
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;
4776
+ var import_node_fs8, import_node_path7, 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;
4749
4777
  var init_windowsSwap = __esm({
4750
4778
  "src/update/windowsSwap.ts"() {
4751
4779
  "use strict";
4752
4780
  init_cjs_shims();
4753
4781
  import_node_fs8 = __toESM(require("fs"), 1);
4754
- import_node_path6 = __toESM(require("path"), 1);
4782
+ import_node_path7 = __toESM(require("path"), 1);
4755
4783
  init_daemonManager();
4756
4784
  init_binaryUpdater();
4757
4785
  init_util();
4758
- WINDOWS_PATH = import_node_path6.default.win32;
4786
+ WINDOWS_PATH = import_node_path7.default.win32;
4759
4787
  BACKUP_MARKER = ".prev";
4760
4788
  NEW_FILE_SUFFIX = ".new.exe";
4761
4789
  OLD_FILE_SUFFIX = ".old";
@@ -5044,17 +5072,17 @@ function fsyncPath(target, flags) {
5044
5072
  }
5045
5073
  }
5046
5074
  function unixDownloadPath(layout) {
5047
- return import_node_path7.default.posix.join(layout.versionsDirectory, `${DOWNLOAD_PREFIX}${process.pid}`);
5075
+ return import_node_path8.default.posix.join(layout.versionsDirectory, `${DOWNLOAD_PREFIX}${process.pid}`);
5048
5076
  }
5049
5077
  function versionDirectory(layout, version) {
5050
- return import_node_path7.default.posix.join(layout.versionsDirectory, version);
5078
+ return import_node_path8.default.posix.join(layout.versionsDirectory, version);
5051
5079
  }
5052
5080
  function versionBinaryPath(layout, version) {
5053
- return import_node_path7.default.posix.join(versionDirectory(layout, version), BINARY_NAME);
5081
+ return import_node_path8.default.posix.join(versionDirectory(layout, version), BINARY_NAME);
5054
5082
  }
5055
5083
  function readLinkVersion(layout) {
5056
5084
  try {
5057
- const version = import_node_path7.default.posix.basename(import_node_path7.default.posix.dirname(import_node_fs11.default.readlinkSync(layout.link)));
5085
+ const version = import_node_path8.default.posix.basename(import_node_path8.default.posix.dirname(import_node_fs11.default.readlinkSync(layout.link)));
5058
5086
  return parseVersion(version) ? version : null;
5059
5087
  } catch {
5060
5088
  return null;
@@ -5069,14 +5097,14 @@ function highestVersionBelow(layout, ceiling) {
5069
5097
  }
5070
5098
  function moveLink(layout, version, environment) {
5071
5099
  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}`);
5100
+ const temporaryLink = import_node_path8.default.posix.join(layout.binDirectory, `${LINK_TEMP_PREFIX}${process.pid}`);
5073
5101
  import_node_fs11.default.rmSync(temporaryLink, { force: true });
5074
5102
  import_node_fs11.default.symlinkSync(versionBinaryPath(layout, version), temporaryLink);
5075
5103
  import_node_fs11.default.renameSync(temporaryLink, layout.link);
5076
5104
  environment.fsyncDirectory(layout.binDirectory);
5077
5105
  }
5078
5106
  function convertPlainFile(layout, execPath, runningVersion, environment) {
5079
- const temporaryPath = import_node_path7.default.posix.join(layout.versionsDirectory, `${CONVERT_PREFIX}${process.pid}`);
5107
+ const temporaryPath = import_node_path8.default.posix.join(layout.versionsDirectory, `${CONVERT_PREFIX}${process.pid}`);
5080
5108
  import_node_fs11.default.copyFileSync(execPath, temporaryPath);
5081
5109
  import_node_fs11.default.chmodSync(temporaryPath, EXECUTABLE_MODE3);
5082
5110
  environment.fsyncFile(temporaryPath);
@@ -5091,7 +5119,7 @@ function removeDeadProcessTemp(directory, prefix, environment) {
5091
5119
  for (const name of import_node_fs11.default.readdirSync(directory)) {
5092
5120
  const pidText = name.startsWith(prefix) ? name.slice(prefix.length) : "";
5093
5121
  if (/^\d+$/.test(pidText) && !environment.isAlive(Number(pidText))) {
5094
- import_node_fs11.default.rmSync(import_node_path7.default.posix.join(directory, name), { force: true });
5122
+ import_node_fs11.default.rmSync(import_node_path8.default.posix.join(directory, name), { force: true });
5095
5123
  }
5096
5124
  }
5097
5125
  }
@@ -5167,13 +5195,13 @@ function rollbackUnixVersion(layout, environment = realUnixSwapEnvironment) {
5167
5195
  }
5168
5196
  return { from: current, to: previous };
5169
5197
  }
5170
- var import_node_fs11, import_node_path7, BINARY_NAME, DOWNLOAD_PREFIX, CONVERT_PREFIX, LINK_TEMP_PREFIX, EXECUTABLE_MODE3, realUnixSwapEnvironment;
5198
+ var import_node_fs11, import_node_path8, BINARY_NAME, DOWNLOAD_PREFIX, CONVERT_PREFIX, LINK_TEMP_PREFIX, EXECUTABLE_MODE3, realUnixSwapEnvironment;
5171
5199
  var init_unixLinkSwap = __esm({
5172
5200
  "src/update/unixLinkSwap.ts"() {
5173
5201
  "use strict";
5174
5202
  init_cjs_shims();
5175
5203
  import_node_fs11 = __toESM(require("fs"), 1);
5176
- import_node_path7 = __toESM(require("path"), 1);
5204
+ import_node_path8 = __toESM(require("path"), 1);
5177
5205
  init_daemonManager();
5178
5206
  init_serviceInstaller();
5179
5207
  init_binaryUpdater();
@@ -5197,7 +5225,7 @@ var init_unixLinkSwap = __esm({
5197
5225
 
5198
5226
  // src/install/pinggyOnPath.ts
5199
5227
  function pathModule(platform3) {
5200
- return platform3 === "win32" ? import_node_path8.default.win32 : import_node_path8.default.posix;
5228
+ return platform3 === "win32" ? import_node_path9.default.win32 : import_node_path9.default.posix;
5201
5229
  }
5202
5230
  function pathFolders(platform3, pathValue) {
5203
5231
  const separator = platform3 === "win32" ? ";" : ":";
@@ -5219,16 +5247,16 @@ function findOnPath(names, lookup) {
5219
5247
  }
5220
5248
  function npmCopyFor(commandPath, lookup) {
5221
5249
  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"));
5250
+ const folder = import_node_path9.default.win32.dirname(commandPath);
5251
+ const packageFolder = import_node_path9.default.win32.join(folder, "node_modules", NPM_PACKAGE);
5252
+ const isPackage = lookup.files.isFile(import_node_path9.default.win32.join(packageFolder, "package.json"));
5225
5253
  return isPackage && !lookup.files.isLink(packageFolder) ? { prefix: folder, packageFolder } : null;
5226
5254
  }
5227
5255
  const realPath2 = lookup.files.realPath(commandPath);
5228
5256
  const segmentStart = realPath2?.indexOf(UNIX_NPM_SEGMENT) ?? -1;
5229
5257
  if (realPath2 === null || segmentStart < 0) return null;
5230
5258
  const prefix = realPath2.slice(0, segmentStart);
5231
- return { prefix, packageFolder: import_node_path8.default.posix.join(prefix, "lib", "node_modules", NPM_PACKAGE) };
5259
+ return { prefix, packageFolder: import_node_path9.default.posix.join(prefix, "lib", "node_modules", NPM_PACKAGE) };
5232
5260
  }
5233
5261
  function findPinggyCommand(lookup) {
5234
5262
  const names = lookup.platform === "win32" ? windowsCommandNames(NPM_PACKAGE, lookup.pathExtensions) : [NPM_PACKAGE];
@@ -5280,13 +5308,13 @@ function processPathLookup() {
5280
5308
  files: realPathFileSystem(process.platform)
5281
5309
  };
5282
5310
  }
5283
- var import_node_fs12, import_node_path8, NPM_PACKAGE, UNIX_NPM_SEGMENT, DEFAULT_PATH_EXTENSIONS, POWERSHELL_SCRIPT_EXTENSION, CURRENT_FOLDER;
5311
+ var import_node_fs12, import_node_path9, NPM_PACKAGE, UNIX_NPM_SEGMENT, DEFAULT_PATH_EXTENSIONS, POWERSHELL_SCRIPT_EXTENSION, CURRENT_FOLDER;
5284
5312
  var init_pinggyOnPath = __esm({
5285
5313
  "src/install/pinggyOnPath.ts"() {
5286
5314
  "use strict";
5287
5315
  init_cjs_shims();
5288
5316
  import_node_fs12 = __toESM(require("fs"), 1);
5289
- import_node_path8 = __toESM(require("path"), 1);
5317
+ import_node_path9 = __toESM(require("path"), 1);
5290
5318
  NPM_PACKAGE = "pinggy";
5291
5319
  UNIX_NPM_SEGMENT = `/lib/node_modules/${NPM_PACKAGE}/`;
5292
5320
  DEFAULT_PATH_EXTENSIONS = ".COM;.EXE;.BAT;.CMD";
@@ -5373,13 +5401,13 @@ function warnIfShadowed(environment, home) {
5373
5401
  if (found === null) return;
5374
5402
  let expectedFolder;
5375
5403
  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;
5404
+ expectedFolder = import_node_path10.default.win32.dirname(installPathFor(environment, home));
5405
+ if (samePath(import_node_path10.default.win32.dirname(found.commandPath), expectedFolder, "win32")) return;
5378
5406
  } 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}/`));
5407
+ expectedFolder = import_node_path10.default.posix.join(home, LINK_DIRECTORY);
5408
+ const folders = pathFolders(environment.platform, environment.variables.PATH ?? "").map((folder2) => import_node_path10.default.posix.normalize(`${folder2}/`));
5381
5409
  if (!folders.includes(`${expectedFolder}/`)) return;
5382
- if (found.commandPath === import_node_path9.default.posix.join(expectedFolder, NPM_PACKAGE2)) return;
5410
+ if (found.commandPath === import_node_path10.default.posix.join(expectedFolder, NPM_PACKAGE2)) return;
5383
5411
  }
5384
5412
  const folder = shown(expectedFolder, environment, home);
5385
5413
  environment.print(`Another pinggy, ${shown(found.commandPath, environment, home)}, comes before ${folder} on PATH, so the pinggy command runs it.`);
@@ -5435,8 +5463,8 @@ function installHome(platform3, variables) {
5435
5463
  function isInstalledCopy(platform3, execPath, home, variables) {
5436
5464
  if (platform3 === "win32") {
5437
5465
  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);
5466
+ const installFolder = import_node_path10.default.win32.dirname(installerBinaryPath(platform3, home, variables));
5467
+ return samePath(import_node_path10.default.win32.dirname(execPath), installFolder, platform3);
5440
5468
  }
5441
5469
  const kind = detectInstallKind(createInstallProbe());
5442
5470
  return kind === InstallKind.UnixLayout || kind === InstallKind.UnixPlainFile;
@@ -5479,7 +5507,7 @@ async function realInstalledBinary(platform3, home, installPath) {
5479
5507
  }
5480
5508
  function readNpmVersion(npm) {
5481
5509
  try {
5482
- const parsed = JSON.parse(import_node_fs13.default.readFileSync(import_node_path9.default.join(npm.packageFolder, "package.json"), "utf-8"));
5510
+ const parsed = JSON.parse(import_node_fs13.default.readFileSync(import_node_path10.default.join(npm.packageFolder, "package.json"), "utf-8"));
5483
5511
  return typeof parsed.version === "string" && parseVersion(parsed.version) ? parsed.version : null;
5484
5512
  } catch {
5485
5513
  return null;
@@ -5541,14 +5569,14 @@ function installerEnvironment(platform3, execPath) {
5541
5569
  }
5542
5570
  function windowsPowerShell() {
5543
5571
  const systemRoot = process.env.SystemRoot;
5544
- return systemRoot ? import_node_path9.default.win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe") : "powershell.exe";
5572
+ return systemRoot ? import_node_path10.default.win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe") : "powershell.exe";
5545
5573
  }
5546
5574
  async function runEmbeddedInstaller(platform3, execPath) {
5547
5575
  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-"));
5576
+ const temporaryFolder = import_node_fs13.default.mkdtempSync(import_node_path10.default.join(import_node_os5.default.tmpdir(), "pinggy-install-"));
5549
5577
  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 });
5578
+ const scriptPath = import_node_path10.default.join(temporaryFolder, scriptName);
5579
+ import_node_fs13.default.writeFileSync(scriptPath, import_node_fs13.default.readFileSync(import_node_path10.default.join(SCRIPTS_DIRECTORY, scriptName)), { mode: 384 });
5552
5580
  const options = { stdio: OUTPUT_ONLY, env: installerEnvironment(platform3, execPath) };
5553
5581
  if (platform3 !== "win32") return await waitForExit("/bin/sh", [scriptPath], options) === 0;
5554
5582
  const command = `iex ([IO.File]::ReadAllText('${scriptPath.replace(/'/g, "''")}'))`;
@@ -5573,17 +5601,17 @@ function canWrite(folder) {
5573
5601
  function findNpm(npm, lookup) {
5574
5602
  if (lookup.platform === "win32") {
5575
5603
  const onPath2 = findOnPath(["npm.cmd"], lookup);
5576
- const inPrefix2 = import_node_path9.default.win32.join(npm.prefix, "npm.cmd");
5604
+ const inPrefix2 = import_node_path10.default.win32.join(npm.prefix, "npm.cmd");
5577
5605
  return onPath2 ?? (lookup.files.isFile(inPrefix2) ? inPrefix2 : null);
5578
5606
  }
5579
5607
  const onPath = findOnPath(["npm"], lookup);
5580
- const inPrefix = import_node_path9.default.posix.join(npm.prefix, "bin", "npm");
5608
+ const inPrefix = import_node_path10.default.posix.join(npm.prefix, "bin", "npm");
5581
5609
  return onPath ?? (lookup.files.isExecutableFile(inPrefix) ? inPrefix : null);
5582
5610
  }
5583
5611
  async function removeNpmCopy(npm) {
5584
5612
  const lookup = processPathLookup();
5585
5613
  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")];
5614
+ const folders = [import_node_path10.default.posix.join(npm.prefix, "lib", "node_modules"), import_node_path10.default.posix.join(npm.prefix, "bin")];
5587
5615
  if (!folders.every(canWrite)) return NpmRemoval.NotWritable;
5588
5616
  }
5589
5617
  const npmPath = findNpm(npm, lookup);
@@ -5633,7 +5661,7 @@ function realEnvironment2() {
5633
5661
  print: (line) => printer_default.print(line)
5634
5662
  };
5635
5663
  }
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;
5664
+ var import_node_child_process5, import_node_fs13, import_node_os5, import_node_path10, 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
5665
  var init_selfInstall = __esm({
5638
5666
  "src/install/selfInstall.ts"() {
5639
5667
  "use strict";
@@ -5641,7 +5669,7 @@ var init_selfInstall = __esm({
5641
5669
  import_node_child_process5 = require("child_process");
5642
5670
  import_node_fs13 = __toESM(require("fs"), 1);
5643
5671
  import_node_os5 = __toESM(require("os"), 1);
5644
- import_node_path9 = __toESM(require("path"), 1);
5672
+ import_node_path10 = __toESM(require("path"), 1);
5645
5673
  import_node_readline = require("readline");
5646
5674
  import_node_url2 = require("url");
5647
5675
  init_daemonManager();
@@ -5660,7 +5688,7 @@ var init_selfInstall = __esm({
5660
5688
  init_pinggyOnPath();
5661
5689
  UPDATE_SUBCOMMAND2 = "update";
5662
5690
  NPM_PACKAGE2 = "pinggy";
5663
- LINK_DIRECTORY = import_node_path9.default.posix.join(".local", "bin");
5691
+ LINK_DIRECTORY = import_node_path10.default.posix.join(".local", "bin");
5664
5692
  NO_ANSWER = /^\s*n/i;
5665
5693
  INTERRUPTED_EXIT_CODE = 130;
5666
5694
  VERSION_RUN_TIMEOUT_MILLIS = 1e4;
@@ -5668,8 +5696,8 @@ var init_selfInstall = __esm({
5668
5696
  INSTALL_ONLY_ENV = "PINGGY_INSTALL_ONLY";
5669
5697
  BINARY_URL_ENV = "PINGGY_BINARY_URL";
5670
5698
  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");
5699
+ BUNDLE_DIRECTORY = import_node_path10.default.dirname((0, import_node_url2.fileURLToPath)(importMetaUrl));
5700
+ SCRIPTS_DIRECTORY = import_node_path10.default.join(BUNDLE_DIRECTORY, "..", "scripts", "install");
5673
5701
  SelfInstallAnswer = {
5674
5702
  Yes: "yes",
5675
5703
  No: "no",
@@ -7126,10 +7154,10 @@ function parseArgs2(finalConfig, remainingPositionals) {
7126
7154
  }
7127
7155
  function storeJson(config, saveconf) {
7128
7156
  if (saveconf) {
7129
- const path20 = saveconf;
7157
+ const path23 = saveconf;
7130
7158
  try {
7131
- import_fs7.default.writeFileSync(path20, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
7132
- logger.info(`Configuration saved to ${path20}`);
7159
+ import_fs7.default.writeFileSync(path23, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
7160
+ logger.info(`Configuration saved to ${path23}`);
7133
7161
  } catch (err) {
7134
7162
  const msg = err instanceof Error ? err.message : String(err);
7135
7163
  logger.error("Error loading configuration:", msg);
@@ -9787,6 +9815,8 @@ function printDeviceHelp() {
9787
9815
  console.log(" --token <TOKEN> Device token from the dashboard");
9788
9816
  console.log(" --manage <HOST> Dashboard address. Default: dashboard.pinggy.io");
9789
9817
  console.log(" --name <NAME> login only: the device's name. Default: this machine's hostname");
9818
+ console.log(" --files on|off login, connect and start: allow or refuse file access from the");
9819
+ console.log(" dashboard. Without it, the first run in a terminal asks");
9790
9820
  console.log(" -f remove only: remove without asking\n");
9791
9821
  console.log("Environment:");
9792
9822
  console.log(" DEVICE_AGENT_TOKEN connect and start: the device token, when --token is not given.");
@@ -9820,14 +9850,21 @@ function readDeviceIdentity() {
9820
9850
  }
9821
9851
  }
9822
9852
  function writeDeviceIdentity(identity) {
9853
+ const written = keepStoredFileManager(identity, readDeviceIdentity());
9823
9854
  ensurePinggyConfigDir();
9824
9855
  const filePath = getDeviceConfigPath();
9825
- import_fs9.default.writeFileSync(filePath, JSON.stringify(identity, null, 2), {
9856
+ import_fs9.default.writeFileSync(filePath, JSON.stringify(written, null, 2), {
9826
9857
  encoding: "utf-8",
9827
9858
  mode: SECRET_FILE_MODE
9828
9859
  });
9829
9860
  import_fs9.default.chmodSync(filePath, SECRET_FILE_MODE);
9830
9861
  }
9862
+ function keepStoredFileManager(identity, stored) {
9863
+ if (identity.file_manager !== void 0 || !stored || stored.token !== identity.token || typeof stored.file_manager !== "boolean") {
9864
+ return identity;
9865
+ }
9866
+ return { ...identity, file_manager: stored.file_manager };
9867
+ }
9831
9868
  function clearDeviceIdentity() {
9832
9869
  const filePath = getDeviceConfigPath();
9833
9870
  if (!import_fs9.default.existsSync(filePath)) {
@@ -9861,8 +9898,8 @@ function request(ch, op, payload) {
9861
9898
  function response(to, op, payload) {
9862
9899
  return { v: PROTOCOL_VERSION, kind: "res", ch: to.ch, op, id: to.id, seq: 0, ts: nowSeconds(), payload };
9863
9900
  }
9864
- function event(ch, op, payload) {
9865
- return { v: PROTOCOL_VERSION, kind: "event", ch, op, id: "", seq: 0, ts: nowSeconds(), payload };
9901
+ function event(ch, op, payload, id = "") {
9902
+ return { v: PROTOCOL_VERSION, kind: "event", ch, op, id, seq: 0, ts: nowSeconds(), payload };
9866
9903
  }
9867
9904
  function parseEnvelope(raw) {
9868
9905
  try {
@@ -9922,6 +9959,12 @@ var init_device_schema = __esm({
9922
9959
  terminal_idle_timeout_seconds: import_zod3.z.number().optional(),
9923
9960
  // Optional: without it the agent keeps the window brake and never skips output.
9924
9961
  terminal_resync: import_zod3.z.boolean().optional(),
9962
+ // Optional: a dashboard that predates the file manager sends none, and every file request is refused.
9963
+ file_manager_enabled: import_zod3.z.boolean().optional(),
9964
+ // No default on the agent. Without it, every copy, move and delete answers file_busy rather than running unbounded.
9965
+ file_max_concurrent_operations: import_zod3.z.number().optional(),
9966
+ // Optional: without it nothing waits, and a copy, move or delete past the running limit answers file_busy.
9967
+ file_max_queued_operations: import_zod3.z.number().optional(),
9925
9968
  // Optional: a dashboard older than these sends neither, and the agent prints only the device id.
9926
9969
  email: import_zod3.z.string().optional(),
9927
9970
  device_url: import_zod3.z.string().optional()
@@ -9986,6 +10029,19 @@ var init_deviceAgentReporter = __esm({
9986
10029
  });
9987
10030
 
9988
10031
  // src/devices/collectors/systemInfo.ts
10032
+ function agentUser() {
10033
+ const uid = process.getuid?.();
10034
+ let username;
10035
+ try {
10036
+ username = import_os3.default.userInfo().username || void 0;
10037
+ } catch {
10038
+ username = void 0;
10039
+ }
10040
+ return {
10041
+ ...username === void 0 ? {} : { username },
10042
+ ...uid === void 0 ? {} : { uid }
10043
+ };
10044
+ }
9989
10045
  function collectSystemInfo() {
9990
10046
  const cpus = import_os3.default.cpus();
9991
10047
  return {
@@ -9999,7 +10055,8 @@ function collectSystemInfo() {
9999
10055
  // os.cpus() is empty on some Android and container builds.
10000
10056
  cpu_model: cpus[0]?.model?.trim() || UNKNOWN_CPU_MODEL,
10001
10057
  cpu_cores: cpus.length,
10002
- total_memory_bytes: import_os3.default.totalmem()
10058
+ total_memory_bytes: import_os3.default.totalmem(),
10059
+ ...agentUser()
10003
10060
  };
10004
10061
  }
10005
10062
  var import_os3, UNKNOWN_CPU_MODEL;
@@ -10544,192 +10601,2826 @@ var init_reconnect = __esm({
10544
10601
  }
10545
10602
  });
10546
10603
 
10547
- // src/devices/terminal/terminal_schema.ts
10548
- function clampGrid(requested, fallback) {
10549
- if (requested === void 0 || !Number.isFinite(requested)) return fallback;
10550
- return Math.max(MIN_GRID, Math.min(MAX_GRID, Math.trunc(requested)));
10604
+ // src/devices/files/file_schema.ts
10605
+ function fileError(code, message) {
10606
+ return { error: { code, message } };
10551
10607
  }
10552
- var import_zod4, CHANNEL_TERMINAL, OP_OPEN, OP_OPENED, OP_CLOSE, OP_DATA, OP_ACK, OP_EXIT, OP_RESIZE, OP_SIGNAL, OP_CONTEXT, OP_SNAPSHOT, OP_RESYNC, OP_ACTIVITY, TERMINAL_SIGNALS, MIN_GRID, MAX_GRID, CLOSE_REASON_USER_CLOSED, CLOSE_REASON_IDLE_TIMEOUT, ERROR_INVALID_PAYLOAD2, ERROR_TERMINAL_LIMIT_REACHED, ERROR_TERMINAL_DISABLED, ERROR_SHELL_NOT_ALLOWED, ERROR_SPAWN_FAILED, TerminalOpenSchema, TerminalCloseSchema, TerminalResizeSchema, TerminalInputSchema, TerminalSignalSchema, TerminalAckSchema, TerminalSnapshotRequestSchema;
10553
- var init_terminal_schema = __esm({
10554
- "src/devices/terminal/terminal_schema.ts"() {
10608
+ var import_zod4, CHANNEL_FILE, OP_LIST, OP_STAT, OP_DELETE, OP_MKDIR, OP_COPY, OP_MOVE, OP_PROGRESS, ERROR_INVALID_PAYLOAD2, ERROR_UNSUPPORTED_OP2, ERROR_FILE_MANAGER_DISABLED, ERROR_FILE_ACCESS_OFF, ERROR_INVALID_PATH, ERROR_PATH_NOT_FOUND, ERROR_NOT_A_DIRECTORY, ERROR_PERMISSION_DENIED, ERROR_FILE_TIMEOUT, ERROR_FILE_OPERATION_FAILED, ERROR_PROTECTED_PATH, ERROR_MOUNT_POINT, ERROR_FILE_BUSY, ERROR_FILE_EXISTS, ERROR_INVALID_NAME, ERROR_INVALID_DESTINATION, ERROR_NO_SPACE, ERROR_SPECIAL_FILE, SORT_BY_NAME, SORT_BY_SIZE, SORT_BY_MODIFIED, SORT_BY_CREATED, SORT_ORDER_ASC, SORT_ORDER_DESC, DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT, MAX_PATH_BYTES, MAX_NAME_BYTES, ON_CONFLICT_FAIL, ON_CONFLICT_SKIP, ON_CONFLICT_KEEP_BOTH, ON_CONFLICT_REPLACE, FileListRequestSchema, FileStatRequestSchema, FileDeleteRequestSchema, FileMkdirRequestSchema, FileCopyRequestSchema;
10609
+ var init_file_schema = __esm({
10610
+ "src/devices/files/file_schema.ts"() {
10555
10611
  "use strict";
10556
10612
  init_cjs_shims();
10557
10613
  import_zod4 = require("zod");
10558
- CHANNEL_TERMINAL = "terminal";
10559
- OP_OPEN = "open";
10560
- OP_OPENED = "opened";
10561
- OP_CLOSE = "close";
10562
- OP_DATA = "data";
10563
- OP_ACK = "ack";
10564
- OP_EXIT = "exit";
10565
- OP_RESIZE = "resize";
10566
- OP_SIGNAL = "signal";
10567
- OP_CONTEXT = "context";
10568
- OP_SNAPSHOT = "snapshot";
10569
- OP_RESYNC = "resync";
10570
- OP_ACTIVITY = "activity";
10571
- TERMINAL_SIGNALS = ["INT", "TERM", "QUIT", "HUP"];
10572
- MIN_GRID = 1;
10573
- MAX_GRID = 1e3;
10574
- CLOSE_REASON_USER_CLOSED = "user_closed";
10575
- CLOSE_REASON_IDLE_TIMEOUT = "idle_timeout";
10614
+ CHANNEL_FILE = "file";
10615
+ OP_LIST = "list";
10616
+ OP_STAT = "stat";
10617
+ OP_DELETE = "delete";
10618
+ OP_MKDIR = "mkdir";
10619
+ OP_COPY = "copy";
10620
+ OP_MOVE = "move";
10621
+ OP_PROGRESS = "progress";
10576
10622
  ERROR_INVALID_PAYLOAD2 = "invalid_payload";
10577
- ERROR_TERMINAL_LIMIT_REACHED = "terminal_limit_reached";
10578
- ERROR_TERMINAL_DISABLED = "terminal_disabled";
10579
- ERROR_SHELL_NOT_ALLOWED = "shell_not_allowed";
10580
- ERROR_SPAWN_FAILED = "spawn_failed";
10581
- TerminalOpenSchema = import_zod4.z.object({
10582
- terminal_id: import_zod4.z.string().min(1),
10583
- cols: import_zod4.z.number().int().optional(),
10584
- rows: import_zod4.z.number().int().optional(),
10585
- shell: import_zod4.z.string().nullable().optional(),
10586
- cwd: import_zod4.z.string().nullable().optional()
10587
- });
10588
- TerminalCloseSchema = import_zod4.z.object({
10589
- terminal_id: import_zod4.z.string().min(1),
10590
- reason: import_zod4.z.string().optional()
10623
+ ERROR_UNSUPPORTED_OP2 = "unsupported_op";
10624
+ ERROR_FILE_MANAGER_DISABLED = "file_manager_disabled";
10625
+ ERROR_FILE_ACCESS_OFF = "file_access_off";
10626
+ ERROR_INVALID_PATH = "invalid_path";
10627
+ ERROR_PATH_NOT_FOUND = "path_not_found";
10628
+ ERROR_NOT_A_DIRECTORY = "not_a_directory";
10629
+ ERROR_PERMISSION_DENIED = "permission_denied";
10630
+ ERROR_FILE_TIMEOUT = "file_timeout";
10631
+ ERROR_FILE_OPERATION_FAILED = "file_operation_failed";
10632
+ ERROR_PROTECTED_PATH = "protected_path";
10633
+ ERROR_MOUNT_POINT = "mount_point";
10634
+ ERROR_FILE_BUSY = "file_busy";
10635
+ ERROR_FILE_EXISTS = "file_exists";
10636
+ ERROR_INVALID_NAME = "invalid_name";
10637
+ ERROR_INVALID_DESTINATION = "invalid_destination";
10638
+ ERROR_NO_SPACE = "no_space";
10639
+ ERROR_SPECIAL_FILE = "special_file";
10640
+ SORT_BY_NAME = "name";
10641
+ SORT_BY_SIZE = "size";
10642
+ SORT_BY_MODIFIED = "modified";
10643
+ SORT_BY_CREATED = "created";
10644
+ SORT_ORDER_ASC = "asc";
10645
+ SORT_ORDER_DESC = "desc";
10646
+ DEFAULT_LIST_LIMIT = 200;
10647
+ MAX_LIST_LIMIT = 500;
10648
+ MAX_PATH_BYTES = 4096;
10649
+ MAX_NAME_BYTES = 255;
10650
+ ON_CONFLICT_FAIL = "fail";
10651
+ ON_CONFLICT_SKIP = "skip";
10652
+ ON_CONFLICT_KEEP_BOTH = "keep_both";
10653
+ ON_CONFLICT_REPLACE = "replace";
10654
+ FileListRequestSchema = import_zod4.z.object({
10655
+ path: import_zod4.z.string().optional(),
10656
+ offset: import_zod4.z.number().int().min(0).optional(),
10657
+ limit: import_zod4.z.number().int().min(1).max(MAX_LIST_LIMIT).optional(),
10658
+ sort_by: import_zod4.z.enum([SORT_BY_NAME, SORT_BY_SIZE, SORT_BY_MODIFIED, SORT_BY_CREATED]).optional(),
10659
+ sort_order: import_zod4.z.enum([SORT_ORDER_ASC, SORT_ORDER_DESC]).optional(),
10660
+ include_hidden: import_zod4.z.boolean().optional()
10591
10661
  });
10592
- TerminalResizeSchema = import_zod4.z.object({
10593
- terminal_id: import_zod4.z.string().min(1),
10594
- cols: import_zod4.z.number().int(),
10595
- rows: import_zod4.z.number().int()
10662
+ FileStatRequestSchema = import_zod4.z.object({
10663
+ path: import_zod4.z.string(),
10664
+ include_hidden: import_zod4.z.boolean().optional()
10596
10665
  });
10597
- TerminalInputSchema = import_zod4.z.object({
10598
- terminal_id: import_zod4.z.string().min(1),
10599
- data: import_zod4.z.string()
10666
+ FileDeleteRequestSchema = import_zod4.z.object({
10667
+ path: import_zod4.z.string()
10600
10668
  });
10601
- TerminalSignalSchema = import_zod4.z.object({
10602
- terminal_id: import_zod4.z.string().min(1),
10603
- signal: import_zod4.z.enum(TERMINAL_SIGNALS)
10669
+ FileMkdirRequestSchema = import_zod4.z.object({
10670
+ path: import_zod4.z.string()
10604
10671
  });
10605
- TerminalAckSchema = import_zod4.z.object({
10606
- terminal_id: import_zod4.z.string().min(1),
10607
- ack_seq: import_zod4.z.number().optional(),
10608
- ack_bytes: import_zod4.z.number()
10609
- });
10610
- TerminalSnapshotRequestSchema = import_zod4.z.object({
10611
- terminal_id: import_zod4.z.string().min(1),
10612
- snapshot_id: import_zod4.z.string().min(1)
10672
+ FileCopyRequestSchema = import_zod4.z.object({
10673
+ source_path: import_zod4.z.string(),
10674
+ destination_path: import_zod4.z.string(),
10675
+ on_conflict: import_zod4.z.enum([ON_CONFLICT_FAIL, ON_CONFLICT_SKIP, ON_CONFLICT_KEEP_BOTH, ON_CONFLICT_REPLACE]).optional()
10613
10676
  });
10614
10677
  }
10615
10678
  });
10616
10679
 
10617
- // src/devices/terminal/flowWindow.ts
10618
- var FlowWindow;
10619
- var init_flowWindow = __esm({
10620
- "src/devices/terminal/flowWindow.ts"() {
10680
+ // src/devices/files/fileSystem.ts
10681
+ function pathsFor(platform3) {
10682
+ return platform3 === "win32" ? import_path9.default.win32 : import_path9.default.posix;
10683
+ }
10684
+ function pathProblem(requested, paths) {
10685
+ if (requested.includes("\0")) {
10686
+ return "The path holds a NUL byte.";
10687
+ }
10688
+ if (Buffer.byteLength(requested, "utf8") > MAX_PATH_BYTES) {
10689
+ return `The path is longer than ${MAX_PATH_BYTES} bytes.`;
10690
+ }
10691
+ if (!paths.isAbsolute(requested)) {
10692
+ return "The path must be absolute.";
10693
+ }
10694
+ return null;
10695
+ }
10696
+ function nameProblem(name, platform3) {
10697
+ if (name.length === 0) {
10698
+ return "A name is empty.";
10699
+ }
10700
+ if (Buffer.byteLength(name, "utf8") > MAX_NAME_BYTES) {
10701
+ return `A name is longer than ${MAX_NAME_BYTES} bytes.`;
10702
+ }
10703
+ if (name === "." || name === "..") {
10704
+ return "A name cannot be . or ..";
10705
+ }
10706
+ if (name.includes("\0")) {
10707
+ return "A name holds a NUL byte.";
10708
+ }
10709
+ if (name.includes("/") || platform3 === "win32" && name.includes("\\")) {
10710
+ return "A name holds a path separator.";
10711
+ }
10712
+ return null;
10713
+ }
10714
+ function windowsNameProblem(name, subject = "A folder name") {
10715
+ if (WINDOWS_FORBIDDEN_CHARACTERS.test(name)) {
10716
+ return `${subject} on Windows cannot hold : * ? " < > |`;
10717
+ }
10718
+ if (WINDOWS_TRAILING_DOT_OR_SPACE.test(name)) {
10719
+ return `${subject} on Windows cannot end with a dot or a space.`;
10720
+ }
10721
+ const stem = name.split(EXTENSION_SEPARATOR)[0].toUpperCase();
10722
+ if (WINDOWS_DEVICE_NAMES.has(stem)) {
10723
+ return `${stem} is a device name on Windows.`;
10724
+ }
10725
+ return null;
10726
+ }
10727
+ function isRoot(resolved, paths) {
10728
+ return paths.dirname(resolved) === resolved;
10729
+ }
10730
+ function resolvedItem(requested, paths) {
10731
+ const resolved = paths.resolve(requested);
10732
+ return { path: resolved, parent: paths.dirname(resolved), name: paths.basename(resolved) };
10733
+ }
10734
+ function withTrimmedName(item) {
10735
+ const name = item.name.trim();
10736
+ if (name === item.name || name.length === 0) {
10737
+ return { ...item, name };
10738
+ }
10739
+ return { ...item, name, path: item.path.slice(0, item.path.length - item.name.length) + name };
10740
+ }
10741
+ function errorCodeOf(err) {
10742
+ return typeof err === "object" && err !== null && "code" in err && typeof err.code === "string" ? err.code : void 0;
10743
+ }
10744
+ function failureMessage(err, fallback) {
10745
+ return sanitizeErrorMessage(err instanceof Error ? err.message : String(err)) ?? fallback;
10746
+ }
10747
+ function entryTypeOf(stats) {
10748
+ if (stats.isSymbolicLink()) return "symlink";
10749
+ if (stats.isDirectory()) return "directory";
10750
+ if (stats.isFile()) return "file";
10751
+ return "other";
10752
+ }
10753
+ function targetTypeOf(stats) {
10754
+ if (stats.isDirectory()) return "directory";
10755
+ if (stats.isFile()) return "file";
10756
+ return "other";
10757
+ }
10758
+ function epochSeconds(millis) {
10759
+ return Math.floor(millis / MILLIS_PER_SECOND);
10760
+ }
10761
+ function utf8Bytes(value) {
10762
+ return Buffer.byteLength(JSON.stringify(value), "utf8");
10763
+ }
10764
+ async function readLinkTarget(linkPath, reader) {
10765
+ const target = {};
10766
+ try {
10767
+ target.linkTarget = await reader.readlink(linkPath);
10768
+ } catch {
10769
+ }
10770
+ try {
10771
+ target.targetStats = await reader.stat(linkPath);
10772
+ target.targetType = targetTypeOf(target.targetStats);
10773
+ } catch (err) {
10774
+ const code = errorCodeOf(err);
10775
+ if (code === "ENOENT" || code === "ENOTDIR") {
10776
+ target.targetType = "missing";
10777
+ }
10778
+ }
10779
+ return target;
10780
+ }
10781
+ function callTimeoutError(millis) {
10782
+ const seconds = Math.round(millis / MILLIS_PER_SECOND);
10783
+ return new FileCallTimeoutError(`A filesystem call took longer than ${seconds} s.`);
10784
+ }
10785
+ function callWithTimeout(work, millis) {
10786
+ return new Promise((resolve, reject) => {
10787
+ const timer = setTimeout(() => reject(callTimeoutError(millis)), millis);
10788
+ work.then((value) => {
10789
+ clearTimeout(timer);
10790
+ resolve(value);
10791
+ }, (err) => {
10792
+ clearTimeout(timer);
10793
+ reject(err);
10794
+ });
10795
+ });
10796
+ }
10797
+ function withTimeout(work, millis, fallback) {
10798
+ return new Promise((resolve) => {
10799
+ const timer = setTimeout(() => resolve(fallback), millis);
10800
+ work.then((value) => {
10801
+ clearTimeout(timer);
10802
+ resolve(value);
10803
+ }, () => {
10804
+ clearTimeout(timer);
10805
+ resolve(fallback);
10806
+ });
10807
+ });
10808
+ }
10809
+ var import_fs10, import_os5, import_path9, machineFileSystem, machineFileSystemDependencies, machineFileSystemRemover, machineFileSystemMaker, NEW_FILE_MODE, CREATE_ONLY_IF_FREE, machineFileSystemCopier, HIDDEN_NAME_PREFIX, MILLIS_PER_SECOND, WINDOWS_FORBIDDEN_CHARACTERS, WINDOWS_TRAILING_DOT_OR_SPACE, WINDOWS_NUMBERED_DEVICES, WINDOWS_DEVICE_NUMBERS, WINDOWS_DEVICE_NAMES, EXTENSION_SEPARATOR, MESSAGE_NAME_TAKEN, FileCallTimeoutError;
10810
+ var init_fileSystem = __esm({
10811
+ "src/devices/files/fileSystem.ts"() {
10621
10812
  "use strict";
10622
10813
  init_cjs_shims();
10623
- FlowWindow = class {
10624
- constructor(windowBytes) {
10625
- this.sentBytes = 0;
10626
- this.ackedBytes = 0;
10627
- if (!Number.isFinite(windowBytes) || windowBytes <= 0) {
10628
- throw new Error("A terminal flow window needs a positive size from welcome");
10629
- }
10630
- this.windowBytes = Math.trunc(windowBytes);
10631
- }
10632
- /** How many more raw bytes may go out before the browser has to catch up. */
10633
- remaining() {
10634
- return Math.max(0, this.windowBytes - (this.sentBytes - this.ackedBytes));
10635
- }
10636
- /** False means stop reading the pty. Nothing else is an acceptable response. */
10637
- isOpen() {
10638
- return this.remaining() > 0;
10639
- }
10640
- recordSent(byteCount) {
10641
- if (!Number.isFinite(byteCount) || byteCount <= 0) return;
10642
- this.sentBytes += Math.trunc(byteCount);
10814
+ import_fs10 = __toESM(require("fs"), 1);
10815
+ import_os5 = __toESM(require("os"), 1);
10816
+ import_path9 = __toESM(require("path"), 1);
10817
+ init_tunnelList();
10818
+ init_file_schema();
10819
+ machineFileSystem = {
10820
+ readdir: (folder) => import_fs10.default.promises.readdir(folder, { withFileTypes: true }),
10821
+ lstat: (target) => import_fs10.default.promises.lstat(target),
10822
+ stat: (target) => import_fs10.default.promises.stat(target),
10823
+ readlink: (target) => import_fs10.default.promises.readlink(target),
10824
+ access: (target, mode) => import_fs10.default.promises.access(target, mode),
10825
+ homedir: () => import_os5.default.homedir()
10826
+ };
10827
+ machineFileSystemDependencies = {
10828
+ fs: machineFileSystem,
10829
+ platform: process.platform
10830
+ };
10831
+ machineFileSystemRemover = {
10832
+ lstat: (target) => import_fs10.default.promises.lstat(target, { bigint: true }),
10833
+ stat: (target) => import_fs10.default.promises.stat(target, { bigint: true }),
10834
+ readdir: (folder) => import_fs10.default.promises.readdir(folder),
10835
+ unlink: (target) => import_fs10.default.promises.unlink(target),
10836
+ rmdir: (target) => import_fs10.default.promises.rmdir(target),
10837
+ chmod: (target, mode) => import_fs10.default.promises.chmod(target, mode),
10838
+ realpath: (target) => import_fs10.default.promises.realpath(target)
10839
+ };
10840
+ machineFileSystemMaker = {
10841
+ mkdir: async (target) => {
10842
+ await import_fs10.default.promises.mkdir(target);
10643
10843
  }
10644
- /**
10645
- * Cumulative totals, never increments, so a dropped ack self-heals on the next one.
10646
- *
10647
- * A browser is not a trusted input. An ack beyond what was sent is clamped rather than believed,
10648
- * and one that arrives out of order never moves the counter backwards.
10649
- */
10650
- recordAck(ackBytes) {
10651
- if (!Number.isFinite(ackBytes)) return;
10652
- const clamped = Math.min(Math.max(Math.trunc(ackBytes), 0), this.sentBytes);
10653
- if (clamped > this.ackedBytes) {
10654
- this.ackedBytes = clamped;
10844
+ };
10845
+ NEW_FILE_MODE = 384;
10846
+ CREATE_ONLY_IF_FREE = "wx";
10847
+ machineFileSystemCopier = {
10848
+ lstat: (target) => import_fs10.default.promises.lstat(target, { bigint: true }),
10849
+ stat: (target) => import_fs10.default.promises.stat(target, { bigint: true }),
10850
+ realpath: (target) => import_fs10.default.promises.realpath(target),
10851
+ readdir: (folder) => import_fs10.default.promises.readdir(folder),
10852
+ mkdir: async (target) => {
10853
+ await import_fs10.default.promises.mkdir(target);
10854
+ },
10855
+ openToRead: (target) => import_fs10.default.promises.open(target, "r"),
10856
+ createFile: (target) => import_fs10.default.promises.open(target, CREATE_ONLY_IF_FREE, NEW_FILE_MODE),
10857
+ read: async (handle, buffer) => (await handle.read(buffer, 0, buffer.length, null)).bytesRead,
10858
+ write: async (handle, buffer, length) => {
10859
+ let written = 0;
10860
+ while (written < length) {
10861
+ written += (await handle.write(buffer, written, length - written, null)).bytesWritten;
10655
10862
  }
10863
+ },
10864
+ close: (handle) => handle.close(),
10865
+ readlink: (target) => import_fs10.default.promises.readlink(target),
10866
+ symlink: (linkText, target, type) => import_fs10.default.promises.symlink(linkText, target, type),
10867
+ chmod: (target, mode) => import_fs10.default.promises.chmod(target, mode),
10868
+ utimes: (target, accessed, modified) => import_fs10.default.promises.utimes(target, accessed, modified),
10869
+ rename: (from, to) => import_fs10.default.promises.rename(from, to),
10870
+ unlink: (target) => import_fs10.default.promises.unlink(target),
10871
+ freeBytes: async (folder) => {
10872
+ const stats = await import_fs10.default.promises.statfs(folder, { bigint: true });
10873
+ return stats.bavail * stats.bsize;
10656
10874
  }
10657
- get sent() {
10658
- return this.sentBytes;
10659
- }
10660
- get acked() {
10661
- return this.ackedBytes;
10662
- }
10663
- get size() {
10664
- return this.windowBytes;
10665
- }
10875
+ };
10876
+ HIDDEN_NAME_PREFIX = ".";
10877
+ MILLIS_PER_SECOND = 1e3;
10878
+ WINDOWS_FORBIDDEN_CHARACTERS = /[:*?"<>|]/;
10879
+ WINDOWS_TRAILING_DOT_OR_SPACE = /[. ]$/;
10880
+ WINDOWS_NUMBERED_DEVICES = ["COM", "LPT"];
10881
+ WINDOWS_DEVICE_NUMBERS = [1, 2, 3, 4, 5, 6, 7, 8, 9];
10882
+ WINDOWS_DEVICE_NAMES = /* @__PURE__ */ new Set([
10883
+ "CON",
10884
+ "PRN",
10885
+ "AUX",
10886
+ "NUL",
10887
+ ...WINDOWS_NUMBERED_DEVICES.flatMap((device) => WINDOWS_DEVICE_NUMBERS.map((number) => `${device}${number}`))
10888
+ ]);
10889
+ EXTENSION_SEPARATOR = ".";
10890
+ MESSAGE_NAME_TAKEN = "A file or folder with this name already exists.";
10891
+ FileCallTimeoutError = class extends Error {
10666
10892
  };
10667
10893
  }
10668
10894
  });
10669
10895
 
10670
- // src/devices/terminal/frameSplitter.ts
10671
- function rawBundleBytes(maxFrameBytes) {
10672
- const available = maxFrameBytes - ENVELOPE_OVERHEAD_BYTES;
10673
- if (available <= 0) {
10674
- throw new Error("max_frame_bytes leaves no room for a terminal payload");
10675
- }
10676
- return Math.floor(available * BASE64_NUMERATOR / BASE64_DENOMINATOR);
10896
+ // src/devices/files/fileCallGate.ts
10897
+ function gatedReader(reader, gate, timeoutMillis) {
10898
+ return {
10899
+ readdir: (folder) => gate.run(() => reader.readdir(folder), timeoutMillis),
10900
+ lstat: (target) => gate.run(() => reader.lstat(target), timeoutMillis),
10901
+ stat: (target) => gate.run(() => reader.stat(target), timeoutMillis),
10902
+ readlink: (target) => gate.run(() => reader.readlink(target), timeoutMillis),
10903
+ access: (target, mode) => gate.run(() => reader.access(target, mode), timeoutMillis),
10904
+ homedir: () => reader.homedir()
10905
+ };
10677
10906
  }
10678
- var ENVELOPE_OVERHEAD_BYTES, BASE64_NUMERATOR, BASE64_DENOMINATOR, BUNDLE_MILLIS, FrameSplitter;
10679
- var init_frameSplitter = __esm({
10680
- "src/devices/terminal/frameSplitter.ts"() {
10907
+ function gatedRemover(remover, gate, timeoutMillis) {
10908
+ return {
10909
+ lstat: (target) => gate.run(() => remover.lstat(target), timeoutMillis),
10910
+ stat: (target) => gate.run(() => remover.stat(target), timeoutMillis),
10911
+ readdir: (folder) => gate.run(() => remover.readdir(folder), timeoutMillis),
10912
+ unlink: (target) => gate.run(() => remover.unlink(target), timeoutMillis),
10913
+ rmdir: (target) => gate.run(() => remover.rmdir(target), timeoutMillis),
10914
+ chmod: (target, mode) => gate.run(() => remover.chmod(target, mode), timeoutMillis),
10915
+ realpath: (target) => gate.run(() => remover.realpath(target), timeoutMillis)
10916
+ };
10917
+ }
10918
+ function gatedMaker(maker, gate, timeoutMillis) {
10919
+ return {
10920
+ mkdir: (target) => gate.run(() => maker.mkdir(target), timeoutMillis)
10921
+ };
10922
+ }
10923
+ function gatedCopier(copier, gate, timeoutMillis) {
10924
+ return {
10925
+ lstat: (target) => gate.run(() => copier.lstat(target), timeoutMillis),
10926
+ stat: (target) => gate.run(() => copier.stat(target), timeoutMillis),
10927
+ realpath: (target) => gate.run(() => copier.realpath(target), timeoutMillis),
10928
+ readdir: (folder) => gate.run(() => copier.readdir(folder), timeoutMillis),
10929
+ mkdir: (target) => gate.run(() => copier.mkdir(target), timeoutMillis),
10930
+ openToRead: (target) => gate.run(() => copier.openToRead(target), timeoutMillis),
10931
+ createFile: (target) => gate.run(() => copier.createFile(target), timeoutMillis),
10932
+ read: (handle, buffer) => gate.run(() => copier.read(handle, buffer), timeoutMillis),
10933
+ write: (handle, buffer, length) => gate.run(() => copier.write(handle, buffer, length), timeoutMillis),
10934
+ close: (handle) => gate.run(() => copier.close(handle), timeoutMillis),
10935
+ readlink: (target) => gate.run(() => copier.readlink(target), timeoutMillis),
10936
+ symlink: (linkText, target, type) => gate.run(() => copier.symlink(linkText, target, type), timeoutMillis),
10937
+ chmod: (target, mode) => gate.run(() => copier.chmod(target, mode), timeoutMillis),
10938
+ utimes: (target, accessed, modified) => gate.run(
10939
+ () => copier.utimes(target, accessed, modified),
10940
+ timeoutMillis
10941
+ ),
10942
+ rename: (from, to) => gate.run(() => copier.rename(from, to), timeoutMillis),
10943
+ unlink: (target) => gate.run(() => copier.unlink(target), timeoutMillis),
10944
+ freeBytes: (folder) => gate.run(() => copier.freeBytes(folder), timeoutMillis)
10945
+ };
10946
+ }
10947
+ var MESSAGE_DRIVE_STOPPED, FileCallsStuckError, FileCallGate;
10948
+ var init_fileCallGate = __esm({
10949
+ "src/devices/files/fileCallGate.ts"() {
10681
10950
  "use strict";
10682
10951
  init_cjs_shims();
10683
- ENVELOPE_OVERHEAD_BYTES = 512;
10684
- BASE64_NUMERATOR = 3;
10685
- BASE64_DENOMINATOR = 4;
10686
- BUNDLE_MILLIS = 8;
10687
- FrameSplitter = class {
10688
- constructor(emit, bundleBytes, bundleMillis = BUNDLE_MILLIS) {
10689
- this.emit = emit;
10690
- this.bundleBytes = bundleBytes;
10691
- this.bundleMillis = bundleMillis;
10692
- this.pending = [];
10693
- this.pendingBytes = 0;
10694
- if (!Number.isFinite(bundleBytes) || bundleBytes <= 0) {
10695
- throw new Error("A frame splitter needs a positive bundle size");
10696
- }
10952
+ init_fileSystem();
10953
+ MESSAGE_DRIVE_STOPPED = "A drive on the device stopped answering. Try again once it is back.";
10954
+ FileCallsStuckError = class extends FileCallTimeoutError {
10955
+ constructor() {
10956
+ super(MESSAGE_DRIVE_STOPPED);
10697
10957
  }
10698
- /** A chunk over the cap is split across frames, never truncated. */
10699
- push(chunk) {
10700
- if (chunk.length === 0) return;
10701
- this.pending.push(chunk);
10702
- this.pendingBytes += chunk.length;
10703
- while (this.pendingBytes >= this.bundleBytes) {
10704
- this.emitBytes(this.bundleBytes);
10705
- }
10706
- if (this.pendingBytes > 0) {
10707
- this.arm();
10708
- } else {
10709
- this.disarm();
10958
+ };
10959
+ FileCallGate = class {
10960
+ constructor(places) {
10961
+ this.places = places;
10962
+ this.running = 0;
10963
+ this.abandoned = 0;
10964
+ /** In arrival order: a Set iterates as it was filled. */
10965
+ this.waiting = /* @__PURE__ */ new Set();
10966
+ if (!Number.isInteger(places) || places < 1) {
10967
+ throw new Error(`The file call gate needs at least 1 place, not ${places}.`);
10968
+ }
10969
+ }
10970
+ /** `work`'s outcome, or a {@link FileCallTimeoutError} once `timeoutMillis` pass from now. */
10971
+ run(work, timeoutMillis) {
10972
+ if (this.isStuck()) {
10973
+ return Promise.reject(new FileCallsStuckError());
10710
10974
  }
10975
+ return new Promise((resolve, reject) => {
10976
+ let answered = false;
10977
+ let holdsPlace = false;
10978
+ let isAbandoned = false;
10979
+ const answer = (outcome) => {
10980
+ if (!answered) {
10981
+ answered = true;
10982
+ clearTimeout(timer);
10983
+ outcome();
10984
+ }
10985
+ };
10986
+ const call = {
10987
+ begin: () => {
10988
+ holdsPlace = true;
10989
+ this.running += 1;
10990
+ let pending;
10991
+ try {
10992
+ pending = work();
10993
+ } catch (err) {
10994
+ pending = Promise.reject(err);
10995
+ }
10996
+ pending.then((value) => answer(() => resolve(value)), (err) => answer(() => reject(err))).finally(() => this.release(isAbandoned));
10997
+ },
10998
+ refuse: (err) => answer(() => reject(err))
10999
+ };
11000
+ const timer = setTimeout(() => {
11001
+ if (holdsPlace) {
11002
+ isAbandoned = true;
11003
+ this.abandoned += 1;
11004
+ } else {
11005
+ this.waiting.delete(call);
11006
+ }
11007
+ answer(() => reject(callTimeoutError(timeoutMillis)));
11008
+ if (this.isStuck()) {
11009
+ this.refuseWaiting();
11010
+ }
11011
+ }, timeoutMillis);
11012
+ if (this.running < this.places) {
11013
+ call.begin();
11014
+ } else {
11015
+ this.waiting.add(call);
11016
+ }
11017
+ });
10711
11018
  }
10712
- /** Sends whatever is held, if anything. Used when the terminal closes and by the timer. */
10713
- flush() {
10714
- this.disarm();
10715
- if (this.pendingBytes > 0) {
10716
- this.emitBytes(this.pendingBytes);
11019
+ release(wasAbandoned) {
11020
+ this.running -= 1;
11021
+ if (wasAbandoned) {
11022
+ this.abandoned -= 1;
11023
+ }
11024
+ for (const call of this.waiting) {
11025
+ if (this.running >= this.places) {
11026
+ return;
11027
+ }
11028
+ this.waiting.delete(call);
11029
+ call.begin();
10717
11030
  }
10718
11031
  }
10719
- dispose() {
10720
- this.disarm();
10721
- this.pending = [];
10722
- this.pendingBytes = 0;
11032
+ isStuck() {
11033
+ return this.abandoned >= this.places;
10723
11034
  }
10724
- get buffered() {
10725
- return this.pendingBytes;
11035
+ refuseWaiting() {
11036
+ const refused = [...this.waiting];
11037
+ this.waiting.clear();
11038
+ refused.forEach((call) => call.refuse(new FileCallsStuckError()));
10726
11039
  }
10727
- emitBytes(byteCount) {
10728
- const joined = Buffer.concat(this.pending, this.pendingBytes);
10729
- const frame = joined.subarray(0, byteCount);
10730
- const rest = joined.subarray(byteCount);
10731
- this.pending = rest.length > 0 ? [rest] : [];
10732
- this.pendingBytes = rest.length;
11040
+ };
11041
+ }
11042
+ });
11043
+
11044
+ // src/devices/files/fileProtectedPaths.ts
11045
+ function systemFoldersFor(platform3, environment) {
11046
+ if (platform3 === "win32") {
11047
+ return WINDOWS_SYSTEM_FOLDER_VARIABLES.map(([variable, fallback]) => environment[variable] || fallback);
11048
+ }
11049
+ return platform3 === "darwin" ? MACOS_SYSTEM_FOLDERS : LINUX_SYSTEM_FOLDERS;
11050
+ }
11051
+ function accountsFolderFor(platform3, environment) {
11052
+ if (platform3 === "win32") {
11053
+ const publicFolder = environment[WINDOWS_PUBLIC_FOLDER_VARIABLE];
11054
+ return publicFolder ? import_path10.default.win32.dirname(publicFolder) : WINDOWS_ACCOUNTS_FOLDER;
11055
+ }
11056
+ return platform3 === "darwin" ? MACOS_ACCOUNTS_FOLDER : POSIX_ACCOUNTS_FOLDER;
11057
+ }
11058
+ function agentFilesFor(platform3, home, environment, runningProgram, script) {
11059
+ const files = [installerBinaryPath(platform3, home, environment), runningProgram];
11060
+ if (script) {
11061
+ files.push(script);
11062
+ }
11063
+ const autostartFile = autostartFilePath(platform3, home);
11064
+ if (autostartFile) {
11065
+ files.push(autostartFile);
11066
+ }
11067
+ return [...new Set(files)];
11068
+ }
11069
+ function machineProtectedSources() {
11070
+ const home = import_os6.default.homedir();
11071
+ const script = isPackagedBinary() ? void 0 : process.argv[1];
11072
+ return {
11073
+ home,
11074
+ configFolder: getPinggyConfigDir(),
11075
+ systemFolders: systemFoldersFor(process.platform, process.env),
11076
+ accountsFolder: accountsFolderFor(process.platform, process.env),
11077
+ agentFiles: agentFilesFor(process.platform, home, process.env, process.execPath, script)
11078
+ };
11079
+ }
11080
+ function identityOf(stats) {
11081
+ return `${stats.dev}:${stats.ino}`;
11082
+ }
11083
+ function selfAndAncestors(target, paths) {
11084
+ const chain = [];
11085
+ let current = paths.resolve(target);
11086
+ for (; ; ) {
11087
+ chain.push(current);
11088
+ const parent = paths.dirname(current);
11089
+ if (parent === current) {
11090
+ return chain;
11091
+ }
11092
+ current = parent;
11093
+ }
11094
+ }
11095
+ function identityOrNull(read, callTimeoutMillis) {
11096
+ return callWithTimeout(read, callTimeoutMillis).then(identityOf, (err) => {
11097
+ if (err instanceof FileCallTimeoutError) {
11098
+ throw err;
11099
+ }
11100
+ return null;
11101
+ });
11102
+ }
11103
+ async function identitiesOf(target, remover, callTimeoutMillis) {
11104
+ const identities = await Promise.all([remover.lstat(target), remover.stat(target)].map((read) => identityOrNull(read, callTimeoutMillis)));
11105
+ return identities.filter((identity) => identity !== null);
11106
+ }
11107
+ async function realPathOrNull(target, remover, callTimeoutMillis) {
11108
+ try {
11109
+ return await callWithTimeout(remover.realpath(target), callTimeoutMillis);
11110
+ } catch (err) {
11111
+ if (err instanceof FileCallTimeoutError) {
11112
+ throw err;
11113
+ }
11114
+ return null;
11115
+ }
11116
+ }
11117
+ async function agentFileChains(files, paths, remover, callTimeoutMillis) {
11118
+ const realPaths = await Promise.all(files.map((file) => realPathOrNull(file, remover, callTimeoutMillis)));
11119
+ return files.flatMap((file, index) => {
11120
+ const realPath2 = realPaths[index];
11121
+ return realPath2 === null ? [] : [...selfAndAncestors(file, paths), ...selfAndAncestors(realPath2, paths)];
11122
+ });
11123
+ }
11124
+ async function addFolders(reasons, folders, message, remover, callTimeoutMillis) {
11125
+ const identities = await Promise.all(folders.map((folder) => identitiesOf(folder, remover, callTimeoutMillis)));
11126
+ for (const identity of identities.flat()) {
11127
+ reasons.set(identity, message);
11128
+ }
11129
+ }
11130
+ async function readProtectedSet(sources, paths, remover, callTimeoutMillis) {
11131
+ const reasons = /* @__PURE__ */ new Map();
11132
+ const agentChains = await agentFileChains(sources.agentFiles, paths, remover, callTimeoutMillis);
11133
+ await addFolders(reasons, agentChains, MESSAGE_PINGGY_PROGRAM, remover, callTimeoutMillis);
11134
+ const systemChains = sources.systemFolders.flatMap((folder) => selfAndAncestors(folder, paths));
11135
+ await addFolders(reasons, systemChains, MESSAGE_SYSTEM_FOLDER, remover, callTimeoutMillis);
11136
+ await addFolders(
11137
+ reasons,
11138
+ selfAndAncestors(sources.accountsFolder, paths),
11139
+ MESSAGE_ACCOUNTS_FOLDER,
11140
+ remover,
11141
+ callTimeoutMillis
11142
+ );
11143
+ const pinggyChains = [...selfAndAncestors(sources.home, paths), ...selfAndAncestors(sources.configFolder, paths)];
11144
+ await addFolders(reasons, pinggyChains, MESSAGE_PINGGY_FOLDER, remover, callTimeoutMillis);
11145
+ const [configFolder, accountsFolder] = await Promise.all([sources.configFolder, sources.accountsFolder].map((folder) => identityOrNull(remover.stat(folder), callTimeoutMillis)));
11146
+ return { reasons, configFolder, accountsFolder };
11147
+ }
11148
+ async function isInsideConfigFolder(directory, protectedSet, paths, remover, callTimeoutMillis) {
11149
+ if (protectedSet.configFolder === null) {
11150
+ return false;
11151
+ }
11152
+ const chain = selfAndAncestors(directory, paths);
11153
+ const identities = await Promise.all(chain.map((folder) => identityOrNull(remover.stat(folder), callTimeoutMillis)));
11154
+ return identities.includes(protectedSet.configFolder);
11155
+ }
11156
+ var import_os6, import_path10, MESSAGE_PINGGY_FOLDER, MESSAGE_PINGGY_PROGRAM, MESSAGE_SYSTEM_FOLDER, MESSAGE_ACCOUNTS_FOLDER, MESSAGE_ACCOUNT_FOLDER, LINUX_SYSTEM_FOLDERS, MACOS_SYSTEM_FOLDERS, WINDOWS_SYSTEM_FOLDER_VARIABLES, POSIX_ACCOUNTS_FOLDER, MACOS_ACCOUNTS_FOLDER, WINDOWS_ACCOUNTS_FOLDER, WINDOWS_PUBLIC_FOLDER_VARIABLE;
11157
+ var init_fileProtectedPaths = __esm({
11158
+ "src/devices/files/fileProtectedPaths.ts"() {
11159
+ "use strict";
11160
+ init_cjs_shims();
11161
+ import_os6 = __toESM(require("os"), 1);
11162
+ import_path10 = __toESM(require("path"), 1);
11163
+ init_servicePaths();
11164
+ init_configDir();
11165
+ init_nodePtyRuntime();
11166
+ init_fileSystem();
11167
+ MESSAGE_PINGGY_FOLDER = "Pinggy keeps this folder so the device stays connected.";
11168
+ MESSAGE_PINGGY_PROGRAM = "Pinggy needs this to keep the device connected.";
11169
+ MESSAGE_SYSTEM_FOLDER = "This is a system folder.";
11170
+ MESSAGE_ACCOUNTS_FOLDER = "This folder holds the accounts on this device.";
11171
+ MESSAGE_ACCOUNT_FOLDER = "This is an account's home folder.";
11172
+ LINUX_SYSTEM_FOLDERS = ["/bin", "/boot", "/etc", "/lib", "/lib64", "/sbin", "/usr", "/var"];
11173
+ MACOS_SYSTEM_FOLDERS = ["/System", "/Library", "/Applications", "/usr", "/bin", "/sbin", "/private"];
11174
+ WINDOWS_SYSTEM_FOLDER_VARIABLES = [
11175
+ ["SystemRoot", "C:\\Windows"],
11176
+ ["ProgramFiles", "C:\\Program Files"],
11177
+ ["ProgramFiles(x86)", "C:\\Program Files (x86)"],
11178
+ ["ProgramData", "C:\\ProgramData"]
11179
+ ];
11180
+ POSIX_ACCOUNTS_FOLDER = "/home";
11181
+ MACOS_ACCOUNTS_FOLDER = "/Users";
11182
+ WINDOWS_ACCOUNTS_FOLDER = "C:\\Users";
11183
+ WINDOWS_PUBLIC_FOLDER_VARIABLE = "PUBLIC";
11184
+ }
11185
+ });
11186
+
11187
+ // src/devices/files/fileDelete.ts
11188
+ async function prepareDelete(request2, dependencies) {
11189
+ const paths = pathsFor(dependencies.platform);
11190
+ const pathIssue = pathProblem(request2.path, paths);
11191
+ if (pathIssue) {
11192
+ return fileError(ERROR_INVALID_PATH, pathIssue);
11193
+ }
11194
+ const item = resolvedItem(request2.path, paths);
11195
+ const { remover, callTimeoutMillis } = dependencies;
11196
+ let stats;
11197
+ let parentStats;
11198
+ try {
11199
+ stats = await callWithTimeout(remover.lstat(item.path), callTimeoutMillis);
11200
+ parentStats = await callWithTimeout(remover.stat(item.parent), callTimeoutMillis);
11201
+ } catch (err) {
11202
+ return { error: deleteFailure(err) };
11203
+ }
11204
+ let protectedSet;
11205
+ let insideConfigFolder;
11206
+ try {
11207
+ protectedSet = await readProtectedSet(dependencies.protectedSources, paths, remover, callTimeoutMillis);
11208
+ insideConfigFolder = await isInsideConfigFolder(item.parent, protectedSet, paths, remover, callTimeoutMillis);
11209
+ } catch (err) {
11210
+ const code = err instanceof FileCallTimeoutError ? ERROR_FILE_TIMEOUT : ERROR_FILE_OPERATION_FAILED;
11211
+ return fileError(code, failureMessage(err, MESSAGE_PROTECTED_UNREAD));
11212
+ }
11213
+ if (insideConfigFolder) {
11214
+ return fileError(ERROR_PROTECTED_PATH, MESSAGE_PINGGY_FOLDER);
11215
+ }
11216
+ if (protectedSet.accountsFolder !== null && identityOf(parentStats) === protectedSet.accountsFolder) {
11217
+ return fileError(ERROR_PROTECTED_PATH, MESSAGE_ACCOUNT_FOLDER);
11218
+ }
11219
+ const reason = protectedSet.reasons.get(identityOf(stats));
11220
+ if (reason) {
11221
+ return fileError(ERROR_PROTECTED_PATH, reason);
11222
+ }
11223
+ if (stats.dev !== parentStats.dev) {
11224
+ return fileError(ERROR_MOUNT_POINT, MESSAGE_SELECTED_MOUNT);
11225
+ }
11226
+ return { target: item.path, name: item.name, stats, protectedSet };
11227
+ }
11228
+ async function runDelete(prepared, progress, dependencies) {
11229
+ const context = {
11230
+ device: prepared.stats.dev,
11231
+ protectedSet: prepared.protectedSet,
11232
+ progress,
11233
+ dependencies,
11234
+ paths: pathsFor(dependencies.platform)
11235
+ };
11236
+ let result = {};
11237
+ try {
11238
+ if (!await removeEntry(prepared.target, prepared.stats, context)) {
11239
+ result = fileError(ERROR_MOUNT_POINT, MESSAGE_MOUNT_INSIDE);
11240
+ }
11241
+ } catch (err) {
11242
+ result = { error: deleteFailure(err) };
11243
+ }
11244
+ progress.items_done += 1;
11245
+ return result;
11246
+ }
11247
+ function removeTree(target, stats, protectedSet, dependencies) {
11248
+ const context = {
11249
+ device: stats.dev,
11250
+ protectedSet,
11251
+ progress: { files_done: 0 },
11252
+ dependencies,
11253
+ paths: pathsFor(dependencies.platform)
11254
+ };
11255
+ return removeEntry(target, stats, context);
11256
+ }
11257
+ async function removeEntry(target, stats, context) {
11258
+ if (!stats.isDirectory()) {
11259
+ if (await removeWith(target, (entry) => context.dependencies.remover.unlink(entry), context)) {
11260
+ context.progress.files_done += 1;
11261
+ }
11262
+ return true;
11263
+ }
11264
+ return removeFolder(target, context);
11265
+ }
11266
+ async function removeFolder(folder, context) {
11267
+ const { remover, callTimeoutMillis } = context.dependencies;
11268
+ const removeFolderItself = (entry) => remover.rmdir(entry);
11269
+ try {
11270
+ if (await removeWith(folder, removeFolderItself, context)) {
11271
+ context.progress.files_done += 1;
11272
+ }
11273
+ return true;
11274
+ } catch (err) {
11275
+ if (!isNotEmpty(err)) {
11276
+ throw err;
11277
+ }
11278
+ }
11279
+ let names;
11280
+ try {
11281
+ names = await callWithTimeout(remover.readdir(folder), callTimeoutMillis);
11282
+ } catch (err) {
11283
+ if (isGone(err)) {
11284
+ return true;
11285
+ }
11286
+ throw err;
11287
+ }
11288
+ let removedAll = true;
11289
+ for (const name of names) {
11290
+ if (!await removeChild(context.paths.join(folder, name), context)) {
11291
+ removedAll = false;
11292
+ }
11293
+ }
11294
+ if (!removedAll) {
11295
+ return false;
11296
+ }
11297
+ if (await removeWith(folder, removeFolderItself, context)) {
11298
+ context.progress.files_done += 1;
11299
+ }
11300
+ return true;
11301
+ }
11302
+ async function removeChild(child, context) {
11303
+ let stats;
11304
+ try {
11305
+ stats = await callWithTimeout(
11306
+ context.dependencies.remover.lstat(child),
11307
+ context.dependencies.callTimeoutMillis
11308
+ );
11309
+ } catch (err) {
11310
+ if (isGone(err)) {
11311
+ return true;
11312
+ }
11313
+ throw err;
11314
+ }
11315
+ const reason = context.protectedSet.reasons.get(identityOf(stats));
11316
+ if (reason) {
11317
+ throw new ProtectedEntryError(reason);
11318
+ }
11319
+ if (stats.isDirectory() && stats.dev !== context.device) {
11320
+ return false;
11321
+ }
11322
+ return removeEntry(child, stats, context);
11323
+ }
11324
+ async function removeWith(target, remove, context) {
11325
+ const { remover, callTimeoutMillis, platform: platform3 } = context.dependencies;
11326
+ try {
11327
+ await callWithTimeout(remove(target), callTimeoutMillis);
11328
+ return true;
11329
+ } catch (err) {
11330
+ if (isGone(err)) {
11331
+ return false;
11332
+ }
11333
+ if (platform3 !== "win32" || errorCodeOf(err) !== "EPERM") {
11334
+ throw err;
11335
+ }
11336
+ try {
11337
+ await callWithTimeout(remover.chmod(target, WINDOWS_WRITABLE_MODE), callTimeoutMillis);
11338
+ } catch {
11339
+ throw err;
11340
+ }
11341
+ }
11342
+ try {
11343
+ await callWithTimeout(remove(target), callTimeoutMillis);
11344
+ return true;
11345
+ } catch (err) {
11346
+ if (isGone(err)) {
11347
+ return false;
11348
+ }
11349
+ throw err;
11350
+ }
11351
+ }
11352
+ function isGone(err) {
11353
+ return errorCodeOf(err) === "ENOENT";
11354
+ }
11355
+ function isNotEmpty(err) {
11356
+ const code = errorCodeOf(err);
11357
+ return code === "ENOTEMPTY" || code === "EEXIST";
11358
+ }
11359
+ function deleteFailure(err) {
11360
+ if (err instanceof FileCallTimeoutError) {
11361
+ return { code: ERROR_FILE_TIMEOUT, message: err.message };
11362
+ }
11363
+ if (err instanceof ProtectedEntryError) {
11364
+ return { code: ERROR_PROTECTED_PATH, message: err.message };
11365
+ }
11366
+ const message = failureMessage(err, MESSAGE_DELETE_FAILED);
11367
+ switch (errorCodeOf(err)) {
11368
+ case "ENOENT":
11369
+ case "ENOTDIR":
11370
+ return { code: ERROR_PATH_NOT_FOUND, message };
11371
+ case "EACCES":
11372
+ case "EPERM":
11373
+ case "EROFS":
11374
+ return { code: ERROR_PERMISSION_DENIED, message };
11375
+ default:
11376
+ return { code: ERROR_FILE_OPERATION_FAILED, message };
11377
+ }
11378
+ }
11379
+ var WINDOWS_WRITABLE_MODE, MESSAGE_DELETE_FAILED, MESSAGE_PROTECTED_UNREAD, MESSAGE_SELECTED_MOUNT, MESSAGE_MOUNT_INSIDE, ProtectedEntryError;
11380
+ var init_fileDelete = __esm({
11381
+ "src/devices/files/fileDelete.ts"() {
11382
+ "use strict";
11383
+ init_cjs_shims();
11384
+ init_file_schema();
11385
+ init_fileProtectedPaths();
11386
+ init_fileSystem();
11387
+ WINDOWS_WRITABLE_MODE = 438;
11388
+ MESSAGE_DELETE_FAILED = "The item could not be deleted.";
11389
+ MESSAGE_PROTECTED_UNREAD = "The protected folders could not be read in time.";
11390
+ MESSAGE_SELECTED_MOUNT = "This folder is a mounted disk. Open it to delete what is inside.";
11391
+ MESSAGE_MOUNT_INSIDE = "Another disk is mounted inside. Pinggy left it in place.";
11392
+ ProtectedEntryError = class extends Error {
11393
+ };
11394
+ }
11395
+ });
11396
+
11397
+ // src/devices/files/fileCopy.ts
11398
+ function randomHiddenNameSuffix() {
11399
+ return import_crypto3.default.randomBytes(HIDDEN_SUFFIX_BYTES).toString("hex");
11400
+ }
11401
+ async function prepareCopy(request2, dependencies) {
11402
+ try {
11403
+ return await checkedCopy(request2, dependencies);
11404
+ } catch (err) {
11405
+ return refusalOf(err);
11406
+ }
11407
+ }
11408
+ function refusalOf(err) {
11409
+ if (err instanceof RequestRefusal) {
11410
+ return err.refusal;
11411
+ }
11412
+ const code = err instanceof FileCallTimeoutError ? ERROR_FILE_TIMEOUT : ERROR_FILE_OPERATION_FAILED;
11413
+ return fileError(code, failureMessage(err, MESSAGE_FOLDER_UNREADABLE));
11414
+ }
11415
+ async function checkedCopy(request2, dependencies) {
11416
+ const { copier, platform: platform3 } = dependencies;
11417
+ const paths = pathsFor(platform3);
11418
+ const { source, destination } = resolvedItems(request2, paths);
11419
+ checkTargetName(destination.name, platform3);
11420
+ const sourceStats = await sourceItemStats(source.path, copier, MESSAGE_COPY_FAILED);
11421
+ if (isSpecial(sourceStats)) {
11422
+ throw new RequestRefusal(fileError(ERROR_SPECIAL_FILE, MESSAGE_SPECIAL_SELECTED));
11423
+ }
11424
+ const destinationStats = await folderStats(destination.parent, copier);
11425
+ await refuseIntoItself(sourceStats, destination.parent, dependencies, MESSAGE_INTO_ITSELF);
11426
+ const onConflict = request2.on_conflict ?? ON_CONFLICT_FAIL;
11427
+ if (onConflict === ON_CONFLICT_FAIL || onConflict === ON_CONFLICT_REPLACE) {
11428
+ const target = await lstatOrNull(destination.path, copier);
11429
+ if (onConflict === ON_CONFLICT_FAIL && target !== null) {
11430
+ throw new RequestRefusal(targetTakenRefusal());
11431
+ }
11432
+ if (onConflict === ON_CONFLICT_REPLACE && target !== null && identityOf(target) === identityOf(sourceStats)) {
11433
+ throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, MESSAGE_REPLACE_ITSELF));
11434
+ }
11435
+ if (onConflict === ON_CONFLICT_REPLACE) {
11436
+ await refuseReplacingAHolder(target, source.parent, dependencies);
11437
+ }
11438
+ }
11439
+ const replaceGuard = onConflict === ON_CONFLICT_REPLACE ? await removalGuard(
11440
+ destination.parent,
11441
+ destinationStats,
11442
+ await readProtectedFolders(dependencies),
11443
+ dependencies
11444
+ ) : null;
11445
+ return {
11446
+ source: source.path,
11447
+ sourceStats,
11448
+ sourceName: source.name,
11449
+ destinationDirectory: destination.parent,
11450
+ targetName: destination.name,
11451
+ onConflict,
11452
+ destinationDevice: destinationStats.dev,
11453
+ replaceGuard
11454
+ };
11455
+ }
11456
+ function resolvedItems(request2, paths) {
11457
+ for (const requested of [request2.source_path, request2.destination_path]) {
11458
+ const issue = pathProblem(requested, paths);
11459
+ if (issue) {
11460
+ throw new RequestRefusal(fileError(ERROR_INVALID_PATH, issue));
11461
+ }
11462
+ }
11463
+ const source = resolvedItem(request2.source_path, paths);
11464
+ const requestedDestination = resolvedItem(request2.destination_path, paths);
11465
+ const destination = requestedDestination.name === source.name ? requestedDestination : withTrimmedName(requestedDestination);
11466
+ if (isRoot(source.path, paths) || isRoot(destination.path, paths)) {
11467
+ throw new RequestRefusal(fileError(ERROR_INVALID_PATH, MESSAGE_ROOT));
11468
+ }
11469
+ return { source, destination };
11470
+ }
11471
+ function checkTargetName(targetName, platform3) {
11472
+ const nameIssue = nameProblem(targetName, platform3);
11473
+ if (nameIssue) {
11474
+ throw new RequestRefusal(fileError(ERROR_INVALID_PAYLOAD2, nameIssue));
11475
+ }
11476
+ const windowsIssue = platform3 === "win32" ? windowsNameProblem(targetName, "A name") : null;
11477
+ if (windowsIssue) {
11478
+ throw new RequestRefusal(fileError(ERROR_INVALID_NAME, windowsIssue));
11479
+ }
11480
+ }
11481
+ async function sourceItemStats(source, copier, fallbackMessage) {
11482
+ try {
11483
+ return await copier.lstat(source);
11484
+ } catch (err) {
11485
+ throw new RequestRefusal({ error: copyFailure(err, fallbackMessage) });
11486
+ }
11487
+ }
11488
+ async function folderStats(folder, copier) {
11489
+ let stats;
11490
+ try {
11491
+ stats = await copier.stat(folder);
11492
+ } catch (err) {
11493
+ if (err instanceof FileCallTimeoutError) {
11494
+ throw err;
11495
+ }
11496
+ throw new RequestRefusal(folderFailure(err));
11497
+ }
11498
+ if (!stats.isDirectory()) {
11499
+ throw new RequestRefusal(fileError(ERROR_NOT_A_DIRECTORY, MESSAGE_NOT_A_FOLDER));
11500
+ }
11501
+ return stats;
11502
+ }
11503
+ function folderFailure(err) {
11504
+ const message = failureMessage(err, MESSAGE_FOLDER_UNREADABLE);
11505
+ switch (errorCodeOf(err)) {
11506
+ case "ENOENT":
11507
+ case "ENOTDIR":
11508
+ return fileError(ERROR_PATH_NOT_FOUND, message);
11509
+ case "EACCES":
11510
+ case "EPERM":
11511
+ return fileError(ERROR_PERMISSION_DENIED, message);
11512
+ default:
11513
+ return fileError(ERROR_FILE_OPERATION_FAILED, message);
11514
+ }
11515
+ }
11516
+ async function refuseIntoItself(source, destinationDirectory, dependencies, message) {
11517
+ if (await folderHolds(source, destinationDirectory, dependencies)) {
11518
+ throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, message));
11519
+ }
11520
+ }
11521
+ async function refuseReplacingAHolder(target, sourceDirectory, dependencies) {
11522
+ if (await folderHolds(target, sourceDirectory, dependencies)) {
11523
+ throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, MESSAGE_REPLACE_HOLDER));
11524
+ }
11525
+ }
11526
+ async function folderHolds(candidate, folder, dependencies) {
11527
+ if (candidate === null || !candidate.isDirectory()) {
11528
+ return false;
11529
+ }
11530
+ const { copier } = dependencies;
11531
+ const paths = pathsFor(dependencies.platform);
11532
+ const realFolder = await copier.realpath(folder);
11533
+ const chain = new Set(await Promise.all(selfAndAncestors(realFolder, paths).map((each) => identityOrNull2(copier.stat(each)))));
11534
+ return chain.has(identityOf(candidate));
11535
+ }
11536
+ function targetTakenRefusal() {
11537
+ return fileError(ERROR_FILE_EXISTS, MESSAGE_TARGET_TAKEN);
11538
+ }
11539
+ async function readProtectedFolders(dependencies) {
11540
+ const { remover, callTimeoutMillis, protectedSources } = dependencies;
11541
+ try {
11542
+ return await readProtectedSet(protectedSources, pathsFor(dependencies.platform), remover, callTimeoutMillis);
11543
+ } catch (err) {
11544
+ throw protectedUnread(err);
11545
+ }
11546
+ }
11547
+ async function removalGuard(folder, stats, protectedSet, dependencies) {
11548
+ const { remover, callTimeoutMillis } = dependencies;
11549
+ try {
11550
+ const insideConfigFolder = await isInsideConfigFolder(
11551
+ folder,
11552
+ protectedSet,
11553
+ pathsFor(dependencies.platform),
11554
+ remover,
11555
+ callTimeoutMillis
11556
+ );
11557
+ const inAccountsFolder = protectedSet.accountsFolder !== null && identityOf(stats) === protectedSet.accountsFolder;
11558
+ return { protectedSet, insideConfigFolder, inAccountsFolder };
11559
+ } catch (err) {
11560
+ throw protectedUnread(err);
11561
+ }
11562
+ }
11563
+ function protectedUnread(err) {
11564
+ const code = err instanceof FileCallTimeoutError ? ERROR_FILE_TIMEOUT : ERROR_FILE_OPERATION_FAILED;
11565
+ return new RequestRefusal(fileError(code, failureMessage(err, MESSAGE_PROTECTED_UNREAD2)));
11566
+ }
11567
+ async function runCopy(prepared, progress, dependencies) {
11568
+ const counted = Object.assign(progress, { bytes_done: progress.bytes_done ?? 0 });
11569
+ const totals = await countSource(prepared, dependencies);
11570
+ counted.files_total = totals.files;
11571
+ counted.bytes_total = totals.bytes;
11572
+ const noSpace = await noSpaceRefusal(totals.bytes, prepared.destinationDirectory, dependencies.copier);
11573
+ if (noSpace) {
11574
+ return noSpace;
11575
+ }
11576
+ const walk = {
11577
+ copier: dependencies.copier,
11578
+ paths: pathsFor(dependencies.platform),
11579
+ platform: dependencies.platform,
11580
+ progress: counted,
11581
+ specialFilesLeftOut: 0
11582
+ };
11583
+ const outcome = await copyItem(prepared, walk, dependencies);
11584
+ counted.items_done += 1;
11585
+ return outcomeAnswer(outcome);
11586
+ }
11587
+ function outcomeAnswer(outcome) {
11588
+ if (outcome === SKIPPED) {
11589
+ return { skipped: true };
11590
+ }
11591
+ return outcome === null ? {} : { error: outcome };
11592
+ }
11593
+ async function noSpaceRefusal(neededBytes, destinationDirectory, copier) {
11594
+ const freeBytes = await copier.freeBytes(destinationDirectory).catch(() => null);
11595
+ if (freeBytes === null || BigInt(neededBytes) <= freeBytes) {
11596
+ return null;
11597
+ }
11598
+ return fileError(ERROR_NO_SPACE, `The copy needs ${formatBytes(neededBytes)}. The destination disk has ${formatBytes(freeBytes)} free.`);
11599
+ }
11600
+ async function countSource(prepared, dependencies) {
11601
+ const { copier } = dependencies;
11602
+ const paths = pathsFor(dependencies.platform);
11603
+ const totals = newCountTotals();
11604
+ const target = paths.join(prepared.destinationDirectory, prepared.targetName);
11605
+ if (prepared.onConflict === ON_CONFLICT_SKIP && await lstatOrNull(target, copier).catch(() => null)) {
11606
+ return totals;
11607
+ }
11608
+ await countEntry(prepared.source, totals, copier, paths, null);
11609
+ return totals;
11610
+ }
11611
+ function newCountTotals() {
11612
+ return { files: 0, bytes: 0, specialFiles: 0, mountedDisks: 0 };
11613
+ }
11614
+ async function countEntry(entry, totals, copier, paths, stopAtDevice) {
11615
+ let stats;
11616
+ try {
11617
+ stats = await copier.lstat(entry);
11618
+ } catch {
11619
+ return;
11620
+ }
11621
+ if (isSpecial(stats)) {
11622
+ totals.specialFiles += 1;
11623
+ return;
11624
+ }
11625
+ if (stats.isDirectory() && stopAtDevice !== null && stats.dev !== stopAtDevice) {
11626
+ totals.mountedDisks += 1;
11627
+ return;
11628
+ }
11629
+ totals.files += 1;
11630
+ if (stats.isFile()) {
11631
+ totals.bytes += Number(stats.size);
11632
+ return;
11633
+ }
11634
+ if (!stats.isDirectory()) {
11635
+ return;
11636
+ }
11637
+ let children;
11638
+ try {
11639
+ children = await copier.readdir(entry);
11640
+ } catch {
11641
+ return;
11642
+ }
11643
+ for (const child of children) {
11644
+ await countEntry(paths.join(entry, child), totals, copier, paths, stopAtDevice);
11645
+ }
11646
+ }
11647
+ async function copyItem(prepared, walk, dependencies) {
11648
+ try {
11649
+ if (prepared.onConflict === ON_CONFLICT_REPLACE) {
11650
+ const refusal = await replaceTarget(prepared, walk, dependencies);
11651
+ if (refusal) {
11652
+ return refusal;
11653
+ }
11654
+ } else if (await copyToFreeName(
11655
+ prepared.source,
11656
+ prepared.sourceStats,
11657
+ prepared.targetName,
11658
+ prepared,
11659
+ walk
11660
+ ) === SKIPPED) {
11661
+ return SKIPPED;
11662
+ }
11663
+ } catch (err) {
11664
+ return copyFailure(err, MESSAGE_COPY_FAILED);
11665
+ }
11666
+ return walk.specialFilesLeftOut > 0 ? specialFilesLeftOut(walk.specialFilesLeftOut) : null;
11667
+ }
11668
+ async function copyToFreeName(source, stats, targetName, prepared, walk) {
11669
+ let candidate = targetName;
11670
+ for (let number = 1; ; number++) {
11671
+ try {
11672
+ await copyEntry(source, stats, walk.paths.join(prepared.destinationDirectory, candidate), walk, true);
11673
+ return null;
11674
+ } catch (err) {
11675
+ if (!(err instanceof TakenError)) {
11676
+ throw err;
11677
+ }
11678
+ if (prepared.onConflict === ON_CONFLICT_SKIP) {
11679
+ return SKIPPED;
11680
+ }
11681
+ if (prepared.onConflict !== ON_CONFLICT_KEEP_BOTH || number > MAX_KEEP_BOTH_NUMBER) {
11682
+ throw err;
11683
+ }
11684
+ candidate = keepBothName(targetName, stats.isDirectory(), number);
11685
+ }
11686
+ }
11687
+ }
11688
+ async function replaceTarget(prepared, walk, dependencies) {
11689
+ const { copier, paths } = walk;
11690
+ const { source, sourceStats: stats, targetName } = prepared;
11691
+ const guard = prepared.replaceGuard;
11692
+ const target = paths.join(prepared.destinationDirectory, targetName);
11693
+ const existing = await lstatOrNull(target, copier);
11694
+ if (existing === null) {
11695
+ await copyEntry(source, stats, target, walk, true);
11696
+ return null;
11697
+ }
11698
+ const refusal = replaceRefusal(existing, stats, prepared.destinationDevice, guard);
11699
+ if (refusal) {
11700
+ return refusal;
11701
+ }
11702
+ const suffix = dependencies.hiddenNameSuffix();
11703
+ const hiddenCopy = paths.join(prepared.destinationDirectory, hiddenName(targetName, HIDDEN_COPY_MARK, suffix));
11704
+ try {
11705
+ await copyEntry(source, stats, hiddenCopy, walk, true);
11706
+ } catch (err) {
11707
+ if (!(err instanceof TakenError)) {
11708
+ await removeQuietly2(hiddenCopy, guard.protectedSet, dependencies);
11709
+ }
11710
+ throw err;
11711
+ }
11712
+ let oldName;
11713
+ try {
11714
+ oldName = await swapIn(
11715
+ hiddenCopy,
11716
+ prepared.destinationDirectory,
11717
+ targetName,
11718
+ existing,
11719
+ stats.isDirectory(),
11720
+ suffix,
11721
+ copier,
11722
+ paths
11723
+ );
11724
+ } catch (err) {
11725
+ await removeQuietly2(hiddenCopy, guard.protectedSet, dependencies);
11726
+ throw err;
11727
+ }
11728
+ if (oldName === null) {
11729
+ return null;
11730
+ }
11731
+ return removeOld(
11732
+ paths.join(prepared.destinationDirectory, oldName),
11733
+ oldName,
11734
+ existing,
11735
+ guard.protectedSet,
11736
+ dependencies,
11737
+ MESSAGE_COPY_IN_PLACE
11738
+ );
11739
+ }
11740
+ async function swapIn(incoming, folder, targetName, existing, incomingIsFolder, suffix, copier, paths) {
11741
+ const target = paths.join(folder, targetName);
11742
+ if (!existing.isDirectory() && !incomingIsFolder) {
11743
+ await copier.rename(incoming, target);
11744
+ return null;
11745
+ }
11746
+ const oldName = hiddenName(targetName, HIDDEN_OLD_MARK, suffix);
11747
+ const hiddenOld = paths.join(folder, oldName);
11748
+ await copier.rename(target, hiddenOld);
11749
+ try {
11750
+ await copier.rename(incoming, target);
11751
+ } catch (err) {
11752
+ await copier.rename(hiddenOld, target).catch(() => void 0);
11753
+ throw err;
11754
+ }
11755
+ return oldName;
11756
+ }
11757
+ function replaceRefusal(existing, source, destinationDevice, guard) {
11758
+ if (identityOf(existing) === identityOf(source)) {
11759
+ return { code: ERROR_INVALID_DESTINATION, message: MESSAGE_REPLACE_ITSELF };
11760
+ }
11761
+ return protectedRefusal(existing, destinationDevice, guard, MESSAGE_REPLACE_MOUNT);
11762
+ }
11763
+ function protectedRefusal(stats, folderDevice, guard, mountMessage) {
11764
+ if (guard.insideConfigFolder) {
11765
+ return { code: ERROR_PROTECTED_PATH, message: MESSAGE_PINGGY_FOLDER };
11766
+ }
11767
+ if (guard.inAccountsFolder) {
11768
+ return { code: ERROR_PROTECTED_PATH, message: MESSAGE_ACCOUNT_FOLDER };
11769
+ }
11770
+ const reason = guard.protectedSet.reasons.get(identityOf(stats));
11771
+ if (reason) {
11772
+ return { code: ERROR_PROTECTED_PATH, message: reason };
11773
+ }
11774
+ if (stats.dev !== folderDevice) {
11775
+ return { code: ERROR_MOUNT_POINT, message: mountMessage };
11776
+ }
11777
+ return null;
11778
+ }
11779
+ async function removeOld(hiddenOld, oldName, existing, protectedSet, dependencies, inPlaceMessage) {
11780
+ try {
11781
+ if (await removeTree(hiddenOld, existing, protectedSet, deleteDependencies(dependencies))) {
11782
+ return null;
11783
+ }
11784
+ return { code: ERROR_MOUNT_POINT, message: `${inPlaceMessage} ${oldName}: ${REASON_MOUNT_INSIDE}` };
11785
+ } catch (err) {
11786
+ const failure2 = deleteFailure(err);
11787
+ const message = sanitizeErrorMessage(`${inPlaceMessage} ${oldName}: ${failure2.message}`) ?? failure2.message;
11788
+ return { code: failure2.code, message };
11789
+ }
11790
+ }
11791
+ async function removeQuietly2(entry, protectedSet, dependencies) {
11792
+ try {
11793
+ const stats = await dependencies.remover.lstat(entry);
11794
+ await removeTree(entry, stats, protectedSet, deleteDependencies(dependencies));
11795
+ } catch {
11796
+ }
11797
+ }
11798
+ function deleteDependencies(dependencies) {
11799
+ const { remover, platform: platform3, protectedSources, callTimeoutMillis } = dependencies;
11800
+ return { remover, platform: platform3, protectedSources, callTimeoutMillis };
11801
+ }
11802
+ async function copyEntry(source, stats, target, walk, top) {
11803
+ if (stats.isSymbolicLink()) {
11804
+ await copyLink(source, target, walk, top);
11805
+ } else if (stats.isDirectory()) {
11806
+ await copyFolder(source, stats, target, walk, top);
11807
+ } else if (stats.isFile()) {
11808
+ await copyFile2(source, stats, target, walk, top);
11809
+ } else {
11810
+ walk.specialFilesLeftOut += 1;
11811
+ }
11812
+ }
11813
+ async function copyFile2(source, stats, target, walk, top) {
11814
+ const { copier, progress } = walk;
11815
+ const reader = await copier.openToRead(source);
11816
+ let writer;
11817
+ try {
11818
+ writer = await created(copier.createFile(target), top);
11819
+ } catch (err) {
11820
+ await closeQuietly(reader, copier);
11821
+ throw err;
11822
+ }
11823
+ const buffer = Buffer.allocUnsafe(Math.min(COPY_PIECE_BYTES, Math.max(SMALL_PIECE_BYTES, Number(stats.size) + 1)));
11824
+ try {
11825
+ for (; ; ) {
11826
+ const bytesRead = await copier.read(reader, buffer);
11827
+ if (bytesRead === 0) {
11828
+ break;
11829
+ }
11830
+ await copier.write(writer, buffer, bytesRead);
11831
+ progress.bytes_done += bytesRead;
11832
+ }
11833
+ await copier.close(writer);
11834
+ } catch (err) {
11835
+ await closeQuietly(writer, copier);
11836
+ await copier.unlink(target).catch(() => void 0);
11837
+ throw err;
11838
+ } finally {
11839
+ await closeQuietly(reader, copier);
11840
+ }
11841
+ await keepModeAndTimes(target, stats, copier);
11842
+ progress.files_done += 1;
11843
+ }
11844
+ async function copyFolder(source, stats, target, walk, top) {
11845
+ const { copier, paths } = walk;
11846
+ await created(copier.mkdir(target), top);
11847
+ walk.progress.files_done += 1;
11848
+ for (const child of await copier.readdir(source)) {
11849
+ const childSource = paths.join(source, child);
11850
+ let childStats;
11851
+ try {
11852
+ childStats = await copier.lstat(childSource);
11853
+ } catch (err) {
11854
+ if (errorCodeOf(err) === "ENOENT") {
11855
+ continue;
11856
+ }
11857
+ throw err;
11858
+ }
11859
+ await copyEntry(childSource, childStats, paths.join(target, child), walk, false);
11860
+ }
11861
+ await keepModeAndTimes(target, stats, copier);
11862
+ }
11863
+ async function copyLink(source, target, walk, top) {
11864
+ const { copier } = walk;
11865
+ const linkText = await copier.readlink(source);
11866
+ const type = walk.platform === "win32" ? await linkTypeOf(source, copier) : LINK_TYPE_FILE;
11867
+ await created(copier.symlink(linkText, target, type), top);
11868
+ walk.progress.files_done += 1;
11869
+ }
11870
+ async function linkTypeOf(link, copier) {
11871
+ try {
11872
+ return (await copier.stat(link)).isDirectory() ? LINK_TYPE_FOLDER : LINK_TYPE_FILE;
11873
+ } catch (err) {
11874
+ if (err instanceof FileCallTimeoutError) {
11875
+ throw err;
11876
+ }
11877
+ return LINK_TYPE_FILE;
11878
+ }
11879
+ }
11880
+ async function keepModeAndTimes(target, stats, copier) {
11881
+ await copier.utimes(target, stats.atime, stats.mtime).catch(() => void 0);
11882
+ await copier.chmod(target, Number(stats.mode & PERMISSION_BITS)).catch(() => void 0);
11883
+ }
11884
+ async function created(making, top) {
11885
+ try {
11886
+ return await making;
11887
+ } catch (err) {
11888
+ if (top && errorCodeOf(err) === "EEXIST") {
11889
+ throw new TakenError(MESSAGE_NAME_TAKEN);
11890
+ }
11891
+ throw err;
11892
+ }
11893
+ }
11894
+ async function closeQuietly(handle, copier) {
11895
+ await copier.close(handle).catch(() => void 0);
11896
+ }
11897
+ function keepBothName(name, isFolder, number) {
11898
+ const suffix = ` (${number})`;
11899
+ const dot = isFolder ? -1 : name.lastIndexOf(EXTENSION_SEPARATOR2);
11900
+ let stem = dot > 0 ? name.slice(0, dot) : name;
11901
+ let extension = dot > 0 ? name.slice(dot) : "";
11902
+ if (Buffer.byteLength(suffix + extension, "utf8") >= MAX_NAME_BYTES) {
11903
+ stem = name;
11904
+ extension = "";
11905
+ }
11906
+ const room = MAX_NAME_BYTES - Buffer.byteLength(suffix + extension, "utf8");
11907
+ return `${cutToBytes(stem, room)}${suffix}${extension}`;
11908
+ }
11909
+ function hiddenName(targetName, mark, suffix) {
11910
+ const tail = `.pinggy-${mark}-${suffix}`;
11911
+ const room = MAX_NAME_BYTES - Buffer.byteLength(HIDDEN_NAME_PREFIX2 + tail, "utf8");
11912
+ return `${HIDDEN_NAME_PREFIX2}${cutToBytes(targetName, room)}${tail}`;
11913
+ }
11914
+ function cutToBytes(text, maxBytes) {
11915
+ let bytes = 0;
11916
+ let kept = "";
11917
+ for (const character of text) {
11918
+ const characterBytes = Buffer.byteLength(character, "utf8");
11919
+ if (bytes + characterBytes > maxBytes) {
11920
+ break;
11921
+ }
11922
+ kept += character;
11923
+ bytes += characterBytes;
11924
+ }
11925
+ return kept;
11926
+ }
11927
+ function formatBytes(bytes) {
11928
+ let value = Number(bytes);
11929
+ let unit = 0;
11930
+ while (value >= BYTES_PER_UNIT && unit < BYTE_UNITS.length - 1) {
11931
+ value /= BYTES_PER_UNIT;
11932
+ unit += 1;
11933
+ }
11934
+ if (unit > 0) {
11935
+ return `${value.toFixed(1)} ${BYTE_UNITS[unit]}`;
11936
+ }
11937
+ return value === 1 ? `1 ${BYTE_UNIT_SINGULAR}` : `${value} ${BYTE_UNITS[0]}`;
11938
+ }
11939
+ function isSpecial(stats) {
11940
+ return !stats.isFile() && !stats.isDirectory() && !stats.isSymbolicLink();
11941
+ }
11942
+ function specialFilesLeftOut(count) {
11943
+ const message = count === 1 ? "1 socket, pipe or device file inside was left out." : `${count} sockets, pipes or device files inside were left out.`;
11944
+ return { code: ERROR_SPECIAL_FILE, message };
11945
+ }
11946
+ async function lstatOrNull(target, copier) {
11947
+ try {
11948
+ return await copier.lstat(target);
11949
+ } catch (err) {
11950
+ if (err instanceof FileCallTimeoutError) {
11951
+ throw err;
11952
+ }
11953
+ return null;
11954
+ }
11955
+ }
11956
+ async function identityOrNull2(read) {
11957
+ try {
11958
+ return identityOf(await read);
11959
+ } catch (err) {
11960
+ if (err instanceof FileCallTimeoutError) {
11961
+ throw err;
11962
+ }
11963
+ return null;
11964
+ }
11965
+ }
11966
+ function copyFailure(err, fallbackMessage) {
11967
+ if (err instanceof TakenError) {
11968
+ return { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN };
11969
+ }
11970
+ if (err instanceof FileCallTimeoutError) {
11971
+ return { code: ERROR_FILE_TIMEOUT, message: err.message };
11972
+ }
11973
+ const message = failureMessage(err, fallbackMessage);
11974
+ switch (errorCodeOf(err)) {
11975
+ case "ENOENT":
11976
+ case "ENOTDIR":
11977
+ return { code: ERROR_PATH_NOT_FOUND, message };
11978
+ case "EEXIST":
11979
+ return { code: ERROR_FILE_EXISTS, message };
11980
+ case "EACCES":
11981
+ case "EPERM":
11982
+ case "EROFS":
11983
+ return { code: ERROR_PERMISSION_DENIED, message };
11984
+ case "ENOSPC":
11985
+ case "EDQUOT":
11986
+ return { code: ERROR_NO_SPACE, message };
11987
+ default:
11988
+ return { code: ERROR_FILE_OPERATION_FAILED, message };
11989
+ }
11990
+ }
11991
+ var import_crypto3, COPY_PIECE_BYTES, SMALL_PIECE_BYTES, PERMISSION_BITS, MAX_KEEP_BOTH_NUMBER, EXTENSION_SEPARATOR2, HIDDEN_NAME_PREFIX2, HIDDEN_COPY_MARK, HIDDEN_OLD_MARK, HIDDEN_SUFFIX_BYTES, LINK_TYPE_FILE, LINK_TYPE_FOLDER, BYTES_PER_UNIT, BYTE_UNITS, BYTE_UNIT_SINGULAR, MESSAGE_FOLDER_UNREADABLE, MESSAGE_NOT_A_FOLDER, MESSAGE_ROOT, MESSAGE_INTO_ITSELF, MESSAGE_REPLACE_ITSELF, MESSAGE_REPLACE_HOLDER, MESSAGE_TARGET_TAKEN, MESSAGE_PROTECTED_UNREAD2, MESSAGE_SPECIAL_SELECTED, MESSAGE_REPLACE_MOUNT, MESSAGE_COPY_FAILED, MESSAGE_COPY_IN_PLACE, REASON_MOUNT_INSIDE, TakenError, RequestRefusal, SKIPPED;
11992
+ var init_fileCopy = __esm({
11993
+ "src/devices/files/fileCopy.ts"() {
11994
+ "use strict";
11995
+ init_cjs_shims();
11996
+ import_crypto3 = __toESM(require("crypto"), 1);
11997
+ init_tunnelList();
11998
+ init_file_schema();
11999
+ init_fileDelete();
12000
+ init_fileProtectedPaths();
12001
+ init_fileSystem();
12002
+ COPY_PIECE_BYTES = 1024 * 1024;
12003
+ SMALL_PIECE_BYTES = 4096;
12004
+ PERMISSION_BITS = 0o777n;
12005
+ MAX_KEEP_BOTH_NUMBER = 1e3;
12006
+ EXTENSION_SEPARATOR2 = ".";
12007
+ HIDDEN_NAME_PREFIX2 = ".";
12008
+ HIDDEN_COPY_MARK = "copy";
12009
+ HIDDEN_OLD_MARK = "old";
12010
+ HIDDEN_SUFFIX_BYTES = 4;
12011
+ LINK_TYPE_FILE = "file";
12012
+ LINK_TYPE_FOLDER = "dir";
12013
+ BYTES_PER_UNIT = 1e3;
12014
+ BYTE_UNITS = ["bytes", "KB", "MB", "GB", "TB", "PB"];
12015
+ BYTE_UNIT_SINGULAR = "byte";
12016
+ MESSAGE_FOLDER_UNREADABLE = "The folder could not be read.";
12017
+ MESSAGE_NOT_A_FOLDER = "The path is not a folder.";
12018
+ MESSAGE_ROOT = "A drive or filesystem root cannot be copied or moved.";
12019
+ MESSAGE_INTO_ITSELF = "A folder cannot be copied into itself.";
12020
+ MESSAGE_REPLACE_ITSELF = "An item cannot replace itself.";
12021
+ MESSAGE_REPLACE_HOLDER = "An item cannot replace a folder that holds it.";
12022
+ MESSAGE_TARGET_TAKEN = "1 item already exists in the destination.";
12023
+ MESSAGE_PROTECTED_UNREAD2 = "The protected folders could not be read in time.";
12024
+ MESSAGE_SPECIAL_SELECTED = "This is a socket, pipe or device file. Pinggy cannot copy it.";
12025
+ MESSAGE_REPLACE_MOUNT = "This item is a mounted disk. Pinggy does not replace it.";
12026
+ MESSAGE_COPY_FAILED = "The item could not be copied.";
12027
+ MESSAGE_COPY_IN_PLACE = "The copy is in place. The old one stays as";
12028
+ REASON_MOUNT_INSIDE = "a disk is mounted inside it.";
12029
+ TakenError = class extends Error {
12030
+ };
12031
+ RequestRefusal = class extends Error {
12032
+ constructor(refusal) {
12033
+ super(refusal.error.message);
12034
+ this.refusal = refusal;
12035
+ }
12036
+ };
12037
+ SKIPPED = "skipped";
12038
+ }
12039
+ });
12040
+
12041
+ // src/devices/files/fileList.ts
12042
+ function folderReadFailure(err) {
12043
+ const message = failureMessage(err, MESSAGE_LIST_FAILED);
12044
+ if (err instanceof FileCallTimeoutError) {
12045
+ return fileError(ERROR_FILE_TIMEOUT, message);
12046
+ }
12047
+ switch (errorCodeOf(err)) {
12048
+ case "ENOENT":
12049
+ return fileError(ERROR_PATH_NOT_FOUND, message);
12050
+ case "ENOTDIR":
12051
+ return fileError(ERROR_NOT_A_DIRECTORY, message);
12052
+ case "EACCES":
12053
+ case "EPERM":
12054
+ return fileError(ERROR_PERMISSION_DENIED, message);
12055
+ default:
12056
+ return fileError(ERROR_FILE_OPERATION_FAILED, message);
12057
+ }
12058
+ }
12059
+ function compareNames(left, right) {
12060
+ const byCollator = NAME_COLLATOR.compare(left, right);
12061
+ if (byCollator !== 0) return byCollator;
12062
+ if (left === right) return 0;
12063
+ return left < right ? -1 : 1;
12064
+ }
12065
+ async function readSortKeys(folder, dirents, dependencies, paths) {
12066
+ const keys = /* @__PURE__ */ new Map();
12067
+ await Promise.all(dirents.map(async (dirent) => {
12068
+ try {
12069
+ const stats = await dependencies.fs.lstat(paths.join(folder, dirent.name));
12070
+ keys.set(dirent.name, {
12071
+ sizeBytes: stats.isFile() ? stats.size : 0,
12072
+ modifiedMillis: stats.mtimeMs,
12073
+ createdMillis: stats.birthtimeMs
12074
+ });
12075
+ } catch {
12076
+ keys.set(dirent.name, { sizeBytes: 0, modifiedMillis: 0, createdMillis: 0 });
12077
+ }
12078
+ }));
12079
+ return keys;
12080
+ }
12081
+ function sortDirents(dirents, sortBy, descending, keys) {
12082
+ const direction = descending ? -1 : 1;
12083
+ return [...dirents].sort((left, right) => {
12084
+ const leftIsFolder = left.isDirectory();
12085
+ if (leftIsFolder !== right.isDirectory()) {
12086
+ return leftIsFolder ? -1 : 1;
12087
+ }
12088
+ let order = 0;
12089
+ if (keys && sortBy === SORT_BY_SIZE && !leftIsFolder) {
12090
+ order = keys.get(left.name).sizeBytes - keys.get(right.name).sizeBytes;
12091
+ } else if (keys && sortBy === SORT_BY_MODIFIED) {
12092
+ order = keys.get(left.name).modifiedMillis - keys.get(right.name).modifiedMillis;
12093
+ } else if (keys && sortBy === SORT_BY_CREATED) {
12094
+ order = keys.get(left.name).createdMillis - keys.get(right.name).createdMillis;
12095
+ }
12096
+ if (order === 0) {
12097
+ order = compareNames(left.name, right.name);
12098
+ }
12099
+ return order * direction;
12100
+ });
12101
+ }
12102
+ async function describeEntry(folder, dirent, dependencies, paths) {
12103
+ const fullPath = paths.join(folder, dirent.name);
12104
+ let stats;
12105
+ try {
12106
+ stats = await dependencies.fs.lstat(fullPath);
12107
+ } catch {
12108
+ return { name: dirent.name, type: "unknown" };
12109
+ }
12110
+ const type = entryTypeOf(stats);
12111
+ const entry = { name: dirent.name, type, modified_at: epochSeconds(stats.mtimeMs) };
12112
+ if (stats.birthtimeMs > 0) {
12113
+ entry.created_at = epochSeconds(stats.birthtimeMs);
12114
+ }
12115
+ if (type === "file") {
12116
+ entry.size_bytes = stats.size;
12117
+ }
12118
+ if (dirent.name.startsWith(HIDDEN_NAME_PREFIX)) {
12119
+ entry.hidden = true;
12120
+ }
12121
+ if (type === "symlink") {
12122
+ const { linkTarget, targetType } = await readLinkTarget(fullPath, dependencies.fs);
12123
+ if (linkTarget !== void 0) {
12124
+ entry.link_target = linkTarget;
12125
+ }
12126
+ if (targetType !== void 0) {
12127
+ entry.target_type = targetType;
12128
+ }
12129
+ }
12130
+ return entry;
12131
+ }
12132
+ async function listRoots(dependencies) {
12133
+ if (dependencies.platform !== "win32") {
12134
+ return [POSIX_ROOT];
12135
+ }
12136
+ const drives = [...WINDOWS_DRIVE_LETTERS].map((letter) => `${letter}:\\`);
12137
+ const answers = await Promise.all(drives.map((drive) => withTimeout(
12138
+ dependencies.fs.access(drive).then(() => true),
12139
+ ROOT_PROBE_TIMEOUT_MILLIS,
12140
+ false
12141
+ )));
12142
+ return drives.filter((_drive, index) => answers[index]);
12143
+ }
12144
+ async function listFolder(request2, maxPayloadBytes, dependencies = machineFileSystemDependencies) {
12145
+ try {
12146
+ return await listFolderOrThrow(request2, maxPayloadBytes, dependencies);
12147
+ } catch (err) {
12148
+ return folderReadFailure(err);
12149
+ }
12150
+ }
12151
+ async function listFolderOrThrow(request2, maxPayloadBytes, dependencies) {
12152
+ const paths = pathsFor(dependencies.platform);
12153
+ const firstOpen = request2.path === void 0;
12154
+ let folder;
12155
+ if (request2.path === void 0) {
12156
+ folder = paths.resolve(dependencies.fs.homedir());
12157
+ } else {
12158
+ const problem = pathProblem(request2.path, paths);
12159
+ if (problem) {
12160
+ return fileError(ERROR_INVALID_PATH, problem);
12161
+ }
12162
+ folder = paths.resolve(request2.path);
12163
+ }
12164
+ let dirents;
12165
+ try {
12166
+ dirents = await dependencies.fs.readdir(folder);
12167
+ } catch (err) {
12168
+ return folderReadFailure(err);
12169
+ }
12170
+ const visible = request2.include_hidden ? dirents : dirents.filter((dirent) => !dirent.name.startsWith(HIDDEN_NAME_PREFIX));
12171
+ const sortBy = request2.sort_by ?? SORT_BY_NAME;
12172
+ const keys = sortBy === SORT_BY_NAME ? null : await readSortKeys(folder, visible, dependencies, paths);
12173
+ const sorted = sortDirents(visible, sortBy, request2.sort_order === SORT_ORDER_DESC, keys);
12174
+ const offset = request2.offset ?? 0;
12175
+ const limit = request2.limit ?? DEFAULT_LIST_LIMIT;
12176
+ const page = sorted.slice(offset, offset + limit);
12177
+ const described = await Promise.all(page.map((dirent) => describeEntry(folder, dirent, dependencies, paths)));
12178
+ const parent = paths.dirname(folder);
12179
+ const answer = {
12180
+ path: folder,
12181
+ ...parent !== folder ? { parent } : {},
12182
+ separator: paths.sep,
12183
+ total: visible.length,
12184
+ offset,
12185
+ entries: []
12186
+ };
12187
+ if (firstOpen) {
12188
+ answer.home = folder;
12189
+ answer.roots = await listRoots(dependencies);
12190
+ }
12191
+ let payloadBytes = utf8Bytes({ ...answer, next_offset: WIDEST_NEXT_OFFSET });
12192
+ for (const entry of described) {
12193
+ const entryBytes = utf8Bytes(entry) + (answer.entries.length > 0 ? 1 : 0);
12194
+ if (payloadBytes + entryBytes > maxPayloadBytes) {
12195
+ break;
12196
+ }
12197
+ answer.entries.push(entry);
12198
+ payloadBytes += entryBytes;
12199
+ }
12200
+ if (described.length > 0 && answer.entries.length === 0) {
12201
+ return fileError(ERROR_FILE_OPERATION_FAILED, "The next entry does not fit in 1 frame.");
12202
+ }
12203
+ const nextOffset = offset + answer.entries.length;
12204
+ if (nextOffset < visible.length) {
12205
+ answer.next_offset = nextOffset;
12206
+ }
12207
+ return answer;
12208
+ }
12209
+ var ROOT_PROBE_TIMEOUT_MILLIS, WINDOWS_DRIVE_LETTERS, POSIX_ROOT, WIDEST_NEXT_OFFSET, NAME_COLLATOR, MESSAGE_LIST_FAILED;
12210
+ var init_fileList = __esm({
12211
+ "src/devices/files/fileList.ts"() {
12212
+ "use strict";
12213
+ init_cjs_shims();
12214
+ init_file_schema();
12215
+ init_fileSystem();
12216
+ ROOT_PROBE_TIMEOUT_MILLIS = 2e3;
12217
+ WINDOWS_DRIVE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
12218
+ POSIX_ROOT = "/";
12219
+ WIDEST_NEXT_OFFSET = Number.MAX_SAFE_INTEGER;
12220
+ NAME_COLLATOR = new Intl.Collator(void 0, { numeric: true, sensitivity: "base" });
12221
+ MESSAGE_LIST_FAILED = "The folder could not be read.";
12222
+ }
12223
+ });
12224
+
12225
+ // src/devices/files/fileMkdir.ts
12226
+ async function makeFolder(request2, dependencies) {
12227
+ const { maker, platform: platform3, callTimeoutMillis } = dependencies;
12228
+ const paths = pathsFor(platform3);
12229
+ const pathIssue = pathProblem(request2.path, paths);
12230
+ if (pathIssue) {
12231
+ return fileError(ERROR_INVALID_PATH, pathIssue);
12232
+ }
12233
+ const item = withTrimmedName(resolvedItem(request2.path, paths));
12234
+ if (!isRoot(item.path, paths)) {
12235
+ const nameIssue = nameProblem(item.name, platform3);
12236
+ if (nameIssue) {
12237
+ return fileError(ERROR_INVALID_PAYLOAD2, nameIssue);
12238
+ }
12239
+ const windowsIssue = platform3 === "win32" ? windowsNameProblem(item.name) : null;
12240
+ if (windowsIssue) {
12241
+ return fileError(ERROR_INVALID_NAME, windowsIssue);
12242
+ }
12243
+ }
12244
+ try {
12245
+ await callWithTimeout(maker.mkdir(item.path), callTimeoutMillis);
12246
+ } catch (err) {
12247
+ return mkdirFailure(err);
12248
+ }
12249
+ return { path: item.path };
12250
+ }
12251
+ function mkdirFailure(err) {
12252
+ if (err instanceof FileCallTimeoutError) {
12253
+ return fileError(ERROR_FILE_TIMEOUT, err.message);
12254
+ }
12255
+ const message = failureMessage(err, MESSAGE_MKDIR_FAILED);
12256
+ switch (errorCodeOf(err)) {
12257
+ case "EEXIST":
12258
+ return fileError(ERROR_FILE_EXISTS, MESSAGE_NAME_TAKEN);
12259
+ case "ENOENT":
12260
+ return fileError(ERROR_PATH_NOT_FOUND, message);
12261
+ case "ENOTDIR":
12262
+ return fileError(ERROR_NOT_A_DIRECTORY, message);
12263
+ case "EACCES":
12264
+ case "EPERM":
12265
+ case "EROFS":
12266
+ return fileError(ERROR_PERMISSION_DENIED, message);
12267
+ default:
12268
+ return fileError(ERROR_FILE_OPERATION_FAILED, message);
12269
+ }
12270
+ }
12271
+ var MESSAGE_MKDIR_FAILED;
12272
+ var init_fileMkdir = __esm({
12273
+ "src/devices/files/fileMkdir.ts"() {
12274
+ "use strict";
12275
+ init_cjs_shims();
12276
+ init_file_schema();
12277
+ init_fileSystem();
12278
+ MESSAGE_MKDIR_FAILED = "The folder could not be made.";
12279
+ }
12280
+ });
12281
+
12282
+ // src/devices/files/fileMove.ts
12283
+ async function prepareMove(request2, dependencies) {
12284
+ try {
12285
+ return await checkedMove(request2, dependencies);
12286
+ } catch (err) {
12287
+ return refusalOf(err);
12288
+ }
12289
+ }
12290
+ async function checkedMove(request2, dependencies) {
12291
+ const { copier, platform: platform3 } = dependencies;
12292
+ const paths = pathsFor(platform3);
12293
+ const { source, destination } = resolvedItems(request2, paths);
12294
+ checkTargetName(destination.name, platform3);
12295
+ const sourceStats = await sourceItemStats(source.path, copier, MESSAGE_MOVE_FAILED);
12296
+ const sourceFolderStats = await folderStats(source.parent, copier);
12297
+ const destinationStats = await folderStats(destination.parent, copier);
12298
+ const sameFolder = identityOf(sourceFolderStats) === identityOf(destinationStats);
12299
+ await refuseIntoItself(sourceStats, destination.parent, dependencies, MESSAGE_INTO_ITSELF2);
12300
+ if (sameFolder && destination.name === source.name) {
12301
+ throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, MESSAGE_ALREADY_HERE));
12302
+ }
12303
+ const protectedSet = await readProtectedFolders(dependencies);
12304
+ const sourceGuard = await removalGuard(source.parent, sourceFolderStats, protectedSet, dependencies);
12305
+ const sourceRefusal = protectedRefusal(sourceStats, sourceFolderStats.dev, sourceGuard, MESSAGE_SELECTED_MOUNT2);
12306
+ if (sourceRefusal) {
12307
+ throw new RequestRefusal({ error: sourceRefusal });
12308
+ }
12309
+ const onConflict = request2.on_conflict ?? ON_CONFLICT_FAIL;
12310
+ if (onConflict === ON_CONFLICT_FAIL || onConflict === ON_CONFLICT_REPLACE) {
12311
+ await checkTarget(onConflict, source, destination, sourceStats, sameFolder, dependencies);
12312
+ }
12313
+ const replaceGuard = onConflict === ON_CONFLICT_REPLACE ? await removalGuard(destination.parent, destinationStats, protectedSet, dependencies) : null;
12314
+ return {
12315
+ source: source.path,
12316
+ sourceStats,
12317
+ sourceName: source.name,
12318
+ destinationDirectory: destination.parent,
12319
+ targetName: destination.name,
12320
+ onConflict,
12321
+ destinationDevice: destinationStats.dev,
12322
+ sameFolder,
12323
+ acrossDisks: sourceFolderStats.dev !== destinationStats.dev,
12324
+ sourceGuard,
12325
+ replaceGuard
12326
+ };
12327
+ }
12328
+ async function checkTarget(onConflict, source, destination, sourceStats, sameFolder, dependencies) {
12329
+ const target = await lstatOrNull(destination.path, dependencies.copier);
12330
+ if (target === null || isCaseOnlyRename(sameFolder, source.name, destination.name, sourceStats, target)) {
12331
+ return;
12332
+ }
12333
+ if (onConflict === ON_CONFLICT_REPLACE) {
12334
+ if (identityOf(target) === identityOf(sourceStats)) {
12335
+ throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, MESSAGE_REPLACE_ITSELF));
12336
+ }
12337
+ await refuseReplacingAHolder(target, source.parent, dependencies);
12338
+ return;
12339
+ }
12340
+ throw new RequestRefusal(targetTakenRefusal());
12341
+ }
12342
+ function isCaseOnlyRename(sameFolder, name, targetName, source, target) {
12343
+ return sameFolder && source !== null && name !== targetName && foldedName(name) === foldedName(targetName) && identityOf(source) === identityOf(target);
12344
+ }
12345
+ function foldedName(name) {
12346
+ return name.normalize("NFC").toLowerCase();
12347
+ }
12348
+ function moveProgress(prepared) {
12349
+ const progress = {
12350
+ items_done: 0,
12351
+ items_total: 1,
12352
+ files_done: 0,
12353
+ bytes_done: 0,
12354
+ current_name: prepared.sourceName
12355
+ };
12356
+ if (!prepared.acrossDisks) {
12357
+ progress.files_total = 1;
12358
+ progress.bytes_total = 0;
12359
+ }
12360
+ return progress;
12361
+ }
12362
+ async function runMove(prepared, progress, dependencies) {
12363
+ const counted = Object.assign(progress, { bytes_done: progress.bytes_done ?? 0 });
12364
+ const item = {
12365
+ name: prepared.sourceName,
12366
+ targetName: prepared.targetName,
12367
+ source: prepared.source,
12368
+ stats: prepared.sourceStats
12369
+ };
12370
+ if (prepared.acrossDisks) {
12371
+ const refusal = await countAcross(item, prepared, counted, dependencies);
12372
+ if (refusal) {
12373
+ return refusal;
12374
+ }
12375
+ }
12376
+ const outcome = await moveItem(item, prepared, counted, dependencies);
12377
+ counted.items_done += 1;
12378
+ return outcomeAnswer(outcome);
12379
+ }
12380
+ async function countAcross(item, prepared, progress, dependencies) {
12381
+ const paths = pathsFor(dependencies.platform);
12382
+ const target = paths.join(prepared.destinationDirectory, item.targetName);
12383
+ if (prepared.onConflict === ON_CONFLICT_SKIP && await lstatOrNull(target, dependencies.copier).catch(() => null)) {
12384
+ progress.files_total = 0;
12385
+ progress.bytes_total = 0;
12386
+ return null;
12387
+ }
12388
+ const totals = await countItem(item, dependencies);
12389
+ const refusal = countRefusal(totals, item.stats);
12390
+ if (refusal) {
12391
+ return { error: refusal };
12392
+ }
12393
+ progress.files_total = totals.files;
12394
+ progress.bytes_total = totals.bytes;
12395
+ return noSpaceRefusal(totals.bytes, prepared.destinationDirectory, dependencies.copier);
12396
+ }
12397
+ async function countItem(item, dependencies) {
12398
+ const totals = newCountTotals();
12399
+ await countEntry(item.source, totals, dependencies.copier, pathsFor(dependencies.platform), item.stats.dev);
12400
+ return totals;
12401
+ }
12402
+ function countRefusal(totals, stats) {
12403
+ if (totals.mountedDisks > 0) {
12404
+ return { code: ERROR_MOUNT_POINT, message: MESSAGE_MOUNT_INSIDE2 };
12405
+ }
12406
+ if (isSpecial(stats)) {
12407
+ return { code: ERROR_SPECIAL_FILE, message: MESSAGE_SPECIAL_SELECTED2 };
12408
+ }
12409
+ return totals.specialFiles > 0 ? specialInside(totals.specialFiles) : null;
12410
+ }
12411
+ function specialInside(count) {
12412
+ const message = count === 1 ? "This folder holds 1 socket, pipe or device file, which cannot be moved to another disk." : `This folder holds ${count} sockets, pipes or device files, which cannot be moved to another disk.`;
12413
+ return { code: ERROR_SPECIAL_FILE, message };
12414
+ }
12415
+ async function moveItem(item, prepared, progress, dependencies) {
12416
+ if (prepared.acrossDisks) {
12417
+ return moveAcross(item, prepared, progress, dependencies);
12418
+ }
12419
+ try {
12420
+ const placement = await placeAt(item.source, item, prepared, dependencies, dependencies.hiddenNameSuffix());
12421
+ if (!placement.placed) {
12422
+ return placement.outcome;
12423
+ }
12424
+ progress.files_done += 1;
12425
+ return placement.oldStays;
12426
+ } catch (err) {
12427
+ if (errorCodeOf(err) !== "EXDEV") {
12428
+ return moveFailure(err);
12429
+ }
12430
+ }
12431
+ const totals = await countItem(item, dependencies);
12432
+ const refusal = countRefusal(totals, item.stats);
12433
+ if (refusal) {
12434
+ return refusal;
12435
+ }
12436
+ progress.files_total = (progress.files_total ?? 0) + totals.files - 1;
12437
+ progress.bytes_total = (progress.bytes_total ?? 0) + totals.bytes;
12438
+ return moveAcross(item, prepared, progress, dependencies);
12439
+ }
12440
+ async function moveAcross(item, prepared, progress, dependencies) {
12441
+ const { copier, platform: platform3 } = dependencies;
12442
+ const paths = pathsFor(platform3);
12443
+ const { protectedSet } = prepared.sourceGuard;
12444
+ try {
12445
+ const settledFirst = await targetBeforeCopy(item, prepared, dependencies);
12446
+ if (settledFirst) {
12447
+ return settledFirst;
12448
+ }
12449
+ } catch (err) {
12450
+ return moveFailure(err);
12451
+ }
12452
+ const suffix = dependencies.hiddenNameSuffix();
12453
+ const hiddenCopy = paths.join(prepared.destinationDirectory, hiddenName(item.targetName, HIDDEN_MOVE_MARK, suffix));
12454
+ const walk = { copier, paths, platform: platform3, progress, specialFilesLeftOut: 0 };
12455
+ let placement;
12456
+ try {
12457
+ await copyEntry(item.source, item.stats, hiddenCopy, walk, true);
12458
+ if (walk.specialFilesLeftOut > 0) {
12459
+ await removeQuietly2(hiddenCopy, protectedSet, dependencies);
12460
+ return specialInside(walk.specialFilesLeftOut);
12461
+ }
12462
+ placement = await placeAt(hiddenCopy, item, prepared, dependencies, suffix);
12463
+ } catch (err) {
12464
+ if (!(err instanceof TakenError)) {
12465
+ await removeQuietly2(hiddenCopy, protectedSet, dependencies);
12466
+ }
12467
+ return moveFailure(err);
12468
+ }
12469
+ if (!placement.placed) {
12470
+ await removeQuietly2(hiddenCopy, protectedSet, dependencies);
12471
+ return placement.outcome;
12472
+ }
12473
+ return await removeOriginal(item, protectedSet, dependencies) ?? placement.oldStays;
12474
+ }
12475
+ async function targetBeforeCopy(item, prepared, dependencies) {
12476
+ if (prepared.onConflict === ON_CONFLICT_KEEP_BOTH) {
12477
+ return null;
12478
+ }
12479
+ const paths = pathsFor(dependencies.platform);
12480
+ const existing = await lstatOrNull(
12481
+ paths.join(prepared.destinationDirectory, item.targetName),
12482
+ dependencies.copier
12483
+ );
12484
+ if (existing === null) {
12485
+ return null;
12486
+ }
12487
+ switch (prepared.onConflict) {
12488
+ case ON_CONFLICT_SKIP:
12489
+ return SKIPPED;
12490
+ case ON_CONFLICT_REPLACE:
12491
+ return replaceRefusal(existing, item.stats, prepared.destinationDevice, prepared.replaceGuard);
12492
+ default:
12493
+ return { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN };
12494
+ }
12495
+ }
12496
+ async function placeAt(incoming, item, prepared, dependencies, suffix) {
12497
+ const { copier } = dependencies;
12498
+ const paths = pathsFor(dependencies.platform);
12499
+ const target = paths.join(prepared.destinationDirectory, item.targetName);
12500
+ const existing = await lstatOrNull(target, copier);
12501
+ if (existing === null || isCaseOnlyRename(prepared.sameFolder, item.name, item.targetName, item.stats, existing)) {
12502
+ await copier.rename(incoming, target);
12503
+ return PLACED;
12504
+ }
12505
+ switch (prepared.onConflict) {
12506
+ case ON_CONFLICT_SKIP:
12507
+ return { placed: false, outcome: SKIPPED };
12508
+ case ON_CONFLICT_KEEP_BOTH:
12509
+ return placeUnderFreeName(incoming, item, prepared, dependencies);
12510
+ case ON_CONFLICT_REPLACE:
12511
+ return replaceAt(incoming, existing, item, prepared, dependencies, suffix);
12512
+ default:
12513
+ return { placed: false, outcome: { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN } };
12514
+ }
12515
+ }
12516
+ async function placeUnderFreeName(incoming, item, prepared, dependencies) {
12517
+ const paths = pathsFor(dependencies.platform);
12518
+ for (let number = 1; number <= MAX_KEEP_BOTH_NUMBER; number++) {
12519
+ const candidate = paths.join(
12520
+ prepared.destinationDirectory,
12521
+ keepBothName(item.targetName, item.stats.isDirectory(), number)
12522
+ );
12523
+ if (await lstatOrNull(candidate, dependencies.copier) === null) {
12524
+ await dependencies.copier.rename(incoming, candidate);
12525
+ return PLACED;
12526
+ }
12527
+ }
12528
+ return { placed: false, outcome: { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN } };
12529
+ }
12530
+ async function replaceAt(incoming, existing, item, prepared, dependencies, suffix) {
12531
+ const guard = prepared.replaceGuard;
12532
+ const refusal = replaceRefusal(existing, item.stats, prepared.destinationDevice, guard);
12533
+ if (refusal) {
12534
+ return { placed: false, outcome: refusal };
12535
+ }
12536
+ const paths = pathsFor(dependencies.platform);
12537
+ const oldName = await swapIn(
12538
+ incoming,
12539
+ prepared.destinationDirectory,
12540
+ item.targetName,
12541
+ existing,
12542
+ item.stats.isDirectory(),
12543
+ suffix,
12544
+ dependencies.copier,
12545
+ paths
12546
+ );
12547
+ if (oldName === null) {
12548
+ return PLACED;
12549
+ }
12550
+ const oldStays = await removeOld(
12551
+ paths.join(prepared.destinationDirectory, oldName),
12552
+ oldName,
12553
+ existing,
12554
+ guard.protectedSet,
12555
+ dependencies,
12556
+ MESSAGE_MOVED_IN_PLACE
12557
+ );
12558
+ return { placed: true, oldStays };
12559
+ }
12560
+ async function removeOriginal(item, protectedSet, dependencies) {
12561
+ try {
12562
+ if (await removeTree(item.source, item.stats, protectedSet, deleteDependencies(dependencies))) {
12563
+ return null;
12564
+ }
12565
+ return { code: ERROR_MOUNT_POINT, message: `${MESSAGE_ORIGINAL_STAYS} ${REASON_MOUNT_INSIDE}` };
12566
+ } catch (err) {
12567
+ const failure2 = deleteFailure(err);
12568
+ const message = sanitizeErrorMessage(`${MESSAGE_ORIGINAL_STAYS} ${failure2.message}`) ?? failure2.message;
12569
+ return { code: failure2.code, message };
12570
+ }
12571
+ }
12572
+ function moveFailure(err) {
12573
+ switch (errorCodeOf(err)) {
12574
+ case "EBUSY":
12575
+ return { code: ERROR_PERMISSION_DENIED, message: failureMessage(err, MESSAGE_MOVE_FAILED) };
12576
+ case "ENOTEMPTY":
12577
+ case "EISDIR":
12578
+ return { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN };
12579
+ default:
12580
+ return copyFailure(err, MESSAGE_MOVE_FAILED);
12581
+ }
12582
+ }
12583
+ var HIDDEN_MOVE_MARK, MESSAGE_INTO_ITSELF2, MESSAGE_ALREADY_HERE, MESSAGE_SELECTED_MOUNT2, MESSAGE_MOUNT_INSIDE2, MESSAGE_SPECIAL_SELECTED2, MESSAGE_MOVED_IN_PLACE, MESSAGE_ORIGINAL_STAYS, MESSAGE_MOVE_FAILED, PLACED;
12584
+ var init_fileMove = __esm({
12585
+ "src/devices/files/fileMove.ts"() {
12586
+ "use strict";
12587
+ init_cjs_shims();
12588
+ init_tunnelList();
12589
+ init_file_schema();
12590
+ init_fileCopy();
12591
+ init_fileDelete();
12592
+ init_fileProtectedPaths();
12593
+ init_fileSystem();
12594
+ HIDDEN_MOVE_MARK = "move";
12595
+ MESSAGE_INTO_ITSELF2 = "A folder cannot be moved into itself.";
12596
+ MESSAGE_ALREADY_HERE = "The item is already in this folder.";
12597
+ MESSAGE_SELECTED_MOUNT2 = "This folder is a mounted disk. Open it to move what is inside.";
12598
+ MESSAGE_MOUNT_INSIDE2 = "Another disk is mounted inside. Pinggy does not move it to another disk.";
12599
+ MESSAGE_SPECIAL_SELECTED2 = "This is a socket, pipe or device file. Pinggy cannot move it to another disk.";
12600
+ MESSAGE_MOVED_IN_PLACE = "The item is in place. The old one stays as";
12601
+ MESSAGE_ORIGINAL_STAYS = "The item is in its new place. The original could not be fully removed:";
12602
+ MESSAGE_MOVE_FAILED = "The item could not be moved.";
12603
+ PLACED = { placed: true, oldStays: null };
12604
+ }
12605
+ });
12606
+
12607
+ // src/devices/files/fileStat.ts
12608
+ function lstatFailure(err) {
12609
+ const message = failureMessage(err, MESSAGE_STAT_FAILED);
12610
+ if (err instanceof FileCallTimeoutError) {
12611
+ return fileError(ERROR_FILE_TIMEOUT, message);
12612
+ }
12613
+ switch (errorCodeOf(err)) {
12614
+ case "ENOENT":
12615
+ case "ENOTDIR":
12616
+ return fileError(ERROR_PATH_NOT_FOUND, message);
12617
+ case "EACCES":
12618
+ case "EPERM":
12619
+ return fileError(ERROR_PERMISSION_DENIED, message);
12620
+ default:
12621
+ return fileError(ERROR_FILE_OPERATION_FAILED, message);
12622
+ }
12623
+ }
12624
+ function modeDigits(mode) {
12625
+ return (mode & PERMISSION_BITS_MASK).toString(OCTAL_RADIX).padStart(MODE_DIGITS, "0");
12626
+ }
12627
+ async function hasAccess(target, mode, dependencies) {
12628
+ try {
12629
+ await dependencies.fs.access(target, mode);
12630
+ return true;
12631
+ } catch {
12632
+ return false;
12633
+ }
12634
+ }
12635
+ async function countEntries(folder, includeHidden, dependencies) {
12636
+ try {
12637
+ const dirents = await dependencies.fs.readdir(folder);
12638
+ return includeHidden ? dirents.length : dirents.filter((dirent) => !dirent.name.startsWith(HIDDEN_NAME_PREFIX)).length;
12639
+ } catch {
12640
+ return void 0;
12641
+ }
12642
+ }
12643
+ async function statPath(request2, maxPayloadBytes, dependencies = machineFileSystemDependencies) {
12644
+ try {
12645
+ return await statPathOrThrow(request2, maxPayloadBytes, dependencies);
12646
+ } catch (err) {
12647
+ return fileError(ERROR_FILE_OPERATION_FAILED, failureMessage(err, MESSAGE_STAT_FAILED));
12648
+ }
12649
+ }
12650
+ async function statPathOrThrow(request2, maxPayloadBytes, dependencies) {
12651
+ const paths = pathsFor(dependencies.platform);
12652
+ const problem = pathProblem(request2.path, paths);
12653
+ if (problem) {
12654
+ return fileError(ERROR_INVALID_PATH, problem);
12655
+ }
12656
+ const target = paths.resolve(request2.path);
12657
+ let stats;
12658
+ try {
12659
+ stats = await dependencies.fs.lstat(target);
12660
+ } catch (err) {
12661
+ return lstatFailure(err);
12662
+ }
12663
+ const type = entryTypeOf(stats);
12664
+ const name = paths.basename(target) || target;
12665
+ const onWindows = dependencies.platform === "win32";
12666
+ const answer = {
12667
+ path: target,
12668
+ name,
12669
+ type,
12670
+ ...type === "file" ? { size_bytes: stats.size } : {},
12671
+ modified_at: epochSeconds(stats.mtimeMs),
12672
+ accessed_at: epochSeconds(stats.atimeMs),
12673
+ // 0 is a filesystem with no birth time. Some report the change time instead, which cannot be told apart.
12674
+ ...stats.birthtimeMs > 0 ? { created_at: epochSeconds(stats.birthtimeMs) } : {},
12675
+ ...name.startsWith(HIDDEN_NAME_PREFIX) ? { hidden: true } : {}
12676
+ };
12677
+ if (!onWindows) {
12678
+ answer.mode = modeDigits(stats.mode);
12679
+ answer.uid = stats.uid;
12680
+ answer.gid = stats.gid;
12681
+ }
12682
+ if (!onWindows && type !== "symlink") {
12683
+ const [readable, writable, executable] = await Promise.all([
12684
+ hasAccess(target, import_fs11.default.constants.R_OK, dependencies),
12685
+ hasAccess(target, import_fs11.default.constants.W_OK, dependencies),
12686
+ hasAccess(target, import_fs11.default.constants.X_OK, dependencies)
12687
+ ]);
12688
+ Object.assign(answer, { readable, writable, executable });
12689
+ }
12690
+ if (type === "directory") {
12691
+ const entryCount = await countEntries(target, request2.include_hidden === true, dependencies);
12692
+ if (entryCount !== void 0) {
12693
+ answer.entry_count = entryCount;
12694
+ }
12695
+ }
12696
+ if (type === "symlink") {
12697
+ const { linkTarget, targetType, targetStats } = await readLinkTarget(target, dependencies.fs);
12698
+ if (linkTarget !== void 0) {
12699
+ answer.link_target = linkTarget;
12700
+ }
12701
+ if (targetType !== void 0) {
12702
+ answer.target_type = targetType;
12703
+ }
12704
+ if (targetStats?.isFile()) {
12705
+ answer.target_size_bytes = targetStats.size;
12706
+ }
12707
+ }
12708
+ if (utf8Bytes(answer) > maxPayloadBytes) {
12709
+ delete answer.link_target;
12710
+ }
12711
+ if (utf8Bytes(answer) > maxPayloadBytes) {
12712
+ return fileError(ERROR_FILE_OPERATION_FAILED, MESSAGE_TOO_LARGE);
12713
+ }
12714
+ return answer;
12715
+ }
12716
+ var import_fs11, PERMISSION_BITS_MASK, OCTAL_RADIX, MODE_DIGITS, MESSAGE_STAT_FAILED, MESSAGE_TOO_LARGE;
12717
+ var init_fileStat = __esm({
12718
+ "src/devices/files/fileStat.ts"() {
12719
+ "use strict";
12720
+ init_cjs_shims();
12721
+ import_fs11 = __toESM(require("fs"), 1);
12722
+ init_file_schema();
12723
+ init_fileSystem();
12724
+ PERMISSION_BITS_MASK = 4095;
12725
+ OCTAL_RADIX = 8;
12726
+ MODE_DIGITS = 4;
12727
+ MESSAGE_STAT_FAILED = "The path could not be read.";
12728
+ MESSAGE_TOO_LARGE = "The details are too large to send.";
12729
+ }
12730
+ });
12731
+
12732
+ // src/devices/files/fileHandler.ts
12733
+ function afterThisTurn(work) {
12734
+ return Promise.resolve().then(work);
12735
+ }
12736
+ function sameProgress(left, right) {
12737
+ return left.items_done === right.items_done && left.files_done === right.files_done && left.bytes_done === right.bytes_done && left.files_total === right.files_total && left.bytes_total === right.bytes_total && left.current_name === right.current_name;
12738
+ }
12739
+ function invalidPayload() {
12740
+ return fileError(ERROR_INVALID_PAYLOAD2, "The file request could not be read.");
12741
+ }
12742
+ function busy(limit, waiting) {
12743
+ if (limit <= 0) {
12744
+ return fileError(ERROR_FILE_BUSY, "The dashboard allows no file operations on this device.");
12745
+ }
12746
+ const noun = limit === 1 ? "file operation" : "file operations";
12747
+ const running = `The device is already running ${limit} ${noun}`;
12748
+ if (waiting <= 0) {
12749
+ return fileError(ERROR_FILE_BUSY, `${running}.`);
12750
+ }
12751
+ const verb = waiting === 1 ? "is" : "are";
12752
+ return fileError(ERROR_FILE_BUSY, `${running}, and ${waiting} more ${verb} waiting.`);
12753
+ }
12754
+ var DEFAULT_READ_TIMEOUT_MILLIS, DEFAULT_DELETE_CALL_TIMEOUT_MILLIS, DEFAULT_MKDIR_TIMEOUT_MILLIS, DEFAULT_COPY_CALL_TIMEOUT_MILLIS, DEFAULT_FILE_CALL_PLACES, MILLIS_PER_SECOND2, PROGRESS_TICK_MILLIS, PROGRESS_KEEPALIVE_TICKS, QUEUED_KEEPALIVE_MILLIS, NULL_PAYLOAD_BYTES, OUTCOME_ANSWERED, FILE_ACCESS_OFF_MESSAGE, HANDLED_OPS, FileHandler;
12755
+ var init_fileHandler = __esm({
12756
+ "src/devices/files/fileHandler.ts"() {
12757
+ "use strict";
12758
+ init_cjs_shims();
12759
+ init_logger();
12760
+ init_envelope();
12761
+ init_file_schema();
12762
+ init_fileCallGate();
12763
+ init_fileCopy();
12764
+ init_fileDelete();
12765
+ init_fileList();
12766
+ init_fileMkdir();
12767
+ init_fileMove();
12768
+ init_fileProtectedPaths();
12769
+ init_fileStat();
12770
+ init_fileSystem();
12771
+ DEFAULT_READ_TIMEOUT_MILLIS = 2e4;
12772
+ DEFAULT_DELETE_CALL_TIMEOUT_MILLIS = 2e4;
12773
+ DEFAULT_MKDIR_TIMEOUT_MILLIS = 2e4;
12774
+ DEFAULT_COPY_CALL_TIMEOUT_MILLIS = 2e4;
12775
+ DEFAULT_FILE_CALL_PLACES = 2;
12776
+ MILLIS_PER_SECOND2 = 1e3;
12777
+ PROGRESS_TICK_MILLIS = 1e3;
12778
+ PROGRESS_KEEPALIVE_TICKS = 5;
12779
+ QUEUED_KEEPALIVE_MILLIS = PROGRESS_TICK_MILLIS * PROGRESS_KEEPALIVE_TICKS;
12780
+ NULL_PAYLOAD_BYTES = Buffer.byteLength("null", "utf8");
12781
+ OUTCOME_ANSWERED = "answered";
12782
+ FILE_ACCESS_OFF_MESSAGE = "File access is off on this device. To allow it, run on the device: pinggy device connect --files on";
12783
+ HANDLED_OPS = /* @__PURE__ */ new Set([OP_LIST, OP_STAT, OP_DELETE, OP_MKDIR, OP_COPY, OP_MOVE]);
12784
+ FileHandler = class {
12785
+ constructor(dependencies) {
12786
+ this.dependencies = dependencies;
12787
+ this.enabled = false;
12788
+ this.maxFrameBytes = 0;
12789
+ this.maxConcurrentOperations = 0;
12790
+ this.maxQueuedOperations = 0;
12791
+ this.runningOperations = 0;
12792
+ /** Oldest first. The first is the next to start. */
12793
+ this.waitingOperations = [];
12794
+ this.queuedKeepalive = null;
12795
+ const gate = new FileCallGate(dependencies.fileCallPlaces ?? DEFAULT_FILE_CALL_PLACES);
12796
+ const fileSystem = dependencies.fileSystem ?? machineFileSystemDependencies;
12797
+ this.gatedFileSystem = {
12798
+ platform: fileSystem.platform,
12799
+ fs: gatedReader(fileSystem.fs, gate, this.readTimeoutMillis())
12800
+ };
12801
+ this.gatedRemover = gatedRemover(
12802
+ dependencies.remover ?? machineFileSystemRemover,
12803
+ gate,
12804
+ this.deleteCallTimeoutMillis()
12805
+ );
12806
+ this.gatedMaker = gatedMaker(dependencies.maker ?? machineFileSystemMaker, gate, this.mkdirTimeoutMillis());
12807
+ this.gatedCopier = gatedCopier(
12808
+ dependencies.copier ?? machineFileSystemCopier,
12809
+ gate,
12810
+ this.copyCallTimeoutMillis()
12811
+ );
12812
+ }
12813
+ /**
12814
+ * From each `welcome`. `max_frame_bytes` is the dashboard's cap on 1 frame from this agent. Without
12815
+ * `file_max_concurrent_operations`, no delete, copy or move runs, and without `file_max_queued_operations`, none
12816
+ * waits. Requests already waiting keep their place: more slots start them, and no slot at all refuses them with
12817
+ * `file_busy`, since none would ever start.
12818
+ */
12819
+ configure(fileManagerEnabled, maxFrameBytes, maxConcurrentOperations, maxQueuedOperations) {
12820
+ this.enabled = fileManagerEnabled === true;
12821
+ this.maxFrameBytes = maxFrameBytes;
12822
+ this.maxConcurrentOperations = maxConcurrentOperations ?? 0;
12823
+ this.maxQueuedOperations = maxQueuedOperations ?? 0;
12824
+ this.admitWaiting();
12825
+ }
12826
+ async handle(envelope) {
12827
+ if (envelope.kind !== "req") {
12828
+ return;
12829
+ }
12830
+ if (!HANDLED_OPS.has(envelope.op)) {
12831
+ this.answer(envelope, fileError(ERROR_UNSUPPORTED_OP2, `Unsupported operation: file/${envelope.op}`));
12832
+ return;
12833
+ }
12834
+ if (!this.enabled) {
12835
+ this.answer(envelope, fileError(ERROR_FILE_MANAGER_DISABLED, "The file manager is disabled."));
12836
+ return;
12837
+ }
12838
+ if (this.dependencies.fileAccessAllowed?.() === false) {
12839
+ this.answer(envelope, fileError(ERROR_FILE_ACCESS_OFF, FILE_ACCESS_OFF_MESSAGE));
12840
+ return;
12841
+ }
12842
+ this.answer(envelope, await this.run(envelope));
12843
+ }
12844
+ run(envelope) {
12845
+ switch (envelope.op) {
12846
+ case OP_LIST:
12847
+ return this.list(envelope);
12848
+ case OP_STAT:
12849
+ return this.stat(envelope);
12850
+ case OP_MKDIR:
12851
+ return this.mkdir(envelope);
12852
+ case OP_COPY:
12853
+ return this.copy(envelope);
12854
+ case OP_MOVE:
12855
+ return this.move(envelope);
12856
+ default:
12857
+ return this.delete(envelope);
12858
+ }
12859
+ }
12860
+ list(envelope) {
12861
+ const parsed = FileListRequestSchema.safeParse(envelope.payload);
12862
+ if (!parsed.success) {
12863
+ return Promise.resolve(invalidPayload());
12864
+ }
12865
+ const listing = afterThisTurn(() => listFolder(parsed.data, this.payloadBudget(envelope), this.fileSystem()));
12866
+ return withTimeout(listing, this.readTimeoutMillis(), this.timedOut("The folder"));
12867
+ }
12868
+ stat(envelope) {
12869
+ const parsed = FileStatRequestSchema.safeParse(envelope.payload);
12870
+ if (!parsed.success) {
12871
+ return Promise.resolve(invalidPayload());
12872
+ }
12873
+ const details = afterThisTurn(() => statPath(parsed.data, this.payloadBudget(envelope), this.fileSystem()));
12874
+ return withTimeout(details, this.readTimeoutMillis(), this.timedOut("The path"));
12875
+ }
12876
+ mkdir(envelope) {
12877
+ const parsed = FileMkdirRequestSchema.safeParse(envelope.payload);
12878
+ if (!parsed.success) {
12879
+ return Promise.resolve(invalidPayload());
12880
+ }
12881
+ return makeFolder(parsed.data, {
12882
+ maker: this.gatedMaker,
12883
+ platform: this.fileSystem().platform,
12884
+ callTimeoutMillis: this.mkdirTimeoutMillis()
12885
+ });
12886
+ }
12887
+ delete(envelope) {
12888
+ const parsed = FileDeleteRequestSchema.safeParse(envelope.payload);
12889
+ if (!parsed.success) {
12890
+ return Promise.resolve(invalidPayload());
12891
+ }
12892
+ return this.inSlot(envelope, "delete", () => this.deleteInSlot(envelope, parsed.data));
12893
+ }
12894
+ copy(envelope) {
12895
+ const parsed = FileCopyRequestSchema.safeParse(envelope.payload);
12896
+ if (!parsed.success) {
12897
+ return Promise.resolve(invalidPayload());
12898
+ }
12899
+ return this.inSlot(envelope, "copy", () => this.copyInSlot(envelope, parsed.data));
12900
+ }
12901
+ move(envelope) {
12902
+ const parsed = FileCopyRequestSchema.safeParse(envelope.payload);
12903
+ if (!parsed.success) {
12904
+ return Promise.resolve(invalidPayload());
12905
+ }
12906
+ return this.inSlot(envelope, "move", () => this.moveInSlot(envelope, parsed.data));
12907
+ }
12908
+ /** Holds 1 slot from {@link takeSlot} to the answer. */
12909
+ async inSlot(envelope, operation, work) {
12910
+ const refusal = await this.takeSlot(envelope);
12911
+ if (refusal) {
12912
+ return refusal;
12913
+ }
12914
+ try {
12915
+ return await work();
12916
+ } catch (err) {
12917
+ logger.warn(`Device agent file ${operation} stopped`, { id: envelope.id, code: errorCodeOf(err) });
12918
+ return fileError(ERROR_FILE_OPERATION_FAILED, `The ${operation} stopped unexpectedly.`);
12919
+ } finally {
12920
+ this.runningOperations -= 1;
12921
+ this.admitWaiting();
12922
+ }
12923
+ }
12924
+ /**
12925
+ * Null once this request holds a slot: at once when 1 is free and nobody waits, else when its turn in line
12926
+ * comes. `file_busy` at once when the line is full, or no slot is allowed.
12927
+ */
12928
+ takeSlot(envelope) {
12929
+ if (this.runningOperations < this.maxConcurrentOperations && this.waitingOperations.length === 0) {
12930
+ this.runningOperations += 1;
12931
+ return Promise.resolve(null);
12932
+ }
12933
+ if (this.maxConcurrentOperations <= 0 || this.waitingOperations.length >= this.maxQueuedOperations) {
12934
+ return Promise.resolve(busy(this.maxConcurrentOperations, this.waitingOperations.length));
12935
+ }
12936
+ return new Promise((admit) => {
12937
+ this.waitingOperations.push({ envelope, admit });
12938
+ this.sendQueuedPosition(envelope, this.waitingOperations.length);
12939
+ this.startQueuedKeepalive();
12940
+ });
12941
+ }
12942
+ /**
12943
+ * Hands each free slot to the oldest request waiting, and counts it as running at once, so a request that
12944
+ * arrives before the waiting one resumes cannot take its slot. Those still waiting hear their new place.
12945
+ */
12946
+ admitWaiting() {
12947
+ if (this.waitingOperations.length === 0) {
12948
+ return;
12949
+ }
12950
+ if (this.maxConcurrentOperations <= 0) {
12951
+ const refusal = busy(this.maxConcurrentOperations, 0);
12952
+ this.waitingOperations.splice(0).forEach((waiting) => waiting.admit(refusal));
12953
+ this.stopQueuedKeepalive();
12954
+ return;
12955
+ }
12956
+ let admitted = 0;
12957
+ while (this.waitingOperations.length > 0 && this.runningOperations < this.maxConcurrentOperations) {
12958
+ this.runningOperations += 1;
12959
+ this.waitingOperations.shift().admit(null);
12960
+ admitted += 1;
12961
+ }
12962
+ if (this.waitingOperations.length === 0) {
12963
+ this.stopQueuedKeepalive();
12964
+ } else if (admitted > 0) {
12965
+ this.sendQueuedPositions();
12966
+ }
12967
+ }
12968
+ sendQueuedPosition(envelope, position) {
12969
+ const payload = { queued_position: position };
12970
+ this.dependencies.send(event(CHANNEL_FILE, OP_PROGRESS, payload, envelope.id));
12971
+ }
12972
+ sendQueuedPositions() {
12973
+ this.waitingOperations.forEach((waiting, index) => this.sendQueuedPosition(waiting.envelope, index + 1));
12974
+ }
12975
+ /** 1 timer for the whole line, running only while someone waits. */
12976
+ startQueuedKeepalive() {
12977
+ if (this.queuedKeepalive === null) {
12978
+ this.queuedKeepalive = setInterval(() => this.sendQueuedPositions(), QUEUED_KEEPALIVE_MILLIS);
12979
+ }
12980
+ }
12981
+ stopQueuedKeepalive() {
12982
+ if (this.queuedKeepalive !== null) {
12983
+ clearInterval(this.queuedKeepalive);
12984
+ this.queuedKeepalive = null;
12985
+ }
12986
+ }
12987
+ /** A refusal from the checks sends no counted `progress`: nothing was deleted, and the answer comes at once. */
12988
+ async deleteInSlot(envelope, request2) {
12989
+ const dependencies = this.deleteDependencies();
12990
+ const prepared = await prepareDelete(request2, dependencies);
12991
+ if ("error" in prepared) {
12992
+ return prepared;
12993
+ }
12994
+ const progress = { items_done: 0, items_total: 1, files_done: 0, current_name: prepared.name };
12995
+ const stopProgress = this.startProgress(envelope, progress);
12996
+ try {
12997
+ return await runDelete(prepared, progress, dependencies);
12998
+ } finally {
12999
+ stopProgress();
13000
+ }
13001
+ }
13002
+ /**
13003
+ * A refusal from the checks sends no counted `progress`: nothing was copied, and the answer comes at once.
13004
+ * `progress` starts before the count, so a large tree keeps the browser's timer alive while it is counted, and a
13005
+ * `no_space` answer follows it.
13006
+ */
13007
+ async copyInSlot(envelope, request2) {
13008
+ const dependencies = this.copyDependencies();
13009
+ const prepared = await prepareCopy(request2, dependencies);
13010
+ if ("error" in prepared) {
13011
+ return prepared;
13012
+ }
13013
+ const progress = {
13014
+ items_done: 0,
13015
+ items_total: 1,
13016
+ files_done: 0,
13017
+ bytes_done: 0,
13018
+ current_name: prepared.sourceName
13019
+ };
13020
+ const stopProgress = this.startProgress(envelope, progress);
13021
+ try {
13022
+ return await runCopy(prepared, progress, dependencies);
13023
+ } finally {
13024
+ stopProgress();
13025
+ }
13026
+ }
13027
+ /**
13028
+ * As for a copy. On 1 disk the first `progress` already holds the totals, since there is nothing to count. To
13029
+ * another disk it starts before the count, as a copy's does.
13030
+ */
13031
+ async moveInSlot(envelope, request2) {
13032
+ const dependencies = this.copyDependencies();
13033
+ const prepared = await prepareMove(request2, dependencies);
13034
+ if ("error" in prepared) {
13035
+ return prepared;
13036
+ }
13037
+ const progress = moveProgress(prepared);
13038
+ const stopProgress = this.startProgress(envelope, progress);
13039
+ try {
13040
+ return await runMove(prepared, progress, dependencies);
13041
+ } finally {
13042
+ stopProgress();
13043
+ }
13044
+ }
13045
+ /** Sends 1 `progress` now, then from a timer. Returns the stop, which the answer waits for. */
13046
+ startProgress(envelope, progress) {
13047
+ let lastSent = this.sendProgress(envelope, progress);
13048
+ let ticksSinceSent = 0;
13049
+ const timer = setInterval(() => {
13050
+ ticksSinceSent += 1;
13051
+ if (sameProgress(progress, lastSent) && ticksSinceSent < PROGRESS_KEEPALIVE_TICKS) {
13052
+ return;
13053
+ }
13054
+ lastSent = this.sendProgress(envelope, progress);
13055
+ ticksSinceSent = 0;
13056
+ }, PROGRESS_TICK_MILLIS);
13057
+ return () => clearInterval(timer);
13058
+ }
13059
+ /** Sends a snapshot, since the op keeps counting into `progress`. Returns the snapshot sent. */
13060
+ sendProgress(envelope, progress) {
13061
+ const snapshot = { ...progress };
13062
+ this.dependencies.send(event(CHANNEL_FILE, OP_PROGRESS, snapshot, envelope.id));
13063
+ return snapshot;
13064
+ }
13065
+ deleteDependencies() {
13066
+ return {
13067
+ remover: this.gatedRemover,
13068
+ platform: this.fileSystem().platform,
13069
+ protectedSources: this.dependencies.protectedSources ?? machineProtectedSources(),
13070
+ callTimeoutMillis: this.deleteCallTimeoutMillis()
13071
+ };
13072
+ }
13073
+ copyDependencies() {
13074
+ return {
13075
+ ...this.deleteDependencies(),
13076
+ copier: this.gatedCopier,
13077
+ hiddenNameSuffix: this.dependencies.hiddenNameSuffix ?? randomHiddenNameSuffix
13078
+ };
13079
+ }
13080
+ fileSystem() {
13081
+ return this.gatedFileSystem;
13082
+ }
13083
+ deleteCallTimeoutMillis() {
13084
+ return this.dependencies.deleteCallTimeoutMillis ?? DEFAULT_DELETE_CALL_TIMEOUT_MILLIS;
13085
+ }
13086
+ copyCallTimeoutMillis() {
13087
+ return this.dependencies.copyCallTimeoutMillis ?? DEFAULT_COPY_CALL_TIMEOUT_MILLIS;
13088
+ }
13089
+ mkdirTimeoutMillis() {
13090
+ return this.dependencies.mkdirTimeoutMillis ?? DEFAULT_MKDIR_TIMEOUT_MILLIS;
13091
+ }
13092
+ readTimeoutMillis() {
13093
+ return this.dependencies.readTimeoutMillis ?? DEFAULT_READ_TIMEOUT_MILLIS;
13094
+ }
13095
+ /** "The folder took longer than 20 s to read." */
13096
+ timedOut(subject) {
13097
+ const seconds = Math.round(this.readTimeoutMillis() / MILLIS_PER_SECOND2);
13098
+ return fileError(ERROR_FILE_TIMEOUT, `${subject} took longer than ${seconds} s to read.`);
13099
+ }
13100
+ /** What is left of `max_frame_bytes` once the answer's envelope is counted. */
13101
+ payloadBudget(envelope) {
13102
+ const envelopeBytes = Buffer.byteLength(JSON.stringify(response(envelope, envelope.op, null)), "utf8");
13103
+ return this.maxFrameBytes - (envelopeBytes - NULL_PAYLOAD_BYTES);
13104
+ }
13105
+ answer(envelope, result) {
13106
+ logger.debug("Device agent file request", {
13107
+ op: envelope.op,
13108
+ id: envelope.id,
13109
+ outcome: "error" in result ? result.error.code : OUTCOME_ANSWERED
13110
+ });
13111
+ this.dependencies.send(response(envelope, envelope.op, result));
13112
+ }
13113
+ };
13114
+ }
13115
+ });
13116
+
13117
+ // src/devices/login/prompts.ts
13118
+ function createTerminalPrompter(input, output) {
13119
+ return {
13120
+ async ask(question, signal) {
13121
+ const readline = (0, import_promises.createInterface)({ input, output, terminal: true });
13122
+ try {
13123
+ return await readline.question(marked(question), signal ? { signal } : {});
13124
+ } finally {
13125
+ readline.close();
13126
+ }
13127
+ },
13128
+ async askHidden(question, signal) {
13129
+ output.write(marked(question));
13130
+ const readline = (0, import_promises.createInterface)({ input, output: discardingOutput(), terminal: true });
13131
+ try {
13132
+ const answer = await readline.question("", signal ? { signal } : {});
13133
+ output.write("\n");
13134
+ return answer;
13135
+ } finally {
13136
+ readline.close();
13137
+ }
13138
+ }
13139
+ };
13140
+ }
13141
+ function isInteractiveTerminal() {
13142
+ return process.stdin.isTTY === true;
13143
+ }
13144
+ function isCtrlCAtPrompt(err) {
13145
+ return err instanceof Error && err.name === ABORT_ERROR_NAME;
13146
+ }
13147
+ function marked(question) {
13148
+ return `${QUESTION_MARKER} ${question}`;
13149
+ }
13150
+ function discardingOutput() {
13151
+ return new import_stream.Writable({
13152
+ write(_chunk, _encoding, callback) {
13153
+ callback();
13154
+ }
13155
+ });
13156
+ }
13157
+ var import_picocolors7, import_promises, import_stream, QUESTION_MARKER, terminalPrompter, ABORT_ERROR_NAME;
13158
+ var init_prompts = __esm({
13159
+ "src/devices/login/prompts.ts"() {
13160
+ "use strict";
13161
+ init_cjs_shims();
13162
+ import_picocolors7 = __toESM(require("picocolors"), 1);
13163
+ import_promises = require("readline/promises");
13164
+ import_stream = require("stream");
13165
+ QUESTION_MARKER = import_picocolors7.default.cyan(import_picocolors7.default.bold("\u2192"));
13166
+ terminalPrompter = createTerminalPrompter(process.stdin, process.stdout);
13167
+ ABORT_ERROR_NAME = "AbortError";
13168
+ }
13169
+ });
13170
+
13171
+ // src/devices/fileAccess.ts
13172
+ function machineFileAccessDependencies() {
13173
+ return {
13174
+ prompter: terminalPrompter,
13175
+ isInteractive: isInteractiveTerminal,
13176
+ writeIdentity: writeDeviceIdentity,
13177
+ print: (message) => printer_default.print(message)
13178
+ };
13179
+ }
13180
+ function parseFilesFlag(value) {
13181
+ if (value === void 0) {
13182
+ return void 0;
13183
+ }
13184
+ switch (value.trim().toLowerCase()) {
13185
+ case FILES_FLAG_ON:
13186
+ return true;
13187
+ case FILES_FLAG_OFF:
13188
+ return false;
13189
+ default:
13190
+ return null;
13191
+ }
13192
+ }
13193
+ async function settleFileAccess(flag, token, stored, dependencies) {
13194
+ const storedForToken = stored?.token === token ? stored : null;
13195
+ let answer = flag;
13196
+ if (answer === void 0) {
13197
+ if (typeof storedForToken?.file_manager === "boolean" || !dependencies.isInteractive()) {
13198
+ return void 0;
13199
+ }
13200
+ answer = !NO_ANSWER2.test((await dependencies.prompter.ask(FILE_ACCESS_QUESTION)).trim());
13201
+ }
13202
+ if (storedForToken) {
13203
+ dependencies.writeIdentity({ ...storedForToken, file_manager: answer });
13204
+ }
13205
+ dependencies.print(answer ? FILE_ACCESS_ON_MESSAGE : FILE_ACCESS_OFF_MESSAGE2);
13206
+ return answer;
13207
+ }
13208
+ function fileAccessAllowed() {
13209
+ return readDeviceIdentity()?.file_manager !== false;
13210
+ }
13211
+ function describeFileAccess(identity) {
13212
+ if (identity.file_manager === true) {
13213
+ return "on";
13214
+ }
13215
+ if (identity.file_manager === false) {
13216
+ return "off";
13217
+ }
13218
+ return "on, not asked yet";
13219
+ }
13220
+ var FILE_ACCESS_QUESTION, INVALID_FILES_FLAG_MESSAGE, FILES_FLAG_ON, FILES_FLAG_OFF, NO_ANSWER2, FILE_ACCESS_ON_MESSAGE, FILE_ACCESS_OFF_MESSAGE2;
13221
+ var init_fileAccess = __esm({
13222
+ "src/devices/fileAccess.ts"() {
13223
+ "use strict";
13224
+ init_cjs_shims();
13225
+ init_printer();
13226
+ init_deviceIdentity();
13227
+ init_prompts();
13228
+ FILE_ACCESS_QUESTION = "Allow file access from the Pinggy dashboard? Your account can browse, copy, move and delete this machine's files from the browser. [Y/n] ";
13229
+ INVALID_FILES_FLAG_MESSAGE = "--files takes on or off.";
13230
+ FILES_FLAG_ON = "on";
13231
+ FILES_FLAG_OFF = "off";
13232
+ NO_ANSWER2 = /^n/i;
13233
+ FILE_ACCESS_ON_MESSAGE = "File access is on. To turn it off, run: pinggy device connect --files off";
13234
+ FILE_ACCESS_OFF_MESSAGE2 = "File access is off. To allow it, run: pinggy device connect --files on";
13235
+ }
13236
+ });
13237
+
13238
+ // src/devices/terminal/terminal_schema.ts
13239
+ function clampGrid(requested, fallback) {
13240
+ if (requested === void 0 || !Number.isFinite(requested)) return fallback;
13241
+ return Math.max(MIN_GRID, Math.min(MAX_GRID, Math.trunc(requested)));
13242
+ }
13243
+ var import_zod5, CHANNEL_TERMINAL, OP_OPEN, OP_OPENED, OP_CLOSE, OP_DATA, OP_ACK, OP_EXIT, OP_RESIZE, OP_SIGNAL, OP_CONTEXT, OP_SNAPSHOT, OP_RESYNC, OP_ACTIVITY, TERMINAL_SIGNALS, MIN_GRID, MAX_GRID, CLOSE_REASON_USER_CLOSED, CLOSE_REASON_IDLE_TIMEOUT, ERROR_INVALID_PAYLOAD3, ERROR_TERMINAL_LIMIT_REACHED, ERROR_TERMINAL_DISABLED, ERROR_SHELL_NOT_ALLOWED, ERROR_SPAWN_FAILED, TerminalOpenSchema, TerminalCloseSchema, TerminalResizeSchema, TerminalInputSchema, TerminalSignalSchema, TerminalAckSchema, TerminalSnapshotRequestSchema;
13244
+ var init_terminal_schema = __esm({
13245
+ "src/devices/terminal/terminal_schema.ts"() {
13246
+ "use strict";
13247
+ init_cjs_shims();
13248
+ import_zod5 = require("zod");
13249
+ CHANNEL_TERMINAL = "terminal";
13250
+ OP_OPEN = "open";
13251
+ OP_OPENED = "opened";
13252
+ OP_CLOSE = "close";
13253
+ OP_DATA = "data";
13254
+ OP_ACK = "ack";
13255
+ OP_EXIT = "exit";
13256
+ OP_RESIZE = "resize";
13257
+ OP_SIGNAL = "signal";
13258
+ OP_CONTEXT = "context";
13259
+ OP_SNAPSHOT = "snapshot";
13260
+ OP_RESYNC = "resync";
13261
+ OP_ACTIVITY = "activity";
13262
+ TERMINAL_SIGNALS = ["INT", "TERM", "QUIT", "HUP"];
13263
+ MIN_GRID = 1;
13264
+ MAX_GRID = 1e3;
13265
+ CLOSE_REASON_USER_CLOSED = "user_closed";
13266
+ CLOSE_REASON_IDLE_TIMEOUT = "idle_timeout";
13267
+ ERROR_INVALID_PAYLOAD3 = "invalid_payload";
13268
+ ERROR_TERMINAL_LIMIT_REACHED = "terminal_limit_reached";
13269
+ ERROR_TERMINAL_DISABLED = "terminal_disabled";
13270
+ ERROR_SHELL_NOT_ALLOWED = "shell_not_allowed";
13271
+ ERROR_SPAWN_FAILED = "spawn_failed";
13272
+ TerminalOpenSchema = import_zod5.z.object({
13273
+ terminal_id: import_zod5.z.string().min(1),
13274
+ cols: import_zod5.z.number().int().optional(),
13275
+ rows: import_zod5.z.number().int().optional(),
13276
+ shell: import_zod5.z.string().nullable().optional(),
13277
+ cwd: import_zod5.z.string().nullable().optional()
13278
+ });
13279
+ TerminalCloseSchema = import_zod5.z.object({
13280
+ terminal_id: import_zod5.z.string().min(1),
13281
+ reason: import_zod5.z.string().optional()
13282
+ });
13283
+ TerminalResizeSchema = import_zod5.z.object({
13284
+ terminal_id: import_zod5.z.string().min(1),
13285
+ cols: import_zod5.z.number().int(),
13286
+ rows: import_zod5.z.number().int()
13287
+ });
13288
+ TerminalInputSchema = import_zod5.z.object({
13289
+ terminal_id: import_zod5.z.string().min(1),
13290
+ data: import_zod5.z.string()
13291
+ });
13292
+ TerminalSignalSchema = import_zod5.z.object({
13293
+ terminal_id: import_zod5.z.string().min(1),
13294
+ signal: import_zod5.z.enum(TERMINAL_SIGNALS)
13295
+ });
13296
+ TerminalAckSchema = import_zod5.z.object({
13297
+ terminal_id: import_zod5.z.string().min(1),
13298
+ ack_seq: import_zod5.z.number().optional(),
13299
+ ack_bytes: import_zod5.z.number()
13300
+ });
13301
+ TerminalSnapshotRequestSchema = import_zod5.z.object({
13302
+ terminal_id: import_zod5.z.string().min(1),
13303
+ snapshot_id: import_zod5.z.string().min(1)
13304
+ });
13305
+ }
13306
+ });
13307
+
13308
+ // src/devices/terminal/flowWindow.ts
13309
+ var FlowWindow;
13310
+ var init_flowWindow = __esm({
13311
+ "src/devices/terminal/flowWindow.ts"() {
13312
+ "use strict";
13313
+ init_cjs_shims();
13314
+ FlowWindow = class {
13315
+ constructor(windowBytes) {
13316
+ this.sentBytes = 0;
13317
+ this.ackedBytes = 0;
13318
+ if (!Number.isFinite(windowBytes) || windowBytes <= 0) {
13319
+ throw new Error("A terminal flow window needs a positive size from welcome");
13320
+ }
13321
+ this.windowBytes = Math.trunc(windowBytes);
13322
+ }
13323
+ /** How many more raw bytes may go out before the browser has to catch up. */
13324
+ remaining() {
13325
+ return Math.max(0, this.windowBytes - (this.sentBytes - this.ackedBytes));
13326
+ }
13327
+ /** False means stop reading the pty. Nothing else is an acceptable response. */
13328
+ isOpen() {
13329
+ return this.remaining() > 0;
13330
+ }
13331
+ recordSent(byteCount) {
13332
+ if (!Number.isFinite(byteCount) || byteCount <= 0) return;
13333
+ this.sentBytes += Math.trunc(byteCount);
13334
+ }
13335
+ /**
13336
+ * Cumulative totals, never increments, so a dropped ack self-heals on the next one.
13337
+ *
13338
+ * A browser is not a trusted input. An ack beyond what was sent is clamped rather than believed,
13339
+ * and one that arrives out of order never moves the counter backwards.
13340
+ */
13341
+ recordAck(ackBytes) {
13342
+ if (!Number.isFinite(ackBytes)) return;
13343
+ const clamped = Math.min(Math.max(Math.trunc(ackBytes), 0), this.sentBytes);
13344
+ if (clamped > this.ackedBytes) {
13345
+ this.ackedBytes = clamped;
13346
+ }
13347
+ }
13348
+ get sent() {
13349
+ return this.sentBytes;
13350
+ }
13351
+ get acked() {
13352
+ return this.ackedBytes;
13353
+ }
13354
+ get size() {
13355
+ return this.windowBytes;
13356
+ }
13357
+ };
13358
+ }
13359
+ });
13360
+
13361
+ // src/devices/terminal/frameSplitter.ts
13362
+ function rawBundleBytes(maxFrameBytes) {
13363
+ const available = maxFrameBytes - ENVELOPE_OVERHEAD_BYTES;
13364
+ if (available <= 0) {
13365
+ throw new Error("max_frame_bytes leaves no room for a terminal payload");
13366
+ }
13367
+ return Math.floor(available * BASE64_NUMERATOR / BASE64_DENOMINATOR);
13368
+ }
13369
+ var ENVELOPE_OVERHEAD_BYTES, BASE64_NUMERATOR, BASE64_DENOMINATOR, BUNDLE_MILLIS, FrameSplitter;
13370
+ var init_frameSplitter = __esm({
13371
+ "src/devices/terminal/frameSplitter.ts"() {
13372
+ "use strict";
13373
+ init_cjs_shims();
13374
+ ENVELOPE_OVERHEAD_BYTES = 512;
13375
+ BASE64_NUMERATOR = 3;
13376
+ BASE64_DENOMINATOR = 4;
13377
+ BUNDLE_MILLIS = 8;
13378
+ FrameSplitter = class {
13379
+ constructor(emit, bundleBytes, bundleMillis = BUNDLE_MILLIS) {
13380
+ this.emit = emit;
13381
+ this.bundleBytes = bundleBytes;
13382
+ this.bundleMillis = bundleMillis;
13383
+ this.pending = [];
13384
+ this.pendingBytes = 0;
13385
+ if (!Number.isFinite(bundleBytes) || bundleBytes <= 0) {
13386
+ throw new Error("A frame splitter needs a positive bundle size");
13387
+ }
13388
+ }
13389
+ /** A chunk over the cap is split across frames, never truncated. */
13390
+ push(chunk) {
13391
+ if (chunk.length === 0) return;
13392
+ this.pending.push(chunk);
13393
+ this.pendingBytes += chunk.length;
13394
+ while (this.pendingBytes >= this.bundleBytes) {
13395
+ this.emitBytes(this.bundleBytes);
13396
+ }
13397
+ if (this.pendingBytes > 0) {
13398
+ this.arm();
13399
+ } else {
13400
+ this.disarm();
13401
+ }
13402
+ }
13403
+ /** Sends whatever is held, if anything. Used when the terminal closes and by the timer. */
13404
+ flush() {
13405
+ this.disarm();
13406
+ if (this.pendingBytes > 0) {
13407
+ this.emitBytes(this.pendingBytes);
13408
+ }
13409
+ }
13410
+ dispose() {
13411
+ this.disarm();
13412
+ this.pending = [];
13413
+ this.pendingBytes = 0;
13414
+ }
13415
+ get buffered() {
13416
+ return this.pendingBytes;
13417
+ }
13418
+ emitBytes(byteCount) {
13419
+ const joined = Buffer.concat(this.pending, this.pendingBytes);
13420
+ const frame = joined.subarray(0, byteCount);
13421
+ const rest = joined.subarray(byteCount);
13422
+ this.pending = rest.length > 0 ? [rest] : [];
13423
+ this.pendingBytes = rest.length;
10733
13424
  this.emit(frame);
10734
13425
  }
10735
13426
  arm() {
@@ -10775,7 +13466,7 @@ function displayCwd(rawCwd, resolvedHome) {
10775
13466
  }
10776
13467
  function resolvedHomeDirectory() {
10777
13468
  try {
10778
- return import_fs10.default.realpathSync(import_os5.default.homedir());
13469
+ return import_fs12.default.realpathSync(import_os7.default.homedir());
10779
13470
  } catch {
10780
13471
  return null;
10781
13472
  }
@@ -10794,14 +13485,14 @@ async function readFromProc(shellPids) {
10794
13485
  await Promise.all(shellPids.map(async (shellPid) => {
10795
13486
  const groups = await readProcGroups(shellPid);
10796
13487
  if (!groups) return;
10797
- const cwd = await readOrNull(() => import_fs10.default.promises.readlink(`/proc/${shellPid}/cwd`));
10798
- const foregroundName = groups.foregroundGroupId === groups.shellGroupId ? null : await readOrNull(() => import_fs10.default.promises.readFile(`/proc/${groups.foregroundGroupId}/comm`, "utf8"));
13488
+ const cwd = await readOrNull(() => import_fs12.default.promises.readlink(`/proc/${shellPid}/cwd`));
13489
+ const foregroundName = groups.foregroundGroupId === groups.shellGroupId ? null : await readOrNull(() => import_fs12.default.promises.readFile(`/proc/${groups.foregroundGroupId}/comm`, "utf8"));
10799
13490
  contexts.set(shellPid, { cwd, foregroundName });
10800
13491
  }));
10801
13492
  return contexts;
10802
13493
  }
10803
13494
  async function readProcGroups(shellPid) {
10804
- const stat = await readOrNull(() => import_fs10.default.promises.readFile(`/proc/${shellPid}/stat`, "utf8"));
13495
+ const stat = await readOrNull(() => import_fs12.default.promises.readFile(`/proc/${shellPid}/stat`, "utf8"));
10805
13496
  if (stat === null) return null;
10806
13497
  const afterName = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
10807
13498
  const shellGroupId = Number.parseInt(afterName[2], 10);
@@ -10869,14 +13560,14 @@ async function readOrNull(read) {
10869
13560
  return null;
10870
13561
  }
10871
13562
  }
10872
- var import_child_process2, import_fs10, import_os5, SHELL_CONTEXT_POLL_MILLIS, MAX_CWD_CHARACTERS, MAX_COMMAND_CHARACTERS, PROCESS_READ_TIMEOUT_MILLIS, HOME_PREFIX, ShellContextTracker;
13563
+ var import_child_process2, import_fs12, import_os7, SHELL_CONTEXT_POLL_MILLIS, MAX_CWD_CHARACTERS, MAX_COMMAND_CHARACTERS, PROCESS_READ_TIMEOUT_MILLIS, HOME_PREFIX, ShellContextTracker;
10873
13564
  var init_shellContext = __esm({
10874
13565
  "src/devices/terminal/shellContext.ts"() {
10875
13566
  "use strict";
10876
13567
  init_cjs_shims();
10877
13568
  import_child_process2 = require("child_process");
10878
- import_fs10 = __toESM(require("fs"), 1);
10879
- import_os5 = __toESM(require("os"), 1);
13569
+ import_fs12 = __toESM(require("fs"), 1);
13570
+ import_os7 = __toESM(require("os"), 1);
10880
13571
  SHELL_CONTEXT_POLL_MILLIS = 5e3;
10881
13572
  MAX_CWD_CHARACTERS = 1024;
10882
13573
  MAX_COMMAND_CHARACTERS = 64;
@@ -11036,7 +13727,7 @@ var init_screenMirror = __esm({
11036
13727
 
11037
13728
  // src/devices/terminal/terminalHandler.ts
11038
13729
  function positiveMillis(seconds) {
11039
- return seconds !== void 0 && Number.isFinite(seconds) && seconds > 0 ? seconds * MILLIS_PER_SECOND : void 0;
13730
+ return seconds !== void 0 && Number.isFinite(seconds) && seconds > 0 ? seconds * MILLIS_PER_SECOND3 : void 0;
11040
13731
  }
11041
13732
  function splitIntoParts(bytes, partBytes) {
11042
13733
  const parts = [];
@@ -11049,18 +13740,18 @@ function errorName2(err) {
11049
13740
  return err instanceof Error ? err.name : typeof err;
11050
13741
  }
11051
13742
  function signalName(signal) {
11052
- for (const [name, number] of Object.entries(import_os6.default.constants.signals)) {
13743
+ for (const [name, number] of Object.entries(import_os8.default.constants.signals)) {
11053
13744
  if (number === signal) return name.replace(/^SIG/, "");
11054
13745
  }
11055
13746
  return String(signal);
11056
13747
  }
11057
- var import_crypto3, import_os6, DEFAULT_COLS, DEFAULT_ROWS, EXPIRY_CHECK_MILLIS, MILLIS_PER_SECOND, RESYNC_MIN_INTERVAL_MILLIS, MIRROR_HIGH_WATER_BYTES, MIRROR_LOW_WATER_BYTES, ACTIVITY_REPORT_MILLIS, DEFAULT_SKIP_TUNING, TerminalHandler;
13748
+ var import_crypto4, import_os8, DEFAULT_COLS, DEFAULT_ROWS, EXPIRY_CHECK_MILLIS, MILLIS_PER_SECOND3, RESYNC_MIN_INTERVAL_MILLIS, MIRROR_HIGH_WATER_BYTES, MIRROR_LOW_WATER_BYTES, ACTIVITY_REPORT_MILLIS, DEFAULT_SKIP_TUNING, TerminalHandler;
11058
13749
  var init_terminalHandler = __esm({
11059
13750
  "src/devices/terminal/terminalHandler.ts"() {
11060
13751
  "use strict";
11061
13752
  init_cjs_shims();
11062
- import_crypto3 = require("crypto");
11063
- import_os6 = __toESM(require("os"), 1);
13753
+ import_crypto4 = require("crypto");
13754
+ import_os8 = __toESM(require("os"), 1);
11064
13755
  init_logger();
11065
13756
  init_envelope();
11066
13757
  init_terminal_schema();
@@ -11071,7 +13762,7 @@ var init_terminalHandler = __esm({
11071
13762
  DEFAULT_COLS = 80;
11072
13763
  DEFAULT_ROWS = 24;
11073
13764
  EXPIRY_CHECK_MILLIS = 5e3;
11074
- MILLIS_PER_SECOND = 1e3;
13765
+ MILLIS_PER_SECOND3 = 1e3;
11075
13766
  RESYNC_MIN_INTERVAL_MILLIS = 1e3;
11076
13767
  MIRROR_HIGH_WATER_BYTES = 1024 * 1024;
11077
13768
  MIRROR_LOW_WATER_BYTES = 256 * 1024;
@@ -11277,7 +13968,7 @@ var init_terminalHandler = __esm({
11277
13968
  open(envelope) {
11278
13969
  const parsed = TerminalOpenSchema.safeParse(envelope.payload);
11279
13970
  if (!parsed.success) {
11280
- this.refuse(envelope, null, ERROR_INVALID_PAYLOAD2, "open payload could not be read.");
13971
+ this.refuse(envelope, null, ERROR_INVALID_PAYLOAD3, "open payload could not be read.");
11281
13972
  return;
11282
13973
  }
11283
13974
  const request2 = parsed.data;
@@ -11584,7 +14275,7 @@ var init_terminalHandler = __esm({
11584
14275
  return;
11585
14276
  }
11586
14277
  if (screen && this.bundleBytes !== void 0) {
11587
- const resyncId = (0, import_crypto3.randomUUID)();
14278
+ const resyncId = (0, import_crypto4.randomUUID)();
11588
14279
  const parts = splitIntoParts(Buffer.from(screen.text, "utf-8"), this.bundleBytes);
11589
14280
  parts.forEach((part, index) => {
11590
14281
  const payload = {
@@ -11908,11 +14599,11 @@ function ensureSpawnHelperExecutable(packageRoot) {
11908
14599
  function resolveCwd(requested) {
11909
14600
  if (requested) {
11910
14601
  try {
11911
- if (import_fs11.default.statSync(requested).isDirectory()) return requested;
14602
+ if (import_fs13.default.statSync(requested).isDirectory()) return requested;
11912
14603
  } catch {
11913
14604
  }
11914
14605
  }
11915
- return import_os7.default.homedir();
14606
+ return import_os9.default.homedir();
11916
14607
  }
11917
14608
  function spawnPty(request2) {
11918
14609
  const pty = loadNodePty();
@@ -11956,14 +14647,14 @@ function spawnPty(request2) {
11956
14647
  }
11957
14648
  };
11958
14649
  }
11959
- var import_child_process3, import_fs11, import_os7, loadedPty, TERM_NAME;
14650
+ var import_child_process3, import_fs13, import_os9, loadedPty, TERM_NAME;
11960
14651
  var init_ptySession = __esm({
11961
14652
  "src/devices/terminal/ptySession.ts"() {
11962
14653
  "use strict";
11963
14654
  init_cjs_shims();
11964
14655
  import_child_process3 = require("child_process");
11965
- import_fs11 = __toESM(require("fs"), 1);
11966
- import_os7 = __toESM(require("os"), 1);
14656
+ import_fs13 = __toESM(require("fs"), 1);
14657
+ import_os9 = __toESM(require("os"), 1);
11967
14658
  init_logger();
11968
14659
  init_nodePtyRuntime();
11969
14660
  TERM_NAME = "xterm-256color";
@@ -11974,7 +14665,7 @@ var init_ptySession = __esm({
11974
14665
  function readShellEnvironment() {
11975
14666
  let etcShells = null;
11976
14667
  try {
11977
- etcShells = import_fs12.default.readFileSync(ETC_SHELLS_PATH, "utf8");
14668
+ etcShells = import_fs14.default.readFileSync(ETC_SHELLS_PATH, "utf8");
11978
14669
  } catch {
11979
14670
  etcShells = null;
11980
14671
  }
@@ -11982,9 +14673,9 @@ function readShellEnvironment() {
11982
14673
  platform: process.platform,
11983
14674
  loginShell: process.env.SHELL,
11984
14675
  etcShells,
11985
- exists: (path20) => {
14676
+ exists: (path23) => {
11986
14677
  try {
11987
- return import_fs12.default.statSync(path20).isFile();
14678
+ return import_fs14.default.statSync(path23).isFile();
11988
14679
  } catch {
11989
14680
  return false;
11990
14681
  }
@@ -12015,12 +14706,12 @@ function resolveShell(requested, environment) {
12015
14706
  const firstUsable = allowed.find(usable);
12016
14707
  return firstUsable ? { shell: firstUsable } : { error: "No allowed shell exists on this machine." };
12017
14708
  }
12018
- var import_fs12, FALLBACK_UNIX_SHELLS, WINDOWS_SHELLS, ETC_SHELLS_PATH;
14709
+ var import_fs14, FALLBACK_UNIX_SHELLS, WINDOWS_SHELLS, ETC_SHELLS_PATH;
12019
14710
  var init_shellAllowlist = __esm({
12020
14711
  "src/devices/terminal/shellAllowlist.ts"() {
12021
14712
  "use strict";
12022
14713
  init_cjs_shims();
12023
- import_fs12 = __toESM(require("fs"), 1);
14714
+ import_fs14 = __toESM(require("fs"), 1);
12024
14715
  FALLBACK_UNIX_SHELLS = ["/bin/bash", "/bin/zsh", "/bin/sh", "/usr/bin/bash", "/usr/bin/zsh"];
12025
14716
  WINDOWS_SHELLS = ["powershell.exe", "cmd.exe"];
12026
14717
  ETC_SHELLS_PATH = "/etc/shells";
@@ -12030,7 +14721,7 @@ var init_shellAllowlist = __esm({
12030
14721
  // src/devices/foregroundAgent.ts
12031
14722
  function readRecordFile(filePath) {
12032
14723
  try {
12033
- const record = JSON.parse(import_fs13.default.readFileSync(filePath, "utf-8"));
14724
+ const record = JSON.parse(import_fs15.default.readFileSync(filePath, "utf-8"));
12034
14725
  return Number.isInteger(record.pid) && record.pid > 0 ? record : null;
12035
14726
  } catch {
12036
14727
  return null;
@@ -12038,7 +14729,7 @@ function readRecordFile(filePath) {
12038
14729
  }
12039
14730
  function deleteRecordFile(filePath) {
12040
14731
  try {
12041
- import_fs13.default.unlinkSync(filePath);
14732
+ import_fs15.default.unlinkSync(filePath);
12042
14733
  } catch (err) {
12043
14734
  logger.debug("No foreground agent record to delete", { error: errorMessage(err) });
12044
14735
  }
@@ -12068,7 +14759,7 @@ function recordForegroundAgent(onRecordDeleted) {
12068
14759
  };
12069
14760
  try {
12070
14761
  ensurePinggyConfigDir();
12071
- import_fs13.default.writeFileSync(filePath, JSON.stringify(record, null, 2), "utf-8");
14762
+ import_fs15.default.writeFileSync(filePath, JSON.stringify(record, null, 2), "utf-8");
12072
14763
  } catch (err) {
12073
14764
  logger.warn(
12074
14765
  "Could not write device-agent.json. pinggy device remove cannot stop this agent.",
@@ -12077,7 +14768,7 @@ function recordForegroundAgent(onRecordDeleted) {
12077
14768
  return () => void 0;
12078
14769
  }
12079
14770
  const timer = setInterval(() => {
12080
- if (!import_fs13.default.existsSync(filePath)) {
14771
+ if (!import_fs15.default.existsSync(filePath)) {
12081
14772
  clearInterval(timer);
12082
14773
  onRecordDeleted();
12083
14774
  }
@@ -12124,12 +14815,12 @@ function foregroundAgentRefusal(record = readForegroundAgent()) {
12124
14815
  }
12125
14816
  return `This machine already runs as a device in another terminal (PID ${record.pid}). Press Ctrl+C in that terminal first.`;
12126
14817
  }
12127
- var import_fs13, RECORD_CHECK_INTERVAL_MILLIS, STOP_WAIT_MILLIS, STOP_POLL_INTERVAL_MILLIS;
14818
+ var import_fs15, RECORD_CHECK_INTERVAL_MILLIS, STOP_WAIT_MILLIS, STOP_POLL_INTERVAL_MILLIS;
12128
14819
  var init_foregroundAgent = __esm({
12129
14820
  "src/devices/foregroundAgent.ts"() {
12130
14821
  "use strict";
12131
14822
  init_cjs_shims();
12132
- import_fs13 = __toESM(require("fs"), 1);
14823
+ import_fs15 = __toESM(require("fs"), 1);
12133
14824
  init_configDir();
12134
14825
  init_daemonManager();
12135
14826
  init_bootId();
@@ -12170,8 +14861,8 @@ function sleep2(millis, state) {
12170
14861
  function buildHello(terminalHandler) {
12171
14862
  return {
12172
14863
  agent_version: getVersion(),
12173
- os: import_os8.default.platform(),
12174
- hostname: import_os8.default.hostname(),
14864
+ os: import_os10.default.platform(),
14865
+ hostname: import_os10.default.hostname(),
12175
14866
  capabilities: buildCapabilities(isTerminalSupported(), isScreenMirrorSupported()),
12176
14867
  terminals: terminalHandler.held()
12177
14868
  };
@@ -12190,11 +14881,13 @@ function startMetricsReporting(intervalSeconds, collect, send) {
12190
14881
  clearInterval(timer);
12191
14882
  };
12192
14883
  }
12193
- function identityForRun(token, server, stored) {
12194
- if (stored?.token === token) {
12195
- return { ...stored, server };
14884
+ function identityForRun(token, server, stored, fileManager) {
14885
+ const identity = stored?.token === token ? { ...stored, server } : { device_agent_id: null, token, server, enrolled_at: null };
14886
+ delete identity.file_manager;
14887
+ if (fileManager !== void 0) {
14888
+ identity.file_manager = fileManager;
12196
14889
  }
12197
- return { device_agent_id: null, token, server, enrolled_at: null };
14890
+ return identity;
12198
14891
  }
12199
14892
  function startDeviceAgent(token, manage, options = {}) {
12200
14893
  const server = manage || DEFAULT_SERVER;
@@ -12205,7 +14898,7 @@ function startDeviceAgent(token, manage, options = {}) {
12205
14898
  const context = {
12206
14899
  wsUrl: buildDeviceAgentWsUrl(manage),
12207
14900
  server,
12208
- identity: identityForRun(token, server, stored),
14901
+ identity: identityForRun(token, server, stored, options.fileManager),
12209
14902
  reconnectPolicy: options.reconnectPolicy ?? new ReconnectPolicy(),
12210
14903
  handshakeTimeoutMillis: options.handshakeTimeoutMillis ?? HANDSHAKE_TIMEOUT_MILLIS,
12211
14904
  terminalHandler: new TerminalHandler({
@@ -12216,6 +14909,7 @@ function startDeviceAgent(token, manage, options = {}) {
12216
14909
  readShellContexts: processTableReader(),
12217
14910
  resolvedHome: resolvedHomeDirectory()
12218
14911
  }),
14912
+ fileHandler: new FileHandler({ send: (frame) => connection.send?.(frame), fileAccessAllowed }),
12219
14913
  connection,
12220
14914
  reporter,
12221
14915
  writeIdentity: options.writeIdentity ?? writeDeviceIdentity,
@@ -12281,7 +14975,7 @@ function fail(context, error) {
12281
14975
  return "terminal";
12282
14976
  }
12283
14977
  function connectOnce(context) {
12284
- const { identity, reconnectPolicy, terminalHandler, connection, reporter, state, options } = context;
14978
+ const { identity, reconnectPolicy, terminalHandler, fileHandler, connection, reporter, state, options } = context;
12285
14979
  return new Promise((resolve) => {
12286
14980
  const ws = new import_ws3.default(context.wsUrl, { headers: { [TOKEN_HEADER]: identity.token } });
12287
14981
  let heartbeat = null;
@@ -12366,7 +15060,7 @@ function connectOnce(context) {
12366
15060
  const startHeartbeat = (intervalSeconds) => {
12367
15061
  heartbeat = setInterval(
12368
15062
  () => sendFrame(
12369
- event(CHANNEL_SYSTEM, OP_HEARTBEAT, { uptime_seconds: Math.floor(import_os8.default.uptime()) })
15063
+ event(CHANNEL_SYSTEM, OP_HEARTBEAT, { uptime_seconds: Math.floor(import_os10.default.uptime()) })
12370
15064
  ),
12371
15065
  intervalSeconds * 1e3
12372
15066
  );
@@ -12388,6 +15082,12 @@ function connectOnce(context) {
12388
15082
  welcome.terminal_resync
12389
15083
  );
12390
15084
  terminalHandler.resumeAll();
15085
+ fileHandler.configure(
15086
+ welcome.file_manager_enabled,
15087
+ welcome.max_frame_bytes,
15088
+ welcome.file_max_concurrent_operations,
15089
+ welcome.file_max_queued_operations
15090
+ );
12391
15091
  startHeartbeat(welcome.heartbeat_interval_seconds);
12392
15092
  startPongWatchdog(welcome.heartbeat_interval_seconds);
12393
15093
  sendFrame(event(CHANNEL_DEVICE, OP_INFO, collectSystemInfo()));
@@ -12411,6 +15111,10 @@ function connectOnce(context) {
12411
15111
  terminalHandler.handle(envelope);
12412
15112
  return;
12413
15113
  }
15114
+ if (envelope.ch === CHANNEL_FILE) {
15115
+ void fileHandler.handle(envelope);
15116
+ return;
15117
+ }
12414
15118
  if (envelope.ch === CHANNEL_TUNNEL) {
12415
15119
  void handleTunnelAction(envelope, (frame) => connection.send?.(frame), options.tunnelActions).then(() => stopTunnels?.pollNow());
12416
15120
  return;
@@ -12506,13 +15210,13 @@ function describeDisconnect(reason) {
12506
15210
  message: DISCONNECT_MESSAGES[reason] ?? `Disconnected by the dashboard: ${reason}. Re-enrol this device to continue.`
12507
15211
  };
12508
15212
  }
12509
- var import_ws3, import_os8, CLOSE_CODE_REVOKED, CLOSE_CODE_NORMAL, CLOSE_TIMEOUT_MILLIS, TOKEN_HEADER, DEFAULT_SERVER, ERROR_ALREADY_CONNECTED, AGENT_ERROR_UNAUTHORIZED, AGENT_ERROR_HANDSHAKE_REFUSED, AGENT_ERROR_DISCONNECTED, AGENT_ERROR_NOT_CONNECTED, UNAUTHORIZED_STORED_TOKEN_MESSAGE, UNAUTHORIZED_NEW_TOKEN_MESSAGE, HANDSHAKE_TIMEOUT_MILLIS, PONG_GRACE_INTERVALS, BASE_CAPABILITIES, CAPABILITY_TERMINAL, CAPABILITY_TERMINAL_SNAPSHOT, CAPABILITY_TERMINAL_RESYNC, DISCONNECT_REASON_SHUTDOWN, DISCONNECT_MESSAGES;
15213
+ var import_ws3, import_os10, CLOSE_CODE_REVOKED, CLOSE_CODE_NORMAL, CLOSE_TIMEOUT_MILLIS, TOKEN_HEADER, DEFAULT_SERVER, ERROR_ALREADY_CONNECTED, AGENT_ERROR_UNAUTHORIZED, AGENT_ERROR_HANDSHAKE_REFUSED, AGENT_ERROR_DISCONNECTED, AGENT_ERROR_NOT_CONNECTED, UNAUTHORIZED_STORED_TOKEN_MESSAGE, UNAUTHORIZED_NEW_TOKEN_MESSAGE, HANDSHAKE_TIMEOUT_MILLIS, PONG_GRACE_INTERVALS, BASE_CAPABILITIES, CAPABILITY_TERMINAL, CAPABILITY_TERMINAL_SNAPSHOT, CAPABILITY_TERMINAL_RESYNC, DISCONNECT_REASON_SHUTDOWN, DISCONNECT_MESSAGES;
12510
15214
  var init_deviceAgent = __esm({
12511
15215
  "src/devices/deviceAgent.ts"() {
12512
15216
  "use strict";
12513
15217
  init_cjs_shims();
12514
15218
  import_ws3 = __toESM(require("ws"), 1);
12515
- import_os8 = __toESM(require("os"), 1);
15219
+ import_os10 = __toESM(require("os"), 1);
12516
15220
  init_logger();
12517
15221
  init_util();
12518
15222
  init_envelope();
@@ -12524,6 +15228,9 @@ var init_deviceAgent = __esm({
12524
15228
  init_tunnelList();
12525
15229
  init_tunnelActions();
12526
15230
  init_reconnect();
15231
+ init_file_schema();
15232
+ init_fileHandler();
15233
+ init_fileAccess();
12527
15234
  init_terminal_schema();
12528
15235
  init_terminalHandler();
12529
15236
  init_screenMirror();
@@ -12547,7 +15254,14 @@ var init_deviceAgent = __esm({
12547
15254
  UNAUTHORIZED_NEW_TOKEN_MESSAGE = "The dashboard refused this device token. Check the token, or copy the install command from the dashboard again.";
12548
15255
  HANDSHAKE_TIMEOUT_MILLIS = 3e4;
12549
15256
  PONG_GRACE_INTERVALS = 2;
12550
- BASE_CAPABILITIES = ["tunnel", "stats", "tunnel_control", "tunnel_update", "saved_config_update"];
15257
+ BASE_CAPABILITIES = [
15258
+ "tunnel",
15259
+ "stats",
15260
+ "tunnel_control",
15261
+ "tunnel_update",
15262
+ "saved_config_update",
15263
+ "file_manager"
15264
+ ];
12551
15265
  CAPABILITY_TERMINAL = "terminal";
12552
15266
  CAPABILITY_TERMINAL_SNAPSHOT = "terminal_snapshot";
12553
15267
  CAPABILITY_TERMINAL_RESYNC = "terminal_resync";
@@ -12561,34 +15275,34 @@ var init_deviceAgent = __esm({
12561
15275
  });
12562
15276
 
12563
15277
  // src/devices/login/login_schema.ts
12564
- var import_zod5, LoginStartedSchema, LoginStatus, LoginAnswerSchema, LoginErrorSchema, LoginErrorType;
15278
+ var import_zod6, LoginStartedSchema, LoginStatus, LoginAnswerSchema, LoginErrorSchema, LoginErrorType;
12565
15279
  var init_login_schema = __esm({
12566
15280
  "src/devices/login/login_schema.ts"() {
12567
15281
  "use strict";
12568
15282
  init_cjs_shims();
12569
- import_zod5 = require("zod");
12570
- LoginStartedSchema = import_zod5.z.object({
12571
- device_code: import_zod5.z.string().min(1),
12572
- match_code: import_zod5.z.string().min(1).optional(),
12573
- expires_in_seconds: import_zod5.z.number().int().positive(),
12574
- poll_interval_seconds: import_zod5.z.number().int().positive()
15283
+ import_zod6 = require("zod");
15284
+ LoginStartedSchema = import_zod6.z.object({
15285
+ device_code: import_zod6.z.string().min(1),
15286
+ match_code: import_zod6.z.string().min(1).optional(),
15287
+ expires_in_seconds: import_zod6.z.number().int().positive(),
15288
+ poll_interval_seconds: import_zod6.z.number().int().positive()
12575
15289
  });
12576
15290
  LoginStatus = {
12577
15291
  Pending: "pending",
12578
15292
  MfaRequired: "mfa_required",
12579
15293
  Approved: "approved"
12580
15294
  };
12581
- LoginAnswerSchema = import_zod5.z.object({
12582
- status: import_zod5.z.enum([LoginStatus.Pending, LoginStatus.MfaRequired, LoginStatus.Approved]),
12583
- token: import_zod5.z.string().min(1).optional(),
12584
- device_agent_id: import_zod5.z.string().min(1).optional(),
12585
- device_name: import_zod5.z.string().optional(),
12586
- open_url: import_zod5.z.string().optional(),
12587
- device_url: import_zod5.z.string().optional()
15295
+ LoginAnswerSchema = import_zod6.z.object({
15296
+ status: import_zod6.z.enum([LoginStatus.Pending, LoginStatus.MfaRequired, LoginStatus.Approved]),
15297
+ token: import_zod6.z.string().min(1).optional(),
15298
+ device_agent_id: import_zod6.z.string().min(1).optional(),
15299
+ device_name: import_zod6.z.string().optional(),
15300
+ open_url: import_zod6.z.string().optional(),
15301
+ device_url: import_zod6.z.string().optional()
12588
15302
  });
12589
- LoginErrorSchema = import_zod5.z.object({
12590
- error_type: import_zod5.z.string(),
12591
- errors: import_zod5.z.array(import_zod5.z.string()).default([])
15303
+ LoginErrorSchema = import_zod6.z.object({
15304
+ error_type: import_zod6.z.string(),
15305
+ errors: import_zod6.z.array(import_zod6.z.string()).default([])
12592
15306
  });
12593
15307
  LoginErrorType = {
12594
15308
  /** A wrong code or authenticator code, with attempts left. Asked again. */
@@ -12611,8 +15325,8 @@ function buildDashboardHttpUrl(manage) {
12611
15325
  }
12612
15326
  function createDeviceLoginApi(manage, fetchImpl = fetch) {
12613
15327
  const baseUrl = buildDashboardHttpUrl(manage);
12614
- async function post(path20, body, schema) {
12615
- const response2 = await fetchImpl(`${baseUrl}/${path20}`, {
15328
+ async function post(path23, body, schema) {
15329
+ const response2 = await fetchImpl(`${baseUrl}/${path23}`, {
12616
15330
  method: "POST",
12617
15331
  headers: { "Content-Type": "application/json", Accept: "application/json" },
12618
15332
  body: JSON.stringify(body)
@@ -12680,56 +15394,6 @@ var init_loginApi = __esm({
12680
15394
  }
12681
15395
  });
12682
15396
 
12683
- // src/devices/login/prompts.ts
12684
- function createTerminalPrompter(input, output) {
12685
- return {
12686
- async ask(question, signal) {
12687
- const readline = (0, import_promises.createInterface)({ input, output, terminal: true });
12688
- try {
12689
- return await readline.question(marked(question), signal ? { signal } : {});
12690
- } finally {
12691
- readline.close();
12692
- }
12693
- },
12694
- async askHidden(question, signal) {
12695
- output.write(marked(question));
12696
- const readline = (0, import_promises.createInterface)({ input, output: discardingOutput(), terminal: true });
12697
- try {
12698
- const answer = await readline.question("", signal ? { signal } : {});
12699
- output.write("\n");
12700
- return answer;
12701
- } finally {
12702
- readline.close();
12703
- }
12704
- }
12705
- };
12706
- }
12707
- function isInteractiveTerminal() {
12708
- return process.stdin.isTTY === true;
12709
- }
12710
- function marked(question) {
12711
- return `${QUESTION_MARKER} ${question}`;
12712
- }
12713
- function discardingOutput() {
12714
- return new import_stream.Writable({
12715
- write(_chunk, _encoding, callback) {
12716
- callback();
12717
- }
12718
- });
12719
- }
12720
- var import_picocolors7, import_promises, import_stream, QUESTION_MARKER, terminalPrompter;
12721
- var init_prompts = __esm({
12722
- "src/devices/login/prompts.ts"() {
12723
- "use strict";
12724
- init_cjs_shims();
12725
- import_picocolors7 = __toESM(require("picocolors"), 1);
12726
- import_promises = require("readline/promises");
12727
- import_stream = require("stream");
12728
- QUESTION_MARKER = import_picocolors7.default.cyan(import_picocolors7.default.bold("\u2192"));
12729
- terminalPrompter = createTerminalPrompter(process.stdin, process.stdout);
12730
- }
12731
- });
12732
-
12733
15397
  // src/devices/login/deviceLogin.ts
12734
15398
  function machineDeviceLoginDependencies() {
12735
15399
  return {
@@ -12741,9 +15405,9 @@ function machineDeviceLoginDependencies() {
12741
15405
  runAgent: (token, manage) => runDeviceAgent(token, manage),
12742
15406
  renderQr: async (url) => (await createQrCodes([url]))[0],
12743
15407
  machine: () => ({
12744
- hostname: import_os9.default.hostname(),
12745
- os: import_os9.default.platform(),
12746
- arch: import_os9.default.arch(),
15408
+ hostname: import_os11.default.hostname(),
15409
+ os: import_os11.default.platform(),
15410
+ arch: import_os11.default.arch(),
12747
15411
  agent_version: getVersion()
12748
15412
  }),
12749
15413
  print: (message) => printer_default.print(message),
@@ -12762,9 +15426,6 @@ async function runDeviceLogin(options, dependencies = machineDeviceLoginDependen
12762
15426
  return EXIT_FAILED;
12763
15427
  }
12764
15428
  }
12765
- function isCtrlCAtPrompt(err) {
12766
- return err instanceof Error && err.name === ABORT_ERROR_NAME;
12767
- }
12768
15429
  async function signInAndRunAgent(options, dependencies) {
12769
15430
  if (!dependencies.isInteractive()) {
12770
15431
  dependencies.printError(NO_TERMINAL_MESSAGE);
@@ -12777,6 +15438,7 @@ async function signInAndRunAgent(options, dependencies) {
12777
15438
  `This machine is already enrolled as ${stored.device_agent_id ?? "a device"} on ${stored.server}. Add it again as a new device? [y/N] `
12778
15439
  );
12779
15440
  if (!YES_ANSWER.test(answer.trim())) {
15441
+ await settleFileAccess(options.fileManager, stored.token, stored, dependencies);
12780
15442
  return await dependencies.runAgent(stored.token, manage, false) ?? EXIT_OK;
12781
15443
  }
12782
15444
  }
@@ -12809,13 +15471,25 @@ async function signInAndRunAgent(options, dependencies) {
12809
15471
  dependencies.printError("The dashboard approved the sign-in without a device token. Update pinggy and try again.");
12810
15472
  return EXIT_FAILED;
12811
15473
  }
12812
- dependencies.writeIdentity({
15474
+ const identity = {
12813
15475
  device_agent_id: approved.device_agent_id,
12814
15476
  token: approved.token,
12815
15477
  server: manage || DEFAULT_SERVER2,
12816
15478
  enrolled_at: null
12817
- });
15479
+ };
12818
15480
  dependencies.print(`${RESULT_MARKER} Signed in as ${email}. Added device ${approved.device_name ?? approved.device_agent_id}.`);
15481
+ let fileManager;
15482
+ try {
15483
+ fileManager = await settleFileAccess(options.fileManager, identity.token, null, dependencies);
15484
+ } catch (err) {
15485
+ if (!isCtrlCAtPrompt(err)) {
15486
+ throw err;
15487
+ }
15488
+ dependencies.writeIdentity(identity);
15489
+ dependencies.print(import_picocolors8.default.yellow("Cancelled. This machine is signed in, and its agent did not start. To start it, run: pinggy device connect"));
15490
+ return EXIT_FAILED;
15491
+ }
15492
+ dependencies.writeIdentity({ ...identity, file_manager: fileManager });
12819
15493
  await printDeviceLink(approved, linkMinutes, dependencies);
12820
15494
  return await dependencies.runAgent(approved.token, manage, true) ?? EXIT_OK;
12821
15495
  }
@@ -12836,7 +15510,7 @@ async function waitForApproval(api, deviceCode, pollIntervalSeconds, dependencie
12836
15510
  const polled = pollUntilApproved(
12837
15511
  api,
12838
15512
  deviceCode,
12839
- pollIntervalSeconds * MILLIS_PER_SECOND2,
15513
+ pollIntervalSeconds * MILLIS_PER_SECOND4,
12840
15514
  controller.signal,
12841
15515
  dependencies
12842
15516
  );
@@ -12971,12 +15645,12 @@ function sleepUnlessAborted(millis, signal) {
12971
15645
  signal.addEventListener("abort", onAbort, { once: true });
12972
15646
  });
12973
15647
  }
12974
- var import_os9, import_picocolors8, EXIT_OK, EXIT_FAILED, DEFAULT_SERVER2, YES_ANSWER, RESULT_MARKER, SECONDS_PER_MINUTE, MILLIS_PER_SECOND2, FIRST_SERVER_ERROR_STATUS, NO_TERMINAL_MESSAGE, ABORT_ERROR_NAME;
15648
+ var import_os11, import_picocolors8, EXIT_OK, EXIT_FAILED, DEFAULT_SERVER2, YES_ANSWER, RESULT_MARKER, SECONDS_PER_MINUTE, MILLIS_PER_SECOND4, FIRST_SERVER_ERROR_STATUS, NO_TERMINAL_MESSAGE;
12975
15649
  var init_deviceLogin = __esm({
12976
15650
  "src/devices/login/deviceLogin.ts"() {
12977
15651
  "use strict";
12978
15652
  init_cjs_shims();
12979
- import_os9 = __toESM(require("os"), 1);
15653
+ import_os11 = __toESM(require("os"), 1);
12980
15654
  import_picocolors8 = __toESM(require("picocolors"), 1);
12981
15655
  init_printer();
12982
15656
  init_util();
@@ -12986,6 +15660,7 @@ var init_deviceLogin = __esm({
12986
15660
  init_deviceIdentity();
12987
15661
  init_loginApi();
12988
15662
  init_login_schema();
15663
+ init_fileAccess();
12989
15664
  init_prompts();
12990
15665
  EXIT_OK = 0;
12991
15666
  EXIT_FAILED = 1;
@@ -12993,10 +15668,9 @@ var init_deviceLogin = __esm({
12993
15668
  YES_ANSWER = /^y(es)?$/i;
12994
15669
  RESULT_MARKER = import_picocolors8.default.green(import_picocolors8.default.bold("\u2192"));
12995
15670
  SECONDS_PER_MINUTE = 60;
12996
- MILLIS_PER_SECOND2 = 1e3;
15671
+ MILLIS_PER_SECOND4 = 1e3;
12997
15672
  FIRST_SERVER_ERROR_STATUS = 500;
12998
15673
  NO_TERMINAL_MESSAGE = "pinggy device login needs a terminal to type the email and the code. On a machine without one, add the device in the dashboard and run: pinggy device connect --token <TOKEN>";
12999
- ABORT_ERROR_NAME = "AbortError";
13000
15674
  }
13001
15675
  });
13002
15676
 
@@ -13010,9 +15684,10 @@ function machineBackgroundAgentDependencies() {
13010
15684
  forgetSavedAgent: forgetDeviceAgent,
13011
15685
  ensureDaemon: ensureDaemonRunning,
13012
15686
  client: (port) => new IPCClient(port, "cli"),
13013
- verify: (token, manage) => startDeviceAgent(token, manage, {
15687
+ verify: (token, manage, fileManager) => startDeviceAgent(token, manage, {
13014
15688
  verifyOnly: true,
13015
- reporter: verifyingReporter
15689
+ reporter: verifyingReporter,
15690
+ fileManager
13016
15691
  }).done,
13017
15692
  sleep: (millis) => new Promise((resolve) => setTimeout(resolve, millis)),
13018
15693
  now: () => Date.now(),
@@ -13050,7 +15725,7 @@ async function readBackgroundAgent(dependencies) {
13050
15725
  }
13051
15726
  async function startAgentInBackground(target, dependencies, options = {}) {
13052
15727
  if (differsFromStored(target, dependencies.readIdentity())) {
13053
- const verified = await dependencies.verify(target.token, target.manage);
15728
+ const verified = await dependencies.verify(target.token, target.manage, options.fileManager);
13054
15729
  if (verified.error || !verified.welcomed) {
13055
15730
  dependencies.printError(verified.error?.message ?? "The device did not connect. Nothing changed.");
13056
15731
  return EXIT_FAILED;
@@ -13346,7 +16021,7 @@ async function handleDaemonStatus() {
13346
16021
  printer_default.print(` Port: ${info.port}`);
13347
16022
  printer_default.print(` Started: ${info.startedAt}`);
13348
16023
  printer_default.print(` Uptime: ${uptimeStr}`);
13349
- printer_default.print(` Host: ${info.host === DaemonHost.APP ? "Pinggy app (in-process)" : "standalone (CLI)"}`);
16024
+ printer_default.print(` Host: ${info.host === DaemonHost.APP ? "Pinggy app" : "standalone (CLI)"}`);
13350
16025
  printer_default.print(` IPC: v${daemonIpcVersion(info)}`);
13351
16026
  if (!isIpcCompatible(info)) {
13352
16027
  printer_default.print(import_picocolors10.default.yellow(` Warning: ${ipcMismatchMessage(info)}`));
@@ -13624,7 +16299,7 @@ function newestLogFile(q) {
13624
16299
  const nameMatch = parsed.name !== void 0 && parsed.name === q;
13625
16300
  const idMatch = parsed.tunnelId !== void 0 && (parsed.tunnelId === q || parsed.tunnelId.startsWith(q));
13626
16301
  if (nameMatch || idMatch) {
13627
- const filePath = import_node_path10.default.join(logDir, file);
16302
+ const filePath = import_node_path11.default.join(logDir, file);
13628
16303
  matches.push({ ...parsed, path: filePath, mtime: import_node_fs14.default.statSync(filePath).mtimeMs });
13629
16304
  }
13630
16305
  }
@@ -13644,13 +16319,13 @@ function resolveStoppedLogPath(q) {
13644
16319
  }
13645
16320
  return { status: "not-found" };
13646
16321
  }
13647
- var import_node_fs14, import_node_path10, TUNNEL_ORIGINS, UUID_RE;
16322
+ var import_node_fs14, import_node_path11, TUNNEL_ORIGINS, UUID_RE;
13648
16323
  var init_logPaths = __esm({
13649
16324
  "src/daemon/logPaths.ts"() {
13650
16325
  "use strict";
13651
16326
  init_cjs_shims();
13652
16327
  import_node_fs14 = __toESM(require("fs"), 1);
13653
- import_node_path10 = __toESM(require("path"), 1);
16328
+ import_node_path11 = __toESM(require("path"), 1);
13654
16329
  init_configStore();
13655
16330
  init_configDir();
13656
16331
  TUNNEL_ORIGINS = ["app", "cli", "remote", "device"];
@@ -14068,7 +16743,7 @@ function resolveConnectTarget(flagToken, environmentToken, manage, stored) {
14068
16743
  }
14069
16744
  return null;
14070
16745
  }
14071
- async function handleDevice(args, background = machineBackgroundAgentDependencies()) {
16746
+ async function handleDevice(args, background = machineBackgroundAgentDependencies(), fileAccess = machineFileAccessDependencies()) {
14072
16747
  const environmentToken = takeEnvironmentToken();
14073
16748
  if (args.length === 0) {
14074
16749
  printDeviceHelp();
@@ -14083,19 +16758,28 @@ async function handleDevice(args, background = machineBackgroundAgentDependencie
14083
16758
  process.exit(1);
14084
16759
  }
14085
16760
  const inBackground = !values.foreground;
16761
+ const fileManager = parseFilesFlag(values.files);
16762
+ if (fileManager === null) {
16763
+ printer_default.error(INVALID_FILES_FLAG_MESSAGE);
16764
+ process.exit(1);
16765
+ }
14086
16766
  switch (verb) {
14087
16767
  case DeviceVerb.Login:
14088
- exitUnlessOk(await handleDeviceLogin(values.manage, values.name, inBackground, background));
16768
+ exitUnlessOk(await handleDeviceLogin(
16769
+ { manage: values.manage, name: values.name, fileManager },
16770
+ inBackground,
16771
+ background
16772
+ ));
14089
16773
  return;
14090
16774
  case DeviceVerb.Connect:
14091
16775
  case DeviceVerb.Start:
14092
- exitUnlessOk(await handleDeviceConnect(
14093
- values.token,
16776
+ exitUnlessOk(await handleDeviceConnect({
16777
+ flagToken: values.token,
14094
16778
  environmentToken,
14095
- values.manage,
16779
+ manage: values.manage,
14096
16780
  inBackground,
14097
- background
14098
- ));
16781
+ fileManager
16782
+ }, background, fileAccess));
14099
16783
  return;
14100
16784
  case DeviceVerb.Stop:
14101
16785
  exitUnlessOk(await stopAgentInBackground(background));
@@ -14148,29 +16832,38 @@ function mayRunInBackground(background) {
14148
16832
  }
14149
16833
  return true;
14150
16834
  }
14151
- async function handleDeviceLogin(manage, name, inBackground, background) {
16835
+ async function handleDeviceLogin(options, inBackground, background) {
14152
16836
  if (!inBackground) {
14153
16837
  if (!await mayRunInForeground(background)) return EXIT_FAILED;
14154
- return runDeviceLogin({ manage, name });
16838
+ return runDeviceLogin(options);
14155
16839
  }
14156
16840
  if (!mayRunInBackground(background)) return EXIT_FAILED;
14157
- return runDeviceLogin({ manage, name }, {
16841
+ return runDeviceLogin(options, {
14158
16842
  ...machineDeviceLoginDependencies(),
14159
16843
  runAgent: (token, agentManage, signInShown) => startAgentInBackground({ token, manage: agentManage }, background, { signInShown })
14160
16844
  });
14161
16845
  }
14162
- async function handleDeviceConnect(flagToken, environmentToken, manage, inBackground, background) {
14163
- const target = resolveConnectTarget(flagToken, environmentToken, manage, background.readIdentity());
16846
+ async function handleDeviceConnect(request2, background, fileAccess) {
16847
+ const stored = background.readIdentity();
16848
+ const target = resolveConnectTarget(request2.flagToken, request2.environmentToken, request2.manage, stored);
14164
16849
  if (!target) {
14165
16850
  printer_default.error("This machine is not enrolled. Sign it in with your email:\n pinggy device login\nOr add a device in the dashboard, then run:\n pinggy device connect --token <TOKEN>");
14166
16851
  return EXIT_FAILED;
14167
16852
  }
14168
- if (inBackground) {
14169
- if (!mayRunInBackground(background)) return EXIT_FAILED;
14170
- return startAgentInBackground(target, background);
16853
+ const mayRun = request2.inBackground ? mayRunInBackground(background) : await mayRunInForeground(background);
16854
+ if (!mayRun) return EXIT_FAILED;
16855
+ let fileManager;
16856
+ try {
16857
+ fileManager = await settleFileAccess(request2.fileManager, target.token, stored, fileAccess);
16858
+ } catch (err) {
16859
+ if (!isCtrlCAtPrompt(err)) throw err;
16860
+ fileAccess.print(import_picocolors14.default.yellow("Cancelled. Nothing changed."));
16861
+ return EXIT_FAILED;
16862
+ }
16863
+ if (request2.inBackground) {
16864
+ return startAgentInBackground(target, background, { fileManager });
14171
16865
  }
14172
- if (!await mayRunInForeground(background)) return EXIT_FAILED;
14173
- await runDeviceAgent(target.token, target.manage);
16866
+ await runDeviceAgent(target.token, target.manage, { fileManager });
14174
16867
  return EXIT_OK;
14175
16868
  }
14176
16869
  async function handleDeviceStatus(background) {
@@ -14188,6 +16881,7 @@ async function handleDeviceStatus(background) {
14188
16881
  printer_default.print(` Token ${maskToken(identity.token)}`);
14189
16882
  printer_default.print(` Enrolled ${identity.enrolled_at ?? import_picocolors14.default.gray("never")}`);
14190
16883
  printer_default.print(` Autostart ${background.hasSavedAgent() ? "on, starts with the daemon" : import_picocolors14.default.gray("off")}`);
16884
+ printer_default.print(` Files ${describeFileAccess(identity)}`);
14191
16885
  if (foreground) {
14192
16886
  printer_default.print(` Foreground running in another terminal, PID ${foreground.pid}`);
14193
16887
  }
@@ -14210,6 +16904,8 @@ var init_deviceCommand = __esm({
14210
16904
  init_backgroundAgent();
14211
16905
  init_foregroundAgent();
14212
16906
  init_removeDevice();
16907
+ init_fileAccess();
16908
+ init_prompts();
14213
16909
  DeviceVerb = {
14214
16910
  Login: "login",
14215
16911
  Connect: "connect",
@@ -15032,7 +17728,7 @@ async function main() {
15032
17728
  await runUpdateChild2();
15033
17729
  process.exit(0);
15034
17730
  }
15035
- if (isPackagedBinary() && (0, import_os10.platform)() === "win32") removeStaleUpdateFiles();
17731
+ if (isPackagedBinary() && (0, import_os12.platform)() === "win32") removeStaleUpdateFiles();
15036
17732
  const { questionShown } = await offerSelfInstall({ rawArgs, values });
15037
17733
  startBackgroundUpdate({ rawArgs, values, hasAnyArgs, installQuestionShown: questionShown });
15038
17734
  if (isSubcommand(rawArgs)) {
@@ -15041,7 +17737,7 @@ async function main() {
15041
17737
  }
15042
17738
  if (!hasAnyArgs || values.help) {
15043
17739
  printHelpMessage();
15044
- if (questionShown && !hasAnyArgs && (0, import_os10.platform)() === "win32") await waitForEnterToClose();
17740
+ if (questionShown && !hasAnyArgs && (0, import_os12.platform)() === "win32") await waitForEnterToClose();
15045
17741
  return;
15046
17742
  }
15047
17743
  if (values.version) {
@@ -15054,7 +17750,7 @@ async function main() {
15054
17750
  printer_default.fatal(error);
15055
17751
  }
15056
17752
  }
15057
- var import_url2, import_process, import_os10, import_fs14, currentFile, entryFile;
17753
+ var import_url2, import_process, import_os12, import_fs16, currentFile, entryFile;
15058
17754
  var init_main = __esm({
15059
17755
  "src/main.ts"() {
15060
17756
  "use strict";
@@ -15073,8 +17769,8 @@ var init_main = __esm({
15073
17769
  init_handler();
15074
17770
  import_url2 = require("url");
15075
17771
  import_process = require("process");
15076
- import_os10 = require("os");
15077
- import_fs14 = require("fs");
17772
+ import_os12 = require("os");
17773
+ import_fs16 = require("fs");
15078
17774
  init_remoteManagement();
15079
17775
  init_buildAndStartTunnel();
15080
17776
  init_subcommands();
@@ -15084,7 +17780,7 @@ var init_main = __esm({
15084
17780
  currentFile = (0, import_url2.fileURLToPath)(importMetaUrl);
15085
17781
  entryFile = null;
15086
17782
  try {
15087
- entryFile = import_process.argv[1] ? (0, import_fs14.realpathSync)(import_process.argv[1]) : null;
17783
+ entryFile = import_process.argv[1] ? (0, import_fs16.realpathSync)(import_process.argv[1]) : null;
15088
17784
  } catch (e) {
15089
17785
  entryFile = null;
15090
17786
  }
@@ -15126,7 +17822,7 @@ var init_wsProtocol = __esm({
15126
17822
 
15127
17823
  // src/daemon/lifecycle/stateStore.ts
15128
17824
  function getStatePath() {
15129
- return import_node_path11.default.join(getPinggyConfigDir(), STATE_FILENAME);
17825
+ return import_node_path12.default.join(getPinggyConfigDir(), STATE_FILENAME);
15130
17826
  }
15131
17827
  function loadDaemonState() {
15132
17828
  const statePath = getStatePath();
@@ -15168,13 +17864,17 @@ function addTunnelToState(state, tunnel) {
15168
17864
  function removeTunnelFromState(state, tunnelId) {
15169
17865
  state.tunnels = state.tunnels.filter((t) => t.tunnelId !== tunnelId);
15170
17866
  }
15171
- var import_node_fs18, import_node_path11, STATE_FILENAME;
17867
+ function restorableTunnelCount() {
17868
+ const state = loadDaemonState();
17869
+ return state ? state.tunnels.filter((t) => t.mode === "detached").length : 0;
17870
+ }
17871
+ var import_node_fs18, import_node_path12, STATE_FILENAME;
15172
17872
  var init_stateStore = __esm({
15173
17873
  "src/daemon/lifecycle/stateStore.ts"() {
15174
17874
  "use strict";
15175
17875
  init_cjs_shims();
15176
17876
  import_node_fs18 = __toESM(require("fs"), 1);
15177
- import_node_path11 = __toESM(require("path"), 1);
17877
+ import_node_path12 = __toESM(require("path"), 1);
15178
17878
  init_configDir();
15179
17879
  init_logger();
15180
17880
  init_util();
@@ -15193,14 +17893,14 @@ function parseBody(method, body) {
15193
17893
  if (!body) return {};
15194
17894
  return JSON.parse(body);
15195
17895
  }
15196
- var import_node_http3, import_node_fs19, import_node_path12, import_ws4, IPCServer;
17896
+ var import_node_http3, import_node_fs19, import_node_path13, import_ws4, IPCServer;
15197
17897
  var init_ipcServer = __esm({
15198
17898
  "src/daemon/ipc/ipcServer.ts"() {
15199
17899
  "use strict";
15200
17900
  init_cjs_shims();
15201
17901
  import_node_http3 = __toESM(require("http"), 1);
15202
17902
  import_node_fs19 = __toESM(require("fs"), 1);
15203
- import_node_path12 = __toESM(require("path"), 1);
17903
+ import_node_path13 = __toESM(require("path"), 1);
15204
17904
  import_ws4 = require("ws");
15205
17905
  init_main();
15206
17906
  init_logger();
@@ -15363,7 +18063,7 @@ var init_ipcServer = __esm({
15363
18063
  if (n) activeNames.add(n);
15364
18064
  }
15365
18065
  for (const file of files) {
15366
- const filePath = import_node_path12.default.join(logDir, file);
18066
+ const filePath = import_node_path13.default.join(logDir, file);
15367
18067
  const stat = import_node_fs19.default.statSync(filePath);
15368
18068
  const parsed = parseTunnelLogFilename(file);
15369
18069
  if (!parsed) continue;
@@ -15387,7 +18087,7 @@ var init_ipcServer = __esm({
15387
18087
  [Route.Shutdown]: () => {
15388
18088
  logger.info("Daemon shutdown requested via IPC");
15389
18089
  if (getDaemonHost() === DaemonHost.APP) {
15390
- logger.info("Shutdown refused: daemon is hosted in-process by the Pinggy app");
18090
+ logger.info("Shutdown refused: the Pinggy app owns this daemon");
15391
18091
  return { status: ShutdownStatus.RefusedInApp, errors: [] };
15392
18092
  }
15393
18093
  const errors = [];
@@ -16106,8 +18806,10 @@ var init_daemonLock = __esm({
16106
18806
  var daemonChild_exports = {};
16107
18807
  __export(daemonChild_exports, {
16108
18808
  DaemonHost: () => DaemonHost,
18809
+ DaemonLockHeldError: () => DaemonLockHeldError,
16109
18810
  getDaemonHost: () => getDaemonHost,
16110
18811
  removeDaemonInfo: () => removeDaemonInfo,
18812
+ restoreCrashedTunnels: () => restoreCrashedTunnels,
16111
18813
  runDaemonChild: () => runDaemonChild,
16112
18814
  setDaemonSessionTracker: () => setDaemonSessionTracker,
16113
18815
  trackIPCTunnelStart: () => trackIPCTunnelStart,
@@ -16189,6 +18891,13 @@ function trackIPCTunnelStart(tunnelId, origin, mode = SessionMode.Detached) {
16189
18891
  SessionMode.Detached
16190
18892
  );
16191
18893
  }
18894
+ function stoppedWhileStarting(manager, tunnelId) {
18895
+ try {
18896
+ return manager.getManagedTunnel("", tunnelId).isStopped === true;
18897
+ } catch {
18898
+ return true;
18899
+ }
18900
+ }
16192
18901
  async function startSavedTunnel(saved, manager) {
16193
18902
  const config = {
16194
18903
  ...saved.tunnelConfig,
@@ -16201,6 +18910,10 @@ async function startSavedTunnel(saved, manager) {
16201
18910
  };
16202
18911
  const tunnel = await manager.createTunnel(config, "cli");
16203
18912
  await manager.startTunnel(tunnel.tunnelid);
18913
+ if (stoppedWhileStarting(manager, tunnel.tunnelid)) {
18914
+ logger.info(`Tunnel "${saved.name}" was stopped while it started`, { tunnelId: tunnel.tunnelid });
18915
+ return;
18916
+ }
16204
18917
  const urls = await manager.getTunnelUrls(tunnel.tunnelid);
16205
18918
  logger.info(`Tunnel "${saved.name}" started`, { tunnelId: tunnel.tunnelid, urls });
16206
18919
  trackTunnelStart(tunnel.tunnelid, saved.configId, saved.name, "cli", saved.tunnelConfig, SessionMode.Detached);
@@ -16217,50 +18930,67 @@ async function startSavedTunnel(saved, manager) {
16217
18930
  logger.error(`[${saved.name}] Reconnection failed after ${retryCnt} attempts`);
16218
18931
  });
16219
18932
  }
18933
+ function newestPerConfig(entries) {
18934
+ const newest = /* @__PURE__ */ new Map();
18935
+ for (const entry of entries) {
18936
+ const seen = newest.get(entry.configId);
18937
+ if (!seen || entry.startedAt >= seen.startedAt) newest.set(entry.configId, entry);
18938
+ }
18939
+ return entries.filter((entry) => newest.get(entry.configId) === entry);
18940
+ }
18941
+ async function restoreTunnel(manager, entry) {
18942
+ try {
18943
+ const config = {
18944
+ ...entry.config,
18945
+ configId: entry.configId,
18946
+ name: entry.name,
18947
+ tunnelid: entry.tunnelId,
18948
+ // reuse stable ID for log file continuity
18949
+ optional: {
18950
+ ...entry.config.optional,
18951
+ noTui: true
18952
+ }
18953
+ };
18954
+ const tunnel = await manager.createTunnel(config, entry.origin);
18955
+ await manager.startTunnel(tunnel.tunnelid);
18956
+ if (stoppedWhileStarting(manager, tunnel.tunnelid)) {
18957
+ logger.info(`Tunnel "${entry.name}" was stopped while it was restored`, { tunnelId: tunnel.tunnelid });
18958
+ return;
18959
+ }
18960
+ const urls = await manager.getTunnelUrls(tunnel.tunnelid);
18961
+ logger.info(`Restored tunnel "${entry.name}"`, { tunnelId: tunnel.tunnelid, urls });
18962
+ trackTunnelStart(tunnel.tunnelid, entry.configId, entry.name, entry.origin, entry.config, SessionMode.Detached);
18963
+ await manager.registerWorkerErrorListner(tunnel.tunnelid, (_id, error) => {
18964
+ logger.error(`[${entry.name}] Fatal error: ${error.message}`);
18965
+ });
18966
+ await manager.registerReconnectingListener(tunnel.tunnelid, (_id, retryCnt) => {
18967
+ logger.info(`[${entry.name}] Reconnecting (attempt #${retryCnt})`);
18968
+ });
18969
+ await manager.registerReconnectionCompletedListener(tunnel.tunnelid, (_id, newUrls) => {
18970
+ logger.info(`[${entry.name}] Reconnected`, { urls: newUrls });
18971
+ });
18972
+ await manager.registerReconnectionFailedListener(tunnel.tunnelid, (_id, retryCnt) => {
18973
+ logger.error(`[${entry.name}] Reconnection failed after ${retryCnt} attempts`);
18974
+ });
18975
+ } catch (err) {
18976
+ logger.error(`Failed to restore tunnel "${entry.name}"`, { error: errorMessage(err) });
18977
+ removeTunnelFromState(daemonState, entry.tunnelId);
18978
+ persistDaemonState(daemonState);
18979
+ }
18980
+ }
16220
18981
  async function restoreCrashedTunnels(manager) {
16221
18982
  const savedState = loadDaemonState();
16222
18983
  if (!savedState || savedState.tunnels.length === 0) return;
16223
- const detachedTunnels = savedState.tunnels.filter((t) => t.mode === "detached");
18984
+ const detachedTunnels = newestPerConfig(savedState.tunnels.filter((t) => t.mode === "detached"));
16224
18985
  if (detachedTunnels.length === 0) {
16225
18986
  logger.info("Crash recovery: no detached tunnels to restore");
16226
18987
  clearDaemonState();
16227
18988
  return;
16228
18989
  }
16229
18990
  logger.info(`Crash recovery: restoring ${detachedTunnels.length} detached tunnel(s)`);
16230
- for (const entry of detachedTunnels) {
16231
- try {
16232
- const config = {
16233
- ...entry.config,
16234
- configId: entry.configId,
16235
- name: entry.name,
16236
- tunnelid: entry.tunnelId,
16237
- // reuse stable ID for log file continuity
16238
- optional: {
16239
- ...entry.config.optional,
16240
- noTui: true
16241
- }
16242
- };
16243
- const tunnel = await manager.createTunnel(config, entry.origin);
16244
- await manager.startTunnel(tunnel.tunnelid);
16245
- const urls = await manager.getTunnelUrls(tunnel.tunnelid);
16246
- logger.info(`Restored tunnel "${entry.name}"`, { tunnelId: tunnel.tunnelid, urls });
16247
- trackTunnelStart(tunnel.tunnelid, entry.configId, entry.name, entry.origin, entry.config, SessionMode.Detached);
16248
- await manager.registerWorkerErrorListner(tunnel.tunnelid, (_id, error) => {
16249
- logger.error(`[${entry.name}] Fatal error: ${error.message}`);
16250
- });
16251
- await manager.registerReconnectingListener(tunnel.tunnelid, (_id, retryCnt) => {
16252
- logger.info(`[${entry.name}] Reconnecting (attempt #${retryCnt})`);
16253
- });
16254
- await manager.registerReconnectionCompletedListener(tunnel.tunnelid, (_id, newUrls) => {
16255
- logger.info(`[${entry.name}] Reconnected`, { urls: newUrls });
16256
- });
16257
- await manager.registerReconnectionFailedListener(tunnel.tunnelid, (_id, retryCnt) => {
16258
- logger.error(`[${entry.name}] Reconnection failed after ${retryCnt} attempts`);
16259
- });
16260
- } catch (err) {
16261
- logger.error(`Failed to restore tunnel "${entry.name}"`, { error: errorMessage(err) });
16262
- }
16263
- }
18991
+ daemonState = { tunnels: [...detachedTunnels], lastUpdated: "" };
18992
+ persistDaemonState(daemonState);
18993
+ await Promise.all(detachedTunnels.map((entry) => restoreTunnel(manager, entry)));
16264
18994
  }
16265
18995
  async function runDaemonChild(opts = {}) {
16266
18996
  const installSignalHandlers = opts.installSignalHandlers ?? true;
@@ -16281,7 +19011,7 @@ async function runDaemonChild(opts = {}) {
16281
19011
  if (!acquireDaemonLock()) {
16282
19012
  logger.info("Another daemon holds daemon.lock. Exiting.");
16283
19013
  if (exitOnFailure) process.exit(0);
16284
- throw new Error("Another pinggy daemon is running.");
19014
+ throw new DaemonLockHeldError();
16285
19015
  }
16286
19016
  const manager = TunnelManager.getInstance();
16287
19017
  const ipcServer = new IPCServer();
@@ -16340,7 +19070,6 @@ async function runDaemonChild(opts = {}) {
16340
19070
  cleanup();
16341
19071
  process.exit(0);
16342
19072
  });
16343
- process.on("exit", cleanup);
16344
19073
  process.on("uncaughtException", (err) => {
16345
19074
  logger.error("Daemon uncaught exception", { error: err.message, stack: err.stack });
16346
19075
  });
@@ -16367,16 +19096,18 @@ async function runDaemonChild(opts = {}) {
16367
19096
  writeDaemonInfo(info);
16368
19097
  logger.info("Daemon info written", info);
16369
19098
  await restoreCrashedTunnels(manager);
16370
- const configs = getAutoStartConfigs();
16371
- if (configs.length > 0) {
19099
+ const configs = opts.skipAutoStart ? [] : getAutoStartConfigs();
19100
+ if (opts.skipAutoStart) {
19101
+ logger.info("Auto-start tunnels skipped: the host restarted this daemon");
19102
+ } else if (configs.length > 0) {
16372
19103
  logger.info(`Starting ${configs.length} auto-start tunnel(s)`);
16373
- for (const saved of configs) {
19104
+ await Promise.all(configs.map(async (saved) => {
16374
19105
  try {
16375
19106
  await startSavedTunnel(saved, manager);
16376
19107
  } catch (err) {
16377
19108
  logger.error(`Failed to start tunnel "${saved.name}"`, { error: errorMessage(err) });
16378
19109
  }
16379
- }
19110
+ }));
16380
19111
  } else {
16381
19112
  logger.info("No auto-start tunnels configured");
16382
19113
  }
@@ -16384,6 +19115,7 @@ async function runDaemonChild(opts = {}) {
16384
19115
  if (savedAgent) {
16385
19116
  await startSavedDeviceAgent(deviceAgentHost, savedAgent);
16386
19117
  }
19118
+ if (installSignalHandlers) process.on("exit", cleanup);
16387
19119
  logger.info("Daemon ready", { pid: process.pid, port });
16388
19120
  return {
16389
19121
  pid: process.pid,
@@ -16400,7 +19132,7 @@ async function runDaemonChild(opts = {}) {
16400
19132
  throw err;
16401
19133
  }
16402
19134
  }
16403
- var import_node_fs21, daemonState, daemonHost, sessionTrackerRef;
19135
+ var import_node_fs21, DaemonLockHeldError, daemonState, daemonHost, sessionTrackerRef;
16404
19136
  var init_daemonChild = __esm({
16405
19137
  "src/daemon/lifecycle/daemonChild.ts"() {
16406
19138
  "use strict";
@@ -16422,6 +19154,12 @@ var init_daemonChild = __esm({
16422
19154
  init_ipcRoutes();
16423
19155
  init_daemonLock();
16424
19156
  init_bootId();
19157
+ DaemonLockHeldError = class extends Error {
19158
+ constructor() {
19159
+ super("Another pinggy daemon is running.");
19160
+ this.name = "DaemonLockHeldError";
19161
+ }
19162
+ };
16425
19163
  daemonState = { tunnels: [], lastUpdated: "" };
16426
19164
  daemonHost = DaemonHost.CLI;
16427
19165
  sessionTrackerRef = null;
@@ -16429,6 +19167,9 @@ var init_daemonChild = __esm({
16429
19167
  });
16430
19168
 
16431
19169
  // src/daemon/lifecycle/daemonManager.ts
19170
+ function setDaemonLauncher(launcher) {
19171
+ daemonLauncher = launcher;
19172
+ }
16432
19173
  function isProcessAlive(pid) {
16433
19174
  try {
16434
19175
  process.kill(pid, 0);
@@ -16545,6 +19286,13 @@ async function ensureDaemonRunning() {
16545
19286
  if (!isIpcCompatible(existing)) throw new Error(ipcMismatchMessage(existing));
16546
19287
  return existing;
16547
19288
  }
19289
+ if (daemonLauncher) {
19290
+ await daemonLauncher();
19291
+ const info = await pollForDaemonInfo(DAEMON_SPAWN_TIMEOUT_MS);
19292
+ if (!info) throw new Error(`Daemon failed to start. Check ${getDaemonLogPath()} for details.`);
19293
+ if (!isIpcCompatible(info)) throw new Error(ipcMismatchMessage(info));
19294
+ return info;
19295
+ }
16548
19296
  if (process.versions.electron) {
16549
19297
  const { runDaemonChild: runDaemonChild2 } = await Promise.resolve().then(() => (init_daemonChild(), daemonChild_exports));
16550
19298
  const handle = await runDaemonChild2({
@@ -16566,6 +19314,15 @@ async function ensureDaemonRunning() {
16566
19314
  function getInProcessDaemonHandle() {
16567
19315
  return inProcessHandle;
16568
19316
  }
19317
+ function removeDeadDaemonFiles(pid) {
19318
+ for (const filePath of [getDaemonInfoPath(), getDaemonLockPath()]) {
19319
+ try {
19320
+ const record = JSON.parse(import_node_fs22.default.readFileSync(filePath, "utf-8"));
19321
+ if (record.pid === pid) import_node_fs22.default.rmSync(filePath, { force: true });
19322
+ } catch {
19323
+ }
19324
+ }
19325
+ }
16569
19326
  async function getActiveTunnelSummaries(origin = "app") {
16570
19327
  const info = getDaemonInfo();
16571
19328
  if (!info) return [];
@@ -16649,7 +19406,7 @@ async function waitForExit2(pid, timeoutMs) {
16649
19406
  }
16650
19407
  return !isProcessAlive(pid);
16651
19408
  }
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;
19409
+ var import_node_os7, import_node_fs22, import_node_child_process6, inProcessHandle, daemonLauncher, DAEMON_SPAWN_TIMEOUT_MS, DAEMON_POLL_INTERVAL_MS, SPAWN_FAILED_EXIT_CODE, DAEMON_STOP_INSTRUCTION, installedBinaryForDaemon;
16653
19410
  var init_daemonManager = __esm({
16654
19411
  "src/daemon/lifecycle/daemonManager.ts"() {
16655
19412
  "use strict";
@@ -16669,6 +19426,7 @@ var init_daemonManager = __esm({
16669
19426
  init_installKind();
16670
19427
  init_bootId();
16671
19428
  inProcessHandle = null;
19429
+ daemonLauncher = null;
16672
19430
  DAEMON_SPAWN_TIMEOUT_MS = 8e3;
16673
19431
  DAEMON_POLL_INTERVAL_MS = 200;
16674
19432
  SPAWN_FAILED_EXIT_CODE = -1;
@@ -16713,6 +19471,10 @@ var init_wsStream = __esm({
16713
19471
  // Lifecycle
16714
19472
  async ensureOpen() {
16715
19473
  if (this.ws && this.ws.readyState === import_ws5.WebSocket.OPEN) return;
19474
+ if (this.ws && this.ws.readyState === import_ws5.WebSocket.CONNECTING && this.wsReady) {
19475
+ await this.wsReady;
19476
+ return;
19477
+ }
16716
19478
  this.wsReady = new Promise((resolve) => {
16717
19479
  this.wsResolve = resolve;
16718
19480
  });
@@ -16731,10 +19493,13 @@ var init_wsStream = __esm({
16731
19493
  }
16732
19494
  });
16733
19495
  this.ws.on("message", (data) => this.handleMessage(data.toString()));
19496
+ const socket = this.ws;
16734
19497
  this.ws.on("close", (code) => {
16735
- this.ws = null;
16736
- this.wsReady = null;
16737
- this.wsResolve = null;
19498
+ if (this.ws === socket) {
19499
+ this.ws = null;
19500
+ this.wsReady = null;
19501
+ this.wsResolve = null;
19502
+ }
16738
19503
  for (const cb of this.closeListeners) {
16739
19504
  try {
16740
19505
  cb(code);
@@ -16760,12 +19525,19 @@ var init_wsStream = __esm({
16760
19525
  this.wsResolve = null;
16761
19526
  this.subscribedTunnels.clear();
16762
19527
  }
16763
- /** Hard kill the socket. Use when daemon is known dead. */
19528
+ /**
19529
+ * Hard kill the socket. Use when daemon is known dead.
19530
+ *
19531
+ * The subscriptions are dropped even when the socket is already gone. A daemon that dies closes
19532
+ * the socket first, and subscriptions left here made a later subscribe() on a new daemon send
19533
+ * nothing.
19534
+ */
16764
19535
  terminate() {
16765
- if (!this.ws) return;
16766
- try {
16767
- this.ws.terminate();
16768
- } catch {
19536
+ if (this.ws) {
19537
+ try {
19538
+ this.ws.terminate();
19539
+ } catch {
19540
+ }
16769
19541
  }
16770
19542
  this.ws = null;
16771
19543
  this.wsReady = null;
@@ -17136,10 +19908,23 @@ var init_tunnelClient = __esm({
17136
19908
  return true;
17137
19909
  }
17138
19910
  bindDaemon(info) {
19911
+ const wasLost = this.health.isLost();
17139
19912
  this.boundDaemon = info;
17140
19913
  this.ipc = new IPCClient(info.port, this.origin);
17141
19914
  this.health.bindPid(info.pid);
17142
19915
  this.health.reset();
19916
+ if (wasLost) this.resubscribeShimListeners();
19917
+ }
19918
+ /**
19919
+ * Daemon loss drops every stream subscription, and a shim listener subscribes only when it is
19920
+ * registered. Without this, listeners registered before the loss stay silent on the new daemon.
19921
+ * A daemon restarted after a crash restores its tunnels under the same tunnel ids.
19922
+ */
19923
+ resubscribeShimListeners() {
19924
+ const tunnelIds = /* @__PURE__ */ new Set();
19925
+ for (const entry of this.shimStatsListeners.values()) tunnelIds.add(entry.tunnelId);
19926
+ for (const entry of this.shimDisconnectListeners.values()) tunnelIds.add(entry.tunnelId);
19927
+ for (const tunnelId of tunnelIds) this.subscribeForShim(tunnelId);
17143
19928
  }
17144
19929
  static async forRemoteManagement() {
17145
19930
  const client = new _TunnelClient({ origin: "remote" });
@@ -17411,6 +20196,8 @@ var init_tunnelClient = __esm({
17411
20196
  // src/index.ts
17412
20197
  var index_exports = {};
17413
20198
  __export(index_exports, {
20199
+ DaemonHost: () => DaemonHost,
20200
+ DaemonLockHeldError: () => DaemonLockHeldError,
17414
20201
  DeviceAgentState: () => DeviceAgentState,
17415
20202
  RemoteManagementUnauthorizedError: () => RemoteManagementUnauthorizedError,
17416
20203
  TUNNEL_CONFIG_V1_KEYS: () => TUNNEL_CONFIG_V1_KEYS,
@@ -17422,6 +20209,7 @@ __export(index_exports, {
17422
20209
  TunnelStateType: () => TunnelStateType,
17423
20210
  TunnelWarningCode: () => TunnelWarningCode,
17424
20211
  bulkReplace: () => bulkReplace,
20212
+ clearDaemonState: () => clearDaemonState,
17425
20213
  closeRemoteManagement: () => closeRemoteManagement,
17426
20214
  configureStorageLogger: () => configureStorageLogger,
17427
20215
  deleteConfig: () => deleteConfig,
@@ -17439,8 +20227,12 @@ __export(index_exports, {
17439
20227
  isDaemonRunning: () => isDaemonRunning,
17440
20228
  listSavedConfigs: () => listSavedConfigs,
17441
20229
  loadConfigByName: () => loadConfigByName,
20230
+ removeDeadDaemonFiles: () => removeDeadDaemonFiles,
20231
+ restorableTunnelCount: () => restorableTunnelCount,
20232
+ runDaemonChild: () => runDaemonChild,
17442
20233
  sanitizeName: () => sanitizeName,
17443
20234
  saveConfig: () => saveConfig,
20235
+ setDaemonLauncher: () => setDaemonLauncher,
17444
20236
  startRemoteManagement: () => startRemoteManagement,
17445
20237
  updateConfigAutoStart: () => updateConfigAutoStart,
17446
20238
  updateTunnelConfig: () => updateTunnelConfig,
@@ -17538,6 +20330,9 @@ init_TunnelManager();
17538
20330
  init_handler();
17539
20331
  init_tunnelClient();
17540
20332
  init_daemonManager();
20333
+ init_daemonChild();
20334
+ init_stateStore();
20335
+ init_ipcRoutes();
17541
20336
  init_ipcRoutes();
17542
20337
  init_logger();
17543
20338
  init_remoteManagement();
@@ -17563,6 +20358,8 @@ verifyAndLoad().catch((err) => {
17563
20358
  });
17564
20359
  // Annotate the CommonJS export names for ESM import in node:
17565
20360
  0 && (module.exports = {
20361
+ DaemonHost,
20362
+ DaemonLockHeldError,
17566
20363
  DeviceAgentState,
17567
20364
  RemoteManagementUnauthorizedError,
17568
20365
  TUNNEL_CONFIG_V1_KEYS,
@@ -17574,6 +20371,7 @@ verifyAndLoad().catch((err) => {
17574
20371
  TunnelStateType,
17575
20372
  TunnelWarningCode,
17576
20373
  bulkReplace,
20374
+ clearDaemonState,
17577
20375
  closeRemoteManagement,
17578
20376
  configureStorageLogger,
17579
20377
  deleteConfig,
@@ -17591,8 +20389,12 @@ verifyAndLoad().catch((err) => {
17591
20389
  isDaemonRunning,
17592
20390
  listSavedConfigs,
17593
20391
  loadConfigByName,
20392
+ removeDeadDaemonFiles,
20393
+ restorableTunnelCount,
20394
+ runDaemonChild,
17594
20395
  sanitizeName,
17595
20396
  saveConfig,
20397
+ setDaemonLauncher,
17596
20398
  startRemoteManagement,
17597
20399
  updateConfigAutoStart,
17598
20400
  updateTunnelConfig,