From 921120ad501277e2d7630076d8424f769a789f17 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Mon, 1 Jul 2024 12:18:45 +0200 Subject: [PATCH 1/7] build: overhaul lib for better esm utilization --- eslint.config.mjs | 3 +- lib/index.js | 18 --- bin/jiti.js => lib/jiti-cli.mjs | 6 +- lib/jiti.cjs | 21 +++ lib/jiti.d.cts | 8 ++ lib/jiti.d.mts | 8 ++ lib/jiti.mjs | 20 +++ lib/types.d.ts | 125 ++++++++++++++++++ package.json | 28 ++-- pnpm-lock.yaml | 11 -- register.cjs | 3 + register.js | 3 - src/babel.ts | 4 +- src/jiti.ts | 13 +- src/options.ts | 9 +- src/types.ts | 64 ++------- ...babel-codeframe.js => babel-codeframe.mjs} | 0 ...gets.js => helper-compilation-targets.mjs} | 0 test/__snapshots__/fixtures.test.ts.snap | 23 ++-- test/bun.test.ts | 4 +- test/fixtures.test.ts | 2 +- test/fixtures/package.json | 3 + tsconfig.json | 5 +- webpack.config.js => webpack.config.mjs | 24 ++-- 24 files changed, 258 insertions(+), 147 deletions(-) delete mode 100644 lib/index.js rename bin/jiti.js => lib/jiti-cli.mjs (74%) create mode 100644 lib/jiti.cjs create mode 100644 lib/jiti.d.cts create mode 100644 lib/jiti.d.mts create mode 100644 lib/jiti.mjs create mode 100644 lib/types.d.ts create mode 100644 register.cjs delete mode 100644 register.js rename stubs/{babel-codeframe.js => babel-codeframe.mjs} (100%) rename stubs/{helper-compilation-targets.js => helper-compilation-targets.mjs} (100%) create mode 100644 test/fixtures/package.json rename webpack.config.js => webpack.config.mjs (63%) diff --git a/eslint.config.mjs b/eslint.config.mjs index 44aaf400..7484f390 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -6,6 +6,7 @@ export default unjs({ ], rules: { "unicorn/no-null": 0, - "unicorn/prefer-top-level-await": 0 + "unicorn/prefer-top-level-await": 0, + "unicorn/prefer-export-from": 0 }, }); diff --git a/lib/index.js b/lib/index.js deleted file mode 100644 index 48dfa55a..00000000 --- a/lib/index.js +++ /dev/null @@ -1,18 +0,0 @@ -function onError(err) { - throw err; /* ↓ Check stack trace ↓ */ -} - -module.exports = function createJiti(filename, opts = {}) { - const _createJITI = require("../dist/jiti"); - - if (!opts.transform) { - opts.transform = require("../dist/babel"); - } - - const nativeImport = (id) => import(id); - - return _createJITI(filename, opts, { - onError, - nativeImport, - }); -}; diff --git a/bin/jiti.js b/lib/jiti-cli.mjs similarity index 74% rename from bin/jiti.js rename to lib/jiti-cli.mjs index 29a44ed7..4f726bc7 100755 --- a/bin/jiti.js +++ b/lib/jiti-cli.mjs @@ -1,6 +1,7 @@ #!/usr/bin/env node -const { resolve } = require("node:path"); +import { resolve } from "node:path"; +import createJiti from "./jiti.cjs"; const script = process.argv.splice(2, 1)[0]; @@ -10,8 +11,7 @@ if (!script) { } const pwd = process.cwd(); -const jiti = require("..")(pwd); +const jiti = createJiti(pwd); const resolved = (process.argv[1] = jiti.resolve(resolve(pwd, script))); - jiti.import(resolved).catch(console.error); diff --git a/lib/jiti.cjs b/lib/jiti.cjs new file mode 100644 index 00000000..9aca5dd1 --- /dev/null +++ b/lib/jiti.cjs @@ -0,0 +1,21 @@ +const _createJiti = require("../dist/jiti.cjs"); +const transform = require("../dist/babel.cjs"); + +function onError(err) { + throw err; /* ↓ Check stack trace ↓ */ +} + +const nativeImport = (id) => import(id); + +function createJiti(id, opts = {}) { + if (!opts.transform) { + opts = { ...opts, transform }; + } + return _createJiti(id, opts, { + onError, + nativeImport, + }); +} + +module.exports = createJiti; +module.exports.createJiti = createJiti; diff --git a/lib/jiti.d.cts b/lib/jiti.d.cts new file mode 100644 index 00000000..c7a7165d --- /dev/null +++ b/lib/jiti.d.cts @@ -0,0 +1,8 @@ +import type { createJiti } from "./types"; + +export * from "./types"; + +/** + * @deprecated Please use `const { createJiti } = require("jiti")` or use ESM import. + */ +export default createJiti; diff --git a/lib/jiti.d.mts b/lib/jiti.d.mts new file mode 100644 index 00000000..1ca5451e --- /dev/null +++ b/lib/jiti.d.mts @@ -0,0 +1,8 @@ +import type { createJiti } from "./types"; + +export * from "./types"; + +/** + * @deprecated Please use `import { createJiti } from "jiti"` + */ +export default createJiti; diff --git a/lib/jiti.mjs b/lib/jiti.mjs new file mode 100644 index 00000000..c121c9f8 --- /dev/null +++ b/lib/jiti.mjs @@ -0,0 +1,20 @@ +import _createJiti from "../dist/jiti.cjs"; +import transform from "../dist/babel.cjs"; + +function onError(err) { + throw err; /* ↓ Check stack trace ↓ */ +} + +const nativeImport = (id) => import(id); + +export function createJiti(id, opts = {}) { + if (!opts.transform) { + opts = { ...opts, transform }; + } + return _createJiti(id, opts, { + onError, + nativeImport, + }); +} + +export default createJiti; diff --git a/lib/types.d.ts b/lib/types.d.ts new file mode 100644 index 00000000..5c272215 --- /dev/null +++ b/lib/types.d.ts @@ -0,0 +1,125 @@ +export declare function createJiti(id: string, userOptions?: JitiOptions): Jiti; + +/** + * Jiti instance + * + * Calling jiti() is similar to CommonJS require() but adds extra features such as Typescript and ESM compatibility. + * + * **Note:**It is recommended to use `await jiti.import` instead + */ +export interface Jiti extends NodeRequire { + /** + * ESM import a module with additional Typescript and ESM compatibility. + */ + import: (id: string) => Promise; + /** + * Transform source code + */ + transform: (opts: TransformOptions) => string; + /** + * Register global (CommonJS) require hook + */ + register: () => () => void; + /** + * Evaluate transformed code as a module + */ + evalModule: (source: string, options?: EvalModuleOptions) => unknown; +} + +/** + * Jiti instance options + */ +export interface JitiOptions { + /** + * Custom transform function + */ + transform?: (opts: TransformOptions) => TransformResult; + + /** + * Enable verbose debugging (disabled by default). + * + * Can also be enabled using `JITI_DEBUG=1` environment variable. + */ + debug?: boolean; + + /** + * Enable hard-source caching with HMR support (enabled by default). + * + * Can also be disabled using `JITI_CACHE=0` environment variable. + * + * **Note:** It is recommended to keep this option enabled for performance. + */ + cache?: boolean | string; + + /** + * Enable sourcemaps (enabled by default) + * + * Can also be disabled using `JITI_SOURCE_MAPS=0` environment variable. + */ + sourceMaps?: boolean; + + /** + * Enable CommonJS require cache integration (enabled by default) + * + * Disabling allows requiring same module multiple times. + * + * Can also be disabled using `JITI_REQUIRE_CACHE=0` environment variable. + */ + requireCache?: boolean; + + /** + * Interop default export (disabled by default) + */ + interopDefault?: boolean; + + /** + * Jiti hard source cache version (internal) + */ + cacheVersion?: string; + + /** + * Supported extensions to resolve. + * + * Default `[".js", ".mjs", ".cjs", ".ts", ".mts", ".cts", ".json"]` + */ + extensions?: string[]; + + /** + * Transform options + */ + transformOptions?: Omit; + + /** + * Resolve aliases + */ + alias?: Record; + + nativeModules?: string[]; + + transformModules?: string[]; + experimentalBun?: boolean; +} + +export type ModuleCache = Record; + +export type EvalModuleOptions = Partial<{ + id: string; + filename: string; + ext: string; + cache: ModuleCache; + async: boolean; +}>; + +export interface TransformOptions { + source: string; + filename?: string; + ts?: boolean; + retainLines?: boolean; + async: boolean; + [key: string]: any; +} + +export interface TransformResult { + code: string; + error?: any; +} diff --git a/package.json b/package.json index 17ea30b3..08f7a002 100644 --- a/package.json +++ b/package.json @@ -4,28 +4,36 @@ "description": "Runtime typescript and ESM support for Node.js", "repository": "unjs/jiti", "license": "MIT", + "type": "module", "exports": { ".": { - "types": "./dist/jiti.d.ts", - "default": "./lib/index.js" - } + "import": { + "types": "./lib/jiti.d.mts", + "default": "./lib/jiti.mjs" + }, + "require": { + "types": "./lib/jiti.d.cts", + "default": "./lib/jiti.cjs" + } + }, + "./package.json": "./package.json" }, - "main": "./lib/index.js", - "types": "./dist/jiti.d.ts", + "main": "./lib/jiti.cjs", + "module": "./lib/jiti.mjs", + "types": "./lib/jiti.d.mts", "bin": { - "jiti": "bin/jiti.js" + "jiti": "./lib/jiti-cli.mjs" }, "files": [ "lib", "dist", - "register.js" + "register.cjs" ], "scripts": { "build": "pnpm clean && NODE_ENV=production pnpm webpack", "clean": "rm -rf dist", "dev": "pnpm clean && pnpm webpack --watch", - "jiti": "JITI_DEBUG=1 JITI_CACHE=false JITI_REQUIRE_CACHE=false ./bin/jiti.js", - "jiti:legacy": "JITI_DEBUG=1 npx node@12 ./bin/jiti.js", + "jiti": "JITI_DEBUG=1 JITI_CACHE=false JITI_REQUIRE_CACHE=false ./lib/jiti-cli.mjs", "lint": "eslint . && prettier -c src lib test stubs", "lint:fix": "eslint --fix . && prettier -w src lib test stubs", "release": "pnpm build && pnpm test && changelogen --release --prerelease --push --publish --publishTag 2x", @@ -50,7 +58,6 @@ "@types/node": "^20.14.9", "@types/object-hash": "^3.0.6", "@types/resolve": "^1.20.6", - "@types/semver": "^7.5.8", "@vitest/coverage-v8": "^1.6.0", "acorn": "^8.12.0", "babel-plugin-parameter-decorator": "^1.0.16", @@ -73,7 +80,6 @@ "pkg-types": "^1.1.1", "prettier": "^3.3.2", "reflect-metadata": "^0.2.1", - "semver": "^7.6.2", "std-env": "^3.7.0", "terser-webpack-plugin": "^5.3.10", "ts-loader": "^9.5.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ca189338..17639262 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -59,9 +59,6 @@ importers: '@types/resolve': specifier: ^1.20.6 version: 1.20.6 - '@types/semver': - specifier: ^7.5.8 - version: 7.5.8 '@vitest/coverage-v8': specifier: ^1.6.0 version: 1.6.0(vitest@1.6.0(@types/node@20.14.9)(terser@5.31.0)) @@ -128,9 +125,6 @@ importers: reflect-metadata: specifier: ^0.2.1 version: 0.2.2 - semver: - specifier: ^7.6.2 - version: 7.6.2 std-env: specifier: ^3.7.0 version: 3.7.0 @@ -724,9 +718,6 @@ packages: '@types/resolve@1.20.6': resolution: {integrity: sha512-A4STmOXPhMUtHH+S6ymgE2GiBSMqf4oTvcQZMcHzokuTLVYzXTB8ttjcgxOVaAp2lGwEdzZ0J+cRbbeevQj1UQ==} - '@types/semver@7.5.8': - resolution: {integrity: sha512-I8EUhyrgfLrcTkzV3TSsGyl1tSuPrEDzr0yd5m90UgNxQkyDXULk3b6MlQqTCpZpNtWe1K0hzclnZkTcLBe2UQ==} - '@types/unist@2.0.10': resolution: {integrity: sha512-IfYcSBWE3hLpBg8+X2SEa8LVkJdJEkT2Ese2aaLs3ptGdVtABxndrMaxuFlQ1qdFf9Q5rDvDpxI3WwgvKFAsQA==} @@ -3002,8 +2993,6 @@ snapshots: '@types/resolve@1.20.6': {} - '@types/semver@7.5.8': {} - '@types/unist@2.0.10': {} '@typescript-eslint/eslint-plugin@7.12.0(@typescript-eslint/parser@7.12.0(eslint@9.5.0)(typescript@5.5.2))(eslint@9.5.0)(typescript@5.5.2)': diff --git a/register.cjs b/register.cjs new file mode 100644 index 00000000..7f790b30 --- /dev/null +++ b/register.cjs @@ -0,0 +1,3 @@ +const jiti = require("./lib/jiti.cjs")(); + +jiti.register(); diff --git a/register.js b/register.js deleted file mode 100644 index 60aaeb3d..00000000 --- a/register.js +++ /dev/null @@ -1,3 +0,0 @@ -const jiti = require(".")(); - -jiti.register(); diff --git a/src/babel.ts b/src/babel.ts index 4fa42b79..e85cee17 100644 --- a/src/babel.ts +++ b/src/babel.ts @@ -3,12 +3,12 @@ import type { TransformOptions as BabelTransformOptions, PluginItem, } from "@babel/core"; -import { TransformOptions, TRANSFORM_RESULT } from "./types"; +import { TransformOptions, TransformResult } from "./types"; import { TransformImportMetaPlugin } from "./plugins/babel-plugin-transform-import-meta"; import { importMetaEnvPlugin } from "./plugins/import-meta-env"; import transformModulesPlugin from "./plugins/transform-module"; -export default function transform(opts: TransformOptions): TRANSFORM_RESULT { +export default function transform(opts: TransformOptions): TransformResult { const _opts: BabelTransformOptions & { plugins: PluginItem[] } = { babelrc: false, configFile: false, diff --git a/src/jiti.ts b/src/jiti.ts index 48837e24..f4a9a751 100644 --- a/src/jiti.ts +++ b/src/jiti.ts @@ -1,7 +1,7 @@ import type { - JITI, + Jiti, TransformOptions, - JITIOptions, + JitiOptions, Context, EvalModuleOptions, } from "./types"; @@ -20,18 +20,16 @@ import { transform } from "./transform"; import { jitiRequire } from "./require"; import { prepareCacheDir } from "./cache"; -export type { JITI, JITIOptions, TransformOptions } from "./types"; - const isWindows = platform() === "win32"; export default function createJITI( filename: string, - userOptions: JITIOptions = {}, + userOptions: JitiOptions = {}, _internal?: Pick< Context, "parentModule" | "parentCache" | "nativeImport" | "onError" >, -): JITI { +): Jiti { // Resolve options const opts = resolveJitiOptions(userOptions); @@ -80,7 +78,6 @@ export default function createJITI( const ctx: Context = { filename, url, - userOptions, opts, alias, nativeModules, @@ -99,7 +96,7 @@ export default function createJITI( prepareCacheDir(ctx); // Create jiti instance - const jiti: JITI = Object.assign( + const jiti: Jiti = Object.assign( function jiti(id: string) { return jitiRequire(ctx, id, false /* no async */); }, diff --git a/src/options.ts b/src/options.ts index 853f357f..41f65adc 100644 --- a/src/options.ts +++ b/src/options.ts @@ -1,8 +1,7 @@ import { destr } from "destr"; -import { lt } from "semver"; import objectHash from "object-hash"; -import type { JITIOptions } from "./types"; +import type { JitiOptions } from "./types"; const _EnvDebug = destr(process.env.JITI_DEBUG); const _EnvCache = destr(process.env.JITI_CACHE); @@ -13,7 +12,7 @@ const _EnvTransform = destr(process.env.JITI_TRANSFORM_MODULES); const _EnvNative = destr(process.env.JITI_NATIVE_MODULES); const _ExpBun = destr(process.env.JITI_EXPERIMENTAL_BUN); -const jitiDefaults: JITIOptions = { +const jitiDefaults: JitiOptions = { debug: _EnvDebug, cache: _EnvCache === undefined ? true : !!_EnvCache, requireCache: _EnvRequireCache === undefined ? true : !!_EnvRequireCache, @@ -27,8 +26,8 @@ const jitiDefaults: JITIOptions = { experimentalBun: _ExpBun === undefined ? !!process.versions.bun : !!_ExpBun, }; -export function resolveJitiOptions(userOptions: JITIOptions): JITIOptions { - const opts: JITIOptions = { ...jitiDefaults, ...userOptions }; +export function resolveJitiOptions(userOptions: JitiOptions): JitiOptions { + const opts: JitiOptions = { ...jitiDefaults, ...userOptions }; // Cache dependencies if (opts.transformOptions) { diff --git a/src/types.ts b/src/types.ts index a5d11d3d..8f2f5c92 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,32 +1,21 @@ -export type ModuleCache = Record; - -export type EvalModuleOptions = Partial<{ - id: string; - filename: string; - ext: string; - cache: ModuleCache; - async: boolean; -}>; - -export interface JITI extends NodeRequire { - transform: (opts: TransformOptions) => string; - register: () => () => void; - evalModule: (source: string, options?: EvalModuleOptions) => unknown; - /** @experimental Behavior of `jiti.import` might change in the future. */ - import: (id: string) => Promise; -} - -type ESMImport = (id: string) => Promise; +import type { JitiOptions, ModuleCache } from "../lib/types"; +export type { + JitiOptions, + ModuleCache, + EvalModuleOptions, + Jiti, + TransformOptions, + TransformResult, +} from "../lib/types"; export interface Context { filename: string; url: URL; - userOptions: JITIOptions; parentModule?: NodeModule; parentCache?: ModuleCache; - nativeImport?: ESMImport; + nativeImport?: (id: string) => Promise; onError?: (error: Error) => void; - opts: JITIOptions; + opts: JitiOptions; nativeModules: string[]; transformModules: string[]; isNativeRe: RegExp; @@ -35,34 +24,3 @@ export interface Context { additionalExts: string[]; nativeRequire: NodeRequire; } - -export type TransformOptions = { - source: string; - filename?: string; - ts?: boolean; - retainLines?: boolean; - async: boolean; - [key: string]: any; -}; - -export type TRANSFORM_RESULT = { - code: string; - error?: any; -}; - -export type JITIOptions = { - transform?: (opts: TransformOptions) => TRANSFORM_RESULT; - debug?: boolean; - cache?: boolean | string; - sourceMaps?: boolean; - requireCache?: boolean; - v8cache?: boolean; - interopDefault?: boolean; - cacheVersion?: string; - extensions?: string[]; - transformOptions?: Omit; - alias?: Record; - nativeModules?: string[]; - transformModules?: string[]; - experimentalBun?: boolean; -}; diff --git a/stubs/babel-codeframe.js b/stubs/babel-codeframe.mjs similarity index 100% rename from stubs/babel-codeframe.js rename to stubs/babel-codeframe.mjs diff --git a/stubs/helper-compilation-targets.js b/stubs/helper-compilation-targets.mjs similarity index 100% rename from stubs/helper-compilation-targets.js rename to stubs/helper-compilation-targets.mjs diff --git a/test/__snapshots__/fixtures.test.ts.snap b/test/__snapshots__/fixtures.test.ts.snap index 6c74bf49..f8535021 100644 --- a/test/__snapshots__/fixtures.test.ts.snap +++ b/test/__snapshots__/fixtures.test.ts.snap @@ -26,21 +26,18 @@ exports[`fixtures > error-runtime > stderr 1`] = ` at _addListener (events) at process.addListener (events) at /index.ts - at evalModule (/dist/jiti) - at jitiRequire (/dist/jiti) - at Function. (/dist/jiti) + at evalModule (/dist/jiti.cjs) + at jitiRequire (/dist/jiti.cjs) + at Function. (/dist/jiti.cjs) at Generator.next () - at /dist/jiti.js + at /dist/jiti.cjs at new Promise () - at __awaiter (/dist/jiti) - at Function.import (/dist/jiti) - at Object. (/bin/jiti) - at Module._compile (internal/modules/cjs/loader) - at Module._extensions..js (internal/modules/cjs/loader) - at Module.load (internal/modules/cjs/loader) - at Module._load (internal/modules/cjs/loader) - at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main) - at internal/main/run_main_module { + at __awaiter (/dist/jiti.cjs) + at Function.import (/dist/jiti.cjs) + at file:///lib/jiti-cli.mjs + at ModuleJob.run (internal/modules/esm/module_job) + at async ModuleLoader.import (internal/modules/esm/loader) + at async asyncRunEntryPointWithESMLoader (internal/modules/run_main) { code: 'ERR_INVALID_ARG_TYPE' }" `; diff --git a/test/bun.test.ts b/test/bun.test.ts index f0f90d04..c782c6ac 100644 --- a/test/bun.test.ts +++ b/test/bun.test.ts @@ -4,13 +4,13 @@ import { join } from "node:path"; // @ts-ignore import { test, expect } from "bun:test"; -import jiti from "../lib/index.js"; +import { createJITI } from "../lib/jiti.cjs"; const fixturesDir = fileURLToPath(new URL("fixtures", import.meta.url)); const fixtures = await readdir(fixturesDir); -const _jiti = jiti(fixturesDir, { +const _jiti = createJITI(fixturesDir, { debug: true, interopDefault: true, requireCache: false, diff --git a/test/fixtures.test.ts b/test/fixtures.test.ts index 21ee14da..f82c0032 100644 --- a/test/fixtures.test.ts +++ b/test/fixtures.test.ts @@ -4,7 +4,7 @@ import { describe, it, expect } from "vitest"; import fg from "fast-glob"; describe("fixtures", async () => { - const jitiPath = resolve(__dirname, "../bin/jiti.js"); + const jitiPath = resolve(__dirname, "../lib/jiti-cli.mjs"); const root = dirname(__dirname); const dir = join(__dirname, "fixtures"); diff --git a/test/fixtures/package.json b/test/fixtures/package.json new file mode 100644 index 00000000..5bbefffb --- /dev/null +++ b/test/fixtures/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/tsconfig.json b/tsconfig.json index 4ace0a92..8a64461c 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,10 +5,9 @@ "moduleResolution": "Node", "allowSyntheticDefaultImports": true, "strict": true, - "declarationDir": "dist", - "declaration": true, + "declaration": false, "experimentalDecorators": true, "types": ["node"] }, - "include": ["src"] + "include": ["src", "lib"] } diff --git a/webpack.config.js b/webpack.config.mjs similarity index 63% rename from webpack.config.js rename to webpack.config.mjs index be8fe048..15bf8951 100644 --- a/webpack.config.js +++ b/webpack.config.mjs @@ -1,12 +1,10 @@ -const path = require("node:path"); -const fsp = require("node:fs/promises"); - -const TerserPlugin = require("terser-webpack-plugin"); -const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer'); +import { fileURLToPath } from 'node:url'; +import TerserPlugin from 'terser-webpack-plugin'; +import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer'; const isProd = process.env.NODE_ENV === "production"; -module.exports = { +export default { target: "node", mode: isProd ? "production" : "development", entry: { @@ -15,18 +13,18 @@ module.exports = { }, devtool: false, output: { - filename: "[name].js", - path: path.resolve(__dirname, "dist"), + filename: "[name].cjs", + path: fileURLToPath(import.meta.resolve('./dist')), libraryTarget: "commonjs2", libraryExport: "default", }, resolve: { - extensions: [".tsx", ".ts", ".js"], + extensions: [".tsx", ".ts", ".js", ".cjs", ".mjs", ".json"], alias: { - "@babel/code-frame": require.resolve("./stubs/babel-codeframe"), - "@babel/helper-compilation-targets": require.resolve( - "./stubs/helper-compilation-targets", - ), + "@babel/code-frame": fileURLToPath(import.meta.resolve("./stubs/babel-codeframe.mjs")), + "@babel/helper-compilation-targets": fileURLToPath(import.meta.resolve( + "./stubs/helper-compilation-targets.mjs", + )), }, }, plugins: [ From 590dcb0f49362a4c913899ddb6ffda983d986b47 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Mon, 1 Jul 2024 12:23:01 +0200 Subject: [PATCH 2/7] cli: use named export! --- lib/jiti-cli.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/jiti-cli.mjs b/lib/jiti-cli.mjs index 4f726bc7..b9c89d4a 100755 --- a/lib/jiti-cli.mjs +++ b/lib/jiti-cli.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node import { resolve } from "node:path"; -import createJiti from "./jiti.cjs"; +import { createJiti } from "./jiti.cjs"; const script = process.argv.splice(2, 1)[0]; From 018335c718f1ea4f2575ee753a57cba5b3592d3c Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Mon, 1 Jul 2024 12:28:33 +0200 Subject: [PATCH 3/7] add more jsdocsd --- lib/types.d.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/lib/types.d.ts b/lib/types.d.ts index 5c272215..23b96882 100644 --- a/lib/types.d.ts +++ b/lib/types.d.ts @@ -45,6 +45,10 @@ export interface JitiOptions { /** * Enable hard-source caching with HMR support (enabled by default). * + * An string can be passed to set the custom cache directory. + * + * By default (when is `true`), jiti uses `node_modules/.cache/jiti` (if exists) or `{TMP_DIR}/node-jiti` + * * Can also be disabled using `JITI_CACHE=0` environment variable. * * **Note:** It is recommended to keep this option enabled for performance. @@ -91,12 +95,29 @@ export interface JitiOptions { /** * Resolve aliases + * + * You can use `JITI_ALIAS` environment variable to set aliases as a JSON string. */ alias?: Record; + /** + * List of modules (within `node_modules`) to always use native require/import for them. + * + * You can use `JITI_NATIVE_MODULES` environment variable to set native modules as a JSON string. + * + */ nativeModules?: string[]; + /** + * List of modules (within `node_modules`) to transform them regardless of syntax. + * + * You can use `JITI_TRANSFORM_MODULES` environment variable to set transform modules as a JSON string. + */ transformModules?: string[]; + + /** + * Enable experimental native Bun support for transformations. + */ experimentalBun?: boolean; } From 22e455e7260653a148e856c7e4e9359176094e64 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Mon, 1 Jul 2024 12:32:23 +0200 Subject: [PATCH 4/7] update fixture test --- test/__snapshots__/fixtures.test.ts.snap | 2 +- test/fixtures.test.ts | 10 +++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/test/__snapshots__/fixtures.test.ts.snap b/test/__snapshots__/fixtures.test.ts.snap index f8535021..77cabb0c 100644 --- a/test/__snapshots__/fixtures.test.ts.snap +++ b/test/__snapshots__/fixtures.test.ts.snap @@ -37,7 +37,7 @@ exports[`fixtures > error-runtime > stderr 1`] = ` at file:///lib/jiti-cli.mjs at ModuleJob.run (internal/modules/esm/module_job) at async ModuleLoader.import (internal/modules/esm/loader) - at async asyncRunEntryPointWithESMLoader (internal/modules/run_main) { + code: 'ERR_INVALID_ARG_TYPE' }" `; diff --git a/test/fixtures.test.ts b/test/fixtures.test.ts index f82c0032..ae3722bb 100644 --- a/test/fixtures.test.ts +++ b/test/fixtures.test.ts @@ -41,6 +41,15 @@ describe("fixtures", async () => { ) .replace("internal/errors:496", "events:276") .replace(" ^", " ^") + .replace( + "at async asyncRunEntryPointWithESMLoader (internal/modules/run_main) {", + "", + ) + .replace("at async loadESM (internal/process/esm_loader)", "") + .replace( + "at async handleMainPromise (internal/modules/run_main) {", + "", + ) .trim() ); } @@ -51,7 +60,6 @@ describe("fixtures", async () => { reject: false, env: { JITI_CACHE: "false", - JITI_ESM_RESOLVE: "true", }, }); From 9ff19bdea55c8e1c1f7e67b6ff63b563bb1fd656 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Mon, 1 Jul 2024 12:34:51 +0200 Subject: [PATCH 5/7] simplify runtime error --- test/__snapshots__/fixtures.test.ts.snap | 22 +--------------------- test/fixtures.test.ts | 9 --------- test/fixtures/error-runtime/index.ts | 3 +-- 3 files changed, 2 insertions(+), 32 deletions(-) diff --git a/test/__snapshots__/fixtures.test.ts.snap b/test/__snapshots__/fixtures.test.ts.snap index 77cabb0c..5414e925 100644 --- a/test/__snapshots__/fixtures.test.ts.snap +++ b/test/__snapshots__/fixtures.test.ts.snap @@ -20,27 +20,7 @@ exports[`fixtures > error-parse > stderr 1`] = ` exports[`fixtures > error-parse > stdout 1`] = `""`; -exports[`fixtures > error-runtime > stderr 1`] = ` -"TypeError: The "listener" argument must be of type function. Received undefined - at checkListener (events) - at _addListener (events) - at process.addListener (events) - at /index.ts - at evalModule (/dist/jiti.cjs) - at jitiRequire (/dist/jiti.cjs) - at Function. (/dist/jiti.cjs) - at Generator.next () - at /dist/jiti.cjs - at new Promise () - at __awaiter (/dist/jiti.cjs) - at Function.import (/dist/jiti.cjs) - at file:///lib/jiti-cli.mjs - at ModuleJob.run (internal/modules/esm/module_job) - at async ModuleLoader.import (internal/modules/esm/loader) - - code: 'ERR_INVALID_ARG_TYPE' -}" -`; +exports[`fixtures > error-runtime > stderr 1`] = `"test error"`; exports[`fixtures > error-runtime > stdout 1`] = `""`; diff --git a/test/fixtures.test.ts b/test/fixtures.test.ts index ae3722bb..f8e1c8dd 100644 --- a/test/fixtures.test.ts +++ b/test/fixtures.test.ts @@ -41,15 +41,6 @@ describe("fixtures", async () => { ) .replace("internal/errors:496", "events:276") .replace(" ^", " ^") - .replace( - "at async asyncRunEntryPointWithESMLoader (internal/modules/run_main) {", - "", - ) - .replace("at async loadESM (internal/process/esm_loader)", "") - .replace( - "at async handleMainPromise (internal/modules/run_main) {", - "", - ) .trim() ); } diff --git a/test/fixtures/error-runtime/index.ts b/test/fixtures/error-runtime/index.ts index 5561aac0..eac835d2 100644 --- a/test/fixtures/error-runtime/index.ts +++ b/test/fixtures/error-runtime/index.ts @@ -1,2 +1 @@ -// @ts-expect-error -process.addListener(null); +throw "test error"; From ed0a628b56556c63f9579ce76189effa7016ba06 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Mon, 1 Jul 2024 12:37:31 +0200 Subject: [PATCH 6/7] chore: use `createJiti` for name --- src/eval.ts | 4 ++-- src/jiti.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/eval.ts b/src/eval.ts index 70285fcd..f0a97678 100644 --- a/src/eval.ts +++ b/src/eval.ts @@ -12,7 +12,7 @@ import { import type { ModuleCache, Context, EvalModuleOptions } from "./types"; import { jitiResolve } from "./resolve"; import { jitiRequire, nativeImportOrRequire } from "./require"; -import createJITI from "./jiti"; +import createJiti from "./jiti"; import { transform } from "./transform"; export function evalModule( @@ -91,7 +91,7 @@ export function evalModule( } } - const _jiti = createJITI(filename, ctx.opts, { + const _jiti = createJiti(filename, ctx.opts, { nativeImport: ctx.nativeImport, onError: ctx.onError, parentModule: mod, diff --git a/src/jiti.ts b/src/jiti.ts index f4a9a751..b637e017 100644 --- a/src/jiti.ts +++ b/src/jiti.ts @@ -22,7 +22,7 @@ import { prepareCacheDir } from "./cache"; const isWindows = platform() === "win32"; -export default function createJITI( +export default function createJiti( filename: string, userOptions: JitiOptions = {}, _internal?: Pick< From 2fc79da8ad57dfe48bdd70301d7e5d922aede495 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Mon, 1 Jul 2024 12:38:30 +0200 Subject: [PATCH 7/7] chore: update bun test --- test/bun.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/bun.test.ts b/test/bun.test.ts index c782c6ac..caa53dbe 100644 --- a/test/bun.test.ts +++ b/test/bun.test.ts @@ -4,13 +4,13 @@ import { join } from "node:path"; // @ts-ignore import { test, expect } from "bun:test"; -import { createJITI } from "../lib/jiti.cjs"; +import { createJiti } from ".."; const fixturesDir = fileURLToPath(new URL("fixtures", import.meta.url)); const fixtures = await readdir(fixturesDir); -const _jiti = createJITI(fixturesDir, { +const _jiti = createJiti(fixturesDir, { debug: true, interopDefault: true, requireCache: false,