-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathset-react-version.mts
More file actions
415 lines (379 loc) · 12.8 KB
/
set-react-version.mts
File metadata and controls
415 lines (379 loc) · 12.8 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
/**
* Reminder that this script is meant to be runnable without installing
* dependencies. It can therefore not rely on any external libraries.
*/
import * as fs from "node:fs";
import * as path from "node:path";
import * as util from "node:util";
import {
isMain,
readJSONFile,
readTextFile,
toVersionNumber,
v,
} from "../helpers.js";
import type { Manifest } from "../types.js";
import { writeJSONFile } from "../utils/filesystem.mjs";
import { fetchPackageMetadata, npmRegistryBaseURL } from "../utils/npm.mjs";
const VALID_TAGS = ["canary-macos", "canary-windows", "nightly"];
/**
* Returns whether specified string is a valid version number.
*/
function isValidVersion(v: string): boolean {
return /^\d+\.\d+$/.test(v) || VALID_TAGS.includes(v);
}
/**
* Type-safe `Object.keys()`
*/
function keys<T extends Record<string, unknown>>(obj: T): (keyof T)[] {
return Object.keys(obj) as (keyof T)[];
}
function searchReplaceInFile(
filename: string,
searchValue: string | RegExp,
replaceValue: string
): void {
const current = readTextFile(filename);
const updated = current.replace(searchValue, replaceValue);
if (updated !== current) {
fs.writeFileSync(filename, updated);
}
}
/**
* Disables [Jetifier](https://developer.android.com/tools/jetifier).
*
* Jetifier is only necessary when you depend on code that has not yet migrated
* to AndroidX. If we only deal with modern code, disabling it makes builds
* slightly faster.
*/
function disableJetifier() {
return searchReplaceInFile(
"example/android/gradle.properties",
"android.enableJetifier=true",
"android.enableJetifier=false"
);
}
function disableWebStorage() {
return searchReplaceInFile(
"example/package.json",
/\s+"@react-native-webapis\/web-storage":.*/,
""
);
}
/**
* Infer the React Native version an out-of-tree platform package is based on.
*/
function inferReactNativeVersion({
name,
version,
dependencies = {},
}: Manifest): string {
const codegenVersion = dependencies["@react-native/codegen"];
if (!codegenVersion) {
throw new Error(
`Unable to determine the react-native version that ${name}@${version} is based on`
);
}
const rnVersion = codegenVersion.split(".").slice(0, 2).join(".") + ".0-0";
return rnVersion[0] === "^" || rnVersion[0] === "~"
? rnVersion
: "^" + rnVersion;
}
/**
* Fetches package information.
*/
function fetchPackageInfo(pkg: string, version: string): Promise<Manifest> {
return fetchPackageMetadata(pkg)
.then(({ ["dist-tags"]: distTags, versions }) => {
const tags = [version, version + "-stable", "v" + version + "-stable"];
for (const t of tags) {
if (distTags[t]) {
return distTags[t];
}
}
const allVersions = Object.keys(versions);
for (let i = allVersions.length - 1; i >= 0; --i) {
const v = allVersions[i];
if (v.startsWith(version)) {
return v;
}
}
})
.then((foundVersion) => {
if (!foundVersion) {
console.warn(`No match found for '${pkg}@${version}'`);
return undefined;
}
return fetch(npmRegistryBaseURL + pkg + "/" + foundVersion);
})
.then((res) => res?.json() ?? ({} as Manifest))
.then(({ version, dependencies = {}, peerDependencies = {} }) => {
return { version, dependencies, peerDependencies };
});
}
/**
* Fetches the latest react-native-windows@canary information via NuGet.
*/
function fetchReactNativeWindowsCanaryInfoViaNuGet(): Promise<Manifest> {
const rnwNuGetFeed =
"https://pkgs.dev.azure.com/ms/react-native/_packaging/react-native-public/nuget/v3/index.json";
return fetch(rnwNuGetFeed)
.then((res) => res.json())
.then(({ resources }) => {
if (!Array.isArray(resources)) {
throw new Error("Unexpected format returned by the services endpoint");
}
const service = resources.find((svc) =>
svc["@type"].startsWith("RegistrationsBaseUrl")
);
if (!service) {
throw new Error("Failed to find 'RegistrationsBaseUrl' resource");
}
return service["@id"];
})
.then((url) => fetch(url + "/Microsoft.ReactNative.Cxx/index.json"))
.then((res) => res.json())
.then(({ items }) => {
if (!Array.isArray(items)) {
throw new Error(
"Unexpected format returned by the 'RegistrationsBaseUrl' service"
);
}
for (const item of items) {
for (const pkg of item.items) {
const version = pkg.catalogEntry?.version;
if (typeof version === "string" && version.startsWith("0.0.0")) {
const m = version.match(/(0\.0\.0-[.0-9a-z]+)/);
if (m) {
return m[1];
}
}
}
}
throw new Error("Failed to find canary builds");
})
.then((version) => fetchPackageInfo("react-native-windows", version));
}
/**
* Returns an object with common dependencies.
*/
async function resolveCommonDependencies(
v: string,
{ dependencies = {}, peerDependencies = {} }: Manifest
): Promise<Record<string, string | undefined>> {
const [rnBabelPresetVersion, rnMetroConfigVersion, metroBabelPresetVersion] =
await (async () => {
if (["^", "canary", "nightly"].some((tag) => v.includes(tag))) {
return [v, v, undefined];
}
const [
{ version: rnBabelPresetVersion },
{ version: rnMetroConfigVersion },
{ version: metroBabelPresetVersion },
] = await Promise.all([
fetchPackageInfo("@react-native/babel-preset", v),
fetchPackageInfo("@react-native/metro-config", v),
(async () => {
// Metro bumps and publishes all packages together, meaning we can use
// `metro-react-native-babel-transformer` to determine the version of
// `metro-react-native-babel-preset` that should be used.
const version = dependencies["metro-react-native-babel-transformer"];
if (version) {
return { version };
}
// `metro-react-native-babel-transformer` is no longer a direct
// dependency of `react-native`. As of 0.72, we should go through
// `@react-native-community/cli-plugin-metro` instead.
const cliVersion = dependencies["@react-native-community/cli"];
if (!cliVersion) {
// `@react-native-community/cli` is no longer a direct dependency in
// 0.73. We should be using `@react-native/babel-preset` instead.
return {};
}
const metroPluginInfo = await fetchPackageInfo(
"@react-native-community/cli-plugin-metro",
cliVersion.replace("^", "").split(".").slice(0, 2).join(".")
);
return { version: metroPluginInfo.dependencies?.["metro"] };
})(),
]);
return [
rnBabelPresetVersion,
rnMetroConfigVersion,
metroBabelPresetVersion,
];
})();
// Starting with 0.76, `react-native` no longer depends on
// `@react-native-community/cli`
const rncli = dependencies["@react-native-community/cli"] ?? "latest";
const rncliAndroid =
dependencies["@react-native-community/cli-platform-android"] ?? rncli;
const rncliIOS =
dependencies["@react-native-community/cli-platform-ios"] ?? rncli;
return {
"@react-native-community/cli": rncli,
"@react-native-community/cli-platform-android": rncliAndroid,
"@react-native-community/cli-platform-ios": rncliIOS,
"@react-native/babel-preset": rnBabelPresetVersion,
"@react-native/metro-config": rnMetroConfigVersion,
"metro-react-native-babel-preset": metroBabelPresetVersion,
// Replace range to avoid React version mismatch
react: peerDependencies["react"].replace(/^\^/, "~"),
};
}
/**
* Returns a profile for specified version.
*/
async function getProfile(
v: string,
coreOnly: boolean
): Promise<Record<string, string | undefined>> {
const manifest = readJSONFile<Manifest>("package.json");
const visionos = manifest.defaultPlatformPackages?.["visionos"];
if (!visionos) {
throw new Error("Missing platform package for visionOS");
}
switch (v) {
case "canary-macos": {
const info = await fetchPackageInfo("react-native-macos", "canary");
const coreVersion = inferReactNativeVersion(info);
const commonDeps = await resolveCommonDependencies(coreVersion, info);
return {
...commonDeps,
"react-native": coreVersion,
"react-native-macos": "canary",
"react-native-windows": undefined,
[visionos]: undefined,
};
}
case "canary-windows": {
const info = await fetchReactNativeWindowsCanaryInfoViaNuGet();
const coreVersion = info.peerDependencies?.["react-native"] || "nightly";
const commonDeps = await resolveCommonDependencies(coreVersion, info);
return {
...commonDeps,
"react-native": coreVersion,
"react-native-macos": undefined,
"react-native-windows": info.version,
[visionos]: undefined,
};
}
case "nightly": {
const info = await fetchPackageInfo("react-native", "nightly");
const commonDeps = await resolveCommonDependencies(v, info);
return {
...commonDeps,
"react-native": "nightly",
"react-native-macos": undefined,
"react-native-windows": undefined,
[visionos]: undefined,
};
}
default: {
const versions = {
core: fetchPackageInfo("react-native", v),
macos: coreOnly
? Promise.resolve({ version: undefined })
: fetchPackageInfo("react-native-macos", v),
visionos: coreOnly
? Promise.resolve({ version: undefined })
: fetchPackageInfo(visionos, v),
windows: coreOnly
? Promise.resolve({ version: undefined })
: fetchPackageInfo("react-native-windows", v),
};
const reactNative = await versions.core;
const commonDeps = await resolveCommonDependencies(v, reactNative);
const getVersion = ({ version }: Manifest) => version;
return {
...commonDeps,
"react-native": reactNative.version,
"react-native-macos": await versions.macos.then(getVersion),
"react-native-windows": await versions.windows.then(getVersion),
[visionos]: await versions.visionos.then(getVersion),
};
}
}
}
/**
* Sets specified React Native version.
*/
export async function setReactVersion(
version: string,
coreOnly: boolean,
overrides: Record<string, string> = {}
): Promise<void> {
try {
const profile = { ...(await getProfile(version, coreOnly)), ...overrides };
console.dir(profile, { depth: null });
const manifests = ["package.json", "example/package.json"];
for (const manifestPath of manifests) {
const manifest = readJSONFile<Manifest>(manifestPath);
const { dependencies, devDependencies, resolutions = {} } = manifest;
if (!devDependencies) {
throw new Error("Expected 'devDependencies' to be declared");
}
for (const packageName of keys(profile)) {
const deps = dependencies?.[packageName]
? dependencies
: devDependencies;
deps[packageName] = profile[packageName];
// Reset resolutions so we don't get old packages
resolutions[packageName] = undefined;
}
// Reset resolutions of the nested type e.g.,
// `@react-native/community-cli-plugin/@react-native-community/cli-server-api`
for (const pkg of Object.keys(resolutions)) {
if (pkg.startsWith("@react-native")) {
resolutions[pkg] = undefined;
}
}
const tmpFile = manifestPath + ".tmp";
writeJSONFile(tmpFile, manifest);
fs.renameSync(tmpFile, manifestPath);
}
} catch (e) {
console.error(e);
process.exitCode = 1;
}
}
if (isMain(import.meta.url)) {
const { values, positionals } = util.parseArgs({
args: process.argv.slice(2),
options: {
"core-only": {
type: "boolean",
default: false,
},
overrides: {
type: "string",
default: "{}",
},
},
strict: true,
allowPositionals: true,
tokens: false,
});
const version = positionals[0];
if (!isValidVersion(version)) {
const script = process.argv[1];
console.log(
`Usage: ${path.basename(script)} [<version number> | ${VALID_TAGS.join(" | ")}]`
);
process.exitCode = 1;
} else {
const { "core-only": coreOnly, overrides } = values;
setReactVersion(version, coreOnly, JSON.parse(overrides)).then(() => {
const numVersion = VALID_TAGS.includes(version)
? Number.MAX_SAFE_INTEGER
: toVersionNumber(version);
if (numVersion >= v(0, 74, 0)) {
disableJetifier();
}
// `@react-native-webapis/web-storage` is not compatible with codegen 0.71
if (numVersion < v(0, 72, 0)) {
disableWebStorage();
}
});
}
}