Awesome Cursor Rules Collection

Showing 757-768 of 2626 matches

Svelte
# Cursor Rules For Svelte 5

## Introduction

I'm using svelte 5 instead of svelte 4 here is an overview of the changes.

## Runes

### Overview

Svelte 5 introduces runes, a set of advanced primitives for controlling reactivity. The runes replace certain non-runes features and provide more explicit control over state and effects.

### $state

- **Purpose:** Declare reactive state.
- **Usage:**

```javascript
<script>let count = $state(0);</script>
```

- **Replaces:** Top-level `let` declarations in non-runes mode.
- **Class Fields:**

```javascript
class Todo {
    done = $state(false);
    text = $state();
    constructor(text) {
        this.text = text;
    }
}
```

- **Deep Reactivity:** Only plain objects and arrays become deeply reactive.

### $state.raw

- **Purpose:** Declare state that cannot be mutated, only reassigned.
- **Usage:**

```javascript
<script>let numbers = $state.raw([1, 2, 3]);</script>
```

- **Performance:** Improves with large arrays and objects.

### $state.snapshot

- **Purpose:** Take a static snapshot of $state.
- **Usage:**

```javascript
<script>
    let counter = $state({ count: 0 });

    function onClick() {
        console.log($state.snapshot(counter));
    }
</script>
```

### $derived

- **Purpose:** Declare derived state.
- **Usage:**

```javascript
<script>let count = $state(0); let doubled = $derived(count * 2);</script>
```

- **Replaces:** Reactive variables computed using `$:` in non-runes mode.

### $derived.by

- **Purpose:** Create complex derivations with a function.
- **Usage:**

```javascript
<script>
    let numbers = $state([1, 2, 3]); 
    let total = $derived.by(() => numbers.reduce((a, b) => a + b, 0));
</script>
```

### $effect

- **Purpose:** Run side-effects when values change.
- **Usage:**

```javascript
<script>
    let size = $state(50);
    let color = $state('#ff3e00');

    $effect(() => {
        const context = canvas.getContext('2d');
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.fillStyle = color;
        context.fillRect(0, 0, size, size);
    });
</script>
```

- **Replacements:** $effect replaces a substantial part of `$: {}` blocks triggering side-effects.

### $effect.pre

- **Purpose:** Run code before the DOM updates.
- **Usage:**

```javascript
<script>
    $effect.pre(() => {
        // logic here
    });
</script>
```

- **Replaces:** beforeUpdate.

### $effect.tracking

- **Purpose:** Check if code is running inside a tracking context.
- **Usage:**

```javascript
<script>
    console.log('tracking:', $effect.tracking());
</script>
```

### $props

- **Purpose:** Declare component props.
- **Usage:**

```javascript
<script>
    let { prop1, prop2 } = $props();
</script>
```

- **Replaces:** export let syntax for declaring props.

### $bindable

- **Purpose:** Declare bindable props.
- **Usage:**

```javascript
<script>
    let { bindableProp = $bindable('fallback') } = $props();
</script>
```

### $inspect

- **Purpose:** Equivalent to `console.log` but re-runs when its argument changes.
- **Usage:**

```javascript
<script>
    let count = $state(0);
    $inspect(count);
</script>
```

### $host

- **Purpose:** Retrieve the this reference of the custom element.
- **Usage:**

```javascript
<script>
    function greet(greeting) {
        $host().dispatchEvent(new CustomEvent('greeting', { detail: greeting }));
    }
</script>
```

- **Note:** Only available inside custom element components on the client-side.

## Snippets

### Explanation

Snippets, along with render tags, help create reusable chunks of markup inside your components, reducing duplication and enhancing maintainability.

### Usage

- **Definition:** Use the `#snippet` syntax to define reusable markup sections.
- **Basic Example:**

```javascript
{#snippet figure(image)}
    <figure>
        <img src={image.src} alt={image.caption} width={image.width} height={image.height} />
        <figcaption>{image.caption}</figcaption>
    </figure>
{/snippet}
```

- **Invocation:** Render predefined snippets with `@render`:

```javascript

{@render figure(image)}
```

### Scope

- **Scope Rules:** Snippets have lexical scoping rules; they are visible to everything in the same lexical scope:

```javascript
<div>
    {#snippet x()}
        {#snippet y()}...{/snippet}

        <!-- valid usage -->
        {@render y()}
    {/snippet}

    <!-- invalid usage -->
    {@render y()}
</div>

<!-- invalid usage -->
{@render x()}
```

### Component Integration

- **Direct Passing as Props:**

```javascript
<script>
    import Table from './Table.svelte';
    const fruits = [{ name: 'apples', qty: 5, price: 2 }, ...];
</script>

{#snippet header()}
    <th>fruit</th>
    <th>qty</th>
    <th>price</th>
    <th>total</th>
{/snippet}

{#snippet row(fruit)}
    <td>{fruit.name}</td>
    <td>{fruit.qty}</td>
    <td>{fruit.price}</td>
    <td>{fruit.qty * fruit.price}</td>
{/snippet}

<Table data={fruits} {header} {row} />
```

## Event Handlers

### Dispatching Events

In Svelte 5, event handlers are treated as properties, integrating them more closely with component properties.

### Basic Usage

- **Property-Based Handlers:**

```javascript
<script>
    let count = $state(0);
</script>

<button onclick={() => count++}>
    clicks: {count}
</button>
```

- **Shorthand Syntax:**

```javascript
<script>
    let count = $state(0);
    function handleClick() {
        count++;
    }
</script>

<button {handleClick}>
    clicks: {count}
</button>
```

### Component Events

- **Using Callback Props:**

```javascript
<script>
    import Pump from './Pump.svelte';
    let size = $state(15);
    let burst = $state(false);

    function reset() {
        size = 15;
        burst = false;
    }
</script>

<Pump
    inflate={(power) => { 
        size += power; 
        if (size > 75) burst = true; 
    }}
    deflate={(power) => { 
        if (size > 0) size -= power; 
    }}
/>
```

### Event Modifiers

- **Wrapper Functions:**

```javascript
<script>
    function once(fn) {
        return function(event) {
            if (fn) fn.call(this, event);
            fn = null;
        }
    }

    function preventDefault(fn) {
        return function(event) {
            event.preventDefault();
            fn.call(this, event);
        }
    }
</script>

<button onclick={once(preventDefault(handler))}>...</button>
```

## Migration Examples

### Counter Example

```javascript
// Svelte 5
<script>
    let count = $state(0);
    let double = $derived(count * 2);
    $effect(() => {
        if (count > 10) alert('Too high!');
    });
</script>

<button onclick={() => count++}> {count} / {double}</button>
```

### Tracking Dependencies

```javascript
// Svelte 5
<script>
    let a = $state(0);
    let b = $state(0);
    let sum = $derived(add());

    function add() {
        return a + b;
    }
</script>

<button onclick={() => a++}>a++</button>
<button onclick={() => b++}>b++</button>
<p>{a} + {b} = {sum}</p>
```

## SvelteKit 2 Changes

### Error Handling

```javascript
// SvelteKit 2
import { error } from '@sveltejs/kit';

function load() {
    error(500, 'something went wrong');
}
```

### Cookie Management

```javascript
// SvelteKit 2
export function load({ cookies }) {
    cookies.set(name, value, { path: '/' });
    return { response };
}
```

### Promise Handling

```javascript
// SvelteKit 2
export async function load({ fetch }) {
    const [a, b] = await Promise.all([
        fetch(...).then(r => r.json()),
        fetch(...).then(r => r.json())
    ]);
    return { a, b };
}
```

### Navigation

- External URLs now require `window.location.href = url` instead of `goto(...)`
- Paths are relative by default
- `resolveRoute` replaces `resolvePath`

### Configuration

- Server fetches are no longer trackable
- Dynamic environment variables cannot be used during prerendering
- Forms with file inputs must use `enctype="multipart/form-data"`
- `use:enhance` callbacks now use `formElement` and `formData` instead of `form` and `data`
css
golang
html
java
javascript
react
svelte
typescript
Wesley7104/Wesley7104.github.io

Used in 1 repository

Vue
// Vue 3 Composition API .cursorrules.js

// Project Configuration
const projectConfig = {
  name: "Uni-App with uView Plus",
  framework: "uni-app",
  language: "JavaScript/TypeScript",
  buildTool: "Vite",
};

// Vue 3 Composition API Best Practices
const vue3CompositionApiBestPractices = [
  "Use setup() function for component logic",
  "Utilize ref and reactive for reactive state",
  "Implement computed properties with computed()",
  "Use watch and watchEffect for side effects",
  "Implement lifecycle hooks with onMounted, onUpdated, etc.",
  "Utilize provide/inject for dependency injection",
  "Prefer composition functions over mixins",
  "Keep components small and focused",
  "Use meaningful and descriptive variable names",
  "Leverage uView Plus components for UI consistency",
];

// Recommended Folder Structure
const folderStructure = {
  root: "src/",
  directories: [
    "components/",
    "composables/",
    "views/",
    "router/",
    "store/",
    "assets/",
    "utils/",
    "types/",
    "styles/", // 新增样式目录
  ],
  mainFiles: ["App.vue", "main.js", "main.ts"],
};

// Code Generation Guidelines
const codeGenerationGuidelines = {
  componentGeneration: {
    preferredStyle: "Composition API",
    requiredImports: [
      'import { ref, reactive, computed, watch, onMounted } from "vue"',
      'import { defineComponent } from "uview-plus"', // 引入 uView Plus
    ],
    componentStructure: `
  export default defineComponent({
    name: 'ComponentName',
    props: {
      // Props definition
    },
    emits: [
      // Emitted events
    ],
    setup(props, { emit }) {
      // Component logic here
      return {
        // Exposed properties and methods
      }
    }
  })
      `,
  },
  stateManagement: {
    preferredStore: "Pinia",
    storeTemplate: `
  import { defineStore } from 'pinia'
  
  export const useStoreName = defineStore('storeName', {
    state: () => ({
      // Initial state
    }),
    getters: {
      // Computed state
    },
    actions: {
      // Methods to modify state
    }
  })
      `,
  },
  apiHandling: {
    preferredHttpClient: "Axios",
    errorHandling: "Global error interceptor",
    requestTemplate: `
  import axios from 'axios'
  
  const request = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL,
    timeout: 10000
  })
  
  request.interceptors.request.use(
    config => {
      // Add authentication token
      return config
    },
    error => Promise.reject(error)
  )
  
  request.interceptors.response.use(
    response => response.data,
    error => {
      // Global error handling
      return Promise.reject(error)
    }
  )
  
  export default request
      `,
  },
};

// Performance Optimization Guidelines
const performanceGuidelines = [
  "Use v-once for static content",
  "Implement lazy loading for routes",
  "Use keep-alive for component caching",
  "Minimize reactivity for large data sets",
  "Use functional components when possible",
  "Avoid unnecessary re-renders",
  "Utilize Unocss for atomic CSS to reduce file size and improve performance",
];

// Linting and Code Style
const lintingAndCodeStyle = {
  indentation: 2,
  quotes: "single",
  semicolon: true,
  trailingComma: "es5",
  maxLineLength: 80,
  preferredESLintConfig: "vue/recommended",
};

// Unocss Configuration
const unocssConfig = require("./unocss.config.js"); // 引用您的 Unocss 配置

// Export the configuration
module.exports = {
  projectConfig,
  vue3CompositionApiBestPractices,
  folderStructure,
  codeGenerationGuidelines,
  performanceGuidelines,
  lintingAndCodeStyle,
  unocssConfig, // 导出您的 Unocss 配置
};
eslint
html
java
javascript
nestjs
react
scss
typescript
+3 more
DylanThomass/Companion-Client

Used in 1 repository

Lua

# Neovim Plugin Lua AI Coding Agent Guidelines

You are an expert in Neovim plugins programming, with deep knowledge of its unique features and common use cases in neovim plugin Development.


## Key Principles
- Write idiomatic Lua code optimized for Neovim's runtime and API ecosystem.
- Leverage the latest Neovim APIs (`vim.api`, `vim.fn`, `vim.treesitter`, `vim.loop`, etc.).
- Use `Luals Annotations` for comprehensive API documentation and type checking.
- Ensure code is modular, maintainable, and easy to extend.
- Optimize for performance while maintaining readability and clarity.
- Neovim version is 0.10+, AVOID USE DRPRECATED API. DONT BE LAZY

---

## Lua-Specific Guidelines for Neovim Plugins

### Naming Conventions
- Use `snake_case` for variables and functions.
- Use `PascalCase` for modules or public classes.
- Use `UPPERCASE` for constants.
- Prefix private functions or variables with `_`.
- Use descriptive and purpose-revealing names.

### Code Organization
- Group related functionality into modules.
- Use `require()` for dependencies, ensuring proper file modularity.
- Keep functions local to a module unless explicitly exported.
- Separate plugin logic, configuration, and mappings into distinct files or namespaces.
- Use clear comments and `Luals Annotations` for all exported APIs.

---

## Neovim-Specific Best Practices

### API Usage
- Prefer `vim.api.nvim_*` over deprecated Vimscript commands.
- Use `vim.keymap.set()` for defining keymaps instead of `vim.api.nvim_set_keymap`.
- Manage user options with `vim.opt` and buffer-specific settings with `vim.bo` or `vim.wo`.
- Use `vim.notify()` for user notifications instead of `print()`.

### Asynchronous Operations
- Use `vim.loop` for performance-critical async tasks.
- Schedule UI updates with `vim.schedule_wrap()` or `vim.defer_fn()`.
- Avoid blocking the main thread—favor async functions when dealing with I/O or long computations.

### Luals Annotations
- Use `---@type` for type definitions.
- Document APIs with `---@param` and `---@return` for improved developer experience.
- Add `---@class` for structured objects or configurations.
- Example:
  ```lua
  --- Resize the current window.
  ---@param width number The desired width of the window.
  ---@return boolean success True if resizing was successful.
  local function resize_window(width)
      vim.api.nvim_win_set_width(0, width)
      return true
  end
  ```

---

## Error Handling
- Use `pcall` or `xpcall` for protected calls, especially when interacting with external commands.
- Provide meaningful error messages via `vim.notify`.
- Use `assert()` for preconditions and validate user input explicitly.


---


## Documentation
- Use `Luals Annotations` extensively to define types, parameters, and return values.
- Maintain `README.md` with clear setup instructions and usage examples.
- Use `help` files for in-editor documentation (`:help myplugin`).


---

## Common Patterns
- Use `require('myplugin.module')` for modular design.
- Define lazy-loaded autocommands and keymaps in `plugin/*.lua` files.
- Create extensible configurations:
  ```lua
  local M = {}
  M.config = {
      option1 = true,
      option2 = "default",
  }

  function M.setup(user_config)
      M.config = vim.tbl_deep_extend("force", M.config, user_config or {})
  end

  return M
  ```
## Deprecated API


Nvim                                                             *deprecated*

The items listed below are deprecated: they will be removed in the future.
They should not be used in new scripts, and old scripts should be updated.

==============================================================================
Deprecated features

------------------------------------------------------------------------------
DEPRECATED IN 0.11					*deprecated-0.11*

API
• nvim_subscribe()	Plugins must maintain their own "multicast" channels list.
• nvim_unsubscribe()	Plugins must maintain their own "multicast" channels list.

DIAGNOSTICS
• *vim.diagnostic.goto_next()*	Use |vim.diagnostic.jump()| with `{count=1, float=true}` instead.
• *vim.diagnostic.goto_prev()*	Use |vim.diagnostic.jump()| with `{count=-1, float=true}` instead.
• *vim.diagnostic.get_next_pos()* Use the "lnum" and "col" fields from the
				return value of |vim.diagnostic.get_next()| instead.
• *vim.diagnostic.get_prev_pos()* Use the "lnum" and "col" fields from the
				return value of |vim.diagnostic.get_prev()| instead.
• The "win_id" parameter used by various functions is deprecated in favor of
  "winid" |winid|
• |vim.diagnostic.JumpOpts| renamed its "cursor_position" field to "pos".

HIGHLIGHTS
• *TermCursorNC*	Unfocused |terminal| windows do not have a cursor.

LSP
• *vim.lsp.util.jump_to_location*	Use |vim.lsp.util.show_document()| with
					`{focus=true}` instead.
• *vim.lsp.buf.execute_command*		Use |Client:exec_cmd()| instead.
• *vim.lsp.buf.completion*		Use |vim.lsp.completion.trigger()| instead.
• vim.lsp.buf_request_all		The `error` key has been renamed to `err` inside
					the result parameter of the handler.
• *vim.lsp.with()*			Pass configuration to equivalent
					functions in `vim.lsp.buf.*`.
• |vim.lsp.handlers| Does not support client-to-server response handlers. Only
  supports server-to-client requests/notification handlers.
• *vim.lsp.handlers.signature_help()*	Use |vim.lsp.buf.signature_help()| instead.
• `client.request()`			Use |Client:request()| instead.
• `client.request_sync()`		Use |Client:request_sync()| instead.
• `client.notify()`			Use |Client:notify()| instead.
• `client.cancel_request()`		Use |Client:cancel_request()| instead.
• `client.stop()`			Use |Client:stop()| instead.
• `client.is_stopped()`			Use |Client:is_stopped()| instead.
• `client.supports_method()`		Use |Client:supports_method()| instead.
• `client.on_attach()`			Use |Client:on_attach()| instead.
• `vim.lsp.start_client()`		Use |vim.lsp.start()| instead.

LUA
• vim.region()		Use |getregionpos()| instead.
• *vim.highlight*	Renamed to |vim.hl|.
• vim.validate(opts: table) Use form 1. See |vim.validate()|.

TREESITTER
• *TSNode:child_containing_descendant()* Use |TSNode:child_with_descendant()|
  instead; it is identical except that it can return the descendant itself.

VIMSCRIPT
• *termopen()* Use |jobstart() with `{term: v:true}`.

------------------------------------------------------------------------------
DEPRECATED IN 0.10					*deprecated-0.10*

API
• *nvim_buf_get_option()*	Use |nvim_get_option_value()| instead.
• *nvim_buf_set_option()*	Use |nvim_set_option_value()| instead.
• *nvim_call_atomic()*		Use |nvim_exec_lua()| instead.
• *nvim_get_option()*		Use |nvim_get_option_value()| instead.
• *nvim_set_option()*		Use |nvim_set_option_value()| instead.
• *nvim_win_get_option()*	Use |nvim_get_option_value()| instead.
• *nvim_win_set_option()*	Use |nvim_set_option_value()| instead.

CHECKHEALTH
• *health#report_error* *vim.health.report_error()*	Use |vim.health.error()| instead.
• *health#report_info* *vim.health.report_info()*	Use |vim.health.info()| instead.
• *health#report_ok* *vim.health.report_ok()*		Use |vim.health.ok()| instead.
• *health#report_start* *vim.health.report_start()*	Use |vim.health.start()| instead.
• *health#report_warn* *vim.health.report_warn()*	Use |vim.health.warn()| instead.

DIAGNOSTICS
• Configuring |diagnostic-signs| using |:sign-define| or |sign_define()|. Use
  the "signs" key of |vim.diagnostic.config()| instead.
• vim.diagnostic functions:
  • *vim.diagnostic.disable()*		Use |vim.diagnostic.enable()|
  • *vim.diagnostic.is_disabled()*	Use |vim.diagnostic.is_enabled()|
  • Legacy signature: `vim.diagnostic.enable(buf:number, namespace:number)`

LSP
• *vim.lsp.util.get_progress_messages()*	Use |vim.lsp.status()| instead.
• *vim.lsp.get_active_clients()*		Use |vim.lsp.get_clients()| instead.
• *vim.lsp.for_each_buffer_client()*		Use |vim.lsp.get_clients()| instead.
• *vim.lsp.util.trim_empty_lines()*		Use |vim.split()| with `trimempty` instead.
• *vim.lsp.util.try_trim_markdown_code_blocks()*
• *vim.lsp.util.set_lines()*
• *vim.lsp.util.extract_completion_items()*
• *vim.lsp.util.parse_snippet()*
• *vim.lsp.util.text_document_completion_list_to_complete_items()*
• *vim.lsp.util.lookup_section()*		Use |vim.tbl_get()| instead: >
						local keys = vim.split(section, '.', { plain = true })
						local  vim.tbl_get(table, unpack(keys))

LUA
• *vim.loop*				Use |vim.uv| instead.
• *vim.tbl_add_reverse_lookup()*
• *vim.tbl_flatten()*			Use |Iter:flatten()| instead.
• *vim.tbl_islist()*			Use |vim.islist()| instead.

OPTIONS
• The "term_background" UI option |ui-ext-options| is deprecated and no longer
  populated. Background color detection is now performed in Lua by the Nvim
  core, not the TUI.

TREESITTER
• *LanguageTree:for_each_child()*	Use |LanguageTree:children()| (non-recursive) instead.


------------------------------------------------------------------------------
DEPRECATED IN 0.9					*deprecated-0.9*

API
• *nvim_get_hl_by_name()*		Use |nvim_get_hl()| instead.
• *nvim_get_hl_by_id()*			Use |nvim_get_hl()| instead.

TREESITTER
• *vim.treesitter.language.require_language()*	Use |vim.treesitter.language.add()| instead.
• *vim.treesitter.get_node_at_pos()*		Use |vim.treesitter.get_node()| instead.
• *vim.treesitter.get_node_at_cursor()*		Use |vim.treesitter.get_node()|
						and |TSNode:type()| instead.
• The following top level Treesitter functions have been moved:
  • *vim.treesitter.inspect_language()*    -> |vim.treesitter.language.inspect()|
  • *vim.treesitter.get_query_files()*     -> |vim.treesitter.query.get_files()|
  • *vim.treesitter.set_query()*           -> |vim.treesitter.query.set()|
  • *vim.treesitter.query.set_query()*     -> |vim.treesitter.query.set()|
  • *vim.treesitter.get_query()*           -> |vim.treesitter.query.get()|
  • *vim.treesitter.query.get_query()*     -> |vim.treesitter.query.get()|
  • *vim.treesitter.parse_query()*         -> |vim.treesitter.query.parse()|
  • *vim.treesitter.query.parse_query()*   -> |vim.treesitter.query.parse()|
  • *vim.treesitter.add_predicate()*       -> |vim.treesitter.query.add_predicate()|
  • *vim.treesitter.add_directive()*       -> |vim.treesitter.query.add_directive()|
  • *vim.treesitter.list_predicates()*     -> |vim.treesitter.query.list_predicates()|
  • *vim.treesitter.list_directives()*     -> |vim.treesitter.query.list_directives()|
  • *vim.treesitter.query.get_range()*     -> |vim.treesitter.get_range()|
  • *vim.treesitter.query.get_node_text()* -> |vim.treesitter.get_node_text()|

LUA
  • *nvim_exec()*				Use |nvim_exec2()| instead.
  • *vim.pretty_print()*			Use |vim.print()| instead.


------------------------------------------------------------------------------
DEPRECATED IN 0.8 OR EARLIER

API
• *nvim_buf_clear_highlight()*	Use |nvim_buf_clear_namespace()| instead.
• *nvim_buf_set_virtual_text()*	Use |nvim_buf_set_extmark()| instead.
• *nvim_command_output()*	Use |nvim_exec2()| instead.
• *nvim_execute_lua()*		Use |nvim_exec_lua()| instead.
• *nvim_get_option_info()*	Use |nvim_get_option_info2()| instead.

COMMANDS
• *:rv* *:rviminfo*		Deprecated alias to |:rshada| command.
• *:wv* *:wviminfo*		Deprecated alias to |:wshada| command.

ENVIRONMENT VARIABLES
• *$NVIM_LISTEN_ADDRESS*
  • Deprecated way to:
    • set the server name (use |--listen| or |serverstart()| instead)
    • get the server name (use |v:servername| instead)
    • detect a parent Nvim (use |$NVIM| instead)
  • Ignored if --listen is given.
  • Unset by |terminal| and |jobstart()| unless explicitly given by the "env"
    option. Example: >vim
	call jobstart(['foo'], { 'env': { 'NVIM_LISTEN_ADDRESS': v:servername  } })
<

EVENTS
• *BufCreate*		Use |BufAdd| instead.
• *EncodingChanged*	Never fired; 'encoding' is always "utf-8".
• *FileEncoding*	Never fired; equivalent to |EncodingChanged|.
• *GUIEnter*		Never fired; use |UIEnter| instead.
• *GUIFailed*		Never fired.

KEYCODES
• *<MouseDown>*		Use <ScrollWheelUp> instead.
• *<MouseUp>*		Use <ScrollWheelDown> instead.

HIGHLIGHTS
• *hl-VertSplit*	Use |hl-WinSeparator| instead.

LSP DIAGNOSTICS
For each of the functions below, use the corresponding function in
|vim.diagnostic| instead (unless otherwise noted). For example, use
|vim.diagnostic.get()| instead of |vim.lsp.diagnostic.get()|.

• *vim.lsp.diagnostic.clear()*		Use |vim.diagnostic.hide()| instead.
• *vim.lsp.diagnostic.disable()*          Use |vim.diagnostic.enable()| instead.
• *vim.lsp.diagnostic.display()*	Use |vim.diagnostic.show()| instead.
• *vim.lsp.diagnostic.enable()*
• *vim.lsp.diagnostic.get()*
• *vim.lsp.diagnostic.get_all()*	Use |vim.diagnostic.get()| instead.
• *vim.lsp.diagnostic.get_count()*	Use |vim.diagnostic.count()| instead.
• *vim.lsp.diagnostic.get_line_diagnostics()* Use |vim.diagnostic.get()| instead.
• *vim.lsp.diagnostic.get_next()*
• *vim.lsp.diagnostic.get_next_pos()*
• *vim.lsp.diagnostic.get_prev()*
• *vim.lsp.diagnostic.get_prev_pos()*
• *vim.lsp.diagnostic.get_virtual_text_chunks_for_line()* No replacement. Use
  options provided by |vim.diagnostic.config()| to customize virtual text.
• *vim.lsp.diagnostic.goto_next()*
• *vim.lsp.diagnostic.goto_prev()*
• *vim.lsp.diagnostic.redraw()*		Use |vim.diagnostic.show()| instead.
• *vim.lsp.diagnostic.reset()*
• *vim.lsp.diagnostic.save()*		Use |vim.diagnostic.set()| instead.
• *vim.lsp.diagnostic.set_loclist()*	Use |vim.diagnostic.setloclist()| instead.
• *vim.lsp.diagnostic.set_qflist()*	Use |vim.diagnostic.setqflist()| instead.
• *vim.lsp.diagnostic.show_line_diagnostics()* Use |vim.diagnostic.open_float()| instead.
• *vim.lsp.diagnostic.show_position_diagnostics()* Use |vim.diagnostic.open_float()| instead.

The following are deprecated without replacement. These functions are moved
internally and are no longer exposed as part of the API. Instead, use
|vim.diagnostic.config()| and |vim.diagnostic.show()|.

• *vim.lsp.diagnostic.set_signs()*
• *vim.lsp.diagnostic.set_underline()*
• *vim.lsp.diagnostic.set_virtual_text()*

LSP FUNCTIONS
• *vim.lsp.buf.server_ready()*
  Use |LspAttach| instead, depending on your use-case. "Server ready" is not
  part of the LSP spec, so the Nvim LSP client cannot meaningfully implement
  it. "Ready" is ambiguous because:
  • Language servers may finish analyzing the workspace, but edits can always
    re-trigger analysis/builds.
  • Language servers can serve some requests even while processing changes.
• *vim.lsp.buf.range_code_action()*		Use |vim.lsp.buf.code_action()| with
						the `range` parameter.
• *vim.lsp.util.diagnostics_to_items()*		Use |vim.diagnostic.toqflist()| instead.
• *vim.lsp.util.set_qflist()*			Use |setqflist()| instead.
• *vim.lsp.util.set_loclist()*			Use |setloclist()| instead.
• *vim.lsp.buf_get_clients()*			Use |vim.lsp.get_clients()| with
						{buffer=bufnr} instead.
• *vim.lsp.buf.formatting()*			Use |vim.lsp.buf.format()| with
						{async=true} instead.
• *vim.lsp.buf.formatting_sync()*		Use |vim.lsp.buf.format()| with
						{async=false} instead.
• *vim.lsp.buf.range_formatting()*		Use |vim.lsp.formatexpr()|
						or |vim.lsp.buf.format()| instead.

LUA
• vim.register_keystroke_callback()	Use |vim.on_key()| instead.

NORMAL COMMANDS
• *]f* *[f*		Same as "gf".

OPTIONS
• *cpo-<* *:menu-<special>* *:menu-special* *:map-<special>* *:map-special*
  `<>` notation is always enabled.
• *'fe'*		'fenc'+'enc' before Vim 6.0; no longer used.
• *'highlight'* *'hl'*	Names of builtin |highlight-groups| cannot be changed.
• *'langnoremap'*	Deprecated alias to 'nolangremap'.
• 'sessionoptions'	Flags "unix", "slash" are ignored and always enabled.
• *'vi'*
• 'viewoptions'		Flags "unix", "slash" are ignored and always enabled.
• *'viminfo'*		Deprecated alias to 'shada' option.
• *'viminfofile'*	Deprecated alias to 'shadafile' option.
• *'paste'* *'nopaste'*	Just Paste It.™  The 'paste' option is obsolete:
			|paste| is handled automatically when you paste text
			using your terminal's or GUI's paste feature
			(CTRL-SHIFT-v, CMD-v (macOS), middle-click, …).
			Enables "paste mode":
			  • Disables mappings in Insert, Cmdline mode.
			  • Disables abbreviations.
			  • Resets 'autoindent' 'expandtab' 'revins' 'ruler'
			    'showmatch' 'smartindent' 'smarttab' 'softtabstop'
			    'textwidth' 'wrapmargin'.
			  • Treats 'formatoptions' as empty.
			  • Disables the effect of these options:
			    • 'cindent'
			    • 'indentexpr'
			    • 'lisp'

UI EXTENSIONS
• *ui-wildmenu*		Use |ui-cmdline| with |ui-popupmenu| instead. Enabled
			by the `ext_wildmenu` |ui-option|. Emits these events:
			• `["wildmenu_show", items]`
			• `["wildmenu_select", selected]`
			• `["wildmenu_hide"]`
• *term_background*	Unused. The terminal background color is now detected
			by the Nvim core directly instead of the TUI.

VARIABLES
• *b:terminal_job_pid*	Use `jobpid(&channel)` instead.
• *b:terminal_job_id*	Use `&channel` instead. To access in non-current buffer:
			• Lua: `vim.bo[bufnr].channel`
			• Vimscript: `getbufvar(bufnr, '&channel')`

VIMSCRIPT
• *buffer_exists()*	Obsolete name for |bufexists()|.
• *buffer_name()*	Obsolete name for |bufname()|.
• *buffer_number()*	Obsolete name for |bufnr()|.
• *file_readable()*	Obsolete name for |filereadable()|.
• *highlight_exists()*	Obsolete name for |hlexists()|.
• *highlightID()*	Obsolete name for |hlID()|.
• *inputdialog()*	Use |input()| instead.
• *jobclose()*		Obsolete name for |chanclose()|
• *jobsend()*		Obsolete name for |chansend()|
• *last_buffer_nr()*	Obsolete name for bufnr("$").
• *rpcstart()*		Use |jobstart()| with `{'rpc': v:true}` instead.
• *rpcstop()*		Use |jobstop()| instead to stop any job, or
			`chanclose(id, "rpc")` to close RPC communication
			without stopping the job. Use chanclose(id) to close
			any socket.



    
golang
less
lua
makefile

First seen in:

kentchiu/aider.nvim

Used in 1 repository

Python
You are an expert software engineer specializing in full-stack development for news/content aggregation applications, with deep expertise in:

Frontend:
- Next.js (App Router)
- TypeScript
- Tailwind CSS
- React Server Components
- Modern React patterns and hooks

Backend:
- Python/FastAPI
- Discord API integration
- AI/LLM integration (Claude/Anthropic)
- Async programming

## Code Style and Structure

### Frontend Principles
- Prefer Server Components unless client interactivity is needed
- Use TypeScript with strict type checking
- Follow functional programming patterns
- Implement proper error boundaries and loading states
- Structure components logically: pages, components, types, utils

### Backend Principles
- Use async/await for all Discord and AI operations
- Implement proper error handling and logging
- Cache responses where appropriate
- Rate limit external API calls
- Validate all incoming data

### Naming Conventions
- React components: PascalCase (MessageList.tsx)
- Utilities/hooks: camelCase (useMessages.ts)
- Types/interfaces: PascalCase with descriptive names (DiscordMessage)
- API routes: kebab-case (/api/channel-summary)
- Python files: snake_case (discord_client.py)

### File Organization
```
frontend/
  ├── app/             # Next.js pages and layouts
  ├── components/      # Reusable React components
  ├── types/          # TypeScript type definitions
  ├── utils/          # Helper functions and hooks
  └── public/         # Static assets

backend/
  ├── ai/             # AI/summarization logic
  ├── scraping/       # Discord integration
  └── api/            # FastAPI routes
```

## Best Practices

### Discord Integration
- Handle rate limits gracefully
- Cache message history appropriately
- Implement proper error handling for API calls
- Use webhook URLs securely

### AI Summarization
- Implement proper prompt engineering
- Handle token limits and chunking
- Provide fallbacks for API failures
- Cache summaries when possible

### Security
- Never expose API keys in client code
- Validate and sanitize all user input
- Implement proper CORS policies
- Use environment variables for sensitive data

### Performance
- Implement proper loading states
- Use pagination for large datasets
- Cache API responses where appropriate
- Optimize image and asset loading

### Error Handling
- Implement proper error boundaries
- Log errors with sufficient context
- Provide user-friendly error messages
- Handle edge cases gracefully

Remember: Focus on delivering a reliable, performant news summarization experience while maintaining clean, maintainable code and proper handling of external APIs (Discord and Claude).
css
fastapi
html
javascript
less
next.js
python
react
+2 more
ghsaboias/discord-summarizer

Used in 1 repository

TypeScript
You are not to make sql migration files directly. Simply update the schema file and I can run the migration.

we use drizzle-kit, so pnpm drizzle-kit generate will generate the migration file, and pnpm drizzle-kit migrate will push the migration to the database.

So do not write any sql migration files.

If I tell you to do something, do it. Do not ask for confirmation.

Make sure to avoid ambiguous sql statements. It happens a lot so be as specific as possible. Never be implicit, this is a database. Come on now.

Follow existing code style for the schema, views, and tables.

When you write raw sql to be inserted into the database to see what it's in it, make sure you return all in one row.

Additionally, use drizzle syntax for sql statements.

Do not use the active column in the effectiveRestakesView view for anything ever. It is soon to be removed.

// Restake System Rules:
// 1. Restakes are commitments to change one's mind about a parent point IF a negation is true
// 2. Slashes are fulfillments of that commitment - admitting the negation changed your mind
// 3. Doubts bet on restakers following through on their commitments

// Implementation Rules:
// 1. For UI visibility, check slashedAmount < originalAmount
// 2. totalRestakeAmount Rules:
//    - Sum of all effectiveAmounts from non-fully-slashed restakes for a point-negation pair
//    - Used as the maximum amount that can be doubted
//    - Excludes restakes where slashedAmount >= originalAmount
//    - Includes both the user's own restakes and others' restakes
//    - Reduced by slashes but not by existing doubts
// 3. For restake visibility, check amount > 0 && slashedAmount < originalAmount
// 4. Doubts are immutable once placed, can only be reduced by slashes
// 5. When calculating effectiveAmount, account for both slashes and doubts
// 6. Hide fully slashed restakes (slashedAmount >= originalAmount) from UI entirely

// Query Rules:
// 1. When calculating totalRestakeAmount:
//    SELECT SUM(effectiveAmount) 
//    WHERE slashedAmount < originalAmount
//    AND pointId/negationId match the point-negation pair
// 2. Viewer-specific data must be clearly separated in query structure
// 3. Global totals must be calculated independently of viewer context
// 4. Ownership flags must be explicitly calculated using userId equality
// 5. All amounts must use COALESCE to handle NULL values consistently

// Core System Rules:
// 1. Points are arguments, negations are counterarguments
// 2. Negations alone don't change minds - restakes make that commitment
// 3. Restaking costs cred immediately but grants favor bonus to parent point
// 4. Slashing removes favor bonus and punishes doubters but costs no additional cred
// 5. Doubters bet against restakers admitting they're wrong
// 6. Multiple doubts don't stack in reducing favor (uses max(slashed, doubted))
// 7. Restakes specifically commit to changing mind about parent point endorsement
// 8. Favor bonus shows extra conviction by stating change conditions
// 9. Endorsement amount limits restake amount on parent point
// 10. Endorsement reductions can affect existing restakes

// Component Detection Rules:
// 1. PointCard:
//    - Shows current states only
//    - Displays restake/doubt icons based on amount > 0 && slashedAmount < originalAmount
//    - Uses totalRestakeAmount for doubt possibility
//    - Delegates state changes to RestakeDialog
//    - Never handles transitions directly
//    - Shows restake icon when restake exists and isn't fully slashed
//    - Shows doubt icon when doubt amount exists
//    - Enables doubt interaction if totalRestakeAmount > 0
//    - Checks endorsement amount for restake possibility
//    - Hides restake option if no parent point endorsement
// 2. RestakeDialog:
//    - Handles full state lifecycle
//    - Manages three modes: restaking, slashing, doubting
//    - Enforces system rules and limits
//    - Calculates state transitions and their impacts
//    - Validates all state changes
//    - Handles proportional doubt reductions on slash
//    - Enforces doubt immutability
//    - Manages favor impact calculations
//    - Shows warnings for state-specific conditions
//    - Tracks endorsement reductions
//    - Handles partial slash calculations
//    - Enforces endorsement-based restake limits
//    - Shows endorsement reduction warnings
//    - Explains favor bonus mechanics
//    - Clarifies slash vs doubt implications

// Economic Rules:
// 1. Restaking:
//    - Costs cred immediately on placement
//    - Grants favor bonus to parent point
//    - Bonus reduced by max(slashed, doubted)
//    - Represents commitment to change mind
//    - Shows intellectual honesty by stating change conditions
//    - Cannot be increased after placement
//    - Can be slashed partially or fully
//    - Limited by parent point endorsement
//    - Demonstrates extra conviction in parent point
// 2. Doubting:
//    - Bets against restaker integrity
//    - Wins if restaker doesn't slash
//    - Loses proportionally if restaker slashes
//    - Immutable after placement
//    - Limited by totalRestakeAmount
//    - Multiple doubts share proportional losses
//    - Cannot be modified even by owner
//    - Forces choice between ego and integrity
// 3. Slashing:
//    - Costs no additional cred
//    - Removes favor bonus
//    - Punishes doubters proportionally
//    - Can be partial or complete
//    - Represents admission of changed mind
//    - Reduces all doubts proportionally
//    - Shows intellectual integrity
//    - Often motivated by already-lost favor from doubts

// Favor Calculation Rules:
// 1. Base favor from point/negation cred ratio
// 2. Restake bonus added to parent point
// 3. Bonus reduced by max(slashed, doubted)
// 4. Multiple doubts don't stack
// 5. Slashes permanently reduce favor
// 6. Favor impact immediate on restake
// 7. Favor reduced before slash if doubted
// 8. Endorsement changes can affect favor calculation
// 9. Parent point gets favor bonus from restake commitment

// State Transition Rules:
// 1. Restakes:
//    - Start with full amount and favor
//    - Can only decrease through slashing
//    - Cannot be undone or increased
//    - Must respect endorsement limits
// 2. Doubts:
//    - Immutable after placement
//    - Only reduced by slashes
//    - Cannot be voluntarily removed
//    - Force restaker choice between ego/integrity
// 3. Slashes:
//    - Can be partial or complete
//    - Trigger doubt reductions
//    - Remove favor proportionally
//    - Cannot be undone
//    - Often motivated by doubt-reduced favor

// Incentive Structure Rules:
// 1. Intellectual Honesty:
//    - Restaking shows willingness to change mind
//    - Slashing demonstrates follow-through
//    - Doubting keeps restakers accountable
//    - Extra conviction shown through restake commitment
// 2. Economic Balance:
//    - Immediate cred cost for restaking
//    - Favor bonus as reward for honesty
//    - Doubt potential as risk factor
//    - Endorsement limits as natural constraint
// 3. Game Theory:
//    - Slashing decision balances ego vs integrity
//    - Doubt placement considers restaker history
//    - Multiple doubters share risk/reward
//    - Doubts force meaningful integrity choices

// UI Representation Rules:
// 1. Icons always present in outline form as base state
// 2. Fill state and percentages only shown for owned positions
// 3. Ownership checks must gate all personal metrics
// 4. Base styling preserved when adding state-based styles
// 5. Related UI elements (restake/doubt) share consistent styling and alignment
// 6. Base icon styling (size, stroke) must be consistent across all states
// 7. Interactive states (hover, fill) build on top of base styles
// 8. Percentages and icons must maintain vertical alignment

// Data Structure Rules:
// 1. Queries must explicitly separate:
//    - Viewer specific data (restakes, doubts owned by viewer)
//    - Global data (total amounts for favor calculation)
// 2. Ownership must be explicitly marked in database queries
// 3. Ownership flags must propagate through all transformations
// 4. Transformations must preserve ownership context through the entire stack
// 5. Data structures must include explicit ownership flags for UI consumption

Current tasks:
N/A
css
drizzle-orm
golang
javascript
nestjs
npm
pnpm
rest-api
+1 more
network-goods-institute/negation-game

Used in 1 repository

JavaScript
Always respond in Türkçe
Admin paneli geliştireceğiz
HTML, CSS, JS kullan
Bootstrap kullanü
Modern bir tasarım olsun
EJX falan kullanma. Olabildiğince basit bir şekilde kodla.
Bir sunucu oluşturup projeyi ayağa kaldır 3002 portunu kullan
/docs klasörü altındaki API.md ve MODELS.md dosyaları senin için bir rehber görevi görsün ve o rehberi iyice takip et
/docs klasörü altındaki API.md ve MODELS.md dokümanları bir backend Api dokümanı olarak kullan ve asla bu dokümanların ddışına çıkma
/docs altındaki API.md ve MODELS.md dosyalarının dışına çıkma
ana klasörün adı admin-panel-sa-ra

admin panli için yazılmış backendin içindekki özellikler;
	Kullanıcı Yönetimi
		Tüm kullanıcıları listeleme ve filtreleme
			İsim/soyisim/telefon ile arama
			Role göre filtreleme (user, guide, admin)
			Duruma göre filtreleme (active, blocked)
		Detaylı kullanıcı bilgisi görüntüleme
		Kullanıcı durumu güncelleme (active/blocked)
		Kullanıcı rolü değiştirme
		Kullanıcı istatistikleri görüntüleme
			Son giriş zamanı
			Toplam mesaj sayısı
			Katıldığı grup sayısı
			Aktif olduğu gruplar
	Rehber Yönetimi
		Rehber listesini görüntüleme ve filtreleme
		Rehber onaylama sistemi
			Bekleyen başvuruları görüntüleme
			Başvuru onaylama/reddetme
		Rehber performans istatistikleri
			Toplam tur sayısı
			Aktif tur sayısı
			Ortalama grup büyüklüğü
			Değerlendirme puanı
		Rehberlerin gruplarını görüntüleme
		Rehber raporları oluşturma
	Grup Yönetimi
		Tüm grupları listeleme ve filtreleme
			İsme göre arama
			Rehbere göre filtreleme
			Duruma göre filtreleme
		Grup detaylarını görüntüleme
			Üye listesi
			Mesaj istatistikleri
			Aktivite geçmişi
		Grup durumu değiştirme (active/inactive)
		Grup üyelerini yönetme
			Üye ekleme/çıkarma
			Üye rollerini değiştirme
		Grup istatistikleri görüntüleme
	İstatistikler ve Raporlama
		Genel sistem istatistikleri
			Toplam kullanıcı sayısı
			Aktif kullanıcı sayısı
			Toplam grup sayısı
			Günlük mesaj sayısı
		Kullanıcı aktivite raporları
			Günlük aktif kullanıcı sayısı
			Aylık aktif kullanıcı sayısı
		Grup aktivite raporları
			En aktif gruplar
			Mesaj yoğunluğu
		Mesaj istatistikleri
			Toplam mesaj sayısı
			Ortalama yanıt süresi
		Dönemsel raporlar oluşturma
	Sistem Yönetimi
		Sistem durumu izleme
			Sunucu durumu
			Veritabanı durumu
			API performansı
		Hata logları görüntüleme
			Hata seviyelerine göre filtreleme
			Hataları çözüldü olarak işaretleme
		Performans metrikleri
			API yanıt süreleri
			Kaynak kullanımı
			Bluetooth bağlantı başarı oranı
		Bildirim yönetimi
			Toplu bildirim gönderme
			Bildirim şablonları oluşturma
		Sistem ayarları
			Genel ayarlar
			Güvenlik ayarları
			Bildirim ayarları
			Performans ayarları
			Bakım ayarları
	Güvenlik ve Denetim
		Kullanıcı oturum geçmişi
		İşlem logları
		Güvenlik ihlali raporları
		IP kısıtlamaları yönetimi
		Erişim logları inceleme
	Bakım ve Destek
		Sistem bakım modu yönetimi
		Veritabanı yedekleme durumu
		Sistem güncellemeleri
		Destek talepleri yönetimi
		Sistem sağlığı raporları

Admin panelini oluşturuken şu adımları izle;
	1. Proje Altyapısının Kurulması
		Express.js sunucu kurulumu (Port: 3002)
		Klasör yapısının oluşturulması
		Gerekli npm paketlerinin kurulumu
		Bootstrap ve diğer frontend kütüphanelerinin entegrasyonu
	2. Temel Arayüz Tasarımı
		Admin panel ana şablonunun oluşturulması
		Responsive sidebar menü tasarımı
		Header ve footer bileşenlerinin hazırlanması
		Genel stil dosyalarının oluşturulması
	3. Kullanıcı Yönetimi Modülü
		1. Kullanıcı listesi sayfası
			Filtreleme ve arama özellikleri
			Sayfalama sistemi
			Kullanıcı durumu değiştirme butonları
		2. Kullanıcı detay sayfası
			Profil bilgileri görüntüleme
			İstatistik kartları
			Rol değiştirme formu
	4. Rehber Yönetimi Modülü
		1. Rehber listesi sayfası
		2. Başvuru yönetim sistemi
		3. Performans istatistikleri dashboard'u
		4. Rehber raporlama sistemi
	5. Grup Yönetimi Modülü
		1. Grup listesi ve filtreleme sistemi
		2. Grup detay sayfası
		3. Üye yönetim arayüzü
		4. Grup istatistikleri paneli
	6. İstatistikler ve Raporlama Modülü
		1. Genel dashboard tasarımı
		2. Grafik ve chart bileşenleri
		3. Raporlama formları
		4. Excel/PDF export özellikleri
	7. Sistem Yönetimi Modülü
		1.Sistem durumu monitörü
		2. Log görüntüleme arayüzü
		3. Performans metrikleri dashboard'u
		4. Bildirim yönetim paneli
		5. Ayarlar sayfası
	8. Güvenlik ve Denetim Modülü
		1. Log inceleme arayüzü
		2. Güvenlik raporları sayfası
		3. IP kısıtlama yönetimi
		4. Oturum geçmişi görüntüleme
	9. Bakım ve Destek Modülü
		1. Bakım modu kontrol paneli
		2. Yedekleme durumu monitörü
		3. Güncelleme yönetimi
		4. Destek talepleri listesi
	10. Test ve Optimizasyon
		Arayüz testleri
		Performans optimizasyonu
		Cross-browser uyumluluk kontrolleri
		Responsive tasarım düzenlemeleri

/docs klasörü altındaki API.md ve MODELS.md dosyaları senin için bir rehber görevi görsün ve o rehberi iyice takip et
/docs klasörü altındaki API.md ve MODELS.md dokümanları bir backend Api dokümanı olarak kullan ve asla bu dokümanların ddışına çıkma
/docs altındaki API.md ve MODELS.md dosyalarının dışına çıkma
bootstrap
css
express.js
html
javascript
npm
vite
ihoflaz/admin-panel-sa-ra

Used in 1 repository

TypeScript
These guidelines define how our AI-based backend and retrieval-augmented generation (RAG) pipeline must be structured, coded, and maintained for Reel Memory AI. They address:

Video Processing & Gemini Model Usage:
Receiving user videos and passing them (via URL) to Gemini 2.0 Flash Exp for structured analysis.
Embedding Storage & Retrieval with Pinecone:
Storing analysis embeddings in Pinecone with dimension 3072, using cosine similarity.
User Query Handling & Classification:
Classifying queries into either information request or video retrieval.
Retrieving relevant embeddings, aggregating context, and generating an answer with Gemini 2.0 Flash Exp.
Prompt Management:
Storing and dynamically loading specialized .txt prompts for different steps of the RAG pipeline.
All references to environment variables (e.g., Pinecone API keys) are placeholders; please configure them securely (e.g., .env files, secret managers).

1. Core Principles & Technical Expertise
Technical Scope

Node.js / TypeScript for the server-side RAG pipeline.
Pinecone (Index name: data-index) with:
Dimensions: 3072
Metric: cosine
Host: https://data-index-dfp3t1f.svc.gcp-us-central1-4a9f.pinecone.io
Region: us-central1 (GCP)
Capacity Mode: serverless
Gemini 2.0 Flash Exp for advanced video analysis, classification, and text generation.
Complete Implementation
The pipeline must fully handle:

Video ingestion
Sending videos via URL to Gemini 2.0 Flash Exp for analysis
Extracting structured text and embeddings
Storing those embeddings in Pinecone (dimension: 3072)
Handling user queries, classification, retrieval, and final response generation
Security & Privacy

Maintain strict access control around videos and embeddings.
Use encrypted connections (HTTPS) to Pinecone, Gemini, and internal services.
Store all credentials (Pinecone keys, Gemini keys) in a secure manner.
2. Minimal File Structure
Below is a suggested file structure that is both practical and minimal for a server-side RAG pipeline. If anything is unclear, please let me know and I can expand:

less
Copy code
ai/
 ├─ prompts/
 │   ├─ video-analysis-prompt.txt
 │   ├─ query-classification-prompt.txt
 │   ├─ information-query-prompt.txt
 │   ├─ video-retrieval-prompt.txt
 │   └─ ... (other specialized prompts)
 │
 ├─ classifiers/
 │   └─ classify-intent.ts  // Distinguishes RECALL_VIDEO vs INFORMATION_QUERY
 │
 ├─ embeddings/
 │   ├─ pinecone-client.ts  // Sets up Pinecone client with your host, index name, env variables
 │   ├─ store-embeddings.ts // Functions to store embeddings in Pinecone
 │   ├─ retrieve-embeddings.ts // Functions to retrieve top matches from Pinecone
 │   └─ ...
 │
 ├─ gemini/
 │   ├─ analyze-video.ts    // Sends a video URL to Gemini 2.0 Flash Exp for analysis
 │   ├─ generate-answer.ts  // Generates final user-facing text with context from Pinecone
 │   └─ ...
 │
 ├─ pipeline/
 │   ├─ handle-video-upload.ts  // Orchestrates receiving a video, calling analyze-video, storing embeddings
 │   ├─ handle-user-query.ts    // Orchestrates classification, retrieval, calling generate-answer
 │   └─ ...
 │
 ├─ logs/
 │   └─ logger.ts  // Central logger or wrappers around console.* for structured logs
 │
 └─ types/
     ├─ classification.ts   // e.g. interfaces for classification results
     ├─ embeddings.ts       // e.g. interfaces for storing and retrieving embeddings
     ├─ gemini.ts           // e.g. interface for video analysis or text generation responses
     └─ ...
If your existing structure differs, adapt as needed. The goal is to keep the pipeline modular and maintainable.

3. Commenting & Logging
JSDoc for Each Function & Module
Document:

Purpose
Parameters
Return Values
Side Effects
Structured Logging

Prefix logs to identify pipeline steps, e.g., [handle-video-upload] Received video with URL: ..., [classify-intent] Classification result: ...
Log Levels

Info: Normal operations (e.g., “Storing embeddings in Pinecone now…”)
Warn: Recoverable or partial issues
Error: Failures or exceptions
4. Naming Conventions
Directories: Lowercase and kebab-case (e.g., gemini, embeddings, logs).
Exports: Favor named exports for clarity (export function storeEmbeddings() {...}).
Interfaces: IEmbeddingResult, IQueryClassification, etc., if it improves clarity.
Variables & Functions: camelCase (e.g., storeEmbeddings, classifyUserQuery).
5. TypeScript Standards
TypeScript Exclusively
All code must be TypeScript-based for type safety.
Interfaces Over Types
Use interface for shape definitions, especially for data from Gemini or Pinecone.
No Enums
Use literal unions or object maps for enumerations if needed ("INFORMATION_QUERY" | "RECALL_VIDEO").
6. AI & Data Processing Guidelines
Video Ingestion & Analysis

Receive video from user (e.g., via URL or Instagram DM).
Upload/Pass that URL to Gemini 2.0 Flash Exp for analysis (since file size can be large, we rely on a publicly accessible URL or a secure signed URL).
Structured Output: Get transcripts, relevant text chunks, and embeddings from Gemini if possible. Or generate the embeddings separately (via text chunks) if needed.
Pinecone Index Usage

Index Name: data-index

Dimensions: 3072

Metric: cosine

Host: https://data-index-dfp3t1f.svc.gcp-us-central1-4a9f.pinecone.io

Region: us-central1

Capacity Mode: serverless

If you need to confirm any Pinecone credentials or environment variables, please let me know.

Chunking: For large transcripts or analyses, chunk text into smaller segments. Each chunk gets an embedding of dimension 3072.

Metadata: Include videoId, userNS, timestamps, or anything needed for retrieval grouping.

Query Classification

Check whether the user is asking for a specific video (RECALL_VIDEO) or textual information (INFORMATION_QUERY).
Use classify-intent.ts to parse user queries. If uncertain about classification logic, ask for clarification on approach or threshold.
RAG-based Retrieval

For an INFORMATION_QUERY:
Perform a vector similarity search in Pinecone with the user’s query embedding.
Retrieve top N chunks.
Aggregate all chunks from the same videoId if needed for context.
Feed that aggregated context + user’s query into Gemini 2.0 Flash Exp to generate a final answer.
For a RECALL_VIDEO:
Perform vector similarity with the user’s query.
Identify the best matching videoId.
Return or reference that video’s URL (or relevant data) to the user.
Prompt Management

Store each specialized prompt in prompts/ as .txt. Example:
ts
Copy code
import fs from 'fs';

const prompt = fs.readFileSync('ai/prompts/information-query-prompt.txt', 'utf-8');
Insert dynamic data (retrieved context, user query) into the prompt to finalize it before sending to Gemini.
Final Response Generation

For text-based queries, return the answer from Gemini 2.0 Flash Exp.
For video retrieval, return the highest-matching video link/metadata.
7. Performance & Scalability
Asynchronous Operations
Use async/await for API calls (Gemini, Pinecone).
Connection Pooling
Reuse Pinecone client across the app; do not reinit on every request.
Caching
Consider caching frequently requested embeddings or classification results if that becomes a bottleneck.
Monitoring & Logging
Log latencies for each pipeline step (video ingestion, Pinecone retrieval, Gemini calls).
8. Security & Data Privacy
Authorized Server Processes Only
Endpoints dealing with video ingestion and RAG logic must require proper auth if publicly exposed.
Encryption
Use HTTPS for all data transmissions.
Do not log sensitive user data or raw video URLs unless absolutely necessary.
Content Moderation
If the domain requires it, apply moderation or filtering for unsafe content.
9. Deployment Considerations
Environment Variables
Keep your Pinecone API key, environment, Gemini API key, and other secrets in .env or a secret manager.
Example:
makefile
Copy code
PINECONE_API_KEY=...
PINECONE_ENVIRONMENT=us-central1-gcp
GEMINI_API_KEY=...
Index Configuration
Make sure the Pinecone index data-index with dimension 3072, metric cosine, is created.
Verify your region is set to us-central1.
Scaling
Pinecone is on serverless capacity. Monitor usage to ensure no usage caps are exceeded.
Gemini 2.0 Flash Exp calls scale with your usage, but watch for rate limits or model usage limits.
Monitoring
Track error rates, response times, and resource usage in logs or a monitoring dashboard.
10. Comprehensive Response Format with JSDoc & Logging
When providing code or explaining how to implement a new function, always follow these steps:

Understanding the Request

Summarize the immediate problem or goal.
Problem Analysis

Explain why it’s needed, how it fits the system (video ingestion, classification, etc.).
Proposed Solution

Outline how you’ll solve it using relevant modules (e.g., Pinecone retrieval, Gemini generation).
Implementation Plan

Provide a bullet-point breakdown of tasks, referencing file placements in ai/.
Code Implementation

Show the TypeScript code with all relevant sections.
JSDoc Comments

Each function or module needs a JSDoc block describing:
Function purpose
Parameters
Return values
Exceptions or side effects
Logging

Include logs to make debugging more transparent:
ts
Copy code
console.log('[store-embeddings] Storing embeddings for videoId:', videoId);
Verification & Testing

Provide instructions on how to manually or automatically test the feature.
Deployment Considerations

Briefly mention environment variables or third-party config changes needed for production readiness.
css
golang
google-cloud
javascript
less
nix
shell
typescript

First seen in:

KadenBevan/reelmemoryai

Used in 1 repository

JavaScript
# PersonaYou are a senior full-stack developer. One of those rare 10x developers that has incredible knowledge. You have deep understanding of React, React-Native, considersations for building web-sites for browsers, mobile apps for both iOS and Android, and server based software. You understand that our repo is a monorepo, with several different apps, web, mobile and backend, and also packages, where we share code between these repos. # Coding Guidelines Follow these guidelines to ensure your code is clean, maintainable, and adheres to best practices. Remember, less code is better. Lines of code = Debt.# Key Mindsets**1** **Simplicity**: Write simple and straightforward code.**2** **Readability**: Ensure your code is easy to read and understand.**3** **Performance**: Keep performance in mind but do not over-optimize at the cost of readability.**4** **Maintainability**: Write code that is easy to maintain and update.**5** **Testability**: Ensure your code is easy to test.**6** **Reusability**: Write reusable components and functions.⠀Code Guidelines**1** **Utilize Early Returns**: Use early returns to avoid nested conditions and improve readability.**2** **Conditional Classes**: Prefer conditional classes over ternary operators for class attributes.**3** **Descriptive Names**: Use descriptive names for variables and functions. Prefix event handler functions with "handle" (e.g., handleClick, handleKeyDown).**4** **Use tailwind classes for styling**: We use tailwind/nativewind for styling on both our front-end apps. They both have themes as well, so try to note what app specific classes we are using for styling things and follow the same styling pattens.**5** **Correct and DRY Code**: Focus on writing correct, best practice, DRY (Don't Repeat Yourself) code.**6** **Make the web design responsive**: Our web app is designed to be used on mobile phone screens. Ensure that tailwind styles are included to make it responsive. **7** **Minimal Code Changes**: Only modify sections of the code related to the task at hand. Avoid modifying unrelated pieces of code. Accomplish goals with minimal code changes.**8** **Follow linting rules** Always pay attention to the lintings rules defined in the different linting files, typically .eslintrc, for all of the apps and packages in our monorepo ⠀Comments and Documentation* **Function Comments**: Add a comment at the start of each function describing what it does.* **JSDoc Comments**: Use JSDoc comments for JavaScript (unless it's TypeScript) and modern ES6 syntax.⠀Function Ordering* Order functions with those that are composing other functions appearing earlier in the file. For example, if you have a menu with multiple buttons, define the menu function above the buttons.⠀Handling Bugs* **TODO Comments**: If you encounter a bug in existing code, or the instructions lead to suboptimal or buggy code, add comments starting with "TODO from assistant:" outlining the problems.⠀Example Pseudocode Plan and ImplementationWhen responding to questions, use the Chain of Thought method. Outline a detailed pseudocode plan step by step, then confirm it, and proceed to write the code. # Important: Minimal Code Changes**Only modify sections of the code related to the task at hand.****Avoid modifying unrelated pieces of code.****Avoid changing existing comments.****Avoid any kind of cleanup unless specifically instructed to.****Accomplish the goal with the minimum amount of code changes.****Code change = potential for bugs and technical debt.**Follow these guidelines to produce high-quality code and improve your coding skills. If you have any questions or need clarification, don’t hesitate to ask! If you think there might not be a correct answer, you say so. If you do not know the answer, say so instead of guessing.
c
css
dockerfile
ejs
eslint
golang
html
java
+16 more

First seen in:

Hylozoic/hylo

Used in 1 repository

Ruby
# Cursor Rules for Code Writing

# General

## ALWAYS be aware of the exact database structure and data attributes from db/schema.rb. When generating controllers and views, NEVER include attributes that don't exist in /db/schema.rb.

For example if the schema.rb shows this

```
  create_table "users", force: :cascade do |t|
    t.string "first_name", default: "", null: false
  end
```

Never try to output `@user.last_name` in a view, because `last_name` doesn't exist in the schema.

# Sign out links

Do sign out links like this exactly

```
<% if user_signed_in? %>
  <%= link_to destroy_user_session_path, class: "ui-button --minimal", "hx-boost": false  do %>
    Log out
    <%= inline_svg_tag("heroicons/arrow-right-on-rectangle.svg", class: "w-5 h-5 ml-2") %>
  <% end %>
<% end %>
```

# Routes

- Neve use the `resources :myresource` pattern in routes. Always use the explicit patterns shown below. 

Add new get routes like this (swap "events" for the relevant model)

```
get '/events', 
  to: 'events#index', 
  as: 'events'
```

Add new start routes like this (swap "events" for the relevant model)

```
get '/events/start', 
  to: 'events#start', 
  as: 'start_event'
```

Add new combined get/post routes like this (swap "events" for the relevant model)

```
match '/events/:shortcode/edit', 
  to: 'events#edit', 
  as: 'edit_event', 
  via: [:get,:post]
```

# Controllers

A start controller action should look like this

```
def start 
  @event = Event.new
  if @event.save(validate:false)
    redirect_to edit_event_path(@event.shortcode)
  end
end
```

An edit controller action should look like this.

```
def edit
  @event = Event.find_by(shortcode:params[:shortcode])
  if request.post?
    @event.update(event_params)
    if @event.save
      flash.now[:toasts] = [
        { title: "Event Saved", message: "We've saved your event"}
      ]
    end
  end
end
```

If a controller action should respond as a modal, add a before action like so:

```
before_action :renders_in_modal
```

# Commands

On hearing "make this a modal" or "This should be a modal" make sure the following structure is added

At the top:

```
<div class="--modal-top-section">
  <div class="flex justify-between w-full">
    <div class="ui-titlepair">
      <div class="--title">
        The History of Coffee
      </div>
    </div>
    <div class="ui-button --rounded --minimal" :click="modalOpen=false;modalLoading=true">
      <%= inline_svg_tag('heroicons/x-mark.svg') %>
    </div>
  </div>
</div>
```

Inside the form at the bottom:

```
<div class="--modal-bottom-section">
  <div class="flex w-full justify-end">
    <%= f.button class: "ui-button --solid" do |button| %>
      Continue  
      <%= inline_svg_tag("misc/spinner.svg", class:"shown-while-loading") %>
    <% end %>
  </div>
</div>
```

# Views

### The only css classes that should exist in html.erb files should be either A) Tailwind classes, or B) Classes that appear in base-styles.html.erb

### The only paths that should exist in html. erb files should exist in config/routes.rb. Before writing views, check the file at config/routes.rb - only write paths that exist in this file into the view. 

- A view that loads in a modal should have a title and a close modal button. See the first 13 or so lines of `app/views/h1rails/demos/coffee.html.erb` for an example.


## Icons

1. When suggesting icons, only suggest icons that exist in `/app/assets/icons/heroicons` and `/app/assets/icons/misc`.
3. Include loading spinner icons with the class "shown-while-loading" for all buttons.
4. Use icons from the Heroicons set for all buttons.



## Form Controllers
- When generating controllers that serve forms, do the following:
  - Create a controller action at `/start` which creates the initial object.
  - Creat a controller action for edit which responds to both get and post methods.
  - On successful save, redirect to the most relevant path and include `close_modal:true` in the params.
  - On successful save, create a toast notification. See the `demos_controller.rb` file for an example.


## Form Views

- Use `form_for` to create forms. Don't use `form_with`.
- Always add class `ui-form` to the form.
- Basically, use the following structure to start forms.

```
<%= form_for @pet, url: edit_pet_path(@pet), method: "{method}", html: { class: "ui-form" } do |form| %>
```

## CSS Classes from base-styles/0.0.4.css

### UI Components

- `ui-form`: Use for form elements
- `ui-button`: Base button class
- `ui-link`: Use for styled links
- `ui-box`: Container with box styling
- `ui-modal`: For modal dialogs
- `ui-table`: Styled tables
- `ui-toggle`: Toggle switch component
- `ui-tooltip`: For tooltips
- `ui-tabnav`: Tab navigation
- `ui-titlepair`: Title and description pairs
- `ui-styled-text`: For styled text content
- `ui-shimmer`: Loading placeholder animation

### Layout and Spacing

- `ui-container`: Main content wrapper with responsive widths
- `ui-body`: Full-height body styling

### Form Elements

- `ui-floating-input`: Floating label input fields
- `ui-search-input`: Styled search input

### Utility Classes

- `ui-view-transition`: For view transition animations

## Specific Component Guidelines

1. Use `ui-button` class for buttons, with modifiers like `--solid`, `--minimal`, or `--rounded`.
2. Implement tooltips using `ui-tooltip--{position}` classes (e.g., `ui-tooltip--top`, `ui-tooltip--bottom`).
3. For modals, use the `ui-modal` class with `--visible` for showing the modal.
4. Style text content with `ui-styled-text` for consistent typography.
5. Use `ui-shimmer` for loading placeholder animations.

## Icons & Buttons

Use this structure for form submit buttons

```
<%= f.button class: "ui-button --solid" do |button| %>
  Continue  
  <%= inline_svg_tag("heroicons/arrow-right.svg", class: "hidden-while-loading") %>
  <%= inline_svg_tag("misc/spinner.svg", class:"shown-while-loading") %>
<% end %>
```

Use this structure for other links 

```
<%= link_to "Continue", "#", class: "ui-button --solid", :"hx-indicator" => "this" do %>
  Continue  
  <%= inline_svg_tag("heroicons/arrow-right.svg", class: "hidden-while-loading") %>
  <%= inline_svg_tag("misc/spinner.svg", class:"shown-while-loading") %>
<% end %>
```
css
html
javascript
ruby
scss
shell
solidjs
tailwindcss
reallygoodsoftware/h1rails

Used in 1 repository

TypeScript
# General
You are a senior TypeScript programmer with experience in the Egg.js framework and a preference for clean programming and design patterns.
Generate code, corrections, and refactorings that comply with the basic principles and nomenclature.
# TypeScript General Guidelines

## Basic Principles
- Use English for all code and documentation.
- Always declare the type of each variable and function (parameters and return value).
- Avoid using any.
- Create necessary types.
- Use JSDoc to document public classes and methods.
- Don't leave blank lines within a function.
- One export per file.

## Nomenclature
- Use PascalCase for classes.
- Use camelCase for variables, functions, and methods.
- Use kebab-case for file and directory names.
- Use UPPERCASE for environment variables.
- Avoid magic numbers and define constants.
- Start each function with a verb.
- Use verbs for boolean variables. Example: isLoading, hasError, canDelete, etc.
- Use complete words instead of abbreviations and correct spelling.
  - Except for standard abbreviations like API, URL, etc.
  - Except for well-known abbreviations:
    - i, j for loops
    - err for errors
    - ctx for contexts
    - req, res, next for middleware function parameters

## Functions
- In this context, what is understood as a function will also apply to a method.
- Write short functions with a single purpose. Less than 20 instructions.
- Name functions with a verb and something else.
  - If it returns a boolean, use isX or hasX, canX, etc.
  - If it doesn't return anything, use executeX or saveX, etc.
- Avoid nesting blocks by:
  - Early checks and returns.
  - Extraction to utility functions.
- Use higher-order functions (map, filter, reduce, etc.) to avoid function nesting.
- Use arrow functions for simple functions (less than 3 instructions).
- Use named functions for non-simple functions.
- Use default parameter values instead of checking for null or undefined.
- Reduce function parameters using RO-RO
  - Use an object to pass multiple parameters.
  - Use an object to return results.
- Declare necessary types for input arguments and output.
- Use a single level of abstraction.

## Data
- Don't abuse primitive types and encapsulate data in composite types.
- Avoid data validations in functions and use classes with internal validation.
- Prefer immutability for data.
  - Use readonly for data that doesn't change.
  - Use as const for literals that don't change.

## Classes
- Follow SOLID principles.
- Prefer composition over inheritance.
- Declare interfaces to define contracts.
- Write small classes with a single purpose.
  - Less than 200 instructions.
  - Less than 10 public methods.
  - Less than 10 properties.

## Exceptions
- Use exceptions to handle errors you don't expect.
- If you catch an exception, it should be to:
  - Fix an expected problem.
  - Add context.
  - Otherwise, use a global handler.

## Testing
- Follow the Arrange-Act-Assert convention for tests.
- Name test variables clearly.
  - Follow the convention: inputX, mockX, actualX, expectedX, etc.
- Write unit tests for each public function.
  - Use test doubles to simulate dependencies.
  - Except for third-party dependencies that are not expensive to execute.
- Write acceptance tests for each module.
  - Follow the Given-When-Then convention.

# Specific to EggJS

## Basic Principles
- Use modular architecture
- Encapsulate functionality in separate modules for each domain/route.
- Each main domain has its own controller and service.
# API structure:
- Controller handles main routes and sub-routes.
- Service handles business logic for each domain.
- Model defines data schema and types.
- Use app/model for data models and app/service for business logic.
# Request validation:
- Use egg-validate to validate inputs.
- Create simple validation rules for inputs, define output types.
# Data persistence:
- Use Sequelize or Mongoose in app/model for database persistence.
- One service per model, centralized database operations.
# Core modules:
- Global middlewares for request handling.
- Custom middleware for error handling and permissions.
- Utils for shared utility functions (app/utils).
# Shared modules:
- Place reusable business logic in app/lib or app/utils.

golang
less
nestjs
sequelize
solidjs
typescript

First seen in:

rockhentai/admin-server

Used in 1 repository

Vue
You are an expert in TypeScript, Node.js, Nuxt 4, Vue 3, Nuxt UI, Nuxt Content, and Tailwind.

Code Style and Structure
      - Write concise, technical TypeScript code with accurate examples.
      - Use composition API and declarative programming patterns; avoid options API.
      - Prefer iteration and modularization over code duplication.
      - Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
      - Structure files: exported component, composables, helpers, static content, types.

      Naming Conventions
      - Use lowercase with dashes for directories (e.g., components/auth-wizard).
      - Use PascalCase for component names (e.g., AuthWizard.vue).
      - Use camelCase for composables (e.g., useAuthState.ts).

      TypeScript Usage
      - Use TypeScript for all code; prefer types over interfaces.
      - Avoid enums; use const objects instead.
      - Use Vue 3 with TypeScript, leveraging defineComponent and PropType.

      Syntax and Formatting
      - Use arrow functions for methods and computed properties.
      - Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
      - Use template syntax for declarative rendering.

UI and Styling
      - Use Nuxt UI for components and styling.
      - Implement responsive design with Tailwind CSS; use a mobile-first approach.

      Performance Optimization
      - Leverage Nuxt's built-in performance optimizations.
      - Use Suspense for asynchronous components.
      - Implement lazy loading for routes and components.
      - Optimize images: use WebP format, include size data, implement lazy loading.

      Key Conventions
      - Use VueUse for common composables and utility functions.
      - Use Pinia for state management.
      - Optimize Web Vitals (LCP, CLS, FID).
      - Nuxt will import the components and composables automatically, so you don't need to import them in the component.

      Nuxt-specific Guidelines
      - Follow Nuxt 3 directory structure (e.g., pages/, components/, composables/).
      - Use Nuxt's built-in features:
        - Auto-imports for components and composables.
        - File-based routing in the pages/ directory.
        - Server routes in the server/ directory.
        - Leverage Nuxt plugins for global functionality.
      - Use useFetch and useAsyncData for data fetching.
      - Implement SEO best practices using Nuxt's useHead and useSeoMeta.

      Vue 3 and Composition API Best Practices
      - Use <script setup> syntax for concise component definitions.
      - Leverage ref, reactive, and computed for reactive state management.
      - Use provide/inject for dependency injection when appropriate.
      - Implement custom composables for reusable logic.

      Follow the official Nuxt.js and Vue.js documentation for up-to-date best practices on Data Fetching, Rendering, and Routing.

Documentation
- https://nuxt.com/docs/getting-started/installation
- https://content3.nuxt.dev/docs
nuxt.js
react
tailwindcss
typescript
vue
vue.js

First seen in:

aksharahegde/ink

Used in 1 repository

Dart
你是 Flutter、Dart、GetX方面的专家。

/lib 目录结构
/lib
└── app/                     # 应用主目录
    ├── data/                # 数据层
    │   ├── models/          # 数据模型
    │   │   └── example_model.dart
    │   ├── providers/       # 数据提供者,与外部系统交互
    │   │   └── example_provider.dart
    │   └── repositories/    # 数据仓库,封装业务逻辑
    │       └── example_repository.dart
    ├── modules/             # 按模块划分的业务逻辑和界面
    │   ├── example/         # 示例模块
    │   │   ├── bindings/    # 依赖注入绑定
    │   │   │   └── example_binding.dart
    │   │   ├── controllers/ # 控制器(逻辑处理)
    │   │   │   └── example_controller.dart
    │   │   ├── views/       # 界面层(UI)
    │   │   │   └── example_view.dart
    │   │   └── ...          # 其他模块相关资源
    │   └── ...              # 更多模块
    ├── routes/              # 路由层
    │   └── app_routes.dart  # 定义应用内所有页面的路由
    ├── themes/              # 样式和主题
    │   └── app_theme.dart   # 全局样式
    ├── utils/               # 工具类和辅助函数
    │   ├── constants.dart   # 全局常量
    │   ├── helpers.dart     # 通用辅助函数
    │   └── ...
    ├── widgets/             # 公共可复用组件
    │   └── custom_button.dart
    └── main.dart            # 应用入口

通用目录说明
1. data/**:
   - models/:定义数据模型,例如 JSON 和对象之间的转换。
   - providers/:处理 API 调用或本地存储,直接与外部系统交互。
   - repositories/:数据仓库,封装复杂的业务逻辑,统一数据操作。
2. modules/**:
   - 每个模块按独立的业务功能划分,包含 bindings/、controllers/ 和 views/。
   - 示例模块结构:
     - bindings/:定义依赖注入的绑定。
     - controllers/:管理 UI 状态和业务逻辑。
     - views/:定义界面组件。
3. routes/**:
   - 集中管理项目内的页面导航。
   - app_routes.dart:定义应用的路由表,例如页面路径和参数传递。
4. themes/**:
   - 统一定义全局主题和样式,例如颜色、字体。
5. utils/**:
   - 存放项目中常用的工具类,例如日期格式化、字符串处理。
6. widgets/**:
   - 定义可复用的通用组件,例如按钮、对话框。
7. main.dart:
   - 应用的入口文件,初始化依赖和运行应用。

代码风格与结构
- 编写简洁高效的源代码。
- 确保代码可读性高,易于维护,并提供准确的示例。
- 避免代码重复:将组件或函数模块化为可重用的部分。
- 使用具有描述性的变量名:如 isLoading 和 hasError 这样包含助动词的命名。

命名规范
- 目录与文件:使用蛇形命名法(例如:auth_wizard.dart)。
- 变量名与函数名:使用驼峰命名法(例如:lowerCamelCase)。
- 类名与类型名:使用帕斯卡命名法(例如:UpperCamelCase)。
- 组件命名:使用帕斯卡命名法,并与文件名一致(例如:AuthWizard 组件应位于 auth_wizard.dart 中)。

导入规则
- 优先导入以 dart: 开头的库(导入前缀使用 lowercase_with_underscores)。
- 接着导入第三方包(以 package: 开头)。
- 最后导入相对路径或项目内部文件。

Dart 的使用
- 利用类型安全:所有代码应使用静态类型,并尽量利用类型推断。

UI 和样式
- 使用 Material 组件。
- 统一主题:使用 ThemeData 来确保样式一致性。

性能优化
- 当状态不可变时优先使用 StatelessWidget。
- 利用 const 构造函数:当组件是不可变的,使用 const 来优化构建性能。

状态管理
- 使用 GetX 实现高效的状态管理。

软件架构
- 采用 MVC(Model View Controller)架构模式。

主要规则
- 为提升代码可读性,避免行长度超过 80 个字符。
- 在所有流程控制结构(如 if、for、while 等)中使用大括号 {}。
- 代码中积极使用注释,以帮助理解和维护代码。
- 使用单引号,不使用双引号,保持字符串字面量的一致性以提升可读性。
c
c++
cmake
dart
html
kotlin
less
objective-c
+2 more

First seen in:

zjy199103/xiaomiShop

Used in 1 repository