diff --git a/.buildkite/ci.ts b/.buildkite/ci.ts index 78b7ee63b4b6..dbf42e39c7c5 100755 --- a/.buildkite/ci.ts +++ b/.buildkite/ci.ts @@ -998,13 +998,6 @@ function getImageSteps( { ...waitStep, label: `${getImageLabel(platform)} - bake-image`, - env: { - // Packer needs several minutes to delete its temp Azure resources after a cancel; - // the agent's default 10s grace SIGKILLs it mid-cleanup and leaks a full - // VM/NIC/IP stack per retry. The agent reads this from job env — there's no - // step-level property for it. - BUILDKITE_SIGNAL_GRACE_PERIOD_SECONDS: `${10 * 60}`, - }, // One command, so that a cancel reaches Packer (see bakeWindowsImage). command: `node ./scripts/ci-image.ts bake-image --key=${key} --name=${name} --timeout-minutes=${bakeTimeout - 10}`, }, @@ -1069,8 +1062,9 @@ function getWindowsSignStep(windowsPlatforms: Platform[], options: PipelineOptio }), retry: getRetry(), cancel_on_build_failing: isMergeQueue(), + // smctl runs signtool.exe, which is only in PATH in a Visual Studio environment. command: [ - `powershell -NoProfile -ExecutionPolicy Bypass -File .buildkite/scripts/sign-windows-artifacts.ps1 ` + + `pwsh -NoProfile -File .\\scripts\\vs-shell.ps1 pwsh -NoProfile -File .\\.buildkite\\scripts\\sign-windows-artifacts.ps1 ` + `-Artifacts ${artifacts.join(",")} ` + `-BuildSteps ${buildSteps.join(",")}`, ], diff --git a/.buildkite/hooks/pre-exit b/.buildkite/hooks/pre-exit index 1d55d9636152..aaf516496505 100755 --- a/.buildkite/hooks/pre-exit +++ b/.buildkite/hooks/pre-exit @@ -30,13 +30,10 @@ status="${BUILDKITE_COMMAND_EXIT_STATUS:-0}" # (buildkite/agent@3ab8ab31, v3.94.0+), and additionally # BUILDKITE_JOB_TIMED_OUT=true when the cancel was a job-level timeout. if [ "${BUILDKITE_JOB_CANCELLED:-}" = "true" ]; then exit 0; fi -# TODO(ci): the exit-code fallback below is only needed while agents older than -# v3.94.0 remain in the fleet (as of 2026-07: the linux queue=ci image is still -# on v3.87.0 and several bare-metal darwin boxes are on v3.87.0/v3.94.0; -# scripts/build/ci-images/spec.ts pins 3.114.0 for every baked image). -# -1 is the posix agent-killed code, 3221225786 is Windows STATUS_CONTROL_C_EXIT, -# both observed on cancel in build 76127. Delete this `case` once every agent is -# v3.94.0+. +# TODO(ci): the exit-code fallback below is only needed for agents older than +# v3.94.0. -1 is the posix agent-killed code, 3221225786 is Windows +# STATUS_CONTROL_C_EXIT, both observed on cancel in build 76127. Delete this +# `case` once every agent is v3.94.0+. case "$status" in -1|3221225786) exit 0 ;; esac if buildkite-agent meta-data exists "reported-${BUILDKITE_JOB_ID}" 2>/dev/null; then diff --git a/.buildkite/scripts/sign-windows-artifacts.ps1 b/.buildkite/scripts/sign-windows-artifacts.ps1 index 9be47625887c..bcc3a015ffdf 100644 --- a/.buildkite/scripts/sign-windows-artifacts.ps1 +++ b/.buildkite/scripts/sign-windows-artifacts.ps1 @@ -9,7 +9,7 @@ # with the same name so downstream steps (release, tests) see signed binaries. param( - # Comma-separated list. powershell.exe -File passes everything as + # Comma-separated list. pwsh -File passes everything as # literal strings, so [string[]] with "a,b,c" becomes a 1-element array. [Parameter(Mandatory=$true)] [string]$Artifacts, @@ -25,10 +25,6 @@ $ProgressPreference = "SilentlyContinue" $ArtifactList = $Artifacts -split "," $BuildStepList = $BuildSteps -split "," -# smctl shells out to signtool.exe which is only in PATH when the VS dev -# environment is loaded. Dot-source the existing helper to set it up. -. $PSScriptRoot\..\..\scripts\vs-shell.ps1 - function Log-Info { param([string]$Message) Write-Host "[INFO] $Message" -ForegroundColor Cyan @@ -262,6 +258,11 @@ try { } Log-Info "Will sign $($ArtifactList.Count) artifacts: $($ArtifactList -join ', ')" + # smctl runs signtool.exe and exits 0 when it cannot. + if (!(Get-Command signtool.exe -ErrorAction SilentlyContinue)) { + throw "signtool.exe is not in PATH. Run this script through scripts/vs-shell.ps1." + } + Ensure-Secrets Setup-Certificate $smctl = Install-KeyLocker diff --git a/.buildkite/scripts/upload-release.sh b/.buildkite/scripts/upload-release.sh index 9e1259c189f9..0bdbad3a5e4f 100755 --- a/.buildkite/scripts/upload-release.sh +++ b/.buildkite/scripts/upload-release.sh @@ -28,7 +28,7 @@ function assert_main() { function assert_buildkite_agent() { if ! command -v "buildkite-agent" &> /dev/null; then echo "error: Cannot find buildkite-agent, please install it:" - echo "https://buildkite.com/docs/agent/v3/install" + echo "https://buildkite.com/docs/agent/self-hosted/install" exit 1 fi } diff --git a/.buildkite/update-test-durations.yml b/.buildkite/update-test-durations.yml index 117125922254..72092a204c86 100644 --- a/.buildkite/update-test-durations.yml +++ b/.buildkite/update-test-durations.yml @@ -9,12 +9,10 @@ steps: if: build.source == "schedule" || build.source == "ui" agents: queue: build-linux + # The scripts read BUILDKITE_API_TOKEN. The agent that runs this step has to + # provide it: `pipeline upload` refuses a pipeline with a secret interpolated in. command: | node scripts/update-test-durations.mjs --builds 5 node scripts/update-parallel-allowlist.mjs --builds 300 buildkite-agent artifact upload test/expected-durations.json buildkite-agent artifact upload test/parallel-allowlist.json - env: - # The script reads BUILDKITE_API_TOKEN; the agent environment hook - # already exports a read-scoped token under this name. - BUILDKITE_API_TOKEN: "$BUILDKITE_API_TOKEN" diff --git a/.claude/skills/implementing-jsc-classes-rust/SKILL.md b/.claude/skills/implementing-jsc-classes-rust/SKILL.md index 26e7aca01215..624941049c7f 100644 --- a/.claude/skills/implementing-jsc-classes-rust/SKILL.md +++ b/.claude/skills/implementing-jsc-classes-rust/SKILL.md @@ -1,133 +1,76 @@ --- name: implementing-jsc-classes-rust -description: Creates JavaScript classes using Bun's Rust bindings generator (.classes.ts). Use when implementing new JS APIs in Rust with JSC integration, prototypes, or constructors. +description: Creates JavaScript classes using Bun's bindings generator (.bind.ts). Use when implementing new JS APIs in Rust with JSC integration, prototypes, or constructors. --- -# Bun's JavaScriptCore Class Bindings Generator +# JavaScript classes implemented in Rust -Bridge JavaScript and Rust through `.classes.ts` definitions and Rust implementations. +A class is a `b.class({..})` exported from a `*.bind.ts` file and a Rust struct. `src/codegen/bindgen.ts` generates the C++ +cell, prototype and constructor, the argument conversions, and the Rust functions that call the struct's methods. +`docs/project/bindgen.mdx` is the reference: read its "Classes" section before writing one. -`src/codegen/bindgen.ts` (`*.bind.ts`, `docs/project/bindgen.mdx`) is replacing this generator: typed arguments, and the struct stored inside the JS object. Use it for a class whose struct only the JS object owns. It does not do ref-counted or shared structs, `hasPendingActivity`, `estimatedSize` or writing to a cached getter's slot yet. - -## Architecture - -1. **JavaScript Interface Definition** (`.classes.ts` files) -2. **Rust Implementation** (`.rs` files) -3. **Generated Code** — `src/codegen/generate-classes.ts` emits C++ + Rust into `${BUN_CODEGEN_DIR}/generated_classes.rs`, `include!`d as `crate::generated_classes` in `bun_runtime`. Run `bun bd` to regenerate. - -## Class Definition (.classes.ts) +## Schema ```typescript -export default [ - define({ - name: "Matcher", - construct: true, - finalize: true, - hasPendingActivity: true, - proto: { - scan: { fn: "scan", length: 1 }, - match: { fn: "match", length: 1 }, - }, - }), -]; +import * as b from "../../codegen/bindgen-lib.ts"; + +export const Matcher = b.class({ + rustPath: "crate::api::matcher::Matcher", + construct: { args: { pattern: b.string.utf8 } }, + internalFields: ["callback"], + proto: { + match: { args: { text: b.string.utf8 }, returns: b.bool }, + pattern: { getter: b.string.utf8, cache: true }, + }, +}); ``` -Options: - -- `construct`: Has a public `new Foo()` constructor -- `finalize`: Needs cleanup beyond `Drop` (rarely — see Finalize below) -- `hasPendingActivity`: GC keep-alive while async work is in flight -- `proto`: Methods (`fn:`), getters (`getter: true`, optionally `cache: true`) -- `values: [...]`: WriteBarrier slots for JS values the native side holds (callbacks, buffers) - -## Rust Implementation +## Rust ```rust -use bun_jsc::{CallFrame, JSGlobalObject, JSValue, JsResult}; -use std::sync::atomic::{AtomicUsize, Ordering}; - -#[bun_jsc::JsClass] pub struct Matcher { pattern: Box<[u8]>, - has_pending_activity: AtomicUsize, } impl Matcher { - pub fn constructor(global: &JSGlobalObject, frame: &CallFrame) -> JsResult> { - let arg = frame.argument(0); - let pattern = bun_core::String::from_js(arg, global)?.to_utf8_bytes().into(); - Ok(Box::new(Matcher { pattern, has_pending_activity: AtomicUsize::new(0) })) + pub fn constructor(pattern: &[u8]) -> Self { + Self { pattern: pattern.into() } } - #[bun_jsc::host_fn(method)] - pub fn r#match(&self, global: &JSGlobalObject, frame: &CallFrame) -> JsResult { - // ... - Ok(JSValue::TRUE) + pub fn r#match(&self, text: &[u8]) -> bool { + bun_core::strings::contains(text, &self.pattern) } - pub fn has_pending_activity(&self) -> bool { - self.has_pending_activity.load(Ordering::SeqCst) > 0 + pub fn get_pattern(&self) -> &[u8] { + &self.pattern } } ``` -### Canonical signatures - -| Hook | Signature | -| ------------------- | ------------------------------------------------------------------------------------ | -| constructor | `pub fn constructor(global: &JSGlobalObject, frame: &CallFrame) -> JsResult>` | -| method (`fn:`) | `pub fn name(&self, global: &JSGlobalObject, frame: &CallFrame) -> JsResult` | -| getter | `pub fn get_x(this: &Self, global: &JSGlobalObject) -> JsResult` | -| finalize | `pub fn finalize(self: Box)` — or omit; the blanket `JsFinalize` just drops | -| hasPendingActivity | `pub fn has_pending_activity(&self) -> bool` | - -A missing or mis-typed hook is a **compile error** in `cargo check -p bun_runtime` — the generated code calls the inherent method directly. - -## Hooking into the generated module - -`#[bun_jsc::JsClass]` on the struct implements the `JsClass` trait (`to_js`, `from_js`, `from_js_direct`, `get_constructor`) by binding the C++ externs. Attribute knobs: `no_constructor`, `no_finalize`, `estimated_size`. - -The codegen also emits a `js_$T` module with the cached-value accessors. Re-export it when you need `*_set_cached` / `*_get_cached` or `detach_ptr`: - -```rust -pub use crate::generated_classes::js_Image as js; -// or -bun_jsc::impl_js_class_via_generated!(Archive => crate::generated_classes::js_Archive); -``` - -The `js_$T` module surface: +A missing or mis-typed method is a compile error: the generated code calls it directly. -```rust -pub fn from_js(value: JSValue) -> Option>; -pub fn from_js_direct(value: JSValue) -> Option>; -pub fn get_constructor(global: &JSGlobalObject) -> JSValue; -pub fn to_js(this: *mut T, global: &JSGlobalObject) -> JSValue; // ownership transfer -pub fn detach_ptr(value: JSValue); -// per cached getter / `values: [...]` entry: -pub fn _set_cached(this_value: JSValue, global: &JSGlobalObject, value: JSValue); -pub fn _get_cached(this_value: JSValue) -> Option; -``` +## Where the struct lives -## Finalize +- Freed when its JS object is freed: it is stored inside the object. This is the default. Cleanup is `Drop`. +- Can outlive its object (a timer, another thread or a C library still points at it): `refCounted: true`. It is a separate, + refcounted heap allocation, and the object holds one ref. -Most classes need nothing — `#[bun_jsc::JsClass]` wires the blanket `JsFinalize` whose default is `drop(Box)`. Override only when you must release a JS handle or defer to a heap helper: +## What a body may do -```rust -pub fn finalize(self: Box) { - bun_ptr::finalize_js_box(self, |this| this.this_value.with_mut(|v| v.finalize())); -} -``` +`capability: "heap"` adds `heap: &JsHeap<'a>` (allocate, throw). `capability: "js"` adds `cx: &mut JsScope<'a>` (also run +JavaScript); `cx.global()` is the `&JSGlobalObject` the rest of the tree takes. `throws: true` makes the result a +`JsResult`. `passThis: true` adds the object, `this_value: JsWrapper<'a, Self>`. -Override with an **inherent** method, never `impl JsFinalize for T`. +Every member takes `&self`; state that changes is in `Cell` or `JsCell`. ## Holding JS values -Never store raw `JSValue` in a struct field. Declare a slot in `.classes.ts` (`values: ["callback"]` or a `cache: true` getter) and read/write it through `js::callback_set_cached(this_value, global, v)` / `js::callback_get_cached(this_value)`. The slot is a `WriteBarrier` visited by the GC, so the value stays alive without a `Strong`. +Never store a raw `JSValue` in a struct field. Declare an internal field (`internalFields: ["callback"]` or a `cache: true` +getter) and use `js_Matcher::callback_set_cached(this_value, global, value)` / `callback_get_cached(this_value)` from +`crate::generated_bindgen::`. To reach its own object the struct stores a `JsRef`. ## Reference implementations -- `src/runtime/api/Shell.classes.ts` — constructor, methods, `hasPendingActivity` -- `src/runtime/api/cron.rs` + `cron.classes.ts` — `noConstructor`, cached getter, `values: [...]`, custom finalize -- `src/runtime/image/Image.rs:56` — the `pub use crate::generated_classes::js_Image as js;` one-liner -- `src/jsc/host_fn.rs` — the host-fn adapters the codegen dispatches through -- `src/jsc_macros/lib.rs` — `#[bun_jsc::JsClass]` proc-macro source +- `src/jsc/bindgen_test.bind.ts` + `src/jsc/bindgen_test.rs`: an example of most keys +- `src/jsc/resolve_message.bind.ts`: cached getters, `prototypeBase`, `construct: "illegal"` +- `src/runtime/api/cron.bind.ts`: `refCounted`, `finalize` diff --git a/.claude/skills/javascriptcore-garbage-collector/SKILL.md b/.claude/skills/javascriptcore-garbage-collector/SKILL.md index 79b075187e10..6f83de6dbc6a 100644 --- a/.claude/skills/javascriptcore-garbage-collector/SKILL.md +++ b/.claude/skills/javascriptcore-garbage-collector/SKILL.md @@ -166,7 +166,7 @@ void JSFoo::visitOutputConstraints(JSCell* cell, Visitor& visitor) { **Why two entry points?** `visitChildren` runs once when the cell turns grey. But marking may later discover that some _other_ native object (an opaque root) is live, which retroactively makes more of _this_ cell's references live. `visitOutputConstraints` is re-invoked by `DOMGCOutputConstraint` during the constraint fixpoint to catch that. -To make a class participate, its IsoSubspace must be registered as an **output-constraint subspace** (`clientSubspaceFor*` with `outputConstraint` in `BunClientData` / generated `ZigGeneratedClasses.cpp`). The codegen does this automatically when `.classes.ts` has `hasPendingActivity`, `own` properties, or event-target semantics. +To make a class participate, its IsoSubspace must be registered as an **output-constraint subspace** (`clientSubspaceFor*` with `outputConstraint` in `BunClientData`). ## Opaque roots — liveness through non-JSCell pointers @@ -243,9 +243,7 @@ self.this_value.finalize(); See `ServerWebSocket`, `UDPSocket`, `MySQLConnection`, `ValkeyClient` for real examples. -**`JSRef` requires a finalizer.** The `Weak` state is only sound because the codegen'd `finalize()` flips it to `Finalized` before the cell is reused. If your `.classes.ts` entry has `finalize: true` (almost all native-backed classes do), `JSRef` is the default choice for self-references. - -**`JSRef` vs `hasPendingActivity`:** prefer `JSRef`. `hasPendingActivity: true` is a GC-thread-polled atomic predicate; its only real justification is when **many concurrent operations** independently keep the wrapper alive and there's no single place to call `upgrade()`/`downgrade()` — i.e., refcount-style liveness where the count is touched from multiple threads. That's uncommon. If you can identify "work started" / "work finished" edges, use `JSRef`. Don't add `hasPendingActivity` reflexively; it costs a constraint-fixpoint poll on every GC. +**`JSRef` requires a finalizer.** The `Weak` state is only sound because `finalize()` flips it to `Finalized` before the cell is reused. A `refCounted` class of a `.bind.ts` file declares `finalize: true` and calls `JsRef::finalize` from its `fn finalize(&self)`; a struct stored inside its object is dropped with it. ## `gcProtect` / `JSValueProtect` — almost never @@ -276,7 +274,7 @@ visitor.reportExtraMemoryVisited(thisObject->wrapped().byteSize()); - If the size changes over time, report the delta on growth (`reportExtraMemoryAllocated(cell, newSize - oldSize)`) and report the current size in `visitChildren`. - `deprecatedReportExtraMemory` exists for callers that can't satisfy the visit-side half — avoid it. -In `.classes.ts`, `estimatedSize: true` generates the `reportExtraMemoryVisited` side; you implement `estimated_size()` in Rust. You still call `reportExtraMemoryAllocated` (or the binding's helper) at allocation time. +In a `.bind.ts` class, `estimatedSize: true` generates both sides; you implement `estimated_size()` in Rust, which marking threads call. For growth after the object is created you still call `vm.report_extra_memory`. ## `HeapAnalyzer` — heap snapshots and labelling @@ -305,25 +303,24 @@ If your class shows up as an opaque blob in heap snapshots, implement `analyzeHe ## How to keep things alive (decision table) -| Scenario | Mechanism | -| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -| JSCell field pointing to another JSCell | `WriteBarrier` member + `visitor.append(m_field)` in `visitChildren` | -| Native state inside the wrapped C++ object holds JS values | `visitAdditionalChildren` + register subspace as output-constraint | -| C++/Rust local across allocation/call | Conservative scan (free) — add `EnsureStillAliveScope` / `value.ensure_still_alive()` if extracting interior pointers or seeing release-only crashes | -| Native object holds its own JS wrapper (class has `finalize: true`) | **`JSRef`** — `upgrade()` when work starts, `downgrade()` when idle. **This is the default.** | -| Native object owns an arbitrary JS value (callback, options object) | `bun_jsc::Strong` — drop in `finalize()`. Watch for cycles | -| C++ non-GC object owns a JS value as a root | `JSC::Strong`. **Danger:** cycle if the JS value can reach back → leak | -| Weak ref with resurrection predicate / finalize callback (C++) | `JSC::Weak` + `WeakHandleOwner` | -| Wrapper kept alive by **many concurrent operations** with no single busy/idle edge | `.classes.ts` `hasPendingActivity: true` (atomic flag polled on GC thread). **Uncommon — prefer `JSRef` if you can.** | -| Group of wrappers share lifetime via a native graph | `visitor.addOpaqueRoot(ptr)` + `containsOpaqueRoot(ptr)` | -| Temporarily forbid GC in a critical section | `DeferGC deferGC(vm)` — defers until scope exit. Never hold across user JS | -| Tell GC about off-heap memory you own | `reportExtraMemoryAllocated` on alloc **and** `reportExtraMemoryVisited` in `visitChildren` | -| ~~Mark a value as root from C API~~ | ~~`gcProtect` / `JSValueProtect`~~ — **avoid**; use `bun_jsc::Strong` / `JSRef` instead | +| Scenario | Mechanism | +| ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | +| JSCell field pointing to another JSCell | `WriteBarrier` member + `visitor.append(m_field)` in `visitChildren` | +| Native state inside the wrapped C++ object holds JS values | `visitAdditionalChildren` + register subspace as output-constraint | +| C++/Rust local across allocation/call | Conservative scan (free) — add `EnsureStillAliveScope` / `value.ensure_still_alive()` if extracting interior pointers or seeing release-only crashes | +| Native object holds its own JS wrapper (class has `finalize: true`) | **`JSRef`** — `upgrade()` when work starts, `downgrade()` when idle. **This is the default.** | +| Native object owns an arbitrary JS value (callback, options object) | `bun_jsc::Strong` — drop in `finalize()`. Watch for cycles | +| C++ non-GC object owns a JS value as a root | `JSC::Strong`. **Danger:** cycle if the JS value can reach back → leak | +| Weak ref with resurrection predicate / finalize callback (C++) | `JSC::Weak` + `WeakHandleOwner` | +| Group of wrappers share lifetime via a native graph | `visitor.addOpaqueRoot(ptr)` + `containsOpaqueRoot(ptr)` | +| Temporarily forbid GC in a critical section | `DeferGC deferGC(vm)` — defers until scope exit. Never hold across user JS | +| Tell GC about off-heap memory you own | `reportExtraMemoryAllocated` on alloc **and** `reportExtraMemoryVisited` in `visitChildren` | +| ~~Mark a value as root from C API~~ | ~~`gcProtect` / `JSValueProtect`~~ — **avoid**; use `bun_jsc::Strong` / `JSRef` instead | ## Destruction & finalizers - `static constexpr bool needsDestruction = true` → C++ destructor runs when the cell is swept. Sweep is **lazy** (next allocation from that block, or `IncrementalSweeper`), so destruction is delayed arbitrarily. Do not rely on it for prompt resource release — expose explicit `close()`/`dispose()`. -- In `.classes.ts`, `finalize: true` → native `finalize()` called from the destructor. Same laziness applies. +- In a `.bind.ts` class, `Drop` of the struct, or `finalize: true` → `fn finalize(&self)` of a `refCounted` one, runs from `destroy`. Same laziness applies. - `WeakHandleOwner::finalize` runs earlier (at weak-reap time) but the cell is already dead; only use it to clear caches. - Destructors run on the mutator thread but **other JS objects may already be swept** — do not dereference `WriteBarrier` fields in a destructor. @@ -363,4 +360,4 @@ If GC runs constantly with little garbage → missing `reportExtraMemoryVisited` - `vendor/WebKit/Source/JavaScriptCore/heap/HeapAnalyzer.h`, `vendor/WebKit/Source/JavaScriptCore/heap/HeapSnapshotBuilder.cpp`, Bun: `vendor/WebKit/Source/JavaScriptCore/heap/BunV8HeapSnapshotBuilder.cpp` - `vendor/WebKit/Source/JavaScriptCore/heap/DeferGC.h`, `vendor/WebKit/Source/JavaScriptCore/heap/Strong.h`, `vendor/WebKit/Source/JavaScriptCore/heap/HandleSet.h` - `runtime/JSCell.h` / `JSCellInlines.h` — header layout, `visitChildren` base -- Bun: `src/jsc/bindings/BunGCOutputConstraint.cpp`, `ZigGeneratedClasses.cpp` (codegen'd `visitChildren` / `visitOutputConstraints`) +- Bun: `src/jsc/bindings/BunGCOutputConstraint.cpp`, `Generated*.cpp` in the build's codegen directory (generated `visitChildren`) diff --git a/.github/workflows/openclaw-build-test.yml b/.github/workflows/openclaw-build-test.yml index 9118c5d4d7c9..948aee752628 100644 --- a/.github/workflows/openclaw-build-test.yml +++ b/.github/workflows/openclaw-build-test.yml @@ -48,7 +48,7 @@ jobs: persist-credentials: false - uses: ./.github/actions/setup-bun with: - bun-version: "1.4.2" + bun-version: "1.4.4" - name: Read toolchain pins id: pins run: | @@ -169,7 +169,7 @@ jobs: persist-credentials: false - uses: ./.github/actions/setup-bun with: - bun-version: "1.4.2" + bun-version: "1.4.4" - name: Read toolchain pins id: pins run: | diff --git a/.github/workflows/openclaw-release.yml b/.github/workflows/openclaw-release.yml index 0253accda952..3f0d4ed84d2d 100644 --- a/.github/workflows/openclaw-release.yml +++ b/.github/workflows/openclaw-release.yml @@ -71,7 +71,7 @@ jobs: - name: Setup Bun uses: ./pipeline/.github/actions/setup-bun with: - bun-version: "1.4.2" + bun-version: "1.4.4" - name: Test pipeline working-directory: pipeline run: bun test test/internal/source-lints/openclaw-release.test.ts @@ -120,7 +120,7 @@ jobs: - name: Setup Bun uses: ./pipeline/.github/actions/setup-bun with: - bun-version: "1.4.2" + bun-version: "1.4.4" - name: Generate provisioning script id: provision env: @@ -418,7 +418,7 @@ jobs: persist-credentials: false - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 with: - node-version: "26.3.0" + node-version: "26.12.1" - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: name: ${{ matrix.artifact }} @@ -468,7 +468,7 @@ jobs: - name: Setup Bun uses: ./pipeline/.github/actions/setup-bun with: - bun-version: "1.4.2" + bun-version: "1.4.4" - name: Download uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f2095bec0647..7d1fecf7eae3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -75,7 +75,7 @@ jobs: - name: Setup Bun uses: ./.github/actions/setup-bun with: - bun-version: "1.4.2" + bun-version: "1.4.4" - name: Install Dependencies run: bun install - name: Sign Release @@ -104,7 +104,7 @@ jobs: - name: Setup Bun uses: ./.github/actions/setup-bun with: - bun-version: "1.4.2" + bun-version: "1.4.4" - name: Install Dependencies run: bun install - name: Release @@ -135,7 +135,7 @@ jobs: if: ${{ env.BUN_VERSION != 'canary' }} uses: ./.github/actions/setup-bun with: - bun-version: "1.4.2" + bun-version: "1.4.4" - name: Setup Bun if: ${{ env.BUN_VERSION == 'canary' }} uses: ./.github/actions/setup-bun @@ -189,7 +189,7 @@ jobs: - name: Setup Bun uses: ./bun/.github/actions/setup-bun with: - bun-version: "1.4.2" + bun-version: "1.4.4" - id: bun-version run: echo "BUN_VERSION=${BUN_VERSION#bun-v}" >> "$GITHUB_OUTPUT" - name: Update bun-types version in package.json @@ -304,7 +304,7 @@ jobs: - name: Setup Ruby uses: ruby/setup-ruby@a0102e0972be65f351c307e2d64b9314a57c8073 # v1 with: - ruby-version: "2.6" + ruby-version: "3.4" - name: Update Tap run: ruby scripts/release.rb "$BUN_VERSION" - name: Commit Tap @@ -333,7 +333,7 @@ jobs: - name: Setup Bun uses: ./.github/actions/setup-bun with: - bun-version: "1.4.2" + bun-version: "1.4.4" - name: Install Dependencies run: bun install - name: Release diff --git a/.github/workflows/rust-lints.yml b/.github/workflows/rust-lints.yml index 3f90a4affc50..157f2c997d91 100644 --- a/.github/workflows/rust-lints.yml +++ b/.github/workflows/rust-lints.yml @@ -9,7 +9,6 @@ on: paths: - "src/**/*.rs" - "src/**/Cargo.toml" - - "src/**/*.classes.ts" - "src/**/*.bind.ts" - "src/codegen/**" - "scripts/build/**" @@ -34,7 +33,7 @@ concurrency: cancel-in-progress: true env: - BUN_VERSION: "1.4.2" + BUN_VERSION: "1.4.4" LLVM_VERSION_MAJOR: "23" # Pin the toolchain explicitly so rustup ignores rust-toolchain.toml's # `targets` list (11 cross triples ≈ 450 MB of prebuilt std we don't need diff --git a/.github/workflows/source-lints.yml b/.github/workflows/source-lints.yml index 5af3365ed742..43ab98e42adf 100644 --- a/.github/workflows/source-lints.yml +++ b/.github/workflows/source-lints.yml @@ -15,7 +15,7 @@ on: - "src/**/*.rs" - "src/**/*.h" - "src/**/*.cpp" - - "src/**/*.classes.ts" + - "src/**/*.bind.ts" - "src/codegen/**" - "src/js/builtins.d.ts" - "src/jsc/bindings/**" @@ -39,7 +39,7 @@ on: - "src/**/*.rs" - "src/**/*.h" - "src/**/*.cpp" - - "src/**/*.classes.ts" + - "src/**/*.bind.ts" - "src/codegen/**" - "src/js/builtins.d.ts" - "src/jsc/bindings/**" @@ -61,7 +61,7 @@ on: merge_group: env: - BUN_VERSION: "1.4.2" + BUN_VERSION: "1.4.4" jobs: source-lints: diff --git a/.github/workflows/vscode-release.yml b/.github/workflows/vscode-release.yml index 4864e5603d1b..aa555f7ec10f 100644 --- a/.github/workflows/vscode-release.yml +++ b/.github/workflows/vscode-release.yml @@ -24,7 +24,7 @@ jobs: - name: Setup Bun uses: ./.github/actions/setup-bun with: - bun-version: "1.4.2" + bun-version: "1.4.4" - name: Install dependencies (root) run: bun install diff --git a/AGENTS.md b/AGENTS.md index 64930d94376a..e331048cdd2c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -116,7 +116,7 @@ test("(multi-file test) my feature", async () => { - **Rust code** (`src/**/*.rs`): Core runtime, JavaScript bindings, bundler, package manager. This is what compiles and ships. - **C++ code** (`src/jsc/bindings/*.cpp`): JavaScriptCore bindings, Web APIs - **TypeScript** (`src/js/`): Built-in JavaScript modules with special syntax (see JavaScript Modules section) -- **Generated code**: Many `.rs` and `.cpp` files are auto-generated from `.classes.ts` and other sources. The build regenerates them automatically when their inputs change. +- **Generated code**: Many `.rs` and `.cpp` files are auto-generated from `.bind.ts` schemas and other sources. The build regenerates them automatically when their inputs change. ### Core Source Organization @@ -131,7 +131,7 @@ The Rust side is a Cargo workspace of ~200 crates rooted at `Cargo.toml`. The ke - `src/transpiler/` - Wrapper around the parser/printer with sourcemap support - `src/resolver/` - Module resolution system - `src/ast/` - AST node types and arena allocation -- `src/jsc/bindings/` - C++ JavaScriptCore bindings (generated classes from `.classes.ts` + manual bindings) +- `src/jsc/bindings/` - C++ JavaScriptCore bindings (generated classes from `.bind.ts` schemas + manual bindings) - `src/jsc/` - Rust-side JSC glue (`VirtualMachine.rs`, `web_worker.rs`, `event_loop.rs`, FFI imports) - `src/runtime/api/` - Bun-specific JS-visible APIs (`BunObject.rs`, `JSBundler.rs`, `Glob`, `Archive`, …) - `src/runtime/server/` - `Bun.serve` HTTP/WebSocket server @@ -167,7 +167,7 @@ When implementing JavaScript classes in C++: Code generation happens automatically as part of the build process. The main scripts are: -- `src/codegen/generate-classes.ts` - Generates Rust & C++ bindings from `*.classes.ts` files +- `src/codegen/bindgen.ts` - Generates Rust & C++ bindings from `*.bind.ts` schemas - `src/codegen/generate-jssink.ts` - Generates stream-related classes - `src/codegen/bundle-modules.ts` - Bundles built-in modules like `node:fs` - `src/codegen/bundle-functions.ts` - Bundles global functions like `ReadableStream` diff --git a/CHANGELOG.md b/CHANGELOG.md index 6832ea81856a..1d7f7098b92d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ ## Unreleased +- Sync oven-sh/bun through `a8fcd319be58ad4d284330b86602cfb3c8e49c83`, including native-binding schema migration, source-position updates, and runtime hardening while retaining fork compatibility and source-sharing fixes. + +- Preserve the relative tail when `path.win32.resolve()` falls back to a different drive's root. + +- Avoid a panic when `bun create` selects a certificate store. + +- Keep a TLS socket's native context alive while delayed transport shutdown re-enters the event loop. + +- Preserve reusable transpiler-cache entries when source maps are explicitly disabled. + +- Preserve custom Headers iterators when `server.fetch()` copies request headers. + - Back out Error.cause serialization (#192, #194) pending a performance-neutral design. - Back out Buffer trailer reservation (#195) for its small-payload serialization cost, pending a design that charges only large-Buffer paths. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0cdd3d914b6c..af1aee0fcd4f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -201,7 +201,7 @@ Several code generation scripts are used during Bun's build process. These are r In particular, these are: - `./src/codegen/generate-jssink.ts` -- Generates `build/debug/codegen/JSSink.cpp`, `build/debug/codegen/JSSink.h` which implement various classes for interfacing with `ReadableStream`. This is internally how `FileSink`, `ArrayBufferSink`, `"type": "direct"` streams and other code related to streams works. -- `./src/codegen/generate-classes.ts` -- Generates Rust & C++ bindings for JavaScriptCore classes implemented in Rust. In `**/*.classes.ts` files, we define the interfaces for various classes, methods, prototypes, getters/setters etc which the code generator reads to generate boilerplate code implementing the JavaScript objects in C++ and wiring them up to Rust. +- `./src/codegen/bindgen.ts` -- Generates Rust, C++ & TypeScript bindings for functions and JavaScriptCore classes implemented in Rust. `**/*.bind.ts` files declare the functions, classes, methods, getters/setters and the types of their arguments; the generator emits the C++ objects, the argument conversions and the calls into Rust. See [Bindgen](/project/bindgen). - `./src/codegen/cppbind.ts` -- Scans the C++ bindings for functions marked with an export attribute and generates automatic Rust FFI wrappers (`cpp.rs`) for them. - `./src/codegen/bundle-modules.ts` -- Bundles built-in modules like `node:fs`, `bun:ffi` into files we can include in the final binary. In development, these can be reloaded without rebuilding native code (you still need to run `bun run build`, but it re-reads the transpiled files from disk afterwards). In release builds, these are embedded into the binary. - `./src/codegen/bundle-functions.ts` -- Bundles globally-accessible functions implemented in JavaScript/TypeScript like `ReadableStream`, `WritableStream`, and a handful more. These are used similarly to the builtin modules, but the output more closely aligns with what WebKit/Safari does for Safari's built-in functions so that we can copy-paste the implementations from WebKit as a starting point. diff --git a/Cargo.lock b/Cargo.lock index 96cd939cd20d..09cc74d2747c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1655,11 +1655,9 @@ dependencies = [ "bun_alloc", "bun_core", "bun_js_parser", - "bun_paths", "bun_sema", "bun_sema_baselines", "bun_sema_driver", - "bun_sema_parser", "bun_sys", "bun_threading", "libc", @@ -1749,17 +1747,17 @@ dependencies = [ name = "bun_sourcemap_jsc" version = "0.0.0" dependencies = [ - "bstr", "bun_alloc", "bun_ast", "bun_collections", "bun_core", "bun_io", + "bun_js_parser", + "bun_js_printer", "bun_jsc", "bun_options_types", "bun_paths", "bun_sourcemap", - "bun_url", "bun_wyhash", ] diff --git a/Cargo.toml b/Cargo.toml index 985da8472b40..2f3934682524 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -281,7 +281,7 @@ clone_on_copy = "deny" useless_conversion = "deny" # vec_box / boxed_local: legit patterns are `#[expect]`-suppressed at the site # with a one-line "why the box is load-bearing" comment (intrusive-list address -# stability, JsClass finalizer thunk contract). Anything new must justify itself. +# stability, a task's reclaim point). Anything new must justify itself. vec_box = "deny" boxed_local = "deny" arc_with_non_send_sync = "deny" diff --git a/REVIEW.md b/REVIEW.md index 909abbbc5229..b95ec92bb5b2 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -23,7 +23,7 @@ Several situational sections live in `.claude/docs/landing-prs.md` — read the - **Treat all size/index/length arithmetic on external data as adversarial.** Bounds-check the TOTAL bytes of a record before reading fields; re-establish bounds after every re-slice; validate header-derived counts before using them as loop bounds. Size output buffers for worst-case OUTPUT expansion, not input size. Widen before multiplying untrusted quantities; clamp kernel/peer-reported lengths to capacity. Debug assertions compile out — validation of untrusted input must survive release builds. Zero-init out-params and every slot a GC visitor or destructor can walk. - **Exception checks after every call that can enter JS.** Every call that can throw or run user code (toString/toNumber, getIfPropertyExists, getIndex, coercions, callbacks) needs RETURN_IF_EXCEPTION under a ThrowScope (C++) or JSError propagation (Rust) before its result is used. Never call non-throwing accessors (asNumber, jsCast, getDirect) on user values without validating type first. Never clearException(). Throwing tail calls go through RELEASE_AND_RETURN; no check macros inside lambdas. Verify with `BUN_JSC_validateExceptionChecks=1` instead of adding suppression-list entries; for calls that provably cannot throw, use scope.assertNoException() with a comment. - **Never let a pointer or slice outlive the memory it points into** (unsafe Rust, C++, FFI). Rejected shapes: slices of stack buffers; pointers into growable containers held across any call that can append; network/parser callback buffers stored without cloning (they are reused); `.data()` of a dead temporary; slices of small-string-optimized values; buffers handed to layers that store them past the call. If background threads reference stack state, every exit path must join them first. -- **Root or copy every JSValue held beyond the current call.** WriteBarrier members declared in `.classes.ts` and visited in visitChildrenImpl (same change); Strong/protect only for justified self-keepalive; MarkedArgumentBuffer for values accumulated across slow calls — never raw JSValues in malloc'd memory or std containers. A Strong ref does not prevent ArrayBuffer detach; pin() is not a GC root; hasPendingActivity uses a counter; zero-copy toSlice-style helpers return borrowed views — consume synchronously or clone. Prove GC-safety with a stress test (thousands of iterations + `Bun.gc(true)`). Don't add Strong refs or ensureStillAlive you can't justify — and don't silently delete existing ones. +- **Root or copy every JSValue held beyond the current call.** `internalFields` of the class's `.bind.ts`, or WriteBarrier members visited in visitChildrenImpl (same change); Strong/protect only for justified self-keepalive; MarkedArgumentBuffer for values accumulated across slow calls — never raw JSValues in malloc'd memory or std containers. A Strong ref does not prevent ArrayBuffer detach; pin() is not a GC root; zero-copy toSlice-style helpers return borrowed views — consume synchronously or clone. Prove GC-safety with a stress test (thousands of iterations + `Bun.gc(true)`). Don't add Strong refs or ensureStillAlive you can't justify — and don't silently delete existing ones. - **Anything that can run user JS can synchronously free your state** — toString/valueOf, getters, Proxy traps, event emits, close(). Do all coercions first while holding no raw pointers; read mutable state (byteLength, typed-array vectors) once, after all observable side effects; re-validate liveness guards after every callback; copy-and-null stored one-shot callbacks before calling them; bracket entry points that can reach synchronous teardown with ref()/defer deref(); register state and listeners BEFORE the call that can trigger them; null member fields before calling close on a local copy. - **Know the thread affinity of every line you touch.** JS-heap operations run only on the JS thread — marshal raw data and enqueue a task. Atomics for every shared counter (even metrics); a mutex only counts if EVERY accessor takes it; benign same-value races are still UB. `thread_isolated_copy()` a string before one other thread touches it, `make_thread_shareable()` before several VMs can reach it; default to seq_cst and comment any weakened ordering. Cross-thread lifetime needs refcounts — a "finalized" boolean cannot prevent UAF. Never invoke callbacks while holding a non-recursive lock. Never back per-VM state with globals or thread-locals — workers share them. - **Reference counts provably balanced on every terminal path** — success, error, cancellation, finalize. Map each ref to a named owner; take a ref only after a fallible enqueue succeeds; never use saturating arithmetic on counts; never add a ref just to silence ASAN — find the actual imbalance. The released ref may be the last one mid-callback; dropping the final reference while holding the object's own lock is UB. diff --git a/dockerhub/alpine/Dockerfile b/dockerhub/alpine/Dockerfile index 63c9f2d5410e..f9aea781ec1f 100644 --- a/dockerhub/alpine/Dockerfile +++ b/dockerhub/alpine/Dockerfile @@ -46,6 +46,7 @@ RUN apk --no-cache add ca-certificates curl gpg gpg-agent unzip \ -fsSLO \ --compressed \ --retry 5 \ + --retry-all-errors \ && gpg --batch --assert-signer F3DCC08A8572C0749B3E18888EAB4D40A7B22B59 \ --verify --output SHASUMS256.verified.txt SHASUMS256.txt.asc \ || (echo "error: failed to verify: $tag" && exit 1) \ diff --git a/dockerhub/debian-slim/Dockerfile b/dockerhub/debian-slim/Dockerfile index ab45830acfcd..debca35b1a23 100644 --- a/dockerhub/debian-slim/Dockerfile +++ b/dockerhub/debian-slim/Dockerfile @@ -54,6 +54,7 @@ RUN apt-get update -qq \ -fsSLO \ --compressed \ --retry 5 \ + --retry-all-errors \ && gpg --batch --assert-signer F3DCC08A8572C0749B3E18888EAB4D40A7B22B59 \ --verify --output SHASUMS256.verified.txt SHASUMS256.txt.asc \ || (echo "error: failed to verify: $tag" && exit 1) \ diff --git a/dockerhub/debian/Dockerfile b/dockerhub/debian/Dockerfile index af6f21e3bef3..ab2cb1959a9d 100644 --- a/dockerhub/debian/Dockerfile +++ b/dockerhub/debian/Dockerfile @@ -58,6 +58,7 @@ RUN apt-get update -qq \ -fsSLO \ --compressed \ --retry 5 \ + --retry-all-errors \ && gpg --batch --assert-signer F3DCC08A8572C0749B3E18888EAB4D40A7B22B59 \ --verify --output SHASUMS256.verified.txt SHASUMS256.txt.asc \ || (echo "error: failed to verify: $tag" && exit 1) \ diff --git a/dockerhub/distroless/Dockerfile b/dockerhub/distroless/Dockerfile index 6f8df44f0d5e..8cc80fe4a1f0 100644 --- a/dockerhub/distroless/Dockerfile +++ b/dockerhub/distroless/Dockerfile @@ -54,6 +54,7 @@ RUN apt-get update -qq \ -fsSLO \ --compressed \ --retry 5 \ + --retry-all-errors \ && gpg --batch --assert-signer F3DCC08A8572C0749B3E18888EAB4D40A7B22B59 \ --verify --output SHASUMS256.verified.txt SHASUMS256.txt.asc \ || (echo "error: failed to verify: $tag" && exit 1) \ diff --git a/docs/format/index.mdx b/docs/format/index.mdx index 3ca3ba0119bb..a135586fcf12 100644 --- a/docs/format/index.mdx +++ b/docs/format/index.mdx @@ -95,6 +95,8 @@ options = { printWidth = 120 } ## Ignore files +Every `.gitignore` in the repository counts, whichever directory you run `bun fmt` from. Outside a repository, those in the current directory and below it count. With a Prettier config, only the `.gitignore` in the current directory does, because that's the only one Prettier reads. + To skip more than `.gitignore` does, list the files in `bunfig.toml`. A `.prettierignore` file works too. ```toml bunfig.toml icon="settings" @@ -146,6 +148,7 @@ import { a, b, c } from "./util"; - Each group is sorted by path, and the names in `{ }` are sorted too. - Two imports from the same module become one. - Side-effect imports like `import "./setup"` never move, and nothing moves past one. +- A comment directly above an import moves with it. Above the first import, comments about the whole file stay at the top: `// @ts-nocheck`, `/// `, `/* eslint-disable */`, `// @flow`, `/** @jsxImportSource ... */`, a license. To pick your own groups, use a table. See [`format.sortImports`](/runtime/bunfig#format-sortimports). @@ -281,7 +284,9 @@ bun run generate-types | bun fmt --parser typescript > types.ts bun fmt --staged ``` -A file with both staged and unstaged changes isn't written, because staging it again would commit the rest. Bun names the file and exits with code `2`. +If a file has both staged and unstaged changes, Bun looks at the staged version, which is what the commit gets. It doesn't write such a file, because staging it again would commit the rest. If the staged version needs formatting, Bun names the file and exits with code `2`. + +Config files, such as `bunfig.toml` and `.prettierrc`, are read from disk. `--changed` formats the files that differ from your default branch. Pass a ref to compare with something else. @@ -303,7 +308,7 @@ Already have a `.prettierrc` or an `.oxfmtrc.json`? `bun fmt` reads it and print } ``` -If `package.json` has a `fmt` script, `bun fmt` runs that script. Inside the script, `bun fmt` is the formatter. +If `package.json` has a `fmt` script, `bun fmt` runs that script. Inside the script, `bun fmt` is the formatter. If `package.json` has `"fmt"` in it but can't be parsed, as in the middle of a merge, `bun fmt` can't tell whether that is a script: it formats nothing and exits with code 2. Writing a tool that calls Bun in projects you don't control? Pass `--no-script`: `bun fmt --no-script` is always the formatter. diff --git a/docs/guides/format/migrate-from-prettier.mdx b/docs/guides/format/migrate-from-prettier.mdx index 00c74097e513..98513ad23446 100644 --- a/docs/guides/format/migrate-from-prettier.mdx +++ b/docs/guides/format/migrate-from-prettier.mdx @@ -86,7 +86,7 @@ Keep `prettier` if your editor's Prettier extension uses it. Bun reads everything Prettier reads: - `.prettierrc` in JSON, YAML, TOML, JavaScript, or TypeScript, `prettier.config.*`, and `"prettier"` in `package.json`, with `overrides` -- `.editorconfig`, `.prettierignore`, and `.gitignore` +- `.editorconfig`, and the `.prettierignore` and `.gitignore` in the current directory - `// prettier-ignore` comments and the `@format` and `@noformat` pragmas - Every flag of Prettier 3 except `--file-info` and `--support-info` diff --git a/docs/lint/index.mdx b/docs/lint/index.mdx index 3c355e037522..37c3b694a1be 100644 --- a/docs/lint/index.mdx +++ b/docs/lint/index.mdx @@ -5,6 +5,10 @@ description: "Bun's fast, built-in linter for JavaScript, TypeScript, and JSX" import Lint from "/snippets/cli/lint.mdx"; + + `bun lint` is only in [canary builds](/installation#canary-builds) of Bun. Run `bun upgrade --canary` to get one. + + Bun ships with a fast, built-in linter. There's nothing to install and nothing to configure. - 1,000+ rules from ESLint, typescript-eslint, React, import, unicorn, jsx-a11y, Jest, Vitest, and more @@ -46,6 +50,12 @@ To lint specific files, pass paths or globs. bun lint src "test/**/*.test.ts" ``` +An argument that starts with `!` leaves files out of what the other arguments select, as it does for `bun fmt`. This holds with an ESLint or oxlint config too. + +```bash terminal icon="terminal" +bun lint src "!src/generated" "!**/*.test.ts" +``` + The exit code is `1` if there are errors and `0` if there are only warnings. ## Fix problems @@ -56,6 +66,8 @@ Many rules can fix what they report. `--fix` applies those fixes and writes the bun lint --fix ``` +`--fix` is for changes that keep what your program does and keep your comments. Where a rule's fix is known to alter behavior or drop a comment, the problem is still reported, but only `--fix-suggestions` or `--fix-dangerously` applies the fix, even if ESLint or oxlint apply it with `--fix`. Each rule's page says which flag it needs. + ## Default rules With no config, `bun lint` turns on the rules that catch real bugs: @@ -85,7 +97,7 @@ Each rule's page says what differs and how to change it. ## Configure rules -Rules live in `bunfig.toml`. Every built-in rule works the same way, with nothing to install. +Rules live in `bunfig.toml`. Every built-in rule works the same way, with nothing to install. The exceptions are the rules for [JSON and Markdown](/lint/plugins#other-languages), which need an ESLint config. ```toml bunfig.toml icon="settings" [lint.rules] @@ -162,6 +174,27 @@ Use `*` as the rule name to turn off every rule of a plugin. A setting for a sin ignorePatterns = ["vendor/", "**/*.gen.ts"] ``` +The patterns use `.gitignore` syntax and are relative to `bunfig.toml`. With an `eslint.config.*` file they're [ESLint `ignores`](/runtime/bunfig#lint-ignorepatterns) instead. + +## ES modules and CommonJS + +`bun lint` works out whether a file is an ES module or CommonJS from the file itself, the way Node.js does: + +- `.mjs` and `.mts` files are modules. `.cjs` and `.cts` files are CommonJS. +- Any other file is a module if the nearest `package.json` has `"type": "module"`. +- Otherwise, a file with an `import`, an `export`, `import.meta` or a top-level `await` is a module. A file with none of them is CommonJS. + +A CommonJS file can `return` at the top level, and it's only in strict mode if it starts with `"use strict"`. + +To decide for every file yourself, set `sourceType` to `"module"`, `"commonjs"` or `"script"`: + +```toml bunfig.toml icon="settings" +[lint.parserOptions] +sourceType = "commonjs" +``` + +Next to an `eslint.config.js`, ESLint's defaults apply instead: `.js` and `.mjs` files are modules and `.cjs` files are CommonJS, unless `languageOptions.sourceType` says otherwise. + ## Disable a rule in code `bun lint` uses ESLint's comments, so existing ones keep working. oxlint's `oxlint-disable` comments mean the same, except next to an ESLint config, where they are ordinary comments as in ESLint. @@ -235,6 +268,10 @@ With an oxlint config, `--tsconfig` does what it does in oxlint. It sets the `ts bun lint --staged --fix ``` +If a file has both staged and unstaged changes, Bun lints the staged version, which is what the commit gets. `--fix` doesn't write such a file, because staging it again would commit the rest. If it has something to fix, Bun names the file and exits with code `2`. + +The same goes for the files that a staged file imports, which the type-aware rules and the `import` rules read. A file you staged and then deleted is still linted. Config files, such as `bunfig.toml` and `eslint.config.js`, are read from disk. + `--changed` lints the files that differ from your default branch. Pass a ref to compare with something else. ```bash terminal icon="terminal" @@ -268,7 +305,7 @@ Already have an `eslint.config.js`, `.eslintrc`, or `.oxlintrc.json`? `bun lint` } ``` -If `package.json` has a `lint` script, `bun lint` runs that script. Inside the script, `bun lint` is the linter. +If `package.json` has a `lint` script, `bun lint` runs that script. Inside the script, `bun lint` is the linter. If `package.json` has `"lint"` in it but can't be parsed, as in the middle of a merge, `bun lint` can't tell whether that is a script: it lints nothing and exits with code 2. Writing a tool that calls Bun in projects you don't control? Pass `--no-script`: `bun lint --no-script` is always the linter. diff --git a/docs/lint/rules/bun-test/consistent-test-it.mdx b/docs/lint/rules/bun-test/consistent-test-it.mdx index f56b78e9c41e..5cea44b62e76 100644 --- a/docs/lint/rules/bun-test/consistent-test-it.mdx +++ b/docs/lint/rules/bun-test/consistent-test-it.mdx @@ -16,7 +16,7 @@ deprecated: false By default, a test at the top level of a file uses `test`, and a test inside a `describe` uses `it`. -`--fix` renames the call if the file already imports the other name. +`--fix` renames the call if the file imports the other name from `bun:test`, and no variable around the call has that name. {/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */} diff --git a/docs/lint/rules/bun-test/no-unneeded-async-expect-function.mdx b/docs/lint/rules/bun-test/no-unneeded-async-expect-function.mdx index 26a1e7a20c70..9fa73e4838c5 100644 --- a/docs/lint/rules/bun-test/no-unneeded-async-expect-function.mdx +++ b/docs/lint/rules/bun-test/no-unneeded-async-expect-function.mdx @@ -12,9 +12,9 @@ typeAware: false deprecated: false --- -`.rejects` and `.resolves` work on a promise, so you can pass the call itself to `expect`. An async function that only awaits the call rejects with the same error, so the wrapper is extra code. +`.rejects` and `.resolves` work on a promise. `bun test` doesn't call a function for them, so an async function in `expect` fails with `Expected promise`. Pass the call itself. -`--fix` replaces the function with the call. +`--fix` replaces the function with the call. It leaves a function that has a comment in it alone, because the comment would be lost. {/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */} @@ -57,20 +57,17 @@ test("rejects an empty name", async () => { }); ``` -A function that does more than await one call isn't reported: +Without `.rejects` or `.resolves` the function is needed, so it isn't reported. `toThrow` calls it and waits for its promise. Given the promise itself, it fails with `Expected value must be a function`: {/* good */} ```ts import { expect, test } from "bun:test"; -test("rejects a second save", async () => { - await expect(async () => { - await saveUser({ name: "Ada" }); - await saveUser({ name: "Ada" }); - }).rejects.toThrow("name is taken"); +test("rejects an empty name", () => { + expect(async () => { + await saveUser({ name: "" }); + }).toThrow("name is required"); }); ``` -## When not to use it - -The two forms differ if the call can throw before it returns a promise. The async function turns that error into a rejection. Without the function, the error is thrown before `expect` runs. +That form also catches an error that the call throws before it returns a promise. Without the function, such an error is thrown before `expect` runs. diff --git a/docs/lint/rules/bun-test/prefer-todo.mdx b/docs/lint/rules/bun-test/prefer-todo.mdx index db7710632273..4c775974bd09 100644 --- a/docs/lint/rules/bun-test/prefer-todo.mdx +++ b/docs/lint/rules/bun-test/prefer-todo.mdx @@ -16,7 +16,7 @@ A test with an empty body passes, so the summary counts a test you haven't writt A test with only a title is reported too, and so is an empty `test.skip`. -`--fix` rewrites the call to `test.todo` and removes the empty function. A test with options, such as `{ timeout: 500 }`, is reported but not fixed. +`--fix` rewrites the call to `test.todo` and removes the empty function. It leaves a call with a comment in the function alone, because the comment would be lost. A test with options, such as `{ timeout: 500 }`, is reported but not fixed. {/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */} diff --git a/docs/lint/rules/eslint/no-extra-boolean-cast.mdx b/docs/lint/rules/eslint/no-extra-boolean-cast.mdx index bf4c4fadd17c..41b2fabcd006 100644 --- a/docs/lint/rules/eslint/no-extra-boolean-cast.mdx +++ b/docs/lint/rules/eslint/no-extra-boolean-cast.mdx @@ -14,7 +14,7 @@ deprecated: false The test of an `if`, a loop or a `? :`, the operand of `!`, and the argument of `Boolean()` are already converted to a boolean. Writing `!!value` or `Boolean(value)` there converts twice and gives the same result. -`--fix` removes the cast. +`--fix` removes the cast. In a TypeScript file, it leaves the test of an `if` or a `? :` alone if the file shows that the value is a function, a promise or an enum member. TypeScript rejects `if (callback)` when `callback` is always defined, and `if (!!callback)` is how people tell it they mean it. `--fix-dangerously` removes those casts too. This rule is on by default. diff --git a/docs/lint/rules/eslint/no-implicit-coercion.mdx b/docs/lint/rules/eslint/no-implicit-coercion.mdx index d739d6da3235..41c846fd7532 100644 --- a/docs/lint/rules/eslint/no-implicit-coercion.mdx +++ b/docs/lint/rules/eslint/no-implicit-coercion.mdx @@ -14,7 +14,7 @@ deprecated: false `!!value`, `+value` and `"" + value` convert a value as a side effect of an operator. You have to know the trick to see that a conversion happens. `Boolean(value)`, `Number(value)` and `String(value)` say it by name. -`--fix` rewrites `!!value` to `Boolean(value)`. For the conversions to a number or a string, the rewrite is offered as a suggestion. +`--fix` rewrites `!!value` to `Boolean(value)`. For the conversions to a number or a string, the rewrite is offered as a suggestion. Neither is offered where a comment would be lost, as in `!!(value /* or null */)`. {/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */} diff --git a/docs/lint/rules/eslint/no-implicit-globals.mdx b/docs/lint/rules/eslint/no-implicit-globals.mdx index fcc551d85476..812dedc71b77 100644 --- a/docs/lint/rules/eslint/no-implicit-globals.mdx +++ b/docs/lint/rules/eslint/no-implicit-globals.mdx @@ -14,7 +14,7 @@ deprecated: false In a classic script (one loaded with `b` renders as "a b". If the content before + /// and after it is inline and there's no whitespace in between, this marks all of it as whitespace-sensitive so + /// that none is added. `first` is the first sibling. The siblings must already have the sensitivity flags that + /// Prettier computes. + fn keep_inline_content_joined_across_hidden_blocks(&mut self, first: Id) { + let can_be_space_sensitive = |node: &Node<'_>| { + !matches!(node.kind, Kind::FrontMatter | Kind::AngularControlFlowBlock) + }; + let mut next = Some(first); + while let Some(start) = next { + next = self.tree.next(start); + if !self.is_hidden_block(start) { + continue; + } + let mut end = start; + while let Some(following) = self.tree.next(end).filter(|&it| { + self.is_hidden_block(it) && !self.tree[it].has(Flags::HAS_LEADING_SPACES) + }) { + end = following; + } + next = self.tree.next(end); + let (before, after) = (self.tree.prev(start), next); + let leading = Flags::IS_LEADING_SPACE_SENSITIVE | Flags::HAS_LEADING_SPACES; + let trailing = Flags::IS_TRAILING_SPACE_SENSITIVE | Flags::HAS_TRAILING_SPACES; + if self.tree[start].flags & leading != Flags::IS_LEADING_SPACE_SENSITIVE + || self.tree[end].flags & trailing != Flags::IS_TRAILING_SPACE_SENSITIVE + || !before.is_none_or(|it| can_be_space_sensitive(&self.tree[it])) + || !after.is_none_or(|it| can_be_space_sensitive(&self.tree[it])) + { + continue; + } + if let Some(before) = before { + self.tree[before] + .flags + .insert(Flags::IS_TRAILING_SPACE_SENSITIVE); + } + if let Some(after) = after { + self.tree[after] + .flags + .insert(Flags::IS_LEADING_SPACE_SENSITIVE); + } + let mut hidden = Some(start); + while let Some(id) = hidden { + self.tree[id] + .flags + .insert(Flags::IS_LEADING_SPACE_SENSITIVE | Flags::IS_TRAILING_SPACE_SENSITIVE); + hidden = self.tree.next(id).filter(|_| id != end); + } + } + } + fn is_simple_element(&self, id: Id) -> bool { let node = &self.tree[id]; node.kind == Kind::Element diff --git a/src/format/html/printer.rs b/src/format/html/printer.rs index c508a218b820..265d026880db 100644 --- a/src/format/html/printer.rs +++ b/src/format/html/printer.rs @@ -18,20 +18,20 @@ pub(crate) struct Printer<'t, 'a, 'o, 'w, 'f> { pub(crate) tree: &'t Tree<'a>, pub(crate) options: &'o Options<'o>, pub(crate) out: Writer<'w, 'f>, - /// How many nodes are around the one that is being printed. + /// The number of ancestors of the node being printed. pub(crate) ancestors: usize, pub(crate) stack_check: bun_core::StackCheck, pub(crate) is_nested_too_deeply: bool, - /// `isVueSfcWithTypescriptScript`, once it has been asked. + /// Cached `isVueSfcWithTypescriptScript`. pub(crate) has_typescript_script: Option, - /// oxfmt's `hasTsxScriptBlock`, once it has been asked. + /// Cached `hasTsxScriptBlock` from oxfmt. pub(crate) has_tsx_script: Option, pub(crate) cursor: Cursor, - /// For the style sheets. + /// Reused for formatting style sheets. pub(crate) css_scratch: crate::css::Scratch, } -/// What `printBetweenLine` returns. +/// The return value of `printBetweenLine`. #[derive(Copy, Clone, PartialEq, Eq)] enum BetweenLine { Nothing, @@ -113,7 +113,7 @@ impl<'t, 'a, 'o> Printer<'t, 'a, 'o, '_, '_> { ) } - /// `ends_with_line_break`: `stripTrailingHardline` is not called for the document. + /// `ends_with_line_break` is false if `stripTrailingHardline` is called on the document. pub(crate) fn print_root(&mut self, ends_with_line_break: bool) { let root = self.tree.root; self.out.start_group(); @@ -124,7 +124,7 @@ impl<'t, 'a, 'o> Printer<'t, 'a, 'o, '_, '_> { } } - /// Calls `print`, which prints `target`, and notes where the part of the text that the cursor is in starts and ends. + /// Calls `print`, which prints `target`, and marks where the part of the text around the cursor starts and ends. pub(crate) fn with_cursor_marks(&mut self, target: Target, print: impl FnOnce(&mut Self)) { let (starts_before, starts_after, ends_before, ends_after) = match self.cursor { Cursor::Nowhere => return print(self), @@ -148,7 +148,8 @@ impl<'t, 'a, 'o> Printer<'t, 'a, 'o, '_, '_> { } } - /// What Prettier's `mainPrint` comes to: what `embed` has made of the node, or else what `genericPrint` makes. + /// The effect of Prettier's `mainPrint`: uses `embed`'s output for the node if there is one, and `genericPrint` + /// otherwise. pub(crate) fn print_node(&mut self, id: Id) { self.with_cursor_marks(Target::Node(id), |printer| { printer.print_node_without_marks(id) @@ -228,7 +229,7 @@ impl<'t, 'a, 'o> Printer<'t, 'a, 'o, '_, '_> { self.out.text(node.span.of(self.options.original_text)); self.out.built_text(|out| tags.closing_tag_suffix(id, out)); } - // It has become a text. + // It has been merged into a text. Kind::Cdata => {} } } @@ -247,7 +248,7 @@ impl<'t, 'a, 'o> Printer<'t, 'a, 'o, '_, '_> { return; }; if parent.kind == Kind::Interpolation { - // The line break at the end is not a literal one: `/\n[^\S\n]*$/` + // The line break at the end isn't a literal one: `/\n[^\S\n]*$/` let text_len = strings::trim_js_whitespace_end(value).len(); return match strings::last_index_of_char(&value[text_len..], b'\n') { Some(at) => { @@ -258,7 +259,7 @@ impl<'t, 'a, 'o> Printer<'t, 'a, 'o, '_, '_> { }; } if parent.has(Flags::IS_WHITESPACE_SENSITIVE) { - // All that is between the parts of the `fill` is forced line breaks, so it is as good as an array. + // All separators in the `fill` are forced line breaks, so a plain array prints the same. self.out.built_text(|out| tags.opening_tag_prefix(id, out)); match parent.has(Flags::IS_INDENTATION_SENSITIVE) { true => self.out.text(value), @@ -275,8 +276,8 @@ impl<'t, 'a, 'o> Printer<'t, 'a, 'o, '_, '_> { } return self.out.built_text(|out| tags.closing_tag_suffix(id, out)); } - // The first and the last part of the `fill` have what is borrowed. One part is no `fill`: `cleanDoc` makes it so in - // a template of JavaScript, where the part can be more than a string. + // The first and last parts of the `fill` include the borrowed markers. A single part isn't a `fill`: `cleanDoc` + // unwraps it in a JavaScript template, where the part can be more than a string. let is_fill = html_split(value).nth(1).is_some(); if is_fill { self.out.start_fill(); @@ -330,11 +331,9 @@ impl<'t, 'a, 'o> Printer<'t, 'a, 'o, '_, '_> { start += tags.len_of(|tags, out| tags.opening_tag_start_marker(child, out)); } let mut end = self.end_location(child) as usize; - if self - .tree - .next(child) - .is_some_and(|next| tags.needs_to_borrow_prev_closing_tag_end_marker(next)) - { + // Prettier only checks whether the next sibling borrows the marker. The parent borrows it from its last child, + // so Prettier prints it twice: `>`. + if tags.lends_closing_tag_end_marker(child) { end = end .saturating_sub(tags.len_of(|tags, out| tags.closing_tag_end_marker(child, out))); } @@ -433,9 +432,9 @@ impl<'t, 'a, 'o> Printer<'t, 'a, 'o, '_, '_> { } return; } - // What is between a child and the one before it, if the one before it has asked. + // The line between a child and its previous sibling, if it was already computed for that sibling. let mut known_line = None; - // The id of the group of the child before, if this one asks about it. + // The group id of the previous child, if this child needs it. let mut prev_group_id = None; for child in tree.children(parent) { let prev = tree.prev(child); @@ -464,7 +463,7 @@ impl<'t, 'a, 'o> Printer<'t, 'a, 'o, '_, '_> { next.map_or(BetweenLine::Nothing, |next| self.between_line(child, next)); known_line = Some(next_line); - // What comes before the groups, and what is at the start of the outer one. + // Write what comes before the groups, and remember what goes at the start of the outer group. let mut leading_line = None; if let Some(prev) = prev.filter(|_| prev_line != BetweenLine::Nothing) { if tree.force_next_empty_line(prev, options) { @@ -491,7 +490,7 @@ impl<'t, 'a, 'o> Printer<'t, 'a, 'o, '_, '_> { let is_trailing_line = next_line != BetweenLine::Nothing && !forces_next_empty_line && next_line != BetweenLine::Hardline; - // Only an element behind it asks whether the group is broken. + // Only an element after it checks whether the group is broken. prev_group_id = match next { Some(next) if is_trailing_line && !is_text_like(&tree[next]) => { Some(self.out.new_group_id()) @@ -522,15 +521,18 @@ impl<'t, 'a, 'o> Printer<'t, 'a, 'o, '_, '_> { let (tags, tree, options) = (self.tags(), self.tree, self.options); let node = &tree[id]; if node.has(Flags::PRESERVES_CONTENT) { - self.out.built_text(|out| tags.opening_tag_prefix(id, out)); + // The tags already include the markers they borrow. Prettier prints those markers again around them: + // `a>
` with strict whitespace sensitivity, and
+            // `>`.
             self.out.start_group();
             self.print_opening_tag(id);
             self.out.end_group();
             self.out.text(tags.node_content(id));
-            if !tags.is_written_to_its_end(id) {
-                self.out.built_text(|out| tags.closing_tag(id, out));
-            }
-            self.out.built_text(|out| tags.closing_tag_suffix(id, out));
+            self.out
+                .built_text(|out| match tags.is_verbatim_without_end_tag(id) {
+                    true => tags.closing_tag_suffix(id, out),
+                    false => tags.closing_tag(id, out),
+                });
             return;
         }
         let (Some(first), Some(last)) = (tree.first_child(id), tree.last_child(id)) else {
@@ -685,7 +687,7 @@ impl<'t, 'a, 'o> Printer<'t, 'a, 'o, '_, '_> {
         } else {
             self.out.line();
         }
-        // In the order they are written in.
+        // In source order.
         let (mut attributes, mut comments) =
             (attributes.iter().peekable(), comments.iter().peekable());
         let mut is_first = true;
diff --git a/src/format/html/tag.rs b/src/format/html/tag.rs
index 0ed10dc15494..dad2e6eb50d9 100644
--- a/src/format/html/tag.rs
+++ b/src/format/html/tag.rs
@@ -1,7 +1,7 @@
-//! Prettier's `language-html/print/tag.js`, as far as it makes strings, and `get-node-content.js`.
+//! The parts of Prettier's `language-html/print/tag.js` that build strings, and `get-node-content.js`.
 //!
-//! Where white space counts, a line can only be broken inside of a tag. So a node may have to write the end of the
-//! tag before it, or the start of the one behind it: it borrows them.
+//! Where whitespace is significant, a line can only be broken inside a tag. So a node may have to print the end of the
+//! tag before it or the start of the tag after it. Prettier calls that borrowing.
 
 use super::Options;
 use super::ast::{Flags, Id, Kind, Tree};
@@ -9,7 +9,7 @@ use super::utilities::{is_pre_like, is_text_like};
 
 const HTML5_DOCTYPE_START_MARKER: &[u8] = b" {
     pub(crate) tree: &'t Tree<'a>,
@@ -44,8 +44,8 @@ impl<'o> Tags<'_, '_, 'o> {
         self.closing_tag_start_marker(id, out);
     }
 
-    /// Whether what follows the node writes the end of its closing tag.
-    fn lends_closing_tag_end_marker(self, id: Id) -> bool {
+    /// True if what follows the node prints the end of the node's closing tag.
+    pub(crate) fn lends_closing_tag_end_marker(self, id: Id) -> bool {
         match (self.tree.next(id), self.tree.parent(id)) {
             (Some(next), _) => self.needs_to_borrow_prev_closing_tag_end_marker(next),
             (None, Some(parent)) => self.needs_to_borrow_last_child_closing_tag_end_marker(parent),
@@ -108,14 +108,27 @@ impl<'o> Tags<'_, '_, 'o> {
             Kind::IeConditionalStartComment => b"]>",
             Kind::Interpolation => b"}}",
             Kind::AngularIcuExpression => b"}",
-            Kind::Element if node.has(Flags::IS_SELF_CLOSING) => b"/>",
+            Kind::Element
+                if node.has(Flags::IS_SELF_CLOSING) && !self.is_verbatim_void_without_slash(id) =>
+            {
+                b"/>"
+            }
             _ => b">",
         });
     }
 
-    /// Whether what is in `id` is written as it is, and `id` has no end tag that says where that ends. Prettier takes it to
-    /// be empty: `
a` becomes `
>`. Here it is written to its end, and gets no end tag.
-    pub(crate) fn is_written_to_its_end(self, id: Id) -> bool {
+    /// True if `id` is a void element written without a slash, like `
`, and is printed verbatim. The marker it + /// lends is then `>`. Prettier assumes `/>`, so `c` becomes `c`. + fn is_verbatim_void_without_slash(self, id: Id) -> bool { + let end = self.tree[id].span.end as usize; + self.tree.has_prettier_ignore(id) + && (self.options.original_text.get(..end)).is_some_and(|text| !text.ends_with(b"/>")) + } + + /// True if the contents of `id` are printed verbatim and `id` has no end tag to mark where they end. Prettier + /// treats the contents as empty: `
a` becomes `
>`. Here they're printed through the end of the last
+    /// descendant, without adding an end tag.
+    pub(crate) fn is_verbatim_without_end_tag(self, id: Id) -> bool {
         let node = &self.tree[id];
         node.has(Flags::PRESERVES_CONTENT)
             && !(node.flags).intersects(Flags::IS_SELF_CLOSING | Flags::HAS_END_SPAN)
@@ -127,7 +140,7 @@ impl<'o> Tags<'_, '_, 'o> {
             .flags
             .intersects(Flags::IS_SELF_CLOSING | Flags::HAS_END_SPAN)
             && (self.tree.has_prettier_ignore(id)
-                || self.is_written_to_its_end(id)
+                || self.is_verbatim_without_end_tag(id)
                 || self
                     .tree
                     .parent_of(id)
@@ -247,7 +260,7 @@ impl<'o> Tags<'_, '_, 'o> {
             Kind::IeConditionalEndComment => out.extend_from_slice(b"` is printed as it is in the text.
+        // The node after `` is printed verbatim.
         let mut is_ignored = false;
         for child in tree.children(id) {
             let node = &tree[child];
diff --git a/src/format/html/utilities.rs b/src/format/html/utilities.rs
index 13af6c059782..d57ac8f24abe 100644
--- a/src/format/html/utilities.rs
+++ b/src/format/html/utilities.rs
@@ -9,7 +9,7 @@ use std::borrow::Cow;
 
 // ───────────────────────────── `htmlWhitespace` ─────────────────────────────
 
-/// `htmlWhitespace.split(text)`: with an empty string where the text starts or ends with white space.
+/// `htmlWhitespace.split(text)`. Yields an empty string where the text starts or ends with whitespace.
 pub(crate) fn html_split(text: &[u8]) -> impl Iterator {
     let mut rest = Some(text);
     std::iter::from_fn(move || {
@@ -24,7 +24,8 @@ pub(crate) fn html_split(text: &[u8]) -> impl Iterator {
     })
 }
 
-/// `htmlWhitespace.dedentString(text)`: by how much every line is to be shortened at its start.
+/// The first half of `htmlWhitespace.dedentString(text)`: returns how many bytes to remove from the start of every
+/// line.
 pub(crate) fn min_indentation(text: &[u8]) -> usize {
     let mut min_indentation = usize::MAX;
     for line in strings::split(text, b"\n") {
@@ -64,14 +65,14 @@ pub(crate) fn dedent_string(text: &[u8]) -> Cow<'_, [u8]> {
 
 /// `htmlTrimPreserveIndentation`
 pub(crate) fn html_trim_preserve_indentation(text: &[u8]) -> &[u8] {
-    // `.replaceAll(/^[\t\f\r ]*\n/g, "")`: without the `m` flag, it is one line at most.
+    // `.replaceAll(/^[\t\f\r ]*\n/g, "")`: without the `m` flag, it removes one line at most.
     let text = text.trim_ascii_end();
-    let blanks = text
+    let whitespace_len = text
         .iter()
         .take_while(|byte| matches!(byte, b'\t' | 0x0C | b'\r' | b' '))
         .count();
-    match text.get(blanks) {
-        Some(b'\n') => &text[blanks + 1..],
+    match text.get(whitespace_len) {
+        Some(b'\n') => &text[whitespace_len + 1..],
         _ => text,
     }
 }
@@ -182,7 +183,7 @@ fn is_text_or_interpolation(node: &Node<'_>) -> bool {
     matches!(node.kind, Kind::Text | Kind::Interpolation)
 }
 
-/// By how many lines the start of `second` is below the end of `first`, up to two.
+/// Returns how many lines the start of `second` is below the end of `first`, capped at two.
 fn lines_between(options: &Options<'_>, first: Span, second: Span) -> usize {
     let Some(between) = options
         .original_text
@@ -249,11 +250,11 @@ impl<'a> Tree<'a> {
         self.is_vue_sfc_block(id, options) && &self[id].name[..] == b"script"
     }
 
-    /// `shouldPreserveContent`, once nothing in `id` changes any more. It looks at all children.
+    /// `shouldPreserveContent`. Call it once nothing in `id` changes anymore. It looks at all children.
     pub(crate) fn should_preserve_content(&self, id: Id, options: &Options<'_>) -> bool {
         let node = &self[id];
         if node.kind == Kind::IeConditionalComment {
-            // An element that is not closed in the comment, or something that cannot be parsed.
+            // An element that isn't closed inside the comment, or contents that couldn't be parsed.
             if self.node_at(self.last_child(id)).is_some_and(|last| {
                 !last.has(Flags::IS_SELF_CLOSING) && !last.has(Flags::HAS_END_SPAN)
             }) {
@@ -270,6 +271,11 @@ impl<'a> Tree<'a> {
         {
             return true;
         }
+        // Whitespace-only content of a `
` is rendered, and in a `\n", "\n"],
+    ["\n", "\n"],
+    ["
 
\n", "
\n"],
+    ["
\n\n
\n", "
\n"],
+    ["
  
\n", "
\n"], + ])("keeps whitespace that's the whole content of a
 or \n", null],
+      ["
a
\n", null], + ["a\n", null], + ["ac\n", null], + ['a\n', 'a\n'], + ["
\n", "
\n"], + ["
\n", "
\n"], + ["\n", "\n"], + [ + `${long}${long}\n`, + `${long}a\n", null], + ["x\n", null], + ["\n", null], + ["\n", null], + ["x\n", null], + ["\n", " \n"], + ["a \n", null], + ["a\n", null], + ["a\n", null], + ])("a b\n", null, "ab\n"], + [ + [], + "ab\n", + "ab\n", + ], + [[], "a
 
\n", "a\n
 
\n", "a\n
\n"],
+      [strict, "a
  
c\n", null, "a
 
c\n"], + ])("more whitespace than one space: %j %j", async (flags, before, changed, byPrettier) => { + const after = changed ?? before; + expect(after).not.toBe(byPrettier); + expect(await read(after)).toEqual(await read(before)); + const result = await formatChecked({ "a.html": before, "b.html": after }, flags, { reads: ["a.html", "b.html"] }); + expect(result.files).toEqual({ "a.html": after, "b.html": after }); + expect(result.exitCode).toBe(0); + }); + + // Each row is the flags, the text, Bun's output (`null` if unchanged) and Prettier 3.9.9's output. Prettier writes + // the end of a tag twice, which makes it text the second time, or takes `/>` from a tag that ends in `>`. + test.each([ + [ + strict, + "a
x
c\n", + "a
xc\n",
+        "a>
xc\n",
+      ],
+      [strict, "a
x\n", "a
x\n", "a>
>\n"],
+      [
+        [],
+        "\n",
+        "\n",
+        ">\n",
+      ],
+      [
+        [],
+        "ac\n",
+        "ac\n",
+        "a>c\n",
+      ],
+      [[], "\n", null, ">\n"],
+      [
+        [],
+        "\n",
+        "\n",
+        "\n>\n",
+      ],
+      [
+        [],
+        '\n',
+        '\n',
+        '/>\n',
+      ],
+      [[], "\n", null, "/>\n"],
+      [[], "c\n", null, "c\n"],
+      [
+        [],
+        "\n

\n", + "\n

\n", + "\n
\n", + ], + [ + [], + "

\n \n x\n

\n", + null, + "

\n \n x\n

\n", + ], + ])("writes the end of a tag only once: %j %j", async (flags, before, changed, byPrettier) => { + const after = changed ?? before; + expect(await read(after)).toEqual(await read(before)); + expect(await read(byPrettier)).not.toEqual(await read(before)); + const result = await formatChecked({ "a.html": before, "b.html": after }, flags, { reads: ["a.html", "b.html"] }); + expect(result.files).toEqual({ "a.html": after, "b.html": after }); + expect(result.exitCode).toBe(0); + }); + }); + + describe("Vue", () => { + const inTemplate = (html: string) => `\n`; + + // Vue doesn't compile any of it: `{{name}}` is rendered as text, and `:b` is an ordinary attribute. Each row is the + // HTML, which stays unchanged, and Prettier 3.9.9's output. + test.each([ + ["{{name}}", "{{ name }}"], + ["

Use {{msg}} and {{a+b}} here

", "

Use {{ msg }} and {{ a + b }} here

"], + ['
t
', '
t
'], + ['t', 't'], + ])("doesn't format an element with v-pre or its content as code: %j", async (html, byPrettier) => { + expect(html).not.toBe(byPrettier); + const files = { "a.vue": inTemplate(html), "b.vue": inTemplate(html.replace(" v-pre", "")) }; + const result = await formatChecked(files, [], { reads: ["a.vue", "b.vue"] }); + expect(result.files).toEqual({ "a.vue": files["a.vue"], "b.vue": inTemplate(byPrettier.replace(" v-pre", "")) }); + expect(result.exitCode).toBe(0); + }); + + // Prettier 3.9.9 prints the same. + test.each([ + "
a
", + "

", + "
a
", + "
{{ a }}
", + "", + "
a
", + ])("a

+
a
+

a

+

ac

+

a

+
+


+

diff --git a/test/cli/format/own/cases/html/textarea-with-a-blank-behind-an-element.html.prettier.snap b/test/cli/format/own/cases/html/textarea-with-a-blank-behind-an-element.html.prettier.snap new file mode 100644 index 000000000000..f2775dce4744 --- /dev/null +++ b/test/cli/format/own/cases/html/textarea-with-a-blank-behind-an-element.html.prettier.snap @@ -0,0 +1,25 @@ +------------------ +{ printWidth: 80 } +------------------ +

+
a
+

a

+

ac

+

a

+
+


+

+ +------------------- +{ printWidth: 100 } +------------------- +

+
a
+

a

+

ac

+

a

+
+


+

+ +===================== End ===================== diff --git a/test/cli/format/own/cases/html/textarea-with-a-blank-behind-an-element.html.snap b/test/cli/format/own/cases/html/textarea-with-a-blank-behind-an-element.html.snap new file mode 100644 index 000000000000..f2775dce4744 --- /dev/null +++ b/test/cli/format/own/cases/html/textarea-with-a-blank-behind-an-element.html.snap @@ -0,0 +1,25 @@ +------------------ +{ printWidth: 80 } +------------------ +

+
a
+

a

+

ac

+

a

+
+


+

+ +------------------- +{ printWidth: 100 } +------------------- +

+
a
+

a

+

ac

+

a

+
+


+

+ +===================== End ===================== diff --git a/test/cli/format/own/cases/markdown/delimiters-of-remark-8.mdx.input b/test/cli/format/own/cases/markdown/delimiters-of-remark-8.mdx.input index dec0394ad75f..994617ad5392 100644 --- a/test/cli/format/own/cases/markdown/delimiters-of-remark-8.mdx.input +++ b/test/cli/format/own/cases/markdown/delimiters-of-remark-8.mdx.input @@ -1,4 +1,4 @@ -**a **b, ** c **, /* d */, e**.** f +e**.** f import * as g from "h"; import * as i from "j"; diff --git a/test/cli/format/own/cases/markdown/delimiters-of-remark-8.mdx.prettier.snap b/test/cli/format/own/cases/markdown/delimiters-of-remark-8.mdx.prettier.snap index 28cbf927e1cf..f23bedcd24f9 100644 --- a/test/cli/format/own/cases/markdown/delimiters-of-remark-8.mdx.prettier.snap +++ b/test/cli/format/own/cases/markdown/delimiters-of-remark-8.mdx.prettier.snap @@ -1,7 +1,7 @@ ------------------ { printWidth: 80 } ------------------ -**a **b, ** c **, /_ d _/, e**.** f +e**.** f import * as g from "h"; import * as i from "j"; @@ -13,7 +13,7 @@ import * as i from "j"; ------------------- { printWidth: 100 } ------------------- -**a **b, ** c **, /_ d _/, e**.** f +e**.** f import * as g from "h"; import * as i from "j"; diff --git a/test/cli/format/own/cases/markdown/delimiters-of-remark-8.mdx.snap b/test/cli/format/own/cases/markdown/delimiters-of-remark-8.mdx.snap index 28cbf927e1cf..f23bedcd24f9 100644 --- a/test/cli/format/own/cases/markdown/delimiters-of-remark-8.mdx.snap +++ b/test/cli/format/own/cases/markdown/delimiters-of-remark-8.mdx.snap @@ -1,7 +1,7 @@ ------------------ { printWidth: 80 } ------------------ -**a **b, ** c **, /_ d _/, e**.** f +e**.** f import * as g from "h"; import * as i from "j"; @@ -13,7 +13,7 @@ import * as i from "j"; ------------------- { printWidth: 100 } ------------------- -**a **b, ** c **, /_ d _/, e**.** f +e**.** f import * as g from "h"; import * as i from "j"; diff --git a/test/cli/format/own/cases/markdown/text-only-by-its-indentation.md.input b/test/cli/format/own/cases/markdown/text-only-by-its-indentation.md.input deleted file mode 100644 index aea71d8e41f4..000000000000 --- a/test/cli/format/own/cases/markdown/text-only-by-its-indentation.md.input +++ /dev/null @@ -1,22 +0,0 @@ -!!! a - b - - d - - -??? f - ``` - g { - } - -- [ ] h - - -return ( -
-

j

- -??? k - ```yaml - l - ``` diff --git a/test/cli/format/own/cases/markdown/text-only-by-its-indentation.md.prettier.snap b/test/cli/format/own/cases/markdown/text-only-by-its-indentation.md.prettier.snap deleted file mode 100644 index e713b1386ca1..000000000000 --- a/test/cli/format/own/cases/markdown/text-only-by-its-indentation.md.prettier.snap +++ /dev/null @@ -1,53 +0,0 @@ ------------------- -{ printWidth: 80 } ------------------- -!!! a -b - -d - - -??? f -``` -g { -} - -- [ ] h - - -return ( -
-

j

- -??? k -`yaml - l - ` - -------------------- -{ printWidth: 100 } -------------------- -!!! a -b - -d - - -??? f -``` -g { -} - -- [ ] h - - -return ( -
-

j

- -??? k -`yaml - l - ` - -===================== End ===================== diff --git a/test/cli/format/own/cases/markdown/text-only-by-its-indentation.md.snap b/test/cli/format/own/cases/markdown/text-only-by-its-indentation.md.snap deleted file mode 100644 index 5bfbbbbb8bb1..000000000000 --- a/test/cli/format/own/cases/markdown/text-only-by-its-indentation.md.snap +++ /dev/null @@ -1,45 +0,0 @@ ------------------- -{ printWidth: 80 } ------------------- -!!! a -b - -d - -??? f - ``` -g { -} - -- [ ] h - -return (

j

- -??? k -`yaml - l - ` - -------------------- -{ printWidth: 100 } -------------------- -!!! a -b - -d - -??? f - ``` -g { -} - -- [ ] h - -return (

j

- -??? k -`yaml - l - ` - -===================== End ===================== diff --git a/test/cli/format/own/cases/vue/textarea-with-a-blank-behind-an-element.vue.input b/test/cli/format/own/cases/vue/textarea-with-a-blank-behind-an-element.vue.input new file mode 100644 index 000000000000..26f549b2d709 --- /dev/null +++ b/test/cli/format/own/cases/vue/textarea-with-a-blank-behind-an-element.vue.input @@ -0,0 +1,6 @@ + diff --git a/test/cli/format/own/cases/vue/textarea-with-a-blank-behind-an-element.vue.prettier.snap b/test/cli/format/own/cases/vue/textarea-with-a-blank-behind-an-element.vue.prettier.snap new file mode 100644 index 000000000000..d7f57657f60a --- /dev/null +++ b/test/cli/format/own/cases/vue/textarea-with-a-blank-behind-an-element.vue.prettier.snap @@ -0,0 +1,31 @@ +------------------ +{ printWidth: 40 } +------------------ + + +------------------ +{ printWidth: 80 } +------------------ + + +------------------- +{ printWidth: 100 } +------------------- + + +===================== End ===================== diff --git a/test/cli/format/own/cases/vue/textarea-with-a-blank-behind-an-element.vue.snap b/test/cli/format/own/cases/vue/textarea-with-a-blank-behind-an-element.vue.snap new file mode 100644 index 000000000000..d7f57657f60a --- /dev/null +++ b/test/cli/format/own/cases/vue/textarea-with-a-blank-behind-an-element.vue.snap @@ -0,0 +1,31 @@ +------------------ +{ printWidth: 40 } +------------------ + + +------------------ +{ printWidth: 80 } +------------------ + + +------------------- +{ printWidth: 100 } +------------------- + + +===================== End ===================== diff --git a/test/cli/format/own/cases/yaml/comment-behind-the-indicator-of-a-block-scalar.yaml.input b/test/cli/format/own/cases/yaml/comment-behind-the-indicator-of-a-block-scalar.yaml.input index 5b1722df5c2b..6ac981ac9ebd 100644 --- a/test/cli/format/own/cases/yaml/comment-behind-the-indicator-of-a-block-scalar.yaml.input +++ b/test/cli/format/own/cases/yaml/comment-behind-the-indicator-of-a-block-scalar.yaml.input @@ -3,7 +3,7 @@ steps: if: matrix.vite run: | # copies the catalogs to the overrides in the workspace file so that the next install enforces them yq -i '.overrides = .catalogs' pnpm-workspace.yaml - pnpm install --no-frozen-lockfile + pnpm install --no-frozen-lockfile - run: > # short a - name: next diff --git a/test/cli/format/own/cases/yaml/comment-behind-the-indicator-of-a-block-scalar.yaml.snap b/test/cli/format/own/cases/yaml/comment-behind-the-indicator-of-a-block-scalar.yaml.snap index 9f14b3bce9e7..80d958e918d1 100644 --- a/test/cli/format/own/cases/yaml/comment-behind-the-indicator-of-a-block-scalar.yaml.snap +++ b/test/cli/format/own/cases/yaml/comment-behind-the-indicator-of-a-block-scalar.yaml.snap @@ -6,7 +6,7 @@ steps: if: matrix.vite run: | # copies the catalogs to the overrides in the workspace file so that the next install enforces them yq -i '.overrides = .catalogs' pnpm-workspace.yaml - pnpm install --no-frozen-lockfile + pnpm install --no-frozen-lockfile - run: > # short a - name: next @@ -19,7 +19,7 @@ steps: if: matrix.vite run: | # copies the catalogs to the overrides in the workspace file so that the next install enforces them yq -i '.overrides = .catalogs' pnpm-workspace.yaml - pnpm install --no-frozen-lockfile + pnpm install --no-frozen-lockfile - run: > # short a - name: next diff --git a/test/cli/format/own/cases/yaml/comments-behind-an-indented-root.yaml.input b/test/cli/format/own/cases/yaml/comments-behind-an-indented-root.yaml.input new file mode 100644 index 000000000000..4eb3bcc966df --- /dev/null +++ b/test/cli/format/own/cases/yaml/comments-behind-an-indented-root.yaml.input @@ -0,0 +1,19 @@ + a: 1 + # at the indentation of the key +# at the start of the line +--- + - a + # x + # y +# z +--- + a: 1 + # before an empty line + +# after it +--- + a: 1 + # in the value + # x + # after one that is not +# y diff --git a/test/cli/format/own/cases/yaml/comments-behind-an-indented-root.yaml.prettier.snap b/test/cli/format/own/cases/yaml/comments-behind-an-indented-root.yaml.prettier.snap new file mode 100644 index 000000000000..b92b1df75881 --- /dev/null +++ b/test/cli/format/own/cases/yaml/comments-behind-an-indented-root.yaml.prettier.snap @@ -0,0 +1,49 @@ +------------------ +{ printWidth: 80 } +------------------ +a: 1 +# at the indentation of the key +# at the start of the line +--- +- a +# x +# y +# z +--- +a: 1 +# before an empty line + +# after it +--- +a: + 1 + # in the value +# x +# after one that is not +# y + +------------------- +{ printWidth: 100 } +------------------- +a: 1 +# at the indentation of the key +# at the start of the line +--- +- a +# x +# y +# z +--- +a: 1 +# before an empty line + +# after it +--- +a: + 1 + # in the value +# x +# after one that is not +# y + +===================== End ===================== diff --git a/test/cli/format/own/cases/yaml/comments-behind-an-indented-root.yaml.snap b/test/cli/format/own/cases/yaml/comments-behind-an-indented-root.yaml.snap new file mode 100644 index 000000000000..b2e0906f5eed --- /dev/null +++ b/test/cli/format/own/cases/yaml/comments-behind-an-indented-root.yaml.snap @@ -0,0 +1,47 @@ +------------------ +{ printWidth: 80 } +------------------ +a: 1 +# at the indentation of the key +# at the start of the line +--- +- a +# x +# y +# z +--- +a: 1 +# before an empty line + +# after it +--- +a: 1 + # in the value +# x +# after one that is not +# y + +------------------- +{ printWidth: 100 } +------------------- +a: 1 +# at the indentation of the key +# at the start of the line +--- +- a +# x +# y +# z +--- +a: 1 +# before an empty line + +# after it +--- +a: 1 + # in the value +# x +# after one that is not +# y + +===================== End ===================== diff --git a/test/cli/format/own/comment-owners.ts b/test/cli/format/own/comment-owners.ts index 76785603b9c3..274d051e5bde 100644 --- a/test/cli/format/own/comment-owners.ts +++ b/test/cli/format/own/comment-owners.ts @@ -1,4 +1,4 @@ -// Writes `comment-owners.txt`: the node that Prettier attaches each comment in the inputs of `cases` to. +// Writes `comment-owners.txt`: the node that Prettier attaches each comment in the `cases` inputs to. // // bun test/cli/format/own/comment-owners.ts // @@ -55,7 +55,7 @@ collect(import.meta.dir, "cases", files, name => !name.endsWith(".input")); let output = ""; for (const [path, bytes] of [...files].sort(([a], [b]) => (a < b ? -1 : 1))) { const name = path.slice("cases/".length, -".input".length); - // The parser of a Flow case is in its `options.json`. + // A Flow case sets its parser in its `options.json`. if (!/\.[cm]?[jt]sx?$/.test(name) || name.startsWith("flow/")) continue; const text = Buffer.from(bytes).toString(); const byteOffset = (index: number) => Buffer.byteLength(text.slice(0, index)); diff --git a/test/cli/format/own/sync.ts b/test/cli/format/own/sync.ts index ffea350ce708..455719a960c5 100644 --- a/test/cli/format/own/sync.ts +++ b/test/cli/format/own/sync.ts @@ -1,4 +1,4 @@ -// Writes what Prettier and oxfmt print for the inputs in `cases`, next to them. +// Writes Prettier's and oxfmt's output for the inputs in `cases` next to them. // // bun test/cli/format/own/sync.ts import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; @@ -24,17 +24,17 @@ for (const [path, bytes] of files) { for (const options of rowsOf(name, files)) { const failure = (error: Error) => `<${error.name}>`; const printed = await prettier.format(Buffer.from(bytes).toString(), { ...options, filepath: name }).catch(failure); - // Prettier has no TOML: only oxfmt judges. + // Prettier doesn't support TOML, so only oxfmt's output is recorded. if (printed !== "") asPrettier.push([options, printed]); const directory = mkdtempSync(join(tmpdir(), "oxfmt-")); writeFileSync(join(directory, ".oxfmtrc.json"), JSON.stringify(options)); const { stdout, exitCode } = Bun.spawnSync([oxfmt, `--stdin-filepath=${basename(name)}`], { cwd: directory, stdin: bytes }); - // What oxfmt refuses, only Prettier judges. + // If oxfmt rejects the input, only Prettier's output is recorded. if (exitCode === 0) asOxfmt.push([options, stdout.toString()]); rmSync(directory, { recursive: true }); } writeFileSync(join(import.meta.dir, `${name}.prettier.snap`), render(asPrettier)); - // `.todo`: `bun fmt` does not print that yet, and it is not compared. + // `.todo` means `bun fmt` doesn't print that yet, so it isn't compared. const snapshot = join(import.meta.dir, `${name}.snap`); if (asOxfmt.length > 0) writeFileSync(existsSync(`${snapshot}.todo`) ? `${snapshot}.todo` : snapshot, render(asOxfmt)); } diff --git a/test/cli/format/oxfmt-cli/oxfmt-cli.test.ts b/test/cli/format/oxfmt-cli/oxfmt-cli.test.ts index 07b3ebc23619..e4e58c346444 100644 --- a/test/cli/format/oxfmt-cli/oxfmt-cli.test.ts +++ b/test/cli/format/oxfmt-cli/oxfmt-cli.test.ts @@ -1,5 +1,6 @@ -// The cases of oxfmt's own command line tests (`apps/oxfmt/test/cli/*/options.json` of oxc-project/oxc, MIT: see LICENSE), with what -// oxfmt 0.72 does in each: the exit code, the files afterwards, and the files that `--check` and `--list-different` name. +// The cases from oxfmt's own command line tests (`apps/oxfmt/test/cli/*/options.json` in oxc-project/oxc, MIT: see +// LICENSE), with oxfmt 0.72's result for each: the exit code, the files afterwards, and the files that `--check` and +// `--list-different` list. // `cases.json` is written by `test/cli/lint/oracle/driver/oxfmt-fixtures.mjs --record`. import { afterAll, describe, expect, test } from "bun:test"; import { bunEnv, bunExe, isWindows, tempDir } from "harness"; @@ -11,17 +12,19 @@ import { cases, fixtures } from "./cases.json"; afterAll(endChildren); type Files = Record; -// A fixture has `experimentalTailwindcss`, which has no effect here. That `bun fmt` says so is tested elsewhere. +// A fixture sets `experimentalTailwindcss`, which has no effect here. `bun fmt`'s message about that is tested +// elsewhere. const command = [bunExe(), "fmt", "--allow-unsupported"]; const env = { NO_COLOR: "1", AGENT: "0", CLAUDECODE: undefined }; -describe.concurrent("bun fmt does what oxfmt does", () => { +describe.concurrent("bun fmt behaves like oxfmt", () => { for (const it of cases) { const files = { ...(fixtures as Record)[it.name], ...it.gitignore } as Files; const links = Object.entries(files).filter(([, file]) => typeof file !== "string") as [string, { link: string }][]; test.skipIf(isWindows && links.length > 0)(`${it.name}/${it.index}: ${it.args.join(" ")}`, async () => { const texts = Object.entries(files).filter(([, file]) => typeof file === "string") as [string, string][]; - // Without a configuration file `bun fmt` is like Prettier. An empty one above the fixtures makes it like oxfmt. + // Without a configuration file, `bun fmt` behaves like Prettier. An empty one above the fixtures makes it behave + // like oxfmt. using dir = tempDir("oxfmt-cli", { ".oxfmtrc.json": "{}\n", ...Object.fromEntries(texts.map(([name, text]) => [`fixtures/${name}`, text])), @@ -41,15 +44,15 @@ describe.concurrent("bun fmt does what oxfmt does", () => { const after = readFileSync(join(root, name), "utf8"); return after === text ? [] : [[name, after]]; }); - const named = (stdout + stderr) + const lines = (stdout + stderr) .replace(/\x1b\[[0-9;]*m/g, "") .split("\n") .map(line => line.replace(/^\[warn\] | \(\d+ms\)$/g, "")); expect({ changed: Object.fromEntries(changed), - listed: it.listed && it.listed.filter(name => named.includes(name)), + listed: it.listed && it.listed.filter(name => lines.includes(name)), others: - it.listed && texts.map(([name]) => name).filter(name => named.includes(name) && !it.listed.includes(name)), + it.listed && texts.map(([name]) => name).filter(name => lines.includes(name) && !it.listed.includes(name)), stdout: it.stdout === undefined ? undefined : stdout, exitCode, }).toEqual({ diff --git a/test/cli/format/oxfmt/expected.txt b/test/cli/format/oxfmt/expected.txt index 7cbdbfec8cd1..23e25301e22e 100644 --- a/test/cli/format/oxfmt/expected.txt +++ b/test/cli/format/oxfmt/expected.txt @@ -2,6 +2,8 @@ FAIL oxfmt css/format/css/combinator-spacing.css { printWidth: 80 } FAIL oxfmt css/format/css/combinator-spacing.css { printWidth: 100 } FAIL oxfmt css/format/css/custom-media.css { printWidth: 80 } FAIL oxfmt css/format/css/custom-media.css { printWidth: 100 } +FAIL prettier css/format/css/custom-property-raw-verbatim.css { printWidth: 80 } +FAIL prettier css/format/css/custom-property-raw-verbatim.css { printWidth: 100 } FAIL oxfmt css/format/css/custom-property-raw-verbatim.css { printWidth: 80 } FAIL oxfmt css/format/css/custom-property-raw-verbatim.css { printWidth: 100 } FAIL oxfmt css/format/css/document-url-brace.css { printWidth: 80 } @@ -13,8 +15,8 @@ FAIL oxfmt css/format/css/keyframe-selector-comment.css { printWidth: 100 } FAIL oxfmt css/format/css/missed-semicolon-accepted.css { printWidth: 80 } FAIL oxfmt css/format/css/missed-semicolon-accepted.css { printWidth: 100 } FAIL oxfmt css/format/css/nest-params-indent.css { printWidth: 80 } -FAIL oxfmt css/format/css/nth-an-plus-b.css { printWidth: 80 } -FAIL oxfmt css/format/css/nth-an-plus-b.css { printWidth: 100 } +FAIL prettier css/format/css/nth-an-plus-b.css { printWidth: 80 } +FAIL prettier css/format/css/nth-an-plus-b.css { printWidth: 100 } FAIL oxfmt css/format/css/paren-group-glued-word.css { printWidth: 80 } FAIL oxfmt css/format/css/paren-group-glued-word.css { printWidth: 100 } FAIL oxfmt css/format/css/postcss-simple-vars/vars.css { printWidth: 80 } @@ -33,8 +35,8 @@ FAIL oxfmt css/format/less/escaped-string-gap.less { printWidth: 80 } FAIL oxfmt css/format/less/escaped-string-gap.less { printWidth: 100 } FAIL oxfmt css/format/less/extend-rule.less { printWidth: 80 } FAIL oxfmt css/format/less/extend-rule.less { printWidth: 100 } -FAIL oxfmt css/format/less/important-comments.less { printWidth: 80 } -FAIL oxfmt css/format/less/important-comments.less { printWidth: 100 } +FAIL prettier css/format/less/important-comments.less { printWidth: 80 } +FAIL prettier css/format/less/important-comments.less { printWidth: 100 } FAIL oxfmt css/format/less/javascript-verbatim.less { printWidth: 80 } FAIL oxfmt css/format/less/javascript-verbatim.less { printWidth: 100 } FAIL oxfmt css/format/less/line-comment-continuation-indent.less { printWidth: 80 } @@ -47,20 +49,28 @@ FAIL oxfmt css/format/less/mixin-selector-list.less { printWidth: 80 } FAIL oxfmt css/format/less/mixin-selector-list.less { printWidth: 100 } FAIL oxfmt css/format/less/signed-value-args.less { printWidth: 80 } FAIL oxfmt css/format/less/signed-value-args.less { printWidth: 100 } +FAIL prettier css/format/less/variable-value-comments.less { printWidth: 80 } +FAIL prettier css/format/less/variable-value-comments.less { printWidth: 100 } FAIL oxfmt css/format/less/variable-value-comments.less { printWidth: 80 } FAIL oxfmt css/format/less/variable-value-comments.less { printWidth: 100 } +FAIL prettier css/format/scss/at-rule-comment-before-block.scss { printWidth: 80 } +FAIL prettier css/format/scss/at-rule-comment-before-block.scss { printWidth: 100 } FAIL oxfmt css/format/scss/at-rule-comment-before-block.scss { printWidth: 80 } FAIL oxfmt css/format/scss/at-rule-comment-before-block.scss { printWidth: 100 } +FAIL prettier css/format/scss/at-rule-prelude-comments.scss { printWidth: 80 } +FAIL prettier css/format/scss/at-rule-prelude-comments.scss { printWidth: 100 } FAIL oxfmt css/format/scss/at-rule-prelude-comments.scss { printWidth: 80 } FAIL oxfmt css/format/scss/at-rule-prelude-comments.scss { printWidth: 100 } FAIL oxfmt css/format/scss/bracket-list.scss { printWidth: 80 } FAIL oxfmt css/format/scss/bracket-list.scss { printWidth: 100 } -FAIL oxfmt css/format/scss/custom-property-raw-verbatim.scss { printWidth: 80 } -FAIL oxfmt css/format/scss/custom-property-raw-verbatim.scss { printWidth: 100 } +FAIL prettier css/format/scss/custom-property-raw-verbatim.scss { printWidth: 80 } +FAIL prettier css/format/scss/custom-property-raw-verbatim.scss { printWidth: 100 } FAIL oxfmt css/format/scss/custom-property-text.scss { printWidth: 80 } FAIL oxfmt css/format/scss/custom-property-text.scss { printWidth: 100 } FAIL oxfmt css/format/scss/forward-members-wrap.scss { printWidth: 80 } FAIL oxfmt css/format/scss/forward-members-wrap.scss { printWidth: 100 } +FAIL prettier css/format/scss/line-comment-after-comma.scss { printWidth: 80 } +FAIL prettier css/format/scss/line-comment-after-comma.scss { printWidth: 100 } FAIL oxfmt css/format/scss/line-comment-after-comma.scss { printWidth: 80 } FAIL oxfmt css/format/scss/line-comment-after-comma.scss { printWidth: 100 } FAIL oxfmt css/format/scss/line-comment-before-comma.scss { printWidth: 80 } @@ -86,106 +96,38 @@ FAIL oxfmt css/format/scss/value-glued-minus.scss { printWidth: 80 } FAIL oxfmt css/format/scss/value-glued-minus.scss { printWidth: 100 } FAIL oxfmt css/format/scss/variable-inline-comment.scss { printWidth: 80 } FAIL oxfmt css/format/scss/variable-inline-comment.scss { printWidth: 100 } -FAIL prettier edge-cases/xxx-in-js-comment/broken-template-comment-indent.js { printWidth: 80 } -FAIL prettier edge-cases/xxx-in-js-comment/broken-template-comment-indent.js { printWidth: 100 } -FAIL prettier edge-cases/xxx-in-md/handlebars-mdx-code-blocks.md { printWidth: 80 } -FAIL prettier edge-cases/xxx-in-md/handlebars-mdx-code-blocks.md { printWidth: 100 } -FAIL prettier edge-cases/xxx-in-md/lwc-code-block.md { printWidth: 80 } -FAIL prettier edge-cases/xxx-in-md/lwc-code-block.md { printWidth: 100 } +FAIL prettier edge-cases/xxx-in-md/nested-fence-length.md { printWidth: 80 } +FAIL prettier edge-cases/xxx-in-md/nested-fence-length.md { printWidth: 100 } +FAIL prettier graphql/graphql/block-string-trailing-whitespace.graphql { printWidth: 80 } +FAIL prettier graphql/graphql/block-string-trailing-whitespace.graphql { printWidth: 100 } +FAIL oxfmt graphql/graphql/block-string-trailing-whitespace.graphql { printWidth: 80 } +FAIL oxfmt graphql/graphql/block-string-trailing-whitespace.graphql { printWidth: 100 } +FAIL prettier graphql/graphql/block-string.graphql { printWidth: 80 } +FAIL prettier graphql/graphql/block-string.graphql { printWidth: 100 } +FAIL oxfmt graphql/graphql/block-string.graphql { printWidth: 80 } +FAIL oxfmt graphql/graphql/block-string.graphql { printWidth: 100 } FAIL oxfmt graphql/graphql/comment-after-opening-delimiter.graphql { printWidth: 80 } FAIL oxfmt graphql/graphql/comment-after-opening-delimiter.graphql { printWidth: 100 } FAIL oxfmt graphql/graphql/comments-inside-node-spans.graphql { printWidth: 80 } FAIL oxfmt graphql/graphql/comments-inside-node-spans.graphql { printWidth: 100 } FAIL oxfmt graphql/graphql/string-escapes.graphql { printWidth: 80 } FAIL oxfmt graphql/graphql/string-escapes.graphql { printWidth: 100 } -FAIL oxfmt js/calls/callee-opener-comment.js { printWidth: 80 } -FAIL oxfmt js/calls/callee-opener-comment.js { printWidth: 100 } -FAIL oxfmt js/calls/issue-16125.js { printWidth: 80 } -FAIL oxfmt js/calls/issue-16125.js { printWidth: 100 } -FAIL oxfmt js/calls/test-call-comment-order.js { printWidth: 80 } -FAIL oxfmt js/calls/test-call-comment-order.js { printWidth: 100 } -FAIL oxfmt js/comments/array-holes.js { printWidth: 80 } -FAIL oxfmt js/comments/array-holes.js { printWidth: 100 } FAIL oxfmt js/comments/arrow.js { printWidth: 80 } FAIL oxfmt js/comments/arrow.js { printWidth: 100 } -FAIL oxfmt js/comments/assignment-eol-line-comment.js { printWidth: 80 } -FAIL oxfmt js/comments/assignment-eol-line-comment.js { printWidth: 100 } -FAIL oxfmt js/comments/do-while-head.js { printWidth: 80 } -FAIL oxfmt js/comments/do-while-head.js { printWidth: 100 } FAIL oxfmt js/comments/empty-statement-head.js { printWidth: 80 } FAIL oxfmt js/comments/empty-statement-head.js { printWidth: 100 } -FAIL oxfmt js/comments/for-head-slots.js { printWidth: 80 } -FAIL oxfmt js/comments/for-head-slots.js { printWidth: 100 } -FAIL oxfmt js/comments/head-body-blocks.js { printWidth: 80 } -FAIL oxfmt js/comments/head-body-blocks.js { printWidth: 100 } -FAIL oxfmt js/comments/head-paren-line-comment.js { printWidth: 80 } -FAIL oxfmt js/comments/head-paren-line-comment.js { printWidth: 100 } -FAIL oxfmt js/comments/multiline-block-head.js { printWidth: 80 } -FAIL oxfmt js/comments/multiline-block-head.js { printWidth: 100 } -FAIL oxfmt js/comments/parenthesized-trailing-comment.js { printWidth: 80 } -FAIL oxfmt js/comments/parenthesized-trailing-comment.js { printWidth: 100 } -FAIL oxfmt js/comments/try-catch-finally-head.js { printWidth: 80 } -FAIL oxfmt js/comments/try-catch-finally-head.js { printWidth: 100 } FAIL oxfmt js/comments/type-cast-comment-inside-added-parens.js { printWidth: 80 } FAIL oxfmt js/comments/type-cast-comment-inside-added-parens.js { printWidth: 100 } -FAIL oxfmt js/comments/type-cast-with-regex-parens.js { printWidth: 80 } -FAIL oxfmt js/comments/type-cast-with-regex-parens.js { printWidth: 100 } -FAIL oxfmt js/comments/unary-argument-parens.js { printWidth: 80 } -FAIL oxfmt js/comments/unary-argument-parens.js { printWidth: 100 } -FAIL oxfmt js/ignore/expression-statement.js { printWidth: 80 } -FAIL oxfmt js/ignore/expression-statement.js { printWidth: 100 } -FAIL oxfmt js/ignore/issue-18595.js { printWidth: 80 } -FAIL oxfmt js/ignore/issue-18595.js { printWidth: 100 } -FAIL oxfmt js/jsx/logical-chain-jsx-leading-comment.jsx { printWidth: 80 } -FAIL oxfmt js/jsx/logical-chain-jsx-leading-comment.jsx { printWidth: 100 } -FAIL oxfmt js/operator-position/comments.js { experimentalOperatorPosition: "start", printWidth: 80 } -FAIL oxfmt js/operator-position/comments.js { experimentalOperatorPosition: "start", printWidth: 100 } -FAIL oxfmt js/semicolons/empty-line.js { printWidth: 80, semi: false } -FAIL oxfmt js/semicolons/empty-line.js { printWidth: 100, semi: false } -FAIL prettier js/semicolons/suppressed-cast-comment-asi-guard.js { printWidth: 80, semi: false } -FAIL prettier js/semicolons/suppressed-cast-comment-asi-guard.js { printWidth: 100, semi: false } FAIL prettier js/semicolons/suppressed-for-head-declaration.js { printWidth: 80, semi: true } FAIL prettier js/semicolons/suppressed-for-head-declaration.js { printWidth: 100, semi: true } -FAIL oxfmt js/semicolons/suppressed-for-head-declaration.js { printWidth: 80, semi: true } -FAIL oxfmt js/semicolons/suppressed-for-head-declaration.js { printWidth: 100, semi: true } -FAIL oxfmt js/semicolons/suppressed-source-paren-asi-guard.js { printWidth: 80, semi: false } -FAIL oxfmt js/semicolons/suppressed-source-paren-asi-guard.js { printWidth: 100, semi: false } -FAIL prettier js/semicolons/suppressed-statement.js { printWidth: 80, semi: true } -FAIL prettier js/semicolons/suppressed-statement.js { printWidth: 100, semi: true } -FAIL prettier js/semicolons/suppressed-statement.js { printWidth: 80, semi: false } -FAIL prettier js/semicolons/suppressed-statement.js { printWidth: 100, semi: false } -FAIL oxfmt js/semicolons/suppressed-statement.js { printWidth: 80, semi: true } -FAIL oxfmt js/semicolons/suppressed-statement.js { printWidth: 100, semi: true } -FAIL oxfmt js/semicolons/suppressed-statement.js { printWidth: 80, semi: false } -FAIL oxfmt js/semicolons/suppressed-statement.js { printWidth: 100, semi: false } -FAIL oxfmt js/semicolons/suppressed-trailing-semicolon.js { printWidth: 80, semi: false } -FAIL oxfmt js/semicolons/suppressed-trailing-semicolon.js { printWidth: 100, semi: false } -FAIL oxfmt js/switch/clause-block-comment.js { printWidth: 80 } -FAIL oxfmt js/switch/clause-block-comment.js { printWidth: 100 } -FAIL oxfmt js/typecast/comments-inside-cast-parens.js { printWidth: 80 } -FAIL oxfmt js/typecast/comments-inside-cast-parens.js { printWidth: 100 } +FAIL prettier js/semicolons/suppressed-source-paren-asi-guard.js { printWidth: 80, semi: false } +FAIL prettier js/semicolons/suppressed-source-paren-asi-guard.js { printWidth: 100, semi: false } +FAIL prettier markdown/markdown/fence-info-backtick.md { printWidth: 80 } +FAIL prettier markdown/markdown/fence-info-backtick.md { printWidth: 100 } FAIL oxfmt markdown/markdown/fence-info-backtick.md { printWidth: 80 } FAIL oxfmt markdown/markdown/fence-info-backtick.md { printWidth: 100 } FAIL oxfmt markdown/markdown/front-matter.md { printWidth: 80 } FAIL oxfmt markdown/markdown/front-matter.md { printWidth: 100 } -FAIL oxfmt markdown/markdown/html-block-trailing-newline.md { printWidth: 80 } -FAIL oxfmt markdown/markdown/html-block-trailing-newline.md { printWidth: 100 } -FAIL oxfmt markdown/markdown/indented-code-tab.md { printWidth: 80 } -FAIL oxfmt markdown/markdown/indented-code-tab.md { printWidth: 100 } -FAIL oxfmt markdown/markdown/lazy-html-block.md { printWidth: 80 } -FAIL oxfmt markdown/markdown/lazy-html-block.md { printWidth: 100 } -FAIL oxfmt markdown/markdown/leading-dashes-paragraph.md { printWidth: 80 } -FAIL oxfmt markdown/markdown/leading-dashes-paragraph.md { printWidth: 100 } -FAIL oxfmt markdown/markdown/leading-thematic-break.md { printWidth: 80 } -FAIL oxfmt markdown/markdown/leading-thematic-break.md { printWidth: 100 } -FAIL oxfmt markdown/markdown/list-after-html-block.md { printWidth: 80 } -FAIL oxfmt markdown/markdown/list-after-html-block.md { printWidth: 100 } -FAIL oxfmt markdown/markdown/list-marker-after-ignored-list.md { printWidth: 80 } -FAIL oxfmt markdown/markdown/list-marker-after-ignored-list.md { printWidth: 100 } -FAIL oxfmt markdown/markdown/nul-character.md { printWidth: 80 } -FAIL oxfmt markdown/markdown/nul-character.md { printWidth: 100 } -FAIL oxfmt markdown/markdown/oxfmt-ignore.md { printWidth: 80 } -FAIL oxfmt markdown/markdown/oxfmt-ignore.md { printWidth: 100 } FAIL oxfmt markdown/markdown/prose-wrap/cj-line-break.md { printWidth: 80, proseWrap: "always" } FAIL oxfmt markdown/markdown/prose-wrap/cj-line-break.md { printWidth: 100, proseWrap: "always" } FAIL oxfmt markdown/markdown/prose-wrap/cj-line-break.md { printWidth: 80, proseWrap: "never" } @@ -196,10 +138,6 @@ FAIL oxfmt markdown/markdown/prose-wrap/code-span-fence-at-line-start.md { print FAIL oxfmt markdown/markdown/prose-wrap/code-span-fence-at-line-start.md { printWidth: 100, proseWrap: "never" } FAIL oxfmt markdown/markdown/prose-wrap/code-span-fence-at-line-start.md { printWidth: 80, proseWrap: "preserve" } FAIL oxfmt markdown/markdown/prose-wrap/code-span-fence-at-line-start.md { printWidth: 100, proseWrap: "preserve" } -FAIL oxfmt markdown/markdown/prose-wrap/container-directive-blanks.md { printWidth: 80, proseWrap: "always" } -FAIL oxfmt markdown/markdown/prose-wrap/container-directive-blanks.md { printWidth: 100, proseWrap: "always" } -FAIL oxfmt markdown/markdown/prose-wrap/container-directive-blanks.md { printWidth: 80, proseWrap: "never" } -FAIL oxfmt markdown/markdown/prose-wrap/container-directive-blanks.md { printWidth: 100, proseWrap: "never" } FAIL oxfmt markdown/markdown/prose-wrap/container-directive.md { printWidth: 80, proseWrap: "always" } FAIL oxfmt markdown/markdown/prose-wrap/container-directive.md { printWidth: 100, proseWrap: "always" } FAIL oxfmt markdown/markdown/prose-wrap/container-directive.md { printWidth: 80, proseWrap: "never" } @@ -216,8 +154,6 @@ FAIL oxfmt markdown/markdown/prose-wrap/footnote-kept-line-break.md { printWidth FAIL oxfmt markdown/markdown/prose-wrap/footnote-kept-line-break.md { printWidth: 100, proseWrap: "never" } FAIL oxfmt markdown/markdown/prose-wrap/footnote-kept-line-break.md { printWidth: 80, proseWrap: "preserve" } FAIL oxfmt markdown/markdown/prose-wrap/footnote-kept-line-break.md { printWidth: 100, proseWrap: "preserve" } -FAIL oxfmt markdown/markdown/prose-wrap/ignored-block-trailing-quote-line.md { printWidth: 80, proseWrap: "always" } -FAIL oxfmt markdown/markdown/prose-wrap/ignored-block-trailing-quote-line.md { printWidth: 100, proseWrap: "always" } FAIL oxfmt markdown/markdown/prose-wrap/line-shapes.md { printWidth: 80, proseWrap: "always" } FAIL oxfmt markdown/markdown/prose-wrap/line-shapes.md { printWidth: 100, proseWrap: "always" } FAIL oxfmt markdown/markdown/prose-wrap/line-shapes.md { printWidth: 80, proseWrap: "never" } @@ -238,88 +174,28 @@ FAIL oxfmt markdown/markdown/prose-wrap/wiki-link-code-span.md { printWidth: 80, FAIL oxfmt markdown/markdown/prose-wrap/wiki-link-code-span.md { printWidth: 100, proseWrap: "always" } FAIL oxfmt markdown/markdown/prose-wrap/wiki-link-code-span.md { printWidth: 80, proseWrap: "never" } FAIL oxfmt markdown/markdown/prose-wrap/wiki-link-code-span.md { printWidth: 100, proseWrap: "never" } -FAIL oxfmt markdown/markdown/prose-wrap/wiki-link-risk-link-text.md { printWidth: 80, proseWrap: "always" } -FAIL oxfmt markdown/markdown/prose-wrap/wiki-link-risk-link-text.md { printWidth: 100, proseWrap: "always" } -FAIL oxfmt markdown/markdown/prose-wrap/wiki-link-risk-link-text.md { printWidth: 80, proseWrap: "never" } -FAIL oxfmt markdown/markdown/prose-wrap/wiki-link-risk-link-text.md { printWidth: 100, proseWrap: "never" } -FAIL oxfmt markdown/markdown/prose-wrap/wiki-link-risk-link-text.md { printWidth: 80, proseWrap: "preserve" } -FAIL oxfmt markdown/markdown/prose-wrap/wiki-link-risk-link-text.md { printWidth: 100, proseWrap: "preserve" } +FAIL prettier markdown/markdown/prose-wrap/wrapped-block-starts.md { printWidth: 80, proseWrap: "always" } +FAIL prettier markdown/markdown/prose-wrap/wrapped-block-starts.md { printWidth: 100, proseWrap: "always" } +FAIL prettier markdown/markdown/prose-wrap/wrapped-block-starts.md { printWidth: 80, proseWrap: "never" } +FAIL prettier markdown/markdown/prose-wrap/wrapped-block-starts.md { printWidth: 100, proseWrap: "never" } +FAIL prettier markdown/markdown/prose-wrap/wrapped-block-starts.md { printWidth: 80, proseWrap: "preserve" } +FAIL prettier markdown/markdown/prose-wrap/wrapped-block-starts.md { printWidth: 100, proseWrap: "preserve" } FAIL oxfmt markdown/markdown/prose-wrap/wrapped-block-starts.md { printWidth: 80, proseWrap: "always" } -FAIL oxfmt markdown/markdown/prose-wrap/wrapped-block-starts.md { printWidth: 100, proseWrap: "always" } -FAIL oxfmt markdown/markdown/prose-wrap/wrapped-block-starts.md { printWidth: 80, proseWrap: "never" } -FAIL oxfmt markdown/markdown/prose-wrap/wrapped-block-starts.md { printWidth: 100, proseWrap: "never" } -FAIL oxfmt markdown/markdown/prose-wrap/wrapped-block-starts.md { printWidth: 80, proseWrap: "preserve" } -FAIL oxfmt markdown/markdown/prose-wrap/wrapped-block-starts.md { printWidth: 100, proseWrap: "preserve" } -FAIL oxfmt markdown/markdown/tab-width-4/list-html-block-alignment.md { printWidth: 80, tabWidth: 4 } -FAIL oxfmt markdown/markdown/tab-width-4/list-html-block-alignment.md { printWidth: 100, tabWidth: 4 } -FAIL oxfmt markdown/markdown/tab-width-4/ordered-marker-before-indented-code.md { printWidth: 80, tabWidth: 4 } -FAIL oxfmt markdown/markdown/tab-width-4/ordered-marker-before-indented-code.md { printWidth: 100, tabWidth: 4 } -FAIL oxfmt markdown/markdown/url-escaping.md { printWidth: 80 } -FAIL oxfmt markdown/markdown/url-escaping.md { printWidth: 100 } -FAIL oxfmt markdown/markdown/verbatim-inline-continuation.md { printWidth: 80 } -FAIL oxfmt markdown/markdown/verbatim-inline-continuation.md { printWidth: 100 } -FAIL oxfmt ts/arguments/issue-26465.ts { printWidth: 80 } -FAIL oxfmt ts/assignments/type-alias-leading-comment.ts { printWidth: 80 } -FAIL oxfmt ts/assignments/type-alias-leading-comment.ts { printWidth: 100 } -FAIL oxfmt ts/calls/callee-opener-comment.ts { printWidth: 80 } -FAIL oxfmt ts/calls/callee-opener-comment.ts { printWidth: 100 } -FAIL oxfmt ts/comments/assignments.ts { printWidth: 80 } -FAIL oxfmt ts/comments/assignments.ts { printWidth: 100 } -FAIL oxfmt ts/comments/declaration-head-body.ts { printWidth: 80 } -FAIL oxfmt ts/comments/declaration-head-body.ts { printWidth: 100 } -FAIL oxfmt ts/comments/if.ts { printWidth: 80 } -FAIL oxfmt ts/comments/if.ts { printWidth: 100 } -FAIL oxfmt ts/comments/method.ts { printWidth: 80 } -FAIL oxfmt ts/comments/method.ts { printWidth: 100 } -FAIL oxfmt ts/comments/type-alias-multiline-block-comment.ts { printWidth: 80 } -FAIL oxfmt ts/comments/type-alias-multiline-block-comment.ts { printWidth: 100 } -FAIL oxfmt ts/comments/type-alias.ts { printWidth: 80 } -FAIL oxfmt ts/comments/type-alias.ts { printWidth: 100 } -FAIL oxfmt ts/ignore/decorated-class-export.ts { printWidth: 80 } -FAIL oxfmt ts/ignore/decorated-class-export.ts { printWidth: 100 } -FAIL oxfmt ts/ignore/eol-after-operator.ts { printWidth: 80 } -FAIL oxfmt ts/ignore/eol-after-operator.ts { printWidth: 100 } -FAIL oxfmt ts/import-phases/issue-22691.ts { printWidth: 80 } -FAIL oxfmt ts/import-phases/issue-22691.ts { printWidth: 100 } -FAIL oxfmt ts/parenthesis/type-assertion-exponentiation.ts { printWidth: 80 } -FAIL oxfmt ts/parenthesis/type-assertion-exponentiation.ts { printWidth: 100 } +FAIL prettier ts/comments/yield.ts { printWidth: 80 } +FAIL prettier ts/comments/yield.ts { printWidth: 100 } FAIL oxfmt ts/quote-props/enums.ts { printWidth: 80, quoteProps: "as-needed" } FAIL oxfmt ts/quote-props/enums.ts { printWidth: 100, quoteProps: "as-needed" } -FAIL oxfmt ts/quote-props/enums.ts { printWidth: 80, quoteProps: "preserve" } -FAIL oxfmt ts/quote-props/enums.ts { printWidth: 100, quoteProps: "preserve" } FAIL oxfmt ts/quote-props/enums.ts { printWidth: 80, quoteProps: "consistent" } FAIL oxfmt ts/quote-props/enums.ts { printWidth: 100, quoteProps: "consistent" } FAIL oxfmt ts/quote-props/enums.ts { printWidth: 80, quoteProps: "consistent", singleQuote: true } FAIL oxfmt ts/quote-props/enums.ts { printWidth: 100, quoteProps: "consistent", singleQuote: true } -FAIL prettier ts/semicolons/suppressed-class-member.ts { printWidth: 80, semi: true } -FAIL prettier ts/semicolons/suppressed-class-member.ts { printWidth: 100, semi: true } -FAIL prettier ts/semicolons/suppressed-class-member.ts { printWidth: 80, semi: false } -FAIL prettier ts/semicolons/suppressed-class-member.ts { printWidth: 100, semi: false } -FAIL oxfmt ts/semicolons/suppressed-class-member.ts { printWidth: 80, semi: true } -FAIL oxfmt ts/semicolons/suppressed-class-member.ts { printWidth: 100, semi: true } -FAIL oxfmt ts/semicolons/suppressed-class-member.ts { printWidth: 80, semi: false } -FAIL oxfmt ts/semicolons/suppressed-class-member.ts { printWidth: 100, semi: false } -FAIL oxfmt ts/semicolons/suppressed-declaration-parens.ts { printWidth: 80, semi: true } -FAIL oxfmt ts/semicolons/suppressed-declaration-parens.ts { printWidth: 100, semi: true } -FAIL oxfmt ts/semicolons/suppressed-declaration-parens.ts { printWidth: 80, semi: false } -FAIL oxfmt ts/semicolons/suppressed-declaration-parens.ts { printWidth: 100, semi: false } -FAIL prettier ts/semicolons/trailing-comments-class-members.ts { printWidth: 80, semi: true } -FAIL prettier ts/semicolons/trailing-comments-class-members.ts { printWidth: 100, semi: true } -FAIL prettier ts/semicolons/trailing-comments-class-members.ts { printWidth: 80, semi: false } -FAIL prettier ts/semicolons/trailing-comments-class-members.ts { printWidth: 100, semi: false } -FAIL oxfmt ts/semicolons/trailing-comments-class-members.ts { printWidth: 80, semi: true } -FAIL oxfmt ts/semicolons/trailing-comments-class-members.ts { printWidth: 100, semi: true } -FAIL oxfmt ts/semicolons/trailing-comments-class-members.ts { printWidth: 80, semi: false } -FAIL oxfmt ts/semicolons/trailing-comments-class-members.ts { printWidth: 100, semi: false } -FAIL oxfmt ts/semicolons/trailing-comments-parens.ts { printWidth: 80, semi: true } -FAIL oxfmt ts/semicolons/trailing-comments-parens.ts { printWidth: 100, semi: true } -FAIL oxfmt ts/semicolons/trailing-comments-parens.ts { printWidth: 80, semi: false } -FAIL oxfmt ts/semicolons/trailing-comments-parens.ts { printWidth: 100, semi: false } -FAIL oxfmt ts/semicolons/trailing-comments.ts { printWidth: 80, semi: true } -FAIL oxfmt ts/semicolons/trailing-comments.ts { printWidth: 100, semi: true } -FAIL oxfmt ts/semicolons/trailing-comments.ts { printWidth: 80, semi: false } -FAIL oxfmt ts/semicolons/trailing-comments.ts { printWidth: 100, semi: false } -FAIL prettier ts/union/suppression.ts { printWidth: 80 } -FAIL prettier ts/union/suppression.ts { printWidth: 100 } -as Prettier prints them: 1548/1570 -as oxfmt prints them, in its flavor: 1102/1498 +FAIL prettier yaml/yaml/block-scalar-trailing-spaces.yaml { printWidth: 80 } +FAIL prettier yaml/yaml/block-scalar-trailing-spaces.yaml { printWidth: 100 } +FAIL prettier yaml/yaml/prose-wrap/trailing-spaces.yaml { printWidth: 80 } +FAIL prettier yaml/yaml/prose-wrap/trailing-spaces.yaml { printWidth: 100 } +FAIL prettier yaml/yaml/prose-wrap/trailing-spaces.yaml { printWidth: 80, proseWrap: "always" } +FAIL prettier yaml/yaml/prose-wrap/trailing-spaces.yaml { printWidth: 100, proseWrap: "always" } +FAIL prettier yaml/yaml/prose-wrap/trailing-spaces.yaml { printWidth: 80, proseWrap: "never" } +FAIL prettier yaml/yaml/prose-wrap/trailing-spaces.yaml { printWidth: 100, proseWrap: "never" } +as Prettier prints them: 1526/1570 +as oxfmt prints them, in its flavor: 1343/1498 diff --git a/test/cli/format/oxfmt/fixtures.ts b/test/cli/format/oxfmt/fixtures.ts index 81f934a08ea3..44e1832d726d 100644 --- a/test/cli/format/oxfmt/fixtures.ts +++ b/test/cli/format/oxfmt/fixtures.ts @@ -1,9 +1,9 @@ -// How oxc's test harness (`oxc_formatter_core/src/test_support/harness.rs`) reads and writes its fixtures. +// Reads and writes fixtures the way oxc's test harness (`oxc_formatter_core/src/test_support/harness.rs`) does. import { dirname } from "node:path"; export type Options = Record; -/** The sets of options that a fixture is formatted with: those of the nearest `options.json`, each at the widths 80 and 100. */ +/** Returns a fixture's option sets: those in the nearest `options.json`, each at widths 80 and 100. */ export function rowsOf(name: string, files: Map): Options[] { let sets: Options[] = [{}]; for (let directory = dirname(name); directory !== "."; directory = dirname(directory)) { @@ -35,7 +35,7 @@ export function render(outputs: [Options, string][]) { return text + "===================== End =====================\n"; } -/** The outputs in a snapshot, by what `display` gives for their options. */ +/** Returns a snapshot's outputs, keyed by the `display` string of their options. */ export function parse(text: string) { const outputs = new Map(); const title = "==================== Output ====================\n"; diff --git a/test/cli/format/oxfmt/sync.ts b/test/cli/format/oxfmt/sync.ts index f26d7d3a66ff..3aa074ec520c 100644 --- a/test/cli/format/oxfmt/sync.ts +++ b/test/cli/format/oxfmt/sync.ts @@ -1,4 +1,4 @@ -// Collects the fixtures of oxc's formatter, its snapshots, and what Prettier prints for the same inputs, in `bundle.zst`. +// Collects the oxc formatter's fixtures, its snapshots, and Prettier's output for the same inputs into `bundle.zst`. // // bun test/cli/format/oxfmt/sync.ts // bun test/cli/format/oxfmt/sync.ts --extract @@ -21,21 +21,22 @@ if (source === "--extract" && rest.length === 2) { for (const language of ["css", "graphql", "json", "markdown", "yaml"]) { const found = new Map(); collect(join(source, `crates/oxc_formatter_${language}/tests`), "fixtures", found, name => name.endsWith(".rs")); - // `embedded`: style sheets with the placeholders that stand for the `${}` of a template. + // `embedded` has style sheets with placeholders that replace a template's `${}`. for (const [name, bytes] of found) if (!name.startsWith("fixtures/embedded/")) files.set(name.replace("fixtures", language), bytes); } - // One language in another. Of these there is no snapshot of oxfmt's. + // One language embedded in another. oxfmt has no snapshots for these. for (const kind of ["css-in-js", "gql-in-js", "md-in-js", "xxx-in-js-comment", "xxx-in-md"]) { collect(join(source, "apps/oxfmt/conformance/fixtures"), `edge-cases/${kind}`, files, () => false); } - // `tests/jsdoc/fixtures` has pairs, `a.ts` and `a.output.ts`, with options in snake case. They are written in the form of the others. + // `tests/jsdoc/fixtures` has pairs, `a.ts` and `a.output.ts`, with options in snake case. They're converted to the + // format of the others. const pairs = new Map(); collect(join(source, "crates/oxc_formatter/tests"), "jsdoc/fixtures", pairs, () => false); const rowsOfPairs = new Map(); for (const [name, bytes] of pairs) { const [, stem, extension] = /^(.*?)(\.[jt]sx?)$/.exec(name) ?? []; const output = pairs.get(`${stem}.output${extension}`); - // The one that oxc's own test leaves out: it needs a formatter for HTML. + // oxc's own test skips this one too, because it needs an HTML formatter. if (!stem || !output || name.endsWith("descriptions/032-jsx-tsx-css.ts")) continue; const given = pairs.get(`${stem}.options.json`) ?? pairs.get(`${dirname(name)}/options.json`); const options: Options = {}; @@ -43,7 +44,7 @@ if (source === "--extract" && rest.length === 2) { const camelCase = key.replace(/_(.)/g, (_, letter) => letter.toUpperCase()); options[key === "single_quote" || key === "print_width" ? camelCase : `jsdoc.${camelCase}`] = value; } - // A property of `jsdoc` says that it is on. + // Setting any `jsdoc` property turns it on. if (!Object.keys(options).some(name => name.startsWith("jsdoc."))) options.jsdoc = true; files.set(name, bytes); files.set(`${name}.snap`, Buffer.from(render([[options, Buffer.from(output).toString()]]))); @@ -53,7 +54,7 @@ if (source === "--extract" && rest.length === 2) { if (!files.has(`${name}.snap`) && !name.startsWith("edge-cases/")) continue; const outputs: [Options, string][] = []; for (const options of rowsOfPairs.get(name) ?? rowsOf(name, files)) { - // Not options of Prettier. + // Prettier doesn't have the `jsdoc` options. const known = Object.fromEntries(Object.entries(options).flatMap(([name, value]) => (name.startsWith("jsdoc") ? [] : [[name === "variant" ? "parser" : name, value]]))); const input = Buffer.from(bytes).toString(); const output: string = await prettier.format(input, { ...known, filepath: name }).catch((error: Error) => `<${error.name}>`); diff --git a/test/cli/format/prettier-cli/prettier-cli.test.ts b/test/cli/format/prettier-cli/prettier-cli.test.ts index 7247a9c80e7b..68df7a389d7e 100644 --- a/test/cli/format/prettier-cli/prettier-cli.test.ts +++ b/test/cli/format/prettier-cli/prettier-cli.test.ts @@ -1,7 +1,7 @@ -// The command lines of Prettier's own integration tests (`runCli("cli/..", [..])` in `tests/integration/__tests__/*.js` of -// prettier/prettier, MIT: see LICENSE), with what Prettier 3.9 does in each: the exit code, the files afterwards, the files that -// `--check` and `--list-different` name, and what is printed for standard input. `bun fmt` writes unless told otherwise, so -// Prettier was given `--write` where the command line only prints. +// The command lines from Prettier's own integration tests (`runCli("cli/..", [..])` in +// `tests/integration/__tests__/*.js` in prettier/prettier, MIT: see LICENSE), with Prettier 3.9's result for each: the +// exit code, the files afterwards, the files that `--check` and `--list-different` list, and the output for standard +// input. `bun fmt` writes unless told otherwise, so Prettier was given `--write` where the command line only prints. // `cases.json` is written by `test/cli/lint/oracle/driver/prettier-fixtures.mjs --record`. import { afterAll, describe, expect, test } from "bun:test"; import { bunEnv, bunExe, isWindows, tempDir } from "harness"; @@ -14,18 +14,18 @@ afterAll(endChildren); type Files = Record; const command = [bunExe(), "fmt"]; -// The languages that `bun fmt` leaves alone. +// The languages that `bun fmt` doesn't format. const notCompared = /\.mdx$/; const env = { ...bunEnv, NO_COLOR: "1", AGENT: "0", CLAUDECODE: undefined }; -describe.concurrent("bun fmt does what Prettier does", () => { +describe.concurrent("bun fmt behaves like Prettier", () => { for (const it of cases) { const top = it.directory.split("/").slice(0, 2).join("/"); const files = (fixtures as Record)[top]; const links = Object.entries(files).filter(([, file]) => typeof file !== "string") as [string, { link: string }][]; - // A name that Windows does not allow. - const isForPosix = links.length > 0 || Object.keys(files).some(name => /[<>:"|?*\\]/.test(name)); - test.skipIf(isWindows && isForPosix)(`${it.test}: ${it.directory} $ ${it.args.join(" ")}`, async () => { + // Links, or a name that Windows doesn't allow. + const needsPosix = links.length > 0 || Object.keys(files).some(name => /[<>:"|?*\\]/.test(name)); + test.skipIf(isWindows && needsPosix)(`${it.test}: ${it.directory} $ ${it.args.join(" ")}`, async () => { const texts = Object.entries(files).filter(([, file]) => typeof file === "string") as [string, string][]; using dir = tempDir("prettier-cli", Object.fromEntries(texts.map(([name, text]) => [`${top}/${name}`, text]))); for (const [name, { link }] of links) symlinkSync(link, join(String(dir), top, name)); @@ -42,10 +42,10 @@ describe.concurrent("bun fmt does what Prettier does", () => { const after = readFileSync(join(String(dir), top, name), "utf8"); return after === text || notCompared.test(name) ? [] : [[`${top}/${name}`, after]]; }); - const named = (stdout + stderr).split("\n").map(line => (line.startsWith("[warn] ") ? line.slice(7) : line)); + const lines = (stdout + stderr).split("\n").map(line => (line.startsWith("[warn] ") ? line.slice(7) : line)); expect({ changed: Object.fromEntries(changed), - listed: it.listed && it.listed.filter(name => named.includes(name)), + listed: it.listed && it.listed.filter(name => lines.includes(name)), stdout: it.stdout === undefined ? undefined : stdout, exitCode, }).toEqual({ diff --git a/test/cli/format/prettier/expected.txt b/test/cli/format/prettier/expected.txt index c65a75efbf15..6ff914b2cb19 100644 --- a/test/cli/format/prettier/expected.txt +++ b/test/cli/format/prettier/expected.txt @@ -1,33 +1,111 @@ +FAIL format js/multiparser-markdown/codeblock.js proseWrap=always FAIL rejected flow/_errors_/number.js FAIL rejected flow/_errors_/ambient/ambient.js FAIL rejected flow/_errors_/ambient/ambient.unknown FAIL format flow/await/await-keywords.js -FAIL second-format flow/comments/type_annotations.js -FAIL format flow/hook/declare-hook.js -FAIL format flow/hook/hook-type-annotation.js -FAIL format flow/mapped-types/comments.js FAIL format flow/ternary/arrows.js +FAIL format css/font/font.css +FAIL format css/postcss-8-improment/test.css +FAIL format less/less-test-suite/snippet: tests-unit/javascript/javascript.less +FAIL format less/postcss-8-improment/test.less +FAIL format scss/variables/postcss-8-improment.scss +FAIL format graphql/string/description.graphql +FAIL format graphql/string/string.graphql +FAIL format yaml/block-value/snippet: "foo: >-\n x\n \n" +FAIL format yaml/block-value/snippet: "foo: >-\n x\n \n\n" +FAIL format yaml/block-value/snippet: "foo: >-\n x\n \n\n..." +FAIL format yaml/block-value/snippet: "foo: >-\n x\n \n\n\n" +FAIL format yaml/block-value/snippet: "foo: >-\n x\n \n\n\n..." +FAIL format yaml/block-value/snippet: "foo: >-\n x\n \n\n\n\n" +FAIL format yaml/block-value/snippet: "foo: >-\n x\n \n\n\n\n..." +FAIL format yaml/block-value/snippet: "foo: >-\n x\n \n\n\n\n\n..." +FAIL format yaml/block-value/snippet: "foo: >-\n x\n \t\n" +FAIL format yaml/block-value/snippet: "foo: >-\n x\n \t\n\n" +FAIL format yaml/block-value/snippet: "foo: >-\n x\n \t\n\n..." +FAIL format yaml/block-value/snippet: "foo: >-\n x\n \t\n\n\n" +FAIL format yaml/block-value/snippet: "foo: >-\n x\n \t\n\n\n..." +FAIL format yaml/block-value/snippet: "foo: >-\n x\n \t\n\n\n\n" +FAIL format yaml/block-value/snippet: "foo: >-\n x\n \t\n\n\n\n..." +FAIL format yaml/block-value/snippet: "foo: >-\n x\n \t\n\n\n\n\n..." +FAIL format yaml/block-value/snippet: "foo: >\n x\n \n" +FAIL format yaml/block-value/snippet: "foo: >\n x\n \n\n" +FAIL format yaml/block-value/snippet: "foo: >\n x\n \n\n..." +FAIL format yaml/block-value/snippet: "foo: >\n x\n \n\n\n" +FAIL format yaml/block-value/snippet: "foo: >\n x\n \n\n\n..." +FAIL format yaml/block-value/snippet: "foo: >\n x\n \n\n\n\n" +FAIL format yaml/block-value/snippet: "foo: >\n x\n \n\n\n\n..." +FAIL format yaml/block-value/snippet: "foo: >\n x\n \n\n\n\n\n..." +FAIL format yaml/block-value/snippet: "foo: >\n x\n \t\n" +FAIL format yaml/block-value/snippet: "foo: >\n x\n \t\n\n" +FAIL format yaml/block-value/snippet: "foo: >\n x\n \t\n\n..." +FAIL format yaml/block-value/snippet: "foo: >\n x\n \t\n\n\n" +FAIL format yaml/block-value/snippet: "foo: >\n x\n \t\n\n\n..." +FAIL format yaml/block-value/snippet: "foo: >\n x\n \t\n\n\n\n" +FAIL format yaml/block-value/snippet: "foo: >\n x\n \t\n\n\n\n..." +FAIL format yaml/block-value/snippet: "foo: >\n x\n \t\n\n\n\n\n..." +FAIL format yaml/block-value/snippet: "foo: |-\n x\n \n" +FAIL format yaml/block-value/snippet: "foo: |-\n x\n \n\n" +FAIL format yaml/block-value/snippet: "foo: |-\n x\n \n\n..." +FAIL format yaml/block-value/snippet: "foo: |-\n x\n \n\n\n" +FAIL format yaml/block-value/snippet: "foo: |-\n x\n \n\n\n..." +FAIL format yaml/block-value/snippet: "foo: |-\n x\n \n\n\n\n" +FAIL format yaml/block-value/snippet: "foo: |-\n x\n \n\n\n\n..." +FAIL format yaml/block-value/snippet: "foo: |-\n x\n \n\n\n\n\n..." +FAIL format yaml/block-value/snippet: "foo: |-\n x\n \t\n" +FAIL format yaml/block-value/snippet: "foo: |-\n x\n \t\n\n" +FAIL format yaml/block-value/snippet: "foo: |-\n x\n \t\n\n..." +FAIL format yaml/block-value/snippet: "foo: |-\n x\n \t\n\n\n" +FAIL format yaml/block-value/snippet: "foo: |-\n x\n \t\n\n\n..." +FAIL format yaml/block-value/snippet: "foo: |-\n x\n \t\n\n\n\n" +FAIL format yaml/block-value/snippet: "foo: |-\n x\n \t\n\n\n\n..." +FAIL format yaml/block-value/snippet: "foo: |-\n x\n \t\n\n\n\n\n..." +FAIL format yaml/block-value/snippet: "foo: |\n x\n \n" +FAIL format yaml/block-value/snippet: "foo: |\n x\n \n\n" +FAIL format yaml/block-value/snippet: "foo: |\n x\n \n\n..." +FAIL format yaml/block-value/snippet: "foo: |\n x\n \n\n\n" +FAIL format yaml/block-value/snippet: "foo: |\n x\n \n\n\n..." +FAIL format yaml/block-value/snippet: "foo: |\n x\n \n\n\n\n" +FAIL format yaml/block-value/snippet: "foo: |\n x\n \n\n\n\n..." +FAIL format yaml/block-value/snippet: "foo: |\n x\n \n\n\n\n\n..." +FAIL format yaml/block-value/snippet: "foo: |\n x\n \t\n" +FAIL format yaml/block-value/snippet: "foo: |\n x\n \t\n\n" +FAIL format yaml/block-value/snippet: "foo: |\n x\n \t\n\n..." +FAIL format yaml/block-value/snippet: "foo: |\n x\n \t\n\n\n" +FAIL format yaml/block-value/snippet: "foo: |\n x\n \t\n\n\n..." +FAIL format yaml/block-value/snippet: "foo: |\n x\n \t\n\n\n\n" +FAIL format yaml/block-value/snippet: "foo: |\n x\n \t\n\n\n\n..." +FAIL format yaml/block-value/snippet: "foo: |\n x\n \t\n\n\n\n\n..." +FAIL format yaml/yaml-test-suite/snippet: L24T-2.yaml - Trailing line of spaces +FAIL format yaml/yaml-test-suite/snippet: L24T.yaml - Trailing line of spaces +FAIL format yaml/yaml-test-suite/snippet: Y79Y-2.yaml - Tabs in various contexts +FAIL format markdown/commonmark-test-suite/snippet: example-112.md (Indented code blocks) proseWrap=always +FAIL format markdown/commonmark-test-suite/snippet: example-118.md (Indented code blocks) proseWrap=always +FAIL format markdown/commonmark-test-suite/snippet: example-129.md (Fenced code blocks) proseWrap=always +FAIL format html/tags/tags2.html printWidth=Infinity +FAIL format html/tags/tags2.html printWidth=1 printWidth=1 +FAIL format html/tags/tags2.html angular: format 109/109 (0 syntax errors), rejected 1/1, second format 96/96, CRLF 109/109, CR 109/109, BOM 109/109 -css: format 162/162 (0 syntax errors), rejected 2/2, second format 136/136, CRLF 162/162, CR 162/162, BOM 161/161 -flow: format 1500/1505 (2 syntax errors), rejected 19/22, second format 1171/1172, CRLF 1493/1493, CR 1493/1493, BOM 1500/1500 -graphql: format 104/104 (0 syntax errors), rejected 2/2, second format 87/87, CRLF 104/104, CR 104/104, BOM 104/104 +css: format 160/162 (0 syntax errors), rejected 2/2, second format 134/134, CRLF 160/160, CR 160/160, BOM 159/159 +flow: format 1503/1505 (2 syntax errors), rejected 19/22, second format 1172/1172, CRLF 1496/1496, CR 1496/1496, BOM 1503/1503 +graphql: format 102/104 (0 syntax errors), rejected 2/2, second format 85/85, CRLF 102/102, CR 102/102, BOM 102/102 handlebars: format 128/128 (0 syntax errors), rejected 33/33, second format 114/114, CRLF 122/122, CR 122/122, BOM 128/128 -html: format 272/272 (0 syntax errors), rejected 2/2, second format 210/210, CRLF 262/262, CR 262/262, BOM 272/272 -js: format 1357/1357 (0 syntax errors), rejected 165/165, second format 1063/1063, CRLF 1347/1347, CR 1347/1347, BOM 1353/1353 +html: format 269/272 (0 syntax errors), rejected 2/2, second format 207/207, CRLF 259/259, CR 259/259, BOM 269/269 +js: format 1356/1357 (0 syntax errors), rejected 165/165, second format 1063/1063, CRLF 1346/1346, CR 1346/1346, BOM 1352/1352 json: format 785/785 (0 syntax errors), rejected 191/191, second format 696/696, CRLF 785/785, CR 785/785, BOM 781/781 jsx: format 186/186 (0 syntax errors), rejected 19/19, second format 166/166, CRLF 185/185, CR 185/185, BOM 186/186 -less: format 238/238 (0 syntax errors), rejected 4/4, second format 191/191, CRLF 236/236, CR 236/236, BOM 238/238 +less: format 236/238 (0 syntax errors), rejected 4/4, second format 189/189, CRLF 234/234, CR 234/234, BOM 236/236 lwc: format 5/5 (0 syntax errors), rejected 0/0, second format 5/5, CRLF 5/5, CR 5/5, BOM 5/5 -markdown: format 1572/1572 (0 syntax errors), rejected 0/0, second format 949/949, CRLF 1568/1568, CR 1568/1568, BOM 1572/1572 +markdown: format 1569/1572 (0 syntax errors), rejected 0/0, second format 946/946, CRLF 1565/1565, CR 1565/1565, BOM 1569/1569 mdx: format 32/32 (0 syntax errors), rejected 0/0, second format 22/22, CRLF 32/32, CR 32/32, BOM 32/32 misc: format 565/565 (0 syntax errors), rejected 7/7, second format 502/502, CRLF 104/104, CR 104/104, BOM 564/564 mjml: format 9/9 (0 syntax errors), rejected 0/0, second format 8/8, CRLF 9/9, CR 9/9, BOM 9/9 -scss: format 136/136 (0 syntax errors), rejected 1/1, second format 117/117, CRLF 136/136, CR 136/136, BOM 136/136 +scss: format 135/136 (0 syntax errors), rejected 1/1, second format 116/116, CRLF 135/135, CR 135/135, BOM 135/135 typescript: format 756/756 (0 syntax errors), rejected 355/355, second format 609/609, CRLF 755/755, CR 755/755, BOM 743/743 vue: format 189/189 (0 syntax errors), rejected 3/3, second format 156/156, CRLF 189/189, CR 189/189, BOM 189/189 -yaml: format 1623/1623 (0 syntax errors), rejected 3/3, second format 1118/1118, CRLF 1616/1616, CR 1616/1616, BOM 1622/1622 -format: 9728/9733 (99.95%) -all checks: 46093/46102 (99.98%) +yaml: format 1554/1621 (0 syntax errors), rejected 3/3, second format 1049/1049, CRLF 1547/1547, CR 1547/1547, BOM 1553/1553 +format: 9648/9731 (99.15%) +all checks: 45692/45778 (99.81%) +not run: 2: Prettier's output is another value: it drops the blanks at the end of a block scalar (prettier#19764) not run: 3: `babel` rejects HTML-like comments, but the snapshots of js/comments/html-like and of jsx/jsx-test-suite, made with `acorn`, have them formatted not run: 2: an input that Prettier's `typescript` parser rejects: the snapshot is made with `babel-ts` not run: 4: an input that only `babel-ts` rejects: Prettier's `typescript` parser accepts it, and the output is the same diff --git a/test/cli/format/prettier/sync.ts b/test/cli/format/prettier/sync.ts index 7e39eac57512..103919998551 100644 --- a/test/cli/format/prettier/sync.ts +++ b/test/cli/format/prettier/sync.ts @@ -1,4 +1,4 @@ -// Collects Prettier's fixtures and snapshots in `bundle.zst`. +// Collects Prettier's fixtures and snapshots into `bundle.zst`. // // bun test/cli/format/prettier/sync.ts // bun test/cli/format/prettier/sync.ts --extract @@ -11,9 +11,9 @@ import { collect, extract, writeBundle } from "../bundle.ts"; const languages = ["js", "jsx", "typescript", "flow", "json", "css", "less", "scss", "graphql", "yaml", "markdown", "mdx", "handlebars", "html", "vue", "angular", "lwc", "mjml", "misc"]; const ours = ["babel", "typescript", "json", "json5", "jsonc", "json-stringify", "css", "less", "scss", "graphql", "yaml", "markdown", "mdx", "glimmer", "html", "vue", "angular", "lwc", "mjml"]; -/** The parsers that count in the tests of a directory. `flow` only where it is the first: elsewhere `babel` stands for it. */ +/** The parsers that are tested in a directory. `flow` only where it's the first one: elsewhere `babel` covers it. */ const parsersIn = (directory: string) => [...ours, ...(directory.startsWith("flow/") ? ["flow", "babel-flow"] : [])]; -/** The name of a file that is parsed with the parser. */ +/** Returns a file name that selects `parser`. */ const fileFor = (parser: string, name: string) => parser === "json-stringify" ? `${name}/package.json` @@ -23,10 +23,11 @@ type Snippet = string | { name?: string; code: string; output?: string; filename type Options = { errors?: true | Record } & Record; /** - * What is in a `format.test.js` and in no snapshot: the expected output of a snippet, if it is next to the input, and the text of a snippet - * that is rejected, and the name of a file that a snippet is given. The tests are run here with a `runFormatTest` that takes notes. They are - * written as the other fixtures are: in `inline-outputs` next to the test a snapshot file, in `rejected-snippets` the inputs and a snapshot - * file. The names are in `snippet-filenames.txt`: the name of the snippet, a tab, the name of the file. + * Adds the data that's only in a `format.test.js` and not in any snapshot: a snippet's expected output if it's written + * next to the input, the text of a rejected snippet, and the file name given to a snippet. The tests are run here with + * a `runFormatTest` that records its arguments. The results are written in the same format as the other fixtures: a + * snapshot file in `inline-outputs` next to the test, and the inputs plus a snapshot file in `rejected-snippets`. The + * file names are written to `snippet-filenames.txt`, one per line: the snippet's name, a tab, the file name. */ async function addFromTests(root: string, files: Map) { const prettier = { getSupportInfo: async () => ({ options: [{ name: "parser", choices: ours.map(value => ({ value })) }] }) }; @@ -48,7 +49,7 @@ async function addFromTests(root: string, files: Map) { for (const parser of parsers.filter(it => parsersIn(directory).includes(it))) { const list = errors === true || errors[parser]; if (list === true || (Array.isArray(list) && filename !== undefined && list.includes(filename))) { - // The name that the test gives it can be what it is about: `script.cjs`. + // The file name that the test gives it can be the point of the test: `script.cjs`. const file = filename === undefined ? fileFor(parser, String(counts.size)) : `${counts.size}/${filename}`; counts.set(file, 1); files.set(`${directory}/rejected-snippets/${file}`, Buffer.from(code)); @@ -57,7 +58,7 @@ async function addFromTests(root: string, files: Map) { } if (filename !== undefined) filenames.add(`${name}\t${filename}\n`); if (output === undefined) return; - // The output is the same for all of them. The first of each language stands for the others. + // The output is the same for all of them, so the first parser of each language represents the others. const families = new Map(parsers.filter(it => parsersIn(directory).includes(it)).map(it => [/^babel$|^typescript$/.test(it) ? "js" : it, it]).reverse()); for (const parser of [...families.values()].reverse()) { const title = `snippet: ${name}${Object.keys(options).length ? ` - ${JSON.stringify(options)}` : ""} format`; @@ -91,7 +92,7 @@ if (source === "--extract" && rest.length === 2) { console.log(`${extract(bundle, rest[0], rest[1])} files in ${rest[1]}`); } else if (source && source !== "--extract") { const files = new Map(); - // The snapshots say with which options an input is formatted. + // The snapshots record the options that each input is formatted with. for (const language of languages) { collect(join(source, "tests/format"), language, files, name => name === "format.test.js"); } diff --git a/test/cli/format/scripts/generate-es5-identifier-tables.ts b/test/cli/format/scripts/generate-es5-identifier-tables.ts index 22e8d0074672..d982e5e4920a 100644 --- a/test/cli/format/scripts/generate-es5-identifier-tables.ts +++ b/test/cli/format/scripts/generate-es5-identifier-tables.ts @@ -1,5 +1,5 @@ -// Generates src/format/js/utils/es5_identifier_tables.rs from the package that Prettier asks whether the quotes of a key can go, -// and from Bun's own tables of identifiers: only where the two differ is written down. +// Generates src/format/js/utils/es5_identifier_tables.rs from the package that Prettier uses to decide whether a key's +// quotes can be removed, and from Bun's own identifier tables. Only the differences between the two are written. // // cd
// bun > src/format/js/utils/es5_identifier_tables.rs @@ -11,9 +11,9 @@ import { pathToFileURL } from "node:url"; const require = createRequire(pathToFileURL(process.cwd() + "/")); const isEs5IdentifierName = (await import(pathToFileURL(require.resolve("is-es5-identifier-name")).href)).default; -// `is_id_start_es_next` and `is_id_continue_es_next` of src/bun_core/string/identifier.rs. +// `is_id_start_es_next` and `is_id_continue_es_next` in src/bun_core/string/identifier.rs. const identifier = readFileSync(join(import.meta.dir, "../../../../src/bun_core/string/identifier.rs"), "utf8"); -function tableOfBun(module: string): (unit: number) => boolean { +function bunTable(module: string): (unit: number) => boolean { const body = identifier.slice(identifier.indexOf(`mod ${module} {`)); const numbers = (name: string) => { const start = body.indexOf("= &[", body.indexOf(`static ${name}:`)); @@ -26,8 +26,8 @@ function tableOfBun(module: string): (unit: number) => boolean { return ((stage2[bit >> 6] >> BigInt(bit & 63)) & 1n) === 1n; }; } -const isStartForBun = tableOfBun("id_start_es_next"); -const isContinueForBun = tableOfBun("id_continue_es_next"); +const isStartForBun = bunTable("id_start_es_next"); +const isContinueForBun = bunTable("id_continue_es_next"); // `bun_core::lexer::is_type_script_identifier_part` const isPartForBun = (unit: number) => isContinueForBun(unit) || unit === 0x30fb || unit === 0xff65; @@ -45,13 +45,13 @@ function ranges(test: (unit: number) => boolean): [number, number][] { const isStart = (unit: number) => isEs5IdentifierName(String.fromCharCode(unit)); const isPart = (unit: number) => isEs5IdentifierName("a" + String.fromCharCode(unit)); const tables: [string, string, [number, number][]][] = [ - ["START_LESS", "What a name can start with for Bun and not for the package.", ranges(it => isStartForBun(it) && !isStart(it))], - ["START_MORE", "What a name can start with for the package and not for Bun.", ranges(it => !isStartForBun(it) && isStart(it))], - ["PART_LESS", "What can be in a name after its first character for Bun and not for the package.", ranges(it => isPartForBun(it) && !isPart(it))], - ["PART_MORE", "What can be in a name after its first character for the package and not for Bun.", ranges(it => !isPartForBun(it) && isPart(it))], + ["START_LESS", "Characters that can start a name in Bun but not in the package.", ranges(it => isStartForBun(it) && !isStart(it))], + ["START_MORE", "Characters that can start a name in the package but not in Bun.", ranges(it => !isStartForBun(it) && isStart(it))], + ["PART_LESS", "Characters that can follow a name's first character in Bun but not in the package.", ranges(it => isPartForBun(it) && !isPart(it))], + ["PART_MORE", "Characters that can follow a name's first character in the package but not in Bun.", ranges(it => !isPartForBun(it) && isPart(it))], ]; -let out = `//! Generated by test/cli/format/scripts/generate-es5-identifier-tables.ts. Where the package \`is-es5-identifier-name\` and\n//! \`bun_core::lexer::is_identifier_start\` / \`is_type_script_identifier_part\` differ, from U+0080 to U+FFFF, as sorted,\n//! inclusive ranges. The package takes nothing outside of the BMP.\n`; +let out = `//! Generated by test/cli/format/scripts/generate-es5-identifier-tables.ts. The differences between the\n//! \`is-es5-identifier-name\` package and \`bun_core::lexer::is_identifier_start\` / \`is_type_script_identifier_part\`, from\n//! U+0080 to U+FFFF, as sorted, inclusive ranges. The package rejects everything outside the BMP.\n`; for (const [name, doc, table] of tables) { out += `\n/// ${doc}\npub(super) const ${name}: &[(u16, u16)] = &[\n`; for (const [start, end] of table) out += ` (0x${start.toString(16).toUpperCase()}, 0x${end.toString(16).toUpperCase()}),\n`; diff --git a/test/cli/format/scripts/generate-width-tables.ts b/test/cli/format/scripts/generate-width-tables.ts index 3cc35cf270b5..3080ea27db91 100644 --- a/test/cli/format/scripts/generate-width-tables.ts +++ b/test/cli/format/scripts/generate-width-tables.ts @@ -2,6 +2,8 @@ // // cd // bun > src/format/ir/width_tables.rs +// +// `OXFMT_ZERO_WIDTH` at the end of that file isn't generated. It was measured with oxfmt, so copy it over by hand. import { createRequire } from "node:module"; import { pathToFileURL } from "node:url"; @@ -33,7 +35,7 @@ const matchesWhole = (regex: RegExp, text: string) => { const tables: [string, string, [number, number][]][] = [ ["WIDE", "East Asian Width is `W` or `F`.", ranges(c => isFullwidth(c) || isWide(c))], ["EMOJI", "`emoji-regex` matches the character by itself.", ranges(c => matchesWhole(emojiRegex(), String.fromCodePoint(c)))], - ["NARROW_EMOJI", "An emoji that takes one column by itself.", ranges(c => isNarrowEmojiCharacter(String.fromCodePoint(c)))], + ["NARROW_EMOJI", "An emoji that's one column wide by itself.", ranges(c => isNarrowEmojiCharacter(String.fromCodePoint(c)))], [ "EMOJI_MODIFIER_BASE", "`emoji-regex` matches the character with a skin tone after it as one emoji.", diff --git a/test/cli/format/sort-imports.test.ts b/test/cli/format/sort-imports.test.ts index 2e57c1a7b64f..8a4eb72a7f1a 100644 --- a/test/cli/format/sort-imports.test.ts +++ b/test/cli/format/sort-imports.test.ts @@ -35,7 +35,104 @@ async function format(files: Record, args: string[] = []) { const bunfig = { "bunfig.toml": "[fmt]\nsortImports = true\n" }; +// oxfmt 0.72.0 moves each of these down with `z`. TypeScript, Flow and Bun only read a pragma that comes before all +// code, and a linter applies `eslint-disable` from its position onward. +const fileComments = [ + "// @ts-nocheck", + "// @ts-check", + '/// ', + '/// ', + '/// ', + "/* eslint-disable */", + "/* eslint no-console: 0 */", + "// oxlint-disable", + "// biome-ignore-all lint: x", + "// @flow", + "/** @jsxImportSource preact */", + "/** @jsx h */", + "/** @format */", + "/** @noprettier */", + "// @bun", + "// Copyright 2026 Someone. MIT license.", + "// SPDX-License-Identifier: MIT", + "/* @license MIT */", + "/*! x 1.0 */", + "/** @jest-environment jsdom */", + "// @vitest-environment happy-dom", + "/** @file What the file is for. */", + "/** @fileoverview What the file is for. */", + "/** @overview What the file is for. */", + "/** @module x */", + "/** @packageDocumentation */", + "// deno-lint-ignore-file", + "// deno-fmt-ignore-file", + "// dprint-ignore-file", +]; +const unsorted = `import z from "z";\nimport a from "a";\n`; +const sorted = `import a from "a";\nimport z from "z";\n`; + const cases: [name: string, input: string, output: string][] = [ + ...fileComments.map((comment): [string, string, string] => [ + `keeps ${comment} above the imports`, + `${comment}\n${unsorted}`, + `${comment}\n${sorted}`, + ]), + [ + "keeps a comment about the file above the imports after a shebang", + `#!/usr/bin/env bun\n// @ts-nocheck\n${unsorted}`, + `#!/usr/bin/env bun\n// @ts-nocheck\n${sorted}`, + ], + [ + "keeps a comment about the file above the imports after a directive", + `"use client";\n/* eslint-disable */\n${unsorted}`, + `"use client";\n/* eslint-disable */\n${sorted}`, + ], + [ + "keeps every comment above a comment about the file", + `// Copyright 2026 Someone.\n// See the file LICENSE.\n// @ts-check\n${unsorted}`, + `// Copyright 2026 Someone.\n// See the file LICENSE.\n// @ts-check\n${sorted}`, + ], + ["changes nothing if the first import stays first", `// @ts-nocheck\n${sorted}`, `// @ts-nocheck\n${sorted}`], + [ + "moves a comment about the first import with it", + `// about z\n${unsorted}`, + `import a from "a";\n// about z\nimport z from "z";\n`, + ], + [ + "moves a comment about the first import with it, below a comment about the file", + `// @ts-nocheck\n// about z\n${unsorted}`, + `// @ts-nocheck\nimport a from "a";\n// about z\nimport z from "z";\n`, + ], + [ + "moves @ts-expect-error with the first import", + `// @ts-expect-error\n${unsorted}`, + `import a from "a";\n// @ts-expect-error\nimport z from "z";\n`, + ], + [ + "moves @ts-ignore with the first import", + `// @ts-ignore\n${unsorted}`, + `import a from "a";\n// @ts-ignore\nimport z from "z";\n`, + ], + [ + "moves eslint-disable-next-line with the first import", + `// eslint-disable-next-line no-restricted-imports\n${unsorted}`, + `import a from "a";\n// eslint-disable-next-line no-restricted-imports\nimport z from "z";\n`, + ], + [ + "doesn't mistake a package name for a pragma", + `// the types are in @bun/types\n${unsorted}`, + `import a from "a";\n// the types are in @bun/types\nimport z from "z";\n`, + ], + [ + "doesn't mistake @jest/globals for a pragma", + `// the mocks are in @jest/globals\n${unsorted}`, + `import a from "a";\n// the mocks are in @jest/globals\nimport z from "z";\n`, + ], + [ + "moves deno-lint-ignore with the first import", + `// deno-lint-ignore no-explicit-any\n${unsorted}`, + `import a from "a";\n// deno-lint-ignore no-explicit-any\nimport z from "z";\n`, + ], [ "sorts names case-insensitively, with numbers in natural order, ignoring inline `type`", `import { b, a, C, a10, a2, type T, type d, _e, $f } from "x"; @@ -761,6 +858,28 @@ describe.concurrent("sortImports sources", () => { expect(flag.files["a.ts"]).toBe(tidy); }); + test("a comment about the file stays above the imports, however sorting is turned on", async () => { + const files = { "a.ts": `// @ts-nocheck\n${unsorted}` }; + const results = await Promise.all([ + format({ ...bunfig, ...files }), + format({ "bunfig.toml": "[fmt.sortImports]\nnewlinesBetween = false\n", ...files }), + format(files, ["--sort-imports"]), + format({ ".oxfmtrc.json": `{ "sortImports": true }`, ...files }), + ]); + for (const result of results) { + expect(result.files["a.ts"]).toBe(`// @ts-nocheck\n${sorted}`); + expect(result.second.files).toEqual(result.files); + } + }); + + test("a Flow file is still a Flow file after its imports are sorted", async () => { + const code = (imports: string) => + `// @flow\n${imports}export function f(x: ?number): %checks {\n return !!x;\n}\n`; + const result = await format({ ...bunfig, "a.js": code(unsorted) }); + expect(result).toMatchObject({ stderr: "", exitCode: 0, files: { "a.js": code(sorted) } }); + expect(result.second).toMatchObject({ stderr: "", exitCode: 0, files: { "a.js": code(sorted) } }); + }); + test("sortSideEffects = true lets side-effect imports move", async () => { const result = await format({ "bunfig.toml": "[fmt.sortImports]\nsortSideEffects = true\n", "a.ts": input }); expect(result.files["a.ts"]).toBe( diff --git a/test/cli/format/sort-imports/sort-imports.test.ts b/test/cli/format/sort-imports/sort-imports.test.ts index 84d9932154a3..dca98673c4df 100644 --- a/test/cli/format/sort-imports/sort-imports.test.ts +++ b/test/cli/format/sort-imports/sort-imports.test.ts @@ -1,8 +1,7 @@ -// The fixtures are the inputs of the tests of @trivago/prettier-plugin-sort-imports, of -// @ianvs/prettier-plugin-sort-imports (both Apache-2.0) and of oxc's formatter (MIT), and generated ones with comments -// and empty lines in odd places. What is expected is what Prettier 3.9.9 with the plugin (for -// prettier-plugin-organize-imports, with TypeScript 5.9), and oxfmt 0.72, print. -// They are made by test/cli/format/oracle/sort-imports/make-fixtures.mjs. +// The fixtures are the test inputs of @trivago/prettier-plugin-sort-imports, @ianvs/prettier-plugin-sort-imports (both +// Apache-2.0) and oxc's formatter (MIT), plus generated ones with comments and empty lines in odd places. The expected +// output comes from Prettier 3.9.9 with the plugin (for prettier-plugin-organize-imports, with TypeScript 5.9) and from +// oxfmt 0.72. test/cli/format/oracle/sort-imports/make-fixtures.mjs generates them. import { afterAll, describe, expect, test } from "bun:test"; import { bunEnv, bunExe, tempDir } from "harness"; import { readFileSync } from "node:fs"; @@ -37,7 +36,10 @@ async function format(files: Record, names: string[], flags: str } for (const [tool, config] of Object.entries(tools)) { - const cases: Case[] = JSON.parse(readFileSync(join(import.meta.dir, `${tool}.json`), "utf8")); + const recorded: Case[] = JSON.parse(readFileSync(join(import.meta.dir, `${tool}.json`), "utf8")); + // Where @trivago's plugin puts a module whose name is a hexadecimal number depends on its original position, and a + // second run moves it again. `bun fmt` always puts it in the same position. + const cases = recorded.filter(it => tool !== "trivago" || !/from (["']) *0x[0-9a-f]+ *\1/i.test(it.input)); // One run for all the cases with the same options. const groups = Map.groupBy(cases, it => JSON.stringify(it.options)); @@ -58,10 +60,10 @@ for (const [tool, config] of Object.entries(tools)) { }); } -// hosts.json: scripts in Vue files, in HTML, in HTML in templates and in blocks of code, with what the tools print. The plugins -// sort the first `\n\n

a

\n\n\n"; for (const text of [parts, `\n${parts}`]) { expect((await format({ ...config({ insertPragma: true }), "a.svelte": text }, ["a.svelte"])).files).toEqual([ @@ -509,20 +548,21 @@ exports.format = async text => "\\n" + text; } }); - // The text, what Bun makes of it, and what the plugin makes of it, which is another component, or none. + // Each row is a label, the text, Bun's output and the plugin's output, which is a different component or not a valid + // one. test.each([ ["a quote in single quotes", `\n`, `\n`, `\n`], - ["an element that is void to Svelte and not to the plugin", "\n", "\n", "\n"], - ["a comment behind an expression", "{a /* b */}\n", "{a /* b */}\n", "{a}\n"], + ["an element that's void in Svelte but not in the plugin", "\n", "\n", "\n"], + ["a comment after an expression", "{a /* b */}\n", "{a /* b */}\n", "{a}\n"], ["a comment before a parenthesis", "{/* b */ (a)}\n", "{/* b */ a}\n", "{a}\n"], - ["a comment up to the end of the line", "{a + b // c\n}\n", "{a + b // c\n}\n", "{a + b}\n"], + ["a line comment", "{a + b // c\n}\n", "{a + b // c\n}\n", "{a + b}\n"], [ "a comment in the value of an attribute", "

\n", "

\n", "

\n", ], - ["the same where the value is the name", "

\n", "

\n", "

\n"], + ["a comment where the value is the name", "

\n", "

\n", "

\n"], [ "the key of a property with a default", "{#each a as { b: c = 1 }}{c}{/each}\n", @@ -530,19 +570,19 @@ exports.format = async text => "\\n" + text; "{#each a as { c = 1 }}{c}{/each}\n", ], [ - "a computed key that is the name", + "a computed key equal to the name", "{#each a as { [b]: b }}{b}{/each}\n", "{#each a as { [b]: b }}{b}{/each}\n", "{#each a as { b }}{b}{/each}\n", ], [ - "a key that is a string, before a pattern", + "a string key before a pattern", `{#each a as { "b": { c } }}{c}{/each}\n`, `{#each a as { "b": { c } }}{c}{/each}\n`, "{#each a as { undefined: { c } }}{c}{/each}\n", ], - ])("what the plugin damages is printed right: %s", async (_, before, after, ofPlugin) => { - expect(after).not.toBe(ofPlugin); + ])("prints correctly what the plugin breaks: %s", async (_, before, after, byPlugin) => { + expect(after).not.toBe(byPlugin); for (const config of [{}, { ".prettierrc": prettierrc }, { ".oxfmtrc.json": oxfmtrc }]) { const result = await format({ ...config, "a.svelte": before, "b.svelte": after }, ["a.svelte", "b.svelte"]); expect(result).toMatchObject({ stderr: "", files: [after, after], exitCode: 0 }); @@ -551,7 +591,7 @@ exports.format = async text => "\\n" + text; } }); - // The same for a comment at every place where there is an expression or a pattern. + // The same for a comment everywhere an expression or a pattern can appear. const comments = [ ["{#if a /* b */}c{/if}\n", "{#if a /* b */}c{/if}\n", "{#if a}c{/if}\n"], ["{#if a}c{:else if d /* b */}e{/if}\n", "{#if a}c{:else if d /* b */}e{/if}\n", "{#if a}c{:else if d}e{/if}\n"], @@ -610,27 +650,28 @@ exports.format = async text => "\\n" + text; "\n", "\n", ], - // One without a letter. + // A comment without a letter. ["{a /* 1 */}\n", "{a /* 1 */}\n", "{a}\n"], ["{#if a /* 1 */}c{/if}\n", "{#if a /* 1 */}c{/if}\n", "{#if a}c{/if}\n"], - // What follows a `//` has to be on the next line. The plugin has some of it before the comment, which is text then. + // Whatever follows a `//` has to go on the next line. The plugin moves some of it before the comment, which then + // becomes text. ["{#if a // b\n}c{/if}\n", "{#if a // b\n}c{/if}\n", "{#if a}c{/if}\n"], ["{#if a // b\n && c}d{/if}\n", "{#if a && // b\n c}d{/if}\n", "{#if a && c}d{/if} // b\n"], ["{#key a(c, // b\n d)}e{/key}\n", "{#key a(\n c, // b\n d,\n)}e{/key}\n", "{#key a(c, d)}e{/key} // b\n"], ["{#each a // b\n as c}d{/each}\n", "{#each a // b\n as c}d{/each}\n", "{#each a as c}d{/each}\n"], ["{@const a = c // b\n}\n", "{@const a = c // b\n}\n", "{@const a = c} // b\n"], - // So has what follows one that is on a line of its own. + // So does whatever follows a comment on its own line. ["{a // b\n/* c */\n}\n", "{a // b\n/* c */\n}\n", "{a}\n"], ["{a\n/* c */\n}\n", "{a\n/* c */\n}\n", "{a}\n"], ["{#if a\n/* c */\n}d{/if}\n", "{#if a\n/* c */\n}d{/if}\n", "{#if a}d{/if}\n"], ["

c

\n", "\n c\n

\n", "

c

\n"], ]; test.each([[{}], [{ ".prettierrc": prettierrc }], [{ ".oxfmtrc.json": oxfmtrc }]])( - "no comment is lost: %j", + "doesn't lose any comment: %j", async config => { const names = comments.map((_, index) => `${index}.svelte`); const files = (which: number) => Object.fromEntries(comments.map((it, index) => [names[index], it[which]])); - for (const [, after, ofPlugin] of comments) expect(after).not.toBe(ofPlugin); + for (const [, after, byPlugin] of comments) expect(after).not.toBe(byPlugin); const expected = { stderr: "", files: comments.map(it => it[1]), exitCode: 0 }; expect(await format({ ...config, ...files(0) }, names)).toMatchObject(expected); expect(await format({ ...config, ...files(1) }, names)).toMatchObject(expected); @@ -639,10 +680,11 @@ exports.format = async text => "\\n" + text; }, ); - // By what is wrong with the plugin: the text, what Bun makes of it, and what the plugin makes of it. `null`: it refuses it. - // `false`: `--debug-check` has nothing to say about that, which has more white space where there is some, or a parenthesis. + // Keyed by the plugin's bug. Each row is the text, Bun's output and the plugin's output, or `null` if the plugin + // rejects the text. `false` means `--debug-check` accepts the plugin's output, which only has more whitespace where + // there's already some, or a parenthesis. const damaged: Record = { - "scripts and style sheets are where the parser finds them": [ + "finds scripts and style sheets where the parser does": [ [ "\n\n

{b}

\n\n", "\n\n\n\n

{b}

\n\n\n", @@ -708,7 +750,7 @@ exports.format = async text => "\\n" + text; ], ['\n', '\n', null], ], - "a comment next to a script takes nothing with it": [ + "a comment next to a script doesn't remove its neighbors": [ [ "\n
kept
\n", "\n\n\n
kept
\n", @@ -730,7 +772,7 @@ exports.format = async text => "\\n" + text; "\n\n\n\n

first

\n", ], ], - "white space that is text stays": [ + "keeps significant whitespace": [ ["
y
\nsome words\n", "
y
\nsome words\n", "
y
\nsomewords\n"], [ '
\n', @@ -748,13 +790,13 @@ exports.format = async text => "\\n" + text; ["y c\n", "\n\ny c\n", "\n\nyc\n"], ["\u00A0b\n", "\u00A0b\n", "b\n"], ["\u2028b\n", "\u2028b\n", "b\n"], - // At the end of the file it would be nothing to Svelte, which has `trimEnd()`. + // At the end of the file, Svelte would drop it with `trimEnd()`. ["b\u00A0\n", "\n\nb \n", "\n\nb\u00A0\n"], ["b\u2028\n", "\n\nb
\n", "\n\nb\u2028\n"], ["b\u00A0\n", "b\u00A0\n\n\n", null], // At the start of the file it would be a byte order mark. ["\n\uFEFFb\n", "b\n", "b\n"], - // What goes with a comment that goes with a script. + // Whitespace next to a comment that moves with its script. [ "b\nc\n", "\n\n\nb c\n", @@ -794,7 +836,7 @@ exports.format = async text => "\\n" + text; ["\n", "\n", "\n"], ["
\n\n
\n", "
\n\n
\n", "
\n"],
     ],
-    "what is ignored is there once, and is the same with every run": [
+    "prettier-ignored content is printed once and is stable across runs": [
       [
         "\nwords\n\n

behind

\n", "\nwords\n

behind

\n\n\n", @@ -836,7 +878,7 @@ exports.format = async text => "\\n" + text; false, ], ], - "comments in a start tag": [ + "keeps comments in a start tag": [ ["
y
\n", "
y
\n", "
y
\n"], ["\n", "\n", "\n"], [' z\n>y
\n', ' z\n>\n y\n
\n', '
y
\n'], @@ -845,7 +887,7 @@ exports.format = async text => "\\n" + text; ['
y
\n', 'y
\n', 'y
// d\n'], ["y\n", "y\n", "y\n"], ], - "what is written is not left out": [ + "doesn't drop parts of the source": [ [ 'y\n', 'y\n', @@ -861,12 +903,12 @@ exports.format = async text => "\\n" + text; ["{#await b}c{:catch d} {/await}\n", "{#await b}c{:catch d}{/await}\n", "{#await b}c{/await}\n"], ["{#await b catch d}{/await}\n", "{#await b catch d}{/await}\n", "{#await b}{/await}\n"], ], - "what is printed can be parsed": [ + "prints output that can be parsed": [ ["{(/b/).test(c)}\n", "{(/b/.test(c))}\n", "{/b/.test(c)}\n"], ["{(/b/g)}\n", "{(/b/g)}\n", "{/b/g}\n"], - // One that is printed as it is written, because it has no such flag. + // This regex is printed verbatim, because `c` isn't a valid flag. ["{(/b/c)}\n", "{(/b/c)}\n", "{/b/c}\n"], - // To Svelte this says that the markup is TypeScript, to the plugin it does not. + // For Svelte this makes the markup TypeScript. For the plugin it doesn't. [ '\n\n{f(a)}\n', '\n\n{f(a)}\n', @@ -884,7 +926,7 @@ exports.format = async text => "\\n" + text; ], ["{#each b=1}y{/each}\n", "{#each b = 1}y{/each}\n", "{#each (b = 1)}y{/each}\n"], ], - "a default that the plugin throws for": [ + "formats a default value that makes the plugin throw": [ ["{#each b as { c = -1 }}{c}{/each}\n", "{#each b as { c = -1 }}{c}{/each}\n", null], ["{#each b as { c = d() }}{c}{/each}\n", "{#each b as { c = d() }}{c}{/each}\n", null], ["{#each b as [c = d.e, f = !g]}{c}{/each}\n", "{#each b as [c = d.e, f = !g]}{c}{/each}\n", null], @@ -899,10 +941,10 @@ exports.format = async text => "\\n" + text; ], }; const typescript = '\n\n'; - // By what Svelte is strict about: the text, what Bun makes of it, and what must not become of it, which Svelte refuses or - // reads as something else. `null`: nothing in particular. + // Keyed by the rule that Svelte is strict about. Each row is the text, Bun's output, and an output that must not be + // produced because Svelte rejects it or reads it differently, or `null` if there's none in particular. const strict: typeof damaged = { - "no comment is behind a declaration": [ + "never puts a comment after a declaration": [ ["{const sum = (b // c\n)}\n", "{const sum = (b // c\n)}\n", "{const sum =\n b // c\n}\n"], ["{const sum = // c\n 1}\n", "{const sum = // c\n 1}\n", "{const sum = 1 // c\n}\n"], ["{let sum = (b /* c */)}\n", "{let sum = (b /* c */)}\n", "{let sum = b /* c */}\n"], @@ -913,10 +955,10 @@ exports.format = async text => "\\n" + text; `${typescript}{const sum = b as C[/* d */]}\n`, `${typescript}{const sum = b as C[] /* d */}\n`, ], - // This one stays where it is: something follows it that does not close anything. + // This comment can stay where it is, because it's followed by something other than a closing bracket. ["{const sum = [1 /* c */,2]}\n", "{const sum = [1 /* c */, 2]}\n", null], ], - "no comment is behind the expression of an each block without `as`": [ + "never puts a comment after the expression of an each block without `as`": [ ["{#each rows[0 // c\n]}y{/each}\n", "{#each rows[0 // c\n]}y{/each}\n", "{#each rows[0] // c\n}y{/each}\n"], [ "{#each rows[0 // c\n], i}y{/each}\n", @@ -926,7 +968,7 @@ exports.format = async text => "\\n" + text; ["{#each b + (c /* d */)}y{/each}\n", "{#each b + (c /* d */)}y{/each}\n", "{#each b + c /* d */}y{/each}\n"], ["{#each f(b /* c */)}y{/each}\n", "{#each f(b /* c */)}y{/each}\n", null], ], - "an each block without `as` gets none": [ + "never adds an `as` to an each block without one": [ [ `${typescript}{#each (b: C) => (b as D)}y{/each}\n`, `${typescript}{#each (b: C) => (b as D)}y{/each}\n`, @@ -937,14 +979,14 @@ exports.format = async text => "\\n" + text; `${typescript}{#each b = (c as D), i}y{/each}\n`, `${typescript}{#each b = c as D, i}y{/each}\n`, ], - // With one of its own, the last is that. + // If the block has its own `as`, that's the last one. [ `${typescript}{#each (b: C) => (b as D) as e}y{/each}\n`, `${typescript}{#each (b: C) => b as D as e}y{/each}\n`, null, ], ], - "no comment is behind the name of a snippet": [ + "never puts a comment after a snippet's name": [ [ "{#snippet row(/* c */\n b)}y{/snippet}\n", "{#snippet row(/* c */\n b)}y{/snippet}\n", @@ -955,14 +997,14 @@ exports.format = async text => "\\n" + text; `${typescript}{#snippet row(b: T)}y{/snippet}\n`, `${typescript}{#snippet row /* c */(b: T)}y{/snippet}\n`, ], - // The line ends behind another comment. + // The line ends after another comment. [ "{#snippet row(/* c */ // d\n b)}y{/snippet}\n", "{#snippet row(/* c */ // d\n b)}y{/snippet}\n", "{#snippet row /* c */( // d\n b,\n)}y{/snippet}\n", ], ["{#snippet row(b /* c */)}y{/snippet}\n", "{#snippet row(b /* c */)}y{/snippet}\n", null], - // On a line of its own it is printed before the parameter. + // A comment on its own line is printed before the parameter. ["{#snippet row(\n /* c */\n b)}y{/snippet}\n", "{#snippet row(\n /* c */\n b,\n)}y{/snippet}\n", null], [ "{#snippet row(\n /** c */\n b, d)}y{/snippet}\n", @@ -975,8 +1017,8 @@ exports.format = async text => "\\n" + text; null, ], ], - "no comment is behind the parameters of a snippet": [ - // The only parameter is a pattern, so no line ends before the `)`. + "never puts a comment after a snippet's parameters": [ + // The only parameter is a pattern, so there's no line break before the `)`. [ "{#snippet row({ b } // c\n = {})}y{/snippet}\n", "{#snippet row({ b } // c\n = {})}y{/snippet}\n", @@ -997,13 +1039,13 @@ exports.format = async text => "\\n" + text; `${typescript}{#snippet row({ b }: D[E // c\n])}y{/snippet}\n`, `${typescript}{#snippet row({\n b,\n}: D[E]) // c\n}y{/snippet}\n`, ], - // With a second one there is a line for it. + // With a second parameter, there's a line break for the comment. [ "{#snippet row(\n { b } = {}, // c\n d,\n)}y{/snippet}\n", "{#snippet row(\n { b } = {}, // c\n d,\n)}y{/snippet}\n", null, ], - // So there is behind the parameter, which is not hugged then, and between its brackets and braces. + // There's also one after the parameter, which isn't hugged then, and between its brackets or braces. ["{#snippet row({ b } // c\n)}y{/snippet}\n", "{#snippet row(\n { b }, // c\n)}y{/snippet}\n", null], [ "{#snippet row({\n id, // the id\n name,\n})}\n

y

\n{/snippet}\n", @@ -1026,7 +1068,7 @@ exports.format = async text => "\\n" + text; null, ], ], - "a comment that Prettier moves each time stays where it is in the head of a snippet": [ + "a comment that Prettier moves on every run stays put in a snippet's head": [ [ `${typescript}{#snippet row(b = // c\n(d as E).f)}y{/snippet}\n`, `${typescript}{#snippet row(b = // c\n(d as E).f)}y{/snippet}\n`, @@ -1037,7 +1079,7 @@ exports.format = async text => "\\n" + text; `${typescript}{#snippet row({ b = // c\n(d as E)[0] })}y{/snippet}\n`, null, ], - // These it does not move. + // Prettier doesn't move these. ["{#snippet row(b = // c\n (1))}y{/snippet}\n", "{#snippet row(\n b = 1, // c\n)}y{/snippet}\n", null], [ "{#snippet row(b = c == // d\n (1))}y{/snippet}\n", @@ -1045,7 +1087,7 @@ exports.format = async text => "\\n" + text; null, ], ], - "a vertical tab next to a comment is white space": [ + "a vertical tab next to a comment is whitespace": [ [ "{#snippet row(b\v/* c */)}y{/snippet}\n", "{#snippet row(b /* c */)}y{/snippet}\n", @@ -1062,8 +1104,8 @@ exports.format = async text => "\\n" + text; "{#if b}{@const c /* d */ = e}{/if}\n", ], ], - "a `{:then}` with nothing in it stays if there is a comment in its head": [ - // What the plugin prints is the third. + "keeps an empty `{:then}` if there's a comment in its head": [ + // The third column is the plugin's output. [ "{#await b}wait{:then { c /* d */ }}{/await}\n", "{#await b}wait{:then { c /* d */ }}{/await}\n", @@ -1085,7 +1127,7 @@ exports.format = async text => "\\n" + text; `${typescript}{#await b}wait{:then c: E}{/await}\n`, `${typescript}{#await b}wait{/await}\n`, ], - // Without one it goes as before. + // Without a comment it's still removed. ["{#await b}wait{:then c}{/await}\n", "{#await b}wait{/await}\n", null], ["{#await b}wait{:then { c = 1 / 2 }}{/await}\n", "{#await b}wait{/await}\n", null], ["{#await b}wait{:then { c = /d/ }}{/await}\n", "{#await b}wait{/await}\n", null], @@ -1093,14 +1135,14 @@ exports.format = async text => "\\n" + text; ["{#await b then { c = `// d` }}{/await}\n", "{#await b}{/await}\n", null], [`${typescript}{#await b}wait{:then c: "d/e"}{/await}\n`, `${typescript}{#await b}wait{/await}\n`, null], ], - "the parameters of a snippet end where their parentheses do": [ + "a snippet's parameters end at their closing parenthesis": [ [ "{#snippet row(b /* () */)}y{/snippet}\n", "{#snippet row(b /* () */)}y{/snippet}\n", "{#snippet row(b /* ()}y{/snippet}\n", ], ], - "a comment before a type": [ + "keeps a comment before a type": [ [ `${typescript}{#each rows as row : /* c */ T}y{/each}\n`, `${typescript}{#each rows as row: /* c */ T}y{/each}\n`, @@ -1114,7 +1156,7 @@ exports.format = async text => "\\n" + text; [ `${typescript}{#each rows as { b } : /* c */ T}y{/each}\n`, `${typescript}{#each rows as { b }: /* c */ T}y{/each}\n`, - // What the plugin prints. + // This is what the plugin prints. `${typescript}{#each rows as { b }: T}y{/each}\n`, ], [ @@ -1128,11 +1170,11 @@ exports.format = async text => "\\n" + text; `${typescript}{#await b}y{:then row : /* c */: T}z{:catch e : /* d */: U}w{/await}\n`, ], ], - "the string of `this` keeps its quotes": [ + "a string in `this` keeps its quotes": [ [ "y\n", "y\n", - // What the plugin prints. + // This is what the plugin prints. 'y\n', ], [ @@ -1146,7 +1188,7 @@ exports.format = async text => "\\n" + text; 'y\n', ], ["y\n", 'y\n', null], - // Not right behind the `{`, the plugin makes a text of the string. + // If the string isn't right after the `{`, the plugin turns it into text. ["y\n", 'y\n', null], [ "y\n", @@ -1163,7 +1205,7 @@ exports.format = async text => "\\n" + text; "y\n", 'y\n', ], - // One backslash in the string would be two in the text, and an entity in the text is none in the string. + // One backslash in the string would be two in the text, and an entity in the text isn't one in the string. [ 'y\n', 'y\n', @@ -1175,8 +1217,8 @@ exports.format = async text => "\\n" + text; 'y\n', ], ], - "a value with a comment in it is not left out": [ - // What the plugin prints is the third. + "doesn't use the shorthand for a value with a comment in it": [ + // The third column is the plugin's output. ["\n", "\n", "\n"], [ "\n", @@ -1197,20 +1239,20 @@ exports.format = async text => "\\n" + text; 'y\n', 'y\n', ], - // The parentheses go, the comment does not go with them the next time. + // The parentheses are removed, and the next run doesn't remove the comment. ["\n", "\n", "\n"], - // Without a comment it is left out as before. + // Without a comment, the shorthand is still used. ["\n", "\n", null], ], - "a declaration ends behind its `;`": [ + "a declaration ends after its `;`": [ ["{const sum = 1;}\n", "{const sum = 1}\n", null], ["{let sum ;}\n", "{let sum}\n", null], ], - "a script that is not code stays as it is": [ + "leaves a script that isn't code unchanged": [ [ '\n', '\n', - // What the plugin prints: it is JSX. + // This is what the plugin prints, because it parses as JSX. '\n', false, ], @@ -1219,7 +1261,7 @@ exports.format = async text => "\\n" + text; '
\n \n
\n', null, ], - // Whether it can be read as JavaScript or not. + // Whether or not it parses as JavaScript. [ '\n', '\n', @@ -1287,7 +1329,7 @@ exports.format = async text => "\\n" + text; `\n`, null, ]), - // In whatever letters the name of the attribute is written, and as a string between braces. + // The attribute name can be in any case, and the value can be a string in braces. ...['TYPE="math/tex"', 'type={"math/tex"}'].flatMap((type): [string, string, string, false][] => [ [ `\n`, @@ -1302,13 +1344,13 @@ exports.format = async text => "\\n" + text; false, ], ]), - // What another expression gives is not known. + // The value of any other expression is unknown. ...['TYPE="module"', 'type={"module"}', "type={kind}"].map((type): [string, string, null] => [ `

\n`, `

\n \n

\n`, null, ]), - // A `lang` counts for more. + // A `lang` takes precedence. [ '\n', '\n', @@ -1320,7 +1362,7 @@ exports.format = async text => "\\n" + text; null, ], ], - "a style sheet ends between two rules": [ + "a `` in a string, a comment or `url()` doesn't end the style sheet": [ [ '"}\n', '";\n }\n\n', @@ -1356,14 +1398,14 @@ exports.format = async text => "\\n" + text; expect(checked).toMatchObject({ stderr: "", files: rows.map(it => it[0]), exitCode: 0 }); }); - test.skipIf(!hasRunner)("--debug-check would not let the other pass", async () => { + test.skipIf(!hasRunner)("--debug-check would reject the other output", async () => { const seen = rows.filter(it => it[2] !== null && it[2] !== it[1]); using dir = tempDir("bun-format-svelte", { ...Object.fromEntries( seen.flatMap((it, index) => it.slice(0, 3).map((text, which) => [`${index}.${which}`, text])), ), }); - // Each with what Bun prints, then with what the plugin prints. + // Each input is paired with Bun's output, then with the other output. const pairs = seen.flatMap((_, index) => [`${index}.0`, `${index}.1`, `${index}.0`, `${index}.2`]); await using proc = spawn({ cmd: [bunExe(), "fmt", "--debug-check-svelte", ...pairs], @@ -1378,11 +1420,11 @@ exports.format = async text => "\\n" + text; }); }); - describe("a comment that waits for the end of the line does not get out of its expression", () => { - // The text, what becomes of it, what becomes of that, which stays, and what must not become of the text: the comment is - // behind the `}` there. Once the parentheses are gone the comment is behind the expression and no longer breaks it, as - // in a file of JavaScript. `null`: these were right before. `false`: `--debug-check` has nothing to say about that, where - // it is a comment in the tag. + describe("a comment deferred to the end of the line stays inside its expression", () => { + // Each row is the text, the first run's output, the second run's output, which is stable, and an output that must + // not be produced because the comment is after the `}` there. Once the parentheses are gone, the comment is after + // the expression and no longer breaks it, as in a JavaScript file. `null` means the case was already correct + // before. `false` means `--debug-check` accepts that output, where it's a comment in the tag. const rows: [string, string, string, string | null, false?][] = [ [ "\n", @@ -1471,7 +1513,7 @@ exports.format = async text => "\\n" + text; expect(checked).toMatchObject({ stderr: "", files: rows.map(it => it[0]), exitCode: 0 }); }); - test.skipIf(!hasRunner)("--debug-check would not let it out", async () => { + test.skipIf(!hasRunner)("--debug-check would reject a comment outside the expression", async () => { const seen = rows.filter(it => it[3] !== null); using dir = tempDir("bun-format-svelte", { ...Object.fromEntries( @@ -1499,8 +1541,8 @@ exports.format = async text => "\\n" + text; }); }); - test("a style sheet ends at the first end tag with a `lang`, or if that is not in a string, a comment or `url()`", async () => { - const refused: [string, string][] = [ + test("a style sheet with a `lang` ends at the first end tag, and otherwise at the first one outside a string, a comment or `url()`", async () => { + const rejected: [string, string][] = [ // A preprocessor cuts it out before Svelte reads it. [ '"}\n', @@ -1511,7 +1553,7 @@ exports.format = async text => "\\n" + text; "\n''\n", "2 | ''\n ^\nerror: This end tag has no start tag\n at 1.svelte:2:5\n\n", ], - // To Svelte this is a comment, to who formats the style sheet it is a selector. + // Svelte reads this as a comment, but the CSS formatter reads it as a selector. [ " -->b{margin:0}\n", "1 | -->b{margin:0}\n" + @@ -1521,12 +1563,12 @@ exports.format = async text => "\\n" + text; "}\n", "1 | }\n ^\nerror: This end tag has no start tag\n at 3.svelte:1:21\n\n", ], - // To Svelte `--c:` is a selector that is not finished. + // Svelte reads `--c:` as an unfinished selector. [ '"}}\n', '1 | "}}\n ^\nerror: This end tag has no start tag\n at 4.svelte:1:29\n\n', ], - // In a string `url(` starts nothing, and with a quote in it `url(..)` is written anew. + // `url(` in a string doesn't start anything, and a `url(..)` with a quote in it isn't kept verbatim. [ ')}\n', '1 | )}\n ^\nerror: This end tag has no start tag\n at 5.svelte:1:38\n\n', @@ -1535,7 +1577,7 @@ exports.format = async text => "\\n" + text; ')}\n', '1 | )}\n ^\nerror: This end tag has no start tag\n at 6.svelte:1:30\n\n', ], - // Neither is `url(..)`. + // Neither of these is `url(..)`. [ ")}\n", "1 | )}\n ^\nerror: This end tag has no start tag\n at 7.svelte:1:25\n\n", @@ -1545,11 +1587,11 @@ exports.format = async text => "\\n" + text; "1 | )}\n ^\nerror: This end tag has no start tag\n at 8.svelte:1:25\n\n", ], ]; - const names = refused.map((_, index) => `${index}.svelte`); - const files = Object.fromEntries(refused.map((it, index) => [names[index], it[0]])); + const names = rejected.map((_, index) => `${index}.svelte`); + const files = Object.fromEntries(rejected.map((it, index) => [names[index], it[0]])); expect(await format(files, names, ["--threads=1"])).toMatchObject({ - stderr: refused.map(it => it[1]).join(""), - files: refused.map(it => it[0]), + stderr: rejected.map(it => it[1]).join(""), + files: rejected.map(it => it[0]), exitCode: 2, }); @@ -1559,7 +1601,7 @@ exports.format = async text => "\\n" + text; '"}\n', '";\n }\n\n', ], - // An apostrophe in a comment of SCSS starts nothing. + // An apostrophe in an SCSS comment doesn't start a string. [ "\n

it's

\n", "

it's

\n\n\n", @@ -1568,13 +1610,14 @@ exports.format = async text => "\\n" + text; "\n", "\n", ], - // What cannot be read stays as it is, up to the first end tag. + // A style sheet that can't be parsed stays unchanged, up to the first end tag. ["\n

y

\n", "

y

\n\n\n"], [ "\n

{c}

\n\n", "

{c}

\n\n\n\n", ], - // What is not closed does not go on in the markup, up to what closes it there and to the end of another style sheet. + // An unclosed construct doesn't continue into the markup until something closes it there, up to the end of + // another style sheet. [ "\n

don't

\n\n", "

don't

\n\n\n\n", @@ -1592,7 +1635,7 @@ exports.format = async text => "\\n" + text; "

y

\n\n\n\n", ], ["' )}\n", '");\n }\n\n'], - // A string goes on in the next line behind a backslash. + // A string continues on the next line after a backslash. [ '"}\n', '";\n }\n\n', @@ -1615,7 +1658,7 @@ exports.format = async text => "\\n" + text; }); }); - describe("every comment next to a value that is named like its attribute is kept", () => { + describe("keeps every comment next to a value with the same name as its attribute", () => { const sites = [ "", "y", @@ -1664,20 +1707,20 @@ exports.format = async text => "\\n" + text; for (const pass of [1, 2, 3]) { const result = await formatIn(String(dir), names); expect({ pass, stderr: result.stderr, exitCode: result.exitCode }).toEqual({ pass, stderr: "", exitCode: 0 }); - // What has lost or doubled one, with what it was. + // The files that lost or duplicated a comment, with their previous text. const wrong = result.files.flatMap((text, index) => Bun.deepEquals(text.match(/C\d/g)?.sort(), comments(texts[index])) ? [] : [[pass, before[index], text]], ); expect(wrong).toEqual([]); before = result.files; } - // It has settled by then. + // The output is stable by then. expect((await formatIn(String(dir), names)).files).toEqual(before); }); }); describe("--debug-check", () => { - // The text, what becomes of it, and what becomes of that, which stays. + // Each row is the text, the first run's output, and the second run's output if it differs, which is stable. const right: [string, string, string?][] = [ ["{#snippet row(b = // c\n 1)}y{/snippet}\n", "{#snippet row(\n b = 1, // c\n)}y{/snippet}\n"], [ @@ -1687,17 +1730,17 @@ exports.format = async text => "\\n" + text; ], ["{#each ( /* c */b + c ) * d, i}y{/each}\n", "{#each /* c */ (b + c) * d, i}y{/each}\n"], ["{#snippet f(b =\n/* c */\n`${d}`)}y{/snippet}\n", "{#snippet f(\n /* c */\n b = `${d}`,\n)}y{/snippet}\n"], - // A name without its escape, modifiers in the usual order, a name that is written twice. + // An unescaped name, reordered modifiers, and an expanded shorthand. [`${typescript}{b\\u{63}}\n`, `${typescript}{bc}\n`], [`${typescript}{class{static private b}}\n`, `${typescript}{class {\n private static b;\n}}\n`], ["{#each b as { c = {d,e} }}y{/each}\n", "{#each b as { c = { d: d, e: e } }}y{/each}\n"], - // The value of a `style:` directive is broken into lines like text. + // The value of a `style:` directive is wrapped like text. [ '

y

\n', '\n y\n

\n', ], ]; - test("says nothing about what is right", async () => { + test("accepts correct output", async () => { const names = right.map((_, index) => `${index}.svelte`); const files = (which: (row: (typeof right)[0]) => string) => Object.fromEntries(right.map((it, index) => [names[index], which(it)])); @@ -1734,7 +1777,8 @@ exports.format = async text => "\\n" + text; ).toMatchObject(printed(it => it[1])); }); - // What a word or a string is does not depend on the `,`, the `;` or the line break next to it, which change. + // How a word or a string is classified doesn't depend on the `,`, `;` or line break next to it, which formatting + // changes. const words = [ "{x as { b: T, readonly [k: string]: U }}", "{x as { b: T\n readonly [k: string]: U }}", @@ -1759,7 +1803,7 @@ exports.format = async text => "\\n" + text; '{class { 1; "2" }}', ].map(code => `${typescript}${code}\n`); test.each([{}, { semi: false }, { quoteProps: "consistent" }])( - "says nothing about words and keys: %j", + "accepts contextual keywords and keys: %j", async options => { const names = words.map((_, index) => `${index}.svelte`); const files = { @@ -1771,18 +1815,18 @@ exports.format = async text => "\\n" + text; ); const different: [string, string][] = [ - // Code that has become a comment. + // Code that became a comment. ["{@html raw + more}\n", "{@html raw // + more\n}\n"], ["{@html raw + more}\n", "{@html raw /* + more */}\n"], ["{#if q}{@const c = b + 1}{c}{/if}\n", "{#if q}{@const c = b /* + 1 */}{c}{/if}\n"], - // A comment that is lost. + // A lost comment. ["{f(b /* c */)}\n", "{f(b)}\n"], - // A string between brackets is a value. + // A string in brackets is a value. ['{{ ["b"]: 1 }}\n', "{{ [b]: 1 }}\n"], ["\n", "\n"], ["\n", "\n"], ["{#await b}wait{:then { c /* d */ }}{/await}\n", "{#await b}wait{/await}\n"], - // A string is no name. + // A string isn't a name. ['{"name"}\n', "{name}\n"], ['{f("x")}\n', "{f(x)}\n"], ['{f(b, "x", c)}\n', "{f(b, x, c)}\n"], @@ -1792,17 +1836,17 @@ exports.format = async text => "\\n" + text; ['

y

\n', "

y

\n"], ['y\n', "y\n"], ['y\n', 'y\n'], - // A template that is in no other language, whatever is before it. + // A template that isn't embedded code, whatever precedes it. ["{() => { return `b c` }}\n", "{() => { return `b c` }}\n"], ["{typeof `b c`}\n", "{typeof `b c`}\n"], ["{b in `b c`}\n", "{b in `b c`}\n"], ["{async () => await `b c`}\n", "{async () => await `b c`}\n"], ["{() => { if (b) `b c` }}\n", "{() => { if (b) `b c` }}\n"], ["{f`b c`}\n", "{f`b c`}\n"], - // A name that is spelled like a modifier. + // A name that's spelled like a modifier. ["{f(public, b)}\n", "{f(b, public)}\n"], ["{static + b}\n", "{b + static}\n"], - // What is no letter. + // Tokens without letters. ["{row(1, 2)}\n", "{row(1)}\n"], ["{b + 1}\n", "{b}\n"], ["{b + 1}\n", "{b - 1}\n"], @@ -1820,7 +1864,7 @@ exports.format = async text => "\\n" + text; ["

y

\n", "

y

\n"], ['

z

\n', '

z

\n'], ['

y

\n', '

y

\n'], - // White space that is not between two tokens. + // Whitespace that isn't between two tokens. ['

z

\n', '

z

\n'], ['{"b c"}\n', '{"b c"}\n'], ["{`b\nc`}\n", "{`b c`}\n"], @@ -1856,13 +1900,13 @@ exports.format = async text => "\\n" + text; `${typescript}{#snippet f(b: C | D)}y{/snippet}\n`, `${typescript}{#snippet f(\n b:\n | C\n | D,\n)}y{/snippet}\n`, ], - // It does not tell these apart: a string that is no value could be a key, which can lose its quotes. + // It can't distinguish these: a string that isn't a value could be a key, which can lose its quotes. [`${typescript}{b as "c"}\n`, `${typescript}{b as c}\n`], - // Nor these: it looks at tokens, not at the tree, and at neither parentheses nor commas. + // Nor these: it compares tokens, not trees, and ignores parentheses and commas. ["{(b + c) * d}\n", "{b + c * d}\n"], ["{[b, , c]}\n", "{[b, c]}\n"], ]; - test.skipIf(!hasRunner)("tells what is something else from what is only written differently", async () => { + test.skipIf(!hasRunner)("distinguishes different code from the same code written differently", async () => { const rows = [...different, ...same]; using dir = tempDir( "bun-format-svelte", @@ -1876,8 +1920,8 @@ exports.format = async text => "\\n" + text; stderr: "pipe", }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - const said = stdout.trimEnd().split("\n"); - expect(rows.map((it, index) => [...it, said[index]])).toEqual([ + const verdicts = stdout.trimEnd().split("\n"); + expect(rows.map((it, index) => [...it, verdicts[index]])).toEqual([ ...different.map(it => [...it, "different"]), ...same.map(it => [...it, "same"]), ]); @@ -1885,7 +1929,7 @@ exports.format = async text => "\\n" + text; }); }); - test("in
 a part of an await block that has white space in it has something in it", async () => {
+  test("in 
, a part of an await block that only contains whitespace isn't empty", async () => {
     const rows = [
       "
{#await b} {:then c} {:catch d} {/await}
\n", "
{#await b}\n{:then c}\n{:catch d}\n{/await}
\n", @@ -1897,12 +1941,12 @@ exports.format = async text => "\\n" + text; const names = rows.map((_, index) => `${index}.svelte`); const files = Object.fromEntries(rows.map((it, index) => [names[index], it])); expect(await format(files, names)).toMatchObject({ stderr: "", files: rows, exitCode: 0 }); - // The control: elsewhere it is nothing. + // The control: elsewhere such a part is empty. const outside = await format({ "a.svelte": "

{#await b} {:then c} {:catch d} {/await}

\n" }, ["a.svelte"]); expect(outside).toMatchObject({ stderr: "", files: ["

{#await b catch d}{/await}

\n"], exitCode: 0 }); }); - test("a start tag that ends with a comment at the end of a line has its `>` on the next, with bracketSameLine too", async () => { + test("a start tag that ends with a comment puts its `>` on the next line, even with bracketSameLine", async () => { const config = { ".prettierrc": JSON.stringify({ plugins, bracketSameLine: true }) }; const rows = [ ['
y
\n', '\n y\n\n'], @@ -1926,15 +1970,15 @@ exports.format = async text => "\\n" + text; } }); - test("white space that other options make text stays", async () => { + test("keeps whitespace that other options make significant", async () => { const rows: [object, string, string][] = [ - // The plugin has a line in an element with nothing in it, which breaks with the start tag. + // The plugin puts a `line` in an empty element, which breaks together with the start tag. [ { bracketSameLine: true }, "
b
{ c; d }}>
e
\n", "
b {\n      c;\n      d;\n    }}>e
\n", ], - // The rows are as they are written: see "rows that are closed by the next". + // The rows are printed as written: see "leaves table rows that are closed by the next row as written". [{ htmlWhitespaceSensitivity: "strict" }, "
b
\n", "
b
\n"], ]; for (const [options, before, after] of rows) { @@ -1946,76 +1990,76 @@ exports.format = async text => "\\n" + text; } }); - // `regex_lang_attribute` of Svelte 5.57, which looks at the text before anything is parsed. - describe("what says that the markup is TypeScript", () => { + // Svelte 5.57's `regex_lang_attribute`, which is matched against the text before anything is parsed. + describe("detecting TypeScript markup", () => { const [before, after] = ["{(e as number)}\n", "{e as number}\n"]; - // What is before the markup, and what it is formatted to. + // Each row is a label, the scripts before the markup, and their formatted text. test.each([ - ["lang in double quotes", '\n', '\n\n'], + ["in double quotes", '\n', '\n\n'], ["in single quotes", "\n", '\n\n'], ["without quotes", "\n", '\n\n'], [ - "behind a value in double quotes with a > in it", + "after a value in double quotes with a > in it", '\n', '\n\n', ], [ - "before it", + "before a value in double quotes with a > in it", '\n', '\n\n', ], [ - "behind a value in single quotes with a > in it", + "after a value in single quotes with a > in it", "\n", '\n\n', ], [ - "behind a > alone", + "after a value with a lone >", '\n', '\n\n', ], [ - "behind an attribute without a value and one with a >", + "after an attribute without a value and one with a >", '\n', '\n\n', ], [ - "on a line of its own", + "on its own line", '\n', '\n\n', ], [ - "on the module", + "on the module script", '\n\n', '\n\n\n\n', ], [ - "on the instance", + "on the instance script", '\n\n', '\n\n\n\n', ], - // The first `lang` counts. + // The first `lang` wins. [ - "on the first of two scripts that say something else", + "on the first of two scripts with different languages", '\n\n', '\n\n\n\n', ], - // Up to the first `>` Svelte looks for the letters, whatever they are in. + // Up to the first `>`, Svelte matches the characters wherever they appear. [ "in the value of another attribute", `\n`, `\n\n`, ], ["at the end of another name", '\n', '\n\n'], - // In double quotes it would not say so any more. - ["with a quote behind it", "\n", "\n\n"], - // Not so another value. + // In double quotes it would no longer match. + ["with a quote after it", "\n", "\n\n"], + // That doesn't apply to another attribute's value. [ "next to a value with a quote in it", "\n", `\n\n`, ], - ])("%s", async (_, scripts, formatted) => { + ])("lang=ts %s makes the markup TypeScript", async (_, scripts, formatted) => { expect(await format({ "a.svelte": scripts + before }, ["a.svelte"])).toMatchObject({ stderr: "", files: [formatted + after], @@ -2023,7 +2067,7 @@ exports.format = async text => "\\n" + text; }); }); - test("a script behind the markup", async () => { + test("a script after the markup makes it TypeScript too", async () => { const script = '\n'; expect(await format({ "a.svelte": before + script }, ["a.svelte"])).toMatchObject({ stderr: "", @@ -2035,14 +2079,14 @@ exports.format = async text => "\\n" + text; test.each([ ["no lang", "\n"], ["another language", '\n'], - ["a blank behind the =", '\n'], - ["a comment", '\n'], + ["a space after the =", '\n'], + ["a script in a comment", '\n'], [ - "the second of two scripts that say something else", + "lang=ts on the second of two scripts with different languages", '\n', ], - ["a lang behind a > that is in no quotes", '\n'], - ])("not %s", async (_, scripts) => { + ["a lang after an unquoted >", '\n'], + ])("the markup isn't TypeScript with %s", async (_, scripts) => { const result = await format({ "a.svelte": scripts + before }, ["a.svelte"]); expect(result).toMatchObject({ stderr: `2 | {(e as number)}\n ^\nerror: This is TypeScript, which needs \n{b}\n'; expect(await format({ "a.svelte": text }, ["a.svelte"])).toMatchObject({ stderr: "", @@ -2060,7 +2104,7 @@ exports.format = async text => "\\n" + text; }); }); - test("types in the markup of a component with generics", async () => { + test("formats types in the markup of a component with generics", async () => { const text = '\n' + "{#snippet c(d: T)}{d}{/snippet}\n

e}>f

\n"; @@ -2075,8 +2119,9 @@ exports.format = async text => "\\n" + text; }); }); - // No expression ends with `as { b = c }`. Svelte hides what is from an `as` on, from the last to the first, until there is one. - describe("where the expression of an each block ends", () => { + // No expression ends with `as { b = c }`. Svelte cuts the text at each `as`, from the last to the first, until the + // rest parses as an expression. + describe("finding the end of an each block's expression", () => { const rows = [ ["{#each a as { b = c }}d{/each}", "{#each a as { b = c }}d{/each}"], ["{#each a as [b = c]}d{/each}", "{#each a as [b = c]}d{/each}"], @@ -2098,7 +2143,7 @@ exports.format = async text => "\\n" + text; test.each([ ["JavaScript", "", rows], ["TypeScript", '\n\n', [...rows, ...typed]], - ])("%s", async (_, script, rows) => { + ])("in %s", async (_, script, rows) => { const names = rows.map((_, index) => `${index}.svelte`); const files = Object.fromEntries(rows.map((it, index) => [names[index], `${script}${it[0]}\n`])); expect(await format(files, names)).toMatchObject({ @@ -2108,16 +2153,17 @@ exports.format = async text => "\\n" + text; }); }); - test("nowhere, if it is in something that is not closed", async () => { + test("fails if the `as` is inside an unclosed bracket", async () => { const text = "{#each (a as b as c}d{/each}\n"; const result = await format({ "a.svelte": text }, ["a.svelte"]); - expect(result.stderr).toMatch(refusalOf("a.svelte")); + expect(result.stderr).toMatch(errorAt("a.svelte")); expect(result).toMatchObject({ files: [text], exitCode: 2 }); }); }); - describe("what only TypeScript has", () => { - // The text, the column of what is refused in a component without `lang="ts"`, and what the text is formatted to in one with it. + describe("TypeScript-only syntax", () => { + // Each row is the text, the column of the error in a component without `lang="ts"`, and the formatted text in one + // with it. const rows: [string, number, string][] = [ ["{(a: number) => a}", 6, "{(a: number) => a}"], ["{(a?) => a}", 4, "{(a?) => a}"], @@ -2131,7 +2177,7 @@ exports.format = async text => "\\n" + text; ["{(a) => { let b: number; }}", 18, "{(a) => {\n let b: number;\n}}"], ["{() => { type A = 1 }}", 15, "{() => {\n type A = 1;\n}}"], ["{() => { enum A {} }}", 15, "{() => {\n enum A {}\n}}"], - // It is printed as an expression, which a declarator with a type is not: it stays as it is written. + // `{@const}` is printed as an expression, which a declarator with a type isn't, so it's printed verbatim. ["{@const a: number = 1}", 10, "{@const a: number = 1}"], ["{let a: number = 1}", 9, "{let a: number = 1}"], ["{#each a as b: number}c{/each}", 15, "{#each a as b: number}c{/each}"], @@ -2140,7 +2186,7 @@ exports.format = async text => "\\n" + text; ]; const names = rows.map((_, index) => `${index}.svelte`); - test("is an error in a component that is JavaScript, which says what it takes", async () => { + test("is an error in a JavaScript component, and the message says what's needed", async () => { const files = Object.fromEntries(rows.map(([text], index) => [names[index], `${text}\n`])); const result = await format(files, names); for (const [index, [text, column]] of rows.entries()) { @@ -2154,7 +2200,7 @@ exports.format = async text => "\\n" + text; expect(result).toMatchObject({ files: Object.values(files), exitCode: 2 }); }); - test("is formatted in one that is TypeScript", async () => { + test("is formatted in a TypeScript component", async () => { const files = Object.fromEntries( rows.map(([text], index) => [names[index], `\n\n${text}\n`]), ); @@ -2174,8 +2220,9 @@ exports.format = async text => "\\n" + text; }); }); - test("what is an expression to Svelte is one in a \n", "b.svelte": '\n', @@ -2187,7 +2234,7 @@ exports.format = async text => "\\n" + text; }); test.each(["{:else}c", "{:else if d}c", "{:else if d}c{:else if e}f{:else}g"])( - "a behind a <svelte:head> is not in it, whatever the head has: {#if a}b%s{/if}", + "a <title> after a <svelte:head> isn't inside it, whatever the head contains: {#if a}b%s{/if}", async rest => { const head = `<svelte:head\n >{#if a}b${rest}{/if}</svelte:head\n>\n`; const result = await format({ "a.svelte": `${head}<title> h i \n` }, ["a.svelte"]); @@ -2195,13 +2242,13 @@ exports.format = async text => "\\n" + text; }, ); - test("a no-break space at the end of a component is nothing to Svelte, and would be text before a \n

b

\u00A0\n" }, ["a.svelte"]); expect(result).toMatchObject({ stderr: "", files: ["

b

\n\n\n"], exitCode: 0 }); }); - // The plugin writes the error to stderr too, and goes on. - describe("what is in a script or a style sheet and cannot be parsed stays as it is, with a warning", () => { + // The plugin writes the error to stderr too, and continues. + describe("a script or style sheet that can't be parsed is left unchanged, with a warning", () => { const warning = (message: string, [line, column, shown]: [number, number, string], name = "a.svelte") => `${line} | ${shown}\n${Buffer.alloc(`${line} | `.length + column - 1, " ").toString()}^\n` + `warn: ${message}\n at ${name}:${line}:${column}\n\n`; @@ -2214,7 +2261,7 @@ exports.format = async text => "\\n" + text; warning("Expression expected.", [2, 11, " let a = ;"]), ], [ - "a style sheet, behind the markup", + "a style sheet after the markup", "

a

\n\n\n", "

a

\n\n\n", warning('Unexpected "}"', [4, 15, " a { color: }}"]), @@ -2232,7 +2279,7 @@ exports.format = async text => "\\n" + text; warning("Unexpected token", [1, 48, '
']), ], [ - "a script whose type is another name of JavaScript", + "a script whose type is another name for JavaScript", '\n', '\n', warning("Identifier expected.", [1, 41, '']), @@ -2244,7 +2291,7 @@ exports.format = async text => "\\n" + text; warning("Expression expected.", [1, 39, '']), ], [ - "behind a byte order mark and letters of two bytes", + "after a byte order mark and two-byte letters", '\uFEFF\n', '\uFEFF\n', warning("Expression expected.", [1, 30, '']), @@ -2263,17 +2310,17 @@ exports.format = async text => "\\n" + text; "\n\n

{a}

\n", "\n\n

{a}

\n", ]; - const said = warning("Expression expected.", [2, 11, " let a = ;"]); + const warn = warning("Expression expected.", [2, 11, " let a = ;"]); - test("--check says it too, about a file that is formatted and about one that is not", async () => { + test("--check prints the warning too, for a formatted file and for an unformatted one", async () => { const checked = await format({ "a.svelte": after }, ["a.svelte"], ["--check"]); - expect(checked).toMatchObject({ stderr: said, files: [after], exitCode: 0 }); + expect(checked).toMatchObject({ stderr: warn, files: [after], exitCode: 0 }); const different = await format({ "a.svelte": before }, ["a.svelte"], ["--check"]); const summary = "1 file needs formatting. Run bun fmt to fix it.\n"; - expect(different).toMatchObject({ stdout: "a.svelte\n", stderr: said + summary, files: [before], exitCode: 1 }); + expect(different).toMatchObject({ stdout: "a.svelte\n", stderr: warn + summary, files: [before], exitCode: 1 }); }); - test("a line is shown with the first warning that is about it", async () => { + test("a source line is only shown with the first warning about it", async () => { const text = "
\n
\n"; const result = await format({ "a.svelte": text }, ["a.svelte"], ["--check"]); expect(result.stderr).toStartWith( @@ -2283,12 +2330,12 @@ exports.format = async text => "\\n" + text; ); }); - test("--log-level=error does not", async () => { + test("--log-level=error hides the warning", async () => { const result = await format({ "a.svelte": before }, ["a.svelte"], ["--log-level=error"]); expect(result).toMatchObject({ stderr: "", files: [after], exitCode: 0 }); }); - test("from standard input", async () => { + test("prints the warning for stdin too", async () => { using dir = tempDir("bun-format-svelte", {}); await using proc = spawn({ cmd: [bunExe(), "fmt", "--stdin-filepath=b.svelte"], @@ -2304,13 +2351,13 @@ exports.format = async text => "\\n" + text; }); }); - test("rows that are closed by the next stay as they are written", async () => { - // To Svelte the second row ends the cell and is in the first row. The plugin gives every element its end tag, and - // then the second row ends the first, whose end tag is left over. + test("leaves table rows that are closed by the next row as written", async () => { + // In Svelte, the second row closes the cell and is nested in the first row. The plugin prints an end tag for every + // element, and then the second row closes the first one, whose end tag is left over. const text = "
a
b
\n"; const result = await format({ ".prettierrc": prettierrc, "a.svelte": text }, ["a.svelte"]); expect(result).toMatchObject({ stderr: "", files: [text], exitCode: 0 }); - // Where the next element ends the one before it and nothing else, there is nothing to lose. + // If the next element only closes the one before it, nothing can go wrong. const items = await format({ ".prettierrc": prettierrc, "a.svelte": "
  • a
  • b
\n" }, ["a.svelte"]); expect(items).toMatchObject({ stderr: "", files: ["
    \n
  • a
  • \n
  • b
  • \n
\n"], exitCode: 0 }); }); @@ -2318,7 +2365,7 @@ exports.format = async text => "\\n" + text; test.each<[string, string, string, [line: number, column: number, text: string]]>([ ["in the markup", "
\n

a

\n", "Unclosed element", [1, 1, "
"]], [ - "in an expression, behind a script and a style sheet", + "in an expression, after a script and a style sheet", "\n\n

{a +}

\n", "Unexpected token", [8, 8, "

{a +}

"], @@ -2329,14 +2376,14 @@ exports.format = async text => "\\n" + text; "There is no open block to end here", [4, 5, "

{/if}

"], ], - // To Svelte this is `t`, or all that is up to a quote further down. + // Svelte reads this as `t`, or as everything up to a quote further down. [ - "at a quote in a \n', "Unclosed string", [1, 14, '", n / 10)}
`, }; - await expectToTakeLittleTime(shapes, [ + await expectToBeFast(shapes, [ "attributes-of-a-script", "attributes-of-a-script-next-to-quotes", "attributes-of-the-options", @@ -2521,7 +2568,7 @@ exports.format = async text => "\\n" + text; ]); }); - test("nothing is looked for, or parsed, again and again", async () => { + test("doesn't rescan or reparse the same text repeatedly", async () => { const shapes: Record = { "starts-of-scripts": repeated("{#each a${repeated(" as a", n)} as { b = 1 }}x{/each}`, "each-with-defaults": repeated("{#each a as { b = 1 }}x{/each}\n", n / 4), - // There is a warning about each. + // Each one gets a warning. "scripts-with-errors": `
${repeated("\n", n / 4)}
`, "scripts-with-errors-and-returns": `
${repeated("\r\n", n / 4)}
`, "scripts-with-errors-on-one-line": `
${repeated("", n / 4)}
`, }; - await expectToTakeLittleTime(shapes, [ + await expectToBeFast(shapes, [ "each-behind-operators", "each-in-a-parenthesis-not-closed", "each-in-parentheses", @@ -2559,7 +2606,7 @@ exports.format = async text => "\\n" + text; ]); }); - test("blocks of Svelte in Markdown are formatted where components are", async () => { + test("formats Svelte code blocks in Markdown whenever it formats components", async () => { const block = (text: string) => `# a\n\n\`\`\`svelte\n${text}\`\`\`\n`; const withOtherVersion = { ".prettierrc": prettierrc, ...plugin("4.1.0") }; for (const config of [{}, { ".prettierrc": prettierrc }, withOtherVersion, { ".oxfmtrc.json": oxfmtrc }]) { @@ -2567,9 +2614,9 @@ exports.format = async text => "\\n" + text; stderr: "", files: [block(output)], }); - // One that is refused stays as it is. - const refused = block("

{a +}

\n"); - expect(await format({ ...config, "a.md": refused }, ["a.md"])).toMatchObject({ files: [refused], exitCode: 0 }); + // A rejected block stays unchanged. + const rejected = block("

{a +}

\n"); + expect(await format({ ...config, "a.md": rejected }, ["a.md"])).toMatchObject({ files: [rejected], exitCode: 0 }); } for (const config of [{ ".prettierrc": "{}" }, { ".oxfmtrc.json": "{}" }]) { expect((await format({ ...config, "a.md": block(input) }, ["a.md"], ["--allow-unsupported"])).files).toEqual([ @@ -2578,8 +2625,8 @@ exports.format = async text => "\\n" + text; } }); - test("the classes of Tailwind CSS are sorted", async () => { - // What oxfmt 0.72 prints with tailwindcss 4.3.3. The package is a stand-in, as in ../tailwind. + test("sorts Tailwind CSS classes", async () => { + // This is what oxfmt 0.72 prints with tailwindcss 4.3.3. The package is a stub, as in ../tailwind. const tailwind = { "node_modules/tailwindcss/package.json": '{ "name": "tailwindcss", "version": "4.0.0", "main": "index.js" }', "node_modules/tailwindcss/theme.css": "", @@ -2624,8 +2671,8 @@ exports.__unstable__loadDesignSystem = async () => ({ expect(await format(files, ["a.svelte"])).toMatchObject({ stderr: "", files: [after], exitCode: 0 }); }); - test("the classes in an object are sorted too", async () => { - // The plugin visits every string of the expression, whatever the expression is. + test("sorts the classes in an object too", async () => { + // The plugin visits every string in the expression, whatever the expression is. const tailwind = { "node_modules/tailwindcss/package.json": '{ "name": "tailwindcss", "version": "4.0.0", "main": "index.js" }', "node_modules/tailwindcss/theme.css": "", @@ -2647,9 +2694,9 @@ exports.__unstable__loadDesignSystem = async () => ({ }); }); - test('with svelteSortOrder "none" every part is there once, in its place', async () => { - // The plugin puts a script or a style sheet back next to a node of the markup. One that has none is lost: the first of these - // comes out empty. Some are there twice. + test('with svelteSortOrder "none", prints every part once and in place', async () => { + // The plugin puts a script or a style sheet back next to a markup node. One without such a node is lost, so the + // first of these comes out empty. Some are printed twice. const script = "\n"; const files = { "only.svelte": "", @@ -2678,7 +2725,7 @@ exports.__unstable__loadDesignSystem = async () => ({ } }); - test("under prettier-ignore a script keeps what is in it", async () => { + test("a script under prettier-ignore keeps its contents", async () => { // The plugin prints ``. const text = "\n
\n"; expect(await format({ ".prettierrc": prettierrc, "a.svelte": text }, ["a.svelte"])).toMatchObject({ diff --git a/test/cli/format/tailwind/tailwind.test.ts b/test/cli/format/tailwind/tailwind.test.ts index 3a159334f0f3..7c167152d3c3 100644 --- a/test/cli/format/tailwind/tailwind.test.ts +++ b/test/cli/format/tailwind/tailwind.test.ts @@ -1,8 +1,9 @@ -// oxfmt's `sortTailwindcss`. cases.json: the inputs of oxfmt's apps/oxfmt/test/api/sort_tailwindcss.test.ts (MIT: see LICENSE) and -// some more, with what oxfmt 0.72 prints for them with tailwindcss 4.3.3. order.json: the classes in them that Tailwind knows, in -// its order. Both are made by test/cli/format/oracle/tailwind/make-fixtures.ts. +// Tests for oxfmt's `sortTailwindcss`. cases.json has the inputs from oxfmt's +// apps/oxfmt/test/api/sort_tailwindcss.test.ts (MIT: see LICENSE) plus some more, with oxfmt 0.72's output for them +// with tailwindcss 4.3.3. order.json has the classes in them that Tailwind knows, in Tailwind's order. +// test/cli/format/oracle/tailwind/make-fixtures.ts generates both. // -// The order comes from the package `tailwindcss` of the project. Here that is a stand-in, which knows what is in order.json. +// The order comes from the project's `tailwindcss` package. Here that's a stub that knows the classes in order.json. import { afterAll, describe, expect, test } from "bun:test"; import { bunEnv, bunExe, isLinux, isWindows, tempDir } from "harness"; import { chmodSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; @@ -14,7 +15,7 @@ import order from "./order.json"; afterAll(endChildren); const getClassOrder = `classes => classes.map(name => [name, order.includes(name) ? BigInt(sign * order.indexOf(name)) : null])`; -/** Tailwind CSS 4, as far as it is asked. A style sheet with `reversed` in it turns the order around. */ +/** A stub of the parts of Tailwind CSS 4 that get called. A style sheet that contains `reversed` reverses the order. */ const version4 = { "node_modules/tailwindcss/package.json": JSON.stringify({ name: "tailwindcss", version: "4.0.0", main: "index.js" }), "node_modules/tailwindcss/theme.css": "", @@ -25,7 +26,7 @@ exports.__unstable__loadDesignSystem = async css => { }; `, }; -/** Tailwind CSS 3. A configuration with `reversed` in it turns the order around, the classes in its `own` come last. */ +/** A stub of Tailwind CSS 3. A configuration with `reversed` reverses the order, and classes in its `own` come last. */ const version3 = { "node_modules/tailwindcss/package.json": JSON.stringify({ name: "tailwindcss", version: "3.0.0", main: "index.js" }), "node_modules/tailwindcss/index.js": "", @@ -60,7 +61,7 @@ async function format(files: Record, names: string[], flags: str describe.concurrent("sortTailwindcss", () => { // One run for all the cases with the same options. for (const [options, group] of Map.groupBy(cases, it => JSON.stringify(it.options))) { - test(`as oxfmt: ${options}`, async () => { + test(`matches oxfmt: ${options}`, async () => { const names = group.map((it, index) => `${index}/${it.filename}`); const files = Object.fromEntries(group.map((it, index) => [names[index], it.input])); const result = await format({ ...version4, ".oxfmtrc.json": options, ...files }, names); @@ -80,9 +81,9 @@ describe.concurrent("sortTailwindcss", () => { const listed = (root: string) => readdirSync(root, { recursive: true, encoding: "utf8" }).sort(); - describe("Handlebars: classes that oxfmt joins with what is next to them, or loses", () => { - // The template, what Bun makes of it, and what oxfmt 0.72 makes of it. It takes the blank at the end of a string away - // whatever follows, moves a class that touches what is before or behind the mustache, and loses a no-break space. + describe("Handlebars: classes that oxfmt joins with adjacent text, or loses", () => { + // Each row is the template, Bun's output and oxfmt 0.72's output. oxfmt removes the space at the end of a string + // whatever follows, moves a class that touches the text before or after the mustache, and loses a no-break space. const rows = [ [ '\n', @@ -110,22 +111,22 @@ describe.concurrent("sortTailwindcss", () => { ``, ], ['\n', '', ''], - // With white space in between nothing touches. + // With whitespace in between, nothing touches. ['\n', ``, null], ] as const; const names = rows.map((_, index) => `${index}.hbs`); const files = Object.fromEntries(rows.map((row, index) => [names[index], row[0]])); const project = { ...version4, ".oxfmtrc.json": '{ "sortTailwindcss": {} }' }; - test("stay apart", async () => { - for (const [, after, ofOxfmt] of rows) expect(after).not.toBe(ofOxfmt); + test("stay separate", async () => { + for (const [, after, byOxfmt] of rows) expect(after).not.toBe(byOxfmt); const result = await format({ ...project, ...files }, names); expect(result.stderr).toBe(""); expect(result.files).toEqual(rows.map(row => row[1])); expect(result.exitCode).toBe(0); }); - test("--debug-check compares what would be written, and has nothing to say about it", async () => { + test("pass --debug-check, which compares what would be written", async () => { const result = await format({ ...project, ...files }, names, ["--debug-check"]); expect(result.stderr).toBe(""); expect(result.files).toEqual(rows.map(row => row[0])); @@ -133,16 +134,16 @@ describe.concurrent("sortTailwindcss", () => { }); }); - test("nothing is written into the project, not even while Tailwind is asked", async () => { - // The stand-in looks around when it is loaded, and refuses to answer if there is a file that the test has not made. - const looksAround = `const { readdirSync } = require("node:fs"); + test("writes nothing into the project, not even while Tailwind is running", async () => { + // When it's loaded, the stub lists the project and throws if there's a file that the test didn't create. + const checkFiles = `const { readdirSync } = require("node:fs"); const now = readdirSync(require("node:path").join(__dirname, "../.."), { recursive: true, encoding: "utf8" }).sort(); const before = JSON.parse(process.env.FILES_OF_THE_TEST); if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => !before.includes(it)).join(", ")); `; using dir = tempDir("bun-format-tailwind", { ...version4, - "node_modules/tailwindcss/index.js": looksAround + version4["node_modules/tailwindcss/index.js"], + "node_modules/tailwindcss/index.js": checkFiles + version4["node_modules/tailwindcss/index.js"], ".oxfmtrc.json": '{ "sortTailwindcss": {} }\n', "a.jsx": input, }); @@ -161,8 +162,8 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => expect(exitCode).toBe(0); }); - // Nix, a layer of an image that belongs to root, a sandbox. Nothing is closed to root. - test.skipIf(isWindows || process.getuid?.() === 0)("the packages can be read-only", async () => { + // As with Nix, an image layer owned by root, or a sandbox. Skipped as root, which can write anywhere. + test.skipIf(isWindows || process.getuid?.() === 0)("works with read-only packages", async () => { using dir = tempDir("bun-format-tailwind", { ...version4, ".oxfmtrc.json": '{ "sortTailwindcss": {} }\n', @@ -177,26 +178,26 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => } }); - test("`stylesheet` is what Tailwind CSS 4 is loaded with, from the directory of the configuration file", async () => { + test("loads Tailwind CSS 4 with `stylesheet`, relative to the configuration file's directory", async () => { const config = JSON.stringify({ sortTailwindcss: { stylesheet: "./css/app.css" } }); const files = { ...version4, ".oxfmtrc.json": config, "css/app.css": "/* reversed */\n", "src/a.jsx": sorted }; const result = await format(files, ["src/a.jsx"]); expect(result).toMatchObject({ stderr: "", files: [reversed], exitCode: 0 }); }); - test("Tailwind CSS 3 is loaded with `config`, or with the nearest tailwind.config.*", async () => { + test("loads Tailwind CSS 3 with `config`, or with the nearest tailwind.config.*", async () => { const files = { ...version3, "other.js": "module.exports = { reversed: true };\n", "src/a.jsx": input }; const nearest = { ".oxfmtrc.json": '{ "sortTailwindcss": true }', "tailwind.config.ts": "export default {};\n" }; expect(await format({ ...files, ...nearest }, ["src/a.jsx"])).toMatchObject({ stderr: "", files: [sorted] }); - const named = { ".oxfmtrc.json": '{ "sortTailwindcss": { "config": "other.js" } }' }; - expect(await format({ ...files, ...named, "src/a.jsx": sorted }, ["src/a.jsx"])).toMatchObject({ + const explicit = { ".oxfmtrc.json": '{ "sortTailwindcss": { "config": "other.js" } }' }; + expect(await format({ ...files, ...explicit, "src/a.jsx": sorted }, ["src/a.jsx"])).toMatchObject({ stderr: "", files: [reversed], }); }); - // As for prettier-plugin-tailwindcss 0.8.1 with Prettier 3.9.9. - test("`process.cwd()` in a tailwind.config.js is where the command runs", async () => { + // Same as prettier-plugin-tailwindcss 0.8.1 with Prettier 3.9.9. + test("`process.cwd()` in a tailwind.config.js is the directory where the command runs", async () => { using dir = tempDir("bun-format-tailwind", { ...version3, ".oxfmtrc.json": '{ "sortTailwindcss": true }', @@ -205,14 +206,14 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => "sub/b.jsx": sorted, }); const below = await formatIn(join(String(dir), "sub"), ["a.jsx"], ["a.jsx"]); - const beside = await formatIn(String(dir), ["sub/b.jsx"], ["sub/b.jsx"]); - expect([below, beside]).toMatchObject([ + const fromRoot = await formatIn(String(dir), ["sub/b.jsx"], ["sub/b.jsx"]); + expect([below, fromRoot]).toMatchObject([ { stderr: "", files: [reversed] }, { stderr: "", files: [sorted] }, ]); }); - test("each package of a workspace has its own Tailwind CSS", async () => { + test("each workspace package uses its own Tailwind CSS", async () => { const inPackage = (files: Record, directory: string) => Object.fromEntries(Object.entries(files).map(([name, text]) => [`${directory}/${name}`, text])); const result = await format( @@ -230,7 +231,7 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => }); test.each([".pnpm", ".bun"])( - "a package that only another package of the workspace depends on is found in %s", + "finds the package in %s if only another package in the workspace depends on it", async store => { const hoisted = Object.fromEntries( Object.entries(version4).map(([name, text]) => [ @@ -243,8 +244,8 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => }, ); - // oxfmt 0.72 sorts them in the order of the Tailwind CSS that it brings along. - test("without the package the classes stay as they are, the rest is formatted, and nothing is said", async () => { + // oxfmt 0.72 sorts them in the order of its bundled Tailwind CSS. + test("without the package, silently leaves the classes unsorted and formats the rest", async () => { using dir = tempDir("bun-format-tailwind", { "package.json": "{}", ".oxfmtrc.json": '{ "sortTailwindcss": {} }', @@ -270,7 +271,7 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => 'export const Done = () =>
hi
;\n', ], }); - // What has been written is what --check wants. + // The written files pass --check. expect(await formatIn(String(dir), [], list)).toEqual({ stdout: "", stderr: "", @@ -307,11 +308,11 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => expect(await format(files, names)).toMatchObject(expected); expect(await format(files, names, ["--allow-unsupported"])).toMatchObject(expected); expect(await format(files, names, ["--threads=1"])).toMatchObject(expected); - // As without the option. + // Same as without the option. expect(await format({ ...files, ".oxfmtrc.json": "{}" }, names)).toMatchObject(expected); }); - test("a workspace without the package beside one that has it", async () => { + test("a workspace without the package next to one that has it", async () => { const inWeb = Object.entries(version4).map(([name, text]) => [`web/${name}`, text]); const files = { ".oxfmtrc.json": '{ "sortTailwindcss": true }', @@ -326,21 +327,21 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => }); }); - // oxfmt 0.72 exits with 0. For a package that cannot be loaded it asks the Tailwind CSS that it brings along. For a file that - // is not there it leaves the classes as they are, and says so only of `config`. + // oxfmt 0.72 exits with 0. If the package can't be loaded, it falls back to its bundled Tailwind CSS. If a file is + // missing, it leaves the classes unsorted, and only reports that for `config`. test.each<[string, Record, RegExp]>([ [ - "the package cannot be loaded", + "the package can't be loaded", { ...version4, "node_modules/tailwindcss/index.js": 'throw new Error("It is broken.");\n' }, /^error: sortTailwindcss: \S+node_modules\/tailwindcss: It is broken\.$/m, ], [ - "`stylesheet` names no file", + "`stylesheet` doesn't exist", { ...version4, ".oxfmtrc.json": '{ "sortTailwindcss": { "stylesheet": "./none.css" } }' }, /^error: sortTailwindcss: \S+\/none\.css: ENOENT/m, ], [ - "`config` names no file", + "`config` doesn't exist", { ...version3, ".oxfmtrc.json": '{ "sortTailwindcss": { "config": "./none.js" } }' }, /^error: sortTailwindcss: \S+\/none\.js: Cannot find module/m, ], @@ -349,22 +350,22 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => { ...version4, ".oxfmtrc.json": '{ "sortTailwindcss": { "config": "./a.js" } }', "a.js": "" }, /^error: sortTailwindcss: \S+\/a\.js: `config` only works with Tailwind CSS 3, and \S+ is another version$/m, ], - ])("with the package it is still an error if %s", async (_, files, said) => { + ])("with the package, it's still an error if %s", async (_, files, message) => { const all = { ".oxfmtrc.json": '{ "sortTailwindcss": true }', ...files, "a.jsx": `${input}a ;\n` }; const result = await format(all, ["a.jsx"]); - expect(result.stderr).toMatch(said); + expect(result.stderr).toMatch(message); expect(result.stderr).toContain(`error: a.jsx: ${unknown} It was not formatted.\n`); expect(result).toMatchObject({ files: [`${input}a ;\n`], exitCode: 2 }); }); - test("classes that Tailwind does not know come first, in the order in which they are written", async () => { + test("classes that Tailwind doesn't know come first, in their original order", async () => { const files = { ...version4, ".oxfmtrc.json": '{ "sortTailwindcss": true }' }; const result = await format({ ...files, "a.jsx": ';\n' }, ["a.jsx"]); expect(result).toMatchObject({ stderr: "", files: [';\n'], exitCode: 0 }); }); - // oxfmt 0.72 does not read such a file. The order is the one that it has for the same text in UTF-8. - test("a file that is not UTF-8 is formatted as without the option: its bytes stay", async () => { + // oxfmt 0.72 can't read such a file. The expected order is the one it produces for the same text in UTF-8. + test("sorts classes in a file that isn't UTF-8 and preserves its bytes", async () => { const files = { "latin1.jsx": `;\n`, "two.jsx": `;\n`, @@ -406,7 +407,7 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => expect(exitCode).toBe(0); }); - test("a file with a class that Tailwind says nothing about is named, and left as it is", async () => { + test("reports a file with a class that Tailwind returns no answer for, and leaves it unchanged", async () => { const entry = "node_modules/tailwindcss/index.js"; using dir = tempDir("bun-format-tailwind", { ...version4, @@ -431,9 +432,9 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => expect(piped).toMatchObject({ stdout: "", stderr: `error: d.jsx: ${unknown}\n`, exitCode: 2 }); }); - // There oxfmt 0.72 sorts in the order of the Tailwind CSS that it brings along, whatever that of the project says. + // oxfmt 0.72 uses the order of its bundled Tailwind CSS there, regardless of the project's. test.skipIf(!isLinux)( - "a Tailwind CSS in a directory whose name is not UTF-8 cannot be asked, and that is said", + "reports an error for a Tailwind CSS in a directory whose name isn't UTF-8, which can't be loaded", async () => { using dir = tempDir("bun-format-tailwind", { ...version4, @@ -457,8 +458,8 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => }, ); - // An editor in a repository whose root has no packages. - test("a text from stdin, for a file of a project below the working directory", async () => { + // This is what an editor does in a repository whose root has no packages. + test("stdin for a file in a project below the working directory", async () => { const inWeb = Object.entries(version4).map(([name, text]) => [`web/${name}`, text]); const files = { "web/.oxfmtrc.json": '{ "sortTailwindcss": true }', ...Object.fromEntries(inWeb) }; using dir = tempDir("bun-format-tailwind", files); @@ -466,8 +467,8 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => expect(result).toMatchObject({ stderr: "", stdout: sorted, exitCode: 0 }); }); - // What an editor runs. - test("without the package, a text from stdin is formatted but for its classes, as a file is", async () => { + // This is what an editor runs. + test("without the package, stdin is formatted except for its classes, like a file", async () => { using dir = tempDir("bun-format-tailwind", { ".oxfmtrc.json": '{ "sortTailwindcss": true }' }); const from = ["--stdin-filepath", "a.jsx"]; expect(await formatIn(String(dir), [], from, `${input}a ;\n`)).toMatchObject({ @@ -475,7 +476,7 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => stderr: "", exitCode: 0, }); - // oxfmt has no --check for it. + // oxfmt has no --check for stdin. using plain = tempDir("bun-format-tailwind", {}); const check = ["--sort-tailwindcss", "--check", ...from]; expect(await formatIn(String(plain), [], check, `${input}a;\n`)).toMatchObject({ @@ -485,7 +486,7 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => }); }); - test("every run that comes across classes asks Tailwind, once, and leaves nothing behind", async () => { + test("every run that finds classes loads Tailwind once and leaves nothing behind", async () => { const entry = "node_modules/tailwindcss/index.js"; const counts = `require("node:fs").appendFileSync(__dirname + "/loaded.txt", "x");\n`; using dir = tempDir("bun-format-tailwind", { @@ -504,7 +505,7 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => stderr: "", files: [sorted, "xx", sorted], }); - // Nothing is asked for a file without classes. + // Tailwind isn't loaded for a file without classes. write("c.js", "c ;\n"); expect(await formatIn(String(dir), ["c.js", names[1]], ["c.js"])).toMatchObject({ stderr: "", @@ -519,7 +520,7 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => expect(readdirSync(join(String(dir), "node_modules"))).toEqual(["tailwindcss"]); }); - test("a Tailwind that cannot be asked takes only its own files with it, in the first run as in the next", async () => { + test("a Tailwind that can't be loaded only fails its own files, on the first run and on later ones", async () => { const files = { ...version3, ".oxfmtrc.json": '{ "sortTailwindcss": true }', @@ -530,7 +531,7 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => "three/tailwind.config.js": 'throw new Error("It has no such plugin.");\n', "three/a.jsx": ';\na ;\n', "four/a.jsx": ';\n', - // More of them. Nothing but the order of the classes could change in their files. + // More configs that fail. Only the class order could change in their files. ...Object.fromEntries( ["z", "c", "x", "b", "y", "a"].flatMap(name => [ [`${name}/tailwind.config.js`, 'throw new Error("Nor has it this one.");\n'], @@ -580,15 +581,15 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => } }); - test("nothing is run for files without classes", async () => { + test("doesn't run anything for files without classes", async () => { const files = { ".oxfmtrc.json": '{ "sortTailwindcss": true }', "a.jsx": ';\n' }; expect(await format(files, ["a.jsx"])).toMatchObject({ stderr: "", exitCode: 0 }); }); - // What is expected is what Prettier 3.9.9 does with prettier-plugin-tailwindcss 0.8.1 and tailwindcss 4.3.3. + // The expected results come from Prettier 3.9.9 with prettier-plugin-tailwindcss 0.8.1 and tailwindcss 4.3.3. describe("prettier-plugin-tailwindcss in a Prettier config", () => { const plugin = "prettier-plugin-tailwindcss"; - /** The plugin as far as a configuration can look at it. Nothing of it runs. */ + /** A stub of the parts of the plugin that a configuration can see. None of it runs. */ const installed = { [`node_modules/${plugin}/package.json`]: JSON.stringify({ name: plugin, type: "module", exports: "./index.mjs" }), [`node_modules/${plugin}/index.mjs`]: @@ -618,7 +619,7 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => { ".prettierrc": `{ "overrides": [{ "files": "*.jsx", "options": { "plugins": ["${plugin}"] } }] }` }, ], ["--plugin", {}, ["--plugin", plugin]], - ["--plugin beside a config", { ".prettierrc": "{}" }, [`--plugin=${plugin}`]], + ["--plugin next to a config", { ".prettierrc": "{}" }, [`--plugin=${plugin}`]], ["package.json", { "package.json": `{ "prettier": { "plugins": ["${plugin}"] } }` }], ["YAML", { ".prettierrc.yaml": `plugins:\n - ${plugin}\n` }], ["TOML", { ".prettierrc.toml": `plugins = ["${plugin}"]\n` }], @@ -633,12 +634,12 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => ...shared("a.js", `module.exports = { plugins: [require.resolve("${plugin}")] };`), }, ], - ])("is named by %s", async (_, files, flags = []) => { + ])("is recognized when it's specified by %s", async (_, files, flags = []) => { const result = await format({ ...project, ...files, "a.jsx": input }, ["a.jsx"], flags); expect(result).toMatchObject({ stderr: "", files: [sorted], exitCode: 0 }); }); - test("counts for the files whose list of plugins has it", async () => { + test("applies to the files whose plugin list includes it", async () => { const overrides = [ { files: "off/**", options: { plugins: [] } }, { files: "*.tsx", options: { tailwindPreserveDuplicates: true } }, @@ -654,7 +655,7 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => }); test.each<[object, string, string]>([ - // No function takes classes unless the config says so. + // No function's arguments are sorted unless the config lists it. [{}, 'cn("p-4 flex");\nclsx("p-4 flex");\ntwMerge("p-4 flex");\ntw`p-4 flex`;\n', ""], [ { tailwindFunctions: ["cn"] }, @@ -678,12 +679,12 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => ';\n', ], [{ tailwindPreserveDuplicates: true }, ';\n', ';\n'], - ])("has its options and its defaults: %j", async (options, before, after) => { + ])("supports its options and defaults: %j", async (options, before, after) => { const result = await format({ ...project, ...config(options), "a.jsx": before }, ["a.jsx"]); expect(result).toMatchObject({ stderr: "", files: [after || before], exitCode: 0 }); }); - // The plugin says the same, behind the directory of the config and without the `warn:`. + // The plugin prints the same text, after the config's directory and without the `warn:`. const deprecated = (name: string) => `warn: Deprecated: Use the \`tailwindStylesheet\` option for v4 projects instead of \`${name}\`.\n`; const both = @@ -702,31 +703,31 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => expect(result).toMatchObject({ stderr, files: [reversed], exitCode: 0 }); }); - test.each(["tailwindStylesheet", "tailwindEntryPoint", "tailwindConfig"])("an empty %s is none", async name => { + test.each(["tailwindStylesheet", "tailwindEntryPoint", "tailwindConfig"])("an empty %s is ignored", async name => { const result = await format({ ...project, ...config({ [name]: "" }), "a.jsx": input }, ["a.jsx"]); expect(result).toMatchObject({ stderr: "", files: [sorted], exitCode: 0 }); }); - test("a path is relative to the working directory if the config is the one that --config names", async () => { + test("a path is relative to the working directory if the config is passed to --config", async () => { const files = { "config/.prettierrc": config({ tailwindStylesheet: "./app.css" })[".prettierrc"], "a.jsx": sorted, }; const flags = ["--config", "config/.prettierrc"]; - const beside = await format({ ...project, ...files, "app.css": "/* reversed */\n" }, ["a.jsx"], flags); - expect(beside).toMatchObject({ stderr: "", files: [reversed], exitCode: 0 }); + const inCwd = await format({ ...project, ...files, "app.css": "/* reversed */\n" }, ["a.jsx"], flags); + expect(inCwd).toMatchObject({ stderr: "", files: [reversed], exitCode: 0 }); const elsewhere = await format({ ...project, ...files, "config/app.css": "/* reversed */\n" }, ["a.jsx"], flags); expect(elsewhere).toMatchObject({ files: [sorted], exitCode: 2 }); expect(elsewhere.stderr).toContain("app.css"); }); - test("tailwindConfig is what Tailwind CSS 3 is loaded with", async () => { + test("loads Tailwind CSS 3 with tailwindConfig", async () => { const files = { ...version3, ...installed, ...config({ tailwindConfig: "./other.js" }), "src/a.jsx": sorted }; const result = await format({ ...files, "other.js": "module.exports = { reversed: true };\n" }, ["src/a.jsx"]); expect(result).toMatchObject({ stderr: "", files: [reversed], exitCode: 0 }); }); - test("tailwindPackageName is what Tailwind CSS is called", async () => { + test("tailwindPackageName sets the Tailwind CSS package name", async () => { const renamed = Object.fromEntries( Object.entries(version4).map(([name, text]) => [name.replace("/tailwindcss/", "/@acme/tw/"), text]), ); @@ -768,14 +769,14 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => { tailwindPreserveDuplicates: null }, "Invalid tailwindPreserveDuplicates value. Expected true or false, but received null.", ], - ])("a value of the wrong type is refused: %j", async (options, refusal) => { + ])("rejects a value of the wrong type: %j", async (options, message) => { const result = await format({ ...project, ...config(options), "a.jsx": input }, ["a.jsx"]); - expect(result.stderr).toBe(`error: ${refusal}\n`); + expect(result.stderr).toBe(`error: ${message}\n`); expect(result.files).toEqual([input]); expect(result.exitCode).not.toBe(0); }); - test("without it its options are unknown, and with it an option that it does not have is", async () => { + test("without it its options are unknown, and with it so is an option it doesn't have", async () => { const options = { tailwindFunctions: ["cn"], tailwindConfig: "./x.js", tailwindPreserveWhitespace: true }; const without = await format({ ...project, ".prettierrc": JSON.stringify(options), "a.jsx": input }, ["a.jsx"]); expect(without).toMatchObject({ @@ -794,13 +795,13 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => }); }); - test("another plugin beside it is still refused, by its name", async () => { + test("another plugin next to it is still rejected by name", async () => { const files = { ".prettierrc": JSON.stringify({ plugins: [plugin, "prettier-plugin-other"] }), "a.jsx": input }; const result = await format({ ...project, ...files }, ["a.jsx"], ["--log-level=log", "--check"]); expect(result.stderr).toContain("plugins that bun fmt does not include: prettier-plugin-other\n"); - // That it has no effect is said in a run that goes on without it. + // "has no effect" is only printed in a run that continues without the plugin. expect(result.stderr).not.toContain("has no effect"); - // Nothing is said about files that have not been looked at. + // Nothing is printed about files that weren't checked. expect(result.stdout).toBe("Checking formatting...\n"); expect(result.files).toEqual([input]); expect(result.exitCode).toBe(2); @@ -808,11 +809,11 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => const names = { tailwindFunctions: ["cn", "/^tw/"], tailwindAttributes: ["mine", "/^data-cls/"] }; - test("where classes are is what it says, not oxfmt", async () => { - // The lines of a file, before and after. + test("finds classes where the plugin does, not where oxfmt does", async () => { + // Each file's lines, before and after. const rows: Record = { "a.jsx": [ - // However deep in an argument or in the value of an attribute. + // At any depth in an argument or an attribute value. ['cn(other("p-4 flex"));', 'cn(other("flex p-4"));'], [';', ';'], ['cn(a === "p-4 flex" && "flex m-2");', 'cn(a === "flex p-4" && "m-2 flex");'], @@ -833,20 +834,21 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => ';', ';', ], - // To Babel a call in an optional chain is another kind of node. + // In Babel's tree, a call in an optional chain is a different kind of node. ['cn?.("p-4 flex");', ""], ['cn?.x.y("p-4 flex");', ""], - // What is added to stays apart, up to the innermost function. + // An operand of `+` keeps the space that separates it from the other operand. The search for a `+` stops at + // the innermost function. ['cn(a + (b ? " p-4 flex " : c));', 'cn(a + (b ? " flex p-4" : c));'], ['cn("x " + cn(" p-4 flex "));', 'cn("x " + cn("flex p-4"));'], ['"x " + cn` p-4 flex ` + " y";', '"x " + cn` flex p-4 ` + " y";'], - // Of the texts of a template it looks at the wrong ends, which leaves more blanks than are needed. + // It looks at the wrong ends of a template's text parts, which leaves more spaces than needed. ['cn(`x ${" p-4 flex "} y`);', 'cn(`x ${" flex p-4 "} y`);'], ['cn(`${" p-4 flex "}`);', 'cn(`${" flex p-4 "}`);'], ['cn(` ${" p-4 flex "} `);', 'cn(` ${"flex p-4"} `);'], ["cn(`p-4 flex${a}m-2 p-1`);", ""], ["cn(` p-4 flex ${a} p-1 m-2 `);", "cn(`flex p-4 ${a} m-2 p-1`);"], - // A list that was on several lines does not keep the element open. + // A class list that spanned several lines doesn't keep the element expanded. [';', ';'], ], "a.tsx": [ @@ -855,7 +857,7 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => ['(cn?.x)("p-4 flex");', ""], ['cn!("p-4 flex");', ""], ['cn("p-4 flex" as string);', 'cn("flex p-4" as string);'], - // In this tree it does not find the texts of a template. + // In this tree it doesn't find a template's text parts. ['cn(`x ${" p-4 flex "} y`);', 'cn(`x ${"flex p-4"} y`);'], ['cn(`${" p-4 flex "}`);', 'cn(`${"flex p-4"}`);'], ['cn(`x${`p-4 flex ${" p-1 m-2 "} p-2 m-3`}y`);', 'cn(`x${`flex p-4 ${"m-2 p-1"} m-3 p-2`}y`);'], @@ -890,8 +892,8 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => expect(result.exitCode).toBe(0); }); - test("a class stays apart from the text of a template that it touches", async () => { - // The code, what Bun makes of it, and what the plugin makes of it: one class of `x` and `flex`. + test("keeps a class separate from the template text next to it", async () => { + // Each row is the code, Bun's output and the plugin's output, which joins `x` and `flex` into one class. const rows: Record = { "a.tsx": [ [ @@ -930,7 +932,7 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => expect(result.exitCode).toBe(0); }); - test("with @prettier/plugin-oxc before it, it looks at the tree of that, and behind that it does nothing", async () => { + test("listed after @prettier/plugin-oxc it uses that plugin's tree, and listed before it, it does nothing", async () => { const code = 'cn?.("p-4 flex");\ncn(`x ${" p-4 flex "} y`);\n'; const sortedCode = 'cn?.("flex p-4");\ncn(`x ${" flex p-4 "} y`);\n'; const inVue = (text: string, lang = "") => `\n${text}\n`; @@ -940,7 +942,7 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => { ...project, ".prettierrc": JSON.stringify({ plugins, tailwindFunctions: ["cn"] }), ...files }, Object.keys(files), ); - // It does not read the JavaScript in HTML. + // @prettier/plugin-oxc doesn't parse the JavaScript in HTML. const byBabel = inVue('cn?.("p-4 flex");\ncn(`x ${" flex p-4 "} y`);\n'); expect(await run(["@prettier/plugin-oxc", plugin])).toMatchObject({ stderr: "", @@ -952,7 +954,7 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => }); }); - test("in Angular it looks at the texts of a template as they are written", async () => { + test("in Angular it looks at a template's text parts as written", async () => { const before = "\n"; const after = "\n"; @@ -960,8 +962,8 @@ if (now.join() !== before.join()) throw new Error("There is " + now.filter(it => expect(result).toMatchObject({ stderr: "", files: [after], exitCode: 0 }); }); - describe("the Tailwind CSS that it brings along", () => { - /** Its `createSorter`, which knows what is in order.json. A file with `reversed` in it turns the order around. */ + describe("its bundled Tailwind CSS", () => { + /** A stub of its `createSorter` that knows the classes in order.json. A file with `reversed` reverses the order. */ const withSorter = { ...installed, [`node_modules/${plugin}/package.json`]: JSON.stringify({ @@ -984,14 +986,14 @@ export async function createSorter({ configPath, stylesheetPath }) { const flipped = "module.exports = { reversed: true };\n"; test.each<[string, Record, string]>([ - ["there is no tailwindcss", config({}), sorted], + ["tailwindcss isn't installed", config({}), sorted], [ - "there is no tailwindcss, with the nearest tailwind.config.js", + "tailwindcss isn't installed, with the nearest tailwind.config.js", { ...config({}), "tailwind.config.js": flipped }, reversed, ], [ - "there is no tailwindcss, with a style sheet", + "tailwindcss isn't installed, with a style sheet", { ...config({ tailwindStylesheet: "a.css" }), "a.css": "/* reversed */" }, reversed, ], @@ -1005,7 +1007,7 @@ export async function createSorter({ configPath, stylesheetPath }) { { ...version3, ...config({ tailwindStylesheet: "a.css" }), "a.css": "/* reversed */" }, reversed, ], - ])("is asked if %s", async (_, files, expected) => { + ])("is used if %s", async (_, files, expected) => { const before = ';\n'; const result = await format({ ...withSorter, ...files, "src/a.jsx": before }, ["src/a.jsx"]); expect(result).toMatchObject({ stderr: "", files: [expected.replace('"', '"x x ')], exitCode: 0 }); @@ -1015,7 +1017,7 @@ export async function createSorter({ configPath, stylesheetPath }) { [config({})], [config({ tailwindStylesheet: "a.css" })], [config({ tailwindPackageName: "@acme/tw" })], - ])("without it and without the package, classes stay as they are: %#", async files => { + ])("without it and without the package, classes stay unsorted: %#", async files => { const result = await format({ ...files, "a.jsx": `${input}a ;\n` }, ["a.jsx"]); expect(result).toMatchObject({ stderr: "", files: [`${input}a;\n`], exitCode: 0 }); }); @@ -1035,17 +1037,17 @@ export async function createSorter({ configPath, stylesheetPath }) { ` Run bun add -d ${plugin}, which brings its own`, ], ], - ])("has to be installed for that: %#", async (files, said) => { + ])("has to be installed for a mismatched option and version: %#", async (files, lines) => { const result = await format({ ...files, "a.jsx": input }, ["a.jsx"]); - for (const line of said) + for (const line of lines) expect(result.stderr).toContain(line.startsWith(" ") ? `\n${line}\n` : `error: sortTailwindcss: ${line}`); expect(result.files).toEqual([input]); expect(result.exitCode).toBe(2); }); }); - // Each stream has what Prettier's has. - test("--check says on standard output that an error occurred, and on standard error what it is", async () => { + // Each stream gets the same text as in Prettier. + test("--check prints that an error occurred to stdout and the error itself to stderr", async () => { const files = { ...config({}), "tailwind.config.js": 'throw new Error("boom");\n', "a.jsx": input }; using dir = tempDir("bun-format-tailwind", { ...version3, ...installed, ...files }); const result = await formatIn(String(dir), [], ["--log-level=log", "--check", "a.jsx"]); @@ -1061,7 +1063,7 @@ export async function createSorter({ configPath, stylesheetPath }) { expect(result.exitCode).toBe(2); }); - test("a flag or [fmt] counts for more", async () => { + test("a flag or [fmt] takes precedence", async () => { const files = { ...config({}), "bunfig.toml": '[fmt.sortTailwindcss]\nfunctions = ["mine"]\n' }; const result = await format({ ...project, ...files, "a.jsx": 'mine("p-4 flex");\n' }, ["a.jsx"]); expect(result).toMatchObject({ stderr: "", files: ['mine("flex p-4");\n'], exitCode: 0 }); diff --git a/test/cli/format/toml-layout.test.ts b/test/cli/format/toml-layout.test.ts index 2b7144ca81d3..ee6ff249d9c3 100644 --- a/test/cli/format/toml-layout.test.ts +++ b/test/cli/format/toml-layout.test.ts @@ -21,7 +21,7 @@ async function run(cwd: string, args: string[]) { const cases: [name: string, input: string, output: string][] = [ [ - "keeps a hugged table with a trailing comment as it is", + "leaves a hugged table with a trailing comment unchanged", `[lint.rules] "prefer-const" = ["warn", { destructuring = "any", # "any" or "all" @@ -108,7 +108,7 @@ b=false}] `, ], [ - "keeps a table that only holds a comment", + "keeps a table that only contains a comment", `a = { # nothing } @@ -307,7 +307,7 @@ d = [ # first `, ], [ - "doesn't take a # in a key or a string for a comment", + "doesn't mistake a # in a key or a string for a comment", `a = { "b#c".d = "# not a comment", # comment e = '#', @@ -320,7 +320,7 @@ d = [ # first `, ], [ - "keeps a multi-line string in a table as it is", + "leaves a multi-line string in a table unchanged", `a = { b = """ x # y @@ -500,14 +500,14 @@ describe.concurrent("a table with a comment", () => { expect(result.exitCode).toBe(0); }); - // The table, what Bun makes of it, and what oxfmt 0.72 makes of it. + // Each row is the table, Bun's output and oxfmt 0.72's output. test.each([ ["a = { # c\n b = 1 }\n", "a = { # c\n b = 1,\n}\n", "a = { # c b = 1 }\n"], ["a = { b = 1 # c\n, d = 2 }\n", "a = {\n b = 1, # c\n d = 2,\n}\n", "a = { b = 1 # c, d = 2 }\n"], ["a = { b = 1,\n # c\n d = 2 }\n", "a = {\n b = 1,\n # c\n d = 2,\n}\n", "a = { b = 1 # c, d = 2 }\n"], ["a = { b = 1, d = 2 # c\n }\n", "a = {\n b = 1,\n d = 2, # c\n}\n", "a = { b = 1, d = 2 # c }\n"], - ])("wherever the comment is: %j", async (before, after, ofOxfmt) => { - expect(after).not.toBe(ofOxfmt); + ])("is expanded wherever the comment is: %j", async (before, after, byOxfmt) => { + expect(after).not.toBe(byOxfmt); using dir = tempDir("bun-format-toml", { ".oxfmtrc.json": "{}\n", "a.toml": before, "b.toml": after }); const checked = await run(String(dir), ["--debug-check", "."]); expect(checked.stderr).toBe(""); @@ -519,7 +519,7 @@ describe.concurrent("a table with a comment", () => { expect(result.exitCode).toBe(0); }); - test("--debug-check has nothing to say about it", async () => { + test("passes --debug-check", async () => { using dir = tempDir("bun-format-toml", { ".oxfmtrc.json": "{}\n", "a.toml": commented }); const result = await run(String(dir), ["--debug-check", "."]); expect(result.stderr).toBe(""); diff --git a/test/cli/format/toml.test.ts b/test/cli/format/toml.test.ts index d2610fb41a42..ccdb609725d3 100644 --- a/test/cli/format/toml.test.ts +++ b/test/cli/format/toml.test.ts @@ -1,4 +1,4 @@ -// TOML under a configuration file of oxfmt. What is printed for which text is in `own/cases/toml`, judged by oxfmt. +// Tests for TOML under an oxfmt config. The expected output for each input is in `own/cases/toml`, recorded from oxfmt. import { afterAll, expect, test } from "bun:test"; import { bunEnv, bunExe, tempDir } from "harness"; import { readFileSync } from "node:fs"; @@ -21,7 +21,7 @@ async function format(files: Record, config: object, args: strin return { files: Object.fromEntries(after), stderr, exitCode }; } -test.concurrent("printWidth, useTabs, trailingComma and endOfLine count", async () => { +test.concurrent("respects printWidth, useTabs, trailingComma and endOfLine", async () => { const config = { printWidth: 20, useTabs: true, trailingComma: "none", endOfLine: "crlf" }; const result = await format({ "a.toml": 'a = ["aaaaaaaa", "bbbbbbbb"]\n' }, config); expect(result.files["a.toml"]).toBe('a = [\r\n\t"aaaaaaaa",\r\n\t"bbbbbbbb"\r\n]\r\n'); @@ -29,7 +29,7 @@ test.concurrent("printWidth, useTabs, trailingComma and endOfLine count", async }); test.concurrent( - "a file with \\r\\n is read as one with \\n, but a string of several lines stays as it is written", + "reads a file with \\r\\n like one with \\n, but leaves the line breaks in a multi-line string unchanged", async () => { const text = 'a = 1\r\n\r\n\r\n\r\n\r\nb = [\r\n 1, # c\r\n 2\r\n]\r\ns = """\r\nx\r\n"""\r\n'; const lf = await format({ "a.toml": text }, {}); @@ -39,7 +39,7 @@ test.concurrent( }, ); -test.concurrent("the names that oxfmt takes for TOML, and the lock files that it never touches", async () => { +test.concurrent("formats the file names that oxfmt treats as TOML, but never lock files", async () => { const names = ["a.toml", "b.toml.example", "Pipfile", "Cargo.toml.orig"]; const locks = ["Cargo.lock", "Gopkg.lock", "pdm.lock", "poetry.lock", "uv.lock"]; const result = await format(Object.fromEntries([...names, ...locks].map(name => [name, "a = 1\n"])), {}); @@ -49,7 +49,7 @@ test.concurrent("the names that oxfmt takes for TOML, and the lock files that it expect(result.exitCode).toBe(0); }); -test.concurrent("numbers, dates, strings and keys stay as they are written, whatever their size", async () => { +test.concurrent("keeps numbers, dates, strings and keys as written, whatever their size", async () => { const text = 'big = 123456789012345678901234567890\nhex=0xDEAD_beef\n"a b" . \'c\'=1979-05-27 07:32:00.123456789123\ns = "\\u00e9\\t"\n'; const result = await format({ "a.toml": text }, {}); @@ -59,7 +59,7 @@ test.concurrent("numbers, dates, strings and keys stay as they are written, what expect(result.exitCode).toBe(0); }); -test.concurrent("what is nested too deeply is left as it is, and that is said", async () => { +test.concurrent("reports a file that's nested too deeply and leaves it unchanged", async () => { const files = { "ok.toml": `a = ${"[".repeat(128)}${"]".repeat(128)}\n`, "huge.toml": `a = ${"[".repeat(200_000)}${"]".repeat(200_000)}\n`, diff --git a/test/cli/format/words.test.ts b/test/cli/format/words.test.ts index fbf8e253f70a..03776c09682a 100644 --- a/test/cli/format/words.test.ts +++ b/test/cli/format/words.test.ts @@ -82,7 +82,7 @@ describe.concurrent("bun fmt --check", () => { }); }); - test("--log-level", async () => { + test("--log-level silent and error print nothing", async () => { const files = { "a.js": ugly, "b.js": formatted }; const [silent, error, warn] = await Promise.all( ["silent", "error", "warn"].map(level => format(files, ["--check", "--log-level", level])), @@ -132,27 +132,27 @@ describe.concurrent("bun fmt --check", () => { describe.concurrent("bun fmt", () => { test("errors start with `error:`, with a .prettierrc too", async () => { - const [missing, ofPrettier] = await Promise.all([ + const [missing, withPrettier] = await Promise.all([ format({ "a.js": formatted }, ["nothing.js"]), format({ "a.js": formatted, ".prettierrc": "{}\n" }, ["nothing.js"]), ]); expect(missing.stderr).toStartWith('error: No files matching the pattern were found: "nothing.js".\n'); expect(missing.exitCode).toBe(2); - expect(ofPrettier.stderr).toStartWith('error: No files matching the pattern were found: "nothing.js".\n'); - expect(ofPrettier.exitCode).toBe(2); + expect(withPrettier.stderr).toStartWith('error: No files matching the pattern were found: "nothing.js".\n'); + expect(withPrettier.exitCode).toBe(2); }); test("errors and warnings about flags get the same prefixes", async () => { const flags = ["--plugin", "prettier-plugin-x"]; - const [refused, allowed, ofPrettier] = await Promise.all([ + const [rejected, allowed, withPrettier] = await Promise.all([ format({ "a.js": formatted }, flags), format({ "a.js": formatted }, [...flags, "--allow-unsupported"]), format({ "a.js": formatted, ".prettierrc": "{}\n" }, flags), ]); - expect(refused.stderr).toStartWith("error: bun fmt does not include the plugin prettier-plugin-x\n"); + expect(rejected.stderr).toStartWith("error: bun fmt does not include the plugin prettier-plugin-x\n"); expect(allowed.stderr).toStartWith("warn: --plugin has no effect "); - expect(ofPrettier.stderr).toStartWith("error: bun fmt does not include the plugin prettier-plugin-x\n"); - expect([refused.exitCode, allowed.exitCode, ofPrettier.exitCode]).toEqual([2, 0, 2]); + expect(withPrettier.stderr).toStartWith("error: bun fmt does not include the plugin prettier-plugin-x\n"); + expect([rejected.exitCode, allowed.exitCode, withPrettier.exitCode]).toEqual([2, 0, 2]); }); test("lists the files it writes and counts them", async () => { diff --git a/test/cli/hot/hot.test.ts b/test/cli/hot/hot.test.ts index 83468a5f65d4..fe2c1cb2da30 100644 --- a/test/cli/hot/hot.test.ts +++ b/test/cli/hot/hot.test.ts @@ -1,7 +1,18 @@ import { spawn } from "bun"; +import { dlopen } from "bun:ffi"; import { beforeEach, expect, it } from "bun:test"; -import { copyFileSync, cpSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "fs"; -import { bunEnv, bunExe, isDebug, isWindows, tempDir, tmpdirSync, waitForFileToExist } from "harness"; +import { + copyFileSync, + cpSync, + mkdirSync, + readFileSync, + realpathSync, + renameSync, + rmSync, + unlinkSync, + writeFileSync, +} from "fs"; +import { bunEnv, bunExe, isASAN, isDebug, isLinux, isWindows, tempDir, tmpdirSync, waitForFileToExist } from "harness"; import { join } from "path"; const timeout = isDebug ? Infinity : 10_000; @@ -929,3 +940,396 @@ it.each([ stderr: [], }); }); + +/** Returns a function that resolves to `true` once the stream's text includes `wanted`, or to the full text at EOF. */ +function follow(stream: ReadableStream) { + const reader = stream.getReader(); + let text = ""; + return async (wanted: string) => { + while (!text.includes(wanted)) { + const { value, done } = await reader.read(); + if (done) return text; + text += Buffer.from(value).toString(); + } + return true; + }; +} + +/** Windows only. Suspends the process while `change` runs, so all of its file events are queued on resume. */ +function whileSuspended(pid: number, change: () => void) { + const kernel32 = dlopen("kernel32.dll", { + OpenProcess: { args: ["u32", "i32", "u32"], returns: "ptr" }, + CloseHandle: { args: ["ptr"], returns: "i32" }, + }); + const ntdll = dlopen("ntdll.dll", { + NtSuspendProcess: { args: ["ptr"], returns: "i32" }, + NtResumeProcess: { args: ["ptr"], returns: "i32" }, + }); + const PROCESS_SUSPEND_RESUME = 0x0800; + const handle = kernel32.symbols.OpenProcess(PROCESS_SUSPEND_RESUME, 0, pid); + expect(handle).not.toBeNull(); + let resumed: number; + try { + expect(ntdll.symbols.NtSuspendProcess(handle)).toBe(0); + change(); + } finally { + resumed = ntdll.symbols.NtResumeProcess(handle); + kernel32.symbols.CloseHandle(handle); + kernel32.close(); + ntdll.close(); + } + expect(resumed).toBe(0); +} + +it.if(isWindows)("notices a deleted import in a burst of file events", async () => { + using dir = tempDir("hot-burst", { + "main.js": `import "./mods/a.js";\nimport "./mods/b.js";\nconsole.log("loaded");\n`, + "mods/a.js": "export {};", + "mods/b.js": "export {};", + "other/keep": "", + }); + const root = String(dir); + await using runner = spawn({ + cmd: [bunExe(), "--hot", "--no-clear-screen", "main.js"], + env: bunEnv, + cwd: root, + stdout: "pipe", + stderr: "pipe", + stdin: "ignore", + }); + const stdout = follow(runner.stdout); + const stderr = follow(runner.stderr); + expect(await stdout("loaded")).toBe(true); + + whileSuspended(runner.pid, () => { + // The pending read completes with only the first change. + writeFileSync(join(root, "other", "first"), ""); + unlinkSync(join(root, "mods", "b.js")); + for (let i = 0; i < 200; i++) writeFileSync(join(root, "other", String(i)), ""); + }); + expect(await stderr("Cannot find module './mods/b.js'")).toBe(true); + + writeFileSync(join(root, "main.js"), `import "./mods/a.js";\nconsole.log("reloaded");\n`); + expect(await stdout("reloaded")).toBe(true); +}); + +it.if(isWindows)("dev server survives a burst of file events that includes a deleted import", async () => { + // The watcher dispatches at most 128 events per batch, so use more files than that. + const count = 150; + const main = (from: number, log: string) => + Array.from({ length: count - from }, (_, i) => `import "./mods/${from + i}.ts";\n`).join("") + + `console.log(${JSON.stringify(log)});\n`; + using dir = tempDir("dev-server-burst", { + "index.html": ``, + "main.ts": main(0, "first bundle"), + ...Object.fromEntries(Array.from({ length: count }, (_, i) => [`mods/${i}.ts`, `console.log(${i});`])), + "other/keep": "", + "server.ts": ` + import html from "./index.html"; + const server = Bun.serve({ port: 0, development: true, routes: { "/": html } }); + await Bun.write("url", server.url.href); + console.log("listening"); + `, + }); + const root = String(dir); + await using runner = spawn({ + cmd: [bunExe(), "server.ts"], + env: bunEnv, + cwd: root, + stdout: "pipe", + stderr: "inherit", + stdin: "ignore", + }); + expect(await follow(runner.stdout)("listening")).toBe(true); + const url = readFileSync(join(root, "url"), "utf8"); + const bundle = async () => { + // A failed build's page has no script, and the build fails while main.ts imports the deleted file. + const src = /src="([^"]+)"/.exec(await (await fetch(url)).text())?.[1]; + return src ? await (await fetch(new URL(src, url))).text() : ""; + }; + expect(await bundle()).toContain("first bundle"); + + whileSuspended(runner.pid, () => { + // The pending read completes with only the first change. + writeFileSync(join(root, "other", "first"), ""); + unlinkSync(join(root, "mods", "0.ts")); + for (let i = 1; i < count; i++) writeFileSync(join(root, "mods", `${i}.ts`), `console.log(${i}, "again");`); + }); + + writeFileSync(join(root, "main.ts"), main(1, "second bundle")); + while (!(await bundle()).includes("second bundle")); +}); + +// Other platforms evict the deleted import and stop watching its path, so "second" is never printed. +it.todoIf(!isWindows)("reloads when a deleted import is recreated", async () => { + using dir = tempDir("hot-import-back", { + "main.js": `import "./imported.js";\n`, + "imported.js": `console.log("first");`, + }); + const root = String(dir); + await using runner = spawn({ + cmd: [bunExe(), "--hot", "--no-clear-screen", "main.js"], + env: bunEnv, + cwd: root, + stdout: "pipe", + stderr: "pipe", + stdin: "ignore", + }); + const stdout = follow(runner.stdout); + const stderr = follow(runner.stderr); + expect(await stdout("first")).toBe(true); + + unlinkSync(join(root, "imported.js")); + expect(await stderr("Cannot find module './imported.js'")).toBe(true); + + writeFileSync(join(root, "imported.js"), `console.log("second");`); + expect(await stdout("second")).toBe(true); +}); + +// The Windows watcher never reads the cached listing. +it.skipIf(isWindows)("survives a directory event for a folder whose cached listing failed to read", async () => { + using dir = tempDir("hot-dir-read-error", { + "trace.log": "", + "src/lib/a.ts": `export {};`, + "src/fence/f.ts": `export {};`, + "src/main.ts": ` + import "./lib/a.ts"; + import "./fence/f.ts"; + import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"; + // The watch follows the renamed folder. Listing "lib" now fails with ENOTDIR. + renameSync("lib", "lib.away"); + writeFileSync("lib", ""); + // The watcher logs each batch before handling it, so the first batch is done once the second is logged. + const trace = process.env.BUN_WATCHER_TRACE; + for (let i = 0; i < 2; i++) { + const from = statSync(trace).size; + mkdirSync("fence/" + i); + while (!readFileSync(trace, "latin1").slice(from).includes("/fence/")) await Bun.sleep(1); + } + await import("./lib/b.ts").catch(() => console.log("import failed")); + writeFileSync("lib.away/c.ts", ""); + console.log("ready"); + setInterval(() => {}, 1e6); + `, + }); + const cwd = join(String(dir), "src"); + await using runner = spawn({ + cmd: [bunExe(), "--hot", "--no-clear-screen", "main.ts"], + env: { ...bunEnv, BUN_WATCHER_TRACE: join(String(dir), "trace.log") }, + cwd, + stdout: "pipe", + stderr: "inherit", + stdin: "ignore", + }); + const stdout = follow(runner.stdout); + expect(await stdout("import failed\nready")).toBe(true); + + writeFileSync(join(cwd, "main.ts"), `console.log("reloaded");\nprocess.exit(0);\n`); + expect(await stdout("reloaded")).toBe(true); + expect(await runner.exited).toBe(0); +}); + +// Only inotify reports the changed entry's name, and PATH_MAX is 1024 on macOS. +it.skipIf(!isLinux).each([ + ["a new file whose path is longer than PATH_MAX", Buffer.alloc(247, "n") + ".ts"], + ["an import whose path is PATH_MAX long", Buffer.alloc(245, "n") + ".png"], +])("survives %s", async (_, name) => { + using dir = tempDir("hot-long-path", {}); + // Folder + separator + name is 4097 bytes for the first name and 4096 bytes for the second. + const folderLength = 3846; + let cwd = realpathSync(String(dir)); + while (folderLength - cwd.length > 256) cwd = join(cwd, Buffer.alloc(200, "d").toString()); + cwd = join(cwd, Buffer.alloc(folderLength - cwd.length - 1, "e").toString()); + mkdirSync(cwd, { recursive: true }); + // The absolute path is too long for a syscall, so use a relative path. + const create = `require("node:fs").writeFileSync("${name}", "");`; + const isImport = name.endsWith(".png"); + if (isImport) { + await using setup = spawn({ cmd: [bunExe(), "-e", create], cwd, env: bunEnv }); + expect(await setup.exited).toBe(0); + } + writeFileSync( + join(cwd, "main.ts"), + `${isImport ? `import "./${name}";` : create}\nconsole.log("ready");\nsetInterval(() => {}, 1e6);\n`, + ); + await using runner = spawn({ + cmd: [bunExe(), "--hot", "--no-clear-screen", "main.ts"], + env: bunEnv, + cwd, + stdout: "pipe", + stderr: "inherit", + stdin: "ignore", + }); + const stdout = follow(runner.stdout); + expect(await stdout("ready")).toBe(true); + + writeFileSync(join(cwd, "main.ts"), `console.log("reloaded");\nprocess.exit(0);\n`); + expect(await stdout("reloaded")).toBe(true); + expect(await runner.exited).toBe(0); +}); + +// BUN_DESTRUCT_VM_ON_EXIT frees the VM at exit. The writes make sure the watcher thread is busy at that point. +it.skipIf(!isASAN)("stops the file watcher thread before the VM is freed at exit", async () => { + async function run() { + using dir = tempDir("hot-exit", { + "main.js": ` + import "./dep.js"; + globalThis.loads = (globalThis.loads ?? 0) + 1; + if (globalThis.loads === 3) process.exit(0); + `, + "dep.js": `export default 0;`, + }); + await using runner = spawn({ + cmd: [bunExe(), "--hot", "--no-clear-screen", "main.js"], + env: { ...bunEnv, BUN_DESTRUCT_VM_ON_EXIT: "1" }, + cwd: String(dir), + stdout: "ignore", + stderr: "inherit", + stdin: "ignore", + }); + let exited = false; + runner.exited.then(() => (exited = true)); + for (let i = 0; !exited; i++) { + for (let j = 0; j < 20; j++) writeFileSync(join(String(dir), "dep.js"), `export default ${i};`); + await new Promise(resolve => setImmediate(resolve)); + } + return await runner.exited; + } + expect(await Promise.all([run(), run(), run(), run()])).toEqual([0, 0, 0, 0]); +}); + +// --hot and --watch intern a module's transpiled text in the VM. +it("throws ERR_STRING_TOO_LONG for a module whose transpiled text exceeds the string limit", async () => { + using dir = tempDir("hot-string-limit", { + "big.cjs": `const s = ${JSON.stringify(Buffer.alloc(200 * 1024, "x").toString())};\nmodule.exports = { len: s.length };\n`, + "small.cjs": `module.exports = { ok: 2 };\n`, + "entry.cjs": ` + let big; + try { + big = "loaded:" + require("./big.cjs").len; + } catch (e) { + big = "caught:" + (e?.code ?? e?.name); + } + console.log(JSON.stringify({ big, small: require("./small.cjs").ok })); + process.exit(0); + `, + }); + await using proc = spawn({ + cmd: [bunExe(), "--hot", "--no-clear-screen", "entry.cjs"], + cwd: String(dir), + env: { ...bunEnv, BUN_FEATURE_FLAG_SYNTHETIC_MEMORY_LIMIT: String(64 * 1024) }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect({ stdout, stderr, exitCode }).toEqual({ + stdout: JSON.stringify({ big: "caught:ERR_STRING_TOO_LONG", small: 2 }) + "\n", + stderr: "", + exitCode: 0, + }); +}); + +it.each(["--hot", "--watch"])("%s keeps running and reloading after uncaught exceptions", async flag => { + using dir = tempDir("hot-uncaught", { + "main.js": ` + const server = Bun.serve({ + port: 0, + fetch(req) { + queueMicrotask(() => { + throw new Error("from " + new URL(req.url).pathname); + }); + return new Response("ok"); + }, + }); + (async () => { + for (let i = 1; i <= 2; i++) await fetch(new URL("/" + i, server.url)); + console.log("still running"); + })(); + // The timers of a run stop at its first uncaught exception. On Windows, libuv goes on firing them. + if (process.platform !== "win32") setTimeout(() => process.exit(1), 1); + throw new Error("from the entry point"); + `, + }); + await using runner = spawn({ + cmd: [bunExe(), flag, "--no-clear-screen", "main.js"], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + stdin: "ignore", + }); + const stdout = follow(runner.stdout); + const stderr = follow(runner.stderr); + expect(await stdout("still running")).toBe(true); + expect(await stderr("error: from /2")).toBe(true); + + writeFileSync( + join(String(dir), "main.js"), + `setTimeout(() => {\n console.log("timer fired");\n process.exit(0);\n}, 1);\n`, + ); + expect(await stdout("timer fired")).toBe(true); + expect(await runner.exited).toBe(0); +}); + +it.each([ + [ + "a throw", + `setInterval(() => console.log("failed run's interval in run " + globalThis.run), 1);\nthrow new Error("the bug");`, + ], + ["a syntax error", `const = ;`], +])("--hot keeps the timers of earlier runs when a save fixes %s", async (_, bug) => { + const source = (run: number, tail: string) => ` + globalThis.run = ${run}; + globalThis.kept ??= setInterval(() => console.log("kept interval in run " + globalThis.run), 1); + require("fs").watchFile("watched", { interval: 1 }, () => { + console.log("watchFile listener of run ${run}"); + if (${run} === 3) process.exit(0); + }); + ${tail} + `; + using dir = tempDir("hot-kept-timers", { "main.js": source(1, ""), "watched": "" }); + await using runner = spawn({ + cmd: [bunExe(), "--hot", "--no-clear-screen", "main.js"], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + stdin: "ignore", + }); + const stdout = follow(runner.stdout); + const stderr = follow(runner.stderr); + expect(await stdout("kept interval in run 1")).toBe(true); + + writeFileSync(join(String(dir), "main.js"), source(2, bug)); + expect(await stderr("error: ")).toBe(true); + + writeFileSync(join(String(dir), "main.js"), source(3, "")); + expect(await stdout("kept interval in run 3")).toBe(true); + writeFileSync(join(String(dir), "watched"), "changed"); + expect(await stdout("watchFile listener of run 3")).toBe(true); + expect(await stdout("failed run's interval in run 3")).not.toBe(true); + expect(await runner.exited).toBe(0); +}); + +it("--hot does not emit beforeExit to the listeners of a failed run", async () => { + using dir = tempDir("hot-failed-before-exit", { + "main.js": `process.on("beforeExit", () => process.exit(1));\nthrow new Error("the bug");`, + }); + await using runner = spawn({ + cmd: [bunExe(), "--hot", "--no-clear-screen", "main.js"], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + stdin: "ignore", + }); + const stdout = follow(runner.stdout); + const stderr = follow(runner.stderr); + expect(await stderr("error: the bug")).toBe(true); + + writeFileSync(join(String(dir), "main.js"), `console.log("fixed");`); + expect(await stdout("fixed")).toBe(true); + writeFileSync(join(String(dir), "main.js"), `console.log("still running");\nprocess.exit();`); + expect(await stdout("still running")).toBe(true); + expect(await runner.exited).toBe(0); +}); diff --git a/test/cli/init/init.test.ts b/test/cli/init/init.test.ts index 113be9d6abcc..62c8471b61fd 100644 --- a/test/cli/init/init.test.ts +++ b/test/cli/init/init.test.ts @@ -1,6 +1,6 @@ import { beforeAll, describe, expect, test } from "bun:test"; import fs, { readdirSync } from "fs"; -import { bunEnv, bunExe, isWindows, tempDir, tempDirWithFiles } from "harness"; +import { bunEnv, bunExe, isCanary, isWindows, tempDir, tempDirWithFiles } from "harness"; import path from "path"; // Whether `bun init` emits CLAUDE.md depends on a `claude` binary being on @@ -60,8 +60,10 @@ const initEnv = { ...bunEnv, BUN_AGENT_RULE_DISABLED: "1" }; expect(readme).toInclude("v" + Bun.version.replaceAll("-debug", "")); expect(readme).toInclude("index.ts"); expect(readme).toInclude("bun check"); - expect(readme).toInclude("`bun lint`"); + // A release build has no `bun lint`. + expect(readme.includes("`bun lint`")).toBe(isCanary); expect(readme).toInclude("`bun fmt`"); + expect(readme).not.toInclude("{["); expect(fs.existsSync(path.join(temp, "index.ts"))).toBe(true); expect(fs.existsSync(path.join(temp, ".gitignore"))).toBe(true); @@ -416,7 +418,7 @@ const initEnv = { ...bunEnv, BUN_AGENT_RULE_DISABLED: "1" }; expect(fs.existsSync(path.join(temp, "src/components/ui"))).toBe(true); }, 30_000); - test.each(["--react", "--react=tailwind", "--react=shadcn"])( + test.skipIf(!isCanary).each(["--react", "--react=tailwind", "--react=shadcn"])( "bun init %s writes the same [lint] section to bunfig.toml as bun lint --init", async flag => { await using temp = tempDir("bun-init-lint-section", { "alone/a.js": "" }); @@ -498,19 +500,21 @@ const initEnv = { ...bunEnv, BUN_AGENT_RULE_DISABLED: "1" }; expect({ checkStdout, checkStderr, checkExited }).toMatchObject({ checkStdout: "", checkExited: 0 }); // `bun lint` reports nothing, not even a warning, and `bun fmt` has nothing to change. - await using lint = Bun.spawn({ - cmd: [bunExe(), "lint", "-f", "json"], - cwd: temp, - stdio: ["ignore", "pipe", "pipe"], - env: bunEnv, - }); - const [lintStdout, lintStderr, lintExited] = await Promise.all([ - lint.stdout.text(), - lint.stderr.text(), - lint.exited, - ]); - const problems = JSON.parse(lintStdout).flatMap((file: { messages: unknown[] }) => file.messages); - expect({ problems, lintStderr, lintExited }).toMatchObject({ problems: [], lintExited: 0 }); + if (isCanary) { + await using lint = Bun.spawn({ + cmd: [bunExe(), "lint", "-f", "json"], + cwd: temp, + stdio: ["ignore", "pipe", "pipe"], + env: bunEnv, + }); + const [lintStdout, lintStderr, lintExited] = await Promise.all([ + lint.stdout.text(), + lint.stderr.text(), + lint.exited, + ]); + const problems = JSON.parse(lintStdout).flatMap((file: { messages: unknown[] }) => file.messages); + expect({ problems, lintStderr, lintExited }).toMatchObject({ problems: [], lintExited: 0 }); + } await using format = Bun.spawn({ cmd: [bunExe(), "fmt", "--check"], diff --git a/test/cli/inspect/inspect.test.ts b/test/cli/inspect/inspect.test.ts index 2469f5756975..0e3e7eb58fb1 100644 --- a/test/cli/inspect/inspect.test.ts +++ b/test/cli/inspect/inspect.test.ts @@ -603,3 +603,71 @@ test("error.stack doesnt lose frames", () => { // We allow it to differ by the existence of as a string. But that's it. expect(no.split("\n").slice(0, -2).join("\n").trim()).toBe(yes.split("\n").slice(0, -2).join("\n").trim()); }); + +test("LifecycleReporter.getModuleGraph reports an empty argv when process.argv isn't an array", async () => { + await using child = spawn({ + cmd: [bunExe(), "--inspect=ws://127.0.0.1:0/", "-e", "setInterval(() => {}, 1000);"], + env: bunEnv, + stdout: "ignore", + stderr: "pipe", + }); + + let stderr = ""; + let url: string | undefined; + const decoder = new TextDecoder(); + for await (const chunk of child.stderr as ReadableStream) { + stderr += decoder.decode(chunk); + url = stderr.match(/(ws:\/\/[^\s]+)/)?.[1]; + if (url) break; + } + if (!url) throw new Error(`Unable to find the inspector URL in:\n${stderr}`); + + type Reply = { result?: any; error?: { message: string } }; + const pending = new Map void>(); + // A crash closes the socket. Resolve instead of rejecting so the failure shows up in the snapshot below. + const closed = Promise.withResolvers(); + const opened = Promise.withResolvers(); + const webSocket = new WebSocket(url); + webSocket.addEventListener("open", () => opened.resolve({})); + webSocket.addEventListener("close", () => closed.resolve({ error: { message: "the inspector closed the socket" } })); + webSocket.addEventListener("error", () => closed.resolve({ error: { message: "the inspector socket failed" } })); + webSocket.addEventListener("message", ({ data }) => { + const reply: Reply & { id: number } = JSON.parse(data.toString()); + pending.get(reply.id)?.(reply); + pending.delete(reply.id); + }); + + let nextId = 1; + function send(method: string, params: object = {}): Promise { + const id = nextId++; + const { promise, resolve } = Promise.withResolvers(); + pending.set(id, resolve); + webSocket.send(JSON.stringify({ id, method, params })); + return Promise.race([promise, closed.promise]); + } + + expect(await Promise.race([opened.promise, closed.promise])).toEqual({}); + + const argv: Record = {}; + for (const expression of ["undefined", "0", `"abc"`, "{}", `["a", "b"]`]) { + const assigned = await send("Runtime.evaluate", { expression: `process.argv = ${expression}` }); + const graph = assigned.error ? assigned : await send("LifecycleReporter.getModuleGraph"); + argv[expression] = graph.error?.message ?? graph.result.argv; + } + + expect(argv).toMatchInlineSnapshot(` + { + "\\"abc\\"": [], + "0": [], + "[\\"a\\", \\"b\\"]": [ + "a", + "b", + ], + "undefined": [], + "{}": [], + } + `); + + expect(child.exitCode).toBe(null); + webSocket.close(); +}); diff --git a/test/cli/install/bad-workspace.test.ts b/test/cli/install/bad-workspace.test.ts index c050ff71c1aa..3fcf4715832d 100644 --- a/test/cli/install/bad-workspace.test.ts +++ b/test/cli/install/bad-workspace.test.ts @@ -553,7 +553,7 @@ describe.concurrent.each([ expect(await runBun(command.split(" "), project.member)).toEqual(before); }); - test("bun install reports that package.json, and does not install the member as a project of its own", async () => { + test("bun install reports that package.json, and doesn't install the workspace as a separate project", async () => { using project = await installThenBreakSibling(); project.breakSibling(); @@ -586,8 +586,8 @@ describe.concurrent.skipIf(isWindows)("package.json in a sticky, shared director "shared/proj/dep/package.json": dep, }; - // `shared/sub` has no package.json. The walk goes on above a manifest it ignores: the empty - // project at the top keeps it inside the fixture. + // `shared/sub` has no package.json. The walk continues above a manifest that it ignores, and the empty project at the + // top keeps it inside the fixture. const projectFiles = { "package.json": JSON.stringify({ name: "fence", version: "0.0.0" }), "shared/package.json": JSON.stringify({ diff --git a/test/cli/install/bun-add-catalog.test.ts b/test/cli/install/bun-add-catalog.test.ts index 713a44618fb5..f9e26bf4b2c5 100644 --- a/test/cli/install/bun-add-catalog.test.ts +++ b/test/cli/install/bun-add-catalog.test.ts @@ -261,7 +261,7 @@ describe.concurrent("bun add --catalog", () => { expect((await dir.lock()).catalog).toStrictEqual({ "a-dep": "^1.0.10", "no-deps": "^2.0.0" }); }); - for (const flag of ["--catalog=", "--catalog= "]) { + for (const flag of ["--catalog=", "--catalog= ", "--save-catalog"]) { test(`${JSON.stringify(flag)} is the default catalog`, async () => { const dir = await createDir(workspacesObject()); @@ -277,22 +277,6 @@ describe.concurrent("bun add --catalog", () => { await dir.installSavesNothing(); }); } - - test("pnpm's --save-catalog is rejected", async () => { - const root = pretty(workspacesObject({ catalog: {} })); - const dir = await createDir(root); - const pkg1Before = await dir.pkg1Text(); - - expect(await dir.add(dir.pkg1Dir, "no-deps", "--save-catalog")).toEqual({ - stdout: "", - stderr: "error: bun add has no --save-catalog flag.\nnote: Run 'bun add --help' for more information\n", - exitCode: 1, - }); - - expect(await dir.pkg1Text()).toBe(pkg1Before); - expect(await dir.rootText()).toBe(root); - expect(await dir.lockExists()).toBeFalse(); - }); }); describe("catalog literal", () => { @@ -706,7 +690,7 @@ describe.concurrent("bun add --catalog", () => { const plainPkg1 = await plain.pkg1(); const catalogPkg1 = await catalog.pkg1(); expect(Object.keys(catalogPkg1)).toStrictEqual(Object.keys(plainPkg1)); - // The peer entry is left alone; --dev adds a devDependencies entry next to it. + // The peer entry isn't changed. --dev adds a devDependencies entry next to it. expect(plainPkg1).toStrictEqual({ name: "pkg1", peerDependencies: { "no-deps": ">=1" }, @@ -841,7 +825,7 @@ describe.concurrent("bun add --catalog", () => { }); }); - describe("leading whitespace in what a package.json declares", () => { + describe("leading whitespace in a package.json value", () => { test("the target's named reference stays in that catalog", async () => { const pkg1 = pretty({ name: "pkg1", dependencies: { "no-deps": " catalog:testing" } }); const dir = await createDir(workspacesObject({ catalogs: { testing: { "no-deps": "1.0.0" } } }), pkg1); diff --git a/test/cli/install/bun-add-filter.test.ts b/test/cli/install/bun-add-filter.test.ts index 6616971eac67..e3b8a3a9289a 100644 --- a/test/cli/install/bun-add-filter.test.ts +++ b/test/cli/install/bun-add-filter.test.ts @@ -1044,19 +1044,16 @@ test.concurrent("add/remove --filter updates bun.lock for a workspace outside th const root = join(String(dir), "root"); const x = () => file(join(String(dir), "x", "package.json")).json(); const lockedX = async () => (await lockfileJson(root)).workspaces["../x"]; - async function runOk(args: string[], note = "") { + async function runOk(args: string[]) { const { stderr, exitCode } = await run(args, String(dir), { cwd: root, linker: "hoisted" }); - expect(stderr).toBe(note + "Saved lockfile\n"); + expect(stderr).toBe("Saved lockfile\n"); expect(exitCode).toBe(0); } await runOk(["install"]); expect(await lockedX()).toStrictEqual({ name: "x", version: "1.0.0" }); - await runOk( - ["add", "--filter", "x", "y@workspace:*"], - 'note: skipping dependencies and scripts of 1 workspace outside the project: "../x"\n', - ); + await runOk(["add", "--filter", "x", "y@workspace:*"]); expect(await x()).toStrictEqual({ name: "x", version: "1.0.0", dependencies: { y: "workspace:*" } }); expect(await lockedX()).toStrictEqual({ name: "x", version: "1.0.0", dependencies: { y: "workspace:*" } }); @@ -1339,7 +1336,8 @@ test.concurrent("remove --filter re-links only the selected workspace", async () const { stdout, stderr, exitCode } = await run(["remove", "no-deps", "--filter", "api"], dir, { linker: "hoisted" }); expect(stderr).toBe("Saved lockfile\n"); - // As with an unfiltered remove, the summary is the install count once something had to be linked: here api alone. + // Like with an unfiltered remove, the summary is the install count once something had to be linked, which here is + // only api. expect(stdoutLines(stdout)).toStrictEqual([HEADER("remove"), "", "1 package installed"]); expect(exitCode).toBe(0); @@ -2016,8 +2014,8 @@ test.concurrent.each( const fresh = await run(["install", omit], dir, { linker }); expect(fresh.stderr).not.toContain("error:"); const { packages, bins } = await topLevel(); - // `add` takes out the folders of the packages it names. What they depend on is in a place that the run leaves out, - // and no install removes that: `bun prune` does. + // `add` removes the folders of the packages that it's given. Their dependencies are in a slot that this install + // skips, and no install removes that. `bun prune` does. expect(after).toStrictEqual({ packages: linker === "hoisted" ? [...packages, "no-deps"].sort() : packages, bins }); expect(after.packages).not.toContain("one-fixed-dep"); expect(fresh.exitCode).toBe(0); diff --git a/test/cli/install/bun-add.test.ts b/test/cli/install/bun-add.test.ts index 696506b725dd..0168a56d61f2 100644 --- a/test/cli/install/bun-add.test.ts +++ b/test/cli/install/bun-add.test.ts @@ -294,8 +294,8 @@ it("bun add --only-missing should not install existing package", async () => { } }); -// Writes `source` to entry-point.ts and returns what `bun --analyze` adds to package.json. -// `urls` collects what it asks the registry for. +// Writes `source` to entry-point.ts and returns what `bun --analyze` adds to package.json. `urls` collects +// its registry requests. async function analyze( command: "add" | "install", source: string, @@ -372,6 +372,17 @@ it("bun add --analyze leaves out builtins, paths and aliases, with or without a ).toEqual({ added: ["bar"], errors: [], exitCode: 0 }); }); +it("bun add --analyze does not add the package that the rest of a bun: specifier names", async () => { + const urls: string[] = []; + // "#!/usr/bin/env bun" makes this a file for bun. + expect(await analyze("add", `#!/usr/bin/env bun\nimport "bun:boba"; import "bar/sub";`, { urls })).toEqual({ + added: ["bar"], + errors: [], + exitCode: 0, + }); + expect(urls).toEqual([`${root_url}/bar`]); +}); + it.each([ ["billing", "billing"], ["billing", "billing/sub"], @@ -388,7 +399,7 @@ it.each([ expect(urls).toEqual([`${root_url}/bar`]); }); -it("bun add --analyze goes by the package.json with a name that is nearest to the importing file", async () => { +it("bun add --analyze uses the nearest package.json with a name above the importing file", async () => { const urls: string[] = []; const member = join(package_dir, "packages", "member"); await mkdir(join(member, "nested"), { recursive: true }); @@ -2975,7 +2986,7 @@ describe("a relative local path typed from a directory below package.json", () = }); // From `package_dir/src`, `../` is `package_dir/`. From `package_dir` it is `add_dir`, another package. - it("a path that names another package relative to package.json installs the one the cwd names", async () => { + it("a path that matches one package relative to package.json and another relative to the cwd installs the cwd's", async () => { const name = basename(add_dir); await writeFile(join(add_dir, "package.json"), JSON.stringify({ name: "lib", version: "1.0.0" })); await writeFile(join(package_dir, "package.json"), JSON.stringify({ name: "app", version: "0.0.1" })); @@ -3138,7 +3149,7 @@ describe("-g and a relative local path", () => { expect(exitCode).toBe(0); }); - it("a path that is not there leaves the global package.json usable", async () => { + it("a path that doesn't exist leaves the global package.json usable", async () => { using dir = tempDir("bun-add-global-relative-missing", files); const home = String(dir); @@ -3523,7 +3534,7 @@ it("should add multiple dependencies specified on command line", async () => { await access(join(package_dir, "bun.lockb")); }); -it("requests the manifests of all the packages on the command line at once", async () => { +it("requests the manifests of all the packages on the command line at the same time", async () => { const registry = dummyRegistry([]); const lastWasRequested = Promise.withResolvers(); setHandler(async request => { @@ -3831,7 +3842,7 @@ describe("should move existing dependency when an explicit group flag is given", ).toBe(pkgJson({ ...root, dependencies: { BaR: "^0.0.2" } })); }); - it("--save-prod gives way to the flag of another group", async () => { + it("another group's flag wins over --save-prod", async () => { expect(await add({ ...root, dependencies: { BaR: "^0.0.2" } }, ["--save-prod", "--dev", "BaR"])).toBe( pkgJson({ ...root, devDependencies: { BaR: "^0.0.2" } }), ); @@ -3842,7 +3853,7 @@ describe("should move existing dependency when an explicit group flag is given", expect(await add(initial, ["--save-prod", "--only-missing", "BaR"])).toBe(pkgJson(initial)); }); - it.each(["remove", "update", "link"])("bun %s does not know --save-prod", async command => { + it.each(["link"])("bun %s has no --save-prod flag", async command => { const initial = pkgJson({ ...root, devDependencies: { BaR: "^0.0.2" } }); await writeFile(join(package_dir, "package.json"), initial); await using proc = spawn({ @@ -4079,7 +4090,8 @@ describe("a spec without a name that resolves to a dependency package.json alrea installed: (await file(join(project, "node_modules", "pkga", "package.json")).json()).version, }); - // package.json, bun.lock and node_modules agree, and stay as they are: no key twice, a frozen install passes, a second install changes nothing. + // package.json, bun.lock and node_modules agree and are stable: no key appears twice, a frozen install passes, and a + // second install changes nothing. async function settled(project: string, frozen = true) { const after = await state(project); expect(duplicateKeys(after.packageJson)).toEqual([]); @@ -4118,7 +4130,8 @@ describe("a spec without a name that resolves to a dependency package.json alrea peerDependencies: { lists: ["peerDependencies"] }, }, }; - // Every cell with a folder. The other kinds only where the list can change the outcome, so that the file stays fast. + // Every cell with a folder. The other kinds are only tested where the list can change the outcome, to keep the file + // fast. const cell = (declared: Declared, kind: Kind, flag: Flag) => ({ declared, kind, flag }); const cells = [ ...(Object.keys(outcomes) as Flag[]).flatMap(flag => @@ -4483,7 +4496,7 @@ describe("-g and a package.json above the global directory", () => { const lock = JSON.stringify({ lockfileVersion: 1, workspaces: { "": { dependencies: { pkg: "1.0.0" } } } }); - // Nor do they create an empty global package.json, against which the lockfile would lose every package. + // They don't create an empty global package.json either, which would make the lockfile lose every package. it.each([ [["update"], "nothing to update"], [["remove", "pkg"], "nothing to remove"], diff --git a/test/cli/install/bun-audit.test.ts b/test/cli/install/bun-audit.test.ts index 56194edb0875..e6ff77f35826 100644 --- a/test/cli/install/bun-audit.test.ts +++ b/test/cli/install/bun-audit.test.ts @@ -864,7 +864,7 @@ describe("`bun audit`", () => { expect(exitCode).toBe(0); }); - // No answer says nothing about the packages. `npm audit` fails on it too. + // No response says nothing about the packages. `npm audit` fails in that case too. test.concurrent.each([ ["", 200], [" \n", 200], @@ -903,7 +903,7 @@ describe("`bun audit`", () => { "ms\x1b[31m": [{ severity: "critical", title: "not a real package", url: "https://example.com/fake" }], }), ); - // Not normalizeBunSnapshot: it rewrites the backslashes the escapes are made of. + // Doesn't use normalizeBunSnapshot, because it rewrites the backslashes in the escapes. expect(withoutHeader(stdout)).toBe( [ "ms@0.7.0", @@ -2903,7 +2903,7 @@ describe("`bun audit fix`", () => { await runBunInstall(installEnv(dir), dir, { frozenLockfile: true }); }); - test.concurrent("an override written as a $reference is reported as the blocker and left alone", async () => { + test.concurrent("an override written as a $reference is reported as the blocker and isn't changed", async () => { await using server = startRegistry({ "no-deps": [adv("<1.0.1")] }); using dir = await setup(server, { name: "foo", @@ -4619,6 +4619,84 @@ describe("`bun audit fix`", () => { expect(await lock(dir)).toContain('"no-deps@1.0.1"'); }); + // A `catalog:` rule reads the catalog entry of the name in its key, and the fix rewrites that entry. + test.concurrent.each([ + ["a flat rule", { "no-deps": "catalog:" }, "catalog:", "default"], + ["a rule scoped to a parent", { "one-range-dep>no-deps": "catalog:build" }, "catalog:build", "build"], + ])("--json names the catalog entry that %s with a catalog: value reads", async (_, overrides, reference, catalog) => { + const catalogs = (version: string) => + reference === "catalog:" ? { catalog: { "no-deps": version } } : { catalogs: { build: { "no-deps": version } } }; + const project = (version: string) => ({ + name: "root", + workspaces: { packages: [], ...catalogs(version) }, + dependencies: { "one-range-dep": "1.0.0" }, + overrides, + }); + await using server = startRegistry({ "no-deps": [adv("<1.0.1")] }); + using dir = await setup(server, project("1.0.0")); + expect(await lock(dir)).toContain('"no-deps@1.0.0"'); + + const { stdout, exitCode } = await auditFix(dir, "--json"); + const doc = JSON.parse(stdout); + expect(doc.fixes).toStrictEqual([ + { + name: "no-deps", + from: "1.0.0", + to: "1.0.1", + downgrade: false, + newerThanMinimumReleaseAge: false, + packageJson: [{ file: "package.json", catalog, override: null, key: "no-deps", from: "1.0.0", to: "1.0.1" }], + }, + ]); + expect(doc).toMatchObject({ dryRun: false, fixed: 1, remaining: 0 }); + expect(exitCode).toBe(0); + expect(await pkgJson(dir)).toStrictEqual(project("1.0.1")); + expect(await lock(dir)).toContain('"no-deps@1.0.1"'); + expect(await lock(dir)).not.toContain('"no-deps@1.0.0"'); + await expectInstall(dir, "--frozen-lockfile"); + }); + + test.concurrent("--json names the catalog entry of the alias for a rule keyed by an npm: alias", async () => { + // The package that the alias points at has an entry of its own. The rule does not read it, and the fix leaves it. + const project = (version: string) => ({ + name: "root", + workspaces: { packages: [], catalog: { "my-alias": `npm:no-deps@${version}`, "no-deps": "1.0.0" } }, + dependencies: { "my-alias": "npm:no-deps@^1.0.0" }, + overrides: { "my-alias@npm:no-deps@^1.0.0": "catalog:" }, + }); + await using server = startRegistry({ "no-deps": [adv("<1.0.1")] }); + using dir = await setup(server, project("1.0.0")); + expect(await lock(dir)).toContain('"no-deps@1.0.0"'); + + const { stdout, exitCode } = await auditFix(dir, "--json"); + const doc = JSON.parse(stdout); + expect(doc.fixes).toStrictEqual([ + { + name: "no-deps", + from: "1.0.0", + to: "1.0.1", + downgrade: false, + newerThanMinimumReleaseAge: false, + packageJson: [ + { + file: "package.json", + catalog: "default", + override: null, + key: "my-alias", + from: "npm:no-deps@1.0.0", + to: "npm:no-deps@1.0.1", + }, + ], + }, + ]); + expect(doc).toMatchObject({ dryRun: false, fixed: 1, remaining: 0 }); + expect(exitCode).toBe(0); + expect(await pkgJson(dir)).toStrictEqual(project("1.0.1")); + expect(await installedVersion(dir, "my-alias")).toBe("1.0.1"); + expect(await lock(dir)).not.toContain('"no-deps@1.0.0"'); + await expectInstall(dir, "--frozen-lockfile"); + }); + test.concurrent("a bunfig.toml that freezes or stops saving the lockfile is explained in the note", async () => { await using server = startRegistry({ "a-dep": [adv("<1.0.4")] }); using dir = await setupVulnerableADep(server); @@ -5127,7 +5205,8 @@ describe("`bun audit fix --latest`", () => { expect(await lock(dir)).toBe(lockBefore); }); - // Both dependents declare no-deps@^1.0.0, which also rejects 2.0.0; the override is what the user can change, so it alone is reported. + // Both dependents declare no-deps@^1.0.0, which also rejects 2.0.0. The override is what the user can change, so only + // the override is reported. test.concurrent( "a range held by an overrides entry is blocked on the override, which --latest rewrites", async () => { diff --git a/test/cli/install/bun-create.test.ts b/test/cli/install/bun-create.test.ts index 20a5cb61a2e8..4a1c095847b4 100644 --- a/test/cli/install/bun-create.test.ts +++ b/test/cli/install/bun-create.test.ts @@ -2,7 +2,7 @@ import { spawn, spawnSync } from "bun"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "bun:test"; import { chmodSync, lstatSync, mkdirSync, readdirSync, statSync, symlinkSync } from "fs"; import { exists, stat } from "fs/promises"; -import { bunExe, bunEnv as env, githubTarball, isPosix, tempDir, tls, tmpdirSync } from "harness"; +import { bunExe, bunEnv as env, githubTarball, isASAN, isPosix, tempDir, tls, tmpdirSync } from "harness"; import { once } from "node:events"; import * as nodetls from "node:tls"; import { delimiter, join } from "path"; @@ -941,6 +941,23 @@ describe.concurrent("GitHub template", () => { expect(exitCode).toBe(0); }); + it.skipIf(!isASAN)("doesn't leak memory at exit", async () => { + using github = await serveGithub(createTest); + using dir = tempDir("create-github-leak", {}); + const { out, err, exitCode } = await create( + String(dir), + ["dylan-conway/create-test", "dest", "--no-install", "--no-git"], + { + ...github.env, + ASAN_OPTIONS: [env.ASAN_OPTIONS, "detect_leaks=1"].filter(Boolean).join(":"), + LSAN_OPTIONS: `print_suppressions=0:suppressions=${join(import.meta.dirname, "../../leaksan.supp")}`, + }, + ); + + expect(out).toContain("Success! dylan-conway/create-test loaded into dest"); + expect(exitCode, err).toBe(0); + }); + it.each(["https://github.com/dylan-conway/create-test", "github.com/dylan-conway/create-test"])( "should create and install github template from %s", async repo => { diff --git a/test/cli/install/bun-info.test.ts b/test/cli/install/bun-info.test.ts index 7796dec4490c..24aa521b3c1c 100644 --- a/test/cli/install/bun-info.test.ts +++ b/test/cli/install/bun-info.test.ts @@ -552,10 +552,10 @@ describe.concurrent("bun info with control characters in the packument", () => { // (overwrites the line), CRLF, tab, DEL, and the C1 controls NEL (U+0085) // and CSI (U+009B). const hostile = "\x1b[2J\x1b]0;PWNED\x07\rX\r\nY\tZ\x7f\u0085\u009b[31m"; - // How the summary view renders it: every control becomes a visible escape. + // The summary view renders every control character as a visible escape. const escaped = String.raw`\x1b[2J\x1b]0;PWNED\x07\rX\r\nY\tZ\x7f\u0085\u009b[31m`; - // How `bun pm view ` renders it: CRLF and tab are kept since - // the field itself may be multi-line (readme), everything else is escaped. + // `bun pm view ` keeps CRLF and tab, because the field itself may have several lines (readme), and + // escapes everything else. const escapedMultiline = String.raw`\x1b[2J\x1b]0;PWNED\x07\rX` + "\r\nY\tZ" + String.raw`\x7f\u0085\u009b[31m`; const packument = { @@ -857,7 +857,7 @@ describe.concurrent("bun pm view (local registry)", () => { err: "", code: 0, }); - // Nothing to expand, one field left: printed bare. + // There's nothing to expand and only one field left, so it's printed bare. expect(await view(["zz-conflict", "maintainers.name", "keywords"])).toEqual({ out: `["verkw"]\n`, err: "", @@ -882,7 +882,7 @@ describe.concurrent("bun pm view (local registry)", () => { }); }); - test("the selected version comes with what the registry says about the whole package", async () => { + test("the selected version also has the registry's package-level fields", async () => { // Root-only keys are visible, version keys win, `readme` only when asked for. expect(await view(["zz-basic@1.0.0", "description", "readmeFilename", "customRoot", "dist-tags.latest"])).toEqual({ out: `description = "basic v1"\nreadmeFilename = "README.md"\ncustomRoot = "root-only"\ndist-tags.latest = "2.0.0"\n`, @@ -1080,7 +1080,7 @@ describe.concurrent("bun info version spec", () => { "zz-dangling": packument("zz-dangling", { latest: "9.9.9", "v0-legacy": "0.5.0" }, ["1.0.0"]), "zz-onlypre": packument("zz-onlypre", { latest: "1.0.0-beta.2" }, ["1.0.0-beta.1", "1.0.0-beta.2"]), "zz-rc": packument("zz-rc", { latest: "2.0.0-rc.1" }, ["1.0.0", "1.1.0", "2.0.0-rc.1"]), - // As some mirrors and private registries send it. + // Some mirrors and private registries send it like this. "zz-untagged": packument("zz-untagged", {}, ["1.0.0", "1.1.0"]), }; let server: ReturnType; diff --git a/test/cli/install/bun-install-android-seccomp.test.ts b/test/cli/install/bun-install-android-seccomp.test.ts index 154df4ab9b96..a851a896142b 100644 --- a/test/cli/install/bun-install-android-seccomp.test.ts +++ b/test/cli/install/bun-install-android-seccomp.test.ts @@ -115,7 +115,7 @@ test.skipIf(!canFilter)("bun install survives Android-style seccomp (openat2/fch // bin in a subdirectory so bin linking validates the parent dir with // openat2(RESOLVE_BENEATH), then chmods the target (fchmodat2). "dep/bin/dep.js": "#!/usr/bin/env node\nconsole.log('ok');\n", - // What makes bun recognize Android here: the test host's kernel release string isn't Android's. + // This makes Bun detect Android here, because the test host's kernel release string isn't Android's. "system/bin/linker64": "", }); diff --git a/test/cli/install/bun-install-backends.test.ts b/test/cli/install/bun-install-backends.test.ts index 900f60870b42..d3109ae33193 100644 --- a/test/cli/install/bun-install-backends.test.ts +++ b/test/cli/install/bun-install-backends.test.ts @@ -245,7 +245,7 @@ describe.skipIf(isWindows)("install backends on POSIX", () => { mkdirSync(installed, { recursive: true }); writeFileSync(join(installed, "index.js"), "stale"); writeFileSync(join(installed, "not-in-the-package"), ""); - // Readable (and, where bun writes, writable) for `nobody` too. + // `nobody` can read it too, and can write where Bun writes. chmodSync(projectDir, 0o777); chmodSync(packageDir, 0o755); for (const file of Object.keys(packageFiles)) chmodSync(join(packageDir, file), 0o644); @@ -431,7 +431,7 @@ describe("file: folder dependencies with the hoisted linker", () => { expect(await readdirSorted(pluginDir)).toEqual(["index.js", "node_modules", "package.json", "tool.tgz"]); expect(await readdirSorted(join(pluginDir, "node_modules"))).toEqual(["helper"]); expect(existsSync(join(projectDir, "node_modules", "tool", "package.json"))).toBe(true); - // Nothing is written into the folder the dependency was installed from. + // Nothing is written into the folder that the dependency was installed from. expect(await readdirSorted(join(String(dir), "plugin"))).toEqual(["index.js", "package.json", "tool.tgz"]); } }, @@ -604,8 +604,8 @@ describe("file: folder dependencies with the hoisted linker", () => { ); } - // What says that a folder is installed is the folder: every file in node_modules is still a - // hard link of the file of that name, and neither side has a name the other lacks. + // The folder itself shows that it's installed: every file in node_modules is still a hard link to the file with the + // same name, and neither side has a file that the other doesn't. describe("a folder that has not changed is not installed again", () => { function project(name: string, spec: string) { const source = spec === "file:../lib" ? "lib" : "project/vendor/lib"; diff --git a/test/cli/install/bun-install-cpu-os.test.ts b/test/cli/install/bun-install-cpu-os.test.ts index 806e209f57d1..bf1405e75c96 100644 --- a/test/cli/install/bun-install-cpu-os.test.ts +++ b/test/cli/install/bun-install-cpu-os.test.ts @@ -597,8 +597,8 @@ describe("bun install --cpu and --os flags", () => { const installedNames = async () => (await readdirSorted(join(package_dir, "node_modules"))).filter(name => !name.startsWith(".")); - // A dependency the project requires does not go missing without a word. Optional ones stay quiet, and so do the - // dependencies of dependencies, which the project cannot do anything about (run with --verbose to list them). + // A dependency that the project requires isn't skipped silently. Optional ones are, and so are the dependencies of + // dependencies, which the project can't do anything about (run with --verbose to list them). it.each(["hoisted", "isolated"])( "warns about each direct required dependency left out for the target platform (%s linker)", async linker => { @@ -616,7 +616,7 @@ describe("bun install --cpu and --os flags", () => { ); await Bun.write( join(package_dir, "packages", "member", "package.json"), - // one that the root names too, and one of its own + // One that the root also depends on, and one of its own. JSON.stringify({ name: "member", dependencies: { "dep-win32-only": "1.0.0", "member-s390x-only": "4.0.0" } }), ); const install = async (...flags: string[]) => { @@ -643,7 +643,7 @@ describe("bun install --cpu and --os flags", () => { expect(await install()).toEqual([]); const removeNodeModules = () => rm(join(package_dir, "node_modules"), { recursive: true, force: true }); - // one that installs from the lockfile does; what is not asked for is not missed + // An install from the lockfile does. A package that isn't requested isn't reported as missing. await removeNodeModules(); expect(await install("--production")).toEqual([win32, s390x]); await removeNodeModules(); @@ -814,7 +814,7 @@ describe("bun install --libc flag and the libc field", () => { expect(await lockfileEntry("dep-musl")).toContain(`{ "libc": "musl" }`); expect(await lockfileEntry("dep-universal")).toContain(", {}"); - // The lockfile alone decides what a frozen install for the other libc gets: no manifest is fetched. + // The lockfile alone decides what a frozen install for the other libc gets, so no manifest is fetched. await rm(join(package_dir, "node_modules"), { recursive: true, force: true }); clear(accepts, urls); await install("--libc", "musl", "--frozen-lockfile"); diff --git a/test/cli/install/bun-install-env-file.test.ts b/test/cli/install/bun-install-env-file.test.ts index e2dd1e2ab3f6..b93a7c663b53 100644 --- a/test/cli/install/bun-install-env-file.test.ts +++ b/test/cli/install/bun-install-env-file.test.ts @@ -292,9 +292,9 @@ describe("bun install .env loading and lifecycle scripts (#31450)", () => { }); }); -// The security scanner runs in a child `bun` that starts in the project root. -// Left alone that child loads the default `.env*` files of `bun run` by itself. -// Like a lifecycle script it gets the environment install resolved, and nothing else. +// The security scanner runs in a child `bun` that starts in the project root. By default, that child would load the +// same `.env*` files as `bun run`. Like a lifecycle script, it gets the environment that the install resolved, and +// nothing else. const scannerProbeKeys = ["SCAN_DOTENV", "SCAN_MODE", "SCAN_CUSTOM", "SCAN_SHELL", "BUN_FEATURE_FLAG_NO_ORPHANS"]; // Records which of the probe variables the scanner process has, and whether a diff --git a/test/cli/install/bun-install-git-deps.test.ts b/test/cli/install/bun-install-git-deps.test.ts index a853ebe12135..47c5ebc990a4 100644 --- a/test/cli/install/bun-install-git-deps.test.ts +++ b/test/cli/install/bun-install-git-deps.test.ts @@ -349,9 +349,8 @@ test.concurrent( [nameOf("a")]: sharedTransitive, }); - // the race depends on threadpool scheduling; two fresh-cache attempts to - // make the failure reliable on the unfixed code. Each has a project and a - // cache of its own so that both run at once: a cold install of 16 git + // The race depends on thread pool scheduling, so two attempts with a fresh cache make the failure reliable without + // the fix. Each attempt has its own project and cache so that both can run at once. A cold install of 16 git // packages spawns about 60 git processes, which is slow on Windows. const attempts = await Promise.all( [0, 1].map(async attempt => { @@ -506,11 +505,10 @@ test.concurrent( 30_000, ); -// The URL parser hands back the committish of a GitHub dependency -// percent-decoded, and one that was written with an escape was then dropped -// from the request: `#feat%2Fx` asked for `/tarball/` (the default branch). It -// goes into the request as written, and GitHub decodes it. -test.concurrent("requests a github: dependency as written when its committish holds a percent-escape", async () => { +// The URL parser returns the committish of a GitHub dependency percent-decoded. A committish that was written with an +// escape was then dropped from the request: `#feat%2Fx` requested `/tarball/` (the default branch). Now it's sent as +// written, and GitHub decodes it. +test.concurrent("requests a github: dependency as written when its committish has a percent-escape", async () => { using dir = tempDir("github-dep-escapes", {}); const root = String(dir); @@ -554,10 +552,10 @@ test.concurrent("requests a github: dependency as written when its committish ho expect(exitCode).toBe(0); }); -// A part of a GitHub dependency that is not in it the way the URL parser hands -// it back was left empty: an empty committish installed the default branch, an -// empty owner asked for `/repos///`. Such a dependency fails to resolve. -test.concurrent("does not request a github: dependency with a part it cannot find", async () => { +// If a part of a GitHub dependency couldn't be found in the form that the URL parser returns, it was left empty. An +// empty committish installed the default branch, and an empty owner requested `/repos///`. Now such a dependency +// fails to resolve. +test.concurrent("does not request a github: dependency if a part of it can't be found", async () => { using dir = tempDir("github-dep-not-found", {}); const root = String(dir); const tarball = await tarballOf("scope-pkg-a-0000000", packageFiles(nameOf("a"), "default-branch")); @@ -594,16 +592,14 @@ test.concurrent("does not request a github: dependency with a part it cannot fin expect(exitCode).toBe(1); }); -// Each ref of a GitHub repository is its own tarball download, and each -// extracted tarball became a new package. Refs on one commit gave packages with -// the same name and resolution, which bun.lock holds as one package. The -// isolated linker linked all of them into the same store directory at once and -// failed at random with `EEXIST: File exists: failed to link package`. +// Each ref of a GitHub repository is a separate tarball download, and each extracted tarball became a new package. Refs +// that point to the same commit produced packages with the same name and resolution, which bun.lock stores as one +// package. The isolated linker linked all of them into the same store directory at once and failed at random with +// `EEXIST: File exists: failed to link package`. // -// The fixture serves `testowner/testrepo` (gh-dep) and `testowner/leaf` -// (gh-leaf, a dependency of gh-dep). Every branch and tag of a repository -// answers with the tarball of the commit in `heads`, so all of them resolve to -// that commit: bun reads it from the name of the tarball's root directory. +// The fixture serves `testowner/testrepo` (gh-dep) and `testowner/leaf` (gh-leaf, a dependency of gh-dep). Every branch +// and tag of a repository returns the tarball of the commit in `heads`, so they all resolve to that commit. Bun reads +// the commit from the name of the tarball's root directory. async function serveGithub() { const tarballs = { testrepo: { @@ -659,8 +655,8 @@ const ghLeafStoreEntry = "gh-leaf@github+testowner+leaf+bbbbbbb"; // where the isolated linker puts gh-leaf for gh-dep, relative to node_modules const ghLeafOfGhDep = join(".bun", ghDepStoreEntry, "node_modules", "gh-leaf"); -// What the isolated linker must leave in node_modules: one store entry for -// gh-dep, with gh-leaf linked next to it, and every alias linked to that entry. +// Checks what the isolated linker should leave in node_modules: one store entry for gh-dep, with gh-leaf linked next to +// it, and every alias linked to that entry. function expectOneStoreEntry(project: string, aliases: string[]) { const modules = join(project, "node_modules"); expect({ @@ -675,13 +671,12 @@ function expectOneStoreEntry(project: string, aliases: string[]) { }); } -// Not on Windows: the three extracts finish into one cache folder, and there an -// extract that finds the folder taken moves it away (`move_to_cache_directory` -// in extract_tarball.rs) while another one still reads its package.json. Now -// and then that one makes a package with no name and no dependencies. +// Skipped on Windows. The three extractions all end up in one cache folder, and on Windows an extraction that finds the +// folder taken moves it away (`move_to_cache_directory` in extract_tarball.rs) while another one is still reading its +// package.json. Occasionally that one creates a package with no name and no dependencies. for (const linker of ["isolated", "hoisted"] as const) { test.concurrent.skipIf(isWindows)( - `${linker} linker installs github: refs on one commit as one package`, + `${linker} linker installs github: refs that point to one commit as one package`, async () => { using dir = tempDir(`github-one-commit-${linker}`, {}); const root = String(dir); @@ -694,8 +689,8 @@ for (const linker of ["isolated", "hoisted"] as const) { // the hoisted linker puts gh-leaf in the root node_modules const leaf = linker === "isolated" ? ghLeafOfGhDep : "gh-leaf"; - // the collision depends on threadpool scheduling; two fresh-cache attempts - // to make the failure reliable on the unfixed code + // The collision depends on thread pool scheduling, so two attempts with a fresh cache make the failure reliable + // without the fix. for (let attempt = 0; attempt < 2; attempt++) { rmSync(join(project, "node_modules"), { recursive: true, force: true }); rmSync(join(project, "bun.lock"), { force: true }); @@ -742,13 +737,13 @@ for (const linker of ["isolated", "hoisted"] as const) { ); } -// The same for a repository whose package.json has no name, or that has no -// package.json: the package is named after the repository, for every ref. +// The same for a repository whose package.json has no name, or that has no package.json. The package is named after the +// repository, for every ref. test.concurrent.skipIf(isWindows).each([ ["a package.json without a name", { "package.json": JSON.stringify({ version: "1.0.0" }) }], ["no package.json", {}], ])( - "isolated linker installs github: refs on one commit of a repository with %s as one package", + "isolated linker installs github: refs that point to one commit of a repository with %s as one package", async (_, manifest) => { using dir = tempDir("github-one-commit-nameless", {}); const root = String(dir); @@ -778,10 +773,10 @@ test.concurrent.skipIf(isWindows).each([ }, ); -// The same collision with a lockfile: the locked package and the package of a -// new ref on its commit were two packages. +// The same collision with a lockfile: the locked package and the package for a new ref to the same commit were two +// packages. test.concurrent( - "isolated linker reuses a locked github: package for a new ref on its commit", + "isolated linker reuses a locked github: package for a new ref to the same commit", async () => { using dir = tempDir("github-one-commit-locked", {}); const root = String(dir); @@ -795,8 +790,8 @@ test.concurrent( expect(exitCode).toBe(0); } - // a fresh machine that adds a second ref: keep bun.lock, drop node_modules + cache. - // The branch of gh-leaf moved in the meantime; bun.lock pins its old commit. + // Simulate a fresh machine that adds a second ref: keep bun.lock, delete node_modules and the cache. gh-leaf's + // branch has moved in the meantime, and bun.lock pins its old commit. writeProject(root, { a: "github:testowner/testrepo#main", b: "github:testowner/testrepo#v1" }); rmSync(join(project, "node_modules"), { recursive: true }); github.heads.leaf = "ccccccc"; @@ -836,7 +831,7 @@ test.concurrent( // commit did not move, so a nested branch ref follows its branch. for (const parent of ["github:", "git+"] as const) { test.concurrent( - `bun update moves a nested github: ref when the commit of its ${parent} parent did not move`, + `bun update moves a nested github: ref when the commit of its ${parent} parent hasn't moved`, async () => { using dir = tempDir("git-update-nested", {}); const root = String(dir); @@ -872,8 +867,8 @@ for (const parent of ["github:", "git+"] as const) { ); } -// The `git+` twin: the checkout task is keyed by the resolved commit, so two -// refs on one commit share one task and one package. +// The same with `git+`. The checkout task is keyed by the resolved commit, so two refs to one commit share one task and +// one package. test.concurrent( "isolated linker reuses a locked git package for a new ref on its commit", async () => { @@ -938,8 +933,8 @@ test.concurrent( const urlOf = (name: string) => `http://localhost:${server.port}/${name}.tgz`; tarballs = { "/tb-dep.tgz": await tarballOf("package", packageFiles("tb-dep", "tb-dep")), - // q-dep -> r-dep -> tb-dep: bun reads r-dep's package.json two downloads - // after it started the download of tb-dep for `b` + // q-dep -> r-dep -> tb-dep. Bun reads r-dep's package.json two downloads after it started downloading tb-dep for + // `b`. "/q-dep.tgz": await tarballOf("package", packageFiles("q-dep", "q-dep", { "r-dep": urlOf("r-dep") })), "/r-dep.tgz": await tarballOf("package", packageFiles("r-dep", "r-dep", { c: urlOf("tb-dep") })), }; @@ -960,7 +955,7 @@ test.concurrent( writeProject(root, { a: urlOf("tb-dep"), b: urlOf("tb-dep"), q: urlOf("q-dep") }); rmSync(join(project, "node_modules"), { recursive: true }); const { stdout, stderr, exitCode } = await runInstall(project, join(root, "cache-cold"), {}, "--linker=isolated"); - // q-dep and r-dep: `b` and `c` find the locked tb-dep by its URL, and the linker downloads it + // Only q-dep and r-dep. `b` and `c` find the locked tb-dep by its URL, and the linker downloads it. expect(normalizeBunSnapshot(stderr)).toMatchInlineSnapshot(` "Resolving dependencies Resolved, downloaded and extracted [4] @@ -1101,8 +1096,8 @@ for (const linker of ["hoisted", "isolated"] as const) { ); } -// A registry that has version 1.0.0 of each package: name -> the rest of its -// package.json. The marker its index.js exports is `-from-registry`. +// Serves a registry that has version 1.0.0 of each package. `packages` maps a name to the rest of its package.json. The +// marker that its index.js exports is `-from-registry`. async function serveRegistry(packages: Record) { const tarballs = new Map(); for (const [name, fields] of Object.entries(packages)) { @@ -1137,14 +1132,14 @@ async function lockedResolutions(project: string): Promise/project`, a workspace root with no dependencies of its own, and its -// one member `packages/m`. A new workspace gets the isolated linker. +// Writes `/project`, a workspace root with no dependencies of its own, and its only workspace, `packages/m`. A +// new project with workspaces gets the isolated linker. function writeWorkspace(root: string, dependencies: Record) { const project = join(root, "project"); const member = join(project, "packages", "m"); @@ -1158,8 +1153,7 @@ function writeWorkspace(root: string, dependencies: Record) { // and keeps one of them with it: the first that its depth-first, name-ordered // walk reaches. In the tests below that is, for the git package `b` of the // workspace member `m`, the peer dependency `b: "*"` of `a`, which is walked -// first. It is not a git dependency, and bun.lock resolves a required one to -// the registry's `b` (`a/b`). Once the repository was cloned, the install took +// first. It is not a git dependency. Once the repository was cloned, the install took // the checkout to start from that dependency: it started none and never exited. for (const peer of ["required", "optional"] as const) { test.concurrent( @@ -1169,7 +1163,6 @@ for (const peer of ["required", "optional"] as const) { const root = String(dir); const bare = await makeSharedRepo(root, [{ name: "b", branch: "main" }], "b.git"); const repoUrl = `git+${pathToFileURL(bare)}`; - // A required peer is also resolved on its own, from the registry. await using registry = await serveRegistry( peer === "required" ? { a: { peerDependencies: { b: "*" } }, b: {} } @@ -1181,9 +1174,8 @@ for (const peer of ["required", "optional"] as const) { a: "a@1.0.0", b: `b@${repoUrl}#${branchCommits(bare).main}`, m: "m@workspace:packages/m", - ...(peer === "required" && { "a/b": "b@1.0.0" }), }; - // What `m` resolves, and the `b` that `a` resolves: the git one. + // What `m` resolves, and the `b` that `a` resolves, which should be the git one. const installed = async () => ({ ...(await installedVersions(member, ["a", "b"])), "a > b": await installedVersionOf(storeEntryOf(member, "a"), "b"), @@ -1201,7 +1193,7 @@ for (const peer of ["required", "optional"] as const) { expect(exitCode).toBe(0); } - // simulate a fresh machine: keep bun.lock, drop node_modules + cache + // Simulate a fresh machine: keep bun.lock, delete node_modules and the cache. rmSync(join(project, "node_modules"), { recursive: true }); rmSync(join(member, "node_modules"), { recursive: true }); const { stdout, stderr, exitCode } = await runInstall( @@ -1218,62 +1210,63 @@ for (const peer of ["required", "optional"] as const) { ); } -// One clone serves every package of a repository. Three wait for it here, and -// the one that a's peer dependency stands for is neither the first nor the last. -test.concurrent("checks out every package of a repository when a peer dependency stands for one of them", async () => { - using dir = tempDir("git-dep-peer-shared-repo", {}); - const root = String(dir); - const names = ["aa", "b", "c"]; - const bare = await makeSharedRepo( - root, - names.map(name => ({ name, branch: name })), - ); - const repoUrl = `git+${pathToFileURL(bare)}`; - const commits = branchCommits(bare); - await using registry = await serveRegistry({ a: { peerDependencies: { b: "*" } }, b: {} }); - const env = { BUN_CONFIG_REGISTRY: registry.url.href }; - const { project, member } = writeWorkspace(root, { - a: "1.0.0", - ...Object.fromEntries(names.map(name => [name, `${repoUrl}#${name}`])), - }); - const locked = { - a: "a@1.0.0", - ...Object.fromEntries(names.map(name => [name, `${name}@${repoUrl}#${commits[name]}`])), - m: "m@workspace:packages/m", - "a/b": "b@1.0.0", - }; - const installed = async () => ({ - ...(await installedVersions(member, ["a", ...names])), - "a > b": await installedVersionOf(storeEntryOf(member, "a"), "b"), - }); - const expected = { a: "a-from-registry", aa: "aa", b: "b", c: "c", "a > b": "b" }; - const output = [expect.stringContaining("bun install v"), "", "4 packages installed"]; +// One clone serves every package of a repository. Three packages wait for it here, and the one that's installed through +// a's peer dependency is neither the first nor the last. +test.concurrent( + "checks out every package of a repository when one of them is installed through a peer dependency", + async () => { + using dir = tempDir("git-dep-peer-shared-repo", {}); + const root = String(dir); + const names = ["aa", "b", "c"]; + const bare = await makeSharedRepo( + root, + names.map(name => ({ name, branch: name })), + ); + const repoUrl = `git+${pathToFileURL(bare)}`; + const commits = branchCommits(bare); + await using registry = await serveRegistry({ a: { peerDependencies: { b: "*" } }, b: {} }); + const env = { BUN_CONFIG_REGISTRY: registry.url.href }; + const { project, member } = writeWorkspace(root, { + a: "1.0.0", + ...Object.fromEntries(names.map(name => [name, `${repoUrl}#${name}`])), + }); + const locked = { + a: "a@1.0.0", + ...Object.fromEntries(names.map(name => [name, `${name}@${repoUrl}#${commits[name]}`])), + m: "m@workspace:packages/m", + }; + const installed = async () => ({ + ...(await installedVersions(member, ["a", ...names])), + "a > b": await installedVersionOf(storeEntryOf(member, "a"), "b"), + }); + const expected = { a: "a-from-registry", aa: "aa", b: "b", c: "c", "a > b": "b" }; + const output = [expect.stringContaining("bun install v"), "", "4 packages installed"]; - // fresh install to produce a complete lockfile - { - const { stdout, stderr, exitCode } = await runInstall(project, join(root, "cache-warm"), env); - expect(stderr).toContain("Saved lockfile"); + // fresh install to produce a complete lockfile + { + const { stdout, stderr, exitCode } = await runInstall(project, join(root, "cache-warm"), env); + expect(stderr).toContain("Saved lockfile"); + expect(installOutput(stdout)).toEqual(output); + expect(await installed()).toEqual(expected); + expect(await lockedResolutions(project)).toEqual(locked); + expect(exitCode).toBe(0); + } + + // Simulate a fresh machine: keep bun.lock, delete node_modules and the cache. + rmSync(join(project, "node_modules"), { recursive: true }); + rmSync(join(member, "node_modules"), { recursive: true }); + const { stdout, stderr, exitCode } = await runInstall(project, join(root, "cache-cold"), env, "--frozen-lockfile"); + expect(stderr).toBe(""); expect(installOutput(stdout)).toEqual(output); expect(await installed()).toEqual(expected); - expect(await lockedResolutions(project)).toEqual(locked); expect(exitCode).toBe(0); - } - - // simulate a fresh machine: keep bun.lock, drop node_modules + cache - rmSync(join(project, "node_modules"), { recursive: true }); - rmSync(join(member, "node_modules"), { recursive: true }); - const { stdout, stderr, exitCode } = await runInstall(project, join(root, "cache-cold"), env, "--frozen-lockfile"); - expect(stderr).toBe(""); - expect(installOutput(stdout)).toEqual(output); - expect(await installed()).toEqual(expected); - expect(exitCode).toBe(0); -}); + }, +); -// The repository is gone when the cold install clones it. The failed clone -// fails every package that waits for it. The one that a's peer dependency -// stands for was left waiting, and the install never exited. +// The repository is gone by the time the cold install clones it. The failed clone fails every package that's waiting +// for it. The one that's installed through a's peer dependency used to be left waiting, and the install never exited. test.concurrent( - "fails every package of a repository that cannot be cloned when a peer dependency stands for one of them", + "fails every package of a repository that can't be cloned when one of them is installed through a peer dependency", async () => { using dir = tempDir("git-dep-peer-clone-fails", {}); const root = String(dir); @@ -1295,7 +1288,6 @@ test.concurrent( const { stderr, exitCode } = await runInstall(project, join(root, "cache-warm"), env); expect(stderr).toContain("Saved lockfile"); expect(await installedVersions(member, ["a", ...names])).toEqual({ a: "a-from-registry", b: "b", c: "c" }); - expect((await lockedResolutions(project))["a/b"]).toBe("b@1.0.0"); expect(exitCode).toBe(0); } @@ -1362,7 +1354,7 @@ test.concurrent( expect(exitCode).toBe(0); } - // simulate a fresh machine: keep bun.lock, drop node_modules + cache + // Simulate a fresh machine: keep bun.lock, delete node_modules and the cache. rmSync(join(project, "node_modules"), { recursive: true }); const { stdout, stderr, exitCode } = await runInstall( project, @@ -1378,11 +1370,10 @@ test.concurrent( }, ); -// bun.lock can spell a repository's URL differently from the dependency: an -// scp-form URL comes back from it with `ssh://` in front. Here the locked URL -// has a `.` segment. The install clones and checks out what bun.lock names. It -// used to go by the dependency once the clone ended: it cloned a second time -// and left the package waiting. +// bun.lock can spell a repository's URL differently than the dependency does. For example, an scp-style URL is read +// back from it with `ssh://` in front. Here the locked URL has a `.` segment. The install clones and checks out what's +// in bun.lock. It used to switch to the dependency's URL once the clone finished, so it cloned a second time and left +// the package waiting. test.concurrent( "isolated linker checks out a git package whose URL bun.lock spells differently from the dependency", async () => { @@ -1415,10 +1406,9 @@ test.concurrent( }, ); -// A patch is applied to a git package right after its checkout when the -// repository was cloned earlier in the same process, here to resolve the new -// dependency `c`. The package to patch was looked up by the name of the -// dependency, which an alias does not share with it: `panic: Package not found`. +// A patch is applied to a git package right after its checkout if the repository was cloned earlier in the same +// process, which happens here to resolve the new dependency `c`. The package to patch was looked up by the dependency's +// name, which is different for an alias: `panic: Package not found`. for (const [added, editsPackageJson] of [ ["`bun install `", false], ["an edit of package.json", true], @@ -1463,7 +1453,7 @@ index 0000000000000000000000000000000000000000..11111111111111111111111111111111 expect(exitCode).toBe(0); } - // a fresh machine: keep bun.lock, drop node_modules + cache, and add `c` + // Simulate a fresh machine: keep bun.lock, delete node_modules and the cache, and add `c`. rmSync(join(project, "node_modules"), { recursive: true }); const args: string[] = []; if (editsPackageJson) writePackageJson({ "b-alias": `${repoUrl}#b`, c: `${repoUrl}#c` }); @@ -1499,7 +1489,7 @@ test.concurrent("installs a git+file:// dependency", async () => { }); test.concurrent( - "a failed prepare script of a git dependency says that its devDependencies are not installed", + "a failed prepare script of a git dependency explains that its devDependencies aren't installed", async () => { using dir = tempDir("git-dep-prepare", {}); const root = String(dir); @@ -1530,7 +1520,7 @@ function libWithFolders(dependencies: Record, more: Partial { + test.concurrent(`the dependencies of a file: folder inside a git dependency are installed (${linker})`, async () => { using dir = tempDir("git-dep-contained-folder", {}); const root = String(dir); const repoUrl = `git+${pathToFileURL(join(root, "shared-repo.git"))}`; @@ -1567,7 +1557,7 @@ for (const linker of ["hoisted", "isolated"]) { }); expect(first.exitCode).toBe(0); - // bun.lock alone gives the same tree, on a machine that has nothing cached. + // bun.lock alone produces the same tree on a machine with an empty cache. const saved = lockfile(); rmSync(join(project, "node_modules"), { recursive: true, force: true }); const frozen = await runInstall(project, join(root, "cache-2"), {}, `--linker=${linker}`, "--frozen-lockfile"); @@ -1583,7 +1573,7 @@ for (const linker of ["hoisted", "isolated"]) { } // The author of `lib` wrote these for their own monorepo. In the user's project `mine` is another package. -test.concurrent("a file: folder inside a git dependency does not reach into the project that installs it", async () => { +test.concurrent("a file: folder inside a git dependency can't reach into the project that installs it", async () => { using dir = tempDir("git-dep-contained-folder-project", {}); const root = String(dir); const repoUrl = `git+${pathToFileURL(join(root, "shared-repo.git"))}`; @@ -1615,7 +1605,7 @@ test.concurrent("a file: folder inside a git dependency does not reach into the expect(exitCode).toBe(0); }); -test.concurrent("a file: folder that a git dependency does not have is an error", async () => { +test.concurrent("a file: folder that's missing from a git dependency is an error", async () => { using dir = tempDir("git-dep-missing-folder", {}); const root = String(dir); const bare = await makeSharedRepo(root, [libWithFolders({ sub: "file:./packages/typo" })]); @@ -1630,27 +1620,28 @@ test.concurrent("a file: folder that a git dependency does not have is an error" expect(exitCode).toBe(1); }); -test.concurrent("a file: folder of a git dependency is not read through a link that leaves the checkout", async () => { - using dir = tempDir("git-dep-linked-folder", { - "outside/package.json": JSON.stringify({ name: "sub", version: "1.0.0" }), - }); - const root = String(dir); - const bare = await makeSharedRepo(root, [ - libWithFolders({ sub: "file:./packages/sub" }, { links: { "packages/sub": join(root, "outside") } }), - ]); - const project = writeProject(root, { lib: `git+${pathToFileURL(bare)}#lib` }); +test.concurrent( + "a file: folder of a git dependency isn't read through a symlink that leaves the checkout", + async () => { + using dir = tempDir("git-dep-linked-folder", { + "outside/package.json": JSON.stringify({ name: "sub", version: "1.0.0" }), + }); + const root = String(dir); + const bare = await makeSharedRepo(root, [ + libWithFolders({ sub: "file:./packages/sub" }, { links: { "packages/sub": join(root, "outside") } }), + ]); + const project = writeProject(root, { lib: `git+${pathToFileURL(bare)}#lib` }); - const { stderr, exitCode } = await runInstall(project, join(root, "cache"), {}); - expect(stderr).toMatch(/error: failed to read package\.json of "sub@file:\.\/packages\/sub" declared by lib@.*: E/); - expect(exitCode).toBe(1); -}); + const { stderr, exitCode } = await runInstall(project, join(root, "cache"), {}); + expect(stderr).toMatch(/error: failed to read package\.json of "sub@file:\.\/packages\/sub" declared by lib@.*: E/); + expect(exitCode).toBe(1); + }, +); -// Two installs of different projects that share a cold cache both clone the -// repository of a git dependency. The one that finishes second finds the -// other's clone in the cache already. It used to swap its own clone in and -// delete the other one, which the first install still had open: its checkout -// then failed with "fatal: repository '/..tmp (deleted)' does not -// exist". The same applies to the checkout folder. +// Two installs of different projects that share a cold cache both clone the repository of a git dependency. The one +// that finishes second finds the other's clone already in the cache. It used to swap in its own clone and delete the +// other one, which the first install still had open. The first install's checkout then failed with "fatal: repository +// '/..tmp (deleted)' does not exist". The same applies to the checkout folder. test.concurrent.skipIf(isWindows)( "an install keeps the git cache folders that another install published first", async () => { @@ -1705,8 +1696,8 @@ exec ${quote(Bun.which("git", { PATH: gitEnv.PATH })!)} "$@" expect(await lockedPackages(project)).toEqual(locked); expect(exitCode).toBe(0); } - // The installs met at every step, and the cache holds one bare clone and - // one checkout: an install that lost removed the folder it had built. + // The installs met at every step, and the cache has one bare clone and one checkout, because the install that lost + // the race removed the folder that it had built. expect(readdirSync(steps).sort()).toEqual([ "first-clones-checkout", "first-runs-log", @@ -1723,11 +1714,9 @@ exec ${quote(Bun.which("git", { PATH: gitEnv.PATH })!)} "$@" 30_000, ); -// The same race on Windows, where a script cannot stand in for git, so nothing -// orders the installs. There the install that lost deleted the published -// folder by its name, and three of four installs failed, with "fatal: -// 'C:\$Extend\$Deleted\' does not appear to be a git repository" or -// "moving to cache dir failed: ENOTEMPTY". +// The same race on Windows, where a script can't replace git, so nothing orders the installs. There, the install that +// lost the race deleted the published folder by name, and three of four installs failed with "fatal: +// 'C:\$Extend\$Deleted\' does not appear to be a git repository" or "moving to cache dir failed: ENOTEMPTY". test.concurrent.skipIf(!isWindows)( "installs that share a cold cache and a git dependency all succeed", async () => { @@ -1758,9 +1747,8 @@ test.concurrent.skipIf(!isWindows)( 30_000, ); -// Only a folder with `.bun-tag` is a complete checkout. A folder without it -// (what a killed install of an older version left) is replaced, and so is a -// link to one. What the link points to is left alone. +// Only a folder with `.bun-tag` is a complete checkout. A folder without it (left by a killed install of an older +// version) is replaced, and so is a symlink to one. The symlink's target is left alone. test.concurrent.each(["folder", "link"] as const)( "replaces a %s that has the cache name of a git checkout and no .bun-tag", async kind => { @@ -1835,8 +1823,8 @@ async function serveY() { type Linker = "hoisted" | "isolated"; -// A project with a docs/ folder of its own. The hoisted linker puts a package's own -// dependencies in node_modules//node_modules, the isolated linker beside it. +// Writes a project that has its own docs/ folder. The hoisted linker puts a package's own dependencies in +// node_modules//node_modules, and the isolated linker puts them next to the package. function writeProjectWithDocs( root: string, dependencies: Record, @@ -1850,8 +1838,8 @@ function writeProjectWithDocs( return project; } -// The folder of the `name` that the installed package `dependent` loads: its own copy -// if it has one, else the one in the node_modules folder that `dependent` is in. +// Returns the folder of the `name` that the installed package `dependent` loads: its own copy if it has one, or else +// the one in the node_modules folder that `dependent` is in. function dependencyOf(project: string, dependent: string, name: string) { const linked = join(project, "node_modules", dependent); const installed = existsSync(linked) ? realpathSync(linked) : linked; @@ -1859,8 +1847,8 @@ function dependencyOf(project: string, dependent: string, name: string) { return existsSync(own) ? own : join(dirname(installed), name); } -// The repository `a` needs its own copy of @x/docs (the project has another version). -// `commit` is what the repository itself commits in node_modules. +// The repository `a` needs its own copy of @x/docs, because the project has another version. `commit` is what the +// repository itself commits in node_modules. async function makeRepoWithNestedDependency(root: string, commit: Pick) { const bare = await makeSharedRepo( root, @@ -1876,8 +1864,7 @@ async function makeRepoWithNestedDependency(root: string, commit: Pick; linker: Linker }[] = [ { // three directories up from node_modules/a/node_modules is the project @@ -1927,7 +1914,7 @@ const committedNodeModules: { name: string; commit: Pick) { const bare = await makeSharedRepo( root, @@ -2000,9 +1987,8 @@ async function makeRepoWithBundledDependency(root: string, committed: Pick { using dir = tempDir("git-dep-optional-shared", {}); const root = String(dir); @@ -2267,11 +2252,9 @@ test.concurrent( }, ); -// A clone or checkout that failed while the dependencies were resolved stayed -// on record, and a locked dependency that needed the same one joined it when -// it got installed: the isolated linker waited forever, the hoisted linker -// skipped the package. The new dependency is optional or a peer, so its -// missing resolution does not end the install before that. +// A clone or checkout that failed during resolution stayed registered, and a locked dependency that needed the same one +// joined it at install time. The isolated linker then waited forever, and the hoisted linker skipped the package. The +// new dependency is optional or a peer, so its missing resolution doesn't end the install earlier. for (const linker of ["hoisted", "isolated"] as const) { const failedToInstall = (name: string, resolution: string, hoistedError: string) => linker === "hoisted" ? hoistedError : expect.stringContaining(`error: failed to download ${name}@${resolution}`); @@ -2369,9 +2352,8 @@ exec '${Bun.which("git")}' "$@" ); } -// A commit lookup that failed stayed on record too. A peer dependency is -// resolved in a later pass: it joined the finished lookup, ran no `git log`, -// and the install ended with an error about the first package only. +// A failed commit lookup stayed registered too. A peer dependency is resolved in a later pass, so it joined the +// finished lookup and ran no `git log`, and the install ended with an error about the first package only. test.concurrent("looks the commit up again for a peer dependency after the lookup failed for another one", async () => { using dir = tempDir("git-dep-failed-commit", {}); const root = String(dir); @@ -2379,7 +2361,7 @@ test.concurrent("looks the commit up again for a peer dependency after the looku const project = writeProject(root, {}, { optionalDependencies: { first: spec }, peerDependencies: { second: spec } }); const { stderr, exitCode } = await runInstall(project, join(root, "cache"), {}); - // git's own failures print at once, the lines about the packages after the resolve phase + // git's own errors are printed immediately, and the lines about the packages come after the resolve phase. expect(diagnostics(stderr)).toEqual([ gitFailed("warn"), gitFailed("error"), @@ -2450,9 +2432,8 @@ test.concurrent.each(["the environment", "the project's .env"])( }, ); -// The same for the `git init` / `git add` / `git commit` that `bun create` runs -// in the new project: they operated on the other repository, whose tracked -// files were committed away, and the new project got no `.git`. +// The same for the `git init`, `git add` and `git commit` that `bun create` runs in the new project. They operated on +// the other repository, whose tracked files were deleted by the commit, and the new project got no `.git`. test.concurrent( "bun create initializes the new project's own repository when GIT_DIR points at another one", async () => { @@ -2485,7 +2466,7 @@ test.concurrent( join(root, "cache"), { BUN_CREATE_DIR: join(root, "bun-create"), - // not the machine's: `commit.gpgsign` would fail the commit + // Don't use the machine's config, because `commit.gpgsign` would make the commit fail. GIT_CONFIG_GLOBAL: join(root, "gitconfig"), GIT_DIR: join(other, ".git"), GIT_INDEX_FILE: join(other, ".git", "index"), @@ -2502,14 +2483,13 @@ test.concurrent( }, ); -// `bun install` loads the project's `.env*` files so that bunfig.toml can -// reference `$VARIABLES`. Those files come with the repository being installed, -// so they must not configure the git the install spawns: git runs whatever -// `GIT_SSH_COMMAND`, `GIT_EXEC_PATH` or a `GIT_CONFIG_*` entry names, also under -// `--ignore-scripts`. Only the environment `bun install` was started with does. +// `bun install` loads the project's `.env*` files so that bunfig.toml can reference `$VARIABLES`. Those files come with +// the repository that's being installed, so they must not configure the git that the install spawns. git runs whatever +// `GIT_SSH_COMMAND`, `GIT_EXEC_PATH` or a `GIT_CONFIG_*` entry points to, even with `--ignore-scripts`. Only the +// environment that `bun install` was started with is passed on. // -// The variables a test sets through `.env` are removed from the install's real -// environment: a real one wins over `.env` in every build. +// The variables that a test sets through `.env` are removed from the install's real environment, because a real +// variable wins over `.env` in every build. const noGitTooling = { GIT_SSH: undefined, GIT_SSH_COMMAND: undefined, @@ -2519,8 +2499,8 @@ const noGitTooling = { XDG_CONFIG_HOME: undefined, }; -// ` \n', @@ -5943,22 +6137,22 @@ describe.concurrent("the plugins jsdoc and vue of oxlint, of which no rule is bu const found = ["a.js:2:17 no-debugger", "b.vue:2:1 no-debugger"]; const clean = { "a.js": "export {};\n", "b.vue": "\n" }; const quiet = { categories: { correctness: "off" }, rules: { "no-debugger": "warn" } }; - const named = (plugin: string, ...rules: string[]) => + const notSupported = (plugin: string, ...rules: string[]) => `${rules.length} ${rules.length > 1 ? "rules" : "rule"} in .oxlintrc.json ${rules.length > 1 ? "are" : "is"} not supported: ${rules.join(", ")}`; - const ofCategories = (...plugins: string[]) => + const noRulesNote = (...plugins: string[]) => `note: bun lint has no "${plugins.join('" or "')}" rules, so none of them ran`; - const silent = { problems: found, exitCode: 0, said: [], notes: [] }; - /** What is reported, the exit code, what is said about what cannot be done, and the notes. */ + const silent = { problems: found, exitCode: 0, errors: [], notes: [] }; + /** Returns the problems, the exit code, and stderr's "error: " lines (`errors`) and "note: " lines. */ async function run(config: object, flags: string[] = [], more: Record = {}) { const all = { ...files, ...more, ".oxlintrc.json": JSON.stringify(config) }; const { problems, stderr, exitCode } = await lint(all, [...flags, "."]); const lines = stderr.split("\n"); - const said = lines.filter(it => it.startsWith("error: ")).map(it => it.slice("error: ".length)); + const errorLines = lines.filter(it => it.startsWith("error: ")).map(it => it.slice("error: ".length)); const notes = lines.filter(it => it.startsWith("note: ")); - return { problems, exitCode, said: said.map(it => it.trim()), notes }; + return { problems, exitCode, errors: errorLines.map(it => it.trim()), notes }; } - test("a rule of theirs that is on: the rest is linted, and the run fails", async () => { + test("enabling one of their rules still runs the other rules, then exits 2 unless --allow-unsupported is passed", async () => { const rules = { ...quiet.rules, "jsdoc/require-param": "error", @@ -5968,7 +6162,7 @@ describe.concurrent("the plugins jsdoc and vue of oxlint, of which no rule is bu expect(await run({ ...quiet, plugins: ["jsdoc", "vue"], rules })).toEqual({ problems: found, exitCode: 2, - said: [named("jsdoc", "jsdoc/require-param"), named("vue", "vue/no-dupe-keys", "vue/max-props")], + errors: [notSupported("jsdoc", "jsdoc/require-param"), notSupported("vue", "vue/no-dupe-keys", "vue/max-props")], notes: [], }); const allowed = await lint( @@ -5976,16 +6170,16 @@ describe.concurrent("the plugins jsdoc and vue of oxlint, of which no rule is bu ["--allow-unsupported", "."], ); expect(allowed.stderr).toContain( - `warn: ${named("jsdoc", "jsdoc/require-param")}\n bun lint has no "jsdoc" rules. Turn it off or remove it.\n`, + `warn: ${notSupported("jsdoc", "jsdoc/require-param")}\n bun lint has no "jsdoc" rules. Turn it off or remove it.\n`, ); expect(allowed.exitCode).toBe(0); }); - test("a rule that is off, or of a plugin that is not on, says nothing", async () => { + test("a rule that's off, or whose plugin isn't enabled, prints nothing", async () => { const on = { ...quiet.rules, "jsdoc/require-param": "error", "vue/no-dupe-keys": "error" }; const off = { ...quiet.rules, "jsdoc/require-param": "off", "vue/no-dupe-keys": "allow" }; expect(await run({ ...quiet, plugins: ["jsdoc", "vue"], rules: off })).toEqual(silent); - // As in oxlint, where it does not run either. + // Like oxlint, which doesn't run the rule either. expect(await run({ ...quiet, rules: on })).toEqual(silent); const base = { "base.json": JSON.stringify({ plugins: ["jsdoc", "vue"], rules: on }) }; expect(await run({ ...quiet, extends: ["./base.json"], plugins: ["jsdoc", "vue"], rules: off }, [], base)).toEqual( @@ -5993,74 +6187,75 @@ describe.concurrent("the plugins jsdoc and vue of oxlint, of which no rule is bu ); }); - test("the plugins alone say nothing", async () => { + test("listing the plugins with every category off prints nothing", async () => { expect(await run({ ...quiet, plugins: ["jsdoc", "vue"] })).toEqual(silent); }); - test("in overrides", async () => { + test("enabling one of their rules in overrides fails the run", async () => { const overrides = [{ files: ["*.vue"], plugins: ["vue"], rules: { "vue/no-dupe-keys": "error" } }]; expect(await run({ ...quiet, overrides })).toEqual({ problems: found, exitCode: 2, - said: [named("vue", "vue/no-dupe-keys")], + errors: [notSupported("vue", "vue/no-dupe-keys")], notes: [], }); }); test.each([ - [["--vue-plugin", "-D", "vue/no-dupe-keys"], [named("vue", "vue/no-dupe-keys")], []], - [["--vue-plugin", "-W", "vue/no-dupe-keys"], [named("vue", "vue/no-dupe-keys")], []], + [["--vue-plugin", "-D", "vue/no-dupe-keys"], [notSupported("vue", "vue/no-dupe-keys")], []], + [["--vue-plugin", "-W", "vue/no-dupe-keys"], [notSupported("vue", "vue/no-dupe-keys")], []], [["--vue-plugin", "-D", "vue/no-dupe-keys", "-A", "vue/no-dupe-keys"], [], []], - [["--vue-plugin", "--jsdoc-plugin", "-D", "correctness"], [], [ofCategories("jsdoc", "vue")]], + [["--vue-plugin", "--jsdoc-plugin", "-D", "correctness"], [], [noRulesNote("jsdoc", "vue")]], [["--vue-plugin"], [], []], [["-D", "vue/no-dupe-keys"], [], []], - ])("%j", async (flags, said, notes) => { + ])("on the command line: %j", async (flags, errors, notes) => { expect(await run({ ...quiet, rules: {} }, flags, clean)).toEqual({ problems: [], - exitCode: said.length > 0 ? 2 : 0, - said, + exitCode: errors.length > 0 ? 2 : 0, + errors, notes, }); }); - // `correctness` is on unless a file says otherwise, and oxlint has rules of both in it. - test("a plugin that is only listed, and a category that oxlint has rules of it in: a note", async () => { + // `correctness` is on by default, and oxlint has rules from both plugins in it. + test("listing a plugin prints a note if oxlint has rules from it in a category that's on", async () => { const config = (categories: object) => ({ categories: { correctness: "off", ...categories }, plugins: ["vue"] }); - const noted = { problems: [], exitCode: 0, said: [], notes: [ofCategories("vue")] }; - const passes = { problems: [], exitCode: 0, said: [], notes: [] }; + const noted = { problems: [], exitCode: 0, errors: [], notes: [noRulesNote("vue")] }; + const passes = { problems: [], exitCode: 0, errors: [], notes: [] }; expect(await run(config({ correctness: "error" }), [], clean)).toEqual(noted); expect(await run({ plugins: ["vue"] }, [], clean)).toEqual(noted); expect(await run(config({ restriction: "warn" }), [], clean)).toEqual(noted); - // The exit code is that of the other rules. + // The other rules decide the exit code. expect(await run(config({ correctness: "error" }), [], { ...clean, "c.js": "debugger;\nexport {};\n" })).toEqual({ ...noted, problems: ["c.js:1:1 no-debugger"], exitCode: 1, }); - // It has none that are about speed. + // oxlint has no vue rules in `perf`. expect(await run(config({ perf: "error" }), [], clean)).toEqual(passes); expect(await run(config({}), [], clean)).toEqual(passes); - // For the files of an override that are linted. + // A plugin that an override lists gets the note only if a linted file matches the override. const override = (pattern: string) => ({ overrides: [{ files: [pattern], plugins: ["vue"] }] }); expect(await run({ plugins: ["unicorn"], ...override("*.vue") }, [], clean)).toEqual(noted); expect(await run({ plugins: ["unicorn"], ...override("*.svelte") }, [], clean)).toEqual(passes); - // oxlint 1.87 runs none of them there: the override names all the plugins of the file. + // oxlint 1.87 runs no vue rules here. It doesn't apply categories to an override's plugins if the override lists + // every plugin that's on for the file. expect(await run({ plugins: [], ...override("*.vue") }, [], clean)).toEqual(passes); }); - test("a rule that is named and a plugin that is only listed: the run fails, and the note is there", async () => { + test("fails the run and still prints the note if a rule is enabled and a plugin is only listed", async () => { const config = { plugins: ["jsdoc", "vue"], rules: { "vue/no-dupe-keys": "error" } }; expect(await run(config, [], clean)).toEqual({ problems: [], exitCode: 2, - said: [named("vue", "vue/no-dupe-keys")], - notes: [ofCategories("jsdoc", "vue")], + errors: [notSupported("vue", "vue/no-dupe-keys")], + notes: [noRulesNote("jsdoc", "vue")], }); }); - // It is on stderr, so what reads a report does not see it. + // The note goes to stderr, so a program that parses the report never sees it. test.each(["--format=json", "--format=github", "--format=unix", "--format=pretty", "--quiet"])( - "the note is there with %s", + "prints the note with %s, and stdout is the same as without the note", async flag => { const config = (plugins: string[]) => ({ ".oxlintrc.json": JSON.stringify({ plugins, rules: { "no-debugger": "error" } }), @@ -6069,35 +6264,36 @@ describe.concurrent("the plugins jsdoc and vue of oxlint, of which no rule is bu lint({ ...files, ...config(["vue"]) }, [flag, "."]), lint({ ...files, ...config([]) }, [flag, "."]), ]); - expect(noted.stderr.split("\n").filter(it => it.startsWith("note: "))).toEqual([ofCategories("vue")]); - const timeless = (stdout: string) => + expect(noted.stderr.split("\n").filter(it => it.startsWith("note: "))).toEqual([noRulesNote("vue")]); + const stripTimes = (stdout: string) => stdout.replace(/"start_time": [\d.e-]+|\d+(\.\d+)?m?s\b|bun-lint-config-files_\w+/g, ""); - expect(timeless(noted.stdout)).toBe(timeless(plain.stdout)); + expect(stripTimes(noted.stdout)).toBe(stripTimes(plain.stdout)); expect([noted.exitCode, plain.exitCode]).toEqual([1, 1]); }, ); - test("only --silent hides it", async () => { + test("only --silent hides the note", async () => { const all = { ...clean, ".oxlintrc.json": JSON.stringify({ plugins: ["vue"] }) }; const { stderr, exitCode } = await lint(all, ["--silent", "."]); expect(stderr).not.toContain("note: "); expect(exitCode).toBe(0); }); - test("settings for them are taken", async () => { + test("accepts settings for them", async () => { const settings = { jsdoc: { ignorePrivate: true, nothing: 1 }, vue: { nothing: 1 } }; expect(await run({ ...quiet, settings })).toEqual(silent); }); - test("any other plugin that oxlint does not know is still refused", async () => { + test("still rejects any other plugin that oxlint doesn't know", async () => { const { stdout, exitCode } = await lint({ ...files, ".oxlintrc.json": JSON.stringify({ plugins: ["jsdocs"] }) }); expect(stdout).toContain(`Unknown plugin: 'jsdocs'.`); expect(exitCode).toBe(1); }); - test("a comment that disables one of their rules is neither wrong nor unused, and stays, if such a rule is on", async () => { + test("a disable comment for one of their rules isn't reported as unused, or removed, while one of their rules is on", async () => { const text = [ - // oxlint's jsdoc rules look at comments like this one. Without any, none of them could have reported anything. + // oxlint's jsdoc rules only look at comments like this one. In a file without one, they couldn't have reported + // anything. "/** A function. */", "// oxlint-disable-next-line jsdoc/require-param", "a;", @@ -6113,14 +6309,14 @@ describe.concurrent("the plugins jsdoc and vue of oxlint, of which no rule is bu expect(JSON.parse(raw).results[0].messages[0].message).toBe( "Unused eslint-disable directive (no problems were reported from no-debugger).", ); - // From a script in such a file oxlint removes what is unused. + // oxlint removes the unused part from the script of a .vue file too. const fixed = await lint(all, ["--report-unused-disable-directives", "--fix-dry-run", "b.vue"]); expect(JSON.parse(fixed.raw).results[0].output).toBe(`\n`); }); - // What oxlint 1.87 reports: each of these comments, whole. Its jsdoc rules only look at `/**` comments, so in a file without one - // none of them was skipped, and a comment that silences nothing here silences nothing there. - test("without a /** comment, comments are unused as for oxlint although rules of jsdoc are on", async () => { + // oxlint 1.87 reports each of these comments as a whole. Its jsdoc rules only look at `/**` comments, so in a file + // without one bun lint didn't skip anything they'd report, and a comment that's unused here is unused in oxlint too. + test("without a /** comment, disable comments are reported as unused like in oxlint, even if jsdoc rules are on", async () => { const text = [ "// oxlint-disable-next-line jsdoc/require-param", "a;", @@ -6137,8 +6333,9 @@ describe.concurrent("the plugins jsdoc and vue of oxlint, of which no rule is bu const all = { "a.js": text, "b.vue": `\n`, ".oxlintrc.json": JSON.stringify(on) }; const { problems } = await lint(all, ["--report-unused-disable-directives", "."]); expect(problems).toEqual([1, 3, 5, 7, 9].flatMap(line => [`a.js:${line}:1 -`, `b.vue:${line + 1}:1 -`]).sort()); - // oxlint reports the same with these. Here nobody knows what their rules would have reported, and a comment that is called - // unused is one that --fix-suggestions removes. So only a name that none of their rules has is reported. + // oxlint reports the same comments with these files. bun lint can't know what the jsdoc and vue rules would have + // reported, and --fix-suggestions removes a comment that's reported as unused. So it only reports rule names that + // neither plugin has. const withBlock = { ...all, "a.js": `/** A function. */\n${text}`, "b.vue": "" }; const withVue = { ...all, @@ -6152,14 +6349,14 @@ describe.concurrent("the plugins jsdoc and vue of oxlint, of which no rule is bu expect(vue.problems).toEqual(["a.js:3:47 -", "a.js:7:29 -"]); }); - test("--rules does not list them", async () => { + test("--rules doesn't list them", async () => { const { raw } = await lint({ ".oxlintrc.json": "{}" }, ["--rules", "-f", "json"]); const scopes = new Set(JSON.parse(raw).map((it: { scope: string }) => it.scope)); expect([scopes.has("unicorn"), scopes.has("jsdoc"), scopes.has("vue")]).toEqual([true, false, false]); }); - // No rule here has ever answered for them. - test("beside a configuration of ESLint they are the packages of the project", async () => { + // bun lint has never had built-in rules for these packages. + test("with an ESLint config, jsdoc and vue rules come from the project's packages", async () => { const plugin = (name: string) => `module.exports = { meta: { name: "eslint-plugin-${name}" }, rules: { "no-dupe-keys": { create: context => ({ Program: node => context.report({ node, message: "of the package" }) }) } } };`; const { problems, exitCode } = await lint({ @@ -6178,10 +6375,10 @@ describe.concurrent("the plugins jsdoc and vue of oxlint, of which no rule is bu }); }); -// As ESLint 10.12 with eslint-plugin-import 2.32.0 and eslint-plugin-react 7.37.5: `" ".repeat(n)` throws beyond the longest string that -// JavaScript has, 2 ** 29 - 24, and for a negative n: the rule throws, which ends the run. Below that ESLint reports as ever, in a format -// that does not print the fixes: its `json` throws over them. -describe.concurrent("a number in the options of a rule that is the length of a text", () => { +// Same as ESLint 10.12 with eslint-plugin-import 2.32.0 and eslint-plugin-react 7.37.5. `" ".repeat(n)` throws if n is +// negative or above the maximum string length, 2 ** 29 - 24, so the rule throws, which ends the run. Below that limit +// ESLint reports as usual, as long as the format doesn't print the fixes. Its `json` format throws on them. +describe.concurrent("a rule option that's used as a string length", () => { const element = 'const a = (\n \n \n
\n);\n'; const tooLong = "RangeError: Invalid string length"; test.each< @@ -6189,12 +6386,12 @@ describe.concurrent("a number in the options of a rule that is the length of a t >([ ["import/newline-after-import", { count: 2 ** 53 }, "a.js", '\nimport "a";\nb();\n', [tooLong, 2]], ["import/newline-after-import", { count: 2 ** 29 }, "a.js", '\nimport "a";\nb();\n', [tooLong, 2]], - // The calls are looked at when the program ends. + // `require` calls are checked in `Program:exit`, so the line is the start of the program. ["import/newline-after-import", { count: 2 ** 31 }, "a.js", '\n\nconst a = require("a");\nb();\n', [tooLong, 1]], ["react/jsx-indent", 2 ** 31, "a.jsx", element, [tooLong, 2]], - // Nothing is repeated. + // There's no JSX, so nothing is repeated. ["react/jsx-indent", 2 ** 31, "a.jsx", "a();\n", []], - // Only twice as much is too long. + // One level of indentation fits. Two levels are too long. ["react/jsx-indent", 2 ** 29 - 24, "a.jsx", element, [tooLong, 5]], ["react/jsx-indent", -1, "a.jsx", element, ["RangeError: Invalid count value: -1", 2]], ["react/jsx-indent-props", 2 ** 31, "a.jsx", element, [tooLong, 2]], @@ -6221,7 +6418,7 @@ describe.concurrent("a number in the options of a rule that is the length of a t }); }); -// As ESLint 9.39.5, but for the kind of the error before the message. +// Same as ESLint 9.39.5, except for the error's name before the message. test.concurrent.each([ ["[", 'Syntax error in selector "[" at position 1: Expected " " or [^ [\\],():#!=><~+.] but end of input found.'], [ @@ -6230,19 +6427,19 @@ test.concurrent.each([ ], [":foo", "Unknown class name: foo"], [`${":not(".repeat(100_000)}a${")".repeat(100_000)}`, "Maximum call stack size exceeded"], -])("no-restricted-syntax with a selector that cannot be read: %#", async (option, message) => { +])("no-restricted-syntax with an invalid selector ends the run: %#", async (option, message) => { const files = { ".eslintrc.json": rc({ rules: { "no-restricted-syntax": ["error", "Foo", option] } }), "a.js": code }; const { problems, stderr, exitCode } = await lint(files, ["a.js"]); - // `lint` has a `/` for each backslash. + // `lint` turns every backslash into a `/`. expect(stderr).toContain(`${message.replaceAll("\\", "/")}\nOccurred while linting /a.js`); expect({ problems, exitCode }).toEqual({ problems: [], exitCode: 2 }); }); -// What reads a selector holds more levels than what matches it: how many depends on the build and on the system. Between -// the two, each `:has()` took the end of the stack for a node that does not match, and went on to the next one. -// ESLint 9.39.5 reports the ten nodes up to 999 levels. +// The selector parser handles deeper nesting than the matcher. How deep depends on the build and the platform. Between +// the two limits, each `:has()` used to treat a stack overflow as a node that doesn't match, and continued with the +// next node. ESLint 9.39.5 reports the ten nodes up to 999 levels. test.concurrent.each(Array.from({ length: 24 }, (_, i) => Math.ceil(300 * 1.2 ** i)))( - "no-restricted-syntax with `:has()` nested about as deep as the stack holds: %d", + "no-restricted-syntax with `:has()` nested close to the stack limit reports every node or fails: %d", async depth => { const selector = `${":has(".repeat(depth)}*${")".repeat(depth)}`; const files = { ".eslintrc.json": rc({ rules: { "no-restricted-syntax": ["error", selector] } }), "a.js": code }; @@ -6254,9 +6451,9 @@ test.concurrent.each(Array.from({ length: 24 }, (_, i) => Math.ceil(300 * 1.2 ** }, ); -// As ESLint 10.12. What is in a plugin of the configuration is known, whether or not a rule of it is on. +// Same as ESLint 10.12. The rules of a plugin in the config are known whether or not the config turns one on. test.concurrent( - "a rule that only a comment names, of a plugin of which the configuration turns no rule on", + "comments can refer to a plugin's rule even if the config turns on none of that plugin's rules", async () => { const files = { "eslint.config.mjs": `export default [{ @@ -6282,22 +6479,23 @@ test.concurrent( }, ); -// ───────────── paths, as each system writes and compares them ───────────── +// ───────────── paths, as each platform writes and compares them ───────────── // `bun lint --run-path-tests` is compiled into debug and canary builds only. const hasRunner = isDebug || Bun.spawnSync({ cmd: [bunExe(), "--revision"], env: bunEnv }).stdout.includes("canary"); const quiet = { categories: { correctness: "off" } }; -// A configuration goes by what a base path looks like, so what it makes of the paths of Windows is tested on every system. What is -// expected of the flat ones is what `ConfigArray` of @eslint/config-array 0.23.5 answers, which goes by that too. -describe.skipIf(!hasRunner)("the paths of Windows, on every system", () => { - async function configurations(cases: object[]) { +// A config picks Windows or POSIX path rules by what its base path looks like, so Windows paths can be tested on every +// platform. The expected results for flat configs come from `ConfigArray` in @eslint/config-array 0.23.5, which picks +// the same way. +describe.skipIf(!hasRunner)("Windows paths, on every platform", () => { + async function resolveConfigs(cases: object[]) { using dir = tempDir("bun-lint-paths", { "cases.json": JSON.stringify(cases) }); await using proc = spawn({ cmd: [...command, "--run-path-tests", "configurations", join(String(dir), "cases.json")], env, - // Not where a `package.json` has a script `lint`. + // Not a directory whose `package.json` has a `lint` script. cwd: String(dir), stdout: "pipe", stderr: "inherit", @@ -6307,9 +6505,9 @@ describe.skipIf(!hasRunner)("the paths of Windows, on every system", () => { return JSON.parse(stdout); } - test("what is in a directory is in it however the two are spelled", async () => { + test("a file is inside a base path regardless of letter case and slash direction", async () => { expect( - await configurations([ + await resolveConfigs([ { basePath: "c:/proj", config: [noVar], @@ -6324,7 +6522,7 @@ describe.skipIf(!hasRunner)("the paths of Windows, on every system", () => { files: ["C:/proj/src/a.js", "C:/proj/src/ignored.js", "C:/proj/src/deep/a.js", "C:/proj/SRC/a.js"], }, { basePath: "C:/proj/Ünï", config: [noVar], files: ["C:/proj/üNÏ/a.js"] }, - // Elsewhere it is not. + // POSIX paths are case-sensitive. { basePath: "/proj", config: [noVar], files: ["/proj/a.js", "/PROJ/a.js"] }, ]), ).toEqual([ @@ -6335,7 +6533,7 @@ describe.skipIf(!hasRunner)("the paths of Windows, on every system", () => { ]); }); - test("a share, and the root of a drive", async () => { + test("a base path can be on a network share or be the root of a drive", async () => { const proj = "//server/share/proj"; const onShare = (basePath: string) => ({ basePath: proj, @@ -6354,36 +6552,36 @@ describe.skipIf(!hasRunner)("the paths of Windows, on every system", () => { const share = { files: [["no-var"], [], "external", "ignored"], directories: [true, false] }; const root = { files: [["no-var"], ["eqeqeq"], ["eqeqeq"], []], directories: [] }; expect( - await configurations([ + await resolveConfigs([ onShare(String.raw`\\SERVER\Share\proj\src`), onShare("//server/share/proj/src"), onShare("src"), atRoot("X:/"), atRoot("X:"), - // What has no configuration file has one in which everything is. + // A run without a config file has the base path `/`, which contains every path. { basePath: "/", config: [noVar], files: ["C:/a/b.js", "D:/a/b.js", `${proj}/a.js`] }, ]), ).toEqual([share, share, share, root, root, { files: [["no-var"], ["no-var"], ["no-var"]], directories: [] }]); }); - test("`ignorePatterns` of oxlint say nothing about what is outside", async () => { + test("oxlint's `ignorePatterns` don't apply to files outside the config's directory", async () => { const config = { ...quiet, ...noVar, ignorePatterns: ["*.js"] }; const expected = { files: [["no-var"], "ignored"], directories: [] }; expect( - await configurations([ + await resolveConfigs([ { basePath: "/proj/config", flavor: "oxlint", config, files: ["/proj/src/a.js", "/proj/config/a.js"] }, { basePath: "C:/proj/config", flavor: "oxlint", config, files: ["C:/proj/src/a.js", "C:/proj/config/a.js"] }, ]), ).toEqual([expected, expected]); }); - test.each(["oxlint", "eslintrc"])("`extends` of %s with `\\`", async flavor => { - const [{ error, files }] = await configurations([ + test.each(["oxlint", "eslintrc"])("`extends` in an %s config can use `\\`", async flavor => { + const [{ error, files }] = await resolveConfigs([ { basePath: "C:/proj", flavor, config: { ...(flavor === "oxlint" ? quiet : { root: true }), extends: [String.raw`..\shared\base.json`] }, - // What it extends in turn is next to it. + // A nested `extends` is relative to the file that has it. extended: { "C:/shared/base.json": { extends: [String.raw`.\more.json`], ...eqeqeq }, "C:/shared/more.json": noVar, @@ -6397,8 +6595,9 @@ describe.skipIf(!hasRunner)("the paths of Windows, on every system", () => { }); }); -// What ESLint 10.12.0, ESLint 8.57.1 and oxlint 1.87.0 do with the same files. Without a configuration file as oxlint. -describe.skipIf(isWindows).concurrent("a symbolic link that leads nowhere, to itself, or back up", () => { +// This is what ESLint 10.12.0, ESLint 8.57.1 and oxlint 1.87.0 do with the same files. Without a config file, bun lint +// behaves like oxlint. +describe.skipIf(isWindows).concurrent("a symlink that's dangling or points to itself or a parent directory", () => { const flavors: Record> = { "eslint.config.js": { "eslint.config.js": `export default [${JSON.stringify(noVar)}];` }, ".eslintrc.json": { ".eslintrc.json": rc(noVar) }, @@ -6407,7 +6606,7 @@ describe.skipIf(isWindows).concurrent("a symbolic link that leads nowhere, to it "no file": {}, }; const others = { "a.js": code, "sub/b.js": code }; - /** The files with problems, what is printed, and the exit code. `links`: where each is, and what it has. */ + /** Returns the files with problems, the output and the exit code. `links` maps each symlink's path to its target. */ const linted = async (flavor: string, links: Record, args = ["."], files = others) => { const inProject = Object.entries({ ...flavors[flavor], ...files }).map(([name, text]) => [`project/${name}`, text]); const before = (dir: string) => @@ -6417,10 +6616,10 @@ describe.skipIf(isWindows).concurrent("a symbolic link that leads nowhere, to it const names = problems.map(it => it.split(":")[0].replace("project/", "")); return { files: [...new Set(names)], stdout, stderr: stderr.replaceAll("/project/", "/"), exitCode }; }; - const passingOver = [".eslintrc.json", ".oxlintrc.json", "bunfig.toml", "no file"]; - const asOxlint = [".oxlintrc.json", "bunfig.toml", "no file"]; + const exceptFlatConfig = [".eslintrc.json", ".oxlintrc.json", "bunfig.toml", "no file"]; + const likeOxlint = [".oxlintrc.json", "bunfig.toml", "no file"]; - test.each(passingOver)("one that leads nowhere is passed over by a search: %s", async flavor => { + test.each(exceptFlatConfig)("a directory search skips a dangling symlink: %s", async flavor => { const links = { "gone.js": "nowhere.js", "sub/gone.js": "/nowhere/at/all.js", @@ -6432,59 +6631,63 @@ describe.skipIf(isWindows).concurrent("a symbolic link that leads nowhere, to it } }); - // "Error: ENOENT: no such file or directory, open '/gone.js'", "Error: ELOOP: too many symbolic links encountered, open .." + // ESLint prints "Error: ENOENT: no such file or directory, open '/gone.js'" and "Error: ELOOP: too many symbolic + // links encountered, open ..". test.each([ ["gone.js", "nowhere.js", "ENOENT"], ["self.js", "self.js", "ELOOP"], - ])("ESLint reads %s, which leads to %s, and that is the end of the run", async (name, to, code) => { - const { files, stderr, exitCode } = await linted("eslint.config.js", { [name]: to }); - expect(stderr).toContain(`Cannot read /${name}: ${code}: `); - expect({ files, exitCode }).toEqual({ files: [], exitCode: 2 }); - // It does not ask what a link is that it does not lint. - expect( - await linted("eslint.config.js", { "gone": "nowhere", "self": "self", "sub/gone.md": "nowhere.md" }), - ).toMatchObject({ - files: ["a.js", "sub/b.js"], - exitCode: 1, - }); - }); - - test.each(asOxlint)( - "one that leads to itself, and two that lead to each other, are passed over: %s", - async flavor => { - const links = { "self.js": "self.js", "self": "self", "sub/c.js": "d.js", "sub/d.js": "c.js" }; - expect(await linted(flavor, links)).toMatchObject({ files: ["a.js", "sub/b.js"], exitCode: 1 }); + ])( + "with an eslint.config.js, like ESLint, %s pointing to %s can't be read, which ends the run", + async (name, to, code) => { + const { files, stderr, exitCode } = await linted("eslint.config.js", { [name]: to }); + expect(stderr).toContain(`Cannot read /${name}: ${code}: `); + expect({ files, exitCode }).toEqual({ files: [], exitCode: 2 }); + // ESLint doesn't resolve a link that it wouldn't lint. + expect( + await linted("eslint.config.js", { "gone": "nowhere", "self": "self", "sub/gone.md": "nowhere.md" }), + ).toMatchObject({ + files: ["a.js", "sub/b.js"], + exitCode: 1, + }); }, ); + test.each(likeOxlint)("skips a symlink to itself and two symlinks to each other: %s", async flavor => { + const links = { "self.js": "self.js", "self": "self", "sub/c.js": "d.js", "sub/d.js": "c.js" }; + expect(await linted(flavor, links)).toMatchObject({ files: ["a.js", "sub/b.js"], exitCode: 1 }); + }); + test.each([ [{ "self.js": "self.js" }, ["."], "self.js"], - // Whatever it is called, and wherever it is. + // With any name, in any directory. [{ "self": "self" }, ["."], "self"], [{ "node_modules/self": "self" }, ["."], "node_modules/self"], [{ "sub/self.md": "self.md" }, ["**/*.js"], "sub/self.md"], [{ "self.js": "self.js" }, ["a.js", "self.js"], "self.js"], - ])("ESLint 8 asks where every link leads, and %j is the end of the run", async (links, args, name) => { - const files = { ...others, "node_modules/.keep": "" }; - const { stderr, exitCode } = await linted(".eslintrc.json", links as Record, args, files); - expect(stderr).toContain(`ELOOP: too many symbolic links encountered, stat '/${name}'`); - expect(exitCode).toBe(2); - }); + ])( + "with an .eslintrc.json, like ESLint 8, every symlink is resolved, so %j ends the run", + async (links, args, name) => { + const files = { ...others, "node_modules/.keep": "" }; + const { stderr, exitCode } = await linted(".eslintrc.json", links as Record, args, files); + expect(stderr).toContain(`ELOOP: too many symbolic links encountered, stat '/${name}'`); + expect(exitCode).toBe(2); + }, + ); - test("nothing but a link that leads nowhere is nothing", async () => { + test("a directory with only a dangling symlink has no files to lint", async () => { const only = (flavor: string) => linted(flavor, { "gone.js": "nowhere.js" }, ["."], {}); const [eslint8, oxlint] = await Promise.all([only(".eslintrc.json"), only(".oxlintrc.json")]); - // 'No files matching the pattern "." were found.' + // Same message as ESLint 8.57.1: 'No files matching the pattern "." were found.' expect(eslint8.stderr).toContain('pattern "."'); expect(eslint8.exitCode).toBe(2); expect(oxlint.stdout).toContain("No files found to lint. Please check your paths and ignore patterns."); expect(oxlint.exitCode).toBe(1); }); - test("one that leads nowhere and is an argument is a file that is not there", async () => { - const named = (flavor: string) => linted(flavor, { "gone.js": "nowhere.js" }, ["gone.js", "a.js"]); + test("a dangling symlink passed as an argument is treated as a missing file", async () => { + const asArgument = (flavor: string) => linted(flavor, { "gone.js": "nowhere.js" }, ["gone.js", "a.js"]); const [eslint, eslint8, oxlint] = await Promise.all( - ["eslint.config.js", ".eslintrc.json", ".oxlintrc.json"].map(named), + ["eslint.config.js", ".eslintrc.json", ".oxlintrc.json"].map(asArgument), ); for (const { stderr, exitCode } of [eslint, eslint8]) { expect(stderr).toContain('No files matching the pattern "gone.js" were found.'); @@ -6493,45 +6696,42 @@ describe.skipIf(isWindows).concurrent("a symbolic link that leads nowhere, to it expect(oxlint).toMatchObject({ files: ["a.js"], exitCode: 1 }); }); - test.each(passingOver)("one that leads to a directory is followed: %s", async flavor => { + test.each(exceptFlatConfig)("follows a symlink to a directory: %s", async flavor => { expect(await linted(flavor, { "linked": "sub", "sub/out": "../../outside" })).toMatchObject({ files: ["a.js", "linked/b.js", "linked/out/c.js", "sub/b.js", "sub/out/c.js"], exitCode: 1, }); }); - test.each(asOxlint)( - "an ignore file is asked about the path with the link in it, not where that leads: %s", - async flavor => { - const files = { ...others, "hid/h.js": code, ".gitignore": "hid/\nskipped\n" }; - expect(await linted(flavor, { "shown": "hid", "skipped": "sub" }, ["."], files)).toMatchObject({ - files: ["a.js", "shown/h.js", "sub/b.js"], - exitCode: 1, - }); - }, - ); + test.each(likeOxlint)("ignore files match the path through the symlink, not its target: %s", async flavor => { + const files = { ...others, "hid/h.js": code, ".gitignore": "hid/\nskipped\n" }; + expect(await linted(flavor, { "shown": "hid", "skipped": "sub" }, ["."], files)).toMatchObject({ + files: ["a.js", "shown/h.js", "sub/b.js"], + exitCode: 1, + }); + }); - test.each(asOxlint)("one that leads above where the search starts is followed, once: %s", async flavor => { + test.each(likeOxlint)("follows a symlink to a parent of the search root, once: %s", async flavor => { expect(await linted(flavor, { "up": ".." })).toMatchObject({ files: ["a.js", "sub/b.js", "up/outside/c.js", "up/project/a.js", "up/project/sub/b.js"], exitCode: 1, }); }); - test.each(asOxlint)("one that leads back up is passed over: %s", async flavor => { + test.each(likeOxlint)("skips a symlink to one of its parent directories inside the search root: %s", async flavor => { const links = { "here": ".", "sub/up": "..", "sub/too": "../sub" }; expect(await linted(flavor, links)).toMatchObject({ files: ["a.js", "sub/b.js"], exitCode: 1 }); }); - // It goes round until the system has had enough: "ELOOP: too many symbolic links encountered, stat '/here/here/here/.." + // ESLint 8 loops until the OS gives up: "ELOOP: too many symbolic links encountered, stat '/here/here/here/.." test.each([ [{ "here": "." }, "here"], [{ "sub/up": ".." }, "sub/up"], - ])("ESLint 8 follows %j to the end of the run", async (links, name) => { + ])("with an .eslintrc.json, like ESLint 8, following %j ends the run with ELOOP", async (links, name) => { const { stderr, exitCode } = await linted(".eslintrc.json", links as Record); expect(stderr).toContain(`ELOOP: too many symbolic links encountered, stat '/${name}`); expect(exitCode).toBe(2); - // Not where it does not go. + // Not if the link is ignored, because the search never enters it. const ignoring = { ".eslintrc.json": rc({ ...noVar, ignorePatterns: [name] }), ...others }; expect(await linted("no file", links as Record, ["."], ignoring)).toMatchObject({ files: ["a.js", "sub/b.js"], @@ -6540,34 +6740,35 @@ describe.skipIf(isWindows).concurrent("a symbolic link that leads nowhere, to it }); }); -// What ESLint 10.12.0 lints, and which configuration files it runs. It judges a directory by the configuration of the directory -// that it is in. Where that has no file, the base path is the working directory, and what is outside of it is ignored. -describe.concurrent("a search that leaves the project of an eslint.config.js", () => { +// Matches what ESLint 10.12.0 lints and which config files it runs. It decides whether to enter a directory with the +// config of that directory's parent. If the parent has no config file, the base path is the working directory, and +// everything outside it is ignored. +describe.concurrent("a search that goes outside an eslint.config.js project", () => { const scripts = ["mine", "mine/sub", "mine/nested", "theirs", "theirs/deep", "none", "none/in"]; const inRepository = ["repo", "repo/packages/a", "repo/packages/b", "repo/packages/b/own", "repo/packages/c"]; const files = Object.fromEntries([...scripts, ...inRepository].map(it => [`w/${it}/x.js`, "debugger;\n"])); const configured = ["mine", "mine/nested", "theirs", "theirs/deep", "repo", "repo/packages/b/own"]; type More = { files?: Record; links?: Record }; - /** The configuration files that ran, but for that of the working directory, which always does, and the files with problems. */ + /** Returns the directories whose config file ran, and the files with problems. */ const run = async (cwd: string, args: string[], more: More = {}) => { using logs = tempDir("bun-lint-config-files-ran", {}); const log = join(String(logs), "ran.log"); const before = (dir: string) => { for (const it of configured) { - const says = `fs.appendFileSync(${JSON.stringify(log)}, ${JSON.stringify(it + "\n")});`; - const text = `import fs from "node:fs";\n${says}\nexport default [{ rules: { "no-debugger": "error" } }];\n`; + const logRun = `fs.appendFileSync(${JSON.stringify(log)}, ${JSON.stringify(it + "\n")});`; + const text = `import fs from "node:fs";\n${logRun}\nexport default [{ rules: { "no-debugger": "error" } }];\n`; writeFileSync(join(dir, "w", it, "eslint.config.js"), text); } for (const [path, to] of Object.entries(more.links ?? {})) { symlinkSync(join(dir, "w", path, "..", to), join(dir, "w", path), "junction"); } }; - const given = args.map(it => it.replace("", "/w")); + const expandedArgs = args.map(it => it.replace("", "/w")); const result = await lint({ ...files, ...more.files }, [], { cwd: `w/${cwd}`, before, - args: dir => given.map(it => it.replace("", dir.replaceAll("\\", "/"))), + args: dir => expandedArgs.map(it => it.replace("", dir.replaceAll("\\", "/"))), }); const ran = existsSync(log) ? [...new Set(readFileSync(log, "utf8").split("\n").filter(Boolean))].sort() : []; return { @@ -6577,16 +6778,16 @@ describe.concurrent("a search that leaves the project of an eslint.config.js", ( exitCode: result.exitCode, }; }; - const ofMine = ["mine/nested/x.js", "mine/sub/x.js", "mine/x.js"]; + const filesInMine = ["mine/nested/x.js", "mine/sub/x.js", "mine/x.js"]; test.each([[".."], ["/**/x.js"], ["../**/x.js"], [""], [".", ".."]])( - "only what is in the working directory is entered: %s", + "only enters directories inside the working directory: %s", async (...args) => { - expect(await run("mine", args)).toMatchObject({ ran: ["mine", "mine/nested"], files: ofMine, exitCode: 1 }); + expect(await run("mine", args)).toMatchObject({ ran: ["mine", "mine/nested"], files: filesInMine, exitCode: 1 }); }, ); - test("not the directories beside it, not those above it", async () => { + test("doesn't enter the working directory's siblings or parents", async () => { expect(await run("mine", ["../*/x.js"])).toMatchObject({ ran: ["mine"], files: ["mine/x.js"], exitCode: 1 }); for (const [cwd, args] of [ ["mine", ["../.."]], @@ -6596,29 +6797,29 @@ describe.concurrent("a search that leaves the project of an eslint.config.js", ( ] as const) { const { ran, files, stderr, exitCode } = await run(cwd, [...args]); expect(stderr).toContain("are ignored."); - // ESLint runs none at all. + // ESLint doesn't run any config file here. bun lint runs the one for the working directory. expect({ ran, files, exitCode }).toEqual({ ran: [cwd.split("/")[0]], files: [], exitCode: 2 }); } }); - // "ESLint couldn't find an eslint.config.* file." + // ESLint prints "ESLint couldn't find an eslint.config.* file." test.each([ ["../none", {}, "none/x.js"], ["../none/x.js", {}, "none/x.js"], ["../none/in", {}, "none/in/x.js"], - // Whatever it is called. + // Any file, whatever its extension. ["..", { files: { "w/readme.md": "" } }, "readme.md"], ["/**/x.js", { files: { "w/x.js": "debugger;\n" } }, "x.js"], - // A link to a directory is no directory to ESLint. + // ESLint doesn't treat a link to a directory as a directory. ["..", { links: { "linked": "theirs" } }, "linked"], - ])("a file without a configuration file ends the run: %s %j", async (argument, more, file) => { + ])("a file with no config file ends the run: %s %j", async (argument, more, file) => { const { ran, files, stderr, exitCode } = await run("mine", [argument], more); expect(stderr).toContain(`Could not find config file.\n No eslint.config.* was found next to /w/${file} or`); expect(ran.filter(it => !it.startsWith("mine"))).toEqual([]); expect({ files, exitCode }).toEqual({ files: [], exitCode: 2 }); }); - test("what is named and has a configuration file of its own is linted with that", async () => { + test("a path passed as an argument is linted with its own config file if it has one", async () => { const theirs = { ran: ["mine", "theirs", "theirs/deep"], files: ["theirs/deep/x.js", "theirs/x.js"], exitCode: 1 }; expect(await run("mine", ["../theirs"])).toMatchObject(theirs); expect(await run("mine", ["/theirs"])).toMatchObject(theirs); @@ -6626,7 +6827,7 @@ describe.concurrent("a search that leaves the project of an eslint.config.js", ( expect(await run("mine", ["../theirs/deep"])).toMatchObject({ ran: ["mine", "theirs/deep"] }); }); - test("a configuration file above the working directory is for what is beside that", async () => { + test("a config file in a parent directory also applies to the working directory's siblings", async () => { const own = ["repo", "repo/packages/b/own"]; const [a, b, c] = ["a", "b", "c"].map(it => `repo/packages/${it}/x.js`); expect(await run("repo/packages/a", ["../b"])).toMatchObject({ ran: own, files: ["repo/packages/b/own/x.js", b] }); @@ -6641,10 +6842,10 @@ describe.concurrent("a search that leaves the project of an eslint.config.js", ( }); }); - test("a link in the working directory that leads out of it is not followed, and is a path like any other if it is named", async () => { + test("a search doesn't follow a symlink out of the working directory, but as an argument it's a path like any other", async () => { const links = { "mine/link": "../theirs", "mine/bare": "../none" }; for (const args of [["."], ["**/x.js"], [".."]]) { - expect(await run("mine", args, { links })).toMatchObject({ ran: ["mine", "mine/nested"], files: ofMine }); + expect(await run("mine", args, { links })).toMatchObject({ ran: ["mine", "mine/nested"], files: filesInMine }); } expect(await run("mine", ["link/x.js"], { links })).toMatchObject({ ran: ["mine", "theirs"], @@ -6654,15 +6855,15 @@ describe.concurrent("a search that leaves the project of an eslint.config.js", ( ran: ["mine", "theirs", "theirs/deep"], files: ["mine/link/deep/x.js", "mine/link/x.js"], }); - // The nearest file on the way up from the path with the link in it. + // The config lookup walks up from the path through the link, not from the link's target. expect(await run("mine", ["bare"], { links })).toMatchObject({ ran: ["mine"], files: ["mine/bare/in/x.js", "mine/bare/x.js"], }); }); - test("with --config and with --no-config-lookup no other file runs, and the base path is the working directory", async () => { - const all = { files: ofMine, exitCode: 1 }; + test("with --config or --no-config-lookup, no other config file runs and the base path is the working directory", async () => { + const all = { files: filesInMine, exitCode: 1 }; expect(await run("mine", ["-c", "eslint.config.js", ".."])).toMatchObject({ ran: ["mine"], ...all }); expect(await run("mine", ["-c", "eslint.config.js", "/**/x.js"])).toMatchObject({ ran: ["mine"], ...all }); expect(await run("mine", ["-c", "../theirs/eslint.config.js", ".."])).toMatchObject({ ran: ["theirs"], ...all }); @@ -6680,7 +6881,7 @@ describe.concurrent("a search that leaves the project of an eslint.config.js", ( } }); - test("without a configuration file in the working directory, each directory tells, as before", async () => { + test("without a config file in the working directory, each directory's own config file is used", async () => { expect(await run("none", [".."])).toMatchObject({ ran: configured.toSorted(), files: Object.keys(files) @@ -6691,33 +6892,38 @@ describe.concurrent("a search that leaves the project of an eslint.config.js", ( }); }); -// A configuration file is a program, or names programs. ESLint stops in such a working directory, so there is no tool to follow. -describe.concurrent("a pattern that leaves a working directory without a configuration file", () => { +// A config file is a program, or loads programs. ESLint exits with an error in a working directory like this, so +// there's no tool to match. +describe.concurrent("a pattern that goes outside a working directory with no config file", () => { const off = `{ rules: { "no-debugger": "off" } }`; - /** The files of a directory with a configuration of each kind. `says`: a statement that writes down that it ran. */ - const kinds: Record Record> = { - "flat-js": says => ({ "eslint.config.js": `import fs from "node:fs";\n${says}\nexport default [${off}];\n` }), - "flat-cts": says => ({ "eslint.config.cts": `const fs = require("fs");\n${says}\nmodule.exports = [${off}];\n` }), - "rc-cjs": says => ({ - ".eslintrc.cjs": `const fs = require("fs");\n${says}\nmodule.exports = { root: true, ...${off} };\n`, + /** + * Returns a directory's files, for each kind of config. `logRun` is a statement that logs that the config's code ran. + */ + const kinds: Record Record> = { + "flat-js": logRun => ({ "eslint.config.js": `import fs from "node:fs";\n${logRun}\nexport default [${off}];\n` }), + "flat-cts": logRun => ({ + "eslint.config.cts": `const fs = require("fs");\n${logRun}\nmodule.exports = [${off}];\n`, + }), + "rc-cjs": logRun => ({ + ".eslintrc.cjs": `const fs = require("fs");\n${logRun}\nmodule.exports = { root: true, ...${off} };\n`, }), - "rc-json-extends": says => ({ + "rc-json-extends": logRun => ({ ".eslintrc.json": `{ "root": true, "extends": "./program.js" }`, - "program.js": `const fs = require("fs");\n${says}\nmodule.exports = ${off};\n`, + "program.js": `const fs = require("fs");\n${logRun}\nmodule.exports = ${off};\n`, }), - "rc-yaml-plugin": says => ({ + "rc-yaml-plugin": logRun => ({ ".eslintrc.yaml": `root: true\nplugins: [local]\nrules: { no-debugger: off }\n`, "node_modules/eslint-plugin-local/package.json": `{ "name": "eslint-plugin-local", "version": "1.0.0", "main": "index.js" }`, - "node_modules/eslint-plugin-local/index.js": `const fs = require("fs");\n${says}\nmodule.exports = { rules: {} };\n`, + "node_modules/eslint-plugin-local/index.js": `const fs = require("fs");\n${logRun}\nmodule.exports = { rules: {} };\n`, }), - "package-json-extends": says => ({ + "package-json-extends": logRun => ({ "package.json": `{ "name": "a", "eslintConfig": { "root": true, "extends": "./program.js" } }`, - "program.js": `const fs = require("fs");\n${says}\nmodule.exports = ${off};\n`, + "program.js": `const fs = require("fs");\n${logRun}\nmodule.exports = ${off};\n`, }), - "ox-ts": says => ({ "oxlint.config.ts": `import fs from "node:fs";\n${says}\nexport default ${off};\n` }), - "ox-json-plugin": says => ({ + "ox-ts": logRun => ({ "oxlint.config.ts": `import fs from "node:fs";\n${logRun}\nexport default ${off};\n` }), + "ox-json-plugin": logRun => ({ ".oxlintrc.json": `{ "jsPlugins": ["./plugin.js"], "rules": { "no-debugger": "off" } }`, - "plugin.js": `import fs from "node:fs";\n${says}\nexport default { meta: { name: "local" }, rules: {} };\n`, + "plugin.js": `import fs from "node:fs";\n${logRun}\nexport default { meta: { name: "local" }, rules: {} };\n`, }), }; const all = (where: string) => @@ -6726,16 +6932,19 @@ describe.concurrent("a pattern that leaves a working directory without a configu .sort(); const scripts = (where: string) => all(where).map(it => `${it}/x.js`); - /** The programs that ran, and the files with problems: those that have the defaults, and not their own configuration. */ + /** + * Returns the programs that ran and the files with problems. A file has problems if it's linted with the defaults + * instead of its own config. + */ const run = async (args: string[], cwd = "empty") => { using logs = tempDir("bun-lint-config-files-ran", {}); const log = join(String(logs), "ran.log"); const files: Record = { "w/empty/x.js": "debugger;\n", "w/empty/plain/x.js": "debugger;\n" }; for (const where of ["beside", "empty/below"]) { - for (const [kind, of] of Object.entries(kinds)) { - const says = `fs.appendFileSync(${JSON.stringify(log)}, ${JSON.stringify(`${where}/${kind}\n`)});`; + for (const [kind, makeFiles] of Object.entries(kinds)) { + const logRun = `fs.appendFileSync(${JSON.stringify(log)}, ${JSON.stringify(`${where}/${kind}\n`)});`; files[`w/${where}/${kind}/x.js`] = "debugger;\n"; - for (const [name, text] of Object.entries(of(says))) files[`w/${where}/${kind}/${name}`] = text; + for (const [name, text] of Object.entries(makeFiles(logRun))) files[`w/${where}/${kind}/${name}`] = text; } } const result = await lint(files, [], { @@ -6749,41 +6958,47 @@ describe.concurrent("a pattern that leaves a working directory without a configu const own = ["empty/plain/x.js", "empty/x.js"]; test.each([["/**/x.js"], ["../**/x.js"]])( - "nothing runs of what %s merely leads to, which has the defaults", + "%s doesn't run config files outside the working directory, and lints the files there with the defaults", async pattern => { expect(await run([pattern])).toMatchObject({ ran: all("empty/below"), files: [...scripts("beside"), ...own] }); }, ); - test.each([["../beside/*/x.js"], ["/beside/**/x.js"], ["../*/*/x.js"]])("nor of what %s does", async pattern => { - const { ran, files } = await run([pattern]); - expect({ ran, beside: files.filter(it => it.startsWith("beside/")) }).toEqual({ - ran: [], - beside: scripts("beside"), - }); - }); + test.each([["../beside/*/x.js"], ["/beside/**/x.js"], ["../*/*/x.js"]])( + "%s doesn't run config files in a sibling directory either", + async pattern => { + const { ran, files } = await run([pattern]); + expect({ ran, beside: files.filter(it => it.startsWith("beside/")) }).toEqual({ + ran: [], + beside: scripts("beside"), + }); + }, + ); - test.each(["--flavor=oxlint", "--flavor=eslint"])("nor with %s", async flavor => { - const { ran, files } = await run([flavor, "/**/x.js"]); - expect(ran.filter(it => it.startsWith("beside/"))).toEqual([]); - expect(files.filter(it => it.startsWith("beside/"))).toEqual(scripts("beside")); - }); + test.each(["--flavor=oxlint", "--flavor=eslint"])( + "doesn't run config files outside the working directory with %s either", + async flavor => { + const { ran, files } = await run([flavor, "/**/x.js"]); + expect(ran.filter(it => it.startsWith("beside/"))).toEqual([]); + expect(files.filter(it => it.startsWith("beside/"))).toEqual(scripts("beside")); + }, + ); - test("not even beside the working directory, in the directory that it is in", async () => { + test("doesn't run config files outside a nested working directory either", async () => { expect(await run(["../**/x.js"], "empty/plain")).toMatchObject({ ran: [], files: [...scripts("empty/below"), ...own], }); }); - test("in and below the working directory each directory tells", async () => { + test("inside the working directory, each directory's own config is used", async () => { for (const args of [[], ["."], ["**/x.js"], ["./below/../**/x.js"]]) { expect(await run(args)).toMatchObject({ ran: all("empty/below"), files: own }); } }); test.each(Object.keys(kinds))( - "a directory that is named tells, and so does that of a file that is: %s", + "a directory or file passed as an argument is linted with its own config: %s", async kind => { const ran = [`beside/${kind}`]; expect(await run([`../beside/${kind}`])).toEqual({ ran, files: [] }); @@ -6791,10 +7006,10 @@ describe.concurrent("a pattern that leaves a working directory without a configu }, ); - test("what is named is all that is in it", async () => { + test("passing a directory as an argument runs every config inside it", async () => { expect(await run(["../beside"])).toEqual({ ran: all("beside"), files: [] }); expect(await run([".."])).toMatchObject({ ran: [...all("beside"), ...all("empty/below")], files: own }); - // Also for a pattern that leads there too. + // The argument's config is also used for a file in it that a pattern matches. expect(await run(["../beside/flat-js", "../beside/*/x.js"])).toMatchObject({ ran: ["beside/flat-js"], files: scripts("beside").filter(it => it !== "beside/flat-js/x.js"), @@ -6802,21 +7017,21 @@ describe.concurrent("a pattern that leaves a working directory without a configu }); }); -// What is left out is what `git check-ignore` has. oxlint 1.87.0 does not find the file of a submodule, and looks for a `gitdir` -// that is not absolute from where it runs. -describe.concurrent("info/exclude of a repository, where the configuration is not of oxlint", () => { +// The skipped files are the ones that `git check-ignore` lists. oxlint 1.87.0 doesn't find a submodule's info/exclude, +// and resolves a relative `gitdir` against its working directory. +describe.concurrent("a repository's info/exclude, without an oxlint config", () => { const names = ["a.js", "gen/b.js", "kept.js", "sub/a.js", "sub/anchored.js", "sub/named.js"]; const excludes = "/a.js\nnamed.js\ngen/\n/sub/anchored.js\n"; - const left = ["kept.js", "sub/a.js"]; - /** `names`, each after `prefix`. */ + const notExcluded = ["kept.js", "sub/a.js"]; + /** Returns a file for each of `names`, with `prefix` before its path. */ const tree = (prefix: string) => Object.fromEntries(names.map(name => [prefix + name, code])); - /** The files that are linted. */ + /** Returns the files that were linted. */ async function linted(files: Record, args: string[], cwd: string) { const { problems } = await lint(files, args, { cwd }); return [...new Set(problems.map(it => it.split(":")[0]))]; } - test("a working tree of `git worktree add --relative-paths`", async () => { + test("applies in a worktree created with `git worktree add --relative-paths`", async () => { const files = { ...tree("wt/"), "wt/.git": "gitdir: ../main/.git/worktrees/wt\n", @@ -6825,10 +7040,10 @@ describe.concurrent("info/exclude of a repository, where the configuration is no }; expect( await Promise.all([linted(files, ["."], "wt"), linted(files, ["."], "wt/sub"), linted(files, ["wt"], ".")]), - ).toEqual([left.map(it => `wt/${it}`), ["wt/sub/a.js"], left.map(it => `wt/${it}`)]); + ).toEqual([notExcluded.map(it => `wt/${it}`), ["wt/sub/a.js"], notExcluded.map(it => `wt/${it}`)]); }); - test("a submodule", async () => { + test("applies in a submodule", async () => { const files = { ...tree("vendor/lib/"), "top.js": code, @@ -6836,7 +7051,7 @@ describe.concurrent("info/exclude of a repository, where the configuration is no ".git/modules/vendor/lib/info/exclude": excludes, "vendor/lib/.git": "gitdir: ../../.git/modules/vendor/lib\n", }; - const inLib = left.map(it => `vendor/lib/${it}`); + const inLib = notExcluded.map(it => `vendor/lib/${it}`); expect( await Promise.all([ linted(files, ["."], "."), @@ -6847,20 +7062,21 @@ describe.concurrent("info/exclude of a repository, where the configuration is no }); test.each([ - ["no configuration", {}], - ["a configuration of ESLint 8", { ".eslintrc.json": rc(eqeqeq) }], - ])("--ignore-path names it, with %s", async (_, configuration) => { + ["no config", {}], + ["an ESLint 8 config", { ".eslintrc.json": rc(eqeqeq) }], + ])("can be passed to --ignore-path, with %s", async (_, configuration) => { const files = { ...tree(""), ...configuration, ".git/info/exclude": excludes }; expect( await Promise.all([ linted(files, ["--ignore-path", ".git/info/exclude", "."], "."), linted(files, ["--ignore-path", "../.git/info/exclude", "."], "sub"), ]), - ).toEqual([left, ["sub/a.js"]]); + ).toEqual([notExcluded, ["sub/a.js"]]); }); - // oxlint compares a file that is named with the patterns as it is spelled. These patterns start where Git has them start. - test("--ignore-path names it, with a configuration of oxlint: its patterns start at the root for files that are named too", async () => { + // oxlint matches a file passed as an argument against the patterns the way it's spelled on the command line. Here the + // patterns are relative to the repository root, as in Git. + test("can be passed to --ignore-path with an oxlint config, and its patterns stay relative to the repository root for files passed as arguments", async () => { const files = { ...tree(""), ".oxlintrc.json": JSON.stringify(noVar), ".git/info/exclude": excludes }; const fromSub = names.map(name => (name.startsWith("sub/") ? name.slice(4) : `../${name}`)); expect( @@ -6870,29 +7086,29 @@ describe.concurrent("info/exclude of a repository, where the configuration is no linted(files, ["--ignore-path", "../.git/info/exclude", ".."], "sub"), linted(files, ["--ignore-path", "../.git/info/exclude", ...fromSub], "sub"), ]), - // About a file that is named, oxlint does not ask the patterns for the directories that it is in. - ).toEqual([left, ["gen/b.js", ...left], left, ["gen/b.js", ...left]]); + // For a file passed as an argument, oxlint doesn't match the patterns against its parent directories. + ).toEqual([notExcluded, ["gen/b.js", ...notExcluded], notExcluded, ["gen/b.js", ...notExcluded]]); }); }); -// With a file of mode 000, as somebody who is not root. -describe.skipIf(isWindows || process.getuid?.() === 0).concurrent("a file that cannot be opened", () => { +// Uses a file with mode 000, which root could still open. +describe.skipIf(isWindows || process.getuid?.() === 0).concurrent("a file that can't be opened", () => { const files = { "a.js": code, "locked.js": code, "sub/b.js": code }; const before = (dir: string) => chmodSync(join(dir, "locked.js"), 0); // oxlint 1.87.0: `x Failed to open file /locked.js with error "Permission denied (os error 13)"`, and - // "Found 0 warnings and 3 errors.". Without a configuration file as oxlint. + // "Found 0 warnings and 3 errors.". Without a config file, bun lint behaves like oxlint. test.each([ [".oxlintrc.json", JSON.stringify({ ...noVar, categories: { correctness: "off" } })], ["bunfig.toml", `[lint.rules]\n"no-var" = "error"\n`], [".keep", ""], - ])("is an error, and the others are linted: %s", async (name, text) => { + ])("is reported as an error, and the other files are linted: %s", async (name, text) => { for (const args of [["."], ["locked.js", "a.js", "sub"]]) { const { problems, stdout, exitCode } = await lint({ ...files, [name]: text }, args, { before }); expect(stdout).toContain("Failed to open file /locked.js with error "); expect(stdout).toContain("Permission denied (os error 13)"); expect(problems).toContain(`${name === ".oxlintrc.json" ? "" : "locked.js"}:0:0 -`); - // For oxlint it is a problem of no file. + // With an oxlint config, the problem doesn't belong to any file. expect([...new Set(problems.map(it => it.split(":")[0]))]).toEqual( [name === ".oxlintrc.json" ? "" : "locked.js", "a.js", "sub/b.js"].sort(), ); @@ -6900,15 +7116,15 @@ describe.skipIf(isWindows || process.getuid?.() === 0).concurrent("a file that c } }); - // oxlint 1.87.0 has two kinds of problems without a place: one is in no file, the other in a file without a name. - test("in oxlint's JSON it has no filename, unlike what is said about the suppressions", async () => { + // oxlint 1.87.0 has two kinds of problems without a location: one has no filename, the other has an empty filename. + test("has no filename in oxlint's JSON, unlike the problems about suppressions, which have an empty one", async () => { const config = JSON.stringify({ ...noVar, categories: { correctness: "off" } }); const stale = JSON.stringify({ "sub/b.js": { "no-debugger": { count: 1 } } }); const all = { ...files, ".oxlintrc.json": config, "oxlint-suppressions.json": stale }; const { raw } = await lint(all, ["-f", "json", "."], { before }); type Diagnostic = { message: string; filename?: string; labels: unknown[] }; - const placeless = (JSON.parse(raw).diagnostics as Diagnostic[]).filter(it => it.labels.length === 0); - expect(placeless.map(it => [it.message.split(" ").slice(0, 4).join(" "), it.filename])).toEqual([ + const withoutLabels = (JSON.parse(raw).diagnostics as Diagnostic[]).filter(it => it.labels.length === 0); + expect(withoutLabels.map(it => [it.message.split(" ").slice(0, 4).join(" "), it.filename])).toEqual([ ["Failed to open file", undefined], ["There are suppressions that", ""], ["There are new violations", ""], @@ -6919,7 +7135,7 @@ describe.skipIf(isWindows || process.getuid?.() === 0).concurrent("a file that c test.each([ ["eslint.config.js", `export default [${JSON.stringify(noVar)}];`], [".eslintrc.json", rc(noVar)], - ])("is the end of the run: %s", async (name, text) => { + ])("ends the run: %s", async (name, text) => { const { problems, stderr, exitCode } = await lint({ ...files, [name]: text }, ["."], { before }); expect(stderr).toContain("Cannot read /locked.js: EACCES: "); expect({ problems, exitCode }).toEqual({ problems: [], exitCode: 2 }); @@ -6927,7 +7143,7 @@ describe.skipIf(isWindows || process.getuid?.() === 0).concurrent("a file that c }); describe.concurrent("paths", () => { - test("`ignorePatterns` of a file that --config names say nothing about what is beside its directory", async () => { + test("`ignorePatterns` in a --config file don't apply to files outside that file's directory", async () => { const { problems, exitCode } = await lint( { "config/.oxlintrc.json": JSON.stringify({ ...quiet, ...noVar, ignorePatterns: ["*.js"] }), @@ -6941,8 +7157,8 @@ describe.concurrent("paths", () => { }); }); -// As ESLint 10.12.0 and 9.39.5. `{ max: Infinity }` is how one limit is switched off. ajv takes it for an integer, and prints a -// value as `JSON.stringify` does. +// Same as ESLint 10.12.0 and 9.39.5. `{ max: Infinity }` is how people switch off a limit. ajv accepts it as an +// integer, and prints values the way `JSON.stringify` does. describe("an infinite number in an eslint.config.mjs", () => { const code = "function f(a) {\n if (a) {\n if (a) {\n if (a) {\n return 123;\n }\n }\n }\n}\nf();\n"; @@ -6970,7 +7186,7 @@ describe("an infinite number in an eslint.config.mjs", () => { 'Key "rules": Key "max-depth":\n\tValue {"max":null} should be integer.\n\tValue null should be >= 0.\n\tValue {"max":null} should match exactly one schema in oneOf.', ], [`"p/limited": ["error", Infinity]`, 'Key "rules": Key "p/limited":\n\tValue null should be <= 10.'], - ] as [string, string[] | string][])("an option of a rule: %s", async (rule, expected) => { + ] as [string, string[] | string][])("as a rule option: %s", async (rule, expected) => { const limited = `{ meta: { schema: [{ type: "integer", maximum: 10 }] }, create: () => ({}) }`; const files = { "eslint.config.mjs": `export default [{ plugins: { p: { rules: { limited: ${limited} } } }, rules: { ${rule} } }];\n`, @@ -6988,7 +7204,7 @@ describe("an infinite number in an eslint.config.mjs", () => { expect(exitCode).toBe(expected.length === 0 ? 0 : 1); }); - // ESLint hands options on as `structuredClone` makes them, and ajv sees an object without properties in a `Map`. + // ESLint passes options through `structuredClone`, and ajv sees a `Map` as an object without properties. test.concurrent.each([ [ `"max-depth": ["error", NaN]`, @@ -7033,7 +7249,7 @@ describe("an infinite number in an eslint.config.mjs", () => { [`"max-depth": ["error", undefined]`, []], [`"max-depth": ["error", { max: undefined }]`, []], [`"eqeqeq": ["error", undefined]`, []], - ] as [string, string[] | string][])("what else JSON has no word for: %s", async (rule, expected) => { + ] as [string, string[] | string][])("other values that JSON can't represent: %s", async (rule, expected) => { const files = { "eslint.config.mjs": `export default [{ name: "mine", rules: { ${rule} } }];\n`, "a.js": "if (a) {\n if (b) {\n if (c) {\n d(123);\n }\n }\n}\n", @@ -7049,7 +7265,7 @@ describe("an infinite number in an eslint.config.mjs", () => { expect(messages.map(it => `${it.line}:${it.column} ${it.message}`)).toEqual(expected); }); - test("what a rule in JavaScript sees", async () => { + test("a JavaScript rule gets the original values in its options and settings", async () => { const files = { "eslint.config.mjs": ` const isPlain = it => Object.getPrototypeOf(it) === Object.prototype; diff --git a/test/cli/lint/conformance.test.ts b/test/cli/lint/conformance.test.ts index 966c80ab360b..a4d6969e4971 100644 --- a/test/cli/lint/conformance.test.ts +++ b/test/cli/lint/conformance.test.ts @@ -7,21 +7,21 @@ import { endChildren, spawn } from "../children"; afterAll(endChildren); -// The tests of ESLint, of typescript-eslint and of the plugins, more cases that the real ESLint has judged, and the tests of -// oxlint's own plugins, which oxlint has judged, run on `bun lint`. See conformance/README.md. `src/lint/conformance` runs -// them: it says what is compared. +// Runs `bun lint` on the test suites of ESLint, typescript-eslint and the plugins, on extra cases recorded with real +// ESLint, and on the tests of oxlint's own plugins, recorded with oxlint. See conformance/README.md. The runner is +// `src/lint/conformance`, which documents what's compared. // -// `conformance/expected*.txt` is what the runner prints: the cases that fail, one per line, and the totals. +// `conformance/expected*.txt` is the runner's output: one line per failing case, then the totals. // The runner is compiled into debug and canary builds only. const hasRunner = isDebug || Bun.spawnSync({ cmd: [bunExe(), "--revision"], env: bunEnv }).stdout.includes("canary"); -// A debug build is 10 to 100 times slower, so it runs a sample. It is always the same sample. +// A debug build is 10 to 100 times slower, so it runs a sample, always the same one. const isSample = isDebug || isASAN; -// Every n-th case that needs no types, and every n-th that does. One that does takes a thousand times as long, since a -// program is loaded for it: all 144,000 without types take 8 seconds of CPU time, the 8,200 of "upstream" with types 600. -// `expected*.txt` are written with [1, 1] and [1, 10]. +// `every` is [n, m]: run every n-th untyped case and every m-th typed case. A typed case loads a program, so it takes a +// thousand times as long: all 144,000 untyped cases take 8 seconds of CPU time, and the 8,200 typed cases in "upstream" +// take 600. `expected*.txt` are written with [1, 1] and [1, 10]. const suites = [ { suite: "upstream", expected: "expected.txt", every: isSample ? [50, 2000] : [1, 20] }, { suite: "more", expected: "expected-more.txt", every: isSample ? [100, 5000] : [1, 200] }, @@ -42,9 +42,9 @@ beforeAll(async () => { afterAll(() => dir?.[Symbol.dispose]()); test.skipIf(!hasRunner).each(suites)( - "$suite", + "the $suite suite has no new failures", async ({ suite, expected: file, every }) => { - // Some cases are files of a project, which the runner writes there. The paths in them are those of POSIX. + // Some cases are files in a project, which the runner extracts to this directory. Their paths are POSIX paths. const projects = isWindows ? [] : [`--projects=${join(root, "projects")}`, "--extract", "--types"]; await using proc = spawn({ timeout: 9 * 60_000, @@ -60,7 +60,7 @@ test.skipIf(!hasRunner).each(suites)( `--threads=${Math.min(availableParallelism(), 8)}`, ], env: bunEnv, - // Not where a `package.json` has a script `lint`. + // A directory whose `package.json` has a `lint` script would run that script instead. cwd: root, stdout: "pipe", stderr: "inherit", @@ -68,20 +68,25 @@ test.skipIf(!hasRunner).each(suites)( const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); const expected = await Bun.file(join(import.meta.dir, "conformance", file)).text(); - // Nothing fails that is not known to. + // Every failure is a known one. const known = new Set(expected.split("\n")); expect(stdout.split("\n").filter(line => line.startsWith("FAIL ") && !known.has(line))).toEqual([]); expect(stdout).toMatch(/\n[1-9]\d* cases passed, /); - // No more is skipped than is known to be. A case that needs a rule of upstream's test file is only counted when it is run. + // No more cases are skipped than expected. A case that needs a rule defined in upstream's test file only counts as + // skipped if the sample includes it. const skipped = (text: string) => Number(/, (\d+) skipped\n/.exec(text)?.[1]); if (!isWindows) expect(skipped(stdout)).toBeLessThanOrEqual(skipped(expected)); - // Nor do more messages lack the help that oxlint has. - const lacking = (text: string) => Number(/\n(\d+) messages lack the help/.exec(text)?.[1] ?? 0); - expect(lacking(stdout)).toBeLessThanOrEqual(lacking(expected)); - // Nor do more cases have their messages in another order than the original has them. - const inAnotherOrder = (text: string) => - Number(/\n(\d+) cases have their messages in another order/.exec(text)?.[1]); - expect(inAnotherOrder(stdout)).toBeLessThanOrEqual(inAnotherOrder(expected)); + // No more messages are missing oxlint's help text than expected. + const missingHelp = (text: string) => Number(/\n(\d+) messages lack the help/.exec(text)?.[1] ?? 0); + expect(missingHelp(stdout)).toBeLessThanOrEqual(missingHelp(expected)); + // No more cases report their messages in a different order from the original than expected. + const reordered = (text: string) => Number(/\n(\d+) cases have their messages in another order/.exec(text)?.[1]); + expect(reordered(stdout)).toBeLessThanOrEqual(reordered(expected)); + // --fix doesn't hold back an upstream fix in more cases than expected. Each one is held back because it changes the + // program's behavior. + const heldBackFixes = (text: string) => + Number(/\n(\d+) cases have a fix that --fix holds back/.exec(text)?.[1] ?? 0); + expect(heldBackFixes(stdout)).toBeLessThanOrEqual(heldBackFixes(expected)); expect(exitCode).toBe(0); }, 10 * 60_000, diff --git a/test/cli/lint/conformance/README.md b/test/cli/lint/conformance/README.md index 7cd6af1ae257..b4d5b59c31ff 100644 --- a/test/cli/lint/conformance/README.md +++ b/test/cli/lint/conformance/README.md @@ -91,6 +91,12 @@ nodes, and the recordings have that order: a case whose messages are the recorde line of each of the three files (there with all cases run, also all with types), and they may not become more. `--in-order` makes such a case fail, as `the order differs`. +`bun lint --fix` applies no fix that can change what a program does, even where the original's `--fix` does. Such a fix takes +`--fix-dangerously` here. The runner compares it as the fix that it is for the original, so its text is still checked. For oxlint, +whose fixes are only seen in the code they leave, what oxlint writes with some flags may take more flags here, never fewer. A case +that passes that way is counted, in a line of each of the three files, and they may not become more: each is a decision. A fix that +isn't offered at all, because it would lose a comment, fails its case, which is then listed. + The options of a case go through the schema of the rule, as those of a configuration do: a case fails, as `the options are refused`, if a configuration with them would end the run. Not where the recorded options have a `null`, which is what JSON makes of `Infinity`. diff --git a/test/cli/lint/conformance/expected-more.txt b/test/cli/lint/conformance/expected-more.txt index d8be6ca32150..604efc1e6cdf 100644 --- a/test/cli/lint/conformance/expected-more.txt +++ b/test/cli/lint/conformance/expected-more.txt @@ -1,9 +1,14 @@ FAIL more/reviews/eslint/no-func-assign#146 messages differ FAIL more/reviews/eslint/no-param-reassign#335 messages differ FAIL more/reviews/eslint/no-param-reassign#336 messages differ +FAIL more/reviews/typescript-eslint/consistent-indexed-object-style#81 messages differ +FAIL more/reviews/typescript-eslint/consistent-indexed-object-style#92 messages differ +FAIL more/reviews/typescript-eslint/consistent-type-definitions#53 messages differ FAIL more/reviews/typescript-eslint/no-unused-vars#2174 messages differ 0 cases have their messages in another order -632 rules, 629 without failures, 0 not implemented -76552 cases passed, 4 failed, 258 skipped +19 cases have a fix that --fix holds back + +632 rules, 627 without failures, 0 not implemented +76549 cases passed, 7 failed, 258 skipped diff --git a/test/cli/lint/conformance/expected-oxlint.txt b/test/cli/lint/conformance/expected-oxlint.txt index 0486a19ed96a..f18e2b75392b 100644 --- a/test/cli/lint/conformance/expected-oxlint.txt +++ b/test/cli/lint/conformance/expected-oxlint.txt @@ -1,7 +1,17 @@ +FAIL oxlint/unicorn/no-useless-undefined#80 output differs +FAIL oxlint/unicorn/no-useless-undefined#81 output differs +FAIL oxlint/unicorn/prefer-string-raw#47 output differs +FAIL oxlint/unicorn/prefer-string-raw#65 output differs +FAIL oxlint/unicorn/require-module-specifiers#25 output differs +FAIL oxlint/unicorn/require-module-specifiers#26 output differs +FAIL oxlint/unicorn/require-module-specifiers#37 output differs +FAIL oxlint/vitest/prefer-importing-vitest-globals#15 messages differ -1 messages lack the help that oxlint has +3 messages lack the help that oxlint has -2 cases have their messages in another order +0 cases have their messages in another order -504 rules, 504 without failures, 0 not implemented -27702 cases passed, 0 failed, 63 skipped +432 cases have a fix that --fix holds back + +504 rules, 500 without failures, 0 not implemented +27694 cases passed, 8 failed, 63 skipped diff --git a/test/cli/lint/conformance/expected.txt b/test/cli/lint/conformance/expected.txt index b6adebc68d1e..ce99240988c4 100644 --- a/test/cli/lint/conformance/expected.txt +++ b/test/cli/lint/conformance/expected.txt @@ -1,5 +1,37 @@ +FAIL typescript-eslint/prefer-readonly#87 messages differ +FAIL react/jsx-newline#60 messages differ +FAIL markdown/no-space-in-emphasis#145 messages differ +FAIL markdown/no-space-in-emphasis#151 messages differ +FAIL markdown/no-space-in-emphasis#157 messages differ +FAIL markdown/no-space-in-emphasis#158 messages differ +FAIL markdown/no-space-in-emphasis#160 messages differ +FAIL markdown/no-space-in-emphasis#161 messages differ +FAIL markdown/no-space-in-emphasis#162 messages differ +FAIL markdown/no-space-in-emphasis#168 messages differ +FAIL markdown/no-space-in-emphasis#175 messages differ +FAIL markdown/no-space-in-emphasis#176 messages differ +FAIL markdown/no-space-in-emphasis#178 messages differ +FAIL markdown/no-space-in-emphasis#181 messages differ +FAIL markdown/no-space-in-emphasis#185 messages differ +FAIL markdown/no-space-in-emphasis#186 messages differ +FAIL markdown/no-space-in-emphasis#187 messages differ +FAIL markdown/no-space-in-emphasis#188 messages differ +FAIL markdown/no-space-in-emphasis#189 messages differ +FAIL markdown/no-space-in-emphasis#190 messages differ +FAIL markdown/no-space-in-emphasis#191 messages differ +FAIL markdown/no-space-in-emphasis#194 messages differ +FAIL markdown/no-space-in-emphasis#196 messages differ +FAIL markdown/no-space-in-emphasis#197 messages differ +FAIL markdown/no-space-in-emphasis#198 messages differ +FAIL markdown/no-space-in-emphasis#199 messages differ +FAIL markdown/no-space-in-emphasis#202 messages differ +FAIL markdown/no-space-in-emphasis#203 messages differ +FAIL markdown/no-space-in-emphasis#204 messages differ +FAIL markdown/no-space-in-emphasis#205 messages differ 0 cases have their messages in another order -532 rules, 532 without failures, 0 not implemented -71379 cases passed, 0 failed, 306 skipped +4 cases have a fix that --fix holds back + +532 rules, 529 without failures, 0 not implemented +71349 cases passed, 30 failed, 306 skipped diff --git a/test/cli/lint/conformance/extra-cases.ts b/test/cli/lint/conformance/extra-cases.ts index 7508aa20a198..d394e0946e87 100644 --- a/test/cli/lint/conformance/extra-cases.ts +++ b/test/cli/lint/conformance/extra-cases.ts @@ -1,4 +1,4 @@ -// Records what real ESLint reports for test cases that are not upstream's, in the format of `fixtures/`. +// Records what real ESLint reports for test cases that aren't upstream's, in the `fixtures/` format. // // ESLINT_DIR=.. TYPESCRIPT_ESLINT_DIR=.. node extra-cases.ts --out / [/ ...] // @@ -7,26 +7,27 @@ // { "code": "..", "options"?: [..], "filename"?: "..", "languageOptions"?: {..}, "settings"?: {..}, "name"?: "..", // "typeAware"?: false } // -// (a plain string is `{ code }`), `languageOptions` as in the fixtures: `parser` is `"espree"` or `"typescript"`, and in -// `parserOptions`, `project` and `tsconfigRootDir` are relative to `fixtures/typescript-eslint-project`. A case of a -// fixture is a valid input. +// (a plain string means `{ code }`). `languageOptions` is the same as in the fixtures: `parser` is `"espree"` or +// `"typescript"`, and `project` and `tsconfigRootDir` in `parserOptions` are relative to +// `fixtures/typescript-eslint-project`. A case copied from a fixture is valid input. // -// The configuration is layered as the RuleTester of the plugin does it (see `extract-*.ts`), with these defaults: +// The config is layered the way the plugin's RuleTester does it (see `extract-*.ts`), with these defaults: // // - eslint: espree, `ecmaVersion: "latest"`, `sourceType: "module"`; the TypeScript parser when `filename` ends in // `.ts`, `.tsx`, `.mts` or `.cts`; JSX when it ends in `.jsx`. -// - typescript-eslint: its parser. A rule that requires types gets the `parserOptions` that most of its upstream cases -// have, and the code is `file.ts` (`react.tsx` with `ecmaFeatures.jsx`) of the fixture project. `typeAware: false` -// turns that off. Unlike in the RuleTester, all the rules of the plugin are defined, and only the one is enabled. -// - A case that names neither a file nor a parser and that does not parse is tried again with JSX, then as `file.ts`, -// then as `file.tsx`. What is recorded says which it was. +// - typescript-eslint: its parser. A rule that requires types gets the `parserOptions` most of its upstream cases use, +// and the code is linted as the fixture project's `file.ts` (`react.tsx` with `ecmaFeatures.jsx`). `typeAware: false` +// turns that off. Unlike in the RuleTester, all of the plugin's rules are defined, but only the one under test is +// enabled. +// - A case with no filename and no parser that fails to parse is retried with JSX, then as `file.ts`, then as +// `file.tsx`. The recorded case has the one that worked. // -// `skip` is set on what cannot be compared: a fatal parse error, options that ESLint rejects, a rule that throws or that -// does not finish in `--timeout` seconds (20). +// `skip` is set on a case that can't be compared: a fatal parse error, options that ESLint rejects, or a rule that +// throws or doesn't finish in `--timeout` seconds (20). // -// `--out ` gets `//.json` and a link to the fixture project. +// Writes `//.json` and a link to the fixture project into `--out `. // -// Needs Node.js >= 23.6, as the extractors do. +// Needs Node.js >= 23.6, like the extractors. import { existsSync, mkdirSync, readFileSync, realpathSync, symlinkSync } from "node:fs"; import { createRequire } from "node:module"; @@ -58,7 +59,7 @@ export interface ExtraCase { filename?: string | null; languageOptions?: Config | null; settings?: Config | null; - /** `false`: without types, also for a rule that requires them. */ + /** `false` lints without types, even for a rule that requires them. */ typeAware?: boolean; } @@ -68,9 +69,9 @@ const scriptDir = dirname(fileURLToPath(import.meta.url)); // Command line // --------------------------------------------------------------------------- -const jobsOfRule: { plugin: Plugin; rule: string; file: string }[] = []; +const ruleJobs: { plugin: Plugin; rule: string; file: string }[] = []; let out = ""; -/** Seconds that ESLint has for one case. */ +/** Time limit for ESLint on one case, in seconds. */ let timeout = 20; let upstream = join(scriptDir, "fixtures"); { @@ -92,12 +93,12 @@ let upstream = join(scriptDir, "fixtures"); const id = plain[i].replace(/^@typescript-eslint\//, "typescript-eslint/"); const [plugin, rule] = id.includes("/") ? id.split("/") : ["eslint", id]; if (plugin !== "eslint" && plugin !== "typescript-eslint") throw new Error(`unknown plugin ${plugin}`); - jobsOfRule.push({ plugin, rule, file: resolve(plain[i + 1]) }); + ruleJobs.push({ plugin, rule, file: resolve(plain[i + 1]) }); } } // --------------------------------------------------------------------------- -// What both plugins share +// Shared by both plugins // --------------------------------------------------------------------------- const withoutNulls = (object: Config | null | undefined): Config => @@ -107,11 +108,11 @@ let pending: () => LintMessage[]; Object.assign(globalThis, { __extraCasesLint: () => pending() }); const watched = new Script("__extraCasesLint()"); -/** Lints, and says why the result cannot be compared if it cannot. */ +/** Lints. `skip` is the reason the result can't be compared, if any. */ function verify(lint: () => LintMessage[]): { messages: LintMessage[]; skip: string | null; fatal: boolean } { let messages: LintMessage[]; try { - // Some rules take exponential time on some types. The watchdog of `vm` also stops code that the script calls. + // Some rules take exponential time on some types. The `vm` timeout also stops code that the script calls. pending = lint; messages = watched.runInThisContext({ timeout: timeout * 1000 }); } catch (error) { @@ -136,7 +137,7 @@ interface Recorder { } // --------------------------------------------------------------------------- -// eslint: `runCase()` of extract-eslint.ts +// eslint: mirrors `runCase()` in extract-eslint.ts // --------------------------------------------------------------------------- function eslintRecorder(): Recorder { @@ -210,10 +211,11 @@ function eslintRecorder(): Recorder { meta: rule => builtinRules.get(rule), record(ruleName, item) { const given = item.languageOptions?.parser; - const named: "espree" | "typescript" | undefined = given === "espree" || given === "typescript" ? given : undefined; + const explicitParser: "espree" | "typescript" | undefined = + given === "espree" || given === "typescript" ? given : undefined; const wantsJsx = Boolean(item.languageOptions?.parserOptions?.ecmaFeatures?.jsx); - if (item.filename || named) { - const parser = named ?? (/\.[cm]?tsx?$/.test(item.filename!) ? "typescript" : "espree"); + if (item.filename || explicitParser) { + const parser = explicitParser ?? (/\.[cm]?tsx?$/.test(item.filename!) ? "typescript" : "espree"); const filename = item.filename ?? `file.${parser === "typescript" ? "ts" : "js"}${wantsJsx ? "x" : ""}`; const only = attempt(ruleName, item, parser, filename, parser === "espree" && filename.endsWith(".jsx")); if (!only.fatal || item.filename || parser === "espree" || wantsJsx) return only.recorded; @@ -236,7 +238,7 @@ function eslintRecorder(): Recorder { } // --------------------------------------------------------------------------- -// typescript-eslint: `runCase()` of extract-typescript-eslint.ts +// typescript-eslint: mirrors `runCase()` in extract-typescript-eslint.ts // --------------------------------------------------------------------------- function typescriptRecorder(): Recorder { @@ -283,7 +285,7 @@ function typescriptRecorder(): Recorder { return linter; } - /** Gives the file of the last type-aware case the text that it has on disk. */ + /** Lints the last type-aware case's file again with its text on disk. */ let restore: { path: string; run: () => void } | null = null; function attempt(ruleName: string, item: ExtraCase, defaults: Config | null, jsx: boolean) { @@ -294,7 +296,7 @@ function typescriptRecorder(): Recorder { delete languageOptions.parser; const given: Config = { ...languageOptions.parserOptions }; - // A case that chooses a project does not also want the project service of the defaults, and the other way around. + // A case that sets `project` doesn't inherit `projectService` from the defaults, and vice versa. const inherited: Config = { ...defaults }; if (given.project !== undefined && given.projectService === undefined) delete inherited.projectService; if (given.projectService && given.project === undefined) delete inherited.project; @@ -305,13 +307,14 @@ function typescriptRecorder(): Recorder { } let filename: string = item.filename ?? (parserOptions.ecmaFeatures?.jsx ? "react.tsx" : "file.ts"); - // As in the fixtures, the name of a type-aware case is relative to the project. + // As in the fixtures, a type-aware case's filename is relative to the project. if (typeAware && item.filename) filename = resolve(projectDir, filename); else if (parserOptions.project) filename = join(parserOptions.tsconfigRootDir ?? process.cwd(), filename); const config: Config = { files: ["**"], - // All the rules, as in a project: a comment that disables another rule of the plugin is about a rule that is defined. + // Define all the rules, as a real project does, so a comment that disables another of the plugin's rules is + // valid. plugins: { "@typescript-eslint": { rules } }, languageOptions: { ...languageOptions, @@ -328,8 +331,8 @@ function typescriptRecorder(): Recorder { }; if (item.settings) config.settings = item.settings; - // The programs of typescript-estree remember the text that a file was linted with. The declarations of a case that was - // `react.tsx` would be visible to the next one that is `file.ts`: both are scripts of one program. + // typescript-estree's programs remember the text a file was last linted with. Without the restore, a `file.ts` case + // would see the declarations of the previous `react.tsx` case, because both are scripts in one program. const path = resolve(parserOptions.tsconfigRootDir ?? ".", filename); if (restore && restore.path !== path) { restore.run(); @@ -338,7 +341,10 @@ function typescriptRecorder(): Recorder { const linter = linterFor(parserOptions.tsconfigRootDir, filename); const result = verify(() => linter.verify(code, config, filename)); if (typeAware && existsSync(path)) { - restore = { path, run: () => verify(() => linter.verify(readFileSync(path, "utf8"), { ...config, rules: {} }, filename)) }; + restore = { + path, + run: () => verify(() => linter.verify(readFileSync(path, "utf8"), { ...config, rules: {} }, filename)), + }; } if (result.skip) result.skip = result.skip.replaceAll(projectDir, "."); @@ -391,8 +397,8 @@ function typescriptRecorder(): Recorder { // --------------------------------------------------------------------------- /** - * The `parserOptions` that most of the type-aware upstream cases of a rule that requires types have. `null` for a rule - * that is mostly tested without types (`naming-convention`). + * Returns the most common `parserOptions` among the rule's type-aware upstream cases, or `null` if the rule doesn't + * require types or is mostly tested without them (`naming-convention`). */ function typeAwareDefaults(fixture: Fixture | null): Config | null { if (!fixture?.meta.requiresTypeChecking) return null; @@ -410,7 +416,7 @@ function typeAwareDefaults(fixture: Fixture | null): Config | null { const recorders: Partial> = {}; -for (const { plugin, rule, file } of jobsOfRule) { +for (const { plugin, rule, file } of ruleJobs) { const recorder = (recorders[plugin] ??= plugin === "eslint" ? eslintRecorder() : typescriptRecorder()); const module = recorder.meta(rule); if (!module) { @@ -437,7 +443,7 @@ if (!existsSync(join(out, "typescript-eslint-project"))) { try { symlinkSync(join(upstream, "typescript-eslint-project"), join(out, "typescript-eslint-project")); } catch { - // Someone else was faster. + // Another process created it first. } } diff --git a/test/cli/lint/conformance/extract-eslint.ts b/test/cli/lint/conformance/extract-eslint.ts index 52e503a9f645..9ce26196d026 100644 --- a/test/cli/lint/conformance/extract-eslint.ts +++ b/test/cli/lint/conformance/extract-eslint.ts @@ -4,10 +4,10 @@ // ESLINT_DIR= bun extract-eslint.ts [--jobs N] [rule...] // // Each test file is loaded with `lib/rule-tester/rule-tester.js` replaced by a -// stub that only records what it is given. Every recorded case is then linted -// by the checkout's real `Linter`, configured the way the real RuleTester -// configures it, and what the Linter reports is the ground truth that is -// written out. What the upstream test asserts is only used as a cross-check. +// stub that only records its arguments. Every recorded case is then linted by +// the checkout's real `Linter`, configured the way the real RuleTester +// configures it. The fixture records what the Linter reports. The upstream +// test's assertions are only used as a cross-check. import { readdirSync, realpathSync } from "node:fs"; import { createRequire } from "node:module"; @@ -39,8 +39,8 @@ const eslintDir = realpathSync(requiredEnv("ESLINT_DIR")); const require = createRequire(join(eslintDir, "package.json")); const builtinRules: Map = require("./lib/rules"); -/** The deprecated rules about layout, which @stylistic/eslint-plugin has taken over. `bun lint` does not have them. */ -function isAboutLayout(rule: string) { +/** True for the deprecated layout rules that moved to @stylistic/eslint-plugin. `bun lint` doesn't implement them. */ +function isLayoutRule(rule: string) { const replacedBy: { plugin?: { name?: string } }[] = builtinRules.get(rule)?.meta?.deprecated?.replacedBy ?? []; return replacedBy.length > 0 && replacedBy.every(it => it.plugin?.name === "@stylistic/eslint-plugin"); } @@ -48,7 +48,7 @@ function isAboutLayout(rule: string) { const allRules = readdirSync(join(eslintDir, "lib/rules")) .filter(file => file.endsWith(".js") && file !== "index.js") .map(file => basename(file, ".js")) - .filter(rule => !isAboutLayout(rule)) + .filter(rule => !isLayoutRule(rule)) .sort(); if (!args.worker) { @@ -114,7 +114,7 @@ require.cache[ruleTesterPath] = { exports: RecordingRuleTester, } as any; -/** Test case properties that are not ESLint config (`RuleTesterParameters` upstream). */ +/** Test case properties that aren't ESLint config (`RuleTesterParameters` upstream). */ const notConfig = ["name", "code", "filename", "options", "before", "after", "errors", "output", "only"]; /** @@ -146,7 +146,7 @@ function runCase( valid: boolean, report: RuleReport, index: number, - /** The parser to use instead of the one the test names. */ + /** Overrides the test's parser. */ realParser?: unknown, ) { const item: Config = typeof rawItem === "string" ? { code: rawItem } : { ...rawItem }; @@ -203,7 +203,7 @@ function runCase( const dropped: string[] = []; const parserOptions = jsonPart(languageOptions.parserOptions, dropped, "parserOptions") as Record; - // ESLint copies `sourceType` in here for espree; it is not something the test set. + // ESLint copies `sourceType` in here for espree. The test didn't set it. if (parser === "espree") delete parserOptions.sourceType; const jsonOptions = jsonPart(options, dropped, "options") as unknown[]; const settings = jsonPart(effective.settings, dropped, "settings") as Record; @@ -240,10 +240,11 @@ function runCase( } /** - * A "parser" of `tests/fixtures/parsers` returns a hard-coded AST of the code: TypeScript, Flow or - * proposals as some parser once read them. Where a real parser reads the code today, and ESLint then - * reports what the test asserts, that is the case. Code that both refuse (`declare var a = 1`, which - * typescript-estree throws on) stays a case for the parser "other": TypeScript, read leniently. + * A "parser" in `tests/fixtures/parsers` returns a hard-coded AST for the code: TypeScript, Flow or + * proposals, as some parser once parsed them. If a real parser accepts the code today and ESLint then + * reports what the test asserts, the case is recorded with that parser. Code that both real parsers + * reject (`declare var a = 1`, which typescript-estree throws on) is recorded with the parser "other", + * which means leniently parsed TypeScript. */ function runCaseWithRealParser(...[ruleName, run, item, valid, report, index]: Parameters) { const scratch: RuleReport = { rule: ruleName, disagreements: [], notes: [] }; diff --git a/test/cli/lint/conformance/extract-oxc.ts b/test/cli/lint/conformance/extract-oxc.ts index 8d4397bb3570..875313740ac2 100644 --- a/test/cli/lint/conformance/extract-oxc.ts +++ b/test/cli/lint/conformance/extract-oxc.ts @@ -1,15 +1,15 @@ // Turns the test cases in oxlint's rule sources (`crates/oxc_linter/src/rules/{eslint,typescript}`) into input for -// `extra-cases.ts`. Only the inputs are taken: what oxlint expects for them is not, because ESLint is the judge. +// `extra-cases.ts`. Only the inputs are used. oxlint's expectations are ignored, because ESLint decides what's correct. // // bun extract-oxc.ts --oxc --out [--fixtures ] [rule...] // -// Writes `//.json` for every rule that `fixtures/` has, and `/stats.json`. A case whose code and -// options equal those of an upstream case is dropped. +// Writes `//.json` for every rule in `fixtures/`, and `/stats.json`. A case with the same code +// and options as an upstream case is dropped. // -// The tests are Rust: `let pass = vec![..]`, `let fail = vec![..]`, `let fix = vec![..]`, `pass.extend(vec![..])` in `#[test]` functions, with -// elements `"code"`, `("code", Some(json!([..])), Some(json!({ "globals": .. })), Some(PathBuf::from("a.ts")))` and -// `("code", "fixed", Some(json!([..])))`. They are read by a scanner that knows the literals of Rust and little else. An -// element that is anything more (`format!`, a variable) is counted in `unparsed`. +// The tests are Rust: `let pass = vec![..]`, `let fail = vec![..]`, `let fix = vec![..]` and `pass.extend(vec![..])` in +// `#[test]` functions. The elements are `"code"`, `("code", Some(json!([..])), Some(json!({ "globals": .. })), +// Some(PathBuf::from("a.ts")))` and `("code", "fixed", Some(json!([..])))`. The scanner that reads them understands +// Rust literals and little else. Any other element (`format!`, a variable) is counted in `unparsed`. import { existsSync, mkdirSync, readFileSync, readdirSync, statSync } from "node:fs"; import { createRequire } from "node:module"; @@ -17,7 +17,7 @@ import { join, relative, resolve } from "node:path"; import { readJson, writeJson, type Fixture } from "./shared.ts"; // --------------------------------------------------------------------------- -// Tokens of Rust +// Rust tokens // --------------------------------------------------------------------------- interface Token { @@ -52,7 +52,7 @@ function unescapeRust(raw: string): string { out += String.fromCodePoint(parseInt(raw.slice(i + 2, end).replaceAll("_", ""), 16)); i = end; } else if (c === "\n" || c === "\r") { - // A line continuation swallows the white space that follows. + // A line continuation swallows the whitespace after it. while (i + 1 < raw.length && /\s/.test(raw[i + 1])) i++; } else out += c; } @@ -109,17 +109,17 @@ export function tokenizeRust(source: string): { tokens: Token[]; comments: Comme } // --------------------------------------------------------------------------- -// The expressions that test cases are made of +// The expressions that make up a test case // --------------------------------------------------------------------------- class Unparsed extends Error {} -/** A path such as `FixKind::Safe`: known to be there, of no interest. */ +/** A path such as `FixKind::Safe`, which is parsed and then ignored. */ const OPAQUE = Symbol("opaque"); class Parser { at = 0; - /** `lookup` finds the value of a `let` or of a function without parameters. */ + /** `lookup` returns the value of a `let` or of a function without parameters. */ constructor( readonly tokens: Token[], readonly lookup: (name: string) => unknown = () => undefined, @@ -256,9 +256,9 @@ export interface Case { filename?: string; languageOptions?: Record; settings?: Record; - /** The part of an `.oxlintrc.json` that the case is linted with, as it is written. */ + /** The case's `.oxlintrc.json` fragment, verbatim. */ oxlintrc?: Record; - /** The path of the file as it is written, whatever its extension. */ + /** The case's file path, verbatim, whatever its extension. */ path?: string; } @@ -276,7 +276,7 @@ const isObject = (value: unknown): value is Record => const EXTENSIONS = /\.(?:[cm]?[jt]s|[jt]sx)$/; const LANGUAGE_KEYS = new Set(["ecmaVersion", "sourceType", "globals", "parserOptions"]); -/** rulegen leaves the `languageOptions` of the upstream test in a comment behind the case. */ +/** rulegen puts the upstream test's `languageOptions` in a comment after the case. */ function languageOptionsIn(comment: string | undefined): Record | undefined { const text = comment?.trim().replace(/,$/, ""); if (!text?.startsWith("{")) return undefined; @@ -350,7 +350,7 @@ export function casesOfFile( const list = tokens[at].kind === "word" ? /^_?(pass|fail|fix)/.exec(name)?.[1] : undefined; if (!list) continue; if (isLet) { - // Over the type, if there is one. + // Skip the type annotation, if any. while (at < tokens.length && tokens[at].text !== "=" && tokens[at].text !== ";") at++; } else { if (tokens[at + 1]?.text !== "." || tokens[at + 2]?.text !== "extend" || tokens[at + 3]?.text !== "(") continue; @@ -444,7 +444,7 @@ if (import.meta.main) { console.error("usage: bun extract-oxc.ts --oxc --out [--fixtures ] [rule...]"); process.exit(2); } - // `env` in a test's configuration is a set of globals. + // An `env` in a test's config expands to a set of globals. const environments = process.env.ESLINT_DIR ? createRequire(join(resolve(process.env.ESLINT_DIR), "package.json"))("globals") : {}; diff --git a/test/cli/lint/conformance/extract-oxlint.ts b/test/cli/lint/conformance/extract-oxlint.ts index 16cc3bf328ef..37876dce3918 100644 --- a/test/cli/lint/conformance/extract-oxlint.ts +++ b/test/cli/lint/conformance/extract-oxlint.ts @@ -1,20 +1,22 @@ -// Turns the tests of the rules that oxlint has in its own plugins (`crates/oxc_linter/src/rules//.rs`) into -// `//.json`, in the format of README.md, with what the **binary of oxlint** reports for each case. What the -// tests expect is not used. +// Turns the tests of the rules in oxlint's own plugins (`crates/oxc_linter/src/rules//.rs`) into +// `//.json`, in the format README.md describes. Each case records what the **oxlint binary** reports +// for it. The tests' own expectations aren't used. // -// export ESLINT_DIR= # for `globals`, which says what an `env` of a case declares +// export ESLINT_DIR= # for `globals`, which lists the globals of a case's `env` // bun extract-oxlint.ts --oxc --oxlint --out [--more ] [--jobs ] [/..] // -// A plugin is called what oxlint calls it in `--rules`, with `-` for `_`. Without names: every rule that is not in `eslint` or -// `typescript`. +// Plugin names are the ones `oxlint --rules` prints, with `-` for `_`. Without rule names, it extracts every rule +// outside `eslint` and `typescript`. // -// - Some tests build their cases with functions and macros, which the scanner of `extract-oxc.ts` cannot read. These cases were -// written out: `--more ` adds the cases of `//.json`, a fixture, to those of the source. `oxlint/` of the -// bundle, extracted, is such a directory. So were the cases that are called `own #n`: oxlint has few for some rules. -// - A message is where the first label of the diagnostic is, which is where oxlint prints it. It has no id. -// - oxlint does not print its fixes. `output` is the code after `--fix`, `outputWithSuggestions` after `--fix --fix-suggestions`, -// and `outputDangerously` after these and `--fix-dangerously`, each `null` if it is the code before it in this list. -// - The file of a case is called what oxlint's `Tester` calls it. The cases of `import` are files of `/import-project`. +// - Some tests build their cases with functions and macros, which the scanner in `extract-oxc.ts` can't read. Those +// cases were written out by hand. `--more ` adds the cases in the fixture `//.json` to the +// ones from the source. The bundle's `oxlint/`, extracted, is such a directory. The cases named `own #n` were also +// written by hand, because oxlint has few tests for some rules. +// - A message's location is the diagnostic's first label, which is where oxlint prints it. It has no id. +// - oxlint doesn't print its fixes. `output` is the code after `--fix`, `outputWithSuggestions` after +// `--fix --fix-suggestions`, and `outputDangerously` after both plus `--fix-dangerously`. Each is `null` if it's the +// same as the one before it. +// - A case's filename is the one oxlint's `Tester` gives it. The `import` cases are files in `/import-project`. import { spawnSync } from "node:child_process"; import { @@ -58,7 +60,7 @@ const environments: Record> = process.env.ESLINT ? createRequire(join(resolve(process.env.ESLINT_DIR), "package.json"))("globals") : {}; const rulesRoot = join(oxc, "crates/oxc_linter/src/rules"); -/** Where the `Tester` is: the files that the cases of `import` are next to. */ +/** The directory the `Tester` runs the `import` cases in. It has the files they import. */ const importProject = join(oxc, "crates/oxc_linter/fixtures/import"); interface Listed { @@ -79,9 +81,9 @@ function rustFiles(path: string): string[] { .filter(file => file.endsWith(".rs")); } -/** What the `Tester` of the test function around a case is told. */ +/** How one test function configures its `Tester`. */ interface Harness { - /** Lines of the source. */ + /** The function's line range in the source. */ from: number; to: number; path?: string; @@ -199,7 +201,7 @@ function record(rule: Listed) { const { cases, unparsed } = rawCasesOf(rule); const id = `${dash(rule.scope)}/${rule.value}`; const hasFixes = rule.fix !== "none" && rule.fix !== "pending"; - // One run of oxlint for all cases with the same configuration. + // Run oxlint once for all the cases with the same config. const groups = new Map(); cases.forEach((it, index) => { const key = JSON.stringify([it.options ?? [], it.oxlintrc ?? {}, it.plugins]); @@ -254,10 +256,10 @@ function record(rule: Listed) { return { line: lines.length, column: lines.at(-1)!.length + 1 }; }; const own = diagnostics.filter(it => it.filename === path); - const isOfRule = (it: Diagnostic) => it.code?.endsWith(`(${rule.value})`); - const fatal = own.find(it => !isOfRule(it)); + const isFromRule = (it: Diagnostic) => it.code?.endsWith(`(${rule.value})`); + const fatal = own.find(it => !isFromRule(it)); const messages = own - .filter(isOfRule) + .filter(isFromRule) .map(it => { const labels = it.labels.map(label => { const [start, end] = [position(label.span.offset), position(label.span.offset + label.span.length)]; @@ -302,7 +304,7 @@ function record(rule: Listed) { parserOptions: /\.(?:[jt]sx|[cm]?js)$/.test(raw.filename) ? { ecmaFeatures: { jsx: true } } : null, }, settings: raw.settings ?? null, - // What else is in the `.oxlintrc.json`. + // The rest of the `.oxlintrc.json`. oxlintrc: raw.oxlintrc, plugins: raw.plugins.length > 0 ? raw.plugins : undefined, typeAware: false, @@ -345,7 +347,7 @@ if (rules.some(it => it.scope === "import") && !process.env.EXTRACT_OXLINT_WORKE if (process.env.EXTRACT_OXLINT_WORKER) { for (const rule of rules) console.log(JSON.stringify(record(rule))); } else { - // A process for each share of the rules. + // Split the rules across `jobs` processes. const shares: string[][] = Array.from({ length: Math.max(1, Math.min(jobs, rules.length)) }, () => []); rules.forEach((rule, i) => shares[i % shares.length].push(`${dash(rule.scope)}/${rule.value}`)); const flags = ["--oxc", oxc, "--oxlint", oxlint, "--out", out, ...(more ? ["--more", more] : [])]; diff --git a/test/cli/lint/conformance/extract-plugins.ts b/test/cli/lint/conformance/extract-plugins.ts index 0615eb682cf3..95c24e505010 100644 --- a/test/cli/lint/conformance/extract-plugins.ts +++ b/test/cli/lint/conformance/extract-plugins.ts @@ -1,5 +1,5 @@ -// Turns the tests of the rules of other plugins into `fixtures//.json`, in the format of README.md, with what the -// real plugin reports under the real ESLint. +// Turns other plugins' rule tests into `fixtures//.json`, in the format README.md describes. Each case +// records what the real plugin reports under real ESLint. // // export ESLINT_DIR= TYPESCRIPT_ESLINT_DIR= OXC_DIR= OXLINT_BIN= // export REACT_DIR= ESLINT_PLUGIN_IMPORT_DIR= @@ -8,17 +8,17 @@ // node extract-plugins.ts [--out ] [/..] // node extract-plugins.ts --cases --out / # your own inputs, see `extra-cases.ts` // -// The cases of a rule, the valid ones first: -// 1. The tests of the plugin itself. Its `RuleTester` is replaced by one that records. -// 2. `import`: the tests that eslint-plugin-import-x has for the same rule. -// 3. The tests that oxlint has for its port of the rule (`name` says where a case is from). What oxlint expects is not used. +// A rule's cases come from these sources, valid cases first: +// 1. The plugin's own tests. Its `RuleTester` is replaced by one that records the cases. +// 2. For `import`, eslint-plugin-import-x's tests for the same rule. +// 3. oxlint's tests for its port of the rule (`name` has the case's origin). oxlint's expectations aren't used. // -// There are two parsers here, espree and that of typescript-eslint. What upstream tests with a parser of Babel or with an old -// typescript-eslint is linted with espree, with JSX, and again as `file.tsx` with typescript-eslint, which is how most code that -// these rules see is parsed. What neither can parse (Flow) is skipped. +// Only two parsers are used here, espree and typescript-eslint's. A case that upstream tests with a Babel parser or an +// old typescript-eslint is linted with espree with JSX on, and again as `file.tsx` with typescript-eslint, which is how +// most code these rules see is parsed. A case that neither can parse (Flow) is skipped. // -// `oxc/*` has no ESLint plugin: the oracle is the binary of oxlint. A message is at the primary label of its diagnostic, or at the -// first, which is also where oxlint looks for a comment that disables the rule. +// `oxc/*` has no ESLint plugin, so the oxlint binary is the oracle. A message's location is its diagnostic's first +// label, which is also where oxlint looks for a comment that disables the rule. import { execFileSync } from "node:child_process"; import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; @@ -42,7 +42,7 @@ import { type Config = Record; -/** A case before it is linted. */ +/** A case before it's linted. */ interface Raw { valid: boolean; name: string | null; @@ -52,9 +52,9 @@ interface Raw { settings?: Config; /** `ecmaVersion`, `sourceType`, `globals`, `parserOptions`, and `parser`: "espree" or "typescript". */ languageOptions?: Config; - /** What upstream parses it with, if that is neither. */ + /** Upstream's parser, if it's neither of those. */ foreignParser?: string; - /** The case as upstream has it, to compare with what it asserts. */ + /** Upstream's original case, for comparing the result with its assertions. */ upstream?: Config; } @@ -118,8 +118,12 @@ class RecordingRuleTester { } } -/** Loads the CommonJS module `file` with `stubs` in place of the modules of these names. */ -function requireWithStubs(file: string, stubs: Record, globals: Record = {}): unknown { +/** Loads the CommonJS module `file`. A `require` of a name in `stubs` returns the stub. */ +function requireWithStubs( + file: string, + stubs: Record, + globals: Record = {}, +): unknown { const module = Module as any; const [load, resolveFilename] = [module._load, module._resolveFilename]; module._resolveFilename = function (request: string, ...rest: unknown[]) { @@ -130,7 +134,14 @@ function requireWithStubs(file: string, stubs: Record, globals: return name in stubs ? stubs[name] : load.call(this, request, ...rest); }; const run = (_: string, body: () => void) => body(); - Object.assign(globalThis, { describe: run, context: run, it: () => {}, before: () => {}, after: () => {}, ...globals }); + Object.assign(globalThis, { + describe: run, + context: run, + it: () => {}, + before: () => {}, + after: () => {}, + ...globals, + }); try { return createRequire(file)(file); } finally { @@ -139,7 +150,7 @@ function requireWithStubs(file: string, stubs: Record, globals: } } -/** Bundles a module, which may be TypeScript, into one CommonJS file. `directory`: where to, if it has to find packages. */ +/** Bundles a module (possibly TypeScript) into one CommonJS file. Pass `directory` if it has to resolve packages. */ function bundleFile(entry: string, name: string, directory = scratch): string { const file = join(directory, `${name}.cjs`); const packages = directory === scratch ? ["--external=eslint"] : ["--packages=external"]; @@ -182,7 +193,7 @@ function reactHooks(rule: string): { rule: RuleModule; cases: Raw[] } { }, { __EXPERIMENTAL__: true }, ); - // The parsers that a case is tested with, by the object that it is. + // The parsers each case is tested with. The runs share their case objects, so the object is the key. const parsers = new Map }>(); for (const run of runs) { const name: string | undefined = run.config.languageOptions?.parser?.foreignParser; @@ -215,7 +226,7 @@ function reactHooks(rule: string): { rule: RuleModule; cases: Raw[] } { // import // --------------------------------------------------------------------------- -/** What `flatConfigs.typescript` of the plugin sets, without which it does not look into TypeScript. */ +/** The settings from the plugin's `flatConfigs.typescript`. Without them it doesn't read TypeScript files. */ const IMPORT_TYPESCRIPT_SETTINGS = { "import/extensions": [".ts", ".cts", ".mts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"], "import/external-module-folders": ["node_modules", "node_modules/@types"], @@ -223,23 +234,27 @@ const IMPORT_TYPESCRIPT_SETTINGS = { "import/resolver": { node: { extensions: [".ts", ".cts", ".mts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"] } }, }; -/** The files that the cases of `import/*` are, and that they import. */ +/** Copies the files that the `import/*` cases are linted as, and the files they import. */ function copyImportProject(): string { const project = join(out, "import-project"); if (casesFile) return join(import.meta.dirname, "fixtures/import-project"); const files = join(realpathSync(requiredEnv("ESLINT_PLUGIN_IMPORT_DIR")), "tests/files"); rmSync(project, { recursive: true, force: true }); mkdirSync(project, { recursive: true }); - for (const name of ["cycles", "restricted-paths", "bar.js", "package.json"]) cpSync(join(files, name), join(project, name), { recursive: true }); - const ofOxlint = join(realpathSync(requiredEnv("OXC_DIR")), "crates/oxc_linter/fixtures/import/cycles"); - for (const name of ["typescript", "issue_21252"]) cpSync(join(ofOxlint, name), join(project, "cycles", name), { recursive: true }); + for (const name of ["cycles", "restricted-paths", "bar.js", "package.json"]) + cpSync(join(files, name), join(project, name), { recursive: true }); + const oxlintCycles = join(realpathSync(requiredEnv("OXC_DIR")), "crates/oxc_linter/fixtures/import/cycles"); + for (const name of ["typescript", "issue_21252"]) + cpSync(join(oxlintCycles, name), join(project, "cycles", name), { recursive: true }); return project; } -/** The paths in `options`, which upstream writes from its root, from `files`: that is the working directory of a case. */ +/** Makes the paths in `options` relative to `files`, a case's working directory. Upstream's start at its root. */ function inProject(options: unknown[] | undefined, files: string): unknown[] | undefined { const text = JSON.stringify(options)?.replaceAll(JSON.stringify(files + "/").slice(1, -1), ""); - return text === undefined ? undefined : JSON.parse(text.replaceAll('"./tests/files/', '"./').replaceAll('"tests/files/', '"')); + return text === undefined + ? undefined + : JSON.parse(text.replaceAll('"./tests/files/', '"./').replaceAll('"tests/files/', '"')); } function importPlugin(rule: string): { rule: RuleModule; cases: Raw[]; cwd: string } { @@ -255,7 +270,7 @@ function importPlugin(rule: string): { rule: RuleModule; cases: Raw[]; cwd: stri process.chdir(root); try { requireWithStubs(bundleFile(join(root, `tests/src/rules/${rule}.js`), `${rule}.test`, built), { - // With a parser of Babel for every version: see `tests/src/utils.js`. + // These versions make `tests/src/utils.js` pick a Babel parser every time. "eslint/package.json": { version: "9.99.0" }, eslint: { RuleTester: RecordingRuleTester }, "typescript/package.json": { version: "5.9.0" }, @@ -277,7 +292,7 @@ function importPlugin(rule: string): { rule: RuleModule; cases: Raw[]; cwd: stri if (typeof item === "string") throw new Error("a case that is a string"); const { parser: used, ...languageOptions } = { ...run.config.languageOptions, ...item.languageOptions }; const name: string = used?.foreignParser ?? "espree"; - // The options for Babel, and a version that only espree looks at. + // Drop Babel's options, and the version, which only espree reads. if (name === "babel") (delete languageOptions.parserOptions, delete languageOptions.ecmaVersion); cases.push({ valid, @@ -296,8 +311,8 @@ function importPlugin(rule: string): { rule: RuleModule; cases: Raw[]; cwd: stri return { rule: module, cases, cwd }; } -/** oxlint's `change_rule_path(..)`, by the line of the case. */ -function importCasesOfOxlint(rule: string): Raw[] { +/** oxlint's cases for `import/`. A case's filename is the next `change_rule_path(..)` after its line. */ +function oxlintImportCases(rule: string): Raw[] { const path = `import/${rule.replaceAll("-", "_")}.rs`; const file = join(realpathSync(requiredEnv("OXC_DIR")), "crates/oxc_linter/src/rules", path); if (!existsSync(file)) return []; @@ -306,7 +321,7 @@ function importCasesOfOxlint(rule: string): Raw[] { line: source.slice(0, it.index).split("\n").length, path: it[1], })); - // Nothing can judge what only oxlint can be told to do. + // `ignoreTypes: false` only exists in oxlint, so there's no oracle for it. const judged = oxlintCases(path).filter(it => (it.options?.[0] as Config | undefined)?.ignoreTypes !== false); return judged.map(it => { const line = Number(/:(\d+) /.exec(it.name!)![1]); @@ -322,7 +337,7 @@ function importCasesOfOxlint(rule: string): Raw[] { // n // --------------------------------------------------------------------------- -/** The directories with a `package.json` that says which versions of Node.js are supported. */ +/** Copies the directories whose `package.json` sets the supported Node.js versions. */ function copyNodeProject(root: string): string { const project = join(out, "n-project"); if (casesFile) return join(import.meta.dirname, "fixtures/n-project"); @@ -337,12 +352,12 @@ function copyNodeProject(root: string): string { function nodePlugin(rule: string): { rule: RuleModule; cases: Raw[]; cwd: string } { const root = realpathSync(requiredEnv("ESLINT_PLUGIN_N_DIR")); const cwd = copyNodeProject(root); - // Next to the test, which looks for its fixtures from where it is. + // The bundle goes next to the test, which finds its fixtures relative to its own path. const directory = join(root, "tests/lib/rules", dirname(rule)); const name = rule.slice(rule.indexOf("/") + 1); runs.length = 0; const globals = createRequire(join(root, "package.json"))("globals"); - /** `RuleTester` of `tests/test-helpers.js` */ + /** Mirrors `RuleTester` in `tests/test-helpers.js`. */ class NodeRuleTester extends RecordingRuleTester { constructor(config: Config = { languageOptions: {} }) { const { env, ...languageOptions } = config.languageOptions; @@ -357,7 +372,7 @@ function nodePlugin(rule: string): { rule: RuleModule; cases: Raw[]; cwd: string } requireWithStubs(bundleFile(join(directory, `${name}.js`), `.extract-${name}`, directory), { "#test-helpers": { RuleTester: NodeRuleTester }, - // For a test that imports the file of the helpers. + // For a test that imports the helpers by file path. eslint: { RuleTester: RecordingRuleTester }, "eslint/package.json": { version: requireFromEslint("./package.json").version }, "eslint/use-at-your-own-risk": {}, @@ -392,8 +407,12 @@ function nodePlugin(rule: string): { rule: RuleModule; cases: Raw[]; cwd: string // react // --------------------------------------------------------------------------- -/** `minEcmaVersion` of `tests/helpers/parsers.js` */ -const REACT_FEATURES: Record = { "class fields": 2022, "optional chaining": 2020, "nullish coalescing": 2020 }; +/** Mirrors `minEcmaVersion` in `tests/helpers/parsers.js`. */ +const REACT_FEATURES: Record = { + "class fields": 2022, + "optional chaining": 2020, + "nullish coalescing": 2020, +}; function reactPlugin(rule: string): { rule: RuleModule; cases: Raw[] } { const root = realpathSync(requiredEnv("ESLINT_PLUGIN_REACT_DIR")); @@ -402,7 +421,7 @@ function reactPlugin(rule: string): { rule: RuleModule; cases: Raw[] } { runs.length = 0; requireWithStubs(join(root, `tests/lib/rules/${rule}.js`), { "../../helpers/ruleTester": RecordingRuleTester, - // `all` makes a case for each parser that has the `features` of the case: that is done below. + // `all` makes one case per parser that supports the case's `features`. The loop below does that instead. "../../helpers/parsers": { all: (tests: unknown[]) => tests }, "eslint/package.json": { version: requireFromEslint("./package.json").version }, }); @@ -421,9 +440,15 @@ function reactPlugin(rule: string): { rule: RuleModule; cases: Raw[] } { options: item.options, settings: item.settings, upstream: item, - foreignParser: features.some(it => /^(flow|bind operator|do expressions)$/.test(it)) ? "babel-eslint" : undefined, + foreignParser: features.some(it => /^(flow|bind operator|do expressions)$/.test(it)) + ? "babel-eslint" + : undefined, + }; + const languageOptions = { + ecmaVersion: versions.length > 0 ? Math.max(...versions) : undefined, + sourceType, + parserOptions, }; - const languageOptions = { ecmaVersion: versions.length > 0 ? Math.max(...versions) : undefined, sourceType, parserOptions }; if (!features.some(it => /^(no-default|decorators|ts|types)$/.test(it))) { cases.push({ ...base, name: item.name ?? null, languageOptions: { ...languageOptions, parser: "espree" } }); } @@ -438,18 +463,21 @@ function reactPlugin(rule: string): { rule: RuleModule; cases: Raw[] } { } // --------------------------------------------------------------------------- -// The tests of oxlint +// oxlint's tests // --------------------------------------------------------------------------- function oxlintCases(path: string): Raw[] { const root = join(realpathSync(requiredEnv("OXC_DIR")), "crates/oxc_linter/src/rules"); - // That module needs more of TypeScript than Node.js strips. + // extract-oxc.ts uses TypeScript syntax that Node.js can't strip, so run it with Bun. const program = ` import { casesOfFile } from ${JSON.stringify(join(import.meta.dirname, "extract-oxc.ts"))}; const stats = { parsed: 0, unparsed: 0, upstream: 0, duplicates: 0, kept: 0 }; const cases = casesOfFile(await Bun.file(process.argv[1]).text(), process.argv[2], {}, stats, false); console.log(JSON.stringify({ cases, stats }));`; - const printed = execFileSync("bun", ["-e", program, join(root, path), path], { encoding: "utf8", maxBuffer: 1 << 28 }); + const printed = execFileSync("bun", ["-e", program, join(root, path), path], { + encoding: "utf8", + maxBuffer: 1 << 28, + }); const { cases, stats }: { cases: Config[]; stats: { unparsed: number } } = JSON.parse(printed); if (stats.unparsed > 0) console.error(`${path}: ${stats.unparsed} cases cannot be read`); return cases.map(it => ({ ...it, code: it.code, name: it.name ?? null, valid: / pass$/.test(it.name ?? "") })); @@ -459,7 +487,7 @@ function oxlintCases(path: string): Raw[] { // Linting // --------------------------------------------------------------------------- -// From the root, so that a file is configured wherever it is. +// With the root as `cwd`, the config applies to a file in any directory. const linter = new Linter({ configType: "flat", cwd: "/" }); interface Attempt { @@ -484,15 +512,18 @@ function attempts(raw: Raw): Attempt[] { return parser === "espree" ? [first] : [first, ...typescript]; } -/** eslint-plugin-import loads the parsers in `import/parsers` by their names, from where it is. */ +/** eslint-plugin-import resolves the names in `import/parsers` from its own directory, so pass an absolute path. */ function settingsToLintWith(settings: Config): Config { const parsers = settings["import/parsers"]; if (!parsers?.["@typescript-eslint/parser"]) return settings; const { "@typescript-eslint/parser": extensions, ...others } = parsers; - return { ...settings, "import/parsers": { ...others, [requireFromEslint.resolve("@typescript-eslint/parser")]: extensions } }; + return { + ...settings, + "import/parsers": { ...others, [requireFromEslint.resolve("@typescript-eslint/parser")]: extensions }, + }; } -/** `ignoreTypes` is an option of oxlint. What it turns on is what eslint-plugin-import always does. */ +/** `ignoreTypes` is an oxlint-only option. `true` is what eslint-plugin-import always does, so drop it. */ function optionsToLintWith(id: string, options: unknown[]): unknown[] { if (id !== "import/no-cycle" || (options[0] as Config | undefined)?.ignoreTypes !== true) return options; const { ignoreTypes: _, ...others } = options[0] as Config; @@ -506,7 +537,10 @@ function record(id: string, rule: RuleModule, raw: Raw, cwd?: string): FixtureCa const given = raw.languageOptions ?? {}; let last: { attempt: Attempt; messages: LintMessage[]; parserOptions: Config } | undefined; for (const attempt of attempts(raw)) { - const parserOptions = { ...given.parserOptions, ecmaFeatures: { ...given.parserOptions?.ecmaFeatures, jsx: attempt.jsx } }; + const parserOptions = { + ...given.parserOptions, + ecmaFeatures: { ...given.parserOptions?.ecmaFeatures, jsx: attempt.jsx }, + }; const config = { files: ["**"], plugins: { [prefix]: { rules: { [name]: rule } } }, @@ -522,7 +556,7 @@ function record(id: string, rule: RuleModule, raw: Raw, cwd?: string): FixtureCa rules: { [id]: ["error", ...optionsToLintWith(id, options)] }, }; const filename = cwd && !attempt.filename.startsWith("<") ? resolve(cwd, attempt.filename) : attempt.filename; - // `basePath` of import/no-restricted-paths is `process.cwd()` unless the options say otherwise. + // import/no-restricted-paths defaults `basePath` to `process.cwd()`. const before = process.cwd(); if (cwd) process.chdir(cwd); let messages: LintMessage[]; @@ -539,9 +573,14 @@ function record(id: string, rule: RuleModule, raw: Raw, cwd?: string): FixtureCa let skip: string | null = null; if (fatal) skip = raw.foreignParser ? `parser: ${raw.foreignParser}` : `fatal: ${fatal.message}`; const resolver = raw.settings?.["import/resolver"]; - const isNode = resolver === undefined || resolver === "node" || (typeof resolver === "object" && Object.keys(resolver).join() === "node"); - const isTypeScript = typeof resolver === "object" && Object.keys(resolver).join() === "eslint-import-resolver-typescript"; - if (!isNode && !(isTypeScript && id === "import/no-restricted-paths")) skip ??= `resolver: ${JSON.stringify(resolver)}`; + const isNode = + resolver === undefined || + resolver === "node" || + (typeof resolver === "object" && Object.keys(resolver).join() === "node"); + const isTypeScript = + typeof resolver === "object" && Object.keys(resolver).join() === "eslint-import-resolver-typescript"; + if (!isNode && !(isTypeScript && id === "import/no-restricted-paths")) + skip ??= `resolver: ${JSON.stringify(resolver)}`; const dropped: string[] = []; const jsonOptions = jsonPart(options, dropped, "options") as unknown[]; const settings = jsonPart(raw.settings ?? {}, dropped, "settings") as Config; @@ -569,10 +608,10 @@ function record(id: string, rule: RuleModule, raw: Raw, cwd?: string): FixtureCa } // --------------------------------------------------------------------------- -// oxc: the binary of oxlint is the oracle +// oxc: the oxlint binary is the oracle // --------------------------------------------------------------------------- -/** The id of a message, from the text that the functions in the source of the rule give their diagnostics. */ +/** Message ids by rule. oxlint has none, so each id is matched by the diagnostic text in the rule's source. */ const OXC_MESSAGES: Record> = { "no-accumulating-spread": { reduceSpread: "Do not spread accumulators in Array.prototype.reduce()", @@ -592,11 +631,18 @@ function recordWithOxlint(rule: string, raws: Raw[]): FixtureCase[] { writeFileSync(file, raw.code); writeFileSync( config, - JSON.stringify({ plugins: ["oxc"], categories: { correctness: "off" }, rules: { [`oxc/${rule}`]: ["error", ...(raw.options ?? [])] } }), + JSON.stringify({ + plugins: ["oxc"], + categories: { correctness: "off" }, + rules: { [`oxc/${rule}`]: ["error", ...(raw.options ?? [])] }, + }), ); let text: string; try { - text = execFileSync(bin, ["-c", config, "-f", "json", file], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }); + text = execFileSync(bin, ["-c", config, "-f", "json", file], { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + }); } catch (error: any) { text = error.stdout; } @@ -613,14 +659,26 @@ function recordWithOxlint(rule: string, raws: Raw[]): FixtureCase[] { .map(it => { const labels = it.labels.map((label: any) => { const [start, end] = [position(label.span.offset), position(label.span.offset + label.span.length)]; - return { line: start.line, column: start.column, endLine: end.line, endColumn: end.column, label: label.label ?? null }; + return { + line: start.line, + column: start.column, + endLine: end.line, + endColumn: end.column, + label: label.label ?? null, + }; }); const id = ids.find(([, message]) => message === it.message)?.[0]; if (!id) throw new Error(`no id for: ${it.message}`); - // The primary label, which the output does not mark. - // Where oxlint prints it. + // The JSON output doesn't mark the primary label. oxlint prints the diagnostic at the first one. const { label: _, ...at } = labels[0]; - return { messageId: id, message: it.message, ...at, fix: null, suggestions: [], oxlint: { labels, help: it.help ?? null } }; + return { + messageId: id, + message: it.message, + ...at, + fix: null, + suggestions: [], + oxlint: { labels, help: it.help ?? null }, + }; }) .sort((a, b) => a.line - b.line || a.column - b.column); return { @@ -653,7 +711,15 @@ function ownCases(): Raw[] { return (Array.isArray(given) ? given : given.cases).map(it => { const item = typeof it === "string" ? { code: it } : it; const { code, options, filename, settings, languageOptions, name } = item; - return { valid: true, name: name ?? null, code, options, filename, settings: settings ?? undefined, languageOptions: languageOptions ?? undefined }; + return { + valid: true, + name: name ?? null, + code, + options, + filename, + settings: settings ?? undefined, + languageOptions: languageOptions ?? undefined, + }; }); } @@ -682,7 +748,7 @@ for (const id of wanted.length > 0 ? wanted : ALL) { if (!casesFile) loaded.cases.push(...oxlintCases(`react/${name.replaceAll("-", "_")}.rs`)); } else if (plugin === "import") { loaded = importPlugin(name); - if (!casesFile) loaded.cases.push(...importCasesOfOxlint(name)); + if (!casesFile) loaded.cases.push(...oxlintImportCases(name)); } else if (plugin === "n") { loaded = nodePlugin(name); } else if (plugin === "react") { @@ -696,11 +762,11 @@ for (const id of wanted.length > 0 ? wanted : ALL) { const made = record(id, loaded.rule, raw, loaded.cwd); if (raw.upstream && !made.skip) { const problems = compareWithUpstream(raw.upstream as any, raw.valid, made, loaded.rule, interpolate); - // The files that it imports are Flow. + // The files it imports are Flow. if (problems.length > 0 && raw.foreignParser) made.skip = `parser: ${raw.foreignParser}`; else if (problems.length > 0) disagreements.push(`#${index}: ${problems.join("; ")}`); } - // ESLint is the judge of what oxlint tests. + // For oxlint's cases, ESLint decides which are valid. if (!raw.upstream) made.valid = made.messages.length === 0; return made; }); @@ -711,6 +777,8 @@ for (const id of wanted.length > 0 ? wanted : ALL) { mkdirSync(dirname(file), { recursive: true }); writeJson(file, { plugin, rule: name, meta, cases }); const skipped = cases.filter(it => it.skip).length; - console.log(`${id}: ${cases.length} cases, ${skipped} skipped, ${disagreements.length} disagree with what upstream asserts`); + console.log( + `${id}: ${cases.length} cases, ${skipped} skipped, ${disagreements.length} disagree with what upstream asserts`, + ); for (const line of disagreements) console.log(` ${line}`); } diff --git a/test/cli/lint/conformance/extract-tsgolint.ts b/test/cli/lint/conformance/extract-tsgolint.ts index fb9c0c29c524..3b46e19dd169 100644 --- a/test/cli/lint/conformance/extract-tsgolint.ts +++ b/test/cli/lint/conformance/extract-tsgolint.ts @@ -1,15 +1,16 @@ -// Turns the test cases of tsgolint (`internal/rules/*/*_test.go`) into input for `extra-cases.ts`. Only the inputs are -// taken: what tsgolint expects for them is not, because typescript-eslint is the judge. +// Turns tsgolint's test cases (`internal/rules/*/*_test.go`) into input for `extra-cases.ts`. Only the inputs are used. +// tsgolint's expectations are ignored, because typescript-eslint decides what's correct. // // bun extract-tsgolint.ts --tsgolint --out [--fixtures ] [rule...] // -// Writes `/typescript-eslint/.json` for every rule that `fixtures/` has, and `/stats.json`. A case whose -// code and options equal those of an upstream case is dropped. +// Writes `/typescript-eslint/.json` for every rule in `fixtures/`, and `/stats.json`. A case with the +// same code and options as an upstream case is dropped. // -// The tests are Go: composite literals `{Code: "..", Options: .., TSConfig: "..", Tsx: true, FileName: ".."}`. They are read -// by a scanner that knows the literals of Go and little else. `Options` is `rule_tester.OptionsFromJSON[T](json)`, or a -// struct whose fields are typescript-eslint's names with a capital. A case with anything more (a variable, a function -// call) is counted in `unparsed`, one with `Files` or with a tsconfig that upstream's project does not have in `unsupported`. +// The tests are Go composite literals: `{Code: "..", Options: .., TSConfig: "..", Tsx: true, FileName: ".."}`. The +// scanner that reads them understands Go literals and little else. `Options` is `rule_tester.OptionsFromJSON[T](json)`, +// or a struct whose fields are typescript-eslint's option names, capitalized. A case with anything else (a variable, a +// function call) is counted in `unparsed`. A case with `Files`, or with a tsconfig that upstream's project doesn't +// have, is counted in `unsupported`. import { existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs"; import { join, resolve } from "node:path"; @@ -69,7 +70,7 @@ class Unparsed extends Error {} const OPEN = "([{"; const CLOSE = ")]}"; -/** The index behind the value that starts at `from`: of the `,` or of the closing bracket. */ +/** Returns the index of the `,` or closing bracket that ends the value starting at `from`. */ function endOfValue(tokens: Token[], from: number): number { let depth = 0; for (let i = from; i < tokens.length; i++) { @@ -83,7 +84,7 @@ function endOfValue(tokens: Token[], from: number): number { return tokens.length; } -/** `{Key: value, ..}` with `open` at the brace: the token range of each value. `null` if it is not that. */ +/** Returns each value's token range in the `{Key: value, ..}` whose brace is at `open`, or `null` if it isn't one. */ function fieldsOf(tokens: Token[], open: number): { fields: Map; end: number } | null { const fields = new Map(); let at = open + 1; @@ -111,7 +112,7 @@ function stringOf(tokens: Token[], [from, to]: [number, number]): string { const lowerFirst = (name: string) => name[0].toLowerCase() + name.slice(1); -/** A value in a struct of options. */ +/** Evaluates a value in an options struct. */ function valueOf(tokens: Token[], [from, to]: [number, number]): unknown { const first = tokens[from]; if (to - from === 1) { @@ -129,7 +130,7 @@ function valueOf(tokens: Token[], [from, to]: [number, number]): unknown { let at = from + 2; while (tokens[at].text !== "{") at++; const items: unknown[] = []; - for (at++; at < to - 1; ) { + for (at++; at < to - 1;) { const end = endOfValue(tokens, at); items.push(valueOf(tokens, [at, end])); at = end + 1; @@ -198,13 +199,13 @@ interface Stats { kept: number; } -/** They stand for the `tsconfig.json` of upstream's project, which has the types of Node.js. */ +/** tsgolint's equivalents of the `tsconfig.json` in upstream's project, which includes the Node.js types. */ const DEFAULT_TSCONFIGS = ["tsconfig.minimal.json", "tsconfig.json", "tsconfig.includeTypes.json"]; function casesOfFile(source: string, label: string, project: string, stats: Stats): Case[] { const tokens = tokenizeGo(source); const cases: Case[] = []; - // The tsconfig that `RunRuleTester(root, "tsconfig.json", ..)` gives to the cases that name none. + // `RunRuleTester(root, "tsconfig.json", ..)` sets the tsconfig for cases that don't have their own. const runs: { start: number; tsconfig: string }[] = []; tokens.forEach((token, i) => { if (token.text !== "RunRuleTester" || tokens[i + 1]?.text !== "(") return; @@ -230,7 +231,10 @@ function casesOfFile(source: string, label: string, project: string, stats: Stat if (fields.has("Tsx") && valueOf(tokens, fields.get("Tsx")!) === true) parserOptions.ecmaFeatures = { jsx: true }; if (fields.has("FileName")) made.filename = stringOf(tokens, fields.get("FileName")!); const run = runs.findLast(it => it.start < tokens[i].start) ?? runs[0]; - const tsconfig = (fields.has("TSConfig") ? stringOf(tokens, fields.get("TSConfig")!) : run?.tsconfig)?.replace(/^\.\//, ""); + const tsconfig = (fields.has("TSConfig") ? stringOf(tokens, fields.get("TSConfig")!) : run?.tsconfig)?.replace( + /^\.\//, + "", + ); stats.parsed++; if (tsconfig === "tsconfig.unstrict.json") { Object.assign(parserOptions, { tsconfigRootDir: "unstrict", projectService: true }); diff --git a/test/cli/lint/conformance/extract-typescript-eslint.ts b/test/cli/lint/conformance/extract-typescript-eslint.ts index 05fa259a0dac..c46a6f39af10 100644 --- a/test/cli/lint/conformance/extract-typescript-eslint.ts +++ b/test/cli/lint/conformance/extract-typescript-eslint.ts @@ -7,10 +7,10 @@ // // The checkout has to be prepared by `prepare-checkouts.ts` first. // -// Same scheme as `extract-eslint.ts`: the test files are loaded with -// `@typescript-eslint/rule-tester` replaced by a stub that records, the real -// `Linter` is then run on every recorded case with the config the real -// RuleTester would have built, and what upstream asserts is a cross-check. +// Works like `extract-eslint.ts`. The test files are loaded with +// `@typescript-eslint/rule-tester` replaced by a stub that records the cases. +// The real `Linter` then runs on every recorded case with the config the real +// RuleTester would have built. Upstream's assertions are only a cross-check. import { cpSync, existsSync, readdirSync, realpathSync, rmSync } from "node:fs"; import { createRequire } from "node:module"; @@ -65,8 +65,8 @@ if (!args.worker) { // fixtures that only mention paths inside of it. process.chdir(projectDir); -// The tests and the rules they import are TypeScript that Node.js cannot strip -// (extensionless imports, enums); the repo's own `tsx` compiles them on require(). +// The tests and the rules they import are TypeScript that Node.js can't strip +// (extensionless imports, enums), so the repo's own `tsx` compiles them on require(). require("tsx/cjs/api").register(); const requireFromRuleTester = createRequire(require.resolve("@typescript-eslint/rule-tester/package.json")); @@ -154,7 +154,7 @@ stubModule("@typescript-eslint/rule-tester", { noFormat: (raw: TemplateStringsArray, ...keys: string[]) => String.raw({ raw }, ...keys), }); -/** Test case properties that are not ESLint config (`RULE_TESTER_PARAMETERS` upstream). */ +/** Test case properties that aren't ESLint config (`RULE_TESTER_PARAMETERS` upstream). */ const notConfig = [ "after", "before", @@ -172,7 +172,7 @@ const notConfig = [ const toPosix = (path: string) => path.split(sep).join("/"); -/** Absolute paths into the upstream fixture project become relative to it, everywhere. */ +/** Recursively makes absolute paths into the upstream fixture project relative to it. */ function relativeToProject(value: T): T { if (typeof value === "string") { if (value !== projectDir && !value.startsWith(projectDir + sep)) return value; @@ -185,12 +185,12 @@ function relativeToProject(value: T): T { return value; } -/** The tsconfig a type-aware case is checked with, relative to the fixture project. */ +/** Returns the tsconfig a type-aware case is checked with, relative to the fixture project. */ function findTsconfig(parserOptions: Config, filename: string): string | null { const root: string = parserOptions.tsconfigRootDir ?? process.cwd(); const project = Array.isArray(parserOptions.project) ? parserOptions.project[0] : parserOptions.project; if (typeof project === "string") return toPosix(relative(projectDir, resolve(root, project))); - // `project: true` and `projectService`: the closest tsconfig.json. + // `project: true` and `projectService` use the closest tsconfig.json. for (let dir = dirname(resolve(root, filename)); ; dir = dirname(dir)) { if (existsSync(join(dir, "tsconfig.json"))) return toPosix(relative(projectDir, join(dir, "tsconfig.json"))); if (dir === dirname(dir)) return null; @@ -297,9 +297,9 @@ function runCase( const settings = jsonPart(config.settings, dropped, "settings") as Config | undefined; if (dropped.length > 0) skip ??= `not JSON-serializable: ${dropped.join(", ")}`; - // ESLint's own idea of these two. The parser is given `parserOptions`' when - // they are set there too, which the RuleTester always does; they are only - // worth recording when the two differ. + // These are the ESLint-level values. The RuleTester also always sets both in + // `parserOptions`, which is what the parser gets. Those are only recorded if + // they differ from the ESLint-level ones. let ecmaVersion: number | "latest" = config.languageOptions.ecmaVersion ?? "latest"; if (typeof ecmaVersion === "number" && ecmaVersion >= 6 && ecmaVersion < 2015) ecmaVersion += 2009; const sourceType = config.languageOptions.sourceType ?? (/\.cjs$/.test(filename) ? "commonjs" : "module"); @@ -336,7 +336,7 @@ function runCase( return result; } -/** `.test.ts` and everything under `/`, in a stable order. */ +/** Returns `.test.ts` and every test under `/`, in a stable order. */ function testFiles(ruleName: string): string[] { const files = existsSync(join(testsDir, `${ruleName}.test.ts`)) ? [join(testsDir, `${ruleName}.test.ts`)] : []; if (existsSync(join(testsDir, ruleName))) { diff --git a/test/cli/lint/conformance/shared.ts b/test/cli/lint/conformance/shared.ts index 44c531133767..a2821a272026 100644 --- a/test/cli/lint/conformance/shared.ts +++ b/test/cli/lint/conformance/shared.ts @@ -1,9 +1,9 @@ // Code shared by `extract-eslint.ts` and `extract-typescript-eslint.ts`. // -// Nothing in here knows how a RuleTester merges its configs. It only knows how -// to turn what the real `Linter` reported into the fixture format, how to -// compare that with what the upstream test asserted, and how to fan the work -// out over child processes. +// Nothing here depends on how a RuleTester merges its configs. This file +// converts the real `Linter`'s reports to the fixture format, compares them +// with the upstream test's assertions, and fans the work out over child +// processes. import { spawn } from "node:child_process"; import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; @@ -29,7 +29,7 @@ export interface FixtureSuggestion { export interface FixtureMessage { /** - * Only present when the message does not come from the rule under test: a + * Only present when the message doesn't come from the rule under test: a * rule enabled by an `/* eslint other-rule: 2 *\/` comment in the code, or * `null` for a problem ESLint itself reports about a directive comment. */ @@ -62,7 +62,7 @@ export interface FixtureCase { settings: Record | null; typeAware: boolean; tsconfig: string | null; - /** The parser with a hard-coded AST that the upstream test names, if a real one took its place. */ + /** The upstream test's hard-coded-AST parser, if the case was recorded with a real parser instead. */ upstreamParser?: string | null; skip: string | null; messages: FixtureMessage[]; @@ -91,21 +91,21 @@ export interface Fixture { /** * Upstream has a few generated stress tests (a string literal of a million - * backslashes). They would be megabytes of JSON each, so they are left out. + * backslashes). They'd be megabytes of JSON each, so they're skipped. */ export const MAX_CODE_LENGTH = 50_000; -/** One place where real ESLint and the upstream assertion do not agree. */ +/** One case where real ESLint and the upstream assertions disagree. */ export interface Disagreement { rule: string; - /** Index into `cases` of the fixture. */ + /** Index into the fixture's `cases`. */ index: number; code: string; skip: string | null; problems: string[]; } -/** What a worker leaves behind for the parent, next to the fixture itself. */ +/** A worker writes one of these for the parent, in addition to the fixture. */ export interface RuleReport { rule: string; disagreements: Disagreement[]; @@ -113,7 +113,7 @@ export interface RuleReport { } // --------------------------------------------------------------------------- -// The slice of ESLint's API that is used +// The parts of ESLint's API used here // --------------------------------------------------------------------------- export interface LintMessage { @@ -170,7 +170,7 @@ export function toFixtureMessages( })); } -/** One pass of `--fix`, or `null` if nothing is fixable. */ +/** Returns the code after one `--fix` pass, or `null` if nothing is fixable. */ export function onePassOutput(code: string, messages: LintMessage[], fixer: SourceCodeFixer): string | null { return messages.some(m => m.fix) ? fixer.applyFixes(code, messages).output : null; } @@ -193,9 +193,9 @@ export function toFixtureMeta(rule: RuleModule): FixtureMeta { } /** - * The JSON-serializable part of a value: functions, class instances (a + * Returns the JSON-serializable part of a value. Functions, class instances (a * `ts.Program`, a parser object, ...) and `undefined` are dropped. `dropped` - * collects the paths that were removed so the caller can decide to skip. + * collects the removed paths so the caller can decide to skip the case. */ export function jsonPart(value: unknown, dropped: string[] = [], path = ""): unknown { if (value === null || typeof value === "string" || typeof value === "boolean") return value; @@ -223,7 +223,7 @@ export const nullIfEmpty = (value: T | null | undefined): T | value && Object.keys(value).length > 0 ? value : null; // --------------------------------------------------------------------------- -// Sanity check against what upstream asserted +// Sanity check against upstream's assertions // --------------------------------------------------------------------------- export interface UpstreamCase { @@ -332,8 +332,8 @@ function inline(value: unknown): string { /** * `JSON.stringify(value, null, 1)`, except that an array or object that fits - * in `width` columns stays on one line. A third of the size, and a message or - * a fix reads as one line in a diff. + * in `width` columns stays on one line. The output is a third of the size, and + * a message or a fix is one line in a diff. */ export function stringify(value: unknown, width = 120, indent = ""): string { if (typeof value !== "object" || value === null) return JSON.stringify(value); diff --git a/test/cli/lint/conformance/sync.ts b/test/cli/lint/conformance/sync.ts index c48dd7928298..21143e4c8238 100644 --- a/test/cli/lint/conformance/sync.ts +++ b/test/cli/lint/conformance/sync.ts @@ -1,17 +1,17 @@ -// Collects the fixtures that the `extract-*.ts` scripts write, and what the cases with types need, in `bundle.zst`. +// Packs the fixtures that the `extract-*.ts` scripts write, plus the files the typed cases need, into `bundle.zst`. // // export ESLINT_DIR=.. TYPESCRIPT_ESLINT_DIR=.. REACT_DIR=.. ESLINT_PLUGIN_IMPORT_X_DIR=.. // export ESLINT_PLUGIN_N_DIR=.. OXC_DIR=.. # the checkouts that the fixtures were recorded with -// bun test/cli/lint/conformance/sync.ts [] # `fixtures` next to this file, unless named -// bun test/cli/lint/conformance/sync.ts --more # `more//` is what `//.json` are -// bun test/cli/lint/conformance/sync.ts --oxlint # `oxlint/` is what `extract-oxlint.ts` wrote to `` +// bun test/cli/lint/conformance/sync.ts [] # default: `fixtures` next to this file +// bun test/cli/lint/conformance/sync.ts --more # replaces `more//` with `` +// bun test/cli/lint/conformance/sync.ts --oxlint # replaces `oxlint/` with `` // bun test/cli/lint/conformance/sync.ts --plugin # replaces `/` with `//.json` // bun test/cli/lint/conformance/sync.ts --extract // // Each of the first four leaves the rest of the bundle untouched. // -// The suites of eslint-plugin-import, -react and -prettier are recorded with the published packages and come into the bundle -// rule by rule, as a rule here does the same as the package's. None of these commands touches them: see `RECORDED`. +// The eslint-plugin-import, -react and -prettier suites are recorded with the published packages. A rule's suite is +// added to the bundle once the rule here passes all of it. Only `--plugin` replaces them. See `RECORDED`. import { $ } from "bun"; import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -20,7 +20,7 @@ import { collect, extract, readBundle, writeBundle } from "../../format/bundle.t const here = import.meta.dir; const bundle = join(here, "bundle.zst"); -/** What the fixtures are from: the directory in `licenses/`, the variable with the checkout, and where `package.json` is in it. */ +/** The fixtures' sources: name in `licenses/`, variable with the checkout's path, directory of its `package.json`. */ const SOURCES = [ ["eslint", "ESLINT_DIR", "."], ["typescript-eslint", "TYPESCRIPT_ESLINT_DIR", "packages/eslint-plugin"], @@ -31,7 +31,7 @@ const SOURCES = [ ["tsgolint", "TSGOLINT_DIR", "."], ] as const; -/** The packages that the project of typescript-eslint's tests finds types in, and from where each is resolved. */ +/** The packages that typescript-eslint's test project gets types from, and the directory each is resolved from. */ const PACKAGES = [ ["@types/node", "."], ["undici-types", "node_modules/@types/node"], @@ -41,7 +41,7 @@ const PACKAGES = [ ["@typescript-eslint/types", "packages/eslint-plugin"], ] as const; -/** What is in the bundle rule by rule, with the projects that the cases are files of. */ +/** The suites that are added to the bundle rule by rule, and the projects their cases are linted in. */ const RECORDED = ["import/", "import-project/", "react/", "prettier/", "prettier-project/", "json/", "markdown/"]; function directoryOf(variable: string): string { @@ -50,7 +50,7 @@ function directoryOf(variable: string): string { return directory; } -/** The directory of `name`, as Node.js finds it from `from`. */ +/** Returns the directory of the package `name`, resolved from `from` the way Node.js does. */ function resolvePackage(name: string, from: string): string { for (let directory = realpathSync(from); ; directory = join(directory, "..")) { if (existsSync(join(directory, "node_modules", name, "package.json"))) @@ -59,13 +59,13 @@ function resolvePackage(name: string, from: string): string { } } -/** Nothing in the bundle names a file of this machine. `local`: directories of it. */ +/** Throws if a fixture contains a path under one of the `local` directories. The bundle must not have local paths. */ function clean(files: Map, local: string[]) { local = local.flatMap(it => [it, realpathSync(it)]); for (const [path, bytes] of files) { if (!path.endsWith(".json")) continue; const text = Buffer.from(bytes).toString("latin1"); - // What Node.js says about a module that it does not find. + // Node.js appends this to its "Cannot find module" message. const cleaned = text.replace(/\\nRequire stack:(?:[^"\\]|\\.)*/g, ""); if (local.some(it => cleaned.includes(it))) throw new Error(`${path} has a path of this machine in it`); if (cleaned !== text) files.set(path, Buffer.from(cleaned, "latin1")); @@ -76,7 +76,7 @@ function summary(files: Map) { return `${files.size} files, ${[...files.values()].reduce((sum, it) => sum + it.length, 0)} bytes`; } -/** What is in the bundle now, if `keeps` says so of the path. */ +/** Returns the current bundle's files whose path passes `keeps`. */ function kept(keeps: (path: string) => boolean): Map { return new Map(existsSync(bundle) ? [...readBundle(bundle)].filter(([path]) => keeps(path)) : []); } @@ -100,12 +100,12 @@ if (first === "--extract" && rest.length === 2) { const files = kept(path => !path.startsWith("oxlint/") && !path.startsWith("oxlint-import-project/")); const found = new Map(); for (const plugin of readdirSync(directory).sort()) { - // `bun lint` has no rule of these two. + // `bun lint` doesn't implement any rules from these two. if (plugin === "jsdoc" || plugin === "vue") continue; if (statSync(join(directory, plugin)).isDirectory()) collect(directory, plugin, found, () => false); } clean(found, [directory]); - // The files that the cases of `import` are next to are not tests. + // The project that the `import` cases are linted in isn't a set of tests, so it gets its own directory. for (const [path, bytes] of found) files.set(path.startsWith("import-project/") ? `oxlint-${path}` : `oxlint/${path}`, bytes); writeBundle(bundle, files); @@ -134,7 +134,7 @@ if (first === "--extract" && rest.length === 2) { } for (const directory of ["typescript-eslint-project", "n-project"]) collect(fixtures, directory, files, () => false); - // What is not from one of `SOURCES` and `PACKAGES` stays as it is. + // Entries that aren't in `SOURCES` or `PACKAGES` are kept as they are. const version: Record = JSON.parse( readFileSync(join(here, "version.json"), "utf8"), ); diff --git a/test/cli/lint/defaults.test.ts b/test/cli/lint/defaults.test.ts index f8c2a585449c..fce92c80b212 100644 --- a/test/cli/lint/defaults.test.ts +++ b/test/cli/lint/defaults.test.ts @@ -16,9 +16,15 @@ const env = { NO_COLOR: "1", }; -type Result = { filePath: string; messages: { line: number; column: number; severity: number; ruleId: string }[] }; +type Result = { + filePath: string; + messages: { line: number; column: number; severity: number; ruleId: string; message: string }[]; +}; -/** `reports` has one `a.js:1:1 error no-debugger` string per problem. `texts` has the files' contents after the run. */ +/** + * Runs `bun lint -f json` on `files`. `reports` lists each problem as `a.js:1:1 error no-debugger`, `problems` lists + * each as `a.js:1:1 Unexpected 'debugger' statement.`, and `texts` maps each file name to its contents after the run. + */ async function lint(files: Record, args: string[], stdin?: string, cwd = ".") { using dir = tempDir("bun-lint-defaults", files); await using proc = spawn({ @@ -37,10 +43,13 @@ async function lint(files: Record, args: string[], stdin?: strin it => `${nameOf(filePath)}:${it.line}:${it.column} ${it.severity === 2 ? "error" : "warning"} ${it.ruleId}`, ), ); + const problems = (Array.isArray(json) ? (json as Result[]) : []).flatMap(({ filePath, messages }) => + messages.map(it => `${nameOf(filePath)}:${it.line}:${it.column} ${it.message}`), + ); const texts = Object.fromEntries( Object.keys(files).map(name => [name, readFileSync(join(String(dir), name), "utf8")]), ); - return { json, reports, texts, stderr, exitCode }; + return { json, reports, problems, texts, stderr, exitCode }; } describe.concurrent("globals", () => { @@ -125,16 +134,17 @@ describe.concurrent("globals", () => { expect(exitCode).toBe(1); }); - // Which names `**/*{.,_,-}{test,spec,e2e,cy}.{js,mjs,cjs,jsx,ts,mts,cts,tsx}` is for. A global of a test runner can't be - // assigned to. In another file nothing defines it, which is only reported in JavaScript. - test("a file is a test by what its name ends with", async () => { + // Checks which names `**/*{.,_,-}{test,spec,e2e,cy}.{js,mjs,cjs,jsx,ts,mts,cts,tsx}` matches. In a test file, + // assigning to a test runner's global is reported by no-global-assign. In any other file the global is undefined, + // which is only reported in JavaScript. + test("a file is a test file if its name ends with a test suffix", async () => { const [stems, separators] = [ ["a", "", "a.b", "test"], [".", "_", "-", "", "+"], ]; const words = ["test", "spec", "e2e", "cy", "tes", "tests", "Test", "atest"]; const extensions = ["js", "mjs", "cjs", "jsx", "ts", "mts", "cts", "tsx"]; - // To Windows and macOS `a.Test.js` is the file `a.test.js`. + // On Windows and macOS, `a.Test.js` and `a.test.js` are the same file. const folderOf = (word: string) => (word === "Test" ? "cased/" : ""); const names = stems.flatMap(stem => separators.flatMap(separator => @@ -216,7 +226,7 @@ skipWaitng(); } }); - test("the test folders count from the closest package.json, also when run from inside one", async () => { + test("test folders are matched relative to the closest package.json, even when run from inside one", async () => { const files = { "package.json": "{}", "test/a.js": 'describe("a", () => {});\n', @@ -579,6 +589,75 @@ export namespace Shapes { expect(eslint).toEqual([`a.ts:2:3 error ${rule}`, `a.ts:8:8 error ${rule}`]); }); + describe("no-var and a var that only declares a type", () => { + const files = { + "a.ts": `declare var top: number; +// eslint-disable-next-line no-var +declare var disabled: number; +export declare var exported: number; +declare namespace ns { var inNamespace: number; } +declare module "m" { var inModule: number; } +declare global { var inGlobal: number; } +declare global { export var exportedInGlobal: number; } +declare global { namespace inner { var nestedInGlobal: number; } } +namespace real { declare var inReal: number; } +var plain = 1; +`, + }; + const eslint = { + ...files, + "eslint.config.mjs": `export default [{ files: ["**/*.ts"], extends: ["typescript-eslint/base"], rules: { "no-var": "error" } }];\n`, + }; + const oxlint = { + ...files, + ".oxlintrc.json": `{ "categories": { "correctness": "off" }, "rules": { "no-var": "error" } }`, + }; + const at = (...places: string[]) => places.map(place => `a.ts:${place} error no-var`); + + test("is reported with an ESLint config, so the comment that disables it isn't unused, and not without a config", async () => { + const [withEslint, native] = await Promise.all([lint(eslint, ["a.ts"]), lint(files, [])]); + expect(withEslint.reports).toEqual(at("1:1", "4:8", "5:24", "6:22", "8:25", "9:36", "10:18", "11:1")); + expect(native.reports.filter(it => it.endsWith(" no-var"))).toEqual(["a.ts:11:1 warning no-var"]); + }); + + test("with an ESLint config, --fix changes what ESLint changes", async () => { + const { texts } = await lint(eslint, ["--fix", "a.ts"]); + expect(texts["a.ts"]).toBe(`declare let top: number; +// eslint-disable-next-line no-var +declare var disabled: number; +export declare var exported: number; +declare namespace ns { let inNamespace: number; } +declare module "m" { let inModule: number; } +declare global { var inGlobal: number; } +declare global { export var exportedInGlobal: number; } +declare global { namespace inner { let nestedInGlobal: number; } } +namespace real { declare let inReal: number; } +let plain = 1; +`); + }); + + test("with an ESLint 8 config, a var in declare global is reported too, and --fix changes none in a block", async () => { + const eslintrc = `{ "root": true, "parser": "@typescript-eslint/parser", "parserOptions": { "sourceType": "module" }, "rules": { "no-var": "error" } }`; + const eslint8 = { ...files, ".eslintrc.json": eslintrc }; + const [{ reports }, { texts }] = await Promise.all([ + lint(eslint8, ["--report-unused-disable-directives", "a.ts"]), + lint(eslint8, ["--fix", "a.ts"]), + ]); + expect(reports).toEqual(at("1:1", "4:8", "5:24", "6:22", "7:18", "8:25", "9:36", "10:18", "11:1")); + expect(texts["a.ts"]).toBe( + files["a.ts"].replace("declare var top", "declare let top").replace("var plain", "let plain"), + ); + }); + + test("with an oxlint config, only a var in an ambient block isn't reported", async () => { + const { json } = await lint(oxlint, ["--report-unused-disable-directives", "a.ts"]); + const reports = json.diagnostics.map( + (it: any) => `${it.labels[0].span.line}:${it.labels[0].span.column} ${it.code}`, + ); + expect(reports).toEqual(["1:9", "4:16", "10:26", "11:1"].map(place => `${place} eslint(no-var)`)); + }); + }); + const react = { "package.json": JSON.stringify({ dependencies: { react: "^19.0.0" } }) }; test("a parameter named use isn't React's hook", async () => { @@ -692,6 +771,150 @@ export function run(command: string) { expect(eslint).toEqual(["a.ts:6:5 error no-fallthrough", "a.ts:8:5 error no-fallthrough"]); }); + describe("with --type-aware, URL in a template literal", () => { + const rule = "@typescript-eslint/restrict-template-expressions"; + const tsconfig = (lib: string[]) => + JSON.stringify({ compilerOptions: { strict: true, lib, types: [], moduleDetection: "force" } }); + const code = `declare const server: { url: URL }; +export const texts = [ + \`\${server.url}api\`, + \`\${new URL("/x", server.url)}\`, + \`\${server.url.searchParams}\`, + \`\${{ a: 1 }}\`, +]; +`; + // Same shape as @types/node: the global URL extends node:url's interface. + const node = `declare module "node:url" { + interface URLSearchParams { toString(): string } + interface URL { href: string; searchParams: URLSearchParams; toString(): string } + var URL: { prototype: URL; new (url: string, base?: string | URL): URL }; +} +`; + const globalsOfNode = `import * as url from "node:url"; +declare global { + interface URL extends url.URL {} + var URL: typeof url.URL; +} +`; + + test("isn't reported when a types package declares the global, like in a `bun init` project", async () => { + const files = { + "tsconfig.json": tsconfig(["ESNext"]), + "url.d.ts": node, + "globals.d.ts": globalsOfNode, + "a.ts": code, + }; + const { native, eslint } = await inBothModes(files, [rule], ["--type-aware"]); + expect(native).toEqual([`a.ts:6:6 error ${rule}`]); + expect(eslint).toEqual([3, 4, 5, 6].map(line => `a.ts:${line}:6 error ${rule}`)); + }); + + test("isn't reported when a script declares the global", async () => { + const declared = `declare class URLSearchParams { toString(): string } +declare class URL { constructor(url: string, base?: string | URL); searchParams: URLSearchParams; toString(): string } +`; + const files = { "tsconfig.json": tsconfig(["ESNext"]), "globals.d.ts": declared, "a.ts": code }; + expect((await inBothModes(files, [rule], ["--type-aware"])).native).toEqual([`a.ts:6:6 error ${rule}`]); + }); + + test("isn't reported when it's imported from node:url", async () => { + const imported = `import { URL } from "node:url";\nexport const text = \`\${new URL("https://bun.com")}\`;\n`; + const files = { "tsconfig.json": tsconfig(["ESNext"]), "url.d.ts": node, "a.ts": imported }; + expect((await inBothModes(files, [rule], ["--type-aware"])).native).toEqual([]); + }); + + test("isn't reported with the DOM lib", async () => { + const files = { "tsconfig.json": tsconfig(["ESNext", "DOM"]), "a.ts": code }; + const { native, eslint } = await inBothModes(files, [rule], ["--type-aware"]); + expect(native).toEqual([`a.ts:6:6 error ${rule}`]); + expect(eslint).toEqual(native); + }); + + test("is reported when URL is the project's own class", async () => { + const files = { + "tsconfig.json": tsconfig(["ESNext", "DOM"]), + "url.ts": 'export class URL {\n href = "";\n}\n', + "a.ts": `import { URL } from "./url";\nexport const text = \`\${new URL()}\`;\n`, + "b.ts": `class URL {\n href = "";\n}\nexport const text = \`\${new URL()}\`;\n`, + }; + const { native } = await inBothModes(files, [rule], ["--type-aware"]); + expect(native).toEqual([`a.ts:2:24 error ${rule}`, `b.ts:4:24 error ${rule}`]); + }); + + test("is reported when the allow list only allows URL from lib and the lib doesn't declare it", async () => { + const files = { + "tsconfig.json": tsconfig(["ESNext"]), + "url.d.ts": node, + "globals.d.ts": globalsOfNode, + "a.ts": code, + "bunfig.toml": `[lint.rules]\n"${rule}" = ["error", { allow = [{ from = "lib", name = ["URL", "URLSearchParams"] }] }]\n`, + }; + const { reports } = await lint(files, ["--type-aware"]); + expect(reports.filter(it => it.endsWith(rule))).toEqual([3, 4, 5, 6].map(line => `a.ts:${line}:6 error ${rule}`)); + }); + }); + + test("with --type-aware, no-implied-eval ignores a setTimeout argument of type any", async () => { + const rule = "@typescript-eslint/no-implied-eval"; + const files = { + "tsconfig.json": `{ "compilerOptions": { "strict": true, "lib": ["esnext", "dom"], "types": [] } }`, + "a.ts": `import { stub } from "not-installed"; +export function later(callback: any, code: string, options: { done: any }) { + setTimeout(callback, 1); + setTimeout(options.done, 1); + setTimeout(stub, 1); + setTimeout(JSON.parse(code), 1); + setTimeout(code, 1); +} +`, + }; + const { native, eslint } = await inBothModes(files, [rule], ["--type-aware"]); + expect(native).toEqual([`a.ts:7:14 warning ${rule}`]); + expect(eslint).toEqual([3, 4, 5, 6, 7].map(line => `a.ts:${line}:14 error ${rule}`)); + }); + + describe("with --type-aware, awaiting a bun:test promise matcher", () => { + const rule = "@typescript-eslint/await-thenable"; + const tsconfig = `{ "compilerOptions": { "strict": true, "lib": ["esnext"], "types": [] } }`; + // The relevant declarations from bun-types. + const matchers = `interface Matchers { + not: Matchers; + resolves: Matchers>; + rejects: Matchers; + toBe(expected: T): void; + toThrow(expected?: unknown): void; + } + export function expect(actual: T): Matchers;`; + const code = (source: string) => `import { expect } from "${source}"; +declare const promise: Promise; +await expect(promise).resolves.toBe(1); +await expect(promise).rejects.toThrow(); +await expect(promise).resolves.not.toBe(2); +await expect(1).toBe(1); +`; + + test("isn't reported", async () => { + const files = { + "tsconfig.json": tsconfig, + "bun-test.d.ts": `declare module "bun:test" {\n ${matchers}\n}\n`, + "a.ts": code("bun:test"), + }; + const { native, eslint } = await inBothModes(files, [rule], ["--type-aware"]); + expect(native).toEqual([`a.ts:6:1 warning ${rule}`]); + expect(eslint).toEqual([`a.ts:6:1 error ${rule}`]); + }); + + test("is reported when expect doesn't come from bun:test", async () => { + const files = { + "tsconfig.json": tsconfig, + "mine.ts": `export ${matchers.replace("export function", "export declare function")}\n`, + "a.ts": code("./mine"), + }; + const { native } = await inBothModes(files, [rule], ["--type-aware"]); + expect(native).toEqual([3, 4, 5, 6].map(line => `a.ts:${line}:1 warning ${rule}`)); + }); + }); + test("an array of elements needs keys only where React renders it as a list", async () => { const files = { ...react, @@ -712,7 +935,7 @@ export const Mapped = ({ items }) => items.map(item =>
  • {item}
  • ); }; const rule = "react/jsx-key"; const { native, eslint } = await inBothModes(files, [rule]); - const at = (places: string[]) => places.map(place => `a.jsx:${place} error ${rule}`); + const at = (positions: string[]) => positions.map(position => `a.jsx:${position} error ${rule}`); const rendered = ["7:33", "7:45", "8:46", "10:11", "10:23", "12:29", "13:56"]; expect(native).toEqual(at(rendered)); expect(eslint).toEqual(at(["2:18", "2:31", "5:23", "5:33", "6:46", "6:69", ...rendered])); @@ -756,7 +979,7 @@ export const HALF = 9007199254740993.5; }; const rule = "no-loss-of-precision"; const { native, eslint } = await inBothModes(files, [rule]); - const at = (places: string[]) => places.map(place => `${name}:${place} error ${rule}`); + const at = (positions: string[]) => positions.map(position => `${name}:${position} error ${rule}`); const integers = ["3:19", "4:20", "5:20", "6:21", "7:21", "8:21"]; expect(native).toEqual(at(integers)); expect(eslint).toEqual(at(["1:19", "2:20", ...integers])); @@ -786,10 +1009,10 @@ export const HALF = 9007199254740993.5; }; const { native, eslint } = await inBothModes(files, ["no-undef"]); expect(native).toEqual(["a.js:3:57 error no-undef"]); - expect(eslint).toEqual(["2:39", "2:51", "3:44", "3:57"].map(place => `a.js:${place} error no-undef`)); + expect(eslint).toEqual(["2:39", "2:51", "3:44", "3:57"].map(position => `a.js:${position} error no-undef`)); const strict = { "bunfig.toml": `[lint.rules]\n"no-undef" = ["error", { typeof = true }]\n` }; expect((await inBothModes({ ...files, ...strict }, ["no-undef"])).native).toEqual( - ["2:14", "2:39", "2:51", "3:17", "3:44", "3:57"].map(place => `a.js:${place} error no-undef`), + ["2:14", "2:39", "2:51", "3:17", "3:44", "3:57"].map(position => `a.js:${position} error no-undef`), ); }); @@ -845,7 +1068,7 @@ export const HALF = 9007199254740993.5; expect((await lint(commented, [])).reports).toEqual(expected); }); - test("the options of an override replace those of [lint.rules], not the defaults", async () => { + test("an override's options replace the ones from [lint.rules], not the defaults", async () => { const bunfig = `[lint.rules] "no-irregular-whitespace" = ["error", { skipComments = false }] [[lint.overrides]] @@ -898,7 +1121,7 @@ describe.concurrent("JSX uses the function it compiles to", () => { expect(reports).toEqual([]); }); - test.each(["a.jsx", "a.tsx"])("the function that a @jsx comment names isn't unused in %s", async name => { + test.each(["a.jsx", "a.tsx"])("the function named in a @jsx comment isn't unused in %s", async name => { const { reports } = await lint({ [name]: preact }, []); expect(reports).toEqual([]); }); @@ -1008,44 +1231,44 @@ export {}; test.each([ [ - "a line that has something else on it stays", + "keeps a line that has something else on it", "const a = 1; // why\nconst b = 2; export {};\n", "// why\nexport {};\n", ], - ["no space stays at the end of a line", "g(); const a = 1;\nexport {};\n", "g();\nexport {};\n"], + ["leaves no trailing space", "g(); const a = 1;\nexport {};\n", "g();\nexport {};\n"], [ - "no doubled space stays", + "leaves no double space", 'import { a, used } from "./b.js";\nused();\n', 'import { used } from "./b.js";\nused();\n', ], [ - "no empty first line in a block", + "leaves no empty first line in a block", "export function f() {\n const a = 1;\n\n return 1;\n}\n", "export function f() {\n return 1;\n}\n", ], [ - "no empty last line in a block", + "leaves no empty last line in a block", "export function f() {\n g();\n\n const a = 1;\n}\n", "export function f() {\n g();\n}\n", ], [ - "no two empty lines in a row", + "leaves no two empty lines in a row", 'import x from "./x.js";\n\nconst a = 1;\n\nexport const y = x;\n', 'import x from "./x.js";\n\nexport const y = x;\n', ], - ["no empty line at the start of the file", "const a = 1;\n\nexport {};\n", "export {};\n"], - ["no empty line at the end of the file", "export {};\n\nconst a = 1;\n", "export {};\n"], + ["leaves no empty line at the start of the file", "const a = 1;\n\nexport {};\n", "export {};\n"], + ["leaves no empty line at the end of the file", "export {};\n\nconst a = 1;\n", "export {};\n"], [ - "an empty line between two statements stays", + "keeps an empty line between two statements", "g();\nconst a = 1;\n\nh();\nexport {};\n", "g();\n\nh();\nexport {};\n", ], [ - "the same with \\r\\n", + "handles \\r\\n the same way", "export function f() {\r\n const a = 1;\r\n\r\n return 1;\r\n}\r\n", "export function f() {\r\n return 1;\r\n}\r\n", ], - ])("%s", async (_, code, expected) => { + ])("removing a declaration %s", async (_, code, expected) => { const { texts } = await lint({ "a.mjs": code }, ["--fix-suggestions"]); expect(texts["a.mjs"]).toBe(expected); }); @@ -1103,7 +1326,62 @@ export function Timer({ ms, cb }) { expect(dangerous.texts["b.jsx"]).toBe(files["b.jsx"].replace("[ms]", "[cb, ms]")); }); - test("it leaves alone what would change working code or break the type check", async () => { + // ESLint's --fix applies all of these. The project type checks before those fixes and fails after them. + test("--fix skips fixes that would cause type errors", async () => { + const kept = { + // TS2339 on `globalThis.BUILD_ID`, and TS2451 if another file declares it too + "global.ts": "declare var BUILD_ID: string;\nconsole.log(globalThis.BUILD_ID);\n", + "ambient.ts": "declare namespace Legacy {\n var version: string;\n}\nconsole.log(Legacy.version);\n", + // TS2540 + "namespace.ts": + "export namespace Config {\n export let verbose = false;\n}\nConfig.verbose = true;\nconsole.log(Config.verbose);\n", + // TS2322, TS2345 + "object.ts": + 'export const a: Object = 1;\nexport function f(x: Object) {\n return x;\n}\nconsole.log(f("s"));\n', + // TS2774 + "cast.ts": + 'declare function cb(): void;\nif (!!cb) console.log("has cb");\nexport const b = Boolean(cb) ? 1 : 2;\n', + }; + const fixed = { + "fixed.ts": + 'export let n = 1;\nlet m = 2;\nvar k = 3;\nexport const s: String = "x";\nconst v = 0;\nif (!!v) console.log(k, m, n);\nexport const g = (name: string) => (!!name ? 1 : 2);\nexport const h = (cb: () => void) => !Boolean(cb);\nexport const i = (value: unknown) => (!!value ? 1 : 2);\n', + "fixed.js": "export function call(cb) {\n if (!!cb) cb();\n}\n", + }; + const rules = /(no-var|prefer-const|no-wrapper-object-types|no-extra-boolean-cast)$/; + const reportsOf = (result: { reports: string[] }) => + result.reports + .filter(it => rules.test(it)) + .map(it => it.replace(/:\d+:\d+ warning/, "")) + .sort(); + const [safe, dangerous] = await Promise.all([ + lint({ ...kept, ...fixed }, ["--fix"]), + lint({ ...kept, ...fixed }, ["--fix-dangerously"]), + ]); + expect(safe.texts).toEqual({ + ...kept, + "fixed.ts": + 'export const n = 1;\nconst m = 2;\nconst k = 3;\nexport const s: string = "x";\nconst v = 0;\nif (v) console.log(k, m, n);\nexport const g = (name: string) => (name ? 1 : 2);\nexport const h = (cb: () => void) => !cb;\nexport const i = (value: unknown) => (value ? 1 : 2);\n', + "fixed.js": "export function call(cb) {\n if (cb) cb();\n}\n", + }); + expect(reportsOf(safe)).toEqual([ + "cast.ts no-extra-boolean-cast", + "cast.ts no-extra-boolean-cast", + "namespace.ts prefer-const", + "object.ts @typescript-eslint/no-wrapper-object-types", + "object.ts @typescript-eslint/no-wrapper-object-types", + ]); + // `declare var` isn't reported at all, so no flag rewrites it. + expect(dangerous.texts["global.ts"]).toBe(kept["global.ts"]); + expect(dangerous.texts["ambient.ts"]).toBe(kept["ambient.ts"]); + expect(dangerous.texts["namespace.ts"]).toContain("export const verbose = false;"); + expect(dangerous.texts["object.ts"]).toContain("a: object = 1"); + expect(dangerous.texts["object.ts"]).toContain("f(x: object)"); + expect(dangerous.texts["cast.ts"]).toContain("if (cb) console.log"); + expect(dangerous.texts["cast.ts"]).toContain("b = cb ? 1 : 2"); + expect(reportsOf(dangerous)).toEqual([]); + }); + + test("skips suggestions that would change working code or break the type check", async () => { const files = { "tsconfig.json": `{ "compilerOptions": { "strict": true, "lib": ["esnext", "dom"], "types": [] } }`, "a.ts": `// @ts-ignore @@ -1206,15 +1484,20 @@ declare const c: any; }); test("rules set in bunfig.toml or with --rule apply to them too", async () => { - const bunfig = `[lint.rules]\n"@typescript-eslint/no-explicit-any" = "warn"\n"no-var" = "error"\n`; + const bunfig = `[lint.rules]\n"@typescript-eslint/no-explicit-any" = "warn"\n"@typescript-eslint/no-empty-object-type" = "error"\n`; const expected = [ - "types.d.ts:1:1 error no-var", "types.d.ts:1:16 warning @typescript-eslint/no-explicit-any", "types.d.ts:2:19 error @typescript-eslint/no-misused-new", + "types.d.ts:3:18 error @typescript-eslint/no-empty-object-type", ]; const [byFile, byFlag] = await Promise.all([ lint({ "types.d.ts": code, "bunfig.toml": bunfig }, []), - lint({ "types.d.ts": code }, ["--rule", "@typescript-eslint/no-explicit-any: warn", "--rule", "no-var: error"]), + lint({ "types.d.ts": code }, [ + "--rule", + "@typescript-eslint/no-explicit-any: warn", + "--rule", + "@typescript-eslint/no-empty-object-type: error", + ]), ]); expect(byFile.reports).toEqual(expected); expect(byFlag.reports).toEqual(expected); @@ -1250,7 +1533,7 @@ const h = 1; test.each([ ["a.js", "no-unused-vars"], ["a.ts", "@typescript-eslint/no-unused-vars"], - ])("%s", async (name, rule) => { + ])("in %s", async (name, rule) => { const set = (setting: string) => ({ [name]: code, "bunfig.toml": `[lint.rules]\n"${rule}" = ${setting}\n` }); const [plain, severity, options] = await Promise.all([ lint({ [name]: code }, []), @@ -1446,14 +1729,14 @@ export function useThing(a, on) { "src/App.jsx": component, "src/deep/App.jsx": component, }; - const [searched, named, piped, printed] = await Promise.all([ + const [searched, explicit, piped, printed] = await Promise.all([ lint(files, []), lint(files, ["src/App.jsx", "src/deep/App.jsx"]), lint(files, ["--stdin", "--stdin-filename", "src/Other.jsx"], component), lint(files, ["--print-config", "src/App.jsx"]), ]); expect(searched.reports).toEqual([...found("src/App.jsx"), ...found("src/deep/App.jsx")]); - expect(named.reports).toEqual(searched.reports); + expect(explicit.reports).toEqual(searched.reports); expect(piped.reports).toEqual(found("src/Other.jsx")); expect(printed.json.rules["react-hooks/rules-of-hooks"]).toEqual([2]); }); @@ -1464,18 +1747,18 @@ export function useThing(a, on) { "server/package.json": `{ "dependencies": {} }`, "server/App.jsx": component, }; - const [searched, named] = await Promise.all([lint(files, []), lint(files, ["server/App.jsx"])]); + const [searched, explicit] = await Promise.all([lint(files, []), lint(files, ["server/App.jsx"])]); expect(searched.reports).toEqual([]); - expect(named.reports).toEqual([]); + expect(explicit.reports).toEqual([]); }); test("they also run on files passed by name and on stdin", async () => { const files = { "package.json": dependingOn("dependencies"), "src/App.jsx": component }; - const [named, piped] = await Promise.all([ + const [explicit, piped] = await Promise.all([ lint(files, ["src/App.jsx"]), lint(files, ["--stdin", "--stdin-filename", "src/Other.jsx"], component), ]); - expect(named.reports).toEqual(found("src/App.jsx")); + expect(explicit.reports).toEqual(found("src/App.jsx")); expect(piped.reports).toEqual(found("src/Other.jsx")); }); @@ -1529,16 +1812,16 @@ export function useThing(a, on) { lint(files, ["--print-config", "App.jsx"]), lint(files, ["--print-config", "mail/App.jsx"]), ]); - const ofReact = (printed: { rules: object }) => + const reactRules = (printed: { rules: object }) => Object.fromEntries(Object.entries(printed.rules).filter(([name]) => name.startsWith("react"))); - expect(ofReact(withReact.json)).toEqual({ + expect(reactRules(withReact.json)).toEqual({ "react-hooks/rules-of-hooks": [2], "react-hooks/exhaustive-deps": [1], "react/jsx-key": [2, { checkArraysOutsideJSX: false }], "react/jsx-uses-react": [2], }); // `react/jsx-uses-react` reports nothing. It's also for Preact's `h`, so it doesn't depend on React. - expect(ofReact(without.json)).toEqual({ + expect(reactRules(without.json)).toEqual({ "react/jsx-key": [0, { checkArraysOutsideJSX: false }], "react/jsx-uses-react": [2], }); @@ -1546,9 +1829,9 @@ export function useThing(a, on) { test("they stay off with an ESLint or oxlint config", async () => { const files = { "package.json": dependingOn("dependencies"), "App.jsx": component }; - const ofEslint = `export default [{ files: ["**/*.jsx"], languageOptions: { parserOptions: { ecmaFeatures: { jsx: true } } } }];\n`; + const eslintConfig = `export default [{ files: ["**/*.jsx"], languageOptions: { parserOptions: { ecmaFeatures: { jsx: true } } } }];\n`; const [eslint, oxlint] = await Promise.all([ - lint({ ...files, "eslint.config.js": ofEslint }, ["App.jsx"]), + lint({ ...files, "eslint.config.js": eslintConfig }, ["App.jsx"]), lint({ ...files, ".oxlintrc.json": "{}" }, ["App.jsx"]), ]); expect(eslint.json).toEqual([expect.objectContaining({ messages: [] })]); @@ -1556,3 +1839,1135 @@ export function useThing(a, on) { expect([eslint.exitCode, oxlint.exitCode]).toEqual([0, 0]); }); }); + +describe.concurrent("ES modules and CommonJS", () => { + const early = `const os = require("os"); +if (os.platform() === "never") { + return; +} +module.exports = os.platform(); +`; + const returnOutside = "Parsing error: 'return' outside of function"; + const esmPackage = { "package.json": `{ "type": "module" }` }; + + test.each([ + ["no package.json", {}], + ["a package.json without a type", { "package.json": `{ "name": "a" }` }], + [`"type": "commonjs"`, { "package.json": `{ "type": "commonjs" }` }], + ])("allows a top-level return with %s", async (_, files) => { + const { problems, exitCode } = await lint({ ...files, "early.js": early }, []); + expect(problems).toEqual([]); + expect(exitCode).toBe(0); + }); + + test("runs rules on a file with a top-level return", async () => { + const { reports } = await lint({ "early.js": `${early}debugger;\n` }, []); + expect(reports).toEqual(["early.js:6:1 error no-debugger"]); + }); + + test(`reports a top-level return with "type": "module"`, async () => { + const { problems, exitCode } = await lint({ ...esmPackage, "early.js": early }, []); + expect(problems).toEqual([`early.js:3:3 ${returnOutside}`]); + expect(exitCode).toBe(1); + }); + + test("uses the type from the nearest package.json", async () => { + const files = { + ...esmPackage, + "early.js": early, + "src/early.js": early, + "legacy/package.json": "{}", + "legacy/early.js": early, + "legacy/esm/package.json": esmPackage["package.json"], + "legacy/esm/early.js": early, + }; + const expected = ["early.js", "legacy/esm/early.js", "src/early.js"].map(it => `${it}:3:3 ${returnOutside}`); + const names = Object.keys(files).filter(it => it.endsWith(".js")); + const [all, explicit] = await Promise.all([lint(files, []), lint(files, names)]); + expect(all.problems.sort()).toEqual(expected); + expect(explicit.problems.sort()).toEqual(expected); + }); + + test.each([ + ["import", `import "./b.js";`], + ["export", "export {};"], + ["import.meta", "console.log(import.meta.url);"], + ["a top-level await", "await 1;"], + ["a top-level for await", "for await (const a of []) console.log(a);"], + ])("%s makes a file a module", async (_, code) => { + const files = { "a.js": `${code}\nreturn;\n`, "b.js": "" }; + const [withoutPackageJson, inCommonJs] = await Promise.all([ + lint(files, ["a.js"]), + lint({ ...files, "package.json": `{ "type": "commonjs" }` }, ["a.js"]), + ]); + expect(withoutPackageJson.problems).toEqual([`a.js:2:1 ${returnOutside}`]); + expect(inCommonJs.problems).toEqual([`a.js:2:1 ${returnOutside}`]); + }); + + test.each([ + ["import()", `import("./b.js").then(console.log);`], + ["an await in a function", "(async () => { await 1; })();"], + ["a keyword inside a string", `console.log("import.meta, export, await");`], + ])("%s doesn't make a file a module", async (_, code) => { + const { problems } = await lint({ "a.js": `${code}\nreturn;\n`, "b.js": "" }, ["a.js"]); + expect(problems).toEqual([]); + }); + + test(`allows an import with "type": "commonjs", like Bun and TypeScript`, async () => { + const files = { + "package.json": `{ "type": "commonjs" }`, + "a.js": `import os from "os";\nexport default os.platform();\n`, + "b.ts": `import os from "os";\nexport default os.platform();\n`, + }; + const { problems, exitCode } = await lint(files, []); + expect(problems).toEqual([]); + expect(exitCode).toBe(0); + }); + + const sloppy: [name: string, code: string, inStrictMode: string][] = [ + ["with", "with (Math) console.log(PI);", "'with' in strict mode"], + ["deleting a variable", "var a = 1;\ndelete a;", "Deleting local variable in strict mode"], + ["a strict-mode reserved word", "var public = 1;\nconsole.log(public);", "The keyword 'public' is reserved"], + ["an octal literal", "console.log(010);", ""], + ["duplicate parameter names", "console.log(function (a, a) {});", ""], + ["await as an identifier", "var await = 1;\nconsole.log(await);", ""], + ["an HTML comment", " the end", ""], + ]; + + test.each(sloppy)("parses a CommonJS file in sloppy mode: %s", async (_, code, inStrictMode) => { + const line = code.split("\n").length + 1; + const files = { "a.js": `${code}\ndebugger;\n` }; + const [commonJs, esm] = await Promise.all([lint(files, []), lint({ ...esmPackage, ...files }, [])]); + expect(commonJs.problems.filter(it => it.includes("Parsing error"))).toEqual([]); + expect(commonJs.reports).toContain(`a.js:${line}:1 error no-debugger`); + expect(esm.problems).toEqual([expect.stringContaining(`Parsing error: ${inStrictMode}`)]); + }); + + test(`"use strict" makes a CommonJS file strict`, async () => { + const { problems } = await lint({ "a.js": `"use strict";\nwith (Math) console.log(PI);\n` }, []); + expect(problems).toEqual(["a.js:2:1 Parsing error: 'with' in strict mode"]); + }); + + test("the file extension overrides package.json", async () => { + const files = { "a.mjs": early, "a.cjs": early }; + const [inCommonJs, inModule] = await Promise.all([ + lint({ ...files, "package.json": `{ "type": "commonjs" }` }, []), + lint({ ...files, ...esmPackage }, []), + ]); + expect(inCommonJs.problems).toEqual([`a.mjs:3:3 ${returnOutside}`]); + expect(inModule.problems).toEqual([`a.mjs:3:3 ${returnOutside}`]); + }); + + describe("sourceType and globalReturn", () => { + const ways = (toml: string, ...flags: string[]): [string, Record, string[]][] => [ + [flags.join(" "), {}, flags.flatMap(it => ["--parser-options", it])], + [toml.replaceAll("\n", " "), { "bunfig.toml": `[lint.parserOptions]\n${toml}\n` }, []], + ]; + + test.each([ + ...ways(`sourceType = "commonjs"`, "sourceType:commonjs"), + ...ways("ecmaFeatures = { globalReturn = true }", "ecmaFeatures:{globalReturn:true}"), + ...ways( + `sourceType = "script"\necmaFeatures = { globalReturn = true }`, + "sourceType:script", + "ecmaFeatures:{globalReturn:true}", + ), + ])(`%s allows a top-level return with "type": "module"`, async (_, files, flags) => { + const { problems, exitCode } = await lint({ ...esmPackage, ...files, "early.js": early }, flags); + expect(problems).toEqual([]); + expect(exitCode).toBe(0); + }); + + test.each([ + ...ways(`sourceType = "module"`, "sourceType:module"), + ...ways(`sourceType = "script"`, "sourceType:script"), + ])("%s rejects a top-level return", async (_, files, flags) => { + const { problems, exitCode } = await lint({ ...files, "early.js": early }, flags); + expect(problems).toEqual([`early.js:3:3 ${returnOutside}`]); + expect(exitCode).toBe(1); + }); + + test("ignores globalReturn in a file with an import, like ESLint", async () => { + const flags = ["--parser-options", "ecmaFeatures:{globalReturn:true}", "a.js"]; + const { problems } = await lint({ "a.js": `import "./b.js";\nreturn;\n`, "b.js": "" }, flags); + expect(problems).toEqual([`a.js:2:1 ${returnOutside}`]); + }); + + test("parses a script in sloppy mode and rejects an import", async () => { + const files = { "a.js": "with (Math) console.log(PI);\ndebugger;\n", "b.js": `import "./a.js";\n` }; + const { problems, reports } = await lint(files, ["--parser-options", "sourceType:script"]); + expect(reports).toContain("a.js:2:1 error no-debugger"); + expect(problems).toContain( + "b.js:1:1 Parsing error: 'import' and 'export' may appear only with 'sourceType: module'", + ); + }); + + test("top-level declarations are global in a script but not in a CommonJS file", async () => { + const files = { "a.js": "var a = 1;\nconsole.log(a);\n" }; + const rule = ["--rule", "no-implicit-globals: error"]; + const [commonJs, script] = await Promise.all([ + lint(files, rule), + lint(files, [...rule, "--parser-options", "sourceType:script"]), + ]); + expect(commonJs.reports).toEqual([]); + expect(script.reports).toEqual(["a.js:1:5 error no-implicit-globals"]); + }); + + test.each(ways(`sourceType = "esm"`, "sourceType:esm"))("%s is an error", async (_, files, flags) => { + const { stderr, exitCode } = await lint({ ...files, "a.js": "" }, flags); + expect(stderr).toContain(`Key "sourceType": Expected "script", "module", or "commonjs".`); + expect(exitCode).toBe(2); + }); + + test("--print-config prints the sourceType", async () => { + const files = { "esm/package.json": esmPackage["package.json"] }; + const sourceType = async (...args: string[]) => + (await lint(files, ["--print-config", ...args])).json.languageOptions.sourceType; + expect( + await Promise.all([ + sourceType("a.js"), + sourceType("a.ts"), + sourceType("a.mjs"), + sourceType("a.cjs"), + sourceType("a.cts"), + sourceType("esm/a.js"), + sourceType("a.js", "--parser-options", "sourceType:script"), + ]), + ).toEqual(["unambiguous", "unambiguous", "module", "commonjs", "commonjs", "module", "script"]); + }); + }); + + describe("strict", () => { + const bunfig = { "bunfig.toml": `[lint.rules]\nstrict = "error"\n` }; + const strict = `"use strict"; +module.exports = (function () { + return this === undefined; +})(); +`; + const unnecessary = "'use strict' is unnecessary inside of modules."; + + test.each([{}, { "package.json": `{ "type": "commonjs" }` }])( + `--fix keeps "use strict" in a CommonJS file: %j`, + async files => { + const { problems, texts } = await lint({ ...bunfig, ...files, "strict.js": strict }, ["--fix"]); + expect(problems).toEqual([]); + expect(texts["strict.js"]).toBe(strict); + }, + ); + + test(`reports a CommonJS file without "use strict"`, async () => { + const { problems } = await lint({ ...bunfig, "a.js": "module.exports = 1;\n" }, []); + expect(problems).toEqual(["a.js:1:1 Use the global form of 'use strict'."]); + }); + + test(`--fix removes "use strict" from a module`, async () => { + const files = { + ...bunfig, + "a.js": `"use strict";\nexport default 1;\n`, + "esm/package.json": esmPackage["package.json"], + }; + const { problems, texts } = await lint({ ...files, "esm/strict.js": strict }, ["--fix"]); + expect(problems).toEqual([]); + expect(texts["a.js"]).not.toContain("use strict"); + expect(texts["esm/strict.js"]).not.toContain("use strict"); + }); + + test.each([ + ["a.js", false], + ["a.jsx", false], + ["a.ts", false], + ["a.tsx", false], + ["a.cjs", false], + ["a.cts", false], + ["a.mjs", true], + ["a.mts", true], + ])("%s without an import or an export is a module: %p", async (name, isModule) => { + const { problems } = await lint({ ...bunfig, [name]: `"use strict";\nconsole.log(1);\n` }, []); + expect(problems).toEqual(isModule ? [`${name}:1:1 ${unnecessary}`] : []); + }); + }); + + test("no-undef allows the CommonJS globals in a CommonJS file", async () => { + const code = "module.exports = exports.a = [require, __filename, __dirname];\n"; + const { reports } = await lint({ "a.js": code, "b.cjs": code }, ["--rule", "no-undef: error"]); + expect(reports).toEqual([]); + }); + + test("no-inner-declarations reports a function inside a block in a CommonJS file", async () => { + const code = "if (process.env.DEBUG) {\n function log() {}\n log();\n}\n"; + const files = { "a.js": code, "b.js": `${code}export {};\n` }; + const { reports } = await lint(files, ["--rule", "no-inner-declarations: error"]); + expect(reports).toEqual(["a.js:2:3 error no-inner-declarations"]); + }); + + test("a JavaScript plugin sees the file's sourceType", async () => { + const files = { + "bunfig.toml": `[lint]\nplugins = ["./plugin.mjs"]\n\n[lint.rules]\n"local/kind" = "error"\n`, + "plugin.mjs": ` + const kind = { + create(context) { + return { + Program(node) { + const scopes = context.sourceCode.scopeManager; + const message = [context.languageOptions.sourceType, node.sourceType, scopes.isGlobalReturn(), scopes.scopes[1].type]; + context.report({ node, message: message.join(" ") }); + }, + }; + }, + }; + export default { meta: { name: "local" }, rules: { kind } };`, + "src/commonjs.js": "module.exports = 1;\n", + "src/module.js": "export default 1;\n", + }; + const { problems } = await lint(files, ["src"]); + expect(problems.sort()).toEqual([ + "src/commonjs.js:1:1 commonjs commonjs true function", + "src/module.js:1:1 module module false module", + ]); + }); + + describe("with an eslint.config.js, ESLint's defaults apply", () => { + const config = (languageOptions = "{}", rules = "{}") => ({ + "package.json": `{ "type": "commonjs" }`, + "eslint.config.mjs": `export default [{ languageOptions: ${languageOptions}, rules: ${rules} }];\n`, + }); + + test(".js and .mjs are modules and .cjs is CommonJS, regardless of package.json", async () => { + const files = { ...config(), "a.js": early, "a.mjs": early, "a.cjs": early }; + const { problems, exitCode } = await lint(files, ["a.js", "a.mjs", "a.cjs"]); + expect(problems.sort()).toEqual([`a.js:3:3 ${returnOutside}`, `a.mjs:3:3 ${returnOutside}`]); + expect(exitCode).toBe(1); + }); + + test.each([ + `{ sourceType: "commonjs" }`, + `{ sourceType: "script", parserOptions: { ecmaFeatures: { globalReturn: true } } }`, + ])("languageOptions: %s allows a top-level return", async languageOptions => { + const { problems, exitCode } = await lint({ ...config(languageOptions), "a.js": early }, ["a.js"]); + expect(problems).toEqual([]); + expect(exitCode).toBe(0); + }); + + test.each([ + `{ sourceType: "script" }`, + `{ parserOptions: { ecmaFeatures: { globalReturn: true } } }`, + // ESLint overwrites it with `languageOptions.sourceType` before it calls espree. + `{ parserOptions: { sourceType: "commonjs" } }`, + ])("languageOptions: %s rejects a top-level return", async languageOptions => { + const { problems } = await lint({ ...config(languageOptions), "a.js": early }, ["a.js"]); + expect(problems).toEqual([`a.js:3:3 ${returnOutside}`]); + }); + + test("no-undef allows require and module only in CommonJS", async () => { + const code = "module.exports = require;\n"; + const rules = `{ "no-undef": "error" }`; + const [byDefault, commonJs] = await Promise.all([ + lint({ ...config("{}", rules), "a.js": code, "a.cjs": code }, ["a.js", "a.cjs"]), + lint({ ...config(`{ sourceType: "commonjs" }`, rules), "a.js": code }, ["a.js"]), + ]); + expect(byDefault.reports).toEqual(["a.js:1:1 error no-undef", "a.js:1:18 error no-undef"]); + expect(commonJs.reports).toEqual([]); + }); + + test(`strict reports "use strict" in a .js file`, async () => { + const files = { ...config("{}", `{ strict: "error" }`), "a.js": `"use strict";\nmodule.exports = 1;\n` }; + const { problems } = await lint(files, ["a.js"]); + expect(problems).toEqual(["a.js:1:1 'use strict' is unnecessary inside of modules."]); + }); + }); + + test("with an .oxlintrc.json, allows a top-level return in a file without imports or exports", async () => { + const { json, exitCode } = await lint({ ...esmPackage, ".oxlintrc.json": "{}", "early.js": early }, ["early.js"]); + expect(json.diagnostics).toEqual([]); + expect(exitCode).toBe(0); + }); +}); + +// Each rule's original linter applies all of these fixes with --fix. +describe.concurrent("--fix preserves behavior and comments", () => { + type Case = { + rule: string; + /** Code that is reported but that --fix doesn't change. */ + kept: string; + /** `kept` after --fix-dangerously. If omitted, --fix-dangerously doesn't change `kept` either. */ + dangerous?: string; + /** Code where the fix is safe, before and after --fix. */ + fixed?: [string, string]; + extension?: string; + }; + const cases: Case[] = [ + { + rule: "unicorn/prefer-single-call", + // The second argument of `Readable#push` is the encoding. `nextId()` depends on the first `push`. + kept: 'import { Readable } from "node:stream";\nexport const readable = new Readable({ read() {} });\nreadable.push("a");\nreadable.push("b");\nexport const rows = [];\nconst nextId = () => rows.length + 1;\nrows.push(nextId());\nrows.push(nextId());\n', + dangerous: + 'import { Readable } from "node:stream";\nexport const readable = new Readable({ read() {} });\nreadable.push("a", "b");\nexport const rows = [];\nconst nextId = () => rows.length + 1;\nrows.push(nextId(), nextId());\n', + fixed: ["export const list = [];\nlist.push(1);\nlist.push(2);\n", "export const list = [];\nlist.push(1, 2);\n"], + }, + { + rule: "unicorn/prefer-string-raw", + kept: 'export const dir = "C:\\\\café\\\\menu";\n', + fixed: ['export const dir = "C:\\\\cafe\\\\menu";\n', "export const dir = String.raw`C:\\cafe\\menu`;\n"], + }, + { + rule: "unicorn/text-encoding-identifier-case", + kept: 'export const isUtf8 = new TextDecoder().encoding === "utf-8";\n', + dangerous: 'export const isUtf8 = new TextDecoder().encoding === "utf8";\n', + fixed: [ + 'import fs from "node:fs";\nexport const text = fs.readFileSync("a.txt", "utf-8");\n', + 'import fs from "node:fs";\nexport const text = fs.readFileSync("a.txt", "utf8");\n', + ], + }, + { + rule: "unicorn/prefer-regexp-test", + // `pattern` can be a string or have the `g` flag, and `database` isn't a regular expression. + kept: "export const has = (text, pattern) => (text.match(pattern) ? 1 : 2);\nexport const ran = (database, sql) => (database.exec(sql) ? 1 : 2);\n", + dangerous: + "export const has = (text, pattern) => (pattern.test(text) ? 1 : 2);\nexport const ran = (database, sql) => (database.test(sql) ? 1 : 2);\n", + fixed: [ + "const pattern = /b/g;\nexport const has = text => (pattern.exec(text) ? 1 : 2);\nexport const starts = text => (`${text}`.match(/^b/) ? 1 : 2);\n", + "const pattern = /b/g;\nexport const has = text => (pattern.test(text) ? 1 : 2);\nexport const starts = text => (/^b/.test(`${text}`) ? 1 : 2);\n", + ], + }, + { + rule: "unicorn/no-useless-undefined", + kept: "export const text = String(undefined);\nfor (const i of [1, 2]) {\n var seen = undefined;\n console.log(seen);\n seen = i;\n}\nexport function f(a = undefined, b) {\n return [a, b];\n}\n", + dangerous: + "export const text = String();\nfor (const i of [1, 2]) {\n var seen;\n console.log(seen);\n seen = i;\n}\nexport function f(a, b) {\n return [a, b];\n}\n", + fixed: [ + "export function g() {\n return undefined;\n}\nexport let x = undefined;\nx = g();\n", + "export function g() {\n return;\n}\nexport let x;\nx = g();\n", + ], + }, + { + rule: "unicorn/no-useless-undefined", + // `g` would return `void`, and `x` would lose its inferred type. + kept: "export function g() {\n return undefined;\n}\nexport let x = undefined;\nx = g();\n", + dangerous: "export function g() {\n return;\n}\nexport let x;\nx = g();\n", + fixed: [ + "export function* h() {\n yield undefined;\n}\nexport const { a = undefined } = { a: 1 };\n", + "export function* h() {\n yield;\n}\nexport const { a } = { a: 1 };\n", + ], + extension: "ts", + }, + { + rule: "unicorn/prefer-spread", + kept: "export const copy = buffer1 => buffer1.slice();\nexport const list = arrayLike => Array.from(arrayLike);\n", + dangerous: "export const copy = buffer1 => [...buffer1];\nexport const list = arrayLike => [...arrayLike];\n", + fixed: [ + "const set = new Set([1, 2]);\nexport const list = Array.from(set);\n", + "const set = new Set([1, 2]);\nexport const list = [...set];\n", + ], + }, + { + rule: "unicorn/prefer-string-starts-ends-with", + kept: "export const isA = x => /^a/.test(x);\n", + dangerous: "export const isA = x => x.startsWith('a');\n", + fixed: ["export const isA = x => /^a/.test(`${x}`);\n", "export const isA = x => `${x}`.startsWith('a');\n"], + }, + { + rule: "unicorn/no-useless-spread", + kept: 'export const ranges = [\n ...["x"],\n // the same after a wildcard\n ...["x.1"],\n];\n', + fixed: ["export const a = [...[1, 2]]; // beside it\n", "export const a = [1, 2]; // beside it\n"], + }, + { + rule: "no-implicit-coercion", + kept: "export const isOn = a =>\n !!(\n a // not b\n );\n", + fixed: ["export const isOn = a => !!a; // beside it\n", "export const isOn = a => Boolean(a); // beside it\n"], + }, + { + rule: "@typescript-eslint/method-signature-style", + kept: "export interface Hot {\n /** Accepts this module. */\n accept(): void;\n /** Accepts a dependency. */\n accept(specifier: string): void;\n}\n", + fixed: [ + "export interface Hot {\n /** Accepts this module. */\n accept(): void;\n}\n", + "export interface Hot {\n /** Accepts this module. */\n accept: () => void;\n}\n", + ], + extension: "ts", + }, + // A type alias can't be declared twice, so a merged interface has no fix. Two properties with the same name parse + // but don't type check, so that fix needs --fix-dangerously. + { + rule: "@typescript-eslint/no-empty-interface", + kept: "export interface Base { a: number }\nexport interface Thing extends Base {}\nexport interface Thing { b: string }\n", + fixed: [ + "export interface Base { a: number }\nexport interface Alone extends Base {}\n", + "export interface Base { a: number }\nexport type Alone = Base\n", + ], + extension: "ts", + }, + { + rule: "@typescript-eslint/method-signature-style", + kept: "export interface Api { get(id: number): string }\nexport interface Api { get(id: string): number }\n", + dangerous: + "export interface Api { get: (id: number) => string }\nexport interface Api { get: (id: string) => number }\n", + fixed: [ + "export interface Api { get(id: number): string }\n", + "export interface Api { get: (id: number) => string }\n", + ], + extension: "ts", + }, + { + rule: "@typescript-eslint/prefer-function-type", + kept: "export interface Handler { (event: string): void }\nexport interface Handler { once?: boolean }\n", + fixed: [ + "export interface Handler { (event: string): void }\n", + "export type Handler = (event: string) => void\n", + ], + extension: "ts", + }, + { + rule: "@typescript-eslint/consistent-indexed-object-style", + kept: "export interface Env { [key: string]: string | undefined }\nexport interface Env { HOME: string }\n", + fixed: ["export interface Env { [key: string]: string }\n", "export type Env = Record;\n"], + extension: "ts", + }, + { + // Other files can merge with an interface in `declare global`. A single top-level interface in a script is fixed. + rule: "@typescript-eslint/prefer-function-type", + kept: "export {};\ndeclare global {\n interface Handler { (event: string): void }\n}\n", + dangerous: "export {};\ndeclare global {\n type Handler = (event: string) => void\n}\n", + fixed: [ + 'interface Handler { (event: string): void }\nconst handler: Handler = () => {};\nhandler("a");\n', + 'type Handler = (event: string) => void\nconst handler: Handler = () => {};\nhandler("a");\n', + ], + extension: "ts", + }, + { + rule: "unicorn/require-module-specifiers", + kept: 'const name = "one";\nconsole.log(name);\nexport {};\n', + dangerous: 'const name = "one";\nconsole.log(name);\n\n', + fixed: ["export const a = 1;\nexport {};\n", "export const a = 1;\n\n"], + extension: "ts", + }, + { + rule: "unicorn/prefer-dom-node-append", + kept: 'export const add = (list, item) => {\n list.appendChild(item);\n};\nexport const li = document.body.appendChild(document.createElement("li"));\n', + dangerous: + 'export const add = (list, item) => {\n list.append(item);\n};\nexport const li = document.body.append(document.createElement("li"));\n', + fixed: [ + 'document.body.appendChild(document.createElement("p"));\n', + 'document.body.append(document.createElement("p"));\n', + ], + }, + { + rule: "unicorn/prefer-dom-node-dataset", + kept: 'new HTMLRewriter().on("div", {\n element(element) {\n element.setAttribute("data-count", "1");\n },\n});\nexport const count = document.body.getAttribute("data-count");\n', + dangerous: + 'new HTMLRewriter().on("div", {\n element(element) {\n element.dataset.count = "1";\n },\n});\nexport const count = document.body.dataset.count;\n', + fixed: ['document.body.setAttribute("data-count", "1");\n', 'document.body.dataset.count = "1";\n'], + }, + { + rule: "unicorn/prefer-query-selector", + kept: 'export const a = document.getElementById("user.name");\nexport const b = document.getElementsByClassName("item");\n', + dangerous: + 'export const a = document.querySelector("#user.name");\nexport const b = document.querySelectorAll(".item");\n', + fixed: [ + 'export const main = document.getElementById("main");\n', + 'export const main = document.querySelector("#main");\n', + ], + }, + { + rule: "unicorn/prefer-dom-node-text-content", + kept: "export const text = node => node.innerText;\n", + dangerous: "export const text = node => node.textContent;\n", + }, + { + rule: "unicorn/prefer-keyboard-event-key", + kept: 'window.addEventListener("keydown", event => {\n if (event.keyCode === 65) save();\n});\n', + dangerous: "window.addEventListener(\"keydown\", event => {\n if (event.key === 'A') save();\n});\n", + fixed: [ + 'window.addEventListener("keydown", event => {\n if (event.keyCode === 27) close();\n});\n', + "window.addEventListener(\"keydown\", event => {\n if (event.key === 'Escape') close();\n});\n", + ], + }, + { + rule: "prefer-destructuring", + kept: "export function f(o: { x?: number }) {\n let x: number | null | undefined = o.x;\n x ??= null;\n return x;\n}\n", + fixed: [ + "export function f(o: { x: number }) {\n const x = o.x;\n return x;\n}\n", + "export function f(o: { x: number }) {\n const {x} = o;\n return x;\n}\n", + ], + extension: "ts", + }, + { + rule: "import/order", + kept: 'import { b } from "./b";\n// @ts-expect-error there are no types for this one\nimport { a } from "a-package";\nconsole.log(a, b);\n', + fixed: [ + 'import { b } from "./b";\nimport { a } from "a-package";\nconsole.log(a, b);\n', + 'import { a } from "a-package";\nimport { b } from "./b";\nconsole.log(a, b);\n', + ], + extension: "ts", + }, + { + rule: "import/order", + // The `@type` comment would apply to `a`. + kept: '/** @type {{ b: number }} */\nconst b = require("./b");\nconst a = require("a-package");\nconsole.log(a, b);\n', + fixed: [ + '// the two letters\nconst b = require("./b");\nconst a = require("a-package");\nconsole.log(a, b);\n', + '// the two letters\nconst a = require("a-package");\nconst b = require("./b");\nconsole.log(a, b);\n', + ], + }, + { + rule: "import/order", + // The doc comment would end up above `console.log`. A license followed by an empty line stays at the top. + kept: 'import { b } from "./b";\n/** The package. */\nimport { a } from "a-package";\nconsole.log(a, b);\n', + fixed: [ + '/**\n * Copyright 2024 Foo\n */\n\nimport { b } from "./b";\nimport { a } from "a-package";\nconsole.log(a, b);\n', + '/**\n * Copyright 2024 Foo\n */\n\nimport { a } from "a-package";\nimport { b } from "./b";\nconsole.log(a, b);\n', + ], + }, + { + rule: "import/order", + // A header doesn't hide the directive below it. + kept: '/** @fileoverview Prints two letters. */\n// @ts-expect-error there are no types for this one\nimport { b } from "./b";\nimport { a } from "a-package";\nconsole.log(a, b);\n', + fixed: [ + '/** @fileoverview Prints two letters. */\nimport { b } from "./b";\nimport { a } from "a-package";\nconsole.log(a, b);\n', + '/** @fileoverview Prints two letters. */\nimport { a } from "a-package";\nimport { b } from "./b";\nconsole.log(a, b);\n', + ], + extension: "ts", + }, + { + rule: "import/order", + // Here the first import is the one that moves. + kept: '/** The local one. */\nimport { b } from "./b";\nimport { a } from "a-package";\nimport { c } from "c-package";\nconsole.log(a, b, c);\n', + fixed: [ + '/** @fileoverview Prints three letters. */\nimport { b } from "./b";\nimport { a } from "a-package";\nimport { c } from "c-package";\nconsole.log(a, b, c);\n', + '/** @fileoverview Prints three letters. */\nimport { a } from "a-package";\nimport { c } from "c-package";\nimport { b } from "./b";\nconsole.log(a, b, c);\n', + ], + }, + { + rule: "import/order", + // `require("./b")` and `[a, b]` would parse as one expression. + kept: 'const b = require("./b")\nconst a = require("a-package")\n;[a, b].forEach(console.log)\n', + fixed: [ + 'const b = require("./b");\nconst a = require("a-package")\n;[a, b].forEach(console.log)\n', + 'const a = require("a-package")\n;\nconst b = require("./b");\n[a, b].forEach(console.log)\n', + ], + }, + ]; + + test.each(cases)("$rule", async ({ rule, kept, dangerous = kept, fixed, extension = "js" }) => { + const [keptName, fixedName] = [`kept.${extension}`, `fixed.${extension}`]; + const [before, after] = fixed ? [{ [fixedName]: fixed[0] }, { [fixedName]: fixed[1] }] : [{}, {}]; + const files = { [keptName]: kept, ...before }; + const [safe, all] = await Promise.all([ + lint(files, ["--fix", "--rule", `${rule}: warn`]), + lint(files, ["--fix-dangerously", "--rule", `${rule}: warn`]), + ]); + const filesWithReports = (result: { reports: string[] }) => [ + ...new Set(result.reports.filter(it => it.endsWith(` ${rule}`)).map(it => it.slice(0, it.indexOf(":")))), + ]; + expect(safe.texts).toEqual({ [keptName]: kept, ...after }); + expect(filesWithReports(safe)).toEqual([keptName]); + expect(all.texts).toEqual({ [keptName]: dangerous, ...after }); + expect(filesWithReports(all)).toEqual(dangerous === kept ? [keptName] : []); + }); + + describe("@typescript-eslint/prefer-function-type", () => { + const rule = "@typescript-eslint/prefer-function-type"; + const use = "export const handler: Handler = () => {};\n"; + const alias = "type Handler = (event: string) => void;"; + /** Code before and after --fix. */ + type Cases = Record; + // typescript-eslint 8.71.1 moves a line comment that follows the signature in front of the declaration, which + // comments the declaration out. It also reverses the comments' order and drops comments before the `{`. + // oxlint 1.87.0 duplicates a comment inside the signature and drops every comment in an interface with type + // parameters or in a type literal. + const comments: Cases = { + "after-the-signature.ts": [ + `interface Handler {\n (event: string): void; // called once\n}\n${use}`, + `// called once\n${alias}\n${use}`, + ], + "above-the-signature.ts": [ + `interface Handler {\n // called once\n (event: string): void;\n}\n${use}`, + `// called once\n${alias}\n${use}`, + ], + "below-the-signature.ts": [ + `interface Handler {\n (event: string): void;\n // called once\n}\n${use}`, + `// called once\n${alias}\n${use}`, + ], + "after-the-opening-brace.ts": [ + `interface Handler { // called once\n (event: string): void;\n}\n${use}`, + `// called once\n${alias}\n${use}`, + ], + "after-the-closing-brace.ts": [ + `interface Handler {\n (event: string): void;\n} // called once\n${use}`, + `${alias} // called once\n${use}`, + ], + "code-after-the-closing-brace.ts": [ + `interface Handler {\n (event: string): void; // called once\n} ${use}`, + `// called once\n${alias} ${use}`, + ], + "everywhere.ts": [ + `interface /* one */ Handler /* two */ { // three\n // four\n /* five */ (event: string /* six */): void /* seven */; // eight\n /** nine */\n} // ten\n${use}`, + `/* one */\n/* two */\n// three\n// four\n/* five */ // eight\n/** nine */\ntype Handler = (event: string /* six */) => void /* seven */; // ten\n${use}`, + ], + "block-comments-on-the-line.ts": [ + `interface Handler {\n /* called */ (event: string): void; /* once */\n}\n${use}`, + `/* called */ /* once */ ${alias}\n${use}`, + ], + "jsdoc.ts": [ + `interface Handler {\n /**\n * Called once.\n */\n (event: string): void;\n}\n${use}`, + `/**\n * Called once.\n */\n${alias}\n${use}`, + ], + "in-the-signature.ts": [ + `interface Handler {\n (\n event: string, // the name\n ): void;\n}\n${use}`, + `type Handler = (\n event: string, // the name\n ) => void;\n${use}`, + ], + "comma.ts": [ + `interface Handler {\n (event: string): void, // called once\n}\n${use}`, + `// called once\n${alias}\n${use}`, + ], + "crlf.ts": [ + `interface Handler {\r\n (event: string): void; // called once\r\n}\r\n${use}`, + `// called once\n${alias}\r\n${use}`, + ], + "export.ts": [ + "export interface Handler {\n /* called */ (event: string): void; // once\n}\n", + `/* called */\n// once\nexport ${alias}\n`, + ], + "export-declare.ts": [ + "export declare interface Handler {\n (event: string): void; // called once\n}\n", + `// called once\nexport ${alias}\n`, + ], + "declare.ts": [ + `declare interface Handler {\n (event: string): void; // called once\n}\n${use}`, + `// called once\n${alias}\n${use}`, + ], + "type-parameters.ts": [ + "export interface Handler /* generic */ {\n (event: T): void; // called once\n}\n", + "/* generic */\n// called once\nexport type Handler = (event: T) => void;\n", + ], + "construct-signature.ts": [ + "export interface Maker {\n new (name: string): object; // called once\n}\n", + "// called once\nexport type Maker = new (name: string) => object;\n", + ], + "directive.ts": [ + "export interface Handler {\n // @ts-expect-error Missing is not declared\n (event: Missing): void;\n}\n", + "// @ts-expect-error Missing is not declared\nexport type Handler = (event: Missing) => void;\n", + ], + "type-literal.ts": [ + "export type Handler = {\n (event: string): void; // called once\n};\n", + "export type Handler = // called once\n(event: string) => void;\n", + ], + "type-literal-above.ts": [ + "export type Handler = {\n // called once\n (event: string): void;\n};\n", + "export type Handler = // called once\n(event: string) => void;\n", + ], + "type-literal-comma.ts": [ + "export type Handler = { (event: string): void, };\n", + "export type Handler = (event: string) => void;\n", + ], + "union.ts": [ + "export type Handler = {\n (event: string): void; // called once\n} | undefined;\n", + "export type Handler = // called once\n((event: string) => void) | undefined;\n", + ], + "union-on-one-line.ts": [ + "export type Handler = { /* called */ (event: string): void /* once */ } | undefined;\n", + "export type Handler = /* called */ /* once */ ((event: string) => void) | undefined;\n", + ], + "parameter.ts": [ + 'export function call(handler: {\n (event: string): void; // called once\n}) {\n handler("a");\n}\n', + 'export function call(handler: // called once\n(event: string) => void) {\n handler("a");\n}\n', + ], + }; + // oxlint doesn't report these. typescript-eslint only adds parentheses for the array. Without them, + // `() => void["length"]` and `() => void extends object ? 1 : 2` are function types. + const parentheses: Cases = { + "array.ts": [ + "export type Handlers = {\n (event: string): void; // called once\n}[];\n", + "export type Handlers = // called once\n((event: string) => void)[];\n", + ], + "keyof.ts": ["export type Keys = keyof { (): void };\n", "export type Keys = keyof (() => void);\n"], + "indexed-access.ts": [ + 'export type Length = { (): void }["length"];\n', + 'export type Length = (() => void)["length"];\n', + ], + "conditional.ts": [ + "export type One = { (): void } extends object ? 1 : 2;\nexport type IsCallable = T extends { (): void } ? { (): true } : { (): false };\n", + "export type One = (() => void) extends object ? 1 : 2;\nexport type IsCallable = T extends (() => void) ? () => true : () => false;\n", + ], + "tuple.ts": [ + "export type Optional = [{ (): void }?];\nexport type Named = [handler?: { (): void }];\n", + "export type Optional = [(() => void)?];\nexport type Named = [handler?: () => void];\n", + ], + "type-argument.ts": [ + "export const handlers: Array<{ (): void }> = [];\n", + "export const handlers: Array<() => void> = [];\n", + ], + }; + // `export default type` doesn't exist. In the other two files, a block comment would end up between the directive + // and its line. + const kept = { + "export-default.ts": "export default interface Handler {\n (event: string): void; // called once\n}\n", + "directive-above.ts": + "// @ts-expect-error Missing is not declared\nexport interface Handler {\n /* called once */\n (event: T): void;\n}\n", + "directive-and-a-comment-below.ts": + "export interface Handler {\n // @ts-expect-error Missing is not declared\n (event: Missing): void;\n /* called once */\n}\n", + }; + const inNamespace: Cases = { + "namespace.ts": [ + `export namespace Events {\n interface Handler {\n (event: string): void; // called once\n }\n ${use}}\n`, + `export namespace Events {\n // called once\n${alias}\n ${use}}\n`, + ], + "exported-from-namespace.ts": [ + "export namespace Events {\n export interface Handler {\n (event: string): void; // called once\n }\n}\n", + `export namespace Events {\n // called once\nexport ${alias}\n}\n`, + ], + }; + const pick = (cases: Cases, index: 0 | 1) => + Object.fromEntries(Object.entries(cases).map(([name, texts]) => [name, texts[index]])); + const filesWithReports = (result: { reports: string[] }) => + [...new Set(result.reports.filter(it => it.endsWith(` ${rule}`)).map(it => it.slice(0, it.indexOf(":"))))].sort(); + const turnedOn = ["--rule", `${rule}: warn`]; + const oxlintrc = '{ "plugins": ["typescript"], "rules": { "typescript/prefer-function-type": "warn" } }\n'; + + test.each([ + ["no config", {}, turnedOn, { ...comments, ...parentheses }], + [".oxlintrc.json", { ".oxlintrc.json": oxlintrc }, [], comments], + ])("--fix keeps every comment exactly once and never comments out code: %s", async (_, config, args, cases) => { + const expected = { ...config, ...pick(cases, 1), ...kept }; + const first = await lint({ ...config, ...pick(cases, 0), ...kept }, ["--fix", ...args]); + expect(first.texts).toEqual(expected); + const second = await lint(first.texts, ["--fix", ...args]); + expect(second.texts).toEqual(expected); + }); + + test("still reports code it can't fix", async () => { + const result = await lint({ ...pick(comments, 0), ...kept }, ["--fix-dangerously", ...turnedOn]); + expect(result.texts).toEqual({ ...pick(comments, 1), ...kept }); + expect(filesWithReports(result)).toEqual(Object.keys(kept).sort()); + }); + + test("only --fix-dangerously fixes an interface in a namespace", async () => { + const [safe, first] = await Promise.all([ + lint(pick(inNamespace, 0), ["--fix", ...turnedOn]), + lint(pick(inNamespace, 0), ["--fix-dangerously", ...turnedOn]), + ]); + expect(safe.texts).toEqual(pick(inNamespace, 0)); + expect(filesWithReports(safe)).toEqual(Object.keys(inNamespace).sort()); + expect(first.texts).toEqual(pick(inNamespace, 1)); + const second = await lint(first.texts, ["--fix-dangerously", ...turnedOn]); + expect(second.texts).toEqual(pick(inNamespace, 1)); + expect(filesWithReports(second)).toEqual([]); + }); + }); + + test("--fix inserts an import below the hashbang, directives and file-level comments", async () => { + const body = 'test("a", () => {\n expect(1).toBe(1);\n});\n'; + const heads = ["// @ts-nocheck\n", '/// \n', '"use strict";\n', "#!/usr/bin/env bun\n"]; + const files = Object.fromEntries(heads.map((head, i) => [`${i}.test.ts`, head + body])); + const [vitest, jest, first] = await Promise.all([ + lint(files, ["--fix", "--rule", "vitest/prefer-importing-vitest-globals: warn"]), + lint(files, ["--fix", "--rule", "jest/prefer-importing-jest-globals: warn"]), + lint({ "a.ts": '"use client";\nconst started = 1;\nimport { b } from "./b";\nconsole.log(started, b);\n' }, [ + "--fix", + "--rule", + "import/first: warn", + ]), + ]); + for (const [i, head] of heads.entries()) { + expect(vitest.texts[`${i}.test.ts`]).toBe(`${head}import { expect, test } from 'vitest';\n${body}`); + expect(jest.texts[`${i}.test.ts`]).toStartWith(head); + expect(jest.texts[`${i}.test.ts`]).toContain("@jest/globals"); + } + expect(first.texts["a.ts"]).toBe( + '"use client";\nimport { b } from "./b";\nconst started = 1;\nconsole.log(started, b);\n', + ); + }); + + describe("an import that becomes the first statement", () => { + type Cases = Record; + const license = "// Copyright 2026 Someone\n// Use of this file is governed by the MIT license.\n"; + const moduleDoc = "/**\n * Counts.\n * @module\n */\n\n"; + const suppressed = "// @ts-expect-error a string is no number\n"; + const filesWithReports = (result: { reports: string[] }, rule: string) => + [...new Set(result.reports.filter(it => it.endsWith(` ${rule}`)).map(it => it.slice(0, it.indexOf(":"))))].sort(); + + /** Expects `--fix` to turn each `before` into its `after` and report nothing, and a second run to be a no-op. */ + async function expectFixed(rule: string, cases: Cases) { + const pick = (index: 0 | 1) => Object.fromEntries(Object.entries(cases).map(([name, it]) => [name, it[index]])); + const args = ["--fix", "--rule", `${rule}: warn`]; + const first = await lint(pick(0), args); + expect(first.texts).toEqual(pick(1)); + expect(filesWithReports(first, rule)).toEqual([]); + const second = await lint(first.texts, args); + expect(second.texts).toEqual(pick(1)); + } + + /** Expects `--fix` to leave the files unchanged without attempting a broken fix, and to still report each file. */ + async function expectKept(rule: string, files: Record) { + const result = await lint(files, ["--fix", "--rule", `${rule}: warn`]); + expect(result.texts).toEqual(files); + expect(result.stderr).not.toContain("not applied"); + expect(filesWithReports(result, rule)).toEqual(Object.keys(files).sort()); + } + + // Each entry is the header that must stay first, then the first statement with its own comments. + const heads: Record = { + "directive.ts": ["", `${suppressed}console.log(Math.abs("1"));\n`], + "doc.ts": ["", "/** Adds one. */\nfunction increment(n: number) {\n return n + 1;\n}\n"], + "use-client.ts": ['"use client";\n', `${suppressed}console.log(Math.abs("1"));\n`], + "use-strict.ts": ['"use strict";\n', "/** Starts at one. */\nconst count = 1;\n"], + "comment-beside-use-client.ts": ['"use client"; // for the router\n', "// starts at one\nconst count = 1;\n"], + "nocheck.ts": ["// @ts-nocheck\n", "// starts at one\nconst count = 1;\n"], + "reference.ts": ['/// \n', "// starts at one\nconst count = 1;\n"], + "hashbang.ts": ["#!/usr/bin/env bun\n", "// starts at one\nconst count = 1;\n"], + "license.ts": [`${license}\n`, "// starts at one\nconst count = 1;\n"], + "license-without-an-empty-line.ts": [license, "const count = 1;\n"], + "license-in-two-paragraphs.ts": [ + `${license}\n// IT IS PROVIDED "AS IS".\n\n`, + "// starts at one\nconst count = 1;\n", + ], + "license-and-directive.ts": [license, `${suppressed}console.log(Math.abs("1"));\n`], + "directive-above-license.ts": ["", `${suppressed}// Copyright 2026 Someone\nconsole.log(Math.abs("1"));\n`], + "module-doc.ts": [moduleDoc, "/** Starts at one. */\nconst count = 1;\n"], + "jest-environment.ts": ["/**\n * @jest-environment jsdom\n */\n", "// starts at one\nconst count = 1;\n"], + "doc-above-nocheck.ts": ["/** Counts. */\n// @ts-nocheck\n", "// starts at one\nconst count = 1;\n"], + "doc-above-reference.ts": ['/** Counts. */\n/// \n', "const count = 1;\n"], + "doc-above-license.ts": [`/** Counts. */\n${license}\n`, "/** Starts at one. */\nconst count = 1;\n"], + "byte-order-mark.ts": ["\ufeff", "// starts at one\nconst count = 1;\n"], + // An empty line separates file-level comments from the first statement's comments. + "header.ts": ["// Counts things.\n// Nothing else.\n\n", "const count = 1;\n"], + "header-in-a-block.ts": ["/**\n * Counts things.\n */\n\n", "// starts at one\nconst count = 1;\n"], + "header-and-doc.ts": ["// Counts things.\n\n", "/** Starts at one. */\nconst count = 1;\n"], + "header-in-two-parts.ts": ["// Counts things.\n\n// Nothing else.\n\n", "// starts at one\nconst count = 1;\n"], + "header-without-an-empty-line.ts": ["", "// Counts things.\n// Nothing else.\nconst count = 1;\n"], + "header-below-use-strict.ts": ['"use strict";\n// Counts things.\n\n', "// starts at one\nconst count = 1;\n"], + "header-below-hashbang.ts": ["#!/usr/bin/env bun\n// Counts things.\n\n", "// starts at one\nconst count = 1;\n"], + "header-and-directive.ts": ["// Counts things.\n\n", `${suppressed}console.log(Math.abs("1"));\n`], + "disable-in-the-middle.ts": [ + "// Counts things.\n/* eslint-disable @typescript-eslint/no-unused-vars */\n", + "// starts at one\nconst count = 1;\n", + ], + // A next-line directive applies across an empty line, so it and the comments below it stay with the statement. + "directive-and-empty-line.ts": ["", `${suppressed}\nconsole.log(Math.abs("1"));\n`], + "directive-above-header.ts": ["", `${suppressed}// Counts things.\n\nconsole.log(Math.abs("1"));\n`], + "triple-slash-directive.ts": ["", `/${suppressed}\nconsole.log(Math.abs("1"));\n`], + "directive-above-reference.ts": [ + '// deno-lint-ignore triple-slash-reference\n/// \n', + "const count = 1;\n", + ], + "ignore-above-license.ts": ["", `// prettier-ignore\n${license}const count = 1;\n`], + "directive-for-the-file.ts": [license, '// @ts-ignore-file\nconsole.log(Math.abs("1"));\n'], + "directive-with-a-suffix.ts": [license, '// @ts-expect-error-next-line\nconsole.log(Math.abs("1"));\n'], + "coverage.ts": ["", "/* v8 ignore next -- @preserve */\n\nconst count = 1;\n"], + "no-side-effects.ts": ["", "/* @__NO_SIDE_EFFECTS__ */\n\nfunction one() {\n return 1;\n}\n"], + "deno.ts": ["// deno-lint-ignore-file no-console\n", "// deno-lint-ignore no-unused-vars\n\nconst count = 1;\n"], + }; + // Repeat a few with CRLF line endings. + for (const name of ["directive.ts", "use-strict.ts", "license.ts", "header.ts", "header-in-two-parts.ts"]) { + heads[`crlf-${name}`] = heads[name]; + } + const withLineBreaksOf = (name: string, text: string) => + name.startsWith("crlf-") ? text.replaceAll("\n", "\r\n") : text; + + test("import/first: moves the import below the file header, above the first statement's comments", async () => { + const a = 'import { a } from "./a";\n'; + const cases = Object.entries(heads).map(([name, [head, first]]) => [ + name, + [`${head}${first}${a}console.log(a);\n`, `${head}${a}${first}console.log(a);\n`].map(it => + withLineBreaksOf(name, it), + ), + ]); + await expectFixed("import/first", { + ...Object.fromEntries(cases), + "directive-beside-use-client.ts": [ + `"use client"; ${suppressed}console.log(Math.abs("1"));\n${a}console.log(a);\n`, + `"use client"; ${a}${suppressed}console.log(Math.abs("1"));\nconsole.log(a);\n`, + ], + "indented.ts": [ + ` // starts at one\n const count = 1;\n ${a} console.log(a, count);\n`, + ` ${a} // starts at one\n const count = 1;\n console.log(a, count);\n`, + ], + }); + }); + + test.each([ + ["vitest/prefer-importing-vitest-globals", "import { test } from 'vitest';\n"], + ["jest/prefer-importing-jest-globals", "const { test } = require('@jest/globals');\n"], + ])("%s: adds the import below the file header, above the first statement's comments", async (rule, statement) => { + const cases = Object.entries(heads).map(([name, [head, first]]) => [ + name.replace(".ts", ".test.ts"), + [`${head}${first}test("a", () => {});\n`, `${head}${statement}${first}test("a", () => {});\n`].map(it => + withLineBreaksOf(name, it), + ), + ]); + await expectFixed(rule, Object.fromEntries(cases)); + }); + + test.each([ + ["vitest/prefer-importing-vitest-globals", "import { test } from 'vitest';\n"], + ["jest/prefer-importing-jest-globals", "import { test } from '@jest/globals';\n"], + ])("%s: adds the import in a file that starts with comments and imports", async (rule, statement) => { + const rest = 'import { a } from "./a";\ntest("a", () => a);\n'; + await expectFixed(rule, { + "header.test.ts": [`// Tests a.\n\n${rest}`, `// Tests a.\n\n${statement}${rest}`], + "header-without-an-empty-line.test.ts": [`// Tests a.\n${rest}`, `${statement}// Tests a.\n${rest}`], + }); + }); + + test("import/first: keeps a trailing comment with its statement", async () => { + const [a, b] = ['import { a } from "./a";', 'import { b } from "./b";']; + await expectFixed("import/first", { + "the-statement-before.ts": [ + `const count = 1; // starts at one\n${a}\nconsole.log(a, count);\n`, + `${a}\nconst count = 1; // starts at one\nconsole.log(a, count);\n`, + ], + "the-import.ts": [ + `const count = 1;\n${a} // the first letter\nconsole.log(a, count);\n`, + `${a} // the first letter\nconst count = 1;\nconsole.log(a, count);\n`, + ], + "two-imports.ts": [ + `const count = 1;\n${a} // the first letter\n${b} // the second letter\nconsole.log(a, b, count);\n`, + `${a} // the first letter\n${b} // the second letter\nconst count = 1;\nconsole.log(a, b, count);\n`, + ], + "the-last-import-on-top.ts": [ + `${b} // the second letter\nconst count = 1;\n${a}\nconsole.log(a, b, count);\n`, + `${b} // the second letter\n${a}\nconst count = 1;\nconsole.log(a, b, count);\n`, + ], + "an-import-behind-a-statement.ts": [ + `const count = 1;\n${a} // the first letter\nconsole.log(count); ${b}\nconsole.log(a, b);\n`, + `${a} // the first letter\n${b}\nconst count = 1;\nconsole.log(count);\nconsole.log(a, b);\n`, + ], + // These two comments apply to the next line. + "directive-for-the-import.ts": [ + 'const count = 1; // @ts-expect-error there is no c\nimport { c } from "./a";\nconsole.log(c, count);\n', + '// @ts-expect-error there is no c\nimport { c } from "./a";\nconst count = 1;\nconsole.log(c, count);\n', + ], + "directive-beside-the-import.ts": [ + `const count = 1;\n${a} ${suppressed}console.log(Math.abs("1"));\nconsole.log(a, count);\n`, + `${a}\nconst count = 1; ${suppressed}console.log(Math.abs("1"));\nconsole.log(a, count);\n`, + ], + }); + // The second `run()` would end up inside the comment. + await expectKept("import/first", { "code-behind-the-import.js": 'run(); // once\nimport "./side"; run();\n' }); + }); + + describe("import/first: in code without semicolons", () => { + // Each of these continues the previous line's statement unless that line ends with a `;`. + const starts = { + bracket: "[1, 2].forEach(run)", + parenthesis: "(function () {})()", + template: "`a`.trim()", + plus: "+run()", + minus: "-run()", + regex: "/a/.test(run())", + jsx: "
    ", + }; + const each = (make: (name: string, start: string) => [string, T][]) => + Object.fromEntries(Object.entries(starts).flatMap(([name, start]) => make(name, start))); + + test("keeps a leading `;` on its line", async () => { + await expectFixed("import/first", { + ...each<[string, string]>((name, start) => [ + [`${name}.js`, [`run()\nimport "./side"\n;${start}\n`, `import "./side"\nrun()\n;${start}\n`]], + [`closed-${name}.js`, [`run();\nimport "./side"\n${start}\n`, `import "./side"\nrun();\n${start}\n`]], + ]), + "two-imports.js": [ + 'run()\nimport "./side"\nimport "./other"\n;[1, 2].forEach(run)\n', + 'import "./side"\nimport "./other"\nrun()\n;[1, 2].forEach(run)\n', + ], + "comment-beside-the-import.js": [ + 'run()\nimport "./side" // first\n;[1, 2].forEach(run)\n', + 'import "./side" // first\nrun()\n;[1, 2].forEach(run)\n', + ], + "below-the-last-import-on-top.js": [ + 'import "./first"\n;[1, 2].forEach(run)\nimport "./side"\n', + 'import "./first"\nimport "./side"\n;[1, 2].forEach(run)\n', + ], + }); + }); + + test("moves an import without a `;` onto its own line", async () => { + await expectFixed("import/first", { + "behind-a-statement.js": ['run(); import "./side"\nrun()\n', 'import "./side"\nrun();\nrun()\n'], + "behind-a-statement-with-an-import-on-top.js": [ + 'import "./first"\nrun(); import "./side"\nrun()\n', + 'import "./first"\nimport "./side"\nrun();\nrun()\n', + ], + "behind-a-block.js": [ + 'if (run()) {} import "./side"\n[1, 2].forEach(run)\n', + 'import "./side"\nif (run()) {}\n[1, 2].forEach(run)\n', + ], + }); + }); + + test("fixes the import when the next line can't continue the previous statement", async () => { + await expectFixed("import/first", { + "word.js": ['run()\nimport "./side"\nrun()\n', 'import "./side"\nrun()\nrun()\n'], + "increment.js": ['let n = run()\nimport "./side"\n++n\n', 'import "./side"\nlet n = run()\n++n\n'], + "function.js": [ + 'function f() {}\nimport "./side"\n[1, 2].forEach(f)\n', + 'import "./side"\nfunction f() {}\n[1, 2].forEach(f)\n', + ], + "same-line.js": ['run();\nimport "./side"; run()\n', 'import "./side";\nrun(); run()\n'], + "parenthesis-after-increment.js": [ + 'let n = 1\nn++\nimport "./side"\n(run)(n)\n', + 'import "./side"\nlet n = 1\nn++\n(run)(n)\n', + ], + "parenthesis-after-type.ts": [ + 'const n = run() as number\nimport "./side"\n(run)(n)\n', + 'import "./side"\nconst n = run() as number\n(run)(n)\n', + ], + }); + }); + + test("doesn't fix the import when two statements would merge", async () => { + await expectKept("import/first", { + ...each((name, start) => [ + [`${name}.js`, `run()\nimport "./side"\n${start}\n`], + [`semicolon-${name}.js`, `run()\nimport "./side";\n${start}\n`], + ]), + "object.js": 'const o = {}\nimport "./side"\n[1, 2].forEach(run)\n', + "two-imports.js": 'run()\nimport "./side"\nimport "./other"\n[1, 2].forEach(run)\n', + "same-line.js": 'run()\nimport "./side"; run()\n', + "same-line-parenthesis.js": 'run()\nimport "./side"; (run)()\n', + "plus-after-increment.js": 'let n = 1\nn++\nimport "./side"\n+run(n)\n', + "minus-after-type.ts": 'const n = run() as number\nimport "./side"\n-run(n)\n', + "minus-after-type-in-braces.ts": 'const o = {} satisfies { a?: 1 }\nimport "./side"\n-run(o)\n', + }); + }); + }); + + test("import/first: keeps an import below an `export .. from` so the modules run in the same order", async () => { + await expectKept("import/first", { + "all.js": 'export * from "./first";\nimport "./side";\n', + "names.js": 'export { a } from "./first";\nimport "./side";\n', + }); + await expectFixed("import/first", { + "own-names.js": [ + 'const a = 1;\nexport { a };\nimport "./side";\n', + 'import "./side";\nconst a = 1;\nexport { a };\n', + ], + }); + }); + }); + + test("with --type-aware, fixes still type check and keep string coercions", async () => { + const files = { + "tsconfig.json": '{ "compilerOptions": { "strict": true, "types": [], "lib": ["esnext"] }, "include": ["*.ts"] }', + // `readonly #limit = 0` has type `0`, so the constructor couldn't assign a number to it. + "readonly.ts": + "export class Pool {\n #limit = 0;\n constructor(limit: number) {\n this.#limit = limit;\n }\n get limit() {\n return this.#limit;\n }\n}\n", + // An untyped caller can pass a number. + "coerce.ts": 'export function time(label = "default") {\n label = `${label}`;\n return label;\n}\n', + "plain.ts": "declare const name: string;\nexport const text = `${name}`;\n", + }; + const rules = ["prefer-readonly", "no-unnecessary-template-expression"].flatMap(rule => [ + "--rule", + `@typescript-eslint/${rule}: warn`, + ]); + const [safe, all] = await Promise.all([ + lint(files, ["--fix", "--type-aware", ...rules]), + lint(files, ["--fix-dangerously", "--type-aware", ...rules]), + ]); + expect(safe.texts["readonly.ts"]).toBe(files["readonly.ts"].replace("#limit = 0", "readonly #limit: number = 0")); + expect(safe.texts["coerce.ts"]).toBe(files["coerce.ts"]); + expect(safe.reports.filter(it => it.endsWith("no-unnecessary-template-expression"))).toEqual([ + expect.stringMatching(/^coerce\.ts:2:/), + ]); + expect(safe.texts["plain.ts"]).toBe("declare const name: string;\nexport const text = name;\n"); + expect(all.texts["coerce.ts"]).toBe(files["coerce.ts"].replace("`${label}`", "label")); + }); +}); diff --git a/test/cli/lint/doctor.test.ts b/test/cli/lint/doctor.test.ts index 2382877a1de7..70d143123b72 100644 --- a/test/cli/lint/doctor.test.ts +++ b/test/cli/lint/doctor.test.ts @@ -99,7 +99,7 @@ const flat = { describe.concurrent("bun lint --doctor", () => { test( - "with an eslint.config.js", + "prints a report for a project with an eslint.config.js", async () => { const { stdout, stderr, exitCode, isUntouched } = await doctor(flat); expect(stderr).toBe(""); @@ -189,7 +189,7 @@ Not checked: other tools' configs, CI files, Git hooks ); test( - "with an .oxlintrc.json", + "prints a report for a project with an .oxlintrc.json", async () => { const { stdout, stderr, exitCode, isUntouched } = await doctor({ ...plugin("eslint-plugin-first", ["a", "b"]), @@ -274,7 +274,7 @@ Not checked: other tools' configs, CI files, Git hooks }); test( - "with an .eslintrc.json", + "prints a report for a project with an .eslintrc.json", async () => { const { stdout, exitCode } = await doctor( { @@ -649,7 +649,7 @@ Also packages/a/eslint.config.js expect(exitCode).toBe(0); }); - test("without a config file", async () => { + test("without a config file, lists Bun's default rules and suggests --init", async () => { const { stdout, stderr, exitCode, isUntouched } = await doctor({ "package.json": dependencies("typescript"), "a.ts": "var a = 1;\n", @@ -671,7 +671,7 @@ Also packages/a/eslint.config.js { "eslint.config.js": "export default [{ rules: {} }];\n" }, "Using ../eslint.config.js (ESLint flat config)\nUsing ../bunfig.toml ([lint])\n\n", ], - ])("says which bunfig.toml it reads, and not to add a section: %j", async (config, start) => { + ])("prints which bunfig.toml it reads and doesn't suggest --init: %j", async (config, start) => { using dir = tempDir("bun-lint-doctor", { ...config, "package.json": `{ "type": "module" }`, diff --git a/test/cli/lint/explain.test.ts b/test/cli/lint/explain.test.ts index cf4adf0c633d..bd78c171ff9e 100644 --- a/test/cli/lint/explain.test.ts +++ b/test/cli/lint/explain.test.ts @@ -137,13 +137,13 @@ describe.concurrent("--rules -f json", () => { }); test("is the same no matter what config the project has", async () => { - const [alone, eslint, oxlint] = await Promise.all([ + const [withoutConfig, eslint, oxlint] = await Promise.all([ lint({}, ["--rules", "-f", "json"]), lint({ "eslint.config.mjs": "export default [];" }, ["--rules", "-f", "json"]), lint({ ".oxlintrc.json": "{}", "bunfig.toml": '[lint.rules]\n"no-var" = "off"\n' }, ["--rules", "-f", "json"]), ]); - expect(eslint.stdout).toBe(alone.stdout); - expect(oxlint.stdout).toBe(alone.stdout); + expect(eslint.stdout).toBe(withoutConfig.stdout); + expect(oxlint.stdout).toBe(withoutConfig.stdout); }); test("no ID or alias refers to more than one rule", async () => { @@ -184,9 +184,9 @@ describe.concurrent("--rules -f json", () => { test("description matches the docs page's description", async () => { const rules = new Map((await listRules()).map(it => [it.docs_url.slice(base.length), it])); - const written = pages().map(page => ({ page, description: frontmatter(page).description })); - expect(written.length).toBeGreaterThan(1000); - expect(written.map(({ page }) => ({ page, description: rules.get(page)?.description }))).toEqual(written); + const documented = pages().map(page => ({ page, description: frontmatter(page).description })); + expect(documented.length).toBeGreaterThan(1000); + expect(documented.map(({ page }) => ({ page, description: rules.get(page)?.description }))).toEqual(documented); }); test("on_by_default matches --print-config in a project without a config", async () => { @@ -244,6 +244,10 @@ describe.concurrent("--rules", () => { .slice(9 + id.length) .trim(); expect(described("no-var")).toBe(frontmatter("eslint/no-var").description.replaceAll("`", "")); + // bunfig.toml can't turn these on. + const note = "These need an ESLint config that says which files are in the language."; + const noted = lines.flatMap((line, i) => (line === note ? [lines[i - 1].split(" ")[0]] : [])); + expect(noted).toEqual(["json", "markdown"]); expect(lines.slice(-3)).toEqual([ `${rules.length} rules. The ones marked error or warn are on by default.`, "Run bun lint --explain to read about a rule.", @@ -340,20 +344,23 @@ describe.concurrent("--explain", () => { test("reads no config and lints nothing", async () => { const files = { "eslint.config.js": "throw new Error('read');", ".oxlintrc.json": "{", "a.js": "debugger;" }; - const [here, alone] = await Promise.all([lint(files, ["--explain", "no-var"]), lint({}, ["--explain", "no-var"])]); - expect(here).toEqual(alone); + const [here, inEmptyDirectory] = await Promise.all([ + lint(files, ["--explain", "no-var"]), + lint({}, ["--explain", "no-var"]), + ]); + expect(here).toEqual(inEmptyDirectory); expect(here.exitCode).toBe(0); }); test("works even if package.json has a `lint` script", async () => { const files = { "package.json": JSON.stringify({ scripts: { lint: "echo the script" } }) }; - const [one, other, alone] = await Promise.all([ + const [one, other, inEmptyDirectory] = await Promise.all([ lint(files, ["--explain", "no-var"]), lint(files, ["--explain=no-var"]), lint({}, ["--explain", "no-var"]), ]); - expect(one).toEqual(alone); - expect(other).toEqual(alone); + expect(one).toEqual(inEmptyDirectory); + expect(other).toEqual(inEmptyDirectory); }); test("wraps at the terminal width, and uses colors when they're on", async () => { diff --git a/test/cli/lint/git.test.ts b/test/cli/lint/git.test.ts index 70ec03809776..eb0e7fe36196 100644 --- a/test/cli/lint/git.test.ts +++ b/test/cli/lint/git.test.ts @@ -187,9 +187,9 @@ describe.concurrent.each(commands)("bun %s", command => { using repo = await repository({ "a.js": tidy }); const { root } = repo; write(root, "a.js", before); - for (const written of ["nothing", "--output=written.txt", "-O", "HEAD..HEAD", "HEAD HEAD", "HEAD:a.js"]) { - const { stdout, stderr, exitCode } = await bun(root, [command, `--changed=${written}`]); - expect(stderr).toContain(`"${written}" is not a branch, tag or commit in this repository`); + for (const ref of ["nothing", "--output=written.txt", "-O", "HEAD..HEAD", "HEAD HEAD", "HEAD:a.js"]) { + const { stdout, stderr, exitCode } = await bun(root, [command, `--changed=${ref}`]); + expect(stderr).toContain(`"${ref}" is not a branch, tag or commit in this repository`); expect({ stdout, exitCode }).toEqual({ stdout: "", exitCode: 2 }); } expect(existsSync(join(root, "written.txt"))).toBe(false); @@ -236,7 +236,7 @@ describe.concurrent.each(commands)("bun %s", command => { stderr: `No changed files to ${verb[command]}\n`, exitCode: 0, }); - // A file is staged, but the argument names a different one. + // A file is staged, but the argument is a different file. write(root, "b.js", before); await git(root, "add", "b.js"); const { stderr, exitCode } = await bun(root, [command, "--staged", "a.js"]); @@ -409,6 +409,41 @@ describe.concurrent.each(commands)("bun %s", command => { expect(three.exitCode).toBe(1); }); + test("reads the staged version of a file with both staged and unstaged changes", async () => { + const odd = isWindows ? "ünï côde.js" : 'ünï "cô\n\tde".js'; + using repo = await repository({ "good.js": tidy, "sub/bad.js": tidy, [odd]: tidy }); + const { root } = repo; + // For these two, `before` is staged and the copies on disk are clean. + for (const name of ["sub/bad.js", odd]) write(root, name, "\n" + before); + write(root, "good.js", tidy + tidy.replace("a", "b")); + await git(root, "add", "-A"); + for (const name of ["sub/bad.js", odd]) write(root, name, tidy); + // good.js is the opposite: clean in the index, `before` on disk. + write(root, "good.js", before); + + const looking = command === "lint" ? ["lint", "--rule", "prefer-const: error", "-f", "unix"] : ["fmt", "--check"]; + for (const cwd of [root, join(root, "sub")]) { + const { stdout, stderr, exitCode } = await bun(cwd, [...looking, "--staged", root]); + const printed = stdout + stderr; + expect(printed).toContain("bad.js"); + expect(printed).toMatch(command === "lint" ? /^2 problems$/m : /\b2 files\b/); + expect(printed).not.toContain("good.js"); + // The position is in the staged text. + if (command === "lint") expect(stdout).toContain("bad.js:2:5: "); + expect(exitCode).toBe(1); + } + + const writeResult = await bun(root, [...writing[command], "--staged"]); + expect(writeResult.stderr).toContain( + `2 files have both staged and unstaged changes, so they were not ${done[command]}`, + ); + expect(writeResult.stderr).not.toContain("good.js"); + expect(writeResult.exitCode).toBe(2); + expect(read(root, "sub/bad.js")).toBe(tidy); + expect(read(root, "good.js")).toBe(before); + expect(await git(root, "show", ":sub/bad.js")).toBe("\n" + before); + }); + test.skipIf(isWindows)("works in a pre-commit hook, on the index of that commit", async () => { using repo = await repository({ "a.js": tidy, "b.js": tidy }); const { root } = repo; @@ -475,21 +510,22 @@ test.concurrent( describe.concurrent("bun lint --staged --fix still reports the problems in a partly staged file", () => { // One problem that can be fixed, and one that cannot. const staged = "let a = 1;\nexport { a };\nif (a) {\n}\n"; - const left = staged + "export const unstaged = 1;\n"; + const workingTreeText = staged + "export const unstaged = 1;\n"; const rules = ["--rule", "prefer-const: error", "--rule", "no-empty: error"]; - const refusal = (ext: string) => `error: partly.${ext} has both staged and unstaged changes, so it was not fixed\n`; + const notFixedError = (ext: string) => + `error: partly.${ext} has both staged and unstaged changes, so it was not fixed\n`; async function partlyStaged(ext: string, more: Record = {}) { const repo = await repository({ [`partly.${ext}`]: tidy, [`whole.${ext}`]: tidy, ...more }); write(repo.root, `partly.${ext}`, staged); write(repo.root, `whole.${ext}`, before); await git(repo.root, "add", "-A"); - write(repo.root, `partly.${ext}`, left); + write(repo.root, `partly.${ext}`, workingTreeText); return repo; } async function isUntouched(root: string, ext: string) { - expect(read(root, `partly.${ext}`)).toBe(left); + expect(read(root, `partly.${ext}`)).toBe(workingTreeText); expect(await git(root, "show", `:partly.${ext}`)).toBe(staged); expect(await git(root, "show", `:whole.${ext}`)).toBe(after.lint); expect(await git(root, "status", "--porcelain")).toBe(`MM partly.${ext}\nM whole.${ext}\n`); @@ -508,7 +544,7 @@ describe.concurrent("bun lint --staged --fix still reports the problems in a par // That's the problem in whole.js. expect(stderr).toContain("Fixed 1 problem in 1 file\n"); expect(stderr).toContain("Linted 2 files "); - expect(stderr).toContain(refusal("js")); + expect(stderr).toContain(notFixedError("js")); expect(exitCode).toBe(2); await isUntouched(repo.root, "js"); }); @@ -538,7 +574,7 @@ describe.concurrent("bun lint --staged --fix still reports the problems in a par "partly.js: eslint(prefer-const)", ]); } - expect(stderr).toContain(refusal(ext)); + expect(stderr).toContain(notFixedError(ext)); expect(exitCode).toBe(2); await isUntouched(repo.root, ext); }); @@ -548,10 +584,383 @@ describe.concurrent("bun lint --staged --fix still reports the problems in a par const { stderr, exitCode } = await bun(repo.root, ["lint", "--staged", "--fix", "--rule", "no-empty: error"]); expect(stderr).not.toContain("unstaged"); expect(exitCode).toBe(1); - expect(read(repo.root, "partly.js")).toBe(left); + expect(read(repo.root, "partly.js")).toBe(workingTreeText); + }); +}); + +describe.concurrent("bun lint --staged reads the staged version of a partly staged file", () => { + const unix = ["-f", "unix"]; + + describe("with type information", () => { + const flags = ["--type-aware", "--type-check", "--rule", "@typescript-eslint/await-thenable: error", ...unix]; + // Fewer declarations to load. + const tsconfig = JSON.stringify({ compilerOptions: { lib: ["es2015"], types: [] } }); + const takesNumber = "export async function f(a: number) {\n await a;\n}\n"; + const takesString = "export async function f(a: string) {\n return a;\n}\n"; + const calls = 'import { f } from "../lib/f";\nlet x = "";\nexport const g = () => {\n f(x);\n};\n'; + + test("for the file itself and for a file that imports it, in every --fix pass", async () => { + using repo = await repository({ "tsconfig.json": tsconfig, "lib/f.ts": tidy, "src/whole.ts": tidy }); + write(repo.root, "lib/f.ts", takesNumber); + write(repo.root, "src/whole.ts", calls); + await git(repo.root, "add", "-A"); + write(repo.root, "lib/f.ts", takesString); + // whole.ts is rechecked after `let` is fixed. + const fix = ["--fix", "--rule", "prefer-const: error"]; + const { stdout, exitCode } = await bun(repo.root, ["lint", "--staged", ...flags, ...fix]); + expect(stdout).toContain("f.ts:2:3: "); + expect(stdout).toContain("await-thenable"); + expect(stdout).toMatch(/whole\.ts:4:5: .*TS2345/); + expect(exitCode).toBe(1); + expect(read(repo.root, "src/whole.ts")).toBe(calls.replace("let", "const")); + }); + + test.each([ + ["is staged too, but isn't linted", true], + ["only has unstaged changes", false], + ])("for an imported file that %s", async (_, isStaged) => { + using repo = await repository({ "tsconfig.json": tsconfig, "lib/f.ts": takesNumber, "src/whole.ts": tidy }); + if (isStaged) write(repo.root, "lib/f.ts", takesNumber + "\n"); + write(repo.root, "src/whole.ts", calls); + await git(repo.root, "add", "-A"); + write(repo.root, "lib/f.ts", takesString); + const { stdout, exitCode } = await bun(repo.root, ["lint", "--staged", ...flags, "src"]); + expect(stdout).not.toContain("f.ts"); + expect(stdout).toMatch(/whole\.ts:4:5: .*TS2345/); + expect(exitCode).toBe(1); + }); + + test("for a new file that was deleted after it was staged", async () => { + using repo = await repository({ "tsconfig.json": tsconfig, "src/whole.ts": tidy }); + write(repo.root, "lib/f.ts", takesNumber); + write(repo.root, "src/whole.ts", calls); + await git(repo.root, "add", "-A"); + rmSync(join(repo.root, "lib"), { recursive: true }); + const { stdout, exitCode } = await bun(repo.root, ["lint", "--staged", ...flags]); + expect(stdout).toContain("f.ts:2:3: "); + expect(stdout).toContain("await-thenable"); + expect(stdout).toMatch(/whole\.ts:4:5: .*TS2345/); + expect(exitCode).toBe(1); + }); + + test.skipIf(isWindows)( + "for a file passed through a symlinked path, and a package.json with a byte order mark", + async () => { + const module = { + "package.json": '\uFEFF{ "type": "module" }', + "tsconfig.json": '{ "compilerOptions": { "module": "nodenext", "lib": ["es2015"], "types": [] } }', + }; + using repo = await repository({ ...module, "a.ts": tidy }); + const { root } = repo; + write(root, "a.ts", "export async function f(a: number) {\n await a;\n return import.meta;\n}\n"); + write(root, "package.json", module["package.json"] + "\n"); + await git(root, "add", "-A"); + write(root, "a.ts", tidy); + write(root, "package.json", module["package.json"]); + using links = tempDir("bun-lint-git-link", {}); + symlinkSync(root, join(String(links), "link")); + const { stdout, exitCode } = await bun(root, [ + "lint", + "--staged", + ...flags, + join(String(links), "link", "a.ts"), + ]); + expect(stdout).toContain("a.ts:2:3: "); + expect(stdout).toMatch(/^1 problem$/m); + expect(exitCode).toBe(1); + }, + ); + }); + + test("for a file that no tsconfig.json includes", async () => { + const code = "export function f() {\n let a = 1;\n a = 2;\n return a;\n}\n"; + using repo = await repository({ "tsconfig.json": "{}", "partly.js": tidy, "whole.js": tidy }); + for (const name of ["partly.js", "whole.js"]) write(repo.root, name, code); + await git(repo.root, "add", "-A"); + write(repo.root, "partly.js", tidy); + const rules = ["--rule", "@typescript-eslint/await-thenable: error", "--rule", "no-useless-assignment: error"]; + const { stdout, exitCode } = await bun(repo.root, ["lint", "--staged", "--type-aware", ...rules]); + expect(stdout.match(/It is overwritten on line 3 before it is read\./g)).toHaveLength(2); + expect(exitCode).toBe(1); + }); + + test("for a rule that follows imports", async () => { + using repo = await repository({ "partly.js": tidy, "whole.js": tidy }); + write(repo.root, "partly.js", tidy + "\n"); + write(repo.root, "whole.js", 'import { b } from "./partly.js";\nexport { b };\n'); + await git(repo.root, "add", "-A"); + write(repo.root, "partly.js", tidy + tidy.replace("a", "b")); + const { stdout, exitCode } = await bun(repo.root, ["lint", "--staged", "--rule", "import/named: error", ...unix]); + expect(stdout).toContain("whole.js:1:10: b not found in './partly.js'"); + expect(exitCode).toBe(1); + }); + + test("--fix-dry-run fixes it because it doesn't write files", async () => { + using repo = await repository({ "partly.js": tidy, "whole.js": tidy }); + for (const name of ["partly.js", "whole.js"]) write(repo.root, name, before); + await git(repo.root, "add", "-A"); + write(repo.root, "partly.js", tidy); + const flags = ["--fix-dry-run", "--rule", "prefer-const: error", "-f", "json"]; + const { stdout, exitCode } = await bun(repo.root, ["lint", "--staged", ...flags]); + const outputs = JSON.parse(stdout).map(it => [basename(it.filePath), it.output]); + expect(outputs.sort()).toEqual([ + ["partly.js", after.lint], + ["whole.js", after.lint], + ]); + expect(exitCode).toBe(0); + expect(read(repo.root, "partly.js")).toBe(tidy); }); }); +describe.concurrent("bun lint --staged lints what will be committed", () => { + const clean = "console.log(1);\n"; + const broken = "debugger;\n" + clean; + const lint = (root: string, ...more: string[]) => bun(root, ["lint", "--staged", "-f", "unix", ...more]); + + test("a staged `debugger` is reported after it's removed on disk", async () => { + using repo = await repository({ "f.js": clean }); + write(repo.root, "f.js", broken); + await git(repo.root, "add", "f.js"); + write(repo.root, "f.js", clean); + const { stdout, exitCode } = await lint(repo.root); + expect(stdout).toContain("f.js:1:1: Unexpected 'debugger' statement."); + expect(exitCode).toBe(1); + expect(read(repo.root, "f.js")).toBe(clean); + }); + + test("a `debugger` that's only on disk isn't reported", async () => { + using repo = await repository({ "f.js": clean }); + write(repo.root, "f.js", clean + clean); + await git(repo.root, "add", "f.js"); + write(repo.root, "f.js", broken); + const { stdout, exitCode } = await lint(repo.root); + expect(stdout).toBe(""); + expect(exitCode).toBe(0); + }); + + test("a file that's the same on disk and in the index is linted as usual", async () => { + using repo = await repository({ "f.js": clean }); + write(repo.root, "f.js", broken); + await git(repo.root, "add", "f.js"); + const { stdout, exitCode } = await lint(repo.root); + expect(stdout).toContain("f.js:1:1: Unexpected 'debugger' statement."); + expect(exitCode).toBe(1); + }); + + test("a staged deletion isn't linted, even if the file is still on disk", async () => { + using repo = await repository({ "deleted.js": broken, "untracked.js": broken, "kept.js": clean }); + await git(repo.root, "rm", "-q", "deleted.js"); + await git(repo.root, "rm", "-q", "--cached", "untracked.js"); + write(repo.root, "kept.js", clean + clean); + await git(repo.root, "add", "kept.js"); + expect(await selected(repo.root, repo.root, ["lint", "--staged"])).toEqual(["kept.js"]); + const { stdout, exitCode } = await lint(repo.root); + expect(stdout).toBe(""); + expect(exitCode).toBe(0); + }); + + test("a new file that was deleted after it was staged is linted", async () => { + using repo = await repository({ "kept/a.js": clean }); + const { root } = repo; + write(root, "sub/gone.js", broken); + await git(root, "add", "-A"); + rmSync(join(root, "sub"), { recursive: true }); + const { stdout, exitCode } = await lint(root); + expect(stdout).toContain("gone.js:1:1: Unexpected 'debugger' statement."); + expect(exitCode).toBe(1); + expect(existsSync(join(root, "sub"))).toBe(false); + + // Arguments and ignore patterns still apply. + expect(await selected(root, root, ["lint", "--staged"])).toEqual(["sub/gone.js"]); + expect(await selected(root, root, ["lint", "--staged", "**/*.js"])).toEqual(["sub/gone.js"]); + expect(await selected(root, root, ["lint", "--staged", "kept"])).toEqual([]); + expect(await selected(root, root, ["lint", "--staged", "--ignore-pattern", "sub/**"])).toEqual([]); + expect(await selected(root, root, ["lint", "--staged", ".", "!kept/other.js"])).toEqual(["sub/gone.js"]); + expect(await selected(root, root, ["lint", "--staged", ".", "!sub/gone.js"])).toEqual([]); + expect(await selected(root, root, ["lint", "--staged", "**/*.js", "!sub"])).toEqual([]); + // Without this flag, an argument that doesn't match anything on disk is an error. + const tolerant = ["lint", "--staged", "--no-error-on-unmatched-pattern"]; + expect(await selected(root, root, [...tolerant, "sub/gone.js"])).toEqual(["sub/gone.js"]); + expect(await selected(root, root, [...tolerant, "sub"])).toEqual(["sub/gone.js"]); + expect(await selected(root, root, [...tolerant, "sub/gone.jsx"])).toEqual([]); + }); + + test("--fix doesn't recreate a file that was deleted after it was staged", async () => { + using repo = await repository({ "kept.js": clean }); + write(repo.root, "gone.js", before); + await git(repo.root, "add", "-A"); + rmSync(join(repo.root, "gone.js")); + const { stderr, exitCode } = await bun(repo.root, [...writing.lint, "--staged"]); + expect(stderr).toContain("gone.js has both staged and unstaged changes, so it was not fixed\n"); + expect(exitCode).toBe(2); + expect(existsSync(join(repo.root, "gone.js"))).toBe(false); + expect(await git(repo.root, "show", ":gone.js")).toBe(before); + }); + + test.skipIf(isWindows)("a staged file that was replaced by a symlink on disk is linted", async () => { + using repo = await repository({ "target.js": clean }); + write(repo.root, "f.js", broken); + await git(repo.root, "add", "-A"); + rmSync(join(repo.root, "f.js")); + symlinkSync("target.js", join(repo.root, "f.js")); + const { stdout, exitCode } = await lint(repo.root); + expect(stdout).toContain("f.js:1:1: Unexpected 'debugger' statement."); + expect(exitCode).toBe(1); + }); +}); + +describe.concurrent("bun fmt --staged reads a partly staged file with the checkout's line endings", () => { + const crlf = (text: string) => text.replaceAll("\n", "\r\n"); + const two = tidy + tidy.replace("a", "b"); + + test("when git stores LF and checks out CRLF", async () => { + using repo = await repository({ ".gitattributes": "*.js text eol=crlf\n", "partly.js": tidy, "whole.js": tidy }); + const { root } = repo; + for (const name of ["partly.js", "whole.js"]) write(root, name, crlf(two)); + await git(root, "add", "-A"); + write(root, "partly.js", crlf(tidy)); + expect(await git(root, "show", ":partly.js")).toBe(two); + for (const flags of [["--check"], []]) { + const { stderr, exitCode } = await bun(root, ["fmt", "--staged", "--end-of-line", "crlf", ...flags]); + expect(stderr).not.toContain("partly.js"); + expect(exitCode).toBe(0); + } + // Same result as whole.js, which is read from disk. + const { stdout, stderr, exitCode } = await bun(root, ["fmt", "--staged", "--check", "--end-of-line", "lf"]); + expect(stdout + stderr).toMatch(/\b2 files\b/); + expect(exitCode).toBe(1); + }); + + test("in a language that only a Prettier plugin supports", async () => { + // Stubs. This Prettier collapses repeated spaces and uses the configured line ending. + using repo = await repository({ + ".gitattributes": "*.astro text eol=crlf\n", + ".gitignore": "node_modules\n", + ".prettierrc": '{ "plugins": ["prettier-plugin-astro"], "endOfLine": "crlf" }\n', + "node_modules/prettier/package.json": '{ "name": "prettier", "version": "3.0.0", "main": "index.cjs" }', + "node_modules/prettier/index.cjs": `const fs = require("node:fs"); +exports.resolveConfig = async (file, { config }) => JSON.parse(fs.readFileSync(config, "utf8")); +exports.format = async (text, { endOfLine }) => + text.replace(/ +/g, " ").replace(/\\r?\\n/g, endOfLine === "crlf" ? "\\r\\n" : "\\n"); +`, + "node_modules/prettier-plugin-astro/package.json": '{ "name": "prettier-plugin-astro", "version": "4.0.0" }', + "tidy.astro": "

    a

    \r\n", + "messy.astro": "

    a

    \r\n", + }); + const { root } = repo; + write(root, "tidy.astro", "

    b

    \r\n"); + write(root, "messy.astro", "

    b

    \r\n"); + await git(root, "add", "-A"); + // On disk it's the other way around. + write(root, "tidy.astro", "

    c

    \r\n"); + write(root, "messy.astro", "

    c

    \r\n"); + expect(await git(root, "show", ":tidy.astro")).toBe("

    b

    \n"); + const { stdout, stderr, exitCode } = await bun(root, ["fmt", "--staged", "--check"]); + expect(stdout + stderr).toContain("messy.astro"); + expect(stdout + stderr).not.toContain("tidy.astro"); + expect(exitCode).toBe(1); + }); + + test("when git doesn't convert line endings", async () => { + using repo = await repository({ "partly.js": tidy }); + const { root } = repo; + write(root, "partly.js", crlf(two)); + await git(root, "add", "-A"); + write(root, "partly.js", crlf(tidy)); + expect(await git(root, "show", ":partly.js")).toBe(crlf(two)); + const { stdout, stderr, exitCode } = await bun(root, ["fmt", "--staged", "--check", "--end-of-line", "lf"]); + expect(stdout + stderr).toContain("partly.js"); + expect(exitCode).toBe(1); + }); + + test("when git doesn't convert line endings and one line on disk ends in CRLF", async () => { + using repo = await repository({ "partly.js": tidy }); + const { root } = repo; + write(root, "partly.js", two); + await git(root, "add", "-A"); + write(root, "partly.js", two + crlf(tidy.replace("a", "c"))); + const { stdout, stderr, exitCode } = await bun(root, ["fmt", "--staged", "--check", "--end-of-line", "lf"]); + expect(stdout + stderr).not.toContain("partly.js"); + expect(exitCode).toBe(0); + }); +}); + +test.concurrent.each(commands)("bun %s --staged only reads the files it needs from the index", async command => { + using repo = await repository({ "asset.bin": "1", "other.js": tidy, "whole.js": tidy }); + const { root } = repo; + write(root, "whole.js", tidy + tidy.replace("a", "b")); + await git(root, "add", "-A"); + const looking = command === "lint" ? ["lint"] : ["fmt", "--check"]; + async function reads() { + using trace = tempDir("bun-lint-git-trace", {}); + const { exitCode } = await bun(root, [...looking, "--staged"], { GIT_TRACE: join(String(trace), "trace") }); + expect(exitCode).toBe(0); + return read(String(trace), "trace").includes("cat-file"); + } + expect(await reads()).toBe(false); + // Not staged, and nothing can import it. + write(root, "asset.bin", "2"); + expect(await reads()).toBe(false); + // Not staged either. A staged file can import it, which only matters to `bun lint`. + write(root, "other.js", tidy + "\n"); + expect(await reads()).toBe(command === "lint"); + write(root, "whole.js", tidy); + expect(await reads()).toBe(true); +}); + +test.concurrent.each(commands)( + "bun %s --staged reports a file whose staged blob is missing from the clone", + async command => { + using repo = await repository({ "sub/partly.js": tidy }); + const { root } = repo; + write(root, "sub/partly.js", before); + await git(root, "add", "-A"); + write(root, "sub/partly.js", tidy); + // Otherwise `git diff` looks for the blob too, and fails first. + await git(root, "config", "diff.autoRefreshIndex", "false"); + const id = (await git(root, "rev-parse", ":sub/partly.js")).trim(); + rmSync(join(root, ".git/objects", id.slice(0, 2), id.slice(2)), { force: true }); + const { stderr, exitCode } = await bun(join(root, "sub"), [command, "--staged"]); + expect(stderr).toContain(`--staged cannot read what is staged of partly.js (blob ${id})\n`); + expect(exitCode).toBe(2); + }, +); + +test.concurrent("bun lint --staged reads a conflicted file from disk", async () => { + using repo = await repository({ "conflict.js": tidy, "whole.js": tidy }); + const { root } = repo; + await git(root, "checkout", "-q", "-b", "other"); + write(root, "conflict.js", "export const theirs = 1;\n"); + write(root, "whole.js", 'import { both } from "./conflict.js";\nexport { both };\n'); + await commit(root); + await git(root, "checkout", "-q", "main"); + write(root, "conflict.js", "export const ours = 1;\n"); + await commit(root); + await run(["git", "merge", "other"], root); + expect(await git(root, "status", "--porcelain")).toBe("UU conflict.js\nM whole.js\n"); + // Resolved, but not staged yet. + write(root, "conflict.js", "export const both = 1;\n"); + expect(await selected(root, root, ["lint", "--staged"])).toEqual(["whole.js"]); + const { stdout, exitCode } = await bun(root, ["lint", "--staged", "--rule", "import/named: error", "-f", "unix"]); + expect(stdout).toBe(""); + expect(exitCode).toBe(0); +}); + +test.skipIf(isWindows).concurrent.each(commands)( + "bun %s --staged skips a file that is staged as a symlink", + async command => { + using repo = await repository({ "target.js": tidy, "a.js": tidy, "b.js": tidy }); + const { root } = repo; + rmSync(join(root, "a.js")); + symlinkSync("target.js", join(root, "a.js")); + write(root, "b.js", before); + await git(root, "add", "-A"); + rmSync(join(root, "a.js")); + write(root, "a.js", tidy); + expect(await selected(root, root, [command, "--staged"])).toEqual(["b.js"]); + }, +); + test.concurrent("bun fmt --staged doesn't count a file it skips", async () => { using repo = await repository({ "partly.js": tidy, "whole.js": tidy, "tidy.js": tidy }); const { root } = repo; diff --git a/test/cli/lint/help.test.ts b/test/cli/lint/help.test.ts index 8fc41114cc28..f8958ff7a439 100644 --- a/test/cli/lint/help.test.ts +++ b/test/cli/lint/help.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from "bun:test"; -import { chmodSync, readFileSync } from "fs"; -import { bunEnv, bunExe, isWindows, tempDir } from "harness"; -import { join } from "path"; +import { chmodSync, mkdirSync, readFileSync, symlinkSync, writeFileSync } from "fs"; +import { bunEnv, bunExe, isLinux, isRoot, isWindows, tempDir } from "harness"; +import { join, posix } from "path"; const root = join(import.meta.dir, "../../.."); @@ -86,11 +86,11 @@ describe.concurrent.each([ const { stdout, stderr, exitCode } = await run(command, "--help", "--all"); expect(stdout.match(/^\S.*:$/gm)).toEqual([...headings.map(heading => `${heading}:`), "Examples:"]); const params = readFileSync(join(root, source), "utf8").matchAll(/clap::param!\(\s*"(?:-\w, )?(--[^\s"]+)/g); - const taken = [...params].flatMap(it => it[1].split("/")); - expect(taken.length).toBeGreaterThan(70); + const acceptedFlags = [...params].flatMap(it => it[1].split("/")); + expect(acceptedFlags.length).toBeGreaterThan(70); const mentioned = new Set(stdout.match(/--[\w-]+/g)); // Listing `--no-semi` covers `--semi` too. - const missing = taken.filter(flag => !mentioned.has(flag) && !mentioned.has(flag.replace("--", "--no-"))); + const missing = acceptedFlags.filter(flag => !mentioned.has(flag) && !mentioned.has(flag.replace("--", "--no-"))); expect(missing).toEqual([]); expect(stderr).toBe(""); expect(exitCode).toBe(0); @@ -101,12 +101,15 @@ describe.concurrent.each([ expect(listed(all.stdout)).toMatchObject(listed(short.stdout)); }); - test.each([["--help-all"], ["--all", "--help"], ["-h", "--all"]])("%s %s is --help --all", async (...args) => { - const [one, other] = await Promise.all([run(command, ...args), run(command, "--help", "--all")]); - expect(one).toEqual(other); - }); + test.each([["--help-all"], ["--all", "--help"], ["-h", "--all"]])( + "%s %s prints the same as --help --all", + async (...args) => { + const [one, other] = await Promise.all([run(command, ...args), run(command, "--help", "--all")]); + expect(one).toEqual(other); + }, + ); - // ESLint, oxlint, Prettier and other tools behind such scripts have these flags too. + // ESLint, oxlint, Prettier and the other tools these scripts run have these flags too. test.each([ ["--init"], ["--rules"], @@ -117,14 +120,14 @@ describe.concurrent.each([ ["-V"], ["src", "-v"], ...(command === "fmt" ? [["--explain", "no-var"], ["--explain=no-var"]] : []), - ])("%s %s is passed to a package.json script of that name, and its exit code counts", async (...args) => { + ])("%s %s is passed to the package.json script with that name, and bun exits with its exit code", async (...args) => { const files = { "package.json": JSON.stringify({ scripts: { [command]: "echo the script && exit 3 && echo" } }) }; const { stdout, exitCode } = await runIn(files, command, ...args); expect(stdout).toBe("the script\n"); expect(exitCode).toBe(3); }); - test.each(["--help", "-h"])("bun %s prints the help and touches no file", async flag => { + test.each(["--help", "-h"])("bun %s prints the help and doesn't write any files", async flag => { using dir = tempDir("bun-help-before", { "a.js": "const a=1\n" }); await using proc = Bun.spawn({ cmd: [bunExe(), flag, command], env: bunEnv, cwd: String(dir), stderr: "pipe" }); const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); @@ -133,7 +136,7 @@ describe.concurrent.each([ expect(exitCode).toBe(0); }); - test("flags of the command that stand before it count", async () => { + test("the command's flags also work before the command", async () => { const [flags, text, after, code] = command === "fmt" ? [["--check", "-c", "--list-different", "-l"], "const a=1\n", "const a=1\n", 1] @@ -154,7 +157,7 @@ describe.concurrent.each([ } }); - test("flags of bun and of BUN_OPTIONS before the command aren't passed to it", async () => { + test("bun's own flags before the command and in BUN_OPTIONS aren't passed to it", async () => { using dir = tempDir("bun-flags-before", { "a.ts": "export const a = 1;\n" }); await using proc = Bun.spawn({ cmd: [bunExe(), "--smol", "--no-install", command, "a.ts"], @@ -170,7 +173,7 @@ describe.concurrent.each([ // No other tool has these flags, and the migration guides send people here who still have "lint": "eslint .". test.each([["--doctor"], ...(command === "lint" ? [["--explain", "no-var"], ["--explain=no-var"]] : [])])( - "%s %s isn't passed to a package.json script of that name", + "%s %s isn't passed to the package.json script with that name", async (...args) => { const scripts = (name: string) => ({ "package.json": JSON.stringify({ scripts: { [name]: "echo the script" } }), @@ -190,7 +193,7 @@ describe.concurrent.each([ describe.concurrent.each(["lint", "fmt", "check"])("bun %s", command => { test.each(["--help", "-h", ...(command === "check" ? [] : ["--help-all"])])( - "%s isn't passed to a package.json script of that name", + "%s isn't passed to the package.json script with that name", async flag => { const files = { "package.json": JSON.stringify({ scripts: { [command]: "echo the script" } }) }; const [here, elsewhere] = await Promise.all([runIn(files, command, flag), run(command, flag)]); @@ -218,49 +221,53 @@ note: package.json has a "${command}" script, so bun ${command} runs that script expect(exitCode).toBe(0); }); - describe("--no-script", () => { - const [flags, problem] = { - lint: [["-f", "unix"], /a\.ts:1:1: .+no-debugger/], - fmt: [["-l", "--print-width", "80"], /^a\.ts$/], - check: [["--pretty", "false", "--threads", "1"], /^a\.ts\(2,14\): error TS2322/], - }[command] as [string[], RegExp]; - const script = { "package.json": JSON.stringify({ scripts: { [command]: "echo the script" } }) }; - const executable = "#!/bin/sh\necho the executable\n"; - - /** - * What `bun ...args` runs in the directory `cwd` of a project with `files`: "the command" if it reports the problem in - * `a.ts`, and otherwise what is printed. - */ - async function ran(files: Record, args: string[], cwd = ".") { - using dir = tempDir("bun-no-script", { - ...files, - [join(cwd, "a.ts")]: "debugger ;\nexport const a: string = 1;\n", - }); - for (const name in files) if (files[name] === executable) chmodSync(join(String(dir), name), 0o755); - await using proc = Bun.spawn({ - cmd: [bunExe(), ...args], - env: bunEnv, - cwd: join(String(dir), cwd), - stderr: "pipe", - }); - const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - return problem.test(stdout.trim()) && exitCode === 1 ? "the command" : stdout.trim() || stderr.trim(); - } + const [flags, problem] = { + lint: [["-f", "unix"], /a\.ts:1:1: .+no-debugger/], + fmt: [["-l", "--print-width", "80"], /^a\.ts$/], + check: [["--pretty", "false", "--threads", "1"], /^a\.ts\(2,14\): error TS2322/], + }[command] as [string[], RegExp]; + const script = { "package.json": JSON.stringify({ scripts: { [command]: "echo the script" } }) }; + const executable = "#!/bin/sh\necho the executable\n"; + const source = "debugger ;\nexport const a: string = 1;\n"; + /** `from` is the directory to start `bun` in (default: `cwd`). `before` runs first, with the project directory. */ + type More = { from?: string; env?: Record; before?: (dir: string) => void }; + + /** Runs `bun ...args` in the `cwd` directory of a project containing `files`. Also writes `a.ts` to `cwd`. */ + async function bun(files: Record, args: string[], cwd = ".", more: More = {}) { + using dir = tempDir("bun-no-script", { ...files, [posix.join(cwd, "a.ts")]: source }); + for (const name in files) if (files[name].startsWith("#!")) chmodSync(join(String(dir), name), 0o755); + more.before?.(String(dir)); + await using proc = Bun.spawn({ + cmd: [bunExe(), ...args], + env: { ...bunEnv, ...more.env }, + cwd: join(String(dir), more.from ?? cwd), + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { stdout, stderr, exitCode, source: readFileSync(join(String(dir), cwd, "a.ts"), "utf8") }; + } + + /** Returns "the command" if `bun` reports the problem in `a.ts`. Otherwise returns the printed output. */ + async function whatRan(...args: Parameters) { + const { stdout, stderr, exitCode } = await bun(...args); + return problem.test(stdout.trim()) && exitCode === 1 ? "the command" : stdout.trim() || stderr.trim(); + } + describe("--no-script", () => { test.each([ `${command} --no-script ${flags.join(" ")} a.ts`, `${command} ${flags.join(" ")} --no-script a.ts`, `${command} ${flags.join(" ")} a.ts --no-script`, `--no-script ${command} ${flags.join(" ")} a.ts`, - ])("bun %s", async args => { - expect(await ran(script, args.split(" "))).toBe("the command"); + ])("bun %s runs the command", async args => { + expect(await whatRan(script, args.split(" "))).toBe("the command"); }); const found = [ ["a script in package.json", script, `the script ${flags.join(" ")} a.ts`, "."], ["a file", { [`${command}.ts`]: 'console.log("the file");' }, "the file", "."], ["a file without an extension", { [command]: 'console.log("the file");' }, "the file", "."], - ["the index of a directory", { [`${command}/index.js`]: 'console.log("the index");' }, "the index", "."], + ["a directory's index file", { [`${command}/index.js`]: 'console.log("the index");' }, "the index", "."], [ "a directory with a package.json", { [`${command}/package.json`]: '{ "main": "main.js" }', [`${command}/main.js`]: 'console.log("the package");' }, @@ -270,51 +277,51 @@ note: package.json has a "${command}" script, so bun ${command} runs that script ...(isWindows ? [] : [ - ["an executable of a package", { [`node_modules/.bin/${command}`]: executable }, "the executable", "."], + ["a package's executable", { [`node_modules/.bin/${command}`]: executable }, "the executable", "."], [ - "an executable of a package further up", + "a package's executable in a parent directory", { [`node_modules/.bin/${command}`]: executable }, "the executable", "sub", ], [ - "an executable beside package.json", + "an executable next to package.json", { "package.json": "{}", [command]: executable }, "the executable", "sub", ], ]), ] as [string, Record, string, string][]; - // `check` has been a command for longer, and only a script wins over it. + // `check` is an older command, and only a package.json script overrides it. test.each(command === "check" ? found.slice(0, 1) : found)( - "%s wins over the command, and not with the flag", + "%s overrides the command, but not with --no-script", async (_, files, printed, cwd) => { const [without, withFlag] = await Promise.all([ - ran(files, [command, ...flags, "a.ts"], cwd), - ran(files, [command, "--no-script", ...flags, "a.ts"], cwd), + whatRan(files, [command, ...flags, "a.ts"], cwd), + whatRan(files, [command, "--no-script", ...flags, "a.ts"], cwd), ]); expect({ without, withFlag }).toEqual({ without: printed, withFlag: "the command" }); }, ); - // These make `bun ` a matter of scripts, even where there is no such script. + // With these flags, `bun ` only looks for scripts, even if there's no script with that name. test.each(["--if-present", "--workspaces", "--filter=*", "--parallel", "--sequential"])( - "bun %s isn't the command, and is with the flag", + "bun %s only runs the command with --no-script", async flag => { const [without, withFlag] = await Promise.all([ - ran({}, [flag, command, ...flags, "a.ts"]), - ran({}, [flag, command, "--no-script", ...flags, "a.ts"]), + whatRan({}, [flag, command, ...flags, "a.ts"]), + whatRan({}, [flag, command, "--no-script", ...flags, "a.ts"]), ]); expect(without).not.toBe("the command"); expect(withFlag).toBe("the command"); }, ); - test("it changes nothing where the project has nothing of that name", async () => { - expect(await ran({}, [command, "--no-script", ...flags, "a.ts"])).toBe("the command"); + test("has no effect if nothing in the project has the command's name", async () => { + expect(await whatRan({}, [command, "--no-script", ...flags, "a.ts"])).toBe("the command"); }); - test("after -- it is a file name", async () => { + test("is a file name after --", async () => { const [here, elsewhere] = await Promise.all([ runIn(script, command, "--", "--no-script"), run(command, "--", "--no-script"), @@ -329,11 +336,439 @@ note: package.json has a "${command}" script, so bun ${command} runs that script } }); - test("bun run is the script, which is passed the flag", async () => { - expect(await ran(script, ["run", command, "--no-script"])).toBe("the script --no-script"); + test("bun run runs the script and passes it the flag", async () => { + expect(await whatRan(script, ["run", command, "--no-script"])).toBe("the script --no-script"); + }); + + // A `bun` flag before the command can have its value in the next argument. + describe.each([ + ["a script", script], + ["a file", { [`${command}.ts`]: 'console.log("the file");' }], + ...(isWindows ? [] : [["a package's executable", { [`node_modules/.bin/${command}`]: executable }]]), + ] as [string, Record][])("when the project has %s", (_, own) => { + const rest = [...flags, "a.ts"]; + + test.each([ + ["--env-file", ".env"], + ["--preload", "./pre.js"], + // `bun check` doesn't accept `-r` or `-r=./pre.js`. + ...(command === "check" ? [] : [["-r", "./pre.js"]]), + ["--shell", "bun"], + ["--elide-lines", "5"], + ])("bun %s %s behaves like bun ", async (...front) => { + const files = { ...own, ".env": "A=1\n", "pre.js": "" }; + const [plain, without, after, before, inOptions] = await Promise.all([ + whatRan(files, [command, ...rest]), + whatRan(files, [...front, command, ...rest]), + whatRan(files, [...front, command, "--no-script", ...rest]), + whatRan(files, ["--no-script", ...front, command, ...rest]), + whatRan(files, [command, "--no-script", ...rest], ".", { env: { BUN_OPTIONS: front.join(" ") } }), + ]); + expect({ without, after, before, inOptions }).toEqual({ + without: plain, + after: "the command", + before: "the command", + inOptions: "the command", + }); + }); + + test("bun --cwd behaves like bun in that directory", async () => { + const files = Object.fromEntries(Object.entries(own).map(([name, text]) => [`project/${name}`, text])); + const outside = (args: string[], env = {}) => whatRan(files, args, "project", { from: ".", env }); + const [plain, without, ...withFlag] = await Promise.all([ + whatRan(own, [command, ...rest]), + outside(["--cwd", "project", command, ...rest]), + outside(["--cwd", "project", command, "--no-script", ...rest]), + outside(["--no-script", "--cwd", "project", command, ...rest]), + outside([command, "--no-script", ...rest], { BUN_OPTIONS: "--cwd project" }), + outside([command, ...rest], { BUN_OPTIONS: "--no-script --cwd project" }), + outside(["--cwd", "project", command, ...rest], { BUN_OPTIONS: "--no-script" }), + ]); + expect(without).toBe(plain); + expect(withFlag).toEqual(Array(5).fill("the command")); + }); + }); + + test.each(command === "check" ? ["--filter"] : ["--filter", "-F"])( + "bun %s behaves like bun --filter= ", + async flag => { + const rest = [...flags, "a.ts"]; + const [blank, equals, withFlag] = await Promise.all([ + whatRan(script, [flag, "*", command, ...rest]), + whatRan(script, ["--filter=*", command, ...rest]), + whatRan(script, [flag, "*", command, "--no-script", ...rest]), + ]); + expect({ blank, withFlag }).toEqual({ blank: equals, withFlag: "the command" }); + }, + ); + + test.skipIf(command !== "check").each([ + ["-r", "./pre.js"], + ["-F", "*"], + ])("bun %s %s check --no-script fails and doesn't run the script", async (...front) => { + const result = await bun({ ...script, "pre.js": "" }, [...front, command, "--no-script"]); + expect(result.stderr).toStartWith(`error: Invalid Argument '${front[0]}'\n`); + expect(result).toMatchObject({ stdout: "", exitCode: 1 }); }); }); + describe("a directory with the same name as the command", () => { + const files = { + [`${command}/package.json`]: JSON.stringify({ scripts: { dev: "echo the dev script" } }), + [`${command}/main.ts`]: 'console.log("the file");', + }; + + test.each([ + ["dev", "the dev script\n"], + ["main.ts", "the file\n"], + ])("bun --cwd %s doesn't run the command", async (word, printed) => { + const result = await bun(files, ["--cwd", command, word], command, { from: "." }); + expect(result).toMatchObject({ stdout: printed, source, exitCode: 0 }); + }); + + test("bun --cwd runs the command", async () => { + const args = ["--cwd", command, command, ...flags, "a.ts"]; + expect(await whatRan(files, args, command, { from: "." })).toBe("the command"); + }); + }); + + test.each([ + ["-e", 'console.log("evaluated")', "evaluated\n"], + ["-be", 'console.log("evaluated")', "evaluated\n"], + ["-p", '"printed"', "printed\n"], + ["-bp", '"printed"', "printed\n"], + ])("bun %s evaluates the code", async (flag, code, printed) => { + expect(await bun({}, [flag, code, command])).toMatchObject({ stdout: printed, source, exitCode: 0 }); + // `bun -ptsconfig.json check` is `bun check --project tsconfig.json`. + if (command === "check" && flag.endsWith("p")) return; + expect(await bun({}, [flag + code, command])).toMatchObject({ stdout: printed, source, exitCode: 0 }); + }); + + // Each contains an `e`, a `p` or an `F`, which mean `--eval`, `--print` and `--filter` in grouped short `bun` flags. + test.skipIf(command !== "lint").each(["-f=agent", "-fagent", "-Deqeqeq", "-Dprefer-const"])( + "bun %s lint: a lint flag isn't parsed as a group of short bun flags", + async flag => { + const { stdout, exitCode } = await bun({}, [flag, command, "a.ts"]); + expect(stdout).toContain("no-debugger"); + expect(exitCode).toBe(1); + }, + ); + + test.skipIf(command !== "check").each(["-ptsconfig.json", "-p=tsconfig.json", "-bptsconfig.json"])( + "bun %s check reads the flag as --project", + async flag => { + expect(await whatRan({ "tsconfig.json": "{}" }, [flag, command, ...flags])).toBe("the command"); + }, + ); + + test.skipIf(command === "check")("bun -bc= : letters in the path aren't parsed as flags", async () => { + expect(await whatRan({ "all.toml": "" }, ["-bc=all.toml", command, ...flags, "a.ts"])).toBe("the command"); + }); + + test.each(["-F", "-bF"])("bun %s runs the packages' scripts", async flag => { + const files = { + "package.json": JSON.stringify({ workspaces: ["one"] }), + "one/package.json": JSON.stringify({ name: "one", scripts: { [command]: "echo the script" } }), + }; + for (const args of [[flag, "*"], [`${flag}*`]]) { + const result = await bun(files, [...args, command]); + expect(result.stdout).toContain("the script"); + expect(result).toMatchObject({ source, exitCode: 0 }); + } + }); + + describe("--cwd is resolved the same way as for `bun run`", () => { + test.each([[["--cwd="]], [["--cwd", ""]]])("an empty value means the working directory: %j", async cwd => { + expect(await whatRan(script, [...cwd, command])).toBe("the script"); + expect(await whatRan({}, [...cwd, command, ...flags, "a.ts"])).toBe("the command"); + }); + + test.each(["missing/..", "a.ts/..", "missing/../."])( + "`..` cancels a preceding name that isn't a directory: %s", + async cwd => { + expect(await whatRan(script, [`--cwd=${cwd}`, command])).toBe("the script"); + expect(await whatRan(script, ["--cwd", cwd, command])).toBe("the script"); + }, + ); + + test.skipIf(isWindows)("`..` after a symlink resolves to the directory that contains the symlink", async () => { + const files = { "project/package.json": script["package.json"], "else/where/deep/b.ts": source }; + const before = (dir: string) => symlinkSync("../else/where/deep", join(dir, "project/link")); + expect(await whatRan(files, ["--cwd=link/..", command], "project", { before })).toBe("the script"); + expect( + await whatRan(files, ["--cwd=link/..", command, "--no-script", ...flags, "a.ts"], "project", { before }), + ).toBe("the command"); + }); + }); + + describe.skipIf(command === "check")("a bun flag whose value is the command's name", () => { + test.skipIf(command !== "fmt")("a command flag after it still applies", async () => { + const result = await bun({}, ["--title", command, "--check", command, "a.ts"]); + expect(result).toMatchObject({ source, exitCode: 1 }); + }); + + test("--cwd after it still applies", async () => { + const args = ["--title", command, "--cwd", "sub", command, ...flags, "a.ts"]; + expect(await whatRan({}, args, "sub", { from: "." })).toBe("the command"); + }); + }); + + // Without a config file, `bun lint` looks for `eslintConfig` in the package.json. + const config = { ".oxlintrc.json": '{ "rules": { "no-debugger": "error" } }' }; + + describe("a package.json that can't be parsed", () => { + const scripts = `"scripts": { "${command}": "echo the script" }`; + const note = `note: package.json may have a "${command}" script, so nothing was run + Fix the file, or pass --no-script to skip the script +`; + const inConflict = (rest: string) => + `{\n<<<<<<< HEAD\n "version": "1",\n=======\n "version": "2",\n>>>>>>> other\n ${rest}\n}\n`; + const broken = { "package.json": inConflict(scripts) }; + + describe.each([ + ["has merge conflict markers", inConflict(scripts), /^error: .+\n {4}at .+package\.json:2:1$/m], + [ + "is truncated", + `{\n "name": "a",\n "scripts": { "${command}": "echo the`, + /^error: .+\n {4}at .+package\.json:3:\d+$/m, + ], + ] as [string, string, RegExp][])("one that %s", (_, text, error) => { + const scriptLocations: [string, Record, string][] = [ + ["in the working directory", { "package.json": text }, "."], + [ + "in a workspace whose root has the script", + { "package.json": `{ "workspaces": ["packages/*"], ${scripts} }`, "packages/a/package.json": text }, + "packages/a", + ], + ]; + + // `bun lint --fix` and `bun fmt` can both write `a.ts`. + test.skipIf(command === "check").each(scriptLocations)( + "%s: fails without running anything", + async (_, files, cwd) => { + // Candidates that are tried after package.json. + const others = { + [posix.join(cwd, `${command}.ts`)]: 'console.log("the file");', + [posix.join(cwd, "node_modules/.bin", command)]: executable, + }; + const result = await bun({ ...files, ...others }, command === "lint" ? ["lint", "--fix"] : ["fmt"], cwd); + expect(result.stderr).toMatch(error); + expect(result.stderr).toContain(join(cwd, "package.json")); + expect(result.stderr).toEndWith(note); + expect(result).toMatchObject({ stdout: "", source, exitCode: 2 }); + }, + ); + + test.skipIf(command !== "check").each(scriptLocations)("%s: the type checker runs", async (_, files, cwd) => { + expect(await whatRan(files, [command, ...flags, "a.ts"], cwd)).toBe("the command"); + }); + + test("--no-script runs the command", async () => { + const files = { "package.json": text, ...config }; + expect(await whatRan(files, [command, "--no-script", ...flags, "a.ts"])).toBe("the command"); + }); + }); + + test.each([ + [command, "--help"], + [command, "-h"], + ["--help", command], + ["-h", command], + ])("bun %s %s prints the help", async (...args) => { + const [here, elsewhere] = await Promise.all([runIn(broken, ...args), run(command, "--help")]); + expect(here).toEqual(elsewhere); + }); + + test.skipIf(command === "check").each(["--version", "-v", "--revision"])( + "bun %s prints the version", + async flag => { + const [here, elsewhere] = await Promise.all([runIn(broken, flag, command), run(flag)]); + expect(here).toEqual(elsewhere); + }, + ); + + test.skipIf(command === "check")( + "bun --version would be passed to the script, so nothing is run", + async () => { + const { stdout, stderr, exitCode } = await runIn(broken, command, "--version"); + expect(stderr).toEndWith(note); + expect({ stdout, exitCode }).toEqual({ stdout: "", exitCode: 2 }); + }, + ); + + test("runs the command if the file doesn't contain the script's name", async () => { + const files = { "package.json": inConflict('"scripts": { "other": "echo no" }'), ...config }; + expect(await whatRan(files, [command, ...flags, "a.ts"])).toBe("the command"); + }); + }); + + describe("finding the package.json with the script", () => { + test.each([ + ["with other scripts", `{ "name": "${command}", "scripts": { "other": "echo no" } }`], + ["that is empty", ""], + ["with only whitespace", " \n"], + ["that is an array", `["${command}"]\n`], + ["that is null", "null\n"], + ])("runs the command with a package.json %s", async (_, text) => { + expect(await whatRan({ "package.json": text, ...config }, [command, ...flags, "a.ts"])).toBe("the command"); + }); + + const code = command.charCodeAt(0).toString(16); + // `bun run` reads all of these. + test.each([ + ["in single quotes", `{ 'scripts': { '${command}': 'echo the script' } }`], + ["with \\u", `{ "scripts": { "\\u00${code}${command.slice(1)}": "echo the script" } }`], + ["with \\x", `{ "scripts": { "\\x${code}${command.slice(1)}": "echo the script" } }`], + ])("finds a script name written %s", async (_, text) => { + expect(await whatRan({ "package.json": text }, [command])).toBe("the script"); + }); + + test("reads a UTF-16 package.json like `bun run` does", async () => { + const text = `\ufeff{ "scripts": { "${command}": "echo the script" } }`; + const before = (dir: string) => writeFileSync(join(dir, "package.json"), Buffer.from(text, "utf16le")); + expect(await whatRan({}, [command], ".", { before })).toBe("the script"); + }); + + describe.skipIf(isWindows)("a package.json that isn't a readable file", () => { + const root = { "package.json": `{ "scripts": { "${command}": "echo the script" } }` }; + const link = (to: string) => (dir: string) => symlinkSync(to, join(dir, "sub/package.json")); + const pipe = (dir: string) => expect(Bun.spawnSync(["mkfifo", join(dir, "sub/package.json")]).exitCode).toBe(0); + + test.each([ + ["a dangling link", link("nowhere")], + ["a link to itself", link("package.json")], + ["a directory", (dir: string) => mkdirSync(join(dir, "sub/package.json"))], + ] as [string, More["before"]][])("%s: uses the parent directory's package.json", async (_, before) => { + expect(await whatRan(root, [command], "sub", { before })).toBe("the script"); + }); + + test.skipIf(isRoot)("a file without read permission: uses the parent directory's package.json", async () => { + const before = (dir: string) => chmodSync(join(dir, "sub/package.json"), 0); + expect(await whatRan({ ...root, "sub/package.json": "{}" }, [command], "sub", { before })).toBe("the script"); + }); + + test.each([ + ["a link to a device", link("/dev/null")], + ["a named pipe", pipe], + ] as [string, More["before"]][])("%s: runs the command, not the parent's script", async (_, before) => { + expect(await whatRan(root, [command, ...flags, "a.ts"], "sub", { before })).toBe("the command"); + }); + }); + }); + + // `check` is an older command, and only a package.json script overrides it. + describe.skipIf(command === "check")("the project's own can call the built-in bun ", () => { + const again = [command, ...flags, "a.ts"]; + const file = ` + if (process.env.STARTED) throw new Error("started again"); + const env = { ...process.env, STARTED: "1" }; + const child = Bun.spawnSync({ cmd: [process.execPath, ...${JSON.stringify(again)}], env, stdout: "inherit" }); + process.exit(child.exitCode); + `; + const packageExecutable = `#!/bin/sh +if [ -n "$STARTED" ]; then echo started again; exit 3; fi +STARTED=1 exec "${bunExe()}" ${again.join(" ")} +`; + + describe.each([ + ["a file", { [`${command}.ts`]: file }], + ["a directory's index", { [`${command}/index.ts`]: file }], + ...(isWindows ? [] : [["a package's executable", { [`node_modules/.bin/${command}`]: packageExecutable }]]), + ] as [string, Record][])("%s", (_, files) => { + test.each([ + ["bun ", [command], {}], + ["bun , beside a package.json", [command], { "package.json": "{}" }], + ["bun run ", ["run", command], {}], + ] as [string, string[], Record][])("%s", async (_, args, more) => { + expect(await whatRan({ ...files, ...more }, args)).toBe("the command"); + }); + }); + }); + + test.skipIf(isWindows)("a backslash in a directory name isn't a separator", async () => { + const { stdout, exitCode } = await bun( + { "a\\b/package.json": script["package.json"] }, + [command, "--help"], + "a\\b", + ); + expect(stdout).toContain(`note: package.json has a "${command}" script, so bun ${command} runs that script\n`); + expect(exitCode).toBe(0); + }); + + // Skipped for `bun check`. Like TypeScript, it treats a backslash as a separator everywhere, so it can't find files + // in a directory like this. + describe.skipIf(isWindows || command === "check")("a backslash in a directory name with --cwd", () => { + // The directory that `a\b` would resolve to if the backslash were a separator. + const other = { "a/b/other.ts": source, "a/b/sub/other.ts": source }; + + test.each([ + [".", "a\\b", "a\\b"], + ["sub", "a\\b", "a\\b/sub"], + ["a\\b", ".", "a\\b"], + ])("--cwd=%s in %s runs the command in the right directory", async (cwd, from, directory) => { + for (const args of [ + [`--cwd=${cwd}`, command], + [command, "--cwd", cwd], + ]) { + expect(await whatRan(other, [...args, ...flags, "a.ts"], directory, { from })).toBe("the command"); + } + }); + }); + + // Like in a script written on Windows. + test.each(["apps\\web", ".\\apps\\web\\", "apps\\other\\..\\web"])("--cwd=%s resolves to apps/web", async cwd => { + const files = { "apps/web/package.json": script["package.json"] }; + expect(await whatRan(files, [`--cwd=${cwd}`, command], "apps/web", { from: "." })).toBe("the script"); + expect(await whatRan(files, ["--cwd", cwd, command], "apps/web", { from: "." })).toBe("the script"); + const args = [`--cwd=${cwd}`, command, "--no-script", ...flags, "a.ts"]; + expect(await whatRan(files, args, "apps/web", { from: "." })).toBe("the command"); + }); + + test.skipIf(isWindows || command === "check")("in `a\\b`, --cwd=missing doesn't resolve to a/b/missing", async () => { + const result = await bun({ "a/b/missing/a.ts": source }, ["--cwd=missing", command, ...flags, "a.ts"], "a\\b"); + expect(result.stderr).toContain('Could not change directory to "missing"'); + expect(result.exitCode).toBe(1); + }); + + test.skipIf(isWindows)("an absolute --cwd works when the working directory was deleted", async () => { + using dir = tempDir("bun-no-script", { "project/a.ts": source, "deleted/a.ts": "" }); + const args = [`--cwd=${join(String(dir), "project")}`, command, ...flags, "a.ts"]; + await using proc = Bun.spawn({ + cmd: ["sh", "-c", 'rm -r "$PWD" && exec "$0" "$@"', bunExe(), ...args], + env: bunEnv, + cwd: join(String(dir), "deleted"), + stderr: "pipe", + }); + const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); + expect(stdout.trim()).toMatch(problem); + expect(exitCode).toBe(1); + }); + + test.skipIf(isWindows)("an absolute --cwd can contain `//`, `.` and `..`", async () => { + using dir = tempDir("bun-no-script", { "project/a.ts": source }); + const cwd = `/..//${String(dir).slice(1)}/./missing/../project//`; + await using proc = Bun.spawn({ + cmd: [bunExe(), `--cwd=${cwd}`, command, ...flags, "a.ts"], + env: bunEnv, + stderr: "pipe", + }); + const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); + expect(stdout.trim()).toMatch(problem); + expect(exitCode).toBe(1); + }); + + // The path of a package.json in this directory exceeds PATH_MAX. + test.skipIf(!isLinux)("finds the script from a working directory whose path is almost PATH_MAX long", async () => { + using dir = tempDir("bun-long-path", script); + let cwd = String(dir); + while (cwd.length < 4085) cwd = join(cwd, Buffer.alloc(Math.min(100, 4089 - cwd.length), "d").toString()); + mkdirSync(cwd, { recursive: true }); + await using proc = Bun.spawn({ cmd: [bunExe(), command], env: bunEnv, cwd, stderr: "pipe" }); + const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); + expect(stdout).toBe("the script\n"); + expect(exitCode).toBe(0); + }); + test("shell completions list the same flags as --help --all", async () => { const { stdout } = await run(command, "--help", "--all"); const flags = Object.entries(listed(stdout)) @@ -353,26 +788,30 @@ note: package.json has a "${command}" script, so bun ${command} runs that script }); }); -test.concurrent("--no-script in a project whose lint and fmt scripts are other tools", async () => { - const files = { - "package.json": '{ "scripts": { "lint": "echo this is the lint script", "fmt": "echo this is the fmt script" } }\n', - ".oxlintrc.json": '{ "rules": { "eqeqeq": "error" } }\n', - "a.js": "export const a = (b) => b == 1;\n", - }; - const results = await Promise.all([ - runIn(files, "lint", "--no-script", "a.js"), - runIn(files, "lint", "-c", ".oxlintrc.json", "--no-script", "a.js"), - runIn(files, "fmt", "--no-script", "--check", "a.js"), - ]); - const printed = results.map(it => it.stdout + it.stderr); - for (const text of printed) expect(text).not.toContain("script"); - expect(printed[0]).toContain("Expected === and instead saw =="); - expect(printed[1]).toContain("Expected === and instead saw =="); - expect(printed[2]).toBe("1 file is formatted.\n"); - expect(results.map(it => it.exitCode)).toEqual([1, 1, 0]); -}); +test.concurrent( + "--no-script runs bun lint and bun fmt in a project whose lint and fmt scripts are other tools", + async () => { + const files = { + "package.json": + '{ "scripts": { "lint": "echo this is the lint script", "fmt": "echo this is the fmt script" } }\n', + ".oxlintrc.json": '{ "rules": { "eqeqeq": "error" } }\n', + "a.js": "export const a = (b) => b == 1;\n", + }; + const results = await Promise.all([ + runIn(files, "lint", "--no-script", "a.js"), + runIn(files, "lint", "-c", ".oxlintrc.json", "--no-script", "a.js"), + runIn(files, "fmt", "--no-script", "--check", "a.js"), + ]); + const printed = results.map(it => it.stdout + it.stderr); + for (const text of printed) expect(text).not.toContain("script"); + expect(printed[0]).toContain("Expected === and instead saw =="); + expect(printed[1]).toContain("Expected === and instead saw =="); + expect(printed[2]).toBe("1 file is formatted.\n"); + expect(results.map(it => it.exitCode)).toEqual([1, 1, 0]); + }, +); -test.concurrent("bun check --no-script -b in a project whose check script is another tool", async () => { +test.concurrent("bun check --no-script -b type-checks a project whose check script is another tool", async () => { const files = { "package.json": '{ "scripts": { "check": "echo this is the check script" } }\n', "tsconfig.json": '{ "files": [], "references": [{ "path": "./sub" }] }\n', @@ -389,7 +828,7 @@ test.concurrent("bun check --no-script -b in a project whose check script is ano expect(script.stdout).toBe("this is the check script -b\n"); for (const { stdout, stderr, exitCode } of results) { expect(stdout).toBe("sub/a.ts(1,14): error TS2322: Type 'number' is not assignable to type 'string'.\n"); - // Without `-b` there is a note first, about the references. + // Without `-b`, a note about the references comes first. expect(stderr).toStartWith("Found 1 error in 1 file, checked 1 file across 1 project"); expect(exitCode).toBe(1); } @@ -402,7 +841,7 @@ test("bun fmt --all is rejected without --help", async () => { expect(exitCode).toBe(2); }); -test("bun format is not a command, and says which one is", async () => { +test("bun format isn't a command, and the error points to bun fmt", async () => { const { stdout, stderr, exitCode } = await runIn({ "a.js": "a = 1\n" }, "format"); expect(stderr).toBe('error: Script not found "format"\nnote: The formatter is bun fmt\n'); expect(stdout).toBe(""); diff --git a/test/cli/lint/hints.test.ts b/test/cli/lint/hints.test.ts index 284c4ef47f56..cba6dd2e9971 100644 --- a/test/cli/lint/hints.test.ts +++ b/test/cli/lint/hints.test.ts @@ -19,8 +19,8 @@ async function hints(code: string, file = "a.js", others: Record return Array.from(reports, ([, rule, line, hint]) => `${rule} ${line}${hint === undefined ? "" : ": " + hint}`); } -describe.concurrent("no-useless-assignment", () => { - test("every branch assigns again", async () => { +describe.concurrent("the no-useless-assignment hint", () => { + test("lists both lines when both branches overwrite the value", async () => { const code = ` export function rename(kind) { let name = "honeypot"; @@ -37,13 +37,13 @@ export function rename(kind) { ]); }); - test("the next statement assigns again", async () => { + test("has the line of the next statement when it overwrites the value", async () => { expect(await hints(`export function f(a) {\n let b = a;\n b = 2;\n return b;\n}\n`)).toEqual([ "no-useless-assignment 2: It is overwritten on line 3 before it is read.", ]); }); - test("three or more branches assign again", async () => { + test("lists at most three lines when more branches overwrite the value", async () => { const cases = (count: number) => Array.from({ length: count }, (_, i) => ` case ${i}: b = ${i}; break;\n`); const code = (count: number) => `export function f(a) {\n let b = -1;\n switch (a) {\n${cases(count).join("")} default: b = 9;\n }\n return b;\n}\n`; @@ -53,11 +53,19 @@ export function rename(kind) { ]); }); - test("the variable is never read again", async () => { + test("is different when the variable is never read again", async () => { expect(await hints(`export function f(a) {\n let b = a;\n use(b);\n b = 2;\n}\n`, "a.ts")).toEqual([ "no-useless-assignment 4: Nothing reads it after this.", ]); }); + + test("an assignment in parentheses is not a pattern", async () => { + const f = `export function f(a: number, b: number) {\n (a = b) = a;\n}\n`; + const g = `export function g(a: number, b: number) {\n (a = b) += a;\n}\n`; + const { stdout, exitCode } = await lint({ "a.ts": f + g }, "-f", "unix"); + expect(stdout).toBe(""); + expect(exitCode).toBe(0); + }); }); /** Code and its expected reports. The code uses everything it declares, so nothing else gets reported. */ @@ -237,11 +245,11 @@ const cases: [code: string, ...reports: string[]][] = [ const globals = { "bunfig.toml": `[lint.globals]\nf = "readonly"\ng = "readonly"\nh = "readonly"\nuse = "readonly"\n` }; -test.concurrent.each(cases)("%s", async (code, ...reports) => { +test.concurrent.each(cases)("hints for %s", async (code, ...reports) => { expect(await hints(code + "\n", "a.js", globals)).toEqual(reports); }); -test.concurrent("@typescript-eslint/no-unused-vars", async () => { +test.concurrent("hints for @typescript-eslint/no-unused-vars", async () => { const code = `try {\n f();\n} catch (e) {\n f();\n}\nconst { a, ...others } = f();\nconst b = f(others);\ndeclare function f(a?: unknown): any;\n`; expect(await hints(code, "a.ts")).toEqual([ "@typescript-eslint/no-unused-vars 3: A catch needs no parameter. Remove it and its parentheses.", @@ -250,17 +258,20 @@ test.concurrent("@typescript-eslint/no-unused-vars", async () => { ]); }); -test.concurrent.each(["a.js", "a.ts"])("no-unused-vars with options from bunfig.toml, in %s", async file => { - const rule = file === "a.js" ? "no-unused-vars" : "@typescript-eslint/no-unused-vars"; - const bunfig = `[lint.rules]\n"${rule}" = ["warn", { ignoreRestSiblings = false, varsIgnorePattern = "^x" }]\n`; - const code = `const { a, ...others } = Bun;\nconsole.log(others);\nconst _b = 1;\n`; - expect(await hints(code, file, { "bunfig.toml": bunfig })).toEqual([ - `${rule} 1: To leave a property out this way, turn on the option ignoreRestSiblings.`, - `${rule} 3`, - ]); -}); +test.concurrent.each(["a.js", "a.ts"])( + "the no-unused-vars hints respect options from bunfig.toml, in %s", + async file => { + const rule = file === "a.js" ? "no-unused-vars" : "@typescript-eslint/no-unused-vars"; + const bunfig = `[lint.rules]\n"${rule}" = ["warn", { ignoreRestSiblings = false, varsIgnorePattern = "^x" }]\n`; + const code = `const { a, ...others } = Bun;\nconsole.log(others);\nconst _b = 1;\n`; + expect(await hints(code, file, { "bunfig.toml": bunfig })).toEqual([ + `${rule} 1: To leave a property out this way, turn on the option ignoreRestSiblings.`, + `${rule} 3`, + ]); + }, +); -test.concurrent("typescript-eslint rules", async () => { +test.concurrent("hints for other typescript-eslint rules", async () => { const code = ` declare const list: number[]; list.pop; @@ -293,7 +304,7 @@ export { path }; ]); }); -test.concurrent("react-hooks/rules-of-hooks", async () => { +test.concurrent("hints for react-hooks/rules-of-hooks", async () => { const code = ` import { useEffect, useState } from "react"; @@ -317,39 +328,42 @@ export function List({ items, open }) { ]); }); -test.concurrent("bun:test/valid-expect", async () => { +test.concurrent("hints for bun:test/valid-expect", async () => { const code = `import { expect, test } from "bun:test";\ntest("a", async () => {\n expect(Promise.resolve(1)).resolves.toBe(1);\n});\n`; expect(await hints(code, "a.test.ts")).toEqual(["bun:test/valid-expect 3: Add await, or return the promise."]); }); -test.concurrent("no-octal", async () => { +test.concurrent("hints for no-octal", async () => { expect(await hints(`module.exports = [071, 09];\n`, "a.cjs")).toEqual([ "no-octal 1: The leading 0 makes it octal, so 071 is 57. Write 0o71 to make that clear.", "no-octal 1: The leading zero does nothing here. Remove it.", ]); }); -describe.concurrent("formats that show a hint", () => { +describe.concurrent("which formats print hints", () => { const files = { "a.js": `export function f(a) {\n let b = a;\n b = 2;\n return b;\n}\n` }; const hint = "It is overwritten on line 3 before it is read."; - test("agent", async () => { + test("-f agent prints the hint", async () => { const { stdout } = await lint(files, "-f", "agent"); expect(stdout).toContain(`${hint}`); }); - test("pretty with --all", async () => { + test("-f pretty --all prints the hint", async () => { const { stdout } = await lint(files, "-f", "pretty", "--all"); expect(stdout).toContain(`note: ${hint}`); }); - test.each(["stylish", "json", "unix", "github", "junit", "checkstyle", "gitlab", "sarif"])("not %s", async format => { - const { stdout } = await lint(files, "-f", format); - expect(stdout).toContain("is not used in subsequent statements"); - expect(stdout).not.toContain("overwritten"); - }); + test.each(["stylish", "json", "unix", "github", "junit", "checkstyle", "gitlab", "sarif"])( + "-f %s doesn't print the hint", + async format => { + const { stdout } = await lint(files, "-f", format); + expect(stdout).toContain("is not used in subsequent statements"); + expect(stdout).not.toContain("overwritten"); + }, + ); - test("not with an oxlint config", async () => { + test("nothing prints the hint with an oxlint config", async () => { const config = JSON.stringify({ rules: { "no-useless-assignment": "error" } }); const { stdout } = await lint({ ...files, ".oxlintrc.json": config }, "-f", "default"); expect(stdout).toContain("no-useless-assignment"); diff --git a/test/cli/lint/import-attributes.test.ts b/test/cli/lint/import-attributes.test.ts index a6ca0c8f6d87..498fd6251dee 100644 --- a/test/cli/lint/import-attributes.test.ts +++ b/test/cli/lint/import-attributes.test.ts @@ -1,5 +1,6 @@ -// A `with` clause can be nested in another one: a value in the options of an import type can hold an import type that has -// options of its own. TypeScript reports values that aren't strings, but every parser accepts them, so rules and plugins see them. +// A `with` clause can be nested in another one: a value in an import type's options can contain an import type with its +// own options. TypeScript reports values that aren't strings, but every parser accepts them, so rules and plugins see +// them. import { afterAll, describe, expect, test } from "bun:test"; import { bunEnv, bunExe, isASAN, isDebug, tempDir } from "harness"; import { endChildren, spawn } from "../children"; @@ -527,7 +528,7 @@ async function lint(more: Record) { const typescript = `files: ["**/*.ts"], languageOptions: { parser: { meta: { name: "typescript-eslint/parser" } } }`; -describe.concurrent("import types with options inside the options of an import type", () => { +describe.concurrent("import types with options nested in another import type's options", () => { const plugin = ` const depth = node => (node.parent ? depth(node.parent) + 1 : 0); const label = node => (node.type === "Identifier" ? " " + node.name : node.type === "Literal" ? " " + node.raw : ""); @@ -576,7 +577,7 @@ describe.concurrent("import types with options inside the options of an import t timeout, ); - /** `show` of each message, by the name of the file. */ + /** Maps each file name to `show` of each of its messages. */ function byFile(stdout: string, show: (message: Message, name: string) => T) { const results: { filePath: string; messages: Message[] }[] = JSON.parse(stdout); const of = (name: string) => @@ -584,7 +585,7 @@ describe.concurrent("import types with options inside the options of an import t return Object.fromEntries(names.map(name => [name, of(name).map(it => show(it, name))])); } - /** What each rule reports in each file: the text of the reported range. None spans lines. */ + /** Lints with `rules`. `of(rule)` maps each file to the source text of that rule's reports. No report spans lines. */ async function reported(rules: Record) { const config = `export default [{ ${typescript}, rules: ${JSON.stringify(rules)} }];`; const { stdout, exitCode } = await lint({ "eslint.config.mjs": config }); @@ -596,7 +597,7 @@ describe.concurrent("import types with options inside the options of an import t return { of, exitCode }; } - test("rules that read the options of an import type get each name once", async () => { + test("rules that read an import type's options see each name once", async () => { const keys = [...new Set(names.flatMap(name => cases[name].keys))]; const { of, exitCode } = await reported({ "id-denylist": ["error", ...keys], @@ -610,14 +611,14 @@ describe.concurrent("import types with options inside the options of an import t expect(exitCode).toBe(1); }); - test("the way up from a value leads through the options of its own import type", async () => { + test("a value's ancestors are the options of its own import type", async () => { const value = "TSImportType > ObjectExpression > Property > ObjectExpression > Property > .value"; const { of, exitCode } = await reported({ "no-restricted-syntax": ["error", value] }); expect(of("no-restricted-syntax")).toEqual(Object.fromEntries(names.map(name => [name, cases[name].values]))); expect(exitCode).toBe(1); }); - test("rules that listen to string literals get each quoted string once", async () => { + test("rules that listen for string literals see each quoted string once", async () => { const patterns = [{ pattern: "^.*$", message: "A string.", in: ["strings"] }]; const { of, exitCode } = await reported({ "bun/no-restricted-text": ["error", { patterns }] }); const quoted = (code: string) => Array.from(code.matchAll(/"([^"]*)"/g), it => it[1]); diff --git a/test/cli/lint/init.test.ts b/test/cli/lint/init.test.ts index e5531d931712..75fb5519a009 100644 --- a/test/cli/lint/init.test.ts +++ b/test/cli/lint/init.test.ts @@ -1,7 +1,7 @@ // Tests for `bun lint --init` and `bun fmt --init`. import { afterAll, describe, expect, test } from "bun:test"; import { bunEnv, bunExe, isWindows, tempDir } from "harness"; -import { chmodSync, existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; +import { chmodSync, existsSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { endChildren, spawn } from "../children"; @@ -127,11 +127,11 @@ describe.concurrent.each(["lint", "fmt"] as const)("bun %s --init", command => { ["a = 1\nb = \n", "bunfig.toml:2:5"], [`[${command}]\nnothing = 1\n`, "bunfig.toml:2:1"], [`${command} = 1\n`, `bunfig.toml:1:${command.length + 4}`], - ])("an invalid bunfig.toml is an error and is left unchanged: %j", async (before, place) => { + ])("an invalid bunfig.toml is an error and is left unchanged: %j", async (before, location) => { using dir = tempDir("bun-init-section", { "bunfig.toml": before }); const result = await run(String(dir), command, "--init"); expect(result.stderr).toContain("error: "); - expect(result.stderr).toContain(place); + expect(result.stderr).toContain(location); expect({ ...result, stderr: "" }).toEqual({ stdout: "", stderr: "", exitCode: 2 }); expect(readFileSync(join(String(dir), "bunfig.toml"), "utf8")).toBe(before); }); @@ -172,9 +172,7 @@ describe.concurrent.each(["lint", "fmt"] as const)("bun %s --init", command => { chmodSync(join(String(dir), "bunfig.toml"), 0o200); expect(await run(String(dir), command, "--init")).toEqual({ stdout: "", - stderr: expect.stringMatching( - /^warn: .+\nignoring settings in .+\nerror: Cannot read bunfig\.toml: EACCES: .+\n$/, - ), + stderr: expect.stringMatching(/^error: Cannot read bunfig\.toml: EACCES: .+\n$/), exitCode: 2, }); chmodSync(join(String(dir), "bunfig.toml"), 0o644); @@ -205,13 +203,44 @@ describe.concurrent.each(["lint", "fmt"] as const)("bun %s --init", command => { } }); + describe.skipIf(isWindows)("a bunfig.toml that is a symlink", () => { + const project = { "project/.git/HEAD": "ref: refs/heads/main\n", "project/a.js": "a;\n" }; + + test("isn't written if it points outside the repository", async () => { + using dir = tempDir("bun-init-section", { ...project, "outside/existing.toml": "a = 1\n" }); + const link = join(String(dir), "project", "bunfig.toml"); + for (const target of ["existing.toml", "new.toml", "new/directory/new.toml"]) { + symlinkSync(join(String(dir), "outside", target), link); + expect(await run(join(String(dir), "project"), command, "--init")).toEqual({ + stdout: "", + stderr: expect.stringContaining( + "error: Cannot write bunfig.toml: it is a symlink to a file outside the repository\n", + ), + exitCode: 2, + }); + rmSync(link); + } + expect(readdirSync(join(String(dir), "outside"))).toEqual(["existing.toml"]); + expect(readFileSync(join(String(dir), "outside", "existing.toml"), "utf8")).toBe("a = 1\n"); + }); + + test("is written through the symlink if it points inside the repository", async () => { + using dir = tempDir("bun-init-section", { ...project, "project/config/a.js": "a;\n" }); + symlinkSync(join("config", "bunfig.toml"), join(String(dir), "project", "bunfig.toml")); + expect(await run(join(String(dir), "project"), command, "--init")).toEqual({ + stdout: `Created bunfig.toml with a [${command}] section\n`, + stderr: "", + exitCode: 0, + }); + expect(readFileSync(join(String(dir), "project", "config", "bunfig.toml"), "utf8")).toBe(section); + }); + }); + test("a directory called bunfig.toml is an error", async () => { using dir = tempDir("bun-init-section", { "bunfig.toml/a.js": "a;\n" }); expect(await run(String(dir), command, "--init")).toEqual({ stdout: "", - stderr: expect.stringMatching( - /^warn: .+\nignoring settings in .+\nerror: Cannot read bunfig\.toml: E[A-Z]+: .+\n$/, - ), + stderr: expect.stringMatching(/^error: Cannot read bunfig\.toml: E[A-Z]+: .+\n$/), exitCode: 2, }); }); @@ -229,7 +258,7 @@ describe.concurrent.each(["lint", "fmt"] as const)("bun %s --init", command => { }); }); -describe.concurrent("writes nothing if another tool's config file is in use", () => { +describe.concurrent("--init in a project with another tool's config", () => { const flat = "export default [];\n"; test.each<[Command, Record, string[], string]>([ ["lint", { "eslint.config.js": flat }, [], "eslint.config.js"], @@ -247,10 +276,10 @@ describe.concurrent("writes nothing if another tool's config file is in use", () ["fmt", { ".oxfmtrc.json": "{}" }, [], ".oxfmtrc.json"], ["fmt", { ".oxfmtrc.jsonc": "{}", "sub/a.js": "" }, ["--cwd", "sub"], "../.oxfmtrc.jsonc"], ["fmt", { "config/mine.json": "{}" }, ["--config", "config/mine.json"], "config/mine.json"], - ])("bun %s: %j %j", async (command, files, args, shown) => { + ])("bun %s writes nothing if the config file is in use: %j %j", async (command, files, args, configName) => { using dir = tempDir("bun-init-section", files); expect(await run(String(dir), command, "--init", ...args)).toEqual({ - stdout: `Using ${shown}. bunfig.toml is not needed.\n`, + stdout: `Using ${configName}. bunfig.toml is not needed.\n`, stderr: "", exitCode: 0, }); @@ -266,7 +295,7 @@ describe.concurrent("writes nothing if another tool's config file is in use", () ["fmt", { "package.json": '{ "devDependencies": { "prettier": "3.0.0" } }' }], ["fmt", { ".editorconfig": "root = true\n" }], ["fmt", { ".prettierrc": "{}", "args": "--no-config" }], - ])("still writes bunfig.toml, bun %s: %j", async (command, { args, ...files }) => { + ])("bun %s still writes bunfig.toml if no config file is in use: %j", async (command, { args, ...files }) => { using dir = tempDir("bun-init-section", files); const result = await run(String(dir), command, "--init", ...(args ? [args] : [])); expect(result.stdout).toBe(`Created bunfig.toml with a [${command}] section\n`); @@ -285,7 +314,7 @@ describe.concurrent("writes nothing if another tool's config file is in use", () }); // Uncomments each commented-out line, one at a time and then all together. -describe.concurrent("the commented-out lines work when uncommented", () => { +describe.concurrent("the commented-out lines that --init writes work when uncommented", () => { const commented = (text: string) => text.split("\n").flatMap((line, at) => (line.startsWith("# ") ? [at] : [])); const variants = (text: string) => [[], ...commented(text).map(at => [at]), commented(text)].map(lines => { diff --git a/test/cli/lint/js-parsers.test.ts b/test/cli/lint/js-parsers.test.ts index b8ccba8e4e78..d912fe5344bc 100644 --- a/test/cli/lint/js-parsers.test.ts +++ b/test/cli/lint/js-parsers.test.ts @@ -29,7 +29,7 @@ async function lint(files: Record, args: string[], read stderr: "pipe", }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - // Where a run ends with an error, or dies, the assertion that fails is often about something else. + // If a run fails or crashes, the assertion that fails is often about something else, so print the real cause. if (exitCode !== 0 && exitCode !== 1) console.error(`bun lint ${args.join(" ")}: exit code ${exitCode}\n${stderr}`); return { raw: stdout, @@ -40,7 +40,7 @@ async function lint(files: Record, args: string[], read }; } -// `file: line:column rule message`, with what else there is to a message. +// Returns `file: line:column rule message` for each message, followed by its other properties in brackets. function summary(json: string) { const lines: string[] = []; for (const { filePath, messages, suppressedMessages } of JSON.parse(json)) { @@ -71,7 +71,7 @@ const repeated = (fill: string, count: number) => Buffer.alloc(count * Buffer.by const hasTestRunner = isDebug || Bun.spawnSync({ cmd: [bunExe(), "--revision"], env: bunEnv }).stdout.includes("canary"); -// Takes the blocks between ``` out of a file, and puts what is reported about them where they are. +// A processor that extracts the ``` blocks from a file, and maps their reports back to positions in the file. const fenced = (supportsAutofix: boolean) => ` const blocksOf = new Map(); export const processor = { @@ -130,7 +130,7 @@ const rules = ` describe.concurrent("bun lint with processors", () => { test( - "the blocks are linted with the configuration for their own names, next to other files", + "lints each block with the config for the block's own name, alongside other files", async () => { const result = await lint( { @@ -200,7 +200,7 @@ describe.concurrent("bun lint with processors", () => { ); test( - "a processor that an object of the configuration has itself, without supportsAutofix: no fixes", + "an inline processor object without supportsAutofix gets no fixes", async () => { const result = await lint( { @@ -226,7 +226,7 @@ describe.concurrent("bun lint with processors", () => { ); test( - "a processor that throws, blocks without a name, and a processor that does not exist", + "handles a processor that throws, blocks without a name, and a processor that doesn't exist", async () => { const files = { "fenced.mjs": fenced(true), @@ -260,7 +260,7 @@ describe.concurrent("bun lint with processors", () => { ); test( - "a rule in JavaScript sees the name of the block and the name of the file", + "a JavaScript rule gets the block's name and the file's name", async () => { const result = await lint( { @@ -300,7 +300,7 @@ describe.concurrent("bun lint with processors", () => { timeout, ); - // As with `configs.recommended` and `configs.processor` of @eslint/markdown. + // This is what @eslint/markdown's `configs.recommended` and `configs.processor` give you together. test( "a file with a language and a processor goes to the processor", async () => { @@ -324,18 +324,19 @@ describe.concurrent("bun lint with processors", () => { `"a.md: 2:1 no-var Unexpected var, use let or const instead. [fix 6,9 "let"]"`, ); expect(result.exitCode).toBe(1); - // What the processor gives back without a name is for the language. - const whole = await lint(files, ["b.txt"]); - expect(whole.stderr).toContain( + // A block that the processor returns without a name is linted in the file's language. + const unnamedBlock = await lint(files, ["b.txt"]); + expect(unnamedBlock.stderr).toContain( "1 file was not linted because it needs eslint, which is not installed (1 *.txt): b.txt", ); - expect(whole.exitCode).toBe(2); + expect(unnamedBlock.exitCode).toBe(2); }, timeout, ); }); -// Enough of the package `eslint` to lint a text in the language of a plugin: `Linter.verify` with one object of configuration. +// A stand-in for the `eslint` package with just enough to lint text in a plugin's language: `Linter.verify` with one +// config object. const eslintPackage = { "node_modules/eslint/package.json": JSON.stringify({ name: "eslint", version: "10.0.0", main: "index.js" }), "node_modules/eslint/index.js": ` @@ -408,7 +409,7 @@ const lines = { describe.concurrent("bun lint with languages", () => { test( - "a file in the language of a plugin is linted by the Linter of the eslint that is installed", + "a file in a plugin's language is linted by the installed eslint's Linter", async () => { const result = await lint({ ...eslintPackage, ...lines }, ["-f", "json", "a.js", "b.txt"]); expect(summary(result.raw)).toMatchInlineSnapshot(` @@ -422,9 +423,9 @@ describe.concurrent("bun lint with languages", () => { timeout, ); - // As `vue-eslint-parser` for `.vue`. + // Like `vue-eslint-parser` for `.vue`. test( - "so is a file that a parser of its own reads", + "a file with a custom parser is linted by the installed eslint's Linter", async () => { const result = await lint( { @@ -450,17 +451,18 @@ describe.concurrent("bun lint with languages", () => { timeout, ); - // `Linter#verify` takes a `ruleFilter` since ESLint 9. That of ESLint 8 runs every rule, and finds a comment that disables one unused. + // `Linter#verify` has accepted a `ruleFilter` since ESLint 9. ESLint 8's runs every rule, and then reports a comment + // that disables one of them as unused. test.each([ ["9", "rules.filter(ruleFilter)"], ["8", `[...rules, ...["'semi'", "'indent' or 'semi'", "'semi' or 'no-var'"].map(unused)]`], ])( - "the deprecated rules about layout do not run there either: ESLint %s", + "the deprecated layout rules don't run in the installed eslint either: ESLint %s", async (_, reported) => { const result = await lint( { ...eslintPackage, - // One message for each rule that runs. + // Reports one message for each rule that runs. "node_modules/eslint/index.js": ` const unused = names => ({ ruleId: null, severity: 1, text: "Unused eslint-disable directive (no problems were reported from " + names + ")." }); exports.Linter = class Linter { @@ -491,10 +493,11 @@ describe.concurrent("bun lint with languages", () => { timeout, ); - // As `@babel/eslint-parser` with a plugin for syntax that is no standard yet. What is called like JavaScript is read here, as - // long as it can be. As in nodejs/node the packages are not above the configuration file: eslint is beside the parser. + // Like `@babel/eslint-parser` with a plugin for syntax that isn't standard yet. Bun parses a file with a JavaScript + // extension itself if it can. As in nodejs/node, the packages aren't in a directory above the config file: eslint is + // next to the parser. test( - "so is a file called like JavaScript that only its own parser can read, and no rule sees what is made of it here", + "a .js file that only its custom parser can parse goes to the installed eslint, and no rule sees Bun's tree for it", async () => { const result = await lint( { @@ -536,7 +539,7 @@ describe.concurrent("bun lint with languages", () => { ); test( - "so is a file for which eslint-plugin-html is configured, which changes the Linter when it is loaded", + "a file configured with eslint-plugin-html, which patches the Linter when it loads, goes to the installed eslint", async () => { const result = await lint( { @@ -569,9 +572,9 @@ describe.concurrent("bun lint with languages", () => { timeout, ); - // As @antfu/eslint-config for `.vue`: the export is a promise, and the processor forgets a file in `postprocess`. + // Like @antfu/eslint-config for `.vue`: the export is a promise, and the processor forgets a file in `postprocess`. test( - "the whole configuration file, which exports a promise, and a processor, which is called once", + "passes on a whole config file that exports a promise, and calls its processor only once", async () => { const result = await lint( { @@ -796,7 +799,7 @@ rules = { "no-console" = "off" } }); test( - "files for which the parser is asked for types all go to one engine", + "files whose parser options request types all go to one engine", async () => { const files: Record = { ...eslintPackage, @@ -817,7 +820,7 @@ rules = { "no-console" = "off" } { files: ["plain/*.vue"], plugins: { own }, languageOptions: { parser }, rules: { "own/seen": "error" } }, ];`, }; - // 6 MB, which is work for several engines. + // 6 MB, which is enough work for several engines. const text = Buffer.alloc(250_000, "\n").toString(); for (let i = 0; i < 24; i++) files[`typed/${i}.vue`] = files[`plain/${i}.vue`] = text; const realms = async (directory: string) => { @@ -833,7 +836,7 @@ rules = { "no-console" = "off" } ); test( - "--fix goes on until nothing is left to fix", + "--fix repeats until there's nothing left to fix", async () => { const result = await lint({ ...eslintPackage, ...lines }, ["--fix", "b.txt"], ["b.txt"]); expect(result.files).toEqual({ "b.txt": "one\n two \n\tthree # off\n" }); @@ -843,7 +846,7 @@ rules = { "no-console" = "off" } ); test( - "without the package eslint such files are named, and the others are linted", + "without the eslint package, lists the files that need it and lints the others", async () => { const result = await lint(lines, ["-f", "unix", "a.js", "b.txt"]); expect(result.stdout).toContain("a.js:1:1: Unexpected var, use let or const instead. [Error/no-var]"); @@ -925,7 +928,7 @@ describe.concurrent("bun lint with the built-in JSON languages", () => { expect(result.exitCode).toBe(1); }); - test("an object with many keys", async () => { + test("finds the duplicates in an object with many keys", async () => { const count = many(50_000); const keys = Array.from({ length: count }, (_, i) => `"k${i}": ${i}`); const text = `{${keys.join(",")},"k7":0,"k${count - 1}":0,"new":0}`; @@ -953,6 +956,14 @@ describe.concurrent("bun lint with the built-in JSON languages", () => { ["json", "[1,]", "1:3 Trailing commas are not allowed in JSON"], ["json", "[1", "1:3 Unterminated array"], ["json", "[1 2]", "1:4 Expected ','"], + ["json", '{\n "a": 1\n "b": 2\n}', "3:3 Expected ','"], + ["json", '["a" "b"]', "1:6 Expected ','"], + ["json", '{"a":1 2}', "1:8 Expected ','"], + ["json", '{"a" "b"}', "1:6 Expected ':' after object key"], + ["json", '{"a":}', "1:6 Unexpected token"], + ["json", '{"a":,"b":1}', "1:6 Unexpected token"], + ["json", "[1,,2]", "1:4 Unexpected token"], + ["json", '"a" "b"', "1:5 Unexpected token after JSON value"], ["json", "[1}", "1:3 Expected ']'"], ["json", '{"a":1]', "1:7 Expected '}'"], ["json", "{} {}", "1:4 Unexpected token after JSON value"], @@ -978,19 +989,26 @@ describe.concurrent("bun lint with the built-in JSON languages", () => { ["jsonc", "/* c", "1:5 Unterminated multi-line comment"], ["jsonc", "[1, // c\n", "2:1 Unexpected end of input"], ["jsonc", "{a:1}", "1:2 Keys must be strings in double quotes"], + ["jsonc", '{"a": "b" // c\n"d": 1}', "2:1 Expected ','"], + ["jsonc", '{"a" /* c */ "b"}', "1:14 Expected ':' after object key"], + ["jsonc", '{"a": /* c */ }', "1:15 Unexpected token"], ["json5", "{1:1}", "1:2 Invalid identifier start character"], ["json5", "0x", "1:3 Invalid hex number"], ["json5", "01", "1:1 Leading zeros are not allowed in JSON5"], ["json5", "[,]", "1:2 Unexpected token"], ["json5", "{a-b:1}", "1:4 Unexpected character"], ["json5", "1 2", "1:3 Unexpected token after JSON5 value"], + ["json5", "{a: 1 b: 2}", "1:7 Expected ','"], + ["json5", "['a' 'b']", "1:6 Expected ','"], + ["json5", "{a 'b'}", "1:4 Expected ':' after object key"], + ["json5", "{a:}", "1:4 Unexpected token"], ]; const files = cases.map(([language, text], i) => [`${String(i).padStart(2, "0")}.${language}`, text]); const result = await lint({ ...json, ...Object.fromEntries(files) }, ["-f", "json", "."]); expect(summary(result.raw).split("\n")).toEqual( cases.map(([, , expected], i) => { - const [place, ...message] = expected.split(" "); - return `${files[i][0]}: ${place} null Parsing error: ${message.join(" ")} [fatal]`; + const [position, ...message] = expected.split(" "); + return `${files[i][0]}: ${position} null Parsing error: ${message.join(" ")} [fatal]`; }), ); expect(result.exitCode).toBe(1); @@ -1434,7 +1452,7 @@ describe.concurrent("bun lint with the built-in JSON languages", () => { expect(result.exitCode).toBe(2); }); - test("many keys out of order, with comments", async () => { + test("handle many keys out of order, with comments", async () => { const count = many(30_000); const keys = Array.from({ length: count }, (_, i) => `"k${count - i}": ${i}, // ${i}`); const result = await lint({ ...all, "many.jsonc": `{\n${keys.join("\n")}\n"a": 1\n}` }, [ @@ -1497,33 +1515,38 @@ describe.concurrent("bun lint with the built-in JSON languages", () => { ["a byte order mark", (text: string) => mark + text], ["carriage returns", (text: string) => text.replaceAll("\n", "\r\n")], ["both", (text: string) => mark + text.replaceAll("\n", "\r\n")], - ])("U+2028 and U+2029 aren't line breaks in JSON: a file with %s", (_, written) => { + ])("U+2028 and U+2029 aren't line breaks in JSON: a file with %s", (_, transform) => { // Unless the file is short, the linter counts lines without saving their offsets, so the formatter recomputes them. const more = Array.from({ length: 50 }, (_, i) => ` "${i}": "${"-".repeat(40)}",\n`).join(""); const text = `{\n "s": "${separators}",\n${more} "a": 1,\n "a": 2\n}\n`; - const files = { ...json, "a.json": written(text) }; + const files = { ...json, "a.json": transform(text) }; - test.each(["pretty", "agent"])("the code excerpt in %s", async format => { + test.each(["pretty", "agent"])("the code excerpt in %s shows the right line", async format => { const result = await lint(files, ["-f", format, "a.json"]); - const shown = result.stdout.split("\n").filter(line => line.includes('"a"') && !line.includes("Duplicate")); - expect(shown.at(-1)).toEndWith('"a": 2'); + const excerptLines = result.stdout + .split("\n") + .filter(line => line.includes('"a"') && !line.includes("Duplicate")); + expect(excerptLines.at(-1)).toEndWith('"a": 2'); expect(result.stdout).toContain(format === "pretty" ? "a.json:54:3" : 'line="54" column="3"'); }); - test.each(["stylish", "json", "unix", "github", "checkstyle", "junit", "gitlab", "sarif"])("%s", async format => { - const result = await lint(files, ["-f", format, "a.json"]); - const places = { - stylish: " 54:3 error", - json: '"line":54,"column":3,"messageId":"duplicateKey","endLine":54,"endColumn":6', - unix: "a.json:54:3:", - github: "line=54,col=3,endLine=54,endColumn=6", - checkstyle: 'line="54" column="3"', - junit: "line 54, column 3", - gitlab: '"begin": 54', - sarif: '"startLine": 54', - }; - expect(result.stdout).toContain(places[format as keyof typeof places]); - }); + test.each(["stylish", "json", "unix", "github", "checkstyle", "junit", "gitlab", "sarif"])( + "%s prints the right line", + async format => { + const result = await lint(files, ["-f", format, "a.json"]); + const expectedByFormat = { + stylish: " 54:3 error", + json: '"line":54,"column":3,"messageId":"duplicateKey","endLine":54,"endColumn":6', + unix: "a.json:54:3:", + github: "line=54,col=3,endLine=54,endColumn=6", + checkstyle: 'line="54" column="3"', + junit: "line 54, column 3", + gitlab: '"begin": 54', + sarif: '"startLine": 54', + }; + expect(result.stdout).toContain(expectedByFormat[format as keyof typeof expectedByFormat]); + }, + ); }); test("comments disable and configure rules in JSONC and JSON5", async () => { @@ -1573,7 +1596,7 @@ describe.concurrent("bun lint with the built-in JSON languages", () => { expect(result.exitCode).toBe(0); }); - test("noInlineConfig, --no-inline-config and --report-unused-disable-directives-severity", async () => { + test("noInlineConfig, --no-inline-config and --report-unused-disable-directives-severity work", async () => { const files = { ...jsonPackage(), "eslint.config.mjs": jsonConfig(`{ files: ["no/*"], linterOptions: { noInlineConfig: true } }`), @@ -1601,7 +1624,7 @@ describe.concurrent("bun lint with the built-in JSON languages", () => { "a.jsonc": '{ "a": [1,], }', "x.json": "{}", }); - const [allowed, printed, refused, wrong, elsewhere] = await Promise.all([ + const [allowed, printed, disallowed, wrong, elsewhere] = await Promise.all([ lint(files("{ allowTrailingCommas: true, globals: { a: true } }"), ["-f", "json", "a.jsonc"]), lint(files("{ allowTrailingCommas: true }"), ["--print-config", "a.jsonc"]), lint(files("{ allowTrailingCommas: false }"), ["-f", "json", "a.jsonc"]), @@ -1612,7 +1635,7 @@ describe.concurrent("bun lint with the built-in JSON languages", () => { expect(allowed.exitCode).toBe(0); expect(JSON.parse(printed.raw).language).toBe("json/jsonc"); expect(JSON.parse(printed.raw).languageOptions).toEqual({ allowTrailingCommas: true }); - expect(summary(refused.raw)).toBe( + expect(summary(disallowed.raw)).toBe( "a.jsonc: 1:10 null Parsing error: Trailing commas are not allowed in JSONC [fatal]", ); expect(wrong.stderr).toContain('Key "languageOptions": allowTrailingCommas must be a boolean if provided.'); @@ -1621,7 +1644,7 @@ describe.concurrent("bun lint with the built-in JSON languages", () => { expect(elsewhere.exitCode).toBe(2); }); - test("--stdin, and a format that shows the code", async () => { + test("--stdin works, also with a format that shows the code", async () => { using dir = tempDir("bun-lint-js-parsers", json); const run = async (format: string) => { await using proc = spawn({ @@ -1783,7 +1806,8 @@ describe.concurrent("bun lint with the built-in JSON languages", () => { expect(result.stderr).toContain("the eslint package linted 1 files"); }); - // A rule that needs eslint can be turned on in the config or by a comment in the file. Either way the run goes on. + // A rule that needs eslint can be turned on in the config or by a comment in the file. Either way the run + // continues. describe("if eslint isn't installed, the file is skipped with a warning and the rest is linted", () => { const languages = { JSON: { @@ -1791,7 +1815,7 @@ describe.concurrent("bun lint with the built-in JSON languages", () => { good: "good.jsonc", text: `${text}\n`, comment: '/* eslint no-irregular-whitespace: "error" */', - // The comment that disables nothing is what `--fix` removes. + // `--fix` removes the unused disable comment. fixable: '{\n "a": 1 // eslint-disable-line json/no-duplicate-keys\n}\n', fixed: '{\n "a": 1 \n}\n', project: (more: string) => ({ ...jsonPackage(), "eslint.config.mjs": jsonConfig(more) }), @@ -1949,7 +1973,7 @@ describe.concurrent("bun lint with the built-in JSON languages", () => { }; const fence = (language: string, code: string) => `\`\`\`${language}\n${code}\n\`\`\`\n\n`; - test("is named in the warning, and the file's other blocks are reported", async () => { + test("is listed in the warning, and the file's other blocks are reported", async () => { const files = { ...project, "a.md": [ @@ -1979,7 +2003,7 @@ describe.concurrent("bun lint with the built-in JSON languages", () => { expect(result.exitCode).toBe(2); }); - test("--fix fixes the other blocks, and names the block once", async () => { + test("--fix fixes the other blocks, and the warning lists the block once", async () => { const files = { ...project, "a.md": fence("js", "var a = 1; var b = 2;") + fence("css", "a {}") }; const result = await lint(files, ["--fix", "a.md"], ["a.md"]); expect(result.files["a.md"]).toBe(fence("js", "let a = 1; let b = 2;") + fence("css", "a {}")); @@ -1989,7 +2013,7 @@ describe.concurrent("bun lint with the built-in JSON languages", () => { expect(result.exitCode).toBe(2); }); - test("with a name, which is the whole file: the warning names the file", async () => { + test("if a named block is the whole file, the warning lists the file", async () => { const result = await lint({ ...project, "b.txt": "text\n", "b.js": "var c;\n" }, [ "-f", "json", @@ -2003,8 +2027,8 @@ describe.concurrent("bun lint with the built-in JSON languages", () => { expect(result.exitCode).toBe(2); }); - // ESLint skips such a block too, and says nothing. - test("is skipped without a warning if no config object is for its name", async () => { + // ESLint silently skips a block like this too. + test("is skipped without a warning if no config object matches its name", async () => { const languages = ["ts", "yaml", "json", "sh", "html", "py", "rs", "toml", "vue", "scss"]; const readme = languages.map(language => fence(language, "a {}")).join(""); const result = await lint({ ...project, "README.md": fence("js", "let a;") + readme }, [ @@ -2268,7 +2292,7 @@ describe.concurrent("bun lint with built-in Markdown", () => { ); }); - test("noInlineConfig, --no-inline-config and --report-unused-disable-directives-severity", async () => { + test("noInlineConfig, --no-inline-config and --report-unused-disable-directives-severity work", async () => { const files = { ...markdownPackage(), "eslint.config.mjs": markdownConfig(`{ files: ["no.md"], linterOptions: { noInlineConfig: true } }`), @@ -2382,7 +2406,7 @@ describe.concurrent("bun lint with built-in Markdown", () => { expect([config.exitCode, comment.exitCode]).toEqual([2, 2]); }); - test("--fix, after a byte order mark and with CRLF", async () => { + test("--fix works after a byte order mark and with CRLF", async () => { const text = `${mark}#Ünï 😀\r\n\r\n** a** and (b)[c] and https://example.com and [d](e)\r\n\r\n[e]: f\r\n`; const result = await lint({ ...project, "a.gfm.md": text }, ["--fix", "."], ["a.gfm.md"]); expect(result.files).toEqual({ @@ -2391,7 +2415,7 @@ describe.concurrent("bun lint with built-in Markdown", () => { expect(result.exitCode).toBe(0); }); - test("--stdin, and the formats", async () => { + test("--stdin works with stylish, unix and pretty", async () => { using dir = tempDir("bun-lint-js-parsers", project); const run = async (format: string) => { await using proc = spawn({ @@ -2483,6 +2507,62 @@ describe.concurrent("bun lint with built-in Markdown", () => { `); }); + describe("markdown/no-space-in-emphasis", () => { + const options = `{ files: ["**/*.md"], rules: { "markdown/no-space-in-emphasis": ["error", { checkStrikethrough: true }] } }`; + const files = { ...markdownPackage(), "eslint.config.mjs": markdownConfig(options, "[]") }; + + // The plugin pairs a paragraph's first marker with the second and the third with the fourth, regardless of the text + // around them. It reports every line below through the table, and its fix changes the rendered text: `2 *3* 4`, + // `*.ts,*.tsx`. + test("ignores stars and underscores that are plain text", async () => { + const text = [ + "The area is 2 * 3 * 4 units.", + "x = a * b + c * d", + 'globs: "*.ts, *.tsx, *.html, *.css"', + "Matches **/*.js, **/*.mjs and src/* files.", + "Prints [[ cyclic ref *1 ]] and then [[ cyclic ref *2 ]].", + "In C: char *a, *b; and x = *p * 2;", + "f(*args, **kwargs) and g(*a, **k)", + "/* one comment */ and (* another *)", + "This is * ambiguous * too.", + "Will _flag on _words, and words* with asterisks* after them.", + "About ~ 5 or ~ 10.", + "# 2 * 3 * 4", + "| a * b * c |\n| --------- |\n| 1 * 2 * 3 |", + "`*.ts, *.tsx` and `2 * 3 * 4`", + "See https://example.com/*/a and https://example.com/*/b.", + ].join("\n\n"); + const result = await lint({ ...files, "a.gfm.md": `${text}\n` }, ["--fix", "-f", "json", "."], ["a.gfm.md"]); + expect(summary(result.raw)).toBe(""); + expect(result.files).toEqual({ "a.gfm.md": `${text}\n` }); + expect(result.exitCode).toBe(0); + }); + + test.each([ + ["This is ** important**.", "This is **important**."], + ["This is **important **.", "This is **important**."], + ["This is ** important ** too.", "This is **important** too."], + ["This is _important _.", "This is _important_."], + ["This is _ important _ too.", "This is _important_ too."], + ["This is *** very important***.", "This is ***very important***."], + ["One-sided *broken emphasis *", "One-sided *broken emphasis*"], + ["(*broken *)", "(*broken*)"], + ["(* broken*)", "(*broken*)"], + ["**`code` **", "**`code`**"], + ["Follow ** [a link](b)**", "Follow **[a link](b)**"], + ["**Several ** in **one ** line.", "**Several** in **one** line."], + ["2 * 3 is ** important**.", "2 * 3 is **important**."], + ["This is ~~ gone~~.", "This is ~~gone~~."], + ["# A ** heading**", "# A **heading**"], + ])("--fix turns %j into emphasis", async (before, after) => { + expect(Bun.markdown.html(before)).not.toMatch(/<(em|strong|del)>/); + expect(Bun.markdown.html(after)).toMatch(/<(em|strong|del)>/); + const result = await lint({ ...files, "a.gfm.md": `${before}\n` }, ["--fix", "."], ["a.gfm.md"]); + expect(result.files).toEqual({ "a.gfm.md": `${after}\n` }); + expect(result.exitCode).toBe(0); + }); + }); + // The rules are only as good as the tree. `conformance/markdown-trees.mjs` recorded the plugin's trees. test.skipIf(!hasTestRunner)( "every example in the CommonMark and GFM specs parses to the same tree as with the plugin's parser", @@ -2668,7 +2748,7 @@ const oxlintrc = JSON.stringify({ }, }); -// `file line:column rule` of oxlint's JSON. +// Returns `file line:column rule` for each diagnostic in oxlint's JSON format. const diagnostics = (json: string) => JSON.parse(json) .diagnostics.map((it: any) => `${it.filename} ${it.labels[0].span.line}:${it.labels[0].span.column} ${it.code}`) @@ -2722,7 +2802,7 @@ debugger; @@ -2733,9 +2813,9 @@ debugger; }; describe.concurrent("bun lint with an .oxlintrc.json", () => { - test("lints the scripts in .vue, .svelte and .astro files, as oxlint does", async () => { + test("lints the scripts in .vue, .svelte and .astro files like oxlint", async () => { const result = await lint(scripts, ["-f", "json"]); - // What oxlint 1.80 reports. + // This is what oxlint 1.80 reports. expect(diagnostics(result.raw)).toMatchInlineSnapshot(` "a.vue 14:15 eslint(no-undef) a.vue 15:22 eslint(no-var) @@ -2757,9 +2837,9 @@ describe.concurrent("bun lint with an .oxlintrc.json", () => { expect(result.exitCode).toBe(1); }); - test("--fix fixes the scripts where they are", async () => { + test("--fix fixes the scripts in place", async () => { const result = await lint(scripts, ["--fix", "-f", "json"], ["a.vue", "b.svelte", "c.astro", "d.vue"]); - // The bytes that oxlint 1.87 writes. + // These are the exact bytes oxlint 1.87 writes. expect(result.files).toMatchInlineSnapshot(` { "a.vue": diff --git a/test/cli/lint/js-plugins.test.ts b/test/cli/lint/js-plugins.test.ts index dbe1f131d9cd..705701d71fc9 100644 --- a/test/cli/lint/js-plugins.test.ts +++ b/test/cli/lint/js-plugins.test.ts @@ -45,7 +45,7 @@ async function lint( stderr: "pipe", }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - // Where a run ends with an error, or dies, the assertion that fails is often about something else. + // If a run fails or crashes, the assertion that fails is often about something else, so print the real cause. if (exitCode !== 0 && exitCode !== 1) console.error(`bun lint ${args.join(" ")}: exit code ${exitCode}\n${stderr}`); return { raw: stdout, @@ -62,9 +62,9 @@ const oxlintrc = (config: object) => // Each thread that lints a file starts a VM, which takes seconds in a debug build. const timeout = isDebug || isASAN ? 120_000 : 10_000; -// As under ESLint 10.12.0. +// Same as under ESLint 10.12.0. test.concurrent( - "the .env of the project is not in `process.env` of a plugin, and what is inherited is", + "a plugin's `process.env` has the inherited variables but not the project's .env", async () => { const files = { ".env": "FROM_FILE=1\n", @@ -81,7 +81,7 @@ test.concurrent( timeout, ); -// Reports every identifier called `foo`, with what the API has to say about it. +// Reports every identifier called `foo`, using most of the report API. const noFoo = ` export default { meta: { name: "eslint-plugin-demo" }, @@ -114,9 +114,9 @@ export default { }; `; -describe.concurrent("bun lint with plugins in JavaScript", () => { +describe.concurrent("bun lint with JavaScript plugins", () => { test( - "jsPlugins of an .oxlintrc.json: messages, data, options with the defaults of the schema", + "jsPlugins in an .oxlintrc.json: messages, data, and options with the schema's defaults", async () => { const { stdout, exitCode } = await lint( { @@ -146,7 +146,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "--fix applies the fixes of a rule, also behind characters that are not ASCII", + "--fix applies a rule's fixes, also after non-ASCII characters", async () => { const { files, exitCode } = await lint( { @@ -165,7 +165,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { // https://github.com/oven-sh/bun/issues/45154 test( - "a package in jsPlugins whose `exports` has nothing but `import`", + "loads a package in jsPlugins whose `exports` only has an `import` condition", async () => { const { stdout, exitCode } = await lint( { @@ -187,7 +187,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "comments disable and configure a rule of a plugin", + "comments disable and configure a plugin's rule", async () => { const { stdout, exitCode } = await lint( { @@ -208,7 +208,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "selectors, :exit and the order of the listeners", + "supports selectors and :exit, and calls listeners in order", async () => { const plugin = ` export default { @@ -251,7 +251,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "tokens, comments, scopes and locations", + "provides tokens, comments, scopes and locations", async () => { const plugin = ` export default { @@ -330,9 +330,10 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { timeout, ); - // As with oxlint 1.87: the mark is on the plugin's variable, and oxlint's own rules have their own. + // Same as oxlint 1.87: the mark is set on the plugin's copy of the variable, and oxlint's own rules have a separate + // one. test( - "a variable that a rule marks as used is still unused for oxlint's no-unused-vars", + "oxlint's no-unused-vars still reports a variable that a plugin's rule marks as used", async () => { const plugin = ` export default { @@ -369,7 +370,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "createOnce, before and after of oxlint's API", + "supports createOnce, before and after from oxlint's API", async () => { const plugin = ` let created = 0; @@ -416,9 +417,9 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { timeout, ); - // The two reports are oxlint 1.87's. + // oxlint 1.87 prints the same two reports. test( - "after runs once for a file, also when another rule's create threw for the file before it", + "after runs once per file, even if another rule's create threw for the previous file", async () => { const hooks = ` let calls = 0; @@ -474,7 +475,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "a plugin in TypeScript, one from a package, one with an alias", + "loads a TypeScript plugin, a plugin from a package, and a plugin with an alias", async () => { const rule = (message: string) => `{ create(context) { return { Program(node) { context.report({ node, message: ${JSON.stringify(message)} }); } }; } }`; @@ -503,9 +504,9 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { timeout, ); - // As `react/jsx-one-expression-per-line` asks. + // `react/jsx-one-expression-per-line` calls it like this. test( - "isSpaceBetweenTokens looks into the text between two elements, isSpaceBetween does not", + "isSpaceBetweenTokens looks inside the text between two elements, and isSpaceBetween doesn't", async () => { const { stdout, exitCode } = await lint( { @@ -534,7 +535,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { timeout, ); - // Nothing of it is built in. + // None of its rules are built in. test.each([ [ "eslint.config.mjs", @@ -548,7 +549,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { "a.js:1:1: of the package [Error/regexp(no-dupe-disjunctions)]", ], ])( - "eslint-plugin-regexp is a plugin like any other, the package of the project runs: %s", + "eslint-plugin-regexp is treated like any other plugin, so the project's package runs: %s", async (name, configuration, printed) => { const { stdout, stderr, exitCode } = await lint( { @@ -568,13 +569,14 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { timeout, ); - // To oxlint `n`, which a plugin can be called, and `node`, which is built in, are two plugins. What oxlint 1.87 prints, sorted. - const calledN = { + // To oxlint, a JavaScript plugin named `n` and the built-in `node` are two separate plugins. The expected lines are + // what oxlint 1.87 prints, sorted. + const pluginN = { "n.js": `const rule = message => ({ create: context => ({ BinaryExpression(node) { context.report({ node, message }); } }) }); export default { meta: { name: "eslint-plugin-n" }, rules: { "no-path-concat": rule("of the package"), "only-there": rule("only there") } };`, "a.js": `export const p = __dirname + "/x";\n`, }; - const besideNode = (more: object) => + const withBuiltInNode = (more: object) => JSON.stringify({ categories: { correctness: "off" }, plugins: ["node"], jsPlugins: ["./n.js"], ...more }); test.each([ [ @@ -587,7 +589,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { 1, ], [ - "both are on, the other way round", + "both are on, in the opposite order", { "rules": { "node/no-path-concat": "warn", "n/no-path-concat": "error" } }, [ "a.js:1:18: Use `path.join()` or `path.resolve()` instead of string concatenation [Warning/node(no-path-concat)]", @@ -596,7 +598,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { 1, ], [ - "only what is built in", + "only the built-in rule is on", { "rules": { "node/no-path-concat": "warn" } }, [ "a.js:1:18: Use `path.join()` or `path.resolve()` instead of string concatenation [Warning/node(no-path-concat)]", @@ -604,19 +606,19 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { 0, ], [ - "only the plugin's", + "only the plugin's rule is on", { "rules": { "n/no-path-concat": "warn" } }, ["a.js:1:18: of the package [Warning/n(no-path-concat)]"], 0, ], [ - "node is not among the plugins", + "node isn't in `plugins`", { "plugins": [], "rules": { "n/no-path-concat": "warn", "node/no-path-concat": "error" } }, ["a.js:1:18: of the package [Warning/n(no-path-concat)]"], 0, ], [ - "a category turns on what is built in", + "a category turns on the built-in rule", { "categories": { "correctness": "off", "restriction": "warn" }, "rules": { "n/only-there": "error" } }, [ "a.js:1:18: Use `path.join()` or `path.resolve()` instead of string concatenation [Warning/node(no-path-concat)]", @@ -625,7 +627,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { 1, ], [ - "an override turns off what is built in", + "an override turns off the built-in rule", { "rules": { "n/no-path-concat": "error", "node/no-path-concat": "warn" }, "overrides": [{ "files": ["*.js"], "rules": { "node/no-path-concat": "off" } }], @@ -634,7 +636,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { 1, ], [ - "an override turns off the plugin's", + "an override turns off the plugin's rule", { "rules": { "n/no-path-concat": "error", "node/no-path-concat": "warn" }, "overrides": [{ "files": ["*.js"], "rules": { "n/no-path-concat": "off" } }], @@ -645,9 +647,9 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { 0, ], ] as [string, object, string[], number][])( - "a plugin that is called n beside the node that is built in: %s", + "a plugin named n alongside the built-in node plugin: %s", async (_, more, expected, exitCode) => { - const result = await lint({ ...calledN, ".oxlintrc.json": besideNode(more) }, ["-f", "unix", "a.js"]); + const result = await lint({ ...pluginN, ".oxlintrc.json": withBuiltInNode(more) }, ["-f", "unix", "a.js"]); expect( result.stdout .split("\n") @@ -659,12 +661,16 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { timeout, ); - // As oxlint 1.87, three runs of three. + // Same as oxlint 1.87, in three runs out of three. test( - "at one place, what is built in comes before what a plugin reports", + "at the same position, built-in rules' reports come before a plugin's", async () => { const rules = { "n/no-path-concat": "error", "n/only-there": "warn", "node/no-path-concat": "warn" }; - const { stdout } = await lint({ ...calledN, ".oxlintrc.json": besideNode({ rules }) }, ["-f", "unix", "a.js"]); + const { stdout } = await lint({ ...pluginN, ".oxlintrc.json": withBuiltInNode({ rules }) }, [ + "-f", + "unix", + "a.js", + ]); expect([...stdout.matchAll(/^a\.js:1:18: .* \[\w+\/(.*)\]$/gm)].map(it => it[1])).toEqual([ "node(no-path-concat)", "n(no-path-concat)", @@ -675,34 +681,34 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "a plugin that is called n beside the node that is built in: --print-config has what is built in, as oxlint's", + "a plugin named n alongside the built-in node plugin: --print-config only lists the built-in rule, like oxlint", async () => { const rules = { "n/no-path-concat": "error", "node/no-path-concat": "warn" }; - const { raw } = await lint({ ...calledN, ".oxlintrc.json": besideNode({ rules }) }, ["--print-config"]); + const { raw } = await lint({ ...pluginN, ".oxlintrc.json": withBuiltInNode({ rules }) }, ["--print-config"]); expect(JSON.parse(raw).rules).toEqual({ "node/no-path-concat": "warn" }); }, timeout, ); - describe("a note says which rules ran in JavaScript that are built in", () => { + describe("the note about rules that ran in JavaScript although they're built in", () => { const rules = { "n/no-path-concat": "error" }; const packaged = (version: string) => ({ - "a.js": calledN["a.js"], + "a.js": pluginN["a.js"], "node_modules/eslint-plugin-n/package.json": JSON.stringify({ name: "eslint-plugin-n", version, type: "module", main: "n.js", }), - "node_modules/eslint-plugin-n/n.js": calledN["n.js"], + "node_modules/eslint-plugin-n/n.js": pluginN["n.js"], }); const notes = async (files: Record, more: object, ...flags: string[]) => - (await lint({ ...files, ".oxlintrc.json": besideNode(more) }, [...flags, "a.js"])).stderr + (await lint({ ...files, ".oxlintrc.json": withBuiltInNode(more) }, [...flags, "a.js"])).stderr .split("\n") .filter(it => it.startsWith("note: ") || it.startsWith(" To use ")); test( - "a package, with its version", + "mentions a package with its version", async () => { const jsPlugins = ["eslint-plugin-n"]; expect(await notes(packaged("17.16.2"), { jsPlugins, rules })).toEqual([ @@ -718,14 +724,14 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "a file, and rules that are not built in", + "mentions a file, and says to keep it for rules that aren't built in", async () => { const more = { "n/no-new-require": "warn", "n/only-there": "error", "n/no-sync": "off" }; - const plugin = calledN["n.js"].replace( + const plugin = pluginN["n.js"].replace( `"only-there"`, `"no-new-require": rule("new"), "no-sync": rule("sync"), "only-there"`, ); - expect(await notes({ ...calledN, "n.js": plugin }, { rules: { ...rules, ...more } })).toEqual([ + expect(await notes({ ...pluginN, "n.js": plugin }, { rules: { ...rules, ...more } })).toEqual([ `note: 2 "n" rules ran in JavaScript from ./n.js, but bun lint has them built in (version 18.4.1)`, ` To use the built-in rules, rename them to "node/.." and add "node" to "plugins". Keep ./n.js for the other rule. Reports may differ.`, ]); @@ -734,27 +740,28 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "nothing where nobody reads it, and nothing where there is nothing to say", + "isn't printed in quiet or machine-readable output, if the run passes, or if no such rule ran", async () => { for (const flags of [["--quiet"], ["--silent"], ["-f", "json"], ["-f", "unix"], ["-f", "github"]]) { - expect([flags, await notes(calledN, { rules }, ...flags)]).toEqual([flags, []]); + expect([flags, await notes(pluginN, { rules }, ...flags)]).toEqual([flags, []]); } - expect(await notes(calledN, { rules: { "n/only-there": "error" } })).toEqual([]); - expect(await notes(calledN, { rules: { "n/no-path-concat": "off", "node/no-path-concat": "error" } })).toEqual( + expect(await notes(pluginN, { rules: { "n/no-path-concat": "warn" } })).toEqual([]); + expect(await notes(pluginN, { rules: { "n/only-there": "error" } })).toEqual([]); + expect(await notes(pluginN, { rules: { "n/no-path-concat": "off", "node/no-path-concat": "error" } })).toEqual( [], ); - expect(await notes(calledN, { jsPlugins: [], rules })).toEqual([]); + expect(await notes(pluginN, { jsPlugins: [], rules })).toEqual([]); }, timeout, ); }); test( - "a plugin that is called n beside the node that is built in: each has its name in oxlint-suppressions.json", + "a plugin named n alongside the built-in node plugin: each is listed under its own name in oxlint-suppressions.json", async () => { const rules = { "n/no-path-concat": "error", "node/no-path-concat": "error" }; const { files } = await lint( - { ...calledN, ".oxlintrc.json": besideNode({ rules }) }, + { ...pluginN, ".oxlintrc.json": withBuiltInNode({ rules }) }, ["--suppress-all", "a.js"], ["oxlint-suppressions.json"], ); @@ -766,7 +773,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "options that the schema refuses, and a rule that does not exist", + "rejects options that the schema doesn't allow, and a rule that doesn't exist", async () => { const files = { "plugin.mjs": noFoo, "a.js": "1;\n" }; const wrongOptions = await lint( @@ -849,8 +856,8 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { lint(files, ["-f", "json", "a.js"]), lint(files, ["-f", "stylish", "a.js"]), ]); - const places = JSON.parse(json.raw)[0].messages.map((it: any) => [it.message, it.line, it.column]); - expect(places).toEqual([ + const positions = JSON.parse(json.raw)[0].messages.map((it: any) => [it.message, it.line, it.column]); + expect(positions).toEqual([ ["loc 1", null, null], ["loc 2", null, null], ["loc 4", null, 3], @@ -869,9 +876,9 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { timeout, ); - // As under ESLint 10.12.0. + // Same as under ESLint 10.12.0. test.concurrent( - "`-f json` has the `data` of a suggestion that has a `desc`", + "`-f json` includes the `data` of a suggestion that has a `desc`", async () => { const files = { "eslint.config.mjs": ` @@ -895,7 +902,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { timeout, ); - // As under ESLint 10.12.0 with eslint-plugin-react-hooks 7.1.1, which passes `desc` and `fix` only. + // Same as under ESLint 10.12.0 with eslint-plugin-react-hooks 7.1.1, which only passes `desc` and `fix`. test.concurrent( "`-f json` has no `data` for a built-in rule's suggestion that only has a `desc` upstream", async () => { @@ -917,9 +924,9 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { timeout, ); - // ESLint 10.12.0 and oxlint 1.87.0 call `fix`, and the `fix` of each suggestion, when a problem is reported, whoever reads what - // they return. - describe("a rule is asked for its fixes whatever is printed", () => { + // ESLint 10.12.0 and oxlint 1.87.0 call `fix`, and each suggestion's `fix`, as soon as a problem is reported, whether + // or not anything uses the result. + describe("a rule's fixers are called regardless of the output format", () => { const rules = `{ "fix-throws": { meta: { fixable: "code" }, @@ -955,7 +962,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { "eslint.config.mjs": `export default [{ plugins: { demo: { rules: ${rules} } }, rules: { "demo/${rule}": "${severity}" } }];`, "a.js": "var a = 1;\n", }); - // Named, for `--silent` is a flag of oxlint. + // Pass the config explicitly, because `--silent` is an oxlint flag. const eslint = (rule: string, flags: string[], severity?: string) => lint(forEslint(rule, severity), ["-c", "eslint.config.mjs", ...flags, "a.js"]); const thrown = (rule: string, message: string) => ({ @@ -963,7 +970,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { stderr: `error: ${message}\nOccurred while linting /a.js:1\nRule: "demo/${rule}"`, exitCode: 2, }); - const said = ({ stdout, stderr, exitCode }: Awaited>) => ({ stdout, stderr, exitCode }); + const outcome = ({ stdout, stderr, exitCode }: Awaited>) => ({ stdout, stderr, exitCode }); test.each([ [[]], @@ -973,14 +980,14 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { [["--silent"]], [["--quiet", "-f", "unix"]], ])( - "one that throws ends the run of ESLint's flavour: %j", + "with an ESLint config, a fixer that throws ends the run: %j", async flags => { const [fix, suggestion, notFixable] = await Promise.all( ["fix-throws", "suggestion-throws", "not-fixable"].map(rule => eslint(rule, flags)), ); - expect(said(fix)).toEqual(thrown("fix-throws", "The fixer threw.")); - expect(said(suggestion)).toEqual(thrown("suggestion-throws", "The suggestion threw.")); - expect(said(notFixable)).toEqual( + expect(outcome(fix)).toEqual(thrown("fix-throws", "The fixer threw.")); + expect(outcome(suggestion)).toEqual(thrown("suggestion-throws", "The suggestion threw.")); + expect(outcome(notFixable)).toEqual( thrown("not-fixable", 'Fixable rules must set the `meta.fixable` property to "code" or "whitespace".'), ); }, @@ -988,20 +995,20 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "with --quiet a rule that warns does not run, unless the warnings are counted", + "with --quiet, a rule set to warn doesn't run unless --max-warnings counts the warnings", async () => { const [quiet, counted] = await Promise.all([ eslint("fix-throws", ["--quiet", "-f", "unix"], "warn"), eslint("fix-throws", ["--quiet", "--max-warnings", "0", "-f", "unix"], "warn"), ]); expect({ stdout: quiet.stdout, exitCode: quiet.exitCode }).toEqual({ stdout: "", exitCode: 0 }); - expect(said(counted)).toEqual(thrown("fix-throws", "The fixer threw.")); + expect(outcome(counted)).toEqual(thrown("fix-throws", "The fixer threw.")); }, timeout, ); test( - "what a fixer does shows in what the rule reports afterwards", + "a fixer's side effects are visible to the rule's later reports", async () => { const { stdout, exitCode } = await eslint("counts", ["-f", "unix"]); expect(stdout).toBe( @@ -1013,7 +1020,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test.each([[[]], [["-f", "unix"]], [["-f", "json"]]])( - "one that throws is reported for the file in oxlint's flavour: %j", + "with an oxlint config, a fixer that throws is reported for the file: %j", async flags => { const { stdout, exitCode } = await lint( { @@ -1030,13 +1037,13 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { timeout, ); - // `supportsAutofix: false` is ESLint's `disableFixes`: then, and only then, no rule is asked. + // `supportsAutofix: false` sets ESLint's `disableFixes`, which is the only case where fixers aren't called. test.each([ [true, 'fix={"range":[10,10],"text":"/**/"} suggestions=1', 'fix={"range":[0,3],"text":"let"} suggestions=0'], [false, "fix=null suggestions=0", "fix=null suggestions=0"], ])( - "`postprocess` is given the fixes whatever is printed: supportsAutofix: %j", - async (supportsAutofix, ofPlugin, builtIn) => { + "`postprocess` gets the fixes regardless of the output format: supportsAutofix: %j", + async (supportsAutofix, fromPlugin, builtIn) => { const files = { "eslint.config.mjs": ` const fixes = { @@ -1066,7 +1073,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { const { stdout, exitCode } = await lint(files, ["-f", "unix", "a.x"]); expect(stdout).toBe( [ - `/a.x:1:1: bad ${ofPlugin} [Error/demo/fixes]`, + `/a.x:1:1: bad ${fromPlugin} [Error/demo/fixes]`, `/a.x:1:1: Unexpected var, use let or const instead. ${builtIn} [Error/no-var]`, "", "2 problems", @@ -1079,7 +1086,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { }); test( - "a plugin that cannot be loaded", + "reports a plugin that can't be loaded", async () => { const run = (plugin: string, specifier = "./broken.mjs") => lint({ ".oxlintrc.json": oxlintrc({ jsPlugins: [specifier] }), "broken.mjs": plugin, "a.js": "1;\n" }, [ @@ -1114,7 +1121,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "what a plugin prints is printed, and process.exit() ends the run", + "a plugin's output is printed, and process.exit() ends the run", async () => { const plugin = ` export default { @@ -1149,7 +1156,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "the exit handlers of a plugin run after the report, once for each thread that has loaded it", + "a plugin's exit handlers run after the report, once for each thread that loaded it", async () => { const plugin = ` let files = 0; @@ -1192,7 +1199,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "what a plugin keeps about a file under its sourceCode or context is not there for the next file", + "each file gets a new sourceCode and context, so a plugin's caches keyed by them don't leak between files", async () => { const plugin = ` const bySourceCode = new WeakMap(); @@ -1235,7 +1242,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "code paths, default options that are not JSON, and a plugin whose rules are in no fixed order", + "supports code paths, non-JSON default options, and a plugin whose rules have no fixed order", async () => { const plugin = ` const rules = {}; @@ -1272,7 +1279,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { }, ["-f", "unix"], ); - // The events are what ESLint 10 gives this rule. + // ESLint 10 sends this rule the same events. const events = "start program s1_1 start function s2_1 s2_2 s2_4 unreachable s2_6"; expect(stdout.split("\n").slice(0, 3)).toEqual([ `a.js:1:1: paths/a a Infinity ${events} [Error/paths(a)]`, @@ -1284,13 +1291,13 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "more files than threads: every file gets its reports, and nothing else is said", + "with more files than threads, every file gets exactly its own reports", async () => { const files: Record = { ".oxlintrc.json": oxlintrc({ jsPlugins: ["./plugin.mjs"], rules: { "demo/no-foo": "error" } }), "plugin.mjs": noFoo, }; - // The file number `i` has `i % 5` of them. + // File number `i` has `i % 5` of them. for (let i = 0; i < 300; i++) files[`src/${i}.ts`] = `export const x: number = ${i};\n` + "foo();\n".repeat(i % 5); for (const threads of isDebug || isASAN ? ["3"] : ["1", "3", "16"]) { @@ -1310,7 +1317,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "plugins of an eslint.config.js: imported, and defined in the file", + "plugins in an eslint.config.js can be imported or defined in the file", async () => { const { stdout, exitCode } = await lint( { @@ -1349,7 +1356,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { timeout, ); - // As much of the package as a configuration uses. + // A stand-in for the package with only what a config uses. const compat = { "node_modules/@eslint/compat/package.json": JSON.stringify({ name: "@eslint/compat", @@ -1368,7 +1375,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { }; test( - "the configuration file is not run again for a plugin that a module exports, also through fixupPluginRules", + "doesn't run the config file again for a plugin that a module exports, even through fixupPluginRules", async () => { const { stdout, stderr, exitCode } = await lint( { @@ -1394,7 +1401,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { 3 problems" `); - // What the process prints that evaluates the file is not shown. + // Output from the process that evaluates the config file isn't shown. expect(stderr).not.toContain("The configuration file runs."); expect(stderr).toMatch(/JavaScript: [12] engines loaded [12] modules, /); expect(exitCode).toBe(1); @@ -1403,7 +1410,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "an engine runs the configuration file, for the files with a rule of a plugin that only it has", + "an engine runs the config file for files that need a plugin defined only in that file", async () => { const files: Record = { "eslint.config.mjs": ` @@ -1436,7 +1443,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "a rule is loaded from the module that exports it, without the plugin and its other rules", + "loads a rule from the module that exports it, without the plugin and its other rules", async () => { const rule = (name: string) => ` console.error("Loaded: the rule ${name}."); @@ -1471,9 +1478,10 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { timeout, ); - // What a process has one of, like the caches of the resolver, is made with its first VM, and not for several threads at a time. + // Per-process state, like the resolver's caches, is created with the first VM, and that isn't safe on several threads + // at once. test.skipIf(!isDebug)( - "no other engine starts before the first is there", + "no other engine starts before the first one is ready", async () => { const files: Record = { "eslint.config.mjs": ` @@ -1493,7 +1501,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { }); const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); const steps = [...stdout.matchAll(/a VM (begins|is made)/g)].map(it => it[1]); - // How many there are depends on the number of cores. + // The number of engines depends on the number of cores. expect(steps.filter(it => it === "begins").length).toBe(steps.filter(it => it === "is made").length); expect(steps.slice(0, 2)).toEqual(["begins", "is made"]); expect(exitCode).toBe(1); @@ -1502,7 +1510,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "what JSON cannot say: a RegExp in the options, a function in the settings. And rules can change their options", + "passes on non-JSON values (a RegExp in the options, a function in the settings), and rules can mutate their options", async () => { const { stdout, stderr, exitCode } = await lint( { @@ -1548,9 +1556,9 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { timeout, ); - // As `synckit` does it, which `eslint-plugin-prettier` is made with. + // This is what `synckit` does, which `eslint-plugin-prettier` is built on. test( - "a rule waits for a worker of its own on every thread that lints", + "a rule can block on its own worker on every linting thread", async () => { const files: Record = { "eslint.config.mjs": ` @@ -1608,10 +1616,10 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { timeout, ); - // As `@cspell/eslint-plugin` does it. With types the threads that lint begin anew for every project and every step of the - // checker, while the workers have Bun's pool read files. + // This is what `@cspell/eslint-plugin` does. With types, the linting threads are restarted for every project and + // every step of the checker, while the workers read files on Bun's thread pool. test( - "a rule waits for a worker of its own, which reads files, in projects with types", + "a rule can block on its own worker, which reads files, in projects with types", async () => { const files: Record = { "eslint.config.mjs": ` @@ -1673,7 +1681,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { using dir = tempDir("bun-lint-js-plugins", files); await using proc = spawn({ cmd: [bunExe(), "lint", "-f", "unix", "--threads", "4"], - // As many threads in a pool, however many cores there are. + // Fixes the thread pool's size, regardless of the number of cores. env: { ...env, GOMAXPROCS: "8" }, cwd: String(dir), stdin: "ignore", @@ -1682,18 +1690,18 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); const reports = stdout.split("\n").filter(it => it.endsWith(": 5 [Error/demo/length]")).length; - // With what it says. + // Include stderr so that a failure shows it. expect({ reports, exitCode, stderr }).toEqual({ reports: 128, exitCode: 1, stderr: expect.any(String) }); }, timeout, ); test( - "there are as many engines as pay, with types and without, and they report the same", + "starts only as many engines as are worth it, with and without types, and they report the same", async () => { - // `waits`: an engine stays in use with its first file until another engine has one. A thread only asks for an engine while - // the others are in use, and whether they are is otherwise up to how the threads happen to run. - const run = async (count: number, extension: string, size: number, threads: string, waits = false) => { + // With `blockFirstFile`, an engine stays busy with its first file until another engine has a file too. A thread + // only requests a new engine while the others are busy, which otherwise depends on thread scheduling. + const run = async (count: number, extension: string, size: number, threads: string, blockFirstFile = false) => { const files: Record = { "engines/.keep": "", "tsconfig.json": JSON.stringify({ compilerOptions: { noLib: true, types: [] } }), @@ -1712,7 +1720,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { import { readdirSync, writeFileSync } from "node:fs"; const engines = new URL("./engines/", import.meta.url); // Each engine evaluates the module once. - let isFirst = ${waits}; + let isFirst = ${blockFirstFile}; export default { rules: { seen: { create: context => ({ Program(node) { if (isFirst) { isFirst = false; @@ -1723,17 +1731,18 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { context.report({ node, message: "seen" }); } }) } } };`, }; - // One comment: thousands of them take a debug build minutes. + // A single comment, because thousands of them take a debug build minutes. const text = `foo;\n/*${Buffer.alloc(size, "x")}*/\n`; for (let i = 0; i < count; i++) files[`src/${i}.${extension}`] = text; - // How many engines fit depends on how much memory is free, which is up to the machine that runs this. + // The number of engines that fit depends on the machine's free memory, so set it explicitly. const variables = { BUN_LINT_MEMORY: String(64 * 2 ** 30) }; const args = ["-f", "unix", "--timing", "--threads", threads, "src"]; const { stdout, stderr, exitCode } = await lint(files, args, [], variables); expect(exitCode).toBe(1); return { stdout, engines: Number(/JavaScript: (\d+) engines/.exec(stderr)?.[1]) }; }; - // 24 files of 250 KB, which are not heavy yet, are 6 MB, which three engines are for. + // 24 files of 250 KB, which is just under the large-file limit, add up to 6 MB, which is enough for three + // engines. const [smallWithTypes, small, oneWithTypes, one, largeWithTypes, large] = await Promise.all([ run(24, "ts", 0, "8"), run(24, "js", 0, "8"), @@ -1755,7 +1764,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - 'a rule written for ESLint 8, and a plugin that is an ES module with an export "module.exports"', + 'runs a rule written for ESLint 8, and a plugin that\'s an ES module with a "module.exports" export', async () => { const { stdout, exitCode } = await lint( { @@ -1805,9 +1814,9 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "a rule that asks for types is taken out, the rest runs, and the run ends with an error that names it", + "a rule that requests types is skipped, the rest runs, and the run ends with an error that lists the rule", async () => { - // As `getParserServices` of @typescript-eslint/utils does it. + // This is what `getParserServices` in @typescript-eslint/utils does. const services = `context => { if (context.sourceCode.parserServices.program == null) { throw new Error("You have used a rule which requires type information, but don't have parserOptions set to generate type information for this file. See https://tseslint.com/typed-linting for enabling linting with type information.\\nParser: (unknown)"); @@ -1853,9 +1862,9 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { timeout, ); - // As `eslint-plugin-import` does it to read the modules that a file imports. + // This is how `eslint-plugin-import` parses the modules that a file imports. test.each(["parser", "* as parser"])( - "a rule parses a text of its own with languageOptions.parser, which is loaded when it is called: import %s", + "a rule can parse other text with languageOptions.parser, which is loaded on first call: import %s", async imported => { const { stdout, exitCode } = await lint( { @@ -1896,9 +1905,9 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { timeout, ); - // As `eslint-plugin-rulesdir` and the plugin of nodejs/node: without the assignment the plugin has no rules. + // Like `eslint-plugin-rulesdir` and nodejs/node's plugin: without the assignment, the plugin has no rules. test( - "a plugin that the configuration file tells where its rules are", + "a plugin whose rules directory is set by the config file", async () => { const rule = (message: string) => `module.exports = { create: context => ({ Program(node) { context.report({ node, message: "${message}" }); } }) };`; @@ -1944,9 +1953,9 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { timeout, ); - // As `indent` of typescript-eslint 5, which hands ESLint's `indent` an object literal for a mapped type. + // Like typescript-eslint 5's `indent`, which passes ESLint's `indent` a made-up object literal for a mapped type. test( - "the nodes that typescript-estree makes for deprecated properties, and nodes that a rule makes up", + "supports the nodes typescript-estree creates for deprecated properties, and nodes that a rule makes up", async () => { const { stdout, exitCode } = await lint( { @@ -1993,9 +2002,10 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { timeout, ); - // `require()` refuses such a module, and some without `await`: the rules of eslint-plugin-import-x in vitejs/vite. + // `require()` rejects a module like this, and some without `await`, such as eslint-plugin-import-x's rules in + // vitejs/vite. test( - "the module of a rule is loaded by import(), and alone", + "a rule's module is loaded with import(), and nothing else is loaded", async () => { const rule = (message: string) => `await 0;\nexport default { create: context => ({ Program(node) { context.report({ node, message: "${message}" }); } }) };`; @@ -2022,7 +2032,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "a plugin that waits for what never comes is an error", + "a plugin that awaits a promise that never settles is an error", async () => { const { stdout, stderr, exitCode } = await lint( { @@ -2039,7 +2049,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { ); test( - "a plugin that waits is loaded after a rule has left a rejection that nobody handles", + "a plugin with a top-level await still loads after a rule leaves an unhandled rejection", async () => { const reports = (message: string, before = "") => `{ create: context => ({ Program(node) { ${before} context.report({ node, message: "${message}" }); } }) }`; @@ -2070,7 +2080,7 @@ describe.concurrent("bun lint with plugins in JavaScript", () => { // The rows are what oxlint 1.87.0 and ESLint 10.12 report for these files with this plugin. test( - "a rule gets the text in JSX as it is written under oxlint, and with what `&` stands for under ESLint", + "a rule gets raw JSX text with an oxlint config, and text with `&` decoded with an ESLint config", async () => { const text = String.raw`export const a = (
    it.filename === name) .map(it => ({ ...it.labels[0].span, rule: it.code, message: it.message })), ); - expect(of("a.tsx")).toBe(sorted(written)); - expect(of("a.jsx")).toBe(sorted(written)); - expect(of("crlf.tsx")).toBe(sorted(written.replaceAll("\\n", "\\r\\n"))); + expect(of("a.tsx")).toBe(sorted(rawText)); + expect(of("a.jsx")).toBe(sorted(rawText)); + expect(of("crlf.tsx")).toBe(sorted(rawText.replaceAll("\\n", "\\r\\n"))); const configuration = ` import shows from "./plugin.mjs"; @@ -2163,9 +2173,9 @@ export default { timeout, ); - // What `@rushstack/eslint-patch` does when `eslint-config-next` loads it, in a package that is laid out as it is. + // This is what `@rushstack/eslint-patch` does when `eslint-config-next` loads it, in a package with the same layout. test( - "a configuration that looks for ESLint among the modules that have loaded it finds that of the project", + "a config that searches its parent modules for ESLint finds the project's ESLint", async () => { const files = { "node_modules/eslint/package.json": `{ "name": "eslint", "version": "9.0.0" }`, @@ -2197,7 +2207,7 @@ export default { import { createRequire } from "node:module"; export default [createRequire(import.meta.url)("eslint-config-mine")];`, "eslint.config.cjs": `module.exports = [require("eslint-config-mine")];`, - // An engine runs this one too: nothing else has the plugin. + // An engine runs this config file too, because the plugin is only defined there. "eslint.config.js": `module.exports = [require("eslint-config-mine"), { plugins: { own: ${own} }, rules: { "own/program": "error" } }];`, }; for (const [name, configuration] of Object.entries(configurations)) { @@ -2210,10 +2220,10 @@ export default { timeout, ); - // ESLint in Node.js gives up at 740: "Not enough stack space to parse input". So does the parser here between 300 and 400 in a - // debug build, whose frames are larger. + // ESLint in Node.js gives up at 740: "Not enough stack space to parse input". Bun's parser gives up between 300 and + // 400 in a debug build, which has larger stack frames. test( - "a rule goes through a tree that is 2,000 deep", + "a rule can traverse a tree that's 2,000 levels deep", async () => { const depth = isDebug || isASAN ? 200 : 2000; const { stdout, exitCode } = await lint( @@ -2236,7 +2246,7 @@ export default { timeout, ); - test("a path reaches a rule as the system writes it, also on Windows", async () => { + test("a rule gets paths with the system's separators, also on Windows", async () => { const source = readFileSync(join(import.meta.dir, "../../../src/lint/js_plugin/worker/paths.js"), "utf8"); const paths = ["C:/proj/src/a.js", "C:/proj/a.md/0_x.js", "//server/share/a.js", "/proj/a\\b.js"]; await using proc = spawn({ @@ -2265,9 +2275,9 @@ export default { expect(exitCode).toBe(0); }); - // What eslint-plugin-turbo does with them: `physicalFilename.startsWith(directoryOfTheWorkspace)`. + // eslint-plugin-turbo relies on this: `physicalFilename.startsWith(directoryOfTheWorkspace)`. test( - "context.filename and context.physicalFilename are what node:path makes of context.cwd", + "context.filename and context.physicalFilename are spelled like node:path joins from context.cwd", async () => { const where = `{ rules: { @@ -2294,8 +2304,8 @@ export default { }, }`; const imports = `import { join, relative, sep } from "node:path";`; - // The format is one that is the same whosever the configuration is. - const [ofOxlint, ofEslint] = await Promise.all([ + // This format is the same with either tool's config. + const [withOxlint, withEslint] = await Promise.all([ lint( { ".oxlintrc.json": oxlintrc({ jsPlugins: ["./plugin.mjs"], rules: { "where/is": "error" } }), @@ -2318,21 +2328,21 @@ export default { ["-f", "json-with-metadata", "src"], ), ]); - const said = ({ raw }: { raw: string }) => + const messagesOf = ({ raw }: { raw: string }) => (JSON.parse(raw).results as { messages: { message: string }[] }[]).flatMap(it => it.messages.map(it => JSON.parse(it.message)), ); const all = { isJoined: true, isInside: true, isPhysicalJoined: true, methods: true }; const file = { ...all, filename: ["src", "deep", "a.js"], physicalFilename: ["src", "deep", "a.js"] }; const block = { ...all, filename: ["src", "b.txt", "0_x.js"], physicalFilename: ["src", "b.txt"] }; - expect(said(ofOxlint)).toEqual([file]); - expect(said(ofEslint)).toEqual([block, file]); + expect(messagesOf(withOxlint)).toEqual([file]); + expect(messagesOf(withEslint)).toEqual([block, file]); }, timeout, ); test( - "fixes that take, give and replace the byte order mark", + "fixes can remove, add and replace the byte order mark", async () => { const rule = (test: string, fix: string) => `{ meta: { fixable: "code" }, create: context => ({ Program(node) { if (${test}) context.report({ node, message: "mark", fix: fixer => ${fix} }); } }) }`; @@ -2362,7 +2372,7 @@ export default { ); test( - "what is no UTF-8 is as long for the places of nodes as in the text", + "node ranges count invalid UTF-8 the same way as the decoded text", async () => { const files = { "eslint.config.mjs": `const p = { rules: { r: { meta: { fixable: "code" }, create: context => ({ VariableDeclarator({ id }) { @@ -2377,7 +2387,7 @@ export default { }; const { raw, exitCode } = await lint(files, ["-f", "json", "a.js"]); const [{ message, line, column }] = JSON.parse(raw)[0].messages; - // What ESLint 10.12 says. + // This is what ESLint 10.12 reports. expect({ message, line, column }).toEqual({ message: "oldName 35,42 oldName 35", line: 2, column: 7 }); expect(exitCode).toBe(1); const fixed = await lint(files, ["--fix", "a.js"], ["a.js"]); @@ -2387,7 +2397,7 @@ export default { ); test( - "what is no UTF-8 is as long for columns and for the fixes of native rules as in the text", + "columns and native rules' fix ranges count invalid UTF-8 the same way as the decoded text", async () => { const files = { "eslint.config.mjs": `export default [{ rules: { "no-var": "error", "no-debugger": "error" } }];`, @@ -2397,7 +2407,7 @@ export default { ), }; const { raw, exitCode } = await lint(files, ["-f", "json", "a.js"]); - // What ESLint 10.12 says. + // This is what ESLint 10.12 reports. expect(JSON.parse(raw)[0].messages.map(it => [it.ruleId, it.column, it.endColumn, it.fix?.range])).toEqual([ ["no-debugger", 21, 30, undefined], ["no-var", 31, 41, [30, 33]], @@ -2408,7 +2418,7 @@ export default { ); test( - "without rules in JavaScript there is no engine", + "doesn't start an engine if no rule runs in JavaScript", async () => { const { stderr, exitCode } = await lint( { "eslint.config.mjs": `export default [{ rules: { "no-debugger": "error" } }];`, "a.js": "debugger;\n" }, @@ -2420,9 +2430,9 @@ export default { timeout, ); - // The first regular expression of a configuration starts JavaScriptCore, before anybody knows how many VMs there are going to be. + // The first regular expression in a config initializes JavaScriptCore, before the number of VMs is known. test.skipIf(!isLinux || availableParallelism() < 2)( - "threads that compile beside a VM: with a few VMs, not with many, and as BUN_JSC_useConcurrentJIT says", + "concurrent JIT threads are on with a few VMs, off with many, and BUN_JSC_useConcurrentJIT overrides that", async () => { const files = (count: number) => ({ "eslint.config.mjs": ` @@ -2451,13 +2461,13 @@ export default { export default { rules: { helpers: { create: context => ({ Program: node => context.report({ node, message: "" + helpers() }) }) } }, };`, - // 200 of them are 16 MB, which five engines are for. + // 200 of them add up to 16 MB, which is enough for five engines. ...Object.fromEntries( Array.from({ length: count }, (_, i) => [`f${i}.js`, `1;\n/*${Buffer.alloc(80_000, "x")}*/\n`]), ), }); const helpers = async (count: number, variables?: Record) => { - // As on a machine with 8 cores. + // Behave as on a machine with 8 cores. const { raw } = await lint(files(count), ["--threads", "8", "-f", "json"], [], { GOMAXPROCS: "8", ...variables, @@ -2466,18 +2476,18 @@ export default { const reported = results.flatMap(it => it.messages.filter(message => message.ruleId === "threads/helpers")); return [...new Set(reported.map(it => it.message))]; }; - const [few, many, asked] = await Promise.all([ + const [few, many, forcedOn] = await Promise.all([ helpers(2), helpers(200), helpers(200, { BUN_JSC_useConcurrentJIT: "1" }), ]); - expect([few, many, asked]).toEqual([["1"], ["0"], ["1"]]); + expect([few, many, forcedOn]).toEqual([["1"], ["0"], ["1"]]); }, timeout, ); test( - "files of 256 KB and more all go to one engine, with types and without, however many threads there are", + "files of 256 KB or more all go to one engine, with and without types, with any number of threads", async () => { const run = async (heavy: number, extension: string, threads: string) => { const files: Record = { @@ -2501,7 +2511,7 @@ export default { const text = (size: number) => `foo;\n/*${Buffer.alloc(size, "x")}*/\n`; for (let i = 0; i < heavy; i++) files[`src/heavy${i}.${extension}`] = text(270_000); for (let i = 0; i < 24; i++) files[`src/light${i}.${extension}`] = text(250_000); - // Not as JSON, which has the text of each file in it. + // Not `-f json`, which includes each file's text. const { raw, exitCode } = await lint(files, ["-f", "unix", "--threads", threads, "src"]); expect(exitCode).toBe(1); const realmsOf = (name: string) => @@ -2525,9 +2535,9 @@ export default { timeout, ); - // A VM takes seconds to start in a debug build: beside the first no other pays for files like these. + // A VM takes seconds to start in a debug build, so a second one isn't worth it there for files like these. test.skipIf(isDebug || isASAN)( - "engines that grow over the memory that is for them are freed, and every file is linted", + "engines that outgrow their memory budget are freed, and every file is still linted", async () => { const run = async (count: number, threads: string) => { const files: Record = { @@ -2564,7 +2574,7 @@ export default { }; const text = `foo;\n/*${Buffer.alloc(250_000, "x")}*/\n`; for (let i = 0; i < count; i++) files[`src/${i}.js`] = text; - // Half of it is planned for the engines, and above three quarters one is freed. + // Half of this is budgeted for the engines, and above three quarters an engine is freed. const variables = { BUN_LINT_MEMORY: String(1 << 30) }; const { raw, stderr, exitCode } = await lint( files, @@ -2586,7 +2596,7 @@ export default { ); test( - "a file in which nothing occurs that is listened to: no listener is called, and who asks for the tree has it", + "in a file without any node a rule listens for, no listener is called, and `after` can still read the tree", async () => { const run = async (count: number, threads: string) => { const files: Record = { @@ -2640,7 +2650,7 @@ export default { ); test( - "a suggestion has the data that the rule gave, also if that is empty", + "a suggestion has the data the rule passed, even if it's empty", async () => { const { raw, exitCode } = await lint( { @@ -2672,7 +2682,7 @@ export default { ); test( - "the settings that a rule sees are those of the configuration, with oxlint's too", + "a rule sees the config's settings, with an oxlint config too", async () => { const { stdout, exitCode } = await lint( { @@ -2695,7 +2705,7 @@ export default { ); test.each(["--disallow-code-generation-from-strings", "--disallow-code-generation-from-strings=strict"])( - "bun %s lint: plugins run, and neither they nor the configuration file make code from a string", + "bun %s lint: plugins run, and neither they nor the config file can evaluate code from a string", async flag => { using dir = tempDir("bun-lint-js-plugins", { "eslint.config.mjs": ` @@ -2720,9 +2730,9 @@ export default { timeout, ); - // As nodejs/node makes a selector of them, and as rules tell `import "ws"` from `import "fs"`. + // nodejs/node builds a selector from this list, and rules use it to tell `import "ws"` from `import "fs"`. test( - "the modules that are built in are those of Node.js, for a configuration file and for a rule", + "a config file and a rule see Node.js's list of builtin modules", async () => { const { stdout, exitCode } = await lint( { @@ -2746,9 +2756,9 @@ export default { timeout, ); - // As `merge(...tseslint.configs.recommended, other)` of lodash does. + // lodash's `merge(...tseslint.configs.recommended, other)` does this. test( - "a plugin that the configuration file has put into what a package exports", + "loads a plugin that the config file merged into an object that a package exports", async () => { const { stdout, exitCode } = await lint( { @@ -2773,9 +2783,9 @@ export default { timeout, ); - // The other tests name a number of threads. A user does not. + // The other tests set the number of threads. Users don't. test( - "a thread for each core, and more files than that", + "lints every file with one thread per core and more files than threads", async () => { const count = 2 * availableParallelism() + 1; const files: Record = { @@ -2792,13 +2802,13 @@ export default { ); test( - "no registry is asked for what a plugin imports or requires", + "never contacts a registry for a package that a plugin imports or requires", async () => { - const asked: string[] = []; + const requests: string[] = []; using registry = Bun.serve({ port: 0, fetch(request) { - asked.push(new URL(request.url).pathname); + requests.push(new URL(request.url).pathname); return new Response("{}", { status: 404 }); }, }); @@ -2824,7 +2834,7 @@ export default { expect(imported.stdout).toContain("Cannot find package 'is-not-installed-anywhere'"); expect(required.stdout).toContain("Cannot find module 'is-not-installed-anywhere'"); expect(awaited.exitCode).toBe(0); - expect(asked).toEqual([]); + expect(requests).toEqual([]); }, timeout, ); @@ -2886,14 +2896,14 @@ describe.concurrent("context.report() in JavaScript plugins", () => { "b.js": "b;", }; const { raw, stderr, exitCode } = await lint(files, ["--threads", "1", "-f", "json", "a.js", "b.js"]); - const said = JSON.parse(raw).map((result: any) => + const messages = JSON.parse(raw).map((result: any) => result.messages.map((it: any) => [it.message, it.line, it.column, it.endLine, it.endColumn, it.fix]), ); - expect(said).toEqual([ + expect(messages).toEqual([ [["first", 1, 1, 4, 1, undefined]], [ ["the node of a.js", 1, 1, 4, 1, undefined], - // The text between the two insertions is that of b.js. + // The text between the two insertions comes from b.js. ["a copy from a.js", 1, 1, 1, 7, { range: [0, 6], text: "(b;)" }], ['the fixer of a.js: {"range":[0,6],"text":"x"}', 1, 1, 1, 3, undefined], ["first", 1, 1, 1, 3, undefined], @@ -2908,15 +2918,16 @@ describe.concurrent("context.report() in JavaScript plugins", () => { timeout, ); - describe("a `loc` that is not in the file", () => { + describe("a `loc` outside the file", () => { const outOfRange = "RangeError: Line/column pair translates to an out of range offset"; const noLine = (line: number) => `RangeError: Line number out of range (line ${line} requested). Line numbers should be 1-based, and less than or equal to number of lines in file (5).`; const notIntegers = "TypeError: Expected an object with integer `line` and `column` properties"; type Place = (number | null)[]; - // The `loc`. Then `line`, `column`, `endLine` and `endColumn` of ESLint 10.12.0. Then the line and column of oxlint 1.87.0, or - // what it says the rule threw. Then the same as for ESLint without a config, if that is something else. - const places: Record = { + // Each entry has the `loc`, then ESLint 10.12.0's `line`, `column`, `endLine` and `endColumn`, then oxlint 1.87.0's + // line and column or the error it says the rule threw, then the same fields as for ESLint without a config, if they + // differ. + const locCases: Record = { "line-0": ["{ line: 0, column: 0 }", [0, 1], "1:1", [1, 1]], "line-0-column-5": ["{ line: 0, column: 5 }", [0, 6], noLine(0), [1, 1]], "line-0-column-100": ["{ line: 0, column: 100 }", [0, 101], noLine(0), [1, 1]], @@ -2977,11 +2988,11 @@ describe.concurrent("context.report() in JavaScript plugins", () => { "TypeError: `loc.end` must be an object or null/undefined", ], }; - const names = Object.keys(places); + const names = Object.keys(locCases); const all = names.map(name => `${name}.js`); const files = { - // The rule reports at the place that the file is called after. - "plugin.mjs": `const places = { ${names.map(name => `"${name}": ${places[name][0]}`).join(", ")} }; + // The rule reports at the `loc` that the file is named after. + "plugin.mjs": `const places = { ${names.map(name => `"${name}": ${locCases[name][0]}`).join(", ")} }; const nameOf = context => context.filename.replace(/^.*[\\\\/]/, "").replace(".js", ""); const create = context => ({ "Program:exit": () => context.report({ message: nameOf(context), loc: places[nameOf(context)] }), @@ -3000,7 +3011,7 @@ describe.concurrent("context.report() in JavaScript plugins", () => { ...files, ".oxlintrc.json": oxlintrc({ jsPlugins: ["./plugin.mjs"], rules: { "demo/at": "error" } }), }; - const alone = { + const withBunfig = { ...files, "bunfig.toml": `[lint]\nplugins = ["./plugin.mjs"]\nignorePatterns = ["plugin.mjs"]\n[lint.rules]\n"demo/at" = "error"\n`, }; @@ -3016,7 +3027,7 @@ describe.concurrent("context.report() in JavaScript plugins", () => { ); test( - "with an ESLint config it is passed on, as in ESLint", + "with an ESLint config, it's printed unchanged, as in ESLint", async () => { const some = ["line-0.js", "line-below-0.js", "column-far-below-0.js"]; const [json, stylish, unix] = await Promise.all([ @@ -3024,7 +3035,7 @@ describe.concurrent("context.report() in JavaScript plugins", () => { lint(eslint, ["-f", "stylish", ...some]), lint(eslint, ["-f", "unix", ...some]), ]); - expect(inJson(json.raw)).toEqual(Object.fromEntries(names.map(name => [name, [places[name][1]]]))); + expect(inJson(json.raw)).toEqual(Object.fromEntries(names.map(name => [name, [locCases[name][1]]]))); expect(stylish.stdout.split("\n").filter(line => line.includes("error "))).toEqual([ " 1 -4 error column-far-below-0 demo/at", " 0:1 error line-0 demo/at", @@ -3041,7 +3052,7 @@ describe.concurrent("context.report() in JavaScript plugins", () => { ); test( - "with an ESLint config, a comment does not disable what is reported before it", + "with an ESLint config, a comment doesn't disable a report located before it", async () => { const text = "/* eslint-disable */\nfoo();\n/* eslint-enable */\nbar();\n"; const { raw, exitCode } = await lint( @@ -3056,7 +3067,7 @@ describe.concurrent("context.report() in JavaScript plugins", () => { }, ["-f", "json", "a.js"], ); - // As ESLint 10.12.0. + // Same as ESLint 10.12.0. expect(JSON.parse(raw)[0].messages.map((it: any) => it.message)).toEqual(["line -1", "line 0", "line 4"]); expect(exitCode).toBe(1); }, @@ -3064,18 +3075,18 @@ describe.concurrent("context.report() in JavaScript plugins", () => { ); test( - "with an oxlint config it is where oxlint has it, and the rule throws where it does in oxlint", + "with an oxlint config, it's moved or rejected the same way as in oxlint", async () => { const [json, pretty, agent] = await Promise.all([ lint(oxlint, ["-f", "json", ...all]), lint(oxlint, ["line-0.js"]), lint(oxlint, ["-f", "agent", "line-0.js"]), ]); - const said = JSON.parse(json.raw).diagnostics.map((it: any) => { + const found = JSON.parse(json.raw).diagnostics.map((it: any) => { const span = it.labels[0]?.span; return [nameOf(it.filename), span ? `${span.line}:${span.column}` : it.message.split("\n")[2]]; }); - expect(Object.fromEntries(said)).toEqual(Object.fromEntries(names.map(name => [name, places[name][2]]))); + expect(Object.fromEntries(found)).toEqual(Object.fromEntries(names.map(name => [name, locCases[name][2]]))); expect(pretty.stdout).toStartWith(`1 | export const a = 1; ^ error: line-0 demo/at @@ -3088,11 +3099,14 @@ error: line-0 demo/at ); test( - "without a config, what is before the first line is at the start of the file", + "without a config, a `loc` before the first line is moved to the start of the file", async () => { - const [json, pretty] = await Promise.all([lint(alone, ["-f", "json", ...all]), lint(alone, ["line-0.js"])]); + const [json, pretty] = await Promise.all([ + lint(withBunfig, ["-f", "json", ...all]), + lint(withBunfig, ["line-0.js"]), + ]); expect(inJson(json.raw)).toEqual( - Object.fromEntries(names.map(name => [name, [places[name][3] ?? places[name][1]]])), + Object.fromEntries(names.map(name => [name, [locCases[name][3] ?? locCases[name][1]]])), ); expect(pretty.stdout).toStartWith(`1 | export const a = 1; ^ @@ -3104,10 +3118,10 @@ error: line-0 demo/at timeout, ); - describe("and the comments that disable rules", () => { + describe("and disable comments", () => { const found = "demo/line-0"; - // The text. Then what ESLint 10.12.0 has, what oxlint 1.87.0 has, and what there is without a config, where a report is - // compared with the comments at the place where it is shown. + // Each entry has the text, then what ESLint 10.12.0 reports, what oxlint 1.87.0 reports, and what's reported + // without a config, where disable comments are matched against the position the report is shown at. const texts: Record = { "none": ["export {};\n", [`${found} 0:1`], [`${found} 1:1`], [`${found} 1:1`]], "block": [ @@ -3169,7 +3183,7 @@ error: line-0 demo/at ...Object.fromEntries(names.map(name => [`${name}.js`, texts[name][0]])), }; const expected = (at: 1 | 2 | 3) => Object.fromEntries(names.map(name => [name, texts[name][at]])); - const said = (raw: string) => + const messagesOf = (raw: string) => Object.fromEntries( JSON.parse(raw).map((result: any) => [ nameOf(result.filePath), @@ -3178,19 +3192,19 @@ error: line-0 demo/at ); test( - "with an ESLint config no comment disables a report at line 0, as in ESLint", + "with an ESLint config, no comment disables a report at line 0, as in ESLint", async () => { const config = `import demo from "./plugin.mjs"; export default [{ files: ["*.js"], plugins: { demo }, rules: { "demo/line-0": "error" } }];`; const { raw, exitCode } = await lint({ ...files, "eslint.config.mjs": config }, args); - expect(said(raw)).toEqual(expected(1)); + expect(messagesOf(raw)).toEqual(expected(1)); expect(exitCode).toBe(1); }, timeout, ); test( - "with an oxlint config no comment disables it either, as in oxlint", + "with an oxlint config, no comment disables it either, as in oxlint", async () => { const config = oxlintrc({ jsPlugins: ["./plugin.mjs"], rules: { "demo/line-0": "error" } }); const { raw, exitCode } = await lint({ ...files, ".oxlintrc.json": config }, args); @@ -3210,13 +3224,13 @@ error: line-0 demo/at async () => { const config = `[lint]\nplugins = ["./plugin.mjs"]\n[lint.rules]\n"demo/line-0" = "error"\n`; const { raw, exitCode } = await lint({ ...files, "bunfig.toml": config }, args); - expect(said(raw)).toEqual(expected(3)); + expect(messagesOf(raw)).toEqual(expected(3)); expect(exitCode).toBe(1); }, timeout, ); - describe("of the built-in rules that report about the whole file", () => { + describe("for built-in rules that report the whole file", () => { const files = { "tsconfig.json": JSON.stringify({ compilerOptions: { strictNullChecks: false } }), "reported.ts": "export const a = 1;\n", @@ -3244,14 +3258,14 @@ error: line-0 demo/at expect(exitCode).toBe(1); }); - test("with an oxlint config they have no place and no comment disables them, as in oxlint", async () => { + test("with an oxlint config, they have no location and no comment disables them, as in oxlint", async () => { const config = oxlintrc({ plugins: ["vitest"], rules: { [rules[1]]: "error" } }); const project = { ...files, ".oxlintrc.json": config }; const [json, agent] = await Promise.all([ lint(project, [...args, "reported.spec.js", "disabled.spec.js"]), lint(project, ["-f", "agent", "reported.spec.js"]), ]); - // As oxlint 1.87.0. + // Same as oxlint 1.87.0. expect( JSON.parse(json.raw) .diagnostics.map((it: any) => [it.filename, it.code ?? "unused", it.labels.length]) @@ -3267,12 +3281,12 @@ error: line-0 demo/at }); }); - // ESLint has none of these formats. + // ESLint doesn't have any of these formats. test.each([ ["an ESLint config", eslint], - ["no config", alone], + ["no config", withBunfig], ])( - "the other formats have it in the file, with %s", + "the other formats clamp it to a position in the file, with %s", async (_, config) => { const some = ["line-0.js", "line-below-0.js", "column-far-below-0.js", "huge-column.js", "huge-end.js"]; const [pretty, agent, github, junit] = await Promise.all( @@ -3285,7 +3299,7 @@ error: line-0 demo/at " at line-0.js:1:1", " at line-below-0.js:1:1", ]); - // The mark is no further right than the end of the line. + // The `^` doesn't go past the end of the line. expect(pretty.stdout).toContain("1 | export const a = 1;\n ^\nerror: huge-column"); expect(agent.stdout.split("\n").filter(line => line.startsWith("`, @@ -3326,7 +3340,7 @@ error: line-0 demo/at // Recorded with ESLint 10.12.0 and @typescript-eslint/parser 8.71.1 by record.mjs in that directory. test.concurrent( - "the listeners of several rules are called in ESLint's order, for types, selectors, exits and code path events", + "several rules' listeners are called in ESLint's order, for node types, selectors, exits and code path events", async () => { const oracle = join(import.meta.dir, "oracle", "jsplugins", "calls"); const expected: Record = JSON.parse( @@ -3360,7 +3374,7 @@ test.concurrent( timeout, ); -describe.concurrent("the nodes in JavaScript plugins", () => { +describe.concurrent("AST nodes in JavaScript plugins", () => { const oracle = join(import.meta.dir, "oracle", "jsplugins", "trees"); const dump = readFileSync(join(oracle, "dump.cjs"), "utf8"); // Recorded with ESLint 10.12.0, @typescript-eslint/parser 8.71.1 and oxlint 1.87.0 by record.mjs in that directory. @@ -3369,7 +3383,7 @@ describe.concurrent("the nodes in JavaScript plugins", () => { ); test( - "they have the properties, the order, the attributes and the classes that espree and typescript-estree give them", + "have the same properties, property order, attributes and classes as in espree and typescript-estree", async () => { const config = `const dump = require("./dump.cjs"); module.exports = [ @@ -3386,7 +3400,7 @@ describe.concurrent("the nodes in JavaScript plugins", () => { ...Object.keys(treeCases), ]); const results: { filePath: string; messages: { message: string }[] }[] = JSON.parse(raw); - // One node to a line, so that a difference can be read. + // One node per line, so that a diff is readable. const lines = (tree: string | undefined) => tree?.split(/(?<=[[ ])(?=(?:Node )?\{ type: )/); for (const file of Object.keys(treeCases)) { const result = results.find(it => it.filePath.replaceAll("\\", "/").endsWith(`/${file}`)); @@ -3401,7 +3415,7 @@ describe.concurrent("the nodes in JavaScript plugins", () => { ); test( - "they are laid out as in oxlint with its configuration", + "have oxlint's layout with an oxlint config", async () => { const config = { ignorePatterns: ["dump.cjs"], jsPlugins: ["./dump.cjs"], rules: { "dump/shapes": "error" } }; const files = Object.keys(expected.oxlint); @@ -3470,7 +3484,7 @@ describe.concurrent("scopes in JavaScript plugins", () => { // ESLint 8 counts them among the configured globals, and its `addDeclaredGlobals` treats them the same. test( - "the global scope has the variables of /* eslint-env */ comments with an ESLint 8 configuration", + "with an ESLint 8 config, the global scope has the variables from /* eslint-env */ comments", async () => { const plugin = `const show = it => it && [it.name, it.writeable, it.eslintImplicitGlobalSetting, it.eslintExplicitGlobal, it.references.length].join(" "); @@ -3507,9 +3521,9 @@ describe.concurrent("scopes in JavaScript plugins", () => { timeout, ); - // The messages under ESLint 10.12.0. + // ESLint 10.12.0 prints the same messages. test( - "a global variable has what ESLint sets on it when a rule gets to it through reference.resolved first", + "a global variable has ESLint's extra properties even if a rule first reaches it through reference.resolved", async () => { const config = `const show = it => it && @@ -3553,10 +3567,9 @@ describe.concurrent("scopes in JavaScript plugins", () => { timeout, ); - // From then on JavaScriptCore stores every array of the realm in another way. - // What is expected is what ESLint 10.12.0 with @typescript-eslint/parser 8.71.1 reports. + // The expected output is what ESLint 10.12.0 with @typescript-eslint/parser 8.71.1 reports. test( - "what the libraries of TypeScript define is in the global scope whichever way a rule looks at it first", + "the global scope has TypeScript's lib globals, however a rule first accesses it", async () => { const config = ` const flagsOf = (object, key) => { @@ -3629,9 +3642,9 @@ describe.concurrent("scopes in JavaScript plugins", () => { timeout, ); - // What is expected is what ESLint 10.12.0 with @typescript-eslint/parser 8.71.1 reports. + // The expected output is what ESLint 10.12.0 with @typescript-eslint/parser 8.71.1 reports. test( - "what a plugin writes to the global scope and its variables stays, and nothing of it is trusted", + "a plugin's writes to the global scope and its variables persist, and bun lint doesn't trust them", async () => { const config = ` const summary = it => [it.variables.length, it.set.size, typeof it.set.get("Array"), it.set.has("mine"), it.set.has("Promise")]; @@ -3718,11 +3731,12 @@ describe.concurrent("scopes in JavaScript plugins", () => { timeout, ); - // The ids are what oxlint 1.87.0 gives the rule, in a run for each row: it has no two plugins of one name in a run. + // The ids are what oxlint 1.87.0 passes to the rule, with one run per row, because it rejects two plugins with the + // same name in one run. test( - "the name of a plugin, and of the plugin in the name of a rule, without eslint-plugin and oxlint-plugin as oxlint takes them off", + "strips eslint-plugin and oxlint-plugin from a plugin's name and from rule keys like oxlint", async () => { - // `meta.name`, the plugin in the key of the rule, `context.id`. + // `meta.name`, the plugin part of the rule's key, and `context.id`. const cases = [ ["eslint-plugin-foo", "eslint-plugin-foo", "foo/r"], ["eslint-plugin-foo", "foo", "foo/r"], @@ -3761,7 +3775,7 @@ describe.concurrent("scopes in JavaScript plugins", () => { [`${directory}a.js`]: "a;\n", }); const directory = (i: number) => `d${String(i).padStart(2, "0")}/`; - const [accepted, ...refused] = await Promise.all([ + const [accepted, ...rejected] = await Promise.all([ lint(Object.assign({}, ...cases.map(([name, key], i) => project(directory(i), name, key))), [ "-f", "json", @@ -3774,7 +3788,7 @@ describe.concurrent("scopes in JavaScript plugins", () => { const results: { filePath: string; messages: { message: string; ruleId: string }[] }[] = JSON.parse(accepted.raw); const found = results.flatMap(it => it.messages.map(({ message, ruleId }) => [message, ruleId])); expect(found).toEqual(cases.map(([, , id]) => [id, id])); - expect(refused.map(it => [it.stderr.split("\n")[0], it.exitCode])).toEqual([ + expect(rejected.map(it => [it.stderr.split("\n")[0], it.exitCode])).toEqual([ ["error: 1 rule in .oxlintrc.json is not supported: foo/bar/r", 2], ["error: 1 rule in .oxlintrc.json is not supported: @scope/x/y/r", 2], ]); @@ -3782,9 +3796,9 @@ describe.concurrent("scopes in JavaScript plugins", () => { timeout, ); - // ESLint 10.12.0 reports the same for `both`, and refuses `once`: "Rule must be an object with a `create` method". + // ESLint 10.12.0 reports the same for `both`, and rejects `once`: "Rule must be an object with a `create` method". test( - "with a configuration of ESLint a rule with create is created for each file, and the context of createOnce is that of the file being linted", + "with an ESLint config, create runs for each file, and createOnce's context reflects the file being linted", async () => { const files = { "plugin.mjs": `const name = path => path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\\\")) + 1); @@ -3840,7 +3854,7 @@ export default { `c.js p/both | create p/both c.js c.js ["all"] all module c;`, `c.js p/once | after c.js`, ]; - // In one realm, where the third file comes after two others, and in several. + // Once in a single realm, where the third file comes after two others, and once in several realms. const runs = await Promise.all( ["1", "3"].map(threads => lint(files, ["--threads", threads, "-f", "json", "a.js", "b.js", "c.js"])), ); @@ -3858,9 +3872,9 @@ export default { timeout, ); - // As under ESLint 10.12.0. + // Same as under ESLint 10.12.0. test( - "a range with a hole is read like any other object", + "a range array with a hole is read like any other object", async () => { const config = ` const rule = { @@ -3890,7 +3904,7 @@ export default { ); test( - "whatever a plugin throws, and wherever, the run ends with an error that can be read", + "whatever a plugin throws, and wherever it throws, the run ends with a readable error", async () => { const config = ` const thrown = { @@ -3942,7 +3956,7 @@ export default { ["listener", "proxy", "from a proxy"], ["listener", "revoked", "Proxy has already been revoked. No more operations are allowed to be performed on it"], ["listener", "toString", "from toString"], - // As in ESLint 10.12, which puts the rule into `message`. + // Same as ESLint 10.12, which adds the rule to `message`. ["create", "bare", "Error while loading rule 'own/rule': undefined"], ["path", "noLoc", "real error"], ["fix", "getter", "2"], @@ -3966,7 +3980,7 @@ export default { ); test( - "a plugin gets at nothing of the host through caller or through what it has put on Array.prototype", + "a plugin can't reach host internals through `caller` or through accessors it puts on Array.prototype", async () => { const config = ` const seen = []; @@ -4009,8 +4023,9 @@ export default { timeout, ); + // An indexed accessor on Array.prototype makes JavaScriptCore switch every array in the realm to slow-put storage. test( - "nodes, scopes and code paths are right after a plugin has put an accessor with an index for a name on Array.prototype", + "nodes, scopes and code paths are still correct after a plugin defines an indexed accessor on Array.prototype", async () => { const plugin = `Object.defineProperty(Array.prototype, "4294967290", { get() {}, set() {}, configurable: true }); const rule = { @@ -4050,7 +4065,7 @@ export default { ); test( - "with an oxlint config the scopes follow the kind of file: strict scopes of TypeScript, and arguments in CommonJS", + "with an oxlint config, scopes depend on the kind of file: strict scopes in TypeScript, and `arguments` in CommonJS", async () => { const plugin = `export default { meta: { name: "p" }, rules: { rule: { create: context => ({ Program(node) { @@ -4074,7 +4089,7 @@ export default { const declared = "I:1:0,C:1:0,M:1:0,E:1:0,N:1:0,g:1:0"; const inner = "type![T:1:1] functionType![x:1:0] type![T:1:1] conditionalType![U:1:1] type![T:1:2] mappedType![K:1:1] tsEnum![A:1:0] tsModule![f:1:0] function![arguments:0:0]"; - // What oxlint 1.87 says. + // This is what oxlint 1.87 reports. const expected = { "types.ts": `global[${declared}] ${inner} function[arguments:0:0]`, "types.cts": `global[] function[arguments:0:0,${declared}] ${inner} function[arguments:0:0]`, @@ -4094,19 +4109,19 @@ export default { "implicit.cjs": "var first;\narguments;\n", }; const { raw, exitCode } = await lint(files, ["-f", "json"]); - const said = JSON.parse(raw).diagnostics.map((it: { filename: string; message: string }) => [ + const found = JSON.parse(raw).diagnostics.map((it: { filename: string; message: string }) => [ it.filename, it.message, ]); - expect(Object.fromEntries(said)).toEqual(expected); + expect(Object.fromEntries(found)).toEqual(expected); expect(exitCode).toBe(1); }, timeout, ); - // What oxlint 1.87 says. Its own no-unused-vars doesn't see the mark. + // This is what oxlint 1.87 reports. Its own no-unused-vars doesn't see the mark. test( - "with an oxlint config markVariableAsUsed marks the variable it names in every kind of file", + "with an oxlint config, markVariableAsUsed marks the named variable in every kind of file", async () => { const plugin = `export default { meta: { name: "p" }, rules: { rule: { create: context => ({ Program(node) { @@ -4127,11 +4142,11 @@ export default { "c.mjs": code, }; const { raw, exitCode } = await lint(files, ["-f", "json"]); - const said = JSON.parse(raw).diagnostics.map( + const found = JSON.parse(raw).diagnostics.map( (it: { filename: string; message: string }) => `${it.filename} ${it.message.match(/'(\w+)'/)?.[1] ?? it.message}`, ); - expect(said.sort()).toEqual( + expect(found.sort()).toEqual( ["a.cjs", "b.js", "c.mjs"].flatMap(file => [ `${file} first`, `${file} second`, @@ -4147,7 +4162,7 @@ export default { describe.concurrent("what a JavaScript plugin sees with an oxlint config", () => { const oracle = join(import.meta.dir, "oracle", "jsplugins", "oxlint"); const dump = readFileSync(join(oracle, "dump.cjs"), "utf8"); - // By the name of a file. Recorded with oxlint 1.87.0 by record.mjs in that directory. + // Keyed by file name. Recorded with oxlint 1.87.0 by record.mjs in that directory. const expected: Record = JSON.parse( Buffer.from(Bun.zstdDecompressSync(readFileSync(join(oracle, "expected.json.zst")))).toString(), ); @@ -4155,7 +4170,7 @@ describe.concurrent("what a JavaScript plugin sees with an oxlint config", () => const slashes = (path: string) => path.replaceAll("\\", "/"); test( - "trees with their values, the traversal, scopes, and what sourceCode says about each node are oxlint's in every kind of file", + "trees and their values, traversal order, scopes and sourceCode's answers for each node match oxlint in every kind of file", async () => { const config = { ignorePatterns: ["dump.cjs"], jsPlugins: ["./dump.cjs"], rules: { "dump/all": "error" } }; const files = { "dump.cjs": dump, ".oxlintrc.json": oxlintrc(config), ...oxlintCases }; @@ -4171,9 +4186,10 @@ describe.concurrent("what a JavaScript plugin sees with an oxlint config", () => timeout, ); - // In a JavaScript file nothing can fill in the fields of TypeScript, so they aren't made for each node, and an empty list is only made - // when it's read. A plugin must not be able to tell. All of this is what the same plugin says under oxlint 1.87. - describe("the fields of TypeScript in a JavaScript file", () => { + // In a JavaScript file the TypeScript-only fields are always empty, so they aren't created for each node, and an + // empty list is only created when it's read. A plugin must not be able to tell. The expected output is what the same + // plugin reports under oxlint 1.87. + describe("TypeScript-only fields in a JavaScript file", () => { const plugin = String.raw`const describe = (object, key) => { const it = Object.getOwnPropertyDescriptor(object, key); return it && JSON.stringify(it); }; const rule = { create: context => { const ids = []; return { Identifier(node) { ids.push(node); }, "Program:exit"(program) { const next = () => ids.pop(); @@ -4223,7 +4239,7 @@ export default { meta: { name: "lazy" }, rules: { rule, kinds } }; { files: ["kinds.jsx"], rules: { "lazy/kinds": "error" } }, ], }); - const said = async (file: string, text: string) => { + const messagesFor = async (file: string, text: string) => { const files = { "plugin.mjs": plugin, ".oxlintrc.json": config, [file]: text }; const { raw, exitCode } = await lint(files, ["-f", "json", file]); const diagnostics: Diagnostic[] = JSON.parse(raw).diagnostics; @@ -4232,10 +4248,10 @@ export default { meta: { name: "lazy" }, rules: { rule, kinds } }; }; test( - "`decorators` of an Identifier is a plain property with an array of its own, whatever is done to it first", + "an Identifier's `decorators` is a plain property with its own array, however it's first accessed", async () => { const text = Array.from({ length: 40 }, (_, i) => `i${i}`).join("; ") + ";\n"; - const [message, ...more] = await said("ids.js", text); + const [message, ...more] = await messagesFor("ids.js", text); expect(JSON.parse(message)).toEqual({ "keys": "type,decorators,name,optional,typeAnnotation,start,end,range,parent", "forIn": "type,decorators,name,optional,typeAnnotation,start,end,range,parent,loc", @@ -4274,11 +4290,11 @@ export default { meta: { name: "lazy" }, rules: { rule, kinds } }; ); test( - "every type that has them has oxlint's values in oxlint's order", + "every node type that has them has oxlint's values in oxlint's order", async () => { const text = 'import { a as b } from "a";\nexport { b as c };\nexport * from "d";\nexport default b;\nexport const e = ({ f }, [g], h = 1, ...i) => j(f)`k`;\nnew L();\nvar m;\nfunction n() {}\n(function () {});\n({ o: 1, p() {} });\n;\n'; - const [message, ...more] = await said("kinds.jsx", text); + const [message, ...more] = await messagesFor("kinds.jsx", text); expect(message.split("\n")).toEqual([ 'ImportSpecifier {"type":"ImportSpecifier","imported":"{}","local":"{}","importKind":"value","start":9,"end":15,"range":2,"parent":"{}"}', 'ExportNamedDeclaration {"type":"ExportNamedDeclaration","declaration":null,"specifiers":1,"source":null,"exportKind":"value","attributes":0,"start":28,"end":46,"range":2,"parent":"{}"}', @@ -4382,9 +4398,10 @@ export default { meta: { name: "lazy" }, rules: { rule, kinds } }; export default { meta: { name: "p" }, rules: { api, globals } };`; const base = { jsPlugins: ["../plugin.mjs"], rules: { "p/globals": "error" } }; - // What oxlint 1.87 says. It goes through `env` and `globals` in the order of a hash map, so the plugin sorts what it prints. + // This is what oxlint 1.87 reports. It iterates over `env` and `globals` in hash map order, so the plugin sorts its + // output. test( - "scopeManager, languageOptions and parserServices are the frozen objects of oxlint, the same for all files", + "scopeManager, languageOptions and parserServices are frozen objects shared by all files, as in oxlint", async () => { const config = { ...base, @@ -4408,7 +4425,7 @@ export default { meta: { name: "lazy" }, rules: { rule, kinds } }; // One thread, so that one VM sees all the files. const { raw, exitCode } = await lint(files, ["-f", "json", "--threads", "1"]); const diagnostics: Diagnostic[] = JSON.parse(raw).diagnostics; - const said = Object.fromEntries(diagnostics.map(it => [slashes(it.filename), it.message.split("\n")])); + const found = Object.fromEntries(diagnostics.map(it => [slashes(it.filename), it.message.split("\n")])); const inScript = [ "scopeManager frozen scopes:get,globalScope:get,getDeclaredVariables,acquire", "getDeclaredVariables/1,acquire/2", @@ -4428,7 +4445,7 @@ export default { meta: { name: "lazy" }, rules: { rule, kinds } }; ]; const options = ([sourceType, jsx, globalReturn, impliedStrict]: (string | boolean)[]) => JSON.stringify({ sourceType, ecmaFeatures: { jsx, globalReturn, impliedStrict } }); - expect(said).toEqual( + expect(found).toEqual( Object.fromEntries( Object.entries(kinds).map(([file, kind]) => [ `api/${file}`, @@ -4443,9 +4460,10 @@ export default { meta: { name: "lazy" }, rules: { rule, kinds } }; timeout, ); - // What oxlint 1.87 says: how many variables the global scope has, a sum over their names, `env`, `globals`, and some variables. + // This is what oxlint 1.87 reports: the number of variables in the global scope, a checksum of their names, `env`, + // `globals`, and some variables. test( - "the globals are those of the envs that are on and of globals: builtin only without env, overrides merge, extends doesn't count", + "globals come from the enabled envs and `globals`: builtin only without env, overrides merge, extends is ignored", async () => { const everyEnv = "amd applescript astro atomtest audioworklet browser builtin bun commonjs embertest es2015 es2016 es2017 es2018 es2019 es2020 es2021 es2022 es2023 es2024 es2025 es2026 es6 greasemonkey jasmine jest jquery meteor mocha mongo nashorn node phantomjs prototypejs protractor qunit serviceworker shared-node-browser shelljs svelte vitest vue webextensions worker"; @@ -4532,10 +4550,10 @@ export default { meta: { name: "lazy" }, rules: { rule, kinds } }; timeout, ); - // What oxlint 1.87 says, and ESLint 10.12 with @typescript-eslint/parser 8.71.1: the same. + // oxlint 1.87 and ESLint 10.12 with @typescript-eslint/parser 8.71.1 both report this. test.each(["oxlint", "eslint"])( - "reference.maybeImplicitGlobal is typescript-eslint's: an object, null or undefined, with a config of %s", - async whose => { + "reference.maybeImplicitGlobal matches typescript-eslint (an object, null or undefined) with an %s config", + async tool => { const rule = `export default { meta: { name: "p" }, rules: { rule: { create: context => ({ Program(node) { const said = context.sourceCode.scopeManager.scopes.flatMap(scope => @@ -4574,29 +4592,29 @@ export default { meta: { name: "lazy" }, rules: { rule, kinds } }; }; const files = { "plugin.mjs": rule, - ...configs[whose as keyof typeof configs], + ...configs[tool as keyof typeof configs], "script.js": `${code}\n`, "script.ts": `${code}${types}\n`, "module.mts": `${code}${types} export { a };\n`, }; const { raw, exitCode } = await lint(files, ["-f", "json", ...Object.keys(expected)]); - const said: [string, string][] = - whose === "oxlint" + const found: [string, string][] = + tool === "oxlint" ? JSON.parse(raw).diagnostics.map((it: Diagnostic) => [it.filename, it.message]) : JSON.parse(raw).map((it: { filePath: string; messages: { message: string }[] }) => [ slashes(it.filePath).split("/").at(-1), it.messages.map(message => message.message).join("|"), ]); - expect(Object.fromEntries(said)).toEqual(expected); + expect(Object.fromEntries(found)).toEqual(expected); expect(exitCode).toBe(1); }, timeout, ); - // What oxlint 1.87 says, and ESLint 10.12 with @typescript-eslint/parser 8.71.1: the same. + // oxlint 1.87 and ESLint 10.12 with @typescript-eslint/parser 8.71.1 both report this. test.each(["oxlint", "eslint"])( - "the index of `a[b]!` in a pattern is referred to before the object, like that of `a[b]`, with a config of %s", - async whose => { + "in a pattern, the reference to the index of `a[b]!` comes before the object's, as for `a[b]`, with an %s config", + async tool => { const rule = `export default { meta: { name: "p" }, rules: { rule: { create: context => ({ "Program:exit"(node) { const lines = {}; @@ -4638,24 +4656,24 @@ export default { meta: { name: "lazy" }, rules: { rule, kinds } }; }; const files = { "plugin.mjs": rule, - ...configs[whose as keyof typeof configs], + ...configs[tool as keyof typeof configs], "a.ts": rows.map(it => `${it[0]}\n`).join(""), }; const { raw, exitCode } = await lint(files, ["-f", "json", "a.ts"]); const message: string = - whose === "oxlint" ? JSON.parse(raw).diagnostics[0].message : JSON.parse(raw)[0].messages[0].message; - expect(message.split("|").map((said, i) => [rows[i][0], said])).toEqual(rows); + tool === "oxlint" ? JSON.parse(raw).diagnostics[0].message : JSON.parse(raw)[0].messages[0].message; + expect(message.split("|").map((cell, i) => [rows[i][0], cell])).toEqual(rows); expect(exitCode).toBe(1); }, timeout, ); - // `loc`, `decorators`, `ast.tokens` and the properties of `sourceCode` are made when they're read. It must not show who reads them first, in - // which realm or in which tier of the engine: they belong to the plugin's realm and stay the same objects. - // This is what oxlint 1.87 and ESLint 10.12 say, where all of it is plain data. + // `loc`, `decorators`, `ast.tokens` and `sourceCode`'s properties are created when they're first read. It must not + // matter what reads them first, in which realm, or in which JIT tier: they belong to the plugin's realm and stay the + // same objects. This is what oxlint 1.87 and ESLint 10.12 report, where all of it is plain data. test.each(["oxlint", "eslint"])( - "what is made on first read is the same from a node:vm context and in hot code, with a config of %s", - async whose => { + "lazily created properties are the same from a node:vm context and in hot code, with an %s config", + async tool => { const plugin = String.raw`import vm from "node:vm"; const keys = ["decorators", "loc", "range"]; // The same functions for each realm. A loop is as long as it takes the JIT compilers to get to it. @@ -4753,13 +4771,13 @@ export default { meta: { name: "p" }, rules: { rule } }; }; const files = { "plugin.mjs": plugin, - ...configs[whose as keyof typeof configs], + ...configs[tool as keyof typeof configs], "a.js": "// c\n" + Array.from({ length: 3002 }, (_, i) => `v${i};\n`).join(""), }; const { raw, exitCode } = await lint(files, ["-f", "json", "a.js"]); const message: string = - whose === "oxlint" ? JSON.parse(raw).diagnostics[0].message : JSON.parse(raw)[0].messages[0].message; - expect(message.split("\n")).toEqual(expected[whose as keyof typeof expected]); + tool === "oxlint" ? JSON.parse(raw).diagnostics[0].message : JSON.parse(raw)[0].messages[0].message; + expect(message.split("\n")).toEqual(expected[tool as keyof typeof expected]); expect(exitCode).toBe(1); }, timeout, @@ -4767,7 +4785,7 @@ export default { meta: { name: "p" }, rules: { rule } }; }); test.concurrent( - "getAncestors returns every ancestor after a plugin has put an accessor with an index for a name on Array.prototype", + "getAncestors returns every ancestor after a plugin defines an indexed accessor on Array.prototype", async () => { const plugin = `Object.defineProperty(Array.prototype, "4294967290", { get() {}, set() {}, configurable: true }); const rule = { @@ -4795,7 +4813,7 @@ test.concurrent( ); test.concurrent( - "context.sourceCode is laid out and answers as in ESLint: text, lines, locations, indices, ancestors, scopes, directive comments, bad input", + "context.sourceCode matches ESLint: layout, text, lines, locations, indices, ancestors, scopes, directive comments, bad input", async () => { const oracle = join(import.meta.dir, "oracle", "jsplugins", "source-code"); const { texts } = require(join(oracle, "plugin.cjs")); @@ -4809,14 +4827,14 @@ test.concurrent( ...texts, }; const { raw, exitCode } = await lint(files, ["-f", "json", ...Object.keys(texts)]); - const said = Object.fromEntries( + const found = Object.fromEntries( JSON.parse(raw).map((result: any) => [ result.filePath.replaceAll("\\", "/").split("/").at(-1), JSON.parse(result.messages.find((it: any) => it.ruleId === "demo/all").message), ]), ); // Recorded with ESLint 10.12.0 and @typescript-eslint/parser 8.71.1 by record.mjs in that directory. - expect(said).toEqual(JSON.parse(readFileSync(join(oracle, "expected.json"), "utf8"))); + expect(found).toEqual(JSON.parse(readFileSync(join(oracle, "expected.json"), "utf8"))); expect(exitCode).toBe(1); }, timeout, @@ -4833,7 +4851,7 @@ describe.concurrent("code paths in JavaScript plugins", () => { const slashes = (path: string) => path.replaceAll("\\", "/"); test( - "events, graphs, traverseSegments and the properties of the objects match ESLint in JavaScript files", + "events, graphs, traverseSegments and the objects' properties match ESLint in JavaScript files", async () => { const cases = codePathCases.filter(it => !isTypeScript(it)); const config = `const trace = require("./trace.cjs"); @@ -4857,7 +4875,7 @@ describe.concurrent("code paths in JavaScript plugins", () => { traces: [expected[it.name]], }); } - // The message under ESLint 10.12.0. + // ESLint 10.12.0 prints the same message. expect(messagesOf("layout.js")?.map(it => it.split("\n"))).toEqual([ [ "CodePath own(id:value:wec,origin:value:wec,upper:value:wec,childCodePaths:value:wec,internal:value:) prototype(constructor:value:wc,initialSegment:getter:c,finalSegments:getter:c,returnedSegments:getter:c,thrownSegments:getter:c,traverseSegments:value:wc) keys(id,origin,upper,childCodePaths)", @@ -4894,9 +4912,9 @@ describe.concurrent("code paths in JavaScript plugins", () => { timeout, ); - // ESLint 9 removed `currentSegments`. The first test checks that it's gone with a flat configuration. + // ESLint 9 removed `currentSegments`. The first test checks that it's gone with a flat config. test( - "codePath.currentSegments follows the traversal with an ESLint 8 configuration", + "codePath.currentSegments follows the traversal with an ESLint 8 config", async () => { const plugin = `module.exports = { rules: { paths: { create(context) { const seen = []; @@ -4928,7 +4946,7 @@ describe.concurrent("code paths in JavaScript plugins", () => { }; const { raw, exitCode } = await lint(files, ["-f", "json", "a.js", "b.js"]); const results: { messages: { message: string }[] }[] = JSON.parse(raw); - // From ESLint's analyzer with the listeners called while it runs, as ESLint 8 calls them. + // Recorded from ESLint's analyzer with the listeners called while it runs, as ESLint 8 does. expect(results.map(result => result.messages.map(it => it.message))).toEqual([ [ "+s1_1 [s1_1] +s2_1 [s2_1] -s2_1 [s2_1] +s2_2 [s2_2] return [s2_2] -s2_2 [s2_2] +s2_4 [s2_4] statement [s2_4] -s2_4 [s2_4] +s2_5 [s2_5] statement [s2_5] exit [s2_5] -s2_5 [s2_5] end [] -s1_1 [s1_1] end []", @@ -4943,7 +4961,7 @@ describe.concurrent("code paths in JavaScript plugins", () => { ); test( - "an error thrown from a code path listener or a traverseSegments callback names the rule", + "an error thrown from a code path listener or a traverseSegments callback mentions the rule", async () => { const plugin = `const fail = () => { throw new Error("thrown on purpose"); }; module.exports = { meta: { name: "throws" }, rules: { @@ -4969,7 +4987,8 @@ describe.concurrent("code paths in JavaScript plugins", () => { }); describe.concurrent("JavaScript plugins and threads", () => { - // A file that's linted with types, and standard input, are parsed on a thread that has no VM. A thread that has one parses them again. + // A file that's linted with types, and standard input, are parsed on a thread without a VM. A thread with a VM then + // parses them again. test( "markVariableAsUsed reaches no-unused-vars in files with types, files without, and standard input", async () => { @@ -5012,12 +5031,12 @@ describe.concurrent("JavaScript plugins and threads", () => { exitCode, }; }; - const [ofFiles, ofStdin] = await Promise.all([ + const [fromFiles, fromStdin] = await Promise.all([ run(["plain", "typed"], "ignore"), run(["--stdin", "--stdin-filename", "plain/b.js"], Buffer.from(code)), ]); - expect(ofFiles).toEqual({ names: ["a.js lostInner", "a.js lost", "a.ts lostInner", "a.ts lost"], exitCode: 1 }); - expect(ofStdin).toEqual({ names: ["b.js lostInner", "b.js lost"], exitCode: 1 }); + expect(fromFiles).toEqual({ names: ["a.js lostInner", "a.js lost", "a.ts lostInner", "a.ts lost"], exitCode: 1 }); + expect(fromStdin).toEqual({ names: ["b.js lostInner", "b.js lost"], exitCode: 1 }); }, timeout, ); @@ -5098,7 +5117,7 @@ describe.concurrent("JavaScript plugins and threads", () => { ); test( - "--threads 1 has one VM, also when a file of 256 KB and more is among the files", + "--threads 1 uses one VM, even if one of the files is 256 KB or more", async () => { const files: Record = { "eslint.config.mjs": ` @@ -5116,9 +5135,9 @@ describe.concurrent("JavaScript plugins and threads", () => { timeout, ); - // As ESLint 10.12.0, which lints one file after the other. + // Same as ESLint 10.12.0, which lints one file at a time. test( - "if a rule throws in several files, the error for the first path is reported, however many threads there are", + "if a rule throws in several files, the error for the first path is reported, with any number of threads", async () => { const files: Record = { "eslint.config.mjs": ` @@ -5128,7 +5147,7 @@ describe.concurrent("JavaScript plugins and threads", () => { Program() { if (context.filename.endsWith("7.js")) throw new Error("thrown on purpose"); }, }) } } };`, }; - // 6 MB, which is work for several VMs. + // 6 MB, which is enough work for several VMs. const text = `foo;\n/*${Buffer.alloc(250_000, "x")}*/\n`; for (let i = 0; i < 24; i++) files[`src/${i}.js`] = text; const run = async (threads: string) => { @@ -5163,13 +5182,13 @@ describe.concurrent("JavaScript plugins and threads", () => { stderr: "pipe", }); const reader = proc.stderr.getReader(); - let said = ""; - while (!said.includes("spinning")) { + let output = ""; + while (!output.includes("spinning")) { const { value, done } = await reader.read(); if (done) break; - said += new TextDecoder().decode(value); + output += new TextDecoder().decode(value); } - expect(said).toContain("spinning"); + expect(output).toContain("spinning"); proc.kill("SIGTERM"); await proc.exited; expect(proc.signalCode).toBe("SIGTERM"); @@ -5207,7 +5226,7 @@ describe.concurrent("tokens and comments in JavaScript plugins", () => { "json", ]); const results: { filePath: string; messages: { message: string }[] }[] = JSON.parse(raw); - // Left out: methods that ESLint 10 doesn't have any more. + // Skips the methods that ESLint 10 removed. const wanted = /^(?:[BDNE]:|L:(?:program|store|shape|parts|lists) )/; for (const it of tokenCases) { const file = `/${tokenFileOf(it)}`; @@ -5223,7 +5242,7 @@ describe.concurrent("tokens and comments in JavaScript plugins", () => { ); test( - "the objects match oxlint with its configuration", + "the objects match oxlint with an oxlint config", async () => { const config = { ignorePatterns: ["dump.cjs"], jsPlugins: ["./dump.cjs"], rules: { "tokens/all": "error" } }; const { raw, exitCode } = await lint({ "dump.cjs": dump, ".oxlintrc.json": oxlintrc(config), ...sources }, [ @@ -5231,7 +5250,7 @@ describe.concurrent("tokens and comments in JavaScript plugins", () => { "json", ]); const diagnostics: { filename: string; message: string }[] = JSON.parse(raw).diagnostics; - // oxlint has other values or types for a few tokens in these two. + // oxlint has different values or types for a few tokens in these two. for (const it of tokenCases.filter(it => it.name !== "escapes.ts" && it.name !== "jsx-names")) { const found = diagnostics.filter(diagnostic => diagnostic.filename.replaceAll("\\", "/") === tokenFileOf(it)); expect({ @@ -5248,7 +5267,7 @@ describe.concurrent("tokens and comments in JavaScript plugins", () => { ); test( - "odd arguments, receivers and filters do what they do in ESLint", + "odd arguments, receivers and filters behave as in ESLint", async () => { const plugin = ` const show = value => @@ -5314,7 +5333,7 @@ describe.concurrent("tokens and comments in JavaScript plugins", () => { const files = { "plugin.cjs": plugin, "eslint.config.cjs": config, "a.js": "a = b; // c\nd(e);\n" }; const { raw, exitCode } = await lint(files, ["-f", "json", "a.js"]); const [{ messages }]: { messages: { message: string }[] }[] = JSON.parse(raw); - // What ESLint 10.12.0 reports when Bun runs it. + // This is what ESLint 10.12.0 reports when Bun runs it. expect(messages.map(it => it.message.split("\n"))).toEqual([ [ "inherited: ;", diff --git a/test/cli/lint/json-parse.test.ts b/test/cli/lint/json-parse.test.ts index 524fc938ed4c..14126a621ebf 100644 --- a/test/cli/lint/json-parse.test.ts +++ b/test/cli/lint/json-parse.test.ts @@ -29,7 +29,7 @@ async function lint(files: Record, args: string[]) { } const couldNotBeParsed = "The package.json file could not be parsed: "; -/** What the rule says is wrong with the text. It also reports the imports, since it knows no dependencies then. */ +/** Keeps only the rule's parse errors. If package.json doesn't parse, it also reports every import as unlisted. */ const syntaxErrors = (messages: string[]) => messages.filter(it => it.startsWith(couldNotBeParsed)); /** @@ -153,29 +153,29 @@ describe.concurrent("JSON files that rules read", () => { ]; test("syntax errors have V8's messages and positions", async () => { - const said = await readAsPackageJson(invalid.map(it => it[0])); - expect(said.map((it, i) => [invalid[i][0], syntaxErrors(it)])).toEqual( + const reported = await readAsPackageJson(invalid.map(it => it[0])); + expect(reported.map((it, i) => [invalid[i][0], syntaxErrors(it)])).toEqual( invalid.map(it => [it[0], [couldNotBeParsed + it[1]]]), ); }); - test.each(Object.entries(nested))("deeply nested %s are read", async (_, value) => { + test.each(Object.entries(nested))("deeply nested %s are parsed", async (_, value) => { const dependencies = `"dependencies":{"listed":"1"}`; - const said = await readAsPackageJson([`{${dependencies},"x":${value}}\n`, `{"x":${value},${dependencies}}\n`]); - expect(said).toEqual([[unlisted], [unlisted]]); + const reported = await readAsPackageJson([`{${dependencies},"x":${value}}\n`, `{"x":${value},${dependencies}}\n`]); + expect(reported).toEqual([[unlisted], [unlisted]]); }); - test("an object with 100,000 names is read as fast as any other text of that size", async () => { + test("an object with 100,000 keys is parsed in linear time", async () => { const names = Array.from({ length: 100_000 }, (_, i) => `"package-${i}":"1"`); expect(await readAsPackageJson([`{"dependencies":{${names.join(",")},"listed":"1"}}`])).toEqual([[unlisted]]); }); - test("the last value of a repeated name counts", async () => { + test("the last value of a duplicate key wins", async () => { const others = Array.from({ length: 40 }, (_, i) => `"name-${i}":${i}`).join(","); const first = `"dependencies":{"unlisted":"1"}`; const last = `"dependencies":{"listed":"1"}`; - const said = await readAsPackageJson([`{${first},${last}}`, `{${first},${others},${last}}`]); - expect(said).toEqual([[unlisted], [unlisted]]); + const reported = await readAsPackageJson([`{${first},${last}}`, `{${first},${others},${last}}`]); + expect(reported).toEqual([[unlisted], [unlisted]]); }); test("the closest package.json can be deeply nested", async () => { @@ -211,12 +211,12 @@ describe.concurrent("JSON files that rules read", () => { `Expected ',' or ']' after array element in JSON at position ${2 * depth + 2} (line ${depth + 1} column 3)`, ], ]; - const said = await readAsPackageJson(texts.map(it => it[0])); - expect(said.map(syntaxErrors)).toEqual(texts.map(it => [couldNotBeParsed + it[1]])); + const reported = await readAsPackageJson(texts.map(it => it[0])); + expect(reported.map(syntaxErrors)).toEqual(texts.map(it => [couldNotBeParsed + it[1]])); }); }); -// `bun lint` looks for `eslintConfig` in every package.json on the way up. +// `bun lint` looks for `eslintConfig` in every package.json in the parent directories. test.concurrent("a deeply nested package.json without eslintConfig doesn't stop the run", async () => { const files = { "package.json": `{"name":"a","x":${nested.arrays}}\n`, "a.js": "debugger;\n" }; const { stdout, exitCode } = await lint(files, ["-f", "json", "--rule", "no-debugger: error", "a.js"]); @@ -263,17 +263,17 @@ describe.concurrent("/* eslint rule: .. */ comments", () => { ["mini/unchecked", nested.arrays, `depth ${depth}, innermost undefined`], ["mini/unchecked", nested.objects, `depth ${depth}, innermost 1`], ["mini/anything", nested.both, `depth ${depth}, innermost 1`], - ])("%s gets deeply nested options", async (rule, options, said) => { - expect(await messages(`${rule}: [2, ${options}]`)).toEqual([`${rule}: ${said}`]); + ])("%s gets deeply nested options", async (rule, options, message) => { + expect(await messages(`${rule}: [2, ${options}]`)).toEqual([`${rule}: ${message}`]); }); test("messages about invalid options print deeply nested values", async () => { - const said = await Promise.all([nested.arrays, nested.objects].map(it => messages(`eqeqeq: [2, ${it}]`))); + const reported = await Promise.all([nested.arrays, nested.objects].map(it => messages(`eqeqeq: [2, ${it}]`))); const invalid = (value: string, all: string) => `eqeqeq: Inline configuration for rule "eqeqeq" is invalid:\n` + `\tValue ${value} should be equal to one of the allowed values.\n`.repeat(2) + `\tValue ${all} should match some schema in anyOf.\n`; - expect(said).toEqual([ + expect(reported).toEqual([ [invalid(`<${depth} [><${depth} ]>`, `<${depth + 1} [><${depth + 1} ]>`)], [invalid(`<${depth} {"a":>1<${depth} }>`, `[<${depth} {"a":>1<${depth} }>]`)], ]); diff --git a/test/cli/lint/lint.test.ts b/test/cli/lint/lint.test.ts index bafb6cf35569..e729ac7963ae 100644 --- a/test/cli/lint/lint.test.ts +++ b/test/cli/lint/lint.test.ts @@ -15,9 +15,13 @@ import { import { chmodSync, chownSync, + closeSync, + constants, existsSync, linkSync, + lstatSync, mkdirSync, + openSync, readdirSync, readFileSync, realpathSync, @@ -26,6 +30,7 @@ import { symlinkSync, truncateSync, writeFileSync, + writeSync, } from "node:fs"; import { basename, dirname, join, parse, posix, sep, win32 } from "node:path"; import { endChildren, spawn } from "../children"; @@ -70,11 +75,11 @@ type Options = { cwd?: string; stdin?: string; env?: Record; - /** Files to read when the command has run. */ + /** Files to read after the command has run. */ reads?: string[]; /** Called with the directory before the command runs. */ before?: (dir: string) => void; - /** The run is meant to end with an error. */ + /** The run is expected to fail, so its stderr isn't printed. */ mayFail?: boolean; }; @@ -90,7 +95,7 @@ async function lint(files: Record, args: string[], options: Opti stderr: "pipe", }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - // Where a run ends with an error, or dies, the assertion that fails is often about something else. + // If a run fails or crashes, the assertion that fails is often about something else, so print the real cause. if (exitCode !== 0 && exitCode !== 1 && !options.mayFail) console.error(`bun lint ${args.join(" ")}: exit code ${exitCode}\n${stderr}`); const read = (name: string) => @@ -104,7 +109,7 @@ async function lint(files: Record, args: string[], options: Opti }; } -/** The same in a directory that is there, with nothing in the output replaced. */ +/** Like `lint`, but runs in an existing directory and doesn't normalize the output. */ async function run(cwd: string, args: string[]) { const stdio = { stdin: "ignore", stdout: "pipe", stderr: "pipe" } as const; await using proc = spawn({ cmd: [...command, ...args], env, cwd, ...stdio }); @@ -142,7 +147,7 @@ describe.concurrent("bun lint", () => { expect(exitCode).toBe(0); }); - test("warnings alone do not fail, unless --max-warnings says so", async () => { + test("exits 0 with only warnings unless --max-warnings is exceeded", async () => { const files = { "eslint.config.js": basic, "a.js": "let unused = 1;\n" }; const [plain, limited] = await Promise.all([lint(files, []), lint(files, ["--max-warnings", "0"])]); expect(plain.stdout).toMatchInlineSnapshot(` @@ -156,7 +161,7 @@ describe.concurrent("bun lint", () => { expect({ plain: plain.exitCode, limited: limited.exitCode }).toEqual({ plain: 0, limited: 1 }); }); - test("--color", async () => { + test("--color colors the stylish output", async () => { const { raw, exitCode } = await lint({ "eslint.config.js": basic, "a.js": "debugger;\n" }, ["--color", "a.js"]); expect(raw.slice(raw.indexOf("a.js"))).toBe( "a.js\x1b[24m\n \x1b[2m1:1\x1b[22m \x1b[31merror\x1b[39m Unexpected 'debugger' statement \x1b[2mno-debugger\x1b[22m\n\n" + @@ -165,26 +170,26 @@ describe.concurrent("bun lint", () => { expect(exitCode).toBe(1); }); - test("without a configuration file: what `bun test` has without an import is defined in the files that it takes", async () => { + test("without a config file, `bun test` globals are defined only in files that `bun test` would run", async () => { const names = "test it describe expect expectTypeOf beforeAll beforeEach afterEach afterAll jest vi xit xtest xdescribe"; const code = `[${names.split(" ").join(", ")}];\n`; - const taken = ["a.test.js", "src/b_test.mjs", "c.spec.jsx", "d_spec.cjs"]; + const testFiles = ["a.test.js", "src/b_test.mjs", "c.spec.jsx", "d_spec.cjs"]; const others = ["test.js", "e.tests.js", "atest.js"]; - const files = Object.fromEntries([...taken, ...others].map(name => [name, code])); + const files = Object.fromEntries([...testFiles, ...others].map(name => [name, code])); const { stdout } = await lint(files, ["-f", "unix"]); const undefinedIn = (name: string) => stdout.split("\n").filter(line => line.startsWith(`/${name}:`) && line.endsWith("[Error/no-undef]")).length; - expect([taken.map(undefinedIn), others.map(undefinedIn)]).toEqual([ + expect([testFiles.map(undefinedIn), others.map(undefinedIn)]).toEqual([ [0, 0, 0, 0], [14, 14, 14], ]); }); - describe("the globals of a file are what the types of its project declare", () => { + describe("a file's globals come from its project's type declarations", () => { const options = (lib: string[], more: object) => JSON.stringify({ compilerOptions: { lib, types: [], ...more } }); const files = { - // In no project. + // Not in any project. "a/a.js": "console.log(window, process, Bun, nothing);\n", "b/jsconfig.json": options(["es2022"], { checkJs: true }), "b/a.js": "console.log(window, process, Bun, nothing, Promise, Map);\n", @@ -194,7 +199,7 @@ describe.concurrent("bun lint", () => { "c/a.js": "console.log(window, process, MY_GLOBAL, MY_CONST, OnlyAType, nothing);\nMY_CONST = 1;\nMY_GLOBAL = 'a';\n" + "/* global process, window: off */\n", - // The project does not take it in. + // This project doesn't include build.js. "d/tsconfig.json": options(["es2022"], {}), "d/build.js": "console.log(window, process, require, nothing);\n", "d/x.ts": "export const a = 1;\n", @@ -205,7 +210,7 @@ describe.concurrent("bun lint", () => { .flatMap(line => /^\/(\S+?:\d+:\d+): .*?'(\w+)'.* \[\w+\/(.*)\]$/.exec(line)?.slice(1).join(" ") ?? []); const union = ["a/a.js:1:35 nothing no-undef", "d/build.js:1:39 nothing no-undef"]; - test("without a configuration file, with --infer-globals", async () => { + test("without a config file, only with --infer-globals", async () => { const [inferred, not] = await Promise.all([ lint(files, ["-f", "unix", "--infer-globals"]), lint(files, ["-f", "unix"]), @@ -239,8 +244,8 @@ describe.concurrent("bun lint", () => { ); }); - // TypeScript knows the three in JavaScript without a declaration. - test("`require`, `module` and `exports` are defined in a JavaScript file that is no ES module", async () => { + // TypeScript defines these three in JavaScript files without a declaration. + test("`require`, `module` and `exports` are defined in a JavaScript file that isn't an ES module", async () => { const { stdout } = await lint( { "tsconfig.json": options(["es2022"], { checkJs: true }), @@ -256,7 +261,7 @@ describe.concurrent("bun lint", () => { ]); }); - test("beside a configuration file only with --infer-globals, and besides what it has", async () => { + test("with a config file, only with --infer-globals, and the config's own globals still apply", async () => { const config = `export default [{ languageOptions: { globals: { nothing: "readonly", MY_CONST: "off" } }, rules: { "no-undef": "error", "no-global-assign": "error" }, @@ -288,7 +293,7 @@ describe.concurrent("bun lint", () => { }); }); - test("--stdin: what only the parser of the configuration can read is named, as for a file", async () => { + test("--stdin reports input that only the config's parser can read, like it does for a file", async () => { const files = { "eslint.config.mjs": `export default [{ languageOptions: { parser: { meta: { name: "@babel/eslint-parser" }, parseForESLint() { throw new Error("called"); } } }, @@ -309,9 +314,9 @@ describe.concurrent("bun lint", () => { expect([read.exitCode, unread.exitCode]).toEqual([1, 2]); }); - // As ESLint 10.12 and oxlint 1.87. + // Same as ESLint 10.12 and oxlint 1.87. test.each(["eslint.config.mjs", "oxlint.config.ts"])( - "`process.cwd()` in %s is where the command runs, not where the file is", + "`process.cwd()` in %s is the directory the command runs in, not the config file's directory", async name => { const rules = `{ "no-debugger": basename(process.cwd()) === "sub" ? "error" : "off" }`; const config = name.startsWith("eslint") ? `[{ rules: ${rules} }]` : `{ rules: ${rules} }`; @@ -319,12 +324,12 @@ describe.concurrent("bun lint", () => { [name]: `import { basename } from "node:path";\nexport default ${config};\n`, "sub/a.js": "debugger;\n", }; - const [below, beside] = await Promise.all([lint(files, ["a.js"], { cwd: "sub" }), lint(files, ["sub/a.js"])]); - expect([below.exitCode, beside.exitCode]).toEqual([1, 0]); + const [fromSub, fromRoot] = await Promise.all([lint(files, ["a.js"], { cwd: "sub" }), lint(files, ["sub/a.js"])]); + expect([fromSub.exitCode, fromRoot.exitCode]).toEqual([1, 0]); }, ); - test("without a configuration file: eslint:recommended, and typescript-eslint/recommended for TypeScript", async () => { + test("without a config file, uses eslint:recommended, plus typescript-eslint/recommended for TypeScript", async () => { const { stdout, exitCode } = await lint( { "a.js": "console.log(Bun.version, process.argv, window);\nlet unused;\nundefinedName();\n", @@ -350,11 +355,12 @@ describe.concurrent("bun lint", () => { expect(exitCode).toBe(1); }); - // What a file is like while it is being written. TypeScript's parser goes on and leaves these to its checker. + // This is what a file looks like while it's being typed. TypeScript's parser recovers and leaves these errors to its + // checker. test.each([ ["eslint.config.js", config({})], [".oxlintrc.json", "{}"], - ])("JavaScript in which a name is missing is a parsing error, with %s", async (name, text) => { + ])("JavaScript with a missing name is a parsing error, with %s", async (name, text) => { const codes = [ "let x = 1;\nconst", "export var", @@ -381,14 +387,15 @@ describe.concurrent("bun lint", () => { expect(exitCode).toBe(1); }); - // oxc reads these. espree, typescript-estree and tsc do not. - test("what only oxc parses is linted with .oxlintrc.json, and a parsing error with eslint.config.js", async () => { + // oxc parses these. espree, typescript-estree and tsc don't. + test("syntax that only oxc parses is linted with .oxlintrc.json, and is a parsing error with eslint.config.js", async () => { const files = { "a.js": 'import source x from "m";\ndebugger;\n', "b.ts": 'import source x from "m";\ndebugger;\n', "c.js": 'import.source("m");\ndebugger;\n', "d.tsx": "<>\n<\n/>;\ndebugger;\n", - // The attributes of a re-export on the next line, where TypeScript reads a `with` statement. In JavaScript espree reads these. + // A re-export's attributes on the next line, which TypeScript parses as a `with` statement. In JavaScript, espree + // parses these. "e.ts": 'export * from "m"\nwith { type: "json" }\ndebugger;\n', "f.ts": 'export * as ns from "m"\nwith { type: "json" }\ndebugger;\n', "g.ts": 'export { a } from "m"\nwith { type: "json" }\ndebugger;\n', @@ -397,25 +404,26 @@ describe.concurrent("bun lint", () => { const names = Object.keys(files); const lines = (stdout: string) => stdout.split("\n").filter(line => /^\S*[a-h]\.\w+:\d/.test(line)); const rules = { "no-debugger": "error" }; - const ofOxlint = JSON.stringify({ categories: { correctness: "off" }, rules }); - const ofEslint = `export default [{ files: ["**/*.{js,ts,tsx}"], rules: ${JSON.stringify(rules)} }];\n`; + const oxlintConfig = JSON.stringify({ categories: { correctness: "off" }, rules }); + const eslintConfig = `export default [{ files: ["**/*.{js,ts,tsx}"], rules: ${JSON.stringify(rules)} }];\n`; const [oxlint, eslint] = await Promise.all([ - lint({ ".oxlintrc.json": ofOxlint, ...files }, ["-f", "unix", ...names]), - lint({ "eslint.config.js": ofEslint, ...files }, ["-f", "unix", ...names]), + lint({ ".oxlintrc.json": oxlintConfig, ...files }, ["-f", "unix", ...names]), + lint({ "eslint.config.js": eslintConfig, ...files }, ["-f", "unix", ...names]), ]); expect(lines(oxlint.stdout).map(line => /no-debugger/.test(line))).toEqual(names.map(() => true)); expect(lines(eslint.stdout).map(line => /Parsing error: /.test(line))).toEqual(names.map(() => true)); }); - // Each row is what oxlint 1.87 prints, in its order. tsc, typescript-estree, espree and Babel reject an escape in a name of JSX. - test("with .oxlintrc.json a name of JSX with a unicode escape is the text as written", async () => { + // Each row is what oxlint 1.87 prints, in the same order. tsc, typescript-estree, espree and Babel reject an escape + // in a JSX name. + test("with .oxlintrc.json, a unicode escape in a JSX name isn't decoded", async () => { const rows: [extension: string, code: string, found: string[]][] = [ ["tsx", 'const X = () => null;\nexport const a = ;', []], ["jsx", "export const a = ;", []], ["jsx", 'export const a = ;', []], ["tsx", 'export const a = <\\u0061-b c-\\u0064="1" />;', []], ["tsx", "const X = { Y: () => null };\nexport const a = ;", []], - // It isn't the variable `Xe`. + // This doesn't refer to the variable `Xe`. [ "tsx", "const Xe = () => null;\nexport const a = ;", @@ -424,7 +432,7 @@ describe.concurrent("bun lint", () => { "eslint(no-unused-vars): Variable 'Xe' is declared but never used. Unused variables should start with a '_'. @6+2", ], ], - // A rule gets the whole name. + // Rules see the whole name, including the escape. [ "jsx", 'export const a =
    ;', @@ -453,7 +461,7 @@ describe.concurrent("bun lint", () => { ); }); - // tsc reports TS17021 and ESLint 10.12 "Unexpected token \\u0059". + // tsc reports TS17021, and ESLint 10.12 reports "Unexpected token \\u0059". test("an escape in a member of a JSX tag name is a parsing error with eslint.config.js", async () => { const config = `export default [{ files: ["**/*.jsx"], languageOptions: { parserOptions: { ecmaFeatures: { jsx: true } } } }];\n`; const code = "const X = { Y: () => null };\nexport const a = ;\n"; @@ -462,9 +470,9 @@ describe.concurrent("bun lint", () => { expect(exitCode).toBe(1); }); - // oxlint 1.87 lints all of these, and ESLint 10.12 with espree lints the .jsx files. tsc 6 and typescript-estree scan a - // JavaScript string, with escapes, as soon as something is between the `=` and the quote. - test("a JSX attribute string has no escapes, whatever is between the `=` and the quote", async () => { + // oxlint 1.87 lints all of these, and ESLint 10.12 with espree lints the .jsx files. tsc 6 and typescript-estree scan + // a JavaScript string, with escapes, as soon as anything comes between the `=` and the quote. + test("a JSX attribute string has no escapes, no matter what's between the `=` and the quote", async () => { const attributes = [ 'id = "x\\" density = "comfortable"', "id = 'x\\' density = 'comfortable'", @@ -482,11 +490,11 @@ describe.concurrent("bun lint", () => { const jsx = Object.fromEntries(code.map((it, i) => [`a${i}.jsx`, it])); const tsx = Object.fromEntries(code.map((it, i) => [`a${i}.tsx`, it])); const rules = { "no-debugger": "error" }; - const ofOxlint = JSON.stringify({ categories: { correctness: "off" }, rules }); - const ofEslint = `export default [{ files: ["**/*.jsx"], languageOptions: { parserOptions: { ecmaFeatures: { jsx: true } } }, rules: ${JSON.stringify(rules)} }];\n`; + const oxlintConfig = JSON.stringify({ categories: { correctness: "off" }, rules }); + const eslintConfig = `export default [{ files: ["**/*.jsx"], languageOptions: { parserOptions: { ecmaFeatures: { jsx: true } } }, rules: ${JSON.stringify(rules)} }];\n`; const [oxlint, eslint] = await Promise.all([ - lint({ ".oxlintrc.json": ofOxlint, ...jsx, ...tsx }, ["-f", "unix"]), - lint({ "eslint.config.js": ofEslint, ...jsx }, ["-f", "unix"]), + lint({ ".oxlintrc.json": oxlintConfig, ...jsx, ...tsx }, ["-f", "unix"]), + lint({ "eslint.config.js": eslintConfig, ...jsx }, ["-f", "unix"]), ]); const reported = (stdout: string) => stdout @@ -497,9 +505,9 @@ describe.concurrent("bun lint", () => { expect(reported(eslint.stdout).sort()).toEqual(expected(jsx).sort()); }); - // Each row is what oxlint 1.87 prints. tsc, typescript-estree and Babel leave the await and yield context inside a type, so - // there `await (k)` is a call of `await`. - test("with .oxlintrc.json an expression in a type is in the await and yield context around the type", async () => { + // Each row is what oxlint 1.87 prints. tsc, typescript-estree and Babel exit the await and yield context inside a + // type, so for them `await (k)` in a type calls a function named `await`. + test("with .oxlintrc.json, an expression in a type inherits the surrounding await and yield context", async () => { const rows: [extension: string, code: string, found: string[]][] = [ ["ts", 'const k = "a"; export let x: { [await (k)]: number };', []], [ @@ -565,7 +573,7 @@ describe.concurrent("bun lint", () => { 'const k = "a"; const f = async (a = await k) => {}; f(); export {};', ["error: await expression not allowed in formal parameter @36+7"], ], - // A declaration of TypeScript that is a statement by itself is outside the await context. + // A TypeScript declaration that is itself a statement is outside the await context. [ "ts", 'const k = "a"; type T = { [await (k)]: number }; export {};', @@ -596,12 +604,12 @@ describe.concurrent("bun lint", () => { 'const k = "a"; declare class C { [await (k)]: number } export {};', ["eslint(no-undef): 'await' is not defined. @34+5"], ], - // Nothing says that these are modules, so `await (k)` is a call. + // Nothing marks these as modules, so `await (k)` is a call. ["ts", 'const k = "a"; let x: { [await (k)]: number };', ["eslint(no-undef): 'await' is not defined. @25+5"]], ["ts", "const k = 1; await (k);", ["eslint(no-undef): 'await' is not defined. @13+5"]], ["js", "const k = 1; await (k);", ["eslint(no-undef): 'await' is not defined. @13+5"]], ["ts", "const k = [1]; await [k];", ["eslint(no-undef): 'await' is not defined. @15+5"]], - // `await k` says so. + // `await k` makes the file a module. ["ts", "const k = 1; await (k); await k;", []], ["ts", "const k = 1; await k; let x: { [await (k)]: number };", []], ["mts", 'const k = "a"; let x: { [await (k)]: number };', []], @@ -623,11 +631,9 @@ describe.concurrent("bun lint", () => { ); }); - // Each row is what oxlint 1.87 prints. oxc's parser reports these, so the file isn't linted. tsc leaves them to its checker - // (TS1308, TS1163), and typescript-estree says nothing. // Every row was run on oxlint 1.87. - test("with .oxlintrc.json an `await` that is put up with outside every body makes the file a module", async () => { - // What the `await` of `await (z);` in the next line is. In a script it is the name of a function. + test("with .oxlintrc.json, an `await` that's accepted outside every function body makes the file a module", async () => { + // `found` is how the `await` of `await (z);` on the next line is parsed. In a script it's the name of a function. const rows: [extensions: string, code: string, found: "the operator" | "a name"][] = [ ["ts tsx", "function f(): { [await g()]: 1 } { return null!; }", "the operator"], ["ts", "const f = function (): { [await g()]: 1 } { return null!; };", "the operator"], @@ -668,10 +674,13 @@ describe.concurrent("bun lint", () => { expect(found).toEqual(Object.fromEntries(cases.map(({ name, found }) => [name, found]))); }); - test("with .oxlintrc.json `await` outside an async function and `yield` outside a generator are errors", async () => { + // Each row is what oxlint 1.87 prints. oxc's parser reports these, so the file isn't linted. tsc leaves them to its + // checker (TS1308, TS1163), and typescript-estree doesn't report them. + test("with .oxlintrc.json, `await` outside an async function and `yield` outside a generator are errors", async () => { const all = "ts tsx mts cts js jsx mjs cjs"; const typescript = "ts tsx mts cts"; - // "await@15": the error about `await`, at offset 15. "linted": no error, and the `debugger` in the last line is reported. + // "await@15": the error about `await`, at offset 15. "linted": no error, and the `debugger` on the last line is + // reported. const rows: [extensions: string, code: string, found: string][] = [ [all, "function f() { await g(); }", "await@15"], [all, "function f() { return await g; }", "await@22"], @@ -693,7 +702,7 @@ describe.concurrent("bun lint", () => { [all, "function f() { class A { [await g()]() {} } }", "await@26"], [all, "function f() { function h(a = await g()) {} }", "await@30"], [all, "function f(a = () => await g()) {}", "await@21"], - // One error: what follows the first `await` is read as if it were in an async function. + // Only one error, because whatever follows the first `await` is parsed as if it were in an async function. [all, "function f() { await await g; }", "await@15"], [all, "function f() { await x(await y); }", "await@15"], // In an async function, or not a keyword. @@ -713,7 +722,7 @@ describe.concurrent("bun lint", () => { ["ts tsx cts js jsx cjs", "function f() { for (await of x) ; }", "linted"], ["mts mjs", "function f() { for (await of x) ; }", "The keyword 'await' is reserved @20+5"], ["ts tsx cts js jsx cjs", "var await; await = 1;", "linted"], - // Outside every function: by the name of the file. + // Outside every function, it depends on the file extension. ["ts tsx mts js jsx mjs", "await g();", "linted"], ["cts cjs", "await g();", "await@0"], ["ts tsx js jsx", "class A { x = await g(); }", "linted"], @@ -768,7 +777,7 @@ describe.concurrent("bun lint", () => { [typescript, "function f() { type T = { [await g]: 1 }; }", "await@27"], ["ts tsx", "function f(): { [await g]: 1 } { return null!; }", "linted"], ["mts cts", "function f(): { [await g]: 1 } { return null!; }", "await@17"], - // A signature in a type starts nothing: it is in the block. + // A signature in a type doesn't start a new context, so it's still in the static block. [ "ts tsx", "class A { static { type F = { (): { [await g()]: 1 } }; } }", @@ -781,13 +790,13 @@ describe.concurrent("bun lint", () => { "Cannot use await in class static initialization block @48+5", ], ["mts cts", "class A { static { interface I { m(): void } } }", "await@48"], - // The type of a variable is read in the context of the block, where `await` is the operator. + // A variable's type is parsed in the block's context, where `await` is the operator. [ typescript, "class A { static { let v: { get x(): { [await g()]: 1 } }; } }", "Cannot use await in class static initialization block @40+5", ], - // A function does, with or without a body. + // A function does start a new context, with or without a body. ["ts tsx", "class A { static { abstract class B { abstract m(): { [await g()]: 1 }; } } }", "linted"], ["ts tsx", "class A { static { function f(): { [await g()]: 1 } { return null!; } } }", "linted"], [typescript, "function o() { @dec(await g()) class A {} }", "await@20"], @@ -795,7 +804,7 @@ describe.concurrent("bun lint", () => { ["ts tsx", "declare const x = await g;", "linted"], ["mts cts", "declare const x = await g;", "await@18"], [typescript, "function f() { let x: { [yield g]: 1 }; }", "yield@25"], - // Arrow parameters are read in the context around the arrow function. + // Arrow parameters are parsed in the context surrounding the arrow function. [ all, "async function f() { const h = (a = await g()) => a; }", @@ -808,7 +817,7 @@ describe.concurrent("bun lint", () => { "function* f() { const h = (a = yield g) => a; }", "yield expression not allowed in formal parameter @31+7", ], - // `await` and `using` on two lines are no declaration. + // `await` and `using` on separate lines aren't a declaration. ["ts tsx cts js jsx cjs", "function f() { await\nusing x = g(); }", "linted"], ["mts mjs", "function f() { await\nusing x = g(); }", "The keyword 'await' is reserved @15+5"], [ @@ -865,10 +874,11 @@ describe.concurrent("bun lint", () => { expect(found).toEqual(Object.fromEntries(cases.map(({ name, found }) => [name, [found]]))); }); - // Each row is what oxlint 1.87 does. oxc can't parse Flow. Where it fails on a JavaScript file whose first comment has `@flow`, - // oxlint prints nothing about the file. - test("with .oxlintrc.json a file that doesn't parse is skipped silently if its first comment has @flow", async () => { - // "silent": nothing is printed. "error": only a syntax error. "linted": the `debugger` in the last line is reported. + // Each row is what oxlint 1.87 does. oxc can't parse Flow. If it fails on a JavaScript file whose first comment has + // `@flow`, oxlint prints nothing about the file. + test("with .oxlintrc.json, a file that doesn't parse is skipped silently if its first comment has @flow", async () => { + // "silent": nothing is printed. "error": only a syntax error. "linted": the `debugger` on the last line is + // reported. const rows: [extension: string, code: string, outcome: "silent" | "error" | "linted"][] = [ ["js", "// @flow\ntype A = number;", "silent"], ["js", "// @flow\nimport typeof X from 'x';", "silent"], @@ -885,20 +895,20 @@ describe.concurrent("bun lint", () => { ["js", "import /* @flow */ typeof X from 'x';", "silent"], ["js", "type /* @flow */ A = number;", "silent"], ["js", "foo( // @flow\n;", "silent"], - // Oxc's lexer hasn't come to the comment yet. + // Oxc's lexer hasn't reached the comment yet. ["js", "import typeof /* @flow */ X from 'x';", "error"], ["js", "import typeof X from 'x';\n// @flow", "error"], ["js", "type A /* @flow */ = number;", "error"], ["js", "type A = number; // @flow", "error"], ["js", "type A = number;\n// @flow", "error"], ["js", "foo(; // @flow", "error"], - // Only the first comment counts, and only in JavaScript. + // Only the first comment is checked, and only in JavaScript. ["js", "// first\n// @flow\nimport typeof X from 'x';", "error"], ["js", "// @noflow\nimport typeof X from 'x';", "error"], ["js", "import typeof X from 'x';", "error"], ["ts", "// @flow\nimport typeof X from 'x';", "error"], ["js", "// @flow\nfoo();", "linted"], - // Oxc goes on after these errors, to the end of the file, so it comes to the comment. + // Oxc recovers from these errors and continues to the end of the file, so it reaches the comment. ["js", "function f() { await g(); }\n// @flow", "silent"], ["js", "function f() { yield 1; }\n// @flow", "silent"], ["js", "function f() { await g(); } // @flow\nlet = ;", "silent"], @@ -929,8 +939,9 @@ describe.concurrent("bun lint", () => { ); }); - // Each text is what oxlint 1.87 prints with --threads 1. It prints the files in no particular order in two of the formats. - test("with .oxlintrc.json every format has the code, the help and every occurrence of a syntax error", async () => { + // Each expected output is what oxlint 1.87 prints with --threads 1. In two of the formats it prints the files in no + // particular order. + test("with .oxlintrc.json, every format includes a syntax error's code and help, and reports each occurrence", async () => { const files = { ".oxlintrc.json": JSON.stringify({ categories: { correctness: "off" }, rules: { "no-debugger": "error" } }), "f1.ts": "class A { constructor(); }\n", @@ -943,7 +954,7 @@ describe.concurrent("bun lint", () => { const print = async (format: string) => { const { raw, stdout, exitCode } = await lint(files, ["--threads", "1", "-f", format, ...names]); expect(exitCode).toBe(1); - // Only this one has the directory in it. + // Only stylish prints absolute paths. return (format === "stylish" ? stdout : raw) .replace(/\x1b\[[0-9;]*m/g, "") .replace(/Finished in [\d.]+ms/, "Finished in Nms"); @@ -1119,7 +1130,7 @@ describe.concurrent("bun lint", () => { }); // Each row is what oxlint 1.87 does. - test("with .oxlintrc.json a file is a script if nothing in it says that it is a module", async () => { + test("with .oxlintrc.json, a file is a script unless its extension or its code makes it a module", async () => { const name = "var await = 1; f(await);\n"; const comments = "var a; d\n"; const linted = { @@ -1132,7 +1143,7 @@ describe.concurrent("bun lint", () => { "b.ts": comments, "b.cts": comments, }; - const refused = { + const rejected = { "c.mjs": name, "c.mts": name, "d.mjs": comments, @@ -1140,25 +1151,26 @@ describe.concurrent("bun lint", () => { "e.js": `export {};\nf(await);\n`, "e.ts": `export {};\nf(await);\n`, "f.js": `export {};\n${comments}`, - // A module by its `await`, and no script with it. + // This is a module because of its `await`, which doesn't parse in a script. "g.js": `await f();\n${comments}`, "g.ts": `await f();\n${comments}`, "h.js": "var await = 1; let x = ;\n", }; const settings = JSON.stringify({ categories: { correctness: "off" }, rules: {} }); - const files = { ...linted, ...refused }; + const files = { ...linted, ...rejected }; const { stdout, exitCode } = await lint({ ".oxlintrc.json": settings, ...files }, [ "-f", "unix", ...Object.keys(files), ]); const reported = stdout.split("\n").flatMap(line => line.match(/^([a-h]\.\w+):\d+:\d+: .* \[Error\]$/)?.[1] ?? []); - expect([...new Set(reported)].sort()).toEqual(Object.keys(refused).sort()); + expect([...new Set(reported)].sort()).toEqual(Object.keys(rejected).sort()); expect(exitCode).toBe(1); }); - // Each is what ESLint says with espree. At the `<` of the first two the parser went round until its stack was used up. - test("which error of broken JavaScript is reported, and where", async () => { + // Each error is what ESLint reports with espree. At the `<` of the first two, the parser used to recurse until it + // overflowed the stack. + test("reports the same error at the same position as espree for broken JavaScript", async () => { const cases: Record = { "a0.js": ["{} while (a)< {}", "1:13: Parsing error: Unexpected token <"], "a1.js": ["var arr =< [, ,];", "1:10: Parsing error: Unexpected token <"], @@ -1172,10 +1184,10 @@ describe.concurrent("bun lint", () => { 'import { a } om "foo"', "1:1: Parsing error: 'import' and 'export' may appear only with 'sourceType: module'", ], - // acorn skips a comment before the string of an attribute, which can have a line break. + // acorn skips a comment before an attribute's string, and the string can contain a line break. "a6.jsx": [';'], "a7.js": ["a = => 1;", "1:5: Parsing error: Unexpected token =>"], - // What is in parentheses is no mix with `??`, however many parentheses follow it. + // A parenthesized `||` or `&&` isn't mixed with `??`, no matter how many parentheses follow it. "a8.js": ["(a || b) ?? ((c)); (a && b) ?? [((c))]; f((a || b) ?? !((c)));"], }; const files = Object.fromEntries(Object.entries(cases).map(([name, [code]]) => [name, code + "\n"])); @@ -1197,9 +1209,9 @@ describe.concurrent("bun lint", () => { expect(exitCode).toBe(1); }); - // Each place is what ESLint 10.12.0 reports. - describe("no-useless-assignment as ESLint has it", () => { - const places = async (lines: string[]) => { + // Each position is what ESLint 10.12.0 reports. + describe("no-useless-assignment matches ESLint", () => { + const positions = async (lines: string[]) => { const files = { "eslint.config.js": config({ "no-useless-assignment": "error" }), "a.cjs": lines.join("\n") + "\n", @@ -1208,9 +1220,9 @@ describe.concurrent("bun lint", () => { return [...raw.matchAll(/\ba\.cjs:(\d+:\d+):/g)].map(it => it[1]); }; - test("the `arguments` of a function is a variable", async () => { + test("a function's `arguments` is treated as a variable", async () => { expect( - await places([ + await positions([ `function a() { arguments = arguments + 1; }`, `function b() { arguments = 1; }`, `function c() { arguments = 1; d(arguments); arguments = 2; }`, @@ -1223,9 +1235,9 @@ describe.concurrent("bun lint", () => { ).toEqual(["1:16", "3:45", "4:16", "5:30", "6:20", "6:40"]); }); - test("a `var` in the block of a `catch` writes the parameter of that name", async () => { + test("a `var` in a `catch` block writes to the catch parameter with the same name", async () => { expect( - await places([ + await positions([ `function a() { try { g(); } catch (e) { h(e); var e = 1; } }`, `function b() { try { g(); } catch (e) { h(e); e = 1; } }`, `function c() { try { g(); } catch (e) { var e = 1; h(e); } }`, @@ -1240,9 +1252,9 @@ describe.concurrent("bun lint", () => { ).toEqual(["1:51", "2:47", "4:51", "5:58", "6:45", "7:53", "8:56", "9:66", "10:51"]); }); - test("two of them, and the variable of the function beside the parameter", async () => { + test("two `var`s in a `catch` block, and a function-level variable with the same name as the catch parameter", async () => { expect( - await places([ + await positions([ `try {`, `\tthrow new Error();`, `} catch (e) {`, @@ -1256,7 +1268,7 @@ describe.concurrent("bun lint", () => { ]), ).toEqual(["4:6"]); expect( - await places([ + await positions([ `var e = 0; try { throw x.e; } catch (e) { var e = 7; } assertEquals(0, e);`, `let c = 1; c = 2; assertEquals(c);`, ]), @@ -1264,7 +1276,7 @@ describe.concurrent("bun lint", () => { }); }); - describe("which files", () => { + describe("which files are linted", () => { const files = { "eslint.config.js": config({ "no-debugger": "error" }), "a.js": "debugger;\n", @@ -1295,7 +1307,7 @@ describe.concurrent("bun lint", () => { }); }); - test("files, directories and patterns", async () => { + test("files, directories and patterns passed as arguments", async () => { expect( await Promise.all([listed(["a.js", "src/deep"]), listed(["src/*.{mjs,cjs}"]), listed(["**/f.js"])]), ).toEqual([ @@ -1305,25 +1317,109 @@ describe.concurrent("bun lint", () => { ]); }); - test("--ext", async () => { + test("--ext also lints files with that extension", async () => { expect(await listed(["--ext", ".ts", "src/d.ts", "src/deep"])).toEqual({ files: ["/src/d.ts", "/src/deep/f.js"], exitCode: 0, }); }); - test("--ignore-pattern", async () => { + test("--ignore-pattern excludes directories and files", async () => { expect(await listed(["--ignore-pattern", "src/deep/", "--ignore-pattern", "**/*.mjs", "src"])).toEqual({ files: ["/src/.hidden/e.js", "/src/c.cjs"], exitCode: 0, }); }); - test("from a subdirectory, with the configuration above", async () => { + test("only the subdirectory when run from one, with the config in a parent directory", async () => { expect(await listed([], { cwd: "src/deep" })).toEqual({ files: ["/src/deep/f.js"], exitCode: 0 }); }); - test.skipIf(isWindows)("a named pipe with the name of a script is passed over", async () => { + // Same as `bun fmt` and Prettier. ESLint 10.12.0 exits with code 2 for these arguments. oxlint 1.87.0 ignores them. + describe.each([ + ["no config", {}], + ["eslint.config.js", { "eslint.config.js": config({ "no-var": "error" }) }], + [".oxlintrc.json", { ".oxlintrc.json": "{}\n" }], + ])("an argument that starts with ! excludes files: %s", (name, project) => { + const code = "var a = 1;\n"; + const files = { + ...project, + "src/f.js": code, + "src/g.js": code, + "src/deep/h.js": code, + "other/o.js": code, + "top.js": code, + }; + const listed = async (...args: string[]) => { + const { stdout, stderr, exitCode } = await lint(files, ["--list-files", ...args], { mayFail: true }); + return { files: stdout.split("\n").filter(Boolean), stderr: stderr.split("\n")[0], exitCode }; + }; + + test.each([ + [ + ["src", "!src/f.js"], + ["/src/deep/h.js", "/src/g.js"], + ], + [ + ["!src/f.js", "src"], + ["/src/deep/h.js", "/src/g.js"], + ], + [["src/*.js", "!src/f.js"], ["/src/g.js"]], + [ + ["src", "!src/deep"], + ["/src/f.js", "/src/g.js"], + ], + [["src", "!**/h.js", "!./src/g.js"], ["/src/f.js"]], + [ + ["src", "top.js", "!nothing.js"], + ["/src/deep/h.js", "/src/f.js", "/src/g.js", "/top.js"], + ], + // A `!` that isn't at the start of the argument opens an extglob group. + [["src/!(f).js"], ["/src/g.js"]], + ])("%j", async (args, expected) => { + expect(await listed(...args)).toEqual({ files: expected, stderr: "", exitCode: 0 }); + }); + + test.skipIf(name === ".oxlintrc.json")("exits with code 2 when the arguments don't select any file", async () => { + expect( + await Promise.all([listed("!top.js"), listed("top.js", "!top.js"), listed("src/*.js", "!src/*")]), + ).toEqual([ + { files: [], stderr: 'error: No files matching the pattern "!top.js" were found.', exitCode: 2 }, + { + files: [], + stderr: + 'error: You are linting "top.js", but all of the files matching the glob pattern "top.js" are ignored.', + exitCode: 2, + }, + { + files: [], + stderr: + 'error: You are linting "src/*.js", but all of the files matching the glob pattern "src/*.js" are ignored.', + exitCode: 2, + }, + ]); + }); + + // Same as oxfmt. + test.skipIf(name !== ".oxlintrc.json")( + "with no other argument, lints the rest of the working directory", + async () => { + expect(await listed("!top.js")).toEqual({ + files: ["/other/o.js", "/src/deep/h.js", "/src/f.js", "/src/g.js"], + stderr: "", + exitCode: 0, + }); + }, + ); + + test("--fix only writes to the selected files", async () => { + const reads = ["src/f.js", "src/g.js", "src/deep/h.js", "other/o.js", "top.js"]; + const result = await lint(files, ["--fix", "--rule", "no-var: error", "src", "!src/f.js"], { reads }); + expect(reads.filter(name => result.files[name] !== code)).toEqual(["src/g.js", "src/deep/h.js"]); + }); + }); + + test.skipIf(isWindows)("a named pipe whose name ends in .js is skipped", async () => { const { stdout, exitCode } = await lint({ "eslint.config.js": basic, "a.js": bad }, ["-f", "unix", "."], { before: dir => expect(Bun.spawnSync(["mkfifo", join(dir, "pipe.js")]).exitCode).toBe(0), }); @@ -1332,11 +1428,125 @@ describe.concurrent("bun lint", () => { expect(exitCode).toBe(1); }); - // git keeps a link to `/dev/zero` as it is. + // Opening a pipe like this blocks until a writer opens it. + test.skipIf(isWindows).each([".gitignore", ".git/info/exclude", ".eslintignore", "package.json"])( + "doesn't hang when %s is a link to a named pipe without a writer", + async name => { + const { raw } = await lint({ "project/a.js": bad, "project/.git/info/a": "" }, ["-f", "json", "."], { + cwd: "project", + before: dir => { + expect(Bun.spawnSync(["mkfifo", join(dir, "pipe")]).exitCode).toBe(0); + symlinkSync(join(dir, "pipe"), join(dir, "project", name)); + }, + }); + expect(raw).toContain("a.js"); + }, + ); + + describe.skipIf(isWindows)("a named pipe passed to a flag", () => { + const makePipes = (dir: string) => + expect(Bun.spawnSync(["mkfifo", join(dir, "pipe"), join(dir, "pipe.json")]).exitCode).toBe(0); + + // Reading the pipe as empty would silently disable the ignore list, so it's an error. `bun lint` doesn't block + // waiting for a writer either. + describe.each([ + ["no config", {}], + ["eslint.config.js", { "eslint.config.js": basic }], + [".oxlintrc.json", { ".oxlintrc.json": "{}\n" }], + [".eslintrc.json", { ".eslintrc.json": "{}\n" }], + ])("without a writer is an error, with %s", (_, config: Record) => { + test.each([ + [["--ignore-path", "pipe"], "pipe"], + [["--ignore-path=./pipe"], "./pipe"], + [["--config", "pipe.json"], "pipe.json"], + [["-c", "pipe.json"], "pipe.json"], + [["--config=pipe"], "pipe"], + ])("%j", async (flags, name) => { + const result = await lint({ ...config, "a.js": bad }, ["--fix", ...flags, "."], { + before: makePipes, + reads: ["a.js"], + mayFail: true, + }); + expect(result.stderr).toBe(`error: cannot read ${name}: nothing is writing to this pipe`); + expect(result.raw).toBe(""); + expect(result.files).toEqual({ "a.js": bad }); + expect(result.exitCode).toBe(2); + }); + }); + + test("a pipe set as ignorePath in bunfig.toml is still read as empty", async () => { + const files = { "bunfig.toml": '[lint]\nignorePath = "pipe"\n', "a.js": bad }; + const { stdout, exitCode } = await lint(files, ["-f", "unix", "."], { before: makePipes }); + expect(stdout).toContain("/a.js:2:15: "); + expect(exitCode).toBe(1); + }); + + // `--ignore-path <(true)` + test("a pipe whose writer closes it without writing is read as an empty file", async () => { + using dir = tempDir("bun-lint", { "a.js": bad }); + await using proc = spawn({ + cmd: ["sh", "-c", ': | "$0" "$@"', ...command, "-f", "unix", "--ignore-path", "/dev/stdin", "."], + env, + cwd: String(dir), + stdin: "ignore", + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).not.toContain("cannot read"); + expect(stdout).toContain("a.js:2:15: "); + expect(exitCode).toBe(1); + }); + + /** Runs `bun lint` with `args` in a directory containing `files` while writing `text` to the pipe `name`. */ + async function lintWhileWriting(files: Record, args: string[], name: string, text: string) { + using dir = tempDir("bun-lint", files); + makePipes(String(dir)); + // With a reader open, opening the pipe for writing doesn't block, and written data stays buffered. + const reader = openSync(join(String(dir), name), constants.O_RDONLY | constants.O_NONBLOCK); + const writer = openSync(join(String(dir), name), constants.O_WRONLY); + try { + const stdio = { stdin: "ignore", stdout: "pipe", stderr: "pipe" } as const; + await using proc = spawn({ cmd: [...command, ...args], env, cwd: String(dir), ...stdio }); + writeSync(writer, text); + closeSync(writer); + const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); + return { stdout, exitCode }; + } finally { + closeSync(reader); + } + } + + // A pipe can only be read once, but the ignore list is needed for every directory that is searched. + test.each([ + ["no config", {}, 1], + [".oxlintrc.json", { ".oxlintrc.json": "{}\n" }, 0], + [".eslintrc.json", { ".eslintrc.json": '{ "rules": { "no-debugger": "error" } }\n' }, 1], + ])("--ignore-path reads patterns written to the pipe, with %s", async (_, config, exitCode) => { + const files = { ...config, "src/a.js": bad, "src/b.js": bad, "lib/a.js": bad, "lib/b.js": bad }; + const args = ["-f", "unix", "--ignore-path", "pipe", "src", "lib"]; + const result = await lintWhileWriting(files, args, "pipe", "a.js\n"); + expect(result.stdout.match(/(?:src|lib)\/[ab]\.js:2:15/g)).toEqual(["lib/b.js:2:15", "src/b.js:2:15"]); + expect(result.exitCode).toBe(exitCode); + }); + + // Detecting whether the config is oxlint's or ESLint's also reads the file, and a pipe can only be read once. + test.each([ + ["oxlint", '{ "rules": { "no-debugger": "off", "eqeqeq": "error" } }\n'], + ["ESLint 8", '{ "root": true, "rules": { "eqeqeq": "error" } }\n'], + ])("--config reads a config written to the pipe, for %s", async (_, text) => { + const args = ["-f", "unix", "--config", "pipe.json", "a.js"]; + const result = await lintWhileWriting({ "a.js": bad }, args, "pipe.json", text); + expect(result.stdout.match(/a\.js:\d+:\d+: .+/g)).toEqual([expect.stringContaining("eqeqeq")]); + expect(result.exitCode).toBe(1); + }); + }); + + // git stores a link to `/dev/zero` as is, so a repository can contain one. test.skipIf(isWindows).each([ ["eslint.config.js", basic], [".oxlintrc.json", "{}"], - ])("a link to a device with the name of a script is passed over: %s", async (name, text) => { + ])("a link to a device whose name ends in .js is skipped: %s", async (name, text) => { const { raw } = await lint({ [name]: text, "a.js": bad }, ["-f", "json", "."], { before: dir => symlinkSync("/dev/null", join(dir, "device.js")), }); @@ -1344,8 +1554,9 @@ describe.concurrent("bun lint", () => { expect(raw).not.toContain("device.js"); }); - // It has holes for all its bytes. Node: "Cannot create a string longer than 0x1fffffe8 characters". - test("a file that JavaScript could not hold as a string is not read", async () => { + // The file is sparse, so it takes no disk space. Node says "Cannot create a string longer than 0x1fffffe8 + // characters". + test("a file too large for a JavaScript string isn't read, and the run fails with EFBIG", async () => { const { stderr, exitCode } = await lint({ "eslint.config.js": basic, "a.js": "", "b.js": bad }, ["."], { before: dir => truncateSync(join(dir, "a.js"), 2 ** 29), mayFail: true, @@ -1371,8 +1582,8 @@ describe.concurrent("bun lint", () => { }); }); - // A junction takes no privilege on Windows. Elsewhere it is a link like any other. - test("a link to a directory is not followed, on Windows neither", async () => { + // Creating a junction doesn't need a privilege on Windows. On other systems it's an ordinary symlink. + test("a link to a directory isn't followed on Windows either", async () => { const before = (dir: string) => symlinkSync(join(dir, "src", "deep"), join(dir, "src", "linked"), "junction"); expect(await listed(["src"], { before })).toEqual({ files: ["/src/.hidden/e.js", "/src/b.mjs", "/src/c.cjs", "/src/deep/f.js"], @@ -1380,8 +1591,8 @@ describe.concurrent("bun lint", () => { }); }); - // Every snapshot above has `/` for `\\`, so none of them can tell. - test("paths are printed as the system writes them", async () => { + // Every snapshot above has `\\` replaced with `/`, so none of them would catch this. + test("paths are printed with the platform's separator", async () => { const inDirectory = async (args: string[]) => { let root = ""; const { raw } = await lint(files, args, { before: dir => void (root = dir) }); @@ -1401,8 +1612,8 @@ describe.concurrent("bun lint", () => { expect(list.raw).toBe(`${list.file}\n`); }); - test.skipIf(!hasRunner)("paths are computed as by node:path, those of Windows on every system", async () => { - // Not where a `package.json` has a script `lint`. + test.skipIf(!hasRunner)("path helpers match node:path, including win32 paths on every platform", async () => { + // Don't run in a directory whose `package.json` has a `lint` script. using dir = tempDir("bun-lint", {}); const cases = { windows: { @@ -1496,11 +1707,11 @@ describe.concurrent("bun lint", () => { expect(all.map((it, i) => [...it, answers[i]])).toEqual(all.map((it, i) => [...it, expected[i]])); expect(exitCode).toBe(0); } - // A path on another drive that does not start at its root is from the working directory, which is that of the process. + // A path on another drive that isn't absolute (`D:a`) is resolved against the process's working directory. const script = `console.log(require("node:path").win32.resolve("C:/proj", "D:a").replaceAll("\\\\", "/"))`; - const ofNode = Bun.spawnSync({ cmd: [bunExe(), "-e", script], cwd: String(dir), env }); + const fromNode = Bun.spawnSync({ cmd: [bunExe(), "-e", script], cwd: String(dir), env }); const onOtherDrive = await run(String(dir), ["--run-path-tests", "windows", "resolve", "C:/proj", "D:a"]); - expect(onOtherDrive.stdout).toBe(ofNode.stdout.toString()); + expect(onOtherDrive.stdout).toBe(fromNode.stdout.toString()); const inside = ["c:/proj", "C:/PROJ/a.js", "C:/proj", "C:/project/a.js", "C:/", "c:/a.js"].flatMap((it, i) => i % 2 ? [it] : ["inside", it], ); @@ -1522,7 +1733,7 @@ describe.concurrent("bun lint", () => { expect(exitCode).toBe(2); }); - test("--no-error-on-unmatched-pattern", async () => { + test("--no-error-on-unmatched-pattern exits with 0 if an argument matches nothing", async () => { const { exitCode } = await lint(files, ["--no-error-on-unmatched-pattern", "nothing.js", "nothing/**"]); expect(exitCode).toBe(0); }); @@ -1533,7 +1744,7 @@ describe.concurrent("bun lint", () => { expect(exitCode).toBe(2); }); - test("warns about a named file that is not linted", async () => { + test("warns about a file passed as an argument that isn't linted", async () => { const { stdout, exitCode } = await lint(files, ["src/d.ts", "node_modules/pkg/g.js"]); expect(stdout).toMatchInlineSnapshot(` "/node_modules/pkg/g.js @@ -1547,15 +1758,15 @@ describe.concurrent("bun lint", () => { expect(exitCode).toBe(0); }); - test("--no-warn-ignored", async () => { + test("--no-warn-ignored hides the warning about an ignored file", async () => { const { raw, exitCode } = await lint(files, ["--no-warn-ignored", "src/d.ts"]); expect(raw).toBe(""); expect(exitCode).toBe(0); }); }); - describe("configuration", () => { - test("global ignores, files, and --no-ignore", async () => { + describe("config", () => { + test("applies global ignores and `files`, and --no-ignore lints ignored files", async () => { const files = { "eslint.config.js": `export default [{ ignores: ["dist/"] }, { files: ["**/*.ts"], rules: { "no-debugger": "error" } }];`, "a.ts": "debugger;\n", @@ -1576,7 +1787,7 @@ describe.concurrent("bun lint", () => { `); }); - test("the nearest configuration file counts", async () => { + test("the nearest config file is used", async () => { const { stdout } = await lint( { "eslint.config.js": config({ "no-debugger": "error" }), @@ -1596,7 +1807,7 @@ describe.concurrent("bun lint", () => { `); }); - test("-c replaces every other configuration file", async () => { + test("-c replaces every other config file", async () => { const { stdout } = await lint( { "eslint.config.js": config({ "no-debugger": "error" }), @@ -1615,7 +1826,7 @@ describe.concurrent("bun lint", () => { `); }); - test("a configuration file in TypeScript, CommonJS, or that exports a promise", async () => { + test("loads a config file written in TypeScript or CommonJS, or one that exports a promise", async () => { const results = await Promise.all([ lint( { @@ -1642,7 +1853,7 @@ describe.concurrent("bun lint", () => { } }); - test("a configuration file that throws fails with 2", async () => { + test("a config file that throws fails with 2", async () => { const { raw, stderr, exitCode } = await lint( { "eslint.config.js": `throw new Error("not today");`, "a.js": "" }, [], @@ -1664,7 +1875,7 @@ describe.concurrent("bun lint", () => { }); test( - "the rules of a plugin run, and their fixes are applied", + "a plugin's rules run, and their fixes are applied", async () => { const files = { "eslint.config.js": ` @@ -1697,7 +1908,7 @@ describe.concurrent("bun lint", () => { isDebug || isASAN ? 120_000 : 30_000, ); - test("--rule, --global, --no-config-lookup", async () => { + test("--rule and --global apply, and --no-config-lookup ignores the config file", async () => { const { stdout } = await lint( { "eslint.config.js": config({ "no-debugger": "error" }), "a.js": "debugger; a = b; c = a == 1;\n" }, [ @@ -1720,7 +1931,7 @@ describe.concurrent("bun lint", () => { `); }); - test("--print-config", async () => { + test("--print-config prints a file's resolved config, or `undefined` if no config applies to it", async () => { const files = { "eslint.config.js": config({ eqeqeq: ["error", "smart"], "no-debugger": "off" }), "a.js": "" }; const [known, unknown] = await Promise.all([ lint(files, ["--print-config", "a.js"]), @@ -1734,7 +1945,7 @@ describe.concurrent("bun lint", () => { expect(unknown.raw).toBe("undefined\n"); }); - test.each([[["--print-config"]], [["--print-config", "--fix"]]])("%j names no file", async flags => { + test.each([[["--print-config"]], [["--print-config", "--fix"]]])("%j without a file is an error", async flags => { const files = { "eslint.config.js": config({ eqeqeq: "error" }), "a.js": "" }; const { raw, stderr, exitCode } = await lint(files, flags, { mayFail: true }); expect({ raw, stderr: stderr.split("\n")[0], exitCode }).toEqual({ @@ -1744,7 +1955,7 @@ describe.concurrent("bun lint", () => { }); }); - test(".oxlintrc.json: categories, overrides, ignorePatterns, .gitignore, -D", async () => { + test("applies categories, overrides and ignorePatterns from .oxlintrc.json, plus .gitignore and -D", async () => { const { stdout, exitCode } = await lint( { ".oxlintrc.json": `{ @@ -1773,7 +1984,8 @@ describe.concurrent("bun lint", () => { }); describe("like oxlint, with an .oxlintrc.json", () => { - // What oxlint 1.87.0 does with each. TypeScript's parser, which reads the file here, takes them all. + // This is what oxlint 1.87.0 does with each row. `bun lint` parses the file with TypeScript's parser, which + // accepts them all. const quiet = JSON.stringify({ categories: { correctness: "off" }, rules: {} }); test.each([ ["a.ts", "const a: string;"], @@ -1791,24 +2003,24 @@ describe.concurrent("bun lint", () => { ["a.js", "export {};\nstatic = 1;"], ["a.js", "[a()] = b;"], ["a.js", "a = /a/gg;"], - ])("what OXC refuses is a parsing error: %s: %j", async (name, code) => { + ])("code that OXC rejects is a parsing error: %s: %j", async (name, code) => { const { stdout, exitCode } = await lint({ ".oxlintrc.json": quiet, [name]: code + "\n" }, ["-f", "unix"]); expect(stdout).toMatch(/^a\.[jt]s:\d+:\d+: (?!Parsing error).* \[Error\]$/m); expect(exitCode).toBe(1); }); // The message, and the offset and length of the first label, are what oxlint 1.87 prints. - test("the label of a parsing error is as long as oxlint's", async () => { - const waits = "only allowed within async functions and at the top levels of modules"; + test("a parsing error's label has the same offset and length as oxlint's", async () => { + const onlyInAsync = "only allowed within async functions and at the top levels of modules"; const rows: [extension: string, code: string, message: string, offset: number, length: number][] = [ ["cjs", 'import a from "a";', "Cannot use import statement outside a module", 0, 6], ["cjs", "export const a = 1;", "Cannot use export statement outside a module", 0, 6], ["cjs", "x = import.meta.url;", "Unexpected import.meta expression", 4, 11], ["cts", "x = import.meta.url;", "Unexpected import.meta expression", 4, 11], - ["cjs", "await 1;", `\`await\` is ${waits}`, 0, 5], - ["cts", "await 1;", `\`await\` is ${waits}`, 0, 5], - ["cjs", "for await (const a of b) {}", `\`for await\` loops are ${waits}`, 4, 5], - ["js", "function f() { for await (const a of b) {} }", `\`for await\` loops are ${waits}`, 19, 5], + ["cjs", "await 1;", `\`await\` is ${onlyInAsync}`, 0, 5], + ["cts", "await 1;", `\`await\` is ${onlyInAsync}`, 0, 5], + ["cjs", "for await (const a of b) {}", `\`for await\` loops are ${onlyInAsync}`, 4, 5], + ["js", "function f() { for await (const a of b) {} }", `\`for await\` loops are ${onlyInAsync}`, 19, 5], ["ts", "export {}; function yield() {}", "The keyword 'yield' is reserved", 20, 5], ["ts", "export {}; class let {}", "The keyword 'let' is reserved", 17, 3], ["ts", "export {}; static: for(;;){}", "The keyword 'static' is reserved", 11, 6], @@ -1861,8 +2073,9 @@ describe.concurrent("bun lint", () => { labels: { label?: string; span: { offset: number; length: number } }[]; }; /** - * Lints each row as a file of its own and returns the rows with what was printed: every error of the file in order, as - * its message (or the short word for it in `words`) and the offset and length of each label. + * Lints each row as its own file and returns the rows with the errors that were printed. A file's errors are + * listed in order, each as its message (or the message's short form in `words`) plus the offset and length of + * each label. */ const withErrorsFound = async ( rows: ErrorRow[], @@ -1877,14 +2090,14 @@ describe.concurrent("bun lint", () => { const print = ({ message, labels }: OxlintDiagnostic) => `${short(message)} ${labels.map(({ span }) => `${span.offset}+${span.length}`).join(",")}`; const found = rows.map(([extension, code], i): ErrorRow => { - const ofFile = diagnostics.filter(it => it.filename === `a${i}.${extension}`); - return [extension, code, ofFile.map(print).join(", ")]; + const fileDiagnostics = diagnostics.filter(it => it.filename === `a${i}.${extension}`); + return [extension, code, fileDiagnostics.map(print).join(", ")]; }); return { found, diagnostics }; }; - // Each row is what oxlint 1.87 prints. "" means that it lints the file. tsc and typescript-estree reject `a = 1`, - // `a as T = 1` and `++a`: to them a type assertion is no left-hand side. + // Each row is what oxlint 1.87 prints. "" means that it lints the file. tsc and typescript-estree reject + // `a = 1`, `a as T = 1` and `++a`, because to them a type assertion isn't a left-hand-side expression. test("assignment targets are checked like oxc's parser checks them", async () => { const words: Record = { "Cannot assign to this expression": "cannot", @@ -2240,12 +2453,13 @@ describe.concurrent("bun lint", () => { for (const { message, help } of diagnostics) expect([message, help]).toEqual([message, helps[words[message]]]); }); - // The parser gives up on these in the middle of a module. Like oxlint 1.87, one error on line 2 and nothing about exports. + // The parser gives up on these in the middle of a module. Like oxlint 1.87, `bun lint` prints one error on line 2 + // and nothing about exports. test.each([ "export const b = 1;\nx y;", 'import { a } from "b";\nwidget W() {\n a();\n}', "export { nope };\nf() {}", - ])("a JavaScript module that doesn't parse gets the parser's error alone: %j", async code => { + ])("a JavaScript module that doesn't parse gets only the parser's error: %j", async code => { const { stdout, exitCode } = await lint({ ".oxlintrc.json": "{}", "a.js": code + "\n" }, ["-f", "unix"]); expect(stdout.split("\n").filter(line => line.startsWith("a.js:"))).toEqual([ expect.stringMatching(/^a\.js:2:/), @@ -2253,17 +2467,17 @@ describe.concurrent("bun lint", () => { expect(exitCode).toBe(1); }); - // Which names are declared twice is found in two ways. With no-unused-vars on, the variables of every file are there to be - // asked. Without it the parser looks out for a file that may have such a name. + // There are two ways to find names that are declared twice. With no-unused-vars on, every file's variables are + // already collected and can be looked up. Without it, the parser detects files that might have such a name. const waysToFindNames: [string, string][] = [ - ["no rule needs the variables", quiet], + ["no rule needs scope analysis", quiet], [ "no-unused-vars is on", JSON.stringify({ categories: { correctness: "off" }, rules: { "no-unused-vars": "warn" } }), ], ]; - describe.each(waysToFindNames)("a name that is declared twice, when %s", (_, config) => { + describe.each(waysToFindNames)("a name declared twice, when %s", (_, config) => { const declarations: Record = { var: "var a;", let: "let a;", @@ -2298,23 +2512,27 @@ describe.concurrent("bun lint", () => { impalias: "import a = b.c;", }; const redeclared = /^Identifier `a` has already been declared$/; - /** How many redeclarations are printed for each file. "-": something else is printed too. */ + /** + * Lints `files`. The returned function gives a file's number of redeclaration errors, or "-" if it has any + * other error. + */ const count = async (files: Record) => { const { raw } = await lint({ ".oxlintrc.json": config, ...files }, ["-f", "json"]); const errors = (JSON.parse(raw).diagnostics as OxlintDiagnostic[]).filter(it => it.severity === "error"); return (name: string) => { - const ofFile = errors.filter(it => it.filename === name); - return ofFile.every(it => redeclared.test(it.message)) ? String(ofFile.length) : "-"; + const fileErrors = errors.filter(it => it.filename === name); + return fileErrors.every(it => redeclared.test(it.message)) ? String(fileErrors.length) : "-"; }; }; - /** Where oxlint has another error, what is printed here is not compared. */ + /** Puts "-" in the cells where oxlint has a different error, so that they aren't compared. */ const like = (expected: string[], found: string[]) => found.map((line, i) => [...line].map((cell, j) => (expected[i][j] === "-" ? "-" : cell)).join("")); - // One table for each place and kind of file. A line is the first declaration, a column the second, both in the order of - // `names`. A cell is how many "Identifier `a` has already been declared" oxlint 1.87 prints, or "-" if it has another error. - test("by two declarations: every pair, in many places", async () => { - const places: Record = { + // One table per position and file extension. Rows are the first declaration and columns the second, both in the + // order of `names`. A cell is how many "Identifier `a` has already been declared" errors oxlint 1.87 prints, or + // "-" if it prints a different error. + test("every pair of declarations, in many scopes, is reported like oxlint", async () => { + const contexts: Record = { same: "1 2", block: "{ 1 2 }", nsbody: "namespace W { 1 2 }", @@ -2331,7 +2549,7 @@ describe.concurrent("bun lint", () => { modblock: "export {}; { 1 2 }", modouter: "export {}; { 1 } 2", }; - const tables: [extension: string, place: string, names: string, cells: string[]][] = [ + const tables: [extension: string, context: string, names: string, cells: string[]][] = [ [ "ts", "same", @@ -2566,29 +2784,30 @@ describe.concurrent("bun lint", () => { ], ]; const files: Record = {}; - const nameOf = (extension: string, place: string, first: string, second: string) => - `${place}-${first}-${second}.${extension}`; - for (const [extension, place, names] of tables) { + const nameOf = (extension: string, context: string, first: string, second: string) => + `${context}-${first}-${second}.${extension}`; + for (const [extension, context, names] of tables) { for (const first of names.split(" ")) { for (const second of names.split(" ")) { - files[nameOf(extension, place, first, second)] = - places[place].replace("1", () => declarations[first]).replace("2", () => declarations[second]) + "\n"; + files[nameOf(extension, context, first, second)] = + contexts[context].replace("1", () => declarations[first]).replace("2", () => declarations[second]) + + "\n"; } } } const counted = await count(files); - for (const [extension, place, names, cells] of tables) { + for (const [extension, context, names, cells] of tables) { const all = names.split(" "); const found = all.map(first => - all.map(second => counted(nameOf(extension, place, first, second))).join(""), + all.map(second => counted(nameOf(extension, context, first, second))).join(""), ); - expect([extension, place, ...like(cells, found)]).toEqual([extension, place, ...cells]); + expect([extension, context, ...like(cells, found)]).toEqual([extension, context, ...cells]); } }); - // A line is a place that has declared `a` already, a column the declaration that is put there. - test("by a declaration and a parameter, a catch parameter, the head of a loop, a type parameter", async () => { - const places: Record = { + // Rows are code that already declares `a`, and columns are the declaration inserted into it. + test("a declaration that collides with a parameter, catch parameter, loop variable or type parameter is reported like oxlint", async () => { + const contexts: Record = { param: "function w(a) { 2 }", paramblock: "function w(a) { { 2 } }", parampat: "function w({ a }) { 2 }", @@ -2617,7 +2836,7 @@ describe.concurrent("bun lint", () => { tparamcls: "class W { w() { 2 } }", pprop: "class W { constructor(public a: any) { 2 } }", }; - const tables: [extension: string, places: string, names: string, cells: string[]][] = [ + const tables: [extension: string, contexts: string, names: string, cells: string[]][] = [ [ "js", "param paramblock parampat paramdef rest arrowparam arrow1 methodparam ctorparam setter catch catchblock catchpat catchpatblock forlet forletbody forvar forafter fnexprname clsexprname modparam modcatch", @@ -2684,27 +2903,28 @@ describe.concurrent("bun lint", () => { ]; const files: Record = {}; for (const [extension, lines, names] of tables) { - for (const place of lines.split(" ")) { + for (const context of lines.split(" ")) { for (const name of names.split(" ")) { - files[`${place}-${name}.${extension}`] = places[place].replace("2", () => declarations[name]) + "\n"; + files[`${context}-${name}.${extension}`] = + contexts[context].replace("2", () => declarations[name]) + "\n"; } } } const counted = await count(files); for (const [extension, lines, names, cells] of tables) { - const found = lines.split(" ").map(place => + const found = lines.split(" ").map(context => names .split(" ") - .map(name => counted(`${place}-${name}.${extension}`)) + .map(name => counted(`${context}-${name}.${extension}`)) .join(""), ); expect([extension, ...like(cells, found)]).toEqual([extension, ...cells]); } }); - // Each row is what oxlint 1.87 prints: the name, then where it is declared first and where again. "" means that it lints - // the file. - test("has oxlint's labels", async () => { + // Each row is what oxlint 1.87 prints: the name, then the spans of the first declaration and of the + // redeclaration. "" means that it lints the file. + test("the error has oxlint's labels", async () => { const rows: ErrorRow[] = [ ["ts", "function f() { type T = 1; }", "T 11+1,23+1"], ["ts", "function f() { interface T {} }", "T 11+1,28+1"], @@ -3147,10 +3367,10 @@ describe.concurrent("bun lint", () => { } }); - // "twice": "Duplicated export 'a'". "defaults": TS(2528), "A module cannot have multiple default exports.". "undefined": - // "Export 'a' is not defined", with the name of its help, "Did you mean 'b'?", in parentheses. TypeScript files have none - // of the three. - test("and what a JavaScript module exports twice, or doesn't declare", async () => { + // "twice" is "Duplicated export 'a'". "defaults" is TS(2528), "A module cannot have multiple default exports.". + // "undefined" is "Export 'a' is not defined", followed in parentheses by the name from its help, "Did you mean + // 'b'?". TypeScript files get none of the three. + test("a JavaScript module's duplicate exports and undeclared exports are errors too", async () => { const rows: ErrorRow[] = [ ["js", "export const a = 1; export const a = 2;", "twice a 13+1,33+1"], ["ts", "export const a = 1; export const a = 2;", "declared a 13+1,33+1"], @@ -3342,8 +3562,8 @@ describe.concurrent("bun lint", () => { }); }); - // oxlint 1.87.0: "Identifier `a` has already been declared", at the first of the two. The parser, which has the names in - // hand, says that a file may have such a list: no other file is looked at. + // oxlint 1.87.0 prints "Identifier `a` has already been declared" at the first of the two. The parser sees the + // names anyway, so it flags the files that may have such a parameter list, and only those files are checked. test.each([ ["a.ts", "export class A {\n foo(a, a) {}\n}", "a.ts:2:7"], ["a.ts", "export {};\nfunction f(b, b) {}", "a.ts:2:12"], @@ -3355,18 +3575,21 @@ describe.concurrent("bun lint", () => { ["a.js", "class A { b = function (a, a) {} }", "a.js:1:25"], ["a.ts", "type A = (a: number, a: number) => void;", "a.ts:1:11"], ["a.ts", "declare function f(a: number, a: number): void;\nexport {};", "a.ts:1:20"], - ])("what OXC refuses is a parsing error: a name that two parameters bind: %s: %j", async (name, code, place) => { - const { stdout, exitCode } = await lint({ ".oxlintrc.json": quiet, [name]: code + "\n" }, ["-f", "unix"]); - expect(stdout).toContain(`${place}: Identifier`); - expect(exitCode).toBe(1); - }); + ])( + "code that OXC rejects is a parsing error: two parameters with the same name: %s: %j", + async (name, code, position) => { + const { stdout, exitCode } = await lint({ ".oxlintrc.json": quiet, [name]: code + "\n" }, ["-f", "unix"]); + expect(stdout).toContain(`${position}: Identifier`); + expect(exitCode).toBe(1); + }, + ); test.each([ - // Only declared. + // Ambient declarations. ["a.ts", "declare const a: string;"], ["a.d.ts", "export const a: string;"], ["a.ts", "declare function f(package: string): void;\nexport {};"], - // A file without `import` and `export` is a script, which is not strict. + // A file without `import` or `export` is a script, which isn't strict. ["a.ts", "type A = (...arguments: any[]) => void;"], ["a.ts", "let = 1;"], ["a.js", "function f() { await (1); }"], @@ -3375,20 +3598,20 @@ describe.concurrent("bun lint", () => { ["a.cjs", "(function (a, a) {});"], ["a.ts", "declare function f(a: number, a: number): void;"], ["a.ts", "function f(a: (a: number) => void, b = (a: number) => a) {}\nexport {};"], - // What acorn does not know, or typescript-estree throws. + // Syntax that acorn doesn't support, or that typescript-estree throws on. ["a.ts", "class A { accessor b = 1 }"], ["a.js", "class A { accessor b = 1 }"], ["a.js", "@d class A {}"], ["a.ts", "let a!: string;"], ["a.ts", "for (const a in b);"], ["a.js", "for (const a of b);"], - ])("what OXC takes is linted: %s: %j", async (name, code) => { + ])("code that OXC accepts is linted: %s: %j", async (name, code) => { const { stdout, exitCode } = await lint({ ".oxlintrc.json": quiet, [name]: code + "\n" }, ["-f", "unix"]); expect(stdout).not.toContain("[Error]"); expect(exitCode).toBe(0); }); - test("--fix makes one pass, and what is left is reported where it was", async () => { + test("--fix makes one pass, and reports the remaining problems at their positions before the fix", async () => { const result = await lint( { ".oxlintrc.json": JSON.stringify({ @@ -3424,7 +3647,7 @@ describe.concurrent("bun lint", () => { expect(result.exitCode).toBe(1); }); - test("--fix applies the fixes of a rule that is about several files", async () => { + test("--fix applies the fixes of a rule that looks at several files", async () => { const result = await lint( { ".oxlintrc.json": JSON.stringify({ @@ -3443,7 +3666,7 @@ describe.concurrent("bun lint", () => { }); test( - "--fix, --fix-suggestions, --fix-dangerously and --quiet change what oxlint's change", + "--fix, --fix-suggestions, --fix-dangerously and --quiet apply the same fixes as oxlint's flags", async () => { const files = { ".oxlintrc.json": JSON.stringify({ @@ -3480,8 +3703,24 @@ describe.concurrent("bun lint", () => { isDebug || isASAN ? 120_000 : 30_000, ); - // What oxlint 1.87 writes. - describe("a comment that disables nothing is removed from the scripts of a .vue file only, there by every flag", () => { + // oxlint 1.87 removes it with --fix, but then the function no longer yields to its caller. + test("only --fix-dangerously removes an await that unicorn/no-unnecessary-await reports", async () => { + const code = "async function worker() {\n await null;\n const retries = await 3;\n return retries;\n}\n"; + const files = { ".oxlintrc.json": "{}", "a.js": code }; + for (const flags of [["--fix"], ["--fix-suggestions"], ["--fix", "--fix-suggestions"]]) { + const result = await lint(files, [...flags, "a.js"], { reads: ["a.js"] }); + expect(result.files["a.js"]).toBe(code); + expect(result.stdout).toContain("no-unnecessary-await"); + } + const result = await lint(files, ["--fix-dangerously", "a.js"], { reads: ["a.js"] }); + expect(result.files["a.js"]).toBe( + "async function worker() {\n null;\n const retries = 3;\n return retries;\n}\n", + ); + expect(result.stdout).not.toContain("no-unnecessary-await"); + }); + + // This is what oxlint 1.87 writes. + describe("an unused disable comment is removed only from a .vue file's scripts, and there by every fix flag", () => { const rules = { "no-debugger": "error", "no-console": "error", "no-var": "error", "no-alert": "error" }; const options = { reportUnusedDisableDirectives: "error" }; const files = { @@ -3527,8 +3766,8 @@ describe.concurrent("bun lint", () => { }); }); - // What oxlint 1.87 writes, in whichever order the file has the rules. - test("of two fixes with the same range, that of the rule that oxlint has first", async () => { + // This is what oxlint 1.87 writes, whatever order the config lists the rules in. + test("of two fixes with the same range, --fix applies the one from the rule that oxlint runs first", async () => { const rules = { "unicorn/numeric-separators-style": "error", "unicorn/number-literal-case": "error" }; const oxlintrc = JSON.stringify({ plugins: ["unicorn"], categories: { correctness: "off" }, rules }); const files = { ".oxlintrc.json": oxlintrc, "a.js": "a = 0xabcdef12;\n" }; @@ -3537,8 +3776,9 @@ describe.concurrent("bun lint", () => { }); }); - // What oxlint 1.87 writes. The one rule replaces the declaration and prints it anew (`'a';`), the other the keyword. - test("of two fixes that start at the same place, the shorter one", async () => { + // This is what oxlint 1.87 writes. One rule replaces the whole declaration and reprints it (`'a';`). The other + // only replaces the keyword. + test("of two fixes that start at the same position, --fix applies the shorter one", async () => { const rules = { "import/consistent-type-specifier-style": "error", "typescript/no-import-type-side-effects": "error", @@ -3555,7 +3795,7 @@ describe.concurrent("bun lint", () => { }); // oxlint 1.87 with tsgolint 7.0 changes nothing. - test("rules that have suggestions for typescript-eslint and none for oxlint", async () => { + test("no fix flag applies a suggestion that typescript-eslint's rule has and oxlint's doesn't", async () => { const rules = { "typescript/strict-boolean-expressions": "error", "typescript/strict-void-return": "error" }; const text = "declare const a: string | null;\nif (a) {}\ndeclare function f(cb: () => void): void;\nf(async () => {});\nexport {};\n"; @@ -3571,8 +3811,8 @@ describe.concurrent("bun lint", () => { } }); - // What oxlint 1.87 writes. - test('a fix that is a dangerous one for oxlint: operator-assignment with "never"', async () => { + // This is what oxlint 1.87 writes. + test('only --fix-dangerously applies a fix that oxlint marks as dangerous: operator-assignment with "never"', async () => { const after = async (mode: string, ...flags: string[]) => { const rules = { "operator-assignment": ["error", mode] }; const oxlintrc = JSON.stringify({ plugins: [], categories: { correctness: "off" }, rules }); @@ -3597,7 +3837,7 @@ describe.concurrent("bun lint", () => { "src/b.ts": "export const b = 1;\n", }; - test("-f json is oxlint's: offsets and columns in bytes, plugin(rule)", async () => { + test("-f json prints oxlint's format: offsets and columns in bytes, rules as plugin(rule)", async () => { const { raw, exitCode } = await lint(files, ["-f", "json", "--threads", "2"]); const { start_time, ...report } = JSON.parse(raw); expect(report).toEqual({ @@ -3629,8 +3869,9 @@ describe.concurrent("bun lint", () => { expect(exitCode).toBe(1); }); - // What oxlint says besides a message is made when the message is shown with its code: its text is linted once more. - describe("the help of a problem that is shown", () => { + // The help that oxlint prints with a message is only computed when the message is printed with its code, by + // linting the file's text again. + describe("a problem's help", () => { const rules = { "no-underscore-dangle": "error", "no-var": "error" }; const help = "note: Remove the dangling '_' or add `_a` to the 'allow' configuration.\n"; const print = async (text: string, flags: string[], stdin?: string) => { @@ -3639,31 +3880,31 @@ describe.concurrent("bun lint", () => { }; const times = (raw: string) => raw.split(help).length - 1; - test("is there, however many problems there are", async () => { + test("is printed however many problems there are", async () => { const [few, many, all] = await Promise.all([ print("{ let _a; }\n".repeat(3), ["a.js"]), print("{ let _a; }\n".repeat(60), ["a.js"]), print("{ let _a; }\n".repeat(60), ["--all", "a.js"]), ]); expect([few, many, all].map(it => times(it.raw))).toEqual([3, 1, 60]); - // The one that stands for all is printed like the first of all. + // The one problem that's printed for the whole group looks like the first one with --all. const first = (raw: string) => raw.slice(0, raw.indexOf(help) + help.length); expect(first(many.raw)).toBe(first(all.raw)); }); - test("is about the text that the message is about, which --fix has changed since", async () => { + test("is computed from the text that was linted, even though --fix has changed the file since", async () => { const { raw, files } = await print("var _a;\n", ["--fix", "a.js"]); expect(files["a.js"]).toBe("let _a;\n"); expect(times(raw)).toBe(1); }); - test("is there for a text from standard input", async () => { + test("is printed for text from standard input", async () => { const { raw } = await print("", ["--stdin", "--stdin-filename", "b.js"], "let _a;\n"); expect(times(raw)).toBe(1); }); }); - test("unix, stylish, github and agent are oxlint's: the path from the working directory, columns in bytes, plugin(rule)", async () => { + test("unix, stylish, github and agent print oxlint's formats: paths relative to the working directory, columns in bytes, rules as plugin(rule)", async () => { const [json, unix, stylish, github, agent] = await Promise.all( ["json", "unix", "stylish", "github", "agent"].map(format => lint(files, ["-f", format, "--threads", "2"], { env: { NO_COLOR: "1" } }), @@ -3697,7 +3938,7 @@ describe.concurrent("bun lint", () => { ); }); - test("what has no place has its text and its severity", async () => { + test("a problem without a location is printed with its message and severity", async () => { const stale = { "oxlint-suppressions.json": JSON.stringify({ "a.js": { "no-debugger": { count: 2 } } }) }; const text = "There are suppressions that do not occur anymore."; const print = async (format: string) => (await lint({ ...files, ...stale }, ["--quiet", "-f", format])).raw; @@ -3706,14 +3947,14 @@ describe.concurrent("bun lint", () => { ``, ); expect(await print("junit")).toContain(`line 0, column 0, ${text}`); - // As oxlint 1.87: it is in a file without a name. + // Same as oxlint 1.87: the filename is empty. expect(await print("json")).toContain( `{"message": "${text}","severity": "error","help": "Run \`oxlint --prune-suppressions\` to remove unused suppressions.","filename": "","labels": []}`, ); }); - // As oxlint 1.87. For ESLint the mark is in no column. - test("what a rule says about the file is before a byte order mark, all else after it", async () => { + // Same as oxlint 1.87. ESLint doesn't count the mark as a column. + test("a report about the whole file is at offset 0, before a byte order mark, and every other report is after it", async () => { const project = { ".oxlintrc.json": rc({ plugins: ["unicorn", "import", "react"], @@ -3739,7 +3980,7 @@ describe.concurrent("bun lint", () => { }); }); - test("number_of_rules has what an override turns on, not what needs types, and is null with a nested configuration", async () => { + test("number_of_rules counts rules that an override turns on but not type-aware rules, and is null with a nested config", async () => { const count = async (more: Record, ...flags: string[]) => JSON.parse((await lint({ ...files, ...more }, ["-f", "json", ...flags])).raw).number_of_rules; const overrides = [ @@ -3755,7 +3996,7 @@ describe.concurrent("bun lint", () => { }).toEqual({ overrides: 4, typed: 1, nested: null, notNested: 2 }); }); - test("all that is said is on stdout", async () => { + test("prints everything to stdout and nothing to stderr", async () => { const warns = { ".oxlintrc.json": rc(), "a.js": "if (a == b) {}\n" }; const stale = { "oxlint-suppressions.json": JSON.stringify({ "a.js": { "no-debugger": { count: 2 } } }) }; const runs = { @@ -3767,7 +4008,7 @@ describe.concurrent("bun lint", () => { denied: lint(warns, ["--quiet", "--deny-warnings"]), none: lint(files, ["nothing.js"]), tolerated: lint(files, ["--no-error-on-unmatched-pattern", "nothing.js"]), - refused: lint({ ...files, ".oxlintrc.json": "{" }, []), + badConfig: lint({ ...files, ".oxlintrc.json": "{" }, []), unpruned: lint({ ...files, ...stale }, ["--quiet"]), unprunedForGitlab: lint({ ...files, ...stale }, ["--quiet", "-f", "gitlab"]), }; @@ -3783,12 +4024,13 @@ describe.concurrent("bun lint", () => { expect(results.denied.stdout).toBe("Linted 1 file"); expect(results.none.stdout).toBe("error: No files found to lint. Please check your paths and ignore patterns."); expect(results.tolerated.stdout).toBe("✓ No problems in 0 files"); - expect(results.refused.stdout).toStartWith("error: "); + expect(results.badConfig.stdout).toStartWith("error: "); expect(results.unpruned.stdout).toBe( "error: There are suppressions that do not occur anymore.\n\n" + "note: Run `oxlint --prune-suppressions` to remove unused suppressions.\n\nLinted 2 files", ); - // oxlint has neither the text nor the severity of what has no place. The fingerprint is Rust's `DefaultHasher` of all of it. + // oxlint prints neither the message nor the severity of a problem without a location. The fingerprint is Rust's + // `DefaultHasher` of the lines, the path, the message and the severity. expect(JSON.parse(results.unprunedForGitlab.raw)).toEqual([ { description: "There are suppressions that do not occur anymore.", @@ -3807,15 +4049,15 @@ describe.concurrent("bun lint", () => { denied: 1, none: 1, tolerated: 0, - refused: 1, + badConfig: 1, unpruned: 1, unprunedForGitlab: 1, }); }); - test("without --format: what tells oxlint that an agent runs it makes `agent` the format, before GITHUB_ACTIONS", async () => { + test("without --format, the variables that tell oxlint an agent is running it select the `agent` format, ahead of GITHUB_ACTIONS", async () => { const run = (env: Record) => lint(files, [], { env: { AGENT: undefined, ...env } }); - const [agent, named, both, off, github] = await Promise.all([ + const [agent, detected, both, off, github] = await Promise.all([ lint(files, ["-f", "agent"]), run({ AI_AGENT: "something" }), run({ CURSOR_AGENT: "0", GITHUB_ACTIONS: "true" }), @@ -3823,11 +4065,11 @@ describe.concurrent("bun lint", () => { lint(files, ["-f", "github"]), ]); const first = (it: { raw: string }) => it.raw.split("\n")[0]; - expect([named.raw, both.raw]).toEqual([agent.raw, agent.raw]); + expect([detected.raw, both.raw]).toEqual([agent.raw, agent.raw]); expect(first(off)).toBe(first(github)); }); - test("oxlint-suppressions.json has oxlint's names of the rules", async () => { + test("oxlint-suppressions.json uses oxlint's rule names", async () => { const project = { ".oxlintrc.json": JSON.stringify({ categories: { correctness: "off" }, @@ -3841,7 +4083,7 @@ describe.concurrent("bun lint", () => { }), "a.tsx": 'console.log(1 as any);\nnew require("x");\n;\n', }; - // What oxlint 1.87 writes with --suppress-all. + // This is what oxlint 1.87 writes with --suppress-all. const names = ["next/no-img-element", "no-console", "node/no-new-require", "typescript/no-explicit-any"]; const written = Object.fromEntries(names.map(name => [name, { count: 1 }])); const suppressed = await lint( @@ -3862,7 +4104,7 @@ describe.concurrent("bun lint", () => { expect(await Bun.file(join(String(dir), "oxlint-suppressions.json")).json()).toEqual({ "a.tsx": written }); }); - test("--silent and no file to lint: a format prints what oxlint's prints", async () => { + test("with --silent, or with no file to lint, each format prints what oxlint's prints", async () => { const formats = ["unix", "checkstyle", "junit", "gitlab", "sarif", "json"]; const [silent, none] = await Promise.all( [["--silent"], ["nothing.js"]].map(flags => @@ -3886,7 +4128,7 @@ describe.concurrent("bun lint", () => { ); }); - test("--rules -f json", async () => { + test("--rules -f json lists every rule once, with oxlint's fields", async () => { const { raw, exitCode } = await lint(files, ["--rules", "-f", "json"]); const rules = JSON.parse(raw); const find = (scope: string, value: string) => @@ -3901,17 +4143,18 @@ describe.concurrent("bun lint", () => { docs_url: "https://bun.com/docs/lint/rules/eslint/no-debugger", }); expect(find("typescript", "no-floating-promises").type_aware).toBe(true); - // Each once. A rule of the React Compiler is `react-hooks/purity` too, which has suggestions: oxlint's has none. + // Each rule is listed once. The React Compiler also has a `react-hooks/purity` rule, which has suggestions. + // oxlint's has none. expect(new Set(rules.map((it: any) => `${it.scope}/${it.value}`)).size).toBe(rules.length); expect(rules.filter((it: any) => it.value === "purity").map((it: any) => [it.scope, it.fix])).toEqual([ ["react", "none"], ]); - // The deprecated rules about layout are not built in. + // The deprecated formatting rules aren't built in. expect([find("eslint", "semi"), find("react", "jsx-space-before-closing")]).toEqual([undefined, undefined]); expect(exitCode).toBe(0); }); - test("checkstyle, junit, gitlab, sarif", async () => { + test("checkstyle, junit, gitlab and sarif print oxlint's formats", async () => { const [checkstyle, junit, gitlab, sarif] = await Promise.all( ["checkstyle", "junit", "gitlab", "sarif"].map(format => lint(files, ["-f", format, "a.js"])), ); @@ -3978,7 +4221,7 @@ describe.concurrent("bun lint", () => { ]); }); - test("an argument that matches nothing is no error, no file at all is, with 1", async () => { + test("an argument that matches nothing isn't an error, but finding no file at all exits with 1", async () => { const [some, none, tolerated] = await Promise.all([ lint(files, ["-f", "unix", "nothing.js", "src/b.ts"]), lint(files, ["nothing.js"]), @@ -3992,7 +4235,7 @@ describe.concurrent("bun lint", () => { expect(none.stdout).toContain("No files found to lint. Please check your paths and ignore patterns."); }); - test("options in the file: denyWarnings, maxWarnings", async () => { + test("the config's `options` can set denyWarnings and maxWarnings", async () => { const warns = { "a.js": "if (a == b) {}\n" }; const [plain, denied, limited] = await Promise.all([ lint({ ...warns, ".oxlintrc.json": rc() }, []), @@ -4006,7 +4249,7 @@ describe.concurrent("bun lint", () => { }); }); - test("a file that is named is left out if --ignore-path has it", async () => { + test("a file passed as an argument is skipped if the --ignore-path file lists it", async () => { const { stdout, exitCode } = await lint({ ...files, "my.ignore": "a.js\n" }, [ "-f", "unix", @@ -4019,7 +4262,7 @@ describe.concurrent("bun lint", () => { expect(exitCode).toBe(0); }); - test("-c: the patterns are from the directory of the file", async () => { + test("-c: the config's patterns are relative to the config file's directory", async () => { const { stdout } = await lint( { "configs/x.json": rc({ overrides: [{ files: ["src/*.js"], rules: { "no-debugger": "off" } }] }), @@ -4035,9 +4278,9 @@ describe.concurrent("bun lint", () => { `); }); - test("no-unused-private-class-members is about #names, not about `private`", async () => { + test("no-unused-private-class-members reports #names, not `private` members", async () => { const unused = " private a = 1;\n private b() {}\n constructor(private c: number) {}\n"; - const [named, byDefault] = await Promise.all([ + const [explicit, byDefault] = await Promise.all([ lint( { ".oxlintrc.json": rc({ rules: { "no-unused-private-class-members": "error" } }), @@ -4047,28 +4290,28 @@ describe.concurrent("bun lint", () => { ), lint({ ".oxlintrc.json": "{}", "a.ts": `export class A {\n${unused}}\n` }, ["-f", "unix"]), ]); - expect(named.stdout).toMatchInlineSnapshot(` + expect(explicit.stdout).toMatchInlineSnapshot(` "a.ts:5:3: 'd' is defined but never used. [Error/eslint(no-unused-private-class-members)] 1 problem" `); - expect(named.exitCode).toBe(1); + expect(explicit.exitCode).toBe(1); expect(byDefault.stdout).toBe(""); expect(byDefault.exitCode).toBe(0); }); - // What is expected in the next two tests is what oxlint 1.87.0 prints for the same files and arguments. - const places = (raw: string) => + // The next two tests expect what oxlint 1.87.0 prints for the same files and arguments. + const reportsIn = (raw: string) => JSON.parse(raw) .diagnostics.map((it: any) => `${it.filename}:${it.labels[0].span.line} ${it.code} ${it.severity}`) .sort(); const unused = { "a.ts": "const u = 1;\nexport {};\n" }; const any = { "a.ts": "export let a: any;\n" }; - test("all names of a rule are one rule, and what is said last about it counts", async () => { + test("all names of a rule are the same rule, and its last entry wins", async () => { const hooks = { "a.jsx": "function C(a) {\n if (a) useState();\n}\n" }; const spread = { "a.js": "x.reduce((acc, it) => [...acc, it], []);\n" }; - // The directory, what its .oxlintrc.json says, its files. + // The directory, its .oxlintrc.json, and its files. const rows: [string, object, Record][] = [ [ "off-then-typescript", @@ -4111,7 +4354,7 @@ describe.concurrent("bun lint", () => { any, ], ["bare-without-its-plugin", { plugins: ["react"], rules: { "no-explicit-any": "error" } }, any], - // `import/no-namespace`, and that plugin is not on. + // This means `import/no-namespace`, and that plugin isn't on. ["bare-of-the-first-plugin", { rules: { "no-namespace": "error" } }, { "a.ts": "namespace N {}\n" }], ["bare-hooks", { plugins: ["react"], rules: { "rules-of-hooks": "warn" } }, hooks], [ @@ -4134,7 +4377,7 @@ describe.concurrent("bun lint", () => { { plugins: ["import"], rules: { "no-cycle": "warn" } }, { "a.js": 'import "./b";\n', "b.js": 'import "./a";\n' }, ], - // oxlint has one in `eslint`, which needs no types, and one in `typescript`. + // oxlint has one rule in `eslint`, which doesn't need types, and another in `typescript`. [ "two-rules", { rules: { "require-await": "warn", "typescript/require-await": "off" } }, @@ -4147,7 +4390,7 @@ describe.concurrent("bun lint", () => { for (const [name, text] of Object.entries(texts)) files[`${directory}/${name}`] = text; } const { raw, exitCode } = await lint(files, ["-f", "json"]); - expect(places(raw)).toEqual([ + expect(reportsIn(raw)).toEqual([ "bare-cycle/a.js:1 import(no-cycle) warning", "bare-cycle/b.js:1 import(no-cycle) warning", "bare-hooks/a.jsx:2 react-hooks(rules-of-hooks) warning", @@ -4165,9 +4408,9 @@ describe.concurrent("bun lint", () => { expect(exitCode).toBe(1); }); - test("-A, -W and -D come after `rules`, a category too, and know a rule by the plugin that oxlint has it in", async () => { + test("-A, -W and -D override `rules`, by category too, and only match a rule under the plugin that oxlint has it in", async () => { const debug = { "a.js": "debugger;\n" }; - // The arguments, `rules`, the files, what is reported. + // The arguments, `rules`, the files, and the expected reports. const rows: [string[], object, Record, string[]][] = [ [["-D", "correctness"], { "no-debugger": "off" }, debug, ["a.js:1 eslint(no-debugger) error"]], [["-W", "correctness"], { "no-debugger": "error" }, debug, ["a.js:1 eslint(no-debugger) warning"]], @@ -4187,7 +4430,7 @@ describe.concurrent("bun lint", () => { ["a.ts:1 eslint(no-unused-vars) warning"], ], [["-A", "no-unused-vars"], { "typescript/no-unused-vars": "warn" }, unused, []], - // The options stay. + // The rule keeps its options. [ ["-D", "eslint/no-unused-vars"], { "typescript/no-unused-vars": ["warn", { varsIgnorePattern: "^u" }] }, @@ -4206,7 +4449,7 @@ describe.concurrent("bun lint", () => { lint({ ".oxlintrc.json": rc({ rules }), ...texts }, [...args, "-f", "json"]), ), ); - expect(results.map(it => places(it.raw))).toEqual(rows.map(it => it[3])); + expect(results.map(it => reportsIn(it.raw))).toEqual(rows.map(it => it[3])); expect(results.map(it => it.exitCode)).toEqual( rows.map(it => (it[3].some(it => it.endsWith("error")) ? 1 : 0)), ); @@ -4262,7 +4505,7 @@ describe.concurrent("bun lint", () => { eqeqeq, ], ], - // "smart" stays, so line 5 is still fine. + // The rule keeps "smart", so line 5 still isn't reported. [ ["-D", "pedantic"], [noVar, noDebugger, ...local, noAlert, noConsole, "a.js:6 eslint(eqeqeq) error"], @@ -4271,7 +4514,7 @@ describe.concurrent("bun lint", () => { ["-D", "eqeqeq"], [noVar, noDebugger, ...local, noAlert, noConsole, "a.js:6 eslint(eqeqeq) error"], ], - // -A forgets the rule, so "smart" is gone when -D or -W turns it on again. + // -A drops the rule with its options, so "smart" is gone when -D or -W turns it back on. [ ["-A", "eqeqeq", "-D", "eqeqeq"], [ @@ -4292,12 +4535,12 @@ describe.concurrent("bun lint", () => { [["-W", "local/own", "-D", "local/inherited"], unchanged], ]; const results = await Promise.all(rows.map(([args]) => lint(files, [...args, "-f", "json", "a.js"]))); - expect(results.map(it => places(it.raw))).toEqual(rows.map(it => it[1])); + expect(results.map(it => reportsIn(it.raw))).toEqual(rows.map(it => it[1])); expect(results.map(it => it.exitCode)).toEqual(rows.map(() => 1)); }); - // Recorded from oxlint 1.87.0 with tsgolint. typescript-eslint passes over `finally`, which waits for the Promise. - test("no-misused-promises reports an async function that is handed to finally()", async () => { + // Recorded from oxlint 1.87.0 with tsgolint. typescript-eslint skips `finally`, which waits for the Promise. + test("no-misused-promises reports an async function passed to finally()", async () => { const texts = { "tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), "a.ts": `declare const p: Promise; @@ -4317,22 +4560,22 @@ void p.finally(() => {}); rules: { "typescript/no-misused-promises": rule["no-misused-promises"] }, }; const flags = ["--type-aware", "--report-unused-disable-directives", "-f", "json", "a.ts"]; - const [forOxlint, alone] = await Promise.all([ + const [forOxlint, withBunfig] = await Promise.all([ lint({ ...texts, ".oxlintrc.json": JSON.stringify(oxlint) }, flags), lint({ ...texts, "bunfig.toml": `[lint.rules]\n"typescript/no-misused-promises" = "error"\n` }, flags), ]); - expect(places(forOxlint.raw)).toEqual([ + expect(reportsIn(forOxlint.raw)).toEqual([ "a.ts:3 typescript(no-misused-promises) error", "a.ts:4 typescript(no-misused-promises) error", ]); - const found = JSON.parse(alone.raw)[0].messages as { line: number; message: string }[]; + const found = JSON.parse(withBunfig.raw)[0].messages as { line: number; message: string }[]; expect(found.map(it => `${it.line} ${it.message}`)).toEqual([ "7 Unused oxlint-disable directive (no problems were reported from 'typescript/no-misused-promises').", ]); }); // Recorded from oxlint 1.87.0 with tsgolint. - test("no-misused-promises on what a function returns: a type in parentheses, and the type that a callback is given", async () => { + test("no-misused-promises matches tsgolint on returned functions: a return type in parentheses, and a callback's contextual return type", async () => { const texts = { "tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), "a.ts": `declare function f(): Promise; @@ -4346,7 +4589,7 @@ maybe(() => { return f; }); }; const oxlint = { categories: { correctness: "off" }, rules: { "typescript/no-misused-promises": "error" } }; const flags = ["--type-aware", "-f", "json", "a.ts"]; - const [forOxlint, alone] = await Promise.all([ + const [forOxlint, withBunfig] = await Promise.all([ lint({ ...texts, ".oxlintrc.json": JSON.stringify(oxlint) }, flags), lint({ ...texts, "bunfig.toml": `[lint.rules]\n"typescript/no-misused-promises" = "error"\n` }, flags), ]); @@ -4361,7 +4604,7 @@ maybe(() => { return f; }); [`6:19+1 ${value}`, `2:37+10 ${context}`, "6:19+1"], [`7:22+1 ${value}`, "7:22+1"], ]); - const lines = (JSON.parse(alone.raw)[0].messages as { line: number }[]).map(it => it.line); + const lines = (JSON.parse(withBunfig.raw)[0].messages as { line: number }[]).map(it => it.line); expect(lines).toEqual([4, 5, 6, 7]); }); @@ -4396,17 +4639,17 @@ maybe(() => { return f; }); lint({ ".oxlintrc.json": rc({ rules: {}, ...config }), ...texts }, ["--type-aware", "-f", "json", "a.ts"]), ), ); - expect(results.map(it => places(it.raw))).toEqual(rows.map(it => it[1])); + expect(results.map(it => reportsIn(it.raw))).toEqual(rows.map(it => it[1])); }); - describe("a rule with types and a rule without types that look for the same problem", () => { + describe("a type-aware rule and an untyped rule that look for the same problem", () => { const tsconfig = JSON.stringify({ compilerOptions: { strict: true, target: "esnext", lib: ["esnext", "dom"] }, }); const config = (rules: Record, more: object = {}) => rc({ plugins: ["unicorn", "typescript"], env: { browser: true }, rules, ...more }); const on = (rules: string[]) => config(Object.fromEntries(rules.map(it => [it, "error"]))); - /** Each row in a directory of its own. What is reported for each, in the order of the rows. */ + /** Lints each row in its own directory, and returns each row's reports, in row order. */ const lintRows = async (rows: [config: string, text: string][], args: string[]) => { const files: Record = { ".oxlintrc.json": rc({ rules: {} }) }; rows.forEach(([config, text], index) => { @@ -4414,12 +4657,12 @@ maybe(() => { return f; }); files[`${index}/tsconfig.json`] = tsconfig; files[`${index}/a.ts`] = text; }); - const all = places((await lint(files, ["-f", "json", ...args])).raw); + const all = reportsIn((await lint(files, ["-f", "json", ...args])).raw); return rows.map((_, index) => all.filter(it => it.startsWith(`${index}/`)).map(it => it.slice(`${index}/`.length)), ); }; - // The rule without types, the rule with types, and code with one thing to report per line. + // The untyped rule, the type-aware rule, and code with one problem per line. const pairs: [untyped: string, typed: string, lines: string[]][] = [ [ "require-await", @@ -4538,7 +4781,7 @@ maybe(() => { return f; }); "export const i = a.filter(Boolean).shift();", "export const [j] = a.filter(Boolean);", "export const k = x.filter(Boolean)[0];", - // Two calls that start at the same place. Only the first is for both rules. + // Two calls that start at the same position. Both rules report only the first. "export const l = aa.filter(Boolean)[0]", " .filter(Boolean).pop();", "export const m = a.find(Boolean);", @@ -4546,9 +4789,9 @@ maybe(() => { return f; }); ], ]; const text = (lines: string[]) => lines.join("\n") + "\n"; - const lineOf = (place: string) => place.slice(0, place.indexOf(" ")); + const lineOf = (report: string) => report.slice(0, report.indexOf(" ")); - test("with both on, what either reports alone is reported once", async () => { + test("with both on, a problem that either rule finds is reported once", async () => { const rowsOf = (rules: (pair: (typeof pairs)[number]) => string[]) => pairs.map((pair): [string, string] => [on(rules(pair)), text(pair[2])]); const [untyped, typed, both] = await Promise.all([ @@ -4569,7 +4812,8 @@ maybe(() => { return f; }); const withTypes = new Set(typed[index].map(lineOf)); const rest = untyped[index].filter(it => !withTypes.has(lineOf(it))); expect([name, both[index]]).toEqual([name, [...typed[index], ...rest].sort()]); - // There is code that both report, and all but one pair has code that only the rule without types reports. + // Every pair has code that both rules report, and all but one pair has code that only the untyped rule + // reports. const hasBoth = untyped[index].length > rest.length; const hasRest = rest.length > 0 || name === "prefer-destructuring"; expect([name, hasBoth, hasRest]).toEqual([name, true, true]); @@ -4651,15 +4895,17 @@ maybe(() => { return f; }); const throw_ = ["no-throw-literal", "typescript/only-throw-error"]; const f = "export async function f() {\n return 1;\n}\n"; - test("without types for the file, the rule without types reports", async () => { + test("without types for the file, the untyped rule reports", async () => { const rows = pairs .slice(0, 4) .map(([untyped, typed, lines]): [string, string] => [on([untyped, typed]), text(lines)]); - const alone = pairs.slice(0, 4).map(([untyped, , lines]): [string, string] => [on([untyped]), text(lines)]); - expect(await lintRows(rows, [])).toEqual(await lintRows(alone, [])); + const untypedOnly = pairs + .slice(0, 4) + .map(([untyped, , lines]): [string, string] => [on([untyped]), text(lines)]); + expect(await lintRows(rows, [])).toEqual(await lintRows(untypedOnly, [])); }); - test("where the rule without types is the more severe, both report", async () => { + test("both report if the untyped rule has the higher severity", async () => { const starts = (untyped: string, typed: string) => config({ "unicorn/prefer-string-starts-ends-with": untyped, @@ -4691,18 +4937,19 @@ maybe(() => { return f; }); `); }); - test("comments that disable work as they do for two reports", async () => { + test("disable comments work as if both rules had reported", async () => { const find = ["unicorn/prefer-array-find", "typescript/prefer-find"]; const first = "declare const a: string[];\n"; const rows: [string, string][] = [ - // A name means the rule whatever plugin it is written with. + // A name matches the rule whichever plugin prefix it's written with. [on(await_), `// oxlint-disable-next-line require-await\n${f}`], [on(await_), `// oxlint-disable-next-line typescript/require-await\n${f}`], [on(await_), `// oxlint-disable-next-line require-await, typescript/require-await\n${f}`], // Nothing to disable. [on(await_), "// oxlint-disable-next-line require-await\nexport function f() {\n return 1;\n}\n"], [on(throw_), "// oxlint-disable-next-line\nexport const a = 1;\n"], - // The two have different names. A comment for one leaves the report of the other, and is in use. + // The two rules have different names. A comment for one doesn't hide the other's report, and isn't reported + // as unused. [on(throw_), '// oxlint-disable-next-line no-throw-literal\nthrow "a";\n'], [on(throw_), '// oxlint-disable-next-line typescript/only-throw-error\nthrow "a";\n'], [on(throw_), '// oxlint-disable-next-line no-throw-literal, typescript/only-throw-error\nthrow "a";\n'], @@ -4715,7 +4962,7 @@ maybe(() => { return f; }); on(find), `${first}// oxlint-disable-next-line unicorn/prefer-array-find\nexport const b = a.filter(Boolean)[0];\n`, ], - // The two report on different lines. + // The two rules report on different lines. [ on(await_), "export const g = async (\n a: number,\n // oxlint-disable-next-line require-await\n) => a;\n", @@ -4754,7 +5001,7 @@ maybe(() => { return f; }); `); }); - test("a file that is linted again for a rule about several files", async () => { + test("a problem is still reported once in a file that's linted again for a rule that looks at several files", async () => { const files = { ".oxlintrc.json": config( { "no-throw-literal": "error", "typescript/only-throw-error": "error", "import/named": "error" }, @@ -4765,7 +5012,7 @@ maybe(() => { return f; }); "b.ts": 'export const b = 1;\nthrow "b";\n', }; const { raw } = await lint(files, ["-f", "json", "--type-aware", "--report-unused-disable-directives"]); - expect(places(raw)).toMatchInlineSnapshot(` + expect(reportsIn(raw)).toMatchInlineSnapshot(` [ "a.ts:3 typescript(only-throw-error) error", "b.ts:2 typescript(only-throw-error) error", @@ -4773,14 +5020,14 @@ maybe(() => { return f; }); `); }); - test("what a hidden report would change is changed", async () => { + test("a hidden report's fix or suggestion is still applied", async () => { const includes = ["unicorn/prefer-includes", "typescript/prefer-includes"]; const destructuring = ["prefer-destructuring", "typescript/prefer-destructuring"]; const rows: [rules: string[], flag: string, code: string][] = [ [throw_, "--fix-suggestions", 'throw "a";\n'], [includes, "--fix-suggestions", 'declare const a: string[];\nexport const b = a.indexOf("b") !== -1;\n'], [destructuring, "--fix", 'declare const o: { a: number };\nexport const a = o["a"];\n'], - // The comment is for the report that has the suggestion. + // The comment disables the report that has the suggestion. [throw_, "--fix-suggestions", '// oxlint-disable-next-line no-throw-literal\nthrow "a";\n'], ]; const fixed = await Promise.all( @@ -4814,14 +5061,14 @@ maybe(() => { return f; }); `); }); - test("a report that a file of suppressions hides hides no other", async () => { + test("a report hidden by a suppressions file doesn't hide the other rule's report", async () => { const project = { ".oxlintrc.json": on(throw_), "tsconfig.json": tsconfig, "a.ts": 'throw "a";\n' }; const suppress = (rule: string) => lint(project, ["--type-aware", "-f", "json", "--suppress-rule", rule]); const [typed, untyped] = await Promise.all([ suppress("typescript/only-throw-error"), suppress("no-throw-literal"), ]); - expect([places(typed.raw), places(untyped.raw)]).toMatchInlineSnapshot(` + expect([reportsIn(typed.raw), reportsIn(untyped.raw)]).toMatchInlineSnapshot(` [ [ "a.ts:1 eslint(no-throw-literal) error", @@ -4833,13 +5080,14 @@ maybe(() => { return f; }); `); }); - // Without a configuration in the working directory the formats are ESLint's, whose JSON has the suggestions. - test("the configuration of the file counts, not that of the working directory", async () => { + // Without a config in the working directory the formats are ESLint's, and ESLint's JSON includes the + // suggestions. + test("the file's config applies, not the working directory's", async () => { const project = { "throw/.oxlintrc.json": on(throw_), "throw/tsconfig.json": tsconfig, "throw/a.ts": 'throw "a";\n', - // Both rules suggest the same. + // Both rules make the same suggestion. "await/.oxlintrc.json": on(await_), "await/tsconfig.json": tsconfig, "await/a.ts": f, @@ -4868,7 +5116,7 @@ maybe(() => { return f; }); `); }); - test("dot-notation and consistent-return have no version without types", async () => { + test("dot-notation and consistent-return have no untyped version", async () => { const code = 'declare const o: { a: number };\nexport const a = o["a"];\nexport function f(x: boolean) {\n if (x) return 1;\n return;\n}\n'; const names = ["dot-notation", "consistent-return"]; @@ -4899,7 +5147,7 @@ maybe(() => { return f; }); }); // Recorded from oxlint 1.87.0. - test("--fix-suggestions alone applies the fixes of JS plugins, but not those of built-in rules", async () => { + test("--fix-suggestions without --fix applies JS plugin fixes but not built-in rule fixes", async () => { const report = (more: string) => `node => context.report({ node, message: "no", ${more} })`; const project = { ".oxlintrc.json": rc({ @@ -4950,10 +5198,10 @@ maybe(() => { return f; }); const results = await Promise.all( rows.map(([config]) => lint({ ".oxlintrc.json": rc({ rules, ...config }), ...text }, ["-f", "json", "a.js"])), ); - expect(results.map(it => places(it.raw))).toEqual(rows.map(it => it[1])); + expect(results.map(it => reportsIn(it.raw))).toEqual(rows.map(it => it[1])); }); - // Recorded from oxlint 1.87.0. The two fixes overlap, so --fix leaves the second report. + // Recorded from oxlint 1.87.0. The two fixes overlap, so the second report remains after --fix. test("use-isnan reports both sides of NaN == NaN", async () => { const files = { ".oxlintrc.json": rc({ rules: { "use-isnan": "error" } }), @@ -4969,7 +5217,7 @@ maybe(() => { return f; }); expect(exitCode).toBe(1); }); - test("the rules that ESLint has given up and oxlint has in `node` run if that plugin is on", async () => { + test("rules that ESLint deprecated and oxlint has in `node` run only if that plugin is on", async () => { const texts: Record = { "callback-return": "function f(err, callback) {\n if (err) {\n callback(err);\n }\n callback();\n}\n", "global-require": 'function f() {\n require("a");\n}\n', @@ -4993,7 +5241,7 @@ maybe(() => { return f; }); } const { raw, exitCode } = await lint(files, ["-f", "json"]); // oxlint 1.87.0 calls them node(no-sync) and so on. - const found = places(raw).map((it: string) => it.replace(/ \w+\((.*)\) /, " $1 ")); + const found = reportsIn(raw).map((it: string) => it.replace(/ \w+\((.*)\) /, " $1 ")); const lines = { "callback-return": 3, "global-require": 2 }; expect(found).toEqual( ["bare-on", "node-on"].flatMap(directory => @@ -5003,11 +5251,12 @@ maybe(() => { return f; }); expect(exitCode).toBe(0); }); - // The projects of oracle/plugins/oxlint. expected.json is what oxlint 1.87.0 with tsgolint 7.0.2003 reports for them. + // The next tests lint the projects in oracle/plugins/oxlint. expected.json is what oxlint 1.87.0 with tsgolint + // 7.0.2003 reports for them. const found = (raw: string, names: string[]) => { const byProject = Object.fromEntries(names.map((it): [string, Set] => [it, new Set()])); for (const it of JSON.parse(raw).diagnostics) { - // A syntax error. + // A syntax error has no code. if (!it.code) continue; const name = names.find(name => it.filename.startsWith(name + "/"))!; const { line, column } = it.labels[0].span; @@ -5015,11 +5264,12 @@ maybe(() => { return f; }); } return Object.fromEntries(names.map(it => [it, [...byProject[it]].sort()])); }; - // With the length of what is pointed at, and each report as often as it is made: two can begin at one place. + // Like `found`, but with the length of each span, and with duplicates, because two reports can start at the same + // position. const foundExactly = (raw: string, names: string[]) => { const byProject = Object.fromEntries(names.map((it): [string, string[]] => [it, []])); for (const it of JSON.parse(raw).diagnostics) { - // A syntax error. + // A syntax error has no code. if (!it.code) continue; const name = names.find(name => it.filename.startsWith(name + "/"))!; const { line, column, length } = it.labels[0].span; @@ -5029,8 +5279,8 @@ maybe(() => { return f; }); }; const expected = (names: string[]) => Object.fromEntries(names.map(it => [it, whatOxlintReports[it as keyof typeof whatOxlintReports]])); - // All that is marked for a report, and what is said there, where that is more than one place without a text. labels.json has - // only the projects in which there is such a report. + // Returns all the labels of each report, with their text, unless the report only has one label without text. + // labels.json has only the projects with such a report. const marked = (raw: string, names: string[]) => { const byProject = Object.fromEntries(names.map((it): [string, string[]] => [it, []])); for (const it of JSON.parse(raw).diagnostics) { @@ -5043,10 +5293,11 @@ maybe(() => { return f; }); const expectedMarks = (names: string[]) => Object.fromEntries(names.map(it => [it, (whatOxlintMarks as Record)[it] ?? []])); - // The tests that lint hundreds of directories are serial: beside them the others do not get the processor in time. + // The tests that lint hundreds of directories are serial. If they ran concurrently, the other tests wouldn't get + // enough CPU time and would time out. test.serial( - "the rules report what oxlint's report, where they report it", + "the rules report the same problems as oxlint's, at the same positions", async () => { const some = projects.filter(it => !it.typed && it.name !== "no-cycle/many-files"); const files: Record = { ".oxlintrc.json": rc({ rules: {} }) }; @@ -5070,9 +5321,10 @@ maybe(() => { return f; }); isDebug || isASAN ? 120_000 : 30_000, ); - // Each project is a program of its own. In twelve runs: one takes seconds in a debug build. + // Each project is its own program. They're split into twelve runs because one program takes seconds in a debug + // build. test.serial.each([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])( - "the rules that need types report what tsgolint's report: part %d", + "type-aware rules report the same problems as tsgolint's: part %d", async part => { const some = projects.filter(it => it.typed).filter((_, index) => index % 12 === part); const compilerOptions = { strict: true, target: "esnext", module: "esnext", lib: ["esnext", "dom"] }; @@ -5104,22 +5356,24 @@ maybe(() => { return f; }); expect(foundExactly(raw, Object.keys(parenthesesExpected))).toEqual(parenthesesExpected); }); - // messages.json has what oxlint 1.87.0 with tsgolint 7.0.2003 says. - test("the rules that oxlint shares with ESLint and typescript-eslint say what oxlint's say", async () => { + // messages.json has the messages of oxlint 1.87.0 with tsgolint 7.0.2003. + test("rules that oxlint shares with ESLint and typescript-eslint print oxlint's messages", async () => { const { raw } = await lint(filesOfMessages(messages), ["-f", "json", "--type-aware"]); - const said = messagesOf(raw, messages).map((it, index) => `${messages[index].rule} ${it.join(" | ")}`); - // Of several the last is the one that is asked about. + const printed = messagesOf(raw, messages).map((it, index) => `${messages[index].rule} ${it.join(" | ")}`); + // If the code gets several reports, the entry is about the last one. const before = (index: number) => messagesOf(raw, messages)[index].slice(0, messages[index].index ?? 0); - expect(said).toEqual(messages.map((it, index) => `${it.rule} ${[...before(index), it.message].join(" | ")}`)); - // A help that is printed is oxlint's, and none is lacking. - const helps = helpsOf(raw, messages).map((it, index) => ({ ...messages[index], said: it })); - const wrong = helps.filter(it => it.said !== undefined && it.said !== it.help); + expect(printed).toEqual( + messages.map((it, index) => `${it.rule} ${[...before(index), it.message].join(" | ")}`), + ); + // Every help that's printed is oxlint's, and none is missing. + const helps = helpsOf(raw, messages).map((it, index) => ({ ...messages[index], printed: it })); + const wrong = helps.filter(it => it.printed !== undefined && it.printed !== it.help); expect(wrong.map(it => [it.rule, it.id])).toEqual([]); - expect(helps.filter(it => it.said === undefined && it.help !== undefined).length).toBeLessThanOrEqual(0); + expect(helps.filter(it => it.printed === undefined && it.help !== undefined).length).toBeLessThanOrEqual(0); }); - // The table has no texts of messages, only numbers that are made of them: a message that is reworded would lose its help. - test("every help of oxlint belongs to a message that a rule has", () => { + // The table has hashes of the messages, not their text, so a reworded message would lose its help. + test("every entry of oxlint's help table belongs to a message that a rule has", () => { const root = join(import.meta.dir, "../../../src/lint"); const unescaped = (text: string) => text.replace(/\\\n\s*/g, "").replace(/\\(.)/g, (_, it) => ({ n: "\n", t: "\t" })[it as "n"] ?? it); @@ -5152,14 +5406,16 @@ maybe(() => { return f; }); const lines = readFileSync(join(root, "oxlint_help.txt"), "utf8").split("\n"); const table = readFileSync(join(root, "oxlint_help.rs"), "utf8"); const entries = [ - ...table.matchAll(/^ {4}\(0x[0-9A-F]{8}, (One|Three|of_the_fix)\((?:\w+, \w+, )?(\d+)\), (\d)\), \/\//gm), + ...table.matchAll( + /^ {4}\(0x[0-9A-F]{8}, (One|Three|fix_description)\((?:\w+, \w+, )?(\d+)\), (\d)\), \/\//gm, + ), ]; expect(entries.length).toBe(table.match(/^ {4}\(0x/gm)!.length); const wrong = entries.filter(([, kind, line, withValues]) => { - // Lines count from 1. A fix's note is optional, and 0 stands for none. + // Line numbers start at 1. A fix's note is optional, and 0 means there's none. const at = Number(line) - 1; - if (kind === "of_the_fix" && at < 0) return withValues !== "0"; - // By part: the help, the label, the note. + if (kind === "fix_description" && at < 0) return withValues !== "0"; + // The parts are the help, the label and the note. const texts = kind === "Three" ? lines.slice(at, at + 3) : kind === "One" ? [lines[at]] : ["", "", lines[at]]; const bits = texts.reduce((bits, text, part) => bits | (Number(text?.includes("{{")) << part), 0); return !texts.some(Boolean) || bits !== Number(withValues); @@ -5167,8 +5423,8 @@ maybe(() => { return f; }); expect(wrong.map(it => it[0])).toEqual([]); }); - // What oxlint 1.87.0 with tsgolint 7.0.2003 reports. - test("JavaScript is linted with types without allowJs, and is `any` to the TypeScript that imports it", async () => { + // This is what oxlint 1.87.0 with tsgolint 7.0.2003 reports. + test("JavaScript is linted with types even without allowJs, and is `any` to TypeScript that imports it", async () => { const { raw } = await lint( { ".oxlintrc.json": rc({ @@ -5195,9 +5451,10 @@ maybe(() => { return f; }); }); }); - // What oxlint 1.87.0 with tsgolint 7.0.2003 does: there is no program for such a tsconfig.json, so no rule that needs types - // runs on its files, and nothing is fixed on types that do not resolve. Each error of TypeScript is one of oxlint. - test("a tsconfig.json that TypeScript refuses is an error, and its files are linted without types", async () => { + // This is what oxlint 1.87.0 with tsgolint 7.0.2003 does. There's no program for such a tsconfig.json, so no + // type-aware rule runs on its files, and nothing is fixed based on types that don't resolve. Each TypeScript + // error becomes one oxlint error. + test("a tsconfig.json that TypeScript rejects is an error, and its files are linted without types", async () => { const options = `"strict":true,"lib":["esnext"]`; const code = "declare const s: string;\nexport const g = s as string;\ndebugger;\n"; const { raw, exitCode, files } = await lint( @@ -5237,16 +5494,16 @@ maybe(() => { return f; }); `unfinished/tsconfig.json 1 52 0 ${invalid} '}' expected.`, `unknown/tsconfig.json 1 52 6 ${invalid} Unknown compiler option 'nope'.`, ]); - // The rules that need no types run everywhere. + // Rules that don't need types run everywhere. expect(found.filter((it: string) => it.includes("no-debugger")).length).toBe(5); const fixed = code.replace(" as string", ""); expect(files).toEqual({ "good/a.ts": fixed, "removed/a.ts": code, "in-no-project.ts": fixed }); expect(exitCode).toBe(1); }); - // The order is oxlint 1.87.0's, with --fix and without types. + // This is oxlint 1.87.0's order with --fix and without types. test.each([[["--fix"]], [["--fix", "--type-aware"]]])( - "what %j leaves is printed in the order in which the rules ran", + "the problems that remain after %j are printed in the order the rules ran", async flags => { const names = ["eqeqeq", "no-empty", "no-unused-vars", "no-var", "no-debugger", "prefer-const"]; const { stdout, exitCode, files } = await lint( @@ -5274,9 +5531,9 @@ maybe(() => { return f; }); }, ); - // What oxlint 1.87.0 with tsgolint 7.0.2003 does. Added to the project as root files, the two .mjs would be errors of the - // program (6504), and the tsconfig.json would be refused for them. - test("--tsconfig adds no file to a project: one that no project includes is in none", async () => { + // This is what oxlint 1.87.0 with tsgolint 7.0.2003 does. If the two .mjs files were added to the project as root + // files, each would be an error in the program (6504), and the tsconfig.json would be rejected because of them. + test("--tsconfig doesn't add files to a project: a file that no project includes stays outside every project", async () => { const code = "async function f() { return 1; }\nf();\n"; const { stdout, exitCode } = await lint( { @@ -5292,8 +5549,8 @@ maybe(() => { return f; }); }, ["-f", "unix", "--type-aware", "--tsconfig", "./tsconfig.json", "src", "other"], ); - const places = stdout.split("\n").filter(it => it.includes("[Error/")); - expect(places.map(it => it.replace(/: .* \[/, " [")).sort()).toEqual( + const errorLines = stdout.split("\n").filter(it => it.includes("[Error/")); + expect(errorLines.map(it => it.replace(/: .* \[/, " [")).sort()).toEqual( ["other/c.ts", "other/d.mjs", "src/a.ts", "src/b.mjs"].map( it => `${it}:2:1 [Error/typescript(no-floating-promises)]`, ), @@ -5301,8 +5558,9 @@ maybe(() => { return f; }); expect(exitCode).toBe(1); }); - // What oxlint 1.87.0 with tsgolint 7.0.2003 does: tsgolint finds the project of each file itself, and is not told the flag. - describe("--tsconfig does not choose the project that a file is checked in", () => { + // This is what oxlint 1.87.0 with tsgolint 7.0.2003 does. tsgolint finds each file's project itself, and never + // sees the flag. + describe("--tsconfig doesn't choose the project that a file is checked in", () => { const compilerOptions = { strict: true, target: "es2023", @@ -5318,10 +5576,11 @@ maybe(() => { return f; }); const nearer = (compilerOptions: object, include: string[]) => JSON.stringify({ extends: "../tsconfig.json", compilerOptions, include }); - // With each: what is reported if the file is checked with `tsconfig.json`. With `src/tsconfig.json` it is nothing. + // Each row ends with what's reported if the file is checked with `tsconfig.json`. With `src/tsconfig.json` + // nothing is reported. test.each<[string, Record, string[]]>([ [ - "jsx, for a type that is imported from a .tsx", + "jsx, for a type imported from a .tsx file", { ".oxlintrc.json": on("no-redundant-type-constituents"), "package.json": `{"type":"module"}`, @@ -5345,7 +5604,7 @@ maybe(() => { return f; }); ], ], [ - "allowJs, for what is imported from a .mjs", + "allowJs, for a function imported from a .mjs file", { ".oxlintrc.json": on("no-unsafe-call", "no-unsafe-assignment"), "tsconfig.json": above(), @@ -5356,7 +5615,7 @@ maybe(() => { return f; }); ["use.ts:2:22 typescript(no-unsafe-assignment)", "use.ts:2:22 typescript(no-unsafe-call)"], ], [ - "jsx and jsxImportSource, for a type that is inferred from the children of an element", + "jsx and jsxImportSource, for a type inferred from an element's children", { ".oxlintrc.json": on("restrict-template-expressions"), "tsconfig.json": above(), @@ -5372,7 +5631,7 @@ maybe(() => { return f; }); ["view.tsx:2:45 typescript(restrict-template-expressions)"], ], [ - "paths, to a declaration file in place of its source", + "paths, to a declaration file instead of its source", { ".oxlintrc.json": on("unbound-method"), "tsconfig.json": above({ paths: { lib: ["./lib/source.ts"] } }), @@ -5383,7 +5642,7 @@ maybe(() => { return f; }); }, ["use.ts:2:31 typescript(unbound-method)"], ], - ])("a nearer tsconfig.json has %s", async (_, files, withTheOneAbove) => { + ])("the nearest tsconfig.json is used when it sets %s", async (_, files, withParentTsconfig) => { const { "src/tsconfig.json": _nearer, ...withoutTheNearer } = files; const run = async (files: Record, ...flags: string[]) => found((await lint(files, ["-f", "json", "--type-aware", ...flags, "src"])).raw, ["src"]).src; @@ -5394,10 +5653,11 @@ maybe(() => { return f; }); run(files, "--tsconfig=src/tsconfig.json"), run(withoutTheNearer), ]), - ).toEqual([[], [], [], withTheOneAbove]); + ).toEqual([[], [], [], withParentTsconfig]); }); - // `which` is declared in a file that only one project has, so its type says which project it was. + // Each project includes its own declaration of `which`, so the type of `which` shows which project a file was + // checked in. const project = (marker: string, include: string[], more: object = {}) => JSON.stringify({ compilerOptions: { strict: true, types: [], ...more }, include: [marker, ...include] }); const solution = (path: string) => JSON.stringify({ files: [], references: [{ path }] }); @@ -5420,7 +5680,7 @@ maybe(() => { return f; }); "src/none/lib.json": project("../../markers/ofFlag.d.ts", ["*.ts"], { composite: true, outDir: "out" }), }; - test("it is the nearest tsconfig.json that includes the file, or one that it references, whatever the flag names", async () => { + test("the project is the nearest tsconfig.json that includes the file, or one that it references, whatever --tsconfig points to", async () => { const files = { ".oxlintrc.json": on("restrict-template-expressions"), ...marked }; const flags = [ [], @@ -5441,7 +5701,7 @@ maybe(() => { return f; }); .map((it): [string, string] => [it.filename, it.labels[0].label]) .sort(), ); - // outside/a.ts is in no project, where `which` is not declared. + // outside/a.ts isn't in any project, so `which` isn't declared there. const expected = { "src/included/a.ts": "Type: { nearer: 1; }", "src/left-out/a.ts": "Type: { top: 1; }", @@ -5451,7 +5711,7 @@ maybe(() => { return f; }); expect(runs.map(it => types(it.raw))).toEqual(flags.map(() => expected)); }); - test("without an oxlint config it is the project of every file, also of one that it does not include", async () => { + test("without an oxlint config, every file is checked in the --tsconfig project, even a file that it doesn't include", async () => { const types = async (...flags: string[]) => { const rule = ["--rule", "@typescript-eslint/restrict-template-expressions: error"]; const { stdout } = await lint(marked, ["-f", "unix", ...rule, ...flags, ...directories]); @@ -5479,8 +5739,8 @@ maybe(() => { return f; }); ]); }); - // What oxlint 1.87.0 does with it instead. - test("it is what the imports of every file are resolved with: the first that it references and that includes the file, or else itself", async () => { + // This is what oxlint 1.87.0 uses the flag for instead. + test("every file's imports are resolved with the --tsconfig file, or with the first project it references that includes the file", async () => { const aliases = (to: string, more: object) => JSON.stringify({ compilerOptions: { paths: { "@lib/*": [`${to}/*`] } }, ...more }); const code = `import * as lib from "@lib/x";\nexport const all = [lib.one, lib.two, lib.three];\n`; @@ -5501,7 +5761,7 @@ maybe(() => { return f; }); "src/sub/c.ts": code, "src/sub/deep/d.ts": code, "outside/e.ts": code, - // Not what a package imports. + // A package's own imports aren't resolved with it. "node_modules/dep/package.json": `{"name":"dep","version":"1.0.0","main":"index.js","type":"module"}`, "node_modules/dep/index.js": `export * from "@lib/x";\nexport const own = 1;\n`, "src/f.js": `import * as dep from "dep";\nexport const all = [dep.own, dep.one];\n`, @@ -5543,10 +5803,10 @@ maybe(() => { return f; }); }); }); - describe("a file that the nearest tsconfig.json does not include", () => { + describe("a file that the nearest tsconfig.json doesn't include", () => { const compilerOptions = { strict: true, lib: ["es2022"], types: [] }; - // A promise that is declared in a project is only one in the program of that project, so what is reported in - // `config.ts` says which program it was. `src/b.ts` is reported in any case. + // A promise declared in a project is only a promise in that project's program, so the lines reported in + // `config.ts` show which program it was checked in. `src/b.ts` is always reported. const files = { ".oxlintrc.json": rc({ rules: { "typescript/no-floating-promises": "error" } }), // Without `include` it includes everything. @@ -5563,18 +5823,28 @@ maybe(() => { return f; }); }; const between = JSON.stringify({ compilerOptions, include: ["between", "a/config.ts"] }); - // What oxlint 1.87.0 with tsgolint 7.0.2003 does. + // This is what oxlint 1.87.0 with tsgolint 7.0.2003 does. test.each([ - ["is in the first project upwards that includes it", {}, [], [1, 2, 3]], - ["is not in one further up than that", { "packages/tsconfig.json": between }, [], [2]], - ["is not in the project of --tsconfig, which includes it", {}, ["--tsconfig", "all.json"], [1, 2, 3]], - ["is in a project if that of --tsconfig does not include it", {}, ["--tsconfig", "src.json"], [1, 2, 3]], + ["is checked in the nearest parent project that includes it", {}, [], [1, 2, 3]], + ["isn't checked in a project above that one", { "packages/tsconfig.json": between }, [], [2]], + [ + "isn't checked in the --tsconfig project, even though it includes the file", + {}, + ["--tsconfig", "all.json"], + [1, 2, 3], + ], + [ + "is still checked in a project if the --tsconfig project doesn't include it", + {}, + ["--tsconfig", "src.json"], + [1, 2, 3], + ], ])("%s", async (_, others, flags, lines) => { const args = ["-f", "unix", "--type-aware", ...flags, "."]; const { stdout, stderr, exitCode } = await lint({ ...files, ...others }, args, { cwd: "packages/a" }); - const places = stdout.split("\n").filter(it => it.includes("[Error/")); - expect({ places: places.map(it => it.replace(/: .* \[/, " [")), stderr, exitCode }).toEqual({ - places: [...lines.map(line => `config.ts:${line}:1`), "src/b.ts:1:1"].map( + const errorLines = stdout.split("\n").filter(it => it.includes("[Error/")); + expect({ errors: errorLines.map(it => it.replace(/: .* \[/, " [")), stderr, exitCode }).toEqual({ + errors: [...lines.map(line => `config.ts:${line}:1`), "src/b.ts:1:1"].map( it => `${it} [Error/typescript(no-floating-promises)]`, ), stderr: "", @@ -5588,12 +5858,12 @@ maybe(() => { return f; }); ../../tsconfig.json has no "include", so it covers every file under it. To speed this up, add "include" to it.`; test.each([ - ["a warning says that a thousand files were loaded for it", {}, [], "packages/a", warning], - ["not if the tsconfig.json says what it includes", { "tsconfig.json": withInclude }, [], "packages/a", ""], - ["also with --tsconfig", {}, ["--tsconfig", "all.json"], "packages/a", warning], - ["not with --silent", {}, ["--silent"], "packages/a", ""], - ["not if they are all linted", {}, [], ".", ""], - ["also if the file is named", {}, ["config.ts", "src/b.ts"], "packages/a", warning], + ["warns that a thousand files were loaded to lint it", {}, [], "packages/a", warning], + ["doesn't warn if that tsconfig.json has an include", { "tsconfig.json": withInclude }, [], "packages/a", ""], + ["also warns with --tsconfig", {}, ["--tsconfig", "all.json"], "packages/a", warning], + ["doesn't warn with --silent", {}, ["--silent"], "packages/a", ""], + ["doesn't warn if all the loaded files are linted", {}, [], ".", ""], + ["also warns if the file is passed as an argument", {}, ["config.ts", "src/b.ts"], "packages/a", warning], ])("%s", async (_, others, flags, cwd, expected) => { const paths = flags.some(it => it.endsWith(".ts")) ? [] : ["."]; const args = ["-f", "unix", "--type-aware", ...flags, ...paths]; @@ -5604,7 +5874,7 @@ maybe(() => { return f; }); }); }); - // Without an oxlint config the flag names the project of every file, so it helps. + // Without an oxlint config, --tsconfig sets the project of every file, so passing it helps. const forEslint = `export default [{ files: ["**/*.ts"], plugins: { "@typescript-eslint": { meta: { name: "@typescript-eslint/eslint-plugin" } } }, @@ -5614,14 +5884,18 @@ maybe(() => { return f; }); describe.each([ ["no config", {}], ["an ESLint config", { "eslint.config.js": forEslint }], - ])("with %s the warning", (_, configured) => { + ])("with %s, the warning", (_, configured) => { const loaded = `warn: Loaded 1,001 files in "], - ["the type of its package", { module: "nodenext", moduleResolution: "nodenext" }, {}, "p.ts", "1"], - ])("%s", async (_, asModule, asScript, name, value) => { + ["the type in its package.json", { module: "nodenext", moduleResolution: "nodenext" }, {}, "p.ts", "1"], + ])("it's a script or a module depending on %s", async (_, asModule, asScript, name, value) => { const run = async (a: object, b: object) => { const { raw } = await lint( { @@ -5716,9 +5992,9 @@ maybe(() => { return f; }); ]); }); - // Two copies of one version of a package are one file to a program, and a private name is of one class. Both projects - // have both copies. - test("the files of a package", async () => { + // A program treats two copies of the same version of a package as one file, and a private name belongs to one + // class. Both projects have both copies. + test("two copies of a package are one file in both projects", async () => { const pkg = { "package.json": `{ "name": "pkg", "version": "1.0.0", "types": "index.d.ts" }`, "index.d.ts": `export declare class C {\n #secret;\n later(): Promise;\n}\n`, @@ -5744,7 +6020,8 @@ maybe(() => { return f; }); expect(found(raw, ["a", "b"])).toEqual({ a: reported, b: reported }); }); - // Each project imports the file of the other, which has the same text, before or after that project reads it itself. + // Each project imports the other's `own.ts`, which has the same text as its own, before or after the other + // project reads it. test.each([ [ "experimentalDecorators", @@ -5780,7 +6057,7 @@ maybe(() => { return f; }); b: ["own.ts:2:24 typescript(TS2700)", "own.ts:2:30 typescript(TS2373)", "own.ts:2:30 typescript(TS2454)"], }, ], - ])("%s", async (_, a, b, text, errors) => { + ])("only one of the projects has %s", async (_, a, b, text, errors) => { const { raw } = await lint( { ".oxlintrc.json": rc({ rules: {} }), @@ -5797,7 +6074,7 @@ maybe(() => { return f; }); }); }); - // The projects of a run are loaded and checked at the same time. + // A run's projects are loaded and checked in parallel. test("with many projects, every thread count reports the same, and each file is checked in its own project", async () => { const compilerOptions = { strict: true, lib: ["es2022"], types: [] }; const project = JSON.stringify({ compilerOptions, include: ["src"] }); @@ -5805,7 +6082,7 @@ maybe(() => { return f; }); ".oxlintrc.json": rc({ rules: { "typescript/no-floating-promises": "error" } }), "broken/tsconfig.json": JSON.stringify({ compilerOptions: { ...compilerOptions, lib: ["es1"] } }), "broken/a.ts": "Promise.resolve();\n", - // In no project. The two are one program. + // These two aren't in any project, so they form one program. "outside/global.ts": "const ofNoProject = Promise.resolve();\n", "outside/a.ts": "ofNoProject;\nof0;\n", // It has most of the files, so it gets several threads. @@ -5817,7 +6094,7 @@ maybe(() => { return f; }); files[`large/src/${i}.ts`] = "ofLarge;\nof0;\nexport {};\n"; expected.push(`large/src/${i}.ts:1:1 no-floating-promises`); } - // A promise that a project declares is only a promise in the program of that project. + // A promise that a project declares is only a promise in that project's program. for (let i = 0; i < 12; i++) { files[`small/${i}/tsconfig.json`] = project; files[`small/${i}/src/own.d.ts`] = `declare const of${i}: Promise;\n`; @@ -5827,18 +6104,63 @@ maybe(() => { return f; }); const runs = await Promise.all( [1, 2, 3, 8, 32].map(threads => lint(files, ["-f", "unix", "--type-aware", "--threads", `${threads}`])), ); - const places = [...runs[0].stdout.matchAll(/^(\S+:\d+:\d+): .*\((.*)\)\]$/gm)].map(it => `${it[1]} ${it[2]}`); - expect(places.sort()).toEqual(expected.sort()); + const reports = [...runs[0].stdout.matchAll(/^(\S+:\d+:\d+): .*\((.*)\)\]$/gm)].map(it => `${it[1]} ${it[2]}`); + expect(reports.sort()).toEqual(expected.sort()); expect(runs.map(it => [it.stdout, it.stderr, it.exitCode])).toEqual(runs.map(() => [runs[0].stdout, "", 1])); }); - const kindsOfFixes = (Object.keys(flagSets) as (keyof typeof flagSets)[]).flatMap(flags => + // TypeScript's parser reports `assert`, but oxc accepts it. The expected output is from oxlint 1.87.0 with + // tsgolint 7.0.2003. + const cycle = 'import { y } from "./b.js";\nString(y);\n'; + const twice = "let r = 1;\nlet r = 2;\n"; + test.each([ + ["nothing else in it", "", ["b.js:1:10 named", "b.js:2:8 default", "b.js:4:38 namespace"]], + [ + "an import cycle", + cycle, + ["a.js:1:19 no-cycle", "b.js:1:10 named", "b.js:1:25 no-cycle", "b.js:2:8 default", "b.js:4:38 namespace"], + ], + // oxc rejects the file, so oxlint doesn't know what it imports or exports. + ["a name declared twice", twice, ["a.js:1:5"]], + ["a name declared twice and an import cycle", cycle + twice, ["a.js:3:5"]], + ])( + "with --type-aware, imports from a file with `assert {}` are checked the same at every thread count: %s", + async (_, before, expected) => { + const compilerOptions = { strict: true, noEmit: true, lib: ["es2015"], types: [], allowJs: true }; + const rules = ["import/named", "import/default", "import/namespace", "import/no-cycle"]; + const files = { + ".oxlintrc.json": rc({ + plugins: ["import", "typescript"], + rules: Object.fromEntries([...rules, "typescript/no-floating-promises"].map(it => [it, "error"])), + }), + "tsconfig.json": JSON.stringify({ + compilerOptions: { ...compilerOptions, resolveJsonModule: true, moduleResolution: "bundler" }, + }), + "d.json": "{}\n", + "a.js": `${before}import json from "./d.json" assert { type: "json" };\nexport const x = json;\n`, + "b.js": + 'import { missing } from "./a.js";\nimport none from "./a.js";\nimport * as all from "./a.js";\n' + + "export const y = [missing, none, all.nope];\n", + }; + const runs = await Promise.all( + [1, 2, 2, 8, 8].map(threads => lint(files, ["-f", "unix", "--type-aware", "--threads", `${threads}`])), + ); + const reportsIn = (stdout: string) => + [...stdout.matchAll(/^(\S+:\d+:\d+): .*?(?:\((.*)\))?\]$/gm)] + .map(it => it.slice(1).join(" ").trim()) + .sort(); + expect(runs.map(it => reportsIn(it.stdout))).toEqual(runs.map(() => expected)); + expect(runs.map(it => [it.stdout, it.stderr, it.exitCode])).toEqual(runs.map(() => [runs[0].stdout, "", 1])); + }, + ); + + const fixKinds = (Object.keys(flagSets) as (keyof typeof flagSets)[]).flatMap(flags => [false, true].map((typed): [keyof typeof flagSets, boolean] => [flags, typed]), ); - test.serial.each(kindsOfFixes)( - "the flags of %s change what they change with oxlint (rules that need types: %p)", + test.serial.each(fixKinds)( + "the `%s` flags make the same changes as oxlint (type-aware rules: %p)", async (flags, typed) => { - // fixes.expected.json is what oxlint 1.87.0 with tsgolint 7.0.2003 makes of the files. + // fixes.expected.json has the files as fixed by oxlint 1.87.0 with tsgolint 7.0.2003. const some = fixCases .map((it, index) => ({ it, directory: directoryOf(index) })) .filter(({ it }) => !!it.typed === typed); @@ -5861,18 +6183,18 @@ maybe(() => { return f; }); isDebug || isASAN ? 120_000 : 30_000, ); - // tsgolint's fix writes code that does not parse, or that does something else. `bun lint` makes the same report and - // leaves the code, or writes the code that does the same. - test("a fix of tsgolint that changes what the code does is not copied", async () => { + // tsgolint's fix writes code that doesn't parse or that behaves differently. `bun lint` reports the same problem, + // and either doesn't fix it or writes code that behaves the same. + test("doesn't copy tsgolint's fixes that change what the code does", async () => { const shapes: [rule: string, file: string, text: string, fixed?: string, options?: object][] = [ - // One match where `match` gave all of them. + // `exec` returns one match where `match` returned all of them. ["prefer-regexp-exec", "a.ts", "declare const s: string;\nexport const a = s.match(new RegExp(/x/g));\n"], [ "prefer-regexp-exec", "a.ts", "declare const s: string;\nexport const a = s.match(new RegExp(/x/g, undefined));\n", ], - // `p` is `/b+/` there, and tsgolint writes `s.includes('abc')`. + // `p` is `/b+/` at that point, but tsgolint writes `s.includes('abc')`. [ "prefer-includes", "a.ts", @@ -5883,7 +6205,7 @@ maybe(() => { return f; }); "a.ts", "declare const s: string;\nlet p = /^a/;\np = /b/;\nexport const a = p.test(s);\n", ], - // `` does not parse. + // `` doesn't parse. [ "dot-notation", "a.tsx", @@ -5891,7 +6213,7 @@ maybe(() => { return f; }); undefined, { allowKeywords: false }, ], - // An `await` in a parameter does not parse. + // An `await` in a parameter doesn't parse. [ "no-misused-spread", "a.ts", @@ -5998,7 +6320,7 @@ maybe(() => { return f; }); expect(pairs.map((_, index) => reported(`${index}-parenthesized`))).toEqual(expected); }); - test("unbound-method knows RegExp.escape and the other newer built-ins that are bound", async () => { + test("unbound-method doesn't report RegExp.escape and the other newer built-ins that are bound", async () => { const it = { rule: "typescript/unbound-method", file: "a.ts", @@ -6010,7 +6332,7 @@ maybe(() => { return f; }); expect(JSON.parse(raw).diagnostics.map((it: { code: string }) => it.code)).toEqual([]); }); - test("what is left after the fixes is reported once, where it was", async () => { + test("problems that remain after --fix are reported once, at their original positions", async () => { const tsconfig = JSON.stringify({ compilerOptions: { strict: true, target: "esnext", module: "esnext" } }); const { files, raw } = await lint( { @@ -6020,7 +6342,7 @@ maybe(() => { return f; }); rules: { "no-var": "error", "no-debugger": "error", "typescript/await-thenable": "error" }, }), "tsconfig.json": tsconfig, - // `var` becomes `const` twice: a name that is declared twice, which is not said about the text that is written. + // Both `var`s become `const`, so the written text declares `a` twice, which isn't reported. "a.ts": "var a = 1; debugger;\nvar a = 2;\nexport async function f() {\n await a;\n}\n", }, ["--fix", "--type-aware", "-f", "json"], @@ -6029,14 +6351,14 @@ maybe(() => { return f; }); expect(files).toEqual({ "a.ts": "const a = 1; debugger;\nconst a = 2;\nexport async function f() {\n await a;\n}\n", }); - const places = JSON.parse(raw).diagnostics.map( + const reports = JSON.parse(raw).diagnostics.map( (it: any) => `${it.filename}:${it.labels[0].span.line}:${it.labels[0].span.column} ${it.code}`, ); - expect(places.sort()).toEqual(["a.ts:1:12 eslint(no-debugger)", "a.ts:4:9 typescript(await-thenable)"]); + expect(reports.sort()).toEqual(["a.ts:1:12 eslint(no-debugger)", "a.ts:4:9 typescript(await-thenable)"]); }); - test("the options that oxlint accepts are accepted", async () => { - // A configuration that is refused ends the run. options.json is what oxlint 1.87.0 accepts. Each of the configurations has + test("accepts the rule options that oxlint accepts", async () => { + // A rejected config ends the run. options.json has the options that oxlint 1.87.0 accepts. Each config here has // options for many rules. const configs = configurations(optionsOfOxlint); expect(configs.length).toBeGreaterThan(100); @@ -6046,12 +6368,12 @@ maybe(() => { return f; }); files[`${index}/a.ts`] = "export {};\n"; }); const { raw } = await lint(files, ["-f", "json"]); - // What is refused is said instead. + // If a config is rejected, the output is the error instead of JSON, so the failure shows it. expect(raw.startsWith("{") ? JSON.parse(raw).number_of_files : raw).toBe(configs.length); }); }); - test(".eslintrc.json", async () => { + test("reads .eslintrc.json, with its env and overrides", async () => { const { stdout } = await lint( { ".eslintrc.json": `{ "root": true, "env": { "node": true }, "rules": { "no-undef": "error" }, "overrides": [{ "files": ["*.test.js"], "globals": { "test": "readonly" } }] }`, @@ -6068,8 +6390,8 @@ maybe(() => { return f; }); }); }); - test("no-useless-assignment: the name of a class declaration is one variable around the class and another in it", async () => { - // What is expected is what ESLint 10.12.0 reports. + test("no-useless-assignment: a class declaration's name is one variable outside the class and another inside it", async () => { + // The expected reports are from ESLint 10.12.0. const cases: [string, string[]][] = [ ["(v0 = v0); class v0 extends (function () { return v0; }) { }", ["1:2"]], ["const v1 = (() => (v3)); class v3 extends [({ k: [(v3 = v3)] })] { }", ["1:52"]], @@ -6095,7 +6417,7 @@ maybe(() => { return f; }); it.messages.map((it: any) => `${it.line}:${it.column}`), ]), ); - expect(reported).toEqual(Object.fromEntries(cases.map(([, places], i) => [`c${i}.cjs`, places]))); + expect(reported).toEqual(Object.fromEntries(cases.map(([, positions], i) => [`c${i}.cjs`, positions]))); }); describe("comments", () => { @@ -6105,7 +6427,7 @@ maybe(() => { return f; }); "// eslint-disable-next-line no-debugger -- on purpose\ndebugger;\n// eslint-disable-next-line no-debugger\nexport {};\n", }; - test("eslint-disable, and a warning for one that disables nothing", async () => { + test("eslint-disable works, and an unused disable comment gets a warning", async () => { const { stdout, exitCode } = await lint(files, ["-f", "unix"]); expect(stdout).toMatchInlineSnapshot(` "/a.js:3:1: Unused eslint-disable directive (no problems were reported from 'no-debugger'). [Warning] @@ -6115,7 +6437,7 @@ maybe(() => { return f; }); expect(exitCode).toBe(0); }); - test("--no-inline-config", async () => { + test("--no-inline-config ignores disable comments", async () => { const { stdout, exitCode } = await lint(files, ["-f", "unix", "--no-inline-config"]); expect(stdout).toMatchInlineSnapshot(` "/a.js:2:1: Unexpected 'debugger' statement. [Error/no-debugger] @@ -6125,7 +6447,7 @@ maybe(() => { return f; }); expect(exitCode).toBe(1); }); - test("--report-unused-disable-directives-severity", async () => { + test("--report-unused-disable-directives-severity sets the severity of an unused disable comment", async () => { const [off, error] = await Promise.all([ lint(files, ["--report-unused-disable-directives-severity", "off"]), lint(files, ["--report-unused-disable-directives-severity", "error"]), @@ -6134,9 +6456,9 @@ maybe(() => { return f; }); expect(off.raw).toBe(""); }); - // What reads the comment stops where the stack ends: how deep that is depends on the build and on the system. A - // little before that depth, the rest of the value was given up at the bottom of the stack, which overflowed. - test("an `eslint` comment that is nested about as deep as the stack holds", async () => { + // The parser for the comment stops when the stack runs out, and how deep that is depends on the build and the OS, + // so this tries many depths. A value nested a little less deeply than that limit used to overflow the stack. + test("an `eslint` comment nested about as deep as the stack allows is reported as one error", async () => { const files: Record = { ".eslintrc.json": '{ "root": true }' }; for (let depth = 1_000; depth < 30_000; depth = Math.ceil(depth * 1.025)) { const arrays = "[".repeat(depth) + "]".repeat(depth); @@ -6151,9 +6473,9 @@ maybe(() => { return f; }); }); }); - // The parser stops where the stack ends. What makes the suggestion of no-unused-vars went out through the pattern with a call - // for each level, and larger frames: a little before that depth the stack overflowed. - test("a pattern that is nested about as deep as the stack holds", async () => { + // The parser stops when the stack runs out. The code that builds the no-unused-vars suggestion used to walk out + // through the pattern with one call per level and larger frames, so the stack overflowed a little before that depth. + test("a pattern nested about as deep as the stack allows is either rejected or reported by no-unused-vars", async () => { const config = { root: true, parserOptions: { ecmaVersion: 2018 }, rules: { "no-unused-vars": "error" } }; const files: Record = { ".eslintrc.json": JSON.stringify(config) }; for (let depth = 1_000; depth < 45_000; depth = Math.ceil(depth * 1.04)) { @@ -6172,9 +6494,9 @@ maybe(() => { return f; }); expect(rules).toHaveLength(Object.keys(files).length - 1); }); - // A fix often has the text of its node, so the fixes of nodes that are in each other have the square of the depth in bytes: - // a gigabyte here. A format that only counts what can be fixed keeps none of it. - test("the fixes of 45,000 nodes in each other, which are only counted", async () => { + // A fix often contains its node's text, so the size of nested nodes' fixes is quadratic in the depth, which is a + // gigabyte here. A format that only counts the fixable problems doesn't keep any of that text. + test("the fixes of 45,000 nested nodes are only counted, not kept in memory", async () => { using dir = tempDir("bun-lint-nested-fixes", { ".eslintrc.json": JSON.stringify({ root: true, rules: { "no-extra-boolean-cast": "error" } }), "a.js": `x = ${"!".repeat(45_000)}a;\n`, @@ -6208,12 +6530,12 @@ maybe(() => { return f; }); expect(maxRSS).toBeLessThan((isASAN || isDebug ? 700 : 300) * 1024 * 1024); }); - // What matches a path with a pattern of `include` called itself for each `**`, and tried every number of directories for each - // of them in turn: the stack, and time that grows like a power of their number. + // The matcher for `include` patterns used to recurse for each `**`, and to try every number of directories for each + // of them in turn. That overflowed the stack, and took time exponential in the number of `**`. test.each([ ["200,000 in a row", [`${"**/".repeat(200_000)}*.ts`], "a.ts"], ["16 that match nothing, 34 directories", [`${"**/a/".repeat(16)}b.ts`, "**/*.ts"], `${"a/".repeat(34)}a.ts`], - ])("`**` in `include` of a tsconfig.json: %s", async (_, include, file) => { + ])("handles many `**` in a tsconfig.json's `include`: %s", async (_, include, file) => { const rules = { "typescript/no-floating-promises": "error" }; const files = { ".oxlintrc.json": JSON.stringify({ plugins: ["typescript"], categories: { correctness: "off" }, rules }), @@ -6225,12 +6547,12 @@ maybe(() => { return f; }); expect(exitCode).toBe(1); }); - // Whether a function is sensitive to its context was asked of each from every one around it, each time down to the last: the - // cube of their number: 25 s. + // Every enclosing function used to ask whether each function inside it is context-sensitive, and each time that + // walked down to the innermost one. That's cubic in the number of functions, and took 25 s. test.skipIf(isDebug || isASAN).each([ ["arrows", "(a: number) => ", ""], ["functions", "function (a: number) { return ", " }"], - ])("2,000 %s in each other, with types", async (_, open, close) => { + ])("handles 2,000 nested %s with --type-aware", async (_, open, close) => { const rules = { "typescript/no-floating-promises": "error" }; const files = { ".oxlintrc.json": JSON.stringify({ plugins: ["typescript"], categories: { correctness: "off" }, rules }), @@ -6242,8 +6564,8 @@ maybe(() => { return f; }); expect(exitCode).toBe(1); }); - // What reads a tsconfig.json called itself for each file that is extended, on the main thread. - test("a tsconfig.json at the end of a chain of 5,000 that extend each other", async () => { + // The tsconfig.json reader used to recurse for each extended file, on the main thread. + test("follows a chain of 5,000 `extends` from a tsconfig.json", async () => { const rules = { "typescript/no-floating-promises": "error" }; const files: Record = { ".oxlintrc.json": JSON.stringify({ plugins: ["typescript"], categories: { correctness: "off" }, rules }), @@ -6257,8 +6579,9 @@ maybe(() => { return f; }); expect(exitCode).toBe(1); }); - // A file to which links give several names, and rules that look at several files. It must be the same in every run. - describe("a file that has several names by links", () => { + // Symlinks give one file several paths, and these rules look at several files. Every run must report the same + // problems. + describe("a file with several paths through symlinks", () => { const project = (configuration: Record) => { const dir = tempDir("bun-lint-links", { ...configuration, @@ -6267,11 +6590,11 @@ maybe(() => { return f; }); "other/keep.txt": "", }); symlinkSync(join(String(dir), "real/skills"), join(String(dir), "other/skills"), "junction"); - // Not everybody may make one on Windows. + // On Windows, not every user is allowed to create a symlink to a file. if (!isWindows) symlinkSync("a.js", join(String(dir), "real/skills/c.js")); return dir; }; - /** The files that have a report, for each outcome that there is among twenty runs. */ + /** Lints twenty times and returns each distinct outcome, as the list of files that have a report. */ const outcomes = async (cwd: string) => { const runs = Array.from({ length: 20 }, async () => { await using proc = spawn({ @@ -6287,8 +6610,8 @@ maybe(() => { return f; }); return [...new Set((await Promise.all(runs)).map(it => it.join(" ")))]; }; - // oxlint 1.87 follows links, and lints a file under each of its names. - test("with an .oxlintrc.json it is reported under each", async () => { + // oxlint 1.87 follows symlinks, and lints a file under each of its paths. + test("with an .oxlintrc.json, it's reported under each path", async () => { using dir = project({ ".oxlintrc.json": JSON.stringify({ plugins: ["import"], @@ -6301,9 +6624,9 @@ maybe(() => { return f; }); expect(await outcomes(String(dir))).toEqual([expected.join(" ")]); }); - // ESLint 10.12 enters no directory that is a link. eslint-plugin-import 2.32.0 knows the file that is linted by its name, and - // what it imports without links: nothing imports c.js, so it is in no cycle. - test("with an eslint.config.js the link to a file is a module of its own", async () => { + // ESLint 10.12 doesn't enter a symlinked directory. eslint-plugin-import 2.32.0 identifies the linted file by the + // path it was given, and the files it imports by their real paths. Nothing imports c.js, so it isn't in a cycle. + test("with an eslint.config.js, a symlink to a file is a separate module", async () => { using dir = project({ "eslint.config.mjs": `export default [{ plugins: { import: { meta: { name: "eslint-plugin-import" }, rules: {} } }, @@ -6314,9 +6637,9 @@ maybe(() => { return f; }); }); }); - // The defaults, the places and the texts of ESLint's rules are those of the major version of `eslint` that is installed for the - // configuration file. What ESLint 9.39.5 and ESLint 10.12.0 report. - describe("the rules of ESLint are those of the eslint that is installed", () => { + // The defaults, report locations and messages of ESLint's rules follow the major version of the `eslint` package + // installed for the config file. The expected reports are from ESLint 9.39.5 and ESLint 10.12.0. + describe("ESLint's rules behave like the installed version of eslint", () => { const files = { "eslint.config.mjs": 'export default [{ linterOptions: { reportUnusedDisableDirectives: "error" }, rules: {\n "max-depth": ["error", 1], "max-statements": ["error", 2], "max-lines-per-function": ["error", 3], "max-nested-callbacks": ["error", 1],\n "require-yield": "error", "no-useless-constructor": "error", "no-shadow-restricted-names": "error", "new-cap": ["error", { properties: false }],\n radix: ["error", "as-needed"], "use-isnan": "error", "no-extra-boolean-cast": "error", "prefer-promise-reject-errors": "error",\n "no-async-promise-executor": "error",\n} }];\n', @@ -6366,22 +6689,23 @@ maybe(() => { return f; }); ]; test.each([ ["9.39.5", nine], - // With such a configuration file it is nearer to 9 than to 10. + // With an eslint.config.mjs, ESLint 8 is closer to 9 than to 10. ["8.57.1", nine], ["10.12.0", ten], [undefined, ten], - ])("%s", async (version, expected) => { + ])("installed eslint: %s", async (version, expected) => { const installed = { "node_modules/eslint/package.json": JSON.stringify({ name: "eslint", version }) }; const { raw } = await lint({ ...files, ...(version && installed) }, ["-f", "json", "a.js"]); - const said = (JSON.parse(raw)[0].messages as any[]).map( + const reports = (JSON.parse(raw)[0].messages as any[]).map( it => `${it.ruleId} ${it.line}:${it.column}-${it.endLine}:${it.endColumn} ${it.message}`, ); - expect(said).toEqual(expected); + expect(reports).toEqual(expected); }); - // `eslint-scope` takes the name of a JSX element for a reference since ESLint 10. Before that a rule of a plugin marks what an - // element uses, as `react/jsx-uses-vars` does: here `local/uses-vars`, which MARKS=off turns off. - describe("the names of JSX elements", () => { + // Since ESLint 10, `eslint-scope` treats a JSX element's name as a reference. Before that, a plugin's rule has to + // mark the variables that an element uses, like `react/jsx-uses-vars`. Here that rule is `local/uses-vars`, and + // MARKS=off turns it off. + describe("JSX element names are references since ESLint 10", () => { const files = { "eslint.config.mjs": '// What eslint-plugin-react\'s jsx-uses-vars does, in short.\nconst usesVars = { create(context) { return {\n Program(node) { context.sourceCode.markVariableAsUsed("marked", node); },\n JSXOpeningElement(node) {\n let name = node.name;\n while (name.type === "JSXMemberExpression") name = name.object;\n if (name.type === "JSXIdentifier") context.sourceCode.markVariableAsUsed(name.name, node);\n },\n}; } };\nexport default [{ files: ["**/*.jsx"], plugins: { local: { rules: { "uses-vars": usesVars } } }, languageOptions: { parserOptions: { ecmaFeatures: { jsx: true } } },\n rules: { "local/uses-vars": process.env.MARKS === "off" ? "off" : "error", "no-unused-vars": "error", "no-undef": "error", "no-use-before-define": "error" } }];\n', @@ -6429,20 +6753,21 @@ maybe(() => { return f; }); "no-use-before-define 6:29-6:35 'Widget' was used before it was defined.", ], ], - ])("%s, the rule that marks them is %s", async (version, MARKS, expected) => { + ])("eslint %s, the rule that marks them as used is %s", async (version, MARKS, expected) => { const installed = { "node_modules/eslint/package.json": JSON.stringify({ name: "eslint", version }) }; const { raw } = await lint({ ...files, ...installed }, ["-f", "json", "a.jsx"], { env: { MARKS } }); - const said = (JSON.parse(raw)[0].messages as any[]).map( + const reports = (JSON.parse(raw)[0].messages as any[]).map( it => `${it.ruleId} ${it.line}:${it.column}-${it.endLine}:${it.endColumn} ${it.message}`, ); - expect(said).toEqual(expected); + expect(reports).toEqual(expected); }); }); }); - // The decorators of a parameter are evaluated in the scope around the function. So a function in one is in that scope, though - // it is written between the parentheses, and what is written after it is in the scope of the function all the same. - describe("the scope of what follows a function in the decorator of a parameter", () => { + // A parameter's decorators are evaluated in the scope around the function. So a function in a decorator is in that + // outer scope even though it's written between the parentheses, but the code after it is still in the function's + // scope. + describe("code after a function in a parameter's decorator is in the function's scope", () => { const code = (decorator: string) => `class S {\n constructor(${decorator}private d: D, private readonly repo: Repo) {\n this.repo = repo;\n }\n}\n`; const sources = { @@ -6471,23 +6796,29 @@ maybe(() => { return f; }); rules: { "@typescript-eslint/no-unnecessary-parameter-property-assignment": "error" }, }];`, ], - ])("as %s", async (_, name, configuration) => { + ])("with an %s config", async (_, name, configuration) => { const { stdout, exitCode } = await lint({ [name]: configuration, ...sources }, [ "-f", "unix", ...Object.keys(sources), ]); - const places = [...stdout.matchAll(/([\w-]+\.ts):(\d+):(\d+): /g)].map(it => `${it[1]}:${it[2]}:${it[3]}`); - expect(places.sort()).toEqual(["arrow.ts:3:5", "function.ts:3:5", "no-decorator.ts:3:5", "no-function.ts:3:5"]); + const positions = [...stdout.matchAll(/([\w-]+\.ts):(\d+):(\d+): /g)].map(it => `${it[1]}:${it[2]}:${it[3]}`); + expect(positions.sort()).toEqual([ + "arrow.ts:3:5", + "function.ts:3:5", + "no-decorator.ts:3:5", + "no-function.ts:3:5", + ]); expect(exitCode).toBe(1); }); }); - // A rule for ESLint that takes the first reference to a name in a scope gets the one the scope manager makes first. That isn't - // always the one that is written first: it visits a type after the value, type arguments after the arguments, type parameters - // after the parameters, decorators after the member, and the `b` of `[a[b]] = c` before `a`. The two rules here take the first - // reference. What they report is what ESLint 10.12.0 reports with typescript-eslint 8.71.1 and eslint-plugin-react 7.37.5. - describe("the references of a scope are in the order in which the scope manager makes them", () => { + // An ESLint rule that takes the first reference to a name in a scope gets the one the scope manager creates first. + // That isn't always the first one in the source: the scope manager visits a type after the value, type arguments + // after the arguments, type parameters after the parameters, decorators after the member, and the `b` of `[a[b]] = c` + // before `a`. The two rules here take the first reference. The expected reports are from ESLint 10.12.0 with + // typescript-eslint 8.71.1 and eslint-plugin-react 7.37.5. + describe("a scope's references are in the order the scope manager creates them", () => { const reported = async (plugin: string, name: string, rule: string, sources: Record) => { const configuration = `export default [{ files: ["**/*.ts"], @@ -6507,7 +6838,7 @@ maybe(() => { return f; }); // `size` is a type outside the class and a parameter property in it. The last line of the constructor is reported if the // first reference to `size` in the constructor is to the parameter. - test("types", async () => { + test("with types", async () => { const box = (parameters: string, body: string, typeParameters = "") => `type size = number;\ndeclare function g(x?: unknown): T;\nexport class Box {\n constructor${typeParameters}(public size: number${parameters}) {\n ${body}\n this.size = size;\n }\n}\n`; const theParameterIsFirst = { @@ -6552,7 +6883,7 @@ maybe(() => { return f; }); // `useState` is a parameter of the function, and `useMemo` is React's. The call of `useState` is reported if the first reference // in its scope to one of the two is to `useMemo`. - test("members in patterns, decorators, and what a class extends", async () => { + test("with members in patterns, decorators, and a class's `extends` clause", async () => { const panel = (body: string) => `import { useMemo, useState } from "react";\nexport function Panel(useState: any, rows: any) {\n ${body}\n}\n`; const call = "const a = useState(0);"; @@ -6591,9 +6922,10 @@ maybe(() => { return f; }); }); }); - // typescript-eslint's scope manager doesn't visit the type of a `catch` parameter or the options of an import type: for it there - // are no scopes, no variables and no references in them. oxc visits both. For both, `["a"]` in an enum declares `a`. - describe("what only one of the two scope analyses visits", () => { + // typescript-eslint's scope manager doesn't visit the type of a `catch` parameter or the options of an import type, + // so it has no scopes, variables or references for them. oxc visits both. In both analyses, `["a"]` in an enum + // declares `a`. + describe("syntax that only one of the two scope analyses visits", () => { const sources = { "catch-type.ts": `type Shape = unknown;\nconst width = 1;\ntry {} catch (e: Shape) { e; }\ntry {} catch (e: typeof width) { e; }\ntry {} catch (e: typeof missing) { e; }\ntry {} catch (e: (width: number) => void) { e; }\nexport {};\n`, "import-type.ts": `const kind = "a";\nexport type A = import("./m", { with: { k: kind } });\nexport type B = import("./m", { with: { k: function (left: unknown) { const right = 1; return missing; } } });\nexport type C = import("./m", { with: { k: function (kind: unknown) { return kind; } } });\nexport type D = import("./m", { with: { k: class kind {} } });\n`, @@ -6610,7 +6942,7 @@ maybe(() => { return f; }); return found.map(it => `${it[1]} ${it[2]}`).sort(); }; - test("as ESLint 10.12.0 with typescript-eslint 8.71.1", async () => { + test("matches ESLint 10.12.0 with typescript-eslint 8.71.1", async () => { const configuration = `export default [{ files: ["**/*.ts"], plugins: { "@typescript-eslint": { meta: { name: "@typescript-eslint/eslint-plugin" } } }, @@ -6623,7 +6955,7 @@ maybe(() => { return f; }); ]); }); - test("as oxlint 1.87", async () => { + test("matches oxlint 1.87", async () => { const configuration = JSON.stringify({ categories: { correctness: "off" }, rules: rules("") }); const enums = { "enum-shadows.ts": `const size = 1;\nenum E { ["size"] = 1, other = size as any }\nexport { E };\n`, @@ -6643,11 +6975,11 @@ maybe(() => { return f; }); }); }); - // oxlint analyses a file twice. Its own rules see the scopes of oxc, a rule of a plugin in JavaScript those of typescript-eslint. They - // differ about `namespace A.B {}`, about a function in a block of sloppy JavaScript, and about what is in the type of a `catch` - // parameter and in the options of an import type. A rule that is built in here and that oxlint lacks, as `no-catch-shadow`, is - // one that oxlint could only run from a plugin. What is expected is what oxlint 1.87 reports, and for `no-catch-shadow` what - // it reports for the plugin's copy of that rule. + // oxlint analyzes a file twice. Its own rules see oxc's scopes, and a JavaScript plugin's rules see + // typescript-eslint's. The two differ on `namespace A.B {}`, on a function in a block in sloppy-mode JavaScript, and + // on what's in the type of a `catch` parameter and in the options of an import type. A rule that's built in here but + // that oxlint lacks, like `no-catch-shadow`, is one that oxlint could only run from a plugin. The expected reports + // are from oxlint 1.87, and for `no-catch-shadow` they're what it reports for the plugin's copy of that rule. describe("with an oxlint config, which scopes a rule sees doesn't depend on the other rules", () => { const sources = { "namespace.ts": `let Inner = 0;\nnamespace Outer.Inner { Inner = 1; export const x = Inner; try {} catch (Inner) {} }\nconsole.log(Inner, Outer);\n`, @@ -6669,7 +7001,7 @@ const scopes = { create(context) { return { Program(node) { } }; } }; export default { meta: { name: "q" }, rules: { shadow, scopes } };\n`, }; - const ofOxlint = { + const oxlintRules = { "no-undef": "error", "no-unused-vars": "error", "no-shadow": "error", @@ -6684,13 +7016,13 @@ export default { meta: { name: "q" }, rules: { shadow, scopes } };\n`, globals: { kind: "readonly" }, ignorePatterns: ["*.mjs"], ...more, - rules: { ...ofOxlint, ...rules }, + rules: { ...oxlintRules, ...rules }, }; const { stdout } = await lint({ ".oxlintrc.json": JSON.stringify(configuration), ...sources }, ["-f", "unix"]); const found = [...stdout.matchAll(/^([\w-]+\.\w+:\d+:\d+): (.*) \[Error\/(\w+)\(([\w-]+)\)\]$/gm)]; const all = found.map(it => `${it[1]} ${it[4]}` + (it[3] === "q" ? ` ${it[2]}` : "")).sort(); - const isOfOxlint = (it: string) => it.split(" ")[1] in ofOxlint; - return { ofOxlint: all.filter(isOfOxlint), others: all.filter(it => !isOfOxlint(it)) }; + const isOxlintRule = (it: string) => it.split(" ")[1] in oxlintRules; + return { fromOxlintRules: all.filter(isOxlintRule), others: all.filter(it => !isOxlintRule(it)) }; }; const expected = [ "block.cjs:3:15 no-shadow", @@ -6708,18 +7040,18 @@ export default { meta: { name: "q" }, rules: { shadow, scopes } };\n`, "switch.cjs:3:67 no-unused-vars", ]; - test("only oxlint's rules", async () => { - expect(await reported({}, {})).toEqual({ ofOxlint: expected, others: [] }); + test("with only oxlint's rules", async () => { + expect(await reported({}, {})).toEqual({ fromOxlintRules: expected, others: [] }); }); - test("beside a plugin without rules", async () => { - expect(await reported({ jsPlugins: ["./empty.mjs"] }, {})).toEqual({ ofOxlint: expected, others: [] }); + test("with a plugin that has no rules", async () => { + expect(await reported({ jsPlugins: ["./empty.mjs"] }, {})).toEqual({ fromOxlintRules: expected, others: [] }); }); - test("beside a plugin that asks the scopes", async () => { + test("with a plugin that reads the scopes", async () => { const rules = { "q/shadow": "error", "q/scopes": "error" }; expect(await reported({ jsPlugins: ["./plugin.mjs"] }, rules)).toEqual({ - ofOxlint: expected, + fromOxlintRules: expected, others: [ "block.cjs:1:1 scopes global[] function[] block[helper] function[] block[] catch[helper] block[]", "block.js:1:1 scopes global[] block[helper] function[] block[] catch[helper] block[]", @@ -6733,7 +7065,7 @@ export default { meta: { name: "q" }, rules: { shadow, scopes } };\n`, }); }); - // The mark is on the plugin's variable. + // The mark is set on the variable that the plugin sees, not on oxlint's. test("`markVariableAsUsed` in a plugin doesn't silence oxlint's no-unused-vars", async () => { const files = { ".oxlintrc.json": JSON.stringify({ @@ -6763,17 +7095,18 @@ export default { meta: { name: "q" }, rules: { marks, marked } };\n`, ]); }); - test("beside a built-in rule that oxlint lacks", async () => { + test("with a built-in rule that oxlint lacks", async () => { expect(await reported({}, { "no-catch-shadow": "error" })).toEqual({ - ofOxlint: expected, + fromOxlintRules: expected, others: ["namespace.ts:2:67 no-catch-shadow"], }); }); }); - // `namespace A.B { .. }` is one node, and what is between the braces is its body: a rule that looks at the statements beside a - // statement says there what it says in `namespace B { .. }` and in `namespace A { export namespace B { .. } }`. - describe("the statements of a namespace with dots in its name", () => { + // `namespace A.B { .. }` is one node, and its body is the code between the braces. So a rule that looks at a + // statement's siblings reports the same there as in `namespace B { .. }` and in + // `namespace A { export namespace B { .. } }`. + describe("statements in a namespace with a dotted name are linted like those in a plain namespace", () => { const bodies = { "one-var": ["let a = 1;", "let b = 2;", "var c = 3;", "var d = 4;"], "vars-on-top": ["export var x = 1;", "foo();", "export var y = 2;"], @@ -6802,7 +7135,7 @@ export default { meta: { name: "q" }, rules: { marks, marked } };\n`, }); test.each([ [ - // What oxlint 1.87 reports for each of the four. + // This is what oxlint 1.87 reports for each of the four forms. "oxlint", ".oxlintrc.json", JSON.stringify({ plugins: ["typescript"], categories: { correctness: "off" }, rules: rules("typescript") }), @@ -6833,7 +7166,7 @@ export default { meta: { name: "q" }, rules: { marks, marked } };\n`, "void": ["4:25 no-invalid-void-type"], }, ], - ])("as %s", async (_, name, configuration, inEach) => { + ])("with an %s config", async (_, name, configuration, expectedByBody) => { const sources: Record = {}; for (const [body, lines] of Object.entries(bodies)) forms.forEach( @@ -6844,13 +7177,17 @@ export default { meta: { name: "q" }, rules: { marks, marked } };\n`, for (const it of stdout.matchAll(/([\w.-]+\.ts):(\d+:\d+): .*[/(]([\w-]+)\)?\]/g)) found[it[1]].push(`${it[2]} ${it[3]}`); for (const it of Object.values(found)) it.sort(); - const expected = Object.keys(sources).map(it => [it, inEach[it.split(".")[0] as keyof typeof inEach]]); + const expected = Object.keys(sources).map(it => [ + it, + expectedByBody[it.split(".")[0] as keyof typeof expectedByBody], + ]); expect(found).toEqual(Object.fromEntries(expected)); }); }); - // In a script `` start a comment, whose value is what follows: as ESLint 10.12 has it. - test("a directive in a comment that starts with ", async () => { + // In a script, `` at the start of a line. The comment's value is the text + // after it, same as in ESLint 10.12. + test("disable directives work in a comment that starts with ", async () => { const files = { "eslint.config.mjs": `export default [{ files: ["**/*.js"], @@ -6867,12 +7204,12 @@ export default { meta: { name: "q" }, rules: { marks, marked } };\n`, "unused-line.js": "foo; ` at the start of a line. [ @@ -21339,7 +22244,7 @@ describe("TypeScript grammar errors under .oxlintrc.json", () => { "HTML comments are not allowed in modules @11+3", ], ["js", "\n--> b\nimport.meta;", "HTML comments are not allowed in modules @1+3"], - // `let` with an escape is a name. + // `let` written with an escape is an identifier. [ "js", "l\\u0065t a;", @@ -21358,7 +22263,8 @@ describe("TypeScript grammar errors under .oxlintrc.json", () => { "Unexpected new.target expression @20+10 help: new.target is only allowed in constructors, functions, and class field initializers", "TS(1036) Statements are not allowed in ambient contexts. @20+11", ], - // What the lexer says next. + // oxc continues after a lexer error, so it prints a second error, or labels the whole word after a number. + // `bun lint` stops at the lexer's first error and labels one character. ["js", "await (x); 1__0; import.meta;", "Invalid Character `_` @13+0", "Invalid characters after number @13+1"], ["js", "await (x); 3in []; import.meta;", "Invalid characters after number @12+2"], ["js", "1__0; new.target; let zz; let zz;", "Invalid Character `_` @2+0", "Invalid characters after number @2+1"], @@ -21375,17 +22281,17 @@ describe("TypeScript grammar errors under .oxlintrc.json", () => { "Invalid Character `;` @2+0", "Unexpected new.target expression @4+10 help: new.target is only allowed in constructors, functions, and class field initializers", ], - // In a .tsx file `b; import.meta;", "Unterminated regular expression @11+18", "Unexpected token @11+18"], - // Type parameters that do not start. + // A `<` that no type parameter follows. ["ts", "declare function <;", "Unexpected token @18+1"], ]; - test.todo.each(knownDifferences)("%s: %j", async (extension, code, ...errors) => { + test.todo.each(knownDifferences)("prints oxlint's errors for a .%s file: %j", async (extension, code, ...errors) => { const name = `a.${extension}`; expect(await run({ [name]: code + "\n" }, oxlintrc)).toEqual({ errors: { [name]: errors }, exitCode: 1 }); }); - test("without a config file this code is linted, as typescript-eslint's parser takes it", async () => { + test("without a config file this code is linted, because typescript-eslint's parser accepts it", async () => { const files = { "a.ts": "export function f(a?: number, b: number) {}\n", "b.ts": "export class A { m(): void; }\n", diff --git a/test/cli/lint/messages.test.ts b/test/cli/lint/messages.test.ts index 217f707fbf57..63b7c410ebe7 100644 --- a/test/cli/lint/messages.test.ts +++ b/test/cli/lint/messages.test.ts @@ -19,12 +19,12 @@ async function bun(files: Record, args: string[]) { using dir = tempDir("bun-lint-messages", files); await using proc = spawn({ cmd: [bunExe(), ...args], env, cwd: String(dir), stdout: "pipe", stderr: "pipe" }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - const shown = (text: string) => normalizeBunSnapshot(text, String(dir)); - return { stdout: shown(stdout), stderr: shown(stderr), exitCode }; + const normalize = (text: string) => normalizeBunSnapshot(text, String(dir)); + return { stdout: normalize(stdout), stderr: normalize(stderr), exitCode }; } describe.concurrent("bun lint", () => { - test("rules that need types are skipped with a warning", async () => { + test("warns that it skipped the rules that need types", async () => { const rules = (...names: string[]) => `[lint.rules]\n${names.map(it => `"${it}" = "error"\n`).join("")}`; const files = { "a.ts": "export const a: number = 1;\n" }; const [one, two] = await Promise.all([ @@ -51,7 +51,7 @@ export default [{ plugins: { "@typescript-eslint": plugin }, rules: { "@typescri expect(stderr).toStartWith("warn: Skipped 1 rule that needs type information\n Use --type-aware to run it.\n"); }); - test("a config file that calls process.exit", async () => { + test("fails if the config file calls process.exit", async () => { const { stderr, exitCode } = await bun({ "eslint.config.mjs": "process.exit(1);\n", "a.js": "a;\n" }, ["lint"]); expect(stderr).toBe( "error: Cannot load the configuration file /eslint.config.mjs:\nIt exited before it exported a config.", @@ -59,13 +59,13 @@ export default [{ plugins: { "@typescript-eslint": plugin }, rules: { "@typescri expect(exitCode).toBe(2); }); - test("an .eslintrc.json with invalid JSON", async () => { + test("fails on an .eslintrc.json with invalid JSON", async () => { const { stderr, exitCode } = await bun({ ".eslintrc.json": "{ nope\n", "a.js": "a;\n" }, ["lint"]); expect(stderr).toEndWith("Cannot read config file: /.eslintrc.json\nError: Invalid JSON."); expect(exitCode).toBe(2); }); - test("a non-JSON option for a rule that runs in JavaScript", async () => { + test("rejects a non-JSON option for a rule that runs in JavaScript", async () => { const files = { "mine.js": `export default { meta: { name: "mine" }, rules: { x: { meta: { schema: false }, create: () => ({}) } } };\n`, "oxlint.config.ts": `export default { jsPlugins: ["./mine.js"], rules: { "mine/x": ["error", { a: new Map() }] } };\n`, @@ -78,7 +78,7 @@ export default [{ plugins: { "@typescript-eslint": plugin }, rules: { "@typescri expect(exitCode).toBe(1); }); - test("an older typescript-eslint with an .eslintrc", async () => { + test("warns about an older installed typescript-eslint with an .eslintrc", async () => { const files = { "node_modules/@typescript-eslint/eslint-plugin/package.json": JSON.stringify({ name: "@typescript-eslint/eslint-plugin", @@ -100,7 +100,7 @@ export default [{ plugins: { "@typescript-eslint": plugin }, rules: { "@typescri expect(exitCode).toBe(0); }); - test("a recognized but unsupported flag, and --env-info", async () => { + test("rejects a recognized but unsupported flag, and --env-info prints the ESLint version", async () => { const [flag, info] = await Promise.all([ bun({ "a.js": "a;\n" }, ["lint", "--mcp"]), bun({}, ["lint", "--env-info"]), @@ -113,13 +113,13 @@ export default [{ plugins: { "@typescript-eslint": plugin }, rules: { "@typescri }); describe.concurrent("bun fmt", () => { - test("a UTF-16 file", async () => { + test("fails on a UTF-16 file", async () => { const { stderr, exitCode } = await bun({ "a.js": Buffer.from("a;\n", "utf16le") }, ["fmt", "a.js"]); expect(stderr).toStartWith("error: This file is UTF-16. bun fmt only reads UTF-8\n at a.js\n\n"); expect(exitCode).toBe(2); }); - test("--plugin with --allow-unsupported, and a recognized but unsupported flag", async () => { + test("warns about --plugin with --allow-unsupported, and rejects a recognized but unsupported flag", async () => { const [plugin, flag] = await Promise.all([ bun({ "a.js": "a;\n" }, ["fmt", "--plugin=prettier-plugin-x", "--allow-unsupported", "--check", "a.js"]), bun({ "a.js": "a;\n" }, ["fmt", "--migrate=prettier"]), @@ -130,7 +130,7 @@ describe.concurrent("bun fmt", () => { expect(flag.exitCode).toBe(2); }); - test("oxfmt options in a .prettierrc", async () => { + test("rejects unsupported oxfmt options in a .prettierrc unless --allow-unsupported is passed", async () => { const hint = "\n Use --allow-unsupported to make this a warning."; const [one, two, allowed] = await Promise.all([ bun({ ".prettierrc": `{ "sortTailwindcss": true }\n`, "a.js": "a;\n" }, ["fmt", "a.js"]), @@ -155,7 +155,7 @@ describe.concurrent("bun fmt", () => { [`{ "customGroups": 1 }`, "`customGroups` must be an array"], [`{ "internalPattern": 1 }`, "`internalPattern` must be an array of strings"], ["1", "it must be a boolean or an object"], - ])("sortImports: %s", async (sortImports, message) => { + ])("rejects an invalid sortImports: %s", async (sortImports, message) => { const files = { ".oxfmtrc.json": `{ "sortImports": ${sortImports} }\n`, "a.js": "a;\n" }; const { stderr, exitCode } = await bun(files, ["fmt", "a.js"]); expect(stderr).toContain(`error: Invalid \`sortImports\` configuration: ${message}\n`); diff --git a/test/cli/lint/native-rules.test.ts b/test/cli/lint/native-rules.test.ts index 904eea997b41..fefd0c566156 100644 --- a/test/cli/lint/native-rules.test.ts +++ b/test/cli/lint/native-rules.test.ts @@ -88,10 +88,10 @@ async function listed() { /** Lists every core rule that has a typescript-eslint version, and whether that version needs type information. */ function pairsOf(rules: Listed[]) { - const ofESLint = new Set(rules.filter(it => it.scope === "eslint").map(it => it.value)); + const eslintRuleNames = new Set(rules.filter(it => it.scope === "eslint").map(it => it.value)); const base = (name: string) => (name === "only-throw-error" ? "no-throw-literal" : name); return rules - .filter(it => it.scope === "typescript" && ofESLint.has(base(it.value))) + .filter(it => it.scope === "typescript" && eslintRuleNames.has(base(it.value))) .map(it => ({ base: base(it.value), extension: `@typescript-eslint/${it.value}`, @@ -125,12 +125,14 @@ describe.concurrent("every built-in rule", () => { bunfig(Object.fromEntries(rules.map(it => [`${it.scope}/${it.value}`, setting(it.value, "error")]))), "d.tsx", ); - const ofHooks = (it: { scope: string; value: string }) => + const isHooksRule = (it: { scope: string; value: string }) => it.scope === "react" && asListed.has(`react-hooks/${it.value}`); - expect(rules.filter(ofHooks).map(it => it.value)).toContain("rules-of-hooks"); - expect(rules.filter(ofHooks).map(it => it.value)).toContain("exhaustive-deps"); - expect(rules.filter(ofHooks).map(it => it.value)).not.toContain("jsx-key"); - const names = rules.map(it => spellings[ofHooks(it) ? "react-hooks" : it.scope].map(prefix => prefix + it.value)); + expect(rules.filter(isHooksRule).map(it => it.value)).toContain("rules-of-hooks"); + expect(rules.filter(isHooksRule).map(it => it.value)).toContain("exhaustive-deps"); + expect(rules.filter(isHooksRule).map(it => it.value)).not.toContain("jsx-key"); + const names = rules.map(it => + spellings[isHooksRule(it) ? "react-hooks" : it.scope].map(prefix => prefix + it.value), + ); const ids = names.map(it => it[0]).sort(); const on = (found: Map) => [...found].flatMap(([id, severity]) => (severity === 2 ? [id] : [])).sort(); @@ -138,9 +140,9 @@ describe.concurrent("every built-in rule", () => { expect(on(asListed)).toEqual(runningOn("d.tsx")); await Promise.all( [0, 1, 2].map(async nth => { - const written = names.map(it => it[Math.min(nth, it.length - 1)]); + const chosenNames = names.map(it => it[Math.min(nth, it.length - 1)]); const found = await configured( - bunfig(Object.fromEntries(written.map(id => [id, setting(id, "error")]))), + bunfig(Object.fromEntries(chosenNames.map(id => [id, setting(id, "error")]))), "a.js", ); expect(on(found)).toEqual(runningOn("a.js")); @@ -235,8 +237,8 @@ describe.concurrent("core rules and their typescript-eslint versions never both results.map(({ filePath, messages }) => { const name = basename(filePath); const own = pairs.find(it => it.base === name.slice(0, -3))!; - const ofPair = messages.filter(it => it.ruleId === own.base || it.ruleId === own.extension); - return [name, ofPair.map(it => `${it.severity} ${it.ruleId}`)]; + const pairMessages = messages.filter(it => it.ruleId === own.base || it.ruleId === own.extension); + return [name, pairMessages.map(it => `${it.severity} ${it.ruleId}`)]; }), ); return { byFile, skipped: /Skipped (\d+) rules? that needs? type information/.exec(stderr)?.[1] }; @@ -486,7 +488,7 @@ describe.concurrent("core rules and their typescript-eslint versions never both expect(stderr).not.toContain("error:"); return problems(stdout); }; - const ofESLint = ["a.js:1 max-params", "b.ts:1 max-params"]; + const baseRuleOnly = ["a.js:1 max-params", "b.ts:1 max-params"]; expect( await Promise.all([ run({ "max-params": ["error", { max: 2 }] }), @@ -495,7 +497,13 @@ describe.concurrent("core rules and their typescript-eslint versions never both run({}, `/* eslint max-params: ["error", 2] */\n`), run({ "max-params": ["error", { max: 2 }] }, `/* eslint max-params: ["error", 2] */\n`), ]), - ).toEqual([["a.js:1 max-params", "b.ts:1 @typescript-eslint/max-params"], ofESLint, ofESLint, ofESLint, ofESLint]); + ).toEqual([ + ["a.js:1 max-params", "b.ts:1 @typescript-eslint/max-params"], + baseRuleOnly, + baseRuleOnly, + baseRuleOnly, + baseRuleOnly, + ]); }); test("eslint-disable works with either name and isn't reported as unused", async () => { @@ -632,7 +640,7 @@ export function A({ list, on }: { list: any[]; on: Object }) { ]; const expected = rules.flatMap(it => it[1]).sort((a, b) => a.localeCompare(b, "en", { numeric: true })); const ids = new Set(expected.map(it => it.slice(it.indexOf(" ") + 1))); - const ofThese = (stdout: string) => problems(stdout).filter(it => ids.has(it.slice(it.indexOf(" ") + 1))); + const relevantProblems = (stdout: string) => problems(stdout).filter(it => ids.has(it.slice(it.indexOf(" ") + 1))); test("when set in [lint.rules]", async () => { const { stdout, exitCode } = await lint( @@ -642,7 +650,7 @@ export function A({ list, on }: { list: any[]; on: Object }) { }, ["-f", "json"], ); - expect(ofThese(stdout)).toEqual(expected); + expect(relevantProblems(stdout)).toEqual(expected); expect(exitCode).toBe(1); }); @@ -653,14 +661,14 @@ export function A({ list, on }: { list: any[]; on: Object }) { "--rule", JSON.stringify(Object.fromEntries(rules.map(it => [it[0], "error"]))), ]); - expect(ofThese(stdout)).toEqual(expected); + expect(relevantProblems(stdout)).toEqual(expected); expect(exitCode).toBe(1); }); test("but are off by default", async () => { const { stdout } = await lint(files, ["-f", "json"]); // no-explicit-any is on by default for TypeScript. - expect(ofThese(stdout)).toEqual(["view.tsx:2 @typescript-eslint/no-explicit-any"]); + expect(relevantProblems(stdout)).toEqual(["view.tsx:2 @typescript-eslint/no-explicit-any"]); }); test("prettier/prettier works without prettier installed", async () => { @@ -797,6 +805,98 @@ describe.concurrent("rule options", () => { }); }); +describe.concurrent("react/jsx-newline", () => { + const id = "react/jsx-newline"; + const component = (children: string) => `export const C = ({ time, now }) => (\n
    \n${children}\n
    \n);\n`; + const onOneLine = component(" took {time} at {now}"); + + test("only offers a fix when there's a line break to double", async () => { + const files = { "a.jsx": onOneLine, "b.jsx": component(" {time}\n {now}"), ...bunfig({ [id]: "error" }) }; + const { stdout } = await lint(files, ["-f", "json", "a.jsx", "b.jsx"]); + const results = JSON.parse(stdout) as { messages: { ruleId: string; line: number; fix?: { text: string } }[] }[]; + expect(results.map(it => it.messages.filter(it => it.ruleId === id).map(it => [it.line, it.fix?.text]))).toEqual([ + [[3, undefined]], + [[4, "\n\n "]], + ]); + }); + + test("--fix doesn't claim to have fixed two expressions on one line", async () => { + const { stdout, stderr, exitCode } = await lint({ "a.jsx": onOneLine, ...bunfig({ [id]: "error" }) }, [ + "--fix", + "-f", + "unix", + "a.jsx", + ]); + expect(stdout).toContain(`a.jsx:3:20: JSX element should start in a new line [Error/${id}]`); + expect(stderr).not.toContain("Circular fixes"); + expect(stderr).not.toContain("Fixed"); + expect(exitCode).toBe(1); + }); +}); + +// oxlint renames in all of these cases, which merges two different variables into one. +describe.concurrent("unicorn/catch-error-name only renames when `error` isn't already in use", () => { + const id = "unicorn/catch-error-name"; + type Fix = { range: [number, number]; text: string }; + + /** Returns, for each report, `code` with its fix applied, or `null` if it has no fix. */ + async function renamed(code: string) { + const { stdout } = await lint({ "a.mjs": code, ...bunfig({ [id]: "error" }) }, ["-f", "json", "a.mjs"]); + const [{ messages }] = JSON.parse(stdout) as { messages: { ruleId: string; fix?: Fix }[] }[]; + return messages + .filter(it => it.ruleId === id) + .map(({ fix }) => (fix ? code.slice(0, fix.range[0]) + fix.text + code.slice(fix.range[1]) : null)); + } + + test.each([ + ["the block assigns to an outer `error`", "let error;\ntry {\n f();\n} catch (e) {\n error = e;\n}\ng(error);\n"], + [ + "a function in the block does", + "let error;\ntry {\n f();\n} catch (e) {\n g(() => (error = e));\n}\ng(error);\n", + ], + ["the function passed to .catch() does", "let error;\np.catch(e => {\n error = e;\n});\ng(error);\n"], + ["the second function passed to .then() reads it", "let error;\np.then(undefined, e => g(e, error));\n"], + [ + "the block reads the enclosing function's `error` parameter", + "function f(error) {\n try {\n g();\n } catch (e) {\n h(error, e);\n }\n}\nf();\n", + ], + ["the block reads a global", "try {\n f();\n} catch (e) {\n g(e, error);\n}\n"], + [ + "an inner block that uses the caught error declares `error`", + "try {\n f();\n} catch (e) {\n {\n const error = 1;\n g(e, error);\n }\n}\n", + ], + [ + "an inner function that uses the caught error has an `error` parameter", + "try {\n f();\n} catch (e) {\n g(error => h(e, error));\n}\n", + ], + ["the catch block declares `error`", "try {\n f();\n} catch (e) {\n const error = 1;\n g(error);\n}\n"], + ["the function itself declares `error`", "p.catch(e => {\n const error = g(e);\n return error;\n});\n"], + ])("no fix: %s", async (_, code) => { + expect(await renamed(code)).toEqual([null]); + }); + + test.each([ + [ + "nothing else is named `error`", + "try {\n f();\n} catch (e) {\n g(e);\n}\n", + "try {\n f();\n} catch (error) {\n g(error);\n}\n", + ], + [ + "an outer `error` isn't used in the block", + "function f(error) {\n try {\n g(error);\n } catch (e) {\n h(e);\n }\n}\nf();\n", + "function f(error) {\n try {\n g(error);\n } catch (error) {\n h(error);\n }\n}\nf();\n", + ], + [ + "an inner `error` doesn't enclose a use of the caught error", + "try {\n f();\n} catch (e) {\n g(e);\n h(error => error);\n}\n", + "try {\n f();\n} catch (error) {\n g(error);\n h(error => error);\n}\n", + ], + ["`{ e }` keeps its key", "p.catch(e => g({ e }));\n", "p.catch(error => g({ e: error }));\n"], + ])("a fix: %s", async (_, code, fixed) => { + expect(await renamed(code)).toEqual([fixed]); + }); +}); + describe.concurrent("comments", () => { const rules = bunfig({ "unicorn/no-null": "error", @@ -807,8 +907,8 @@ describe.concurrent("comments", () => { "react/rules-of-hooks": "error", }); - // Both tools' comments count when neither tool's config is there. - test.each(["eslint", "oxlint"])("%s-disable in every form", async tool => { + // Both tools' comments work when the project has neither tool's config. + test.each(["eslint", "oxlint"])("%s-disable works in every form", async tool => { const code = `// ${tool}-disable-next-line no-debugger debugger; debugger; // ${tool}-disable-line no-debugger @@ -826,38 +926,44 @@ export const a: any = 1; debugger; `; const { stdout, exitCode } = await lint({ "a.ts": code, ...rules }, ["-f", "json"]); - // The last comment is for another rule, so it is unused. + // The last comment is for another rule, so it's unused. expect(problems(stdout)).toEqual(["a.ts:7 no-debugger", "a.ts:14 null", "a.ts:15 no-debugger"]); expect(exitCode).toBe(1); }); - test.each(["eslint", "oxlint"])("// %s-disable is for the rest of the file, up to the next -enable", async tool => { - const code = `debugger;\n// ${tool}-disable no-debugger\ndebugger;\ndebugger;\n// ${tool}-enable no-debugger\ndebugger;\n`; - const { stdout } = await lint({ "a.js": code }, ["-f", "json"]); - expect(problems(stdout)).toEqual(["a.js:1 no-debugger", "a.js:6 no-debugger"]); - }); + test.each(["eslint", "oxlint"])( + "// %s-disable applies to the rest of the file, up to the next -enable", + async tool => { + const code = `debugger;\n// ${tool}-disable no-debugger\ndebugger;\ndebugger;\n// ${tool}-enable no-debugger\ndebugger;\n`; + const { stdout } = await lint({ "a.js": code }, ["-f", "json"]); + expect(problems(stdout)).toEqual(["a.js:1 no-debugger", "a.js:6 no-debugger"]); + }, + ); - test.each(["eslint", "oxlint"])("an unused %s-disable comment is called what it is called", async tool => { - const files = { - "a.js": `// ${tool}-disable-next-line no-debugger\nexport const a = 1;\n/* ${tool}-enable no-debugger */\n`, - }; - const { stdout, exitCode } = await lint(files, ["-f", "unix", "--report-unused-disable-directives"]); - expect(stdout).toContain( - `:1:1: Unused ${tool}-disable directive (no problems were reported from 'no-debugger'). [Error]`, - ); - expect(stdout).toContain( - `:3:1: Unused ${tool}-enable directive (no matching ${tool}-disable directives were found for 'no-debugger'). [Error]`, - ); - expect(exitCode).toBe(1); - }); + test.each(["eslint", "oxlint"])( + "the message about an unused %s-disable comment uses the comment's own prefix", + async tool => { + const files = { + "a.js": `// ${tool}-disable-next-line no-debugger\nexport const a = 1;\n/* ${tool}-enable no-debugger */\n`, + }; + const { stdout, exitCode } = await lint(files, ["-f", "unix", "--report-unused-disable-directives"]); + expect(stdout).toContain( + `:1:1: Unused ${tool}-disable directive (no problems were reported from 'no-debugger'). [Error]`, + ); + expect(stdout).toContain( + `:3:1: Unused ${tool}-enable directive (no matching ${tool}-disable directives were found for 'no-debugger'). [Error]`, + ); + expect(exitCode).toBe(1); + }, + ); - test("the comments of the two can be mixed", async () => { + test("eslint- and oxlint- comments can be mixed", async () => { const code = `/* oxlint-disable no-debugger */\ndebugger;\n/* eslint-enable no-debugger */\ndebugger;\n`; const { stdout } = await lint({ "a.js": code }, ["-f", "json"]); expect(problems(stdout)).toEqual(["a.js:4 no-debugger"]); }); - test("the rules about comments pass over the comments of both", async () => { + test("rules about comments skip both tools' directive comments", async () => { const code = `// oxlint-disable-next-line no-debugger debugger; debugger; // oxlint-disable-line no-debugger @@ -868,13 +974,13 @@ debugger; // eslint-disable-line no-debugger `; const rules = { "capitalized-comments": "error", "no-inline-comments": "error", "no-debugger": "error" } as const; const flat = { "eslint.config.mjs": `export default [{ rules: ${JSON.stringify(rules)} }];\n` }; - const [alone, fixed, withEslint] = await Promise.all([ + const [withBunfig, fixed, withEslint] = await Promise.all([ lint({ "a.js": code, ...bunfig(rules) }, ["-f", "json"]), - // A capital letter would end what the comment does. + // Capitalizing a directive comment would break it. lint({ "a.js": code, ...bunfig(rules) }, ["-f", "json", "--fix-dry-run"]), lint({ "a.js": code, ...flat }, ["-f", "json"]), ]); - expect(problems(alone.stdout)).toEqual(["a.js:7 capitalized-comments"]); + expect(problems(withBunfig.stdout)).toEqual(["a.js:7 capitalized-comments"]); expect(JSON.parse(fixed.stdout)[0].output).toBe(code.replace("another", "Another")); expect(problems(withEslint.stdout)).toEqual([ "a.js:1 capitalized-comments", @@ -1080,11 +1186,11 @@ describe.concurrent("[lint.categories] and framework plugins", () => { test("a rule named in [lint.rules] runs whether or not the project uses its framework", async () => { const rules = `[lint.rules]\n"@next/next/no-img-element" = "warn"\n"jest/valid-expect" = "error"\n`; - const [alone, withCategories] = await Promise.all([ + const [rulesOnly, withCategories] = await Promise.all([ lint({ ...frameworkFiles, "package.json": dependsOn(), "bunfig.toml": rules }, ["-f", "json"]), lint({ ...project, "package.json": dependsOn(), "bunfig.toml": correctnessAndPerf + rules }, ["-f", "json"]), ]); - expect(problems(alone.stdout)).toEqual(sorted(next, jest)); + expect(problems(rulesOnly.stdout)).toEqual(sorted(next, jest)); expect(problems(withCategories.stdout)).toEqual(sorted(general, next, jest)); }); @@ -1241,16 +1347,14 @@ describe.concurrent(`"plugin/*" = "off" turns off every rule of a plugin`, () => test("react/* and react-hooks/* are separate plugins", async () => { const hooks = `export function App({ on }) {\n if (on) useState(0);\n return
    ;\n}\n`; const files = { "app.jsx": hooks, "package.json": dependsOn("react") }; - const [ofHooks, ofReact] = ["app.jsx:2 react-hooks/rules-of-hooks", "app.jsx:3 react/no-children-prop"]; + const [hooksProblem, reactProblem] = ["app.jsx:2 react-hooks/rules-of-hooks", "app.jsx:3 react/no-children-prop"]; const correctness = `[lint.categories]\ncorrectness = "error"\n`; - const ofBoth = async (bunfig: string) => (await found(bunfig, [], files)).filter(it => it.includes(" react")); - const off = (name: string) => ofBoth(`${correctness}[lint.rules]\n"${name}/*" = "off"\n`); - expect(await Promise.all([ofBoth(correctness), off("react"), off("react-hooks"), off("react_hooks")])).toEqual([ - [ofHooks, ofReact], - [ofHooks], - [ofReact], - [ofReact], - ]); + const reactProblems = async (bunfig: string) => + (await found(bunfig, [], files)).filter(it => it.includes(" react")); + const off = (name: string) => reactProblems(`${correctness}[lint.rules]\n"${name}/*" = "off"\n`); + expect( + await Promise.all([reactProblems(correctness), off("react"), off("react-hooks"), off("react_hooks")]), + ).toEqual([[hooksProblem, reactProblem], [hooksProblem], [reactProblem], [reactProblem]]); }); test("react/* leaves react/jsx-uses-react on, which only keeps no-unused-vars quiet about React", async () => { @@ -1343,9 +1447,9 @@ describe.concurrent(`"plugin/*" = "off" turns off every rule of a plugin`, () => export default { meta: { name: "demo" }, rules: { one: rule, two: rule } };\n`; const files = { "a.js": "export {};\n", "demo.js": plugin }; const load = `[lint]\nplugins = ["./demo.js"]\nignorePatterns = ["demo.js"]\n[lint.rules]\n`; - const named = `${load}"demo/one" = "error"\n"demo/two" = "error"\n`; - expect(await found(named, [], files)).toEqual(["a.js:1 demo/one", "a.js:1 demo/two"]); - expect(await found(named, ["--rule", "demo/*: off"], files)).toEqual([]); + const listedByName = `${load}"demo/one" = "error"\n"demo/two" = "error"\n`; + expect(await found(listedByName, [], files)).toEqual(["a.js:1 demo/one", "a.js:1 demo/two"]); + expect(await found(listedByName, ["--rule", "demo/*: off"], files)).toEqual([]); expect(await found(`${load}"demo/*" = "off"\n"demo/two" = "error"\n`, [], files)).toEqual(["a.js:1 demo/two"]); }); @@ -1497,12 +1601,12 @@ describe.concurrent("[lint.settings]", () => { "eslint.config.mjs": `const rule = { create: context => ({ Program: node => context.report({ node, message: JSON.stringify(context.settings) }) }) }; export default [{ files: ["**/*.jsx"], languageOptions: { parserOptions: { ecmaFeatures: { jsx: true } } }, settings: { mine: 1 }, plugins: { p: { rules: { r: rule } } }, rules: { "p/r": "error" } }];\n`, }; - const [ofOxlint, ofESLint] = await Promise.all([ + const [withOxlint, withESLint] = await Promise.all([ lint({ ...files, ...oxlint }, ["-f", "unix"]), lint({ ...files, ...eslint }, ["-f", "unix"]), ]); - expect(ofOxlint.stdout).toContain("[Error/jsx-a11y(alt-text)]"); - expect(ofESLint.stdout).toContain(`{"mine":1,"jsx-a11y":{"components":{"Picture":"img"}}}`); + expect(withOxlint.stdout).toContain("[Error/jsx-a11y(alt-text)]"); + expect(withESLint.stdout).toContain(`{"mine":1,"jsx-a11y":{"components":{"Picture":"img"}}}`); }); }); @@ -1540,7 +1644,7 @@ describe.concurrent("unknown rules", () => { `Unknown rule "foo/bar-baz"\n To use a rule from an ESLint plugin, add the plugin to plugins in [lint]`, `Unknown rule "foo/bar-baz"\n To use a rule from an ESLint plugin, load the plugin with --plugin`, ], - // The plugin is there already. + // The plugin is already built in. [ "react/only-in-the-package", `Unknown rule "react/only-in-the-package"\n react is built in and has no rule of that name\n To run a rule of the package, load it under another name in [lint]: plugins = [{ name = "react-js", specifier = "eslint-plugin-react" }]`, @@ -1549,12 +1653,12 @@ describe.concurrent("unknown rules", () => { "typescript/only-in-the-package", `Unknown rule "typescript/only-in-the-package"\n typescript is built in and has no rule of that name\n To run a rule of the package, load it under another name in [lint]: plugins = [{ name = "typescript-js", specifier = "@typescript-eslint/eslint-plugin" }]`, ], - // No package has them. + // There's no package that could have these rules. ["bun/only-in-the-package", `Unknown rule "bun/only-in-the-package"`], ["oxc/only-in-the-package", `Unknown rule "oxc/only-in-the-package"`], ["eslint/only-in-the-package", `Unknown rule "eslint/only-in-the-package"`], ["perfectly-fine", `Unknown rule "perfectly-fine"`], - // Rules that bun lint leaves out on purpose. + // Rules that bun lint deliberately doesn't implement. ["indent", `"indent" is a formatting rule\n bun fmt does that`], ["eslint/semi", `"eslint/semi" is a formatting rule\n bun fmt does that`], ["@stylistic/quotes", `"@stylistic/quotes" is a formatting rule\n bun fmt does that`], @@ -1566,24 +1670,33 @@ describe.concurrent("unknown rules", () => { "vue/no-dupe-keys", `"vue/no-dupe-keys" is not supported\n bun lint has no vue rules. To run eslint-plugin-vue, add it to plugins in [lint]`, ], + // --rules lists these, but only an ESLint config can specify which files are JSON or Markdown. + [ + "json/no-duplicate-keys", + `"json/no-duplicate-keys" needs an ESLint config\n Set language: "json/json" for the files in an eslint.config.js`, + ], + [ + "markdown/no-empty-links", + `"markdown/no-empty-links" needs an ESLint config\n Set language: "markdown/commonmark" for the files in an eslint.config.js`, + ], ]; - test.each(cases)("%s is rejected", async (written, said, saidToFlag = said) => { + test.each(cases)("%s is rejected", async (key, message, flagMessage = message) => { const [inFile, byFlag] = await Promise.all([ lint({ ...source, - "bunfig.toml": `[lint.rules]\n"no-debugger" = "error"\n"${written}" = "error"\n`, + "bunfig.toml": `[lint.rules]\n"no-debugger" = "error"\n"${key}" = "error"\n`, }), - lint(source, ["--rule", JSON.stringify({ [written]: "error" })]), + lint(source, ["--rule", JSON.stringify({ [key]: "error" })]), ]); expect(inFile).toEqual({ stdout: "", - stderr: `3 | "${written}" = "error"\n ^\nerror: ${said}\n at bunfig.toml:3:1\n`, + stderr: `3 | "${key}" = "error"\n ^\nerror: ${message}\n at bunfig.toml:3:1\n`, exitCode: 2, }); expect(byFlag).toEqual({ stdout: "", - stderr: `error: ${saidToFlag}\n`, + stderr: `error: ${flagMessage}\n`, exitCode: 2, }); }); @@ -1676,14 +1789,14 @@ describe.concurrent("invalid rule settings", () => { [`"eqeqeq" = 3`, 12, `3 is not a valid severity for eqeqeq\n Expected "off", "warn", or "error"`], ]; - test.each(cases.filter(it => it[2] !== ""))("%s is rejected", async (line, column, said) => { + test.each(cases.filter(it => it[2] !== ""))("%s is rejected", async (line, column, message) => { const { stdout, stderr, exitCode } = await lint({ ...source, "bunfig.toml": `[lint.rules]\n${line}\n`, }); expect({ stdout, stderr, exitCode }).toEqual({ stdout: "", - stderr: `2 | ${line}\n${" ".repeat(column + 3)}^\nerror: ${said}\n at bunfig.toml:2:${column}\n`, + stderr: `2 | ${line}\n${" ".repeat(column + 3)}^\nerror: ${message}\n at bunfig.toml:2:${column}\n`, exitCode: 2, }); }); @@ -1694,9 +1807,9 @@ describe.concurrent("invalid rule settings", () => { lint(source, ["--rule", `eqeqeq: eror`]), lint({ ...source, ...bunfig({ eqeqeq: ["error", "smart"] }) }, ["--rule", `eqeqeq: [error, smrt]`]), ]); - const said = `error: "smrt" is not a valid option for eqeqeq\n Expected "always", "smart", or "allow-null"\n`; - expect(options).toEqual({ stdout: "", stderr: said, exitCode: 2 }); - expect(overBunfig).toEqual({ stdout: "", stderr: said, exitCode: 2 }); + const expectedError = `error: "smrt" is not a valid option for eqeqeq\n Expected "always", "smart", or "allow-null"\n`; + expect(options).toEqual({ stdout: "", stderr: expectedError, exitCode: 2 }); + expect(overBunfig).toEqual({ stdout: "", stderr: expectedError, exitCode: 2 }); expect(severity).toEqual({ stdout: "", stderr: `error: "eror" is not a valid severity for eqeqeq\n Expected "off", "warn", or "error"\n`, @@ -1704,6 +1817,25 @@ describe.concurrent("invalid rule settings", () => { }); }); + test.each(["eqeqeq:", "eqeqeq: ", "no-var: error, eqeqeq:", "eqeqeq: [, smart]", "", " ", "{}"])( + "--rule %j is rejected: it has a rule without a severity, or no rule", + async value => { + expect(await lint({ ...source, ...bunfig({ eqeqeq: "error" }) }, ["--rule", value])).toEqual({ + stdout: "", + stderr: `error: Invalid value for option 'rule' - expected type Object, received value: ${value}.\nnote: run 'bun lint --help' for more information\n`, + exitCode: 2, + }); + }, + ); + + test("the error for a bad --rule doesn't point at the bunfig.toml line that sets the same rule", async () => { + expect(await lint({ ...source, ...bunfig({ eqeqeq: "warn" }) }, ["--rule", "eqeqeq: null"])).toEqual({ + stdout: "", + stderr: `error: null is not a valid severity for eqeqeq\n Expected "off", "warn", or "error"\n`, + exitCode: 2, + }); + }); + test("options aren't validated when the rule is off", async () => { const { stderr, exitCode } = await lint({ ...source, ...bunfig({ eqeqeq: ["off", "smrt"] }) }, ["-f", "json"]); expect(stderr).not.toContain("error:"); @@ -1739,6 +1871,14 @@ describe.concurrent("ESLint and oxlint configs keep their own behavior", () => { expect(problems(inLegacy.stdout)).toEqual(["a.js:2 no-debugger", "a.js:4 no-debugger"]); }); + test("with an ESLint config, eslint/no-var in a disable comment isn't treated as no-var", async () => { + const code = + "var a = 1; // eslint-disable-line eslint/no-var\nvar b = 2; // eslint-disable-line no-var\nexport { a, b };\n"; + const { stdout } = await lint({ "a.js": code, ...flat({ "no-var": "error" }) }, ["-f", "json"]); + expect(problems(stdout)).toEqual(["a.js:1 eslint/no-var", "a.js:1 no-var"]); + expect(stdout).toContain("Definition for rule 'eslint/no-var' was not found."); + }); + test("an ESLint config still has to declare its plugins", async () => { const [inFile, inBunfig] = await Promise.all([ lint({ ...source, ...flat({ "unicorn/no-null": "error" }) }), @@ -1755,7 +1895,7 @@ describe.concurrent("ESLint and oxlint configs keep their own behavior", () => { } }); - test("invalid options print ESLint's message under a line that names the file", async () => { + test("invalid options print ESLint's message under a line with the config file's name", async () => { const words = `Key "rules": Key "eqeqeq":\n\tValue "smrt" should be equal to one of the allowed values.`; const wrong = { eqeqeq: ["error", "smrt"] as Setting }; const legacy = { diff --git a/test/cli/lint/oracle/driver/generate-deprecated.mjs b/test/cli/lint/oracle/driver/generate-deprecated.mjs index 25b28b9e9fa9..4ad5e87282a2 100644 --- a/test/cli/lint/oracle/driver/generate-deprecated.mjs +++ b/test/cli/lint/oracle/driver/generate-deprecated.mjs @@ -1,4 +1,5 @@ -// Writes src/lint/linter/deprecated_data.rs and deprecated.txt: what ESLint's `usedDeprecatedRules` says about each deprecated rule. +// Writes src/lint/linter/deprecated_data.rs and deprecated.txt: ESLint's `usedDeprecatedRules` entry for each +// deprecated rule. // // bun generate-deprecated.mjs // @@ -14,7 +15,7 @@ const core = require(path.join(eslintRoot, "lib/rules/index.js")); const typescript = require(path.join(typescriptRoot, "packages/eslint-plugin/dist/index.js")).rules; const rulesOf = name => Object.entries(require(path.join(packages, `eslint-plugin-${name}`)).rules); -// `getDeprecatedRuleReplacements` of lib/eslint/eslint.js +// `getDeprecatedRuleReplacements` in lib/eslint/eslint.js function replacements(meta) { if (typeof meta.deprecated !== "object") return meta.replacedBy || []; const { replacedBy } = meta.deprecated; @@ -27,7 +28,7 @@ function replacements(meta) { }); } -// The rules about layout, which `bun lint` does not have: what @stylistic/eslint-plugin has taken over, and this one. +// The layout rules, which `bun lint` doesn't have: the ones @stylistic/eslint-plugin took over, plus this one. const isAboutLayout = (id, replacedBy) => id === "react/jsx-space-before-closing" || (replacedBy.length > 0 && replacedBy.every(it => it.startsWith("@stylistic/"))); @@ -49,7 +50,7 @@ for (const [prefix, rules] of [ entries.sort((a, b) => (a[0] < b[0] ? -1 : 1)); const tables = [ - ["DEPRECATED", "ESLint's, and those of the plugins that are built in, in whole or in part. Sorted by name.", it => !it[2]], + ["DEPRECATED", "The deprecated rules of ESLint and of the plugins that are fully or partly built in. Sorted by name.", it => !it[2]], ["FORMATTING", "Rules about code layout, sorted by name. Bun doesn't have them: `bun fmt` does their work.", it => it[2]], ].map(([name, comment, isMeant]) => { const rows = entries.flatMap((it, line) => (isMeant(it) ? [` (${JSON.stringify(it[0])}, ${line}),\n`] : [])); @@ -60,9 +61,9 @@ writeFileSync( path.join(directory, "deprecated_data.rs"), `//! Generated by test/cli/lint/oracle/driver/generate-deprecated.mjs, together with \`deprecated.txt\`. -/// A deprecated rule's name, and the line of \`deprecated.txt\` (from 0) that is about it. +/// A deprecated rule's name and its 0-based line in \`deprecated.txt\`. pub type Deprecated = (&'static str, u16); ${tables.join("")}`, ); -// One line per rule: what follows `ruleId` in ESLint's `DeprecatedRuleInfo`, as JSON. +// One line per rule: the fields after `ruleId` in ESLint's `DeprecatedRuleInfo`, as JSON. writeFileSync(path.join(directory, "deprecated.txt"), entries.map(it => `${it[1]}\n`).join("")); diff --git a/test/cli/lint/oracle/jsplugins/parsers/compare.ts b/test/cli/lint/oracle/jsplugins/parsers/compare.ts index 5cdd19df6292..9e0fd4542b35 100644 --- a/test/cli/lint/oracle/jsplugins/parsers/compare.ts +++ b/test/cli/lint/oracle/jsplugins/parsers/compare.ts @@ -1,11 +1,12 @@ -// Real ESLint against `bun lint` on files that need a parser, a language or a processor of a plugin. +// Compares `bun lint` with real ESLint on files that need a plugin's parser, language or processor. // // bun compare.ts [--fix] [--show=3] [--threads=8] -- // -// `` is next to a `node_modules` that has `eslint` (or `ESLINT_DIR` is a checkout of it) and the plugins. Both run in `` with `-c -f json`, -// with `--fix` also `--fix-dry-run`. Compared for each file: every message and every suppressed message as JSON (ruleId, severity, -// message, line, column, endLine, endColumn, messageId, fix, suggestions, suppressions), `output`, the counts and -// `usedDeprecatedRules`. Prints one line: how many files are identical, and what each run took. +// `` has to be next to a `node_modules` with the plugins and `eslint` (or set `ESLINT_DIR` to an ESLint +// checkout). Both tools run in `` with `-c -f json`, plus `--fix-dry-run` if `--fix` is passed. For +// each file it compares every message and suppressed message as JSON (ruleId, severity, message, line, column, endLine, +// endColumn, messageId, fix, suggestions, suppressions), `output`, the counts and `usedDeprecatedRules`. The last line +// it prints has the number of identical files and each run's duration. import { dirname, join, relative } from "node:path"; @@ -54,7 +55,7 @@ for (const theirs of expected.results) { messages += theirs.messages.length; const mine = byPath.get(theirs.filePath); byPath.delete(theirs.filePath); - // The text of the file is in both. + // `source` is just the file's text. const strip = ({ source, ...rest }: any) => JSON.stringify(rest); if (mine !== undefined && strip(mine) === strip(theirs)) { same++; @@ -80,7 +81,8 @@ for (const theirs of expected.results) { console.log(` ours: ${JSON.stringify(b[index])?.slice(0, 400)}`); } } -for (const extra of [...byPath.keys()].slice(0, show)) console.log(`── ${relative(directory, extra)}\n only linted by us`); +for (const extra of [...byPath.keys()].slice(0, show)) + console.log(`── ${relative(directory, extra)}\n only linted by us`); const total = expected.results.length; console.log( `${same} / ${total} files identical${byPath.size ? `, ${byPath.size} only linted by us` : ""}, ${messages} messages, exit codes ${expected.code} / ${actual.code}, eslint ${expected.seconds} s, ours ${actual.seconds} s`, diff --git a/test/cli/lint/oracle/jsplugins/parsers/oxlint.ts b/test/cli/lint/oracle/jsplugins/parsers/oxlint.ts index ccaa866c880c..ffdd9665159e 100644 --- a/test/cli/lint/oracle/jsplugins/parsers/oxlint.ts +++ b/test/cli/lint/oracle/jsplugins/parsers/oxlint.ts @@ -1,9 +1,10 @@ -// oxlint against `bun lint` on the scripts in `.vue`, `.svelte` and `.astro` files. +// Compares `bun lint` with oxlint on the scripts in `.vue`, `.svelte` and `.astro` files. // // bun oxlint.ts [--show=3] -- // -// Both run in `` with the `.oxlintrc.json` below and `-f json` on the files that match ``. Compared for each -// file: the rule, the line and the column of every diagnostic. The texts are ESLint's here, and so is where a diagnostic ends. +// Both tools run in `` with the `.oxlintrc.json` below and `-f json` on the files that match ``. +// For each file it compares every diagnostic's rule, line and column. It doesn't compare message text or end positions, +// because `bun lint` uses ESLint's here. import { Glob } from "bun"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; @@ -45,7 +46,7 @@ const files = [...new Glob(pattern).scanSync({ cwd: directory })].filter(it => ! async function run(cmd: string[]) { const byFile = new Map(); const started = performance.now(); - // The command line has an end. + // Run in batches to stay under the command line length limit. for (let at = 0; at < files.length; at += 500) { const child = Bun.spawn({ cmd: [...cmd, "-c", configFile, "-f", "json", ...files.slice(at, at + 500)], diff --git a/test/cli/lint/oracle/jsplugins/parsers/run.ts b/test/cli/lint/oracle/jsplugins/parsers/run.ts index 1459dfc181a5..e654f915f5ff 100644 --- a/test/cli/lint/oracle/jsplugins/parsers/run.ts +++ b/test/cli/lint/oracle/jsplugins/parsers/run.ts @@ -1,15 +1,16 @@ -// All of `compare.ts`: each plugin on public projects and on the fixtures of its own repository. +// Runs `compare.ts` for each plugin, on public projects and on the fixtures in the plugin's own repository. // // bun run.ts [--fix] [--show=0] [--threads=8] [name ..] -- // -// ``: a directory where `bun add` has installed eslint, typescript@5, typescript-eslint, globals, @eslint/js and -// the packages that `configs/*.mjs` import. The configurations are copied there. ``: a directory with shallow clones, by the name -// of the repository, of what is listed below (`git clone --depth 1 https://github.com//`). +// `` is a directory where `bun add` has installed eslint, typescript@5, typescript-eslint, globals, +// @eslint/js and the packages that `configs/*.mjs` import. The configs are copied there. `` is a directory +// with a shallow clone of each repository listed below, named after the repository +// (`git clone --depth 1 https://github.com//`). import { copyFileSync, existsSync, readdirSync } from "node:fs"; import { join, resolve } from "node:path"; -// The configuration, the repository, the patterns. +// [config, repository, patterns] const cases: [string, string, string[]][] = [ ["vue", "element-plus/element-plus", ["**/*.vue"]], ["vue", "vuejs/eslint-plugin-vue", ["tests/fixtures/**/*.vue"]], diff --git a/test/cli/lint/oracle/plugins/oxlint/audit.json b/test/cli/lint/oracle/plugins/oxlint/audit.json index f31f91cbf65a..1e4c104ce105 100644 --- a/test/cli/lint/oracle/plugins/oxlint/audit.json +++ b/test/cli/lint/oracle/plugins/oxlint/audit.json @@ -1173,7 +1173,7 @@ "template-empty-string.ts": "// GO: no_unnecessary_type_conversion.go:66: ast.IsStringLiteral is false for a NoSubstitutionTemplateLiteral\n// RUST: no_unnecessary_type_conversion.rs:42: Expr::as_string (ast/expr.rs:479) decides by the byte at the start of the literal and then by kind_of_string\n// EXPECT: oxlint reports nothing; bun lint should report nothing (reports lines 5 to 7 if a template counts as a string)\nlet s = 'asdf';\nexport const a = s + ``;\nexport const b = `` + s;\ns += ``;\n", "tilde-numeric-enum.ts": "// GO: no_unnecessary_type_conversion.go:86: each part of a numeric enum has TypeFlagsNumberLiteral and literal.String() parses as an integer: `~~e` is reported\n// RUST: no_unnecessary_type_conversion.rs:239: is_type_flag_set(NUMBER_LITERAL) && ty.number_value() (types/ty.rs:367) of an enum literal type\n// EXPECT: oxlint reports lines 8, 9 and 10 and not 11; bun lint the same only if number_value() answers for enum literals\nenum E { A = 1, B = 2 }\nenum F { A = 1.5, B = 2 }\ndeclare const e: E;\ndeclare const f: F;\nexport const a = ~~e;\nexport const b = ~~E.A;\nexport const c = ~~F.B;\nexport const d = ~~f;\n", "tilde-unary-plus-literal.ts": "// GO: no_unnecessary_type_conversion.go:430: the type at `+1` / `-2` is the number literal type; reportUnaryPlus (372) also reports the `+`\n// RUST: no_unnecessary_type_conversion.rs:255: type_of_operand(argument) of a Unary operand; (UnOp::Plus, _) at 249 needs `+1` to be a Unary and not a folded number\n// EXPECT: oxlint reports line 4 twice (the `~~` and the `+`), line 5 once, line 6 once; bun lint the same unless the literal type or the node is lost\nexport const a = ~~+1;\nexport const b = ~~-2;\nexport const c = +1;\n", - "tsx-empty-string.tsx": "// GO: no_unnecessary_type_conversion.go:66: ast.IsStringLiteral with Text \"\" in a .tsx file as in any other\n// RUST: ast/expr.rs:483: as_string takes the slow path as_string_that_is_not_plainly_one whenever the file has JSX\n// EXPECT: oxlint reports lines 8, 9 and 10; bun lint should do the same\ndeclare global {\n namespace JSX { interface IntrinsicElements { div: { title?: string } } }\n}\ndeclare const s: string;\nexport const el =
    ;\nexport const a = '' + s;\nexport const b =
    ;\n", + "tsx-empty-string.tsx": "// GO: no_unnecessary_type_conversion.go:66: ast.IsStringLiteral with Text \"\" in a .tsx file as in any other\n// RUST: ast/expr.rs:483: as_string takes the slow path as_string_slow whenever the file has JSX\n// EXPECT: oxlint reports lines 8, 9 and 10; bun lint should do the same\ndeclare global {\n namespace JSX { interface IntrinsicElements { div: { title?: string } } }\n}\ndeclare const s: string;\nexport const el =
    ;\nexport const a = '' + s;\nexport const b =
    ;\n", "type-alias-named-builtin.ts": "// GO: no_unnecessary_type_conversion.go:313: the VALUE `Number` is the global one whatever types the module declares under that name\n// RUST: no_unnecessary_type_conversion.rs:222: scope().resolve_name resolves \"as a value or as a type\" (semantic/mod.rs:1140), so a type alias named Number hides the global\n// EXPECT: oxlint reports lines 6 and 7; bun lint reports nothing\ntype Number = number;\ninterface String { probe(): void }\nexport const a = Number(1);\nexport const b = String('asdf');\nexport type { Number, String };\n", "type-parameter-named-builtin.ts": "// GO: no_unnecessary_type_conversion.go:313: the value `Boolean` inside the function is the global BooleanConstructor; a type parameter is no value\n// RUST: no_unnecessary_type_conversion.rs:222: scope().resolve_name finds the type parameter `Boolean` of the enclosing function\n// EXPECT: oxlint reports line 5; bun lint reports nothing\nexport function f(flag: boolean, other: Boolean) {\n return [Boolean(flag), other] as const;\n}\n", "typeof-narrowed-constrained-generic.ts": "// GO: ts_eslint.go:85: the base constraint of `T & string` with T extends string | number is string: reported\n// RUST: no_unnecessary_type_conversion.rs:37: get_constrained_type_at_location must intersect the constraint of T with string\n// EXPECT: oxlint reports lines 6, 7 and 8 and probably not 11 (after the if x is still T, whose constraint is string | number); bun lint must agree\nexport function f(x: T) {\n if (typeof x === 'string') {\n const a = x + '';\n const b = String(x);\n const c = x.toString();\n return [a, b, c];\n }\n return [+x];\n}\n", @@ -1517,7 +1517,7 @@ "boolean-union.ts": "// GO: type_matches_specifier.go:526 / ts_api_utils.go:58: IsIntrinsicErrorType asks `IsIntrinsicType(t) && t.AsIntrinsicType()` even with no specifiers; `boolean` is a union that has the Boolean flag\n// RUST: type_or_value_specifier.rs:296: with no specifiers nothing is asked\n// EXPECT: oxlint reports \"object\" at line 6 (`flag`), unless the rule fails on this file; bun lint reports \"object\" at line 6\ndeclare const flag: boolean;\nfunction fail(): never {\n throw flag;\n}\nexport { fail };\n", "error-anonymous-class.ts": "// GO: builtin_symbol_likes.go:258: a class expression's symbol (`__class`) has SymbolFlagsClass, so its base types are asked\n// RUST: builtin_symbol_likes.rs:156: `symbol.has_flags(CLASS | INTERFACE)` for the symbol of an anonymous class expression\n// EXPECT: oxlint reports nothing; bun lint reports \"object\" at line 5 or 9 if the anonymous class has no symbol or no CLASS flag\nfunction first(): never {\n throw new (class extends Error {})(\"anonymous\");\n}\nconst Anonymous = class extends TypeError {};\nfunction second(): never {\n throw new Anonymous(\"assigned\");\n}\nexport { first, second };\n", "error-generic-indexed.ts": "// GO: builtin_symbol_likes.go:240: only TypeFlagsTypeParameter takes the constraint; an indexed access type `T[K]` has no symbol, the predicate answers False\n// RUST: builtin_symbol_likes.rs:145: only TYPE_PARAMETER; differs if the type at `t[k]` is already the constraint's property type\n// EXPECT: oxlint reports \"object\" at line 5 (`t[k]`) and nothing at line 8; bun lint the same unless it resolves T[K] to Error\nfunction pick(t: T, k: K): never {\n throw t[k];\n}\nfunction plain(t: T): never {\n throw t;\n}\nexport { pick, plain };\n", - "error-interface-two-bases.ts": "// GO: builtin_symbol_likes.go:260: every base type is recursed into, without a memo\n// RUST: builtin_symbol_likes.rs:165: with more than one base type the answer goes through BaseTypeAnswers::get_or_ask\n// EXPECT: oxlint reports nothing; bun lint reports \"object\" at line 16 if the memo answers false for the second base\ninterface Tagged {\n tag: string;\n}\ninterface Coded extends Error {\n code: number;\n}\ninterface Named extends Tagged {\n label: string;\n}\ninterface Both extends Named, Tagged, Coded {}\ndeclare const both: Both;\nfunction fail(): never {\n throw both;\n}\nexport { fail };\n", + "error-interface-two-bases.ts": "// GO: builtin_symbol_likes.go:260: every base type is recursed into, without a memo\n// RUST: builtin_symbol_likes.rs:165: with more than one base type the answer goes through BaseTypeAnswers::get_or_compute\n// EXPECT: oxlint reports nothing; bun lint reports \"object\" at line 16 if the memo answers false for the second base\ninterface Tagged {\n tag: string;\n}\ninterface Coded extends Error {\n code: number;\n}\ninterface Named extends Tagged {\n label: string;\n}\ninterface Both extends Named, Tagged, Coded {}\ndeclare const both: Both;\nfunction fail(): never {\n throw both;\n}\nexport { fail };\n", "error-merged-interface-base.ts": "// GO: builtin_symbol_likes.go:259-260: `getBaseTypes(getDeclaredTypeOfSymbol(symbol))` of a class merged with an interface that extends Error includes Error\n// RUST: builtin_symbol_likes.rs:159: `symbol.get_declared_type().get_base_types()`\n// EXPECT: oxlint reports nothing; bun lint reports \"object\" at line 10 if the base types of the merged interface declaration are missing\nclass Merged {\n constructor(public code: number) {}\n}\ninterface Merged extends Error {}\ndeclare const merged: Merged;\nfunction fail(): never {\n throw merged;\n}\nexport { fail };\n", "error-this-type.ts": "// GO: builtin_symbol_likes.go:240: the type of `this` is a type parameter; `getBaseConstraintOfType` gives the class, whose base type is Error\n// RUST: builtin_symbol_likes.rs:145: `flags.contains(TYPE_PARAMETER)` and `get_base_constraint_of_type()` for the type at `this`\n// EXPECT: oxlint reports \"object\" only at line 11 (`this` of a class that does not extend Error); bun lint reports line 6 too if the this type has no constraint\nclass Retryable extends Error {\n rethrow(): never {\n throw this;\n }\n}\nclass Plain {\n rethrow(): never {\n throw this;\n }\n}\nexport { Retryable, Plain };\n", "optional-param-union-undefined.ts": "// GO: only_throw_error.go:133: IsTypeFlagSet(t, Undefined) looks at the flags of the type itself; `Error | undefined` is a union, so the message is \"object\" on the expression\n// RUST: only_throw_error.rs:81: `ty.has_flags(TypeFlags::UNDEFINED)`; differs if a union's flags include those of its constituents\n// EXPECT: oxlint reports \"Expected an error object to be thrown.\" at line 5 on `problem`; bun lint the same, or \"Do not throw undefined.\" on the statement\nfunction fail(problem?: Error): never {\n throw problem;\n}\nexport { fail };\n", diff --git a/test/cli/lint/oracle/plugins/oxlint/compare-fixes.ts b/test/cli/lint/oracle/plugins/oxlint/compare-fixes.ts index 41a4c1e781bc..9ad8415a263a 100644 --- a/test/cli/lint/oracle/plugins/oxlint/compare-fixes.ts +++ b/test/cli/lint/oracle/plugins/oxlint/compare-fixes.ts @@ -1,8 +1,8 @@ -// Compares what `bun lint` and oxlint make of the files of fixes.ts with each of the flags. +// Compares how `bun lint` and oxlint fix the files in fixes.ts, with each set of fix flags. // // BUN_LINT="bun lint" OXLINT_BIN= OXLINT_TSGOLINT_PATH= bun compare-fixes.ts [--record] // -// Without OXLINT_BIN, what oxlint makes of them is read from fixes.expected.json, which `--record` writes. +// Without OXLINT_BIN, oxlint's output is read from fixes.expected.json, which `--record` writes. import { spawnSync } from "node:child_process"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; @@ -17,7 +17,7 @@ const expectedPath = join(import.meta.dir, "fixes.expected.json"); type Texts = Record>; -/** The texts of the files after a run with each of the sets of flags. */ +/** Returns each file's text after a run with each set of flags. */ function run(command: string, before: string[]): Texts { const texts: Texts = {}; for (const [name, flags] of Object.entries(flagSets)) { @@ -25,7 +25,9 @@ function run(command: string, before: string[]): Texts { const cwd = mkdtempSync(join(tmpdir(), "oxlint-fixes-")); try { writeFileSync(join(cwd, ".oxlintrc.json"), JSON.stringify({ categories: { correctness: "off" } })); - const some = cases.map((it, index) => ({ it, directory: directoryOf(index) })).filter(({ it }) => !!it.typed === typed); + const some = cases + .map((it, index) => ({ it, directory: directoryOf(index) })) + .filter(({ it }) => !!it.typed === typed); for (const { it, directory } of some) { for (const [path, text] of Object.entries(filesOf(it))) { mkdirSync(dirname(join(cwd, directory, path)), { recursive: true }); @@ -33,7 +35,8 @@ function run(command: string, before: string[]): Texts { } } spawnSync(command, [...before, ...flags, ...(typed ? ["--type-aware"] : []), "."], { cwd, encoding: "utf8" }); - for (const { it, directory } of some) (texts[directory] ??= {})[name] = readFileSync(join(cwd, directory, it.file), "utf8"); + for (const { it, directory } of some) + (texts[directory] ??= {})[name] = readFileSync(join(cwd, directory, it.file), "utf8"); } finally { rmSync(cwd, { recursive: true, force: true }); } diff --git a/test/cli/lint/oracle/plugins/oxlint/compare-options.ts b/test/cli/lint/oracle/plugins/oxlint/compare-options.ts index 093c7caec352..131ae5091609 100644 --- a/test/cli/lint/oracle/plugins/oxlint/compare-options.ts +++ b/test/cli/lint/oracle/plugins/oxlint/compare-options.ts @@ -1,10 +1,11 @@ -// The options that oxlint accepts for a rule are accepted by `bun lint` beside an .oxlintrc.json: a configuration that is refused ends the run. +// Checks that `bun lint` with an .oxlintrc.json accepts every rule option that oxlint accepts. A rejected config ends +// the run, so this matters. // // BUN_LINT="bun lint" bun compare-options.ts // OXLINT_BIN= bun compare-options.ts --record [--from=] // -// options.json has, for each rule that both have, the options that oxlint accepts. `--record` asks oxlint about each of them again, one run -// for each, and with `--from` about all options in the test cases too. +// options.json lists the options oxlint accepts for each rule that both tools have. `--record` tries each of them on +// oxlint again, one run per option set. With `--from` it also tries every option set in the test cases. import { spawnSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; @@ -15,7 +16,7 @@ type Recorded = Record; const path = join(import.meta.dir, "options.json"); const recorded: Recorded = JSON.parse(readFileSync(path, "utf8")); -/** Configurations that have all accepted options between them: the first of each rule, the second of each rule that has two, .. */ +/** Returns configs that together cover all the accepted options. Config `n` has every rule's `n`-th option set. */ export function configurations(all: Recorded): Record[] { const most = Math.max(...Object.values(all).map(it => it.length)); return Array.from({ length: most }, (_, index) => ({ @@ -29,8 +30,8 @@ export function configurations(all: Recorded): Record[] { })); } -/** What the tool says if it refuses one of the configurations, each of which has a directory of its own. */ -function refusal(command: string[], configs: object[]): string | undefined { +/** Runs the tool with each config in its own directory. Returns its error output if it rejects one of them. */ +function rejectionMessage(command: string[], configs: object[]): string | undefined { const cwd = mkdtempSync(join(tmpdir(), "oxlint-options-")); try { writeFileSync(join(cwd, ".oxlintrc.json"), JSON.stringify({ categories: { correctness: "off" } })); @@ -39,7 +40,10 @@ function refusal(command: string[], configs: object[]): string | undefined { writeFileSync(join(cwd, String(index), ".oxlintrc.json"), JSON.stringify(config)); writeFileSync(join(cwd, String(index), "a.ts"), "export {};\n"); }); - const { stdout, stderr } = spawnSync(command[0], [...command.slice(1), "-f", "json", "."], { cwd, encoding: "utf8" }); + const { stdout, stderr } = spawnSync(command[0], [...command.slice(1), "-f", "json", "."], { + cwd, + encoding: "utf8", + }); return stdout.includes('"number_of_files"') ? undefined : (stderr || stdout).trim(); } finally { rmSync(cwd, { recursive: true, force: true }); @@ -66,17 +70,20 @@ if (import.meta.main) { if (it.options?.length) candidates.set(JSON.stringify(it.options), it.options); } } - next[rule] = [...candidates.values()].filter(it => refusal([process.env.OXLINT_BIN!], [one(rule, it)]) === undefined); + next[rule] = [...candidates.values()].filter( + it => rejectionMessage([process.env.OXLINT_BIN!], [one(rule, it)]) === undefined, + ); } writeFileSync(path, JSON.stringify(next, null, 1) + "\n"); } else { const ours = (process.env.BUN_LINT ?? "bun lint").split(" "); let count = 0; - if (refusal(ours, configurations(recorded)) !== undefined) { + if (rejectionMessage(ours, configurations(recorded)) !== undefined) { for (const [rule, accepted] of Object.entries(recorded)) { for (const options of accepted) { - const message = refusal(ours, [one(rule, options)]); - if (message !== undefined) console.log(`${++count}. ${rule} ${JSON.stringify(options)}\n ${message.replace(/\s+/g, " ")}`); + const message = rejectionMessage(ours, [one(rule, options)]); + if (message !== undefined) + console.log(`${++count}. ${rule} ${JSON.stringify(options)}\n ${message.replace(/\s+/g, " ")}`); } } } diff --git a/test/cli/lint/oracle/plugins/oxlint/compare.ts b/test/cli/lint/oracle/plugins/oxlint/compare.ts index a5de0ceff2d3..31c3a4afad3e 100644 --- a/test/cli/lint/oracle/plugins/oxlint/compare.ts +++ b/test/cli/lint/oracle/plugins/oxlint/compare.ts @@ -1,11 +1,12 @@ -// Compares `bun lint` with oxlint on small projects, for the rules of plugins whose port in oxlint differs from the plugin: with a -// configuration of oxlint, oxlint is what counts. +// Compares `bun lint` with oxlint on small projects, for plugin rules whose oxlint port behaves differently from the +// plugin. With an oxlint config, `bun lint` follows oxlint. // // BUN_LINT="bun lint" OXLINT_BIN= OXLINT_TSGOLINT_PATH= bun compare.ts [--record] [name..] // -// Without OXLINT_BIN, what oxlint reports is read from expected.json, which `--record` writes: from oxlint 1.87.0 with tsgolint 7.0.2003. -// A report is `file:line:column+length rule`, and is there as often as it is made: two reports can begin at one place. -// labels.json has, in the same way, `file rule line:column+length "text" | ..` for each report for which oxlint marks more than one place or says something there. +// Without OXLINT_BIN, oxlint's reports are read from expected.json, which `--record` writes. It was recorded with +// oxlint 1.87.0 and tsgolint 7.0.2003. A report is `file:line:column+length rule`. Duplicates are kept, because two +// reports can start at the same position. labels.json likewise has `file rule line:column+length "text" | ..` for each +// report with more than one label or with label text. import { spawnSync } from "node:child_process"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; @@ -19,13 +20,23 @@ const expectedPath = join(import.meta.dir, "expected.json"); const labelsPath = join(import.meta.dir, "labels.json"); const oxlint = process.env.OXLINT_BIN; const [ours, ...oursArgs] = (process.env.BUN_LINT ?? "bun lint").split(" "); -// With names, `--record` leaves what is recorded for the other projects as it is. -const expected: Record = oxlint && names.length === 0 ? {} : JSON.parse(readFileSync(expectedPath, "utf8")); -const expectedLabels: Record = oxlint && names.length === 0 ? {} : JSON.parse(readFileSync(labelsPath, "utf8")); +// With names, `--record` keeps the other projects' recordings. +const expected: Record = + oxlint && names.length === 0 ? {} : JSON.parse(readFileSync(expectedPath, "utf8")); +const expectedLabels: Record = + oxlint && names.length === 0 ? {} : JSON.parse(readFileSync(labelsPath, "utf8")); -/** `file:line:column+length rule` of each diagnostic, at its first label, which is what oxlint prints; and all the labels of those that have more. */ +/** + * `reports` has `file:line:column+length rule` for each diagnostic, at its first label, which is where oxlint prints + * it. `labels` has all the labels of the diagnostics that `labelsOf` covers. + */ function run(command: string, before: string[], cwd: string): { reports: string[]; labels: string[] } { - const { stdout, stderr, error } = spawnSync(command, [...before, "-f", "json", "."], { cwd, encoding: "utf8", timeout: 60_000, maxBuffer: 1 << 28 }); + const { stdout, stderr, error } = spawnSync(command, [...before, "-f", "json", "."], { + cwd, + encoding: "utf8", + timeout: 60_000, + maxBuffer: 1 << 28, + }); if (error) throw new Error(`${command} ${before.join(" ")}: ${error.message}`); let diagnostics; try { @@ -33,19 +44,25 @@ function run(command: string, before: string[], cwd: string): { reports: string[ } catch { throw new Error(`${command}: ${stderr || stdout}`); } - // A file that oxlint cannot read says nothing about a rule. + // A file that oxlint can't parse doesn't test any rule, so point it out. for (const it of diagnostics) { - // `TS(2391)` is an error of oxc's semantic analysis. - if (!/^[a-z]/.test(it.code ?? "") && command === oxlint && !cwd.includes("syntax-error")) console.log(`NOT READ by oxlint: ${cwd} ${it.filename}: ${it.message}`); + // `TS(2391)` is an error from oxc's semantic analysis. + if (!/^[a-z]/.test(it.code ?? "") && command === oxlint && !cwd.includes("syntax-error")) + console.log(`NOT READ by oxlint: ${cwd} ${it.filename}: ${it.message}`); } const found = diagnostics.filter((it: any) => it.code); return { - reports: found.map((it: any) => `${it.filename}:${it.labels[0].span.line}:${it.labels[0].span.column}+${it.labels[0].span.length} ${it.code}`).sort(), + reports: found + .map( + (it: any) => + `${it.filename}:${it.labels[0].span.line}:${it.labels[0].span.column}+${it.labels[0].span.length} ${it.code}`, + ) + .sort(), labels: found.flatMap((it: any) => (labelsOf(it) ? [`${it.filename} ${it.code} ${labelsOf(it)}`] : [])).sort(), }; } -/** What is in `some` more often than in `others`. */ +/** Returns the items that occur more often in `some` than in `others`. */ function more(some: string[], others: string[]): string[] { const left = new Map(); for (const it of others) left.set(it, (left.get(it) ?? 0) + 1); @@ -61,9 +78,19 @@ for (const project of projects) { if (names.length > 0 && !names.includes(project.name)) continue; const cwd = mkdtempSync(join(tmpdir(), `oxlint-${project.name.replaceAll("/", "-")}-`)); try { - const tsconfig = project.typed ? { "tsconfig.json": JSON.stringify({ compilerOptions: { strict: true, target: "esnext", module: "esnext", lib: ["esnext", "dom"] } }) } : {}; + const tsconfig = project.typed + ? { + "tsconfig.json": JSON.stringify({ + compilerOptions: { strict: true, target: "esnext", module: "esnext", lib: ["esnext", "dom"] }, + }), + } + : {}; const typed = project.typed ? ["--type-aware"] : []; - for (const [path, text] of Object.entries({ ".oxlintrc.json": JSON.stringify(project.config), ...tsconfig, ...project.files })) { + for (const [path, text] of Object.entries({ + ".oxlintrc.json": JSON.stringify(project.config), + ...tsconfig, + ...project.files, + })) { mkdirSync(dirname(join(cwd, path)), { recursive: true }); writeFileSync(join(cwd, path), text); } @@ -74,12 +101,12 @@ for (const project of projects) { if (oxlint) { const { reports, labels } = run(oxlint, typed, cwd); expected[project.name] = reports; - // Only the projects that have some are in the file. + // The file only lists projects that have labels. delete expectedLabels[project.name]; if (labels.length > 0) expectedLabels[project.name] = labels; } const wanted = [...(expected[project.name] ?? []), ...(expectedLabels[project.name] ?? [])]; - // With one thread, with fewer threads than files, and with as many as there are. + // One thread, fewer threads than files, and the default. for (const threads of project.name.startsWith("no-cycle/") ? ["--threads=1", "--threads=2", ""] : [""]) { const { reports, labels } = run(ours, [...oursArgs, ...typed, ...(threads ? [threads] : [])], cwd); const actual = [...reports, ...labels]; diff --git a/test/cli/lint/oracle/plugins/oxlint/fixes.ts b/test/cli/lint/oracle/plugins/oxlint/fixes.ts index dc04bec7329c..94c1daf32b5c 100644 --- a/test/cli/lint/oracle/plugins/oxlint/fixes.ts +++ b/test/cli/lint/oracle/plugins/oxlint/fixes.ts @@ -1,20 +1,21 @@ -// What `--fix`, `--fix-suggestions` and `--fix-dangerously` make of a file, rule by rule: with a configuration of oxlint they change -// what oxlint changes. `oxlint --rules -f json` names the most dangerous kind of fix that a rule can have, which says nothing about a -// report, and for the rules that need types it is wrong: so each case was tried. +// Inputs for checking, rule by rule, what `--fix`, `--fix-suggestions` and `--fix-dangerously` do to a file. With an +// oxlint config they make the same changes as oxlint. `oxlint --rules -f json` only lists the most dangerous kind of +// fix a rule can have, not the kind each report gets, and it's wrong for the type-aware rules, so every case here was +// run through oxlint. export interface Case { - /** As it is written in `rules`. */ + /** The rule's name as written in the config's `rules`. */ rule: string; - /** The name of the file, which says what language it is. */ + /** The filename. Its extension sets the language. */ file: string; text: string; - /** It is linted with `--type-aware`. */ + /** Lint with `--type-aware`. */ typed?: boolean; - /** The options of the rule. */ + /** The rule's options. */ options?: object; - /** The other rules that are on. */ + /** Other rules to enable. */ also?: string[]; - /** More of them in the `tsconfig.json`. */ + /** Extra `compilerOptions` for the `tsconfig.json`. */ compilerOptions?: object; } @@ -25,26 +26,26 @@ const ts = (rule: string, text: string): Case => ({ rule: `typescript/${rule}`, const typed = (rule: string, text: string): Case => ({ ...ts(rule, text), typed: true }); export const cases: Case[] = [ - // The rule of oxlint has no fix of any kind. + // oxlint's rule has no fix of any kind. js("no-lonely-if", "if (a) {} else { if (b) {} }"), js("no-extra-bind", "a = function () {}.bind(b);"), js("no-useless-return", "function a() { return; }"), js("logical-assignment-operators", "a = a || b;"), ts("method-signature-style", "interface A { b(): void }"), ts("no-empty-interface", "interface A extends B {}"), - // It has suggestions only. + // oxlint's rule only has suggestions. ts("no-inferrable-types", "let a: number = 1;"), js("no-debugger", "debugger;"), js("no-console", "console.log(1);"), typed("non-nullable-type-assertion-style", "declare const a: string | null; export const b = a as string;"), - // Its fix is dangerous. + // oxlint's fix is dangerous. js("no-unneeded-ternary", "a = b ? true : false;"), js("no-unneeded-ternary", "a = b ? b : c;"), js("require-await", "async function a() { b(); }"), js("radix", "parseInt(a);"), js("no-eq-null", "a == null;"), ts("no-extraneous-class", "class A {}"), - // It depends on the report. + // The kind of fix depends on the report. js("no-extra-boolean-cast", "if (!!a) {}"), js("no-extra-boolean-cast", "if (Boolean(a)) {}"), js("eqeqeq", "a == 'b'; typeof a == 'c'; a == b;"), @@ -54,7 +55,7 @@ export const cases: Case[] = [ js("no-compare-neg-zero", "a === -0;"), ts("explicit-member-accessibility", "class A { b = 1 }"), ts("prefer-as-const", "let a: 'b' = 'b'; let c = 'd' as 'd';"), - // It has a fix. + // oxlint's rule has a safe fix. js("no-div-regex", "a = /=b/;"), js("no-var", "var a = 1; a;"), js("no-var", "var a = 1; a = 2;"), @@ -66,7 +67,7 @@ export const cases: Case[] = [ js("func-names", "a = function () {};"), js("sort-keys", "a = { c: 1, b: 2 };"), js("no-negated-condition", "if (!a) { b(); } else { c(); }"), - // tsgolint fixes what the executable says has no fix. + // tsgolint fixes these, although `oxlint --rules` says they have no fix. typed("dot-notation", `declare const a: { b: 1 }; a["b"];`), typed("prefer-readonly", "export class A { private b = 1; c() { return this.b; } }"), typed("prefer-string-starts-ends-with", `declare const a: string; a[0] === "b";`), @@ -75,16 +76,28 @@ export const cases: Case[] = [ typed("consistent-type-exports", "type A = 1; export { A };"), typed("no-unnecessary-qualifier", "namespace A { export type B = 1; const c: A.B = 1; }"), typed("prefer-includes", `declare const a: string[]; a.indexOf("b") !== -1;`), - // The text that its fix leaves. + // The exact text that oxlint's fix produces. js("no-else-return", "export function f(a) {\n if (a) {\n return 1;\n } else {\n return 2;\n }\n}"), js("no-else-return", "export function g(a) {\n if (a) return 1; else return 2;\n}"), js("no-else-return", "export function h(a) {\n if (a) return 1\n else return 2\n}"), js("no-else-return", "export function i(a) {\n if (a) { return 1 } else { b() } c();\n}"), - js("no-else-return", "export function j(a) {\n if (a) {\n return 1;\n } else if (b) {\n return 2;\n } else {\n return 3;\n }\n}"), - js("no-else-return", "export function k(a) {\n if (a) {\n return 1;\n } else {\n if (b) {\n return 2;\n } else {\n return 3;\n }\n }\n}"), - js("no-else-return", "export function l(a) {\n if (a) { return 1; } else { x(); }\n if (a) { return 1; } else { y(); }\n}"), + js( + "no-else-return", + "export function j(a) {\n if (a) {\n return 1;\n } else if (b) {\n return 2;\n } else {\n return 3;\n }\n}", + ), + js( + "no-else-return", + "export function k(a) {\n if (a) {\n return 1;\n } else {\n if (b) {\n return 2;\n } else {\n return 3;\n }\n }\n}", + ), + js( + "no-else-return", + "export function l(a) {\n if (a) { return 1; } else { x(); }\n if (a) { return 1; } else { y(); }\n}", + ), js("no-else-return", "export function m(a) {\n let n = 1;\n if (a) { return n; } else { let n = 2; return n; }\n}"), - js("no-else-return", "export function o(a) {\n if (a) { return 1; } else { let p = 2; return p; }\n function q() { return p; }\n}"), + js( + "no-else-return", + "export function o(a) {\n if (a) { return 1; } else { let p = 2; return p; }\n function q() { return p; }\n}", + ), js("no-else-return", "export function r(a) {\n if (a) { return 1; } /* s */ else /* t */ { return 2; }\n}"), js("no-else-return", "export function w(a) {\n if (a) return 1\n else (b)\n}"), js("no-else-return", "export function x(a) {\n if (a) { return 1; } else { b }\n [c]\n}"), @@ -113,40 +126,46 @@ export const cases: Case[] = [ { rule: "no-var", file: "a.ts", text: "namespace N { export var a = 1; }\nN.a;\n" }, { rule: "no-var", file: "a.ts", text: "var a: number = 1; type B = typeof a;\n" }, { rule: "no-var", file: "a.ts", text: "class C { static { var a = 1; a; } }\n" }, - // What ESLint suggests, oxlint does. - js("preserve-caught-error", "try {} catch (e) { throw new Error(\"a\"); }"), + // ESLint only suggests these changes. oxlint applies them as fixes. + js("preserve-caught-error", 'try {} catch (e) { throw new Error("a"); }'), js("preserve-caught-error", "try {} catch (e) { throw new Error(); }"), js("preserve-caught-error", "try {} catch (e) { throw new Error; }"), - js("preserve-caught-error", "try {} catch (e) { throw new Error(\"a\", {}); }"), - js("preserve-caught-error", "try {} catch (e) { throw new Error(\"a\", { }); }"), - js("preserve-caught-error", "try {} catch (e) { throw new Error(\"a\", { b: 1 }); }"), - js("preserve-caught-error", "try {} catch (e) { throw new Error(\"a\", { b: 1, }); }"), - js("preserve-caught-error", "try {} catch (e) { throw new Error(\"a\", { cause: f }); }"), - js("preserve-caught-error", "try {} catch (e) { throw new Error(\"a\", { cause }); }"), - js("preserve-caught-error", "try {} catch (e) { throw new Error((\"a\")); }"), - js("preserve-caught-error", "try {} catch (e) { throw new Error(\"a\",); }"), + js("preserve-caught-error", 'try {} catch (e) { throw new Error("a", {}); }'), + js("preserve-caught-error", 'try {} catch (e) { throw new Error("a", { }); }'), + js("preserve-caught-error", 'try {} catch (e) { throw new Error("a", { b: 1 }); }'), + js("preserve-caught-error", 'try {} catch (e) { throw new Error("a", { b: 1, }); }'), + js("preserve-caught-error", 'try {} catch (e) { throw new Error("a", { cause: f }); }'), + js("preserve-caught-error", 'try {} catch (e) { throw new Error("a", { cause }); }'), + js("preserve-caught-error", 'try {} catch (e) { throw new Error(("a")); }'), + js("preserve-caught-error", 'try {} catch (e) { throw new Error("a",); }'), js("preserve-caught-error", "try {} catch (e) { throw new TypeError(`a${b}`); }"), js("preserve-caught-error", "try {} catch (e) { throw new AggregateError(); }"), js("preserve-caught-error", "try {} catch (e) { throw new AggregateError([]); }"), - js("preserve-caught-error", "try {} catch (e) { throw new AggregateError([], \"a\"); }"), - js("preserve-caught-error", "try {} catch (e) { throw new AggregateError([], \"a\", {}); }"), - js("preserve-caught-error", "try {} catch (e) { throw Error(\"a\"); }"), - js("preserve-caught-error", "try {} catch (e) { throw new Error(\"a\", o); }"), - js("preserve-caught-error", "try {} catch (e) { throw new RangeError(\"a\"); }"), - js("preserve-caught-error", "try {} catch ({ e }) { throw new Error(\"a\"); }"), - js("preserve-caught-error", "try {} catch (e) { if (a) { throw new Error(\"a\"); } else { throw new Error(\"b\"); } }"), - js("preserve-caught-error", "try {} catch (e) { throw new Error(\"a\", ({})); }"), + js("preserve-caught-error", 'try {} catch (e) { throw new AggregateError([], "a"); }'), + js("preserve-caught-error", 'try {} catch (e) { throw new AggregateError([], "a", {}); }'), + js("preserve-caught-error", 'try {} catch (e) { throw Error("a"); }'), + js("preserve-caught-error", 'try {} catch (e) { throw new Error("a", o); }'), + js("preserve-caught-error", 'try {} catch (e) { throw new RangeError("a"); }'), + js("preserve-caught-error", 'try {} catch ({ e }) { throw new Error("a"); }'), + js("preserve-caught-error", 'try {} catch (e) { if (a) { throw new Error("a"); } else { throw new Error("b"); } }'), + js("preserve-caught-error", 'try {} catch (e) { throw new Error("a", ({})); }'), ts("no-import-type-side-effects", 'import {} from "a";'), - js("preserve-caught-error", "try {} catch (e) { throw new Error(\"a\", { cause: f, cause: g }); }"), - js("preserve-caught-error", "try {} catch (e) { throw new Error(\"a\", { \"cause\": e }); }"), - js("preserve-caught-error", "try {} catch (e) { const g = () => { throw new Error(\"a\"); }; }"), - js("preserve-caught-error", "try {} catch (e) { throw new Error(\"a\", 1, 2); }"), - js("preserve-caught-error", "try {} catch (e) { throw (new Error(\"a\")); }"), - js("preserve-caught-error", "try {} catch (e) { throw new Error(\"a\", { cause: f, ...c }); }"), - js("preserve-caught-error", "try {} catch (e) { throw new Error(\"a\", { b, ...c }); }"), - js("preserve-caught-error", "try {} catch (e) { class A { static { throw new Error(\"a\"); } b = () => { throw new Error(\"b\"); }; c() { throw new Error(\"c\"); } } }"), - // The text and the range of oxlint's fix, where the original has another or none. - js("arrow-body-style", "a = () => { return b; };\nc = () => {\n return { d: 1 };\n};\nfor (e = () => { return f in g; };;) {}"), + js("preserve-caught-error", 'try {} catch (e) { throw new Error("a", { cause: f, cause: g }); }'), + js("preserve-caught-error", 'try {} catch (e) { throw new Error("a", { "cause": e }); }'), + js("preserve-caught-error", 'try {} catch (e) { const g = () => { throw new Error("a"); }; }'), + js("preserve-caught-error", 'try {} catch (e) { throw new Error("a", 1, 2); }'), + js("preserve-caught-error", 'try {} catch (e) { throw (new Error("a")); }'), + js("preserve-caught-error", 'try {} catch (e) { throw new Error("a", { cause: f, ...c }); }'), + js("preserve-caught-error", 'try {} catch (e) { throw new Error("a", { b, ...c }); }'), + js( + "preserve-caught-error", + 'try {} catch (e) { class A { static { throw new Error("a"); } b = () => { throw new Error("b"); }; c() { throw new Error("c"); } } }', + ), + // The text and range of oxlint's fix, where the original rule's fix differs or doesn't exist. + js( + "arrow-body-style", + "a = () => { return b; };\nc = () => {\n return { d: 1 };\n};\nfor (e = () => { return f in g; };;) {}", + ), js("arrow-body-style", "a = () => { return () => { return b; }; };"), js("no-negated-condition", "if (!a) { b(); } else { c(); }\nd = e !== f ? g : h;"), js("yoda", "a = ['b' === c,d]; if (1 console.log(2); c = d ? console.log(3) : 4; console.log(5)\ne(console.log);"), - js("prefer-arrow-callback", "a(function () { b(function () {}); }); c(function () { return this; }.bind(this)); d(e || async function f(g) {});"), + js( + "no-console", + "if (a) console.log(1); b = () => console.log(2); c = d ? console.log(3) : 4; console.log(5)\ne(console.log);", + ), + js( + "prefer-arrow-callback", + "a(function () { b(function () {}); }); c(function () { return this; }.bind(this)); d(e || async function f(g) {});", + ), js("use-isnan", "a === NaN; b != Number.NaN; c < NaN; d.indexOf(NaN);"), js("no-useless-rename", "import { a as a } from 'b'; const { c /* d */: c, e: e = 1 } = f; export { c as c };"), { rule: "no-useless-rename", file: "a.ts", text: "import { type a as a } from 'b'; export { type a as a };\n" }, @@ -167,10 +192,16 @@ export const cases: Case[] = [ js("no-iterator", "a.__iterator__ = b; c['__iterator__'];"), js("no-empty-static-block", "class A { static {} }"), js("no-debugger", "if (a) debugger; else debugger\nfor (;;) debugger;"), - js("for-direction", "for (let i = 0; i < 1; i--) {} for (let j = 0; j < 1; j -= 1) {} for (let k = 1; k > 0; ++k) {}"), + js( + "for-direction", + "for (let i = 0; i < 1; i--) {} for (let j = 0; j < 1; j -= 1) {} for (let k = 1; k > 0; ++k) {}", + ), js("no-useless-escape", "a = /[\\*\\?]/; b = '\\d\\e';"), js("prefer-destructuring", "const a = (b || c).a; const d = e['d']; const f /* g */ = (h.i).f;"), - js("no-unneeded-ternary", "a = (b !== c) ? true : false; d = e & f ? true : false; g = h == i ? false : true; j = k[l] ? false : true;"), + js( + "no-unneeded-ternary", + "a = (b !== c) ? true : false; d = e & f ? true : false; g = h == i ? false : true; j = k[l] ? false : true;", + ), js("sort-vars", "var b, a; var d = e(), c, g = 1, f; var i, /* j */ h;"), js("one-var", "const a = 1; const b = 2; export const c = 3;"), { rule: "one-var", file: "a.ts", text: "declare const a: number; const b = 2; const c = 3;\n" }, @@ -178,103 +209,314 @@ export const cases: Case[] = [ ts("no-explicit-any", "let a: any; type B = keyof any; function c(...d: any) {}"), ts("ban-ts-comment", "// @ts-ignore\nlet a: number = 'b';\n/* @ts-ignore: @ts-ignore */\nlet c: number = 'd';"), ts("consistent-type-assertions", "a = c; d(f); g = i ? 1 : 2; j = (l, m); n = () => {};"), - ts("prefer-function-type", "interface A { (): void }\nexport interface B { (d: C): void; }\ntype E = { (): void };"), + ts( + "prefer-function-type", + "interface A { (): void }\nexport interface B { (d: C): void; }\ntype E = { (): void };", + ), ts("no-empty-object-type", "interface A extends C {}\ninterface A { d: B }\ninterface E extends F {}"), - ts("consistent-indexed-object-style", "type A = {\n /** b */\n [C in D]: E;\n};\ninterface F { [g: string]: H /* i */ }"), - // oxlint has a fix, ESLint and typescript-eslint have none. - js("sort-keys", "a = { c: 1, b: { e: 1, d: 2 }, a: 3 };\nf = {\n /** h */\n h: 1, // i\n g: 2,\n};\nj = { ...k, m: 1, l: 2, ...n };\no = { q: 1, /* r */ p: 2 };"), - js("func-names", "var a = function () {}; b.c = function* () {}; d = { e: function () { e; }, 'f': async function () {}, g: h(function () {}) }; (function () {})();"), + ts( + "consistent-indexed-object-style", + "type A = {\n /** b */\n [C in D]: E;\n};\ninterface F { [g: string]: H /* i */ }", + ), + // oxlint has a fix where ESLint and typescript-eslint have none. + js( + "sort-keys", + "a = { c: 1, b: { e: 1, d: 2 }, a: 3 };\nf = {\n /** h */\n h: 1, // i\n g: 2,\n};\nj = { ...k, m: 1, l: 2, ...n };\no = { q: 1, /* r */ p: 2 };", + ), + js( + "func-names", + "var a = function () {}; b.c = function* () {}; d = { e: function () { e; }, 'f': async function () {}, g: h(function () {}) }; (function () {})();", + ), js("no-plusplus", "a++; --b.c; d['e']++; f[g]--; for (;; h++) {}"), js("no-void", "a = void 0; void b(); c(void (d));"), js("no-eq-null", "a == null; null != (b); c /* d */ == /* e */ null;"), js("no-throw-literal", "function a() { throw 'b'; } function c() { throw (`d`); } function e() { throw 1; }"), js("no-unexpected-multiline", "a\n(b || c).d();\ne\n[f].g();\nh\n`i`;"), ts("no-extraneous-class", "export class A {}\nclass B {}\n@c class D {}\ne = class {};"), - ts("no-unnecessary-parameter-property-assignment", "class A { constructor(public b: number, private c: string) { this.b = b; d(this.c = c); } }"), - // The bytes that the fixes of tsgolint leave: what it puts in begins where the token before ends, what it takes out ends there. - typed("no-unnecessary-boolean-literal-compare", "declare const b: boolean, n: boolean | null, x: unknown, f: (a?: boolean) => boolean, o: { p?: boolean }; let r;\nif (b === true) {}\nif (b !== true) {}\nif (b === false) {}\nif (b !== false) {}\nif (true === b) {}\nif (false !== b) {}\nif (true !== b) {}\nif (false === (x instanceof Error)) {}\nr = b === true;\nr = b === false;\nr = !(b === true);\nr = !(b !== true);\nr = !(b === false);\nr = !((b === false));\nr = (x instanceof Error) === false;\nr = x instanceof Error === false;\nr = f() === false;\nif (n === true) {}\nif (n !== true) {}\nif (n === false) {}\nif (n !== false) {}\nr = n === true;\nr = n !== true;\nr = n === false;\nr = n !== false;\nr = !(n === true);\nr = !(n !== true);\nr = !(n === false);\nr = (n ?? b) === true;\nr = (n ?? b) === false;\nr = n === true && b;\nr = n === true ? 1 : 2;\nwhile (n === true) {}\nr = b /* c */ === /* d */ true;\nr = true /* c */ === /* d */ b;\nr = b\n === true;\nr = true ===\n b;\nr = !!(n === true);\nfor (; n === true; ) {}\ndo {} while (n === true);\nr = [n === true];\nr = f(n === true);\nexport {};"), + ts( + "no-unnecessary-parameter-property-assignment", + "class A { constructor(public b: number, private c: string) { this.b = b; d(this.c = c); } }", + ), + // The exact bytes that tsgolint's fixes produce. Its nodes start at the end of the previous token, so an insertion + // goes there and a removal stops there. + typed( + "no-unnecessary-boolean-literal-compare", + "declare const b: boolean, n: boolean | null, x: unknown, f: (a?: boolean) => boolean, o: { p?: boolean }; let r;\nif (b === true) {}\nif (b !== true) {}\nif (b === false) {}\nif (b !== false) {}\nif (true === b) {}\nif (false !== b) {}\nif (true !== b) {}\nif (false === (x instanceof Error)) {}\nr = b === true;\nr = b === false;\nr = !(b === true);\nr = !(b !== true);\nr = !(b === false);\nr = !((b === false));\nr = (x instanceof Error) === false;\nr = x instanceof Error === false;\nr = f() === false;\nif (n === true) {}\nif (n !== true) {}\nif (n === false) {}\nif (n !== false) {}\nr = n === true;\nr = n !== true;\nr = n === false;\nr = n !== false;\nr = !(n === true);\nr = !(n !== true);\nr = !(n === false);\nr = (n ?? b) === true;\nr = (n ?? b) === false;\nr = n === true && b;\nr = n === true ? 1 : 2;\nwhile (n === true) {}\nr = b /* c */ === /* d */ true;\nr = true /* c */ === /* d */ b;\nr = b\n === true;\nr = true ===\n b;\nr = !!(n === true);\nfor (; n === true; ) {}\ndo {} while (n === true);\nr = [n === true];\nr = f(n === true);\nexport {};", + ), { - ...typed("no-unnecessary-boolean-literal-compare", "declare const b: boolean, n: boolean | null, x: unknown, f: (a?: boolean) => boolean, o: { p?: boolean }; let r;\nif (n === true) {}\nif (n !== true) {}\nif (n === false) {}\nif (n !== false) {}\nr = n === true;\nr = n !== true;\nr = n === false;\nr = n !== false;\nr = !(n === true);\nr = !(n !== true);\nr = !(n === false);\nr = (n ?? b) === true;\nr = (n ?? b) === false;\nr = n === true && b;\nr = n === true ? 1 : 2;\nwhile (n === true) {}\nr = !!(n === true);\nfor (; n === true; ) {}\ndo {} while (n === true);\nr = [n === true];\nr = f(n === true);\nr = true === n;\nr = false === n;\nr = false !== n;\nr = o.p === true;\nr = o.p === false;\nr = (b ? n : null) === true;\nr = (b ? n : null) === false;\nr = !(b ? n : null) === false;\nif (!(n === false)) {}\nif ((n === true)) {}\nr = n === true || b;\nif (n === true || b) {}\nr = !(n !== false);\nr = n! === true;\nr = (n as boolean | null) === false;\nr = (n as boolean | null) === true;\nexport {};"), + ...typed( + "no-unnecessary-boolean-literal-compare", + "declare const b: boolean, n: boolean | null, x: unknown, f: (a?: boolean) => boolean, o: { p?: boolean }; let r;\nif (n === true) {}\nif (n !== true) {}\nif (n === false) {}\nif (n !== false) {}\nr = n === true;\nr = n !== true;\nr = n === false;\nr = n !== false;\nr = !(n === true);\nr = !(n !== true);\nr = !(n === false);\nr = (n ?? b) === true;\nr = (n ?? b) === false;\nr = n === true && b;\nr = n === true ? 1 : 2;\nwhile (n === true) {}\nr = !!(n === true);\nfor (; n === true; ) {}\ndo {} while (n === true);\nr = [n === true];\nr = f(n === true);\nr = true === n;\nr = false === n;\nr = false !== n;\nr = o.p === true;\nr = o.p === false;\nr = (b ? n : null) === true;\nr = (b ? n : null) === false;\nr = !(b ? n : null) === false;\nif (!(n === false)) {}\nif ((n === true)) {}\nr = n === true || b;\nif (n === true || b) {}\nr = !(n !== false);\nr = n! === true;\nr = (n as boolean | null) === false;\nr = (n as boolean | null) === true;\nexport {};", + ), options: { allowComparingNullableBooleansToTrue: false, allowComparingNullableBooleansToFalse: false }, }, - typed("no-meaningless-void-operator", "let r;\nvoid (() => {})();\nfunction g() {}\nvoid g();\nvoid g2();\nfunction g2() {}\nvoid/* c */g3();\nfunction g3() {}\nvoid\ng4();\nfunction g4() {}\nfunction g5(): never { throw 1; }\nvoid g5();\nr = void g6();\nfunction g6() {}\nvoid void g7();\nfunction g7() {}\nvoid (g8());\nfunction g8() {}\ndeclare const u: undefined;\nvoid u;\nexport {};"), - // What tsgolint leaves alone or only suggests, and where it puts `async`. - typed("promise-function-async", "const a = function (p: Promise) { return p; };\nfunction b(p: Promise) { return p; }\nexport function c(p: Promise) { return p; }\nexport default function d(p: Promise) { return p; }\nconst e = (p: Promise) => p;\nconst f = { g(p: Promise) { return p; }, h: function (p: Promise) { return p; }, i: (p: Promise) => p, [\"j\"](p: Promise) { return p; } };\nclass K { l(p: Promise) { return p; } public m(p: Promise) { return p; } static n(p: Promise) { return p; } public static o(p: Promise) { return p; } [\"q\"](p: Promise) { return p; } r = (p: Promise) => p; }\nfunction s(p: boolean) { return p ? Promise.resolve(5) : 5; }\nexport function t(p: boolean) { return p ? Promise.resolve(5) : 5; }\nconst u = (p: boolean) => (p ? Promise.resolve(5) : 5);\nfunction v(p: boolean): Promise | number { return p ? Promise.resolve(5) : 5; }\nfunction w(p: boolean): Promise | Promise { return p ? Promise.resolve(5) : Promise.resolve(\"\"); }\nx(function (p: Promise) { return p; });\ndeclare function x(a: unknown): void;\n function y(p: Promise) { return p; }\n/* z */ function z(p: Promise) { return p; }\ndeclare const dec: any;\nclass A1 { @dec b1(p: Promise) { return p; } }\nclass A2 { /* c */ b2(p: Promise) { return p; } }\nabstract class A3 { protected b3(p: Promise) { return p; } override toString(): any { return Promise.resolve(); } }\nexport {};"), - typed("prefer-readonly", "class A { private a: number; }\nclass B { #b: number; }\nclass C { private c = 1; }\nclass D { private d: number; constructor() { this.d = 1; } }\nclass E { private [Symbol.iterator] = 7; }\nclass F { private [1] = 7; }\nclass G { private [\"g\"] = 7; }\nclass H { private \"h\" = 7; }\nclass I { private 1 = 7; }\nclass J { private static j: number; }\nclass K { private static k = 1; }\nclass L { constructor(private l: number) {} }\nclass M { private m?: number; }\nclass N { private declare n: number; }\nclass O { private o!: number; }\nclass P { private p: number | undefined; q() { return this.p; } }\nexport {};"), - typed("prefer-string-starts-ends-with", "declare const s: string;\ns.match(/^bar/) !== undefined;\ns.match(/^bar/) === undefined;\ns.match(/^bar/) != undefined;\ns.match(/^bar/) == undefined;\ns.match(/^bar/) !== null;\ns.match(/^bar/) === null;\ns.match(/^bar/) != null;\ns.match(/^bar/) == null;\nconst m = undefined;\ns.match(/^bar/) === m;\nconst n = null;\ns.match(/^bar/) === n;\nconst o = null;\ns.match(/^bar/) != o;\ns.match(/bar$/) !== void 0;\nnull !== s.match(/^bar/);\nundefined !== s.match(/^bar/);\nexport {};"), - typed("no-unnecessary-type-assertion", "enum E { A, B }\nenum S { A = \"a\" }\ndeclare const e: E, n: number, s: S, k: \"A\" | \"B\", eu: E | undefined, nu: number | undefined;\nexport const a1 = e as number;\nexport const a2 = n as E;\nexport const a3 = E[k] as number;\nexport const a4 = (1 as number) as E;\nexport const a5 = eu as number | undefined;\nexport const a6 = nu as E | undefined;\nexport const a7 = e;\nexport const a8 = n;\nexport const a9 = E[n as E];\nexport const b1 = s as string;\nexport const b2: number = e as number;\nexport const b3: E = n as E;\ndeclare function f(x: number): void; declare function g(x: E): void;\nf(e as number);\ng(n as E);\nexport const b4 = E.A as number;\nexport const b5 = E.A as E;\nexport const b6 = e as E;\nexport const b7 = [e as number];\nexport const b8 = { c: e as number };\nexport function b9(): number { return e as number; }"), - typed("no-unnecessary-type-assertion", "type V = string | undefined;\nexport function n1(value: V, c: boolean) { value = c ? (value as string) : \"\"; return value.length; }\nexport function n2(value: V) { value = (console.log(), value as string); return value.length; }\nexport function n3(value: V) { [value] = [value as string]; return value.length; }\nexport function n4(value: V) { ({ value } = { value: value as string }); return value.length; }\nexport function n5(value: V) { ({ value } = { ...{ value: value as string } }); return value.length; }\nexport function n7(value: V, other: string) { value = other && (value as string); return value.length; }\nexport function n8(value: V, other: V) { value = other ?? (value as string); return value.length; }\nexport function n9(value: V, other: string) { value = (value as string) || other; return value.length; }\nexport function m1(value: V) { value = value as string; return value.length; }\nexport function m2(value: V, o: { v: V }) { o.v = value as string; }\nexport function m3(value: V) { const x: V = value as string; return x; }\nexport function m4(value: V, f: (a?: string) => void) { f(value as string); }\nexport function m5(value: V) { let y: V; y = [value as string][0]; return y; }\nexport function m6(value: V) { let y: { v?: string }; y = { v: value as string }; return y; }\nexport function m7(value: V, c: boolean) { value = c ? (value as V) : \"\"; return value; }\nexport function m8(value: V) { let y: V; y = (value as string) ?? \"\"; return y; }\nexport function m9(value: V) { let y: V; [y] = [value as V]; return y; }\nexport function p1(o: T) { (o as { a: number }).a = 1; }\nexport function p2(o: T) { (o as { a: { b: number } }).a.b++; }\nexport function p3(o: T) { return (o as { a: number }).a; }\nexport function p4(o: T) { return (o as T).a; }"), - // no-unused-vars: oxlint has a fixer of its own, and an option for what its fixes are. - { rule: "no-unused-vars", file: "a.ts", text: "import a from 'm1';\nimport b, { c, d } from 'm2';\nimport e, * as f from 'm3';\nimport { g, h /* i */, j } from 'm4';\nimport k = require('m5');\nimport { l, m } from 'm6';\nc; e; h;\n" }, - { rule: "no-unused-vars", file: "a.ts", text: "let a = 1;\nvar b = 1, c = 2, d = 3;\nlet e = 1; e = 2;\nconst { f, g } = c, [h, i, ...j] = c;\nconst [k, ...[l]] = c;\nfor (const n of c) {}\ntry {} catch (o) {}\nfunction p(q: number, _q: number): q is 1 { return _q; }\nconst r = () => {};\nconst s = c(); (b, s, d);\nb; d; g; i; k; p;\n" }, - { rule: "no-unused-vars", file: "a.ts", text: "import a from 'm1';\nimport b, { c, d } from 'm2';\nimport e, * as f from 'm3';\nimport { g, h /* i */, j } from 'm4';\nimport k = require('m5');\nimport { l, m } from 'm6';\nc; e; h;\nlet n = 1;\n", options: { fix: { imports: "safe-fix", variables: "off" } } }, - { rule: "no-unused-vars", file: "a.ts", text: "import a from 'm1';\nimport b, { c, d } from 'm2';\nimport e, * as f from 'm3';\nimport { g, h /* i */, j } from 'm4';\nimport k = require('m5');\nimport { l, m } from 'm6';\nc; e; h;\nlet n = 1; let o = 1; o = 2;\n", options: { fix: { imports: "fix", variables: "fix" }, varsIgnorePattern: "^_" } }, - { rule: "no-unused-vars", file: "a.ts", text: "import a from 'm1';\nimport b, { c, d } from 'm2';\nimport e, * as f from 'm3';\nimport { g, h /* i */, j } from 'm4';\nimport k = require('m5');\nimport { l, m } from 'm6';\nc; e; h;\ntry {} catch (n) {}\n", options: { fix: { imports: "off" } } }, - { rule: "no-unused-vars", file: "a.ts", text: "import _a, { b } from 'm';\nconst _c = 1; _a; _c;\ntry {} catch (_d) { _d; }\n", options: { reportUsedIgnorePattern: true, varsIgnorePattern: "^_", caughtErrorsIgnorePattern: "^_" } }, - // A chain and what follows it: what tsgolint fixes, only suggests, or leaves alone. Not here: where its own text is broken. - typed("prefer-optional-chain", "declare const foo: { bar: { baz: { buzz: number } | undefined } | undefined } | undefined;\ndeclare const nul: { bar: { baz: number } | null } | null;\ndeclare const both: { bar: { baz: number } | null | undefined } | null | undefined;\nfoo === undefined || foo.bar === undefined || foo.bar.baz === undefined || foo.bar.baz.buzz === undefined;\nfoo === undefined || foo.bar === undefined;\nfoo === undefined || !foo.bar;\nfoo === undefined || foo.bar === 1;\nfoo !== undefined && foo.bar !== undefined;\nfoo !== undefined && foo.bar !== undefined && foo.bar.baz;\nfoo !== undefined && foo.bar;\nnul === null || nul.bar === null;\nnul === null || nul.bar === null || nul.bar.baz === 1;\nnul !== null && nul.bar !== null;\nnul !== null && nul.bar;\nboth == null || both.bar == null;\nboth == null || both.bar == null || both.bar.baz === 1;\nboth != null && both.bar != null;\nboth != null && both.bar;\n!foo || !foo.bar;\n!foo || !foo.bar || !foo.bar.baz;\nfoo && foo.bar;\nfoo && foo.bar && foo.bar.baz;\ntypeof foo === \"undefined\" || foo.bar === undefined;\nfoo == undefined || foo.bar == undefined;\nexport {};"), - typed("prefer-optional-chain", "declare const foo: { bar: { baz: number | undefined } | undefined } | undefined;\ndeclare const both: { bar: { baz: number } | null | undefined } | null | undefined;\ndeclare const c: { d: number };\nfoo && foo.bar && foo.bar.baz === 1;\nfoo && foo.bar && foo.bar.baz !== 1;\nfoo && foo.bar && foo.bar.baz == null;\nfoo && foo.bar && foo.bar.baz != null;\nfoo && foo.bar && foo.bar.baz === undefined;\nfoo && foo.bar && foo.bar.baz !== undefined;\nfoo && foo.bar && foo.bar.baz > 1;\nboth != null && both.bar != null && both.bar.baz === 1;\nboth != null && both.bar != null && both.bar.baz !== 1;\nboth != null && both.bar != null && both.bar.baz > 1;\nboth == null || both.bar == null || both.bar.baz === 1;\nboth == null || both.bar == null || both.bar.baz !== 1;\nboth == null || both.bar == null || both.bar.baz > 1;\nboth == null || both.bar == null || both.bar.baz == null;\nboth == null || both.bar == null || both.bar.baz === undefined;\nboth == null || both.bar == null || c.d === 1;\nboth == null || both.bar == null || c.d === 1 || both.bar.baz === 1;\n!foo || !foo.bar || foo.bar.baz === 1;\n!foo || !foo.bar || foo.bar.baz !== 1;\n!foo || !foo.bar || foo.bar.baz > 1;\n!both || !both.bar || both.bar.baz === c.d;\n!both || !both.bar || both.bar.baz !== c.d;\nboth == null || both.bar == null || both.bar.baz === 1 || both.bar.baz === 2;\nexport {};"), - typed("prefer-optional-chain", "declare const foo: { bar: { baz: number | undefined | null } | undefined } | undefined;\ndeclare const both: { bar: { baz: number | null } | null | undefined } | null | undefined;\nfoo && foo.bar && !foo.bar.baz;\nfoo && foo.bar && foo.bar.baz === null;\nfoo && foo.bar && foo.bar.baz !== null;\nfoo && foo.bar && typeof foo.bar.baz === \"undefined\";\nfoo && foo.bar && typeof foo.bar.baz !== \"undefined\";\n!foo || !foo.bar || foo.bar.baz;\n!foo || !foo.bar || foo.bar.baz != null;\n!foo || !foo.bar || foo.bar.baz !== undefined;\n!foo || !foo.bar || foo.bar.baz !== null;\n!foo || !foo.bar || foo.bar.baz === null;\n!foo || !foo.bar || foo.bar.baz == null;\n!foo || !foo.bar || foo.bar.baz === undefined;\nboth == null || both.bar == null || both.bar.baz != null;\nboth == null || both.bar == null || both.bar.baz;\nboth == null || both.bar == null || !both.bar.baz;\nboth != null && both.bar != null && both.bar.baz == null;\nboth != null && both.bar != null && !both.bar.baz;\nboth != null && both.bar != null && both.bar.baz;\nboth != null && both.bar != null && both.bar.baz != null;\nfoo && foo.bar && !foo.bar.baz && foo.bar.baz === 1;\nfoo && foo.bar && foo.bar.baz === null && 1;\nexport {};"), - typed("prefer-optional-chain", "declare const a: { b: { c: number } | null } | undefined;\ndeclare const foo: { bar: { baz: number | undefined | null } | undefined } | undefined;\ndeclare const both: { bar: { baz: number | null } | null | undefined } | null | undefined;\na && a.b !== null;\na && a.b !== null && a.b.c;\n!a || a.b === null;\n!a || a.b === null || !a.b.c;\n!foo || !foo.bar || typeof foo.bar.baz !== \"undefined\";\nboth != null && both.bar != null && typeof both.bar.baz === \"undefined\";\nboth != null && both.bar != null && typeof both.bar.baz !== \"undefined\";\nboth == null || both.bar == null || typeof both.bar.baz !== \"undefined\";\nfoo && typeof foo.bar === \"undefined\";\nfoo && typeof foo.bar !== \"undefined\";\n!foo || typeof foo.bar !== \"undefined\";\nfoo && foo.bar !== null;\n!foo || foo.bar === null;\nfoo && foo.bar === null;\n!foo || foo.bar !== null;\nfoo && foo.bar && \"undefined\" === typeof foo.bar.baz;\nfoo && foo.bar && null !== foo.bar.baz;\nfoo && foo.bar && undefined === foo.bar.baz;\nexport {};"), - // The type of a call where nothing is expected of it, and `as any` on a property of one of several types. - typed("no-unnecessary-type-assertion", "type El = HTMLElement; type In = HTMLInputElement;\ntype Fn = (c: El, id: string) => T;\ntype Cond = T extends string ? number : string;\ntype Via = Parameters>;\ntype Box = { v: T };\ndeclare function f1(...a: Parameters>): T;\ndeclare function f2(a: Cond): T;\ndeclare function f3(a: T extends In ? number : string): T;\ndeclare function f4(...a: Via): T;\ndeclare function f5(a: T[\"id\"]): T;\ndeclare function f6(a: keyof T): T;\ndeclare function f7(a: Partial): T;\ndeclare function f8(a: Box): T;\ndeclare function f9(a: (x: T) => void): T;\ndeclare function g1(a: string, b?: T): T;\ndeclare function g2(a: string, ...b: T[]): T;\ndeclare function g3(a: ReturnType>): T;\ndeclare function g4(a: NonNullable): T;\ndeclare function g5(a: Exclude): T;\ndeclare function g6(a: Awaited): T;\ndeclare function g7(a: Readonly): T;\ndeclare function g8(a: Pick): T;\ndeclare const el: El, inp: In;\nexport const a1 = f1(el, \"a\") as In;\nexport const a2 = f2(\"a\") as In;\nexport const a3 = f3(\"a\") as In;\nexport const a4 = f4(el, \"a\") as In;\nexport const a5 = f5(\"a\") as In;\nexport const a6 = f6(\"id\") as In;\nexport const a7 = f7({}) as In;\nexport const a8 = f8({ v: inp }) as In;\nexport const a9 = f9(() => {}) as In;\nexport const b1 = g1(\"a\") as In;\nexport const b2 = g2(\"a\") as In;\nexport const b3 = g3(inp) as In;\nexport const b4 = g4(inp) as In;\nexport const b5 = g5(inp) as In;\nexport const b6 = g6(inp) as In;\nexport const b8 = g8({ id: \"a\" }) as In;\nexport const c1 = g1(\"a\", inp) as In;\nexport const c2 = g2(\"a\", inp) as In;"), - typed("no-unnecessary-type-assertion", "import type { ClientBase } from \"pg\";\ninterface Config { dir: string }\ninterface WithUrl { databaseUrl: string }\ninterface WithClient { dbClient: ClientBase }\ninterface Known { dbClient: { query(): void } }\ninterface WithAny { dbClient: any }\ndeclare function r1(o: Config & (WithClient | WithUrl)): void;\ndeclare function r2(o: Config & WithClient): void;\ndeclare function r3(o: (Config & WithClient) | (Config & WithUrl)): void;\ndeclare function r4(o: Config & (Known | WithUrl)): void;\ndeclare function r5(o: Config & (WithAny | WithUrl)): void;\ndeclare function r6(o: Config & (WithAny | WithUrl)): void;\ndeclare const u: unknown, n: number;\nr1({ dbClient: u as ClientBase, dir: \"a\" });\nr2({ dbClient: u as ClientBase, dir: \"a\" });\nr3({ dbClient: u as ClientBase, dir: \"a\" });\nr4({ dbClient: u as { query(): void }, dir: \"a\" });\nr5({ dbClient: u as any, dir: \"a\" });\nr6({ dbClient: n as any, dir: \"a\" });\nr1({ dbClient: n as number, dir: \"a\" });\nr1({ dbClient: n as unknown as ClientBase, dir: \"a\" });\nr5({ dbClient: n as unknown as any, dir: \"a\" });\nr5({ dbClient: n as unknown as string, dir: \"a\" });"), - // What tsgolint writes: a node begins where the token before it ends, parentheses are nodes, and a name in brackets is what its type says. - typed("no-array-delete", "namespace N0 {\ndeclare const a: number[]; delete a[0];\n}\nnamespace N1 {\ndeclare const a: number[]; delete a[0, 1];\n}\nnamespace N2 {\ndeclare const a: number[]; delete a.length;\n}\nnamespace N3 {\ndeclare const a: number[]; delete (a)[0];\n}\nnamespace N4 {\ndeclare const a: number[]; delete a [ 0 ] ;\n}\nnamespace N5 {\ndeclare const a: number[]; delete a[\"x\"];\n}\nnamespace N6 {\ndeclare const a: number[]; delete/* b */a[0];\n}\nnamespace N7 {\ndeclare const a: number[][]; delete a[0][1];\n}\nnamespace N8 {\ndeclare const a: number[]; delete a![0];\n}\nnamespace N9 {\ndeclare const a: number[]; delete (a as number[])[0];\n}\nnamespace N10 {\ndeclare const a: number[]; void delete a[0];\n}"), - typed("no-misused-spread", "namespace N0 {\ndeclare const m: Map; const o = { ...m };\n}\nnamespace N1 {\ndeclare const m: Map; const o = { ...m, };\n}\nnamespace N2 {\ndeclare const m: Map; const o = {...m};\n}\nnamespace N3 {\ndeclare const m: Map; const o = { a: 1, ...m };\n}\nnamespace N4 {\ndeclare const m: Map; const o = { .../* c */m /* d */ };\n}\nnamespace N5 {\ndeclare const m: Map; const o = ({ ...m });\n}\nnamespace N6 {\ndeclare const m: Map; f({ ...m }); declare function f(x: object): void;\n}\nnamespace N7 {\ndeclare const m: Map; const o = { ...m as Map };\n}\nnamespace N8 {\ndeclare const m: Map; const o = { ...(m) , };\n}\nnamespace N9 {\ndeclare const p: Promise<{a: 1}>; async function f() { return { ...p }; }\n}\nnamespace N10 {\ndeclare const p: Promise<{a: 1}>, q: boolean; async function f() { return { ...(q ? p : p) }; }\n}\nnamespace N11 {\ndeclare const p: Promise<{a: 1}>, q: boolean; async function f() { return { ...q ? p : p }; }\n}"), - typed("no-confusing-void-expression", "namespace N0 {\nconst a = () => console.log(1);\n}\nnamespace N1 {\nconst a = () => (console.log(1));\n}\nnamespace N2 {\nconst a = () => ((console.log(1)));\n}\nnamespace N3 {\nconst a = () => /* c */ console.log(1);\n}\nnamespace N4 {\nconst a = () => console.log(1) /* d */;\n}\nnamespace N5 {\nconst a = () =>\n console.log(1);\n}\nnamespace N6 {\nconst a = (): number => console.log(1) as any;\n}\nnamespace N7 {\nf(() => console.log(1)); declare function f(x: () => void): void;\n}\nnamespace N8 {\nfunction f() { return console.log(1); }\n}\nnamespace N9 {\nfunction f() { return console.log(1) }\n}\nnamespace N10 {\nfunction f() { return (console.log(1)); }\n}\nnamespace N11 {\nfunction f() { return /* c */ console.log(1); }\n}\nnamespace N12 {\nfunction f(c: boolean) { if (c) return console.log(1); f(c); }\n}\nnamespace N13 {\nfunction f(c: boolean) { if (c) { return console.log(1); } f(c); }\n}\nnamespace N14 {\nfunction f(c: boolean) { if (c) { return console.log(1) } f(c); }\n}\nnamespace N15 {\nfunction f(c: boolean) { if (c) return console.log(1)\nf(c); }\n}\nnamespace N16 {\nfunction f() { g()\nreturn [1].forEach(console.log) }\ndeclare function g(): void;\n}\nnamespace N17 {\nfunction f() { g()\nreturn (console.log(1)) }\ndeclare function g(): void;\n}\nnamespace N18 {\nfunction f(c: boolean) { g()\nif (c) { return [1].forEach(console.log) } g() }\ndeclare function g(): void;\n}\nnamespace N19 {\nfunction f() { return `a`.length ? console.log(1) : console.log(2); }\n}\nnamespace N20 {\nconst x = console.log(1);\n}\nnamespace N21 {\nfunction f(): number { return console.log(1) as any; }\n}\nnamespace N22 {\nfunction f(c: boolean) { label: return console.log(1); }\n}\nnamespace N23 {\nfunction f(c: boolean) { switch (c) { case true: return console.log(1); } }\n}\nnamespace N24 {\nfunction f(c: boolean) { try { return console.log(1); } finally {} }\n}"), - typed("no-unnecessary-type-conversion", "namespace N0 {\nconst arr = ['asdf']; arr[0] += '';\n}\nnamespace N1 {\nconst obj = { prop: 'asdf' }; obj.prop += '';\n}\nnamespace N2 {\nlet s = 'asdf'; s += '';\n}\nnamespace N3 {\nlet s = 'asdf'; (s) += '';\n}\nnamespace N4 {\n'asdf'.toString(console.log('extra'));\n}\nnamespace N5 {\nString('asdf', console.log('extra'));\n}\nnamespace N6 {\nString('asdf');\n}\nnamespace N7 {\n'asdf'.toString();\n}\nnamespace N8 {\nNumber(1, 2);\n}\nnamespace N9 {\nBoolean(true, 1);\n}\nnamespace N10 {\nBigInt(1n, 2);\n}\nnamespace N11 {\nfunction f(x: T) { return x + ''; }\n}\nnamespace N12 {\nfunction f(x: T) { return '' + x; }\n}\nnamespace N13 {\nfunction f(x: T) { x += ''; return x; }\n}\nnamespace N14 {\nfunction f(x: T) { return +x; }\n}\nnamespace N15 {\nfunction f(x: T) { return !!x; }\n}\nnamespace N16 {\nfunction f(x: T) { return ~~x; }\n}\nnamespace N17 {\nfunction f(x: T) { return String(x); }\n}\nnamespace N18 {\nfunction f(x: T) { return x.toString(); }\n}\nnamespace N19 {\nfunction f(x: T) { return String(x); }\n}\nnamespace N20 {\nfunction f(x: T) { return String(x); }\n}\nnamespace N21 {\nfunction f(x: T) { return Number(x); }\n}\nnamespace N22 {\nfunction f(x: T) { return BigInt(x); }\n}\nnamespace N23 {\nfunction f(x: string & { a: 1 }) { return String(x); }\n}"), - { ...typed("dot-notation", "namespace N0 {\nclass E { private _b = 0; public get priv(): number { return this._b; } private set priv(v: number) { this._b = v; } }\ndeclare const obj: E;\nobj['priv'] = 1;\n}\nnamespace N1 {\nclass E { private _b = 0; public get priv(): number { return this._b; } private set priv(v: number) { this._b = v; } }\ndeclare const obj: E;\nobj['priv'];\n}\nnamespace N2 {\nclass E { private _b = 0; private set priv(v: number) { this._b = v; } public get priv(): number { return this._b; } }\ndeclare const obj: E;\nobj['priv'];\n}\nnamespace N3 {\nclass E { private _b = 0; private set priv(v: number) { this._b = v; } public get priv(): number { return this._b; } }\ndeclare const obj: E;\nobj['priv'] = 1;\n}\nnamespace N4 {\nclass E { private _b = 0; public get priv(): number { return this._b; } private set priv(v: number) { this._b = v; } }\ndeclare const obj: E;\nobj['priv'] += 1;\n}\nnamespace N5 {\nclass E { private _b = 0; public get priv(): number { return this._b; } private set priv(v: number) { this._b = v; } }\ndeclare const obj: E;\nobj['priv']++;\n}\nnamespace N6 {\nclass E { private _b = 0; public get priv(): number { return this._b; } private set priv(v: number) { this._b = v; } }\ndeclare const obj: E;\n[obj['priv']] = [1];\n}\nnamespace N7 {\nclass E { private _b = 0; public get priv(): number { return this._b; } private set priv(v: number) { this._b = v; } }\ndeclare const obj: E;\ndelete obj['priv'];\n}\nnamespace N8 {\nclass E { private p = 0; }\ndeclare const obj: E;\nobj['p'] = 1; obj['p'];\n}\nnamespace N9 {\nclass E { public p = 0; }\ndeclare const obj: E;\nobj['p'] = 1; obj['p'];\n}"), options: {"allowPrivateClassPropertyAccess": true} }, - typed("use-unknown-in-catch-callback-variable", "namespace N0 {\nlet method = 'catch'; Promise.resolve()[method]((error: Error) => {});\n}\nnamespace N1 {\nconst method = 'catch'; Promise.resolve()[method]((error: Error) => {});\n}\nnamespace N2 {\nPromise.resolve()['catch']((error: Error) => {});\n}\nnamespace N3 {\nPromise.resolve()[`catch`]((error: Error) => {});\n}\nnamespace N4 {\nPromise.resolve().catch((error: Error) => {});\n}\nnamespace N5 {\nlet method = 'then'; Promise.resolve()[method](() => {}, (error: Error) => {});\n}\nnamespace N6 {\ndeclare const method: 'catch'; Promise.resolve()[method]((error: Error) => {});\n}\nnamespace N7 {\ndeclare const method: 'catch' | 'then'; Promise.resolve()[method]((error: Error) => {});\n}"), - typed("prefer-readonly", "namespace N0 {\nclass A { private a: number; }\n}\nnamespace N1 {\nclass A { #a: number; }\n}\nnamespace N2 {\nclass A { private a = 1; }\n}\nnamespace N3 {\nclass A { private a: number; constructor() { this.a = 1; } }\n}\nnamespace N4 {\nclass A { private a?: number; }\n}\nnamespace N5 {\nclass A { private a!: number; }\n}\nnamespace N6 {\nclass A { private static a: number; }\n}\nnamespace N7 {\nclass A { private prop = 7; foo() { this['prop'] = 10; } }\n}\nnamespace N8 {\nclass A { private 'prop' = 7; foo() { this.prop = 10; } }\n}\nnamespace N9 {\nclass A { private 'prop' = 7; foo() { this['prop'] = 10; } }\n}\nnamespace N10 {\nclass A { private prop = 7; foo() { this[`prop`] = 10; } }\n}\nnamespace N11 {\nclass A { private prop = 7; foo() { this['prop']++; } }\n}\nnamespace N12 {\nclass A { private prop = 7; foo() { const k = 'prop'; this[k] = 10; } }\n}"), - { ...typed("prefer-readonly", "namespace N0 {\nclass A { private a: number; }\n}\nnamespace N1 {\nclass A { #a: number; }\n}\nnamespace N2 {\nclass A { private a = 1; }\n}\nnamespace N3 {\nclass A { private a: number; constructor() { this.a = 1; } }\n}\nnamespace N4 {\nclass A { private a?: number; }\n}\nnamespace N5 {\nclass A { private a!: number; }\n}\nnamespace N6 {\nclass A { private static a: number; }\n}\nnamespace N7 {\nclass A { private prop = 7; foo() { this['prop'] = 10; } }\n}\nnamespace N8 {\nclass A { private 'prop' = 7; foo() { this.prop = 10; } }\n}\nnamespace N9 {\nclass A { private 'prop' = 7; foo() { this['prop'] = 10; } }\n}\nnamespace N10 {\nclass A { private prop = 7; foo() { this[`prop`] = 10; } }\n}\nnamespace N11 {\nclass A { private prop = 7; foo() { this['prop']++; } }\n}\nnamespace N12 {\nclass A { private prop = 7; foo() { const k = 'prop'; this[k] = 10; } }\n}"), options: {"onlyInlineLambdas": true} }, - { ...typed("prefer-readonly", "namespace N0 {\nclass A { constructor(private a: number) {} }\n}\nnamespace N1 {\nclass A { constructor(private a = () => 1) {} }\n}\nnamespace N2 {\nclass A { private a = () => 1; }\n}\nnamespace N3 {\nclass A { private a = (() => 1); }\n}\nnamespace N4 {\nclass A { private a = function () {}; }\n}"), options: {"onlyInlineLambdas": true} }, - typed("prefer-reduce-type-parameter", "namespace N0 {\nlet m = 'reduce'; [1, 2][m]((a: number[], s: number) => a.concat(s), [] as number[]);\n}\nnamespace N1 {\nconst m = 'reduce'; [1, 2][m]((a: number[], s: number) => a.concat(s), [] as number[]);\n}\nnamespace N2 {\ndeclare const m: 'reduce'; [1, 2][m]((a: number[], s: number) => a.concat(s), [] as number[]);\n}"), - typed("prefer-nullish-coalescing", "namespace N0 {\ndeclare let a: string | null, b: string | null, c: string, d: string; a || b;\n}\nnamespace N1 {\ndeclare let a: string | null, b: string | null, c: string, d: string; a || b || c;\n}\nnamespace N2 {\ndeclare let a: string | null, b: string | null, c: string, d: string; a || b && c;\n}\nnamespace N3 {\ndeclare let a: string | null, b: string | null, c: string, d: string; a && b || c;\n}\nnamespace N4 {\ndeclare let a: string | null, b: string | null, c: string, d: string; (a && b) || c;\n}\nnamespace N5 {\ndeclare let a: string | null, b: string | null, c: string, d: string; a || (b && c);\n}\nnamespace N6 {\ndeclare let a: string | null, b: string | null, c: string, d: string; (a || b) && c;\n}\nnamespace N7 {\ndeclare let a: string | null, b: string | null, c: string, d: string; c && (a || b);\n}\nnamespace N8 {\ndeclare let a: string | null, b: string | null, c: string, d: string; c && a || b;\n}\nnamespace N9 {\ndeclare let a: string | null, b: string | null, c: string, d: string; a || b ? c : d;\n}\nnamespace N10 {\ndeclare let a: string | null, b: string | null, c: string, d: string; a /* x */ || /* y */ b;\n}\nnamespace N11 {\ndeclare let a: string | null, b: string | null, c: string, d: string; a ||= b;\n}\nnamespace N12 {\ndeclare let a: string | null, b: string | null, c: string, d: string; (a || b) || c;\n}\nnamespace N13 {\ndeclare let a: string | null, b: string | null, c: string, d: string; a || (b || c);\n}\nnamespace N15 {\ndeclare let a: string | null, b: boolean, c: boolean, d: string; const x = b || c || a;\n}\nnamespace N16 {\ndeclare let a: string | null, b: string | null, c: string, d: string; f(a || b || c || d); declare function f(x: string): void;\n}"), - typed("no-unnecessary-template-expression", "namespace N0 {\nconst a = `x ${' '}\r\ny`;\n}\nnamespace N1 {\nconst a = `x ${' '}\ny`;\n}\nnamespace N2 {\nconst a = `x ${' '}\ry`;\n}\nnamespace N3 {\nconst a = `x ${' '}\ny`;\n}\nnamespace N4 {\nconst a = `x ${' '} y`;\n}"), + typed( + "no-meaningless-void-operator", + "let r;\nvoid (() => {})();\nfunction g() {}\nvoid g();\nvoid g2();\nfunction g2() {}\nvoid/* c */g3();\nfunction g3() {}\nvoid\ng4();\nfunction g4() {}\nfunction g5(): never { throw 1; }\nvoid g5();\nr = void g6();\nfunction g6() {}\nvoid void g7();\nfunction g7() {}\nvoid (g8());\nfunction g8() {}\ndeclare const u: undefined;\nvoid u;\nexport {};", + ), + // Cases that tsgolint doesn't fix or only has a suggestion for, and where it inserts `async`. + typed( + "promise-function-async", + 'const a = function (p: Promise) { return p; };\nfunction b(p: Promise) { return p; }\nexport function c(p: Promise) { return p; }\nexport default function d(p: Promise) { return p; }\nconst e = (p: Promise) => p;\nconst f = { g(p: Promise) { return p; }, h: function (p: Promise) { return p; }, i: (p: Promise) => p, ["j"](p: Promise) { return p; } };\nclass K { l(p: Promise) { return p; } public m(p: Promise) { return p; } static n(p: Promise) { return p; } public static o(p: Promise) { return p; } ["q"](p: Promise) { return p; } r = (p: Promise) => p; }\nfunction s(p: boolean) { return p ? Promise.resolve(5) : 5; }\nexport function t(p: boolean) { return p ? Promise.resolve(5) : 5; }\nconst u = (p: boolean) => (p ? Promise.resolve(5) : 5);\nfunction v(p: boolean): Promise | number { return p ? Promise.resolve(5) : 5; }\nfunction w(p: boolean): Promise | Promise { return p ? Promise.resolve(5) : Promise.resolve(""); }\nx(function (p: Promise) { return p; });\ndeclare function x(a: unknown): void;\n function y(p: Promise) { return p; }\n/* z */ function z(p: Promise) { return p; }\ndeclare const dec: any;\nclass A1 { @dec b1(p: Promise) { return p; } }\nclass A2 { /* c */ b2(p: Promise) { return p; } }\nabstract class A3 { protected b3(p: Promise) { return p; } override toString(): any { return Promise.resolve(); } }\nexport {};', + ), + typed( + "prefer-readonly", + 'class A { private a: number; }\nclass B { #b: number; }\nclass C { private c = 1; }\nclass D { private d: number; constructor() { this.d = 1; } }\nclass E { private [Symbol.iterator] = 7; }\nclass F { private [1] = 7; }\nclass G { private ["g"] = 7; }\nclass H { private "h" = 7; }\nclass I { private 1 = 7; }\nclass J { private static j: number; }\nclass K { private static k = 1; }\nclass L { constructor(private l: number) {} }\nclass M { private m?: number; }\nclass N { private declare n: number; }\nclass O { private o!: number; }\nclass P { private p: number | undefined; q() { return this.p; } }\nexport {};', + ), + typed( + "prefer-string-starts-ends-with", + "declare const s: string;\ns.match(/^bar/) !== undefined;\ns.match(/^bar/) === undefined;\ns.match(/^bar/) != undefined;\ns.match(/^bar/) == undefined;\ns.match(/^bar/) !== null;\ns.match(/^bar/) === null;\ns.match(/^bar/) != null;\ns.match(/^bar/) == null;\nconst m = undefined;\ns.match(/^bar/) === m;\nconst n = null;\ns.match(/^bar/) === n;\nconst o = null;\ns.match(/^bar/) != o;\ns.match(/bar$/) !== void 0;\nnull !== s.match(/^bar/);\nundefined !== s.match(/^bar/);\nexport {};", + ), + typed( + "no-unnecessary-type-assertion", + 'enum E { A, B }\nenum S { A = "a" }\ndeclare const e: E, n: number, s: S, k: "A" | "B", eu: E | undefined, nu: number | undefined;\nexport const a1 = e as number;\nexport const a2 = n as E;\nexport const a3 = E[k] as number;\nexport const a4 = (1 as number) as E;\nexport const a5 = eu as number | undefined;\nexport const a6 = nu as E | undefined;\nexport const a7 = e;\nexport const a8 = n;\nexport const a9 = E[n as E];\nexport const b1 = s as string;\nexport const b2: number = e as number;\nexport const b3: E = n as E;\ndeclare function f(x: number): void; declare function g(x: E): void;\nf(e as number);\ng(n as E);\nexport const b4 = E.A as number;\nexport const b5 = E.A as E;\nexport const b6 = e as E;\nexport const b7 = [e as number];\nexport const b8 = { c: e as number };\nexport function b9(): number { return e as number; }', + ), + typed( + "no-unnecessary-type-assertion", + 'type V = string | undefined;\nexport function n1(value: V, c: boolean) { value = c ? (value as string) : ""; return value.length; }\nexport function n2(value: V) { value = (console.log(), value as string); return value.length; }\nexport function n3(value: V) { [value] = [value as string]; return value.length; }\nexport function n4(value: V) { ({ value } = { value: value as string }); return value.length; }\nexport function n5(value: V) { ({ value } = { ...{ value: value as string } }); return value.length; }\nexport function n7(value: V, other: string) { value = other && (value as string); return value.length; }\nexport function n8(value: V, other: V) { value = other ?? (value as string); return value.length; }\nexport function n9(value: V, other: string) { value = (value as string) || other; return value.length; }\nexport function m1(value: V) { value = value as string; return value.length; }\nexport function m2(value: V, o: { v: V }) { o.v = value as string; }\nexport function m3(value: V) { const x: V = value as string; return x; }\nexport function m4(value: V, f: (a?: string) => void) { f(value as string); }\nexport function m5(value: V) { let y: V; y = [value as string][0]; return y; }\nexport function m6(value: V) { let y: { v?: string }; y = { v: value as string }; return y; }\nexport function m7(value: V, c: boolean) { value = c ? (value as V) : ""; return value; }\nexport function m8(value: V) { let y: V; y = (value as string) ?? ""; return y; }\nexport function m9(value: V) { let y: V; [y] = [value as V]; return y; }\nexport function p1(o: T) { (o as { a: number }).a = 1; }\nexport function p2(o: T) { (o as { a: { b: number } }).a.b++; }\nexport function p3(o: T) { return (o as { a: number }).a; }\nexport function p4(o: T) { return (o as T).a; }', + ), + // no-unused-vars: oxlint has its own fixer, and a `fix` option that sets the kind of fix for imports and variables. + { + rule: "no-unused-vars", + file: "a.ts", + text: "import a from 'm1';\nimport b, { c, d } from 'm2';\nimport e, * as f from 'm3';\nimport { g, h /* i */, j } from 'm4';\nimport k = require('m5');\nimport { l, m } from 'm6';\nc; e; h;\n", + }, + { + rule: "no-unused-vars", + file: "a.ts", + text: "let a = 1;\nvar b = 1, c = 2, d = 3;\nlet e = 1; e = 2;\nconst { f, g } = c, [h, i, ...j] = c;\nconst [k, ...[l]] = c;\nfor (const n of c) {}\ntry {} catch (o) {}\nfunction p(q: number, _q: number): q is 1 { return _q; }\nconst r = () => {};\nconst s = c(); (b, s, d);\nb; d; g; i; k; p;\n", + }, + { + rule: "no-unused-vars", + file: "a.ts", + text: "import a from 'm1';\nimport b, { c, d } from 'm2';\nimport e, * as f from 'm3';\nimport { g, h /* i */, j } from 'm4';\nimport k = require('m5');\nimport { l, m } from 'm6';\nc; e; h;\nlet n = 1;\n", + options: { fix: { imports: "safe-fix", variables: "off" } }, + }, + { + rule: "no-unused-vars", + file: "a.ts", + text: "import a from 'm1';\nimport b, { c, d } from 'm2';\nimport e, * as f from 'm3';\nimport { g, h /* i */, j } from 'm4';\nimport k = require('m5');\nimport { l, m } from 'm6';\nc; e; h;\nlet n = 1; let o = 1; o = 2;\n", + options: { fix: { imports: "fix", variables: "fix" }, varsIgnorePattern: "^_" }, + }, + { + rule: "no-unused-vars", + file: "a.ts", + text: "import a from 'm1';\nimport b, { c, d } from 'm2';\nimport e, * as f from 'm3';\nimport { g, h /* i */, j } from 'm4';\nimport k = require('m5');\nimport { l, m } from 'm6';\nc; e; h;\ntry {} catch (n) {}\n", + options: { fix: { imports: "off" } }, + }, + { + rule: "no-unused-vars", + file: "a.ts", + text: "import _a, { b } from 'm';\nconst _c = 1; _a; _c;\ntry {} catch (_d) { _d; }\n", + options: { reportUsedIgnorePattern: true, varsIgnorePattern: "^_", caughtErrorsIgnorePattern: "^_" }, + }, + // Chains and the expressions after them: which ones tsgolint fixes, only has a suggestion for, or doesn't touch. + // Cases where tsgolint's output is broken code are excluded. + typed( + "prefer-optional-chain", + 'declare const foo: { bar: { baz: { buzz: number } | undefined } | undefined } | undefined;\ndeclare const nul: { bar: { baz: number } | null } | null;\ndeclare const both: { bar: { baz: number } | null | undefined } | null | undefined;\nfoo === undefined || foo.bar === undefined || foo.bar.baz === undefined || foo.bar.baz.buzz === undefined;\nfoo === undefined || foo.bar === undefined;\nfoo === undefined || !foo.bar;\nfoo === undefined || foo.bar === 1;\nfoo !== undefined && foo.bar !== undefined;\nfoo !== undefined && foo.bar !== undefined && foo.bar.baz;\nfoo !== undefined && foo.bar;\nnul === null || nul.bar === null;\nnul === null || nul.bar === null || nul.bar.baz === 1;\nnul !== null && nul.bar !== null;\nnul !== null && nul.bar;\nboth == null || both.bar == null;\nboth == null || both.bar == null || both.bar.baz === 1;\nboth != null && both.bar != null;\nboth != null && both.bar;\n!foo || !foo.bar;\n!foo || !foo.bar || !foo.bar.baz;\nfoo && foo.bar;\nfoo && foo.bar && foo.bar.baz;\ntypeof foo === "undefined" || foo.bar === undefined;\nfoo == undefined || foo.bar == undefined;\nexport {};', + ), + typed( + "prefer-optional-chain", + "declare const foo: { bar: { baz: number | undefined } | undefined } | undefined;\ndeclare const both: { bar: { baz: number } | null | undefined } | null | undefined;\ndeclare const c: { d: number };\nfoo && foo.bar && foo.bar.baz === 1;\nfoo && foo.bar && foo.bar.baz !== 1;\nfoo && foo.bar && foo.bar.baz == null;\nfoo && foo.bar && foo.bar.baz != null;\nfoo && foo.bar && foo.bar.baz === undefined;\nfoo && foo.bar && foo.bar.baz !== undefined;\nfoo && foo.bar && foo.bar.baz > 1;\nboth != null && both.bar != null && both.bar.baz === 1;\nboth != null && both.bar != null && both.bar.baz !== 1;\nboth != null && both.bar != null && both.bar.baz > 1;\nboth == null || both.bar == null || both.bar.baz === 1;\nboth == null || both.bar == null || both.bar.baz !== 1;\nboth == null || both.bar == null || both.bar.baz > 1;\nboth == null || both.bar == null || both.bar.baz == null;\nboth == null || both.bar == null || both.bar.baz === undefined;\nboth == null || both.bar == null || c.d === 1;\nboth == null || both.bar == null || c.d === 1 || both.bar.baz === 1;\n!foo || !foo.bar || foo.bar.baz === 1;\n!foo || !foo.bar || foo.bar.baz !== 1;\n!foo || !foo.bar || foo.bar.baz > 1;\n!both || !both.bar || both.bar.baz === c.d;\n!both || !both.bar || both.bar.baz !== c.d;\nboth == null || both.bar == null || both.bar.baz === 1 || both.bar.baz === 2;\nexport {};", + ), + typed( + "prefer-optional-chain", + 'declare const foo: { bar: { baz: number | undefined | null } | undefined } | undefined;\ndeclare const both: { bar: { baz: number | null } | null | undefined } | null | undefined;\nfoo && foo.bar && !foo.bar.baz;\nfoo && foo.bar && foo.bar.baz === null;\nfoo && foo.bar && foo.bar.baz !== null;\nfoo && foo.bar && typeof foo.bar.baz === "undefined";\nfoo && foo.bar && typeof foo.bar.baz !== "undefined";\n!foo || !foo.bar || foo.bar.baz;\n!foo || !foo.bar || foo.bar.baz != null;\n!foo || !foo.bar || foo.bar.baz !== undefined;\n!foo || !foo.bar || foo.bar.baz !== null;\n!foo || !foo.bar || foo.bar.baz === null;\n!foo || !foo.bar || foo.bar.baz == null;\n!foo || !foo.bar || foo.bar.baz === undefined;\nboth == null || both.bar == null || both.bar.baz != null;\nboth == null || both.bar == null || both.bar.baz;\nboth == null || both.bar == null || !both.bar.baz;\nboth != null && both.bar != null && both.bar.baz == null;\nboth != null && both.bar != null && !both.bar.baz;\nboth != null && both.bar != null && both.bar.baz;\nboth != null && both.bar != null && both.bar.baz != null;\nfoo && foo.bar && !foo.bar.baz && foo.bar.baz === 1;\nfoo && foo.bar && foo.bar.baz === null && 1;\nexport {};', + ), + typed( + "prefer-optional-chain", + 'declare const a: { b: { c: number } | null } | undefined;\ndeclare const foo: { bar: { baz: number | undefined | null } | undefined } | undefined;\ndeclare const both: { bar: { baz: number | null } | null | undefined } | null | undefined;\na && a.b !== null;\na && a.b !== null && a.b.c;\n!a || a.b === null;\n!a || a.b === null || !a.b.c;\n!foo || !foo.bar || typeof foo.bar.baz !== "undefined";\nboth != null && both.bar != null && typeof both.bar.baz === "undefined";\nboth != null && both.bar != null && typeof both.bar.baz !== "undefined";\nboth == null || both.bar == null || typeof both.bar.baz !== "undefined";\nfoo && typeof foo.bar === "undefined";\nfoo && typeof foo.bar !== "undefined";\n!foo || typeof foo.bar !== "undefined";\nfoo && foo.bar !== null;\n!foo || foo.bar === null;\nfoo && foo.bar === null;\n!foo || foo.bar !== null;\nfoo && foo.bar && "undefined" === typeof foo.bar.baz;\nfoo && foo.bar && null !== foo.bar.baz;\nfoo && foo.bar && undefined === foo.bar.baz;\nexport {};', + ), + // A call's type when it has no contextual type, and `as any` on a property that only some members of a union declare. + typed( + "no-unnecessary-type-assertion", + 'type El = HTMLElement; type In = HTMLInputElement;\ntype Fn = (c: El, id: string) => T;\ntype Cond = T extends string ? number : string;\ntype Via = Parameters>;\ntype Box = { v: T };\ndeclare function f1(...a: Parameters>): T;\ndeclare function f2(a: Cond): T;\ndeclare function f3(a: T extends In ? number : string): T;\ndeclare function f4(...a: Via): T;\ndeclare function f5(a: T["id"]): T;\ndeclare function f6(a: keyof T): T;\ndeclare function f7(a: Partial): T;\ndeclare function f8(a: Box): T;\ndeclare function f9(a: (x: T) => void): T;\ndeclare function g1(a: string, b?: T): T;\ndeclare function g2(a: string, ...b: T[]): T;\ndeclare function g3(a: ReturnType>): T;\ndeclare function g4(a: NonNullable): T;\ndeclare function g5(a: Exclude): T;\ndeclare function g6(a: Awaited): T;\ndeclare function g7(a: Readonly): T;\ndeclare function g8(a: Pick): T;\ndeclare const el: El, inp: In;\nexport const a1 = f1(el, "a") as In;\nexport const a2 = f2("a") as In;\nexport const a3 = f3("a") as In;\nexport const a4 = f4(el, "a") as In;\nexport const a5 = f5("a") as In;\nexport const a6 = f6("id") as In;\nexport const a7 = f7({}) as In;\nexport const a8 = f8({ v: inp }) as In;\nexport const a9 = f9(() => {}) as In;\nexport const b1 = g1("a") as In;\nexport const b2 = g2("a") as In;\nexport const b3 = g3(inp) as In;\nexport const b4 = g4(inp) as In;\nexport const b5 = g5(inp) as In;\nexport const b6 = g6(inp) as In;\nexport const b8 = g8({ id: "a" }) as In;\nexport const c1 = g1("a", inp) as In;\nexport const c2 = g2("a", inp) as In;', + ), + typed( + "no-unnecessary-type-assertion", + 'import type { ClientBase } from "pg";\ninterface Config { dir: string }\ninterface WithUrl { databaseUrl: string }\ninterface WithClient { dbClient: ClientBase }\ninterface Known { dbClient: { query(): void } }\ninterface WithAny { dbClient: any }\ndeclare function r1(o: Config & (WithClient | WithUrl)): void;\ndeclare function r2(o: Config & WithClient): void;\ndeclare function r3(o: (Config & WithClient) | (Config & WithUrl)): void;\ndeclare function r4(o: Config & (Known | WithUrl)): void;\ndeclare function r5(o: Config & (WithAny | WithUrl)): void;\ndeclare function r6(o: Config & (WithAny | WithUrl)): void;\ndeclare const u: unknown, n: number;\nr1({ dbClient: u as ClientBase, dir: "a" });\nr2({ dbClient: u as ClientBase, dir: "a" });\nr3({ dbClient: u as ClientBase, dir: "a" });\nr4({ dbClient: u as { query(): void }, dir: "a" });\nr5({ dbClient: u as any, dir: "a" });\nr6({ dbClient: n as any, dir: "a" });\nr1({ dbClient: n as number, dir: "a" });\nr1({ dbClient: n as unknown as ClientBase, dir: "a" });\nr5({ dbClient: n as unknown as any, dir: "a" });\nr5({ dbClient: n as unknown as string, dir: "a" });', + ), + // tsgolint's exact output: a node starts at the end of the previous token, parentheses are nodes, and a computed name + // is resolved from its type. + typed( + "no-array-delete", + 'namespace N0 {\ndeclare const a: number[]; delete a[0];\n}\nnamespace N1 {\ndeclare const a: number[]; delete a[0, 1];\n}\nnamespace N2 {\ndeclare const a: number[]; delete a.length;\n}\nnamespace N3 {\ndeclare const a: number[]; delete (a)[0];\n}\nnamespace N4 {\ndeclare const a: number[]; delete a [ 0 ] ;\n}\nnamespace N5 {\ndeclare const a: number[]; delete a["x"];\n}\nnamespace N6 {\ndeclare const a: number[]; delete/* b */a[0];\n}\nnamespace N7 {\ndeclare const a: number[][]; delete a[0][1];\n}\nnamespace N8 {\ndeclare const a: number[]; delete a![0];\n}\nnamespace N9 {\ndeclare const a: number[]; delete (a as number[])[0];\n}\nnamespace N10 {\ndeclare const a: number[]; void delete a[0];\n}', + ), + typed( + "no-misused-spread", + "namespace N0 {\ndeclare const m: Map; const o = { ...m };\n}\nnamespace N1 {\ndeclare const m: Map; const o = { ...m, };\n}\nnamespace N2 {\ndeclare const m: Map; const o = {...m};\n}\nnamespace N3 {\ndeclare const m: Map; const o = { a: 1, ...m };\n}\nnamespace N4 {\ndeclare const m: Map; const o = { .../* c */m /* d */ };\n}\nnamespace N5 {\ndeclare const m: Map; const o = ({ ...m });\n}\nnamespace N6 {\ndeclare const m: Map; f({ ...m }); declare function f(x: object): void;\n}\nnamespace N7 {\ndeclare const m: Map; const o = { ...m as Map };\n}\nnamespace N8 {\ndeclare const m: Map; const o = { ...(m) , };\n}\nnamespace N9 {\ndeclare const p: Promise<{a: 1}>; async function f() { return { ...p }; }\n}\nnamespace N10 {\ndeclare const p: Promise<{a: 1}>, q: boolean; async function f() { return { ...(q ? p : p) }; }\n}\nnamespace N11 {\ndeclare const p: Promise<{a: 1}>, q: boolean; async function f() { return { ...q ? p : p }; }\n}", + ), + typed( + "no-confusing-void-expression", + "namespace N0 {\nconst a = () => console.log(1);\n}\nnamespace N1 {\nconst a = () => (console.log(1));\n}\nnamespace N2 {\nconst a = () => ((console.log(1)));\n}\nnamespace N3 {\nconst a = () => /* c */ console.log(1);\n}\nnamespace N4 {\nconst a = () => console.log(1) /* d */;\n}\nnamespace N5 {\nconst a = () =>\n console.log(1);\n}\nnamespace N6 {\nconst a = (): number => console.log(1) as any;\n}\nnamespace N7 {\nf(() => console.log(1)); declare function f(x: () => void): void;\n}\nnamespace N8 {\nfunction f() { return console.log(1); }\n}\nnamespace N9 {\nfunction f() { return console.log(1) }\n}\nnamespace N10 {\nfunction f() { return (console.log(1)); }\n}\nnamespace N11 {\nfunction f() { return /* c */ console.log(1); }\n}\nnamespace N12 {\nfunction f(c: boolean) { if (c) return console.log(1); f(c); }\n}\nnamespace N13 {\nfunction f(c: boolean) { if (c) { return console.log(1); } f(c); }\n}\nnamespace N14 {\nfunction f(c: boolean) { if (c) { return console.log(1) } f(c); }\n}\nnamespace N15 {\nfunction f(c: boolean) { if (c) return console.log(1)\nf(c); }\n}\nnamespace N16 {\nfunction f() { g()\nreturn [1].forEach(console.log) }\ndeclare function g(): void;\n}\nnamespace N17 {\nfunction f() { g()\nreturn (console.log(1)) }\ndeclare function g(): void;\n}\nnamespace N18 {\nfunction f(c: boolean) { g()\nif (c) { return [1].forEach(console.log) } g() }\ndeclare function g(): void;\n}\nnamespace N19 {\nfunction f() { return `a`.length ? console.log(1) : console.log(2); }\n}\nnamespace N20 {\nconst x = console.log(1);\n}\nnamespace N21 {\nfunction f(): number { return console.log(1) as any; }\n}\nnamespace N22 {\nfunction f(c: boolean) { label: return console.log(1); }\n}\nnamespace N23 {\nfunction f(c: boolean) { switch (c) { case true: return console.log(1); } }\n}\nnamespace N24 {\nfunction f(c: boolean) { try { return console.log(1); } finally {} }\n}", + ), + typed( + "no-unnecessary-type-conversion", + "namespace N0 {\nconst arr = ['asdf']; arr[0] += '';\n}\nnamespace N1 {\nconst obj = { prop: 'asdf' }; obj.prop += '';\n}\nnamespace N2 {\nlet s = 'asdf'; s += '';\n}\nnamespace N3 {\nlet s = 'asdf'; (s) += '';\n}\nnamespace N4 {\n'asdf'.toString(console.log('extra'));\n}\nnamespace N5 {\nString('asdf', console.log('extra'));\n}\nnamespace N6 {\nString('asdf');\n}\nnamespace N7 {\n'asdf'.toString();\n}\nnamespace N8 {\nNumber(1, 2);\n}\nnamespace N9 {\nBoolean(true, 1);\n}\nnamespace N10 {\nBigInt(1n, 2);\n}\nnamespace N11 {\nfunction f(x: T) { return x + ''; }\n}\nnamespace N12 {\nfunction f(x: T) { return '' + x; }\n}\nnamespace N13 {\nfunction f(x: T) { x += ''; return x; }\n}\nnamespace N14 {\nfunction f(x: T) { return +x; }\n}\nnamespace N15 {\nfunction f(x: T) { return !!x; }\n}\nnamespace N16 {\nfunction f(x: T) { return ~~x; }\n}\nnamespace N17 {\nfunction f(x: T) { return String(x); }\n}\nnamespace N18 {\nfunction f(x: T) { return x.toString(); }\n}\nnamespace N19 {\nfunction f(x: T) { return String(x); }\n}\nnamespace N20 {\nfunction f(x: T) { return String(x); }\n}\nnamespace N21 {\nfunction f(x: T) { return Number(x); }\n}\nnamespace N22 {\nfunction f(x: T) { return BigInt(x); }\n}\nnamespace N23 {\nfunction f(x: string & { a: 1 }) { return String(x); }\n}", + ), + { + ...typed( + "dot-notation", + "namespace N0 {\nclass E { private _b = 0; public get priv(): number { return this._b; } private set priv(v: number) { this._b = v; } }\ndeclare const obj: E;\nobj['priv'] = 1;\n}\nnamespace N1 {\nclass E { private _b = 0; public get priv(): number { return this._b; } private set priv(v: number) { this._b = v; } }\ndeclare const obj: E;\nobj['priv'];\n}\nnamespace N2 {\nclass E { private _b = 0; private set priv(v: number) { this._b = v; } public get priv(): number { return this._b; } }\ndeclare const obj: E;\nobj['priv'];\n}\nnamespace N3 {\nclass E { private _b = 0; private set priv(v: number) { this._b = v; } public get priv(): number { return this._b; } }\ndeclare const obj: E;\nobj['priv'] = 1;\n}\nnamespace N4 {\nclass E { private _b = 0; public get priv(): number { return this._b; } private set priv(v: number) { this._b = v; } }\ndeclare const obj: E;\nobj['priv'] += 1;\n}\nnamespace N5 {\nclass E { private _b = 0; public get priv(): number { return this._b; } private set priv(v: number) { this._b = v; } }\ndeclare const obj: E;\nobj['priv']++;\n}\nnamespace N6 {\nclass E { private _b = 0; public get priv(): number { return this._b; } private set priv(v: number) { this._b = v; } }\ndeclare const obj: E;\n[obj['priv']] = [1];\n}\nnamespace N7 {\nclass E { private _b = 0; public get priv(): number { return this._b; } private set priv(v: number) { this._b = v; } }\ndeclare const obj: E;\ndelete obj['priv'];\n}\nnamespace N8 {\nclass E { private p = 0; }\ndeclare const obj: E;\nobj['p'] = 1; obj['p'];\n}\nnamespace N9 {\nclass E { public p = 0; }\ndeclare const obj: E;\nobj['p'] = 1; obj['p'];\n}", + ), + options: { "allowPrivateClassPropertyAccess": true }, + }, + typed( + "use-unknown-in-catch-callback-variable", + "namespace N0 {\nlet method = 'catch'; Promise.resolve()[method]((error: Error) => {});\n}\nnamespace N1 {\nconst method = 'catch'; Promise.resolve()[method]((error: Error) => {});\n}\nnamespace N2 {\nPromise.resolve()['catch']((error: Error) => {});\n}\nnamespace N3 {\nPromise.resolve()[`catch`]((error: Error) => {});\n}\nnamespace N4 {\nPromise.resolve().catch((error: Error) => {});\n}\nnamespace N5 {\nlet method = 'then'; Promise.resolve()[method](() => {}, (error: Error) => {});\n}\nnamespace N6 {\ndeclare const method: 'catch'; Promise.resolve()[method]((error: Error) => {});\n}\nnamespace N7 {\ndeclare const method: 'catch' | 'then'; Promise.resolve()[method]((error: Error) => {});\n}", + ), + typed( + "prefer-readonly", + "namespace N0 {\nclass A { private a: number; }\n}\nnamespace N1 {\nclass A { #a: number; }\n}\nnamespace N2 {\nclass A { private a = 1; }\n}\nnamespace N3 {\nclass A { private a: number; constructor() { this.a = 1; } }\n}\nnamespace N4 {\nclass A { private a?: number; }\n}\nnamespace N5 {\nclass A { private a!: number; }\n}\nnamespace N6 {\nclass A { private static a: number; }\n}\nnamespace N7 {\nclass A { private prop = 7; foo() { this['prop'] = 10; } }\n}\nnamespace N8 {\nclass A { private 'prop' = 7; foo() { this.prop = 10; } }\n}\nnamespace N9 {\nclass A { private 'prop' = 7; foo() { this['prop'] = 10; } }\n}\nnamespace N10 {\nclass A { private prop = 7; foo() { this[`prop`] = 10; } }\n}\nnamespace N11 {\nclass A { private prop = 7; foo() { this['prop']++; } }\n}\nnamespace N12 {\nclass A { private prop = 7; foo() { const k = 'prop'; this[k] = 10; } }\n}", + ), + { + ...typed( + "prefer-readonly", + "namespace N0 {\nclass A { private a: number; }\n}\nnamespace N1 {\nclass A { #a: number; }\n}\nnamespace N2 {\nclass A { private a = 1; }\n}\nnamespace N3 {\nclass A { private a: number; constructor() { this.a = 1; } }\n}\nnamespace N4 {\nclass A { private a?: number; }\n}\nnamespace N5 {\nclass A { private a!: number; }\n}\nnamespace N6 {\nclass A { private static a: number; }\n}\nnamespace N7 {\nclass A { private prop = 7; foo() { this['prop'] = 10; } }\n}\nnamespace N8 {\nclass A { private 'prop' = 7; foo() { this.prop = 10; } }\n}\nnamespace N9 {\nclass A { private 'prop' = 7; foo() { this['prop'] = 10; } }\n}\nnamespace N10 {\nclass A { private prop = 7; foo() { this[`prop`] = 10; } }\n}\nnamespace N11 {\nclass A { private prop = 7; foo() { this['prop']++; } }\n}\nnamespace N12 {\nclass A { private prop = 7; foo() { const k = 'prop'; this[k] = 10; } }\n}", + ), + options: { "onlyInlineLambdas": true }, + }, + { + ...typed( + "prefer-readonly", + "namespace N0 {\nclass A { constructor(private a: number) {} }\n}\nnamespace N1 {\nclass A { constructor(private a = () => 1) {} }\n}\nnamespace N2 {\nclass A { private a = () => 1; }\n}\nnamespace N3 {\nclass A { private a = (() => 1); }\n}\nnamespace N4 {\nclass A { private a = function () {}; }\n}", + ), + options: { "onlyInlineLambdas": true }, + }, + typed( + "prefer-reduce-type-parameter", + "namespace N0 {\nlet m = 'reduce'; [1, 2][m]((a: number[], s: number) => a.concat(s), [] as number[]);\n}\nnamespace N1 {\nconst m = 'reduce'; [1, 2][m]((a: number[], s: number) => a.concat(s), [] as number[]);\n}\nnamespace N2 {\ndeclare const m: 'reduce'; [1, 2][m]((a: number[], s: number) => a.concat(s), [] as number[]);\n}", + ), + typed( + "prefer-nullish-coalescing", + "namespace N0 {\ndeclare let a: string | null, b: string | null, c: string, d: string; a || b;\n}\nnamespace N1 {\ndeclare let a: string | null, b: string | null, c: string, d: string; a || b || c;\n}\nnamespace N2 {\ndeclare let a: string | null, b: string | null, c: string, d: string; a || b && c;\n}\nnamespace N3 {\ndeclare let a: string | null, b: string | null, c: string, d: string; a && b || c;\n}\nnamespace N4 {\ndeclare let a: string | null, b: string | null, c: string, d: string; (a && b) || c;\n}\nnamespace N5 {\ndeclare let a: string | null, b: string | null, c: string, d: string; a || (b && c);\n}\nnamespace N6 {\ndeclare let a: string | null, b: string | null, c: string, d: string; (a || b) && c;\n}\nnamespace N7 {\ndeclare let a: string | null, b: string | null, c: string, d: string; c && (a || b);\n}\nnamespace N8 {\ndeclare let a: string | null, b: string | null, c: string, d: string; c && a || b;\n}\nnamespace N9 {\ndeclare let a: string | null, b: string | null, c: string, d: string; a || b ? c : d;\n}\nnamespace N10 {\ndeclare let a: string | null, b: string | null, c: string, d: string; a /* x */ || /* y */ b;\n}\nnamespace N11 {\ndeclare let a: string | null, b: string | null, c: string, d: string; a ||= b;\n}\nnamespace N12 {\ndeclare let a: string | null, b: string | null, c: string, d: string; (a || b) || c;\n}\nnamespace N13 {\ndeclare let a: string | null, b: string | null, c: string, d: string; a || (b || c);\n}\nnamespace N15 {\ndeclare let a: string | null, b: boolean, c: boolean, d: string; const x = b || c || a;\n}\nnamespace N16 {\ndeclare let a: string | null, b: string | null, c: string, d: string; f(a || b || c || d); declare function f(x: string): void;\n}", + ), + typed( + "no-unnecessary-template-expression", + "namespace N0 {\nconst a = `x ${' '}\r\ny`;\n}\nnamespace N1 {\nconst a = `x ${' '}\ny`;\n}\nnamespace N2 {\nconst a = `x ${' '}\ry`;\n}\nnamespace N3 {\nconst a = `x ${' '}\ny`;\n}\nnamespace N4 {\nconst a = `x ${' '} y`;\n}", + ), typed("dot-notation", "declare const foo: { bar: 1 };\nfoo[/* c */ 'bar'];\nfoo['bar' /* c */];"), - { ...typed("dot-notation", "declare const foo: { while: 1 };\nfoo./* c */ while;"), options: { allowKeywords: false } }, + { + ...typed("dot-notation", "declare const foo: { while: 1 };\nfoo./* c */ while;"), + options: { allowKeywords: false }, + }, typed("prefer-includes", "function f(a?: string, b = '') {\n a?.indexOf(b) === -1;\n a?.indexOf(b) !== -1;\n}"), - // `a && a.b.c()` is `a?.b?.c()` for tsgolint, and what starts with a chain is left alone. - typed("prefer-optional-chain", "declare const a: { b: { c: { d: number; e(): { f: number } }; g(): { h: number }; [k: string]: any } } | null;\ndeclare const p: any, u: unknown, k: string, rel: string;\ndeclare const attr: { value: string | null } | null;\na && a.b.c;\na && a.b.c.d;\na && a.b.g();\na && a.b.c.e();\na && a.b.c.e().f;\na && a.b.g().h;\na && a.b[k];\na && a.b[k].c;\na && a[\"b\"].c;\na && a.b;\na && a.b && a.b.c.d;\na && a.b.c && a.b.c.d;\na != null && a.b.c.d;\n!a || !a.b.c;\n!a || !a.b.c.d;\n!a || a.b.c.d === 1;\na && a.b.c.d === 1;\na && a.b!.c;\na && a.b.c!.d;\na && (a.b).c;\na && (a.b.c).d;\nif (p && p.id) { k; }\nif (p && p.id.x) { k; }\np && p.id && p.id.x;\np && p.id();\nif (attr?.value && (attr.value.toLowerCase() === rel)) { k; }\nif (attr?.value && attr.value.toLowerCase() === rel) { k; }\nif (attr && (attr.value)) { k; }\nif ((attr) && attr.value) { k; }\nif (attr && attr.value && (attr.value.length)) { k; }\nexport {};"), - typed("prefer-optional-chain", "declare const attr: { value: string | null; n: { m: string } | null } | null, rel: string, k: string;\ndeclare const parsed: any, maybe: { id?: string } | undefined, j: ReturnType;\nattr?.value && attr.value.length;\nattr?.value && attr.value.toLowerCase();\nattr?.value && attr.value.length === 1;\nattr?.value && attr.value.toLowerCase() === rel;\nattr?.value && attr?.value.toLowerCase() === rel;\nattr && attr.value && attr.value.toLowerCase() === rel;\nattr && attr.value && attr.value.length === 1;\nattr?.n && attr.n.m;\nattr?.n && attr.n.m === rel;\nattr?.n && attr?.n.m;\nattr?.n != null && attr.n.m;\nattr && attr.value === rel;\nattr && attr.value.length === 1;\nattr && attr.n && attr.n.m === rel;\nif (parsed && parsed.id) { k; }\nif (j && j.id) { k; }\nif (maybe && maybe.id) { k; }\nfunction f(x: unknown) { const q = x as any; if (q && q.id) { k; } }\ntry { k; } catch (e: any) { if (e && e.id) { k; } }\nlet late; late = JSON.parse(k); if (late && late.id) { k; }\nlet typed: any; try { typed = JSON.parse(k); } catch {} if (typed && typed.id) { k; }\nexport {};"), - typed("prefer-optional-chain", "declare const attr: { n: { m: string; o: { p: string } | null } | null | undefined; f?(): { g: string } | null } | null;\nattr?.n !== null && attr.n.m;\nattr?.n !== undefined && attr.n.m;\nattr?.n !== null && attr?.n !== undefined && attr.n.m;\nattr?.n !== null && attr.n !== undefined && attr.n.m;\nattr?.n !== undefined && attr?.n !== null && attr.n.m;\nattr?.n != null && attr.n.m;\nattr?.n != null && attr.n.o != null && attr.n.o.p;\nattr?.n && attr.n.o && attr.n.o.p;\nattr && attr.n?.o && attr.n.o.p;\nattr && attr.n && attr.n?.o;\n!attr?.n || !attr.n.m;\nattr?.n == null || attr.n.m;\nattr?.n == null || !attr.n.m;\nattr?.n == null || attr.n.o == null;\nattr?.n === null || attr.n.o === null;\nattr?.n === undefined || attr.n.o === undefined;\nattr?.f && attr.f();\nattr?.f?.() && attr.f().g;\nattr?.[\"n\"] && attr[\"n\"].m;\n(attr?.n) && attr.n.m;\nattr?.n! && attr.n.m;\nexport {};"), - typed("no-unnecessary-condition", "type Q = { b: { c: { d: number; e?: number }; f(): { g: { h: number } }; i?: { j: number } }; k: () => { l: number } };\ndeclare const q: Q | undefined, nn: Q;\nq?.b.c?.d;\nq?.b.c.d?.toFixed();\nq?.b?.c;\nq?.b?.c?.d;\nq?.b.i?.j;\nq?.b.c.e?.toFixed();\nq?.b.f?.();\nq?.b.f()?.g;\nq?.b.f().g?.h;\nq?.k()?.l;\nq?.k().l?.toFixed();\nq?.k?.();\nnn.b.c?.d;\nnn?.b.c?.d;\nnn.b?.c.d?.toFixed();\n(q?.b.c)?.d;\nq?.b[\"c\"]?.d;\nq?.[\"b\"].c?.d;\nq!.b.c?.d;\nexport {};"), - typed("no-unnecessary-condition", "type L = { s?: { d: boolean; e?: { f: number } }; t: { d: boolean }; u: { d: boolean } | null };\ndeclare function ok(v: unknown): asserts v;\ndeclare let l: L | undefined, m: L, un: { s?: { d: boolean } } | { s: { d: boolean } } | undefined;\nexport function a1() { ok(l?.s); return l?.s?.d; }\nexport function a2() { if (l?.s) { return l?.s?.d; } return 0; }\nexport function a3() { if (l?.s) { return l.s?.d; } return 0; }\nexport function a4() { return l?.t?.d; }\nexport function a5() { return l?.u?.d; }\nexport function a6() { if (l?.u) { return l?.u?.d; } return 0; }\nexport function a7() { if (m.s) { return m.s?.d; } return 0; }\nexport function a8() { if (m.s) { return m?.s?.d; } return 0; }\nexport function a9() { if (l?.s?.e) { return l?.s?.e?.f; } return 0; }\nexport function b1() { return un?.s?.d; }\nexport function b2() { if (un?.s) { return un?.s?.d; } return 0; }\nexport function b3() { const s = l?.s; if (s) { return s?.d; } return 0; }\nexport function b4() { if (l?.s) { return l?.s?.d ?? 1; } return 0; }\nexport function b5() { if (l?.s) { if (l?.s) { return 1; } } return 0; }"), - // Where tsgolint puts parentheses around what moves out of a template, and which of two suggestions that begin at the same place wins. - typed("no-unnecessary-template-expression", "namespace N0 {\ndeclare const s: string; const a = `${s}`;\n}\nnamespace N1 {\ndeclare const s: string; f(`${s}`); declare function f(x: string): void;\n}\nnamespace N2 {\ndeclare const s: string; const a = [`${s}`];\n}\nnamespace N3 {\ndeclare const s: string; const a = [`${s}`, 1];\n}\nnamespace N4 {\ndeclare const s: string; const a = `${s.trim()}`;\n}\nnamespace N5 {\ndeclare const s: string; f(`${s.trim()}`); declare function f(x: string): void;\n}\nnamespace N6 {\ndeclare const s: string; const a = { b: `${s}` };\n}\nnamespace N7 {\ndeclare const s: string; const a = `${s}`.length;\n}\nnamespace N8 {\ndeclare const s: string; const a = `${s + s}`;\n}\nnamespace N9 {\ndeclare const s: string; const a = `${'a'}`;\n}\nnamespace N10 {\ndeclare const s: string; function g() { return `${s}`; }\n}\nnamespace N11 {\ndeclare const s: string; const a = s + `${s}`;\n}\nnamespace N12 {\ndeclare const s: any; const a = [\n `${s as string}`,\n];\n}\nnamespace N13 {\ntype T = string; declare const type: T; const a = [\n `${type}`,\n];\n}\nnamespace N14 {\ndeclare const s: string; const a = `${s.trim()}`.length;\n}\nnamespace N15 {\ndeclare const s: string; const a = s + `${s + s}`;\n}\nnamespace N16 {\ndeclare const s: string; const a = `${s + s}` + s;\n}\nnamespace N17 {\ndeclare const o: { s: string }; f(`${o.s}`); declare function f(x: string): void;\n}\nnamespace N18 {\ndeclare const o: { s: string }; new F(`${o.s}`); declare class F { constructor(x: string); }\n}\nnamespace N19 {\ndeclare const s: string; new F(`${s}`); declare class F { constructor(x: string); }\n}\nnamespace N20 {\ndeclare const s: string; const a = s ? `${s}` : s;\n}\nnamespace N21 {\ndeclare const s: string; const a = s ? `${s + s}` : s;\n}\nnamespace N22 {\ndeclare const s: string; const a = s ? `${s ? s : s}` : s;\n}\nnamespace N23 {\ndeclare const s: string; const a = (`${s}`);\n}\nnamespace N24 {\ndeclare const s: string; const a = (`${s + s}`);\n}\nnamespace N25 {\ndeclare const s: string; const a = `${s}` as string;\n}\nnamespace N26 {\ndeclare const s: any; const a = `${s as string}` as string;\n}\nnamespace N27 {\ndeclare const s: string; const a = typeof `${s}`;\n}\nnamespace N28 {\ndeclare const s: string; const a = typeof `${typeof s}`;\n}\nnamespace N29 {\ndeclare const s: string; const a = [...`${s}`];\n}\nnamespace N30 {\ndeclare const s: string; const a = `${s}`!;\n}\nnamespace N31 {\ndeclare const s: string; let a; a = `${s}`;\n}\nnamespace N32 {\ndeclare const s: string; let a; a = `${a = s}`;\n}\nnamespace N33 {\ndeclare const s: string; const a = `a${`${s}`}`;\n}\nnamespace N34 {\ndeclare const s: string; const a = { [`${s}`]: 1 };\n}\nnamespace N35 {\ndeclare const s: string; const a = () => `${s}`;\n}\nnamespace N36 {\ndeclare const s: string; const a = s || `${s || s}`;\n}\nnamespace N37 {\ndeclare const s: string; const a = s && `${s || s}`;\n}\nnamespace N38 {\ndeclare const s: string; const a = o[`${s}`]; declare const o: Record;\n}\nnamespace N39 {\ndeclare const s: string; const a = o[`${s.trim()}`]; declare const o: Record;\n}\nnamespace N40 {\ndeclare let s: string; const a = () => `${s = s}`;\n}\nnamespace N41 {\ndeclare let s: string; const a = () => `${s ? s : s}`;\n}\nnamespace N42 {\ndeclare let s: string; const a = () => `${s + s}`;\n}\nnamespace N43 {\ndeclare let s: string; const a = () => `${(s, s)}`;\n}\nnamespace N44 {\ndeclare let s: string; const a = `${(s)}`;\n}\nnamespace N45 {\ndeclare let s: string; const a = [`${(s)}`];\n}\nnamespace N46 {\ndeclare let s: string; const a = s || `${s ?? s}`;\n}\nnamespace N47 {\ndeclare let s: string; const a = `${s ?? s}` || s;\n}\nnamespace N48 {\ndeclare let s: string; const a = s && `${s ?? s}`;\n}\nnamespace N49 {\ndeclare let s: string; const a = s ?? `${s ?? s}`;\n}\nnamespace N50 {\ndeclare let s: string; const a = s ?? `${s + s}`;\n}\nnamespace N51 {\ndeclare let s: string; const a = s ?? `${s ? s : s}`;\n}\nnamespace N52 {\ndeclare let s: string; f`${`${s}`}`; declare function f(...x: unknown[]): void;\n}\nnamespace N53 {\ndeclare let s: string; `${s}`.trim();\n}\nnamespace N54 {\ndeclare let o: { s: string }; `${o.s}`.trim();\n}\nnamespace N55 {\ndeclare let o: { s: string }; const a = `${o.s}`.length;\n}\nnamespace N56 {\ndeclare let o: { s: string }; const a = p[`${o.s}`]; declare const p: Record;\n}\nnamespace N57 {\ndeclare let o: { s: string }; const a = [`${o.s}`];\n}\nnamespace N58 {\ndeclare let s: string; async function g() { await `${s}`; }\n}\nnamespace N59 {\ndeclare let s: string; function* g() { yield `${s}`; }\n}\nnamespace N60 {\ndeclare let s: string; function* g() { yield `${s + s}`; }\n}\nnamespace N61 {\ndeclare let s: string; const a = { ...{ b: `${s}` } };\n}\nnamespace N62 {\ndeclare let s: string; const a = new (`${s}` as any)();\n}\nnamespace N63 {\ndeclare let s: string; if (`${s}`) {}\n}\nnamespace N64 {\ndeclare let s: string; `${s}`;\n}\nnamespace N65 {\ndeclare let s: string; const a = (s, `${s}`);\n}\nnamespace N66 {\ndeclare let s: string; const a = (`${s}`, s);\n}"), - typed("prefer-nullish-coalescing", "namespace N0 {\ndeclare let a: string | null | undefined; declare let b: string | null | undefined; declare let c: string | null | undefined; declare let d: string | null | undefined;\n(a && b) || c || d;\n}\nnamespace N1 {\ndeclare let a: string | null | undefined; declare let b: string | null | undefined; declare let c: string | null | undefined; declare let d: string | null | undefined;\na || c || d;\n}\nnamespace N2 {\ndeclare let a: string | null | undefined; declare let b: string | null | undefined; declare let c: string | null | undefined; declare let d: string | null | undefined;\na && b || c || d;\n}\nnamespace N3 {\ndeclare let a: string | null | undefined; declare let b: string | null | undefined; declare let c: string | null | undefined; declare let d: string | null | undefined;\n(a || b) || c;\n}\nnamespace N4 {\ndeclare let a: string | null | undefined; declare let b: string | null | undefined; declare let c: string | null | undefined; declare let d: string | null | undefined;\na || (b && c) || d;\n}\nnamespace N5 {\ndeclare let a: string | null | undefined; declare let b: string | null | undefined; declare let c: string | null | undefined; declare let d: string | null | undefined;\na || b && c;\n}\nnamespace N6 {\ndeclare let a: string | null | undefined; declare let b: string | null | undefined; declare let c: string | null | undefined; declare let d: string | null | undefined;\na || b || c && d;\n}"), - // Of the last `return` tsgolint removes the keyword alone, so that another rule can change the rest. - { ...typed("no-confusing-void-expression", "namespace N0 {\ndeclare function f(): Promise; const g = async () => { return await f(); };\n}\nnamespace N1 {\ndeclare function f(): Promise; const g = async (x: boolean) => { if (x) { return await f(); } f(); };\n}\nnamespace N2 {\ndeclare function f(): Promise; const g = async (x: boolean) => { if (x) return await f(); f(); };\n}\nnamespace N3 {\ndeclare function f(): Promise; const g = async () => await f();\n}\nnamespace N4 {\ndeclare function f(): Promise; const g = async () => { return await (f()); };\n}\nnamespace N5 {\ndeclare function f(): Promise; const g = async () => { return (await f()); };\n}\nnamespace N6 {\ndeclare function f(): Promise; const g = async () => { return await f() };\n}"), also: ["typescript/return-await"] }, - // With `noPropertyAccessFromIndexSignature`, a property that nothing declares may be in brackets. - { ...typed("dot-notation", "namespace N0 {\ndeclare function make(k: Record): Record; const KEYS = make({ a: 1, b: 1 }); KEYS[\"a\"];\n}\nnamespace N1 {\ndeclare const KEYS: Record<\"a\" | \"b\", 1>; KEYS[\"a\"];\n}\nnamespace N2 {\ndeclare const KEYS: { [K in \"a\" | \"b\"]: 1 }; KEYS[\"a\"];\n}\nnamespace N3 {\ndeclare const KEYS: Record; KEYS[\"a\"];\n}\nnamespace N4 {\ndeclare const KEYS: { a: 1 }; KEYS[\"a\"];\n}\nnamespace N5 {\ndeclare const KEYS: Partial<{ a: 1 }>; KEYS[\"a\"];\n}\nnamespace N6 {\ndeclare const KEYS: Pick<{ a: 1; b: 2 }, \"a\">; KEYS[\"a\"];\n}\nnamespace N7 {\ndeclare const KEYS: { a: 1 } & { b: 2 }; KEYS[\"a\"];\n}\nnamespace N8 {\ndeclare const KEYS: { a: 1 } | { a: 2 }; KEYS[\"a\"];\n}\nnamespace N9 {\ndeclare const KEYS: Readonly<{ a: 1 }>; KEYS[\"a\"];\n}"), compilerOptions: { noPropertyAccessFromIndexSignature: true } }, - // The `?.` after `a?.[0]`: two reports begin at the same place, and only what the suggestions leave tells them apart. - typed("no-unnecessary-condition", "type T = { x: number; y?: { z: number } };\ndeclare const arr: T[], maybe: T[] | undefined, o: { l: T[]; m?: T[] }, tup: [T, T], nested: T[][], rec: Record, k: string;\narr?.[0]?.x;\narr[0]?.x;\nmaybe?.[0]?.x;\nmaybe?.[0].x;\no.l?.[0]?.x;\no.m?.[0]?.x;\no.l[0]?.y?.z;\no.l?.[0]?.y?.z;\ntup?.[0]?.x;\ntup[0]?.x;\nnested?.[0]?.[0]?.x;\nnested[0]?.[0]?.x;\nnested[0][0]?.x;\nrec[k]?.[0]?.x;\nrec?.[k]?.[0]?.x;\n(arr as T[])?.[0]?.x;\narr?.[0]?.x ?? 1;\narr?.at(0)?.x;\nif (arr?.[0]) { k; }\nif (arr?.[0]?.x) { k; }\nexport {};"), - // What is asserted is expected of a call among the arguments too: nothing is taken away there. - typed("no-unnecessary-type-assertion", "declare const root: HTMLElement, els: NodeListOf, hs: NodeListOf;\ndeclare function id(a: T): T;\ndeclare function wrap(a: T): { v: T };\ndeclare function get(s: string): T;\ndeclare function list(s: string): T[];\nexport const a1 = Array.from(root.querySelectorAll(\".a\")) as HTMLElement[];\nexport const a2 = Array.from(els) as Element[];\nexport const a3 = Array.from(hs) as HTMLElement[];\nexport const a4 = id(get(\"a\")) as HTMLElement;\nexport const a5 = wrap(get(\"a\")) as { v: HTMLElement };\nexport const a6 = id(id(get(\"a\"))) as HTMLElement;\nexport const a7 = [...root.querySelectorAll(\".a\")] as HTMLElement[];\nexport const a8 = Array.from(root.querySelectorAll(\".a\")) as HTMLElement[];\nexport const a9 = list(\"a\").map(x => x) as HTMLElement[];\nexport const b1 = id(list(\"a\")) as HTMLElement[];\nexport const b2 = id([get(\"a\")]) as HTMLElement[];\nexport const b3 = id({ v: get(\"a\") }) as { v: HTMLElement };\nexport const b4 = id(root.querySelector(\".a\")) as HTMLElement | null;\nexport const b5 = Array.from(root.querySelectorAll(\".a\"), x => x) as HTMLElement[];\nexport const b6 = Promise.resolve(get(\"a\")) as Promise;\nexport const b8 = Array.from(root.children) as HTMLElement[];\nexport const b9 = id(new Set(list(\"a\"))) as Set;"), - // tsgolint leaves the parentheses of `(a) as B`, and the `` of `a`. - typed("non-nullable-type-assertion-style", "declare const c: HTMLElement, m: Map, s: { get(k: string): T | undefined; one(k: string): HTMLElement | null };\nexport const a1 = c.querySelector(\".a\") as HTMLElement;\nexport const a2 = c.querySelector(\".a\") as Element;\nexport const a3 = c.querySelector(\"div\") as HTMLDivElement;\nexport const a4 = m.get(\"a\") as HTMLElement;\nexport const a5 = s.get(\"a\") as HTMLElement;\nexport const a6 = s.get(\"a\") as HTMLElement;\nexport const a7 = s.one(\"a\") as HTMLElement;\nexport let a8: HTMLElement; a8 = c.querySelector(\".a\") as HTMLElement;\nexport function a9() { return c.querySelector(\".a\") as HTMLElement; }\nexport const b1 = c.querySelector(\".a\");\nexport const b2 = (c.querySelector(\".a\")) as HTMLElement;"), - // In a method of an object that is an argument of a generic call tsgolint takes nothing away. - typed("no-unnecessary-type-assertion", "type S = { a: number };\ndeclare const st: { readonly value: { readonly a: number } };\ndeclare function define(o: { setup(): T }): T;\ndeclare function plain(o: { setup(): unknown }): void;\nlet e1!: () => S;\nlet e2!: () => S;\nlet e3!: () => S;\nlet e4!: () => S;\nexport const h1 = define({\n setup() {\n e1 = () => st.value as S;\n return () => null;\n },\n});\nplain({\n setup() {\n e2 = () => st.value as S;\n return () => null;\n },\n});\nexport const h3 = define({\n setup: () => {\n e3 = () => st.value as S;\n return () => null;\n },\n});\nexport const h4 = define({\n setup() {\n e4 = function () {\n return st.value as S;\n };\n const x: S = st.value as S;\n return () => x;\n },\n});\nexport { e1, e2, e3, e4 };"), - // oxlint looks at every parameter, and not at a name in parentheses. - ts("consistent-generic-constructors", "declare class Tree { a: A; b: B }\ndeclare function make(c: T): void;\ndeclare function gen(): T;\nmake(Tree);\nexport const i1 = Tree;\nexport const i2 = gen;\nexport const i3 = gen();\nexport const i4 = new Tree();\nexport type I5 = Tree;\nexport const i6: Tree | undefined = undefined;\nexport function c1(file: string, seen: Set = new Set()) { file; seen; }\nexport const c2: Set = new Set([\"a\"]);\nexport const c3: Set = new Set();\nexport const c4 = new Set();\nexport class C5 { a: Set = new Set(); constructor(public b: Map = new Map()) {} }\nexport const c6 = (seen: Set = new Set()) => seen;\nexport function c7({ s }: { s: Set } = { s: new Set() }) { s; }\nexport const c8: Set = new Set();\nexport let c9: Array = new Array();\nexport const d1: Set = new (Set)();\nexport const d2: globalThis.Set = new globalThis.Set();"), - // A comparison of what the chain tests last is part of the chain, or the chain is left alone. Nothing follows `f()`. - typed("prefer-optional-chain", "type P = { text?: string; n?: number; o?: { v?: string } | null };\ndeclare const a: P | undefined, g: () => boolean, sel: () => { type: string } | undefined, rq: { data?: { rank: number } | null };\nexport const o1 = a === undefined || a.text === undefined || a.text === \"\";\nexport const o2 = a === undefined || a.text === undefined || a.text !== \"\";\nexport const o3 = a === undefined || a.text === undefined || a.text == \"\";\nexport const o4 = a === undefined || a.text === undefined || a.text != \"\";\nexport const o5 = !a || !a.text || a.text === \"\";\nexport const o6 = !a || !a.text || a.text !== \"\";\nexport const o7 = a == null || a.text == null || a.text === \"\";\nexport const o8 = a == null || a.text == null || a.text !== \"x\";\nexport const p1 = a === undefined || a.text === undefined || a.text === \"\" || a.n === 1;\nexport const p2 = a === undefined || a.text === undefined || a.text.length === 0;\nexport const p3 = a === undefined || a.text === undefined || a.text === g.name;\nexport const p4 = a === undefined || a.n === undefined || a.n === 0;\nexport const p5 = a === undefined || a.n === undefined || a.n > 0;\nexport const n1 = a !== undefined && a.text !== undefined && a.text !== \"\";\nexport const n2 = a !== undefined && a.text !== undefined && a.text === \"\";\nexport const n3 = a && a.text && a.text !== \"\";\nexport const n4 = a && a.text && a.text === \"x\";\nexport const n5 = a != null && a.text != null && a.text !== \"\";\nexport const n6 = a != null && a.text != null && a.text === \"x\";\nexport const n7 = a !== undefined && a.n !== undefined && a.n > 0;\nexport const c1 = sel() !== undefined && sel().type === \"allTime\";\nexport const c2 = rq.data !== undefined && rq.data !== null && sel() !== undefined && sel().type === \"allTime\";\nexport const c3 = sel() && sel().type === \"allTime\";\nexport const c4 = sel() !== undefined && sel().type;\nexport const c5 = rq.data !== undefined && rq.data !== null && rq.data.rank === 1;\nexport const c6 = sel() != null && sel().type === \"allTime\";"), - typed("prefer-optional-chain", "type P = { text?: string; n?: number };\ndeclare const b: P, a: P | undefined;\nexport const s1 = b.text !== undefined && b.text === \"\";\nexport const s2 = b.text && b.text === \"x\";\nexport const s3 = b.text === undefined || b.text !== \"\";\nexport const s4 = b.text != null && b.text === \"x\";\nexport const s5 = a && a === b;\nexport const s6 = a !== undefined && a === b;\nexport const s7 = !b.text || b.text !== \"x\";\nexport const s8 = a && a.text && a.text === \"x\" && a.n;\nexport const s9 = a && a.text && a.text === \"x\" && a.n === 1;\nexport const t1 = a && a.text && \"x\" === a.text;\nexport const t3 = a && a.text !== undefined && a.text !== null && a.text === \"x\";\nexport const t4 = a && a.text && a.text === \"x\" || b;\n// oxlint-disable-next-line typescript/prefer-optional-chain\nexport const t5 = a && a.text && a.text === \"x\";"), - // `ShapeID` is no `any`: `Omit` of a union does not ask for the type of what it leaves out. - typed("no-unnecessary-type-assertion", "interface A { id: string; shape?: \"c\" }\ninterface B { id: string; shape?: ShapeID }\ntype N = A | B;\ndeclare const k: Omit, l: Pick;\nconst shapes = { k, l } satisfies Record;\nexport type ShapeID = keyof typeof shapes;\nexport function isValidShape(shape: string): shape is ShapeID { return shape in shapes; }\ndeclare function alias(s: string): string;\nexport function f1(v: { type?: ShapeID | \"x\" }): ShapeID {\n const resolved = typeof v.type === \"string\" ? alias(v.type) : v.type;\n switch (resolved) {\n case undefined:\n return \"k\";\n default:\n return resolved as ShapeID;\n }\n}\nexport function f2(v: { type?: ShapeID | \"x\" }) { return alias(v.type as string | undefined ?? \"\"); }\nexport function f3(s: string) { if (!isValidShape(s)) { return `No such shape: ${s}.`; } return s; }\nexport type U = ShapeID | 1;\nexport const f4 = \"k\" as ShapeID;\nexport type V = any | 1;\n// oxlint-disable-next-line typescript/no-redundant-type-constituents\nexport type W = any | 1;\nexport const f5 = f4 as ShapeID;"), - // `a && a.b?.c` is left alone. - typed("prefer-optional-chain", "declare const c: { editor?: { indentSize?: number | \"tabSize\"; o?: { p?: string } } }, el: { hover?: { content?: string }; item?: number } | undefined, e: { index?: number };\nexport const t1 = c.editor && typeof c.editor.indentSize !== \"undefined\" && c.editor.indentSize !== \"tabSize\";\nexport const t2 = c.editor && typeof c.editor.indentSize !== \"undefined\" && c.editor.indentSize === \"tabSize\";\nexport const t3 = c.editor && c.editor.indentSize !== undefined && c.editor.indentSize !== \"tabSize\";\nexport const t4 = c.editor && typeof c.editor.indentSize !== \"undefined\";\nexport const t5 = c.editor && typeof c.editor.indentSize !== \"undefined\" && e.index;\nexport const t6 = c.editor && typeof c.editor.o !== \"undefined\" && c.editor.o.p !== \"x\";\nexport const u1 = el && el.hover?.content && typeof e.index === \"number\";\nexport const u2 = el && el.hover?.content;\nexport const u3 = el && el.hover?.content && e.index;\nexport const u4 = el && el.hover && typeof e.index === \"number\";\nexport const u5 = el && el.hover?.content && typeof el.item === \"number\";\nexport const u6 = el && el.item && typeof e.index === \"number\";\nexport const u7 = el && el.hover?.content && e.index === 1;\nexport const v1 = el && el?.hover;\nexport const v2 = el && el?.item === 1;\nexport const v3 = el && el?.item !== undefined;\nexport const v4 = c.editor && c.editor?.o?.p;\nexport const v5 = c.editor && c.editor.o?.p === \"x\";\nexport const v6 = el && el.hover?.content !== undefined;\nexport const v7 = el != null && el.hover?.content;\nexport const v8 = el && el.hover && el.hover.content?.length;\nexport const v9 = !el || !el.hover?.content;\nexport const w1 = el && el.hover!?.content;\nexport const w2 = el && el[\"hover\"]?.content;\nexport const w3 = el && el.hover?.content?.length;\n// oxlint-disable-next-line typescript/prefer-optional-chain\nexport const w4 = el && el?.hover;"), - // The letter after a ``, which are comments in a script. + // tsgolint turns `a && a.b.c()` into `a?.b?.c()`, and doesn't touch an expression that starts with a chain. + typed( + "prefer-optional-chain", + 'declare const a: { b: { c: { d: number; e(): { f: number } }; g(): { h: number }; [k: string]: any } } | null;\ndeclare const p: any, u: unknown, k: string, rel: string;\ndeclare const attr: { value: string | null } | null;\na && a.b.c;\na && a.b.c.d;\na && a.b.g();\na && a.b.c.e();\na && a.b.c.e().f;\na && a.b.g().h;\na && a.b[k];\na && a.b[k].c;\na && a["b"].c;\na && a.b;\na && a.b && a.b.c.d;\na && a.b.c && a.b.c.d;\na != null && a.b.c.d;\n!a || !a.b.c;\n!a || !a.b.c.d;\n!a || a.b.c.d === 1;\na && a.b.c.d === 1;\na && a.b!.c;\na && a.b.c!.d;\na && (a.b).c;\na && (a.b.c).d;\nif (p && p.id) { k; }\nif (p && p.id.x) { k; }\np && p.id && p.id.x;\np && p.id();\nif (attr?.value && (attr.value.toLowerCase() === rel)) { k; }\nif (attr?.value && attr.value.toLowerCase() === rel) { k; }\nif (attr && (attr.value)) { k; }\nif ((attr) && attr.value) { k; }\nif (attr && attr.value && (attr.value.length)) { k; }\nexport {};', + ), + typed( + "prefer-optional-chain", + "declare const attr: { value: string | null; n: { m: string } | null } | null, rel: string, k: string;\ndeclare const parsed: any, maybe: { id?: string } | undefined, j: ReturnType;\nattr?.value && attr.value.length;\nattr?.value && attr.value.toLowerCase();\nattr?.value && attr.value.length === 1;\nattr?.value && attr.value.toLowerCase() === rel;\nattr?.value && attr?.value.toLowerCase() === rel;\nattr && attr.value && attr.value.toLowerCase() === rel;\nattr && attr.value && attr.value.length === 1;\nattr?.n && attr.n.m;\nattr?.n && attr.n.m === rel;\nattr?.n && attr?.n.m;\nattr?.n != null && attr.n.m;\nattr && attr.value === rel;\nattr && attr.value.length === 1;\nattr && attr.n && attr.n.m === rel;\nif (parsed && parsed.id) { k; }\nif (j && j.id) { k; }\nif (maybe && maybe.id) { k; }\nfunction f(x: unknown) { const q = x as any; if (q && q.id) { k; } }\ntry { k; } catch (e: any) { if (e && e.id) { k; } }\nlet late; late = JSON.parse(k); if (late && late.id) { k; }\nlet typed: any; try { typed = JSON.parse(k); } catch {} if (typed && typed.id) { k; }\nexport {};", + ), + typed( + "prefer-optional-chain", + 'declare const attr: { n: { m: string; o: { p: string } | null } | null | undefined; f?(): { g: string } | null } | null;\nattr?.n !== null && attr.n.m;\nattr?.n !== undefined && attr.n.m;\nattr?.n !== null && attr?.n !== undefined && attr.n.m;\nattr?.n !== null && attr.n !== undefined && attr.n.m;\nattr?.n !== undefined && attr?.n !== null && attr.n.m;\nattr?.n != null && attr.n.m;\nattr?.n != null && attr.n.o != null && attr.n.o.p;\nattr?.n && attr.n.o && attr.n.o.p;\nattr && attr.n?.o && attr.n.o.p;\nattr && attr.n && attr.n?.o;\n!attr?.n || !attr.n.m;\nattr?.n == null || attr.n.m;\nattr?.n == null || !attr.n.m;\nattr?.n == null || attr.n.o == null;\nattr?.n === null || attr.n.o === null;\nattr?.n === undefined || attr.n.o === undefined;\nattr?.f && attr.f();\nattr?.f?.() && attr.f().g;\nattr?.["n"] && attr["n"].m;\n(attr?.n) && attr.n.m;\nattr?.n! && attr.n.m;\nexport {};', + ), + typed( + "no-unnecessary-condition", + 'type Q = { b: { c: { d: number; e?: number }; f(): { g: { h: number } }; i?: { j: number } }; k: () => { l: number } };\ndeclare const q: Q | undefined, nn: Q;\nq?.b.c?.d;\nq?.b.c.d?.toFixed();\nq?.b?.c;\nq?.b?.c?.d;\nq?.b.i?.j;\nq?.b.c.e?.toFixed();\nq?.b.f?.();\nq?.b.f()?.g;\nq?.b.f().g?.h;\nq?.k()?.l;\nq?.k().l?.toFixed();\nq?.k?.();\nnn.b.c?.d;\nnn?.b.c?.d;\nnn.b?.c.d?.toFixed();\n(q?.b.c)?.d;\nq?.b["c"]?.d;\nq?.["b"].c?.d;\nq!.b.c?.d;\nexport {};', + ), + typed( + "no-unnecessary-condition", + "type L = { s?: { d: boolean; e?: { f: number } }; t: { d: boolean }; u: { d: boolean } | null };\ndeclare function ok(v: unknown): asserts v;\ndeclare let l: L | undefined, m: L, un: { s?: { d: boolean } } | { s: { d: boolean } } | undefined;\nexport function a1() { ok(l?.s); return l?.s?.d; }\nexport function a2() { if (l?.s) { return l?.s?.d; } return 0; }\nexport function a3() { if (l?.s) { return l.s?.d; } return 0; }\nexport function a4() { return l?.t?.d; }\nexport function a5() { return l?.u?.d; }\nexport function a6() { if (l?.u) { return l?.u?.d; } return 0; }\nexport function a7() { if (m.s) { return m.s?.d; } return 0; }\nexport function a8() { if (m.s) { return m?.s?.d; } return 0; }\nexport function a9() { if (l?.s?.e) { return l?.s?.e?.f; } return 0; }\nexport function b1() { return un?.s?.d; }\nexport function b2() { if (un?.s) { return un?.s?.d; } return 0; }\nexport function b3() { const s = l?.s; if (s) { return s?.d; } return 0; }\nexport function b4() { if (l?.s) { return l?.s?.d ?? 1; } return 0; }\nexport function b5() { if (l?.s) { if (l?.s) { return 1; } } return 0; }", + ), + // Where tsgolint parenthesizes an expression it moves out of a template, and which of two suggestions that start at + // the same position wins. + typed( + "no-unnecessary-template-expression", + "namespace N0 {\ndeclare const s: string; const a = `${s}`;\n}\nnamespace N1 {\ndeclare const s: string; f(`${s}`); declare function f(x: string): void;\n}\nnamespace N2 {\ndeclare const s: string; const a = [`${s}`];\n}\nnamespace N3 {\ndeclare const s: string; const a = [`${s}`, 1];\n}\nnamespace N4 {\ndeclare const s: string; const a = `${s.trim()}`;\n}\nnamespace N5 {\ndeclare const s: string; f(`${s.trim()}`); declare function f(x: string): void;\n}\nnamespace N6 {\ndeclare const s: string; const a = { b: `${s}` };\n}\nnamespace N7 {\ndeclare const s: string; const a = `${s}`.length;\n}\nnamespace N8 {\ndeclare const s: string; const a = `${s + s}`;\n}\nnamespace N9 {\ndeclare const s: string; const a = `${'a'}`;\n}\nnamespace N10 {\ndeclare const s: string; function g() { return `${s}`; }\n}\nnamespace N11 {\ndeclare const s: string; const a = s + `${s}`;\n}\nnamespace N12 {\ndeclare const s: any; const a = [\n `${s as string}`,\n];\n}\nnamespace N13 {\ntype T = string; declare const type: T; const a = [\n `${type}`,\n];\n}\nnamespace N14 {\ndeclare const s: string; const a = `${s.trim()}`.length;\n}\nnamespace N15 {\ndeclare const s: string; const a = s + `${s + s}`;\n}\nnamespace N16 {\ndeclare const s: string; const a = `${s + s}` + s;\n}\nnamespace N17 {\ndeclare const o: { s: string }; f(`${o.s}`); declare function f(x: string): void;\n}\nnamespace N18 {\ndeclare const o: { s: string }; new F(`${o.s}`); declare class F { constructor(x: string); }\n}\nnamespace N19 {\ndeclare const s: string; new F(`${s}`); declare class F { constructor(x: string); }\n}\nnamespace N20 {\ndeclare const s: string; const a = s ? `${s}` : s;\n}\nnamespace N21 {\ndeclare const s: string; const a = s ? `${s + s}` : s;\n}\nnamespace N22 {\ndeclare const s: string; const a = s ? `${s ? s : s}` : s;\n}\nnamespace N23 {\ndeclare const s: string; const a = (`${s}`);\n}\nnamespace N24 {\ndeclare const s: string; const a = (`${s + s}`);\n}\nnamespace N25 {\ndeclare const s: string; const a = `${s}` as string;\n}\nnamespace N26 {\ndeclare const s: any; const a = `${s as string}` as string;\n}\nnamespace N27 {\ndeclare const s: string; const a = typeof `${s}`;\n}\nnamespace N28 {\ndeclare const s: string; const a = typeof `${typeof s}`;\n}\nnamespace N29 {\ndeclare const s: string; const a = [...`${s}`];\n}\nnamespace N30 {\ndeclare const s: string; const a = `${s}`!;\n}\nnamespace N31 {\ndeclare const s: string; let a; a = `${s}`;\n}\nnamespace N32 {\ndeclare const s: string; let a; a = `${a = s}`;\n}\nnamespace N33 {\ndeclare const s: string; const a = `a${`${s}`}`;\n}\nnamespace N34 {\ndeclare const s: string; const a = { [`${s}`]: 1 };\n}\nnamespace N35 {\ndeclare const s: string; const a = () => `${s}`;\n}\nnamespace N36 {\ndeclare const s: string; const a = s || `${s || s}`;\n}\nnamespace N37 {\ndeclare const s: string; const a = s && `${s || s}`;\n}\nnamespace N38 {\ndeclare const s: string; const a = o[`${s}`]; declare const o: Record;\n}\nnamespace N39 {\ndeclare const s: string; const a = o[`${s.trim()}`]; declare const o: Record;\n}\nnamespace N40 {\ndeclare let s: string; const a = () => `${s = s}`;\n}\nnamespace N41 {\ndeclare let s: string; const a = () => `${s ? s : s}`;\n}\nnamespace N42 {\ndeclare let s: string; const a = () => `${s + s}`;\n}\nnamespace N43 {\ndeclare let s: string; const a = () => `${(s, s)}`;\n}\nnamespace N44 {\ndeclare let s: string; const a = `${(s)}`;\n}\nnamespace N45 {\ndeclare let s: string; const a = [`${(s)}`];\n}\nnamespace N46 {\ndeclare let s: string; const a = s || `${s ?? s}`;\n}\nnamespace N47 {\ndeclare let s: string; const a = `${s ?? s}` || s;\n}\nnamespace N48 {\ndeclare let s: string; const a = s && `${s ?? s}`;\n}\nnamespace N49 {\ndeclare let s: string; const a = s ?? `${s ?? s}`;\n}\nnamespace N50 {\ndeclare let s: string; const a = s ?? `${s + s}`;\n}\nnamespace N51 {\ndeclare let s: string; const a = s ?? `${s ? s : s}`;\n}\nnamespace N52 {\ndeclare let s: string; f`${`${s}`}`; declare function f(...x: unknown[]): void;\n}\nnamespace N53 {\ndeclare let s: string; `${s}`.trim();\n}\nnamespace N54 {\ndeclare let o: { s: string }; `${o.s}`.trim();\n}\nnamespace N55 {\ndeclare let o: { s: string }; const a = `${o.s}`.length;\n}\nnamespace N56 {\ndeclare let o: { s: string }; const a = p[`${o.s}`]; declare const p: Record;\n}\nnamespace N57 {\ndeclare let o: { s: string }; const a = [`${o.s}`];\n}\nnamespace N58 {\ndeclare let s: string; async function g() { await `${s}`; }\n}\nnamespace N59 {\ndeclare let s: string; function* g() { yield `${s}`; }\n}\nnamespace N60 {\ndeclare let s: string; function* g() { yield `${s + s}`; }\n}\nnamespace N61 {\ndeclare let s: string; const a = { ...{ b: `${s}` } };\n}\nnamespace N62 {\ndeclare let s: string; const a = new (`${s}` as any)();\n}\nnamespace N63 {\ndeclare let s: string; if (`${s}`) {}\n}\nnamespace N64 {\ndeclare let s: string; `${s}`;\n}\nnamespace N65 {\ndeclare let s: string; const a = (s, `${s}`);\n}\nnamespace N66 {\ndeclare let s: string; const a = (`${s}`, s);\n}", + ), + typed( + "prefer-nullish-coalescing", + "namespace N0 {\ndeclare let a: string | null | undefined; declare let b: string | null | undefined; declare let c: string | null | undefined; declare let d: string | null | undefined;\n(a && b) || c || d;\n}\nnamespace N1 {\ndeclare let a: string | null | undefined; declare let b: string | null | undefined; declare let c: string | null | undefined; declare let d: string | null | undefined;\na || c || d;\n}\nnamespace N2 {\ndeclare let a: string | null | undefined; declare let b: string | null | undefined; declare let c: string | null | undefined; declare let d: string | null | undefined;\na && b || c || d;\n}\nnamespace N3 {\ndeclare let a: string | null | undefined; declare let b: string | null | undefined; declare let c: string | null | undefined; declare let d: string | null | undefined;\n(a || b) || c;\n}\nnamespace N4 {\ndeclare let a: string | null | undefined; declare let b: string | null | undefined; declare let c: string | null | undefined; declare let d: string | null | undefined;\na || (b && c) || d;\n}\nnamespace N5 {\ndeclare let a: string | null | undefined; declare let b: string | null | undefined; declare let c: string | null | undefined; declare let d: string | null | undefined;\na || b && c;\n}\nnamespace N6 {\ndeclare let a: string | null | undefined; declare let b: string | null | undefined; declare let c: string | null | undefined; declare let d: string | null | undefined;\na || b || c && d;\n}", + ), + // For the last `return`, tsgolint removes only the keyword, so another rule's fix can change the rest. + { + ...typed( + "no-confusing-void-expression", + "namespace N0 {\ndeclare function f(): Promise; const g = async () => { return await f(); };\n}\nnamespace N1 {\ndeclare function f(): Promise; const g = async (x: boolean) => { if (x) { return await f(); } f(); };\n}\nnamespace N2 {\ndeclare function f(): Promise; const g = async (x: boolean) => { if (x) return await f(); f(); };\n}\nnamespace N3 {\ndeclare function f(): Promise; const g = async () => await f();\n}\nnamespace N4 {\ndeclare function f(): Promise; const g = async () => { return await (f()); };\n}\nnamespace N5 {\ndeclare function f(): Promise; const g = async () => { return (await f()); };\n}\nnamespace N6 {\ndeclare function f(): Promise; const g = async () => { return await f() };\n}", + ), + also: ["typescript/return-await"], + }, + // With `noPropertyAccessFromIndexSignature`, bracket access to an undeclared property is allowed. + { + ...typed( + "dot-notation", + 'namespace N0 {\ndeclare function make(k: Record): Record; const KEYS = make({ a: 1, b: 1 }); KEYS["a"];\n}\nnamespace N1 {\ndeclare const KEYS: Record<"a" | "b", 1>; KEYS["a"];\n}\nnamespace N2 {\ndeclare const KEYS: { [K in "a" | "b"]: 1 }; KEYS["a"];\n}\nnamespace N3 {\ndeclare const KEYS: Record; KEYS["a"];\n}\nnamespace N4 {\ndeclare const KEYS: { a: 1 }; KEYS["a"];\n}\nnamespace N5 {\ndeclare const KEYS: Partial<{ a: 1 }>; KEYS["a"];\n}\nnamespace N6 {\ndeclare const KEYS: Pick<{ a: 1; b: 2 }, "a">; KEYS["a"];\n}\nnamespace N7 {\ndeclare const KEYS: { a: 1 } & { b: 2 }; KEYS["a"];\n}\nnamespace N8 {\ndeclare const KEYS: { a: 1 } | { a: 2 }; KEYS["a"];\n}\nnamespace N9 {\ndeclare const KEYS: Readonly<{ a: 1 }>; KEYS["a"];\n}', + ), + compilerOptions: { noPropertyAccessFromIndexSignature: true }, + }, + // The `?.` after `a?.[0]`: two reports start at the same position, and only their suggestions' output distinguishes + // them. + typed( + "no-unnecessary-condition", + "type T = { x: number; y?: { z: number } };\ndeclare const arr: T[], maybe: T[] | undefined, o: { l: T[]; m?: T[] }, tup: [T, T], nested: T[][], rec: Record, k: string;\narr?.[0]?.x;\narr[0]?.x;\nmaybe?.[0]?.x;\nmaybe?.[0].x;\no.l?.[0]?.x;\no.m?.[0]?.x;\no.l[0]?.y?.z;\no.l?.[0]?.y?.z;\ntup?.[0]?.x;\ntup[0]?.x;\nnested?.[0]?.[0]?.x;\nnested[0]?.[0]?.x;\nnested[0][0]?.x;\nrec[k]?.[0]?.x;\nrec?.[k]?.[0]?.x;\n(arr as T[])?.[0]?.x;\narr?.[0]?.x ?? 1;\narr?.at(0)?.x;\nif (arr?.[0]) { k; }\nif (arr?.[0]?.x) { k; }\nexport {};", + ), + // The asserted type is also the contextual type of calls nested in the arguments, so the assertion isn't removed. + typed( + "no-unnecessary-type-assertion", + 'declare const root: HTMLElement, els: NodeListOf, hs: NodeListOf;\ndeclare function id(a: T): T;\ndeclare function wrap(a: T): { v: T };\ndeclare function get(s: string): T;\ndeclare function list(s: string): T[];\nexport const a1 = Array.from(root.querySelectorAll(".a")) as HTMLElement[];\nexport const a2 = Array.from(els) as Element[];\nexport const a3 = Array.from(hs) as HTMLElement[];\nexport const a4 = id(get("a")) as HTMLElement;\nexport const a5 = wrap(get("a")) as { v: HTMLElement };\nexport const a6 = id(id(get("a"))) as HTMLElement;\nexport const a7 = [...root.querySelectorAll(".a")] as HTMLElement[];\nexport const a8 = Array.from(root.querySelectorAll(".a")) as HTMLElement[];\nexport const a9 = list("a").map(x => x) as HTMLElement[];\nexport const b1 = id(list("a")) as HTMLElement[];\nexport const b2 = id([get("a")]) as HTMLElement[];\nexport const b3 = id({ v: get("a") }) as { v: HTMLElement };\nexport const b4 = id(root.querySelector(".a")) as HTMLElement | null;\nexport const b5 = Array.from(root.querySelectorAll(".a"), x => x) as HTMLElement[];\nexport const b6 = Promise.resolve(get("a")) as Promise;\nexport const b8 = Array.from(root.children) as HTMLElement[];\nexport const b9 = id(new Set(list("a"))) as Set;', + ), + // tsgolint keeps the parentheses in `(a) as B` and the `` in `a`. + typed( + "non-nullable-type-assertion-style", + 'declare const c: HTMLElement, m: Map, s: { get(k: string): T | undefined; one(k: string): HTMLElement | null };\nexport const a1 = c.querySelector(".a") as HTMLElement;\nexport const a2 = c.querySelector(".a") as Element;\nexport const a3 = c.querySelector("div") as HTMLDivElement;\nexport const a4 = m.get("a") as HTMLElement;\nexport const a5 = s.get("a") as HTMLElement;\nexport const a6 = s.get("a") as HTMLElement;\nexport const a7 = s.one("a") as HTMLElement;\nexport let a8: HTMLElement; a8 = c.querySelector(".a") as HTMLElement;\nexport function a9() { return c.querySelector(".a") as HTMLElement; }\nexport const b1 = c.querySelector(".a");\nexport const b2 = (c.querySelector(".a")) as HTMLElement;', + ), + // tsgolint doesn't remove an assertion inside a method of an object literal that's passed to a generic call. + typed( + "no-unnecessary-type-assertion", + "type S = { a: number };\ndeclare const st: { readonly value: { readonly a: number } };\ndeclare function define(o: { setup(): T }): T;\ndeclare function plain(o: { setup(): unknown }): void;\nlet e1!: () => S;\nlet e2!: () => S;\nlet e3!: () => S;\nlet e4!: () => S;\nexport const h1 = define({\n setup() {\n e1 = () => st.value as S;\n return () => null;\n },\n});\nplain({\n setup() {\n e2 = () => st.value as S;\n return () => null;\n },\n});\nexport const h3 = define({\n setup: () => {\n e3 = () => st.value as S;\n return () => null;\n },\n});\nexport const h4 = define({\n setup() {\n e4 = function () {\n return st.value as S;\n };\n const x: S = st.value as S;\n return () => x;\n },\n});\nexport { e1, e2, e3, e4 };", + ), + // oxlint checks every parameter, but not a parenthesized constructor name (`new (Set)()`). + ts( + "consistent-generic-constructors", + 'declare class Tree { a: A; b: B }\ndeclare function make(c: T): void;\ndeclare function gen(): T;\nmake(Tree);\nexport const i1 = Tree;\nexport const i2 = gen;\nexport const i3 = gen();\nexport const i4 = new Tree();\nexport type I5 = Tree;\nexport const i6: Tree | undefined = undefined;\nexport function c1(file: string, seen: Set = new Set()) { file; seen; }\nexport const c2: Set = new Set(["a"]);\nexport const c3: Set = new Set();\nexport const c4 = new Set();\nexport class C5 { a: Set = new Set(); constructor(public b: Map = new Map()) {} }\nexport const c6 = (seen: Set = new Set()) => seen;\nexport function c7({ s }: { s: Set } = { s: new Set() }) { s; }\nexport const c8: Set = new Set();\nexport let c9: Array = new Array();\nexport const d1: Set = new (Set)();\nexport const d2: globalThis.Set = new globalThis.Set();', + ), + // A trailing comparison of the chain's last operand either joins the chain or keeps the whole chain from being + // reported. Nothing chains onto a call like `f()`. + typed( + "prefer-optional-chain", + 'type P = { text?: string; n?: number; o?: { v?: string } | null };\ndeclare const a: P | undefined, g: () => boolean, sel: () => { type: string } | undefined, rq: { data?: { rank: number } | null };\nexport const o1 = a === undefined || a.text === undefined || a.text === "";\nexport const o2 = a === undefined || a.text === undefined || a.text !== "";\nexport const o3 = a === undefined || a.text === undefined || a.text == "";\nexport const o4 = a === undefined || a.text === undefined || a.text != "";\nexport const o5 = !a || !a.text || a.text === "";\nexport const o6 = !a || !a.text || a.text !== "";\nexport const o7 = a == null || a.text == null || a.text === "";\nexport const o8 = a == null || a.text == null || a.text !== "x";\nexport const p1 = a === undefined || a.text === undefined || a.text === "" || a.n === 1;\nexport const p2 = a === undefined || a.text === undefined || a.text.length === 0;\nexport const p3 = a === undefined || a.text === undefined || a.text === g.name;\nexport const p4 = a === undefined || a.n === undefined || a.n === 0;\nexport const p5 = a === undefined || a.n === undefined || a.n > 0;\nexport const n1 = a !== undefined && a.text !== undefined && a.text !== "";\nexport const n2 = a !== undefined && a.text !== undefined && a.text === "";\nexport const n3 = a && a.text && a.text !== "";\nexport const n4 = a && a.text && a.text === "x";\nexport const n5 = a != null && a.text != null && a.text !== "";\nexport const n6 = a != null && a.text != null && a.text === "x";\nexport const n7 = a !== undefined && a.n !== undefined && a.n > 0;\nexport const c1 = sel() !== undefined && sel().type === "allTime";\nexport const c2 = rq.data !== undefined && rq.data !== null && sel() !== undefined && sel().type === "allTime";\nexport const c3 = sel() && sel().type === "allTime";\nexport const c4 = sel() !== undefined && sel().type;\nexport const c5 = rq.data !== undefined && rq.data !== null && rq.data.rank === 1;\nexport const c6 = sel() != null && sel().type === "allTime";', + ), + typed( + "prefer-optional-chain", + 'type P = { text?: string; n?: number };\ndeclare const b: P, a: P | undefined;\nexport const s1 = b.text !== undefined && b.text === "";\nexport const s2 = b.text && b.text === "x";\nexport const s3 = b.text === undefined || b.text !== "";\nexport const s4 = b.text != null && b.text === "x";\nexport const s5 = a && a === b;\nexport const s6 = a !== undefined && a === b;\nexport const s7 = !b.text || b.text !== "x";\nexport const s8 = a && a.text && a.text === "x" && a.n;\nexport const s9 = a && a.text && a.text === "x" && a.n === 1;\nexport const t1 = a && a.text && "x" === a.text;\nexport const t3 = a && a.text !== undefined && a.text !== null && a.text === "x";\nexport const t4 = a && a.text && a.text === "x" || b;\n// oxlint-disable-next-line typescript/prefer-optional-chain\nexport const t5 = a && a.text && a.text === "x";', + ), + // `ShapeID` isn't `any`: `Omit` on a union doesn't resolve the types of the properties it drops, so the reference + // isn't circular. + typed( + "no-unnecessary-type-assertion", + 'interface A { id: string; shape?: "c" }\ninterface B { id: string; shape?: ShapeID }\ntype N = A | B;\ndeclare const k: Omit, l: Pick;\nconst shapes = { k, l } satisfies Record;\nexport type ShapeID = keyof typeof shapes;\nexport function isValidShape(shape: string): shape is ShapeID { return shape in shapes; }\ndeclare function alias(s: string): string;\nexport function f1(v: { type?: ShapeID | "x" }): ShapeID {\n const resolved = typeof v.type === "string" ? alias(v.type) : v.type;\n switch (resolved) {\n case undefined:\n return "k";\n default:\n return resolved as ShapeID;\n }\n}\nexport function f2(v: { type?: ShapeID | "x" }) { return alias(v.type as string | undefined ?? ""); }\nexport function f3(s: string) { if (!isValidShape(s)) { return `No such shape: ${s}.`; } return s; }\nexport type U = ShapeID | 1;\nexport const f4 = "k" as ShapeID;\nexport type V = any | 1;\n// oxlint-disable-next-line typescript/no-redundant-type-constituents\nexport type W = any | 1;\nexport const f5 = f4 as ShapeID;', + ), + // `a && a.b?.c` isn't fixed. + typed( + "prefer-optional-chain", + 'declare const c: { editor?: { indentSize?: number | "tabSize"; o?: { p?: string } } }, el: { hover?: { content?: string }; item?: number } | undefined, e: { index?: number };\nexport const t1 = c.editor && typeof c.editor.indentSize !== "undefined" && c.editor.indentSize !== "tabSize";\nexport const t2 = c.editor && typeof c.editor.indentSize !== "undefined" && c.editor.indentSize === "tabSize";\nexport const t3 = c.editor && c.editor.indentSize !== undefined && c.editor.indentSize !== "tabSize";\nexport const t4 = c.editor && typeof c.editor.indentSize !== "undefined";\nexport const t5 = c.editor && typeof c.editor.indentSize !== "undefined" && e.index;\nexport const t6 = c.editor && typeof c.editor.o !== "undefined" && c.editor.o.p !== "x";\nexport const u1 = el && el.hover?.content && typeof e.index === "number";\nexport const u2 = el && el.hover?.content;\nexport const u3 = el && el.hover?.content && e.index;\nexport const u4 = el && el.hover && typeof e.index === "number";\nexport const u5 = el && el.hover?.content && typeof el.item === "number";\nexport const u6 = el && el.item && typeof e.index === "number";\nexport const u7 = el && el.hover?.content && e.index === 1;\nexport const v1 = el && el?.hover;\nexport const v2 = el && el?.item === 1;\nexport const v3 = el && el?.item !== undefined;\nexport const v4 = c.editor && c.editor?.o?.p;\nexport const v5 = c.editor && c.editor.o?.p === "x";\nexport const v6 = el && el.hover?.content !== undefined;\nexport const v7 = el != null && el.hover?.content;\nexport const v8 = el && el.hover && el.hover.content?.length;\nexport const v9 = !el || !el.hover?.content;\nexport const w1 = el && el.hover!?.content;\nexport const w2 = el && el["hover"]?.content;\nexport const w3 = el && el.hover?.content?.length;\n// oxlint-disable-next-line typescript/prefer-optional-chain\nexport const w4 = el && el?.hover;', + ), + // The first letter after ``, which start comments in a script. js("capitalized-comments", " lower\na;\n

    "); + compare("detached", detached, ["onEndTag"]); + + expect(missing).toEqual(given); + expect(new Set(Object.keys(missing).map(label => label.split(".")[0]))).toEqual( + new Set(["element", "endTag", "text", "comment", "end", "detached"]), + ); + expect(missing["element.before()"]).toEqual({ + name: "TypeError", + code: "ERR_INVALID_ARG_TYPE", + message: "Expected string", + }); + expect(missing["element.onEndTag()"]).toEqual({ name: "TypeError", code: undefined, message: "Expected a function" }); + expect(missing["detached.onEndTag()"]).toEqual({ returned: null }); +}); + describe("tagName, endTag.name, and comment.text setters", () => { it("element.tagName renames the start and end tag", () => { const out = new HTMLRewriter() diff --git a/test/leaksan.supp b/test/leaksan.supp index 06f00aa8c43d..1403d57c9a9f 100644 --- a/test/leaksan.supp +++ b/test/leaksan.supp @@ -95,7 +95,7 @@ leak:runtime.node.node_fs_watcher.FSWatcher.Arguments.fromJS leak:jsc.web_worker.create leak:runtime.node.zlib.NativeZlib.Context.init leak:JSC::intlCollatorAvailableLocales -leak:Bun__canonicalizeIP +leak:Bun__Bindgen__CaresJsc__canonicalizeIP leak:dlopen leak:Bun::evaluateCommonJSModuleOnce leak:fse_run_loop diff --git a/test/napi/napi-app/async_tests.cpp b/test/napi/napi-app/async_tests.cpp index 38c5680c7570..d8399c02841c 100644 --- a/test/napi/napi-app/async_tests.cpp +++ b/test/napi/napi-app/async_tests.cpp @@ -777,6 +777,59 @@ napi_value late_finalizer_run_count(const Napi::CallbackInfo &info) { // termination, or napi_tsfn_abort. Everything is printed from here (not from // JS: a worker's console.log reaches stdout asynchronously) and compared with // node's output. `data` carries the item number. +struct ExternalBufferWork { + std::atomic *report; + std::atomic finalized{false}; + napi_async_work work; +}; + +// async_work_with_external_buffer(report: Int32Array on a SharedArrayBuffer): +// queues work on an external ArrayBuffer. report[0] is set when execute() +// starts. execute() returns once the buffer's finalizer has run, or after half +// a second, and report[1] says which: 1 if the finalizer ran during execute(). +static napi_value +async_work_with_external_buffer(const Napi::CallbackInfo &info) { + napi_env env = info.Env(); + void *report; + NODE_API_CALL(env, napi_get_typedarray_info(env, info[0], nullptr, nullptr, + &report, nullptr, nullptr)); + auto *data = new ExternalBufferWork; + data->report = static_cast *>(report); + + napi_value buffer, name; + NODE_API_CALL(env, napi_create_external_arraybuffer( + env, data, 1, + [](napi_env, void *data, void *) { + static_cast(data)->finalized = + true; + }, + nullptr, &buffer)); + NODE_API_CALL(env, + napi_create_string_utf8(env, "work", NAPI_AUTO_LENGTH, &name)); + NODE_API_CALL( + env, + napi_create_async_work( + env, nullptr, name, + [](napi_env, void *opaque) { + auto *data = static_cast(opaque); + data->report[0] = 1; + const auto deadline = std::chrono::steady_clock::now() + + std::chrono::milliseconds(500); + while (!data->finalized && + std::chrono::steady_clock::now() < deadline) { + std::this_thread::yield(); + } + data->report[1] = data->finalized; + }, + [](napi_env env, napi_status, void *opaque) { + napi_delete_async_work( + env, static_cast(opaque)->work); + }, + data, &data->work)); + NODE_API_CALL(env, napi_queue_async_work(env, data->work)); + return buffer; +} + static napi_threadsafe_function queued_items_tsfn = nullptr; static bool queued_items_tsfn_print_finalize = false; static bool queued_items_tsfn_finalized = false; @@ -864,6 +917,7 @@ napi_value threadsafe_function_with_queued_items_finalized( } void register_async_tests(Napi::Env env, Napi::Object exports) { + REGISTER_FUNCTION(env, exports, async_work_with_external_buffer); REGISTER_FUNCTION(env, exports, queue_threadsafe_function_items); REGISTER_FUNCTION(env, exports, abort_threadsafe_function_with_queued_items); REGISTER_FUNCTION(env, exports, diff --git a/test/napi/napi-app/binding.gyp b/test/napi/napi-app/binding.gyp index 9558e63b65a3..11f194f20a7c 100644 --- a/test/napi/napi-app/binding.gyp +++ b/test/napi/napi-app/binding.gyp @@ -386,5 +386,53 @@ "cflags_cc!": ["-DNDEBUG"], "xcode_settings": {"GCC_PREPROCESSOR_DEFINITIONS": ["NAPI_VERSION=10"]}, }, + # The Windows link shapes of an addon that names node.exe in its import tables without + # node-gyp's win_delay_load_hook. On other platforms they are ordinary addons. + { + "target_name": "no_delay_load_hook_addon", + "sources": ["no_delay_load_hook_addon.c"], + "win_delay_load_hook": "false", + "conditions": [ + ["OS=='win'", { + "msvs_settings": { + "VCLinkerTool": { + "DelayLoadDLLs": ["node.exe"], + }, + }, + }], + ], + }, + { + "target_name": "regular_node_exe_import_addon", + "sources": ["no_delay_load_hook_addon.c"], + "win_delay_load_hook": "false", + }, + { + "target_name": "no_delay_load_hook_ctor_addon", + "sources": ["no_delay_load_hook_addon.c"], + "defines": ["REGISTER_VIA_CONSTRUCTOR"], + "win_delay_load_hook": "false", + "conditions": [ + ["OS=='win'", { + "msvs_settings": { + "VCLinkerTool": { + "DelayLoadDLLs": ["node.exe"], + }, + }, + }], + ], + }, + { + "target_name": "regular_node_exe_import_ctor_addon", + "sources": ["no_delay_load_hook_addon.c"], + "defines": ["REGISTER_VIA_CONSTRUCTOR"], + "win_delay_load_hook": "false", + }, + { + "target_name": "regular_node_exe_import_missing_addon", + "sources": ["no_delay_load_hook_addon.c"], + "defines": ["IMPORT_MISSING_FROM_HOST"], + "win_delay_load_hook": "false", + }, ] } diff --git a/test/napi/napi-app/module.js b/test/napi/napi-app/module.js index 7144ee7ca6b6..3576645eb0ba 100644 --- a/test/napi/napi-app/module.js +++ b/test/napi/napi-app/module.js @@ -405,7 +405,6 @@ nativeTests.test_get_all_property_names_throwing_proxy_traps = () => { napi_key_keep_numbers, ), ); - }; nativeTests.test_get_all_property_names_get_prototype_throws_in_descriptor_walk = () => { @@ -1952,6 +1951,38 @@ nativeTests.test_ungated_calls_worker_terminate = async () => { } }; +nativeTests.test_async_work_worker_terminate = async () => { + const { Worker } = require("node:worker_threads"); + const path = require("node:path"); + const report = new Int32Array(new SharedArrayBuffer(8)); + const worker = new Worker( + `globalThis.buffer = require(${JSON.stringify(path.join(__dirname, "build/Debug/napitests.node"))}) + .async_work_with_external_buffer(require("node:worker_threads").workerData);`, + { eval: true, workerData: report }, + ); + const { promise: failed, reject } = Promise.withResolvers(); + worker.once("error", reject); + while (Atomics.load(report, 0) === 0) await Promise.race([failed, new Promise(resolve => setImmediate(resolve))]); + console.log("terminate() resolved with", await worker.terminate()); + console.log("finalized during execute():", report[1]); +}; + +nativeTests.test_gated_calls_worker_terminate = async () => { + const { Worker } = require("node:worker_threads"); + const path = require("node:path"); + const report = new Int32Array(new SharedArrayBuffer(12)); + const worker = new Worker( + `require(${JSON.stringify(path.join(__dirname, "build/Debug/napitests.node"))}) + .gated_calls_until_terminated(require("node:worker_threads").workerData);`, + { eval: true, workerData: report }, + ); + const { promise: failed, reject } = Promise.withResolvers(); + worker.once("error", reject); + while (Atomics.load(report, 0) === 0) await Promise.race([failed, new Promise(resolve => setImmediate(resolve))]); + console.log("terminate() resolved with", await worker.terminate()); + console.log("napi_throw:", report[1], "exception pending:", report[2]); +}; + // See ungated_calls_through_timeout in standalone_tests.cpp: 600ms of ungated // calls under a 150ms timeout. The timeout is wall-clock from the start of the // run, so it must comfortably cover reaching the addon on the slowest lane. diff --git a/test/napi/napi-app/no_delay_load_hook_addon.c b/test/napi/napi-app/no_delay_load_hook_addon.c new file mode 100644 index 000000000000..52aac4f1c7e8 --- /dev/null +++ b/test/napi/napi-app/no_delay_load_hook_addon.c @@ -0,0 +1,65 @@ +// An N-API addon whose Windows build imports from node.exe without node-gyp's +// win_delay_load_hook. binding.gyp builds this source in several variants: +// (default) exports napi_register_module_v1 +// REGISTER_VIA_CONSTRUCTOR calls napi_module_register from a static initializer, inside DllMain, +// as NAPI_MODULE() did in node_api.h before v18.17.0 +// IMPORT_MISSING_FROM_HOST also imports a node.exe export that bun.exe doesn't have +#include +#include + +#if defined(_WIN32) && defined(IMPORT_MISSING_FROM_HOST) +// Exported by node.exe (OpenSSL) but not by bun. +__declspec(dllimport) unsigned long OpenSSL_version_num(void); +#endif + +static napi_value hello(napi_env env, napi_callback_info info) { + (void)info; + napi_value out; + const char *text = "hello"; +#if defined(_WIN32) && defined(IMPORT_MISSING_FROM_HOST) + char buf[64]; + snprintf(buf, sizeof(buf), "hello %lx", OpenSSL_version_num()); + text = buf; +#endif + if (napi_create_string_utf8(env, text, NAPI_AUTO_LENGTH, &out) != napi_ok) + return NULL; + return out; +} + +static napi_value init(napi_env env, napi_value exports) { + napi_value fn; + if (napi_create_function(env, "hello", NAPI_AUTO_LENGTH, hello, NULL, &fn) != + napi_ok) + return NULL; + if (napi_set_named_property(env, exports, "hello", fn) != napi_ok) + return NULL; + return exports; +} + +#ifdef REGISTER_VIA_CONSTRUCTOR + +static napi_module module_description = { + NAPI_MODULE_VERSION, 0, __FILE__, init, "no_delay_load_hook_addon", NULL, {0}, +}; + +// Copied from NAPI_C_CTOR in node_api.h v18.16.0, with different names. +#if defined(_MSC_VER) +#pragma section(".CRT$XCU", read) +static void __cdecl register_module(void); +__declspec(dllexport, allocate(".CRT$XCU")) void(__cdecl *register_module_)(void) = + register_module; +static void __cdecl register_module(void) { +#else +static void register_module(void) __attribute__((constructor)); +static void register_module(void) { +#endif + napi_module_register(&module_description); +} + +#else + +NAPI_MODULE_EXPORT napi_value napi_register_module_v1(napi_env env, napi_value exports) { + return init(env, exports); +} + +#endif diff --git a/test/napi/napi-app/standalone_tests.cpp b/test/napi/napi-app/standalone_tests.cpp index c77623dcd083..0ad81cf36e84 100644 --- a/test/napi/napi-app/standalone_tests.cpp +++ b/test/napi/napi-app/standalone_tests.cpp @@ -11,6 +11,12 @@ #include #include +#ifdef _WIN32 +#include +#else +#include +#endif + #include "utils.h" namespace napitests { @@ -724,6 +730,42 @@ static napi_value test_napi_run_script(const Napi::CallbackInfo &info) { return ret; } +static napi_value +test_napi_run_script_exception_value(const Napi::CallbackInfo &info) { + napi_env env = info.Env(); + // info[0] is the GC callback + napi_value script = info[1]; + + napi_value ret = nullptr; + napi_status run_status = napi_run_script(env, script, &ret); + bool pending = false; + NODE_API_CALL(env, napi_is_exception_pending(env, &pending)); + printf("run status=%d pending=%d\n", (int)run_status, (int)pending); + + napi_value exc = nullptr; + NODE_API_CALL(env, napi_get_and_clear_last_exception(env, &exc)); + + napi_valuetype type = (napi_valuetype)99; + napi_status typeof_status = napi_typeof(env, exc, &type); + bool is_error = false; + NODE_API_CALL(env, napi_is_error(env, exc, &is_error)); + printf("typeof status=%d type=%d is_error=%d\n", (int)typeof_status, + (int)type, (int)is_error); + + if (type == napi_object) { + napi_value message = nullptr; + NODE_API_CALL(env, + napi_get_named_property(env, exc, "message", &message)); + char buf[128] = {0}; + size_t len = 0; + NODE_API_CALL(env, napi_get_value_string_utf8(env, message, buf, + sizeof buf, &len)); + printf("message=%s\n", buf); + } + + return exc; +} + static napi_value test_napi_throw_with_nullptr(const Napi::CallbackInfo &info) { napi_env env = info.Env(); const napi_status status = napi_throw(env, nullptr); @@ -3216,6 +3258,40 @@ static napi_value make_ungated_calls_spinner(const Napi::CallbackInfo &info) { return spin; } +// gated_calls_until_terminated(report: Int32Array on a SharedArrayBuffer): +// makes a call that Node gates behind can_call_into_js() until +// worker.terminate() has it refused. report[0] is set once the loop is about to +// start. Then report[1] is the status of napi_throw and report[2] is whether an +// exception is pending after it. node-addon-api calls napi_fatal_error if an +// exception that it cannot clear is pending. +static napi_value +gated_calls_until_terminated(const Napi::CallbackInfo &info) { + napi_env env = info.Env(); + void *data; + NODE_API_CALL(env, napi_get_typedarray_info(env, info[0], nullptr, nullptr, + &data, nullptr, nullptr)); + auto *report = static_cast *>(data); + napi_value object, one, message, error; + NODE_API_CALL(env, napi_create_object(env, &object)); + NODE_API_CALL(env, napi_create_int32(env, 1, &one)); + NODE_API_CALL(env, napi_create_string_utf8(env, "refused", NAPI_AUTO_LENGTH, + &message)); + NODE_API_CALL(env, napi_create_error(env, nullptr, message, &error)); + + report[0] = 1; + const auto deadline = + std::chrono::steady_clock::now() + std::chrono::seconds(20); + while (napi_set_named_property(env, object, "k", one) == napi_ok && + std::chrono::steady_clock::now() < deadline) { + } + + report[1] = napi_throw(env, error); + bool pending = true; + napi_is_exception_pending(env, &pending); + report[2] = pending; + return nullptr; +} + // Leaves an exception pending on the engine itself, not just recorded by // napi_throw_error: Bun's napi_call_function raises the recorded exception // before refusing the call. Returns false if the setup failed (an error has @@ -3892,9 +3968,6 @@ test_napi_adjust_external_memory(const Napi::CallbackInfo &info) { extern "C" { napi_status node_api_set_prototype(napi_env env, napi_value object, napi_value value); -napi_status node_api_create_object_with_properties( - napi_env env, napi_value prototype_or_null, napi_value *property_names, - napi_value *property_values, size_t property_count, napi_value *result); napi_status node_api_is_sharedarraybuffer(napi_env env, napi_value value, bool *result); napi_status node_api_create_sharedarraybuffer(napi_env env, size_t byte_length, @@ -4067,6 +4140,132 @@ test_node_api_sharedarraybuffer(const Napi::CallbackInfo &info) { return ok(env); } +// Reserved but never committed, so it doesn't use any memory. +static constexpr size_t kReservedBytes = (size_t{1} << 32) + 4096; + +static void *reserve_address_space() { +#ifdef _WIN32 + return VirtualAlloc(nullptr, kReservedBytes, MEM_RESERVE, PAGE_NOACCESS); +#else + void *reserved = mmap(nullptr, kReservedBytes, PROT_NONE, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + return reserved == MAP_FAILED ? nullptr : reserved; +#endif +} + +static void release_address_space(void *reserved) { +#ifdef _WIN32 + VirtualFree(reserved, 0, MEM_RELEASE); +#else + munmap(reserved, kReservedBytes); +#endif +} + +static std::atomic reserved_finalize_count{0}; + +static void finalize_reserved(napi_env, void *data, void *) { + reserved_finalize_count++; + release_address_space(data); +} + +static void finalize_reserved_noenv(void *data, void *) { + reserved_finalize_count++; + release_address_space(data); +} + +static std::string string_property(napi_env env, napi_value object, + const char *name) { + napi_value value; + char buf[256]; + size_t len = 0; + if (napi_get_named_property(env, object, name, &value) != napi_ok || + napi_get_value_string_utf8(env, value, buf, sizeof(buf), &len) != + napi_ok) { + return ""; + } + return std::string(buf, len); +} + +// Prints whether an exception is pending. If one is, clears it and prints its +// constructor name and code. +static void print_pending_exception(napi_env env) { + bool pending = false; + napi_is_exception_pending(env, &pending); + printf(" pending=%s", pending ? "true" : "false"); + if (!pending) { + return; + } + napi_value exception; + napi_value constructor; + napi_get_and_clear_last_exception(env, &exception); + napi_get_named_property(env, exception, "constructor", &constructor); + printf(" error=%s code=%s", string_property(env, constructor, "name").c_str(), + string_property(env, exception, "code").c_str()); +} + +// test_external_buffer_length_limit(gc, length) calls each external buffer API +// with `length` on a fresh reservation and prints one line per API. +static napi_value +test_external_buffer_length_limit(const Napi::CallbackInfo &info) { + napi_env env = info.Env(); + double length = 0; + NODE_API_CALL(env, napi_get_value_double(env, info[1], &length)); + + static const char *const names[] = { + "napi_create_external_arraybuffer", + "napi_create_external_buffer", + "node_api_create_external_sharedarraybuffer", + }; + // Never dereferenced. A failed call must not write to *result. + const napi_value untouched = + reinterpret_cast(&reserved_finalize_count); + + for (int api = 0; api < 3; api++) { + void *reserved = reserve_address_space(); + if (reserved == nullptr) { + printf("FAIL: could not reserve %zu bytes of address space\n", + kReservedBytes); + return ok(env); + } + reserved_finalize_count = 0; + napi_value result = untouched; + napi_status status; + if (api == 0) { + status = napi_create_external_arraybuffer( + env, reserved, static_cast(length), finalize_reserved, + nullptr, &result); + } else if (api == 1) { + status = napi_create_external_buffer(env, static_cast(length), + reserved, finalize_reserved, nullptr, + &result); + } else { + status = node_api_create_external_sharedarraybuffer( + env, reserved, static_cast(length), finalize_reserved_noenv, + nullptr, &result); + } + + printf("%s: status=%d", names[api], static_cast(status)); + print_pending_exception(env); + printf(" finalized=%d result=%s", reserved_finalize_count.load(), + result == untouched ? "untouched" : "set"); + if (status == napi_ok) { + napi_value byte_length_value; + double byte_length = -1; + NODE_API_CALL(env, napi_get_named_property(env, result, "byteLength", + &byte_length_value)); + NODE_API_CALL( + env, napi_get_value_double(env, byte_length_value, &byte_length)); + printf(" byteLength=%.0f", byte_length); + } else if (reserved_finalize_count == 0) { + // The call failed and the finalizer didn't run, so the caller still owns + // the bytes. + release_address_space(reserved); + } + printf("\n"); + } + return ok(env); +} + static void noop_tsfn_cb(napi_env, napi_value, void *, void *) {} // Each case below returns a different napi_status in Bun than in Node.js 26 @@ -4634,6 +4833,7 @@ void register_standalone_tests(Napi::Env env, Napi::Object exports) { REGISTER_FUNCTION(env, exports, test_napi_handle_scope_many_args); REGISTER_FUNCTION(env, exports, test_napi_ref); REGISTER_FUNCTION(env, exports, test_napi_run_script); + REGISTER_FUNCTION(env, exports, test_napi_run_script_exception_value); REGISTER_FUNCTION(env, exports, test_napi_throw_with_nullptr); REGISTER_FUNCTION(env, exports, test_extended_error_messages); REGISTER_FUNCTION(env, exports, bigint_to_i64); @@ -4671,6 +4871,7 @@ void register_standalone_tests(Napi::Env env, Napi::Object exports) { REGISTER_FUNCTION(env, exports, external_for_transfer_stats); REGISTER_FUNCTION(env, exports, test_pending_exception_gate); REGISTER_FUNCTION(env, exports, make_ungated_calls_spinner); + REGISTER_FUNCTION(env, exports, gated_calls_until_terminated); REGISTER_FUNCTION(env, exports, test_ungated_calls_with_engine_exception); REGISTER_FUNCTION(env, exports, ungated_calls_through_timeout); REGISTER_FUNCTION(env, exports, test_napi_get_named_property_copied_string); @@ -4681,6 +4882,7 @@ void register_standalone_tests(Napi::Env env, Napi::Object exports) { REGISTER_FUNCTION(env, exports, test_node_api_set_prototype); REGISTER_FUNCTION(env, exports, test_node_api_create_object_with_properties); REGISTER_FUNCTION(env, exports, test_node_api_sharedarraybuffer); + REGISTER_FUNCTION(env, exports, test_external_buffer_length_limit); REGISTER_FUNCTION(env, exports, test_napi_status_codes_node26); REGISTER_FUNCTION(env, exports, test_tsfn_null_js_callback); REGISTER_FUNCTION(env, exports, test_tsfn_null_js_callback_ran); diff --git a/test/napi/napi.test.ts b/test/napi/napi.test.ts index 2a6082c4ddbc..def9ab3a30e1 100644 --- a/test/napi/napi.test.ts +++ b/test/napi/napi.test.ts @@ -10,11 +10,12 @@ import { isMacOS, isMusl, isWindows, + mergeWindowEnvs, noCoreCmd, nodeExeMatchingAbi, tempDir, } from "harness"; -import { join } from "path"; +import { dirname, join } from "path"; // The napi-app addons don't link against bun, so existing binaries stay valid // across bun builds. `bun install` runs a full `node-gyp rebuild` (clean + build @@ -318,6 +319,34 @@ describe.concurrent.skipIf(!canBuildNodeAddons())("napi", () => { it("keeps arguments moved off the stack alive", async () => { await checkSameOutput("test_napi_handle_scope_many_args", ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]); }); + it("exists when bun test --isolate calls a function that an earlier file created", async () => { + // The addon is loaded once per process, so its reference keeps the function of the first file for the second one. + const testFile = ` + import { expect, test } from "bun:test"; + const addon = require(${JSON.stringify(join(__dirname, "napi-app/build/Debug/napitests.node"))}); + test("keeps strings alive", () => { + let first; + try { + first = addon.get_object_from_ref(); + } catch { + addon.create_wrap({ keepsStringsAlive: addon.test_napi_handle_scope_string }, true, true); + return; + } + expect(first.keepsStringsAlive(() => Bun.gc(true))).toBeUndefined(); + }); + `; + using dir = tempDir("napi-isolate", { "a.test.ts": testFile, "b.test.ts": testFile }); + await using proc = spawn({ + cmd: [bunExe(), "test", "--isolate", "./a.test.ts", "./b.test.ts"], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]); + expect(stderr).toContain(" 2 pass"); + expect(exitCode).toBe(0); + }); }); describe("escapable_handle_scope", () => { @@ -647,6 +676,18 @@ describe.concurrent.skipIf(!canBuildNodeAddons())("napi", () => { }); }); + // Node wraps this length around, so this only runs on Bun. + it("creating an external buffer larger than 2 ** 32 bytes fails with ERR_BUFFER_TOO_LARGE", async () => { + const result = await runOn(bunExe(), "test_external_buffer_length_limit", [2 ** 32 + 1]); + expect(result.trim().split(/\r?\n/)).toEqual( + [ + "napi_create_external_arraybuffer", + "napi_create_external_buffer", + "node_api_create_external_sharedarraybuffer", + ].map(api => `${api}: status=9 pending=true error=Error code=ERR_BUFFER_TOO_LARGE finalized=0 result=untouched`), + ); + }); + // The finalizer of an external buffer belongs to the env that created it, and that env's // teardown frees the bytes, so the bytes must not be transferred to another thread. describe("external buffers are untransferable", () => { @@ -814,6 +855,16 @@ describe.concurrent.skipIf(!canBuildNodeAddons())("napi", () => { const result = await checkSameOutput("test_ungated_calls_worker_terminate", []); expect(result.split(/\r?\n/)).toEqual([...Array(2).fill("terminate() resolved with 1"), "resolved to undefined"]); }, 30_000); + + // node-addon-api aborts the process if a refused call leaves an exception pending that it cannot clear. + it("worker.terminate() during a gated call leaves no exception pending", async () => { + const result = await checkSameOutput("test_gated_calls_worker_terminate", []); + expect(result.split(/\r?\n/)).toEqual([ + "terminate() resolved with 1", + "napi_throw: 23 exception pending: 0", + "resolved to undefined", + ]); + }); }); describe("status code alignment with Node.js", () => { @@ -913,6 +964,14 @@ describe.concurrent.skipIf(!canBuildNodeAddons())("napi", () => { expect(output).toContain("success!"); expect(output).not.toContain("failure!"); }); + it("worker.terminate() runs no finalizer while execute() runs", async () => { + const output = await checkSameOutput("test_async_work_worker_terminate", []); + expect(output.split(/\r?\n/)).toEqual([ + "terminate() resolved with 1", + "finalized during execute(): 0", + "resolved to undefined", + ]); + }); }); describe("napi_threadsafe_function", () => { @@ -1498,6 +1557,12 @@ describe.concurrent.skipIf(!canBuildNodeAddons())("napi", () => { it("propagates exceptions", async () => { await checkSameOutput("test_napi_run_script", ["(()=>{ throw new TypeError('oops'); })()"]); }); + it("passes the thrown value to napi_get_and_clear_last_exception", async () => { + const result = await checkSameOutput("test_napi_run_script_exception_value", ['throw new RangeError("boom")']); + expect(result).toContain("run status=9 pending=1"); + expect(result).toContain("typeof status=0 type=6 is_error=1"); + expect(result).toContain("message=boom"); + }); it("cannot see locals from around its invocation", async () => { // variable should_not_exist is declared on main.js:18, but it should not be in scope for the eval'd code // this doesn't use await checkSameOutput because V8 and JSC use different error messages for a missing variable @@ -2043,6 +2108,41 @@ describe.concurrent.skipIf(!canBuildNodeAddons())("napi", () => { expect(exitCode).toBe(0); }); + it("runs the outer module's init function when the module.exports getter loads another addon", async () => { + // process.dlopen reads module.exports a second time to pass it to the init function. + const script = ` + const build = ${JSON.stringify(join(__dirname, "napi-app", "build", "Debug"))}; + const exports = {}; + let reads = 0; + const outer = { + get exports() { + if (++reads === 2) process.dlopen({ exports: {} }, build + "/reentrant_register_addon.node"); + return exports; + }, + }; + process.dlopen(outer, build + "/constructor_order_addon.node"); + `; + await using proc = spawn({ + cmd: [bunExe(), "-e", script], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + // On Windows each addon has its own stdout buffer, so line order is only guaranteed within one addon. + const lines = stdout.split(/\r?\n/).filter(Boolean); + const outer = ["call_register", "init_static", "register_cb"]; + expect({ + outer: lines.filter(line => outer.includes(line)), + inner: lines.filter(line => !outer.includes(line)), + }).toEqual({ + outer, + inner: ["register_cb_a", "register_cb_b", "register_cb_reentrant x 64"], + }); + expect(exitCode).toBe(0); + }); + it("behaves as expected when performing operations with an exception pending", async () => { await checkSameOutput("test_deferred_exceptions", []); }); @@ -2323,6 +2423,59 @@ describe.concurrent.skipIf(!canBuildNodeAddons())("napi", () => { }, 25_000, ); + + // Off Windows these fixtures are ordinary addons, so this only checks that they load. + describe("an addon that imports node.exe without win_delay_load_hook", () => { + const fixtures = { + no_delay_load_hook_addon: { delayLoad: true, missing: false }, + regular_node_exe_import_addon: { delayLoad: false, missing: false }, + no_delay_load_hook_ctor_addon: { delayLoad: true, missing: false }, + regular_node_exe_import_ctor_addon: { delayLoad: false, missing: false }, + regular_node_exe_import_missing_addon: { delayLoad: false, missing: true }, + } as const; + type Fixture = keyof typeof fixtures; + const fixtureNames = Object.keys(fixtures) as Fixture[]; + + // PATH is a single directory and the cwd is empty, so the DLL search path contains at most one node.exe. + async function load(target: Fixture, nodeOnPath: boolean) { + using dir = tempDir("napi-node-exe-import", {}); + const addon = join(__dirname, `napi-app/build/Debug/${target}.node`); + await using proc = spawn({ + cmd: [ + bunExe(), + "-e", + `try { console.log(require(${JSON.stringify(addon)}).hello()); } catch (e) { console.log(e.code + ": " + e.message); process.exit(1); }`, + ], + env: mergeWindowEnvs([bunEnv, { PATH: nodeOnPath ? dirname(await nodeExeMatchingAbi()) : String(dir) }]), + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { stdout: stdout.trim(), stderr, exitCode }; + } + const loaded = { stdout: "hello", stderr: "", exitCode: 0 }; + + it.each(fixtureNames)("%s loads with node.exe on PATH", async target => { + const result = await load(target, true); + if (isWindows && fixtures[target].missing) { + expect(result.stdout).toStartWith("ERR_DLOPEN_FAILED: Cannot load native addon "); + expect(result.stdout).toEndWith( + `${target}.node imports 'OpenSSL_version_num' from node.exe, which Bun does not provide`, + ); + expect(result.exitCode).toBe(1); + } else { + expect(result).toEqual(loaded); + } + }); + + it.skipIf(!isWindows).each(fixtureNames.filter(target => fixtures[target].delayLoad))( + "%s loads without a node.exe on the DLL search path", + async target => { + expect(await load(target, false)).toEqual(loaded); + }, + ); + }); }); // Kept outside describe.concurrent("napi") so RSS measurement isn't skewed by diff --git a/test/napi/node-napi-tests/harness.ts b/test/napi/node-napi-tests/harness.ts index 93379e4181c6..b3aa8692c37f 100644 --- a/test/napi/node-napi-tests/harness.ts +++ b/test/napi/node-napi-tests/harness.ts @@ -10,7 +10,7 @@ import { bunExe, bunEnv, isCI, isMusl } from "../../harness"; const abortingJsNativeApiTests = ["test_finalizer/test_fatal_finalize.js"]; // Must match the npm_config_target passed to node-gyp below (without the leading "v"). -const NODE_HEADERS_VERSION = "26.3.0"; +const NODE_HEADERS_VERSION = "26.12.1"; const linuxClang = !isMusl ? "/opt/llvm/bin/clang" : "/usr/lib/llvm23/bin/clang"; diff --git a/test/napi/node-napi-tests/test/node-api/test_callback_scope/do.test.ts b/test/napi/node-napi-tests/test/node-api/test_callback_scope/do.test.ts index b415716c512f..769814ef6a44 100644 --- a/test/napi/node-napi-tests/test/node-api/test_callback_scope/do.test.ts +++ b/test/napi/node-napi-tests/test/node-api/test_callback_scope/do.test.ts @@ -7,12 +7,11 @@ test("build", async () => { }); for (const file of Array.from(new Bun.Glob("*.js").scanSync(import.meta.dir))) { - // crash inside uv_queue_work - // https://github.com/oven-sh/bun/issues/12827 is the latter - test.todoIf(["test-resolve-async.js", "test-async-hooks.js"].includes(file) || (file === "test.js" && isWindows))( - file, - () => { - run(dirname(import.meta.dir), basename(import.meta.dir) + sep + file); - }, - ); + // test-async-hooks.js: https://github.com/oven-sh/bun/issues/12827 + // test-resolve-async.js on Windows: the process exits before uv_queue_work's after_work_cb runs. + test.todoIf( + file === "test-async-hooks.js" || (["test.js", "test-resolve-async.js"].includes(file) && isWindows), + )(file, () => { + run(dirname(import.meta.dir), basename(import.meta.dir) + sep + file); + }); } diff --git a/test/napi/uv-stub-stuff/plugin.c b/test/napi/uv-stub-stuff/plugin.c index 932e776ec352..e22c47f629e9 100644 --- a/test/napi/uv-stub-stuff/plugin.c +++ b/test/napi/uv-stub-stuff/plugin.c @@ -45,22 +45,6 @@ napi_value call_uv_func(napi_env env, napi_callback_info info) { return NULL; } - if (strcmp(buffer, "uv_async_init") == 0) { - uv_loop_t *arg0 = {0}; - uv_async_t *arg1 = {0}; - uv_async_cb arg2 = NULL; - - uv_async_init(arg0, arg1, arg2); - return NULL; - } - - if (strcmp(buffer, "uv_async_send") == 0) { - uv_async_t *arg0 = {0}; - - uv_async_send(arg0); - return NULL; - } - if (strcmp(buffer, "uv_available_parallelism") == 0) { uv_available_parallelism(); @@ -111,13 +95,6 @@ napi_value call_uv_func(napi_env env, napi_callback_info info) { return NULL; } - if (strcmp(buffer, "uv_cancel") == 0) { - uv_req_t *arg0 = {0}; - - uv_cancel(arg0); - return NULL; - } - if (strcmp(buffer, "uv_chdir") == 0) { const char *arg0 = {0}; @@ -156,14 +133,6 @@ napi_value call_uv_func(napi_env env, napi_callback_info info) { return NULL; } - if (strcmp(buffer, "uv_close") == 0) { - uv_handle_t *arg0 = {0}; - uv_close_cb arg1 = NULL; - - uv_close(arg0, arg1); - return NULL; - } - if (strcmp(buffer, "uv_cond_broadcast") == 0) { uv_cond_t *arg0 = {0}; @@ -223,20 +192,6 @@ napi_value call_uv_func(napi_env env, napi_callback_info info) { return NULL; } - if (strcmp(buffer, "uv_cwd") == 0) { - char *arg0 = {0}; - size_t *arg1 = {0}; - - uv_cwd(arg0, arg1); - return NULL; - } - - if (strcmp(buffer, "uv_default_loop") == 0) { - - uv_default_loop(); - return NULL; - } - if (strcmp(buffer, "uv_disable_stdio_inheritance") == 0) { uv_disable_stdio_inheritance(); @@ -867,13 +822,6 @@ napi_value call_uv_func(napi_env env, napi_callback_info info) { return NULL; } - if (strcmp(buffer, "uv_get_osfhandle") == 0) { - int arg0 = {0}; - - uv_get_osfhandle(arg0); - return NULL; - } - if (strcmp(buffer, "uv_get_process_title") == 0) { char *arg0 = {0}; size_t arg1 = {0}; @@ -932,56 +880,6 @@ napi_value call_uv_func(napi_env env, napi_callback_info info) { return NULL; } - if (strcmp(buffer, "uv_handle_get_data") == 0) { - const uv_handle_t *arg0 = {0}; - - uv_handle_get_data(arg0); - return NULL; - } - - if (strcmp(buffer, "uv_handle_get_loop") == 0) { - const uv_handle_t *arg0 = {0}; - - uv_handle_get_loop(arg0); - return NULL; - } - - if (strcmp(buffer, "uv_handle_get_type") == 0) { - const uv_handle_t *arg0 = {0}; - - uv_handle_get_type(arg0); - return NULL; - } - - if (strcmp(buffer, "uv_handle_set_data") == 0) { - uv_handle_t *arg0 = {0}; - void *arg1 = {0}; - - uv_handle_set_data(arg0, arg1); - return NULL; - } - - if (strcmp(buffer, "uv_handle_size") == 0) { - uv_handle_type arg0 = {0}; - - uv_handle_size(arg0); - return NULL; - } - - if (strcmp(buffer, "uv_handle_type_name") == 0) { - uv_handle_type arg0 = {0}; - - uv_handle_type_name(arg0); - return NULL; - } - - if (strcmp(buffer, "uv_has_ref") == 0) { - const uv_handle_t *arg0 = {0}; - - uv_has_ref(arg0); - return NULL; - } - if (strcmp(buffer, "uv_idle_init") == 0) { uv_loop_t *arg0 = {0}; uv_idle_t *arg1 = {0}; @@ -1095,20 +993,6 @@ napi_value call_uv_func(napi_env env, napi_callback_info info) { return NULL; } - if (strcmp(buffer, "uv_is_active") == 0) { - const uv_handle_t *arg0 = {0}; - - uv_is_active(arg0); - return NULL; - } - - if (strcmp(buffer, "uv_is_closing") == 0) { - const uv_handle_t *arg0 = {0}; - - uv_is_closing(arg0); - return NULL; - } - if (strcmp(buffer, "uv_is_readable") == 0) { const uv_stream_t *arg0 = {0}; @@ -1218,13 +1102,6 @@ napi_value call_uv_func(napi_env env, napi_callback_info info) { return NULL; } - if (strcmp(buffer, "uv_loop_get_data") == 0) { - const uv_loop_t *arg0 = {0}; - - uv_loop_get_data(arg0); - return NULL; - } - if (strcmp(buffer, "uv_loop_init") == 0) { uv_loop_t *arg0 = {0}; @@ -1238,14 +1115,6 @@ napi_value call_uv_func(napi_env env, napi_callback_info info) { return NULL; } - if (strcmp(buffer, "uv_loop_set_data") == 0) { - uv_loop_t *arg0 = {0}; - void *arg1 = {0}; - - uv_loop_set_data(arg0, arg1); - return NULL; - } - if (strcmp(buffer, "uv_loop_size") == 0) { uv_loop_size(); @@ -1274,13 +1143,6 @@ napi_value call_uv_func(napi_env env, napi_callback_info info) { return NULL; } - if (strcmp(buffer, "uv_open_osfhandle") == 0) { - uv_os_fd_t arg0 = {0}; - - uv_open_osfhandle(arg0); - return NULL; - } - if (strcmp(buffer, "uv_os_environ") == 0) { uv_env_item_t **arg0 = NULL; int *arg1 = {0}; @@ -1607,16 +1469,6 @@ napi_value call_uv_func(napi_env env, napi_callback_info info) { return NULL; } - if (strcmp(buffer, "uv_queue_work") == 0) { - uv_loop_t *arg0 = {0}; - uv_work_t *arg1 = {0}; - uv_work_cb arg2 = NULL; - uv_after_work_cb arg3 = NULL; - - uv_queue_work(arg0, arg1, arg2, arg3); - return NULL; - } - if (strcmp(buffer, "uv_random") == 0) { uv_loop_t *arg0 = {0}; uv_random_t *arg1 = {0}; @@ -1653,13 +1505,6 @@ napi_value call_uv_func(napi_env env, napi_callback_info info) { return NULL; } - if (strcmp(buffer, "uv_ref") == 0) { - uv_handle_t *arg0 = {0}; - - uv_ref(arg0); - return NULL; - } - if (strcmp(buffer, "uv_replace_allocator") == 0) { uv_malloc_func arg0 = {0}; uv_realloc_func arg1 = {0}; @@ -1670,42 +1515,6 @@ napi_value call_uv_func(napi_env env, napi_callback_info info) { return NULL; } - if (strcmp(buffer, "uv_req_get_data") == 0) { - const uv_req_t *arg0 = {0}; - - uv_req_get_data(arg0); - return NULL; - } - - if (strcmp(buffer, "uv_req_get_type") == 0) { - const uv_req_t *arg0 = {0}; - - uv_req_get_type(arg0); - return NULL; - } - - if (strcmp(buffer, "uv_req_set_data") == 0) { - uv_req_t *arg0 = {0}; - void *arg1 = {0}; - - uv_req_set_data(arg0, arg1); - return NULL; - } - - if (strcmp(buffer, "uv_req_size") == 0) { - uv_req_type arg0 = {0}; - - uv_req_size(arg0); - return NULL; - } - - if (strcmp(buffer, "uv_req_type_name") == 0) { - uv_req_type arg0 = {0}; - - uv_req_type_name(arg0); - return NULL; - } - if (strcmp(buffer, "uv_resident_set_memory") == 0) { size_t *arg0 = {0}; @@ -2406,13 +2215,6 @@ napi_value call_uv_func(napi_env env, napi_callback_info info) { return NULL; } - if (strcmp(buffer, "uv_unref") == 0) { - uv_handle_t *arg0 = {0}; - - uv_unref(arg0); - return NULL; - } - if (strcmp(buffer, "uv_update_time") == 0) { uv_loop_t *arg0 = {0}; @@ -2427,18 +2229,6 @@ napi_value call_uv_func(napi_env env, napi_callback_info info) { return NULL; } - if (strcmp(buffer, "uv_version") == 0) { - - uv_version(); - return NULL; - } - - if (strcmp(buffer, "uv_version_string") == 0) { - - uv_version_string(); - return NULL; - } - if (strcmp(buffer, "uv_walk") == 0) { uv_loop_t *arg0 = {0}; uv_walk_cb arg1 = NULL; diff --git a/test/napi/uv-stub-stuff/uv_impl.c b/test/napi/uv-stub-stuff/uv_impl.c index 6e75a5816866..5e4f2560287b 100644 --- a/test/napi/uv-stub-stuff/uv_impl.c +++ b/test/napi/uv-stub-stuff/uv_impl.c @@ -2,7 +2,11 @@ #include #include +#include +#include +#include #include +#include #include #include #include @@ -103,6 +107,47 @@ static napi_value test_uv_once(napi_env env, napi_callback_info info) { return ret; } +// Test uv_cwd +static napi_value test_cwd(napi_env env, napi_callback_info info) { + napi_value obj; + napi_create_object(env, &obj); + + napi_value v; + + napi_create_int32(env, UV_EINVAL, &v); + napi_set_named_property(env, obj, "UV_EINVAL", v); + napi_create_int32(env, UV_ENOBUFS, &v); + napi_set_named_property(env, obj, "UV_ENOBUFS", v); + + size_t zero = 0; + size_t one = 1; + char dummy[1]; + napi_create_int32(env, uv_cwd(NULL, &one), &v); + napi_set_named_property(env, obj, "nullBuffer", v); + napi_create_int32(env, uv_cwd(dummy, NULL), &v); + napi_set_named_property(env, obj, "nullSize", v); + napi_create_int32(env, uv_cwd(dummy, &zero), &v); + napi_set_named_property(env, obj, "zeroSize", v); + + char small[2]; + size_t small_size = sizeof(small); + napi_create_int32(env, uv_cwd(small, &small_size), &v); + napi_set_named_property(env, obj, "smallRc", v); + napi_create_int64(env, (int64_t)small_size, &v); + napi_set_named_property(env, obj, "smallRequired", v); + + char buf[4096]; + size_t size = sizeof(buf); + napi_create_int32(env, uv_cwd(buf, &size), &v); + napi_set_named_property(env, obj, "rc", v); + napi_create_string_utf8(env, buf, size, &v); + napi_set_named_property(env, obj, "cwd", v); + napi_create_int64(env, (int64_t)size, &v); + napi_set_named_property(env, obj, "size", v); + + return obj; +} + // Test uv_hrtime static napi_value test_hrtime(napi_env env, napi_callback_info info) { uint64_t time1 = uv_hrtime(); @@ -187,10 +232,1028 @@ static napi_value test_tty_reset_mode_concurrent(napi_env env, return obj; } +// --------------------------------------------------------------------------- +// Tests for the loop-backed functions: uv_default_loop, uv_queue_work, the +// uv_async_t, uv_idle_t, uv_prepare_t, uv_check_t and uv_timer_t handles, and +// their header-only helpers. Each test reports events through a JS callback +// `(event, a, b)` so uv.test.ts can check callback order, thread and loop +// iteration. uv.test.ts runs them in a child process because a stubbed uv_* +// function aborts. +// --------------------------------------------------------------------------- + +struct reporter { + napi_env env; + napi_ref callback; +}; + +static void reporter_init(struct reporter *r, napi_env env, + napi_value callback) { + r->env = env; + napi_create_reference(env, callback, 1, &r->callback); +} + +// Calls the JS callback. Ignores the call's status on purpose, because one test +// throws from the callback to check that the exception is reported as uncaught. +static void report(struct reporter *r, const char *event, int32_t a, + int32_t b) { + napi_env env = r->env; + napi_handle_scope scope; + napi_open_handle_scope(env, &scope); + napi_value callback, undefined, argv[3]; + napi_get_reference_value(env, r->callback, &callback); + napi_get_undefined(env, &undefined); + napi_create_string_utf8(env, event, NAPI_AUTO_LENGTH, &argv[0]); + napi_create_int32(env, a, &argv[1]); + napi_create_int32(env, b, &argv[2]); + napi_call_function(env, undefined, callback, 3, argv, NULL); + napi_close_handle_scope(env, scope); +} + +static void reporter_destroy(struct reporter *r) { + napi_delete_reference(r->env, r->callback); +} + +static uv_loop_t *get_loop(napi_env env, bool use_default_loop) { + if (use_default_loop) + return uv_default_loop(); + uv_loop_t *loop = NULL; + napi_get_uv_event_loop(env, &loop); + return loop; +} + +static napi_value make_int32_array(napi_env env, const int32_t *values, + size_t count) { + napi_value array; + napi_create_array_with_length(env, count, &array); + for (size_t i = 0; i < count; i++) { + napi_value value; + napi_create_int32(env, values[i], &value); + napi_set_element(env, array, (uint32_t)i, value); + } + return array; +} + +static void set_int32(napi_env env, napi_value object, const char *name, + int32_t value) { + napi_value number; + napi_create_int32(env, value, &number); + napi_set_named_property(env, object, name, number); +} + +static void get_args(napi_env env, napi_callback_info info, napi_value *args, + size_t count) { + size_t argc = count; + napi_get_cb_info(env, info, &argc, args, NULL, NULL); +} + +static bool as_bool(napi_env env, napi_value value) { + bool result = false; + napi_get_value_bool(env, value, &result); + return result; +} + +// testVersion() returns { version, versionString }. +static napi_value test_version(napi_env env, napi_callback_info info) { + napi_value result, version, version_string; + napi_create_object(env, &result); + napi_create_uint32(env, uv_version(), &version); + napi_create_string_utf8(env, uv_version_string(), NAPI_AUTO_LENGTH, + &version_string); + napi_set_named_property(env, result, "version", version); + napi_set_named_property(env, result, "versionString", version_string); + return result; +} + +// testSizesAndNames() checks uv_handle_size, uv_req_size and the type names +// against the headers this addon was compiled with. Addons rely on these to +// allocate handles dynamically. +static napi_value test_sizes_and_names(napi_env env, napi_callback_info info) { + napi_value result, value; + napi_create_object(env, &result); + + napi_get_boolean(env, uv_handle_size(UV_ASYNC) == sizeof(uv_async_t), &value); + napi_set_named_property(env, result, "asyncSizeMatches", value); + napi_get_boolean(env, uv_handle_size(UV_TIMER) == sizeof(uv_timer_t), &value); + napi_set_named_property(env, result, "timerSizeMatches", value); + napi_get_boolean(env, uv_handle_size(UV_UNKNOWN_HANDLE) == (size_t)-1, + &value); + napi_set_named_property(env, result, "unknownHandleSizeIsMinusOne", value); + napi_get_boolean(env, uv_req_size(UV_WORK) == sizeof(uv_work_t), &value); + napi_set_named_property(env, result, "workSizeMatches", value); + napi_get_boolean(env, uv_req_size(UV_UNKNOWN_REQ) == (size_t)-1, &value); + napi_set_named_property(env, result, "unknownReqSizeIsMinusOne", value); + napi_create_uint32(env, (uint32_t)sizeof(uv_async_t), &value); + napi_set_named_property(env, result, "asyncSize", value); + + napi_create_string_utf8(env, uv_handle_type_name(UV_ASYNC), NAPI_AUTO_LENGTH, + &value); + napi_set_named_property(env, result, "asyncName", value); + napi_create_string_utf8(env, uv_handle_type_name(UV_NAMED_PIPE), + NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "pipeName", value); + napi_create_string_utf8(env, uv_req_type_name(UV_WORK), NAPI_AUTO_LENGTH, + &value); + napi_set_named_property(env, result, "workName", value); + napi_get_boolean(env, uv_handle_type_name(UV_UNKNOWN_HANDLE) == NULL, &value); + napi_set_named_property(env, result, "unknownHandleNameIsNull", value); + napi_get_boolean(env, uv_req_type_name(UV_UNKNOWN_REQ) == NULL, &value); + napi_set_named_property(env, result, "unknownReqNameIsNull", value); + return result; +} + +// testOsfhandle(fd) returns uv_open_osfhandle(uv_get_osfhandle(fd)), which is +// `fd` on Unix. +static napi_value test_osfhandle(napi_env env, napi_callback_info info) { + size_t argc = 1; + napi_value args[1]; + napi_get_cb_info(env, info, &argc, args, NULL, NULL); + int32_t fd = -1; + napi_get_value_int32(env, args[0], &fd); + napi_value result; + napi_create_int32(env, uv_open_osfhandle(uv_get_osfhandle(fd)), &result); + return result; +} + +static void *call_uv_default_loop(void *out) { + *(uv_loop_t **)out = uv_default_loop(); + return NULL; +} + +// testLoops() checks how the loops relate. On the main thread, +// napi_get_uv_event_loop returns uv_default_loop(). In a Worker it returns the +// Worker's own loop. uv_default_loop() is the same loop on every thread, and +// its `data` slot belongs to the addon. +static napi_value test_loops(napi_env env, napi_callback_info info) { + uv_loop_t *napi_loop = get_loop(env, false); + uv_loop_t *default_loop = uv_default_loop(); + uv_loop_t *default_loop_from_thread = NULL; + pthread_t thread; + if (pthread_create(&thread, NULL, call_uv_default_loop, + &default_loop_from_thread) != 0) { + napi_throw_error(env, NULL, "pthread_create failed"); + return NULL; + } + pthread_join(thread, NULL); + + int marker; + uv_loop_set_data(napi_loop, &marker); + bool data_round_trips = + uv_loop_get_data(napi_loop) == &marker && napi_loop->data == ▮ + uv_loop_set_data(napi_loop, NULL); + + napi_value result, value; + napi_create_object(env, &result); + napi_get_boolean(env, napi_loop != NULL, &value); + napi_set_named_property(env, result, "napiLoopIsSet", value); + napi_get_boolean(env, napi_loop == default_loop, &value); + napi_set_named_property(env, result, "napiLoopIsDefaultLoop", value); + napi_get_boolean(env, default_loop_from_thread == default_loop, &value); + napi_set_named_property(env, result, "defaultLoopIsSameFromThread", value); + napi_get_boolean(env, data_round_trips, &value); + napi_set_named_property(env, result, "loopDataRoundTrips", value); + return result; +} + +// testErrors() returns the result of each invalid call, all UV_EINVAL (listed +// in uv.test.ts). It closes the two handles it initializes so the process can +// exit. They're static because a handle must outlive its close. +static void unused_async_cb(uv_async_t *handle) { (void)handle; } +static void unused_idle_cb(uv_idle_t *handle) { (void)handle; } +static void unused_timer_cb(uv_timer_t *handle) { (void)handle; } + +static uv_idle_t errors_idle; +static uv_timer_t errors_timer; + +static napi_value test_errors(napi_env env, napi_callback_info info) { + uv_loop_t *loop = get_loop(env, false); + uv_async_t async; + uv_check_t check; + uv_timer_t timer; + uv_work_t work; + uv_req_t not_work; + memset(¬_work, 0, sizeof(not_work)); + if (uv_idle_init(loop, &errors_idle) != 0 || + uv_timer_init(loop, &errors_timer) != 0) { + napi_throw_error(env, NULL, "init failed"); + return NULL; + } + int32_t results[] = { + uv_async_init(NULL, &async, unused_async_cb), + uv_check_init(NULL, &check), + uv_timer_init(NULL, &timer), + uv_queue_work(loop, &work, NULL, NULL), + uv_cancel(¬_work), + // No callback. + uv_idle_start(&errors_idle, NULL), + uv_timer_start(&errors_timer, NULL, 0, 0), + // Never started, so there's nothing to repeat. + uv_timer_again(&errors_timer), + // Wrong handle type. + uv_prepare_start((uv_prepare_t *)&errors_idle, + (uv_prepare_cb)unused_idle_cb), + uv_prepare_stop((uv_prepare_t *)&errors_idle), + uv_idle_start((uv_idle_t *)&errors_timer, unused_idle_cb), + uv_timer_start((uv_timer_t *)&errors_idle, unused_timer_cb, 0, 0), + uv_timer_stop((uv_timer_t *)&errors_idle), + uv_timer_again((uv_timer_t *)&errors_idle), + }; + uv_close((uv_handle_t *)&errors_idle, NULL); + uv_close((uv_handle_t *)&errors_timer, NULL); + return make_int32_array(env, results, sizeof(results) / sizeof(results[0])); +} + +// --- uv_async_t ------------------------------------------------------------- + +struct async_test { + uv_async_t handle; + struct reporter reporter; + int calls; +}; + +static void async_test_close_cb(uv_handle_t *handle) { + struct async_test *test = handle->data; + report(&test->reporter, "close", uv_is_closing(handle), + uv_handle_get_data(handle) == test); + reporter_destroy(&test->reporter); + free(test); +} + +static void async_test_cb(uv_async_t *handle) { + struct async_test *test = handle->data; + test->calls++; + report(&test->reporter, "async", test->calls, + uv_is_active((uv_handle_t *)handle)); + if (test->calls == 1) { + // A send from inside the callback must trigger another callback. + uv_async_send(handle); + return; + } + uv_close((uv_handle_t *)handle, async_test_close_cb); + // The handle is closing immediately, but close_cb runs later. + report(&test->reporter, "closing", uv_is_closing((uv_handle_t *)handle), + uv_is_active((uv_handle_t *)handle)); +} + +static void *send_after_a_while(void *arg) { + usleep(30 * 1000); + uv_async_send(arg); + return NULL; +} + +// Calls uv_async_init and throws if it fails, so the test fails here instead of +// on bogus events from an uninitialized handle. +static bool init_async(napi_env env, uv_loop_t *loop, uv_async_t *handle, + uv_async_cb cb) { + int rc = uv_async_init(loop, handle, cb); + if (rc != 0) { + char message[64]; + snprintf(message, sizeof(message), "uv_async_init returned %d", rc); + napi_throw_error(env, NULL, message); + return false; + } + return true; +} + +// testAsync(useDefaultLoop, sendFromThread, callback) reports these events: +// async 1 1 first callback, for the three coalesced sends +// async 2 1 the callback's own send +// closing 1 0 right after uv_close +// close 1 1 the deferred close callback +// The calling script returns right away, so only the ref'd handle keeps the +// process alive until the events fire. +// Returns [is_active, is_closing, has_ref] right after init. +static napi_value test_async(napi_env env, napi_callback_info info) { + napi_value args[3]; + get_args(env, info, args, 3); + bool use_default_loop = as_bool(env, args[0]); + bool send_from_thread = as_bool(env, args[1]); + + struct async_test *test = calloc(1, sizeof(*test)); + reporter_init(&test->reporter, env, args[2]); + test->handle.data = test; // set before init, as addons commonly do + uv_loop_t *loop = get_loop(env, use_default_loop); + if (!init_async(env, loop, &test->handle, async_test_cb)) + return NULL; + if (test->handle.data != test || + uv_handle_get_loop((uv_handle_t *)&test->handle) != loop || + uv_handle_get_type((uv_handle_t *)&test->handle) != UV_ASYNC) { + napi_throw_error(env, NULL, "uv_async_init didn't set up the handle"); + return NULL; + } + int32_t observed[3] = { + uv_is_active((uv_handle_t *)&test->handle), + uv_is_closing((uv_handle_t *)&test->handle), + uv_has_ref((uv_handle_t *)&test->handle), + }; + + if (send_from_thread) { + pthread_t thread; + if (pthread_create(&thread, NULL, send_after_a_while, &test->handle) != 0) { + napi_throw_error(env, NULL, "pthread_create failed"); + return NULL; + } + pthread_detach(thread); + } else { + // Nothing can run the callback between these, so they coalesce into one. + uv_async_send(&test->handle); + uv_async_send(&test->handle); + uv_async_send(&test->handle); + } + return make_int32_array(env, observed, 3); +} + +// testAsyncCloseWithSendPending(callback) sends and then closes a handle before +// the loop iterates, so only the close callback runs. A send after uv_close +// (allowed until close_cb) doesn't trigger a callback either. +// Returns [is_active, is_closing, send after close] right after uv_close. +static napi_value test_async_close_with_send_pending(napi_env env, + napi_callback_info info) { + napi_value args[1]; + get_args(env, info, args, 1); + struct async_test *test = calloc(1, sizeof(*test)); + reporter_init(&test->reporter, env, args[0]); + if (!init_async(env, get_loop(env, false), &test->handle, async_test_cb)) + return NULL; + uv_handle_set_data((uv_handle_t *)&test->handle, test); + uv_async_send(&test->handle); + uv_close((uv_handle_t *)&test->handle, async_test_close_cb); + uv_close((uv_handle_t *)&test->handle, async_test_close_cb); // ignored + int32_t observed[3] = { + uv_is_active((uv_handle_t *)&test->handle), + uv_is_closing((uv_handle_t *)&test->handle), + uv_async_send(&test->handle), + }; + return make_int32_array(env, observed, 3); +} + +// --- uv_async_send from another thread --------------------------------------- + +#define STRESS_ROUNDS 200 +#define STRESS_BURST 2000 + +struct stress_test { + uv_async_t handle; + struct reporter reporter; + pthread_t sender; + atomic_int callbacks; +}; + +static void *stress_sender(void *arg) { + struct stress_test *test = arg; + // Each round is one send and one callback. A send that arrives after the loop + // consumed the previous one must wake the loop again. A lost wakeup hangs + // here until the test times out. + for (int round = 1; round <= STRESS_ROUNDS; round++) { + uv_async_send(&test->handle); + while (atomic_load(&test->callbacks) < round) + sched_yield(); + } + // The pending flag was cleared before the last round's callback ran, so this + // burst triggers exactly one more callback, which closes the handle. The + // remaining sends arrive during or after uv_close, which is allowed until + // close_cb runs. close_cb joins this thread before it frees the handle. + for (int i = 0; i < STRESS_BURST; i++) + uv_async_send(&test->handle); + return NULL; +} + +static void stress_close_cb(uv_handle_t *handle) { + struct stress_test *test = handle->data; + pthread_join(test->sender, NULL); + report(&test->reporter, "done", atomic_load(&test->callbacks), + uv_is_closing(handle)); + reporter_destroy(&test->reporter); + free(test); +} + +static void stress_async_cb(uv_async_t *handle) { + struct stress_test *test = handle->data; + if (atomic_fetch_add(&test->callbacks, 1) + 1 > STRESS_ROUNDS) + uv_close((uv_handle_t *)handle, stress_close_cb); +} + +// testAsyncStress(callback) reports `done 1`: one callback +// per round, plus one for the burst, which closes the handle. +static napi_value test_async_stress(napi_env env, napi_callback_info info) { + napi_value args[1]; + get_args(env, info, args, 1); + struct stress_test *test = calloc(1, sizeof(*test)); + reporter_init(&test->reporter, env, args[0]); + test->handle.data = test; + if (!init_async(env, get_loop(env, false), &test->handle, stress_async_cb)) + return NULL; + if (pthread_create(&test->sender, NULL, stress_sender, test) != 0) { + napi_throw_error(env, NULL, "pthread_create failed"); + return NULL; + } + return NULL; +} + +static struct { + uv_async_t handle; + pthread_t sender; + atomic_uint sends; + atomic_bool stop; +} flood; + +static void *flood_sender(void *arg) { + while (!atomic_load(&flood.stop)) { + uv_async_send(&flood.handle); + atomic_fetch_add(&flood.sends, 1); + } + return NULL; +} + +// Returns after a whole send ran during the callback, so the handle is always +// pending again when the callback returns. +static void flood_async_cb(uv_async_t *handle) { + unsigned start = atomic_load(&flood.sends); + while (atomic_load(&flood.sends) - start < 2) + sched_yield(); +} + +// startAsyncFlood() sends from another thread in a tight loop until +// stopAsyncFlood() is called. +static napi_value start_async_flood(napi_env env, napi_callback_info info) { + if (!init_async(env, get_loop(env, false), &flood.handle, flood_async_cb)) + return NULL; + if (pthread_create(&flood.sender, NULL, flood_sender, NULL) != 0) + napi_throw_error(env, NULL, "pthread_create failed"); + return NULL; +} + +static napi_value stop_async_flood(napi_env env, napi_callback_info info) { + atomic_store(&flood.stop, true); + pthread_join(flood.sender, NULL); + uv_close((uv_handle_t *)&flood.handle, NULL); + return NULL; +} + +static uv_async_t unref_test_handle; + +// testAsyncRef() checks that uv_ref and uv_unref are idempotent. Returns +// uv_has_ref after each step. The handle is never closed, only unref'd, so the +// process must still exit. +static napi_value test_async_ref(napi_env env, napi_callback_info info) { + uv_handle_t *handle = (uv_handle_t *)&unref_test_handle; + if (!init_async(env, get_loop(env, false), &unref_test_handle, + unused_async_cb)) + return NULL; + int32_t observed[6]; + observed[0] = uv_has_ref(handle); + uv_unref(handle); + observed[1] = uv_has_ref(handle); + uv_unref(handle); + observed[2] = uv_has_ref(handle); + uv_ref(handle); + observed[3] = uv_has_ref(handle); + uv_ref(handle); + observed[4] = uv_has_ref(handle); + uv_unref(handle); + observed[5] = uv_has_ref(handle); + return make_int32_array(env, observed, 6); +} + +// --- uv_queue_work ---------------------------------------------------------- + +struct work_test { + uv_work_t req; + struct reporter reporter; + pthread_t loop_thread; + int work_ran; + int work_ran_off_the_loop_thread; +}; + +static void work_test_work_cb(uv_work_t *req) { + struct work_test *test = req->data; + test->work_ran = 1; + test->work_ran_off_the_loop_thread = + !pthread_equal(pthread_self(), test->loop_thread); + // The script has returned by now, so the request must keep the process alive. + usleep(20 * 1000); +} + +// Reports "after" with the status and one bit per check that passed: +// 1 work_cb ran 2 work_cb ran off the loop thread +// 4 after_work_cb is on the loop thread +// 8 data is unchanged 16 req->loop is the loop it was queued on +// 32 uv_req_get_type returns UV_WORK +// 64 uv_cancel on a finished request returns UV_EBUSY +static void work_test_after_work_cb(uv_work_t *req, int status) { + struct work_test *test = uv_req_get_data((uv_req_t *)req); + uv_loop_t *loop = NULL; + napi_get_uv_event_loop(test->reporter.env, &loop); + int32_t passed = 0; + if (test->work_ran) + passed |= 1; + if (test->work_ran_off_the_loop_thread) + passed |= 2; + if (pthread_equal(pthread_self(), test->loop_thread)) + passed |= 4; + if (req->data == test) + passed |= 8; + if (req->loop == loop) + passed |= 16; + if (uv_req_get_type((uv_req_t *)req) == UV_WORK) + passed |= 32; + if (uv_cancel((uv_req_t *)req) == UV_EBUSY) + passed |= 64; + report(&test->reporter, "after", status, passed); + reporter_destroy(&test->reporter); + free(test); +} + +static struct work_test *queue_work(napi_env env, napi_value callback) { + struct work_test *test = calloc(1, sizeof(*test)); + reporter_init(&test->reporter, env, callback); + test->loop_thread = pthread_self(); + uv_req_set_data((uv_req_t *)&test->req, test); // set before queueing + int rc = uv_queue_work(get_loop(env, false), &test->req, work_test_work_cb, + work_test_after_work_cb); + if (rc != 0) { + napi_throw_error(env, NULL, "uv_queue_work failed"); + return NULL; + } + return test; +} + +// testQueueWork(callback) reports `after 0 127`. +static napi_value test_queue_work(napi_env env, napi_callback_info info) { + napi_value args[1]; + get_args(env, info, args, 1); + queue_work(env, args[0]); + return NULL; +} + +// testCancelWork(callback) queues work and cancels it immediately. Returns +// uv_cancel's result: 0 if the request was still queued (the event is then +// `after UV_ECANCELED` with the work_cb bits clear), or UV_EBUSY if a pool +// thread had already started it (then `after 0` with the work_cb bits set). +static napi_value test_cancel_work(napi_env env, napi_callback_info info) { + napi_value args[1]; + get_args(env, info, args, 1); + struct work_test *test = queue_work(env, args[0]); + if (test == NULL) + return NULL; + napi_value result; + napi_create_int32(env, uv_cancel((uv_req_t *)&test->req), &result); + return result; +} + +// --- uv_idle_t / uv_prepare_t / uv_check_t ----------------------------------- + +struct watcher_test { + uv_idle_t idle; + uv_prepare_t prepare; + uv_check_t check; + struct reporter reporter; + int iterations; + bool close_requested; + int open; +}; + +// Reports "close ", using the type that the init function stored. +static void watcher_test_close_cb(uv_handle_t *handle) { + struct watcher_test *test = uv_handle_get_data(handle); + char event[32]; + snprintf(event, sizeof(event), "close %s", + uv_handle_type_name(uv_handle_get_type(handle))); + report(&test->reporter, event, uv_is_closing(handle), uv_is_active(handle)); + if (--test->open == 0) { + reporter_destroy(&test->reporter); + free(test); + } +} + +// Called from a check callback, so this closes the handles, including the check +// handle itself, while the loop is iterating over them. +static void watcher_test_close_all(struct watcher_test *test) { + if (test->open == 3) + uv_close((uv_handle_t *)&test->idle, watcher_test_close_cb); + uv_close((uv_handle_t *)&test->prepare, watcher_test_close_cb); + uv_close((uv_handle_t *)&test->check, watcher_test_close_cb); + report(&test->reporter, "closing", uv_is_closing((uv_handle_t *)&test->check), + uv_is_active((uv_handle_t *)&test->check)); +} + +static struct watcher_test *init_watchers(napi_env env, napi_value callback, + bool with_idle) { + struct watcher_test *test = calloc(1, sizeof(*test)); + reporter_init(&test->reporter, env, callback); + uv_loop_t *loop = get_loop(env, false); + int rc = + uv_prepare_init(loop, &test->prepare) | uv_check_init(loop, &test->check); + test->open = 2; + if (with_idle) { + rc |= uv_idle_init(loop, &test->idle); + test->open = 3; + uv_handle_set_data((uv_handle_t *)&test->idle, test); + } + if (rc != 0) { + napi_throw_error(env, NULL, "init failed"); + return NULL; + } + uv_handle_set_data((uv_handle_t *)&test->prepare, test); + uv_handle_set_data((uv_handle_t *)&test->check, test); + return test; +} + +static void loop_idle_cb(uv_idle_t *handle) { + struct watcher_test *test = handle->data; + test->iterations++; + report(&test->reporter, "idle", test->iterations, + uv_is_active((uv_handle_t *)handle)); +} + +static void loop_prepare_cb(uv_prepare_t *handle) { + struct watcher_test *test = handle->data; + report(&test->reporter, "prepare", test->iterations, + uv_is_active((uv_handle_t *)handle)); +} + +static void loop_check_cb(uv_check_t *handle) { + struct watcher_test *test = handle->data; + report(&test->reporter, "check", test->iterations, + uv_is_active((uv_handle_t *)handle)); + if (test->iterations == 2) + watcher_test_close_all(test); +} + +// testLoopWatchers(callback) starts an idle, a prepare and a check handle. The +// idle handle counts iterations and keeps the poll from blocking, since nothing +// else would wake the loop. Each iteration runs the three in libuv's order, and +// the second iteration's check callback closes all three. Events: +// idle 1 1 / prepare 1 1 / check 1 1 / idle 2 1 / prepare 2 1 / check 2 1 +// closing 1 0 / close idle 1 0 / close prepare 1 0 / close check 1 0 +static napi_value test_loop_watchers(napi_env env, napi_callback_info info) { + napi_value args[1]; + get_args(env, info, args, 1); + struct watcher_test *test = init_watchers(env, args[0], true); + if (test == NULL) + return NULL; + if ((uv_idle_start(&test->idle, loop_idle_cb) | + uv_prepare_start(&test->prepare, loop_prepare_cb) | + uv_check_start(&test->check, loop_check_cb)) != 0) + napi_throw_error(env, NULL, "start failed"); + return NULL; +} + +static struct watcher_test *io_test; + +static void io_prepare_cb(uv_prepare_t *handle) { + struct watcher_test *test = handle->data; + test->iterations++; + report(&test->reporter, "prepare", test->iterations, + uv_is_active((uv_handle_t *)handle)); +} + +static void io_check_cb(uv_check_t *handle) { + struct watcher_test *test = handle->data; + report(&test->reporter, "check", test->iterations, + uv_is_active((uv_handle_t *)handle)); + if (test->close_requested) { + io_test = NULL; + watcher_test_close_all(test); + } +} + +// testPrepareAndCheckAroundIo(callback) starts a prepare and a check handle +// without an idle handle, so the loop blocks in its poll between the two until +// I/O arrives. The script does some socket I/O and calls requestClose() from +// its I/O callback. That callback runs inside the poll, between one iteration's +// prepare and check events, and that iteration's check callback closes both +// handles. +static napi_value test_prepare_and_check_around_io(napi_env env, + napi_callback_info info) { + napi_value args[1]; + get_args(env, info, args, 1); + struct watcher_test *test = init_watchers(env, args[0], false); + if (test == NULL) + return NULL; + if ((uv_prepare_start(&test->prepare, io_prepare_cb) | + uv_check_start(&test->check, io_check_cb)) != 0) { + napi_throw_error(env, NULL, "start failed"); + return NULL; + } + io_test = test; + return NULL; +} + +static napi_value request_close(napi_env env, napi_callback_info info) { + if (io_test != NULL) + io_test->close_requested = true; + return NULL; +} + +static uv_idle_t state_idle; +static uv_check_t state_check; +static void unused_check_cb(uv_check_t *handle) { (void)handle; } + +// testWatcherStates() checks the start/stop state machine synchronously. It +// closes both handles before the loop iterates, so no callback runs and the +// process exits. Otherwise the started idle handle would spin forever. +static napi_value test_watcher_states(napi_env env, napi_callback_info info) { + uv_loop_t *loop = get_loop(env, false); + uv_handle_t *idle = (uv_handle_t *)&state_idle; + uv_handle_t *check = (uv_handle_t *)&state_check; + napi_value result; + napi_create_object(env, &result); + set_int32(env, result, "init", + uv_idle_init(loop, &state_idle) | + uv_check_init(loop, &state_check)); + set_int32(env, result, "activeAfterInit", uv_is_active(idle)); + set_int32(env, result, "refAfterInit", uv_has_ref(idle)); + set_int32(env, result, "typeIsIdle", uv_handle_get_type(idle) == UV_IDLE); + set_int32(env, result, "typeIsCheck", uv_handle_get_type(check) == UV_CHECK); + set_int32(env, result, "loopIsSet", uv_handle_get_loop(idle) == loop); + set_int32(env, result, "start", uv_idle_start(&state_idle, unused_idle_cb)); + set_int32(env, result, "activeAfterStart", uv_is_active(idle)); + set_int32(env, result, "startAgain", + uv_idle_start(&state_idle, unused_idle_cb)); + set_int32(env, result, "stop", uv_idle_stop(&state_idle)); + set_int32(env, result, "activeAfterStop", uv_is_active(idle)); + set_int32(env, result, "stopAgain", uv_idle_stop(&state_idle)); + set_int32(env, result, "restart", uv_idle_start(&state_idle, unused_idle_cb)); + set_int32(env, result, "activeAfterRestart", uv_is_active(idle)); + uv_unref(idle); + set_int32(env, result, "refAfterUnref", uv_has_ref(idle)); + set_int32(env, result, "activeAfterUnref", uv_is_active(idle)); + uv_ref(idle); + set_int32(env, result, "refAfterRef", uv_has_ref(idle)); + set_int32(env, result, "checkStart", + uv_check_start(&state_check, unused_check_cb)); + uv_close(idle, NULL); + uv_close(check, NULL); + set_int32(env, result, "activeAfterClose", uv_is_active(idle)); + set_int32(env, result, "closingAfterClose", uv_is_closing(idle)); + set_int32(env, result, "refAfterClose", uv_has_ref(idle)); + set_int32(env, result, "startAfterClose", + uv_idle_start(&state_idle, unused_idle_cb)); + set_int32(env, result, "activeAfterStartAfterClose", uv_is_active(idle)); + return result; +} + +// --- uv_timer_t -------------------------------------------------------------- + +struct timer_test { + uv_timer_t handle; + struct reporter reporter; + int fires; +}; + +static void timer_test_close_cb(uv_handle_t *handle) { + struct timer_test *test = handle->data; + report(&test->reporter, "close timer", uv_is_closing(handle), + uv_is_active(handle)); + reporter_destroy(&test->reporter); + free(test); +} + +static struct timer_test *init_timer(napi_env env, napi_value callback) { + struct timer_test *test = calloc(1, sizeof(*test)); + reporter_init(&test->reporter, env, callback); + test->handle.data = test; + if (uv_timer_init(get_loop(env, false), &test->handle) != 0) { + napi_throw_error(env, NULL, "uv_timer_init failed"); + return NULL; + } + return test; +} + +static napi_value timer_state(napi_env env, struct timer_test *test) { + uv_handle_t *handle = (uv_handle_t *)&test->handle; + napi_value result; + napi_create_object(env, &result); + set_int32(env, result, "typeIsTimer", uv_handle_get_type(handle) == UV_TIMER); + set_int32(env, result, "isActive", uv_is_active(handle)); + set_int32(env, result, "hasRef", uv_has_ref(handle)); + set_int32(env, result, "dueIn", (int32_t)uv_timer_get_due_in(&test->handle)); + set_int32(env, result, "repeat", (int32_t)uv_timer_get_repeat(&test->handle)); + return result; +} + +static void timer_once_cb(uv_timer_t *handle) { + struct timer_test *test = handle->data; + // Like libuv, a one-shot timer is already stopped when its callback runs. + report(&test->reporter, "timer", uv_is_active((uv_handle_t *)handle), + (int32_t)uv_timer_get_due_in(handle)); + uv_close((uv_handle_t *)handle, timer_test_close_cb); +} + +// testTimer(callback) starts a 10ms one-shot timer. The script returns right +// away, and the timer keeps the process alive until it fires. Reports +// `timer 0 0`, then `close timer 1 0`. Returns the state right after the start. +static napi_value test_timer(napi_env env, napi_callback_info info) { + napi_value args[1]; + get_args(env, info, args, 1); + struct timer_test *test = init_timer(env, args[0]); + if (test == NULL) + return NULL; + if (uv_timer_start(&test->handle, timer_once_cb, 10, 0) != 0) { + napi_throw_error(env, NULL, "uv_timer_start failed"); + return NULL; + } + return timer_state(env, test); +} + +static void timer_repeat_cb(uv_timer_t *handle) { + struct timer_test *test = handle->data; + test->fires++; + // A repeating timer is already rearmed when its callback runs. + report(&test->reporter, "repeat", test->fires, + uv_is_active((uv_handle_t *)handle)); + if (test->fires < 3) + return; + uv_timer_stop(handle); + report(&test->reporter, "stopped", uv_is_active((uv_handle_t *)handle), + (int32_t)uv_timer_get_repeat(handle)); + uv_close((uv_handle_t *)handle, timer_test_close_cb); +} + +// testTimerRepeat(callback) starts a timer with a 1ms timeout and a 1ms repeat. +// Reports `repeat 1 1`, `repeat 2 1`, `repeat 3 1`, `stopped 0 1`, +// `close timer 1 0`. +static napi_value test_timer_repeat(napi_env env, napi_callback_info info) { + napi_value args[1]; + get_args(env, info, args, 1); + struct timer_test *test = init_timer(env, args[0]); + if (test == NULL) + return NULL; + uv_timer_start(&test->handle, timer_repeat_cb, 1, 1); + return timer_state(env, test); +} + +// testTimerAgain(callback) starts a one-hour timer, sets a 1ms repeat and calls +// uv_timer_again, which restarts it with the repeat. Reports the same events as +// testTimerRepeat. Returns { dueInBefore, again, dueInAfter, repeat }. +static napi_value test_timer_again(napi_env env, napi_callback_info info) { + napi_value args[1]; + get_args(env, info, args, 1); + struct timer_test *test = init_timer(env, args[0]); + if (test == NULL) + return NULL; + uv_timer_start(&test->handle, timer_repeat_cb, 60 * 60 * 1000, 0); + napi_value result; + napi_create_object(env, &result); + set_int32(env, result, "dueInBefore", + (int32_t)uv_timer_get_due_in(&test->handle)); + uv_timer_set_repeat(&test->handle, 1); + set_int32(env, result, "again", uv_timer_again(&test->handle)); + set_int32(env, result, "dueInAfter", + (int32_t)uv_timer_get_due_in(&test->handle)); + set_int32(env, result, "repeat", (int32_t)uv_timer_get_repeat(&test->handle)); + return result; +} + +// testTimerRestart(callback) starts a one-hour timer and starts it again with +// 10ms. uv_timer_start reschedules a started timer, so this reports the same +// events as testTimer. Returns the state after the restart. +static napi_value test_timer_restart(napi_env env, napi_callback_info info) { + napi_value args[1]; + get_args(env, info, args, 1); + struct timer_test *test = init_timer(env, args[0]); + if (test == NULL) + return NULL; + uv_timer_start(&test->handle, timer_once_cb, 60 * 60 * 1000, 0); + uv_timer_start(&test->handle, timer_once_cb, 10, 0); + return timer_state(env, test); +} + +// testTimerClosedBeforeItFires(callback) starts a one-hour timer and closes it +// immediately. The only event is `close timer 1 0`, and the process exits. +// Returns the state right after uv_close. +static napi_value test_timer_closed_before_it_fires(napi_env env, + napi_callback_info info) { + napi_value args[1]; + get_args(env, info, args, 1); + struct timer_test *test = init_timer(env, args[0]); + if (test == NULL) + return NULL; + uv_timer_start(&test->handle, timer_once_cb, 60 * 60 * 1000, 0); + uv_close((uv_handle_t *)&test->handle, timer_test_close_cb); + // Allowed until close_cb runs, but none of these may restart the timer. + uv_timer_start(&test->handle, timer_once_cb, 0, 0); + uv_timer_again(&test->handle); + uv_timer_stop(&test->handle); + return timer_state(env, test); +} + +static void timer_unref_cb(uv_timer_t *handle) { + struct timer_test *test = handle->data; + report(&test->reporter, "fired", 0, 0); +} + +// testTimerUnref(callback) starts a one-hour timer and unrefs it. The process +// must exit even though the timer is never stopped or closed, so `fired` is +// never reported. Returns the state after the unref. +static napi_value test_timer_unref(napi_env env, napi_callback_info info) { + napi_value args[1]; + get_args(env, info, args, 1); + struct timer_test *test = init_timer(env, args[0]); + if (test == NULL) + return NULL; + uv_timer_start(&test->handle, timer_unref_cb, 60 * 60 * 1000, 0); + uv_unref((uv_handle_t *)&test->handle); + return timer_state(env, test); +} + +// testNow() checks that uv_now advances while the process spins for 5ms of +// uv_hrtime. Returns { nowIsPositive, advancedMs }. +static napi_value test_now(napi_env env, napi_callback_info info) { + uv_loop_t *loop = get_loop(env, false); + uv_update_time(loop); + uint64_t before = uv_now(loop); + uint64_t start = uv_hrtime(); + while (uv_hrtime() - start < 5 * 1000 * 1000) + ; + uv_update_time(loop); + uint64_t after = uv_now(loop); + napi_value result; + napi_create_object(env, &result); + set_int32(env, result, "nowIsPositive", before > 0); + set_int32(env, result, "advancedMs", (int32_t)(after - before)); + return result; +} + napi_value Init(napi_env env, napi_value exports) { // Register all test functions napi_value fn; + napi_create_function(env, NULL, 0, test_loop_watchers, NULL, &fn); + napi_set_named_property(env, exports, "testLoopWatchers", fn); + + napi_create_function(env, NULL, 0, test_prepare_and_check_around_io, NULL, + &fn); + napi_set_named_property(env, exports, "testPrepareAndCheckAroundIo", fn); + + napi_create_function(env, NULL, 0, request_close, NULL, &fn); + napi_set_named_property(env, exports, "requestClose", fn); + + napi_create_function(env, NULL, 0, test_watcher_states, NULL, &fn); + napi_set_named_property(env, exports, "testWatcherStates", fn); + + napi_create_function(env, NULL, 0, test_timer, NULL, &fn); + napi_set_named_property(env, exports, "testTimer", fn); + + napi_create_function(env, NULL, 0, test_timer_repeat, NULL, &fn); + napi_set_named_property(env, exports, "testTimerRepeat", fn); + + napi_create_function(env, NULL, 0, test_timer_again, NULL, &fn); + napi_set_named_property(env, exports, "testTimerAgain", fn); + + napi_create_function(env, NULL, 0, test_timer_restart, NULL, &fn); + napi_set_named_property(env, exports, "testTimerRestart", fn); + + napi_create_function(env, NULL, 0, test_timer_closed_before_it_fires, NULL, + &fn); + napi_set_named_property(env, exports, "testTimerClosedBeforeItFires", fn); + + napi_create_function(env, NULL, 0, test_timer_unref, NULL, &fn); + napi_set_named_property(env, exports, "testTimerUnref", fn); + + napi_create_function(env, NULL, 0, test_now, NULL, &fn); + napi_set_named_property(env, exports, "testNow", fn); + + napi_create_function(env, NULL, 0, test_version, NULL, &fn); + napi_set_named_property(env, exports, "testVersion", fn); + + napi_create_function(env, NULL, 0, test_sizes_and_names, NULL, &fn); + napi_set_named_property(env, exports, "testSizesAndNames", fn); + + napi_create_function(env, NULL, 0, test_osfhandle, NULL, &fn); + napi_set_named_property(env, exports, "testOsfhandle", fn); + + napi_create_function(env, NULL, 0, test_loops, NULL, &fn); + napi_set_named_property(env, exports, "testLoops", fn); + + napi_create_function(env, NULL, 0, test_errors, NULL, &fn); + napi_set_named_property(env, exports, "testErrors", fn); + + napi_create_function(env, NULL, 0, test_async, NULL, &fn); + napi_set_named_property(env, exports, "testAsync", fn); + + napi_create_function(env, NULL, 0, test_async_close_with_send_pending, NULL, + &fn); + napi_set_named_property(env, exports, "testAsyncCloseWithSendPending", fn); + + napi_create_function(env, NULL, 0, test_async_stress, NULL, &fn); + napi_set_named_property(env, exports, "testAsyncStress", fn); + + napi_create_function(env, NULL, 0, start_async_flood, NULL, &fn); + napi_set_named_property(env, exports, "startAsyncFlood", fn); + + napi_create_function(env, NULL, 0, stop_async_flood, NULL, &fn); + napi_set_named_property(env, exports, "stopAsyncFlood", fn); + + napi_create_function(env, NULL, 0, test_async_ref, NULL, &fn); + napi_set_named_property(env, exports, "testAsyncRef", fn); + + napi_create_function(env, NULL, 0, test_queue_work, NULL, &fn); + napi_set_named_property(env, exports, "testQueueWork", fn); + + napi_create_function(env, NULL, 0, test_cancel_work, NULL, &fn); + napi_set_named_property(env, exports, "testCancelWork", fn); + napi_create_function(env, NULL, 0, test_mutex_init_destroy, NULL, &fn); napi_set_named_property(env, exports, "testMutexInitDestroy", fn); @@ -206,6 +1269,9 @@ napi_value Init(napi_env env, napi_value exports) { napi_create_function(env, NULL, 0, test_uv_once, NULL, &fn); napi_set_named_property(env, exports, "testUvOnce", fn); + napi_create_function(env, NULL, 0, test_cwd, NULL, &fn); + napi_set_named_property(env, exports, "testCwd", fn); + napi_create_function(env, NULL, 0, test_hrtime, NULL, &fn); napi_set_named_property(env, exports, "testHrtime", fn); diff --git a/test/napi/uv.test.ts b/test/napi/uv.test.ts index bd26f07c80d5..d3f248cb9f24 100644 --- a/test/napi/uv.test.ts +++ b/test/napi/uv.test.ts @@ -96,6 +96,21 @@ describe.if(!isWindows)("uv stubs", () => { expect(nativeModule.testUvOnce()).toBe(1); }); + test("uv_cwd returns the cwd and rejects a missing or too-small buffer", () => { + const result = nativeModule.testCwd(); + const cwdBytes = Buffer.byteLength(process.cwd()); + expect(result.rc).toBe(0); + expect(result.cwd).toBe(process.cwd()); + expect(result.size).toBe(cwdBytes); + + expect(result.nullBuffer).toBe(result.UV_EINVAL); + expect(result.nullSize).toBe(result.UV_EINVAL); + expect(result.zeroSize).toBe(result.UV_EINVAL); + + expect(result.smallRc).toBe(result.UV_ENOBUFS); + expect(result.smallRequired).toBe(cwdBytes + 1); + }); + test("hrtime", () => { const result = nativeModule.testHrtime(); @@ -183,4 +198,507 @@ describe.if(!isWindows)("uv stubs", () => { }); expect(exitCode).toBe(0); }); + + // The loop-backed functions (uv_default_loop, uv_queue_work, and the async, + // idle, prepare, check and timer handles) and their header-only helpers run in + // a child process. The child's exit is part of the test: a ref'd handle or a + // queued request must keep it alive, and an unref'd handle must not. `script` + // can use `addon` and `report`, which prints one line per event from the addon. + async function runInChild(script: string) { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + const addon = require(${JSON.stringify(addonPath)}); + const report = (event, a, b) => console.log(event, a, b); + ${script} + `, + ], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { stdout, stderr, exitCode }; + } + + test.concurrent("uv_version and uv_version_string agree", async () => { + const { stdout, stderr, exitCode } = await runInChild(` + console.log(JSON.stringify(addon.testVersion())); + `); + expect(stderr).toBe(""); + const { version, versionString } = JSON.parse(stdout); + expect(versionString).toMatch(/^\d+\.\d+\.\d+$/); + const [major, minor, patch] = versionString.split(".").map(Number); + expect(version).toBe((major << 16) | (minor << 8) | patch); + expect(exitCode).toBe(0); + }); + + test.concurrent("uv_handle_size, uv_req_size and the type names match the headers", async () => { + const { stdout, stderr, exitCode } = await runInChild(`console.log(JSON.stringify(addon.testSizesAndNames()));`); + expect(stderr).toBe(""); + expect(JSON.parse(stdout)).toEqual({ + asyncSizeMatches: true, + timerSizeMatches: true, + unknownHandleSizeIsMinusOne: true, + workSizeMatches: true, + unknownReqSizeIsMinusOne: true, + // sizeof(uv_async_t) on 64-bit Unix. Bun's private fields must fit in it. + asyncSize: 128, + asyncName: "async", + pipeName: "pipe", + workName: "work", + unknownHandleNameIsNull: true, + unknownReqNameIsNull: true, + }); + expect(exitCode).toBe(0); + }); + + test.concurrent("uv_get_osfhandle and uv_open_osfhandle return the fd unchanged", async () => { + const { stdout, stderr, exitCode } = await runInChild( + `console.log(addon.testOsfhandle(2), addon.testOsfhandle(41));`, + ); + expect(stderr).toBe(""); + expect(stdout).toBe("2 41\n"); + expect(exitCode).toBe(0); + }); + + test.concurrent("uv_default_loop is the main thread's napi_get_uv_event_loop", async () => { + const { stdout, stderr, exitCode } = await runInChild(`console.log(JSON.stringify(addon.testLoops()));`); + expect(stderr).toBe(""); + expect(JSON.parse(stdout)).toEqual({ + napiLoopIsSet: true, + napiLoopIsDefaultLoop: true, + defaultLoopIsSameFromThread: true, + loopDataRoundTrips: true, + }); + expect(exitCode).toBe(0); + }); + + test.concurrent("returns UV_EINVAL for a missing loop, a missing callback or the wrong handle type", async () => { + const { stdout, stderr, exitCode } = await runInChild(`console.log(JSON.stringify(addon.testErrors()));`); + expect(stderr).toBe(""); + const EINVAL = -constants.errno.EINVAL; + expect(JSON.parse(stdout)).toEqual([ + EINVAL, // uv_async_init without a loop + EINVAL, // uv_check_init without a loop + EINVAL, // uv_timer_init without a loop + EINVAL, // uv_queue_work without a work_cb + EINVAL, // uv_cancel on a request that isn't a work request + EINVAL, // uv_idle_start without a callback + EINVAL, // uv_timer_start without a callback + EINVAL, // uv_timer_again on a timer that was never started + EINVAL, // uv_prepare_start on an idle handle + EINVAL, // uv_prepare_stop on an idle handle + EINVAL, // uv_idle_start on a timer + EINVAL, // uv_timer_start on an idle handle + EINVAL, // uv_timer_stop on an idle handle + EINVAL, // uv_timer_again on an idle handle + ]); + expect(exitCode).toBe(0); + }); + + // Three sends before the loop iterates coalesce into one callback, and a send + // from inside the callback triggers another. uv_close stops the handle + // immediately and runs close_cb on a later iteration. The script returns right + // after the call, so only the ref'd handle keeps the process alive. + const asyncEvents = ["async 1 1", "async 2 1", "closing 1 0", "close 1 1", ""].join("\n"); + + test.concurrent.each([ + ["napi_get_uv_event_loop", "false"], + ["uv_default_loop", "true"], + ])("uv_async_t on the loop from %s fires when sent from the JS thread", async (_, useDefaultLoop) => { + const { stdout, stderr, exitCode } = await runInChild(` + const observed = addon.testAsync(${useDefaultLoop}, false, report); + console.log("after init", JSON.stringify(observed)); + `); + expect(stderr).toBe(""); + expect(stdout).toBe("after init [1,0,1]\n" + asyncEvents); + expect(exitCode).toBe(0); + }); + + test.concurrent("uv_async_t fires when sent from another thread after the script has returned", async () => { + const { stdout, stderr, exitCode } = await runInChild(`addon.testAsync(false, true, report);`); + expect(stderr).toBe(""); + expect(stdout).toBe(asyncEvents); + expect(exitCode).toBe(0); + }); + + test.concurrent("uv_async_t in a Worker uses the Worker's own loop", async () => { + const { stdout, stderr, exitCode } = await runInChild(` + const { Worker } = require("node:worker_threads"); + const worker = new Worker( + \` + const { parentPort } = require("node:worker_threads"); + const addon = require(${JSON.stringify(addonPath)}); + parentPort.postMessage(JSON.stringify(addon.testLoops())); + addon.testAsync(false, true, (event, a, b) => parentPort.postMessage([event, a, b].join(" "))); + \`, + { eval: true }, + ); + worker.on("message", message => console.log(message)); + worker.on("exit", code => console.log("worker exited", code)); + `); + expect(stderr).toBe(""); + expect(stdout).toBe( + JSON.stringify({ + napiLoopIsSet: true, + napiLoopIsDefaultLoop: false, + defaultLoopIsSameFromThread: true, + loopDataRoundTrips: true, + }) + + "\n" + + asyncEvents + + "worker exited 0\n", + ); + expect(exitCode).toBe(0); + }); + + test.concurrent("uv_async_send from another thread never loses a wakeup, and a burst can race uv_close", async () => { + // A lost wakeup makes the sender thread wait forever, so the child hangs + // and this times out. 201 is STRESS_ROUNDS + 1 in uv_impl.c. + const { stdout, stderr, exitCode } = await runInChild(`addon.testAsyncStress(report);`); + expect(stderr).toBe(""); + expect(stdout).toBe("done 201 1\n"); + expect(exitCode).toBe(0); + }); + + test.concurrent("a thread that calls uv_async_send in a tight loop doesn't starve JS timers", async () => { + // The child hangs if the timer never fires, and this times out. + const { stdout, stderr, exitCode } = await runInChild(` + addon.startAsyncFlood(); + setTimeout(() => { + addon.stopAsyncFlood(); + console.log("timer fired"); + }, 1); + `); + expect(stderr).toBe(""); + expect(stdout).toBe("timer fired\n"); + expect(exitCode).toBe(0); + }); + + test.concurrent("uv_close with a send pending only runs close_cb, and a later close or send is a no-op", async () => { + const { stdout, stderr, exitCode } = await runInChild(` + console.log("after close", JSON.stringify(addon.testAsyncCloseWithSendPending(report))); + `); + expect(stderr).toBe(""); + expect(stdout).toBe("after close [0,1,0]\nclose 1 1\n"); + expect(exitCode).toBe(0); + }); + + test.concurrent("uv_ref and uv_unref toggle uv_has_ref, and an unref'd handle lets the process exit", async () => { + // The handle is still open but unref'd, so the test fails if the child hangs. + const { stdout, stderr, exitCode } = await runInChild(`console.log(JSON.stringify(addon.testAsyncRef()));`); + expect(stderr).toBe(""); + expect(JSON.parse(stdout)).toEqual([1, 0, 0, 1, 1, 0]); + expect(exitCode).toBe(0); + }); + + test.concurrent("an exception thrown by JS called from async_cb is reported as uncaught", async () => { + const { stdout, stderr, exitCode } = await runInChild(` + addon.testAsync(false, false, () => { throw new Error("thrown from inside async_cb"); }); + `); + expect(stdout).toBe(""); + expect(stderr).toContain("thrown from inside async_cb"); + expect(exitCode).toBe(1); + }); + + test.concurrent("uv_queue_work runs work_cb on the pool and after_work_cb on the loop thread", async () => { + const { stdout, stderr, exitCode } = await runInChild(`addon.testQueueWork(report);`); + expect(stderr).toBe(""); + // 127 means every check in work_test_after_work_cb (uv_impl.c) passed. + expect(stdout).toBe("after 0 127\n"); + expect(exitCode).toBe(0); + }); + + test.concurrent("uv_cancel either cancels queued work or returns UV_EBUSY", async () => { + const { stdout, stderr, exitCode } = await runInChild(`console.log("cancel", addon.testCancelWork(report));`); + expect(stderr).toBe(""); + // uv_cancel races with the pool picking up the request, so either outcome + // is valid. 124 is 127 without the two work_cb bits. + const cancelled = `cancel 0\nafter ${-constants.errno.ECANCELED} 124\n`; + const tooLate = `cancel ${-constants.errno.EBUSY}\nafter 0 127\n`; + expect([cancelled, tooLate]).toContain(stdout); + expect(exitCode).toBe(0); + }); + + // The handle tests below print the addon's returned state as one JSON line, + // then one line per event. + function stateAndEvents(stdout: string) { + const [state, ...events] = stdout.split("\n"); + return { state: JSON.parse(state), events: events.join("\n") }; + } + + const loopWatcherEvents = [ + "idle 1 1", + "prepare 1 1", + "check 1 1", + "idle 2 1", + "prepare 2 1", + "check 2 1", + "closing 1 0", + "close idle 1 0", + "close prepare 1 0", + "close check 1 0", + "", + ].join("\n"); + + test.concurrent("idle, prepare and check handles run once per loop iteration, in that order", async () => { + // Only the idle handle keeps the loop iterating. If it let the poll block, + // the child would hang here. See test_loop_watchers in uv_impl.c. + const { stdout, stderr, exitCode } = await runInChild(`addon.testLoopWatchers(report);`); + expect(stderr).toBe(""); + expect(stdout).toBe(loopWatcherEvents); + expect(exitCode).toBe(0); + }); + + test.concurrent("a Worker's watchers run on the Worker's loop", async () => { + const { stdout, stderr, exitCode } = await runInChild(` + const { Worker } = require("node:worker_threads"); + const worker = new Worker( + \` + const { parentPort } = require("node:worker_threads"); + require(${JSON.stringify(addonPath)}).testLoopWatchers((event, a, b) => parentPort.postMessage([event, a, b].join(" "))); + \`, + { eval: true }, + ); + worker.on("message", message => console.log(message)); + worker.on("exit", code => console.log("worker exited", code)); + `); + expect(stderr).toBe(""); + expect(stdout).toBe(loopWatcherEvents + "worker exited 0\n"); + expect(exitCode).toBe(0); + }); + + test.concurrent("prepare runs before the poll and check runs after it", async () => { + // The server's data callback runs inside the poll, and the addon closes both + // handles from that iteration's check callback. The number of iterations + // before the data arrives varies. + const { stdout, stderr, exitCode } = await runInChild(` + addon.testPrepareAndCheckAroundIo(report); + const server = Bun.listen({ + hostname: "127.0.0.1", + port: 0, + socket: { + data(socket) { + console.log("io"); + addon.requestClose(); + socket.end(); + server.stop(true); + }, + }, + }); + Bun.connect({ + hostname: "127.0.0.1", + port: server.port, + socket: { + open(socket) { + socket.write("x"); + }, + data() {}, + }, + }); + `); + expect(stderr).toBe(""); + const lines = stdout.split("\n"); + const io = lines.indexOf("io"); + expect(io).toBeGreaterThan(0); + const iteration = (io + 1) / 2; + const expected: string[] = []; + for (let i = 1; i < iteration; i++) { + expected.push(`prepare ${i} 1`, `check ${i} 1`); + } + expected.push( + `prepare ${iteration} 1`, + "io", + `check ${iteration} 1`, + "closing 1 0", + "close prepare 1 0", + "close check 1 0", + "", + ); + expect(lines).toEqual(expected); + expect(exitCode).toBe(0); + }); + + test.concurrent("a watcher's start/stop state machine matches libuv", async () => { + // The addon closes the handles before the script returns. The child must + // exit, because a started idle handle would otherwise spin forever. + const { stdout, stderr, exitCode } = await runInChild(`console.log(JSON.stringify(addon.testWatcherStates()));`); + expect(stderr).toBe(""); + expect(JSON.parse(stdout)).toEqual({ + init: 0, + activeAfterInit: 0, + refAfterInit: 1, + typeIsIdle: 1, + typeIsCheck: 1, + loopIsSet: 1, + start: 0, + activeAfterStart: 1, + startAgain: 0, + stop: 0, + activeAfterStop: 0, + stopAgain: 0, + restart: 0, + activeAfterRestart: 1, + refAfterUnref: 0, + activeAfterUnref: 1, + refAfterRef: 1, + checkStart: 0, + activeAfterClose: 0, + closingAfterClose: 1, + // The ref flag is independent of closing, as in libuv. + refAfterClose: 1, + // Starting a closing handle is a no-op that reports success, as in libuv. + startAfterClose: 0, + activeAfterStartAfterClose: 0, + }); + expect(exitCode).toBe(0); + }); + + test.concurrent("an exception thrown by JS called from a watcher callback is reported as uncaught", async () => { + // All six callbacks throw. The loop must still reach the check callback that + // closes the handles, or the child never exits. + const { stdout, stderr, exitCode } = await runInChild(` + addon.testLoopWatchers(() => { throw new Error("thrown from inside a watcher callback"); }); + `); + expect(stdout).toBe(""); + expect(stderr).toContain("thrown from inside a watcher callback"); + expect(exitCode).toBe(1); + }); + + const oneShotTimerEvents = "timer 0 0\nclose timer 1 0\n"; + // The third callback stops and closes the timer (timer_repeat_cb in uv_impl.c). + const repeatingTimerEvents = "repeat 1 1\nrepeat 2 1\nrepeat 3 1\nstopped 0 1\nclose timer 1 0\n"; + const HOUR = 60 * 60 * 1000; + + test.concurrent("a one-shot uv_timer_t keeps the process alive and fires once", async () => { + const { stdout, stderr, exitCode } = await runInChild(`console.log(JSON.stringify(addon.testTimer(report)));`); + expect(stderr).toBe(""); + const { state, events } = stateAndEvents(stdout); + expect(state).toEqual({ typeIsTimer: 1, isActive: 1, hasRef: 1, dueIn: expect.any(Number), repeat: 0 }); + expect(state.dueIn).toBeGreaterThanOrEqual(0); + expect(state.dueIn).toBeLessThanOrEqual(10); + expect(events).toBe(oneShotTimerEvents); + expect(exitCode).toBe(0); + }); + + test.concurrent("uv_timer_t fires when started from inside a JS timer callback, alongside a JS timer", async () => { + // The addon arms its timers while the timer heap is being drained, like an + // addon constructor called from a setTimeout callback. The order in which + // the three timers fire depends on the scheduler, so compare sorted events. + const { stdout, stderr, exitCode } = await runInChild(` + setTimeout(() => { + console.log(JSON.stringify(addon.testTimer(report))); + addon.testTimerRepeat(report); + setTimeout(() => console.log("js timer"), 10); + }, 1); + `); + expect(stderr).toBe(""); + const { state, events } = stateAndEvents(stdout); + expect(state).toEqual({ typeIsTimer: 1, isActive: 1, hasRef: 1, dueIn: expect.any(Number), repeat: 0 }); + const lines = (s: string) => s.trimEnd().split("\n"); + expect(lines(events).sort()).toEqual( + [...lines(oneShotTimerEvents), ...lines(repeatingTimerEvents), "js timer"].sort(), + ); + expect(exitCode).toBe(0); + }); + + test.concurrent("a uv_timer_t in a Worker fires on the Worker's loop", async () => { + const { stdout, stderr, exitCode } = await runInChild(` + const { Worker } = require("node:worker_threads"); + const worker = new Worker( + \` + const { parentPort } = require("node:worker_threads"); + const state = require(${JSON.stringify(addonPath)}).testTimer((event, a, b) => parentPort.postMessage([event, a, b].join(" "))); + parentPort.postMessage("started " + state.isActive); + \`, + { eval: true }, + ); + worker.on("message", message => console.log(message)); + worker.on("exit", code => console.log("worker exited", code)); + `); + expect(stderr).toBe(""); + expect(stdout).toBe("started 1\n" + oneShotTimerEvents + "worker exited 0\n"); + expect(exitCode).toBe(0); + }); + + test.concurrent("a repeating uv_timer_t fires until it is stopped", async () => { + const { stdout, stderr, exitCode } = await runInChild( + `console.log(JSON.stringify(addon.testTimerRepeat(report)));`, + ); + expect(stderr).toBe(""); + const { state, events } = stateAndEvents(stdout); + expect(state).toEqual({ typeIsTimer: 1, isActive: 1, hasRef: 1, dueIn: expect.any(Number), repeat: 1 }); + expect(state.dueIn).toBeLessThanOrEqual(1); + expect(events).toBe(repeatingTimerEvents); + expect(exitCode).toBe(0); + }); + + test.concurrent("uv_timer_set_repeat and uv_timer_again restart a timer with its repeat", async () => { + const { stdout, stderr, exitCode } = await runInChild(`console.log(JSON.stringify(addon.testTimerAgain(report)));`); + expect(stderr).toBe(""); + const { state, events } = stateAndEvents(stdout); + expect(state).toEqual({ dueInBefore: expect.any(Number), again: 0, dueInAfter: expect.any(Number), repeat: 1 }); + expect(state.dueInBefore).toBeGreaterThan(HOUR / 2); + expect(state.dueInBefore).toBeLessThanOrEqual(HOUR); + expect(state.dueInAfter).toBeLessThanOrEqual(1); + expect(events).toBe(repeatingTimerEvents); + expect(exitCode).toBe(0); + }); + + test.concurrent("uv_timer_start on a started timer reschedules it", async () => { + const { stdout, stderr, exitCode } = await runInChild( + `console.log(JSON.stringify(addon.testTimerRestart(report)));`, + ); + expect(stderr).toBe(""); + const { state, events } = stateAndEvents(stdout); + expect(state).toEqual({ typeIsTimer: 1, isActive: 1, hasRef: 1, dueIn: expect.any(Number), repeat: 0 }); + expect(state.dueIn).toBeLessThanOrEqual(10); + expect(events).toBe(oneShotTimerEvents); + expect(exitCode).toBe(0); + }); + + test.concurrent("uv_close on a started timer only runs close_cb, and the process exits", async () => { + const { stdout, stderr, exitCode } = await runInChild( + `console.log(JSON.stringify(addon.testTimerClosedBeforeItFires(report)));`, + ); + expect(stderr).toBe(""); + expect(stateAndEvents(stdout)).toEqual({ + state: { typeIsTimer: 1, isActive: 0, hasRef: 1, dueIn: 0, repeat: 0 }, + events: "close timer 1 0\n", + }); + expect(exitCode).toBe(0); + }); + + test.concurrent("an unref'd timer lets the process exit", async () => { + // The timer is never stopped. If unref didn't work, the child would hang for an hour. + const { stdout, stderr, exitCode } = await runInChild(`console.log(JSON.stringify(addon.testTimerUnref(report)));`); + expect(stderr).toBe(""); + const { state, events } = stateAndEvents(stdout); + expect(state).toEqual({ typeIsTimer: 1, isActive: 1, hasRef: 0, dueIn: expect.any(Number), repeat: 0 }); + expect(state.dueIn).toBeGreaterThan(HOUR / 2); + expect(events).toBe(""); + expect(exitCode).toBe(0); + }); + + test.concurrent("an exception thrown by JS called from timer_cb is reported as uncaught", async () => { + const { stdout, stderr, exitCode } = await runInChild(` + addon.testTimer(() => { throw new Error("thrown from inside timer_cb"); }); + `); + expect(stdout).toBe(""); + expect(stderr).toContain("thrown from inside timer_cb"); + expect(exitCode).toBe(1); + }); + + test.concurrent("uv_now advances", async () => { + const { stdout, stderr, exitCode } = await runInChild(`console.log(JSON.stringify(addon.testNow()));`); + expect(stderr).toBe(""); + const result = JSON.parse(stdout); + expect(result).toEqual({ nowIsPositive: 1, advancedMs: expect.any(Number) }); + // The addon spins for 5ms between the two readings. + expect(result.advancedMs).toBeGreaterThanOrEqual(4); + expect(exitCode).toBe(0); + }); }); diff --git a/test/regression/issue/29181.test.ts b/test/regression/issue/29181.test.ts index 145eb949ea4a..c45be729b32e 100644 --- a/test/regression/issue/29181.test.ts +++ b/test/regression/issue/29181.test.ts @@ -49,13 +49,18 @@ test.skipIf(!isPosix)("Bun.serve static file route does not leak fds on 304 / HE await r.text(); } - const after = getFDCount(); - // Pre-fix: delta would be 400 (one fd leaked per request). // Post-fix: delta is bounded by HTTP keep-alive sockets (typically a // small constant). 16 is comfortably above that and still catches the // old 400-fd leak. - const delta = after - before; + let delta = getFDCount() - before; + // The route closes its fds on the work pool, which can be behind the + // responses. A leaked fd stays open however long this waits. + const deadline = performance.now() + 2000; + while (delta >= 16 && performance.now() < deadline) { + await Bun.sleep(1); + delta = getFDCount() - before; + } expect(delta).toBeLessThan(16); }); diff --git a/test/regression/issue/30613.test.ts b/test/regression/issue/30613.test.ts new file mode 100644 index 000000000000..9aab1bf80f02 --- /dev/null +++ b/test/regression/issue/30613.test.ts @@ -0,0 +1,19 @@ +import { expect, test } from "bun:test"; +import { bunEnv, bunExe, isArm64 } from "harness"; + +// simdutf treats an unknown implementation name like a CPU that none of its kernels supports. +// arm64 builds have a single kernel and ignore the variable. +test.skipIf(isArm64)("fails fast with a clear error when simdutf has no supported implementation", async () => { + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", "console.log('unreachable')"], + env: { ...bunEnv, SIMDUTF_FORCE_IMPLEMENTATION: "none" }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + + expect(stderr).toContain("which Bun requires"); + expect(stderr).toContain("SIMDUTF_FORCE_IMPLEMENTATION"); + expect(stdout).toBe(""); + expect(exitCode).toBe(134); +}); diff --git a/test/regression/issue/44915.test.ts b/test/regression/issue/44915.test.ts new file mode 100644 index 000000000000..4951d85637b6 --- /dev/null +++ b/test/regression/issue/44915.test.ts @@ -0,0 +1,41 @@ +import { expect, test } from "bun:test"; +import { bunEnv, bunExe, tempDir } from "harness"; + +// A class decorator that returns a new class replaces the class binding inside +// the class body too. The argument of a member decorator read it through the +// original class in 1.4.3 (a regression from 1.4.2). The other body positions +// are covered in test/bundler/transpiler/es-decorators.test.ts. +test("a member decorator argument sees the class its class decorator returns", async () => { + using dir = tempDir("issue-44915", { + "repro.ts": ` + function replace(cls: any, _ctx: ClassDecoratorContext) { + return class extends cls {}; + } + + let thunk!: () => unknown; + function capture(fn: () => unknown) { + thunk = fn; + return (_value: undefined, _ctx: ClassFieldDecoratorContext) => {}; + } + + @replace + class Model { + @capture(() => Model) + field = 1; + } + + console.log("decorator argument:", thunk() === Model); + `, + }); + + await using proc = Bun.spawn({ + cmd: [bunExe(), "repro.ts"], + env: bunEnv, + cwd: String(dir), + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + expect(stdout).toBe("decorator argument: true\n"); + expect(exitCode).toBe(0); +}); diff --git a/test/regression/issue/44982.test.ts b/test/regression/issue/44982.test.ts new file mode 100644 index 000000000000..4651c2a13281 --- /dev/null +++ b/test/regression/issue/44982.test.ts @@ -0,0 +1,81 @@ +// https://github.com/oven-sh/bun/issues/44982 +// +// On Linux, JSC suspends the JS thread with a signal (SIGPWR) when the collector thread +// needs its stack for the conservative scan. A Go c-shared library loaded into the process +// adds SA_ONSTACK to every installed signal handler, and Bun's crash handler gives the main +// thread an alternate signal stack, so the suspend handler then runs on that stack. Up to +// 1.4.3 the handler backed off whenever its own stack pointer was outside the thread's +// stack, so every suspend attempt failed and the process hung once an idle collection +// finished while the JS thread was parked in epoll without heap access. +import { expect, test } from "bun:test"; +import { bunEnv, bunExe, isLinux, isMusl } from "harness"; + +const libc = isMusl ? (process.arch === "arm64" ? "libc.musl-aarch64.so.1" : "libc.musl-x86_64.so.1") : "libc.so.6"; + +test.skipIf(!isLinux)( + "an idle collection finishes while the JS thread is parked, with SA_ONSTACK on the suspend signal", + async () => { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + // What the Go runtime does in runtime.setsigstack: add SA_ONSTACK to the handler it finds. + import { dlopen, ptr, FFIType } from "bun:ffi"; + const SIGPWR = 30; + const SA_ONSTACK = 0x08000000; + const { symbols } = dlopen(${JSON.stringify(libc)}, { + sigaction: { args: [FFIType.i32, FFIType.ptr, FFIType.ptr], returns: FFIType.i32 }, + }); + // struct sigaction on 64-bit Linux (glibc and musl): handler (8), sa_mask (128), sa_flags (4 at 136), restorer (8). + const act = new Uint8Array(152); + if (symbols.sigaction(SIGPWR, null, ptr(act)) !== 0) throw new Error("sigaction read failed"); + const view = new DataView(act.buffer); + if (view.getBigUint64(0, true) === 0n) throw new Error("no SIGPWR handler installed"); + view.setUint32(136, view.getUint32(136, true) | SA_ONSTACK, true); + if (symbols.sigaction(SIGPWR, ptr(act), null) !== 0) throw new Error("sigaction write failed"); + + // Enough live objects that marking does not finish in the pause that starts the collection, so the + // collector thread still owns it when this thread parks and has to suspend this thread for its stack. + const keep = []; + for (let i = 0; i < 30_000; i++) keep.push({ i, s: "x" + i, tags: ["a" + i, "b" + i] }); + // The GC timer (every 250 ms) requests the idle collection after 1 s of quiet, so by about + // 1.3 s, and the collector runs it while this thread waits for the timer. BUN_JSC_logGC + // prints the collection to stderr; the parent checks that one happened between the marks. + console.error("MARK"); + setTimeout(() => { + console.error("DONE"); + console.log("done", keep.length); + }, 2500); + `, + ], + env: { + ...bunEnv, + BUN_IDLE_GC_SECONDS: "1", + BUN_GC_TIMER_INTERVAL: "250", + BUN_GC_TIMER_DISABLE: undefined, + BUN_JSC_logGC: "1", + }, + stdout: "pipe", + stderr: "pipe", + }); + + let timer: ReturnType | undefined; + const exited = await Promise.race([ + proc.exited, + new Promise<"hung">(resolve => { + timer = setTimeout(() => resolve("hung"), 20_000); + }), + ]); + clearTimeout(timer); + if (exited === "hung") { + proc.kill(); + throw new Error("the process hung: the collector could not suspend the JS thread"); + } + const [stdout, stderr] = await Promise.all([proc.stdout.text(), proc.stderr.text()]); + const idleWindow = stderr.slice(stderr.indexOf("MARK"), stderr.indexOf("DONE")); + expect(idleWindow).toContain("=> FullCollection"); + expect(stdout).toBe("done 30000\n"); + expect(exited).toBe(0); + }, +); diff --git a/test/v8/v8-module/main.cpp b/test/v8/v8-module/main.cpp index 76bcb331cec2..b4e13959fd8b 100644 --- a/test/v8/v8-module/main.cpp +++ b/test/v8/v8-module/main.cpp @@ -890,6 +890,43 @@ void test_uv_os_getppid(const FunctionCallbackInfo &info) { return ok(info); } +struct QueuedWork { + uv_work_t req; + Isolate *isolate; + Global callback; + int result = 0; +}; + +// Queues work the way Nan::AsyncQueueWorker does. after_work_cb only opens a +// v8::HandleScope, like Nan::AsyncExecuteComplete. +void queue_work_and_call(const FunctionCallbackInfo &info) { + Isolate *isolate = info.GetIsolate(); + auto *work = new QueuedWork; + work->req.data = work; + work->isolate = isolate; + work->callback.Reset(isolate, info[0].As()); + int rc = uv_queue_work( + node::GetCurrentEventLoop(isolate), &work->req, + [](uv_work_t *req) { static_cast(req->data)->result = 42; }, + [](uv_work_t *req, int status) { + auto *work = static_cast(req->data); + Isolate *isolate = work->isolate; + { + HandleScope scope(isolate); + Local args[] = { + String::NewFromUtf8(isolate, "done").ToLocalChecked(), + Number::New(isolate, status), + Number::New(isolate, work->result), + }; + Local::New(isolate, work->callback) + ->Call(isolate->GetCurrentContext(), Undefined(isolate), 3, args) + .ToLocalChecked(); + } + delete work; + }); + info.GetReturnValue().Set(Number::New(isolate, rc)); +} + void test_v8_object_get_by_key(const FunctionCallbackInfo &info) { printf("Testing Object::Get(context, key)...\n"); @@ -1885,6 +1922,36 @@ void test_v8_exception(const FunctionCallbackInfo &info) { isolate->ThrowException(err); } +void test_v8_exception_empty_message(const FunctionCallbackInfo &info) { + Isolate *isolate = info.GetIsolate(); + Local empty = String::NewFromUtf8(isolate, "").ToLocalChecked(); + + Local errors[] = {Exception::Error(empty), + Exception::TypeError(empty)}; + info.GetReturnValue().Set(Array::New(isolate, errors, 2)); +} + +void test_v8_throw_error_empty_message( + const FunctionCallbackInfo &info) { + Isolate *isolate = info.GetIsolate(); + isolate->ThrowError(String::NewFromUtf8(isolate, "").ToLocalChecked()); +} + +// These return a Local, not a MaybeLocal, so an addon does not check them. +void test_v8_new_values_with_pending_exception( + const FunctionCallbackInfo &info) { + Isolate *isolate = info.GetIsolate(); + isolate->ThrowError(String::NewFromUtf8(isolate, "pending").ToLocalChecked()); + + LOG_EXPR(Array::New(isolate, 3)->Length()); + Local elements[] = {Number::New(isolate, 1), Number::New(isolate, 2)}; + LOG_EXPR(Array::New(isolate, elements, 2)->Length()); + Local buffer = ArrayBuffer::New(isolate, 16); + LOG_EXPR(Uint8Array::New(buffer, 0, 8)->IsUint8Array()); + LOG_EXPR(Uint32Array::New(buffer, 0, 2)->IsObject()); + LOG_EXPR(BigInt::New(isolate, 5)->IsBigInt()); +} + void test_v8_aligned_pointer_in_internal_field( const FunctionCallbackInfo &info) { Isolate *isolate = info.GetIsolate(); @@ -2184,6 +2251,7 @@ void initialize(Local exports, Local module, return_accessor_value_from_inner_scope); NODE_SET_METHOD(exports, "test_uv_os_getpid", test_uv_os_getpid); NODE_SET_METHOD(exports, "test_uv_os_getppid", test_uv_os_getppid); + NODE_SET_METHOD(exports, "queue_work_and_call", queue_work_and_call); NODE_SET_METHOD(exports, "test_v8_object_get_by_key", test_v8_object_get_by_key); NODE_SET_METHOD(exports, "test_v8_object_get_by_index", @@ -2226,6 +2294,12 @@ void initialize(Local exports, Local module, test_v8_getfunction_memoized); NODE_SET_METHOD(exports, "test_v8_map", test_v8_map); NODE_SET_METHOD(exports, "test_v8_exception", test_v8_exception); + NODE_SET_METHOD(exports, "test_v8_exception_empty_message", + test_v8_exception_empty_message); + NODE_SET_METHOD(exports, "test_v8_throw_error_empty_message", + test_v8_throw_error_empty_message); + NODE_SET_METHOD(exports, "test_v8_new_values_with_pending_exception", + test_v8_new_values_with_pending_exception); NODE_SET_METHOD(exports, "test_v8_aligned_pointer_in_internal_field", test_v8_aligned_pointer_in_internal_field); NODE_SET_METHOD(exports, "test_v8_cpu_profiler", test_v8_cpu_profiler); diff --git a/test/v8/v8-module/module.js b/test/v8/v8-module/module.js index 2625a5035dde..7160abcfa0d8 100644 --- a/test/v8/v8-module/module.js +++ b/test/v8/v8-module/module.js @@ -122,7 +122,17 @@ module.exports = debugMode => { const obj = nativeModule.test_v8_define_own_property(); for (const key of ["writable", "readonly", "hidden"]) { const d = Object.getOwnPropertyDescriptor(obj, key); - console.log(key, "=", d.value, "writable =", d.writable, "enumerable =", d.enumerable, "configurable =", d.configurable); + console.log( + key, + "=", + d.value, + "writable =", + d.writable, + "enumerable =", + d.enumerable, + "configurable =", + d.configurable, + ); } console.log("enumerable keys =", JSON.stringify(Object.keys(obj).sort())); }, @@ -185,6 +195,31 @@ module.exports = debugMode => { } }, + test_v8_exception_empty_message() { + for (const e of nativeModule.test_v8_exception_empty_message()) { + console.log(e.constructor.name, "message =", JSON.stringify(e.message), "own =", Object.hasOwn(e, "message")); + } + }, + + test_v8_throw_error_empty_message() { + try { + nativeModule.test_v8_throw_error_empty_message(); + console.log("did not throw"); + } catch (e) { + const own = Object.hasOwn(e, "message"); + console.log("caught", e.constructor.name, "message =", JSON.stringify(e.message), "own =", own); + } + }, + + test_v8_new_values_with_pending_exception() { + try { + nativeModule.test_v8_new_values_with_pending_exception(); + console.log("did not throw"); + } catch (e) { + console.log("caught", e.message); + } + }, + print_native_function() { nativeModule.print_values_from_js(nativeModule.create_function_with_data()); }, @@ -259,6 +294,11 @@ module.exports = debugMode => { keep(); }, + test_uv_queue_work_on_current_event_loop() { + const rc = nativeModule.queue_work_and_call((...args) => console.log("after_work_cb", ...args)); + console.log("uv_queue_work", rc); + }, + test_v8_object_get_set_exceptions() { for (const key of [0, "key"]) { for (const access of ["get", "set"]) { diff --git a/test/v8/v8.test.ts b/test/v8/v8.test.ts index 90c0b92cfc96..d2f265e8c5c9 100644 --- a/test/v8/v8.test.ts +++ b/test/v8/v8.test.ts @@ -469,6 +469,18 @@ describe.skipIf(!canBuildNodeAddons()).todoIf(isBroken && isMusl)("node:v8", () it("Exception::Error/TypeError create throwable Error objects", async () => { await checkSameOutput("test_v8_exception"); }); + it("Exception::Error/TypeError accept an empty message", async () => { + const output = await checkSameOutput("test_v8_exception_empty_message"); + expect(output).toBe(['Error message = "" own = true', 'TypeError message = "" own = true'].join("\n")); + }); + it("Isolate::ThrowError accepts an empty message", async () => { + const output = await checkSameOutput("test_v8_throw_error_empty_message"); + expect(output).toBe('caught Error message = "" own = true'); + }); + it("Array, Uint8Array, Uint32Array and BigInt ::New work while an exception is pending", async () => { + const output = await checkSameOutput("test_v8_new_values_with_pending_exception"); + expect(output).toEndWith("caught pending"); + }); }); describe("Aligned internal fields", () => { @@ -503,6 +515,13 @@ describe.skipIf(!canBuildNodeAddons()).todoIf(isBroken && isMusl)("node:v8", () await checkSameOutput("test_uv_os_getppid"); }); }); + + describe("uv_queue_work", () => { + // TODO: on Windows libuv calls after_work_cb with no handle scope open, so creating a handle aborts. + it.skipIf(isWindows)("runs on node::GetCurrentEventLoop and after_work_cb can use a v8::HandleScope", async () => { + await checkSameOutput("test_uv_queue_work_on_current_event_loop"); + }); + }); }); async function checkSameOutput(testName: string, args?: string, thisValue?: any) { @@ -822,6 +841,251 @@ for (const [hi, lo] of [ ); }); +// Node runs every Node-API callback inside a v8::HandleScope, so an addon that calls the V8 API +// from one doesn't need to open its own scope. With the Node 26 headers, an addon's +// v8::HandleScope is inlined and never calls into Bun either. +describe.skipIf(!canBuildNodeAddons()).todoIf(isBroken && isMusl)("V8 API from Node-API callbacks", () => { + it( + "creates handles in the Node-API scope, keeps them alive, and releases them when it closes", + async () => { + using dir = tempDir( + "v8-api-from-napi", + standaloneAddonFiles( + "hybridnapi", + `// A Node-API addon whose callbacks also use the V8 C++ API. Node runs every Node-API callback +// inside a v8::HandleScope, so the callbacks below only open one when that's what they test. +// Each callback returns its result as a string so run.js can print everything in order. +#include +#include +#include +#include + +namespace hybrid_test { + +using namespace v8; + +Global stashed_array; + +napi_value to_napi_string(napi_env env, const char* text) { + napi_value result; + napi_create_string_utf8(env, text, NAPI_AUTO_LENGTH, &result); + return result; +} + +// Bun's callback overload of Array::New opens an EscapableHandleScope around the callbacks. +napi_value describe_new_values(napi_env env, Isolate* isolate) { + Local array = Array::New(isolate, 3); + Local string = + String::NewFromUtf8(isolate, "string from v8", NewStringType::kNormal).ToLocalChecked(); + int next = 0; + Local from_callback = + Array::New(isolate->GetCurrentContext(), 4, + [&]() -> MaybeLocal { return Number::New(isolate, next++); }) + .ToLocalChecked(); + char string_text[64]; + string->WriteUtf8V2(isolate, string_text, sizeof string_text, String::WriteFlags::kNullTerminate); + char result[128]; + snprintf(result, sizeof result, "arrays of length %u and %u, '%s'", array->Length(), + from_callback->Length(), string_text); + return to_napi_string(env, result); +} + +napi_value without_scope(napi_env env, napi_callback_info info) { + return describe_new_values(env, Isolate::GetCurrent()); +} + +napi_value with_scope(napi_env env, napi_callback_info info) { + Isolate* isolate = Isolate::GetCurrent(); + HandleScope scope(isolate); + return describe_new_values(env, isolate); +} + +napi_value with_escapable_scope(napi_env env, napi_callback_info info) { + Isolate* isolate = Isolate::GetCurrent(); + Local escaped; + { + EscapableHandleScope scope(isolate); + escaped = scope.Escape( + String::NewFromUtf8(isolate, "escaped string", NewStringType::kNormal).ToLocalChecked()); + } + char text[64]; + escaped->WriteUtf8V2(isolate, text, sizeof text, String::WriteFlags::kNullTerminate); + return to_napi_string(env, text); +} + +napi_value constructor(napi_env env, napi_callback_info info) { + napi_value description = describe_new_values(env, Isolate::GetCurrent()); + napi_value this_arg; + size_t argc = 0; + napi_get_cb_info(env, info, &argc, nullptr, &this_arg, nullptr); + napi_set_named_property(env, this_arg, "description", description); + return this_arg; +} + +void call_argument(napi_env env, napi_callback_info info, napi_value* result) { + size_t argc = 1; + napi_value callback; + napi_get_cb_info(env, info, &argc, &callback, nullptr, nullptr); + napi_value global; + napi_get_global(env, &global); + napi_call_function(env, global, callback, 0, nullptr, result); +} + +// Handles created in a callback must keep their values alive for the rest of the callback, +// including across a GC that the callback triggers. The argument is a function that runs the GC. +napi_value survives_gc(napi_env env, napi_callback_info info) { + Isolate* isolate = Isolate::GetCurrent(); + constexpr int count = 500; + Local strings[count]; + for (int i = 0; i < count; i++) { + char text[32]; + snprintf(text, sizeof text, "string %d", i); + strings[i] = String::NewFromUtf8(isolate, text, NewStringType::kNormal).ToLocalChecked(); + } + + napi_value ignored; + call_argument(env, info, &ignored); + + int intact = 0; + for (int i = 0; i < count; i++) { + char expected[32], actual[32]; + snprintf(expected, sizeof expected, "string %d", i); + strings[i]->WriteUtf8V2(isolate, actual, sizeof actual, String::WriteFlags::kNullTerminate); + intact += strcmp(expected, actual) == 0; + } + char result[64]; + snprintf(result, sizeof result, "%d of %d strings intact after gc", intact, count); + return to_napi_string(env, result); +} + +constexpr int num_buffers = 1000; + +// The argument is a function that runs the GC and returns the number of live ArrayBuffers. Reports +// whether the buffers the caller created in already-closed scopes were collected. +napi_value describe_released(napi_env env, napi_callback_info info) { + napi_value live_value; + call_argument(env, info, &live_value); + int32_t live = -1; + napi_get_value_int32(env, live_value, &live); + return to_napi_string(env, live < num_buffers / 10 ? "released before the callback returned" + : "still alive when the callback returned"); +} + +napi_value napi_scopes_release(napi_env env, napi_callback_info info) { + Isolate* isolate = Isolate::GetCurrent(); + for (int i = 0; i < num_buffers; i++) { + napi_handle_scope scope; + napi_open_handle_scope(env, &scope); + ArrayBuffer::New(isolate, 8); + napi_close_handle_scope(env, scope); + } + return describe_released(env, info); +} + +// Doesn't open a scope. run.js checks that the buffers are released once this returns. +napi_value create_buffers(napi_env env, napi_callback_info info) { + Isolate* isolate = Isolate::GetCurrent(); + for (int i = 0; i < num_buffers; i++) { + ArrayBuffer::New(isolate, 8); + } + return nullptr; +} + +napi_value stash_array(napi_env env, napi_callback_info info) { + Isolate* isolate = Isolate::GetCurrent(); + stashed_array.Reset(isolate, Array::New(isolate, 5)); + return nullptr; +} + +// Global::Get creates its Local with V8's inline handle creation code, which calls into Bun through +// HandleScope::Extend instead of a value constructor like Array::New. Each inline HandleScope +// releases those handles through HandleScope::DeleteExtensions when it closes. +napi_value read_stashed_array(napi_env env, napi_callback_info info) { + Isolate* isolate = Isolate::GetCurrent(); + unsigned total_length = 0; + for (int i = 0; i < 1000; i++) { + HandleScope scope(isolate); + total_length += stashed_array.Get(isolate)->Length(); + } + Local array = stashed_array.Get(isolate); + char result[96]; + snprintf(result, sizeof result, "stashed array of length %u, %u in total over 1000 inline scopes", + array->Length(), total_length); + stashed_array.Reset(); + return to_napi_string(env, result); +} + +napi_value init(napi_env env, napi_value exports) { + struct { + const char* name; + napi_callback callback; + } functions[] = { + {"withoutScope", without_scope}, + {"withScope", with_scope}, + {"withEscapableScope", with_escapable_scope}, + {"survivesGc", survives_gc}, + {"napiScopesRelease", napi_scopes_release}, + {"createBuffers", create_buffers}, + {"stashArray", stash_array}, + {"readStashedArray", read_stashed_array}, + }; + for (auto& function : functions) { + napi_value value; + napi_create_function(env, function.name, NAPI_AUTO_LENGTH, function.callback, nullptr, &value); + napi_set_named_property(env, exports, function.name, value); + } + napi_value klass; + napi_define_class(env, "Klass", NAPI_AUTO_LENGTH, constructor, nullptr, 0, nullptr, &klass); + napi_set_named_property(env, exports, "Klass", klass); + return exports; +} + +} // namespace hybrid_test + +NAPI_MODULE(NODE_GYP_MODULE_NAME, hybrid_test::init)`, + `const addon = require("./build/Release/hybridnapi"); +const { heapStats } = require("bun:jsc"); + +function gc() { + Bun.gc(true); +} + +function liveArrayBuffers() { + gc(); + return heapStats().objectTypeCounts.ArrayBuffer ?? 0; +} + +console.log("function without scope:", addon.withoutScope()); +console.log("function with scope:", addon.withScope()); +console.log("function with escapable scope:", addon.withEscapableScope()); +console.log("class constructor:", new addon.Klass().description); +console.log("survives gc:", addon.survivesGc(gc)); +console.log("per-iteration napi_handle_scope:", addon.napiScopesRelease(liveArrayBuffers)); +addon.createBuffers(); +console.log("no scope:", liveArrayBuffers() < 100 ? "released when the callback returned" : "still alive after the callback returned"); +addon.stashArray(); +console.log("global handle:", addon.readStashedArray());`, + ), + ); + const cwd = String(dir); + await buildStandaloneAddon(cwd); + const { lines, err, exitCode } = await runStandaloneAddon(cwd); + expect(lines, `stderr:\n${err}`).toEqual([ + "function without scope: arrays of length 3 and 4, 'string from v8'", + "function with scope: arrays of length 3 and 4, 'string from v8'", + "function with escapable scope: escaped string", + "class constructor: arrays of length 3 and 4, 'string from v8'", + "survives gc: 500 of 500 strings intact after gc", + "per-iteration napi_handle_scope: released before the callback returned", + "no scope: released when the callback returned", + "global handle: stashed array of length 5, 5000 in total over 1000 inline scopes", + ]); + expect(exitCode).toBe(0); + }, + 10 * 60 * 1000, + ); +}); + describe.skipIf(!canBuildNodeAddons()).todoIf(isBroken && isMusl)("String::Utf8Length bounds", () => { it( "reports sizes beyond INT32_MAX without wrapping",