@dev-anywhere/proxy 0.9.6 → 0.9.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +8 -1
  2. package/dist/autostart-6DMQS43N.js +864 -0
  3. package/dist/autostart-6DMQS43N.js.map +1 -0
  4. package/dist/chunk-3NUN2VYO.js +46 -0
  5. package/dist/chunk-3NUN2VYO.js.map +1 -0
  6. package/dist/{chunk-C2VZS676.js → chunk-3ZDUDCEI.js} +2 -2
  7. package/dist/{chunk-7FPUPHTZ.js → chunk-5KXGIGKU.js} +9 -2
  8. package/dist/chunk-5KXGIGKU.js.map +1 -0
  9. package/dist/{chunk-LAFXAGDU.js → chunk-5RESCDN4.js} +2 -2
  10. package/dist/{chunk-DEMLXEB5.js → chunk-7EOSTWVO.js} +3 -3
  11. package/dist/{chunk-PCF2R2TG.js → chunk-AS7W2D2X.js} +2 -2
  12. package/dist/{chunk-PCF2R2TG.js.map → chunk-AS7W2D2X.js.map} +1 -1
  13. package/dist/{chunk-724Y2CKO.js → chunk-CFO5GU5U.js} +2 -43
  14. package/dist/chunk-CFO5GU5U.js.map +1 -0
  15. package/dist/{chunk-5COVSNQZ.js → chunk-CFPY2A6Q.js} +2 -2
  16. package/dist/chunk-DEL6NNYV.js +161 -0
  17. package/dist/chunk-DEL6NNYV.js.map +1 -0
  18. package/dist/{chunk-TLY6IMDY.js → chunk-DSZJSFEG.js} +42 -8
  19. package/dist/chunk-DSZJSFEG.js.map +1 -0
  20. package/dist/{chunk-SSTYQQSR.js → chunk-EWIHC4BK.js} +2 -2
  21. package/dist/{chunk-IEBAPWH3.js → chunk-HEXGO236.js} +6 -6
  22. package/dist/{chunk-TQP3COOV.js → chunk-HJOYOYGB.js} +2 -1
  23. package/dist/{chunk-EEXWF5SA.js → chunk-JRSPTWQB.js} +2 -2
  24. package/dist/{chunk-LIGQMX7K.js → chunk-MPW6H537.js} +85 -7
  25. package/dist/chunk-MPW6H537.js.map +1 -0
  26. package/dist/{chunk-UBWS5JVM.js → chunk-QZJBIFGW.js} +16 -9
  27. package/dist/chunk-QZJBIFGW.js.map +1 -0
  28. package/dist/{chunk-BUUAXCBP.js → chunk-QZNAESON.js} +2 -2
  29. package/dist/{chunk-WEATMI5J.js → chunk-SKKPJULC.js} +10 -1
  30. package/dist/chunk-SKKPJULC.js.map +1 -0
  31. package/dist/{chunk-TIXHLU3Q.js → chunk-ZE73PMOL.js} +6 -4
  32. package/dist/chunk-ZE73PMOL.js.map +1 -0
  33. package/dist/{chunk-ZRABX7EM.js → chunk-ZHG3MO4C.js} +2 -2
  34. package/dist/chunk-ZRCMGVGT.js +33 -0
  35. package/dist/chunk-ZRCMGVGT.js.map +1 -0
  36. package/dist/index.js +35 -21
  37. package/dist/index.js.map +1 -1
  38. package/dist/{logger-XEIQC6K6.js → logger-2EQWS3V2.js} +3 -3
  39. package/dist/preview-worker.js +10 -8
  40. package/dist/preview-worker.js.map +1 -1
  41. package/dist/{quick-tunnel-ZIFTYUUD.js → quick-tunnel-HA5NE7K6.js} +2 -2
  42. package/dist/{relay-token-Y3IFNUMX.js → relay-token-SK3OOH2H.js} +4 -4
  43. package/dist/serve.js +78 -20
  44. package/dist/serve.js.map +1 -1
  45. package/dist/service-host-YEX4IBZO.js +139 -0
  46. package/dist/service-host-YEX4IBZO.js.map +1 -0
  47. package/dist/session-worker.js +8 -8
  48. package/dist/{terminal-FNVKGTTL.js → terminal-H6DLED7O.js} +26 -15
  49. package/dist/terminal-H6DLED7O.js.map +1 -0
  50. package/dist/terminal-worker.js +17 -14
  51. package/dist/terminal-worker.js.map +1 -1
  52. package/dist/update-runner.js +7 -33
  53. package/dist/update-runner.js.map +1 -1
  54. package/package.json +3 -3
  55. package/dist/autostart-TMACAYHZ.js +0 -370
  56. package/dist/autostart-TMACAYHZ.js.map +0 -1
  57. package/dist/chunk-724Y2CKO.js.map +0 -1
  58. package/dist/chunk-7FPUPHTZ.js.map +0 -1
  59. package/dist/chunk-LIGQMX7K.js.map +0 -1
  60. package/dist/chunk-TIXHLU3Q.js.map +0 -1
  61. package/dist/chunk-TLY6IMDY.js.map +0 -1
  62. package/dist/chunk-UBWS5JVM.js.map +0 -1
  63. package/dist/chunk-WEATMI5J.js.map +0 -1
  64. package/dist/terminal-FNVKGTTL.js.map +0 -1
  65. /package/dist/{chunk-C2VZS676.js.map → chunk-3ZDUDCEI.js.map} +0 -0
  66. /package/dist/{chunk-LAFXAGDU.js.map → chunk-5RESCDN4.js.map} +0 -0
  67. /package/dist/{chunk-DEMLXEB5.js.map → chunk-7EOSTWVO.js.map} +0 -0
  68. /package/dist/{chunk-5COVSNQZ.js.map → chunk-CFPY2A6Q.js.map} +0 -0
  69. /package/dist/{chunk-SSTYQQSR.js.map → chunk-EWIHC4BK.js.map} +0 -0
  70. /package/dist/{chunk-IEBAPWH3.js.map → chunk-HEXGO236.js.map} +0 -0
  71. /package/dist/{chunk-TQP3COOV.js.map → chunk-HJOYOYGB.js.map} +0 -0
  72. /package/dist/{chunk-EEXWF5SA.js.map → chunk-JRSPTWQB.js.map} +0 -0
  73. /package/dist/{chunk-BUUAXCBP.js.map → chunk-QZNAESON.js.map} +0 -0
  74. /package/dist/{chunk-ZRABX7EM.js.map → chunk-ZHG3MO4C.js.map} +0 -0
  75. /package/dist/{logger-XEIQC6K6.js.map → logger-2EQWS3V2.js.map} +0 -0
  76. /package/dist/{quick-tunnel-ZIFTYUUD.js.map → quick-tunnel-HA5NE7K6.js.map} +0 -0
  77. /package/dist/{relay-token-Y3IFNUMX.js.map → relay-token-SK3OOH2H.js.map} +0 -0
@@ -0,0 +1,864 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ refreshLoginShellPath
4
+ } from "./chunk-BZWRTKXC.js";
5
+ import {
6
+ getErrorMessage
7
+ } from "./chunk-5OARBB2B.js";
8
+ import {
9
+ createProfileServiceLifecycle
10
+ } from "./chunk-MPW6H537.js";
11
+ import {
12
+ requestServiceHost
13
+ } from "./chunk-DEL6NNYV.js";
14
+ import "./chunk-AZ5MTPUR.js";
15
+ import {
16
+ IS_DEV,
17
+ resolveTopLevelScript
18
+ } from "./chunk-AS7W2D2X.js";
19
+ import "./chunk-3NUN2VYO.js";
20
+ import "./chunk-CFO5GU5U.js";
21
+ import "./chunk-77QVUYU7.js";
22
+ import "./chunk-ZRCMGVGT.js";
23
+ import {
24
+ quoteWindowsArgument
25
+ } from "./chunk-EWIHC4BK.js";
26
+ import "./chunk-HJOYOYGB.js";
27
+ import {
28
+ PROFILE_NAME,
29
+ SERVICE_HOST_PATH,
30
+ buildProxyProfilePaths,
31
+ isInitialized
32
+ } from "./chunk-SKKPJULC.js";
33
+
34
+ // src/autostart.ts
35
+ import { homedir, userInfo } from "os";
36
+ import { fileURLToPath } from "url";
37
+ import { setTimeout as sleep } from "timers/promises";
38
+
39
+ // src/common/service-autostart.ts
40
+ import { execFile } from "child_process";
41
+ import { mkdir, writeFile } from "fs/promises";
42
+ import { dirname, join, win32 as win322 } from "path";
43
+ import { promisify } from "util";
44
+
45
+ // src/common/windows-autostart-launcher.ts
46
+ import { createHash } from "crypto";
47
+ import { win32 } from "path";
48
+ function encodedString(value) {
49
+ if ([...value].some((char) => char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127)) {
50
+ throw new Error("Autostart paths and environment must not contain control characters");
51
+ }
52
+ return `Decode("${Buffer.from(value, "utf8").toString("base64")}")`;
53
+ }
54
+ function buildWindowsAutostartLauncher(options) {
55
+ const paths = buildProxyProfilePaths(options.home, options.profile, "win32");
56
+ const logPath = win32.join(paths.logDir, "autostart-launcher.log");
57
+ const source = `using System;
58
+ using System.Diagnostics;
59
+ using System.IO;
60
+ using System.Text;
61
+
62
+ internal static class DevAnywhereAutostart {
63
+ private static StreamWriter log;
64
+ private static volatile bool logFailed;
65
+ private static string Decode(string value) { return Encoding.UTF8.GetString(Convert.FromBase64String(value)); }
66
+ private static void WriteLog(string stream, string message) {
67
+ if (message == null) return;
68
+ try { lock (log) { log.WriteLine(DateTime.UtcNow.ToString("o") + " " + stream + ": " + message); } }
69
+ catch { logFailed = true; } // Keep draining output; report logging failures through the task exit code.
70
+ }
71
+ public static int Main() {
72
+ try {
73
+ string logPath = ${encodedString(logPath)};
74
+ Directory.CreateDirectory(Path.GetDirectoryName(logPath));
75
+ using (log = new StreamWriter(new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite), new UTF8Encoding(false))) {
76
+ log.AutoFlush = true;
77
+ try {
78
+ var info = new ProcessStartInfo();
79
+ info.FileName = ${encodedString(options.executable)};
80
+ info.Arguments = ${encodedString(options.args.map(quoteWindowsArgument).join(" "))};
81
+ info.WorkingDirectory = ${encodedString(options.home)};
82
+ info.EnvironmentVariables["USERPROFILE"] = ${encodedString(options.home)};
83
+ info.EnvironmentVariables["HOME"] = ${encodedString(options.home)};
84
+ info.UseShellExecute = false;
85
+ info.CreateNoWindow = true;
86
+ info.RedirectStandardInput = true;
87
+ info.RedirectStandardOutput = true;
88
+ info.RedirectStandardError = true;
89
+ info.StandardOutputEncoding = Encoding.UTF8;
90
+ info.StandardErrorEncoding = Encoding.UTF8;
91
+ using (var child = new Process()) {
92
+ child.StartInfo = info;
93
+ child.OutputDataReceived += (sender, e) => WriteLog("stdout", e.Data);
94
+ child.ErrorDataReceived += (sender, e) => WriteLog("stderr", e.Data);
95
+ child.Start();
96
+ child.StandardInput.Close();
97
+ child.BeginOutputReadLine();
98
+ child.BeginErrorReadLine();
99
+ child.WaitForExit();
100
+ return child.ExitCode != 0 ? child.ExitCode : (logFailed ? 1 : 0);
101
+ }
102
+ } catch (Exception error) { WriteLog("launcher", error.ToString()); return 1; }
103
+ }
104
+ } catch { return 1; } // An unwritable log directory is also a failed task, not a silent success.
105
+ }
106
+ }
107
+ `;
108
+ const digest = createHash("sha256").update(source).digest("hex").slice(0, 20);
109
+ const path = win32.join(paths.profileDir, "autostart", `launcher-${digest}.exe`);
110
+ const sourceBase64 = Buffer.from(source, "utf8").toString("base64");
111
+ const compileScript = `$launcherPath = '${path.replaceAll("'", "''")}';
112
+ if (!(Test-Path -LiteralPath $launcherPath -PathType Leaf)) {
113
+ [System.IO.Directory]::CreateDirectory([System.IO.Path]::GetDirectoryName($launcherPath)) | Out-Null;
114
+ $candidate = $launcherPath + '.' + [guid]::NewGuid().ToString('N') + '.tmp.exe';
115
+ try {
116
+ $source = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${sourceBase64}'));
117
+ Add-Type -TypeDefinition $source -OutputAssembly $candidate -OutputType WindowsApplication -ErrorAction Stop;
118
+ Move-Item -LiteralPath $candidate -Destination $launcherPath -ErrorAction Stop;
119
+ } finally {
120
+ if (Test-Path -LiteralPath $candidate) { Remove-Item -LiteralPath $candidate -Force; }
121
+ }
122
+ }`;
123
+ return { path, logPath, source, compileScript };
124
+ }
125
+
126
+ // src/common/autostart-definition.ts
127
+ import { createHash as createHash2 } from "crypto";
128
+ import { readFile, unlink } from "fs/promises";
129
+ function autostartLabel(home, profile) {
130
+ return `dev-anywhere-${createHash2("sha256").update(`${home}\0${profile}`).digest("hex").slice(0, 20)}`;
131
+ }
132
+ function checkAutostartText(value) {
133
+ if ([...value].some((char) => char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127)) {
134
+ throw new Error("Autostart paths and environment must not contain control characters");
135
+ }
136
+ return value;
137
+ }
138
+ function xmlString(value) {
139
+ return checkAutostartText(value).replace(
140
+ /[&<>"']/g,
141
+ (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&apos;" })[char]
142
+ );
143
+ }
144
+ function unitValue(value) {
145
+ return checkAutostartText(value).replaceAll("%", "%%");
146
+ }
147
+ function unitString(value) {
148
+ return `"${unitValue(value).replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
149
+ }
150
+ function psString(value) {
151
+ return `'${checkAutostartText(value).replaceAll("'", "''")}'`;
152
+ }
153
+ async function readIfPresent(path) {
154
+ try {
155
+ return await readFile(path, "utf8");
156
+ } catch (error) {
157
+ if (error.code === "ENOENT") return null;
158
+ throw error;
159
+ }
160
+ }
161
+ async function removeIfPresent(path) {
162
+ try {
163
+ await unlink(path);
164
+ } catch (error) {
165
+ if (error.code !== "ENOENT") throw error;
166
+ }
167
+ }
168
+
169
+ // src/common/service-autostart.ts
170
+ function encodePowerShell(script) {
171
+ return Buffer.from(script, "utf16le").toString("base64");
172
+ }
173
+ var execFileAsync = promisify(execFile);
174
+ function createServiceAutostart(options) {
175
+ const { platform, home, profile, executable, env } = options;
176
+ if (!["darwin", "linux", "win32"].includes(platform)) {
177
+ throw new Error(`Proxy autostart is not supported on ${platform}`);
178
+ }
179
+ const label = autostartLabel(home, profile);
180
+ const args = [...options.args, "--profile", profile, "serve", "autostart", "run"];
181
+ const run = options.run ?? (async (command, commandArgs) => {
182
+ const result = await execFileAsync(command, commandArgs, {
183
+ timeout: 15e3,
184
+ maxBuffer: 256 * 1024,
185
+ windowsHide: true,
186
+ encoding: "utf8"
187
+ });
188
+ return result.stdout;
189
+ });
190
+ const powershell = win322.join(
191
+ env.SystemRoot ?? env.SYSTEMROOT ?? "C:\\Windows",
192
+ "System32",
193
+ "WindowsPowerShell",
194
+ "v1.0",
195
+ "powershell.exe"
196
+ );
197
+ const runPowerShell = (script) => run(powershell, [
198
+ "-NoProfile",
199
+ "-NonInteractive",
200
+ "-EncodedCommand",
201
+ encodePowerShell(`$ErrorActionPreference = 'Stop';
202
+ ${script}`)
203
+ ]);
204
+ const taskLookup = `$task = Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskPath -eq '\\' -and $_.TaskName -eq ${psString(label)} };`;
205
+ const unit = `${label}.service`;
206
+ const filePath = platform === "darwin" ? join(home, "Library", "LaunchAgents", `${label}.plist`) : join(env.XDG_CONFIG_HOME || join(home, ".config"), "systemd", "user", unit);
207
+ const domain = `gui/${options.uid}`;
208
+ const launchdTarget = `${domain}/${label}`;
209
+ const environment = {
210
+ HOME: checkAutostartText(home),
211
+ ...Object.fromEntries(
212
+ ["PATH", "SHELL"].flatMap((key) => env[key] ? [[key, checkAutostartText(env[key])]] : [])
213
+ )
214
+ };
215
+ function definition() {
216
+ if (platform === "darwin") {
217
+ return `<?xml version="1.0" encoding="UTF-8"?>
218
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
219
+ <plist version="1.0"><dict>
220
+ <key>Label</key><string>${xmlString(label)}</string>
221
+ <key>ProgramArguments</key><array>${[executable, ...args].map((arg) => `<string>${xmlString(arg)}</string>`).join("")}</array>
222
+ <key>WorkingDirectory</key><string>${xmlString(home)}</string>
223
+ <key>EnvironmentVariables</key><dict>${Object.entries(environment).map(([key, value]) => `<key>${xmlString(key)}</key><string>${xmlString(value)}</string>`).join("")}</dict>
224
+ <key>RunAtLoad</key><true/>
225
+ <key>KeepAlive</key><false/>
226
+ </dict></plist>
227
+ `;
228
+ }
229
+ return `[Unit]
230
+ Description=DEV Anywhere Proxy (${checkAutostartText(profile)})
231
+
232
+ [Service]
233
+ Type=oneshot
234
+ RemainAfterExit=yes
235
+ Restart=no
236
+ WorkingDirectory=${unitValue(home)}
237
+ ${Object.entries(environment).map(([key, value]) => `Environment=${unitString(`${key}=${value}`)}`).join("\n")}
238
+ ExecStart=:${[executable, ...args, "--daemon"].map(unitString).join(" ")}
239
+ TimeoutStartSec=60
240
+
241
+ [Install]
242
+ WantedBy=default.target
243
+ `;
244
+ }
245
+ function windowsTask() {
246
+ const launcher = buildWindowsAutostartLauncher({ home, profile, executable, args });
247
+ return `${launcher.compileScript}
248
+ $user = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name;
249
+ $action = New-ScheduledTaskAction -Execute ${psString(launcher.path)} -WorkingDirectory ${psString(home)};
250
+ $trigger = New-ScheduledTaskTrigger -AtLogOn -User $user;
251
+ $principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited;
252
+ $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew -Priority 4;
253
+ Register-ScheduledTask -TaskPath '\\' -TaskName ${psString(label)} -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description 'DEV Anywhere Proxy: start at user login' -Force | Out-Null;`;
254
+ }
255
+ async function status() {
256
+ if (platform === "win32") {
257
+ const output2 = await runPowerShell(
258
+ `${taskLookup}
259
+ [bool]($task -and $task.Settings.Enabled) | ConvertTo-Json -Compress;`
260
+ );
261
+ const enabled = JSON.parse(output2.trim());
262
+ if (typeof enabled !== "boolean") throw new Error("Invalid Windows autostart status");
263
+ return enabled;
264
+ }
265
+ if (await readIfPresent(filePath) === null) return false;
266
+ if (platform === "darwin") {
267
+ if (options.uid === void 0) throw new Error("Cannot determine the current macOS user");
268
+ const output2 = await run("/bin/launchctl", ["print-disabled", domain]);
269
+ return !output2.includes(`"${label}" => true`);
270
+ }
271
+ const output = await run("systemctl", [
272
+ "--user",
273
+ "show",
274
+ unit,
275
+ "--property=UnitFileState",
276
+ "--value"
277
+ ]);
278
+ return output.trim() === "enabled";
279
+ }
280
+ async function enable() {
281
+ if (platform === "win32") {
282
+ await runPowerShell(windowsTask());
283
+ return;
284
+ }
285
+ if (platform === "darwin" && options.uid === void 0) {
286
+ throw new Error("Cannot determine the current macOS user");
287
+ }
288
+ const content = definition();
289
+ await mkdir(dirname(filePath), { recursive: true });
290
+ const previous = await readIfPresent(filePath);
291
+ await writeFile(filePath, content, { mode: 384 });
292
+ try {
293
+ if (platform === "darwin") {
294
+ await run("/bin/launchctl", ["enable", launchdTarget]);
295
+ } else {
296
+ await run("systemctl", ["--user", "daemon-reload"]);
297
+ await run("systemctl", ["--user", "enable", unit]);
298
+ }
299
+ } catch (error) {
300
+ if (previous === null) await removeIfPresent(filePath);
301
+ else await writeFile(filePath, previous, { mode: 384 });
302
+ throw error;
303
+ }
304
+ }
305
+ async function disable() {
306
+ if (platform === "win32") {
307
+ await runPowerShell(
308
+ `${taskLookup}
309
+ if ($task) { $task | Unregister-ScheduledTask -Confirm:$false; }`
310
+ );
311
+ return;
312
+ }
313
+ if (await readIfPresent(filePath) === null) return;
314
+ if (platform === "darwin") {
315
+ if (options.uid === void 0) throw new Error("Cannot determine the current macOS user");
316
+ await run("/bin/launchctl", ["disable", launchdTarget]);
317
+ } else {
318
+ await run("systemctl", ["--user", "disable", unit]);
319
+ }
320
+ await removeIfPresent(filePath);
321
+ if (platform === "linux") await run("systemctl", ["--user", "daemon-reload"]);
322
+ }
323
+ return { enable, disable, status };
324
+ }
325
+
326
+ // src/common/system-service-autostart.ts
327
+ import { execFile as execFile2, spawn } from "child_process";
328
+ import { mkdtemp, mkdir as mkdir2, rm, writeFile as writeFile2 } from "fs/promises";
329
+ import { tmpdir } from "os";
330
+ import { dirname as dirname2, join as join2, win32 as win324 } from "path";
331
+ import { promisify as promisify2 } from "util";
332
+ import { z } from "zod";
333
+
334
+ // src/common/windows-service.ts
335
+ import { createHash as createHash3 } from "crypto";
336
+ import { win32 as win323 } from "path";
337
+ var WINDOWS_SERVICE_POWERSHELL_PREAMBLE = `$ErrorActionPreference = 'Stop';
338
+ $env:PSModulePath = $PSHOME + '\\Modules';
339
+ $ProgressPreference = 'SilentlyContinue';
340
+ [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false);`;
341
+ function encoded(value) {
342
+ return `Decode("${Buffer.from(checkAutostartText(value), "utf8").toString("base64")}")`;
343
+ }
344
+ function buildWindowsService(options) {
345
+ const paths = buildProxyProfilePaths(options.home, options.profile, "win32");
346
+ const logPath = win323.join(paths.logDir, "system-service.log");
347
+ const source = `using System;
348
+ using System.Diagnostics;
349
+ using System.IO;
350
+ using System.ServiceProcess;
351
+ using System.Text;
352
+ using System.Threading;
353
+
354
+ public sealed class DevAnywhereService : ServiceBase {
355
+ private Process child;
356
+ private StreamWriter log;
357
+ private volatile bool stopping;
358
+ private static string Decode(string value) { return Encoding.UTF8.GetString(Convert.FromBase64String(value)); }
359
+ public DevAnywhereService() {
360
+ ServiceName = ${encoded(options.label)};
361
+ CanStop = true; CanShutdown = true; AutoLog = false;
362
+ }
363
+ private void WriteLog(string stream, string message) {
364
+ if (message == null || log == null) return;
365
+ try { lock (log) { log.WriteLine(DateTime.UtcNow.ToString("o") + " " + stream + ": " + message); } }
366
+ catch { } // Draining the child's pipes must continue even if its log disk fills.
367
+ }
368
+ private void StartChild() {
369
+ string logPath = ${encoded(logPath)};
370
+ Directory.CreateDirectory(Path.GetDirectoryName(logPath));
371
+ log = new StreamWriter(new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite), new UTF8Encoding(false));
372
+ log.AutoFlush = true;
373
+ var info = new ProcessStartInfo();
374
+ info.FileName = ${encoded(options.executable)};
375
+ info.Arguments = ${encoded(options.args.map(quoteWindowsArgument).join(" "))};
376
+ info.WorkingDirectory = ${encoded(options.home)};
377
+ ${Object.entries(options.env).map(([key, value]) => `info.EnvironmentVariables[${encoded(key)}] = ${encoded(value)};`).join("\n ")}
378
+ info.UseShellExecute = false;
379
+ info.CreateNoWindow = true;
380
+ info.RedirectStandardInput = true;
381
+ info.RedirectStandardOutput = true;
382
+ info.RedirectStandardError = true;
383
+ info.StandardOutputEncoding = Encoding.UTF8;
384
+ info.StandardErrorEncoding = Encoding.UTF8;
385
+ child = new Process();
386
+ child.StartInfo = info;
387
+ child.OutputDataReceived += (sender, e) => WriteLog("stdout", e.Data);
388
+ child.ErrorDataReceived += (sender, e) => WriteLog("stderr", e.Data);
389
+ child.Start();
390
+ child.BeginOutputReadLine();
391
+ child.BeginErrorReadLine();
392
+ }
393
+ protected override void OnStart(string[] args) {
394
+ StartChild();
395
+ ThreadPool.QueueUserWorkItem(_ => {
396
+ child.WaitForExit();
397
+ if (!stopping) { ExitCode = child.ExitCode; Stop(); }
398
+ });
399
+ }
400
+ private void StopChild(bool requestedStop) {
401
+ stopping = true;
402
+ if (child == null) return;
403
+ if (!child.HasExited) {
404
+ if (requestedStop) RequestAdditionalTime(120000);
405
+ try { child.StandardInput.WriteLine("stop"); child.StandardInput.Flush(); }
406
+ catch (IOException) { }
407
+ if (!child.WaitForExit(110000)) { child.Kill(); ExitCode = 1; }
408
+ }
409
+ }
410
+ protected override void OnStop() { StopChild(true); }
411
+ protected override void OnShutdown() { StopChild(false); }
412
+ public static int Main(string[] args) {
413
+ using (var service = new DevAnywhereService()) {
414
+ // Native tests exercise the compiled process/pipe contract without installing an OS service.
415
+ if (args.Length == 1 && (args[0] == "--console-test" || args[0] == "--console-shutdown-test")) {
416
+ try {
417
+ service.StartChild();
418
+ ThreadPool.QueueUserWorkItem(_ => {
419
+ Console.ReadLine();
420
+ if (args[0] == "--console-shutdown-test") { service.OnShutdown(); return; }
421
+ try { service.child.StandardInput.WriteLine("stop"); service.child.StandardInput.Flush(); }
422
+ catch (IOException) { }
423
+ });
424
+ service.child.WaitForExit();
425
+ return service.child.ExitCode;
426
+ } catch (Exception error) { service.WriteLog("host", error.ToString()); return 1; }
427
+ }
428
+ ServiceBase.Run(service);
429
+ return 0;
430
+ }
431
+ }
432
+ }
433
+ `;
434
+ const digest = createHash3("sha256").update(source).digest("hex").slice(0, 20);
435
+ const path = win323.join(paths.profileDir, "autostart", `service-${digest}.exe`);
436
+ const compileScript = `$servicePath = ${psString(path)};
437
+ if (!(Test-Path -LiteralPath $servicePath -PathType Leaf)) {
438
+ [IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($servicePath)) | Out-Null;
439
+ $candidate = $servicePath + '.' + [guid]::NewGuid().ToString('N') + '.tmp.exe';
440
+ try {
441
+ $source = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(source).toString("base64")}'));
442
+ Add-Type -TypeDefinition $source -ReferencedAssemblies 'System.dll','System.ServiceProcess.dll' -OutputAssembly $candidate -OutputType WindowsApplication -ErrorAction Stop;
443
+ Move-Item -LiteralPath $candidate -Destination $servicePath -ErrorAction Stop;
444
+ } finally { if (Test-Path -LiteralPath $candidate) { Remove-Item -LiteralPath $candidate -Force; } }
445
+ }`;
446
+ return { path, source, logPath, compileScript };
447
+ }
448
+ function windowsServiceRegistration(label, binaryPath) {
449
+ return `$binaryPath = ${psString(quoteWindowsArgument(binaryPath))};
450
+ if ($service) {
451
+ $account = New-Object Security.Principal.NTAccount($service.StartName);
452
+ if ($account.Translate([Security.Principal.SecurityIdentifier]).Value -ne $ownerSid) { throw 'Existing service belongs to another account'; }
453
+ $result = Invoke-CimMethod -InputObject $service -MethodName Change -Arguments @{ PathName = $binaryPath; StartMode = 'Automatic' };
454
+ if ($result.ReturnValue -ne 0) { throw ('Service update failed: ' + $result.ReturnValue); }
455
+ } else {
456
+ $credential = Get-Credential -UserName $ownerName -Message 'DEV Anywhere: enter this Windows account password for startup before desktop login (not the Windows Hello PIN)';
457
+ if (!$credential) { throw 'Service installation cancelled'; }
458
+ $account = New-Object Security.Principal.NTAccount($credential.UserName);
459
+ if ($account.Translate([Security.Principal.SecurityIdentifier]).Value -ne $ownerSid) { throw 'Use the same account that owns this DEV Anywhere profile'; }
460
+ Add-Type -AssemblyName System.ServiceProcess;
461
+ Add-Type -AssemblyName System.Configuration.Install;
462
+ $processInstaller = New-Object System.ServiceProcess.ServiceProcessInstaller;
463
+ $processInstaller.Account = [System.ServiceProcess.ServiceAccount]::User;
464
+ $processInstaller.Username = $ownerName;
465
+ $processInstaller.Password = $credential.GetNetworkCredential().Password;
466
+ $installer = New-Object System.ServiceProcess.ServiceInstaller;
467
+ $installer.ServiceName = ${psString(label)};
468
+ $installer.DisplayName = ${psString(`DEV Anywhere (${label})`)};
469
+ $installer.Description = 'DEV Anywhere Proxy: run before desktop login as the profile owner';
470
+ $installer.StartType = [System.ServiceProcess.ServiceStartMode]::Automatic;
471
+ $processInstaller.Installers.Add($installer) | Out-Null;
472
+ $processInstaller.Context = New-Object System.Configuration.Install.InstallContext($null, @('/LogToConsole=false'));
473
+ $processInstaller.Context.Parameters['assemblypath'] = $binaryPath;
474
+ $state = @{};
475
+ try {
476
+ # ServiceProcessInstaller grants SeServiceLogonRight and rolls it back on failed installation.
477
+ $processInstaller.Install($state);
478
+ $processInstaller.Commit($state);
479
+ } catch { $processInstaller.Rollback($state); throw; }
480
+ finally { $processInstaller.Password = $null; $credential = $null; }
481
+ }`;
482
+ }
483
+
484
+ // src/common/system-service-autostart.ts
485
+ var execFileAsync2 = promisify2(execFile2);
486
+ async function runCommand(command, args) {
487
+ const result = await execFileAsync2(command, args, {
488
+ windowsHide: true,
489
+ timeout: 15e3,
490
+ maxBuffer: 256 * 1024,
491
+ encoding: "utf8"
492
+ });
493
+ return result.stdout;
494
+ }
495
+ async function runInteractive(command, args) {
496
+ return new Promise((resolve, reject) => {
497
+ const child = spawn(command, args, { stdio: "inherit", windowsHide: false });
498
+ child.once("error", reject);
499
+ child.once(
500
+ "exit",
501
+ (code) => code === 0 ? resolve("") : reject(
502
+ new Error(`System service registration command exited with code ${code ?? "unknown"}`)
503
+ )
504
+ );
505
+ });
506
+ }
507
+ function createSystemServiceAutostart(options) {
508
+ const { platform, home, profile, executable, env } = options;
509
+ if (!["darwin", "linux", "win32"].includes(platform))
510
+ throw new Error(`System services are not supported on ${platform}`);
511
+ const label = `${autostartLabel(home, profile)}-system`;
512
+ const unit = `${label}.service`;
513
+ const paths = buildProxyProfilePaths(home, profile, platform);
514
+ const filePath = join2(
515
+ options.systemDirectory ?? (platform === "darwin" ? "/Library/LaunchDaemons" : "/etc/systemd/system"),
516
+ platform === "darwin" ? `${label}.plist` : unit
517
+ );
518
+ const run = options.run ?? runCommand;
519
+ const interactive = options.runInteractive ?? runInteractive;
520
+ const args = [...options.args, "--profile", profile, "serve", "autostart", "run", "--system"];
521
+ const environment = {
522
+ HOME: checkAutostartText(home),
523
+ ...platform === "win32" ? { USERPROFILE: checkAutostartText(home) } : {},
524
+ ...Object.fromEntries(
525
+ [
526
+ "PATH",
527
+ "SHELL",
528
+ "XDG_CONFIG_HOME",
529
+ ...platform === "win32" ? ["APPDATA", "LOCALAPPDATA"] : []
530
+ ].flatMap((key) => env[key] ? [[key, checkAutostartText(env[key])]] : [])
531
+ )
532
+ };
533
+ const powershell = win324.join(
534
+ env.SystemRoot ?? env.SYSTEMROOT ?? "C:\\Windows",
535
+ "System32",
536
+ "WindowsPowerShell",
537
+ "v1.0",
538
+ "powershell.exe"
539
+ );
540
+ const lookup = `$service = Get-CimInstance -ClassName Win32_Service -Filter ${psString(`Name='${label}'`)} -ErrorAction Stop;`;
541
+ const powerShell = (script) => run(powershell, [
542
+ "-NoProfile",
543
+ "-NonInteractive",
544
+ "-EncodedCommand",
545
+ Buffer.from(`${WINDOWS_SERVICE_POWERSHELL_PREAMBLE}
546
+ ${script}`, "utf16le").toString(
547
+ "base64"
548
+ )
549
+ ]);
550
+ const privileged = (command, commandArgs) => interactive("/usr/bin/sudo", [command, ...commandArgs]);
551
+ const requireUser = () => {
552
+ if (!options.uid || !options.username)
553
+ throw new Error(
554
+ "Run system-service registration as your normal user; it requests sudo only for installation"
555
+ );
556
+ checkAutostartText(options.username);
557
+ };
558
+ async function stage(content, fn, suffix = "definition") {
559
+ const directory = await mkdtemp(join2(tmpdir(), "dev-anywhere-service-"));
560
+ const path = join2(directory, suffix);
561
+ try {
562
+ await writeFile2(path, content, { mode: 384 });
563
+ return await fn(path);
564
+ } finally {
565
+ await rm(directory, { recursive: true, force: true });
566
+ }
567
+ }
568
+ async function windowsMutation(script) {
569
+ const owner = z.object({ name: z.string().min(1), sid: z.string().regex(/^S-1-/) }).parse(
570
+ JSON.parse(
571
+ await powerShell(
572
+ "$identity = [Security.Principal.WindowsIdentity]::GetCurrent(); @{ name = $identity.Name; sid = $identity.User.Value } | ConvertTo-Json -Compress;"
573
+ )
574
+ )
575
+ );
576
+ const source = `param([switch]$Elevated)
577
+ ${WINDOWS_SERVICE_POWERSHELL_PREAMBLE}
578
+ $principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent());
579
+ if (!$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
580
+ if ($Elevated) { throw 'Administrator privileges are required to install a system service'; }
581
+ $child = Start-Process -FilePath ${psString(powershell)} -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', ('"' + $PSCommandPath + '"'), '-Elevated') -Verb RunAs -Wait -PassThru;
582
+ exit $child.ExitCode;
583
+ }
584
+ try {
585
+ $ownerName = ${psString(owner.name)};
586
+ $ownerSid = ${psString(owner.sid)};
587
+ ${lookup}
588
+ if ($service) {
589
+ $account = New-Object Security.Principal.NTAccount($service.StartName);
590
+ if ($account.Translate([Security.Principal.SecurityIdentifier]).Value -ne $ownerSid) { throw 'Existing service belongs to another account'; }
591
+ }
592
+ ${script}
593
+ } catch {
594
+ Write-Error $_ -ErrorAction Continue;
595
+ if ($Elevated) { Read-Host 'Service operation failed. Press Enter to close this window' | Out-Null; }
596
+ exit 1;
597
+ }
598
+ `;
599
+ await stage(
600
+ `\uFEFF${source}`,
601
+ (path) => interactive(powershell, ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", path]),
602
+ "register.ps1"
603
+ );
604
+ }
605
+ function definition() {
606
+ requireUser();
607
+ const user = options.username;
608
+ const userEnv = { ...environment, USER: user, LOGNAME: user };
609
+ if (platform === "darwin")
610
+ return `<?xml version="1.0" encoding="UTF-8"?>
611
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
612
+ <plist version="1.0"><dict>
613
+ <key>Label</key><string>${xmlString(label)}</string>
614
+ <key>UserName</key><string>${xmlString(user)}</string>
615
+ <key>ProgramArguments</key><array>${[executable, ...args].map((arg) => `<string>${xmlString(arg)}</string>`).join("")}</array>
616
+ <key>WorkingDirectory</key><string>${xmlString(home)}</string>
617
+ <key>EnvironmentVariables</key><dict>${Object.entries(userEnv).map(([key, value]) => `<key>${xmlString(key)}</key><string>${xmlString(value)}</string>`).join("")}</dict>
618
+ <key>RunAtLoad</key><true/>
619
+ <key>KeepAlive</key><false/>
620
+ <key>ExitTimeOut</key><integer>120</integer>
621
+ </dict></plist>
622
+ `;
623
+ return `[Unit]
624
+ Description=DEV Anywhere system service (${checkAutostartText(profile)})
625
+ Wants=network-online.target
626
+ After=network-online.target
627
+ RequiresMountsFor=${unitString(home)}
628
+
629
+ [Service]
630
+ Type=simple
631
+ User=${unitValue(user)}
632
+ WorkingDirectory=${unitValue(home)}
633
+ ${Object.entries(userEnv).map(([key, value]) => `Environment=${unitString(`${key}=${value}`)}`).join("\n")}
634
+ ExecStart=:${[executable, ...args].map(unitString).join(" ")}
635
+ Restart=no
636
+ TimeoutStopSec=120
637
+
638
+ [Install]
639
+ WantedBy=multi-user.target
640
+ `;
641
+ }
642
+ const install = (source) => privileged("/usr/bin/install", [
643
+ "-o",
644
+ "root",
645
+ "-g",
646
+ platform === "darwin" ? "wheel" : "root",
647
+ "-m",
648
+ "644",
649
+ source,
650
+ filePath
651
+ ]);
652
+ async function status() {
653
+ if (platform === "win32") {
654
+ return z.boolean().parse(
655
+ JSON.parse(
656
+ (await powerShell(
657
+ `${lookup}
658
+ [bool]($service -and $service.StartMode -eq 'Auto') | ConvertTo-Json -Compress;`
659
+ )).trim()
660
+ )
661
+ );
662
+ }
663
+ if (await readIfPresent(filePath) === null) return false;
664
+ if (platform === "darwin")
665
+ return !(await run("/bin/launchctl", ["print-disabled", "system"])).includes(
666
+ `"${label}" => true`
667
+ );
668
+ return (await run("systemctl", ["--system", "show", unit, "--property=UnitFileState", "--value"])).trim() === "enabled";
669
+ }
670
+ async function enable() {
671
+ if (platform === "win32") {
672
+ const wrapper = buildWindowsService({
673
+ home,
674
+ profile,
675
+ label,
676
+ executable,
677
+ args,
678
+ env: environment
679
+ });
680
+ await windowsMutation(
681
+ `${wrapper.compileScript}
682
+ ${windowsServiceRegistration(label, wrapper.path)}`
683
+ );
684
+ } else {
685
+ const content = definition();
686
+ const previous = await readIfPresent(filePath);
687
+ await stage(content, install);
688
+ try {
689
+ if (platform === "darwin")
690
+ await privileged("/bin/launchctl", ["enable", `system/${label}`]);
691
+ else {
692
+ await privileged("systemctl", ["--system", "daemon-reload"]);
693
+ await privileged("systemctl", ["--system", "enable", unit]);
694
+ }
695
+ } catch (error) {
696
+ if (previous === null) await privileged("/bin/rm", ["-f", filePath]);
697
+ else await stage(previous, install);
698
+ if (platform === "linux") await privileged("systemctl", ["--system", "daemon-reload"]);
699
+ throw error;
700
+ }
701
+ }
702
+ await mkdir2(dirname2(paths.systemAutostartPath), { recursive: true });
703
+ await writeFile2(paths.systemAutostartPath, `${label}
704
+ `, { mode: 384 });
705
+ }
706
+ async function disable() {
707
+ if (platform === "win32") {
708
+ if (await status())
709
+ await windowsMutation(`if ($service) {
710
+ $result = Invoke-CimMethod -InputObject $service -MethodName ChangeStartMode -Arguments @{ StartMode = 'Disabled' };
711
+ if ($result.ReturnValue -ne 0) { throw ('Service disable failed: ' + $result.ReturnValue); }
712
+ }`);
713
+ } else if (await readIfPresent(filePath) !== null) {
714
+ requireUser();
715
+ if (platform === "darwin") await privileged("/bin/launchctl", ["disable", `system/${label}`]);
716
+ else await privileged("systemctl", ["--system", "disable", unit]);
717
+ await privileged("/bin/rm", ["-f", filePath]);
718
+ if (platform === "linux") await privileged("systemctl", ["--system", "daemon-reload"]);
719
+ }
720
+ await removeIfPresent(paths.systemAutostartPath);
721
+ }
722
+ async function activate() {
723
+ if (platform === "win32") {
724
+ await windowsMutation(
725
+ `if (!$service) { throw 'System service is not installed'; }
726
+ Start-Service -Name ${psString(label)};`
727
+ );
728
+ } else if (platform === "darwin") {
729
+ requireUser();
730
+ let loaded = false;
731
+ try {
732
+ await run("/bin/launchctl", ["print", `system/${label}`]);
733
+ loaded = true;
734
+ } catch (error) {
735
+ if (![3, 113].includes(Number(error.code))) throw error;
736
+ }
737
+ if (!loaded) await privileged("/bin/launchctl", ["bootstrap", "system", filePath]);
738
+ else await privileged("/bin/launchctl", ["kickstart", `system/${label}`]);
739
+ } else {
740
+ requireUser();
741
+ await privileged("systemctl", ["--system", "start", unit]);
742
+ }
743
+ }
744
+ return { label, filePath, enable, disable, status, activate };
745
+ }
746
+
747
+ // src/common/autostart-mode.ts
748
+ async function switchAutostartMode(selected, previous) {
749
+ const alreadyEnabled = await selected.status();
750
+ const previousEnabled = await previous.status();
751
+ await selected.enable();
752
+ try {
753
+ await previous.disable();
754
+ } catch (error) {
755
+ if (previousEnabled) await previous.enable();
756
+ if (!alreadyEnabled) await selected.disable();
757
+ throw error;
758
+ }
759
+ }
760
+
761
+ // src/autostart.ts
762
+ async function runAutostartCommand(action, options = {}) {
763
+ try {
764
+ if (options.now && (action !== "enable" || !options.system))
765
+ throw new Error("--now requires autostart enable --system");
766
+ if (action === "enable" && !isInitialized()) {
767
+ throw new Error('Dev Anywhere is not initialized. Run "dev-anywhere init" first.');
768
+ }
769
+ const entry = `${fileURLToPath(resolveTopLevelScript("index"))}${IS_DEV ? ".ts" : ".js"}`;
770
+ const account = userInfo();
771
+ const settings = {
772
+ platform: process.platform,
773
+ home: homedir(),
774
+ profile: PROFILE_NAME,
775
+ executable: process.execPath,
776
+ args: IS_DEV ? ["--import", import.meta.resolve("tsx"), entry] : [entry],
777
+ env: { ...process.env, SHELL: process.env.SHELL ?? account.shell ?? void 0 },
778
+ uid: process.getuid?.(),
779
+ username: account.username
780
+ };
781
+ const login = createServiceAutostart(settings);
782
+ const system = createSystemServiceAutostart(settings);
783
+ const autostart = options.system ? system : login;
784
+ if (action === "status") {
785
+ console.log(
786
+ `${PROFILE_NAME}: ${await autostart.status() ? options.system ? "\u5DF2\u8BBE\u7F6E\u5F00\u673A\u81EA\u52A8\u542F\u52A8\uFF08\u65E0\u9700\u684C\u9762\u767B\u5F55\uFF09" : "\u5DF2\u8BBE\u7F6E\u767B\u5F55\u540E\u81EA\u52A8\u542F\u52A8" : "\u672A\u8BBE\u7F6E\u6B64\u6A21\u5F0F\u7684\u81EA\u52A8\u542F\u52A8"}`
787
+ );
788
+ if (options.system) {
789
+ const host = await requestServiceHost(SERVICE_HOST_PATH, PROFILE_NAME, { action: "probe" });
790
+ console.log(
791
+ `Service: ${system.label}; ${host?.status === "host" ? `running (PID ${host.pid})` : "not running"}`
792
+ );
793
+ }
794
+ return;
795
+ }
796
+ if (action === "enable") await switchAutostartMode(autostart, options.system ? login : system);
797
+ else await autostart.disable();
798
+ if (options.now) {
799
+ const wasRunning = await requestServiceHost(SERVICE_HOST_PATH, PROFILE_NAME, {
800
+ action: "probe"
801
+ });
802
+ await system.activate();
803
+ const deadline = Date.now() + 3e4;
804
+ let ready = false;
805
+ while (Date.now() < deadline) {
806
+ const result = await requestServiceHost(SERVICE_HOST_PATH, PROFILE_NAME, {
807
+ action: wasRunning ? "restart" : "start",
808
+ intent: "explicit"
809
+ });
810
+ if (result?.status === "failed") throw new Error(result.message);
811
+ if (result?.status === "ready") {
812
+ ready = true;
813
+ break;
814
+ }
815
+ await sleep(150);
816
+ }
817
+ if (!ready)
818
+ throw new Error(
819
+ "System service is registered, but did not become ready; check the OS service status"
820
+ );
821
+ }
822
+ console.log(
823
+ action === "enable" ? options.system ? `${PROFILE_NAME}: \u5DF2\u8BBE\u7F6E\u5F00\u673A\u81EA\u52A8\u542F\u52A8\uFF08\u65E0\u9700\u684C\u9762\u767B\u5F55\uFF09\u3002${options.now ? "Proxy \u5DF2\u542F\u52A8\uFF1B\u65B0\u5EFA\u4F1A\u8BDD\u53EF\u5728\u9000\u51FA\u684C\u9762\u540E\u7EE7\u7EED\u4F7F\u7528\u3002" : "\u4E0B\u6B21\u5F00\u673A\u751F\u6548\uFF1B\u7ACB\u5373\u542F\u52A8\u8BF7\u52A0 --now\u3002"}` : `${PROFILE_NAME}: \u5DF2\u8BBE\u7F6E\u767B\u5F55\u540E\u81EA\u52A8\u542F\u52A8\uFF0C\u5F53\u524D Proxy \u4E0D\u53D7\u5F71\u54CD\u3002` : `${PROFILE_NAME}: \u5DF2\u53D6\u6D88\u81EA\u52A8\u542F\u52A8\uFF0C\u5F53\u524D Proxy \u4E0D\u53D7\u5F71\u54CD\u3002`
824
+ );
825
+ } catch (error) {
826
+ console.error(getErrorMessage(error));
827
+ process.exitCode = 1;
828
+ }
829
+ }
830
+ async function startAutostartService(daemon, system = false) {
831
+ try {
832
+ if (!isInitialized()) throw new Error("Proxy configuration is missing");
833
+ if (process.platform !== "win32") {
834
+ const refreshed = await refreshLoginShellPath({
835
+ env: { ...process.env, SHELL: process.env.SHELL ?? userInfo().shell ?? void 0 }
836
+ });
837
+ if (refreshed.path !== void 0) process.env.PATH = refreshed.path;
838
+ }
839
+ if (system) {
840
+ if (daemon) throw new Error("The system service host must remain in the foreground");
841
+ const { startSystemServiceHost } = await import("./service-host-YEX4IBZO.js");
842
+ await startSystemServiceHost();
843
+ return;
844
+ }
845
+ const lifecycle = createProfileServiceLifecycle();
846
+ if (daemon) await lifecycle.start("explicit");
847
+ else
848
+ await lifecycle.startForeground(async () => {
849
+ const { startService } = await import("./serve.js");
850
+ await startService();
851
+ });
852
+ } catch (error) {
853
+ const { serviceLogger } = await import("./logger-2EQWS3V2.js");
854
+ const { flushLogger } = await import("./logger-24TGGN76.js");
855
+ serviceLogger.error({ err: getErrorMessage(error) }, "Proxy automatic startup failed");
856
+ await flushLogger(serviceLogger);
857
+ process.exit(1);
858
+ }
859
+ }
860
+ export {
861
+ runAutostartCommand,
862
+ startAutostartService
863
+ };
864
+ //# sourceMappingURL=autostart-6DMQS43N.js.map