- 
          
- 
                Notifications
    You must be signed in to change notification settings 
- Fork 59
          feat: Add svelte/valid-context-access rule
          #480
        
          New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Draft
      
      
            baseballyama
  wants to merge
  13
  commits into
  sveltejs:main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
baseballyama:feat/448
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Draft
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            13 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      7e51ff3
              
                implement
              
              
                baseballyama 2c57127
              
                add changeset
              
              
                baseballyama 05f8917
              
                add test
              
              
                baseballyama a86eac8
              
                add if statement test
              
              
                baseballyama 72dffcc
              
                fix if statement and support context module
              
              
                baseballyama d7d0449
              
                fix function argument
              
              
                baseballyama 9e01170
              
                support await
              
              
                baseballyama bcdb3a9
              
                Merge remote-tracking branch 'upstream/main' into feat/448
              
              
                baseballyama 972e900
              
                refactor
              
              
                baseballyama 0f50d57
              
                refactor
              
              
                baseballyama 736e5a1
              
                support setTimeout and others
              
              
                baseballyama 6ff0994
              
                support then / catch
              
              
                baseballyama ffc0bce
              
                add tests and fix bug
              
              
                baseballyama File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "eslint-plugin-svelte": minor | ||
| --- | ||
|  | ||
| feat: Add `svelte/valid-context-access` rule | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| --- | ||
| pageClass: "rule-details" | ||
| sidebarDepth: 0 | ||
| title: "svelte/valid-context-access" | ||
| description: "context functions must be called during component initialization." | ||
| --- | ||
|  | ||
| # svelte/valid-context-access | ||
|  | ||
| > context functions must be called during component initialization. | ||
|  | ||
| - :exclamation: <badge text="This rule has not been released yet." vertical="middle" type="error"> **_This rule has not been released yet._** </badge> | ||
|  | ||
| ## :book: Rule Details | ||
|  | ||
| This rule reports where context API is called except during component initialization. | ||
|  | ||
| <ESLintCodeBlock> | ||
|  | ||
| <!--eslint-skip--> | ||
|  | ||
| ```svelte | ||
| <script> | ||
| /* eslint svelte/valid-context-access: "error" */ | ||
| import { setContext, onMount } from "svelte" | ||
|  | ||
| /** ✓ GOOD */ | ||
| setContext("answer", 42) | ||
| ;(() => { | ||
| setContext("answer", 42) | ||
| })() | ||
|  | ||
| const init = () => { | ||
| setContext("answer", 42) | ||
| } | ||
|  | ||
| init() | ||
|  | ||
| /** ✗ BAD */ | ||
| const update = () => { | ||
| setContext("answer", 42) | ||
| } | ||
|  | ||
| onMount(() => { | ||
| update() | ||
| setContext("answer", 42) | ||
| }) | ||
|  | ||
| const update2 = async () => { | ||
| await Promise.resolve() | ||
| setContext("answer", 42) | ||
| } | ||
|  | ||
| ;(async () => { | ||
| await Promise.resolve() | ||
| setContext("answer", 42) | ||
| })() | ||
| </script> | ||
| ``` | ||
|  | ||
| </ESLintCodeBlock> | ||
|  | ||
| - :warning: This rule only inspects Svelte files, not JS / TS files. | ||
|  | ||
| ## :wrench: Options | ||
|  | ||
| Nothing. | ||
|  | ||
| ## :books: Further Reading | ||
|  | ||
| - [Svelte - Docs > RUN TIME > svelte > setContext](https://svelte.dev/docs#run-time-svelte-setcontext) | ||
| - [Svelte - Docs > RUN TIME > svelte > getContext](https://svelte.dev/docs#run-time-svelte-getContext) | ||
| - [Svelte - Docs > RUN TIME > svelte > hasContext](https://svelte.dev/docs#run-time-svelte-hasContext) | ||
| - [Svelte - Docs > RUN TIME > svelte > getAllContexts](https://svelte.dev/docs#run-time-svelte-getAllContexts) | ||
|  | ||
| ## :mag: Implementation | ||
|  | ||
| - [Rule source](https://github.com/sveltejs/eslint-plugin-svelte/blob/main/src/rules/valid-context-access.ts) | ||
| - [Test source](https://github.com/sveltejs/eslint-plugin-svelte/blob/main/tests/src/rules/valid-context-access.ts) | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -1,57 +1,11 @@ | ||
| import type { TSESTree } from "@typescript-eslint/types" | ||
| import type { AST } from "svelte-eslint-parser" | ||
| import { ReferenceTracker } from "@eslint-community/eslint-utils" | ||
| import { createRule } from "../utils" | ||
| import type { RuleContext } from "../types" | ||
| import { findVariable } from "../utils/ast-utils" | ||
| import { traverseNodes } from "svelte-eslint-parser" | ||
|  | ||
| /** | ||
| * Get usage of `tick` | ||
| */ | ||
| function extractTickReferences( | ||
| context: RuleContext, | ||
| ): { node: TSESTree.CallExpression; name: string }[] { | ||
| const referenceTracker = new ReferenceTracker( | ||
| context.getSourceCode().scopeManager.globalScope!, | ||
| ) | ||
| const a = referenceTracker.iterateEsmReferences({ | ||
| svelte: { | ||
| [ReferenceTracker.ESM]: true, | ||
| tick: { | ||
| [ReferenceTracker.CALL]: true, | ||
| }, | ||
| }, | ||
| }) | ||
| return Array.from(a).map(({ node, path }) => { | ||
| return { | ||
| node: node as TSESTree.CallExpression, | ||
| name: path[path.length - 1], | ||
| } | ||
| }) | ||
| } | ||
|  | ||
| /** | ||
| * Get usage of `setTimeout`, `setInterval`, `queueMicrotask` | ||
| */ | ||
| function extractTaskReferences( | ||
| context: RuleContext, | ||
| ): { node: TSESTree.CallExpression; name: string }[] { | ||
| const referenceTracker = new ReferenceTracker( | ||
| context.getSourceCode().scopeManager.globalScope!, | ||
| ) | ||
| const a = referenceTracker.iterateGlobalReferences({ | ||
| setTimeout: { [ReferenceTracker.CALL]: true }, | ||
| setInterval: { [ReferenceTracker.CALL]: true }, | ||
| queueMicrotask: { [ReferenceTracker.CALL]: true }, | ||
| }) | ||
| return Array.from(a).map(({ node, path }) => { | ||
| return { | ||
| node: node as TSESTree.CallExpression, | ||
| name: path[path.length - 1], | ||
| } | ||
| }) | ||
| } | ||
| import { extractSvelteLifeCycleReferences } from "./reference-helpers/svelte-lifecycle" | ||
| import { extractTaskReferences } from "./reference-helpers/microtask" | ||
|  | ||
| /** | ||
| * If `node` is inside of `maybeAncestorNode`, return true. | ||
|  | @@ -400,12 +354,14 @@ export default createRule("infinite-reactive-loop", { | |
| type: "suggestion", | ||
| }, | ||
| create(context) { | ||
| const tickCallExpressions = Array.from( | ||
| extractSvelteLifeCycleReferences(context, ["tick"]), | ||
| ) | ||
| const taskReferences = Array.from(extractTaskReferences(context)) | ||
| const reactiveVariableReferences = getReactiveVariableReferences(context) | ||
| 
      Comment on lines
    
      +357
     to 
      +361
    
   There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Just I moved there lines for performance improvement. | ||
|  | ||
| return { | ||
| ["SvelteReactiveStatement"]: (ast: AST.SvelteReactiveStatement) => { | ||
| const tickCallExpressions = extractTickReferences(context) | ||
| const taskReferences = extractTaskReferences(context) | ||
| const reactiveVariableReferences = | ||
| getReactiveVariableReferences(context) | ||
| const trackedVariableNodes = getTrackedVariableNodes( | ||
| reactiveVariableReferences, | ||
| ast, | ||
|  | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| import type { TSESTree } from "@typescript-eslint/types" | ||
| import { ReferenceTracker } from "@eslint-community/eslint-utils" | ||
| import type { RuleContext } from "../../types" | ||
|  | ||
| type FunctionName = "setTimeout" | "setInterval" | "queueMicrotask" | ||
|  | ||
| /** | ||
| * Get usage of `setTimeout`, `setInterval`, `queueMicrotask` | ||
| */ | ||
| export function* extractTaskReferences( | ||
| context: RuleContext, | ||
| functionNames: FunctionName[] = [ | ||
| "setTimeout", | ||
| "setInterval", | ||
| "queueMicrotask", | ||
| ], | ||
| ): Generator<{ node: TSESTree.CallExpression; name: string }, void> { | ||
| const referenceTracker = new ReferenceTracker( | ||
| context.getSourceCode().scopeManager.globalScope!, | ||
| ) | ||
| for (const { node, path } of referenceTracker.iterateGlobalReferences({ | ||
| setTimeout: { | ||
| [ReferenceTracker.CALL]: functionNames.includes("setTimeout"), | ||
| }, | ||
| setInterval: { | ||
| [ReferenceTracker.CALL]: functionNames.includes("setInterval"), | ||
| }, | ||
| queueMicrotask: { | ||
| [ReferenceTracker.CALL]: functionNames.includes("queueMicrotask"), | ||
| }, | ||
| })) { | ||
| yield { | ||
| node: node as TSESTree.CallExpression, | ||
| name: path[path.length - 1], | ||
| } | ||
| } | ||
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| import type { TSESTree } from "@typescript-eslint/types" | ||
| import { ReferenceTracker } from "@eslint-community/eslint-utils" | ||
| import type { RuleContext } from "../../types" | ||
|  | ||
| type ContextName = "setContext" | "getContext" | "hasContext" | "getAllContexts" | ||
|  | ||
| /** Extract svelte's context API references */ | ||
| export function* extractContextReferences( | ||
| context: RuleContext, | ||
| contextNames: ContextName[] = [ | ||
| "setContext", | ||
| "getContext", | ||
| "hasContext", | ||
| "getAllContexts", | ||
| ], | ||
| ): Generator<{ node: TSESTree.CallExpression; name: string }, void> { | ||
| const referenceTracker = new ReferenceTracker( | ||
| context.getSourceCode().scopeManager.globalScope!, | ||
| ) | ||
| for (const { node, path } of referenceTracker.iterateEsmReferences({ | ||
| svelte: { | ||
| [ReferenceTracker.ESM]: true, | ||
| setContext: { | ||
| [ReferenceTracker.CALL]: contextNames.includes("setContext"), | ||
| }, | ||
| getContext: { | ||
| [ReferenceTracker.CALL]: contextNames.includes("getContext"), | ||
| }, | ||
| hasContext: { | ||
| [ReferenceTracker.CALL]: contextNames.includes("hasContext"), | ||
| }, | ||
| getAllContexts: { | ||
| [ReferenceTracker.CALL]: contextNames.includes("getAllContexts"), | ||
| }, | ||
| }, | ||
| })) { | ||
| yield { | ||
| node: node as TSESTree.CallExpression, | ||
| name: path[path.length - 1], | ||
| } | ||
| } | ||
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| import type { TSESTree } from "@typescript-eslint/types" | ||
| import { ReferenceTracker } from "@eslint-community/eslint-utils" | ||
| import type { RuleContext } from "../../types" | ||
|  | ||
| type LifeCycleName = | ||
| | "onMount" | ||
| | "beforeUpdate" | ||
| | "afterUpdate" | ||
| | "onDestroy" | ||
| | "tick" | ||
|  | ||
| /** | ||
| * Get usage of Svelte life cycle functions. | ||
| */ | ||
| export function* extractSvelteLifeCycleReferences( | ||
| context: RuleContext, | ||
| fuctionName: LifeCycleName[] = [ | ||
| "onMount", | ||
| "beforeUpdate", | ||
| "afterUpdate", | ||
| "onDestroy", | ||
| "tick", | ||
| ], | ||
| ): Generator<{ node: TSESTree.CallExpression; name: string }, void> { | ||
| const referenceTracker = new ReferenceTracker( | ||
| context.getSourceCode().scopeManager.globalScope!, | ||
| ) | ||
| for (const { node, path } of referenceTracker.iterateEsmReferences({ | ||
| svelte: { | ||
| [ReferenceTracker.ESM]: true, | ||
| onMount: { | ||
| [ReferenceTracker.CALL]: fuctionName.includes("onMount"), | ||
| }, | ||
| beforeUpdate: { | ||
| [ReferenceTracker.CALL]: fuctionName.includes("beforeUpdate"), | ||
| }, | ||
| afterUpdate: { | ||
| [ReferenceTracker.CALL]: fuctionName.includes("afterUpdate"), | ||
| }, | ||
| onDestroy: { | ||
| [ReferenceTracker.CALL]: fuctionName.includes("onDestroy"), | ||
| }, | ||
| tick: { | ||
| [ReferenceTracker.CALL]: fuctionName.includes("tick"), | ||
| }, | ||
| }, | ||
| })) { | ||
| yield { | ||
| node: node as TSESTree.CallExpression, | ||
| name: path[path.length - 1], | ||
| } | ||
| } | ||
| } | 
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I moved few functions to utils dir because I want to use these in
valid-context-accessrule.