Skip to content

Conversation

eunjae-lee
Copy link
Contributor

@eunjae-lee eunjae-lee commented Jul 11, 2025

ESLint Rule: Detect this.method Context Loss in Static Methods

Summary

Adds a new ESLint rule @calcom/eslint/no-this-in-static-method that detects when this.method references in static methods will lose their context binding. This prevents runtime errors like the one found in RoleOutputMapper.ts where this.toDomainPermission was passed to .map() causing the method to lose its this context.

The rule detects 6 different patterns where context loss occurs:

  1. Callback references: items.map(this.method)
  2. Variable assignments: const fn = this.method
  3. Object properties: { prop: this.method }
  4. Array elements: [this.method]
  5. Function arguments: someFunc(this.method)
  6. Return statements: return this.method

The rule allows direct method calls (this.method()) since these preserve context, and includes auto-fix functionality that replaces this.methodName with ClassName.methodName.

Examples of what gets flagged:

class RoleOutputMapper {
  static toDomain(prismaRole: PrismaRole): Role {
    return {
      // ❌ Context loss - this.toDomainPermission becomes undefined
      permissions: prismaRole.permissions.map(this.toDomainPermission),
    };
  }
  
  static createConfig() {
    // ❌ All of these lose context
    const fn = this.toDomainPermission;
    const obj = { mapper: this.toDomainPermission };
    const arr = [this.toDomainPermission];
    someFunction(this.toDomainPermission);
    return this.toDomainPermission;
  }
}

Examples of what's allowed:

class RoleOutputMapper {
  static toDomain(prismaRole: PrismaRole): Role {
    // ✅ Direct calls preserve context
    const result = this.toDomainPermission(prismaRole.permissions[0]);
    return result;
  }
}

Review & Testing Checklist for Human

Risk Level: 🟡 Yellow - Complex AST logic with auto-fix functionality

  • Test rule against various code patterns - Run the rule on existing Cal.com code to verify it catches intended patterns without false positives
  • Verify auto-fix functionality - Test that the auto-fix correctly replaces this.methodName with ClassName.methodName and doesn't break code
  • Check for false positives - Ensure the rule doesn't flag legitimate direct method calls or other safe patterns
  • Validate rule integration - Confirm the rule is properly registered in ESLint config and works with existing Cal.com linting setup

Recommended Test Plan:

  1. Run yarn lint on the entire codebase to see what the rule catches
  2. Test the auto-fix: yarn lint --fix on a test file with violations
  3. Manually verify the rule's behavior on edge cases like nested calls, complex expressions, etc.

Diagram

%%{ init : { "theme" : "default" }}%%
graph TD
    RuleFile["packages/eslint-plugin/src/rules/<br/>no-this-in-static-method.ts"]:::major-edit
    IndexFile["packages/eslint-plugin/src/rules/<br/>index.ts"]:::minor-edit
    ConfigFile["packages/eslint-plugin/src/configs/<br/>recommended.ts"]:::minor-edit
    
    RoleMapper["packages/features/pbac/infrastructure/<br/>mappers/RoleOutputMapper.ts"]:::context
    InputService["apps/api/v2/src/ee/schedules/<br/>schedules_2024_06_11/services/<br/>input-schedules.service.ts"]:::context
    
    RuleFile -->|"exports rule"| IndexFile
    IndexFile -->|"registers rule"| ConfigFile
    ConfigFile -->|"applies to"| RoleMapper
    ConfigFile -->|"applies to"| InputService
    
    RuleFile -->|"detects violations in"| RoleMapper
    RuleFile -->|"detects violations in"| InputService
    
    subgraph Legend
        L1["Major Edit"]:::major-edit
        L2["Minor Edit"]:::minor-edit
        L3["Context/No Edit"]:::context
    end
    
    classDef major-edit fill:#90EE90
    classDef minor-edit fill:#87CEEB
    classDef context fill:#FFFFFF
Loading

Notes

  • The rule was developed iteratively based on user feedback, expanding from simple callback detection to comprehensive pattern matching
  • Found existing violations in RoleOutputMapper.ts and input-schedules.service.ts that this rule will catch
  • The rule includes sophisticated AST traversal logic to distinguish between safe and unsafe this.method usage
  • Auto-fix functionality requires careful testing to ensure it doesn't break existing code

Session Details:

…ss in static methods

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>
Copy link
Contributor

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR that start with 'DevinAI'.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment and CI monitoring

Copy link

vercel bot commented Jul 11, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

2 Skipped Deployments
Name Status Preview Comments Updated (UTC)
cal ⬜️ Ignored (Inspect) Visit Preview Jul 18, 2025 6:33pm
cal-eu ⬜️ Ignored (Inspect) Visit Preview Jul 18, 2025 6:33pm

@keithwillcode keithwillcode added consumer core area: core, team members only labels Jul 11, 2025
Copy link

delve-auditor bot commented Jul 11, 2025

No security or compliance issues detected. Reviewed everything up to 615e4d4.

Security Overview
  • 🔎 Scanned files: 3 changed file(s)
Detected Code Changes
Change Type Relevant files
Enhancement ► recommended.ts
    Add new ESLint rule for static method context
► index.ts
    Register new ESLint rule
► no-this-in-static-method.ts
    Implement new ESLint rule for static method context

Reply to this PR with @delve-auditor followed by a description of what change you want and we'll auto-submit a change to this PR to implement it.

devin-ai-integration bot and others added 2 commits July 11, 2025 11:31
…irect calls

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>
…is.method'

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>
…ction args, and returns

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>
@eunjae-lee eunjae-lee changed the title feat(eslint): add no-this-in-static-method rule to prevent context loss chore(eslint): add no-this-in-static-method rule to prevent context loss Jul 11, 2025
@eunjae-lee eunjae-lee marked this pull request as ready for review July 11, 2025 12:36
@graphite-app graphite-app bot requested a review from a team July 11, 2025 12:37
@eunjae-lee
Copy link
Contributor Author

Working well!

@dosubot dosubot bot added the 🧹 Improvements Improvements to existing features. Mostly UX/UI label Jul 11, 2025
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

cubic found 1 issue across 3 files. Review it in cubic.dev

React with 👍 or 👎 to teach cubic. Tag @cubic-dev-ai to give specific feedback.

Copy link

graphite-app bot commented Jul 11, 2025

Graphite Automations

"Add consumer team as reviewer" took an action on this PR • (07/11/25)

1 reviewer was added to this PR based on Keith Williams's automation.

"Add ready-for-e2e label" took an action on this PR • (07/18/25)

1 label was added to this PR based on Keith Williams's automation.

Copy link
Contributor

coderabbitai bot commented Jul 15, 2025

Walkthrough

A new ESLint rule, no-this-in-static-method, was introduced to the plugin. This rule detects and disallows the use of this to reference static methods within static class methods, encouraging the use of the class name instead. The rule is exported in the plugin's rules index and added to the recommended ESLint configuration with an error severity. The rule includes logic to identify problematic usages and provides an automatic fix to replace this.methodName with ClassName.methodName where applicable. No other rules or exports were modified.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/eslint-plugin/src/rules/no-this-in-static-method.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-playwright".

(The package "eslint-plugin-playwright" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-playwright@latest --save-dev

The plugin "eslint-plugin-playwright" was referenced from the config file in ".eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

packages/eslint-plugin/src/rules/index.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-playwright".

(The package "eslint-plugin-playwright" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-playwright@latest --save-dev

The plugin "eslint-plugin-playwright" was referenced from the config file in ".eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

packages/eslint-plugin/src/configs/recommended.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-playwright".

(The package "eslint-plugin-playwright" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-playwright@latest --save-dev

The plugin "eslint-plugin-playwright" was referenced from the config file in ".eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
packages/eslint-plugin/src/rules/no-this-in-static-method.ts (1)

8-28: Fix nested static methods tracking issue.

The current implementation uses a single boolean flag to track static method context, which fails when static methods are nested (e.g., a static method containing a nested class with its own static method). This creates false negatives where the rule stops detecting issues in the outer method after exiting the inner one.

Use a counter or stack-based approach instead:

-    let currentMethodIsStatic = false;
+    let staticMethodDepth = 0;
     let currentClassName = "";
+    const classNameStack: string[] = [];

     return {
       MethodDefinition(node) {
         if (node.static && node.key.type === "Identifier") {
-          currentMethodIsStatic = true;
+          staticMethodDepth++;
           if (node.parent?.type === "ClassBody" && node.parent.parent?.type === "ClassDeclaration") {
             const classNode = node.parent.parent as TSESTree.ClassDeclaration;
             if (classNode.id?.name) {
-              currentClassName = classNode.id.name;
+              classNameStack.push(classNode.id.name);
+              currentClassName = classNode.id.name;
             }
           }
         }
       },
       "MethodDefinition:exit"(node: TSESTree.MethodDefinition) {
         if (node.static) {
-          currentMethodIsStatic = false;
-          currentClassName = "";
+          staticMethodDepth--;
+          if (staticMethodDepth === 0) {
+            currentClassName = "";
+            classNameStack.length = 0;
+          } else {
+            classNameStack.pop();
+            currentClassName = classNameStack[classNameStack.length - 1] || "";
+          }
         }
       },
       MemberExpression(node) {
         if (
-          currentMethodIsStatic &&
+          staticMethodDepth > 0 &&
🧹 Nitpick comments (2)
packages/eslint-plugin/src/rules/no-this-in-static-method.ts (2)

37-61: Consider edge cases in function argument detection.

The isFunctionArgument logic excludes array methods but might miss other scenarios where context loss occurs. Consider these edge cases:

  1. Method chaining: items.map(this.method).filter(this.otherMethod)
  2. Nested function calls: Promise.resolve(this.method)
  3. Event handlers: element.addEventListener('click', this.method)

Consider expanding the detection logic or documenting known limitations:

 const isFunctionArgument =
   parent?.type === "CallExpression" &&
   parent.arguments.includes(node) &&
   !(
     parent.callee.type === "MemberExpression" &&
     parent.callee.property.type === "Identifier" &&
-    ["map", "filter", "forEach", "reduce", "find", "some", "every"].includes(
+    ["map", "filter", "forEach", "reduce", "find", "some", "every", "then", "catch", "finally"].includes(
       parent.callee.property.name
     )
   );

80-85: Enhance auto-fix safety checks.

The auto-fix implementation should validate that the replacement is safe and doesn't introduce naming conflicts.

Add safety checks for the auto-fix:

 fix(fixer) {
-  if (currentClassName && node.property.type === "Identifier") {
+  if (currentClassName && node.property.type === "Identifier") {
+    // Ensure the class name is valid and doesn't conflict
+    if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(currentClassName)) {
+      return null;
+    }
     return fixer.replaceText(node, `${currentClassName}.${node.property.name}`);
   }
   return null;
 },
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 10bf982 and 8e1b90f.

📒 Files selected for processing (3)
  • packages/eslint-plugin/src/configs/recommended.ts (1 hunks)
  • packages/eslint-plugin/src/rules/index.ts (1 hunks)
  • packages/eslint-plugin/src/rules/no-this-in-static-method.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Install dependencies / Yarn install & cache
  • GitHub Check: Security Check
🔇 Additional comments (3)
packages/eslint-plugin/src/configs/recommended.ts (1)

11-11: LGTM! Rule correctly added to recommended configuration.

The new rule is properly integrated into the recommended configuration with appropriate error severity.

packages/eslint-plugin/src/rules/index.ts (1)

11-11: LGTM! Rule correctly exported in the rules index.

The new rule export follows the established pattern and uses consistent naming.

packages/eslint-plugin/src/rules/no-this-in-static-method.ts (1)

92-107: LGTM! Rule metadata is well-structured.

The rule metadata correctly defines the rule as a problem type with error recommendation, includes clear messaging, and properly declares fixable capability.

Copy link
Member

@sean-brydon sean-brydon left a comment

Choose a reason for hiding this comment

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

Working well for me - lets double check with @calcom/foundation

Copy link
Contributor

github-actions bot commented Jul 18, 2025

E2E results are ready!

@zomars zomars merged commit 30a92a4 into main Jul 18, 2025
42 checks passed
@zomars zomars deleted the devin/1752224780-eslint-rule-static-method-context branch July 18, 2025 20:05
zomars added a commit that referenced this pull request Jul 22, 2025
…oss (#22410)

Co-authored-by: eunjae@cal.com <hey@eunjae.dev>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
Co-authored-by: Omar López <zomars@me.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
consumer core area: core, team members only 🧹 Improvements Improvements to existing features. Mostly UX/UI ready-for-e2e
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants