Skip to content

Commit

Permalink
fix(cli,napi-derive): re-export types from shared crate
Browse files Browse the repository at this point in the history
  • Loading branch information
Brooooooklyn committed Mar 21, 2023
1 parent 3b831f4 commit 649601f
Show file tree
Hide file tree
Showing 13 changed files with 102 additions and 3 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ members = [
"./crates/napi",
"./crates/sys",
"./examples/napi",
"./examples/napi-shared",
"./examples/napi-compat-mode",
"./examples/binary",
"./bench",
Expand Down
12 changes: 12 additions & 0 deletions cli/src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import * as chalk from 'colorette'
import envPaths from 'env-paths'
import { groupBy } from 'lodash-es'

import { version } from '../package.json'

import { ARM_FEATURES_H } from './arm-features.h'
import { getNapiConfig } from './consts'
import { debugFactory } from './debug'
Expand Down Expand Up @@ -493,6 +495,7 @@ export class BuildCommand extends Command {
}
const cwdSha = createHash('sha256')
.update(process.cwd())
.update(version)
.digest('hex')
.substring(0, 8)
const intermediateTypeFile = join(
Expand Down Expand Up @@ -698,6 +701,15 @@ async function processIntermediateTypeFile(
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
.map((line) => {
// compatible with old version
if (line.startsWith('{')) {
return line
} else {
const [_crateName, ...rest] = line.split(':')
return rest.join(':')
}
})

if (!lines.length) {
return idents
Expand Down
4 changes: 3 additions & 1 deletion crates/backend/src/typegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ fn escape_json(src: &str) -> String {

impl ToString for TypeDef {
fn to_string(&self) -> String {
let pkg_name = std::env::var("CARGO_PKG_NAME").expect("CARGO_PKG_NAME is not set");
let js_mod = if let Some(js_mod) = &self.js_mod {
format!(", \"js_mod\": \"{}\"", js_mod)
} else {
Expand All @@ -103,7 +104,8 @@ impl ToString for TypeDef {
"".to_owned()
};
format!(
r#"{{"kind": "{}", "name": "{}", "js_doc": "{}", "def": "{}"{}{}}}"#,
r#"{}:{{"kind": "{}", "name": "{}", "js_doc": "{}", "def": "{}"{}{}}}"#,
pkg_name,
self.kind,
self.name,
escape_json(&self.js_doc),
Expand Down
39 changes: 37 additions & 2 deletions crates/macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ pub fn napi(attr: RawStream, input: RawStream) -> RawStream {
{
// logic on first macro expansion
#[cfg(feature = "type-def")]
if let Ok(type_def_file) = env::var("TYPE_DEF_TMP_PATH") {
if let Err(_e) = fs::remove_file(type_def_file) {
if let Ok(ref type_def_file) = env::var("TYPE_DEF_TMP_PATH") {
if let Err(_e) = remove_existed_type_def(type_def_file) {
#[cfg(debug_assertions)]
{
println!("Failed to manipulate type def file: {:?}", _e);
Expand Down Expand Up @@ -432,3 +432,38 @@ fn replace_napi_attr_in_mod(
None
}
}

#[cfg(all(feature = "type-def", not(feature = "noop")))]
fn remove_existed_type_def(type_def_file: &str) -> std::io::Result<()> {
use std::io::{BufRead, BufReader};

let pkg_name = std::env::var("CARGO_PKG_NAME").expect("CARGO_PKG_NAME is not set");
if let Ok(content) = std::fs::File::open(type_def_file) {
let reader = BufReader::new(content);
let cleaned_content = reader
.lines()
.filter_map(|line| {
if let Ok(line) = line {
if let Some((package_name, _)) = line.split_once(':') {
if pkg_name == package_name {
return None;
}
}
Some(line)
} else {
None
}
})
.collect::<Vec<String>>()
.join("\n");
let mut content = std::fs::OpenOptions::new()
.read(true)
.write(true)
.truncate(true)
.open(type_def_file)?;

content.write_all(cleaned_content.as_bytes())?;
content.write(b"\n")?;
}
Ok(())
}
22 changes: 22 additions & 0 deletions examples/napi-shared/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[package]
authors = ["LongYinan <lynweklm@gmail.com>"]
edition = "2021"
name = "napi-shared"
publish = false
version = "0.1.0"

[dependencies]
napi = { path = "../../crates/napi", default-features = false, features = [
"tokio_fs",
"napi8",
"tokio_rt",
"serde-json",
"async",
"experimental",
"latin1",
"chrono_date",
] }
napi-derive = { path = "../../crates/macro", features = ["type-def"] }

[build-dependencies]
napi-build = { path = "../../crates/build" }
6 changes: 6 additions & 0 deletions examples/napi-shared/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
use napi_derive::napi;

#[napi(object)]
pub struct Shared {
pub value: u32,
}
1 change: 1 addition & 0 deletions examples/napi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ napi = { path = "../../crates/napi", default-features = false, features = [
"chrono_date",
] }
napi-derive = { path = "../../crates/macro", features = ["type-def"] }
napi-shared = { path = "../napi-shared" }
serde = "1"
serde_derive = "1"
serde_json = "1"
Expand Down
4 changes: 4 additions & 0 deletions examples/napi/__test__/typegen.spec.ts.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ Generated by [AVA](https://avajs.dev).
[K: symbol]: T␊
}␊
}␊
export interface Shared {␊
value: number␊
}␊
/** This is a const */␊
export const DEFAULT_COST: number␊
export function getWords(): Array<string>␊
Expand Down Expand Up @@ -192,6 +195,7 @@ Generated by [AVA](https://avajs.dev).
export function readPackageJson(): PackageJson␊
export function getPackageJsonName(packageJson: PackageJson): string␊
export function testSerdeRoundtrip(data: any): any␊
export function returnFromSharedCrate(): Shared␊
export function contains(source: string, target: string): boolean␊
export function concatStr(s: string): string␊
export function concatUtf16(s: string): string␊
Expand Down
Binary file modified examples/napi/__test__/typegen.spec.ts.snap
Binary file not shown.
7 changes: 7 additions & 0 deletions examples/napi/__test__/values.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ import {
runScript,
tsfnReturnPromise,
tsfnReturnPromiseTimeout,
returnFromSharedCrate,
} from '../'

test('export const', (t) => {
Expand Down Expand Up @@ -650,6 +651,12 @@ test('should be able to run script', async (t) => {
t.is(await runScript(`Promise.resolve(1)`), 1)
})

test('should be able to return object from shared crate', (t) => {
t.deepEqual(returnFromSharedCrate(), {
value: 42,
})
})

const AbortSignalTest =
typeof AbortController !== 'undefined' ? test : test.skip

Expand Down
1 change: 1 addition & 0 deletions examples/napi/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ export interface PackageJson {
export function readPackageJson(): PackageJson
export function getPackageJsonName(packageJson: PackageJson): string
export function testSerdeRoundtrip(data: any): any
export function returnFromSharedCrate(): Shared
export function contains(source: string, target: string): boolean
export function concatStr(s: string): string
export function concatUtf16(s: string): string
Expand Down
1 change: 1 addition & 0 deletions examples/napi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ mod object;
mod promise;
mod reference;
mod serde;
mod shared;
mod string;
mod symbol;
mod task;
Expand Down
7 changes: 7 additions & 0 deletions examples/napi/src/shared.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use napi_derive::napi;
use napi_shared::Shared;

#[napi]
pub fn return_from_shared_crate() -> Shared {
Shared { value: 42 }
}

1 comment on commit 649601f

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Benchmark

Benchmark suite Current: 649601f Previous: 3b831f4 Ratio
noop#napi-rs 63029175 ops/sec (±0.44%) 49256299 ops/sec (±1.23%) 0.78
noop#JavaScript 710236800 ops/sec (±0.15%) 729666474 ops/sec (±0.95%) 1.03
Plus number#napi-rs 18644731 ops/sec (±0.26%) 14677733 ops/sec (±0.96%) 0.79
Plus number#JavaScript 706630396 ops/sec (±0.3%) 696004559 ops/sec (±1.06%) 0.98
Create buffer#napi-rs 374687 ops/sec (±10.61%) 316631 ops/sec (±9.79%) 0.85
Create buffer#JavaScript 1877453 ops/sec (±8.21%) 1472552 ops/sec (±6.88%) 0.78
createArray#createArrayJson 39440 ops/sec (±0.55%) 32700 ops/sec (±0.99%) 0.83
createArray#create array for loop 7503 ops/sec (±0.12%) 6001 ops/sec (±0.88%) 0.80
createArray#create array with serde trait 7522 ops/sec (±0.12%) 6151 ops/sec (±0.77%) 0.82
getArrayFromJs#get array from json string 16611 ops/sec (±0.45%) 14300 ops/sec (±0.95%) 0.86
getArrayFromJs#get array from serde 10269 ops/sec (±0.03%) 8369 ops/sec (±1.05%) 0.81
getArrayFromJs#get array with for loop 12612 ops/sec (±0.08%) 10193 ops/sec (±1.25%) 0.81
Get Set property#Get Set from native#u32 426650 ops/sec (±9.59%) 387711 ops/sec (±8.4%) 0.91
Get Set property#Get Set from JavaScript#u32 379461 ops/sec (±10.79%) 341191 ops/sec (±9.69%) 0.90
Get Set property#Get Set from native#string 401215 ops/sec (±17.54%) 371833 ops/sec (±4.07%) 0.93
Get Set property#Get Set from JavaScript#string 381228 ops/sec (±3.91%) 310627 ops/sec (±14.99%) 0.81
Async task#spawn task 37246 ops/sec (±1%) 27194 ops/sec (±3.62%) 0.73
Async task#ThreadSafeFunction 2009 ops/sec (±13.46%) 1493 ops/sec (±3.3%) 0.74
Async task#Tokio future to Promise 33357 ops/sec (±1.28%) 27053 ops/sec (±2%) 0.81
Query#query * 100 2096 ops/sec (±2.55%) 1546 ops/sec (±2.17%) 0.74
Query#query * 1 31844 ops/sec (±0.48%) 21866 ops/sec (±2.53%) 0.69

This comment was automatically generated by workflow using github-action-benchmark.

Please sign in to comment.