Skip to content

feat: JSDoc type annotations for all tree node files - #4413

Merged
matthew-dean merged 2 commits into
less:masterfrom
matthew-dean:feat/jsdoc-classes
Mar 10, 2026
Merged

matthew-dean merged 2 commits into
less:masterfrom
matthew-dean:feat/jsdoc-classes

Conversation

@matthew-dean

@matthew-dean matthew-dean commented Mar 10, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Adds @ts-check and proper JSDoc type annotations to all 44 files in lib/less/tree/
  • Enables per-file TypeScript checking — zero TS errors with tsc --noEmit
  • No {*} or {any} casts — all types derived from reading actual code
  • Adds typecheck to prepublishOnly and pre-commit hook to prevent regressions
  • Step toward enabling checkJs: true globally in tsconfig.json

Key changes

  • Shared types (EvalContext, CSSOutput, TreeVisitor, FileInfo, VisibilityInfo) defined in node.js
  • Node.value typed as union: Node | Node[] | string | number | undefined
  • Node.prototype.parse declared for parser-injected prototype property (avoids shadowing)
  • Constructor properties explicitly declared with proper types
  • Inline casts used to narrow union types at usage sites
  • Base class param types widened where subclasses pass different types

Test plan

  • All 139 existing tests pass
  • tsc --noEmit reports zero errors
  • No runtime behavior changes (JSDoc casts are compile-time only)
  • Pre-commit hook validates typecheck + tests

Summary by CodeRabbit

  • Refactor

    • Modernized many core modules to ES2015 class-style implementations.
    • Added widespread JSDoc/TypeScript check annotations and stronger runtime type handling.
    • Updated public APIs across the tree model (constructors, methods and getters) for numerous node types, improving eval/genCSS/error paths and consistency.
  • Chores

    • Pre-commit now runs a typecheck step before tests.
    • Build/publish tooling enforces stricter type checking during packaging.

@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Mar 10, 2026
@coderabbitai

coderabbitai Bot commented Mar 10, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Converts many Less AST node implementations from prototype-style to ES6 classes, adds // @ts-check and JSDoc typing across tree modules, tightens runtime type casts, and adds a pre-commit hook that runs the less package typecheck before tests.

Changes

Cohort / File(s) Summary
Build & Package
/.husky/pre-commit, packages/less/package.json
Adds pre-commit step to run cd packages/less && npm run typecheck && cd ../.. before tests; changes less package typecheck to tsc --noEmit and runs typecheck in prepublish.
Core Node & Type Infrastructure
packages/less/lib/less/tree/node.js, packages/less/lib/less/tree/debug-info.js, packages/less/lib/less/tree/index.js
Expanded Node API (visibility blocks, fileInfo/index getters, compare/numeric helpers), added typedefs and // @ts-check, and small export list cleanup.
Major AST refactors (Ruleset / Selector / Import / Media / AtRule / Container)
packages/less/lib/less/tree/ruleset.js, packages/less/lib/less/tree/selector.js, packages/less/lib/less/tree/import.js, packages/less/lib/less/tree/atrule.js, packages/less/lib/less/tree/media.js, packages/less/lib/less/tree/container.js, packages/less/lib/less/tree/nested-at-rule.js
Large rewrites from prototype functions to ES6 classes with new constructors, typed fields/typedefs, reworked eval/genCSS flows, import/ruleset handling, NestableAtRule behaviours merged into classes, and new exported helpers (e.g., ContainerSyntaxOptions).
Mixins & Definitions
packages/less/lib/less/tree/mixin-definition.js, packages/less/lib/less/tree/mixin-call.js
Converted mixin Definition and MixinCall to classes, added MixinParam/MixinSearchFrame typedefs, improved arg expansion, matching, and evaluation with explicit casts.
Declarations / Values / Expressions / Quoted / Assignment
packages/less/lib/less/tree/declaration.js, packages/less/lib/less/tree/value.js, packages/less/lib/less/tree/expression.js, packages/less/lib/less/tree/quoted.js, packages/less/lib/less/tree/assignment.js
Class-based refactors, added evalName helper, stronger JSDoc/@ts-check, safer eval/genCSS paths, iterative variable/property replacement, and explicit node/array casts.
Variables, VariableCall, Namespace Lookup
packages/less/lib/less/tree/variable.js, packages/less/lib/less/tree/variable-call.js, packages/less/lib/less/tree/namespace-value.js
Added recursion guard (evaluating), find helper, robust Ruleset casting, and normalized VariableCall/NamespaceValue evaluation for varied return shapes.
Functions / JS Eval / Call / JS helpers
packages/less/lib/less/tree/call.js, packages/less/lib/less/tree/javascript.js, packages/less/lib/less/tree/js-eval-node.js
Call/JavaScript/JsEvalNode moved to classes, stronger error normalization, compiled expression function caching, jsify helper, and wrapping non-Node JS results into Node types.
Operations, Dimensions, Units & Color
packages/less/lib/less/tree/operation.js, packages/less/lib/less/tree/dimension.js, packages/less/lib/less/tree/unit.js, packages/less/lib/less/tree/color.js
Typed/operator-aware refactors: Operation dispatches to Dimension/Color, Dimension/Unit/Color become classes with conversion/operate/compare utilities and explicit casts.
Various small AST nodes & utilities
packages/less/lib/less/tree/*.js (e.g., anonymous.js, keyword.js, comment.js, combinator.js, paren.js, negative.js, url.js, attribute.js, query-in-parens.js, property.js, merge-rules.js, unicode-descriptor.js)
Many smaller AST node files converted to classes, added // @ts-check and JSDoc, minor logic or genCSS/toCSS casts, small API additions (e.g., Keyword.True/False, Comment.debugInfo), and typed helpers.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

Poem

🐰 I hopped through nodes with types in my paw,

Swapped prototypes for classes, obeying each law.
A pre-commit typecheck, a tidy new shoelace,
Less trees now march in a clearer, typed place.
Hooray — carrots for refactor, and peace in the base!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat: JSDoc type annotations for all tree node files' clearly and concisely summarizes the main change—adding comprehensive JSDoc type annotations across all 44 tree node files in lib/less/tree/.
Docstring Coverage ✅ Passed Docstring coverage is 88.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
packages/less/lib/less/functions/style.js (1)

20-27: ⚠️ Potential issue | 🟠 Major

Don't swallow all style() evaluation failures.

This fallback now hides real Less errors too. If styleExpression throws because a Less variable is missing or invalid, the function will quietly return undefined and fall back to plain CSS instead of failing. It also suppresses the new zero-argument Argument error. Limit the fallback to the CSS-function case only, and let genuine evaluation errors propagate.

🔧 Narrow the fallback instead of catching everything
 export default {
     /** `@param` {...*} args */
     style: function(...args) {
-        try {
-            return styleExpression.call(this, args);
-        } catch (e) {
-            // When style() is used as a CSS function (e.g. `@container` style(--responsive: true)),
-            // arguments won't be valid Less variables. Return undefined to let the
-            // parser fall through and treat it as plain CSS.
-        }
+        if (args.length === 0 || args[0] instanceof Variable) {
+            return styleExpression.call(this, args);
+        }
+
+        // When style() is used as a CSS function (e.g. `@container` style(--responsive: true)),
+        // the argument is not a Less variable. Return undefined so the call is emitted as CSS.
+        return;
     },
 };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/functions/style.js` around lines 20 - 27, The current
try/catch in style() swallows all errors from styleExpression; narrow it so only
the CSS-function case is ignored: inspect the received args in style(...args)
and if they look like a raw CSS function invocation (e.g., a single
Anonymous/Quoted node or an arg whose .type indicates it’s not a parsed Less
expression) return undefined, otherwise rethrow the caught error so genuine Less
evaluation errors (including the zero-argument Argument error) propagate; update
the catch in style() to only swallow and return undefined for that specific args
shape and rethrow for anything else, keeping references to style and
styleExpression to locate the change.
packages/less/lib/less/tree/ruleset.js (1)

689-708: ⚠️ Potential issue | 🟠 Major

The single-selector branch in createParenthesis() is inverted.

Line 694 checks elementsToPak.length === 0 and then immediately reads elementsToPak[0]. The call at Line 950 passes a one-element array, so the direct new Paren(selector) path never runs and single nested selectors are wrapped differently from the original AST.

💡 Proposed fix
-            if (elementsToPak.length === 0) {
+            if (elementsToPak.length === 1) {
                 replacementParen = new Paren(elementsToPak[0]);
             } else {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/ruleset.js` around lines 689 - 708, The branch in
createParenthesis wrongly treats an empty array as the single-selector case;
change the condition to check for a single element (elementsToPak.length === 1)
so that when there is exactly one element you do replacementParen = new
Paren(elementsToPak[0]), otherwise build insideParent / Selector from
elementsToPak as currently implemented; locate this in the createParenthesis
function using the symbols elementsToPak, replacementParen, originalElement,
Paren, Selector, and Element.
packages/less/lib/less/tree/property.js (1)

41-79: ⚠️ Potential issue | 🟠 Major

Use the node accessors here and clear evaluating on every exit.

Line 77/Line 78 still read this.currentFileInfo.filename and this.index, but this class now stores _fileInfo/_index and the earlier throw path already uses fileInfo() / getIndex(). That means an undefined property reference can raise a secondary error instead of the intended Name error, and because this.evaluating is only reset on the success path, any throw between Line 41 and Line 79 leaves the node stuck in the recursive state on the next eval.

Proposed fix
         this.evaluating = true;
-
-        property = this.find(context.frames, function (/** `@type` {Node} */ frame) {
-            let v;
-            const vArr = /** `@type` {Ruleset} */ (frame).property(name);
-            if (vArr) {
-                for (let i = 0; i < vArr.length; i++) {
-                    v = vArr[i];
-
-                    vArr[i] = new Declaration(v.name,
-                        v.value,
-                        v.important,
-                        v.merge,
-                        v.index,
-                        v.currentFileInfo,
-                        v.inline,
-                        v.variable
-                    );
-                }
-                mergeRules(vArr);
-
-                v = vArr[vArr.length - 1];
-                if (v.important) {
-                    const importantScope = context.importantScope[context.importantScope.length - 1];
-                    importantScope.important = v.important;
-                }
-                v = v.value.eval(context);
-                return v;
-            }
-        });
-        if (property) {
-            this.evaluating = false;
-            return property;
-        } else {
-            throw { type: 'Name',
-                message: `Property '${name}' is undefined`,
-                filename: this.currentFileInfo.filename,
-                index: this.index };
-        }
+        try {
+            property = this.find(context.frames, function (/** `@type` {Node} */ frame) {
+                let v;
+                const vArr = /** `@type` {Ruleset} */ (frame).property(name);
+                if (vArr) {
+                    for (let i = 0; i < vArr.length; i++) {
+                        v = vArr[i];
+
+                        vArr[i] = new Declaration(v.name,
+                            v.value,
+                            v.important,
+                            v.merge,
+                            v.index,
+                            v.currentFileInfo,
+                            v.inline,
+                            v.variable
+                        );
+                    }
+                    mergeRules(vArr);
+
+                    v = vArr[vArr.length - 1];
+                    if (v.important) {
+                        const importantScope = context.importantScope[context.importantScope.length - 1];
+                        importantScope.important = v.important;
+                    }
+                    v = v.value.eval(context);
+                    return v;
+                }
+            });
+        } finally {
+            this.evaluating = false;
+        }
+        if (property) {
+            return property;
+        }
+        throw { type: 'Name',
+            message: `Property '${name}' is undefined`,
+            filename: this.fileInfo().filename,
+            index: this.getIndex() };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/property.js` around lines 41 - 79, The node
leaves this.evaluating true and uses legacy fields on error paths; update the
method (the Property node's eval logic) to always clear this.evaluating on every
exit (use a try { ... } finally { this.evaluating = false; }) and replace
references to this.currentFileInfo.filename and this.index in the thrown Name
error with the node accessors fileInfo().filename and getIndex() (or fileInfo()
/ getIndex()) so the thrown error uses the new _fileInfo/_index accessors.
packages/less/lib/less/tree/call.js (1)

71-109: ⚠️ Potential issue | 🟠 Major

Restore calc state in a single finally.

Line 74 exits calc/math mode before the fallback path is decided, while exceptions from funcCaller.call() and this.args.map(...) skip cleanup entirely. Inside nested calc(...) evaluation, that can leave the caller with the wrong calc/math state or unwind it too far before the outer call finishes.

Proposed fix
-        if (funcCaller.isValid()) {
-            try {
-                result = funcCaller.call(this.args);
-                exitCalc();
-            } catch (e) {
-                // eslint-disable-next-line no-prototype-builtins
-                if (/** `@type` {Record<string, unknown>} */ (e).hasOwnProperty('line') && /** `@type` {Record<string, unknown>} */ (e).hasOwnProperty('column')) {
-                    throw e;
-                }
-                throw {
-                    type: /** `@type` {Record<string, string>} */ (e).type || 'Runtime',
-                    message: `Error evaluating function \`${this.name}\`${/** `@type` {Error} */ (e).message ? `: ${/** `@type` {Error} */ (e).message}` : ''}`,
-                    index: this.getIndex(),
-                    filename: this.fileInfo().filename,
-                    line: /** `@type` {Record<string, number>} */ (e).lineNumber,
-                    column: /** `@type` {Record<string, number>} */ (e).columnNumber
-                };
-            }
-        }
-
-        if (result !== null && result !== undefined) {
-            // Results that that are not nodes are cast as Anonymous nodes
-            // Falsy values or booleans are returned as empty nodes
-            if (!(result instanceof Node)) {
-                if (!result || result === true) {
-                    result = new Anonymous(null);
-                }
-                else {
-                    result = new Anonymous(result.toString());
-                }
-
-            }
-            result._index = this._index;
-            result._fileInfo = this._fileInfo;
-            return result;
-        }
-
-        const args = this.args.map(a => a.eval(context));
-        exitCalc();
-
-        return new Call(this.name, args, this.getIndex(), this.fileInfo());
+        try {
+            if (funcCaller.isValid()) {
+                try {
+                    result = funcCaller.call(this.args);
+                } catch (e) {
+                    // eslint-disable-next-line no-prototype-builtins
+                    if (/** `@type` {Record<string, unknown>} */ (e).hasOwnProperty('line') && /** `@type` {Record<string, unknown>} */ (e).hasOwnProperty('column')) {
+                        throw e;
+                    }
+                    throw {
+                        type: /** `@type` {Record<string, string>} */ (e).type || 'Runtime',
+                        message: `Error evaluating function \`${this.name}\`${/** `@type` {Error} */ (e).message ? `: ${/** `@type` {Error} */ (e).message}` : ''}`,
+                        index: this.getIndex(),
+                        filename: this.fileInfo().filename,
+                        line: /** `@type` {Record<string, number>} */ (e).lineNumber,
+                        column: /** `@type` {Record<string, number>} */ (e).columnNumber
+                    };
+                }
+            }
+
+            if (result !== null && result !== undefined) {
+                // Results that that are not nodes are cast as Anonymous nodes
+                // Falsy values or booleans are returned as empty nodes
+                if (!(result instanceof Node)) {
+                    if (!result || result === true) {
+                        result = new Anonymous(null);
+                    }
+                    else {
+                        result = new Anonymous(result.toString());
+                    }
+
+                }
+                result._index = this._index;
+                result._fileInfo = this._fileInfo;
+                return result;
+            }
+
+            const args = this.args.map(a => a.eval(context));
+            return new Call(this.name, args, this.getIndex(), this.fileInfo());
+        } finally {
+            exitCalc();
+        }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/call.js` around lines 71 - 109, The calc/math
state must be restored in a single finally so exitCalc() always runs; wrap the
logic that may early-return or throw (the funcCaller.isValid() branch including
the funcCaller.call(this.args) call and the later fallback this.args.map(a =>
a.eval(context))) in a try { ... } finally { exitCalc(); } and remove the
existing exitCalc() calls inside the try and before args evaluation so
exitCalc() is invoked exactly once regardless of success, return, or exception;
keep the existing behavior around converting non-Node results to Anonymous and
preserving _index/_fileInfo.
🧹 Nitpick comments (8)
packages/less/lib/less/tree/value.js (1)

8-20: Minor: Error message doesn't match the accepted parameter type.

The JSDoc indicates value can be Node[] | Node, but the error message says "Value requires an array argument". Consider updating the message to reflect that a single Node is also accepted.

💡 Suggested message update
         if (!value) {
-            throw new Error('Value requires an array argument');
+            throw new Error('Value requires a value argument');
         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/value.js` around lines 8 - 20, The constructor
for Value currently throws "Value requires an array argument" when value is
falsy; update the thrown Error message in the Value class constructor to
accurately reflect the accepted parameter types (Node or Node[]) — e.g., mention
that a Node or array of Nodes is required — so the message aligns with the JSDoc
and the constructor's handling of single Node values.
packages/less/benchmark/index.js (1)

29-37: The less.parse callback signature is correct. The callback receives four parameters (err, root, imports, options) as shown in line 82 of packages/less/lib/less/parse.js, and the ParseTree constructor correctly accepts root and imports.

Consider wrapping the ParseTree construction and toCSS call in a try-catch block to handle rendering errors gracefully during benchmarking, since any exception thrown by toCSS would otherwise propagate uncaught.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/benchmark/index.js` around lines 29 - 37, The less.parse
callback currently calls new less.ParseTree(root, imports) and
tree.toCSS(options) without protection; wrap the ParseTree construction and the
tree.toCSS(options) call in a try-catch inside the less.parse callback to catch
rendering exceptions, call console.error with the caught error and a short
context message, and exit or set a non-zero status (e.g., process.exit(3) or
similar) so the benchmark handles rendering errors gracefully instead of letting
exceptions propagate.
packages/less/lib/less/tree/quoted.js (1)

58-83: Use the real replace() callback shape here.

These patterns each have one capture group. At Line 64 and Line 75, the next argument from String.prototype.replace() would be the numeric offset, not a second captured name, so the current JSDoc and ?? name2 fallback are misleading.

Suggested cleanup
         /**
          * `@param` {string} _
          * `@param` {string} name1
-         * `@param` {string} name2
          * `@returns` {string}
          */
-        const variableReplacement = function (_, name1, name2) {
-            const v = new Variable(`@${name1 ?? name2}`, that.getIndex(), that.fileInfo()).eval(context);
+        const variableReplacement = function (_, name1) {
+            const v = new Variable(`@${name1}`, that.getIndex(), that.fileInfo()).eval(context);
             return (v instanceof Quoted) ? /** `@type` {string} */ (v.value) : v.toCSS(context);
         };
         /**
          * `@param` {string} _
          * `@param` {string} name1
-         * `@param` {string} name2
          * `@returns` {string}
          */
-        const propertyReplacement = function (_, name1, name2) {
-            const v = new Property(`$${name1 ?? name2}`, that.getIndex(), that.fileInfo()).eval(context);
+        const propertyReplacement = function (_, name1) {
+            const v = new Property(`$${name1}`, that.getIndex(), that.fileInfo()).eval(context);
             return (v instanceof Quoted) ? /** `@type` {string} */ (v.value) : v.toCSS(context);
         };
         /**
          * `@param` {string} value
          * `@param` {RegExp} regexp
-         * `@param` {(substring: string, ...args: string[]) => string} replacementFnc
+         * `@param` {(substring: string, name: string) => string} replacementFnc
          * `@returns` {string}
          */
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/quoted.js` around lines 58 - 83, The replace
callback signatures are wrong: String.prototype.replace passes (match, capture1,
offset, string...), so there is no second captured name; update
variableReplacement and propertyReplacement to accept (match, name) (remove
name2 and the "?? name2" fallback), update their JSDoc to reflect a single
captured group (e.g., `@param` {string} match, `@param` {string} name), and use that
single name when constructing new Variable(`@${name}`...) and new
Property(`$${name}`...); keep the rest of the logic (instanceof Quoted check and
toCSS) unchanged.
packages/less/lib/less/tree/expression.js (1)

55-72: Prefer structural narrow types over Expression assertions here.

value[0] and returnValue are not guaranteed to be Expression instances on this path — returnValue can be a Dimension, and value[0] only needs a couple of optional flags. Using small structural types keeps @ts-check honest instead of asserting a narrower runtime shape.

♻️ Suggested typing cleanup
-            const first = /** `@type` {Expression} */ (value[0]);
+            const first = /** `@type` {{ parens?: boolean, parensInOp?: boolean }} */ (value[0]);
             if (first.parens && !first.parensInOp && !context.inCalc) {
                 doubleParen = true;
             }
             returnValue = value[0].eval(context);

-        /** `@type` {Expression} */ (returnValue).noSpacing =
-            /** `@type` {Expression} */ (returnValue).noSpacing || noSpacing;
+        /** `@type` {{ noSpacing?: boolean }} */ (returnValue).noSpacing =
+            /** `@type` {{ noSpacing?: boolean }} */ (returnValue).noSpacing || noSpacing;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/expression.js` around lines 55 - 72, The code
currently asserts value[0] and returnValue as Expression which is too narrow
(returnValue can be a Dimension and value[0] only needs a few optional flags and
eval), so remove the blanket /** `@type` {Expression} */ casts and introduce small
structural JSDoc types (e.g. a MinimalExpr with optional properties parens,
parensInOp, noSpacing and an eval(context) method, and a union type for
Returnable = MinimalExpr | Dimension). Replace the two Expression assertions
around value[0] and returnValue with casts to these small structural types (or
use inline object-type JSDoc annotations) and update the final noSpacing
assignment to safely access noSpacing on the union (using the structural type)
so `@ts-check` validates the shape without over-asserting Expression.
packages/less/lib/less/tree/variable.js (1)

2-5: Use a type-only JSDoc import for Ruleset.

Ruleset is only used in the cast on Line 45, so this real ESM import adds a runtime module edge to an otherwise annotation-only change. Please switch it to a JSDoc type alias/import unless ruleset.js is intentionally needed at runtime.

💡 Suggested fix
 /** `@import` { EvalContext, FileInfo } from './node.js' */
+/** `@typedef` {import('./ruleset.js').default} Ruleset */
 import Node from './node.js';
 import Call from './call.js';
-import Ruleset from './ruleset.js';
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/variable.js` around lines 2 - 5, The import of
Ruleset in variable.js is a runtime ESM import but it's only used as a type in
the cast (the cast referencing Ruleset), so remove the runtime import of Ruleset
and replace it with a JSDoc type-only import/typedef (e.g. a typedef that
imports Ruleset via import('./ruleset.js').Ruleset) so the cast can keep using
the Ruleset identifier without creating a runtime module edge; keep the existing
cast as-is and remove the "import Ruleset from './ruleset.js';" statement.
packages/less/lib/less/tree/atrule.js (1)

49-49: Use const instead of var for consistency.

The rest of the file uses let/const declarations. This var should be updated for consistency.

-        var selectors = (new Selector([], null, null, index, currentFileInfo)).createEmptySelectors();
+        const selectors = (new Selector([], null, null, index, currentFileInfo)).createEmptySelectors();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/atrule.js` at line 49, Replace the
function-scoped var declaration with a block-scoped const to match the rest of
the file: change the declaration of selectors (the result of (new Selector([],
null, null, index, currentFileInfo)).createEmptySelectors()) from var to const
so it uses const and preserves immutability while keeping references to Selector
and createEmptySelectors unchanged.
packages/less/lib/less/tree/unit.js (1)

71-73: Consider extracting the regex to a module-level constant.

The RegExp is recreated on every isLength() call. While this is a minor performance concern, extracting it as a module-level constant would be slightly more efficient.

+const LENGTH_UNITS_REGEX = /^(px|em|ex|ch|rem|in|cm|mm|pc|pt|ex|vw|vh|vmin|vmax)$/i;
+
 class Unit extends Node {
     // ...
     isLength() {
-        return RegExp('^(px|em|ex|ch|rem|in|cm|mm|pc|pt|ex|vw|vh|vmin|vmax)$', 'gi').test(this.toCSS(/** `@type` {import('./node.js').EvalContext} */ ({})));
+        return LENGTH_UNITS_REGEX.test(this.toCSS(/** `@type` {import('./node.js').EvalContext} */ ({})));
     }

Note: The gi flags include g (global) which is unnecessary for .test() with a single match, and i alone suffices for case-insensitivity.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/unit.js` around lines 71 - 73, The isLength()
method recreates the RegExp on each call and uses an unnecessary 'g' flag;
extract the pattern to a module-level constant (e.g., LENGTH_UNITS) using a
single case-insensitive regex (no 'g') and replace the inline RegExp call in
isLength() with LENGTH_UNITS.test(this.toCSS(/** `@type`
{import('./node.js').EvalContext} */ ({}))); this moves the regex allocation out
of the hot path and removes the redundant global flag.
packages/less/lib/less/tree/js-eval-node.js (1)

66-71: Casting undefined to EvalContext may mask runtime issues.

The toCSS method typically expects a valid context object. While this cast silences the type checker, passing undefined could cause runtime issues if toCSS implementations access context properties without null checks.

Consider using an empty object instead if a minimal context is acceptable:

-            return `[${obj.value.map(function (v) { return v.toCSS(/** `@type` {EvalContext} */ (undefined)); }).join(', ')}]`;
+            return `[${obj.value.map(function (v) { return v.toCSS(/** `@type` {EvalContext} */ ({})); }).join(', ')}]`;
         } else {
-            return obj.toCSS(/** `@type` {EvalContext} */ (undefined));
+            return obj.toCSS(/** `@type` {EvalContext} */ ({}));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/js-eval-node.js` around lines 66 - 71, The code
is casting undefined to EvalContext when calling obj.toCSS inside the array map
and fallback, which can hide runtime errors; update the calls to pass a minimal
context object instead of undefined (e.g., an empty object typed as EvalContext
or a shared minimalEvalContext) so toCSS receives a real context; modify the two
places where toCSS is invoked (the map callback using v.toCSS(...) and the
fallback obj.toCSS(...)) to use that minimal context and ensure its shape
satisfies any required properties of EvalContext.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/less/lib/less/tree/atrule.js`:
- Line 202: The forEach callback currently uses an expression that returns a
value (rule.merge = false), which Biome flags; change the callback on
rules.forEach to use an explicit block-style function body so it performs the
assignment without returning a value (i.e. replace the concise arrow expression
with a block that sets rule.merge = false); locate the invocation at
rules.forEach(/** `@param` {RulesetLikeNode} rule */ rule => rule.merge = false)
and update it so the callback is a statement-only block to avoid unintended
returns.

In `@packages/less/lib/less/tree/color.js`:
- Around line 18-53: The constructor currently uses "this.alpha = this.alpha ||
(typeof a === 'number' ? a : 1);" which overwrites a parsed alpha of 0; change
the logic in the Color constructor to only assign the default alpha when
this.alpha is undefined (i.e., check typeof this.alpha === 'undefined') and
otherwise keep the parsed value, falling back to the passed parameter a if
provided; refer to the Color constructor, this.alpha, and parameter a when
making the change.

In `@packages/less/lib/less/tree/import.js`:
- Around line 182-183: The evaluated features node (const features =
this.features && this.features.eval(context)) is computed but later branches
still check this.features.value, causing layer(...) to be missed after
evaluation; update the isLayer checks and any subsequent inspections in
Import.prototype methods (the branches handling layer-import vs media-import,
e.g. the blocks referenced around lines 182, 216-229, 255-288) to use the
already-evaluated features variable instead of this.features.value so the
decision uses the post-evaluation AST node; locate uses of this.features.value
in those methods and replace them with checks against features (and adjust
null/undefined handling accordingly).

In `@packages/less/lib/less/tree/mixin-call.js`:
- Around line 226-229: The catch block currently recreates an error object
losing any extra properties from the original Less error (e.g., type); preserve
nested error metadata by merging the original error object (err) into the thrown
object while still setting/overriding message, index (this.getIndex()), filename
(this.fileInfo().filename) and stack; locate the catch in mixin-call.js around
evalCall() where err is defined and change the throw to include the full err
(spread or equivalent) so nested fields like type are retained.

In `@packages/less/lib/less/tree/nested-at-rule.js`:
- Around line 21-37: The typedef NestableAtRuleThis declares evalNested as
returning Ruleset but the implementation can return self (a Node subtype);
update the typedef entry evalNested: (context: EvalContext) => Ruleset to
evalNested: (context: EvalContext) => Node | Ruleset so the signature matches
possible return values (adjust the union type on the evalNested property in the
NestableAtRuleThis typedef).

In `@packages/less/lib/less/tree/ruleset.js`:
- Around line 146-153: The callback passed to Parser.prototype.parseNode
currently ignores the err parameter, causing invalid interpolated selectors to
be silently kept; update the callback used in the new Parser(...).parseNode(...)
call to check for err and throw/propagate it (e.g. if (err) throw err;) before
assigning selectors, mirroring the error handling used in Selector parsing; keep
the existing assignment selectors = utils.flattenArray(result) only when err is
null and result is present.

In `@packages/less/lib/less/tree/selector.js`:
- Around line 76-86: The callback passed to Parser.parseNode inside
getElements() uses a plain function and references this._fileInfo, causing this
to be undefined on callback invocation; fix it by capturing this._fileInfo into
a local variable (e.g. const fileInfo = this._fileInfo) before the parseNode
call and replace the plain function callback with an arrow function (or
otherwise bind the callback) so the error path uses the captured fileInfo when
constructing the LessError; update the callback passed to Parser.parseNode in
getElements() accordingly.

---

Outside diff comments:
In `@packages/less/lib/less/functions/style.js`:
- Around line 20-27: The current try/catch in style() swallows all errors from
styleExpression; narrow it so only the CSS-function case is ignored: inspect the
received args in style(...args) and if they look like a raw CSS function
invocation (e.g., a single Anonymous/Quoted node or an arg whose .type indicates
it’s not a parsed Less expression) return undefined, otherwise rethrow the
caught error so genuine Less evaluation errors (including the zero-argument
Argument error) propagate; update the catch in style() to only swallow and
return undefined for that specific args shape and rethrow for anything else,
keeping references to style and styleExpression to locate the change.

In `@packages/less/lib/less/tree/call.js`:
- Around line 71-109: The calc/math state must be restored in a single finally
so exitCalc() always runs; wrap the logic that may early-return or throw (the
funcCaller.isValid() branch including the funcCaller.call(this.args) call and
the later fallback this.args.map(a => a.eval(context))) in a try { ... } finally
{ exitCalc(); } and remove the existing exitCalc() calls inside the try and
before args evaluation so exitCalc() is invoked exactly once regardless of
success, return, or exception; keep the existing behavior around converting
non-Node results to Anonymous and preserving _index/_fileInfo.

In `@packages/less/lib/less/tree/property.js`:
- Around line 41-79: The node leaves this.evaluating true and uses legacy fields
on error paths; update the method (the Property node's eval logic) to always
clear this.evaluating on every exit (use a try { ... } finally { this.evaluating
= false; }) and replace references to this.currentFileInfo.filename and
this.index in the thrown Name error with the node accessors fileInfo().filename
and getIndex() (or fileInfo() / getIndex()) so the thrown error uses the new
_fileInfo/_index accessors.

In `@packages/less/lib/less/tree/ruleset.js`:
- Around line 689-708: The branch in createParenthesis wrongly treats an empty
array as the single-selector case; change the condition to check for a single
element (elementsToPak.length === 1) so that when there is exactly one element
you do replacementParen = new Paren(elementsToPak[0]), otherwise build
insideParent / Selector from elementsToPak as currently implemented; locate this
in the createParenthesis function using the symbols elementsToPak,
replacementParen, originalElement, Paren, Selector, and Element.

---

Nitpick comments:
In `@packages/less/benchmark/index.js`:
- Around line 29-37: The less.parse callback currently calls new
less.ParseTree(root, imports) and tree.toCSS(options) without protection; wrap
the ParseTree construction and the tree.toCSS(options) call in a try-catch
inside the less.parse callback to catch rendering exceptions, call console.error
with the caught error and a short context message, and exit or set a non-zero
status (e.g., process.exit(3) or similar) so the benchmark handles rendering
errors gracefully instead of letting exceptions propagate.

In `@packages/less/lib/less/tree/atrule.js`:
- Line 49: Replace the function-scoped var declaration with a block-scoped const
to match the rest of the file: change the declaration of selectors (the result
of (new Selector([], null, null, index,
currentFileInfo)).createEmptySelectors()) from var to const so it uses const and
preserves immutability while keeping references to Selector and
createEmptySelectors unchanged.

In `@packages/less/lib/less/tree/expression.js`:
- Around line 55-72: The code currently asserts value[0] and returnValue as
Expression which is too narrow (returnValue can be a Dimension and value[0] only
needs a few optional flags and eval), so remove the blanket /** `@type`
{Expression} */ casts and introduce small structural JSDoc types (e.g. a
MinimalExpr with optional properties parens, parensInOp, noSpacing and an
eval(context) method, and a union type for Returnable = MinimalExpr |
Dimension). Replace the two Expression assertions around value[0] and
returnValue with casts to these small structural types (or use inline
object-type JSDoc annotations) and update the final noSpacing assignment to
safely access noSpacing on the union (using the structural type) so `@ts-check`
validates the shape without over-asserting Expression.

In `@packages/less/lib/less/tree/js-eval-node.js`:
- Around line 66-71: The code is casting undefined to EvalContext when calling
obj.toCSS inside the array map and fallback, which can hide runtime errors;
update the calls to pass a minimal context object instead of undefined (e.g., an
empty object typed as EvalContext or a shared minimalEvalContext) so toCSS
receives a real context; modify the two places where toCSS is invoked (the map
callback using v.toCSS(...) and the fallback obj.toCSS(...)) to use that minimal
context and ensure its shape satisfies any required properties of EvalContext.

In `@packages/less/lib/less/tree/quoted.js`:
- Around line 58-83: The replace callback signatures are wrong:
String.prototype.replace passes (match, capture1, offset, string...), so there
is no second captured name; update variableReplacement and propertyReplacement
to accept (match, name) (remove name2 and the "?? name2" fallback), update their
JSDoc to reflect a single captured group (e.g., `@param` {string} match, `@param`
{string} name), and use that single name when constructing new
Variable(`@${name}`...) and new Property(`$${name}`...); keep the rest of the
logic (instanceof Quoted check and toCSS) unchanged.

In `@packages/less/lib/less/tree/unit.js`:
- Around line 71-73: The isLength() method recreates the RegExp on each call and
uses an unnecessary 'g' flag; extract the pattern to a module-level constant
(e.g., LENGTH_UNITS) using a single case-insensitive regex (no 'g') and replace
the inline RegExp call in isLength() with LENGTH_UNITS.test(this.toCSS(/** `@type`
{import('./node.js').EvalContext} */ ({}))); this moves the regex allocation out
of the hot path and removes the redundant global flag.

In `@packages/less/lib/less/tree/value.js`:
- Around line 8-20: The constructor for Value currently throws "Value requires
an array argument" when value is falsy; update the thrown Error message in the
Value class constructor to accurately reflect the accepted parameter types (Node
or Node[]) — e.g., mention that a Node or array of Nodes is required — so the
message aligns with the JSDoc and the constructor's handling of single Node
values.

In `@packages/less/lib/less/tree/variable.js`:
- Around line 2-5: The import of Ruleset in variable.js is a runtime ESM import
but it's only used as a type in the cast (the cast referencing Ruleset), so
remove the runtime import of Ruleset and replace it with a JSDoc type-only
import/typedef (e.g. a typedef that imports Ruleset via
import('./ruleset.js').Ruleset) so the cast can keep using the Ruleset
identifier without creating a runtime module edge; keep the existing cast as-is
and remove the "import Ruleset from './ruleset.js';" statement.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 3f0e3012-372f-4696-b174-0c639140899a

📥 Commits

Reviewing files that changed from the base of the PR and between 76fc00c and 0c1a282.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (56)
  • .husky/pre-commit
  • packages/less/benchmark/index.js
  • packages/less/lib/less-browser/add-default-options.js
  • packages/less/lib/less-browser/utils.js
  • packages/less/lib/less-node/fs.js
  • packages/less/lib/less/deprecation.js
  • packages/less/lib/less/functions/style.js
  • packages/less/lib/less/index.js
  • packages/less/lib/less/parser/parser.js
  • packages/less/lib/less/transform-tree.js
  • packages/less/lib/less/tree/anonymous.js
  • packages/less/lib/less/tree/assignment.js
  • packages/less/lib/less/tree/atrule-syntax.js
  • packages/less/lib/less/tree/atrule.js
  • packages/less/lib/less/tree/attribute.js
  • packages/less/lib/less/tree/call.js
  • packages/less/lib/less/tree/color.js
  • packages/less/lib/less/tree/combinator.js
  • packages/less/lib/less/tree/comment.js
  • packages/less/lib/less/tree/condition.js
  • packages/less/lib/less/tree/container.js
  • packages/less/lib/less/tree/debug-info.js
  • packages/less/lib/less/tree/declaration.js
  • packages/less/lib/less/tree/detached-ruleset.js
  • packages/less/lib/less/tree/dimension.js
  • packages/less/lib/less/tree/element.js
  • packages/less/lib/less/tree/expression.js
  • packages/less/lib/less/tree/extend.js
  • packages/less/lib/less/tree/import.js
  • packages/less/lib/less/tree/index.js
  • packages/less/lib/less/tree/javascript.js
  • packages/less/lib/less/tree/js-eval-node.js
  • packages/less/lib/less/tree/keyword.js
  • packages/less/lib/less/tree/media.js
  • packages/less/lib/less/tree/merge-rules.js
  • packages/less/lib/less/tree/mixin-call.js
  • packages/less/lib/less/tree/mixin-definition.js
  • packages/less/lib/less/tree/namespace-value.js
  • packages/less/lib/less/tree/negative.js
  • packages/less/lib/less/tree/nested-at-rule.js
  • packages/less/lib/less/tree/node.js
  • packages/less/lib/less/tree/operation.js
  • packages/less/lib/less/tree/paren.js
  • packages/less/lib/less/tree/property.js
  • packages/less/lib/less/tree/query-in-parens.js
  • packages/less/lib/less/tree/quoted.js
  • packages/less/lib/less/tree/ruleset.js
  • packages/less/lib/less/tree/selector.js
  • packages/less/lib/less/tree/unicode-descriptor.js
  • packages/less/lib/less/tree/unit.js
  • packages/less/lib/less/tree/url.js
  • packages/less/lib/less/tree/value.js
  • packages/less/lib/less/tree/variable-call.js
  • packages/less/lib/less/tree/variable.js
  • packages/less/lib/less/visitors/set-tree-visibility-visitor.js
  • packages/less/package.json

Comment thread packages/less/lib/less/tree/atrule.js Resolved
Comment thread packages/less/lib/less/tree/color.js Resolved
Comment thread packages/less/lib/less/tree/import.js Resolved
Comment thread packages/less/lib/less/tree/ruleset.js Resolved
Comment thread packages/less/lib/less/tree/selector.js Resolved
@matthew-dean
matthew-dean force-pushed the feat/jsdoc-classes branch 2 times, most recently from ffa45da to 7760c01 Compare March 10, 2026 16:29
Add proper JSDoc type annotations to all 44 files in lib/less/tree/,
enabling per-file TypeScript checking via @ts-check. No {*} or {any}
casts — all types are derived from reading the actual code.

Key changes:
- Shared types (EvalContext, CSSOutput, TreeVisitor, FileInfo, VisibilityInfo) defined in node.js
- Node.value typed as union: Node | Node[] | string | number | undefined
- Node.prototype.parse declared for parser-injected prototype property
- Constructor properties explicitly declared with proper types
- Inline casts used to narrow union types at usage sites
- Widened base class params where subclasses pass different types

Also adds typecheck to prepublishOnly and pre-commit hook to catch
regressions as more files are annotated toward global checkJs: true.

All 139 tests pass, zero TypeScript errors.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/less/lib/less/tree/variable.js (1)

42-68: ⚠️ Potential issue | 🟡 Minor

Reset this.evaluating in a finally.

Any exception from v.value.eval(context)/Call.eval(context) or the undefined-variable branch leaves this node permanently marked as evaluating. Reusing the same AST node after that will false-positive as a recursive definition.

🛠️ Suggested fix
         this.evaluating = true;
-
-        variable = this.find(context.frames, function (frame) {
-            const v = /** `@type` {Ruleset} */ (frame).variable(name);
-            if (v) {
-                if (v.important) {
-                    const importantScope = context.importantScope[context.importantScope.length - 1];
-                    importantScope.important = v.important;
-                }
-                // If in calc, wrap vars in a function call to cascade evaluate args first
-                if (context.inCalc) {
-                    return (new Call('_SELF', [v.value], 0, undefined)).eval(context);
-                }
-                else {
-                    return v.value.eval(context);
-                }
-            }
-        });
-        if (variable) {
-            this.evaluating = false;
-            return variable;
-        } else {
-            throw { type: 'Name',
-                message: `variable ${name} is undefined`,
-                filename: this.fileInfo().filename,
-                index: this.getIndex() };
-        }
+        try {
+            variable = this.find(context.frames, function (frame) {
+                const v = /** `@type` {Ruleset} */ (frame).variable(name);
+                if (v) {
+                    if (v.important) {
+                        const importantScope = context.importantScope[context.importantScope.length - 1];
+                        importantScope.important = v.important;
+                    }
+                    // If in calc, wrap vars in a function call to cascade evaluate args first
+                    if (context.inCalc) {
+                        return (new Call('_SELF', [v.value], 0, undefined)).eval(context);
+                    }
+                    return v.value.eval(context);
+                }
+            });
+            if (variable) {
+                return variable;
+            }
+            throw { type: 'Name',
+                message: `variable ${name} is undefined`,
+                filename: this.fileInfo().filename,
+                index: this.getIndex() };
+        } finally {
+            this.evaluating = false;
+        }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/variable.js` around lines 42 - 68, The code sets
this.evaluating = true but only clears it on the success path, so exceptions
from v.value.eval(context), Call(...).eval(context), or the throw branch leave
the node marked evaluating; wrap the variable lookup and evaluation logic (the
find callback and subsequent return/throw) in a try/finally (or ensure a
finally-like cleanup) so that this.evaluating is always set back to false,
referencing the this.evaluating flag, the find invocation that calls
v.value.eval(context) and Call('_SELF', [v.value], 0, undefined).eval(context),
and ensure the finally executes before any throw to avoid spurious recursive
detection.
packages/less/lib/less/tree/ruleset.js (1)

689-710: ⚠️ Potential issue | 🟠 Major

Fix off-by-one error: condition should check length === 1, not length === 0.

When elementsToPak.length === 0, line 695 accesses elementsToPak[0], which is undefined. The condition should be === 1 to handle the single-element case, where that element is passed directly to the Paren constructor. The else branch handles multiple elements by wrapping each in an Element and Selector structure.

Proposed fix
-            if (elementsToPak.length === 0) {
+            if (elementsToPak.length === 1) {
                 replacementParen = new Paren(elementsToPak[0]);
             } else {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/ruleset.js` around lines 689 - 710, The
createParenthesis function has an off-by-one: it checks elementsToPak.length ===
0 but then uses elementsToPak[0]; change the condition to elementsToPak.length
=== 1 so the single-element path constructs replacementParen = new
Paren(elementsToPak[0]) correctly, while the else branch continues to wrap
multiple items into Element and Selector; update the conditional that currently
references elementsToPak.length to === 1 and ensure no other logic assumes a
zero-length array there.
♻️ Duplicate comments (4)
packages/less/lib/less/tree/nested-at-rule.js (1)

21-37: ⚠️ Potential issue | 🟡 Minor

evalNested still advertises the wrong return type.

Line 130 returns self, so NestableAtRuleThis.evalNested cannot be Ruleset-only. Because packages/less/lib/less/tree/atrule.js:332 reuses this prototype directly, the bad signature leaks beyond this helper.

🛠️ Type fix
- *   evalNested: (context: EvalContext) => Ruleset,
+ *   evalNested: (context: EvalContext) => Node | Ruleset,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/nested-at-rule.js` around lines 21 - 37, The
JSDoc typedef for NestableAtRuleThis incorrectly declares evalNested as
returning only Ruleset while the implementation (and reuse in atrule.js) can
return self (a Node) as well; update the typedef in nested-at-rule.js so
evalNested: (context: EvalContext) => Node | Ruleset (or the correct union type
used elsewhere) to match actual return values and prevent the incorrect narrow
signature from leaking to atrule.js and other consumers.
packages/less/lib/less/tree/color.js (1)

51-52: ⚠️ Potential issue | 🟠 Major

Don't overwrite parsed alpha 0 with the default.

Line 52 uses ||, so #0000 or #00000000 parse with alpha = 0 at lines 37/47, but then it's immediately replaced with 1 because 0 is falsy. This transforms fully transparent hex colors into opaque black.

Suggested fix
     /** `@type` {number} */
-    this.alpha = this.alpha || (typeof a === 'number' ? a : 1);
+    this.alpha = (this.alpha !== undefined) ? this.alpha : (typeof a === 'number' ? a : 1);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/color.js` around lines 51 - 52, The alpha
assignment in the Color constructor uses a falsy check and overwrites a parsed 0
(fully transparent) with 1; replace the falsy `||` logic on `this.alpha` with an
explicit undefined/null check (e.g., use nullish coalescing or test for
undefined) so that a parsed numeric 0 is preserved while still defaulting to `a`
or 1 when alpha is truly missing; update the line that sets `this.alpha` in
color.js (the assignment using `this.alpha || (typeof a === 'number' ? a : 1)`)
to use the explicit check.
packages/less/lib/less/tree/atrule.js (1)

202-202: ⚠️ Potential issue | 🟡 Minor

Use block syntax in forEach callback to avoid unintended return.

The assignment expression rule.merge = false returns false, which Biome flags as an unintended return from a forEach callback.

Suggested fix
-                rules.forEach(/** `@param` {RulesetLikeNode} rule */ rule => rule.merge = false);
+                rules.forEach(/** `@param` {RulesetLikeNode} rule */ rule => { rule.merge = false; });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/atrule.js` at line 202, The forEach callback
currently returns the assignment expression (rules.forEach(rule => rule.merge =
false)), which Biome flags as an unintended return; update the callback to use
block syntax so it performs the assignment without returning a value (e.g.,
change the arrow callback to a block-body that sets rule.merge = false) — locate
the rules.forEach call in atrule.js where RulesetLikeNode objects are iterated
and replace the concise arrow expression with a block-bodied callback that
executes rule.merge = false;.
packages/less/lib/less/tree/selector.js (1)

76-89: ⚠️ Potential issue | 🔴 Critical

Fix the callback binding in getElements().

The callback at lines 81-89 uses a plain function with this._fileInfo in the error path (line 86). When parseNode() invokes the callback on parse failures, this is undefined, causing a TypeError instead of reporting the actual parse error.

Suggested fix
         if (typeof els === 'string') {
             const parse = this.parse;
+            const fileInfo = this._fileInfo;
             new (/** `@type` {new (...args: unknown[]) => { parseNode: Function }} */ (/** `@type` {unknown} */ (Parser)))(parse.context, parse.importManager, this._fileInfo, this._index).parseNode(
                 els,
                 ['selector'],
-                function(/** `@type` {{ index: number, message: string } | null} */ err, /** `@type` {Selector[]} */ result) {
+                (/** `@type` {{ index: number, message: string } | null} */ err, /** `@type` {Selector[]} */ result) => {
                     if (err) {
                         throw new LessError({
                             index: err.index,
                             message: err.message
-                        }, parse.imports, /** `@type` {string} */ (/** `@type` {FileInfo} */ (this._fileInfo).filename));
+                        }, parse.imports, /** `@type` {string} */ (fileInfo && fileInfo.filename));
                     }
                     els = result[0].elements;
                 });
         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/selector.js` around lines 76 - 89, The callback
passed to Parser.parseNode inside getElements() uses a plain function so `this`
is undefined when invoked, causing a TypeError when referencing this._fileInfo;
change the callback to a bound function (e.g., use an arrow function or
.bind(this)) so it preserves the surrounding `this`, and ensure the error branch
constructs LessError with the correct this._fileInfo filename; update the
callback passed to parseNode (the anonymous function handling err and result)
accordingly to reference this._fileInfo safely.
🧹 Nitpick comments (3)
packages/less/lib/less/tree/property.js (1)

5-5: Import mergeRules directly instead of reaching through pluginManager.

packages/less/lib/less/tree/merge-rules.js already exports the helper this code needs. Pulling _mergeRules off ToCSSVisitor.prototype couples Property to a private visitor implementation and to context.pluginManager being populated in every eval context.

♻️ Proposed cleanup
 import Node from './node.js';
 import Declaration from './declaration.js';
+import mergeRules from './merge-rules.js';
 import Ruleset from './ruleset.js';
-        // TODO: shorten this reference
-        const mergeRules = /** `@type` {{ less: { visitors: { ToCSSVisitor: { prototype: { _mergeRules: (rules: Declaration[]) => void } } } } }} */ (context.pluginManager).less.visitors.ToCSSVisitor.prototype._mergeRules;

Also applies to: 32-33

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/property.js` at line 5, Property currently
reaches into a private visitor via
context.pluginManager/ToCSSVisitor.prototype._mergeRules to get the merge
helper; instead import the exported mergeRules directly from './merge-rules.js'
and use that function in Property (and the other occurrences around lines 32-33)
to avoid coupling to the private visitor and pluginManager. Replace any usage of
ToCSSVisitor.prototype._mergeRules or context.pluginManager._mergeRules with the
imported mergeRules and ensure the import is added at the top of the file.
packages/less/lib/less/tree/color.js (1)

33-39: Prefer forEach over map when not using return values.

Using map() for side effects (populating this.rgb and this.alpha) without returning values triggers a lint warning. Since the mapped values aren't used, forEach is semantically correct.

Suggested fix
-        /** `@type` {RegExpMatchArray} */ (rgb.match(/.{2}/g)).map(function (c, i) {
+        /** `@type` {RegExpMatchArray} */ (rgb.match(/.{2}/g)).forEach(function (c, i) {
             if (i < 3) {
                 self.rgb.push(parseInt(c, 16));
             } else {
                 self.alpha = (parseInt(c, 16)) / 255;
             }
         });

Apply the same change to the short hex branch at lines 43-49.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/color.js` around lines 33 - 39, The code
currently uses Array.prototype.map for side effects when parsing hex RGB:
replace the use of .map on the result of rgb.match(/.{2}/g) with .forEach so you
don't create an unused array; update the block that pushes into self.rgb and
sets self.alpha (the function that calls parseInt(c, 16) and assigns to
self.rgb/self.alpha) to use .forEach, and make the identical change in the
short-hex branch that currently mirrors this logic (the branch that expands
short hex parts and assigns to self.rgb/self.alpha).
packages/less/lib/less/tree/ruleset.js (1)

302-305: Redundant length check can be simplified.

The condition importRules.length || importRules.length === 0 is always true for any non-negative length. This appears to be checking if importRules is array-like.

♻️ Suggested simplification
-                if (importRules && (/** `@type` {Node[]} */ (/** `@type` {unknown} */ (importRules)).length || /** `@type` {Node[]} */ (/** `@type` {unknown} */ (importRules)).length === 0)) {
+                if (importRules && Array.isArray(importRules)) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/ruleset.js` around lines 302 - 305, The
conditional checking importRules is redundant — replace the expression
`importRules && (importRules.length || importRules.length === 0)` with a clear
array check such as `Array.isArray(importRules)` to ensure importRules is
array-like before casting to Node[]; keep the subsequent code using importArr,
rules.splice(i, 1, ...importArr) and i += importArr.length - 1 unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/less/lib/less/tree/call.js`:
- Around line 13-18: Update the JSDoc for the Call constructor so the
currentFileInfo parameter allows undefined: change the `@param` annotation on
currentFileInfo in Call (in packages/less/lib/less/tree/call.js) from `@param`
{FileInfo} currentFileInfo to `@param` {FileInfo | undefined} currentFileInfo to
match usages like new Call('_SELF', [v.value], 0, undefined).

In `@packages/less/lib/less/tree/container.js`:
- Line 86: The assignment unconditionally calls .inherit() on
context.frames[0].functionRegistry which can be undefined; change the code in
container.js (the line assigning this.rules[0].functionRegistry) to guard the
call — only call .inherit() if context.frames[0].functionRegistry exists,
otherwise leave functionRegistry undefined or set a safe fallback; reference the
symbols this.rules[0].functionRegistry and context.frames[0].functionRegistry to
locate and update the logic so it matches how mixin-definition.js treats
functionRegistry as optional.

In `@packages/less/lib/less/tree/declaration.js`:
- Around line 116-119: The error wrapper in Declaration evaluation assumes
fileInfo() exists and calls this.fileInfo().filename, which can throw when
currentFileInfo is undefined; update the logic in the Declaration error handling
(the block that uses getIndex() and fileInfo()) to be null-safe: only set
err.filename if this.fileInfo() returns a non-null object (or
this.currentFileInfo is present), and avoid overwriting an existing
err.filename; keep setting err.index via getIndex() as before but guard fileInfo
access to prevent a secondary TypeError.

In `@packages/less/lib/less/tree/media.js`:
- Line 72: The assignment to RulesetLikeNode.functionRegistry should be guarded
to avoid calling .inherit() on an undefined synthetic frame; check that
context.frames[0] and its functionRegistry exist before calling .inherit() and
only assign the result when present (i.e. if (context.frames[0] &&
context.frames[0].functionRegistry) this.rules[0].functionRegistry =
context.frames[0].functionRegistry.inherit()); ensure you use the same
null-check style as Container.eval to match the codebase.

In `@packages/less/lib/less/tree/nested-at-rule.js`:
- Around line 164-172: The permute method's base case returns arr[0] (a Node[])
while the signature promises Node[][]; fix by returning [arr[0]] in the
arr.length === 1 branch so the method always returns Node[][], or alternatively
if you intend a different shape, widen the return type to allow Node[] |
Node[][] and update the related typedef accordingly (prefer the first fix:
change the base case in permute to return an array containing arr[0]).

In `@packages/less/lib/less/tree/property.js`:
- Around line 15-21: The constructor for Property now sets only _index and
_fileInfo but legacy code in eval() still reads this.index and
this.currentFileInfo.filename, causing a TypeError on missing-property lookups;
update the constructor (constructor(name, index, currentFileInfo)) to preserve
compatibility by also assigning this.index = index and this.currentFileInfo =
currentFileInfo (or ensure eval() uses the new _index/_fileInfo fields and
throws the Less Name error there), so either restore the legacy fields or update
eval()’s throw site to reference the new symbols.

In `@packages/less/lib/less/tree/ruleset.js`:
- Around line 930-932: Remove the duplicated JSDoc type annotation immediately
above the resolvedElements declaration: there are two consecutive "/** `@type`
{(Element | Selector)[]} */" comments; delete one so only a single JSDoc comment
precedes the const resolvedElements = [] declaration (refer to the
resolvedElements variable in ruleset.js).

---

Outside diff comments:
In `@packages/less/lib/less/tree/ruleset.js`:
- Around line 689-710: The createParenthesis function has an off-by-one: it
checks elementsToPak.length === 0 but then uses elementsToPak[0]; change the
condition to elementsToPak.length === 1 so the single-element path constructs
replacementParen = new Paren(elementsToPak[0]) correctly, while the else branch
continues to wrap multiple items into Element and Selector; update the
conditional that currently references elementsToPak.length to === 1 and ensure
no other logic assumes a zero-length array there.

In `@packages/less/lib/less/tree/variable.js`:
- Around line 42-68: The code sets this.evaluating = true but only clears it on
the success path, so exceptions from v.value.eval(context),
Call(...).eval(context), or the throw branch leave the node marked evaluating;
wrap the variable lookup and evaluation logic (the find callback and subsequent
return/throw) in a try/finally (or ensure a finally-like cleanup) so that
this.evaluating is always set back to false, referencing the this.evaluating
flag, the find invocation that calls v.value.eval(context) and Call('_SELF',
[v.value], 0, undefined).eval(context), and ensure the finally executes before
any throw to avoid spurious recursive detection.

---

Duplicate comments:
In `@packages/less/lib/less/tree/atrule.js`:
- Line 202: The forEach callback currently returns the assignment expression
(rules.forEach(rule => rule.merge = false)), which Biome flags as an unintended
return; update the callback to use block syntax so it performs the assignment
without returning a value (e.g., change the arrow callback to a block-body that
sets rule.merge = false) — locate the rules.forEach call in atrule.js where
RulesetLikeNode objects are iterated and replace the concise arrow expression
with a block-bodied callback that executes rule.merge = false;.

In `@packages/less/lib/less/tree/color.js`:
- Around line 51-52: The alpha assignment in the Color constructor uses a falsy
check and overwrites a parsed 0 (fully transparent) with 1; replace the falsy
`||` logic on `this.alpha` with an explicit undefined/null check (e.g., use
nullish coalescing or test for undefined) so that a parsed numeric 0 is
preserved while still defaulting to `a` or 1 when alpha is truly missing; update
the line that sets `this.alpha` in color.js (the assignment using `this.alpha ||
(typeof a === 'number' ? a : 1)`) to use the explicit check.

In `@packages/less/lib/less/tree/nested-at-rule.js`:
- Around line 21-37: The JSDoc typedef for NestableAtRuleThis incorrectly
declares evalNested as returning only Ruleset while the implementation (and
reuse in atrule.js) can return self (a Node) as well; update the typedef in
nested-at-rule.js so evalNested: (context: EvalContext) => Node | Ruleset (or
the correct union type used elsewhere) to match actual return values and prevent
the incorrect narrow signature from leaking to atrule.js and other consumers.

In `@packages/less/lib/less/tree/selector.js`:
- Around line 76-89: The callback passed to Parser.parseNode inside
getElements() uses a plain function so `this` is undefined when invoked, causing
a TypeError when referencing this._fileInfo; change the callback to a bound
function (e.g., use an arrow function or .bind(this)) so it preserves the
surrounding `this`, and ensure the error branch constructs LessError with the
correct this._fileInfo filename; update the callback passed to parseNode (the
anonymous function handling err and result) accordingly to reference
this._fileInfo safely.

---

Nitpick comments:
In `@packages/less/lib/less/tree/color.js`:
- Around line 33-39: The code currently uses Array.prototype.map for side
effects when parsing hex RGB: replace the use of .map on the result of
rgb.match(/.{2}/g) with .forEach so you don't create an unused array; update the
block that pushes into self.rgb and sets self.alpha (the function that calls
parseInt(c, 16) and assigns to self.rgb/self.alpha) to use .forEach, and make
the identical change in the short-hex branch that currently mirrors this logic
(the branch that expands short hex parts and assigns to self.rgb/self.alpha).

In `@packages/less/lib/less/tree/property.js`:
- Line 5: Property currently reaches into a private visitor via
context.pluginManager/ToCSSVisitor.prototype._mergeRules to get the merge
helper; instead import the exported mergeRules directly from './merge-rules.js'
and use that function in Property (and the other occurrences around lines 32-33)
to avoid coupling to the private visitor and pluginManager. Replace any usage of
ToCSSVisitor.prototype._mergeRules or context.pluginManager._mergeRules with the
imported mergeRules and ensure the import is added at the top of the file.

In `@packages/less/lib/less/tree/ruleset.js`:
- Around line 302-305: The conditional checking importRules is redundant —
replace the expression `importRules && (importRules.length || importRules.length
=== 0)` with a clear array check such as `Array.isArray(importRules)` to ensure
importRules is array-like before casting to Node[]; keep the subsequent code
using importArr, rules.splice(i, 1, ...importArr) and i += importArr.length - 1
unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a5a4b651-5cf4-4bb0-bdaf-03b7b1ab4a78

📥 Commits

Reviewing files that changed from the base of the PR and between 0c1a282 and 8b9e255.

📒 Files selected for processing (46)
  • .husky/pre-commit
  • packages/less/lib/less/tree/anonymous.js
  • packages/less/lib/less/tree/assignment.js
  • packages/less/lib/less/tree/atrule-syntax.js
  • packages/less/lib/less/tree/atrule.js
  • packages/less/lib/less/tree/attribute.js
  • packages/less/lib/less/tree/call.js
  • packages/less/lib/less/tree/color.js
  • packages/less/lib/less/tree/combinator.js
  • packages/less/lib/less/tree/comment.js
  • packages/less/lib/less/tree/condition.js
  • packages/less/lib/less/tree/container.js
  • packages/less/lib/less/tree/debug-info.js
  • packages/less/lib/less/tree/declaration.js
  • packages/less/lib/less/tree/detached-ruleset.js
  • packages/less/lib/less/tree/dimension.js
  • packages/less/lib/less/tree/element.js
  • packages/less/lib/less/tree/expression.js
  • packages/less/lib/less/tree/extend.js
  • packages/less/lib/less/tree/import.js
  • packages/less/lib/less/tree/index.js
  • packages/less/lib/less/tree/javascript.js
  • packages/less/lib/less/tree/js-eval-node.js
  • packages/less/lib/less/tree/keyword.js
  • packages/less/lib/less/tree/media.js
  • packages/less/lib/less/tree/merge-rules.js
  • packages/less/lib/less/tree/mixin-call.js
  • packages/less/lib/less/tree/mixin-definition.js
  • packages/less/lib/less/tree/namespace-value.js
  • packages/less/lib/less/tree/negative.js
  • packages/less/lib/less/tree/nested-at-rule.js
  • packages/less/lib/less/tree/node.js
  • packages/less/lib/less/tree/operation.js
  • packages/less/lib/less/tree/paren.js
  • packages/less/lib/less/tree/property.js
  • packages/less/lib/less/tree/query-in-parens.js
  • packages/less/lib/less/tree/quoted.js
  • packages/less/lib/less/tree/ruleset.js
  • packages/less/lib/less/tree/selector.js
  • packages/less/lib/less/tree/unicode-descriptor.js
  • packages/less/lib/less/tree/unit.js
  • packages/less/lib/less/tree/url.js
  • packages/less/lib/less/tree/value.js
  • packages/less/lib/less/tree/variable-call.js
  • packages/less/lib/less/tree/variable.js
  • packages/less/package.json
🚧 Files skipped from review as they are similar to previous changes (13)
  • packages/less/lib/less/tree/merge-rules.js
  • packages/less/lib/less/tree/index.js
  • packages/less/lib/less/tree/assignment.js
  • packages/less/lib/less/tree/combinator.js
  • packages/less/lib/less/tree/atrule-syntax.js
  • packages/less/lib/less/tree/query-in-parens.js
  • packages/less/package.json
  • .husky/pre-commit
  • packages/less/lib/less/tree/js-eval-node.js
  • packages/less/lib/less/tree/unicode-descriptor.js
  • packages/less/lib/less/tree/anonymous.js
  • packages/less/lib/less/tree/url.js
  • packages/less/lib/less/tree/operation.js

Comment thread packages/less/lib/less/tree/call.js Resolved
Comment thread packages/less/lib/less/tree/media.js Resolved
Comment thread packages/less/lib/less/tree/property.js Resolved
Comment thread packages/less/lib/less/tree/ruleset.js Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/less/lib/less/tree/call.js (1)

54-65: ⚠️ Potential issue | 🟠 Major

Always unwind calc state in a finally block.

exitCalc() is skipped if funcCaller.call(...) or any a.eval(context) throws, so context.mathOn / calc nesting can leak out of this node on error paths.

Suggested fix
-        if (funcCaller.isValid()) {
-            try {
-                result = funcCaller.call(this.args);
-                exitCalc();
-            } catch (e) {
+        try {
+            if (funcCaller.isValid()) {
+                try {
+                    result = funcCaller.call(this.args);
+                } catch (e) {
+                    // existing normalization logic
+                    throw e;
+                }
+            }
+
+            if (result !== null && result !== undefined) {
+                // existing result normalization logic
+                return result;
+            }
+
+            const args = this.args.map(a => a.eval(context));
+            return new Call(this.name, args, this.getIndex(), this.fileInfo());
+        } finally {
+            exitCalc();
-            }
-        }
-
-        if (result !== null && result !== undefined) {
-            // existing result normalization logic
-            return result;
         }
-
-        const args = this.args.map(a => a.eval(context));
-        exitCalc();
-
-        return new Call(this.name, args, this.getIndex(), this.fileInfo());

Also applies to: 71-109

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/call.js` around lines 54 - 65, The code currently
toggles context.mathOn and calls context.enterCalc() but doesn't guarantee
context.exitCalc() and restoration of context.mathOn when evaluation throws;
wrap the evaluation sequence that calls a.eval(context) and funcCaller.call(...)
in a try/finally so exit logic always runs: move the existing exitCalc() logic
into a finally block and ensure it always calls context.exitCalc() when
this.calc || context.inCalc and restores context.mathOn to the saved
currentMathContext; apply the same try/finally pattern to the related section
around lines 71-109 that performs similar enter/exit calls.
packages/less/lib/less/tree/mixin-definition.js (1)

128-146: ⚠️ Potential issue | 🟠 Major

Don't evaluate named arguments twice.

This branch calls arg.value.eval(context) once for evaldArguments[j] and again for the Declaration. That can change behavior for non-idempotent expressions and doubles the work for every named argument.

🐛 Reuse the evaluated node
                         if (!evaldArguments[j] && name === params[j].name) {
-                            evaldArguments[j] = arg.value.eval(context);
-                            frame.prependRule(new Declaration(name, arg.value.eval(context)));
+                            const evaluatedArg = arg.value.eval(context);
+                            evaldArguments[j] = evaluatedArg;
+                            frame.prependRule(new Declaration(name, evaluatedArg));
                             isNamedFound = true;
                             break;
                         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/mixin-definition.js` around lines 128 - 146, The
code currently calls arg.value.eval(context) twice for named args (once
assigning to evaldArguments[j] and again when creating the Declaration), which
can double work and break non-idempotent expressions; change the branch in
mixin-definition.js to evaluate arg.value once into a local variable (e.g.,
evaluated = arg.value.eval(context)), assign evaldArguments[j] = evaluated, and
use that same evaluated variable when calling frame.prependRule(new
Declaration(name, ...)) so the evaluated node is reused and the second eval is
removed.
♻️ Duplicate comments (9)
packages/less/lib/less/tree/color.js (1)

51-52: ⚠️ Potential issue | 🟠 Major

Preserve parsed alpha 0 instead of defaulting it away.

Line 52 still uses ||, so a parsed alpha of 0 from 4/8-digit hex is treated as missing and replaced with a or 1. That changes fully transparent colors into opaque ones, which violates the PR’s “no runtime behavior changes” goal.

Suggested fix
-        this.alpha = this.alpha || (typeof a === 'number' ? a : 1);
+        this.alpha = this.alpha === undefined ? (typeof a === 'number' ? a : 1) : this.alpha;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/color.js` around lines 51 - 52, The assignment to
this.alpha uses the || operator which treats a parsed alpha of 0 as falsy and
overwrites it; update the logic in the constructor/initializer (referencing
this.alpha and the local a parameter in color.js) to preserve numeric 0 by using
an explicit existence check (e.g. test typeof this.alpha === 'number' or !=
null) before falling back to a or 1 so fully transparent colors are not coerced
to opaque.
packages/less/lib/less/tree/call.js (1)

13-18: ⚠️ Potential issue | 🟡 Minor

Allow currentFileInfo to be optional in the constructor JSDoc.

Some internal new Call(...) sites pass undefined here, so this annotation is narrower than the actual API and makes later fileInfo() usage look safer than it is.

#!/bin/bash
# Verify current Call constructor usages and look for undefined file info arguments.
sed -n '48,58p' packages/less/lib/less/tree/variable.js
rg -nP "new\s+Call\s*\(" packages/less/lib/less -C1
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/call.js` around lines 13 - 18, The JSDoc for the
Call constructor incorrectly requires currentFileInfo; update the parameter
annotation for currentFileInfo in the Call constructor JSDoc (symbol: Call,
param name: currentFileInfo) to allow undefined (e.g. FileInfo|undefined or
FileInfo|null) so callers that pass undefined are accurately represented and
downstream uses like fileInfo() reflect the possibility of missing data; ensure
the JSDoc matches other call sites that pass undefined.
packages/less/lib/less/tree/property.js (1)

74-79: ⚠️ Potential issue | 🟠 Major

Error path references undefined legacy fields.

The error branch at lines 77-78 reads this.currentFileInfo.filename and this.index, but the constructor (lines 15-22) only sets this._index and this._fileInfo. This will throw a TypeError instead of the intended Less Name error when a property lookup fails.

🐛 Fix to use the correct fields
         } else {
             throw { type: 'Name',
                 message: `Property '${name}' is undefined`,
-                filename: this.currentFileInfo.filename,
-                index: this.index };
+                filename: this.fileInfo().filename,
+                index: this.getIndex() };
         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/property.js` around lines 74 - 79, The error
throw in the Property lookup uses legacy fields this.currentFileInfo.filename
and this.index which are not defined; update the throw to use the actual
instance fields set in the constructor (this._fileInfo.filename and this._index)
so the intended Less Name error is thrown correctly from the property lookup in
property.js.
packages/less/lib/less/tree/declaration.js (1)

115-122: ⚠️ Potential issue | 🟡 Minor

Error handler should guard fileInfo() access.

Line 119 calls this.fileInfo().filename without checking if fileInfo() returns a valid object. Since currentFileInfo is optional in the constructor (line 36), this could replace a real evaluation error with a TypeError when _fileInfo is undefined.

Note: The genCSS error handler (lines 70-71) already uses the safer pattern this._fileInfo && this._fileInfo.filename.

🛡️ Apply the same null-safe pattern
         catch (e) {
             const err = /** `@type` {{ index?: number, filename?: string }} */ (e);
             if (typeof err.index !== 'number') {
                 err.index = this.getIndex();
-                err.filename = this.fileInfo().filename;
+                const fileInfo = this.fileInfo();
+                err.filename = fileInfo && fileInfo.filename;
             }
             throw e;
         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/declaration.js` around lines 115 - 122, The catch
block in declaration.js uses this.fileInfo().filename without null-checking and
can throw if _fileInfo is undefined; change the error handling in the catch of
the relevant function to use a null-safe access (like this._fileInfo &&
this._fileInfo.filename) when assigning err.filename, and only call
this.getIndex() and this._fileInfo.filename if those values exist; update the
catch that currently references this.fileInfo() to mirror the safe pattern used
in genCSS (lines ~70-71) so a real evaluation error isn't replaced by a
TypeError.
packages/less/lib/less/tree/nested-at-rule.js (1)

164-184: ⚠️ Potential issue | 🟡 Minor

permute() base case returns wrong shape.

Line 172 returns arr[0] (a Node[]) but the method signature promises Node[][]. The double cast /** @type{Node[][]} */ (/**@type {unknown} */ (arr[0])) hides this mismatch at compile time, but callers expecting Node[][] may receive a flat array.

🔧 Fix to maintain the Node[][] contract
         } else if (arr.length === 1) {
-            return /** `@type` {Node[][]} */ (/** `@type` {unknown} */ (arr[0]));
+            return arr[0].map(item => [item]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/nested-at-rule.js` around lines 164 - 184, The
permute() base case returns a Node[] instead of the promised Node[][]; in the
branch where arr.length === 1 return an array containing arr[0] (i.e. return
[arr[0]]) so the function always returns Node[][], and remove the unnecessary
double-cast; keep the existing behavior for the empty and multi-element branches
unchanged.
packages/less/lib/less/tree/mixin-call.js (1)

226-229: ⚠️ Potential issue | 🟡 Minor

Preserve nested Less error metadata when rethrowing.

This wrapper keeps the message and stack, but it drops type and any other structured fields from inner Less errors. Failures bubbling out of evalCall() get flattened at the mixin call site.

💡 Suggested fix
                         } catch (e) {
-                            const err = /** `@type` {{ message?: string, stack?: string }} */ (e);
-                            throw { message: err.message, index: this.getIndex(), filename: this.fileInfo().filename, stack: err.stack };
+                            const err = (e && typeof e === 'object') ? e : { message: String(e) };
+                            throw {
+                                ...err,
+                                message: /** `@type` {{ message?: string }} */ (err).message ?? String(e),
+                                index: this.getIndex(),
+                                filename: this.fileInfo().filename,
+                                stack: /** `@type` {{ stack?: string }} */ (err).stack
+                            };
                         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/mixin-call.js` around lines 226 - 229, The catch
block in mixin-call.js currently rethrows a new object with only message/stack,
dropping other Less error fields; update the rethrow to preserve all properties
from the original error (e.g., using Object.assign or object spread) and then
set/override index and filename with this.getIndex() and
this.fileInfo().filename so nested Less error metadata like type is retained
(keep the existing use-site: the catch around evalCall() in the
MixinCall/evalCall code path).
packages/less/lib/less/tree/ruleset.js (1)

146-153: ⚠️ Potential issue | 🟠 Major

Propagate selector reparse failures here.

If interpolation produces an invalid selector, this callback leaves selectors on the pre-parse AST and evaluation continues. That hides the parse failure instead of surfacing a Less error.

💡 Suggested fix
                     toParseSelectors.join(','),
                     ['selectors'],
                     function(/** `@type` {Error | null} */ err, /** `@type` {Node[]} */ result) {
+                        if (err) {
+                            throw err;
+                        }
                         if (result) {
                             selectors = /** `@type` {Selector[]} */ (utils.flattenArray(result));
                         }
                     });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/ruleset.js` around lines 146 - 153, The callback
passed to Parser.parseNode in ruleset.js ignores the err parameter and leaves
selectors unchanged on parse failure; update the anonymous callback in the
parseNode call so that if err is non-null it immediately propagates the failure
(e.g., throw the error or rethrow as a Less parsing error) instead of silently
continuing, otherwise proceed to set selectors = utils.flattenArray(result) as
before; ensure this change references the same Parser.new(...).parseNode
callback and the selectors variable so invalid selector reparses surface as a
Less error.
packages/less/lib/less/tree/container.js (1)

86-86: ⚠️ Potential issue | 🟠 Major

Guard the inherited function registry here.

The functionRegistry on context.frames[0] may be undefined in synthetic frames (as handled in mixin-definition.js). Calling .inherit() unconditionally can throw.

💡 Suggested fix
-        this.rules[0].functionRegistry = /** `@type` {RulesetWithExtras} */ (context.frames[0]).functionRegistry.inherit();
+        const parentRegistry = /** `@type` {RulesetWithExtras} */ (context.frames[0]).functionRegistry;
+        this.rules[0].functionRegistry = parentRegistry ? parentRegistry.inherit() : undefined;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/container.js` at line 86, The assignment to
this.rules[0].functionRegistry calls .inherit() on
context.frames[0].functionRegistry without checking for existence and can throw
for synthetic frames; update the code in container.js to first check whether
context.frames[0].functionRegistry is defined and only call .inherit() when
present (otherwise set this.rules[0].functionRegistry to a safe fallback such as
undefined or a new/empty registry), mirroring the guarding logic used in
mixin-definition.js so .inherit() is never invoked on an undefined value.
packages/less/lib/less/tree/media.js (1)

72-72: ⚠️ Potential issue | 🟠 Major

Guard the inherited function registry here too.

Same issue as Container.eval: functionRegistry is treated as optional elsewhere in the tree, so .inherit() can throw on undefined.

💡 Suggested fix
-        /** `@type` {RulesetLikeNode} */ (this.rules[0]).functionRegistry = /** `@type` {RulesetLikeNode} */ (context.frames[0]).functionRegistry.inherit();
+        const parentRegistry = /** `@type` {RulesetLikeNode} */ (context.frames[0]).functionRegistry;
+        /** `@type` {RulesetLikeNode} */ (this.rules[0]).functionRegistry = parentRegistry ? parentRegistry.inherit() : undefined;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/media.js` at line 72, The assignment to
functionRegistry calls .inherit() without checking existence and can throw if
context.frames[0].functionRegistry is undefined; update the code in media.js so
that when setting /** `@type` {RulesetLikeNode} */
(this.rules[0]).functionRegistry you first check whether
context.frames[0].functionRegistry exists (e.g., conditional or optional
chaining) and only call .inherit() when present, otherwise leave
functionRegistry undefined (matching how Container.eval guards it).
🧹 Nitpick comments (2)
packages/less/lib/less/tree/variable.js (1)

71-82: Consider extracting the shared find() helper.

The find(obj, fun) method is identical to the one in Property class. While not blocking, extracting this to a shared utility or the base Node class would reduce duplication.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/variable.js` around lines 71 - 82, The find(obj,
fun) implementation is duplicated in Variable and Property; extract it to a
shared helper or the base Node class (e.g., add Node.find(obj, fun) or a util
function findInArray) and replace the per-class method with a call to that
shared implementation. Update Variable.find and Property.find to delegate to the
new Node.find / util function (preserve signature and behavior: iterate obj,
call fun with obj[i] and return first truthy result or null). Ensure tests still
pass and remove the duplicated method bodies from both classes.
packages/less/lib/less/tree/import.js (1)

277-293: Potential null dereference when accessing nested feature value.

Line 280 casts featureValue[0].value to Node[] and reassigns to featureValue, but there's no guard ensuring featureValue[0].value is actually an array before the subsequent Array.isArray(featureValue) check on line 281. If featureValue[0].value is undefined or a non-array, the cast silently proceeds and the array check fails gracefully, but this relies on implicit behavior.

Consider adding a truthiness check before the cast for clarity:

♻️ Suggested improvement
             if (Array.isArray(featureValue) && featureValue.length >= 1) {
-                featureValue = /** `@type` {Node[]} */ (featureValue[0].value);
-                if (Array.isArray(featureValue) && featureValue.length >= 2) {
+                const innerValue = featureValue[0].value;
+                if (Array.isArray(innerValue) && innerValue.length >= 2) {
+                    featureValue = innerValue;
                     const isLayer = featureValue[0].type === 'Keyword' && featureValue[0].value === 'layer'
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/import.js` around lines 277 - 293, The code may
dereference featureValue[0].value without ensuring it exists; before
casting/reassigning featureValue to featureValue[0].value in the import handling
block (where this.features and featureValue are used), first check that
featureValue[0] is truthy and that Array.isArray(featureValue[0].value) (or
featureValue[0].value != null && Array.isArray(...)) is true; only then reassign
featureValue = featureValue[0].value and proceed to the later length/type checks
and Expression creation (references: this.features, featureValue, Expression,
this.css).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/less/lib/less/tree/atrule.js`:
- Around line 86-95: The constructor currently calls setParent(selectors, this)
on a detached local so newly-attached child nodes remain unparented; instead
parent the actual child properties: after creating/assigning this.declarations
in the simple-block path call this.setParent(this.declarations, this) (or this
if declarations are nodes), and after you replace this.rules[0].selectors with a
new Selector list call this.setParent(this.rules[0].selectors, this.rules[0]) so
the fresh selector list is parented to its ruleset; keep the existing
this.setParent(this.rules, this) for the rules array itself.

In `@packages/less/lib/less/tree/call.js`:
- Around line 75-86: Replace the unsafe direct hasOwnProperty calls on the
caught error object with safe calls using Object.prototype.hasOwnProperty.call;
specifically in the catch block in packages/less/lib/less/tree/call.js, change
the condition that currently uses (e).hasOwnProperty('line') and
(e).hasOwnProperty('column') to Object.prototype.hasOwnProperty.call(e, 'line')
and Object.prototype.hasOwnProperty.call(e, 'column') so null/undefined or
objects created with Object.create(null) don't throw; leave the rest of the
thrown error construction (references to this.name, this.getIndex(),
this.fileInfo(), and e.message/lineNumber/columnNumber) unchanged.

In `@packages/less/lib/less/tree/node.js`:
- Around line 57-61: Node.accept currently forwards this.value (and other child
fields) directly to TreeVisitor.visit but the new TreeVisitor.visit signature
expects Node values; update Node.accept to guard before calling visitor.visit:
only call visitor.visit(child) when the child is a Node (e.g., check instanceof
Node or child && typeof child.accept === 'function'), call visitor.visitArray
for arrays (use visitor.visitArray(this.value, nonReplacing) when value is an
array), and otherwise leave primitive children (strings, numbers) unchanged;
apply the same guarded logic to the other child-visiting code paths referenced
(e.g., the later block around the other accept usage) so comment.js and similar
subclasses no longer pass primitives into TreeVisitor.visit.

In `@packages/less/lib/less/tree/selector.js`:
- Around line 13-20: The JSDoc for the constructor parameter currently allows
"(Element | Selector)[] | string" even though getElements() always yields
Element[] and the class uses Element-only members; update the JSDoc for the
"elements" (aka "els") parameter to be Element[] (or document that incoming
Selector[] are normalized to Element[]), and make the same narrowing change for
the other related JSDoc block (the second occurrence around lines 68–91) so that
`@ts-check` reflects the actual runtime shape; reference getElements(), Selector
(class), and the constructor/els parameter when making the edits.

---

Outside diff comments:
In `@packages/less/lib/less/tree/call.js`:
- Around line 54-65: The code currently toggles context.mathOn and calls
context.enterCalc() but doesn't guarantee context.exitCalc() and restoration of
context.mathOn when evaluation throws; wrap the evaluation sequence that calls
a.eval(context) and funcCaller.call(...) in a try/finally so exit logic always
runs: move the existing exitCalc() logic into a finally block and ensure it
always calls context.exitCalc() when this.calc || context.inCalc and restores
context.mathOn to the saved currentMathContext; apply the same try/finally
pattern to the related section around lines 71-109 that performs similar
enter/exit calls.

In `@packages/less/lib/less/tree/mixin-definition.js`:
- Around line 128-146: The code currently calls arg.value.eval(context) twice
for named args (once assigning to evaldArguments[j] and again when creating the
Declaration), which can double work and break non-idempotent expressions; change
the branch in mixin-definition.js to evaluate arg.value once into a local
variable (e.g., evaluated = arg.value.eval(context)), assign evaldArguments[j] =
evaluated, and use that same evaluated variable when calling
frame.prependRule(new Declaration(name, ...)) so the evaluated node is reused
and the second eval is removed.

---

Duplicate comments:
In `@packages/less/lib/less/tree/call.js`:
- Around line 13-18: The JSDoc for the Call constructor incorrectly requires
currentFileInfo; update the parameter annotation for currentFileInfo in the Call
constructor JSDoc (symbol: Call, param name: currentFileInfo) to allow undefined
(e.g. FileInfo|undefined or FileInfo|null) so callers that pass undefined are
accurately represented and downstream uses like fileInfo() reflect the
possibility of missing data; ensure the JSDoc matches other call sites that pass
undefined.

In `@packages/less/lib/less/tree/color.js`:
- Around line 51-52: The assignment to this.alpha uses the || operator which
treats a parsed alpha of 0 as falsy and overwrites it; update the logic in the
constructor/initializer (referencing this.alpha and the local a parameter in
color.js) to preserve numeric 0 by using an explicit existence check (e.g. test
typeof this.alpha === 'number' or != null) before falling back to a or 1 so
fully transparent colors are not coerced to opaque.

In `@packages/less/lib/less/tree/container.js`:
- Line 86: The assignment to this.rules[0].functionRegistry calls .inherit() on
context.frames[0].functionRegistry without checking for existence and can throw
for synthetic frames; update the code in container.js to first check whether
context.frames[0].functionRegistry is defined and only call .inherit() when
present (otherwise set this.rules[0].functionRegistry to a safe fallback such as
undefined or a new/empty registry), mirroring the guarding logic used in
mixin-definition.js so .inherit() is never invoked on an undefined value.

In `@packages/less/lib/less/tree/declaration.js`:
- Around line 115-122: The catch block in declaration.js uses
this.fileInfo().filename without null-checking and can throw if _fileInfo is
undefined; change the error handling in the catch of the relevant function to
use a null-safe access (like this._fileInfo && this._fileInfo.filename) when
assigning err.filename, and only call this.getIndex() and
this._fileInfo.filename if those values exist; update the catch that currently
references this.fileInfo() to mirror the safe pattern used in genCSS (lines
~70-71) so a real evaluation error isn't replaced by a TypeError.

In `@packages/less/lib/less/tree/media.js`:
- Line 72: The assignment to functionRegistry calls .inherit() without checking
existence and can throw if context.frames[0].functionRegistry is undefined;
update the code in media.js so that when setting /** `@type` {RulesetLikeNode} */
(this.rules[0]).functionRegistry you first check whether
context.frames[0].functionRegistry exists (e.g., conditional or optional
chaining) and only call .inherit() when present, otherwise leave
functionRegistry undefined (matching how Container.eval guards it).

In `@packages/less/lib/less/tree/mixin-call.js`:
- Around line 226-229: The catch block in mixin-call.js currently rethrows a new
object with only message/stack, dropping other Less error fields; update the
rethrow to preserve all properties from the original error (e.g., using
Object.assign or object spread) and then set/override index and filename with
this.getIndex() and this.fileInfo().filename so nested Less error metadata like
type is retained (keep the existing use-site: the catch around evalCall() in the
MixinCall/evalCall code path).

In `@packages/less/lib/less/tree/nested-at-rule.js`:
- Around line 164-184: The permute() base case returns a Node[] instead of the
promised Node[][]; in the branch where arr.length === 1 return an array
containing arr[0] (i.e. return [arr[0]]) so the function always returns
Node[][], and remove the unnecessary double-cast; keep the existing behavior for
the empty and multi-element branches unchanged.

In `@packages/less/lib/less/tree/property.js`:
- Around line 74-79: The error throw in the Property lookup uses legacy fields
this.currentFileInfo.filename and this.index which are not defined; update the
throw to use the actual instance fields set in the constructor
(this._fileInfo.filename and this._index) so the intended Less Name error is
thrown correctly from the property lookup in property.js.

In `@packages/less/lib/less/tree/ruleset.js`:
- Around line 146-153: The callback passed to Parser.parseNode in ruleset.js
ignores the err parameter and leaves selectors unchanged on parse failure;
update the anonymous callback in the parseNode call so that if err is non-null
it immediately propagates the failure (e.g., throw the error or rethrow as a
Less parsing error) instead of silently continuing, otherwise proceed to set
selectors = utils.flattenArray(result) as before; ensure this change references
the same Parser.new(...).parseNode callback and the selectors variable so
invalid selector reparses surface as a Less error.

---

Nitpick comments:
In `@packages/less/lib/less/tree/import.js`:
- Around line 277-293: The code may dereference featureValue[0].value without
ensuring it exists; before casting/reassigning featureValue to
featureValue[0].value in the import handling block (where this.features and
featureValue are used), first check that featureValue[0] is truthy and that
Array.isArray(featureValue[0].value) (or featureValue[0].value != null &&
Array.isArray(...)) is true; only then reassign featureValue =
featureValue[0].value and proceed to the later length/type checks and Expression
creation (references: this.features, featureValue, Expression, this.css).

In `@packages/less/lib/less/tree/variable.js`:
- Around line 71-82: The find(obj, fun) implementation is duplicated in Variable
and Property; extract it to a shared helper or the base Node class (e.g., add
Node.find(obj, fun) or a util function findInArray) and replace the per-class
method with a call to that shared implementation. Update Variable.find and
Property.find to delegate to the new Node.find / util function (preserve
signature and behavior: iterate obj, call fun with obj[i] and return first
truthy result or null). Ensure tests still pass and remove the duplicated method
bodies from both classes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ce242e2e-442a-47d8-b17c-6afa84bfd635

📥 Commits

Reviewing files that changed from the base of the PR and between 8b9e255 and d0eb430.

📒 Files selected for processing (46)
  • .husky/pre-commit
  • packages/less/lib/less/tree/anonymous.js
  • packages/less/lib/less/tree/assignment.js
  • packages/less/lib/less/tree/atrule-syntax.js
  • packages/less/lib/less/tree/atrule.js
  • packages/less/lib/less/tree/attribute.js
  • packages/less/lib/less/tree/call.js
  • packages/less/lib/less/tree/color.js
  • packages/less/lib/less/tree/combinator.js
  • packages/less/lib/less/tree/comment.js
  • packages/less/lib/less/tree/condition.js
  • packages/less/lib/less/tree/container.js
  • packages/less/lib/less/tree/debug-info.js
  • packages/less/lib/less/tree/declaration.js
  • packages/less/lib/less/tree/detached-ruleset.js
  • packages/less/lib/less/tree/dimension.js
  • packages/less/lib/less/tree/element.js
  • packages/less/lib/less/tree/expression.js
  • packages/less/lib/less/tree/extend.js
  • packages/less/lib/less/tree/import.js
  • packages/less/lib/less/tree/index.js
  • packages/less/lib/less/tree/javascript.js
  • packages/less/lib/less/tree/js-eval-node.js
  • packages/less/lib/less/tree/keyword.js
  • packages/less/lib/less/tree/media.js
  • packages/less/lib/less/tree/merge-rules.js
  • packages/less/lib/less/tree/mixin-call.js
  • packages/less/lib/less/tree/mixin-definition.js
  • packages/less/lib/less/tree/namespace-value.js
  • packages/less/lib/less/tree/negative.js
  • packages/less/lib/less/tree/nested-at-rule.js
  • packages/less/lib/less/tree/node.js
  • packages/less/lib/less/tree/operation.js
  • packages/less/lib/less/tree/paren.js
  • packages/less/lib/less/tree/property.js
  • packages/less/lib/less/tree/query-in-parens.js
  • packages/less/lib/less/tree/quoted.js
  • packages/less/lib/less/tree/ruleset.js
  • packages/less/lib/less/tree/selector.js
  • packages/less/lib/less/tree/unicode-descriptor.js
  • packages/less/lib/less/tree/unit.js
  • packages/less/lib/less/tree/url.js
  • packages/less/lib/less/tree/value.js
  • packages/less/lib/less/tree/variable-call.js
  • packages/less/lib/less/tree/variable.js
  • packages/less/package.json
🚧 Files skipped from review as they are similar to previous changes (12)
  • packages/less/lib/less/tree/variable-call.js
  • packages/less/lib/less/tree/atrule-syntax.js
  • packages/less/lib/less/tree/assignment.js
  • packages/less/lib/less/tree/operation.js
  • packages/less/lib/less/tree/detached-ruleset.js
  • packages/less/package.json
  • packages/less/lib/less/tree/paren.js
  • packages/less/lib/less/tree/condition.js
  • packages/less/lib/less/tree/debug-info.js
  • .husky/pre-commit
  • packages/less/lib/less/tree/index.js
  • packages/less/lib/less/tree/javascript.js

Comment thread packages/less/lib/less/tree/atrule.js Resolved
Comment thread packages/less/lib/less/tree/call.js Resolved
Comment thread packages/less/lib/less/tree/node.js Resolved
Comment thread packages/less/lib/less/tree/selector.js Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/less/lib/less/tree/ruleset.js (1)

694-710: ⚠️ Potential issue | 🔴 Critical

Bug: Accessing elementsToPak[0] when elementsToPak.length === 0 yields undefined.

The condition at line 694 checks for an empty array (elementsToPak.length === 0) but then attempts to access elementsToPak[0], which will be undefined. This passes undefined to the Paren constructor, causing a runtime error.

The condition should be === 1 to handle the single-element case (unwrapping it directly), with the else branch handling multiple elements (wrapping them in a Selector). When the array is truly empty, no valid Paren can be constructed.

🐛 Proposed fix
         function createParenthesis(elementsToPak, originalElement) {
             /** `@type` {Paren} */
             let replacementParen;
             /** `@type` {number} */
             let j;
-            if (elementsToPak.length === 0) {
+            if (elementsToPak.length === 1) {
                 replacementParen = new Paren(elementsToPak[0]);
             } else {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/ruleset.js` around lines 694 - 710, The current
code creates a Paren with elementsToPak[0] when elementsToPak.length === 0
(producing undefined); change the branching so that if elementsToPak.length ===
1 you construct replacementParen = new Paren(elementsToPak[0]), if
elementsToPak.length > 1 you build insideParent with Element(...) and do
replacementParen = new Paren(new Selector(insideParent)), and if
elementsToPak.length === 0 return null (or otherwise bail out) instead of
attempting to construct a Paren; references: elementsToPak, Paren, Selector,
Element, originalElement.
♻️ Duplicate comments (1)
packages/less/lib/less/tree/ruleset.js (1)

146-154: ⚠️ Potential issue | 🟠 Major

Handle parseNode errors in selector reparsing.

The callback at line 149 receives an err parameter but doesn't handle it. If variable interpolation produces invalid selector syntax, the error is silently ignored and the selectors array retains its unevaluated state, allowing malformed selectors to proceed to code generation.

Other parseNode invocations in the codebase consistently handle errors: selector.js throws, and transformDeclaration in the same file marks as parsed on error. This callback should follow the same pattern.

Proposed fix
                 new (/** `@type` {new (...args: [EvalContext, object, FileInfo, number]) => { parseNode: Function }} */ (/** `@type` {unknown} */ (Parser)))(context, /** `@type` {{ context: EvalContext, importManager: object }} */ (this.parse).importManager, selectorFileInfo, startingIndex).parseNode(
                     toParseSelectors.join(','),
                     ['selectors'],
                     function(/** `@type` {Error | null} */ err, /** `@type` {Node[]} */ result) {
+                        if (err) {
+                            throw err;
+                        }
                         if (result) {
                             selectors = /** `@type` {Selector[]} */ (utils.flattenArray(result));
                         }
                     });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/ruleset.js` around lines 146 - 154, The parseNode
callback in ruleset.js ignores the err parameter, allowing invalid selectors
through; update the anonymous callback passed to Parser(...).parseNode so that
if err is truthy it is propagated (throw the error) instead of silently
continuing—locate the parseNode call inside the Ruleset reparse branch (the
callback that currently sets selectors = utils.flattenArray(result)) and add an
early err check that throws the received Error to match selector.js behavior.
🧹 Nitpick comments (2)
packages/less/lib/less/tree/ruleset.js (2)

302-305: Consider using Array.isArray() for clarity.

The condition (importRules.length || importRules.length === 0) is a verbose way to check if the result is an array. Using Array.isArray(importRules) would be more idiomatic and clearer.

♻️ Suggested simplification
-                if (importRules && (/** `@type` {Node[]} */ (/** `@type` {unknown} */ (importRules)).length || /** `@type` {Node[]} */ (/** `@type` {unknown} */ (importRules)).length === 0)) {
-                    const importArr = /** `@type` {Node[]} */ (/** `@type` {unknown} */ (importRules));
+                if (importRules && Array.isArray(importRules)) {
+                    const importArr = /** `@type` {Node[]} */ (importRules);
                     rules.splice(i, 1, ...importArr);
                     i += importArr.length - 1;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/ruleset.js` around lines 302 - 305, The current
condition checking importRules uses a verbose length check; update the if
statement to use Array.isArray(importRules) for clarity and intent (keep the
existing type casts around importRules). Locate the block handling importRules
in ruleset.js (the code that does rules.splice(i, 1, ...importArr) and adjusts i
by importArr.length - 1) and replace the combined length check with
Array.isArray(importRules), ensuring importArr remains the same casted Node[]
and the splice and i arithmetic are unchanged.

429-446: Type mismatch: decl.parsed stores boolean but cast to Node.

The property decl.parsed appears to store a boolean value (true) but is cast to Node via /** @type{Node} */ (/**@type {unknown} */ (true)). This suggests a type definition mismatch in the underlying Declaration type where parsed should be typed as boolean rather than Node.

This is pre-existing behavior and doesn't introduce bugs, but consider correcting the type definition if feasible.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/lib/less/tree/ruleset.js` around lines 429 - 446, The code
incorrectly casts boolean flags to Node (see decl.parsed assignments and the
JSDoc cast /** `@type` {Node} */ (/** `@type` {unknown} */ (true))); update the
Declaration type so parsed is boolean (not Node) and replace these casts with
boolean-typed annotations or plain assignments (adjust any other occurrences
where decl.parsed is treated as a Node), e.g., change the
Declaration/Declaration & { parsed?: ... } JSDoc to parsed?: boolean and remove
the /** `@type` {Node} */ casts around true in the parseNode callback and the else
branch so decl.parsed is assigned a boolean consistently.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@packages/less/lib/less/tree/ruleset.js`:
- Around line 694-710: The current code creates a Paren with elementsToPak[0]
when elementsToPak.length === 0 (producing undefined); change the branching so
that if elementsToPak.length === 1 you construct replacementParen = new
Paren(elementsToPak[0]), if elementsToPak.length > 1 you build insideParent with
Element(...) and do replacementParen = new Paren(new Selector(insideParent)),
and if elementsToPak.length === 0 return null (or otherwise bail out) instead of
attempting to construct a Paren; references: elementsToPak, Paren, Selector,
Element, originalElement.

---

Duplicate comments:
In `@packages/less/lib/less/tree/ruleset.js`:
- Around line 146-154: The parseNode callback in ruleset.js ignores the err
parameter, allowing invalid selectors through; update the anonymous callback
passed to Parser(...).parseNode so that if err is truthy it is propagated (throw
the error) instead of silently continuing—locate the parseNode call inside the
Ruleset reparse branch (the callback that currently sets selectors =
utils.flattenArray(result)) and add an early err check that throws the received
Error to match selector.js behavior.

---

Nitpick comments:
In `@packages/less/lib/less/tree/ruleset.js`:
- Around line 302-305: The current condition checking importRules uses a verbose
length check; update the if statement to use Array.isArray(importRules) for
clarity and intent (keep the existing type casts around importRules). Locate the
block handling importRules in ruleset.js (the code that does rules.splice(i, 1,
...importArr) and adjusts i by importArr.length - 1) and replace the combined
length check with Array.isArray(importRules), ensuring importArr remains the
same casted Node[] and the splice and i arithmetic are unchanged.
- Around line 429-446: The code incorrectly casts boolean flags to Node (see
decl.parsed assignments and the JSDoc cast /** `@type` {Node} */ (/** `@type`
{unknown} */ (true))); update the Declaration type so parsed is boolean (not
Node) and replace these casts with boolean-typed annotations or plain
assignments (adjust any other occurrences where decl.parsed is treated as a
Node), e.g., change the Declaration/Declaration & { parsed?: ... } JSDoc to
parsed?: boolean and remove the /** `@type` {Node} */ casts around true in the
parseNode callback and the else branch so decl.parsed is assigned a boolean
consistently.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 28373fb7-de66-4675-9427-d45bf260a925

📥 Commits

Reviewing files that changed from the base of the PR and between d0eb430 and 68959fd.

📒 Files selected for processing (1)
  • packages/less/lib/less/tree/ruleset.js

@matthew-dean
matthew-dean merged commit 784dfa9 into less:master Mar 10, 2026
7 checks passed
matthew-dean added a commit to matthew-dean/less.js that referenced this pull request Jul 29, 2026
* fix(issue#4339): limit whitespace check

* Fix issue less#4339 by limiting the whitespace check for the deprecation
  notice to not produce false positives.

* fix(issue#4339): correct deprecation notice

* Correct deprecation notice for issue less#4339.

* Some updated tests for Less v5

* Update various acceptance tests for new parser

* Lots of v5 syntax tweaks

* Unit test updates for v5 - atrules

* v5 updates in test expectations

* Extend stylesheet changes

* fix:(issue#4397): container query variable names

* Fix for issue less#4397 container query with variable names like
  @container @foo () {}.

* Update unit tests to Less v5 engine

* Rebaseline test-data fixtures and move removed legacy JavaScript cases.

This updates expected outputs for current behavior and relocates removed inline-JavaScript and IE filter fixtures into explicit legacy/REMOVED folders to preserve historical references.

* Rebaseline import/media fixtures and skip alpha pre-commit test gate.

This updates import/media fixture expectations and moves the previous media v5 snapshot into legacy while keeping current output at media.css, and bypasses pre-commit verification on the alpha branch during broad migration work.

* test-data: update mixin fixture baselines with legacy snapshots

Capture accepted fixture output updates for mixin guard/default ordering and mixin output parity while preserving prior snapshots under legacy paths for traceability.

* Update parse-interpolation fixtures for selector capture semantics.

This removes the invalid quoted ampersand merge-template case from unit output expectations and moves it into tests-error/eval with an explicit invalid merge-template error fixture.

* Add nesting fixture variants (legacy, uncollapsed, styles.config)

* fix(test-data): update import-reference expected CSS for jess compat

Update expected output to match jess's collapseNesting behavior:
- Unwrap single-item :is() wrappers (.visible instead of :is(.visible))
- Simplify extend selectors (.visible + .visible instead of :is() form)
- Add .b { color: green; } from bare & { } (matches lessc output)

* fix(test-data): update extract-and-length expected CSS for @arguments semantics

BREAKING: @arguments no longer flattens Sequence arguments.
Passing .mixin(a b c d) to (...) gives @arguments length 1 (one Sequence),
not 4 (individual items). Previous expected output saved to legacy/.

* feat(benchmark): add historical benchmark suite for Less v2.0-v4.4

Comprehensive benchmark harness that tests every major/minor Less release
using git worktrees for isolation and fnm for Node version management.

- benchmark.less: enhanced with extend, guards, property merging, detached
  rulesets, complex nesting, color functions, loops, and more
- benchmark-v3.less: v3.6+ features (if, boolean, property lookups)
- benchmark-v37.less: v3.7+ features (each with lists/maps)
- benchmark-v39.less: v3.9+ features (range for columns/spacing)
- benchmark-runner.js: portable runner with ESM interop for v4.x
- run-historical.sh: orchestrator with per-system result tracking

Results organized as:
  results/latest/{system-id}.json   - most recent per system
  results/runs/{date}_{system-id}.json - historical archive

* feat(deprecation): add deprecation warnings for features removed in Less 5.x

New deprecation infrastructure with automatic repetition limiting (max 5 per type):
- deprecation.js: registry of deprecation IDs with descriptions
- Parser warn() accepts deprecation IDs for categorized warnings
- --quiet-deprecations: suppress only deprecation warnings (keeps other warnings)

New deprecation warnings for features being removed in 5.x:
- js-eval: inline JavaScript backtick expressions
- at-plugin: @plugin directive

Existing warnings now tagged with stable IDs:
- mixin-call-no-parens, mixin-call-whitespace, dot-slash-operator
- variable-in-unknown-value, property-in-unknown-value

CLI deprecation notices for: --js, --line-numbers, --math=always

* feat(benchmark): add historical benchmark suite with per-system result tracking

Results organized as:
  results/latest/{system-id}.json  - most recent per system
  results/runs/{date}_{system-id}.json - historical archive (gitignored)

* fix(benchmark): don't path.resolve bare package names in benchmark-runner

path.resolve('less') turns the package name into an absolute filesystem
path, preventing Node's package resolution from finding npm-installed
versions. Only resolve relative paths starting with '.'.

* fix(benchmark): use coefficient of variation instead of range for variance_pct

variance_pct was computing (max-min)/avg which is range-over-mean.
Now uses stddev/avg (coefficient of variation) which is a proper
variability statistic.

* fix(benchmark): use timestamp instead of date for run filenames

Prevents same-day runs from overwriting each other in the runs/ archive.

* fix(cli): queue deprecation warnings until after arg parsing

Deprecation warnings from flags like --js, --line-numbers, and
--math=always were printed immediately during arg parsing, so
--quiet-deprecations only worked if it appeared before the deprecated
flag. Now all CLI deprecation messages are queued and flushed after
parsing completes, respecting --silent, --quiet, and
--quiet-deprecations regardless of flag order.

* Remove duplicate length check from expression.genCSS() (less#4327)

Follows-up 53f84f0, which started the conditional
with a check for `i + 1 < this.value.length`, which is the same
as the parent block.

* Remove unused `parsers.entities.propertyCurly()` (less#4271)

Follows-up a38f8a1, which introduced
this as part of implementing property accessors. The method was not
used there, and hasn't been used elsewhere since then either.

Ref less#3163.

* Remove redundant return from `parsers.blockRuleset()` (less#4265)

* chore: replace deprecated String.prototype.substr() (less#3702)

.substr() is deprecated so we replace it with .slice() which works similarily but isn't deprecated

Signed-off-by: Tobias Speicher <[email protected]>

* Handle the lack of the optional dependencies (less#3791)

* Handle optional dependencies

* Handle optional dependency image-size

* remove phantom stuff (less#3782)

* remove phantom stuff

* lint fix

* use deep clone

* fixed bug in import subpath module (less#4236)

* fix(issue#4354): unknown at-rule expression commas (less#4389)

* Fix issue less#4354 unknown at-rule expressions should not have commas in
  a keyword list.
* Add some additional layer at-rule tests.

* chore: update README.md copyright (less#4386)

* Update README.md copyright year.

* Fix no-prototype-builtins issues in Ruleset and ToCSSVisitor (less#4404)

Co-authored-by: Timo Tijhof <[email protected]>

* chore: add test for number with underscore parsing (less#4406)

In Less.js 2.6.0, parsing of dimensions changed so that `5_large`
is seen as one value, instead of as a list containing "5" and "_large".

In updating the Less.php port, we forgot to consider this change
because none of the Less.js 3.13 tests seem to cover this behavior.

Follows-up less#2485.

This adds the test case from less#2462,
as inpired by downstream https://gerrit.wikimedia.org/r/1197310.

Co-authored-by: Timo Tijhof <[email protected]>

* fix(less#4331): exclude CSS at-rule keywords from declarationCall parsing (less#4407)

* fix(less#4331): exclude CSS at-rule keywords from declarationCall parsing

* fix(less#4331): normalize spacing after CSS at-rule keywords in media queries

When `and`, `or`, `not`, or `only` keywords appear without a space
before `(` in media queries, ensure spacing is added in the output
to produce valid CSS.

* fix(less#4358): resolve parent selectors in comma-separated pseudo-selector lists (less#4408)

* refactor: code quality cleanup for container queries and related code (less#4409)

* fix: correct import and error handling in style() function

- Fix incorrect import: `Anonymous` was imported from '../tree/variable'
  instead of '../tree/anonymous' (worked by accident since Variable
  was imported on the line above)
- Simplify switch/case with single case 0 to a plain if statement
- Add explanatory comment to the catch block documenting why it exists
  (CSS pass-through for @container style() queries)

* refactor: remove dead boolean logic in evalRoot()

- Remove `allAmpersands` variable that was initialized to false and
  never set to true, making it dead code
- Replace string-based ampersand detection (genCSS + regex) with
  direct element value checks, avoiding unnecessary AST-to-string
  conversion
- Simplify boolean conditions that referenced the dead variable

* fix: add missing parserInput.forget() in colorOperand

The colorOperand parser rule called parserInput.save() but only called
restore() on failure, missing the forget() call on the success path.

* refactor: QueryInParens eval() returns new node instead of mutating this

QueryInParens.eval() was mutating `this` directly instead of returning
a new node, violating the core Less.js tree pattern. It also used a
brittle queue pattern where deep copies were pushed to an `mvalues`
array during eval() and shifted off during genCSS().

Now eval() creates and returns a new QueryInParens with evaluated
children, and genCSS() reads directly from the node's properties.
The `copy-anything` import is removed from this file (still used
elsewhere in the codebase).

* refactor: extract mergeRules into shared utility to fix AtRule layering violation

AtRule.eval() was directly calling ToCSSVisitor.prototype._mergeRules,
which breaks the architectural boundary between tree nodes and visitors.

Extract the merge logic into a standalone utility (merge-rules.js) that
both AtRule.eval() and ToCSSVisitor can use without coupling.

* fix: remove Container copy-paste duplication and fix evalNested splice index bug

Container was overriding evalNested, permute, and bubbleSelectors with
identical copies of the methods already provided by NestableAtRulePrototype.
Remove the redundant overrides so Container properly inherits from the
shared prototype.

Also fix a bug in NestableAtRulePrototype.evalNested where
context.mediaBlocks.splice(i, 1) used `i` (the index into `path`) to
splice `mediaBlocks`. These are different arrays with different contents,
so the index was wrong. Use indexOf(this) to find the correct position.

* fix(benchmark): update scripts and results for v4.x compatibility

- Fix percentage() calls in benchmark .less files for parens-division
- Add --math=always passthrough to benchmark-runner.js
- Handle all v3.12+/v4.x build scenarios in run-historical.sh
  (pnpm for workspace protocol, fallback tsc, separate runtime deps)
- Use last patch of each minor version in historical suite
- Update latest benchmark results (v2.0–v4.5.1)

* perf: optimize hot paths and fix benchmark infrastructure (less#4410)

* fix(benchmark): fix division in benchmark files for v4 math defaults

Wrap bare divisions inside percentage() calls in extra parens so
benchmarks work with v4's default parens-division math mode. Add
--math option passthrough to benchmark-runner.js and pass
--math=always in run-historical.sh for consistent cross-version results.

* perf: remove unnecessary closures in hot paths

- Remove `extendVisitor` alias in findMatch, use `this` directly
- Replace IIFE closure for functionRegistry lookup in Ruleset.eval
  with inline loop

~5% improvement on main benchmark (median 38.6ms → 37.1ms)

* perf: replace forEach/map closures with for loops in hot paths

- Selector.eval: replace map() closures with pre-allocated for loops
- Ruleset transformDeclaration: replace forEach with for loop
- extend-visitor visitRuleset: replace forEach with for loop, cache
  extend and pathCount to reduce repeated property access

Combined with previous commit: ~8% improvement on 104KB benchmark
(median 38.6ms → 36.4ms)

* fix(benchmark): handle all v3.12+/v4.x build scenarios

- Use pnpm for v4.3+ (workspace: protocol)
- Fallback tsc installation when npm can't install locally
- Install runtime deps separately when npm fails due to
  unpublished workspace packages (@less/test-import-module)
- Use last patch version of each minor release
- Skip v3.13.x (broken source: missing tree/util.js)

* bench: update benchmark results after hot-path optimizations

Median: 39.07ms → 34.32ms (~12% improvement)
Throughput: 2,495 KB/s → 2,828 KB/s
System: macbook-pro arm64

* bench: add historical benchmark results and track runs in git

- Add historical benchmark data (v3.5–v4.2) to results/runs/
- Update latest/ with all versions including v4.5.0-dev optimized results
- Format JSON with 2-space indentation
- Update .gitignore to track runs/ (historical records belong in git)

* bench: full historical benchmark run (v2.0–v4.5, 23 versions)

Apple M4 Pro, arm64, Node v18/v20/v24

Key findings:
- v2.4-v2.5 fastest era (~31ms median on 104KB file)
- v3.10-v3.12 massive regression (3-5x slower, 126-185ms)
- v4.0 recovered to ~40ms
- v4.2 fastest v4.x (35.4ms)
- v4.5.1 current master: 42.2ms

* bench: prune version list to significant performance changes

Reduced from 23 to 15 versions based on full benchmark data.
Dropped versions with <5% difference from their predecessor:
- v2.1 (broken), v2.5, v2.7 (plateau with v2.4/v2.6)
- v3.6–v3.9 (all within 1ms, flat ~41ms)
- v4.1 (identical to v4.0)

The full set can still be run with --versions flag.

* fix(benchmark): fix invalid CSS in benchmark.less and add Jess wrapper support

- Fix invalid CSS patterns in benchmark.less: hex-color selectors (#808080),
  bare declarations in @media, :not(1), unquoted attr values, empty margin
- Add benchmark-runner.cjs for CJS compatibility with ESM package
- Add callback support to render() in lib/index.js alongside Promise return

* feat: migrate to native ESM with no build step (less#4411)

* feat: migrate to native ESM with no build step

- Rename src/ to lib/ — source files are shipped directly, no compilation
- Add "type": "module" to package.json for native ESM support (Node 18+)
- Convert bin/lessc, test files, and build scripts from CJS to ESM
- Rename Gruntfile.js and .eslintrc.js to .cjs (must remain CommonJS)
- Add .js extensions to all relative import paths for ESM resolution
- Use createRequire() for optional dependency resolution (npm packages, JSON)
- Configure TypeScript for check-only mode (noEmit: true, allowJs: true)
- Update Rollup config to read from lib/ directly
- Update CI matrix to drop Node 16 (minimum Node 18+)
- Browser build is smaller: 500KB (was 509KB), minified 153KB (was 158KB)
- All 139 tests pass

* chore: fix trailing semicolons from linter

* chore: gitignore generated .css.map files in lib/

* fix(ci): restore lts/-3 to test matrix

* chore: stop tracking dist/ build artifacts

Generated browser bundles don't need to be in source control — they're
built during publish and included in the npm package via the files field.
Removes duplicate copies from both root dist/ and packages/less/dist/.

* fix(ci): use pnpm exec for playwright install

npx doesn't reliably find binaries with pnpm. Since playwright is
already a devDependency, use pnpm exec to run the installed version.

* fix(ci): use pnpm --filter for playwright, disable fail-fast

pnpm exec at workspace root can't find playwright binary since it's a
devDependency of the less package. Use --filter to run in that context.
Also disable fail-fast so all matrix jobs complete independently.

* fix(ci): move playwright to root devDependencies

Makes pnpm exec playwright work from workspace root in CI.

* fix: upgrade copy-anything to v3 for ESM compat, fix Windows test paths

copy-anything v2 lacks "type": "module", causing named import failures
on Node 18. v3 has proper ESM exports.

Revert testFolder to absolute path (matching original behavior) so debug
test path replacements match Less compiler output on Windows.

* chore: add CodeRabbit config to raise file review limit

* fix: add files field to package.json, remove postinstall from published package

Restricts npm package to only bin/, lib/, dist/, index.js, and README.md.
Previously shipped test files, Gruntfile, eslint config, etc.
Removes postinstall script (Playwright browser install) which only applies
in the monorepo dev environment and fails when installed from npm.

Verified: npm pack --dry-run shows 120 files (was 229), lessc CLI and
API both work from a clean tarball install.

* refactor: convert prototype-based tree nodes to ES6 classes (less#4412)

* refactor: convert prototype-based tree nodes to ES6 classes

Convert all 30 tree node files from `Object.assign(new Node(), {...})`
prototype pattern to proper `class extends Node` syntax. This enables
TypeScript to understand the inheritance chain, reducing checkJs errors
from 2756 to 0.

- All tree nodes now use `class X extends Node` (or appropriate parent)
- Node.type converted from instance property to getter for clean override
- Factory functions in index.js updated to use `new` instead of
  Object.create + apply (required for ES6 class compatibility)
- Benchmark script converted to ESM
- Added @types/node devDependency for checkJs support
- Enabled checkJs in tsconfig.json
- Added JSDoc types to node.js base class and several utility files

No behavioral changes - all 139 tests pass, benchmark performance
unchanged vs historical baselines (avg 36-39ms for 104KB).

* fix: @plugin deprecation says "replaced" not "removed"

* fix: use constructor params for AtRule selectors, path.resolve in benchmark

* fix: align @types/node with engines.node >=18 floor

* feat: JSDoc type annotations for all tree node files (less#4413)

* feat: add JSDoc type annotations with @ts-check to all tree node files

Add proper JSDoc type annotations to all 44 files in lib/less/tree/,
enabling per-file TypeScript checking via @ts-check. No {*} or {any}
casts — all types are derived from reading the actual code.

Key changes:
- Shared types (EvalContext, CSSOutput, TreeVisitor, FileInfo, VisibilityInfo) defined in node.js
- Node.value typed as union: Node | Node[] | string | number | undefined
- Node.prototype.parse declared for parser-injected prototype property
- Constructor properties explicitly declared with proper types
- Inline casts used to narrow union types at usage sites
- Widened base class params where subclasses pass different types

Also adds typecheck to prepublishOnly and pre-commit hook to catch
regressions as more files are annotated toward global checkJs: true.

All 139 tests pass, zero TypeScript errors.

* fix: remove duplicate JSDoc type annotation in ruleset.js

* fix: pre-existing bug fixes in tree nodes (less#4414)

* fix: preserve alpha 0 for fully transparent hex colors

#0000 and #00000000 parsed alpha as 0 which was treated as falsy by
the || operator, causing it to fall back to 1 (opaque). Use typeof
check instead so alpha 0 is preserved.

* fix: selector getElements callback `this` binding and forEach lint

- Capture `this._fileInfo` and `this.parse.imports` into locals before
  the plain function callback in Selector.getElements(), where `this`
  is undefined in strict mode (ES modules)
- Use explicit block in forEach to avoid implicit return of assignment

* fix: preserve full error context when rethrowing mixin call errors

The catch block in MixinCall.eval() only copied message and stack,
dropping type, extract, callLine, and other LessError fields. This
caused all mixin call errors to be reported as SyntaxError regardless
of their actual type (e.g. NameError). Use spread to preserve all
fields while still overriding index/filename to the call site.

* fix: guard functionRegistry.inherit() and fix atrule parenting

- Container and Media eval() now guard functionRegistry before calling
  .inherit(), matching mixin-definition.js defensive pattern
- AtRule constructor: remove dead setParent(selectors) on orphaned local,
  parent this.declarations and this.rules with null checks

* chore: release v4.6.0 (less#4415)

* chore: prepare v4.6.0 release

- Bump version to 4.6.0 in all package.json files
- Add CHANGELOG entry for v4.6.0
- Update publish workflow: replace deprecated actions/create-release with
  gh release create, attach dist files (less.js, less.min.js) as release
  assets, bump contents permission to write
- Remove .github/** from paths-ignore (was preventing workflow updates)
- Update CONTRIBUTING.md with detailed release documentation

version: 4.6.0

* fix: publish workflow and provenance errors

- Add repository field to test-data package.json (fixes npm OIDC
  provenance verification failure)
- Skip publish workflow on forks (only run on less/less.js)
- Remove duplicate require('fs') in bump-and-publish.js
- Add language specifier to markdown code block in CONTRIBUTING.md

* fix: handle existing releases for idempotent workflow re-runs

* fix: CJS compatibility, enriched npm README, ESM tests (less#4417)

* docs: enrich npm README with usage examples and feature highlights

version: 4.6.0

* fix: update README and tests to show ESM + promise/await usage

The package is ESM-only ("type": "module"), so the README now correctly
shows `import less from 'less'` with `await` instead of CJS `require()`.
The ES6 test now verifies both promise/await and callback APIs.

version: 4.6.0

* fix: add CJS compatibility wrapper so require('less') works

Adds index.cjs as a one-line wrapper that re-exports the ESM default.
The exports field now has both import and require conditions.
Adds test-cjs.cjs to verify CJS consumption alongside the existing
ESM test.

version: 4.6.0

* fix: lazy Proxy CJS wrapper for Node 18+ compatibility

Node 22+ uses native require(esm). Node 18-20 uses a lazy Proxy with
dynamic import() — transparent because render()/parse() already return
promises. Tested with render, callback, and version property access.

* fix: include Node 20.19+ in native require(esm) path

* fix: add alt text to README images for accessibility

* fix: publish script skips stale version markers in squash merges (less#4418)

* fix: skip stale version markers in squash merge commit messages

When a squash merge includes commit messages with `version: X.Y.Z`
from a previous release, the publish script would use that version
instead of auto-incrementing. Now checks if the requested version
already has a tag — if so, skips it and falls through to auto-increment.

* fix: simplify publish version logic — compare package.json vs NPM

Remove commit message version parsing entirely. The publish script now:
1. Checks EXPLICIT_VERSION env var (override)
2. If package.json > NPM version, uses package.json
3. Otherwise, bumps from latest NPM patch version

Updated CONTRIBUTING.md to reflect simplified workflow.

* chore: remove .claude directory and add to .gitignore (less#4419)

* chore: remove .claude directory and add to .gitignore

* ci: skip publish for .gitignore and .claude changes

* feat(alpha): refresh Jess wrapper integration

* fix: update extend.css expected output (.ff selector removal)

* test: update expected test outputs

* Prepare Less alpha publish gate and sync test-data

* benchmark runner update

* Fix scope value in v5

* Fix scope value in v5

* Don't collapse media queries in Less v5

* test-data: reconcile Jess alpha fixture baselines

* test-data: rebaseline import-reference fixture

* test-data: rebaseline scope fixture

* test: preserve Jess serializer expectations

* test: align extend nest generated is output

* test: align reference import comment output

* Consolidate Less alpha Jess wrapper

* perf(less-compat): plugin-free fast-path (__jessSkipLessCompatWhenPluginFree) + harden stableStringify (functions/circular/plugin objects); benchmark tooling + color-stress fixture + fast-path test

* test-data: graduate 13 pure-nesting Less goldens to v5 nested shape

For each fixture, v5 flat render == current golden but nested differs
(pure-nesting, semantically identical). Moved flat golden to legacy/,
wrote v5 nested output as the new top-level golden, and set
collapseNesting:false in the fixture's styles.config.

Graduated (13): at-rules, css-escapes, layer, mixin-noparens,
mixins-closure, mixins-guards, mixins-interpolated, mixins-nested,
mixins/maps, rulesets, namespacing/namespacing-7,
strict-imports, import/import-reference-issues.

Verified: full all-less harness 106/106 green against graduated data
(zero sibling regressions).

* test(test-data): add top-level styles.config default (collapseNesting: true)

Provide the flat-output default at the root of the fixture corpus so the Jess
all-less harness can source it from the config cascade instead of hardcoding
it. Fixture-directory styles.config files override this per directory; fixtures
without an explicit collapseNesting inherit this default.

* fix(test-data): @Viewport initial-scale stays 1.0 (v5 un-operated verbatim)

* test(test-data): migrate bare @var at-rule preludes to @{var} interpolation (v5)

Cherry-pick of 31bbe396 (fix/atrule-var-migrate-v5) onto content branch.
Source .less bare-@var -> @{var}; goldens unchanged. Un-migrated source was
the sole reason ast/ (correct v5 strict-prelude behavior) diverged.

* fix(test-data): correct extend/extend-exact/merge goldens (v5)

extend/extend-exact: alpha goldens carried the exact-extend-into-children
bug; merge: alpha anchored at first occurrence, v5 uses last. Applies the
owner-staged proposed-alpha-corrections; ast/ output is byte-identical to
these (gated by extend-byte-identity + r4-byte-identity tests).

* chore: prepare Less 5 alpha.1 release guards

* test(test-data): restore property accessor v5 oracle

* test(test-data): retain property accessor source order

* test(test-data): preserve important mixin source order

* test(test-data): preserve source order in collapsed fixtures

* test(less): honor fixture nesting output modes

* test(release): prove packed Less alpha consumer

* docs: prepare Less 5 alpha.1 release notes

* docs(release): link Less alpha corpus inventory

* test(v5): classify removed charset interpolation

* docs: clarify Less 5 alpha changelog

* docs: remove Less alpha support cruft

* docs: note Less 5 browser build follow-up

* fix: preserve Linecraft diagnostics in Less alpha

* docs: expand Less 5 alpha release notes

* chore: remove Grunt from Less alpha

* fix: skip browser assets for Less alpha releases

* chore: harden Less 5 alpha release candidate

* fix: normalize packed alpha tarball checks

* fix: harden Less alpha public release surface

* fix: address Less alpha review lint findings

* test-data: v5 numeric-precision expectations, 4.x snapshotted to legacy/

jess replaces the 8-decimal-place output floor with a shortest-decimal-within-
1e-10 tolerance trim, and stops applying that floor to un-operated SOURCE
literals. Both are intended v5 divergences from 4.x, so the top-level .css moves
to the v5 value and legacy/{name}.css keeps the 4.x one.

- variables/variable-advanced.css: add-px-2 393.35275591px -> 393.3527559px
  (1cm = 96/2.54 px, a genuine repeating decimal). legacy/ created.
- property-name-interp/property-name-interp.css: 3.141592653589793 ->
  3.1415926536 x2 — the interpolation splice no longer bypasses the number
  policy. legacy/ created. The unrelated `/* foo */` divergence is left intact.
- css-3/css-3.css: rotate(0deg) -> rotate(-0.0000000001deg) — an un-operated
  source literal is now preserved verbatim instead of being denoised to 0.
  legacy/ already existed.
- functions/functions.css: 6 trig/luma literals gain their earned digits.
  legacy/ already existed. The unrelated hsl-clamp and length-1 divergences are
  left intact.

* test-data: label legacy/*.css as inert Less 4.x records

legacy/{name}.css holds the Less 4.x output recorded when a fixture
graduated to v5-expected. Nothing reads these files (fixture globs are
tests-unit/*/*.less one level deep; no styles.config names an output
under legacy/), but they share the shape and extension of an asserted
fixture one directory away, so they have been misread as asserted.

Header states the truth at the top of each file. Additive only.

Skipped the three legacy/ dirs that also hold a .less (functions,
ie-filters-REMOVED, javascript-REMOVED): those are fixture pairs read
by the optional corpus-report tool, not pure records.

* test(functions): graduate min/max to the coherent v5 output

`min(6em, 5, 4ex, 3, 2pt, 1)` and `max(1px, 2, 3em, 4, 5m, 6)` recorded
less.js 4.x's PARTIAL reduction (`min(1, 4ex, 2pt)` / `max(5m, 3em)`).

That output is not a policy jess reproduces. less.js throws on mismatched
units only when the FIRST argument carries a unit; an intervening unitless
argument resets its `unitStatic` bookkeeping and reaches a per-unit-group
reduction branch instead, so the same expression reduces or is preserved
depending on argument ORDER. dart-sass reduces the same input all the way
to `1`/`6`. Under jess's coherent model `min`/`max` reduce when the units
reduce and fail otherwise, and a failed CSS-function call in bare position
is preserved verbatim, so both lines now emit every original argument.

Verified against lessc 4.8.0 and dart-sass 1.101.0: this deliberately
matches neither on THESE two inputs, and matches both everywhere else.

No `legacy/` record written: `tests-unit/functions/legacy/functions.css`
already exists as a live fixture pair with its own `legacy/functions.less`,
so it is not a graduation slot and must not be overwritten.

* fix(release): sync release version from PR title (less#4484)

* fix(release): sync release version from PR title (less#4483)

* fix(release): sync release version from PR title

* fix(release): harden title sync automation

* fix(release): harden title sync workflow

* fix(release): make changelog title sync idempotent

* fix(release): insert missing changelog heading on title sync

* fix(release): insert changelog heading without prior releases

* fix(release): automate alpha release tests and pin title sync actions

* test: sync upstream alpha fixtures

* fix: use Jess alpha.10 compiler closure for Less alpha

* test: assert structured Less alpha warnings

* fix(release): abort on remote tag mismatch

* test-data(container): fix v5 expected container output

* test: run alpha fixture gate in less package

* test: cover alpha error and warning fixtures

* test: narrow alpha fixture diagnostic assertions

* fix: format lessc errors with Jess diagnostics

* fix(lessc): route Jess warnings to stderr

* test: suppress intentional legacy units

* test: require Linecraft diagnostics in packed lessc

* test: require stable Linecraft diagnostics

* test: harden alpha release gates

* ci: align alpha node matrix with Jess runtime

* fix: preserve Jess diagnostic messages

* test: preserve Jess dynamic charset diagnostics

* test: derive packed Jess alpha version

* test: derive Jess alpha release assertions

* test: consume Jess alpha 11 in Less alpha

* test: surface alpha fixture timeouts

* test: tighten Less alpha review hygiene

* ci: harden release metadata defaults

* test: support focused alpha fixture runs

* docs: record upstream fixture sync check

---------

Signed-off-by: Tobias Speicher <[email protected]>
Co-authored-by: Daniel Puckowski <[email protected]>
Co-authored-by: Timo Tijhof <[email protected]>
Co-authored-by: CommanderRoot <[email protected]>
Co-authored-by: Memmie Lenglet <[email protected]>
Co-authored-by: Jimmy Wärting <[email protected]>
Co-authored-by: Shahadat Hossain <[email protected]>
Co-authored-by: Matthew Dean <[email protected]>
matthew-dean added a commit that referenced this pull request Aug 1, 2026
* fix(issue#4339): limit whitespace check

* Fix issue #4339 by limiting the whitespace check for the deprecation
  notice to not produce false positives.

* fix(issue#4339): correct deprecation notice

* Correct deprecation notice for issue #4339.

* fix:(issue#4397): container query variable names

* Fix for issue #4397 container query with variable names like
  @container @foo () {}.

* feat(deprecation): add deprecation warnings for features removed in Less 5.x

New deprecation infrastructure with automatic repetition limiting (max 5 per type):
- deprecation.js: registry of deprecation IDs with descriptions
- Parser warn() accepts deprecation IDs for categorized warnings
- --quiet-deprecations: suppress only deprecation warnings (keeps other warnings)

New deprecation warnings for features being removed in 5.x:
- js-eval: inline JavaScript backtick expressions
- at-plugin: @plugin directive

Existing warnings now tagged with stable IDs:
- mixin-call-no-parens, mixin-call-whitespace, dot-slash-operator
- variable-in-unknown-value, property-in-unknown-value

CLI deprecation notices for: --js, --line-numbers, --math=always

* feat(benchmark): add historical benchmark suite with per-system result tracking

Results organized as:
  results/latest/{system-id}.json  - most recent per system
  results/runs/{date}_{system-id}.json - historical archive (gitignored)

* fix(benchmark): don't path.resolve bare package names in benchmark-runner

path.resolve('less') turns the package name into an absolute filesystem
path, preventing Node's package resolution from finding npm-installed
versions. Only resolve relative paths starting with '.'.

* fix(benchmark): use coefficient of variation instead of range for variance_pct

variance_pct was computing (max-min)/avg which is range-over-mean.
Now uses stddev/avg (coefficient of variation) which is a proper
variability statistic.

* fix(benchmark): use timestamp instead of date for run filenames

Prevents same-day runs from overwriting each other in the runs/ archive.

* fix(cli): queue deprecation warnings until after arg parsing

Deprecation warnings from flags like --js, --line-numbers, and
--math=always were printed immediately during arg parsing, so
--quiet-deprecations only worked if it appeared before the deprecated
flag. Now all CLI deprecation messages are queued and flushed after
parsing completes, respecting --silent, --quiet, and
--quiet-deprecations regardless of flag order.

* Remove duplicate length check from expression.genCSS() (#4327)

Follows-up 53f84f02bad6e, which started the conditional
with a check for `i + 1 < this.value.length`, which is the same
as the parent block.

* Remove unused `parsers.entities.propertyCurly()` (#4271)

Follows-up a38f8a1eb7beed589d2fa734fcf411cf4461d231, which introduced
this as part of implementing property accessors. The method was not
used there, and hasn't been used elsewhere since then either.

Ref https://github.com/less/less.js/pull/3163.

* Remove redundant return from `parsers.blockRuleset()` (#4265)

* chore: replace deprecated String.prototype.substr() (#3702)

.substr() is deprecated so we replace it with .slice() which works similarily but isn't deprecated

Signed-off-by: Tobias Speicher <[email protected]>

* Handle the lack of the optional dependencies (#3791)

* Handle optional dependencies

* Handle optional dependency image-size

* remove phantom stuff (#3782)

* remove phantom stuff

* lint fix

* use deep clone

* fixed bug in import subpath module (#4236)

* fix(issue#4354): unknown at-rule expression commas (#4389)

* Fix issue less#4354 unknown at-rule expressions should not have commas in
  a keyword list.
* Add some additional layer at-rule tests.

* chore: update README.md copyright (#4386)

* Update README.md copyright year.

* Fix no-prototype-builtins issues in Ruleset and ToCSSVisitor (#4404)

Co-authored-by: Timo Tijhof <[email protected]>

* chore: add test for number with underscore parsing (#4406)

In Less.js 2.6.0, parsing of dimensions changed so that `5_large`
is seen as one value, instead of as a list containing "5" and "_large".

In updating the Less.php port, we forgot to consider this change
because none of the Less.js 3.13 tests seem to cover this behavior.

Follows-up https://github.com/less/less.js/pull/2485.

This adds the test case from https://github.com/less/less.js/issues/2462,
as inpired by downstream https://gerrit.wikimedia.org/r/1197310.

Co-authored-by: Timo Tijhof <[email protected]>

* fix(#4331): exclude CSS at-rule keywords from declarationCall parsing (#4407)

* fix(#4331): exclude CSS at-rule keywords from declarationCall parsing

* fix(#4331): normalize spacing after CSS at-rule keywords in media queries

When `and`, `or`, `not`, or `only` keywords appear without a space
before `(` in media queries, ensure spacing is added in the output
to produce valid CSS.

* fix(#4358): resolve parent selectors in comma-separated pseudo-selector lists (#4408)

* refactor: code quality cleanup for container queries and related code (#4409)

* fix: correct import and error handling in style() function

- Fix incorrect import: `Anonymous` was imported from '../tree/variable'
  instead of '../tree/anonymous' (worked by accident since Variable
  was imported on the line above)
- Simplify switch/case with single case 0 to a plain if statement
- Add explanatory comment to the catch block documenting why it exists
  (CSS pass-through for @container style() queries)

* refactor: remove dead boolean logic in evalRoot()

- Remove `allAmpersands` variable that was initialized to false and
  never set to true, making it dead code
- Replace string-based ampersand detection (genCSS + regex) with
  direct element value checks, avoiding unnecessary AST-to-string
  conversion
- Simplify boolean conditions that referenced the dead variable

* fix: add missing parserInput.forget() in colorOperand

The colorOperand parser rule called parserInput.save() but only called
restore() on failure, missing the forget() call on the success path.

* refactor: QueryInParens eval() returns new node instead of mutating this

QueryInParens.eval() was mutating `this` directly instead of returning
a new node, violating the core Less.js tree pattern. It also used a
brittle queue pattern where deep copies were pushed to an `mvalues`
array during eval() and shifted off during genCSS().

Now eval() creates and returns a new QueryInParens with evaluated
children, and genCSS() reads directly from the node's properties.
The `copy-anything` import is removed from this file (still used
elsewhere in the codebase).

* refactor: extract mergeRules into shared utility to fix AtRule layering violation

AtRule.eval() was directly calling ToCSSVisitor.prototype._mergeRules,
which breaks the architectural boundary between tree nodes and visitors.

Extract the merge logic into a standalone utility (merge-rules.js) that
both AtRule.eval() and ToCSSVisitor can use without coupling.

* fix: remove Container copy-paste duplication and fix evalNested splice index bug

Container was overriding evalNested, permute, and bubbleSelectors with
identical copies of the methods already provided by NestableAtRulePrototype.
Remove the redundant overrides so Container properly inherits from the
shared prototype.

Also fix a bug in NestableAtRulePrototype.evalNested where
context.mediaBlocks.splice(i, 1) used `i` (the index into `path`) to
splice `mediaBlocks`. These are different arrays with different contents,
so the index was wrong. Use indexOf(this) to find the correct position.

* perf: optimize hot paths and fix benchmark infrastructure (#4410)

* fix(benchmark): fix division in benchmark files for v4 math defaults

Wrap bare divisions inside percentage() calls in extra parens so
benchmarks work with v4's default parens-division math mode. Add
--math option passthrough to benchmark-runner.js and pass
--math=always in run-historical.sh for consistent cross-version results.

* perf: remove unnecessary closures in hot paths

- Remove `extendVisitor` alias in findMatch, use `this` directly
- Replace IIFE closure for functionRegistry lookup in Ruleset.eval
  with inline loop

~5% improvement on main benchmark (median 38.6ms → 37.1ms)

* perf: replace forEach/map closures with for loops in hot paths

- Selector.eval: replace map() closures with pre-allocated for loops
- Ruleset transformDeclaration: replace forEach with for loop
- extend-visitor visitRuleset: replace forEach with for loop, cache
  extend and pathCount to reduce repeated property access

Combined with previous commit: ~8% improvement on 104KB benchmark
(median 38.6ms → 36.4ms)

* fix(benchmark): handle all v3.12+/v4.x build scenarios

- Use pnpm for v4.3+ (workspace: protocol)
- Fallback tsc installation when npm can't install locally
- Install runtime deps separately when npm fails due to
  unpublished workspace packages (@less/test-import-module)
- Use last patch version of each minor release
- Skip v3.13.x (broken source: missing tree/util.js)

* bench: update benchmark results after hot-path optimizations

Median: 39.07ms → 34.32ms (~12% improvement)
Throughput: 2,495 KB/s → 2,828 KB/s
System: macbook-pro arm64

* bench: add historical benchmark results and track runs in git

- Add historical benchmark data (v3.5–v4.2) to results/runs/
- Update latest/ with all versions including v4.5.0-dev optimized results
- Format JSON with 2-space indentation
- Update .gitignore to track runs/ (historical records belong in git)

* bench: full historical benchmark run (v2.0–v4.5, 23 versions)

Apple M4 Pro, arm64, Node v18/v20/v24

Key findings:
- v2.4-v2.5 fastest era (~31ms median on 104KB file)
- v3.10-v3.12 massive regression (3-5x slower, 126-185ms)
- v4.0 recovered to ~40ms
- v4.2 fastest v4.x (35.4ms)
- v4.5.1 current master: 42.2ms

* bench: prune version list to significant performance changes

Reduced from 23 to 15 versions based on full benchmark data.
Dropped versions with <5% difference from their predecessor:
- v2.1 (broken), v2.5, v2.7 (plateau with v2.4/v2.6)
- v3.6–v3.9 (all within 1ms, flat ~41ms)
- v4.1 (identical to v4.0)

The full set can still be run with --versions flag.

* feat: migrate to native ESM with no build step (#4411)

* feat: migrate to native ESM with no build step

- Rename src/ to lib/ — source files are shipped directly, no compilation
- Add "type": "module" to package.json for native ESM support (Node 18+)
- Convert bin/lessc, test files, and build scripts from CJS to ESM
- Rename Gruntfile.js and .eslintrc.js to .cjs (must remain CommonJS)
- Add .js extensions to all relative import paths for ESM resolution
- Use createRequire() for optional dependency resolution (npm packages, JSON)
- Configure TypeScript for check-only mode (noEmit: true, allowJs: true)
- Update Rollup config to read from lib/ directly
- Update CI matrix to drop Node 16 (minimum Node 18+)
- Browser build is smaller: 500KB (was 509KB), minified 153KB (was 158KB)
- All 139 tests pass

* chore: fix trailing semicolons from linter

* chore: gitignore generated .css.map files in lib/

* fix(ci): restore lts/-3 to test matrix

* chore: stop tracking dist/ build artifacts

Generated browser bundles don't need to be in source control — they're
built during publish and included in the npm package via the files field.
Removes duplicate copies from both root dist/ and packages/less/dist/.

* fix(ci): use pnpm exec for playwright install

npx doesn't reliably find binaries with pnpm. Since playwright is
already a devDependency, use pnpm exec to run the installed version.

* fix(ci): use pnpm --filter for playwright, disable fail-fast

pnpm exec at workspace root can't find playwright binary since it's a
devDependency of the less package. Use --filter to run in that context.
Also disable fail-fast so all matrix jobs complete independently.

* fix(ci): move playwright to root devDependencies

Makes pnpm exec playwright work from workspace root in CI.

* fix: upgrade copy-anything to v3 for ESM compat, fix Windows test paths

copy-anything v2 lacks "type": "module", causing named import failures
on Node 18. v3 has proper ESM exports.

Revert testFolder to absolute path (matching original behavior) so debug
test path replacements match Less compiler output on Windows.

* chore: add CodeRabbit config to raise file review limit

* fix: add files field to package.json, remove postinstall from published package

Restricts npm package to only bin/, lib/, dist/, index.js, and README.md.
Previously shipped test files, Gruntfile, eslint config, etc.
Removes postinstall script (Playwright browser install) which only applies
in the monorepo dev environment and fails when installed from npm.

Verified: npm pack --dry-run shows 120 files (was 229), lessc CLI and
API both work from a clean tarball install.

* refactor: convert prototype-based tree nodes to ES6 classes (#4412)

* refactor: convert prototype-based tree nodes to ES6 classes

Convert all 30 tree node files from `Object.assign(new Node(), {...})`
prototype pattern to proper `class extends Node` syntax. This enables
TypeScript to understand the inheritance chain, reducing checkJs errors
from 2756 to 0.

- All tree nodes now use `class X extends Node` (or appropriate parent)
- Node.type converted from instance property to getter for clean override
- Factory functions in index.js updated to use `new` instead of
  Object.create + apply (required for ES6 class compatibility)
- Benchmark script converted to ESM
- Added @types/node devDependency for checkJs support
- Enabled checkJs in tsconfig.json
- Added JSDoc types to node.js base class and several utility files

No behavioral changes - all 139 tests pass, benchmark performance
unchanged vs historical baselines (avg 36-39ms for 104KB).

* fix: @plugin deprecation says "replaced" not "removed"

* fix: use constructor params for AtRule selectors, path.resolve in benchmark

* fix: align @types/node with engines.node >=18 floor

* feat: JSDoc type annotations for all tree node files (#4413)

* feat: add JSDoc type annotations with @ts-check to all tree node files

Add proper JSDoc type annotations to all 44 files in lib/less/tree/,
enabling per-file TypeScript checking via @ts-check. No {*} or {any}
casts — all types are derived from reading the actual code.

Key changes:
- Shared types (EvalContext, CSSOutput, TreeVisitor, FileInfo, VisibilityInfo) defined in node.js
- Node.value typed as union: Node | Node[] | string | number | undefined
- Node.prototype.parse declared for parser-injected prototype property
- Constructor properties explicitly declared with proper types
- Inline casts used to narrow union types at usage sites
- Widened base class params where subclasses pass different types

Also adds typecheck to prepublishOnly and pre-commit hook to catch
regressions as more files are annotated toward global checkJs: true.

All 139 tests pass, zero TypeScript errors.

* fix: remove duplicate JSDoc type annotation in ruleset.js

* fix: pre-existing bug fixes in tree nodes (#4414)

* fix: preserve alpha 0 for fully transparent hex colors

#0000 and #00000000 parsed alpha as 0 which was treated as falsy by
the || operator, causing it to fall back to 1 (opaque). Use typeof
check instead so alpha 0 is preserved.

* fix: selector getElements callback `this` binding and forEach lint

- Capture `this._fileInfo` and `this.parse.imports` into locals before
  the plain function callback in Selector.getElements(), where `this`
  is undefined in strict mode (ES modules)
- Use explicit block in forEach to avoid implicit return of assignment

* fix: preserve full error context when rethrowing mixin call errors

The catch block in MixinCall.eval() only copied message and stack,
dropping type, extract, callLine, and other LessError fields. This
caused all mixin call errors to be reported as SyntaxError regardless
of their actual type (e.g. NameError). Use spread to preserve all
fields while still overriding index/filename to the call site.

* fix: guard functionRegistry.inherit() and fix atrule parenting

- Container and Media eval() now guard functionRegistry before calling
  .inherit(), matching mixin-definition.js defensive pattern
- AtRule constructor: remove dead setParent(selectors) on orphaned local,
  parent this.declarations and this.rules with null checks

* chore: release v4.6.0 (#4415)

* chore: prepare v4.6.0 release

- Bump version to 4.6.0 in all package.json files
- Add CHANGELOG entry for v4.6.0
- Update publish workflow: replace deprecated actions/create-release with
  gh release create, attach dist files (less.js, less.min.js) as release
  assets, bump contents permission to write
- Remove .github/** from paths-ignore (was preventing workflow updates)
- Update CONTRIBUTING.md with detailed release documentation

version: 4.6.0

* fix: publish workflow and provenance errors

- Add repository field to test-data package.json (fixes npm OIDC
  provenance verification failure)
- Skip publish workflow on forks (only run on less/less.js)
- Remove duplicate require('fs') in bump-and-publish.js
- Add language specifier to markdown code block in CONTRIBUTING.md

* fix: handle existing releases for idempotent workflow re-runs

* fix: CJS compatibility, enriched npm README, ESM tests (#4417)

* docs: enrich npm README with usage examples and feature highlights

version: 4.6.0

* fix: update README and tests to show ESM + promise/await usage

The package is ESM-only ("type": "module"), so the README now correctly
shows `import less from 'less'` with `await` instead of CJS `require()`.
The ES6 test now verifies both promise/await and callback APIs.

version: 4.6.0

* fix: add CJS compatibility wrapper so require('less') works

Adds index.cjs as a one-line wrapper that re-exports the ESM default.
The exports field now has both import and require conditions.
Adds test-cjs.cjs to verify CJS consumption alongside the existing
ESM test.

version: 4.6.0

* fix: lazy Proxy CJS wrapper for Node 18+ compatibility

Node 22+ uses native require(esm). Node 18-20 uses a lazy Proxy with
dynamic import() — transparent because render()/parse() already return
promises. Tested with render, callback, and version property access.

* fix: include Node 20.19+ in native require(esm) path

* fix: add alt text to README images for accessibility

* fix: publish script skips stale version markers in squash merges (#4418)

* fix: skip stale version markers in squash merge commit messages

When a squash merge includes commit messages with `version: X.Y.Z`
from a previous release, the publish script would use that version
instead of auto-incrementing. Now checks if the requested version
already has a tag — if so, skips it and falls through to auto-increment.

* fix: simplify publish version logic — compare package.json vs NPM

Remove commit message version parsing entirely. The publish script now:
1. Checks EXPLICIT_VERSION env var (override)
2. If package.json > NPM version, uses package.json
3. Otherwise, bumps from latest NPM patch version

Updated CONTRIBUTING.md to reflect simplified workflow.

* chore: remove .claude directory and add to .gitignore (#4419)

* chore: remove .claude directory and add to .gitignore

* ci: skip publish for .gitignore and .claude changes

* fix: webpack browser build - use UMD dist/less.js, add CJS bundle (#4424)

* fix: webpack browser build - use UMD dist/less.js, add CJS bundle (#4423)

- Browser exports point to dist/less.js (UMD) instead of less-node
- Add CJS bundle (dist/less-node.cjs) for Node require() with module shim
- Remove dead index.js; index.cjs re-exports CJS bundle
- Add export tests: import-patterns, webpack-browser, test-cjs-suite
- CI and publish workflows run test:node (build + CJS + ESM tests)

* Beta publish script

* chore: clarify test:node runs ESM + CJS in workflow labels

* fix: normalize path separators in rollup plugin for Windows CI

The inlinePackageVersion plugin used forward-slash path check that
failed on Windows where rollup passes backslash-separated IDs,
leaving the require('../../package.json') unresolved at runtime.

* chore: bump version to 4.6.3 for release

* test: Add coverage for :is()/:matches()/:where() containing nested :has() selectors and comma-separated lists (#4422)

* Initial plan

* Initial plan

Co-authored-by: matthew-dean <[email protected]>

* test: add test cases for :is()/:matches() containing :has() (fixes #4378)

Co-authored-by: matthew-dean <[email protected]>

* test: add :where() and comma-separated list test cases for pseudo-selectors

Co-authored-by: matthew-dean <[email protected]>

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: matthew-dean <[email protected]>
Co-authored-by: Matthew Dean <[email protected]>

* fix: ensure npm publish is always backed by a GitHub tag, release, and version-bump commit (#4430)

* Initial plan

* fix: prevent npm publish when GitHub push fails, skip workflow on version bump commits

Co-authored-by: matthew-dean <[email protected]>

* fix: skip version-bump commit entirely, push only the tag to bypass branch protection

Co-authored-by: matthew-dean <[email protected]>

* fix: restore version-bump commit + push to master, add infinite-loop guard

Co-authored-by: matthew-dean <[email protected]>

* fix: exclude .github and scripts from publish workflow trigger

Co-authored-by: matthew-dean <[email protected]>

* feat: implement PR-based release flow for master

Co-authored-by: matthew-dean <[email protected]>

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: matthew-dean <[email protected]>

* fix(less): upgrade make-dir to v4 to fix security vulnerability (#4426)

Co-authored-by: Matthew Dean <[email protected]>

* fix(issue#4356): parenthesis in media query (#4427)

* Fix issue #4356 issue with parenthesis in media query.
* Add tests for issue #4356.

Co-authored-by: Matthew Dean <[email protected]>

* feat: PR-based release flow for alpha; test suite proving all three release properties (#4431)

* Initial plan

* fix: correct release automation for master merges and publishing

- create-release-pr.yml: add set -euo pipefail; track whether a commit
  was created; skip push + gh pr create when no version changes (no-op
  safety - fixes the "no commits between head and base" failure).

- scripts/bump-and-publish.js: on master, use the version already in
  package.json as-is (no auto-increment). Validate it is > NPM version.
  Skip updateAllVersions/git-add/git-commit on master so the published
  tag always points to the release PR merge commit on master, not to a
  local detached commit. Alpha behavior is unchanged.

- Fix error message: on master say "Git tag was pushed" rather than
  "Version bump commit and tag were pushed".

Co-authored-by: matthew-dean <[email protected]>

* test: add release automation test suite (20 tests)

Proves the three components of the release flow work correctly:
- publish.yml if: conditions (6 scenarios)
- create-release-pr.yml if: conditions (4 scenarios)
- bump-and-publish.js master path: existing version, no commit, no push (4 tests)
- bump-and-publish.js alpha path: auto-increment, commit, alpha tag (4 tests)
- create-release-pr no-op safety: commit when needed, clean exit when not (2 tests)

Run with: node scripts/test-release-automation.js
         or: npm run test:release (after pnpm install)

Co-authored-by: matthew-dean <[email protected]>

* plan: implement PR-based release flow for alpha branch

Co-authored-by: matthew-dean <[email protected]>

* feat: PR-based release flow for alpha branch (mirrors master)

- create-release-pr.yml: listen on alpha push; compute alpha version
  increment (X.Y.Z-alpha.N → X.Y.Z-alpha.N+1); use branch-specific PR
  title/base/branch naming; update loop guards for both flavours
- publish.yml: remove push:alpha trigger; add alpha to pull_request
  branches; update if: condition for alpha release PR title+base
- bump-and-publish.js: remove auto-increment/commit/push for alpha;
  add getNpmAlphaVersion(); alpha now validates and publishes like master
- test-release-automation.js: 34 tests covering new flows end-to-end

Co-authored-by: matthew-dean <[email protected]>

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: matthew-dean <[email protected]>

* Fix `not` keyword silently ignored when used without parentheses in conditions (#4421)

* Initial plan

* Fix: not keyword now works without parentheses in guard conditions

Previously, `boolean(not false)` silently ignored the `not` keyword
while `boolean(not (false))` worked correctly.

The `negatedCondition` parser function consumed the `not` keyword but
only tried `parenthesisCondition`, which requires `(`. With no parens,
it returned undefined with `not` already consumed, causing silent skip.

Fix: fall back to `atomicCondition` when `parenthesisCondition` fails,
allowing both `not false` and `not (false)` to work consistently.

Co-authored-by: matthew-dean <[email protected]>

* Restrict not-without-parens to simple values only (keywords/variables)

Complex conditions like `not 2 < 1` still require parentheses,
keeping alignment with CSS media query syntax. Only simple bare
values (keywords, variables, quoted strings) are allowed after
`not` without parens: `not false`, `not @var`.

Remove the `boolean(not 2 < 1)` test case that relied on the
broader atomicCondition fallback.

Co-authored-by: matthew-dean <[email protected]>

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: matthew-dean <[email protected]>
Co-authored-by: Matthew Dean <[email protected]>

* test: regression test for @container mixin parameter variable resolution (#4420)

* Initial plan

* Initial plan: add regression test for container mixin parameters issue

Co-authored-by: matthew-dean <[email protected]>

* test: add regression test for container mixin parameters issue (#4420)

Co-authored-by: matthew-dean <[email protected]>

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: matthew-dean <[email protected]>
Co-authored-by: Matthew Dean <[email protected]>

* fix: update packageManager to [email protected] to match lockfileVersion 9.0 in pnpm-lock.yaml (#4432)

* Initial plan

* fix: trigger create-release-pr on any push to master/alpha, not just packages/**

Co-authored-by: matthew-dean <[email protected]>

* fix: update packageManager to [email protected] to match lockfileVersion 9.0

Co-authored-by: matthew-dean <[email protected]>

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: matthew-dean <[email protected]>

* ci: fix Playwright chromium install hang on Node current/lts/* (#4445)

* ci: fix Playwright chromium install hang on Node current/lts/*

The `playwright install chromium` step was hanging for 1h+ on jobs using Node `current` and `lts/*` after the 163 MiB download completed (post-download extraction/setup blocked indefinitely).

Fixes:
- Add `timeout-minutes: 5` to fail fast instead of burning a runner for 6 hours
- Add `--with-deps` to install required system libraries (likely cause of the hang)
- Cache Playwright browser binaries via `actions/cache` using `PLAYWRIGHT_BROWSERS_PATH` pointed at `${{ github.workspace }}/.playwright-browsers` (cross-platform)

Older LTS jobs (lts/-1, lts/-2, lts/-3) were unaffected and completed fine.

* Refactor CI workflow for improved clarity

The `Install chromium` step was causing CI to hang indefinitely on Node current/lts/* (and timeout when we added a 5-min limit). Root cause: `test:node` only runs grunt node tests and has no browser dependency, so installing Chromium was never necessary in the first place.

Also drops the unused `env: PLAYWRIGHT_BROWSERS_PATH` and `actions/cache` step added in the previous commit.

* Fix browser export interop by routing bundlers to CJS-typed UMD artifact (#4444)

* Initial plan

* Fix browser export to CJS dist entry for bundler interop

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: Matthew Dean <[email protected]>

* Add Copilot review request job to CI workflow

Added a new job to request Copilot review for pull requests.

* fix: add continue-on-error to copilot-review CI job (#4448)

Updated CI workflow to include 'continue-on-error' for copilot-review job.

* chore: automate CHANGELOG generation in release workflow (#4447)

* chore: automate CHANGELOG generation in release workflow

Updated comments for clarity and consistency in the release PR workflow.

* fix: correct bash escaping in PR body template

Fix typo in push event and update release message format.

* chore: release v4.6.5 (#4436)

* chore: release v4.6.5

* docs: add CHANGELOG entries for v4.6.1 through v4.6.5

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Matthew Dean <[email protected]>

* fix: correct push event typo in create-release-pr workflow (pus → push:) (#4449)

* fix: use printf for PR body to avoid YAML indentation error in run block (#4450)

Removed redundant line from PR body in release workflow.

* docs: fix incorrect contributor attributions in v4.6.0 changelog (#4437)

Seven entries under v4.6.0 credited @nicolo-ribaudo for PRs authored by
other contributors. Updated each entry to match the actual PR author.

Fixes #4428

* chore: prevent dependency lifecycle scripts (#4440)

* chore: prevent dependency lifecycle scripts

* Prevent dependency lifecycle scripts during CI work.

* fix: partial revert for CI run

* Partial revert of CI run; keep only frozen lockfile so CI can
  complete.

* fix: CI hang on chromium install

* Fix CI hang on chromium install; should not be needed for CI test
  purposes.

* chore: re-add dependency script ignore for CI

* Re-add dependency script ignore for CI now that chromium hang is
  resolved and CI can complete.

---------

Co-authored-by: Matthew Dean <[email protected]>

* fix(issue#4316): color calc inside from expression (#4434)

* Fix color calc() inside from expression parsing issues.
* Add tests for #4316.

Co-authored-by: Matthew Dean <[email protected]>

* fix: avoid crash on nested @supports with dumpLineNumbers (#4446)

A nested @supports (or @document) builds an implicit, non-root ruleset
that never gets a debugInfo attached during parsing. With dumpLineNumbers
enabled, genCSS tried to read lineNumber/fileName off that missing
debugInfo and threw a TypeError instead of producing output.

Skip emitting debug info when a node has none, the same way nodes without
a recorded line are already handled elsewhere.

* Preserve spacing for container feature functions (#4441)

* Preserve container feature function spacing

Signed-off-by: Puneet Dixit <[email protected]>

* Handle non-ASCII container names

---------

Signed-off-by: Puneet Dixit <[email protected]>
Co-authored-by: Puneet Dixit <[email protected]>

* chore: release v4.6.6 (#4451)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* Fix failing "Request Copilot review" CI job (#4457)

* Initial plan

* Fix failing Request Copilot review CI job by handling 403 gracefully

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>

* chore: release v4.6.7 (#4458)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* feat: deprecate bare @variable in non-value at-rule positions (#4462)

* feat: deprecate bare @variable in non-value at-rule positions

Bare @var in at-rule preludes, names, and identifiers is deprecated in
favour of @{foo} interpolation; the bare form still resolves, so this is
a warning only (id: variable-in-at-rule-prelude, respects
--quiet-deprecations and the repetition cap).

Covered positions:
- @media / @container feature preludes
- @supports / @document / unknown & custom at-rule preludes
- @keyframes / @counter-style / @charset identifiers
- @layer names and lists
- @namespace prefix

@{foo} interpolation is now accepted in these positions as the migration
target (previously it errored in most of them). A bare @var in a nested
declaration value -- e.g. @supports (display: @v) or @media
(min-width: @v) -- is NOT deprecated: it is a declaration value and
stays valid, detected via paren-depth awareness so parsing and output
are unchanged.

Value-position parsing is otherwise untouched: @var works, @{var} is not
newly accepted in top-level declaration values.

Migrates existing fixtures to @{var} and adds a dedicated fixture
locking in backward-compatible resolution of the bare form.

* fix: also deprecate @@variable-variable prefix in @namespace

The @namespace prefix lookahead used `@[\w-]`, which misses an indirect
`@@ref` (variable-variable) reference — entities.variable() accepts
`@@name`, so `@namespace @@ref "..."` fell through to expression() and
resolved without the deprecation warning. Widen the lookahead to
`@@?[\w-]` so @@-prefixes hit the same warning path. Adds fixture
coverage.

* Fix #4460: parse comparison/range syntax in container style() queries (#4461)

* Fix #4460: parse comparison/range syntax in container style() queries

The mediaFeature lookahead regex only matched a bare identifier
before a comparison operator (=, >, <, >=, <=), so it failed
whenever the operand was a function call, e.g. var(--n) or
calc(6/2). Widened the regex to also match a single level of
balanced parens before the operator.

Added regression tests covering:
  @container style(var(--n) = 3)
  @container style(calc(6 / 2) = var(--n))
  @container style(var(--size) > 1lh)

* Refactor parser.js for improved readability

---------

Co-authored-by: dweep <existing1.001@gmail>

* refactor: extract shared ESLint config and add lint scripts (#4459)

* refactor: extract shared ESLint config and add lint scripts

Addresses discussion #3787 by extracting shared ESLint rules to
config/eslint/base.cjs and adding lint/lint:fix npm scripts.

Changes:
- Created config/eslint/base.cjs with common ESLint rules
- Updated packages/less/.eslintrc.cjs to extend the shared config
- Added lint and lint:fix scripts to root package.json

The shared config maintains compatibility with both JS and TS
files. TypeScript-specific recommended rules are scoped to .ts
files only to avoid noise in legacy .js source files.

Verified: pnpm run lint passes with zero errors, 139/139 unit
tests pass (pre-commit hook failed only on unrelated port conflict).

* style: apply eslint --fix formatting

Auto-generated by 'pnpm run lint:fix' using the new shared config.
Touches only quote style and indentation; no logic changes.

- benchmark/benchmark-runner.js: indent
- build/rollup.js: quotes (backtick -> single)
- lib/less-node/environment.js: indent
- lib/less/tree/nested-at-rule.js: indent

* test(benchmark): add JSDoc for coverage

Addresses docstring coverage warning in PR #4459 by adding full
JSDoc to all functions in the benchmark-runner script.

* Replace image-size with probe-image-size (#4456)

* Replace image-size with probe-image-size

* validation

* Use loaded contents for image size probing

* Use loaded contents for image size probing

* chore: release v4.6.8 (#4463)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* Follow-up to #4462: migrate remaining @var fixtures, DRY the prelude bare-@var scan, add warnings coverage (#4469)

* test: migrate remaining bare @variable at-rule fixtures to @{variable}

Follow-up to #4462, which deprecated bare @variable in non-value at-rule
positions and migrated most fixtures to @{variable} but left two feature
fixtures on the bare form:
  - tests-unit/layer/layer.less             @layer @layer-name
  - tests-unit/import/import/import-reference.less  @keyframes @keyframeName
Migrated to @{layer-name} / @{keyframeName} (byte-identical render).

Also repairs pnpm-lock.yaml: master had a dangling `minimatch: 3.1.2`
dependency edge with no package entry (bad-merge artifact), so
`pnpm install --frozen-lockfile` failed for every PR. Repinned to the
resolved 3.1.5 already present; no dependency version changes.

* test: assert deprecation/warning emission + suppress warnings in test output

less.js asserts errors via tests-error/*.txt but had no coverage that warnings
actually fire, so deprecation notices were unguarded (nothing would catch a
regression that silently stopped emitting one).

- Suppress warnings from normal test output (they are noise across the corpus);
  set LESS_TEST_SHOW_WARNINGS=1 to see them.
- Add testWarnings() (run from index.js) which installs a capturing logger
  listener and asserts each render-reachable warning fires: variable-in-at-rule-
  prelude (incl. bar[@v] top-level -> warns and (x:@v) decl-value -> no warn),
  js-eval, mixin-call-whitespace, mixin-call-no-parens, variable-in-unknown-value,
  dot-slash-operator, complex-selector, extend-no-match, compress, at-plugin.

Documented gaps (not render-reachable): property-in-unknown-value (a $prop ref
resolves via the entity path before the permissive text scan), math-always and
dumpLineNumbers (registered in deprecation.js but never emitted via warn()).

* refactor(parser): fold at-rule prelude bare-@var detection into $parseUntil (DRY)

The at-rule-prelude deprecation detected a top-level bare @var two ways: the
permissiveValue entity loop (structural), plus a standalone hasTopLevelBareVariable()
that RE-SCANNED the same text $parseUntil had already walked, with its own hand-rolled
paren counter (and no string/comment handling).

Fold that second scan into $parseUntil's single pass: it already skips strings/comments/
escapes and tracks brackets, so add an opt-in `detectBareVar` that records the first bare
@var (not @{interp}) seen at PAREN depth 0 — [...]/{...} don't shield a reference, only a
declaration-value (...) does — exposed as `.bareVarIndex`. $parseUntil has a single caller
(permissiveValue), so the extra arg/property is contained. Delete hasTopLevelBareVariable.

Behaviour preserved (regression-guarded by testWarnings): @foo @bar -> 1, @a and @b -> 2,
bar[@v] -> 1 (bracket is top-level), (x:@v) -> 0 (decl value), and the mixed
(a:@x) y[@z] -> 1. Also drops the testWarnings 'variable-in-unknown-value' case: it only
fires for the inconsistent bracket edge (--x: bar[@bar]) while --x: @bar / 1px @bar /
foo(@bar) resolve silently, so asserting it would lock in an artifact (now documented).

* chore: release v4.7.0 (#4471)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* Fix boolean() parsing for comparisons between inline condition expressions (#4472)

* Initial plan

* Fix boolean comparison of inline condition expressions

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>

* fix(mixing): resolves issue #4234 (#4473)

* Fix mixin arity issue for mixins that provide a default value for
  arguments early in the list that caused wrong number of arguments
  error.

* chore: release v4.8.0 — deprecate legacy identifier forms and dynamic @charset (#4475)

* test: migrate remaining bare @variable at-rule fixtures to @{variable}

Follow-up to #4462, which deprecated bare @variable in non-value at-rule
positions and migrated most fixtures to @{variable} but left two feature
fixtures on the bare form:
  - tests-unit/layer/layer.less             @layer @layer-name
  - tests-unit/import/import/import-reference.less  @keyframes @keyframeName
Migrated to @{layer-name} / @{keyframeName} (byte-identical render).

Also repairs pnpm-lock.yaml: master had a dangling `minimatch: 3.1.2`
dependency edge with no package entry (bad-merge artifact), so
`pnpm install --frozen-lockfile` failed for every PR. Repinned to the
resolved 3.1.5 already present; no dependency version changes.

* test: assert deprecation/warning emission + suppress warnings in test output

less.js asserts errors via tests-error/*.txt but had no coverage that warnings
actually fire, so deprecation notices were unguarded (nothing would catch a
regression that silently stopped emitting one).

- Suppress warnings from normal test output (they are noise across the corpus);
  set LESS_TEST_SHOW_WARNINGS=1 to see them.
- Add testWarnings() (run from index.js) which installs a capturing logger
  listener and asserts each render-reachable warning fires: variable-in-at-rule-
  prelude (incl. bar[@v] top-level -> warns and (x:@v) decl-value -> no warn),
  js-eval, mixin-call-whitespace, mixin-call-no-parens, variable-in-unknown-value,
  dot-slash-operator, complex-selector, extend-no-match, compress, at-plugin.

Documented gaps (not render-reachable): property-in-unknown-value (a $prop ref
resolves via the entity path before the permissive text scan), math-always and
dumpLineNumbers (registered in deprecation.js but never emitted via warn()).

* refactor(parser): fold at-rule prelude bare-@var detection into $parseUntil (DRY)

The at-rule-prelude deprecation detected a top-level bare @var two ways: the
permissiveValue entity loop (structural), plus a standalone hasTopLevelBareVariable()
that RE-SCANNED the same text $parseUntil had already walked, with its own hand-rolled
paren counter (and no string/comment handling).

Fold that second scan into $parseUntil's single pass: it already skips strings/comments/
escapes and tracks brackets, so add an opt-in `detectBareVar` that records the first bare
@var (not @{interp}) seen at PAREN depth 0 — [...]/{...} don't shield a reference, only a
declaration-value (...) does — exposed as `.bareVarIndex`. $parseUntil has a single caller
(permissiveValue), so the extra arg/property is contained. Delete hasTopLevelBareVariable.

Behaviour preserved (regression-guarded by testWarnings): @foo @bar -> 1, @a and @b -> 2,
bar[@v] -> 1 (bracket is top-level), (x:@v) -> 0 (decl value), and the mixed
(a:@x) y[@z] -> 1. Also drops the testWarnings 'variable-in-unknown-value' case: it only
fires for the inconsistent bracket edge (--x: bar[@bar]) while --x: @bar / 1px @bar /
foo(@bar) resolve silently, so asserting it would lock in an artifact (now documented).

* deprecate dash-only variable names

* deprecate dynamic charset interpolation

* chore: release v4.8.0

* chore: release v4.8.0 (#4474)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Matthew Dean <[email protected]>

* fix: forwarding an unset variadic no longer overrides callee defaults (#4477)

Signed-off-by: 林晨 (Leo Cheng) <[email protected]>

* fix: leave math functions for the browser when an argument is a runtime CSS var() (#4479)

Signed-off-by: 林晨 (Leo Cheng) <[email protected]>

* fix(release): sync release version from PR title (#4483)

* fix(release): sync release version from PR title

* fix(release): harden title sync automation

* fix(release): harden title sync workflow

* fix(release): make changelog title sync idempotent

* fix(release): insert missing changelog heading on title sync

* fix(release): insert changelog heading without prior releases

* chore: release v4.8.1 (#4482)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* Less 5 alpha.1: Jess-powered compiler preview (#19)

* fix(issue#4339): limit whitespace check

* Fix issue #4339 by limiting the whitespace check for the deprecation
  notice to not produce false positives.

* fix(issue#4339): correct deprecation notice

* Correct deprecation notice for issue #4339.

* Some updated tests for Less v5

* Update various acceptance tests for new parser

* Lots of v5 syntax tweaks

* Unit test updates for v5 - atrules

* v5 updates in test expectations

* Extend stylesheet changes

* fix:(issue#4397): container query variable names

* Fix for issue #4397 container query with variable names like
  @container @foo () {}.

* Update unit tests to Less v5 engine

* Rebaseline test-data fixtures and move removed legacy JavaScript cases.

This updates expected outputs for current behavior and relocates removed inline-JavaScript and IE filter fixtures into explicit legacy/REMOVED folders to preserve historical references.

* Rebaseline import/media fixtures and skip alpha pre-commit test gate.

This updates import/media fixture expectations and moves the previous media v5 snapshot into legacy while keeping current output at media.css, and bypasses pre-commit verification on the alpha branch during broad migration work.

* test-data: update mixin fixture baselines with legacy snapshots

Capture accepted fixture output updates for mixin guard/default ordering and mixin output parity while preserving prior snapshots under legacy paths for traceability.

* Update parse-interpolation fixtures for selector capture semantics.

This removes the invalid quoted ampersand merge-template case from unit output expectations and moves it into tests-error/eval with an explicit invalid merge-template error fixture.

* Add nesting fixture variants (legacy, uncollapsed, styles.config)

* fix(test-data): update import-reference expected CSS for jess compat

Update expected output to match jess's collapseNesting behavior:
- Unwrap single-item :is() wrappers (.visible instead of :is(.visible))
- Simplify extend selectors (.visible + .visible instead of :is() form)
- Add .b { color: green; } from bare & { } (matches lessc output)

* fix(test-data): update extract-and-length expected CSS for @arguments semantics

BREAKING: @arguments no longer flattens Sequence arguments.
Passing .mixin(a b c d) to (...) gives @arguments length 1 (one Sequence),
not 4 (individual items). Previous expected output saved to legacy/.

* feat(benchmark): add historical benchmark suite for Less v2.0-v4.4

Comprehensive benchmark harness that tests every major/minor Less release
using git worktrees for isolation and fnm for Node version management.

- benchmark.less: enhanced with extend, guards, property merging, detached
  rulesets, complex nesting, color functions, loops, and more
- benchmark-v3.less: v3.6+ features (if, boolean, property lookups)
- benchmark-v37.less: v3.7+ features (each with lists/maps)
- benchmark-v39.less: v3.9+ features (range for columns/spacing)
- benchmark-runner.js: portable runner with ESM interop for v4.x
- run-historical.sh: orchestrator with per-system result tracking

Results organized as:
  results/latest/{system-id}.json   - most recent per system
  results/runs/{date}_{system-id}.json - historical archive

* feat(deprecation): add deprecation warnings for features removed in Less 5.x

New deprecation infrastructure with automatic repetition limiting (max 5 per type):
- deprecation.js: registry of deprecation IDs with descriptions
- Parser warn() accepts deprecation IDs for categorized warnings
- --quiet-deprecations: suppress only deprecation warnings (keeps other warnings)

New deprecation warnings for features being removed in 5.x:
- js-eval: inline JavaScript backtick expressions
- at-plugin: @plugin directive

Existing warnings now tagged with stable IDs:
- mixin-call-no-parens, mixin-call-whitespace, dot-slash-operator
- variable-in-unknown-value, property-in-unknown-value

CLI deprecation notices for: --js, --line-numbers, --math=always

* feat(benchmark): add historical benchmark suite with per-system result tracking

Results organized as:
  results/latest/{system-id}.json  - most recent per system
  results/runs/{date}_{system-id}.json - historical archive (gitignored)

* fix(benchmark): don't path.resolve bare package names in benchmark-runner

path.resolve('less') turns the package name into an absolute filesystem
path, preventing Node's package resolution from finding npm-installed
versions. Only resolve relative paths starting with '.'.

* fix(benchmark): use coefficient of variation instead of range for variance_pct

variance_pct was computing (max-min)/avg which is range-over-mean.
Now uses stddev/avg (coefficient of variation) which is a proper
variability statistic.

* fix(benchmark): use timestamp instead of date for run filenames

Prevents same-day runs from overwriting each other in the runs/ archive.

* fix(cli): queue deprecation warnings until after arg parsing

Deprecation warnings from flags like --js, --line-numbers, and
--math=always were printed immediately during arg parsing, so
--quiet-deprecations only worked if it appeared before the deprecated
flag. Now all CLI deprecation messages are queued and flushed after
parsing completes, respecting --silent, --quiet, and
--quiet-deprecations regardless of flag order.

* Remove duplicate length check from expression.genCSS() (#4327)

Follows-up 53f84f02bad6e, which started the conditional
with a check for `i + 1 < this.value.length`, which is the same
as the parent block.

* Remove unused `parsers.entities.propertyCurly()` (#4271)

Follows-up a38f8a1eb7beed589d2fa734fcf411cf4461d231, which introduced
this as part of implementing property accessors. The method was not
used there, and hasn't been used elsewhere since then either.

Ref https://github.com/less/less.js/pull/3163.

* Remove redundant return from `parsers.blockRuleset()` (#4265)

* chore: replace deprecated String.prototype.substr() (#3702)

.substr() is deprecated so we replace it with .slice() which works similarily but isn't deprecated

Signed-off-by: Tobias Speicher <[email protected]>

* Handle the lack of the optional dependencies (#3791)

* Handle optional dependencies

* Handle optional dependency image-size

* remove phantom stuff (#3782)

* remove phantom stuff

* lint fix

* use deep clone

* fixed bug in import subpath module (#4236)

* fix(issue#4354): unknown at-rule expression commas (#4389)

* Fix issue less#4354 unknown at-rule expressions should not have commas in
  a keyword list.
* Add some additional layer at-rule tests.

* chore: update README.md copyright (#4386)

* Update README.md copyright year.

* Fix no-prototype-builtins issues in Ruleset and ToCSSVisitor (#4404)

Co-authored-by: Timo Tijhof <[email protected]>

* chore: add test for number with underscore parsing (#4406)

In Less.js 2.6.0, parsing of dimensions changed so that `5_large`
is seen as one value, instead of as a list containing "5" and "_large".

In updating the Less.php port, we forgot to consider this change
because none of the Less.js 3.13 tests seem to cover this behavior.

Follows-up https://github.com/less/less.js/pull/2485.

This adds the test case from https://github.com/less/less.js/issues/2462,
as inpired by downstream https://gerrit.wikimedia.org/r/1197310.

Co-authored-by: Timo Tijhof <[email protected]>

* fix(#4331): exclude CSS at-rule keywords from declarationCall parsing (#4407)

* fix(#4331): exclude CSS at-rule keywords from declarationCall parsing

* fix(#4331): normalize spacing after CSS at-rule keywords in media queries

When `and`, `or`, `not`, or `only` keywords appear without a space
before `(` in media queries, ensure spacing is added in the output
to produce valid CSS.

* fix(#4358): resolve parent selectors in comma-separated pseudo-selector lists (#4408)

* refactor: code quality cleanup for container queries and related code (#4409)

* fix: correct import and error handling in style() function

- Fix incorrect import: `Anonymous` was imported from '../tree/variable'
  instead of '../tree/anonymous' (worked by accident since Variable
  was imported on the line above)
- Simplify switch/case with single case 0 to a plain if statement
- Add explanatory comment to the catch block documenting why it exists
  (CSS pass-through for @container style() queries)

* refactor: remove dead boolean logic in evalRoot()

- Remove `allAmpersands` variable that was initialized to false and
  never set to true, making it dead code
- Replace string-based ampersand detection (genCSS + regex) with
  direct element value checks, avoiding unnecessary AST-to-string
  conversion
- Simplify boolean conditions that referenced the dead variable

* fix: add missing parserInput.forget() in colorOperand

The colorOperand parser rule called parserInput.save() but only called
restore() on failure, missing the forget() call on the success path.

* refactor: QueryInParens eval() returns new node instead of mutating this

QueryInParens.eval() was mutating `this` directly instead of returning
a new node, violating the core Less.js tree pattern. It also used a
brittle queue pattern where deep copies were pushed to an `mvalues`
array during eval() and shifted off during genCSS().

Now eval() creates and returns a new QueryInParens with evaluated
children, and genCSS() reads directly from the node's properties.
The `copy-anything` import is removed from this file (still used
elsewhere in the codebase).

* refactor: extract mergeRules into shared utility to fix AtRule layering violation

AtRule.eval() was directly calling ToCSSVisitor.prototype._mergeRules,
which breaks the architectural boundary between tree nodes and visitors.

Extract the merge logic into a standalone utility (merge-rules.js) that
both AtRule.eval() and ToCSSVisitor can use without coupling.

* fix: remove Container copy-paste duplication and fix evalNested splice index bug

Container was overriding evalNested, permute, and bubbleSelectors with
identical copies of the methods already provided by NestableAtRulePrototype.
Remove the redundant overrides so Container properly inherits from the
shared prototype.

Also fix a bug in NestableAtRulePrototype.evalNested where
context.mediaBlocks.splice(i, 1) used `i` (the index into `path`) to
splice `mediaBlocks`. These are different arrays with different contents,
so the index was wrong. Use indexOf(this) to find the correct position.

* fix(benchmark): update scripts and results for v4.x compatibility

- Fix percentage() calls in benchmark .less files for parens-division
- Add --math=always passthrough to benchmark-runner.js
- Handle all v3.12+/v4.x build scenarios in run-historical.sh
  (pnpm for workspace protocol, fallback tsc, separate runtime deps)
- Use last patch of each minor version in historical suite
- Update latest benchmark results (v2.0–v4.5.1)

* perf: optimize hot paths and fix benchmark infrastructure (#4410)

* fix(benchmark): fix division in benchmark files for v4 math defaults

Wrap bare divisions inside percentage() calls in extra parens so
benchmarks work with v4's default parens-division math mode. Add
--math option passthrough to benchmark-runner.js and pass
--math=always in run-historical.sh for consistent cross-version results.

* perf: remove unnecessary closures in hot paths

- Remove `extendVisitor` alias in findMatch, use `this` directly
- Replace IIFE closure for functionRegistry lookup in Ruleset.eval
  with inline loop

~5% improvement on main benchmark (median 38.6ms → 37.1ms)

* perf: replace forEach/map closures with for loops in hot paths

- Selector.eval: replace map() closures with pre-allocated for loops
- Ruleset transformDeclaration: replace forEach with for loop
- extend-visitor visitRuleset: replace forEach with for loop, cache
  extend and pathCount to reduce repeated property access

Combined with previous commit: ~8% improvement on 104KB benchmark
(median 38.6ms → 36.4ms)

* fix(benchmark): handle all v3.12+/v4.x build scenarios

- Use pnpm for v4.3+ (workspace: protocol)
- Fallback tsc installation when npm can't install locally
- Install runtime deps separately when npm fails due to
  unpublished workspace packages (@less/test-import-module)
- Use last patch version of each minor release
- Skip v3.13.x (broken source: missing tree/util.js)

* bench: update benchmark results after hot-path optimizations

Median: 39.07ms → 34.32ms (~12% improvement)
Throughput: 2,495 KB/s → 2,828 KB/s
System: macbook-pro arm64

* bench: add historical benchmark results and track runs in git

- Add historical benchmark data (v3.5–v4.2) to results/runs/
- Update latest/ with all versions including v4.5.0-dev optimized results
- Format JSON with 2-space indentation
- Update .gitignore to track runs/ (historical records belong in git)

* bench: full historical benchmark run (v2.0–v4.5, 23 versions)

Apple M4 Pro, arm64, Node v18/v20/v24

Key findings:
- v2.4-v2.5 fastest era (~31ms median on 104KB file)
- v3.10-v3.12 massive regression (3-5x slower, 126-185ms)
- v4.0 recovered to ~40ms
- v4.2 fastest v4.x (35.4ms)
- v4.5.1 current master: 42.2ms

* bench: prune version list to significant performance changes

Reduced from 23 to 15 versions based on full benchmark data.
Dropped versions with <5% difference from their predecessor:
- v2.1 (broken), v2.5, v2.7 (plateau with v2.4/v2.6)
- v3.6–v3.9 (all within 1ms, flat ~41ms)
- v4.1 (identical to v4.0)

The full set can still be run with --versions flag.

* fix(benchmark): fix invalid CSS in benchmark.less and add Jess wrapper support

- Fix invalid CSS patterns in benchmark.less: hex-color selectors (#808080),
  bare declarations in @media, :not(1), unquoted attr values, empty margin
- Add benchmark-runner.cjs for CJS compatibility with ESM package
- Add callback support to render() in lib/index.js alongside Promise return

* feat: migrate to native ESM with no build step (#4411)

* feat: migrate to native ESM with no build step

- Rename src/ to lib/ — source files are shipped directly, no compilation
- Add "type": "module" to package.json for native ESM support (Node 18+)
- Convert bin/lessc, test files, and build scripts from CJS to ESM
- Rename Gruntfile.js and .eslintrc.js to .cjs (must remain CommonJS)
- Add .js extensions to all relative import paths for ESM resolution
- Use createRequire() for optional dependency resolution (npm packages, JSON)
- Configure TypeScript for check-only mode (noEmit: true, allowJs: true)
- Update Rollup config to read from lib/ directly
- Update CI matrix to drop Node 16 (minimum Node 18+)
- Browser build is smaller: 500KB (was 509KB), minified 153KB (was 158KB)
- All 139 tests pass

* chore: fix trailing semicolons from linter

* chore: gitignore generated .css.map files in lib/

* fix(ci): restore lts/-3 to test matrix

* chore: stop tracking dist/ build artifacts

Generated browser bundles don't need to be in source control — they're
built during publish and included in the npm package via the files field.
Removes duplicate copies from both root dist/ and packages/less/dist/.

* fix(ci): use pnpm exec for playwright install

npx doesn't reliably find binaries with pnpm. Since playwright is
already a devDependency, use pnpm exec to run the installed version.

* fix(ci): use pnpm --filter for playwright, disable fail-fast

pnpm exec at workspace root can't find playwright binary since it's a
devDependency of the less package. Use --filter to run in that context.
Also disable fail-fast so all matrix jobs complete independently.

* fix(ci): move playwright to root devDependencies

Makes pnpm exec playwright work from workspace root in CI.

* fix: upgrade copy-anything to v3 for ESM compat, fix Windows test paths

copy-anything v2 lacks "type": "module", causing named import failures
on Node 18. v3 has proper ESM exports.

Revert testFolder to absolute path (matching original behavior) so debug
test path replacements match Less compiler output on Windows.

* chore: add CodeRabbit config to raise file review limit

* fix: add files field to package.json, remove postinstall from published package

Restricts npm package to only bin/, lib/, dist/, index.js, and README.md.
Previously shipped test files, Gruntfile, eslint config, etc.
Removes postinstall script (Playwright browser install) which only applies
in the monorepo dev environment and fails when installed from npm.

Verified: npm pack --dry-run shows 120 files (was 229), lessc CLI and
API both work from a clean tarball install.

* refactor: convert prototype-based tree nodes to ES6 classes (#4412)

* refactor: convert prototype-based tree nodes to ES6 classes

Convert all 30 tree node files from `Object.assign(new Node(), {...})`
prototype pattern to proper `class extends Node` syntax. This enables
TypeScript to understand the inheritance chain, reducing checkJs errors
from 2756 to 0.

- All tree nodes now use `class X extends Node` (or appropriate parent)
- Node.type converted from instance property to getter for clean override
- Factory functions in index.js updated to use `new` instead of
  Object.create + apply (required for ES6 class compatibility)
- Benchmark script converted to ESM
- Added @types/node devDependency for checkJs support
- Enabled checkJs in tsconfig.json
- Added JSDoc types to node.js base class and several utility files

No behavioral changes - all 139 tests pass, benchmark performance
unchanged vs historical baselines (avg 36-39ms for 104KB).

* fix: @plugin deprecation says "replaced" not "removed"

* fix: use constructor params for AtRule selectors, path.resolve in benchmark

* fix: align @types/node with engines.node >=18 floor

* feat: JSDoc type annotations for all tree node files (#4413)

* feat: add JSDoc type annotations with @ts-check to all tree node files

Add proper JSDoc type annotations to all 44 files in lib/less/tree/,
enabling per-file TypeScript checking via @ts-check. No {*} or {any}
casts — all types are derived from reading the actual code.

Key changes:
- Shared types (EvalContext, CSSOutput, TreeVisitor, FileInfo, VisibilityInfo) defined in node.js
- Node.value typed as union: Node | Node[] | string | number | undefined
- Node.prototype.parse declared for parser-injected prototype property
- Constructor properties explicitly declared with proper types
- Inline casts used to narrow union types at usage sites
- Widened base class params where subclasses pass different types

Also adds typecheck to prepublishOnly and pre-commit hook to catch
regressions as more files are annotated toward global checkJs: true.

All 139 tests pass, zero TypeScript errors.

* fix: remove duplicate JSDoc type annotation in ruleset.js

* fix: pre-existing bug fixes in tree nodes (#4414)

* fix: preserve alpha 0 for fully transparent hex colors

#0000 and #00000000 parsed alpha as 0 which was treated as falsy by
the || operator, causing it to fall back to 1 (opaque). Use typeof
check instead so alpha 0 is preserved.

* fix: selector getElements callback `this` binding and forEach lint

- Capture `this._fileInfo` and `this.parse.imports` into locals before
  the plain function callback in Selector.getElements(), where `this`
  is undefined in strict mode (ES modules)
- Use explicit block in forEach to avoid implicit return of assignment

* fix: preserve full error context when rethrowing mixin call errors

The catch block in MixinCall.eval() only copied message and stack,
dropping type, extract, callLine, and other LessError fields. This
caused all mixin call errors to be reported as SyntaxError regardless
of their actual type (e.g. NameError). Use spread to preserve all
fields while still overriding index/filename to the call site.

* fix: guard functionRegistry.inherit() and fix atrule parenting

- Container and Media eval() now guard functionRegistry before calling
  .inherit(), matching mixin-definition.js defensive pattern
- AtRule constructor: remove dead setParent(selectors) on orphaned local,
  parent this.declarations and this.rules with null checks

* chore: release v4.6.0 (#4415)

* chore: prepare v4.6.0 release

- Bump version to 4.6.0 in all package.json files
- Add CHANGELOG entry for v4.6.0
- Update publish workflow: replace deprecated actions/create-release with
  gh release create, attach dist files (less.js, less.min.js) as release
  assets, bump contents permission to write
- Remove .github/** from paths-ignore (was preventing workflow updates)
- Update CONTRIBUTING.md with detailed release documentation

version: 4.6.0

* fix: publish workflow and provenance errors

- Add repository field to test-data package.json (fixes npm OIDC
  provenance verification failure)
- Skip publish workflow on forks (only run on less/less.js)
- Remove duplicate require('fs') in bump-and-publish.js
- Add language specifier to markdown code block in CONTRIBUTING.md

* fix: handle existing releases for idempotent workflow re-runs

* fix: CJS compatibility…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant