### Markdown Image Syntax Examples Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/md/imageContents.mdx Demonstrates incorrect and correct Markdown image syntax. Incorrect examples show images with empty URLs or only fragments. Correct examples show images with valid URLs. This helps users understand the rule's purpose and how to avoid broken image links. ```markdown ![]() ``` ```markdown ![Flint Logo]() ``` ```markdown ![](#) ``` ```markdown ![](https://flint.fyi/logo.png) ``` ```markdown ![Flint Logo](https://flint.fyi/logo.png) ``` -------------------------------- ### Configure Flint with Logical and Stylistic Presets Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/md.mdx This configuration uses the recommended 'logical' and 'stylistic' presets for general Markdown linting. It applies these rules to all Markdown files recognized by Flint. This is suitable for most projects getting started with linting. ```typescript import { defineConfig, md } from "flint"; export default defineConfig({ use: [ { files: md.files.all, rules: [md.presets.logical, md.presets.stylistic], }, ], }); ``` -------------------------------- ### JSON: Example with allowKeys Configuration Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/json/keyDuplicates.mdx Illustrates JSON structures where duplicate keys are disallowed by default but are permitted when they match the configured 'allowKeys' option, such as for comments. ```json { "comment": "First comment.", "comment": "Second comment." } ``` ```json { "//": "First comment.", "//": "Second comment." } ``` -------------------------------- ### JSON Key Normalization Examples Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/json/keyNormalization.mdx Demonstrates incorrect and correct JSON object keys with regard to Unicode normalization. Incorrect examples show keys with multiple representations of characters like 'é', while correct examples use a single, normalized form. ```json { "cafe\u0301": "value" } ``` ```json { "cafè": "espresso", "cafe\u0300": "latte" } ``` ```json { "café": "value" } ``` ```json { "résumé": "document", "naïve": "approach", "piñata": "party" } ``` ```json { "simple": "value", "no_special_chars": true } ``` -------------------------------- ### Markdown Reversed Link Syntax Example Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/md/mediaSyntaxReversals.mdx Demonstrates incorrect Markdown syntax for links where the square brackets and parentheses are reversed, which will not render correctly. This is contrasted with the correct syntax. ```markdown (Flint)[https://flint.fyi] ! # (Flint)[https://flint.fyi] Check out (this link)[https://example.com] for more info. ``` -------------------------------- ### Creating a Custom Flint Plugin Source: https://context7.com/flint-fyi/flint/llms.txt Illustrates how to create a custom Flint plugin by defining its name and associating custom rules. This example shows plugins for Node.js and JSON, demonstrating rule and file glob pattern definitions. ```typescript import { createPlugin } from "@flint.fyi/core"; import assertStrict from "./rules/assertStrict.js"; import assertStyles from "./rules/assertStyles.js"; import nodeProtocols from "./rules/nodeProtocols.js"; export const node = createPlugin({ name: "Node.js", rules: [ assertStrict, assertStyles, nodeProtocols, ], }); // Plugin with file glob patterns export const json = createPlugin({ files: { all: ["**/*.json"], }, name: "JSON", rules: [keyDuplicates, keyNormalization, valueSafety], }); ``` -------------------------------- ### Specify Multiple TypeScript Files for Linting Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/configuration.mdx Shows how to configure Flint to lint multiple TypeScript files based on glob patterns. This example includes test files in both 'src' and 'test' directories. ```ts import { defineConfig, ts } from "flint"; export default defineConfig({ use: [ { files: ["src/**/*.test.*.ts", "test/**/*.ts"], rules: ts.presets.logical, }, ], }); ``` -------------------------------- ### Markdown Reversed Image Syntax Example Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/md/mediaSyntaxReversals.mdx Illustrates incorrect Markdown syntax for images with reversed brackets and parentheses, leading to rendering issues. The correct syntax is also shown for comparison. ```markdown !(A beautiful sunset)[sunset.png] ``` -------------------------------- ### Configure Flint with Browser Logical Preset Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/browser.mdx This example configures Flint to use the 'logical' preset for browser linting, focusing on common rules for bug detection and good practices in browser environments. It applies these rules to all TypeScript files. ```typescript import { browser } from "@flint.fyi/browser"; import { defineConfig, ts } from "flint"; export default defineConfig({ use: [ { files: ts.files.all, rules: browser.presets.logical, }, ], }); ``` -------------------------------- ### Correct H1 Heading Usage in HTML Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/md/headingRootDuplicates.mdx Provides an example of correct H1 tag usage in HTML, with a single H1. ```html

Single HTML Heading

Content here. ``` -------------------------------- ### Markdown Correct Label References Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/md/labelReferences.mdx Examples of correct Markdown syntax where all label references are properly defined. This ensures that links and images render as intended. ```markdown [Flint][flint] [flint]: https://flint.fyi ``` ```markdown [flint][] [flint]: https://flint.fyi ``` ```markdown ![Logo][logo] [logo]: ./logo.png ``` -------------------------------- ### Configure Flint with Browser Stylistic Strict Preset Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/browser.mdx This example configures Flint with the 'stylisticStrict' preset for browser linting. It includes advanced stylistic rules for experienced developers, applied to all TypeScript files. This preset is a superset of the 'stylistic' preset. ```typescript import { browser } from "@flint.fyi/browser"; import { defineConfig, ts } from "flint"; export default defineConfig({ use: [ { files: ts.files.all, rules: browser.presets.stylisticStrict, }, ], }); ``` -------------------------------- ### Configure and Disable TypeScript Rules Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/configuration.mdx Demonstrates how to configure specific TypeScript rules and disable others using `ts.rules`. This example disables `debuggerStatements` and configures `namespaceDeclarations`. ```ts import { defineConfig, ts } from "flint"; export default defineConfig({ use: [ { files: ts.files.all, rules: [ ts.presets.logical, ts.presets.stylistic, ts.rules({ debuggerStatements: false, namespaceDeclarations: { allowDeclarations: true, }, }), ], }, ], }); ``` -------------------------------- ### Correct for loop direction example (TypeScript) Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/ts/forDirections.mdx Provides examples of correctly structured `for` loops where the counter variable's movement aligns with the termination condition. These TypeScript snippets illustrate both ascending and descending loop patterns. ```ts for (let i = 0; i < 10; i++) { console.log(i); } ``` ```ts for (let i = 10; i >= 0; i--) { console.log(i); } ``` ```ts for (let i = 0; i < 10; i += 1) { process(i); } ``` ```ts for (let i = 10; i > 0; i -= 1) { handle(i); } ``` -------------------------------- ### Correct URL usage alternatives - TypeScript Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/browser/scriptUrls.mdx Provides examples of correct URL usage in TypeScript as alternatives to `javascript:` URLs. These include standard HTTP/HTTPS URLs, relative paths, and data URIs, which are secure and do not pose eval-related risks. ```typescript const url = "https://example.com"; ``` ```typescript const url = "http://example.com"; ``` ```typescript const url = "/page"; ``` ```typescript const data = "data:text/plain;base64,SGVsbG8="; ``` -------------------------------- ### Correct Markdown Link and Image Syntax Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/md/mediaSyntaxReversals.mdx Provides examples of correctly formatted Markdown links and images, adhering to the standard syntax of square brackets for text/alt text and parentheses for URLs/image sources. ```markdown [Flint](https://flint.fyi) ![A beautiful sunset](sunset.png) # [Flint](https://flint.fyi) Check out [this link](https://example.com) for more info. ``` -------------------------------- ### Creating a Custom Flint Rule Source: https://context7.com/flint-fyi/flint/llms.txt Defines a custom linting rule for TypeScript files using AST visitors. This example rule, 'assertStrict', checks for preferred import methods related to Node.js assertions, providing detailed messages and suggestions. ```typescript import { getTSNodeRange, typescriptLanguage } from "@flint.fyi/ts"; import * as ts from "typescript"; export default typescriptLanguage.createRule({ about: { description: "Prefer strict assertion mode from Node.js for better error messages and behavior.", id: "assertStrict", preset: "logical", }, messages: { preferStrictAssert: { primary: "Prefer importing from `node:assert/strict` or using `{ strict as assert }` from `node:assert`.", secondary: [ "In strict assertion mode, non-strict methods like `deepEqual()` behave like their strict counterparts (`deepStrictEqual()`).", "Strict mode provides better error messages with diffs and more reliable equality checks.", ], suggestions: [ "Import from `node:assert/strict` for strict assertion mode", "Use `import { strict as assert }` from `node:assert`", ], }, }, setup(context) { return { visitors: { ImportDeclaration(node: ts.ImportDeclaration, { sourceFile }) { const isAssertImport = ts.isStringLiteral(node.moduleSpecifier) && (node.moduleSpecifier.text === "assert" || node.moduleSpecifier.text === "node:assert"); if (!isAssertImport) { return; } const hasStrictImport = node.importClause?.namedBindings && ts.isNamedImports(node.importClause.namedBindings) && node.importClause.namedBindings.elements.some( el => (el.propertyName?.text ?? el.name.text) === "strict" ); if (!hasStrictImport) { context.report({ message: "preferStrictAssert", range: getTSNodeRange(node.moduleSpecifier, sourceFile), }); } }, }, }; }, }); ``` -------------------------------- ### Markdown Unused Definition Example (Correct) Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/md/definitionUses.mdx Illustrates correct Markdown usage where reference definitions are properly utilized by links, images, or are used as comments. This ensures definitions are purposeful and do not add clutter. ```markdown [Mercury][mercury] [mercury]: https://example.com/mercury/ ``` ```markdown ![Venus Image][venus] [venus]: https://example.com/venus.jpg ``` ```markdown See [docs][] and [guide][]. [docs]: https://docs.example.com [guide]: https://guide.example.com ``` ```markdown [//]: # "This is a comment 1" [//]: <> (This is a comment 2) ``` -------------------------------- ### Use Modern DOM Query Methods (TypeScript) Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/browser/nodeQueryMethods.mdx Illustrates the correct usage of modern DOM query methods, querySelector and querySelectorAll, which leverage CSS selectors for more powerful and consistent element selection. Includes an example for namespaced elements. ```typescript const element = document.querySelector("#myId"); ``` ```typescript const elements = document.querySelectorAll(".myClass"); ``` ```typescript const divs = document.querySelectorAll("div"); ``` ```typescript // For namespaced elements, use attribute selectors or specific namespaced query methods const svgElements = document.querySelectorAll('svg, [xmlns*="svg"]'); ``` -------------------------------- ### Configure Flint with YAML Logical Preset Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/yaml.mdx This code snippet configures Flint to use the 'logical' preset for linting YAML files. It's a common setup for finding bugs and enforcing good practices in most YAML files. ```TypeScript import { defineConfig, yaml } from "flint"; export default defineConfig({ use: [ { files: yaml.files.all, rules: yaml.presets.logical, }, ], }); ``` -------------------------------- ### Running Flint CLI Commands Source: https://context7.com/flint-fyi/flint/llms.txt Demonstrates how to execute Flint linting from the command line. Includes basic execution, help, version display, and enabling watch mode for continuous linting. ```bash # Run linting once on the project flint # Display help information flint --help # Show version number flint --version # Enable watch mode for continuous linting flint --watch ``` -------------------------------- ### Configure Flint with Strict Logical and Stylistic Presets Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/md.mdx This configuration uses the 'logicalStrict' and 'stylisticStrict' presets for advanced Markdown linting. It's recommended for experienced users and projects where strict adherence to logical and stylistic best practices is desired. This setup applies to all Markdown files. ```typescript import { defineConfig, md } from "flint"; export default defineConfig({ use: [ { files: md.files.all, rules: [md.presets.logicalStrict, md.presets.stylisticStrict], }, ], }); ``` -------------------------------- ### Correct Buffer Allocation (TypeScript) Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/node/bufferAllocators.mdx Shows the modern and recommended ways to create buffers using `Buffer.from()` for existing data (hex strings, arrays) and `Buffer.alloc()` for creating a zero-filled buffer of a specific size. These methods are safer and more explicit. ```typescript const buffer = Buffer.from("7468697320697320612074c3a97374", "hex"); const buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); const buffer = Buffer.alloc(10); ``` -------------------------------- ### Markdown Invalid Label References Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/md/labelReferenceValidity.mdx Demonstrates incorrect and correct Markdown syntax for label references. Incorrect examples show whitespace within the brackets, while correct examples show proper formatting. ```markdown [eslint][ ] ``` ```markdown [eslint][ ] ``` ```markdown [link][ ] ``` ```markdown [eslint][] ``` ```markdown [eslint][eslint] ``` ```markdown [link][ref] [ref]: https://example.com ``` -------------------------------- ### Correct direct function calls (TypeScript) Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/ts/functionCurryingRedundancy.mdx Illustrates the correct and preferred way to call functions in TypeScript by avoiding redundant `.call()` or `.apply()` with `null`/`undefined` context. Direct calls enhance readability and maintainability. Includes examples with meaningful context for `.call()` and `.apply()`. ```typescript function add(a: number, b: number) { return a + b; } const result = add(1, 2); ``` ```typescript const callback = (message: string) => message.toUpperCase(); callback("hello"); ``` ```typescript // Using .call() with a meaningful context const obj = { value: 10 }; function getValue() { return this.value; } const contextResult = getValue.call(obj); ``` ```typescript // Using .apply() to pass an array of arguments with context function greet(this: { name: string }, greeting: string) { return `${greeting}, ${this.name}!`; } const person = { name: "Alice" }; greet.apply(person, ["Hello"]); ``` -------------------------------- ### JSON Key Normalization Correct with NFD Form Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/json/keyNormalization.mdx Shows a JSON object key that is considered correct when the 'NFD' normalization form is enforced. This example demonstrates the expected representation of a character, contrasting with the incorrect example. ```json { "cafe\u0301": "value" } ``` -------------------------------- ### Define Flint Configuration with TypeScript Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/configuration.mdx Demonstrates how to define a Flint configuration using TypeScript and the `defineConfig` function. It specifies TypeScript files and applies logical rules. ```ts import { defineConfig, ts } from "flint"; export default defineConfig({ use: [ { files: ts.files.all, rules: ts.presets.logical, }, ], }); ``` -------------------------------- ### Incorrect alt text examples (TSX) Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/jsx/altTexts.mdx Demonstrates incorrect usage of elements that require alternative text, showing missing alt attributes or improperly defined ones. These examples highlight common mistakes that violate WCAG 1.1.1. ```tsx ``` ```tsx ``` ```tsx ``` ```tsx ``` ```tsx ``` -------------------------------- ### Avoid document.cookie with JavaScript Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/browser/documentCookies.mdx Demonstrates incorrect and correct ways to handle cookies. The incorrect examples show manual parsing and setting via `document.cookie`, while the correct examples utilize the `cookieStore` API for safer and more structured cookie operations. ```javascript const sessionId = document.cookie .split("; ") .find((row) => row.startsWith("session=")) ?.split("=")[1]; document.cookie = "theme=dark"; document.cookie = `user=${userId}; expires=${expiryDate.toUTCString()}`; ``` ```javascript const sessionId = await cookieStore.get("session"); await cookieStore.set("theme", "dark"); await cookieStore.set({ name: "user", value: userId, expires: expiryDate.getTime(), }); ``` -------------------------------- ### Incorrect for loop direction example (TypeScript) Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/ts/forDirections.mdx Demonstrates common ways a `for` loop's counter can move in the wrong direction relative to its condition, leading to unintended behavior. This TypeScript example shows incrementing counters with a decreasing condition and vice-versa. ```ts for (let i = 0; i < 10; i--) { console.log(i); } ``` ```ts for (let i = 10; i >= 0; i++) { console.log(i); } ``` ```ts for (let i = 0; i < 10; i -= 1) { process(i); } ``` ```ts const step = -2; for (let i = 0; i < 10; i += step) { handle(i); } ``` -------------------------------- ### Correct alt text examples (TSX) Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/jsx/altTexts.mdx Provides correct implementations of elements requiring alternative text, showcasing valid uses of alt attributes, empty alt attributes, and aria-label for accessibility. These examples adhere to WCAG 1.1.1 standards. ```tsx A foo ``` ```tsx ``` ```tsx ``` ```tsx Click here ``` ```tsx ``` ```tsx ``` -------------------------------- ### Configure Flint with Browser Logical and Stylistic Presets Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/browser.mdx This code snippet demonstrates how to configure Flint to use the recommended 'logical' and 'stylistic' presets for browser linting. It imports necessary modules from '@flint.fyi/browser' and 'flint', and defines the configuration to apply these presets to all TypeScript files. ```typescript import { browser } from "@flint.fyi/browser"; import { defineConfig, ts } from "flint"; export default defineConfig({ use: [ { files: ts.files.all, rules: [browser.presets.logical, browser.presets.stylistic], }, ], }); ``` -------------------------------- ### Correct JSON Values Example Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/json/valueSafety.mdx This snippet shows examples of JSON values that are considered safe for data interchange. It includes standard integers, correctly formed Unicode characters (emojis), zero values, and numbers within the safe integer range. ```json [ 123, 1234, 12345 ] ``` ```json { "emoji": "🔥" } ``` ```json { "emoji": "\ud83d\udd25" } ``` ```json [ 0, 0.0, 0 ] ``` ```json { "id": 9007199254740991 } ``` -------------------------------- ### Disallow Assignments in Return Statements (TypeScript) Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/ts/returnAssignments.mdx This snippet demonstrates the TypeScript rule that flags assignments inside return statements. It highlights how such assignments can obscure the intent of the code and potentially lead to mistakes. The incorrect examples show direct assignments, while the correct examples separate assignment from the return. ```ts function getValue() { let value; return (value = 1); } ``` ```ts function process() { let result; return (result = calculate()); } ``` ```ts const arrow = () => (value = 42); ``` ```ts function compound() { let count; return (count += 5); } ``` ```ts function getValue() { let value = 1; return value; } ``` ```ts function process() { let result = calculate(); return result; } ``` ```ts const arrow = () => { const value = 42; return value; }; ``` ```ts function compound() { let count = 0; count += 5; return count; } ``` -------------------------------- ### Configure Flint with Browser Logical Strict and Stylistic Strict Presets Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/browser.mdx This configuration shows how to set up Flint with the 'logicalStrict' and 'stylisticStrict' presets for browser linting. These presets are more comprehensive and recommended for experienced teams. The configuration applies these strict rules to all TypeScript files. ```typescript import { browser } from "@flint.fyi/browser"; import { defineConfig, ts } from "flint"; export default defineConfig({ use: [ { files: ts.files.all, rules: [browser.presets.logicalStrict, browser.presets.stylisticStrict], }, ], }); ``` -------------------------------- ### Correct autocomplete attribute usage - JSX Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/jsx/autocomplete.mdx Provides examples of correct 'autocomplete' attribute usage in JSX. These examples adhere to the HTML specification's valid tokens, ensuring proper functionality for browsers and assistive technologies. Using these values improves form completion speed and accuracy for users. ```jsx ``` ```jsx ``` ```jsx ``` ```jsx ``` ```jsx ``` -------------------------------- ### Avoid Comma Operator in TypeScript Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/ts/sequences.mdx Demonstrates the incorrect and correct ways to handle operations typically done with the comma operator. The incorrect example uses the comma operator to perform a side effect and compute a value in one line. The correct example separates these into distinct statements for improved clarity. ```ts const result = (doSideEffect(), computeValue()); ``` ```ts doSideEffect(); const result = computeValue(); ``` -------------------------------- ### Prevent Exception Parameter Reassignment (TypeScript) Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/ts/exceptionAssignments.mdx This rule prevents the reassignment of exception parameters within catch clauses. Reassigning the parameter can obscure the original error, making debugging harder. The incorrect examples show direct reassignment, while the correct examples demonstrate creating new error objects or accessing the original error's properties without reassignment. ```ts try { processData(); } catch (error) { error = new Error("Processing failed"); throw error; } ``` ```ts try { validateInput(); } catch (exception) { exception = null; console.log(exception); } ``` ```ts try { processData(); } catch (error) { const wrappedError = new Error("Processing failed"); throw wrappedError; } ``` ```ts try { validateInput(); } catch (exception) { console.log(exception.message); } ``` -------------------------------- ### Correct Constructor Usage (TypeScript) Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/ts/constructorReturns.mdx Illustrates correct TypeScript constructor patterns where no explicit value is returned, allowing the instance to be implicitly returned. Dependencies include TypeScript. Input is the constructor call, output is the properly initialized instance. ```typescript class Example { constructor() { this.value = 42; } } class SpecialValue { constructor(value: number) { if (value < 0) { throw new Error("Value must be non-negative"); } this.value = value; } ``` -------------------------------- ### TypeScript: Prevent functions from returning 'any' Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/ts/anyReturns.mdx This TypeScript code demonstrates incorrect and correct ways to handle function return types to avoid using `any`. The incorrect examples show functions returning values explicitly cast to `any` or `any[]`, or promises resolving to `any`. The correct examples show functions returning values with inferred or explicitly defined specific types, adhering to type safety principles. ```typescript function foo1() { return 1 as any; } function foo2() { return [] as any[]; } async function foo3() { return Promise.resolve({} as any); } function assignability(): Set { return new Set(); } ``` ```typescript function foo1() { return 1; } function foo2() { return []; } async function foo3() { return Promise.resolve({}); } function assignability(): Set { return new Set(); } ``` -------------------------------- ### Correct Bare URL Formatting in Markdown Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/md/bareUrls.mdx This snippet shows the correct ways to format URLs in Markdown to ensure they are recognized as clickable links. URLs should be enclosed in angle brackets (e.g., '') or formatted as standard Markdown links (e.g., '[Example Website](https://www.example.com)'). Email addresses can be formatted as mailto links. ```markdown For more info, visit For more info, visit [Example Website](https://www.example.com) Contact us at Contact us at [user@example.com](mailto:user@example.com) # Not a clickable link: `https://www.example.com/` ``` -------------------------------- ### Correct Alternatives to process.exit() Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/node/processExits.mdx Illustrates correct alternatives to `process.exit()`, such as throwing errors for unrecoverable issues or returning exit codes from CLI entry points. These methods allow for better error propagation and testability. ```typescript throw new Error("Application failed"); function main() { return 1; } async function run() { throw new Error("Fatal error"); } ``` -------------------------------- ### Avoid void Operator in TypeScript Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/ts/voidOperator.mdx This snippet demonstrates incorrect and correct usage of the 'void' operator in TypeScript. The 'void' operator evaluates an expression and returns 'undefined'. Modern JavaScript provides 'undefined' as a direct value, making 'void' often redundant. Using 'undefined' directly is clearer and more explicit. The incorrect examples show common patterns where 'void' is used unnecessarily, while the correct examples illustrate the preferred approach. ```ts const value = void 0; function process() { void doSomething(); } const callback = () => void action(); ``` ```ts const value = undefined; function process() { doSomething(); } const callback = () => { action(); return undefined; }; ``` -------------------------------- ### JSON: Example of Duplicate Keys Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/json/keyDuplicates.mdx Demonstrates an incorrect JSON structure with duplicate keys and the correct structure where only the last value for a key is retained. ```json { "value": 123, "value": 456 } ``` ```json { "value": 456 } ``` -------------------------------- ### Programmatic Linting with lintOnce Source: https://context7.com/flint-fyi/flint/llms.txt Execute linting programmatically and retrieve detailed results including reports and diagnostics. ```APIDOC ## Programmatic Linting with lintOnce ### Description Execute linting programmatically and retrieve detailed results including reports and diagnostics. ### Method `POST` (This is a conceptual API representation; the actual usage is via a function call) ### Endpoint `/flint-fyi/flint/lintOnce` ### Parameters #### Path Parameters None #### Query Parameters * `ignoreCache` (boolean) - Optional - Whether to ignore the cache. * `skipDiagnostics` (boolean) - Optional - Whether to skip generating diagnostics. #### Request Body * **configDefinition** (ProcessedConfigDefinition) - Required - The configuration definition for linting. * `filePath` (string) - Required - The path to the Flint configuration file. * `use` (Array) - Required - An array of rule configurations. * `files` (Array) - Required - Glob patterns for files to lint. * `rules` (Array) - Required - Configurations for the rules to apply. ### Request Example ```typescript import { lintOnce } from "@flint.fyi/core"; import type { ProcessedConfigDefinition, LintResults } from "@flint.fyi/core"; const configDefinition: ProcessedConfigDefinition = { filePath: "/path/to/flint.config.ts", use: [ { files: ["**/*.ts"], rules: [/* rule configurations */], }, ], }; const results: LintResults = await lintOnce(configDefinition, { ignoreCache: false, skipDiagnostics: false, }); ``` ### Response #### Success Response (200) * **filesResults** (Map) - A map where keys are file paths and values contain linting results for each file. * `reports` (Array) - An array of linting reports for the file. * `diagnostics` (Array) - An array of diagnostics for the file. #### Response Example ```json { "filesResults": [ ["path/to/file.ts", { "reports": [ { "message": "Some linting issue found.", "range": { "start": {"line": 1, "character": 0}, "end": {"line": 1, "character": 10} } } ], "diagnostics": [] }] ] } ``` ``` -------------------------------- ### Incorrect Bare URL Formatting in Markdown Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/md/bareUrls.mdx This snippet demonstrates incorrect ways to present URLs in Markdown. Bare URLs like 'https://www.example.com' or email addresses 'user@example.com' without proper formatting may not be recognized as clickable links by all Markdown processors, reducing accessibility and usability. ```markdown For more info, visit https://www.example.com Contact us at user@example.com # https://www.example.com/ ``` -------------------------------- ### Markdown Unused Definition Example (Incorrect) Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/md/definitionUses.mdx Demonstrates incorrect Markdown usage where reference definitions are created but not referenced in the document. This can lead to unnecessary clutter and confusion. ```markdown [mercury]: https://example.com/mercury/ ``` ```markdown [venus]: https://example.com/venus.jpg ``` ```markdown [mercury]: https://example.com/mercury/ [Mercury][mercury] [venus]: https://example.com/venus/ ``` -------------------------------- ### Execute Linting Programmatically with lintOnce Source: https://context7.com/flint-fyi/flint/llms.txt Programmatically execute linting tasks using the `lintOnce` function. This function accepts a configuration definition and options, returning detailed linting results including reports and diagnostics. It requires the `@flint.fyi/core` package. ```typescript import { lintOnce } from "@flint.fyi/core"; import type { ProcessedConfigDefinition, LintResults } from "@flint.fyi/core"; const configDefinition: ProcessedConfigDefinition = { filePath: "/path/to/flint.config.ts", use: [ { files: ["**/*.ts"], rules: [/* rule configurations */], }, ], }; const results: LintResults = await lintOnce(configDefinition, { ignoreCache: false, skipDiagnostics: false, }); // Access results for (const [filePath, fileResults] of results.filesResults.entries()) { console.log(`File: ${filePath}`); console.log(`Reports: ${fileResults.reports.length}`); console.log(`Diagnostics: ${fileResults.diagnostics.length}`); for (const report of fileResults.reports) { console.log(` - ${report.message} at line ${report.range.start.line}`); } } ``` -------------------------------- ### Apply Spelling Plugin to All Files Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/configuration.mdx Configures Flint to use the spelling plugin on all files being linted, in addition to linting Markdown and TypeScript files separately. This utilizes the `globs.all` helper. ```ts import { spelling } from "@flint.fyi/plugin-spelling"; import { defineConfig, globs, md, ts } from "flint"; export default defineConfig({ use: [ { files: md.files.all, rules: md.presets.logical, }, { files: ts.files.all, rules: [ts.presets.logical, ts.presets.stylistic], }, { files: globs.all, rules: spelling.presets.logical, }, ], }); ``` -------------------------------- ### Markdown Incorrect Label References Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/md/labelReferences.mdx Examples of incorrect Markdown syntax where labels are referenced but not defined. This can lead to plain text rendering instead of links or images. ```markdown [Flint][flint] ``` ```markdown [flint][] ``` ```markdown ![Logo][logo] ``` -------------------------------- ### Creating a Custom Language Source: https://context7.com/flint-fyi/flint/llms.txt Define support for a new language with custom parsing and AST traversal. ```APIDOC ## Creating a Custom Language ### Description Define support for a new language with custom parsing and AST traversal. ### Method `POST` (This is a conceptual API representation; the actual usage is via a function call) ### Endpoint `/flint-fyi/core/createLanguage` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **languageDefinition** (LanguageDefinition) - Required - The definition for the new language. * `about` (Object) - Required - Information about the language. * `name` (string) - Required - The human-readable name of the language. * `id` (string) - Required - A unique identifier for the language. * `prepare` (Function) - Required - A function that prepares the language for use. * Returns an object with `prepareFromDisk`, `prepareFromVirtual`, and `dispose` methods. * `prepareFromDisk` (Function) - Prepares a file from the disk. * Takes `filePathAbsolute` (string) as input. * Returns a `FilePreparation` object containing a `file` and `dependencies`. * `file` (object) - Contains `ast`, `sourceText`, `visit` method, and `dispose` method. * `dependencies` (Set) - A set of file paths this preparation depends on. * `prepareFromVirtual` (Function) - Prepares a file from virtual source text. * Takes `filePathAbsolute` (string) and `sourceText` (string) as input. * Returns a `FilePreparation` object similar to `prepareFromDisk`. * `dispose` (Function) - Cleans up language-level resources. ### Request Example ```typescript import { createLanguage } from "@flint.fyi/core"; import type { LanguageDefinition } from "@flint.fyi/core"; // Assume parseCustomLanguage and traverseAST are defined elsewhere // declare function parseCustomLanguage(sourceText: string): any; // declare function traverseAST(ast: any, visitors: any): void; // declare const fs: any; const languageDefinition: LanguageDefinition = { about: { name: "CustomLang", id: "customlang", }, prepare() { return { prepareFromDisk(filePathAbsolute: string) { const sourceText = fs.readFileSync(filePathAbsolute, "utf-8"); const ast = parseCustomLanguage(sourceText); return { file: { ast, sourceText, visit(visitors) { traverseAST(ast, visitors); }, dispose() { // Cleanup resources }, }, dependencies: new Set([filePathAbsolute]), }; }, prepareFromVirtual(filePathAbsolute: string, sourceText: string) { const ast = parseCustomLanguage(sourceText); return { file: { ast, sourceText, visit(visitors) { traverseAST(ast, visitors); }, dispose() { // Cleanup resources }, }, dependencies: new Set([filePathAbsolute]), }; }, dispose() { // Cleanup language-level resources }, }; }, }; export const customLanguage = createLanguage(languageDefinition); ``` ### Response #### Success Response (200) Returns the created language instance. #### Response Example (No specific JSON response example; the function returns a language instance that can be used with Flint.fyi) ``` -------------------------------- ### Configure Flint with JSON Plugin Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/json.mdx This code snippet shows how to configure Flint to use the JSON plugin, specifically applying the recommended 'logical' preset to all JSON files. It imports necessary functions from 'flint' and specifies the files and rules to be used. ```typescript import { defineConfig, json } from "flint"; export default defineConfig({ use: [ { files: json.files.all, rules: json.presets.logical, }, ], }); ``` -------------------------------- ### Incorrect JSX Fragments (TSX) Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/jsx/unnecessaryFragments.mdx Demonstrates the incorrect usage of JSX fragments. These examples show fragments wrapping a single div, a single string, or being completely empty, which are unnecessary. ```tsx const element = ( <>
Hello
); ``` ```tsx const element = <>Hello; ``` ```tsx const element = <>; ``` ```tsx const element = (
Hello
); ``` -------------------------------- ### Correct Node.js module imports with node: prefix Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/node/nodeProtocols.mdx Demonstrates the correct way to import Node.js built-in modules using the `node:` protocol prefix. This practice enhances code readability and explicitly distinguishes built-in modules from external packages. ```typescript import fs from "node:fs"; import path from "node:path"; import { readFile } from "node:fs"; import fsPromises from "node:fs/promises"; const crypto = require("node:crypto"); ``` -------------------------------- ### JSX: Invalid lang attribute example Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/jsx/langValidity.mdx Demonstrates incorrect usage of the 'lang' attribute in JSX, where empty, single-letter, numeric, or improperly formatted tags are used. These can lead to accessibility issues. ```tsx
Content
``` ```tsx
Content
``` ```tsx
Content
``` ```tsx Content ``` -------------------------------- ### Incorrect Anchor Text - JSX Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/jsx/anchorAmbiguousText.mdx This snippet demonstrates anchor elements with ambiguous text that does not clearly indicate the link's destination. Examples include 'click here', 'here', 'link', and 'read more'. ```jsx click here ``` ```jsx here ``` ```jsx link ``` ```jsx read more ``` -------------------------------- ### Configure Flint with YAML Logical and Stylistic Presets Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/yaml.mdx This configuration sets up Flint to use both the recommended logical and stylistic presets for YAML files. It imports necessary functions from 'flint' and specifies that all YAML files should be linted using these presets. ```TypeScript import { defineConfig, yaml } from "flint"; export default defineConfig({ use: [ { files: yaml.files.all, rules: [yaml.presets.logical, yaml.presets.stylistic], }, ], }); ``` -------------------------------- ### Correct window.postMessage() Calls (TypeScript) Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/browser/windowMessagingTargetOrigin.mdx Illustrates the correct usage of window.postMessage() by providing a targetOrigin, such as a specific domain ('https://example.com') or any origin ('*'). This ensures messages can be received across windows. Worker.postMessage is also shown as unaffected. ```typescript window.postMessage("message", "https://example.com"); ``` ```typescript window.postMessage("message", "*"); ``` ```typescript self.postMessage("message", "https://example.com"); ``` ```typescript parent.postMessage("message", "*"); ``` ```typescript // Worker, MessagePort, and other postMessage calls are not affected worker.postMessage("message"); ``` -------------------------------- ### Correctly Checking Object Properties with Object.hasOwn Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/ts/objectHasOwns.mdx These examples show the modern and recommended way to check if an object has its own property using Object.hasOwn(). This method is safer and more reliable than older approaches, especially for objects that do not inherit from Object.prototype. ```ts const hasKey = Object.hasOwn(obj, "key"); ``` ```ts if (Object.hasOwn(obj, "prop")) { console.log("Has property"); } ``` ```ts const result = Object.hasOwn(obj, "key"); ``` ```ts const exists = Object.hasOwn(obj, "prop"); ``` -------------------------------- ### Correct Generator Functions With Yields (TypeScript) Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/ts/generatorFunctionYields.mdx Provides examples of correctly implemented generator functions using `yield` to produce values. This includes a simple generator yielding multiple numbers and a generator creating a range of numbers. ```ts function* numbers() { yield 1; yield 2; yield 3; } ``` ```ts function* range(start: number, end: number) { for (let i = start; i < end; i++) { yield i; } } ``` ```ts class Collection { *iterator() { yield* this.items; } } ``` -------------------------------- ### Define Custom Language Support with createLanguage Source: https://context7.com/flint-fyi/flint/llms.txt Extend Flint's capabilities by defining support for a new language. This involves creating a `LanguageDefinition` object that specifies how to parse the language and traverse its Abstract Syntax Tree (AST). Requires the `@flint.fyi/core` package. ```typescript import { createLanguage } from "@flint.fyi/core"; import type { LanguageDefinition } from "@flint.fyi/core"; const languageDefinition: LanguageDefinition = { about: { name: "CustomLang", id: "customlang", }, prepare() { return { prepareFromDisk(filePathAbsolute: string) { const sourceText = fs.readFileSync(filePathAbsolute, "utf-8"); const ast = parseCustomLanguage(sourceText); return { file: { ast, sourceText, visit(visitors) { traverseAST(ast, visitors); }, dispose() { // Cleanup resources }, }, dependencies: new Set([filePathAbsolute]), }; }, prepareFromVirtual(filePathAbsolute: string, sourceText: string) { const ast = parseCustomLanguage(sourceText); return { file: { ast, sourceText, visit(visitors) { traverseAST(ast, visitors); }, dispose() { // Cleanup resources }, }, dependencies: new Set([filePathAbsolute]), }; }, dispose() { // Cleanup language-level resources }, }; }, }; export const customLanguage = createLanguage(languageDefinition); ``` -------------------------------- ### Incorrect ARIA Role Usage (TSX) Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/jsx/roleTags.mdx Demonstrates incorrect usage of ARIA roles with generic HTML elements. These examples should be refactored to use their semantic HTML equivalents for improved accessibility and browser compatibility. ```tsx
``` ```tsx
``` ```tsx ``` -------------------------------- ### Apply Stylistic Sorting Preset to All Files Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/sorting.mdx This code snippet shows a simplified configuration for the Flint sorting plugin, directly applying the 'stylistic' preset to all supported files. This is a common approach for projects aiming for consistent code formatting without complex rule customization. ```typescript import { sorting } from "@flint.fyi/sorting"; import { defineConfig } from "flint"; export default defineConfig({ use: [ { files: sorting.files.all, rules: sorting.presets.stylistic, }, ], }); ``` -------------------------------- ### Correct HTML Structure with Lang Attribute (JSX) Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/jsx/htmlLangs.mdx Shows examples of correctly implemented elements with the 'lang' attribute specified in JSX. This ensures proper language identification for assistive technologies. ```tsx Content ``` ```tsx Content ``` ```tsx Content ``` -------------------------------- ### Correct autoFocus Usage in JSX Source: https://github.com/flint-fyi/flint/blob/main/packages/site/src/content/docs/rules/jsx/autoFocusProps.mdx These code examples show the correct usage of the 'autoFocus' prop in JSX, where it is either omitted or explicitly set to 'false'. This ensures that elements do not auto-focus, improving accessibility and user experience. ```tsx