From 0fc5763939bc8bb252f09bafb21359e6e5d4547b Mon Sep 17 00:00:00 2001 From: WannProject Date: Sun, 6 Sep 2026 21:43:36 +0800 Subject: [PATCH] update repo --- .../skills/inertia-react-development/SKILL.md | 524 ------------ .../skills/laravel-best-practices/SKILL.md | 59 -- .../rules/advanced-queries.md | 106 --- .../rules/architecture.md | 202 ----- .../rules/blade-views.md | 36 - .../laravel-best-practices/rules/caching.md | 70 -- .../rules/collections.md | 44 - .../laravel-best-practices/rules/config.md | 73 -- .../rules/db-performance.md | 192 ----- .../laravel-best-practices/rules/eloquent.md | 148 ---- .../rules/error-handling.md | 72 -- .../rules/events-notifications.md | 52 -- .../rules/http-client.md | 160 ---- .../laravel-best-practices/rules/mail.md | 27 - .../rules/migrations.md | 121 --- .../rules/queue-jobs.md | 144 ---- .../laravel-best-practices/rules/routing.md | 99 --- .../rules/scheduling.md | 39 - .../laravel-best-practices/rules/security.md | 198 ----- .../laravel-best-practices/rules/style.md | 125 --- .../laravel-best-practices/rules/testing.md | 43 - .../rules/validation.md | 75 -- .agents/skills/pest-testing/SKILL.md | 166 ---- .../skills/tailwindcss-development/SKILL.md | 119 --- .agents/skills/wayfinder-development/SKILL.md | 80 -- .../skills/inertia-react-development/SKILL.md | 524 ------------ .../skills/laravel-best-practices/SKILL.md | 59 -- .../rules/advanced-queries.md | 106 --- .../rules/architecture.md | 202 ----- .../rules/blade-views.md | 36 - .../laravel-best-practices/rules/caching.md | 70 -- .../rules/collections.md | 44 - .../laravel-best-practices/rules/config.md | 73 -- .../rules/db-performance.md | 192 ----- .../laravel-best-practices/rules/eloquent.md | 148 ---- .../rules/error-handling.md | 72 -- .../rules/events-notifications.md | 52 -- .../rules/http-client.md | 160 ---- .../laravel-best-practices/rules/mail.md | 27 - .../rules/migrations.md | 121 --- .../rules/queue-jobs.md | 144 ---- .../laravel-best-practices/rules/routing.md | 99 --- .../rules/scheduling.md | 39 - .../laravel-best-practices/rules/security.md | 198 ----- .../laravel-best-practices/rules/style.md | 125 --- .../laravel-best-practices/rules/testing.md | 43 - .../rules/validation.md | 75 -- .claude/skills/pest-testing/SKILL.md | 166 ---- .../skills/tailwindcss-development/SKILL.md | 119 --- .claude/skills/wayfinder-development/SKILL.md | 80 -- .codex/config.toml | 6 - .gitignore | 14 + .mcp.json | 11 - .prettierignore | 2 - .prettierrc | 25 - AGENTS.md | 206 ----- CLAUDE.md | 206 ----- deployment.md | 352 -------- freekliping-prd.md | 147 ---- opencode.json | 14 - technical-flow.md | 145 ---- todo.md | 769 ------------------ 62 files changed, 14 insertions(+), 7831 deletions(-) delete mode 100644 .agents/skills/inertia-react-development/SKILL.md delete mode 100644 .agents/skills/laravel-best-practices/SKILL.md delete mode 100644 .agents/skills/laravel-best-practices/rules/advanced-queries.md delete mode 100644 .agents/skills/laravel-best-practices/rules/architecture.md delete mode 100644 .agents/skills/laravel-best-practices/rules/blade-views.md delete mode 100644 .agents/skills/laravel-best-practices/rules/caching.md delete mode 100644 .agents/skills/laravel-best-practices/rules/collections.md delete mode 100644 .agents/skills/laravel-best-practices/rules/config.md delete mode 100644 .agents/skills/laravel-best-practices/rules/db-performance.md delete mode 100644 .agents/skills/laravel-best-practices/rules/eloquent.md delete mode 100644 .agents/skills/laravel-best-practices/rules/error-handling.md delete mode 100644 .agents/skills/laravel-best-practices/rules/events-notifications.md delete mode 100644 .agents/skills/laravel-best-practices/rules/http-client.md delete mode 100644 .agents/skills/laravel-best-practices/rules/mail.md delete mode 100644 .agents/skills/laravel-best-practices/rules/migrations.md delete mode 100644 .agents/skills/laravel-best-practices/rules/queue-jobs.md delete mode 100644 .agents/skills/laravel-best-practices/rules/routing.md delete mode 100644 .agents/skills/laravel-best-practices/rules/scheduling.md delete mode 100644 .agents/skills/laravel-best-practices/rules/security.md delete mode 100644 .agents/skills/laravel-best-practices/rules/style.md delete mode 100644 .agents/skills/laravel-best-practices/rules/testing.md delete mode 100644 .agents/skills/laravel-best-practices/rules/validation.md delete mode 100644 .agents/skills/pest-testing/SKILL.md delete mode 100644 .agents/skills/tailwindcss-development/SKILL.md delete mode 100644 .agents/skills/wayfinder-development/SKILL.md delete mode 100644 .claude/skills/inertia-react-development/SKILL.md delete mode 100644 .claude/skills/laravel-best-practices/SKILL.md delete mode 100644 .claude/skills/laravel-best-practices/rules/advanced-queries.md delete mode 100644 .claude/skills/laravel-best-practices/rules/architecture.md delete mode 100644 .claude/skills/laravel-best-practices/rules/blade-views.md delete mode 100644 .claude/skills/laravel-best-practices/rules/caching.md delete mode 100644 .claude/skills/laravel-best-practices/rules/collections.md delete mode 100644 .claude/skills/laravel-best-practices/rules/config.md delete mode 100644 .claude/skills/laravel-best-practices/rules/db-performance.md delete mode 100644 .claude/skills/laravel-best-practices/rules/eloquent.md delete mode 100644 .claude/skills/laravel-best-practices/rules/error-handling.md delete mode 100644 .claude/skills/laravel-best-practices/rules/events-notifications.md delete mode 100644 .claude/skills/laravel-best-practices/rules/http-client.md delete mode 100644 .claude/skills/laravel-best-practices/rules/mail.md delete mode 100644 .claude/skills/laravel-best-practices/rules/migrations.md delete mode 100644 .claude/skills/laravel-best-practices/rules/queue-jobs.md delete mode 100644 .claude/skills/laravel-best-practices/rules/routing.md delete mode 100644 .claude/skills/laravel-best-practices/rules/scheduling.md delete mode 100644 .claude/skills/laravel-best-practices/rules/security.md delete mode 100644 .claude/skills/laravel-best-practices/rules/style.md delete mode 100644 .claude/skills/laravel-best-practices/rules/testing.md delete mode 100644 .claude/skills/laravel-best-practices/rules/validation.md delete mode 100644 .claude/skills/pest-testing/SKILL.md delete mode 100644 .claude/skills/tailwindcss-development/SKILL.md delete mode 100644 .claude/skills/wayfinder-development/SKILL.md delete mode 100644 .codex/config.toml delete mode 100644 .mcp.json delete mode 100644 .prettierignore delete mode 100644 .prettierrc delete mode 100644 AGENTS.md delete mode 100644 CLAUDE.md delete mode 100644 deployment.md delete mode 100644 freekliping-prd.md delete mode 100644 opencode.json delete mode 100644 technical-flow.md delete mode 100644 todo.md diff --git a/.agents/skills/inertia-react-development/SKILL.md b/.agents/skills/inertia-react-development/SKILL.md deleted file mode 100644 index 813e62f..0000000 --- a/.agents/skills/inertia-react-development/SKILL.md +++ /dev/null @@ -1,524 +0,0 @@ ---- -name: inertia-react-development -description: "Develops Inertia.js v3 React client-side applications. Activates when creating React pages, forms, or navigation; using ,
, useForm, useHttp, setLayoutProps, or router; working with deferred props, prefetching, optimistic updates, instant visits, or polling; or when user mentions React with Inertia, React pages, React forms, or React navigation." -license: MIT -metadata: - author: laravel ---- - -# Inertia React Development - -## When to Apply - -Activate this skill when: - -- Creating or modifying React page components for Inertia -- Working with forms in React (using ``, `useForm`, or `useHttp`) -- Implementing client-side navigation with `` or `router` -- Using v3 features: deferred props, prefetching, optimistic updates, instant visits, layout props, HTTP requests, WhenVisible, InfiniteScroll, once props, flash data, or polling -- Building React-specific features with the Inertia protocol - -## Documentation - -Use `search-docs` for detailed Inertia v3 React patterns and documentation. - -## Basic Usage - -### Page Components Location - -React page components should be placed in the `resources/js/pages` directory. - -### Page Component Structure - - -```react -export default function UsersIndex({ users }) { - return ( -
-

Users

-
    - {users.map(user =>
  • {user.name}
  • )} -
-
- ) -} -``` - -## Client-Side Navigation - -### Basic Link Component - -Use `` for client-side navigation instead of traditional `` tags: - - -```react -import { Link, router } from '@inertiajs/react' - -Home -Users -View User -``` - -### Link with Method - - -```react -import { Link } from '@inertiajs/react' - - - Logout - -``` - -### Prefetching - -Prefetch pages to improve perceived performance: - - -```react -import { Link } from '@inertiajs/react' - - - Users - -``` - -### Programmatic Navigation - - -```react -import { router } from '@inertiajs/react' - -function handleClick() { - router.visit('/users') -} - -// Or with options -router.visit('/users', { - method: 'post', - data: { name: 'John' }, - onSuccess: () => console.log('Success!'), -}) -``` - -## Form Handling - -### Form Component (Recommended) - -The recommended way to build forms is with the `` component: - - -```react -import { Form } from '@inertiajs/react' - -export default function CreateUser() { - return ( - - {({ errors, processing, wasSuccessful }) => ( - <> - - {errors.name &&
{errors.name}
} - - - {errors.email &&
{errors.email}
} - - - - {wasSuccessful &&
User created!
} - - )} - - ) -} -``` - -### Form Component With All Props - - -```react -import { Form } from '@inertiajs/react' - -
- {({ - errors, - hasErrors, - processing, - progress, - wasSuccessful, - recentlySuccessful, - clearErrors, - resetAndClearErrors, - defaults, - isDirty, - reset, - submit - }) => ( - <> - - {errors.name &&
{errors.name}
} - - - - {progress && ( - - {progress.percentage}% - - )} - - {wasSuccessful &&
Saved!
} - - )} -
-``` - -### Form Component Reset Props - -The `
` component supports automatic resetting: - -- `resetOnError` - Reset form data when the request fails -- `resetOnSuccess` - Reset form data when the request succeeds -- `setDefaultsOnSuccess` - Update default values on success - -Use the `search-docs` tool with a query of `form component resetting` for detailed guidance. - - -```react -import { Form } from '@inertiajs/react' - - - {({ errors, processing, wasSuccessful }) => ( - <> - - {errors.name &&
{errors.name}
} - - - - )} -
-``` - -Forms can also be built using the `useForm` helper for more programmatic control. Use the `search-docs` tool with a query of `useForm helper` for guidance. - -### `useForm` Hook - -For more programmatic control or to follow existing conventions, use the `useForm` hook: - - -```react -import { useForm } from '@inertiajs/react' - -export default function CreateUser() { - const { data, setData, post, processing, errors, reset } = useForm({ - name: '', - email: '', - password: '', - }) - - function submit(e) { - e.preventDefault() - post('/users', { - onSuccess: () => reset('password'), - }) - } - - return ( -
- setData('name', e.target.value)} - /> - {errors.name &&
{errors.name}
} - - setData('email', e.target.value)} - /> - {errors.email &&
{errors.email}
} - - setData('password', e.target.value)} - /> - {errors.password &&
{errors.password}
} - - -
- ) -} -``` - -## Inertia v3 Features - -### HTTP Requests - -Use the `useHttp` hook for standalone HTTP requests that do not trigger Inertia page visits. It provides the same developer experience as `useForm`, but for plain JSON endpoints. - - -```react -import { useHttp } from '@inertiajs/react' - -export default function Search() { - const { data, setData, get, processing } = useHttp({ - query: '', - }) - - function search(e) { - setData('query', e.target.value) - get('/api/search', { - onSuccess: (response) => { - console.log(response) - }, - }) - } - - return ( - <> - - {processing &&
Searching...
} - - ) -} -``` - -### Optimistic Updates - -Apply data changes instantly before the server responds, with automatic rollback on failure: - - -```react -import { router } from '@inertiajs/react' - -function like(post) { - router.optimistic((props) => ({ - post: { - ...props.post, - likes: props.post.likes + 1, - }, - })).post(`/posts/${post.id}/like`) -} -``` - -Optimistic updates also work with `useForm` and the `
` component: - - -```react -import { Form } from '@inertiajs/react' - - ({ - todos: [...props.todos, { id: Date.now(), name: data.name, done: false }], - })} -> - - -
-``` - -### Instant Visits - -Navigate to a new page immediately without waiting for the server response. The target component renders right away with shared props, while page-specific props load in the background. - - -```react -import { Link } from '@inertiajs/react' - -Dashboard - - - View Post - -``` - -### Layout Props - -Share dynamic data between pages and persistent layouts: - - -```react -export default function Layout({ title = 'My App', showSidebar = true, children }) { - return ( - <> -
{title}
- {showSidebar && } -
{children}
- - ) -} -``` - - -```react -import { setLayoutProps } from '@inertiajs/react' - -export default function Dashboard() { - setLayoutProps({ - title: 'Dashboard', - showSidebar: false, - }) - - return

Dashboard

-} -``` - -### Deferred Props - -Use deferred props to load data after initial page render: - - -```react -export default function UsersIndex({ users }) { - return ( -
-

Users

- {!users ? ( -
-
-
-
- ) : ( -
    - {users.map(user => ( -
  • {user.name}
  • - ))} -
- )} -
- ) -} -``` - -### Polling - -Use the `usePoll` hook to automatically refresh data at intervals. It handles cleanup on unmount and throttles polling when the tab is inactive. - - -```react -import { usePoll } from '@inertiajs/react' - -export default function Dashboard({ stats }) { - usePoll(5000) - - return ( -
-

Dashboard

-
Active Users: {stats.activeUsers}
-
- ) -} -``` - - -```react -import { usePoll } from '@inertiajs/react' - -export default function Dashboard({ stats }) { - const { start, stop } = usePoll(5000, { - only: ['stats'], - onStart() { - console.log('Polling request started') - }, - onFinish() { - console.log('Polling request finished') - }, - }, { - autoStart: false, - keepAlive: true, - }) - - return ( -
-

Dashboard

-
Active Users: {stats.activeUsers}
- - -
- ) -} -``` - -- `autoStart` (default `true`) - set to `false` to start polling manually via the returned `start()` function -- `keepAlive` (default `false`) - set to `true` to prevent throttling when the browser tab is inactive - -### WhenVisible - -Lazy-load a prop when an element scrolls into view. Useful for deferring expensive data that sits below the fold: - - -```react -import { WhenVisible } from '@inertiajs/react' - -export default function Dashboard({ stats }) { - return ( -
-

Dashboard

- - Loading stats...
}> - {({ fetching }) => ( -
-

Total Users: {stats.total_users}

-

Revenue: {stats.revenue}

- {fetching && Refreshing...} -
- )} - - - ) -} -``` - -### InfiniteScroll - -Automatically load additional pages of paginated data as users scroll: - - -```react -import { InfiniteScroll } from '@inertiajs/react' - -export default function Users({ users }) { - return ( - - {users.data.map(user => ( -
{user.name}
- ))} -
- ) -} -``` - -The server must use `Inertia::scroll()` to configure the paginated data. Use the `search-docs` tool with a query of `infinite scroll` for detailed guidance on buffers, manual loading, reverse mode, and custom trigger elements. - -## Server-Side Patterns - -Server-side patterns (Inertia::render, props, middleware) are covered in inertia-laravel guidelines. - -## Common Pitfalls - -- Using traditional `
` links instead of Inertia's `` component (breaks SPA behavior) -- Forgetting to add loading states (skeleton screens) when using deferred props -- Not handling the `undefined` state of deferred props before data loads -- Using `
` without preventing default submission (use `` component or `e.preventDefault()`) -- Forgetting to check if `` component is available in your Inertia version -- Using `router.cancel()` instead of `router.cancelAll()` (v3 breaking change) -- Using `router.on('invalid', ...)` or `router.on('exception', ...)` instead of the renamed `httpException` and `networkError` events diff --git a/.agents/skills/laravel-best-practices/SKILL.md b/.agents/skills/laravel-best-practices/SKILL.md deleted file mode 100644 index d136d75..0000000 --- a/.agents/skills/laravel-best-practices/SKILL.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -name: laravel-best-practices -description: "Apply this skill whenever writing, reviewing, or refactoring Laravel PHP code. This includes creating or modifying controllers, models, migrations, form requests, policies, jobs, scheduled commands, service classes, and Eloquent queries. Triggers for N+1 and query performance issues, caching strategies, authorization and security patterns, validation, error handling, queue and job configuration, route definitions, and architectural decisions. Also use for Laravel code reviews and refactoring existing Laravel code to follow best practices. Covers any task involving Laravel backend PHP code patterns." -license: MIT -metadata: - author: laravel ---- - -# Laravel Best Practices - -Best practices for Laravel, organized as an index of rule files. Each rule file teaches what to do and why. For exact API syntax, verify with `search-docs`. - -## Consistency First - -Before applying any rule, check what the application already does. Laravel offers multiple valid approaches, and the best choice is the one the codebase already uses, even if another pattern would be theoretically better. Inconsistency is worse than a suboptimal pattern. - -Check sibling files, related controllers, models, or tests for established patterns. If one exists, follow it. Don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides. - -## How to Apply - -1. Check the changed files, nearby code, project configuration, and relevant tests for established patterns. Deviate only for a correctness or security defect, and call the deviation out. -2. Map every affected concern to the rule index below. Read each mapped rule file before editing. Skip unrelated rule files. -3. Make the smallest coherent change. Keep the application's architecture and naming instead of introducing a second pattern for the same job. -4. Verify version-sensitive Laravel APIs for the installed version with `search-docs`, or inspect the installed framework when it is unavailable. -5. Run the narrowest relevant tests first, then the project's formatting and static-analysis checks when the change warrants them. -6. Re-read the diff against every mapped rule before finishing. - -## Rule Index - -Cross-cutting changes often need more than one rule file. - -| Concern | Read | -| --- | --- | -| Query count, eager loading, indexes, large datasets | [`rules/db-performance.md`](rules/db-performance.md) | -| Subqueries, aggregates, complex ordering and query plans | [`rules/advanced-queries.md`](rules/advanced-queries.md) | -| Models, relationships, scopes, casts | [`rules/eloquent.md`](rules/eloquent.md) | -| Authentication, authorization, input safety, secrets, uploads | [`rules/security.md`](rules/security.md) | -| Form Requests and validation rules | [`rules/validation.md`](rules/validation.md) | -| Controllers, route binding, resources, middleware | [`rules/routing.md`](rules/routing.md) | -| Schema changes, columns, foreign keys, indexes | [`rules/migrations.md`](rules/migrations.md) | -| Jobs, retries, uniqueness, batches, Horizon | [`rules/queue-jobs.md`](rules/queue-jobs.md) | -| Cache lifetime, invalidation, locks, memoization | [`rules/caching.md`](rules/caching.md) | -| Outbound requests, retries, timeouts, fakes | [`rules/http-client.md`](rules/http-client.md) | -| Exceptions, reporting, rendering, log context | [`rules/error-handling.md`](rules/error-handling.md) | -| Events and notifications | [`rules/events-notifications.md`](rules/events-notifications.md) | -| Mailables and mail assertions | [`rules/mail.md`](rules/mail.md) | -| Scheduled tasks and overlap protection | [`rules/scheduling.md`](rules/scheduling.md) | -| Collections, lazy iteration, bulk operations | [`rules/collections.md`](rules/collections.md) | -| Blade components, attributes, composers | [`rules/blade-views.md`](rules/blade-views.md) | -| Environment values and application configuration | [`rules/config.md`](rules/config.md) | -| Pest/PHPUnit patterns, factories, fakes | [`rules/testing.md`](rules/testing.md) | -| Naming, helpers, file boundaries, PHP style | [`rules/style.md`](rules/style.md) | -| Actions, services, dependencies, application structure | [`rules/architecture.md`](rules/architecture.md) | - -## Decision Rules - -- Prefer framework features and existing application abstractions over new helpers or dependencies. -- Avoid speculative abstractions. Extract code when it creates a clear domain boundary, removes meaningful duplication, or makes behavior independently testable. -- Keep database access out of Blade views and prevent hidden N+1 queries across controllers, resources, jobs, and serialization. diff --git a/.agents/skills/laravel-best-practices/rules/advanced-queries.md b/.agents/skills/laravel-best-practices/rules/advanced-queries.md deleted file mode 100644 index f12876e..0000000 --- a/.agents/skills/laravel-best-practices/rules/advanced-queries.md +++ /dev/null @@ -1,106 +0,0 @@ -# Advanced Query Patterns - -## Use `addSelect()` Subqueries for Single Values from Has-Many - -Instead of eager-loading an entire has-many relationship for a single value (like the latest timestamp), use a correlated subquery via `addSelect()`. This pulls the value directly in the main SQL query — zero extra queries. - -```php -public function scopeWithLastLoginAt($query): void -{ - $query->addSelect([ - 'last_login_at' => Login::select('created_at') - ->whereColumn('user_id', 'users.id') - ->latest() - ->take(1), - ])->withCasts(['last_login_at' => 'datetime']); -} -``` - -## Create Dynamic Relationships via Subquery FK - -Extend the `addSelect()` pattern to fetch a foreign key via subquery, then define a `belongsTo` relationship on that virtual attribute. This provides a fully-hydrated related model without loading the entire collection. - -```php -public function lastLogin(): BelongsTo -{ - return $this->belongsTo(Login::class); -} - -public function scopeWithLastLogin($query): void -{ - $query->addSelect([ - 'last_login_id' => Login::select('id') - ->whereColumn('user_id', 'users.id') - ->latest() - ->take(1), - ])->with('lastLogin'); -} -``` - -## Use Conditional Aggregates Instead of Multiple Count Queries - -Replace N separate `count()` queries with a single query using `CASE WHEN` inside `selectRaw()`. Use `toBase()` to skip model hydration when you only need scalar values. - -```php -$statuses = Feature::toBase() - ->selectRaw("count(case when status = 'Requested' then 1 end) as requested") - ->selectRaw("count(case when status = 'Planned' then 1 end) as planned") - ->selectRaw("count(case when status = 'Completed' then 1 end) as completed") - ->first(); -``` - -## Use `setRelation()` to Prevent Circular N+1 - -When a parent model is eager-loaded with its children, and the view also needs `$child->parent`, use `setRelation()` to inject the already-loaded parent rather than letting Eloquent fire N additional queries. - -```php -$feature->load('comments.user'); -$feature->comments->each->setRelation('feature', $feature); -``` - -## Prefer `whereIn` + Subquery Over `whereHas` - -`whereHas()` emits a correlated `EXISTS` subquery that re-executes per row. Using `whereIn()` with a `select('id')` subquery lets the database use an index lookup instead, without loading data into PHP memory. - -Incorrect (correlated EXISTS re-executes per row): - -```php -$query->whereHas('company', fn ($q) => $q->where('name', 'like', $term)); -``` - -Correct (index-friendly subquery, no PHP memory overhead): - -```php -$query->whereIn('company_id', Company::where('name', 'like', $term)->select('id')); -``` - -## Sometimes Two Simple Queries Beat One Complex Query - -Running a small, targeted secondary query and passing its results via `whereIn` is often faster than a single complex correlated subquery or join. The additional round-trip is worthwhile when the secondary query is highly selective and uses its own index. - -## Use Compound Indexes Matching `orderBy` Column Order - -When ordering by multiple columns, create a single compound index in the same column order as the `ORDER BY` clause. Individual single-column indexes cannot combine for multi-column sorts — the database will filesort without a compound index. - -```php -// Migration -$table->index(['last_name', 'first_name']); - -// Query — column order must match the index -User::query()->orderBy('last_name')->orderBy('first_name')->paginate(); -``` - -## Use Correlated Subqueries for Has-Many Ordering - -When sorting by a value from a has-many relationship, avoid joins (they duplicate rows). Use a correlated subquery inside `orderBy()` instead, paired with an `addSelect` scope for eager loading. - -```php -public function scopeOrderByLastLogin($query): void -{ - $query->orderByDesc(Login::select('created_at') - ->whereColumn('user_id', 'users.id') - ->latest() - ->take(1) - ); -} -``` diff --git a/.agents/skills/laravel-best-practices/rules/architecture.md b/.agents/skills/laravel-best-practices/rules/architecture.md deleted file mode 100644 index 138d5a4..0000000 --- a/.agents/skills/laravel-best-practices/rules/architecture.md +++ /dev/null @@ -1,202 +0,0 @@ -# Architecture Best Practices - -## Single-Purpose Action Classes - -Extract discrete business operations into invokable Action classes. - -```php -class CreateOrderAction -{ - public function __construct(private InventoryService $inventory) {} - - public function handle(array $data): Order - { - $order = Order::create($data); - $this->inventory->reserve($order); - - return $order; - } -} -``` - -## Use Dependency Injection - -Always use constructor injection. Avoid `app()` or `resolve()` inside classes. - -Incorrect: -```php -class OrderController extends Controller -{ - public function store(StoreOrderRequest $request) - { - $service = app(OrderService::class); - - return $service->create($request->validated()); - } -} -``` - -Correct: -```php -class OrderController extends Controller -{ - public function __construct(private OrderService $service) {} - - public function store(StoreOrderRequest $request) - { - return $this->service->create($request->validated()); - } -} -``` - -## Code to Interfaces - -Depend on contracts at system boundaries (payment gateways, notification channels, external APIs) for testability and swappability. - -Incorrect (concrete dependency): -```php -class OrderService -{ - public function __construct(private StripeGateway $gateway) {} -} -``` - -Correct (interface dependency): -```php -interface PaymentGateway -{ - public function charge(int $amount, string $customerId): PaymentResult; -} - -class OrderService -{ - public function __construct(private PaymentGateway $gateway) {} -} -``` - -Bind in a service provider: - -```php -$this->app->bind(PaymentGateway::class, StripeGateway::class); -``` - -## Default Sort by Descending - -When no explicit order is specified, sort by `id` or `created_at` descending. Without an explicit `ORDER BY`, row order is undefined. - -Incorrect: -```php -$posts = Post::paginate(); -``` - -Correct: -```php -$posts = Post::latest()->paginate(); -``` - -## Use Atomic Locks for Race Conditions - -Prevent race conditions with `Cache::lock()` or `lockForUpdate()`. - -```php -Cache::lock('order-processing-'.$order->id, 10)->block(5, function () use ($order) { - $order->process(); -}); - -// Or at query level -$product = Product::where('id', $id)->lockForUpdate()->first(); -``` - -## Use `mb_*` String Functions - -When no Laravel helper exists, prefer `mb_strlen`, `mb_strtolower`, etc. for UTF-8 safety. Standard PHP string functions count bytes, not characters. - -Incorrect: -```php -strlen('José'); // 5 (bytes, not characters) -strtolower('MÜNCHEN'); // 'mÜnchen' — fails on multibyte -``` - -Correct: -```php -mb_strlen('José'); // 4 (characters) -mb_strtolower('MÜNCHEN'); // 'münchen' - -// Prefer Laravel's Str helpers when available -Str::length('José'); // 4 -Str::lower('MÜNCHEN'); // 'münchen' -``` - -## Use `defer()` for Post-Response Work - -For lightweight tasks that don't need to survive a crash (logging, analytics, cleanup), use `defer()` instead of dispatching a job. The callback runs after the HTTP response is sent — no queue overhead. - -Incorrect (job overhead for trivial work): -```php -dispatch(new LogPageView($page)); -``` - -Correct (runs after response, same process): -```php -defer(fn () => PageView::create(['page_id' => $page->id, 'user_id' => auth()->id()])); -``` - -Use jobs when the work must survive process crashes or needs retry logic. Use `defer()` for fire-and-forget work. - -## Use `Context` for Request-Scoped Data - -The `Context` facade passes data through the entire request lifecycle — middleware, controllers, jobs, logs — without passing arguments manually. - -```php -// In middleware -Context::add('tenant_id', $request->header('X-Tenant-ID')); - -// Anywhere later — controllers, jobs, log context -$tenantId = Context::get('tenant_id'); -``` - -Context data automatically propagates to queued jobs and is included in log entries. Use `Context::addHidden()` for sensitive data that should be available in queued jobs but excluded from log context. If data must not leave the current process, do not store it in `Context`. - -## Use `Concurrency::run()` for Parallel Execution - -Run independent operations in parallel using child processes — no async libraries needed. - -```php -use Illuminate\Support\Facades\Concurrency; - -[$users, $orders] = Concurrency::run([ - fn () => User::count(), - fn () => Order::where('status', 'pending')->count(), -]); -``` - -Each closure runs in a separate process with full Laravel access. Use for independent database queries, API calls, or computations that would otherwise run sequentially. - -## Convention Over Configuration - -Follow Laravel conventions. Don't override defaults unnecessarily. - -Incorrect: -```php -class Customer extends Model -{ - protected $table = 'Customer'; - protected $primaryKey = 'customer_id'; - - public function roles(): BelongsToMany - { - return $this->belongsToMany(Role::class, 'role_customer', 'customer_id', 'role_id'); - } -} -``` - -Correct: -```php -class Customer extends Model -{ - public function roles(): BelongsToMany - { - return $this->belongsToMany(Role::class); - } -} -``` diff --git a/.agents/skills/laravel-best-practices/rules/blade-views.md b/.agents/skills/laravel-best-practices/rules/blade-views.md deleted file mode 100644 index 5f0b3a1..0000000 --- a/.agents/skills/laravel-best-practices/rules/blade-views.md +++ /dev/null @@ -1,36 +0,0 @@ -# Blade & Views Best Practices - -## Use `$attributes->merge()` in Component Templates - -Hardcoding classes prevents consumers from adding their own. `merge()` combines class attributes cleanly. - -```blade -
merge(['class' => 'alert alert-'.$type]) }}> - {{ $message }} -
-``` - -## Use `@pushOnce` for Per-Component Scripts - -If a component renders inside a `@foreach`, `@push` inserts the script N times. `@pushOnce` guarantees it's included exactly once. - -## Prefer Blade Components Over `@include` - -`@include` shares all parent variables implicitly (hidden coupling). Components have explicit props, attribute bags, and slots. - -## Use View Composers for Shared View Data - -If every controller rendering a sidebar must pass `$categories`, that's duplicated code. A View Composer centralizes it. - -## Use Blade Fragments for Partial Re-Renders (htmx/Turbo) - -A single view can return either the full page or just a fragment, keeping routing clean. - -```php -return view('dashboard', compact('users')) - ->fragmentIf($request->hasHeader('HX-Request'), 'user-list'); -``` - -## Use `@aware` for Deeply Nested Component Props - -Avoids re-passing parent props through every level of nested components. diff --git a/.agents/skills/laravel-best-practices/rules/caching.md b/.agents/skills/laravel-best-practices/rules/caching.md deleted file mode 100644 index 67408d6..0000000 --- a/.agents/skills/laravel-best-practices/rules/caching.md +++ /dev/null @@ -1,70 +0,0 @@ -# Caching Best Practices - -## Use `Cache::remember()` Instead of Manual Get/Put - -Cleaner cache-aside pattern that removes boilerplate. use `Cache::lock()` for race conditions. - -Incorrect: -```php -$val = Cache::get('stats'); -if (! $val) { - $val = $this->computeStats(); - Cache::put('stats', $val, 60); -} -``` - -Correct: -```php -$val = Cache::remember('stats', 60, fn () => $this->computeStats()); -``` - -## Use `Cache::flexible()` for Stale-While-Revalidate - -On high-traffic keys, one user always gets a slow response when the cache expires. `flexible()` serves slightly stale data while refreshing in the background. - -Incorrect: `Cache::remember('users', 300, fn () => User::all());` - -Correct: `Cache::flexible('users', [300, 600], fn () => User::all());` — fresh for 5 min, stale-but-served up to 10 min, refreshes via deferred function. - -## Use `Cache::memo()` to Avoid Redundant Hits Within a Request - -If the same cache key is read multiple times per request (e.g., a service called from multiple places), `memo()` stores the resolved value in memory. - -`Cache::memo()->get('settings');` — 5 calls = 1 Redis round-trip instead of 5. - -## Use Cache Tags to Invalidate Related Groups - -Without tags, invalidating a group of entries requires tracking every key. Tags let you flush atomically. Only works with `redis`, `memcached`, `dynamodb` — not `file` or `database`. - -```php -Cache::tags(['user-1'])->flush(); -``` - -## Use `Cache::add()` for Atomic Conditional Writes - -`add()` only writes if the key does not exist — atomic, no race condition between checking and writing. - -Incorrect: `if (! Cache::has('lock')) { Cache::put('lock', true, 10); }` - -Correct: `Cache::add('lock', true, 10);` - -## Use `once()` for Per-Request Memoization - -`once()` memoizes a function's return value for the lifetime of the object (or request for closures). Unlike `Cache::memo()`, it doesn't hit the cache store at all — pure in-memory. - -```php -public function roles(): Collection -{ - return once(fn () => $this->loadRoles()); -} -``` - -Multiple calls return the cached result without re-executing. Use `once()` for expensive computations called multiple times per request. Use `Cache::memo()` when you also want cross-request caching. - -## Configure Failover Cache Stores in Production - -If Redis goes down, the app falls back to a secondary store automatically. - -```php -'failover' => ['driver' => 'failover', 'stores' => ['redis', 'database']], -``` diff --git a/.agents/skills/laravel-best-practices/rules/collections.md b/.agents/skills/laravel-best-practices/rules/collections.md deleted file mode 100644 index 18e8d9e..0000000 --- a/.agents/skills/laravel-best-practices/rules/collections.md +++ /dev/null @@ -1,44 +0,0 @@ -# Collection Best Practices - -## Use Higher-Order Messages for Simple Operations - -Incorrect: -```php -$users->each(function (User $user) { - $user->markAsVip(); -}); -``` - -Correct: `$users->each->markAsVip();` - -Works with `each`, `map`, `sum`, `filter`, `reject`, `contains`, etc. - -## Choose `cursor()` vs. `lazy()` Correctly - -- `cursor()` — one model in memory, but cannot eager-load relationships (N+1 risk). -- `lazy()` — chunked pagination returning a flat LazyCollection, supports eager loading. - -Incorrect: `User::with('roles')->cursor()` — eager loading silently ignored. - -Correct: `User::with('roles')->lazy()` for relationship access; `User::cursor()` for attribute-only work. - -## Use `lazyById()` When Updating Records While Iterating - -`lazy()` uses offset pagination — updating records during iteration can skip or double-process. `lazyById()` uses `id > last_id`, safe against mutation. - -## Use `toQuery()` for Bulk Operations on Collections - -Avoids manual `whereIn` construction. - -Incorrect: `User::whereIn('id', $users->pluck('id'))->update([...]);` - -Correct: `$users->toQuery()->update([...]);` - -## Use `#[CollectedBy]` for Custom Collection Classes - -More declarative than overriding `newCollection()`. - -```php -#[CollectedBy(UserCollection::class)] -class User extends Model {} -``` diff --git a/.agents/skills/laravel-best-practices/rules/config.md b/.agents/skills/laravel-best-practices/rules/config.md deleted file mode 100644 index 9bea727..0000000 --- a/.agents/skills/laravel-best-practices/rules/config.md +++ /dev/null @@ -1,73 +0,0 @@ -# Configuration Best Practices - -## `env()` Only in Config Files - -Direct `env()` calls may return `null` when config is cached. - -Incorrect: -```php -$key = env('API_KEY'); -``` - -Correct: -```php -// config/services.php -'key' => env('API_KEY'), - -// Application code -$key = config('services.key'); -``` - -## Use Encrypted Env or External Secrets - -Never store production secrets in plain `.env` files in version control. - -Incorrect: -```bash - -# .env committed to repo or shared in Slack - -STRIPE_SECRET=sk_live_abc123 -AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI -``` - -Correct: -```bash -php artisan env:encrypt --env=production --readable -php artisan env:decrypt --env=production -``` - -For cloud deployments, prefer the platform's native secret store (AWS Secrets Manager, Vault, etc.) and inject at runtime. - -## Use `App::environment()` for Environment Checks - -Incorrect: -```php -if (env('APP_ENV') === 'production') { -``` - -Correct: -```php -if (app()->isProduction()) { -// or -if (App::environment('production')) { -``` - -## Use Constants and Language Files - -Use class constants instead of hardcoded magic strings for model states, types, and statuses. - -```php -// Incorrect -return $this->type === 'normal'; - -// Correct -return $this->type === self::TYPE_NORMAL; -``` - -If the application already uses language files for localization, use `__()` for user-facing strings too. Do not introduce language files purely for English-only apps — simple string literals are fine there. - -```php -// Only when lang files already exist in the project -return back()->with('message', __('app.article_added')); -``` diff --git a/.agents/skills/laravel-best-practices/rules/db-performance.md b/.agents/skills/laravel-best-practices/rules/db-performance.md deleted file mode 100644 index c49ba16..0000000 --- a/.agents/skills/laravel-best-practices/rules/db-performance.md +++ /dev/null @@ -1,192 +0,0 @@ -# Database Performance Best Practices - -## Always Eager Load Relationships - -Lazy loading causes N+1 query problems — one query per loop iteration. Always use `with()` to load relationships upfront. - -Incorrect (N+1 — executes 1 + N queries): -```php -$posts = Post::all(); -foreach ($posts as $post) { - echo $post->author->name; -} -``` - -Correct (2 queries total): -```php -$posts = Post::with('author')->get(); -foreach ($posts as $post) { - echo $post->author->name; -} -``` - -Constrain eager loads to select only needed columns (always include the foreign key): - -```php -$users = User::with(['posts' => function ($query) { - $query->select('id', 'user_id', 'title') - ->where('published', true) - ->latest() - ->limit(10); -}])->get(); -``` - -## Prevent Lazy Loading in Development - -Enable this in `AppServiceProvider::boot()` to catch N+1 issues during development. - -```php -public function boot(): void -{ - Model::preventLazyLoading(! app()->isProduction()); -} -``` - -Throws `LazyLoadingViolationException` when a relationship is accessed without being eager-loaded. - -## Select Only Needed Columns - -Avoid `SELECT *` — especially when tables have large text or JSON columns. - -Incorrect: -```php -$posts = Post::with('author')->get(); -``` - -Correct: -```php -$posts = Post::select('id', 'title', 'user_id', 'created_at') - ->with(['author:id,name,avatar']) - ->get(); -``` - -When selecting columns on eager-loaded relationships, always include the foreign key column or the relationship won't match. - -## Chunk Large Datasets - -Never load thousands of records at once. Use chunking for batch processing. - -Incorrect: -```php -$users = User::all(); -foreach ($users as $user) { - $user->notify(new WeeklyDigest); -} -``` - -Correct: -```php -User::where('subscribed', true)->chunk(200, function ($users) { - foreach ($users as $user) { - $user->notify(new WeeklyDigest); - } -}); -``` - -Use `chunkById()` when modifying records during iteration — standard `chunk()` uses OFFSET which shifts when rows change: - -```php -User::where('active', false)->chunkById(200, function ($users) { - $users->each->delete(); -}); -``` - -## Add Database Indexes - -Index columns that appear in `WHERE`, `ORDER BY`, `JOIN`, and `GROUP BY` clauses. - -Incorrect: -```php -Schema::create('orders', function (Blueprint $table) { - $table->id(); - $table->foreignId('user_id')->constrained(); - $table->string('status'); - $table->timestamps(); -}); -``` - -Correct: -```php -Schema::create('orders', function (Blueprint $table) { - $table->id(); - $table->foreignId('user_id')->index()->constrained(); - $table->string('status')->index(); - $table->timestamps(); - $table->index(['status', 'created_at']); -}); -``` - -Add composite indexes for common query patterns (e.g., `WHERE status = ? ORDER BY created_at`). - -## Use `withCount()` for Counting Relations - -Never load entire collections just to count them. - -Incorrect: -```php -$posts = Post::all(); -foreach ($posts as $post) { - echo $post->comments->count(); -} -``` - -Correct: -```php -$posts = Post::withCount('comments')->get(); -foreach ($posts as $post) { - echo $post->comments_count; -} -``` - -Conditional counting: - -```php -$posts = Post::withCount([ - 'comments', - 'comments as approved_comments_count' => function ($query) { - $query->where('approved', true); - }, -])->get(); -``` - -## Use `cursor()` for Memory-Efficient Iteration - -For read-only iteration over large result sets, `cursor()` loads one record at a time via a PHP generator. - -Incorrect: -```php -$users = User::where('active', true)->get(); -``` - -Correct: -```php -foreach (User::where('active', true)->cursor() as $user) { - ProcessUser::dispatch($user->id); -} -``` - -Use `cursor()` for read-only iteration. Use `chunk()` / `chunkById()` when modifying records. - -## No Queries in Blade Templates - -Never execute queries in Blade templates. Pass data from controllers. - -Incorrect: -```blade -@foreach (User::all() as $user) - {{ $user->profile->name }} -@endforeach -``` - -Correct: -```php -// Controller -$users = User::with('profile')->get(); -return view('users.index', compact('users')); -``` - -```blade -@foreach ($users as $user) - {{ $user->profile->name }} -@endforeach -``` diff --git a/.agents/skills/laravel-best-practices/rules/eloquent.md b/.agents/skills/laravel-best-practices/rules/eloquent.md deleted file mode 100644 index 413d5da..0000000 --- a/.agents/skills/laravel-best-practices/rules/eloquent.md +++ /dev/null @@ -1,148 +0,0 @@ -# Eloquent Best Practices - -## Use Correct Relationship Types - -Use `hasMany`, `belongsTo`, `morphMany`, etc. with proper return type hints. - -```php -public function comments(): HasMany -{ - return $this->hasMany(Comment::class); -} - -public function author(): BelongsTo -{ - return $this->belongsTo(User::class, 'user_id'); -} -``` - -## Use Local Scopes for Reusable Queries - -Extract reusable query constraints into local scopes to avoid duplication. - -Incorrect: -```php -$active = User::where('verified', true)->whereNotNull('activated_at')->get(); -$articles = Article::whereHas('user', function ($q) { - $q->where('verified', true)->whereNotNull('activated_at'); -})->get(); -``` - -Correct: -```php -public function scopeActive(Builder $query): Builder -{ - return $query->where('verified', true)->whereNotNull('activated_at'); -} - -// Usage -$active = User::active()->get(); -$articles = Article::whereHas('user', fn ($q) => $q->active())->get(); -``` - -## Apply Global Scopes Sparingly - -Global scopes silently modify every query on the model, making debugging difficult. Prefer local scopes and reserve global scopes for truly universal constraints like soft deletes or multi-tenancy. - -Incorrect (global scope for a conditional filter): -```php -class PublishedScope implements Scope -{ - public function apply(Builder $builder, Model $model): void - { - $builder->where('published', true); - } -} -// Now admin panels, reports, and background jobs all silently skip drafts -``` - -Correct (local scope you opt into): -```php -public function scopePublished(Builder $query): Builder -{ - return $query->where('published', true); -} - -Post::published()->paginate(); // Explicit -Post::paginate(); // Admin sees all -``` - -## Define Attribute Casts - -Use the `casts()` method (or `$casts` property following project convention) for automatic type conversion. - -```php -protected function casts(): array -{ - return [ - 'is_active' => 'boolean', - 'metadata' => 'array', - 'total' => 'decimal:2', - ]; -} -``` - -## Cast Date Columns Properly - -Always cast date columns. Use Carbon instances in templates instead of formatting strings manually. - -Incorrect: -```blade -{{ Carbon::createFromFormat('Y-d-m H-i', $order->ordered_at)->toDateString() }} -``` - -Correct: -```php -protected function casts(): array -{ - return [ - 'ordered_at' => 'datetime', - ]; -} -``` - -```blade -{{ $order->ordered_at->toDateString() }} -{{ $order->ordered_at->format('m-d') }} -``` - -## Use `whereBelongsTo()` for Relationship Queries - -Cleaner than manually specifying foreign keys. - -Incorrect: -```php -Post::where('user_id', $user->id)->get(); -``` - -Correct: -```php -Post::whereBelongsTo($user)->get(); -Post::whereBelongsTo($user, 'author')->get(); -``` - -## Avoid Hardcoded Table Names in Queries - -Never use string literals for table names in raw queries, joins, or subqueries. Hardcoded table names make it impossible to find all places a model is used and break refactoring (e.g., renaming a table requires hunting through every raw string). - -Incorrect: -```php -DB::table('users')->where('active', true)->get(); - -$query->join('companies', 'companies.id', '=', 'users.company_id'); - -DB::select('SELECT * FROM orders WHERE status = ?', ['pending']); -``` - -Correct — reference the model's table: -```php -DB::table((new User)->getTable())->where('active', true)->get(); - -// Even better — use Eloquent or the query builder instead of raw SQL -User::where('active', true)->get(); -Order::where('status', 'pending')->get(); -``` - -Prefer Eloquent queries and relationships over `DB::table()` whenever possible — they already reference the model's table. When `DB::table()` or raw joins are unavoidable, always use `(new Model)->getTable()` to keep the reference traceable. - -**Exception — migrations:** In migrations, hardcoded table names via `DB::table('settings')` are acceptable and preferred. Models change over time but migrations are frozen snapshots — referencing a model that is later renamed or deleted would break the migration. diff --git a/.agents/skills/laravel-best-practices/rules/error-handling.md b/.agents/skills/laravel-best-practices/rules/error-handling.md deleted file mode 100644 index 4b14866..0000000 --- a/.agents/skills/laravel-best-practices/rules/error-handling.md +++ /dev/null @@ -1,72 +0,0 @@ -# Error Handling Best Practices - -## Exception Reporting and Rendering - -There are two valid approaches — choose one and apply it consistently across the project. - -**Co-location on the exception class** — keeps behavior alongside the exception definition, easier to find: - -```php -class InvalidOrderException extends Exception -{ - public function report(): void { /* custom reporting */ } - - public function render(Request $request): Response - { - return response()->view('errors.invalid-order', status: 422); - } -} -``` - -**Centralized in `bootstrap/app.php`** — all exception handling in one place, easier to see the full picture: - -```php -->withExceptions(function (Exceptions $exceptions) { - $exceptions->report(function (InvalidOrderException $e) { /* ... */ }); - $exceptions->render(function (InvalidOrderException $e, Request $request) { - return response()->view('errors.invalid-order', status: 422); - }); -}) -``` - -Check the existing codebase and follow whichever pattern is already established. - -## Use `ShouldntReport` for Exceptions That Should Never Log - -More discoverable than listing classes in `dontReport()`. - -```php -class PodcastProcessingException extends Exception implements ShouldntReport {} -``` - -## Throttle High-Volume Exceptions - -A single failing integration can flood error tracking. Use `throttle()` to rate-limit per exception type. - -## Enable `dontReportDuplicates()` - -Prevents the same exception instance from being logged multiple times when `report($e)` is called in multiple catch blocks. - -## Force JSON Error Rendering for API Routes - -Laravel auto-detects `Accept: application/json` but API clients may not set it. Explicitly declare JSON rendering for API routes. - -```php -$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) { - return $request->is('api/*') || $request->expectsJson(); -}); -``` - -## Add Context to Exception Classes - -Attach structured data to exceptions at the source via a `context()` method — Laravel includes it automatically in the log entry. - -```php -class InvalidOrderException extends Exception -{ - public function context(): array - { - return ['order_id' => $this->orderId]; - } -} -``` diff --git a/.agents/skills/laravel-best-practices/rules/events-notifications.md b/.agents/skills/laravel-best-practices/rules/events-notifications.md deleted file mode 100644 index 82e329e..0000000 --- a/.agents/skills/laravel-best-practices/rules/events-notifications.md +++ /dev/null @@ -1,52 +0,0 @@ -# Events & Notifications Best Practices - -## Rely on Event Discovery - -Laravel auto-discovers listeners by reading `handle(EventType $event)` type-hints. No manual registration needed in `AppServiceProvider`. - -## Run `event:cache` in Production Deploy - -Event discovery scans the filesystem per-request in dev. Cache it in production: `php artisan optimize` or `php artisan event:cache`. - -## Use `ShouldDispatchAfterCommit` Inside Transactions - -Without it, a queued listener may process before the DB transaction commits, reading data that doesn't exist yet. - -```php -class OrderShipped implements ShouldDispatchAfterCommit {} -``` - -## Always Queue Notifications - -Notifications often hit external APIs (email, SMS, Slack). Without `ShouldQueue`, they block the HTTP response. - -```php -class InvoicePaid extends Notification implements ShouldQueue -{ - use Queueable; -} -``` - -## Use `afterCommit()` on Notifications in Transactions - -Same race condition as events — call `afterCommit()` to delay dispatch until the transaction commits. - -```php -$user->notify((new InvoicePaid($invoice))->afterCommit()); -``` - -## Route Notification Channels to Dedicated Queues - -Mail and database notifications have different priorities. Use `viaQueues()` to route them to separate queues. - -## Use On-Demand Notifications for Non-User Recipients - -Avoid creating dummy models to send notifications to arbitrary addresses. - -```php -Notification::route('mail', 'admin@example.com')->notify(new SystemAlert()); -``` - -## Implement `HasLocalePreference` on Notifiable Models - -Laravel automatically uses the user's preferred locale for all notifications and mailables — no per-call `locale()` needed. diff --git a/.agents/skills/laravel-best-practices/rules/http-client.md b/.agents/skills/laravel-best-practices/rules/http-client.md deleted file mode 100644 index 8e2f16e..0000000 --- a/.agents/skills/laravel-best-practices/rules/http-client.md +++ /dev/null @@ -1,160 +0,0 @@ -# HTTP Client Best Practices - -## Always Set Explicit Timeouts - -The default timeout is 30 seconds — too long for most API calls. Always set explicit `timeout` and `connectTimeout` to fail fast. - -Incorrect: -```php -$response = Http::get('https://api.example.com/users'); -``` - -Correct: -```php -$response = Http::timeout(5) - ->connectTimeout(3) - ->get('https://api.example.com/users'); -``` - -For service-specific clients, define timeouts in a macro: - -```php -Http::macro('github', function () { - return Http::baseUrl('https://api.github.com') - ->timeout(10) - ->connectTimeout(3) - ->withToken(config('services.github.token')); -}); - -$response = Http::github()->get('/repos/laravel/framework'); -``` - -## Use Retry with Backoff for External APIs - -External APIs have transient failures. Use `retry()` with increasing delays. - -Incorrect: -```php -$response = Http::post('https://api.stripe.com/v1/charges', $data); - -if ($response->failed()) { - throw new PaymentFailedException('Charge failed'); -} -``` - -Correct: -```php -$response = Http::retry([100, 500, 1000]) - ->timeout(10) - ->post('https://api.stripe.com/v1/charges', $data); -``` - -Only retry on specific errors: - -```php -$response = Http::retry(3, 100, function (Throwable $exception, PendingRequest $request) { - return $exception instanceof ConnectionException - || ($exception instanceof RequestException && $exception->response->serverError()); -})->post('https://api.example.com/data'); -``` - -## Handle Errors Explicitly - -The HTTP Client does not throw on 4xx/5xx by default. Always check status or use `throw()`. - -Incorrect: -```php -$response = Http::get('https://api.example.com/users/1'); -$user = $response->json(); // Could be an error body -``` - -Correct: -```php -$response = Http::timeout(5) - ->get('https://api.example.com/users/1') - ->throw(); - -$user = $response->json(); -``` - -For graceful degradation: - -```php -$response = Http::get('https://api.example.com/users/1'); - -if ($response->successful()) { - return $response->json(); -} - -if ($response->notFound()) { - return null; -} - -$response->throw(); -``` - -## Use Request Pooling for Concurrent Requests - -When making multiple independent API calls, use `Http::pool()` instead of sequential calls. - -Incorrect: -```php -$users = Http::get('https://api.example.com/users')->json(); -$posts = Http::get('https://api.example.com/posts')->json(); -$comments = Http::get('https://api.example.com/comments')->json(); -``` - -Correct: -```php -use Illuminate\Http\Client\Pool; - -$responses = Http::pool(fn (Pool $pool) => [ - $pool->as('users')->get('https://api.example.com/users'), - $pool->as('posts')->get('https://api.example.com/posts'), - $pool->as('comments')->get('https://api.example.com/comments'), -]); - -$users = $responses['users']->json(); -$posts = $responses['posts']->json(); -``` - -## Fake HTTP Calls in Tests - -Never make real HTTP requests in tests. Use `Http::fake()` and `preventStrayRequests()`. - -Incorrect: -```php -it('syncs user from API', function () { - $service = new UserSyncService; - $service->sync(1); // Hits the real API -}); -``` - -Correct: -```php -it('syncs user from API', function () { - Http::preventStrayRequests(); - - Http::fake([ - 'api.example.com/users/1' => Http::response([ - 'name' => 'John Doe', - 'email' => 'john@example.com', - ]), - ]); - - $service = new UserSyncService; - $service->sync(1); - - Http::assertSent(function (Request $request) { - return $request->url() === 'https://api.example.com/users/1'; - }); -}); -``` - -Test failure scenarios too: - -```php -Http::fake([ - 'api.example.com/*' => Http::failedConnection(), -]); -``` diff --git a/.agents/skills/laravel-best-practices/rules/mail.md b/.agents/skills/laravel-best-practices/rules/mail.md deleted file mode 100644 index 7c71733..0000000 --- a/.agents/skills/laravel-best-practices/rules/mail.md +++ /dev/null @@ -1,27 +0,0 @@ -# Mail Best Practices - -## Implement `ShouldQueue` on the Mailable Class - -Makes queueing the default regardless of how the mailable is dispatched. No need to remember `Mail::queue()` at every call site — `Mail::send()` also queues it. - -## Use `afterCommit()` on Mailables Inside Transactions - -A queued mailable dispatched inside a transaction may process before the commit. Use `$this->afterCommit()` in the constructor. - -## Use `assertQueued()` Not `assertSent()` for Queued Mailables - -`Mail::assertSent()` only catches synchronous mail. Queued mailables fail `assertSent` with a "Did you mean to use assertQueued()?" hint. - -Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`. - -Correct: `Mail::assertQueued(OrderShipped::class);` - -## Use Markdown Mailables for Transactional Emails - -Markdown mailables auto-generate both HTML and plain-text versions, use responsive components, and allow global style customization. Generate with `--markdown` flag. - -## Separate Content Tests from Sending Tests - -Content tests: instantiate the mailable directly, call `assertSeeInHtml()`. -Sending tests: use `Mail::fake()` and `assertSent()`/`assertQueued()`. -Don't mix them — it conflates concerns and makes tests brittle. diff --git a/.agents/skills/laravel-best-practices/rules/migrations.md b/.agents/skills/laravel-best-practices/rules/migrations.md deleted file mode 100644 index df6f5f3..0000000 --- a/.agents/skills/laravel-best-practices/rules/migrations.md +++ /dev/null @@ -1,121 +0,0 @@ -# Migration Best Practices - -## Generate Migrations with Artisan - -Always use `php artisan make:migration` for consistent naming and timestamps. - -Incorrect (manually created file): -```php -// database/migrations/posts_migration.php ← wrong naming, no timestamp -``` - -Correct (Artisan-generated): -```bash -php artisan make:migration create_posts_table -php artisan make:migration add_slug_to_posts_table -``` - -## Use `constrained()` for Foreign Keys - -Automatic naming and referential integrity. - -```php -$table->foreignId('user_id')->constrained()->cascadeOnDelete(); - -// Non-standard names -$table->foreignId('author_id')->constrained('users'); -``` - -## Never Modify Deployed Migrations - -Once a migration has run in production, treat it as immutable. Create a new migration to change the table. - -Incorrect (editing a deployed migration): -```php -// 2024_01_01_create_posts_table.php — already in production -$table->string('slug')->unique(); // ← added after deployment -``` - -Correct (new migration to alter): -```php -// 2024_03_15_add_slug_to_posts_table.php -Schema::table('posts', function (Blueprint $table) { - $table->string('slug')->unique()->after('title'); -}); -``` - -## Add Indexes in the Migration - -Add indexes when creating the table, not as an afterthought. Columns used in `WHERE`, `ORDER BY`, and `JOIN` clauses need indexes. - -Incorrect: -```php -Schema::create('orders', function (Blueprint $table) { - $table->id(); - $table->foreignId('user_id')->constrained(); - $table->string('status'); - $table->timestamps(); -}); -``` - -Correct: -```php -Schema::create('orders', function (Blueprint $table) { - $table->id(); - $table->foreignId('user_id')->constrained()->index(); - $table->string('status')->index(); - $table->timestamp('shipped_at')->nullable()->index(); - $table->timestamps(); -}); -``` - -## Mirror Defaults in Model `$attributes` - -When a column has a database default, mirror it in the model so new instances have correct values before saving. - -```php -// Migration -$table->string('status')->default('pending'); - -// Model -protected $attributes = [ - 'status' => 'pending', -]; -``` - -## Write Reversible `down()` Methods by Default - -Implement `down()` for schema changes that can be safely reversed so `migrate:rollback` works in CI and failed deployments. - -```php -public function down(): void -{ - Schema::table('posts', function (Blueprint $table) { - $table->dropColumn('slug'); - }); -} -``` - -For intentionally irreversible migrations (e.g., destructive data backfills), leave a clear comment and require a forward fix migration instead of pretending rollback is supported. - -## Keep Migrations Focused - -One concern per migration. Never mix DDL (schema changes) and DML (data manipulation). - -Incorrect (partial failure creates unrecoverable state): -```php -public function up(): void -{ - Schema::create('settings', function (Blueprint $table) { ... }); - DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']); -} -``` - -Correct (separate migrations): -```php -// Migration 1: create_settings_table -Schema::create('settings', function (Blueprint $table) { ... }); - -// Migration 2: seed_default_settings -DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']); -``` diff --git a/.agents/skills/laravel-best-practices/rules/queue-jobs.md b/.agents/skills/laravel-best-practices/rules/queue-jobs.md deleted file mode 100644 index c41915e..0000000 --- a/.agents/skills/laravel-best-practices/rules/queue-jobs.md +++ /dev/null @@ -1,144 +0,0 @@ -# Queue & Job Best Practices - -## Set `retry_after` Greater Than `timeout` - -If `retry_after` is shorter than the job's `timeout`, the queue worker re-dispatches the job while it's still running, causing duplicate execution. - -Incorrect (`retry_after` ≤ `timeout`): -```php -class ProcessReport implements ShouldQueue -{ - public $timeout = 120; -} - -// config/queue.php — retry_after: 90 ← job retried while still running! -``` - -Correct (`retry_after` > `timeout`): -```php -class ProcessReport implements ShouldQueue -{ - public $timeout = 120; -} - -// config/queue.php — retry_after: 180 ← safely longer than any job timeout -``` - -## Use Exponential Backoff - -Use progressively longer delays between retries to avoid hammering failing services. - -Incorrect (fixed retry interval): -```php -class SyncWithStripe implements ShouldQueue -{ - public $tries = 3; - // Default: retries immediately, overwhelming the API -} -``` - -Correct (exponential backoff): -```php -class SyncWithStripe implements ShouldQueue -{ - public $tries = 3; - public $backoff = [1, 5, 10]; -} -``` - -## Implement `ShouldBeUnique` - -Prevent duplicate job processing. - -```php -class GenerateInvoice implements ShouldQueue, ShouldBeUnique -{ - public function uniqueId(): string - { - return $this->order->id; - } - - public $uniqueFor = 3600; -} -``` - -## Always Implement `failed()` - -Handle errors explicitly — don't rely on silent failure. - -```php -public function failed(?Throwable $exception): void -{ - $this->podcast->update(['status' => 'failed']); - Log::error('Processing failed', ['id' => $this->podcast->id, 'error' => $exception->getMessage()]); -} -``` - -## Rate Limit External API Calls in Jobs - -Use `RateLimited` middleware to throttle jobs calling third-party APIs. - -```php -public function middleware(): array -{ - return [new RateLimited('external-api')]; -} -``` - -## Batch Related Jobs - -Use `Bus::batch()` when jobs should succeed or fail together. - -```php -Bus::batch([ - new ImportCsvChunk($chunk1), - new ImportCsvChunk($chunk2), -]) -->then(fn (Batch $batch) => Notification::send($user, new ImportComplete)) -->catch(fn (Batch $batch, Throwable $e) => Log::error('Batch failed')) -->dispatch(); -``` - -## `retryUntil()` Needs `$tries = 0` - -When using time-based retry limits, set `$tries = 0` to avoid premature failure. - -```php -public $tries = 0; - -public function retryUntil(): \DateTimeInterface -{ - return now()->addHours(4); -} -``` - -## Use `ShouldBeUniqueUntilProcessing` for Early Lock Release - -`ShouldBeUnique` holds the lock until the job completes. `ShouldBeUniqueUntilProcessing` releases it when processing starts, allowing new instances to queue. - -```php -class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing -{ - // Lock releases when processing begins, not when it finishes -} -``` - -## Use Horizon for Complex Queue Scenarios - -Use Laravel Horizon when you need monitoring, auto-scaling, failure tracking, or multiple queues with different priorities. - -```php -// config/horizon.php -'environments' => [ - 'production' => [ - 'supervisor-1' => [ - 'connection' => 'redis', - 'queue' => ['high', 'default', 'low'], - 'balance' => 'auto', - 'minProcesses' => 1, - 'maxProcesses' => 10, - 'tries' => 3, - ], - ], -], -``` diff --git a/.agents/skills/laravel-best-practices/rules/routing.md b/.agents/skills/laravel-best-practices/rules/routing.md deleted file mode 100644 index b6e3086..0000000 --- a/.agents/skills/laravel-best-practices/rules/routing.md +++ /dev/null @@ -1,99 +0,0 @@ -# Routing & Controllers Best Practices - -## Use Implicit Route Model Binding - -Let Laravel resolve models automatically from route parameters. - -Incorrect: -```php -public function show(int $id) -{ - $post = Post::findOrFail($id); -} -``` - -Correct: -```php -public function show(Post $post) -{ - return view('posts.show', ['post' => $post]); -} -``` - -## Use Scoped Bindings for Nested Resources - -Enforce parent-child relationships automatically. - -```php -Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) { - // $post is automatically scoped to $user -})->scopeBindings(); -``` - -## Use Resource Controllers - -Use `Route::resource()` or `apiResource()` for RESTful endpoints. - -```php -Route::resource('posts', PostController::class); -// In routes/api.php — the /api prefix is applied automatically -Route::apiResource('posts', Api\PostController::class); -``` - -## Keep Controllers Thin - -Aim for under 10 lines per method. Extract business logic to action or service classes. - -Incorrect: -```php -public function store(Request $request) -{ - $validated = $request->validate([...]); - if ($request->hasFile('image')) { - $request->file('image')->move(public_path('images')); - } - $post = Post::create($validated); - $post->tags()->sync($validated['tags']); - event(new PostCreated($post)); - return redirect()->route('posts.show', $post); -} -``` - -Correct: -```php -public function store(StorePostRequest $request, CreatePostAction $create) -{ - $post = $create->execute($request->validated()); - - return redirect()->route('posts.show', $post); -} -``` - -## Type-Hint Form Requests - -Type-hinting Form Requests triggers automatic validation and authorization before the method executes. - -Incorrect: -```php -public function store(Request $request): RedirectResponse -{ - $validated = $request->validate([ - 'title' => ['required', 'max:255'], - 'body' => ['required'], - ]); - - Post::create($validated); - - return redirect()->route('posts.index'); -} -``` - -Correct: -```php -public function store(StorePostRequest $request): RedirectResponse -{ - Post::create($request->validated()); - - return redirect()->route('posts.index'); -} -``` diff --git a/.agents/skills/laravel-best-practices/rules/scheduling.md b/.agents/skills/laravel-best-practices/rules/scheduling.md deleted file mode 100644 index a984794..0000000 --- a/.agents/skills/laravel-best-practices/rules/scheduling.md +++ /dev/null @@ -1,39 +0,0 @@ -# Task Scheduling Best Practices - -## Use `withoutOverlapping()` on Variable-Duration Tasks - -Without it, a long-running task spawns a second instance on the next tick, causing double-processing or resource exhaustion. - -## Use `onOneServer()` on Multi-Server Deployments - -Without it, every server runs the same task simultaneously. Requires a shared cache driver (Redis, database, Memcached). - -## Use `runInBackground()` for Concurrent Long Tasks - -By default, tasks at the same tick run sequentially. A slow first task delays all subsequent ones. `runInBackground()` runs them as separate processes. - -## Use `environments()` to Restrict Tasks - -Prevent accidental execution of production-only tasks (billing, reporting) on staging. - -```php -Schedule::command('billing:charge')->monthly()->environments(['production']); -``` - -## Use `takeUntilTimeout()` for Time-Bounded Processing - -A task running every 15 minutes that processes an unbounded cursor can overlap with the next run. Bound execution time. - -## Use Schedule Groups for Shared Configuration - -Avoid repeating `->onOneServer()->timezone('America/New_York')` across many tasks. - -```php -Schedule::daily() - ->onOneServer() - ->timezone('America/New_York') - ->group(function () { - Schedule::command('emails:send --force'); - Schedule::command('emails:prune'); - }); -``` diff --git a/.agents/skills/laravel-best-practices/rules/security.md b/.agents/skills/laravel-best-practices/rules/security.md deleted file mode 100644 index 2d7200c..0000000 --- a/.agents/skills/laravel-best-practices/rules/security.md +++ /dev/null @@ -1,198 +0,0 @@ -# Security Best Practices - -## Mass Assignment Protection - -Every model must define `$fillable` (whitelist) or `$guarded` (blacklist). - -Incorrect: -```php -class User extends Model -{ - protected $guarded = []; // All fields are mass assignable -} -``` - -Correct: -```php -class User extends Model -{ - protected $fillable = [ - 'name', - 'email', - 'password', - ]; -} -``` - -Never use `$guarded = []` on models that accept user input. - -## Authorize Every Action - -Use policies or gates in controllers. Never skip authorization. - -Incorrect: -```php -public function update(UpdatePostRequest $request, Post $post) -{ - $post->update($request->validated()); -} -``` - -Correct: -```php -public function update(UpdatePostRequest $request, Post $post) -{ - Gate::authorize('update', $post); - - $post->update($request->validated()); -} -``` - -Or via Form Request: - -```php -public function authorize(): bool -{ - return $this->user()->can('update', $this->route('post')); -} -``` - -## Prevent SQL Injection - -Always use parameter binding. Never interpolate user input into queries. - -Incorrect: -```php -DB::select("SELECT * FROM users WHERE name = '{$request->name}'"); -``` - -Correct: -```php -User::where('name', $request->name)->get(); - -// Raw expressions with bindings -User::whereRaw('LOWER(name) = ?', [strtolower($request->name)])->get(); -``` - -## Escape Output to Prevent XSS - -Use `{{ }}` for HTML escaping. Only use `{!! !!}` for trusted, pre-sanitized content. - -Incorrect: -```blade -{!! $user->bio !!} -``` - -Correct: -```blade -{{ $user->bio }} -``` - -## CSRF Protection - -Include `@csrf` in all POST/PUT/DELETE Blade forms. In Inertia apps, the `@csrf` directive is automatically applied. - -Incorrect: -```blade - - -
-``` - -Correct: -```blade -
- @csrf - -
-``` - -## Rate Limit Auth and API Routes - -Apply `throttle` middleware to authentication and API routes. - -```php -RateLimiter::for('login', function (Request $request) { - return Limit::perMinute(5)->by($request->ip()); -}); - -Route::post('/login', LoginController::class)->middleware('throttle:login'); -``` - -## Validate File Uploads - -Validate extension, MIME type, and size. The `mimes` rule checks extensions; use `mimetypes` for actual MIME type validation. Never trust client-provided filenames. - -```php -public function rules(): array -{ - return [ - 'avatar' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'], - ]; -} -``` - -Store with generated filenames: - -```php -$path = $request->file('avatar')->store('avatars', 'public'); -``` - -## Keep Secrets Out of Code - -Never commit `.env`. Access secrets via `config()` only. - -Incorrect: -```php -$key = env('API_KEY'); -``` - -Correct: -```php -// config/services.php -'api_key' => env('API_KEY'), - -// In application code -$key = config('services.api_key'); -``` - -## Audit Dependencies - -Run `composer audit` periodically to check for known vulnerabilities in dependencies. Automate this in CI to catch issues before deployment. - -```bash -composer audit -``` - -## Encrypt Sensitive Database Fields - -Use `encrypted` cast for API keys/tokens and mark the attribute as `hidden`. - -Incorrect: -```php -class Integration extends Model -{ - protected function casts(): array - { - return [ - 'api_key' => 'string', - ]; - } -} -``` - -Correct: -```php -class Integration extends Model -{ - protected $hidden = ['api_key', 'api_secret']; - - protected function casts(): array - { - return [ - 'api_key' => 'encrypted', - 'api_secret' => 'encrypted', - ]; - } -} -``` diff --git a/.agents/skills/laravel-best-practices/rules/style.md b/.agents/skills/laravel-best-practices/rules/style.md deleted file mode 100644 index a8afb36..0000000 --- a/.agents/skills/laravel-best-practices/rules/style.md +++ /dev/null @@ -1,125 +0,0 @@ -# Conventions & Style - -## Follow Laravel Naming Conventions - -| What | Convention | Good | Bad | -|------|-----------|------|-----| -| Controller | singular | `ArticleController` | `ArticlesController` | -| Model | singular | `User` | `Users` | -| Table | plural, snake_case | `article_comments` | `articleComments` | -| Pivot table | singular alphabetical | `article_user` | `user_article` | -| Column | snake_case, no model name | `meta_title` | `article_meta_title` | -| Foreign key | singular model + `_id` | `article_id` | `articles_id` | -| Route | plural | `articles/1` | `article/1` | -| Route name | snake_case with dots | `users.show_active` | `users.show-active` | -| Method | camelCase | `getAll` | `get_all` | -| Variable | camelCase | `$articlesWithAuthor` | `$articles_with_author` | -| Collection | descriptive, plural | `$activeUsers` | `$data` | -| Object | descriptive, singular | `$activeUser` | `$users` | -| View | kebab-case | `show-filtered.blade.php` | `showFiltered.blade.php` | -| Config | snake_case | `google_calendar.php` | `googleCalendar.php` | -| Enum | singular | `UserType` | `UserTypes` | - -## Prefer Shorter Readable Syntax - -| Verbose | Shorter | -|---------|---------| -| `Session::get('cart')` | `session('cart')` | -| `$request->session()->get('cart')` | `session('cart')` | -| `$request->input('name')` | `$request->name` | -| `return Redirect::back()` | `return back()` | -| `Carbon::now()` | `now()` | -| `App::make('Class')` | `app('Class')` | -| `->where('column', '=', 1)` | `->where('column', 1)` | -| `->orderBy('created_at', 'desc')` | `->latest()` | -| `->orderBy('created_at', 'asc')` | `->oldest()` | -| `->first()->name` | `->value('name')` | - -## Use Laravel String & Array Helpers - -Laravel provides `Str`, `Arr`, `Number`, and `Uri` helper classes that are more readable, chainable, and UTF-8 safe than raw PHP functions. Always prefer them. - -Strings — use `Str` and fluent `Str::of()` over raw PHP: -```php -// Incorrect -$slug = strtolower(str_replace(' ', '-', $title)); -$short = substr($text, 0, 100) . '...'; -$class = substr(strrchr('App\Models\User', '\\'), 1); - -// Correct -$slug = Str::slug($title); -$short = Str::limit($text, 100); -$class = class_basename('App\Models\User'); -``` - -Fluent strings — chain operations for complex transformations: -```php -// Incorrect -$result = strtolower(trim(str_replace('_', '-', $input))); - -// Correct -$result = Str::of($input)->trim()->replace('_', '-')->lower(); -``` - -Key `Str` methods to prefer: `Str::slug()`, `Str::limit()`, `Str::contains()`, `Str::before()`, `Str::after()`, `Str::between()`, `Str::camel()`, `Str::snake()`, `Str::kebab()`, `Str::headline()`, `Str::squish()`, `Str::mask()`, `Str::uuid()`, `Str::ulid()`, `Str::random()`, `Str::is()`. - -Arrays — use `Arr` over raw PHP: -```php -// Incorrect -$name = isset($array['user']['name']) ? $array['user']['name'] : 'default'; - -// Correct -$name = Arr::get($array, 'user.name', 'default'); -``` - -Key `Arr` methods: `Arr::get()`, `Arr::has()`, `Arr::only()`, `Arr::except()`, `Arr::first()`, `Arr::flatten()`, `Arr::pluck()`, `Arr::where()`, `Arr::wrap()`. - -Numbers — use `Number` for display formatting: -```php -Number::format(1000000); // "1,000,000" -Number::currency(1500, 'USD'); // "$1,500.00" -Number::abbreviate(1000000); // "1M" -Number::fileSize(1024 * 1024); // "1 MB" -Number::percentage(75.5); // "75.5%" -``` - -URIs — use `Uri` for URL manipulation: -```php -$uri = Uri::of('https://example.com/search') - ->withQuery(['q' => 'laravel', 'page' => 1]); -``` - -Use `$request->string('name')` to get a fluent `Stringable` directly from request input for immediate chaining. - -Use `search-docs` for the full list of available methods — these helpers are extensive. - -## No Inline JS/CSS in Blade - -Do not put JS or CSS in Blade templates. Do not put HTML in PHP classes. - -Incorrect: -```blade -let article = `{{ json_encode($article) }}`; -``` - -Correct: -```blade - -``` - -Pass data to JS via data attributes or use a dedicated PHP-to-JS package. - -## No Unnecessary Comments - -Code should be readable on its own. Use descriptive method and variable names instead of comments. The only exception is config files, where descriptive comments are expected. - -Incorrect: -```php -// Check if there are any joins -if (count((array) $builder->getQuery()->joins) > 0) -``` - -Correct: -```php -if ($this->hasJoins()) -``` diff --git a/.agents/skills/laravel-best-practices/rules/testing.md b/.agents/skills/laravel-best-practices/rules/testing.md deleted file mode 100644 index 4fbf12f..0000000 --- a/.agents/skills/laravel-best-practices/rules/testing.md +++ /dev/null @@ -1,43 +0,0 @@ -# Testing Best Practices - -## Use `LazilyRefreshDatabase` Over `RefreshDatabase` - -`RefreshDatabase` migrates once per process and wraps each test in a rolled-back transaction. `LazilyRefreshDatabase` skips even that first migration if the schema is already up to date. - -## Use Model Assertions Over Raw Database Assertions - -Incorrect: `$this->assertDatabaseHas('users', ['id' => $user->id]);` - -Correct: `$this->assertModelExists($user);` - -More expressive, type-safe, and fails with clearer messages. - -## Use Factory States and Sequences - -Named states make tests self-documenting. Sequences eliminate repetitive setup. - -Incorrect: `User::factory()->create(['email_verified_at' => null]);` - -Correct: `User::factory()->unverified()->create();` - -## Use `Exceptions::fake()` to Assert Exception Reporting - -Instead of `withoutExceptionHandling()`, use `Exceptions::fake()` to assert the correct exception was reported while the request completes normally. - -## Call `Event::fake()` After Factory Setup - -Model factories rely on model events (e.g., `creating` to generate UUIDs). Calling `Event::fake()` before factory calls silences those events, producing broken models. - -Incorrect: `Event::fake(); $user = User::factory()->create();` - -Correct: `$user = User::factory()->create(); Event::fake();` - -## Use `recycle()` to Share Relationship Instances Across Factories - -Without `recycle()`, nested factories create separate instances of the same conceptual entity. - -```php -Ticket::factory() - ->recycle(Airline::factory()->create()) - ->create(); -``` diff --git a/.agents/skills/laravel-best-practices/rules/validation.md b/.agents/skills/laravel-best-practices/rules/validation.md deleted file mode 100644 index 5fde106..0000000 --- a/.agents/skills/laravel-best-practices/rules/validation.md +++ /dev/null @@ -1,75 +0,0 @@ -# Validation & Forms Best Practices - -## Use Form Request Classes - -Extract validation from controllers into dedicated Form Request classes. - -Incorrect: -```php -public function store(Request $request) -{ - $request->validate([ - 'title' => 'required|max:255', - 'body' => 'required', - ]); -} -``` - -Correct: -```php -public function store(StorePostRequest $request) -{ - Post::create($request->validated()); -} -``` - -## Array vs. String Notation for Rules - -Array syntax is more readable and composes cleanly with `Rule::` objects. Prefer it in new code, but check existing Form Requests first and match whatever notation the project already uses. - -```php -// Preferred for new code -'email' => ['required', 'email', Rule::unique('users')], - -// Follow existing convention if the project uses string notation -'email' => 'required|email|unique:users', -``` - -## Always Use `validated()` - -Get only validated data. Never use `$request->all()` for mass operations. - -Incorrect: -```php -Post::create($request->all()); -``` - -Correct: -```php -Post::create($request->validated()); -``` - -## Use `Rule::when()` for Conditional Validation - -```php -'company_name' => [ - Rule::when($this->account_type === 'business', ['required', 'string', 'max:255']), -], -``` - -## Use the `after()` Method for Custom Validation - -Use `after()` instead of `withValidator()` for custom validation logic that depends on multiple fields. - -```php -public function after(): array -{ - return [ - function (Validator $validator) { - if ($this->quantity > Product::find($this->product_id)?->stock) { - $validator->errors()->add('quantity', 'Not enough stock.'); - } - }, - ]; -} -``` diff --git a/.agents/skills/pest-testing/SKILL.md b/.agents/skills/pest-testing/SKILL.md deleted file mode 100644 index ab27161..0000000 --- a/.agents/skills/pest-testing/SKILL.md +++ /dev/null @@ -1,166 +0,0 @@ ---- -name: pest-testing -description: "Use this skill for Pest PHP testing in Laravel projects only. Trigger whenever any test is being written, edited, fixed, or refactored — including fixing tests that broke after a code change, adding assertions, converting PHPUnit to Pest, adding datasets, and TDD workflows. Always activate when the user asks how to write something in Pest, mentions test files or directories (tests/Feature, tests/Unit, tests/Browser), or needs browser testing, smoke testing multiple pages for JS errors, or architecture tests. Covers: test()/it()/expect() syntax, datasets, mocking, browser testing (visit/click/fill), smoke testing, arch(), Livewire component tests, RefreshDatabase, and all Pest 4 features. Do not use for factories, seeders, migrations, controllers, models, or non-test PHP code." -license: MIT -metadata: - author: laravel ---- - -# Pest Testing 4 - -## Documentation - -Use `search-docs` for detailed Pest 4 patterns and documentation. - -## Basic Usage - -### Creating Tests - -All tests must be written using Pest. Use `php artisan make:test --pest {name}`. - -The `{name}` argument should include only the path and test name, but should not include the test suite. -- Incorrect: `php artisan make:test --pest Feature/SomeFeatureTest` will generate `tests/Feature/Feature/SomeFeatureTest.php` -- Correct: `php artisan make:test --pest SomeControllerTest` will generate `tests/Feature/SomeControllerTest.php` -- Incorrect: `php artisan make:test --pest --unit Unit/SomeServiceTest` will generate `tests/Unit/Unit/SomeServiceTest.php` -- Correct: `php artisan make:test --pest --unit SomeServiceTest` will generate `tests/Unit/SomeServiceTest.php` - -### Test Organization - -- Unit/Feature tests: `tests/Feature` and `tests/Unit` directories. -- Browser tests: `tests/Browser/` directory. -- Do NOT remove tests without approval - these are core application code. - -### Basic Test Structure - -Pest supports both `test()` and `it()` functions. Before writing new tests, check existing test files in the same directory to match the project's convention. Use `test()` if existing tests use `test()`, or `it()` if they use `it()`. - - -```php -it('is true', function () { - expect(true)->toBeTrue(); -}); -``` - -### Running Tests - -- Run minimal tests with filter before finalizing: `php artisan test --compact --filter=testName`. -- Run all tests: `php artisan test --compact`. -- Run file: `php artisan test --compact tests/Feature/ExampleTest.php`. - -## Assertions - -Use specific assertions (`assertSuccessful()`, `assertNotFound()`) instead of `assertStatus()`: - - -```php -it('returns all', function () { - $this->postJson('/api/docs', [])->assertSuccessful(); -}); -``` - -| Use | Instead of | -|-----|------------| -| `assertSuccessful()` | `assertStatus(200)` | -| `assertNotFound()` | `assertStatus(404)` | -| `assertForbidden()` | `assertStatus(403)` | - -## Mocking - -Import mock function before use: `use function Pest\Laravel\mock;` - -## Datasets - -Use datasets for repetitive tests (validation rules, etc.): - - -```php -it('has emails', function (string $email) { - expect($email)->not->toBeEmpty(); -})->with([ - 'james' => 'james@laravel.com', - 'taylor' => 'taylor@laravel.com', -]); -``` - -## Pest 4 Features - -| Feature | Purpose | -|---------|---------| -| Browser Testing | Full integration tests in real browsers | -| Smoke Testing | Validate multiple pages quickly | -| Visual Regression | Compare screenshots for visual changes | -| Test Sharding | Parallel CI runs | -| Architecture Testing | Enforce code conventions | - -### Browser Test Example - -Browser tests run in real browsers for full integration testing: - -- Browser tests live in `tests/Browser/`. -- Use Laravel features like `Event::fake()`, `assertAuthenticated()`, and model factories. -- Use `RefreshDatabase` for clean state per test. -- Interact with page: click, type, scroll, select, submit, drag-and-drop, touch gestures. -- Test on multiple browsers (Chrome, Firefox, Safari) if requested. -- Test on different devices/viewports (iPhone 14 Pro, tablets) if requested. -- Switch color schemes (light/dark mode) when appropriate. -- Take screenshots or pause tests for debugging. - - -```php -it('may reset the password', function () { - Notification::fake(); - - $this->actingAs(User::factory()->create()); - - $page = visit('/sign-in'); - - $page->assertSee('Sign In') - ->assertNoJavaScriptErrors() - ->click('Forgot Password?') - ->fill('email', 'nuno@laravel.com') - ->click('Send Reset Link') - ->assertSee('We have emailed your password reset link!'); - - Notification::assertSent(ResetPassword::class); -}); -``` - -### Smoke Testing - -Quickly validate multiple pages have no JavaScript errors: - - -```php -$pages = visit(['/', '/about', '/contact']); - -$pages->assertNoJavaScriptErrors()->assertNoConsoleLogs(); -``` - -### Visual Regression Testing - -Capture and compare screenshots to detect visual changes. - -### Test Sharding - -Split tests across parallel processes for faster CI runs. - -### Architecture Testing - -Pest 4 includes architecture testing (from Pest 3): - - -```php -arch('controllers') - ->expect('App\Http\Controllers') - ->toExtendNothing() - ->toHaveSuffix('Controller'); -``` - -## Common Pitfalls - -- Not importing `use function Pest\Laravel\mock;` before using mock -- Using `assertStatus(200)` instead of `assertSuccessful()` -- Forgetting datasets for repetitive validation tests -- Deleting tests without approval -- Forgetting `assertNoJavaScriptErrors()` in browser tests -- Prefixing `Feature/` or `Unit/` in `{name}` when using `make:test` diff --git a/.agents/skills/tailwindcss-development/SKILL.md b/.agents/skills/tailwindcss-development/SKILL.md deleted file mode 100644 index c0cb2fb..0000000 --- a/.agents/skills/tailwindcss-development/SKILL.md +++ /dev/null @@ -1,119 +0,0 @@ ---- -name: tailwindcss-development -description: "Always invoke when the user's message includes 'tailwind' in any form. Also invoke for: building responsive grid layouts (multi-column card grids, product grids), flex/grid page structures (dashboards with sidebars, fixed topbars, mobile-toggle navs), styling UI components (cards, tables, navbars, pricing sections, forms, inputs, badges), adding dark mode variants, fixing spacing or typography, and Tailwind v3/v4 work. The core use case: writing or fixing Tailwind utility classes in HTML templates (Blade, JSX, Vue). Skip for backend PHP logic, database queries, API routes, JavaScript with no HTML/CSS component, CSS file audits, build tool configuration, and vanilla CSS." -license: MIT -metadata: - author: laravel ---- - -# Tailwind CSS Development - -## Documentation - -Use `search-docs` for detailed Tailwind CSS v4 patterns and documentation. - -## Basic Usage - -- Use Tailwind CSS classes to style HTML. Check and follow existing Tailwind conventions in the project before introducing new patterns. -- Offer to extract repeated patterns into components that match the project's conventions (e.g., Blade, JSX, Vue). -- Consider class placement, order, priority, and defaults. Remove redundant classes, add classes to parent or child elements carefully to reduce repetition, and group elements logically. - -## Tailwind CSS v4 Specifics - -- Always use Tailwind CSS v4 and avoid deprecated utilities. -- `corePlugins` is not supported in Tailwind v4. - -### CSS-First Configuration - -In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed: - - -```css -@theme { - --color-brand: oklch(0.72 0.11 178); -} -``` - -### Import Syntax - -In Tailwind v4, import Tailwind with a regular CSS `@import` statement instead of the `@tailwind` directives used in v3: - - -```diff -- @tailwind base; -- @tailwind components; -- @tailwind utilities; -+ @import "tailwindcss"; -``` - -### Replaced Utilities - -Tailwind v4 removed deprecated utilities. Use the replacements shown below. Opacity values remain numeric. - -| Deprecated | Replacement | -|------------|-------------| -| bg-opacity-* | bg-black/* | -| text-opacity-* | text-black/* | -| border-opacity-* | border-black/* | -| divide-opacity-* | divide-black/* | -| ring-opacity-* | ring-black/* | -| placeholder-opacity-* | placeholder-black/* | -| flex-shrink-* | shrink-* | -| flex-grow-* | grow-* | -| overflow-ellipsis | text-ellipsis | -| decoration-slice | box-decoration-slice | -| decoration-clone | box-decoration-clone | - -## Spacing - -Use `gap` utilities instead of margins for spacing between siblings: - - -```html -
-
Item 1
-
Item 2
-
-``` - -## Dark Mode - -If existing pages and components support dark mode, new pages and components must support it the same way, typically using the `dark:` variant: - - -```html -
- Content adapts to color scheme -
-``` - -## Common Patterns - -### Flexbox Layout - - -```html -
-
Left content
-
Right content
-
-``` - -### Grid Layout - - -```html -
-
Card 1
-
Card 2
-
Card 3
-
-``` - -## Common Pitfalls - -- Using deprecated v3 utilities (bg-opacity-*, flex-shrink-*, etc.) -- Using `@tailwind` directives instead of `@import "tailwindcss"` -- Trying to use `tailwind.config.js` instead of CSS `@theme` directive -- Using margins for spacing between siblings instead of gap utilities -- Forgetting to add dark mode variants when the project uses dark mode diff --git a/.agents/skills/wayfinder-development/SKILL.md b/.agents/skills/wayfinder-development/SKILL.md deleted file mode 100644 index 8537dc0..0000000 --- a/.agents/skills/wayfinder-development/SKILL.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -name: wayfinder-development -description: "Use this skill for Laravel Wayfinder which auto-generates typed functions for Laravel controllers and routes. ALWAYS use this skill when frontend code needs to call backend routes or controller actions. Trigger when: connecting any React/Vue/Svelte/Inertia frontend to Laravel controllers, routes, building end-to-end features with both frontend and backend, wiring up forms or links to backend endpoints, fixing route-related TypeScript errors, importing from @/actions or @/routes, or running wayfinder:generate. Use Wayfinder route functions instead of hardcoded URLs. Covers: wayfinder() vite plugin, .url()/.get()/.post()/.form(), query params, route model binding, tree-shaking. Do not use for backend-only task" -license: MIT -metadata: - author: laravel ---- - -# Wayfinder Development - -## Documentation - -Use `search-docs` for detailed Wayfinder patterns and documentation. - -## Quick Reference - -### Generate Routes - -Run after route changes if Vite plugin isn't installed: -```bash -php artisan wayfinder:generate --no-interaction -``` -For form helpers, use `--with-form` flag: -```bash -php artisan wayfinder:generate --with-form --no-interaction -``` - -### Import Patterns - - -```typescript -// Named imports for tree-shaking (preferred)... -import { show, store, update } from '@/actions/App/Http/Controllers/PostController' - -// Named route imports... -import { show as postShow } from '@/routes/post' -``` - -### Common Methods - - -```typescript -// Get route object... -show(1) // { url: "/posts/1", method: "get" } - -// Get URL string... -show.url(1) // "/posts/1" - -// Specific HTTP methods... -show.get(1) -store.post() -update.patch(1) -destroy.delete(1) - -// Form attributes for HTML forms... -store.form() // { action: "/posts", method: "post" } - -// Query parameters... -show(1, { query: { page: 1 } }) // "/posts/1?page=1" -``` - -## Wayfinder + Inertia - -Use Wayfinder with the `
` component: - -```typescript -
-``` - -## Verification - -1. Run `php artisan wayfinder:generate` to regenerate routes if Vite plugin isn't installed -2. Check TypeScript imports resolve correctly -3. Verify route URLs match expected paths - -## Common Pitfalls - -- Using default imports instead of named imports (breaks tree-shaking) -- Forgetting to regenerate after route changes -- Not using type-safe parameter objects for route model binding diff --git a/.claude/skills/inertia-react-development/SKILL.md b/.claude/skills/inertia-react-development/SKILL.md deleted file mode 100644 index 813e62f..0000000 --- a/.claude/skills/inertia-react-development/SKILL.md +++ /dev/null @@ -1,524 +0,0 @@ ---- -name: inertia-react-development -description: "Develops Inertia.js v3 React client-side applications. Activates when creating React pages, forms, or navigation; using ,
, useForm, useHttp, setLayoutProps, or router; working with deferred props, prefetching, optimistic updates, instant visits, or polling; or when user mentions React with Inertia, React pages, React forms, or React navigation." -license: MIT -metadata: - author: laravel ---- - -# Inertia React Development - -## When to Apply - -Activate this skill when: - -- Creating or modifying React page components for Inertia -- Working with forms in React (using ``, `useForm`, or `useHttp`) -- Implementing client-side navigation with `` or `router` -- Using v3 features: deferred props, prefetching, optimistic updates, instant visits, layout props, HTTP requests, WhenVisible, InfiniteScroll, once props, flash data, or polling -- Building React-specific features with the Inertia protocol - -## Documentation - -Use `search-docs` for detailed Inertia v3 React patterns and documentation. - -## Basic Usage - -### Page Components Location - -React page components should be placed in the `resources/js/pages` directory. - -### Page Component Structure - - -```react -export default function UsersIndex({ users }) { - return ( -
-

Users

-
    - {users.map(user =>
  • {user.name}
  • )} -
-
- ) -} -``` - -## Client-Side Navigation - -### Basic Link Component - -Use `` for client-side navigation instead of traditional `
` tags: - - -```react -import { Link, router } from '@inertiajs/react' - -Home -Users -View User -``` - -### Link with Method - - -```react -import { Link } from '@inertiajs/react' - - - Logout - -``` - -### Prefetching - -Prefetch pages to improve perceived performance: - - -```react -import { Link } from '@inertiajs/react' - - - Users - -``` - -### Programmatic Navigation - - -```react -import { router } from '@inertiajs/react' - -function handleClick() { - router.visit('/users') -} - -// Or with options -router.visit('/users', { - method: 'post', - data: { name: 'John' }, - onSuccess: () => console.log('Success!'), -}) -``` - -## Form Handling - -### Form Component (Recommended) - -The recommended way to build forms is with the `` component: - - -```react -import { Form } from '@inertiajs/react' - -export default function CreateUser() { - return ( - - {({ errors, processing, wasSuccessful }) => ( - <> - - {errors.name &&
{errors.name}
} - - - {errors.email &&
{errors.email}
} - - - - {wasSuccessful &&
User created!
} - - )} - - ) -} -``` - -### Form Component With All Props - - -```react -import { Form } from '@inertiajs/react' - -
- {({ - errors, - hasErrors, - processing, - progress, - wasSuccessful, - recentlySuccessful, - clearErrors, - resetAndClearErrors, - defaults, - isDirty, - reset, - submit - }) => ( - <> - - {errors.name &&
{errors.name}
} - - - - {progress && ( - - {progress.percentage}% - - )} - - {wasSuccessful &&
Saved!
} - - )} -
-``` - -### Form Component Reset Props - -The `
` component supports automatic resetting: - -- `resetOnError` - Reset form data when the request fails -- `resetOnSuccess` - Reset form data when the request succeeds -- `setDefaultsOnSuccess` - Update default values on success - -Use the `search-docs` tool with a query of `form component resetting` for detailed guidance. - - -```react -import { Form } from '@inertiajs/react' - - - {({ errors, processing, wasSuccessful }) => ( - <> - - {errors.name &&
{errors.name}
} - - - - )} -
-``` - -Forms can also be built using the `useForm` helper for more programmatic control. Use the `search-docs` tool with a query of `useForm helper` for guidance. - -### `useForm` Hook - -For more programmatic control or to follow existing conventions, use the `useForm` hook: - - -```react -import { useForm } from '@inertiajs/react' - -export default function CreateUser() { - const { data, setData, post, processing, errors, reset } = useForm({ - name: '', - email: '', - password: '', - }) - - function submit(e) { - e.preventDefault() - post('/users', { - onSuccess: () => reset('password'), - }) - } - - return ( -
- setData('name', e.target.value)} - /> - {errors.name &&
{errors.name}
} - - setData('email', e.target.value)} - /> - {errors.email &&
{errors.email}
} - - setData('password', e.target.value)} - /> - {errors.password &&
{errors.password}
} - - -
- ) -} -``` - -## Inertia v3 Features - -### HTTP Requests - -Use the `useHttp` hook for standalone HTTP requests that do not trigger Inertia page visits. It provides the same developer experience as `useForm`, but for plain JSON endpoints. - - -```react -import { useHttp } from '@inertiajs/react' - -export default function Search() { - const { data, setData, get, processing } = useHttp({ - query: '', - }) - - function search(e) { - setData('query', e.target.value) - get('/api/search', { - onSuccess: (response) => { - console.log(response) - }, - }) - } - - return ( - <> - - {processing &&
Searching...
} - - ) -} -``` - -### Optimistic Updates - -Apply data changes instantly before the server responds, with automatic rollback on failure: - - -```react -import { router } from '@inertiajs/react' - -function like(post) { - router.optimistic((props) => ({ - post: { - ...props.post, - likes: props.post.likes + 1, - }, - })).post(`/posts/${post.id}/like`) -} -``` - -Optimistic updates also work with `useForm` and the `
` component: - - -```react -import { Form } from '@inertiajs/react' - - ({ - todos: [...props.todos, { id: Date.now(), name: data.name, done: false }], - })} -> - - -
-``` - -### Instant Visits - -Navigate to a new page immediately without waiting for the server response. The target component renders right away with shared props, while page-specific props load in the background. - - -```react -import { Link } from '@inertiajs/react' - -Dashboard - - - View Post - -``` - -### Layout Props - -Share dynamic data between pages and persistent layouts: - - -```react -export default function Layout({ title = 'My App', showSidebar = true, children }) { - return ( - <> -
{title}
- {showSidebar && } -
{children}
- - ) -} -``` - - -```react -import { setLayoutProps } from '@inertiajs/react' - -export default function Dashboard() { - setLayoutProps({ - title: 'Dashboard', - showSidebar: false, - }) - - return

Dashboard

-} -``` - -### Deferred Props - -Use deferred props to load data after initial page render: - - -```react -export default function UsersIndex({ users }) { - return ( -
-

Users

- {!users ? ( -
-
-
-
- ) : ( -
    - {users.map(user => ( -
  • {user.name}
  • - ))} -
- )} -
- ) -} -``` - -### Polling - -Use the `usePoll` hook to automatically refresh data at intervals. It handles cleanup on unmount and throttles polling when the tab is inactive. - - -```react -import { usePoll } from '@inertiajs/react' - -export default function Dashboard({ stats }) { - usePoll(5000) - - return ( -
-

Dashboard

-
Active Users: {stats.activeUsers}
-
- ) -} -``` - - -```react -import { usePoll } from '@inertiajs/react' - -export default function Dashboard({ stats }) { - const { start, stop } = usePoll(5000, { - only: ['stats'], - onStart() { - console.log('Polling request started') - }, - onFinish() { - console.log('Polling request finished') - }, - }, { - autoStart: false, - keepAlive: true, - }) - - return ( -
-

Dashboard

-
Active Users: {stats.activeUsers}
- - -
- ) -} -``` - -- `autoStart` (default `true`) - set to `false` to start polling manually via the returned `start()` function -- `keepAlive` (default `false`) - set to `true` to prevent throttling when the browser tab is inactive - -### WhenVisible - -Lazy-load a prop when an element scrolls into view. Useful for deferring expensive data that sits below the fold: - - -```react -import { WhenVisible } from '@inertiajs/react' - -export default function Dashboard({ stats }) { - return ( -
-

Dashboard

- - Loading stats...
}> - {({ fetching }) => ( -
-

Total Users: {stats.total_users}

-

Revenue: {stats.revenue}

- {fetching && Refreshing...} -
- )} - - - ) -} -``` - -### InfiniteScroll - -Automatically load additional pages of paginated data as users scroll: - - -```react -import { InfiniteScroll } from '@inertiajs/react' - -export default function Users({ users }) { - return ( - - {users.data.map(user => ( -
{user.name}
- ))} -
- ) -} -``` - -The server must use `Inertia::scroll()` to configure the paginated data. Use the `search-docs` tool with a query of `infinite scroll` for detailed guidance on buffers, manual loading, reverse mode, and custom trigger elements. - -## Server-Side Patterns - -Server-side patterns (Inertia::render, props, middleware) are covered in inertia-laravel guidelines. - -## Common Pitfalls - -- Using traditional `
` links instead of Inertia's `` component (breaks SPA behavior) -- Forgetting to add loading states (skeleton screens) when using deferred props -- Not handling the `undefined` state of deferred props before data loads -- Using `
` without preventing default submission (use `` component or `e.preventDefault()`) -- Forgetting to check if `` component is available in your Inertia version -- Using `router.cancel()` instead of `router.cancelAll()` (v3 breaking change) -- Using `router.on('invalid', ...)` or `router.on('exception', ...)` instead of the renamed `httpException` and `networkError` events diff --git a/.claude/skills/laravel-best-practices/SKILL.md b/.claude/skills/laravel-best-practices/SKILL.md deleted file mode 100644 index d136d75..0000000 --- a/.claude/skills/laravel-best-practices/SKILL.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -name: laravel-best-practices -description: "Apply this skill whenever writing, reviewing, or refactoring Laravel PHP code. This includes creating or modifying controllers, models, migrations, form requests, policies, jobs, scheduled commands, service classes, and Eloquent queries. Triggers for N+1 and query performance issues, caching strategies, authorization and security patterns, validation, error handling, queue and job configuration, route definitions, and architectural decisions. Also use for Laravel code reviews and refactoring existing Laravel code to follow best practices. Covers any task involving Laravel backend PHP code patterns." -license: MIT -metadata: - author: laravel ---- - -# Laravel Best Practices - -Best practices for Laravel, organized as an index of rule files. Each rule file teaches what to do and why. For exact API syntax, verify with `search-docs`. - -## Consistency First - -Before applying any rule, check what the application already does. Laravel offers multiple valid approaches, and the best choice is the one the codebase already uses, even if another pattern would be theoretically better. Inconsistency is worse than a suboptimal pattern. - -Check sibling files, related controllers, models, or tests for established patterns. If one exists, follow it. Don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides. - -## How to Apply - -1. Check the changed files, nearby code, project configuration, and relevant tests for established patterns. Deviate only for a correctness or security defect, and call the deviation out. -2. Map every affected concern to the rule index below. Read each mapped rule file before editing. Skip unrelated rule files. -3. Make the smallest coherent change. Keep the application's architecture and naming instead of introducing a second pattern for the same job. -4. Verify version-sensitive Laravel APIs for the installed version with `search-docs`, or inspect the installed framework when it is unavailable. -5. Run the narrowest relevant tests first, then the project's formatting and static-analysis checks when the change warrants them. -6. Re-read the diff against every mapped rule before finishing. - -## Rule Index - -Cross-cutting changes often need more than one rule file. - -| Concern | Read | -| --- | --- | -| Query count, eager loading, indexes, large datasets | [`rules/db-performance.md`](rules/db-performance.md) | -| Subqueries, aggregates, complex ordering and query plans | [`rules/advanced-queries.md`](rules/advanced-queries.md) | -| Models, relationships, scopes, casts | [`rules/eloquent.md`](rules/eloquent.md) | -| Authentication, authorization, input safety, secrets, uploads | [`rules/security.md`](rules/security.md) | -| Form Requests and validation rules | [`rules/validation.md`](rules/validation.md) | -| Controllers, route binding, resources, middleware | [`rules/routing.md`](rules/routing.md) | -| Schema changes, columns, foreign keys, indexes | [`rules/migrations.md`](rules/migrations.md) | -| Jobs, retries, uniqueness, batches, Horizon | [`rules/queue-jobs.md`](rules/queue-jobs.md) | -| Cache lifetime, invalidation, locks, memoization | [`rules/caching.md`](rules/caching.md) | -| Outbound requests, retries, timeouts, fakes | [`rules/http-client.md`](rules/http-client.md) | -| Exceptions, reporting, rendering, log context | [`rules/error-handling.md`](rules/error-handling.md) | -| Events and notifications | [`rules/events-notifications.md`](rules/events-notifications.md) | -| Mailables and mail assertions | [`rules/mail.md`](rules/mail.md) | -| Scheduled tasks and overlap protection | [`rules/scheduling.md`](rules/scheduling.md) | -| Collections, lazy iteration, bulk operations | [`rules/collections.md`](rules/collections.md) | -| Blade components, attributes, composers | [`rules/blade-views.md`](rules/blade-views.md) | -| Environment values and application configuration | [`rules/config.md`](rules/config.md) | -| Pest/PHPUnit patterns, factories, fakes | [`rules/testing.md`](rules/testing.md) | -| Naming, helpers, file boundaries, PHP style | [`rules/style.md`](rules/style.md) | -| Actions, services, dependencies, application structure | [`rules/architecture.md`](rules/architecture.md) | - -## Decision Rules - -- Prefer framework features and existing application abstractions over new helpers or dependencies. -- Avoid speculative abstractions. Extract code when it creates a clear domain boundary, removes meaningful duplication, or makes behavior independently testable. -- Keep database access out of Blade views and prevent hidden N+1 queries across controllers, resources, jobs, and serialization. diff --git a/.claude/skills/laravel-best-practices/rules/advanced-queries.md b/.claude/skills/laravel-best-practices/rules/advanced-queries.md deleted file mode 100644 index f12876e..0000000 --- a/.claude/skills/laravel-best-practices/rules/advanced-queries.md +++ /dev/null @@ -1,106 +0,0 @@ -# Advanced Query Patterns - -## Use `addSelect()` Subqueries for Single Values from Has-Many - -Instead of eager-loading an entire has-many relationship for a single value (like the latest timestamp), use a correlated subquery via `addSelect()`. This pulls the value directly in the main SQL query — zero extra queries. - -```php -public function scopeWithLastLoginAt($query): void -{ - $query->addSelect([ - 'last_login_at' => Login::select('created_at') - ->whereColumn('user_id', 'users.id') - ->latest() - ->take(1), - ])->withCasts(['last_login_at' => 'datetime']); -} -``` - -## Create Dynamic Relationships via Subquery FK - -Extend the `addSelect()` pattern to fetch a foreign key via subquery, then define a `belongsTo` relationship on that virtual attribute. This provides a fully-hydrated related model without loading the entire collection. - -```php -public function lastLogin(): BelongsTo -{ - return $this->belongsTo(Login::class); -} - -public function scopeWithLastLogin($query): void -{ - $query->addSelect([ - 'last_login_id' => Login::select('id') - ->whereColumn('user_id', 'users.id') - ->latest() - ->take(1), - ])->with('lastLogin'); -} -``` - -## Use Conditional Aggregates Instead of Multiple Count Queries - -Replace N separate `count()` queries with a single query using `CASE WHEN` inside `selectRaw()`. Use `toBase()` to skip model hydration when you only need scalar values. - -```php -$statuses = Feature::toBase() - ->selectRaw("count(case when status = 'Requested' then 1 end) as requested") - ->selectRaw("count(case when status = 'Planned' then 1 end) as planned") - ->selectRaw("count(case when status = 'Completed' then 1 end) as completed") - ->first(); -``` - -## Use `setRelation()` to Prevent Circular N+1 - -When a parent model is eager-loaded with its children, and the view also needs `$child->parent`, use `setRelation()` to inject the already-loaded parent rather than letting Eloquent fire N additional queries. - -```php -$feature->load('comments.user'); -$feature->comments->each->setRelation('feature', $feature); -``` - -## Prefer `whereIn` + Subquery Over `whereHas` - -`whereHas()` emits a correlated `EXISTS` subquery that re-executes per row. Using `whereIn()` with a `select('id')` subquery lets the database use an index lookup instead, without loading data into PHP memory. - -Incorrect (correlated EXISTS re-executes per row): - -```php -$query->whereHas('company', fn ($q) => $q->where('name', 'like', $term)); -``` - -Correct (index-friendly subquery, no PHP memory overhead): - -```php -$query->whereIn('company_id', Company::where('name', 'like', $term)->select('id')); -``` - -## Sometimes Two Simple Queries Beat One Complex Query - -Running a small, targeted secondary query and passing its results via `whereIn` is often faster than a single complex correlated subquery or join. The additional round-trip is worthwhile when the secondary query is highly selective and uses its own index. - -## Use Compound Indexes Matching `orderBy` Column Order - -When ordering by multiple columns, create a single compound index in the same column order as the `ORDER BY` clause. Individual single-column indexes cannot combine for multi-column sorts — the database will filesort without a compound index. - -```php -// Migration -$table->index(['last_name', 'first_name']); - -// Query — column order must match the index -User::query()->orderBy('last_name')->orderBy('first_name')->paginate(); -``` - -## Use Correlated Subqueries for Has-Many Ordering - -When sorting by a value from a has-many relationship, avoid joins (they duplicate rows). Use a correlated subquery inside `orderBy()` instead, paired with an `addSelect` scope for eager loading. - -```php -public function scopeOrderByLastLogin($query): void -{ - $query->orderByDesc(Login::select('created_at') - ->whereColumn('user_id', 'users.id') - ->latest() - ->take(1) - ); -} -``` diff --git a/.claude/skills/laravel-best-practices/rules/architecture.md b/.claude/skills/laravel-best-practices/rules/architecture.md deleted file mode 100644 index 138d5a4..0000000 --- a/.claude/skills/laravel-best-practices/rules/architecture.md +++ /dev/null @@ -1,202 +0,0 @@ -# Architecture Best Practices - -## Single-Purpose Action Classes - -Extract discrete business operations into invokable Action classes. - -```php -class CreateOrderAction -{ - public function __construct(private InventoryService $inventory) {} - - public function handle(array $data): Order - { - $order = Order::create($data); - $this->inventory->reserve($order); - - return $order; - } -} -``` - -## Use Dependency Injection - -Always use constructor injection. Avoid `app()` or `resolve()` inside classes. - -Incorrect: -```php -class OrderController extends Controller -{ - public function store(StoreOrderRequest $request) - { - $service = app(OrderService::class); - - return $service->create($request->validated()); - } -} -``` - -Correct: -```php -class OrderController extends Controller -{ - public function __construct(private OrderService $service) {} - - public function store(StoreOrderRequest $request) - { - return $this->service->create($request->validated()); - } -} -``` - -## Code to Interfaces - -Depend on contracts at system boundaries (payment gateways, notification channels, external APIs) for testability and swappability. - -Incorrect (concrete dependency): -```php -class OrderService -{ - public function __construct(private StripeGateway $gateway) {} -} -``` - -Correct (interface dependency): -```php -interface PaymentGateway -{ - public function charge(int $amount, string $customerId): PaymentResult; -} - -class OrderService -{ - public function __construct(private PaymentGateway $gateway) {} -} -``` - -Bind in a service provider: - -```php -$this->app->bind(PaymentGateway::class, StripeGateway::class); -``` - -## Default Sort by Descending - -When no explicit order is specified, sort by `id` or `created_at` descending. Without an explicit `ORDER BY`, row order is undefined. - -Incorrect: -```php -$posts = Post::paginate(); -``` - -Correct: -```php -$posts = Post::latest()->paginate(); -``` - -## Use Atomic Locks for Race Conditions - -Prevent race conditions with `Cache::lock()` or `lockForUpdate()`. - -```php -Cache::lock('order-processing-'.$order->id, 10)->block(5, function () use ($order) { - $order->process(); -}); - -// Or at query level -$product = Product::where('id', $id)->lockForUpdate()->first(); -``` - -## Use `mb_*` String Functions - -When no Laravel helper exists, prefer `mb_strlen`, `mb_strtolower`, etc. for UTF-8 safety. Standard PHP string functions count bytes, not characters. - -Incorrect: -```php -strlen('José'); // 5 (bytes, not characters) -strtolower('MÜNCHEN'); // 'mÜnchen' — fails on multibyte -``` - -Correct: -```php -mb_strlen('José'); // 4 (characters) -mb_strtolower('MÜNCHEN'); // 'münchen' - -// Prefer Laravel's Str helpers when available -Str::length('José'); // 4 -Str::lower('MÜNCHEN'); // 'münchen' -``` - -## Use `defer()` for Post-Response Work - -For lightweight tasks that don't need to survive a crash (logging, analytics, cleanup), use `defer()` instead of dispatching a job. The callback runs after the HTTP response is sent — no queue overhead. - -Incorrect (job overhead for trivial work): -```php -dispatch(new LogPageView($page)); -``` - -Correct (runs after response, same process): -```php -defer(fn () => PageView::create(['page_id' => $page->id, 'user_id' => auth()->id()])); -``` - -Use jobs when the work must survive process crashes or needs retry logic. Use `defer()` for fire-and-forget work. - -## Use `Context` for Request-Scoped Data - -The `Context` facade passes data through the entire request lifecycle — middleware, controllers, jobs, logs — without passing arguments manually. - -```php -// In middleware -Context::add('tenant_id', $request->header('X-Tenant-ID')); - -// Anywhere later — controllers, jobs, log context -$tenantId = Context::get('tenant_id'); -``` - -Context data automatically propagates to queued jobs and is included in log entries. Use `Context::addHidden()` for sensitive data that should be available in queued jobs but excluded from log context. If data must not leave the current process, do not store it in `Context`. - -## Use `Concurrency::run()` for Parallel Execution - -Run independent operations in parallel using child processes — no async libraries needed. - -```php -use Illuminate\Support\Facades\Concurrency; - -[$users, $orders] = Concurrency::run([ - fn () => User::count(), - fn () => Order::where('status', 'pending')->count(), -]); -``` - -Each closure runs in a separate process with full Laravel access. Use for independent database queries, API calls, or computations that would otherwise run sequentially. - -## Convention Over Configuration - -Follow Laravel conventions. Don't override defaults unnecessarily. - -Incorrect: -```php -class Customer extends Model -{ - protected $table = 'Customer'; - protected $primaryKey = 'customer_id'; - - public function roles(): BelongsToMany - { - return $this->belongsToMany(Role::class, 'role_customer', 'customer_id', 'role_id'); - } -} -``` - -Correct: -```php -class Customer extends Model -{ - public function roles(): BelongsToMany - { - return $this->belongsToMany(Role::class); - } -} -``` diff --git a/.claude/skills/laravel-best-practices/rules/blade-views.md b/.claude/skills/laravel-best-practices/rules/blade-views.md deleted file mode 100644 index 5f0b3a1..0000000 --- a/.claude/skills/laravel-best-practices/rules/blade-views.md +++ /dev/null @@ -1,36 +0,0 @@ -# Blade & Views Best Practices - -## Use `$attributes->merge()` in Component Templates - -Hardcoding classes prevents consumers from adding their own. `merge()` combines class attributes cleanly. - -```blade -
merge(['class' => 'alert alert-'.$type]) }}> - {{ $message }} -
-``` - -## Use `@pushOnce` for Per-Component Scripts - -If a component renders inside a `@foreach`, `@push` inserts the script N times. `@pushOnce` guarantees it's included exactly once. - -## Prefer Blade Components Over `@include` - -`@include` shares all parent variables implicitly (hidden coupling). Components have explicit props, attribute bags, and slots. - -## Use View Composers for Shared View Data - -If every controller rendering a sidebar must pass `$categories`, that's duplicated code. A View Composer centralizes it. - -## Use Blade Fragments for Partial Re-Renders (htmx/Turbo) - -A single view can return either the full page or just a fragment, keeping routing clean. - -```php -return view('dashboard', compact('users')) - ->fragmentIf($request->hasHeader('HX-Request'), 'user-list'); -``` - -## Use `@aware` for Deeply Nested Component Props - -Avoids re-passing parent props through every level of nested components. diff --git a/.claude/skills/laravel-best-practices/rules/caching.md b/.claude/skills/laravel-best-practices/rules/caching.md deleted file mode 100644 index 67408d6..0000000 --- a/.claude/skills/laravel-best-practices/rules/caching.md +++ /dev/null @@ -1,70 +0,0 @@ -# Caching Best Practices - -## Use `Cache::remember()` Instead of Manual Get/Put - -Cleaner cache-aside pattern that removes boilerplate. use `Cache::lock()` for race conditions. - -Incorrect: -```php -$val = Cache::get('stats'); -if (! $val) { - $val = $this->computeStats(); - Cache::put('stats', $val, 60); -} -``` - -Correct: -```php -$val = Cache::remember('stats', 60, fn () => $this->computeStats()); -``` - -## Use `Cache::flexible()` for Stale-While-Revalidate - -On high-traffic keys, one user always gets a slow response when the cache expires. `flexible()` serves slightly stale data while refreshing in the background. - -Incorrect: `Cache::remember('users', 300, fn () => User::all());` - -Correct: `Cache::flexible('users', [300, 600], fn () => User::all());` — fresh for 5 min, stale-but-served up to 10 min, refreshes via deferred function. - -## Use `Cache::memo()` to Avoid Redundant Hits Within a Request - -If the same cache key is read multiple times per request (e.g., a service called from multiple places), `memo()` stores the resolved value in memory. - -`Cache::memo()->get('settings');` — 5 calls = 1 Redis round-trip instead of 5. - -## Use Cache Tags to Invalidate Related Groups - -Without tags, invalidating a group of entries requires tracking every key. Tags let you flush atomically. Only works with `redis`, `memcached`, `dynamodb` — not `file` or `database`. - -```php -Cache::tags(['user-1'])->flush(); -``` - -## Use `Cache::add()` for Atomic Conditional Writes - -`add()` only writes if the key does not exist — atomic, no race condition between checking and writing. - -Incorrect: `if (! Cache::has('lock')) { Cache::put('lock', true, 10); }` - -Correct: `Cache::add('lock', true, 10);` - -## Use `once()` for Per-Request Memoization - -`once()` memoizes a function's return value for the lifetime of the object (or request for closures). Unlike `Cache::memo()`, it doesn't hit the cache store at all — pure in-memory. - -```php -public function roles(): Collection -{ - return once(fn () => $this->loadRoles()); -} -``` - -Multiple calls return the cached result without re-executing. Use `once()` for expensive computations called multiple times per request. Use `Cache::memo()` when you also want cross-request caching. - -## Configure Failover Cache Stores in Production - -If Redis goes down, the app falls back to a secondary store automatically. - -```php -'failover' => ['driver' => 'failover', 'stores' => ['redis', 'database']], -``` diff --git a/.claude/skills/laravel-best-practices/rules/collections.md b/.claude/skills/laravel-best-practices/rules/collections.md deleted file mode 100644 index 18e8d9e..0000000 --- a/.claude/skills/laravel-best-practices/rules/collections.md +++ /dev/null @@ -1,44 +0,0 @@ -# Collection Best Practices - -## Use Higher-Order Messages for Simple Operations - -Incorrect: -```php -$users->each(function (User $user) { - $user->markAsVip(); -}); -``` - -Correct: `$users->each->markAsVip();` - -Works with `each`, `map`, `sum`, `filter`, `reject`, `contains`, etc. - -## Choose `cursor()` vs. `lazy()` Correctly - -- `cursor()` — one model in memory, but cannot eager-load relationships (N+1 risk). -- `lazy()` — chunked pagination returning a flat LazyCollection, supports eager loading. - -Incorrect: `User::with('roles')->cursor()` — eager loading silently ignored. - -Correct: `User::with('roles')->lazy()` for relationship access; `User::cursor()` for attribute-only work. - -## Use `lazyById()` When Updating Records While Iterating - -`lazy()` uses offset pagination — updating records during iteration can skip or double-process. `lazyById()` uses `id > last_id`, safe against mutation. - -## Use `toQuery()` for Bulk Operations on Collections - -Avoids manual `whereIn` construction. - -Incorrect: `User::whereIn('id', $users->pluck('id'))->update([...]);` - -Correct: `$users->toQuery()->update([...]);` - -## Use `#[CollectedBy]` for Custom Collection Classes - -More declarative than overriding `newCollection()`. - -```php -#[CollectedBy(UserCollection::class)] -class User extends Model {} -``` diff --git a/.claude/skills/laravel-best-practices/rules/config.md b/.claude/skills/laravel-best-practices/rules/config.md deleted file mode 100644 index 9bea727..0000000 --- a/.claude/skills/laravel-best-practices/rules/config.md +++ /dev/null @@ -1,73 +0,0 @@ -# Configuration Best Practices - -## `env()` Only in Config Files - -Direct `env()` calls may return `null` when config is cached. - -Incorrect: -```php -$key = env('API_KEY'); -``` - -Correct: -```php -// config/services.php -'key' => env('API_KEY'), - -// Application code -$key = config('services.key'); -``` - -## Use Encrypted Env or External Secrets - -Never store production secrets in plain `.env` files in version control. - -Incorrect: -```bash - -# .env committed to repo or shared in Slack - -STRIPE_SECRET=sk_live_abc123 -AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI -``` - -Correct: -```bash -php artisan env:encrypt --env=production --readable -php artisan env:decrypt --env=production -``` - -For cloud deployments, prefer the platform's native secret store (AWS Secrets Manager, Vault, etc.) and inject at runtime. - -## Use `App::environment()` for Environment Checks - -Incorrect: -```php -if (env('APP_ENV') === 'production') { -``` - -Correct: -```php -if (app()->isProduction()) { -// or -if (App::environment('production')) { -``` - -## Use Constants and Language Files - -Use class constants instead of hardcoded magic strings for model states, types, and statuses. - -```php -// Incorrect -return $this->type === 'normal'; - -// Correct -return $this->type === self::TYPE_NORMAL; -``` - -If the application already uses language files for localization, use `__()` for user-facing strings too. Do not introduce language files purely for English-only apps — simple string literals are fine there. - -```php -// Only when lang files already exist in the project -return back()->with('message', __('app.article_added')); -``` diff --git a/.claude/skills/laravel-best-practices/rules/db-performance.md b/.claude/skills/laravel-best-practices/rules/db-performance.md deleted file mode 100644 index c49ba16..0000000 --- a/.claude/skills/laravel-best-practices/rules/db-performance.md +++ /dev/null @@ -1,192 +0,0 @@ -# Database Performance Best Practices - -## Always Eager Load Relationships - -Lazy loading causes N+1 query problems — one query per loop iteration. Always use `with()` to load relationships upfront. - -Incorrect (N+1 — executes 1 + N queries): -```php -$posts = Post::all(); -foreach ($posts as $post) { - echo $post->author->name; -} -``` - -Correct (2 queries total): -```php -$posts = Post::with('author')->get(); -foreach ($posts as $post) { - echo $post->author->name; -} -``` - -Constrain eager loads to select only needed columns (always include the foreign key): - -```php -$users = User::with(['posts' => function ($query) { - $query->select('id', 'user_id', 'title') - ->where('published', true) - ->latest() - ->limit(10); -}])->get(); -``` - -## Prevent Lazy Loading in Development - -Enable this in `AppServiceProvider::boot()` to catch N+1 issues during development. - -```php -public function boot(): void -{ - Model::preventLazyLoading(! app()->isProduction()); -} -``` - -Throws `LazyLoadingViolationException` when a relationship is accessed without being eager-loaded. - -## Select Only Needed Columns - -Avoid `SELECT *` — especially when tables have large text or JSON columns. - -Incorrect: -```php -$posts = Post::with('author')->get(); -``` - -Correct: -```php -$posts = Post::select('id', 'title', 'user_id', 'created_at') - ->with(['author:id,name,avatar']) - ->get(); -``` - -When selecting columns on eager-loaded relationships, always include the foreign key column or the relationship won't match. - -## Chunk Large Datasets - -Never load thousands of records at once. Use chunking for batch processing. - -Incorrect: -```php -$users = User::all(); -foreach ($users as $user) { - $user->notify(new WeeklyDigest); -} -``` - -Correct: -```php -User::where('subscribed', true)->chunk(200, function ($users) { - foreach ($users as $user) { - $user->notify(new WeeklyDigest); - } -}); -``` - -Use `chunkById()` when modifying records during iteration — standard `chunk()` uses OFFSET which shifts when rows change: - -```php -User::where('active', false)->chunkById(200, function ($users) { - $users->each->delete(); -}); -``` - -## Add Database Indexes - -Index columns that appear in `WHERE`, `ORDER BY`, `JOIN`, and `GROUP BY` clauses. - -Incorrect: -```php -Schema::create('orders', function (Blueprint $table) { - $table->id(); - $table->foreignId('user_id')->constrained(); - $table->string('status'); - $table->timestamps(); -}); -``` - -Correct: -```php -Schema::create('orders', function (Blueprint $table) { - $table->id(); - $table->foreignId('user_id')->index()->constrained(); - $table->string('status')->index(); - $table->timestamps(); - $table->index(['status', 'created_at']); -}); -``` - -Add composite indexes for common query patterns (e.g., `WHERE status = ? ORDER BY created_at`). - -## Use `withCount()` for Counting Relations - -Never load entire collections just to count them. - -Incorrect: -```php -$posts = Post::all(); -foreach ($posts as $post) { - echo $post->comments->count(); -} -``` - -Correct: -```php -$posts = Post::withCount('comments')->get(); -foreach ($posts as $post) { - echo $post->comments_count; -} -``` - -Conditional counting: - -```php -$posts = Post::withCount([ - 'comments', - 'comments as approved_comments_count' => function ($query) { - $query->where('approved', true); - }, -])->get(); -``` - -## Use `cursor()` for Memory-Efficient Iteration - -For read-only iteration over large result sets, `cursor()` loads one record at a time via a PHP generator. - -Incorrect: -```php -$users = User::where('active', true)->get(); -``` - -Correct: -```php -foreach (User::where('active', true)->cursor() as $user) { - ProcessUser::dispatch($user->id); -} -``` - -Use `cursor()` for read-only iteration. Use `chunk()` / `chunkById()` when modifying records. - -## No Queries in Blade Templates - -Never execute queries in Blade templates. Pass data from controllers. - -Incorrect: -```blade -@foreach (User::all() as $user) - {{ $user->profile->name }} -@endforeach -``` - -Correct: -```php -// Controller -$users = User::with('profile')->get(); -return view('users.index', compact('users')); -``` - -```blade -@foreach ($users as $user) - {{ $user->profile->name }} -@endforeach -``` diff --git a/.claude/skills/laravel-best-practices/rules/eloquent.md b/.claude/skills/laravel-best-practices/rules/eloquent.md deleted file mode 100644 index 413d5da..0000000 --- a/.claude/skills/laravel-best-practices/rules/eloquent.md +++ /dev/null @@ -1,148 +0,0 @@ -# Eloquent Best Practices - -## Use Correct Relationship Types - -Use `hasMany`, `belongsTo`, `morphMany`, etc. with proper return type hints. - -```php -public function comments(): HasMany -{ - return $this->hasMany(Comment::class); -} - -public function author(): BelongsTo -{ - return $this->belongsTo(User::class, 'user_id'); -} -``` - -## Use Local Scopes for Reusable Queries - -Extract reusable query constraints into local scopes to avoid duplication. - -Incorrect: -```php -$active = User::where('verified', true)->whereNotNull('activated_at')->get(); -$articles = Article::whereHas('user', function ($q) { - $q->where('verified', true)->whereNotNull('activated_at'); -})->get(); -``` - -Correct: -```php -public function scopeActive(Builder $query): Builder -{ - return $query->where('verified', true)->whereNotNull('activated_at'); -} - -// Usage -$active = User::active()->get(); -$articles = Article::whereHas('user', fn ($q) => $q->active())->get(); -``` - -## Apply Global Scopes Sparingly - -Global scopes silently modify every query on the model, making debugging difficult. Prefer local scopes and reserve global scopes for truly universal constraints like soft deletes or multi-tenancy. - -Incorrect (global scope for a conditional filter): -```php -class PublishedScope implements Scope -{ - public function apply(Builder $builder, Model $model): void - { - $builder->where('published', true); - } -} -// Now admin panels, reports, and background jobs all silently skip drafts -``` - -Correct (local scope you opt into): -```php -public function scopePublished(Builder $query): Builder -{ - return $query->where('published', true); -} - -Post::published()->paginate(); // Explicit -Post::paginate(); // Admin sees all -``` - -## Define Attribute Casts - -Use the `casts()` method (or `$casts` property following project convention) for automatic type conversion. - -```php -protected function casts(): array -{ - return [ - 'is_active' => 'boolean', - 'metadata' => 'array', - 'total' => 'decimal:2', - ]; -} -``` - -## Cast Date Columns Properly - -Always cast date columns. Use Carbon instances in templates instead of formatting strings manually. - -Incorrect: -```blade -{{ Carbon::createFromFormat('Y-d-m H-i', $order->ordered_at)->toDateString() }} -``` - -Correct: -```php -protected function casts(): array -{ - return [ - 'ordered_at' => 'datetime', - ]; -} -``` - -```blade -{{ $order->ordered_at->toDateString() }} -{{ $order->ordered_at->format('m-d') }} -``` - -## Use `whereBelongsTo()` for Relationship Queries - -Cleaner than manually specifying foreign keys. - -Incorrect: -```php -Post::where('user_id', $user->id)->get(); -``` - -Correct: -```php -Post::whereBelongsTo($user)->get(); -Post::whereBelongsTo($user, 'author')->get(); -``` - -## Avoid Hardcoded Table Names in Queries - -Never use string literals for table names in raw queries, joins, or subqueries. Hardcoded table names make it impossible to find all places a model is used and break refactoring (e.g., renaming a table requires hunting through every raw string). - -Incorrect: -```php -DB::table('users')->where('active', true)->get(); - -$query->join('companies', 'companies.id', '=', 'users.company_id'); - -DB::select('SELECT * FROM orders WHERE status = ?', ['pending']); -``` - -Correct — reference the model's table: -```php -DB::table((new User)->getTable())->where('active', true)->get(); - -// Even better — use Eloquent or the query builder instead of raw SQL -User::where('active', true)->get(); -Order::where('status', 'pending')->get(); -``` - -Prefer Eloquent queries and relationships over `DB::table()` whenever possible — they already reference the model's table. When `DB::table()` or raw joins are unavoidable, always use `(new Model)->getTable()` to keep the reference traceable. - -**Exception — migrations:** In migrations, hardcoded table names via `DB::table('settings')` are acceptable and preferred. Models change over time but migrations are frozen snapshots — referencing a model that is later renamed or deleted would break the migration. diff --git a/.claude/skills/laravel-best-practices/rules/error-handling.md b/.claude/skills/laravel-best-practices/rules/error-handling.md deleted file mode 100644 index 4b14866..0000000 --- a/.claude/skills/laravel-best-practices/rules/error-handling.md +++ /dev/null @@ -1,72 +0,0 @@ -# Error Handling Best Practices - -## Exception Reporting and Rendering - -There are two valid approaches — choose one and apply it consistently across the project. - -**Co-location on the exception class** — keeps behavior alongside the exception definition, easier to find: - -```php -class InvalidOrderException extends Exception -{ - public function report(): void { /* custom reporting */ } - - public function render(Request $request): Response - { - return response()->view('errors.invalid-order', status: 422); - } -} -``` - -**Centralized in `bootstrap/app.php`** — all exception handling in one place, easier to see the full picture: - -```php -->withExceptions(function (Exceptions $exceptions) { - $exceptions->report(function (InvalidOrderException $e) { /* ... */ }); - $exceptions->render(function (InvalidOrderException $e, Request $request) { - return response()->view('errors.invalid-order', status: 422); - }); -}) -``` - -Check the existing codebase and follow whichever pattern is already established. - -## Use `ShouldntReport` for Exceptions That Should Never Log - -More discoverable than listing classes in `dontReport()`. - -```php -class PodcastProcessingException extends Exception implements ShouldntReport {} -``` - -## Throttle High-Volume Exceptions - -A single failing integration can flood error tracking. Use `throttle()` to rate-limit per exception type. - -## Enable `dontReportDuplicates()` - -Prevents the same exception instance from being logged multiple times when `report($e)` is called in multiple catch blocks. - -## Force JSON Error Rendering for API Routes - -Laravel auto-detects `Accept: application/json` but API clients may not set it. Explicitly declare JSON rendering for API routes. - -```php -$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) { - return $request->is('api/*') || $request->expectsJson(); -}); -``` - -## Add Context to Exception Classes - -Attach structured data to exceptions at the source via a `context()` method — Laravel includes it automatically in the log entry. - -```php -class InvalidOrderException extends Exception -{ - public function context(): array - { - return ['order_id' => $this->orderId]; - } -} -``` diff --git a/.claude/skills/laravel-best-practices/rules/events-notifications.md b/.claude/skills/laravel-best-practices/rules/events-notifications.md deleted file mode 100644 index 82e329e..0000000 --- a/.claude/skills/laravel-best-practices/rules/events-notifications.md +++ /dev/null @@ -1,52 +0,0 @@ -# Events & Notifications Best Practices - -## Rely on Event Discovery - -Laravel auto-discovers listeners by reading `handle(EventType $event)` type-hints. No manual registration needed in `AppServiceProvider`. - -## Run `event:cache` in Production Deploy - -Event discovery scans the filesystem per-request in dev. Cache it in production: `php artisan optimize` or `php artisan event:cache`. - -## Use `ShouldDispatchAfterCommit` Inside Transactions - -Without it, a queued listener may process before the DB transaction commits, reading data that doesn't exist yet. - -```php -class OrderShipped implements ShouldDispatchAfterCommit {} -``` - -## Always Queue Notifications - -Notifications often hit external APIs (email, SMS, Slack). Without `ShouldQueue`, they block the HTTP response. - -```php -class InvoicePaid extends Notification implements ShouldQueue -{ - use Queueable; -} -``` - -## Use `afterCommit()` on Notifications in Transactions - -Same race condition as events — call `afterCommit()` to delay dispatch until the transaction commits. - -```php -$user->notify((new InvoicePaid($invoice))->afterCommit()); -``` - -## Route Notification Channels to Dedicated Queues - -Mail and database notifications have different priorities. Use `viaQueues()` to route them to separate queues. - -## Use On-Demand Notifications for Non-User Recipients - -Avoid creating dummy models to send notifications to arbitrary addresses. - -```php -Notification::route('mail', 'admin@example.com')->notify(new SystemAlert()); -``` - -## Implement `HasLocalePreference` on Notifiable Models - -Laravel automatically uses the user's preferred locale for all notifications and mailables — no per-call `locale()` needed. diff --git a/.claude/skills/laravel-best-practices/rules/http-client.md b/.claude/skills/laravel-best-practices/rules/http-client.md deleted file mode 100644 index 8e2f16e..0000000 --- a/.claude/skills/laravel-best-practices/rules/http-client.md +++ /dev/null @@ -1,160 +0,0 @@ -# HTTP Client Best Practices - -## Always Set Explicit Timeouts - -The default timeout is 30 seconds — too long for most API calls. Always set explicit `timeout` and `connectTimeout` to fail fast. - -Incorrect: -```php -$response = Http::get('https://api.example.com/users'); -``` - -Correct: -```php -$response = Http::timeout(5) - ->connectTimeout(3) - ->get('https://api.example.com/users'); -``` - -For service-specific clients, define timeouts in a macro: - -```php -Http::macro('github', function () { - return Http::baseUrl('https://api.github.com') - ->timeout(10) - ->connectTimeout(3) - ->withToken(config('services.github.token')); -}); - -$response = Http::github()->get('/repos/laravel/framework'); -``` - -## Use Retry with Backoff for External APIs - -External APIs have transient failures. Use `retry()` with increasing delays. - -Incorrect: -```php -$response = Http::post('https://api.stripe.com/v1/charges', $data); - -if ($response->failed()) { - throw new PaymentFailedException('Charge failed'); -} -``` - -Correct: -```php -$response = Http::retry([100, 500, 1000]) - ->timeout(10) - ->post('https://api.stripe.com/v1/charges', $data); -``` - -Only retry on specific errors: - -```php -$response = Http::retry(3, 100, function (Throwable $exception, PendingRequest $request) { - return $exception instanceof ConnectionException - || ($exception instanceof RequestException && $exception->response->serverError()); -})->post('https://api.example.com/data'); -``` - -## Handle Errors Explicitly - -The HTTP Client does not throw on 4xx/5xx by default. Always check status or use `throw()`. - -Incorrect: -```php -$response = Http::get('https://api.example.com/users/1'); -$user = $response->json(); // Could be an error body -``` - -Correct: -```php -$response = Http::timeout(5) - ->get('https://api.example.com/users/1') - ->throw(); - -$user = $response->json(); -``` - -For graceful degradation: - -```php -$response = Http::get('https://api.example.com/users/1'); - -if ($response->successful()) { - return $response->json(); -} - -if ($response->notFound()) { - return null; -} - -$response->throw(); -``` - -## Use Request Pooling for Concurrent Requests - -When making multiple independent API calls, use `Http::pool()` instead of sequential calls. - -Incorrect: -```php -$users = Http::get('https://api.example.com/users')->json(); -$posts = Http::get('https://api.example.com/posts')->json(); -$comments = Http::get('https://api.example.com/comments')->json(); -``` - -Correct: -```php -use Illuminate\Http\Client\Pool; - -$responses = Http::pool(fn (Pool $pool) => [ - $pool->as('users')->get('https://api.example.com/users'), - $pool->as('posts')->get('https://api.example.com/posts'), - $pool->as('comments')->get('https://api.example.com/comments'), -]); - -$users = $responses['users']->json(); -$posts = $responses['posts']->json(); -``` - -## Fake HTTP Calls in Tests - -Never make real HTTP requests in tests. Use `Http::fake()` and `preventStrayRequests()`. - -Incorrect: -```php -it('syncs user from API', function () { - $service = new UserSyncService; - $service->sync(1); // Hits the real API -}); -``` - -Correct: -```php -it('syncs user from API', function () { - Http::preventStrayRequests(); - - Http::fake([ - 'api.example.com/users/1' => Http::response([ - 'name' => 'John Doe', - 'email' => 'john@example.com', - ]), - ]); - - $service = new UserSyncService; - $service->sync(1); - - Http::assertSent(function (Request $request) { - return $request->url() === 'https://api.example.com/users/1'; - }); -}); -``` - -Test failure scenarios too: - -```php -Http::fake([ - 'api.example.com/*' => Http::failedConnection(), -]); -``` diff --git a/.claude/skills/laravel-best-practices/rules/mail.md b/.claude/skills/laravel-best-practices/rules/mail.md deleted file mode 100644 index 7c71733..0000000 --- a/.claude/skills/laravel-best-practices/rules/mail.md +++ /dev/null @@ -1,27 +0,0 @@ -# Mail Best Practices - -## Implement `ShouldQueue` on the Mailable Class - -Makes queueing the default regardless of how the mailable is dispatched. No need to remember `Mail::queue()` at every call site — `Mail::send()` also queues it. - -## Use `afterCommit()` on Mailables Inside Transactions - -A queued mailable dispatched inside a transaction may process before the commit. Use `$this->afterCommit()` in the constructor. - -## Use `assertQueued()` Not `assertSent()` for Queued Mailables - -`Mail::assertSent()` only catches synchronous mail. Queued mailables fail `assertSent` with a "Did you mean to use assertQueued()?" hint. - -Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`. - -Correct: `Mail::assertQueued(OrderShipped::class);` - -## Use Markdown Mailables for Transactional Emails - -Markdown mailables auto-generate both HTML and plain-text versions, use responsive components, and allow global style customization. Generate with `--markdown` flag. - -## Separate Content Tests from Sending Tests - -Content tests: instantiate the mailable directly, call `assertSeeInHtml()`. -Sending tests: use `Mail::fake()` and `assertSent()`/`assertQueued()`. -Don't mix them — it conflates concerns and makes tests brittle. diff --git a/.claude/skills/laravel-best-practices/rules/migrations.md b/.claude/skills/laravel-best-practices/rules/migrations.md deleted file mode 100644 index df6f5f3..0000000 --- a/.claude/skills/laravel-best-practices/rules/migrations.md +++ /dev/null @@ -1,121 +0,0 @@ -# Migration Best Practices - -## Generate Migrations with Artisan - -Always use `php artisan make:migration` for consistent naming and timestamps. - -Incorrect (manually created file): -```php -// database/migrations/posts_migration.php ← wrong naming, no timestamp -``` - -Correct (Artisan-generated): -```bash -php artisan make:migration create_posts_table -php artisan make:migration add_slug_to_posts_table -``` - -## Use `constrained()` for Foreign Keys - -Automatic naming and referential integrity. - -```php -$table->foreignId('user_id')->constrained()->cascadeOnDelete(); - -// Non-standard names -$table->foreignId('author_id')->constrained('users'); -``` - -## Never Modify Deployed Migrations - -Once a migration has run in production, treat it as immutable. Create a new migration to change the table. - -Incorrect (editing a deployed migration): -```php -// 2024_01_01_create_posts_table.php — already in production -$table->string('slug')->unique(); // ← added after deployment -``` - -Correct (new migration to alter): -```php -// 2024_03_15_add_slug_to_posts_table.php -Schema::table('posts', function (Blueprint $table) { - $table->string('slug')->unique()->after('title'); -}); -``` - -## Add Indexes in the Migration - -Add indexes when creating the table, not as an afterthought. Columns used in `WHERE`, `ORDER BY`, and `JOIN` clauses need indexes. - -Incorrect: -```php -Schema::create('orders', function (Blueprint $table) { - $table->id(); - $table->foreignId('user_id')->constrained(); - $table->string('status'); - $table->timestamps(); -}); -``` - -Correct: -```php -Schema::create('orders', function (Blueprint $table) { - $table->id(); - $table->foreignId('user_id')->constrained()->index(); - $table->string('status')->index(); - $table->timestamp('shipped_at')->nullable()->index(); - $table->timestamps(); -}); -``` - -## Mirror Defaults in Model `$attributes` - -When a column has a database default, mirror it in the model so new instances have correct values before saving. - -```php -// Migration -$table->string('status')->default('pending'); - -// Model -protected $attributes = [ - 'status' => 'pending', -]; -``` - -## Write Reversible `down()` Methods by Default - -Implement `down()` for schema changes that can be safely reversed so `migrate:rollback` works in CI and failed deployments. - -```php -public function down(): void -{ - Schema::table('posts', function (Blueprint $table) { - $table->dropColumn('slug'); - }); -} -``` - -For intentionally irreversible migrations (e.g., destructive data backfills), leave a clear comment and require a forward fix migration instead of pretending rollback is supported. - -## Keep Migrations Focused - -One concern per migration. Never mix DDL (schema changes) and DML (data manipulation). - -Incorrect (partial failure creates unrecoverable state): -```php -public function up(): void -{ - Schema::create('settings', function (Blueprint $table) { ... }); - DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']); -} -``` - -Correct (separate migrations): -```php -// Migration 1: create_settings_table -Schema::create('settings', function (Blueprint $table) { ... }); - -// Migration 2: seed_default_settings -DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']); -``` diff --git a/.claude/skills/laravel-best-practices/rules/queue-jobs.md b/.claude/skills/laravel-best-practices/rules/queue-jobs.md deleted file mode 100644 index c41915e..0000000 --- a/.claude/skills/laravel-best-practices/rules/queue-jobs.md +++ /dev/null @@ -1,144 +0,0 @@ -# Queue & Job Best Practices - -## Set `retry_after` Greater Than `timeout` - -If `retry_after` is shorter than the job's `timeout`, the queue worker re-dispatches the job while it's still running, causing duplicate execution. - -Incorrect (`retry_after` ≤ `timeout`): -```php -class ProcessReport implements ShouldQueue -{ - public $timeout = 120; -} - -// config/queue.php — retry_after: 90 ← job retried while still running! -``` - -Correct (`retry_after` > `timeout`): -```php -class ProcessReport implements ShouldQueue -{ - public $timeout = 120; -} - -// config/queue.php — retry_after: 180 ← safely longer than any job timeout -``` - -## Use Exponential Backoff - -Use progressively longer delays between retries to avoid hammering failing services. - -Incorrect (fixed retry interval): -```php -class SyncWithStripe implements ShouldQueue -{ - public $tries = 3; - // Default: retries immediately, overwhelming the API -} -``` - -Correct (exponential backoff): -```php -class SyncWithStripe implements ShouldQueue -{ - public $tries = 3; - public $backoff = [1, 5, 10]; -} -``` - -## Implement `ShouldBeUnique` - -Prevent duplicate job processing. - -```php -class GenerateInvoice implements ShouldQueue, ShouldBeUnique -{ - public function uniqueId(): string - { - return $this->order->id; - } - - public $uniqueFor = 3600; -} -``` - -## Always Implement `failed()` - -Handle errors explicitly — don't rely on silent failure. - -```php -public function failed(?Throwable $exception): void -{ - $this->podcast->update(['status' => 'failed']); - Log::error('Processing failed', ['id' => $this->podcast->id, 'error' => $exception->getMessage()]); -} -``` - -## Rate Limit External API Calls in Jobs - -Use `RateLimited` middleware to throttle jobs calling third-party APIs. - -```php -public function middleware(): array -{ - return [new RateLimited('external-api')]; -} -``` - -## Batch Related Jobs - -Use `Bus::batch()` when jobs should succeed or fail together. - -```php -Bus::batch([ - new ImportCsvChunk($chunk1), - new ImportCsvChunk($chunk2), -]) -->then(fn (Batch $batch) => Notification::send($user, new ImportComplete)) -->catch(fn (Batch $batch, Throwable $e) => Log::error('Batch failed')) -->dispatch(); -``` - -## `retryUntil()` Needs `$tries = 0` - -When using time-based retry limits, set `$tries = 0` to avoid premature failure. - -```php -public $tries = 0; - -public function retryUntil(): \DateTimeInterface -{ - return now()->addHours(4); -} -``` - -## Use `ShouldBeUniqueUntilProcessing` for Early Lock Release - -`ShouldBeUnique` holds the lock until the job completes. `ShouldBeUniqueUntilProcessing` releases it when processing starts, allowing new instances to queue. - -```php -class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing -{ - // Lock releases when processing begins, not when it finishes -} -``` - -## Use Horizon for Complex Queue Scenarios - -Use Laravel Horizon when you need monitoring, auto-scaling, failure tracking, or multiple queues with different priorities. - -```php -// config/horizon.php -'environments' => [ - 'production' => [ - 'supervisor-1' => [ - 'connection' => 'redis', - 'queue' => ['high', 'default', 'low'], - 'balance' => 'auto', - 'minProcesses' => 1, - 'maxProcesses' => 10, - 'tries' => 3, - ], - ], -], -``` diff --git a/.claude/skills/laravel-best-practices/rules/routing.md b/.claude/skills/laravel-best-practices/rules/routing.md deleted file mode 100644 index b6e3086..0000000 --- a/.claude/skills/laravel-best-practices/rules/routing.md +++ /dev/null @@ -1,99 +0,0 @@ -# Routing & Controllers Best Practices - -## Use Implicit Route Model Binding - -Let Laravel resolve models automatically from route parameters. - -Incorrect: -```php -public function show(int $id) -{ - $post = Post::findOrFail($id); -} -``` - -Correct: -```php -public function show(Post $post) -{ - return view('posts.show', ['post' => $post]); -} -``` - -## Use Scoped Bindings for Nested Resources - -Enforce parent-child relationships automatically. - -```php -Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) { - // $post is automatically scoped to $user -})->scopeBindings(); -``` - -## Use Resource Controllers - -Use `Route::resource()` or `apiResource()` for RESTful endpoints. - -```php -Route::resource('posts', PostController::class); -// In routes/api.php — the /api prefix is applied automatically -Route::apiResource('posts', Api\PostController::class); -``` - -## Keep Controllers Thin - -Aim for under 10 lines per method. Extract business logic to action or service classes. - -Incorrect: -```php -public function store(Request $request) -{ - $validated = $request->validate([...]); - if ($request->hasFile('image')) { - $request->file('image')->move(public_path('images')); - } - $post = Post::create($validated); - $post->tags()->sync($validated['tags']); - event(new PostCreated($post)); - return redirect()->route('posts.show', $post); -} -``` - -Correct: -```php -public function store(StorePostRequest $request, CreatePostAction $create) -{ - $post = $create->execute($request->validated()); - - return redirect()->route('posts.show', $post); -} -``` - -## Type-Hint Form Requests - -Type-hinting Form Requests triggers automatic validation and authorization before the method executes. - -Incorrect: -```php -public function store(Request $request): RedirectResponse -{ - $validated = $request->validate([ - 'title' => ['required', 'max:255'], - 'body' => ['required'], - ]); - - Post::create($validated); - - return redirect()->route('posts.index'); -} -``` - -Correct: -```php -public function store(StorePostRequest $request): RedirectResponse -{ - Post::create($request->validated()); - - return redirect()->route('posts.index'); -} -``` diff --git a/.claude/skills/laravel-best-practices/rules/scheduling.md b/.claude/skills/laravel-best-practices/rules/scheduling.md deleted file mode 100644 index a984794..0000000 --- a/.claude/skills/laravel-best-practices/rules/scheduling.md +++ /dev/null @@ -1,39 +0,0 @@ -# Task Scheduling Best Practices - -## Use `withoutOverlapping()` on Variable-Duration Tasks - -Without it, a long-running task spawns a second instance on the next tick, causing double-processing or resource exhaustion. - -## Use `onOneServer()` on Multi-Server Deployments - -Without it, every server runs the same task simultaneously. Requires a shared cache driver (Redis, database, Memcached). - -## Use `runInBackground()` for Concurrent Long Tasks - -By default, tasks at the same tick run sequentially. A slow first task delays all subsequent ones. `runInBackground()` runs them as separate processes. - -## Use `environments()` to Restrict Tasks - -Prevent accidental execution of production-only tasks (billing, reporting) on staging. - -```php -Schedule::command('billing:charge')->monthly()->environments(['production']); -``` - -## Use `takeUntilTimeout()` for Time-Bounded Processing - -A task running every 15 minutes that processes an unbounded cursor can overlap with the next run. Bound execution time. - -## Use Schedule Groups for Shared Configuration - -Avoid repeating `->onOneServer()->timezone('America/New_York')` across many tasks. - -```php -Schedule::daily() - ->onOneServer() - ->timezone('America/New_York') - ->group(function () { - Schedule::command('emails:send --force'); - Schedule::command('emails:prune'); - }); -``` diff --git a/.claude/skills/laravel-best-practices/rules/security.md b/.claude/skills/laravel-best-practices/rules/security.md deleted file mode 100644 index 2d7200c..0000000 --- a/.claude/skills/laravel-best-practices/rules/security.md +++ /dev/null @@ -1,198 +0,0 @@ -# Security Best Practices - -## Mass Assignment Protection - -Every model must define `$fillable` (whitelist) or `$guarded` (blacklist). - -Incorrect: -```php -class User extends Model -{ - protected $guarded = []; // All fields are mass assignable -} -``` - -Correct: -```php -class User extends Model -{ - protected $fillable = [ - 'name', - 'email', - 'password', - ]; -} -``` - -Never use `$guarded = []` on models that accept user input. - -## Authorize Every Action - -Use policies or gates in controllers. Never skip authorization. - -Incorrect: -```php -public function update(UpdatePostRequest $request, Post $post) -{ - $post->update($request->validated()); -} -``` - -Correct: -```php -public function update(UpdatePostRequest $request, Post $post) -{ - Gate::authorize('update', $post); - - $post->update($request->validated()); -} -``` - -Or via Form Request: - -```php -public function authorize(): bool -{ - return $this->user()->can('update', $this->route('post')); -} -``` - -## Prevent SQL Injection - -Always use parameter binding. Never interpolate user input into queries. - -Incorrect: -```php -DB::select("SELECT * FROM users WHERE name = '{$request->name}'"); -``` - -Correct: -```php -User::where('name', $request->name)->get(); - -// Raw expressions with bindings -User::whereRaw('LOWER(name) = ?', [strtolower($request->name)])->get(); -``` - -## Escape Output to Prevent XSS - -Use `{{ }}` for HTML escaping. Only use `{!! !!}` for trusted, pre-sanitized content. - -Incorrect: -```blade -{!! $user->bio !!} -``` - -Correct: -```blade -{{ $user->bio }} -``` - -## CSRF Protection - -Include `@csrf` in all POST/PUT/DELETE Blade forms. In Inertia apps, the `@csrf` directive is automatically applied. - -Incorrect: -```blade - - -
-``` - -Correct: -```blade -
- @csrf - -
-``` - -## Rate Limit Auth and API Routes - -Apply `throttle` middleware to authentication and API routes. - -```php -RateLimiter::for('login', function (Request $request) { - return Limit::perMinute(5)->by($request->ip()); -}); - -Route::post('/login', LoginController::class)->middleware('throttle:login'); -``` - -## Validate File Uploads - -Validate extension, MIME type, and size. The `mimes` rule checks extensions; use `mimetypes` for actual MIME type validation. Never trust client-provided filenames. - -```php -public function rules(): array -{ - return [ - 'avatar' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'], - ]; -} -``` - -Store with generated filenames: - -```php -$path = $request->file('avatar')->store('avatars', 'public'); -``` - -## Keep Secrets Out of Code - -Never commit `.env`. Access secrets via `config()` only. - -Incorrect: -```php -$key = env('API_KEY'); -``` - -Correct: -```php -// config/services.php -'api_key' => env('API_KEY'), - -// In application code -$key = config('services.api_key'); -``` - -## Audit Dependencies - -Run `composer audit` periodically to check for known vulnerabilities in dependencies. Automate this in CI to catch issues before deployment. - -```bash -composer audit -``` - -## Encrypt Sensitive Database Fields - -Use `encrypted` cast for API keys/tokens and mark the attribute as `hidden`. - -Incorrect: -```php -class Integration extends Model -{ - protected function casts(): array - { - return [ - 'api_key' => 'string', - ]; - } -} -``` - -Correct: -```php -class Integration extends Model -{ - protected $hidden = ['api_key', 'api_secret']; - - protected function casts(): array - { - return [ - 'api_key' => 'encrypted', - 'api_secret' => 'encrypted', - ]; - } -} -``` diff --git a/.claude/skills/laravel-best-practices/rules/style.md b/.claude/skills/laravel-best-practices/rules/style.md deleted file mode 100644 index a8afb36..0000000 --- a/.claude/skills/laravel-best-practices/rules/style.md +++ /dev/null @@ -1,125 +0,0 @@ -# Conventions & Style - -## Follow Laravel Naming Conventions - -| What | Convention | Good | Bad | -|------|-----------|------|-----| -| Controller | singular | `ArticleController` | `ArticlesController` | -| Model | singular | `User` | `Users` | -| Table | plural, snake_case | `article_comments` | `articleComments` | -| Pivot table | singular alphabetical | `article_user` | `user_article` | -| Column | snake_case, no model name | `meta_title` | `article_meta_title` | -| Foreign key | singular model + `_id` | `article_id` | `articles_id` | -| Route | plural | `articles/1` | `article/1` | -| Route name | snake_case with dots | `users.show_active` | `users.show-active` | -| Method | camelCase | `getAll` | `get_all` | -| Variable | camelCase | `$articlesWithAuthor` | `$articles_with_author` | -| Collection | descriptive, plural | `$activeUsers` | `$data` | -| Object | descriptive, singular | `$activeUser` | `$users` | -| View | kebab-case | `show-filtered.blade.php` | `showFiltered.blade.php` | -| Config | snake_case | `google_calendar.php` | `googleCalendar.php` | -| Enum | singular | `UserType` | `UserTypes` | - -## Prefer Shorter Readable Syntax - -| Verbose | Shorter | -|---------|---------| -| `Session::get('cart')` | `session('cart')` | -| `$request->session()->get('cart')` | `session('cart')` | -| `$request->input('name')` | `$request->name` | -| `return Redirect::back()` | `return back()` | -| `Carbon::now()` | `now()` | -| `App::make('Class')` | `app('Class')` | -| `->where('column', '=', 1)` | `->where('column', 1)` | -| `->orderBy('created_at', 'desc')` | `->latest()` | -| `->orderBy('created_at', 'asc')` | `->oldest()` | -| `->first()->name` | `->value('name')` | - -## Use Laravel String & Array Helpers - -Laravel provides `Str`, `Arr`, `Number`, and `Uri` helper classes that are more readable, chainable, and UTF-8 safe than raw PHP functions. Always prefer them. - -Strings — use `Str` and fluent `Str::of()` over raw PHP: -```php -// Incorrect -$slug = strtolower(str_replace(' ', '-', $title)); -$short = substr($text, 0, 100) . '...'; -$class = substr(strrchr('App\Models\User', '\\'), 1); - -// Correct -$slug = Str::slug($title); -$short = Str::limit($text, 100); -$class = class_basename('App\Models\User'); -``` - -Fluent strings — chain operations for complex transformations: -```php -// Incorrect -$result = strtolower(trim(str_replace('_', '-', $input))); - -// Correct -$result = Str::of($input)->trim()->replace('_', '-')->lower(); -``` - -Key `Str` methods to prefer: `Str::slug()`, `Str::limit()`, `Str::contains()`, `Str::before()`, `Str::after()`, `Str::between()`, `Str::camel()`, `Str::snake()`, `Str::kebab()`, `Str::headline()`, `Str::squish()`, `Str::mask()`, `Str::uuid()`, `Str::ulid()`, `Str::random()`, `Str::is()`. - -Arrays — use `Arr` over raw PHP: -```php -// Incorrect -$name = isset($array['user']['name']) ? $array['user']['name'] : 'default'; - -// Correct -$name = Arr::get($array, 'user.name', 'default'); -``` - -Key `Arr` methods: `Arr::get()`, `Arr::has()`, `Arr::only()`, `Arr::except()`, `Arr::first()`, `Arr::flatten()`, `Arr::pluck()`, `Arr::where()`, `Arr::wrap()`. - -Numbers — use `Number` for display formatting: -```php -Number::format(1000000); // "1,000,000" -Number::currency(1500, 'USD'); // "$1,500.00" -Number::abbreviate(1000000); // "1M" -Number::fileSize(1024 * 1024); // "1 MB" -Number::percentage(75.5); // "75.5%" -``` - -URIs — use `Uri` for URL manipulation: -```php -$uri = Uri::of('https://example.com/search') - ->withQuery(['q' => 'laravel', 'page' => 1]); -``` - -Use `$request->string('name')` to get a fluent `Stringable` directly from request input for immediate chaining. - -Use `search-docs` for the full list of available methods — these helpers are extensive. - -## No Inline JS/CSS in Blade - -Do not put JS or CSS in Blade templates. Do not put HTML in PHP classes. - -Incorrect: -```blade -let article = `{{ json_encode($article) }}`; -``` - -Correct: -```blade - -``` - -Pass data to JS via data attributes or use a dedicated PHP-to-JS package. - -## No Unnecessary Comments - -Code should be readable on its own. Use descriptive method and variable names instead of comments. The only exception is config files, where descriptive comments are expected. - -Incorrect: -```php -// Check if there are any joins -if (count((array) $builder->getQuery()->joins) > 0) -``` - -Correct: -```php -if ($this->hasJoins()) -``` diff --git a/.claude/skills/laravel-best-practices/rules/testing.md b/.claude/skills/laravel-best-practices/rules/testing.md deleted file mode 100644 index 4fbf12f..0000000 --- a/.claude/skills/laravel-best-practices/rules/testing.md +++ /dev/null @@ -1,43 +0,0 @@ -# Testing Best Practices - -## Use `LazilyRefreshDatabase` Over `RefreshDatabase` - -`RefreshDatabase` migrates once per process and wraps each test in a rolled-back transaction. `LazilyRefreshDatabase` skips even that first migration if the schema is already up to date. - -## Use Model Assertions Over Raw Database Assertions - -Incorrect: `$this->assertDatabaseHas('users', ['id' => $user->id]);` - -Correct: `$this->assertModelExists($user);` - -More expressive, type-safe, and fails with clearer messages. - -## Use Factory States and Sequences - -Named states make tests self-documenting. Sequences eliminate repetitive setup. - -Incorrect: `User::factory()->create(['email_verified_at' => null]);` - -Correct: `User::factory()->unverified()->create();` - -## Use `Exceptions::fake()` to Assert Exception Reporting - -Instead of `withoutExceptionHandling()`, use `Exceptions::fake()` to assert the correct exception was reported while the request completes normally. - -## Call `Event::fake()` After Factory Setup - -Model factories rely on model events (e.g., `creating` to generate UUIDs). Calling `Event::fake()` before factory calls silences those events, producing broken models. - -Incorrect: `Event::fake(); $user = User::factory()->create();` - -Correct: `$user = User::factory()->create(); Event::fake();` - -## Use `recycle()` to Share Relationship Instances Across Factories - -Without `recycle()`, nested factories create separate instances of the same conceptual entity. - -```php -Ticket::factory() - ->recycle(Airline::factory()->create()) - ->create(); -``` diff --git a/.claude/skills/laravel-best-practices/rules/validation.md b/.claude/skills/laravel-best-practices/rules/validation.md deleted file mode 100644 index 5fde106..0000000 --- a/.claude/skills/laravel-best-practices/rules/validation.md +++ /dev/null @@ -1,75 +0,0 @@ -# Validation & Forms Best Practices - -## Use Form Request Classes - -Extract validation from controllers into dedicated Form Request classes. - -Incorrect: -```php -public function store(Request $request) -{ - $request->validate([ - 'title' => 'required|max:255', - 'body' => 'required', - ]); -} -``` - -Correct: -```php -public function store(StorePostRequest $request) -{ - Post::create($request->validated()); -} -``` - -## Array vs. String Notation for Rules - -Array syntax is more readable and composes cleanly with `Rule::` objects. Prefer it in new code, but check existing Form Requests first and match whatever notation the project already uses. - -```php -// Preferred for new code -'email' => ['required', 'email', Rule::unique('users')], - -// Follow existing convention if the project uses string notation -'email' => 'required|email|unique:users', -``` - -## Always Use `validated()` - -Get only validated data. Never use `$request->all()` for mass operations. - -Incorrect: -```php -Post::create($request->all()); -``` - -Correct: -```php -Post::create($request->validated()); -``` - -## Use `Rule::when()` for Conditional Validation - -```php -'company_name' => [ - Rule::when($this->account_type === 'business', ['required', 'string', 'max:255']), -], -``` - -## Use the `after()` Method for Custom Validation - -Use `after()` instead of `withValidator()` for custom validation logic that depends on multiple fields. - -```php -public function after(): array -{ - return [ - function (Validator $validator) { - if ($this->quantity > Product::find($this->product_id)?->stock) { - $validator->errors()->add('quantity', 'Not enough stock.'); - } - }, - ]; -} -``` diff --git a/.claude/skills/pest-testing/SKILL.md b/.claude/skills/pest-testing/SKILL.md deleted file mode 100644 index ab27161..0000000 --- a/.claude/skills/pest-testing/SKILL.md +++ /dev/null @@ -1,166 +0,0 @@ ---- -name: pest-testing -description: "Use this skill for Pest PHP testing in Laravel projects only. Trigger whenever any test is being written, edited, fixed, or refactored — including fixing tests that broke after a code change, adding assertions, converting PHPUnit to Pest, adding datasets, and TDD workflows. Always activate when the user asks how to write something in Pest, mentions test files or directories (tests/Feature, tests/Unit, tests/Browser), or needs browser testing, smoke testing multiple pages for JS errors, or architecture tests. Covers: test()/it()/expect() syntax, datasets, mocking, browser testing (visit/click/fill), smoke testing, arch(), Livewire component tests, RefreshDatabase, and all Pest 4 features. Do not use for factories, seeders, migrations, controllers, models, or non-test PHP code." -license: MIT -metadata: - author: laravel ---- - -# Pest Testing 4 - -## Documentation - -Use `search-docs` for detailed Pest 4 patterns and documentation. - -## Basic Usage - -### Creating Tests - -All tests must be written using Pest. Use `php artisan make:test --pest {name}`. - -The `{name}` argument should include only the path and test name, but should not include the test suite. -- Incorrect: `php artisan make:test --pest Feature/SomeFeatureTest` will generate `tests/Feature/Feature/SomeFeatureTest.php` -- Correct: `php artisan make:test --pest SomeControllerTest` will generate `tests/Feature/SomeControllerTest.php` -- Incorrect: `php artisan make:test --pest --unit Unit/SomeServiceTest` will generate `tests/Unit/Unit/SomeServiceTest.php` -- Correct: `php artisan make:test --pest --unit SomeServiceTest` will generate `tests/Unit/SomeServiceTest.php` - -### Test Organization - -- Unit/Feature tests: `tests/Feature` and `tests/Unit` directories. -- Browser tests: `tests/Browser/` directory. -- Do NOT remove tests without approval - these are core application code. - -### Basic Test Structure - -Pest supports both `test()` and `it()` functions. Before writing new tests, check existing test files in the same directory to match the project's convention. Use `test()` if existing tests use `test()`, or `it()` if they use `it()`. - - -```php -it('is true', function () { - expect(true)->toBeTrue(); -}); -``` - -### Running Tests - -- Run minimal tests with filter before finalizing: `php artisan test --compact --filter=testName`. -- Run all tests: `php artisan test --compact`. -- Run file: `php artisan test --compact tests/Feature/ExampleTest.php`. - -## Assertions - -Use specific assertions (`assertSuccessful()`, `assertNotFound()`) instead of `assertStatus()`: - - -```php -it('returns all', function () { - $this->postJson('/api/docs', [])->assertSuccessful(); -}); -``` - -| Use | Instead of | -|-----|------------| -| `assertSuccessful()` | `assertStatus(200)` | -| `assertNotFound()` | `assertStatus(404)` | -| `assertForbidden()` | `assertStatus(403)` | - -## Mocking - -Import mock function before use: `use function Pest\Laravel\mock;` - -## Datasets - -Use datasets for repetitive tests (validation rules, etc.): - - -```php -it('has emails', function (string $email) { - expect($email)->not->toBeEmpty(); -})->with([ - 'james' => 'james@laravel.com', - 'taylor' => 'taylor@laravel.com', -]); -``` - -## Pest 4 Features - -| Feature | Purpose | -|---------|---------| -| Browser Testing | Full integration tests in real browsers | -| Smoke Testing | Validate multiple pages quickly | -| Visual Regression | Compare screenshots for visual changes | -| Test Sharding | Parallel CI runs | -| Architecture Testing | Enforce code conventions | - -### Browser Test Example - -Browser tests run in real browsers for full integration testing: - -- Browser tests live in `tests/Browser/`. -- Use Laravel features like `Event::fake()`, `assertAuthenticated()`, and model factories. -- Use `RefreshDatabase` for clean state per test. -- Interact with page: click, type, scroll, select, submit, drag-and-drop, touch gestures. -- Test on multiple browsers (Chrome, Firefox, Safari) if requested. -- Test on different devices/viewports (iPhone 14 Pro, tablets) if requested. -- Switch color schemes (light/dark mode) when appropriate. -- Take screenshots or pause tests for debugging. - - -```php -it('may reset the password', function () { - Notification::fake(); - - $this->actingAs(User::factory()->create()); - - $page = visit('/sign-in'); - - $page->assertSee('Sign In') - ->assertNoJavaScriptErrors() - ->click('Forgot Password?') - ->fill('email', 'nuno@laravel.com') - ->click('Send Reset Link') - ->assertSee('We have emailed your password reset link!'); - - Notification::assertSent(ResetPassword::class); -}); -``` - -### Smoke Testing - -Quickly validate multiple pages have no JavaScript errors: - - -```php -$pages = visit(['/', '/about', '/contact']); - -$pages->assertNoJavaScriptErrors()->assertNoConsoleLogs(); -``` - -### Visual Regression Testing - -Capture and compare screenshots to detect visual changes. - -### Test Sharding - -Split tests across parallel processes for faster CI runs. - -### Architecture Testing - -Pest 4 includes architecture testing (from Pest 3): - - -```php -arch('controllers') - ->expect('App\Http\Controllers') - ->toExtendNothing() - ->toHaveSuffix('Controller'); -``` - -## Common Pitfalls - -- Not importing `use function Pest\Laravel\mock;` before using mock -- Using `assertStatus(200)` instead of `assertSuccessful()` -- Forgetting datasets for repetitive validation tests -- Deleting tests without approval -- Forgetting `assertNoJavaScriptErrors()` in browser tests -- Prefixing `Feature/` or `Unit/` in `{name}` when using `make:test` diff --git a/.claude/skills/tailwindcss-development/SKILL.md b/.claude/skills/tailwindcss-development/SKILL.md deleted file mode 100644 index c0cb2fb..0000000 --- a/.claude/skills/tailwindcss-development/SKILL.md +++ /dev/null @@ -1,119 +0,0 @@ ---- -name: tailwindcss-development -description: "Always invoke when the user's message includes 'tailwind' in any form. Also invoke for: building responsive grid layouts (multi-column card grids, product grids), flex/grid page structures (dashboards with sidebars, fixed topbars, mobile-toggle navs), styling UI components (cards, tables, navbars, pricing sections, forms, inputs, badges), adding dark mode variants, fixing spacing or typography, and Tailwind v3/v4 work. The core use case: writing or fixing Tailwind utility classes in HTML templates (Blade, JSX, Vue). Skip for backend PHP logic, database queries, API routes, JavaScript with no HTML/CSS component, CSS file audits, build tool configuration, and vanilla CSS." -license: MIT -metadata: - author: laravel ---- - -# Tailwind CSS Development - -## Documentation - -Use `search-docs` for detailed Tailwind CSS v4 patterns and documentation. - -## Basic Usage - -- Use Tailwind CSS classes to style HTML. Check and follow existing Tailwind conventions in the project before introducing new patterns. -- Offer to extract repeated patterns into components that match the project's conventions (e.g., Blade, JSX, Vue). -- Consider class placement, order, priority, and defaults. Remove redundant classes, add classes to parent or child elements carefully to reduce repetition, and group elements logically. - -## Tailwind CSS v4 Specifics - -- Always use Tailwind CSS v4 and avoid deprecated utilities. -- `corePlugins` is not supported in Tailwind v4. - -### CSS-First Configuration - -In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed: - - -```css -@theme { - --color-brand: oklch(0.72 0.11 178); -} -``` - -### Import Syntax - -In Tailwind v4, import Tailwind with a regular CSS `@import` statement instead of the `@tailwind` directives used in v3: - - -```diff -- @tailwind base; -- @tailwind components; -- @tailwind utilities; -+ @import "tailwindcss"; -``` - -### Replaced Utilities - -Tailwind v4 removed deprecated utilities. Use the replacements shown below. Opacity values remain numeric. - -| Deprecated | Replacement | -|------------|-------------| -| bg-opacity-* | bg-black/* | -| text-opacity-* | text-black/* | -| border-opacity-* | border-black/* | -| divide-opacity-* | divide-black/* | -| ring-opacity-* | ring-black/* | -| placeholder-opacity-* | placeholder-black/* | -| flex-shrink-* | shrink-* | -| flex-grow-* | grow-* | -| overflow-ellipsis | text-ellipsis | -| decoration-slice | box-decoration-slice | -| decoration-clone | box-decoration-clone | - -## Spacing - -Use `gap` utilities instead of margins for spacing between siblings: - - -```html -
-
Item 1
-
Item 2
-
-``` - -## Dark Mode - -If existing pages and components support dark mode, new pages and components must support it the same way, typically using the `dark:` variant: - - -```html -
- Content adapts to color scheme -
-``` - -## Common Patterns - -### Flexbox Layout - - -```html -
-
Left content
-
Right content
-
-``` - -### Grid Layout - - -```html -
-
Card 1
-
Card 2
-
Card 3
-
-``` - -## Common Pitfalls - -- Using deprecated v3 utilities (bg-opacity-*, flex-shrink-*, etc.) -- Using `@tailwind` directives instead of `@import "tailwindcss"` -- Trying to use `tailwind.config.js` instead of CSS `@theme` directive -- Using margins for spacing between siblings instead of gap utilities -- Forgetting to add dark mode variants when the project uses dark mode diff --git a/.claude/skills/wayfinder-development/SKILL.md b/.claude/skills/wayfinder-development/SKILL.md deleted file mode 100644 index 8537dc0..0000000 --- a/.claude/skills/wayfinder-development/SKILL.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -name: wayfinder-development -description: "Use this skill for Laravel Wayfinder which auto-generates typed functions for Laravel controllers and routes. ALWAYS use this skill when frontend code needs to call backend routes or controller actions. Trigger when: connecting any React/Vue/Svelte/Inertia frontend to Laravel controllers, routes, building end-to-end features with both frontend and backend, wiring up forms or links to backend endpoints, fixing route-related TypeScript errors, importing from @/actions or @/routes, or running wayfinder:generate. Use Wayfinder route functions instead of hardcoded URLs. Covers: wayfinder() vite plugin, .url()/.get()/.post()/.form(), query params, route model binding, tree-shaking. Do not use for backend-only task" -license: MIT -metadata: - author: laravel ---- - -# Wayfinder Development - -## Documentation - -Use `search-docs` for detailed Wayfinder patterns and documentation. - -## Quick Reference - -### Generate Routes - -Run after route changes if Vite plugin isn't installed: -```bash -php artisan wayfinder:generate --no-interaction -``` -For form helpers, use `--with-form` flag: -```bash -php artisan wayfinder:generate --with-form --no-interaction -``` - -### Import Patterns - - -```typescript -// Named imports for tree-shaking (preferred)... -import { show, store, update } from '@/actions/App/Http/Controllers/PostController' - -// Named route imports... -import { show as postShow } from '@/routes/post' -``` - -### Common Methods - - -```typescript -// Get route object... -show(1) // { url: "/posts/1", method: "get" } - -// Get URL string... -show.url(1) // "/posts/1" - -// Specific HTTP methods... -show.get(1) -store.post() -update.patch(1) -destroy.delete(1) - -// Form attributes for HTML forms... -store.form() // { action: "/posts", method: "post" } - -// Query parameters... -show(1, { query: { page: 1 } }) // "/posts/1?page=1" -``` - -## Wayfinder + Inertia - -Use Wayfinder with the `
` component: - -```typescript -
-``` - -## Verification - -1. Run `php artisan wayfinder:generate` to regenerate routes if Vite plugin isn't installed -2. Check TypeScript imports resolve correctly -3. Verify route URLs match expected paths - -## Common Pitfalls - -- Using default imports instead of named imports (breaks tree-shaking) -- Forgetting to regenerate after route changes -- Not using type-safe parameter objects for route model binding diff --git a/.codex/config.toml b/.codex/config.toml deleted file mode 100644 index c0748a8..0000000 --- a/.codex/config.toml +++ /dev/null @@ -1,6 +0,0 @@ -[mcp_servers.laravel-boost] -command = "php" -args = ["artisan", "boost:mcp"] - -[mcp_servers.laravel-boost.tools.search-docs] -approval_mode = "approve" diff --git a/.gitignore b/.gitignore index 74e10e4..ab79fb3 100644 --- a/.gitignore +++ b/.gitignore @@ -27,3 +27,17 @@ yarn-error.log /.nova /.vscode /.zed + +/.agents/skills +/.claude/skills +/.codex +/AGENTS.md +/CLAUDE.md +/deployment.md +/freekliping-prd.md +/opencode.json +/technical-flow.md +/todo.md +/.prettierrc +/.prettierignore +/.mcp.json diff --git a/.mcp.json b/.mcp.json deleted file mode 100644 index 8c6715a..0000000 --- a/.mcp.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "mcpServers": { - "laravel-boost": { - "command": "php", - "args": [ - "artisan", - "boost:mcp" - ] - } - } -} \ No newline at end of file diff --git a/.prettierignore b/.prettierignore deleted file mode 100644 index 6b929ae..0000000 --- a/.prettierignore +++ /dev/null @@ -1,2 +0,0 @@ -resources/js/components/ui/* -resources/views/mail/* diff --git a/.prettierrc b/.prettierrc deleted file mode 100644 index 92805fa..0000000 --- a/.prettierrc +++ /dev/null @@ -1,25 +0,0 @@ -{ - "semi": true, - "singleQuote": true, - "singleAttributePerLine": false, - "htmlWhitespaceSensitivity": "css", - "printWidth": 80, - "plugins": [ - "prettier-plugin-tailwindcss" - ], - "tailwindFunctions": [ - "clsx", - "cn", - "cva" - ], - "tailwindStylesheet": "resources/css/app.css", - "tabWidth": 4, - "overrides": [ - { - "files": "**/*.yml", - "options": { - "tabWidth": 2 - } - } - ] -} diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index 22ce104..0000000 --- a/AGENTS.md +++ /dev/null @@ -1,206 +0,0 @@ - -=== foundation rules === - -# Laravel Boost Guidelines - -The Laravel Boost guidelines are specifically curated by Laravel maintainers for this application. These guidelines should be followed closely to ensure the best experience when building Laravel applications. - -## Foundational Context - -This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions. - -- php - 8.5 -- inertiajs/inertia-laravel (INERTIA_LARAVEL) - v3 -- laravel/framework (LARAVEL) - v13 -- laravel/prompts (PROMPTS) - v0 -- laravel/wayfinder (WAYFINDER) - v0 -- larastan/larastan (LARASTAN) - v3 -- laravel/boost (BOOST) - v2 -- laravel/mcp (MCP) - v0 -- laravel/pail (PAIL) - v1 -- laravel/pint (PINT) - v1 -- laravel/sail (SAIL) - v1 -- pestphp/pest (PEST) - v4 -- phpunit/phpunit (PHPUNIT) - v12 -- @inertiajs/react (INERTIA_REACT) - v3 -- react (REACT) - v19 -- tailwindcss (TAILWINDCSS) - v4 -- @laravel/vite-plugin-wayfinder (WAYFINDER_VITE) - v0 -- eslint (ESLINT) - v9 -- prettier (PRETTIER) - v3 - -## Skills Activation - -This project has domain-specific skills available in `**/skills/**`. You MUST activate the relevant skill whenever you work in that domain—don't wait until you're stuck. - -## Conventions - -- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, and naming. -- Use descriptive names for variables and methods. For example, `isRegisteredForDiscounts`, not `discount()`. -- Check for existing components to reuse before writing a new one. - -## Verification Scripts - -- Do not create verification scripts or tinker when tests cover that functionality and prove they work. Unit and feature tests are more important. - -## Application Structure & Architecture - -- Stick to existing directory structure; don't create new base folders without approval. -- Do not change the application's dependencies without approval. - -## Frontend Bundling - -- If the user doesn't see a frontend change reflected in the UI, it could mean they need to run `npm run build`, `npm run dev`, or `composer run dev`. Ask them. - -## Documentation Files - -- You must only create documentation files if explicitly requested by the user. - -## Replies - -- Be concise in your explanations - focus on what's important rather than explaining obvious details. - -=== boost rules === - -# Laravel Boost - -## Tools - -- Laravel Boost is an MCP server with tools designed specifically for this application. Prefer Boost tools over manual alternatives like shell commands or file reads. -- Use `database-query` to run read-only queries against the database instead of writing raw SQL in tinker. -- Use `database-schema` to inspect table structure before writing migrations or models. -- Use `get-absolute-url` to resolve the correct scheme, domain, and port for project URLs. Always use this before sharing a URL with the user. -- Use `browser-logs` to read browser logs, errors, and exceptions. Only recent logs are useful, ignore old entries. - -## Searching Documentation (IMPORTANT) - -- Always use `search-docs` before making code changes. Do not skip this step. It returns version-specific docs based on installed packages automatically. -- Pass a `packages` array to scope results when you know which packages are relevant. -- Use multiple broad, topic-based queries: `['rate limiting', 'routing rate limiting', 'routing']`. Expect the most relevant results first. -- Do not add package names to queries because package info is already shared. Use `test resource table`, not `filament 4 test resource table`. - -### Search Syntax - -1. Use words for auto-stemmed AND logic: `rate limit` matches both "rate" AND "limit". -2. Use `"quoted phrases"` for exact position matching: `"infinite scroll"` requires adjacent words in order. -3. Combine words and phrases for mixed queries: `middleware "rate limit"`. -4. Use multiple queries for OR logic: `queries=["authentication", "middleware"]`. - -## Artisan - -- Run Artisan commands directly via the command line (e.g., `php artisan route:list`). Use `php artisan list` to discover available commands and `php artisan [command] --help` to check parameters. -- Inspect routes with `php artisan route:list`. Filter with: `--method=GET`, `--name=users`, `--path=api`, `--except-vendor`, `--only-vendor`. -- Read configuration values using dot notation: `php artisan config:show app.name`, `php artisan config:show database.default`. Or read config files directly from the `config/` directory. - -## Tinker - -- Execute PHP in app context for debugging and testing code. Do not create models without user approval, prefer tests with factories instead. Prefer existing Artisan commands over custom tinker code. -- Always use single quotes to prevent shell expansion: `php artisan tinker --execute 'Your::code();'` - - Double quotes for PHP strings inside: `php artisan tinker --execute 'User::where("active", true)->count();'` - -=== php rules === - -# PHP - -- Always use curly braces for control structures, even for single-line bodies. -- Use PHP 8 constructor property promotion: `public function __construct(public GitHub $github) { }`. Do not leave empty zero-parameter `__construct()` methods unless the constructor is private. -- Use explicit return type declarations and type hints for all method parameters: `function isAccessible(User $user, ?string $path = null): bool` -- Follow existing application Enum naming conventions. -- Prefer PHPDoc blocks over inline comments. Only add inline comments for exceptionally complex logic. -- Use array shape type definitions in PHPDoc blocks. - -=== deployments rules === - -# Deployment - -- Laravel can be deployed using [Laravel Cloud](https://cloud.laravel.com/), which is the fastest way to deploy and scale production Laravel applications. - -=== tests rules === - -# Test Enforcement - -- Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass. -- Run the minimum number of tests needed to ensure code quality and speed. Use `php artisan test --compact` with a specific filename or filter. - -=== inertia-laravel/core rules === - -# Inertia - -- Inertia creates fully client-side rendered SPAs without modern SPA complexity, leveraging existing server-side patterns. -- Components live in `resources/js/pages` (unless specified in `vite.config.js`). Use `Inertia::render()` for server-side routing instead of Blade views. -- ALWAYS use `search-docs` tool for version-specific Inertia documentation and updated code examples. -- IMPORTANT: Activate `inertia-react-development` when working with Inertia client-side patterns. - -# Inertia v3 - -- Use all Inertia features from v1, v2, and v3. Check the documentation before making changes to ensure the correct approach. -- New v3 features: standalone HTTP requests (`useHttp` hook), optimistic updates with automatic rollback, layout props (`useLayoutProps` hook), instant visits, simplified SSR via `@inertiajs/vite` plugin, custom exception handling for error pages. -- Carried over from v2: deferred props, infinite scroll, merging props, polling, prefetching, once props, flash data. -- When using deferred props, add an empty state with a pulsing or animated skeleton. -- Axios has been removed. Use the built-in XHR client with interceptors, or install Axios separately if needed. -- `Inertia::lazy()` / `LazyProp` has been removed. Use `Inertia::optional()` instead. -- Prop types (`Inertia::optional()`, `Inertia::defer()`, `Inertia::merge()`) work inside nested arrays with dot-notation paths. -- SSR works automatically in Vite dev mode with `@inertiajs/vite` - no separate Node.js server needed during development. -- Event renames: `invalid` is now `httpException`, `exception` is now `networkError`. -- `router.cancel()` replaced by `router.cancelAll()`. -- The `future` configuration namespace has been removed - all v2 future options are now always enabled. - -=== laravel/core rules === - -# Do Things the Laravel Way - -- Use `php artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using `php artisan list` and check their parameters with `php artisan [command] --help`. -- If you're creating a generic PHP class, use `php artisan make:class`. -- Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior. - -### Model Creation - -- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `php artisan make:model --help` to check the available options. - -## APIs & Eloquent Resources - -- For APIs, default to using Eloquent API Resources and API versioning unless existing API routes do not, then you should follow existing application convention. - -## URL Generation - -- When generating links to other pages, prefer named routes and the `route()` function. - -## Testing - -- When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model. -- Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`. -- When creating tests, make use of `php artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests. - -## Vite Error - -- If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `npm run build` or ask the user to run `npm run dev` or `composer run dev`. - -=== wayfinder/core rules === - -# Laravel Wayfinder - -Use Wayfinder to generate TypeScript functions for Laravel routes. Import from `@/actions/` (controllers) or `@/routes/` (named routes). - -=== pint/core rules === - -# Laravel Pint Code Formatter - -- If you have modified any PHP files, you must run `vendor/bin/pint --dirty --format agent` before finalizing changes to ensure your code matches the project's expected style. -- Do not run `vendor/bin/pint --test --format agent`, simply run `vendor/bin/pint --format agent` to fix any formatting issues. - -=== pest/core rules === - -## Pest - -- This project uses Pest for testing. Create tests: `php artisan make:test --pest {name}`. -- The `{name}` argument should not include the test suite directory. Use `php artisan make:test --pest SomeFeatureTest` instead of `php artisan make:test --pest Feature/SomeFeatureTest`. -- Run tests: `php artisan test --compact` or filter: `php artisan test --compact --filter=testName`. -- Do NOT delete tests without approval. - -=== inertia-react/core rules === - -# Inertia + React - -- IMPORTANT: Activate `inertia-react-development` when working with Inertia React client-side patterns. - - diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 22ce104..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,206 +0,0 @@ - -=== foundation rules === - -# Laravel Boost Guidelines - -The Laravel Boost guidelines are specifically curated by Laravel maintainers for this application. These guidelines should be followed closely to ensure the best experience when building Laravel applications. - -## Foundational Context - -This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions. - -- php - 8.5 -- inertiajs/inertia-laravel (INERTIA_LARAVEL) - v3 -- laravel/framework (LARAVEL) - v13 -- laravel/prompts (PROMPTS) - v0 -- laravel/wayfinder (WAYFINDER) - v0 -- larastan/larastan (LARASTAN) - v3 -- laravel/boost (BOOST) - v2 -- laravel/mcp (MCP) - v0 -- laravel/pail (PAIL) - v1 -- laravel/pint (PINT) - v1 -- laravel/sail (SAIL) - v1 -- pestphp/pest (PEST) - v4 -- phpunit/phpunit (PHPUNIT) - v12 -- @inertiajs/react (INERTIA_REACT) - v3 -- react (REACT) - v19 -- tailwindcss (TAILWINDCSS) - v4 -- @laravel/vite-plugin-wayfinder (WAYFINDER_VITE) - v0 -- eslint (ESLINT) - v9 -- prettier (PRETTIER) - v3 - -## Skills Activation - -This project has domain-specific skills available in `**/skills/**`. You MUST activate the relevant skill whenever you work in that domain—don't wait until you're stuck. - -## Conventions - -- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, and naming. -- Use descriptive names for variables and methods. For example, `isRegisteredForDiscounts`, not `discount()`. -- Check for existing components to reuse before writing a new one. - -## Verification Scripts - -- Do not create verification scripts or tinker when tests cover that functionality and prove they work. Unit and feature tests are more important. - -## Application Structure & Architecture - -- Stick to existing directory structure; don't create new base folders without approval. -- Do not change the application's dependencies without approval. - -## Frontend Bundling - -- If the user doesn't see a frontend change reflected in the UI, it could mean they need to run `npm run build`, `npm run dev`, or `composer run dev`. Ask them. - -## Documentation Files - -- You must only create documentation files if explicitly requested by the user. - -## Replies - -- Be concise in your explanations - focus on what's important rather than explaining obvious details. - -=== boost rules === - -# Laravel Boost - -## Tools - -- Laravel Boost is an MCP server with tools designed specifically for this application. Prefer Boost tools over manual alternatives like shell commands or file reads. -- Use `database-query` to run read-only queries against the database instead of writing raw SQL in tinker. -- Use `database-schema` to inspect table structure before writing migrations or models. -- Use `get-absolute-url` to resolve the correct scheme, domain, and port for project URLs. Always use this before sharing a URL with the user. -- Use `browser-logs` to read browser logs, errors, and exceptions. Only recent logs are useful, ignore old entries. - -## Searching Documentation (IMPORTANT) - -- Always use `search-docs` before making code changes. Do not skip this step. It returns version-specific docs based on installed packages automatically. -- Pass a `packages` array to scope results when you know which packages are relevant. -- Use multiple broad, topic-based queries: `['rate limiting', 'routing rate limiting', 'routing']`. Expect the most relevant results first. -- Do not add package names to queries because package info is already shared. Use `test resource table`, not `filament 4 test resource table`. - -### Search Syntax - -1. Use words for auto-stemmed AND logic: `rate limit` matches both "rate" AND "limit". -2. Use `"quoted phrases"` for exact position matching: `"infinite scroll"` requires adjacent words in order. -3. Combine words and phrases for mixed queries: `middleware "rate limit"`. -4. Use multiple queries for OR logic: `queries=["authentication", "middleware"]`. - -## Artisan - -- Run Artisan commands directly via the command line (e.g., `php artisan route:list`). Use `php artisan list` to discover available commands and `php artisan [command] --help` to check parameters. -- Inspect routes with `php artisan route:list`. Filter with: `--method=GET`, `--name=users`, `--path=api`, `--except-vendor`, `--only-vendor`. -- Read configuration values using dot notation: `php artisan config:show app.name`, `php artisan config:show database.default`. Or read config files directly from the `config/` directory. - -## Tinker - -- Execute PHP in app context for debugging and testing code. Do not create models without user approval, prefer tests with factories instead. Prefer existing Artisan commands over custom tinker code. -- Always use single quotes to prevent shell expansion: `php artisan tinker --execute 'Your::code();'` - - Double quotes for PHP strings inside: `php artisan tinker --execute 'User::where("active", true)->count();'` - -=== php rules === - -# PHP - -- Always use curly braces for control structures, even for single-line bodies. -- Use PHP 8 constructor property promotion: `public function __construct(public GitHub $github) { }`. Do not leave empty zero-parameter `__construct()` methods unless the constructor is private. -- Use explicit return type declarations and type hints for all method parameters: `function isAccessible(User $user, ?string $path = null): bool` -- Follow existing application Enum naming conventions. -- Prefer PHPDoc blocks over inline comments. Only add inline comments for exceptionally complex logic. -- Use array shape type definitions in PHPDoc blocks. - -=== deployments rules === - -# Deployment - -- Laravel can be deployed using [Laravel Cloud](https://cloud.laravel.com/), which is the fastest way to deploy and scale production Laravel applications. - -=== tests rules === - -# Test Enforcement - -- Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass. -- Run the minimum number of tests needed to ensure code quality and speed. Use `php artisan test --compact` with a specific filename or filter. - -=== inertia-laravel/core rules === - -# Inertia - -- Inertia creates fully client-side rendered SPAs without modern SPA complexity, leveraging existing server-side patterns. -- Components live in `resources/js/pages` (unless specified in `vite.config.js`). Use `Inertia::render()` for server-side routing instead of Blade views. -- ALWAYS use `search-docs` tool for version-specific Inertia documentation and updated code examples. -- IMPORTANT: Activate `inertia-react-development` when working with Inertia client-side patterns. - -# Inertia v3 - -- Use all Inertia features from v1, v2, and v3. Check the documentation before making changes to ensure the correct approach. -- New v3 features: standalone HTTP requests (`useHttp` hook), optimistic updates with automatic rollback, layout props (`useLayoutProps` hook), instant visits, simplified SSR via `@inertiajs/vite` plugin, custom exception handling for error pages. -- Carried over from v2: deferred props, infinite scroll, merging props, polling, prefetching, once props, flash data. -- When using deferred props, add an empty state with a pulsing or animated skeleton. -- Axios has been removed. Use the built-in XHR client with interceptors, or install Axios separately if needed. -- `Inertia::lazy()` / `LazyProp` has been removed. Use `Inertia::optional()` instead. -- Prop types (`Inertia::optional()`, `Inertia::defer()`, `Inertia::merge()`) work inside nested arrays with dot-notation paths. -- SSR works automatically in Vite dev mode with `@inertiajs/vite` - no separate Node.js server needed during development. -- Event renames: `invalid` is now `httpException`, `exception` is now `networkError`. -- `router.cancel()` replaced by `router.cancelAll()`. -- The `future` configuration namespace has been removed - all v2 future options are now always enabled. - -=== laravel/core rules === - -# Do Things the Laravel Way - -- Use `php artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using `php artisan list` and check their parameters with `php artisan [command] --help`. -- If you're creating a generic PHP class, use `php artisan make:class`. -- Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior. - -### Model Creation - -- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `php artisan make:model --help` to check the available options. - -## APIs & Eloquent Resources - -- For APIs, default to using Eloquent API Resources and API versioning unless existing API routes do not, then you should follow existing application convention. - -## URL Generation - -- When generating links to other pages, prefer named routes and the `route()` function. - -## Testing - -- When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model. -- Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`. -- When creating tests, make use of `php artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests. - -## Vite Error - -- If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `npm run build` or ask the user to run `npm run dev` or `composer run dev`. - -=== wayfinder/core rules === - -# Laravel Wayfinder - -Use Wayfinder to generate TypeScript functions for Laravel routes. Import from `@/actions/` (controllers) or `@/routes/` (named routes). - -=== pint/core rules === - -# Laravel Pint Code Formatter - -- If you have modified any PHP files, you must run `vendor/bin/pint --dirty --format agent` before finalizing changes to ensure your code matches the project's expected style. -- Do not run `vendor/bin/pint --test --format agent`, simply run `vendor/bin/pint --format agent` to fix any formatting issues. - -=== pest/core rules === - -## Pest - -- This project uses Pest for testing. Create tests: `php artisan make:test --pest {name}`. -- The `{name}` argument should not include the test suite directory. Use `php artisan make:test --pest SomeFeatureTest` instead of `php artisan make:test --pest Feature/SomeFeatureTest`. -- Run tests: `php artisan test --compact` or filter: `php artisan test --compact --filter=testName`. -- Do NOT delete tests without approval. - -=== inertia-react/core rules === - -# Inertia + React - -- IMPORTANT: Activate `inertia-react-development` when working with Inertia React client-side patterns. - - diff --git a/deployment.md b/deployment.md deleted file mode 100644 index 32b7cbf..0000000 --- a/deployment.md +++ /dev/null @@ -1,352 +0,0 @@ -# FreeKliping Deployment Guide - -Panduan ini untuk deploy FreeKliping ke VPS/staging/production. Aplikasi ini bukan app Laravel biasa saja: proses video membutuhkan queue worker, scheduler, `ffmpeg`, `yt-dlp`, dan storage yang tidak hilang saat restart. - -## Status Kesiapan - -Layak deploy ke staging atau beta tertutup setelah semua checklist di bawah terpenuhi. - -Belum disarankan dibuka public ramai sebelum: - -- Queue worker production berjalan stabil. -- Scheduler cleanup berjalan. -- Storage output clip persistent. -- Monitoring basic tersedia untuk app, queue, disk, dan log. - -## Requirement Server - -Minimum awal yang realistis: - -- Ubuntu 22.04/24.04 atau distro Linux setara. -- PHP 8.5 dengan extension Laravel umum: `bcmath`, `ctype`, `curl`, `dom`, `fileinfo`, `mbstring`, `openssl`, `pdo_mysql`, `tokenizer`, `xml`, `zip`. -- Composer 2. -- Node.js 22 dan npm. -- MySQL 8.4 atau MariaDB kompatibel. -- Redis opsional. Saat ini `.env.example` default memakai `QUEUE_CONNECTION=database`. -- `ffmpeg`. -- `yt-dlp`. -- Node runtime tersedia untuk yt-dlp caption extraction. -- Python hanya wajib jika smart crop detector atau Whisper diaktifkan. - -## Service Yang Wajib Berjalan - -Production minimal membutuhkan tiga proses: - -- Web server: Nginx/Apache + PHP-FPM. -- Queue worker: menjalankan job analisis dan render clip. -- Scheduler: menjalankan cleanup periodik. - -Jika queue worker tidak berjalan, user akan stuck di status `Menunggu antrian render` / 5%. - -## Environment Production - -Gunakan `.env.example` sebagai dasar, lalu set minimal: - -```env -APP_NAME=FreeKliping -APP_ENV=production -APP_DEBUG=false -APP_URL=https://domain-kamu.com - -DB_CONNECTION=mysql -DB_HOST=127.0.0.1 -DB_PORT=3306 -DB_DATABASE=freecliping -DB_USERNAME=freecliping -DB_PASSWORD=ISI_PASSWORD_KUAT - -SESSION_DRIVER=database -CACHE_STORE=database -QUEUE_CONNECTION=database - -FILESYSTEM_DISK=local -FREEKLIPING_OUTPUT_DISK=local - -FREEKLIPING_YT_DLP_BINARY=yt-dlp -FREEKLIPING_YT_DLP_JS_RUNTIME=node -FREEKLIPING_FFMPEG_BINARY=ffmpeg -FREEKLIPING_FFMPEG_PRESET=veryfast - -FREEKLIPING_MAX_CLIP_LENGTH=180 -FREEKLIPING_RETENTION_HOURS=1 -FREEKLIPING_MAX_CONCURRENT_CLIPS=10 -FREEKLIPING_MAX_PENDING_PER_IP=3 -FREEKLIPING_MAX_CONCURRENT_ANALYSES=8 -FREEKLIPING_MAX_PENDING_ANALYSES_PER_IP=2 - -DB_QUEUE_RETRY_AFTER=2100 -``` - -Untuk production public, pertimbangkan Object Storage seperti S3/R2 daripada local disk. Kalau memakai local disk, pastikan `storage/` berada di disk persistent dan cukup besar. - -## First Deploy - -Contoh flow deploy manual di VPS: - -```bash -cd /var/www -git clone freecliping -cd freecliping - -cp .env.example .env -composer install --no-dev --optimize-autoloader -npm ci -npm run build - -php artisan key:generate -php artisan migrate --force -php artisan storage:link -php artisan optimize -``` - -Set permission: - -```bash -sudo chown -R www-data:www-data storage bootstrap/cache -sudo chmod -R ug+rw storage bootstrap/cache -``` - -Verifikasi: - -```bash -php artisan about -php artisan route:list --except-vendor -php artisan queue:failed -curl -I https://domain-kamu.com/up -``` - -## Deploy Update - -Setiap deploy update: - -```bash -cd /var/www/freecliping -git pull - -composer install --no-dev --optimize-autoloader -npm ci -npm run build - -php artisan migrate --force -php artisan optimize -php artisan queue:restart -php artisan schedule:interrupt -``` - -`queue:restart` penting karena worker adalah proses long-running dan tidak otomatis membaca code baru. - -## Queue Worker - -Command worker yang sesuai dengan timeout job video saat ini: - -```bash -php artisan queue:work --timeout=1900 --tries=1 -``` - -Contoh Supervisor config: - -```ini -[program:freecliping-worker] -process_name=%(program_name)s_%(process_num)02d -command=php /var/www/freecliping/artisan queue:work --timeout=1900 --tries=1 -autostart=true -autorestart=true -stopasgroup=true -killasgroup=true -user=www-data -numprocs=1 -redirect_stderr=true -stdout_logfile=/var/www/freecliping/storage/logs/worker.log -stopwaitsecs=2100 -``` - -Reload Supervisor: - -```bash -sudo supervisorctl reread -sudo supervisorctl update -sudo supervisorctl status -``` - -Kalau traffic mulai naik, naikkan `numprocs` secara hati-hati. Jangan terlalu tinggi di VPS kecil karena `ffmpeg` CPU intensive. - -## Scheduler - -Tambahkan cron untuk user yang menjalankan aplikasi: - -```cron -* * * * * cd /var/www/freecliping && php artisan schedule:run >> /dev/null 2>&1 -``` - -Scheduler saat ini menjalankan: - -- `clips:prune` setiap jam untuk cleanup output clip. -- `cache:clear` harian. - -## Nginx Contoh - -```nginx -server { - listen 80; - server_name domain-kamu.com; - root /var/www/freecliping/public; - - index index.php; - - client_max_body_size 20M; - - location / { - try_files $uri $uri/ /index.php?$query_string; - } - - location ~ \.php$ { - include snippets/fastcgi-php.conf; - fastcgi_pass unix:/run/php/php8.5-fpm.sock; - fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; - include fastcgi_params; - } - - location ~ /\.(?!well-known).* { - deny all; - } -} -``` - -Aktifkan HTTPS dengan Certbot atau reverse proxy yang sudah menyediakan TLS. - -## Binary Check - -Pastikan binary bisa dipanggil oleh user worker/web: - -```bash -which ffmpeg -ffmpeg -version - -which yt-dlp -yt-dlp --version - -which node -node --version -``` - -Jika path berbeda, set: - -```env -FREEKLIPING_FFMPEG_BINARY=/usr/bin/ffmpeg -FREEKLIPING_YT_DLP_BINARY=/usr/local/bin/yt-dlp -FREEKLIPING_YT_DLP_JS_RUNTIME=/usr/bin/node -``` - -## Health Check - -Laravel health route tersedia di: - -```text -/up -``` - -Gunakan untuk uptime monitor atau load balancer. - -Queue health manual: - -```bash -php artisan queue:monitor database:default --max=10 -php artisan queue:failed -``` - -Log: - -```bash -tail -f storage/logs/laravel.log -tail -f storage/logs/worker.log -``` - -## Smoke Test Setelah Deploy - -1. Buka homepage. -2. Paste URL YouTube pendek. -3. Tunggu analisis sampai rekomendasi muncul. -4. Generate satu clip pendek. -5. Pastikan status berubah dari queued ke processing. -6. Pastikan hasil clip bisa preview dan download. -7. Cek tidak ada failed job: - -```bash -php artisan queue:failed -``` - -## Troubleshooting - -### Stuck di 5% / Menunggu antrian render - -Penyebab paling umum: queue worker tidak berjalan. - -```bash -sudo supervisorctl status -php artisan queue:monitor database:default --max=0 -php artisan queue:failed -``` - -Jalankan manual untuk debug: - -```bash -php artisan queue:work --timeout=1900 --tries=1 -vvv -``` - -### Clip gagal diproses - -Cek binary: - -```bash -ffmpeg -version -yt-dlp --version -node --version -``` - -Cek log: - -```bash -tail -n 200 storage/logs/laravel.log -tail -n 200 storage/logs/worker.log -``` - -### Output clip hilang - -Kemungkinan storage tidak persistent atau scheduler cleanup berjalan sesuai retention. - -Cek: - -```env -FREEKLIPING_RETENTION_HOURS=1 -FREEKLIPING_OUTPUT_DISK=local -``` - -Untuk public production, gunakan retention pendek untuk biaya, tapi storage tetap harus persistent selama masa download. - -## Rollback - -Rollback manual sederhana: - -```bash -cd /var/www/freecliping -git log --oneline -5 -git checkout -composer install --no-dev --optimize-autoloader -npm ci -npm run build -php artisan migrate --force -php artisan optimize -php artisan queue:restart -php artisan schedule:interrupt -``` - -Catatan: rollback database migration bisa butuh langkah manual kalau migration baru sudah mengubah struktur data production. - -## Production Notes - -- Jangan set `APP_DEBUG=true` di production. -- Jangan commit `.env`. -- Jangan menjalankan `php artisan serve` untuk production. -- Batasi concurrency sesuai CPU server. -- Pantau disk karena file video cepat menghabiskan storage. -- Untuk public traffic, pertimbangkan Redis queue, object storage, dan worker terpisah dari web server. diff --git a/freekliping-prd.md b/freekliping-prd.md deleted file mode 100644 index b78fee1..0000000 --- a/freekliping-prd.md +++ /dev/null @@ -1,147 +0,0 @@ -# FreeKliping — Dokumen Kebutuhan Produk (PRD) - -| | | -|---|---| -| **Status** | Draft v1 | -| **Pemilik** | Kurniawan | -| **Domain** | freekliping.com | -| **Dokumen terkait** | Frontend Design Prompt (spek implementasi / prototipe yang sudah dibangun) | - ---- - -## 1. Ringkasan - -FreeKliping adalah tool berbasis browser, gratis, tanpa login, yang -memungkinkan siapa saja memotong sebagian klip pendek dari video YouTube -dengan menandai titik awal dan akhir, lalu mengunduh hasilnya. MVP saat ini -berupa prototipe frontend dengan data video yang di-mock; PRD ini mencakup -apa yang sudah tervalidasi di prototipe tersebut sekaligus apa yang -dibutuhkan versi produksi yang sesungguhnya. - -## 2. Latar Belakang & Masalah - -Kreator dan social media manager sering butuh mengambil momen 15–90 detik -dari video YouTube panjang untuk diunggah ulang sebagai Shorts/Reels/TikTok. -Tool yang sudah bagus melakukan ini (OpusClip, Klap, Vizard) dibangun di -atas AI auto-highlight, mewajibkan akun, dan harganya untuk kebutuhan tim — -kebanyakan fitur buat orang yang sebenarnya sudah tahu persis 20 detik mana -yang mau dipotong dan cuma butuh cara cepat buat motongnya. Belum ada tool -yang cepat, tanpa akun, dan kontrolnya manual yang mengisi celah itu. - -## 3. Tujuan - -- Membuat pengguna baru bisa dari "tempel link" sampai "klip sudah - ditandai" dalam waktu kurang dari satu menit, tanpa perlu bikin akun. -- Menjaga tool ini tetap gratis dan hanya dibiayai dari tip sukarela - (Saweria) — tanpa iklan, tanpa tier berbayar. -- Memvalidasi model interaksi (scrub manual + input timecode numerik) - sebelum berinvestasi ke infrastruktur pemrosesan video yang sesungguhnya. - -## 4. Bukan Tujuan (di MVP) - -- Tidak ada auto-clipping berbasis AI, deteksi highlight, atau auto-reframe -- Tidak ada subtitle/caption -- Tidak ada akun, billing, atau fitur kolaborasi tim -- Tidak ada pengambilan atau rendering video sungguhan di fase ini — data - di-mock sepenuhnya di sisi client; ini prototipe interaksi/UX, bukan - encoder yang benar-benar berfungsi - -## 5. Target Pengguna - -- **Utama:** kreator konten independen dan social media manager yang - mengolah ulang konten YouTube panjang jadi klip pendek -- **Sekunder:** pengguna kasual yang butuh satu klip cepat tanpa install - software (mis. Premiere, CapCut Desktop) untuk kebutuhan sekali pakai - -## 6. User Stories - -- Sebagai pengguna, saya ingin menempelkan link YouTube dan langsung bisa - menandai klip, tanpa perlu daftar akun. -- Sebagai pengguna, saya ingin menyeret secara visual untuk menandai awal - dan akhir klip, supaya tidak perlu menebak-nebak timestamp. -- Sebagai pengguna, saya juga ingin field timecode numerik yang presisi, - supaya bisa menyesuaikan sampai hitungan detik. -- Sebagai pengguna, saya ingin ada feedback yang jelas saat klip sedang - "diproses", supaya saya tahu tool-nya sedang bekerja, bukan macet. -- Sebagai pengguna, saya ingin bisa mengunduh klip dengan satu klik tanpa - dipaksa daftar akun di akhir prosesnya. -- Sebagai pengguna, saya ingin tahu dari awal bahwa tidak ada biaya, tidak - ada watermark, dan tidak ada pengumpulan data, supaya saya cukup percaya - untuk memakai tool ini. - -## 7. Kebutuhan Fungsional - -| Prioritas | Kebutuhan | -|---|---| -| P0 | Menerima dan memvalidasi URL YouTube (youtube.com, youtu.be, shorts) | -| P0 | Menampilkan metadata video (judul, channel, durasi, thumbnail) | -| P0 | Timeline visual dengan penanda in/out yang bisa diseret | -| P0 | Field timecode numerik in/out, tersinkron dengan timeline visual | -| P0 | Aksi "Generate clip" dengan feedback progres | -| P0 | Mengunduh hasil klip | -| P1 | Titik masuk dukungan/donasi (Saweria) | -| P1 | Halaman Privacy Policy dan Terms of Service | -| P2 (pasca-MVP) | Pengambilan metadata YouTube yang sesungguhnya | -| P2 (pasca-MVP) | Pemotongan dan encoding video di server yang sesungguhnya | -| P2 (pasca-MVP) | Batas panjang klip yang ditegakkan, rate limiting anti-abuse | - -## 8. Kebutuhan Non-Fungsional - -- Sepenuhnya responsif: desktop-first, tetap nyaman dipakai di tablet dan - mobile -- Tanpa akun, cookie, atau analytics/tracker pihak ketiga -- Kontrol bisa dinavigasi dengan keyboard; focus state terlihat jelas di - setiap elemen interaktif -- Setiap elemen interaktif punya state hover, focus, disabled, loading, - error, empty, dan success -- Performa yang terasa cepat — tidak ada interaksi yang terasa menunggu - round-trip jaringan di fase MVP, karena memang belum ada jaringan yang - dipanggil - -## 9. Referensi Desain & UX - -Kebutuhan visual dan tingkat komponen dijabarkan terpisah di Frontend -Design Prompt, yang sudah diimplementasikan sebagai prototipe yang -berjalan: React 19 + TypeScript + Vite + Tailwind v4 + Framer Motion + -React Router, UI premium bertema gelap, seluruh data di-mock. - -## 10. Asumsi & Ketergantungan - -- Diasumsikan pengguna memiliki hak untuk memotong dan menyebarluaskan - video sumbernya — tool ini tidak memberikan hak apa pun yang belum - dimiliki penggunanya -- Versi nyata (tidak di-mock) bergantung pada backend pemrosesan video - (mis. pipeline yt-dlp/ffmpeg) dan storage untuk hasil render - -## 11. Risiko & Pertanyaan Terbuka - -- **Risiko legal/ToS:** mengunduh atau menghosting ulang konten video - YouTube berpotensi bertentangan dengan Terms of Service YouTube. Ini - butuh tinjauan legal sebelum backend sungguhan dirilis — inilah alasan - utama kenapa MVP sengaja tetap frontend-only dan sepenuhnya di-mock - untuk saat ini. -- **Risiko penyalahgunaan:** backend sungguhan tanpa login tidak punya - cara alami untuk membatasi atau melacak pemakaian — perlu rencana - mitigasi (rate limit berbasis IP, CAPTCHA, dll.) sebelum diluncurkan. -- **Pertanyaan terbuka:** apakah FreeKliping akan tetap jadi proyek - portofolio/demo, atau memang direncanakan punya backend pemrosesan - sungguhan? Keputusan ini sangat menentukan biaya infrastruktur dan - eksposur legal, dan sebaiknya diputuskan sebelum masuk Phase 2. -- **Pertanyaan terbuka:** apakah monetisasi lewat tip saja (Saweria) masih - berkelanjutan begitu biaya server sungguhan (encoding, bandwidth) mulai - berjalan? - -## 12. Rencana Rilis - -| Fase | Cakupan | Status | -|---|---|---| -| 1 | Prototipe frontend, sepenuhnya di-mock | Selesai | -| 2 | Pengambilan metadata YouTube sungguhan (oEmbed atau sejenisnya) | Belum dimulai | -| 3 | Backend pemrosesan klip sungguhan, menunggu tinjauan legal | Belum dimulai | - -## 13. Metrik Keberhasilan - -- Fase MVP: feedback usability kualitatif, waktu sampai klip pertama saat - testing, completion rate (link ditempel → klip "diunduh") -- Fase pasca-backend: jumlah klip dibuat per minggu, tingkat penggunaan - berulang, tip Saweria yang diterima \ No newline at end of file diff --git a/opencode.json b/opencode.json deleted file mode 100644 index 53e16f3..0000000 --- a/opencode.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "$schema": "https://opencode.ai/config.json", - "mcp": { - "laravel-boost": { - "type": "local", - "enabled": true, - "command": [ - "php", - "artisan", - "boost:mcp" - ] - } - } -} \ No newline at end of file diff --git a/technical-flow.md b/technical-flow.md deleted file mode 100644 index 000b1ec..0000000 --- a/technical-flow.md +++ /dev/null @@ -1,145 +0,0 @@ -# FreeKliping — Dokumen Teknis: Alur Pemrosesan Klip (yt-dlp + ffmpeg) - -| | | -| ----------- | ----------------------------------------------------------------------------------------------------- | -| **Status** | Draft v1 | -| **Cakupan** | Phase 2–3 di PRD (backend sungguhan, belum dimulai) | -| **Terkait** | freekliping-prd-id.md — lihat bagian 11 (Risiko & Pertanyaan Terbuka) sebelum mengerjakan dokumen ini | - ---- - -## 1. Tujuan Dokumen - -Menjelaskan tools dan alur kerja teknis di balik backend FreeKliping yang -sesungguhnya (belum diimplementasi) — bagian yang mengambil video dari -YouTube dan memotongnya sesuai timestamp in/out yang dipilih pengguna di -UI, lalu menghasilkan file klip yang bisa diunduh. - -Frontend (yang sudah dibangun) tidak berubah — dokumen ini hanya membahas -apa yang terjadi di belakangnya begitu tombol **Generate clip** benar-benar -memanggil server sungguhan, bukan simulasi. - ---- - -## 2. Tools yang Digunakan - -| Tool | Peran | -| --------------------------------------- | ----------------------------------------------------------------------------------------------- | -| **YouTube Data API v3** | Ambil & validasi metadata (judul, channel, durasi) sebelum proses download — jalur resmi, legal | -| **yt-dlp** | Mengambil stream video dari YouTube | -| **ffmpeg** | Memotong video sesuai in/out point, lalu encode ke MP4 | -| **Job queue** (mis. BullMQ + Redis) | Menjalankan proses download+potong secara asinkron di background, bukan blocking request | -| **Object storage** (mis. S3-compatible) | Menyimpan file hasil klip sementara sebelum diunduh pengguna | - ---- - -## 3. Alur Kerja (High-Level) - -```mermaid -flowchart TD - A[User submit: URL + start/end time] --> B{Validasi URL & durasi} - B -- tidak valid --> B1[Kembalikan error ke frontend] - B -- valid --> C[Cek metadata via YouTube Data API v3] - C --> D[Masukkan job ke queue] - D --> E[Worker: yt-dlp ambil segmen video] - E --> F[Worker: ffmpeg potong + encode ke MP4] - F --> G[Simpan hasil ke object storage] - G --> H[Kirim signed URL download ke frontend] - H --> I[Hapus file setelah retention window habis] -``` - -## 4. Detail Tiap Tahap - -### 4.1 Validasi awal - -Backend memvalidasi format URL dan memastikan panjang klip yang diminta -tidak melebihi batas (sesuai `MAX_CLIP_LENGTH` yang sudah ada di frontend, -mis. 180 detik) **sebelum** menyentuh yt-dlp sama sekali — mencegah proses -berat berjalan untuk request yang jelas tidak valid. - -### 4.2 Ambil metadata - -Panggil YouTube Data API v3 untuk konfirmasi video benar-benar ada, publik -(bukan private/unlisted-restricted), dan durasinya masuk akal dibanding -timestamp yang diminta user. - -### 4.3 Ambil video — yt-dlp - -Alih-alih mengunduh keseluruhan video (boros bandwidth & storage untuk -video panjang), gunakan fitur **`--download-sections`** milik yt-dlp untuk -langsung mengambil hanya rentang waktu yang dibutuhkan plus sedikit buffer -di kedua sisi (mis. ±3 detik) untuk jaga-jaga alignment keyframe. - -Contoh pola perintah (disesuaikan lagi saat implementasi): - -``` -yt-dlp --download-sections "*START-END" -f "bv*+ba/b" -o "source.%(ext)s" -``` - -### 4.4 Potong presisi — ffmpeg - -Karena `--download-sections` di yt-dlp kadang tidak 100% presisi ke frame -(tergantung posisi keyframe sumber), ffmpeg dipakai sebagai tahap kedua -untuk memotong tepat ke timestamp yang diminta dan re-encode ke MP4 yang -konsisten: - -``` -ffmpeg -i source.mp4 -ss -to -c:v libx264 -c:a aac output.mp4 -``` - -Re-encode (bukan `-c copy`) dipilih supaya potongan akurat ke frame yang -diminta user, bukan cuma ke keyframe terdekat — konsekuensinya proses ini -butuh CPU, sehingga wajib berjalan di background job, bukan di request -path langsung. - -### 4.5 Simpan & kirim hasil - -File hasil disimpan sementara di object storage, backend mengembalikan -signed URL (kadaluarsa otomatis) ke frontend untuk tombol **Download clip** -menggantikan file dummy `.txt` yang dipakai di prototipe saat ini. - -### 4.6 Pembersihan - -File sumber dan file hasil dihapus otomatis setelah periode retensi -pendek (mis. 1–24 jam) — selaras dengan posisi privasi yang sudah -dituliskan di halaman `/privacy`: tidak ada data yang disimpan lama. - ---- - -## 5. Penanganan Error - -| Kasus | Penanganan | -| ------------------------------------------------- | ----------------------------------------------------------------------------------------- | -| Video private/tidak tersedia/dibatasi wilayah | Tolak di tahap validasi metadata, tampilkan error state yang sudah ada di `UrlInput` | -| Video melebihi batas panjang klip | Tolak sebelum masuk queue | -| yt-dlp gagal ambil stream (YouTube ubah struktur) | Retry terbatas, lalu gagalkan job dengan pesan jelas — lihat catatan maintenance di bawah | -| ffmpeg gagal encode | Gagalkan job, jangan kirim file rusak ke user | -| Job menumpuk / server overload | Batasi job bersamaan per IP, tolak request baru dengan pesan "coba lagi nanti" | - ---- - -## 6. Catatan Infrastruktur & Maintenance - -- **yt-dlp perlu update rutin** — YouTube sering mengubah struktur - internalnya sehingga extractor yt-dlp bisa "patah" tiba-tiba. Pin versi - di Docker image tapi siapkan proses update cepat, bukan versi yang - dibekukan permanen. -- **Proses download+encode itu berat** — wajib jalan di worker terpisah - dari web server utama (job queue), supaya request HTTP biasa tidak ikut - ke-block oleh proses ffmpeg yang bisa makan waktu beberapa detik hingga - menit tergantung panjang klip. -- **Tanpa login berarti tanpa identitas user** — rate limiting realistis - hanya bisa berbasis IP/fingerprint kasar, bukan akun. Ini trade-off - langsung dari prinsip "No Login" di PRD, perlu disadari sejak desain - sistem, bukan ditambal belakangan. - ---- - -## 7. Pengingat Legal - -Sebelum bagian ini benar-benar diimplementasikan dan dipublikasikan, -tinjau ulang bagian **Risiko & Pertanyaan Terbuka** di PRD — penggunaan -yt-dlp untuk mengambil konten YouTube berada di area yang berpotensi -bertentangan dengan Terms of Service YouTube. Dokumen ini menjelaskan -_cara kerja teknisnya_, bukan konfirmasi bahwa ini aman secara hukum untuk -dijalankan publik. diff --git a/todo.md b/todo.md deleted file mode 100644 index 419b0ea..0000000 --- a/todo.md +++ /dev/null @@ -1,769 +0,0 @@ -# FreeKliping Todo & Phase Plan - -Dokumen ini menjadi pegangan kerja agar implementasi FreeKliping berjalan sesuai PRD dan `technical-flow.md`. Urutan fase dibuat dari pekerjaan dengan risiko paling rendah sampai backend video production yang membutuhkan VPS, queue worker, `yt-dlp`, `ffmpeg`, hardening, dan pertimbangan legal. - -Dokumen diperbarui berdasarkan audit repository pada 20 Juli 2026. Audit menemukan bahwa beberapa checklist Phase 1 sudah selesai di kode tetapi belum ditandai, sementara sisa starter-kit Laravel masih aktif dan perlu dibersihkan secara bertahap. - -## Prinsip Eksekusi - -- Kerjakan fase secara berurutan, kecuali ada alasan teknis yang jelas untuk memecahnya. -- Setiap fase harus punya hasil yang bisa diuji, bukan hanya perubahan kode. -- Backend video sungguhan tidak boleh berjalan di request HTTP utama; proses berat wajib lewat queue worker. -- Karena aplikasi tanpa login, rate limit dan pembatasan durasi harus dibuat sebelum fitur generate sungguhan dibuka publik. -- Risiko legal/ToS YouTube harus diputuskan sebelum rilis publik fitur download video sungguhan. -- Cleanup starter-kit harus dilakukan dari route dan dependency terlebih dahulu, bukan langsung menghapus folder secara massal. -- Setiap tahap cleanup wajib diikuti pengecekan route, TypeScript, lint, build, dan test. - -## Status Ringkas - -| Fase | Fokus | Status | Prioritas | -| ---- | --------------------------------------------------- | -------------- | --------- | -| 0 | Keputusan produk, stack, dan deployment | Selesai | P0 | -| 1 | Prototype UI tanpa login | Selesai | P0 | -| 1A | Cleanup starter-kit auth, team, dashboard, settings | Selesai | P0 | -| 2 | Metadata YouTube sungguhan via yt-dlp | Selesai | P0 | -| 3 | Pipeline generate clip sungguhan | Selesai | P0 | -| 4 | VPS deployment siap worker | Belum dimulai | P0 | -| 5 | Hardening anti-abuse dan cleanup output | Selesai | P1 | -| 6 | Export polish, subtitle, dan smart crop | Belum dimulai | P1/P2 | -| 7 | Storage dan cost optimization | Belum dimulai | P2 | -| 8 | Free public launch dan support transparency | Sebagian selesai | P1 | -| 9 | YouTube link ke AI clip recommendations | Sebagian selesai | P0 | -| 10 | Production-safe content workflow | Sebagian selesai | P0 | -| 11 | Hybrid local worker | Belum dimulai | P1 | -| 12 | Paid MVP packaging dan manual editor | Belum dimulai | P0 | - -## Phase 0 - Product & Technical Decision - -Tujuan: mengunci arah sebelum masuk pekerjaan backend yang mahal dan berisiko. - -- [x] Tentukan prinsip produk: gratis, tanpa login, tanpa watermark. -- [x] Hapus route login dan register dari pengalaman publik. -- [x] Putuskan deployment target: VPS, bukan shared cPanel. -- [x] Putuskan stack MVP: Laravel + Inertia React tetap dipakai. -- [x] Tentukan batas maksimum durasi klip production: 180 detik. -- [x] Tentukan retention file hasil: 1 jam untuk awal MVP. -- [x] Tentukan apakah fitur backend sungguhan hanya untuk demo terbatas atau rilis publik: demo terbatas/private testing dulu. -- [x] Tinjau risiko legal/ToS YouTube sebelum public launch: wajib dilakukan sebelum rilis publik, belum membuka public launch. - -Exit criteria: - -- Stack MVP disepakati. -- Target hosting disepakati. -- Batas durasi dan retention disepakati. -- Keputusan legal minimum sudah terdokumentasi. - -## Phase 1 - Frontend Prototype - -Tujuan: membuktikan UX utama sebelum investasi backend video. - -### Status fitur utama - -- [x] Tampilan utama mengikuti referensi ClipStudio. -- [x] User bisa paste URL YouTube. -- [x] UI menampilkan state metadata video. -- [x] Timeline visual tersedia. -- [x] Input timecode numerik tersedia dan sinkron dengan timeline. -- [x] Tambahkan input manual menit/detik eksplisit untuk Start dan End. -- [x] Tambahkan quick length preset agar user cepat memilih durasi umum. -- [x] Tombol Generate clip menampilkan feedback progres. -- [x] Tombol Download clip tersedia di prototype. -- [x] Halaman Privacy tersedia. -- [x] Halaman Terms tersedia. - -### 1.1 Refactor struktur frontend - -- [x] Pecah `resources/js/pages/clip-studio.tsx` menjadi komponen yang lebih kecil. -- [x] Buat folder `resources/js/features/clip-editor/`. -- [x] Pindahkan type clip editor ke `clip-editor.types.ts`. -- [x] Pindahkan helper timecode dan range ke `clip-editor.utils.ts`. -- [x] Pindahkan daftar ratio, quality, dan preset ke `clip-editor.constants.ts`. -- [x] Pertahankan `clip-studio.tsx` hanya untuk komposisi halaman. - -Struktur target: - -```text -resources/js/features/clip-editor/ -├── components/ -│ ├── url-input.tsx -│ ├── empty-state.tsx -│ ├── video-preview.tsx -│ ├── editor-panel.tsx -│ ├── clip-timeline.tsx -│ ├── time-range-controls.tsx -│ ├── manual-time-input.tsx -│ ├── quick-length-presets.tsx -│ ├── export-options.tsx -│ ├── generation-progress.tsx -│ └── clip-result-card.tsx -├── clip-editor.constants.ts -├── clip-editor.types.ts -└── clip-editor.utils.ts -``` - -### 1.2 Profesionalisasi UI dengan shadcn - -- [x] Ganti card manual utama dengan `Card`, `CardHeader`, `CardContent`, dan `CardFooter`. -- [x] Ganti error manual dengan `Alert`, `AlertTitle`, dan `AlertDescription`. -- [x] Gunakan `Progress` untuk status generate. -- [x] Gunakan `Skeleton` untuk metadata loading agar layout tidak meloncat. -- [x] Gunakan `Separator` untuk pembagian section editor. -- [x] Gunakan `Collapsible` untuk input timecode lanjutan. -- [x] Gunakan `Tooltip` untuk icon button yang tidak memiliki label visual. -- [x] Ganti semua elemen `