Skip to content

Commit 5c45f17

Browse files
authored
chore: removes the last require() usages (#2435)
1 parent 10bab2e commit 5c45f17

File tree

24 files changed

+89
-136
lines changed

24 files changed

+89
-136
lines changed

.github/workflows/deploy-doc.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,10 @@ jobs:
1313
- uses: actions/checkout@v5
1414
with:
1515
fetch-depth: 0
16-
- name: Use Node.js 20
16+
- name: Use Node.js 22
1717
uses: actions/setup-node@v5
1818
with:
19-
node-version: 20
19+
node-version: 22
2020
# https://github.com/actions/setup-node/issues/1357
2121
package-manager-cache: false
2222
- name: Install Vercel CLI

.github/workflows/tests.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ jobs:
1414
strategy:
1515
matrix:
1616
os: [ubuntu-latest, windows-latest]
17-
node-version: [20.x]
17+
node-version: [22.x]
1818
steps:
1919
- uses: actions/checkout@v5
2020
- name: Use Node.js ${{ matrix.node-version }}

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
"@commitlint/cli": "^19.8.1",
4242
"@commitlint/config-conventional": "^19.8.1",
4343
"@eslint/js": "^9.35.0",
44-
"@types/node": "^20.19.14",
44+
"@types/node": "^22.18.10",
4545
"esbuild-plugin-alias": "^0.2.1",
4646
"eslint": "^9.35.0",
4747
"eslint-config-prettier": "^10.1.8",

packages/core/src/generators/mutator.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,12 +63,10 @@ export const generateMutator = async ({
6363
? `${pascal(name)}${BODY_TYPE_NAME}`
6464
: BODY_TYPE_NAME;
6565

66-
const { file, cached } = await loadFile<string>(importPath, {
67-
isDefault: false,
66+
const { file, cached } = await loadFile(importPath, {
6867
root: workspace,
6968
alias: mutator.alias,
7069
tsconfig,
71-
load: false,
7270
});
7371

7472
if (file) {

packages/core/src/utils/file.ts

Lines changed: 13 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import mm from 'micromatch';
99
import type { Tsconfig } from '../types';
1010
import { isDirectory } from './assertion';
1111
import { createDebugger } from './debug';
12-
import { createLogger, type LogLevel } from './logger';
1312
import { joinSafe, normalizeSafe } from './path';
1413

1514
export const getFileInfo = (
@@ -42,44 +41,36 @@ export const getFileInfo = (
4241

4342
const debug = createDebugger('orval:file-load');
4443

45-
const cache = new Map<string, { file?: any; error?: any }>();
44+
const cache = new Map<string, { file?: string; error?: unknown }>();
4645

47-
export async function loadFile<File = any>(
46+
export async function loadFile(
4847
filePath?: string,
4948
options?: {
5049
root?: string;
5150
defaultFileName?: string;
52-
logLevel?: LogLevel;
53-
isDefault?: boolean;
5451
alias?: Record<string, string>;
5552
tsconfig?: Tsconfig;
56-
load?: boolean;
5753
},
5854
): Promise<{
5955
path: string;
60-
file?: File;
61-
error?: any;
56+
file?: string;
57+
error?: unknown;
6258
cached?: boolean;
6359
}> {
6460
const {
6561
root = process.cwd(),
66-
isDefault = true,
6762
defaultFileName,
68-
logLevel,
6963
alias,
7064
tsconfig,
71-
load = true,
7265
} = options ?? {};
7366
const start = Date.now();
7467

7568
let resolvedPath: string | undefined;
76-
let isTS = false;
7769
let isMjs = false;
7870

7971
if (filePath) {
8072
// explicit path is always resolved from cwd
8173
resolvedPath = path.resolve(filePath);
82-
isTS = filePath.endsWith('.ts');
8374
} else if (defaultFileName) {
8475
// implicit file loaded from inline root (if present)
8576
// otherwise from cwd
@@ -107,7 +98,6 @@ export async function loadFile<File = any>(
10798
const tsFile = path.resolve(root, `${defaultFileName}.ts`);
10899
if (fs.existsSync(tsFile)) {
109100
resolvedPath = tsFile;
110-
isTS = true;
111101
}
112102
}
113103
}
@@ -136,62 +126,23 @@ export async function loadFile<File = any>(
136126
}
137127

138128
try {
139-
let file: File | undefined;
140-
141-
if (!file && !isTS && !isMjs) {
142-
// 1. try to directly require the module (assuming commonjs)
143-
try {
144-
// clear cache in case of server restart
145-
delete require.cache[require.resolve(resolvedPath)];
146-
147-
file = require(resolvedPath);
148-
149-
debug(`cjs loaded in ${Date.now() - start}ms`);
150-
} catch (error) {
151-
const ignored = new RegExp(
152-
[
153-
`Cannot use import statement`,
154-
`Must use import to load ES Module`,
155-
// #1635, #2050 some Node 12.x versions don't have esm detection
156-
// so it throws normal syntax errors when encountering esm syntax
157-
`Unexpected token`,
158-
`Unexpected identifier`,
159-
].join('|'),
160-
);
161-
//@ts-ignore
162-
if (!ignored.test(error.message)) {
163-
throw error;
164-
}
165-
}
166-
}
167-
168-
if (!file) {
169-
// 2. if we reach here, the file is ts or using es import syntax, or
170-
// the user has type: "module" in their package.json (#917)
171-
// transpile es import syntax to require syntax using rollup.
172-
// lazy require rollup (it's actually in dependencies)
173-
const { code } = await bundleFile(
174-
resolvedPath,
175-
isMjs,
176-
root || path.dirname(normalizeResolvedPath),
177-
alias,
178-
tsconfig?.compilerOptions,
179-
);
129+
const { code: file } = await bundleFile(
130+
resolvedPath,
131+
isMjs,
132+
root || path.dirname(normalizeResolvedPath),
133+
alias,
134+
tsconfig?.compilerOptions,
135+
);
180136

181-
file = load
182-
? await loadFromBundledFile<File>(resolvedPath, code, isDefault)
183-
: (code as any);
184-
185-
debug(`bundled file loaded in ${Date.now() - start}ms`);
186-
}
137+
debug(`bundled file loaded in ${Date.now() - start}ms`);
187138

188139
cache.set(resolvedPath, { file });
189140

190141
return {
191142
path: normalizeResolvedPath,
192143
file,
193144
};
194-
} catch (error: any) {
145+
} catch (error) {
195146
cache.set(resolvedPath, { error });
196147

197148
return {
@@ -344,32 +295,6 @@ async function bundleFile(
344295
};
345296
}
346297

347-
interface NodeModuleWithCompile extends NodeModule {
348-
_compile(code: string, filename: string): any;
349-
}
350-
351-
async function loadFromBundledFile<File = unknown>(
352-
fileName: string,
353-
bundledCode: string,
354-
isDefault: boolean,
355-
): Promise<File> {
356-
const extension = path.extname(fileName);
357-
const defaultLoader = require.extensions[extension]!;
358-
require.extensions[extension] = (module: NodeModule, filename: string) => {
359-
if (filename === fileName) {
360-
(module as NodeModuleWithCompile)._compile(bundledCode, filename);
361-
} else {
362-
defaultLoader(module, filename);
363-
}
364-
};
365-
// clear cache in case of server restart
366-
delete require.cache[require.resolve(fileName)];
367-
const raw = require(fileName);
368-
const file = isDefault && raw.__esModule ? raw.default : raw;
369-
require.extensions[extension] = defaultLoader;
370-
return file;
371-
}
372-
373298
export async function removeFilesAndEmptyFolders(
374299
patterns: string[],
375300
dir: string,

packages/orval/package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@
1515
"default": "./dist/index.js"
1616
}
1717
},
18+
"engines": {
19+
"node": ">=22.18.0"
20+
},
1821
"keywords": [
1922
"rest",
2023
"client",

packages/orval/src/generate.ts

Lines changed: 40 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
import fs from 'node:fs';
2+
import path from 'node:path';
3+
import process from 'node:process';
4+
import url from 'node:url';
5+
16
import {
27
asyncReduce,
38
type ConfigExternal,
@@ -6,13 +11,11 @@ import {
611
type GlobalOptions,
712
isFunction,
813
isString,
9-
loadFile,
1014
log,
1115
logError,
1216
type NormalizedConfig,
1317
type NormalizedOptions,
1418
removeFilesAndEmptyFolders,
15-
upath,
1619
} from '@orval/core';
1720

1821
import { importSpecs } from './import-specs';
@@ -90,23 +93,47 @@ export const generateSpecs = async (
9093
throw new Error('One or more project failed, see above for details');
9194
};
9295

96+
function findConfigFile(configFilePath?: string) {
97+
if (configFilePath) {
98+
if (!fs.existsSync(configFilePath))
99+
throw new Error(`Config file ${configFilePath} does not exist`);
100+
101+
return configFilePath;
102+
}
103+
104+
const root = process.cwd();
105+
const exts = ['.ts', '.js', '.mjs', '.cjs'];
106+
for (const ext of exts) {
107+
const fullPath = path.resolve(root, `orval.config${ext}`);
108+
if (fs.existsSync(fullPath)) {
109+
return fullPath;
110+
}
111+
}
112+
113+
throw new Error(`No config file found in ${root}`);
114+
}
115+
93116
export const generateConfig = async (
94117
configFile?: string,
95118
options?: GlobalOptions,
96119
) => {
97-
const {
98-
path,
99-
file: configExternal,
100-
error,
101-
} = await loadFile<ConfigExternal>(configFile, {
102-
defaultFileName: 'orval.config',
103-
});
104-
105-
if (!configExternal) {
106-
throw new Error(`failed to load from ${path} => ${error}`);
120+
const configFilePath = findConfigFile(configFile);
121+
let configExternal: ConfigExternal;
122+
try {
123+
const importPath = url.pathToFileURL(configFilePath).href;
124+
const importedModule = (await import(importPath)) as {
125+
default?: ConfigExternal;
126+
};
127+
if (importedModule.default === undefined) {
128+
throw new Error(`${configFilePath} doesn't have a default export`);
129+
}
130+
configExternal = importedModule.default;
131+
} catch (error) {
132+
const errorMsg = error instanceof Error ? error.message : 'unknown error';
133+
throw new Error(`failed to load from ${configFilePath} => ${errorMsg}`);
107134
}
108135

109-
const workspace = upath.dirname(path);
136+
const workspace = path.dirname(configFilePath);
110137

111138
const config = await (isFunction(configExternal)
112139
? configExternal()

packages/tsdown.base.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { UserConfig } from 'tsdown';
22

33
export const baseOptions: UserConfig = {
44
entry: ['src/index.ts'],
5-
target: 'node18',
5+
target: 'node22.18',
66
format: 'cjs',
77
tsconfig: 'tsconfig.build.json',
88
sourcemap: true,

samples/angular-app/src/api/endpoints/pets/pets.msw.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ export const getShowPetByIdResponseMock = () =>
5757
(() => ({
5858
id: faker.number.int({ min: 1, max: 99 }),
5959
name: faker.person.firstName(),
60-
tag: faker.helpers.arrayElement([faker.word.sample(), void 0]),
60+
tag: faker.helpers.arrayElement([faker.word.sample(), undefined]),
6161
}))();
6262

6363
export const getShowPetTextResponseMock = (): string => faker.word.sample();

samples/basic/api/endpoints/petstoreFromFileSpecWithTransformer.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ export const getShowPetByIdResponseMock = () =>
140140
(() => ({
141141
id: faker.number.int({ min: 1, max: 99 }),
142142
name: faker.person.firstName(),
143-
tag: faker.helpers.arrayElement([faker.word.sample(), void 0]),
143+
tag: faker.helpers.arrayElement([faker.word.sample(), undefined]),
144144
}))();
145145

146146
export const getListPetsMockHandler = (

0 commit comments

Comments
 (0)