Repository navigation
Expand file tree
/
Copy pathlaunchClient.test.ts
More file actions
1119 lines (1072 loc) · 51.1 KB
/
Copy pathlaunchClient.test.ts
File metadata and controls
1119 lines (1072 loc) · 51.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import { spawn, type ChildProcess } from 'node:child_process';
import { once } from 'node:events';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import * as http from 'node:http';
import { setTimeout as delayAsync } from 'node:timers/promises';
import { Rush } from '@microsoft/rush-lib';
import {
DaemonClient,
DaemonClientError,
connectOrStartDaemonAsync,
getDaemonLogFilePath,
reclaimCrashedDaemonAsync
} from '@rushstack/rush-client-core';
import type { DaemonClientOutcome } from '@rushstack/rush-client-core';
import { RushDaemonHost, WorkspaceSession } from '@rushstack/rush-daemon';
import {
removeTestFolderAsync,
waitForTestProcessExitAsync
} from '@rushstack/rush-daemon/lib/test/TestProcessExit';
import { captureTestDaemonListenerAsync } from '@rushstack/rush-daemon/lib/test/TestDaemonListener';
import {
DaemonTransportError,
DaemonTransportErrorCode,
readDaemonLockfile,
type IDaemonLockfile
} from '@rushstack/rush-daemon-transport';
import { getDaemonConnectionOptions } from '../daemonConnectionOptions';
import { CI_ENVIRONMENT_VARIABLES } from '../earlyRouting';
import { isConnectionFailure } from '../launchClient';
import {
CANCELLATION_SIGNALS,
formatCancellationMessage,
getSignalExitCode,
isCancelledOutcome
} from '../clientCancellation';
import { getTestProcessEnvironment } from './TestProcessEnvironment';
interface IInvocationResult {
readonly code: number | undefined;
readonly stdout: string;
readonly stderr: string;
}
// What `daemon status` adds when no daemon runs, for each resolved daemon.enabled and daemon.autoStart.
const NEXT_COMMAND_STARTS: string = '; the next rush-client command that uses the daemon starts one.';
const AUTO_START_OFF: string =
', and auto-start is off, so rush-client commands run Rush in-process until "rush-client daemon start" starts one.';
const NOT_ENABLED: string = '; the daemon is not enabled here, so rush-client commands run Rush in-process.';
// Turns off every CI marker that the test process may have inherited from its CI runner.
const NON_CI_ENVIRONMENT: NodeJS.ProcessEnv = Object.fromEntries(
CI_ENVIRONMENT_VARIABLES.map((name) => [name, 'false'])
);
// Windows runners take much longer to start the processes that these tests run.
const SLOW_TEST_TIMEOUT_MS: number = process.platform === 'win32' ? 60000 : 15000;
const CLEANUP_TIMEOUT_MS: number = process.platform === 'win32' ? 30000 : 5000;
describe('standalone rushx fallback', () => {
let folder: string;
let project: string;
let logFilePath: string;
let host: RushDaemonHost | undefined;
let invocationClosures: Promise<unknown>[];
let daemonPids: Set<number>;
beforeEach(() => {
invocationClosures = [];
daemonPids = new Set();
folder = fs.mkdtempSync(path.join(os.tmpdir(), 'rush-cli-client-'));
project = path.join(folder, 'project');
fs.mkdirSync(project);
fs.mkdirSync(path.join(folder, 'common/config/rush'), { recursive: true });
fs.writeFileSync(
path.join(folder, 'rush.json'),
JSON.stringify({
rushVersion: Rush.version,
suppressNodeLtsWarning: true,
pnpmVersion: '10.27.0',
daemon: { enabled: false, autoStart: false },
projects: [{ packageName: 'sample', projectFolder: 'project' }],
projectFolderMinDepth: 1
})
);
logFilePath = getDaemonLogFilePath(getDaemonConnectionOptions(folder, Rush.version, {}, false).paths);
fs.writeFileSync(
path.join(project, 'package.json'),
JSON.stringify({
name: 'sample',
version: '1.0.0',
scripts: {
sample:
'node -e "process.stdout.write(process.env.CLIENT_MARKER); process.stderr.write(\'script-error\'); process.exitCode=7;"'
}
})
);
});
afterEach(async () => {
const closingHost: RushDaemonHost | undefined = host;
const closingFolder: string = folder;
const closingLogFilePath: string = logFilePath;
const closingDaemonPids: Set<number> = daemonPids;
host = undefined;
await Promise.all(invocationClosures);
await closingHost?.closeAsync();
await Promise.all(Array.from(closingDaemonPids, (pid) => waitForTestProcessExitAsync(pid)));
await removeTestFolderAsync(closingLogFilePath, true);
await removeTestFolderAsync(closingFolder);
}, CLEANUP_TIMEOUT_MS);
async function invokeAsync(
client: boolean,
optIn: boolean,
fakeTty: boolean = false,
managementArgs?: ReadonlyArray<string>,
environmentOverrides: NodeJS.ProcessEnv = {},
onStderr?: (stderr: string) => void
): Promise<IInvocationResult> {
const invocationDaemonPids: Set<number> = daemonPids;
const entry: string = client
? path.resolve(__dirname, managementArgs ? '../../bin/rush-client' : '../../bin/rushx-client')
: path.resolve(path.dirname(require.resolve('@microsoft/rush/package.json')), 'bin/rushx');
const args: string[] = fakeTty
? [
'-e',
`Object.defineProperty(process.stdin, 'isTTY', { value: true }); process.argv = [process.execPath, ${JSON.stringify(entry)}, 'sample']; require(${JSON.stringify(entry)});`
]
: [entry, ...(managementArgs ?? [...(client ? ['--no-daemon'] : []), 'sample'])];
const child: ChildProcess = spawn(process.execPath, args, {
cwd: project,
env: {
...getTestProcessEnvironment(),
CLIENT_MARKER: 'script-output',
RUSH_DAEMON: optIn ? '1' : '0',
...NON_CI_ENVIRONMENT,
CI: managementArgs ? 'true' : 'false',
...environmentOverrides
},
stdio: ['ignore', 'pipe', 'pipe']
});
let stdout: string = '';
let stderr: string = '';
child.stdout!.on('data', (chunk: Buffer) => {
stdout += chunk.toString();
});
child.stderr!.on('data', (chunk: Buffer) => {
stderr += chunk.toString();
onStderr?.(stderr);
});
const closed: Promise<unknown[]> = once(child, 'close');
invocationClosures.push(closed);
const [code] = await closed;
if (
code === 0 &&
managementArgs?.[0] === 'daemon' &&
(managementArgs[1] === 'start' || managementArgs[1] === 'restart')
) {
const { pid }: { pid: unknown } = JSON.parse(stdout);
if (typeof pid !== 'number' || !Number.isSafeInteger(pid) || pid <= 0) {
throw new Error('The started fixture daemon did not report a valid PID.');
}
if (pid !== process.pid) invocationDaemonPids.add(pid);
}
return { code: typeof code === 'number' ? code : undefined, stdout, stderr };
}
/** The client names the repository by the path it found; that spelling of the temporary folder varies by platform. */
function expectNoDaemonRunning(result: IInvocationResult, next: string): void {
expect(result).toMatchObject({ code: 1, stdout: '' });
expect(result.stderr).toMatch(/^rush-client: No daemon is running for /);
expect(result.stderr).toContain(`${path.sep}${path.basename(folder)} (Rush ${Rush.version})${next}\n`);
expect(result.stderr.split('\n')).toHaveLength(2);
}
it(
'preserves native project-script output and exit code for --no-daemon',
async () => {
const native: IInvocationResult = await invokeAsync(false, false);
expect(native.code).toBe(7);
expect(await invokeAsync(true, true)).toEqual(native);
},
SLOW_TEST_TIMEOUT_MS
);
it(
'keeps unknown interactive scripts on the native path even when a daemon is running',
async () => {
const daemonPackage: { version: string } = require('@rushstack/rush-daemon/package.json');
host = await RushDaemonHost.startAsync({
repoRoot: folder,
rushVersion: Rush.version,
daemonVersion: daemonPackage.version
});
const native: IInvocationResult = await invokeAsync(false, false);
const client: IInvocationResult = await invokeAsync(true, true, true);
expect(client.code).toBe(native.code);
expect(client.stdout).toBe(native.stdout);
// RUSH_DAEMON=1 asked for the daemon, so the client says why it did not use it.
expect(client).toEqual({
...native,
stderr:
'rushx-client: the daemon does not run scripts in a terminal; using in-process Rush.\n' +
native.stderr
});
// rushx-client always uses legacy output, so an agent marker adds no line.
expect(await invokeAsync(true, false, true, undefined, { COPILOT_CLI: '1' })).toEqual(native);
},
SLOW_TEST_TIMEOUT_MS
);
it('says why a command runs in-process in agent mode, or when RUSH_DAEMON=1 asked for the daemon', async () => {
const agent: IInvocationResult = await invokeAsync(true, false, false, ['-q', 'list'], {
COPILOT_CLI: '1'
});
expect(agent.code).toBe(0);
expect(agent.stderr).toBe('rush-client: RUSH_DAEMON=0 turns the daemon off; using in-process Rush.\n');
// In-process Rush got the quiet flag, and no progress line was written.
expect(agent.stdout).toContain('sample');
expect(agent.stdout).not.toMatch(/Rush Multi-Project Build Tool|rushd/);
const legacy: IInvocationResult = await invokeAsync(true, false, false, ['-q', 'list']);
expect(legacy).toEqual({ ...agent, stderr: '' });
const requested: IInvocationResult = await invokeAsync(true, true, false, ['-q', '--debug', 'list']);
expect(requested.code).toBe(0);
expect(requested.stderr).toBe(
'rush-client: the daemon does not support "--debug"; using in-process Rush.\n'
);
// In-process Rush got both flags: --debug lists the plugins that Rush loads.
expect(requested.stdout).toMatch(/^Loaded rush plugin[^]*\nsample\n$/);
expect(requested.stdout).not.toContain('Rush Multi-Project Build Tool');
expect(await invokeAsync(true, true, false, ['--no-daemon', '-q', 'list'])).toEqual(legacy);
expect((await invokeAsync(true, false, false, ['list'])).stdout).toContain(
'Rush Multi-Project Build Tool'
);
}, 30000);
it('keeps the quiet flag for in-process Rush after the daemon could not run the command', async () => {
const unreachable: IInvocationResult = await invokeAsync(true, true, false, ['-q', 'list']);
expect(unreachable).toMatchObject({ code: 0, stdout: 'sample\n' });
expect(unreachable.stderr).toMatch(
/^rush-client: No ready daemon at .*; auto-start is disabled; using in-process Rush\.\n$/
);
const daemonPackage: { version: string } = require('@rushstack/rush-daemon/package.json');
host = await RushDaemonHost.startAsync({
repoRoot: folder,
rushVersion: Rush.version,
daemonVersion: daemonPackage.version
});
const sentBack: IInvocationResult = await invokeAsync(true, true, false, ['-q', 'list']);
expect(sentBack).toMatchObject({ code: 0, stdout: 'sample\n' });
expect(sentBack.stderr).toMatch(/^rush-client: .*; using in-process Rush\.\n$/);
}, 30000);
it('paints no progress line on a terminal for a command that runs in-process', async () => {
const entry: string = path.resolve(__dirname, '../../bin/rush-client');
const invokeOnTerminalAsync = async (environment: NodeJS.ProcessEnv): Promise<IInvocationResult> => {
const child: ChildProcess = spawn(
process.execPath,
[
'-e',
`Object.assign(process.stdout, { isTTY: true, columns: 80 }); process.argv = [process.execPath, ${JSON.stringify(entry)}, '-q', 'list']; require(${JSON.stringify(entry)});`
],
{
cwd: project,
env: {
...getTestProcessEnvironment(),
COPILOT_CLI: '1',
TERM: 'xterm',
...NON_CI_ENVIRONMENT,
...environment
},
stdio: ['ignore', 'pipe', 'pipe']
}
);
let stdout: string = '';
let stderr: string = '';
child.stdout!.on('data', (chunk: Buffer) => (stdout += chunk.toString()));
child.stderr!.on('data', (chunk: Buffer) => (stderr += chunk.toString()));
const closed: Promise<unknown[]> = once(child, 'close');
invocationClosures.push(closed);
const [code] = await closed;
return { code: typeof code === 'number' ? code : undefined, stdout, stderr };
};
for (const environment of [
{ RUSH_DAEMON: '0' },
{ RUSH_DAEMON: undefined },
{ CI: '1', RUSH_DAEMON: undefined }
]) {
const result: IInvocationResult = await invokeOnTerminalAsync(environment);
expect(result).toMatchObject({ code: 0, stdout: 'sample\n' });
expect(result.stderr).toContain('; using in-process Rush.');
}
// The early guess misses the escaped key and paints nothing; the line starts once routing chose the daemon.
const rushJsonPath: string = path.join(folder, 'rush.json');
const config: Record<string, unknown> = JSON.parse(fs.readFileSync(rushJsonPath, 'utf8'));
fs.writeFileSync(
rushJsonPath,
JSON.stringify({ ...config, daemon: { autoStart: false } }).replace(
'"daemon":{',
'"daemon":{"\\u0065nabled":true,'
)
);
const daemonPackage: { version: string } = require('@rushstack/rush-daemon/package.json');
host = await RushDaemonHost.startAsync({
repoRoot: folder,
rushVersion: Rush.version,
daemonVersion: daemonPackage.version
});
const routed: IInvocationResult = await invokeOnTerminalAsync({ RUSH_DAEMON: undefined });
expect(routed.code).toBe(0);
// Painted before the request was sent, so the line started when routing chose the daemon.
expect(routed.stdout).toContain('rush list · ');
expect(routed.stdout).toContain('connecting to rushd');
expect(routed.stdout).toMatch(/sample\n$/);
}, 30000);
it('starts idempotently and reports real readiness in CI without execution opt-in', async () => {
const daemonPackage: { version: string } = require('@rushstack/rush-daemon/package.json');
host = await RushDaemonHost.startAsync({
repoRoot: folder,
rushVersion: Rush.version,
daemonVersion: daemonPackage.version
});
for (const verb of ['start', 'start', 'status']) {
const result: IInvocationResult = await invokeAsync(true, false, false, ['daemon', verb]);
expect(result.code).toBe(0);
expect(result.stderr).toBe('');
const status: Record<string, unknown> = JSON.parse(result.stdout);
expect(status).toMatchObject({
state: 'ready',
socketPath: host.paths.socketPath,
daemonVersion: daemonPackage.version
});
expect(status.uptimeMs).toEqual(expect.any(Number));
expect(status.pid).toBe(process.pid);
expect(status.residentMemoryBytes).toEqual(expect.any(Number));
expect(status).not.toHaveProperty('warmProjects');
}
}, 15000);
it('status reports a daemon whose installation was removed, with rc 1', async () => {
const daemonPackage: { version: string } = require('@rushstack/rush-daemon/package.json');
host = await RushDaemonHost.startAsync({
repoRoot: folder,
rushVersion: Rush.version,
daemonVersion: daemonPackage.version,
checkInstallation: () => ({ change: 'removed', folder: '/snapshots/gone' })
});
const result: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'status']);
expect(result.code).toBe(1);
expect(JSON.parse(result.stdout)).toMatchObject({
state: 'installationChanged',
socketPath: host.paths.socketPath,
pid: process.pid,
installationChange: { change: 'removed', folder: '/snapshots/gone' }
});
expect(result.stderr).toBe(
"rush-client: The daemon's installation at /snapshots/gone was removed. " +
'The next command restarts the daemon, or run "rush-client daemon restart".\n'
);
}, 15000);
it('status never starts an absent daemon or falls back to command execution', async () => {
const result: IInvocationResult = await invokeAsync(true, true, false, ['daemon', 'status']);
expectNoDaemonRunning(result, AUTO_START_OFF);
expect(result.stderr).not.toContain('using in-process');
// What the next command does follows the resolved settings.
expectNoDaemonRunning(
await invokeAsync(true, true, false, ['daemon', 'status'], { RUSH_DAEMON_AUTO_START: '1' }),
NEXT_COMMAND_STARTS
);
expectNoDaemonRunning(await invokeAsync(true, false, false, ['daemon', 'status']), NOT_ENABLED);
const { paths } = getDaemonConnectionOptions(folder, Rush.version, {}, false);
expect(fs.existsSync(paths.lockfilePath)).toBe(false);
});
it('starts an absent daemon that survives the client and then shuts down when idle', async () => {
const rushJsonPath: string = path.join(folder, 'rush.json');
const config: Record<string, unknown> = JSON.parse(fs.readFileSync(rushJsonPath, 'utf8'));
fs.writeFileSync(
rushJsonPath,
JSON.stringify({
...config,
daemon: { enabled: false, autoStart: false, idleTimeoutSeconds: 2 }
})
);
const { paths } = getDaemonConnectionOptions(folder, Rush.version, {}, false);
try {
const result: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'start']);
expect(result.code).toBe(0);
expect(result.stderr).toBe('');
expect(JSON.parse(result.stdout)).toMatchObject({ state: 'ready', socketPath: paths.socketPath });
expect(fs.existsSync(paths.lockfilePath)).toBe(true);
} finally {
const deadline: number = Date.now() + 7000;
while (fs.existsSync(paths.lockfilePath) && Date.now() < deadline) await delayAsync(50);
expect(fs.existsSync(paths.lockfilePath)).toBe(false);
}
const stopped: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'status']);
expectNoDaemonRunning(stopped, NOT_ENABLED);
const log: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'logs']);
expect(log.code).toBe(0);
const isoTime: string = '\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d\\.\\d{3}Z';
const ready: RegExpMatchArray | null = log.stdout.match(
new RegExp(`^${isoTime} rushd ready at .+ \\(Rush ${Rush.version}, PID (\\d+)\\)$`, 'm')
);
expect(ready).not.toBeNull();
expect(log.stdout).toMatch(
new RegExp(`^${isoTime} rushd \\(PID ${ready![1]}\\) shutting down: idle for 2 s$`, 'm')
);
}, 15000);
it('status says that no daemon is running after daemon stop and after SIGTERM', async () => {
const { paths } = getDaemonConnectionOptions(folder, Rush.version, {}, false);
try {
const stopCases: string[] = process.platform === 'win32' ? ['daemon stop'] : ['daemon stop', 'SIGTERM'];
for (const stopWith of stopCases) {
const started: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'start']);
expect(started.code).toBe(0);
const { pid }: { pid: number } = JSON.parse(started.stdout);
expect(pid).not.toBe(process.pid);
if (stopWith === 'SIGTERM') {
// The daemon that this test just started shuts down in order on SIGTERM.
process.kill(pid, 'SIGTERM');
} else {
expect((await invokeAsync(true, false, false, ['daemon', 'stop'])).code).toBe(0);
}
await waitForTestProcessExitAsync(pid);
expect(fs.existsSync(paths.lockfilePath)).toBe(false);
expectNoDaemonRunning(
await invokeAsync(true, true, false, ['daemon', 'status'], { RUSH_DAEMON_AUTO_START: '1' }),
NEXT_COMMAND_STARTS
);
}
} finally {
const deadline: number = Date.now() + 7000;
while (fs.existsSync(paths.lockfilePath) && Date.now() < deadline) await delayAsync(50);
}
}, 30000);
(process.platform === 'win32' ? it.skip : it)(
'status keeps the refused-connection diagnostic for a socket that remains without its daemon',
async () => {
const { paths } = getDaemonConnectionOptions(folder, Rush.version, {}, false);
fs.mkdirSync(path.dirname(paths.lockfilePath), { recursive: true, mode: 0o700 });
const listener: ChildProcess = spawn(
process.execPath,
[
'-e',
`require('net').createServer().listen(${JSON.stringify(paths.socketPath)}, () => process.kill(process.pid, 'SIGKILL'))`
],
{ stdio: 'ignore' }
);
await once(listener, 'close');
try {
expect(fs.existsSync(paths.socketPath)).toBe(true);
const status: IInvocationResult = await invokeAsync(true, true, false, ['daemon', 'status']);
expect(status).toMatchObject({ code: 1, stdout: '' });
expect(status.stderr).toBe(`rush-client: Could not connect to daemon at ${paths.socketPath}.\n`);
} finally {
fs.rmSync(paths.socketPath, { force: true });
}
}
);
it('reads a saved launcher log without connecting or auto-starting', async () => {
fs.mkdirSync(path.dirname(logFilePath), { recursive: true, mode: 0o700 });
const contents: string = `${'startup output\n'.repeat(20000)}startup error\n`;
fs.writeFileSync(logFilePath, contents, { mode: 0o600 });
const result: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'logs']);
expect(result).toEqual({ code: 0, stdout: contents, stderr: '' });
expect(
fs.existsSync(getDaemonConnectionOptions(folder, Rush.version, {}, false).paths.lockfilePath)
).toBe(false);
});
it('returns an actionable missing-log error without creating a log or daemon', async () => {
const result: IInvocationResult = await invokeAsync(true, true, false, ['daemon', 'logs']);
expect(result.code).toBe(1);
expect(result.stdout).toBe('');
expect(result.stderr).toContain('No launcher log exists');
expect(result.stderr).toContain(logFilePath);
expect(fs.existsSync(logFilePath)).toBe(false);
});
it('accepts an empty launcher log and rejects extra follow arguments', async () => {
fs.mkdirSync(path.dirname(logFilePath), { recursive: true, mode: 0o700 });
fs.writeFileSync(logFilePath, '', { mode: 0o600 });
expect(await invokeAsync(true, false, false, ['daemon', 'logs'])).toEqual({
code: 0,
stdout: '',
stderr: ''
});
expect((await invokeAsync(true, false, false, ['daemon', 'logs', '--follow', 'extra'])).code).toBe(1);
});
it('treats stop as idempotent and restart as start when no daemon is running', async () => {
const { paths } = getDaemonConnectionOptions(folder, Rush.version, {}, false);
for (const args of [
['daemon', 'stop'],
['daemon', 'stop', '--force']
]) {
const result: IInvocationResult = await invokeAsync(true, false, false, args);
expect(result).toMatchObject({ code: 0, stderr: '' });
expect(JSON.parse(result.stdout)).toEqual({
state: 'notRunning',
socketPath: paths.socketPath,
...(args[2] ? { removedPaths: [] } : {})
});
}
try {
const restarted: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'restart']);
expect(restarted.stderr).toBe('');
expect(restarted.code).toBe(0);
expect(JSON.parse(restarted.stdout)).toMatchObject({ state: 'ready', socketPath: paths.socketPath });
const stopped: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'stop']);
expect(stopped.code).toBe(0);
expect(JSON.parse(stopped.stdout)).toMatchObject({ state: 'shutdownAccepted' });
} finally {
const deadline: number = Date.now() + 7000;
while (fs.existsSync(paths.lockfilePath) && Date.now() < deadline) await delayAsync(50);
expect(fs.existsSync(paths.lockfilePath)).toBe(false);
}
}, 30000);
it('stop --force clears an abandoned startup reservation next to a running daemon', async () => {
const { paths } = getDaemonConnectionOptions(folder, Rush.version, {}, false);
const reservation: string = `${paths.lockfilePath}.starting`;
try {
expect((await invokeAsync(true, false, false, ['daemon', 'start'])).code).toBe(0);
fs.writeFileSync(reservation, 'abandoned');
const result: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'stop', '--force']);
expect(result).toMatchObject({ code: 0, stderr: '' });
expect(JSON.parse(result.stdout)).toEqual({
state: 'shutdownAccepted',
socketPath: paths.socketPath,
cancelledRequests: 0,
removedPaths: [reservation]
});
expect(fs.existsSync(reservation)).toBe(false);
expect(fs.existsSync(paths.lockfilePath)).toBe(false);
} finally {
const deadline: number = Date.now() + 7000;
while (fs.existsSync(paths.lockfilePath) && Date.now() < deadline) await delayAsync(50);
}
}, 30000);
it('stop resolves a startup reservation next to a ready daemon so that a later start launches', async () => {
const { paths } = getDaemonConnectionOptions(folder, Rush.version, {}, false);
const reservation: string = `${paths.lockfilePath}.starting`;
try {
const started: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'start']);
expect(started.code).toBe(0);
const { pid }: { pid: number } = JSON.parse(started.stdout);
fs.writeFileSync(reservation, 'abandoned');
const stopped: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'stop']);
expect(stopped).toMatchObject({ code: 0, stderr: '' });
expect(JSON.parse(stopped.stdout)).toEqual({
state: 'shutdownAccepted',
socketPath: paths.socketPath,
cancelledRequests: 0
});
expect(fs.existsSync(reservation)).toBe(false);
// The daemon writes the line before it acknowledges the request.
expect(fs.readFileSync(logFilePath, 'utf8')).toContain(
`rushd (PID ${pid}) shutting down: requested by a client ("rush-client daemon stop" or "daemon restart")\n`
);
const deadline: number = Date.now() + 7000;
while (fs.existsSync(paths.lockfilePath) && Date.now() < deadline) await delayAsync(50);
const restarted: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'start']);
expect(restarted).toMatchObject({ code: 0, stderr: '' });
expect(JSON.parse(restarted.stdout).pid).not.toBe(pid);
expect((await invokeAsync(true, false, false, ['daemon', 'stop'])).code).toBe(0);
} finally {
const deadline: number = Date.now() + 7000;
while (fs.existsSync(paths.lockfilePath) && Date.now() < deadline) await delayAsync(50);
}
}, 30000);
it('reports a startup reservation next to a ready daemon, and restart resolves it', async () => {
const { paths } = getDaemonConnectionOptions(folder, Rush.version, {}, false);
const reservation: string = `${paths.lockfilePath}.starting`;
try {
const started: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'start']);
expect(started.code).toBe(0);
const { pid }: { pid: number } = JSON.parse(started.stdout);
fs.writeFileSync(reservation, 'abandoned');
const status: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'status']);
expect(status).toMatchObject({ code: 0, stderr: '' });
expect(JSON.parse(status.stdout)).toMatchObject({
state: 'ready',
pid,
startupReservation: { path: reservation, helperState: 'unknown' }
});
// Status only reports the reservation.
expect(fs.readFileSync(reservation, 'utf8')).toBe('abandoned');
const restarted: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'restart']);
expect(restarted).toMatchObject({ code: 0, stderr: '' });
const successor: Record<string, unknown> = JSON.parse(restarted.stdout);
expect(successor).toMatchObject({ state: 'ready', pid: expect.any(Number) });
expect(successor.pid).not.toBe(pid);
expect(successor).not.toHaveProperty('startupReservation');
expect(fs.existsSync(reservation)).toBe(false);
expect((await invokeAsync(true, false, false, ['daemon', 'stop'])).code).toBe(0);
} finally {
const deadline: number = Date.now() + 7000;
while (fs.existsSync(paths.lockfilePath) && Date.now() < deadline) await delayAsync(50);
}
}, 30000);
it.each(['exited', 'running'])(
'status explains a startup reservation (helper %s) while no daemon is ready',
async (helperState) => {
const { paths } = getDaemonConnectionOptions(folder, Rush.version, {}, false);
const reservation: string = `${paths.lockfilePath}.starting`;
fs.mkdirSync(path.dirname(paths.lockfilePath), { recursive: true, mode: 0o700 });
// A startup helper that runs until its stdin ends, without ever starting a daemon.
const helper: ChildProcess = spawn(process.execPath, ['-e', 'process.stdin.resume()'], {
stdio: ['pipe', 'ignore', 'ignore']
});
const helperClosed: Promise<unknown[]> = once(helper, 'close');
const helperPid: number = helper.pid!;
if (helperState === 'exited') {
helper.stdin!.end();
await helperClosed;
}
const helperStartedAt: Date = new Date();
fs.writeFileSync(
reservation,
JSON.stringify({ token: 'fixture', helperPid, helperStartedAt: helperStartedAt.toISOString() })
);
const relaunchAfter: string = new Date(helperStartedAt.getTime() + 15000).toISOString();
try {
const status: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'status']);
expect(status).toMatchObject({ code: 1, stdout: '' });
expect(status.stderr).toContain('Could not connect to daemon');
expect(status.stderr).toContain(
helperState === 'exited'
? `its startup helper (PID ${helperPid}) exited before the daemon became ready. A command that starts the daemon after ${relaunchAfter} takes the reservation over and launches the daemon again, provided that nothing listens at ${paths.socketPath} then. "rush-client daemon logs" may show why the daemon did not become ready.`
: `A daemon is starting: its startup helper (PID ${helperPid}) is still waiting for it to become ready; retry shortly.`
);
let onStopWaits: () => void = () => undefined;
const stopWaits: Promise<void> = new Promise((resolve) => (onStopWaits = resolve));
const stopping: Promise<IInvocationResult> = invokeAsync(
true,
false,
false,
['daemon', 'stop'],
{},
(stderr: string) => {
if (stderr.includes('stop waits up to')) onStopWaits();
}
);
if (helperState === 'running') {
// Stop waits while the helper runs, and reports the reservation once the helper exits without a daemon.
await Promise.race([stopWaits, stopping]);
helper.stdin!.end();
await helperClosed;
}
const stopped: IInvocationResult = await stopping;
expect(stopped.code).toBe(0);
expect(stopped.stderr).toEqual(
helperState === 'exited'
? ''
: expect.stringMatching(
new RegExp(
`^rush-client: The daemon is not ready yet\\. Its startup helper \\(PID ${helperPid}\\) is still waiting for the daemon, so stop waits up to \\d+ s for it to become ready and then stops it\\.\\n$`
)
)
);
expect(JSON.parse(stopped.stdout)).toEqual({
state: 'notRunning',
socketPath: paths.socketPath,
startupReservation: { path: reservation, helperPid, helperState: 'exited', relaunchAfter }
});
const reset: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'stop', '--force']);
expect(reset).toMatchObject({ code: 0, stderr: '' });
expect(JSON.parse(reset.stdout)).toEqual({
state: 'reset',
socketPath: paths.socketPath,
removedPaths: [reservation]
});
} finally {
if (!helper.stdin!.writableEnded) helper.stdin!.end();
await helperClosed;
}
},
30000
);
it('stop waits for a daemon that is still starting and then stops it', async () => {
const { paths } = getDaemonConnectionOptions(folder, Rush.version, {}, false);
const reservation: string = `${paths.lockfilePath}.starting`;
fs.mkdirSync(path.dirname(paths.lockfilePath), { recursive: true, mode: 0o700 });
// This process stands in for the startup helper: it starts the daemon below while stop waits.
fs.writeFileSync(
reservation,
JSON.stringify({ token: 'fixture', helperPid: process.pid, helperStartedAt: new Date().toISOString() })
);
try {
let onStopWaits: () => void = () => undefined;
const stopWaits: Promise<void> = new Promise((resolve) => (onStopWaits = resolve));
const stopping: Promise<IInvocationResult> = invokeAsync(
true,
false,
false,
['daemon', 'stop'],
{},
(stderr: string) => {
if (stderr.includes('stop waits up to')) onStopWaits();
}
);
await Promise.race([stopWaits, stopping]);
const daemonPackage: { version: string } = require('@rushstack/rush-daemon/package.json');
host = await RushDaemonHost.startAsync({
repoRoot: folder,
rushVersion: Rush.version,
daemonVersion: daemonPackage.version
});
const stopped: IInvocationResult = await stopping;
expect(stopped.code).toBe(0);
expect(stopped.stderr).toMatch(
new RegExp(
`^rush-client: The daemon is not ready yet\\. Its startup helper \\(PID ${process.pid}\\) is still waiting for the daemon, so stop waits up to \\d+ s for it to become ready and then stops it\\.\\n$`
)
);
// Stop resolved the reservation next to the ready daemon before it shut that daemon down.
expect(JSON.parse(stopped.stdout)).toEqual({
state: 'shutdownAccepted',
socketPath: paths.socketPath,
cancelledRequests: 0
});
expect(fs.existsSync(reservation)).toBe(false);
} finally {
const deadline: number = Date.now() + 7000;
while (fs.existsSync(paths.lockfilePath) && Date.now() < deadline) await delayAsync(50);
expect(fs.existsSync(paths.lockfilePath)).toBe(false);
}
}, 30000);
it('status names a recorded daemon that exited without shutting down', async () => {
const { paths } = getDaemonConnectionOptions(folder, Rush.version, {}, false);
fs.mkdirSync(path.dirname(paths.lockfilePath), { recursive: true, mode: 0o700 });
const exited: ChildProcess = spawn(process.execPath, ['-e', ''], { stdio: 'ignore' });
await once(exited, 'close');
const record: IDaemonLockfile = {
pid: exited.pid!,
protocolVersion: { major: 0, minor: 11 },
startedAt: new Date().toISOString(),
socketPath: paths.socketPath
};
try {
fs.writeFileSync(paths.lockfilePath, JSON.stringify(record));
const status: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'status']);
expect(status).toMatchObject({ code: 1, stdout: '' });
expect(status.stderr).toContain(
`Could not connect to daemon at ${paths.socketPath}. rushd (PID ${record.pid}) exited without shutting down; "rush-client daemon logs" may show why.`
);
// A record for another endpoint says nothing about the daemon at this one.
fs.writeFileSync(
paths.lockfilePath,
JSON.stringify({ ...record, socketPath: `${paths.socketPath}.x` })
);
const other: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'status']);
expect(other).toMatchObject({ code: 1, stdout: '' });
expect(other.stderr).toContain('Could not connect to daemon');
expect(other.stderr).not.toContain('exited without shutting down');
} finally {
fs.rmSync(paths.lockfilePath, { force: true });
}
});
it('status still names a daemon that exited without shutting down after a client reclaimed it', async () => {
const { paths } = getDaemonConnectionOptions(folder, Rush.version, {}, false);
fs.mkdirSync(path.dirname(paths.lockfilePath), { recursive: true, mode: 0o700 });
async function reclaimExitedDaemonAsync(): Promise<string> {
const exited: ChildProcess = spawn(process.execPath, ['-e', ''], { stdio: 'ignore' });
await once(exited, 'close');
const record: IDaemonLockfile = {
pid: exited.pid!,
protocolVersion: { major: 0, minor: 11 },
startedAt: new Date().toISOString(),
socketPath: paths.socketPath
};
fs.writeFileSync(paths.lockfilePath, JSON.stringify(record));
// As the client whose command the daemon ran does, or Rush in-process; this removes the record.
await reclaimCrashedDaemonAsync(paths);
expect(fs.existsSync(paths.lockfilePath)).toBe(false);
return ` The last daemon, rushd (PID ${record.pid}), exited without shutting down; "rush-client daemon logs" may show why.`;
}
const exitedWithoutShutdown: string = await reclaimExitedDaemonAsync();
expectNoDaemonRunning(
await invokeAsync(true, true, false, ['daemon', 'status'], { RUSH_DAEMON_AUTO_START: '1' }),
NEXT_COMMAND_STARTS + exitedWithoutShutdown
);
expectNoDaemonRunning(
await invokeAsync(true, true, false, ['daemon', 'status']),
AUTO_START_OFF + exitedWithoutShutdown
);
expectNoDaemonRunning(
await invokeAsync(true, false, false, ['daemon', 'status']),
NOT_ENABLED + exitedWithoutShutdown
);
// A reset clears the report, as it removed the record before a client reclaimed the daemon.
const reset: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'stop', '--force']);
expect(reset).toMatchObject({ code: 0, stderr: '' });
expect(JSON.parse(reset.stdout)).toMatchObject({ state: 'notRunning', removedPaths: [] });
expectNoDaemonRunning(await invokeAsync(true, false, false, ['daemon', 'status']), NOT_ENABLED);
// So does a daemon that becomes ready, even when it is then stopped in order.
const exitedAgain: string = await reclaimExitedDaemonAsync();
expectNoDaemonRunning(
await invokeAsync(true, false, false, ['daemon', 'status']),
NOT_ENABLED + exitedAgain
);
const started: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'start']);
expect(started.code).toBe(0);
const { pid }: { pid: number } = JSON.parse(started.stdout);
expect((await invokeAsync(true, false, false, ['daemon', 'stop'])).code).toBe(0);
await waitForTestProcessExitAsync(pid);
expectNoDaemonRunning(
await invokeAsync(true, true, false, ['daemon', 'status'], { RUSH_DAEMON_AUTO_START: '1' }),
NEXT_COMMAND_STARTS
);
}, 30000);
(process.platform === 'win32' ? it.skip : it)(
'stop --force removes stale artifacts left by a killed daemon',
async () => {
const { paths } = getDaemonConnectionOptions(folder, Rush.version, {}, false);
fs.mkdirSync(path.dirname(paths.lockfilePath), { recursive: true, mode: 0o700 });
const listener: ChildProcess = spawn(
process.execPath,
[
'-e',
`require('net').createServer().listen(${JSON.stringify(paths.socketPath)}, () => process.kill(process.pid, 'SIGKILL'))`
],
{ stdio: 'ignore' }
);
await once(listener, 'close');
fs.writeFileSync(paths.lockfilePath, 'garbage{');
const result: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'stop', '--force']);
expect(result).toMatchObject({ code: 0, stderr: '' });
expect(JSON.parse(result.stdout)).toEqual({
state: 'reset',
socketPath: paths.socketPath,
removedPaths: [paths.lockfilePath, paths.socketPath]
});
expect(fs.existsSync(paths.lockfilePath)).toBe(false);
expect(fs.existsSync(paths.socketPath)).toBe(false);
}
);
it.each([false, true])(
'restarts after ownership release and stops the successor (embedded: %s)',
async (embedded) => {
const rushJsonPath: string = path.join(folder, 'rush.json');
const config: Record<string, unknown> = JSON.parse(fs.readFileSync(rushJsonPath, 'utf8'));
fs.writeFileSync(
rushJsonPath,
JSON.stringify({
...config,
daemon: { enabled: false, autoStart: false, idleTimeoutSeconds: 5 }
})
);
const { paths } = getDaemonConnectionOptions(folder, Rush.version, {}, false);
try {
if (embedded) {
const daemonPackage: { version: string } = require('@rushstack/rush-daemon/package.json');
host = await RushDaemonHost.startAsync({
repoRoot: folder,
rushVersion: Rush.version,
daemonVersion: daemonPackage.version
});
} else {
const started: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'start']);
expect(started.code).toBe(0);
}
const originalLock: { startedAt: string } = JSON.parse(fs.readFileSync(paths.lockfilePath, 'utf8'));
const restarted: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'restart']);
expect(restarted.stderr).toBe('');
expect(restarted.code).toBe(0);
expect(JSON.parse(restarted.stdout)).toMatchObject({
state: 'ready',
pid: expect.any(Number),
residentMemoryBytes: expect.any(Number)
});
const successorLock: { startedAt: string } = JSON.parse(fs.readFileSync(paths.lockfilePath, 'utf8'));
expect(successorLock.startedAt).not.toBe(originalLock.startedAt);
await host?.closeAsync();
expect(fs.existsSync(paths.lockfilePath)).toBe(true);
const stopped: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'stop']);
expect(stopped.code).toBe(0);
expect(JSON.parse(stopped.stdout)).toMatchObject({ state: 'shutdownAccepted' });
} finally {
const deadline: number = Date.now() + 7000;
while (fs.existsSync(paths.lockfilePath) && Date.now() < deadline) await delayAsync(50);
expect(fs.existsSync(paths.lockfilePath)).toBe(false);
}
},
30000
);
it('bounds restart after failed workspace cleanup without deleting live ownership', async () => {
const errors: Error[] = [];
const cleanupFailure: Error = new Error('workspace cleanup failed');
const { value: failedHost, listener } = await captureTestDaemonListenerAsync(() =>
RushDaemonHost.startAsync({
repoRoot: folder,
rushVersion: Rush.version,
daemonVersion: 'cleanup-failure-test',
onError: (error) => {
errors.push(error);
},
createWorkspaceSessionAsync: async (sessionOptions) =>
WorkspaceSession.createAsync({
...sessionOptions,
createComponentsAsync: async () => ({
[Symbol.asyncDispose]: async () => {
throw cleanupFailure;
}
})
})
})
);
let client: DaemonClient | undefined;
try {
const originalRecord: string = fs.readFileSync(failedHost.paths.lockfilePath, 'utf8');
const previousDaemon = readDaemonLockfile(failedHost.paths.lockfilePath)!;
client = await DaemonClient.connectAsync({ socketPath: failedHost.paths.socketPath });
await client.shutdownAsync();
await failedHost.closed;
await expect(failedHost.closeAsync()).rejects.toThrow('workspace cleanup failed');
expect(errors).toHaveLength(1);
await expect(
connectOrStartDaemonAsync({
...getDaemonConnectionOptions(folder, Rush.version, {}, true),
previousDaemon,
startupTimeoutMs: 40
})
).rejects.toThrow('previous daemon still owns');
expect(fs.readFileSync(failedHost.paths.lockfilePath, 'utf8')).toBe(originalRecord);
if (process.platform !== 'win32') expect(fs.existsSync(failedHost.paths.socketPath)).toBe(true);
} finally {
const cleanup = await Promise.allSettled([client?.closeAsync(), failedHost.closeAsync()]);
try {
expect(cleanup).toEqual([
{ status: 'fulfilled', value: undefined },
{ status: 'rejected', reason: cleanupFailure }
]);
} finally {
// The only injected failure owns no live resources; release the real fixture listener last.
await listener.closeAsync();
}
}
expect(fs.existsSync(failedHost.paths.lockfilePath)).toBe(false);
if (process.platform !== 'win32') expect(fs.existsSync(failedHost.paths.socketPath)).toBe(false);
});
it('rejects extra management arguments without silently ignoring them', async () => {
const result: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'status', 'extra']);
expect(result.code).toBe(1);
expect(result.stderr).toContain('Usage: rush-client daemon start|status');
});
it('does not guess a daemon launcher for a different selected Rush version', async () => {
const rushJsonPath: string = path.join(folder, 'rush.json');
const config: Record<string, unknown> = JSON.parse(fs.readFileSync(rushJsonPath, 'utf8'));
fs.writeFileSync(rushJsonPath, JSON.stringify({ ...config, rushVersion: '0.0.0' }));
let registryRequests: number = 0;
const registry = http.createServer((request, response) => {
registryRequests++;
request.resume();
response.writeHead(404, { 'content-type': 'application/json', connection: 'close' });
response.end(JSON.stringify({ error: 'no supported release' }));
});
await new Promise<void>((resolve) => registry.listen(0, '127.0.0.1', resolve));
try {
const address = registry.address();
if (!address || typeof address === 'string') throw new Error('Expected a local registry address.');
const registryUrl: string = `http://127.0.0.1:${address.port}`;
// Native Rush subprocesses discard NPM_CONFIG_* overrides.
fs.writeFileSync(
path.join(folder, 'common/config/rush/.npmrc'),
`registry=${registryUrl}\ncache=${path.join(folder, 'npm-cache')}\naudit=false\nfund=false\n`
);
const home: string = path.join(folder, 'home');
fs.mkdirSync(home);
fs.writeFileSync(path.join(home, '.npmrc'), '');
const result: IInvocationResult = await invokeAsync(true, false, false, ['daemon', 'start'], {
HOME: home,
USERPROFILE: home,
RUSH_GLOBAL_FOLDER: path.join(folder, 'global'),
// Use Node's npm rather than a user-specific wrapper that depends on the real HOME.
PATH: [path.dirname(process.execPath), process.env.PATH].filter(Boolean).join(path.delimiter)