chore: use root package.json for napi build (#469)

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
This commit is contained in:
Boshen
2025-04-25 11:51:50 +08:00
committed by GitHub
co-authored by autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
parent 9f328783b5
commit f1a6db6e2f
16 changed files with 427 additions and 438 deletions
+6 -8
View File
@@ -8,10 +8,7 @@ on:
branches:
- main
paths:
- npm/package.json # Please only commit this file, so we don't need to wait for test CI to pass.
env:
DEBUG: "napi:*"
- package.json
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
@@ -32,7 +29,7 @@ jobs:
with:
static-checking: localIsNew
file-url: https://unpkg.com/oxc-resolver@latest/package.json
file-name: npm/package.json
file-name: package.json
- name: Set version name
if: steps.version.outputs.changed == 'true'
@@ -219,8 +216,8 @@ jobs:
- name: Prepare dirs and artifacts
run: |
pnpm napi create-npm-dirs --package-json-path npm/package.json
pnpm napi artifacts --package-json-path npm/package.json --build-output-dir napi
pnpm napi create-npm-dirs
pnpm napi artifacts --build-output-dir napi
- name: Publish npm packages as latest
env:
@@ -231,6 +228,7 @@ jobs:
cp napi/index.js npm/index.js
cp napi/index.d.ts npm/index.d.ts
cp napi/browser.js npm/browser.js
cp package.json npm/package.json
echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc
pnpm napi pre-publish --no-gh-release -t npm --package-json-path npm/package.json
pnpm napi pre-publish --no-gh-release -t npm
npm publish npm/ --tag latest --provenance --access public
+1
View File
@@ -1,3 +1,4 @@
target/
/npm
/node_modules
fuzz/Cargo.lock
+45 -4
View File
@@ -32,6 +32,51 @@ Rust port of [enhanced-resolve].
## Usage
### npm package
See index.d.ts for `resolveSync` and `ResolverFactory` API.
Quick example:
```javascript
import assert from 'assert';
import path from 'path';
import resolve, { ResolverFactory } from './index.js';
// `resolve`
assert(resolve.sync(process.cwd(), './index.js').path, path.join(cwd, 'index.js'));
// `ResolverFactory`
const resolver = new ResolverFactory();
assert(resolver.sync(process.cwd(), './index.js').path, path.join(cwd, 'index.js'));
```
### Rust
See [docs.rs/oxc_resolver](https://docs.rs/oxc_resolver/latest/oxc_resolver).
## Terminology
### `directory`
An **absolute** path to a directory where the specifier is resolved against.
For CommonJS modules, it is the `__dirname` variable that contains the absolute path to the folder containing current module.
For ECMAScript modules, it is the value of `import.meta.url`.
Behavior is undefined when given a path to a file.
### `specifier`
The string passed to `require` or `import`, i.e. `require("specifier")` or `import "specifier"`
## Errors and Trouble Shooting
- `Error: Package subpath '.' is not defined by "exports" in` - occurs when resolving without `conditionNames`.
## Configuration
The following usages apply to both Rust and Node.js; the code snippets are written in JavaScript.
To handle the `exports` field in `package.json`, ESM and CJS need to be differentiated.
@@ -109,10 +154,6 @@ Quoting esbuild's documentation:
- `module` - This field came from a [proposal](https://github.com/dherman/defense-of-dot-js/blob/f31319be735b21739756b87d551f6711bd7aa283/proposal.md) for how to integrate ECMAScript modules into node. Because of this, it's reasonable to expect that the file path in this field is an ECMAScript-style module. This proposal wasn't adopted by node (node uses "type": "module" instead) but it was adopted by major bundlers because ECMAScript-style modules lead to better tree shaking, or dead code removal.
- `browser` - This field came from a [proposal](https://gist.github.com/defunctzombie/4339901/49493836fb873ddaa4b8a7aa0ef2352119f69211) that allows bundlers to replace node-specific files or modules with their browser-friendly versions. It lets you specify an alternate browser-specific entry point. Note that it is possible for a package to use both the browser and module field together (see the note below).
## Errors & Trouble Shooting
- `Error: Package subpath '.' is not defined by "exports" in` - occurs when resolving without `conditionNames`.
## Options
The following options are aligned with [enhanced-resolve], and is implemented for Rust crate usage.
+4
View File
@@ -11,6 +11,10 @@
},
"excludes": [
"fixtures/**",
"napi/*.js",
"napi/*.ts",
"napi/*.cjs",
"napi/*.mjs",
"CHANGELOG.md",
"pnpm-workspace.yaml",
"pnpm-lock.yaml"
-18
View File
@@ -1,18 +0,0 @@
# Installation
```bash
corepack enable
```
# Build
```bash
pnpm install
pnpm run build
```
# Test
```bash
pnpm test
```
+1 -1
View File
@@ -1 +1 @@
export * from '@oxc-resolver/binding-wasm32-wasi';
export * from '@oxc-resolver/binding-wasm32-wasi'
+38 -38
View File
@@ -1,22 +1,22 @@
/* auto-generated by NAPI-RS */
/* eslint-disable */
export declare class ResolverFactory {
constructor(options?: NapiResolveOptions | undefined | null);
static default(): ResolverFactory;
constructor(options?: NapiResolveOptions | undefined | null)
static default(): ResolverFactory
/** Clone the resolver using the same underlying cache. */
cloneWithOptions(options: NapiResolveOptions): ResolverFactory;
cloneWithOptions(options: NapiResolveOptions): ResolverFactory
/** Clear the underlying cache. */
clearCache(): void;
clearCache(): void
/** Synchronously resolve `specifier` at an absolute path to a `directory`. */
sync(directory: string, request: string): ResolveResult;
sync(directory: string, request: string): ResolveResult
/** Asynchronously resolve `specifier` at an absolute path to a `directory`. */
async(directory: string, request: string): Promise<ResolveResult>;
async(directory: string, request: string): Promise<ResolveResult>
}
export declare const enum EnforceExtension {
Auto = 0,
Enabled = 1,
Disabled = 2,
Disabled = 2
}
/**
@@ -32,7 +32,7 @@ export interface NapiResolveOptions {
*
* Default `None`
*/
tsconfig?: TsconfigOptions;
tsconfig?: TsconfigOptions
/**
* Alias for [ResolveOptions::alias] and [ResolveOptions::fallback].
*
@@ -41,7 +41,7 @@ export interface NapiResolveOptions {
* Create aliases to import or require certain modules more easily.
* A trailing $ can also be added to the given object's keys to signify an exact match.
*/
alias?: Record<string, Array<string | undefined | null>>;
alias?: Record<string, Array<string | undefined | null>>
/**
* A list of alias fields in description files.
* Specify a field, such as `browser`, to be parsed according to [this specification](https://github.com/defunctzombie/package-browser-field-spec).
@@ -49,20 +49,20 @@ export interface NapiResolveOptions {
*
* Default `[]`
*/
aliasFields?: (string | string[])[];
aliasFields?: (string | string[])[]
/**
* Condition names for exports field which defines entry points of a package.
* The key order in the exports field is significant. During condition matching, earlier entries have higher priority and take precedence over later entries.
*
* Default `[]`
*/
conditionNames?: Array<string>;
conditionNames?: Array<string>
/**
* The JSON files to use for descriptions. (There was once a `bower.json`.)
*
* Default `["package.json"]`
*/
descriptionFiles?: Array<string>;
descriptionFiles?: Array<string>
/**
* If true, it will not allow extension-less files.
* So by default `require('./foo')` works if `./foo` has a `.js` extension,
@@ -74,14 +74,14 @@ export interface NapiResolveOptions {
*
* Default None, which is the same as `Some(false)` when the above empty rule is not applied.
*/
enforceExtension?: EnforceExtension;
enforceExtension?: EnforceExtension
/**
* A list of exports fields in description files.
* Can be a path to json object such as `["path", "to", "exports"]`.
*
* Default `[["exports"]]`.
*/
exportsFields?: (string | string[])[];
exportsFields?: (string | string[])[]
/**
* Fields from `package.json` which are used to provide the internal requests of a package
* (requests starting with # are considered internal).
@@ -90,13 +90,13 @@ export interface NapiResolveOptions {
*
* Default `[["imports"]]`.
*/
importsFields?: (string | string[])[];
importsFields?: (string | string[])[]
/**
* An object which maps extension to extension aliases.
*
* Default `{}`
*/
extensionAlias?: Record<string, Array<string>>;
extensionAlias?: Record<string, Array<string>>
/**
* Attempt to resolve these extensions in order.
* If multiple files share the same name but have different extensions,
@@ -104,13 +104,13 @@ export interface NapiResolveOptions {
*
* Default `[".js", ".json", ".node"]`
*/
extensions?: Array<string>;
extensions?: Array<string>
/**
* Redirect module requests when normal resolving fails.
*
* Default `[]`
*/
fallback?: Record<string, Array<string | undefined | null>>;
fallback?: Record<string, Array<string | undefined | null>>
/**
* Request passed to resolve is already fully specified and extensions or main files are not resolved for it (they are still resolved for internal requests).
*
@@ -118,56 +118,56 @@ export interface NapiResolveOptions {
*
* Default `false`
*/
fullySpecified?: boolean;
fullySpecified?: boolean
/**
* A list of main fields in description files
*
* Default `["main"]`.
*/
mainFields?: string | string[];
mainFields?: string | string[]
/**
* The filename to be used while resolving directories.
*
* Default `["index"]`
*/
mainFiles?: Array<string>;
mainFiles?: Array<string>
/**
* A list of directories to resolve modules from, can be absolute path or folder name.
*
* Default `["node_modules"]`
*/
modules?: string | string[];
modules?: string | string[]
/**
* Resolve to a context instead of a file.
*
* Default `false`
*/
resolveToContext?: boolean;
resolveToContext?: boolean
/**
* Prefer to resolve module requests as relative requests instead of using modules from node_modules directories.
*
* Default `false`
*/
preferRelative?: boolean;
preferRelative?: boolean
/**
* Prefer to resolve server-relative urls as absolute paths before falling back to resolve in ResolveOptions::roots.
*
* Default `false`
*/
preferAbsolute?: boolean;
preferAbsolute?: boolean
/**
* A list of resolve restrictions to restrict the paths that a request can be resolved on.
*
* Default `[]`
*/
restrictions?: Array<Restriction>;
restrictions?: Array<Restriction>
/**
* A list of directories where requests of server-relative URLs (starting with '/') are resolved.
* On non-Windows systems these requests are resolved as an absolute path first.
*
* Default `[]`
*/
roots?: Array<string>;
roots?: Array<string>
/**
* Whether to resolve symlinks to their symlinked location.
* When enabled, symlinked resources are resolved to their real path, not their symlinked location.
@@ -175,22 +175,22 @@ export interface NapiResolveOptions {
*
* Default `true`
*/
symlinks?: boolean;
symlinks?: boolean
/**
* Whether to parse [module.builtinModules](https://nodejs.org/api/module.html#modulebuiltinmodules) or not.
* For example, "zlib" will throw [crate::ResolveError::Builtin] when set to true.
*
* Default `false`
*/
builtinModules?: boolean;
builtinModules?: boolean
}
export interface ResolveResult {
path?: string;
error?: string;
path?: string
error?: string
/** "type" field in the package.json file */
moduleType?: string;
packageJsonPath?: string;
moduleType?: string
packageJsonPath?: string
}
/**
@@ -198,11 +198,11 @@ export interface ResolveResult {
* Use struct because napi don't support structured union now
*/
export interface Restriction {
path?: string;
regex?: string;
path?: string
regex?: string
}
export declare function sync(path: string, request: string): ResolveResult;
export declare function sync(path: string, request: string): ResolveResult
/**
* Tsconfig Options
@@ -216,12 +216,12 @@ export interface TsconfigOptions {
* * a relative path to the configuration file. It will be resolved relative to cwd.
* * an absolute path to the configuration file.
*/
configFile: string;
configFile: string
/**
* Support for Typescript Project References.
*
* * `'auto'`: use the `references` field from tsconfig of `config_file`.
* * `string[]`: manually provided relative or absolute path.
*/
references?: 'auto' | string[];
references?: 'auto' | string[]
}
+188 -165
View File
@@ -3,61 +3,65 @@
// @ts-nocheck
/* auto-generated by NAPI-RS */
const { createRequire } = require('node:module');
require = createRequire(__filename);
const { createRequire } = require('node:module')
require = createRequire(__filename)
const { readFileSync } = require('node:fs');
let nativeBinding = null;
const loadErrors = [];
const { readFileSync } = require('node:fs')
let nativeBinding = null
const loadErrors = []
const isMusl = () => {
let musl = false;
let musl = false
if (process.platform === 'linux') {
musl = isMuslFromFilesystem();
musl = isMuslFromFilesystem()
if (musl === null) {
musl = isMuslFromReport();
musl = isMuslFromReport()
}
if (musl === null) {
musl = isMuslFromChildProcess();
musl = isMuslFromChildProcess()
}
}
return musl;
};
return musl
}
const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-');
const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-')
const isMuslFromFilesystem = () => {
try {
return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl');
return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl')
} catch {
return null;
return null
}
};
}
const isMuslFromReport = () => {
const report = typeof process.report.getReport === 'function' ? process.report.getReport() : null;
let report = null
if (typeof process.report?.getReport === 'function') {
process.report.excludeNetwork = true
report = process.report.getReport()
}
if (!report) {
return null;
return null
}
if (report.header && report.header.glibcVersionRuntime) {
return false;
return false
}
if (Array.isArray(report.sharedObjects)) {
if (report.sharedObjects.some(isFileMusl)) {
return true;
return true
}
}
return false;
};
return false
}
const isMuslFromChildProcess = () => {
try {
return require('child_process').execSync('ldd --version', { encoding: 'utf8' }).includes('musl');
return require('child_process').execSync('ldd --version', { encoding: 'utf8' }).includes('musl')
} catch (e) {
// If we reach this case, we don't know if the system is musl or not, so is better to just fallback to false
return false;
return false
}
};
}
function requireNative() {
if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) {
@@ -69,272 +73,291 @@ function requireNative() {
} else if (process.platform === 'android') {
if (process.arch === 'arm64') {
try {
return require('./resolver.android-arm64.node');
return require('./resolver.android-arm64.node')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-android-arm64');
return require('@oxc-resolver/binding-android-arm64')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
} else if (process.arch === 'arm') {
try {
return require('./resolver.android-arm-eabi.node');
return require('./resolver.android-arm-eabi.node')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-android-arm-eabi');
return require('@oxc-resolver/binding-android-arm-eabi')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
} else {
loadErrors.push(new Error(`Unsupported architecture on Android ${process.arch}`));
loadErrors.push(new Error(`Unsupported architecture on Android ${process.arch}`))
}
} else if (process.platform === 'win32') {
if (process.arch === 'x64') {
try {
return require('./resolver.win32-x64-msvc.node');
return require('./resolver.win32-x64-msvc.node')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-win32-x64-msvc');
return require('@oxc-resolver/binding-win32-x64-msvc')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
} else if (process.arch === 'ia32') {
try {
return require('./resolver.win32-ia32-msvc.node');
return require('./resolver.win32-ia32-msvc.node')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-win32-ia32-msvc');
return require('@oxc-resolver/binding-win32-ia32-msvc')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
} else if (process.arch === 'arm64') {
try {
return require('./resolver.win32-arm64-msvc.node');
return require('./resolver.win32-arm64-msvc.node')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-win32-arm64-msvc');
return require('@oxc-resolver/binding-win32-arm64-msvc')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
} else {
loadErrors.push(new Error(`Unsupported architecture on Windows: ${process.arch}`));
loadErrors.push(new Error(`Unsupported architecture on Windows: ${process.arch}`))
}
} else if (process.platform === 'darwin') {
try {
return require('./resolver.darwin-universal.node');
} catch (e) {
loadErrors.push(e);
}
try {
return require('@oxc-resolver/binding-darwin-universal');
} catch (e) {
loadErrors.push(e);
}
return require('./resolver.darwin-universal.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-darwin-universal')
} catch (e) {
loadErrors.push(e)
}
if (process.arch === 'x64') {
try {
return require('./resolver.darwin-x64.node');
return require('./resolver.darwin-x64.node')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-darwin-x64');
return require('@oxc-resolver/binding-darwin-x64')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
} else if (process.arch === 'arm64') {
try {
return require('./resolver.darwin-arm64.node');
return require('./resolver.darwin-arm64.node')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-darwin-arm64');
return require('@oxc-resolver/binding-darwin-arm64')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
} else {
loadErrors.push(new Error(`Unsupported architecture on macOS: ${process.arch}`));
loadErrors.push(new Error(`Unsupported architecture on macOS: ${process.arch}`))
}
} else if (process.platform === 'freebsd') {
if (process.arch === 'x64') {
try {
return require('./resolver.freebsd-x64.node');
return require('./resolver.freebsd-x64.node')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-freebsd-x64');
return require('@oxc-resolver/binding-freebsd-x64')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
} else if (process.arch === 'arm64') {
try {
return require('./resolver.freebsd-arm64.node');
return require('./resolver.freebsd-arm64.node')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-freebsd-arm64');
return require('@oxc-resolver/binding-freebsd-arm64')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
} else {
loadErrors.push(new Error(`Unsupported architecture on FreeBSD: ${process.arch}`));
loadErrors.push(new Error(`Unsupported architecture on FreeBSD: ${process.arch}`))
}
} else if (process.platform === 'linux') {
if (process.arch === 'x64') {
if (isMusl()) {
try {
return require('./resolver.linux-x64-musl.node');
} catch (e) {
loadErrors.push(e);
}
try {
return require('@oxc-resolver/binding-linux-x64-musl');
} catch (e) {
loadErrors.push(e);
}
return require('./resolver.linux-x64-musl.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-linux-x64-musl')
} catch (e) {
loadErrors.push(e)
}
} else {
try {
return require('./resolver.linux-x64-gnu.node');
} catch (e) {
loadErrors.push(e);
}
try {
return require('@oxc-resolver/binding-linux-x64-gnu');
} catch (e) {
loadErrors.push(e);
}
return require('./resolver.linux-x64-gnu.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-linux-x64-gnu')
} catch (e) {
loadErrors.push(e)
}
}
} else if (process.arch === 'arm64') {
if (isMusl()) {
try {
return require('./resolver.linux-arm64-musl.node');
} catch (e) {
loadErrors.push(e);
}
try {
return require('@oxc-resolver/binding-linux-arm64-musl');
} catch (e) {
loadErrors.push(e);
}
return require('./resolver.linux-arm64-musl.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-linux-arm64-musl')
} catch (e) {
loadErrors.push(e)
}
} else {
try {
return require('./resolver.linux-arm64-gnu.node');
} catch (e) {
loadErrors.push(e);
}
try {
return require('@oxc-resolver/binding-linux-arm64-gnu');
} catch (e) {
loadErrors.push(e);
}
return require('./resolver.linux-arm64-gnu.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-linux-arm64-gnu')
} catch (e) {
loadErrors.push(e)
}
}
} else if (process.arch === 'arm') {
if (isMusl()) {
try {
return require('./resolver.linux-arm-musleabihf.node');
} catch (e) {
loadErrors.push(e);
}
try {
return require('@oxc-resolver/binding-linux-arm-musleabihf');
} catch (e) {
loadErrors.push(e);
}
return require('./resolver.linux-arm-musleabihf.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-linux-arm-musleabihf')
} catch (e) {
loadErrors.push(e)
}
} else {
try {
return require('./resolver.linux-arm-gnueabihf.node');
} catch (e) {
loadErrors.push(e);
}
try {
return require('@oxc-resolver/binding-linux-arm-gnueabihf');
} catch (e) {
loadErrors.push(e);
}
return require('./resolver.linux-arm-gnueabihf.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-linux-arm-gnueabihf')
} catch (e) {
loadErrors.push(e)
}
}
} else if (process.arch === 'riscv64') {
if (isMusl()) {
try {
return require('./resolver.linux-riscv64-musl.node');
} catch (e) {
loadErrors.push(e);
}
try {
return require('@oxc-resolver/binding-linux-riscv64-musl');
} catch (e) {
loadErrors.push(e);
}
return require('./resolver.linux-riscv64-musl.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-linux-riscv64-musl')
} catch (e) {
loadErrors.push(e)
}
} else {
try {
return require('./resolver.linux-riscv64-gnu.node');
} catch (e) {
loadErrors.push(e);
}
try {
return require('@oxc-resolver/binding-linux-riscv64-gnu');
} catch (e) {
loadErrors.push(e);
}
return require('./resolver.linux-riscv64-gnu.node')
} catch (e) {
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-linux-riscv64-gnu')
} catch (e) {
loadErrors.push(e)
}
}
} else if (process.arch === 'ppc64') {
try {
return require('./resolver.linux-ppc64-gnu.node');
return require('./resolver.linux-ppc64-gnu.node')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-linux-ppc64-gnu');
return require('@oxc-resolver/binding-linux-ppc64-gnu')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
} else if (process.arch === 's390x') {
try {
return require('./resolver.linux-s390x-gnu.node');
return require('./resolver.linux-s390x-gnu.node')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
try {
return require('@oxc-resolver/binding-linux-s390x-gnu');
return require('@oxc-resolver/binding-linux-s390x-gnu')
} catch (e) {
loadErrors.push(e);
loadErrors.push(e)
}
} else {
loadErrors.push(new Error(`Unsupported architecture on Linux: ${process.arch}`));
loadErrors.push(new Error(`Unsupported architecture on Linux: ${process.arch}`))
}
} else {
loadErrors.push(new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`));
loadErrors.push(new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`))
}
}
nativeBinding = requireNative();
nativeBinding = requireNative()
if (!nativeBinding || process.env.NAPI_RS_FORCE_WASI) {
try {
nativeBinding = require('./resolver.wasi.cjs');
nativeBinding = require('./resolver.wasi.cjs')
} catch (err) {
if (process.env.NAPI_RS_FORCE_WASI) {
loadErrors.push(err);
loadErrors.push(err)
}
}
if (!nativeBinding) {
try {
nativeBinding = require('@oxc-resolver/binding-wasm32-wasi');
nativeBinding = require('@oxc-resolver/binding-wasm32-wasi')
} catch (err) {
if (process.env.NAPI_RS_FORCE_WASI) {
loadErrors.push(err);
loadErrors.push(err)
}
}
}
@@ -346,11 +369,11 @@ if (!nativeBinding) {
// - The package owner could build/publish bindings for this arch
// - The user may need to bundle the correct files
// - The user may need to re-install node_modules to get new packages
throw new Error('Failed to load native binding', { cause: loadErrors });
throw new Error('Failed to load native binding', { cause: loadErrors })
}
throw new Error(`Failed to load native binding`);
throw new Error(`Failed to load native binding`)
}
module.exports.ResolverFactory = nativeBinding.ResolverFactory;
module.exports.EnforceExtension = nativeBinding.EnforceExtension;
module.exports.sync = nativeBinding.sync;
module.exports.ResolverFactory = nativeBinding.ResolverFactory
module.exports.EnforceExtension = nativeBinding.EnforceExtension
module.exports.sync = nativeBinding.sync
+20 -20
View File
@@ -1,13 +1,13 @@
import {
createOnMessage as __wasmCreateOnMessageForFsProxy,
getDefaultContext as __emnapiGetDefaultContext,
instantiateNapiModuleSync as __emnapiInstantiateNapiModuleSync,
getDefaultContext as __emnapiGetDefaultContext,
WASI as __WASI,
} from '@napi-rs/wasm-runtime';
import { memfs } from '@napi-rs/wasm-runtime/fs';
import __wasmUrl from './resolver.wasm32-wasi.wasm?url';
createOnMessage as __wasmCreateOnMessageForFsProxy,
} from '@napi-rs/wasm-runtime'
import { memfs } from '@napi-rs/wasm-runtime/fs'
import __wasmUrl from './resolver.wasm32-wasi.wasm?url'
export const { fs: __fs, vol: __volume } = memfs();
export const { fs: __fs, vol: __volume } = memfs()
const __wasi = new __WASI({
version: 'preview1',
@@ -15,17 +15,17 @@ const __wasi = new __WASI({
preopens: {
'/': '/',
},
});
})
const __emnapiContext = __emnapiGetDefaultContext();
const __emnapiContext = __emnapiGetDefaultContext()
const __sharedMemory = new WebAssembly.Memory({
initial: 4000,
maximum: 65536,
shared: true,
});
})
const __wasmFile = await fetch(__wasmUrl).then((res) => res.arrayBuffer());
const __wasmFile = await fetch(__wasmUrl).then((res) => res.arrayBuffer())
const {
instance: __napiInstance,
@@ -38,10 +38,10 @@ const {
onCreateWorker() {
const worker = new Worker(new URL('./wasi-worker-browser.mjs', import.meta.url), {
type: 'module',
});
worker.addEventListener('message', __wasmCreateOnMessageForFsProxy(__fs));
})
worker.addEventListener('message', __wasmCreateOnMessageForFsProxy(__fs))
return worker;
return worker
},
overwriteImports(importObject) {
importObject.env = {
@@ -49,17 +49,17 @@ const {
...importObject.napi,
...importObject.emnapi,
memory: __sharedMemory,
};
return importObject;
}
return importObject
},
beforeInit({ instance }) {
for (const name of Object.keys(instance.exports)) {
if (name.startsWith('__napi_register__')) {
instance.exports[name]();
instance.exports[name]()
}
}
},
});
export const ResolverFactory = __napiModule.exports.ResolverFactory;
export const EnforceExtension = __napiModule.exports.EnforceExtension;
export const sync = __napiModule.exports.sync;
})
export const ResolverFactory = __napiModule.exports.ResolverFactory
export const EnforceExtension = __napiModule.exports.EnforceExtension
export const sync = __napiModule.exports.sync
+56 -61
View File
@@ -3,93 +3,88 @@
/* auto-generated by NAPI-RS */
const __nodeFs = require('node:fs');
const __nodePath = require('node:path');
const { WASI: __nodeWASI } = require('node:wasi');
const { Worker } = require('node:worker_threads');
const __nodeFs = require('node:fs')
const __nodePath = require('node:path')
const { WASI: __nodeWASI } = require('node:wasi')
const { Worker } = require('node:worker_threads')
const {
instantiateNapiModuleSync: __emnapiInstantiateNapiModuleSync,
getDefaultContext: __emnapiGetDefaultContext,
createOnMessage: __wasmCreateOnMessageForFsProxy,
} = require('@napi-rs/wasm-runtime');
} = require('@napi-rs/wasm-runtime')
const __rootDir = __nodePath.parse(process.cwd()).root;
const __rootDir = __nodePath.parse(process.cwd()).root
const __wasi = new __nodeWASI({
version: 'preview1',
env: process.env,
preopens: {
[__rootDir]: __rootDir,
},
});
}
})
const __emnapiContext = __emnapiGetDefaultContext();
const __emnapiContext = __emnapiGetDefaultContext()
const __sharedMemory = new WebAssembly.Memory({
initial: 4000,
maximum: 65536,
shared: true,
});
})
let __wasmFilePath = __nodePath.join(__dirname, 'resolver.wasm32-wasi.wasm');
const __wasmDebugFilePath = __nodePath.join(__dirname, 'resolver.wasm32-wasi.debug.wasm');
let __wasmFilePath = __nodePath.join(__dirname, 'resolver.wasm32-wasi.wasm')
const __wasmDebugFilePath = __nodePath.join(__dirname, 'resolver.wasm32-wasi.debug.wasm')
if (__nodeFs.existsSync(__wasmDebugFilePath)) {
__wasmFilePath = __wasmDebugFilePath;
__wasmFilePath = __wasmDebugFilePath
} else if (!__nodeFs.existsSync(__wasmFilePath)) {
try {
__wasmFilePath = __nodePath.resolve('@oxc-resolver/binding-wasm32-wasi');
__wasmFilePath = __nodePath.resolve('@oxc-resolver/binding-wasm32-wasi')
} catch {
throw new Error(
'Cannot find resolver.wasm32-wasi.wasm file, and @oxc-resolver/binding-wasm32-wasi package is not installed.',
);
throw new Error('Cannot find resolver.wasm32-wasi.wasm file, and @oxc-resolver/binding-wasm32-wasi package is not installed.')
}
}
const { instance: __napiInstance, module: __wasiModule, napiModule: __napiModule } = __emnapiInstantiateNapiModuleSync(
__nodeFs.readFileSync(__wasmFilePath),
{
context: __emnapiContext,
asyncWorkPoolSize: (function() {
const threadsSizeFromEnv = Number(process.env.NAPI_RS_ASYNC_WORK_POOL_SIZE ?? process.env.UV_THREADPOOL_SIZE);
// NaN > 0 is false
if (threadsSizeFromEnv > 0) {
return threadsSizeFromEnv;
} else {
return 4;
}
})(),
reuseWorker: true,
wasi: __wasi,
onCreateWorker() {
const worker = new Worker(__nodePath.join(__dirname, 'wasi-worker.mjs'), {
env: process.env,
});
worker.onmessage = ({ data }) => {
__wasmCreateOnMessageForFsProxy(__nodeFs)(data);
};
return worker;
},
overwriteImports(importObject) {
importObject.env = {
...importObject.env,
...importObject.napi,
...importObject.emnapi,
memory: __sharedMemory,
};
return importObject;
},
beforeInit({ instance }) {
for (const name of Object.keys(instance.exports)) {
if (name.startsWith('__napi_register__')) {
instance.exports[name]();
}
}
},
const { instance: __napiInstance, module: __wasiModule, napiModule: __napiModule } = __emnapiInstantiateNapiModuleSync(__nodeFs.readFileSync(__wasmFilePath), {
context: __emnapiContext,
asyncWorkPoolSize: (function() {
const threadsSizeFromEnv = Number(process.env.NAPI_RS_ASYNC_WORK_POOL_SIZE ?? process.env.UV_THREADPOOL_SIZE)
// NaN > 0 is false
if (threadsSizeFromEnv > 0) {
return threadsSizeFromEnv
} else {
return 4
}
})(),
reuseWorker: true,
wasi: __wasi,
onCreateWorker() {
const worker = new Worker(__nodePath.join(__dirname, 'wasi-worker.mjs'), {
env: process.env,
})
worker.onmessage = ({ data }) => {
__wasmCreateOnMessageForFsProxy(__nodeFs)(data)
}
return worker
},
);
overwriteImports(importObject) {
importObject.env = {
...importObject.env,
...importObject.napi,
...importObject.emnapi,
memory: __sharedMemory,
}
return importObject
},
beforeInit({ instance }) {
for (const name of Object.keys(instance.exports)) {
if (name.startsWith('__napi_register__')) {
instance.exports[name]()
}
}
},
})
module.exports.ResolverFactory = __napiModule.exports.ResolverFactory;
module.exports.EnforceExtension = __napiModule.exports.EnforceExtension;
module.exports.sync = __napiModule.exports.sync;
module.exports.ResolverFactory = __napiModule.exports.ResolverFactory
module.exports.EnforceExtension = __napiModule.exports.EnforceExtension
module.exports.sync = __napiModule.exports.sync
+13 -13
View File
@@ -1,7 +1,7 @@
import { createFsProxy, instantiateNapiModuleSync, MessageHandler, WASI } from '@napi-rs/wasm-runtime';
import { memfsExported as __memfsExported } from '@napi-rs/wasm-runtime/fs';
import { instantiateNapiModuleSync, MessageHandler, WASI, createFsProxy } from '@napi-rs/wasm-runtime'
import { memfsExported as __memfsExported } from '@napi-rs/wasm-runtime/fs'
const fs = createFsProxy(__memfsExported);
const fs = createFsProxy(__memfsExported)
const handler = new MessageHandler({
onLoad({ wasmModule, wasmMemory }) {
@@ -10,15 +10,15 @@ const handler = new MessageHandler({
preopens: {
'/': '/',
},
print: function() {
print: function () {
// eslint-disable-next-line no-console
console.log.apply(console, arguments);
console.log.apply(console, arguments)
},
printErr: function() {
// eslint-disable-next-line no-console
console.error.apply(console, arguments);
console.error.apply(console, arguments)
},
});
})
return instantiateNapiModuleSync(wasmModule, {
childThread: true,
wasi,
@@ -28,12 +28,12 @@ const handler = new MessageHandler({
...importObject.napi,
...importObject.emnapi,
memory: wasmMemory,
};
}
},
});
})
},
});
})
globalThis.onmessage = function(e) {
handler.handle(e);
};
globalThis.onmessage = function (e) {
handler.handle(e)
}
+12 -12
View File
@@ -1,15 +1,15 @@
import fs from 'node:fs';
import { createRequire } from 'node:module';
import { parse } from 'node:path';
import { WASI } from 'node:wasi';
import { parentPort, Worker } from 'node:worker_threads';
import fs from "node:fs";
import { createRequire } from "node:module";
import { parse } from "node:path";
import { WASI } from "node:wasi";
import { parentPort, Worker } from "node:worker_threads";
const require = createRequire(import.meta.url);
const { instantiateNapiModuleSync, MessageHandler, getDefaultContext } = require('@napi-rs/wasm-runtime');
const { instantiateNapiModuleSync, MessageHandler, getDefaultContext } = require("@napi-rs/wasm-runtime");
if (parentPort) {
parentPort.on('message', (data) => {
parentPort.on("message", (data) => {
globalThis.onmessage({ data });
});
}
@@ -18,10 +18,10 @@ Object.assign(globalThis, {
self: globalThis,
require,
Worker,
importScripts: function(f) {
(0, eval)(fs.readFileSync(f, 'utf8') + '//# sourceURL=' + f);
importScripts: function (f) {
;(0, eval)(fs.readFileSync(f, "utf8") + "//# sourceURL=" + f);
},
postMessage: function(msg) {
postMessage: function (msg) {
if (parentPort) {
parentPort.postMessage(msg);
}
@@ -51,13 +51,13 @@ const handler = new MessageHandler({
...importObject.env,
...importObject.napi,
...importObject.emnapi,
memory: wasmMemory,
memory: wasmMemory
};
},
});
},
});
globalThis.onmessage = function(e) {
globalThis.onmessage = function (e) {
handler.handle(e);
};
-4
View File
@@ -1,4 +0,0 @@
*
!package.json
!README.md
!.gitignore
-39
View File
@@ -1,39 +0,0 @@
# Oxc Resolver Napi Binding
See
- `index.d.ts` for `resolveSync` and `ResolverFactory` API.
- [README.md](https://github.com/oxc-project/oxc-resolver?tab=readme-ov-file#oxc-resolver) for options.
## API
`resolve(directory, specifier)` - resolve `specifier` at an absolute path to a `directory`.
### `directory`
An **absolute** path to a directory where the specifier is resolved against.
For CommonJS modules, it is the `__dirname` variable that contains the absolute path to the folder containing current module.
For ECMAScript modules, it is the value of `import.meta.url`.
Behavior is undefined when given a path to a file.
### `specifier`
The string passed to `require` or `import`, i.e. `require("specifier")` or `import "specifier"`
## ESM Example
```javascript
import assert from 'assert';
import path from 'path';
import resolve, { ResolverFactory } from './index.js';
// `resolve`
assert(resolve.sync(process.cwd(), './index.js').path, path.join(cwd, 'index.js'));
// `ResolverFactory`
const resolver = new ResolverFactory();
assert(resolver.sync(process.cwd(), './index.js').path, path.join(cwd, 'index.js'));
```
-49
View File
@@ -1,49 +0,0 @@
{
"name": "oxc-resolver",
"version": "6.0.0",
"description": "Oxc Resolver Node API",
"main": "index.js",
"browser": "browser.js",
"files": [
"index.d.ts",
"index.js",
"browser.js"
],
"license": "MIT",
"homepage": "https://oxc.rs",
"repository": {
"type": "git",
"url": "git+https://github.com/oxc-project/oxc-resolver.git"
},
"publishConfig": {
"registry": "https://registry.npmjs.org/",
"access": "public"
},
"napi": {
"binaryName": "resolver",
"packageName": "@oxc-resolver/binding",
"wasm": {
"browser": {
"fs": true
}
},
"targets": [
"x86_64-pc-windows-msvc",
"aarch64-pc-windows-msvc",
"x86_64-unknown-linux-gnu",
"x86_64-unknown-linux-musl",
"x86_64-unknown-freebsd",
"aarch64-unknown-linux-gnu",
"aarch64-unknown-linux-musl",
"armv7-unknown-linux-gnueabihf",
"s390x-unknown-linux-gnu",
"riscv64gc-unknown-linux-gnu",
"x86_64-apple-darwin",
"aarch64-apple-darwin",
"wasm32-wasip1-threads"
]
},
"funding": {
"url": "https://github.com/sponsors/Boshen"
}
}
+43 -6
View File
@@ -1,7 +1,10 @@
{
"name": "@oxc-resolver/binding",
"private": true,
"version": "0.0.0",
"name": "oxc-resolver",
"version": "6.0.0",
"license": "MIT",
"description": "Oxc Resolver Node API",
"packageManager": "[email protected]",
"homepage": "https://oxc.rs",
"repository": {
"type": "git",
"url": "git+https://github.com/oxc-project/oxc-resolver.git"
@@ -9,9 +12,16 @@
"funding": {
"url": "https://github.com/sponsors/Boshen"
},
"main": "index.js",
"browser": "browser.js",
"files": [
"index.d.ts",
"index.js",
"browser.js"
],
"scripts": {
"build": "napi build --platform --release --package-json-path npm/package.json --manifest-path napi/Cargo.toml",
"build:debug": "napi build --platform --package-json-path npm/package.json --manifest-path napi/Cargo.toml",
"build": "napi build --platform --release --manifest-path napi/Cargo.toml",
"build:debug": "napi build --platform --manifest-path napi/Cargo.toml",
"prepublishOnly": "napi pre-publish -t npm",
"test": "vitest run -r ./napi"
},
@@ -23,5 +33,32 @@
"typescript": "^5.8.2",
"vitest": "^3.0.8"
},
"packageManager": "[email protected]"
"publishConfig": {
"registry": "https://registry.npmjs.org/",
"access": "public"
},
"napi": {
"binaryName": "resolver",
"packageName": "@oxc-resolver/binding",
"wasm": {
"browser": {
"fs": true
}
},
"targets": [
"x86_64-pc-windows-msvc",
"aarch64-pc-windows-msvc",
"x86_64-unknown-linux-gnu",
"x86_64-unknown-linux-musl",
"x86_64-unknown-freebsd",
"aarch64-unknown-linux-gnu",
"aarch64-unknown-linux-musl",
"armv7-unknown-linux-gnueabihf",
"s390x-unknown-linux-gnu",
"riscv64gc-unknown-linux-gnu",
"x86_64-apple-darwin",
"aarch64-apple-darwin",
"wasm32-wasip1-threads"
]
}
}