@dev-anywhere/proxy 0.9.7 → 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.
- package/README.md +8 -1
- package/dist/autostart-6DMQS43N.js +864 -0
- package/dist/autostart-6DMQS43N.js.map +1 -0
- package/dist/chunk-3NUN2VYO.js +46 -0
- package/dist/chunk-3NUN2VYO.js.map +1 -0
- package/dist/{chunk-DEMLXEB5.js → chunk-7EOSTWVO.js} +3 -3
- package/dist/{chunk-PCF2R2TG.js → chunk-AS7W2D2X.js} +2 -2
- package/dist/{chunk-PCF2R2TG.js.map → chunk-AS7W2D2X.js.map} +1 -1
- package/dist/{chunk-724Y2CKO.js → chunk-CFO5GU5U.js} +2 -43
- package/dist/chunk-CFO5GU5U.js.map +1 -0
- package/dist/{chunk-5COVSNQZ.js → chunk-CFPY2A6Q.js} +2 -2
- package/dist/chunk-DEL6NNYV.js +161 -0
- package/dist/chunk-DEL6NNYV.js.map +1 -0
- package/dist/{chunk-7EKB4LAE.js → chunk-HEXGO236.js} +4 -4
- package/dist/{chunk-EEXWF5SA.js → chunk-JRSPTWQB.js} +2 -2
- package/dist/{chunk-LIGQMX7K.js → chunk-MPW6H537.js} +85 -7
- package/dist/chunk-MPW6H537.js.map +1 -0
- package/dist/{chunk-YEBLIMID.js → chunk-QZJBIFGW.js} +3 -3
- package/dist/{chunk-WEATMI5J.js → chunk-SKKPJULC.js} +10 -1
- package/dist/chunk-SKKPJULC.js.map +1 -0
- package/dist/{chunk-CQFTS5QX.js → chunk-ZE73PMOL.js} +2 -2
- package/dist/chunk-ZRCMGVGT.js +33 -0
- package/dist/chunk-ZRCMGVGT.js.map +1 -0
- package/dist/index.js +32 -18
- package/dist/index.js.map +1 -1
- package/dist/{logger-XEIQC6K6.js → logger-2EQWS3V2.js} +3 -3
- package/dist/preview-worker.js +6 -4
- package/dist/preview-worker.js.map +1 -1
- package/dist/{quick-tunnel-ZIFTYUUD.js → quick-tunnel-HA5NE7K6.js} +2 -2
- package/dist/{relay-token-Y3IFNUMX.js → relay-token-SK3OOH2H.js} +4 -4
- package/dist/serve.js +11 -9
- package/dist/serve.js.map +1 -1
- package/dist/service-host-YEX4IBZO.js +139 -0
- package/dist/service-host-YEX4IBZO.js.map +1 -0
- package/dist/session-worker.js +3 -3
- package/dist/{terminal-XOAZAJYR.js → terminal-H6DLED7O.js} +11 -8
- package/dist/{terminal-XOAZAJYR.js.map → terminal-H6DLED7O.js.map} +1 -1
- package/dist/terminal-worker.js +11 -8
- package/dist/terminal-worker.js.map +1 -1
- package/dist/update-runner.js +5 -31
- package/dist/update-runner.js.map +1 -1
- package/package.json +3 -3
- package/dist/autostart-GMEGJAZJ.js +0 -370
- package/dist/autostart-GMEGJAZJ.js.map +0 -1
- package/dist/chunk-724Y2CKO.js.map +0 -1
- package/dist/chunk-LIGQMX7K.js.map +0 -1
- package/dist/chunk-WEATMI5J.js.map +0 -1
- /package/dist/{chunk-DEMLXEB5.js.map → chunk-7EOSTWVO.js.map} +0 -0
- /package/dist/{chunk-5COVSNQZ.js.map → chunk-CFPY2A6Q.js.map} +0 -0
- /package/dist/{chunk-7EKB4LAE.js.map → chunk-HEXGO236.js.map} +0 -0
- /package/dist/{chunk-EEXWF5SA.js.map → chunk-JRSPTWQB.js.map} +0 -0
- /package/dist/{chunk-YEBLIMID.js.map → chunk-QZJBIFGW.js.map} +0 -0
- /package/dist/{chunk-CQFTS5QX.js.map → chunk-ZE73PMOL.js.map} +0 -0
- /package/dist/{logger-XEIQC6K6.js.map → logger-2EQWS3V2.js.map} +0 -0
- /package/dist/{quick-tunnel-ZIFTYUUD.js.map → quick-tunnel-HA5NE7K6.js.map} +0 -0
- /package/dist/{relay-token-Y3IFNUMX.js.map → relay-token-SK3OOH2H.js.map} +0 -0
|
@@ -1,370 +0,0 @@
|
|
|
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-LIGQMX7K.js";
|
|
11
|
-
import "./chunk-AZ5MTPUR.js";
|
|
12
|
-
import {
|
|
13
|
-
IS_DEV,
|
|
14
|
-
resolveTopLevelScript
|
|
15
|
-
} from "./chunk-PCF2R2TG.js";
|
|
16
|
-
import "./chunk-724Y2CKO.js";
|
|
17
|
-
import "./chunk-77QVUYU7.js";
|
|
18
|
-
import {
|
|
19
|
-
quoteWindowsArgument
|
|
20
|
-
} from "./chunk-EWIHC4BK.js";
|
|
21
|
-
import "./chunk-HJOYOYGB.js";
|
|
22
|
-
import {
|
|
23
|
-
PROFILE_NAME,
|
|
24
|
-
buildProxyProfilePaths,
|
|
25
|
-
isInitialized
|
|
26
|
-
} from "./chunk-WEATMI5J.js";
|
|
27
|
-
|
|
28
|
-
// src/autostart.ts
|
|
29
|
-
import { homedir, userInfo } from "os";
|
|
30
|
-
import { fileURLToPath } from "url";
|
|
31
|
-
|
|
32
|
-
// src/common/service-autostart.ts
|
|
33
|
-
import { execFile } from "child_process";
|
|
34
|
-
import { createHash as createHash2 } from "crypto";
|
|
35
|
-
import { mkdir, readFile, unlink, writeFile } from "fs/promises";
|
|
36
|
-
import { dirname, join, win32 as win322 } from "path";
|
|
37
|
-
import { promisify } from "util";
|
|
38
|
-
|
|
39
|
-
// src/common/windows-autostart-launcher.ts
|
|
40
|
-
import { createHash } from "crypto";
|
|
41
|
-
import { win32 } from "path";
|
|
42
|
-
function encodedString(value) {
|
|
43
|
-
if ([...value].some((char) => char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127)) {
|
|
44
|
-
throw new Error("Autostart paths and environment must not contain control characters");
|
|
45
|
-
}
|
|
46
|
-
return `Decode("${Buffer.from(value, "utf8").toString("base64")}")`;
|
|
47
|
-
}
|
|
48
|
-
function buildWindowsAutostartLauncher(options) {
|
|
49
|
-
const paths = buildProxyProfilePaths(options.home, options.profile, "win32");
|
|
50
|
-
const logPath = win32.join(paths.logDir, "autostart-launcher.log");
|
|
51
|
-
const source = `using System;
|
|
52
|
-
using System.Diagnostics;
|
|
53
|
-
using System.IO;
|
|
54
|
-
using System.Text;
|
|
55
|
-
|
|
56
|
-
internal static class DevAnywhereAutostart {
|
|
57
|
-
private static StreamWriter log;
|
|
58
|
-
private static volatile bool logFailed;
|
|
59
|
-
private static string Decode(string value) { return Encoding.UTF8.GetString(Convert.FromBase64String(value)); }
|
|
60
|
-
private static void WriteLog(string stream, string message) {
|
|
61
|
-
if (message == null) return;
|
|
62
|
-
try { lock (log) { log.WriteLine(DateTime.UtcNow.ToString("o") + " " + stream + ": " + message); } }
|
|
63
|
-
catch { logFailed = true; } // Keep draining output; report logging failures through the task exit code.
|
|
64
|
-
}
|
|
65
|
-
public static int Main() {
|
|
66
|
-
try {
|
|
67
|
-
string logPath = ${encodedString(logPath)};
|
|
68
|
-
Directory.CreateDirectory(Path.GetDirectoryName(logPath));
|
|
69
|
-
using (log = new StreamWriter(new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite), new UTF8Encoding(false))) {
|
|
70
|
-
log.AutoFlush = true;
|
|
71
|
-
try {
|
|
72
|
-
var info = new ProcessStartInfo();
|
|
73
|
-
info.FileName = ${encodedString(options.executable)};
|
|
74
|
-
info.Arguments = ${encodedString(options.args.map(quoteWindowsArgument).join(" "))};
|
|
75
|
-
info.WorkingDirectory = ${encodedString(options.home)};
|
|
76
|
-
info.EnvironmentVariables["USERPROFILE"] = ${encodedString(options.home)};
|
|
77
|
-
info.EnvironmentVariables["HOME"] = ${encodedString(options.home)};
|
|
78
|
-
info.UseShellExecute = false;
|
|
79
|
-
info.CreateNoWindow = true;
|
|
80
|
-
info.RedirectStandardInput = true;
|
|
81
|
-
info.RedirectStandardOutput = true;
|
|
82
|
-
info.RedirectStandardError = true;
|
|
83
|
-
info.StandardOutputEncoding = Encoding.UTF8;
|
|
84
|
-
info.StandardErrorEncoding = Encoding.UTF8;
|
|
85
|
-
using (var child = new Process()) {
|
|
86
|
-
child.StartInfo = info;
|
|
87
|
-
child.OutputDataReceived += (sender, e) => WriteLog("stdout", e.Data);
|
|
88
|
-
child.ErrorDataReceived += (sender, e) => WriteLog("stderr", e.Data);
|
|
89
|
-
child.Start();
|
|
90
|
-
child.StandardInput.Close();
|
|
91
|
-
child.BeginOutputReadLine();
|
|
92
|
-
child.BeginErrorReadLine();
|
|
93
|
-
child.WaitForExit();
|
|
94
|
-
return child.ExitCode != 0 ? child.ExitCode : (logFailed ? 1 : 0);
|
|
95
|
-
}
|
|
96
|
-
} catch (Exception error) { WriteLog("launcher", error.ToString()); return 1; }
|
|
97
|
-
}
|
|
98
|
-
} catch { return 1; } // An unwritable log directory is also a failed task, not a silent success.
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
`;
|
|
102
|
-
const digest = createHash("sha256").update(source).digest("hex").slice(0, 20);
|
|
103
|
-
const path = win32.join(paths.profileDir, "autostart", `launcher-${digest}.exe`);
|
|
104
|
-
const sourceBase64 = Buffer.from(source, "utf8").toString("base64");
|
|
105
|
-
const compileScript = `$launcherPath = '${path.replaceAll("'", "''")}';
|
|
106
|
-
if (!(Test-Path -LiteralPath $launcherPath -PathType Leaf)) {
|
|
107
|
-
[System.IO.Directory]::CreateDirectory([System.IO.Path]::GetDirectoryName($launcherPath)) | Out-Null;
|
|
108
|
-
$candidate = $launcherPath + '.' + [guid]::NewGuid().ToString('N') + '.tmp.exe';
|
|
109
|
-
try {
|
|
110
|
-
$source = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${sourceBase64}'));
|
|
111
|
-
Add-Type -TypeDefinition $source -OutputAssembly $candidate -OutputType WindowsApplication -ErrorAction Stop;
|
|
112
|
-
Move-Item -LiteralPath $candidate -Destination $launcherPath -ErrorAction Stop;
|
|
113
|
-
} finally {
|
|
114
|
-
if (Test-Path -LiteralPath $candidate) { Remove-Item -LiteralPath $candidate -Force; }
|
|
115
|
-
}
|
|
116
|
-
}`;
|
|
117
|
-
return { path, logPath, source, compileScript };
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
// src/common/service-autostart.ts
|
|
121
|
-
function checkText(value) {
|
|
122
|
-
if ([...value].some((char) => char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127)) {
|
|
123
|
-
throw new Error("Autostart paths and environment must not contain control characters");
|
|
124
|
-
}
|
|
125
|
-
return value;
|
|
126
|
-
}
|
|
127
|
-
function xml(value) {
|
|
128
|
-
return checkText(value).replace(
|
|
129
|
-
/[&<>"']/g,
|
|
130
|
-
(char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]
|
|
131
|
-
);
|
|
132
|
-
}
|
|
133
|
-
function unitString(value) {
|
|
134
|
-
return `"${checkText(value).replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("%", "%%")}"`;
|
|
135
|
-
}
|
|
136
|
-
function psString(value) {
|
|
137
|
-
return `'${checkText(value).replaceAll("'", "''")}'`;
|
|
138
|
-
}
|
|
139
|
-
function encodePowerShell(script) {
|
|
140
|
-
return Buffer.from(script, "utf16le").toString("base64");
|
|
141
|
-
}
|
|
142
|
-
async function readIfPresent(path) {
|
|
143
|
-
try {
|
|
144
|
-
return await readFile(path, "utf8");
|
|
145
|
-
} catch (error) {
|
|
146
|
-
if (error.code === "ENOENT") return null;
|
|
147
|
-
throw error;
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
async function removeIfPresent(path) {
|
|
151
|
-
try {
|
|
152
|
-
await unlink(path);
|
|
153
|
-
} catch (error) {
|
|
154
|
-
if (error.code !== "ENOENT") throw error;
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
var execFileAsync = promisify(execFile);
|
|
158
|
-
function createServiceAutostart(options) {
|
|
159
|
-
const { platform, home, profile, executable, env } = options;
|
|
160
|
-
if (!["darwin", "linux", "win32"].includes(platform)) {
|
|
161
|
-
throw new Error(`Proxy autostart is not supported on ${platform}`);
|
|
162
|
-
}
|
|
163
|
-
const identity = createHash2("sha256").update(`${home}\0${profile}`).digest("hex").slice(0, 20);
|
|
164
|
-
const label = `dev-anywhere-${identity}`;
|
|
165
|
-
const args = [...options.args, "--profile", profile, "serve", "autostart", "run"];
|
|
166
|
-
const run = options.run ?? (async (command, commandArgs) => {
|
|
167
|
-
const result = await execFileAsync(command, commandArgs, {
|
|
168
|
-
timeout: 15e3,
|
|
169
|
-
maxBuffer: 256 * 1024,
|
|
170
|
-
windowsHide: true,
|
|
171
|
-
encoding: "utf8"
|
|
172
|
-
});
|
|
173
|
-
return result.stdout;
|
|
174
|
-
});
|
|
175
|
-
const powershell = win322.join(
|
|
176
|
-
env.SystemRoot ?? env.SYSTEMROOT ?? "C:\\Windows",
|
|
177
|
-
"System32",
|
|
178
|
-
"WindowsPowerShell",
|
|
179
|
-
"v1.0",
|
|
180
|
-
"powershell.exe"
|
|
181
|
-
);
|
|
182
|
-
const runPowerShell = (script) => run(powershell, [
|
|
183
|
-
"-NoProfile",
|
|
184
|
-
"-NonInteractive",
|
|
185
|
-
"-EncodedCommand",
|
|
186
|
-
encodePowerShell(`$ErrorActionPreference = 'Stop';
|
|
187
|
-
${script}`)
|
|
188
|
-
]);
|
|
189
|
-
const taskLookup = `$task = Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskPath -eq '\\' -and $_.TaskName -eq ${psString(label)} };`;
|
|
190
|
-
const unit = `${label}.service`;
|
|
191
|
-
const filePath = platform === "darwin" ? join(home, "Library", "LaunchAgents", `${label}.plist`) : join(env.XDG_CONFIG_HOME || join(home, ".config"), "systemd", "user", unit);
|
|
192
|
-
const domain = `gui/${options.uid}`;
|
|
193
|
-
const launchdTarget = `${domain}/${label}`;
|
|
194
|
-
const environment = {
|
|
195
|
-
HOME: checkText(home),
|
|
196
|
-
...Object.fromEntries(
|
|
197
|
-
["PATH", "SHELL"].flatMap((key) => env[key] ? [[key, checkText(env[key])]] : [])
|
|
198
|
-
)
|
|
199
|
-
};
|
|
200
|
-
function definition() {
|
|
201
|
-
if (platform === "darwin") {
|
|
202
|
-
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
203
|
-
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
204
|
-
<plist version="1.0"><dict>
|
|
205
|
-
<key>Label</key><string>${xml(label)}</string>
|
|
206
|
-
<key>ProgramArguments</key><array>${[executable, ...args].map((arg) => `<string>${xml(arg)}</string>`).join("")}</array>
|
|
207
|
-
<key>WorkingDirectory</key><string>${xml(home)}</string>
|
|
208
|
-
<key>EnvironmentVariables</key><dict>${Object.entries(environment).map(([key, value]) => `<key>${xml(key)}</key><string>${xml(value)}</string>`).join("")}</dict>
|
|
209
|
-
<key>RunAtLoad</key><true/>
|
|
210
|
-
<key>KeepAlive</key><false/>
|
|
211
|
-
</dict></plist>
|
|
212
|
-
`;
|
|
213
|
-
}
|
|
214
|
-
return `[Unit]
|
|
215
|
-
Description=DEV Anywhere Proxy (${checkText(profile)})
|
|
216
|
-
|
|
217
|
-
[Service]
|
|
218
|
-
Type=oneshot
|
|
219
|
-
RemainAfterExit=yes
|
|
220
|
-
Restart=no
|
|
221
|
-
WorkingDirectory=${unitString(home)}
|
|
222
|
-
${Object.entries(environment).map(([key, value]) => `Environment=${unitString(`${key}=${value}`)}`).join("\n")}
|
|
223
|
-
ExecStart=:${[executable, ...args, "--daemon"].map(unitString).join(" ")}
|
|
224
|
-
TimeoutStartSec=60
|
|
225
|
-
|
|
226
|
-
[Install]
|
|
227
|
-
WantedBy=default.target
|
|
228
|
-
`;
|
|
229
|
-
}
|
|
230
|
-
function windowsTask() {
|
|
231
|
-
const launcher = buildWindowsAutostartLauncher({ home, profile, executable, args });
|
|
232
|
-
return `${launcher.compileScript}
|
|
233
|
-
$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name;
|
|
234
|
-
$action = New-ScheduledTaskAction -Execute ${psString(launcher.path)} -WorkingDirectory ${psString(home)};
|
|
235
|
-
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $user;
|
|
236
|
-
$principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited;
|
|
237
|
-
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew -Priority 4;
|
|
238
|
-
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;`;
|
|
239
|
-
}
|
|
240
|
-
async function status() {
|
|
241
|
-
if (platform === "win32") {
|
|
242
|
-
const output2 = await runPowerShell(
|
|
243
|
-
`${taskLookup}
|
|
244
|
-
[bool]($task -and $task.Settings.Enabled) | ConvertTo-Json -Compress;`
|
|
245
|
-
);
|
|
246
|
-
const enabled = JSON.parse(output2.trim());
|
|
247
|
-
if (typeof enabled !== "boolean") throw new Error("Invalid Windows autostart status");
|
|
248
|
-
return enabled;
|
|
249
|
-
}
|
|
250
|
-
if (await readIfPresent(filePath) === null) return false;
|
|
251
|
-
if (platform === "darwin") {
|
|
252
|
-
if (options.uid === void 0) throw new Error("Cannot determine the current macOS user");
|
|
253
|
-
const output2 = await run("/bin/launchctl", ["print-disabled", domain]);
|
|
254
|
-
return !output2.includes(`"${label}" => true`);
|
|
255
|
-
}
|
|
256
|
-
const output = await run("systemctl", [
|
|
257
|
-
"--user",
|
|
258
|
-
"show",
|
|
259
|
-
unit,
|
|
260
|
-
"--property=UnitFileState",
|
|
261
|
-
"--value"
|
|
262
|
-
]);
|
|
263
|
-
return output.trim() === "enabled";
|
|
264
|
-
}
|
|
265
|
-
async function enable() {
|
|
266
|
-
if (platform === "win32") {
|
|
267
|
-
await runPowerShell(windowsTask());
|
|
268
|
-
return;
|
|
269
|
-
}
|
|
270
|
-
if (platform === "darwin" && options.uid === void 0) {
|
|
271
|
-
throw new Error("Cannot determine the current macOS user");
|
|
272
|
-
}
|
|
273
|
-
const content = definition();
|
|
274
|
-
await mkdir(dirname(filePath), { recursive: true });
|
|
275
|
-
const previous = await readIfPresent(filePath);
|
|
276
|
-
await writeFile(filePath, content, { mode: 384 });
|
|
277
|
-
try {
|
|
278
|
-
if (platform === "darwin") {
|
|
279
|
-
await run("/bin/launchctl", ["enable", launchdTarget]);
|
|
280
|
-
} else {
|
|
281
|
-
await run("systemctl", ["--user", "daemon-reload"]);
|
|
282
|
-
await run("systemctl", ["--user", "enable", unit]);
|
|
283
|
-
}
|
|
284
|
-
} catch (error) {
|
|
285
|
-
if (previous === null) await removeIfPresent(filePath);
|
|
286
|
-
else await writeFile(filePath, previous, { mode: 384 });
|
|
287
|
-
throw error;
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
async function disable() {
|
|
291
|
-
if (platform === "win32") {
|
|
292
|
-
await runPowerShell(
|
|
293
|
-
`${taskLookup}
|
|
294
|
-
if ($task) { $task | Unregister-ScheduledTask -Confirm:$false; }`
|
|
295
|
-
);
|
|
296
|
-
return;
|
|
297
|
-
}
|
|
298
|
-
if (await readIfPresent(filePath) === null) return;
|
|
299
|
-
if (platform === "darwin") {
|
|
300
|
-
if (options.uid === void 0) throw new Error("Cannot determine the current macOS user");
|
|
301
|
-
await run("/bin/launchctl", ["disable", launchdTarget]);
|
|
302
|
-
} else {
|
|
303
|
-
await run("systemctl", ["--user", "disable", unit]);
|
|
304
|
-
}
|
|
305
|
-
await removeIfPresent(filePath);
|
|
306
|
-
if (platform === "linux") await run("systemctl", ["--user", "daemon-reload"]);
|
|
307
|
-
}
|
|
308
|
-
return { enable, disable, status };
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
// src/autostart.ts
|
|
312
|
-
async function runAutostartCommand(action) {
|
|
313
|
-
try {
|
|
314
|
-
if (action === "enable" && !isInitialized()) {
|
|
315
|
-
throw new Error('Dev Anywhere is not initialized. Run "dev-anywhere init" first.');
|
|
316
|
-
}
|
|
317
|
-
const entry = `${fileURLToPath(resolveTopLevelScript("index"))}${IS_DEV ? ".ts" : ".js"}`;
|
|
318
|
-
const autostart = createServiceAutostart({
|
|
319
|
-
platform: process.platform,
|
|
320
|
-
home: homedir(),
|
|
321
|
-
profile: PROFILE_NAME,
|
|
322
|
-
executable: process.execPath,
|
|
323
|
-
args: IS_DEV ? ["--import", import.meta.resolve("tsx"), entry] : [entry],
|
|
324
|
-
env: { ...process.env, SHELL: process.env.SHELL ?? userInfo().shell ?? void 0 },
|
|
325
|
-
uid: process.getuid?.()
|
|
326
|
-
});
|
|
327
|
-
if (action === "status") {
|
|
328
|
-
console.log(
|
|
329
|
-
`${PROFILE_NAME}: ${await autostart.status() ? "\u5DF2\u8BBE\u7F6E\u767B\u5F55\u540E\u81EA\u52A8\u542F\u52A8" : "\u672A\u8BBE\u7F6E\u81EA\u52A8\u542F\u52A8"}`
|
|
330
|
-
);
|
|
331
|
-
return;
|
|
332
|
-
}
|
|
333
|
-
await autostart[action]();
|
|
334
|
-
console.log(
|
|
335
|
-
action === "enable" ? `${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`
|
|
336
|
-
);
|
|
337
|
-
} catch (error) {
|
|
338
|
-
console.error(getErrorMessage(error));
|
|
339
|
-
process.exitCode = 1;
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
async function startAutostartService(daemon) {
|
|
343
|
-
try {
|
|
344
|
-
if (!isInitialized()) throw new Error("Proxy configuration is missing");
|
|
345
|
-
if (process.platform !== "win32") {
|
|
346
|
-
const refreshed = await refreshLoginShellPath({
|
|
347
|
-
env: { ...process.env, SHELL: process.env.SHELL ?? userInfo().shell ?? void 0 }
|
|
348
|
-
});
|
|
349
|
-
if (refreshed.path !== void 0) process.env.PATH = refreshed.path;
|
|
350
|
-
}
|
|
351
|
-
const lifecycle = createProfileServiceLifecycle();
|
|
352
|
-
if (daemon) await lifecycle.start("explicit");
|
|
353
|
-
else
|
|
354
|
-
await lifecycle.startForeground(async () => {
|
|
355
|
-
const { startService } = await import("./serve.js");
|
|
356
|
-
await startService();
|
|
357
|
-
});
|
|
358
|
-
} catch (error) {
|
|
359
|
-
const { serviceLogger } = await import("./logger-XEIQC6K6.js");
|
|
360
|
-
const { flushLogger } = await import("./logger-24TGGN76.js");
|
|
361
|
-
serviceLogger.error({ err: getErrorMessage(error) }, "Proxy login startup failed");
|
|
362
|
-
await flushLogger(serviceLogger);
|
|
363
|
-
process.exit(1);
|
|
364
|
-
}
|
|
365
|
-
}
|
|
366
|
-
export {
|
|
367
|
-
runAutostartCommand,
|
|
368
|
-
startAutostartService
|
|
369
|
-
};
|
|
370
|
-
//# sourceMappingURL=autostart-GMEGJAZJ.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/autostart.ts","../src/common/service-autostart.ts","../src/common/windows-autostart-launcher.ts"],"sourcesContent":["import { homedir, userInfo } from \"node:os\";\nimport { fileURLToPath } from \"node:url\";\nimport { IS_DEV, resolveTopLevelScript } from \"./common/env.js\";\nimport { isInitialized, PROFILE_NAME } from \"./common/paths.js\";\nimport { createServiceAutostart } from \"./common/service-autostart.js\";\nimport { createProfileServiceLifecycle } from \"./common/profile-service.js\";\nimport { refreshLoginShellPath } from \"./common/login-shell-path.js\";\nimport { getErrorMessage } from \"./common/process-probe.js\";\n\nexport async function runAutostartCommand(action: \"enable\" | \"disable\" | \"status\"): Promise<void> {\n try {\n if (action === \"enable\" && !isInitialized()) {\n throw new Error('Dev Anywhere is not initialized. Run \"dev-anywhere init\" first.');\n }\n const entry = `${fileURLToPath(resolveTopLevelScript(\"index\"))}${IS_DEV ? \".ts\" : \".js\"}`;\n const autostart = createServiceAutostart({\n platform: process.platform,\n home: homedir(),\n profile: PROFILE_NAME,\n executable: process.execPath,\n args: IS_DEV ? [\"--import\", import.meta.resolve(\"tsx\"), entry] : [entry],\n env: { ...process.env, SHELL: process.env.SHELL ?? userInfo().shell ?? undefined },\n uid: process.getuid?.(),\n });\n if (action === \"status\") {\n console.log(\n `${PROFILE_NAME}: ${(await autostart.status()) ? \"已设置登录后自动启动\" : \"未设置自动启动\"}`,\n );\n return;\n }\n await autostart[action]();\n console.log(\n action === \"enable\"\n ? `${PROFILE_NAME}: 已设置登录后自动启动,当前 Proxy 不受影响。`\n : `${PROFILE_NAME}: 已取消自动启动,当前 Proxy 不受影响。`,\n );\n } catch (error) {\n console.error(getErrorMessage(error));\n process.exitCode = 1;\n }\n}\n\n/** System login triggers enter the same lifecycle controller as manual CLI commands. */\nexport async function startAutostartService(daemon: boolean): Promise<void> {\n try {\n if (!isInitialized()) throw new Error(\"Proxy configuration is missing\");\n if (process.platform !== \"win32\") {\n const refreshed = await refreshLoginShellPath({\n env: { ...process.env, SHELL: process.env.SHELL ?? userInfo().shell ?? undefined },\n });\n if (refreshed.path !== undefined) process.env.PATH = refreshed.path;\n }\n const lifecycle = createProfileServiceLifecycle();\n if (daemon) await lifecycle.start(\"explicit\");\n else\n await lifecycle.startForeground(async () => {\n const { startService } = await import(\"./serve.js\");\n await startService();\n });\n } catch (error) {\n const { serviceLogger } = await import(\"./common/logger.js\");\n const { flushLogger } = await import(\"@dev-anywhere/shared/logger\");\n serviceLogger.error({ err: getErrorMessage(error) }, \"Proxy login startup failed\");\n await flushLogger(serviceLogger);\n process.exit(1);\n }\n}\n","import { execFile } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { mkdir, readFile, unlink, writeFile } from \"node:fs/promises\";\nimport { dirname, join, win32 } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { buildWindowsAutostartLauncher } from \"./windows-autostart-launcher.js\";\n\ninterface AutostartOptions {\n platform: NodeJS.Platform;\n home: string;\n profile: string;\n executable: string;\n /** Absolute CLI entry and any runtime arguments (e.g. the source-mode TS loader). */\n args: string[];\n env: NodeJS.ProcessEnv;\n uid?: number;\n run?: (command: string, args: string[]) => Promise<string>;\n}\n\nfunction checkText(value: string): string {\n if ([...value].some((char) => char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127)) {\n throw new Error(\"Autostart paths and environment must not contain control characters\");\n }\n return value;\n}\n\nfunction xml(value: string): string {\n return checkText(value).replace(\n /[&<>\"']/g,\n (char) => ({ \"&\": \"&\", \"<\": \"<\", \">\": \">\", '\"': \""\", \"'\": \"'\" })[char]!,\n );\n}\n\nfunction unitString(value: string): string {\n return `\"${checkText(value).replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"').replaceAll(\"%\", \"%%\")}\"`;\n}\n\nfunction psString(value: string): string {\n return `'${checkText(value).replaceAll(\"'\", \"''\")}'`;\n}\n\nfunction encodePowerShell(script: string): string {\n return Buffer.from(script, \"utf16le\").toString(\"base64\");\n}\n\nasync function readIfPresent(path: string): Promise<string | null> {\n try {\n return await readFile(path, \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw error;\n }\n}\n\nasync function removeIfPresent(path: string): Promise<void> {\n try {\n await unlink(path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n}\n\nconst execFileAsync = promisify(execFile);\n\n/** Registers a login trigger, not another process supervisor. Enabling never restarts a Proxy. */\nexport function createServiceAutostart(options: AutostartOptions) {\n const { platform, home, profile, executable, env } = options;\n if (![\"darwin\", \"linux\", \"win32\"].includes(platform)) {\n throw new Error(`Proxy autostart is not supported on ${platform}`);\n }\n const identity = createHash(\"sha256\").update(`${home}\\0${profile}`).digest(\"hex\").slice(0, 20);\n const label = `dev-anywhere-${identity}`;\n const args = [...options.args, \"--profile\", profile, \"serve\", \"autostart\", \"run\"];\n const run =\n options.run ??\n (async (command: string, commandArgs: string[]) => {\n const result = await execFileAsync(command, commandArgs, {\n timeout: 15_000,\n maxBuffer: 256 * 1024,\n windowsHide: true,\n encoding: \"utf8\",\n });\n return result.stdout;\n });\n const powershell = win32.join(\n env.SystemRoot ?? env.SYSTEMROOT ?? \"C:\\\\Windows\",\n \"System32\",\n \"WindowsPowerShell\",\n \"v1.0\",\n \"powershell.exe\",\n );\n const runPowerShell = (script: string) =>\n run(powershell, [\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-EncodedCommand\",\n encodePowerShell(`$ErrorActionPreference = 'Stop';\\n${script}`),\n ]);\n const taskLookup = `$task = Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskPath -eq '\\\\' -and $_.TaskName -eq ${psString(label)} };`;\n const unit = `${label}.service`;\n const filePath =\n platform === \"darwin\"\n ? join(home, \"Library\", \"LaunchAgents\", `${label}.plist`)\n : join(env.XDG_CONFIG_HOME || join(home, \".config\"), \"systemd\", \"user\", unit);\n const domain = `gui/${options.uid}`;\n const launchdTarget = `${domain}/${label}`;\n\n const environment = {\n HOME: checkText(home),\n ...Object.fromEntries(\n [\"PATH\", \"SHELL\"].flatMap((key) => (env[key] ? [[key, checkText(env[key]!)]] : [])),\n ),\n };\n\n function definition(): string {\n if (platform === \"darwin\") {\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\"><dict>\n<key>Label</key><string>${xml(label)}</string>\n<key>ProgramArguments</key><array>${[executable, ...args].map((arg) => `<string>${xml(arg)}</string>`).join(\"\")}</array>\n<key>WorkingDirectory</key><string>${xml(home)}</string>\n<key>EnvironmentVariables</key><dict>${Object.entries(environment)\n .map(([key, value]) => `<key>${xml(key)}</key><string>${xml(value)}</string>`)\n .join(\"\")}</dict>\n<key>RunAtLoad</key><true/>\n<key>KeepAlive</key><false/>\n</dict></plist>\n`;\n }\n // Keep the unit active after the short-lived start command exits. Otherwise systemd would\n // terminate the detached Proxy (and its updater) along with that command's control group.\n return `[Unit]\nDescription=DEV Anywhere Proxy (${checkText(profile)})\n\n[Service]\nType=oneshot\nRemainAfterExit=yes\nRestart=no\nWorkingDirectory=${unitString(home)}\n${Object.entries(environment)\n .map(([key, value]) => `Environment=${unitString(`${key}=${value}`)}`)\n .join(\"\\n\")}\nExecStart=:${[executable, ...args, \"--daemon\"].map(unitString).join(\" \")}\nTimeoutStartSec=60\n\n[Install]\nWantedBy=default.target\n`;\n }\n\n function windowsTask(): string {\n const launcher = buildWindowsAutostartLauncher({ home, profile, executable, args });\n return `${launcher.compileScript}\n$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name;\n$action = New-ScheduledTaskAction -Execute ${psString(launcher.path)} -WorkingDirectory ${psString(home)};\n$trigger = New-ScheduledTaskTrigger -AtLogOn -User $user;\n$principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited;\n$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew -Priority 4;\nRegister-ScheduledTask -TaskPath '\\\\' -TaskName ${psString(label)} -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description 'DEV Anywhere Proxy: start at user login' -Force | Out-Null;`;\n }\n\n async function status(): Promise<boolean> {\n if (platform === \"win32\") {\n const output = await runPowerShell(\n `${taskLookup}\\n[bool]($task -and $task.Settings.Enabled) | ConvertTo-Json -Compress;`,\n );\n const enabled: unknown = JSON.parse(output.trim());\n if (typeof enabled !== \"boolean\") throw new Error(\"Invalid Windows autostart status\");\n return enabled;\n }\n if ((await readIfPresent(filePath)) === null) return false;\n if (platform === \"darwin\") {\n if (options.uid === undefined) throw new Error(\"Cannot determine the current macOS user\");\n const output = await run(\"/bin/launchctl\", [\"print-disabled\", domain]);\n return !output.includes(`\"${label}\" => true`);\n }\n const output = await run(\"systemctl\", [\n \"--user\",\n \"show\",\n unit,\n \"--property=UnitFileState\",\n \"--value\",\n ]);\n return output.trim() === \"enabled\";\n }\n\n async function enable(): Promise<void> {\n if (platform === \"win32\") {\n await runPowerShell(windowsTask());\n return;\n }\n if (platform === \"darwin\" && options.uid === undefined) {\n throw new Error(\"Cannot determine the current macOS user\");\n }\n const content = definition();\n await mkdir(dirname(filePath), { recursive: true });\n const previous = await readIfPresent(filePath);\n await writeFile(filePath, content, { mode: 0o600 });\n try {\n if (platform === \"darwin\") {\n // No bootstrap/kickstart: registration takes effect at the next login, without touching\n // a running Proxy. An existing system-disabled override must not defeat re-enabling.\n await run(\"/bin/launchctl\", [\"enable\", launchdTarget]);\n } else {\n await run(\"systemctl\", [\"--user\", \"daemon-reload\"]);\n await run(\"systemctl\", [\"--user\", \"enable\", unit]);\n }\n } catch (error) {\n if (previous === null) await removeIfPresent(filePath);\n else await writeFile(filePath, previous, { mode: 0o600 });\n throw error;\n }\n }\n\n async function disable(): Promise<void> {\n if (platform === \"win32\") {\n await runPowerShell(\n `${taskLookup}\\nif ($task) { $task | Unregister-ScheduledTask -Confirm:$false; }`,\n );\n return;\n }\n if ((await readIfPresent(filePath)) === null) return;\n if (platform === \"darwin\") {\n if (options.uid === undefined) throw new Error(\"Cannot determine the current macOS user\");\n await run(\"/bin/launchctl\", [\"disable\", launchdTarget]);\n } else {\n await run(\"systemctl\", [\"--user\", \"disable\", unit]);\n }\n await removeIfPresent(filePath);\n if (platform === \"linux\") await run(\"systemctl\", [\"--user\", \"daemon-reload\"]);\n // Never bootout, stop, or unregister with process termination: disabling only affects login.\n }\n\n return { enable, disable, status };\n}\n","import { createHash } from \"node:crypto\";\nimport { win32 } from \"node:path\";\nimport { quoteWindowsArgument } from \"./command-launch.js\";\nimport { buildProxyProfilePaths } from \"./paths.js\";\n\nfunction encodedString(value: string): string {\n if ([...value].some((char) => char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127)) {\n throw new Error(\"Autostart paths and environment must not contain control characters\");\n }\n return `Decode(\"${Buffer.from(value, \"utf8\").toString(\"base64\")}\")`;\n}\n\n/** Compile only during registration; the task runs this GUI executable, never PowerShell. */\nexport function buildWindowsAutostartLauncher(options: {\n home: string;\n profile: string;\n executable: string;\n args: readonly string[];\n}): { path: string; logPath: string; source: string; compileScript: string } {\n const paths = buildProxyProfilePaths(options.home, options.profile, \"win32\");\n const logPath = win32.join(paths.logDir, \"autostart-launcher.log\");\n const source = `using System;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Text;\n\ninternal static class DevAnywhereAutostart {\n private static StreamWriter log;\n private static volatile bool logFailed;\n private static string Decode(string value) { return Encoding.UTF8.GetString(Convert.FromBase64String(value)); }\n private static void WriteLog(string stream, string message) {\n if (message == null) return;\n try { lock (log) { log.WriteLine(DateTime.UtcNow.ToString(\"o\") + \" \" + stream + \": \" + message); } }\n catch { logFailed = true; } // Keep draining output; report logging failures through the task exit code.\n }\n public static int Main() {\n try {\n string logPath = ${encodedString(logPath)};\n Directory.CreateDirectory(Path.GetDirectoryName(logPath));\n using (log = new StreamWriter(new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite), new UTF8Encoding(false))) {\n log.AutoFlush = true;\n try {\n var info = new ProcessStartInfo();\n info.FileName = ${encodedString(options.executable)};\n info.Arguments = ${encodedString(options.args.map(quoteWindowsArgument).join(\" \"))};\n info.WorkingDirectory = ${encodedString(options.home)};\n info.EnvironmentVariables[\"USERPROFILE\"] = ${encodedString(options.home)};\n info.EnvironmentVariables[\"HOME\"] = ${encodedString(options.home)};\n info.UseShellExecute = false;\n info.CreateNoWindow = true;\n info.RedirectStandardInput = true;\n info.RedirectStandardOutput = true;\n info.RedirectStandardError = true;\n info.StandardOutputEncoding = Encoding.UTF8;\n info.StandardErrorEncoding = Encoding.UTF8;\n using (var child = new Process()) {\n child.StartInfo = info;\n child.OutputDataReceived += (sender, e) => WriteLog(\"stdout\", e.Data);\n child.ErrorDataReceived += (sender, e) => WriteLog(\"stderr\", e.Data);\n child.Start();\n child.StandardInput.Close();\n child.BeginOutputReadLine();\n child.BeginErrorReadLine();\n child.WaitForExit();\n return child.ExitCode != 0 ? child.ExitCode : (logFailed ? 1 : 0);\n }\n } catch (Exception error) { WriteLog(\"launcher\", error.ToString()); return 1; }\n }\n } catch { return 1; } // An unwritable log directory is also a failed task, not a silent success.\n }\n}\n`;\n const digest = createHash(\"sha256\").update(source).digest(\"hex\").slice(0, 20);\n const path = win32.join(paths.profileDir, \"autostart\", `launcher-${digest}.exe`);\n // The source contains only encoded paths/argv, not credentials or a snapshot of the user's env.\n const sourceBase64 = Buffer.from(source, \"utf8\").toString(\"base64\");\n const compileScript = `$launcherPath = '${path.replaceAll(\"'\", \"''\")}';\nif (!(Test-Path -LiteralPath $launcherPath -PathType Leaf)) {\n [System.IO.Directory]::CreateDirectory([System.IO.Path]::GetDirectoryName($launcherPath)) | Out-Null;\n $candidate = $launcherPath + '.' + [guid]::NewGuid().ToString('N') + '.tmp.exe';\n try {\n $source = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${sourceBase64}'));\n Add-Type -TypeDefinition $source -OutputAssembly $candidate -OutputType WindowsApplication -ErrorAction Stop;\n Move-Item -LiteralPath $candidate -Destination $launcherPath -ErrorAction Stop;\n } finally {\n if (Test-Path -LiteralPath $candidate) { Remove-Item -LiteralPath $candidate -Force; }\n }\n}`;\n return { path, logPath, source, compileScript };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS,gBAAgB;AAClC,SAAS,qBAAqB;;;ACD9B,SAAS,gBAAgB;AACzB,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,OAAO,UAAU,QAAQ,iBAAiB;AACnD,SAAS,SAAS,MAAM,SAAAC,cAAa;AACrC,SAAS,iBAAiB;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
|
|
1
|
-
{"version":3,"sources":["../src/common/file-lock.ts","../src/common/socket-connect.ts"],"sourcesContent":["import { closeSync, constants, mkdirSync, openSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { tryLock } from \"fs-native-extensions\";\n\nexport interface FileLock {\n release(): void;\n}\n\n/** The file stays in place: replacing its inode would allow two independent locks. */\nexport function tryAcquireFileLock(path: string): FileLock | null {\n mkdirSync(dirname(path), { recursive: true });\n const fd = openSync(path, constants.O_CREAT | constants.O_RDWR, 0o600);\n let acquired: boolean;\n try {\n acquired = tryLock(fd);\n } catch (error) {\n closeSync(fd);\n throw error;\n }\n if (!acquired) {\n closeSync(fd);\n return null;\n }\n\n let released = false;\n return {\n release() {\n if (released) return;\n released = true;\n closeSync(fd);\n },\n };\n}\n\nexport async function acquireFileLock(\n path: string,\n options: { timeoutMs?: number; pollMs?: number } = {},\n): Promise<FileLock> {\n const { timeoutMs = 10_000, pollMs = 25 } = options;\n if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {\n throw new RangeError(\"File lock timeout must be a finite non-negative number\");\n }\n if (!Number.isFinite(pollMs) || pollMs <= 0) {\n throw new RangeError(\"File lock polling interval must be a finite positive number\");\n }\n\n const deadline = performance.now() + timeoutMs;\n while (true) {\n const lock = tryAcquireFileLock(path);\n if (lock) return lock;\n const remainingMs = deadline - performance.now();\n if (remainingMs <= 0) throw new Error(`Timed out waiting for file lock: ${path}`);\n await sleep(Math.min(pollMs, remainingMs));\n }\n}\n","import { connect, type Socket } from \"node:net\";\n\nconst DEFAULT_CONNECT_TIMEOUT_MS = 1_000;\n\n/** Only an absent listener is null; an unknown or inaccessible service must not be replaced. */\nexport function tryConnectSocket(\n socketPath: string,\n timeoutMs = DEFAULT_CONNECT_TIMEOUT_MS,\n): Promise<Socket | null> {\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n return Promise.reject(new TypeError(\"Invalid socket connection timeout\"));\n }\n return new Promise((resolve, reject) => {\n let socket: Socket;\n try {\n socket = connect(socketPath);\n } catch (error) {\n reject(error);\n return;\n }\n\n let settled = false;\n const timer = setTimeout(\n () => finish(null, new Error(\"Service socket connection timed out\")),\n timeoutMs,\n );\n const onConnect = () => finish(socket);\n const onError = (error: NodeJS.ErrnoException) =>\n finish(null, error.code === \"ENOENT\" || error.code === \"ECONNREFUSED\" ? undefined : error);\n const cleanup = () => {\n clearTimeout(timer);\n socket.off(\"connect\", onConnect);\n socket.off(\"error\", onError);\n };\n const finish = (result: Socket | null, error?: Error) => {\n if (settled) return;\n settled = true;\n cleanup();\n if (!result) socket.destroy();\n if (error) reject(error);\n else resolve(result);\n };\n socket.once(\"connect\", onConnect);\n socket.once(\"error\", onError);\n });\n}\n"],"mappings":";;;AAAA,SAAS,WAAW,WAAW,WAAW,gBAAgB;AAC1D,SAAS,eAAe;AACxB,SAAS,cAAc,aAAa;AACpC,SAAS,eAAe;AAOjB,SAAS,mBAAmB,MAA+B;AAChE,YAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAC5C,QAAM,KAAK,SAAS,MAAM,UAAU,UAAU,UAAU,QAAQ,GAAK;AACrE,MAAI;AACJ,MAAI;AACF,eAAW,QAAQ,EAAE;AAAA,EACvB,SAAS,OAAO;AACd,cAAU,EAAE;AACZ,UAAM;AAAA,EACR;AACA,MAAI,CAAC,UAAU;AACb,cAAU,EAAE;AACZ,WAAO;AAAA,EACT;AAEA,MAAI,WAAW;AACf,SAAO;AAAA,IACL,UAAU;AACR,UAAI,SAAU;AACd,iBAAW;AACX,gBAAU,EAAE;AAAA,IACd;AAAA,EACF;AACF;AAEA,eAAsB,gBACpB,MACA,UAAmD,CAAC,GACjC;AACnB,QAAM,EAAE,YAAY,KAAQ,SAAS,GAAG,IAAI;AAC5C,MAAI,CAAC,OAAO,SAAS,SAAS,KAAK,YAAY,GAAG;AAChD,UAAM,IAAI,WAAW,wDAAwD;AAAA,EAC/E;AACA,MAAI,CA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AAQ,MAAM;AAAA,IACrB;AACA,WAAO,KAAK,WAAW,SAAS;AAChC,WAAO,KAAK,SAAS,OAAO;AAAA,EAC9B,CAAC;AACH;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/common/daemon-env.ts","../src/common/service-lifecycle.ts","../src/common/profile-service.ts"],"sourcesContent":["import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { DESIRED_RELAY_PATH } from \"./paths.js\";\n\nexport function setDesiredDaemonRelay(relayName: string | undefined): void {\n const normalized = relayName?.trim();\n if (normalized) {\n mkdirSync(dirname(DESIRED_RELAY_PATH), { recursive: true });\n writeFileSync(DESIRED_RELAY_PATH, `${normalized}\\n`);\n return;\n }\n try {\n unlinkSync(DESIRED_RELAY_PATH);\n } catch {\n // Missing desired-relay file means \"use the selected profile's relay\".\n }\n}\n\nfunction readDesiredDaemonRelay(): string | undefined {\n if (!existsSync(DESIRED_RELAY_PATH)) return undefined;\n const value = readFileSync(DESIRED_RELAY_PATH, \"utf-8\").trim();\n return value || undefined;\n}\n\nexport function daemonRelayArgs(relayName?: string): string[] {\n const selected = relayName?.trim() || readDesiredDaemonRelay();\n return selected ? [\"--relay\", selected] : [];\n}\n","import type { ChildProcess } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { acquireFileLock, tryAcquireFileLock } from \"./file-lock.js\";\nimport { requestServiceControl, type ServiceStatus } from \"./service-control.js\";\nimport { tryConnectSocket } from \"./socket-connect.js\";\n\nexport type ServiceLifecycleErrorCode =\n | \"STOP_FAILED\"\n | \"START_FAILED\"\n | \"STOPPED\"\n | \"UNSUPPORTED_SERVICE\";\n\nexport class ServiceLifecycleError extends Error {\n recoveryToken?: string;\n\n constructor(\n readonly code: ServiceLifecycleErrorCode,\n message: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = \"ServiceLifecycleError\";\n }\n}\n\nexport interface ServiceLifecycleOptions {\n profile: string;\n controlPath: string;\n socketPath: string;\n runtimeLockPath: string;\n operationLockPath: string;\n stoppedPath: string;\n spawn(): ChildProcess;\n startupTimeoutMs?: number;\n stopTimeoutMs?: number;\n}\n\nexport interface ServiceReadyResult {\n status: \"ready\";\n service: ServiceStatus;\n}\n\nexport interface ServiceLifecycle {\n status(): Promise<ServiceStatus | null>;\n start(intent: \"explicit\" | \"recover\", expectedStoppedToken?: string): Promise<ServiceReadyResult>;\n startForeground(start: () => Promise<void>): Promise<ServiceReadyResult>;\n stop(): Promise<void>;\n restart(intent?: \"explicit\" | \"recover\"): Promise<ServiceReadyResult>;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction runtimeIsFree(path: string): boolean {\n const lock = tryAcquireFileLock(path);\n if (!lock) return false;\n lock.release();\n return true;\n}\n\nasync function socketIsOccupied(path: string, timeoutMs: number): Promise<boolean> {\n const socket = await tryConnectSocket(path, timeoutMs);\n socket?.destroy();\n return socket !== null;\n}\n\nfunction childHasExited(child: ChildProcess): boolean {\n return child.exitCode !== null || child.signalCode !== null;\n}\n\nasync function stopOwnChild(child: ChildProcess): Promise<void> {\n if (!child.pid || childHasExited(child)) return;\n for (const [signal, timeoutMs] of [\n [\"SIGTERM\", 2_000],\n [\"SIGKILL\", 1_000],\n ] as const) {\n const exited = await new Promise<boolean>((resolve, reject) => {\n let timer: NodeJS.Timeout | undefined;\n const finish = (value: boolean) => {\n if (timer) clearTimeout(timer);\n child.off(\"exit\", onExit);\n resolve(value);\n };\n const onExit = () => finish(true);\n child.once(\"exit\", onExit);\n try {\n child.kill(signal);\n } catch (error) {\n child.off(\"exit\", onExit);\n if (childHasExited(child)) resolve(true);\n else reject(error);\n return;\n }\n if (childHasExited(child)) finish(true);\n else timer = setTimeout(() => finish(false), timeoutMs);\n });\n if (exited) return;\n }\n throw new Error(\"The service child did not exit after termination\");\n}\n\nexport function createServiceLifecycle(options: ServiceLifecycleOptions): ServiceLifecycle {\n const startupTimeoutMs = options.startupTimeoutMs ?? 30_000;\n const stopTimeoutMs = options.stopTimeoutMs ?? 10_000;\n for (const timeout of [startupTimeoutMs, stopTimeoutMs]) {\n if (!Number.isFinite(timeout) || timeout <= 0) throw new TypeError(\"Invalid service timeout\");\n }\n if (options.runtimeLockPath === options.operationLockPath) {\n throw new TypeError(\"Service operation and runtime locks must be different\");\n }\n\n const control = async (action: \"status\" | \"stop\", timeoutMs = 5_000) => {\n let status;\n try {\n status = await requestServiceControl(options.controlPath, action, timeoutMs);\n } catch (error) {\n throw new ServiceLifecycleError(\"STOP_FAILED\", \"Service control could not be verified\", {\n cause: error,\n });\n }\n if (status && status.profile !== options.profile) {\n throw new ServiceLifecycleError(\"STOP_FAILED\", \"Service control belongs to another profile\");\n }\n return status;\n };\n const budget = (deadline: number) => Math.max(1, Math.min(5_000, deadline - Date.now()));\n const pause = (deadline: number) => sleep(Math.max(1, Math.min(50, deadline - Date.now())));\n const markStopped = () => {\n mkdirSync(dirname(options.stoppedPath), { recursive: true });\n const token = randomUUID();\n writeFileSync(options.stoppedPath, token, { mode: 0o600 });\n return token;\n };\n const stoppedToken = () => {\n try {\n return readFileSync(options.stoppedPath, \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw error;\n }\n };\n const clearStopped = () => {\n try {\n unlinkSync(options.stoppedPath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n };\n const unsupported = () =>\n new ServiceLifecycleError(\n \"UNSUPPORTED_SERVICE\",\n \"An existing service cannot be managed by this version. Stop it using the CLI that started it before retrying.\",\n );\n\n const withOperation = async <T>(run: () => Promise<T>): Promise<T> => {\n let lock;\n try {\n lock = await acquireFileLock(options.operationLockPath, {\n timeoutMs: startupTimeoutMs + stopTimeoutMs,\n });\n } catch (error) {\n throw new ServiceLifecycleError(\"STOP_FAILED\", \"Another service operation is still active\", {\n cause: error,\n });\n }\n try {\n return await run();\n } finally {\n lock.release();\n }\n };\n\n // The runtime lock protects this inspection. It is never transferred to a child: a candidate\n // must acquire its own runtime lock before opening sockets or starting any service work.\n const canStart = async (deadline: number): Promise<boolean> => {\n const runtime = tryAcquireFileLock(options.runtimeLockPath);\n if (!runtime) return false;\n try {\n if (await socketIsOccupied(options.socketPath, budget(deadline))) throw unsupported();\n if (await control(\"status\", budget(deadline))) {\n throw new ServiceLifecycleError(\n \"STOP_FAILED\",\n \"Service control is live without runtime ownership\",\n );\n }\n return true;\n } finally {\n runtime.release();\n }\n };\n\n const startInternal = async (\n intent: \"explicit\" | \"recover\",\n expectedStoppedToken?: string,\n foreground?: () => Promise<void>,\n ): Promise<ServiceReadyResult> => {\n if (expectedStoppedToken !== undefined && stoppedToken() !== expectedStoppedToken) {\n throw new ServiceLifecycleError(\n \"STOPPED\",\n \"The service stop state changed; recovery was cancelled\",\n );\n }\n if (\n intent === \"recover\" &&\n existsSync(options.stoppedPath) &&\n expectedStoppedToken === undefined\n ) {\n throw new ServiceLifecycleError(\"STOPPED\", \"Service was explicitly stopped\");\n }\n if (intent === \"explicit\" || expectedStoppedToken !== undefined) clearStopped();\n\n const deadline = Date.now() + startupTimeoutMs;\n let child: ChildProcess | undefined;\n let childFailure: Error | undefined;\n const onChildError = (error: Error) => {\n childFailure = error;\n };\n try {\n while (Date.now() < deadline) {\n const current = await control(\"status\", budget(deadline));\n if (current?.state === \"ready\") {\n if (runtimeIsFree(options.runtimeLockPath)) {\n throw new ServiceLifecycleError(\n \"STOP_FAILED\",\n \"Service control is live without runtime ownership\",\n );\n }\n return { status: \"ready\", service: current };\n }\n if (childFailure) throw childFailure;\n if (child && childHasExited(child)) {\n throw new Error(\n `Service child exited during startup (code=${child.exitCode}, signal=${child.signalCode})`,\n );\n }\n if (!child && !current && (await canStart(deadline))) {\n if (foreground) {\n let timer: NodeJS.Timeout | undefined;\n try {\n await Promise.race([\n foreground(),\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(\"Foreground service startup timed out\")),\n Math.max(1, deadline - Date.now()),\n );\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n const service = await control(\"status\", budget(deadline));\n if (service?.state !== \"ready\") throw new Error(\"Service did not publish readiness\");\n if (runtimeIsFree(options.runtimeLockPath)) {\n throw new ServiceLifecycleError(\n \"STOP_FAILED\",\n \"Foreground service did not retain runtime ownership\",\n );\n }\n return { status: \"ready\", service };\n }\n child = options.spawn();\n child.once(\"error\", onChildError);\n }\n await pause(deadline);\n }\n throw new Error(`Service did not become ready within ${startupTimeoutMs}ms`);\n } catch (error) {\n if (child) {\n try {\n await stopOwnChild(child);\n } catch (terminationError) {\n throw new ServiceLifecycleError(\"STOP_FAILED\", \"Could not confirm service child exit\", {\n cause: terminationError,\n });\n }\n }\n if (error instanceof ServiceLifecycleError) throw error;\n try {\n if (!(await canStart(Date.now() + 1_000))) {\n throw new ServiceLifecycleError(\n \"STOP_FAILED\",\n \"A service is still running but could not be managed\",\n { cause: error },\n );\n }\n } catch (inspectionError) {\n if (inspectionError instanceof ServiceLifecycleError) throw inspectionError;\n throw new ServiceLifecycleError(\n \"STOP_FAILED\",\n \"Could not verify the service state after startup failure\",\n { cause: inspectionError },\n );\n }\n throw new ServiceLifecycleError(\n \"START_FAILED\",\n `Service failed to start: ${messageOf(error)}`,\n { cause: error },\n );\n } finally {\n child?.off(\"error\", onChildError);\n child?.unref();\n }\n };\n\n const stopInternal = async (): Promise<void> => {\n markStopped();\n const deadline = Date.now() + stopTimeoutMs;\n let stopRequested = false;\n try {\n while (Date.now() < deadline) {\n if (!stopRequested) {\n const service = await control(\"stop\", budget(deadline));\n stopRequested = service !== null;\n }\n const runtime = tryAcquireFileLock(options.runtimeLockPath);\n if (runtime) {\n try {\n if (await socketIsOccupied(options.socketPath, budget(deadline))) throw unsupported();\n if (await control(\"status\", budget(deadline))) {\n throw new ServiceLifecycleError(\n \"STOP_FAILED\",\n \"Service control is still live after runtime ownership ended\",\n );\n }\n return;\n } finally {\n runtime.release();\n }\n }\n await pause(deadline);\n }\n throw new Error(`Service did not stop within ${stopTimeoutMs}ms`);\n } catch (error) {\n if (error instanceof ServiceLifecycleError) throw error;\n throw new ServiceLifecycleError(\n \"STOP_FAILED\",\n `Could not confirm service stop: ${messageOf(error)}`,\n { cause: error },\n );\n }\n };\n\n return {\n status: () => control(\"status\"),\n start: (intent, expectedStoppedToken) =>\n withOperation(() => startInternal(intent, expectedStoppedToken)),\n startForeground: (start) => withOperation(() => startInternal(\"explicit\", undefined, start)),\n stop: () => withOperation(stopInternal),\n restart: (intent = \"explicit\") =>\n withOperation(async () => {\n if (intent === \"recover\" && existsSync(options.stoppedPath)) {\n throw new ServiceLifecycleError(\"STOPPED\", \"Service was explicitly stopped\");\n }\n await stopInternal();\n try {\n return await startInternal(\"explicit\");\n } catch (error) {\n const token = markStopped();\n if (error instanceof ServiceLifecycleError && error.code === \"START_FAILED\") {\n error.recoveryToken = token;\n }\n throw error;\n }\n }),\n };\n}\n","import {\n PROFILE_NAME,\n SOCK_PATH,\n SERVICE_CONTROL_PATH,\n SERVICE_RUNTIME_LOCK_PATH,\n SERVICE_OPERATION_LOCK_PATH,\n STOPPED_PATH,\n ensureProfileWorkspace,\n} from \"./paths.js\";\nimport { spawnScript } from \"./env.js\";\nimport { daemonRelayArgs } from \"./daemon-env.js\";\nimport { createServiceLifecycle } from \"./service-lifecycle.js\";\n\nexport function createProfileServiceLifecycle(\n options: {\n relayName?: string;\n env?: NodeJS.ProcessEnv;\n } = {},\n) {\n ensureProfileWorkspace();\n return createServiceLifecycle({\n profile: PROFILE_NAME,\n socketPath: SOCK_PATH,\n controlPath: SERVICE_CONTROL_PATH,\n runtimeLockPath: SERVICE_RUNTIME_LOCK_PATH,\n operationLockPath: SERVICE_OPERATION_LOCK_PATH,\n stoppedPath: STOPPED_PATH,\n spawn: () =>\n spawnScript(\"serve\", [\"--profile\", PROFILE_NAME, ...daemonRelayArgs(options.relayName)], {\n env: { ...(options.env ?? process.env) },\n stdio: \"ignore\",\n unref: false,\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,WAAW,cAAc,YAAY,qBAAqB;AAC/E,SAAS,eAAe;AAGjB,SAAS,sBAAsB,WAAqC;AACzE,QAAM,aAAa,WAAW,KAAK;AACnC,MAAI,YAAY;AACd,cAAU,QAAQ,kBAAkB,GAAG,EAAE,WAAW,KAAK,CAAC;AAC1D,kBAAc,oBAAoB,GAAG,UAAU;AAAA,CAAI;AACnD;AAAA,EACF;AACA,MAAI;AACF,eAAW,kBAAkB;AAAA,EAC/B,QAAQ;AAAA,EAER;AACF;AAEA,SAAS,yBAA6C;AACpD,MAAI,CAAC,WAAW,kBAAkB,EAAG,QAAO;AAC5C,QAAM,QAAQ,aAAa,oBAAoB,OAAO,EAAE,KAAK;AAC7D,SAAO,SAAS;AAClB;AAEO,SAAS,gBAAgB,WAA8B;AAC5D,QAAM,WAAW,WAAW,KAAK,KAAK,uBAAuB;AAC7D,SAAO,WAAW,CAAC,WAAW,QAAQ,IAAI,CAAC;AAC7C;;;AC1BA,SAAS,kBAAkB;AAC3B,SAAS,cAAAA,aAAY,aAAAC,YAAW,gBAAAC,eAAc,cAAAC,aAAY,iBAAAC,sBAAqB;AAC/E,SAAS,WAAAC,gBAAe;AACxB,SAAS,cAAc,aAAa;AAW7B,IAAM,wBAAN,cAAoC,MAAM;AAAA,EAG/C,YACW,MACT,SACA,SACA;AACA,UAAM,SAAS,OAAO;AAJb;AAKT,SAAK,OAAO;AAAA,EACd;AAAA,EANW;AAAA,EAHX;AAUF;AA2BA,SAAS,UAAU,OAAwB;AACzC,SAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAEA,SAAS,cAAc,MAAuB;AAC5C,QAAM,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;AAAA,IACjB,mBAAmB;AAAA,IACnB,aAAa;AAAA,IACb,OAAO,MACL,YAAY,SAAS,CAAC,aAAa,cAAc,GAAG,gBAAgB,QAAQ,SAAS,CAAC,GAAG;AAAA,MACvF,KAAK,EAAE,GAAI,QAAQ,OAAO,QAAQ,IAAK;AAAA,MACvC,OAAO;AAAA,MACP,OAAO;AAAA,IACT,CAAC;AAAA,EACL,CAAC;AACH;","names":["existsSync","mkdirSync","readFileSync","unlinkSync","writeFileSync","dirname","mkdirSync","dirname","writeFileSync","readFileSync","unlinkSync","existsSync"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/common/paths.ts"],"sourcesContent":["import { cpSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport { homedir } from \"node:os\";\nimport { dirname, resolve, win32 } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n// 所有 dev-anywhere 文件路径的集中定义\n// 使用 os.homedir():POSIX 走 HOME,Windows 走 USERPROFILE;未设置时回退到 getpwuid。\n// 相比 process.env.HOME,不会在缺失环境变量时构造出 \"undefined/.dev-anywhere\"。\nconst HOME = homedir();\nconst MODULE_DIR = dirname(fileURLToPath(import.meta.url));\nconst SOURCE_FONT_ASSETS_DIR = resolve(MODULE_DIR, \"../../assets/fonts\");\nconst DIST_FONT_ASSETS_DIR = resolve(MODULE_DIR, \"../assets/fonts\");\nconst DEFAULT_FONT_FAMILY = \"sarasa-fixed-sc\";\nexport const DEFAULT_PROXY_PROFILE = \"default\";\n\ninterface ProxyProfilePaths {\n profileName: string;\n isDefaultProfile: boolean;\n appDir: string;\n profileDir: string;\n configPath: string;\n runDir: string;\n sockPath: string;\n pidPath: string;\n serviceControlPath: string;\n serviceRuntimeLockPath: string;\n serviceOperationLockPath: string;\n stoppedPath: string;\n desiredRelayPath: string;\n stateDir: string;\n sessionsPath: string;\n sessionRuntimeIpcVersionPath: string;\n historyMetadataPath: string;\n previewsPath: string;\n hookRegistryPath: string;\n previewRunDir: string;\n previewWorkerSock: string;\n previewWorkerLock: string;\n dataDir: string;\n proxyIdPath: string;\n logDir: string;\n serviceLogPath: string;\n relayDataDir: string;\n fontDir: string;\n}\n\nexport function normalizeProxyProfileName(value: string | undefined): string {\n const normalized = value?.trim() || DEFAULT_PROXY_PROFILE;\n if (\n normalized === \".\" ||\n normalized === \"..\" ||\n !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(normalized)\n ) {\n throw new Error(\n `Invalid dev-anywhere profile \"${normalized}\". Use 1-64 letters, numbers, \".\", \"_\" or \"-\".`,\n );\n }\n return normalized;\n}\n\nfunction readProxyProfileNameFromArgv(argv: readonly string[]): string | undefined {\n const args = [...argv];\n while (args[0] === \"--\") args.shift();\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === \"claude\" || arg === \"codex\" || arg === \"kimi\") return undefined;\n if (arg === \"--profile\") {\n const next = args[i + 1];\n return next && !next.startsWith(\"-\") ? next : undefined;\n }\n if (arg.startsWith(\"--profile=\")) {\n return arg.slice(\"--profile=\".length);\n }\n }\n return undefined;\n}\n\nfunction resolveProxyProfileName(\n argv: readonly string[] = process.argv.slice(2),\n home: string = HOME,\n): string {\n return normalizeProxyProfileName(\n readProxyProfileNameFromArgv(argv) ?? readDefaultProfileFromConfig(home),\n );\n}\n\nfunction readDefaultProfileFromConfig(home: string): string | undefined {\n try {\n const parsed = JSON.parse(readFileSync(`${home}/.dev-anywhere/config.json`, \"utf-8\")) as {\n defaultProfile?: unknown;\n };\n return typeof parsed.defaultProfile === \"string\" ? parsed.defaultProfile : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Windows pipes have no filesystem entry. The full resource path scopes their names by user,\n * profile and session; hashing only keeps names bounded, and is not an access-control mechanism. */\nexport function localIpcEndpointPath(\n filePath: string,\n platform: NodeJS.Platform = process.platform,\n): string {\n if (platform !== \"win32\") return filePath;\n const identity = win32.normalize(filePath).toLowerCase();\n const digest = createHash(\"sha256\").update(identity).digest(\"hex\");\n return `\\\\\\\\.\\\\pipe\\\\dev-anywhere-${digest}`;\n}\n\nexport function buildProxyProfilePaths(\n home: string,\n profileName: string,\n platform: NodeJS.Platform = process.platform,\n): ProxyProfilePaths {\n const normalizedProfile = normalizeProxyProfileName(profileName);\n const appDir = `${home}/.dev-anywhere`;\n const isDefaultProfile = normalizedProfile === DEFAULT_PROXY_PROFILE;\n const profileDir = isDefaultProfile ? appDir : `${appDir}/profiles/${normalizedProfile}`;\n const runDir = isDefaultProfile ? `${appDir}/run` : `${profileDir}/run`;\n const stateDir = isDefaultProfile ? `${appDir}/state` : `${profileDir}/state`;\n const dataDir = isDefaultProfile ? `${appDir}/data` : `${profileDir}/data`;\n const logDir = isDefaultProfile ? `${appDir}/logs` : `${profileDir}/logs`;\n const relayDataDir = `${appDir}/relay-data`;\n\n return {\n profileName: normalizedProfile,\n isDefaultProfile,\n appDir,\n profileDir,\n configPath: `${appDir}/config.json`,\n runDir,\n sockPath: localIpcEndpointPath(`${runDir}/dev-anywhere.sock`, platform),\n pidPath: `${runDir}/dev-anywhere.pid`,\n serviceControlPath: localIpcEndpointPath(`${runDir}/service-control.sock`, platform),\n serviceRuntimeLockPath: `${runDir}/service-runtime.lock`,\n serviceOperationLockPath: `${runDir}/service-operation.lock`,\n stoppedPath: `${runDir}/stopped`,\n desiredRelayPath: `${runDir}/desired-relay`,\n stateDir,\n sessionsPath: `${stateDir}/sessions.json`,\n sessionRuntimeIpcVersionPath: `${stateDir}/session-runtime-ipc-version`,\n historyMetadataPath: `${stateDir}/history-metadata.json`,\n previewsPath: `${stateDir}/previews.json`,\n hookRegistryPath: `${stateDir}/hooks.json`,\n previewRunDir: `${runDir}/previews`,\n previewWorkerSock: localIpcEndpointPath(`${runDir}/preview-worker.sock`, platform),\n previewWorkerLock: `${runDir}/preview-worker.lock`,\n dataDir,\n proxyIdPath: isDefaultProfile ? `${appDir}/proxy-id` : `${profileDir}/proxy-id`,\n logDir,\n serviceLogPath: `${logDir}/service.log`,\n relayDataDir,\n fontDir: `${relayDataDir}/fonts`,\n };\n}\n\nexport function defaultHookPortForProfile(profileName: string): number {\n const normalizedProfile = normalizeProxyProfileName(profileName);\n if (normalizedProfile === DEFAULT_PROXY_PROFILE) return 17654;\n\n let hash = 0;\n for (const char of normalizedProfile) {\n hash = (hash * 31 + char.charCodeAt(0)) % 1000;\n }\n return 17655 + hash;\n}\n\nexport const PROFILE_NAME = resolveProxyProfileName();\nconst PROFILE_PATHS = buildProxyProfilePaths(HOME, PROFILE_NAME);\nexport const APP_DIR = PROFILE_PATHS.appDir;\n\n// 把 cwd 前缀替换为 ~,HOME 为空时原样返回(避免 replace(\"\", \"~\") 把 ~ 前缀到所有路径)\nexport function tildify(cwd: string): string {\n return HOME ? cwd.replace(HOME, \"~\") : cwd;\n}\nexport const CONFIG_PATH = PROFILE_PATHS.configPath;\n\n// 运行时文件\nexport const RUN_DIR = PROFILE_PATHS.runDir;\nexport const SOCK_PATH = PROFILE_PATHS.sockPath;\nexport const PID_PATH = PROFILE_PATHS.pidPath;\nexport const SERVICE_CONTROL_PATH = PROFILE_PATHS.serviceControlPath;\nexport const SERVICE_RUNTIME_LOCK_PATH = PROFILE_PATHS.serviceRuntimeLockPath;\nexport const SERVICE_OPERATION_LOCK_PATH = PROFILE_PATHS.serviceOperationLockPath;\n// 停机标记文件。用户执行 `dev-anywhere stop` 时创建,其它时候不存在。文件内容无意义。\n// 作用:terminal 重连逻辑检查此标记,存在则仅 tryConnect 不主动 spawn daemon,\n// 防止 stop 结束 daemon 后 terminal 立即将其重新拉起。\nexport const STOPPED_PATH = PROFILE_PATHS.stoppedPath;\nexport const DESIRED_RELAY_PATH = PROFILE_PATHS.desiredRelayPath;\n// npm 全局安装对同一用户的所有 profile / daemon 都是共享写操作,锁不能放进 profile\n// 自己的 runDir,否则两个 profile 会同时改写同一个 node_modules 目录。\nexport const AUTO_UPDATE_LOCK_PATH = `${APP_DIR}/run/auto-update.lock`;\n\n// 持久化状态\nconst STATE_DIR = PROFILE_PATHS.stateDir;\nexport const SESSIONS_PATH = PROFILE_PATHS.sessionsPath;\nexport const SESSION_RUNTIME_IPC_VERSION_PATH = PROFILE_PATHS.sessionRuntimeIpcVersionPath;\nexport const HISTORY_METADATA_PATH = PROFILE_PATHS.historyMetadataPath;\nexport const PREVIEWS_PATH = PROFILE_PATHS.previewsPath;\nexport const HOOK_REGISTRY_PATH = PROFILE_PATHS.hookRegistryPath;\nexport const PREVIEW_RUN_DIR = PROFILE_PATHS.previewRunDir;\nexport const PREVIEW_WORKER_SOCK = PROFILE_PATHS.previewWorkerSock;\nexport const PREVIEW_WORKER_LOCK = PROFILE_PATHS.previewWorkerLock;\n\n// 会话数据\nexport const DATA_DIR = PROFILE_PATHS.dataDir;\nexport const PROXY_ID_PATH = PROFILE_PATHS.proxyIdPath;\nconst RELAY_DATA_DIR = PROFILE_PATHS.relayDataDir;\nconst FONT_DIR = PROFILE_PATHS.fontDir;\n\n// 日志\nexport const LOG_DIR = PROFILE_PATHS.logDir;\nexport const SERVICE_LOG_PATH = PROFILE_PATHS.serviceLogPath;\n\nexport function buildSessionPaths(\n dataDir: string,\n sessionId: string,\n platform: NodeJS.Platform = process.platform,\n) {\n const dir = `${dataDir}/${sessionId}`;\n return {\n dir,\n workerSock: localIpcEndpointPath(`${dir}/worker.sock`, platform),\n };\n}\n\nexport function sessionPaths(sessionId: string) {\n return buildSessionPaths(DATA_DIR, sessionId);\n}\n\nexport function isInitialized(): boolean {\n return existsSync(CONFIG_PATH);\n}\n\nconst DEFAULT_CONFIG = `{\n \"defaultProfile\": \"default\",\n \"autoUpdate\": true,\n \"profiles\": {\n \"default\": {\n \"relay\": \"cloud\"\n },\n \"local\": {\n \"relay\": \"local\"\n }\n },\n \"relays\": {\n \"cloud\": {\n \"url\": \"wss://dev-anywhere.example.com\",\n \"proxyToken\": \"\"\n },\n \"local\": {\n \"url\": \"ws://localhost:3100\"\n }\n }\n}\n`;\n\ntype FontAssetSource = {\n dir: string;\n family?: string;\n};\n\nfunction copyFontFamilyIfMissing(targetFontsDir: string, source: FontAssetSource): boolean {\n const family = source.family ?? DEFAULT_FONT_FAMILY;\n const sourceFamilyDir = `${source.dir}/${family}`;\n const targetFamilyDir = `${targetFontsDir}/${family}`;\n if (existsSync(targetFamilyDir) || !existsSync(sourceFamilyDir)) return false;\n mkdirSync(targetFontsDir, { recursive: true });\n cpSync(sourceFamilyDir, targetFamilyDir, { recursive: true });\n return true;\n}\n\nexport function installFontAssetsFromSources(\n targetFontsDir: string,\n sources: FontAssetSource[],\n): boolean {\n for (const source of sources) {\n if (copyFontFamilyIfMissing(targetFontsDir, source)) return true;\n }\n return false;\n}\n\nfunction installFontAssets(): void {\n installFontAssetsFromSources(FONT_DIR, [\n { dir: SOURCE_FONT_ASSETS_DIR, family: DEFAULT_FONT_FAMILY },\n { dir: DIST_FONT_ASSETS_DIR, family: DEFAULT_FONT_FAMILY },\n ]);\n}\n\nexport function initWorkspace(): void {\n ensureProfileWorkspace();\n mkdirSync(RELAY_DATA_DIR, { recursive: true });\n installFontAssets();\n if (!existsSync(CONFIG_PATH)) {\n writeFileSync(CONFIG_PATH, DEFAULT_CONFIG);\n }\n}\n\nexport function ensureProfileWorkspace(): void {\n mkdirSync(RUN_DIR, { recursive: true });\n mkdirSync(STATE_DIR, { recursive: true });\n mkdirSync(DATA_DIR, { recursive: true });\n mkdirSync(LOG_DIR, { recursive: true });\n}\n"],"mappings":";;;AAAA,SAAS,QAAQ,YAAY,WAAW,cAAc,qBAAqB;AAC3E,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AACxB,SAAS,SAAS,SAAS,aAAa;AACxC,SAAS,qBAAqB;AAK9B,IAAM,OAAO,QAAQ;AACrB,IAAM,aAAa,QAAQ,cAAc,YAAY,GAAG,CAAC;AACzD,IAAM,yBAAyB,QAAQ,YAAY,oBAAoB;AACvE,IAAM,uBAAuB,QAAQ,YAAY,iBAAiB;AAClE,IAAM,s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AEO,SAAS,yBAA+B;AAC7C,YAAU,SAAS,EAAE,WAAW,KAAK,CAAC;AACtC,YAAU,WAAW,EAAE,WAAW,KAAK,CAAC;AACxC,YAAU,UAAU,EAAE,WAAW,KAAK,CAAC;AACvC,YAAU,SAAS,EAAE,WAAW,KAAK,CAAC;AACxC;","names":[]}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|