onnxruntime-node 1.22.0-dev.20250415-c18e06d5e3 → 1.22.0-rev

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 (41) hide show
  1. package/README.md +56 -51
  2. package/bin/{napi-v3 → napi-v6}/darwin/arm64/libonnxruntime.1.22.0.dylib +0 -0
  3. package/bin/napi-v6/darwin/arm64/onnxruntime_binding.node +0 -0
  4. package/bin/{napi-v3 → napi-v6}/darwin/x64/libonnxruntime.1.22.0.dylib +0 -0
  5. package/bin/napi-v6/darwin/x64/onnxruntime_binding.node +0 -0
  6. package/bin/{napi-v3 → napi-v6}/linux/arm64/libonnxruntime.so.1 +0 -0
  7. package/bin/napi-v6/linux/arm64/onnxruntime_binding.node +0 -0
  8. package/bin/{napi-v3 → napi-v6}/linux/x64/libonnxruntime.so.1 +0 -0
  9. package/bin/napi-v6/linux/x64/onnxruntime_binding.node +0 -0
  10. package/bin/{napi-v3 → napi-v6}/win32/arm64/DirectML.dll +0 -0
  11. package/bin/{napi-v3 → napi-v6}/win32/arm64/dxcompiler.dll +0 -0
  12. package/bin/{napi-v3 → napi-v6}/win32/arm64/dxil.dll +0 -0
  13. package/bin/{napi-v3 → napi-v6}/win32/arm64/onnxruntime.dll +0 -0
  14. package/bin/napi-v6/win32/arm64/onnxruntime_binding.node +0 -0
  15. package/bin/{napi-v3 → napi-v6}/win32/x64/DirectML.dll +0 -0
  16. package/bin/{napi-v3 → napi-v6}/win32/x64/dxcompiler.dll +0 -0
  17. package/bin/{napi-v3 → napi-v6}/win32/x64/dxil.dll +0 -0
  18. package/bin/{napi-v3 → napi-v6}/win32/x64/onnxruntime.dll +0 -0
  19. package/bin/napi-v6/win32/x64/onnxruntime_binding.node +0 -0
  20. package/dist/binding.js +1 -1
  21. package/dist/version.d.ts +1 -1
  22. package/dist/version.js +1 -1
  23. package/dist/version.js.map +1 -1
  24. package/lib/backend.ts +158 -158
  25. package/lib/binding.ts +91 -91
  26. package/lib/index.ts +15 -15
  27. package/lib/version.ts +7 -7
  28. package/package.json +4 -6
  29. package/script/build.ts +130 -130
  30. package/script/install-metadata-versions.js +7 -0
  31. package/script/install-metadata.js +58 -0
  32. package/script/install-utils.js +306 -0
  33. package/script/install.js +134 -198
  34. package/script/prepack.ts +20 -20
  35. package/__commit.txt +0 -1
  36. package/bin/napi-v3/darwin/arm64/onnxruntime_binding.node +0 -0
  37. package/bin/napi-v3/darwin/x64/onnxruntime_binding.node +0 -0
  38. package/bin/napi-v3/linux/arm64/onnxruntime_binding.node +0 -0
  39. package/bin/napi-v3/linux/x64/onnxruntime_binding.node +0 -0
  40. package/bin/napi-v3/win32/arm64/onnxruntime_binding.node +0 -0
  41. package/bin/napi-v3/win32/x64/onnxruntime_binding.node +0 -0
@@ -0,0 +1,306 @@
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ 'use strict';
5
+
6
+ const fs = require('fs');
7
+ const https = require('https');
8
+ const { execFileSync } = require('child_process');
9
+ const path = require('path');
10
+ const os = require('os');
11
+ const AdmZip = require('adm-zip'); // Use adm-zip instead of spawn
12
+
13
+ async function downloadFile(url, dest) {
14
+ return new Promise((resolve, reject) => {
15
+ const file = fs.createWriteStream(dest);
16
+ https
17
+ .get(url, (res) => {
18
+ if (res.statusCode !== 200) {
19
+ file.close();
20
+ fs.unlinkSync(dest);
21
+ reject(new Error(`Failed to download from ${url}. HTTP status code = ${res.statusCode}`));
22
+ return;
23
+ }
24
+
25
+ res.pipe(file);
26
+ file.on('finish', () => {
27
+ file.close();
28
+ resolve();
29
+ });
30
+ file.on('error', (err) => {
31
+ fs.unlinkSync(dest);
32
+ reject(err);
33
+ });
34
+ })
35
+ .on('error', (err) => {
36
+ fs.unlinkSync(dest);
37
+ reject(err);
38
+ });
39
+ });
40
+ }
41
+
42
+ async function downloadJson(url) {
43
+ return new Promise((resolve, reject) => {
44
+ https
45
+ .get(url, (res) => {
46
+ const { statusCode } = res;
47
+ const contentType = res.headers['content-type'];
48
+
49
+ if (!statusCode) {
50
+ reject(new Error('No response statud code from server.'));
51
+ return;
52
+ }
53
+ if (statusCode >= 400 && statusCode < 500) {
54
+ resolve(null);
55
+ return;
56
+ } else if (statusCode !== 200) {
57
+ reject(new Error(`Failed to download build list. HTTP status code = ${statusCode}`));
58
+ return;
59
+ }
60
+ if (!contentType || !/^application\/json/.test(contentType)) {
61
+ reject(new Error(`unexpected content type: ${contentType}`));
62
+ return;
63
+ }
64
+ res.setEncoding('utf8');
65
+ let rawData = '';
66
+ res.on('data', (chunk) => {
67
+ rawData += chunk;
68
+ });
69
+ res.on('end', () => {
70
+ try {
71
+ resolve(JSON.parse(rawData));
72
+ } catch (e) {
73
+ reject(e);
74
+ }
75
+ });
76
+ res.on('error', (err) => {
77
+ reject(err);
78
+ });
79
+ })
80
+ .on('error', (err) => {
81
+ reject(err);
82
+ });
83
+ });
84
+ }
85
+
86
+ async function installPackages(packages, manifests, feeds) {
87
+ // Step.1: resolve packages
88
+ const resolvedPackages = new Map();
89
+ for (const packageCandidates of packages) {
90
+ // iterate all candidates from packagesInfo and try to find the first one that exists
91
+ for (const { feed, version } of packageCandidates.versions) {
92
+ const { type, index } = feeds[feed];
93
+ const pkg = await resolvePackage(type, index, packageCandidates.name, version);
94
+ if (pkg) {
95
+ resolvedPackages.set(packageCandidates, pkg);
96
+ break;
97
+ }
98
+ }
99
+ if (!resolvedPackages.has(packageCandidates)) {
100
+ throw new Error(`Failed to resolve package. No package exists for: ${JSON.stringify(packageCandidates)}`);
101
+ }
102
+ }
103
+
104
+ // Step.2: download packages
105
+ for (const [pkgInfo, pkg] of resolvedPackages) {
106
+ const manifestsForPackage = manifests.filter((x) => x.packagesInfo === pkgInfo);
107
+ await pkg.download(manifestsForPackage);
108
+ }
109
+ }
110
+
111
+ async function resolvePackage(type, index, packageName, version) {
112
+ // https://learn.microsoft.com/en-us/nuget/api/overview
113
+ const nugetPackageUrlResolver = async (index, packageName, version) => {
114
+ // STEP.1 - get Nuget package index
115
+ const nugetIndex = await downloadJson(index);
116
+ if (!nugetIndex) {
117
+ throw new Error(`Failed to download Nuget index from ${index}`);
118
+ }
119
+
120
+ // STEP.2 - get the base url of "PackageBaseAddress/3.0.0"
121
+ const packageBaseUrl = nugetIndex.resources.find((x) => x['@type'] === 'PackageBaseAddress/3.0.0')?.['@id'];
122
+ if (!packageBaseUrl) {
123
+ throw new Error(`Failed to find PackageBaseAddress in Nuget index`);
124
+ }
125
+
126
+ // STEP.3 - get the package version info
127
+ const packageInfo = await downloadJson(`${packageBaseUrl}${packageName.toLowerCase()}/index.json`);
128
+ if (!packageInfo.versions.includes(version.toLowerCase())) {
129
+ throw new Error(`Failed to find specific package versions for ${packageName} in ${index}`);
130
+ }
131
+
132
+ // STEP.4 - generate the package URL
133
+ const packageUrl = `${packageBaseUrl}${packageName.toLowerCase()}/${version.toLowerCase()}/${packageName.toLowerCase()}.${version.toLowerCase()}.nupkg`;
134
+ const packageFileName = `${packageName.toLowerCase()}.${version.toLowerCase()}.nupkg`;
135
+
136
+ return {
137
+ download: async (manifests) => {
138
+ if (manifests.length === 0) {
139
+ return;
140
+ }
141
+
142
+ // Create a temporary directory
143
+ const tempDir = path.join(os.tmpdir(), `onnxruntime-node-pkgs_${Date.now()}`);
144
+ fs.mkdirSync(tempDir, { recursive: true });
145
+
146
+ try {
147
+ const packageFilePath = path.join(tempDir, packageFileName);
148
+
149
+ // Download the NuGet package
150
+ console.log(`Downloading ${packageUrl}`);
151
+ await downloadFile(packageUrl, packageFilePath);
152
+
153
+ // Load the NuGet package (which is a ZIP file)
154
+ let zip;
155
+ try {
156
+ zip = new AdmZip(packageFilePath);
157
+ } catch (err) {
158
+ throw new Error(`Failed to open NuGet package: ${err.message}`);
159
+ }
160
+
161
+ // Extract only the needed files from the package
162
+ const extractDir = path.join(tempDir, 'extracted');
163
+ fs.mkdirSync(extractDir, { recursive: true });
164
+
165
+ // Process each manifest and extract/copy files to their destinations
166
+ for (const manifest of manifests) {
167
+ const { filepath, pathInPackage } = manifest;
168
+
169
+ // Create directory for the target file
170
+ const targetDir = path.dirname(filepath);
171
+ fs.mkdirSync(targetDir, { recursive: true });
172
+
173
+ // Check if the file exists directly in the zip
174
+ const zipEntry = zip.getEntry(pathInPackage);
175
+ if (!zipEntry) {
176
+ throw new Error(`Failed to find ${pathInPackage} in NuGet package`);
177
+ }
178
+
179
+ console.log(`Extracting ${pathInPackage} to ${filepath}`);
180
+
181
+ // Extract just this entry to a temporary location
182
+ const extractedFilePath = path.join(extractDir, path.basename(pathInPackage));
183
+ zip.extractEntryTo(zipEntry, extractDir, false, true);
184
+
185
+ // Copy to the final destination
186
+ fs.copyFileSync(extractedFilePath, filepath);
187
+ }
188
+ } finally {
189
+ // Clean up the temporary directory - always runs even if an error occurs
190
+ try {
191
+ fs.rmSync(tempDir, { recursive: true });
192
+ } catch (e) {
193
+ console.warn(`Failed to clean up temporary directory: ${tempDir}`, e);
194
+ // Don't rethrow this error as it would mask the original error
195
+ }
196
+ }
197
+ },
198
+ };
199
+ };
200
+
201
+ switch (type) {
202
+ case 'nuget':
203
+ return await nugetPackageUrlResolver(index, packageName, version);
204
+ default:
205
+ throw new Error(`Unsupported package type: ${type}`);
206
+ }
207
+ }
208
+
209
+ function tryGetCudaVersion() {
210
+ // Should only return 11 or 12.
211
+
212
+ // try to get the CUDA version from the system ( `nvcc --version` )
213
+ let ver = 12;
214
+ try {
215
+ const nvccVersion = execFileSync('nvcc', ['--version'], { encoding: 'utf8' });
216
+ const match = nvccVersion.match(/release (\d+)/);
217
+ if (match) {
218
+ ver = parseInt(match[1]);
219
+ if (ver !== 11 && ver !== 12) {
220
+ throw new Error(`Unsupported CUDA version: ${ver}`);
221
+ }
222
+ }
223
+ } catch (e) {
224
+ if (e?.code === 'ENOENT') {
225
+ console.warn('`nvcc` not found. Assuming CUDA 12.');
226
+ } else {
227
+ console.warn('Failed to detect CUDA version from `nvcc --version`:', e.message);
228
+ }
229
+ }
230
+
231
+ // assume CUDA 12 if failed to detect
232
+ return ver;
233
+ }
234
+
235
+ function parseInstallFlag() {
236
+ let flag = process.env.ONNXRUNTIME_NODE_INSTALL || process.env.npm_config_onnxruntime_node_install;
237
+ if (!flag) {
238
+ for (let i = 0; i < process.argv.length; i++) {
239
+ if (process.argv[i].startsWith('--onnxruntime-node-install=')) {
240
+ flag = process.argv[i].split('=')[1];
241
+ break;
242
+ } else if (process.argv[i] === '--onnxruntime-node-install') {
243
+ flag = 'true';
244
+ }
245
+ }
246
+ }
247
+ switch (flag) {
248
+ case 'true':
249
+ case '1':
250
+ case 'ON':
251
+ return true;
252
+ case 'skip':
253
+ return false;
254
+ case undefined: {
255
+ flag = parseInstallCudaFlag();
256
+ if (flag === 'skip') {
257
+ return false;
258
+ }
259
+ if (flag === 11) {
260
+ throw new Error('CUDA 11 is no longer supported. Please consider using CPU or upgrade to CUDA 12.');
261
+ }
262
+ if (flag === 12) {
263
+ return 'cuda12';
264
+ }
265
+ return undefined;
266
+ }
267
+ default:
268
+ if (!flag || typeof flag !== 'string') {
269
+ throw new Error(`Invalid value for --onnxruntime-node-install: ${flag}`);
270
+ }
271
+ }
272
+ }
273
+
274
+ function parseInstallCudaFlag() {
275
+ let flag = process.env.ONNXRUNTIME_NODE_INSTALL_CUDA || process.env.npm_config_onnxruntime_node_install_cuda;
276
+ if (!flag) {
277
+ for (let i = 0; i < process.argv.length; i++) {
278
+ if (process.argv[i].startsWith('--onnxruntime-node-install-cuda=')) {
279
+ flag = process.argv[i].split('=')[1];
280
+ break;
281
+ } else if (process.argv[i] === '--onnxruntime-node-install-cuda') {
282
+ flag = 'true';
283
+ }
284
+ }
285
+ }
286
+ switch (flag) {
287
+ case 'true':
288
+ case '1':
289
+ case 'ON':
290
+ return tryGetCudaVersion();
291
+ case 'v11':
292
+ return 11;
293
+ case 'v12':
294
+ return 12;
295
+ case 'skip':
296
+ case undefined:
297
+ return flag;
298
+ default:
299
+ throw new Error(`Invalid value for --onnxruntime-node-install-cuda: ${flag}`);
300
+ }
301
+ }
302
+
303
+ module.exports = {
304
+ installPackages,
305
+ parseInstallFlag,
306
+ };
package/script/install.js CHANGED
@@ -1,198 +1,134 @@
1
- // Copyright (c) Microsoft Corporation. All rights reserved.
2
- // Licensed under the MIT License.
3
-
4
- 'use strict';
5
-
6
- // This script is written in JavaScript. This is because it is used in "install" script in package.json, which is called
7
- // when the package is installed either as a dependency or from "npm ci"/"npm install" without parameters. TypeScript is
8
- // not always available.
9
-
10
- // The purpose of this script is to download the required binaries for the platform and architecture.
11
- // Currently, most of the binaries are already bundled in the package, except for the following:
12
- // - Linux/x64/CUDA 12
13
- //
14
- // The CUDA binaries are not bundled because they are too large to be allowed in the npm registry. Instead, they are
15
- // downloaded from the GitHub release page of ONNX Runtime. The script will download the binaries if they are not
16
- // already present in the package.
17
-
18
- // Step.1: Check if we should exit early
19
- const os = require('os');
20
- const fs = require('fs');
21
- const https = require('https');
22
- const path = require('path');
23
- const tar = require('tar');
24
- const { execFileSync } = require('child_process');
25
- const { bootstrap: globalAgentBootstrap } = require('global-agent');
26
-
27
- // Bootstrap global-agent to honor the proxy settings in
28
- // environment variables, e.g. GLOBAL_AGENT_HTTPS_PROXY.
29
- // See https://github.com/gajus/global-agent/blob/v3.0.0/README.md#environment-variables for details.
30
- globalAgentBootstrap();
31
-
32
- // commandline flag:
33
- // --onnxruntime-node-install-cuda Force install the CUDA EP binaries. Try to detect the CUDA version.
34
- // --onnxruntime-node-install-cuda=v11 Force install the CUDA EP binaries for CUDA 11.
35
- // --onnxruntime-node-install-cuda=v12 Force install the CUDA EP binaries for CUDA 12.
36
- // --onnxruntime-node-install-cuda=skip Skip the installation of the CUDA EP binaries.
37
- //
38
- // Alternatively, use environment variable "ONNXRUNTIME_NODE_INSTALL_CUDA"
39
- //
40
- // If the flag is not provided, the script will only install the CUDA EP binaries when:
41
- // - The platform is Linux/x64.
42
- // - The binaries are not already present in the package.
43
- // - The installation is not a local install (when used inside ONNX Runtime repo).
44
- //
45
- const INSTALL_CUDA_FLAG = parseInstallCudaFlag();
46
- const NO_INSTALL = INSTALL_CUDA_FLAG === 'skip';
47
- const FORCE_INSTALL = !NO_INSTALL && INSTALL_CUDA_FLAG;
48
-
49
- const IS_LINUX_X64 = os.platform() === 'linux' && os.arch() === 'x64';
50
- const BIN_FOLDER = path.join(__dirname, '..', 'bin/napi-v3/linux/x64');
51
- const BIN_FOLDER_EXISTS = fs.existsSync(BIN_FOLDER);
52
- const CUDA_DLL_EXISTS = fs.existsSync(path.join(BIN_FOLDER, 'libonnxruntime_providers_cuda.so'));
53
- const ORT_VERSION = require('../package.json').version;
54
-
55
- const npm_config_local_prefix = process.env.npm_config_local_prefix;
56
- const npm_package_json = process.env.npm_package_json;
57
- const SKIP_LOCAL_INSTALL =
58
- npm_config_local_prefix && npm_package_json && path.dirname(npm_package_json) === npm_config_local_prefix;
59
-
60
- const shouldInstall = FORCE_INSTALL || (!SKIP_LOCAL_INSTALL && IS_LINUX_X64 && BIN_FOLDER_EXISTS && !CUDA_DLL_EXISTS);
61
- if (NO_INSTALL || !shouldInstall) {
62
- process.exit(0);
63
- }
64
-
65
- // Step.2: Download the required binaries
66
- const artifactUrl = {
67
- get 11() {
68
- // TODO: support ORT Cuda v11 binaries
69
- throw new Error(`CUDA 11 binaries are not supported by this script yet.
70
-
71
- To use ONNX Runtime Node.js binding with CUDA v11 support, please follow the manual steps:
72
-
73
- 1. Use "--onnxruntime-node-install-cuda=skip" to skip the auto installation.
74
- 2. Navigate to https://aiinfra.visualstudio.com/PublicPackages/_artifacts/feed/onnxruntime-cuda-11
75
- 3. Download the binaries for your platform and architecture
76
- 4. Extract the following binaries to "node_modules/onnxruntime-node/bin/napi-v3/linux/x64:
77
- - libonnxruntime_providers_tensorrt.so
78
- - libonnxruntime_providers_shared.so
79
- - libonnxruntime.so.${ORT_VERSION}
80
- - libonnxruntime_providers_cuda.so
81
- `);
82
- },
83
- 12: `https://github.com/microsoft/onnxruntime/releases/download/v${ORT_VERSION}/onnxruntime-linux-x64-gpu-${
84
- ORT_VERSION
85
- }.tgz`,
86
- }[INSTALL_CUDA_FLAG || tryGetCudaVersion()];
87
- console.log(`Downloading "${artifactUrl}"...`);
88
-
89
- const FILES = new Set([
90
- 'libonnxruntime_providers_tensorrt.so',
91
- 'libonnxruntime_providers_shared.so',
92
- `libonnxruntime.so.${ORT_VERSION}`,
93
- 'libonnxruntime_providers_cuda.so',
94
- ]);
95
-
96
- downloadAndExtract(artifactUrl, BIN_FOLDER, FILES);
97
-
98
- async function downloadAndExtract(url, dest, files) {
99
- return new Promise((resolve, reject) => {
100
- https.get(url, (res) => {
101
- const { statusCode } = res;
102
- const contentType = res.headers['content-type'];
103
-
104
- if (statusCode === 301 || statusCode === 302) {
105
- downloadAndExtract(res.headers.location, dest, files).then(
106
- (value) => resolve(value),
107
- (reason) => reject(reason),
108
- );
109
- return;
110
- } else if (statusCode !== 200) {
111
- throw new Error(`Failed to download the binaries: ${res.statusCode} ${res.statusMessage}.
112
-
113
- Use "--onnxruntime-node-install-cuda=skip" to skip the installation. You will still be able to use ONNX Runtime, but the CUDA EP will not be available.`);
114
- }
115
-
116
- if (!contentType || !/^application\/octet-stream/.test(contentType)) {
117
- throw new Error(`unexpected content type: ${contentType}`);
118
- }
119
-
120
- res
121
- .pipe(
122
- tar.t({
123
- strict: true,
124
- onentry: (entry) => {
125
- const filename = path.basename(entry.path);
126
- if (entry.type === 'File' && files.has(filename)) {
127
- console.log(`Extracting "${filename}" to "${dest}"...`);
128
- entry.pipe(fs.createWriteStream(path.join(dest, filename)));
129
- entry.on('finish', () => {
130
- console.log(`Finished extracting "${filename}".`);
131
- });
132
- }
133
- },
134
- }),
135
- )
136
- .on('error', (err) => {
137
- throw new Error(`Failed to extract the binaries: ${err.message}.
138
-
139
- Use "--onnxruntime-node-install-cuda=skip" to skip the installation. You will still be able to use ONNX Runtime, but the CUDA EP will not be available.`);
140
- });
141
- });
142
- });
143
- }
144
-
145
- function tryGetCudaVersion() {
146
- // Should only return 11 or 12.
147
-
148
- // try to get the CUDA version from the system ( `nvcc --version` )
149
- let ver = 12;
150
- try {
151
- const nvccVersion = execFileSync('nvcc', ['--version'], { encoding: 'utf8' });
152
- const match = nvccVersion.match(/release (\d+)/);
153
- if (match) {
154
- ver = parseInt(match[1]);
155
- if (ver !== 11 && ver !== 12) {
156
- throw new Error(`Unsupported CUDA version: ${ver}`);
157
- }
158
- }
159
- } catch (e) {
160
- if (e?.code === 'ENOENT') {
161
- console.warn('`nvcc` not found. Assuming CUDA 12.');
162
- } else {
163
- console.warn('Failed to detect CUDA version from `nvcc --version`:', e.message);
164
- }
165
- }
166
-
167
- // assume CUDA 12 if failed to detect
168
- return ver;
169
- }
170
-
171
- function parseInstallCudaFlag() {
172
- let flag = process.env.ONNXRUNTIME_NODE_INSTALL_CUDA || process.env.npm_config_onnxruntime_node_install_cuda;
173
- if (!flag) {
174
- for (let i = 0; i < process.argv.length; i++) {
175
- if (process.argv[i].startsWith('--onnxruntime-node-install-cuda=')) {
176
- flag = process.argv[i].split('=')[1];
177
- break;
178
- } else if (process.argv[i] === '--onnxruntime-node-install-cuda') {
179
- flag = 'true';
180
- }
181
- }
182
- }
183
- switch (flag) {
184
- case 'true':
185
- case '1':
186
- case 'ON':
187
- return tryGetCudaVersion();
188
- case 'v11':
189
- return 11;
190
- case 'v12':
191
- return 12;
192
- case 'skip':
193
- case undefined:
194
- return flag;
195
- default:
196
- throw new Error(`Invalid value for --onnxruntime-node-install-cuda: ${flag}`);
197
- }
198
- }
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ 'use strict';
5
+
6
+ // This script is written in JavaScript. This is because it is used in "install" script in package.json, which is called
7
+ // when the package is installed either as a dependency or from "npm ci"/"npm install" without parameters. TypeScript is
8
+ // not always available.
9
+
10
+ // The purpose of this script is to download the required binaries for the platform and architecture.
11
+ // Currently, most of the binaries are already bundled in the package, except for the files that described in the file
12
+ // install-metadata.js.
13
+ //
14
+ // Some files (eg. the CUDA EP binaries) are not bundled because they are too large to be allowed in the npm registry.
15
+ // Instead, they are downloaded from the Nuget feed. The script will download the binaries if they are not already
16
+ // present in the NPM package.
17
+
18
+ // Step.1: Check if we should exit early
19
+ const os = require('os');
20
+ const path = require('path');
21
+ const { bootstrap: globalAgentBootstrap } = require('global-agent');
22
+ const { installPackages, parseInstallFlag } = require('./install-utils.js');
23
+
24
+ const INSTALL_METADATA = require('./install-metadata.js');
25
+
26
+ // Bootstrap global-agent to honor the proxy settings in
27
+ // environment variables, e.g. GLOBAL_AGENT_HTTPS_PROXY.
28
+ // See https://github.com/gajus/global-agent/blob/v3.0.0/README.md#environment-variables for details.
29
+ globalAgentBootstrap();
30
+
31
+ // commandline flag:
32
+ //
33
+ // --onnxruntime-node-install Force install the files that are not bundled in the package.
34
+ //
35
+ // --onnxruntime-node-install=skip Skip the installation of the files that are not bundled in the package.
36
+ //
37
+ // --onnxruntime-node-install=cuda12 Force install the CUDA EP binaries for CUDA 12.
38
+ //
39
+ // --onnxruntime-node-install-cuda Force install the CUDA EP binaries.
40
+ // (deprecated, use --onnxruntime-node-install=cuda12)
41
+ //
42
+ // --onnxruntime-node-install-cuda=skip Skip the installation of the CUDA EP binaries.
43
+ // (deprecated, use --onnxruntime-node-install=skip)
44
+ //
45
+ //
46
+ // Alternatively, use environment variable "ONNXRUNTIME_NODE_INSTALL" or "ONNXRUNTIME_NODE_INSTALL_CUDA" (deprecated).
47
+ //
48
+ // If the flag is not provided, the script will look up the metadata file to determine the manifest.
49
+ //
50
+
51
+ /**
52
+ * Possible values:
53
+ * - undefined: the default behavior. This is the value when no installation flag is specified.
54
+ *
55
+ * - false: skip installation. This is the value when the installation flag is set to "skip":
56
+ * --onnxruntime-node-install=skip
57
+ *
58
+ * - true: force installation. This is the value when the installation flag is set with no value:
59
+ * --onnxruntime-node-install
60
+ *
61
+ * - string: the installation flag is set to a specific value:
62
+ * --onnxruntime-node-install=cuda12
63
+ */
64
+ const INSTALL_FLAG = parseInstallFlag();
65
+
66
+ // if installation is skipped, exit early
67
+ if (INSTALL_FLAG === false) {
68
+ process.exit(0);
69
+ }
70
+ // if installation is not specified, exit early when the installation is local (e.g. `npm ci` in <ORT_ROOT>/js/node/)
71
+ if (INSTALL_FLAG === undefined) {
72
+ const npm_config_local_prefix = process.env.npm_config_local_prefix;
73
+ const npm_package_json = process.env.npm_package_json;
74
+ const IS_LOCAL_INSTALL =
75
+ npm_config_local_prefix && npm_package_json && path.dirname(npm_package_json) === npm_config_local_prefix;
76
+ if (IS_LOCAL_INSTALL) {
77
+ process.exit(0);
78
+ }
79
+ }
80
+
81
+ const PLATFORM = `${os.platform()}/${os.arch()}`;
82
+ let INSTALL_MANIFEST_NAMES = INSTALL_METADATA.requirements[PLATFORM] ?? [];
83
+
84
+ // if installation is specified explicitly, validate the manifest
85
+ if (typeof INSTALL_FLAG === 'string') {
86
+ const installations = INSTALL_FLAG.split(',').map((x) => x.trim());
87
+ for (const installation of installations) {
88
+ if (INSTALL_MANIFEST_NAMES.indexOf(installation) === -1) {
89
+ throw new Error(`Invalid installation: ${installation} for platform: ${PLATFORM}`);
90
+ }
91
+ }
92
+ INSTALL_MANIFEST_NAMES = installations;
93
+ }
94
+
95
+ const BIN_FOLDER = path.join(__dirname, '..', 'bin/napi-v6', PLATFORM);
96
+ const INSTALL_MANIFESTS = [];
97
+
98
+ const PACKAGES = new Set();
99
+ for (const name of INSTALL_MANIFEST_NAMES) {
100
+ const manifest = INSTALL_METADATA.manifests[`${PLATFORM}:${name}`];
101
+ if (!manifest) {
102
+ throw new Error(`Manifest not found: ${name} for platform: ${PLATFORM}`);
103
+ }
104
+
105
+ for (const [filename, { package: pkg, path: pathInPackage }] of Object.entries(manifest)) {
106
+ const packageCandidates = INSTALL_METADATA.packages[pkg];
107
+ if (!packageCandidates) {
108
+ throw new Error(`Package information not found: ${pkg}`);
109
+ }
110
+ PACKAGES.add(packageCandidates);
111
+
112
+ INSTALL_MANIFESTS.push({
113
+ filepath: path.normalize(path.join(BIN_FOLDER, filename)),
114
+ packagesInfo: packageCandidates,
115
+ pathInPackage,
116
+ });
117
+ }
118
+ }
119
+
120
+ // If the installation flag is not specified, we do a check to see if the files are already installed.
121
+ if (INSTALL_FLAG === undefined) {
122
+ let hasMissingFiles = false;
123
+ for (const { filepath } of INSTALL_MANIFESTS) {
124
+ if (!require('fs').existsSync(filepath)) {
125
+ hasMissingFiles = true;
126
+ break;
127
+ }
128
+ }
129
+ if (!hasMissingFiles) {
130
+ process.exit(0);
131
+ }
132
+ }
133
+
134
+ void installPackages(PACKAGES, INSTALL_MANIFESTS, INSTALL_METADATA.feeds);