Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions apps/oxlint/src-js/js_config.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { basename as pathBasename } from "node:path";

import { getErrorMessage } from "./utils/utils.ts";
import { isDefineConfig } from "./package/config.ts";
import { DateNow, JSONStringify } from "./utils/globals.ts";
Expand All @@ -12,6 +14,9 @@ type LoadJsConfigsResult =
| { Failures: { path: string; error: string }[] }
| { Error: string };

const VITE_CONFIG_NAME = "vite.config.ts";
const VITE_OXLINT_CONFIG_FIELD = "lint";

function validateConfigExtends(root: object): void {
const visited = new WeakSet<object>();
const inStack = new WeakSet<object>();
Expand Down Expand Up @@ -95,7 +100,7 @@ export async function loadJsConfigs(paths: string[]): Promise<string> {
// Bypass Node.js module cache to allow reloading changed config files (used for LSP, where we reload configs after important changes)
const fileUrl = new URL(`file://${path}?cache=${cacheKey}`);
const module = await import(fileUrl.href);
const config = module.default;
let config = module.default;

if (config === undefined) {
throw new Error(`Configuration file has no default export.`);
Expand All @@ -105,19 +110,23 @@ export async function loadJsConfigs(paths: string[]): Promise<string> {
throw new Error(`Configuration file must have a default export that is an object.`);
}

// Vite config files (e.g. `vite.config.ts`) are not Oxlint configs,
// so skip `defineConfig()` and `extends` validation.
// The `.lint` field extraction is handled on the Rust side.
if (!path.endsWith("/vite.config.ts")) {
if (pathBasename(path) === VITE_CONFIG_NAME) {
config = (config as Record<string, unknown>)[VITE_OXLINT_CONFIG_FIELD] ?? {};
if (typeof config !== "object" || config === null || Array.isArray(config)) {
throw new Error(
`The \`${VITE_OXLINT_CONFIG_FIELD}\` field in the default export must be an object.`,
);
}
} else {
if (!isDefineConfig(config)) {
throw new Error(
`Configuration file must wrap its default export with defineConfig() from "oxlint".`,
);
}

validateConfigExtends(config as object);
}

validateConfigExtends(config as object);

return { path, config };
}),
);
Expand Down
56 changes: 34 additions & 22 deletions apps/oxlint/src/js_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use oxc_diagnostics::OxcDiagnostic;
use oxc_linter::Oxlintrc;

use crate::run::JsLoadJsConfigsCb;
use crate::{VITE_CONFIG_NAME, VITE_OXLINT_CONFIG_FIELD};

/// Callback type for loading JavaScript/TypeScript config files.
pub type JsConfigLoaderCb =
Expand Down Expand Up @@ -119,27 +118,7 @@ fn parse_js_config_response(json: &str) -> Result<Vec<JsConfigResult>, Vec<OxcDi
(Vec::with_capacity(count), Vec::new()),
|(mut configs, mut errors), entry| {
let path = PathBuf::from(&entry.path);

// Vite config files: extract the `.lint` field
let is_vite_config = path
.file_name()
.and_then(|f| f.to_str())
.is_some_and(|name| name == VITE_CONFIG_NAME);
let config_value = if is_vite_config {
if let Some(v) = entry.config.get(VITE_OXLINT_CONFIG_FIELD).cloned() {
v
} else {
errors.push(OxcDiagnostic::error(format!(
"Expected a `{VITE_OXLINT_CONFIG_FIELD}` field in the default export of {}",
entry.path
)));
return (configs, errors);
}
} else {
entry.config
};

let mut oxlintrc = match parse_js_oxlintrc(config_value) {
let mut oxlintrc = match parse_js_oxlintrc(entry.config) {
Ok(config) => config,
Err(err) => {
errors.push(
Expand Down Expand Up @@ -185,3 +164,36 @@ fn parse_js_config_response(json: &str) -> Result<Vec<JsConfigResult>, Vec<OxcDi
}
}
}

#[cfg(test)]
mod test {
use serde_json::json;

use super::parse_js_config_response;

#[test]
fn test_parse_js_config_response_accepts_vite_lint_payloads() {
let path = std::env::temp_dir().join("vite.config.ts");
let json = serde_json::to_string(&json!({
"Success": [{
"path": path,
"config": {
"options": { "typeAware": true },
"extends": [{
"options": { "typeCheck": true }
}]
}
}]
}))
.unwrap();

let configs = parse_js_config_response(&json).unwrap();
assert_eq!(configs.len(), 1);

let config = &configs[0].config;
assert_eq!(config.path, path);
assert_eq!(config.options.type_aware, Some(true));
assert_eq!(config.extends_configs.len(), 1);
assert_eq!(config.extends_configs[0].options.type_check, Some(true));
}
}
1 change: 0 additions & 1 deletion apps/oxlint/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ const DEFAULT_JSONC_OXLINTRC_NAME: &str = ".oxlintrc.jsonc";
const DEFAULT_TS_OXLINTRC_NAME: &str = "oxlint.config.ts";
/// Vite config file that may contain oxlint config under a `.lint` field.
const VITE_CONFIG_NAME: &str = "vite.config.ts";
const VITE_OXLINT_CONFIG_FIELD: &str = "lint";

/// Return a JSON blob containing metadata for all available oxlint rules.
///
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
# Exit code
1
0

# stdout
```
Failed to parse oxlint configuration file.
! eslint(no-debugger): `debugger` statement is not allowed
,-[files/test.js:1:1]
1 | debugger;
: ^^^^^^^^^
`----
help: Remove the debugger statement

x Expected a `lint` field in the default export of <fixture>/vite.config.ts
Found 1 warning and 0 errors.
Finished in Xms on 1 file with 93 rules using X threads.
```

# stderr
Expand Down
Loading