@delta-infra/cli 1.0.83 → 1.0.84

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 (30) hide show
  1. package/README.md +429 -429
  2. package/checksums.txt +5 -5
  3. package/package.json +1 -1
  4. package/scripts/install-wizard.js +625 -625
  5. package/scripts/install.js +417 -417
  6. package/scripts/run.js +65 -65
  7. package/skills/delta-sandbox/SKILL.md +356 -356
  8. package/skills/delta-sandbox/agents/openai.yaml +4 -4
  9. package/skills/delta-sandbox/references/commands.md +56 -56
  10. package/skills/delta-sandbox/references/lifecycle.md +92 -92
  11. package/skills/delta-sandbox/references/recipes.md +133 -133
  12. package/skills/delta-science/SKILL.md +140 -136
  13. package/skills/delta-science/agents/openai.yaml +4 -4
  14. package/skills/delta-science/references/antbo.md +100 -100
  15. package/skills/delta-science/references/cli-contract.md +53 -53
  16. package/skills/delta-science/references/delta-bo.md +89 -89
  17. package/skills/delta-science/references/gsasii.md +116 -116
  18. package/skills/delta-science/references/lammps.md +66 -66
  19. package/skills/delta-science/references/ldm-bo.md +129 -129
  20. package/skills/delta-science/references/ldm.md +73 -73
  21. package/skills/delta-science/references/pubchem.md +126 -126
  22. package/skills/delta-science/references/pymatgen.md +68 -68
  23. package/skills/delta-science/references/rdkit.md +138 -138
  24. package/skills/delta-science/references/routing-index.md +36 -36
  25. package/skills/delta-science/references/strbo.md +87 -87
  26. package/skills/delta-science/references/synbo.md +198 -198
  27. package/skills/delta-science/references/workflows.md +61 -61
  28. package/skills/delta-shared/SKILL.md +95 -95
  29. package/skills/delta-shared/agents/openai.yaml +4 -4
  30. package/skills/manifest.json +19 -19
@@ -1,417 +1,417 @@
1
- // Copyright (c) 2026 Delta Infra Authors
2
- // SPDX-License-Identifier: MIT
3
-
4
- const fs = require("fs");
5
- const path = require("path");
6
- const { execFileSync } = require("child_process");
7
- const os = require("os");
8
- const crypto = require("crypto");
9
-
10
- const PKG = "@delta-infra/cli";
11
-
12
- // Resolve the version to download:
13
- // env var > npm registry > local package.json (fallback)
14
- function resolveVersion() {
15
- if (process.env.DELTA_CLI_VERSION) return process.env.DELTA_CLI_VERSION.replace(/^v/, "");
16
- try {
17
- const out = require("child_process").execFileSync("npm", ["view", PKG, "version"], {
18
- stdio: ["ignore", "pipe", "pipe"],
19
- timeout: 15000,
20
- encoding: "utf8",
21
- });
22
- const ver = out.trim();
23
- if (/^\d+\.\d+\.\d+/.test(ver)) return ver;
24
- } catch {}
25
- return require("../package.json").version.replace(/-.*$/, "");
26
- }
27
-
28
- const VERSION = resolveVersion();
29
- const NAME = "delta-cli";
30
- const REPO = "yzailab/delta-infra-cli";
31
- const DEFAULT_ALLOWED_HOSTS = new Set([
32
- "github.com",
33
- "gh-proxy.com",
34
- "ghproxy.net",
35
- "gh.ddlc.top",
36
- "objects.githubusercontent.com",
37
- "release-assets.githubusercontent.com",
38
- "github-releases.githubusercontent.com",
39
- "raw.githubusercontent.com",
40
- "registry.npmmirror.com",
41
- ]);
42
- const DEFAULT_ALLOWED_HOST_PREFIXES = [
43
- "github-production-release-asset-",
44
- ];
45
-
46
- const PLATFORM_MAP = {
47
- darwin: "darwin",
48
- linux: "linux",
49
- win32: "windows",
50
- };
51
-
52
- const ARCH_MAP = {
53
- x64: "amd64",
54
- arm64: "arm64",
55
- };
56
-
57
- const platform = PLATFORM_MAP[process.platform];
58
- const arch = ARCH_MAP[process.arch];
59
-
60
- const isWindows = process.platform === "win32";
61
- const ext = isWindows ? ".zip" : ".tar.gz";
62
- const archiveName = `${NAME}-${platform}-${arch}${ext}`;
63
- const GITHUB_URL = `https://github.com/${REPO}/releases/download/v${VERSION}/${archiveName}`;
64
-
65
- const binDir = path.join(__dirname, "..", "bin");
66
- const dest = path.join(binDir, NAME + (isWindows ? ".exe" : ""));
67
-
68
- // ── Mirror URL resolution ──────────────────────────────────────────────────
69
-
70
- var _curlTimeoutMs = null;
71
-
72
- function _getCurlTimeout() {
73
- if (_curlTimeoutMs !== null) return _curlTimeoutMs;
74
- var env = process.env.DELTA_CLI_DOWNLOAD_TIMEOUT;
75
- var t = env ? parseInt(env, 10) : 0;
76
- _curlTimeoutMs = t > 0 ? t : 60000;
77
- return _curlTimeoutMs;
78
- }
79
-
80
- // GitHub release download mirrors.
81
- // Format: [hostname, urlPrefix] — urlPrefix is prepended to the GitHub URL.
82
- var _MIRROR_LIST = [
83
- ["gh.ddlc.top", "https://gh.ddlc.top"],
84
- ["ghproxy.net", "https://ghproxy.net"],
85
- ["gh-proxy.com", "https://gh-proxy.com"],
86
- ];
87
-
88
- // Quick connectivity check: fetch a small file (checksums.txt) from each
89
- // mirror and return only the ones that respond within the probe timeout.
90
- function probeMirrors(version, cb) {
91
- console.error("Probing " + _MIRROR_LIST.length + " download mirrors...");
92
- var probeUrl = "/https://github.com/" + REPO + "/releases/download/v" + version + "/checksums.txt";
93
- var results = [];
94
- var pending = _MIRROR_LIST.length;
95
- var done = false;
96
-
97
- function finish() {
98
- if (done) return;
99
- done = true;
100
- if (results.length > 0) {
101
- console.error("Found " + results.length + " available mirror(s)");
102
- } else {
103
- console.error("No mirror responded, falling back to GitHub source");
104
- }
105
- cb(results);
106
- }
107
-
108
- if (pending === 0) return finish();
109
-
110
- for (var i = 0; i < _MIRROR_LIST.length; i++) {
111
- (function(idx) {
112
- var entry = _MIRROR_LIST[idx];
113
- var host = entry[0];
114
- var prefix = entry[1];
115
- var testUrl = prefix + probeUrl;
116
- var args = [
117
- "--fail", "--location", "--silent", "--show-error",
118
- "--connect-timeout", "3", "--max-time", "5",
119
- "--output", "/dev/null", testUrl,
120
- ];
121
- var child;
122
- try {
123
- child = require("child_process").spawn("curl", args, { stdio: ["ignore", "pipe", "pipe"], timeout: 5000 });
124
- var stdout = "";
125
- var stderr = "";
126
- child.stdout.on("data", function(d) { stdout += d; });
127
- child.stderr.on("data", function(d) { stderr += d; });
128
- child.on("close", function(code) {
129
- if (code === 0) {
130
- results.push(prefix + "/https://github.com/" + REPO + "/releases/download/v" + version + "/" + archiveName);
131
- }
132
- pending--;
133
- if (pending === 0) finish();
134
- });
135
- child.on("error", function() {
136
- pending--;
137
- if (pending === 0) finish();
138
- });
139
- } catch (e) {
140
- pending--;
141
- if (pending === 0) finish();
142
- }
143
- })(i);
144
- }
145
- // Safety timeout: if probes hang, continue without mirrors after 10s
146
- setTimeout(finish, 5000);
147
- }
148
-
149
- function releaseAssetUrls(version, assetName, cb) {
150
- var urls = [];
151
- var mirror = process.env.DELTA_CLI_MIRROR || "";
152
- if (mirror) {
153
- urls.push("" + mirror.replace(/\/$/, "") + "/yzailab/delta-infra-cli/releases/download/v" + version + "/" + assetName);
154
- }
155
- // Probe mirrors in parallel first, then fallback
156
- probeMirrors(version, function(mirrorUrls) {
157
- for (var i = 0; i < mirrorUrls.length; i++) {
158
- urls.push(mirrorUrls[i]);
159
- }
160
- // GitHub source (last resort)
161
- urls.push(GITHUB_URL);
162
- cb(urls);
163
- });
164
- }
165
-
166
- function assertAllowedHost(url) {
167
- const { hostname } = new URL(url);
168
- const allowlist = new Set(DEFAULT_ALLOWED_HOSTS);
169
- (process.env.DELTA_CLI_MIRROR_ALLOWLIST || "")
170
- .split(",")
171
- .map((h) => h.trim().toLowerCase())
172
- .filter(Boolean)
173
- .forEach((h) => allowlist.add(h));
174
- for (const allowed of allowlist) {
175
- if (hostname === allowed || hostname.endsWith("." + allowed)) return;
176
- }
177
- for (const prefix of DEFAULT_ALLOWED_HOST_PREFIXES) {
178
- if (hostname.startsWith(prefix)) return;
179
- }
180
- throw new Error(`Download host not allowed: ${hostname}`);
181
- }
182
-
183
- // ── curl version detection (for --ssl-revoke-best-effort) ──────────────────
184
-
185
- function isCurlVersionSupported(versionOutput) {
186
- const match = String(versionOutput).match(/^\s*curl\s+(\d+)\.(\d+)\.(\d+)/i);
187
- if (!match) return false;
188
- const major = parseInt(match[1], 10);
189
- const minor = parseInt(match[2], 10);
190
- return major > 7 || (major === 7 && minor >= 70);
191
- }
192
-
193
- let _curlSupportsSslRevokeBestEffort;
194
-
195
- function curlSupportsSslRevokeBestEffort() {
196
- if (_curlSupportsSslRevokeBestEffort !== undefined) {
197
- return _curlSupportsSslRevokeBestEffort;
198
- }
199
- try {
200
- const output = execFileSync("curl", ["--version"], {
201
- stdio: ["ignore", "pipe", "ignore"],
202
- encoding: "utf8",
203
- timeout: 5000,
204
- });
205
- _curlSupportsSslRevokeBestEffort = isCurlVersionSupported(output);
206
- } catch {
207
- _curlSupportsSslRevokeBestEffort = false;
208
- }
209
- return _curlSupportsSslRevokeBestEffort;
210
- }
211
-
212
- // ── Download ───────────────────────────────────────────────────────────────
213
-
214
- function download(url, destPath) {
215
- assertAllowedHost(url);
216
- const args = [
217
- "--fail", "--location", "--silent", "--show-error",
218
- "--connect-timeout", "10",
219
- "--max-time", "45",
220
- "--speed-limit", "50000", "--speed-time", "10",
221
- "--max-redirs", "3",
222
- "--output", destPath,
223
- ];
224
- if (isWindows && curlSupportsSslRevokeBestEffort()) {
225
- args.unshift("--ssl-revoke-best-effort");
226
- }
227
- args.push(url);
228
- execFileSync("curl", args, { stdio: ["ignore", "ignore", "pipe"] });
229
- }
230
-
231
- // ── Extraction ─────────────────────────────────────────────────────────────
232
-
233
- function extractZipWindows(archivePath, destDir) {
234
- const psOpts = ["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command"];
235
- const psEnv = {
236
- DELTA_CLI_ARCHIVE: archivePath,
237
- DELTA_CLI_DEST: destDir,
238
- };
239
- try {
240
- const dotnet =
241
- "$ErrorActionPreference='Stop';" +
242
- "Add-Type -AssemblyName System.IO.Compression.FileSystem;" +
243
- "[System.IO.Compression.ZipFile]::ExtractToDirectory($env:DELTA_CLI_ARCHIVE,$env:DELTA_CLI_DEST)";
244
- execFileSync("powershell.exe", [...psOpts, dotnet], { stdio: ["ignore", "inherit", "inherit"], env: psEnv });
245
- } catch (primaryErr) {
246
- try {
247
- const cmdlet =
248
- "$ErrorActionPreference='Stop';" +
249
- "Expand-Archive -LiteralPath $env:DELTA_CLI_ARCHIVE -DestinationPath $env:DELTA_CLI_DEST -Force";
250
- execFileSync("powershell.exe", [...psOpts, cmdlet], { stdio: ["ignore", "inherit", "inherit"], env: psEnv });
251
- } catch (secondErr) {
252
- try {
253
- execFileSync("tar", ["-xf", archivePath, "-C", destDir], { stdio: "ignore" });
254
- } catch (fallbackErr) {
255
- throw new Error(
256
- `Failed to extract ${archivePath}. ` +
257
- `.NET ZipFile: ${primaryErr.message}. ` +
258
- `Expand-Archive: ${secondErr.message}. ` +
259
- `tar: ${fallbackErr.message}`
260
- );
261
- }
262
- }
263
- }
264
- }
265
-
266
- // ── Checksum ───────────────────────────────────────────────────────────────
267
-
268
- function getExpectedChecksum(archiveName, checksumsDir) {
269
- const dir = checksumsDir || path.join(__dirname, "..");
270
- const checksumsPath = path.join(dir, "checksums.txt");
271
- if (!fs.existsSync(checksumsPath)) {
272
- console.error("[WARN] checksums.txt not found, skipping checksum verification");
273
- return null;
274
- }
275
- const content = fs.readFileSync(checksumsPath, "utf8");
276
- for (const line of content.split("\n")) {
277
- const trimmed = line.trim();
278
- if (!trimmed) continue;
279
- const match = trimmed.match(/^([a-fA-F0-9]{64})\s+\*?(.+)$/);
280
- if (!match) continue;
281
- const hash = match[1];
282
- const name = match[2];
283
- if (name === archiveName) return hash;
284
- }
285
- throw new Error(`Checksum entry not found for ${archiveName}`);
286
- }
287
-
288
- function verifyChecksum(archivePath, expectedHash) {
289
- if (expectedHash === null) return;
290
- const hash = crypto.createHash("sha256");
291
- const fd = fs.openSync(archivePath, "r");
292
- try {
293
- const buf = Buffer.alloc(64 * 1024);
294
- let bytesRead;
295
- while ((bytesRead = fs.readSync(fd, buf, 0, buf.length, null)) > 0) {
296
- hash.update(buf.subarray(0, bytesRead));
297
- }
298
- } finally {
299
- fs.closeSync(fd);
300
- }
301
- const actual = hash.digest("hex");
302
- if (actual.toLowerCase() !== expectedHash.toLowerCase()) {
303
- throw new Error(
304
- `[SECURITY] Checksum mismatch for ${path.basename(archivePath)}: expected ${expectedHash} but got ${actual}`
305
- );
306
- }
307
- }
308
-
309
- // ── Main install ───────────────────────────────────────────────────────────
310
-
311
- function install() {
312
- fs.mkdirSync(binDir, { recursive: true });
313
- var tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "delta-cli-"));
314
- var archivePath = path.join(tmpDir, archiveName);
315
-
316
- releaseAssetUrls(VERSION, archiveName, function(downloadUrls) {
317
- try {
318
- var lastErr;
319
- var downloaded = false;
320
- for (var i = 0; i < downloadUrls.length; i++) {
321
- try {
322
- console.error("Downloading from " + downloadUrls[i]);
323
- download(downloadUrls[i], archivePath);
324
- console.error("Download complete, verifying checksum...");
325
- const expectedHash = getExpectedChecksum(archiveName);
326
- verifyChecksum(archivePath, expectedHash);
327
- console.error("Checksum verified");
328
- downloaded = true;
329
- break;
330
- } catch (e) {
331
- console.error("Failed: " + e.message + " (" + downloadUrls[i] + ")");
332
- lastErr = e;
333
- }
334
- }
335
- if (!downloaded) throw lastErr;
336
-
337
- if (isWindows) {
338
- console.error("Extracting archive...");
339
- extractZipWindows(archivePath, tmpDir);
340
- } else {
341
- console.error("Extracting archive...");
342
- execFileSync("tar", ["-xzf", archivePath, "-C", tmpDir], { stdio: "ignore" });
343
- }
344
-
345
- const binaryName = NAME + (isWindows ? ".exe" : "");
346
- const extractedBinary = path.join(tmpDir, NAME + "-" + platform + "-" + arch);
347
- if (fs.existsSync(extractedBinary)) {
348
- fs.copyFileSync(extractedBinary, dest);
349
- } else {
350
- // Fallback: try the plain name (older release format)
351
- const plainBinary = path.join(tmpDir, binaryName);
352
- if (fs.existsSync(plainBinary)) {
353
- fs.copyFileSync(plainBinary, dest);
354
- } else {
355
- // Search in tmpDir
356
- const files = fs.readdirSync(tmpDir).filter(function(f) { return f.indexOf(NAME) !== -1 || f.indexOf(binaryName) !== -1; });
357
- if (files.length > 0) {
358
- fs.copyFileSync(path.join(tmpDir, files[0]), dest);
359
- } else {
360
- throw new Error("Binary not found in extracted archive. Files: " + fs.readdirSync(tmpDir).join(", "));
361
- }
362
- }
363
- }
364
- fs.chmodSync(dest, 0o755);
365
- ensureExecutable(path.join(__dirname, "run.js"));
366
- console.error("Installed to " + dest);
367
- } finally {
368
- fs.rmSync(tmpDir, { recursive: true, force: true });
369
- }
370
- });
371
- }
372
-
373
- function ensureExecutable(filePath) {
374
- try {
375
- if (fs.existsSync(filePath)) fs.chmodSync(filePath, 0o755);
376
- } catch {}
377
- }
378
-
379
- // ── Entry ──────────────────────────────────────────────────────────────────
380
-
381
- if (require.main === module) {
382
- if (!platform || !arch) {
383
- console.error(`Unsupported platform: ${process.platform}-${process.arch}`);
384
- process.exit(1);
385
- }
386
-
387
- // npx postinstall guard: skip binary download in ephemeral npx context
388
- const isNpxPostinstall =
389
- process.env.npm_command === "exec" && !process.env.DELTA_CLI_RUN;
390
-
391
- if (isNpxPostinstall) {
392
- process.exit(0);
393
- }
394
-
395
- try {
396
- install();
397
- console.log(`${NAME} v${VERSION} installed successfully`);
398
- } catch (err) {
399
- console.error(`Failed to install ${NAME}:`, err.message);
400
- console.error(
401
- `\nIf you are behind a firewall or in a restricted network, try one of:\n` +
402
- ` # 1. Use a proxy:\n` +
403
- ` export https_proxy=http://your-proxy:port\n` +
404
- ` npm install -g @delta-infra/cli\n\n` +
405
- ` # 2. Point to a corporate npm mirror:\n` +
406
- ` npm install -g @delta-infra/cli --registry=https://your-corp-mirror/\n` +
407
- `\nOr manually download from:\n` +
408
- ` https://github.com/${REPO}/releases/tag/v${VERSION}`
409
- );
410
- process.exit(1);
411
- }
412
- }
413
-
414
- module.exports = {
415
- getExpectedChecksum, verifyChecksum, assertAllowedHost,
416
- isCurlVersionSupported, curlSupportsSslRevokeBestEffort,
417
- };
1
+ // Copyright (c) 2026 Delta Infra Authors
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ const fs = require("fs");
5
+ const path = require("path");
6
+ const { execFileSync } = require("child_process");
7
+ const os = require("os");
8
+ const crypto = require("crypto");
9
+
10
+ const PKG = "@delta-infra/cli";
11
+
12
+ // Resolve the version to download:
13
+ // env var > npm registry > local package.json (fallback)
14
+ function resolveVersion() {
15
+ if (process.env.DELTA_CLI_VERSION) return process.env.DELTA_CLI_VERSION.replace(/^v/, "");
16
+ try {
17
+ const out = require("child_process").execFileSync("npm", ["view", PKG, "version"], {
18
+ stdio: ["ignore", "pipe", "pipe"],
19
+ timeout: 15000,
20
+ encoding: "utf8",
21
+ });
22
+ const ver = out.trim();
23
+ if (/^\d+\.\d+\.\d+/.test(ver)) return ver;
24
+ } catch {}
25
+ return require("../package.json").version.replace(/-.*$/, "");
26
+ }
27
+
28
+ const VERSION = resolveVersion();
29
+ const NAME = "delta-cli";
30
+ const REPO = "yzailab/delta-infra-cli";
31
+ const DEFAULT_ALLOWED_HOSTS = new Set([
32
+ "github.com",
33
+ "gh-proxy.com",
34
+ "ghproxy.net",
35
+ "gh.ddlc.top",
36
+ "objects.githubusercontent.com",
37
+ "release-assets.githubusercontent.com",
38
+ "github-releases.githubusercontent.com",
39
+ "raw.githubusercontent.com",
40
+ "registry.npmmirror.com",
41
+ ]);
42
+ const DEFAULT_ALLOWED_HOST_PREFIXES = [
43
+ "github-production-release-asset-",
44
+ ];
45
+
46
+ const PLATFORM_MAP = {
47
+ darwin: "darwin",
48
+ linux: "linux",
49
+ win32: "windows",
50
+ };
51
+
52
+ const ARCH_MAP = {
53
+ x64: "amd64",
54
+ arm64: "arm64",
55
+ };
56
+
57
+ const platform = PLATFORM_MAP[process.platform];
58
+ const arch = ARCH_MAP[process.arch];
59
+
60
+ const isWindows = process.platform === "win32";
61
+ const ext = isWindows ? ".zip" : ".tar.gz";
62
+ const archiveName = `${NAME}-${platform}-${arch}${ext}`;
63
+ const GITHUB_URL = `https://github.com/${REPO}/releases/download/v${VERSION}/${archiveName}`;
64
+
65
+ const binDir = path.join(__dirname, "..", "bin");
66
+ const dest = path.join(binDir, NAME + (isWindows ? ".exe" : ""));
67
+
68
+ // ── Mirror URL resolution ──────────────────────────────────────────────────
69
+
70
+ var _curlTimeoutMs = null;
71
+
72
+ function _getCurlTimeout() {
73
+ if (_curlTimeoutMs !== null) return _curlTimeoutMs;
74
+ var env = process.env.DELTA_CLI_DOWNLOAD_TIMEOUT;
75
+ var t = env ? parseInt(env, 10) : 0;
76
+ _curlTimeoutMs = t > 0 ? t : 60000;
77
+ return _curlTimeoutMs;
78
+ }
79
+
80
+ // GitHub release download mirrors.
81
+ // Format: [hostname, urlPrefix] — urlPrefix is prepended to the GitHub URL.
82
+ var _MIRROR_LIST = [
83
+ ["gh.ddlc.top", "https://gh.ddlc.top"],
84
+ ["ghproxy.net", "https://ghproxy.net"],
85
+ ["gh-proxy.com", "https://gh-proxy.com"],
86
+ ];
87
+
88
+ // Quick connectivity check: fetch a small file (checksums.txt) from each
89
+ // mirror and return only the ones that respond within the probe timeout.
90
+ function probeMirrors(version, cb) {
91
+ console.error("Probing " + _MIRROR_LIST.length + " download mirrors...");
92
+ var probeUrl = "/https://github.com/" + REPO + "/releases/download/v" + version + "/checksums.txt";
93
+ var results = [];
94
+ var pending = _MIRROR_LIST.length;
95
+ var done = false;
96
+
97
+ function finish() {
98
+ if (done) return;
99
+ done = true;
100
+ if (results.length > 0) {
101
+ console.error("Found " + results.length + " available mirror(s)");
102
+ } else {
103
+ console.error("No mirror responded, falling back to GitHub source");
104
+ }
105
+ cb(results);
106
+ }
107
+
108
+ if (pending === 0) return finish();
109
+
110
+ for (var i = 0; i < _MIRROR_LIST.length; i++) {
111
+ (function(idx) {
112
+ var entry = _MIRROR_LIST[idx];
113
+ var host = entry[0];
114
+ var prefix = entry[1];
115
+ var testUrl = prefix + probeUrl;
116
+ var args = [
117
+ "--fail", "--location", "--silent", "--show-error",
118
+ "--connect-timeout", "3", "--max-time", "5",
119
+ "--output", "/dev/null", testUrl,
120
+ ];
121
+ var child;
122
+ try {
123
+ child = require("child_process").spawn("curl", args, { stdio: ["ignore", "pipe", "pipe"], timeout: 5000 });
124
+ var stdout = "";
125
+ var stderr = "";
126
+ child.stdout.on("data", function(d) { stdout += d; });
127
+ child.stderr.on("data", function(d) { stderr += d; });
128
+ child.on("close", function(code) {
129
+ if (code === 0) {
130
+ results.push(prefix + "/https://github.com/" + REPO + "/releases/download/v" + version + "/" + archiveName);
131
+ }
132
+ pending--;
133
+ if (pending === 0) finish();
134
+ });
135
+ child.on("error", function() {
136
+ pending--;
137
+ if (pending === 0) finish();
138
+ });
139
+ } catch (e) {
140
+ pending--;
141
+ if (pending === 0) finish();
142
+ }
143
+ })(i);
144
+ }
145
+ // Safety timeout: if probes hang, continue without mirrors after 10s
146
+ setTimeout(finish, 5000);
147
+ }
148
+
149
+ function releaseAssetUrls(version, assetName, cb) {
150
+ var urls = [];
151
+ var mirror = process.env.DELTA_CLI_MIRROR || "";
152
+ if (mirror) {
153
+ urls.push("" + mirror.replace(/\/$/, "") + "/yzailab/delta-infra-cli/releases/download/v" + version + "/" + assetName);
154
+ }
155
+ // Probe mirrors in parallel first, then fallback
156
+ probeMirrors(version, function(mirrorUrls) {
157
+ for (var i = 0; i < mirrorUrls.length; i++) {
158
+ urls.push(mirrorUrls[i]);
159
+ }
160
+ // GitHub source (last resort)
161
+ urls.push(GITHUB_URL);
162
+ cb(urls);
163
+ });
164
+ }
165
+
166
+ function assertAllowedHost(url) {
167
+ const { hostname } = new URL(url);
168
+ const allowlist = new Set(DEFAULT_ALLOWED_HOSTS);
169
+ (process.env.DELTA_CLI_MIRROR_ALLOWLIST || "")
170
+ .split(",")
171
+ .map((h) => h.trim().toLowerCase())
172
+ .filter(Boolean)
173
+ .forEach((h) => allowlist.add(h));
174
+ for (const allowed of allowlist) {
175
+ if (hostname === allowed || hostname.endsWith("." + allowed)) return;
176
+ }
177
+ for (const prefix of DEFAULT_ALLOWED_HOST_PREFIXES) {
178
+ if (hostname.startsWith(prefix)) return;
179
+ }
180
+ throw new Error(`Download host not allowed: ${hostname}`);
181
+ }
182
+
183
+ // ── curl version detection (for --ssl-revoke-best-effort) ──────────────────
184
+
185
+ function isCurlVersionSupported(versionOutput) {
186
+ const match = String(versionOutput).match(/^\s*curl\s+(\d+)\.(\d+)\.(\d+)/i);
187
+ if (!match) return false;
188
+ const major = parseInt(match[1], 10);
189
+ const minor = parseInt(match[2], 10);
190
+ return major > 7 || (major === 7 && minor >= 70);
191
+ }
192
+
193
+ let _curlSupportsSslRevokeBestEffort;
194
+
195
+ function curlSupportsSslRevokeBestEffort() {
196
+ if (_curlSupportsSslRevokeBestEffort !== undefined) {
197
+ return _curlSupportsSslRevokeBestEffort;
198
+ }
199
+ try {
200
+ const output = execFileSync("curl", ["--version"], {
201
+ stdio: ["ignore", "pipe", "ignore"],
202
+ encoding: "utf8",
203
+ timeout: 5000,
204
+ });
205
+ _curlSupportsSslRevokeBestEffort = isCurlVersionSupported(output);
206
+ } catch {
207
+ _curlSupportsSslRevokeBestEffort = false;
208
+ }
209
+ return _curlSupportsSslRevokeBestEffort;
210
+ }
211
+
212
+ // ── Download ───────────────────────────────────────────────────────────────
213
+
214
+ function download(url, destPath) {
215
+ assertAllowedHost(url);
216
+ const args = [
217
+ "--fail", "--location", "--silent", "--show-error",
218
+ "--connect-timeout", "10",
219
+ "--max-time", "45",
220
+ "--speed-limit", "50000", "--speed-time", "10",
221
+ "--max-redirs", "3",
222
+ "--output", destPath,
223
+ ];
224
+ if (isWindows && curlSupportsSslRevokeBestEffort()) {
225
+ args.unshift("--ssl-revoke-best-effort");
226
+ }
227
+ args.push(url);
228
+ execFileSync("curl", args, { stdio: ["ignore", "ignore", "pipe"] });
229
+ }
230
+
231
+ // ── Extraction ─────────────────────────────────────────────────────────────
232
+
233
+ function extractZipWindows(archivePath, destDir) {
234
+ const psOpts = ["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command"];
235
+ const psEnv = {
236
+ DELTA_CLI_ARCHIVE: archivePath,
237
+ DELTA_CLI_DEST: destDir,
238
+ };
239
+ try {
240
+ const dotnet =
241
+ "$ErrorActionPreference='Stop';" +
242
+ "Add-Type -AssemblyName System.IO.Compression.FileSystem;" +
243
+ "[System.IO.Compression.ZipFile]::ExtractToDirectory($env:DELTA_CLI_ARCHIVE,$env:DELTA_CLI_DEST)";
244
+ execFileSync("powershell.exe", [...psOpts, dotnet], { stdio: ["ignore", "inherit", "inherit"], env: psEnv });
245
+ } catch (primaryErr) {
246
+ try {
247
+ const cmdlet =
248
+ "$ErrorActionPreference='Stop';" +
249
+ "Expand-Archive -LiteralPath $env:DELTA_CLI_ARCHIVE -DestinationPath $env:DELTA_CLI_DEST -Force";
250
+ execFileSync("powershell.exe", [...psOpts, cmdlet], { stdio: ["ignore", "inherit", "inherit"], env: psEnv });
251
+ } catch (secondErr) {
252
+ try {
253
+ execFileSync("tar", ["-xf", archivePath, "-C", destDir], { stdio: "ignore" });
254
+ } catch (fallbackErr) {
255
+ throw new Error(
256
+ `Failed to extract ${archivePath}. ` +
257
+ `.NET ZipFile: ${primaryErr.message}. ` +
258
+ `Expand-Archive: ${secondErr.message}. ` +
259
+ `tar: ${fallbackErr.message}`
260
+ );
261
+ }
262
+ }
263
+ }
264
+ }
265
+
266
+ // ── Checksum ───────────────────────────────────────────────────────────────
267
+
268
+ function getExpectedChecksum(archiveName, checksumsDir) {
269
+ const dir = checksumsDir || path.join(__dirname, "..");
270
+ const checksumsPath = path.join(dir, "checksums.txt");
271
+ if (!fs.existsSync(checksumsPath)) {
272
+ console.error("[WARN] checksums.txt not found, skipping checksum verification");
273
+ return null;
274
+ }
275
+ const content = fs.readFileSync(checksumsPath, "utf8");
276
+ for (const line of content.split("\n")) {
277
+ const trimmed = line.trim();
278
+ if (!trimmed) continue;
279
+ const match = trimmed.match(/^([a-fA-F0-9]{64})\s+\*?(.+)$/);
280
+ if (!match) continue;
281
+ const hash = match[1];
282
+ const name = match[2];
283
+ if (name === archiveName) return hash;
284
+ }
285
+ throw new Error(`Checksum entry not found for ${archiveName}`);
286
+ }
287
+
288
+ function verifyChecksum(archivePath, expectedHash) {
289
+ if (expectedHash === null) return;
290
+ const hash = crypto.createHash("sha256");
291
+ const fd = fs.openSync(archivePath, "r");
292
+ try {
293
+ const buf = Buffer.alloc(64 * 1024);
294
+ let bytesRead;
295
+ while ((bytesRead = fs.readSync(fd, buf, 0, buf.length, null)) > 0) {
296
+ hash.update(buf.subarray(0, bytesRead));
297
+ }
298
+ } finally {
299
+ fs.closeSync(fd);
300
+ }
301
+ const actual = hash.digest("hex");
302
+ if (actual.toLowerCase() !== expectedHash.toLowerCase()) {
303
+ throw new Error(
304
+ `[SECURITY] Checksum mismatch for ${path.basename(archivePath)}: expected ${expectedHash} but got ${actual}`
305
+ );
306
+ }
307
+ }
308
+
309
+ // ── Main install ───────────────────────────────────────────────────────────
310
+
311
+ function install() {
312
+ fs.mkdirSync(binDir, { recursive: true });
313
+ var tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "delta-cli-"));
314
+ var archivePath = path.join(tmpDir, archiveName);
315
+
316
+ releaseAssetUrls(VERSION, archiveName, function(downloadUrls) {
317
+ try {
318
+ var lastErr;
319
+ var downloaded = false;
320
+ for (var i = 0; i < downloadUrls.length; i++) {
321
+ try {
322
+ console.error("Downloading from " + downloadUrls[i]);
323
+ download(downloadUrls[i], archivePath);
324
+ console.error("Download complete, verifying checksum...");
325
+ const expectedHash = getExpectedChecksum(archiveName);
326
+ verifyChecksum(archivePath, expectedHash);
327
+ console.error("Checksum verified");
328
+ downloaded = true;
329
+ break;
330
+ } catch (e) {
331
+ console.error("Failed: " + e.message + " (" + downloadUrls[i] + ")");
332
+ lastErr = e;
333
+ }
334
+ }
335
+ if (!downloaded) throw lastErr;
336
+
337
+ if (isWindows) {
338
+ console.error("Extracting archive...");
339
+ extractZipWindows(archivePath, tmpDir);
340
+ } else {
341
+ console.error("Extracting archive...");
342
+ execFileSync("tar", ["-xzf", archivePath, "-C", tmpDir], { stdio: "ignore" });
343
+ }
344
+
345
+ const binaryName = NAME + (isWindows ? ".exe" : "");
346
+ const extractedBinary = path.join(tmpDir, NAME + "-" + platform + "-" + arch);
347
+ if (fs.existsSync(extractedBinary)) {
348
+ fs.copyFileSync(extractedBinary, dest);
349
+ } else {
350
+ // Fallback: try the plain name (older release format)
351
+ const plainBinary = path.join(tmpDir, binaryName);
352
+ if (fs.existsSync(plainBinary)) {
353
+ fs.copyFileSync(plainBinary, dest);
354
+ } else {
355
+ // Search in tmpDir
356
+ const files = fs.readdirSync(tmpDir).filter(function(f) { return f.indexOf(NAME) !== -1 || f.indexOf(binaryName) !== -1; });
357
+ if (files.length > 0) {
358
+ fs.copyFileSync(path.join(tmpDir, files[0]), dest);
359
+ } else {
360
+ throw new Error("Binary not found in extracted archive. Files: " + fs.readdirSync(tmpDir).join(", "));
361
+ }
362
+ }
363
+ }
364
+ fs.chmodSync(dest, 0o755);
365
+ ensureExecutable(path.join(__dirname, "run.js"));
366
+ console.error("Installed to " + dest);
367
+ } finally {
368
+ fs.rmSync(tmpDir, { recursive: true, force: true });
369
+ }
370
+ });
371
+ }
372
+
373
+ function ensureExecutable(filePath) {
374
+ try {
375
+ if (fs.existsSync(filePath)) fs.chmodSync(filePath, 0o755);
376
+ } catch {}
377
+ }
378
+
379
+ // ── Entry ──────────────────────────────────────────────────────────────────
380
+
381
+ if (require.main === module) {
382
+ if (!platform || !arch) {
383
+ console.error(`Unsupported platform: ${process.platform}-${process.arch}`);
384
+ process.exit(1);
385
+ }
386
+
387
+ // npx postinstall guard: skip binary download in ephemeral npx context
388
+ const isNpxPostinstall =
389
+ process.env.npm_command === "exec" && !process.env.DELTA_CLI_RUN;
390
+
391
+ if (isNpxPostinstall) {
392
+ process.exit(0);
393
+ }
394
+
395
+ try {
396
+ install();
397
+ console.log(`${NAME} v${VERSION} installed successfully`);
398
+ } catch (err) {
399
+ console.error(`Failed to install ${NAME}:`, err.message);
400
+ console.error(
401
+ `\nIf you are behind a firewall or in a restricted network, try one of:\n` +
402
+ ` # 1. Use a proxy:\n` +
403
+ ` export https_proxy=http://your-proxy:port\n` +
404
+ ` npm install -g @delta-infra/cli\n\n` +
405
+ ` # 2. Point to a corporate npm mirror:\n` +
406
+ ` npm install -g @delta-infra/cli --registry=https://your-corp-mirror/\n` +
407
+ `\nOr manually download from:\n` +
408
+ ` https://github.com/${REPO}/releases/tag/v${VERSION}`
409
+ );
410
+ process.exit(1);
411
+ }
412
+ }
413
+
414
+ module.exports = {
415
+ getExpectedChecksum, verifyChecksum, assertAllowedHost,
416
+ isCurlVersionSupported, curlSupportsSslRevokeBestEffort,
417
+ };