-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathbuild.ts
More file actions
351 lines (326 loc) · 10.7 KB
/
build.ts
File metadata and controls
351 lines (326 loc) · 10.7 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
import path from "node:path";
import fs from "node:fs";
import { Command, Option } from "@commander-js/extra-typings";
import chalk from "chalk";
import { SpawnFailure } from "bufout";
import { oraPromise } from "ora";
import {
determineAndroidLibsFilename,
createAndroidLibsDirectory,
AndroidTriplet,
createAppleFramework,
determineXCFrameworkFilename,
createXCframework,
createUniversalAppleLibrary,
determineLibraryBasename,
prettyPath,
} from "react-native-node-api";
import { UsageError } from "./errors.js";
import { ensureCargo, build } from "./cargo.js";
import {
ALL_TARGETS,
ANDROID_TARGETS,
AndroidTargetName,
APPLE_TARGETS,
AppleTargetName,
ensureInstalledTargets,
filterTargetsByPlatform,
} from "./targets.js";
import { generateTypeScriptDeclarations } from "./napi-rs.js";
import { getBlockComment } from "./banner.js";
type EntrypointOptions = {
outputPath: string;
libraryName: string;
};
async function generateEntrypoint({
outputPath,
libraryName,
}: EntrypointOptions) {
await fs.promises.writeFile(
outputPath,
[
"/* eslint-disable */",
getBlockComment(),
`module.exports = require('./${libraryName}.node');`,
].join("\n\n") + "\n",
"utf8"
);
}
const ANDROID_TRIPLET_PER_TARGET: Record<AndroidTargetName, AndroidTriplet> = {
"aarch64-linux-android": "aarch64-linux-android",
"armv7-linux-androideabi": "armv7a-linux-androideabi",
"i686-linux-android": "i686-linux-android",
"x86_64-linux-android": "x86_64-linux-android",
};
// This should match https://github.com/react-native-community/template/blob/main/template/android/build.gradle#L7
const DEFAULT_NDK_VERSION = "27.1.12297006";
const ANDROID_API_LEVEL = 24;
const targetOption = new Option("--target <target...>", "Target triple")
.choices(ALL_TARGETS)
.default([]);
const appleTarget = new Option("--apple", "Use all Apple targets");
const androidTarget = new Option("--android", "Use all Android targets");
const ndkVersionOption = new Option(
"--ndk-version <version>",
"The NDK version to use for Android builds"
).default(DEFAULT_NDK_VERSION);
const xcframeworkExtensionOption = new Option(
"--xcframework-extension",
"Don't rename the xcframework to .apple.node"
).default(false);
const outputPathOption = new Option(
"--output <path>",
"Writing outputs to this directory"
).default(process.cwd());
const configurationOption = new Option(
"--configuration <configuration>",
"Build configuration"
)
.choices(["debug", "release"])
.default("debug");
export const buildCommand = new Command("build")
.description("Build Rust Node-API module")
.addOption(targetOption)
.addOption(appleTarget)
.addOption(androidTarget)
.addOption(ndkVersionOption)
.addOption(outputPathOption)
.addOption(configurationOption)
.addOption(xcframeworkExtensionOption)
.action(
async ({
target: targetArg,
apple,
android,
ndkVersion,
output: outputPath,
configuration,
xcframeworkExtension,
}) => {
try {
const targets = new Set([...targetArg]);
if (apple) {
for (const target of APPLE_TARGETS) {
targets.add(target);
}
}
if (android) {
for (const target of ANDROID_TARGETS) {
targets.add(target);
}
}
if (targets.size === 0) {
if (isAndroidSupported()) {
if (process.arch === "arm64") {
targets.add("aarch64-linux-android");
} else if (process.arch === "x64") {
targets.add("x86_64-linux-android");
}
}
if (isAppleSupported()) {
if (process.arch === "arm64") {
targets.add("aarch64-apple-ios-sim");
}
}
console.error(
chalk.yellowBright("ℹ"),
chalk.dim(
`Using default targets, pass ${chalk.italic(
"--android"
)}, ${chalk.italic("--apple")} or individual ${chalk.italic(
"--target"
)} options, to avoid this.`
)
);
}
ensureCargo();
ensureInstalledTargets(targets);
const appleTargets = filterTargetsByPlatform(targets, "apple");
const androidTargets = filterTargetsByPlatform(targets, "android");
const targetsDescription =
targets.size +
(targets.size === 1 ? " target" : " targets") +
chalk.dim(" (" + [...targets].join(", ") + ")");
const [appleLibraries, androidLibraries] = await oraPromise(
Promise.all([
Promise.all(
appleTargets.map(
async (target) =>
[target, await build({ configuration, target })] as const
)
),
Promise.all(
androidTargets.map(
async (target) =>
[
target,
await build({
configuration,
target,
ndkVersion,
androidApiLevel: ANDROID_API_LEVEL,
}),
] as const
)
),
]),
{
text: `Building ${targetsDescription}`,
successText: `Built ${targetsDescription}`,
failText: (error: Error) => `Failed to build: ${error.message}`,
}
);
if (androidLibraries.length > 0) {
const libraryPathByTriplet = Object.fromEntries(
androidLibraries.map(([target, outputPath]) => [
ANDROID_TRIPLET_PER_TARGET[target],
outputPath,
])
) as Record<AndroidTriplet, string>;
const androidLibsFilename = determineAndroidLibsFilename(
Object.values(libraryPathByTriplet)
);
const androidLibsOutputPath = path.resolve(
outputPath,
androidLibsFilename
);
await oraPromise(
createAndroidLibsDirectory({
outputPath: androidLibsOutputPath,
libraryPathByTriplet,
autoLink: true,
}),
{
text: "Assembling Android libs directory",
successText: `Android libs directory assembled into ${prettyPath(
androidLibsOutputPath
)}`,
failText: ({ message }) =>
`Failed to assemble Android libs directory: ${message}`,
}
);
}
if (appleLibraries.length > 0) {
const libraryPaths = await combineLibraries(appleLibraries);
const frameworkPaths = libraryPaths.map(createAppleFramework);
const xcframeworkFilename = determineXCFrameworkFilename(
frameworkPaths,
xcframeworkExtension ? ".xcframework" : ".apple.node"
);
// Create the xcframework
const xcframeworkOutputPath = path.resolve(
outputPath,
xcframeworkFilename
);
await oraPromise(
createXCframework({
outputPath: xcframeworkOutputPath,
frameworkPaths,
autoLink: true,
}),
{
text: "Assembling XCFramework",
successText: `XCFramework assembled into ${chalk.dim(
path.relative(process.cwd(), xcframeworkOutputPath)
)}`,
failText: ({ message }) =>
`Failed to assemble XCFramework: ${message}`,
}
);
}
const libraryName = determineLibraryBasename([
...androidLibraries.map(([, outputPath]) => outputPath),
...appleLibraries.map(([, outputPath]) => outputPath),
]);
const declarationsFilename = `${libraryName}.d.ts`;
const declarationsPath = path.join(outputPath, declarationsFilename);
await oraPromise(
generateTypeScriptDeclarations({
outputFilename: declarationsFilename,
createPath: process.cwd(),
outputPath,
}),
{
text: "Generating TypeScript declarations",
successText: `Generated TypeScript declarations ${prettyPath(
declarationsPath
)}`,
failText: (error) =>
`Failed to generate TypeScript declarations: ${error.message}`,
}
);
const entrypointPath = path.join(outputPath, `${libraryName}.js`);
await oraPromise(
generateEntrypoint({
libraryName,
outputPath: entrypointPath,
}),
{
text: `Generating entrypoint`,
successText: `Generated entrypoint into ${prettyPath(
entrypointPath
)}`,
failText: (error) =>
`Failed to generate entrypoint: ${error.message}`,
}
);
} catch (error) {
process.exitCode = 1;
if (error instanceof SpawnFailure) {
error.flushOutput("both");
}
if (error instanceof UsageError || error instanceof SpawnFailure) {
console.error(chalk.red("ERROR"), error.message);
if (error.cause instanceof Error) {
console.error(chalk.red("CAUSE"), error.cause.message);
}
if (error instanceof UsageError && error.fix) {
console.error(
chalk.green("FIX"),
error.fix.command
? chalk.dim("Run: ") + error.fix.command
: error.fix.instructions
);
}
} else {
throw error;
}
}
}
);
async function combineLibraries(
libraries: Readonly<[AppleTargetName, string]>[]
): Promise<string[]> {
const result = [];
const darwinLibraries = [];
for (const [target, libraryPath] of libraries) {
if (target.endsWith("-darwin")) {
darwinLibraries.push(libraryPath);
} else {
result.push(libraryPath);
}
}
if (darwinLibraries.length === 0) {
return result;
} else if (darwinLibraries.length === 1) {
return [...result, darwinLibraries[0]];
} else {
const universalPath = await oraPromise(
createUniversalAppleLibrary(darwinLibraries),
{
text: "Combining Darwin libraries into a universal library",
successText: "Combined Darwin libraries into a universal library",
failText: (error) =>
`Failed to combine Darwin libraries: ${error.message}`,
}
);
return [...result, universalPath];
}
}
export function isAndroidSupported() {
const { ANDROID_HOME } = process.env;
return typeof ANDROID_HOME === "string" && fs.existsSync(ANDROID_HOME);
}
export function isAppleSupported() {
return process.platform === "darwin";
}