docs: Add project overview, development guidelines, API design patterns, and component design pattern documentation.

This commit is contained in:
ccbikai 2025-05-27 20:07:03 +08:00
parent 643df5c6de
commit 3438170d95
6 changed files with 702 additions and 0 deletions

View file

@ -0,0 +1,88 @@
---
description:
globs:
alwaysApply: false
---
# API Design Patterns
## API Route Structure
### Link Management API
Located in the `server/api/link/` directory, containing the following endpoints:
- [create.post.ts](mdc:server/api/link/create.post.ts): Create new short links
- [edit.put.ts](mdc:server/api/link/edit.put.ts): Edit existing links
- [delete.post.ts](mdc:server/api/link/delete.post.ts): Delete links
- [list.get.ts](mdc:server/api/link/list.get.ts): Get link lists
- [query.get.ts](mdc:server/api/link/query.get.ts): Query specific links
- [search.get.ts](mdc:server/api/link/search.get.ts): Search links
- [upsert.post.ts](mdc:server/api/link/upsert.post.ts): Create or update links
- [ai.get.ts](mdc:server/api/link/ai.get.ts): AI-generated slugs
### Other APIs
- [location.ts](mdc:server/api/location.ts): Geographic location information
- [verify.ts](mdc:server/api/verify.ts): Authentication
- `stats/`: Analytics-related APIs
- `logs/`: Logging-related APIs
- `ws/`: WebSocket-related APIs
## API Design Conventions
### HTTP Methods
- `GET`: Retrieve data (queries, lists)
- `POST`: Create resources or perform operations
- `PUT`: Update resources
- `DELETE`: Remove resources
### Response Format
```typescript
// Success response
{
success: true,
data: any
}
// Error response
{
success: false,
error: string,
code?: number
}
```
### Authentication
- Use Site Token for authentication
- Pass token in request header: `Authorization: Bearer <token>`
### Data Validation
- Use Zod for input validation
- Define validation schemas in `schemas/` directory
- Unified error handling and response format
### Cloudflare Integration
- Use Cloudflare Workers KV for data storage
- Leverage Cloudflare Analytics Engine for statistics
- Use Cloudflare AI for slug generation
## Error Handling
### Common Error Codes
- `400`: Bad request parameters
- `401`: Unauthorized access
- `403`: Insufficient permissions
- `404`: Resource not found
- `429`: Rate limit exceeded
- `500`: Internal server error
### Error Handling Pattern
```typescript
try {
// API logic
return { success: true, data: result }
} catch (error) {
return createError({
statusCode: 400,
statusMessage: error.message
})
}
```

View file

@ -0,0 +1,205 @@
---
description:
globs:
alwaysApply: false
---
# Coding Standards
## Code Quality
### TypeScript Requirements
- All new code must use TypeScript
- Enable strict type checking
- Avoid using `any` type, prefer specific types
- Define interfaces or type aliases for complex objects
```typescript
// ✅ Good practice
interface LinkData {
slug: string
url: string
createdAt: Date
expiresAt?: Date
}
// ❌ Avoid
const linkData: any = { ... }
```
### Function and Variable Naming
- Use descriptive names
- Function names should start with verbs
- Boolean variables use `is`, `has`, `should` prefixes
- Constants use UPPER_SNAKE_CASE
```typescript
// ✅ Good practice
const isValidUrl = (url: string): boolean => { ... }
const hasExpired = computed(() => { ... })
const MAX_SLUG_LENGTH = 50
// ❌ Avoid
const check = (u: string) => { ... }
const expired = computed(() => { ... })
const maxLen = 50
```
## Security Requirements
### Input Validation
- All user input must be validated using Zod
- API endpoints must validate request parameters
- Frontend forms use vee-validate + Zod
```typescript
// API input validation
import { z } from 'zod'
const createLinkSchema = z.object({
url: z.string().url(),
slug: z.string().min(1).max(50).optional(),
expiresAt: z.string().datetime().optional()
})
export default defineEventHandler(async (event) => {
const body = await readBody(event)
const validatedData = createLinkSchema.parse(body)
// ...
})
```
### Authentication
- Use Site Token for authentication
- Sensitive operations require permission verification
- Don't store sensitive information on the client
### Data Sanitization
- Sanitize user-input HTML content
- Validate URL format and security
- Prevent XSS and injection attacks
## Performance Best Practices
### Reactive Data
- Use `ref` and `reactive` appropriately
- Avoid unnecessary reactive wrapping
- Use `readonly` to protect data
```typescript
// ✅ Good practice
const { data: links, pending } = await $fetch('/api/links')
const filteredLinks = computed(() =>
links.value.filter(link => link.isActive)
)
// ❌ Avoid
const links = ref([])
const filteredLinks = ref([])
watch(links, () => {
filteredLinks.value = links.value.filter(link => link.isActive)
})
```
### Async Operations
- Use `async/await` instead of Promise chains
- Handle errors and loading states properly
- Avoid blocking UI operations
```typescript
// ✅ Good practice
const { data, error, pending } = await useFetch('/api/links')
// Error handling
try {
const result = await $fetch('/api/link/create', { ... })
} catch (error) {
// Handle error
}
```
## Code Organization
### File Structure
- Each file should export only one main functionality
- Group related functionality in the same directory
- Use `index.ts` as directory entry point
### Import/Export
- Use ES6 module syntax
- Organize imports alphabetically
- Separate third-party and local imports
```typescript
// Third-party libraries
import { ref, computed } from 'vue'
import { z } from 'zod'
// Local imports
import type { LinkData } from '~/types'
import { validateUrl } from '~/utils/validation'
```
### Comments and Documentation
- Add comments for complex logic
- Use JSDoc comments for public APIs
- Keep comments in sync with code
```typescript
/**
* Create a new short link
* @param url - Original URL
* @param slug - Custom slug (optional)
* @returns Created link data
*/
export async function createLink(url: string, slug?: string): Promise<LinkData> {
// Implementation logic
}
```
## Testing Requirements
### Type Checking
- Resolve all TypeScript errors
- Use strict type configuration
### Code Style
- Follow ESLint rules
- Use Prettier for code formatting
- Automatically run lint-staged on commit
### Manual Testing
- Test main user flows
- Verify API endpoint functionality
- Check responsive design
## Git Commit Conventions
### Commit Message Format
```
type(scope): description
body (optional)
footer (optional)
```
### Commit Types
- `feat`: New feature
- `fix`: Bug fix
- `docs`: Documentation update
- `style`: Code style (no functional impact)
- `refactor`: Refactoring
- `perf`: Performance optimization
- `test`: Testing related
- `chore`: Build process or auxiliary tool changes
### Example
```
feat(api): add AI-powered slug generation
- Integrate Cloudflare AI for automatic slug creation
- Add new /api/link/ai endpoint
- Update link creation flow to support AI suggestions
Closes #123
```

View file

@ -0,0 +1,156 @@
---
description:
globs:
alwaysApply: false
---
# Vue Component Design Patterns
## Component Directory Structure
### UI Components (`app/components/ui/`)
Reusable UI components based on shadcn-vue:
- Buttons, inputs, dialogs, and other fundamental components
- Follow shadcn-vue design system
- Styled with Tailwind CSS
- Support theme switching (light/dark mode)
### Business Components
- `dashboard/`: Dashboard-related components
- `home/`: Homepage-related components
- `login/`: Login-related components
- `layouts/`: Layout components
- `spark-ui/`: Special UI components
### Global Components
- [SwitchLanguage.vue](mdc:app/components/SwitchLanguage.vue): Language switching component
- [SwitchTheme.vue](mdc:app/components/SwitchTheme.vue): Theme switching component
## Component Development Standards
### Component Structure
```vue
<script setup lang="ts">
// Imports
import { ref, computed } from 'vue'
// Type definitions
interface Props {
// props types
}
// Props and Emits
const props = defineProps<Props>()
const emit = defineEmits<{
// event types
}>()
// Reactive data
const state = ref()
// Computed properties
const computed = computed(() => {
// computation logic
})
// Methods
function handleAction() {
// handler logic
}
</script>
<template>
<!-- template -->
</template>
<style scoped>
/* styles (if needed) */
</style>
```
### Naming Conventions
- Component files use PascalCase: `MyComponent.vue`
- Internal variables use camelCase
- CSS class names use Tailwind CSS utility classes
- Event names use kebab-case
### Props and Events
```typescript
// Props type definition
interface Props {
title: string
isVisible?: boolean
items: Array<Item>
}
// Events type definition
const emit = defineEmits<{
update: [value: string]
close: []
select: [item: Item]
}>()
```
## State Management
### Composables (`app/composables/`)
- Use VueUse utility functions
- Create custom composables for shared state management
- Follow `use` prefix naming convention
### Reactive State
```typescript
// composables/useAuth.ts
export function useAuth() {
const isAuthenticated = ref(false)
const user = ref(null)
const login = async (token: string) => {
// login logic
}
const logout = () => {
// logout logic
}
return {
isAuthenticated: readonly(isAuthenticated),
user: readonly(user),
login,
logout
}
}
```
## Styling and Theming
### Tailwind CSS
- Use Tailwind utility classes for styling
- Configuration file: [tailwind.config.js](mdc:tailwind.config.js)
- Support responsive design and dark mode
### Theme System
- Use `@nuxtjs/color-mode` module
- Support automatic system theme detection
- Theme switching component: [SwitchTheme.vue](mdc:app/components/SwitchTheme.vue)
### Animation Effects
- Use `@vueuse/motion` for animations
- Use animation classes provided by `tailwindcss-animate`
- Keep animations simple and performance-friendly
## Internationalization
### Multi-language Support
- Use `@nuxtjs/i18n` module
- Language switching component: [SwitchLanguage.vue](mdc:app/components/SwitchLanguage.vue)
- Store translation files in `i18n/` directory
### Usage
```vue
<template>
<div>
<h1>{{ $t('welcome.title') }}</h1>
<p>{{ $t('welcome.description') }}</p>
</div>
</template>
```

View file

@ -0,0 +1,139 @@
---
description:
globs:
alwaysApply: false
---
# Deployment and Infrastructure
## Cloudflare Platform
Sink runs entirely on the Cloudflare platform, leveraging the following services:
### Cloudflare Workers
- Serverless computing platform
- Global edge network deployment
- Configuration file: [wrangler.jsonc](mdc:wrangler.jsonc)
### Cloudflare Pages
- Static website hosting
- Automatic build and deployment
- Preview deployment support
### Cloudflare Workers KV
- Key-value storage database
- Globally distributed storage
- Used for storing link data and configuration
### Cloudflare Analytics Engine
- Real-time analytics data collection
- High-performance time-series database
- Used for link click statistics
### Cloudflare AI
- AI model inference service
- Used for automatic slug generation
- Model: `@cf/meta/llama-3.1-8b-instruct`
## Deployment Configuration
### Environment Variables
Defined in `runtimeConfig` in [nuxt.config.ts](mdc:nuxt.config.ts):
```typescript
runtimeConfig: {
siteToken: 'SinkCool', // Site access token
redirectStatusCode: '301', // Redirect status code
linkCacheTtl: 60, // Link cache time
redirectWithQuery: false, // Whether to preserve query parameters
homeURL: '', // Home URL
cfAccountId: '', // Cloudflare Account ID
cfApiToken: '', // Cloudflare API token
dataset: 'sink', // Analytics dataset name
aiModel: '@cf/meta/llama-3.1-8b-instruct', // AI model
caseSensitive: false, // Case sensitivity
listQueryLimit: 500, // List query limit
disableBotAccessLog: false, // Disable bot access logging
}
```
### Build Scripts
- `pnpm build`: Build for production
- `pnpm build:map`: Build map data
- `pnpm build:colo`: Build Cloudflare data center information
### Deployment Commands
```bash
# Preview deployment
pnpm preview
# Production deployment
pnpm deploy
# Using Wrangler CLI
wrangler pages deploy dist
```
## Performance Optimization
### Caching Strategy
- Static assets cached using Cloudflare CDN
- Configurable link data cache TTL
- Leverage edge computing to reduce latency
### Route Rules
Configured in [nuxt.config.ts](mdc:nuxt.config.ts):
```typescript
routeRules: {
'/': {
prerender: true, // Prerender homepage
},
'/dashboard/**': {
prerender: true, // Prerender dashboard
ssr: false, // Disable server-side rendering
},
'/dashboard': {
redirect: '/dashboard/links', // Redirect to links page
},
}
```
### Build Optimization
- Use `NODE_OPTIONS=--max-old-space-size=8192` to increase memory limit
- Enable Nuxt's built-in optimization features
- Code splitting and lazy loading
## Monitoring and Logging
### Analytics Engine
- Real-time click data collection
- Geographic location statistics
- User agent analysis
- Referrer statistics
### Error Handling
- Unified error response format
- Error logging
- Performance monitoring
### Security
- Site Token authentication
- CORS configuration
- Input validation and sanitization
- Malicious link prevention
## Development Environment
### Local Development
```bash
# Start development server
pnpm dev
# Code style checking
pnpm lint
```
### Environment Configuration
- Use `.env` file for local environment variables
- Use Cloudflare Workers local simulator during development
- Support hot reload and live preview

View file

@ -0,0 +1,64 @@
---
description:
globs:
alwaysApply: false
---
# Development Guidelines
## Code Style and Standards
### TypeScript/JavaScript
- Use TypeScript for type-safe development
- Follow ESLint rules defined in [eslint.config.mjs](mdc:eslint.config.mjs)
- Use `@antfu/eslint-config` as the base configuration
- Run `pnpm lint` to check code style, `pnpm lint:fix` to auto-fix issues
### Vue Components
- Use Composition API with `<script setup>` syntax
- Name component files using PascalCase
- Place UI components in `app/components/ui/` directory
- Place business components in `app/components/` directory
### API Development
- Place API routes in `server/api/` directory
- Use Nitro's file-system routing
- Use consistent error handling format for API responses
- Leverage Cloudflare Workers KV for data storage
## Development Tools and Scripts
### Common Commands
```bash
pnpm dev # Start development server
pnpm build # Build for production
pnpm preview # Preview built application
pnpm deploy # Deploy to Cloudflare
pnpm lint # Code style checking
pnpm lint:fix # Auto-fix code style issues
```
### Environment Configuration
- Use [wrangler.jsonc](mdc:wrangler.jsonc) to configure Cloudflare Workers
- Define environment variables in `runtimeConfig` in [nuxt.config.ts](mdc:nuxt.config.ts)
- Use `.env` file for development (not committed to version control)
## Best Practices
### Performance Optimization
- Utilize Nuxt's built-in optimization features
- Properly configure `prerender` and SSR settings
- Leverage Cloudflare's global CDN network
### Security
- Use Site Token for authentication
- Validate inputs using Zod schemas
- Follow Cloudflare Workers security best practices
### Internationalization
- Use `@nuxtjs/i18n` module
- Store translation files in [i18n/](mdc:i18n/) directory
- Support multi-language detection and switching
### Testing
- Use lint-staged to automatically check code style on commit
- Follow Git commit conventions

View file

@ -0,0 +1,50 @@
---
description:
globs:
alwaysApply: false
---
# Sink Project Overview
Sink is a simple, speedy, and secure link shortener with analytics, running 100% on Cloudflare.
## Project Architecture
This is a full-stack application built with Nuxt.js, utilizing the following tech stack:
- **Frontend Framework**: Nuxt.js 3 ([nuxt.config.ts](mdc:nuxt.config.ts))
- **UI Components**: shadcn-vue + Tailwind CSS
- **Database**: Cloudflare Workers KV
- **Analytics Engine**: Cloudflare Workers Analytics Engine
- **Deployment Platform**: Cloudflare Workers/Pages
## Core Features
1. **URL Shortening**: Compress long URLs into short links
2. **Analytics**: Monitor link click data and gather insightful statistics
3. **Custom Slugs**: Support for personalized slugs and case sensitivity
4. **AI Slug Generation**: Leverage AI to automatically generate slugs
5. **Link Expiration**: Set expiration dates for links
## Project Structure
- **app/**: Nuxt application frontend code
- `components/`: Vue components
- `pages/`: Page routes
- `composables/`: Composable functions
- `layouts/`: Layout components
- `middleware/`: Middleware
- **server/**: Backend API code
- `api/`: API route handlers
- `middleware/`: Server middleware
- `utils/`: Server utility functions
- **i18n/**: Internationalization configuration
- **schemas/**: Data validation schemas
- **scripts/**: Build scripts
## Configuration Files
- [package.json](mdc:package.json): Project dependencies and scripts
- [nuxt.config.ts](mdc:nuxt.config.ts): Nuxt configuration
- [wrangler.jsonc](mdc:wrangler.jsonc): Cloudflare Workers configuration
- [tailwind.config.js](mdc:tailwind.config.js): Tailwind CSS configuration
- [eslint.config.mjs](mdc:eslint.config.mjs): ESLint configuration