@saptools/cf-debugger 0.2.2 → 0.3.0
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 +29 -0
- package/dist/cli.js +1142 -3
- package/dist/cli.js.map +1 -1
- package/package.json +2 -1
package/dist/cli.js
CHANGED
|
@@ -26,6 +26,1141 @@ import {
|
|
|
26
26
|
|
|
27
27
|
// src/cli.ts
|
|
28
28
|
import nodeProcess from "process";
|
|
29
|
+
|
|
30
|
+
// ../core/src/package-metadata.ts
|
|
31
|
+
import { readFileSync } from "fs";
|
|
32
|
+
import { dirname, join } from "path";
|
|
33
|
+
import { fileURLToPath } from "url";
|
|
34
|
+
|
|
35
|
+
// ../core/src/records.ts
|
|
36
|
+
function isRecord(value) {
|
|
37
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
38
|
+
}
|
|
39
|
+
function errorMessage(error) {
|
|
40
|
+
return error instanceof Error ? error.message : String(error);
|
|
41
|
+
}
|
|
42
|
+
function readString(record, key) {
|
|
43
|
+
const value = record[key];
|
|
44
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// ../core/src/package-metadata.ts
|
|
48
|
+
var MAX_WALK_UP = 6;
|
|
49
|
+
function readPackageManifest(directory) {
|
|
50
|
+
let raw;
|
|
51
|
+
try {
|
|
52
|
+
raw = readFileSync(join(directory, "package.json"), "utf8");
|
|
53
|
+
} catch {
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
let parsed;
|
|
57
|
+
try {
|
|
58
|
+
parsed = JSON.parse(raw);
|
|
59
|
+
} catch {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
if (!isRecord(parsed)) {
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
const name = readString(parsed, "name");
|
|
66
|
+
const version = readString(parsed, "version");
|
|
67
|
+
if (name === void 0 || version === void 0) {
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
return { name, version, directory };
|
|
71
|
+
}
|
|
72
|
+
function findPackageMetadata(startDirectory, expectedName) {
|
|
73
|
+
let current = startDirectory;
|
|
74
|
+
for (let depth = 0; depth < MAX_WALK_UP; depth += 1) {
|
|
75
|
+
const manifest = readPackageManifest(current);
|
|
76
|
+
if (manifest?.name === expectedName) {
|
|
77
|
+
return manifest;
|
|
78
|
+
}
|
|
79
|
+
const parent = dirname(current);
|
|
80
|
+
if (parent === current) {
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
current = parent;
|
|
84
|
+
}
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ../core/src/saptools-paths.ts
|
|
89
|
+
import { chmodSync, mkdirSync, readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "fs";
|
|
90
|
+
import { homedir } from "os";
|
|
91
|
+
import { join as join2 } from "path";
|
|
92
|
+
var SAPTOOLS_DIR_NAME = ".saptools";
|
|
93
|
+
var SAPTOOLS_ROOT_ENV = "SAPTOOLS_ROOT";
|
|
94
|
+
function resolveSaptoolsRoot(explicit, env = process.env) {
|
|
95
|
+
if (explicit !== void 0 && explicit.length > 0) {
|
|
96
|
+
return explicit;
|
|
97
|
+
}
|
|
98
|
+
const fromEnv = env[SAPTOOLS_ROOT_ENV];
|
|
99
|
+
if (fromEnv !== void 0 && fromEnv.length > 0) {
|
|
100
|
+
return fromEnv;
|
|
101
|
+
}
|
|
102
|
+
return join2(homedir(), SAPTOOLS_DIR_NAME);
|
|
103
|
+
}
|
|
104
|
+
function ensurePrivateDirectorySync(directory) {
|
|
105
|
+
mkdirSync(directory, { recursive: true, mode: 448 });
|
|
106
|
+
try {
|
|
107
|
+
chmodSync(directory, 448);
|
|
108
|
+
} catch {
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
function writeFileAtomicSync(path, data, mode = 384) {
|
|
112
|
+
const temp = `${path}.${String(process.pid)}.${Math.random().toString(36).slice(2, 8)}.tmp`;
|
|
113
|
+
try {
|
|
114
|
+
writeFileSync(temp, data, { encoding: "utf8", mode });
|
|
115
|
+
try {
|
|
116
|
+
chmodSync(temp, mode);
|
|
117
|
+
} catch {
|
|
118
|
+
}
|
|
119
|
+
renameSync(temp, path);
|
|
120
|
+
} catch (error) {
|
|
121
|
+
rmSync(temp, { force: true });
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
function readJsonFileSync(path) {
|
|
126
|
+
let raw;
|
|
127
|
+
try {
|
|
128
|
+
raw = readFileSync2(path, "utf8");
|
|
129
|
+
} catch {
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
try {
|
|
133
|
+
return JSON.parse(raw);
|
|
134
|
+
} catch {
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// ../core/src/self-update/reexec.ts
|
|
140
|
+
import { spawn } from "child_process";
|
|
141
|
+
import { constants } from "os";
|
|
142
|
+
var REEXEC_MARKER_ENV = "SAPTOOLS_SELF_UPDATE_REEXEC";
|
|
143
|
+
var FORWARDED_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
144
|
+
function nativeExecve() {
|
|
145
|
+
return process.execve?.bind(process);
|
|
146
|
+
}
|
|
147
|
+
function defaultRuntime() {
|
|
148
|
+
return {
|
|
149
|
+
platform: process.platform,
|
|
150
|
+
execve: nativeExecve(),
|
|
151
|
+
spawnImpl: spawn,
|
|
152
|
+
onSignal: (signal, handler) => {
|
|
153
|
+
process.on(signal, handler);
|
|
154
|
+
},
|
|
155
|
+
offSignal: (signal, handler) => {
|
|
156
|
+
process.off(signal, handler);
|
|
157
|
+
},
|
|
158
|
+
kill: (pid, signal) => {
|
|
159
|
+
process.kill(pid, signal);
|
|
160
|
+
},
|
|
161
|
+
exit: (code) => {
|
|
162
|
+
process.exit(code);
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
function buildReexecArgv(request) {
|
|
167
|
+
return [...request.execArgv, request.binPath, ...request.args];
|
|
168
|
+
}
|
|
169
|
+
function reexecEnvironment(env) {
|
|
170
|
+
return { ...env, [REEXEC_MARKER_ENV]: "1" };
|
|
171
|
+
}
|
|
172
|
+
function signalExitCode(signal) {
|
|
173
|
+
const number = constants.signals[signal];
|
|
174
|
+
return 128 + number;
|
|
175
|
+
}
|
|
176
|
+
async function reexecProcess(request, runtimeOverrides = {}) {
|
|
177
|
+
const runtime = { ...defaultRuntime(), ...runtimeOverrides };
|
|
178
|
+
const argv = buildReexecArgv(request);
|
|
179
|
+
const env = reexecEnvironment(request.env);
|
|
180
|
+
if (runtime.platform !== "win32" && runtime.execve !== void 0) {
|
|
181
|
+
try {
|
|
182
|
+
runtime.execve(request.execPath, [request.execPath, ...argv], env);
|
|
183
|
+
} catch {
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
await new Promise((resolve, reject) => {
|
|
187
|
+
const child = runtime.spawnImpl(request.execPath, argv, { stdio: "inherit", env });
|
|
188
|
+
const forward = (signal) => {
|
|
189
|
+
child.kill(signal);
|
|
190
|
+
};
|
|
191
|
+
for (const signal of FORWARDED_SIGNALS) {
|
|
192
|
+
runtime.onSignal(signal, forward);
|
|
193
|
+
}
|
|
194
|
+
const detach = () => {
|
|
195
|
+
for (const signal of FORWARDED_SIGNALS) {
|
|
196
|
+
runtime.offSignal(signal, forward);
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
child.once("error", (error) => {
|
|
200
|
+
detach();
|
|
201
|
+
reject(error);
|
|
202
|
+
});
|
|
203
|
+
child.once("exit", (code, signal) => {
|
|
204
|
+
detach();
|
|
205
|
+
if (signal === null) {
|
|
206
|
+
runtime.exit(code ?? 1);
|
|
207
|
+
} else {
|
|
208
|
+
runtime.kill(process.pid, signal);
|
|
209
|
+
runtime.exit(signalExitCode(signal));
|
|
210
|
+
}
|
|
211
|
+
resolve();
|
|
212
|
+
});
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// ../core/src/self-update/policy.ts
|
|
217
|
+
var POLICY_ENV = "SAPTOOLS_AUTO_UPDATE";
|
|
218
|
+
var INTERVAL_ENV = "SAPTOOLS_UPDATE_INTERVAL_MINUTES";
|
|
219
|
+
var DEBUG_ENV = "SAPTOOLS_UPDATE_DEBUG";
|
|
220
|
+
var DEFAULT_CHECK_INTERVAL_MINUTES = 60;
|
|
221
|
+
var SELF_UPDATE_COMMAND = "self-update";
|
|
222
|
+
function parsePolicy(raw) {
|
|
223
|
+
if (raw === void 0) {
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
const value = raw.trim().toLowerCase();
|
|
227
|
+
if (["on", "1", "true", "yes", "auto", "always"].includes(value)) {
|
|
228
|
+
return "on";
|
|
229
|
+
}
|
|
230
|
+
if (["notify", "check"].includes(value)) {
|
|
231
|
+
return "notify";
|
|
232
|
+
}
|
|
233
|
+
if (["off", "0", "false", "no", "never", "disabled"].includes(value)) {
|
|
234
|
+
return "off";
|
|
235
|
+
}
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
function isTruthyFlag(raw) {
|
|
239
|
+
return raw !== void 0 && !["", "0", "false", "no", "off"].includes(raw.trim().toLowerCase());
|
|
240
|
+
}
|
|
241
|
+
function readExplicitPolicy(env, envPrefix) {
|
|
242
|
+
const perPackage = envPrefix === void 0 ? void 0 : parsePolicy(env[`${envPrefix}_AUTO_UPDATE`]);
|
|
243
|
+
return perPackage ?? parsePolicy(env[POLICY_ENV]);
|
|
244
|
+
}
|
|
245
|
+
function off(reason, explicit) {
|
|
246
|
+
return { policy: "off", reason, explicit };
|
|
247
|
+
}
|
|
248
|
+
function notify(reason, explicit) {
|
|
249
|
+
return { policy: "notify", reason, explicit };
|
|
250
|
+
}
|
|
251
|
+
function locationDecision(location, explicit) {
|
|
252
|
+
switch (location.kind) {
|
|
253
|
+
case "local":
|
|
254
|
+
return off("running from a source checkout or linked package, not a package-manager install", explicit);
|
|
255
|
+
case "npx":
|
|
256
|
+
return off("running through npx or dlx, which resolves the version on its own", explicit);
|
|
257
|
+
case "unknown":
|
|
258
|
+
return notify(`install location not recognized (${location.detail})`, explicit);
|
|
259
|
+
case "npm-global":
|
|
260
|
+
case "pnpm-global":
|
|
261
|
+
case "yarn-global":
|
|
262
|
+
case "bun-global":
|
|
263
|
+
case "volta":
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
function resolveUpdatePolicy(input) {
|
|
268
|
+
const { env, location } = input;
|
|
269
|
+
const manual = input.manual === true;
|
|
270
|
+
const explicit = readExplicitPolicy(env, input.envPrefix);
|
|
271
|
+
if (!manual && isTruthyFlag(env[REEXEC_MARKER_ENV])) {
|
|
272
|
+
return off("already re-executed after an update", false);
|
|
273
|
+
}
|
|
274
|
+
const commandPath = input.commandPath ?? "";
|
|
275
|
+
if (!manual && (commandPath === SELF_UPDATE_COMMAND || (input.skipCommands ?? []).includes(commandPath))) {
|
|
276
|
+
return off(`the "${commandPath}" command is excluded from automatic updates`, false);
|
|
277
|
+
}
|
|
278
|
+
if (!manual && explicit === "off") {
|
|
279
|
+
return off(`${POLICY_ENV} is off`, true);
|
|
280
|
+
}
|
|
281
|
+
if (!manual && explicit === void 0) {
|
|
282
|
+
if (isTruthyFlag(env["NO_UPDATE_NOTIFIER"])) {
|
|
283
|
+
return off("NO_UPDATE_NOTIFIER is set", false);
|
|
284
|
+
}
|
|
285
|
+
if (isTruthyFlag(env["CI"])) {
|
|
286
|
+
return off("running in CI", false);
|
|
287
|
+
}
|
|
288
|
+
if (env["NODE_ENV"] === "test") {
|
|
289
|
+
return off("NODE_ENV is test", false);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
const byLocation = locationDecision(location, explicit !== void 0);
|
|
293
|
+
if (byLocation !== void 0) {
|
|
294
|
+
return byLocation;
|
|
295
|
+
}
|
|
296
|
+
if (!location.writable) {
|
|
297
|
+
return notify("the install directory is not writable by this user", explicit !== void 0);
|
|
298
|
+
}
|
|
299
|
+
if (manual) {
|
|
300
|
+
return { policy: "on", reason: "requested explicitly", explicit: true };
|
|
301
|
+
}
|
|
302
|
+
return explicit === void 0 ? { policy: "on", reason: "default", explicit: false } : { policy: explicit, reason: `${POLICY_ENV} is ${explicit}`, explicit: true };
|
|
303
|
+
}
|
|
304
|
+
function resolveCheckIntervalMs(env) {
|
|
305
|
+
const raw = env[INTERVAL_ENV];
|
|
306
|
+
if (raw === void 0) {
|
|
307
|
+
return DEFAULT_CHECK_INTERVAL_MINUTES * 6e4;
|
|
308
|
+
}
|
|
309
|
+
const minutes = Number(raw.trim());
|
|
310
|
+
if (!Number.isFinite(minutes) || minutes < 0) {
|
|
311
|
+
return DEFAULT_CHECK_INTERVAL_MINUTES * 6e4;
|
|
312
|
+
}
|
|
313
|
+
return Math.round(minutes * 6e4);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// ../core/src/self-update/run.ts
|
|
317
|
+
import { spawn as spawn2 } from "child_process";
|
|
318
|
+
import { homedir as homedir2 } from "os";
|
|
319
|
+
|
|
320
|
+
// ../core/src/self-update/install-location.ts
|
|
321
|
+
import { accessSync, constants as constants2, realpathSync } from "fs";
|
|
322
|
+
import { basename, dirname as dirname2, join as join3, sep } from "path";
|
|
323
|
+
var UPGRADABLE_KINDS = /* @__PURE__ */ new Set(["npm-global", "pnpm-global", "yarn-global", "bun-global", "volta"]);
|
|
324
|
+
function isUpgradableKind(kind) {
|
|
325
|
+
return UPGRADABLE_KINDS.has(kind);
|
|
326
|
+
}
|
|
327
|
+
function defaultIsWritable(path) {
|
|
328
|
+
try {
|
|
329
|
+
accessSync(path, constants2.W_OK);
|
|
330
|
+
return true;
|
|
331
|
+
} catch {
|
|
332
|
+
return false;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
function toPosix(path) {
|
|
336
|
+
return path.split(sep).join("/");
|
|
337
|
+
}
|
|
338
|
+
function isPnpmGlobal(posixDirectory, env) {
|
|
339
|
+
if (posixDirectory.includes("/pnpm/global/")) {
|
|
340
|
+
return true;
|
|
341
|
+
}
|
|
342
|
+
const home = env["PNPM_HOME"];
|
|
343
|
+
return home !== void 0 && home.length > 0 && posixDirectory.startsWith(`${toPosix(home).replace(/\/+$/, "")}/global/`);
|
|
344
|
+
}
|
|
345
|
+
function nodeModulesRootOf(packageDirectory) {
|
|
346
|
+
const parent = dirname2(packageDirectory);
|
|
347
|
+
if (basename(parent) === "node_modules") {
|
|
348
|
+
return parent;
|
|
349
|
+
}
|
|
350
|
+
const grandparent = dirname2(parent);
|
|
351
|
+
return basename(grandparent) === "node_modules" ? grandparent : void 0;
|
|
352
|
+
}
|
|
353
|
+
function npmPrefixFor(packageDirectory, platform) {
|
|
354
|
+
const nodeModules = nodeModulesRootOf(packageDirectory);
|
|
355
|
+
if (nodeModules === void 0) {
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
const parent = dirname2(nodeModules);
|
|
359
|
+
if (platform === "win32") {
|
|
360
|
+
return basename(parent).toLowerCase() === "npm" ? parent : void 0;
|
|
361
|
+
}
|
|
362
|
+
return basename(parent) === "lib" ? dirname2(parent) : void 0;
|
|
363
|
+
}
|
|
364
|
+
function classifyKind(packageDirectory, platform, env) {
|
|
365
|
+
const posix = toPosix(packageDirectory);
|
|
366
|
+
if (posix.includes("/_npx/") || /\/dlx-[^/]+\//.test(posix) || posix.includes("/pnpm/dlx/") || posix.includes("/.cache/pnpm/dlx")) {
|
|
367
|
+
return "npx";
|
|
368
|
+
}
|
|
369
|
+
if (posix.includes("/.volta/tools/image/packages/")) {
|
|
370
|
+
return "volta";
|
|
371
|
+
}
|
|
372
|
+
if (posix.includes("/.bun/install/global/")) {
|
|
373
|
+
return "bun-global";
|
|
374
|
+
}
|
|
375
|
+
if (posix.includes("/.config/yarn/global/") || posix.includes("/yarn/global/node_modules/")) {
|
|
376
|
+
return "yarn-global";
|
|
377
|
+
}
|
|
378
|
+
if (isPnpmGlobal(posix, env)) {
|
|
379
|
+
return "pnpm-global";
|
|
380
|
+
}
|
|
381
|
+
if (!posix.includes("/node_modules/")) {
|
|
382
|
+
return "local";
|
|
383
|
+
}
|
|
384
|
+
return npmPrefixFor(packageDirectory, platform) === void 0 ? "local" : "npm-global";
|
|
385
|
+
}
|
|
386
|
+
function writableForUpgrade(packageDirectory, prefix, platform, isWritable) {
|
|
387
|
+
const targets = [packageDirectory, dirname2(packageDirectory)];
|
|
388
|
+
const nodeModules = nodeModulesRootOf(packageDirectory);
|
|
389
|
+
if (nodeModules !== void 0) {
|
|
390
|
+
targets.push(nodeModules);
|
|
391
|
+
}
|
|
392
|
+
if (prefix !== void 0) {
|
|
393
|
+
targets.push(platform === "win32" ? prefix : join3(prefix, "bin"));
|
|
394
|
+
}
|
|
395
|
+
return targets.every((target) => isWritable(target));
|
|
396
|
+
}
|
|
397
|
+
function describe(kind, packageDirectory, prefix) {
|
|
398
|
+
if (kind === "npm-global" && prefix !== void 0) {
|
|
399
|
+
return `npm global install under ${prefix}`;
|
|
400
|
+
}
|
|
401
|
+
return `${kind} install at ${packageDirectory}`;
|
|
402
|
+
}
|
|
403
|
+
function unknownLocation(detail) {
|
|
404
|
+
return { kind: "unknown", packageDirectory: void 0, prefix: void 0, writable: false, detail };
|
|
405
|
+
}
|
|
406
|
+
function detectInstallLocation(options) {
|
|
407
|
+
const platform = options.platform ?? process.platform;
|
|
408
|
+
const env = options.env ?? process.env;
|
|
409
|
+
const realpath = options.realpath ?? ((path) => realpathSync(path));
|
|
410
|
+
const isWritable = options.isWritable ?? defaultIsWritable;
|
|
411
|
+
let resolvedBin;
|
|
412
|
+
try {
|
|
413
|
+
resolvedBin = realpath(options.binPath);
|
|
414
|
+
} catch (error) {
|
|
415
|
+
return unknownLocation(`cannot resolve ${options.binPath}: ${errorMessage(error)}`);
|
|
416
|
+
}
|
|
417
|
+
const manifest = findPackageMetadata(dirname2(resolvedBin), options.packageName);
|
|
418
|
+
if (manifest === void 0) {
|
|
419
|
+
return unknownLocation(`no package.json for ${options.packageName} above ${resolvedBin}`);
|
|
420
|
+
}
|
|
421
|
+
const packageDirectory = manifest.directory;
|
|
422
|
+
const kind = classifyKind(packageDirectory, platform, env);
|
|
423
|
+
const prefix = kind === "npm-global" ? npmPrefixFor(packageDirectory, platform) : void 0;
|
|
424
|
+
const writable = isUpgradableKind(kind) && writableForUpgrade(packageDirectory, prefix, platform, isWritable);
|
|
425
|
+
return { kind, packageDirectory, prefix, writable, detail: describe(kind, packageDirectory, prefix) };
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// ../core/src/self-update/installer.ts
|
|
429
|
+
import { existsSync, realpathSync as realpathSync2 } from "fs";
|
|
430
|
+
import { tmpdir } from "os";
|
|
431
|
+
import { dirname as dirname3, join as join4 } from "path";
|
|
432
|
+
var DEFAULT_INSTALL_TIMEOUT_MS = 18e4;
|
|
433
|
+
function manualInstallCommand(kind, spec) {
|
|
434
|
+
switch (kind) {
|
|
435
|
+
case "pnpm-global":
|
|
436
|
+
return `pnpm add -g ${spec}`;
|
|
437
|
+
case "yarn-global":
|
|
438
|
+
return `yarn global add ${spec}`;
|
|
439
|
+
case "bun-global":
|
|
440
|
+
return `bun add -g ${spec}`;
|
|
441
|
+
case "volta":
|
|
442
|
+
return `volta install ${spec}`;
|
|
443
|
+
case "npm-global":
|
|
444
|
+
case "npx":
|
|
445
|
+
case "local":
|
|
446
|
+
case "unknown":
|
|
447
|
+
return `npm install -g ${spec}`;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
function resolveNpmInvocation(execPath, platform, exists, realpath) {
|
|
451
|
+
const binDirectory = dirname3(execPath);
|
|
452
|
+
if (platform === "win32") {
|
|
453
|
+
const cli = join4(binDirectory, "node_modules", "npm", "bin", "npm-cli.js");
|
|
454
|
+
return exists(cli) ? { file: execPath, leadingArgs: [cli] } : void 0;
|
|
455
|
+
}
|
|
456
|
+
const sibling = join4(binDirectory, "npm");
|
|
457
|
+
if (exists(sibling)) {
|
|
458
|
+
try {
|
|
459
|
+
const target = realpath(sibling);
|
|
460
|
+
return target.endsWith(".js") ? { file: execPath, leadingArgs: [target] } : { file: target, leadingArgs: [] };
|
|
461
|
+
} catch {
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
return { file: "npm", leadingArgs: [] };
|
|
465
|
+
}
|
|
466
|
+
function buildNpmCommand(options, spec) {
|
|
467
|
+
if (options.location.prefix === void 0) {
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
const npm = resolveNpmInvocation(
|
|
471
|
+
options.execPath ?? process.execPath,
|
|
472
|
+
options.platform ?? process.platform,
|
|
473
|
+
options.exists ?? existsSync,
|
|
474
|
+
options.realpath ?? ((path) => realpathSync2(path))
|
|
475
|
+
);
|
|
476
|
+
if (npm === void 0) {
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
return {
|
|
480
|
+
file: npm.file,
|
|
481
|
+
args: [
|
|
482
|
+
...npm.leadingArgs,
|
|
483
|
+
"install",
|
|
484
|
+
"--global",
|
|
485
|
+
"--prefix",
|
|
486
|
+
options.location.prefix,
|
|
487
|
+
spec,
|
|
488
|
+
"--registry",
|
|
489
|
+
options.registryUrl,
|
|
490
|
+
"--no-fund",
|
|
491
|
+
"--no-audit",
|
|
492
|
+
"--no-update-notifier",
|
|
493
|
+
"--loglevel=error"
|
|
494
|
+
],
|
|
495
|
+
display: manualInstallCommand("npm-global", spec)
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
function buildInstallCommand(options) {
|
|
499
|
+
const spec = `${options.packageName}@${options.version}`;
|
|
500
|
+
switch (options.location.kind) {
|
|
501
|
+
case "npm-global":
|
|
502
|
+
return buildNpmCommand(options, spec);
|
|
503
|
+
case "pnpm-global":
|
|
504
|
+
return { file: "pnpm", args: ["add", "--global", spec], display: manualInstallCommand("pnpm-global", spec) };
|
|
505
|
+
case "yarn-global":
|
|
506
|
+
return { file: "yarn", args: ["global", "add", spec], display: manualInstallCommand("yarn-global", spec) };
|
|
507
|
+
case "bun-global":
|
|
508
|
+
return { file: "bun", args: ["add", "--global", spec], display: manualInstallCommand("bun-global", spec) };
|
|
509
|
+
case "volta":
|
|
510
|
+
return { file: "volta", args: ["install", spec], display: manualInstallCommand("volta", spec) };
|
|
511
|
+
case "npx":
|
|
512
|
+
case "local":
|
|
513
|
+
case "unknown":
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
function lastLine(text) {
|
|
518
|
+
const lines = text.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0);
|
|
519
|
+
return lines.at(-1) ?? "";
|
|
520
|
+
}
|
|
521
|
+
function runInstall(command, options) {
|
|
522
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_INSTALL_TIMEOUT_MS;
|
|
523
|
+
const env = { ...options.env, SAPTOOLS_AUTO_UPDATE: "off" };
|
|
524
|
+
delete env["SAP_EMAIL"];
|
|
525
|
+
delete env["SAP_PASSWORD"];
|
|
526
|
+
return new Promise((resolve) => {
|
|
527
|
+
let child;
|
|
528
|
+
try {
|
|
529
|
+
child = options.spawnImpl(command.file, command.args, { cwd: tmpdir(), env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
|
530
|
+
} catch (error) {
|
|
531
|
+
resolve({ ok: false, reason: errorMessage(error) });
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
let stderr = "";
|
|
535
|
+
child.stderr?.on("data", (chunk) => {
|
|
536
|
+
stderr = `${stderr}${chunk.toString()}`.slice(-4e3);
|
|
537
|
+
});
|
|
538
|
+
const timer = setTimeout(() => {
|
|
539
|
+
child.kill("SIGKILL");
|
|
540
|
+
}, timeoutMs);
|
|
541
|
+
child.once("error", (error) => {
|
|
542
|
+
clearTimeout(timer);
|
|
543
|
+
resolve({ ok: false, reason: `${command.file}: ${error.message}` });
|
|
544
|
+
});
|
|
545
|
+
child.once("close", (code, signal) => {
|
|
546
|
+
clearTimeout(timer);
|
|
547
|
+
if (code === 0) {
|
|
548
|
+
resolve({ ok: true });
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
const detail = lastLine(stderr);
|
|
552
|
+
const suffix = detail.length > 0 ? `: ${detail}` : "";
|
|
553
|
+
resolve({
|
|
554
|
+
ok: false,
|
|
555
|
+
reason: signal === null ? `${command.display} exited with code ${String(code ?? -1)}${suffix}` : `${command.display} was killed by ${signal} after ${String(Math.round(timeoutMs / 1e3))}s`
|
|
556
|
+
});
|
|
557
|
+
});
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// ../core/src/self-update/registry.ts
|
|
562
|
+
import { readFileSync as readFileSync3 } from "fs";
|
|
563
|
+
import { join as join5 } from "path";
|
|
564
|
+
|
|
565
|
+
// ../core/src/self-update/semver.ts
|
|
566
|
+
var SEMVER_PATTERN = /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
|
|
567
|
+
function parseSemver(text) {
|
|
568
|
+
const match = SEMVER_PATTERN.exec(text.trim());
|
|
569
|
+
if (match === null) {
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
const [, major, minor, patch, prerelease] = match;
|
|
573
|
+
if (major === void 0 || minor === void 0 || patch === void 0) {
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
return {
|
|
577
|
+
major: Number(major),
|
|
578
|
+
minor: Number(minor),
|
|
579
|
+
patch: Number(patch),
|
|
580
|
+
prerelease: prerelease === void 0 ? [] : prerelease.split(".")
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
function compareIdentifiers(left, right) {
|
|
584
|
+
const leftNumeric = /^\d+$/.test(left);
|
|
585
|
+
const rightNumeric = /^\d+$/.test(right);
|
|
586
|
+
if (leftNumeric && rightNumeric) {
|
|
587
|
+
return Math.sign(Number(left) - Number(right));
|
|
588
|
+
}
|
|
589
|
+
if (leftNumeric) {
|
|
590
|
+
return -1;
|
|
591
|
+
}
|
|
592
|
+
if (rightNumeric) {
|
|
593
|
+
return 1;
|
|
594
|
+
}
|
|
595
|
+
if (left === right) {
|
|
596
|
+
return 0;
|
|
597
|
+
}
|
|
598
|
+
return left < right ? -1 : 1;
|
|
599
|
+
}
|
|
600
|
+
function comparePrerelease(left, right) {
|
|
601
|
+
if (left.length === 0 && right.length === 0) {
|
|
602
|
+
return 0;
|
|
603
|
+
}
|
|
604
|
+
if (left.length === 0) {
|
|
605
|
+
return 1;
|
|
606
|
+
}
|
|
607
|
+
if (right.length === 0) {
|
|
608
|
+
return -1;
|
|
609
|
+
}
|
|
610
|
+
for (const [index, identifier] of left.entries()) {
|
|
611
|
+
const other = right[index];
|
|
612
|
+
if (other === void 0) {
|
|
613
|
+
return 1;
|
|
614
|
+
}
|
|
615
|
+
const result = compareIdentifiers(identifier, other);
|
|
616
|
+
if (result !== 0) {
|
|
617
|
+
return result;
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
return left.length < right.length ? -1 : 0;
|
|
621
|
+
}
|
|
622
|
+
function compareSemver(left, right) {
|
|
623
|
+
for (const key of ["major", "minor", "patch"]) {
|
|
624
|
+
if (left[key] !== right[key]) {
|
|
625
|
+
return left[key] < right[key] ? -1 : 1;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
return comparePrerelease(left.prerelease, right.prerelease);
|
|
629
|
+
}
|
|
630
|
+
function isNewerRelease(candidate, current) {
|
|
631
|
+
const next = parseSemver(candidate);
|
|
632
|
+
const installed = parseSemver(current);
|
|
633
|
+
if (next === void 0 || installed === void 0) {
|
|
634
|
+
return false;
|
|
635
|
+
}
|
|
636
|
+
if (next.prerelease.length > 0) {
|
|
637
|
+
return false;
|
|
638
|
+
}
|
|
639
|
+
return compareSemver(next, installed) > 0;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
// ../core/src/self-update/registry.ts
|
|
643
|
+
var DEFAULT_NPM_REGISTRY = "https://registry.npmjs.org";
|
|
644
|
+
var REGISTRY_ENV = "SAPTOOLS_NPM_REGISTRY";
|
|
645
|
+
var DEFAULT_CHECK_TIMEOUT_MS = 2e3;
|
|
646
|
+
function normalizeRegistryUrl(value) {
|
|
647
|
+
if (value === void 0) {
|
|
648
|
+
return;
|
|
649
|
+
}
|
|
650
|
+
const trimmed = value.trim().replace(/\/+$/, "");
|
|
651
|
+
if (!/^https?:\/\/\S+$/i.test(trimmed)) {
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
return trimmed;
|
|
655
|
+
}
|
|
656
|
+
function registryFromNpmrc(text, key) {
|
|
657
|
+
if (text === void 0) {
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
for (const line of text.split(/\r?\n/)) {
|
|
661
|
+
const trimmed = line.trim();
|
|
662
|
+
if (trimmed.length === 0 || trimmed.startsWith("#") || trimmed.startsWith(";")) {
|
|
663
|
+
continue;
|
|
664
|
+
}
|
|
665
|
+
const separator = trimmed.indexOf("=");
|
|
666
|
+
if (separator === -1 || trimmed.slice(0, separator).trim() !== key) {
|
|
667
|
+
continue;
|
|
668
|
+
}
|
|
669
|
+
return trimmed.slice(separator + 1).trim().replace(/^"(.*)"$/, "$1");
|
|
670
|
+
}
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
function readUserNpmrc(homeDirectory) {
|
|
674
|
+
try {
|
|
675
|
+
return readFileSync3(join5(homeDirectory, ".npmrc"), "utf8");
|
|
676
|
+
} catch {
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
function resolveRegistryUrl(env, userNpmrc) {
|
|
681
|
+
const candidates = [
|
|
682
|
+
env[REGISTRY_ENV],
|
|
683
|
+
env["npm_config_registry"],
|
|
684
|
+
registryFromNpmrc(userNpmrc, "@saptools:registry"),
|
|
685
|
+
registryFromNpmrc(userNpmrc, "registry")
|
|
686
|
+
];
|
|
687
|
+
for (const candidate of candidates) {
|
|
688
|
+
const normalized = normalizeRegistryUrl(candidate);
|
|
689
|
+
if (normalized !== void 0) {
|
|
690
|
+
return normalized;
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
return DEFAULT_NPM_REGISTRY;
|
|
694
|
+
}
|
|
695
|
+
async function fetchJson(fetchImpl, url, headers, timeoutMs) {
|
|
696
|
+
try {
|
|
697
|
+
const response = await fetchImpl(url, { headers, signal: AbortSignal.timeout(timeoutMs), redirect: "follow" });
|
|
698
|
+
if (!response.ok) {
|
|
699
|
+
return { ok: false, status: response.status, reason: `HTTP ${String(response.status)} from ${url}` };
|
|
700
|
+
}
|
|
701
|
+
const body = await response.json();
|
|
702
|
+
return { ok: true, body };
|
|
703
|
+
} catch (error) {
|
|
704
|
+
return { ok: false, status: void 0, reason: `${errorMessage(error)} (${url})` };
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
function readLatestTag(body, nestedUnderDistTags) {
|
|
708
|
+
if (!isRecord(body)) {
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
const tags = nestedUnderDistTags ? body["dist-tags"] : body;
|
|
712
|
+
if (!isRecord(tags)) {
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
const latest = readString(tags, "latest");
|
|
716
|
+
return latest !== void 0 && parseSemver(latest) !== void 0 ? latest : void 0;
|
|
717
|
+
}
|
|
718
|
+
async function fetchLatestVersion(packageName, registryUrl, options = {}) {
|
|
719
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
720
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
|
|
721
|
+
const encoded = encodeURIComponent(packageName);
|
|
722
|
+
const baseHeaders = { "user-agent": options.userAgent ?? "saptools-self-update" };
|
|
723
|
+
const distTags = await fetchJson(fetchImpl, `${registryUrl}/-/package/${encoded}/dist-tags`, { ...baseHeaders, accept: "application/json" }, timeoutMs);
|
|
724
|
+
if (distTags.ok) {
|
|
725
|
+
const latest2 = readLatestTag(distTags.body, false);
|
|
726
|
+
return latest2 === void 0 ? { ok: false, reason: "dist-tags response carries no valid latest version" } : { ok: true, latest: latest2 };
|
|
727
|
+
}
|
|
728
|
+
if (distTags.status === void 0) {
|
|
729
|
+
return { ok: false, reason: distTags.reason };
|
|
730
|
+
}
|
|
731
|
+
const packument = await fetchJson(
|
|
732
|
+
fetchImpl,
|
|
733
|
+
`${registryUrl}/${encoded}`,
|
|
734
|
+
{ ...baseHeaders, accept: "application/vnd.npm.install-v1+json" },
|
|
735
|
+
timeoutMs
|
|
736
|
+
);
|
|
737
|
+
if (!packument.ok) {
|
|
738
|
+
return { ok: false, reason: packument.reason };
|
|
739
|
+
}
|
|
740
|
+
const latest = readLatestTag(packument.body, true);
|
|
741
|
+
return latest === void 0 ? { ok: false, reason: "packument carries no valid latest dist-tag" } : { ok: true, latest };
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
// ../core/src/self-update/state.ts
|
|
745
|
+
import { closeSync, openSync, rmSync as rmSync2, statSync, utimesSync, writeSync } from "fs";
|
|
746
|
+
import { dirname as dirname4, join as join6 } from "path";
|
|
747
|
+
var EMPTY_UPDATE_STATE = { version: 1 };
|
|
748
|
+
var UPDATES_DIRECTORY_NAME = "updates";
|
|
749
|
+
var DEFAULT_LOCK_STALE_MS = 10 * 6e4;
|
|
750
|
+
var STRING_FIELDS = ["checkedAt", "latest", "lastFailureAt", "lastFailureReason", "notifiedVersion", "notifiedAt"];
|
|
751
|
+
function updateStateFileName(packageName) {
|
|
752
|
+
return `${packageName.replace(/^@/, "").replaceAll("/", "__")}.json`;
|
|
753
|
+
}
|
|
754
|
+
function updateStatePath(saptoolsRoot, packageName) {
|
|
755
|
+
return join6(saptoolsRoot, UPDATES_DIRECTORY_NAME, updateStateFileName(packageName));
|
|
756
|
+
}
|
|
757
|
+
function updateLockPath(statePath) {
|
|
758
|
+
return statePath.replace(/\.json$/, ".lock");
|
|
759
|
+
}
|
|
760
|
+
function readInstallAttempt(value) {
|
|
761
|
+
if (!isRecord(value)) {
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
const version = readString(value, "version");
|
|
765
|
+
const at = readString(value, "at");
|
|
766
|
+
const ok = value["ok"];
|
|
767
|
+
if (version === void 0 || at === void 0 || typeof ok !== "boolean") {
|
|
768
|
+
return;
|
|
769
|
+
}
|
|
770
|
+
const reason = readString(value, "reason");
|
|
771
|
+
return reason === void 0 ? { version, at, ok } : { version, at, ok, reason };
|
|
772
|
+
}
|
|
773
|
+
function readUpdateState(path) {
|
|
774
|
+
const parsed = readJsonFileSync(path);
|
|
775
|
+
if (!isRecord(parsed) || parsed["version"] !== 1) {
|
|
776
|
+
return EMPTY_UPDATE_STATE;
|
|
777
|
+
}
|
|
778
|
+
const draft = { version: 1 };
|
|
779
|
+
for (const key of STRING_FIELDS) {
|
|
780
|
+
const value = readString(parsed, key);
|
|
781
|
+
if (value !== void 0) {
|
|
782
|
+
draft[key] = value;
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
const lastInstall = readInstallAttempt(parsed["lastInstall"]);
|
|
786
|
+
if (lastInstall !== void 0) {
|
|
787
|
+
draft.lastInstall = lastInstall;
|
|
788
|
+
}
|
|
789
|
+
return draft;
|
|
790
|
+
}
|
|
791
|
+
function clearFailure(state) {
|
|
792
|
+
const next = { ...state };
|
|
793
|
+
delete next.lastFailureAt;
|
|
794
|
+
delete next.lastFailureReason;
|
|
795
|
+
return next;
|
|
796
|
+
}
|
|
797
|
+
function writeUpdateState(path, state) {
|
|
798
|
+
ensurePrivateDirectorySync(dirname4(path));
|
|
799
|
+
writeFileAtomicSync(path, `${JSON.stringify(state, null, 2)}
|
|
800
|
+
`, 384);
|
|
801
|
+
}
|
|
802
|
+
function tryCreateLock(lockPath, now) {
|
|
803
|
+
let descriptor;
|
|
804
|
+
try {
|
|
805
|
+
descriptor = openSync(lockPath, "wx", 384);
|
|
806
|
+
} catch {
|
|
807
|
+
return;
|
|
808
|
+
}
|
|
809
|
+
try {
|
|
810
|
+
writeSync(descriptor, `${JSON.stringify({ pid: process.pid, at: now.toISOString() })}
|
|
811
|
+
`);
|
|
812
|
+
} finally {
|
|
813
|
+
closeSync(descriptor);
|
|
814
|
+
}
|
|
815
|
+
utimesSync(lockPath, now, now);
|
|
816
|
+
return {
|
|
817
|
+
release: () => {
|
|
818
|
+
rmSync2(lockPath, { force: true });
|
|
819
|
+
}
|
|
820
|
+
};
|
|
821
|
+
}
|
|
822
|
+
function isStaleLock(lockPath, now, staleMs) {
|
|
823
|
+
try {
|
|
824
|
+
return now.getTime() - statSync(lockPath).mtimeMs > staleMs;
|
|
825
|
+
} catch {
|
|
826
|
+
return false;
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
function acquireUpdateLock(lockPath, now, staleMs = DEFAULT_LOCK_STALE_MS) {
|
|
830
|
+
ensurePrivateDirectorySync(dirname4(lockPath));
|
|
831
|
+
const lock = tryCreateLock(lockPath, now);
|
|
832
|
+
if (lock !== void 0) {
|
|
833
|
+
return lock;
|
|
834
|
+
}
|
|
835
|
+
if (!isStaleLock(lockPath, now, staleMs)) {
|
|
836
|
+
return;
|
|
837
|
+
}
|
|
838
|
+
rmSync2(lockPath, { force: true });
|
|
839
|
+
return tryCreateLock(lockPath, now);
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
// ../core/src/self-update/run.ts
|
|
843
|
+
var FAILURE_BACKOFF_MS = 15 * 6e4;
|
|
844
|
+
var NOTIFY_INTERVAL_MS = 24 * 60 * 6e4;
|
|
845
|
+
var INSTALL_RETRY_BACKOFF_MS = 24 * 60 * 6e4;
|
|
846
|
+
function defaultRuntime2() {
|
|
847
|
+
return {
|
|
848
|
+
env: process.env,
|
|
849
|
+
argv: process.argv,
|
|
850
|
+
execPath: process.execPath,
|
|
851
|
+
execArgv: process.execArgv,
|
|
852
|
+
platform: process.platform,
|
|
853
|
+
homeDirectory: homedir2(),
|
|
854
|
+
now: () => /* @__PURE__ */ new Date(),
|
|
855
|
+
fetchImpl: fetch,
|
|
856
|
+
spawnImpl: spawn2,
|
|
857
|
+
reexecImpl: reexecProcess,
|
|
858
|
+
checkTimeoutMs: DEFAULT_CHECK_TIMEOUT_MS,
|
|
859
|
+
installTimeoutMs: DEFAULT_INSTALL_TIMEOUT_MS
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
function ageMs(isoTimestamp, nowMs) {
|
|
863
|
+
const then = Date.parse(isoTimestamp);
|
|
864
|
+
return Number.isNaN(then) || then > nowMs ? Number.POSITIVE_INFINITY : nowMs - then;
|
|
865
|
+
}
|
|
866
|
+
function detectLocation(options, runtime, binPath) {
|
|
867
|
+
return detectInstallLocation({
|
|
868
|
+
binPath,
|
|
869
|
+
packageName: options.packageName,
|
|
870
|
+
platform: runtime.platform,
|
|
871
|
+
env: runtime.env,
|
|
872
|
+
...runtime.realpath === void 0 ? {} : { realpath: runtime.realpath },
|
|
873
|
+
...runtime.isWritable === void 0 ? {} : { isWritable: runtime.isWritable }
|
|
874
|
+
});
|
|
875
|
+
}
|
|
876
|
+
function createContext(options, runtime) {
|
|
877
|
+
const { env } = runtime;
|
|
878
|
+
const binPath = runtime.argv[1] ?? "";
|
|
879
|
+
const location = detectLocation(options, runtime, binPath);
|
|
880
|
+
const decision = resolveUpdatePolicy({
|
|
881
|
+
env,
|
|
882
|
+
location,
|
|
883
|
+
skipCommands: options.skipCommands ?? [],
|
|
884
|
+
manual: options.manual === true,
|
|
885
|
+
...options.envPrefix === void 0 ? {} : { envPrefix: options.envPrefix },
|
|
886
|
+
...options.commandPath === void 0 ? {} : { commandPath: options.commandPath }
|
|
887
|
+
});
|
|
888
|
+
const statePath = updateStatePath(resolveSaptoolsRoot(options.saptoolsRoot, env), options.packageName);
|
|
889
|
+
const notice = options.notice ?? ((line) => {
|
|
890
|
+
process.stderr.write(`${options.binName}: ${line}
|
|
891
|
+
`);
|
|
892
|
+
});
|
|
893
|
+
const debug = isTruthyFlag(env[DEBUG_ENV]) ? (line) => {
|
|
894
|
+
process.stderr.write(`${options.binName}: [self-update] ${line}
|
|
895
|
+
`);
|
|
896
|
+
} : () => {
|
|
897
|
+
};
|
|
898
|
+
return {
|
|
899
|
+
options,
|
|
900
|
+
runtime,
|
|
901
|
+
binPath,
|
|
902
|
+
location,
|
|
903
|
+
decision,
|
|
904
|
+
registryUrl: resolveRegistryUrl(env, readUserNpmrc(runtime.homeDirectory)),
|
|
905
|
+
statePath,
|
|
906
|
+
intervalMs: resolveCheckIntervalMs(env),
|
|
907
|
+
// Loaded lazily in resolveLatest: a disabled run must not touch ~/.saptools at all.
|
|
908
|
+
state: EMPTY_UPDATE_STATE,
|
|
909
|
+
notice,
|
|
910
|
+
debug
|
|
911
|
+
};
|
|
912
|
+
}
|
|
913
|
+
function saveState(ctx) {
|
|
914
|
+
try {
|
|
915
|
+
writeUpdateState(ctx.statePath, ctx.state);
|
|
916
|
+
} catch (error) {
|
|
917
|
+
ctx.debug(`cannot write ${ctx.statePath}: ${errorMessage(error)}`);
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
async function resolveLatest(ctx) {
|
|
921
|
+
ctx.state = readUpdateState(ctx.statePath);
|
|
922
|
+
const { state } = ctx;
|
|
923
|
+
const nowMs = ctx.runtime.now().getTime();
|
|
924
|
+
if (ctx.options.manual !== true) {
|
|
925
|
+
if (state.latest !== void 0 && state.checkedAt !== void 0 && ageMs(state.checkedAt, nowMs) < ctx.intervalMs) {
|
|
926
|
+
ctx.debug(`using cached latest ${state.latest} (checked ${state.checkedAt})`);
|
|
927
|
+
return state.latest;
|
|
928
|
+
}
|
|
929
|
+
if (state.lastFailureAt !== void 0 && ageMs(state.lastFailureAt, nowMs) < FAILURE_BACKOFF_MS) {
|
|
930
|
+
ctx.debug(`skipping the registry check after a recent failure: ${state.lastFailureReason ?? "unknown"}`);
|
|
931
|
+
return state.latest;
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
const result = await fetchLatestVersion(ctx.options.packageName, ctx.registryUrl, {
|
|
935
|
+
fetchImpl: ctx.runtime.fetchImpl,
|
|
936
|
+
timeoutMs: ctx.runtime.checkTimeoutMs,
|
|
937
|
+
userAgent: `${ctx.options.binName}/${ctx.options.currentVersion} saptools-self-update`
|
|
938
|
+
});
|
|
939
|
+
const at = ctx.runtime.now().toISOString();
|
|
940
|
+
if (result.ok) {
|
|
941
|
+
ctx.state = clearFailure({ ...ctx.state, checkedAt: at, latest: result.latest });
|
|
942
|
+
saveState(ctx);
|
|
943
|
+
return result.latest;
|
|
944
|
+
}
|
|
945
|
+
ctx.state = { ...ctx.state, lastFailureAt: at, lastFailureReason: result.reason };
|
|
946
|
+
saveState(ctx);
|
|
947
|
+
ctx.debug(`registry check failed: ${result.reason}`);
|
|
948
|
+
return ctx.state.latest;
|
|
949
|
+
}
|
|
950
|
+
function notify2(ctx, latest, reason) {
|
|
951
|
+
const nowMs = ctx.runtime.now().getTime();
|
|
952
|
+
const alreadyAnnounced = ctx.state.notifiedVersion === latest && ctx.state.notifiedAt !== void 0 && ageMs(ctx.state.notifiedAt, nowMs) < NOTIFY_INTERVAL_MS;
|
|
953
|
+
if (!alreadyAnnounced || ctx.options.manual === true) {
|
|
954
|
+
const command = manualInstallCommand(ctx.location.kind, `${ctx.options.packageName}@${latest}`);
|
|
955
|
+
ctx.notice(`${latest} is available (installed ${ctx.options.currentVersion}) but was not installed: ${reason}. Run: ${command}`);
|
|
956
|
+
ctx.state = { ...ctx.state, notifiedVersion: latest, notifiedAt: ctx.runtime.now().toISOString() };
|
|
957
|
+
saveState(ctx);
|
|
958
|
+
}
|
|
959
|
+
return { kind: "notified", latest, reason };
|
|
960
|
+
}
|
|
961
|
+
function recentInstallFailure(ctx, latest) {
|
|
962
|
+
const attempt = ctx.state.lastInstall;
|
|
963
|
+
if (ctx.options.manual === true || attempt === void 0 || attempt.ok || attempt.version !== latest) {
|
|
964
|
+
return;
|
|
965
|
+
}
|
|
966
|
+
if (ageMs(attempt.at, ctx.runtime.now().getTime()) >= INSTALL_RETRY_BACKOFF_MS) {
|
|
967
|
+
return;
|
|
968
|
+
}
|
|
969
|
+
return `the previous attempt failed (${attempt.reason ?? "unknown reason"})`;
|
|
970
|
+
}
|
|
971
|
+
function recordInstall(ctx, latest, ok, reason) {
|
|
972
|
+
const at = ctx.runtime.now().toISOString();
|
|
973
|
+
ctx.state = { ...ctx.state, lastInstall: reason === void 0 ? { version: latest, at, ok } : { version: latest, at, ok, reason } };
|
|
974
|
+
saveState(ctx);
|
|
975
|
+
}
|
|
976
|
+
async function installLatest(ctx, latest) {
|
|
977
|
+
const command = buildInstallCommand({
|
|
978
|
+
location: ctx.location,
|
|
979
|
+
packageName: ctx.options.packageName,
|
|
980
|
+
version: latest,
|
|
981
|
+
registryUrl: ctx.registryUrl,
|
|
982
|
+
execPath: ctx.runtime.execPath,
|
|
983
|
+
platform: ctx.runtime.platform,
|
|
984
|
+
...ctx.runtime.exists === void 0 ? {} : { exists: ctx.runtime.exists },
|
|
985
|
+
...ctx.runtime.realpath === void 0 ? {} : { realpath: ctx.runtime.realpath }
|
|
986
|
+
});
|
|
987
|
+
if (command === void 0) {
|
|
988
|
+
return notify2(ctx, latest, "no supported package manager was found for this install");
|
|
989
|
+
}
|
|
990
|
+
const lock = acquireUpdateLock(updateLockPath(ctx.statePath), ctx.runtime.now());
|
|
991
|
+
if (lock === void 0) {
|
|
992
|
+
ctx.debug("another process holds the update lock");
|
|
993
|
+
return { kind: "skipped", reason: "another process is installing the update" };
|
|
994
|
+
}
|
|
995
|
+
try {
|
|
996
|
+
ctx.notice(`updating ${ctx.options.currentVersion} -> ${latest} ...`);
|
|
997
|
+
const result = await runInstall(command, { env: ctx.runtime.env, timeoutMs: ctx.runtime.installTimeoutMs, spawnImpl: ctx.runtime.spawnImpl });
|
|
998
|
+
const installed = ctx.location.packageDirectory === void 0 ? void 0 : readPackageManifest(ctx.location.packageDirectory)?.version;
|
|
999
|
+
const failure = result.ok ? installed === latest ? void 0 : `the installed version is ${installed ?? "unreadable"}, not ${latest}` : result.reason;
|
|
1000
|
+
if (failure !== void 0) {
|
|
1001
|
+
recordInstall(ctx, latest, false, failure);
|
|
1002
|
+
ctx.notice(`update to ${latest} failed (${failure}); continuing with ${ctx.options.currentVersion}. Run: ${command.display}`);
|
|
1003
|
+
return { kind: "failed", latest, reason: failure };
|
|
1004
|
+
}
|
|
1005
|
+
recordInstall(ctx, latest, true);
|
|
1006
|
+
} finally {
|
|
1007
|
+
lock.release();
|
|
1008
|
+
}
|
|
1009
|
+
return;
|
|
1010
|
+
}
|
|
1011
|
+
async function upgrade(ctx, latest) {
|
|
1012
|
+
const failed = await installLatest(ctx, latest);
|
|
1013
|
+
if (failed !== void 0) {
|
|
1014
|
+
return failed;
|
|
1015
|
+
}
|
|
1016
|
+
const outcome = { kind: "updated", from: ctx.options.currentVersion, to: latest };
|
|
1017
|
+
if (ctx.options.reexec === false) {
|
|
1018
|
+
ctx.notice(`updated to ${latest}`);
|
|
1019
|
+
return outcome;
|
|
1020
|
+
}
|
|
1021
|
+
ctx.notice(`updated to ${latest}; re-running the command`);
|
|
1022
|
+
try {
|
|
1023
|
+
await ctx.runtime.reexecImpl({
|
|
1024
|
+
execPath: ctx.runtime.execPath,
|
|
1025
|
+
execArgv: ctx.runtime.execArgv,
|
|
1026
|
+
binPath: ctx.binPath,
|
|
1027
|
+
args: ctx.runtime.argv.slice(2),
|
|
1028
|
+
env: ctx.runtime.env
|
|
1029
|
+
});
|
|
1030
|
+
} catch (error) {
|
|
1031
|
+
ctx.notice(`could not re-run on ${latest} (${errorMessage(error)}); continuing with the already loaded ${ctx.options.currentVersion}`);
|
|
1032
|
+
}
|
|
1033
|
+
return outcome;
|
|
1034
|
+
}
|
|
1035
|
+
async function runSelfUpdateUnsafe(options, runtime) {
|
|
1036
|
+
const ctx = createContext(options, runtime);
|
|
1037
|
+
if (ctx.decision.policy === "off") {
|
|
1038
|
+
ctx.debug(`off: ${ctx.decision.reason}`);
|
|
1039
|
+
return { kind: "skipped", reason: ctx.decision.reason };
|
|
1040
|
+
}
|
|
1041
|
+
const latest = await resolveLatest(ctx);
|
|
1042
|
+
if (latest === void 0) {
|
|
1043
|
+
return { kind: "skipped", reason: "the latest version is unknown" };
|
|
1044
|
+
}
|
|
1045
|
+
if (!isNewerRelease(latest, options.currentVersion)) {
|
|
1046
|
+
return { kind: "current", latest };
|
|
1047
|
+
}
|
|
1048
|
+
if (ctx.decision.policy === "notify") {
|
|
1049
|
+
return notify2(ctx, latest, ctx.decision.reason);
|
|
1050
|
+
}
|
|
1051
|
+
const backoff = recentInstallFailure(ctx, latest);
|
|
1052
|
+
if (backoff !== void 0) {
|
|
1053
|
+
return notify2(ctx, latest, backoff);
|
|
1054
|
+
}
|
|
1055
|
+
return await upgrade(ctx, latest);
|
|
1056
|
+
}
|
|
1057
|
+
async function runSelfUpdate(options, overrides = {}) {
|
|
1058
|
+
const runtime = { ...defaultRuntime2(), ...overrides };
|
|
1059
|
+
try {
|
|
1060
|
+
return await runSelfUpdateUnsafe(options, runtime);
|
|
1061
|
+
} catch (error) {
|
|
1062
|
+
const reason = errorMessage(error);
|
|
1063
|
+
if (isTruthyFlag(runtime.env[DEBUG_ENV])) {
|
|
1064
|
+
process.stderr.write(`${options.binName}: [self-update] ${reason}
|
|
1065
|
+
`);
|
|
1066
|
+
}
|
|
1067
|
+
return { kind: "skipped", reason };
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
async function inspectSelfUpdate(options, overrides = {}) {
|
|
1071
|
+
const runtime = { ...defaultRuntime2(), ...overrides };
|
|
1072
|
+
const ctx = createContext({ ...options, manual: true }, runtime);
|
|
1073
|
+
const result = await fetchLatestVersion(options.packageName, ctx.registryUrl, {
|
|
1074
|
+
fetchImpl: runtime.fetchImpl,
|
|
1075
|
+
timeoutMs: runtime.checkTimeoutMs,
|
|
1076
|
+
userAgent: `${options.binName}/${options.currentVersion} saptools-self-update`
|
|
1077
|
+
});
|
|
1078
|
+
return {
|
|
1079
|
+
packageName: options.packageName,
|
|
1080
|
+
installed: options.currentVersion,
|
|
1081
|
+
location: ctx.location,
|
|
1082
|
+
policy: resolveUpdatePolicy({
|
|
1083
|
+
env: runtime.env,
|
|
1084
|
+
location: ctx.location,
|
|
1085
|
+
...options.envPrefix === void 0 ? {} : { envPrefix: options.envPrefix }
|
|
1086
|
+
}),
|
|
1087
|
+
registryUrl: ctx.registryUrl,
|
|
1088
|
+
statePath: ctx.statePath,
|
|
1089
|
+
latest: result.ok ? result.latest : void 0,
|
|
1090
|
+
checkError: result.ok ? void 0 : result.reason
|
|
1091
|
+
};
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
// ../core/src/self-update/commander.ts
|
|
1095
|
+
function commandPathOf(command) {
|
|
1096
|
+
const names = [];
|
|
1097
|
+
let current = command;
|
|
1098
|
+
while (current.parent !== null) {
|
|
1099
|
+
names.unshift(current.name());
|
|
1100
|
+
current = current.parent;
|
|
1101
|
+
}
|
|
1102
|
+
return names.join(" ");
|
|
1103
|
+
}
|
|
1104
|
+
function attachSelfUpdate(program, options) {
|
|
1105
|
+
program.hook("preAction", async (_thisCommand, actionCommand) => {
|
|
1106
|
+
await runSelfUpdate({ ...options, commandPath: commandPathOf(actionCommand) });
|
|
1107
|
+
});
|
|
1108
|
+
}
|
|
1109
|
+
function formatSelfUpdateStatus(status) {
|
|
1110
|
+
const latest = status.latest ?? (status.checkError === void 0 ? "unknown" : `unknown (${status.checkError})`);
|
|
1111
|
+
const install = status.location.packageDirectory === void 0 ? status.location.detail : `${status.location.kind} ${status.location.packageDirectory}`;
|
|
1112
|
+
return [
|
|
1113
|
+
`package=${status.packageName}`,
|
|
1114
|
+
`installed=${status.installed}`,
|
|
1115
|
+
`latest=${latest}`,
|
|
1116
|
+
`policy=${status.policy.policy} (${status.policy.reason})`,
|
|
1117
|
+
`install=${install}`,
|
|
1118
|
+
`writable=${status.location.writable ? "yes" : "no"}`,
|
|
1119
|
+
`registry=${status.registryUrl}`,
|
|
1120
|
+
`state=${status.statePath}`
|
|
1121
|
+
];
|
|
1122
|
+
}
|
|
1123
|
+
function describeOutcome(outcome) {
|
|
1124
|
+
switch (outcome.kind) {
|
|
1125
|
+
case "current":
|
|
1126
|
+
return `current (${outcome.latest} is the newest release)`;
|
|
1127
|
+
case "updated":
|
|
1128
|
+
return `updated ${outcome.from} -> ${outcome.to}`;
|
|
1129
|
+
case "notified":
|
|
1130
|
+
return `not installed (${outcome.reason})`;
|
|
1131
|
+
case "failed":
|
|
1132
|
+
return `failed (${outcome.reason})`;
|
|
1133
|
+
case "skipped":
|
|
1134
|
+
return `skipped (${outcome.reason})`;
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
async function runSelfUpdateCommand(options, checkOnly) {
|
|
1138
|
+
const print = options.print ?? ((line) => {
|
|
1139
|
+
process.stdout.write(`${line}
|
|
1140
|
+
`);
|
|
1141
|
+
});
|
|
1142
|
+
const status = await inspectSelfUpdate(options);
|
|
1143
|
+
for (const line of formatSelfUpdateStatus(status)) {
|
|
1144
|
+
print(line);
|
|
1145
|
+
}
|
|
1146
|
+
if (checkOnly) {
|
|
1147
|
+
const verdict = status.latest === void 0 ? "unknown" : isNewerRelease(status.latest, status.installed) ? "update-available" : "current";
|
|
1148
|
+
print(`result=${verdict}`);
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
1151
|
+
const outcome = await runSelfUpdate({ ...options, manual: true, reexec: false });
|
|
1152
|
+
print(`result=${describeOutcome(outcome)}`);
|
|
1153
|
+
if (outcome.kind === "failed") {
|
|
1154
|
+
process.exitCode = 1;
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
function registerSelfUpdateCommand(program, options) {
|
|
1158
|
+
program.command(SELF_UPDATE_COMMAND).description("check npm for a newer release and install it now; every other command does this automatically (at most once an hour)").option("--check", "report whether a newer release exists without installing it").action(async (flags) => {
|
|
1159
|
+
await runSelfUpdateCommand(options, flags.check === true);
|
|
1160
|
+
});
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
// src/cli.ts
|
|
29
1164
|
import { Command } from "commander";
|
|
30
1165
|
|
|
31
1166
|
// src/cli-input.ts
|
|
@@ -57,10 +1192,10 @@ function parseSeconds(raw, label) {
|
|
|
57
1192
|
}
|
|
58
1193
|
|
|
59
1194
|
// src/package-version.ts
|
|
60
|
-
import { readFileSync } from "fs";
|
|
1195
|
+
import { readFileSync as readFileSync4 } from "fs";
|
|
61
1196
|
function readPackageVersion() {
|
|
62
1197
|
const parsed = JSON.parse(
|
|
63
|
-
|
|
1198
|
+
readFileSync4(new URL("../package.json", import.meta.url), "utf8")
|
|
64
1199
|
);
|
|
65
1200
|
if (typeof parsed !== "object" || parsed === null) {
|
|
66
1201
|
throw new CfDebuggerError("PACKAGE_METADATA_INVALID", "Package metadata is not an object.");
|
|
@@ -490,10 +1625,14 @@ function registerReadCommands(program) {
|
|
|
490
1625
|
});
|
|
491
1626
|
}
|
|
492
1627
|
async function main(argv) {
|
|
493
|
-
const
|
|
1628
|
+
const version = readPackageVersion();
|
|
1629
|
+
const selfUpdate = { packageName: "@saptools/cf-debugger", currentVersion: version, binName: "cf-debugger", envPrefix: "CF_DEBUGGER" };
|
|
1630
|
+
const program = new Command().name("cf-debugger").description("Open an SSH debug tunnel to a SAP BTP Cloud Foundry Node.js inspector").version(version);
|
|
1631
|
+
attachSelfUpdate(program, selfUpdate);
|
|
494
1632
|
registerStartCommand(program);
|
|
495
1633
|
registerStopCommand(program);
|
|
496
1634
|
registerReadCommands(program);
|
|
1635
|
+
registerSelfUpdateCommand(program, selfUpdate);
|
|
497
1636
|
await program.parseAsync([...argv]);
|
|
498
1637
|
}
|
|
499
1638
|
function writeTopLevelError(error) {
|