@foundry-rs/forge 1.4.4-nightly.20251028.b32f4ee → 1.4.4-nightly.20251029.b1964f9

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 CHANGED
@@ -1,4 +1,4 @@
1
1
  # Forge
2
2
 
3
3
  Forge is a command-line tool that ships with Foundry. Forge tests, builds, and deploys your smart contracts.
4
- Forge is part of the Foundry suite and is installed alongside `cast`, `chisel`, and `anvil`.
4
+ The forge binary can be used both within and outside of a Foundry project.
package/bin.mjs ADDED
@@ -0,0 +1,117 @@
1
+ import { BINARY_NAME, colors, KNOWN_TOOLS, PLATFORM_SPECIFIC_PACKAGE_NAME, resolveTargetTool } from './postinstall.mjs'
2
+ import * as NodeChildProcess from 'node:child_process'
3
+ import * as NodeFS from 'node:fs'
4
+ import * as NodeModule from 'node:module'
5
+ import * as NodePath from 'node:path'
6
+ import { fileURLToPath } from 'node:url'
7
+
8
+ /**
9
+ * @typedef {import('./postinstall.mjs').Tool} Tool
10
+ */
11
+
12
+ const require = NodeModule.createRequire(import.meta.url)
13
+ const __dirname = NodePath.dirname(fileURLToPath(import.meta.url))
14
+
15
+ const targetTool = resolveTool()
16
+ process.env.TARGET_TOOL ??= targetTool
17
+
18
+ const binaryName = BINARY_NAME(targetTool)
19
+ const platformPackage = PLATFORM_SPECIFIC_PACKAGE_NAME(targetTool)
20
+
21
+ if (!platformPackage) {
22
+ console.error(colors.red, 'Platform not supported!')
23
+ console.error(colors.reset)
24
+ console.error(colors.yellow, `Platform: ${process.platform}, Architecture: ${process.arch}`)
25
+ console.error(colors.reset)
26
+ process.exit(1)
27
+ }
28
+
29
+ NodeChildProcess.spawn(selectBinaryPath(), process.argv.slice(2), { stdio: 'inherit' })
30
+
31
+ /**
32
+ * Determines which tool wrapper is executing.
33
+ * @returns {Tool}
34
+ */
35
+ function resolveTool() {
36
+ const candidates = [
37
+ process.env.TARGET_TOOL,
38
+ toolFromPackageName(process.env.npm_package_name),
39
+ toolFromLocalPackage(),
40
+ toolFromPath()
41
+ ]
42
+
43
+ for (const candidate of candidates) {
44
+ if (!candidate) continue
45
+ try {
46
+ return resolveTargetTool(candidate)
47
+ } catch {
48
+ // try next
49
+ }
50
+ }
51
+
52
+ throw new Error('TARGET_TOOL must be set to one of: ' + KNOWN_TOOLS.join(', '))
53
+ }
54
+
55
+ /**
56
+ * Attempts to read the tool name from the nearest package.json.
57
+ * @returns {Tool | undefined}
58
+ */
59
+ function toolFromLocalPackage() {
60
+ try {
61
+ const packageJsonPath = NodePath.join(__dirname, 'package.json')
62
+ if (!NodeFS.existsSync(packageJsonPath)) return undefined
63
+ const pkg = require(packageJsonPath)
64
+ return toolFromPackageName(pkg?.name)
65
+ } catch {
66
+ return undefined
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Extracts the tool name from an @foundry-rs scoped package identifier.
72
+ * @param {unknown} name
73
+ * @returns {Tool | undefined}
74
+ */
75
+ function toolFromPackageName(name) {
76
+ if (typeof name !== 'string') return undefined
77
+ const match = name.match(/^@foundry-rs\/(forge|cast|anvil|chisel)(?:$|-)/)
78
+ return match ? /** @type {Tool} */ (match[1]) : undefined
79
+ }
80
+
81
+ /**
82
+ * Walks up the directory tree to infer the tool name from the folder structure.
83
+ * @returns {Tool | undefined}
84
+ */
85
+ function toolFromPath() {
86
+ const segments = NodePath.resolve(__dirname).split(NodePath.sep)
87
+ for (let i = segments.length - 1; i >= 0; i--) {
88
+ const candidate = segments[i]
89
+ if (isTool(candidate)) return candidate
90
+ }
91
+ return undefined
92
+ }
93
+
94
+ /**
95
+ * Type guard verifying a candidate string is a known tool.
96
+ * @param {string | undefined} candidate
97
+ * @returns {candidate is Tool}
98
+ */
99
+ function isTool(candidate) {
100
+ if (typeof candidate !== 'string') return false
101
+ return KNOWN_TOOLS.includes(/** @type {Tool} */ (candidate))
102
+ }
103
+
104
+ /**
105
+ * Determines the executable file path for the current platform.
106
+ * @returns {string}
107
+ */
108
+ function selectBinaryPath() {
109
+ try {
110
+ const candidate = require.resolve(`${platformPackage}/bin/${binaryName}`)
111
+ if (NodeFS.existsSync(candidate)) return candidate
112
+ } catch {
113
+ // fall through to dist/ binary
114
+ }
115
+
116
+ return NodePath.join(__dirname, '..', 'dist', binaryName)
117
+ }
package/package.json CHANGED
@@ -1,25 +1,25 @@
1
1
  {
2
2
  "name": "@foundry-rs/forge",
3
- "version": "1.4.4-nightly.20251028.b32f4ee",
3
+ "version": "1.4.4-nightly.20251029.b1964f9",
4
4
  "type": "module",
5
5
  "homepage": "https://getfoundry.sh/forge",
6
6
  "description": "Fast and flexible Ethereum testing framework",
7
7
  "bin": {
8
- "forge": "./bin/forge.mjs"
8
+ "forge": "./bin.mjs"
9
9
  },
10
10
  "files": [
11
- "bin",
12
- "dist"
11
+ "bin.mjs",
12
+ "postinstall.mjs"
13
13
  ],
14
14
  "scripts": {
15
- "postinstall": "node ./dist/install.mjs"
15
+ "postinstall": "node ./postinstall.mjs"
16
16
  },
17
17
  "optionalDependencies": {
18
- "@foundry-rs/forge-darwin-arm64": "1.4.4-nightly.20251028.b32f4ee",
19
- "@foundry-rs/forge-darwin-amd64": "1.4.4-nightly.20251028.b32f4ee",
20
- "@foundry-rs/forge-linux-arm64": "1.4.4-nightly.20251028.b32f4ee",
21
- "@foundry-rs/forge-linux-amd64": "1.4.4-nightly.20251028.b32f4ee",
22
- "@foundry-rs/forge-win32-amd64": "1.4.4-nightly.20251028.b32f4ee"
18
+ "@foundry-rs/forge-darwin-arm64": "1.4.4-nightly.20251029.b1964f9",
19
+ "@foundry-rs/forge-darwin-amd64": "1.4.4-nightly.20251029.b1964f9",
20
+ "@foundry-rs/forge-linux-arm64": "1.4.4-nightly.20251029.b1964f9",
21
+ "@foundry-rs/forge-linux-amd64": "1.4.4-nightly.20251029.b1964f9",
22
+ "@foundry-rs/forge-win32-amd64": "1.4.4-nightly.20251029.b1964f9"
23
23
  },
24
24
  "publishConfig": {
25
25
  "access": "public",
@@ -30,5 +30,8 @@
30
30
  "repository": {
31
31
  "directory": "npm",
32
32
  "url": "https://github.com/foundry-rs/foundry"
33
+ },
34
+ "imports": {
35
+ "#const.mjs": "./postinstall.mjs"
33
36
  }
34
37
  }
@@ -0,0 +1,265 @@
1
+ // src/install.mjs
2
+ import * as NodeCrypto from "node:crypto";
3
+ import * as NodeFS from "node:fs";
4
+ import * as NodeHttp from "node:http";
5
+ import * as NodeHttps from "node:https";
6
+ import * as NodeModule from "node:module";
7
+ import * as NodePath2 from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import * as NodeZlib from "node:zlib";
10
+
11
+ // src/const.mjs
12
+ import * as NodePath from "node:path";
13
+ var KNOWN_TOOLS = Object.freeze(["forge", "cast", "anvil", "chisel"]);
14
+ var TOOL_SET = new Set(KNOWN_TOOLS);
15
+ function resolveTargetTool(raw = process.env.TARGET_TOOL) {
16
+ const value = typeof raw === "string" ? raw.trim() : "";
17
+ if (!value)
18
+ throw new Error("TARGET_TOOL must be set to one of: " + KNOWN_TOOLS.join(", "));
19
+ if (value !== NodePath.basename(value) || value.includes("..") || value.includes("/") || value.includes("\\"))
20
+ throw new Error("TARGET_TOOL contains invalid path segments");
21
+ if (!TOOL_SET.has(value))
22
+ throw new Error(`TARGET_TOOL "${value}" is not supported. Expected: ${KNOWN_TOOLS.join(", ")}`);
23
+ return value;
24
+ }
25
+ function getRegistryUrl() {
26
+ return process.env.npm_config_registry || process.env.REGISTRY_URL || "https://registry.npmjs.org";
27
+ }
28
+ var BINARY_DISTRIBUTION_PACKAGES = (tool) => ({
29
+ darwin: {
30
+ x64: `@foundry-rs/${tool}-darwin-amd64`,
31
+ arm64: `@foundry-rs/${tool}-darwin-arm64`
32
+ },
33
+ linux: {
34
+ x64: `@foundry-rs/${tool}-linux-amd64`,
35
+ arm64: `@foundry-rs/${tool}-linux-arm64`
36
+ },
37
+ win32: {
38
+ x64: `@foundry-rs/${tool}-win32-amd64`
39
+ }
40
+ });
41
+ var BINARY_NAME = (tool) => process.platform === "win32" ? `${tool}.exe` : tool;
42
+ var PLATFORM_SPECIFIC_PACKAGE_NAME = (tool) => {
43
+ const platformPackages = BINARY_DISTRIBUTION_PACKAGES(tool)[process.platform];
44
+ if (!platformPackages)
45
+ return;
46
+ return platformPackages?.[process.arch];
47
+ };
48
+ var colors = {
49
+ red: "\x1B[31m",
50
+ green: "\x1B[32m",
51
+ yellow: "\x1B[33m",
52
+ blue: "\x1B[34m",
53
+ magenta: "\x1B[35m",
54
+ cyan: "\x1B[36m",
55
+ white: "\x1B[37m",
56
+ reset: "\x1B[0m"
57
+ };
58
+
59
+ // src/install.mjs
60
+ var __dirname2 = NodePath2.dirname(fileURLToPath(import.meta.url));
61
+ var targetTool = resolveTargetTool();
62
+ var binaryName = BINARY_NAME(targetTool);
63
+ var fallbackBinaryPath = NodePath2.join(__dirname2, binaryName);
64
+ var platformSpecificPackageName = PLATFORM_SPECIFIC_PACKAGE_NAME(targetTool);
65
+ var expectedTarEntryPath = `package/bin/${binaryName}`;
66
+ if (NodePath2.relative(__dirname2, fallbackBinaryPath).startsWith(".."))
67
+ throw new Error("Resolved binary path escapes package directory");
68
+ if (!platformSpecificPackageName)
69
+ throw new Error("Platform not supported!");
70
+ var require2 = NodeModule.createRequire(import.meta.url);
71
+ function ensureSecureUrl(urlString, purpose) {
72
+ try {
73
+ const url = new URL(urlString);
74
+ if (url.protocol === "http:") {
75
+ const allowInsecure = process.env.ALLOW_INSECURE_REGISTRY === "true";
76
+ if (!["localhost", "127.0.0.1", "::1"].includes(url.hostname) && !allowInsecure) {
77
+ throw new Error(`Refusing to use insecure HTTP for ${purpose}: ${urlString}. ` + `Set ALLOW_INSECURE_REGISTRY=true to override (not recommended).`);
78
+ }
79
+ }
80
+ } catch {}
81
+ }
82
+ var MAX_REDIRECTS = 10;
83
+ var REQUEST_TIMEOUT = 30000;
84
+ var MAX_METADATA_BYTES = 5 * 1024 * 1024;
85
+ var MAX_TARBALL_BYTES = 200 * 1024 * 1024;
86
+ var MAX_BINARY_BYTES = 500 * 1024 * 1024;
87
+ function makeRequest(url, options = {}) {
88
+ const {
89
+ parentSignal,
90
+ redirectDepth = 0,
91
+ visited = new Set,
92
+ maxBytes,
93
+ collect = true,
94
+ onChunk
95
+ } = options;
96
+ if (redirectDepth > MAX_REDIRECTS)
97
+ throw new Error("Maximum redirect depth exceeded");
98
+ if (visited.has(url))
99
+ throw new Error("Circular redirect detected");
100
+ visited.add(url);
101
+ ensureSecureUrl(url, "HTTP request");
102
+ const controller = new AbortController;
103
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT);
104
+ const signal = parentSignal ? AbortSignal.any([parentSignal, controller.signal]) : controller.signal;
105
+ return new Promise((resolve, reject) => {
106
+ const client = url.startsWith("https:") ? NodeHttps : NodeHttp;
107
+ const request = client.get(url, { signal }, (response) => {
108
+ const finish = (error, value = undefined) => {
109
+ clearTimeout(timer);
110
+ if (error)
111
+ reject(error);
112
+ else
113
+ resolve(value);
114
+ };
115
+ if (response?.statusCode && response.statusCode >= 200 && response.statusCode < 300) {
116
+ let totalBytes = 0;
117
+ const chunks = collect ? [] : undefined;
118
+ response.on("data", (chunk) => {
119
+ totalBytes += chunk.length;
120
+ if (maxBytes && totalBytes > maxBytes) {
121
+ response.destroy(new Error("Response exceeded maximum allowed size"));
122
+ return;
123
+ }
124
+ if (chunks)
125
+ chunks.push(chunk);
126
+ if (onChunk) {
127
+ try {
128
+ onChunk(chunk, response);
129
+ } catch (error) {
130
+ response.destroy(error instanceof Error ? error : new Error(`Error occurred: ${error}`));
131
+ }
132
+ }
133
+ });
134
+ response.on("end", () => {
135
+ finish(null, chunks ? Buffer.concat(chunks) : undefined);
136
+ });
137
+ response.on("error", finish);
138
+ } else if (response?.statusCode && response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) {
139
+ clearTimeout(timer);
140
+ const nextUrl = new URL(response.headers.location, url).href;
141
+ return makeRequest(nextUrl, {
142
+ parentSignal: signal,
143
+ redirectDepth: redirectDepth + 1,
144
+ visited,
145
+ maxBytes,
146
+ collect,
147
+ onChunk
148
+ }).then(resolve, reject);
149
+ } else {
150
+ finish(new Error(`Package registry responded with status code ${response?.statusCode ?? "(none)"} when downloading the package.`));
151
+ }
152
+ });
153
+ request.on("error", (error) => {
154
+ clearTimeout(timer);
155
+ reject(error);
156
+ });
157
+ });
158
+ }
159
+ function extractFileFromTarball(tarballBuffer, filepath) {
160
+ let offset = 0;
161
+ while (offset < tarballBuffer.length) {
162
+ const header = tarballBuffer.subarray(offset, offset + 512);
163
+ offset += 512;
164
+ const fileName = header.toString("utf-8", 0, 100).replace(/\0.*/g, "");
165
+ const fileSize = Number.parseInt(header.toString("utf-8", 124, 136).replace(/\0.*/g, ""), 8);
166
+ if (fileName === filepath) {
167
+ if (!Number.isFinite(fileSize) || Number.isNaN(fileSize) || fileSize < 0)
168
+ throw new Error(`Invalid size for ${filepath} in tarball`);
169
+ if (fileSize > MAX_BINARY_BYTES)
170
+ throw new Error(`Binary size for ${filepath} exceeds maximum allowed threshold`);
171
+ return tarballBuffer.subarray(offset, offset + fileSize);
172
+ }
173
+ offset = offset + fileSize + 511 & ~511;
174
+ }
175
+ throw new Error(`File ${filepath} not found in tarball`);
176
+ }
177
+ async function downloadBinaryFromRegistry() {
178
+ if (!platformSpecificPackageName)
179
+ throw new Error("Platform-specific package name is not defined");
180
+ const registryUrl = getRegistryUrl().replace(/\/$/, "");
181
+ ensureSecureUrl(registryUrl, "registry URL");
182
+ const encodedName = platformSpecificPackageName.startsWith("@") ? encodeURIComponent(platformSpecificPackageName) : platformSpecificPackageName;
183
+ let desiredVersion;
184
+ try {
185
+ const pkgJsonPath = NodePath2.join(__dirname2, "..", "package.json");
186
+ const pkgJson = JSON.parse(NodeFS.readFileSync(pkgJsonPath, "utf8"));
187
+ desiredVersion = pkgJson?.optionalDependencies[platformSpecificPackageName] || pkgJson?.version;
188
+ } catch {}
189
+ const metaUrl = `${registryUrl}/${encodedName}`;
190
+ const metaBuffer = await makeRequest(metaUrl, { maxBytes: MAX_METADATA_BYTES });
191
+ if (!metaBuffer)
192
+ throw new Error("Failed to download package metadata");
193
+ const metadata = JSON.parse(metaBuffer.toString("utf8"));
194
+ const version = desiredVersion || metadata?.["dist-tags"]?.latest;
195
+ const versionMeta = metadata?.versions?.[version];
196
+ const dist = versionMeta?.dist;
197
+ if (!dist?.tarball) {
198
+ throw new Error(`Could not find tarball for ${platformSpecificPackageName}@${version} from ${metaUrl}`);
199
+ }
200
+ ensureSecureUrl(dist.tarball, "tarball URL");
201
+ console.info(colors.green, `Downloading binary from:
202
+ `, dist.tarball, `
203
+ `, colors.reset);
204
+ const integrity = typeof dist.integrity === "string" ? dist.integrity : "";
205
+ const sriMatch = integrity.match(/^([a-z0-9]+)-([A-Za-z0-9+/=]+)$/i);
206
+ const allowedSRIAlgorithms = new Set(["sha512", "sha256", "sha1"]);
207
+ const sriAlgo = sriMatch && allowedSRIAlgorithms.has(sriMatch[1].toLowerCase()) ? sriMatch[1].toLowerCase() : undefined;
208
+ const expectedSri = sriAlgo ? sriMatch?.[2] : undefined;
209
+ const sriHasher = sriAlgo ? NodeCrypto.createHash(sriAlgo) : undefined;
210
+ const expectedSha1Hex = typeof dist.shasum === "string" && dist.shasum.length === 40 ? dist.shasum.toLowerCase() : undefined;
211
+ const sha1Hasher = expectedSha1Hex ? NodeCrypto.createHash("sha1") : undefined;
212
+ const tarballDownloadBuffer = await makeRequest(dist.tarball, {
213
+ maxBytes: MAX_TARBALL_BYTES,
214
+ onChunk: (chunk) => {
215
+ sriHasher?.update(chunk);
216
+ sha1Hasher?.update(chunk);
217
+ }
218
+ });
219
+ if (!tarballDownloadBuffer)
220
+ throw new Error("Failed to download tarball contents");
221
+ let verified = false;
222
+ if (sriHasher && expectedSri) {
223
+ const actual = sriHasher.digest("base64");
224
+ if (expectedSri !== actual) {
225
+ throw new Error(`Downloaded tarball failed integrity check (${sriAlgo} mismatch)`);
226
+ }
227
+ verified = true;
228
+ }
229
+ if (!verified && sha1Hasher && expectedSha1Hex) {
230
+ const actualSha1Hex = sha1Hasher.digest("hex");
231
+ if (expectedSha1Hex !== actualSha1Hex) {
232
+ throw new Error("Downloaded tarball failed integrity check (sha1 shasum mismatch)");
233
+ }
234
+ verified = true;
235
+ }
236
+ if (!verified) {
237
+ const allowNoIntegrity = process.env.ALLOW_NO_INTEGRITY === "true" || process.env.ALLOW_UNVERIFIED_TARBALL === "true";
238
+ if (!allowNoIntegrity) {
239
+ throw new Error("No integrity metadata found for downloaded tarball. " + "Set ALLOW_NO_INTEGRITY=true to bypass (not recommended).");
240
+ }
241
+ console.warn(colors.yellow, "Warning: proceeding without integrity verification (explicitly allowed).", colors.reset);
242
+ }
243
+ const tarballBuffer = NodeZlib.gunzipSync(tarballDownloadBuffer);
244
+ NodeFS.writeFileSync(fallbackBinaryPath, extractFileFromTarball(tarballBuffer, expectedTarEntryPath), { mode: 493 });
245
+ }
246
+ function isPlatformSpecificPackageInstalled() {
247
+ try {
248
+ require2.resolve(`${platformSpecificPackageName}/bin/${binaryName}`);
249
+ return true;
250
+ } catch {
251
+ return false;
252
+ }
253
+ }
254
+ if (!isPlatformSpecificPackageInstalled()) {
255
+ console.log("Platform specific package not found. Will manually download binary.");
256
+ downloadBinaryFromRegistry().catch((error) => {
257
+ console.error(colors.red, "Failed to download binary:", error, colors.reset);
258
+ process.exitCode = 1;
259
+ });
260
+ } else {
261
+ console.log("Platform specific package already installed. Skipping manual download.");
262
+ }
263
+ export {
264
+ makeRequest
265
+ };
package/bin/forge.mjs DELETED
@@ -1,54 +0,0 @@
1
- #!/usr/bin/env node
2
- import * as NodeModule from "node:module";
3
- import * as NodeChildProcess from "node:child_process";
4
- import * as NodeFS from "node:fs";
5
- import * as NodePath from "node:path";
6
- import { fileURLToPath } from "node:url";
7
-
8
- //#region src/const.ts
9
- const BINARY_DISTRIBUTION_PACKAGES = {
10
- darwin: {
11
- x64: "@foundry-rs/forge-darwin-amd64",
12
- arm64: "@foundry-rs/forge-darwin-arm64"
13
- },
14
- linux: {
15
- x64: "@foundry-rs/forge-linux-amd64",
16
- arm64: "@foundry-rs/forge-linux-arm64"
17
- },
18
- win32: { x64: "@foundry-rs/forge-win32-amd64" }
19
- };
20
- const BINARY_NAME = process.platform === "win32" ? "forge.exe" : "forge";
21
- const PLATFORM_SPECIFIC_PACKAGE_NAME = BINARY_DISTRIBUTION_PACKAGES[process.platform][process.arch];
22
- const colors = {
23
- red: "\x1B[31m",
24
- green: "\x1B[32m",
25
- yellow: "\x1B[33m",
26
- blue: "\x1B[34m",
27
- magenta: "\x1B[35m",
28
- cyan: "\x1B[36m",
29
- white: "\x1B[37m",
30
- reset: "\x1B[0m"
31
- };
32
-
33
- //#endregion
34
- //#region src/forge.ts
35
- const require = NodeModule.createRequire(import.meta.url);
36
- const __dirname = NodePath.dirname(fileURLToPath(import.meta.url));
37
- function getBinaryPath() {
38
- try {
39
- const binaryPath = require.resolve(`${PLATFORM_SPECIFIC_PACKAGE_NAME}/bin/${BINARY_NAME}`);
40
- if (NodeFS.existsSync(binaryPath)) return binaryPath;
41
- } catch {
42
- return NodePath.join(__dirname, "..", "dist", BINARY_NAME);
43
- }
44
- console.error(colors.red, `Platform-specific package ${PLATFORM_SPECIFIC_PACKAGE_NAME} not found.`);
45
- console.error(colors.yellow, "This usually means the installation failed or your platform is not supported.");
46
- console.error(colors.reset);
47
- console.error(colors.yellow, `Platform: ${process.platform}, Architecture: ${process.arch}`);
48
- console.error(colors.reset);
49
- process.exit(1);
50
- }
51
- NodeChildProcess.spawn(getBinaryPath(), process.argv.slice(2), { stdio: "inherit" });
52
-
53
- //#endregion
54
- export { };
package/dist/install.mjs DELETED
@@ -1,171 +0,0 @@
1
- #!/usr/bin/env node
2
- import * as NodeModule from "node:module";
3
- import * as NodeCrypto from "node:crypto";
4
- import * as NodeFS from "node:fs";
5
- import * as NodeHttp from "node:http";
6
- import * as NodeHttps from "node:https";
7
- import * as NodePath from "node:path";
8
- import { fileURLToPath } from "node:url";
9
- import * as NodeZlib from "node:zlib";
10
-
11
- //#region src/const.ts
12
- function getRegistryUrl() {
13
- return process.env.npm_config_registry || process.env.REGISTRY_URL || "https://registry.npmjs.org";
14
- }
15
- const BINARY_DISTRIBUTION_PACKAGES = {
16
- darwin: {
17
- x64: "@foundry-rs/forge-darwin-amd64",
18
- arm64: "@foundry-rs/forge-darwin-arm64"
19
- },
20
- linux: {
21
- x64: "@foundry-rs/forge-linux-amd64",
22
- arm64: "@foundry-rs/forge-linux-arm64"
23
- },
24
- win32: { x64: "@foundry-rs/forge-win32-amd64" }
25
- };
26
- const BINARY_NAME = process.platform === "win32" ? "forge.exe" : "forge";
27
- const PLATFORM_SPECIFIC_PACKAGE_NAME = BINARY_DISTRIBUTION_PACKAGES[process.platform][process.arch];
28
- const colors = {
29
- red: "\x1B[31m",
30
- green: "\x1B[32m",
31
- yellow: "\x1B[33m",
32
- blue: "\x1B[34m",
33
- magenta: "\x1B[35m",
34
- cyan: "\x1B[36m",
35
- white: "\x1B[37m",
36
- reset: "\x1B[0m"
37
- };
38
-
39
- //#endregion
40
- //#region src/install.ts
41
- const __dirname = NodePath.dirname(fileURLToPath(import.meta.url));
42
- const fallbackBinaryPath = NodePath.join(__dirname, BINARY_NAME);
43
- const require = NodeModule.createRequire(import.meta.url);
44
- const isLocalhostHost = (hostname) => hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
45
- function ensureSecureUrl(urlString, purpose) {
46
- try {
47
- const url = new URL(urlString);
48
- if (url.protocol === "http:") {
49
- const allowInsecure = process.env.ALLOW_INSECURE_REGISTRY === "true";
50
- if (!isLocalhostHost(url.hostname) && !allowInsecure) throw new Error(`Refusing to use insecure HTTP for ${purpose}: ${urlString}. Set ALLOW_INSECURE_REGISTRY=true to override (not recommended).`);
51
- }
52
- } catch {}
53
- }
54
- function makeRequest(url) {
55
- return new Promise((resolve, reject) => {
56
- ensureSecureUrl(url, "HTTP request");
57
- (url.startsWith("https:") ? NodeHttps : NodeHttp).get(url, (response) => {
58
- if (response?.statusCode && response.statusCode >= 200 && response.statusCode < 300) {
59
- const chunks = [];
60
- response.on("data", (chunk) => chunks.push(chunk));
61
- response.on("end", () => resolve(Buffer.concat(chunks)));
62
- } else if (response?.statusCode && response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) {
63
- const redirected = (() => {
64
- try {
65
- return new URL(response.headers.location, url).href;
66
- } catch {
67
- return response.headers.location;
68
- }
69
- })();
70
- makeRequest(redirected).then(resolve, reject);
71
- } else reject(/* @__PURE__ */ new Error(`Package registry responded with status code ${response.statusCode} when downloading the package.`));
72
- }).on("error", (error) => reject(error));
73
- });
74
- }
75
- /**
76
- * Scoped package names should be percent-encoded
77
- * e.g. @scope/pkg -> %40scope%2Fpkg
78
- */
79
- const encodePackageNameForRegistry = (name) => name.startsWith("@") ? encodeURIComponent(name) : name;
80
- /**
81
- * Tar archives are organized in 512 byte blocks.
82
- * Blocks can either be header blocks or data blocks.
83
- * Header blocks contain file names of the archive in the first 100 bytes, terminated by a null byte.
84
- * The size of a file is contained in bytes 124-135 of a header block and in octal format.
85
- * The following blocks will be data blocks containing the file.
86
- */
87
- function extractFileFromTarball(tarballBuffer, filepath) {
88
- let offset = 0;
89
- while (offset < tarballBuffer.length) {
90
- const header = tarballBuffer.subarray(offset, offset + 512);
91
- offset += 512;
92
- const fileName = header.toString("utf-8", 0, 100).replace(/\0.*/g, "");
93
- const fileSize = Number.parseInt(header.toString("utf-8", 124, 136).replace(/\0.*/g, ""), 8);
94
- if (fileName === filepath) return tarballBuffer.subarray(offset, offset + fileSize);
95
- offset = offset + fileSize + 511 & -512;
96
- }
97
- throw new Error(`File ${filepath} not found in tarball`);
98
- }
99
- async function downloadBinaryFromRegistry() {
100
- const registryUrl = getRegistryUrl().replace(/\/$/, "");
101
- ensureSecureUrl(registryUrl, "registry URL");
102
- const encodedName = encodePackageNameForRegistry(PLATFORM_SPECIFIC_PACKAGE_NAME);
103
- let desiredVersion;
104
- try {
105
- const pkgJsonPath = NodePath.join(__dirname, "..", "package.json");
106
- const pkgJson = JSON.parse(NodeFS.readFileSync(pkgJsonPath, "utf8"));
107
- desiredVersion = pkgJson?.optionalDependencies?.[PLATFORM_SPECIFIC_PACKAGE_NAME] || pkgJson?.version;
108
- } catch {}
109
- const metaUrl = `${registryUrl}/${encodedName}`;
110
- const metaBuffer = await makeRequest(metaUrl);
111
- const metadata = JSON.parse(metaBuffer.toString("utf8"));
112
- const version = desiredVersion || metadata?.["dist-tags"]?.latest;
113
- const dist = (metadata?.versions?.[version])?.dist;
114
- if (!dist?.tarball) throw new Error(`Could not find tarball for ${PLATFORM_SPECIFIC_PACKAGE_NAME}@${version} from ${metaUrl}`);
115
- ensureSecureUrl(dist.tarball, "tarball URL");
116
- console.info(colors.green, "Downloading binary from:\n", dist.tarball, "\n", colors.reset);
117
- /**
118
- * Download the tarball of the right binary distribution package
119
- * Verify integrity: prefer SRI integrity (sha512/sha256/sha1),
120
- * fallback to legacy dist.shasum (sha1 hex). Fail if neither unless explicitly allowed.
121
- */
122
- const tarballDownloadBuffer = await makeRequest(dist.tarball);
123
- (() => {
124
- let verified = false;
125
- const sriMatch = (typeof dist.integrity === "string" ? dist.integrity : "").match(/^([a-z0-9]+)-([A-Za-z0-9+/=]+)$/i);
126
- if (sriMatch) {
127
- const algo = sriMatch[1].toLowerCase();
128
- const expected = sriMatch[2];
129
- if (new Set([
130
- "sha512",
131
- "sha256",
132
- "sha1"
133
- ]).has(algo)) {
134
- const actual = NodeCrypto.createHash(algo).update(tarballDownloadBuffer).digest("base64");
135
- if (expected !== actual) throw new Error(`Downloaded tarball failed integrity check (${algo} mismatch)`);
136
- verified = true;
137
- }
138
- }
139
- if (!verified && typeof dist.shasum === "string" && dist.shasum.length === 40) {
140
- const expectedSha1Hex = dist.shasum.toLowerCase();
141
- const actualSha1Hex = NodeCrypto.createHash("sha1").update(tarballDownloadBuffer).digest("hex");
142
- if (expectedSha1Hex !== actualSha1Hex) throw new Error("Downloaded tarball failed integrity check (sha1 shasum mismatch)");
143
- verified = true;
144
- }
145
- if (!verified) {
146
- if (!(process.env.ALLOW_NO_INTEGRITY === "true" || process.env.ALLOW_UNVERIFIED_TARBALL === "true")) throw new Error("No integrity metadata found for downloaded tarball. Set ALLOW_NO_INTEGRITY=true to bypass (not recommended).");
147
- console.warn(colors.yellow, "Warning: proceeding without integrity verification (explicitly allowed).", colors.reset);
148
- }
149
- })();
150
- const tarballBuffer = NodeZlib.gunzipSync(tarballDownloadBuffer);
151
- NodeFS.writeFileSync(fallbackBinaryPath, extractFileFromTarball(tarballBuffer, `package/bin/${BINARY_NAME}`), { mode: 493 });
152
- }
153
- function isPlatformSpecificPackageInstalled() {
154
- try {
155
- require.resolve(`${PLATFORM_SPECIFIC_PACKAGE_NAME}/bin/${BINARY_NAME}`);
156
- return true;
157
- } catch (_error) {
158
- return false;
159
- }
160
- }
161
- if (!PLATFORM_SPECIFIC_PACKAGE_NAME) throw new Error("Platform not supported!");
162
- if (!isPlatformSpecificPackageInstalled()) {
163
- console.log("Platform specific package not found. Will manually download binary.");
164
- downloadBinaryFromRegistry().catch((error) => {
165
- console.error(colors.red, "Failed to download binary:", error, colors.reset);
166
- process.exitCode = 1;
167
- });
168
- } else console.log("Platform specific package already installed. Skipping manual download.");
169
-
170
- //#endregion
171
- export { };