@mawesome/npm-vm 0.0.0-alpha.0 → 0.1.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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -1
  3. package/dist/cli.js +4157 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/index-B071ZJDk.d.cts +164 -0
  6. package/dist/index-B071ZJDk.d.ts +164 -0
  7. package/dist/index.cjs +7 -0
  8. package/dist/index.d.cts +2 -0
  9. package/dist/index.d.ts +2 -0
  10. package/dist/index.js +2 -0
  11. package/dist/internal.cjs +2709 -0
  12. package/dist/internal.cjs.map +1 -0
  13. package/dist/internal.d.cts +139 -0
  14. package/dist/internal.d.ts +139 -0
  15. package/dist/internal.js +2706 -0
  16. package/dist/internal.js.map +1 -0
  17. package/dist/provenance--sOYCeF2.js +322 -0
  18. package/dist/provenance--sOYCeF2.js.map +1 -0
  19. package/dist/provenance-DDegWCyS.js +2 -0
  20. package/dist/runtime/atomic-C3shKdH9.cjs +88 -0
  21. package/dist/runtime/bootstrap.cjs +271 -0
  22. package/dist/runtime/commonjs-AANzyd21.cjs +7393 -0
  23. package/dist/runtime/dispatch-B9OSfqsn.cjs +25156 -0
  24. package/dist/runtime/dist-CXwBT6rE.cjs +30766 -0
  25. package/dist/runtime/home-BaoZZSBy.cjs +91 -0
  26. package/dist/runtime/install-C_M5WK98.cjs +13598 -0
  27. package/dist/runtime/journal-_bs-eJRJ.cjs +282 -0
  28. package/dist/runtime/launchers/cmd.tmpl +2 -0
  29. package/dist/runtime/launchers/ps1.tmpl +5 -0
  30. package/dist/runtime/launchers/sh.tmpl +3 -0
  31. package/dist/runtime/lease-HBD4CmBx.cjs +224 -0
  32. package/dist/runtime/lock-DBeYN-Zg.cjs +141 -0
  33. package/dist/runtime/messages-vUDkl1-0.cjs +174 -0
  34. package/dist/runtime/p-map-b8pXdaFZ.cjs +105 -0
  35. package/dist/runtime/proc-hB8N9WjN.cjs +127 -0
  36. package/dist/runtime/provenance-B4bajGXQ.cjs +2 -0
  37. package/dist/runtime/rolldown-runtime-BGT596CS.cjs +64 -0
  38. package/dist/runtime/runtime.cjs +143 -0
  39. package/dist/runtime/src-SpeGbMJx.cjs +314 -0
  40. package/dist/src-Bc9nN1Kl.cjs +2125 -0
  41. package/dist/src-Bc9nN1Kl.cjs.map +1 -0
  42. package/dist/src-NhNG2mnQ.js +1798 -0
  43. package/dist/src-NhNG2mnQ.js.map +1 -0
  44. package/package.json +87 -17
  45. package/index.js +0 -3
@@ -0,0 +1,174 @@
1
+ //#region src/errors.ts
2
+ /** Exit codes of `npm-vm` itself and of the shim before npm starts (spec section 10). */
3
+ const EXIT = {
4
+ ok: 0,
5
+ problems: 1,
6
+ partial: 2,
7
+ resolution: 3,
8
+ transport: 4,
9
+ verification: 5,
10
+ abi: 6,
11
+ usage: 64
12
+ };
13
+ /** A failure with a message id from spec section 12 and the exit code it maps to. */
14
+ var NpmVmError = class extends Error {
15
+ name = "NpmVmError";
16
+ id;
17
+ exitCode;
18
+ constructor(id, exitCode, message) {
19
+ super(message);
20
+ this.id = id;
21
+ this.exitCode = exitCode;
22
+ }
23
+ };
24
+ function isNpmVmError(error) {
25
+ return error instanceof NpmVmError;
26
+ }
27
+ //#endregion
28
+ //#region src/messages.ts
29
+ /** Message builders for spec section 12; every message names the cause and one fix. */
30
+ /** Every URL in `text` with its user info replaced, so a registry token never reaches a terminal (spec SEC-10). */
31
+ function redactUrls(text) {
32
+ return text.replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/]*)@/gi, "$1***@");
33
+ }
34
+ function describeSpecs(specs) {
35
+ return specs.map((spec) => spec.hash ? `${spec.exact}+${spec.hash.algorithm}.${spec.hash.hex.slice(0, 8)}…` : spec.range).join(" or ");
36
+ }
37
+ function engineMessage(version, enginesNode, nodeVersion) {
38
+ return [`npm ${version} needs Node ${enginesNode}, but the active Node is ${nodeVersion}.`, `Switch Node with \`nvm install <version>\` or \`fnm use <version>\`, or relax the npm range in package.json.`].join("\n");
39
+ }
40
+ function noMatchMessage(specs, file, reason) {
41
+ return [`No npm version satisfies ${describeSpecs(specs)} (${file}): ${reason}.`, `Run \`npm-vm which\` to see the resolution.`].join("\n");
42
+ }
43
+ function transportMessage(ownVersion, detail) {
44
+ return [`Cannot download npm: ${ownVersion === null ? "no npm beside the active Node" : `Node's own npm ${ownVersion}`} (${detail}); npm 8 or newer is needed as the transport.`, `Reinstall Node or run \`npm-vm install <version>\` from a Node whose npm works.`].join("\n");
45
+ }
46
+ function keyMessage(keyid) {
47
+ return [`The registry signed npm with key ${keyid}, which npm-vm does not know.`, `Run \`npm-vm self-update\` to pick up new registry keys.`].join("\n");
48
+ }
49
+ function unsignedMessage(registry, version) {
50
+ return [`${redactUrls(registry)} serves npm ${version} without a registry signature.`, `Pin a tarball hash in devEngines.packageManager (\`${version}+sha512.<hex>\`) to allow unsigned registries.`].join("\n");
51
+ }
52
+ function integrityMessage(expected, actual, detail) {
53
+ return [`npm tarball verification failed: ${detail}.`, `Expected ${expected}, got ${actual}. Clear the entry with \`npm-vm cache prune\` and retry.`].join("\n");
54
+ }
55
+ function abiMessage(detail) {
56
+ return [`npm-vm launcher mismatch: ${detail}.`, `Run \`npx --prefix ~ -y @mawesome/npm-vm setup\` to reinstall the launchers.`].join("\n");
57
+ }
58
+ /** M-LOCKED: names the file, the holder, and the one recovery that is safe for where the holder runs. */
59
+ function lockedMessage(path, holder, live, foreign) {
60
+ if (holder === null) return `${path} is locked by an unreadable owner. If no npm-vm command is running, delete that file and retry.`;
61
+ const who = `PID ${holder.pid} on ${holder.host} since ${holder.createdAt || "an unknown time"}`;
62
+ if (foreign) return [`${path} is locked by ${who}, which cannot be verified from this machine.`, `Confirm on ${holder.host} that no npm-vm command runs, then delete ${path} and retry.`].join("\n");
63
+ if (live) return `${path} is locked by ${who}, which is still running. Wait for it to finish and retry.`;
64
+ return `${path} is locked by ${who}, which is no longer running. Delete ${path} and retry.`;
65
+ }
66
+ function provenanceMessage(name, version, detail) {
67
+ return [`${name}@${version} failed provenance verification: ${detail}.`, "The installed version is unchanged. Retry later, or install the release by hand after checking it at https://www.npmjs.com/package/@mawesome/npm-vm."].join("\n");
68
+ }
69
+ function dirPermsMessage(dir, problem, fix) {
70
+ return [`${dir} ${problem}.`, `Run \`${fix}\` and retry, or point NPM_VM_HOME at a private directory.`].join("\n");
71
+ }
72
+ function changedMessage(file, what) {
73
+ return `${file} changed since npm-vm wrote it; left untouched. Remove the ${what} by hand if you still want it gone.`;
74
+ }
75
+ function restartMessage() {
76
+ return "Restart open terminals and IDEs so they pick up the new PATH.";
77
+ }
78
+ //#endregion
79
+ Object.defineProperty(exports, "EXIT", {
80
+ enumerable: true,
81
+ get: function() {
82
+ return EXIT;
83
+ }
84
+ });
85
+ Object.defineProperty(exports, "NpmVmError", {
86
+ enumerable: true,
87
+ get: function() {
88
+ return NpmVmError;
89
+ }
90
+ });
91
+ Object.defineProperty(exports, "abiMessage", {
92
+ enumerable: true,
93
+ get: function() {
94
+ return abiMessage;
95
+ }
96
+ });
97
+ Object.defineProperty(exports, "changedMessage", {
98
+ enumerable: true,
99
+ get: function() {
100
+ return changedMessage;
101
+ }
102
+ });
103
+ Object.defineProperty(exports, "dirPermsMessage", {
104
+ enumerable: true,
105
+ get: function() {
106
+ return dirPermsMessage;
107
+ }
108
+ });
109
+ Object.defineProperty(exports, "engineMessage", {
110
+ enumerable: true,
111
+ get: function() {
112
+ return engineMessage;
113
+ }
114
+ });
115
+ Object.defineProperty(exports, "integrityMessage", {
116
+ enumerable: true,
117
+ get: function() {
118
+ return integrityMessage;
119
+ }
120
+ });
121
+ Object.defineProperty(exports, "isNpmVmError", {
122
+ enumerable: true,
123
+ get: function() {
124
+ return isNpmVmError;
125
+ }
126
+ });
127
+ Object.defineProperty(exports, "keyMessage", {
128
+ enumerable: true,
129
+ get: function() {
130
+ return keyMessage;
131
+ }
132
+ });
133
+ Object.defineProperty(exports, "lockedMessage", {
134
+ enumerable: true,
135
+ get: function() {
136
+ return lockedMessage;
137
+ }
138
+ });
139
+ Object.defineProperty(exports, "noMatchMessage", {
140
+ enumerable: true,
141
+ get: function() {
142
+ return noMatchMessage;
143
+ }
144
+ });
145
+ Object.defineProperty(exports, "provenanceMessage", {
146
+ enumerable: true,
147
+ get: function() {
148
+ return provenanceMessage;
149
+ }
150
+ });
151
+ Object.defineProperty(exports, "redactUrls", {
152
+ enumerable: true,
153
+ get: function() {
154
+ return redactUrls;
155
+ }
156
+ });
157
+ Object.defineProperty(exports, "restartMessage", {
158
+ enumerable: true,
159
+ get: function() {
160
+ return restartMessage;
161
+ }
162
+ });
163
+ Object.defineProperty(exports, "transportMessage", {
164
+ enumerable: true,
165
+ get: function() {
166
+ return transportMessage;
167
+ }
168
+ });
169
+ Object.defineProperty(exports, "unsignedMessage", {
170
+ enumerable: true,
171
+ get: function() {
172
+ return unsignedMessage;
173
+ }
174
+ });
@@ -0,0 +1,105 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-BGT596CS.cjs");
2
+ //#region ../../node_modules/.pnpm/p-map@7.0.4/node_modules/p-map/index.js
3
+ async function pMap(iterable, mapper, { concurrency = Number.POSITIVE_INFINITY, stopOnError = true, signal } = {}) {
4
+ return new Promise((resolve_, reject_) => {
5
+ if (iterable[Symbol.iterator] === void 0 && iterable[Symbol.asyncIterator] === void 0) throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof iterable})`);
6
+ if (typeof mapper !== "function") throw new TypeError("Mapper function is required");
7
+ if (!(Number.isSafeInteger(concurrency) && concurrency >= 1 || concurrency === Number.POSITIVE_INFINITY)) throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\` (${typeof concurrency})`);
8
+ const result = [];
9
+ const errors = [];
10
+ const skippedIndexesMap = /* @__PURE__ */ new Map();
11
+ let isRejected = false;
12
+ let isResolved = false;
13
+ let isIterableDone = false;
14
+ let resolvingCount = 0;
15
+ let currentIndex = 0;
16
+ const iterator = iterable[Symbol.iterator] === void 0 ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
17
+ const signalListener = () => {
18
+ reject(signal.reason);
19
+ };
20
+ const cleanup = () => {
21
+ signal?.removeEventListener("abort", signalListener);
22
+ };
23
+ const resolve = (value) => {
24
+ resolve_(value);
25
+ cleanup();
26
+ };
27
+ const reject = (reason) => {
28
+ isRejected = true;
29
+ isResolved = true;
30
+ reject_(reason);
31
+ cleanup();
32
+ };
33
+ if (signal) {
34
+ if (signal.aborted) reject(signal.reason);
35
+ signal.addEventListener("abort", signalListener, { once: true });
36
+ }
37
+ const next = async () => {
38
+ if (isResolved) return;
39
+ const nextItem = await iterator.next();
40
+ const index = currentIndex;
41
+ currentIndex++;
42
+ if (nextItem.done) {
43
+ isIterableDone = true;
44
+ if (resolvingCount === 0 && !isResolved) {
45
+ if (!stopOnError && errors.length > 0) {
46
+ reject(new AggregateError(errors));
47
+ return;
48
+ }
49
+ isResolved = true;
50
+ if (skippedIndexesMap.size === 0) {
51
+ resolve(result);
52
+ return;
53
+ }
54
+ const pureResult = [];
55
+ for (const [index, value] of result.entries()) {
56
+ if (skippedIndexesMap.get(index) === pMapSkip) continue;
57
+ pureResult.push(value);
58
+ }
59
+ resolve(pureResult);
60
+ }
61
+ return;
62
+ }
63
+ resolvingCount++;
64
+ (async () => {
65
+ try {
66
+ const element = await nextItem.value;
67
+ if (isResolved) return;
68
+ const value = await mapper(element, index);
69
+ if (value === pMapSkip) skippedIndexesMap.set(index, value);
70
+ result[index] = value;
71
+ resolvingCount--;
72
+ await next();
73
+ } catch (error) {
74
+ if (stopOnError) reject(error);
75
+ else {
76
+ errors.push(error);
77
+ resolvingCount--;
78
+ try {
79
+ await next();
80
+ } catch (error) {
81
+ reject(error);
82
+ }
83
+ }
84
+ }
85
+ })();
86
+ };
87
+ (async () => {
88
+ for (let index = 0; index < concurrency; index++) {
89
+ try {
90
+ await next();
91
+ } catch (error) {
92
+ reject(error);
93
+ break;
94
+ }
95
+ if (isIterableDone || isRejected) break;
96
+ }
97
+ })();
98
+ });
99
+ }
100
+ var pMapSkip;
101
+ //#endregion
102
+ require_rolldown_runtime.__esmMin((() => {
103
+ pMapSkip = Symbol("skip");
104
+ }))();
105
+ exports.default = pMap;
@@ -0,0 +1,127 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-BGT596CS.cjs");
2
+ let node_child_process = require("node:child_process");
3
+ let node_path = require("node:path");
4
+ let node_fs = require("node:fs");
5
+ //#region src/state/proc.ts
6
+ var proc_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
7
+ isLive: () => isLive,
8
+ ownIdentity: () => ownIdentity,
9
+ powershellPath: () => powershellPath,
10
+ shellBinary: () => shellBinary,
11
+ startIdentity: () => startIdentity
12
+ });
13
+ function powershellPath(env = process.env) {
14
+ return (0, node_path.join)(env["SystemRoot"] ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
15
+ }
16
+ const SHELL_DIRS = [
17
+ "/bin",
18
+ "/usr/bin",
19
+ "/usr/local/bin",
20
+ "/opt/homebrew/bin",
21
+ "/snap/bin"
22
+ ];
23
+ /**
24
+ * An absolute path for a shell to probe (spec SEC-8): the login shell when `$SHELL` is absolute, else system dirs.
25
+ * Never PATH, which inside an npm script starts with `node_modules/.bin`.
26
+ */
27
+ function shellBinary(shell, env = process.env, platform = process.platform) {
28
+ const name = shell === "powershell" ? "pwsh" : shell;
29
+ if (platform === "win32") {
30
+ const pwsh = (0, node_path.join)(env["ProgramFiles"] ?? "C:\\Program Files", "PowerShell", "7", "pwsh.exe");
31
+ return shell === "powershell" && (0, node_fs.existsSync)(pwsh) ? pwsh : null;
32
+ }
33
+ const login = env["SHELL"];
34
+ return [...login !== void 0 && (0, node_path.isAbsolute)(login) && (0, node_path.basename)(login) === name ? [login] : [], ...SHELL_DIRS.map((dir) => (0, node_path.join)(dir, name))].find((candidate) => (0, node_fs.existsSync)(candidate)) ?? null;
35
+ }
36
+ /** The start identity of `pid`, or null when the lookup fails or is ambiguous. */
37
+ function startIdentity(pid, platform = process.platform, env = process.env) {
38
+ try {
39
+ if (platform === "linux") {
40
+ const stat = (0, node_fs.readFileSync)(`/proc/${pid}/stat`, "utf8");
41
+ const start = stat.slice(stat.lastIndexOf(")") + 1).trim().split(/\s+/)[19];
42
+ return start !== void 0 && /^\d+$/.test(start) ? start : null;
43
+ }
44
+ if (platform === "darwin") {
45
+ const out = (0, node_child_process.execFileSync)("/bin/ps", [
46
+ "-o",
47
+ "lstart=",
48
+ "-p",
49
+ String(pid)
50
+ ], {
51
+ encoding: "utf8",
52
+ env: {
53
+ LC_ALL: "C",
54
+ PATH: "/usr/bin:/bin"
55
+ }
56
+ }).trim();
57
+ return out === "" || out.includes("\n") ? null : out;
58
+ }
59
+ if (platform === "win32") {
60
+ const out = (0, node_child_process.execFileSync)(powershellPath(env), [
61
+ "-NoProfile",
62
+ "-NonInteractive",
63
+ "-Command",
64
+ `(Get-Process -Id ${pid}).StartTime.ToFileTimeUtc()`
65
+ ], {
66
+ encoding: "utf8",
67
+ windowsHide: true
68
+ }).trim();
69
+ return /^\d+$/.test(out) ? out : null;
70
+ }
71
+ } catch {
72
+ return null;
73
+ }
74
+ return null;
75
+ }
76
+ function ownIdentity(platform, env) {
77
+ return {
78
+ pid: process.pid,
79
+ start: startIdentity(process.pid, platform, env)
80
+ };
81
+ }
82
+ /**
83
+ * Whether the recorded process still runs: dead only when the PID is gone or its start identity differs.
84
+ * Any failure to look up means live, so nothing ever expires a process that merely cannot be inspected.
85
+ */
86
+ function isLive(identity, platform = process.platform) {
87
+ try {
88
+ process.kill(identity.pid, 0);
89
+ } catch (error) {
90
+ if (error.code === "ESRCH") return false;
91
+ return true;
92
+ }
93
+ if (identity.start === null) return true;
94
+ const current = startIdentity(identity.pid, platform);
95
+ return current === null || current === identity.start;
96
+ }
97
+ //#endregion
98
+ Object.defineProperty(exports, "isLive", {
99
+ enumerable: true,
100
+ get: function() {
101
+ return isLive;
102
+ }
103
+ });
104
+ Object.defineProperty(exports, "ownIdentity", {
105
+ enumerable: true,
106
+ get: function() {
107
+ return ownIdentity;
108
+ }
109
+ });
110
+ Object.defineProperty(exports, "powershellPath", {
111
+ enumerable: true,
112
+ get: function() {
113
+ return powershellPath;
114
+ }
115
+ });
116
+ Object.defineProperty(exports, "proc_exports", {
117
+ enumerable: true,
118
+ get: function() {
119
+ return proc_exports;
120
+ }
121
+ });
122
+ Object.defineProperty(exports, "shellBinary", {
123
+ enumerable: true,
124
+ get: function() {
125
+ return shellBinary;
126
+ }
127
+ });
@@ -0,0 +1,2 @@
1
+ const require_dispatch = require("./dispatch-B9OSfqsn.cjs");
2
+ exports.verifyBundleHere = require_dispatch.verifyBundleHere;
@@ -0,0 +1,64 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esmMin = (fn, res, err) => () => {
9
+ if (err) throw err[0];
10
+ try {
11
+ return fn && (res = fn(fn = 0)), res;
12
+ } catch (e) {
13
+ throw err = [e], e;
14
+ }
15
+ };
16
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
17
+ var __exportAll = (all, no_symbols) => {
18
+ let target = {};
19
+ for (var name in all) __defProp(target, name, {
20
+ get: all[name],
21
+ enumerable: true
22
+ });
23
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
24
+ return target;
25
+ };
26
+ var __copyProps = (to, from, except, desc) => {
27
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
28
+ key = keys[i];
29
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
30
+ get: ((k) => from[k]).bind(null, key),
31
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
32
+ });
33
+ }
34
+ return to;
35
+ };
36
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
37
+ value: mod,
38
+ enumerable: true
39
+ }) : target, mod));
40
+ //#endregion
41
+ Object.defineProperty(exports, "__commonJSMin", {
42
+ enumerable: true,
43
+ get: function() {
44
+ return __commonJSMin;
45
+ }
46
+ });
47
+ Object.defineProperty(exports, "__esmMin", {
48
+ enumerable: true,
49
+ get: function() {
50
+ return __esmMin;
51
+ }
52
+ });
53
+ Object.defineProperty(exports, "__exportAll", {
54
+ enumerable: true,
55
+ get: function() {
56
+ return __exportAll;
57
+ }
58
+ });
59
+ Object.defineProperty(exports, "__toESM", {
60
+ enumerable: true,
61
+ get: function() {
62
+ return __toESM;
63
+ }
64
+ });
@@ -0,0 +1,143 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_messages = require("./messages-vUDkl1-0.cjs");
3
+ const require_install = require("./install-C_M5WK98.cjs");
4
+ const require_src = require("./src-SpeGbMJx.cjs");
5
+ let node_child_process = require("node:child_process");
6
+ let node_path = require("node:path");
7
+ //#region src/runtime.ts
8
+ /** The launcher ABI this runtime needs; a launcher runs runtimes of its own ABI or one below (spec RUN-2). */
9
+ const abi = 1;
10
+ /** Entry point `bootstrap.cjs` calls; returns the exit code. */
11
+ async function main(selector, argv, options) {
12
+ try {
13
+ if (selector === "cli") {
14
+ const { run } = await Promise.resolve().then(() => require("./dispatch-B9OSfqsn.cjs"));
15
+ return await run(argv, {
16
+ home: options.home,
17
+ env: process.env
18
+ });
19
+ }
20
+ return await launch(selector, argv, options.home);
21
+ } catch (error) {
22
+ if (require_messages.isNpmVmError(error)) {
23
+ process.stderr.write(`npm-vm: ${error.message}\n`);
24
+ return error.exitCode;
25
+ }
26
+ process.stderr.write(`npm-vm: ${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
27
+ return require_messages.EXIT.problems;
28
+ }
29
+ }
30
+ /**
31
+ * Finishes journals left by a crashed command before anything else runs (spec RUN-2, MUT-2).
32
+ * The lock is tried once without waiting: npm must never wait on a setup, and `current` is always runnable.
33
+ */
34
+ async function recoverLeftovers(home) {
35
+ const { resolveDirs } = await Promise.resolve().then(() => require("./home-BaoZZSBy.cjs")).then((n) => n.home_exports);
36
+ const { hasJournals, recoverDeadJournals } = await Promise.resolve().then(() => require("./journal-_bs-eJRJ.cjs")).then((n) => n.journal_exports);
37
+ const { lockOwnerLive, readLock, tryLock } = await Promise.resolve().then(() => require("./lock-DBeYN-Zg.cjs")).then((n) => n.lock_exports);
38
+ const { ownerRecord } = await Promise.resolve().then(() => require("./lease-HBD4CmBx.cjs")).then((n) => n.lease_exports);
39
+ const dirs = resolveDirs(process.env, home);
40
+ if (!hasJournals(dirs.journal)) return;
41
+ const owner = ownerRecord(dirs.machine.id);
42
+ const lock = tryLock(dirs.state, owner);
43
+ if (lock === null) {
44
+ const holder = readLock(dirs.state);
45
+ if (!lockOwnerLive(holder, dirs.machine.id)) process.stderr.write(`npm-vm: ${require_messages.lockedMessage((0, node_path.join)(dirs.state, "lock"), holder, false, false)}\n`);
46
+ return;
47
+ }
48
+ try {
49
+ const report = recoverDeadJournals(dirs.journal, dirs.machine.id);
50
+ for (const id of report.changed) process.stderr.write(`npm-vm: ${require_messages.changedMessage(id, "leftover change")}\n`);
51
+ } finally {
52
+ lock.release();
53
+ }
54
+ }
55
+ /** Resolves and runs npm or npx for the current directory (spec RUN-3 to RUN-7). */
56
+ async function launch(selector, argv, home) {
57
+ const env = process.env;
58
+ await recoverLeftovers(home);
59
+ let installer = null;
60
+ const lazy = () => {
61
+ installer ??= Promise.resolve().then(() => require("./install-C_M5WK98.cjs")).then((n) => n.install_exports).then((install) => install.createInstaller(install.createContext(env, home)));
62
+ return installer;
63
+ };
64
+ const providers = {
65
+ nodeVersion: process.version,
66
+ ownNpm: () => require_install.findOwnNpm(),
67
+ cached: async (specs) => (await lazy()).cached(specs),
68
+ registry: async (specs) => (await lazy()).registry(specs),
69
+ entryPathFor: (candidate) => (0, node_path.join)(home, "pending", candidate.version)
70
+ };
71
+ const result = await require_src.resolveNpmWith(argv, process.cwd(), { env }, providers);
72
+ if (result.warning !== null) process.stderr.write(`npm-vm: ${result.warning}\n`);
73
+ const script = selector === "npx" ? "npx-cli.js" : "npm-cli.js";
74
+ if (result.kind === "own" || result.selection === null) return runChild((0, node_path.join)((0, node_path.dirname)(result.cliPath), script), argv, null);
75
+ const ensured = await (await lazy()).ensure(result.selection);
76
+ const { createLease, ownerRecord } = await Promise.resolve().then(() => require("./lease-HBD4CmBx.cjs")).then((n) => n.lease_exports);
77
+ const { startIdentity } = await Promise.resolve().then(() => require("./proc-hB8N9WjN.cjs")).then((n) => n.proc_exports);
78
+ const { resolveDirs } = await Promise.resolve().then(() => require("./home-BaoZZSBy.cjs")).then((n) => n.home_exports);
79
+ const machineId = resolveDirs(env, home).machine.id;
80
+ const leaseForChild = (child) => {
81
+ const pid = child.pid;
82
+ return createLease(ensured.entryPath, ownerRecord(machineId, {
83
+ pid,
84
+ start: startIdentity(pid)
85
+ })).release;
86
+ };
87
+ return runChild((0, node_path.join)(ensured.entryPath, "bin", script), argv, ensured.lease.release, leaseForChild);
88
+ }
89
+ const FORWARD_NOW = ["SIGTERM", "SIGHUP"];
90
+ const FORWARD_LATER = ["SIGINT", "SIGQUIT"];
91
+ const LATER_DELAY_MS = 1e3;
92
+ function alive(child) {
93
+ return child.exitCode === null && child.signalCode === null;
94
+ }
95
+ /**
96
+ * Spawns npm with inherited stdio and mirrors its exit (spec RUN-3 to RUN-5).
97
+ * SIGTERM and SIGHUP are forwarded at once; SIGINT and SIGQUIT only if the child outlives them by a second, since a terminal already hit the whole group.
98
+ */
99
+ function runChild(script, argv, release, onSpawn = null) {
100
+ return new Promise((resolve) => {
101
+ const child = (0, node_child_process.spawn)(process.execPath, [script, ...argv], {
102
+ stdio: "inherit",
103
+ env: process.env
104
+ });
105
+ const releaseChild = child.pid === void 0 ? null : onSpawn?.(child) ?? null;
106
+ const handlers = [];
107
+ const timers = [];
108
+ if (process.platform !== "win32") {
109
+ for (const signal of FORWARD_NOW) handlers.push([signal, () => child.kill(signal)]);
110
+ for (const signal of FORWARD_LATER) handlers.push([signal, () => {
111
+ const timer = setTimeout(() => {
112
+ if (alive(child)) child.kill(signal);
113
+ }, LATER_DELAY_MS);
114
+ timer.unref();
115
+ timers.push(timer);
116
+ }]);
117
+ for (const [signal, handler] of handlers) process.on(signal, handler);
118
+ }
119
+ const cleanup = () => {
120
+ for (const [signal, handler] of handlers) process.removeListener(signal, handler);
121
+ for (const timer of timers) clearTimeout(timer);
122
+ releaseChild?.();
123
+ release?.();
124
+ };
125
+ child.on("error", (error) => {
126
+ cleanup();
127
+ process.stderr.write(`npm-vm: cannot start ${script}: ${error.message}\n`);
128
+ resolve(require_messages.EXIT.problems);
129
+ });
130
+ child.on("exit", (code, signal) => {
131
+ cleanup();
132
+ if (signal !== null) {
133
+ process.kill(process.pid, signal);
134
+ return;
135
+ }
136
+ resolve(code ?? require_messages.EXIT.problems);
137
+ });
138
+ });
139
+ }
140
+ //#endregion
141
+ exports.abi = abi;
142
+ exports.main = main;
143
+ exports.runChild = runChild;