-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
1044 lines (963 loc) · 30.6 KB
/
Copy pathutils.ts
File metadata and controls
1044 lines (963 loc) · 30.6 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
import assert from 'node:assert';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import actionsCore from '@actions/core';
//eslint-disable-next-line n/no-unpublished-import
import { AGENTS, detect, getCommand, serializeCommand } from '@antfu/ni';
import { getPackages } from '@manypkg/get-packages';
import { type Options as ExecaOptions, execaCommand } from 'execa';
import yaml from 'yaml';
import type {
Agent,
EnvironmentData,
Overrides,
RepoOptions,
RunOptions,
Stack,
Task,
} from './types';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const isGitHubActions = !!process.env.GITHUB_ACTIONS;
const STACK_WORKSPACE_DIR: Record<Stack, string> = {
rsbuild: 'rsbuild',
rspack: 'rspack',
rstest: 'rstest',
rslib: 'rslib',
rsdoctor: 'rsdoctor',
rspress: 'rspress',
};
const STACK_DEFAULT_REPO: Record<Stack, string> = {
rsbuild: 'web-infra-dev/rsbuild',
rspack: 'web-infra-dev/rspack',
rstest: 'web-infra-dev/rstest',
rslib: 'web-infra-dev/rslib',
rsdoctor: 'web-infra-dev/rsdoctor',
rspress: 'web-infra-dev/rspress',
};
let activeStack: Stack = 'rsbuild';
let stackPath: string;
let workspaceRoot: string;
let cwd: string;
let env: NodeJS.ProcessEnv;
const monorepoPackagesCache: Partial<
Record<
'rsbuild' | 'rstest' | 'rslib' | 'rsdoctor' | 'rspress',
{ name: string; directory: string }[]
>
> = {};
interface RspackPackageInfo {
name: string;
directory: string;
}
interface RspackPackageData {
npm: RspackPackageInfo[];
binding: RspackPackageInfo[];
packages: RspackPackageInfo[];
}
let rspackPackageData: RspackPackageData | null = null;
export function cd(dir: string) {
cwd = path.resolve(cwd, dir);
}
export async function $(literals: TemplateStringsArray, ...values: unknown[]) {
const cmd = literals.reduce(
(result, current, i) =>
result + current + (values?.[i] != null ? `${values[i]}` : ''),
'',
);
const start = Date.now();
if (isGitHubActions) {
actionsCore.startGroup(`${cwd} $> ${cmd}`);
} else {
console.log(`${cwd} $> ${cmd}`);
}
const proc = execaCommand(cmd, {
env,
stdio: 'pipe',
cwd,
reject: false,
});
proc.stdin?.pipe(process.stdin);
proc.stdout?.pipe(process.stdout);
proc.stderr?.pipe(process.stderr);
const result = await proc;
if (result.failed) {
const errorResult = result as unknown as {
shortMessage?: string;
message?: string;
};
throw new Error(
errorResult.shortMessage ?? errorResult.message ?? 'Command failed',
);
}
if (isGitHubActions) {
actionsCore.endGroup();
const cost = Math.ceil((Date.now() - start) / 1000);
console.log(`Cost for \`${cmd}\`: ${cost} s`);
}
return result.stdout;
}
export const execa = async (cmd: string, options?: ExecaOptions) => {
const start = Date.now();
if (isGitHubActions) {
actionsCore.startGroup(`${cwd} $> ${cmd}`);
} else {
console.log(`${cwd} $> ${cmd}`);
}
const proc = execaCommand(cmd, {
env,
cwd,
stdio: 'pipe',
...options,
});
proc.stdin?.pipe(process.stdin);
proc.stdout?.pipe(process.stdout);
proc.stderr?.pipe(process.stderr);
const result = await proc;
if (isGitHubActions) {
actionsCore.endGroup();
const cost = Math.ceil((Date.now() - start) / 1000);
console.log(`Cost for \`${cmd}\`: ${cost} s`);
}
return result.stdout;
};
export async function setupEnvironment(stack: Stack): Promise<EnvironmentData> {
// @ts-expect-error import.meta
const root = dirnameFrom(import.meta.url);
workspaceRoot = path.resolve(root, 'workspace');
stackPath = path.resolve(workspaceRoot, STACK_WORKSPACE_DIR[stack]);
activeStack = stack;
cwd = process.cwd();
env = {
...process.env,
CI: 'true',
TURBO_FORCE: 'true', // disable turbo caching, ecosystem-ci modifies things and we don't want replays
YARN_ENABLE_IMMUTABLE_INSTALLS: 'false', // to avoid errors with mutated lockfile due to overrides
NODE_OPTIONS: '--max-old-space-size=6144', // GITHUB CI has 7GB max, stay below
ECOSYSTEM_CI: 'true', // flag for tests, can be used to conditionally skip irrelevant tests.
};
initWorkspace(workspaceRoot);
fs.mkdirSync(stackPath, { recursive: true });
if (stack === 'rspack') {
rspackPackageData = null;
}
const data: EnvironmentData = {
stack,
root,
workspace: workspaceRoot,
stackPath,
projectPath: stackPath,
cwd,
env,
};
if (stack === 'rsbuild') {
data.rsbuildPath = stackPath;
} else if (stack === 'rspack') {
data.rspackPath = stackPath;
} else if (stack === 'rstest') {
data.rstestPath = stackPath;
} else if (stack === 'rslib') {
data.rslibPath = stackPath;
} else if (stack === 'rsdoctor') {
data.rsdoctorPath = stackPath;
} else if (stack === 'rspress') {
data.rspressPath = stackPath;
}
return data;
}
export function getDefaultRepository(stack: Stack) {
return STACK_DEFAULT_REPO[stack];
}
function initWorkspace(workspace: string) {
if (!fs.existsSync(workspace)) {
fs.mkdirSync(workspace, { recursive: true });
}
const eslintrc = path.join(workspace, '.eslintrc.json');
if (!fs.existsSync(eslintrc)) {
fs.writeFileSync(eslintrc, '{"root":true}\n', 'utf-8');
}
const editorconfig = path.join(workspace, '.editorconfig');
if (!fs.existsSync(editorconfig)) {
fs.writeFileSync(editorconfig, 'root = true\n', 'utf-8');
}
}
export async function setupRepo(options: RepoOptions) {
if (options.branch == null) {
options.branch = 'main';
}
if (options.shallow == null) {
options.shallow = true;
}
let { repo } = options;
const { commit, branch, tag, dir, shallow } = options;
if (!dir) {
throw new Error('setupRepo must be called with options.dir');
}
if (!repo.includes(':')) {
repo = `https://github.com/${repo}.git`;
}
let needClone = true;
if (fs.existsSync(dir)) {
const _cwd = cwd;
cd(dir);
let currentClonedRepo: string | undefined;
try {
currentClonedRepo = await $`git ls-remote --get-url`;
} catch {
// when not a git repo
}
cd(_cwd);
if (repo === currentClonedRepo) {
needClone = false;
} else {
fs.rmSync(dir, { recursive: true, force: true });
}
}
if (needClone) {
await $`git -c advice.detachedHead=false clone ${
shallow ? '--depth=1 --no-tags' : ''
} --branch ${tag || branch} ${repo} ${dir}`;
}
cd(dir);
await $`git clean -fdxq`;
await $`git fetch ${shallow ? '--depth=1 --no-tags' : '--tags'} origin ${
tag ? `tag ${tag}` : `${commit || branch}`
}`;
if (shallow) {
await $`git -c advice.detachedHead=false checkout ${
tag ? `tags/${tag}` : `${commit || branch}`
}`;
} else {
await $`git checkout ${branch}`;
await $`git merge FETCH_HEAD`;
if (tag || commit) {
await $`git reset --hard ${tag || commit}`;
}
}
await $`git log -1 --format='%H'`;
}
function toCommand(
task: Task | Task[] | void,
agent: Agent,
): ((scripts: any) => Promise<any>) | void {
return async (scripts: any) => {
const tasks = Array.isArray(task) ? task : [task];
for (const task of tasks) {
if (task == null || task === '') {
continue;
}
if (typeof task === 'string') {
const taskParts = task.trim().split(/\s+/);
const scriptOrBin = taskParts[0];
if (scripts?.[scriptOrBin] != null) {
// `@antfu/ni` ≥ 0.21 quotes any arg containing whitespace, so we
// must split multi-word tasks (e.g. `test -u`) ourselves and pass
// each token as a separate arg before serializing.
const runTaskWithAgent = serializeCommand(
getCommand(agent, 'run', taskParts),
);
await $`${runTaskWithAgent}`;
} else {
await $`${task}`;
}
} else if (typeof task === 'function') {
await task();
} else {
throw new Error(
`invalid task, expected string or function but got ${typeof task}: ${task}`,
);
}
}
};
}
async function getMonorepoPackages(
stack: 'rsbuild' | 'rstest' | 'rslib' | 'rsdoctor' | 'rspress',
) {
const cached = monorepoPackagesCache[stack];
if (cached) {
return cached;
}
const packages = await getPackages(stackPath);
const packageList = packages.packages.flatMap((pkg) => {
const { name, private: isPrivate } = pkg.packageJson;
if (!name || isPrivate) {
return [];
}
return [
{
name,
directory: pkg.dir,
},
];
});
monorepoPackagesCache[stack] = packageList;
return packageList;
}
async function getRspackPackageData(): Promise<RspackPackageData> {
if (rspackPackageData) {
return rspackPackageData;
}
const {
default: { npm, binding, packages },
} = await import('./rspack-package.json');
const optionalKey = `${process.platform}-${process.arch}` as
| 'darwin-arm64'
| 'darwin-x64'
| 'linux-x64'
| 'win32-x64';
assert(
Object.keys(npm).includes(optionalKey),
`${optionalKey} is not supported`,
);
const normalize = (pkg: RspackPackageInfo) => ({
name: pkg.name,
directory: path.join(stackPath, pkg.directory),
});
rspackPackageData = {
npm: npm[
optionalKey as 'darwin-arm64' | 'darwin-x64' | 'linux-x64' | 'win32-x64'
].map(normalize),
binding: binding.map(normalize),
packages: packages.map(normalize),
};
return rspackPackageData;
}
export async function runInRepo(options: RunOptions & RepoOptions) {
if (options.verify == null) {
options.verify = true;
}
if (options.skipGit == null) {
options.skipGit = false;
}
if (options.branch == null) {
options.branch = 'main';
}
const {
build,
test,
repo,
branch,
tag,
commit,
skipGit,
verify,
beforeInstall,
afterInstall,
beforeBuild,
beforeTest,
} = options;
const dir = path.resolve(
options.workspace,
options.dir || repo.substring(repo.lastIndexOf('/') + 1),
);
if (!skipGit) {
await setupRepo({
repo,
dir,
branch: options.suiteBranch ?? branch,
tag: options.suiteTag ?? tag,
commit: options.suiteCommit ?? commit,
});
} else {
cd(dir);
}
const workspaceFile = path.resolve(__dirname, 'pnpm-workspace.yaml');
const tempWorkspaceFile = path.resolve(__dirname, '_pnpm-workspace.yaml');
const isFileNotFoundError = (error: unknown) =>
Boolean(
error &&
typeof error === 'object' &&
'code' in error &&
(error as NodeJS.ErrnoException).code === 'ENOENT',
);
let workspaceRenamed = false;
// weird, is the pnpm-workspace.yaml exists in the root dir, some package installation will fail.
// e.g. `pnpm test --stack rsbuild plugins`
try {
await fs.promises.rename(workspaceFile, tempWorkspaceFile);
workspaceRenamed = true;
} catch (error) {
if (!isFileNotFoundError(error)) {
throw error;
}
}
const runWorkflow = async () => {
if (options.agent == null) {
const detectedAgent = await detect({ cwd: dir, autoInstall: false });
if (detectedAgent == null) {
throw new Error(`Failed to detect packagemanager in ${dir}`);
}
options.agent = detectedAgent;
}
if (!AGENTS.includes(options.agent)) {
throw new Error(
`Invalid agent ${options.agent}. Allowed values: ${AGENTS.join(', ')}`,
);
}
const agent = options.agent;
const beforeInstallCommand = toCommand(beforeInstall, agent);
const afterInstallCommand = toCommand(afterInstall, agent);
const beforeBuildCommand = toCommand(beforeBuild, agent);
const beforeTestCommand = toCommand(beforeTest, agent);
const buildCommand = toCommand(build, agent);
const testCommand = toCommand(test, agent);
const pkgFile = path.join(dir, 'package.json');
const pkg = JSON.parse(await fs.promises.readFile(pkgFile, 'utf-8'));
if (verify && test) {
const frozenInstall = serializeCommand(getCommand(agent, 'frozen'));
await $`${frozenInstall}`;
await beforeBuildCommand?.(pkg.scripts);
await buildCommand?.(pkg.scripts);
await beforeTestCommand?.(pkg.scripts);
await testCommand?.(pkg.scripts);
}
const overrides: Overrides = { ...(options.overrides || {}) };
if (
activeStack === 'rsbuild' ||
activeStack === 'rstest' ||
activeStack === 'rslib' ||
activeStack === 'rsdoctor' ||
activeStack === 'rspress'
) {
const packages = await getMonorepoPackages(activeStack);
if (options.release) {
for (const pkgInfo of packages) {
if (
overrides[pkgInfo.name] &&
overrides[pkgInfo.name] !== options.release
) {
throw new Error(
`conflicting overrides[${pkgInfo.name}]=${overrides[pkgInfo.name]} and --release=${options.release} config. Use either one or the other`,
);
}
overrides[pkgInfo.name] = options.release;
}
} else {
for (const pkgInfo of packages) {
overrides[pkgInfo.name] ||= pkgInfo.directory;
}
}
await applyPackageOverrides({
dir,
pkg,
overrides,
agent,
beforeInstallCommand,
installArgs: {
pnpm: [
'--prefer-frozen-lockfile',
'--prefer-offline',
'--strict-peer-dependencies',
'false',
],
},
devDependencyStrategy: 'local',
});
} else {
const { npm, binding, packages } = await getRspackPackageData();
const packageList = [
...(options.release ? [] : npm),
...binding,
...packages,
];
if (options.release) {
for (const pkgInfo of packageList) {
if (
overrides[pkgInfo.name] &&
overrides[pkgInfo.name] !== options.release
) {
throw new Error(
`conflicting overrides[${pkgInfo.name}]=${overrides[pkgInfo.name]} and --release=${options.release} config. Use either one or the other`,
);
}
overrides[pkgInfo.name] = options.release;
}
} else {
await patchBindingPackageJson(binding);
for (const pkgInfo of packageList) {
overrides[pkgInfo.name] ||= pkgInfo.directory;
}
}
await applyPackageOverrides({
dir,
pkg,
overrides,
agent,
beforeInstallCommand,
installArgs: {
pnpm: [
'--prefer-frozen-lockfile',
'--prefer-offline',
'--no-strict-peer-dependencies',
],
},
devDependencyStrategy: 'all',
});
}
await afterInstallCommand?.(pkg.scripts);
await beforeBuildCommand?.(pkg.scripts);
await buildCommand?.(pkg.scripts);
if (test) {
await beforeTestCommand?.(pkg.scripts);
await testCommand?.(pkg.scripts);
}
return { dir };
};
try {
return await runWorkflow();
} finally {
if (workspaceRenamed) {
try {
await fs.promises.rename(tempWorkspaceFile, workspaceFile);
} catch (error) {
if (!isFileNotFoundError(error)) {
throw error;
}
}
}
}
}
export async function setupStackRepo(options: Partial<RepoOptions> = {}) {
const repo = options.repo ?? STACK_DEFAULT_REPO[activeStack];
await setupRepo({
repo,
dir: stackPath,
branch: 'main',
shallow: true,
...options,
});
if (
activeStack === 'rsbuild' ||
activeStack === 'rstest' ||
activeStack === 'rslib' ||
activeStack === 'rsdoctor' ||
activeStack === 'rspress'
) {
delete monorepoPackagesCache[activeStack];
} else if (activeStack === 'rspack') {
rspackPackageData = null;
}
}
export async function getPermanentRef() {
cd(stackPath);
try {
const ref = await $`git log -1 --pretty=format:%h`;
return ref;
} catch (e) {
console.warn(`Failed to obtain perm ref. ${e}`);
return undefined;
}
}
export async function buildStack({ verify = false }: { verify?: boolean }) {
cd(stackPath);
if (activeStack === 'rspack') {
const frozenInstall = serializeCommand(getCommand('pnpm', 'frozen'));
const runBuildBinding = serializeCommand(
getCommand('pnpm', 'run', ['build:binding:release']),
);
// `@antfu/ni` ≥ 0.21 quotes any arg containing whitespace; pass each
// token separately so the resulting `pnpm run --filter ... move-binding`
// is not collapsed into a single quoted positional.
const runMoveBinding = serializeCommand(
getCommand('pnpm', 'run', [
'--filter',
'@rspack/binding',
'move-binding',
]),
);
const runBuildJs = serializeCommand(
getCommand('pnpm', 'run', ['build:js']),
);
await $`${frozenInstall}`;
await $`cargo codegen`;
await $`${runBuildBinding}`;
await $`${runMoveBinding}`;
await $`${runBuildJs}`;
if (verify) {
const runTest = serializeCommand(getCommand('pnpm', 'run', ['test:js']));
await $`${runTest}`;
}
} else {
const frozenInstall = serializeCommand(getCommand('pnpm', 'frozen'));
const runBuild = serializeCommand(getCommand('pnpm', 'run', ['build']));
await $`${frozenInstall}`;
await $`${runBuild}`;
if (verify) {
const runTest = serializeCommand(getCommand('pnpm', 'run', ['test']));
await $`${runTest}`;
}
}
}
export async function bisectStack(
good: string,
runSuite: () => Promise<Error | void>,
) {
const resetChanges = async () => $`git reset --hard HEAD`;
try {
cd(stackPath);
await resetChanges();
await $`git bisect start`;
await $`git bisect bad`;
await $`git bisect good ${good}`;
let bisecting = true;
while (bisecting) {
const commitMsg = await $`git log -1 --format=%s`;
const isNonCodeCommit = commitMsg.match(/^(?:release|docs)[:(]/);
if (isNonCodeCommit) {
await $`git bisect skip`;
continue;
}
const error = await runSuite();
cd(stackPath);
await resetChanges();
const bisectOut = await $`git bisect ${error ? 'bad' : 'good'}`;
bisecting = bisectOut.substring(0, 10).toLowerCase() === 'bisecting:';
}
} catch (e) {
console.log('error while bisecting', e);
} finally {
try {
cd(stackPath);
await $`git bisect reset`;
} catch (e) {
console.log('Error while resetting bisect', e);
}
}
}
function isLocalOverride(v: string): boolean {
if (!v.includes('/') || v.startsWith('@')) {
return false;
}
try {
return !!fs.lstatSync(v)?.isDirectory();
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {
throw e;
}
return false;
}
}
async function patchBindingPackageJson(infos: RspackPackageInfo[]) {
for (const bindingInfo of infos) {
const pkgJsonPath = path.join(bindingInfo.directory, 'package.json');
const pkgJson = JSON.parse(
await fs.promises.readFile(pkgJsonPath, 'utf-8'),
);
pkgJson.optionalDependencies = undefined;
await fs.promises.writeFile(pkgJsonPath, JSON.stringify(pkgJson, null, 2));
}
}
async function readPnpmWorkspaceYaml(
dir: string,
): Promise<{ exists: boolean; content: any; filePath: string }> {
const filePath = path.join(dir, 'pnpm-workspace.yaml');
if (!fs.existsSync(filePath)) {
return { exists: false, content: null, filePath };
}
const content = await fs.promises.readFile(filePath, 'utf-8');
const parsed = yaml.parse(content);
return { exists: true, content: parsed || {}, filePath };
}
async function writePnpmWorkspaceYaml(
filePath: string,
content: any,
): Promise<void> {
const yamlContent = yaml.stringify(content);
await fs.promises.writeFile(filePath, yamlContent, 'utf-8');
}
const FILE_PROTOCOL = 'file:';
const CATALOG_PROTOCOL = 'catalog:';
const DEP_SECTIONS = [
'dependencies',
'devDependencies',
'peerDependencies',
'optionalDependencies',
] as const;
interface SourceWorkspaceYaml {
catalog?: Record<string, string>;
catalogs?: Record<string, Record<string, string>>;
}
async function findAncestorWorkspaceYaml(
startDir: string,
cache: Map<string, SourceWorkspaceYaml | null>,
): Promise<SourceWorkspaceYaml | null> {
const visited: string[] = [];
let cursor = startDir;
let result: SourceWorkspaceYaml | null = null;
while (true) {
if (cache.has(cursor)) {
result = cache.get(cursor) ?? null;
break;
}
visited.push(cursor);
const ws = await readPnpmWorkspaceYaml(cursor);
if (ws.exists) {
result = (ws.content ?? {}) as SourceWorkspaceYaml;
break;
}
const parent = path.dirname(cursor);
if (parent === cursor) break;
cursor = parent;
}
for (const c of visited) cache.set(c, result);
return result;
}
function resolveCatalogSpec(
spec: string,
depName: string,
ws: SourceWorkspaceYaml,
): string | undefined {
const catalogName = spec.slice(CATALOG_PROTOCOL.length) || 'default';
if (catalogName === 'default') {
return ws.catalog?.[depName];
}
return ws.catalogs?.[catalogName]?.[depName];
}
// pnpm publish replaces `catalog:` specs with concrete versions at pack time.
// When ecosystem-ci links a workspace package via `file:`, the catalog refs
// in its manifest leak into the consuming workspace, which usually has a
// different (or missing) catalog block. Replicate publish-time resolution by
// rewriting the linked manifest in place.
async function inlineCatalogsInLinkedPackages(
overrides: Record<string, string>,
): Promise<void> {
const yamlCache = new Map<string, SourceWorkspaceYaml | null>();
await Promise.all(
Object.values(overrides).map(async (spec) => {
if (!spec.startsWith(FILE_PROTOCOL)) return;
const pkgDir = spec.slice(FILE_PROTOCOL.length);
const pkgJsonPath = path.join(pkgDir, 'package.json');
if (!fs.existsSync(pkgJsonPath)) return;
const pkgJson = JSON.parse(
await fs.promises.readFile(pkgJsonPath, 'utf-8'),
);
let sourceWs: SourceWorkspaceYaml | null | undefined;
let modified = false;
for (const section of DEP_SECTIONS) {
const deps = pkgJson[section];
if (!deps || typeof deps !== 'object') continue;
for (const [depName, depSpec] of Object.entries(deps)) {
if (typeof depSpec !== 'string') continue;
if (!depSpec.startsWith(CATALOG_PROTOCOL)) continue;
if (sourceWs === undefined) {
sourceWs = await findAncestorWorkspaceYaml(pkgDir, yamlCache);
}
const resolved = sourceWs
? resolveCatalogSpec(depSpec, depName, sourceWs)
: undefined;
if (resolved === undefined) {
throw new Error(
`cannot resolve "${depSpec}" for "${depName}" in ${pkgJsonPath}: ` +
'entry not found in source pnpm-workspace.yaml catalog',
);
}
deps[depName] = resolved;
modified = true;
}
}
if (modified) {
await fs.promises.writeFile(
pkgJsonPath,
JSON.stringify(pkgJson, null, 2),
'utf-8',
);
}
}),
);
}
async function applyPackageOverrides({
dir,
pkg,
overrides = {},
agent,
beforeInstallCommand,
installArgs,
devDependencyStrategy = 'local',
}: {
dir: string;
pkg: any;
overrides: Overrides;
agent: Agent;
beforeInstallCommand: ((scripts: any) => Promise<any>) | void;
installArgs?: {
pnpm?: string[];
yarn?: string[];
npm?: string[];
};
devDependencyStrategy?: 'all' | 'local';
}) {
const useFileProtocol = (v: string) =>
isLocalOverride(v) ? `${FILE_PROTOCOL}${path.resolve(v)}` : v;
const normalizedOverrides = Object.fromEntries(
Object.entries(overrides)
.filter(([_key, value]) => typeof value === 'string')
.map(([key, value]) => [key, useFileProtocol(value as string)]),
);
const devOverrides =
devDependencyStrategy === 'all'
? normalizedOverrides
: Object.fromEntries(
Object.entries(normalizedOverrides).filter(([_key, value]) =>
(value as string).startsWith(FILE_PROTOCOL),
),
);
await $`git clean -fdxq`;
const pm = agent.split('@')[0];
if (pm === 'pnpm') {
// applyPackageOverrides writes overrides into the consumer's
// pnpm-workspace.yaml. pnpm <10 treats that file strictly as a workspace
// definition and errors with `ERROR packages field missing or empty`
// when it exists without a `packages:` field. pnpm 10 moved overrides /
// catalogs / etc. into pnpm-workspace.yaml as project-level config, so we
// require >=10 here and fail loudly instead of producing that confusing
// install-time error downstream.
const declaredPm: unknown = pkg?.packageManager;
if (typeof declaredPm === 'string' && declaredPm.startsWith('pnpm@')) {
const major = parseInt(declaredPm.slice('pnpm@'.length), 10);
if (Number.isFinite(major) && major < 10) {
throw new Error(
`${dir}: consumer pins \`packageManager: "${declaredPm}"\`; ` +
`rstack-ecosystem-ci requires pnpm >= 10. applyPackageOverrides writes ` +
`overrides into pnpm-workspace.yaml, which pnpm <10 rejects without a ` +
`\`packages:\` field. Bump the consumer's \`packageManager\` field to pnpm@10.x or newer.`,
);
}
}
if (!pkg.devDependencies) {
pkg.devDependencies = {};
}
pkg.devDependencies = {
...pkg.devDependencies,
...devOverrides,
};
// pnpm 11 ignores `pkg.pnpm.overrides` (pnpm/pnpm#10086); on pnpm 10 it
// shadows the yaml. Migrate any pre-existing pkg overrides into the yaml
// so the result is identical across pnpm 10 and 11.
const workspace = await readPnpmWorkspaceYaml(dir);
const inheritedOverrides = pkg.pnpm?.overrides;
if (workspace.content?.overrides && inheritedOverrides) {
throw new Error(
'Conflicting overrides detected: both pnpm-workspace.yaml and package.json contain pnpm overrides. ' +
'Please use only one location for overrides configuration.',
);
}
if (inheritedOverrides) {
delete pkg.pnpm.overrides;
if (Object.keys(pkg.pnpm).length === 0) delete pkg.pnpm;
}
const wsContent = workspace.content ?? {};
wsContent.overrides = {
...wsContent.overrides,
...inheritedOverrides,
...normalizedOverrides,
};
// Mirror vite-ecosystem-ci: relax workspace constraints that would
// conflict with the override-mutated dependency graph (e.g. a freshly
// linked package can introduce build scripts or younger versions that
// the upstream lockfile never had to clear).
// pnpm 11 treats `allowBuilds:` as implicit strict mode, so this must
// be set unconditionally — guarding on a truthy value silently leaves
// repos that have `allowBuilds` but no explicit `strictDepBuilds`.
wsContent.strictDepBuilds = false;
// pnpm 11 ships a built-in default `minimumReleaseAge: 1440` (24h
// supply-chain gate; pnpm/pnpm config/reader/src/index.ts:176 @ v11.3.0).
// Deleting the key falls back to that default and rejects lockfile entries
// published in the past day, so the override-mutated tree fails to install.
// Per the pnpm 11 changelog the opt-out is an explicit `0`; pnpm 10 reads
// it as "policy off" too, so the same write works on both supported majors.
wsContent.minimumReleaseAge = 0;
delete wsContent.minimumReleaseAgeExclude;
// Same default-flip pattern as minimumReleaseAge above:
// pnpm 10 defaults `block-exotic-subdeps` to `false`, pnpm 11 to `true`
// (config/reader/src/index.ts:187 @ v11.3.0; 11.0 changelog
// "blockExoticSubdeps is true by default"). The override-mutated graph may
// pull in transitively-resolved git/http subdeps that the upstream lockfile
// accepted; under pnpm 11 they would now throw ERR_PNPM_EXOTIC_SUBDEP.
// `file:` overrides themselves are `local-filesystem` and are trusted, so
// disabling the policy is safe here (resolveDependencies.ts:1831-1844).
wsContent.blockExoticSubdeps = false;
await writePnpmWorkspaceYaml(workspace.filePath, wsContent);
await inlineCatalogsInLinkedPackages(normalizedOverrides);
} else if (pm === 'yarn') {
if (!pkg.devDependencies) {
pkg.devDependencies = {};
}
pkg.devDependencies = {
...pkg.devDependencies,
...devOverrides,
};
pkg.resolutions = {
...pkg.resolutions,
...normalizedOverrides,
};
} else if (pm === 'npm') {
pkg.overrides = {
...pkg.overrides,
...normalizedOverrides,
};
for (const [name, version] of Object.entries(normalizedOverrides)) {
if (pkg.dependencies?.[name]) {
pkg.dependencies[name] = version;
}
if (pkg.devDependencies?.[name]) {
pkg.devDependencies[name] = version;
}
}
} else {
throw new Error(`unsupported package manager detected: ${pm}`);
}
const pkgFile = path.join(dir, 'package.json');
await fs.promises.writeFile(pkgFile, JSON.stringify(pkg, null, 2), 'utf-8');
await beforeInstallCommand?.(pkg.scripts);
if (pm === 'pnpm') {
const pnpmArgs = [...(installArgs?.pnpm ?? [])];
// pnpm 11 dropped `NPM_CONFIG_*` env vars in favor of `PNPM_CONFIG_*`
// (see pnpm/pnpm#11189), so rspack suites that publish to a local
// Verdaccio can no longer rely on `NPM_CONFIG_REGISTRY`. Forward it as
// a CLI flag, which works for both pnpm 10 and 11.
if (process.env.NPM_CONFIG_REGISTRY) {
pnpmArgs.push(`--registry=${process.env.NPM_CONFIG_REGISTRY}`);
}
const command = ['pnpm', 'install', ...pnpmArgs].join(' ');
await $`${command}`;
} else if (pm === 'yarn') {
const yarnArgs = installArgs?.yarn ?? [];