Repository: awslabs/llrt
File: llrt_core/src/vm.rs (Rust)

Code before:
        res
    }
}

fn set_import_meta(module: &Module<'_>, filepath: &str) -> Result<()> {
    let meta: Object = module.meta()?;
    meta.prop("url", ["file://", filepath].concat())?;
    Ok(())
}

pub fn get_module_path_in_node_modules(ctx: &Ctx<'_>, specifier: &str) -> Result<String> {
    let ex = Exception::throw_reference(ctx, &format!("Error resolving module '{}'", specifier));
    let current_dir = env::current_dir()
        .map(|path| path.display().to_string())
        .unwrap_or_default();

    let (mut scope, mut name) = match specifier.split_once('/') {
        Some((s, n)) => (s, ["./", n].concat()),
        None => (specifier, ".".to_string()),
    };

    let mut package_json_path = [&current_dir, "/node_modules/", scope, "/package.json"].concat();
    if !Path::new(&package_json_path).exists() && name != "." {
        scope = specifier;
        name = ".".to_string();
        package_json_path = [&current_dir, "/node_modules/", scope, "/package.json"].concat();
    }

    let package_json = fs::read_to_string(&package_json_path).unwrap_or_default();
    let package_json: JsonValue = serde_json::from_str(&package_json).map_err(|_| ex)?;

    let module_path = (package_json["exports"][name.as_str()]["require"]["default"].as_str())
        .or_else(|| package_json["exports"][name.as_str()]["require"].as_str())
        .or_else(|| package_json["exports"]["require"]["default"].as_str())
        .or_else(|| package_json["exports"]["default"].as_str())
        .or_else(|| package_json["main"].as_str())
        .unwrap_or("./index.js");

    Ok([&current_dir, "/node_modules/", scope, "/", module_path].concat())
}


Review comment (suggestion):
Since the prefix `[&current_dir, "/node_modules/"` is always the same, we can truncate and push instead to potentially avoid allocations

Code after:
        if c_str.is_null() {
            qjs::JS_FreeCString(ctx_ptr, c_str);
            return String::from(".");
        }
        let bytes = CStr::from_ptr(c_str).to_bytes();
        let res = std::str::from_utf8_unchecked(bytes).to_string();
        qjs::JS_FreeCString(ctx_ptr, c_str);
        res
    }
}

fn set_import_meta(module: &Module<'_>, filepath: &str) -> Result<()> {
    let meta: Object = module.meta()?;
    meta.prop("url", ["file://", filepath].concat())?;
    Ok(())
}

fn get_module_path_in_node_modules(ctx: &Ctx<'_>, specifier: &str) -> Result<String> {
    let current_dir = env::current_dir()
        .ok()
        .and_then(|path| path.into_os_string().into_string().ok())
        .unwrap_or_else(|| "/".to_string());

    let (scope, name) = match specifier.split_once('/') {
        Some((s, n)) => (s, ["./", n].concat()),
        None => (specifier, ".".to_string()),
    };

    let mut package_json_path = [&current_dir, "/node_modules/"].concat();
    let base_path_length = package_json_path.len();
    package_json_path.push_str(scope);
    package_json_path.push_str("/package.json");

    let (scope, name) = if name != "." && !Path::new(&package_json_path).exists() {
        package_json_path.truncate(base_path_length);
        package_json_path.push_str(specifier);
        package_json_path.push_str("/package.json");
        (specifier, ".")
    } else {
        (scope, name.as_str())
    };

    if !Path::new(&package_json_path).exists() {
        return Err(Exception::throw_reference(
            ctx,
            &["Error resolving module '", specifier, "'"].concat(),
        ));
    };

    let mut package_json = fs::read(&package_json_path).unwrap_or_default();
    let package_json = simd_json::to_borrowed_value(&mut package_json).or_throw(ctx)?;