@rsbuild/core 2.0.0-beta.2 → 2.0.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+ import { resolve } from "node:path";
3
+ import nodeModule from "node:module";
4
+ const script = process.argv.splice(2, 1)[0];
5
+ if (!script) {
6
+ console.error("Usage: jiti <path> [...arguments]");
7
+ process.exit(1);
8
+ }
9
+ if (nodeModule.enableCompileCache && !process.env.NODE_DISABLE_COMPILE_CACHE) try {
10
+ nodeModule.enableCompileCache();
11
+ } catch {}
12
+ const pwd = process.cwd();
13
+ const { createJiti } = await import("./jiti.cjs");
14
+ const jiti = createJiti(pwd);
15
+ const resolved = process.argv[1] = jiti.resolve(resolve(pwd, script));
16
+ await jiti.import(resolved).catch((error)=>{
17
+ console.error(error);
18
+ process.exit(1);
19
+ });
@@ -0,0 +1,89 @@
1
+ import { dirname, join } from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ import { existsSync } from "node:fs";
4
+ import { readFile } from "node:fs/promises";
5
+ import { isBuiltin } from "node:module";
6
+ import { createJiti } from "./jiti.mjs";
7
+ let jiti;
8
+ export async function initialize() {
9
+ jiti = createJiti();
10
+ }
11
+ export async function resolve(specifier, context, nextResolve) {
12
+ if (_shouldSkip(specifier)) return nextResolve(specifier, context);
13
+ const resolvedPath = jiti.esmResolve(specifier, {
14
+ parentURL: context?.parentURL,
15
+ conditions: context?.conditions
16
+ });
17
+ return {
18
+ url: resolvedPath,
19
+ shortCircuit: true
20
+ };
21
+ }
22
+ export async function load(url, context, nextLoad) {
23
+ if (_shouldSkip(url)) return nextLoad(url, context);
24
+ const filename = fileURLToPath(url);
25
+ if (url.endsWith(".js")) {
26
+ const pkg = await _findClosestPackageJson(dirname(filename));
27
+ if (pkg && "module" === pkg.type) return nextLoad(url, context);
28
+ }
29
+ const rawSource = await readFile(filename, "utf8");
30
+ if (url.endsWith(".json")) {
31
+ const pkg = await _findClosestPackageJson(dirname(filename));
32
+ return pkg && "module" === pkg.type ? {
33
+ source: `export default ${rawSource}`,
34
+ format: "module",
35
+ shortCircuit: true
36
+ } : {
37
+ source: `module.exports = ${rawSource}`,
38
+ format: "commonjs",
39
+ shortCircuit: true
40
+ };
41
+ }
42
+ const transpiledSource = jiti.transform({
43
+ source: rawSource,
44
+ filename: filename,
45
+ ts: url.endsWith("ts"),
46
+ retainLines: true,
47
+ async: true,
48
+ jsx: jiti.options.jsx
49
+ });
50
+ if (url.endsWith(".js") && !transpiledSource.includes("jitiImport")) return {
51
+ source: transpiledSource,
52
+ format: "commonjs",
53
+ shortCircuit: true
54
+ };
55
+ return {
56
+ source: _wrapSource(transpiledSource, filename),
57
+ format: "module",
58
+ shortCircuit: true
59
+ };
60
+ }
61
+ function _wrapSource(source, filename) {
62
+ const _jitiPath = new URL("jiti.mjs", import.meta.url).href;
63
+ return `import { createJiti as __createJiti__ } from ${JSON.stringify(_jitiPath)};async function _module(exports, require, module, __filename, __dirname, jitiImport) { ${source}\n};
64
+ // GENERATED BY JITI ESM LOADER
65
+ const filename = ${JSON.stringify(filename)};
66
+ const dirname = ${JSON.stringify(dirname(filename))};
67
+ const jiti = __createJiti__(filename);
68
+ const module = { exports: Object.create(null) };
69
+ await _module(module.exports, jiti, module, filename, dirname, jiti.import);
70
+ if (module.exports && module.exports.__JITI_ERROR__) {
71
+ const { filename, line, column, code, message } =
72
+ module.exports.__JITI_ERROR__;
73
+ const loc = [filename, line, column].join(':');
74
+ const err = new Error(code + ": " + message + " " + loc);
75
+ Error.captureStackTrace(err, _module);
76
+ throw err;
77
+ }
78
+ export default module.exports;
79
+ `;
80
+ }
81
+ function _shouldSkip(url) {
82
+ return !jiti || url.endsWith(".mjs") || url.endsWith(".cjs") || !url.startsWith("./") && !url.startsWith("file://") || isBuiltin(url);
83
+ }
84
+ async function _findClosestPackageJson(dir) {
85
+ if ("/" === dir) return null;
86
+ const packageJsonPath = join(dir, "package.json");
87
+ if (existsSync(packageJsonPath)) return JSON.parse(await readFile(packageJsonPath, "utf8"));
88
+ return _findClosestPackageJson(dirname(dir));
89
+ }
@@ -0,0 +1,76 @@
1
+ const isDeno = "Deno" in globalThis;
2
+ export function createJiti(parentURL, jitiOptions) {
3
+ parentURL = normalizeParentURL(parentURL);
4
+ function jiti() {
5
+ throw unsupportedError("`jiti()` is not supported in native mode, use `jiti.import()` instead.");
6
+ }
7
+ jiti.resolve = ()=>{
8
+ throw unsupportedError("`jiti.resolve()` is not supported in native mode.");
9
+ };
10
+ jiti.esmResolve = (id, opts)=>{
11
+ try {
12
+ const importMeta = jitiOptions?.importMeta || import.meta;
13
+ if (isDeno) return importMeta.resolve(id);
14
+ const parent = normalizeParentURL(opts?.parentURL || parentURL);
15
+ return importMeta.resolve(id, parent);
16
+ } catch (error) {
17
+ if (opts?.try) return;
18
+ throw error;
19
+ }
20
+ };
21
+ jiti.import = async function(id, opts) {
22
+ for (const suffix of [
23
+ "",
24
+ "/index"
25
+ ])for (const ext of [
26
+ "",
27
+ ".js",
28
+ ".mjs",
29
+ ".cjs",
30
+ ".ts",
31
+ ".tsx",
32
+ ".mts",
33
+ ".cts"
34
+ ])try {
35
+ const resolved = this.esmResolve(id + suffix + ext, opts);
36
+ if (!resolved) continue;
37
+ let importAttrs;
38
+ if (resolved.endsWith('.json')) importAttrs = {
39
+ with: {
40
+ type: 'json'
41
+ }
42
+ };
43
+ return await import(resolved, importAttrs);
44
+ } catch (error) {
45
+ if ('ERR_MODULE_NOT_FOUND' === error.code || 'ERR_UNSUPPORTED_DIR_IMPORT' === error.code) continue;
46
+ if (opts?.try) return;
47
+ throw error;
48
+ }
49
+ if (!opts?.try) {
50
+ const parent = normalizeParentURL(opts?.parentURL || parentURL);
51
+ const error = new Error(`[jiti] [ERR_MODULE_NOT_FOUND] Cannot import '${id}' from '${parent}'.`);
52
+ error.code = "ERR_MODULE_NOT_FOUND";
53
+ throw error;
54
+ }
55
+ };
56
+ jiti.transform = ()=>{
57
+ throw unsupportedError("`jiti.transform()` is not supported in native mode.");
58
+ };
59
+ jiti.evalModule = ()=>{
60
+ throw unsupportedError("`jiti.evalModule()` is not supported in native mode.");
61
+ };
62
+ jiti.main = void 0;
63
+ jiti.extensions = Object.create(null);
64
+ jiti.cache = Object.create(null);
65
+ return jiti;
66
+ }
67
+ export default createJiti;
68
+ function unsupportedError(message) {
69
+ throw new Error(`[jiti] ${message} (import or require 'jiti' instead of 'jiti/native' for more features).`);
70
+ }
71
+ function normalizeParentURL(input) {
72
+ if (!input) return "file:///";
73
+ if ("string" != typeof filename || input.startsWith("file://")) return input;
74
+ if (input.endsWith("/")) input += "_";
75
+ return `file://${input}`;
76
+ }
@@ -0,0 +1 @@
1
+ // eslint-disable-next-line unicorn/no-empty-file
@@ -0,0 +1,2 @@
1
+ import { register } from "node:module";
2
+ register("./jiti-hooks.mjs", import.meta.url, {});
@@ -0,0 +1,24 @@
1
+ const { createRequire } = require("node:module");
2
+ const _createJiti = require("../dist/jiti.cjs");
3
+ function onError(err) {
4
+ throw err;
5
+ }
6
+ const nativeImport = (id)=>import(id);
7
+ let _transform;
8
+ function lazyTransform(...args) {
9
+ if (!_transform) _transform = require("../dist/babel.cjs");
10
+ return _transform(...args);
11
+ }
12
+ function createJiti(id, opts = {}) {
13
+ if (!opts.transform) opts = {
14
+ ...opts,
15
+ transform: lazyTransform
16
+ };
17
+ return _createJiti(id, opts, {
18
+ onError,
19
+ nativeImport,
20
+ createRequire
21
+ });
22
+ }
23
+ module.exports = createJiti;
24
+ module.exports.createJiti = createJiti;
@@ -0,0 +1,8 @@
1
+ import * as types from "./types.js";
2
+ declare const allExports: typeof types & {
3
+ /**
4
+ * @deprecated Please use `const { createJiti } = require("jiti")` or use ESM import.
5
+ */
6
+ (...args: Parameters<typeof types.createJiti>): types.Jiti;
7
+ };
8
+ export = allExports;
@@ -0,0 +1,8 @@
1
+ import { createJiti } from "./types.js";
2
+
3
+ export * from "./types.js";
4
+
5
+ /**
6
+ * @deprecated Please use `import { createJiti } from "jiti"`
7
+ */
8
+ export default createJiti;
@@ -0,0 +1,23 @@
1
+ import { createRequire } from "node:module";
2
+ import _createJiti from "../dist/jiti.cjs";
3
+ function onError(err) {
4
+ throw err;
5
+ }
6
+ const nativeImport = (id)=>import(id);
7
+ let _transform;
8
+ function lazyTransform(...args) {
9
+ if (!_transform) _transform = createRequire(import.meta.url)("../dist/babel.cjs");
10
+ return _transform(...args);
11
+ }
12
+ export function createJiti(id, opts = {}) {
13
+ if (!opts.transform) opts = {
14
+ ...opts,
15
+ transform: lazyTransform
16
+ };
17
+ return _createJiti(id, opts, {
18
+ onError,
19
+ nativeImport,
20
+ createRequire
21
+ });
22
+ }
23
+ export default createJiti;
@@ -0,0 +1,363 @@
1
+ /**
2
+ * Creates a new {@linkcode Jiti} instance with custom options.
3
+ *
4
+ * @param id - Instance id, usually the current filename.
5
+ * @param userOptions - Custom options to override the default options.
6
+ * @returns A {@linkcode Jiti} instance.
7
+ *
8
+ * @example
9
+ * <caption>ESM Usage</caption>
10
+ *
11
+ * ```ts
12
+ * import { createJiti } from "jiti";
13
+ *
14
+ * const jiti = createJiti(import.meta.url, { debug: true });
15
+ * ```
16
+ *
17
+ * @example
18
+ * <caption>CommonJS Usage **(deprecated)**</caption>
19
+ *
20
+ * ```ts
21
+ * const { createJiti } = require("jiti");
22
+ *
23
+ * const jiti = createJiti(__filename, { debug: true });
24
+ * ```
25
+ *
26
+ * @since 2.0.0
27
+ */
28
+ export declare function createJiti(id: string, userOptions?: JitiOptions): Jiti;
29
+
30
+ /**
31
+ * Jiti instance
32
+ *
33
+ * Calling `jiti()` is similar to CommonJS {@linkcode require()} but adds
34
+ * extra features such as TypeScript and ESM compatibility.
35
+ *
36
+ * **Note:** It is recommended to use
37
+ * {@linkcode Jiti.import | await jiti.import()} instead.
38
+ */
39
+ export interface Jiti extends NodeRequire {
40
+ /**
41
+ * Resolved options
42
+ */
43
+ options: JitiOptions;
44
+
45
+ /**
46
+ * ESM import a module with additional TypeScript and ESM compatibility.
47
+ *
48
+ * If you need the default export of module, you can use
49
+ * `jiti.import(id, { default: true })` as shortcut to `mod?.default ?? mod`.
50
+ */
51
+ import<T = unknown>(
52
+ id: string,
53
+ opts?: JitiResolveOptions & { default?: true },
54
+ ): Promise<T>;
55
+
56
+ /**
57
+ * Resolve with ESM import conditions.
58
+ */
59
+ esmResolve(id: string, parentURL?: string): string;
60
+ esmResolve<T extends JitiResolveOptions = JitiResolveOptions>(
61
+ id: string,
62
+ opts?: T,
63
+ ): T["try"] extends true ? string | undefined : string;
64
+
65
+ /**
66
+ * Transform source code
67
+ */
68
+ transform: (opts: TransformOptions) => string;
69
+
70
+ /**
71
+ * Evaluate transformed code as a module
72
+ */
73
+ evalModule: (source: string, options?: EvalModuleOptions) => unknown;
74
+ }
75
+
76
+ /**
77
+ * Jiti instance options
78
+ */
79
+ export interface JitiOptions {
80
+ /**
81
+ * Filesystem source cache
82
+ *
83
+ * An string can be passed to set the custom cache directory.
84
+ *
85
+ * By default (when set to `true`), jiti uses
86
+ * `node_modules/.cache/jiti` (if exists) or `{TMP_DIR}/jiti`.
87
+ *
88
+ * This option can also be disabled using
89
+ * `JITI_FS_CACHE=false` environment variable.
90
+ *
91
+ * **Note:** It is recommended to keep this option
92
+ * enabled for better performance.
93
+ *
94
+ * @default true
95
+ */
96
+ fsCache?: boolean | string;
97
+
98
+ /**
99
+ * Rebuild the filesystem source cache
100
+ *
101
+ * This option can also be enabled using
102
+ * `JITI_REBUILD_FS_CACHE=true` environment variable.
103
+ *
104
+ * @default false
105
+ */
106
+ rebuildFsCache?: boolean;
107
+
108
+ /**
109
+ * @deprecated Use the {@linkcode fsCache} option.
110
+ *
111
+ * @default true
112
+ */
113
+ cache?: boolean | string;
114
+
115
+ /**
116
+ * Runtime module cache
117
+ *
118
+ * Disabling allows editing code and importing same module multiple times.
119
+ *
120
+ * When enabled, jiti integrates with Node.js native CommonJS cache store.
121
+ *
122
+ * This option can also be disabled using
123
+ * `JITI_MODULE_CACHE=false` environment variable.
124
+ *
125
+ * @default true
126
+ */
127
+ moduleCache?: boolean;
128
+
129
+ /**
130
+ * @deprecated Use the {@linkcode moduleCache} option.
131
+ *
132
+ * @default true
133
+ */
134
+ requireCache?: boolean;
135
+
136
+ /**
137
+ * Custom transform function
138
+ */
139
+ transform?: (opts: TransformOptions) => TransformResult;
140
+
141
+ /**
142
+ * Enable verbose debugging.
143
+ *
144
+ * Can also be enabled using `JITI_DEBUG=1` environment variable.
145
+ *
146
+ * @default false
147
+ */
148
+ debug?: boolean;
149
+
150
+ /**
151
+ * Enable sourcemaps for transformed code.
152
+ *
153
+ * Can also be disabled using `JITI_SOURCE_MAPS=0` environment variable.
154
+ *
155
+ * @default false
156
+ */
157
+ sourceMaps?: boolean;
158
+
159
+ /**
160
+ * Jiti combines module exports with the `default` export using an
161
+ * internal Proxy to improve compatibility with mixed CJS/ESM usage.
162
+ * You can check the current implementation
163
+ * {@link https://github.com/unjs/jiti/blob/main/src/utils.ts#L105 here}.
164
+ *
165
+ * Can be disabled using `JITI_INTEROP_DEFAULT=0` environment variable.
166
+ *
167
+ * @default true
168
+ */
169
+ interopDefault?: boolean;
170
+
171
+ /**
172
+ * Jiti hard source cache version.
173
+ *
174
+ * @internal
175
+ */
176
+ cacheVersion?: string;
177
+
178
+ /**
179
+ * Supported extensions to resolve.
180
+ *
181
+ * @default [".js", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts", ".mtsx", ".ctsx", ".json"]
182
+ */
183
+ extensions?: string[];
184
+
185
+ /**
186
+ * Transform options
187
+ */
188
+ transformOptions?: Omit<TransformOptions, "source">;
189
+
190
+ /**
191
+ * Resolve aliases
192
+ *
193
+ * You can use `JITI_ALIAS` environment variable to set aliases as
194
+ * a JSON string.
195
+ *
196
+ * @default {}
197
+ */
198
+ alias?: Record<string, string>;
199
+
200
+ /**
201
+ * List of modules (within `node_modules`) to always use native
202
+ * require/import for them.
203
+ *
204
+ * You can use `JITI_NATIVE_MODULES` environment variable to set
205
+ * native modules as a JSON string.
206
+ *
207
+ * @default []
208
+ */
209
+ nativeModules?: string[];
210
+
211
+ /**
212
+ * List of modules (within `node_modules`) to transform them
213
+ * regardless of syntax.
214
+ *
215
+ * You can use `JITI_TRANSFORM_MODULES` environment variable to set
216
+ * transform modules as a JSON string.
217
+ *
218
+ * @default []
219
+ */
220
+ transformModules?: string[];
221
+
222
+ /**
223
+ * Parent module's {@linkcode ImportMeta | import.meta} context to use
224
+ * for ESM resolution.
225
+ *
226
+ * (Only used for `jiti/native` import)
227
+ */
228
+ importMeta?: ImportMeta;
229
+
230
+ /**
231
+ * Try to use native require and import without jiti transformations first.
232
+ *
233
+ * Enabled if Bun is detected.
234
+ *
235
+ * @default false
236
+ */
237
+ tryNative?: boolean;
238
+
239
+ /**
240
+ * Enable JSX support Enable JSX support using
241
+ * {@link https://babeljs.io/docs/babel-plugin-transform-react-jsx | `@babel/plugin-transform-react-jsx`}.
242
+ *
243
+ * You can also use `JITI_JSX=1` environment variable to enable JSX support.
244
+ *
245
+ * @default false
246
+ */
247
+ jsx?: boolean | JSXOptions;
248
+ }
249
+
250
+ interface NodeRequire {
251
+ /**
252
+ * Module cache
253
+ */
254
+ cache: ModuleCache;
255
+
256
+ /**
257
+ * @deprecated Prefer {@linkcode Jiti.import | await jiti.import()}
258
+ * for better compatibility.
259
+ */
260
+ (id: string): any;
261
+
262
+ /**
263
+ * @deprecated Prefer {@linkcode Jiti.esmResolve | jiti.esmResolve}
264
+ * for better compatibility.
265
+ */
266
+ resolve: {
267
+ /** @deprecated */
268
+ (id: string, options?: { paths?: string[] | undefined }): string;
269
+ /** @deprecated */
270
+ paths(request: string): string[] | null;
271
+ };
272
+
273
+ /** @deprecated CommonJS API */
274
+ extensions: Record<
275
+ ".js" | ".json" | ".node",
276
+ (m: NodeModule, filename: string) => any | undefined
277
+ >;
278
+
279
+ /** @deprecated CommonJS API */
280
+ main: NodeModule | undefined;
281
+ }
282
+
283
+ export interface NodeModule {
284
+ /**
285
+ * `true` if the module is running during the Node.js preload.
286
+ */
287
+ isPreloading: boolean;
288
+ exports: any;
289
+ require: NodeRequire;
290
+ id: string;
291
+ filename: string;
292
+ loaded: boolean;
293
+ /**
294
+ * @deprecated since Node.js **v14.6.0** Please use
295
+ * {@linkcode NodeRequire.main | require.main} and
296
+ * {@linkcode NodeModule.children | module.children} instead.
297
+ */
298
+ parent: NodeModule | null | undefined;
299
+ children: NodeModule[];
300
+ /**
301
+ * The directory name of the module.
302
+ * This is usually the same as the `path.dirname()` of the `module.id`.
303
+ *
304
+ * @since Node.js **v11.14.0**
305
+ */
306
+ path: string;
307
+ paths: string[];
308
+ }
309
+
310
+ export type ModuleCache = Record<string, NodeModule>;
311
+
312
+ export type EvalModuleOptions = Partial<{
313
+ id: string;
314
+ filename: string;
315
+ ext: string;
316
+ cache: ModuleCache;
317
+ /**
318
+ * @default true
319
+ */
320
+ async: boolean;
321
+ forceTranspile: boolean;
322
+ }>;
323
+
324
+ export interface TransformOptions {
325
+ source: string;
326
+ filename?: string;
327
+ ts?: boolean;
328
+ retainLines?: boolean;
329
+ interopDefault?: boolean;
330
+ /**
331
+ * @default false
332
+ */
333
+ async?: boolean;
334
+ /**
335
+ * @default false
336
+ */
337
+ jsx?: boolean | JSXOptions;
338
+ babel?: Record<string, any>;
339
+ }
340
+
341
+ export interface TransformResult {
342
+ code: string;
343
+ error?: any;
344
+ }
345
+
346
+ export interface JitiResolveOptions {
347
+ conditions?: string[];
348
+ parentURL?: string | URL;
349
+ try?: boolean;
350
+ }
351
+
352
+ /**
353
+ * @see {@link https://babeljs.io/docs/babel-plugin-transform-react-jsx#options | Reference}
354
+ */
355
+ export interface JSXOptions {
356
+ throwIfNamespace?: boolean;
357
+ runtime?: "classic" | "automatic";
358
+ importSource?: string;
359
+ pragma?: string;
360
+ pragmaFrag?: string;
361
+ useBuiltIns?: boolean;
362
+ useSpread?: boolean;
363
+ }