@gfean/react-native-bundle-drop 0.7.0 → 0.8.1

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 (34) hide show
  1. package/README.md +215 -0
  2. package/android/build.gradle +7 -5
  3. package/lib/CLI/cli.js +5 -0
  4. package/lib/CLI/scripts/sight-artifacts.d.ts +9 -1
  5. package/lib/CLI/scripts/sight-artifacts.js +20 -8
  6. package/lib/CLI/scripts/sight-assets.d.ts +15 -0
  7. package/lib/CLI/scripts/sight-assets.js +71 -0
  8. package/lib/CLI/scripts/sight-cli.d.ts +3 -0
  9. package/lib/CLI/scripts/sight-cli.js +50 -4
  10. package/lib/CLI/scripts/sight-compare/assets.d.ts +6 -0
  11. package/lib/CLI/scripts/sight-compare/assets.js +73 -0
  12. package/lib/CLI/scripts/sight-compare/dependencies.d.ts +22 -0
  13. package/lib/CLI/scripts/sight-compare/dependencies.js +289 -0
  14. package/lib/CLI/scripts/sight-compare/git.d.ts +22 -0
  15. package/lib/CLI/scripts/sight-compare/git.js +116 -0
  16. package/lib/CLI/scripts/sight-compare/inspect-project.d.ts +37 -0
  17. package/lib/CLI/scripts/sight-compare/inspect-project.js +191 -0
  18. package/lib/CLI/scripts/sight-compare/metadata.d.ts +4 -0
  19. package/lib/CLI/scripts/sight-compare/metadata.js +39 -0
  20. package/lib/CLI/scripts/sight-compare/process.d.ts +22 -0
  21. package/lib/CLI/scripts/sight-compare/process.js +221 -0
  22. package/lib/CLI/scripts/sight-compare/run.d.ts +3 -0
  23. package/lib/CLI/scripts/sight-compare/run.js +290 -0
  24. package/lib/CLI/scripts/sight-compare/snapshot.d.ts +26 -0
  25. package/lib/CLI/scripts/sight-compare/snapshot.js +279 -0
  26. package/lib/CLI/scripts/sight-compare/types.d.ts +87 -0
  27. package/lib/CLI/scripts/sight-compare/types.js +2 -0
  28. package/lib/CLI/scripts/sight-ota.d.ts +18 -0
  29. package/lib/CLI/scripts/sight-ota.js +260 -0
  30. package/lib/CLI/scripts/sight-session.d.ts +9 -2
  31. package/lib/CLI/scripts/sight-session.js +58 -20
  32. package/lib/scripts/bundle.d.ts +3 -0
  33. package/lib/scripts/bundle.js +7 -4
  34. package/package.json +12 -12
@@ -0,0 +1,191 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.prepareProjectEnvironment = prepareProjectEnvironment;
7
+ exports.inspectInstalledProject = inspectInstalledProject;
8
+ exports.inspectSourceMapContext = inspectSourceMapContext;
9
+ exports.inspectSightProject = inspectSightProject;
10
+ const fs_1 = __importDefault(require("fs"));
11
+ const path_1 = __importDefault(require("path"));
12
+ const module_1 = require("module");
13
+ const expo_1 = require("../../../expo");
14
+ const process_1 = require("./process");
15
+ function requireInsideSnapshot(snapshotRoot, resolved) {
16
+ const real = fs_1.default.realpathSync(resolved);
17
+ const relative = path_1.default.relative(snapshotRoot, real);
18
+ if (relative === '..' || relative.startsWith(`..${path_1.default.sep}`) || path_1.default.isAbsolute(relative)) {
19
+ throw new Error(`Sight comparison resolved a file outside the repository snapshot: ${resolved}`);
20
+ }
21
+ return real;
22
+ }
23
+ function logicalEntryForResolvedFile(projectRoot, entryFile) {
24
+ const relative = path_1.default.relative(projectRoot, entryFile).split(path_1.default.sep).join('/');
25
+ const marker = '/node_modules/';
26
+ const normalized = entryFile.split(path_1.default.sep).join('/');
27
+ const moduleStart = normalized.lastIndexOf(marker);
28
+ if (moduleStart !== -1) {
29
+ return { kind: 'module', value: normalized.slice(moduleStart + marker.length).replace(/\.[cm]?[jt]sx?$/, '') };
30
+ }
31
+ return { kind: 'relative', value: relative };
32
+ }
33
+ /** Match export:embed's dotenv loading before evaluating dynamic app configuration. */
34
+ function prepareProjectEnvironment(options) {
35
+ if (options.explicitType === 'bare')
36
+ return;
37
+ const snapshotRoot = fs_1.default.realpathSync(options.snapshotRoot);
38
+ const projectRoot = requireInsideSnapshot(snapshotRoot, options.projectRoot);
39
+ const projectRequire = (0, module_1.createRequire)(path_1.default.join(projectRoot, 'package.json'));
40
+ let expoManifest;
41
+ try {
42
+ expoManifest = projectRequire.resolve('expo/package.json');
43
+ }
44
+ catch {
45
+ return;
46
+ }
47
+ const expoRequire = (0, module_1.createRequire)(requireInsideSnapshot(snapshotRoot, expoManifest));
48
+ let loaderPath;
49
+ try {
50
+ loaderPath = expoRequire.resolve('@expo/cli/build/src/utils/nodeEnv');
51
+ }
52
+ catch {
53
+ // Bare apps may have Expo modules without the export CLI installed.
54
+ }
55
+ const loader = loaderPath ? expoRequire(requireInsideSnapshot(snapshotRoot, loaderPath)) : undefined;
56
+ if (typeof loader?.loadEnvFiles !== 'function') {
57
+ if ((0, expo_1.detectProjectType)({ projectRoot, explicitType: options.explicitType }) === 'bare')
58
+ return;
59
+ throw new Error('This Expo CLI does not expose its environment loader. Sight cannot reproduce export:embed configuration for this version.');
60
+ }
61
+ // The installed loader owns dotenv precedence and EXPO_NO_DOTENV behavior.
62
+ loader.loadEnvFiles(projectRoot);
63
+ }
64
+ /** Runs only in the disposable snapshot child process; exported for fixture tests. */
65
+ function inspectInstalledProject(options) {
66
+ const snapshotRoot = fs_1.default.realpathSync(options.snapshotRoot);
67
+ const projectRoot = requireInsideSnapshot(snapshotRoot, options.projectRoot);
68
+ const manifestPath = requireInsideSnapshot(snapshotRoot, path_1.default.join(projectRoot, 'package.json'));
69
+ const projectRequire = (0, module_1.createRequire)(manifestPath);
70
+ const projectType = (0, expo_1.detectProjectType)({ projectRoot, explicitType: options.explicitType });
71
+ const resolve = (specifier) => requireInsideSnapshot(snapshotRoot, projectRequire.resolve(specifier));
72
+ const reactNativeManifest = resolve('react-native/package.json');
73
+ const versions = {
74
+ reactNative: JSON.parse(fs_1.default.readFileSync(reactNativeManifest, 'utf8')).version,
75
+ };
76
+ let expoRequire;
77
+ if (projectType === 'expo') {
78
+ const expoManifest = resolve('expo/package.json');
79
+ versions.expo = JSON.parse(fs_1.default.readFileSync(expoManifest, 'utf8')).version;
80
+ expoRequire = (0, module_1.createRequire)(expoManifest);
81
+ }
82
+ const moduleResolvers = [projectRequire, (0, module_1.createRequire)(reactNativeManifest)];
83
+ if (expoRequire)
84
+ moduleResolvers.push(expoRequire);
85
+ for (const resolver of moduleResolvers) {
86
+ let metroManifest;
87
+ try {
88
+ metroManifest = resolver.resolve('metro/package.json');
89
+ }
90
+ catch {
91
+ continue;
92
+ }
93
+ versions.metro = JSON.parse(fs_1.default.readFileSync(requireInsideSnapshot(snapshotRoot, metroManifest), 'utf8')).version;
94
+ break;
95
+ }
96
+ let resolvedEntryFile;
97
+ let logicalEntry = options.logicalEntry;
98
+ if (logicalEntry) {
99
+ resolvedEntryFile = logicalEntry.kind === 'module'
100
+ ? resolve(logicalEntry.value)
101
+ : path_1.default.resolve(projectRoot, logicalEntry.value);
102
+ }
103
+ else if (options.entryFile) {
104
+ if (path_1.default.isAbsolute(options.entryFile)) {
105
+ throw new Error('Comparison --entry-file must be relative to the app directory.');
106
+ }
107
+ resolvedEntryFile = path_1.default.resolve(projectRoot, options.entryFile);
108
+ }
109
+ else if (expoRequire) {
110
+ const configPaths = expoRequire(requireInsideSnapshot(snapshotRoot, expoRequire.resolve('@expo/config/paths')));
111
+ const entry = configPaths.resolveEntryPoint(projectRoot, { platform: options.platform });
112
+ if (!entry)
113
+ throw new Error(`Expo could not resolve the ${options.platform} entrypoint.`);
114
+ resolvedEntryFile = path_1.default.resolve(projectRoot, entry);
115
+ const manifest = JSON.parse(fs_1.default.readFileSync(manifestPath, 'utf8'));
116
+ if (manifest.main && !manifest.main.startsWith('.') && !path_1.default.isAbsolute(manifest.main)) {
117
+ try {
118
+ if (resolve(manifest.main) === fs_1.default.realpathSync(resolvedEntryFile)) {
119
+ logicalEntry = { kind: 'module', value: manifest.main };
120
+ }
121
+ }
122
+ catch {
123
+ // A file such as index.js is a valid main field but not a module specifier.
124
+ }
125
+ }
126
+ }
127
+ else {
128
+ const entry = ['index.js', 'index.ts', 'index.tsx', 'index.jsx'].find(file => {
129
+ const candidate = path_1.default.join(projectRoot, file);
130
+ return fs_1.default.existsSync(candidate) && fs_1.default.statSync(candidate).isFile();
131
+ });
132
+ if (!entry)
133
+ throw new Error('Could not find a React Native entry file. Pass --entry-file <relative-path>.');
134
+ resolvedEntryFile = path_1.default.join(projectRoot, entry);
135
+ }
136
+ logicalEntry = logicalEntry || logicalEntryForResolvedFile(projectRoot, resolvedEntryFile);
137
+ resolvedEntryFile = requireInsideSnapshot(snapshotRoot, resolvedEntryFile);
138
+ if (!fs_1.default.statSync(resolvedEntryFile).isFile())
139
+ throw new Error('The comparison entrypoint must be a file.');
140
+ return { projectType, entry: logicalEntry, resolvedEntryFile, versions };
141
+ }
142
+ /** Use the same config loader as export:embed; custom Metro roots must be honored. */
143
+ async function inspectSourceMapContext(options, projectType) {
144
+ const snapshotRoot = fs_1.default.realpathSync(options.snapshotRoot);
145
+ if (projectType === 'bare')
146
+ return { sourceMapBase: snapshotRoot, sourcePathConvention: 'filesystem' };
147
+ const projectRoot = requireInsideSnapshot(snapshotRoot, options.projectRoot);
148
+ const projectRequire = (0, module_1.createRequire)(path_1.default.join(projectRoot, 'package.json'));
149
+ const expoManifest = requireInsideSnapshot(snapshotRoot, projectRequire.resolve('expo/package.json'));
150
+ const expoRequire = (0, module_1.createRequire)(expoManifest);
151
+ let loaderPath;
152
+ try {
153
+ loaderPath = requireInsideSnapshot(snapshotRoot, expoRequire.resolve('@expo/cli/build/src/start/server/metro/instantiateMetro'));
154
+ }
155
+ catch {
156
+ throw new Error('This Expo CLI does not expose its Metro configuration loader. Sight cannot establish source-map paths for this version.');
157
+ }
158
+ const loader = expoRequire(loaderPath);
159
+ if (typeof loader.loadMetroConfigAsync !== 'function') {
160
+ throw new Error('This Expo CLI does not expose loadMetroConfigAsync. Sight cannot establish source-map paths for this version.');
161
+ }
162
+ const expoConfig = expoRequire(requireInsideSnapshot(snapshotRoot, expoRequire.resolve('@expo/config')));
163
+ const { exp } = expoConfig.getConfig(projectRoot, { skipSDKVersionRequirement: true });
164
+ const { config } = await loader.loadMetroConfigAsync(projectRoot, {}, { exp, isExporting: true });
165
+ const sourceMapBase = requireInsideSnapshot(snapshotRoot, config.server?.unstable_serverRoot ?? config.projectRoot);
166
+ return { sourceMapBase, sourcePathConvention: 'expo-server-root' };
167
+ }
168
+ const resultMarker = 'BUNDLE_DROP_SIGHT_PROJECT=';
169
+ const childScript = `const helper = require(process.argv[1]);
170
+ void (async () => {
171
+ const options = JSON.parse(process.argv[2]);
172
+ helper.prepareProjectEnvironment(options);
173
+ const result = helper.inspectInstalledProject(options);
174
+ const context = await helper.inspectSourceMapContext(options, result.projectType);
175
+ process.stdout.write('\\n${resultMarker}' + JSON.stringify({ ...result, ...context }) + '\\n');
176
+ })().catch(error => { console.error(error); process.exitCode = 1; });`;
177
+ async function inspectSightProject(options, processOptions = {}) {
178
+ const result = await (0, process_1.runComparisonProcess)({
179
+ command: process.execPath,
180
+ args: ['-e', childScript, __filename, JSON.stringify(options)],
181
+ cwd: options.projectRoot,
182
+ phase: 'Inspect comparison project',
183
+ signal: processOptions.signal,
184
+ env: { ...(processOptions.env || process.env), NODE_ENV: 'production' },
185
+ logPath: processOptions.logPath,
186
+ });
187
+ const line = result.stdout.split('\n').reverse().find(value => value.startsWith(resultMarker));
188
+ if (!line)
189
+ throw new Error('Project inspection did not return comparison metadata. See the inspection log.');
190
+ return JSON.parse(line.slice(resultMarker.length));
191
+ }
@@ -0,0 +1,4 @@
1
+ import type { ComparisonArtifact, ComparisonArtifacts, ComparisonMetadata } from './types';
2
+ export declare const MAX_COMPARISON_METADATA_BYTES: number;
3
+ export declare function describeArtifact(outputDirectory: string, filePath: string): ComparisonArtifact;
4
+ export declare function writeComparisonMetadata(artifacts: ComparisonArtifacts, metadata: Omit<ComparisonMetadata, 'artifacts'>): ComparisonMetadata;
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.MAX_COMPARISON_METADATA_BYTES = void 0;
7
+ exports.describeArtifact = describeArtifact;
8
+ exports.writeComparisonMetadata = writeComparisonMetadata;
9
+ const crypto_1 = require("crypto");
10
+ const fs_1 = __importDefault(require("fs"));
11
+ const path_1 = __importDefault(require("path"));
12
+ exports.MAX_COMPARISON_METADATA_BYTES = 64 * 1024;
13
+ function describeArtifact(outputDirectory, filePath) {
14
+ const contents = fs_1.default.readFileSync(filePath);
15
+ return {
16
+ path: path_1.default.relative(outputDirectory, filePath).split(path_1.default.sep).join('/'),
17
+ bytes: contents.length,
18
+ sha256: (0, crypto_1.createHash)('sha256').update(contents).digest('hex'),
19
+ };
20
+ }
21
+ function writeComparisonMetadata(artifacts, metadata) {
22
+ const describe = (filePath) => describeArtifact(artifacts.outputDirectory, filePath);
23
+ const document = {
24
+ ...metadata,
25
+ artifacts: {
26
+ baselineBundle: describe(artifacts.baseline.bundlePath),
27
+ baselineSourceMap: describe(artifacts.baseline.sourceMapPath),
28
+ currentBundle: describe(artifacts.current.bundlePath),
29
+ currentSourceMap: describe(artifacts.current.sourceMapPath),
30
+ },
31
+ ...(artifacts.assetManifestPath ? { assetManifest: describe(artifacts.assetManifestPath) } : {}),
32
+ };
33
+ const json = JSON.stringify(document, null, 2) + '\n';
34
+ if (Buffer.byteLength(json) > exports.MAX_COMPARISON_METADATA_BYTES) {
35
+ throw new Error('Sight comparison metadata exceeds 64 KiB. Reduce the included paths and retry.');
36
+ }
37
+ fs_1.default.writeFileSync(artifacts.metadataPath, json, { mode: 0o600 });
38
+ return document;
39
+ }
@@ -0,0 +1,22 @@
1
+ export type ComparisonProcessOptions = {
2
+ command: string;
3
+ args: string[];
4
+ cwd: string;
5
+ phase: string;
6
+ signal?: AbortSignal;
7
+ env?: NodeJS.ProcessEnv;
8
+ logPath?: string;
9
+ inheritStdin?: boolean;
10
+ inheritOutput?: boolean;
11
+ input?: string;
12
+ allowedExitCodes?: number[];
13
+ };
14
+ export type ComparisonProcessResult = {
15
+ stdout: string;
16
+ stderr: string;
17
+ exitCode: number;
18
+ };
19
+ export declare function comparisonAbortError(): Error;
20
+ export declare function checkComparisonAbort(signal?: AbortSignal): void;
21
+ /** Run in a separate process group so cancelling also stops Metro/install children. */
22
+ export declare function runComparisonProcess({ command, args, cwd, phase, signal, env, logPath, inheritStdin, inheritOutput, input, allowedExitCodes, }: ComparisonProcessOptions): Promise<ComparisonProcessResult>;
@@ -0,0 +1,221 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.comparisonAbortError = comparisonAbortError;
7
+ exports.checkComparisonAbort = checkComparisonAbort;
8
+ exports.runComparisonProcess = runComparisonProcess;
9
+ const child_process_1 = require("child_process");
10
+ const fs_1 = __importDefault(require("fs"));
11
+ const path_1 = __importDefault(require("path"));
12
+ function comparisonAbortError() {
13
+ const error = new Error('Sight comparison cancelled.');
14
+ error.name = 'AbortError';
15
+ return error;
16
+ }
17
+ function checkComparisonAbort(signal) {
18
+ if (signal?.aborted)
19
+ throw comparisonAbortError();
20
+ }
21
+ function redactOutput(output, env) {
22
+ let result = output.replace(/(https?:\/\/)[^\s/@]+@/gi, '$1[redacted]@');
23
+ for (const [name, value] of Object.entries(env)) {
24
+ if (/(token|password|secret|credential|authorization)/i.test(name) && value && value.length >= 4) {
25
+ result = result.split(value).join('[redacted]');
26
+ }
27
+ }
28
+ return result;
29
+ }
30
+ function windowsPackageManager(command, args, cwd, env) {
31
+ const manager = path_1.default.basename(command).match(/^(npm|yarn|pnpm)(?:\.(?:cmd|bat|exe|com))?$/i)?.[1]?.toLowerCase();
32
+ if (process.platform !== 'win32' || !manager)
33
+ return { command, args };
34
+ const variables = Object.fromEntries(Object.entries(env).map(([name, value]) => [name.toUpperCase(), value]));
35
+ const extensions = (variables.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').map(extension => extension.toLowerCase());
36
+ const directories = path_1.default.isAbsolute(command) || /[/\\]/.test(command)
37
+ ? [path_1.default.dirname(path_1.default.resolve(cwd, command))]
38
+ : (variables.PATH || '').split(';').filter(Boolean).map(directory => directory.replace(/^"|"$/g, ''));
39
+ const names = path_1.default.extname(command) ? [path_1.default.basename(command)] : extensions.map(extension => `${manager}${extension}`);
40
+ let executable;
41
+ for (const directory of directories) {
42
+ executable = names.map(name => path_1.default.resolve(directory, name)).find(file => fs_1.default.existsSync(file) && fs_1.default.statSync(file).isFile());
43
+ if (executable)
44
+ break;
45
+ }
46
+ if (!executable)
47
+ throw new Error(`Could not find ${manager} on PATH. Install the required package manager before comparing.`);
48
+ if (/\.(?:exe|com)$/i.test(executable))
49
+ return { command: executable, args };
50
+ if (/\.(?:cmd|bat)$/i.test(executable)) {
51
+ const directory = path_1.default.dirname(executable);
52
+ const entries = {
53
+ npm: 'npm/bin/npm-cli.js',
54
+ yarn: 'yarn/bin/yarn.js',
55
+ pnpm: 'pnpm/bin/pnpm.cjs',
56
+ };
57
+ const candidates = [
58
+ path_1.default.join(directory, 'node_modules', entries[manager]),
59
+ path_1.default.join(directory, 'node_modules', 'corepack', 'dist', `${manager}.js`),
60
+ ];
61
+ if (path_1.default.basename(directory) === '.bin') {
62
+ candidates.push(path_1.default.resolve(directory, '..', entries[manager]), path_1.default.resolve(directory, '..', 'corepack', 'dist', `${manager}.js`));
63
+ }
64
+ const script = candidates.find(file => fs_1.default.existsSync(file) && fs_1.default.statSync(file).isFile());
65
+ if (script)
66
+ return { command: process.execPath, args: [script, ...args] };
67
+ }
68
+ throw new Error(`Unsupported Windows ${manager} launcher. Install a standard Node/npm or Corepack package-manager shim, or provide its native executable on PATH.`);
69
+ }
70
+ async function waitForProcessGroupExit(pid, timeoutMs) {
71
+ const deadline = Date.now() + timeoutMs;
72
+ const permissionDeadline = Date.now() + Math.max(timeoutMs, 100);
73
+ while (true) {
74
+ try {
75
+ process.kill(-pid, 0);
76
+ }
77
+ catch (error) {
78
+ if (error.code === 'ESRCH')
79
+ return true;
80
+ // Darwin can report EPERM for a group containing only unreaped zombies.
81
+ // Require a later ESRCH; a persistent permission failure must still reject.
82
+ if (process.platform === 'darwin' && error.code === 'EPERM' && Date.now() < permissionDeadline) {
83
+ await new Promise(resolve => setTimeout(resolve, 20));
84
+ continue;
85
+ }
86
+ throw error;
87
+ }
88
+ if (Date.now() >= deadline)
89
+ return false;
90
+ await new Promise(resolve => setTimeout(resolve, 20));
91
+ }
92
+ }
93
+ async function stopRemainingProcessGroup(pid) {
94
+ // Windows taskkill requires a live leader; Job Object containment is not provided here.
95
+ if (process.platform === 'win32' || !pid || await waitForProcessGroupExit(pid, 0))
96
+ return;
97
+ for (const signal of ['SIGTERM', 'SIGKILL']) {
98
+ try {
99
+ process.kill(-pid, signal);
100
+ }
101
+ catch (error) {
102
+ if (error.code === 'ESRCH')
103
+ return;
104
+ throw error;
105
+ }
106
+ if (await waitForProcessGroupExit(pid, 1000))
107
+ return;
108
+ }
109
+ throw new Error('A comparison subprocess left a process group running after termination.');
110
+ }
111
+ /** Run in a separate process group so cancelling also stops Metro/install children. */
112
+ async function runComparisonProcess({ command, args, cwd, phase, signal, env = process.env, logPath, inheritStdin = false, inheritOutput = false, input, allowedExitCodes = [0], }) {
113
+ checkComparisonAbort(signal);
114
+ if (logPath)
115
+ fs_1.default.mkdirSync(path_1.default.dirname(logPath), { recursive: true });
116
+ const executable = windowsPackageManager(command, args, cwd, env);
117
+ return new Promise((resolve, reject) => {
118
+ const child = (0, child_process_1.spawn)(executable.command, executable.args, {
119
+ cwd,
120
+ env,
121
+ shell: false,
122
+ detached: process.platform !== 'win32',
123
+ windowsHide: true,
124
+ stdio: [input !== undefined ? 'pipe' : inheritStdin ? 'inherit' : 'ignore', inheritOutput ? 'inherit' : 'pipe', inheritOutput ? 'inherit' : 'pipe'],
125
+ });
126
+ let stdout = '';
127
+ let stderr = '';
128
+ let escalation;
129
+ let processError;
130
+ let windowsTermination;
131
+ let groupTermination;
132
+ let groupCleanupTimer;
133
+ const stopGroup = () => {
134
+ groupTermination ?? (groupTermination = stopRemainingProcessGroup(child.pid).catch(error => { processError = error; }));
135
+ return groupTermination;
136
+ };
137
+ const terminateGroup = (force) => {
138
+ if (!child.pid)
139
+ return;
140
+ if (process.platform === 'win32') {
141
+ const killer = (0, child_process_1.spawn)('taskkill', ['/pid', String(child.pid), '/t', '/f'], {
142
+ windowsHide: true,
143
+ stdio: 'ignore',
144
+ });
145
+ windowsTermination = new Promise(done => {
146
+ killer.once('error', () => { child.kill(); done(); });
147
+ killer.once('close', () => done());
148
+ });
149
+ }
150
+ else {
151
+ try {
152
+ process.kill(-child.pid, force ? 'SIGKILL' : 'SIGTERM');
153
+ }
154
+ catch (error) {
155
+ if (error.code !== 'ESRCH') {
156
+ processError = error;
157
+ child.kill(force ? 'SIGKILL' : 'SIGTERM');
158
+ }
159
+ }
160
+ }
161
+ };
162
+ const abort = () => {
163
+ terminateGroup(false);
164
+ if (process.platform !== 'win32') {
165
+ escalation = setTimeout(() => terminateGroup(true), 1000);
166
+ }
167
+ };
168
+ child.stdout?.setEncoding('utf8');
169
+ if (input !== undefined) {
170
+ child.stdin.on('error', error => { processError = error; });
171
+ child.stdin.end(input);
172
+ }
173
+ child.stderr?.setEncoding('utf8');
174
+ child.stdout?.on('data', (chunk) => { stdout += chunk; });
175
+ child.stderr?.on('data', (chunk) => { stderr += chunk; });
176
+ child.once('error', error => { processError = error; });
177
+ // Descendants can keep the output pipes open after the leader exits, delaying close.
178
+ child.once('exit', () => {
179
+ // Give normally exiting children a turn to release their pipes and process group.
180
+ groupCleanupTimer = setTimeout(stopGroup, 20);
181
+ });
182
+ child.once('close', async (code, exitSignal) => {
183
+ if (groupCleanupTimer)
184
+ clearTimeout(groupCleanupTimer);
185
+ signal?.removeEventListener('abort', abort);
186
+ if (escalation) {
187
+ // The leader may exit before descendants; finish killing its group before cleanup.
188
+ clearTimeout(escalation);
189
+ terminateGroup(true);
190
+ }
191
+ await windowsTermination;
192
+ await stopGroup();
193
+ const safeStdout = redactOutput(stdout, env);
194
+ const safeStderr = redactOutput(stderr, env);
195
+ try {
196
+ if (logPath)
197
+ fs_1.default.writeFileSync(logPath, `${safeStdout}${safeStderr}`, { mode: 0o600 });
198
+ }
199
+ catch (error) {
200
+ reject(error);
201
+ return;
202
+ }
203
+ if (signal?.aborted) {
204
+ reject(comparisonAbortError());
205
+ }
206
+ else if (processError) {
207
+ reject(new Error(`${phase} could not start or finish: ${redactOutput(processError.message, env)}`));
208
+ }
209
+ else if (code === null || !allowedExitCodes.includes(code)) {
210
+ const detail = safeStderr.trim().slice(-2000);
211
+ reject(new Error(`${phase} failed (${exitSignal || `exit ${code}`}).${detail ? `\n${detail}` : ''}`));
212
+ }
213
+ else {
214
+ resolve({ stdout, stderr: safeStderr, exitCode: code });
215
+ }
216
+ });
217
+ signal?.addEventListener('abort', abort, { once: true });
218
+ if (signal?.aborted)
219
+ abort();
220
+ });
221
+ }
@@ -0,0 +1,3 @@
1
+ import type { SightCommandOptions } from '../sight-cli';
2
+ export declare function comparisonEnvironment(source: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
3
+ export declare function runSightComparison(options: SightCommandOptions): Promise<void>;