Skip to content

Commit 46662cc

Browse files
kraenhansenclaude
andcommitted
feat(ferric): check resolved napi-sys features before building (#482)
* feat(ferric): check resolved napi-sys features before building Ask cargo metadata for the crate's resolved features for each target and fail with a fixable error if napi-sys' dyn-symbols feature is enabled, since it resolves Node-API functions at runtime instead of linking them against weak-node-api (#331). Pass --skip-feature-check to bypass. Also adds a unit test setup to ferric, mirroring cmake-rn's tsconfig layout. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01U2xSE3sZkTrATdVrV2xqbZ * feat(ferric): fail on napiN features above Node-API version 10 The host implements Node-API up to version 10 (NAPI_VERSION in packages/host/cpp/Versions.hpp), so a higher napiN feature on napi-sys would call functions the runtime doesn't provide. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01U2xSE3sZkTrATdVrV2xqbZ * chore: trigger CI with Ferric label Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01U2xSE3sZkTrATdVrV2xqbZ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 7c876ad commit 46662cc

11 files changed

Lines changed: 223 additions & 12 deletions
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"ferric-cli": minor
3+
---
4+
5+
Check the crate's resolved `napi-sys` features before building and fail if `dyn-symbols` is enabled (it prevents linking against `weak-node-api`) or a `napiN` feature above the supported Node-API version 10. Pass `--skip-feature-check` to bypass.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
"publint": "node scripts/run-in-published.ts pnpm exec publint --strict",
1515
"prettier:check": "prettier --experimental-cli --check .",
1616
"prettier:write": "prettier --experimental-cli --write .",
17-
"test": "pnpm --filter react-native-node-api --filter cmake-rn --filter gyp-to-cmake run test",
17+
"test": "pnpm --filter react-native-node-api --filter cmake-rn --filter gyp-to-cmake --filter ferric-cli run test",
1818
"bootstrap": "node --run build && pnpm --recursive run bootstrap",
1919
"changeset": "changeset",
2020
"release": "node --run prerelease && changeset publish",

‎packages/ferric/README.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,21 @@
11
# `ferric`
22

33
A wrapper around Cargo making it easier to produce prebuilt binaries targeting iOS and Android matching [the prebuilt binary specification](https://github.com/callstackincubator/react-native-node-api/blob/main/docs/PREBUILDS.md) as well as [napi.rs](https://napi.rs/) to generate bindings from annotated Rust code.
4+
5+
## Feature check
6+
7+
Before building, `ferric build` asks Cargo for the crate's resolved features for each target and fails if `napi-sys` has either of these enabled:
8+
9+
- `dyn-symbols`, which makes napi-rs look up Node-API functions in the host process at runtime instead of linking them against `weak-node-api`. That doesn't work in React Native ([#331](https://github.com/callstackincubator/react-native-node-api/issues/331)).
10+
- A `napiN` feature above Node-API version 10, the highest version the host supports.
11+
12+
`napi` enables `dyn-symbols` through its default features, so disable those and pick the Node-API version explicitly:
13+
14+
```toml
15+
[dependencies.napi]
16+
version = "3"
17+
default-features = false
18+
features = ["napi3"]
19+
```
20+
21+
Pass `--skip-feature-check` to bypass the check.

‎packages/ferric/package.json‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,14 @@
1717
"ferric": "./bin/ferric.js"
1818
},
1919
"scripts": {
20-
"start": "tsx src/run.ts"
20+
"start": "tsx src/run.ts",
21+
"test": "tsx --test --test-reporter=@reporters/github --test-reporter-destination=stdout --test-reporter=spec --test-reporter-destination=stdout"
2122
},
2223
"dependencies": {
2324
"@napi-rs/cli": "~3.10.8",
2425
"@react-native-node-api/cli-utils": "workspace:*",
2526
"react-native-node-api": "workspace:*",
26-
"weak-node-api": "workspace:*"
27+
"weak-node-api": "workspace:*",
28+
"zod": "^4.1.11"
2729
}
2830
}

‎packages/ferric/src/build.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import {
3939
} from "./targets.js";
4040
import { generateTypeScriptDeclarations } from "./napi-rs.js";
4141
import { getBlockComment } from "./banner.js";
42+
import { assertNapiFeatures } from "./features.js";
4243

4344
type EntrypointOptions = {
4445
outputPath: string;
@@ -104,6 +105,10 @@ const xcframeworkExtensionOption = new Option(
104105
"--xcframework-extension",
105106
"Don't rename the xcframework to .apple.node",
106107
).default(false);
108+
const skipFeatureCheckOption = new Option(
109+
"--skip-feature-check",
110+
"Don't check the crate's resolved napi-sys features before building",
111+
).default(false);
107112
const dtsOnlyOption = new Option(
108113
"--dts-only",
109114
"Only generate the TypeScript declarations and entrypoint, skipping Android/Apple cross-compilation. Still runs a real `cargo build` for the host target (napi-rs has no lighter typegen-only mode), so this is not a no-op — it's meant for regenerating a checked-in declarations fixture, not for toolchain-free environments.",
@@ -158,6 +163,7 @@ export const buildCommand = new Command("build")
158163
.addOption(concurrencyOption)
159164
.addOption(verboseOption)
160165
.addOption(dtsOnlyOption)
166+
.addOption(skipFeatureCheckOption)
161167
.action(
162168
wrapAction(
163169
async ({
@@ -173,6 +179,7 @@ export const buildCommand = new Command("build")
173179
concurrency,
174180
verbose,
175181
dtsOnly,
182+
skipFeatureCheck,
176183
}) => {
177184
if (dtsOnly) {
178185
assertFixable(
@@ -271,6 +278,9 @@ export const buildCommand = new Command("build")
271278
}
272279
ensureCargo();
273280
ensureAvailableTargets(targets);
281+
if (!skipFeatureCheck) {
282+
assertNapiFeatures(process.cwd(), targets);
283+
}
274284

275285
const appleTargets = filterTargetsByPlatform(targets, "apple");
276286
const androidTargets = filterTargetsByPlatform(targets, "android");
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import assert from "node:assert/strict";
2+
import { describe, it } from "node:test";
3+
4+
import {
5+
getNodeApiVersion,
6+
getResolvedFeatures,
7+
type CargoResolvedMetadata,
8+
} from "./features.js";
9+
10+
const NAPI_SYS_ID =
11+
"registry+https://github.com/rust-lang/crates.io-index#napi-sys@3.4.0";
12+
const NAPI_ID =
13+
"registry+https://github.com/rust-lang/crates.io-index#napi@3.14.2";
14+
15+
function createMetadata(napiSysFeatures: string[]): CargoResolvedMetadata {
16+
return {
17+
packages: [
18+
{ id: NAPI_SYS_ID, name: "napi-sys" },
19+
{ id: NAPI_ID, name: "napi" },
20+
],
21+
resolve: {
22+
nodes: [
23+
{ id: NAPI_SYS_ID, features: napiSysFeatures },
24+
{ id: NAPI_ID, features: ["default", "dyn-symbols"] },
25+
],
26+
},
27+
};
28+
}
29+
30+
describe("getResolvedFeatures", () => {
31+
it("returns the features resolved for the package", () => {
32+
const features = getResolvedFeatures(
33+
createMetadata(["dyn-symbols", "napi1"]),
34+
"napi-sys",
35+
);
36+
assert.deepEqual([...features], ["dyn-symbols", "napi1"]);
37+
});
38+
39+
it("ignores features of other packages", () => {
40+
const features = getResolvedFeatures(createMetadata(["napi1"]), "napi-sys");
41+
assert.deepEqual([...features], ["napi1"]);
42+
});
43+
44+
it("returns no features when the package isn't a dependency", () => {
45+
const metadata = createMetadata(["napi1"]);
46+
assert.equal(getResolvedFeatures(metadata, "missing").size, 0);
47+
assert.equal(
48+
getResolvedFeatures({ ...metadata, resolve: null }, "napi-sys").size,
49+
0,
50+
);
51+
});
52+
});
53+
54+
describe("getNodeApiVersion", () => {
55+
it("returns the highest enabled napiN feature", () => {
56+
assert.equal(
57+
getNodeApiVersion(["napi1", "napi10", "napi3", "dyn-symbols"]),
58+
10,
59+
);
60+
});
61+
62+
it("returns 0 when no napiN feature is enabled", () => {
63+
assert.equal(getNodeApiVersion(["dyn-symbols", "napi"]), 0);
64+
});
65+
});

‎packages/ferric/src/features.ts‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import cp from "node:child_process";
2+
3+
import { assertFixable, chalk } from "@react-native-node-api/cli-utils";
4+
import * as z from "zod";
5+
6+
import type { TargetName } from "./targets.js";
7+
8+
const CargoResolvedMetadata = z.object({
9+
packages: z.array(z.object({ id: z.string(), name: z.string() })),
10+
resolve: z
11+
.object({
12+
nodes: z.array(
13+
z.object({ id: z.string(), features: z.array(z.string()).optional() }),
14+
),
15+
})
16+
.nullable(),
17+
});
18+
19+
export type CargoResolvedMetadata = z.infer<typeof CargoResolvedMetadata>;
20+
21+
export function getResolvedFeatures(
22+
metadata: CargoResolvedMetadata,
23+
packageName: string,
24+
): Set<string> {
25+
const ids = new Set(
26+
metadata.packages
27+
.filter((pkg) => pkg.name === packageName)
28+
.map((pkg) => pkg.id),
29+
);
30+
const nodes = metadata.resolve?.nodes ?? [];
31+
return new Set(
32+
nodes
33+
.filter((node) => ids.has(node.id))
34+
.flatMap((node) => node.features ?? []),
35+
);
36+
}
37+
38+
function readResolvedMetadata(
39+
cwd: string,
40+
target: TargetName,
41+
): CargoResolvedMetadata {
42+
const output = cp.execFileSync(
43+
"cargo",
44+
["metadata", "--format-version", "1", "--filter-platform", target],
45+
{ cwd, encoding: "utf-8" },
46+
);
47+
return CargoResolvedMetadata.parse(JSON.parse(output));
48+
}
49+
50+
/**
51+
* The highest Node-API version implemented by the host.
52+
*/
53+
export const MAX_NODE_API_VERSION = 10;
54+
55+
export function getNodeApiVersion(features: Iterable<string>): number {
56+
let result = 0;
57+
for (const feature of features) {
58+
const match = /^napi(\d+)$/.exec(feature);
59+
if (match) {
60+
result = Math.max(result, parseInt(match[1], 10));
61+
}
62+
}
63+
return result;
64+
}
65+
66+
export function assertNapiFeatures(cwd: string, targets: Iterable<TargetName>) {
67+
for (const target of targets) {
68+
const features = getResolvedFeatures(
69+
readResolvedMetadata(cwd, target),
70+
"napi-sys",
71+
);
72+
const treeCommand = chalk.blue(
73+
`cargo tree -e features -i napi-sys --target ${target}`,
74+
);
75+
const skipFlag = chalk.blue("--skip-feature-check");
76+
assertFixable(
77+
!features.has("dyn-symbols"),
78+
`The "dyn-symbols" feature of napi-sys is enabled when building for ${target}, which loads Node-API functions at runtime instead of linking them against weak-node-api`,
79+
{
80+
instructions: [
81+
`Set ${chalk.blue("default-features = false")} on the napi dependency in Cargo.toml and enable the "napiN" features you need explicitly.`,
82+
`Run ${treeCommand} to see which dependency enables it, or pass ${skipFlag} to build anyway.`,
83+
].join("\n"),
84+
},
85+
);
86+
const version = getNodeApiVersion(features);
87+
assertFixable(
88+
version <= MAX_NODE_API_VERSION,
89+
`The "napi${version}" feature of napi-sys is enabled when building for ${target}, but React Native Node-API supports Node-API versions up to ${MAX_NODE_API_VERSION}`,
90+
{
91+
instructions: [
92+
`Enable at most the "napi${MAX_NODE_API_VERSION}" feature on the napi dependency in Cargo.toml.`,
93+
`Run ${treeCommand} to see which dependency enables it, or pass ${skipFlag} to build anyway.`,
94+
].join("\n"),
95+
},
96+
);
97+
}
98+
}

‎packages/ferric/tsconfig.json‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
{
2-
"extends": "@tsconfig/node22/tsconfig.json",
32
"compilerOptions": {
4-
"composite": true,
5-
"declarationMap": true,
6-
"outDir": "dist",
7-
"rootDir": "src",
8-
"types": ["node"]
3+
"composite": true
94
},
10-
"include": ["src/**/*.ts"],
11-
"exclude": ["**.test.ts"]
5+
"files": [],
6+
"references": [
7+
{ "path": "./tsconfig.node.json" },
8+
{ "path": "./tsconfig.node-tests.json" }
9+
]
1210
}
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
"exclude": [],
99
"references": [
1010
{
11-
"path": "./tsconfig.json"
11+
"path": "./tsconfig.node.json"
1212
}
1313
]
1414
}

‎packages/ferric/tsconfig.node.json‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"extends": "@tsconfig/node22/tsconfig.json",
3+
"compilerOptions": {
4+
"composite": true,
5+
"declarationMap": true,
6+
"outDir": "dist",
7+
"rootDir": "src",
8+
"types": ["node"]
9+
},
10+
"include": ["src/**/*.ts"],
11+
"exclude": ["**/*.test.ts"]
12+
}

0 commit comments

Comments
 (0)